Education › Blockchain › Stage 3: Building dApps

DeFi: the money protocols

DEXes, AMMs, lending, stablecoins and oracles — how decentralised finance is actually built.

Intermediate ~34 min read Module 12 of 16

DeFi — decentralised finance — is the most active use of smart contracts: exchanges, lending, and stablecoins run entirely as code, with no bank in the middle. It's where the token standards, the approve/transferFrom flow, and the security lessons all come together. This lesson explains the core building blocks — how a decentralised exchange sets prices without an order book, how lending works without a loan officer, what a stablecoin is, and why oracles are both essential and dangerous — so you understand what these protocols actually do, and the risks that come with them.

After this module you can
  • Explain what DeFi is and the property of composability
  • Describe how an automated market maker (AMM) prices trades
  • Explain over-collateralised lending and stablecoins
  • Explain why oracles are needed and how price manipulation exploits them

What DeFi is, and composability

DeFi is financial services — trading, lending, borrowing, earning interest — built as open smart contracts instead of run by banks or brokers. Anyone with a wallet can use them, permissionlessly, and the rules are enforced by code rather than an institution. The property that makes DeFi powerful (and risky) is composability: because every protocol is a public contract with a standard token interface, protocols snap together like blocks. A token you receive from a lending protocol can be deposited into an exchange and used as collateral elsewhere, all in one transaction. This 'money legos' quality lets complex strategies be assembled from simple parts — but it also means a flaw in one protocol can cascade into others built on top of it.

DEXes and the automated market maker

A decentralised exchange (DEX) lets people swap tokens with no company holding their funds. Most don't use a traditional order book; they use an automated market maker (AMM). Here's the idea: a liquidity pool holds a reserve of two tokens, say ETH and a stablecoin. The AMM prices trades with a formula that keeps the *product* of the two reserves roughly constant (the classic 'x times y equals k'). When you buy ETH from the pool, you add stablecoin and remove ETH, which shifts the ratio and moves the price — buying pushes the price up automatically. Liquidity providers deposit both tokens into the pool and earn a share of the trading fees. No matching engine, no broker — just a formula and a pool of tokens.

text
Constant-product AMM:   x * y = k   (k stays ~constant)

Pool reserves:  x = 100 ETH,  y = 300,000 USDC   ->  k = 30,000,000
Spot price:     y / x = 3,000 USDC per ETH

Buy 1 ETH: pool must keep k, so USDC in = k/(x-1) - y
           = 30,000,000 / 99 - 300,000  =  ~3,030 USDC
// You paid slightly above 3,000 -- the price moved as you traded (slippage).

Two consequences fall out of the formula. Slippage: a large trade moves the price against you, because it shifts the reserves more. And impermanent loss: liquidity providers can end up worse off than simply holding the two tokens if the price diverges a lot — a real risk to understand before providing liquidity.

Lending without a loan officer

DeFi lending protocols let you deposit tokens to earn interest, or borrow against tokens you deposit — with no credit check, because there's no identity to check. The trick that replaces trust is over-collateralisation: to borrow, you must lock up *more* value than you take out. Deposit $150 of ETH, borrow up to maybe $100 of a stablecoin. If the value of your collateral falls too close to your debt, the protocol liquidates it — sells your collateral automatically to repay the loan — protecting the lenders. Interest rates adjust algorithmically with supply and demand for each asset. It sounds odd to borrow while posting more than you take, but it enables useful things: getting liquidity without selling an asset, or leverage, all enforced by code.

Note

Over-collateralisation is why DeFi lending needs no credit score: the loan is always backed by more value than it lends, and liquidation enforces that automatically. It also means a sharp price drop can trigger mass liquidations — a key risk in volatile markets.

Stablecoins

Volatile prices make many financial uses awkward, so stablecoins are tokens designed to hold a steady value, usually one US dollar. There are two main kinds. Collateral-backed stablecoins are backed by reserves — either off-chain dollars held by a company (the token is a claim on those dollars) or on-chain crypto locked as over-collateralisation. Algorithmic stablecoins instead try to hold the peg through supply-and-demand mechanisms with no full backing; several have failed dramatically when confidence broke, so they carry a distinct, serious risk. Stablecoins are the backbone of DeFi trading and lending because they give a stable unit to price and borrow in, but 'stable' depends entirely on the quality of the backing or mechanism — not all are equally safe.

Oracles and the manipulation risk

Contracts can't see off-chain data — including real-world prices — because the EVM is deterministic and isolated. An oracle is a service that brings external data on-chain, most importantly asset prices that lending and derivatives protocols depend on to know when to liquidate. This creates a dangerous dependency: if a protocol trusts a manipulable price source, an attacker can move that price and exploit the protocol. The classic attack uses a flash loan — borrowing a huge sum within a single transaction — to distort a thinly-traded DEX's spot price, then using that fake price against a protocol that naively reads it, draining it, and repaying the loan, all atomically. The defence is robust oracles that resist manipulation (like time-averaged or aggregated multi-source prices, e.g. Chainlink), never a single pool's instantaneous price.

Watch out

Never trust a price you can cheaply move for anything valuable. A large share of DeFi hacks are oracle or price-manipulation attacks, often powered by flash loans. Using a robust, manipulation-resistant price feed is not optional for a protocol that handles real money.

Hands-on practice

Reason about the DeFi building blocks

  1. Explain composability and give an example of using one protocol's output token in another.
  2. Using the x*y=k idea, explain why a large buy pushes the price up (slippage).
  3. Explain why DeFi lending is over-collateralised and what liquidation does.
  4. Describe the difference between collateral-backed and algorithmic stablecoins and their risk.
  5. Explain how a flash-loan oracle-manipulation attack works and how a robust oracle prevents it.
Cheat sheet

DeFi: the money protocols — at a glance

Main things to focus on

  • DeFi is financial services as open smart contracts; composability lets protocols snap together.
  • A DEX uses an AMM: a liquidity pool priced by a formula (x*y=k), not an order book.
  • Large trades cause slippage; liquidity providers face impermanent loss.
  • DeFi lending is over-collateralised; liquidation sells collateral to protect lenders.
  • Stablecoins hold a steady value via collateral backing or (riskier) algorithms.
  • Oracles bring prices on-chain; a manipulable price source is a top attack vector.

DeFi basics

permissionlessanyone with a wallet can use it
composabilityprotocols snap together like legos
code, not banksrules enforced by contracts
cascading riska flaw can spread across protocols

DEX / AMM

liquidity poolreserves of two tokens
x * y = kconstant-product pricing formula
slippagebig trades move the price
impermanent lossLP risk when prices diverge

Lending & stables

over-collateralisedlock more value than you borrow
liquidationauto-sell collateral to repay
collateral-backedstablecoin backed by reserves
algorithmicpeg by mechanism; riskier

Oracles

oraclebrings off-chain data on-chain
price feedwhat lending protocols rely on
flash loanhuge loan within one transaction
robust oracleaggregated, manipulation-resistant

Common pitfalls

  • Providing liquidity without understanding slippage and impermanent loss.
  • Assuming all stablecoins are equally safe — algorithmic ones have collapsed.
  • Reading a single DEX's spot price as truth, inviting oracle manipulation.
  • Forgetting that composability spreads one protocol's failure into others.
  • Ignoring liquidation risk on a leveraged position during a price drop.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →