Decentralized Finance (DeFi)

Smart Contracts, DeFi & Web3 Security
Course 2 · Chapter 4 · Decentralized Finance (DeFi): AMMs, Liquidity Pools & Lending

Chapters 1 through 3 gave you the real tools smart contracts are built from. This chapter applies all of it to DeFi — "decentralized finance": real trading, lending, and borrowing services built entirely from smart contracts, with no bank, exchange, or broker sitting in the middle.

Automated Market Makers: Trading Without an Order Book

A traditional exchange matches buyers and sellers through an order book. DeFi's dominant real alternative is the Automated Market Maker (AMM), pioneered by Uniswap, created by Hayden Adams and launched on 2 November 2018, directly inspired by an earlier blog post from Ethereum co-founder Vitalik Buterin (Course 1, Chapter 6).

Instead of matching individual buy and sell orders, an AMM holds a shared pool of two tokens and prices trades using a real, deterministic formula: the constant product formula, x × y = k, where x and y are the pool's current quantities of each token, and k must stay exactly constant across every trade.

Before a trade100 ETH × 200,000 USDC = k (20,000,000)
A trader adds+10 ETH to the pool
To keep k constant, USDC must fall to20,000,000 ÷ 110 ≈ 181,818 USDC
The trader receives200,000 − 181,818 ≈ 18,182 USDC

Notice what just happened to the real price: before the trade, 1 ETH was worth 2,000 USDC (200,000 ÷ 100). After it, the pool implies roughly 1,653 USDC per ETH (181,818 ÷ 110) — the trade itself moved the price, purely as a mechanical consequence of the formula, with no separate "order book" or human market maker involved at all.

Liquidity Pools and Liquidity Providers

The tokens sitting in that pool don't come from Uniswap itself — they're deposited by ordinary users called liquidity providers (LPs), who contribute a matched pair of tokens to the pool and, in exchange, earn a real share of the trading fees every subsequent swap generates.

Impermanent Loss: A Real, Honest Risk for Liquidity Providers If the real market price of the two pooled tokens shifts after you deposit, the AMM's own constant-product formula automatically rebalances the pool — effectively selling off some of whichever token is becoming more valuable and buying more of whichever is becoming less valuable, exactly as the worked example above shows happening on every single trade. This means a liquidity provider can end up, upon withdrawal, holding a combination of tokens worth less than if they had simply held the original two tokens outside the pool the whole time. It's called "impermanent" because the loss only becomes real once you actually withdraw at an unfavorable price ratio — if prices later return to where they started, the loss disappears on paper. But it's a genuine, real financial risk in the meantime, not a theoretical footnote.

Lending and Borrowing: Real Protocols, No Credit Check

Real DeFi lending protocols — Aave and Compound are two of the most established — let users deposit crypto assets to earn interest, and let other users borrow against posted collateral, with interest rates that adjust automatically based on real-time supply and demand for each asset.

There's a genuine structural reason DeFi lending looks different from a bank loan: over-collateralization. Since there's no credit check, no identity verification, and no legal recourse against a pseudonymous blockchain address, these protocols require borrowers to post more collateral value than they're actually allowed to borrow — the collateral itself is the entire basis of trust, replacing everything a credit score or a bank's own underwriting process would normally provide.

Liquidation: Code, Not a Court, Enforces the Loan If a borrower's collateral value falls too close to the value of what they've borrowed (because the collateral asset's own market price dropped), the protocol automatically liquidates — sells off enough of the collateral to repay the loan, with no human intervention, no negotiation, and no notice period beyond what the smart contract's own code specifies. This is a direct, real-world consequence of Chapter 3's own Checks-Effects- Interactions discipline and Course 1's own "code is law" theme: the loan's own terms are enforced exactly as written, automatically, the moment the code's own conditions are met.

Flash Loans: A Genuinely Novel DeFi Primitive

DeFi introduced a real financial instrument with no direct traditional-finance equivalent: the flash loan — an uncollateralized loan of any size, borrowed and fully repaid within a single blockchain transaction, or the entire transaction reverts as though it never happened.

1
Borrow a large sum — potentially millions of dollars worth of tokens — with zero collateral posted.
2
Use the borrowed funds for something — commonly, a trade or a series of trades across multiple protocols.
3
Repay the full loan amount, plus a fee, before the same transaction finishes.
4
If step 3 doesn't succeed for any reason, the EVM reverts the entire transaction — including the original loan — as if none of it had ever happened at all.

This is only possible because of a real property Chapter 2 already established: a single Ethereum transaction is atomic — if execution fails to complete for any reason, every state change it attempted gets reverted, exactly like Chapter 2's own out-of-gas behavior, just triggered here by a deliberate require check instead of running out of gas. Because the loan and its repayment are forced into that same atomic unit, the lender needs zero trust in the borrower at all: either the money genuinely comes back by the end of the transaction, or, from the chain's own perspective, the loan simply never happened.

A Real, Honest Forward Reference Flash loans are a genuinely powerful, legitimate tool — but their real ability to temporarily command enormous, uncollateralized sums has also made them a real, documented component of several serious DeFi exploits, typically used to briefly manipulate an AMM's own price (exactly the mechanism this chapter's own worked example demonstrated) before another protocol that trusts that price gets exploited. Chapters 7 and 8 cover this in real, specific detail.
DeFi PrimitiveReal PurposeReal Risk
AMM / liquidity poolToken trading without an order bookImpermanent loss for liquidity providers
Over-collateralized lendingBorrowing without a credit checkAutomatic liquidation if collateral value falls
Flash loanTrust-free, uncollateralized borrowing within one transactionA real, documented tool in several price-manipulation exploits

Hands-On Exercises

Three exercises applying AMM mechanics, over-collateralization, and flash loan atomicity before Chapter 5 turns to the broader dApp and Web3 stack these protocols live inside.

Exercise 1
A pool holds 50 ETH and 100,000 USDC. Using this chapter's own constant product formula, work out roughly how many USDC a trader receives for adding 5 ETH to the pool, and what the pool's implied ETH price is immediately before and after the trade.
Exercise 2
A friend says: "DeFi lending is safer than a bank loan, since it doesn't need a credit check at all." Using this chapter's own explanation of over-collateralization, explain what's misleading about this claim.
Exercise 3
Explain, using this chapter's own flash loan flow and Chapter 2's own transaction-atomicity/ revert behavior, why a flash loan lender takes on essentially zero counterparty risk — even when lending an enormous, completely uncollateralized sum to a stranger.

Quick Reference

  • AMM — prices trades via the constant product formula (x × y = k) instead of an order book; pioneered by Uniswap (Hayden Adams, 2 November 2018).
  • Liquidity pool / LP — users deposit paired tokens, earn trading fees, but risk impermanent loss if the price ratio shifts.
  • Over-collateralization — DeFi lending requires more collateral than borrowed, replacing a credit check.
  • Liquidation — automatic, code-enforced collateral sale if its value falls too close to the borrowed amount.
  • Flash loan — an uncollateralized loan that must be repaid within the same atomic transaction, or the whole thing reverts.