inkspell
writing topics feed
MODE
THEME
← writing

The Making of an Automated Market Maker: Constant Product Under a Market Price

How arbitrage drains a fixed-price pool, the constant-product pool that limits the loss, and the properties that measure both.

November 3, 2026 · 16 min read
amm property-based-testing testing defi blockchain

A pool that trades at a fixed price passes every property about its own books and still loses money as soon as the market price moves. Anyone can buy from it at the old price and sell elsewhere at the new one, and they can keep doing it until a reserve is empty.

This is the second post in a series about automated market makers, the programs that let anyone swap one token for another without a person on the other side. The first post built a constant-sum pool and introduced properties (rules the code must keep for every input, checked on random cases). This one adds a market price to the model, measures what arbitrage takes from that pool, and replaces it with a constant-product pool. The code is in the same public repository, and the version described here is tagged ch02-model.

The first post called the pool’s two balances jars. From here on they’re reserves, which is what the code calls them.

A fixed price loses value when the market moves

The pool from the first post holds 100 gold and 100 silver and trades them one for one. Now gold trades for two silver everywhere else.

A trader pays the pool 100 silver and gets its 100 gold, then sells the gold elsewhere for 200 silver. They started with 100 silver and end with 200, and the pool’s gold reserve is empty.

No property from the first post fails. The total is still 200 coins, the trader got one coin for each coin they paid, and no reserve went negative. Those properties only look at coin counts, and the loss doesn’t show in coin counts.

It shows once the reserves are valued at the market price. Before the trade, the pool held 100 gold worth 200 silver plus 100 silver, so 300 in all. After it, the pool holds 200 silver. The trader’s 100 silver profit is exactly the pool’s loss, since no one else was involved.

Buying where something is cheap and selling where it’s dear is arbitrage. Nothing in the swap rules prevents it, and in a pool with a fixed price, nothing limits it.

Pool value at a market price, as a property

That valuation gives a property: at the market price, a swap never makes the pool worth less. First, the valuation itself:

poolValue goldPrice (Pool gold silver) =
  goldPrice * fromInteger gold + fromInteger silver

goldPrice is how many silver one gold is worth on the market, and it can be a fraction, such as 3/2. (fromInteger only converts the coin counts so they can be multiplied by a fraction.)

Then the property, for the constant-sum pool:

prop_sumValueNeverDecreases (Positive goldPrice) pool s =
  case CS.swap s pool of
    Left _           -> property True
    Right (_, pool') -> property (sumPoolValue goldPrice pool' >= sumPoolValue goldPrice pool)

Positive goldPrice asks for a random gold price above zero. CS.swap is the first post’s swap; the test file uses both pools, so it puts CS. in front of everything from the constant-sum one and CP. in front of the constant-product one, which comes next. sumPoolValue is the same valuation as poolValue, for that pool.

A case looks at which shape the swap gave back and picks a line: a refusal passes as it is (property True is a test that always passes), and a success has to leave the pool worth at least as much as before. A _ stands for a part the line doesn’t need, here the reason for a refusal and the amount paid out, and pool' (read “pool prime”) is the pool after the swap.

The property is expected to fail. One run printed this:

+++ OK, failed as expected. Falsified (after 6 tests and 6 shrinks):
Positive {getPositive = 2 % 1}
Pool {gold = 1, silver = 0}
Swap {direction = SilverForGold, amountIn = 1}

The test file wraps this property in expectFailure, so the suite passes only if QuickCheck finds a case that breaks it. That keeps a known weakness of the constant-sum pool in the suite as a checked fact, instead of a red test everyone learns to ignore.

The last three lines are the case: a price of 2 (2 % 1 is the fraction 2/1), a pool with one gold and no silver, and a swap of one silver for gold. The pool sells a coin worth two silver for one, and its value drops from 2 to 1. It’s the 100-coin trade above, at the smallest size that still fails.

QuickCheck found a failing case on its sixth try, probably with larger numbers. It then tried smaller versions of that case, kept each one that still failed, and stopped when none of the smaller versions it tried failed. That’s called shrinking, and “6 shrinks” means six of those steps worked. A shrunk case is usually small enough to show the cause directly.

Constant product moves the price with each trade

The constant-sum pool loses so much because its price never moves: it sells every coin at the same price until the reserve is empty. The fix many real pools use is to let the reserves set the price: the smaller a reserve, the more its coins cost.

The rule that does it is constant product. Multiply the reserves: 100 gold times 100 silver is 10,000. Call that number k. A swap has to leave k where it was. Pay in 10 gold, and the gold reserve holds 110. For 110 times the silver to stay 10,000, the silver reserve has to drop to 90.9…, so the pool owes you 9.09… silver. It can only pay whole coins, so it rounds down and pays 9. The reserves now hold 110 and 91, and their product is 10,010: a little more than before, because the rounding left a fraction of a coin in the pool.

You paid 10 gold and got 9 silver, and the next trader gets less: one gold is now worth 91 ÷ 110, or about 0.83 silver, in the pool. That ratio is the pool’s price. An actual swap always gets less than it, because the swap itself moves the price and then rounds down.

A pool on this rule can’t be emptied. Buying the pool’s last silver would take infinitely much gold, so every swap pays out less than the reserve holds. Uniswap’s first two versions use this rule with a fee added; this model has no fee yet.

Where the formula comes from, for the curious

Call the reserve you pay into reserveIn and the one that pays you reserveOut. After the swap, the first holds reserveIn + amountIn and the second reserveOut - amountOut, and their product must still be reserveIn * reserveOut. Solve that for amountOut:

amountOut = reserveOut * amountIn / (reserveIn + amountIn)

With 100, 100 and 10, that’s 1,000 / 110 = 9.09…. And since reserveIn + amountIn is always more than amountIn, the fraction is always less than reserveOut: you never get the whole reserve.

The swap function gets a minimum and two new refusals

Here is the new swap:

swap (Swap direction amountIn minAmountOut) (Pool gold silver)
  | amountIn <= 0                = Left AmountNotPositive
  | gold <= 0 || silver <= 0     = Left EmptyPool
  | amountOut == 0
    || amountOut < minAmountOut  = Left OutputTooSmall
  | direction == GoldForSilver   =
      Right (amountOut, Pool (gold + amountIn)
                             (silver - amountOut))
  | otherwise                    =
      Right (amountOut, Pool (gold - amountOut)
                             (silver + amountIn))
  where
    -- keep reserveIn * reserveOut, rounding down in the pool's favour
    amountOut = reserveOut * amountIn `div` (reserveIn + amountIn)
    reserveIn  = if direction == GoldForSilver then gold else silver
    reserveOut = if direction == GoldForSilver then silver else gold

Most of it is the first post’s function. The changes are in three places.

The swap has a third field, minAmountOut: the least the trader will accept. The price now moves with every trade, including other traders’ trades that land first, so the price you saw may not be the price you get. A swap that would pay less than the minimum is refused.

InsufficientLiquidity is gone, since no swap can ask for more than the reserve holds. Two refusals replace it. EmptyPool refuses to trade when a reserve holds nothing (|| means “or”). Without it, a pool with no gold and 100 silver would give you all 100 silver for one gold, because the formula divides by an empty reserve plus your one coin. OutputTooSmall refuses a swap that would pay nothing, or less than the minimum.

The where block does the arithmetic. reserveIn and reserveOut pick the reserves by direction, and amountOut is the formula. div divides and rounds down, and the backticks let it sit between its two inputs, like *. The text after -- is a comment, written for people and ignored by the computer.

Rounding down keeps the fraction in the pool. Rounding up would let a swap take up to one coin more than the rule allows, which is enough to take the last coin from a small reserve, and a trader could choose amounts that do it every time.

Run the 10 gold through it. Is 10 at most zero? No. Is either reserve empty? No. amountOut is 100 × 10 div 110, which is 9: not zero, and not below a minimum of 0. You’re paying gold, so the answer is Right (9, Pool 110 91).

The widget below runs the same function. Set an amount and a minimum, then step through the guards, or open Predict the result and work out each answer before you look. As in the first post, its code panel shows the rest of the file, type lines included.

The model has more names now, and some are easy to mix up: amountIn is a payment, reserveIn is a reserve, and which reserve it is depends on the direction. The 15 cards below test these names and the ideas behind them. A card you miss comes round again.

Larger trades get worse prices

In the pool of 100 and 100, paying 10 gold gets you 9 silver, or 0.9 for each gold. Paying 100 gets you 50, which is 0.5 each. Paying 1,000 gets you 90: 0.09 each, for a trade that’s ten times larger and gets less than twice as much. Every coin you pay in moves the price against the next one. This is price impact, and it’s the cost of a pool that can’t be emptied.

Pool size matters as much as trade size. In a pool of 10,000 and 10,000, the same 100 gold gets 99 silver. Deeper pools give better prices.

The top chart below draws this pool’s rule as a curve, next to the first post’s straight line. A trade is a step along it. The chart under it shows the price each trade size gets.

