okx-onchain-gateway

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

OKX Onchain Gateway API

OKX 链上网关API

6 endpoints for gas estimation, transaction simulation, broadcasting, and order tracking.
Base URL:
https://web3.okx.com
Base paths:
/api/v6/dex/pre-transaction
and
/api/v6/dex/post-transaction
Auth: HMAC-SHA256 signature, 4 headers required (
OK-ACCESS-KEY
,
OK-ACCESS-SIGN
,
OK-ACCESS-PASSPHRASE
,
OK-ACCESS-TIMESTAMP
)
Note: Endpoints #1-2 are GET requests, endpoints #3-5 are POST requests, endpoint #6 is GET.
用于燃气费估算、交易模拟、广播及订单追踪的6个端点。
Base URL:
https://web3.okx.com
基础路径:
/api/v6/dex/pre-transaction
/api/v6/dex/post-transaction
身份验证: HMAC-SHA256签名,需4个请求头 (
OK-ACCESS-KEY
,
OK-ACCESS-SIGN
,
OK-ACCESS-PASSPHRASE
,
OK-ACCESS-TIMESTAMP
)
注意: 端点#1-2为 GET 请求,端点#3-5为 POST 请求,端点#6为 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:
//   GET  → body = "", requestPath includes query string (e.g., "/api/v6/dex/pre-transaction/gas-price?chainIndex=1")
//   POST → body = JSON string of request body, requestPath is path only (e.g., "/api/v6/dex/pre-transaction/gas-limit")
//   Note: Endpoints #1-2, #6 are GET; endpoints #3-5 are POST
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';

// Signature rule:
//   GET  → body = "", requestPath includes query string (e.g., "/api/v6/dex/pre-transaction/gas-price?chainIndex=1")
//   POST → body = JSON string of request body, requestPath is path only (e.g., "/api/v6/dex/pre-transaction/gas-limit")
//   Note: Endpoints #1-2, #6 are GET; endpoints #3-5 are POST
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;
}
响应格式:
{ "code": "0", "data": [...], "msg": "" }
code
=
"0"
表示请求成功。

Developer Quickstart

开发者快速入门

Get Gas Price

获取燃气价格

typescript
// Get current gas price on Ethereum
const gasPrice = await okxFetch('GET', '/api/v6/dex/pre-transaction/gas-price?' + new URLSearchParams({
  chainIndex: '1',
}));
// → gasPrice[].normal, gasPrice[].min, gasPrice[].max (legacy)
// → gasPrice[].eip1559Protocol.suggestBaseFee, .proposePriorityFee (EIP-1559)
console.log(`Gas price: ${gasPrice[0].eip1559Protocol?.suggestBaseFee ?? gasPrice[0].normal} wei`);
typescript
// 获取以太坊当前燃气价格
const gasPrice = await okxFetch('GET', '/api/v6/dex/pre-transaction/gas-price?' + new URLSearchParams({
  chainIndex: '1',
}));
// → gasPrice[].normal, gasPrice[].min, gasPrice[].max (legacy)
// → gasPrice[].eip1559Protocol.suggestBaseFee, .proposePriorityFee (EIP-1559)
console.log(`Gas price: ${gasPrice[0].eip1559Protocol?.suggestBaseFee ?? gasPrice[0].normal} wei`);

Broadcast a Signed Transaction

广播已签名交易

typescript
// Broadcast a signed EVM transaction
const result = await okxFetch('POST', '/api/v6/dex/pre-transaction/broadcast-transaction', {
  signedTx: '0xf86c...signed_hex',
  chainIndex: '1',
  address: '0xYourWallet',
});
// → result[].orderId — use with /post-transaction/orders to track
console.log(`Broadcast success, orderId: ${result[0].orderId}`);
typescript
// 广播已签名的EVM交易
const result = await okxFetch('POST', '/api/v6/dex/pre-transaction/broadcast-transaction', {
  signedTx: '0xf86c...signed_hex',
  chainIndex: '1',
  address: '0xYourWallet',
});
// → result[].orderId — 用于配合 /post-transaction/orders 接口追踪订单
console.log(`Broadcast success, orderId: ${result[0].orderId}`);

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

