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.

Prereq: blockchain basics, hash functions, ECDSA Time to read: ~50 min Interactive diagrams: 2 UPDATED Apr 11 2026 19:32

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:

EOA
Externally Owned Account. Controlled by a private key. Has a balance (in wei) and a nonce (transaction counter). No code.
Contract account
Created by deploying bytecode. Has a balance, a nonce, EVM bytecode, and a persistent storage mapping (256-bit key → 256-bit value). Only executes when called.
World state
A mapping of 20-byte addresses to account objects. The state root (a Merkle-Patricia trie root) is committed to every block header.
Nonce
Monotonically increasing counter per EOA. Transaction with nonce N is only valid after nonce N-1 has been processed — prevents replay attacks and enforces ordering.

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: VISION VS REALITY

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

RegionSizePersistenceCost
StackMax 1024 items × 256 bitsExecution-scoped~3 gas per operation
MemoryDynamically allocated bytesExecution-scoped (zeroed per call)Quadratic: cheap when small, expensive when large
Storage2²⁵⁶ slots × 32 bytes per contractPermanent (survives across transactions)SSTORE: 20,000 gas (new slot), 2,900 gas (update); most expensive EVM operation
CalldataVaries; passed with transactionRead-only within execution4 gas/zero byte, 16 gas/non-zero byte (post-EIP-2028)
ReturndataVaries; output from subcallAvailable after CALL/STATICCALL returnsNo additional cost beyond reading
CodeFixed at deploy timeImmutable (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:

base_fee
Protocol-set fee that adjusts automatically. Increases by up to 12.5% if previous block was full; decreases by up to 12.5% if empty. Target: 50% full blocks.
priority_fee
Tip paid directly to validator/miner. Only way to jump the queue above base fee.
max_fee
User-specified ceiling. If base_fee + priority_fee < max_fee, user pays base_fee + priority_fee. If base_fee > max_fee, tx is not included.
Fee burn
The entire base_fee is burned — permanently removed from supply. Makes ETH net deflationary when activity is high enough (>~15 gwei 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

OpcodeGas (Berlin/Shanghai)Operation
ADD, MUL, SUB3Basic arithmetic on 256-bit stack items
PUSH1 … PUSH323Push N-byte constant onto stack
MLOAD / MSTORE3 + memory expansionLoad/store 32 bytes to/from memory
SLOAD2,100 (cold), 100 (warm)Load 32-byte value from contract storage
SSTORE20,000 (zero→nonzero), 2,900 (update), 100 (same value)Write 32-byte value to contract storage
CALL2,600 (cold target) + value transfer overheadCall external contract
CREATE32,000 + init code costDeploy new contract
KECCAK25630 + 6/wordKeccak-256 hash of memory range
LOG0…LOG4375 + 375/topic + 8/byteEmit event (stored in receipt, not state)
SELFDESTRUCT5,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.

PROGRAM
STACK (top is first)
MEMORY (slot 0)

Transaction lifecycle

  1. User signs transaction (nonce, to, value, data, gas params, chainId via EIP-155)
  2. Transaction broadcast to peer-to-peer network; each node validates signature and nonce, adds to mempool
  3. Block proposer (PoS validator) selects transactions from mempool; EIP-1559: all must pay ≥ base_fee
  4. EVM executes each transaction in order; state changes are buffered in a write-ahead journal
  5. If execution reverts (OOG, REVERT), state changes are discarded but gas is consumed up to the OOG point
  6. Successful transactions are committed; state root, receipts root, bloom filter are computed and placed in the block header
  7. 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

PatternPurposeMechanism
Proxy (UUPS/Transparent)Upgradeable contracts — logic can be replaced without changing the addressdelegatecall from proxy to implementation; proxy stores state, implementation provides logic. Storage layout must remain identical.
OwnableAdministrative access controlSingle owner address with modifier onlyOwner. Simple but centralized — often replaced by multisig (Gnosis Safe) or DAO governance.
Checks-Effects-InteractionsPrevent reentrancy attacksAlways update internal state BEFORE making external calls. Prevents re-entry into the function with stale state.
Pull over PushAvoid DoS via reverting recipientsInstead of sending ETH to all recipients (any one failure blocks all), let each recipient pull their own funds.
FactoryDeploy many instances of a contractFactory 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

TechniqueSavingExplanation
Pack struct fieldsUp to 10× on readsEVM storage slots are 32 bytes. Multiple small values (uint128, uint64, bool) packed into one slot use one SLOAD instead of N.
Use calldata not memory16 gas/byte vs memory copyFor function parameters that are only read (not modified), declare as calldata — avoids copying to memory.
unchecked { } blocks3× faster arithmeticSolidity 0.8+ adds overflow checks by default (~3 gas each). When you know overflow can't happen (loop counter), use unchecked.
Cache storage in memory2,000+ gas per repeated readuint256 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 revertCustom errors error Unauthorized() are cheaper than revert strings — no string encoding in bytecode.
Avoid address.transfer()Future-proofHard-codes 2300 gas stipend — breaks with any EVM gas cost repricing. Use call{value: amount}("") with checks-effects-interactions instead.

Security checklist

TOP SECURITY VULNERABILITIES

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:

LMD-GHOST
Latest Message Driven Greediest Heaviest Observed Subtree — the fork choice rule. At each fork, follow the branch with the most recent attestation weight. Provides liveness: the chain always has a canonical head.
Casper FFG
Friendly Finality Gadget — adds economic finality. Once a checkpoint gets 2/3+ validator votes in two consecutive epochs, it is finalized. Reverting a finalized block requires slashing ≥1/3 of staked ETH.
Slot
12 seconds. One validator is randomly selected to propose a block. 128 validators attest (vote) for the block head.
Epoch
32 slots = 6.4 minutes. At epoch boundaries, checkpoints are created and FFG votes are tallied for finality.
Finality
A block is finalized after 2 epochs (~12.8 minutes). Reverting it would cost the attacker >1/3 of all staked ETH (~$30B+) in slashing penalties.

Validator lifecycle

StageConditionDetail
Deposit32 ETH sent to deposit contractGenerates BLS key pair; deposit included in beacon chain state
Activation queueUp to several weeks when demand is highLimited activation rate (churn limit) prevents rapid validator influx from destabilizing committee selection
ActiveProposing and attesting each epochEarn ~4–5% APR from issuance + MEV tips; must maintain uptime
Inactivity leakOffline for >4 epochs during non-finalityBalance gradually depleted — forces non-participating stake offline to allow remaining 2/3 to achieve finality
SlashingDouble-vote or surround-vote detectedImmediate ≥1/32 penalty, 36-day exit queue, correlation penalty proportional to % of validators slashed simultaneously
Voluntary exitValidator submits exit messageExit queue; minimum 256 epochs withdrawal delay after exit; principal unlocked after Shanghai upgrade (April 2023)

Slashing conditions

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):

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.

Arbitrum One
Multi-round interactive fraud proofs (disagree → challenge → narrow to single step → verify on L1). Most used optimistic rollup by TVL. Uses custom ArbOS that extends EVM.
Optimism / Base
Single-round fault proofs (Cannon). OP Stack is an open-source framework enabling many chains (Base by Coinbase, Mode, Zora) to share the same tech stack and liquidity via the "Superchain" vision.
7-day delay
Users withdrawing to L1 must wait 7 days for the challenge period to expire. Liquidity providers (bridges) can front the liquidity and claim the L1 funds when it matures — for a fee.

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).

