The one-line mental model
Decentralized finance reimplements lending, exchange, and derivatives as composable smart contracts holding pooled collateral, which removes intermediaries and simultaneously removes the safety nets those intermediaries used to provide.
Prerequisites
- !ERC-20 tokens: transfer, approve, and allowance
- !How a liquidity pool differs from an order book at a conceptual level
What You'll Learn
- 1Compute the execution price and price impact of a swap in a constant-product pool
- 2Derive impermanent loss from a price ratio and explain why it is not a fee
- 3Identify the four independent sources of risk in a typical deposit
- 4Decompose a headline APY into its sustainable and unsustainable parts
Permissionless composition changes the economics
An ERC-20 token is a public database table with a transfer function, and a pool is a contract holding two of them. Because anyone can call anyone, DeFi protocols stack like Lego: a loan collateralized by an LP position, which itself earns fees from trades routed by an aggregator, which reports prices through an oracle that a derivatives protocol consumes. That composability is the entire value proposition and also the entire contagion mechanism.
The practical consequence is that risk compounds. A token that is safe in isolation can become toxic when a lending market lists it, because the lending market's liquidations now create sell pressure that feeds back into the price of the collateral. Reading a protocol in isolation is therefore insufficient; the question is always what else is plugged into it.
The constant-product market maker, with numbers
Uniswap-style pools hold reserves of two assets and enforce the invariant that the product of those reserves never decreases across a trade. Setting aside fees for a moment, a swap that removes dy of token Y must add enough of token X to restore the product:
def swap_out(amount_in, reserve_x, reserve_y):
"""Constant-product swap: x * y = k, 0.3% fee applied on input."""
dx = amount_in * 0.997
return (reserve_y * dx) / (reserve_x + dx)
def price_impact(amount_in, reserve_x, reserve_y):
spot = reserve_y / reserve_x
execution = swap_out(amount_in, reserve_x, reserve_y) / amount_in
return 1 - execution / spot
pool_x, pool_y = 1_000_000, 1_000_000 # 1M / 1M, so spot price is 1.0
out = swap_out(10_000, pool_x, pool_y)
print(f"you receive {out:.2f} Y") # about 9,891.2 Y
print(f"price impact {price_impact(10_000, pool_x, pool_y) * 100:.3f}%") # about 0.99%
Two lessons fall out immediately. Small trades pay almost nothing in slippage, large trades pay a lot, because impact grows with the trade's size relative to the reserve depth. And liquidity depth, not headline volume, is what protects your execution: a pool with 10Ã the reserves gives 10Ã worse attackers a much harder time and 10Ã better prices to ordinary users.
Impermanent loss, derived
Liquidity providers deposit both assets in the pool's current ratio. When the market price of an asset moves, arbitrageurs rebalance the pool, and the LP ends up holding proportionally more of the falling asset than a simple holder would. The gap is called impermanent loss, and it becomes permanent the moment you withdraw.
def impermanent_loss(price_ratio):
"""price_ratio = current external price / price when you deposited."""
r = price_ratio
return 2 * (r ** 0.5) / (1 + r) - 1
for move in (1.1, 1.5, 2.0, 3.0):
print(f"{move:.1f}x move -> IL {impermanent_loss(move) * 100:.2f}%")
| External price move | Impermanent loss | Fee buffer needed |
|---|---|---|
| 1.10x | â0.08% | Roughly one week of average fees |
| 1.25x | â0.60% | A few busy days of fees |
| 1.50x | â2.02% | Sustained volume for weeks |
| 2.00x | â5.72% | Often never recovered |
| 3.00x | â13.40% | Effectively a permanent haircut |
This is why single-sided exposure to a volatile pair is a bet, not a savings account. Stablecoin pairs such as USDC against DAI barely move relative to each other, so their impermanent loss is negligible and their return comes almost entirely from trading fees â which is exactly why stable pools attract most passive liquidity.
Where yield actually comes from
No protocol mints yield from nowhere. Every APY decomposes into a payment made by someone else for a service you provided:
| Source | Who pays | Sustainability | Typical example |
|---|---|---|---|
| Trading fees | Traders | High, proportional to volume | Uniswap LP fees |
| Borrow interest | Borrowers | High, utilization-dependent | Aave supply APY |
| Liquidation bonuses | Liquidated borrowers | Moderate, event-driven | Liquidation kickers |
| Token emissions | The protocol's inflation schedule | Low, decays as rewards dilute | "Reward rate" on new farms |
| Real-world yield | Off-chain businesses | Depends on disclosure | Tokenized treasuries |
When a dashboard shows 40% APY, check how much is emissions. A reward token falling 80% in a year turns that 40% into a modest fee yield plus a large unrealized loss, and the first depositors are often being paid with later depositors' capital â the signature of a scheme rather than a market.
Stablecoins: the collateral question
Stablecoins are the settlement layer of DeFi, and they differ in exactly one dimension that matters: what makes the peg hold. Fiat-backed tokens like USDC rely on a custodian and periodic attestation. Crypto-collateralized tokens like DAI over-collateralize volatile assets and rely on liquidations to keep solvency. Algorithmic designs that rely on arbitrage between two tokens have repeatedly lost the peg under stress, so treat "stable" as a claim to be verified rather than a property.
| Design | Peg mechanism | Failure mode | What to watch |
|---|---|---|---|
| Fiat-backed | Reserves and redemptions | Custodian freeze or reserve gap | Attestation frequency |
| Crypto-collateralized | Over-collateralized vaults | Cascading liquidations in a crash | Collateral ratio and diversity |
| Liquid staking derivative | Market peg plus redemption | Discount widening under exit pressure | Withdrawal queue depth |
| Algorithmic | On-chain arbitrage between tokens | Death spiral | Peg depth under load |
Routing, aggregators, and MEV
Because many pools coexist for the same token pair, a single order can be split across them to reduce impact. Aggregators solve this continuously: they query several pools, compute a route, and often split a trade across two or three venues so the blended execution price beats anything one pool could offer. For retail-sized orders the gain is usually a few basis points; for size, it can be the difference between a good fill and a badly degraded one.
The same transaction stream that aggregators read is also read by searchers running automated bots, and the ordering of transactions inside a block is a market of its own â maximum extractable value. A large swap visible in the mempool invites a front-run, where a bot trades ahead of you, and a back-run, where it trades right after you to capture the price impact you created. Protection ranges from simple (private transaction relays that keep your order out of the public mempool) to structural (limit-style orders that execute only at a stated price). Anyone routing size through public pools without one of those protections is, in effect, paying a voluntary tip to whichever bot sees the transaction first.
The risk matrix nobody prints on the box
Depositing into a protocol exposes you to independent risks that must be evaluated separately, because a single 100% loss in any one of them ends the position.
| Risk | Mechanism | Historical example pattern | Mitigation |
|---|---|---|---|
| Smart contract | Code bug drains the pool | Reentrancy and logic bugs | Audited code, bug bounties, time-locked caps |
| Oracle | Manipulated price triggers bad liquidations | Thin DEX pools used as price source | TWAPs, multiple feeds, sanity bounds |
| Governance | Token holders vote to upgrade and drain | Hostile or compromised proposal passing | Timelocks, multisig vetoes |
| Liquidity | Large exit moves the market against you | Bank-run withdrawal spirals | Position sizing, depth checks |
| Market | Underlying asset collapses | Depeg of collateral | Diversified collateral, exit liquidity |
đĄReading an APY like an analyst
Split the displayed number into fees, interest, and emissions. If emissions dominate, ask what happens when the reward token's issuance halves. A fee-only APY of 3% that is honest is a better product than a 60% APY funded by inflation that ends in three weeks.
Common Mistakes
Treating a liquidity pool deposit as a yield-bearing savings account
Fix: Model impermanent loss against the price paths you expect, and treat fee income as compensation for a two-sided market-making bet
Chasing the highest APY on an unaudited fork
Fix: Check who wrote the code, whether an audit exists, whether admin keys can mint or pause, and how much TVL is already exposed
Assuming the displayed price is the price your trade executes at
Fix: Simulate the swap and compare execution price with spot; route large orders through aggregators or split them over time
Ignoring the governance surface of a protocol you deposit into
Fix: Read what the admin key or governor can do; if it can upgrade logic arbitrarily, your deposit is a bet on that key's honesty
Best Practices
- Prefer deep pools over high-APY thin ones; depth is what protects execution and exits
- Diversify across protocols that do not share collateral, oracle, or governance dependencies
- Track positions with a health-factor alert so liquidation risk never arrives as a surprise
- Keep a portion of stable exposure outside DeFi entirely so a protocol incident cannot freeze all liquidity
Interview Questions
Q1: Why does a large swap move the price more than a small one?
In a constant-product pool the price is the ratio of reserves, and each trade shifts both reserves. Impact scales with trade size relative to depth, so doubling the trade size more than doubles the impact.
Q2: Is impermanent loss a fee paid to the protocol?
No. It is an opportunity cost relative to simply holding the two assets, caused by arbitrage rebalancing the pool. Fees earned by the LP can offset it, which is the trade LPs are actually making.
Q3: What distinguishes sustainable DeFi yield from a Ponzi dynamic?
Whether an external party pays for a service. Trading fees and borrow interest come from users of the market; reward emissions funded by new depositors' capital do not, and they collapse when inflows stop.
Key Takeaways
- Constant-product pools price trades by reserve ratios, so depth determines slippage, not volume
- Impermanent loss is rebalancing cost against holding, and it scales with price movement distance
- Every APY decomposes into fees, interest, or emissions, and only the first two come from external users
- Stablecoin designs differ in what backs the peg, and that difference dominates their risk
- Smart contract, oracle, governance, and liquidity risks are independent and each can cause total loss