Loading...
How data is stored on-chain
Understanding storage is critical because every byte stored on-chain costs gas.
Storage Locations:
• storage — Persistent, saved on the blockchain. State variables default to storage.
• memory — Temporary, only exists during function execution. Used for function parameters and local variables.
• calldata — Read-only temporary, used for external function parameters. Cheaper than memory.
Mappings: The most common data structure. Like a dictionary with key-value pairs.
mapping(address => uint256) public balances;
balances[msg.sender] = 100;
Structs: Custom data types that group related fields.
struct User { string name; uint256 balance; bool active; }
Arrays: Both fixed-size and dynamic arrays are supported, but dynamic arrays in storage are expensive. Use mappings when possible.
Gas optimization tips:
• Pack variables of the same type together to share storage slots
• Use events for data that doesn’t need to be read on-chain
• Prefer mappings over arrays for lookups
• Use calldata instead of memory for read-only function parameters