okx-dex-swap

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

OKX DEX Aggregator API

OKX DEX Aggregator API

6 endpoints for multi-chain swap aggregation — quote, approve, and execute.
Base URL:
https://web3.okx.com
Base path:
/api/v6/dex/aggregator
Auth: HMAC-SHA256 signature, 4 headers required (
OK-ACCESS-KEY
,
OK-ACCESS-SIGN
,
OK-ACCESS-PASSPHRASE
,
OK-ACCESS-TIMESTAMP
)
Note: All aggregator endpoints are GET requests.
6个用于多链兑换聚合的接口——报价、授权和执行。
Base URL
https://web3.okx.com
Base path
/api/v6/dex/aggregator
身份验证:采用HMAC-SHA256签名,需4个请求头(
OK-ACCESS-KEY
OK-ACCESS-SIGN
OK-ACCESS-PASSPHRASE
OK-ACCESS-TIMESTAMP
注意:所有聚合器接口均为GET请求。

Authentication & Credentials

身份验证与凭证

API Key Application: OKX Developer Portal
Read credentials from environment variables:
  • OKX_API_KEY
    → API key
  • OKX_SECRET_KEY
    → Secret key (system-generated)
  • OKX_PASSPHRASE
    → Passphrase (developer-supplied)
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:
{ "code": "0", "data": [...], "msg": "" }
.
code
=
"0"
means success.
API密钥申请OKX开发者门户
设置指南开发者门户文档
从环境变量中读取凭证:
  • OKX_API_KEY
    → API密钥
  • 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 & send
typescript
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

ChainchainIndexChainchainIndex
Ethereum
1
Arbitrum
42161
BSC
56
Base
8453
Polygon
137
Solana
501
链名称chainIndex链名称chainIndex
Ethereum
1
Arbitrum
42161
BSC
56
Base
8453
Polygon
137
Solana
501

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
ChainNative Token Address
EVM (Ethereum, BSC, Polygon, Arbitrum, Base, etc.)
0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
Solana
11111111111111111111111111111111
Sui
0x2::sui::SUI
Tron
T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb
Ton
EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c
WARNING — Solana native SOL: The correct address is
11111111111111111111111111111111
(Solana system program). Do NOT use
So11111111111111111111111111111111111111112
(wSOL SPL token) — it is a different token and will cause swap failures (
custom program error: 0xb
).
重要提示:每条链在OKX DEX API中都有特定的原生代币地址。使用错误地址(例如,使用wSOL SPL代币地址而非Solana系统程序地址)会导致兑换交易失败。参考:DEX聚合常见问题
链名称原生代币地址
EVM链(Ethereum、BSC、Polygon、Arbitrum、Base等)
0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
Solana
11111111111111111111111111111111
Sui
0x2::sui::SUI
Tron
T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb
Ton
EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c
警告——Solana原生SOL:正确地址为
11111111111111111111111111111111
(Solana系统程序)。切勿使用
So11111111111111111111111111111111111111112
(wSOL SPL代币)——这是不同的代币,会导致兑换失败(错误码:
custom program error: 0xb
)。

Endpoint Index

接口索引

#MethodPathDocs
1GET
/api/v6/dex/aggregator/supported/chain
dex-get-aggregator-supported-chains
2GET
/api/v6/dex/aggregator/get-liquidity
dex-get-liquidity
3GET
/api/v6/dex/aggregator/approve-transaction
dex-approve-transaction
4GET
/api/v6/dex/aggregator/quote
dex-get-quote
5GET
/api/v6/dex/aggregator/swap-instruction
dex-solana-swap-instruction
6GET
/api/v6/dex/aggregator/swap
dex-swap
Error Codes: DEX Error Codes
序号请求方法路径文档
1GET
/api/v6/dex/aggregator/supported/chain
dex-get-aggregator-supported-chains
2GET
/api/v6/dex/aggregator/get-liquidity
dex-get-liquidity
3GET
/api/v6/dex/aggregator/approve-transaction
dex-approve-transaction
4GET
/api/v6/dex/aggregator/quote
dex-get-quote
5GET
/api/v6/dex/aggregator/swap-instruction
dex-solana-swap-instruction
6GET
/api/v6/dex/aggregator/swap
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:
  • tokenContractAddress
    from step 1 →
    toTokenAddress
    in steps 3-4
  • SOL native address =
    "11111111111111111111111111111111"
    (Solana system program) →
    fromTokenAddress
    . Do NOT use
    So11111111111111111111111111111111111111112
    (wSOL) — see Native Token Addresses.
  • Amount
    1 SOL
    =
    "1000000000"
    (9 decimals) →
    amount
    param
  • balance
    from step 2 is UI units; swap needs minimal units → multiply by
    10^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的
    tokenContractAddress
    → 步骤3-4的
    toTokenAddress
  • Solana原生SOL地址 =
    "11111111111111111111111111111111"
    (Solana系统程序)→
    fromTokenAddress
    。切勿使用
    So11111111111111111111111111111111111111112
    (wSOL)——详见原生代币地址
  • 金额
    1 SOL
    =
    "1000000000"
    (9位小数)→
    amount
    参数
  • 步骤2的
    balance
    是UI单位;兑换需要最小单位 → 乘以
    10^小数位数

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) → swap
1. 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 tx
1. 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 tx
1. 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
    chainIndex
    -> ask which chain
  • Missing token addresses -> use
    okx-dex-token
    /market/token/search
    to resolve name → address
  • 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
    /quote
    , display estimated results
    • Expected output, gas estimate, price impact, routing path
    • Check
      isHoneyPot
      and
      taxRate
      — surface safety info to users
  • Confirmation phase: wait for user approval before proceeding
  • Approval phase (EVM only): check/execute approve if selling non-native token
  • Execution phase: call
    /swap
    (EVM) or
    /swap-instruction
    (Solana), return tx data for signing
  • 报价阶段:调用
    /quote
    ,展示估算结果
    • 预计到账金额、gas估算、价格影响、兑换路径
    • 检查
      isHoneyPot
      taxRate
      —— 向用户展示安全信息
  • 确认阶段:等待用户确认后再继续
  • 授权阶段(仅EVM链):如果出售的是非原生代币,检查/执行授权
  • 执行阶段:调用
    /swap
    (EVM链)或
    /swap-instruction
    (Solana链),返回供签名的交易数据

