🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

DeFi Mechanics: AMMs, Liquidity Pools, and Real Risks

DeFiđŸŸĸ Free Lesson
DeFi

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:

python
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.

python
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 moveImpermanent lossFee 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:

SourceWho paysSustainabilityTypical example
Trading feesTradersHigh, proportional to volumeUniswap LP fees
Borrow interestBorrowersHigh, utilization-dependentAave supply APY
Liquidation bonusesLiquidated borrowersModerate, event-drivenLiquidation kickers
Token emissionsThe protocol's inflation scheduleLow, decays as rewards dilute"Reward rate" on new farms
Real-world yieldOff-chain businessesDepends on disclosureTokenized 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.

DesignPeg mechanismFailure modeWhat to watch
Fiat-backedReserves and redemptionsCustodian freeze or reserve gapAttestation frequency
Crypto-collateralizedOver-collateralized vaultsCascading liquidations in a crashCollateral ratio and diversity
Liquid staking derivativeMarket peg plus redemptionDiscount widening under exit pressureWithdrawal queue depth
AlgorithmicOn-chain arbitrage between tokensDeath spiralPeg 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.

RiskMechanismHistorical example patternMitigation
Smart contractCode bug drains the poolReentrancy and logic bugsAudited code, bug bounties, time-locked caps
OracleManipulated price triggers bad liquidationsThin DEX pools used as price sourceTWAPs, multiple feeds, sanity bounds
GovernanceToken holders vote to upgrade and drainHostile or compromised proposal passingTimelocks, multisig vetoes
LiquidityLarge exit moves the market against youBank-run withdrawal spiralsPosition sizing, depth checks
MarketUnderlying asset collapsesDepeg of collateralDiversified 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement