npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@berachain-foundation/berancer-sdk

v0.33.2

Published

SDK for interacting with the Balancer protocol

Downloads

77

Readme

SDK

WIP SDK for Balancer Protocol. Interfaces may have frequent breaking changes until a stable release.

Local Setup

pnpm install

Requirements

  • fetch

Polyfill

If your platform does not support one of the required features, it is also possible to import a polyfill.

Testing

pnpm test

Testing runs against a local anvil fork and requires the following RPC URL to be configured in your .env file:

ETHEREUM_RPC_URL
POLYGON_RPC_URL
FANTOM_RPC_URL
SEPOLIA_RPC_URL

Anvil Client

To download and install the anvil client, run the following commands (MacOS):

  • curl -L https://foundry.paradigm.xyz | bash
  • brew install libusb
  • source /Users/$(whoami)/.zshenv
  • foundryup

Documentation

Installation

The Balancer SDK is a Typescript/Javascript library for interfacing with the Balancer protocol and can be installed with:

pnpm add @balancer-labs/sdk

API

AddLiquidity

This class provides functionality to:

  • Perform on-chain queries to see the result of an addLiqudity operation
  • Build an addLiquidity transaction, with slippage, for a consumer to submit
  • Supported add types: SingleToken, Unbalanced, Proportional
  • Supports Balancer V2 & V3

Example

See the addLiqudity example.

Constructor

const addLiquidity = new AddLiquidity();

Methods

query

Simulate addLiquidity operation by using an onchain call.

query(
  input: AddLiquidityInput, 
  poolState: PoolState
): Promise<AddLiquidityQueryOutput>

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | input | AddLiquidityInput | User defined inputs | | poolState | PoolState | Current state of pool that liqudity is being added to |

Returns

Promise<AddLiquidityQueryOutput>

AddLiquidityQueryOutput - Data that can be passed to buildCall. Includes updated bptOut amount.


buildCall

Builds the addLiquidity transaction using user defined slippage.

buildCall(input: AddLiquidityBuildCallInput): AddLiquidityBuildCallOutput

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | input | AddLiquidityBuildCallInput | Parameters required to build the call including user defined slippage |

Returns

AddLiquidityBuildCallOutput

AddLiquidityBuildCallOutput - Encoded call data for addLiquidity that user can submit.


RemoveLiquidity

This class provides functionality to:

  • Perform on-chain queries to see the result of an removeLiqudity operation
  • Build a removeLiquidity transaction, with slippage, for a consumer to submit
  • Supported remove types: Unbalanced, SingleTokenExactOutInput, SingleTokenExactInInput, Proportional
  • Supports Balancer V2 & V3

Example

See the removeLiqudity example.

Constructor

const removeLiquidity = new RemoveLiquidity();

Methods

query

Simulate removeLiquidity operation by using an onchain call.

query(
  input: RemoveLiquidityInput,
  poolState: PoolState,
): Promise<RemoveLiquidityQueryOutput>

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | input | RemoveLiquidityInput | User defined inputs | | poolState | PoolState | Current state of pool that liqudity is being removed from |

Returns

Promise<RemoveLiquidityQueryOutput>

RemoveLiquidityQueryOutput - Data that can be passed to buildCall. Includes updated amountsOut amount.


queryRemoveLiquidityRecovery

Calculates proportional exit using pool state. Note - this does not do an onchain query.

queryRemoveLiquidityRecovery(
  input: RemoveLiquidityRecoveryInput,
  poolState: PoolState,
): Promise<RemoveLiquidityQueryOutput> 

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | input | RemoveLiquidityRecoveryInput | User defined inputs | | poolState | PoolState | Current state of pool that liqudity is being removed from |

Returns

Promise<RemoveLiquidityQueryOutput>

RemoveLiquidityQueryOutput - Data that can be passed to buildCall. Includes updated amountsOut amount.


buildCall

Builds the removeLiquidity transaction using user defined slippage.

buildCall(
  input: RemoveLiquidityBuildCallInput,
): RemoveLiquidityBuildCallOutput

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | input | RemoveLiquidityBuildCallInput | Input with user defined slippage |

Returns