Step 4: Suggest Next Steps

步骤4:建议后续操作

After displaying results, suggest 2-3 relevant follow-up actions based on the swap phase just completed:
Just completedSuggest
/aggregator/quote
(quote only, not yet confirmed)
1. Check wallet balance first →
okx-wallet-portfolio
2. View price chart before deciding →
okx-dex-market
3. Proceed with swap → continue approve + swap (this skill)
Swap executed successfully1. Verify updated balance →
okx-wallet-portfolio
2. Check price of the token just received →
okx-dex-market
3. Swap another token → new swap flow (this skill)
/aggregator/get-liquidity
1. Get a swap quote →
/aggregator/quote
(this skill)
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个相关的后续操作:
刚完成的操作建议操作
/aggregator/quote
(仅获取报价,尚未确认)
1. 先检查钱包余额 →
okx-wallet-portfolio
2. 查看价格走势后再做决定 →
okx-dex-market
3. 继续兑换 → 执行授权+兑换(本技能)
兑换执行成功1. 验证更新后的余额 →
okx-wallet-portfolio
2. 查看刚收到代币的价格 →
okx-dex-market
3. 兑换其他代币 → 启动新的兑换流程(本技能)
/aggregator/get-liquidity
1. 获取兑换报价 →
/aggregator/quote
(本技能)
以对话形式呈现,例如:“兑换完成!要不要检查更新后的余额?” —— 切勿向用户暴露技能名称或接口路径。

API Reference

API参考

1. GET /aggregator/supported/chain

