OKX DEX Aggregator Quote Skill
Overview
This skill generates production-ready code for fetching optimal swap quotes from the OKX DEX Aggregator API v6. The API finds the best price across multiple DEX protocols (Uniswap, SushiSwap, Curve, etc.) and returns detailed routing information including price impact, gas estimates, and token safety flags.
Key capabilities:
- Authenticated API requests with HMAC-SHA256 signing
- Correct handling of token decimals and amount formatting
- Support for
exactIn (fixed input) and exactOut (fixed output) swap modes
- Multi-chain support (Ethereum, BSC, Arbitrum, Base, Solana, and 20+ chains)
- Price impact protection and honeypot detection
- Fee/commission splitting configuration
Prerequisites
Required Credentials
Users must have an OKX Web3 API key set. The skill needs three values:
OKX_ACCESS_KEY — API key
OKX_SECRET_KEY — Secret key for HMAC signing
OKX_PASSPHRASE — Account passphrase
Environment
- Python:
requests, hmac, hashlib, base64, datetime (all stdlib except requests)
- Node.js:
axios or node-fetch, built-in crypto
- No additional blockchain dependencies required (this is a read-only quote endpoint)
API Endpoint
GET https://web3.okx.com/api/v6/dex/aggregator/quote
Workflow
Step 1: Validate User Input
Before constructing the API call, validate:
Chain ID (chainIndex) — Must be a supported chain. Common values:
1 = Ethereum
56 = BSC
137 = Polygon
42161 = Arbitrum
8453 = Base
130 = Unichain
501 = Solana
Token addresses — Must be valid contract addresses or the native token placeholder:
- Native tokens (ETH, BNB, etc.):
0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
- Contract tokens: Full 42-character hex address (EVM) or base58 (Solana)
Amount — MUST include token decimals. This is the #1 source of errors:
- 1 ETH (18 decimals) →
"1000000000000000000"
- 1 USDT (6 decimals) →
"1000000"
- 1 WBTC (8 decimals) →
"100000000"
- Formula:
amount_raw = human_amount * (10 ** token_decimals)
Swap mode — exactIn (default) or exactOut
exactOut only supported on: Ethereum, Base, BSC, Arbitrum
exactOut only works with Uniswap V2/V3 pools
Step 2: Construct Authentication Headers
OKX API requires HMAC-SHA256 signed requests with 4 headers:
OK-ACCESS-KEY: <api_key>
OK-ACCESS-SIGN: <hmac_signature>
OK-ACCESS-PASSPHRASE: <passphrase>
OK-ACCESS-TIMESTAMP: <iso8601_timestamp>
Signing algorithm:
timestamp = ISO 8601 UTC time (e.g., "2025-01-15T12:00:00.000Z")
prehash = timestamp + "GET" + request_path_with_query
signature = Base64(HMAC-SHA256(secret_key, prehash))
CRITICAL: The request_path_with_query must include the full path starting from /api/... plus the query string. Example:
/api/v6/dex/aggregator/quote?chainIndex=1&amount=1000000000000000000&fromTokenAddress=0xeee...&toTokenAddress=0xa0b...
Step 3: Send Request and Parse Response
Success response structure:
{
"code": "0",
"data": [{
"chainIndex": "1",
"fromToken": { "tokenSymbol": "ETH", "decimal": "18", ... },
"toToken": { "tokenSymbol": "USDC", "decimal": "6", ... },
"fromTokenAmount": "1000000000000000000",
"toTokenAmount": "3521432100",
"dexRouterList": [...],
"tradeFee": "2.45",
"estimateGasFee": "150000",
"priceImpactPercent": "-0.12"
}],
"msg": ""
}
Key fields to extract:
toTokenAmount — The amount you'll receive (in raw units with decimals)
tradeFee — Estimated network fee in USD
priceImpactPercent — Negative = losing value; large negative = danger
dexRouterList — Routing path through various DEX protocols
fromToken.isHoneyPot / toToken.isHoneyPot — Scam token flag
fromToken.taxRate / toToken.taxRate — Token buy/sell tax
Step 4: Format Output for User
Convert raw amounts back to human-readable:
human_amount = raw_amount / (10 ** decimal)
Always display:
- Exchange rate (e.g., "1 ETH = 3,521.43 USDC")
- Price impact percentage with warning if > 3%
- Estimated gas fee in USD
- Routing summary (which DEXes are used)
- Honeypot warnings if detected
- Token tax rates if > 0
Best Practices
Security
- NEVER hardcode API credentials in generated code. Always use environment variables or config files.
- NEVER log the secret key or signature in debug output.
- Validate all token addresses against expected format before sending.
- Check
isHoneyPot flag on both tokens and warn the user prominently.
Amount Handling
- Always use string type for amounts to avoid floating-point precision loss.
- Python: Use
int() for amount calculations, never float().
- JavaScript: Use
BigInt or string math for amounts > 2^53.
- When user provides a human-readable amount like "1.5 ETH", convert:
str(int(1.5 * 10**18)).
Error Handling
- Check
response["code"] == "0" before accessing data.
- Common error codes:
- Non-zero code with
msg = API error (e.g., insufficient liquidity, invalid params)
- HTTP 401 = Authentication failure (check signature algorithm)
- HTTP 429 = Rate limited
- If
priceImpactPercent is null, warn that price impact couldn't be calculated.
Rate Limits
- Respect OKX rate limits. For production use, implement exponential backoff.
- Cache quotes if polling repeatedly (quotes are valid for ~15-30 seconds).
Optional Parameters Usage
dexIds — Use when you want to restrict to specific DEXes (e.g., only Uniswap).
directRoute=true — Only for Solana; forces single-pool routing.
priceImpactProtectionPercent — Set to a sensible default like 10 for safety. Set to 100 to disable.
feePercent — For integrators taking commission. Max 3% (EVM) or 10% (Solana). Up to 9 decimal places.
Examples
Example 1: Python — Get ETH to USDC Quote on Ethereum
import os, hmac, hashlib, base64, requests
from datetime import datetime, timezone
from urllib.parse import urlencode
API_KEY = os.environ["OKX_ACCESS_KEY"]
SECRET_KEY = os.environ["OKX_SECRET_KEY"]
PASSPHRASE = os.environ["OKX_PASSPHRASE"]
def get_okx_quote(chain_index, from_token, to_token, amount, swap_mode="exactIn"):
base_url = "https://web3.okx.com"
path = "/api/v6/dex/aggregator/quote"
params = {
"chainIndex": chain_index,
"fromTokenAddress": from_token,
"toTokenAddress": to_token,
"amount": amount,
"swapMode": swap_mode,
}
query_string = urlencode(params)
request_path = f"{path}?{query_string}"
# Generate timestamp and signature
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
prehash = timestamp + "GET" + request_path
signature = base64.b64encode(
hmac.new(SECRET_KEY.encode(), prehash.encode(), hashlib.sha256).digest()
).decode()
headers = {
"OK-ACCESS-KEY": API_KEY,
"OK-ACCESS-SIGN": signature,
"OK-ACCESS-PASSPHRASE": PASSPHRASE,
"OK-ACCESS-TIMESTAMP": timestamp,
}
resp = requests.get(base_url + request_path, headers=headers)
resp.raise_for_status()
data = resp.json()
if data["code"] != "0":
raise Exception(f"OKX API error: {data['msg']}")
return data["data"][0]
# Swap 1 ETH -> USDC on Ethereum
ETH = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
USDC = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
amount = str(1 * 10**18) # 1 ETH in wei
quote = get_okx_quote("1", ETH, USDC, amount)
to_decimals = int(quote["toToken"]["decimal"])
received = int(quote["toTokenAmount"]) / (10 ** to_decimals)
print(f"You will receive: {received:,.2f} {quote['toToken']['tokenSymbol']}")
print(f"Price impact: {quote['priceImpactPercent']}%")
print(f"Gas fee (USD): ${quote['tradeFee']}")
print(f"Honeypot check: {'WARNING' if quote['toToken']['isHoneyPot'] else 'Safe'}")
Example 2: Node.js — Get Quote with Commission Fee
const crypto = require("crypto");
const https = require("https");
const API_KEY = process.env.OKX_ACCESS_KEY;
const SECRET_KEY = process.env.OKX_SECRET_KEY;
const PASSPHRASE = process.env.OKX_PASSPHRASE;
function getQuote(chainIndex, fromToken, toToken, amount, options = {}) {
const params = new URLSearchParams({
chainIndex,
fromTokenAddress: fromToken,
toTokenAddress: toToken,
amount,
swapMode: options.swapMode || "exactIn",
...(options.feePercent && { feePercent: options.feePercent }),
...(options.priceImpactProtectionPercent && {
priceImpactProtectionPercent: options.priceImpactProtectionPercent,
}),
});
const path = `/api/v6/dex/aggregator/quote?${params}`;
const timestamp = new Date().toISOString();
const prehash = timestamp + "GET" + path;
const signature = crypto
.createHmac("sha256", SECRET_KEY)
.update(prehash)
.digest("base64");
return new Promise((resolve, reject) => {
const req = https.get(
`https://web3.okx.com${path}`,
{
headers: {
"OK-ACCESS-KEY": API_KEY,
"OK-ACCESS-SIGN": signature,
"OK-ACCESS-PASSPHRASE": PASSPHRASE,
"OK-ACCESS-TIMESTAMP": timestamp,
},
},
(res) => {
let body = "";
res.on("data", (chunk) => (body += chunk));
res.on("end", () => {
const data = JSON.parse(body);
if (data.code !== "0") reject(new Error(`OKX: ${data.msg}`));
else resolve(data.data[0]);
});
}
);
req.on("error", reject);
});
}
Example 3: Understanding the Routing Path
Router: ETH -> WBTC -> USDC
dexRouterList shows:
- 55% ETH -> WBTC via Uniswap V4
- 30% ETH -> USDC via Uniswap V4 (direct)
- WBTC -> USDC via Euler (73%) + Uniswap V4 (27%)
This means the aggregator splits the trade across multiple paths
to minimize price impact and maximize output.
Troubleshooting
| Problem |
Cause |
Solution |
401 Unauthorized |
Signature mismatch |
Verify prehash string is exactly timestamp + "GET" + full_path_with_query. Check secret key encoding. |
| Amount too small |
Missing decimal conversion |
Multiply human amount by 10 ** token_decimals. 1 USDT = 1000000, not 1. |
| Invalid token address |
Wrong chain/address combo |
Verify the token exists on the specified chain. Use native token placeholder for ETH/BNB/etc. |
priceImpactPercent very negative (< -10%) |
Low liquidity or large trade |
Reduce trade size or split across multiple transactions. |
isHoneyPot: true |
Scam token detected |
Do NOT proceed with the swap. Warn the user immediately. |
exactOut not working |
Unsupported chain/protocol |
Only works on Ethereum, Base, BSC, Arbitrum with Uniswap V2/V3. |
taxRate > 0 |
Token has built-in tax |
Factor tax into expected output. E.g., 5% tax means receiving 5% less. |
Empty dexRouterList |
No liquidity path found |
Try a different token pair, smaller amount, or different chain. |
code is non-zero |
General API error |
Read msg field for details. Common: rate limit, maintenance, invalid params. |
Reference: Common Chain IDs
| Chain |
chainIndex |
| Ethereum |
1 |
| BSC |
56 |
| Polygon |
137 |
| Arbitrum |
42161 |
| Optimism |
10 |
| Avalanche |
43114 |
| Base |
8453 |
| Solana |
501 |
| Unichain |
130 |
Reference: Common Token Addresses (Ethereum)
| Token |
Address |
Decimals |
| ETH (native) |
0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee |
18 |
| USDT |
0xdac17f958d2ee523a2206206994597c13d831ec7 |
6 |
| USDC |
0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 |
6 |
| WETH |
0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 |
18 |
| WBTC |
0x2260fac5e5542a773aa44fbcfedf7c193bc2c599 |
8 |
| DAI |
0x6b175474e89094c44da98b954eedeac495271d0f |
18 |
Reference: Request Parameters Summary
| Parameter |
Required |
Description |
chainIndex |
Yes |
Chain ID (e.g., 1 for Ethereum) |
amount |
Yes |
Amount in raw units (with decimals) |
swapMode |
Yes |
exactIn or exactOut |
fromTokenAddress |
Yes |
Sell token contract address |
toTokenAddress |
Yes |
Buy token contract address |
dexIds |
No |
Comma-separated DEX IDs to restrict routing |
directRoute |
No |
true for single-pool only (Solana only) |
priceImpactProtectionPercent |
No |
Max allowed price impact 0-100 (default 90) |
feePercent |
No |
Commission fee percentage for integrators |
1---
2name: okx-dex-quote
3description: >
4 Fetch optimal swap quotes from OKX DEX Aggregator API (v6). Use this skill when a user wants to:
5 1. Get the best price for swapping tokens on any supported EVM/Solana chain
6 2. Compare DEX routing paths and price impact for token swaps
7 3. Build applications or scripts that query real-time DEX aggregator pricing
8 Core value: Generates correct, authenticated API calls with proper token decimals,
9 amount formatting, HMAC-SHA256 signing, and comprehensive error handling.
10version: 1.0.0
11allowed_tools: [bash_tool, create_file, str_replace, view]
12required_context: [api_key, secret_key, passphrase]
13license: MIT
14author: Claude Assistant
15tags: [defi, dex, okx, swap, quote, web3, aggregator, evm, solana]
16metadata:
17 source: https://skillmd.com/skills/modbender/okx-dex-quote
18---
19
20# OKX DEX Aggregator Quote Skill
21
22## Overview
23
24This skill generates production-ready code for fetching optimal swap quotes from the **OKX DEX Aggregator API v6**. The API finds the best price across multiple DEX protocols (Uniswap, SushiSwap, Curve, etc.) and returns detailed routing information including price impact, gas estimates, and token safety flags.
25
26**Key capabilities:**
27- Authenticated API requests with HMAC-SHA256 signing
28- Correct handling of token decimals and amount formatting
29- Support for `exactIn` (fixed input) and `exactOut` (fixed output) swap modes
30- Multi-chain support (Ethereum, BSC, Arbitrum, Base, Solana, and 20+ chains)
31- Price impact protection and honeypot detection
32- Fee/commission splitting configuration
33
34## Prerequisites
35
36### Required Credentials
37Users must have an OKX Web3 API key set. The skill needs three values:
38- `OKX_ACCESS_KEY` — API key
39- `OKX_SECRET_KEY` — Secret key for HMAC signing
40- `OKX_PASSPHRASE` — Account passphrase
41
42### Environment
43- **Python**: `requests`, `hmac`, `hashlib`, `base64`, `datetime` (all stdlib except `requests`)
44- **Node.js**: `axios` or `node-fetch`, built-in `crypto`
45- No additional blockchain dependencies required (this is a read-only quote endpoint)
46
47### API Endpoint
48```
49GET https://web3.okx.com/api/v6/dex/aggregator/quote
50```
51
52## Workflow
53
54### Step 1: Validate User Input
55
56Before constructing the API call, validate:
57
581. **Chain ID (`chainIndex`)** — Must be a supported chain. Common values:
59 - `1` = Ethereum
60 - `56` = BSC
61 - `137` = Polygon
62 - `42161` = Arbitrum
63 - `8453` = Base
64 - `130` = Unichain
65 - `501` = Solana
66
672. **Token addresses** — Must be valid contract addresses or the native token placeholder:
68 - Native tokens (ETH, BNB, etc.): `0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee`
69 - Contract tokens: Full 42-character hex address (EVM) or base58 (Solana)
70
713. **Amount** — MUST include token decimals. This is the #1 source of errors:
72 - 1 ETH (18 decimals) → `"1000000000000000000"`
73 - 1 USDT (6 decimals) → `"1000000"`
74 - 1 WBTC (8 decimals) → `"100000000"`
75 - Formula: `amount_raw = human_amount * (10 ** token_decimals)`
76
774. **Swap mode** — `exactIn` (default) or `exactOut`
78 - `exactOut` only supported on: Ethereum, Base, BSC, Arbitrum
79 - `exactOut` only works with Uniswap V2/V3 pools
80
81### Step 2: Construct Authentication Headers
82
83OKX API requires HMAC-SHA256 signed requests with 4 headers:
84
85```
86OK-ACCESS-KEY: <api_key>
87OK-ACCESS-SIGN: <hmac_signature>
88OK-ACCESS-PASSPHRASE: <passphrase>
89OK-ACCESS-TIMESTAMP: <iso8601_timestamp>
90```
91
92**Signing algorithm:**
93```
94timestamp = ISO 8601 UTC time (e.g., "2025-01-15T12:00:00.000Z")
95prehash = timestamp + "GET" + request_path_with_query
96signature = Base64(HMAC-SHA256(secret_key, prehash))
97```
98
99**CRITICAL**: The `request_path_with_query` must include the full path starting from `/api/...` plus the query string. Example:
100```
101/api/v6/dex/aggregator/quote?chainIndex=1&amount=1000000000000000000&fromTokenAddress=0xeee...&toTokenAddress=0xa0b...
102```
103
104### Step 3: Send Request and Parse Response
105
106**Success response structure:**
107```json
108{
109 "code": "0",
110 "data": [{
111 "chainIndex": "1",
112 "fromToken": { "tokenSymbol": "ETH", "decimal": "18", ... },
113 "toToken": { "tokenSymbol": "USDC", "decimal": "6", ... },
114 "fromTokenAmount": "1000000000000000000",
115 "toTokenAmount": "3521432100",
116 "dexRouterList": [...],
117 "tradeFee": "2.45",
118 "estimateGasFee": "150000",
119 "priceImpactPercent": "-0.12"
120 }],
121 "msg": ""
122}
123```
124
125**Key fields to extract:**
126- `toTokenAmount` — The amount you'll receive (in raw units with decimals)
127- `tradeFee` — Estimated network fee in USD
128- `priceImpactPercent` — Negative = losing value; large negative = danger
129- `dexRouterList` — Routing path through various DEX protocols
130- `fromToken.isHoneyPot` / `toToken.isHoneyPot` — Scam token flag
131- `fromToken.taxRate` / `toToken.taxRate` — Token buy/sell tax
132
133### Step 4: Format Output for User
134
135Convert raw amounts back to human-readable:
136```
137human_amount = raw_amount / (10 ** decimal)
138```
139
140Always display:
1411. Exchange rate (e.g., "1 ETH = 3,521.43 USDC")
1422. Price impact percentage with warning if > 3%
1433. Estimated gas fee in USD
1444. Routing summary (which DEXes are used)
1455. Honeypot warnings if detected
1466. Token tax rates if > 0
147
148## Best Practices
149
150### Security
151- **NEVER hardcode API credentials** in generated code. Always use environment variables or config files.
152- **NEVER log the secret key or signature** in debug output.
153- Validate all token addresses against expected format before sending.
154- Check `isHoneyPot` flag on both tokens and warn the user prominently.
155
156### Amount Handling
157- **Always use string type** for amounts to avoid floating-point precision loss.
158- Python: Use `int()` for amount calculations, never `float()`.
159- JavaScript: Use `BigInt` or string math for amounts > 2^53.
160- When user provides a human-readable amount like "1.5 ETH", convert: `str(int(1.5 * 10**18))`.
161
162### Error Handling
163- Check `response["code"] == "0"` before accessing data.
164- Common error codes:
165 - Non-zero code with `msg` = API error (e.g., insufficient liquidity, invalid params)
166 - HTTP 401 = Authentication failure (check signature algorithm)
167 - HTTP 429 = Rate limited
168- If `priceImpactPercent` is `null`, warn that price impact couldn't be calculated.
169
170### Rate Limits
171- Respect OKX rate limits. For production use, implement exponential backoff.
172- Cache quotes if polling repeatedly (quotes are valid for ~15-30 seconds).
173
174### Optional Parameters Usage
175- `dexIds` — Use when you want to restrict to specific DEXes (e.g., only Uniswap).
176- `directRoute=true` — Only for Solana; forces single-pool routing.
177- `priceImpactProtectionPercent` — Set to a sensible default like `10` for safety. Set to `100` to disable.
178- `feePercent` — For integrators taking commission. Max 3% (EVM) or 10% (Solana). Up to 9 decimal places.
179
180## Examples
181
182### Example 1: Python — Get ETH to USDC Quote on Ethereum
183
184```python
185import os, hmac, hashlib, base64, requests
186from datetime import datetime, timezone
187from urllib.parse import urlencode
188
189API_KEY = os.environ["OKX_ACCESS_KEY"]
190SECRET_KEY = os.environ["OKX_SECRET_KEY"]
191PASSPHRASE = os.environ["OKX_PASSPHRASE"]
192
193def get_okx_quote(chain_index, from_token, to_token, amount, swap_mode="exactIn"):
194 base_url = "https://web3.okx.com"
195 path = "/api/v6/dex/aggregator/quote"
196
197 params = {
198 "chainIndex": chain_index,
199 "fromTokenAddress": from_token,
200 "toTokenAddress": to_token,
201 "amount": amount,
202 "swapMode": swap_mode,
203 }
204
205 query_string = urlencode(params)
206 request_path = f"{path}?{query_string}"
207
208 # Generate timestamp and signature
209 timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
210 prehash = timestamp + "GET" + request_path
211 signature = base64.b64encode(
212 hmac.new(SECRET_KEY.encode(), prehash.encode(), hashlib.sha256).digest()
213 ).decode()
214
215 headers = {
216 "OK-ACCESS-KEY": API_KEY,
217 "OK-ACCESS-SIGN": signature,
218 "OK-ACCESS-PASSPHRASE": PASSPHRASE,
219 "OK-ACCESS-TIMESTAMP": timestamp,
220 }
221
222 resp = requests.get(base_url + request_path, headers=headers)
223 resp.raise_for_status()
224 data = resp.json()
225
226 if data["code"] != "0":
227 raise Exception(f"OKX API error: {data['msg']}")
228
229 return data["data"][0]
230
231
232# Swap 1 ETH -> USDC on Ethereum
233ETH = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
234USDC = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
235amount = str(1 * 10**18) # 1 ETH in wei
236
237quote = get_okx_quote("1", ETH, USDC, amount)
238
239to_decimals = int(quote["toToken"]["decimal"])
240received = int(quote["toTokenAmount"]) / (10 ** to_decimals)
241
242print(f"You will receive: {received:,.2f} {quote['toToken']['tokenSymbol']}")
243print(f"Price impact: {quote['priceImpactPercent']}%")
244print(f"Gas fee (USD): ${quote['tradeFee']}")
245print(f"Honeypot check: {'WARNING' if quote['toToken']['isHoneyPot'] else 'Safe'}")
246```
247
248### Example 2: Node.js — Get Quote with Commission Fee
249
250```javascript
251const crypto = require("crypto");
252const https = require("https");
253
254const API_KEY = process.env.OKX_ACCESS_KEY;
255const SECRET_KEY = process.env.OKX_SECRET_KEY;
256const PASSPHRASE = process.env.OKX_PASSPHRASE;
257
258function getQuote(chainIndex, fromToken, toToken, amount, options = {}) {
259 const params = new URLSearchParams({
260 chainIndex,
261 fromTokenAddress: fromToken,
262 toTokenAddress: toToken,
263 amount,
264 swapMode: options.swapMode || "exactIn",
265 ...(options.feePercent && { feePercent: options.feePercent }),
266 ...(options.priceImpactProtectionPercent && {
267 priceImpactProtectionPercent: options.priceImpactProtectionPercent,
268 }),
269 });
270
271 const path = `/api/v6/dex/aggregator/quote?${params}`;
272 const timestamp = new Date().toISOString();
273 const prehash = timestamp + "GET" + path;
274 const signature = crypto
275 .createHmac("sha256", SECRET_KEY)
276 .update(prehash)
277 .digest("base64");
278
279 return new Promise((resolve, reject) => {
280 const req = https.get(
281 `https://web3.okx.com${path}`,
282 {
283 headers: {
284 "OK-ACCESS-KEY": API_KEY,
285 "OK-ACCESS-SIGN": signature,
286 "OK-ACCESS-PASSPHRASE": PASSPHRASE,
287 "OK-ACCESS-TIMESTAMP": timestamp,
288 },
289 },
290 (res) => {
291 let body = "";
292 res.on("data", (chunk) => (body += chunk));
293 res.on("end", () => {
294 const data = JSON.parse(body);
295 if (data.code !== "0") reject(new Error(`OKX: ${data.msg}`));
296 else resolve(data.data[0]);
297 });
298 }
299 );
300 req.on("error", reject);
301 });
302}
303```
304
305### Example 3: Understanding the Routing Path
306
307```
308Router: ETH -> WBTC -> USDC
309dexRouterList shows:
310 - 55% ETH -> WBTC via Uniswap V4
311 - 30% ETH -> USDC via Uniswap V4 (direct)
312 - WBTC -> USDC via Euler (73%) + Uniswap V4 (27%)
313
314This means the aggregator splits the trade across multiple paths
315to minimize price impact and maximize output.
316```
317
318## Troubleshooting
319
320| Problem | Cause | Solution |
321|---------|-------|----------|
322| `401 Unauthorized` | Signature mismatch | Verify prehash string is exactly `timestamp + "GET" + full_path_with_query`. Check secret key encoding. |
323| Amount too small | Missing decimal conversion | Multiply human amount by `10 ** token_decimals`. 1 USDT = `1000000`, not `1`. |
324| Invalid token address | Wrong chain/address combo | Verify the token exists on the specified chain. Use native token placeholder for ETH/BNB/etc. |
325| `priceImpactPercent` very negative (< -10%) | Low liquidity or large trade | Reduce trade size or split across multiple transactions. |
326| `isHoneyPot: true` | Scam token detected | **Do NOT proceed with the swap.** Warn the user immediately. |
327| `exactOut` not working | Unsupported chain/protocol | Only works on Ethereum, Base, BSC, Arbitrum with Uniswap V2/V3. |
328| `taxRate > 0` | Token has built-in tax | Factor tax into expected output. E.g., 5% tax means receiving 5% less. |
329| Empty `dexRouterList` | No liquidity path found | Try a different token pair, smaller amount, or different chain. |
330| `code` is non-zero | General API error | Read `msg` field for details. Common: rate limit, maintenance, invalid params. |
331
332## Reference: Common Chain IDs
333
334| Chain | chainIndex |
335|-------|-----------|
336| Ethereum | 1 |
337| BSC | 56 |
338| Polygon | 137 |
339| Arbitrum | 42161 |
340| Optimism | 10 |
341| Avalanche | 43114 |
342| Base | 8453 |
343| Solana | 501 |
344| Unichain | 130 |
345
346## Reference: Common Token Addresses (Ethereum)
347
348| Token | Address | Decimals |
349|-------|---------|----------|
350| ETH (native) | `0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee` | 18 |
351| USDT | `0xdac17f958d2ee523a2206206994597c13d831ec7` | 6 |
352| USDC | `0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48` | 6 |
353| WETH | `0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2` | 18 |
354| WBTC | `0x2260fac5e5542a773aa44fbcfedf7c193bc2c599` | 8 |
355| DAI | `0x6b175474e89094c44da98b954eedeac495271d0f` | 18 |
356
357## Reference: Request Parameters Summary
358
359| Parameter | Required | Description |
360|-----------|----------|-------------|
361| `chainIndex` | Yes | Chain ID (e.g., `1` for Ethereum) |
362| `amount` | Yes | Amount in raw units (with decimals) |
363| `swapMode` | Yes | `exactIn` or `exactOut` |
364| `fromTokenAddress` | Yes | Sell token contract address |
365| `toTokenAddress` | Yes | Buy token contract address |
366| `dexIds` | No | Comma-separated DEX IDs to restrict routing |
367| `directRoute` | No | `true` for single-pool only (Solana only) |
368| `priceImpactProtectionPercent` | No | Max allowed price impact 0-100 (default 90) |
369| `feePercent` | No | Commission fee percentage for integrators |