Lecture 8: DeFi Overview: Money Legos
Instructor: Yu Feng, UCSB
CS190: Blockchain Programming and Applications
Lecture 8 explores how decentralized finance protocols compose like building blocks to create a transparent, permissionless financial system. We'll examine the core primitives—stablecoins, AMMs, lending, perpetuals, and governance—that form the foundation of modern DeFi.
What Is DeFi?
Smart Contract Foundation
Financial services executed by transparent, auditable code rather than centralized institutions
Open Access
Permissionless participation—anyone with an internet connection can access global financial markets
Always Available
Protocols operate continuously without banking hours, holidays, or geographic restrictions
"Trust in code, not companies."
FTX vs DeFi: A Tale of Two Systems
November 2022: FTX Collapse
  • $8+ billion in missing customer funds
  • Complete platform shutdown within days
  • Opaque accounting and centralized control
  • Users locked out of their assets

Centralized exchanges function as black boxes where users must trust management with custody of funds.
DeFi Protocols Continue
  • Aave, Uniswap, Compound operated normally
  • All transactions visible on-chain
  • Users maintained full control of assets
  • Zero downtime or fund freezes

Every transaction, collateral ratio, and protocol balance is publicly auditable in real-time.
Key Lesson: Code can be audited and verified by anyone. CEOs and corporate balance sheets cannot.
Composability: DeFi's Superpower
Each DeFi protocol functions as a modular building block—a "Money Lego"—that can be combined with others to create sophisticated financial products. This permissionless composability enables innovation without requiring approval from any central authority.
Stablecoins
Stable value foundation
AMMs
Decentralized liquidity
Lending
Credit markets
Perpetuals
Advanced derivatives
Governance
Community control
Output from one protocol becomes input to another, creating an innovation flywheel where developers can build increasingly complex financial instruments.
Example: Stacking the Legos
Here's how a user might compose multiple DeFi protocols in a single workflow:
Acquire Stablecoins
Convert fiat or crypto into USDC or DAI to establish a stable value base
Deposit into Aave
Supply stablecoins to Aave's lending pool and receive interest-bearing aTokens
Use aTokens as Collateral
These yield-generating tokens can themselves serve as collateral in another protocol
Trade on DEX
Borrow against collateral and trade on Uniswap or GMX—all while still earning yield

This composability happens entirely on-chain without intermediaries. Each protocol interaction is atomic—either the entire sequence succeeds or it reverts.
Why Stablecoins Exist
The Volatility Problem
Native cryptocurrencies like ETH and BTC experience dramatic price swings, making them unsuitable for:
  • Predictable loan repayments
  • Merchant payment processing
  • Denominating financial contracts
  • Storing value short-term
The Stablecoin Solution
Stablecoins provide "digital cash" pegged to fiat currencies (typically USD) that combines blockchain benefits with price stability. They serve as the value foundation enabling other DeFi primitives to function.
A stable unit of account is essential for building financial infrastructure.
How Stablecoins Work
Different stablecoin designs make different trade-offs between decentralization, capital efficiency, and stability mechanisms.
Most successful stablecoins today use fiat backing (USDC) or crypto over-collateralization (DAI). Pure algorithmic stablecoins remain largely unproven after UST's spectacular collapse in 2022.
The Problem with Order Books
Traditional Order Books
  • Require matching specific buyers and sellers
  • Constant order placement and cancellation
  • High frequency updates needed
  • Gas costs prohibitive on Ethereum
  • Vulnerable to front-running
On-chain order books are too slow and expensive for efficient price discovery.
The AMM Solution
  • Liquidity always available in pool
  • No need to match individual orders
  • Algorithmic pricing via formula
  • Single transaction to swap
  • Passive liquidity provision
Automated Market Makers (AMMs) provide autonomous liquidity through smart contracts, enabling instant swaps at any time.
How AMMs Work
1
Liquidity Pool Structure
A pool holds reserves of two tokens (e.g., ETH and USDC). Liquidity providers deposit both tokens in proportion to current price.
2
Constant Product Formula
The core invariant x · y = k ensures the product of token reserves remains constant. As traders swap, reserves adjust but k stays fixed.
3
Automatic Price Discovery
When someone buys ETH with USDC, ETH reserve decreases and USDC reserve increases. Price automatically rises to maintain the constant product.

Mathematical Intuition: If you buy a lot of ETH (reducing x), the formula requires y to increase proportionally, making additional ETH exponentially more expensive. This creates a smooth pricing curve.
Intuition: The Vending Machine
Think of an AMM as an autonomous vending machine that's always open and always stocked:
Always Available
Unlike order books that need counterparties, the pool provides instant liquidity 24/7
Dynamic Pricing
As one snack sells out, its price automatically rises to reflect scarcity
No Operator Needed
The smart contract enforces all rules autonomously without human intervention

Leading Protocols: Uniswap (general purpose), Balancer (multi-asset pools), Curve (stablecoin-optimized)
Over-Collateralized Lending
DeFi lending enables borrowing without traditional credit checks by requiring borrowers to lock up collateral worth more than their loan value. This creates trustless credit markets.
How It Works: The Digital Pawn Shop
  1. Deposit Collateral: Lock $1,000 worth of ETH in a smart contract
  1. Borrow Stablecoins: Receive up to $750 USDC (75% collateral ratio)
  1. Maintain Health: If ETH price drops, collateral ratio decreases
  1. Automatic Liquidation: If ratio drops below threshold (e.g., 80%), protocol sells collateral to repay loan

