Storage Layout
Contract state variables are stored in a persistent key-value store. The EVM maps variable names to 32-byte 'slots'. To save space (and expensive gas), solidity packs smaller variables that are declared next to each other into a single slot.
Syntax Structure
Key Components
- Boilerplate structure required by the Solc compiler.
- Placement of state variables versus functions.
Practical Implementation
Visualizing the difference between packed and unpacked storage.
Core Concepts
Slot
A 32-byte chunk of storage. The basic unit of persistence.
Packing
Putting multiple variables < 32 bytes into one slot.
Offset
Where a variable begins within a slot (0 to 31).
Mental Model
Tetris in a Warehouse
Storage is like a warehouse with uniform 32-byte boxes. You want to fill each box completely before opening a new one. If you put a small marble (uint8) in a box and seal it, you wasted space. If you put 32 marbles in, you win.
Under the Hood
Variables are laid out in order of declaration. If a variable doesn't fit in the remaining space of the current slot, it moves to the next. Structs and Arrays always start a new slot.
Gas Analysis
`SSTORE` is the most expensive opcode (20k gas for new slot).
- • Pack `uint128` timestamps and `address` (160 bits) together.
- • Pack `bool` flags (1 byte each).
Security Risks
Storage collisions in Proxy patterns.
- ! If you upgrade a contract and insert a new variable in the middle, purely by index, it will overwrite the data of the variable that used to be there.
Common Use Cases
Interactive Visualization
See exactly how the EVM handles this code in memory, storage, and the stack.
Unpacked
uint128 auint256 cuint128 bPacked
uint128 auint128 buint256 c