9

I want to get an estimation of how much it would cost to store arbitrarily many elements in a mapping of the form BYTES32 -> BYTES32. I see here that a STORAGEADD operation costs 20000 gas, which I believe is the instruction to add an element to a mapping (is it correct?).

The gas price today is 20 gwei, so 20 * 10^9 wei which gives me a total of 20000 * 20 * 10^9 * 10^-18 = 0.0004 ether ~ 0.0048 USD (with 1 ETH = 12 USD).

Is it correct and is there any limit to how many elements I can put into the mapping (disregarding gas price limitations)?

eth
  • 85,679
  • 53
  • 285
  • 406
Symeof
  • 1,434
  • 13
  • 19

2 Answers2

6

The total storage is made of 32-bytes slots addressed with 256 bits. This gives us 2^256 * 32 bytes to use. When you add an item to a mapping, it is sent to a random location in the storage calculated by sha3, see this answer.

Adding an item to a mapping will never fail because there always will be a sha3-calculated location to put the info into. Of course, the closer you get to 2^256 insertions, the higher the likelihood that you will eventually overwrite something else.

  • 1
    A good rule of thumb is that you need approximately sqrt(n) entries before you expect a collision, so 2^128 in this case. That's about 3.4e38, which is 340 million million million million million million.

    https://en.wikipedia.org/wiki/Birthday_problem#Square_approximation

    There are also means to correct for hash collisions in maps, allowing for theoretically infinite entries, but I'm not sure of the exact implementation in the EVM.

    – Arran Schlosberg Jul 03 '21 at 13:45
0

See this response to a similar question. In short: you can store any number of elements in a mapping.