inkspell
writing topics feed
MODE
THEME
← writing

The Making of an Automated Market Maker: The Pool on Ethereum

A Haskell model of a constant-product pool, rebuilt in Solidity, and the bug feature that six Foundry property tests let through.

November 6, 2026 · 19 min read
amm ethereum solidity foundry property-based-testing testing defi blockchain

Here’s a bug. You swap gold for silver at a pool that owes you 1,000 silver, and it pays you 999. It keeps one coin in every thousand.

Six tests ran against that pool, a thousand random trades each, and all six passed. Each one checks something the pool must never do, such as run out of coins, pay out more than it holds, or let you profit by trading back and forth. Paying you too little breaks none of those. Nothing checked how much you should get.

One more test catches the bug within a few tries, without ever working out the right payout: it checks that the pool could afford what it paid you, and couldn’t have afforded one coin more.

This is the third 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 previous post wrote such a pool as a small Haskell program, the model, along with rules it must keep for every input, its properties. This one rebuilds the pool as a Solidity contract for Ethereum and turns those rules into tests with Foundry, a toolkit for building and testing Solidity contracts.

The code is in the same public repository, and the version described here is tagged ch02-evm. Nothing runs the model and the contract on the same inputs yet: the checking is the model’s properties rewritten as Foundry tests, plus worked examples whose answers come from the model.

The contract computes the model’s swap

A contract is a program stored on the chain. It has its own storage, and anyone can call the functions it exposes, so any limit on who may call one has to be written into the function.

Here is the model’s swap from the last post:

swap :: Swap -> Pool -> Either SwapError (Integer, Pool)
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

And here is the first half of the contract’s:

function swap(bool zeroForOne, uint256 amountIn, uint256 minAmountOut)
    external
    returns (uint256 amountOut)
{
    if (amountIn == 0) revert AmountNotPositive();
    if (reserve0 == 0 || reserve1 == 0) revert EmptyPool();

    (uint256 reserveIn, uint256 reserveOut) =
        zeroForOne ? (reserve0, reserve1) : (reserve1, reserve0);

    // keep reserveIn * reserveOut, rounding down in the pool's favour
    amountOut = reserveOut * amountIn / (reserveIn + amountIn);
    if (amountOut == 0 || amountOut < minAmountOut) {
        revert OutputTooSmall();
    }
    // ...the new reserves, a log entry and two token transfers

The names follow Uniswap’s contracts rather than the model. A pool’s tokens are token0 and token1, so gold is token0 and silver is token1, and the model’s direction becomes a yes-or-no: zeroForOne is true for GoldForSilver. The reserves are reserve0 and reserve1, stored in the contract so they outlast the call.

The same guards come in the same order. revert stops the call, undoes every change it made, and reports the error, which is the model’s Left. The formula is the model’s, with / for div.

The rest writes the model’s new reserves into storage, logs the swap and moves the tokens, and moving tokens is where Ethereum differs most from the model.

Tokens are other contracts, and the pool can’t take them on its own

In the model, a pool is two numbers. On Ethereum, gold and silver are tokens, and each token is its own contract: it keeps a table of who holds how much and moves amounts between accounts, through a standard set of functions called ERC-20, which the code calls IERC20. The pool holds the addresses of its two token contracts, which it’s given when it’s deployed:

constructor(IERC20 token0_, IERC20 token1_) {
    if (address(token0_) == address(token1_)) revert IdenticalTokens();

    token0 = token0_;
    token1 = token1_;
    owner = msg.sender;
}

msg.sender is the account that made the call. Here it’s the account deploying the pool, which becomes the owner. token0, token1 and owner are declared immutable, so they’re set here once and can’t change afterwards.

The model can’t mix up its tokens, because they’re two different fields. A contract is handed two addresses, and they could be the same one, so the constructor refuses that.

Paying takes two steps. A contract can’t take tokens from your account on its own, so you first call the token’s approve, which lets the pool take up to an amount you choose. Then you call swap, and the pool moves amountIn from you to its own address, address(this), with the token’s transferFrom. Paying out needs no approval, since the pool is sending its own tokens. The safe versions of these calls come from OpenZeppelin’s library, and they turn a token that reports failure by returning false, instead of reverting, into a revert.

Four boxes, Trader, Gold token, Pool and Silver token, joined by four numbered arrows: 1 from Trader to Gold token, 2 from Trader to Pool, 3 from Pool to Gold token, 4 from Pool to Silver token. Four boxes, Trader, Gold token, Pool and Silver token, joined by four numbered arrows: 1 from Trader to Gold token, 2 from Trader to Pool, 3 from Pool to Gold token, 4 from Pool to Silver token.
① The trader approves the pool to take 100 gold. ② The trader calls swap. ③ The pool takes the 100 gold with transferFrom. ④ The pool pays the silver out with transfer.

The model starts a pool by writing one down: Pool 1000 4000. The contract starts empty, and its owner fills it once with initialize, which takes the two amounts from the owner’s account. It refuses anyone but the owner, a second call, and a zero amount. There’s no way back for the owner: no function withdraws the reserves, and tokens leave the pool only as a swap’s payout.

The reserves are the pool’s books, not its balances

The pool's books and the token contracts' balances drawn as two ledgers. A swap arrow changes both; a gift arrow from outside reaches only the balances; the price is read from the books. The pool's books and the token contracts' balances drawn as two ledgers. A swap arrow changes both; a gift arrow from outside reaches only the balances; the price is read from the books.
A swap changes the pool's books and its balances. A gift changes only the balances, and the price is read from the books.

reserve0 and reserve1 are the pool’s own record of what it holds, and only initialize and swap change them. The token contracts keep another record, the pool’s balance, and anyone can raise that by sending tokens to the pool’s address without calling the pool at all.

The pool prices from its books, so such a gift changes nothing. One test sends the pool 500 of each token after it opens with 1,000 and 1,000, and a swap of 100 still pays 90, which is the model’s answer for a pool of 1,000 and 1,000. The gift stays in the pool, off the books, and nothing can get it out. A gift to this pool is a gift to nobody.

Uniswap V2 works the other way: it measures what came in from its balances and then sets its reserves to them, so a gift there counts toward the next trader’s payment, unless someone claims it first or it’s added to the reserves. Both choices are right for something. Measuring what arrived is what lets V2 handle tokens that deliver less than was sent.

The model only knows two numbers, so this pool keeps its books to exactly those. Balances would need a bigger model, and that can wait. Matching the model is only worth something if the books match the real tokens, though, so the tests check that too: every swap moves both records by the same amount, and the books plus every gift always equal the balances.

The books settle before any tokens move

The second half of swap writes the new reserves, which are the model’s new Pool, logs the swap, and only then moves tokens:

    if (zeroForOne) {
        reserve0 = reserveIn + amountIn;
        reserve1 = reserveOut - amountOut;
    } else {
        reserve0 = reserveOut - amountOut;
        reserve1 = reserveIn + amountIn;
    }
    emit Swap(msg.sender, zeroForOne, amountIn, amountOut);

    // the books are settled before any other contract runs
    (IERC20 tokenIn, IERC20 tokenOut) =
        zeroForOne ? (token0, token1) : (token1, token0);
    tokenIn.safeTransferFrom(msg.sender, address(this), amountIn);
    tokenOut.safeTransfer(msg.sender, amountOut);
}

emit Swap(...) writes a log entry: who traded, which way, and how much went in and out. Contracts can’t read these logs, but wallets and other programs off the chain can, and that’s how they find out a trade happened.

The order matters because a token is someone else’s contract. Calling its transferFrom hands control to code the pool didn’t write, and that code could call the pool back before it returns. By then the pool has nothing left to do but move tokens: the price is worked out and the books already show the swap. This order — checks, then the contract’s own changes, then calls to other contracts — is known as checks-effects-interactions. The other common defence against being called back mid-change is a lock that refuses any call while the contract is running, which Uniswap V2 uses because it pays out before it checks.

The order doesn’t make every token safe. Say a trader swaps 100 gold, and the gold token calls the pool’s swap again from inside transferFrom, before it has moved those 100 gold. That second swap is priced from reserves that already count them. Whether that hurts anyone depends on the token, and the tests don’t try it.

The widget below steps through the whole of swap on a pool of 1,000 and 1,000, with the pool’s books on one side and the token contracts’ ledgers on the other. Send the pool a gift, or make the approval too small, and watch the gift stay off the books and a failed payment undo the swap.

uint256 rounds like the model, until a number doesn’t fit

The model’s amounts are Integers, which have no size limit. The contract’s are uint256: whole numbers from 0 up to 2^256 − 1, about 1.16 × 10^77. They can’t be negative, which is why the model’s amountIn <= 0 became amountIn == 0, and gold <= 0 || silver <= 0 became reserve0 == 0 || reserve1 == 0. Tokens count in whole units too: a token with 18 decimals counts one token as 10^18 units, and the pool only ever sees units.

Division on uint256 rounds down, as div does on amounts that aren’t negative, so the formula gives the same answer in both. From 10 and 10, a swap of 3 is owed 2.3 and gets 2 in either.

They part on size. Since version 0.8, Solidity checks its arithmetic: a result that doesn’t fit in 256 bits stops the call with an error, a panic, instead of wrapping round to a small number. In swap that can happen in two places, reserveOut * amountIn and reserveIn + amountIn.

One test opens a pool with 2^200 of each token and swaps 2^100: the product is 2^300, the swap reverts, and the model would have priced it. Another stocks 2^255 gold against 1 silver and swaps 2^255 gold, so the sum is 2^256, one past the limit. The model refuses that swap too, because it would pay nothing, but the contract panics before it gets that far.

No trade in an ordinary token gets near that. A trillion tokens with 18 decimals is 10^30 units, and multiplying two such amounts gives 10^60, still about 10^17 times below the limit. The edge also sits further out than it looks. A trade of 1,000 on a pool of 2^128 and 2^128 pays what the model says, although the product of those reserves doesn’t fit, because swap never multiplies the reserves together.

The tests hold the contract to the model in three layers

The contract is 113 lines of Solidity, comments included, and its test code is 872. The first layer is worked examples whose answers come from the model:

function test_SwapGoldForSilver() public {
    stock(1000, 4000);
    assertEq(trade(true, 100, 0), 363);
    assertReserves(1100, 3637);
}

stock opens the pool as its owner with 1,000 gold and 4,000 silver. trade gives a trader the tokens, approves the pool, swaps 100 gold with no minimum, and returns what the pool paid. For the same swap the model gives Right (363, Pool 1100 3637), so the test expects 363 and those reserves. trade also checks every swap it makes: the reserves and both sides’ token balances have to move by exactly what the swap returned, and the pool can’t leave behind an approval that would let the trader take more of its tokens later.

The second layer takes the model’s six properties and gives each a Foundry test with the same name. Foundry runs a test that takes parameters as a fuzz test: it calls it with random values, 1,000 times in this project. Here is the model’s product property from the last post, and then its Foundry version:

prop_productNeverDecreases pool s =
  whenSwapSucceeds pool s $ \_ pool' ->
    property (gold pool' * silver pool' >= gold pool * silver pool)
function testFuzz_ProductNeverDecreases(
    uint256 goldAmount,
    uint256 silverAmount,
    bool zeroForOne,
    uint256 amountIn
) public {
    stockFuzzed(goldAmount, silverAmount);
    uint256 product = pool.reserve0() * pool.reserve1();
    tradeOrDiscard(zeroForOne, bound(amountIn, 1, MAX_AMOUNT));
    assertGe(pool.reserve0() * pool.reserve1(), product);
}

In Haskell, the QuickCheck library generates a Pool and a Swap; Foundry generates plain numbers, and the test builds the pool from them. The reserves are declared public, so each comes with a reader of the same name, pool.reserve0(). bound squeezes a random number into a range, and the pools and amounts the tests draw top out at MAX_AMOUNT, just under 2^127, so that every product the tests compute fits in uint256.