Endpoint Index

端点索引

#MethodPathDocs
1GET
/api/v6/dex/pre-transaction/supported/chain
onchain-gateway-api-chains
2GET
/api/v6/dex/pre-transaction/gas-price
onchain-gateway-api-gas-price
3POST
/api/v6/dex/pre-transaction/gas-limit
onchain-gateway-api-gas-limit
4POST
/api/v6/dex/pre-transaction/simulate
onchain-gateway-api-simulate-transaction
5POST
/api/v6/dex/pre-transaction/broadcast-transaction
onchain-gateway-api-broadcast-transaction
6GET
/api/v6/dex/post-transaction/orders
onchain-gateway-api-orders
#请求方法路径文档
1GET
/api/v6/dex/pre-transaction/supported/chain
onchain-gateway-api-chains
2GET
/api/v6/dex/pre-transaction/gas-price
onchain-gateway-api-gas-price
3POST
/api/v6/dex/pre-transaction/gas-limit
onchain-gateway-api-gas-limit
4POST
/api/v6/dex/pre-transaction/simulate
onchain-gateway-api-simulate-transaction
5POST
/api/v6/dex/pre-transaction/broadcast-transaction
onchain-gateway-api-broadcast-transaction
6GET
/api/v6/dex/post-transaction/orders
onchain-gateway-api-orders

Cross-Skill Workflows

跨Skill工作流

This skill is the final mile — it takes a signed transaction and sends it on-chain. It pairs with swap (to get tx data) and balance (to verify funds).
本Skill是最后一环——接收已签名的交易并将其发送至链上。它可与兑换(获取交易数据)和余额查询(验证资金)Skill配合使用。

Workflow A: Swap → Broadcast → Track

工作流A:兑换 → 广播 → 追踪

User: "Swap 1 ETH for USDC and broadcast it"
1. okx-dex-swap    /aggregator/swap                                → get tx calldata { from, to, data, value, gas }
       ↓ user signs the tx locally
2. okx-onchain-gateway /pre-transaction/broadcast-transaction      → broadcast signed tx → orderId
3. okx-onchain-gateway /post-transaction/orders                    → track order status until confirmed
Data handoff:
  • tx.data
    ,
    tx.to
    ,
    tx.value
    ,
    tx.gas
    from swap → user builds & signs →
    signedTx
    for broadcast
  • orderId
    from broadcast →
    orderId
    param in orders query
用户:"将1 ETH兑换为USDC并广播交易"
1. okx-dex-swap    /aggregator/swap                                → 获取交易调用数据 { from, to, data, value, gas }
       ↓ 用户本地签名交易
2. okx-onchain-gateway /pre-transaction/broadcast-transaction      → 广播已签名交易 → 获取orderId
3. okx-onchain-gateway /post-transaction/orders                    → 追踪订单状态直至确认
数据传递:
  • 从兑换Skill获取
    tx.data
    ,
    tx.to
    ,
    tx.value
    ,
    tx.gas
    → 用户构建并签名交易 → 生成
    signTx
    用于广播
  • 从广播接口获取
    orderId
    → 作为订单查询接口的
    orderId
    参数

Workflow B: Simulate → Broadcast → Track

工作流B:模拟 → 广播 → 追踪

User: "Simulate this transaction first, then broadcast if safe"
1. okx-onchain-gateway /pre-transaction/simulate                   → check if tx will succeed
       ↓ simulation passes (no revert)
2. okx-onchain-gateway /pre-transaction/broadcast-transaction      → broadcast signed tx
3. okx-onchain-gateway /post-transaction/orders                    → track order status
用户:"先模拟这笔交易,安全的话再广播"
1. okx-onchain-gateway /pre-transaction/simulate                   → 检查交易是否会成功
       ↓ 模拟通过(无回滚)
2. okx-onchain-gateway /pre-transaction/broadcast-transaction      → 广播已签名交易
3. okx-onchain-gateway /post-transaction/orders                    → 追踪订单状态

Workflow C: Balance Check → Swap → Broadcast

工作流C:余额检查 → 兑换 → 广播