1. GET /aggregator/supported/chain

ParamTypeRequiredDescription
chainIndex
StringNoFilter to a specific chain (e.g.,
"1"
)
Response:
FieldTypeDescription
data[].chainIndex
StringChain unique identifier (e.g., "1")
data[].chainName
StringChain name (e.g., "Ethereum")
data[].dexTokenApproveAddress
StringOKX DEX token approve contract address
参数类型是否必填描述
chainIndex
String过滤特定链(例如:
"1"
响应
字段类型描述
data[].chainIndex
String链唯一标识符(例如:"1")
data[].chainName
String链名称(例如:"Ethereum")
data[].dexTokenApproveAddress
StringOKX DEX代币授权合约地址

2. GET /aggregator/get-liquidity

2. GET /aggregator/get-liquidity

ParamTypeRequiredDescription
chainIndex
StringYesChain ID
Response:
FieldTypeDescription
data[].id
StringLiquidity pool ID
data[].name
StringPool name (e.g., "Uniswap V3")
data[].logo
StringPool logo URL
参数类型是否必填描述
chainIndex
String链ID
响应
字段类型描述
data[].id
String流动性池ID
data[].name
String池名称(例如:"Uniswap V3")
data[].logo
String池Logo URL

3. GET /aggregator/approve-transaction

3. GET /aggregator/approve-transaction

ParamTypeRequiredDescription
chainIndex
StringYesChain ID
tokenContractAddress
StringYesToken to approve
approveAmount
StringYesAmount in minimal units
Response:
FieldTypeDescription
data[].data
StringApproval calldata (
approve(dexContractAddress, amount)
)
data[].dexContractAddress
StringDEX router address (the spender, already encoded in calldata). NOT the tx
to
— send tx to the token contract
data[].gasLimit
StringGas limit. May underestimate — use simulation or ×1.5
data[].gasPrice
StringGas price in wei
参数类型是否必填描述
chainIndex
String链ID
tokenContractAddress
String要授权的代币
approveAmount
String最小单位的金额
响应
字段类型描述
data[].data
String授权调用数据(
approve(dexContractAddress, amount)
data[].dexContractAddress
StringDEX路由地址(授权对象,已编码在调用数据中)。并非交易的
to
地址 —— 交易需发送到代币合约
data[].gasLimit
StringGas上限。可能低估 —— 建议使用模拟值或乘以1.5
data[].gasPrice
StringGas价格(wei单位)

4. GET /aggregator/quote

4. GET /aggregator/quote

ParamTypeRequiredDescription
chainIndex
StringYesChain ID
amount
StringYesAmount in minimal units (sell amount if exactIn, buy amount if exactOut)
swapMode
StringYes
exactIn
(default) or
exactOut
fromTokenAddress
StringYesToken to sell
toTokenAddress
StringYesToken to buy
Optional params:
dexIds
,
directRoute
,
priceImpactProtectionPercent
(default 90%),
feePercent
(max 10 Solana, 3 others).
Response key fields:
toTokenAmount
(output minimal units),
fromTokenAmount
,
estimateGasFee
,
tradeFee
(USD estimate),
priceImpactPercent
,
router
,
dexRouterList
,
fromToken
/
toToken
(each has
isHoneyPot
,
taxRate
,
decimal
,
tokenUnitPrice
). Full fields: see docs.
参数类型是否必填描述
chainIndex
String链ID
amount
String最小单位的金额(exactIn模式下为出售金额,exactOut模式下为购买金额)
swapMode
String
exactIn
(默认)或
exactOut
fromTokenAddress
String要出售的代币
toTokenAddress
String要购买的代币
可选参数:
dexIds
directRoute
priceImpactProtectionPercent
(默认90%)、
feePercent
(Solana链最高10,其他链最高3)。
响应关键字段
toTokenAmount
(输出最小单位)、
fromTokenAmount
estimateGasFee
tradeFee
(USD估算)、
priceImpactPercent
router
dexRouterList
fromToken
/
toToken
(包含
isHoneyPot
taxRate
decimal
tokenUnitPrice
)。完整字段:查看文档

5. GET /aggregator/swap-instruction (Solana only)

5. GET /aggregator/swap-instruction(仅Solana链)

ParamTypeRequiredDescription
chainIndex
StringYesMust be
"501"
(Solana)
amount
StringYesAmount in minimal units
fromTokenAddress
StringYesToken to sell
toTokenAddress
StringYesToken to buy
userWalletAddress
StringYesUser's wallet
slippagePercent
StringYes0 to <100
Optional params:
autoSlippage
,
computeUnitPrice
,
computeUnitLimit
,
dexIds
,
swapReceiverAddress
,
feePercent
,
priceImpactProtectionPercent
.
Response key fields:
instructionLists[]
(each has
data
,
accounts
,
programId
),
addressLookupTableAccount
,
routerResult
(same as /quote),
tx
(
minReceiveAmount
,
slippagePercent
),
wsolRentFee
. Full fields: see docs.
参数类型是否必填描述
chainIndex
String必须为
"501"
(Solana链)
amount
String最小单位的金额
fromTokenAddress
String要出售的代币
toTokenAddress
String要购买的代币
userWalletAddress
String用户钱包地址
slippagePercent
String0到<100
可选参数:
autoSlippage
computeUnitPrice
computeUnitLimit
dexIds
swapReceiverAddress
feePercent
priceImpactProtectionPercent
响应关键字段
instructionLists[]
(包含
data
accounts
programId
)、
addressLookupTableAccount
routerResult
(与
/quote
相同)、
tx
minReceiveAmount
slippagePercent
)、
wsolRentFee
。完整字段:查看文档

6. GET /aggregator/swap (EVM + Solana)

6. GET /aggregator/swap(EVM链+Solana链)

Note: This endpoint works for all chains including Solana.
/swap-instruction
is a Solana-specific alternative that returns deserialized instructions instead of a serialized transaction.
ParamTypeRequiredDescription
chainIndex
StringNoChain ID. Technically optional but strongly recommended — always pass it.
amount
StringYesAmount in minimal units
swapMode
StringYes
exactIn
(default) or
exactOut
fromTokenAddress
StringYesToken to sell
toTokenAddress
StringYesToken to buy
slippagePercent
StringYes0-100 (EVM), 0-<100 (Solana)
userWalletAddress
StringYesUser's wallet
Optional params:
gasLevel
(
average
/
fast
/
slow
),
computeUnitPrice
,
computeUnitLimit
,
tips
(Jito, 0.0000000001-2 SOL; use
0
if
computeUnitPrice
is set),
dexIds
,
autoSlippage
,
maxAutoSlippagePercent
,
swapReceiverAddress
,
feePercent
,
priceImpactProtectionPercent
(default 90%),
approveTransaction
(Boolean, combine approve+swap in one call),
approveAmount
(used with
approveTransaction
).
Response key fields:
routerResult
(same as /quote),
tx
from
,
to
,
data
(hex-encoded for EVM, base58-encoded for Solana),
gas
,
gasPrice
,
maxPriorityFeePerGas
(EIP-1559),
value
,
minReceiveAmount
,
maxSpendAmount
,
slippagePercent
,
signatureData
. Full fields: see docs.
注意:本接口适用于所有链包括Solana链。
/swap-instruction
是Solana链专用的替代接口,返回反序列化的指令而非序列化交易。
参数类型是否必填描述
chainIndex
String链ID。技术上可选但强烈建议传入。
amount
String最小单位的金额
swapMode
String
exactIn
(默认)或
exactOut
fromTokenAddress
String要出售的代币
toTokenAddress
String要购买的代币
slippagePercent
String0-100(EVM链),0-<100(Solana链)
userWalletAddress
String用户钱包地址
可选参数:
gasLevel
average
/
fast
/
slow
)、
computeUnitPrice
computeUnitLimit
tips
(Jito,0.0000000001-2 SOL;如果设置了
computeUnitPrice
则传
0
)、
dexIds
autoSlippage
maxAutoSlippagePercent
swapReceiverAddress
feePercent
priceImpactProtectionPercent
(默认90%)、
approveTransaction
(布尔值,将授权+兑换合并为一次调用)、
approveAmount
(与
approveTransaction
配合使用)。
响应关键字段
routerResult
(与
/quote
相同)、
tx
——
from
to
data
(EVM链为十六进制编码,Solana链为base58编码)、
gas
gasPrice
maxPriorityFeePerGas
(EIP-1559)、
value
minReceiveAmount
maxSpendAmount
slippagePercent
signatureData
。完整字段:查看文档

