✅ Master Smart Contract Storage

Optimize storage layout, pack variables, and reduce gas costs

🎯 Key Takeaways

You've mastered contract storage! Here's what you've learned about efficient on-chain data management.

💾

Storage Fundamentals

  • • 2^256 slots, each 32 bytes
  • • Storage vs memory vs calldata
  • • SSTORE: 20,000 gas (new), 5,000 (update)
  • • SLOAD: 2,100 gas per read
  • • Default to zero until written
📦

Variable Packing

  • • Group variables to fit in 32 bytes
  • • Order by size for efficiency
  • • uint128 + uint128 = 1 slot
  • • Save 40-80% on gas costs
  • • Use smallest type needed

Optimization Techniques

  • • Cache storage reads in memory
  • • Minimize storage writes
  • • Delete unused slots for refunds
  • • Use events for historical data
  • • Bit packing for extreme optimization
🔄

Upgradeable Patterns

  • • Proxy: delegatecall for upgrades
  • • Diamond: modular facets
  • • Unstructured: collision prevention
  • • Eternal: separate storage contract
  • • Append variables only!

🎯 Interactive: Knowledge Check

Test your understanding with this quiz:

1. What is the gas cost for writing to a new storage slot (SSTORE)?
2. How many bytes is each storage slot in the EVM?
3. Which variables can be packed into a single 32-byte slot?
4. What does delegatecall do in the proxy pattern?
5. How does unstructured storage prevent collisions?

Quick Reference Guide

Gas Costs

SSTORE (new):20,000 gas
SSTORE (update):5,000 gas
SLOAD (read):2,100 gas
Memory word:~3 gas
Calldata byte:16 gas

Variable Sizes

uint256 / int256:32 bytes
uint128 / int128:16 bytes
address:20 bytes
uint64 / int64:8 bytes
uint8 / bool:1 byte

💡 Remember

Storage is expensive — optimize aggressively or users won't afford your contract

Pack variables — 40-80% gas savings just from smart ordering

Cache reads — load storage once, use memory repeatedly

Upgradeability — never reorder/remove variables, only append

Test upgrades — storage collisions can destroy your contract's data