mcohen
11 months ago  Karma: 35
Best approach for breaking up a Solidity function that iterates through a larger data set

The function I'm working on iterates through a larger array and it runs out of gas at some point. Is there a mechanism in Solidity where you can run as much of a function as gas limit allows and then pick up at the same point in a new transaction?

en
#solidity
#games
mcohen
11 months ago  Karma: 35
Best approach for breaking up a Solidity function that iterates through a larger data set

The function I'm working on iterates through a larger array and it runs out of gas at some point. Is there a mechanism in Solidity where you can run as much of a function as gas limit allows and then pick up at the same point in a new transaction?

en
#solidity
#games

3 ANSWERS
bartley.gillan30
11 months ago Karma: 74

@mcohen you can do this if you code the logic in your smart contract. Figure out the gas used on each iteration through the yellow paper and/or trial and error like:

function loop() {
  gasBeginning = gasleft();
  do_stuff;
  gasBurned = gasBeginning - gasleft();

Then in your loop call gasleft() and check that you have enough gas before each iteration. When you are almost out of gas either save the current index of the array to storage, or emit it in an Event Log so you know where to start on your next transaction call.

@mcohen you can do this if you code the logic in your smart contract. Figure out the gas used on each iteration through the yellow paper and/or trial and error like:

function loop() {
  gasBeginning = gasleft();
  do_stuff;
  gasBurned = gasBeginning - gasleft();

Then in your loop call gasleft() and check that you have enough gas before each iteration. When you are almost out of gas either save the current index of the array to storage, or emit it in an Event Log so you know where to start on your next transaction call.

kaijchang2
11 months ago Karma: 19864

There is no support splitting computation across several transactions. I'm not sure about your specific case, but is there a way to move it off-chain?

There is no support splitting computation across several transactions. I'm not sure about your specific case, but is there a way to move it off-chain?

j1koc5
11 months ago Karma: 829

I advise you to do such computations off-chain. It is more efficient to perform this task in the front-end.

I advise you to do such computations off-chain. It is more efficient to perform this task in the front-end.

Earn tokens by posting and answering questions about blockchain!
Karma to eth
YOUR ANSWER