Developers
Search…
⌃K

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

Python

There are also Python implementations in progress
  • stableMath.py There are known bugs in this implementation. This warning will be removed when they are fixed.

Invariant

Since the Stable Math equation is quite complex, determining the invariant,
DD
, is typically done iteratively. For an example of how to do this, please refer to this function.
Annxi+D=ADnn+Dn+1nnxiA \cdot n^n \cdot \sum{x_i} +D = A \cdot D \cdot n^n + { \frac{D^{n+1}}{{n}^{n}\cdot \prod{x_i} } }
Where:
  • nn
    is the number of tokens
  • xix_i
    is is balance of token
    ii
  • AA
    is the amplification parameter

Trade 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.

outGivenIn

y2+(DAnn+joutxjD)yDn+1An2njoutxj=0y^2 + (\frac{D}{An^n} + \sum_{j \neq out}{x'_j} - D)y -\frac{D^{n+1}}{An^{2n} \prod_{j \neq out}{x'_j}}= 0
aout=xoutxout=xoutya_{out} = x_{out} - x'_{out} = x_{out} - y
Where:
  • xix'_i
    is the ending amount of each token
  • aouta_{out}
    is the amount out
  • xoutx_{out}
    is the starting amount of the output token
  • y=xouty = x'_{out}
    is the ending amount of the output token
  • DD
    is the pool invariant
  • AA
    is the amplification parameter
  • nn
    is the number of tokens

inGivenOut

y2+(DAnn+jinxjD)yDn+1An2njinxj=0y^2 + (\frac{D}{An^n} + \sum_{j \neq in}{x'_j} - D)y -\frac{D^{n+1}}{An^{2n} \prod_{j \neq in}{x'_j}}= 0
ain=xinxin=yxina_{in} = x'_{in} - x_{in} = y-x_{in}
Where:
  • xix'_i
    is the ending amount of each token
  • aina_{in}
    is the amount in
  • xinx_{in}
    is the starting amount of the input token
  • y=xiny = x'_{in}
    is the ending amount of the input token
  • DD
    is the pool invariant
  • AA
    is the amplification parameter
  • nn
    is the number of tokens