tradeOrDiscard does the job of the model’s whenSwapSucceeds: it keeps only the cases where the swap goes through. With an open pool, a positive amount and no minimum, the only swap the model refuses is one that would pay nothing. tradeOrDiscard checks that the contract refuses it too, with OutputTooSmall, and drops the case so that Foundry draws another. The other five properties follow the same pattern, and separate tests try the other refusals.

Six passing properties can still miss an underpayment

A seventh property checks how much: the output must be the largest that keeps the product. Paying it leaves the product at least where it was, and paying one unit more would drop it below. Call the reserve the swap pays into reserveA and the one it pays out of reserveB, both as they stood before the swap, and their product product:

assertGe((reserveA + amountIn) * (reserveB - amountOut), product);
assertLt((reserveA + amountIn) * (reserveB - amountOut - 1), product);

The first line catches a pool that pays too much, and the second one that pays too little. Neither contains the formula. A test that computed the expected output with the contract’s own expression would agree with any mistake made in both places; this one only says what the formula is for.

To see what that buys, take a pool that keeps a thousandth of each payout, rounded down, so that payouts under 1,000 lose nothing:

amountOut -= amountOut / 1000;

That pool passes every worked example, since all their payouts are under 1,000, and a full run of all six ported properties. (The one that checks a larger trade gets a worse price can catch it, but only on rare cases that 1,000 random tries didn’t hit.) The largest-output property fails within its first few random cases.

The widget below has both halves. First, pick what a pool of 10,000 and 10,000 pays for 10,000 in, and predict whether each line passes before you look. Then run all seven properties against the honest pool and the one that keeps a thousandth.

What Foundry prints when a fuzz test fails, for the curious

On the pool that keeps a thousandth, one run printed this (line breaks added):

[FAIL: assertion failed:
  18704220734837674072343012655773089531733875925309751737023138085458909375840 >=
  18682919601675392751727817536409797336694041814402305259316382123064956977552;
counterexample: args=[
  27450250782494845564735763484632910622659017220630402784 [2.745e55],
  1002263738311142612063743378838805115008383020567598112900163816323564691 [1.002e72],
  false,
  10718926481285366298682078729364654839352494519779559358552621760462 [1.071e67]]]
testFuzz_OutputIsTheLargestThatKeepsTheProduct(uint256,uint256,bool,uint256) (runs: 6, μ: 757603, ~: 756965)

A failed assertLt(a, b) prints as a >= b. Here the first number is the product with one more unit paid out, and it’s still above the product before the swap, so the pool paid too little. The arguments are the numbers Foundry drew, before bound brought them into range, so they aren’t the pool’s reserves.

Eight invariants watch 50,000 random calls

Each fuzz test makes a swap or two on a fresh pool. The third layer makes long sequences of them. Foundry’s invariant tests call the functions of a chosen contract in random order with random arguments, and after each call check a list of conditions, the invariants.

Foundry holds a shuffled stack of swap and donate calls and sends them to Trader, which calls the Pool. Eight lit lamps beside the Pool are checked after every call. Foundry holds a shuffled stack of swap and donate calls and sends them to Trader, which calls the Pool. Eight lit lamps beside the Pool are checked after every call.
Foundry calls Trader in random order, Trader calls the pool, and all eight invariants are checked after every call.

The contract Foundry calls here is a test helper, Trader, with two actions. Its swap trades as one of three accounts, two traders and the pool’s owner. The owner trades like the others because the model has no owner: anything the contract did differently for the account that deployed it would be a departure from the model.

Each swap picks a random direction and amount, and one of three minimums: none, exactly what the model says it pays, or one more than that, which the pool must refuse. It also picks how the trader pays. Sometimes the trader holds exactly amountIn and approves exactly that. Otherwise the trader holds a spare unit and approves more, so a pool that took too much would get away with it, and the balance checks would see it.

Trader’s other action, donate, sends tokens straight to the pool without calling it. The pool opens with 1,000 gold and 4,000 silver, and Foundry makes 100 runs of 500 calls each.

For every swap, Trader works out what the model’s formula pays and raises a flag at any departure from the model: a wrong refusal or a wrong pass, a product that went down, an output that isn’t the largest, reserves or balances that moved by the wrong amount, or a missing or wrong log entry. Six of the eight invariants check that their flag is still down. The other two read the pool itself: both reserves stay positive, and each reserve plus what was donated equals the pool’s balance.

With Foundry 1.8.7, forge test in the repository’s evm folder printed this for the invariant suite:

[PASS] invariant_OutputIsTheLargestThatKeepsTheProduct
[PASS] invariant_ProductNeverDecreases
[PASS] invariant_ReservesMatchBalances
[PASS] invariant_ReservesStayPositive
[PASS] invariant_SwapsDoWhatTheyReturn
[PASS] invariant_SwapsLogWhatTheyDid
[PASS] invariant_SwapsThatDoNotPayAreRefused
[PASS] invariant_SwapsThatPayGoThrough
 ConstantProductPoolInvariantTest invariants (runs: 100, calls: 50000, reverts: 0)

Foundry counts the eight invariants as one test, because they share one run of calls, so with the 30 worked examples and fuzz tests the total is 31. reverts: 0 doesn’t mean no swap was refused. Trader catches the pool’s refusals and judges them, and the project’s settings fail the run if a call to Trader itself reverts.

The same suite failed against the pool that keeps a thousandth. Foundry doesn’t simplify a failing fuzz test’s inputs, but it does simplify a failing invariant run, by dropping calls from the sequence: it cut that one from 14 calls to a single swap.

What the tests show, and what they don’t

On the cases they try, and with amounts that fit in uint256, the contract gives the model’s answers: the same payouts, the same refusals in the same order, and books that match the pool’s balances apart from gifts. The invariant run shows the same across long sequences, with several traders, the owner among them. And the one test that never writes the formula down catches a pool paying a thousandth too little, which the other six passed.

That’s evidence, not proof. The fuzz tests and the invariant run try random cases, and the link to the model is a translation: the worked examples’ answers were worked out with the model, and its properties were rewritten in Solidity, where a mistake in the rewriting would go unnoticed.

The tests also use only plain tokens, so three kinds of token go untested:

  • A token that takes a fee on each transfer. From 1,000 and 1,000, a swap of 100 with a minimum of 90 goes through, and with a 10% fee on the way out the trader receives 81, below the minimum the pool checked. A fee on the way in leaves the reserves above the pool’s balance.
  • A token that calls back into the pool during a transfer, while the books already count tokens that haven’t arrived.
  • A token that reports failure by returning false. SafeERC20 should refuse it, but the test token only ever reverts, so nothing checks that it does.

The next post asks how much these tests would notice: it plants bugs in the contract and counts how many of them the tests catch.

← Back to all writing
Last login: Fri, Nov 6, 00:00:00 on ttys001
user@inkspell:~/blog read constant-product-on-ethereum.md
FILE: constant-product-on-ethereum.md DATE: 2026-11-06 WORDS: 3753 READ: ~19m
TAGS: [amm] [ethereum] [solidity] [foundry] [property-based-testing] [testing] [defi] [blockchain]

The Making of an Automated Market Maker: The Pool on Ethereum

// A Haskell model of a constant-product pool, rebuilt in Solidity, and the bug feature that six Foundry property tests let through.

» BEGIN OUTPUT

Here’s a bug. You swap gold for silver at a pool that owes you 1,000 silver, and it pays you 999. It keeps one coin in every thousand.

Six tests ran against that pool, a thousand random trades each, and all six passed. Each one checks something the pool must never do, such as run out of coins, pay out more than it holds, or let you profit by trading back and forth. Paying you too little breaks none of those. Nothing checked how much you should get.

One more test catches the bug within a few tries, without ever working out the right payout: it checks that the pool could afford what it paid you, and couldn’t have afforded one coin more.

This is the third 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 previous post wrote such a pool as a small Haskell program, the model, along with rules it must keep for every input, its properties. This one rebuilds the pool as a Solidity contract for Ethereum and turns those rules into tests with Foundry, a toolkit for building and testing Solidity contracts.

The code is in the same public repository, and the version described here is tagged ch02-evm. Nothing runs the model and the contract on the same inputs yet: the checking is the model’s properties rewritten as Foundry tests, plus worked examples whose answers come from the model.

The contract computes the model’s swap

A contract is a program stored on the chain. It has its own storage, and anyone can call the functions it exposes, so any limit on who may call one has to be written into the function.

Here is the model’s swap from the last post:

swap :: Swap -> Pool -> Either SwapError (Integer, Pool)
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

And here is the first half of the contract’s:

function swap(bool zeroForOne, uint256 amountIn, uint256 minAmountOut)
    external
    returns (uint256 amountOut)
{
    if (amountIn == 0) revert AmountNotPositive();
    if (reserve0 == 0 || reserve1 == 0) revert EmptyPool();

    (uint256 reserveIn, uint256 reserveOut) =
        zeroForOne ? (reserve0, reserve1) : (reserve1, reserve0);

    // keep reserveIn * reserveOut, rounding down in the pool's favour
    amountOut = reserveOut * amountIn / (reserveIn + amountIn);
    if (amountOut == 0 || amountOut < minAmountOut) {
        revert OutputTooSmall();
    }
    // ...the new reserves, a log entry and two token transfers

The names follow Uniswap’s contracts rather than the model. A pool’s tokens are token0 and token1, so gold is token0 and silver is token1, and the model’s direction becomes a yes-or-no: zeroForOne is true for GoldForSilver. The reserves are reserve0 and reserve1, stored in the contract so they outlast the call.

The same guards come in the same order. revert stops the call, undoes every change it made, and reports the error, which is the model’s Left. The formula is the model’s, with / for div.

The rest writes the model’s new reserves into storage, logs the swap and moves the tokens, and moving tokens is where Ethereum differs most from the model.

Tokens are other contracts, and the pool can’t take them on its own

In the model, a pool is two numbers. On Ethereum, gold and silver are tokens, and each token is its own contract: it keeps a table of who holds how much and moves amounts between accounts, through a standard set of functions called ERC-20, which the code calls IERC20. The pool holds the addresses of its two token contracts, which it’s given when it’s deployed:

constructor(IERC20 token0_, IERC20 token1_) {
    if (address(token0_) == address(token1_)) revert IdenticalTokens();

    token0 = token0_;
    token1 = token1_;
    owner = msg.sender;
}

msg.sender is the account that made the call. Here it’s the account deploying the pool, which becomes the owner. token0, token1 and owner are declared immutable, so they’re set here once and can’t change afterwards.

The model can’t mix up its tokens, because they’re two different fields. A contract is handed two addresses, and they could be the same one, so the constructor refuses that.

Paying takes two steps. A contract can’t take tokens from your account on its own, so you first call the token’s approve, which lets the pool take up to an amount you choose. Then you call swap, and the pool moves amountIn from you to its own address, address(this), with the token’s transferFrom. Paying out needs no approval, since the pool is sending its own tokens. The safe versions of these calls come from OpenZeppelin’s library, and they turn a token that reports failure by returning false, instead of reverting, into a revert.

Four boxes, Trader, Gold token, Pool and Silver token, joined by four numbered arrows: 1 from Trader to Gold token, 2 from Trader to Pool, 3 from Pool to Gold token, 4 from Pool to Silver token. Four boxes, Trader, Gold token, Pool and Silver token, joined by four numbered arrows: 1 from Trader to Gold token, 2 from Trader to Pool, 3 from Pool to Gold token, 4 from Pool to Silver token.
① The trader approves the pool to take 100 gold. ② The trader calls swap. ③ The pool takes the 100 gold with transferFrom. ④ The pool pays the silver out with transfer.

The model starts a pool by writing one down: Pool 1000 4000. The contract starts empty, and its owner fills it once with initialize, which takes the two amounts from the owner’s account. It refuses anyone but the owner, a second call, and a zero amount. There’s no way back for the owner: no function withdraws the reserves, and tokens leave the pool only as a swap’s payout.

The reserves are the pool’s books, not its balances

The pool's books and the token contracts' balances drawn as two ledgers. A swap arrow changes both; a gift arrow from outside reaches only the balances; the price is read from the books. The pool's books and the token contracts' balances drawn as two ledgers. A swap arrow changes both; a gift arrow from outside reaches only the balances; the price is read from the books.
A swap changes the pool's books and its balances. A gift changes only the balances, and the price is read from the books.

reserve0 and reserve1 are the pool’s own record of what it holds, and only initialize and swap change them. The token contracts keep another record, the pool’s balance, and anyone can raise that by sending tokens to the pool’s address without calling the pool at all.

The pool prices from its books, so such a gift changes nothing. One test sends the pool 500 of each token after it opens with 1,000 and 1,000, and a swap of 100 still pays 90, which is the model’s answer for a pool of 1,000 and 1,000. The gift stays in the pool, off the books, and nothing can get it out. A gift to this pool is a gift to nobody.

Uniswap V2 works the other way: it measures what came in from its balances and then sets its reserves to them, so a gift there counts toward the next trader’s payment, unless someone claims it first or it’s added to the reserves. Both choices are right for something. Measuring what arrived is what lets V2 handle tokens that deliver less than was sent.

The model only knows two numbers, so this pool keeps its books to exactly those. Balances would need a bigger model, and that can wait. Matching the model is only worth something if the books match the real tokens, though, so the tests check that too: every swap moves both records by the same amount, and the books plus every gift always equal the balances.

The books settle before any tokens move

The second half of swap writes the new reserves, which are the model’s new Pool, logs the swap, and only then moves tokens:

    if (zeroForOne) {
        reserve0 = reserveIn + amountIn;
        reserve1 = reserveOut - amountOut;
    } else {
        reserve0 = reserveOut - amountOut;
        reserve1 = reserveIn + amountIn;
    }
    emit Swap(msg.sender, zeroForOne, amountIn, amountOut);

    // the books are settled before any other contract runs
    (IERC20 tokenIn, IERC20 tokenOut) =
        zeroForOne ? (token0, token1) : (token1, token0);
    tokenIn.safeTransferFrom(msg.sender, address(this), amountIn);
    tokenOut.safeTransfer(msg.sender, amountOut);
}

