← Back to course
Lecture 07 · Applications

L07: Decentralized Finance

DeFi Protocols, AMMs, and Lending
Explore the revolution in financial services built on public blockchains: how automated market makers replace order books, how collateralized lending eliminates credit checks, and why composability creates both power and systemic risk in the DeFi ecosystem.
Slides: ~31 slides Charts: 12 new charts Track: Applications

Traditional finance is built on trust in intermediaries: banks hold deposits, brokerages execute trades, clearinghouses settle transactions, and credit bureaus gatekeep loans. Each layer extracts a fee, imposes delays, and requires identity verification that excludes 1.4 billion unbanked adults worldwide. Geography, creditworthiness scores, minimum balance requirements, and business-hours availability are constraints that feel invisible to those inside the system but represent absolute barriers to those outside it.

Decentralized Finance (DeFi) proposes a different architecture: replace institutional trust with smart contract code. If the rules governing a lending protocol are encoded in an audited Ethereum contract, then any wallet address — whether in Frankfurt or Lagos — can participate on identical terms, 24 hours a day, 365 days a year, with no application, no KYC form, and no credit score. The contract is the bank, the exchange, and the clearinghouse simultaneously.

Scale of the opportunity: At its 2021 peak, DeFi protocols held over $180 billion in Total Value Locked (TVL). Even after the 2022 bear market corrections, tens of billions of dollars remained deployed in permissionless financial infrastructure — a level of capital commitment that no experiment in open finance had achieved before.
DeFi Protocol Stack
Fig 7.1 — The DeFi stack: settlement layer, asset layer, protocol layer, aggregation layer, and application layer

The deeper motivation is composability. DeFi protocols are designed to interoperate like financial Lego bricks. A user can deposit ETH as collateral in MakerDAO to mint DAI, deposit that DAI in Aave to earn interest, and stake the resulting aTokens in a yield-aggregation vault — all in a single transaction. This composability would be impossible in traditional finance, where each institution maintains its own siloed ledger and API integrations require months of negotiation and compliance review.

DeFi is the collection of financial services — trading, lending, borrowing, derivatives, insurance, asset management — implemented as open-source smart contracts on public blockchains, primarily Ethereum. The defining characteristic is that no entity controls the protocol: governance may be community-driven via tokens, but the core mechanics execute deterministically without human intervention. Assets never leave the blockchain; custody is maintained by the user’s private key throughout.

The DeFi stack has five logical layers. The settlement layer (Ethereum, Solana, Avalanche) provides the trust substrate: consensus, finality, and smart contract execution. The asset layer covers tokens: ETH, ERC-20 tokens, wrapped assets like WBTC, and algorithmic stablecoins. The protocol layer is where financial logic lives: AMM contracts (Uniswap), lending pools (Aave), synthetic asset minters (Synthetix). The aggregation layer optimizes across protocols: DEX aggregators (1inch) route trades across multiple AMMs; yield optimizers (Yearn) automatically shift capital to highest-yield strategies. The application layer presents user-facing interfaces, though the contracts themselves require no UI.

Key pillars of DeFi:
Non-custodial: users hold their own private keys
Permissionless: any address can interact
Transparent: all transactions visible on-chain
Composable: protocols interoperate trustlessly
Programmable: arbitrary financial logic in code
DeFi TVL Growth
Fig 7.2 — Total Value Locked in DeFi protocols 2019–2024: growth and market cycles

Stablecoins are the essential primitive. A decentralized exchange denominated in volatile assets is difficult to use for everyday financial activity; stablecoins provide the unit-of-account stability that makes DeFi practically useful. Three stablecoin architectures coexist: fiat-collateralized (USDC, USDT — centralized issuers hold reserves), crypto-collateralized (DAI — over-collateralized with ETH and other assets, governed by MakerDAO), and algorithmic (various designs, most famously Terra/UST — maintain the peg via token supply mechanics without collateral reserves, a model that collapsed catastrophically in May 2022).

