I have a contract doing a lot of multiplication & addition. Something like:

for (uint index = 0; index < 10; index++) {
      let numAdders = adders[index];
      if (numAdders > 0) {
        added = numAdders * index;
        tokens[senders] = tokens[sender] + added;

A) I see the opcode cost is 3 for add, 5 for multiply... so it looks like I'm never in danger of running out of gas for this, right?

B) If the 10 in the above code was dynamic, could I have the contract iterate through index up until gas limit was reached (or some gas limit threshhold set by the caller of the function passed as a param) and then commit all state changes up to that point + store a state variable to know where to continue next function call?

1 Answer 1


Not really, but you can manage gas consumption and respond accordingly.

Your big cost is going to be SSTORE and to a lessor extent, SREAD. While the computations are somewhat trivial reading the state is non-trivial and setting the state is quite expensive.

If I'm not mistaken, msg.gas will give the contract visibility into the remaining gas. Importantly, the contract needs to have enough gas left to perform any wind-down steps so everything finishes before the available gas is exhausted.

Generally, unbounded loops are an anti-pattern. Instead of introducing unwanted complexity into the contract in support of an interative process, consider designing the function to deal with one iteration at a time so you have a consistent gas cost at any scale. A client would attend to interation and send multiple transactions.

There is an implication that you would need to leave the contract in a valid state every step of the way. That takes a little getting used to.

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.