Playground
amm.gno
// Package amm is a minimal constant-product automated market maker for GRC20
// token pairs, in a single file.
//
// It holds many pools in one realm. A pool is created implicitly by its first
// liquidity deposit and is addressed by the two tokens' grc20reg keys, in
// either order. Swaps follow x*y=k with a 30 bps fee that stays in the pool
// and therefore accrues to the liquidity providers.
//
// # What it is not
//
// Not an oracle: the reserve ratio is a spot price that any trader can move
// within a single transaction. Nothing should price off this realm.
// Not audited. Not a router: one hop, one pool, no path finding. Not a
// place to park value.
//
// # Design notes worth knowing before calling it
//
// Reserves are stored fields and are NEVER derived from BalanceOf. That is
// the single decision that removes Uniswap V2's MINIMUM_LIQUIDITY burn, its
// skim/sync pair, and the first-depositor share-inflation attack in one go:
// sending tokens straight to this realm's address changes no reserve, no
// price and no share value. The price of that is blunt and worth stating:
// tokens sent directly to the realm address are PERMANENTLY STUCK.
//
// The first deposit mints shares equal to the token-A amount rather than
// sqrt(A*B). The geometric mean is cosmetic, every later operation uses only
// ratios, and dropping it removes an integer square root over a 128-bit
// product. Later deposits mint min(A-side, B-side) with floor division on
// both, so an off-ratio deposit always rounds against the depositor.
//
// # v1 vs v0: LP shares are a real GRC20 token
//
// v0 tracks LP positions in a private avl ledger: smallest possible, but a
// position can only be held by the address that opened it and is invisible to
// every other contract. v1 mints one GRC20 token per pool instead, holds its
// PrivateLedger, and registers it with grc20reg. A position is then an
// ordinary fungible token: transferable, approvable, usable as collateral,
// and readable by any realm that knows the registry key.
//
// The cost is honest and measurable. Pool creation now also mints a token and
// writes a registry entry. Positions gain an allowance surface, and with it
// the classic GRC20 approve race. And because MsgCall cannot pass a realm
// argument, this realm has to re-export Transfer/Approve/TransferFrom/
// Allowance wrappers over the LP token for signing users, four functions that
// v0 does not need at all. Another REALM can skip them and move its own LP
// balance through grc20reg directly.
//
// All amounts are int64, as GRC20 mandates, and there is no 256-bit type in
// reach. Pricing therefore runs through a 128-bit mulDiv (math/bits), and
// every reserve is capped at maxReserve so that the plain int64 parts of the
// formula cannot overflow. See the comment on maxReserve for the arithmetic,
// and note the consequence: this AMM is unusable with 18-decimal tokens.
// Six to nine decimals is the practical band.
//
// Design study and full analysis: https://github.com/moul/gno-contracts/issues/135
package amm
import (
"chain"
"math"
"math/bits"
"strconv"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/grc20/v0"
"gno.land/p/nt/seqid/v0"
"gno.land/p/nt/ufmt/v0"
"gno.land/r/nt/grc20reg/v0"
)
const (
// feeNum/feeDen is the swap fee kept by the pool: 997/1000, i.e. 30 bps.
feeNum = 997
feeDen = 1000
// maxReserve is the largest reserve a pool will hold, in base units.
//
// Pricing computes den = reserveIn*feeDen + amountIn*feeNum in plain
// int64 before handing off to the 128-bit mulDiv. Capping every reserve,
// and every post-swap reserve, at MaxInt64/feeDen makes that sum provably
// safe:
//
// den < (reserveIn + amountIn) * feeDen <= maxReserve * feeDen
// = 9223372036854775000 <= MaxInt64 = 9223372036854775807
//
// AddLiquidity enforces the cap on the reserves themselves and Swap
// enforces it on reserveIn+amountIn, so a pool can never even enter the
// region where the formula would be unsafe.
maxReserve = math.MaxInt64 / feeDen // 9223372036854775
)
// pool is one token pair. keyA < keyB always holds: the pair is canonicalised
// on the way in, so (X,Y) and (Y,X) address the same pool.
type pool struct {
keyA, keyB string
tokA, tokB *grc20.Token
resA, resB int64
// lp is this pool's LP token: total supply is the share supply and a
// holder's balance is their position. lpLedger is the minting authority
// and MUST NOT leak out of this file. lpKey is lp's grc20reg key.
lp *grc20.Token
lpLedger *grc20.PrivateLedger
lpKey string
}
// pools maps the pool id "keyA~keyB" -> *pool. "~" cannot occur in a
// grc20reg key, and unlike "|" it does not break a markdown table cell.
var pools avl.Tree
// lpSeq numbers the LP tokens. It is never reset, so a symbol is never reused
// and grc20reg's one-token-per-realm-and-symbol rule is never tripped.
var lpSeq seqid.ID
//
// Writes.
//
// AddLiquidity deposits up to maxA of keyA and maxB of keyB and mints LP
// shares to the caller. It creates the pool if this is its first deposit, in
// which case the caller's amounts set the starting price and the whole of
// maxA and maxB is taken.
//
// On an existing pool the deposit is trimmed to the current reserve ratio:
// only one side is consumed in full and the remainder of the richer side is
// left untouched, so pass the amounts you are willing to spend, not the
// amounts you insist on spending.
//
// The caller must first Approve this realm's address on BOTH tokens for at
// least the amounts that will be taken. Returns the shares minted.
func AddLiquidity(cur realm, keyA, keyB string, maxA, maxB int64) int64 {
a, b, flipped := canon(keyA, keyB)
amtA, amtB := maxA, maxB
if flipped {
amtA, amtB = maxB, maxA
}
if amtA <= 0 || amtB <= 0 {
panic("amm: both deposit amounts must be > 0")
}
p := getPool(a, b)
if p == nil {
p = newPool(0, cur, a, b)
pools.Set(poolID(a, b), p)
}
var minted int64
if p.lp.TotalSupply() == 0 {
// First position: the depositor sets the price and the share unit is
// token A at seed time. No sqrt, no MINIMUM_LIQUIDITY burn.
minted = amtA
} else {
// Trim to the current ratio, then mint from whichever side is scarcer.
// Both divisions floor, and taking the minimum means an off-ratio
// deposit is rounded against the depositor, never against the pool.
if want := mulDiv(amtA, p.resB, p.resA); want <= amtB {
amtB = want
} else {
amtA = mulDiv(amtB, p.resA, p.resB)
}
if amtA <= 0 || amtB <= 0 {
panic("amm: deposit too small for the current ratio")
}
supply := p.lp.TotalSupply()
minted = min64(
mulDiv(amtA, supply, p.resA),
mulDiv(amtB, supply, p.resB),
)
}
if minted <= 0 {
panic("amm: deposit mints zero shares")
}
if p.resA+amtA > maxReserve || p.resB+amtB > maxReserve {
panic("amm: reserve cap exceeded")
}
provider := cur.Previous().Address()
self := cur.Address()
pull(0, cur, p.tokA, provider, self, amtA)
pull(0, cur, p.tokB, provider, self, amtB)
p.resA += amtA
p.resB += amtB
if err := p.lpLedger.Mint(provider, minted); err != nil {
panic("amm: cannot mint LP shares: " + err.Error())
}
chain.Emit("AddLiquidity",
"pool", poolID(p.keyA, p.keyB),
"provider", provider.String(),
"amountA", itoa(amtA),
"amountB", itoa(amtB),
"shares", itoa(minted),
)
return minted
}
// RemoveLiquidity burns shares held by the caller and returns the proportional
// amounts of both tokens, in the caller's (keyA, keyB) argument order.
//
// Burning the pool's entire share supply pays out the whole reserve, so the
// last provider out leaves nothing unclaimable behind and the pool can be
// reseeded at a fresh price.
func RemoveLiquidity(cur realm, keyA, keyB string, shares int64) (int64, int64) {
if shares <= 0 {
panic("amm: shares must be > 0")
}
a, b, flipped := canon(keyA, keyB)
p := mustPool(a, b)
owner := cur.Previous().Address()
if p.lp.BalanceOf(owner) < shares {
panic("amm: insufficient shares")
}
supply := p.lp.TotalSupply()
var amtA, amtB int64
if shares == supply {
amtA, amtB = p.resA, p.resB
} else {
amtA = mulDiv(shares, p.resA, supply)
amtB = mulDiv(shares, p.resB, supply)
}
if amtA <= 0 || amtB <= 0 {
panic("amm: burn would return nothing on one side")
}
p.resA -= amtA
p.resB -= amtB
if err := p.lpLedger.Burn(owner, shares); err != nil {
panic("amm: cannot burn LP shares: " + err.Error())
}
push(0, cur, p.tokA, owner, amtA)
push(0, cur, p.tokB, owner, amtB)
chain.Emit("RemoveLiquidity",
"pool", poolID(p.keyA, p.keyB),
"provider", owner.String(),
"amountA", itoa(amtA),
"amountB", itoa(amtB),
"shares", itoa(shares),
)
if flipped {
return amtB, amtA
}
return amtA, amtB
}
// Swap sells amountIn of keyIn for keyOut and aborts unless at least minOut
// comes back. The caller must first Approve this realm's address on keyIn.
//
// minOut is the only protection against being sandwiched or against the pool
// moving between quoting and execution. Pass a real bound; passing 0 means
// accepting any price at all.
func Swap(cur realm, keyIn, keyOut string, amountIn, minOut int64) int64 {
if amountIn <= 0 {
panic("amm: amountIn must be > 0")
}
if minOut < 0 {
panic("amm: minOut must be >= 0")
}
a, b, flipped := canon(keyIn, keyOut)
p := mustPool(a, b)
resIn, resOut := p.resA, p.resB
tokIn, tokOut := p.tokA, p.tokB
if flipped {
resIn, resOut = p.resB, p.resA
tokIn, tokOut = p.tokB, p.tokA
}
out := AmountOut(amountIn, resIn, resOut)
if out <= 0 {
panic("amm: output rounds to zero")
}
if out < minOut {
panic("amm: slippage, output below minOut")
}
trader := cur.Previous().Address()
pull(0, cur, tokIn, trader, cur.Address(), amountIn)
newIn, newOut := resIn+amountIn, resOut-out
// The invariant holds by construction (out is floored), so this can only
// fire if the pricing above is ever edited into being wrong. It is exact:
// both products are compared in 128 bits.
if cmpProd(newIn, newOut, resIn, resOut) < 0 {
panic("amm: constant product regression")
}
if flipped {
p.resB, p.resA = newIn, newOut
} else {
p.resA, p.resB = newIn, newOut
}
push(0, cur, tokOut, trader, out)
chain.Emit("Swap",
"pool", poolID(p.keyA, p.keyB),
"trader", trader.String(),
"tokenIn", tokIn.GetSymbol(),
"amountIn", itoa(amountIn),
"amountOut", itoa(out),
)
return out
}
// TransferLP moves amount of the caller's LP position to `to`.
//
// The LP token lives in this realm, so a signing user cannot reach it through
// the token's own entry points the way they would for any other GRC20: there
// are none. These four wrappers are that entry point. A REALM holding LP does
// not need them and can go through grc20reg instead:
//
// grc20reg.Transfer(0, cur, amm.LPToken(keyA, keyB), to, n)
func TransferLP(cur realm, keyA, keyB string, to address, amount int64) {
a, b, _ := canon(keyA, keyB)
lpCheck(mustPool(a, b).lpLedger.CallerTeller().Transfer(0, cur, to, amount))
}
// ApproveLP lets spender move up to amount of the caller's LP position.
//
// Same approve race as any GRC20: an allowance changed from a non-zero value
// can be spent at both the old and the new one if the holder is unlucky with
// ordering. Set it to 0 first when lowering it.
func ApproveLP(cur realm, keyA, keyB string, spender address, amount int64) {
a, b, _ := canon(keyA, keyB)
lpCheck(mustPool(a, b).lpLedger.CallerTeller().Approve(0, cur, spender, amount))
}
// TransferFromLP spends an allowance the owner granted to the caller.
func TransferFromLP(cur realm, keyA, keyB string, from, to address, amount int64) {
a, b, _ := canon(keyA, keyB)
lpCheck(mustPool(a, b).lpLedger.CallerTeller().TransferFrom(0, cur, from, to, amount))
}
func lpCheck(err error) {
if err != nil {
panic("amm: LP token: " + err.Error())
}
}
//
// Reads.
//
// AmountOut is the pricing function, fee included, as a pure function of the
// two reserves. Exported so a caller can quote off-chain against reserves it
// already holds, and so the arithmetic is testable on its own.
func AmountOut(amountIn, reserveIn, reserveOut int64) int64 {
if amountIn <= 0 {
panic("amm: amountIn must be > 0")
}
if reserveIn <= 0 || reserveOut <= 0 {
panic("amm: pool has an empty reserve")
}
if reserveIn > maxReserve || reserveOut > maxReserve {
panic("amm: reserve above cap")
}
if amountIn > maxReserve-reserveIn {
panic("amm: reserve cap exceeded")
}
inFee := amountIn * feeNum
den := reserveIn*feeDen + inFee
return mulDiv(inFee, reserveOut, den)
}
// Quote prices amountIn of keyIn against the pool's live reserves. It is the
// number Swap would return right now, which is not a promise about the next
// block.
func Quote(keyIn, keyOut string, amountIn int64) int64 {
a, b, flipped := canon(keyIn, keyOut)
p := mustPool(a, b)
if flipped {
return AmountOut(amountIn, p.resB, p.resA)
}
return AmountOut(amountIn, p.resA, p.resB)
}
// Reserves returns the two reserves in the caller's argument order.
func Reserves(keyA, keyB string) (int64, int64) {
a, b, flipped := canon(keyA, keyB)
p := mustPool(a, b)
if flipped {
return p.resB, p.resA
}
return p.resA, p.resB
}
// SharesOf returns owner's LP shares, i.e. their LP token balance.
func SharesOf(keyA, keyB string, owner address) int64 {
a, b, _ := canon(keyA, keyB)
return mustPool(a, b).lp.BalanceOf(owner)
}
// TotalShares returns the pool's LP token total supply.
func TotalShares(keyA, keyB string) int64 {
a, b, _ := canon(keyA, keyB)
return mustPool(a, b).lp.TotalSupply()
}
// LPToken returns the grc20reg key of the pool's LP token. Hand it to any
// realm that should read or move these positions without importing this one.
func LPToken(keyA, keyB string) string {
a, b, _ := canon(keyA, keyB)
return mustPool(a, b).lpKey
}
// AllowanceLP reports how much of owner's LP position spender may move.
func AllowanceLP(keyA, keyB string, owner, spender address) int64 {
a, b, _ := canon(keyA, keyB)
return mustPool(a, b).lp.Allowance(owner, spender)
}
// PoolCount returns how many pools exist.
func PoolCount() int { return pools.Size() }
// Render lists every pool, or one pool's detail when path is a "keyA~keyB"
// pool id.
func Render(path string) string {
if path != "" {
v := pools.Get(path)
if v == nil {
return "# 404\n\nNo pool `" + path + "`.\n"
}
p := v.(*pool)
out := "# " + p.tokA.GetSymbol() + " / " + p.tokB.GetSymbol() + "\n\n"
out += "- **" + p.tokA.GetSymbol() + "** reserve: " + itoa(p.resA) + " (`" + p.keyA + "`)\n"
out += "- **" + p.tokB.GetSymbol() + "** reserve: " + itoa(p.resB) + " (`" + p.keyB + "`)\n"
out += "- **LP token**: `" + p.lpKey + "` (" + p.lp.GetSymbol() + ")\n"
out += "- **LP shares**: " + itoa(p.lp.TotalSupply()) + " across " + strconv.Itoa(p.lp.KnownAccounts()) + " holder(s)\n"
return out
}
out := "# Minimal AMM\n\n"
out += "Constant product (`x*y=k`) with a 30 bps fee kept by the pool. Every position is a transferable GRC20 LP token. Reserves are stored, never read from balances, so sending tokens here directly does nothing and they cannot be recovered.\n\n"
if pools.Size() == 0 {
out += "_No pools yet. Call `AddLiquidity` with two `grc20reg` keys to open one._\n"
return out
}
out += "| pool | reserves | LP token | supply | holders |\n"
out += "|---|---|---|---|---|\n"
pools.Iterate("", "", func(key string, value any) bool {
p := value.(*pool)
out += ufmt.Sprintf("| [%s/%s](/r/nym-moultest123/x/amm/v0:%s) | %d %s / %d %s | %s | %d | %d |\n",
p.tokA.GetSymbol(), p.tokB.GetSymbol(), key,
p.resA, p.tokA.GetSymbol(), p.resB, p.tokB.GetSymbol(),
p.lp.GetSymbol(), p.lp.TotalSupply(), p.lp.KnownAccounts())
return false
})
return out
}
//
// Internals.
//
// canon sorts a caller's token pair into the pool's canonical order and
// reports whether the caller's order was reversed.
func canon(first, second string) (a, b string, flipped bool) {
if first == "" || second == "" {
panic("amm: empty token key")
}
if first == second {
panic("amm: a pool needs two different tokens")
}
if first > second {
return second, first, true
}
return first, second, false
}
// newPool resolves both tokens, mints this pool's LP token and registers it.
//
// Non-crossing (`_ int, rlm realm`): grc20.NewToken binds the token's
// origRealm to rlm.PkgPath() under an IsCurrent assertion, and grc20reg
// keys off the registering caller, so rlm has to stay AddLiquidity's own
// live frame rather than a fresh one.
//
// The LP unit is token A at seed time, so the LP token mirrors token A's
// decimals. The symbol is LP<n> because grc20 caps a symbol at 11 chars,
// which "LP-" plus two 11-char symbols would blow past; the human-readable
// pair lives in the name instead.
func newPool(_ int, rlm realm, a, b string) *pool {
tokA, tokB := grc20reg.MustGet(a), grc20reg.MustGet(b)
id := lpSeq.Next()
lp, ledger := grc20.NewToken(
"AMM LP "+tokA.GetSymbol()+"/"+tokB.GetSymbol(),
"LP"+strconv.FormatUint(uint64(id), 10),
tokA.GetDecimals(),
id,
rlm,
)
p := &pool{keyA: a, keyB: b, tokA: tokA, tokB: tokB, lp: lp, lpLedger: ledger}
p.lpKey = grc20reg.Register(cross(rlm), lp, "")
return p
}
// poolID is the storage and render key for a canonicalised pair.
func poolID(a, b string) string { return a + "~" + b }
func getPool(a, b string) *pool {
v := pools.Get(poolID(a, b))
if v == nil {
return nil
}
return v.(*pool)
}
func mustPool(a, b string) *pool {
p := getPool(a, b)
if p == nil {
panic("amm: no such pool: " + poolID(a, b))
}
return p
}
// pull moves amount of tok from `from` into this realm, spending the
// allowance `from` granted to this realm's address.
//
// Non-crossing on purpose: `_ int, rlm realm` is the only shape that keeps
// rlm the caller's own live frame. RealmTeller binds the spender eagerly to
// rlm.Address(), which is this realm.
func pull(_ int, rlm realm, tok *grc20.Token, from, to address, amount int64) {
err := tok.RealmTeller(0, rlm).TransferFrom(0, rlm, from, to, amount)
if err != nil {
panic("amm: cannot take " + tok.GetSymbol() + ": " + err.Error())
}
}
// push sends amount of tok from this realm to `to`.
func push(_ int, rlm realm, tok *grc20.Token, to address, amount int64) {
err := tok.RealmTeller(0, rlm).Transfer(0, rlm, to, amount)
if err != nil {
panic("amm: cannot send " + tok.GetSymbol() + ": " + err.Error())
}
}
// mulDiv returns floor(a*b/c) through a 128-bit intermediate, which plain
// int64 arithmetic cannot do: a*b is routinely wider than 63 bits here even
// when the quotient is small.
func mulDiv(a, b, c int64) int64 {
if a < 0 || b < 0 {
panic("amm: negative operand")
}
if c <= 0 {
panic("amm: division by a non-positive value")
}
hi, lo := bits.Mul64(uint64(a), uint64(b))
// bits.Div64 panics for y <= hi; refusing here turns that into a named
// abort and also covers every quotient that would not fit in 64 bits.
if hi >= uint64(c) {
panic("amm: quotient overflows int64")
}
q, _ := bits.Div64(hi, lo, uint64(c))
if q > uint64(math.MaxInt64) {
panic("amm: quotient overflows int64")
}
return int64(q)
}
// cmpProd compares a*b with c*d exactly, in 128 bits, and returns -1, 0 or 1.
func cmpProd(a, b, c, d int64) int {
h1, l1 := bits.Mul64(uint64(a), uint64(b))
h2, l2 := bits.Mul64(uint64(c), uint64(d))
if h1 != h2 {
if h1 < h2 {
return -1
}
return 1
}
if l1 != l2 {
if l1 < l2 {
return -1
}
return 1
}
return 0
}
func min64(a, b int64) int64 {
if a < b {
return a
}
return b
}
func itoa(v int64) string { return strconv.FormatInt(v, 10) }
amm_test.gno
package amm
import (
"chain"
"testing"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/grc20/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/r/nt/grc20reg/v0"
)
// Two throwaway tokens, minted and registered once for the whole test binary.
// They are created from this realm, so grc20reg keys them under this path.
var (
tokAAA, tokBBB *grc20.Token
ledAAA, ledBBB *grc20.PrivateLedger
keyAAA, keyBBB string
)
func init(cur realm) {
tokAAA, ledAAA = grc20.NewToken("Test Alpha", "AAA", 6, 0, cur)
tokBBB, ledBBB = grc20.NewToken("Test Beta", "BBB", 6, 1, cur)
keyAAA = grc20reg.Register(cross(cur), tokAAA, "")
keyBBB = grc20reg.Register(cross(cur), tokBBB, "")
}
func self() address { return chain.PackageAddress("gno.land/r/nym-moultest123/x/amm/v0") }
// fund mints both tokens to addr and approves this realm to spend them.
func fund(addr address, amount int64) {
ledAAA.Mint(addr, amount)
ledBBB.Mint(addr, amount)
ledAAA.Approve(addr, self(), amount)
ledBBB.Approve(addr, self(), amount)
}
// reset clears every pool so each test starts from an empty realm.
func reset() { pools = avl.Tree{} }
//
// Pure arithmetic.
//
func TestAmountOut(t *testing.T) {
cases := []struct {
name string
in, resIn, resOut, want int64
}{
{"balanced pool, small trade", 1_000, 1_000_000, 1_000_000, 996},
{"balanced pool, 1%", 10_000, 1_000_000, 1_000_000, 9_871},
{"balanced pool, 10%", 100_000, 1_000_000, 1_000_000, 90_661},
{"balanced pool, 50%", 500_000, 1_000_000, 1_000_000, 332_665},
{"skewed pool", 100_000, 1_000_000, 4_000_000, 362_644},
{"near drain", 1_000, 1, 1_000_000, 998_997},
{"dust rounds to zero", 1, 1_000_000, 1_000_000, 0},
{"reserves at the cap", maxReserve / 2, maxReserve / 2, maxReserve, 4_604_758_097_518_382},
}
for _, tc := range cases {
got := AmountOut(tc.in, tc.resIn, tc.resOut)
uassert.Equal(t, tc.want, got, tc.name)
}
}
func TestAmountOutNeverBreaksK(t *testing.T) {
resIn, resOut := int64(3_000_000), int64(7_500_000)
for _, in := range []int64{1, 7, 1_000, 999_999, 3_000_000} {
out := AmountOut(in, resIn, resOut)
uassert.True(t, out < resOut, "output must stay inside the reserve")
uassert.True(t, cmpProd(resIn+in, resOut-out, resIn, resOut) >= 0, "k must not decrease")
}
}
func TestAmountOutGuards(cur realm, t *testing.T) {
uassert.PanicsWithMessage(t, cur, "amm: amountIn must be > 0", func() {
AmountOut(0, 1_000, 1_000)
})
uassert.PanicsWithMessage(t, cur, "amm: pool has an empty reserve", func() {
AmountOut(1, 0, 1_000)
})
uassert.PanicsWithMessage(t, cur, "amm: reserve above cap", func() {
AmountOut(1, maxReserve+1, 1_000)
})
uassert.PanicsWithMessage(t, cur, "amm: reserve cap exceeded", func() {
AmountOut(maxReserve, maxReserve, 1_000)
})
}
func TestMulDiv(t *testing.T) {
uassert.Equal(t, int64(0), mulDiv(0, 12345, 7))
uassert.Equal(t, int64(3), mulDiv(7, 5, 10)) // floors
// 2^62 * 4 is 2^64: the intermediate does not fit in int64, the result does.
const big = int64(1) << 62
uassert.Equal(t, big/2, mulDiv(big, 4, 8))
// maxReserve * feeDen is the widest product this realm ever forms.
uassert.Equal(t, int64(maxReserve), mulDiv(maxReserve, feeDen, feeDen))
}
func TestCmpProd(t *testing.T) {
const big = int64(1) << 40
uassert.Equal(t, 0, cmpProd(big, big, big, big))
uassert.Equal(t, -1, cmpProd(big, big, big, big+1))
uassert.Equal(t, 1, cmpProd(big, big+1, big, big))
}
//
// Lifecycle.
//
func TestSeedSwapRemove(cur realm, t *testing.T) {
reset()
alice := testutils.TestAddress("seed-alice")
fund(alice, 10_000_000)
testing.SetRealm(testing.NewUserRealm(alice))
heldA, heldB := tokAAA.BalanceOf(self()), tokBBB.BalanceOf(self())
// Seed: the first provider sets the price and gets shares == amountA.
minted := AddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 4_000_000)
uassert.Equal(t, int64(1_000_000), minted)
uassert.Equal(t, int64(1), int64(PoolCount()))
rA, rB := Reserves(keyAAA, keyBBB)
uassert.Equal(t, int64(1_000_000), rA)
uassert.Equal(t, int64(4_000_000), rB)
uassert.Equal(t, heldA+1_000_000, tokAAA.BalanceOf(self()), "reserve is really held")
// Swap AAA -> BBB.
quoted := Quote(keyAAA, keyBBB, 100_000)
uassert.Equal(t, int64(362_644), quoted)
out := Swap(cross(cur), keyAAA, keyBBB, 100_000, 362_000)
uassert.Equal(t, quoted, out)
rA, rB = Reserves(keyAAA, keyBBB)
uassert.Equal(t, int64(1_100_000), rA)
uassert.Equal(t, int64(3_637_356), rB)
uassert.True(t, cmpProd(rA, rB, 1_000_000, 4_000_000) > 0, "fee grew k")
// Burn half the position.
gotA, gotB := RemoveLiquidity(cross(cur), keyAAA, keyBBB, 500_000)
uassert.Equal(t, int64(550_000), gotA)
uassert.Equal(t, int64(1_818_678), gotB)
uassert.Equal(t, int64(500_000), TotalShares(keyAAA, keyBBB))
// Burn the rest: the last provider out takes the whole reserve.
gotA, gotB = RemoveLiquidity(cross(cur), keyAAA, keyBBB, 500_000)
uassert.Equal(t, int64(550_000), gotA)
uassert.Equal(t, int64(1_818_678), gotB)
uassert.Equal(t, int64(0), TotalShares(keyAAA, keyBBB))
rA, rB = Reserves(keyAAA, keyBBB)
uassert.Equal(t, int64(0), rA)
uassert.Equal(t, int64(0), rB)
uassert.Equal(t, heldA, tokAAA.BalanceOf(self()), "nothing unclaimable left behind")
uassert.Equal(t, heldB, tokBBB.BalanceOf(self()), "nothing unclaimable left behind")
// A drained pool is reseedable, at whatever price the next provider picks.
uassert.Equal(t, int64(200_000), AddLiquidity(cross(cur), keyAAA, keyBBB, 200_000, 100_000))
rA, rB = Reserves(keyAAA, keyBBB)
uassert.Equal(t, int64(200_000), rA)
uassert.Equal(t, int64(100_000), rB)
}
func TestArgumentOrderIsSymmetric(cur realm, t *testing.T) {
reset()
alice := testutils.TestAddress("sym-alice")
fund(alice, 10_000_000)
testing.SetRealm(testing.NewUserRealm(alice))
AddLiquidity(cross(cur), keyBBB, keyAAA, 4_000_000, 1_000_000)
uassert.Equal(t, int64(1), int64(PoolCount()), "one pool whichever order is used")
rA, rB := Reserves(keyAAA, keyBBB)
uassert.Equal(t, int64(1_000_000), rA)
uassert.Equal(t, int64(4_000_000), rB)
rB2, rA2 := Reserves(keyBBB, keyAAA)
uassert.Equal(t, rA, rA2, "reserves follow the caller's order")
uassert.Equal(t, rB, rB2, "reserves follow the caller's order")
}
func TestSecondProviderIsTrimmedToRatio(cur realm, t *testing.T) {
reset()
alice := testutils.TestAddress("trim-alice")
bob := testutils.TestAddress("trim-bob")
fund(alice, 10_000_000)
fund(bob, 10_000_000)
testing.SetRealm(testing.NewUserRealm(alice))
AddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 4_000_000)
// Bob offers a badly skewed pair: 100k AAA is only worth 400k BBB, so the
// extra BBB is left in his wallet and his shares price off the scarce side.
testing.SetRealm(testing.NewUserRealm(bob))
beforeB := tokBBB.BalanceOf(bob)
minted := AddLiquidity(cross(cur), keyAAA, keyBBB, 100_000, 9_000_000)
uassert.Equal(t, int64(100_000), minted)
uassert.Equal(t, int64(400_000), beforeB-tokBBB.BalanceOf(bob), "only the ratio amount was taken")
rA, rB := Reserves(keyAAA, keyBBB)
uassert.Equal(t, int64(1_100_000), rA)
uassert.Equal(t, int64(4_400_000), rB)
uassert.Equal(t, int64(1_100_000), TotalShares(keyAAA, keyBBB))
// Round-trip: Bob can never take out more than he put in.
gotA, gotB := RemoveLiquidity(cross(cur), keyAAA, keyBBB, minted)
uassert.True(t, gotA <= 100_000, "no value created on the A side")
uassert.True(t, gotB <= 400_000, "no value created on the B side")
}
func TestDonationIsInert(cur realm, t *testing.T) {
reset()
alice := testutils.TestAddress("don-alice")
mallory := testutils.TestAddress("don-mallory")
fund(alice, 10_000_000)
fund(mallory, 10_000_000)
testing.SetRealm(testing.NewUserRealm(alice))
AddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 1_000_000)
before := Quote(keyAAA, keyBBB, 10_000)
// Mallory sends 5,000,000 AAA straight to the realm address, the classic
// setup for a share-inflation or price-manipulation attack.
heldA := tokAAA.BalanceOf(self())
ledAAA.Transfer(mallory, self(), 5_000_000)
uassert.Equal(t, heldA+5_000_000, tokAAA.BalanceOf(self()), "the balance really moved")
rA, rB := Reserves(keyAAA, keyBBB)
uassert.Equal(t, int64(1_000_000), rA, "reserves ignore balances")
uassert.Equal(t, int64(1_000_000), rB, "reserves ignore balances")
uassert.Equal(t, before, Quote(keyAAA, keyBBB, 10_000), "price is unchanged")
// And a later provider is priced off reserves, not off the donation.
testing.SetRealm(testing.NewUserRealm(mallory))
uassert.Equal(t, int64(1_000_000), AddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 1_000_000))
}
//
// Guards.
//
func TestGuards(cur realm, t *testing.T) {
reset()
alice := testutils.TestAddress("guard-alice")
fund(alice, 10_000_000)
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsWithMessage(t, cur, "amm: a pool needs two different tokens", func() {
AddLiquidity(cross(cur), keyAAA, keyAAA, 1, 1)
})
uassert.AbortsWithMessage(t, cur, "amm: both deposit amounts must be > 0", func() {
AddLiquidity(cross(cur), keyAAA, keyBBB, 0, 1)
})
uassert.AbortsWithMessage(t, cur, "amm: no such pool: "+keyAAA+"~"+keyBBB, func() {
Swap(cross(cur), keyAAA, keyBBB, 1, 0)
})
AddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 1_000_000)
uassert.AbortsWithMessage(t, cur, "amm: slippage, output below minOut", func() {
Swap(cross(cur), keyAAA, keyBBB, 10_000, 10_000)
})
uassert.AbortsWithMessage(t, cur, "amm: output rounds to zero", func() {
Swap(cross(cur), keyAAA, keyBBB, 1, 0)
})
uassert.AbortsWithMessage(t, cur, "amm: amountIn must be > 0", func() {
Swap(cross(cur), keyAAA, keyBBB, 0, 0)
})
uassert.AbortsWithMessage(t, cur, "amm: insufficient shares", func() {
RemoveLiquidity(cross(cur), keyAAA, keyBBB, 2_000_000)
})
uassert.AbortsWithMessage(t, cur, "amm: reserve cap exceeded", func() {
AddLiquidity(cross(cur), keyAAA, keyBBB, maxReserve, maxReserve)
})
// An allowance that does not cover the deposit aborts, and nothing moved.
bob := testutils.TestAddress("guard-bob")
ledAAA.Mint(bob, 1_000_000)
ledBBB.Mint(bob, 1_000_000)
ledAAA.Approve(bob, self(), 10)
ledBBB.Approve(bob, self(), 1_000_000)
testing.SetRealm(testing.NewUserRealm(bob))
uassert.AbortsContains(t, cur, "insufficient allowance", func() {
AddLiquidity(cross(cur), keyAAA, keyBBB, 100_000, 100_000)
})
uassert.Equal(t, int64(1_000_000), tokAAA.BalanceOf(bob), "nothing moved: the first pull failed")
uassert.Equal(t, int64(0), SharesOf(keyAAA, keyBBB, bob))
}
gas_test.gno
package amm
import (
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
// A fixed four-step profile, declared in order so `gno test -v` reports one
// `--- GAS:` figure per operation. The same four steps exist verbatim in v1,
// so the difference between the two runs is the cost of the share accounting
// and nothing else. See moul/gno-contracts#135.
var (
gasAlice = testutils.TestAddress("gas-alice")
gasBob = testutils.TestAddress("gas-bob")
)
// TestGas0Fund keeps the fixture cost (minting and approving both tokens for
// both actors) out of the four measured numbers.
func TestGas0Fund(t *testing.T) {
reset()
fund(gasAlice, 10_000_000)
fund(gasBob, 10_000_000)
}
func TestGas1Seed(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(gasAlice))
uassert.Equal(t, int64(1_000_000), AddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 4_000_000))
}
func TestGas2Swap(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(gasAlice))
uassert.Equal(t, int64(362_644), Swap(cross(cur), keyAAA, keyBBB, 100_000, 1))
}
func TestGas3Join(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(gasBob))
uassert.Equal(t, int64(90_908), AddLiquidity(cross(cur), keyAAA, keyBBB, 100_000, 1_000_000))
}
func TestGas4Exit(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(gasBob))
held := SharesOf(keyAAA, keyBBB, gasBob)
uassert.Equal(t, int64(90_908), held)
RemoveLiquidity(cross(cur), keyAAA, keyBBB, held)
uassert.Equal(t, int64(0), SharesOf(keyAAA, keyBBB, gasBob))
}
gnomod.toml
module = "gno.land/r/nym-moultest123/x/amm/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186407 max_deposit = "19000000ugnot"
lp_test.gno
package amm
import (
"testing"
"gno.land/p/nt/grc20/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/r/nt/grc20reg/v0"
)
// A third token, so a second pool can prove each one mints its own LP token.
var (
tokCCC *grc20.Token
ledCCC *grc20.PrivateLedger
keyCCC string
)
func init(cur realm) {
tokCCC, ledCCC = grc20.NewToken("Test Gamma", "CCC", 6, 2, cur)
keyCCC = grc20reg.Register(cross(cur), tokCCC, "")
}
// TestLPPositionIsARealToken is the whole point of v1: the position exists
// outside this realm, as an ordinary registered GRC20.
func TestLPPositionIsARealToken(cur realm, t *testing.T) {
reset()
alice := testutils.TestAddress("lp-alice")
fund(alice, 10_000_000)
testing.SetRealm(testing.NewUserRealm(alice))
minted := AddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 4_000_000)
// Readable by any realm that knows the key, without importing this one.
lp := grc20reg.MustGet(LPToken(keyAAA, keyBBB))
uassert.Equal(t, minted, lp.BalanceOf(alice))
uassert.Equal(t, minted, lp.TotalSupply())
uassert.Equal(t, minted, TotalShares(keyAAA, keyBBB))
// The LP unit is token A at seed time, so it mirrors token A's decimals.
uassert.Equal(t, tokAAA.GetDecimals(), lp.GetDecimals())
uassert.Equal(t, "AMM LP AAA/BBB", lp.GetName())
}
// TestLPIsTransferable: a position can change hands without touching the pool.
func TestLPIsTransferable(cur realm, t *testing.T) {
reset()
alice := testutils.TestAddress("xfer-alice")
bob := testutils.TestAddress("xfer-bob")
fund(alice, 10_000_000)
testing.SetRealm(testing.NewUserRealm(alice))
AddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 4_000_000)
TransferLP(cross(cur), keyAAA, keyBBB, bob, 500_000)
uassert.Equal(t, int64(500_000), SharesOf(keyAAA, keyBBB, alice))
uassert.Equal(t, int64(500_000), SharesOf(keyAAA, keyBBB, bob))
// Bob exits on a position he was given, having never deposited anything.
// In v0 this is not expressible at all.
testing.SetRealm(testing.NewUserRealm(bob))
gotA, gotB := RemoveLiquidity(cross(cur), keyAAA, keyBBB, 500_000)
uassert.Equal(t, int64(500_000), gotA)
uassert.Equal(t, int64(2_000_000), gotB)
uassert.Equal(t, int64(500_000), tokAAA.BalanceOf(bob), "bob was never funded")
}
// TestLPAllowance: the approve/transferFrom surface v1 gains, and the abort
// when it is spent past its limit.
func TestLPAllowance(cur realm, t *testing.T) {
reset()
alice := testutils.TestAddress("allow-alice")
carol := testutils.TestAddress("allow-carol")
fund(alice, 10_000_000)
testing.SetRealm(testing.NewUserRealm(alice))
AddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 1_000_000)
ApproveLP(cross(cur), keyAAA, keyBBB, carol, 300_000)
uassert.Equal(t, int64(300_000), AllowanceLP(keyAAA, keyBBB, alice, carol))
testing.SetRealm(testing.NewUserRealm(carol))
TransferFromLP(cross(cur), keyAAA, keyBBB, alice, carol, 300_000)
uassert.Equal(t, int64(300_000), SharesOf(keyAAA, keyBBB, carol))
uassert.Equal(t, int64(700_000), SharesOf(keyAAA, keyBBB, alice))
uassert.Equal(t, int64(0), AllowanceLP(keyAAA, keyBBB, alice, carol))
uassert.AbortsContains(t, cur, "insufficient allowance", func() {
TransferFromLP(cross(cur), keyAAA, keyBBB, alice, carol, 1)
})
}
// TestEachPoolMintsItsOwnLPToken: two pools, two distinct registered tokens.
func TestEachPoolMintsItsOwnLPToken(cur realm, t *testing.T) {
reset()
alice := testutils.TestAddress("two-alice")
fund(alice, 10_000_000)
ledCCC.Mint(alice, 10_000_000)
ledCCC.Approve(alice, self(), 10_000_000)
testing.SetRealm(testing.NewUserRealm(alice))
AddLiquidity(cross(cur), keyAAA, keyBBB, 1_000_000, 4_000_000)
AddLiquidity(cross(cur), keyAAA, keyCCC, 2_000_000, 2_000_000)
ab := LPToken(keyAAA, keyBBB)
ac := LPToken(keyAAA, keyCCC)
uassert.NotEqual(t, ab, ac, "one LP token per pool")
uassert.Equal(t, int64(1_000_000), grc20reg.MustGet(ab).TotalSupply())
uassert.Equal(t, int64(2_000_000), grc20reg.MustGet(ac).TotalSupply())
uassert.Equal(t, "AMM LP AAA/CCC", grc20reg.MustGet(ac).GetName())
// Moving one pool's LP leaves the other alone.
TransferLP(cross(cur), keyAAA, keyBBB, testutils.TestAddress("two-bob"), 400_000)
uassert.Equal(t, int64(600_000), SharesOf(keyAAA, keyBBB, alice))
uassert.Equal(t, int64(2_000_000), SharesOf(keyAAA, keyCCC, alice))
}
render_example_test.gno
package amm
import (
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/grc20/v0"
"gno.land/p/nt/testutils/v0"
)
// A fixed LP token for the examples, so the rendered symbol does not depend on
// how many pools the other tests happened to open first.
var (
exLP *grc20.Token
exLedge *grc20.PrivateLedger
)
func init(cur realm) {
exLP, exLedge = grc20.NewToken("AMM LP AAA/BBB", "LPDEMO", 6, 9999, cur)
exLedge.Mint(testutils.TestAddress("lp"), 1_000_000)
}
// seedExamplePool installs one deterministic pool so the examples below do not
// depend on which tests ran before them. The numbers are the worked example
// from the package docs: a 1,000,000 / 4,000,000 pool after a 100,000 swap.
func seedExamplePool() {
pools = avl.Tree{}
pools.Set(poolID(keyAAA, keyBBB), &pool{
keyA: keyAAA, keyB: keyBBB,
tokA: tokAAA, tokB: tokBBB,
resA: 1_100_000, resB: 3_637_356,
lp: exLP, lpLedger: exLedge,
lpKey: "gno.land/r/nym-moultest123/x/amm/v0.LPDEMO",
})
}
// ExampleRender pins the realm's home page.
func ExampleRender() {
seedExamplePool()
print(Render(""))
// Output:
// # Minimal AMM
//
// Constant product (`x*y=k`) with a 30 bps fee kept by the pool. Every position is a transferable GRC20 LP token. Reserves are stored, never read from balances, so sending tokens here directly does nothing and they cannot be recovered.
//
// | pool | reserves | LP token | supply | holders |
// |---|---|---|---|---|
// | [AAA/BBB](/r/nym-moultest123/x/amm/v0:gno.land/r/nym-moultest123/x/amm/v0.AAA~gno.land/r/nym-moultest123/x/amm/v0.BBB) | 1100000 AAA / 3637356 BBB | LPDEMO | 1000000 | 1 |
}
// ExampleRender_pool pins a single pool's detail page.
func ExampleRender_pool() {
seedExamplePool()
print(Render(poolID(keyAAA, keyBBB)))
// Output:
// # AAA / BBB
//
// - **AAA** reserve: 1100000 (`gno.land/r/nym-moultest123/x/amm/v0.AAA`)
// - **BBB** reserve: 3637356 (`gno.land/r/nym-moultest123/x/amm/v0.BBB`)
// - **LP token**: `gno.land/r/nym-moultest123/x/amm/v0.LPDEMO` (LPDEMO)
// - **LP shares**: 1000000 across 1 holder(s)
}
// ExampleRender_unknown pins the miss.
func ExampleRender_unknown() {
seedExamplePool()
print(Render("nope"))
// Output:
// # 404
//
// No pool `nope`.
}