Protocol CategoryFunctionKey ExamplesTVL Range
Decentralized ExchangesToken swapping via AMMUniswap, Curve, Balancer$2B–$5B
Lending & BorrowingCollateralized loansAave, Compound, Morpho$5B–$15B
CDP / StablecoinsMint stablecoin vs. collateralMakerDAO, Liquity$3B–$8B
Liquid StakingStake ETH, receive liquid tokenLido, Rocket Pool$15B–$30B
Yield AggregatorsAuto-compound strategiesYearn, Convex$500M–$2B
DerivativesPerpetuals, options on-chaindYdX, GMX, Synthetix$500M–$3B

Uniswap is the canonical AMM and the most-used smart contract application in Ethereum history. Launched in November 2018, Uniswap V1 demonstrated that a 300-line Vyper contract could replace an entire exchange order book using a constant-product pricing function. Uniswap V3 (2021) introduced concentrated liquidity, allowing liquidity providers to specify a price range within which their capital is deployed — dramatically improving capital efficiency at the cost of active management. By 2023, Uniswap was regularly processing more daily volume than the largest US stock exchanges measured in trade count.

AMM Constant Product Curve
Fig 7.3 — Constant product market maker: x·y=k curve, price impact, and liquidity depth

Aave (originally ETHLend, rebranded 2018) is the leading decentralized lending protocol. Users deposit assets into liquidity pools and earn interest automatically; borrowers post collateral exceeding the loan value and borrow against it. Interest rates adjust dynamically based on pool utilization — as more of the pool is borrowed, the borrow rate rises to attract more deposits and discourage further borrowing. Aave introduced flash loans: uncollateralized loans that must be borrowed and repaid within a single transaction block. Flash loans have no traditional analogue and have enabled both legitimate arbitrage and high-profile exploits.

MakerDAO case study: MakerDAO is the oldest major DeFi protocol (2017). Users lock ETH or other approved collateral in a “Vault” (formerly CDP), which mints DAI stablecoin at a collateralization ratio typically above 150%. If the collateral value drops below the liquidation threshold, the Vault is automatically liquidated by external keepers who receive a discount on the collateral. MKR token holders govern risk parameters via on-chain voting — a live experiment in decentralized financial governance at billion-dollar scale.

The composability of these three protocols illustrates the “money Lego” concept. A sophisticated user might: (1) deposit ETH into Lido to receive stETH while earning staking rewards; (2) deposit stETH into Aave as collateral; (3) borrow USDC against that collateral; (4) swap the USDC for more ETH via Uniswap; (5) loop back to step 1. Each step executes trustlessly against audited contracts with no counterparty permission required. The same strategy in traditional finance would require accounts at multiple institutions, weeks of setup time, and minimum capital thresholds that exclude retail participants.

The constant product formula x · y = k is the mathematical heart of most AMMs. A liquidity pool holds reserves of two tokens (x and y). When a trader swaps token X for token Y, they add Δx to the pool and receive Δy such that (x + Δx)(y − Δy) = k. This automatically prices the trade: as x increases, y must decrease proportionally to maintain the constant product, pushing the price of X down and the price of Y up. No order book, no market makers, no off-chain matching — just arithmetic enforced by the EVM.

Price impact and slippage: The constant product formula implies that larger trades move the price more. A swap of 1% of the pool’s liquidity causes approximately 1% price impact; a swap of 10% of the pool causes ~11% impact. This is why deep liquidity pools matter and why large trades are routed across multiple pools by aggregators like 1inch to minimize slippage.

Collateralized lending on Aave and Compound operates via algorithmic interest rate curves. Each supported asset has a utilization rate U = Borrows / (Deposits + Borrows). Below an optimal utilization target U_opt, the borrow rate rises gently with utilization. Above U_opt, the rate increases steeply to incentivize repayment and new deposits. This design ensures pools remain liquid while automatically clearing excess demand through price signals.

Liquidation mechanics are equally important. When a borrower’s Health Factor drops below 1.0 (collateral value / debt value < liquidation threshold), external liquidators can repay a portion of the debt and claim the collateral at a discount — typically 5–10%. This liquidation bonus compensates liquidators for the gas cost and price risk of executing quickly. The entire process is permissionless: anyone running a liquidation bot can participate, which keeps the protocol solvent without relying on any particular party.

DeFi Interest Rate Curves
Fig 7.4 — Algorithmic interest rate curves: utilization vs. borrow/supply rates with kink model

