Smart Contracts: Code as Law on the Blockchain
Nick Szabo coined the term "smart contract" in 1994 — before the internet was mainstream. His vision: self-executing agreements encoded in software, enforced by cryptography, not courts. Ethereum made this vision real in 2015.
What Is a Smart Contract?
A smart contract is a program that lives on a blockchain. It has:
- An address (like a bank account)
- State (variables stored on-chain)
- Functions (callable by anyone who knows the ABI)
- Ether (it can hold, send, and receive value)
Once deployed, it runs exactly as written — no company can modify it, no executive can shut it down, no government can freeze it (without 51% control of the network).
The Ethereum Virtual Machine (EVM)
All EVM-compatible chains (Ethereum, Polygon, BSC, Avalanche, Base) run a stack-based virtual machine. Your Solidity code compiles to EVM bytecode:
Gas is the unit of computational effort. Every opcode costs gas. This prevents infinite loops and compensates validators.
Writing Your First Contract
Key Concepts Above:
msg.sender— the address calling the functionmsg.value— ETH sent with the call (in wei)mapping— key-value storage (like a hashmap, persisted on-chain)event— logs emitted to the blockchain (queryable, but not on-chain state)require— reverts the entire transaction if false
The Reentrancy Vulnerability
The most infamous smart contract bug. In 2016, it drained $60M from The DAO.
The fix (Checks-Effects-Interactions pattern):
DeFi: Smart Contracts at Scale
Automated Market Makers (AMM)
Uniswap V2's entire exchange logic fits in ~500 lines of Solidity. The core is the constant product formula:
x * y = k
Where x and y are token reserves. Buying token Y with token X:
(x + Δx) * (y - Δy) = k
Δy = (y * Δx) / (x + Δx)
No order books. No market makers. Just math.
Flash Loans
Borrow millions with zero collateral — as long as you repay within one transaction:
Security Checklist
| Vulnerability | Prevention |
|---|---|
| Reentrancy | CEI pattern, ReentrancyGuard |
| Integer overflow | Solidity 0.8+ (built-in checks) |
| Access control | OpenZeppelin Ownable/AccessControl |
| Oracle manipulation | TWAP oracles, Chainlink |
| Frontrunning | Commit-reveal, private mempools |
| Selfdestruct abuse | Avoid address(this).balance for logic |
Oracles: Connecting to the Real World
Smart contracts can't access external data natively. Oracles are the bridge:
The Promise: Smart contracts remove the need to trust institutions. You trust the math, the audit, and the open-source code instead. The more composable and open the ecosystem becomes, the more powerful — and the more critical security becomes.