Constant-Sum AMM
Install and import#
npm install fintech-algorithmsimport { 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#
| Name | Type | Notes |
|---|---|---|
reserve0 | number | Reserve of the input token. min: 0 |
reserve1 | number | Reserve of the output token. min: 0 |
amount0In | number | Input amount. min: 0 |
feeRate | number | Fee 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#
10001000100.003Call#
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#
Calculation flow#
Diagram
flowchart LR
A["Normalize balances, amount, and token order"] --> B["Select Constant-Sum AMM contract"]
B --> C["Apply declared fee convention"]
C --> D["Solve invariant or piecewise position"]
D --> E{"Valid state?"}
E -- "No" --> F["Reject: exhaustion, bounds, or convergence"]
E -- "Yes" --> G["Update actual balances"]
G --> H["Compute spot, execution, and diagnostics"]
H --> I["Report exclusions and state label"]
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.
References#
- Uniswap v2 Core whitepaper — Uniswap
- StableSwap whitepaper — Curve Finance / Michael Egorov
- Balancer whitepaper — Balancer Labs
- Uniswap v3 Core whitepaper — Uniswap
- Source discipline