How DeFi Works
AMMs, lending protocols, liquidations, flash loans, and MEV — the complete guide to decentralised finance
What Is DeFi?
Decentralised Finance (DeFi) is a set of financial applications built on public blockchains that operate without banks, brokers, or clearing houses. Smart contracts replace institutions — enforcing rules, holding collateral, and executing transactions automatically.
The key distinction from traditional finance is that DeFi protocols are non-custodial and permissionless. You retain control of your assets at all times — the protocol never holds them in the way a bank does. Anyone with an internet connection and a wallet can access DeFi, regardless of jurisdiction, credit history, or wealth. There is no KYC to swap tokens on Uniswap, no account approval to lend on Aave.
DeFi emerged from Ethereum's programmable smart contracts. The first wave (2017–2018) brought MakerDAO's DAI stablecoin and early DEXs like EtherDelta. The second wave — "DeFi Summer" of 2020 — produced Uniswap v2, Compound, Aave, Yearn, and Curve, collectively reaching $100 billion in total value locked (TVL) by late 2021. Today, DeFi spans dozens of chains, hundreds of protocols, and manages tens of billions in assets daily.
TVL measures the USD value of assets deposited into DeFi protocols — in liquidity pools, lending markets, and vaults. It is the primary metric for DeFi market size, though it double-counts assets that move through multiple protocols and rises with asset prices regardless of new deposits. DeFi Llama is the canonical tracker.
Automated Market Makers
Automated market makers (AMMs) replaced the order book with a mathematical formula. Instead of matching buyers and sellers, an AMM holds a pool of two assets and uses an equation to quote a price at all times. Anyone can trade against the pool, and anyone can provide liquidity to earn a share of fees.
The dominant design is the constant product formula: x · y = k, pioneered by Uniswap. The pool holds reserves of two tokens (x and y). After any trade, the product of the reserves must equal the same constant k. To buy token X, you add token Y to the pool — increasing y and decreasing x — causing the price of X to rise. The larger the trade relative to the pool, the more the price moves: this is price impact.
Impermanent loss is the opportunity cost of providing liquidity. If the price ratio of the two assets changes after you deposit, you end up with a different mix of assets than you started with — worth less than if you had simply held. The loss is "impermanent" because it reverses if prices return to the original ratio. But if one asset moons or craters, the loss becomes permanent.
Uniswap v3 introduced concentrated liquidity: LPs can specify a price range within which they provide liquidity, earning more fees for less capital — but earning nothing if the price moves outside their range. This made AMM liquidity provision an active strategy requiring range management.
| AMM Design | Formula | Best for | Example |
|---|---|---|---|
| Constant Product | x·y = k | Volatile pairs — always liquid at any price | Uniswap v2/v3 |
| Stableswap | Hybrid of x·y=k and x+y=k | Stablecoin pairs — low slippage near peg | Curve Finance |
| Weighted pool | Generalised constant product with weights | Multi-asset pools (e.g. 80/20 BPT) | Balancer |
| CLMM | Concentrated liquidity ranges | Capital-efficient active liquidity | Uniswap v3, Raydium |
Lending & Borrowing
DeFi lending protocols let anyone deposit assets to earn interest, or borrow assets by posting collateral. Everything is governed by smart contracts and interest rate models — no credit checks, no loan officers, no bank.
The core mechanic is overcollateralised borrowing. To borrow $100 of USDC, you might need to post $150 of ETH as collateral — a 150% collateral ratio. If your collateral value falls below the minimum ratio, your position is liquidated: a keeper bot repays part of your debt and receives your collateral at a discount.
Interest rates are set algorithmically based on the utilisation rate — the fraction of the pool's liquidity currently borrowed. Low utilisation means excess supply, so rates are low to attract borrowers. High utilisation means the pool is nearly empty; rates spike sharply to incentivise repayments and attract new depositors. The "kink" in the curve (typically at 80% utilisation) creates a sharp non-linear rate jump above the optimal point.
Aave and Compound are the dominant lending protocols. Aave introduced flash loans, stable borrowing rates, credit delegation, and isolation mode for newer assets. Compound pioneered the concept of cTokens — interest-bearing receipt tokens that accrue value as interest accumulates, redeemable for the underlying plus interest.
Liquidations
Liquidations are the safety valve of DeFi lending. When a borrower's collateral falls below the minimum ratio, their position is opened for liquidation — allowing anyone to repay part of their debt in exchange for their collateral at a discount.
The liquidation process is competitive and automated. Liquidator bots (typically running on Ethereum with MEV infrastructure) constantly monitor positions on every lending protocol. When a position becomes liquidatable, multiple bots race to submit the liquidation transaction first — since only the first one succeeds and earns the liquidation bonus (typically 5–15%).
The liquidation bonus must be calibrated carefully. Too small and liquidators won't bother, leaving bad debt to accumulate. Too large and the penalty falls heavily on borrowers, making the protocol unappealing. If the collateral value falls so fast that liquidators cannot act in time, the protocol incurs bad debt — a shortfall that must be covered by a protocol reserve or by minting new governance tokens.
During sharp market downturns (March 2020 "Black Thursday", May 2021, LUNA collapse), falling collateral prices trigger liquidations, which sell more collateral, further depressing prices, triggering more liquidations. These cascades can drain protocol reserves and cause mass bad debt. MakerDAO accrued ~$5M in bad debt on Black Thursday when ETH fell 50% in hours and gas prices spiked, preventing liquidations from executing.
Yield Farming & Liquidity Mining
Yield farming is the practice of moving assets between DeFi protocols to maximise returns. Liquidity mining is the mechanism protocols use to bootstrap liquidity by rewarding depositors with governance tokens on top of base fees.
- Impermanent loss if asset prices diverge
- Smart contract risk
- Low fee volume in bear markets
The mechanics of compound yield are straightforward but deceptively powerful. If you earn 10% APY paid daily, auto-compounding converts it to ~10.5% APY through daily reinvestment. At 50% APY, compounding daily gives ~64.8% effective APY. This is why APY figures in DeFi always refer to annualised rates assuming reinvestment — the raw rate (APR) is lower.
Liquidity mining — paying token emissions to LPs — was the core mechanic of DeFi Summer. Compound began distributing COMP tokens to borrowers and lenders in June 2020, triggering an arms race as every protocol launched a token with similar incentives. The model has a structural problem: emission tokens are often immediately sold by farmers, creating persistent sell pressure. Protocols that survived long-term (Curve, Uniswap) either had genuine fee revenue or implemented tokenomics that aligned incentives.
Flash Loans
A flash loan lets you borrow any amount of assets — with no collateral — as long as you repay in the same transaction. If repayment fails, the entire transaction reverts as if it never happened.
This is only possible because of how blockchain transactions work: every operation within a transaction either succeeds together or all reverts. A flash loan leverages this atomicity. You borrow $10 million, execute arbitrage or collateral swaps, repay the loan plus a small fee — all within one atomic transaction. If any step fails, the entire thing reverts and the lender never lost a dollar.
Flash loans are used legitimately for arbitrage (exploiting price differences between exchanges), collateral swaps (replace your DAI collateral with USDC without closing and reopening the position), and self-liquidation (repay your own loan to avoid a liquidation penalty). They are also used in attacks: many DeFi exploits have used flash loans to temporarily acquire enough capital to manipulate an oracle, drain a pool, or exploit a governance vulnerability.
Aave charges 0.05% on flash loans; dYdX offered zero-fee flash loans for a time. Despite the enormous notional sizes — flash loans routinely involve hundreds of millions of dollars — the fee income is modest because the loans are repaid instantly and carry no duration risk. Their value is in enabling zero-capital arbitrage and capital-efficient position management.
Governance & DAOs
Most major DeFi protocols are governed by a Decentralised Autonomous Organisation (DAO) — a group of token holders who vote on protocol changes, fee parameters, treasury allocation, and risk management.
Governance tokens (UNI, AAVE, CRV, COMP) confer voting rights proportional to holdings. Proposals are submitted on-chain (or via off-chain Snapshot for temperature checks), debated in forums, and executed automatically if passed. The entire governance history is on-chain and verifiable.
In practice, DeFi governance is heavily concentrated. Andreessen Horowitz alone holds enough UNI to pass many Uniswap proposals unilaterally. Voter apathy is chronic — most governance proposals pass with only 5–15% of eligible tokens voting. The Curve Wars of 2021–2022 showed what determined actors can do with governance: Convex Finance accumulated enough CRV voting power to direct Curve liquidity rewards, making veCRV control a strategic asset worth billions.
MEV & the Dark Forest
Maximal Extractable Value (MEV) is profit that block producers can capture by reordering, inserting, or censoring transactions within a block. It is the DeFi equivalent of high-frequency trading — and it extracts billions annually from ordinary users.
The mempool is a public waiting room for unconfirmed transactions. Every transaction you send sits visible in the mempool until a validator includes it in a block. Searcher bots continuously scan the mempool for profitable opportunities:
Sandwich attacks: A searcher sees your large DEX swap in the mempool. They submit a buy order before yours (frontrun) and a sell order after (backrun), moving the price against you and pocketing the difference. Your execution price worsens; the searcher profits at your expense.
Arbitrage: When a DEX trade moves a price out of line with other exchanges, bots race to arbitrage the difference before anyone else. This is largely benign — it keeps prices efficient — but the competition for arbitrage opportunities drives up gas costs for everyone.
Liquidations: Bots race to be the first to liquidate undercollateralised positions and earn the liquidation bonus. The competition is so intense that searchers simulate entire blocks to determine exactly which transactions to submit and at what gas price.
MEV-Boost and Flashbots have partially democratised MEV by separating block building from block proposing — but they have also professionalised it. Users can protect themselves with private RPCs (MEV Blocker, Flashbots Protect) that route transactions directly to validators, bypassing the public mempool.
Composability & Money Legos
DeFi protocols are composable — they can be combined and stacked like building blocks. A position in one protocol becomes collateral in another; a yield strategy in one vault can be combined with a leverage position on a lending platform. This is the "money legos" concept that distinguishes DeFi from traditional finance.
A concrete example of composability: deposit ETH into Lido to get stETH (earning staking rewards) → deposit stETH into Aave as collateral → borrow USDC → deposit USDC into Curve to earn trading fees and CRV rewards → stake CRV into Convex for boosted yields. Each layer adds yield; each layer also adds complexity and compounding risk.
Composability is DeFi's greatest innovation and its greatest vulnerability. When one protocol fails, every protocol built on top of it can fail simultaneously. The Euler Finance exploit of March 2023 — $197M drained — triggered a cascade because dozens of protocols held eTokens as collateral or liquidity. Systemic risk in DeFi is tightly correlated precisely because everything is connected.
Risks & How DeFi Fails
DeFi eliminates traditional intermediary risk but creates new, often novel, failure modes. Understanding these is not optional — it is a prerequisite for any DeFi participation.
| Risk | Mechanism | Notable Examples |
|---|---|---|
| Smart contract exploit | Bug in contract logic allows attacker to drain funds | Ronin ($625M), Euler ($197M), Nomad ($190M) |
| Oracle manipulation | Flash loan manipulates price feed; protocol acts on false price | Mango Markets ($114M), Cream Finance ($130M) |
| Governance attack | Attacker acquires majority voting power and passes malicious proposal | Beanstalk ($182M) — governance flash loan |
| Impermanent loss | Price divergence erodes LP returns below simple holding | Chronic in volatile-pair pools |
| Liquidation cascade | Falling prices trigger liquidations, which sell more collateral, causing more falls | Black Thursday (Mar 2020), LUNA collapse (May 2022) |
| Rug pull | Developers abandon project and drain treasury or LP funds | Squid Game token ($3.3M), numerous smaller projects |
| Bridge exploit | Bridge smart contract bug or key compromise | Wormhole ($320M), Ronin Bridge ($625M) |
| Regulatory action | Regulators shut down front-end or sanction addresses | Tornado Cash OFAC sanctions (Aug 2022) |
The most important risk management principle in DeFi is understand what you own. A yield-bearing token is a claim on an underlying position — it inherits all the risks of that position. Stacked DeFi positions (LP → collateral → borrow → farm) stack all the risks of each layer. When evaluating a protocol, the right questions are: What can go wrong with the smart contract? How is the oracle sourced and could it be manipulated? What happens if the governance token price collapses?
From safest to most risky (roughly): staking native assets on major PoS chains → lending blue-chip assets on audited protocols (Aave, Compound) → providing liquidity on established DEXs → leveraged yield farming on newer protocols → algorithmic stablecoin strategies → unaudited or anonymous protocols offering extreme yields. The higher the advertised APY, the more risk you are taking — usually in a form you cannot immediately see.