Courses / Blockchain / Week 8
Week 8 of 12 · Intermediate

DeFi: Markets Built From Contracts

You learn how decentralized finance builds swapping, lending and stable money out of smart contracts and tokens. You also learn where its main risks come from and how to read a protocol before you trust it.

3 hours18 slides6 min read
Open slidesRead study notes

You Will Be Able To

  • Explain how a constant product automated market maker prices a swap.
  • Describe how overcollateralized lending and liquidation protect a lending pool.
  • Compare the main designs of stablecoins and their failure modes.
  • Explain why smart contracts need oracles and how oracle manipulation works.
  • Assess a DeFi protocol for smart contract, economic and governance risk.

What Decentralized Finance Means

In week 7 you saw that a token is a ledger inside a contract, and that approve plus transferFrom lets other contracts move tokens for you. Decentralized finance, usually shortened to DeFi, is the set of financial services built on that idea. Contracts hold the tokens, apply the rules, and settle every action in the same transaction.

Traditional finance relies on institutions to match buyers and sellers, hold collateral and keep records. A DeFi protocol replaces many of those steps with code that anyone can call. You do not open an account. You connect a wallet and send a transaction. The price you pay for this openness is that you carry more responsibility, since no support desk can reverse a mistake.

DeFi Building Blocks
BlockPurposeExample
AMMSwap tokens from a poolUniswap
Lending poolBorrow against collateralCompound, Aave
StablecoinToken aiming at a stable priceDAI, USDC
OracleBring outside prices on chainChainlink

Blocks can be combined, which is called composability. Source: Protocol documentation

Automated Market Makers

A traditional exchange keeps an order book: a list of buy offers and sell offers. An automated market maker, or AMM, uses a different idea. A pool contract holds reserves of two tokens, and a formula sets the price. Anyone can swap by adding one token to the pool and taking the other out.

The simplest formula is the constant product rule. If the pool holds x units of token A and y units of token B, every swap must keep the product x times y from falling. Suppose a pool holds 1000 A and 1000 B. A trader who adds 100 A cannot take out 100 B. After the swap the pool holds 1100 A, so B must fall to about 909.09, and the trader receives about 90.91 B. The more you buy relative to the pool size, the worse your price. That price change is called slippage.

Anyone can deposit both tokens into a pool and become a liquidity provider. In return they receive pool shares and a part of the swap fees, which is often a fraction of a percent per trade. Providers face impermanent loss: if the price of one token moves a lot against the other, the provider ends up with less value than if they had simply held both tokens. The fees may or may not make up for that.

Constant Product Curve
units of token Y
02856841121005025201010204050100

Illustrative: pool where x times y equals 1000. Fewer X in the pool means each X costs more Y. Source: Constant product formula x*y=k

A Swap In An AMM
  1. Trader sends token X
  2. Pool adds X
  3. Formula sets new Y amount
  4. Pool pays out Y
  5. Price moves a little

The pool keeps the product of its reserves constant, apart from fees.

Lending And Borrowing

Lending protocols let people deposit tokens to earn interest, and let others borrow those tokens. Everyone uses the same pool, so there is no individual negotiation. The interest rate usually rises as more of the pool is borrowed, which draws in new deposits and discourages new loans.

Because the protocol does not know who you are, it cannot chase an unpaid debt. It uses collateral instead. To borrow 100 units of a stablecoin, you might need to lock 150 units worth of another token. This is overcollateralization. Each asset has a collateral factor, which sets how much you may borrow against it.

If the collateral price falls and your loan becomes too large compared with it, anyone can liquidate your position. A liquidator repays part of your debt and receives your collateral at a discount. The discount pays for the service. This keeps the pool solvent as long as prices move slowly enough and liquidators can act. In a very fast crash, liquidations can fail, and the pool can be left with bad debt.

Stablecoins

Prices of most crypto assets swing widely, which makes them awkward as money. A stablecoin aims to hold a steady value, usually one US dollar. There are three main designs, and each has different risks.

