如何在Solidity中管理大循环?

问题描述 投票:0回答:2

所以我有这个合同,资助者可以通过getFundsByAddress函数检索特定广告系列的总金额。问题是,如果一个活动有超过3万名创始人,合同将无法执行代码,因为它需要经历3万次,所以可以找到所有正确的地址

在Rinkeby网络中,它可以达到的最大循环为30k,之后返回0

我该如何解决此类案件?

contract CrowdFunding {
    struct Funder {
        address addr;
        uint amount;
    }

    struct Campaign {
        address beneficiary;
        uint numFunders;
        uint amount;
        mapping (uint => Funder) funders;
    }

    uint numCampaigns;
    Campaign[] public campaigns;

    function newCampaign() public returns (uint campaignID) {
        campaignID = campaigns.length++;
        Campaign storage c = campaigns[campaignID];
        c.beneficiary = msg.sender;
    }

    function contribute(uint _campaignID, uint _amount) public {
        Campaign storage c = campaigns[_campaignID];
        c.funders[c.numFunders++] = Funder({addr: msg.sender, amount: _amount});
        c.amount += 100;
    }

    // not tested
    function getFundsByAddress() public view returns (uint[] memory) {
        Campaign storage c = campaigns[0];
        uint cont = c.numFunders;

        uint[] memory allAmount = new uint[](TotalAmountOfUser);

        uint counter = 0;

        for (uint i=0; i < cont; i++) {
           if (c.funders[counter].addr == msg.sender) {
               allAmount[amountCont] = c.funders[counter].amount;
           }
           counter++;
        }

        return allAmount;
    }   
}
ethereum solidity smartcontracts
2个回答
0
投票

我没有看到任何特殊的数字30K可以解释这一点。

您的问题可能是交易耗尽气体或达到阻塞气体限制。如果你必须遍历数组并且不能以任何其他方式进行,你应该考虑在多个事务中循环遍历数组(即0-9999,10.000-19.999,...)。

然而,就真实网络上的天然气而言,循环通过如此多的条目将是非常昂贵的。但如果不能以另一种方式完成,那么上述内容应该对你有所帮助。


0
投票

很难猜测getFundsByAddress应该做什么,因为代码没有编译,循环似乎没有做任何事情。 (从不使用循环变量i。)

但是,如果我不得不猜测,它应该返回调用者所做贡献的总和。如果是这种情况,只需跟踪贡献的总和,并完全避免循环:

mapping(address => uint256) public totalContributions;

function contribute(uint _campaignID, uint _amount) public {
    ...

    // Add this line to keep track of the total.
    totalContributions[msg.sender] += _amount;
}

// No need for getFundsByAddress at all because a call to `totalContributions(address)`
// (the auto-generated getter) does the trick.

// But if you want a function that returns specifically `msg.sender`'s total:
function getMyContributions() external view returns (uint256) {
    return totalContributions[msg.sender];
}
© www.soinside.com 2019 - 2024. All rights reserved.