User: "Check if I have enough ETH, swap for USDC, then send it"
1. okx-wallet-portfolio /balance/token-balances-by-address         → verify ETH balance
       ↓ sufficient balance confirmed
2. okx-dex-swap    /aggregator/swap                                → get swap tx calldata
       ↓ user signs
3. okx-onchain-gateway /pre-transaction/broadcast-transaction      → broadcast
4. okx-onchain-gateway /post-transaction/orders                    → track
用户:"检查我是否有足够的ETH,兑换为USDC后发送"
1. okx-wallet-portfolio /balance/token-balances-by-address         → 验证ETH余额
       ↓ 确认余额充足
2. okx-dex-swap    /aggregator/swap                                → 获取兑换交易调用数据
       ↓ 用户签名
3. okx-onchain-gateway /pre-transaction/broadcast-transaction      → 广播交易
4. okx-onchain-gateway /post-transaction/orders                    → 追踪订单

Operation Flow

操作流程

Step 1: Identify Intent

步骤1:识别用户意图

  • Estimate gas for a chain →
    GET /pre-transaction/gas-price
  • Estimate gas limit for a specific tx →
    POST /pre-transaction/gas-limit
  • Test if a tx will succeed →
    POST /pre-transaction/simulate
  • Broadcast a signed tx →
    POST /pre-transaction/broadcast-transaction
  • Track a broadcast order →
    GET /post-transaction/orders
  • Check supported chains →
    GET /pre-transaction/supported/chain
  • 估算某条公链的燃气费 →
    GET /pre-transaction/gas-price
  • 估算特定交易的燃气限额 →
    POST /pre-transaction/gas-limit
  • 测试交易是否会成功 →
    POST /pre-transaction/simulate
  • 广播已签名交易 →
    POST /pre-transaction/broadcast-transaction
  • 追踪广播订单 →
    GET /post-transaction/orders
  • 检查支持的公链 →
    GET /pre-transaction/supported/chain

Step 2: Collect Parameters

步骤2:收集参数

  • Missing
    chainIndex
    → ask which chain
  • Missing
    signedTx
    → remind user to sign the transaction first (this API does NOT sign)
  • Missing wallet
    address
    → ask user
  • For gas-limit / simulate → need
    fromAddress
    ,
    toAddress
    ,
    txAmount
    ,
    extJson.inputData
  • For orders query → need
    address
    and
    chainIndex
    , optionally
    orderId
  • 缺少
    chainIndex
    → 询问用户具体公链
  • 缺少
    signedTx
    → 提醒用户先签名交易(本API不提供签名功能)
  • 缺少钱包
    address
    → 询问用户
  • 燃气限额估算/交易模拟 → 需要
    fromAddress
    ,
    toAddress
    ,
    txAmount
    ,
    extJson.inputData
  • 订单查询 → 需要
    address
    chainIndex
    ,可选参数
    orderId

Step 3: Execute

步骤3:执行操作

  • Gas estimation: call
    /gas-price
    or
    /gas-limit
    , display results
  • Simulation: call
    /simulate
    , check for revert or success
  • Broadcast: call
    /broadcast-transaction
    with signed tx, return
    orderId
  • Tracking: call
    /orders
    , display order status
  • 燃气费估算: 调用
    /gas-price
    /gas-limit
    接口,展示结果
  • 交易模拟: 调用
    /simulate
    接口,检查是否回滚或成功
  • 交易广播: 携带已签名交易调用
    /broadcast-transaction
    接口,返回
    orderId
  • 订单追踪: 调用
    /orders
    接口,展示订单状态

Step 4: Suggest Next Steps

步骤4:建议后续操作