emit Swap(...) writes a log entry: who traded, which way, and how much went in and out. Contracts can’t read these logs, but wallets and other programs off the chain can, and that’s how they find out a trade happened.

The order matters because a token is someone else’s contract. Calling its transferFrom hands control to code the pool didn’t write, and that code could call the pool back before it returns. By then the pool has nothing left to do but move tokens: the price is worked out and the books already show the swap. This order — checks, then the contract’s own changes, then calls to other contracts — is known as checks-effects-interactions. The other common defence against being called back mid-change is a lock that refuses any call while the contract is running, which Uniswap V2 uses because it pays out before it checks.

The order doesn’t make every token safe. Say a trader swaps 100 gold, and the gold token calls the pool’s swap again from inside transferFrom, before it has moved those 100 gold. That second swap is priced from reserves that already count them. Whether that hurts anyone depends on the token, and the tests don’t try it.

The widget below steps through the whole of swap on a pool of 1,000 and 1,000, with the pool’s books on one side and the token contracts’ ledgers on the other. Send the pool a gift, or make the approval too small, and watch the gift stay off the books and a failed payment undo the swap.

uint256 rounds like the model, until a number doesn’t fit

The model’s amounts are Integers, which have no size limit. The contract’s are uint256: whole numbers from 0 up to 2^256 − 1, about 1.16 × 10^77. They can’t be negative, which is why the model’s amountIn <= 0 became amountIn == 0, and gold <= 0 || silver <= 0 became reserve0 == 0 || reserve1 == 0. Tokens count in whole units too: a token with 18 decimals counts one token as 10^18 units, and the pool only ever sees units.

Division on uint256 rounds down, as div does on amounts that aren’t negative, so the formula gives the same answer in both. From 10 and 10, a swap of 3 is owed 2.3 and gets 2 in either.

They part on size. Since version 0.8, Solidity checks its arithmetic: a result that doesn’t fit in 256 bits stops the call with an error, a panic, instead of wrapping round to a small number. In swap that can happen in two places, reserveOut * amountIn and reserveIn + amountIn.

One test opens a pool with 2^200 of each token and swaps 2^100: the product is 2^300, the swap reverts, and the model would have priced it. Another stocks 2^255 gold against 1 silver and swaps 2^255 gold, so the sum is 2^256, one past the limit. The model refuses that swap too, because it would pay nothing, but the contract panics before it gets that far.

No trade in an ordinary token gets near that. A trillion tokens with 18 decimals is 10^30 units, and multiplying two such amounts gives 10^60, still about 10^17 times below the limit. The edge also sits further out than it looks. A trade of 1,000 on a pool of 2^128 and 2^128 pays what the model says, although the product of those reserves doesn’t fit, because swap never multiplies the reserves together.

The tests hold the contract to the model in three layers

The contract is 113 lines of Solidity, comments included, and its test code is 872. The first layer is worked examples whose answers come from the model:

function test_SwapGoldForSilver() public {
    stock(1000, 4000);
    assertEq(trade(true, 100, 0), 363);
    assertReserves(1100, 3637);
}

stock opens the pool as its owner with 1,000 gold and 4,000 silver. trade gives a trader the tokens, approves the pool, swaps 100 gold with no minimum, and returns what the pool paid. For the same swap the model gives Right (363, Pool 1100 3637), so the test expects 363 and those reserves. trade also checks every swap it makes: the reserves and both sides’ token balances have to move by exactly what the swap returned, and the pool can’t leave behind an approval that would let the trader take more of its tokens later.

The second layer takes the model’s six properties and gives each a Foundry test with the same name. Foundry runs a test that takes parameters as a fuzz test: it calls it with random values, 1,000 times in this project. Here is the model’s product property from the last post, and then its Foundry version:

prop_productNeverDecreases pool s =
  whenSwapSucceeds pool s $ \_ pool' ->
    property (gold pool' * silver pool' >= gold pool * silver pool)
function testFuzz_ProductNeverDecreases(
    uint256 goldAmount,
    uint256 silverAmount,
    bool zeroForOne,
    uint256 amountIn
) public {
    stockFuzzed(goldAmount, silverAmount);
    uint256 product = pool.reserve0() * pool.reserve1();
    tradeOrDiscard(zeroForOne, bound(amountIn, 1, MAX_AMOUNT));
    assertGe(pool.reserve0() * pool.reserve1(), product);
}

In Haskell, the QuickCheck library generates a Pool and a Swap; Foundry generates plain numbers, and the test builds the pool from them. The reserves are declared public, so each comes with a reader of the same name, pool.reserve0(). bound squeezes a random number into a range, and the pools and amounts the tests draw top out at MAX_AMOUNT, just under 2^127, so that every product the tests compute fits in uint256.

tradeOrDiscard does the job of the model’s whenSwapSucceeds: it keeps only the cases where the swap goes through. With an open pool, a positive amount and no minimum, the only swap the model refuses is one that would pay nothing. tradeOrDiscard checks that the contract refuses it too, with OutputTooSmall, and drops the case so that Foundry draws another. The other five properties follow the same pattern, and separate tests try the other refusals.

Six passing properties can still miss an underpayment

A seventh property checks how much: the output must be the largest that keeps the product. Paying it leaves the product at least where it was, and paying one unit more would drop it below. Call the reserve the swap pays into reserveA and the one it pays out of reserveB, both as they stood before the swap, and their product product:

assertGe((reserveA + amountIn) * (reserveB - amountOut), product);
assertLt((reserveA + amountIn) * (reserveB - amountOut - 1), product);

The first line catches a pool that pays too much, and the second one that pays too little. Neither contains the formula. A test that computed the expected output with the contract’s own expression would agree with any mistake made in both places; this one only says what the formula is for.

To see what that buys, take a pool that keeps a thousandth of each payout, rounded down, so that payouts under 1,000 lose nothing:

amountOut -= amountOut / 1000;

That pool passes every worked example, since all their payouts are under 1,000, and a full run of all six ported properties. (The one that checks a larger trade gets a worse price can catch it, but only on rare cases that 1,000 random tries didn’t hit.) The largest-output property fails within its first few random cases.

The widget below has both halves. First, pick what a pool of 10,000 and 10,000 pays for 10,000 in, and predict whether each line passes before you look. Then run all seven properties against the honest pool and the one that keeps a thousandth.

What Foundry prints when a fuzz test fails, for the curious

On the pool that keeps a thousandth, one run printed this (line breaks added):

[FAIL: assertion failed:
  18704220734837674072343012655773089531733875925309751737023138085458909375840 >=
  18682919601675392751727817536409797336694041814402305259316382123064956977552;
counterexample: args=[
  27450250782494845564735763484632910622659017220630402784 [2.745e55],
  1002263738311142612063743378838805115008383020567598112900163816323564691 [1.002e72],
  false,
  10718926481285366298682078729364654839352494519779559358552621760462 [1.071e67]]]
testFuzz_OutputIsTheLargestThatKeepsTheProduct(uint256,uint256,bool,uint256) (runs: 6, μ: 757603, ~: 756965)

A failed assertLt(a, b) prints as a >= b. Here the first number is the product with one more unit paid out, and it’s still above the product before the swap, so the pool paid too little. The arguments are the numbers Foundry drew, before bound brought them into range, so they aren’t the pool’s reserves.

Eight invariants watch 50,000 random calls

Each fuzz test makes a swap or two on a fresh pool. The third layer makes long sequences of them. Foundry’s invariant tests call the functions of a chosen contract in random order with random arguments, and after each call check a list of conditions, the invariants.

Foundry holds a shuffled stack of swap and donate calls and sends them to Trader, which calls the Pool. Eight lit lamps beside the Pool are checked after every call. Foundry holds a shuffled stack of swap and donate calls and sends them to Trader, which calls the Pool. Eight lit lamps beside the Pool are checked after every call.
Foundry calls Trader in random order, Trader calls the pool, and all eight invariants are checked after every call.

The contract Foundry calls here is a test helper, Trader, with two actions. Its swap trades as one of three accounts, two traders and the pool’s owner. The owner trades like the others because the model has no owner: anything the contract did differently for the account that deployed it would be a departure from the model.

Each swap picks a random direction and amount, and one of three minimums: none, exactly what the model says it pays, or one more than that, which the pool must refuse. It also picks how the trader pays. Sometimes the trader holds exactly amountIn and approves exactly that. Otherwise the trader holds a spare unit and approves more, so a pool that took too much would get away with it, and the balance checks would see it.

Trader’s other action, donate, sends tokens straight to the pool without calling it. The pool opens with 1,000 gold and 4,000 silver, and Foundry makes 100 runs of 500 calls each.

For every swap, Trader works out what the model’s formula pays and raises a flag at any departure from the model: a wrong refusal or a wrong pass, a product that went down, an output that isn’t the largest, reserves or balances that moved by the wrong amount, or a missing or wrong log entry. Six of the eight invariants check that their flag is still down. The other two read the pool itself: both reserves stay positive, and each reserve plus what was donated equals the pool’s balance.

With Foundry 1.8.7, forge test in the repository’s evm folder printed this for the invariant suite:

[PASS] invariant_OutputIsTheLargestThatKeepsTheProduct
[PASS] invariant_ProductNeverDecreases
[PASS] invariant_ReservesMatchBalances
[PASS] invariant_ReservesStayPositive
[PASS] invariant_SwapsDoWhatTheyReturn
[PASS] invariant_SwapsLogWhatTheyDid
[PASS] invariant_SwapsThatDoNotPayAreRefused
[PASS] invariant_SwapsThatPayGoThrough
 ConstantProductPoolInvariantTest invariants (runs: 100, calls: 50000, reverts: 0)

Foundry counts the eight invariants as one test, because they share one run of calls, so with the 30 worked examples and fuzz tests the total is 31. reverts: 0 doesn’t mean no swap was refused. Trader catches the pool’s refusals and judges them, and the project’s settings fail the run if a call to Trader itself reverts.

The same suite failed against the pool that keeps a thousandth. Foundry doesn’t simplify a failing fuzz test’s inputs, but it does simplify a failing invariant run, by dropping calls from the sequence: it cut that one from 14 calls to a single swap.

What the tests show, and what they don’t

On the cases they try, and with amounts that fit in uint256, the contract gives the model’s answers: the same payouts, the same refusals in the same order, and books that match the pool’s balances apart from gifts. The invariant run shows the same across long sequences, with several traders, the owner among them. And the one test that never writes the formula down catches a pool paying a thousandth too little, which the other six passed.

That’s evidence, not proof. The fuzz tests and the invariant run try random cases, and the link to the model is a translation: the worked examples’ answers were worked out with the model, and its properties were rewritten in Solidity, where a mistake in the rewriting would go unnoticed.

The tests also use only plain tokens, so three kinds of token go untested:

  • A token that takes a fee on each transfer. From 1,000 and 1,000, a swap of 100 with a minimum of 90 goes through, and with a 10% fee on the way out the trader receives 81, below the minimum the pool checked. A fee on the way in leaves the reserves above the pool’s balance.
  • A token that calls back into the pool during a transfer, while the books already count tokens that haven’t arrived.
  • A token that reports failure by returning false. SafeERC20 should refuse it, but the test token only ever reverts, so nothing checks that it does.

The next post asks how much these tests would notice: it plants bugs in the contract and counts how many of them the tests catch.

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

The Making of an Automated Market Maker: The Pool on Ethereum

☸︎

A Haskell model of a constant-product pool, rebuilt in Solidity, and the bug feature that six Foundry property tests let through.

session · 19 min sitting · November 6, 2026
— enter the practice —

Here’s a bug. You swap gold for silver at a pool that owes you 1,000 silver, and it pays you 999. It keeps one coin in every thousand.

Six tests ran against that pool, a thousand random trades each, and all six passed. Each one checks something the pool must never do, such as run out of coins, pay out more than it holds, or let you profit by trading back and forth. Paying you too little breaks none of those. Nothing checked how much you should get.

One more test catches the bug within a few tries, without ever working out the right payout: it checks that the pool could afford what it paid you, and couldn’t have afforded one coin more.

This is the third 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 previous post wrote such a pool as a small Haskell program, the model, along with rules it must keep for every input, its properties. This one rebuilds the pool as a Solidity contract for Ethereum and turns those rules into tests with Foundry, a toolkit for building and testing Solidity contracts.

The code is in the same public repository, and the version described here is tagged ch02-evm. Nothing runs the model and the contract on the same inputs yet: the checking is the model’s properties rewritten as Foundry tests, plus worked examples whose answers come from the model.

The contract computes the model’s swap

A contract is a program stored on the chain. It has its own storage, and anyone can call the functions it exposes, so any limit on who may call one has to be written into the function.

Here is the model’s swap from the last post:

swap :: Swap -> Pool -> Either SwapError (Integer, Pool)
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

And here is the first half of the contract’s:

function swap(bool zeroForOne, uint256 amountIn, uint256 minAmountOut)
    external
    returns (uint256 amountOut)
{
    if (amountIn == 0) revert AmountNotPositive();
    if (reserve0 == 0 || reserve1 == 0) revert EmptyPool();

    (uint256 reserveIn, uint256 reserveOut) =
        zeroForOne ? (reserve0, reserve1) : (reserve1, reserve0);

    // keep reserveIn * reserveOut, rounding down in the pool's favour
    amountOut = reserveOut * amountIn / (reserveIn + amountIn);
    if (amountOut == 0 || amountOut < minAmountOut) {
        revert OutputTooSmall();
    }
    // ...the new reserves, a log entry and two token transfers

The names follow Uniswap’s contracts rather than the model. A pool’s tokens are token0 and token1, so gold is token0 and silver is token1, and the model’s direction becomes a yes-or-no: zeroForOne is true for GoldForSilver. The reserves are reserve0 and reserve1, stored in the contract so they outlast the call.

The same guards come in the same order. revert stops the call, undoes every change it made, and reports the error, which is the model’s Left. The formula is the model’s, with / for div.

The rest writes the model’s new reserves into storage, logs the swap and moves the tokens, and moving tokens is where Ethereum differs most from the model.

Tokens are other contracts, and the pool can’t take them on its own

In the model, a pool is two numbers. On Ethereum, gold and silver are tokens, and each token is its own contract: it keeps a table of who holds how much and moves amounts between accounts, through a standard set of functions called ERC-20, which the code calls IERC20. The pool holds the addresses of its two token contracts, which it’s given when it’s deployed:

constructor(IERC20 token0_, IERC20 token1_) {
    if (address(token0_) == address(token1_)) revert IdenticalTokens();

    token0 = token0_;
    token1 = token1_;
    owner = msg.sender;
}

msg.sender is the account that made the call. Here it’s the account deploying the pool, which becomes the owner. token0, token1 and owner are declared immutable, so they’re set here once and can’t change afterwards.

The model can’t mix up its tokens, because they’re two different fields. A contract is handed two addresses, and they could be the same one, so the constructor refuses that.

Paying takes two steps. A contract can’t take tokens from your account on its own, so you first call the token’s approve, which lets the pool take up to an amount you choose. Then you call swap, and the pool moves amountIn from you to its own address, address(this), with the token’s transferFrom. Paying out needs no approval, since the pool is sending its own tokens. The safe versions of these calls come from OpenZeppelin’s library, and they turn a token that reports failure by returning false, instead of reverting, into a revert.

Four boxes, Trader, Gold token, Pool and Silver token, joined by four numbered arrows: 1 from Trader to Gold token, 2 from Trader to Pool, 3 from Pool to Gold token, 4 from Pool to Silver token. Four boxes, Trader, Gold token, Pool and Silver token, joined by four numbered arrows: 1 from Trader to Gold token, 2 from Trader to Pool, 3 from Pool to Gold token, 4 from Pool to Silver token.
① The trader approves the pool to take 100 gold. ② The trader calls swap. ③ The pool takes the 100 gold with transferFrom. ④ The pool pays the silver out with transfer.

The model starts a pool by writing one down: Pool 1000 4000. The contract starts empty, and its owner fills it once with initialize, which takes the two amounts from the owner’s account. It refuses anyone but the owner, a second call, and a zero amount. There’s no way back for the owner: no function withdraws the reserves, and tokens leave the pool only as a swap’s payout.

The reserves are the pool’s books, not its balances

The pool's books and the token contracts' balances drawn as two ledgers. A swap arrow changes both; a gift arrow from outside reaches only the balances; the price is read from the books. The pool's books and the token contracts' balances drawn as two ledgers. A swap arrow changes both; a gift arrow from outside reaches only the balances; the price is read from the books.
A swap changes the pool's books and its balances. A gift changes only the balances, and the price is read from the books.

reserve0 and reserve1 are the pool’s own record of what it holds, and only initialize and swap change them. The token contracts keep another record, the pool’s balance, and anyone can raise that by sending tokens to the pool’s address without calling the pool at all.

The pool prices from its books, so such a gift changes nothing. One test sends the pool 500 of each token after it opens with 1,000 and 1,000, and a swap of 100 still pays 90, which is the model’s answer for a pool of 1,000 and 1,000. The gift stays in the pool, off the books, and nothing can get it out. A gift to this pool is a gift to nobody.

Uniswap V2 works the other way: it measures what came in from its balances and then sets its reserves to them, so a gift there counts toward the next trader’s payment, unless someone claims it first or it’s added to the reserves. Both choices are right for something. Measuring what arrived is what lets V2 handle tokens that deliver less than was sent.

The model only knows two numbers, so this pool keeps its books to exactly those. Balances would need a bigger model, and that can wait. Matching the model is only worth something if the books match the real tokens, though, so the tests check that too: every swap moves both records by the same amount, and the books plus every gift always equal the balances.

The books settle before any tokens move

The second half of swap writes the new reserves, which are the model’s new Pool, logs the swap, and only then moves tokens:

    if (zeroForOne) {
        reserve0 = reserveIn + amountIn;
        reserve1 = reserveOut - amountOut;
    } else {
        reserve0 = reserveOut - amountOut;
        reserve1 = reserveIn + amountIn;
    }
    emit Swap(msg.sender, zeroForOne, amountIn, amountOut);

    // the books are settled before any other contract runs
    (IERC20 tokenIn, IERC20 tokenOut) =
        zeroForOne ? (token0, token1) : (token1, token0);
    tokenIn.safeTransferFrom(msg.sender, address(this), amountIn);
    tokenOut.safeTransfer(msg.sender, amountOut);
}

emit Swap(...) writes a log entry: who traded, which way, and how much went in and out. Contracts can’t read these logs, but wallets and other programs off the chain can, and that’s how they find out a trade happened.

The order matters because a token is someone else’s contract. Calling its transferFrom hands control to code the pool didn’t write, and that code could call the pool back before it returns. By then the pool has nothing left to do but move tokens: the price is worked out and the books already show the swap. This order — checks, then the contract’s own changes, then calls to other contracts — is known as checks-effects-interactions. The other common defence against being called back mid-change is a lock that refuses any call while the contract is running, which Uniswap V2 uses because it pays out before it checks.

The order doesn’t make every token safe. Say a trader swaps 100 gold, and the gold token calls the pool’s swap again from inside transferFrom, before it has moved those 100 gold. That second swap is priced from reserves that already count them. Whether that hurts anyone depends on the token, and the tests don’t try it.

The widget below steps through the whole of swap on a pool of 1,000 and 1,000, with the pool’s books on one side and the token contracts’ ledgers on the other. Send the pool a gift, or make the approval too small, and watch the gift stay off the books and a failed payment undo the swap.

uint256 rounds like the model, until a number doesn’t fit

The model’s amounts are Integers, which have no size limit. The contract’s are uint256: whole numbers from 0 up to 2^256 − 1, about 1.16 × 10^77. They can’t be negative, which is why the model’s amountIn <= 0 became amountIn == 0, and gold <= 0 || silver <= 0 became reserve0 == 0 || reserve1 == 0. Tokens count in whole units too: a token with 18 decimals counts one token as 10^18 units, and the pool only ever sees units.

Division on uint256 rounds down, as div does on amounts that aren’t negative, so the formula gives the same answer in both. From 10 and 10, a swap of 3 is owed 2.3 and gets 2 in either.

They part on size. Since version 0.8, Solidity checks its arithmetic: a result that doesn’t fit in 256 bits stops the call with an error, a panic, instead of wrapping round to a small number. In swap that can happen in two places, reserveOut * amountIn and reserveIn + amountIn.

One test opens a pool with 2^200 of each token and swaps 2^100: the product is 2^300, the swap reverts, and the model would have priced it. Another stocks 2^255 gold against 1 silver and swaps 2^255 gold, so the sum is 2^256, one past the limit. The model refuses that swap too, because it would pay nothing, but the contract panics before it gets that far.

