SolidityIn

Storage layout and slots

Lesson 21 of 40 · EVM

Every contract has its own storage, which you can picture as a huge array of 32-byte slots numbered from 0. State variables are assigned to slots in the order you declare them. A uint256 takes a full slot, and smaller values that fit can share one.

Mappings and dynamic arrays work differently. The variable's own slot holds nothing useful for a mapping, or only the length for an array. The values live at addresses computed with keccak256. For a mapping, the value for key k is stored at keccak256 of k and the slot number.

Nothing in storage is private. The private keyword only stops other contracts from reading a variable through code. Anyone can read any slot straight from a node, for example with eth_getStorageAt, so never store a password or a secret in a contract.

Layout matters for upgradeable contracts, where new versions must keep the old variables in the same slots. It also affects gas, because variables that share a slot are cheaper to read and write together. Assembly can read a slot directly with sload, as shown below.

contract Layout {
    uint256 public a = 7;                         // slot 0
    uint128 public b = 1;                         // slot 1
    uint128 public c = 2;                         // slot 1 (shares with b)
    address public owner = msg.sender;            // slot 2
    mapping(address => uint256) public balances;  // slot 3 (holds nothing itself)

    function setBalance(uint256 v) external {
        balances[msg.sender] = v;
    }
    function readSlot(uint256 slot) external view returns (bytes32 v) {
        assembly { v := sload(slot) }
    }
    function balanceSlot(address who) external pure returns (bytes32) {
        return keccak256(abi.encode(who, uint256(3)));
    }
}

Try it yourself

In Remix, call readSlot with 0, 1 and 2 and compare the results. Then call setBalance, get your slot from balanceSlot, and pass it to readSlot to find your balance.

Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.

Quick check: Does the private keyword hide a variable's value from the outside world?