Constant-Product AMM
Install and import
npm install fintech-algorithmsimport { constantProductQuote } from "fintech-algorithms/digital-assets-and-on-chain-finance/amm-pricing/constant-product-amm";Signature
constantProductQuote(reserve0, reserve1, amount0In, feeRate)The x · y = k curve behind Uniswap v2. Price is set by the reserve ratio, so every trade moves it — and the slippage a trade suffers is a deterministic function of its size relative to the pool.
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, taken from the input before the swap. min: 0 · max: 1 |
Returns
{ amountOut, priceImpact, effectivePrice, spotPriceAfter, … }
Output amount with the price impact and the post-trade spot price.
Errors
- When a reserve is zero, or feeRate falls outside 0…1 — throws
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
constantProductQuote(reserve0, reserve1, amount0In, feeRate)Returns
object with 16 fields: model, reserve0Before, reserve1Before, amount0In, effectiveAmount0In, feeAmount0, amount1Out, reserve0After, …
{
"model": "constant-product",
"reserve0Before": 1000,
"reserve1Before": 1000,
"amount0In": 10,
"effectiveAmount0In": 9.97,
"feeAmount0": 0.03,
"amount1Out": 9.871580343971,
"reserve0After": 1010,
"reserve1After": 990.128419656029,
"invariantBefore": 1000000,
"invariantAfter": 1000029.7038525896,
"spotPriceBeforeToken1PerToken0": 1,
"spotPriceAfterToken1PerToken0": 0.980325167976,
"executionPriceToken1PerToken0": 0.987158034397
}Showing 14 of 16 fields.
Other exports
This module also exports
constantSumQuote, 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
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