Execute Swap

Perform token swaps through DLMM pairs using the bin-based liquidity system. Swaps traverse through multiple bins as needed to fill the order.

Prerequisites

  • Valid sender address with tokens

  • Pair address for trading

  • Sufficient balance of input token

  • Gas for transaction execution

Basic Swap

const pair = await sdk.Pair.getPair(pairAddress);

// Swap 1 SUI for USDC
const tx = await sdk.Swap.prepareSwap(pair, {
  amount: 1000000000n,  // 1 SUI (9 decimals)
  xtoy: true,           // SUI (X) to USDC (Y)
  recipient: userAddress // Optional, defaults to sender
});

await sdk.fullClient.signAndExecuteTransaction({
  transaction: tx,
  signer: keypair
});

Swap Parameters

interface PrepareSwapParams {
  amount: bigint;        // Input token amount
  xtoy: boolean;         // Direction: true = X→Y, false = Y→X
  recipient?: string;    // Receiver address (optional)
}

Swap Directions

X to Y Swap

// Token X → Token Y
const swapXtoY = await sdk.Swap.prepareSwap(pair, {
  amount: inputAmount,
  xtoy: true
});

Y to X Swap

// Token Y → Token X
const swapYtoX = await sdk.Swap.prepareSwap(pair, {
  amount: inputAmount,
  xtoy: false
});

Understanding Token Order

// Check pair token order
console.log("Token X:", pair.tokenXType); // e.g., "0x2::sui::SUI"
console.log("Token Y:", pair.tokenYType); // e.g., "0x...::usdc::USDC"

// X is always the "smaller" address
// SDK handles this automatically

Complete Swap Example

async function executeSwap(
  pairAddress: string,
  inputAmount: bigint,
  isXtoY: boolean
) {
  try {
    // Get pair info
    const pair = await sdk.Pair.getPair(pairAddress);
    
    // Prepare swap transaction
    const tx = await sdk.Swap.prepareSwap(pair, {
      amount: inputAmount,
      xtoy: isXtoY,
    });
    
    // Execute
    const result = await sdk.fullClient.signAndExecuteTransaction({
      transaction: tx,
      signer: keypair
    });
    
    console.log("Swap completed:", result.digest);
    return result;
    
  } catch (error) {
    console.error("Swap failed:", error);
    throw error;
  }
}

Swap with Custom Recipient

// Send output to different address
const tx = await sdk.Swap.prepareSwap(pair, {
  amount: swapAmount,
  xtoy: true,
  recipient: "0x456..." // Different wallet
});

How Swaps Work

  1. Start at active bin: Current trading price

  2. Consume liquidity: Use available reserves

  3. Move to next bin: If more needed

  4. Continue until filled: Or liquidity exhausted

Before: [Bin-2][Bin-1][Active][Bin+1][Bin+2]
Swap:    →→→→→→→→→→→→→→→→→→→→→→→
After:  [Bin-2][Bin-1][Empty][Active][Bin+2]

Common Patterns

Swap Exact Input

// Know input amount, accept any output
const exactInput = 1000000000n; // 1 token

const tx = await sdk.Swap.prepareSwap(pair, {
  amount: exactInput,
  xtoy: true
});

Check Balance First

// Verify sufficient balance
const balance = await getTokenBalance(userAddress, tokenType);

if (balance < swapAmount) {
  throw new Error("Insufficient balance");
}

const tx = await sdk.Swap.prepareSwap(pair, {
  amount: swapAmount,
  xtoy: true
});

Error Handling

try {
  const tx = await sdk.Swap.prepareSwap(pair, params);
  // Execute transaction
} catch (error) {
  if (error.message.includes("Invalid sender")) {
    console.error("Set sender address first");
  } else if (error.message.includes("Insufficient")) {
    console.error("Not enough input tokens");
  }
}

Gas Optimization

  • Swaps through fewer bins cost less gas

  • Large swaps may traverse many bins

  • Consider splitting very large swaps

  • Active bin swaps are most efficient

Last updated