Ethereum Smart Contracts Explained: Programmable Blockchain
Bitcoin is digital money—it records transactions immutably. Ethereum does something fundamentally different: it's a global computer running code on blockchains. Instead of only recording "Alice sent Bob 1 Bitcoin," Ethereum records transactions AND executes arbitrary code in response. This code, called smart contracts, can create entirely new possibilities in finance, identity, ownership, and coordination.
Smart contracts are powerful and revolutionary but also risky. Code bugs become permanent and costly. Misunderstood code can cause enormous financial losses. Understanding what smart contracts are, what they enable, and their fundamental limitations is essential for participating in modern cryptocurrency.
Quick definition: A smart contract is a self-executing program deployed on a blockchain that automatically enforces the terms of an agreement when conditions are met, with no intermediary required.
Key Takeaways
- Code runs on blockchain: Instead of trusting an intermediary, code enforces the agreement automatically
- Deterministic execution: Every node runs the same code and gets the same result (consensus requires this)
- Immutable: Once deployed, code cannot be changed (except with upgradeable contracts, which add complexity)
- Trustless execution: You don't need to trust the creator or an intermediary; the code is the law
- State is permanent: Unlike traditional software, smart contract state is recorded forever on the blockchain
- Gas costs: Running code costs money (Ethereum "gas" fees); more complex code costs more
- Code bugs are permanent: A vulnerable contract cannot be "patched"; it executes forever as written
- Network effect: Ethereum's large developer community creates more applications, more liquidity, more value
Bitcoin vs. Ethereum: Two Different Blockchains, Two Different Philosophies
Bitcoin:
- Purpose: Store and transfer value (digital money)
- Programming: Very limited (script language for basic conditions only)
- Transactions per second: ~7
- Network value: Network for a narrow purpose (payment)
- Philosophy: "Sound money, censorship-resistant"
Example Bitcoin transaction:
IF (you know this secret) THEN (you can spend this Bitcoin)
Ethereum:
- Purpose: Store and transfer value AND run arbitrary programs
- Programming: Full Turing-complete language (Solidity)
- Transactions per second: ~30 (pre-merge), unlimited in theory
- Network value: Infrastructure for thousands of applications
- Philosophy: "World computer, program everything"
Example Ethereum transaction:
IF (price of Bitcoin exceeds $50,000)
AND (user sends 1 Ether)
AND (30 days have passed)
THEN (transfer ownership to user)
AND (burn 10% of fees)
AND (emit event notifying listeners)
How Ethereum Works: From Transaction to Code Execution
Step 1: You deploy a smart contract
You write code (in Solidity language) that specifies rules:
pragma solidity ^0.8.0;
contract SimplePayment {
mapping(address => uint) balances;
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function withdraw(uint amount) public {
require(balances[msg.sender] >= amount);
balances[msg.sender] -= amount;
payable(msg.sender).transfer(amount);
}
}
You send a transaction containing this code to Ethereum. Miners include it in a block. The contract is deployed to a specific address (like: 0x3f5CE5FBFe3E9af3971dD820d23cb72f4B242D7a). It lives on Ethereum forever.
Step 2: Users interact with the contract
Someone sends a transaction: "Call the deposit() function of the contract at address 0x3f5... and send 1 Ether."
Step 3: Nodes execute the code
Every node on Ethereum's network receives this transaction. They all run the code:
- Check if the transaction is valid
- Execute the
deposit()function - Update the contract's state (
balances[sender] += 1 ether) - Record the result in the blockchain
Step 4: Consensus
After some nodes execute the code, a validator (post-2022) or miner (pre-2022) creates a block containing this transaction. Other nodes verify:
- Did they execute the same code?
- Did they get the same state change?
If the majority agree, the block is added and the code execution is permanent.
Real-World Smart Contract Applications
Decentralized Finance (DeFi):
Uniswap (already discussed) is a smart contract. People deposit tokens into liquidity pools. Smart contracts automatically handle:
- Swapping tokens
- Calculating prices
- Distributing fees
- Tracking LP shares
Total value locked in DeFi: ~$50 billion (2024) Annual transaction volume: ~$1 trillion
NFTs and Ownership:
Smart contracts track ownership of digital items:
contract NFT {
mapping(uint => address) nftOwner;
function transfer(uint nftId, address newOwner) public {
require(nftOwner[nftId] == msg.sender);
nftOwner[nftId] = newOwner;
}
}
Artists can mint digital works that prove ownership cryptographically. The contract enforces royalties (10% of every future sale goes to the artist automatically).
Lending and Borrowing:
Compound (smart contract on Ethereum) lets users:
- Deposit USDC and earn 4% APY
- Borrow Ethereum by depositing Bitcoin as collateral
The smart contract:
- Manages collateral ratios
- Liquidates loans if price drops too much
- Distributes interest automatically
Billions in crypto are lent through these contracts.
Insurance:
Nexus Mutual (Ethereum smart contract) lets people:
- Buy insurance against smart contract hacks
- Stake crypto to underwrite policies
- Automatically pay claims when hacks occur
DAOs (Decentralized Autonomous Organizations):
Entire organizations run via smart contracts:
- MakerDAO manages the DAI stablecoin (~$5 billion in supply)
- Uniswap is governed by UNI token holders
- Decisions are made by code-enforced voting
The Vending Machine Analogy
A vending machine is a simple smart contract:
IF (you insert $2) THEN (dispense snack)
The rules are:
- Hardcoded (you can't change them; the machine enforces them)
- Deterministic (everyone gets the same snack for $2)
- Trustless (you don't need to trust the vending machine company; the machine's rules are the law)
Ethereum contracts work similarly:
- Code enforces the rules
- Everyone running the code gets the same result
- No company or intermediary can cheat
Smart Contract Limitations and Risks
Risk #1: Code Bugs
If code has a bug, it executes perfectly—just wrong. Classic example:
function transfer(uint amount) public {
balances[msg.sender] -= amount; // OOPS: should be +=
balances[recipient] += amount;
}
This code would deduct money from the sender AND the recipient (double-spending). If deployed, this runs forever. There's no "undo."
Famous example: The DAO hack (2016)
The DAO was a smart contract managing $150 million in investor funds. Code had a reentrancy bug:
- Attacker called
withdraw() - Smart contract sent Ether to attacker's address
- Attacker's code immediately called
withdraw()again - Smart contract didn't update balance yet, so attacker could withdraw again
- Attacker repeated this 1 million times, draining $50 million
The Ethereum community's response:
- They performed a "hard fork" (essentially rewriting Ethereum's history)
- The fork reversed all transactions from the hack
- This demonstrated that even immutable blockchains can be rolled back if the community agrees
- Some users rejected the fork, creating Ethereum Classic (the original chain)
Risk #2: Design Flaws
Code can be bug-free but still do something unintended due to poor design.
Example: A contract offers "risk-free 100% APY returns." The math works:
- Deposit $10,000
- Earn $10,000/year
But where does the yield come from? The contract is burning through capital. After 1 year, there's no money left. This is a Ponzi scheme, technically executed by code perfectly.
Risk #3: Oracle Risk
Smart contracts can't access external data directly (Bitcoin price, weather, sports results). They depend on "oracles"—external services providing data.
Example:
if (chainlinkOracle.getPrice("BTC") > $50,000) {
// do something
}
If the oracle is hacked, delayed, or lying, the smart contract makes wrong decisions. This is called "oracle risk."
Risk #4: Regulatory Risk
Code doesn't care about laws, but humans do. A smart contract might:
- Illegally transfer assets
- Violate sanctions
- Enable money laundering
- Operate as an unregistered security
The code might be legal, but the creator could face legal consequences.
Smart Contract Audits: Reducing but Not Eliminating Risk
Before deploying large contracts, projects hire security firms to audit the code:
What audits check:
- Logic errors (off-by-one errors, wrong operators)
- Security vulnerabilities (reentrancy, overflow/underflow)
- Gas efficiency
- Best practice violations
Cost: $50,000-$500,000 for comprehensive audits
Reality: Even audited code has been hacked
Example: Ronin Bridge (audited, $625 million theft). Audits reduce risk from maybe 10% to 1%, but don't eliminate it.
Gas Costs: The Price of Running Code
Running code on Ethereum costs money (measured in "gas"). Each operation has a cost:
Simple operation (add numbers): 3 gas
Read from storage: 200 gas
Write to storage: 20,000 gas
Create new contract: 32,000 gas
When you deploy a contract or call a function, you pay:
Gas Used × Gas Price = Total Fee
Example:
- Swap 1,000 USDC for ETH on Uniswap
- Gas used: 100,000
- Gas price: 50 Gwei (during normal congestion)
- Total fee: 100,000 × 50 = 5,000,000 Gwei = 0.005 ETH = ~$15
This means:
- Simple transactions: cheap ($1-5)
- Complex transactions: expensive ($10-100)
- During network congestion: very expensive ($100-1,000)
This creates incentives for efficient code and discourages spam.
Solidity: The Language of Smart Contracts
Solidity is the primary language for writing Ethereum smart contracts. It's similar to JavaScript but:
- Type-safe (variables have specific types)
- Compiled to bytecode (not interpreted)
- Runs on Ethereum Virtual Machine (EVM)
pragma solidity ^0.8.0;
contract MyContract {
// State variables (persistent storage)
mapping(address => uint) public balances;
uint public totalSupply;
// Functions (executable code)
function deposit() public payable {
balances[msg.sender] += msg.value;
totalSupply += msg.value;
}
function getBalance(address user) public view returns (uint) {
return balances[user];
}
}
Alternative languages:
- Vyper: Python-like syntax, emphasis on security
- Rust: Used for contracts on Solana blockchain
- Move: Language designed by Facebook for Libra/Diem
Ethereum 2.0: From Proof of Work to Proof of Stake
Ethereum originally used Proof of Work (mining):
- Miners competed to solve puzzles
- Blocks took ~15 seconds
- Energy consumption: ~150 TWh/year
- Transaction fees: $5-200 depending on congestion
Ethereum 2.0 (completed 2022) uses Proof of Stake:
- Validators stake 32 ETH to become block producers
- Blocks take ~12 seconds
- Energy consumption: 99.95% lower (~0.3 TWh/year)
- Transaction fees: similar but more predictable
This change was controversial:
- Pro: Massively lower energy use, faster transactions
- Con: Validator concentration, potential centralization
Common Mistakes About Smart Contracts
Mistake #1: "Code is law, so smart contracts enforce fairness"
Code enforces the rules, but only the rules the programmer wrote. If the programmer writes unfair rules, the code executes them perfectly. "Code is law" is accurate but doesn't guarantee justice.
Mistake #2: "Audited code is safe"
Audits reduce risk but don't guarantee safety. Some audited contracts have been hacked. Audits check for known vulnerabilities; novel attacks might slip through.
Mistake #3: "Smart contracts replace courts"
Contracts can enforce agreements automatically, but what if disputes arise? If two parties signed a contract expecting different terms, who decides the truth? Ultimately, courts still matter.
Mistake #4: "I can call any function on any contract without risk"
False. Calling a malicious function could:
- Transfer your tokens to the attacker
- Drain your wallet
- Exploit your browser's local storage
Always verify you're interacting with the correct address.
Mistake #5: "Decentralized means safe"
A decentralized smart contract has no central authority to shut it down, but it can still be insecure. Decentralization and security are different properties.
FAQ: Smart Contracts
Q1: Can a smart contract be updated after deployment?
Not usually. Once deployed, code is immutable. However:
- Some contracts are "upgradeable" (using proxy patterns), adding complexity
- If a major bug is found, the community can perform a hard fork (reversing transactions)
- Hard forks require majority consensus and can cause controversy
Q2: How do smart contracts enforce agreements in the real world?
They don't directly. A contract can enforce cryptocurrency transfers, but what about physical goods? If you buy a house using a smart contract, the smart contract transfers the deed (digitized), but physical delivery happens outside the contract.
Q3: Can I sue if a smart contract harms me?
Maybe. You could potentially sue the creator if:
- They misrepresented what the code does
- They were negligent in deploying buggy code
- They intended to defraud you
But suing the code itself doesn't work; code has no legal personhood.
Q4: What's the difference between a smart contract and a blockchain application?
- Smart contract: The code deployed on-chain
- Blockchain application: The full application including user interface, servers, and smart contracts
Uniswap is a blockchain application. The smart contract is one part of it.
Q5: Can quantum computers break smart contracts?
Yes, theoretically. A sufficiently powerful quantum computer could break the cryptographic assumptions underlying Ethereum. This is 10+ years away. The community is researching quantum-resistant cryptography.
Related Concepts
- Blockchain Explained — How blockchain enables smart contracts
- Decentralized Exchanges — Smart contracts handling trading
- DeFi for Beginners — The ecosystem built on smart contracts
- Stablecoins — Smart contracts creating stable value
- Common Scams — Smart contract-based fraud
- Transaction Settlement — How smart contracts finalize
Summary
Ethereum smart contracts enable code to run on blockchains, creating trustless execution of agreements. Instead of trusting intermediaries, rules encoded in smart contracts are enforced automatically by thousands of nodes. This enables new applications in finance, identity, ownership, and coordination. However, smart contracts are not magical. Bugs become permanent and costly, code can be misunderstood, and the code itself cannot enforce real-world agreements. Smart contracts have created a multi-trillion-dollar ecosystem of applications, but they remain experimental technology with significant risks.
Deeper coverage in Book 18 — Cryptocurrency for Beginners.