Solidity Variables Explained: State, Local, and Global
In Solidity, variables act as containers for storing data on the blockchain. But not all variables are created equal! Understanding their types and lifetimes is crucial for writing efficient and secure smart contracts.
Quick Comparison
Type | Lifetime | Gas Cost | Example |
---|---|---|---|
State | Contract lifetime | High (storage) | uint256 public count; |
Local | Function execution | Low (memory) | uint256 temp = 5; |
Global | Always available | None (pre-defined) | msg.sender |
1. State Variables: The Blockchain's Database
contract MyContract {
// State variable (stored on-chain)
uint256 public persistentData;
function updateData(uint256 _new) public {
persistentData = _new; // Modifies blockchain state
}
}
- ๐ Stored in contract storage
- ๐ธ Modifying them costs gas
- ๐ Accessible across all functions
2. Local Variables: Temporary Workers
function calculateTotal() public pure returns(uint256) {
uint256 a = 5; // Local variable
uint256 b = 10;
return a + b; // Dies after execution
}
- โก Exist only during function execution
- ๐ No gas cost (memory-based)
- ๐ซ Cannot be accessed externally
3. Global Variables: Blockchain Oracles
function getInfo() public view returns(
address, uint256, uint256
) {
return (
msg.sender, // Caller's address
block.timestamp, // Current time
address(this).balance // Contract balance
);
}
Common Global Variables:
msg.value
: ETH sent with calltx.origin
: Original senderblock.number
: Current block
โ ๏ธ Common Mistakes
- Confusing
memory
andstorage
for reference types - Using global variables like
tx.origin
for authorization - Overusing state variables ($$$ gas costs!)
Best Practices
- Minimize state variables to reduce gas costs
- Use
memory
for temporary arrays/structs - Validate global inputs (e.g., check
msg.value > 0
)
Comments
Post a Comment