0
0
Blockchain / Solidityprogramming~15 mins

State variables in Blockchain / Solidity - Deep Dive

Choose your learning style9 modes available
Overview - State variables
What is it?
State variables are special variables in blockchain smart contracts that store data permanently on the blockchain. Unlike regular variables that exist only temporarily during a function call, state variables keep their values between transactions. They represent the contract's memory or state that everyone on the blockchain can see and trust. This stored data can include balances, ownership, or any information the contract needs to remember.
Why it matters
Without state variables, smart contracts would forget everything after running, making it impossible to keep track of things like who owns what or how much money is stored. State variables solve the problem of persistent data in a decentralized system where no single person controls the memory. This permanence and transparency enable trustless applications like cryptocurrencies, voting systems, and supply chains.
Where it fits
Before learning state variables, you should understand basic programming variables and functions. After mastering state variables, you can learn about storage vs memory, gas costs, and advanced contract patterns like mappings and structs that use state variables extensively.
Mental Model
Core Idea
State variables are the permanent memory of a smart contract that keeps data safe and visible on the blockchain between transactions.
Think of it like...
Imagine a public ledger book in a town square where everyone can write and read entries. State variables are like the pages in that ledger that keep records safe forever, unlike notes you write on a whiteboard that get erased after a meeting.
┌─────────────────────────────┐
│       Smart Contract        │
│ ┌───────────────┐           │
│ │ State Variable│◄──Stored───┤
│ │  (Permanent)  │           │
│ └───────────────┘           │
│                             │
│ ┌───────────────┐           │
│ │ Local Variable│           │
│ │ (Temporary)   │           │
│ └───────────────┘           │
└─────────────┬───────────────┘
              │
              ▼
       Blockchain Storage
