PreSwap

Calculate swap amounts and check price impact before executing trades.

Quick Start

// Simulate swap before execution
const pool = await sdk.Pool.getPool(poolId)

const preSwapResult = await sdk.Swap.preswap({
  pool: pool,
  coinTypeA: pool.coinTypeA,
  coinTypeB: pool.coinTypeB,
  decimalsA: 9,  // SUI decimals
  decimalsB: 6,  // USDC decimals
  a2b: true,     // SUI -> USDC
  byAmountIn: true,
  amount: '1000000000',  // 1 SUI
  currentSqrtPrice: pool.current_sqrt_price
})

console.log({
  amountIn: preSwapResult.estimatedAmountIn,
  amountOut: preSwapResult.estimatedAmountOut,
  fee: preSwapResult.estimatedFeeAmount,
  priceAfter: preSwapResult.estimatedEndSqrtPrice
})

PreSwap Methods

Single Pool PreSwap

const params = {
  pool: pool,
  coinTypeA: '0x2::sui::SUI',
  coinTypeB: '0x...::usdc::USDC',
  decimalsA: 9,
  decimalsB: 6,
  a2b: true,           // Direction: A to B
  byAmountIn: true,    // Fix input amount
  amount: '1000000000',
  currentSqrtPrice: pool.current_sqrt_price
}

const result = await sdk.Swap.preswap(params)

if (result.isExceed) {
  console.log('Swap exceeds pool liquidity')
}

Multi-Pool PreSwap

Find best pool for swap:

const pools = ['0xpool1...', '0xpool2...', '0xpool3...']

const result = await sdk.Swap.preSwapWithMultiPool({
  poolAddresses: pools,
  coinTypeA: '0x2::sui::SUI',
  coinTypeB: '0x...::usdc::USDC',
  a2b: true,
  byAmountIn: true,
  amount: '1000000000'
})

console.log('Best pool:', result.poolAddress)
console.log('Best output:', result.estimatedAmountOut)

Calculate Price Impact

// Local calculation with tick data
const ticks = await sdk.Pool.fetchTicks({
  pool_id: poolId,
  coinTypeA: pool.coinTypeA,
  coinTypeB: pool.coinTypeB
})

const rateResult = sdk.Swap.calculateRates({
  currentPool: pool,
  coinTypeA: pool.coinTypeA,
  coinTypeB: pool.coinTypeB,
  decimalsA: 9,
  decimalsB: 6,
  a2b: true,
  byAmountIn: true,
  amount: new BN('1000000000'),
  swapTicks: ticks
})

console.log({
  priceImpact: rateResult.priceImpactPct.toFixed(2) + '%',
  isExceed: rateResult.isExceed,
  extraGas: rateResult.extraComputeLimit
})

Response Types

interface PreSwapResult {
  poolAddress: string
  estimatedAmountIn: string
  estimatedAmountOut: string
  estimatedEndSqrtPrice: string
  estimatedFeeAmount: string
  isExceed: boolean        // Exceeds liquidity
  amount: string
  aToB: boolean
  byAmountIn: boolean
}

interface CalculateRatesResult {
  estimatedAmountIn: BN
  estimatedAmountOut: BN
  estimatedEndSqrtPrice: BN
  estimatedFeeAmount: BN
  isExceed: boolean
  extraComputeLimit: number
  priceImpactPct: number
}

Usage Examples

Check Slippage

// 1. PreSwap to get expected output
const preSwap = await sdk.Swap.preswap(params)

// 2. Calculate minimum output with 1% slippage
const expectedOut = new BN(preSwap.estimatedAmountOut)
const minOutput = expectedOut.mul(new BN(99)).div(new BN(100))

console.log({
  expected: expectedOut.toString(),
  minimum: minOutput.toString()
})

Compare Pools

const pools = await sdk.Pool.getPools()
const suiUsdcPools = pools.filter(p => 
  p.coinTypeA.includes('sui') && 
  p.coinTypeB.includes('usdc')
)

// Test each pool
const results = []
for (const pool of suiUsdcPools) {
  const result = await sdk.Swap.preswap({
    pool,
    coinTypeA: pool.coinTypeA,
    coinTypeB: pool.coinTypeB,
    decimalsA: 9,
    decimalsB: 6,
    a2b: true,
    byAmountIn: true,
    amount: '1000000000',
    currentSqrtPrice: pool.current_sqrt_price
  })
  
  if (!result.isExceed) {
    results.push({
      pool: pool.poolAddress,
      output: result.estimatedAmountOut,
      fee: result.estimatedFeeAmount
    })
  }
}

// Find best rate
const best = results.sort((a, b) => 
  Number(b.output) - Number(a.output)
)[0]

Fix Output Amount

// Want exactly 1000 USDC output
const params = {
  pool,
  coinTypeA: pool.coinTypeA,
  coinTypeB: pool.coinTypeB,
  decimalsA: 9,
  decimalsB: 6,
  a2b: true,
  byAmountIn: false,    // Fix output
  amount: '1000000000', // 1000 USDC
  currentSqrtPrice: pool.current_sqrt_price
}

const result = await sdk.Swap.preswap(params)
console.log('Need SUI:', result.estimatedAmountIn)

Important Notes

  • PreSwap uses simulation for accurate results

  • Multi-pool automatically finds best execution

  • isExceed indicates insufficient liquidity

  • Always check price impact before large swaps

  • Results include fees in calculations

Last updated