Member-only story
All About Solidity Data Locations — Storage
Diving into storage references and smart contract storage layout.
This is Part I of the “All About Data Locations” sub-series.
In today's article, we cover in more detail an important data location in the EVM: the smart contract storage.
We will see how the layout of the contract storage works, storage
references. how to write to the contract storage in assembly. We will also use some contracts from OpenZeppelin and Compound to learn how storage
references work in practice while learning the Solidity code behind these popular contracts and protocols along the way.
Table of Content
- Introduction
- Layout of Storage
- Basics of Storage
- Interacting with Storage
- Storage pointers in function parameters
- Storage pointers in function body
- The cost of reading storage.
- Conclusion
Introduction
Understanding the storage model in Ethereum and EVM-based chain is essential for good smart contract development.
The only place where you can store data permanently on a smart contract so that it can then be accessed for future executions is in its storage. Each smart contract maintains its state in its own permanent storage. It acts like “a mini-database for a smart contract”, but unlike other databases, this database is publicly accessible. All the values stored in the smart contract storage are available for external reading for free (via static calls), without the need to send a transaction to the blockchain.
Writing to the storage, however, is quite expensive. Actually, it is the most expensive operation in the EVM when it comes to gas cost. The content of the storage can be changed with sendTransaction
calls. Such calls change state. This is the reason why contract-level variables are referred to as state variables.
One important thing to remember is that by design in Ethereum and the EVM, a contract can neither read nor write any storage apart from its own. The only way contract A can read or write from…