Mappings

Reading a mapping

The solidity storage layout documentation (opens in a new tab) states that the "value corresponding to a mapping key k is located at keccak256(h(k) . p) where . is concatenation and h is a function that is applied to the key depending on its type"

Our virtual machine abstracts away this complexity and manages calculating and updating the internal slot pointer such that data can be read.

Contract definition

Example.sol
 
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.25;
 
    contract Example {
        mapping(uint256=>string) exampleMapping;          
 
        constructor() {
            exampleMapping[42] = "string";
        }
    }

Reading values

The value at index 42 can be read as follows:

example.js
 
    const OUTPUT_COUNT = 1;
    const CONTRACT_ADDRESS = "0x123..;
    const MAPPING_KEY = 42;
 
    new GatewayRequest(OUTPUT_COUNT)    //Specify the number of outputs
        .setTarget(CONTRACT_ADDRESS)    //Specify the contract address
        .setSlot(0)                     //Specify the base slot number
        .push(MAPPING_KEY)              //Specify the mapping key you want to read
        .follow()                       //Update the VM internal slot pointer to point to that key 
        .readBytes()                    //Read the value
        .setOutput(0)                   //Set it at output index 0