Rounding bends the lower chart at the small end. Pay 1 gold, and the pool owes you 0.99… silver, which rounds down to nothing, so the swap is refused. Pay 2, and you get 1 silver: 0.5 each. Pay 3, and you get 2: 0.67 each. The larger trade got the better price, because rounding took a bigger share of the smaller one. Rounding always takes less than one coin, so the larger the trade, the less it matters, but a property about prices has to allow for it.

Six properties for the constant-product pool

The first post’s four properties described a pool with a fixed price. Each has a counterpart here, and two are new:

  • The product of the reserves never goes down, where the sum used to stay the same. Rounding makes it grow a little.
  • What comes out is less than the reserve it comes from, where it used to equal what went in.
  • A round trip never profits: swap, then swap straight back, and you get back at most what you paid. It used to restore the pool exactly; now rounding can keep some, and in a lopsided pool or after a large trade, quite a lot.
  • Both reserves stay above zero, where they used to stay at zero or above.
  • What comes out is at least minAmountOut.
  • A larger trade never gets a better price, except by what rounding took from the smaller one.

The first is the constant-product version of the first post’s sum property:

prop_productNeverDecreases pool s =
  whenSwapSucceeds pool s $ \_ pool' ->
    property (gold pool' * silver pool' >= gold pool * silver pool)

whenSwapSucceeds runs the swap and hands the check the amount paid out and the pool after it. property turns the yes-or-no answer into a test. The rest follow the same pattern. The one about prices is the most involved, because “except by what rounding took” has to be written down exactly.

How the rounding allowance is written, for the curious

The property makes a second swap, larger, that pays a random positive amount, extra, more than the first, and runs both on the same pool. amountOut is what the first one paid and amountOut' what the larger one paid. It checks two things, joined by .&&., which means both must hold:

amountOut' >= amountOut
  .&&. amountOut' * amountIn s < (amountOut + 1) * amountIn larger

The first says paying more never gets you less. The second compares prices, and its + 1 is the rounding: rounding took less than one coin from the first trade, so the larger trade can beat its price, but by less than one coin’s worth. Comparing a / b < c / d as a * d < c * b gives the same answer without dividing, and with whole numbers there’s nothing to round.

The widget below steps through any of the six on a generated case, as in the first post, and runs a hundred. The percentage in the result is how many of the generated swaps went through; the rest were refused, which is expected, since the inputs include negative amounts and empty pools on purpose.

All six pass. In the real test suite, each one runs on 800 to 1,600 cases, because QuickCheck keeps going until it’s sure that enough of its generated swaps went through.

Arbitrage against both pools

The constant-product pool’s version of the value property fails too. One run’s smallest case was a gold price of 2, a pool of 2 gold and 1 silver, and a swap of 1 silver for gold. That pool prices gold at half a silver, while the market says two. Pay 1 silver, and the formula gives you 2 × 1 ÷ (1 + 1), which is one gold, worth two silver. The pool was worth 5 silver, and now it’s worth 4.

So a moving price doesn’t prevent arbitrage; it limits it. Starting both pools at 100 and 100, with gold at two silver, the trader’s most profitable swap in each pool gives:

Constant sumConstant product
Trader’s swap100 silver for 100 gold37 silver for 27 gold
Trader’s profit100 silver17 silver
Pool value after200 silver283 silver
Pool price after1 silver per gold1.88 silver per gold
Reserve emptiedyes, the goldno

In the constant-product pool, a few larger swaps earn exactly the same 17 silver. After the best one, the pool’s price is close enough to the market’s 2 that no swap makes money any more, so the trader stops.

That’s how the constant-product pool follows the market without being told the market price: each arbitrage trade moves its price toward the market’s, and the trader’s profit is what the update costs the pool. The constant-sum pool’s price never moves, so it pays out until a reserve is empty and its price is still 1.

The 283 is also less than the 300 the coins would be worth if their owner had held them instead of putting them in the pool. DeFi calls that gap impermanent loss. It’s called impermanent because it would close again, give or take rounding, if gold went back to one silver.

The test suite checks emptying in two more properties: no swap empties a reserve that started with something. The constant-sum version fails within its first couple of tries; one run caught it on a pool of 1 and 1 and a swap of 1 gold. The constant-product version passes.

In the widget below, set a market price and press Trader swaps. A trader makes the most profitable swap in each pool, and the pools show what’s left. Under them are the four market properties and what a run of each finds. The widget’s runs pick their own numbers, so the smallest cases they find can differ from the ones above, often mirrored, with gold and silver swapped.

What the model shows so far

With a market price in the model, both pools fail the value property: a pool whose price differs from the market’s loses value to arbitrage. What differs is how much. The constant-sum pool loses until a reserve is empty. The constant-product pool loses only until its price is close to the market’s, and no swap can empty it. In exchange, every trade moves its price against the trader, by more in a smaller pool.

The model still has no fees, so every price correction is paid for by whoever supplied the reserves, and nothing in this model pays them for it. Fees, and who supplies the reserves, come later in the series. The next post implements this pool on Ethereum and checks the contract against the Haskell model.

← Back to all writing
Last login: Tue, Nov 3, 00:00:00 on ttys001
user@inkspell:~/blog read constant-product.md
FILE: constant-product.md DATE: 2026-11-03 WORDS: 3016 READ: ~16m
TAGS: [amm] [property-based-testing] [testing] [defi] [blockchain]

The Making of an Automated Market Maker: Constant Product Under a Market Price

// How arbitrage drains a fixed-price pool, the constant-product pool that limits the loss, and the properties that measure both.

» BEGIN OUTPUT

A pool that trades at a fixed price passes every property about its own books and still loses money as soon as the market price moves. Anyone can buy from it at the old price and sell elsewhere at the new one, and they can keep doing it until a reserve is empty.

This is the second post in a series about automated market makers, the programs that let anyone swap one token for another without a person on the other side. The first post built a constant-sum pool and introduced properties (rules the code must keep for every input, checked on random cases). This one adds a market price to the model, measures what arbitrage takes from that pool, and replaces it with a constant-product pool. The code is in the same public repository, and the version described here is tagged ch02-model.

The first post called the pool’s two balances jars. From here on they’re reserves, which is what the code calls them.

A fixed price loses value when the market moves

The pool from the first post holds 100 gold and 100 silver and trades them one for one. Now gold trades for two silver everywhere else.

A trader pays the pool 100 silver and gets its 100 gold, then sells the gold elsewhere for 200 silver. They started with 100 silver and end with 200, and the pool’s gold reserve is empty.

No property from the first post fails. The total is still 200 coins, the trader got one coin for each coin they paid, and no reserve went negative. Those properties only look at coin counts, and the loss doesn’t show in coin counts.

It shows once the reserves are valued at the market price. Before the trade, the pool held 100 gold worth 200 silver plus 100 silver, so 300 in all. After it, the pool holds 200 silver. The trader’s 100 silver profit is exactly the pool’s loss, since no one else was involved.

Buying where something is cheap and selling where it’s dear is arbitrage. Nothing in the swap rules prevents it, and in a pool with a fixed price, nothing limits it.

Pool value at a market price, as a property

That valuation gives a property: at the market price, a swap never makes the pool worth less. First, the valuation itself:

poolValue goldPrice (Pool gold silver) =
  goldPrice * fromInteger gold + fromInteger silver

goldPrice is how many silver one gold is worth on the market, and it can be a fraction, such as 3/2. (fromInteger only converts the coin counts so they can be multiplied by a fraction.)

Then the property, for the constant-sum pool:

prop_sumValueNeverDecreases (Positive goldPrice) pool s =
  case CS.swap s pool of
    Left _           -> property True
    Right (_, pool') -> property (sumPoolValue goldPrice pool' >= sumPoolValue goldPrice pool)

Positive goldPrice asks for a random gold price above zero. CS.swap is the first post’s swap; the test file uses both pools, so it puts CS. in front of everything from the constant-sum one and CP. in front of the constant-product one, which comes next. sumPoolValue is the same valuation as poolValue, for that pool.

A case looks at which shape the swap gave back and picks a line: a refusal passes as it is (property True is a test that always passes), and a success has to leave the pool worth at least as much as before. A _ stands for a part the line doesn’t need, here the reason for a refusal and the amount paid out, and pool' (read “pool prime”) is the pool after the swap.

The property is expected to fail. One run printed this:

+++ OK, failed as expected. Falsified (after 6 tests and 6 shrinks):
Positive {getPositive = 2 % 1}
Pool {gold = 1, silver = 0}
Swap {direction = SilverForGold, amountIn = 1}

The test file wraps this property in expectFailure, so the suite passes only if QuickCheck finds a case that breaks it. That keeps a known weakness of the constant-sum pool in the suite as a checked fact, instead of a red test everyone learns to ignore.

The last three lines are the case: a price of 2 (2 % 1 is the fraction 2/1), a pool with one gold and no silver, and a swap of one silver for gold. The pool sells a coin worth two silver for one, and its value drops from 2 to 1. It’s the 100-coin trade above, at the smallest size that still fails.