TypeEVM compatibilityProof systemExamples
Type 1Fully EVM-equivalent (hash-for-hash identical)ZK proof of actual EVM executionTaiko; theoretical ideal
Type 2EVM-equivalent (same behavior, slightly different internals)ZK proof of EVM-like VMScroll, Polygon zkEVM
Type 3Almost EVM-equivalent (minor incompatibilities)Modified EVM for proof efficiencyPolygon zkEVM v1, early zkSync Era
Type 4High-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.

THE DANKSHARDING ROADMAP

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).


L1 (Ethereum)
$1.95
65,000 gas × base fee
Optimistic Rollup
$0.08
L1 data amortized + L2 execution
ZK Rollup
$0.03
Validity proof amortized + L2 exec

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:

x × y = k

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:

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:

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:

DAONotable governance action
CompoundFirst major DeFi governance; COMP token holders vote on interest rate models, supported assets. Governor Bravo framework widely forked.
ENS DAOControls the .eth domain system; treasury holds ~$1B ENS tokens. Demonstrated on-chain governance of public infrastructure.
MakerDAO / SkyGoverns $8B+ in DAI collateral via MKR votes; risk parameter updates executed automatically post-vote.
Uniswap DAOControls ~$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.

THE MODULAR BLOCKCHAIN THESIS

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.