swap

Swap from one coin to another one with specific pools.

Signature

swap(options: SwapOptions): Promise<Transaction>

Params

interface SwapOptions {
  routes: Array<{
    // Pool object ID
    pool: string;
    // Swap from coinA to coinB
    a2b: boolean;
    // computed next tick index
    nextTickIndex: number;
  }>;
  // Coin A address
  coinTypeA: string;
  // Coin B address
  coinTypeB: string;
  // User's wallet address
  address: string;
  // Amount of coinA
  amountA: string | number;
  // Amount of coinB
  amountB: string | number;
  // When `true`, amountA is input by user. 
  // When `false`, amountB is input by user. 
  amountSpecifiedIsInput: boolean;
  // Acceptable wasted amount percentage. Range: [0, 100)
  slippage: string | number;
  // Expires timeout(ms), defaults 60_000
  deadline?: number;
  // Custom transaction handler
  txb?: Transaction;
}

Examples

const turbosSdk = new TurbosSdk(Network.testnet, {
  url: 'https://fullnode.testnet.sui.io',
});
//const signer = turbosSdk.account.getKeypairFromMnemonics("your mnemonic");
const signer = services.turbosBaseService.signer;
const poolId = '0x328572f9d3c99bdb0a2da46fa61ef7917e1d35e67ec9472d412aa82b4a5222b2';
const pool = await turbosSdk.pool.getPool(poolId);
const coinADecimals = 9;
const amountA = 0.01 * 10 ** coinADecimals;
const preSwapResult = await turbosSdk.trade.computeSwapResultV2({
  pools: [
    {
      pool: poolId,
      a2b: true,
      amountSpecified: amountA,
    },
  ],
  amountSpecifiedIsInput: true,
  tickStep: 100,
  address: signer.toSuiAddress(),
});
console.log(preSwapResult);

const txb = await turbosSdk.trade.swap({
  routes: [
    {
      pool: poolId,
      a2b: true,
      nextTickIndex: turbosSdk.math.bitsToNumber(
        preSwapResult[0]!.tick_current_index.bits,
      ),
    },
  ],
  coinTypeA: pool.types[0],
  coinTypeB: pool.types[1],
  address: signer.toSuiAddress(),
  amountA: amountA.toString(),
  amountB: preSwapResult[0]!.amount_b,
  amountSpecifiedIsInput: true,
  slippage: '0.1',
});
const result = await turbosSdk.provider.signAndExecuteTransaction({
  transaction: txb,
  signer,
});
console.log(result);

Last updated