Stable Math
Overview
Stable Math is designed to allow for swaps between any assets that have the same price, or are "pegged" to the same asset. The most common examples are stablecoins that track US Dollars (DAI, USDT, USDC), and assets that track the price of Bitcoin (WBTC, renBTC, sBTC). Prices are determined by the pool balances, the amplification parameter, and amounts of the tokens that are being swapped.
Implementations
TypeScript
Developers can use the TypeScript math implementations used by the Smart Order router (equivalent v2 reference).
Invariant
Since the Stable Math equation is quite complex, determining the invariant,
Where:
is the number of tokens is is balance of token is the amplification parameter
Swap Equations
Similar to determining the invariant, determining (out/in) amount given (in/out) amounts is also done iteratively. Both outGivenIn and inGivenOut use the same function, getTokenBalanceGivenInvariantAndAllOtherBalances. Note that these are v2 references; we don't use TS in this way in v3, and computeBalance
is equivalent to getTokenBalanceGivenInvariantAndAllOtherBalances
in v2. Otherwise, they are mathematically equivalent.
outGivenIn
Where:
is the ending amount of each token is the amount out is the starting amount of the output token is the ending amount of the output token is the pool invariant is the amplification parameter is the number of tokens
inGivenOut
Where:
is the ending amount of each token is the amount in is the starting amount of the input token is the ending amount of the input token is the pool invariant is the amplification parameter is the number of tokens