Search code examples
blockchainethereumsoliditysmartcontracts

Updating the state of many addresses in Solidity is gas costly


I've mapping of addresses and need to somehow set bulk data at contract deployment or able to update it later

mapping (address => bool) private accounts;

this is current solution to set addresses

 function setAccounts(address[] memory _accounts) public onlyOwner { 
    for(uint i=0; i< _accounts.length; i++){
       accounts[_accounts[i]] = true;
    } 

}

The problem is that I need to set about 10,000 addresses and doing it with loop requires lots of gas and too expensive. Probably, it's not possible to pass an array directly, but what could be a solution to get 10K list of addresses in 1 transaction without loop (or decrease gas fee)

Should I use array instead and keep the address index to filter it later? Please advise Thanks in advance


Solution

  • It is unlikely you can gas optimize this even further.

    You will hit the block size limit with 10,000 transactions.

    For operations that cannot fit into one Ethereum transaction, must be done in batches.

    Just set first 0...1000 addresses in one transaction, then 1000 ... 2000.

    Alternative you can use some kind of Merkle tree claim process to optimise the Ethereum state size and push the gas cost to the user.