Path: balancer_math.py file discussed in this article.
This file uses balancer_constants.py as an imported file.
Important notice: all swaps in Balancer pools are occurring between two tokens. It means, that if the pool has 8 tokens, all trades are executing between different trading pairs (token1 vs token2, token1 vs token3, etc).
When the user sends tokens to the pool for swapping them to other tokens the "i" label refers to "tokens in", or to tokens that were "sold" in this swap. The "o" refers to "tokens out", which means that these tokens were "bought" by the user.
The Balancer AMM math from Whitepaper doesn't contain a swap fee/exit fee, but Solidity and Python implementations contain it. The fee is set to zero in the constants (as in the smart contracts)
All methods except spot price return the class BalancerMathResult
@dataclass
class BalancerMathResult:
# The relevant result of the operation
result: Decimal
# Amount of tokens the pool keeps in the token going into the pool (for join and joinswaps) or out the pool (exits)
fee: Decimal
calc_sport_price
This function returns the spot price based on the ratio of token balances in the pool taking into account their weights:
SPio=WiB0⋅BiWo⋅1−swapfee1
def calc_spot_price(
token_balance_in: Decimal,
token_weight_in: Decimal,
token_balance_out: Decimal,
token_weight_out: Decimal,
swap_fee: Decimal):
numer = token_balance_in / token_weight_in
denom = token_balance_out / token_weight_out
ratio = numer / denom
scale = 1 / (1 - swap_fee)
return ratio * scale
Note, that spot price is the "price without slippage" since the amount of asset for trading is assumed to be very low (lim -> 0).
calc_out_given_in
This function is the function for computing the result of swapping assets.
A - amount of tokens (in and out)
B - token balance in the pool (for "token in" and "token out")
W - weights of these tokens inside the pool (for "token in" and "token out")
A0=B0⋅1–(Bi+Ai⋅(1−swapfee)Bi)WoWi
calc_in_given_out
This formula is used for the calculation of how many tokens "in" you need to send to the pool to receive the desired number of tokens "out" back.
Ai=Bi⋅((Bo−AoBo)WiWo−1)⋅1−swapfee1
calc_pool_out_given_single_in
This function returns the number of pool shares (or BPT tokens) issued as a result of single-side liquidity provision (join a pool with a specified number of "token in" asset).
Bt is a pool balance, and At is the amount of this token deposited to the pool.
This is another single-side liquidity provision function. It returns the number of At (token in) that is necessary to supply for minting a specified number of Pool Shares.