Build-Up - 7 Steps
1
FoundationWhat are variables in programming
🤔
Concept: Introduce the basic idea of variables as containers for data.
In programming, a variable is like a labeled box where you can store information such as numbers or words. You can put data into the box, change it, or look inside to see what's there. For example, in many languages, you can write: int age = 25; which means you have a box named 'age' holding the number 25.
Result
You understand that variables hold data temporarily during program execution.
Knowing what variables are is essential because state variables build on this idea but add permanence.
2
FoundationDifference between local and state variables
🤔
Concept: Explain that local variables exist only during function execution, while state variables persist.
Local variables are created inside functions and disappear when the function ends. State variables, however, live in the contract itself and keep their values even after functions finish. For example, in Solidity, a local variable might be: uint temp = 5; inside a function, but a state variable is declared outside functions and saved on the blockchain.
Result
You can distinguish temporary data from permanent contract data.
Understanding this difference helps you know why state variables are needed for blockchain contracts.
3
IntermediateDeclaring state variables in smart contracts
🤔
Concept: Show how to declare state variables in Solidity and their default visibility.
In Solidity, you declare state variables inside the contract but outside any function. For example: contract MyContract { uint public count; // state variable } Here, 'count' is a state variable of type unsigned integer. The 'public' keyword means anyone can read it. If you don't specify visibility, it defaults to 'internal', meaning only the contract and its children can access it.
Result
You can write and recognize state variable declarations in smart contracts.
Knowing how to declare state variables correctly is the first step to managing contract data.
4
IntermediateState variables and blockchain storage costs
🤔Before reading on: do you think changing a state variable costs gas or is free? Commit to your answer.
Concept: Explain that storing and changing state variables costs gas because it uses blockchain storage.
Every time you write or update a state variable, the blockchain must save this change forever. This uses storage space, which costs gas (a fee paid in cryptocurrency). Reading state variables is usually free if done off-chain, but writing or changing them costs gas. For example, increasing a counter stored as a state variable will cost gas each time.
Result
You understand why optimizing state variable usage saves money.
Knowing the cost of state variables helps you write efficient and cost-effective smart contracts.
5
IntermediateVisibility and access control of state variables
🤔Before reading on: do you think all state variables are visible to everyone on the blockchain? Commit to your answer.
Concept: Teach how visibility keywords control who can read or write state variables.
State variables can have visibility modifiers: public, private, internal, or external (external is not used for variables). Public variables automatically get a getter function so anyone can read them. Private variables can only be accessed inside the contract. Internal variables are accessible in the contract and derived contracts. This controls how data is shared or hidden.
Result
You can control who sees or changes your contract's data.
Understanding visibility protects sensitive data and controls contract behavior.
6
AdvancedState variables in mappings and structs
🤔Before reading on: do you think state variables can store complex data like lists or key-value pairs? Commit to your answer.
Concept: Show how state variables can hold complex data structures like mappings and structs for flexible storage.
State variables are not limited to simple types. You can declare mappings (like dictionaries) and structs (custom data types) as state variables. For example: contract MyContract { mapping(address => uint) public balances; struct User { uint id; string name; } User public user; } This allows contracts to store complex, organized data on the blockchain.
Result
You can design contracts that manage rich data efficiently.
Knowing how to use complex state variables unlocks powerful contract designs.
7
ExpertStorage layout and upgradeability challenges
🤔Before reading on: do you think changing the order of state variables in a contract affects its data? Commit to your answer.
Concept: Explain how the order and layout of state variables in storage matters for contract upgrades and data integrity.
State variables are stored in specific slots in blockchain storage based on their declaration order and type size. Changing this order or removing variables in upgraded contracts can corrupt stored data. Upgradeable contracts must carefully manage storage layout to avoid overwriting or losing data. Tools and patterns exist to help maintain storage compatibility across versions.
Result
You understand the risks and best practices for contract upgrades involving state variables.
Knowing storage layout details prevents costly bugs and data loss in real-world contract upgrades.
Under the Hood
State variables are stored in the blockchain's persistent storage, which is a key-value store indexed by 32-byte slots. Each state variable is assigned a storage slot based on its declaration order and type size. When a transaction modifies a state variable, the new value is written to the blockchain state trie, which is replicated and secured by all nodes. This storage is expensive and permanent, ensuring data integrity and transparency.
Why designed this way?
Blockchain storage is designed to be immutable and decentralized, so state variables must be stored in a way that all participants agree on the data. The slot-based storage layout allows efficient access and predictable storage patterns. Alternatives like ephemeral memory would lose data after execution, breaking contract functionality. The design balances permanence, security, and cost.
┌───────────────────────────────┐
│       Blockchain Storage       │
│ ┌───────────────┐             │
│ │ Slot 0        │◄── count    │
│ ├───────────────┤             │
│ │ Slot 1        │◄── balances │
│ ├───────────────┤             │
│ │ Slot 2        │◄── user.id  │
│ └───────────────┘             │
│                               │
│  Smart Contract Storage Slots │
│  assigned by declaration order│
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think state variables are free to change because they are just variables? Commit to yes or no.
Common Belief:Changing state variables is free because they are just like normal variables.
Tap to reveal reality
Reality:Changing state variables costs gas because it updates permanent blockchain storage.
Why it matters:Ignoring gas costs leads to expensive contracts and failed transactions due to out-of-gas errors.
Quick: Do you think private state variables are hidden from everyone on the blockchain? Commit to yes or no.
Common Belief:Private state variables keep data secret from everyone except the contract.
Tap to reveal reality
Reality:Private variables are hidden only from other contracts and users at the code level, but their data is still visible on the public blockchain.
Why it matters:Assuming privacy can cause leaks of sensitive data, risking security and trust.
Quick: Do you think changing the order of state variables in a contract is safe? Commit to yes or no.
Common Belief:You can reorder or remove state variables freely without affecting stored data.
Tap to reveal reality
Reality:Changing order or removing state variables breaks storage layout and corrupts data in upgradeable contracts.
Why it matters:Mismanaging storage layout causes bugs and permanent data loss in deployed contracts.
Quick: Do you think state variables can only store simple data types? Commit to yes or no.
Common Belief:State variables can only hold simple types like numbers or booleans.
Tap to reveal reality
Reality:State variables can store complex types like mappings, structs, and arrays.
Why it matters:Underestimating state variables limits contract design and functionality.
Expert Zone
1
State variables of dynamic types like strings or arrays store a hash pointer in their slot, with actual data stored elsewhere, affecting gas costs and access patterns.
2
Packing multiple small state variables into a single 32-byte slot reduces storage costs but requires careful ordering and understanding of Solidity's storage layout.
3
Using immutable variables (set once at deployment) can save gas compared to regular state variables, but they cannot be changed later.
When NOT to use
State variables should not be used for temporary data or computations that do not need to persist. For such cases, use memory or calldata variables to save gas. Also, avoid storing large data on-chain; instead, use off-chain storage with on-chain references.
Production Patterns
In production, state variables are often combined with access control modifiers to protect sensitive data. Upgradeable contracts use proxy patterns with careful storage layout management. Developers optimize state variables by minimizing writes and using efficient data structures like mappings and packed structs.
Connections
Database Systems
Both manage persistent data storage with structured access.
Understanding state variables is like understanding how databases store and retrieve data permanently, helping grasp blockchain's data persistence.
Memory vs Storage in Programming
State variables correspond to storage, while local variables correspond to memory.
Knowing the difference between temporary and permanent storage in programming clarifies why state variables behave differently and cost more.
Accounting Ledger
State variables act like ledger entries recording balances and transactions.
Seeing state variables as ledger entries helps understand their role in maintaining trustworthy, transparent records.
Common Pitfalls
#1Forgetting that changing state variables costs gas and writing inefficient code that updates them unnecessarily.
Wrong approach:contract Example { uint public count; function increment() public { count = count + 1; // called many times without need } }
Correct approach:contract Example { uint public count; function increment() public { if (someCondition) { count = count + 1; } } }
Root cause:Misunderstanding that every write to state variables consumes gas leads to costly and inefficient contracts.
#2Assuming private state variables keep data secret from blockchain users.
Wrong approach:contract Secret { string private password = "1234"; }
Correct approach:contract Secret { bytes32 private passwordHash; function setPassword(string memory pwd) public { passwordHash = keccak256(abi.encodePacked(pwd)); } }
Root cause:Confusing code-level privacy with blockchain data privacy causes sensitive data exposure.
#3Changing the order of state variables in an upgradeable contract causing data corruption.
Wrong approach:// Original contract contract V1 { uint a; uint b; } // Upgraded contract contract V2 { uint b; uint a; }
Correct approach:// Upgraded contract preserving order contract V2 { uint a; uint b; uint c; // new variable added at the end }
Root cause:Not understanding storage slot assignment leads to broken data after upgrades.
Key Takeaways
State variables store data permanently on the blockchain, unlike temporary local variables.
Changing state variables costs gas because it uses expensive blockchain storage.
Visibility modifiers control who can read or write state variables but do not hide data from the public blockchain.
The order and layout of state variables matter deeply for contract upgrades and data integrity.
State variables can hold complex data types, enabling powerful and flexible smart contracts.