EVM Storage
How smart contracts store data
Smart contracts have storage slots to store state data. Each storage slot is 32 bytes.
Here is an example smart contract where a user can change the state for a uint variable. Note: a uint variable is 256 bits by default in Solidity, equivalent to 32 bytes:
EVM storage opcodes
Storage (stored, expensive):
-SSTORE: write data to storage slot (20000 gas)
-SLOAD: read data from a storage slot (800 gas)
Memory (run time, cheap):
-MSTORE (3 gas)
-MLOAD (3 gas)
Here is a smart contract that uses Assembly (Yul in Solidity) to access these opcodes:
How to compress data in storage slots
-If you are using a variable that never changes, make the variable immutable so that it doesn't use a storage slot.
-Try to fit data in less storage slots when possible. For example, if you need a uint, an address and an uint with only 96 bits:
Correct:
Note: Pack the compressed data together (above), or you will end up using another storage slot anyway (below)
Wrong:
Why is storing large data not recommended on chain?
The more storage slots you want to write to, the more gas you need to pay. Storing large files like high resolution images is very expensive on chain. Decentralized storage alternatives like IPFS and Filecoin solve this problem.