1

Most of contracts I examine store data in public tables indexed by address, example for balance of ERC20 token is shown below. To get balance of give address balanceOf(address) is called. Which is fine as long as address is known. What I struggle with - how to get all addresses that are used in this mapping? I.e. for balanceOf(X) - how to get a list of all X that are stored in that contract?

abstract contract ERC20 is IERC20 {
    /// @notice owner > balance mapping.
    mapping(address => uint256) public override balanceOf;
}
1
  • mappings aren't iterable themselves but there is a pattern for getting around it and creating an iterable mapping of sorts. This link is another example a bit different from Julissa's youtube.com/watch?v=YOjo_lvUhj8
    – sola24
    Jul 1, 2022 at 15:14

1 Answer 1

0

Short answer, you can't get all mapping keys, but what you can do is create an array to store that information like this:

contract AContract {
    // Array with all info ids, used for enumeration
    uint256[] private _allThings;

    // Mapping from info id to position in the allThings array
    mapping(uint256 => uint256) private _allThingsIndex;

    function insert(uint256 key, uint256 value) public {
        _allThingsIndex[key] = value;
        _allThings.push(key);
    }
    }
2
  • Thanks, I understand that keys can be stored at creation but all blockchain explorers, like etherscan.io, are showing all keys somehow without doing that. For example they show full list of IERC20 token holders for every single token known. Yes it can be done by tracing events but that would have to be done for every single token that exists which is prohibitively expensive, not to mention full rescan. How is this information grabbed then? Jul 3, 2022 at 19:28
  • They probably use a DB outside the blockchain, but I dont know for sure since they are not open source
    – Julissa DC
    Jul 3, 2022 at 22:44

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.