okx-dex-swap
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOKX DEX Aggregator API
OKX DEX Aggregator API
6 endpoints for multi-chain swap aggregation — quote, approve, and execute.
Base URL:
https://web3.okx.comBase path:
/api/v6/dex/aggregatorAuth: HMAC-SHA256 signature, 4 headers required (, , , )
OK-ACCESS-KEYOK-ACCESS-SIGNOK-ACCESS-PASSPHRASEOK-ACCESS-TIMESTAMPNote: All aggregator endpoints are GET requests.
6个用于多链兑换聚合的接口——报价、授权和执行。
Base URL:
https://web3.okx.comBase path:
/api/v6/dex/aggregator身份验证:采用HMAC-SHA256签名,需4个请求头(、、、)
OK-ACCESS-KEYOK-ACCESS-SIGNOK-ACCESS-PASSPHRASEOK-ACCESS-TIMESTAMP注意:所有聚合器接口均为GET请求。
Authentication & Credentials
身份验证与凭证
API Key Application: OKX Developer Portal
Setup Guide: Developer Portal Docs
Read credentials from environment variables:
- → API key
OKX_API_KEY - → Secret key (system-generated)
OKX_SECRET_KEY - → Passphrase (developer-supplied)
OKX_PASSPHRASE
Never output the above credentials to logs, response content, or any user-visible interface.
typescript
import crypto from 'crypto';
const BASE = 'https://web3.okx.com';
// Signature rule (all aggregator endpoints are GET):
// GET → body = "", requestPath includes query string (e.g., "/api/v6/dex/aggregator/quote?chainIndex=1&...")
// POST → body = JSON string of request body, requestPath is path only (not used in this skill)
async function okxFetch(method: 'GET' | 'POST', path: string, body?: object) {
const timestamp = new Date().toISOString();
const bodyStr = body ? JSON.stringify(body) : '';
const sign = crypto
.createHmac('sha256', process.env.OKX_SECRET_KEY!)
.update(timestamp + method + path + bodyStr)
.digest('base64');
const headers: Record<string, string> = {
'OK-ACCESS-KEY': process.env.OKX_API_KEY!,
'OK-ACCESS-SIGN': sign,
'OK-ACCESS-PASSPHRASE': process.env.OKX_PASSPHRASE!,
'OK-ACCESS-TIMESTAMP': timestamp,
'Content-Type': 'application/json',
};
const res = await fetch(`${BASE}${path}`, {
method,
headers,
...(body && { body: bodyStr }),
});
if (res.status === 429) throw { code: 'RATE_LIMITED', msg: 'Rate limited — retry with backoff', retryable: true };
if (res.status >= 500) throw { code: `HTTP_${res.status}`, msg: 'Server error', retryable: true };
const json = await res.json();
if (json.code !== '0') throw { code: json.code, msg: json.msg || 'API error', retryable: false };
return json.data;
}Response envelope: . = means success.
{ "code": "0", "data": [...], "msg": "" }code"0"API密钥申请:OKX开发者门户
设置指南:开发者门户文档
从环境变量中读取凭证:
- → API密钥
OKX_API_KEY - → 密钥(系统生成)
OKX_SECRET_KEY - → 密码短语(开发者设置)
OKX_PASSPHRASE
切勿将上述凭证输出到日志、响应内容或任何用户可见界面中。
typescript
import crypto from 'crypto';
const BASE = 'https://web3.okx.com';
// 签名规则(所有聚合器接口均为GET):
// GET → body = "", requestPath包含查询字符串(例如:"/api/v6/dex/aggregator/quote?chainIndex=1&...")
// POST → body = 请求体的JSON字符串,requestPath仅为路径(本技能中未使用)
async function okxFetch(method: 'GET' | 'POST', path: string, body?: object) {
const timestamp = new Date().toISOString();
const bodyStr = body ? JSON.stringify(body) : '';
const sign = crypto
.createHmac('sha256', process.env.OKX_SECRET_KEY!)
.update(timestamp + method + path + bodyStr)
.digest('base64');
const headers: Record<string, string> = {
'OK-ACCESS-KEY': process.env.OKX_API_KEY!,
'OK-ACCESS-SIGN': sign,
'OK-ACCESS-PASSPHRASE': process.env.OKX_PASSPHRASE!,
'OK-ACCESS-TIMESTAMP': timestamp,
'Content-Type': 'application/json',
};
const res = await fetch(`${BASE}${path}`, {
method,
headers,
...(body && { body: bodyStr }),
});
if (res.status === 429) throw { code: 'RATE_LIMITED', msg: '请求频率超限——请延迟后重试', retryable: true };
if (res.status >= 500) throw { code: `HTTP_${res.status}`, msg: '服务器错误', retryable: true };
const json = await res.json();
if (json.code !== '0') throw { code: json.code, msg: json.msg || 'API错误', retryable: false };
return json.data;
}响应格式:。当为时表示请求成功。
{ "code": "0", "data": [...], "msg": "" }code"0"Developer Quickstart
开发者快速入门
EVM Swap (quote → approve → swap)
EVM链兑换(报价→授权→兑换)
typescript
// 1. Quote — sell 100 USDC for ETH
const params = new URLSearchParams({
chainIndex: '1', fromTokenAddress: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', // USDC
toTokenAddress: '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', // native ETH
amount: '100000000', swapMode: 'exactIn', // 100 USDC (6 decimals)
});
const quote = await okxFetch('GET', `/api/v6/dex/aggregator/quote?${params}`);
console.log(`Expected: ${quote[0].toTokenAmount} ETH (minimal units)`);
// 2. Approve — ERC-20 tokens need approval before swap (skip for native ETH)
const approveParams = new URLSearchParams({
chainIndex: '1', tokenContractAddress: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
approveAmount: '100000000',
});
const approve = await okxFetch('GET', `/api/v6/dex/aggregator/approve-transaction?${approveParams}`);
// → build tx: { to: tokenContractAddress, data: approve[0].data }, sign & send
// approve[0].dexContractAddress is the spender (already encoded in calldata), NOT the tx target
// 3. Swap
const swapParams = new URLSearchParams({
chainIndex: '1', fromTokenAddress: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
toTokenAddress: '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
amount: '100000000', slippagePercent: '1',
userWalletAddress: '0xYourWallet', swapMode: 'exactIn',
});
const swap = await okxFetch('GET', `/api/v6/dex/aggregator/swap?${swapParams}`);
// → sign & send swap[0].tx { from, to, data, value, gas }typescript
// 1. 报价——出售100 USDC兑换ETH
const params = new URLSearchParams({
chainIndex: '1', fromTokenAddress: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', // USDC
toTokenAddress: '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', // 原生ETH
amount: '100000000', swapMode: 'exactIn', // 100 USDC(6位小数)
});
const quote = await okxFetch('GET', `/api/v6/dex/aggregator/quote?${params}`);
console.log(`预计到账:${quote[0].toTokenAmount} ETH(最小单位)`);
// 2. 授权——ERC-20代币在兑换前需要授权(原生ETH可跳过此步骤)
const approveParams = new URLSearchParams({
chainIndex: '1', tokenContractAddress: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
approveAmount: '100000000',
});
const approve = await okxFetch('GET', `/api/v6/dex/aggregator/approve-transaction?${approveParams}`);
// → 构建交易:{ to: tokenContractAddress, data: approve[0].data },签名并发送
// approve[0].dexContractAddress是授权对象(已编码在调用数据中),**并非**交易目标地址
// 3. 兑换
const swapParams = new URLSearchParams({
chainIndex: '1', fromTokenAddress: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
toTokenAddress: '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
amount: '100000000', slippagePercent: '1',
userWalletAddress: '0xYourWallet', swapMode: 'exactIn',
});
const swap = await okxFetch('GET', `/api/v6/dex/aggregator/swap?${swapParams}`);
// → 签名并发送swap[0].tx { from, to, data, value, gas }Solana Swap (swap-instruction)
Solana链兑换(swap-instruction)
typescript
const params = new URLSearchParams({
chainIndex: '501', fromTokenAddress: '11111111111111111111111111111111', // native SOL
toTokenAddress: 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263', // BONK
amount: '1000000000', slippagePercent: '1', userWalletAddress: 'YourSolanaWallet',
});
const result = await okxFetch('GET', `/api/v6/dex/aggregator/swap-instruction?${params}`);
// → result[0].instructionLists: assemble into VersionedTransaction, sign & sendtypescript
const params = new URLSearchParams({
chainIndex: '501', fromTokenAddress: '11111111111111111111111111111111', // 原生SOL
toTokenAddress: 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263', // BONK
amount: '1000000000', slippagePercent: '1', userWalletAddress: 'YourSolanaWallet',
});
const result = await okxFetch('GET', `/api/v6/dex/aggregator/swap-instruction?${params}`);
// → result[0].instructionLists:组装为VersionedTransaction,签名并发送Common Chain IDs
常用链ID
| Chain | chainIndex | Chain | chainIndex |
|---|---|---|---|
| Ethereum | | Arbitrum | |
| BSC | | Base | |
| Polygon | | Solana | |
| 链名称 | chainIndex | 链名称 | chainIndex |
|---|---|---|---|
| Ethereum | | Arbitrum | |
| BSC | | Base | |
| Polygon | | Solana | |
Native Token Addresses
原生代币地址
CRITICAL: Each chain has a specific native token address for use in OKX DEX API. Using the wrong address (e.g., wSOL SPL token address instead of the Solana system program address) will cause swap transactions to fail. Reference: DEX Aggregation FAQ
| Chain | Native Token Address |
|---|---|
| EVM (Ethereum, BSC, Polygon, Arbitrum, Base, etc.) | |
| Solana | |
| Sui | |
| Tron | |
| Ton | |
WARNING — Solana native SOL: The correct address is(Solana system program). Do NOT use11111111111111111111111111111111(wSOL SPL token) — it is a different token and will cause swap failures (So11111111111111111111111111111111111111112).custom program error: 0xb
重要提示:每条链在OKX DEX API中都有特定的原生代币地址。使用错误地址(例如,使用wSOL SPL代币地址而非Solana系统程序地址)会导致兑换交易失败。参考:DEX聚合常见问题
| 链名称 | 原生代币地址 |
|---|---|
| EVM链(Ethereum、BSC、Polygon、Arbitrum、Base等) | |
| Solana | |
| Sui | |
| Tron | |
| Ton | |
警告——Solana原生SOL:正确地址为(Solana系统程序)。切勿使用11111111111111111111111111111111(wSOL SPL代币)——这是不同的代币,会导致兑换失败(错误码:So11111111111111111111111111111111111111112)。custom program error: 0xb
Endpoint Index
接口索引
| # | Method | Path | Docs |
|---|---|---|---|
| 1 | GET | | dex-get-aggregator-supported-chains |
| 2 | GET | | dex-get-liquidity |
| 3 | GET | | dex-approve-transaction |
| 4 | GET | | dex-get-quote |
| 5 | GET | | dex-solana-swap-instruction |
| 6 | GET | | dex-swap |
Error Codes: DEX Error Codes
| 序号 | 请求方法 | 路径 | 文档 |
|---|---|---|---|
| 1 | GET | | dex-get-aggregator-supported-chains |
| 2 | GET | | dex-get-liquidity |
| 3 | GET | | dex-approve-transaction |
| 4 | GET | | dex-get-quote |
| 5 | GET | | dex-solana-swap-instruction |
| 6 | GET | | dex-swap |
错误码:DEX错误码
Cross-Skill Workflows
跨技能工作流
This skill is the execution endpoint of most user trading flows. It almost always needs input from other skills first.
本技能是大多数用户交易流程的执行端点,几乎总是需要先从其他技能获取输入。
Workflow A: Full Swap by Token Name (most common)
工作流A:通过代币名称完成完整兑换(最常见)
User: "Swap 1 SOL for BONK on Solana"
1. okx-dex-token /market/token/search?search=BONK&chains=501 → get BONK tokenContractAddress
↓ tokenContractAddress
2. okx-wallet-portfolio /balance/all-token-balances-by-address → verify SOL balance >= 1
↓ sufficient balance confirmed
3. okx-dex-swap /aggregator/quote → get quote (show expected output, gas, price impact)
↓ user confirms
4. okx-dex-swap /aggregator/swap-instruction → get serialized instruction (Solana)
5. User signs & sends tx (or use `okx-onchain-gateway` to broadcast via OKX nodes)Data handoff:
- from step 1 →
tokenContractAddressin steps 3-4toTokenAddress - SOL native address = (Solana system program) →
"11111111111111111111111111111111". Do NOT usefromTokenAddress(wSOL) — see Native Token Addresses.So11111111111111111111111111111111111111112 - Amount =
1 SOL(9 decimals) →"1000000000"paramamount - from step 2 is UI units; swap needs minimal units → multiply by
balance10^decimal
用户:“在Solana链上用1 SOL兑换BONK”
1. okx-dex-token /market/token/search?search=BONK&chains=501 → 获取BONK的tokenContractAddress
↓ tokenContractAddress
2. okx-wallet-portfolio /balance/all-token-balances-by-address → 验证SOL余额≥1
↓ 确认余额充足
3. okx-dex-swap /aggregator/quote → 获取报价(显示预计到账金额、gas费用、价格影响)
↓ 用户确认
4. okx-dex-swap /aggregator/swap-instruction → 获取序列化指令(Solana链)
5. 用户签名并发送交易(或使用`okx-onchain-gateway`通过OKX节点广播)数据传递:
- 步骤1的→ 步骤3-4的
tokenContractAddresstoTokenAddress - Solana原生SOL地址 = (Solana系统程序)→
"11111111111111111111111111111111"。切勿使用fromTokenAddress(wSOL)——详见原生代币地址。So11111111111111111111111111111111111111112 - 金额=
1 SOL(9位小数)→"1000000000"参数amount - 步骤2的是UI单位;兑换需要最小单位 → 乘以
balance10^小数位数
Workflow B: EVM Swap with Approval
工作流B:带授权的EVM链兑换
User: "Swap 100 USDC for ETH on Ethereum"
1. okx-dex-token /market/token/search?search=USDC&chains=1 → get USDC address
2. okx-wallet-portfolio /balance/token-balances-by-address → verify USDC balance >= 100
3. okx-dex-swap /aggregator/quote → get quote
↓ check isHoneyPot, taxRate, priceImpactPercent
4. okx-dex-swap /aggregator/approve-transaction → get ERC-20 approval calldata
5. User signs & sends approval tx
6. okx-dex-swap /aggregator/swap → get swap calldata
7. User signs & sends swap tx (or use `okx-onchain-gateway` to broadcast via OKX nodes)Key: EVM tokens (not native ETH) require an approve step. Skip it if user is selling native ETH.
用户:“在Ethereum链上用100 USDC兑换ETH”
1. okx-dex-token /market/token/search?search=USDC&chains=1 → 获取USDC地址
2. okx-wallet-portfolio /balance/token-balances-by-address → 验证USDC余额≥100
3. okx-dex-swap /aggregator/quote → 获取报价
↓ 检查isHoneyPot、taxRate、priceImpactPercent
4. okx-dex-swap /aggregator/approve-transaction → 获取ERC-20授权调用数据
5. 用户签名并发送授权交易
6. okx-dex-swap /aggregator/swap → 获取兑换调用数据
7. 用户签名并发送兑换交易(或使用`okx-onchain-gateway`通过OKX节点广播)关键提示:EVM代币(非原生ETH)需要授权步骤。如果用户出售的是原生ETH,则可跳过此步骤。
Workflow C: Compare Quote Then Execute
工作流C:对比报价后执行
1. okx-dex-swap /aggregator/quote → get quote with route info
2. Display to user: expected output, gas, price impact, route
3. If price impact > 5% → warn user
4. If isHoneyPot = true → block trade, warn user
5. User confirms → proceed to approve (if EVM) → swap1. okx-dex-swap /aggregator/quote → 获取包含路径信息的报价
2. 向用户展示:预计到账金额、gas费用、价格影响、兑换路径
3. 如果价格影响>5% → 向用户发出警告
4. 如果isHoneyPot = true → 阻止交易并警告用户
5. 用户确认 → 继续执行授权(EVM链)→ 兑换Swap Flow
兑换流程
EVM Chains (Ethereum, BSC, Arbitrum, Base, etc.)
EVM链(Ethereum、BSC、Arbitrum、Base等)
1. GET /aggregator/quote -> Get price and route
2. GET /aggregator/approve-transaction -> Get approval calldata (if needed)
3. User signs & sends approval tx
4. GET /aggregator/swap -> Get swap calldata
5. User signs & sends swap tx1. GET /aggregator/quote → 获取价格和路径
2. GET /aggregator/approve-transaction → 获取授权调用数据(如需要)
3. 用户签名并发送授权交易
4. GET /aggregator/swap → 获取兑换调用数据
5. 用户签名并发送兑换交易Solana
Solana链
1. GET /aggregator/quote -> Get price and route
2. GET /aggregator/swap-instruction -> Get serialized instruction
3. User signs & sends tx1. GET /aggregator/quote → 获取价格和路径
2. GET /aggregator/swap-instruction → 获取序列化指令
3. 用户签名并发送交易Operation Flow
操作流程
Step 1: Identify Intent
步骤1:识别意图
- View a quote ->
GET /aggregator/quote - Execute a swap -> full swap flow (quote -> approve -> swap)
- List available DEXes ->
GET /aggregator/get-liquidity - Approve a token ->
GET /aggregator/approve-transaction
- 查看报价 →
GET /aggregator/quote - 执行兑换 → 完整兑换流程(报价→授权→兑换)
- 列出可用DEX →
GET /aggregator/get-liquidity - 授权代币 →
GET /aggregator/approve-transaction
Step 2: Collect Parameters
步骤2:收集参数
- Missing -> ask which chain
chainIndex - Missing token addresses -> use
okx-dex-tokento resolve name → address/market/token/search - Missing amount -> ask user, remind to convert to minimal units
- Missing slippage -> suggest 1% default, 3-5% for volatile tokens
- Missing wallet address -> ask user
- 缺少→ 询问用户具体链
chainIndex - 缺少代币地址 → 使用的
okx-dex-token接口通过代币名称解析为地址/market/token/search - 缺少金额 → 询问用户,提醒转换为最小单位
- 缺少滑点 → 建议默认1%,波动大的代币建议3-5%
- 缺少钱包地址 → 询问用户
Step 3: Execute
步骤3:执行
- Quote phase: call , display estimated results
/quote- Expected output, gas estimate, price impact, routing path
- Check and
isHoneyPot— surface safety info to userstaxRate
- Confirmation phase: wait for user approval before proceeding
- Approval phase (EVM only): check/execute approve if selling non-native token
- Execution phase: call (EVM) or
/swap(Solana), return tx data for signing/swap-instruction
- 报价阶段:调用,展示估算结果
/quote- 预计到账金额、gas估算、价格影响、兑换路径
- 检查和
isHoneyPot—— 向用户展示安全信息taxRate
- 确认阶段:等待用户确认后再继续
- 授权阶段(仅EVM链):如果出售的是非原生代币,检查/执行授权
- 执行阶段:调用(EVM链)或
/swap(Solana链),返回供签名的交易数据/swap-instruction
Step 4: Suggest Next Steps
步骤4:建议后续操作
After displaying results, suggest 2-3 relevant follow-up actions based on the swap phase just completed:
| Just completed | Suggest |
|---|---|
| 1. Check wallet balance first → |
| Swap executed successfully | 1. Verify updated balance → |
| 1. Get a swap quote → |
Present conversationally, e.g.: "Swap complete! Would you like to check your updated balance?" — never expose skill names or endpoint paths to the user.
展示结果后,根据刚完成的兑换阶段建议2-3个相关的后续操作:
| 刚完成的操作 | 建议操作 |
|---|---|
| 1. 先检查钱包余额 → |
| 兑换执行成功 | 1. 验证更新后的余额 → |
| 1. 获取兑换报价 → |
以对话形式呈现,例如:“兑换完成!要不要检查更新后的余额?” —— 切勿向用户暴露技能名称或接口路径。
API Reference
API参考
1. GET /aggregator/supported/chain
1. GET /aggregator/supported/chain
| Param | Type | Required | Description |
|---|---|---|---|
| String | No | Filter to a specific chain (e.g., |
Response:
| Field | Type | Description |
|---|---|---|
| String | Chain unique identifier (e.g., "1") |
| String | Chain name (e.g., "Ethereum") |
| String | OKX DEX token approve contract address |
| 参数 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
| String | 否 | 过滤特定链(例如: |
响应:
| 字段 | 类型 | 描述 |
|---|---|---|
| String | 链唯一标识符(例如:"1") |
| String | 链名称(例如:"Ethereum") |
| String | OKX DEX代币授权合约地址 |
2. GET /aggregator/get-liquidity
2. GET /aggregator/get-liquidity
| Param | Type | Required | Description |
|---|---|---|---|
| String | Yes | Chain ID |
Response:
| Field | Type | Description |
|---|---|---|
| String | Liquidity pool ID |
| String | Pool name (e.g., "Uniswap V3") |
| String | Pool logo URL |
| 参数 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
| String | 是 | 链ID |
响应:
| 字段 | 类型 | 描述 |
|---|---|---|
| String | 流动性池ID |
| String | 池名称(例如:"Uniswap V3") |
| String | 池Logo URL |
3. GET /aggregator/approve-transaction
3. GET /aggregator/approve-transaction
| Param | Type | Required | Description |
|---|---|---|---|
| String | Yes | Chain ID |
| String | Yes | Token to approve |
| String | Yes | Amount in minimal units |
Response:
| Field | Type | Description |
|---|---|---|
| String | Approval calldata ( |
| String | DEX router address (the spender, already encoded in calldata). NOT the tx |
| String | Gas limit. May underestimate — use simulation or ×1.5 |
| String | Gas price in wei |
| 参数 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
| String | 是 | 链ID |
| String | 是 | 要授权的代币 |
| String | 是 | 最小单位的金额 |
响应:
| 字段 | 类型 | 描述 |
|---|---|---|
| String | 授权调用数据( |
| String | DEX路由地址(授权对象,已编码在调用数据中)。并非交易的 |
| String | Gas上限。可能低估 —— 建议使用模拟值或乘以1.5 |
| String | Gas价格(wei单位) |
4. GET /aggregator/quote
4. GET /aggregator/quote
| Param | Type | Required | Description |
|---|---|---|---|
| String | Yes | Chain ID |
| String | Yes | Amount in minimal units (sell amount if exactIn, buy amount if exactOut) |
| String | Yes | |
| String | Yes | Token to sell |
| String | Yes | Token to buy |
Optional params: , , (default 90%), (max 10 Solana, 3 others).
dexIdsdirectRoutepriceImpactProtectionPercentfeePercentResponse key fields: (output minimal units), , , (USD estimate), , , , / (each has , , , ). Full fields: see docs.
toTokenAmountfromTokenAmountestimateGasFeetradeFeepriceImpactPercentrouterdexRouterListfromTokentoTokenisHoneyPottaxRatedecimaltokenUnitPrice| 参数 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
| String | 是 | 链ID |
| String | 是 | 最小单位的金额(exactIn模式下为出售金额,exactOut模式下为购买金额) |
| String | 是 | |
| String | 是 | 要出售的代币 |
| String | 是 | 要购买的代币 |
可选参数:、、(默认90%)、(Solana链最高10,其他链最高3)。
dexIdsdirectRoutepriceImpactProtectionPercentfeePercent响应关键字段:(输出最小单位)、、、(USD估算)、、、、/(包含、、、)。完整字段:查看文档。
toTokenAmountfromTokenAmountestimateGasFeetradeFeepriceImpactPercentrouterdexRouterListfromTokentoTokenisHoneyPottaxRatedecimaltokenUnitPrice5. GET /aggregator/swap-instruction (Solana only)
5. GET /aggregator/swap-instruction(仅Solana链)
| Param | Type | Required | Description |
|---|---|---|---|
| String | Yes | Must be |
| String | Yes | Amount in minimal units |
| String | Yes | Token to sell |
| String | Yes | Token to buy |
| String | Yes | User's wallet |
| String | Yes | 0 to <100 |
Optional params: , , , , , , .
autoSlippagecomputeUnitPricecomputeUnitLimitdexIdsswapReceiverAddressfeePercentpriceImpactProtectionPercentResponse key fields: (each has , , ), , (same as /quote), (, ), . Full fields: see docs.
instructionLists[]dataaccountsprogramIdaddressLookupTableAccountrouterResulttxminReceiveAmountslippagePercentwsolRentFee| 参数 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
| String | 是 | 必须为 |
| String | 是 | 最小单位的金额 |
| String | 是 | 要出售的代币 |
| String | 是 | 要购买的代币 |
| String | 是 | 用户钱包地址 |
| String | 是 | 0到<100 |
可选参数:、、、、、、。
autoSlippagecomputeUnitPricecomputeUnitLimitdexIdsswapReceiverAddressfeePercentpriceImpactProtectionPercent响应关键字段:(包含、、)、、(与相同)、(、)、。完整字段:查看文档。
instructionLists[]dataaccountsprogramIdaddressLookupTableAccountrouterResult/quotetxminReceiveAmountslippagePercentwsolRentFee6. GET /aggregator/swap (EVM + Solana)
6. GET /aggregator/swap(EVM链+Solana链)
Note: This endpoint works for all chains including Solana.is a Solana-specific alternative that returns deserialized instructions instead of a serialized transaction./swap-instruction
| Param | Type | Required | Description |
|---|---|---|---|
| String | No | Chain ID. Technically optional but strongly recommended — always pass it. |
| String | Yes | Amount in minimal units |
| String | Yes | |
| String | Yes | Token to sell |
| String | Yes | Token to buy |
| String | Yes | 0-100 (EVM), 0-<100 (Solana) |
| String | Yes | User's wallet |
Optional params: (//), , , (Jito, 0.0000000001-2 SOL; use if is set), , , , , , (default 90%), (Boolean, combine approve+swap in one call), (used with ).
gasLevelaveragefastslowcomputeUnitPricecomputeUnitLimittips0computeUnitPricedexIdsautoSlippagemaxAutoSlippagePercentswapReceiverAddressfeePercentpriceImpactProtectionPercentapproveTransactionapproveAmountapproveTransactionResponse key fields: (same as /quote), — , , (hex-encoded for EVM, base58-encoded for Solana), , , (EIP-1559), , , , , . Full fields: see docs.
routerResulttxfromtodatagasgasPricemaxPriorityFeePerGasvalueminReceiveAmountmaxSpendAmountslippagePercentsignatureData注意:本接口适用于所有链包括Solana链。是Solana链专用的替代接口,返回反序列化的指令而非序列化交易。/swap-instruction
| 参数 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
| String | 否 | 链ID。技术上可选但强烈建议传入。 |
| String | 是 | 最小单位的金额 |
| String | 是 | |
| String | 是 | 要出售的代币 |
| String | 是 | 要购买的代币 |
| String | 是 | 0-100(EVM链),0-<100(Solana链) |
| String | 是 | 用户钱包地址 |
可选参数:(//)、、、(Jito,0.0000000001-2 SOL;如果设置了则传)、、、、、、(默认90%)、(布尔值,将授权+兑换合并为一次调用)、(与配合使用)。
gasLevelaveragefastslowcomputeUnitPricecomputeUnitLimittipscomputeUnitPrice0dexIdsautoSlippagemaxAutoSlippagePercentswapReceiverAddressfeePercentpriceImpactProtectionPercentapproveTransactionapproveAmountapproveTransaction响应关键字段:(与相同)、 —— 、、(EVM链为十六进制编码,Solana链为base58编码)、、、(EIP-1559)、、、、、。完整字段:查看文档。
routerResult/quotetxfromtodatagasgasPricemaxPriorityFeePerGasvalueminReceiveAmountmaxSpendAmountslippagePercentsignatureDataInput / Output Examples
输入/输出示例
User says: "Swap 100 USDC for ETH"
1. GET /api/v6/dex/aggregator/quote?chainIndex=1&fromTokenAddress=0xa0b8...&toTokenAddress=0xeeee...&amount=100000000&swapMode=exactIn
-> Display:
Expected output: 0.031 ETH
Gas fee: ~$2.50
Price impact: 0.05%
Route: USDC -> WETH -> ETH (Uniswap V3)
2. User confirms
3. GET /api/v6/dex/aggregator/approve-transaction?chainIndex=1&tokenContractAddress=0xa0b8...&approveAmount=100000000
-> Returns approval calldata and spender address
-> Build tx: { to: "0xa0b8..." (token contract), data: response.data } — sign & send
4. GET /api/v6/dex/aggregator/swap?chainIndex=1&...&slippagePercent=1&userWalletAddress=0x...
-> Returns tx: { from, to, data, gas, gasPrice, value, minReceiveAmount }
-> User signs and broadcastsUser says: "What DEXes are available on Ethereum?"
GET /api/v6/dex/aggregator/get-liquidity?chainIndex=1
-> Display: Uniswap V2, Uniswap V3, SushiSwap, Curve, Balancer, ... (80+ sources)用户提问: “用100 USDC兑换ETH”
1. GET /api/v6/dex/aggregator/quote?chainIndex=1&fromTokenAddress=0xa0b8...&toTokenAddress=0xeeee...&amount=100000000&swapMode=exactIn
-> 展示:
预计到账:0.031 ETH
Gas费用:约2.50美元
价格影响:0.05%
兑换路径:USDC -> WETH -> ETH(Uniswap V3)
2. 用户确认
3. GET /api/v6/dex/aggregator/approve-transaction?chainIndex=1&tokenContractAddress=0xa0b8...&approveAmount=100000000
-> 返回授权调用数据和授权对象地址
-> 构建交易:{ to: "0xa0b8..."(代币合约), data: response.data } —— 签名并发送
4. GET /api/v6/dex/aggregator/swap?chainIndex=1&...&slippagePercent=1&userWalletAddress=0x...
-> 返回交易数据:{ from, to, data, gas, gasPrice, value, minReceiveAmount }
-> 用户签名并广播用户提问: “Ethereum链上有哪些可用的DEX?”
GET /api/v6/dex/aggregator/get-liquidity?chainIndex=1
-> 展示:Uniswap V2、Uniswap V3、SushiSwap、Curve、Balancer、...(80+个来源)Edge Cases
边缘情况
- High slippage (>5%): warn user, suggest splitting the trade or adjusting slippage
- Large price impact (>10%): strongly warn, suggest reducing amount
- Honeypot token: — block trade and warn user
isHoneyPot = true - Tax token: non-zero — display to user (e.g. 5% buy tax)
taxRate - Insufficient balance: use to check first, show current balance, suggest adjusting amount
okx-wallet-portfolio - exactOut not supported: only Ethereum/Base/BSC/Arbitrum — prompt user to use
exactIn - Solana chain: returns deserialized instructions (more control);
/swap-instructionalso works but returns a serialized transaction/swap - Solana native SOL address: Must use (system program), NOT
11111111111111111111111111111111(wSOL). Using wSOL address causesSo11111111111111111111111111111111111111112on-chain failures. See DEX Aggregation FAQ.custom program error: 0xb - 429 rate limit: exponential backoff with jitter. See Rate Limit & Fee Docs for tier-specific RPS limits (Trial: 1 RPS, Start-up: 2-50 RPS, Enterprise: custom).
- Cross-skill pipeline rate limit: when chaining calls across multiple skills (e.g., token search → balance check → swap), add 300-500ms delay between requests to avoid triggering rate limit (error code ).
50011 - Network error: retry once, then prompt user to try again later
- Request timeout: all API calls must set a 10-second timeout limit
- 高滑点(>5%):警告用户,建议拆分交易或调整滑点
- 大价格影响(>10%):强烈警告,建议减少交易金额
- 蜜罐代币:—— 阻止交易并警告用户
isHoneyPot = true - 手续费代币:非零 —— 向用户展示(例如5%买入手续费)
taxRate - 余额不足:先使用检查,显示当前余额,建议调整金额
okx-wallet-portfolio - 不支持exactOut:仅Ethereum/Base/BSC/Arbitrum链支持 —— 提示用户使用
exactIn - Solana链:返回反序列化指令(更可控);
/swap-instruction也可用但返回序列化交易/swap - Solana原生SOL地址:必须使用(系统程序),切勿使用
11111111111111111111111111111111(wSOL)。使用wSOL地址会导致链上失败,错误码So11111111111111111111111111111111111111112。详见DEX聚合常见问题。custom program error: 0xb - 429请求频率超限:使用带抖动的指数退避重试。查看请求频率限制与费用文档获取不同等级的RPS限制(试用版:1 RPS,初创版:2-50 RPS,企业版:定制)。
- 跨技能流水线请求频率超限:当跨多个技能链式调用时(例如:代币搜索→余额检查→兑换),请求之间添加300-500ms延迟以避免触发限制(错误码)。
50011 - 网络错误:重试一次,然后提示用户稍后再试
- 请求超时:所有API调用必须设置10秒超时限制
Amount Display Rules
金额显示规则
- Input/output amounts in UI units (,
1.5 ETH)3,200 USDC - Internal API params use minimal units (=
1 USDC,"1000000"=1 ETH)"1000000000000000000" - Gas fees in USD
- in both UI units and USD
minReceiveAmount - Price impact as percentage
- 输入/输出金额使用UI单位(、
1.5 ETH)3,200 USDC - 内部API参数使用最小单位(=
1 USDC,"1000000"=1 ETH)"1000000000000000000" - Gas费用以USD显示
- 同时显示UI单位和USD
minReceiveAmount - 价格影响以百分比显示
Global Notes
全局注意事项
- All endpoints are GET — no POST in the aggregator family
- Amounts must be in minimal units (wei/lamports)
- only on Ethereum(
exactOut)/Base(1)/BSC(8453)/Arbitrum(56)42161 - is Solana-only
/swap-instruction - Check and
isHoneyPot— surface safety info to userstaxRate - Solana referrer wallets require SOL deposit activation
- TON chain has limited commission pool support (excludes Stonfi V1)
- EVM contract addresses must be all lowercase
- For token search -> use
okx-dex-token - For market prices -> use
okx-dex-market - For balance queries -> use
okx-wallet-portfolio - For transaction broadcasting -> use
okx-onchain-gateway
- 所有接口均为GET —— 聚合器系列无POST请求
- 金额必须为最小单位(wei/lamports)
- 仅支持Ethereum(
exactOut)/Base(1)/BSC(8453)/Arbitrum(56)42161 - 仅适用于Solana链
/swap-instruction - 检查和
isHoneyPot—— 向用户展示安全信息taxRate - Solana推荐人钱包需要存入SOL激活
- TON链的佣金池支持有限(不包含Stonfi V1)
- EVM合约地址必须为全小写
- 代币搜索 -> 使用
okx-dex-token - 市场价格 -> 使用
okx-dex-market - 余额查询 -> 使用
okx-wallet-portfolio - 交易广播 -> 使用
okx-onchain-gateway