You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Solidity继承合约moneyPaid函数钱包未声明错误求助

修复Solidity继承合约的Wallets声明与语法错误

你的代码核心问题是变量作用域错误和语法错误,导致编译器找不到wallets标识符。以下是具体修复步骤和完整可运行代码:

关键错误分析与修复

  1. 修饰符未正确闭合
    你把wallets数组和inheritance mapping的声明写在了isDeceased修饰符的代码块内(修饰符的_;后未加闭合}),导致这两个变量属于修饰符局部作用域,合约其他函数无法访问。必须将它们移到合约全局作用域下。

  2. 数组声明语法错误
    错误写法:address [0xa1F9019E4F941071cAabCbb3fBc6314c06BeD18f] wallets;
    正确写法:使用动态数组address[] public wallets;(因为需要动态添加钱包地址),固定长度数组的声明格式为address[5] wallets;,你用地址作为长度的写法完全不符合语法。

  3. 函数内的语法错误

    • setup函数中:_wallet.push(_wallet); 应改为wallets.push(_wallet);(向数组wallets添加元素,而非参数_wallet);Inheritance [_wallet] = _inheritance; 改为inheritance[_wallet] = _inheritance;(inheritance是你定义的mapping名,Inheritance是合约名,不能用来访问mapping)。
    • moneyPaid函数中:wallets;[i]多了分号,改为wallets[i];Inheritance[wallets][i]改为inheritance[wallets[i]](用数组中的地址作为mapping的key,获取对应的继承金额)。

修正后的完整代码

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;

contract Inheritance { 
    address owner;
    bool deceased;
    uint money;
    // 正确声明动态地址数组,存储继承钱包地址
    address[] public wallets;
    // 存储每个地址对应的继承金额
    mapping (address => uint) public inheritance;

    constructor () payable {
        owner = msg.sender;
        money = msg.value;
        deceased = false;
    }

    modifier oneOwner {
        require(msg.sender == owner, "Only owner can call this function");
        _;
    }

    modifier isDeceased {
        require(deceased == true, "Deceased must be true");
        _;
    }

    function setup(address _wallet, uint _inheritance) public oneOwner {
        // 向wallets数组添加新的钱包地址
        wallets.push(_wallet);
        // 记录该地址对应的继承金额
        inheritance[_wallet] = _inheritance;
    }

    function moneyPaid() private isDeceased {
        for (uint i=0; i < wallets.length; i++) {
            // 获取当前钱包地址对应的继承金额并转账
            uint amount = inheritance[wallets[i]];
            payable(wallets[i]).transfer(amount);
        }
    }

    function died() public oneOwner { 
        deceased = true; 
        moneyPaid();
    }
}

额外优化说明

  • 给修饰符添加了错误提示字符串,方便调试时定位问题。
  • 转账时使用payable(wallets[i]),因为Solidity 0.8.x中地址默认不可支付,需显式转换为payable地址才能调用transfer。
  • 将wallets和inheritance设为public,方便在Remix中查看状态变量的值,提升调试效率。

现在这份代码可以在Remix IDE中使用Solidity 0.8.x编译器正常编译和运行。

内容的提问来源于stack exchange,提问作者Gassed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 21:39:20