Over-collateralization eliminates counterparty risk—the protocol holds sufficient assets to cover the loan regardless of borrower behavior.
Why Borrow?
  • Maintain ETH exposure while accessing liquidity
  • No credit check or KYC required
  • Tax efficiency (loans aren't taxable events)
  • Leverage positions
Lending in Action
DeFi lending protocols match lenders and borrowers through smart contract-managed pools with algorithmically determined interest rates.
Lender Supplies
Deposit USDC into protocol, receive interest-bearing aTokens or cTokens that appreciate over time
Borrower Withdraws
Lock collateral and borrow against it, paying interest that flows to lenders
Market-Driven Rates
Interest rates adjust automatically based on utilization—high demand increases rates to attract more supply
Repayment Cycle
Borrowers repay principal plus interest to unlock collateral, completing the cycle
This creates efficient credit markets without traditional financial intermediaries—the protocol algorithmically balances supply and demand.
What Are Perpetual Futures?
Perpetuals (perps) are derivatives contracts that track the price of an underlying asset without an expiration date, enabling leveraged trading in DeFi.
No Expiration
Unlike traditional futures, perpetual contracts never settle or expire. Traders can hold positions indefinitely.
Leverage Exposure
Open long (bullish) or short (bearish) positions with leverage—control $10,000 of exposure with $1,000 collateral.
Funding Rate Mechanism
Periodic payments between longs and shorts keep contract price anchored to spot price. When perp trades above spot, longs pay shorts (and vice versa).

The funding rate elegantly solves the problem of perpetual contracts: without expiration, what keeps the contract price aligned with reality? The answer is economic incentives—traders are paid to push prices back toward spot.
Why Perpetuals Matter
Core DeFi Risk Tool
  • Hedging: Offset spot holdings with short positions
  • Speculation: Express market views with leverage
  • Market Making: Arbitrage funding rates and spot prices
  • Capital Efficiency: Gain exposure without holding underlying assets
Post-FTX Alternatives
On-chain perpetual platforms emerged as transparent alternatives after centralized exchange failures:
  • dYdX: Order book-based perps with off-chain matching
  • GMX: Pool-based leverage trading
  • Hyperliquid: High-performance L1 for derivatives
All positions, collateral, and liquidations are publicly verifiable on-chain.
Governance via DAOs
Decentralized Autonomous Organizations (DAOs) enable community ownership and control of DeFi protocols through token-based voting.
01
Proposal Creation
Token holders or delegates create proposals for protocol changes—fee adjustments, parameter updates, treasury spending, or code upgrades.
02
Community Voting
Governance token holders (UNI, AAVE, MKR) vote on-chain. Voting power is typically proportional to token holdings or can be delegated.
03
Automated Execution
If proposal passes, changes execute automatically via smart contract. No trusted party can block implementation.
Community Ownership
  • Protocol direction controlled by users
  • Revenue accrual to token holders
  • Transparent decision-making process
vs Corporate Control
  • Board of directors makes decisions
  • Profit flows to shareholders
  • Opaque executive decisions
MEV: Maximal Extractable Value
Block producers (miners/validators) can reorder, insert, or censor transactions within blocks to extract additional profit—a phenomenon called MEV that affects all DeFi users.
1
User Transaction
Alice submits a large Uniswap trade to buy ETH
2
Bot Detects
MEV bot spots pending transaction in mempool
3
Front-Run
Bot places buy order before Alice's transaction
4
Back-Run
Bot sells immediately after Alice's trade executes
5
Profit Extracted
Bot captures price movement caused by Alice's trade

Healthy MEV
  • Arbitrage between DEXs (improves price efficiency)
  • Liquidations (maintains protocol solvency)
Harmful MEV
  • Sandwich attacks (extracts value from users)
  • Toxic frontrunning (manipulates prices)
The DeFi Stack Summary
1
2
3
4
5
1
Governance
2
Perpetuals
3
Lending Markets
4
AMMs
5
Stablecoins
Each layer of the DeFi stack builds on the primitives below it:
Stablecoins
Stable value foundation
AMMs
Decentralized swaps & pricing
Lending
Credit markets (over-collateralized)
Perpetuals
Leverage, hedging & risk management
Governance
Community ownership & protocol evolution

MEV operates as a cross-layer economic force affecting all protocols—from simple swaps to complex derivatives—representing both opportunity and challenge for DeFi's future.
Key Takeaways
Open Infrastructure
DeFi recreates traditional finance as open, programmable infrastructure where anyone can participate, audit, or build—no permission required.
Composability Drives Innovation
The "Money Legos" model creates an innovation flywheel. Each new protocol becomes a building block for future applications.
Primitive Stack
Stablecoins anchor value → AMMs enable markets → Lending builds credit → Perps extend risk tools
Future Challenges
Governance models and MEV extraction represent fundamental challenges that will shape DeFi's evolution and sustainability.
"DeFi demonstrates that financial infrastructure can be transparent, permissionless, and community-owned—but also reveals new challenges around frontrunning, governance capture, and protocol security."
Next Lecture Preview
Lecture 9: Stablecoins in Depth
We'll dive deeper into stablecoin design, examining the trade-offs between different architectures and exploring what makes a stablecoin truly stable.
Topics Covered:
  • USDC: Fiat-backed centralized stablecoins
  • DAI: Crypto-collateralized decentralized design
  • UST: Algorithmic stablecoin case study and collapse
  • Design trade-offs: decentralization vs stability vs capital efficiency
Case Studies
Build & Deploy
Risk Analysis