Storing Mappings in Solidity's Storage

Photo by KAL VISUALS on Unsplash

Storing Mappings in Solidity's Storage

Okay let’s first look at the code

contract Demo {
    uint256 a = 0x1a01; // Slot 0
    uint256 b = 0x2a01; // Slot 1
    mapping(uint => uint) c; // Slot 2
    uint256 d = 0x5a01; // Sot 3

    constructor(){
        c[10] = 0xfe3f;
        c[100] = 0xabcd;
    }

    function getMappingValue(uint256 key,uint mappingSlot) returns (uint256)
    {
        // Line 13
        uint256 slot = uint256(keccak256(abi.encode(key,mappingSlot)));
        return slot;
    }

    function getSlotvalue(uint slot) public view return(bytes32) //Line 15
    {
        bytes32 value;
        assembly{
            value := sload(slot);
        }
        return value;
    }
}

So storing Mapping in Solidity is very similar to storing Dynamic Arrays , with a minor difference . In the example above , We have a uint to uint mapping ‘ c ’ . In the constructor, we push two uints into the mapping c

c[100]=0xabcd

c[10] = 0xfe3f

We have 2 numbers of key 10 and 100, So now to retrieve element of key 10 , we will again follow the 2-step strategy , as discussed in the Dynamic Storage Article , for step 1 we use the funtion getMappngValue and we pass key=10 and mappingSlot=2 because the mapping c is allotted slot-2 . in Line 13 we use the keccak256 hashing Algorithm and it is applied to the product(multiplication) of the key and mapping slot.

As a result we get the slot address of c[10] and finally following step-2 we retrieve the element by using the getSlotValue function.