Reference
Math
Stable Math

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

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 (opens in a new tab).

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

Swap Equations

Similar to determining the invariant, determining (out/in) amount given (in/out) amounts is also done iteratively. Both outGivenIn (opens in a new tab) and inGivenOut (opens in a new tab) use the same function, getTokenBalanceGivenInvariantAndAllOtherBalances (opens in a new tab).

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

© 2023 Balancer Labs