Smart Contracts Explained
Build and deploy your first smart contract interactively
What Are Smart Contracts?
A smart contract is a self-executing program stored on a blockchain. When predetermined conditions are met, the contract automatically executes without any human intervention.
๐ก The Big Idea
Think of a vending machine: You put in money (input), select a product (condition), and the machine automatically dispenses it (execution). No cashier needed. Smart contracts work the same way on the blockchain.
Understanding Smart Contract Code
๐ง What Makes Code "Smart"?
A smart contract is just code, but what makes it special is where it runs and how it executes. Instead of running on a company's server (which they control), it runs on thousands of computers in a blockchain network (which no one controls).
๐ Anatomy of a Smart Contract
State Variables
Data stored on the blockchain (balances, owner addresses, etc.)
Functions
Actions the contract can perform (transfer, mint, withdraw, etc.)
Conditions
Logic that determines when functions execute (if/else statements)
Events
Signals emitted when important actions occur (for logging and monitoring)
โ Traditional Code
- โข Runs on centralized servers
- โข Company can change it anytime
- โข Users must trust the company
- โข Can be taken offline
โ Smart Contract Code
- โข Runs on decentralized network
- โข Immutable once deployed
- โข Code is the only truth
- โข Always available (24/7/365)
๐ก Why "Compile" Matters
Before a smart contract can run on the blockchain, it needs to be compiled - converted from human-readable code (like Solidity) into bytecode that the blockchain's virtual machine (EVM) can execute.
๐ The Compilation Process:
1. Write Your First Smart Contract
โ๏ธ Interactive: Contract Code Editor
How Smart Contracts Make Decisions
๐ฏ Conditions: The Brain of Smart Contracts
Every smart contract is built on if/then logic. Think of it like a promise: "IF this happens, THEN do that." The beauty? The blockchain automatically checks these conditions and executes the code when they're met - no human needed!
๐ฑ Real-World Example: Flight Insurance
Contract: "If flight is delayed more than 2 hours, pay passenger $200"
Passenger buys insurance
Contract monitors flight data
Automatic payout if delayed
๐ฅ Why This Is Revolutionary
Traditional Insurance:
- โข File a claim form
- โข Wait days/weeks for review
- โข Provide proof and documents
- โข Hope they approve it
- โข Wait for payment processing
Smart Contract Insurance:
- โ Condition met automatically
- โ Contract executes instantly
- โ Payment in your wallet
- โ Zero paperwork
- โ No trust required
๐ข Types of Conditions
๐ Numeric Conditions
Check values against thresholds
โฐ Time-Based Conditions
Execute after a specific time
โ Boolean Conditions
Check if something is true/false
๐ฅ Ownership Conditions
Verify who's calling the function
2. Test Contract Conditions
๐ก๏ธ Interactive: Insurance Trigger Simulator
Conditions Not Met
Contract is monitoring conditions. Payment will trigger automatically when conditions are met.
Why Smart Contracts Are Different
๐ข The Problem with Traditional Contracts
Traditional contracts are agreements on paper that require humans to enforce. This creates friction, delays, and costs. Think about how many people are involved when you buy a house, get insurance, or send money internationally.
๐ The Hidden Cost: Time & Trust
Manual Verification
Every step needs human review - lawyers read contracts, banks verify identities, auditors check records. This takes days or weeks.
Multiple Intermediaries
Each middleman adds fees and delays. Want to send money abroad? You'll go through: your bank โ SWIFT network โ correspondent bank โ recipient's bank.
Trust Dependencies
You must trust that each party will do their job correctly and honestly. If they don't, you need courts and lawyers to enforce the contract.
โก The Smart Contract Solution
Instant Verification
The blockchain network automatically verifies everything in seconds. No humans needed to check if conditions are met.
Zero Intermediaries
Direct peer-to-peer transactions. Money goes straight from your wallet to the recipient. No banks, no payment processors taking cuts.
Code Is the Authority
The contract executes exactly as written. No one can refuse to follow through. No legal battles needed.
๐ฐ Real Cost Comparison
International Wire Transfer
Escrow Service
Legal Contract
3. Traditional vs Smart Contracts
โ๏ธ Interactive: Process Comparison
Submit claim
Manual review (3-5 days)
Request documents
Verification (1-2 weeks)
Approval process
Payment (3-7 days)
Traditional: Weeks
Manual processes, intermediaries, trust required
Smart: Instant
Automatic execution, no middlemen, trustless
The Cost of Execution: Gas Fees
โฝ What Is Gas?
Gas is the fuel that powers smart contracts on Ethereum (and similar blockchains). Just like your car needs gasoline to run, smart contracts need gas to execute. But instead of burning fuel, you're paying for computational work done by miners/validators.
๐งฎ The Gas Formula
Gas Fee = Gas Units ร Gas Price
Then multiply by ETH price to get USD cost
Gas Units
How much work the contract does (like miles traveled). Simple transfer = 21,000 units. Complex DeFi swap = 200,000+ units.
Gas Price (Gwei)
How much you pay per unit (like price per gallon). Higher price = faster processing. Typical range: 10-200 Gwei.
๐๏ธ Why Do Gas Prices Change?
Network Congestion
When lots of people use the blockchain at once (like during an NFT drop), gas prices spike. Everyone competes to get their transaction processed first.
Supply and Demand
Each block has limited space. If 10,000 transactions compete for 100 spots, miners pick the highest gas payers. It's an auction!
Time of Day
Gas is typically cheaper during off-peak hours (2-8 AM UTC) when fewer people are transacting.
๐ก Why Smart Contracts Cost More Than Simple Transfers
A simple ETH transfer is like sending a text message - quick and cheap. A complex smart contract is like running a full computer program - it requires more computational steps, storage updates, and processing time.
Simple Transfer
21k
gas units
Just moving ETH from A to B
Token Swap
150k
gas units
Multiple contract calls + math
NFT Mint
300k+
gas units
Storage writes + metadata
4. Understanding Gas Fees
โฝ Interactive: Gas Fee Calculator
Estimated Transaction Cost
๐ก Gas fees compensate miners for computational work. More complex contracts cost more to execute.
Smart Contracts as Escrow Services
๐ What Is Escrow?
Imagine buying a used car from a stranger online. You don't want to send money before getting the car, and they don't want to send the car before getting paid. Escrow solves this trust problem by holding the money until both parties fulfill their obligations.
๐๏ธ Traditional Escrow Problems
Expensive Fees
Traditional escrow companies charge 1-3% of the transaction value. For a $10,000 purchase, that's $100-300 just to hold your money!
Slow Processing
Money release can take 3-10 business days after conditions are met. More waiting, more phone calls, more frustration.
Trust the Escrow Agent
You're just moving the trust problem. Now you must trust the escrow company not to lose your money, go bankrupt, or make mistakes.
โ Smart Contract Escrow Solution
Minimal Fees
Just pay gas fees (typically $5-50). No percentage-based fees. The smart contract doesn't charge rent for holding your funds!
Instant Release
When conditions are met, funds transfer in the next block (~15 seconds). No waiting for business hours or manual approval.
Trustless Execution
No humans involved. The code is public and auditable. If conditions are met, funds release automatically. No one can stop it or steal it.
๐ How Smart Escrow Works
Buyer Deposits Funds
Buyer sends payment to the smart contract. Money is locked - neither buyer nor seller can access it yet.
Seller Delivers
Seller marks item as delivered by calling a function in the contract. This is recorded on-chain.
Buyer Confirms
Buyer receives item and approves the transaction. This triggers the contract's release condition.
Automatic Payment
Contract automatically sends funds to seller. No button to click, no form to fill. It just happens.
5. Smart Contract Escrow
๐ Interactive: Escrow Service
Buyer
Funds locked in escrow
Smart Contract
โณ Awaiting delivery...
Seller
Product to deliver
๐ก How it works: Buyer's funds are locked in the smart contract. When seller delivers and buyer approves, funds automatically release. No third party needed!
Multi-Signature Security
โ๏ธ What Are Multi-Sig Wallets?
Think of a multi-signature (multi-sig) wallet as a bank vault that requires multiple keys to open. Instead of one person having complete control, a group must agree before funds can be moved. It's like requiring 2 out of 3 executives to approve a major company expense.
๐ข Real-World Use Cases
DAO Treasury Management
DAOs use multi-sig wallets to protect millions in treasury funds. Example: Require 5 of 9 council members to approve withdrawals.
Family Inheritance
Parents set up 2-of-3 wallet with themselves and trusted executor. If something happens, inheritance is secure but accessible.
Company Operations
Require CEO + CFO to approve large payments. Prevents rogue employee or hacked account from draining funds.
Business Partnership
Three co-founders require 2-of-3 approval for major expenses. Protects against single founder misusing company funds.
โ ๏ธ The Single Point of Failure Problem
With a regular wallet (single-sig), one private key controls everything. This creates serious risks:
๐ Key Loss
Lose your key? Your funds are gone forever. No password reset button.
๐ฃ Phishing Attack
One mistake, one malicious signature, and attackers drain everything.
๐จ $5 Wrench Attack
Physical threats force you to transfer funds. Multi-sig protects against coercion.
๐ก๏ธ How Multi-Sig Provides Security
No Single Point of Failure
Compromise one key? Funds are still safe. Attacker needs to breach multiple independent parties simultaneously.
Collaborative Decision Making
Important decisions require consensus. One person can't act alone, reducing impulsive or malicious actions.
Recovery Options
Lose one key? Use the others to move funds to a new multi-sig. Unlike single-sig where loss = permanent loss.
๐ Popular configurations: 2-of-3 (personal security), 3-of-5 (small team), 5-of-9 (DAO governance), 4-of-7 (large organizations)
6. Multi-Signature Wallets
โ๏ธ Interactive: Multi-Sig Authorization
Transaction: Send 100 ETH to Project Treasury
Requires 2 of 3 signatures to execute
Signer 1
0x0f029292...
Signer 2
0x2e2e10ad...
Signer 3
0xff2883bc...
Status: 0/2 Signatures
How Token Transfers Work
๐ช What Are Tokens?
Tokens are programmable digital assets created by smart contracts. Unlike ETH (which is native to Ethereum), tokens like USDC, DAI, or UNI exist because a smart contract tracks who owns how many. Think of it as a giant spreadsheet managed by code instead of a company.
๐ The ERC-20 Standard
Most tokens follow the ERC-20 standard - a set of rules that ensures all tokens work the same way. This is why your wallet can hold thousands of different tokens without special code for each one.
Required Functions
- โข transfer() - Send tokens
- โข balanceOf() - Check balance
- โข approve() - Allow spending
- โข totalSupply() - Get total tokens
Why Standards Matter
- โข Wallets can support all ERC-20s
- โข Exchanges can list new tokens easily
- โข DeFi protocols are composable
- โข Developers save time
โก What Happens During a Transfer
Balance Check
Smart contract verifies you have enough tokens. If not, transaction reverts instantly (you don't lose gas for failed checks!).
Update Balances
Contract subtracts tokens from your balance and adds them to recipient's balance. This happens atomically - either both updates succeed or neither does.
Emit Event
Contract emits a Transfer event that wallets and block explorers can track. This is how your wallet knows to update your balance display.
๐ Atomic Transfers: All or Nothing
One of the most powerful features of smart contract transfers is atomicity. Either the entire transaction succeeds, or it fails completely with no partial state changes. You can never end up in a situation where tokens leave your wallet but don't arrive at the destination.
โ Traditional Banking
- โข Money can get "stuck in transit"
- โข Failed transfers may still deduct
- โข Reversals take days to process
- โข Different systems may desync
โ Smart Contract Transfers
- โข Instant finality (seconds)
- โข Impossible to have partial execution
- โข Automatic rollback if error occurs
- โข Single source of truth (blockchain)
7. Token Transfer Simulation
๐ธ Interactive: Send Tokens
๐ค Your Wallet
Available balance
๐ฏ Recipient Wallet
Current balance
โก Instant execution: Smart contracts verify balance and execute transfer atomically. No bank processing time!
Smart Contract Security Risks
โ ๏ธ Why Security Is Critical
Remember: smart contracts are immutable. Once deployed, you can't patch bugs like traditional software. If there's a vulnerability, attackers can exploit it forever (or until funds are drained). Billions of dollars have been stolen due to smart contract bugs.
๐ Historic Hacks
The DAO Hack (2016)
$60M stolenReentrancy attack drained funds by calling withdraw function recursively before balance updated. Led to Ethereum hard fork.
Poly Network (2021)
$611M stolenCross-chain bridge exploit. Attacker called privileged functions without proper access control checks.
Ronin Bridge (2022)
$625M stolenMulti-sig compromise. Attackers gained control of enough validator keys to approve malicious withdrawals.
๐ Common Vulnerabilities
Reentrancy Attacks
Attacker calls a function that calls back into the contract before the first call finishes, potentially withdrawing funds multiple times.
โ Update balance AFTER sending funds
โ Update balance BEFORE sending funds
Access Control Issues
Functions that should be restricted to owner/admin are accidentally public, allowing anyone to call them.
โ function withdraw() public
โ function withdraw() onlyOwner
Integer Overflow/Underflow
Math operations wrap around when exceeding max/min values (Solidity 0.8+ fixed this with automatic checks).
255 + 1 = 0 (overflow)
0 - 1 = 255 (underflow)
Bad Randomness
Using block.timestamp or block.number as random source. Miners can manipulate these values!
โ uint random = block.timestamp % 100
โ Use Chainlink VRF for true randomness
๐ก๏ธ Security Best Practices
โ Professional Audits
Hire security firms to review code before mainnet deployment. Cost: $5k-100k+ but worth it for high-value contracts.
โ Use Battle-Tested Libraries
OpenZeppelin contracts are audited and used by thousands of projects. Don't reinvent the wheel.
โ Bug Bounty Programs
Pay white-hat hackers to find vulnerabilities before bad actors do. Immunefi hosts many bounties.
โ Automated Testing
Write comprehensive unit tests. Use tools like Slither, Mythril, and Echidna for static analysis.
8. Smart Contract Security
๐ Interactive: Vulnerability Scanner
Smart Contract Events and Monitoring
๐ก What Are Events?
Events are signals that smart contracts emit when important actions occur. Think of them as a contract's way of talking to the outside world. Without events, you'd have to constantly query the blockchain to check if something happened - like refreshing your email every second instead of getting notifications.
๐ Why Events Matter
Real-Time Notifications
dApps listen for events to update UI instantly. When someone sends you tokens, your wallet detects the Transfer event and shows the new balance.
Historical Data
Events are logged permanently on-chain. Block explorers and analytics tools use them to show transaction history and activity graphs.
Gas Efficiency
Events are much cheaper than storing data in contract storage. Use them for data you don't need to access from other contracts.
Off-Chain Integration
Backend services listen for events to trigger actions - like sending email confirmations or updating databases when certain transactions occur.
๐ How Events Work
Contract Emits Event
When a function executes, it can emit events with relevant data. Example: emit Transfer(from, to, amount)
Stored in Transaction Receipt
Events are added to the transaction receipt (not contract storage), making them queryable but not accessible from other smart contracts.
Indexed for Fast Searching
Up to 3 parameters can be "indexed", allowing efficient filtering. Find all transfers TO a specific address, or FROM a specific address.
Applications Listen and React
Your wallet, block explorers, and dApps subscribe to relevant events and update their interfaces when events are detected.
๐ฏ Common Event Use Cases
Token Transfers
Every ERC-20 token emits a Transfer(from, to, value) event for every transfer. This is how your wallet knows your balance changed!
Example: USDC transfer from Alice to Bob
Transfer(0xAlice..., 0xBob..., 1000000)
NFT Minting & Sales
NFT marketplaces listen for Transfer events to update listings and Sale events to show recent activity.
Example: NFT #1337 sold for 2 ETH
Sale(tokenId: 1337, price: 2000000000000000000, buyer: 0x...)
DAO Governance
DAOs emit events for proposals, votes, and executions. Governance dashboards subscribe to these to show voting activity.
Example: Proposal #42 passed with 75% approval
ProposalExecuted(proposalId: 42, votesFor: 750000, votesAgainst: 250000)
9. Contract Event Monitoring
๐ Interactive: Live Event Log
Recent Contract Events
0 events๐ก Events: Smart contracts emit events for important actions, allowing dApps to track contract activity in real-time.
๐ฏ Key Takeaways
Automation & Trust
Smart contracts execute automatically when conditions are met, eliminating intermediaries and the need for trust.
Immutable Code
Once deployed, smart contracts cannot be changed. This ensures transparency but requires careful security auditing.
Cost Efficiency
Eliminate lawyers, banks, and other middlemen. Gas fees are typically lower than traditional transaction costs.
Real-World Applications
DeFi, NFTs, DAOs, supply chain, insurance, real estate, and countless other use cases are powered by smart contracts.
Security Matters
Smart contract bugs can be catastrophic. Always audit code, use established patterns, and test extensively.
The Future
Smart contracts are building the foundation for Web3, enabling truly decentralized applications and services.