Liquidity providers (LPs) earn fees from trading activity in exchange for bearing impermanent loss — the opportunity cost of providing liquidity versus simply holding the assets. If the price of one asset in the pool rises sharply, the AMM rebalances by selling the appreciating asset and buying the depreciating one, leaving LPs holding less of the winner. The loss is “impermanent” only in that it disappears if prices return to the original ratio; if they do not, the loss is realized upon withdrawal. Understanding impermanent loss is essential for evaluating LP positions as financial instruments rather than risk-free yield sources.

DeFi combines the execution risk of software with the financial risk of leveraged markets, creating a novel risk landscape that traditional risk frameworks do not fully address. Smart contract bugs are the most direct form: a single line of incorrect Solidity can drain an entire protocol treasury. The Ronin bridge hack ($625M, March 2022), the Wormhole exploit ($320M, February 2022), and the Euler Finance flash loan attack ($197M, March 2023) demonstrate that even audited, battle-tested code remains vulnerable to creative attack vectors.

Flash loan attacks explained: Flash loans allow borrowers to access millions of dollars of uncollateralized capital for a single transaction. An attacker can: (1) borrow $100M in a flash loan; (2) manipulate a price oracle by trading in a low-liquidity pool; (3) exploit a protocol that reads that manipulated price; (4) repay the flash loan in the same transaction. No capital is required upfront — only the ability to construct a profitable sequence of calls. This attack is impossible in traditional finance because no institution lends $100M for 15 seconds with no questions asked.
Oracle manipulation:
DeFi protocols rely on price oracles to determine collateral values and trigger liquidations. A protocol reading prices from a single on-chain source (e.g., Uniswap spot price) can be manipulated within a single block. Chainlink and TWAP (time-weighted average price) oracles mitigate this by aggregating across sources and time periods, making manipulation prohibitively expensive.
Smart contract risk categories:
• Reentrancy (The DAO, 2016)
• Integer overflow / underflow
• Access control errors
• Front-running / MEV extraction
• Logic errors in business rules
• Upgrade proxy vulnerabilities
• Economic design exploits
DeFi Hacks Timeline
Fig 7.5 — Major DeFi exploits by size and attack type, 2020–2024

Systemic risk arises from composability itself. Because DeFi protocols are deeply interconnected, a failure in one protocol can cascade through the ecosystem. The May 2022 Terra/UST collapse — where a $40 billion algorithmic stablecoin lost its peg and collapsed to near zero within 72 hours — triggered liquidations across lending protocols, forced vault closures, and drove TVL across all DeFi from $180B to under $50B. The interconnection that creates DeFi’s power also means that a single sufficiently large failure can trigger systemic contagion analogous to a traditional banking crisis.

The DeFi ecosystem has matured substantially since the “DeFi Summer” of 2020. Ethereum remains the dominant settlement layer by TVL, but significant activity has migrated to alternative L1s (Solana, Avalanche, BNB Chain) and Ethereum Layer 2 rollups (Arbitrum, Optimism, Base). This multi-chain expansion has introduced new bridging risks but also dramatically reduced user gas costs, making DeFi accessible for smaller positions that were previously uneconomical on Ethereum mainnet.

Liquid staking dominance: By 2024, liquid staking protocols — primarily Lido — had become the largest DeFi category by TVL, exceeding $30B. Lido holds over 30% of all staked ETH, raising centralization concerns about the Ethereum consensus layer. This concentration highlights a recurring DeFi tension: the protocols that win on convenience and yield often win on scale in ways that create new systemic dependencies.
TVL Distribution by Protocol
Fig 7.6 — TVL distribution across DeFi protocol categories and chains, 2024

Governance tokens have become the primary mechanism for coordinating decentralized protocol development. UNI (Uniswap), AAVE (Aave), MKR (MakerDAO), and CRV (Curve) give holders the right to propose and vote on parameter changes, fee switches, and treasury allocations. In practice, governance participation is low — most token holders do not vote — and large holders (venture funds, protocol teams) wield disproportionate influence. The “Curve Wars” of 2021–2022 illustrated an extreme case: protocols competed to accumulate veCRV (vote-escrowed CRV) to direct Curve’s liquidity mining emissions toward their own pools, effectively turning governance tokens into financial weapons in a yield competition.

