Development & Examples

This page has been deprecated. V1 documentation is partially maintained here

Development & Examples

Documentation for working with the @balancer-labs/sor package. For a description of the SOR and math, see this page.

The SOR package includes a primary SOR object with an SOR.getSwaps function and several helper functions for retireving Balancer pool data.

SOR Object

When instantiating a new SOR object we must pass five parameters to the constructor:

const SOR = new sor.SOR(Provider: JsonRpcProvider, GasPrice: BigNumber, MaxPools: number, ChainId: number, PoolsUrl: string)

Where:

Fetching Pool Data

The SOR requires an up to date list of pool data when calculating swap information and retrieves on-chain token balances for each pool. There are two available methods:

await SOR.fetchPools()

This will fetch all pools (using the URL in constructor) and on-chain balances. Returns true on success or false if there has been an error.

await SOR.fetchFilteredPairPools(TokenIn, TokenOut)

A subset of valid pools for token pair, TokenIn/TokenOut, is found and on-chain balances retrieved. Returns true on success or false if there has been an error. This can be a quicker alternative to using fetchPools but will need to be called for every token pair of interest.

Processing Swaps

async SOR.getSwaps(...)

The getSwaps function will use the pool data and the trade parameters to perform an optimization for the best price execution. It returns swap information and the total that can then be used to execute the swaps on-chain.

tokenIn - string: address of token in

tokenOut - string: address of token out

swapType - string: either swapExactIn or swapExactOut

swapAmount - BigNumber: amount to be traded, in Wei

async SOR.setCostOutputToken(tokenOut)

The cost of the output token in ETH multiplied by the gas cost to perform the swap. This is used to determine whether the lower price obtained through including an additional pool in the transaction outweigh the gas costs. This function can be called before getSwaps to retrieve and cache the cost which will then be used in any getSwap calls using that token. Defaults to 0 for a token if not previously set.

Notice that tokenOut is tokenOut if swapType == 'swapExactIn' and tokenIn if swapType == 'swapExactOut.

Example - Using SOR To Get List Of Swaps

Below is an example snippet that uses the SOR to return a final list of swaps and the expected output. The swaps returned can then be passed on to the exchange proxy or otherwise used to atomically execute the trades.

Example - SOR & ExchangeProxy

Balancer labs makes use of a ExchangeProxy contract that allows users to batch execute swaps recommended by the SOR. The following example shows how SOR and ExchangeProxy can be used together to execute on-chain trades.

Last updated