State Variable
1 min read
Pronunciation
[stayt vair-ee-uh-buhl]
Analogy
State variables are like fields in a database record—they persist between transactions and represent the contract’s stored data.
Definition
A variable declared at contract scope in Solidity whose value is permanently stored in contract storage on the blockchain.
Key Points Intro
State variables define on‑chain storage via:
Key Points
Persistent storage: Saved in contract’s storage trie.
Default visibility: Internal unless marked public/private.
Gas cost: Reads/writes incur SLOAD/SSTORE gas.
Types: Value types and reference types (structs, arrays).
Example
```
contract Token {
uint256 public totalSupply;
}
``` stores `totalSupply` on‑chain and auto‑generates a getter.
Technical Deep Dive
Each state variable is assigned a storage slot (32 bytes) or packed into slots. Reading uses the `SLOAD` opcode, writing uses `SSTORE` which can refund gas if zeroing. Complex types use a keccak256‑based scheme for dynamic indexing.
Security Warning
Unintended storage collisions in upgradeable proxies can corrupt state; follow storage gap patterns.
Caveat
Excessive state writes are costly; minimize storage usage for gas optimization.
State Variable - Related Articles
No related articles for this term.