No trade in an ordinary token gets near that. A trillion tokens with 18 decimals is 10^30 units, and multiplying two such amounts gives 10^60, still about 10^17 times below the limit. The edge also sits further out than it looks. A trade of 1,000 on a pool of 2^128 and 2^128 pays what the model says, although the product of those reserves doesn’t fit, because swap never multiplies the reserves together.

The tests hold the contract to the model in three layers

The contract is 113 lines of Solidity, comments included, and its test code is 872. The first layer is worked examples whose answers come from the model:

function test_SwapGoldForSilver() public {
    stock(1000, 4000);
    assertEq(trade(true, 100, 0), 363);
    assertReserves(1100, 3637);
}

stock opens the pool as its owner with 1,000 gold and 4,000 silver. trade gives a trader the tokens, approves the pool, swaps 100 gold with no minimum, and returns what the pool paid. For the same swap the model gives Right (363, Pool 1100 3637), so the test expects 363 and those reserves. trade also checks every swap it makes: the reserves and both sides’ token balances have to move by exactly what the swap returned, and the pool can’t leave behind an approval that would let the trader take more of its tokens later.

The second layer takes the model’s six properties and gives each a Foundry test with the same name. Foundry runs a test that takes parameters as a fuzz test: it calls it with random values, 1,000 times in this project. Here is the model’s product property from the last post, and then its Foundry version:

prop_productNeverDecreases pool s =
  whenSwapSucceeds pool s $ \_ pool' ->
    property (gold pool' * silver pool' >= gold pool * silver pool)
function testFuzz_ProductNeverDecreases(
    uint256 goldAmount,
    uint256 silverAmount,
    bool zeroForOne,
    uint256 amountIn
) public {
    stockFuzzed(goldAmount, silverAmount);
    uint256 product = pool.reserve0() * pool.reserve1();
    tradeOrDiscard(zeroForOne, bound(amountIn, 1, MAX_AMOUNT));
    assertGe(pool.reserve0() * pool.reserve1(), product);
}

In Haskell, the QuickCheck library generates a Pool and a Swap; Foundry generates plain numbers, and the test builds the pool from them. The reserves are declared public, so each comes with a reader of the same name, pool.reserve0(). bound squeezes a random number into a range, and the pools and amounts the tests draw top out at MAX_AMOUNT, just under 2^127, so that every product the tests compute fits in uint256.

tradeOrDiscard does the job of the model’s whenSwapSucceeds: it keeps only the cases where the swap goes through. With an open pool, a positive amount and no minimum, the only swap the model refuses is one that would pay nothing. tradeOrDiscard checks that the contract refuses it too, with OutputTooSmall, and drops the case so that Foundry draws another. The other five properties follow the same pattern, and separate tests try the other refusals.

Six passing properties can still miss an underpayment

A seventh property checks how much: the output must be the largest that keeps the product. Paying it leaves the product at least where it was, and paying one unit more would drop it below. Call the reserve the swap pays into reserveA and the one it pays out of reserveB, both as they stood before the swap, and their product product:

assertGe((reserveA + amountIn) * (reserveB - amountOut), product);
assertLt((reserveA + amountIn) * (reserveB - amountOut - 1), product);

The first line catches a pool that pays too much, and the second one that pays too little. Neither contains the formula. A test that computed the expected output with the contract’s own expression would agree with any mistake made in both places; this one only says what the formula is for.

To see what that buys, take a pool that keeps a thousandth of each payout, rounded down, so that payouts under 1,000 lose nothing:

amountOut -= amountOut / 1000;

That pool passes every worked example, since all their payouts are under 1,000, and a full run of all six ported properties. (The one that checks a larger trade gets a worse price can catch it, but only on rare cases that 1,000 random tries didn’t hit.) The largest-output property fails within its first few random cases.

The widget below has both halves. First, pick what a pool of 10,000 and 10,000 pays for 10,000 in, and predict whether each line passes before you look. Then run all seven properties against the honest pool and the one that keeps a thousandth.

What Foundry prints when a fuzz test fails, for the curious

On the pool that keeps a thousandth, one run printed this (line breaks added):

[FAIL: assertion failed:
  18704220734837674072343012655773089531733875925309751737023138085458909375840 >=
  18682919601675392751727817536409797336694041814402305259316382123064956977552;
counterexample: args=[
  27450250782494845564735763484632910622659017220630402784 [2.745e55],
  1002263738311142612063743378838805115008383020567598112900163816323564691 [1.002e72],
  false,
  10718926481285366298682078729364654839352494519779559358552621760462 [1.071e67]]]
testFuzz_OutputIsTheLargestThatKeepsTheProduct(uint256,uint256,bool,uint256) (runs: 6, μ: 757603, ~: 756965)

A failed assertLt(a, b) prints as a >= b. Here the first number is the product with one more unit paid out, and it’s still above the product before the swap, so the pool paid too little. The arguments are the numbers Foundry drew, before bound brought them into range, so they aren’t the pool’s reserves.

Eight invariants watch 50,000 random calls

Each fuzz test makes a swap or two on a fresh pool. The third layer makes long sequences of them. Foundry’s invariant tests call the functions of a chosen contract in random order with random arguments, and after each call check a list of conditions, the invariants.

Foundry holds a shuffled stack of swap and donate calls and sends them to Trader, which calls the Pool. Eight lit lamps beside the Pool are checked after every call. Foundry holds a shuffled stack of swap and donate calls and sends them to Trader, which calls the Pool. Eight lit lamps beside the Pool are checked after every call.
Foundry calls Trader in random order, Trader calls the pool, and all eight invariants are checked after every call.

The contract Foundry calls here is a test helper, Trader, with two actions. Its swap trades as one of three accounts, two traders and the pool’s owner. The owner trades like the others because the model has no owner: anything the contract did differently for the account that deployed it would be a departure from the model.

Each swap picks a random direction and amount, and one of three minimums: none, exactly what the model says it pays, or one more than that, which the pool must refuse. It also picks how the trader pays. Sometimes the trader holds exactly amountIn and approves exactly that. Otherwise the trader holds a spare unit and approves more, so a pool that took too much would get away with it, and the balance checks would see it.

Trader’s other action, donate, sends tokens straight to the pool without calling it. The pool opens with 1,000 gold and 4,000 silver, and Foundry makes 100 runs of 500 calls each.

For every swap, Trader works out what the model’s formula pays and raises a flag at any departure from the model: a wrong refusal or a wrong pass, a product that went down, an output that isn’t the largest, reserves or balances that moved by the wrong amount, or a missing or wrong log entry. Six of the eight invariants check that their flag is still down. The other two read the pool itself: both reserves stay positive, and each reserve plus what was donated equals the pool’s balance.

With Foundry 1.8.7, forge test in the repository’s evm folder printed this for the invariant suite:

[PASS] invariant_OutputIsTheLargestThatKeepsTheProduct
[PASS] invariant_ProductNeverDecreases
[PASS] invariant_ReservesMatchBalances
[PASS] invariant_ReservesStayPositive
[PASS] invariant_SwapsDoWhatTheyReturn
[PASS] invariant_SwapsLogWhatTheyDid
[PASS] invariant_SwapsThatDoNotPayAreRefused
[PASS] invariant_SwapsThatPayGoThrough
 ConstantProductPoolInvariantTest invariants (runs: 100, calls: 50000, reverts: 0)

Foundry counts the eight invariants as one test, because they share one run of calls, so with the 30 worked examples and fuzz tests the total is 31. reverts: 0 doesn’t mean no swap was refused. Trader catches the pool’s refusals and judges them, and the project’s settings fail the run if a call to Trader itself reverts.

The same suite failed against the pool that keeps a thousandth. Foundry doesn’t simplify a failing fuzz test’s inputs, but it does simplify a failing invariant run, by dropping calls from the sequence: it cut that one from 14 calls to a single swap.

What the tests show, and what they don’t

On the cases they try, and with amounts that fit in uint256, the contract gives the model’s answers: the same payouts, the same refusals in the same order, and books that match the pool’s balances apart from gifts. The invariant run shows the same across long sequences, with several traders, the owner among them. And the one test that never writes the formula down catches a pool paying a thousandth too little, which the other six passed.

That’s evidence, not proof. The fuzz tests and the invariant run try random cases, and the link to the model is a translation: the worked examples’ answers were worked out with the model, and its properties were rewritten in Solidity, where a mistake in the rewriting would go unnoticed.

The tests also use only plain tokens, so three kinds of token go untested:

  • A token that takes a fee on each transfer. From 1,000 and 1,000, a swap of 100 with a minimum of 90 goes through, and with a 10% fee on the way out the trader receives 81, below the minimum the pool checked. A fee on the way in leaves the reserves above the pool’s balance.
  • A token that calls back into the pool during a transfer, while the books already count tokens that haven’t arrived.
  • A token that reports failure by returning false. SafeERC20 should refuse it, but the test token only ever reverts, so nothing checks that it does.

The next post asks how much these tests would notice: it plants bugs in the contract and counts how many of them the tests catch.

☸︎
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-06 00:00:00 from somewhere you'll regret  ·  session pid 1352
⚡ luser activity is being monitored. it always was. 9 LARTs administered today.
☠︎ BOFH EXCUSE #1154 :: someone enabled DHCP on the wrong VLAN again
root@larts-server:/var/rants # cat constant-product-on-ethereum.txt  # and what was your username again?
SUBJECT: The Making of an Automated Market Maker: The Pool on Ethereum
DATE: 2026-11-06 00:00:00 READ: ~19 min of your billable downtime WORDS: 3753
TAGS: [amm] [ethereum] [solidity] [foundry] [property-based-testing] [testing] [defi] [blockchain]
// A Haskell model of a constant-product pool, rebuilt in Solidity, and the bug feature that six Foundry property tests let through.
☠︎ ::: BEGIN TRANSMISSION — touch nothing ::: ☠︎

Here’s a bug. You swap gold for silver at a pool that owes you 1,000 silver, and it pays you 999. It keeps one coin in every thousand.

Six tests ran against that pool, a thousand random trades each, and all six passed. Each one checks something the pool must never do, such as run out of coins, pay out more than it holds, or let you profit by trading back and forth. Paying you too little breaks none of those. Nothing checked how much you should get.

One more test catches the bug within a few tries, without ever working out the right payout: it checks that the pool could afford what it paid you, and couldn’t have afforded one coin more.

This is the third 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 previous post wrote such a pool as a small Haskell program, the model, along with rules it must keep for every input, its properties. This one rebuilds the pool as a Solidity contract for Ethereum and turns those rules into tests with Foundry, a toolkit for building and testing Solidity contracts.

The code is in the same public repository, and the version described here is tagged ch02-evm. Nothing runs the model and the contract on the same inputs yet: the checking is the model’s properties rewritten as Foundry tests, plus worked examples whose answers come from the model.

The contract computes the model’s swap

A contract is a program stored on the chain. It has its own storage, and anyone can call the functions it exposes, so any limit on who may call one has to be written into the function.

Here is the model’s swap from the last post:

swap :: Swap -> Pool -> Either SwapError (Integer, Pool)
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

And here is the first half of the contract’s:

function swap(bool zeroForOne, uint256 amountIn, uint256 minAmountOut)
    external
    returns (uint256 amountOut)
{
    if (amountIn == 0) revert AmountNotPositive();
    if (reserve0 == 0 || reserve1 == 0) revert EmptyPool();

    (uint256 reserveIn, uint256 reserveOut) =
        zeroForOne ? (reserve0, reserve1) : (reserve1, reserve0);

    // keep reserveIn * reserveOut, rounding down in the pool's favour
    amountOut = reserveOut * amountIn / (reserveIn + amountIn);
    if (amountOut == 0 || amountOut < minAmountOut) {
        revert OutputTooSmall();
    }
    // ...the new reserves, a log entry and two token transfers

The names follow Uniswap’s contracts rather than the model. A pool’s tokens are token0 and token1, so gold is token0 and silver is token1, and the model’s direction becomes a yes-or-no: zeroForOne is true for GoldForSilver. The reserves are reserve0 and reserve1, stored in the contract so they outlast the call.

The same guards come in the same order. revert stops the call, undoes every change it made, and reports the error, which is the model’s Left. The formula is the model’s, with / for div.

The rest writes the model’s new reserves into storage, logs the swap and moves the tokens, and moving tokens is where Ethereum differs most from the model.

Tokens are other contracts, and the pool can’t take them on its own

In the model, a pool is two numbers. On Ethereum, gold and silver are tokens, and each token is its own contract: it keeps a table of who holds how much and moves amounts between accounts, through a standard set of functions called ERC-20, which the code calls IERC20. The pool holds the addresses of its two token contracts, which it’s given when it’s deployed:

constructor(IERC20 token0_, IERC20 token1_) {
    if (address(token0_) == address(token1_)) revert IdenticalTokens();

    token0 = token0_;
    token1 = token1_;
    owner = msg.sender;
}

msg.sender is the account that made the call. Here it’s the account deploying the pool, which becomes the owner. token0, token1 and owner are declared immutable, so they’re set here once and can’t change afterwards.

The model can’t mix up its tokens, because they’re two different fields. A contract is handed two addresses, and they could be the same one, so the constructor refuses that.

Paying takes two steps. A contract can’t take tokens from your account on its own, so you first call the token’s approve, which lets the pool take up to an amount you choose. Then you call swap, and the pool moves amountIn from you to its own address, address(this), with the token’s transferFrom. Paying out needs no approval, since the pool is sending its own tokens. The safe versions of these calls come from OpenZeppelin’s library, and they turn a token that reports failure by returning false, instead of reverting, into a revert.

Four boxes, Trader, Gold token, Pool and Silver token, joined by four numbered arrows: 1 from Trader to Gold token, 2 from Trader to Pool, 3 from Pool to Gold token, 4 from Pool to Silver token. Four boxes, Trader, Gold token, Pool and Silver token, joined by four numbered arrows: 1 from Trader to Gold token, 2 from Trader to Pool, 3 from Pool to Gold token, 4 from Pool to Silver token.
① The trader approves the pool to take 100 gold. ② The trader calls swap. ③ The pool takes the 100 gold with transferFrom. ④ The pool pays the silver out with transfer.

The model starts a pool by writing one down: Pool 1000 4000. The contract starts empty, and its owner fills it once with initialize, which takes the two amounts from the owner’s account. It refuses anyone but the owner, a second call, and a zero amount. There’s no way back for the owner: no function withdraws the reserves, and tokens leave the pool only as a swap’s payout.

The reserves are the pool’s books, not its balances

The pool's books and the token contracts' balances drawn as two ledgers. A swap arrow changes both; a gift arrow from outside reaches only the balances; the price is read from the books. The pool's books and the token contracts' balances drawn as two ledgers. A swap arrow changes both; a gift arrow from outside reaches only the balances; the price is read from the books.
A swap changes the pool's books and its balances. A gift changes only the balances, and the price is read from the books.

reserve0 and reserve1 are the pool’s own record of what it holds, and only initialize and swap change them. The token contracts keep another record, the pool’s balance, and anyone can raise that by sending tokens to the pool’s address without calling the pool at all.

The pool prices from its books, so such a gift changes nothing. One test sends the pool 500 of each token after it opens with 1,000 and 1,000, and a swap of 100 still pays 90, which is the model’s answer for a pool of 1,000 and 1,000. The gift stays in the pool, off the books, and nothing can get it out. A gift to this pool is a gift to nobody.

Uniswap V2 works the other way: it measures what came in from its balances and then sets its reserves to them, so a gift there counts toward the next trader’s payment, unless someone claims it first or it’s added to the reserves. Both choices are right for something. Measuring what arrived is what lets V2 handle tokens that deliver less than was sent.

The model only knows two numbers, so this pool keeps its books to exactly those. Balances would need a bigger model, and that can wait. Matching the model is only worth something if the books match the real tokens, though, so the tests check that too: every swap moves both records by the same amount, and the books plus every gift always equal the balances.

The books settle before any tokens move

The second half of swap writes the new reserves, which are the model’s new Pool, logs the swap, and only then moves tokens:

    if (zeroForOne) {
        reserve0 = reserveIn + amountIn;
        reserve1 = reserveOut - amountOut;
    } else {
        reserve0 = reserveOut - amountOut;
        reserve1 = reserveIn + amountIn;
    }
    emit Swap(msg.sender, zeroForOne, amountIn, amountOut);

    // the books are settled before any other contract runs
    (IERC20 tokenIn, IERC20 tokenOut) =
        zeroForOne ? (token0, token1) : (token1, token0);
    tokenIn.safeTransferFrom(msg.sender, address(this), amountIn);
    tokenOut.safeTransfer(msg.sender, amountOut);
}

emit Swap(...) writes a log entry: who traded, which way, and how much went in and out. Contracts can’t read these logs, but wallets and other programs off the chain can, and that’s how they find out a trade happened.

The order matters because a token is someone else’s contract. Calling its transferFrom hands control to code the pool didn’t write, and that code could call the pool back before it returns. By then the pool has nothing left to do but move tokens: the price is worked out and the books already show the swap. This order — checks, then the contract’s own changes, then calls to other contracts — is known as checks-effects-interactions. The other common defence against being called back mid-change is a lock that refuses any call while the contract is running, which Uniswap V2 uses because it pays out before it checks.

The order doesn’t make every token safe. Say a trader swaps 100 gold, and the gold token calls the pool’s swap again from inside transferFrom, before it has moved those 100 gold. That second swap is priced from reserves that already count them. Whether that hurts anyone depends on the token, and the tests don’t try it.

The widget below steps through the whole of swap on a pool of 1,000 and 1,000, with the pool’s books on one side and the token contracts’ ledgers on the other. Send the pool a gift, or make the approval too small, and watch the gift stay off the books and a failed payment undo the swap.

uint256 rounds like the model, until a number doesn’t fit

The model’s amounts are Integers, which have no size limit. The contract’s are uint256: whole numbers from 0 up to 2^256 − 1, about 1.16 × 10^77. They can’t be negative, which is why the model’s amountIn <= 0 became amountIn == 0, and gold <= 0 || silver <= 0 became reserve0 == 0 || reserve1 == 0. Tokens count in whole units too: a token with 18 decimals counts one token as 10^18 units, and the pool only ever sees units.

Division on uint256 rounds down, as div does on amounts that aren’t negative, so the formula gives the same answer in both. From 10 and 10, a swap of 3 is owed 2.3 and gets 2 in either.

They part on size. Since version 0.8, Solidity checks its arithmetic: a result that doesn’t fit in 256 bits stops the call with an error, a panic, instead of wrapping round to a small number. In swap that can happen in two places, reserveOut * amountIn and reserveIn + amountIn.

One test opens a pool with 2^200 of each token and swaps 2^100: the product is 2^300, the swap reverts, and the model would have priced it. Another stocks 2^255 gold against 1 silver and swaps 2^255 gold, so the sum is 2^256, one past the limit. The model refuses that swap too, because it would pay nothing, but the contract panics before it gets that far.

No trade in an ordinary token gets near that. A trillion tokens with 18 decimals is 10^30 units, and multiplying two such amounts gives 10^60, still about 10^17 times below the limit. The edge also sits further out than it looks. A trade of 1,000 on a pool of 2^128 and 2^128 pays what the model says, although the product of those reserves doesn’t fit, because swap never multiplies the reserves together.

The tests hold the contract to the model in three layers

The contract is 113 lines of Solidity, comments included, and its test code is 872. The first layer is worked examples whose answers come from the model:

function test_SwapGoldForSilver() public {
    stock(1000, 4000);
    assertEq(trade(true, 100, 0), 363);
    assertReserves(1100, 3637);
}

stock opens the pool as its owner with 1,000 gold and 4,000 silver. trade gives a trader the tokens, approves the pool, swaps 100 gold with no minimum, and returns what the pool paid. For the same swap the model gives Right (363, Pool 1100 3637), so the test expects 363 and those reserves. trade also checks every swap it makes: the reserves and both sides’ token balances have to move by exactly what the swap returned, and the pool can’t leave behind an approval that would let the trader take more of its tokens later.

The second layer takes the model’s six properties and gives each a Foundry test with the same name. Foundry runs a test that takes parameters as a fuzz test: it calls it with random values, 1,000 times in this project. Here is the model’s product property from the last post, and then its Foundry version:

prop_productNeverDecreases pool s =
  whenSwapSucceeds pool s $ \_ pool' ->
    property (gold pool' * silver pool' >= gold pool * silver pool)
function testFuzz_ProductNeverDecreases(
    uint256 goldAmount,
    uint256 silverAmount,
    bool zeroForOne,
    uint256 amountIn
) public {
    stockFuzzed(goldAmount, silverAmount);
    uint256 product = pool.reserve0() * pool.reserve1();
    tradeOrDiscard(zeroForOne, bound(amountIn, 1, MAX_AMOUNT));
    assertGe(pool.reserve0() * pool.reserve1(), product);
}

In Haskell, the QuickCheck library generates a Pool and a Swap; Foundry generates plain numbers, and the test builds the pool from them. The reserves are declared public, so each comes with a reader of the same name, pool.reserve0(). bound squeezes a random number into a range, and the pools and amounts the tests draw top out at MAX_AMOUNT, just under 2^127, so that every product the tests compute fits in uint256.

tradeOrDiscard does the job of the model’s whenSwapSucceeds: it keeps only the cases where the swap goes through. With an open pool, a positive amount and no minimum, the only swap the model refuses is one that would pay nothing. tradeOrDiscard checks that the contract refuses it too, with OutputTooSmall, and drops the case so that Foundry draws another. The other five properties follow the same pattern, and separate tests try the other refusals.

Six passing properties can still miss an underpayment

A seventh property checks how much: the output must be the largest that keeps the product. Paying it leaves the product at least where it was, and paying one unit more would drop it below. Call the reserve the swap pays into reserveA and the one it pays out of reserveB, both as they stood before the swap, and their product product:

assertGe((reserveA + amountIn) * (reserveB - amountOut), product);
assertLt((reserveA + amountIn) * (reserveB - amountOut - 1), product);

The first line catches a pool that pays too much, and the second one that pays too little. Neither contains the formula. A test that computed the expected output with the contract’s own expression would agree with any mistake made in both places; this one only says what the formula is for.

To see what that buys, take a pool that keeps a thousandth of each payout, rounded down, so that payouts under 1,000 lose nothing:

amountOut -= amountOut / 1000;

That pool passes every worked example, since all their payouts are under 1,000, and a full run of all six ported properties. (The one that checks a larger trade gets a worse price can catch it, but only on rare cases that 1,000 random tries didn’t hit.) The largest-output property fails within its first few random cases.

The widget below has both halves. First, pick what a pool of 10,000 and 10,000 pays for 10,000 in, and predict whether each line passes before you look. Then run all seven properties against the honest pool and the one that keeps a thousandth.

What Foundry prints when a fuzz test fails, for the curious

On the pool that keeps a thousandth, one run printed this (line breaks added):

[FAIL: assertion failed:
  18704220734837674072343012655773089531733875925309751737023138085458909375840 >=
  18682919601675392751727817536409797336694041814402305259316382123064956977552;
counterexample: args=[
  27450250782494845564735763484632910622659017220630402784 [2.745e55],
  1002263738311142612063743378838805115008383020567598112900163816323564691 [1.002e72],
  false,
  10718926481285366298682078729364654839352494519779559358552621760462 [1.071e67]]]