QuickCheck found a failing case on its sixth try, probably with larger numbers. It then tried smaller versions of that case, kept each one that still failed, and stopped when none of the smaller versions it tried failed. That’s called shrinking, and “6 shrinks” means six of those steps worked. A shrunk case is usually small enough to show the cause directly.

Constant product moves the price with each trade

The constant-sum pool loses so much because its price never moves: it sells every coin at the same price until the reserve is empty. The fix many real pools use is to let the reserves set the price: the smaller a reserve, the more its coins cost.

The rule that does it is constant product. Multiply the reserves: 100 gold times 100 silver is 10,000. Call that number k. A swap has to leave k where it was. Pay in 10 gold, and the gold reserve holds 110. For 110 times the silver to stay 10,000, the silver reserve has to drop to 90.9…, so the pool owes you 9.09… silver. It can only pay whole coins, so it rounds down and pays 9. The reserves now hold 110 and 91, and their product is 10,010: a little more than before, because the rounding left a fraction of a coin in the pool.

You paid 10 gold and got 9 silver, and the next trader gets less: one gold is now worth 91 ÷ 110, or about 0.83 silver, in the pool. That ratio is the pool’s price. An actual swap always gets less than it, because the swap itself moves the price and then rounds down.

A pool on this rule can’t be emptied. Buying the pool’s last silver would take infinitely much gold, so every swap pays out less than the reserve holds. Uniswap’s first two versions use this rule with a fee added; this model has no fee yet.

Where the formula comes from, for the curious

Call the reserve you pay into reserveIn and the one that pays you reserveOut. After the swap, the first holds reserveIn + amountIn and the second reserveOut - amountOut, and their product must still be reserveIn * reserveOut. Solve that for amountOut:

amountOut = reserveOut * amountIn / (reserveIn + amountIn)

With 100, 100 and 10, that’s 1,000 / 110 = 9.09…. And since reserveIn + amountIn is always more than amountIn, the fraction is always less than reserveOut: you never get the whole reserve.

The swap function gets a minimum and two new refusals

Here is the new swap:

swap (Swap direction amountIn minAmountOut) (Pool gold silver)
  | amountIn <= 0                = Left AmountNotPositive
  | gold <= 0 || silver <= 0     = Left EmptyPool
  | amountOut == 0
    || amountOut < minAmountOut  = Left OutputTooSmall
  | direction == GoldForSilver   =
      Right (amountOut, Pool (gold + amountIn)
                             (silver - amountOut))
  | otherwise                    =
      Right (amountOut, Pool (gold - amountOut)
                             (silver + amountIn))
  where
    -- keep reserveIn * reserveOut, rounding down in the pool's favour
    amountOut = reserveOut * amountIn `div` (reserveIn + amountIn)
    reserveIn  = if direction == GoldForSilver then gold else silver
    reserveOut = if direction == GoldForSilver then silver else gold

Most of it is the first post’s function. The changes are in three places.

The swap has a third field, minAmountOut: the least the trader will accept. The price now moves with every trade, including other traders’ trades that land first, so the price you saw may not be the price you get. A swap that would pay less than the minimum is refused.

InsufficientLiquidity is gone, since no swap can ask for more than the reserve holds. Two refusals replace it. EmptyPool refuses to trade when a reserve holds nothing (|| means “or”). Without it, a pool with no gold and 100 silver would give you all 100 silver for one gold, because the formula divides by an empty reserve plus your one coin. OutputTooSmall refuses a swap that would pay nothing, or less than the minimum.

The where block does the arithmetic. reserveIn and reserveOut pick the reserves by direction, and amountOut is the formula. div divides and rounds down, and the backticks let it sit between its two inputs, like *. The text after -- is a comment, written for people and ignored by the computer.

Rounding down keeps the fraction in the pool. Rounding up would let a swap take up to one coin more than the rule allows, which is enough to take the last coin from a small reserve, and a trader could choose amounts that do it every time.

Run the 10 gold through it. Is 10 at most zero? No. Is either reserve empty? No. amountOut is 100 × 10 div 110, which is 9: not zero, and not below a minimum of 0. You’re paying gold, so the answer is Right (9, Pool 110 91).

The widget below runs the same function. Set an amount and a minimum, then step through the guards, or open Predict the result and work out each answer before you look. As in the first post, its code panel shows the rest of the file, type lines included.

The model has more names now, and some are easy to mix up: amountIn is a payment, reserveIn is a reserve, and which reserve it is depends on the direction. The 15 cards below test these names and the ideas behind them. A card you miss comes round again.

Larger trades get worse prices

In the pool of 100 and 100, paying 10 gold gets you 9 silver, or 0.9 for each gold. Paying 100 gets you 50, which is 0.5 each. Paying 1,000 gets you 90: 0.09 each, for a trade that’s ten times larger and gets less than twice as much. Every coin you pay in moves the price against the next one. This is price impact, and it’s the cost of a pool that can’t be emptied.

Pool size matters as much as trade size. In a pool of 10,000 and 10,000, the same 100 gold gets 99 silver. Deeper pools give better prices.

The top chart below draws this pool’s rule as a curve, next to the first post’s straight line. A trade is a step along it. The chart under it shows the price each trade size gets.

Rounding bends the lower chart at the small end. Pay 1 gold, and the pool owes you 0.99… silver, which rounds down to nothing, so the swap is refused. Pay 2, and you get 1 silver: 0.5 each. Pay 3, and you get 2: 0.67 each. The larger trade got the better price, because rounding took a bigger share of the smaller one. Rounding always takes less than one coin, so the larger the trade, the less it matters, but a property about prices has to allow for it.

Six properties for the constant-product pool

The first post’s four properties described a pool with a fixed price. Each has a counterpart here, and two are new:

  • The product of the reserves never goes down, where the sum used to stay the same. Rounding makes it grow a little.
  • What comes out is less than the reserve it comes from, where it used to equal what went in.
  • A round trip never profits: swap, then swap straight back, and you get back at most what you paid. It used to restore the pool exactly; now rounding can keep some, and in a lopsided pool or after a large trade, quite a lot.
  • Both reserves stay above zero, where they used to stay at zero or above.
  • What comes out is at least minAmountOut.
  • A larger trade never gets a better price, except by what rounding took from the smaller one.

The first is the constant-product version of the first post’s sum property:

prop_productNeverDecreases pool s =
  whenSwapSucceeds pool s $ \_ pool' ->
    property (gold pool' * silver pool' >= gold pool * silver pool)

whenSwapSucceeds runs the swap and hands the check the amount paid out and the pool after it. property turns the yes-or-no answer into a test. The rest follow the same pattern. The one about prices is the most involved, because “except by what rounding took” has to be written down exactly.

How the rounding allowance is written, for the curious

The property makes a second swap, larger, that pays a random positive amount, extra, more than the first, and runs both on the same pool. amountOut is what the first one paid and amountOut' what the larger one paid. It checks two things, joined by .&&., which means both must hold:

amountOut' >= amountOut
  .&&. amountOut' * amountIn s < (amountOut + 1) * amountIn larger

The first says paying more never gets you less. The second compares prices, and its + 1 is the rounding: rounding took less than one coin from the first trade, so the larger trade can beat its price, but by less than one coin’s worth. Comparing a / b < c / d as a * d < c * b gives the same answer without dividing, and with whole numbers there’s nothing to round.

The widget below steps through any of the six on a generated case, as in the first post, and runs a hundred. The percentage in the result is how many of the generated swaps went through; the rest were refused, which is expected, since the inputs include negative amounts and empty pools on purpose.

All six pass. In the real test suite, each one runs on 800 to 1,600 cases, because QuickCheck keeps going until it’s sure that enough of its generated swaps went through.

Arbitrage against both pools

The constant-product pool’s version of the value property fails too. One run’s smallest case was a gold price of 2, a pool of 2 gold and 1 silver, and a swap of 1 silver for gold. That pool prices gold at half a silver, while the market says two. Pay 1 silver, and the formula gives you 2 × 1 ÷ (1 + 1), which is one gold, worth two silver. The pool was worth 5 silver, and now it’s worth 4.

So a moving price doesn’t prevent arbitrage; it limits it. Starting both pools at 100 and 100, with gold at two silver, the trader’s most profitable swap in each pool gives:

Constant sumConstant product
Trader’s swap100 silver for 100 gold37 silver for 27 gold
Trader’s profit100 silver17 silver
Pool value after200 silver283 silver
Pool price after1 silver per gold1.88 silver per gold
Reserve emptiedyes, the goldno

In the constant-product pool, a few larger swaps earn exactly the same 17 silver. After the best one, the pool’s price is close enough to the market’s 2 that no swap makes money any more, so the trader stops.

That’s how the constant-product pool follows the market without being told the market price: each arbitrage trade moves its price toward the market’s, and the trader’s profit is what the update costs the pool. The constant-sum pool’s price never moves, so it pays out until a reserve is empty and its price is still 1.

