The Making of an Automated Market Maker: Follow the Maths, and the Money Will Follow. Probably.
The simplest automated market maker, how to read its code, and tests that say “for every pool and every swap” instead of listing examples.
This is the first post in a series about automated market makers: the machines that let anyone on
the internet trade one kind of token for another without a person on the other side. The series
starts with the most naive pool there is and works toward something like the ones that run
on Ethereum and Solana. I’m not an AMM specialist, so I’m learning this in public, and I’ll write
the later posts as I go. The code lives in a public repository,
and the version this post describes is tagged ch01.
This first post is about PHASE 1. It builds the pool, shows how to read its code, and introduces a concept every later post leans on: the property.
A market maker is two jars and a rule
An ordinary exchange matches people. You want to sell gold, someone else wants to buy it, and the exchange introduces you. An automated market maker drops the someone else. In their place is a pool: two jars of tokens (call them gold and silver) and a rule that says how much of one you get for the other. Someone fills the jars to begin with, and after that anyone can trade with them, at any hour, without asking.
Most real pools set the price from how full each jar is, so the price moves as people trade. This one doesn’t. Its rule is the simplest there is: one for one. Pay the pool 10 gold, and it pays you 10 silver. If it held 100 of each, it now holds 110 gold and 90 silver. The total is still 200, which is why this design is called a constant-sum pool.
That is the whole idea, and it already has holes. What happens if you ask for 200 silver from a pool that holds 90? What if you pay it minus five gold? “One for one” doesn’t say. A person at a counter would shrug and refuse. A machine needs to be told, and the telling is the code.
The code reads like a form you fill in
There are four pieces to understand.
The first is a record: a form with named blanks. A pool is two blanks, one per jar, and a swap is a direction and an amount.
data Pool = Pool
{ gold :: Integer
, silver :: Integer
}
data Swap = Swap
{ direction :: Direction
, amountIn :: Integer
}
direction says which way you trade. What follows :: says what kind of thing goes in the blank:
Integer is a whole number, and Direction is the next piece. To read a blank, put its name in
front of the record: if pool is a pool, gold pool is how much gold it holds, and if s is a
swap, amountIn s is how much it pays in.
The second piece is an enum: a value that is exactly one of a fixed list of names. A swap goes one of two ways:
data Direction
= GoldForSilver
| SilverForGold
The | reads as “or”. You either pay gold and receive silver, or pay silver and receive gold. A
swap can also be refused for two reasons, and the code lists them the same way:
data SwapError
= AmountNotPositive
| InsufficientLiquidity
A refusal is either AmountNotPositive (you paid zero or less) or InsufficientLiquidity (the pool
doesn’t hold enough to pay you).
The third piece, Either, is what a swap gives back. A swap either fails with a reason or
succeeds with a result, and Either holds exactly one of those two shapes. Left carries the
reason. Right (as in “all right”) carries the success in two parts: how much the pool hands you,
and the pool after the trade. So if you paid 10 gold into the pool of 100 and 100,
Right (10, Pool 110 90) means “10 silver
came out of the silver jar and is yours now, and the jars hold 110 gold and 90 silver”. No coins are
made or destroyed: your 10 gold went into one jar, and 10 silver came out of the other.
The fourth piece is the function itself:
swap (Swap direction amountIn) (Pool gold silver)
| amountIn <= 0 = Left AmountNotPositive
| amountOut > reserveOut = Left InsufficientLiquidity
| direction == GoldForSilver =
Right (amountOut, Pool (gold + amountIn)
(silver - amountOut))
| otherwise =
Right (amountOut, Pool (gold - amountOut)
(silver + amountIn))
where
amountOut = amountIn -- constant sum: one for one
reserveOut = if direction == GoldForSilver then silver else gold
The first line takes a swap and a pool, and opens them up: it gives names to the parts inside, so
the rest of the function can say amountIn instead of “the amount field of the swap”. There are no
commas between the arguments; a space is enough. Building a pool works the same way:
Pool (gold + amountIn) (silver - amountOut) is a new pool built from the two new jar amounts.
The | is back with a different job. At the start of a line in a function, it begins a guard: a
question, then =, then the answer. Guards are tried top to bottom, and the first question that
comes out true wins. == asks whether two things are equal, so direction == GoldForSilver asks
whether you’re paying gold. otherwise is a question that is always true, so it catches what’s
left.
The where block at the bottom defines the two names the guards use: how much you get back (exactly
what you paid in, which is the one-for-one rule) and how much is in the jar that pays you.
Run one in your head. Pay 10 gold into a pool of 100 and 100. Is 10 at most zero? No. The pool pays
out 10 from the silver jar, which holds 100. Is 10 more than 100? No. Are you paying gold? Yes, so
the answer is Right (10, Pool 110 90).
In the widget below, choose a direction and an amount, then use the arrows to step through the guards with the values filled in. Press Swap to apply the trade to the jars. It also shows the rest of the file, including the type lines the code above leaves out. You can ignore those, here and in the property widget further down.
What the type line means, for the curious
swap :: Swap -> Pool -> Either SwapError (Integer, Pool)
That’s the function’s type, and it uses the same :: as the records. Everything before the last
arrow is an input, and what follows it is the result: swap takes a swap and a pool, and gives back
a refusal or an amount with a new pool. It’s there for the compiler, which checks that the function
really does take and give back those things.
An example checks the case somebody thought of
One case is worth running by hand: a pool holds 40 gold and 25 silver, and you pay it 25 gold.
The pool owes you 25 silver and holds exactly 25, so it pays. The answer is Right (25, Pool 65 0):
the silver jar is empty. The code allows that on purpose. It never pays out more than it holds, but
it will pay out all of it.
The quiz below has more like it. Predict each answer before you look.
That quiz is example testing. Each question is one pool, one swap and one expected answer, and you are the test runner. Examples are useful, but they only cover the cases somebody thought to write, and a pool has a lot of cases nobody would write down.
A property drops the specific numbers. Instead of “this pool and this swap give that answer”, it says “for every pool and every swap, this holds”.
A property is a rule with no exceptions
Finding properties is the hard part of this whole approach, and there’s no recipe for it. One way in is to stop thinking about code and describe the pool to someone who has never seen one: a gnome, say, deciding whether to put its savings in the jars. Described that way, the pool comes down to four sentences:
- A swap leaves the total number of coins in the pool unchanged.
- For each coin you pay in, you get one coin of the other kind back.
- If you swap and then swap straight back, everything is as it was.
- Neither jar ever goes below zero.
Those four sentences are a mental model of the pool. Each one is also a property, because each one is supposed to hold for any pool and any swap. If the code disagrees with one of them, either the code is wrong or the model is, and both are worth knowing.
Here is the first sentence as code:
prop_sumPreserved pool s =
whenSwapSucceeds pool s $ \_ pool' ->
gold pool' + silver pool' === gold pool + silver pool
pool and s are any pool and any swap. The second line runs the swap and, if it goes through,
calls the pool after it pool'; you can skip the rest of that line. The last line is the sentence
itself: the gold and silver in the new pool add up to the same total as before.
The rest of that line, for the curious
whenSwapSucceeds pool s takes one more input: what to do if the swap goes through. That’s a
small function, written on the spot after the $. The $ saves a pair of brackets: everything
after it is one input.
\_ pool' -> … is the function itself. The \ starts it, its inputs go before the ->, and what
it does with them goes after. It gets two inputs, the amount you got back and the new pool. This
property doesn’t need the amount, so it writes _, which means “there’s an input here, and I’m
ignoring it”. The second input, the state of the pool after the swap, it names pool'.
The ' (read “prime”) marks the next version of something: pool is the pool before the swap, and
pool' is the same pool after it. I’ll use it that way for the rest of the series.
=== means “these must be equal”, and when they aren’t, it shows both sides. A refused swap has
nothing to check, so it passes as it is.
The other three follow the same pattern, and only their checks differ:
-- One for each: what came out is what went in
amountOut === amountIn s
-- Swap straight back: the other way, paying in what came out
swap (Swap (opposite (direction s)) amountOut) pool'
=== Right (amountIn s, pool)
-- Never negative: neither jar of the new pool is below zero
property (gold pool' >= 0 && silver pool' >= 0)
The first two need the amount that came out, so they name it amountOut on their second line. opposite turns a
direction round, && means “and”, and property turns a yes-or-no answer into a check.
The four aren’t all the same kind of sentence. Two describe trades: how much comes out, and what happens when you swap it straight back. The other two describe the pool itself, in every state it can ever reach: the total never changes, and no jar goes negative. These are invariants, the simplest kind of safety property, which is the formal name for “nothing bad ever happens”.
Checking one swap at a time is enough for those. If a pool starts with no negative jar, and no single swap can change the total or push a jar below zero, then no run of swaps can either. The tests go looking for the swap that breaks them.
On a blockchain, the jars hold real people’s money, and “no jar goes negative” means nobody gets paid with money the pool doesn’t have.
So where do properties come from when the thing is less obvious than two jars? Three answers:
- Someone wrote them down already. AMMs have a formal literature with their properties spelled out. An agent checked the four above against it, and “swap straight back” has a proper name there: reversibility.
- Guess, then check. Ask an agent to propose properties, and run them. That’s where the four above came from.
- Compare with a model. Later in the series the same pool is written for Ethereum and for Solana, and most of their properties boil down to one: for any pool and any swap, the chain code gives the same answer as this model. That’s a lot easier than guessing at maths.
Let a machine pick the numbers
A property says “for every pool and every swap”, but no test can try every pool. What it can do is try a lot of them, picked at random. That’s the heart of property-based testing: call the function with random inputs, and check the property each time.
The machine makes up pools whose jars hold zero or more, and swaps in either direction with any amount, including zero and negative ones. It doesn’t know which inputs are sensible, and that’s the point. It will happily try paying minus seven silver into a pool that has no silver at all. The pool has to refuse it, and the property has to survive the refusal.
Each property gets at least a hundred made-up cases. If all of them pass, the run says so in one line. If one fails, the run stops and shows the pool and the swap that broke it.
All four pass. That’s a small result, and it should be: the pool is tiny, and the properties say nothing surprising about it. What’s worth having is the method. Write down what must always hold, let a machine hunt for a case where it doesn’t, and pay attention when it finds one.
The scary part was the name
You’ve just read Haskell. Nothing bad happened.
The language has a reputation for being hard, and some of it is earned, but not by code like this. Two records, two enums, a function with guards and four properties are enough to describe a market maker precisely, and a library called QuickCheck generates the tests’ random inputs.
That leaves the gnomes’ board. PHASE 1 holds up: the maths checks out, and every coin is accounted for. But all four properties are about bookkeeping, and none of them asks whether the pool is a good deal for whoever filled it.
Out in the market, gold and silver don’t have to be worth the same. Suppose a gold coin starts trading for two silver. The pool will still hand over gold for one silver apiece to anyone who asks, and every property above still passes.
What happens to the jars is PHASE 2, and it’s the next post.
The Making of an Automated Market Maker: Follow the Maths, and the Money Will Follow. Probably.
// The simplest automated market maker, how to read its code, and tests that say “for every pool and every swap” instead of listing examples.
This is the first post in a series about automated market makers: the machines that let anyone on
the internet trade one kind of token for another without a person on the other side. The series
starts with the most naive pool there is and works toward something like the ones that run
on Ethereum and Solana. I’m not an AMM specialist, so I’m learning this in public, and I’ll write
the later posts as I go. The code lives in a public repository,
and the version this post describes is tagged ch01.
This first post is about PHASE 1. It builds the pool, shows how to read its code, and introduces a concept every later post leans on: the property.
A market maker is two jars and a rule
An ordinary exchange matches people. You want to sell gold, someone else wants to buy it, and the exchange introduces you. An automated market maker drops the someone else. In their place is a pool: two jars of tokens (call them gold and silver) and a rule that says how much of one you get for the other. Someone fills the jars to begin with, and after that anyone can trade with them, at any hour, without asking.
Most real pools set the price from how full each jar is, so the price moves as people trade. This one doesn’t. Its rule is the simplest there is: one for one. Pay the pool 10 gold, and it pays you 10 silver. If it held 100 of each, it now holds 110 gold and 90 silver. The total is still 200, which is why this design is called a constant-sum pool.
That is the whole idea, and it already has holes. What happens if you ask for 200 silver from a pool that holds 90? What if you pay it minus five gold? “One for one” doesn’t say. A person at a counter would shrug and refuse. A machine needs to be told, and the telling is the code.
The code reads like a form you fill in
There are four pieces to understand.
The first is a record: a form with named blanks. A pool is two blanks, one per jar, and a swap is a direction and an amount.
data Pool = Pool
{ gold :: Integer
, silver :: Integer
}
data Swap = Swap
{ direction :: Direction
, amountIn :: Integer
}
direction says which way you trade. What follows :: says what kind of thing goes in the blank:
Integer is a whole number, and Direction is the next piece. To read a blank, put its name in
front of the record: if pool is a pool, gold pool is how much gold it holds, and if s is a
swap, amountIn s is how much it pays in.
The second piece is an enum: a value that is exactly one of a fixed list of names. A swap goes one of two ways:
data Direction
= GoldForSilver
| SilverForGold
The | reads as “or”. You either pay gold and receive silver, or pay silver and receive gold. A
swap can also be refused for two reasons, and the code lists them the same way:
data SwapError
= AmountNotPositive
| InsufficientLiquidity
A refusal is either AmountNotPositive (you paid zero or less) or InsufficientLiquidity (the pool
doesn’t hold enough to pay you).
The third piece, Either, is what a swap gives back. A swap either fails with a reason or
succeeds with a result, and Either holds exactly one of those two shapes. Left carries the
reason. Right (as in “all right”) carries the success in two parts: how much the pool hands you,
and the pool after the trade. So if you paid 10 gold into the pool of 100 and 100,
Right (10, Pool 110 90) means “10 silver
came out of the silver jar and is yours now, and the jars hold 110 gold and 90 silver”. No coins are
made or destroyed: your 10 gold went into one jar, and 10 silver came out of the other.
The fourth piece is the function itself:
swap (Swap direction amountIn) (Pool gold silver)
| amountIn <= 0 = Left AmountNotPositive
| amountOut > reserveOut = Left InsufficientLiquidity
| direction == GoldForSilver =
Right (amountOut, Pool (gold + amountIn)
(silver - amountOut))
| otherwise =
Right (amountOut, Pool (gold - amountOut)
(silver + amountIn))
where
amountOut = amountIn -- constant sum: one for one
reserveOut = if direction == GoldForSilver then silver else gold
The first line takes a swap and a pool, and opens them up: it gives names to the parts inside, so
the rest of the function can say amountIn instead of “the amount field of the swap”. There are no
commas between the arguments; a space is enough. Building a pool works the same way:
Pool (gold + amountIn) (silver - amountOut) is a new pool built from the two new jar amounts.
The | is back with a different job. At the start of a line in a function, it begins a guard: a
question, then =, then the answer. Guards are tried top to bottom, and the first question that
comes out true wins. == asks whether two things are equal, so direction == GoldForSilver asks
whether you’re paying gold. otherwise is a question that is always true, so it catches what’s
left.
The where block at the bottom defines the two names the guards use: how much you get back (exactly
what you paid in, which is the one-for-one rule) and how much is in the jar that pays you.
Run one in your head. Pay 10 gold into a pool of 100 and 100. Is 10 at most zero? No. The pool pays
out 10 from the silver jar, which holds 100. Is 10 more than 100? No. Are you paying gold? Yes, so
the answer is Right (10, Pool 110 90).
In the widget below, choose a direction and an amount, then use the arrows to step through the guards with the values filled in. Press Swap to apply the trade to the jars. It also shows the rest of the file, including the type lines the code above leaves out. You can ignore those, here and in the property widget further down.
What the type line means, for the curious
swap :: Swap -> Pool -> Either SwapError (Integer, Pool)
That’s the function’s type, and it uses the same :: as the records. Everything before the last
arrow is an input, and what follows it is the result: swap takes a swap and a pool, and gives back
a refusal or an amount with a new pool. It’s there for the compiler, which checks that the function
really does take and give back those things.
An example checks the case somebody thought of
One case is worth running by hand: a pool holds 40 gold and 25 silver, and you pay it 25 gold.
The pool owes you 25 silver and holds exactly 25, so it pays. The answer is Right (25, Pool 65 0):
the silver jar is empty. The code allows that on purpose. It never pays out more than it holds, but
it will pay out all of it.
The quiz below has more like it. Predict each answer before you look.
That quiz is example testing. Each question is one pool, one swap and one expected answer, and you are the test runner. Examples are useful, but they only cover the cases somebody thought to write, and a pool has a lot of cases nobody would write down.
A property drops the specific numbers. Instead of “this pool and this swap give that answer”, it says “for every pool and every swap, this holds”.
A property is a rule with no exceptions
Finding properties is the hard part of this whole approach, and there’s no recipe for it. One way in is to stop thinking about code and describe the pool to someone who has never seen one: a gnome, say, deciding whether to put its savings in the jars. Described that way, the pool comes down to four sentences:
- A swap leaves the total number of coins in the pool unchanged.
- For each coin you pay in, you get one coin of the other kind back.
- If you swap and then swap straight back, everything is as it was.
- Neither jar ever goes below zero.
Those four sentences are a mental model of the pool. Each one is also a property, because each one is supposed to hold for any pool and any swap. If the code disagrees with one of them, either the code is wrong or the model is, and both are worth knowing.
Here is the first sentence as code:
prop_sumPreserved pool s =
whenSwapSucceeds pool s $ \_ pool' ->
gold pool' + silver pool' === gold pool + silver pool
pool and s are any pool and any swap. The second line runs the swap and, if it goes through,
calls the pool after it pool'; you can skip the rest of that line. The last line is the sentence
itself: the gold and silver in the new pool add up to the same total as before.
The rest of that line, for the curious
whenSwapSucceeds pool s takes one more input: what to do if the swap goes through. That’s a
small function, written on the spot after the $. The $ saves a pair of brackets: everything
after it is one input.
\_ pool' -> … is the function itself. The \ starts it, its inputs go before the ->, and what
it does with them goes after. It gets two inputs, the amount you got back and the new pool. This
property doesn’t need the amount, so it writes _, which means “there’s an input here, and I’m
ignoring it”. The second input, the state of the pool after the swap, it names pool'.
The ' (read “prime”) marks the next version of something: pool is the pool before the swap, and
pool' is the same pool after it. I’ll use it that way for the rest of the series.
=== means “these must be equal”, and when they aren’t, it shows both sides. A refused swap has
nothing to check, so it passes as it is.
The other three follow the same pattern, and only their checks differ:
-- One for each: what came out is what went in
amountOut === amountIn s
-- Swap straight back: the other way, paying in what came out
swap (Swap (opposite (direction s)) amountOut) pool'
=== Right (amountIn s, pool)
-- Never negative: neither jar of the new pool is below zero
property (gold pool' >= 0 && silver pool' >= 0)
The first two need the amount that came out, so they name it amountOut on their second line. opposite turns a
direction round, && means “and”, and property turns a yes-or-no answer into a check.
The four aren’t all the same kind of sentence. Two describe trades: how much comes out, and what happens when you swap it straight back. The other two describe the pool itself, in every state it can ever reach: the total never changes, and no jar goes negative. These are invariants, the simplest kind of safety property, which is the formal name for “nothing bad ever happens”.
Checking one swap at a time is enough for those. If a pool starts with no negative jar, and no single swap can change the total or push a jar below zero, then no run of swaps can either. The tests go looking for the swap that breaks them.
On a blockchain, the jars hold real people’s money, and “no jar goes negative” means nobody gets paid with money the pool doesn’t have.
So where do properties come from when the thing is less obvious than two jars? Three answers:
- Someone wrote them down already. AMMs have a formal literature with their properties spelled out. An agent checked the four above against it, and “swap straight back” has a proper name there: reversibility.
- Guess, then check. Ask an agent to propose properties, and run them. That’s where the four above came from.
- Compare with a model. Later in the series the same pool is written for Ethereum and for Solana, and most of their properties boil down to one: for any pool and any swap, the chain code gives the same answer as this model. That’s a lot easier than guessing at maths.
Let a machine pick the numbers
A property says “for every pool and every swap”, but no test can try every pool. What it can do is try a lot of them, picked at random. That’s the heart of property-based testing: call the function with random inputs, and check the property each time.
The machine makes up pools whose jars hold zero or more, and swaps in either direction with any amount, including zero and negative ones. It doesn’t know which inputs are sensible, and that’s the point. It will happily try paying minus seven silver into a pool that has no silver at all. The pool has to refuse it, and the property has to survive the refusal.
Each property gets at least a hundred made-up cases. If all of them pass, the run says so in one line. If one fails, the run stops and shows the pool and the swap that broke it.
All four pass. That’s a small result, and it should be: the pool is tiny, and the properties say nothing surprising about it. What’s worth having is the method. Write down what must always hold, let a machine hunt for a case where it doesn’t, and pay attention when it finds one.
The scary part was the name
You’ve just read Haskell. Nothing bad happened.
The language has a reputation for being hard, and some of it is earned, but not by code like this. Two records, two enums, a function with guards and four properties are enough to describe a market maker precisely, and a library called QuickCheck generates the tests’ random inputs.
That leaves the gnomes’ board. PHASE 1 holds up: the maths checks out, and every coin is accounted for. But all four properties are about bookkeeping, and none of them asks whether the pool is a good deal for whoever filled it.
Out in the market, gold and silver don’t have to be worth the same. Suppose a gold coin starts trading for two silver. The pool will still hand over gold for one silver apiece to anyone who asks, and every property above still passes.
What happens to the jars is PHASE 2, and it’s the next post.
The Making of an Automated Market Maker: Follow the Maths, and the Money Will Follow. Probably.
The simplest automated market maker, how to read its code, and tests that say “for every pool and every swap” instead of listing examples.
This is the first post in a series about automated market makers: the machines that let anyone on
the internet trade one kind of token for another without a person on the other side. The series
starts with the most naive pool there is and works toward something like the ones that run
on Ethereum and Solana. I’m not an AMM specialist, so I’m learning this in public, and I’ll write
the later posts as I go. The code lives in a public repository,
and the version this post describes is tagged ch01.
This first post is about PHASE 1. It builds the pool, shows how to read its code, and introduces a concept every later post leans on: the property.
A market maker is two jars and a rule
An ordinary exchange matches people. You want to sell gold, someone else wants to buy it, and the exchange introduces you. An automated market maker drops the someone else. In their place is a pool: two jars of tokens (call them gold and silver) and a rule that says how much of one you get for the other. Someone fills the jars to begin with, and after that anyone can trade with them, at any hour, without asking.
Most real pools set the price from how full each jar is, so the price moves as people trade. This one doesn’t. Its rule is the simplest there is: one for one. Pay the pool 10 gold, and it pays you 10 silver. If it held 100 of each, it now holds 110 gold and 90 silver. The total is still 200, which is why this design is called a constant-sum pool.
That is the whole idea, and it already has holes. What happens if you ask for 200 silver from a pool that holds 90? What if you pay it minus five gold? “One for one” doesn’t say. A person at a counter would shrug and refuse. A machine needs to be told, and the telling is the code.
The code reads like a form you fill in
There are four pieces to understand.
The first is a record: a form with named blanks. A pool is two blanks, one per jar, and a swap is a direction and an amount.
data Pool = Pool
{ gold :: Integer
, silver :: Integer
}
data Swap = Swap
{ direction :: Direction
, amountIn :: Integer
}
direction says which way you trade. What follows :: says what kind of thing goes in the blank:
Integer is a whole number, and Direction is the next piece. To read a blank, put its name in
front of the record: if pool is a pool, gold pool is how much gold it holds, and if s is a
swap, amountIn s is how much it pays in.
The second piece is an enum: a value that is exactly one of a fixed list of names. A swap goes one of two ways:
data Direction
= GoldForSilver
| SilverForGold
The | reads as “or”. You either pay gold and receive silver, or pay silver and receive gold. A
swap can also be refused for two reasons, and the code lists them the same way:
data SwapError
= AmountNotPositive
| InsufficientLiquidity
A refusal is either AmountNotPositive (you paid zero or less) or InsufficientLiquidity (the pool
doesn’t hold enough to pay you).
The third piece, Either, is what a swap gives back. A swap either fails with a reason or
succeeds with a result, and Either holds exactly one of those two shapes. Left carries the
reason. Right (as in “all right”) carries the success in two parts: how much the pool hands you,
and the pool after the trade. So if you paid 10 gold into the pool of 100 and 100,
Right (10, Pool 110 90) means “10 silver
came out of the silver jar and is yours now, and the jars hold 110 gold and 90 silver”. No coins are
made or destroyed: your 10 gold went into one jar, and 10 silver came out of the other.
The fourth piece is the function itself:
swap (Swap direction amountIn) (Pool gold silver)
| amountIn <= 0 = Left AmountNotPositive
| amountOut > reserveOut = Left InsufficientLiquidity
| direction == GoldForSilver =
Right (amountOut, Pool (gold + amountIn)
(silver - amountOut))
| otherwise =
Right (amountOut, Pool (gold - amountOut)
(silver + amountIn))
where
amountOut = amountIn -- constant sum: one for one
reserveOut = if direction == GoldForSilver then silver else gold
The first line takes a swap and a pool, and opens them up: it gives names to the parts inside, so
the rest of the function can say amountIn instead of “the amount field of the swap”. There are no
commas between the arguments; a space is enough. Building a pool works the same way:
Pool (gold + amountIn) (silver - amountOut) is a new pool built from the two new jar amounts.
The | is back with a different job. At the start of a line in a function, it begins a guard: a
question, then =, then the answer. Guards are tried top to bottom, and the first question that
comes out true wins. == asks whether two things are equal, so direction == GoldForSilver asks
whether you’re paying gold. otherwise is a question that is always true, so it catches what’s
left.
The where block at the bottom defines the two names the guards use: how much you get back (exactly
what you paid in, which is the one-for-one rule) and how much is in the jar that pays you.
Run one in your head. Pay 10 gold into a pool of 100 and 100. Is 10 at most zero? No. The pool pays
out 10 from the silver jar, which holds 100. Is 10 more than 100? No. Are you paying gold? Yes, so
the answer is Right (10, Pool 110 90).
In the widget below, choose a direction and an amount, then use the arrows to step through the guards with the values filled in. Press Swap to apply the trade to the jars. It also shows the rest of the file, including the type lines the code above leaves out. You can ignore those, here and in the property widget further down.
What the type line means, for the curious
swap :: Swap -> Pool -> Either SwapError (Integer, Pool)
That’s the function’s type, and it uses the same :: as the records. Everything before the last
arrow is an input, and what follows it is the result: swap takes a swap and a pool, and gives back
a refusal or an amount with a new pool. It’s there for the compiler, which checks that the function
really does take and give back those things.
An example checks the case somebody thought of
One case is worth running by hand: a pool holds 40 gold and 25 silver, and you pay it 25 gold.
The pool owes you 25 silver and holds exactly 25, so it pays. The answer is Right (25, Pool 65 0):
the silver jar is empty. The code allows that on purpose. It never pays out more than it holds, but
it will pay out all of it.
The quiz below has more like it. Predict each answer before you look.
That quiz is example testing. Each question is one pool, one swap and one expected answer, and you are the test runner. Examples are useful, but they only cover the cases somebody thought to write, and a pool has a lot of cases nobody would write down.
A property drops the specific numbers. Instead of “this pool and this swap give that answer”, it says “for every pool and every swap, this holds”.
A property is a rule with no exceptions
Finding properties is the hard part of this whole approach, and there’s no recipe for it. One way in is to stop thinking about code and describe the pool to someone who has never seen one: a gnome, say, deciding whether to put its savings in the jars. Described that way, the pool comes down to four sentences:
- A swap leaves the total number of coins in the pool unchanged.
- For each coin you pay in, you get one coin of the other kind back.
- If you swap and then swap straight back, everything is as it was.
- Neither jar ever goes below zero.
Those four sentences are a mental model of the pool. Each one is also a property, because each one is supposed to hold for any pool and any swap. If the code disagrees with one of them, either the code is wrong or the model is, and both are worth knowing.
Here is the first sentence as code:
prop_sumPreserved pool s =
whenSwapSucceeds pool s $ \_ pool' ->
gold pool' + silver pool' === gold pool + silver pool
pool and s are any pool and any swap. The second line runs the swap and, if it goes through,
calls the pool after it pool'; you can skip the rest of that line. The last line is the sentence
itself: the gold and silver in the new pool add up to the same total as before.
The rest of that line, for the curious
whenSwapSucceeds pool s takes one more input: what to do if the swap goes through. That’s a
small function, written on the spot after the $. The $ saves a pair of brackets: everything
after it is one input.
\_ pool' -> … is the function itself. The \ starts it, its inputs go before the ->, and what
it does with them goes after. It gets two inputs, the amount you got back and the new pool. This
property doesn’t need the amount, so it writes _, which means “there’s an input here, and I’m
ignoring it”. The second input, the state of the pool after the swap, it names pool'.
The ' (read “prime”) marks the next version of something: pool is the pool before the swap, and
pool' is the same pool after it. I’ll use it that way for the rest of the series.
=== means “these must be equal”, and when they aren’t, it shows both sides. A refused swap has
nothing to check, so it passes as it is.
The other three follow the same pattern, and only their checks differ:
-- One for each: what came out is what went in
amountOut === amountIn s
-- Swap straight back: the other way, paying in what came out
swap (Swap (opposite (direction s)) amountOut) pool'
=== Right (amountIn s, pool)
-- Never negative: neither jar of the new pool is below zero
property (gold pool' >= 0 && silver pool' >= 0)
The first two need the amount that came out, so they name it amountOut on their second line. opposite turns a
direction round, && means “and”, and property turns a yes-or-no answer into a check.
The four aren’t all the same kind of sentence. Two describe trades: how much comes out, and what happens when you swap it straight back. The other two describe the pool itself, in every state it can ever reach: the total never changes, and no jar goes negative. These are invariants, the simplest kind of safety property, which is the formal name for “nothing bad ever happens”.
Checking one swap at a time is enough for those. If a pool starts with no negative jar, and no single swap can change the total or push a jar below zero, then no run of swaps can either. The tests go looking for the swap that breaks them.
On a blockchain, the jars hold real people’s money, and “no jar goes negative” means nobody gets paid with money the pool doesn’t have.
So where do properties come from when the thing is less obvious than two jars? Three answers:
- Someone wrote them down already. AMMs have a formal literature with their properties spelled out. An agent checked the four above against it, and “swap straight back” has a proper name there: reversibility.
- Guess, then check. Ask an agent to propose properties, and run them. That’s where the four above came from.
- Compare with a model. Later in the series the same pool is written for Ethereum and for Solana, and most of their properties boil down to one: for any pool and any swap, the chain code gives the same answer as this model. That’s a lot easier than guessing at maths.
Let a machine pick the numbers
A property says “for every pool and every swap”, but no test can try every pool. What it can do is try a lot of them, picked at random. That’s the heart of property-based testing: call the function with random inputs, and check the property each time.
The machine makes up pools whose jars hold zero or more, and swaps in either direction with any amount, including zero and negative ones. It doesn’t know which inputs are sensible, and that’s the point. It will happily try paying minus seven silver into a pool that has no silver at all. The pool has to refuse it, and the property has to survive the refusal.
Each property gets at least a hundred made-up cases. If all of them pass, the run says so in one line. If one fails, the run stops and shows the pool and the swap that broke it.
All four pass. That’s a small result, and it should be: the pool is tiny, and the properties say nothing surprising about it. What’s worth having is the method. Write down what must always hold, let a machine hunt for a case where it doesn’t, and pay attention when it finds one.
The scary part was the name
You’ve just read Haskell. Nothing bad happened.
The language has a reputation for being hard, and some of it is earned, but not by code like this. Two records, two enums, a function with guards and four properties are enough to describe a market maker precisely, and a library called QuickCheck generates the tests’ random inputs.
That leaves the gnomes’ board. PHASE 1 holds up: the maths checks out, and every coin is accounted for. But all four properties are about bookkeeping, and none of them asks whether the pool is a good deal for whoever filled it.
Out in the market, gold and silver don’t have to be worth the same. Suppose a gold coin starts trading for two silver. The pool will still hand over gold for one silver apiece to anyone who asks, and every property above still passes.
What happens to the jars is PHASE 2, and it’s the next post.
This is the first post in a series about automated market makers: the machines that let anyone on
the internet trade one kind of token for another without a person on the other side. The series
starts with the most naive pool there is and works toward something like the ones that run
on Ethereum and Solana. I’m not an AMM specialist, so I’m learning this in public, and I’ll write
the later posts as I go. The code lives in a public repository,
and the version this post describes is tagged ch01.
This first post is about PHASE 1. It builds the pool, shows how to read its code, and introduces a concept every later post leans on: the property.
A market maker is two jars and a rule
An ordinary exchange matches people. You want to sell gold, someone else wants to buy it, and the exchange introduces you. An automated market maker drops the someone else. In their place is a pool: two jars of tokens (call them gold and silver) and a rule that says how much of one you get for the other. Someone fills the jars to begin with, and after that anyone can trade with them, at any hour, without asking.
Most real pools set the price from how full each jar is, so the price moves as people trade. This one doesn’t. Its rule is the simplest there is: one for one. Pay the pool 10 gold, and it pays you 10 silver. If it held 100 of each, it now holds 110 gold and 90 silver. The total is still 200, which is why this design is called a constant-sum pool.
That is the whole idea, and it already has holes. What happens if you ask for 200 silver from a pool that holds 90? What if you pay it minus five gold? “One for one” doesn’t say. A person at a counter would shrug and refuse. A machine needs to be told, and the telling is the code.
The code reads like a form you fill in
There are four pieces to understand.
The first is a record: a form with named blanks. A pool is two blanks, one per jar, and a swap is a direction and an amount.
data Pool = Pool
{ gold :: Integer
, silver :: Integer
}
data Swap = Swap
{ direction :: Direction
, amountIn :: Integer
}
direction says which way you trade. What follows :: says what kind of thing goes in the blank:
Integer is a whole number, and Direction is the next piece. To read a blank, put its name in
front of the record: if pool is a pool, gold pool is how much gold it holds, and if s is a
swap, amountIn s is how much it pays in.
The second piece is an enum: a value that is exactly one of a fixed list of names. A swap goes one of two ways:
data Direction
= GoldForSilver
| SilverForGold
The | reads as “or”. You either pay gold and receive silver, or pay silver and receive gold. A
swap can also be refused for two reasons, and the code lists them the same way:
data SwapError
= AmountNotPositive
| InsufficientLiquidity
A refusal is either AmountNotPositive (you paid zero or less) or InsufficientLiquidity (the pool
doesn’t hold enough to pay you).
The third piece, Either, is what a swap gives back. A swap either fails with a reason or
succeeds with a result, and Either holds exactly one of those two shapes. Left carries the
reason. Right (as in “all right”) carries the success in two parts: how much the pool hands you,
and the pool after the trade. So if you paid 10 gold into the pool of 100 and 100,
Right (10, Pool 110 90) means “10 silver
came out of the silver jar and is yours now, and the jars hold 110 gold and 90 silver”. No coins are
made or destroyed: your 10 gold went into one jar, and 10 silver came out of the other.
The fourth piece is the function itself:
swap (Swap direction amountIn) (Pool gold silver)
| amountIn <= 0 = Left AmountNotPositive
| amountOut > reserveOut = Left InsufficientLiquidity
| direction == GoldForSilver =
Right (amountOut, Pool (gold + amountIn)
(silver - amountOut))
| otherwise =
Right (amountOut, Pool (gold - amountOut)
(silver + amountIn))
where
amountOut = amountIn -- constant sum: one for one
reserveOut = if direction == GoldForSilver then silver else gold
The first line takes a swap and a pool, and opens them up: it gives names to the parts inside, so
the rest of the function can say amountIn instead of “the amount field of the swap”. There are no
commas between the arguments; a space is enough. Building a pool works the same way:
Pool (gold + amountIn) (silver - amountOut) is a new pool built from the two new jar amounts.
The | is back with a different job. At the start of a line in a function, it begins a guard: a
question, then =, then the answer. Guards are tried top to bottom, and the first question that
comes out true wins. == asks whether two things are equal, so direction == GoldForSilver asks
whether you’re paying gold. otherwise is a question that is always true, so it catches what’s
left.
The where block at the bottom defines the two names the guards use: how much you get back (exactly
what you paid in, which is the one-for-one rule) and how much is in the jar that pays you.
Run one in your head. Pay 10 gold into a pool of 100 and 100. Is 10 at most zero? No. The pool pays
out 10 from the silver jar, which holds 100. Is 10 more than 100? No. Are you paying gold? Yes, so
the answer is Right (10, Pool 110 90).
In the widget below, choose a direction and an amount, then use the arrows to step through the guards with the values filled in. Press Swap to apply the trade to the jars. It also shows the rest of the file, including the type lines the code above leaves out. You can ignore those, here and in the property widget further down.
What the type line means, for the curious
swap :: Swap -> Pool -> Either SwapError (Integer, Pool)
That’s the function’s type, and it uses the same :: as the records. Everything before the last
arrow is an input, and what follows it is the result: swap takes a swap and a pool, and gives back
a refusal or an amount with a new pool. It’s there for the compiler, which checks that the function
really does take and give back those things.
An example checks the case somebody thought of
One case is worth running by hand: a pool holds 40 gold and 25 silver, and you pay it 25 gold.
The pool owes you 25 silver and holds exactly 25, so it pays. The answer is Right (25, Pool 65 0):
the silver jar is empty. The code allows that on purpose. It never pays out more than it holds, but
it will pay out all of it.
The quiz below has more like it. Predict each answer before you look.
That quiz is example testing. Each question is one pool, one swap and one expected answer, and you are the test runner. Examples are useful, but they only cover the cases somebody thought to write, and a pool has a lot of cases nobody would write down.
A property drops the specific numbers. Instead of “this pool and this swap give that answer”, it says “for every pool and every swap, this holds”.
A property is a rule with no exceptions
Finding properties is the hard part of this whole approach, and there’s no recipe for it. One way in is to stop thinking about code and describe the pool to someone who has never seen one: a gnome, say, deciding whether to put its savings in the jars. Described that way, the pool comes down to four sentences:
- A swap leaves the total number of coins in the pool unchanged.
- For each coin you pay in, you get one coin of the other kind back.
- If you swap and then swap straight back, everything is as it was.
- Neither jar ever goes below zero.
Those four sentences are a mental model of the pool. Each one is also a property, because each one is supposed to hold for any pool and any swap. If the code disagrees with one of them, either the code is wrong or the model is, and both are worth knowing.
Here is the first sentence as code:
prop_sumPreserved pool s =
whenSwapSucceeds pool s $ \_ pool' ->
gold pool' + silver pool' === gold pool + silver pool
pool and s are any pool and any swap. The second line runs the swap and, if it goes through,
calls the pool after it pool'; you can skip the rest of that line. The last line is the sentence
itself: the gold and silver in the new pool add up to the same total as before.
The rest of that line, for the curious
whenSwapSucceeds pool s takes one more input: what to do if the swap goes through. That’s a
small function, written on the spot after the $. The $ saves a pair of brackets: everything
after it is one input.
\_ pool' -> … is the function itself. The \ starts it, its inputs go before the ->, and what
it does with them goes after. It gets two inputs, the amount you got back and the new pool. This
property doesn’t need the amount, so it writes _, which means “there’s an input here, and I’m
ignoring it”. The second input, the state of the pool after the swap, it names pool'.
The ' (read “prime”) marks the next version of something: pool is the pool before the swap, and
pool' is the same pool after it. I’ll use it that way for the rest of the series.
=== means “these must be equal”, and when they aren’t, it shows both sides. A refused swap has
nothing to check, so it passes as it is.
The other three follow the same pattern, and only their checks differ:
-- One for each: what came out is what went in
amountOut === amountIn s
-- Swap straight back: the other way, paying in what came out
swap (Swap (opposite (direction s)) amountOut) pool'
=== Right (amountIn s, pool)
-- Never negative: neither jar of the new pool is below zero
property (gold pool' >= 0 && silver pool' >= 0)
The first two need the amount that came out, so they name it amountOut on their second line. opposite turns a
direction round, && means “and”, and property turns a yes-or-no answer into a check.
The four aren’t all the same kind of sentence. Two describe trades: how much comes out, and what happens when you swap it straight back. The other two describe the pool itself, in every state it can ever reach: the total never changes, and no jar goes negative. These are invariants, the simplest kind of safety property, which is the formal name for “nothing bad ever happens”.
Checking one swap at a time is enough for those. If a pool starts with no negative jar, and no single swap can change the total or push a jar below zero, then no run of swaps can either. The tests go looking for the swap that breaks them.
On a blockchain, the jars hold real people’s money, and “no jar goes negative” means nobody gets paid with money the pool doesn’t have.
So where do properties come from when the thing is less obvious than two jars? Three answers:
- Someone wrote them down already. AMMs have a formal literature with their properties spelled out. An agent checked the four above against it, and “swap straight back” has a proper name there: reversibility.
- Guess, then check. Ask an agent to propose properties, and run them. That’s where the four above came from.
- Compare with a model. Later in the series the same pool is written for Ethereum and for Solana, and most of their properties boil down to one: for any pool and any swap, the chain code gives the same answer as this model. That’s a lot easier than guessing at maths.
Let a machine pick the numbers
A property says “for every pool and every swap”, but no test can try every pool. What it can do is try a lot of them, picked at random. That’s the heart of property-based testing: call the function with random inputs, and check the property each time.
The machine makes up pools whose jars hold zero or more, and swaps in either direction with any amount, including zero and negative ones. It doesn’t know which inputs are sensible, and that’s the point. It will happily try paying minus seven silver into a pool that has no silver at all. The pool has to refuse it, and the property has to survive the refusal.
Each property gets at least a hundred made-up cases. If all of them pass, the run says so in one line. If one fails, the run stops and shows the pool and the swap that broke it.
All four pass. That’s a small result, and it should be: the pool is tiny, and the properties say nothing surprising about it. What’s worth having is the method. Write down what must always hold, let a machine hunt for a case where it doesn’t, and pay attention when it finds one.
The scary part was the name
You’ve just read Haskell. Nothing bad happened.
The language has a reputation for being hard, and some of it is earned, but not by code like this. Two records, two enums, a function with guards and four properties are enough to describe a market maker precisely, and a library called QuickCheck generates the tests’ random inputs.
That leaves the gnomes’ board. PHASE 1 holds up: the maths checks out, and every coin is accounted for. But all four properties are about bookkeeping, and none of them asks whether the pool is a good deal for whoever filled it.
Out in the market, gold and silver don’t have to be worth the same. Suppose a gold coin starts trading for two silver. The pool will still hand over gold for one silver apiece to anyone who asks, and every property above still passes.
What happens to the jars is PHASE 2, and it’s the next post.
The Making of an Automated Market Maker: Follow the Maths, and the Money Will Follow. Probably.
The simplest automated market maker, how to read its code, and tests that say “for every pool and every swap” instead of listing examples.
This is the first post in a series about automated market makers: the machines that let anyone on
the internet trade one kind of token for another without a person on the other side. The series
starts with the most naive pool there is and works toward something like the ones that run
on Ethereum and Solana. I’m not an AMM specialist, so I’m learning this in public, and I’ll write
the later posts as I go. The code lives in a public repository,
and the version this post describes is tagged ch01.
This first post is about PHASE 1. It builds the pool, shows how to read its code, and introduces a concept every later post leans on: the property.
A market maker is two jars and a rule
An ordinary exchange matches people. You want to sell gold, someone else wants to buy it, and the exchange introduces you. An automated market maker drops the someone else. In their place is a pool: two jars of tokens (call them gold and silver) and a rule that says how much of one you get for the other. Someone fills the jars to begin with, and after that anyone can trade with them, at any hour, without asking.
Most real pools set the price from how full each jar is, so the price moves as people trade. This one doesn’t. Its rule is the simplest there is: one for one. Pay the pool 10 gold, and it pays you 10 silver. If it held 100 of each, it now holds 110 gold and 90 silver. The total is still 200, which is why this design is called a constant-sum pool.
That is the whole idea, and it already has holes. What happens if you ask for 200 silver from a pool that holds 90? What if you pay it minus five gold? “One for one” doesn’t say. A person at a counter would shrug and refuse. A machine needs to be told, and the telling is the code.
The code reads like a form you fill in
There are four pieces to understand.
The first is a record: a form with named blanks. A pool is two blanks, one per jar, and a swap is a direction and an amount.
data Pool = Pool
{ gold :: Integer
, silver :: Integer
}
data Swap = Swap
{ direction :: Direction
, amountIn :: Integer
}
direction says which way you trade. What follows :: says what kind of thing goes in the blank:
Integer is a whole number, and Direction is the next piece. To read a blank, put its name in
front of the record: if pool is a pool, gold pool is how much gold it holds, and if s is a
swap, amountIn s is how much it pays in.
The second piece is an enum: a value that is exactly one of a fixed list of names. A swap goes one of two ways:
data Direction
= GoldForSilver
| SilverForGold
The | reads as “or”. You either pay gold and receive silver, or pay silver and receive gold. A
swap can also be refused for two reasons, and the code lists them the same way:
data SwapError
= AmountNotPositive
| InsufficientLiquidity
A refusal is either AmountNotPositive (you paid zero or less) or InsufficientLiquidity (the pool
doesn’t hold enough to pay you).
The third piece, Either, is what a swap gives back. A swap either fails with a reason or
succeeds with a result, and Either holds exactly one of those two shapes. Left carries the
reason. Right (as in “all right”) carries the success in two parts: how much the pool hands you,
and the pool after the trade. So if you paid 10 gold into the pool of 100 and 100,
Right (10, Pool 110 90) means “10 silver
came out of the silver jar and is yours now, and the jars hold 110 gold and 90 silver”. No coins are
made or destroyed: your 10 gold went into one jar, and 10 silver came out of the other.
The fourth piece is the function itself:
swap (Swap direction amountIn) (Pool gold silver)
| amountIn <= 0 = Left AmountNotPositive
| amountOut > reserveOut = Left InsufficientLiquidity
| direction == GoldForSilver =
Right (amountOut, Pool (gold + amountIn)
(silver - amountOut))
| otherwise =
Right (amountOut, Pool (gold - amountOut)
(silver + amountIn))
where
amountOut = amountIn -- constant sum: one for one
reserveOut = if direction == GoldForSilver then silver else gold
The first line takes a swap and a pool, and opens them up: it gives names to the parts inside, so
the rest of the function can say amountIn instead of “the amount field of the swap”. There are no
commas between the arguments; a space is enough. Building a pool works the same way:
Pool (gold + amountIn) (silver - amountOut) is a new pool built from the two new jar amounts.
The | is back with a different job. At the start of a line in a function, it begins a guard: a
question, then =, then the answer. Guards are tried top to bottom, and the first question that
comes out true wins. == asks whether two things are equal, so direction == GoldForSilver asks
whether you’re paying gold. otherwise is a question that is always true, so it catches what’s
left.
The where block at the bottom defines the two names the guards use: how much you get back (exactly
what you paid in, which is the one-for-one rule) and how much is in the jar that pays you.
Run one in your head. Pay 10 gold into a pool of 100 and 100. Is 10 at most zero? No. The pool pays
out 10 from the silver jar, which holds 100. Is 10 more than 100? No. Are you paying gold? Yes, so
the answer is Right (10, Pool 110 90).
In the widget below, choose a direction and an amount, then use the arrows to step through the guards with the values filled in. Press Swap to apply the trade to the jars. It also shows the rest of the file, including the type lines the code above leaves out. You can ignore those, here and in the property widget further down.
What the type line means, for the curious
swap :: Swap -> Pool -> Either SwapError (Integer, Pool)
That’s the function’s type, and it uses the same :: as the records. Everything before the last
arrow is an input, and what follows it is the result: swap takes a swap and a pool, and gives back
a refusal or an amount with a new pool. It’s there for the compiler, which checks that the function
really does take and give back those things.
An example checks the case somebody thought of
One case is worth running by hand: a pool holds 40 gold and 25 silver, and you pay it 25 gold.
The pool owes you 25 silver and holds exactly 25, so it pays. The answer is Right (25, Pool 65 0):
the silver jar is empty. The code allows that on purpose. It never pays out more than it holds, but
it will pay out all of it.
The quiz below has more like it. Predict each answer before you look.
That quiz is example testing. Each question is one pool, one swap and one expected answer, and you are the test runner. Examples are useful, but they only cover the cases somebody thought to write, and a pool has a lot of cases nobody would write down.
A property drops the specific numbers. Instead of “this pool and this swap give that answer”, it says “for every pool and every swap, this holds”.
A property is a rule with no exceptions
Finding properties is the hard part of this whole approach, and there’s no recipe for it. One way in is to stop thinking about code and describe the pool to someone who has never seen one: a gnome, say, deciding whether to put its savings in the jars. Described that way, the pool comes down to four sentences:
- A swap leaves the total number of coins in the pool unchanged.
- For each coin you pay in, you get one coin of the other kind back.
- If you swap and then swap straight back, everything is as it was.
- Neither jar ever goes below zero.
Those four sentences are a mental model of the pool. Each one is also a property, because each one is supposed to hold for any pool and any swap. If the code disagrees with one of them, either the code is wrong or the model is, and both are worth knowing.
Here is the first sentence as code:
prop_sumPreserved pool s =
whenSwapSucceeds pool s $ \_ pool' ->
gold pool' + silver pool' === gold pool + silver pool
pool and s are any pool and any swap. The second line runs the swap and, if it goes through,
calls the pool after it pool'; you can skip the rest of that line. The last line is the sentence
itself: the gold and silver in the new pool add up to the same total as before.
The rest of that line, for the curious
whenSwapSucceeds pool s takes one more input: what to do if the swap goes through. That’s a
small function, written on the spot after the $. The $ saves a pair of brackets: everything
after it is one input.
\_ pool' -> … is the function itself. The \ starts it, its inputs go before the ->, and what
it does with them goes after. It gets two inputs, the amount you got back and the new pool. This
property doesn’t need the amount, so it writes _, which means “there’s an input here, and I’m
ignoring it”. The second input, the state of the pool after the swap, it names pool'.
The ' (read “prime”) marks the next version of something: pool is the pool before the swap, and
pool' is the same pool after it. I’ll use it that way for the rest of the series.
=== means “these must be equal”, and when they aren’t, it shows both sides. A refused swap has
nothing to check, so it passes as it is.
The other three follow the same pattern, and only their checks differ:
-- One for each: what came out is what went in
amountOut === amountIn s
-- Swap straight back: the other way, paying in what came out
swap (Swap (opposite (direction s)) amountOut) pool'
=== Right (amountIn s, pool)
-- Never negative: neither jar of the new pool is below zero
property (gold pool' >= 0 && silver pool' >= 0)
The first two need the amount that came out, so they name it amountOut on their second line. opposite turns a
direction round, && means “and”, and property turns a yes-or-no answer into a check.
The four aren’t all the same kind of sentence. Two describe trades: how much comes out, and what happens when you swap it straight back. The other two describe the pool itself, in every state it can ever reach: the total never changes, and no jar goes negative. These are invariants, the simplest kind of safety property, which is the formal name for “nothing bad ever happens”.
Checking one swap at a time is enough for those. If a pool starts with no negative jar, and no single swap can change the total or push a jar below zero, then no run of swaps can either. The tests go looking for the swap that breaks them.
On a blockchain, the jars hold real people’s money, and “no jar goes negative” means nobody gets paid with money the pool doesn’t have.
So where do properties come from when the thing is less obvious than two jars? Three answers:
- Someone wrote them down already. AMMs have a formal literature with their properties spelled out. An agent checked the four above against it, and “swap straight back” has a proper name there: reversibility.
- Guess, then check. Ask an agent to propose properties, and run them. That’s where the four above came from.
- Compare with a model. Later in the series the same pool is written for Ethereum and for Solana, and most of their properties boil down to one: for any pool and any swap, the chain code gives the same answer as this model. That’s a lot easier than guessing at maths.
Let a machine pick the numbers
A property says “for every pool and every swap”, but no test can try every pool. What it can do is try a lot of them, picked at random. That’s the heart of property-based testing: call the function with random inputs, and check the property each time.
The machine makes up pools whose jars hold zero or more, and swaps in either direction with any amount, including zero and negative ones. It doesn’t know which inputs are sensible, and that’s the point. It will happily try paying minus seven silver into a pool that has no silver at all. The pool has to refuse it, and the property has to survive the refusal.
Each property gets at least a hundred made-up cases. If all of them pass, the run says so in one line. If one fails, the run stops and shows the pool and the swap that broke it.
All four pass. That’s a small result, and it should be: the pool is tiny, and the properties say nothing surprising about it. What’s worth having is the method. Write down what must always hold, let a machine hunt for a case where it doesn’t, and pay attention when it finds one.
The scary part was the name
You’ve just read Haskell. Nothing bad happened.
The language has a reputation for being hard, and some of it is earned, but not by code like this. Two records, two enums, a function with guards and four properties are enough to describe a market maker precisely, and a library called QuickCheck generates the tests’ random inputs.
That leaves the gnomes’ board. PHASE 1 holds up: the maths checks out, and every coin is accounted for. But all four properties are about bookkeeping, and none of them asks whether the pool is a good deal for whoever filled it.
Out in the market, gold and silver don’t have to be worth the same. Suppose a gold coin starts trading for two silver. The pool will still hand over gold for one silver apiece to anyone who asks, and every property above still passes.
What happens to the jars is PHASE 2, and it’s the next post.