Solidity Struct Size – Size Limit to Number of Items in a Struct in Solidity

gas-limitsoliditystruct

If I loop over mapping into a struct the gas fee is very low. However, in trying to test its limits, the EVM often causes Remix to crash in creating edge cases, because I'm creating blocks of 50 new structs. It does not crash on the loop where I read data and do some algebra, however, and in practice new structs would be added one at a time.

For example, I find that I can basically get to a loop that runs through 7000 items if I extrapolate from a mapping with 200 structs. However, given Remix is often crashing, and it takes a long time to run this loop (seemingly more than proportional to the gas), I wonder if in practice I should lower my estimate of the maximum set of struct members some percentage.

The basic idea looks something like this:

mapping(bytes32 => Contract) public contracts;
bytes32[] public customerContracts;
uint public totalBalance

struct Contract {
    address customer;
    uint inventory;
}

function totalInventory()
public
{
 uint temporaryBalance;
 for (uint i = 0; i < contracts.length; i++) {
     Subcontract storage k = contracts[customerContracts[i]];
     temporaryBalance += k.inventory;
 }
 totalBalance = temporaryBalance;
 }

Best Answer

Remix IDE is not authoritative. If it crashes, it's a failure of the simulation. In the end, the network block gasLimit is a hard stop. That value is voted on by miners and has been known to drop during periods of high congestion. Caution about cutting it too close.

I think you should have a look over here. https://blog.b9lab.com/getting-loopy-with-solidity-1d51794622ad

Another thing that jumps out is the storage i/o cost. It all looks like a classic approach without much regard to the paradigm changes in Ethereum. You need to economize on storage and transaction complexity and be mindful of gas costs.

Instead of iterating over the structure, consider tallying that total as you go. This has desirable effects:

  1. The cost of updating it is borne by the users who are updating something.
  2. The work is amortized. That is, each transaction does a little work to keep the value current. That will be O(1) so the gas cost per transaction will be scale-invariant (the same in any case).

Hope it helps.

Related Topic