The 283 is also less than the 300 the coins would be worth if their owner had held them instead of putting them in the pool. DeFi calls that gap impermanent loss. It’s called impermanent because it would close again, give or take rounding, if gold went back to one silver.

The test suite checks emptying in two more properties: no swap empties a reserve that started with something. The constant-sum version fails within its first couple of tries; one run caught it on a pool of 1 and 1 and a swap of 1 gold. The constant-product version passes.

In the widget below, set a market price and press Trader swaps. A trader makes the most profitable swap in each pool, and the pools show what’s left. Under them are the four market properties and what a run of each finds. The widget’s runs pick their own numbers, so the smallest cases they find can differ from the ones above, often mirrored, with gold and silver swapped.

What the model shows so far

With a market price in the model, both pools fail the value property: a pool whose price differs from the market’s loses value to arbitrage. What differs is how much. The constant-sum pool loses until a reserve is empty. The constant-product pool loses only until its price is close to the market’s, and no swap can empty it. In exchange, every trade moves its price against the trader, by more in a smaller pool.

The model still has no fees, so every price correction is paid for by whoever supplied the reserves, and nothing in this model pays them for it. Fees, and who supplies the reserves, come later in the series. The next post implements this pool on Ethereum and checks the contract against the Haskell model.

END OF FILE
user@inkspell:~/blog $
$ cd ..
phone down  ·  breathe  ·  begin
☸︎
amm ☸︎ property-based-testing ☸︎ testing ☸︎ defi ☸︎ blockchain

The Making of an Automated Market Maker: Constant Product Under a Market Price

☸︎

How arbitrage drains a fixed-price pool, the constant-product pool that limits the loss, and the properties that measure both.

session · 16 min sitting · November 3, 2026
— enter the practice —

A pool that trades at a fixed price passes every property about its own books and still loses money as soon as the market price moves. Anyone can buy from it at the old price and sell elsewhere at the new one, and they can keep doing it until a reserve is empty.

This is the second post in a series about automated market makers, the programs that let anyone swap one token for another without a person on the other side. The first post built a constant-sum pool and introduced properties (rules the code must keep for every input, checked on random cases). This one adds a market price to the model, measures what arbitrage takes from that pool, and replaces it with a constant-product pool. The code is in the same public repository, and the version described here is tagged ch02-model.

The first post called the pool’s two balances jars. From here on they’re reserves, which is what the code calls them.

A fixed price loses value when the market moves

The pool from the first post holds 100 gold and 100 silver and trades them one for one. Now gold trades for two silver everywhere else.

A trader pays the pool 100 silver and gets its 100 gold, then sells the gold elsewhere for 200 silver. They started with 100 silver and end with 200, and the pool’s gold reserve is empty.

No property from the first post fails. The total is still 200 coins, the trader got one coin for each coin they paid, and no reserve went negative. Those properties only look at coin counts, and the loss doesn’t show in coin counts.

It shows once the reserves are valued at the market price. Before the trade, the pool held 100 gold worth 200 silver plus 100 silver, so 300 in all. After it, the pool holds 200 silver. The trader’s 100 silver profit is exactly the pool’s loss, since no one else was involved.

Buying where something is cheap and selling where it’s dear is arbitrage. Nothing in the swap rules prevents it, and in a pool with a fixed price, nothing limits it.

Pool value at a market price, as a property

That valuation gives a property: at the market price, a swap never makes the pool worth less. First, the valuation itself:

poolValue goldPrice (Pool gold silver) =
  goldPrice * fromInteger gold + fromInteger silver

goldPrice is how many silver one gold is worth on the market, and it can be a fraction, such as 3/2. (fromInteger only converts the coin counts so they can be multiplied by a fraction.)

Then the property, for the constant-sum pool:

prop_sumValueNeverDecreases (Positive goldPrice) pool s =
  case CS.swap s pool of
    Left _           -> property True
    Right (_, pool') -> property (sumPoolValue goldPrice pool' >= sumPoolValue goldPrice pool)

Positive goldPrice asks for a random gold price above zero. CS.swap is the first post’s swap; the test file uses both pools, so it puts CS. in front of everything from the constant-sum one and CP. in front of the constant-product one, which comes next. sumPoolValue is the same valuation as poolValue, for that pool.

A case looks at which shape the swap gave back and picks a line: a refusal passes as it is (property True is a test that always passes), and a success has to leave the pool worth at least as much as before. A _ stands for a part the line doesn’t need, here the reason for a refusal and the amount paid out, and pool' (read “pool prime”) is the pool after the swap.

The property is expected to fail. One run printed this:

+++ OK, failed as expected. Falsified (after 6 tests and 6 shrinks):
Positive {getPositive = 2 % 1}
Pool {gold = 1, silver = 0}
Swap {direction = SilverForGold, amountIn = 1}

The test file wraps this property in expectFailure, so the suite passes only if QuickCheck finds a case that breaks it. That keeps a known weakness of the constant-sum pool in the suite as a checked fact, instead of a red test everyone learns to ignore.

The last three lines are the case: a price of 2 (2 % 1 is the fraction 2/1), a pool with one gold and no silver, and a swap of one silver for gold. The pool sells a coin worth two silver for one, and its value drops from 2 to 1. It’s the 100-coin trade above, at the smallest size that still fails.

QuickCheck found a failing case on its sixth try, probably with larger numbers. It then tried smaller versions of that case, kept each one that still failed, and stopped when none of the smaller versions it tried failed. That’s called shrinking, and “6 shrinks” means six of those steps worked. A shrunk case is usually small enough to show the cause directly.

Constant product moves the price with each trade

The constant-sum pool loses so much because its price never moves: it sells every coin at the same price until the reserve is empty. The fix many real pools use is to let the reserves set the price: the smaller a reserve, the more its coins cost.

The rule that does it is constant product. Multiply the reserves: 100 gold times 100 silver is 10,000. Call that number k. A swap has to leave k where it was. Pay in 10 gold, and the gold reserve holds 110. For 110 times the silver to stay 10,000, the silver reserve has to drop to 90.9…, so the pool owes you 9.09… silver. It can only pay whole coins, so it rounds down and pays 9. The reserves now hold 110 and 91, and their product is 10,010: a little more than before, because the rounding left a fraction of a coin in the pool.

You paid 10 gold and got 9 silver, and the next trader gets less: one gold is now worth 91 ÷ 110, or about 0.83 silver, in the pool. That ratio is the pool’s price. An actual swap always gets less than it, because the swap itself moves the price and then rounds down.

A pool on this rule can’t be emptied. Buying the pool’s last silver would take infinitely much gold, so every swap pays out less than the reserve holds. Uniswap’s first two versions use this rule with a fee added; this model has no fee yet.

Where the formula comes from, for the curious

Call the reserve you pay into reserveIn and the one that pays you reserveOut. After the swap, the first holds reserveIn + amountIn and the second reserveOut - amountOut, and their product must still be reserveIn * reserveOut. Solve that for amountOut:

amountOut = reserveOut * amountIn / (reserveIn + amountIn)

With 100, 100 and 10, that’s 1,000 / 110 = 9.09…. And since reserveIn + amountIn is always more than amountIn, the fraction is always less than reserveOut: you never get the whole reserve.

The swap function gets a minimum and two new refusals

Here is the new swap:

swap (Swap direction amountIn minAmountOut) (Pool gold silver)
  | amountIn <= 0                = Left AmountNotPositive
  | gold <= 0 || silver <= 0     = Left EmptyPool
  | amountOut == 0
    || amountOut < minAmountOut  = Left OutputTooSmall
  | direction == GoldForSilver   =
      Right (amountOut, Pool (gold + amountIn)
                             (silver - amountOut))
  | otherwise                    =
      Right (amountOut, Pool (gold - amountOut)
                             (silver + amountIn))
  where
    -- keep reserveIn * reserveOut, rounding down in the pool's favour
    amountOut = reserveOut * amountIn `div` (reserveIn + amountIn)
    reserveIn  = if direction == GoldForSilver then gold else silver
    reserveOut = if direction == GoldForSilver then silver else gold

Most of it is the first post’s function. The changes are in three places.

The swap has a third field, minAmountOut: the least the trader will accept. The price now moves with every trade, including other traders’ trades that land first, so the price you saw may not be the price you get. A swap that would pay less than the minimum is refused.

InsufficientLiquidity is gone, since no swap can ask for more than the reserve holds. Two refusals replace it. EmptyPool refuses to trade when a reserve holds nothing (|| means “or”). Without it, a pool with no gold and 100 silver would give you all 100 silver for one gold, because the formula divides by an empty reserve plus your one coin. OutputTooSmall refuses a swap that would pay nothing, or less than the minimum.

The where block does the arithmetic. reserveIn and reserveOut pick the reserves by direction, and amountOut is the formula. div divides and rounds down, and the backticks let it sit between its two inputs, like *. The text after -- is a comment, written for people and ignored by the computer.

