L06: Decentralized Finance (DeFi)
Master decentralized financial protocols: automated market makers, liquidity pools, yield farming, and the economic mechanisms behind modern DeFi.
Learning Objectives
By the end of this study session, you will be able to:
- Understand the economics of automated market makers (AMMs) and constant product formulas
- Calculate impermanent loss and understand its impact on liquidity providers
- Analyze yield farming mechanisms and incentive structures
- Compare DeFi protocols (DEX, lending, derivatives) and their economic tradeoffs
- Model slippage and price impact in decentralized exchanges
- Understand flash loans and their use cases and risks
- Evaluate DeFi composability and systemic risk propagation
Study Path
Read Summary Slides
Start with the summary slides (PDF). Focus on AMM mechanics diagrams and impermanent loss visualizations.
Learn AMM Math
Review the constant product formula (x*y=k) and understand how swaps affect pricing. Work through derivations in the concepts section.
Calculate Key Metrics
Work through practice problems involving impermanent loss, slippage, and yield calculations. These math skills are essential.
Take the Quiz
Test your knowledge with Quiz 6. Aim for at least 80% correct.
Explore DeFi Platforms
Visit Uniswap, Aave, or Curve (on testnet) to observe liquidity pools, fee tiers, and yield mechanisms in action.
Key Concepts Summary
Automated Market Makers (AMMs)
Key Idea: Replace orderbook with formula-based pricing. Instead of buyers and sellers bidding, algorithms set prices based on pool liquidity.
Constant Product Formula: x * y = k, where x and y are token reserves, k is constant. Price = y/x.
Example: Pool with 100 ETH and 500,000 USDC (k = 50,000,000). To buy 1 ETH, swap gets: 500,000 - (50,000,000 / 99) ≈ 5,050 USDC. Average price: $5,050/ETH (vs $5,000 without trade).
Liquidity Pools & Fees
LP Role: Deposit equal value of two tokens, earn a % of swap fees (e.g., 0.3% on Uniswap).
Fee Distribution: Fees accumulate in proportion to LP share of pool. More capital = more fees.
Risk: Impermanent loss - if prices diverge significantly, LP's holdings' value at withdrawal may be less than if they'd simply held the tokens.
Impermanent Loss (IL)
Definition: Difference between current value of LP holdings vs. value if tokens held unchanged since deposit.
Formula: IL % = (2 * sqrt(Price Ratio)) / (1 + Price Ratio) - 1
Example: Deposit $500 each of ETH and USDC (1:1 ratio). If ETH doubles, IL ≈ -5.7%. The LP now holds more USDC, fewer ETH (rebalanced to equal value), so lost potential upside.
Mitigation: High fees compensate for IL. Concentrated liquidity (e.g., Uniswap v3) reduces IL by targeting specific price ranges.
Slippage & Price Impact
Slippage: Difference between expected price and actual execution price due to market movement or large trades.
Price Impact: From a single large trade in AMM. Larger trades face exponentially worse prices because they move the curve more.
Example: Swapping $100k in USDC for ETH might get you 1% less ETH than the mid-market rate suggests. Swapping $1M might get 15% less.
Yield Farming & Incentives
Yield Farming: Earning rewards (LP fees + governance tokens) for providing liquidity or borrowing/lending.
APY Calculation: Annual yield as a percentage. E.g., $1000 in pool earning $50/year = 5% APY.
Risk: Unsustainable yields collapse when governance token incentives end. Farming token may dump as rewards vest.
Flash Loans
Concept: Borrow any amount instantly, must repay (plus fee) in the same transaction block.
Use Cases: Arbitrage, liquidations, protocol upgrades without collateral.
Risk: Flash loan attacks - exploit price differences within a single block to steal funds from other protocols.
DeFi Composability & Systemic Risk
Composability: Protocols can call each other in smart contracts, enabling "money legos." Powerful for innovation.
Cascading Failures: If one protocol fails (e.g., collateral value crashes), others relying on it may be dragged down. 2020-2021 saw several incidents.
Concentration Risk: Many protocols depend on same stablecoin or collateral. Failure of that asset crashes entire ecosystem.
Practice Problems
In pool: Due to rebalancing, LP now holds more USDC (price went up, pool sold ETH). Using IL formula with price ratio = 2: IL = (2 * sqrt(2)) / (1 + 2) - 1 = (2 * 1.414) / 3 - 1 ≈ 0.943 - 1 = -5.7%
LP's current holdings worth ≈ $60,000 * (1 - 0.057) ≈ $56,580. Loss from holding = $60,000 - $56,580 = $1,420 (impermanent loss). However, if LP earned $2,000 in fees over 3 months, total return = +$580 profit despite IL!
If APY drops to 5% midway (6 months in): First 6 months at 15% = $10,000 * 0.15 * 0.5 = $750. Second 6 months at 5% = ($10,000 + $750) * 0.05 * 0.5 ≈ $268. Total interest ≈ $1,018. Total = $11,018. The early high rates are very valuable! Note: 15% is unsustainably high in traditional finance, suggesting governance token incentives or protocol risk. Yields rarely stay high long-term.
Strategy A: Hold 10 ETH: $20,000 → $30,000 = +$10,000 gain + 5% fees on initial = +$1,000 = $31,000 total
Strategy B: LP with 10 ETH + $20,000 USDC. After price increase (using IL formula with ratio 1.5): IL ≈ -3.6%. LP value ≈ ($20,000 + $10,000 + $10,000 * 0.5) * (1 - 0.036) ≈ $29,472. Plus fees earned (say 2% = $400) = $29,872.
Winner: Strategy A (hold) is better in this bull scenario. Strategy B is better in low-volatility or down markets where IL is minimal and fees dominate. Strategy B also requires less capital to achieve the same ETH exposure (half the capital gets 50% exposure, thanks to borrowed capital from USDC deposit).
Safeguards:
1. Multiple oracles: Use prices from multiple sources, not just one DEX.
2. Time-weighted averages: Uniswap uses TWAP (time-weighted average prices) over a block, harder to manipulate.
3. Circuit breakers: Pause trading if price moves >X% in one block.
4. Slippage limits: Require minimum output; if slippage too high, revert.
5. Require profit > fee: Flash loan fee (0.05%) must be less than attacker's profit, reducing incentive.
Example: 1M USDC flash loan fee = 500 USDC. Attacker must profit >500 USDC from the manipulation, limiting attack size.
Sustainability: Almost certainly NOT sustainable. 200% is 10-100x typical risk-free rates, indicating either:
1. Protocol is brand new, offering high incentives to bootstrap liquidity (temporary).
2. High inflation in governance token (diluting existing holders).
3. Protocol takes unsustainable risk or has flawed economics.
LP Risks:
1. Token price dumps: Governance token earned as rewards hyperinflates and loses value. Earning "200% APY" in a token that drops 90% = net -70% loss.
2. IL still applies: LP faces normal impermanent loss despite high yields.
3. Opportunity cost: When yields normalize to 10%, the protocol may not be worth LP capital anymore. Early LPs who exit before the cliff are winners; late entrants are bagholders.
Best Practice: High yields are attractive but unsustainable. Participate early with dry powder ready to exit when yields normalize.
1. Higher yield = higher risk premium: If both are similar size, B pays 60% more yield, suggesting either: (a) B takes more credit risk (lends to riskier borrowers), or (b) B subsidizes yields with governance token, which is unsustainable.
2. Sustainability: A's 5% is more likely sustainable from protocol fees. B's 8% is harder to sustain unless B's lending actually generates >8% in fees (unlikely).
3. Governance token dilution: If B subsidizes with token incentives, that token supply grows, suppressing price. Over time, users exit B for A.
Safe Choice: A is lower risk. B is riskier but offers higher immediate returns - good for yield farmers, bad for passive savers. Smart strategy: Allocate capital proportionally to time horizon. Short-term yield farming → use B. Long-term savings → use A.
What happens: Collateral = $4.5M, but $10M in stablecoins outstanding. Undercollateralized by $0.5M! If users rush to redeem stablecoins for collateral, later users get nothing. System collapses (like Luna-Terra 2023).
Safer System:
1. Higher collateral ratio: Require 150% collateral for $100 stablecoins. Only $67 stablecoins per $100 collateral. If collateral drops 33%, still fully backed.
2. Automated liquidations: If ratio drops below 130%, liquidate borrower's position to restore safety.
3. Diversified collateral: Instead of one asset (which can crash), require mix of ETH, BTC, USDC. Correlation < 1 reduces risk.
4. Stability fund: Reserve pool of capital to absorb losses.
Example: MakerDAO uses 150% collateral + liquidations, surviving 2022-2023 crashes. Terra used 50% + poor incentives, collapsed.
Cascading Failure: X uses Y's prices to execute swaps. If Y's oracle is hacked and provides fake high prices for asset Z, X might execute swaps at terrible rates, losing capital. Users of X lose money even though X's code is sound.
Real Example: Curve uses Chainlink oracles. If Chainlink is compromised, Curve's internal price checks fail, allowing arbitrageurs to drain liquidity.
Prevention:
1. Multiple oracles: X queries Y, Z, and W. If one is hacked, majority vote rejects the malicious price.
2. Price bounds: Reject price updates >10% from previous block. Slows recovery but prevents one-block attacks.
3. Separate risk management: X has its own price sanity checks independent of Y.
4. Insurance/backstop: Protocol holds reserve to cover losses if composability breaks.
5. Minimize dependencies: Y is core to X, so X should audit Y regularly and have backup oracles ready.
Approaches to Reduce IL:
1. Concentrated Liquidity (Uniswap v3): LPs specify a price range (e.g., $1,800-$2,200 for ETH-USDC). Capital efficiency increases, IL decreases within range. Trade-off: Liquidity gaps outside range reduce protocol's trading capacity.
2. Stablecoin Pairs: If pair is ETH-USDC, IL is massive for price swings. If pair is USDC-USDT, IL is minimal. Trade-off: Stablecoin pairs don't capture as much trading volume or fees.
3. Dynamic Fees: Higher volatility → higher fees to compensate for IL. Trade-off: High fees reduce trading volume when volatility spikes.
4. Insurance Fund: Protocol insures LPs against IL, paying them if loss occurs. Trade-off: Expensive for protocol, requires surplus capital.
5. Asymmetric Liquidity: Single-sided LP (deposit only one token, protocol hedges). Trade-off: Reduces composability, adds complexity.
Reality: Most protocols accept IL as inherent cost of AMM design. LPs compensate via fee earnings (ideally IL < Fees, so net positive). Liquidity providers are sophisticated and price IL into their decision.
External Resources
Articles & Guides
-
Uniswap V3 Whitepaper - Concentrated Liquidity
ARTICLE
Technical deep-dive into AMM improvements and liquidity concentration
-
Impermanent Loss Explained - Bancor
ARTICLE
Comprehensive guide to IL with visual examples and mitigation strategies
-
Aave Governance & DeFi Lending
DOCS
Overview of DeFi lending protocols and risk management
Tools & Calculators
-
Liquidity Provider Returns Calculator
TOOL
Calculate IL and fee earnings for different price scenarios
-
Uniswap Interface
INTERACTIVE
Hands-on exploration of AMM mechanics on Ethereum or testnet
Videos
-
What is DeFi? - Finematics
VIDEO
Clear introduction to DeFi protocols and composability
-
Impermanent Loss Deep Dive - Whiteboard Crypto
VIDEO
Visual explanation of IL with real examples
Self-Check Questions
Before moving to Lesson 7, ensure you can confidently answer these questions:
- Can you explain the constant product formula and derive a swap output?
- Can you calculate impermanent loss for a given price move?
- Can you determine whether fee earnings offset IL for an LP?
- Can you explain slippage and how it affects large trades?
- Can you describe flash loan mechanics and associated risks?
- Can you compare yield farming opportunities and identify unsustainable yields?
- Can you explain composability risks in DeFi?
If you answered "yes" to most, you're ready for Lesson 7: Smart Contracts & Game Theory!