I have a function in my contract loops through the current user base (an address[]), within each loop, it performs some logic and writes some data into state user variables.

The function starts to fail when the user base gets larger then 30 due to gas cost exceed block gas limit.

I wonder if this is a good solution here -

I can offload the loops to front end js, just call the function to write results onchain after each loop, in this way although I need to make more calls to write data onchain, at least each call will not exceed block gas limit. Then it is more scalable.

Is this a good way for gas optimization?

1 Answer 1


It could be a good solution, but each transaction has an inherent gas cost of 21,000. A good medium between your two solutions could be to do the work off chain, and have your contract take in the results in bulk (i.e., take in an array). It would cost less gas overall, and you can fiddle with it to figure out how many you can take at a time to avoid the block limit.


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.