How to manage big Loops in Solidity?what does “=>” mean in solidity?Solidity setting a mapping to emptyModifiers on solidityInitialize a big fixed length array in SoliditySolidity tx.destination.call.value(tx.value)(tx.data)Solidity Point of _ statementsBig loop in SolidityCan I use my custom ERC-20 with my smart contract?Solidity - Solidity code to Input JSON DescriptionReturning Struct Array in solidity

Defense against attacks using dictionaries

Why is my Earth simulation slower than the reality?

Is "burning" metals in the Mistborn series the same as digesting?

Would it be possible to have a GMO that produces chocolate?

Architectural feasibility of a tiered circular stone keep

Non-visual Computers - thoughts?

LeetCode: Group Anagrams C#

Efficiently pathfinding many flocking enemies around obstacles

Sitecore PowerShell script to get all images where the File Path is empty

Did the British navy fail to take into account the ballistics correction due to Coriolis force during WW1 Falkland Islands battle?

Why did MS-DOS applications built using Turbo Pascal fail to start with a division by zero error on faster systems?

Would the Republic of Ireland and Northern Ireland be interested in joining together?

How to use "Du hast/ Du hattest'?

If the first law of thermodynamics ensures conservation of energy, why does it allow systems to lose energy?

Justifying the use of directed energy weapons

Do they have Supervillain(s)?

Shouldn't the "credit score" prevent Americans from going deeper and deeper into personal debt?

Slitherlink Fillomino hybrid

Couple of slangs I've heard when watching anime

Is gzip atomic?

Are there any elected officials in the U.S. who are not legislators, judges, or constitutional officers?

Are the players on the same team as the DM?

Numbers Decrease while Letters Increase

Why in most German places is the church the tallest building?



How to manage big Loops in Solidity?


what does “=>” mean in solidity?Solidity setting a mapping to emptyModifiers on solidityInitialize a big fixed length array in SoliditySolidity tx.destination.call.value(tx.value)(tx.data)Solidity Point of _ statementsBig loop in SolidityCan I use my custom ERC-20 with my smart contract?Solidity - Solidity code to Input JSON DescriptionReturning Struct Array in solidity






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















So I have this contract and the funder can retrieve the total amounts of a specific campaign through the getFundsByAddress function. The problem is that if a campaign has more than 30 thousand founders,the contract is not able to execute the code because it would need to go through the 30 thousand times so can find all the correct addresses



In the Rinkeby nework the max a loop it can reach is 30k, after that is returning 0



How can I resolve such cases?



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;