Fiat-backed stablecoins are issued by a company that holds bank deposits and short-term securities as reserves. They are simple, but they depend on the issuer and its custodians, so you carry counterparty risk. Crypto-collateralized stablecoins, such as the dollar token of the Maker protocol, are minted when users lock more crypto than they borrow, using the same liquidation ideas as above. Algorithmic stablecoins try to hold the price with incentives and a companion token, with little or no collateral. Several have lost their peg, and the TerraUSD collapse in 2022 is the best-known case. The lesson is that stability needs real assets or real demand behind it.

When you review a stablecoin, ask three questions: what backs it, who can redeem it and at what price, and what happens if a large number of holders ask for redemption at the same time.

Oracles

A smart contract can only see what is on the chain. It does not know the price of ether in dollars, the weather or the result of a match. An oracle is a service that brings outside data onto the chain so contracts can use it. Lending protocols depend on price oracles to decide when to liquidate.

Oracle design is a security question. If a protocol reads its price from one small AMM pool, an attacker can move that pool with a large trade, borrow against the false price in the same transaction and leave. Safer designs combine many sources, use averages over time, or rely on a network of independent reporters, such as Chainlink. A contract can also set limits, such as pausing if the price jumps beyond a set range in one block.

Composability

Every DeFi contract is public and speaks the same token standards. That lets developers combine them like building blocks, which people call composability or 'money Lego'. A single transaction can borrow from one pool, swap on a second, deposit into a third and repay the first.

A flash loan shows the idea well. A flash loan lends any amount with no collateral, on one condition: the borrower must repay within the same transaction. If repayment fails, the whole transaction reverts as if it never happened. Traders use flash loans to move collateral or rebalance positions. Attackers use them to get temporary capital for price manipulation. Composability brings speed and invention, and it also means that a flaw in one contract can spread to every protocol built on top of it.

Risks And How To Reason About Them

DeFi risk has several layers. Smart contract risk is a bug in the code. Economic risk is a design that fails under stress, even if the code is correct. Oracle risk is bad data. Governance risk appears when token holders or a small team can change the rules, for example through an admin key or a proxy upgrade. Market risk includes slippage, liquidation and impermanent loss. Finally, front-running is a known problem: block builders and bots can see pending transactions and reorder them to take profit, which is part of what is called MEV, or maximal extractable value.

A practical review looks at the following points before any money moves. Read the protocol documentation. Check whether the code has been audited, and by whom, and whether the audit report lists open issues. See who holds admin powers and whether a time delay protects users from sudden changes. Look at how long the protocol has been running and how much value it has held. Start with an amount you can afford to lose, and use a test network first for learning.

Week 10 returns to many of these topics in more detail, including reentrancy and audits. For now remember the habit: before you ask what a protocol could earn you, ask how it could fail.

Key Terms

Automated market maker
A contract that holds two token reserves and sets swap prices with a formula instead of an order book.
Liquidity provider
A user who deposits tokens into a pool and earns a share of its swap fees.
Slippage
The difference between the expected price and the price you actually get because your trade moves the pool.
Impermanent loss
The value a liquidity provider gives up compared with simply holding the tokens when prices diverge.
Overcollateralization
Locking more value as collateral than the amount borrowed, to cover price drops.
Liquidation
The forced sale of a borrower's collateral to repay debt when the loan becomes too risky.
Stablecoin
A token designed to keep a steady value, usually one unit of a national currency.
Oracle
A service that delivers outside data, such as prices, to smart contracts.
Flash loan
An uncollateralized loan that must be borrowed and repaid within a single transaction.

Exercise: Simulate A Constant Product Pool

  1. Install Python 3 or open an online Python notebook, and create a file named amm.py.
  2. Paste the quote function from the slides and set the pool to 1000 token A and 1000 token B.
  3. Print the output for swaps of 10, 100 and 500 token A. Note how the price per unit worsens as the size grows.
  4. Update the reserves after each swap and repeat the 100 token trade. Observe that the second trade pays a different price.
  5. Open a public lending protocol's documentation page and find its collateral factor and liquidation discount for one asset. Write them down.
  6. Write five lines on one DeFi protocol: what backs it, who holds admin powers, whether it has an audit, and one way it could fail.

Further Reading