DeFi Multi-Chain Landscape
Fig 7.7 — DeFi TVL distribution across chains: Ethereum, L2s, and alt-L1s, 2023–2024

DeFi’s impact on the structure of financial markets is already measurable, even if its long-term trajectory remains uncertain. On-chain DEX volumes regularly exceed $10–20 billion per day during active markets, representing a genuinely new venue for price discovery that operates in parallel to centralized exchanges. Lending protocols have demonstrated that algorithmic interest rate determination can efficiently price credit risk without underwriters, credit bureaus, or loan officers — at least for over-collateralized borrowers.

Financial inclusion potential:
• Dollar-denominated savings accessible in hyperinflationary economies (Argentina, Turkey, Venezuela) via stablecoins
• Instant settlement vs. T+2 in traditional equity markets
• Remittances at <0.1% fee vs. 6–8% via traditional services
• 24/7 market access without broker intermediation
• Programmable money enabling micro-contracts impractical at traditional fee levels
Composability effects:
Composability creates capital efficiency unachievable in siloed traditional finance. The same dollar of collateral can simultaneously: earn staking yield (liquid staking), serve as collateral in a lending protocol, and back a short position in a derivatives market — a form of financial leverage that is transparent on-chain but creates correlated liquidation risk across all three positions simultaneously.
DeFi vs TradFi Comparison
Fig 7.8 — DeFi versus traditional finance: settlement time, access, fees, and counterparty risk

Institutional engagement with DeFi has grown cautiously. Major banks and asset managers have explored DeFi-adjacent infrastructure — tokenized money market funds (BlackRock’s BUIDL fund on Ethereum), permissioned DeFi forks (JPMorgan’s Project Onyx), and regulated stablecoin issuance (PayPal’s PYUSD). These experiments share a common pattern: institutions adopt the technology stack while preserving regulatory compliance and identity controls — a hybrid model that captures operational efficiency without the full permissionlessness that defines native DeFi.

The trajectory of DeFi depends on three interacting forces: regulatory clarity, scalability improvements, and the evolution of governance models. Regulatory pressure is intensifying: the EU’s MiCA regulation, US SEC actions against DeFi protocols, and FATF guidance on virtual asset service providers are collectively pushing toward a world where permissionless finance faces compliance requirements originally designed for permissioned institutions. How DeFi protocols adapt — through optional compliance layers, geofencing, or outright resistance — will shape the industry’s legal standing for years.

The institutional DeFi thesis: Rather than competing with TradFi, a convergence scenario is plausible where: (1) tokenized real-world assets (Treasuries, equities, private credit) flow onto public chains; (2) permissioned DeFi pools allow KYC’d institutions to interact with on-chain liquidity; (3) CBDC integrations create on-chain settlement finality; (4) smart contract infrastructure becomes the back office of global finance without the front-end ever becoming “permissionless” in the cypherpunk sense. This is already visible in pilot programs from BlackRock, JPMorgan, and numerous central banks.
DeFi Adoption Trajectory
Fig 7.9 — DeFi adoption S-curve: wallet growth, protocol diversity, and institutional engagement, 2020–2024

Scalability improvements via Layer 2 rollups are making DeFi genuinely accessible to retail users. Gas fees that once made a $100 Uniswap swap economically irrational on Ethereum mainnet are sub-cent on Arbitrum, Optimism, and Base. As rollup technology matures — ZK rollups approaching EVM equivalence, shared sequencers enabling cross-rollup composability — the user experience gap with centralized exchanges is narrowing. The remaining differentiator for DeFi will be its trustless, self-custodial, auditable nature: properties that matter less to users comfortable with Coinbase and more to those who have experienced custodial failure firsthand.

For students entering the blockchain field, DeFi represents the richest intersection of financial engineering, cryptography, mechanism design, and software security in the current technology landscape. A single AMM contract requires understanding calculus (the bonding curve), market microstructure (impermanent loss), game theory (liquidity provider incentives), and Solidity security (reentrancy, MEV). Mastery of DeFi mechanics is increasingly a prerequisite for roles in blockchain engineering, crypto-native finance, and the growing segment of traditional finance building on-chain infrastructure.

© 2025 BSc Blockchain Course · Blockchain Technology · Course Home · Slide Gallery