fintech-algorithms

Constant-Sum AMM

Install and import

bash
npm install fintech-algorithms
ts
import { constantSumQuote } from "fintech-algorithms/digital-assets-and-on-chain-finance/amm-pricing/constant-sum-amm";

Signature

constantSumQuote(reserve0, reserve1, amount0In, feeRate)

The x + y = k curve: zero slippage, and the pool can be fully drained of one asset. Never used alone for that reason — it is the component that makes stableswap flat near the peg.

Parameters

NameTypeNotes
reserve0numberReserve of the input token.
min: 0
reserve1numberReserve of the output token.
min: 0
amount0InnumberInput amount.
min: 0
feeRatenumberFee as a fraction.
min: 0 · max: 1

Returns

{ amountOut, depleted, effectivePrice, … }

Output amount with an explicit depletion flag for the case the curve permits and reality does not.

Errors

  • When the output reserve cannot cover the trade — reported as depleted rather than thrown

Complexity: time O(1), space O(1).

Worked example

executed Captured by running this function on the input its own test provides. Real output of real code — but not asserted against a published figure.

Input

reserve0
1000
reserve1
1000
amount0In
10
feeRate
0.003

Call

constantSumQuote(reserve0, reserve1, amount0In, feeRate)

Returns

object with 16 fields: model, reserve0Before, reserve1Before, amount0In, effectiveAmount0In, feeAmount0, amount1Out, reserve0After, …

{
  "model": "constant-sum",
  "reserve0Before": 1000,
  "reserve1Before": 1000,
  "amount0In": 10,
  "effectiveAmount0In": 9.97,
  "feeAmount0": 0.03,
  "amount1Out": 9.97,
  "reserve0After": 1010,
  "reserve1After": 990.03,
  "invariantBefore": 2000,
  "invariantAfter": 2000.03,
  "spotPriceBeforeToken1PerToken0": 1,
  "executionPriceToken1PerToken0": 0.997,
  "remainingExactFillCapacityToken0": 993.009027081244
}

Showing 14 of 16 fields.

Other exports

This module also exports constantProductQuote, stableSwapInvariant, stableSwapQuote, weightedProductQuote, concentratedLiquidityPosition. Every module additionally exports run as an alias of its primary function, and a meta object carrying its catalog id, domain, family, shape and article URL.

Diagrams

Constant-Sum AMM — system map

How it works

This page states the contract — how to call it correctly. The article explains the concept: why it works, and where it breaks.

Read the article →

References

  • Uniswap v2 Core whitepaper — Uniswap
  • StableSwap whitepaper — Curve Finance / Michael Egorov
  • Balancer whitepaper — Balancer Labs
  • Uniswap v3 Core whitepaper — Uniswap
  • Source discipline