Skip to content
Back to Curriculum
INTERNALS

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

Example.sol
Loading...

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.

Practical.sol
Loading...

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.

SSTORESLOAD

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

Audit preparation: ensuring critical data is where you expect.
Gas Optimization: Squeezing 4 `uint64`s into 1 slot saves 75% gas.
Upgradeability: Ensuring storage layouts don't collide in proxies.

Interactive Visualization

See exactly how the EVM handles this code in memory, storage, and the stack.

Unpacked

Slot 0
16 bytes free
a16B
Slot 1
c32B
Slot 2
16 bytes free
b16B
Variables:
uint128 a
uint256 c
uint128 b

Packed

Slot 0
b16B
a16B
Slot 1
c32B
Variables:
uint128 a
uint128 b
uint256 c