Crypto OS
Non-Technical Crypto OSStage 3 · How Crypto Recreates Finance

Chapter 14 · How a DEX Works Without a Central Exchange

Who sets prices when no market maker sits in the middle?

Capabilities practiced
Financial LiteracyOnchain Literacy
Hands on
On a DEX, inspect the depth of one pool, simulate buying $100 and $100,000, and record the slippage for each.
AI Lab
Have AI calculate a quote using the constant-product formula. Recalculate it by hand from a pool's real reserves and compare.

A Real-World Problem

At three in the morning, you want to buy a token launched a few hours ago.

On a traditional exchange, someone must have posted a sell order. Often these are specialist firms, quoting both buy and sell prices, earning the spread, and controlling risk through speed and inventory management. Their focus is volume rather than market direction.

They have strict requirements: quotes must be fast, and cancellations faster. When markets move, stale orders must disappear within milliseconds or others exploit them. Millions of daily cancellations are normal for a market maker.

Move this on-chain. Blocks arrive seconds apart; each order and cancellation is a transaction requiring Gas, a queue, and advance public visibility.

Traditional market makers cannot survive in this environment.

Yet on-chain tokens trade around the clock. If nobody quotes prices, who sets them?

Thought Experiment

Imagine an unattended stall.

Two boxes contain 100 apples and 1,000 dollars. A sign states one rule:

Take from either box, but afterward the product of the amounts in both boxes must remain unchanged.

That product is 100 × 1000 = 100000.

To buy 10 apples, you leave 90. The money box must then hold 100000 ÷ 90 ≈ 1111.11 dollars. You must add $111.11.

The apparent quote is $10 per apple, but buying 10 costs $111.11, averaging $11.11.

Buy 50 instead. With 50 apples remaining, the money box must hold $2,000. You pay $1,000, averaging $20: twice the displayed price.

Larger purchases cost more per apple. The box never empties: taking all 100 requires infinite money.

The stall always quotes a price without an attendant; that price depends entirely on the ratio of inventory in the boxes, independently of outside markets; and your trade moves the quote, always against you.

This rule powers the slider from Chapter 13. Here we study its operation and a more pressing question: who put the assets into the boxes?

Your Decision

You hold $5,000 of a token and $5,000 of stablecoins.

An on-chain pool invites you to deposit the full $10,000 as a liquidity provider. Each trade pays a fee distributed proportionally to you. The displayed annualized return looks attractive.

What do you do?

What Happens

Replace the stall with realistic numbers.

A pool contains 1 ETH and $1,000 of stablecoins while ETH trades at $1,000. Total value is $2,000. Your share is half; to simplify the calculation, assume you own the entire pool. Its product is 1000.

ETH rises to $4,000 outside the pool. The pool still has its old ratio. Arbitrageurs buy its cheap ETH with stablecoins until its price also reaches $4,000.

The pool then contains 0.5 ETH and $2,000.

  • Pool value: 0.5 × 4000 + 2000 = $4,000
  • Value from simply holding: 1 × 4000 + 1000 = $5,000

A $1,000 difference: 20%.

This difference is structural, regardless of whether fees cover it. Calculate several scenarios:

ETH price changeHolding valueLP valueDifference
Unchanged ($1,000)200020000
Doubles ($2,000)30002828−5.7%
Quadruples ($4,000)50004000−20%
Halves ($500)15001414−5.7%
Falls 90% ($100)1100632−42.5%

Notice three things:

  1. Whenever the price leaves the entry ratio, the difference is negative, whether rising or falling.
  2. It depends on the price-change multiple, not direction. Doubling and halving give the same percentage difference.
  3. Returning to the original price eliminates the difference. That is the entire reason for the name "impermanent," which has misled many people.

It is not merely a temporary loss. It is the gap between providing liquidity and holding. Without a price reversal, it persists; withdrawal locks it in. It also need not mean a loss of principal. After a 90% token decline, an LP loses money, but holding also loses money, by a smaller amount.

A more useful description: LP positions earn less during rises and lose less during falls, surrendering large directional gains in exchange for fees.

Who supplies liquidity? People who deposit real assets and accept the table above. Move the sliders to see what traders pay:

You receive
45,455 tokens
Execution price above market
10.00%
Pool price increase after trade
21.00%

No market maker sets this quote. The x·y=k curve determines the price. A shallower pool and a larger purchase move your price further from the market price; arbitrageurs and liquidity providers capture that difference.

Minimum depth and maximum trade size can push average execution tens of percentage points away from market price. That money splits between fees paid to LPs and arbitrage profits that restore the market price. The arbitrageurs' gain is precisely the LPs' shortfall.

  1. External price changes
  2. Pool price lags
  3. Arbitrageurs buy its cheaper asset
  4. Pool price realigns
  5. The difference moves from LPs to arbitrageurs
