Solidity Basics
Solidity is an object-oriented, high-level language for implementing smart contracts. A contract is a collection of code (functions) and data (state) that resides at a specific address on the Ethereum blockchain.
Syntax Structure
Key Components
- Boilerplate structure required by the Solc compiler.
- Placement of state variables versus functions.
Practical Implementation
A minimal contract that stores and retrieves a value.
Core Concepts
contract
Defines a new smart contract. Similar to a 'class' in other languages.
uint256
Unsigned Integer of 256 bits. The standard variable type for numbers in Ethereum.
public
Visibility modifier. Automatically creates a 'getter' function so others can read this variable.
function
A block of code that allows you to execute actions or calculations.
Mental Model
The Persistent State Machine
Think of a Smart Contract not as a script that runs and finishes, but as a singleton object living on the blockchain that maintains its state forever. Every function call is a transaction that transitions this state from A to B.
Under the Hood
When you declare a `uint256` state variable, the EVM reserves a 32-byte slot in the contract's specific Storage Trie. Accessing this variable uses the `SLOAD` opcode (costly) and writing to it uses `SSTORE` (very costly). The 'public' keyword automatically generates a getter function that corresponds to a specific 4-byte function selector in the bytecode.
Gas Analysis
State changes are the most expensive operations on Ethereum.
- • Avoid writing to storage in loops.
- • Use `memory` variables for intermediate calculations.
- • Pack variables (e.g. uint128, uint128) to fit in one slot.
Security Risks
Everything on the blockchain is public, even 'private' variables.
- ! Don't store passwords or API keys in variables, even private ones.
- ! Integer overflows (solved in Solidity 0.8+).
Common Use Cases
Interactive Visualization
See exactly how the EVM handles this code in memory, storage, and the stack.
Click Run to execute the simulation
Then use the step controls to navigate