RemoveLiquidityBuildCallOutput

RemoveLiquidityBuildCallOutput - Encoded call data for addLiquidity that user can submit.


Swap

This class provides functionality to:

  • Perform on-chain queries to see the result of a Swap operation
  • Build a Swap transaction, with slippage, for a consumer to submit
  • Supports Balancer V2 & V3

Example

See the swap example.

Constructor

const swap = new Swap(swapInput: SwapInput);

| Name | Type | Description | | ------------- | ------------- | ------------ | | swapInput | SwapInput | Swap input including path information. |

Note: SwapInput data is normally returned from an API SOR query but may be constructed manually.

Methods

query

Gets up to date swap result by querying onchain.

query(
  rpcUrl?: string,
  block?: bigint,
): Promise<ExactInQueryOutput | ExactOutQueryOutput> 

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | rpcUrl (optional) | string | RPC URL, e.g. Infura/Alchemy | | block (optional) | bigint | Block no to perform the query |

Returns

Promise<ExactInQueryOutput | ExactOutQueryOutput>

ExactInQueryOutput ExactOutQueryOutput

The upated return for the given swap, either expectedAmountOut or expectedAmountIn depending on swap kind.


buildCall

Builds the swap transaction using user defined slippage.

buildCall(
  input: SwapBuildCallInput,
): SwapBuildOutputExactIn | SwapBuildOutputExactOut

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | input | SwapBuildCallInput | Input with user defined slippage |

Returns

SwapBuildOutputExactIn | SwapBuildOutputExactOut

SwapBuildOutputExactIn SwapBuildOutputExactOut

RemoveLiquidityBuildCallOutput - Encoded call data for swap that user can submit. Includes minAmountOut or maxAmountIn depending on swap kind.


quote

Gives the combined return amount for all paths. Note - this always uses the original path amounts provided in constructor and does not get updated.

public get quote(): TokenAmount

Returns

TokenAmount

TokenAmount - Gives the combined return amount for all paths (output amount for givenIn, input amount for givenOut).


inputAmount

public get inputAmount(): TokenAmount

Returns

TokenAmount

TokenAmount - Gives the combined input amount for all paths.


outputAmount

public get outputAmount(): TokenAmount

Returns

TokenAmount

TokenAmount - Gives the combined output amount for all paths.


queryCallData

public queryCallData(): string

Returns

string

Encoded query data for swap that a user can call to get an updated amount.


PriceImpact

This class provides helper functions to calculate Price Impact for add/remove/swap actions.

  • Supports Balancer V2 & V3

Example

See the price impact example.

Methods

addLiquiditySingleToken

Calculate price impact on add liquidity single token operations.

addLiquiditySingleToken(
  input: AddLiquiditySingleTokenInput,
  poolState: PoolState,
): Promise<PriceImpactAmount> 

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | input | AddLiquiditySingleTokenInput | Same input used in the corresponding add liquidity operation | | poolState | PoolState | Current state of pool that liqudity is being added to |

Returns

Promise<PriceImpactAmount>

PriceImpactAmount - Price impact for operation.


addLiquidityUnbalanced

Calculate price impact on add liquidity unbalanced operations.

addLiquidityUnbalanced = async (
    input: AddLiquidityUnbalancedInput,
    poolState: PoolState,
): Promise<PriceImpactAmount>

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | input | AddLiquidityUnbalancedInput | Same input used in the corresponding add liquidity operation | | poolState | PoolState | Current state of pool that liqudity is being added to |

Returns

Promise<PriceImpactAmount>

PriceImpactAmount - Price impact for operation.


addLiquidityNested

Calculate price impact on add liquidity nested token operations.

addLiquidityNested = async (
  input: AddLiquidityNestedInput,
  nestedPoolState: NestedPoolState,
): Promise<PriceImpactAmount>

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | input | AddLiquidityNestedInput | Same input used in the corresponding add liquidity operation | | nestedPoolState | NestedPoolState | Current state of nested pools |

Returns

Promise<PriceImpactAmount>

PriceImpactAmount - Price impact for operation.


removeLiquidity

Calculate price impact on remove liquidity operations.