After displaying results, suggest 2-3 relevant follow-up actions based on the endpoint just called:
Just completedSuggest
/pre-transaction/gas-price
1. Estimate gas limit for a specific tx →
/pre-transaction/gas-limit
(this skill) 2. Get a swap quote →
okx-dex-swap
3. Check wallet balance →
okx-wallet-portfolio
/pre-transaction/gas-limit
1. Simulate the transaction →
/pre-transaction/simulate
(this skill) 2. Proceed to broadcast →
/pre-transaction/broadcast-transaction
(this skill)
/pre-transaction/simulate
1. Broadcast the transaction →
/pre-transaction/broadcast-transaction
(this skill) 2. Adjust and re-simulate if failed →
/pre-transaction/simulate
(this skill)
/pre-transaction/broadcast-transaction
1. Track order status →
/post-transaction/orders
(this skill) 2. Check updated wallet balance →
okx-wallet-portfolio
/post-transaction/orders
1. Check wallet balance after confirmation →
okx-wallet-portfolio
2. View price of received token →
okx-dex-market
3. Execute another swap →
okx-dex-swap
Present conversationally, e.g.: "Transaction broadcast! Would you like to track the order status?" — never expose skill names or endpoint paths to the user.
展示结果后,根据刚调用的接口,建议2-3个相关后续操作:
刚完成的操作建议操作
/pre-transaction/gas-price
1. 估算特定交易的燃气限额 →
/pre-transaction/gas-limit
(本Skill) 2. 获取兑换报价 →
okx-dex-swap
3. 检查钱包余额 →
okx-wallet-portfolio
/pre-transaction/gas-limit
1. 模拟交易 →
/pre-transaction/simulate
(本Skill) 2. 继续广播交易 →
/pre-transaction/broadcast-transaction
(本Skill)
/pre-transaction/simulate
1. 广播交易 →
/pre-transaction/broadcast-transaction
(本Skill) 2. 调整参数后重新模拟 →
/pre-transaction/simulate
(本Skill)
/pre-transaction/broadcast-transaction
1. 追踪订单状态 →
/post-transaction/orders
(本Skill) 2. 检查更新后的钱包余额 →
okx-wallet-portfolio
/post-transaction/orders
1. 确认后检查钱包余额 →
okx-wallet-portfolio
2. 查询收到代币的价格 →
okx-dex-market
3. 执行另一笔兑换 →
okx-dex-swap
需以对话形式呈现,例如:"交易已广播!需要帮您追踪订单状态吗?" —— 绝不能向用户暴露Skill名称或接口路径。

API Reference

API参考

1. GET /pre-transaction/supported/chain

1. GET /pre-transaction/supported/chain

No request parameters.
Response:
FieldTypeDescription
data[].chainIndex
StringChain unique identifier (e.g., "1")
data[].name
StringChain name (e.g., "Ethereum")
data[].logoUrl
StringChain logo URL
data[].shortName
StringChain short name (e.g., "ETH")
无请求参数。
响应:
字段类型描述
data[].chainIndex
字符串公链唯一标识(例如:"1")
data[].name
字符串公链名称(例如:"Ethereum")
data[].logoUrl
字符串公链Logo地址
data[].shortName
字符串公链简称(例如:"ETH")

2. GET /pre-transaction/gas-price

2. GET /pre-transaction/gas-price

