StableSwap Invariant
Install and import
npm install fintech-algorithmsimport { stableSwapQuote } from "fintech-algorithms/digital-assets-and-on-chain-finance/amm-pricing/stableswap-invariant";Signature
stableSwapQuote(balances, amountIn, amplification, feeRate, inputIndex, outputIndex)Curve's invariant: nearly constant-sum near the peg, constant-product away from it. The amplification coefficient sets where that transition happens, and it is what lets a stablecoin pool quote size with almost no slippage until it suddenly cannot.
Parameters
| Name | Type | Notes |
|---|---|---|
balances | number[] | Pool balances for every asset. |
amountIn | number | Input amount. min: 0 |
amplification | number | Amplification coefficient. Higher keeps the curve flat further from the peg — and makes depegging more violent when it comes. min: 0 |
feeRate | number | Fee as a fraction. min: 0 · max: 1 |
inputIndex | number | Index of the input asset in balances. min: 0 · integer: true |
outputIndex | number | Index of the output asset. min: 0 · integer: true |
Returns
{ amountOut, invariant, priceImpact, iterations, converged, … }
Output with the invariant D and whether the Newton solve converged — an unconverged quote must not be traded on.
Errors
- When the indices are equal or out of range, or the solve fails to converge — throws
Complexity: time O(assets × iterations),
space O(assets).
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
[1000, 1000]101000.0004Call
stableSwapQuote(balances, amountIn, amplification, feeRate, inputIndex, outputIndex)Returns
object with 18 fields: model, balancesBefore, balancesAfter, inputIndex, outputIndex, amountIn, grossAmountOut, feeAmountOut, …
{
"model": "stableswap",
"balancesBefore": [1000, 1000],
"balancesAfter": [1010, 990.004497337927],
"inputIndex": 0,
"outputIndex": 1,
"amountIn": 10,
"grossAmountOut": 9.999502463058,
"feeAmountOut": 0.003999800985,
"amountOut": 9.995502662073,
"executionPriceOutputPerInput": 0.999550266207,
"priceImpactFromPegFraction": 0.000049753694,
"DBefore": 2000,
"DAfterFeeRetained": 2000.004000000989,
"DIterations": 1
}Showing 14 of 18 fields.
Other exports
This module also exports
constantProductQuote, constantSumQuote, stableSwapInvariant, 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