Resources

Sui Example#

Create a Token Helper (Optional)#

// Common tokens on Sui mainnet
export const TOKENS = {
    SUI: "0x2::sui::SUI",
    USDC: "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC"
} as const;

Create a Swap#

// swap.ts
import { client } from './DexClient';
import { TOKENS } from './Tokens'; // Optional, if you created the token helper
/**
Example: Execute a swap from SUI to USDC
*/
async function executeSwap() {
  try {
    if (!process.env.SUI_PRIVATE_KEY) {
      throw new Error('Missing SUI_PRIVATE_KEY in .env file');
    }
    // First, get token information using a quote
    console.log("Getting token information...");
    const fromTokenAddress = TOKENS.SUI; // Or use directly: "0x2::sui::SUI"
    const toTokenAddress = TOKENS.USDC; // Or use directly: "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC"

    const quote = await client.dex.getQuote({
        chainId: '784', // Sui chain ID
        fromTokenAddress,
        toTokenAddress,
        amount: '1000000', // Small amount for quote
        slippage: '0.5'
    });
    const tokenInfo = {
        fromToken: {
            symbol: quote.data[0].fromToken.tokenSymbol,
            decimals: parseInt(quote.data[0].fromToken.decimal),
            price: quote.data[0].fromToken.tokenUnitPrice
        },
        toToken: {
            symbol: quote.data[0].toToken.tokenSymbol,
            decimals: parseInt(quote.data[0].toToken.decimal),
            price: quote.data[0].toToken.tokenUnitPrice
        }
    };
    // Convert amount to base units
    const humanReadableAmount = 1.5; // 1.5 SUI
    const rawAmount = (humanReadableAmount * Math.pow(10, tokenInfo.fromToken.decimals)).toString();
    console.log("\nSwap Details:");
    console.log("--------------------");
    console.log(
From: ${tokenInfo.fromToken.symbol}
);
    console.log(
To: ${tokenInfo.toToken.symbol}
);
    console.log(
Amount: ${humanReadableAmount} ${tokenInfo.fromToken.symbol}
);
    console.log(
Amount in base units: ${rawAmount}
);
    console.log(
Approximate USD value: $${(humanReadableAmount * parseFloat(tokenInfo.fromToken.price)).toFixed(2)}
);
    // Execute the swap
    console.log("\nExecuting swap...");
    const swapResult = await client.dex.executeSwap({
      chainId: '784', // Sui chain ID
      fromTokenAddress,
      toTokenAddress,
      amount: rawAmount,
      slippage: '0.5', // 0.5% slippage
      userWalletAddress: process.env.SUI_WALLET_ADDRESS!
    });
    console.log('Swap executed successfully:');
    console.log("\nTransaction ID:", swapResult.transactionId);
    console.log("Explorer URL:", swapResult.explorerUrl);

    if (swapResult.details) {
        console.log("\nDetails:");
        console.log(
Input: ${swapResult.details.fromToken.amount} ${swapResult.details.fromToken.symbol}
);
        console.log(
Output: ${swapResult.details.toToken.amount} ${swapResult.details.toToken.symbol}
);
        if (swapResult.details.priceImpact) {
            console.log(
Price Impact: ${swapResult.details.priceImpact}%
);
        }
    }

    return swapResult;
  } catch (error) {
    if (error instanceof Error) {
      console.error('Error executing swap:', error.message);
      // API errors include details in the message
      if (error.message.includes('API Error:')) {
        const match = error.message.match(/API Error: (.*)/);
        if (match) console.error('API Error Details:', match[1]);
      }
    }
    throw error;
  }
}
// Run if this file is executed directly
if (require.main === module) {
  executeSwap()
    .then(() => process.exit(0))
    .catch((error) => {
      console.error('Error:', error);
      process.exit(1);
    });
}
export { executeSwap };

Get a quote#

const quote = await client.dex.getQuote({
    chainId: '784',  // Sui
    fromTokenAddress: '0x2::sui::SUI', // SUI
    toTokenAddress: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC', // USDC
    amount: '100000000',  // In base units
    slippage: '0.5'     // 0.5%
});