ParamTypeRequiredDescription
chainIndex
StringYesChain ID (e.g.,
"1"
)
Response:
FieldTypeDescription
data[].normal
StringNormal gas price (legacy)
data[].min
StringMinimum gas price
data[].max
StringMaximum gas price
data[].supporteip1559
BooleanWhether EIP-1559 is supported
data[].eip1559Protocol.suggestBaseFee
StringSuggested base fee
data[].eip1559Protocol.baseFee
StringCurrent base fee
data[].eip1559Protocol.proposePriorityFee
StringProposed priority fee
data[].eip1559Protocol.safePriorityFee
StringSafe (slow) priority fee
data[].eip1559Protocol.fastPriorityFee
StringFast priority fee
For Solana chains, response includes:
proposePriorityFee
,
safePriorityFee
,
fastPriorityFee
,
extremePriorityFee
.
json
{
  "code": "0",
  "data": [{
    "normal": "20000000000",
    "min": "15000000000",
    "max": "30000000000",
    "supporteip1559": true,
    "eip1559Protocol": {
      "suggestBaseFee": "18000000000",
      "baseFee": "18000000000",
      "proposePriorityFee": "2000000000",
      "safePriorityFee": "1000000000",
      "fastPriorityFee": "3000000000"
    }
  }],
  "msg": ""
}
参数类型是否必填描述
chainIndex
字符串公链ID(例如:
"1"
响应:
字段类型描述
data[].normal
字符串常规燃气价格(legacy)
data[].min
字符串最低燃气价格
data[].max
字符串最高燃气价格
data[].supporteip1559
布尔值是否支持EIP-1559
data[].eip1559Protocol.suggestBaseFee
字符串建议基础费用
data[].eip1559Protocol.baseFee
字符串当前基础费用
data[].eip1559Protocol.proposePriorityFee
字符串建议优先费用
data[].eip1559Protocol.safePriorityFee
字符串安全(慢速)优先费用
data[].eip1559Protocol.fastPriorityFee
字符串快速优先费用
对于Solana公链,响应还包含:
proposePriorityFee
,
safePriorityFee
,
fastPriorityFee
,
extremePriorityFee
json
{
  "code": "0",
  "data": [{
    "normal": "20000000000",
    "min": "15000000000",
    "max": "30000000000",
    "supporteip1559": true,
    "eip1559Protocol": {
      "suggestBaseFee": "18000000000",
      "baseFee": "18000000000",
      "proposePriorityFee": "2000000000",
      "safePriorityFee": "1000000000",
      "fastPriorityFee": "3000000000"
    }
  }],
  "msg": ""
}

3. POST /pre-transaction/gas-limit

3. POST /pre-transaction/gas-limit

ParamTypeRequiredDescription
chainIndex
StringYesChain ID
fromAddress
StringYesSender address
toAddress
StringYesRecipient / contract address
txAmount
StringNoTransfer value in minimal units (default "0")
extJson
ObjectNoExtended parameters
extJson.inputData
StringNoEncoded calldata (for contract interactions)
Response:
FieldTypeDescription
data[].gasLimit
StringEstimated gas limit
json
{
  "code": "0",
  "data": [{ "gasLimit": "21000" }],
  "msg": ""
}
参数类型是否必填描述
chainIndex
字符串公链ID
fromAddress
字符串发送者地址
toAddress
字符串接收者/合约地址
txAmount
字符串转账金额(最小单位,默认"0")
extJson
对象扩展参数
extJson.inputData
字符串编码后的调用数据(用于合约交互)
响应:
字段类型描述
data[].gasLimit
字符串估算的燃气限额
json
{
  "code": "0",
  "data": [{ "gasLimit": "21000" }],
  "msg": ""
}

4. POST /pre-transaction/simulate

4. POST /pre-transaction/simulate

ParamTypeRequiredDescription
chainIndex
StringYesChain ID
fromAddress
StringYesSender address
toAddress
StringYesRecipient / contract address
txAmount
StringNoTransfer value in minimal units
gasPrice
StringNoGas price in wei (for legacy EVM txs)
priorityFee
StringNoPriority fee in micro-lamports (Solana only)
extJson
ObjectYesExtended parameters
extJson.inputData
StringYesEncoded calldata
Response:
FieldTypeDescription
data[].intention
StringTransaction intent description
data[].assetChange[]
ArrayAsset changes from the simulation
data[].assetChange[].assetType
StringAsset type
data[].assetChange[].name
StringToken name
data[].assetChange[].symbol
StringToken symbol
data[].assetChange[].decimals
NumberToken decimals
data[].assetChange[].address
StringToken contract address
data[].assetChange[].rawValue
StringRaw amount change
data[].gasUsed
StringGas consumed in simulation
data[].failReason
StringFailure reason (empty string = success)
data[].risks[]
ArrayRisk information (address, addressType)
json
{
  "code": "0",
  "data": [{
    "intention": "Token Swap",
    "assetChange": [{"assetType": "token", "name": "USDC", "symbol": "USDC", "decimals": 6, "address": "0xa0b8...", "rawValue": "-100000000"}],
    "gasUsed": "145000",
    "failReason": "",
    "risks": []
  }],
  "msg": ""
}
参数类型是否必填描述
chainIndex
字符串公链ID
fromAddress
字符串发送者地址
toAddress
字符串接收者/合约地址
txAmount
字符串转账金额(最小单位)
gasPrice
字符串燃气价格(wei单位,适用于legacy EVM交易)
priorityFee
字符串优先费用(微lamports单位,仅Solana)
extJson
对象扩展参数
extJson.inputData
字符串编码后的调用数据
响应:
字段类型描述
data[].intention
字符串交易意图描述
data[].assetChange[]
数组模拟交易后的资产变化
data[].assetChange[].assetType
字符串资产类型
data[].assetChange[].name
字符串代币名称
data[].assetChange[].symbol
字符串代币符号
data[].assetChange[].decimals
数字代币小数位数
data[].assetChange[].address
字符串代币合约地址
data[].assetChange[].rawValue
字符串原始金额变化
data[].gasUsed
字符串模拟交易消耗的燃气
data[].failReason
字符串失败原因(空字符串表示成功)
data[].risks[]
数组风险信息(address, addressType)
json
{
  "code": "0",
  "data": [{
    "intention": "Token Swap",
    "assetChange": [{"assetType": "token", "name": "USDC", "symbol": "USDC", "decimals": 6, "address": "0xa0b8...", "rawValue": "-100000000"}],
    "gasUsed": "145000",
    "failReason": "",
    "risks": []
  }],
  "msg": ""
}

5. POST /pre-transaction/broadcast-transaction

5. POST /pre-transaction/broadcast-transaction

ParamTypeRequiredDescription
signedTx
StringYesFully signed transaction (hex for EVM, base58 for Solana)
chainIndex
StringYesChain ID
address
StringYesSender wallet address
extraData
StringNoJSON string of extra options (must
JSON.stringify
before sending)
extraData
JSON fields:
FieldTypeDescription
enableMevProtection
BooleanEnable MEV protection (ETH/BSC/SOL/BASE)
jitoSignedTx
StringJito signed transaction (Solana)
Response:
FieldTypeDescription
data[].orderId
StringOKX order tracking ID
data[].txHash
StringOn-chain transaction hash
json
{
  "code": "0",
  "data": [{ "orderId": "123456789", "txHash": "0xabc...def" }],
  "msg": ""
}
参数类型是否必填描述
signedTx
字符串已完全签名的交易(EVM为十六进制,Solana为base58编码)
chainIndex
字符串公链ID
address
字符串发送者钱包地址
extraData
字符串扩展选项的JSON字符串(发送前需使用
JSON.stringify
处理)
extraData
JSON字段:
字段类型描述
enableMevProtection
布尔值启用MEV保护(支持ETH/BSC/SOL/BASE)
jitoSignedTx
字符串Jito签名交易(仅Solana)
响应:
字段类型描述
data[].orderId
字符串OKX订单追踪ID
data[].txHash
字符串链上交易哈希
json
{
  "code": "0",
  "data": [{ "orderId": "123456789", "txHash": "0xabc...def" }],
  "msg": ""
}

6. GET /post-transaction/orders

6. GET /post-transaction/orders

ParamTypeRequiredDescription
address
StringYesWallet address
chainIndex
StringYesChain ID
orderId
StringNoSpecific order ID (from broadcast response)
txStatus
StringNoFilter by status:
1
=Pending,
2
=Success,
3
=Failed
cursor
StringNoPagination cursor
limit
StringNoMax results per page (default 20)
Response:
FieldTypeDescription
data[].cursor
StringPagination cursor for next page
data[].orders[]
ArrayOrder list (nested under each data element)
data[].orders[].orderId
StringOrder ID
data[].orders[].txHash
StringOn-chain transaction hash
data[].orders[].chainIndex
StringChain ID
data[].orders[].address
StringSender address
data[].orders[].txStatus
StringOrder status:
1
=Pending,
2
=Success,
3
=Failed
data[].orders[].failReason
StringFailure reason (if failed)
json
{
  "code": "0",
  "data": [{
    "cursor": "1",
    "orders": [{
      "orderId": "123456789",
      "txHash": "0xabc...def",
      "chainIndex": "1",
      "address": "0x...",
      "txStatus": "2",
      "failReason": ""
    }]
  }],
  "msg": ""
}
参数类型是否必填描述
address
字符串钱包地址
chainIndex
字符串公链ID
orderId
字符串特定订单ID(来自广播接口响应)
txStatus
字符串按状态过滤:
1
=待处理,
2
=成功,
3
=失败
cursor
字符串分页游标
limit
字符串每页最大结果数(默认20)
响应:
字段类型描述
data[].cursor
字符串下一页的分页游标
data[].orders[]
数组订单列表(嵌套在每个data元素下)
data[].orders[].orderId
字符串订单ID
data[].orders[].txHash
字符串链上交易哈希
data[].orders[].chainIndex
字符串公链ID
data[].orders[].address
字符串发送者地址
data[].orders[].txStatus
字符串订单状态:
1
=待处理,
2
=成功,
3
=失败
data[].orders[].failReason
字符串失败原因(如果交易失败)
json
{
  "code": "0",
  "data": [{
    "cursor": "1",
    "orders": [{
      "orderId": "123456789",
      "txHash": "0xabc...def",
      "chainIndex": "1",
      "address": "0x...",
      "txStatus": "2",
      "failReason": ""
    }]
  }],
  "msg": ""
}

Input / Output Examples

输入/输出示例

User says: "What's the current gas price on Ethereum?"
GET /api/v6/dex/pre-transaction/gas-price?chainIndex=1
-> Display:
  Base fee: 18 Gwei
  Max fee: 25 Gwei
  Priority fee: 2 Gwei
User says: "Simulate this swap transaction before I send it"
POST /api/v6/dex/pre-transaction/simulate
Body: {
  "chainIndex": "1",
  "fromAddress": "0xYourWallet",
  "toAddress": "0xDexContract",
  "txAmount": "1000000000000000000",
  "extJson": { "inputData": "0x..." }
}
-> Display:
  Simulation: SUCCESS (failReason is empty)
  Estimated gas: 145,000
  Intent: Token Swap
User says: "Broadcast my signed transaction"
POST /api/v6/dex/pre-transaction/broadcast-transaction
Body: {
  "signedTx": "0xf86c...signed",
  "chainIndex": "1",
  "address": "0xYourWallet"
}
-> Display:
  Broadcast successful!
  Order ID: 123456789
  Tx Hash: 0xabc...def
User says: "Check the status of my broadcast order"
GET /api/v6/dex/post-transaction/orders?address=0xYourWallet&chainIndex=1&orderId=123456789
-> Response: data[0].orders[0] contains order details
-> Display:
  Order 123456789: Success (txStatus=2)
  Tx Hash: 0xabc...def
  Confirmed on-chain
用户提问: "以太坊当前的燃气价格是多少?"
GET /api/v6/dex/pre-transaction/gas-price?chainIndex=1
-> 展示:
  基础费用: 18 Gwei
  最高费用: 25 Gwei
  优先费用: 2 Gwei
用户提问: "在我发送之前先模拟这笔兑换交易"
POST /api/v6/dex/pre-transaction/simulate
Body: {
  "chainIndex": "1",
  "fromAddress": "0xYourWallet",
  "toAddress": "0xDexContract",
  "txAmount": "1000000000000000000",
  "extJson": { "inputData": "0x..." }
}
-> 展示:
  模拟结果: 成功(failReason为空)
  估算燃气消耗: 145,000
  交易意图: 代币兑换
用户提问: "广播我的已签名交易"
POST /api/v6/dex/pre-transaction/broadcast-transaction
Body: {
  "signedTx": "0xf86c...signed",
  "chainIndex": "1",
  "address": "0xYourWallet"
}
-> 展示:
  广播成功!
  订单ID: 123456789
  交易哈希: 0xabc...def
用户提问: "查询我广播的订单状态"
GET /api/v6/dex/post-transaction/orders?address=0xYourWallet&chainIndex=1&orderId=123456789
-> 响应: data[0].orders[0]包含订单详情
-> 展示:
  订单123456789: 成功(txStatus=2)
  交易哈希: 0xabc...def
  已在链上确认

Edge Cases

边缘情况

  • MEV protection: Broadcasting through OKX nodes may offer MEV protection on supported chains — confirm with OKX documentation for chain-specific behavior.
  • Solana special handling: Solana signed transactions use base58 encoding (not hex). Ensure the
    signedTx
    format matches the chain.
  • Chain not supported (81104): call
    /pre-transaction/supported/chain
    first to verify. Not all chains support all endpoints.
  • Node return failed (81451): the underlying blockchain node rejected the transaction. Common causes: insufficient gas, nonce too low, contract revert. Retry with corrected parameters.
  • Wallet type mismatch (81108): the address format does not match the chain (e.g., EVM address on Solana chain).
  • 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., swap → simulate → broadcast), 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
  • Transaction already broadcast: if the same
    signedTx
    is broadcast twice, the API may return an error or the same
    txHash
    — handle idempotently.
  • MEV保护: 通过OKX节点广播交易可能在支持的公链上提供MEV保护——请参考OKX文档确认各公链的具体行为。
  • Solana特殊处理: Solana已签名交易使用base58编码(而非十六进制)。确保
    signedTx
    格式与对应公链匹配。
  • 公链不支持(错误码81104): 先调用
    /pre-transaction/supported/chain
    接口验证。并非所有公链都支持所有端点。
  • 节点返回失败(错误码81451): 底层区块链节点拒绝了交易。常见原因:燃气不足、nonce值过低、合约回滚。修正参数后重试。
  • 钱包类型不匹配(错误码81108): 地址格式与公链不匹配(例如:在Solana链上使用EVM地址)。
  • 429请求超限: 使用指数退避策略并添加随机抖动。请参考Rate Limit & Fee Docs查看不同层级的RPS限制(试用版:1 RPS,初创版:2-50 RPS,企业版:自定义)。
  • 跨Skill流水线请求超限: 当跨多个Skill链式调用时(例如:兑换→模拟→广播),在请求之间添加300-500ms延迟以避免触发请求超限(错误码
    50011
    )。
  • 网络错误: 重试一次,然后提示用户稍后再试
  • 请求超时: 所有API调用必须设置10秒超时限制
  • 交易已广播: 如果同一
    signedTx
    被广播两次,API可能返回错误或相同的
    txHash
    ——需处理幂等性。