This cycle occurs thousands of times daily. It keeps pools aligned with markets, at LPs' expense.

Build a Model

Compare an order book with this stall to understand what the AMM replaces:

Order-book exchangeAMM pool
Price sourcePosted ordersMathematical curve
Quote updatesActive cancellation and repricingEach trade moves the price
No operator presentNo executionTrading continues
Liquidity providerMarket makers who can cancelLPs who withdraw through transactions
Large-order costCrossing multiple order levelsMoving along the curve
External price alignmentMarket makers repriceArbitrageurs realign
Provider incomeBid–ask spreadFees
Provider riskDirectional inventory exposurePrice divergence

One requirement remains: someone must supply real assets. AMMs remove the person quoting prices, not the capital provider.

LP returns have four components. Most interfaces show only the first:

ComponentSignWho paysLargest when
Trading fees+Pool tradersVolume is high
Token subsidies+Subsidizing protocolProjects seek higher TVL
Price divergence−Arbitrageurs extract it from youLarge directional moves
Gas and operating costs−YouFrequent entry and exit

Remember: fees and divergence often increase simultaneously. Volatility raises volume and fees while also producing large price moves and larger shortfalls. They arrive together rather than offsetting predictably. Which dominates cannot be known in advance; reconcile afterward.

What It Is Called

Order BookOrder Book

Buy and sell orders arranged into two price-ranked columns, matched when their prices meet.

It requires people willing to post orders continuously. Without them, it is an empty table.

Market MakerMarket Maker

A participant quoting both sides and earning the spread. Their service is the availability of a counterparty, rather than a prediction of market direction.

High Gas costs and seconds between blocks make traditional market making difficult on-chain, motivating AMMs.

AMMAutomated Market Maker

A mechanism replacing manual quotes with a formula. Anyone can trade against it at any time, with prices determined by reserve ratios.

Its key property is permissionless access: no listing application or market-making approval is required. Anyone can create a pool for two tokens, enabling newly launched tokens to trade within hours.

x·y=kConstant Product

The most common curve keeps the product of two asset reserves constant.

Two properties: the pool never sells out, since price approaches infinity; and larger trades cause greater price divergence. Chapter 15 turns the second into a practical formula.

Later variations optimize stablecoin trading or concentrate funds within price ranges, but retain related trade-offs.

LPLiquidity Provider

Someone who deposits two assets proportionally and receives a claim representing a pool share, redeemable at its current ratio.

Note that current ratio: depositing 1 ETH and $1,000 rarely returns that same combination. You deposit assets and withdraw a share of the pool.

Impermanent LossImpermanent Loss

The difference between an LP position's value and holding the same original assets.

Remember: it is not necessarily temporary, because it persists until prices return and becomes fixed on withdrawal; not necessarily a principal loss, but a shortfall relative to holding, while falling markets can reduce absolute losses; and independent of direction, depending on the price multiple.

Divergence Loss is a clearer name. "Impermanent" has drawn many people into misunderstanding the risk.

Hands-on

Hands onTwo order sizes in the same poolAny DEX trading interface and a block explorerFree; inspect quotes without confirming

No funds are needed. Enter amounts and read quotes; never press the final confirmation button.

Choose a pool. Pick a pair with moderate activity. Huge pools hide the effect; tiny ones exaggerate it. Record both reserves and the current price.

Quote a $100 purchase. Record tokens received, displayed slippage or price impact, and fees.

Quote a $100,000 purchase. Change only the amount and record the same three numbers.

If slippage scaled linearly, this would buy 1,000 times as many tokens. How many does it actually buy?

Calculate it yourself. Use the reserves to calculate the $100,000 purchase:

Before purchase: x tokens, y stablecoin dollars; k = x × y
After adding A dollars: stablecoins = y + A
                       remaining tokens = k ÷ (y + A)
Tokens received = x − k ÷ (y + A)

Compare with the interface. Differences should come from fees and reserve changes during observation. If they do not match, find the missing step; that is more valuable than a correct calculation alone.

Complete the comparison.

Buy $100Buy $100,000
Tokens received
Execution premium over market
Increase in pool price
Manual calculation matches?

Then answer: what order size makes execution 10% worse than market price? Remember that scale; Chapter 15 uses it throughout.

AI Lab

AI LabAsk AI for a constant-product quote and check it with real reservesLevel 2 · AI Copilot

Supply real reserves from the previous Lab and request calculations, not just answers:

A constant-product pool has [X] tokens and [Y] stablecoin dollars.
Its fee rate is [F]%.

Calculate token purchases with 100, 10000, and 1000000 stablecoin dollars.
For each, provide:
- Tokens received
- Average execution price
- Percentage premium over the initial price
- Final pool price and change from the original price
- Fee deduction step and amount

