Crypto Training
Solidity Storage Layout: Slots, Packing, and the Bugs It Enables
How Solidity 0.8.38 assigns storage slots (packing, mappings, dynamic arrays, strings, inheritance, namespaced and transient storage), with slot derivations you can reproduce and the incidents where layout was the root cause.
The EVM gives each contract a key-value store with 2^256 keys and 32-byte values, read with SLOAD and written with SSTORE. Variable names, types and packing exist only in the compiler, which maps each state variable to a slot and a byte offset by rules documented in Layout of State Variables in Storage and Transient Storage. The statements and slot values in this post were checked against that page and against output from the 0.8.38 compiler.
An auditor needs those rules in three situations. Code that runs through delegatecall shares one store between two contracts, assembly and libraries write to slots chosen by hand, and upgrades change the list of declarations while the stored data stays where it is. Each of the three has produced incidents, and the cases below are grouped the same way.
A worked layout#
State variables are assigned in declaration order, starting at slot 0. The first item in a slot sits in the lowest-order bytes, a value type takes only the bytes it needs, and an item that does not fit into the rest of the current slot starts the next one.
contract Layout {
uint128 a; // slot 0, bytes 0..15
uint64 b; // slot 0, bytes 16..23
bool paused; // slot 0, byte 24
address owner; // slot 1: 20 bytes do not fit in the 7 left in slot 0
uint256 total; // slot 2
mapping(address => uint256) balances; // slot 3: the slot itself stays empty
uint64[] checkpoints; // slot 4 holds the length
string name; // slot 5
uint256 transient lock; // transient slot 0, no storage slot
uint256 constant FEE = 30; // no slot, inlined at each use
address immutable deployer = msg.sender; // no slot, written into the runtime code
}
forge inspect Layout storageLayout prints exactly this assignment, so there is no need to work it out by hand for code you can compile. After a = 1, b = 2 and paused = true, the raw content of slot 0 is 0x0000000000000001000000000000000200000000000000000000000000000001. Reading from the right, the low 16 bytes hold a, the next 8 hold b, and byte 24 holds the flag.
Mappings, arrays and strings#
Mappings and dynamically sized types reserve a single slot p in the sequence and keep their data at positions derived from p by hashing, while a struct (the last row) occupies consecutive slots starting at a fresh one.
Type at slot p | What slot p holds | Where the data is |
|---|---|---|
mapping(K => V) | nothing | value for key k at keccak256(h(k) . p). For value-type keys h pads to 32 bytes, which is keccak256(abi.encode(k, p)). For string and bytes keys h(k) is the unpadded data |
T[] | the length | elements from keccak256(p) onward, packed like state variables when T is 16 bytes or smaller |
bytes, string, up to 31 bytes | the data, left-aligned, with length * 2 in the lowest byte | in slot p itself |
bytes, string, 32 bytes or more | length * 2 + 1 | from keccak256(p) onward |
| struct | its first member | members in order from p, packed by the same rules |
For the contract above, balances[0x000000000000000000000000000000000000a11c] is at 0xb780fdf346bc6561072f198dbcfdf062dc202b02eded58dc4b72d16aaf535052, which cast index address 0x000000000000000000000000000000000000a11c 3 reproduces. A nested mapping applies the formula twice, with the first result as the p of the second. After pushing 11, 22, 33, 44 and 55 into checkpoints, slot keccak256(4) holds 0x000000000000002c00000000000000210000000000000016000000000000000b, four elements in one word, and the fifth sits alone in the next slot. The string "Vault" is stored as 0x5661756c74 followed by zeros and a final byte 0x0a, twice its length.
All of these regions share one address space, and the only reason they do not overlap is that nobody can choose a key whose hash lands on a slot already in use. Hand-written assembly gets no such protection, since it must reproduce these formulas exactly, including the element packing and the two string encodings.
Writing a packed slot by hand#
The compiler masks and shifts whenever Solidity code touches a, b or paused. Assembly sees only the full word, so a direct sstore replaces all three.
// VULNERABLE: overwrites b and paused together with a
function setAUnsafe(uint128 newA) external {
assembly {
sstore(a.slot, newA)
}
}
function setA(uint128 newA) external {
assembly {
let mask := 0xffffffffffffffffffffffffffffffff // the low 16 bytes, where a lives
let word := sload(a.slot)
sstore(a.slot, or(and(word, not(mask)), and(newA, mask)))
}
}
In a test, setAUnsafe(7) left b at 0 and paused false, while setA(9) preserved both. Code like the first function usually passes its unit tests on the day it is written, because the variable it writes is alone in its slot, and breaks when a later change packs a neighbour next to it. Using a.slot and a.offset in place of literals at least keeps the assembly aligned with the compiler when declarations move.
Inheritance and upgrades#
For a contract with base contracts, the compiler orders state variables by the C3 linearisation, starting with the most base-ward contract, and it will pack a derived contract's first variables into the last slot of its base when they fit. With contract Base { uint128 x; } and contract Mid is Base { uint128 y; uint256 z; }, both x and y are in slot 0. Adding a uint256 to the end of Base moves y to slot 2 and z to slot 3. "Append only" therefore means appending to the end of the whole linearised layout, and a base contract can only grow if it reserved a gap or keeps its state in a namespace (see the next section).
An upgrade that violates this fails without any error, because old data is simply read through new offsets. Take a v1 with bool paused; address owner;, which packs both into slot 0, and a v2 that inserts uint256 feeBps in front of them. Running v2's code on v1's storage, we got a feeBps of 24942961277114076470676221145024563535461248733441 (the old owner and flag read as one number), paused == false and owner == address(0). A pause switch that turned itself off and an owner of zero are both states that the rest of the code may treat as legitimate.
Audius is the reference case for a collision between a proxy and its implementation. Its proxy contract stored proxyAdmin in slot 0, and the logic contracts inherited OpenZeppelin's Initializable, which at that time kept its initialized and initializing flags in slot 0 as well. The admin address ended in the bytes ab ac, so through the implementation's layout both flags read as true and the initializer modifier let every call through. On 23 July 2022 an attacker called initialize again on the governance, staking and delegation contracts, passed a proposal under the new parameters and moved 18.56M AUDIO out of the treasury (writeup, Audius post-mortem). The contracts had been live since October 2020.
Miscounting is the more ordinary route to the same result. A Pashov review of Gains Network found a storage struct whose layout comment treated bytes32[2] as 64 bits, when it occupies two full slots, which pushed the struct's tail into the storage of the next module and over that module's owner field (finding).
Fixed slots: EIP-1967, ERC-7201 and layout specifiers#
The sequential layout is fragile for state that several contracts must agree on, so three conventions place state at fixed locations.
EIP-1967 puts a proxy's own variables at constants such as 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc for the implementation address, which is keccak256("eip1967.proxy.implementation") - 1. The subtraction matters. Mapping and array data live at hashes of known inputs, and after subtracting one "the preimage of the hash cannot be known", so no key can be constructed that lands there. A proxy written this way cannot repeat the Audius collision.
ERC-7201 applies the same idea to implementation state. A module declares a struct and places it at keccak256(abi.encode(uint256(keccak256(id)) - 1)) & ~bytes32(uint256(0xff)). OpenZeppelin's upgradeable contracts have used it since v5.0, with Ownable at 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300 for the id openzeppelin.storage.Ownable, and cast index-erc7201 computes the value for any id. Inside a namespace the struct members are still laid out in order, so the append-only rule now applies per struct, and base contracts no longer shift each other.
Since Solidity 0.8.29 a contract can also move its whole sequential layout with a specifier. contract Relocated layout at 0x1000 { uint256 a; } compiles with a in slot 4096.
A fixed slot is a constant in the source, and a constant is a claim you can check. ATOHook, a Uniswap v4 hook drained of 14.41 ETH in June 2026, carried a reentrancy guard in the style of Solady's whose slot constant was 0x02215292eb9609279094554c6e223f800950648ddfa3da30329838d6c170928d. Solady's published constant is the 9-byte value 0x929eee149b4bd21268. The value in the hook equals keccak256(abi.encode(0x2441E480F62bf609A08dA09143e4BAf8a817D757, 17)), the slot of rewards[0x2441...] for the rewards mapping at slot 17, and that address is the contract that later called getReward() and was paid the guard's "entered" marker as its reward 200 times (writeup). A 256-bit match between a constant and a mapping slot cannot happen by chance, which suggests the constant was derived from that address. Recomputing each hard-coded slot from its stated derivation takes a minute with cast keccak and would have exposed it.
Transient storage#
EIP-1153, live since the Cancun fork of March 2024, adds a second store per contract that is addressed by TSTORE and TLOAD and discarded at the end of the transaction. Solidity supports value-type state variables with the transient keyword from 0.8.28. They follow the same packing rules in a layout of their own, so transient slot 0 has no relation to storage slot 0.
The property that bites is the lifetime, which covers the whole transaction and so outlives the call that wrote the value. SIR's vault kept the address of the Uniswap pool it was about to call in transient slot 1 and used it to authenticate uniswapV3SwapCallback. Later in the same function it reused slot 1 for an output amount and never cleared it. On 30 March 2025 an attacker minted an amount whose numeric value equalled an address they could deploy to, then called the callback from that address in the same transaction and withdrew about $354k (writeup). Startale's account proxy made the mirror-image mistake in September 2026 by setting a transient "may initialize" flag in its constructor, which stayed set for the rest of the deployment transaction (writeup).
Compiler support is recent enough to have had its own bug. Versions 0.8.28 to 0.8.33 could, when compiling through the IR pipeline, emit a delete that cleared the persistent variable where the transient one was meant, or the reverse, which the team fixed in 0.8.34.
Reviewing layout in practice#
The check we would run first on any upgradeable system is a layout diff, since it is mechanical and catches the most expensive class of mistake.
- Run
forge inspect <Contract> storageLayout(andtransientStorageLayout) on the deployed version and on the candidate, and compare slot by slot. OpenZeppelin's upgrade plugins automate the comparison against a reference contract. - For a proxy, list the slots the proxy itself writes. Anything outside the EIP-1967 constants has to be checked against the implementation's layout.
- Search for
sstore,sload,tstore,tloadand.slot :=. For each hit, establish which variable it addresses, whether a packed word is masked, and whether a literal slot matches its stated derivation. - For each transient variable, find where it is cleared and ask what a second call in the same transaction would read.
- On a live contract, read the slots.
cast storage <address> <slot>together withcast indexis enough, and the Storage Viewer on this site does the same in the browser, including mapping and array positions.
Unbounded arrays and mappings with a parallel index array raise a separate question about gas and liveness, which Gas Griefing and Untrusted Reverts takes up.
Sources#
- Solidity 0.8.38: Layout of State Variables in Storage and Transient Storage for packing, inheritance order, mappings, dynamic arrays,
bytesandstring, and layout specifiers - EIP-1967 for the proxy slots and the reason for the
- 1 - ERC-7201 for the namespace formula, and OwnableUpgradeable.sol at v5.7.0 for a contract that uses it
- EIP-1153 for transient storage semantics and lifetime
- Solady ReentrancyGuard.sol at v0.1.26 for the published guard slot
- The EVM opcode reference on this site for
SLOAD,SSTORE,TLOADandTSTORE