Build Swap Applications on Sui

·

Creating decentralized swap applications on the Sui blockchain has become increasingly accessible, thanks to powerful tools like the OKX DEX API and SDK. Whether you're a seasoned developer or new to blockchain development, this guide walks you through two effective methods for building seamless token swap experiences—using either a direct API-first approach or the streamlined SDK approach. Both paths empower developers to integrate decentralized exchange functionality with precision, scalability, and ease.

By the end of this guide, you’ll understand how to set up your environment, retrieve token data, simulate transactions, execute swaps, and track outcomes—all tailored for the Sui network.


Method 1: API-First Approach

The API-first method gives developers full control by directly interacting with OKX DEX endpoints. This approach is ideal for teams requiring custom logic, advanced error handling, or integration into existing backend systems.

Set Up Your Development Environment

Begin by initializing a Node.js project and installing essential dependencies:

npm init -y
npm install node-fetch dotenv @mysten/sui.js

Create a .env file to securely store your API keys and wallet credentials. Never expose these in public repositories.

Retrieve Token Information and Swap Quotes

To initiate a swap, first gather accurate token data. Start by creating a utility function to manage authentication headers:

const getAuthHeaders = () => ({
  'X-API-Key': process.env.OKX_API_KEY,
  'Content-Type': 'application/json'
});

Next, build a function to fetch token details such as decimals and contract addresses:

const getTokenInfo = async (symbol) => {
  const response = await fetch(`https://www.okx.com/join/BLOCKSTARapi/v5/dex/aggregator/tokens?sui=${symbol}`, {
    headers: getAuthHeaders()
  });
  return response.json();
};

Since blockchain operations require base units (e.g., converting 1 SUI to 1,000,000,000 MIST), include a conversion utility:

const toBaseUnits = (amount, decimals) => BigInt(Math.floor(amount * Math.pow(10, decimals)));

👉 Discover how to connect your wallet and start swapping tokens in minutes

Fetch Swap Transaction Data

Define key swap parameters:

Request transaction payload from the OKX DEX Aggregator API:

const getSwapData = async (fromToken, toToken, amount, slippage) => {
  const quoteResponse = await fetch(
    `https://www.okx.com/join/BLOCKSTARapi/v5/dex/aggregator/quote?from=${fromToken}&to=${toToken}&amount=${amount}&slippage=${slippage}&chainId=sui`
  );
  const quote = await quoteResponse.json();

  const txResponse = await fetch('https://www.okx.com/join/BLOCKSTARapi/v5/dex/aggregator/swap', {
    method: 'POST',
    headers: getAuthHeaders(),
    body: JSON.stringify({
      from: fromToken,
      to: toToken,
      amount,
      quoteId: quote.quoteId,
      userAddr: process.env.WALLET_ADDRESS
    })
  });

  return txResponse.json();
};

Simulate the Transaction

Before broadcasting, simulate the transaction to catch errors early:

const simulateTransaction = async (txPayload) => {
  const response = await fetch('https://www.okx.com/join/BLOCKSTARapi/v5/dex/aggregator/simulate', {
    method: 'POST',
    headers: getAuthHeaders(),
    body: JSON.stringify(txPayload)
  });
  return response.json();
};

Simulation helps detect issues like insufficient balance or invalid approvals—critical for user experience.

Execute the Swap

Once simulated successfully, sign and send the transaction using Sui’s @mysten/sui.js library:

import { JsonRpcProvider, RawSigner } from '@mysten/sui.js';

const provider = new JsonRpcProvider('https://fullnode.mainnet.sui.io');
const signer = new RawSigner(privateKey, provider);

const executeSwap = async (txPayload) => {
  const result = await signer.signAndExecuteTransactionBlock({
    transactionBlock: txPayload.transactionData
  });
  return result.digest; // Transaction ID
};

You can also use the Onchain Gateway API (enterprise-only) for enhanced reliability and monitoring.

Track Transaction Status

Monitor your swap using the transaction digest:

const trackTransaction = async (digest) => {
  return await provider.getTransactionBlock({ digest });
};

Alternatively, use the SWAP API endpoint to check status via OKX’s infrastructure.


Method 2: SDK Approach

For faster development and reduced complexity, the OKX DEX SDK abstracts away low-level details while preserving full functionality.

Install the SDK

Run the following command:

npm install @okx-dex/okx-dex-sdk

This package includes built-in retry mechanisms, error handling, and chain-specific configurations.

Configure Environment Variables

In your .env file, add:

OKX_API_KEY=your_api_key_here
SUI_PRIVATE_KEY=your_hex_without_flag_private_key
WALLET_ADDRESS=your_sui_wallet_address

Ensure your private key is in hexWithoutFlag format. You can extract it using the SUI CLI:

sui keytool export --format hexWithoutFlag

Initialize the DEX Client

Create a DexClient.ts file:

import { OkxDexClient } from '@okx-dex/okx-dex-sdk';

const client = new OkxDexClient({
  apiKey: process.env.OKX_API_KEY!,
  chainId: 'sui',
  signer: yourSuiSigner // From @mysten/sui.js
});

👉 See real-time swap examples and start building with one click

Optional: Create a Token Helper

Simplify access to common tokens:

const TOKENS = {
  SUI: { symbol: 'SUI', address: '0x2::sui::SUI' },
  USDC: { symbol: 'USDC', address: '0xf9c69a8...::coin::COIN' }
};

Execute a Swap Using the SDK

Perform a complete swap with minimal code:

const swap = async () => {
  const quote = await client.getQuote({
    fromToken: TOKENS.SUI,
    toToken: TOKENS.USDC,
    amount: '10',
    slippage: 0.5
  });

  const txResult = await client.swap(quote);
  console.log('Swap successful:', txResult.digest);
};

The SDK also supports additional features:


Core Keywords

To align with search intent and improve SEO visibility, here are the core keywords naturally integrated throughout this guide:

These terms reflect high-intent queries from developers exploring DeFi solutions on Sui.


Frequently Asked Questions

Q: Can I use the OKX DEX API for free?
A: Yes, basic access to the OKX DEX API is free. Advanced features like the Onchain Gateway API are available for enterprise partners.

Q: Do I need prior experience with Sui to use this guide?
A: While familiarity helps, this guide includes foundational steps suitable for intermediate developers. Basic knowledge of JavaScript/TypeScript and blockchain concepts is recommended.

Q: What is the difference between hexWithFlag and hexWithoutFlag private keys?
A: The hexWithoutFlag format excludes metadata flags used in some wallets. It's required by the SDK for direct signing and must be extracted using the SUI CLI.

Q: How do I handle slippage in my swap app?
A: Set an appropriate slippage tolerance (typically 0.1%–1%) when requesting quotes. Higher volatility pairs may require more buffer.

Q: Is transaction simulation mandatory?
A: Not mandatory, but strongly recommended. Simulation prevents failed transactions and improves user trust by catching errors pre-execution.

Q: Can I track swaps across multiple chains?
A: Currently, this guide focuses on Sui. However, OKX DEX supports multi-chain integrations—check documentation for other networks.


👉 Jumpstart your DeFi project—integrate swaps now with full documentation support