Rounding down keeps the fraction in the pool. Rounding up would let a swap take up to one coin more than the rule allows, which is enough to take the last coin from a small reserve, and a trader could choose amounts that do it every time.

Run the 10 gold through it. Is 10 at most zero? No. Is either reserve empty? No. amountOut is 100 × 10 div 110, which is 9: not zero, and not below a minimum of 0. You’re paying gold, so the answer is Right (9, Pool 110 91).

The widget below runs the same function. Set an amount and a minimum, then step through the guards, or open Predict the result and work out each answer before you look. As in the first post, its code panel shows the rest of the file, type lines included.

The model has more names now, and some are easy to mix up: amountIn is a payment, reserveIn is a reserve, and which reserve it is depends on the direction. The 15 cards below test these names and the ideas behind them. A card you miss comes round again.

Larger trades get worse prices

In the pool of 100 and 100, paying 10 gold gets you 9 silver, or 0.9 for each gold. Paying 100 gets you 50, which is 0.5 each. Paying 1,000 gets you 90: 0.09 each, for a trade that’s ten times larger and gets less than twice as much. Every coin you pay in moves the price against the next one. This is price impact, and it’s the cost of a pool that can’t be emptied.

Pool size matters as much as trade size. In a pool of 10,000 and 10,000, the same 100 gold gets 99 silver. Deeper pools give better prices.

The top chart below draws this pool’s rule as a curve, next to the first post’s straight line. A trade is a step along it. The chart under it shows the price each trade size gets.

Rounding bends the lower chart at the small end. Pay 1 gold, and the pool owes you 0.99… silver, which rounds down to nothing, so the swap is refused. Pay 2, and you get 1 silver: 0.5 each. Pay 3, and you get 2: 0.67 each. The larger trade got the better price, because rounding took a bigger share of the smaller one. Rounding always takes less than one coin, so the larger the trade, the less it matters, but a property about prices has to allow for it.

Six properties for the constant-product pool

The first post’s four properties described a pool with a fixed price. Each has a counterpart here, and two are new:

  • The product of the reserves never goes down, where the sum used to stay the same. Rounding makes it grow a little.
  • What comes out is less than the reserve it comes from, where it used to equal what went in.
  • A round trip never profits: swap, then swap straight back, and you get back at most what you paid. It used to restore the pool exactly; now rounding can keep some, and in a lopsided pool or after a large trade, quite a lot.
  • Both reserves stay above zero, where they used to stay at zero or above.
  • What comes out is at least minAmountOut.
  • A larger trade never gets a better price, except by what rounding took from the smaller one.

The first is the constant-product version of the first post’s sum property:

prop_productNeverDecreases pool s =
  whenSwapSucceeds pool s $ \_ pool' ->
    property (gold pool' * silver pool' >= gold pool * silver pool)

whenSwapSucceeds runs the swap and hands the check the amount paid out and the pool after it. property turns the yes-or-no answer into a test. The rest follow the same pattern. The one about prices is the most involved, because “except by what rounding took” has to be written down exactly.

How the rounding allowance is written, for the curious

The property makes a second swap, larger, that pays a random positive amount, extra, more than the first, and runs both on the same pool. amountOut is what the first one paid and amountOut' what the larger one paid. It checks two things, joined by .&&., which means both must hold:

amountOut' >= amountOut
  .&&. amountOut' * amountIn s < (amountOut + 1) * amountIn larger

The first says paying more never gets you less. The second compares prices, and its + 1 is the rounding: rounding took less than one coin from the first trade, so the larger trade can beat its price, but by less than one coin’s worth. Comparing a / b < c / d as a * d < c * b gives the same answer without dividing, and with whole numbers there’s nothing to round.

The widget below steps through any of the six on a generated case, as in the first post, and runs a hundred. The percentage in the result is how many of the generated swaps went through; the rest were refused, which is expected, since the inputs include negative amounts and empty pools on purpose.

All six pass. In the real test suite, each one runs on 800 to 1,600 cases, because QuickCheck keeps going until it’s sure that enough of its generated swaps went through.

Arbitrage against both pools

The constant-product pool’s version of the value property fails too. One run’s smallest case was a gold price of 2, a pool of 2 gold and 1 silver, and a swap of 1 silver for gold. That pool prices gold at half a silver, while the market says two. Pay 1 silver, and the formula gives you 2 × 1 ÷ (1 + 1), which is one gold, worth two silver. The pool was worth 5 silver, and now it’s worth 4.

So a moving price doesn’t prevent arbitrage; it limits it. Starting both pools at 100 and 100, with gold at two silver, the trader’s most profitable swap in each pool gives:

Constant sumConstant product
Trader’s swap100 silver for 100 gold37 silver for 27 gold
Trader’s profit100 silver17 silver
Pool value after200 silver283 silver
Pool price after1 silver per gold1.88 silver per gold
Reserve emptiedyes, the goldno

In the constant-product pool, a few larger swaps earn exactly the same 17 silver. After the best one, the pool’s price is close enough to the market’s 2 that no swap makes money any more, so the trader stops.

That’s how the constant-product pool follows the market without being told the market price: each arbitrage trade moves its price toward the market’s, and the trader’s profit is what the update costs the pool. The constant-sum pool’s price never moves, so it pays out until a reserve is empty and its price is still 1.

The 283 is also less than the 300 the coins would be worth if their owner had held them instead of putting them in the pool. DeFi calls that gap impermanent loss. It’s called impermanent because it would close again, give or take rounding, if gold went back to one silver.

The test suite checks emptying in two more properties: no swap empties a reserve that started with something. The constant-sum version fails within its first couple of tries; one run caught it on a pool of 1 and 1 and a swap of 1 gold. The constant-product version passes.

In the widget below, set a market price and press Trader swaps. A trader makes the most profitable swap in each pool, and the pools show what’s left. Under them are the four market properties and what a run of each finds. The widget’s runs pick their own numbers, so the smallest cases they find can differ from the ones above, often mirrored, with gold and silver swapped.

What the model shows so far

With a market price in the model, both pools fail the value property: a pool whose price differs from the market’s loses value to arbitrage. What differs is how much. The constant-sum pool loses until a reserve is empty. The constant-product pool loses only until its price is close to the market’s, and no swap can empty it. In exchange, every trade moves its price against the trader, by more in a smaller pool.

The model still has no fees, so every price correction is paid for by whoever supplied the reserves, and nothing in this model pays them for it. Fees, and who supplies the reserves, come later in the series. The next post implements this pool on Ethereum and checks the contract against the Haskell model.

☸︎
the session ends
learn  ·  unlearn  ·  return
return when ready
☠︎ LARTS-SERVER BBS v2.3.1 — root console
⚠︎ Unauthorised access will be met with creative, legally ambiguous, and frankly disproportionate solutions.
Last login: 2026-11-03 00:00:00 from somewhere you'll regret  ·  session pid 1331
⚡ luser activity is being monitored. it always was. 6 LARTs administered today.
☠︎ BOFH EXCUSE #1151 :: the coffee machine shared a circuit with the database UPS
root@larts-server:/var/rants # cat constant-product.txt  # and what was your username again?
SUBJECT: The Making of an Automated Market Maker: Constant Product Under a Market Price
DATE: 2026-11-03 00:00:00 READ: ~16 min of your billable downtime WORDS: 3016
TAGS: [amm] [property-based-testing] [testing] [defi] [blockchain]
// How arbitrage drains a fixed-price pool, the constant-product pool that limits the loss, and the properties that measure both.
☠︎ ::: BEGIN TRANSMISSION — touch nothing ::: ☠︎

A pool that trades at a fixed price passes every property about its own books and still loses money as soon as the market price moves. Anyone can buy from it at the old price and sell elsewhere at the new one, and they can keep doing it until a reserve is empty.

This is the second post in a series about automated market makers, the programs that let anyone swap one token for another without a person on the other side. The first post built a constant-sum pool and introduced properties (rules the code must keep for every input, checked on random cases). This one adds a market price to the model, measures what arbitrage takes from that pool, and replaces it with a constant-product pool. The code is in the same public repository, and the version described here is tagged ch02-model.

The first post called the pool’s two balances jars. From here on they’re reserves, which is what the code calls them.

A fixed price loses value when the market moves

The pool from the first post holds 100 gold and 100 silver and trades them one for one. Now gold trades for two silver everywhere else.

A trader pays the pool 100 silver and gets its 100 gold, then sells the gold elsewhere for 200 silver. They started with 100 silver and end with 200, and the pool’s gold reserve is empty.

No property from the first post fails. The total is still 200 coins, the trader got one coin for each coin they paid, and no reserve went negative. Those properties only look at coin counts, and the loss doesn’t show in coin counts.

It shows once the reserves are valued at the market price. Before the trade, the pool held 100 gold worth 200 silver plus 100 silver, so 300 in all. After it, the pool holds 200 silver. The trader’s 100 silver profit is exactly the pool’s loss, since no one else was involved.

Buying where something is cheap and selling where it’s dear is arbitrage. Nothing in the swap rules prevents it, and in a pool with a fixed price, nothing limits it.