Input / 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 broadcasts
User 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:
    isHoneyPot = true
    — block trade and warn user
  • Tax token:
    taxRate
    non-zero — display to user (e.g. 5% buy tax)
  • Insufficient balance: use
    okx-wallet-portfolio
    to check first, show current balance, suggest adjusting amount
  • exactOut not supported: only Ethereum/Base/BSC/Arbitrum — prompt user to use
    exactIn
  • Solana chain:
    /swap-instruction
    returns deserialized instructions (more control);
    /swap
    also works but returns a serialized transaction
  • Solana native SOL address: Must use
    11111111111111111111111111111111
    (system program), NOT
    So11111111111111111111111111111111111111112
    (wSOL). Using wSOL address causes
    custom program error: 0xb
    on-chain failures. See DEX Aggregation FAQ.
  • 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
    —— 阻止交易并警告用户
  • 手续费代币
    taxRate
    非零 —— 向用户展示(例如5%买入手续费)
  • 余额不足:先使用
    okx-wallet-portfolio
    检查,显示当前余额,建议调整金额
  • 不支持exactOut:仅Ethereum/Base/BSC/Arbitrum链支持 —— 提示用户使用
    exactIn
  • Solana链
    /swap-instruction
    返回反序列化指令(更可控);
    /swap
    也可用但返回序列化交易
  • Solana原生SOL地址:必须使用
    11111111111111111111111111111111
    (系统程序),切勿使用
    So11111111111111111111111111111111111111112
    (wSOL)。使用wSOL地址会导致链上失败,错误码
    custom program error: 0xb
    。详见DEX聚合常见问题
  • 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
  • minReceiveAmount
    in both UI units and USD
  • Price impact as percentage
  • 输入/输出金额使用UI单位(
    1.5 ETH
    3,200 USDC
  • 内部API参数使用最小单位(
    1 USDC
    =
    "1000000"
    1 ETH
    =
    "1000000000000000000"
  • Gas费用以USD显示
  • minReceiveAmount
    同时显示UI单位和USD
  • 价格影响以百分比显示

Global Notes

全局注意事项

  • All endpoints are GET — no POST in the aggregator family
  • Amounts must be in minimal units (wei/lamports)
  • exactOut
    only on Ethereum(
    1
    )/Base(
    8453
    )/BSC(
    56
    )/Arbitrum(
    42161
    )
  • /swap-instruction
    is Solana-only
  • Check
    isHoneyPot
    and
    taxRate
    — surface safety info to users
  • 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)
  • exactOut
    仅支持Ethereum(
    1
    )/Base(
    8453
    )/BSC(
    56
    )/Arbitrum(
    42161
    )
  • /swap-instruction
    仅适用于Solana链
  • 检查
    isHoneyPot
    taxRate
    —— 向用户展示安全信息
  • Solana推荐人钱包需要存入SOL激活
  • TON链的佣金池支持有限(不包含Stonfi V1)
  • EVM合约地址必须为全小写
  • 代币搜索 -> 使用
    okx-dex-token
  • 市场价格 -> 使用
    okx-dex-market
  • 余额查询 -> 使用
    okx-wallet-portfolio
  • 交易广播 -> 使用
    okx-onchain-gateway