MENU

solidity复合结构体(struct嵌套mapping)

July 3, 2022 • 默认分类

solidity struct 中经常会有嵌套 mapping 的情况:

pragma solidity >=0.6.0 <0.9.0;
​
  struct Funder {
      address addr;
      uint amount;
  }
​
  contract CrowdFunding {
​
    // 也可以在合约内部定义结构体,这使得它们仅在此合约和衍生合约中可见。
    struct Campaign {
        address beneficiary;
        uint fundingGoal;
        uint numFunders;
        uint amount;
        mapping (uint => Funder) funders;
    }
​
    uint numCampaigns;
    mapping (uint => Campaign) campaigns;
​
    function newCampaign(address payable beneficiary, uint goal) public returns (uint campaignID) {
        // campaignID 作为一个变量返回,也就是说不一定要有return,而且函数的返回值定义中也可以初始化变量。
        campaignID = numCampaigns++; 
​
        // 不能使用 "campaigns[campaignID] = Campaign(beneficiary, goal, 0, 0)"
        // 因为RHS会创建一个包含映射的内存结构体 "Campaign",而映射只能是storage
        Campaign storage c = campaigns[campaignID];
        c.beneficiary = beneficiary;
        c.fundingGoal = goal;
    }
​
    function contribute(uint campaignID) public payable {
        Campaign storage c = campaigns[campaignID];
        // 以给定的值初始化,创建一个新的临时 memory 结构体,
        // 并将其拷贝到 storage 中。
        // 注意你也可以使用 Funder(msg.sender, msg.value) 来初始化。
        c.funders[c.numFunders++] = Funder({addr: msg.sender, amount: msg.value});
        c.amount += msg.value;
    }
​
    function checkGoalReached(uint campaignID) public returns (bool reached) {
        Campaign storage c = campaigns[campaignID];
        if (c.amount < c.fundingGoal)
            return false;
        uint amount = c.amount;
        c.amount = 0;
        c.beneficiary.transfer(amount);
        return true;
    }
}

资料

https://zhuanlan.zhihu.com/p/388738378