...by Daniel Szego
quote
"Simplicity is the ultimate sophistication."
Leonardo da Vinci

Monday, January 1, 2018

Solidity and Truffle Tips and Tricks - iteration on a mapping


Mapping is a great structure in solidity, however a big drawback is to make an iteration on that. Basically it is not really possible, what you can do are the followings: 

1. If the key-space is small like working with uint8, you can iterate the whole key-space.
2.  You can use a pattern that adds the used key into an array as well, like bellow. Certainly this pattern increases the gas consumption.  

contract Iterrativemapping  {
  mapping(keyType = valueType) myMapping;
  keyType[] possibleKeys;

  function insert (keyType key, valuType value) public {
    possibleKeys.push(key);
    myMapping[key] = value;
  }
  
  function remove ....

  function setValue ...

}

3. Last but not least, you can create an event that is triggered at setting the value. Certainly this scenario does not provide a way to iterate on the mapping from a solidity contract, but there will be an off-chain log available about possible keys, values and about the whole history that can be evaluated off-chain.

contract Mappingwithevent {
  mapping(keyType = valueType) myMapping;

  event ValueSetEvent(keyType, valueType);

  function setValue (keyType key, valuType value) public {
    myMapping[key] = value;
    ValueSetEvent(key, value);
  }
  
}