Amount Display Rules

金额展示规则

  • Gas prices in Gwei for EVM chains (
    18.5 Gwei
    ), never raw wei
  • Gas limit as integer (
    21000
    ,
    145000
    )
  • USD gas cost estimate when possible
  • Transaction values in UI units (
    1.5 ETH
    ), never base units
  • EVM公链的燃气价格以Gwei为单位(例如
    18.5 Gwei
    ),绝不显示原始wei值
  • 燃气限额以整数展示(例如
    21000
    ,
    145000
  • 尽可能展示以USD为单位的燃气成本估算
  • 交易金额以UI单位展示(例如
    1.5 ETH
    ),绝不显示基础单位

Global Notes

全局注意事项

  • This skill does NOT sign transactions — it only broadcasts pre-signed transactions
  • Amounts in API params use minimal units (wei/lamports)
  • Gas price fields: use
    eip1559Protocol.suggestBaseFee
    +
    eip1559Protocol.proposePriorityFee
    for EIP-1559 chains,
    normal
    for legacy
  • EVM contract addresses must be all lowercase
  • For swap quote and execution → use
    okx-dex-swap
  • For market prices → use
    okx-dex-market
  • For balance queries → use
    okx-wallet-portfolio
  • For token search → use
    okx-dex-token
  • For transaction broadcasting → use this skill (
    okx-onchain-gateway
    )
  • 本Skill不提供交易签名功能——仅广播已预先签名的交易
  • API参数中的金额使用最小单位(wei/lamports)
  • 燃气价格字段:对于支持EIP-1559的公链,使用
    eip1559Protocol.suggestBaseFee
    +
    eip1559Protocol.proposePriorityFee
    ;对于legacy公链,使用
    normal
  • EVM合约地址必须为全小写
  • 兑换报价和执行操作 → 使用
    okx-dex-swap
  • 市场价格查询 → 使用
    okx-dex-market
  • 余额查询 → 使用
    okx-wallet-portfolio
  • 代币搜索 → 使用
    okx-dex-token
  • 交易广播 → 使用本Skill (
    okx-onchain-gateway
    )