Okay, we all know looping over mapping is not possible in Solidity, and we all know how to solve it: add an array or counter to keep track of indices in the mapping.

But this question is about why this is the case. The information of which keys are allowed in the mapping should be somewhere, as it can be retrieved.

And if it's not computationally feasible to allow this in smart contracts, why can't Web3 or similar libraries loop over mappings? They are able to query the full smart contract state with no incurred gas costs. Why can they not deduce the list of keys stored in a mapping?


Please see the following article for a very nice explanation of how mappings are saved any why we can not iterate over them.


TLDR - Mapping values are saved at position hash(mappingKey, mappingStorageSlot). The result of this hashing can not be known in advance / iterated upon.

  • 1
    Okay thank you, one small follow-up question: does this store everything in the storage of the smart contract, or the storage of the EVM? What I mean is, can I estimate the size of a mapping by viewing the smart contract's storage?
    – vrwim
    Nov 23 at 12:34
  • You're welcome. I'm not sure, but I don't think you can estimate the size of the smart contract storage, for the same reason: the storage is saved as a hash map and you can't iterate it because you don't know which parts are populated. However I admit the issue is not totally clear to me. Nov 23 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.