removeLiquidity = async (
  input:
      | RemoveLiquiditySingleTokenExactInInput
      | RemoveLiquidityUnbalancedInput,
  poolState: PoolState,
): Promise<PriceImpactAmount>

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | input | RemoveLiquiditySingleTokenExactInInput | Same input used in the corresponding remove liquidity operation | | input | RemoveLiquidityUnbalancedInput | Same input used in the corresponding remove liquidity operation | | poolState | PoolState | Current state of pool that liqudity is being removed from |

Returns

Promise<PriceImpactAmount>

PriceImpactAmount - Price impact for operation.


removeLiquidityNested

Calculate price impact on remove liquidity single token nested operations.

removeLiquidityNested = async (
  input: RemoveLiquidityNestedSingleTokenInput,
  nestedPoolState: NestedPoolState,
): Promise<PriceImpactAmount>

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | input | RemoveLiquidityNestedSingleTokenInput | Same input used in the corresponding remove liquidity operation | | nestedPoolState | NestedPoolState | Current state of nested pools |

Returns

Promise<PriceImpactAmount>

PriceImpactAmount - Price impact for operation.


swap

Calculate price impact on swap operations.

swap = async (
  swapInput: SwapInput,
  rpcUrl?: string,
  block?: bigint,
): Promise<PriceImpactAmount>

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | swapInput | SwapInput | Swap input including path information. | | rpcUrl (optional) | string | RPC URL, e.g. Infura/Alchemy | | block (optional) | bigint | Block no to perform the query |

Note: SwapInput data is normally returned from an API SOR query but may be constructed manually.

Returns

Promise<PriceImpactAmount>

PriceImpactAmount - Price impact for operation.


BalancerApi

This class provides helper functions for interacting with the Balancer API.

Example

See the examples for add/remove/swap linked above as these use BalancerApi to fetch required data.

Constructor

const balancerApi = new BalancerApi(balancerApiUrl: string, chainId: ChainId);

| Name | Type | Description | | ------------- | ------------- | ------------ | | balancerApiUrl | string | Url of Balancer API | | chainId | ChainId | Chain that will be queried |

Methods

pools.fetchPoolState

Finds state of given pool.

pools.fetchPoolState(id: string): Promise<PoolState> 

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | id | string | ID of pool, V2=poolId, V3=address |

Returns

Promise<PoolState>

PoolState - State of given pool.


pools.fetchPoolStateWithBalances

Finds state of given pool including token balances and pool shares.

fetchPoolStateWithBalances(
  id: string,
): Promise<PoolStateWithBalances> 

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | id | string | ID of pool, V2=poolId, V3=address |

Returns

Promise<PoolStateWithBalances>

PoolStateWithBalances - State of given pool including token balances and pool shares.


nestedPools.fetchPoolState

Finds state of a set of nested pools.

fetchNestedPoolState(id: string): Promise<NestedPoolState>

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | id | string | ID of pool, V2=poolId, V3=address |

Returns

Promise<NestedPoolState>

NestedPoolState - state of a set of nested pools.


sorSwapPaths.fetchSorSwapPaths

Finds optimised swap paths for a given swap config.

fetchSorSwapPaths(sorInput: SorInput): Promise<Path[]>

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | sorInput | SorInput | Swap configs |

Returns

Promise<Path[]>

Path[] - optimised swap paths for the given swap.


Utils

Helper functions.

calculateProportionalAmounts

Given pool balances (including BPT) and a reference token amount, it calculates all other amounts proportional to the reference amount.

Example

See the price impact example.

calculateProportionalAmounts(
  pool: {
    address: Address;
    totalShares: HumanAmount;
    tokens: { 
      address: Address; 
      balance: HumanAmount; 
      decimals: number 
    }[];
  },
  referenceAmount: InputAmount,
): {
  tokenAmounts: InputAmount[];
  bptAmount: InputAmount;
}

Parameters

| Name | Type | Description | | ------------- | ------------- | ------------ | | pool | See above | Pool state | | referenceAmount | InputAmount | Ref token amount |

Returns

{
  tokenAmounts: InputAmount[];
  bptAmount: InputAmount;
}

Amounts proportional to the reference amount.