web3.path

PHASE 11 DeFi · ~4 hours

DeFi Concepts

DeFi is finance rebuilt as open, composable smart contracts. If you squint, it's just stateful microservices trading tokens with ruthlessly-enforced math.

Goal — understand AMMs, liquidity provision, lending, staking, and build a working constant-product simulator.

1. The four building blocks

PrimitiveAnalogyExample
AMM (DEX)Automated market makerUniswap
LendingPawn shop with mathAave, Compound
StablecoinsPegged currencyUSDC (fiat-backed), DAI (crypto-collateral)
Yield / stakingSavings account with riskLido, Curve

2. AMM — the x·y = k magic

Instead of an order book, Uniswap v2 keeps a pool of two tokens. Price is defined by a constant-product invariant:

$$x \cdot y = k$$

To buy Δy of token Y, you deposit enough X so that new product ≥ k. Slippage emerges naturally: buying more moves the price.

# Python simulator
def swap_x_for_y(x, y, dx, fee=0.003):
    dx_net = dx * (1 - fee)
    dy = (y * dx_net) / (x + dx_net)
    return x + dx, y - dy, dy    # new reserves, amount out

x, y = 1000, 1000        # 1:1 pool
x, y, out = swap_x_for_y(x, y, 10)
print(out, y/x)          # ~9.87 Y out, new price ~1.02
Analogy — imagine a scale with water on both sides: pour into side X, side Y rises, but the next cup pours less effectively. The curve self-balances; no human market maker needed.

3. Liquidity providers (LPs)

Anyone can deposit equal value of X and Y; the pool mints LP tokens representing a share. Fees (0.3% per swap on v2) accrue to LPs. Redeem LP tokens → get back proportional slice of pool.

Impermanent loss — if the price of X moves relative to Y, holding X and Y separately would've been worth more than the LP position. It's "impermanent" only if the price returns; otherwise it's just loss.

4. Uniswap v3 — concentrated liquidity

Instead of liquidity spread from 0 to ∞, LPs specify a price range. Capital efficiency jumps ~1000× but requires active management. Think "limit orders that earn fees while waiting".

5. Lending (Aave / Compound)

Supplier deposits 1 ETH → earns interest from borrowers Borrower locks 1.5 ETH as collateral → borrows 1000 USDC at variable rate If collateral value / debt < liquidation threshold → anyone can liquidate (bonus)

6. Flash loans

Borrow any amount within one transaction with zero collateral. If you don't repay by the end, the entire tx reverts — so the loan either succeeds or never happened.

// pseudo
function flashLoan(IERC20 token, uint256 amount, bytes calldata data) external {
  uint256 before = token.balanceOf(address(this));
  token.transfer(msg.sender, amount);
  IBorrower(msg.sender).onFlashLoan(token, amount, data);
  require(token.balanceOf(address(this)) >= before + fee, "not repaid");
}

Legitimate use: arbitrage, collateral swaps, liquidations. Malicious use: oracle manipulation (Phase 10).

7. Stablecoins — three flavors

TypePeg mechanismRisk
Fiat-backed (USDC, USDT)1 token ↔ 1 USD in bankIssuer freezes, bank fails
Crypto-collateralized (DAI)Overcollateralized ETH → mint DAICollateral crash
Algorithmic (failed mostly)Code tries to maintain pegDeath spiral (see UST/LUNA, 2022)

8. Staking & yield

9. Composability — "money legos"

Because every contract is on the same chain with public ABIs, you can chain them in one tx: flash-loan USDC → deposit to Aave → borrow ETH → swap on Uniswap → supply to Curve LP → repay flash loan. This is why DeFi UX is "a bundle of calls", not a sequence of services.

Analogy — it's the Unix pipe model for money. Each contract is a small program, stdout of one is stdin of the next, all in one atomic operation.

10. Project

Deliverable — (a) in Python, simulate a v2 AMM pool with LP share accounting, and compare HODL vs LP returns across a month of price data (use any CSV). (b) in Solidity, implement Pool.addLiquidity / removeLiquidity / swap with mint/burn LP tokens. Fuzz-test the invariant x·y ≥ k.

Quiz

Q. A pool has 10 ETH and 20,000 USDC (x·y = 200,000). Someone swaps 1 ETH in (ignoring fees). What's the USDC out?
(10+1)·(20000−Δ) = 200,000 → Δ = 20000 − 200000/11 ≈ 1818. The curve, not a price feed, defines the trade.
← Phase 10Phase 12: Layer 2 →