Show each equation with substituted numbers.
Then explain in one sentence why 100 times the input buys far less than
100 times the tokens.

Then recalculate the middle case yourself with a calculator.

The model should be able to solve constant-product arithmetic without research or internet access. If it errs here, mistakes involving real-world data will be harder to spot.

Common errors: deducting fees incorrectly, confusing average execution deviation with price impact, and silently introducing a market price different from your reserves. The third is dangerous because the answer can look entirely plausible.

Verify these points yourself after using AI

  • Did it use the two reserve amounts you supplied?
  • Did it include fees, and deduct them at the input or output stage?
  • Does its slippage mean average execution deviation or the change in final pool price? These differ.
  • Does ten times the input produce clearly less than ten times the output?
  • Did it dismiss impermanent loss by saying prices will eventually return?
  • Does the output remain bounded when input equals 100 times the stablecoin reserve?

Real-World Case

A few hundred lines replace a market-making teamSince 2018

Early constant-product exchange contracts used only a few hundred lines of core logic, with no matching engine, order book, market maker, or listing review.

Their greatest change was access: previously, exchanges and market makers decided whether an asset could trade. Now anyone could create a pair within minutes.

The same opening also admitted scams. Chapters 22 and 24 explore that cost.

Subsidies attract liquidity and can take it awaySince 2020

Many protocols subsidized LPs with newly issued tokens, displaying enormous annualized rates. Liquidity genuinely arrived.

Competitors then offered larger subsidies and moved entire groups of LPs within days. When subsidy tokens fell in price, fee income no longer covered divergence, and LPs departed.

The lesson: subsidized liquidity is loyal to the subsidy difference. Chapter 17 examines this further.

A trader's slippage becomes someone else's profitOngoing

Public pending transactions let others buy before a large order and sell after it, capturing its slippage. These activities fall under MEV.

Understand that this value already exists: it is the price deviation traders pay in shallow pools. AMM structure creates it; the question is who captures it: arbitrageurs, LPs, validators, or front-running bots. Chapter 24 treats MEV separately.

Concentrated liquidity increases efficiency and riskSince 2021

Later designs let LPs concentrate capital within a price range, multiplying depth within it.

Once price leaves the range, the position becomes entirely the weaker-performing asset and stops earning fees. Greater capital efficiency also magnifies divergence loss. This becomes a position requiring active management.

Change One Variable

What ifFees fall from 0.3% to 0.05%

Trading becomes cheaper and volume likely rises.

But LP income shrinks while divergence costs remain. Capital moves to higher-fee or less volatile pools, reducing depth and increasing slippage. Traders may end up paying no less.

Fee rates balance attracting traders with retaining LPs, explaining why assets with different volatility use different tiers.

What ifNo arbitrageurs exist

The pool stays at its last execution price. The first person buying an asset there at half the market price becomes an arbitrageur. Arbitrage is an inevitable role, not merely a profession.

Ask instead: if expensive Gas or insufficient capital makes arbitrage uneconomic, how long does the pool remain disconnected? Does its displayed price still meaningfully represent a price?

What ifLPs can withdraw free before prices move

Divergence disappears because LPs stay only for favorable conditions.

But LPs and arbitrageurs see the same data. If LPs always withdraw before repricing, that repricing never occurs in the pool, which loses its quoting function.

Divergence is an unavoidable cost of replacing quotes with inventory. For any design claiming to eliminate it, investigate where that cost moved.

What ifThe curve becomes extremely flat near 1:1

Depth increases and slippage falls near parity, benefiting equivalent assets such as two dollar stablecoins or an asset and its staking claim.

The price is that a depeg lets the flat region keep exchanging good assets for bad near 1:1, rapidly leaving LPs with only the impaired asset.

Chapter 13's reserves-and-redemption question returns: the curve assumes equality, while real equality is conditional.

Takeaway Questions

8
Who supplies liquidity?

AMMs remove manual quoters, not capital providers. Ask: whose money is in the pool, why is it there, and would it remain if fees and subsidies vanished?

5
Who is paying?

Traders pay LP fees; arbitrageurs capture LP divergence. Together they explain both sides of the LP's income and loss. Trace both to understand the pool.

10
What is the incentive?

Token subsidies commonly incentivize LPs. Ask how many tokens are issued daily, which price converts them into annualized yield, and when issuance ends. Chapter 17 shows that interfaces often use the subsidy token's current price, while issuance itself depresses that price.

9
Who bears the risk?

LPs bear divergence, contract exploit, and worthless-token risks. Traders bear slippage and front-running. An LP is a passive counterparty trading against the trend, rather than a depositor.

Chapter Check

Key idea

An AMM replaces human quote makers with a curve, but someone still has to provide real capital for liquidity.

Finished this chapter’s lab? Mark it completeView all progress

On this page