5

A deployed smart contract has public view functions that searchs into mapping of struct with a for loop.

The problem is that in the 500 loop lap of data (there are 10,000 indexes and growing..) the blockchain return:

{
  "code": -32000,
  "message": "out of gas"
}

Then, contract is now useless. Any idea of how to control the GASLEFT and exit of the loop before OUT of GAS?

Thanks!

1
  • 1
    Can you share the smart contract code? Commented Sep 4, 2022 at 14:32

3 Answers 3

8

Let me just add a bit to the existing great answer.

Yes, you can implement that kind of tricks in your contract. But I strongly suggest not to. Mostly because:

  1. Contract should never rely on gas costs of operations. So you shouldn't estimate how much gas you will need for some remaining operations. Gas costs may change dramatically along with different blockchain forks.

  2. You should avoid open-ended loops, or at least make them pageable. So if you have 10000 entries, and you are 100% sure you have to loop through all of those, the loop should allow retrieving the data in batches: first you take first X entries, then next X entries etc. If the page/batch size can be chosen freely, you can avoid any gas issues. The only downsides are that the complexity grows and that, in theory, the data may change between pages.

6

Sure thing, just do something like :

do{
// Your stuff
}while(gasleft() > whateverYouNeed)

(Where whateverYouNeed would be the amount of gas required to run one iteration of the loop + what comes after ( maybe *1.5, just in case)

3
  • Thanks! What is exactly your 1.5 expresed in real gas? or is the case of your example empty loop? In localhost, every my contract loop cost 84.072 ... Commented Sep 10, 2022 at 10:59
  • Well according to remix, this loop costs 22 gas, so assuming there's nothing after i'd set whateverYouNeed to 33
    – Foxxxey
    Commented Sep 11, 2022 at 18:55
  • But as Lauri pointed out, you shouldn't be doing that, a hard fork changing the cost of different opcodes could break your contract.
    – Foxxxey
    Commented Sep 11, 2022 at 18:56
2

I agree with Lauri.

Also, check if the data you are saving could be "expired" and deleted after some time.

If you know that certain data could be deleted after some time, then you could add logic to handle the data deletion, so your smart contract data does not grow to a point where it would be wasting resources and is unusable.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.