Pool value at a market price, as a property

That valuation gives a property: at the market price, a swap never makes the pool worth less. First, the valuation itself:

poolValue goldPrice (Pool gold silver) =
  goldPrice * fromInteger gold + fromInteger silver

goldPrice is how many silver one gold is worth on the market, and it can be a fraction, such as 3/2. (fromInteger only converts the coin counts so they can be multiplied by a fraction.)

Then the property, for the constant-sum pool:

prop_sumValueNeverDecreases (Positive goldPrice) pool s =
  case CS.swap s pool of
    Left _           -> property True
    Right (_, pool') -> property (sumPoolValue goldPrice pool' >= sumPoolValue goldPrice pool)

Positive goldPrice asks for a random gold price above zero. CS.swap is the first post’s swap; the test file uses both pools, so it puts CS. in front of everything from the constant-sum one and CP. in front of the constant-product one, which comes next. sumPoolValue is the same valuation as poolValue, for that pool.

A case looks at which shape the swap gave back and picks a line: a refusal passes as it is (property True is a test that always passes), and a success has to leave the pool worth at least as much as before. A _ stands for a part the line doesn’t need, here the reason for a refusal and the amount paid out, and pool' (read “pool prime”) is the pool after the swap.

The property is expected to fail. One run printed this:

+++ OK, failed as expected. Falsified (after 6 tests and 6 shrinks):
Positive {getPositive = 2 % 1}
Pool {gold = 1, silver = 0}
Swap {direction = SilverForGold, amountIn = 1}

The test file wraps this property in expectFailure, so the suite passes only if QuickCheck finds a case that breaks it. That keeps a known weakness of the constant-sum pool in the suite as a checked fact, instead of a red test everyone learns to ignore.

The last three lines are the case: a price of 2 (2 % 1 is the fraction 2/1), a pool with one gold and no silver, and a swap of one silver for gold. The pool sells a coin worth two silver for one, and its value drops from 2 to 1. It’s the 100-coin trade above, at the smallest size that still fails.

QuickCheck found a failing case on its sixth try, probably with larger numbers. It then tried smaller versions of that case, kept each one that still failed, and stopped when none of the smaller versions it tried failed. That’s called shrinking, and “6 shrinks” means six of those steps worked. A shrunk case is usually small enough to show the cause directly.

Constant product moves the price with each trade

The constant-sum pool loses so much because its price never moves: it sells every coin at the same price until the reserve is empty. The fix many real pools use is to let the reserves set the price: the smaller a reserve, the more its coins cost.

The rule that does it is constant product. Multiply the reserves: 100 gold times 100 silver is 10,000. Call that number k. A swap has to leave k where it was. Pay in 10 gold, and the gold reserve holds 110. For 110 times the silver to stay 10,000, the silver reserve has to drop to 90.9…, so the pool owes you 9.09… silver. It can only pay whole coins, so it rounds down and pays 9. The reserves now hold 110 and 91, and their product is 10,010: a little more than before, because the rounding left a fraction of a coin in the pool.

You paid 10 gold and got 9 silver, and the next trader gets less: one gold is now worth 91 ÷ 110, or about 0.83 silver, in the pool. That ratio is the pool’s price. An actual swap always gets less than it, because the swap itself moves the price and then rounds down.

A pool on this rule can’t be emptied. Buying the pool’s last silver would take infinitely much gold, so every swap pays out less than the reserve holds. Uniswap’s first two versions use this rule with a fee added; this model has no fee yet.

Where the formula comes from, for the curious

Call the reserve you pay into reserveIn and the one that pays you reserveOut. After the swap, the first holds reserveIn + amountIn and the second reserveOut - amountOut, and their product must still be reserveIn * reserveOut. Solve that for amountOut:

amountOut = reserveOut * amountIn / (reserveIn + amountIn)

With 100, 100 and 10, that’s 1,000 / 110 = 9.09…. And since reserveIn + amountIn is always more than amountIn, the fraction is always less than reserveOut: you never get the whole reserve.

The swap function gets a minimum and two new refusals

Here is the new swap:

swap (Swap direction amountIn minAmountOut) (Pool gold silver)
  | amountIn <= 0                = Left AmountNotPositive
  | gold <= 0 || silver <= 0     = Left EmptyPool
  | amountOut == 0
    || amountOut < minAmountOut  = Left OutputTooSmall
  | direction == GoldForSilver   =
      Right (amountOut, Pool (gold + amountIn)
                             (silver - amountOut))
  | otherwise                    =
      Right (amountOut, Pool (gold - amountOut)
                             (silver + amountIn))
  where
    -- keep reserveIn * reserveOut, rounding down in the pool's favour
    amountOut = reserveOut * amountIn `div` (reserveIn + amountIn)
    reserveIn  = if direction == GoldForSilver then gold else silver
    reserveOut = if direction == GoldForSilver then silver else gold

Most of it is the first post’s function. The changes are in three places.

The swap has a third field, minAmountOut: the least the trader will accept. The price now moves with every trade, including other traders’ trades that land first, so the price you saw may not be the price you get. A swap that would pay less than the minimum is refused.

InsufficientLiquidity is gone, since no swap can ask for more than the reserve holds. Two refusals replace it. EmptyPool refuses to trade when a reserve holds nothing (|| means “or”). Without it, a pool with no gold and 100 silver would give you all 100 silver for one gold, because the formula divides by an empty reserve plus your one coin. OutputTooSmall refuses a swap that would pay nothing, or less than the minimum.

The where block does the arithmetic. reserveIn and reserveOut pick the reserves by direction, and amountOut is the formula. div divides and rounds down, and the backticks let it sit between its two inputs, like *. The text after -- is a comment, written for people and ignored by the computer.

Rounding down keeps the fraction in the pool. Rounding up would let a swap take up to one coin more than the rule allows, which is enough to take the last coin from a small reserve, and a trader could choose amounts that do it every time.

Run the 10 gold through it. Is 10 at most zero? No. Is either reserve empty? No. amountOut is 100 × 10 div 110, which is 9: not zero, and not below a minimum of 0. You’re paying gold, so the answer is Right (9, Pool 110 91).

The widget below runs the same function. Set an amount and a minimum, then step through the guards, or open Predict the result and work out each answer before you look. As in the first post, its code panel shows the rest of the file, type lines included.

The model has more names now, and some are easy to mix up: amountIn is a payment, reserveIn is a reserve, and which reserve it is depends on the direction. The 15 cards below test these names and the ideas behind them. A card you miss comes round again.

Larger trades get worse prices

In the pool of 100 and 100, paying 10 gold gets you 9 silver, or 0.9 for each gold. Paying 100 gets you 50, which is 0.5 each. Paying 1,000 gets you 90: 0.09 each, for a trade that’s ten times larger and gets less than twice as much. Every coin you pay in moves the price against the next one. This is price impact, and it’s the cost of a pool that can’t be emptied.

Pool size matters as much as trade size. In a pool of 10,000 and 10,000, the same 100 gold gets 99 silver. Deeper pools give better prices.

The top chart below draws this pool’s rule as a curve, next to the first post’s straight line. A trade is a step along it. The chart under it shows the price each trade size gets.

Rounding bends the lower chart at the small end. Pay 1 gold, and the pool owes you 0.99… silver, which rounds down to nothing, so the swap is refused. Pay 2, and you get 1 silver: 0.5 each. Pay 3, and you get 2: 0.67 each. The larger trade got the better price, because rounding took a bigger share of the smaller one. Rounding always takes less than one coin, so the larger the trade, the less it matters, but a property about prices has to allow for it.

Six properties for the constant-product pool

The first post’s four properties described a pool with a fixed price. Each has a counterpart here, and two are new:

  • The product of the reserves never goes down, where the sum used to stay the same. Rounding makes it grow a little.
  • What comes out is less than the reserve it comes from, where it used to equal what went in.
  • A round trip never profits: swap, then swap straight back, and you get back at most what you paid. It used to restore the pool exactly; now rounding can keep some, and in a lopsided pool or after a large trade, quite a lot.
  • Both reserves stay above zero, where they used to stay at zero or above.
  • What comes out is at least minAmountOut.
  • A larger trade never gets a better price, except by what rounding took from the smaller one.

The first is the constant-product version of the first post’s sum property:

prop_productNeverDecreases pool s =
  whenSwapSucceeds pool s $ \_ pool' ->
    property (gold pool' * silver pool' >= gold pool * silver pool)

whenSwapSucceeds runs the swap and hands the check the amount paid out and the pool after it. property turns the yes-or-no answer into a test. The rest follow the same pattern. The one about prices is the most involved, because “except by what rounding took” has to be written down exactly.

How the rounding allowance is written, for the curious

The property makes a second swap, larger, that pays a random positive amount, extra, more than the first, and runs both on the same pool. amountOut is what the first one paid and amountOut' what the larger one paid. It checks two things, joined by .&&., which means both must hold:

