{
  "schemaVersion": "1.0",
  "item": {
    "slug": "dex-quote",
    "name": "DEX Aggregator Quote",
    "source": "tencent",
    "type": "skill",
    "category": "开发工具",
    "sourceUrl": "https://clawhub.ai/AaronLLee/dex-quote",
    "canonicalUrl": "https://clawhub.ai/AaronLLee/dex-quote",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadMode": "redirect",
    "downloadUrl": "/downloads/dex-quote",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=dex-quote",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "installMethod": "Manual import",
    "extraction": "Extract archive",
    "prerequisites": [
      "OpenClaw"
    ],
    "packageFormat": "ZIP package",
    "includedAssets": [
      "SKILL.md",
      "scripts/dex_quote.py"
    ],
    "primaryDoc": "SKILL.md",
    "quickSetup": [
      "Download the package from Yavira.",
      "Extract the archive and review SKILL.md first.",
      "Import or place the package into your OpenClaw setup."
    ],
    "agentAssist": {
      "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
      "steps": [
        "Download the package from Yavira.",
        "Extract it into a folder your agent can access.",
        "Paste one of the prompts below and point your agent at the extracted folder."
      ],
      "prompts": [
        {
          "label": "New install",
          "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Tell me what you changed and call out any manual steps you could not complete."
        },
        {
          "label": "Upgrade existing",
          "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Summarize what changed and any follow-up checks I should run."
        }
      ]
    },
    "sourceHealth": {
      "source": "tencent",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-04-30T16:55:25.780Z",
      "expiresAt": "2026-05-07T16:55:25.780Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=network",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=network",
        "contentDisposition": "attachment; filename=\"network-1.0.0.zip\"",
        "redirectLocation": null,
        "bodySnippet": null
      },
      "scope": "source",
      "summary": "Source download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this source.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/dex-quote"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    },
    "downloadPageUrl": "https://openagent3.xyz/downloads/dex-quote",
    "agentPageUrl": "https://openagent3.xyz/skills/dex-quote/agent",
    "manifestUrl": "https://openagent3.xyz/skills/dex-quote/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/dex-quote/agent.md"
  },
  "agentAssist": {
    "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
    "steps": [
      "Download the package from Yavira.",
      "Extract it into a folder your agent can access.",
      "Paste one of the prompts below and point your agent at the extracted folder."
    ],
    "prompts": [
      {
        "label": "New install",
        "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Tell me what you changed and call out any manual steps you could not complete."
      },
      {
        "label": "Upgrade existing",
        "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Summarize what changed and any follow-up checks I should run."
      }
    ]
  },
  "documentation": {
    "source": "clawhub",
    "primaryDoc": "SKILL.md",
    "sections": [
      {
        "title": "Overview",
        "body": "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.\n\nKey capabilities:\n\nAuthenticated API requests with HMAC-SHA256 signing\nCorrect handling of token decimals and amount formatting\nSupport for exactIn (fixed input) and exactOut (fixed output) swap modes\nMulti-chain support (Ethereum, BSC, Arbitrum, Base, Solana, and 20+ chains)\nPrice impact protection and honeypot detection\nFee/commission splitting configuration"
      },
      {
        "title": "Required Credentials",
        "body": "Users must have an OKX Web3 API key set. The skill needs three values:\n\nOKX_ACCESS_KEY — API key\nOKX_SECRET_KEY — Secret key for HMAC signing\nOKX_PASSPHRASE — Account passphrase"
      },
      {
        "title": "Environment",
        "body": "Python: requests, hmac, hashlib, base64, datetime (all stdlib except requests)\nNode.js: axios or node-fetch, built-in crypto\nNo additional blockchain dependencies required (this is a read-only quote endpoint)"
      },
      {
        "title": "API Endpoint",
        "body": "GET https://web3.okx.com/api/v6/dex/aggregator/quote"
      },
      {
        "title": "Step 1: Validate User Input",
        "body": "Before constructing the API call, validate:\n\nChain ID (chainIndex) — Must be a supported chain. Common values:\n\n1 = Ethereum\n56 = BSC\n137 = Polygon\n42161 = Arbitrum\n8453 = Base\n130 = Unichain\n501 = Solana\n\n\n\nToken addresses — Must be valid contract addresses or the native token placeholder:\n\nNative tokens (ETH, BNB, etc.): 0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\nContract tokens: Full 42-character hex address (EVM) or base58 (Solana)\n\n\n\nAmount — MUST include token decimals. This is the #1 source of errors:\n\n1 ETH (18 decimals) → \"1000000000000000000\"\n1 USDT (6 decimals) → \"1000000\"\n1 WBTC (8 decimals) → \"100000000\"\nFormula: amount_raw = human_amount * (10 ** token_decimals)\n\n\n\nSwap mode — exactIn (default) or exactOut\n\nexactOut only supported on: Ethereum, Base, BSC, Arbitrum\nexactOut only works with Uniswap V2/V3 pools"
      },
      {
        "title": "Step 2: Construct Authentication Headers",
        "body": "OKX API requires HMAC-SHA256 signed requests with 4 headers:\n\nOK-ACCESS-KEY: <api_key>\nOK-ACCESS-SIGN: <hmac_signature>\nOK-ACCESS-PASSPHRASE: <passphrase>\nOK-ACCESS-TIMESTAMP: <iso8601_timestamp>\n\nSigning algorithm:\n\ntimestamp = ISO 8601 UTC time (e.g., \"2025-01-15T12:00:00.000Z\")\nprehash = timestamp + \"GET\" + request_path_with_query\nsignature = Base64(HMAC-SHA256(secret_key, prehash))\n\nCRITICAL: The request_path_with_query must include the full path starting from /api/... plus the query string. Example:\n\n/api/v6/dex/aggregator/quote?chainIndex=1&amount=1000000000000000000&fromTokenAddress=0xeee...&toTokenAddress=0xa0b..."
      },
      {
        "title": "Step 3: Send Request and Parse Response",
        "body": "Success response structure:\n\n{\n  \"code\": \"0\",\n  \"data\": [{\n    \"chainIndex\": \"1\",\n    \"fromToken\": { \"tokenSymbol\": \"ETH\", \"decimal\": \"18\", ... },\n    \"toToken\": { \"tokenSymbol\": \"USDC\", \"decimal\": \"6\", ... },\n    \"fromTokenAmount\": \"1000000000000000000\",\n    \"toTokenAmount\": \"3521432100\",\n    \"dexRouterList\": [...],\n    \"tradeFee\": \"2.45\",\n    \"estimateGasFee\": \"150000\",\n    \"priceImpactPercent\": \"-0.12\"\n  }],\n  \"msg\": \"\"\n}\n\nKey fields to extract:\n\ntoTokenAmount — The amount you'll receive (in raw units with decimals)\ntradeFee — Estimated network fee in USD\npriceImpactPercent — Negative = losing value; large negative = danger\ndexRouterList — Routing path through various DEX protocols\nfromToken.isHoneyPot / toToken.isHoneyPot — Scam token flag\nfromToken.taxRate / toToken.taxRate — Token buy/sell tax"
      },
      {
        "title": "Step 4: Format Output for User",
        "body": "Convert raw amounts back to human-readable:\n\nhuman_amount = raw_amount / (10 ** decimal)\n\nAlways display:\n\nExchange rate (e.g., \"1 ETH = 3,521.43 USDC\")\nPrice impact percentage with warning if > 3%\nEstimated gas fee in USD\nRouting summary (which DEXes are used)\nHoneypot warnings if detected\nToken tax rates if > 0"
      },
      {
        "title": "Security",
        "body": "NEVER hardcode API credentials in generated code. Always use environment variables or config files.\nNEVER log the secret key or signature in debug output.\nValidate all token addresses against expected format before sending.\nCheck isHoneyPot flag on both tokens and warn the user prominently."
      },
      {
        "title": "Amount Handling",
        "body": "Always use string type for amounts to avoid floating-point precision loss.\nPython: Use int() for amount calculations, never float().\nJavaScript: Use BigInt or string math for amounts > 2^53.\nWhen user provides a human-readable amount like \"1.5 ETH\", convert: str(int(1.5 * 10**18))."
      },
      {
        "title": "Error Handling",
        "body": "Check response[\"code\"] == \"0\" before accessing data.\nCommon error codes:\n\nNon-zero code with msg = API error (e.g., insufficient liquidity, invalid params)\nHTTP 401 = Authentication failure (check signature algorithm)\nHTTP 429 = Rate limited\n\n\nIf priceImpactPercent is null, warn that price impact couldn't be calculated."
      },
      {
        "title": "Rate Limits",
        "body": "Respect OKX rate limits. For production use, implement exponential backoff.\nCache quotes if polling repeatedly (quotes are valid for ~15-30 seconds)."
      },
      {
        "title": "Optional Parameters Usage",
        "body": "dexIds — Use when you want to restrict to specific DEXes (e.g., only Uniswap).\ndirectRoute=true — Only for Solana; forces single-pool routing.\npriceImpactProtectionPercent — Set to a sensible default like 10 for safety. Set to 100 to disable.\nfeePercent — For integrators taking commission. Max 3% (EVM) or 10% (Solana). Up to 9 decimal places."
      },
      {
        "title": "Example 1: Python — Get ETH to USDC Quote on Ethereum",
        "body": "import os, hmac, hashlib, base64, requests\nfrom datetime import datetime, timezone\nfrom urllib.parse import urlencode\n\nAPI_KEY = os.environ[\"OKX_ACCESS_KEY\"]\nSECRET_KEY = os.environ[\"OKX_SECRET_KEY\"]\nPASSPHRASE = os.environ[\"OKX_PASSPHRASE\"]\n\ndef get_okx_quote(chain_index, from_token, to_token, amount, swap_mode=\"exactIn\"):\n    base_url = \"https://web3.okx.com\"\n    path = \"/api/v6/dex/aggregator/quote\"\n\n    params = {\n        \"chainIndex\": chain_index,\n        \"fromTokenAddress\": from_token,\n        \"toTokenAddress\": to_token,\n        \"amount\": amount,\n        \"swapMode\": swap_mode,\n    }\n\n    query_string = urlencode(params)\n    request_path = f\"{path}?{query_string}\"\n\n    # Generate timestamp and signature\n    timestamp = datetime.now(timezone.utc).strftime(\"%Y-%m-%dT%H:%M:%S.%f\")[:-3] + \"Z\"\n    prehash = timestamp + \"GET\" + request_path\n    signature = base64.b64encode(\n        hmac.new(SECRET_KEY.encode(), prehash.encode(), hashlib.sha256).digest()\n    ).decode()\n\n    headers = {\n        \"OK-ACCESS-KEY\": API_KEY,\n        \"OK-ACCESS-SIGN\": signature,\n        \"OK-ACCESS-PASSPHRASE\": PASSPHRASE,\n        \"OK-ACCESS-TIMESTAMP\": timestamp,\n    }\n\n    resp = requests.get(base_url + request_path, headers=headers)\n    resp.raise_for_status()\n    data = resp.json()\n\n    if data[\"code\"] != \"0\":\n        raise Exception(f\"OKX API error: {data['msg']}\")\n\n    return data[\"data\"][0]\n\n\n# Swap 1 ETH -> USDC on Ethereum\nETH = \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\"\nUSDC = \"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\"\namount = str(1 * 10**18)  # 1 ETH in wei\n\nquote = get_okx_quote(\"1\", ETH, USDC, amount)\n\nto_decimals = int(quote[\"toToken\"][\"decimal\"])\nreceived = int(quote[\"toTokenAmount\"]) / (10 ** to_decimals)\n\nprint(f\"You will receive: {received:,.2f} {quote['toToken']['tokenSymbol']}\")\nprint(f\"Price impact: {quote['priceImpactPercent']}%\")\nprint(f\"Gas fee (USD): ${quote['tradeFee']}\")\nprint(f\"Honeypot check: {'WARNING' if quote['toToken']['isHoneyPot'] else 'Safe'}\")"
      },
      {
        "title": "Example 2: Node.js — Get Quote with Commission Fee",
        "body": "const crypto = require(\"crypto\");\nconst https = require(\"https\");\n\nconst API_KEY = process.env.OKX_ACCESS_KEY;\nconst SECRET_KEY = process.env.OKX_SECRET_KEY;\nconst PASSPHRASE = process.env.OKX_PASSPHRASE;\n\nfunction getQuote(chainIndex, fromToken, toToken, amount, options = {}) {\n  const params = new URLSearchParams({\n    chainIndex,\n    fromTokenAddress: fromToken,\n    toTokenAddress: toToken,\n    amount,\n    swapMode: options.swapMode || \"exactIn\",\n    ...(options.feePercent && { feePercent: options.feePercent }),\n    ...(options.priceImpactProtectionPercent && {\n      priceImpactProtectionPercent: options.priceImpactProtectionPercent,\n    }),\n  });\n\n  const path = `/api/v6/dex/aggregator/quote?${params}`;\n  const timestamp = new Date().toISOString();\n  const prehash = timestamp + \"GET\" + path;\n  const signature = crypto\n    .createHmac(\"sha256\", SECRET_KEY)\n    .update(prehash)\n    .digest(\"base64\");\n\n  return new Promise((resolve, reject) => {\n    const req = https.get(\n      `https://web3.okx.com${path}`,\n      {\n        headers: {\n          \"OK-ACCESS-KEY\": API_KEY,\n          \"OK-ACCESS-SIGN\": signature,\n          \"OK-ACCESS-PASSPHRASE\": PASSPHRASE,\n          \"OK-ACCESS-TIMESTAMP\": timestamp,\n        },\n      },\n      (res) => {\n        let body = \"\";\n        res.on(\"data\", (chunk) => (body += chunk));\n        res.on(\"end\", () => {\n          const data = JSON.parse(body);\n          if (data.code !== \"0\") reject(new Error(`OKX: ${data.msg}`));\n          else resolve(data.data[0]);\n        });\n      }\n    );\n    req.on(\"error\", reject);\n  });\n}"
      },
      {
        "title": "Example 3: Understanding the Routing Path",
        "body": "Router: ETH -> WBTC -> USDC\ndexRouterList shows:\n  - 55% ETH -> WBTC via Uniswap V4\n  - 30% ETH -> USDC via Uniswap V4 (direct)\n  - WBTC -> USDC via Euler (73%) + Uniswap V4 (27%)\n\nThis means the aggregator splits the trade across multiple paths\nto minimize price impact and maximize output."
      },
      {
        "title": "Troubleshooting",
        "body": "ProblemCauseSolution401 UnauthorizedSignature mismatchVerify prehash string is exactly timestamp + \"GET\" + full_path_with_query. Check secret key encoding.Amount too smallMissing decimal conversionMultiply human amount by 10 ** token_decimals. 1 USDT = 1000000, not 1.Invalid token addressWrong chain/address comboVerify the token exists on the specified chain. Use native token placeholder for ETH/BNB/etc.priceImpactPercent very negative (< -10%)Low liquidity or large tradeReduce trade size or split across multiple transactions.isHoneyPot: trueScam token detectedDo NOT proceed with the swap. Warn the user immediately.exactOut not workingUnsupported chain/protocolOnly works on Ethereum, Base, BSC, Arbitrum with Uniswap V2/V3.taxRate > 0Token has built-in taxFactor tax into expected output. E.g., 5% tax means receiving 5% less.Empty dexRouterListNo liquidity path foundTry a different token pair, smaller amount, or different chain.code is non-zeroGeneral API errorRead msg field for details. Common: rate limit, maintenance, invalid params."
      },
      {
        "title": "Reference: Common Chain IDs",
        "body": "ChainchainIndexEthereum1BSC56Polygon137Arbitrum42161Optimism10Avalanche43114Base8453Solana501Unichain130"
      },
      {
        "title": "Reference: Common Token Addresses (Ethereum)",
        "body": "TokenAddressDecimalsETH (native)0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee18USDT0xdac17f958d2ee523a2206206994597c13d831ec76USDC0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb486WETH0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc218WBTC0x2260fac5e5542a773aa44fbcfedf7c193bc2c5998DAI0x6b175474e89094c44da98b954eedeac495271d0f18"
      },
      {
        "title": "Reference: Request Parameters Summary",
        "body": "ParameterRequiredDescriptionchainIndexYesChain ID (e.g., 1 for Ethereum)amountYesAmount in raw units (with decimals)swapModeYesexactIn or exactOutfromTokenAddressYesSell token contract addresstoTokenAddressYesBuy token contract addressdexIdsNoComma-separated DEX IDs to restrict routingdirectRouteNotrue for single-pool only (Solana only)priceImpactProtectionPercentNoMax allowed price impact 0-100 (default 90)feePercentNoCommission fee percentage for integrators"
      }
    ],
    "body": "OKX DEX Aggregator Quote Skill\nOverview\n\nThis 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.\n\nKey capabilities:\n\nAuthenticated API requests with HMAC-SHA256 signing\nCorrect handling of token decimals and amount formatting\nSupport for exactIn (fixed input) and exactOut (fixed output) swap modes\nMulti-chain support (Ethereum, BSC, Arbitrum, Base, Solana, and 20+ chains)\nPrice impact protection and honeypot detection\nFee/commission splitting configuration\nPrerequisites\nRequired Credentials\n\nUsers must have an OKX Web3 API key set. The skill needs three values:\n\nOKX_ACCESS_KEY — API key\nOKX_SECRET_KEY — Secret key for HMAC signing\nOKX_PASSPHRASE — Account passphrase\nEnvironment\nPython: requests, hmac, hashlib, base64, datetime (all stdlib except requests)\nNode.js: axios or node-fetch, built-in crypto\nNo additional blockchain dependencies required (this is a read-only quote endpoint)\nAPI Endpoint\nGET https://web3.okx.com/api/v6/dex/aggregator/quote\n\nWorkflow\nStep 1: Validate User Input\n\nBefore constructing the API call, validate:\n\nChain ID (chainIndex) — Must be a supported chain. Common values:\n\n1 = Ethereum\n56 = BSC\n137 = Polygon\n42161 = Arbitrum\n8453 = Base\n130 = Unichain\n501 = Solana\n\nToken addresses — Must be valid contract addresses or the native token placeholder:\n\nNative tokens (ETH, BNB, etc.): 0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\nContract tokens: Full 42-character hex address (EVM) or base58 (Solana)\n\nAmount — MUST include token decimals. This is the #1 source of errors:\n\n1 ETH (18 decimals) → \"1000000000000000000\"\n1 USDT (6 decimals) → \"1000000\"\n1 WBTC (8 decimals) → \"100000000\"\nFormula: amount_raw = human_amount * (10 ** token_decimals)\n\nSwap mode — exactIn (default) or exactOut\n\nexactOut only supported on: Ethereum, Base, BSC, Arbitrum\nexactOut only works with Uniswap V2/V3 pools\nStep 2: Construct Authentication Headers\n\nOKX API requires HMAC-SHA256 signed requests with 4 headers:\n\nOK-ACCESS-KEY: <api_key>\nOK-ACCESS-SIGN: <hmac_signature>\nOK-ACCESS-PASSPHRASE: <passphrase>\nOK-ACCESS-TIMESTAMP: <iso8601_timestamp>\n\n\nSigning algorithm:\n\ntimestamp = ISO 8601 UTC time (e.g., \"2025-01-15T12:00:00.000Z\")\nprehash = timestamp + \"GET\" + request_path_with_query\nsignature = Base64(HMAC-SHA256(secret_key, prehash))\n\n\nCRITICAL: The request_path_with_query must include the full path starting from /api/... plus the query string. Example:\n\n/api/v6/dex/aggregator/quote?chainIndex=1&amount=1000000000000000000&fromTokenAddress=0xeee...&toTokenAddress=0xa0b...\n\nStep 3: Send Request and Parse Response\n\nSuccess response structure:\n\n{\n  \"code\": \"0\",\n  \"data\": [{\n    \"chainIndex\": \"1\",\n    \"fromToken\": { \"tokenSymbol\": \"ETH\", \"decimal\": \"18\", ... },\n    \"toToken\": { \"tokenSymbol\": \"USDC\", \"decimal\": \"6\", ... },\n    \"fromTokenAmount\": \"1000000000000000000\",\n    \"toTokenAmount\": \"3521432100\",\n    \"dexRouterList\": [...],\n    \"tradeFee\": \"2.45\",\n    \"estimateGasFee\": \"150000\",\n    \"priceImpactPercent\": \"-0.12\"\n  }],\n  \"msg\": \"\"\n}\n\n\nKey fields to extract:\n\ntoTokenAmount — The amount you'll receive (in raw units with decimals)\ntradeFee — Estimated network fee in USD\npriceImpactPercent — Negative = losing value; large negative = danger\ndexRouterList — Routing path through various DEX protocols\nfromToken.isHoneyPot / toToken.isHoneyPot — Scam token flag\nfromToken.taxRate / toToken.taxRate — Token buy/sell tax\nStep 4: Format Output for User\n\nConvert raw amounts back to human-readable:\n\nhuman_amount = raw_amount / (10 ** decimal)\n\n\nAlways display:\n\nExchange rate (e.g., \"1 ETH = 3,521.43 USDC\")\nPrice impact percentage with warning if > 3%\nEstimated gas fee in USD\nRouting summary (which DEXes are used)\nHoneypot warnings if detected\nToken tax rates if > 0\nBest Practices\nSecurity\nNEVER hardcode API credentials in generated code. Always use environment variables or config files.\nNEVER log the secret key or signature in debug output.\nValidate all token addresses against expected format before sending.\nCheck isHoneyPot flag on both tokens and warn the user prominently.\nAmount Handling\nAlways use string type for amounts to avoid floating-point precision loss.\nPython: Use int() for amount calculations, never float().\nJavaScript: Use BigInt or string math for amounts > 2^53.\nWhen user provides a human-readable amount like \"1.5 ETH\", convert: str(int(1.5 * 10**18)).\nError Handling\nCheck response[\"code\"] == \"0\" before accessing data.\nCommon error codes:\nNon-zero code with msg = API error (e.g., insufficient liquidity, invalid params)\nHTTP 401 = Authentication failure (check signature algorithm)\nHTTP 429 = Rate limited\nIf priceImpactPercent is null, warn that price impact couldn't be calculated.\nRate Limits\nRespect OKX rate limits. For production use, implement exponential backoff.\nCache quotes if polling repeatedly (quotes are valid for ~15-30 seconds).\nOptional Parameters Usage\ndexIds — Use when you want to restrict to specific DEXes (e.g., only Uniswap).\ndirectRoute=true — Only for Solana; forces single-pool routing.\npriceImpactProtectionPercent — Set to a sensible default like 10 for safety. Set to 100 to disable.\nfeePercent — For integrators taking commission. Max 3% (EVM) or 10% (Solana). Up to 9 decimal places.\nExamples\nExample 1: Python — Get ETH to USDC Quote on Ethereum\nimport os, hmac, hashlib, base64, requests\nfrom datetime import datetime, timezone\nfrom urllib.parse import urlencode\n\nAPI_KEY = os.environ[\"OKX_ACCESS_KEY\"]\nSECRET_KEY = os.environ[\"OKX_SECRET_KEY\"]\nPASSPHRASE = os.environ[\"OKX_PASSPHRASE\"]\n\ndef get_okx_quote(chain_index, from_token, to_token, amount, swap_mode=\"exactIn\"):\n    base_url = \"https://web3.okx.com\"\n    path = \"/api/v6/dex/aggregator/quote\"\n\n    params = {\n        \"chainIndex\": chain_index,\n        \"fromTokenAddress\": from_token,\n        \"toTokenAddress\": to_token,\n        \"amount\": amount,\n        \"swapMode\": swap_mode,\n    }\n\n    query_string = urlencode(params)\n    request_path = f\"{path}?{query_string}\"\n\n    # Generate timestamp and signature\n    timestamp = datetime.now(timezone.utc).strftime(\"%Y-%m-%dT%H:%M:%S.%f\")[:-3] + \"Z\"\n    prehash = timestamp + \"GET\" + request_path\n    signature = base64.b64encode(\n        hmac.new(SECRET_KEY.encode(), prehash.encode(), hashlib.sha256).digest()\n    ).decode()\n\n    headers = {\n        \"OK-ACCESS-KEY\": API_KEY,\n        \"OK-ACCESS-SIGN\": signature,\n        \"OK-ACCESS-PASSPHRASE\": PASSPHRASE,\n        \"OK-ACCESS-TIMESTAMP\": timestamp,\n    }\n\n    resp = requests.get(base_url + request_path, headers=headers)\n    resp.raise_for_status()\n    data = resp.json()\n\n    if data[\"code\"] != \"0\":\n        raise Exception(f\"OKX API error: {data['msg']}\")\n\n    return data[\"data\"][0]\n\n\n# Swap 1 ETH -> USDC on Ethereum\nETH = \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\"\nUSDC = \"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\"\namount = str(1 * 10**18)  # 1 ETH in wei\n\nquote = get_okx_quote(\"1\", ETH, USDC, amount)\n\nto_decimals = int(quote[\"toToken\"][\"decimal\"])\nreceived = int(quote[\"toTokenAmount\"]) / (10 ** to_decimals)\n\nprint(f\"You will receive: {received:,.2f} {quote['toToken']['tokenSymbol']}\")\nprint(f\"Price impact: {quote['priceImpactPercent']}%\")\nprint(f\"Gas fee (USD): ${quote['tradeFee']}\")\nprint(f\"Honeypot check: {'WARNING' if quote['toToken']['isHoneyPot'] else 'Safe'}\")\n\nExample 2: Node.js — Get Quote with Commission Fee\nconst crypto = require(\"crypto\");\nconst https = require(\"https\");\n\nconst API_KEY = process.env.OKX_ACCESS_KEY;\nconst SECRET_KEY = process.env.OKX_SECRET_KEY;\nconst PASSPHRASE = process.env.OKX_PASSPHRASE;\n\nfunction getQuote(chainIndex, fromToken, toToken, amount, options = {}) {\n  const params = new URLSearchParams({\n    chainIndex,\n    fromTokenAddress: fromToken,\n    toTokenAddress: toToken,\n    amount,\n    swapMode: options.swapMode || \"exactIn\",\n    ...(options.feePercent && { feePercent: options.feePercent }),\n    ...(options.priceImpactProtectionPercent && {\n      priceImpactProtectionPercent: options.priceImpactProtectionPercent,\n    }),\n  });\n\n  const path = `/api/v6/dex/aggregator/quote?${params}`;\n  const timestamp = new Date().toISOString();\n  const prehash = timestamp + \"GET\" + path;\n  const signature = crypto\n    .createHmac(\"sha256\", SECRET_KEY)\n    .update(prehash)\n    .digest(\"base64\");\n\n  return new Promise((resolve, reject) => {\n    const req = https.get(\n      `https://web3.okx.com${path}`,\n      {\n        headers: {\n          \"OK-ACCESS-KEY\": API_KEY,\n          \"OK-ACCESS-SIGN\": signature,\n          \"OK-ACCESS-PASSPHRASE\": PASSPHRASE,\n          \"OK-ACCESS-TIMESTAMP\": timestamp,\n        },\n      },\n      (res) => {\n        let body = \"\";\n        res.on(\"data\", (chunk) => (body += chunk));\n        res.on(\"end\", () => {\n          const data = JSON.parse(body);\n          if (data.code !== \"0\") reject(new Error(`OKX: ${data.msg}`));\n          else resolve(data.data[0]);\n        });\n      }\n    );\n    req.on(\"error\", reject);\n  });\n}\n\nExample 3: Understanding the Routing Path\nRouter: ETH -> WBTC -> USDC\ndexRouterList shows:\n  - 55% ETH -> WBTC via Uniswap V4\n  - 30% ETH -> USDC via Uniswap V4 (direct)\n  - WBTC -> USDC via Euler (73%) + Uniswap V4 (27%)\n\nThis means the aggregator splits the trade across multiple paths\nto minimize price impact and maximize output.\n\nTroubleshooting\nProblem\tCause\tSolution\n401 Unauthorized\tSignature mismatch\tVerify prehash string is exactly timestamp + \"GET\" + full_path_with_query. Check secret key encoding.\nAmount too small\tMissing decimal conversion\tMultiply human amount by 10 ** token_decimals. 1 USDT = 1000000, not 1.\nInvalid token address\tWrong chain/address combo\tVerify the token exists on the specified chain. Use native token placeholder for ETH/BNB/etc.\npriceImpactPercent very negative (< -10%)\tLow liquidity or large trade\tReduce trade size or split across multiple transactions.\nisHoneyPot: true\tScam token detected\tDo NOT proceed with the swap. Warn the user immediately.\nexactOut not working\tUnsupported chain/protocol\tOnly works on Ethereum, Base, BSC, Arbitrum with Uniswap V2/V3.\ntaxRate > 0\tToken has built-in tax\tFactor tax into expected output. E.g., 5% tax means receiving 5% less.\nEmpty dexRouterList\tNo liquidity path found\tTry a different token pair, smaller amount, or different chain.\ncode is non-zero\tGeneral API error\tRead msg field for details. Common: rate limit, maintenance, invalid params.\nReference: Common Chain IDs\nChain\tchainIndex\nEthereum\t1\nBSC\t56\nPolygon\t137\nArbitrum\t42161\nOptimism\t10\nAvalanche\t43114\nBase\t8453\nSolana\t501\nUnichain\t130\nReference: Common Token Addresses (Ethereum)\nToken\tAddress\tDecimals\nETH (native)\t0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\t18\nUSDT\t0xdac17f958d2ee523a2206206994597c13d831ec7\t6\nUSDC\t0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\t6\nWETH\t0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\t18\nWBTC\t0x2260fac5e5542a773aa44fbcfedf7c193bc2c599\t8\nDAI\t0x6b175474e89094c44da98b954eedeac495271d0f\t18\nReference: Request Parameters Summary\nParameter\tRequired\tDescription\nchainIndex\tYes\tChain ID (e.g., 1 for Ethereum)\namount\tYes\tAmount in raw units (with decimals)\nswapMode\tYes\texactIn or exactOut\nfromTokenAddress\tYes\tSell token contract address\ntoTokenAddress\tYes\tBuy token contract address\ndexIds\tNo\tComma-separated DEX IDs to restrict routing\ndirectRoute\tNo\ttrue for single-pool only (Solana only)\npriceImpactProtectionPercent\tNo\tMax allowed price impact 0-100 (default 90)\nfeePercent\tNo\tCommission fee percentage for integrators"
  },
  "trust": {
    "sourceLabel": "tencent",
    "provenanceUrl": "https://clawhub.ai/AaronLLee/dex-quote",
    "publisherUrl": "https://clawhub.ai/AaronLLee/dex-quote",
    "owner": "AaronLLee",
    "version": "1.0.0",
    "license": null,
    "verificationStatus": "Indexed source record"
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/dex-quote",
    "downloadUrl": "https://openagent3.xyz/downloads/dex-quote",
    "agentUrl": "https://openagent3.xyz/skills/dex-quote/agent",
    "manifestUrl": "https://openagent3.xyz/skills/dex-quote/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/dex-quote/agent.md"
  }
}