DeFi Explained: AMMs, Liquidity Pools & Smart Contracts
Decentralized Finance (DeFi) builds financial primitives — trading, lending, borrowing — using smart contracts on public blockchains, replacing institutional intermediaries with transparent, auditable code. The mathematics behind Automated Market Makers and the mechanics of impermanent loss are elegant enough to understand completely.
1. Smart Contracts
A smart contract is a program deployed to the Ethereum Virtual Machine (EVM) blockchain. Once deployed, its code is immutable and publicly readable. Execution is deterministic — every node in the network gets the same result. No single party controls it.
This enables trustless transactions: a DEX (decentralized exchange) can hold users' funds and execute swaps without requiring trust in any company, because the logic is provably correct from the code.
// Minimal ERC-20 transfer (Solidity)
function transfer(address to, uint256 amount) public returns (bool) {
require(balances[msg.sender] >= amount, "Insufficient balance");
balances[msg.sender] -= amount;
balances[to] += amount;
emit Transfer(msg.sender, to, amount);
return true;
}
Gas fees pay miners/validators for executing computation. Complex DeFi transactions can cost $5–$200 in gas on Ethereum mainnet during congestion. Layer 2 networks (Arbitrum, Optimism, Base) reduce this 10–100×.
2. ERC-20 Tokens
ERC-20 is the standard interface for fungible tokens on Ethereum. Any
ERC-20 token (USDC, UNI, LINK, SHIB) implements:
transfer(), approve(),
transferFrom(), balanceOf(),
allowance().
The approve + transferFrom pattern allows DeFi protocols
to spend tokens on your behalf: you first approve the DEX contract to
spend up to N tokens, then the DEX calls
transferFrom(you, pool, N) during a swap. This requires a
separate approval transaction before the first interaction with each
protocol.
3. Automated Market Makers (x*y=k)
Traditional exchanges use order books: buyers and sellers post limit orders and trades execute when prices match. Order books require liquidity providers (market makers) to post orders manually.
Uniswap V2 (2020) introduced the constant product AMM. A pool holds reserves of two tokens (x, y) and enforces:
The price automatically adjusts with every trade — no order book, no market maker. The curve x·y=k is a hyperbola: as x increases (buyers swap X for Y), y decreases and price of Y in terms of X rises (slippage).
Example: Pool has 1000 ETH and 2,000,000 USDC → ETH price = $2,000. Trader buys 10 ETH:
A 0.3% fee is charged on the input token and added to the pool reserves, increasing k over time — this is how liquidity providers earn fees.
4. Liquidity Pools and LP Tokens
Anyone can provide liquidity by depositing equal values of both tokens into the pool. They receive LP tokens representing their share of the pool. Example:
- Pool has $10M TVL (Total Value Locked). You deposit $1M (0.5 ETH + 1000 USDC in proportion).
- You receive LP tokens representing 10% of the pool.
- Your LP tokens entitle you to 10% of accumulated trading fees.
- At any time, burn LP tokens to withdraw your proportional share of the pool.
Uniswap V3 (2021) introduced concentrated liquidity: LPs can restrict their capital to a specific price range (e.g., $1,800–$2,200 for ETH/USDC). This concentrates capital where trades actually happen, increasing capital efficiency ~4000× for stablecoin pairs, but requiring active management.
5. Impermanent Loss
When the external market price of one token changes relative to the other, arbitrageurs trade against the pool until its price matches. This rebalancing changes the ratio of tokens held — LPs end up holding more of the token that fell and less of the one that rose, compared to simply holding both tokens.
IL is "impermanent" — if the price returns to its original ratio, IL disappears. It only crystallizes when you withdraw. In volatile asset pairs, IL often outweighs trading fee income. IL is minimal for stablecoin pairs (USDC/USDT) where price ratio stays near 1.
6. Lending Protocols
Aave and Compound allow overcollateralized lending: deposit 3 ETH worth $6,000, borrow up to $4,500 USDC (75% collateral factor). Interest rates adjust algorithmically based on utilization rate (borrowed / supplied):
If collateral value falls below the liquidation threshold (e.g., borrowed/collateral > 80%), a liquidation bot repays part of the borrower's debt and seizes their collateral at a 5–10% discount. This keeps the protocol solvent without a central credit team.
Flash loans: borrow any amount from an Aave pool within a single transaction with zero collateral, as long as it is returned by the transaction's end. Used for arbitrage, self-liquidations, and collateral swaps.
7. Risks in DeFi
- Smart contract bugs: The Ronin bridge hack ($625M, 2022) exploited a validator key compromise. DAO hack ($60M, 2016) exploited reentrancy. Audits reduce but do not eliminate risk — Curve Finance ($73M, 2023) was audited.
- Oracle manipulation: DeFi protocols rely on price oracles (Chainlink, Pyth, or on-chain TWAP). Flash loan attacks manipulate spot prices in thin AMM pools to corrupt oracle data within one block.
- Rug pulls: Malicious developers drain liquidity pools after attracting capital. Common in anonymous teams on new chains.
- Regulatory: SEC enforcement, OFAC sanctions (Tornado Cash). Stablecoin regulation bills actively debated in US, EU, UK.
- MEV (Maximal Extractable Value): Block builders can order, insert, or censor transactions. Sandwich attacks front/back-run large swaps, extracting value from users.