Search code examples
ethereumsoliditysmartcontractsevm

Solidity field size of mapping type


Solidity allows mapping types inside a struct. How many bytes does such a field cost?

Specifically I'd like to optimise the storage layout of the following type.

struct Balance {
    uint40 amount;
    mapping(address => uint) allowances;
}

Solution

  • I think you mean the storage layout, not memory layout.

    uint is an alias for uint256, which is 256-bits. So each value stored in that mapping uses one 32-byte slot in storage.

    EDIT

    For the full Balance struct, each one will consume two slots in storage, but one slot will always be zero. The first slot is consumed by the uint40, and the second is a placeholder for the mapping that doesn't actually have any value stored. In terms of gas cost, that's free.

    So storing a new Balance will write one 32-byte word to storage, and then each uint you add to the allowances mapping will write one 32-byte word to storage.