Iterable mappings in Solidity

Iterable mappings in Solidity

A mapping in Solidity is a reference type that functions similarly to a dictionary or hash table in other programming languages. Key-value pairs are used to store data, with the key being any built-in data type, a byte, a string, or any contract, and value can be any type. Mappings in Solidity allows developers store and retrieve data based on keys in Solidity contracts.

Traditionally, we're unable to iterate through a mappings because we cannot enumerate mapping keys. However, there are ways to iterate through mappings in Solidity. One way to create an iterable mapping is to store the keys of the mapping in an array and then iterate over that array. Below is an example of how to create an iterable mapping in Solidity.


// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

contract IterableMapping {
    mapping(address => uint) public balances;
    mapping(address => bool) public inserted;
    address[] public keys;

    function set(address _addr, uint _bal) external {
        balances[_addr] = _bal;

        if (!inserted[_addr]) {
            inserted[_addr] = true;
            keys.push(_addr);
        }
    }

    function get(uint _index) external view returns (uint) {
        address key = keys[_index];
        return balances[key];
    }
}

The contract defines a mapping that stores the balances of addresses and another mapping that keeps track of whether an address has been inserted into the mapping or not. It also defines an array of addresses to store the inserted addresses.

The set() function allows the contract owner to set the balance of a specific address. If the address is not already inserted in the mapping, it is inserted and added to the array of keys.

The get() function allows the contract owner to retrieve the balance of an address by its index in the array of keys.

Another way to create an iterable mapping is by using a library called "EnumerableMap" developed by OpenZeppelin. In conclusion, while mappings are not natively iterable in Solidity, there are ways around this limitation such as storing keys in arrays or using libraries like Openzeppelin.