Weighted Math

Overview

Weighted Math is designed to allow for swaps between any assets whether or not they have any price correlation. Prices are determined by the pool balances, pool weights, and amounts of the tokens that are being swapped.

Balancer's Weighted Math equation is a generalization of the constant product formula, accounting for cases with tokens as well as weightings that are not an even 50/50 split.

For more formulas and derivations of the below formulas, please refer to the Balancer Whitepaperopen in new window.

Implementations

TypeScript

Developers can use the TypeScript math implementations used by the Smart Order router

Python

There are also Python implementations in progress

Invariant

The value function is defined as:

Where

  • ranges over the tokens in the pool
  • is the balance of the token in the pool
  • ‚Äčis the normalized weight of the tokens, such that the sum of all normalized weights is 1.

Spot Price

Each pair of tokens in a pool has a spot price defined entirely by the weights and balances of just that pair of tokens. The spot price between any two tokens,, or in short , is the the ratio of the token balances normalized by their weights:

  • is the balance of token , the token being sold by the swapper which is going into the pool
  • is the balance of token , the token being bought by the swapper which is going out of the pool
  • is the weight of token
  • is the weight of token

Spot Price with Swap Fees

When we consider swap fees, we do exactly the same calculations as without fees, but using instead of since fees are taken out of the input amount. The equation then becomes:

Swap Equations

outGivenIn

When a user sends tokens to get tokens , all other token balances remain the same. Therefore, if we define and as the amount of tokens and exchanged, and since the value function must be constant before and after the swap, we can calculate the amount a users gets when sending .

Info

If you're computing this value yourself, remember that the pool collects swap fees as a percentage of the input token. In the equation above, is the amount that the pool actually swaps into the output token, not the amount sent by a swapper, . To calculate through, we must compute:

inGivenOut

It is also very useful for swappers to know how much they need to send of the input token to get a desired amount of output token :