Creating decentralized exchange (DEX) swap applications on the Sui blockchain has become increasingly accessible thanks to powerful tools like the OKX DEX API and SDK. Whether you're building a trading interface, integrating automated swaps into a dApp, or developing a portfolio manager, understanding how to leverage these tools is essential. This guide walks you through two robust approaches: the API-first method for granular control and the SDK-based approach for rapid development.
By the end, you'll be equipped to choose the right path based on your project’s complexity, scalability needs, and development timeline.
Core Keywords
- Sui swap application
- OKX DEX API
- DEX SDK for Sui
- Token swap on Sui
- Decentralized exchange integration
- Sui blockchain development
- Web3 swap integration
- On-chain transaction simulation
These keywords naturally align with developer search intent and are strategically woven throughout this guide to enhance SEO performance while maintaining readability.
Method 1: API-First Approach
The API-first approach gives developers full control over every aspect of the swap process. It's ideal for teams requiring custom logic, advanced error handling, or integration with existing backend systems.
1. Set Up Your Environment
Begin by initializing a Node.js project and installing essential dependencies:
npm init -y
npm install axios dotenvThen, import required libraries in your main file:
require('dotenv').config();
const axios = require('axios');Ensure your environment variables include your API key, secret, and Sui wallet private key.
👉 Discover how to securely manage API credentials for seamless Web3 integration.
2. Obtain Token Information and Swap Quote
Start by creating a utility function to authenticate requests:
function getAuthHeaders() {
return {
'OK-ACCESS-KEY': process.env.API_KEY,
'OK-ACCESS-SIGN': generateSignature(), // Implement signing logic
'OK-ACCESS-PASSPHRASE': process.env.PASSPHRASE,
'Content-Type': 'application/json'
};
}Next, build a function to retrieve token metadata:
async function getTokenInfo(symbol) {
const response = await axios.get(`https://www.okx.com/join/8265080api/v5/asset/currency?ccy=${symbol}`);
return response.data;
}Convert human-readable amounts (e.g., 1.5 SUI) to base units (e.g., 1500000000) using a helper:
function toBaseUnits(amount, decimals) {
return BigInt(amount * Math.pow(10, decimals));
}3. Get Swap Data
Define Swap Parameters
Specify source and target tokens, amount, slippage tolerance, and user address:
const swapParams = {
fromCoin: 'SUI',
toCoin: 'USDC',
amount: '1.5',
slippage: '0.5',
userAddr: process.env.WALLET_ADDRESS
};Request Swap Transaction Data
Call the OKX DEX quote endpoint:
async function getSwapQuote(params) {
const response = await axios.get('https://www.okx.com/join/8265080api/v5/trade/quote', {
params,
headers: getAuthHeaders()
});
return response.data.data[0];
}4. Simulate Transaction
Before broadcasting, simulate the transaction to prevent failures:
async function simulateTransaction(txData) {
const response = await axios.post('https://www.okx.com/join/8265080api/v5/trade/simulate', txData, {
headers: getAuthHeaders()
});
return response.data;
}Note: The Onchain Gateway API used for simulation and execution is available exclusively to enterprise clients. For access, contact OKX DEX support directly.
5. Execute the Transaction
Sign the transaction using your Sui wallet library (e.g., @mysten/sui.js):
const { RawSigner } = require('@mysten/sui.js');
const signer = new RawSigner(privateKey, suiClient);
const result = await signer.signAndExecuteTransactionBlock({ transactionBlock });You can broadcast via standard Sui RPC or use the Onchain Gateway API (enterprise-only).
6. Track Transaction Status
Monitor progress using either method:
Via Swap API:
await axios.get(`https://www.okx.com/join/8265080api/v5/trade/order?orderId=${orderId}`);- Via Onchain Gateway (enterprise feature)
This ensures real-time feedback for users during execution.
7. Complete Implementation
Combine all steps into a single flow: authenticate → quote → simulate → sign → execute → track. This modular design supports reusability across multiple dApps.
Method 2: SDK Approach
For faster development and reduced boilerplate, the @okx-dex/okx-dex-sdk package simplifies interaction with OKX DEX on Sui.
1. Install the SDK
npm install @okx-dex/okx-dex-sdk2. Set Up Your Environment
Create a .env file:
API_KEY=your_api_key
API_SECRET=your_secret
PASSPHRASE=your_passphrase
SUI_PRIVATE_KEY=hex_without_flag_formatExtract your private key in correct format using SUI CLI:
sui keytool export --format hex-including-sui-scheme3. Initialize the Client
Create DexClient.ts:
import { OkxDexClient } from '@okx-dex/okx-dex-sdk';
const client = new OkxDexClient({
apiKey: process.env.API_KEY!,
apiSecret: process.env.API_SECRET!,
passphrase: process.env.PASSPHRASE!,
network: 'testnet' // or 'mainnet'
});👉 See how the SDK reduces development time by up to 60% in real-world projects.
4. Create a Token Helper (Optional)
Build a token list for quick access:
const TOKENS = {
SUI: '0x2::sui::SUI',
USDC: '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d73e166d8aa89cd9cc::coin::COIN'
};5. Execute a Swap With the SDK
Perform a full swap in just a few lines:
const swapTx = await client.swap({
fromToken: TOKENS.SUI,
toToken: TOKENS.USDC,
amount: '1.5',
userAddress: process.env.WALLET_ADDRESS!
});
await signer.signAndExecuteTransactionBlock({ transactionBlock: swapTx });Additional SDK Features
Get a quote:
const quote = await client.getQuote('SUI', 'USDC', '1.5');- Auto-retry logic, built-in error handling, and gas estimation reduce operational overhead.
Frequently Asked Questions
Q: Can I use the OKX DEX API on Sui testnet?
A: Yes, both the API and SDK support testnet environments for development and testing before mainnet deployment.
Q: Is the Onchain Gateway API free to use?
A: The Onchain Gateway is currently available only to enterprise partners of OKX DEX. Contact their sales team for eligibility and pricing.
Q: What format should my Sui private key be in?
A: Use the hexWithoutFlag format, which excludes the first byte indicating key type. You can extract it using the SUI CLI command sui keytool export.
Q: How does slippage protection work in swaps?
A: Slippage tolerance defines the maximum price deviation allowed. If market movement exceeds this during execution, the transaction reverts to protect user funds.
Q: Can I integrate this into a mobile dApp?
A: Absolutely. Both the API and SDK can be wrapped in backend services that communicate securely with mobile frontends.
Q: Does the SDK support other blockchains besides Sui?
A: While this guide focuses on Sui, OKX DEX also offers cross-chain compatible tools—check official documentation for updates.
Final Thoughts
Whether you opt for low-level control via the OKX DEX API or rapid deployment using the DEX SDK, building swap applications on Sui is now more efficient than ever. The ecosystem's high throughput and low latency make it an excellent choice for DeFi innovation.
👉 Start building your next-gen Sui swap app with powerful tools designed for developers.