amountOut' >= amountOut
  .&&. amountOut' * amountIn s < (amountOut + 1) * amountIn larger

The first says paying more never gets you less. The second compares prices, and its + 1 is the rounding: rounding took less than one coin from the first trade, so the larger trade can beat its price, but by less than one coin’s worth. Comparing a / b < c / d as a * d < c * b gives the same answer without dividing, and with whole numbers there’s nothing to round.

The widget below steps through any of the six on a generated case, as in the first post, and runs a hundred. The percentage in the result is how many of the generated swaps went through; the rest were refused, which is expected, since the inputs include negative amounts and empty pools on purpose.

All six pass. In the real test suite, each one runs on 800 to 1,600 cases, because QuickCheck keeps going until it’s sure that enough of its generated swaps went through.

Arbitrage against both pools

The constant-product pool’s version of the value property fails too. One run’s smallest case was a gold price of 2, a pool of 2 gold and 1 silver, and a swap of 1 silver for gold. That pool prices gold at half a silver, while the market says two. Pay 1 silver, and the formula gives you 2 × 1 ÷ (1 + 1), which is one gold, worth two silver. The pool was worth 5 silver, and now it’s worth 4.

So a moving price doesn’t prevent arbitrage; it limits it. Starting both pools at 100 and 100, with gold at two silver, the trader’s most profitable swap in each pool gives:

Constant sumConstant product
Trader’s swap100 silver for 100 gold37 silver for 27 gold
Trader’s profit100 silver17 silver
Pool value after200 silver283 silver
Pool price after1 silver per gold1.88 silver per gold
Reserve emptiedyes, the goldno

In the constant-product pool, a few larger swaps earn exactly the same 17 silver. After the best one, the pool’s price is close enough to the market’s 2 that no swap makes money any more, so the trader stops.

That’s how the constant-product pool follows the market without being told the market price: each arbitrage trade moves its price toward the market’s, and the trader’s profit is what the update costs the pool. The constant-sum pool’s price never moves, so it pays out until a reserve is empty and its price is still 1.

The 283 is also less than the 300 the coins would be worth if their owner had held them instead of putting them in the pool. DeFi calls that gap impermanent loss. It’s called impermanent because it would close again, give or take rounding, if gold went back to one silver.

The test suite checks emptying in two more properties: no swap empties a reserve that started with something. The constant-sum version fails within its first couple of tries; one run caught it on a pool of 1 and 1 and a swap of 1 gold. The constant-product version passes.

In the widget below, set a market price and press Trader swaps. A trader makes the most profitable swap in each pool, and the pools show what’s left. Under them are the four market properties and what a run of each finds. The widget’s runs pick their own numbers, so the smallest cases they find can differ from the ones above, often mirrored, with gold and silver swapped.

What the model shows so far

With a market price in the model, both pools fail the value property: a pool whose price differs from the market’s loses value to arbitrage. What differs is how much. The constant-sum pool loses until a reserve is empty. The constant-product pool loses only until its price is close to the market’s, and no swap can empty it. In exchange, every trade moves its price against the trader, by more in a smaller pool.

The model still has no fees, so every price correction is paid for by whoever supplied the reserves, and nothing in this model pays them for it. Fees, and who supplies the reserves, come later in the series. The next post implements this pool on Ethereum and checks the contract against the Haskell model.

☠︎ ::: END OF FILE — this never happened ::: ☠︎
[2026-11-03 00:00:00] SYSTEM: days since last 'accidental' BIOS flash: 3
[2026-11-03 00:00:00] SYSTEM: your read has been logged against your permanent record.
root@larts-server:/var/rants # logout  # don't let the airlock hit you
⛤︎
the circle is opened
☾ return to the archive ☽
☾ amm ☽ ☾ property-based-testing ☽ ☾ testing ☽ ☾ defi ☽ ☾ blockchain ☽
⛤︎   NEXUS   ⛤︎

The Making of an Automated Market Maker: Constant Product Under a Market Price

☾   ⛤︎   ☽

How arbitrage drains a fixed-price pool, the constant-product pool that limits the loss, and the properties that measure both.

November 3, 2026 ⛤︎ 16 min rite ⛤︎ 3016 words

A pool that trades at a fixed price passes every property about its own books and still loses money as soon as the market price moves. Anyone can buy from it at the old price and sell elsewhere at the new one, and they can keep doing it until a reserve is empty.

This is the second post in a series about automated market makers, the programs that let anyone swap one token for another without a person on the other side. The first post built a constant-sum pool and introduced properties (rules the code must keep for every input, checked on random cases). This one adds a market price to the model, measures what arbitrage takes from that pool, and replaces it with a constant-product pool. The code is in the same public repository, and the version described here is tagged ch02-model.

The first post called the pool’s two balances jars. From here on they’re reserves, which is what the code calls them.

A fixed price loses value when the market moves

The pool from the first post holds 100 gold and 100 silver and trades them one for one. Now gold trades for two silver everywhere else.

A trader pays the pool 100 silver and gets its 100 gold, then sells the gold elsewhere for 200 silver. They started with 100 silver and end with 200, and the pool’s gold reserve is empty.

No property from the first post fails. The total is still 200 coins, the trader got one coin for each coin they paid, and no reserve went negative. Those properties only look at coin counts, and the loss doesn’t show in coin counts.

It shows once the reserves are valued at the market price. Before the trade, the pool held 100 gold worth 200 silver plus 100 silver, so 300 in all. After it, the pool holds 200 silver. The trader’s 100 silver profit is exactly the pool’s loss, since no one else was involved.

Buying where something is cheap and selling where it’s dear is arbitrage. Nothing in the swap rules prevents it, and in a pool with a fixed price, nothing limits it.

Pool value at a market price, as a property

That valuation gives a property: at the market price, a swap never makes the pool worth less. First, the valuation itself:

poolValue goldPrice (Pool gold silver) =
  goldPrice * fromInteger gold + fromInteger silver

goldPrice is how many silver one gold is worth on the market, and it can be a fraction, such as 3/2. (fromInteger only converts the coin counts so they can be multiplied by a fraction.)

Then the property, for the constant-sum pool:

prop_sumValueNeverDecreases (Positive goldPrice) pool s =
  case CS.swap s pool of
    Left _           -> property True
    Right (_, pool') -> property (sumPoolValue goldPrice pool' >= sumPoolValue goldPrice pool)

Positive goldPrice asks for a random gold price above zero. CS.swap is the first post’s swap; the test file uses both pools, so it puts CS. in front of everything from the constant-sum one and CP. in front of the constant-product one, which comes next. sumPoolValue is the same valuation as poolValue, for that pool.

A case looks at which shape the swap gave back and picks a line: a refusal passes as it is (property True is a test that always passes), and a success has to leave the pool worth at least as much as before. A _ stands for a part the line doesn’t need, here the reason for a refusal and the amount paid out, and pool' (read “pool prime”) is the pool after the swap.

The property is expected to fail. One run printed this:

+++ OK, failed as expected. Falsified (after 6 tests and 6 shrinks):
Positive {getPositive = 2 % 1}
Pool {gold = 1, silver = 0}
Swap {direction = SilverForGold, amountIn = 1}

The test file wraps this property in expectFailure, so the suite passes only if QuickCheck finds a case that breaks it. That keeps a known weakness of the constant-sum pool in the suite as a checked fact, instead of a red test everyone learns to ignore.

The last three lines are the case: a price of 2 (2 % 1 is the fraction 2/1), a pool with one gold and no silver, and a swap of one silver for gold. The pool sells a coin worth two silver for one, and its value drops from 2 to 1. It’s the 100-coin trade above, at the smallest size that still fails.

QuickCheck found a failing case on its sixth try, probably with larger numbers. It then tried smaller versions of that case, kept each one that still failed, and stopped when none of the smaller versions it tried failed. That’s called shrinking, and “6 shrinks” means six of those steps worked. A shrunk case is usually small enough to show the cause directly.

Constant product moves the price with each trade

The constant-sum pool loses so much because its price never moves: it sells every coin at the same price until the reserve is empty. The fix many real pools use is to let the reserves set the price: the smaller a reserve, the more its coins cost.

The rule that does it is constant product. Multiply the reserves: 100 gold times 100 silver is 10,000. Call that number k. A swap has to leave k where it was. Pay in 10 gold, and the gold reserve holds 110. For 110 times the silver to stay 10,000, the silver reserve has to drop to 90.9…, so the pool owes you 9.09… silver. It can only pay whole coins, so it rounds down and pays 9. The reserves now hold 110 and 91, and their product is 10,010: a little more than before, because the rounding left a fraction of a coin in the pool.

You paid 10 gold and got 9 silver, and the next trader gets less: one gold is now worth 91 ÷ 110, or about 0.83 silver, in the pool. That ratio is the pool’s price. An actual swap always gets less than it, because the swap itself moves the price and then rounds down.

A pool on this rule can’t be emptied. Buying the pool’s last silver would take infinitely much gold, so every swap pays out less than the reserve holds. Uniswap’s first two versions use this rule with a fee added; this model has no fee yet.

