Removing Liquidity

This guide shows how to remove liquidity from a V2.2 pool using the SDKs, and Viem. In this example, we will be removing liquidity from a LBPair of USDC/USDC.e/1bps

1. Required imports and constants for this guide

Imports

import { ChainId, Token } from '@traderjoe-xyz/sdk-core'
import { PairV2, LB_ROUTER_V22_ADDRESS, jsonAbis, } from '@traderjoe-xyz/sdk-v2'
import { getContract, createPublicClient, createWalletClient, http, BaseError, ContractFunctionRevertedError } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { avalanche } from 'viem/chains'
import { config } from 'dotenv';

Constants: chain and wallet

config();
const privateKey = process.env.PRIVATE_KEY;
const { LBRouterV22ABI, LBPairV21ABI } = jsonAbis
const CHAIN_ID = ChainId.AVALANCHE
const router = LB_ROUTER_V22_ADDRESS[CHAIN_ID]
const account = privateKeyToAccount(`0x${privateKey}`)

Note that in your project, you most likely will not hardcode the private key at any time. You would be using libraries like web3react or wagmi to connect to a wallet, sign messages, interact with contracts, and get the values for PROVIDER, SIGNER and ACCOUNT

Constants: tokens and LBPair bin step

2. Create Viem clients

3. Getting data

LBPair and active bin

Liquidity positions

Use the below code to fetch your positions directly from chain. You need all the binIds where you have liquidity and the amount of liquidity in each bin.

Please take note, that we aren't fetching ERC20 token amounts underlying for this example. This results in using parameters amountXmin and amountYmin equal to zero. Calculating them would require additionally:

  1. Fetch tokenSupply of all owned bins

  2. Fetch reserves of all owned bins

  3. Calculate reserves owned by user (ownedReserves * liquidityOwned / totalSupply)

  4. Applying desired slippage to above.

This process will become easier, when public API is opened.

4. Grant LBRouter access to your LBTokens

5. Set removeLiquidity parameters

Note that removeLiquidityParams will look different for the removeLiquidityAVAX method. Please refer to this link for specific details.

6. Execute removeLiquidity contract call

Last updated