Calculate Swap Rates

Overview

calculateRates is a method used to calculate and estimate swap results before executing an actual transaction. This method helps determine input/output token amounts, transaction fees, and other important parameters without spending gas.

Method Signature

sdk.Swap.calculateRates(params: CalculateRatesParams): CalculateRatesResult

Parameters

Parameter
Type
Description

decimalsA

number

Number of decimals for token A

decimalsB

number

Number of decimals for token B

a2b

boolean

Swap direction. true for A→B, false for B→A

byAmountIn

boolean

Calculation mode. true to specify input amount, false to specify output amount

amount

BN

Amount to swap (in smallest unit). Input amount if byAmountIn=true, output amount if byAmountIn=false

swapTicks

Tick[]

Array of tick data from the pool

currentPool

Pool

Current pool object containing pool state

Return Values

Field
Type
Description

estimatedAmountIn

BN

Estimated amount of tokens to be swapped in

estimatedAmountOut

BN

Estimated amount of tokens to be received

estimatedEndSqrtPrice

BN

Estimated sqrt price after swap

estimatedFeeAmount

BN

Estimated fee amount for the swap

isExceed

boolean

Whether the swap exceeds pool liquidity

extraComputeLimit

number

Additional compute units needed for transaction

amount

BN

The input amount used for calculation

aToB

boolean

Swap direction used in calculation

byAmountIn

boolean

Calculation mode used

Examples

Example 1: Calculate swap from token B to token A by specifying input amount

Example 2: Calculate swap from token A to token B by specifying output amount

Example 3: Check for large swap impact

Important Notes

  1. Amount Units: All amounts must be in the smallest unit (considering decimals). For example, 1 token with 6 decimals = 1000000.

  2. Tick Data: Always fetch fresh tick data before calculating rates to ensure accurate results:

  3. Gas Estimation: Use extraComputeLimit to adjust transaction gas limits when executing the actual swap:

  4. Slippage Protection: The calculated amounts are estimates. Always implement slippage tolerance when executing actual swaps:

  5. Error Handling: Always check isExceed before executing swaps to avoid failed transactions due to insufficient liquidity.

Last updated