testFuzz_OutputIsTheLargestThatKeepsTheProduct(uint256,uint256,bool,uint256) (runs: 6, μ: 757603, ~: 756965)

A failed assertLt(a, b) prints as a >= b. Here the first number is the product with one more unit paid out, and it’s still above the product before the swap, so the pool paid too little. The arguments are the numbers Foundry drew, before bound brought them into range, so they aren’t the pool’s reserves.

Eight invariants watch 50,000 random calls

Each fuzz test makes a swap or two on a fresh pool. The third layer makes long sequences of them. Foundry’s invariant tests call the functions of a chosen contract in random order with random arguments, and after each call check a list of conditions, the invariants.

Foundry holds a shuffled stack of swap and donate calls and sends them to Trader, which calls the Pool. Eight lit lamps beside the Pool are checked after every call. Foundry holds a shuffled stack of swap and donate calls and sends them to Trader, which calls the Pool. Eight lit lamps beside the Pool are checked after every call.
Foundry calls Trader in random order, Trader calls the pool, and all eight invariants are checked after every call.

The contract Foundry calls here is a test helper, Trader, with two actions. Its swap trades as one of three accounts, two traders and the pool’s owner. The owner trades like the others because the model has no owner: anything the contract did differently for the account that deployed it would be a departure from the model.

Each swap picks a random direction and amount, and one of three minimums: none, exactly what the model says it pays, or one more than that, which the pool must refuse. It also picks how the trader pays. Sometimes the trader holds exactly amountIn and approves exactly that. Otherwise the trader holds a spare unit and approves more, so a pool that took too much would get away with it, and the balance checks would see it.

Trader’s other action, donate, sends tokens straight to the pool without calling it. The pool opens with 1,000 gold and 4,000 silver, and Foundry makes 100 runs of 500 calls each.

For every swap, Trader works out what the model’s formula pays and raises a flag at any departure from the model: a wrong refusal or a wrong pass, a product that went down, an output that isn’t the largest, reserves or balances that moved by the wrong amount, or a missing or wrong log entry. Six of the eight invariants check that their flag is still down. The other two read the pool itself: both reserves stay positive, and each reserve plus what was donated equals the pool’s balance.

With Foundry 1.8.7, forge test in the repository’s evm folder printed this for the invariant suite:

[PASS] invariant_OutputIsTheLargestThatKeepsTheProduct
[PASS] invariant_ProductNeverDecreases
[PASS] invariant_ReservesMatchBalances
[PASS] invariant_ReservesStayPositive
[PASS] invariant_SwapsDoWhatTheyReturn
[PASS] invariant_SwapsLogWhatTheyDid
[PASS] invariant_SwapsThatDoNotPayAreRefused
[PASS] invariant_SwapsThatPayGoThrough
 ConstantProductPoolInvariantTest invariants (runs: 100, calls: 50000, reverts: 0)

Foundry counts the eight invariants as one test, because they share one run of calls, so with the 30 worked examples and fuzz tests the total is 31. reverts: 0 doesn’t mean no swap was refused. Trader catches the pool’s refusals and judges them, and the project’s settings fail the run if a call to Trader itself reverts.

The same suite failed against the pool that keeps a thousandth. Foundry doesn’t simplify a failing fuzz test’s inputs, but it does simplify a failing invariant run, by dropping calls from the sequence: it cut that one from 14 calls to a single swap.

What the tests show, and what they don’t

On the cases they try, and with amounts that fit in uint256, the contract gives the model’s answers: the same payouts, the same refusals in the same order, and books that match the pool’s balances apart from gifts. The invariant run shows the same across long sequences, with several traders, the owner among them. And the one test that never writes the formula down catches a pool paying a thousandth too little, which the other six passed.

That’s evidence, not proof. The fuzz tests and the invariant run try random cases, and the link to the model is a translation: the worked examples’ answers were worked out with the model, and its properties were rewritten in Solidity, where a mistake in the rewriting would go unnoticed.

The tests also use only plain tokens, so three kinds of token go untested:

  • A token that takes a fee on each transfer. From 1,000 and 1,000, a swap of 100 with a minimum of 90 goes through, and with a 10% fee on the way out the trader receives 81, below the minimum the pool checked. A fee on the way in leaves the reserves above the pool’s balance.
  • A token that calls back into the pool during a transfer, while the books already count tokens that haven’t arrived.
  • A token that reports failure by returning false. SafeERC20 should refuse it, but the test token only ever reverts, so nothing checks that it does.

The next post asks how much these tests would notice: it plants bugs in the contract and counts how many of them the tests catch.

☠︎ ::: END OF FILE — this never happened ::: ☠︎
[2026-11-06 00:00:00] SYSTEM: outstanding tickets resolved via /dev/null: 2,847
[2026-11-06 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 ☽ ☾ ethereum ☽ ☾ solidity ☽ ☾ foundry ☽ ☾ property-based-testing ☽ ☾ testing ☽ ☾ defi ☽ ☾ blockchain ☽
⛤︎   FATUM   ⛤︎

The Making of an Automated Market Maker: The Pool on Ethereum

☾   ⛤︎   ☽

A Haskell model of a constant-product pool, rebuilt in Solidity, and the bug feature that six Foundry property tests let through.

November 6, 2026 ⛤︎ 19 min rite ⛤︎ 3753 words

Here’s a bug. You swap gold for silver at a pool that owes you 1,000 silver, and it pays you 999. It keeps one coin in every thousand.

Six tests ran against that pool, a thousand random trades each, and all six passed. Each one checks something the pool must never do, such as run out of coins, pay out more than it holds, or let you profit by trading back and forth. Paying you too little breaks none of those. Nothing checked how much you should get.

One more test catches the bug within a few tries, without ever working out the right payout: it checks that the pool could afford what it paid you, and couldn’t have afforded one coin more.

This is the third 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 previous post wrote such a pool as a small Haskell program, the model, along with rules it must keep for every input, its properties. This one rebuilds the pool as a Solidity contract for Ethereum and turns those rules into tests with Foundry, a toolkit for building and testing Solidity contracts.

The code is in the same public repository, and the version described here is tagged ch02-evm. Nothing runs the model and the contract on the same inputs yet: the checking is the model’s properties rewritten as Foundry tests, plus worked examples whose answers come from the model.

The contract computes the model’s swap

A contract is a program stored on the chain. It has its own storage, and anyone can call the functions it exposes, so any limit on who may call one has to be written into the function.

Here is the model’s swap from the last post:

swap :: Swap -> Pool -> Either SwapError (Integer, Pool)
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

And here is the first half of the contract’s:

function swap(bool zeroForOne, uint256 amountIn, uint256 minAmountOut)
    external
    returns (uint256 amountOut)
{
    if (amountIn == 0) revert AmountNotPositive();
    if (reserve0 == 0 || reserve1 == 0) revert EmptyPool();

    (uint256 reserveIn, uint256 reserveOut) =
        zeroForOne ? (reserve0, reserve1) : (reserve1, reserve0);

    // keep reserveIn * reserveOut, rounding down in the pool's favour
    amountOut = reserveOut * amountIn / (reserveIn + amountIn);
    if (amountOut == 0 || amountOut < minAmountOut) {
        revert OutputTooSmall();
    }
    // ...the new reserves, a log entry and two token transfers

The names follow Uniswap’s contracts rather than the model. A pool’s tokens are token0 and token1, so gold is token0 and silver is token1, and the model’s direction becomes a yes-or-no: zeroForOne is true for GoldForSilver. The reserves are reserve0 and reserve1, stored in the contract so they outlast the call.

The same guards come in the same order. revert stops the call, undoes every change it made, and reports the error, which is the model’s Left. The formula is the model’s, with / for div.

The rest writes the model’s new reserves into storage, logs the swap and moves the tokens, and moving tokens is where Ethereum differs most from the model.

Tokens are other contracts, and the pool can’t take them on its own

In the model, a pool is two numbers. On Ethereum, gold and silver are tokens, and each token is its own contract: it keeps a table of who holds how much and moves amounts between accounts, through a standard set of functions called ERC-20, which the code calls IERC20. The pool holds the addresses of its two token contracts, which it’s given when it’s deployed:

constructor(IERC20 token0_, IERC20 token1_) {
    if (address(token0_) == address(token1_)) revert IdenticalTokens();

    token0 = token0_;
    token1 = token1_;
    owner = msg.sender;
}

msg.sender is the account that made the call. Here it’s the account deploying the pool, which becomes the owner. token0, token1 and owner are declared immutable, so they’re set here once and can’t change afterwards.

The model can’t mix up its tokens, because they’re two different fields. A contract is handed two addresses, and they could be the same one, so the constructor refuses that.

Paying takes two steps. A contract can’t take tokens from your account on its own, so you first call the token’s approve, which lets the pool take up to an amount you choose. Then you call swap, and the pool moves amountIn from you to its own address, address(this), with the token’s transferFrom. Paying out needs no approval, since the pool is sending its own tokens. The safe versions of these calls come from OpenZeppelin’s library, and they turn a token that reports failure by returning false, instead of reverting, into a revert.

Four boxes, Trader, Gold token, Pool and Silver token, joined by four numbered arrows: 1 from Trader to Gold token, 2 from Trader to Pool, 3 from Pool to Gold token, 4 from Pool to Silver token. Four boxes, Trader, Gold token, Pool and Silver token, joined by four numbered arrows: 1 from Trader to Gold token, 2 from Trader to Pool, 3 from Pool to Gold token, 4 from Pool to Silver token.
① The trader approves the pool to take 100 gold. ② The trader calls swap. ③ The pool takes the 100 gold with transferFrom. ④ The pool pays the silver out with transfer.

The model starts a pool by writing one down: Pool 1000 4000. The contract starts empty, and its owner fills it once with initialize, which takes the two amounts from the owner’s account. It refuses anyone but the owner, a second call, and a zero amount. There’s no way back for the owner: no function withdraws the reserves, and tokens leave the pool only as a swap’s payout.

The reserves are the pool’s books, not its balances

The pool's books and the token contracts' balances drawn as two ledgers. A swap arrow changes both; a gift arrow from outside reaches only the balances; the price is read from the books. The pool's books and the token contracts' balances drawn as two ledgers. A swap arrow changes both; a gift arrow from outside reaches only the balances; the price is read from the books.
A swap changes the pool's books and its balances. A gift changes only the balances, and the price is read from the books.

reserve0 and reserve1 are the pool’s own record of what it holds, and only initialize and swap change them. The token contracts keep another record, the pool’s balance, and anyone can raise that by sending tokens to the pool’s address without calling the pool at all.

The pool prices from its books, so such a gift changes nothing. One test sends the pool 500 of each token after it opens with 1,000 and 1,000, and a swap of 100 still pays 90, which is the model’s answer for a pool of 1,000 and 1,000. The gift stays in the pool, off the books, and nothing can get it out. A gift to this pool is a gift to nobody.

Uniswap V2 works the other way: it measures what came in from its balances and then sets its reserves to them, so a gift there counts toward the next trader’s payment, unless someone claims it first or it’s added to the reserves. Both choices are right for something. Measuring what arrived is what lets V2 handle tokens that deliver less than was sent.

The model only knows two numbers, so this pool keeps its books to exactly those. Balances would need a bigger model, and that can wait. Matching the model is only worth something if the books match the real tokens, though, so the tests check that too: every swap moves both records by the same amount, and the books plus every gift always equal the balances.

The books settle before any tokens move

The second half of swap writes the new reserves, which are the model’s new Pool, logs the swap, and only then moves tokens:

    if (zeroForOne) {
        reserve0 = reserveIn + amountIn;
        reserve1 = reserveOut - amountOut;
    } else {
        reserve0 = reserveOut - amountOut;
        reserve1 = reserveIn + amountIn;
    }
    emit Swap(msg.sender, zeroForOne, amountIn, amountOut);

    // the books are settled before any other contract runs
    (IERC20 tokenIn, IERC20 tokenOut) =
        zeroForOne ? (token0, token1) : (token1, token0);
    tokenIn.safeTransferFrom(msg.sender, address(this), amountIn);
    tokenOut.safeTransfer(msg.sender, amountOut);
}

emit Swap(...) writes a log entry: who traded, which way, and how much went in and out. Contracts can’t read these logs, but wallets and other programs off the chain can, and that’s how they find out a trade happened.

The order matters because a token is someone else’s contract. Calling its transferFrom hands control to code the pool didn’t write, and that code could call the pool back before it returns. By then the pool has nothing left to do but move tokens: the price is worked out and the books already show the swap. This order — checks, then the contract’s own changes, then calls to other contracts — is known as checks-effects-interactions. The other common defence against being called back mid-change is a lock that refuses any call while the contract is running, which Uniswap V2 uses because it pays out before it checks.

The order doesn’t make every token safe. Say a trader swaps 100 gold, and the gold token calls the pool’s swap again from inside transferFrom, before it has moved those 100 gold. That second swap is priced from reserves that already count them. Whether that hurts anyone depends on the token, and the tests don’t try it.

The widget below steps through the whole of swap on a pool of 1,000 and 1,000, with the pool’s books on one side and the token contracts’ ledgers on the other. Send the pool a gift, or make the approval too small, and watch the gift stay off the books and a failed payment undo the swap.

uint256 rounds like the model, until a number doesn’t fit

The model’s amounts are Integers, which have no size limit. The contract’s are uint256: whole numbers from 0 up to 2^256 − 1, about 1.16 × 10^77. They can’t be negative, which is why the model’s amountIn <= 0 became amountIn == 0, and gold <= 0 || silver <= 0 became reserve0 == 0 || reserve1 == 0. Tokens count in whole units too: a token with 18 decimals counts one token as 10^18 units, and the pool only ever sees units.

Division on uint256 rounds down, as div does on amounts that aren’t negative, so the formula gives the same answer in both. From 10 and 10, a swap of 3 is owed 2.3 and gets 2 in either.

They part on size. Since version 0.8, Solidity checks its arithmetic: a result that doesn’t fit in 256 bits stops the call with an error, a panic, instead of wrapping round to a small number. In swap that can happen in two places, reserveOut * amountIn and reserveIn + amountIn.

One test opens a pool with 2^200 of each token and swaps 2^100: the product is 2^300, the swap reverts, and the model would have priced it. Another stocks 2^255 gold against 1 silver and swaps 2^255 gold, so the sum is 2^256, one past the limit. The model refuses that swap too, because it would pay nothing, but the contract panics before it gets that far.

No trade in an ordinary token gets near that. A trillion tokens with 18 decimals is 10^30 units, and multiplying two such amounts gives 10^60, still about 10^17 times below the limit. The edge also sits further out than it looks. A trade of 1,000 on a pool of 2^128 and 2^128 pays what the model says, although the product of those reserves doesn’t fit, because swap never multiplies the reserves together.

The tests hold the contract to the model in three layers

The contract is 113 lines of Solidity, comments included, and its test code is 872. The first layer is worked examples whose answers come from the model:

function test_SwapGoldForSilver() public {
    stock(1000, 4000);
    assertEq(trade(true, 100, 0), 363);
    assertReserves(1100, 3637);
}

stock opens the pool as its owner with 1,000 gold and 4,000 silver. trade gives a trader the tokens, approves the pool, swaps 100 gold with no minimum, and returns what the pool paid. For the same swap the model gives Right (363, Pool 1100 3637), so the test expects 363 and those reserves. trade also checks every swap it makes: the reserves and both sides’ token balances have to move by exactly what the swap returned, and the pool can’t leave behind an approval that would let the trader take more of its tokens later.

The second layer takes the model’s six properties and gives each a Foundry test with the same name. Foundry runs a test that takes parameters as a fuzz test: it calls it with random values, 1,000 times in this project. Here is the model’s product property from the last post, and then its Foundry version:

prop_productNeverDecreases pool s =
  whenSwapSucceeds pool s $ \_ pool' ->
    property (gold pool' * silver pool' >= gold pool * silver pool)
function testFuzz_ProductNeverDecreases(
    uint256 goldAmount,
    uint256 silverAmount,
    bool zeroForOne,
    uint256 amountIn
) public {
    stockFuzzed(goldAmount, silverAmount);
    uint256 product = pool.reserve0() * pool.reserve1();
    tradeOrDiscard(zeroForOne, bound(amountIn, 1, MAX_AMOUNT));
    assertGe(pool.reserve0() * pool.reserve1(), product);
}

In Haskell, the QuickCheck library generates a Pool and a Swap; Foundry generates plain numbers, and the test builds the pool from them. The reserves are declared public, so each comes with a reader of the same name, pool.reserve0(). bound squeezes a random number into a range, and the pools and amounts the tests draw top out at MAX_AMOUNT, just under 2^127, so that every product the tests compute fits in uint256.

tradeOrDiscard does the job of the model’s whenSwapSucceeds: it keeps only the cases where the swap goes through. With an open pool, a positive amount and no minimum, the only swap the model refuses is one that would pay nothing. tradeOrDiscard checks that the contract refuses it too, with OutputTooSmall, and drops the case so that Foundry draws another. The other five properties follow the same pattern, and separate tests try the other refusals.

Six passing properties can still miss an underpayment

A seventh property checks how much: the output must be the largest that keeps the product. Paying it leaves the product at least where it was, and paying one unit more would drop it below. Call the reserve the swap pays into reserveA and the one it pays out of reserveB, both as they stood before the swap, and their product product:

assertGe((reserveA + amountIn) * (reserveB - amountOut), product);
assertLt((reserveA + amountIn) * (reserveB - amountOut - 1), product);

The first line catches a pool that pays too much, and the second one that pays too little. Neither contains the formula. A test that computed the expected output with the contract’s own expression would agree with any mistake made in both places; this one only says what the formula is for.

To see what that buys, take a pool that keeps a thousandth of each payout, rounded down, so that payouts under 1,000 lose nothing:

amountOut -= amountOut / 1000;

That pool passes every worked example, since all their payouts are under 1,000, and a full run of all six ported properties. (The one that checks a larger trade gets a worse price can catch it, but only on rare cases that 1,000 random tries didn’t hit.) The largest-output property fails within its first few random cases.

The widget below has both halves. First, pick what a pool of 10,000 and 10,000 pays for 10,000 in, and predict whether each line passes before you look. Then run all seven properties against the honest pool and the one that keeps a thousandth.

What Foundry prints when a fuzz test fails, for the curious

On the pool that keeps a thousandth, one run printed this (line breaks added):

[FAIL: assertion failed:
  18704220734837674072343012655773089531733875925309751737023138085458909375840 >=
  18682919601675392751727817536409797336694041814402305259316382123064956977552;
counterexample: args=[
  27450250782494845564735763484632910622659017220630402784 [2.745e55],
  1002263738311142612063743378838805115008383020567598112900163816323564691 [1.002e72],
  false,
  10718926481285366298682078729364654839352494519779559358552621760462 [1.071e67]]]
testFuzz_OutputIsTheLargestThatKeepsTheProduct(uint256,uint256,bool,uint256) (runs: 6, μ: 757603, ~: 756965)

A failed assertLt(a, b) prints as a >= b. Here the first number is the product with one more unit paid out, and it’s still above the product before the swap, so the pool paid too little. The arguments are the numbers Foundry drew, before bound brought them into range, so they aren’t the pool’s reserves.

Eight invariants watch 50,000 random calls

Each fuzz test makes a swap or two on a fresh pool. The third layer makes long sequences of them. Foundry’s invariant tests call the functions of a chosen contract in random order with random arguments, and after each call check a list of conditions, the invariants.

Foundry holds a shuffled stack of swap and donate calls and sends them to Trader, which calls the Pool. Eight lit lamps beside the Pool are checked after every call. Foundry holds a shuffled stack of swap and donate calls and sends them to Trader, which calls the Pool. Eight lit lamps beside the Pool are checked after every call.
Foundry calls Trader in random order, Trader calls the pool, and all eight invariants are checked after every call.

The contract Foundry calls here is a test helper, Trader, with two actions. Its swap trades as one of three accounts, two traders and the pool’s owner. The owner trades like the others because the model has no owner: anything the contract did differently for the account that deployed it would be a departure from the model.

Each swap picks a random direction and amount, and one of three minimums: none, exactly what the model says it pays, or one more than that, which the pool must refuse. It also picks how the trader pays. Sometimes the trader holds exactly amountIn and approves exactly that. Otherwise the trader holds a spare unit and approves more, so a pool that took too much would get away with it, and the balance checks would see it.

Trader’s other action, donate, sends tokens straight to the pool without calling it. The pool opens with 1,000 gold and 4,000 silver, and Foundry makes 100 runs of 500 calls each.

For every swap, Trader works out what the model’s formula pays and raises a flag at any departure from the model: a wrong refusal or a wrong pass, a product that went down, an output that isn’t the largest, reserves or balances that moved by the wrong amount, or a missing or wrong log entry. Six of the eight invariants check that their flag is still down. The other two read the pool itself: both reserves stay positive, and each reserve plus what was donated equals the pool’s balance.

With Foundry 1.8.7, forge test in the repository’s evm folder printed this for the invariant suite:

[PASS] invariant_OutputIsTheLargestThatKeepsTheProduct
[PASS] invariant_ProductNeverDecreases
[PASS] invariant_ReservesMatchBalances
[PASS] invariant_ReservesStayPositive
[PASS] invariant_SwapsDoWhatTheyReturn
[PASS] invariant_SwapsLogWhatTheyDid
[PASS] invariant_SwapsThatDoNotPayAreRefused
[PASS] invariant_SwapsThatPayGoThrough
 ConstantProductPoolInvariantTest invariants (runs: 100, calls: 50000, reverts: 0)

Foundry counts the eight invariants as one test, because they share one run of calls, so with the 30 worked examples and fuzz tests the total is 31. reverts: 0 doesn’t mean no swap was refused. Trader catches the pool’s refusals and judges them, and the project’s settings fail the run if a call to Trader itself reverts.

The same suite failed against the pool that keeps a thousandth. Foundry doesn’t simplify a failing fuzz test’s inputs, but it does simplify a failing invariant run, by dropping calls from the sequence: it cut that one from 14 calls to a single swap.

What the tests show, and what they don’t

On the cases they try, and with amounts that fit in uint256, the contract gives the model’s answers: the same payouts, the same refusals in the same order, and books that match the pool’s balances apart from gifts. The invariant run shows the same across long sequences, with several traders, the owner among them. And the one test that never writes the formula down catches a pool paying a thousandth too little, which the other six passed.

That’s evidence, not proof. The fuzz tests and the invariant run try random cases, and the link to the model is a translation: the worked examples’ answers were worked out with the model, and its properties were rewritten in Solidity, where a mistake in the rewriting would go unnoticed.

The tests also use only plain tokens, so three kinds of token go untested:

  • A token that takes a fee on each transfer. From 1,000 and 1,000, a swap of 100 with a minimum of 90 goes through, and with a 10% fee on the way out the trader receives 81, below the minimum the pool checked. A fee on the way in leaves the reserves above the pool’s balance.
  • A token that calls back into the pool during a transfer, while the books already count tokens that haven’t arrived.
  • A token that reports failure by returning false. SafeERC20 should refuse it, but the test token only ever reverts, so nothing checks that it does.

The next post asks how much these tests would notice: it plants bugs in the contract and counts how many of them the tests catch.

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