Where the formula comes from, for the curious

Call the reserve you pay into reserveIn and the one that pays you reserveOut. After the swap, the first holds reserveIn + amountIn and the second reserveOut - amountOut, and their product must still be reserveIn * reserveOut. Solve that for amountOut:

amountOut = reserveOut * amountIn / (reserveIn + amountIn)

With 100, 100 and 10, that’s 1,000 / 110 = 9.09…. And since reserveIn + amountIn is always more than amountIn, the fraction is always less than reserveOut: you never get the whole reserve.

The swap function gets a minimum and two new refusals

Here is the new swap:

swap (Swap direction amountIn minAmountOut) (Pool gold silver)
  | amountIn <= 0                = Left AmountNotPositive
  | gold <= 0 || silver <= 0     = Left EmptyPool
  | amountOut == 0
    || amountOut < minAmountOut  = Left OutputTooSmall
  | direction == GoldForSilver   =
      Right (amountOut, Pool (gold + amountIn)
                             (silver - amountOut))
  | otherwise                    =
      Right (amountOut, Pool (gold - amountOut)
                             (silver + amountIn))
  where
    -- keep reserveIn * reserveOut, rounding down in the pool's favour
    amountOut = reserveOut * amountIn `div` (reserveIn + amountIn)
    reserveIn  = if direction == GoldForSilver then gold else silver
    reserveOut = if direction == GoldForSilver then silver else gold

Most of it is the first post’s function. The changes are in three places.

The swap has a third field, minAmountOut: the least the trader will accept. The price now moves with every trade, including other traders’ trades that land first, so the price you saw may not be the price you get. A swap that would pay less than the minimum is refused.

InsufficientLiquidity is gone, since no swap can ask for more than the reserve holds. Two refusals replace it. EmptyPool refuses to trade when a reserve holds nothing (|| means “or”). Without it, a pool with no gold and 100 silver would give you all 100 silver for one gold, because the formula divides by an empty reserve plus your one coin. OutputTooSmall refuses a swap that would pay nothing, or less than the minimum.

The where block does the arithmetic. reserveIn and reserveOut pick the reserves by direction, and amountOut is the formula. div divides and rounds down, and the backticks let it sit between its two inputs, like *. The text after -- is a comment, written for people and ignored by the computer.

Rounding down keeps the fraction in the pool. Rounding up would let a swap take up to one coin more than the rule allows, which is enough to take the last coin from a small reserve, and a trader could choose amounts that do it every time.

Run the 10 gold through it. Is 10 at most zero? No. Is either reserve empty? No. amountOut is 100 × 10 div 110, which is 9: not zero, and not below a minimum of 0. You’re paying gold, so the answer is Right (9, Pool 110 91).

The widget below runs the same function. Set an amount and a minimum, then step through the guards, or open Predict the result and work out each answer before you look. As in the first post, its code panel shows the rest of the file, type lines included.

The model has more names now, and some are easy to mix up: amountIn is a payment, reserveIn is a reserve, and which reserve it is depends on the direction. The 15 cards below test these names and the ideas behind them. A card you miss comes round again.

Larger trades get worse prices

In the pool of 100 and 100, paying 10 gold gets you 9 silver, or 0.9 for each gold. Paying 100 gets you 50, which is 0.5 each. Paying 1,000 gets you 90: 0.09 each, for a trade that’s ten times larger and gets less than twice as much. Every coin you pay in moves the price against the next one. This is price impact, and it’s the cost of a pool that can’t be emptied.

Pool size matters as much as trade size. In a pool of 10,000 and 10,000, the same 100 gold gets 99 silver. Deeper pools give better prices.

The top chart below draws this pool’s rule as a curve, next to the first post’s straight line. A trade is a step along it. The chart under it shows the price each trade size gets.

Rounding bends the lower chart at the small end. Pay 1 gold, and the pool owes you 0.99… silver, which rounds down to nothing, so the swap is refused. Pay 2, and you get 1 silver: 0.5 each. Pay 3, and you get 2: 0.67 each. The larger trade got the better price, because rounding took a bigger share of the smaller one. Rounding always takes less than one coin, so the larger the trade, the less it matters, but a property about prices has to allow for it.

Six properties for the constant-product pool

The first post’s four properties described a pool with a fixed price. Each has a counterpart here, and two are new:

  • The product of the reserves never goes down, where the sum used to stay the same. Rounding makes it grow a little.
  • What comes out is less than the reserve it comes from, where it used to equal what went in.
  • A round trip never profits: swap, then swap straight back, and you get back at most what you paid. It used to restore the pool exactly; now rounding can keep some, and in a lopsided pool or after a large trade, quite a lot.
  • Both reserves stay above zero, where they used to stay at zero or above.
  • What comes out is at least minAmountOut.
  • A larger trade never gets a better price, except by what rounding took from the smaller one.

The first is the constant-product version of the first post’s sum property:

prop_productNeverDecreases pool s =
  whenSwapSucceeds pool s $ \_ pool' ->
    property (gold pool' * silver pool' >= gold pool * silver pool)

whenSwapSucceeds runs the swap and hands the check the amount paid out and the pool after it. property turns the yes-or-no answer into a test. The rest follow the same pattern. The one about prices is the most involved, because “except by what rounding took” has to be written down exactly.

How the rounding allowance is written, for the curious

The property makes a second swap, larger, that pays a random positive amount, extra, more than the first, and runs both on the same pool. amountOut is what the first one paid and amountOut' what the larger one paid. It checks two things, joined by .&&., which means both must hold:

amountOut' >= amountOut
  .&&. amountOut' * amountIn s < (amountOut + 1) * amountIn larger

The first says paying more never gets you less. The second compares prices, and its + 1 is the rounding: rounding took less than one coin from the first trade, so the larger trade can beat its price, but by less than one coin’s worth. Comparing a / b < c / d as a * d < c * b gives the same answer without dividing, and with whole numbers there’s nothing to round.

The widget below steps through any of the six on a generated case, as in the first post, and runs a hundred. The percentage in the result is how many of the generated swaps went through; the rest were refused, which is expected, since the inputs include negative amounts and empty pools on purpose.

All six pass. In the real test suite, each one runs on 800 to 1,600 cases, because QuickCheck keeps going until it’s sure that enough of its generated swaps went through.

Arbitrage against both pools

The constant-product pool’s version of the value property fails too. One run’s smallest case was a gold price of 2, a pool of 2 gold and 1 silver, and a swap of 1 silver for gold. That pool prices gold at half a silver, while the market says two. Pay 1 silver, and the formula gives you 2 × 1 ÷ (1 + 1), which is one gold, worth two silver. The pool was worth 5 silver, and now it’s worth 4.

So a moving price doesn’t prevent arbitrage; it limits it. Starting both pools at 100 and 100, with gold at two silver, the trader’s most profitable swap in each pool gives:

Constant sumConstant product
Trader’s swap100 silver for 100 gold37 silver for 27 gold
Trader’s profit100 silver17 silver
Pool value after200 silver283 silver
Pool price after1 silver per gold1.88 silver per gold
Reserve emptiedyes, the goldno

In the constant-product pool, a few larger swaps earn exactly the same 17 silver. After the best one, the pool’s price is close enough to the market’s 2 that no swap makes money any more, so the trader stops.

That’s how the constant-product pool follows the market without being told the market price: each arbitrage trade moves its price toward the market’s, and the trader’s profit is what the update costs the pool. The constant-sum pool’s price never moves, so it pays out until a reserve is empty and its price is still 1.

The 283 is also less than the 300 the coins would be worth if their owner had held them instead of putting them in the pool. DeFi calls that gap impermanent loss. It’s called impermanent because it would close again, give or take rounding, if gold went back to one silver.

The test suite checks emptying in two more properties: no swap empties a reserve that started with something. The constant-sum version fails within its first couple of tries; one run caught it on a pool of 1 and 1 and a swap of 1 gold. The constant-product version passes.

In the widget below, set a market price and press Trader swaps. A trader makes the most profitable swap in each pool, and the pools show what’s left. Under them are the four market properties and what a run of each finds. The widget’s runs pick their own numbers, so the smallest cases they find can differ from the ones above, often mirrored, with gold and silver swapped.

What the model shows so far

With a market price in the model, both pools fail the value property: a pool whose price differs from the market’s loses value to arbitrage. What differs is how much. The constant-sum pool loses until a reserve is empty. The constant-product pool loses only until its price is close to the market’s, and no swap can empty it. In exchange, every trade moves its price against the trader, by more in a smaller pool.

The model still has no fees, so every price correction is paid for by whoever supplied the reserves, and nothing in this model pays them for it. Fees, and who supplies the reserves, come later in the series. The next post implements this pool on Ethereum and checks the contract against the Haskell model.

☾  ⛤︎  ────────  ⛤︎  ☽
so it is written · so it is bound
☾ return to the archive ☽
inkspell
© 2026 inkspell RSS