EVM Storage Overview
The Ethereum Virtual Machine (EVM) executes smart contract code, storing contract states or memory at designated smart contract addresses. This storage functions like an infinitely long array of data structures tied to each contract address. The system ensures no storage location conflicts occur by adhering to strict rules, enabling users to decode any contract’s state. Decoding mapped data requires knowledge of the specific keys used. Contract data is retrieved via the RPC call eth_getStorageAt.
Slot Positioning
Variable Allocation Rules
Variables are assigned positions (called "slots") in a smart contract’s storage array based on:
- Declaration order in the code.
- Variable size (e.g., 256-bit vs. smaller types).
Key behaviors:
- Variables smaller than 256 bits may share a single slot if packed sequentially.
- Mappings/arrays always occupy a full slot. Their elements follow hashing rules (detailed below).
Storage Decoding
- Base types (uint, string): Directly fetch values by slot location using
GetStorageAt. Arrays:
- Slot location returns the array length.
- Array elements are accessed via
keccak256(slot) + index.
Mappings:
- Values are stored at
keccak256(key.concat(slot)). - Multidimensional mappings recursively hash keys and slot positions.
- Values are stored at
👉 Learn how to optimize EVM gas costs
Practical Examples
Case 1: 256-Bit Variables
- All variables are 32 bytes long (no packing).
- Slots align 1:1 with variable order (e.g., Slot 0 = Variable 1).
Case 2: Variable Packing
Rules:
- Applies only to base types (e.g.,
uint128,bool) in declaration order. - Mappings/arrays trigger new slots.
- Packing affects array elements (e.g., multiple indices may share a slot).
- Applies only to base types (e.g.,
- Example: A
uint128followed by auint128occupies one slot, while a subsequent mapping starts a new slot.
Inheritance Impact
- Parent contract variables occupy initial slots.
- Child contract variables follow in declaration order.
FAQs
1. How does EVM handle overlapping storage?
EVM prevents conflicts via slot hashing (e.g., keccak256 for mappings) and sequential packing.
2. Can packed variables reduce gas costs?
Yes! Packing optimizes storage usage, lowering SSTORE/SLOAD operations.
3. How are dynamic arrays stored?
Array length uses the declared slot; elements start at keccak256(slot).
👉 Explore advanced EVM optimization techniques
Key Takeaways
- EVM storage is deterministic but requires hashing for complex types.
- Packing rules minimize storage overhead for small variables.
- Inheritance preserves slot order from parent to child contracts.
By mastering these rules, developers can efficiently decode and optimize smart contract storage.