Decentralized finance (DeFi) continues to expand across high-performance blockchains, and Sui has emerged as a leading platform for building scalable, low-latency applications. One of the most in-demand DeFi features is token swapping, and developers can now integrate seamless swap functionality into their Sui-based applications using the OKX DEX API and SDK.
Whether you're building a wallet, DeFi dashboard, or a full-fledged trading interface, this guide walks you through two powerful approaches to implement swaps on Sui: the API-first method for maximum control, and the SDK-based approach for rapid development.
By the end, you'll understand how to fetch token data, generate swap quotes, simulate transactions, execute trades, and track their status—all on the Sui network.
Method 1: API-First Approach
The API-first method gives developers direct access to OKX DEX endpoints, offering granular control over every step of the swap process. This approach is ideal for teams requiring custom logic, advanced error handling, or integration with existing backend systems.
Set Up Your Environment
Begin by installing essential Node.js packages:
npm install axios dotenv @mysten/sui.jsThen, configure your environment variables in a .env file:
OKX_API_KEY=your_api_key
OKX_API_SECRET=your_api_secret
SUI_PRIVATE_KEY=your_sui_private_keyImport dependencies in your project:
require('dotenv').config();
const axios = require('axios');Obtain Token Information and Swap Quote
Start by creating a utility function to authenticate API requests:
function getAuthHeaders() {
return {
'OK-ACCESS-KEY': process.env.OKX_API_KEY,
'OK-ACCESS-SIGN': generateSignature(), // Implement signing logic
'Content-Type': 'application/json'
};
}Next, build a function to retrieve token metadata such as decimals and contract addresses:
async function getTokenInfo(symbol) {
const response = await axios.get(`https://www.okx.com/join/8265080api/v5/asset/token?symbol=${symbol}`, {
headers: getAuthHeaders()
});
return response.data;
}Since blockchain transactions use base units (e.g., micro-SUI), convert human-readable amounts:
function toBaseUnit(amount, decimals) {
return BigInt(amount * Math.pow(10, decimals));
}👉 Discover how to connect your Sui app to real-time swap data with minimal latency.
Get Swap Data
Define key swap parameters:
fromToken: Source token symbol (e.g., SUI)toToken: Target token symbol (e.g., USDC)amount: Amount to swap in human-readable format
Request transaction data from the OKX DEX API:
async function getSwapData(fromToken, toToken, amount) {
const params = { fromToken, toToken, amount };
const response = await axios.get('https://www.okx.com/join/8265080api/v5/trade/swap-quote', {
params,
headers: getAuthHeaders()
});
return response.data;
}Simulate Transaction
Before broadcasting, simulate the transaction to verify success and detect potential failures:
async function simulateTransaction(swapData) {
const response = await axios.post('https://www.okx.com/join/8265080api/v5/trade/simulate', swapData, {
headers: getAuthHeaders()
});
return response.data;
}Note: The Onchain Gateway API used for simulation and execution is currently available only to enterprise clients. Contact [email protected] for access.Execute the Transaction
Sign and send the transaction using your Sui wallet:
const { Ed25519Keypair } = require('@mysten/sui.js/keypairs/ed25519');
const { fromB64 } = require('@mysten/sui.js/utils');
const keypair = Ed25519Keypair.fromSecretKey(
fromB64(process.env.SUI_PRIVATE_KEY).slice(1)
);Submit via RPC:
const suiClient = new JsonRpcProvider(Connection.create({ fullnode: 'https://fullnode.mainnet.sui.io' }));
await suiClient.executeTransactionBlock({ transactionBlock: signedTx });Or use the Onchain Gateway API (enterprise only):
await axios.post('https://www.okx.com/join/8265080api/v5/trade/execute', { txData }, { headers: getAuthHeaders() });Track Transaction Status
Monitor your swap using either method:
- Onchain Gateway API: Real-time status updates (enterprise)
- SWAP API: Polling-based tracking for public integrations
async function getTransactionStatus(txId) {
const response = await axios.get(`https://www.okx.com/join/8265080api/v5/trade/order?orderId=${txId}`, {
headers: getAuthHeaders()
});
return response.data;
}Method 2: SDK Approach
For faster development and simplified integration, the OKX DEX SDK abstracts away complex implementation details like authentication, retries, and transaction signing.
Install the SDK
npm install @okx-dex/okx-dex-sdk👉 See how the OKX DEX SDK can cut your development time in half.
Set Up Your Environment
Ensure your .env file includes:
OKX_API_KEY=your_api_key
OKX_API_SECRET=your_api_secret
SUI_PRIVATE_KEY_HEX=your_private_key_in_hex_without_flagYou can extract your private key in hex format using the SUI CLI:
sui keytool export --format hex-private-keyInitialize the Client
Create a client instance to interact with OKX DEX services:
import { OkxDexClient } from '@okx-dex/okx-dex-sdk';
const client = new OkxDexClient({
apiKey: process.env.OKX_API_KEY,
apiSecret: process.env.OKX_API_SECRET,
chain: 'sui',
wallet: process.env.SUI_PRIVATE_KEY_HEX
});Create a Token Helper (Optional)
Streamline token lookups with a helper class:
const tokenList = {
SUI: '0x2::sui::SUI',
USDC: '0x5d4b302506645c37ff13363f545898bfdb935b0d::coin::COIN'
};
function getTokenAddress(symbol: string) {
return tokenList[symbol];
}Execute a Swap With the SDK
Perform a complete swap in just a few lines:
async function executeSwap() {
const quote = await client.getQuote({
fromToken: getTokenAddress('SUI'),
toToken: getTokenAddress('USDC'),
amount: '1'
});
const result = await client.swap(quote);
console.log('Swap successful:', result.txId);
}Additional SDK Features
The SDK includes utility methods for enhanced functionality:
- Get liquidity data:
client.getLiquidityPool(tokenA, tokenB) - Fetch price impact:
quote.priceImpact - Check allowance:
client.getTokenAllowance(token) - Approve tokens:
client.approveToken(token)
👉 Start building your next-gen Sui swap app with powerful tools and low fees.
Frequently Asked Questions
Q: Can I use the OKX DEX API on Sui testnet?
A: Yes, the API supports both mainnet and testnet environments. Ensure you're using testnet tokens and endpoints during development.
Q: Is the Onchain Gateway API free to use?
A: Access is currently limited to enterprise partners. Contact [email protected] for pricing and availability.
Q: What tokens are supported for swapping on Sui via OKX DEX?
A: Supported tokens include SUI, USDC, WETH, and other major assets deployed on Sui. Check the latest token list via the /api/v5/asset/tokens endpoint.
Q: How do I handle slippage in my swap transactions?
A: The SDK and API allow you to set slippage tolerance (e.g., 0.5%–1%). Higher slippage increases success chances in volatile markets.
Q: Can I integrate the SDK into a frontend application?
A: For security reasons, private key management should occur server-side. Use backend services to handle signing and expose secure endpoints to your frontend.
Q: Does OKX DEX support limit orders on Sui?
A: Currently, only market swaps are supported. Limit order functionality may be introduced in future updates.
Core Keywords
- Sui swap
- OKX DEX API
- DeFi on Sui
- Token swap SDK
- Sui blockchain
- Decentralized exchange
- Web3 trading
- Build DeFi app
With either the API-first or SDK method, developers can now efficiently build robust swap applications on Sui. Choose based on your need for control or speed—both paths lead to powerful DeFi innovation.