Skip to main content
Using the Berancer SDK, you can execute swaps using the Smart Order Router (SOR) to find optimal swap paths. The SDK supports two types of swaps (see SwapKind):
  1. GivenIn - specify the exact input amount (you know how much you want to send)
  2. GivenOut - specify the exact output amount (you know how much you want to receive)
For more comprehensive swap examples, see the swap examples in the BEX SDK repository.

Understanding SwapKind

The SwapKind enum determines how your swap amount is interpreted:
  • GivenIn (SwapKind.GivenIn): You specify the exact amount of input tokens to swap. Use this when you know how much you want to spend, and the SDK will calculate how much output tokens you’ll receive. Example: “Swap exactly 100 USDC for as much BERA as possible.”
  • GivenOut (SwapKind.GivenOut): You specify the exact amount of output tokens you want to receive. Use this when you have a target amount, and the SDK will calculate how much input tokens you need to provide. Example: “Receive exactly 1 BERA, how much USDC do I need to swap?”

Requirements

Before executing swaps, ensure you have:
  • A wallet initialized with Ethers.js
  • Sufficient token balance for the swap (input token for GivenIn, calculated amount for GivenOut)
  • An approved spending allowance for the token (if required)
  • Access to an RPC endpoint

Example: exact input swap (GivenIn)

In this example, we use the Berancer SDK and Ethers.js to swap HONEY for USDC using the optimal swap path.
Below we breakdown the code example above.

Helper classes

The main helper classes we use from the SDK are:
  • BalancerApi - to query the Smart Order Router for optimized swap paths
  • Token and TokenAmount - to represent tokens and their amounts
  • Swap - to build swap queries and transactions
  • Slippage - to simplify creating limits with user defined slippage

Finding optimal swap paths

The SDK uses the Smart Order Router (SOR) to find the best swap path for a given token pair:
The SOR considers all available liquidity to find the path that provides the best execution price.

Simulation and price quoting

The Swap class provides a query method to simulate the swap and get current rates:
This helps you understand the expected output amount before executing the trade.

Building the transaction

The buildCall method prepares the transaction with the defined slippage protection and deadline:
The buildCall method returns an object containing:
  • to: The contract address to send the transaction to
  • callData: The encoded transaction data
  • value: Any native token value (usually 0 for token swaps)

Example: exact output swap (GivenOut)

When you need to receive an exact amount of output tokens, use SwapKind.GivenOut. The SOR will calculate the required input amount:

Key differences for GivenOut

  • The swapAmount parameter represents the desired output amount, not input
  • The queryOutput will contain the calculated input amount needed
  • You should approve slightly more than the calculated input amount to account for price movements

Multi-hop swaps

The Smart Order Router automatically finds multi-hop swap paths when direct pools don’t offer the best price. The SDK handles routing through intermediate tokens transparently. For advanced multi-hop swap configurations and batch swaps, see the Smart Order Router Guide and Batch Swap documentation.

Best practices

Slippage protection

Always set appropriate slippage limits based on:
  • Token pair volatility
  • Current market conditions
  • Expected trade size (larger trades may need higher slippage)

Deadline management

Set deadlines that account for network congestion:

Query before execution

Always query the swap before executing to:
  • Validate the swap is possible
  • Check expected output amounts
  • Estimate price impact
  • Identify any errors before sending a transaction

Error handling

Common errors and how to handle them:

Insufficient liquidity

Slippage exceeded

If the transaction reverts due to slippage:

Token approval issues

Ensure sufficient approval before swapping: