Ethereum — Smart Contracts, DeFi, and the Rollup-Centric World
From Vitalik Buterin's 2013 whitepaper to the settlement layer of decentralized finance: how the EVM, Solidity, the Merge to Proof-of-Stake, and a rollup-centric scaling roadmap combine to create the programmable blockchain. Covers gas mechanics, EIP-1559, Casper FFG, ZK vs optimistic rollups, EIP-4844, and the DeFi primitives reshaping finance.
1. Overview
In late 2013, Vitalik Buterin proposed a general-purpose blockchain that treats smart contracts as first-class citizens. Where Bitcoin's Script is deliberately limited, Ethereum's EVM is a complete computational environment — any program that can be expressed as a finite state machine can be deployed and run on-chain, with execution guaranteed by every node independently.
The conceptual shift: Bitcoin's blockchain is a ledger of ownership. Ethereum's blockchain is a ledger of state — including the state of arbitrary programs.
Account model
Ethereum uses an account model rather than Bitcoin's UTXO model. There are two account types:
What "trustless" contracts actually means
A smart contract is not "trusted" in the sense of being correct or bug-free. It is "trustless" in the sense that its execution is deterministic and transparent: anyone can read the bytecode and predict exactly what will happen given any inputs, without trusting the deployer to execute it honestly. The Ethereum network guarantees the code runs exactly as written — no more, no less.
The "world computer" framing was powerful but misleading. Ethereum is not a fast computer — it processes ~15 transactions/second at L1. It is better understood as a shared notary: an expensive but highly credible record of state changes, with the property that no single party controls its output. The actual computation happens off-chain (in L2 rollups). L1 is used for settlement and dispute resolution.
2. The EVM
The Ethereum Virtual Machine is a 256-bit stack machine. Every full node runs it identically — determinism is guaranteed by the specification (the Yellow Paper, or its more readable successor, the Execution Client Specs). A transaction that calls a contract triggers EVM execution; the resulting state change is included in the block.
Memory regions
| Region | Size | Persistence | Cost |
|---|---|---|---|
| Stack | Max 1024 items × 256 bits | Execution-scoped | ~3 gas per operation |
| Memory | Dynamically allocated bytes | Execution-scoped (zeroed per call) | Quadratic: cheap when small, expensive when large |
| Storage | 2²⁵⁶ slots × 32 bytes per contract | Permanent (survives across transactions) | SSTORE: 20,000 gas (new slot), 2,900 gas (update); most expensive EVM operation |
| Calldata | Varies; passed with transaction | Read-only within execution | 4 gas/zero byte, 16 gas/non-zero byte (post-EIP-2028) |
| Returndata | Varies; output from subcall | Available after CALL/STATICCALL returns | No additional cost beyond reading |
| Code | Fixed at deploy time | Immutable (unless proxy pattern) | CODESIZE, CODECOPY opcodes |
Gas model
Every EVM opcode consumes a fixed (or dynamic) number of gas units. Gas is purchased at the current base fee rate in ETH. This prevents infinite loops and prices computation proportionally to its cost to network validators.
Why 21,000 base fee for a simple transfer? Every transaction incurs fixed overhead: signature verification, nonce check, sender balance check, updating sender and recipient state, and adding the receipt to the trie. The 21,000 gas covers this minimum overhead even with zero calldata and no contract execution.
EIP-1559: base fee + priority tip + burn
Before EIP-1559 (August 2021), gas pricing was a first-price auction — users bid arbitrarily high to get included. EIP-1559 replaced this with a protocol-determined base fee:
The deflationary mechanism: in periods of high network activity, ETH issuance (validator rewards) < ETH burned (base fees). The supply shrinks. In low-activity periods, issuance > burn and supply grows slightly. The supply dynamics depend on network usage, making ETH fundamentally different from Bitcoin's predictable issuance schedule.
Key opcodes with gas costs
| Opcode | Gas (Berlin/Shanghai) | Operation |
|---|---|---|
ADD, MUL, SUB | 3 | Basic arithmetic on 256-bit stack items |
PUSH1 … PUSH32 | 3 | Push N-byte constant onto stack |
MLOAD / MSTORE | 3 + memory expansion | Load/store 32 bytes to/from memory |
SLOAD | 2,100 (cold), 100 (warm) | Load 32-byte value from contract storage |
SSTORE | 20,000 (zero→nonzero), 2,900 (update), 100 (same value) | Write 32-byte value to contract storage |
CALL | 2,600 (cold target) + value transfer overhead | Call external contract |
CREATE | 32,000 + init code cost | Deploy new contract |
KECCAK256 | 30 + 6/word | Keccak-256 hash of memory range |
LOG0…LOG4 | 375 + 375/topic + 8/byte | Emit event (stored in receipt, not state) |
SELFDESTRUCT | 5,000 (+ 25,000 if creating new account) | Destroy contract, send ETH to target; deprecated in EIP-6049 |
Interactive: EVM stack execution trace
Step through the execution of PUSH1 3, PUSH1 4, ADD, PUSH1 0, MSTORE — a minimal EVM program that computes 3+4 and stores the result at memory offset 0.
Transaction lifecycle
- User signs transaction (nonce, to, value, data, gas params, chainId via EIP-155)
- Transaction broadcast to peer-to-peer network; each node validates signature and nonce, adds to mempool
- Block proposer (PoS validator) selects transactions from mempool; EIP-1559: all must pay ≥ base_fee
- EVM executes each transaction in order; state changes are buffered in a write-ahead journal
- If execution reverts (OOG, REVERT), state changes are discarded but gas is consumed up to the OOG point
- Successful transactions are committed; state root, receipts root, bloom filter are computed and placed in the block header
- Block is gossiped; other validators attest to it; after 2 epochs (~12.8 min) block is finalized by Casper FFG
3. Solidity in practice
Solidity is not the only language that compiles to EVM bytecode (see: Vyper, Yul, Fe, Huff) but it is the dominant choice (~90% of deployed contracts). This section covers design patterns, security pitfalls, and gas optimization — not a syntax tutorial.
ABI encoding
Contracts interact via the ABI (Application Binary Interface). A function call is encoded as: first 4 bytes = keccak256(function signature)[0:4], followed by ABI-encoded arguments. The 4-byte selector enables compact routing — each contract can expose hundreds of functions using a simple dispatch table.
Key design patterns
| Pattern | Purpose | Mechanism |
|---|---|---|
| Proxy (UUPS/Transparent) | Upgradeable contracts — logic can be replaced without changing the address | delegatecall from proxy to implementation; proxy stores state, implementation provides logic. Storage layout must remain identical. |
| Ownable | Administrative access control | Single owner address with modifier onlyOwner. Simple but centralized — often replaced by multisig (Gnosis Safe) or DAO governance. |
| Checks-Effects-Interactions | Prevent reentrancy attacks | Always update internal state BEFORE making external calls. Prevents re-entry into the function with stale state. |
| Pull over Push | Avoid DoS via reverting recipients | Instead of sending ETH to all recipients (any one failure blocks all), let each recipient pull their own funds. |
| Factory | Deploy many instances of a contract | Factory contract calls CREATE or CREATE2. CREATE2 enables counterfactual deployment — predict address before deployment using salt. |
Events and logs
Events (LOG0–LOG4 opcodes) are the primary off-chain communication mechanism. Log data is stored in the transaction receipt and indexed in Bloom filters in the block header — not in the Merkle state trie. This makes them ~50× cheaper than storage for data you only need to query off-chain. The Graph Protocol indexes Ethereum events to power decentralized subgraphs used by Uniswap, Aave, and every major DeFi protocol.
Gas optimization techniques
| Technique | Saving | Explanation |
|---|---|---|
| Pack struct fields | Up to 10× on reads | EVM storage slots are 32 bytes. Multiple small values (uint128, uint64, bool) packed into one slot use one SLOAD instead of N. |
Use calldata not memory | 16 gas/byte vs memory copy | For function parameters that are only read (not modified), declare as calldata — avoids copying to memory. |
unchecked { } blocks | 3× faster arithmetic | Solidity 0.8+ adds overflow checks by default (~3 gas each). When you know overflow can't happen (loop counter), use unchecked. |
| Cache storage in memory | 2,000+ gas per repeated read | uint256 val = myStorage; — one SLOAD (2100 gas). Reading myStorage in a loop = N × 100 gas (warm) vs 1 copy. Load once, read many times. |
| Use custom errors | ~100 gas per revert | Custom errors error Unauthorized() are cheaper than revert strings — no string encoding in bytecode. |
Avoid address.transfer() | Future-proof | Hard-codes 2300 gas stipend — breaks with any EVM gas cost repricing. Use call{value: amount}("") with checks-effects-interactions instead. |
Security checklist
Reentrancy — The DAO hack ($60M, 2016). External call before state update lets attacker recursively drain funds. Fix: Checks-Effects-Interactions pattern, or ReentrancyGuard modifier.
Integer overflow (pre-0.8) — BEC token hack ($900M). Solidity <0.8 silently wraps on overflow. Fix: use SafeMath or Solidity ≥0.8.
tx.origin authentication — Using tx.origin (original EOA) instead of msg.sender (immediate caller) enables phishing. Fix: always use msg.sender.
block.timestamp manipulation — Miners/validators can manipulate timestamp by ~15 seconds. Do not use for randomness or high-precision timing.
Price oracle manipulation — Spot prices on AMMs can be manipulated in a single transaction (flash loan). Fix: use TWAP (time-weighted average price) over multiple blocks.
▶ Proxy pattern: delegatecall mechanics (pseudocode)
# Transparent proxy pattern
# Proxy contract (stores all state)
contract Proxy:
address implementation # slot 0 — must match implementation's slot layout
address admin # slot 1
fallback():
# Forward all calls to implementation using delegatecall
# delegatecall: runs implementation code but with proxy's storage/address
result = delegatecall(
target=self.implementation,
calldata=msg.data,
gas=gasleft()
)
return result
# Implementation contract (provides logic, no state)
contract ImplementationV2:
uint256 counter # must be at same slot as in V1!
function increment():
self.counter += 1 # modifies PROXY's storage, not own
# Upgrade
proxy.upgradeTo(ImplementationV2_address)
# All subsequent calls to proxy now use V2 logic
# Storage state is preserved — only the code changes
# Storage collision danger:
# If V2 declares a new variable BEFORE counter, it overwrites
# a different slot than V1 expected — SILENT data corruption
4. The Merge and Proof-of-Stake
On September 15, 2022, Ethereum switched from Proof-of-Work to Proof-of-Stake in a live network upgrade called The Merge — one of the most complex protocol upgrades in blockchain history. The PoW execution chain was merged with the PoS Beacon Chain (launched December 1, 2020).
Motivations: (1) eliminate ~99.9% of Ethereum's energy consumption; (2) reduce ETH issuance from ~13,000 ETH/day to ~1,700 ETH/day; (3) lay groundwork for sharding and rollup-centric scaling.
How Gasper works
Gasper is the combination of two consensus mechanisms:
Validator lifecycle
| Stage | Condition | Detail |
|---|---|---|
| Deposit | 32 ETH sent to deposit contract | Generates BLS key pair; deposit included in beacon chain state |
| Activation queue | Up to several weeks when demand is high | Limited activation rate (churn limit) prevents rapid validator influx from destabilizing committee selection |
| Active | Proposing and attesting each epoch | Earn ~4–5% APR from issuance + MEV tips; must maintain uptime |
| Inactivity leak | Offline for >4 epochs during non-finality | Balance gradually depleted — forces non-participating stake offline to allow remaining 2/3 to achieve finality |
| Slashing | Double-vote or surround-vote detected | Immediate ≥1/32 penalty, 36-day exit queue, correlation penalty proportional to % of validators slashed simultaneously |
| Voluntary exit | Validator submits exit message | Exit queue; minimum 256 epochs withdrawal delay after exit; principal unlocked after Shanghai upgrade (April 2023) |
Slashing conditions
- Double vote (equivocation) — proposing two different blocks for the same slot, or attesting to two different checkpoint pairs in the same epoch
- Surround vote — attesting to a pair (source, target) that "surrounds" a previous attestation — a more subtle form of attempting to rewrite finalized history
These are the only two slashable offenses. Being offline (missing attestations) is penalized via inactivity leak but is not slashable — the protocol distinguishes between honest failure (crash) and malicious behavior (equivocation).
Issuance vs. burn: when is ETH deflationary?
Post-Merge ETH dynamics (approximate, 2025 numbers):
- Validator issuance: ~2,600 ETH/day (with ~1M+ validators)
- EIP-1559 burn: variable, ~500–3,000 ETH/day depending on base fee
- ETH is net deflationary when base_fee > ~15 gwei continuously (burn > issuance)
- At peak DeFi activity (base fee ~100+ gwei), ETH burns faster than it is issued by 5–10×
5. The Rollup-Centric Roadmap
Ethereum L1 processes ~15 tx/s. Visa processes ~24,000 tx/s. The scaling gap is 1,600×. The Ethereum core developer community settled on a specific strategy: scale via rollups (Layer 2), not by increasing L1 block size. L1 remains a high-security settlement and data availability layer; rollups provide user-facing throughput.
Optimistic rollups
Optimistic rollups assume transactions are valid by default (optimistically) and post compressed transaction data to L1. Validity is enforced by a 7-day challenge period during which anyone can submit a fraud proof showing a specific transaction was invalid.
ZK rollups
ZK rollups generate a cryptographic validity proof (ZK-SNARK or ZK-STARK) that mathematically proves the state transition is correct. L1 verifies this proof — no need for a challenge period. Withdrawals to L1 can be instant (once the proof is verified).
| Type | EVM compatibility | Proof system | Examples |
|---|---|---|---|
| Type 1 | Fully EVM-equivalent (hash-for-hash identical) | ZK proof of actual EVM execution | Taiko; theoretical ideal |
| Type 2 | EVM-equivalent (same behavior, slightly different internals) | ZK proof of EVM-like VM | Scroll, Polygon zkEVM |
| Type 3 | Almost EVM-equivalent (minor incompatibilities) | Modified EVM for proof efficiency | Polygon zkEVM v1, early zkSync Era |
| Type 4 | High-level language compatible (compiles to different VM) | ZK proof of native VM (Cairo) | StarkNet (Cairo VM), zkSync (LLVM-based) |
The tradeoff: Type 1 maximizes compatibility but generating ZK proofs of full EVM execution is enormously computationally expensive. Type 4 breaks compatibility but enables much faster proof generation and potentially better performance.
EIP-4844: proto-danksharding
Activated March 2024. Introduces blob transactions — a new transaction type that carries 128 KB data blobs that are stored by consensus nodes for ~18 days (not forever) and are NOT accessible to the EVM (only their commitments are). This creates a separate fee market for rollup data with a target of 3 blobs per block.
Impact: rollup data costs dropped by ~90% immediately after activation. Arbitrum, Optimism, Base, and zkSync all reduced L2 fees from ~$0.10–1.00 to ~$0.001–0.01 per transaction within days.
EIP-4844 is the first step. Full danksharding will increase blob capacity to 64 blobs/block (~8 MB/block). Combined with Data Availability Sampling (DAS) — where light clients verify that blobs are available without downloading them — the target is ~1.3 GB/block of DA capacity, sufficient to support thousands of rollups with millions of transactions per second in aggregate.
Interactive: L1 vs L2 fee comparison
Adjust the base fee slider to see how L1 and L2 costs compare for a simple ERC-20 transfer (65,000 gas L1 / ~200 gas equivalent L2).
Assumes ETH price $2,500. L2 costs are approximate ratios vs L1; actual costs depend on batch size, proof costs, and blob availability. Post-EIP-4844 numbers.
6. DeFi ecosystem
Decentralized Finance (DeFi) is a suite of financial primitives deployed as smart contracts on Ethereum and its L2 ecosystem. Total Value Locked (TVL) peaked at ~$180B in 2021, contracted during the bear market, and has recovered to $60–100B (2025). The primitives below form the foundation of the entire DeFi stack.
Uniswap: Automated Market Maker
Uniswap replaced the order book with a mathematical formula. In Uniswap v2, each pool holds two tokens (e.g., ETH and USDC) and maintains the invariant:
where x and y are the reserves of each token and k is a constant. To buy ETH: deposit USDC → x increases → y decreases to maintain k → you receive ETH. Price = dy/dx = y/x. Slippage is proportional to trade size relative to pool liquidity.
Uniswap v3 introduced concentrated liquidity: LPs deposit liquidity within a specific price range [P_lower, P_upper] rather than the full [0, ∞] curve. This enables 100–4000× capital efficiency but requires active management (LPs suffer impermanent loss if price exits their range).
Aave: overcollateralized lending
Aave enables borrowing against crypto collateral. Users deposit assets (e.g., ETH) and can borrow up to a loan-to-value ratio (e.g., 80% LTV) in other assets (e.g., USDC). If the collateral value falls and the health factor drops below 1.0, the position is liquidated — a third party repays part of the loan and receives the collateral at a discount.
Flash loans — Aave's most novel primitive: borrow any amount in a single transaction with zero collateral, provided the loan (plus fee) is repaid within the same transaction. Atomicity is the collateral. Used for: arbitrage, collateral swaps, liquidation bots. Abused for: price oracle manipulation attacks in poorly designed protocols.
MakerDAO / Sky: algorithmic stablecoin
DAI is an ERC-20 token soft-pegged to $1.00. It is minted by depositing collateral (ETH, WBTC, real-world assets) into Maker Vaults (CDPs) at overcollateralization ratios (e.g., 150%). If collateral drops below the liquidation ratio, the vault is auctioned. The peg is maintained via:
- Stability fee (interest rate on DAI debt) — raised to reduce DAI supply; lowered to increase it
- DAI Savings Rate (DSR) — offers yield to DAI holders, attracting demand when supply exceeds peg
- Peg Stability Module (PSM) — allows 1:1 swap between DAI and USDC; the majority of DAI backing is now USDC (centralization concern)
Curve: stableswap
Curve Finance uses a modified AMM invariant optimized for assets that trade near 1:1 (stablecoins, liquid staking derivatives). The stableswap invariant is a combination of the constant sum (x+y=k, zero slippage at 1:1) and constant product (x×y=k) formulas, weighted by an amplification factor A. Higher A → more like a constant sum → less slippage for stable pairs.
Liquid staking: Lido
Ethereum validators require 32 ETH minimum stake. Lido pools ETH from users and distributes it to a curated set of node operators. In return, users receive stETH — a rebasing token representing their share of the staking pool. stETH can be used in DeFi (as collateral on Aave, in Curve pools) while earning staking yield. Lido controls ~30% of all staked ETH, creating systemic centralization risk debated extensively in the Ethereum community.
MEV: Maximal Extractable Value
MEV is the value that block producers can extract by reordering, inserting, or censoring transactions within a block. Forms include:
- Arbitrage — exploit price differences across DEXs in a single atomic transaction
- Sandwich attacks — see a large DEX trade in mempool, front-run it (buy) and back-run it (sell), profiting from the price impact
- Liquidations — competing to be first to liquidate undercollateralized positions
Flashbots / MEV-Boost separates block building from block proposing. "Searchers" (bots) submit bundles of transactions to specialized "block builders" who construct maximally profitable blocks. Validators simply pick the highest-paying block via MEV-Boost. This prevents the worst "chaos" MEV (failed transactions, gas spikes) but concentrates block building in a small number of sophisticated entities — a centralization concern.
Proposer-Builder Separation (PBS) — EIP-3675 and related proposals formalize MEV-Boost in-protocol, adding censorship resistance guarantees via inclusion lists.
7. Ethereum's impact
NFTs: ERC-721 and ERC-1155
ERC-721 (2018) defines a non-fungible token standard: each token has a unique ID and an owner. The tokenURI function returns metadata (often a JSON file with image URL). Key contracts: CryptoPunks (pre-standard, 2017), CryptoKitties (2017, first mainstream NFT), Bored Ape Yacht Club (2021, $1B+ market cap).
What NFTs actually enable: on-chain provenance (immutable ownership history), programmable royalties, composability (an NFT can be used as collateral in DeFi), and coordination mechanisms (NFT-gated communities, governance rights).
DAOs: on-chain governance
A DAO (Decentralized Autonomous Organization) uses smart contracts to codify governance. Token holders vote on-chain; if a proposal passes, it is executed automatically (no human execution required). Notable examples:
| DAO | Notable governance action |
|---|---|
| Compound | First major DeFi governance; COMP token holders vote on interest rate models, supported assets. Governor Bravo framework widely forked. |
| ENS DAO | Controls the .eth domain system; treasury holds ~$1B ENS tokens. Demonstrated on-chain governance of public infrastructure. |
| MakerDAO / Sky | Governs $8B+ in DAI collateral via MKR votes; risk parameter updates executed automatically post-vote. |
| Uniswap DAO | Controls ~$3B UNI treasury; controversially slow to activate fee switch; deployed on BNB Chain, Avalanche, Polygon via governance. |
The EVM monoculture
Over 30 blockchains (BNB Chain, Polygon, Avalanche C-Chain, Fantom, Celo, Cronos, Mantle, Blast, Linea, Scroll, zkSync, Arbitrum, Base, Optimism, and many more) implement EVM compatibility. Developers write Solidity once and deploy everywhere. This network effect creates a powerful gravitational pull around the EVM toolchain (Hardhat, Foundry, MetaMask, ethers.js/viem), Ethereum security research, and Ethereum audit firms.
Ethereum's role is increasingly that of a settlement layer: the chain where final state transitions are recorded, disputes resolved, and cross-rollup bridges anchored. The "internet of value" settlement layer may be more accurate than "world computer" as a mental model for where Ethereum is heading by 2028–2030.
Ethereum's endgame is a modular architecture: L1 provides consensus and data availability (via danksharding); rollups provide execution; bridges provide cross-rollup asset movement; and specialized chains (privacy chains, gaming chains, real-world asset chains) extend the ecosystem. The Ethereum L1 becomes the bedrock — rarely touched directly by end users, but securing trillions of dollars of economic activity processed in L2s above it.