Storage packing in Solidity: reading packed slots from the outside
Solidity packs small state variables into a single 32-byte slot. That is cheap on gas, and it quietly breaks every tool that assumes one variable means one slot: indexers, debuggers, and anyone reproducing a bug from a transaction trace.
Here is the smallest honest demo I could write. Two uint128s land at slot 0 offsets 0 and 16. A uint256 gets its own slot. The mapping/array data starts at keccak256(abi.encode(key, slot)).
contract PackedVault { uint128 public low; // slot 0, offset 0 uint128 public high; // slot 0, offset 16 uint256 public total; // slot 1 mapping(address => uint256) public balanceOf; // data at keccak256(abi.encode(user, uint256(2))) uint256[] public history; // data at keccak256(abi.encode(uint256(3))) } Reading it back from the outside is one eth_getStorageAt per slot plus a local slice:
cast storage $VAULT 0 # low | high, packed into one word cast storage $VAULT 1 # total, alone cast keccak $(cast abi-encode "f(address,uint256)" $USER 2) # balanceOf($USER) slot Decoding slot 0 gives low in the low 16 bytes and high in the high 16. Forgetting the offset is the classic bug: a naive reader reports low as the whole word and silently drops high.
Two rules that keep this honest:
- Order matters. Packing depends on declaration order and types; a refactor that reorders fields moves every value. Treat the layout as an ABI.
- Only signed/unsigned integers and bytesN pack. Structs and arrays start a new slot, and a mapping is always a hash, never an inline value.
The harness (Foundry, 12 tests including a fuzz test over the packed pair) is at github.com/Rishidar-lab/slotseer. It dumps raw slots on anvil so you can see the layout instead of guessing it.
If you index contracts for a living, assume packing until the ABI proves otherwise.