0

So I have to prepare a smart contract that need to be the most possible gas optimized.

So far so good, but then i came across this requirement.

Given a json file with pairs containing address: value, i need to update the state of the addresses in my contract.

I tought about various approaches.

  1. The good ol' loop

    function update_value(address[] calldata addies, uint256[] calldata uints) {

         for(uint256 i=0; i<=addies.length; i++) {
             mapping_addies[addies[i]].value += uints[i];
         }
     }
    

This one i tought with mappings or arrays.

  1. The MEGARRAY

    function update_value(address[] calldata addies, uint256[] calldata uints) {
    
             addresses = addies;
    
             values = uints;
    
         }
    

Which one would be more gas optimized and why? The array is HUGE

1 Answer 1

1

The array is HUGE

This is a problem.

Given a json file with pairs containing address: value, i need to update the state of the addresses in my contract

This is an implementation idea expressed as a requirement. Since the implementation is impractical, it's time to dig in and find out what the actually requirement actually is.

WHY?

I would expect to hear something about rewards, interest, etc. that seems to necessitate a massive update. However, given sufficient creativity and determination it is not necessary to use a pattern that is best suited to a centralized, unlimited (for practical purposes) algorithm to accomplish such things. The solution will undoubtedly seem unfamiliar because it will optimized for blockchain constraints.

You need algorithms with O(1) time complexity. Both ideas are O(n) which will not do for an array that is HUGE.

Hope it helps.

2
  • actually i agree and it helps, i still have to find a way to better suit this initial data because i wouldnt know how Dec 29, 2021 at 17:11
  • A go-to approach is to invert control so the client iterates instead of the contract. You can also use "just-in-time" computations to increment/add/apply function to elements when needed. You can make it self-serve so the cost of claim/update/etc is outsourced to the user who benefits from it, when they decide to process it. There are exotic approaches like "reflection" that create the illusion of a bulk update. I can't be more specific with only general notions of what you need to accomplish. Dec 29, 2021 at 20:27

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.