share|improve this question






























    0















    So I have this contract and the funder can retrieve the total amounts of a specific campaign through the getFundsByAddress function. The problem is that if a campaign has more than 30 thousand founders,the contract is not able to execute the code because it would need to go through the 30 thousand times so can find all the correct addresses



    In the Rinkeby nework the max a loop it can reach is 30k, after that is returning 0



    How can I resolve such cases?



    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;











    share|improve this question


























      0












      0








      0








      So I have this contract and the funder can retrieve the total amounts of a specific campaign through the getFundsByAddress function. The problem is that if a campaign has more than 30 thousand founders,the contract is not able to execute the code because it would need to go through the 30 thousand times so can find all the correct addresses



      In the Rinkeby nework the max a loop it can reach is 30k, after that is returning 0



      How can I resolve such cases?



      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;











      share|improve this question














      So I have this contract and the funder can retrieve the total amounts of a specific campaign through the getFundsByAddress function. The problem is that if a campaign has more than 30 thousand founders,the contract is not able to execute the code because it would need to go through the 30 thousand times so can find all the correct addresses



      In the Rinkeby nework the max a loop it can reach is 30k, after that is returning 0



      How can I resolve such cases?



      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






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 27 at 17:23









      BAl2005BAl2005

      1




      1

























          2 Answers
          2






          active

          oldest

          votes


















          0















          I don't see anything special with the number 30K that would explain this.



          Your problem could be that the transaction is either running out of gas or is hitting the block gas limit. If you have to loop through the array and cannot do it in any other way you should consider looping through the array in multiple transactions (i.e. 0-9999,10.000-19.999, ...).



          However, looping through so many entries will be quite expensive in terms of gas which on a real network costs money. But if it cannot be done in another way then the above should help you.






          share|improve this answer
































            0















            It's hard to guess at what getFundsByAddress is supposed to do because the code doesn't compile and the loop doesn't seem to do anything. (The loop variable i is never used.)



            But if I had to guess, it's supposed to return the sum of the contributions made by the caller. If that's the case, just keep track of that total as contributions are made and avoid the loop altogether:



            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];






            share|improve this answer



























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55383179%2fhow-to-manage-big-loops-in-solidity%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0















              I don't see anything special with the number 30K that would explain this.



              Your problem could be that the transaction is either running out of gas or is hitting the block gas limit. If you have to loop through the array and cannot do it in any other way you should consider looping through the array in multiple transactions (i.e. 0-9999,10.000-19.999, ...).



              However, looping through so many entries will be quite expensive in terms of gas which on a real network costs money. But if it cannot be done in another way then the above should help you.






              share|improve this answer





























                0















                I don't see anything special with the number 30K that would explain this.



                Your problem could be that the transaction is either running out of gas or is hitting the block gas limit. If you have to loop through the array and cannot do it in any other way you should consider looping through the array in multiple transactions (i.e. 0-9999,10.000-19.999, ...).



                However, looping through so many entries will be quite expensive in terms of gas which on a real network costs money. But if it cannot be done in another way then the above should help you.






                share|improve this answer



























                  0














                  0










                  0









                  I don't see anything special with the number 30K that would explain this.



                  Your problem could be that the transaction is either running out of gas or is hitting the block gas limit. If you have to loop through the array and cannot do it in any other way you should consider looping through the array in multiple transactions (i.e. 0-9999,10.000-19.999, ...).



                  However, looping through so many entries will be quite expensive in terms of gas which on a real network costs money. But if it cannot be done in another way then the above should help you.






                  share|improve this answer













                  I don't see anything special with the number 30K that would explain this.



                  Your problem could be that the transaction is either running out of gas or is hitting the block gas limit. If you have to loop through the array and cannot do it in any other way you should consider looping through the array in multiple transactions (i.e. 0-9999,10.000-19.999, ...).



                  However, looping through so many entries will be quite expensive in terms of gas which on a real network costs money. But if it cannot be done in another way then the above should help you.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 27 at 18:59









                  nikos fotiadisnikos fotiadis

                  8312 gold badges5 silver badges15 bronze badges




                  8312 gold badges5 silver badges15 bronze badges


























                      0















                      It's hard to guess at what getFundsByAddress is supposed to do because the code doesn't compile and the loop doesn't seem to do anything. (The loop variable i is never used.)



                      But if I had to guess, it's supposed to return the sum of the contributions made by the caller. If that's the case, just keep track of that total as contributions are made and avoid the loop altogether:



                      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];






                      share|improve this answer





























                        0















                        It's hard to guess at what getFundsByAddress is supposed to do because the code doesn't compile and the loop doesn't seem to do anything. (The loop variable i is never used.)



                        But if I had to guess, it's supposed to return the sum of the contributions made by the caller. If that's the case, just keep track of that total as contributions are made and avoid the loop altogether:



                        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];






                        share|improve this answer



























                          0














                          0










                          0









                          It's hard to guess at what getFundsByAddress is supposed to do because the code doesn't compile and the loop doesn't seem to do anything. (The loop variable i is never used.)



                          But if I had to guess, it's supposed to return the sum of the contributions made by the caller. If that's the case, just keep track of that total as contributions are made and avoid the loop altogether:



                          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];






                          share|improve this answer













                          It's hard to guess at what getFundsByAddress is supposed to do because the code doesn't compile and the loop doesn't seem to do anything. (The loop variable i is never used.)



                          But if I had to guess, it's supposed to return the sum of the contributions made by the caller. If that's the case, just keep track of that total as contributions are made and avoid the loop altogether:



                          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];







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 28 at 4:55









                          smarxsmarx

                          50.4k6 gold badges70 silver badges80 bronze badges




                          50.4k6 gold badges70 silver badges80 bronze badges






























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55383179%2fhow-to-manage-big-loops-in-solidity%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                              용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                              155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해