Storage layout shows how data is saved in a blockchain smart contract. It helps us understand where and how values are kept.
0
0
Storage layout in Blockchain / Solidity
Introduction
When you want to know how variables are stored in a smart contract.
When debugging or upgrading contracts to avoid data loss.
When optimizing contract storage to save gas fees.
When reading contract data directly from the blockchain.
When designing contracts that interact with each other and share storage.
Syntax
Blockchain / Solidity
Storage layout depends on the contract language and compiler. For example, in Solidity: - State variables are stored in slots. - Each slot is 32 bytes. - Variables are packed if possible. Example: uint256 a; // slot 0 uint128 b; // slot 1 (or packed with others)
Storage slots are 32 bytes each in Ethereum smart contracts.
Variables are stored in order of declaration unless packed.
Examples
Here,
b and c share the same slot because they fit together.Blockchain / Solidity
contract Example {
uint256 a; // stored in slot 0
uint128 b; // stored in slot 1
uint128 c; // packed with b in slot 1
}flag uses 1 byte but occupies a full slot unless packed with others.Blockchain / Solidity
contract Example {
bool flag; // stored in slot 0
uint256 number; // stored in slot 1
}Sample Program
This contract shows how variables are stored in slots. Variables b and c share slot 1 because they fit in 32 bytes together. Similarly, flag and small share slot 2.
Blockchain / Solidity
pragma solidity ^0.8.0; contract StorageLayout { uint256 public a = 1; // slot 0 uint128 public b = 2; // slot 1 (part 1) uint128 public c = 3; // slot 1 (part 2) bool public flag = true; // slot 2 (part 1) uint8 public small = 4; // slot 2 (part 2) }
OutputSuccess
Important Notes
Understanding storage layout helps prevent bugs when upgrading contracts.
Storage is expensive on blockchain, so packing variables saves gas.
Always check compiler documentation for exact storage rules.
Summary
Storage layout defines how contract variables are saved in blockchain storage slots.
Variables are stored in order and packed to save space.
Knowing storage layout helps with debugging, upgrading, and optimizing contracts.