{"id":"2cfdf4ad-e1fd-45f3-accf-0fae368bf39a","entityType":"agent","slug":"clawhub-skills-aaronllee-easy-swap","name":"okx-dex-swap","canonicalUrl":"https://www.xpersona.co/agent/clawhub-skills-aaronllee-easy-swap","canonicalPath":"/agent/clawhub-skills-aaronllee-easy-swap","generatedAt":"2026-10-09T22:21:27.911Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"description":"Execute token swaps on-chain via OKX DEX Aggregator API (v6). Use this skill when a user wants to: 1. Build a complete swap flow: get swap calldata -> sign transaction -> broadcast to chain 2. Execute token-to-token swaps with slippage protection, MEV protection, and Jito tips (Solana) 3. Integrate OKX DEX swap + broadcast into applications, bots, or scripts This skill covers the FULL lifecycle: /swap endpoint (get tx data) + /broadcast-transaction endpoint (submit signed tx). For quote-only (no execution), use the okx-dex-quote skill instead. --- name: okx-dex-swap description: > Execute token swaps on-chain via OKX DEX Aggregator API (v6). Use this skill when a user wants to: 1. Build a complete swap flow: get swap calldata -> sign transaction -> broadcast to chain 2. Execute token-to-token swaps with slippage protection, MEV protection, and Jito tips (Solana) 3. Integrate OKX DEX swap + broadcast into applications, bots, or scripts This skill covers the","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. Last updated 4/15/2026.","installCommand":"clawhub skill install skills:aaronllee:easy-swap","sourceUrl":"https://github.com/openclaw/skills/tree/main/skills/aaronllee/easy-swap","homepage":null,"primaryLinks":[{"label":"View on ClawHub","url":"https://github.com/openclaw/skills/tree/main/skills/aaronllee/easy-swap","kind":"source"}],"safetyScore":84,"overallRank":62,"popularityScore":50,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Execute token swaps on-chain via OKX DEX Aggregator API (v6). Use this skill when a user wants to: 1. Build a complete swap flow: get swap calldata -> sign tran"},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[{"label":"receiving","status":"self-declared"}],"verifiedCount":0,"selfDeclaredCount":2,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"},{"key":"receiving","type":"capability","support":"supported","confidenceSource":"profile","notes":"Declared in agent profile metadata"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile capability:receiving|supported|profile"}},"adoption":{"evidence":{"source":"no-adoption-signals","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"No source adoption metrics were available."},"stars":null,"forks":null,"downloads":null,"packageName":null,"latestVersion":null,"tractionLabel":null},"release":{"evidence":{"source":"agent-index","verified":false,"confidence":"medium","updatedAt":"2026-02-25T05:54:48.356Z","emptyReason":null},"lastUpdatedAt":"2026-04-15T00:45:39.800Z","lastCrawledAt":"2026-02-25T05:54:48.356Z","lastIndexedAt":null,"nextCrawlAt":"2026-02-26T05:54:48.356Z","lastVerifiedAt":null,"highlights":[]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install skills:aaronllee:easy-swap","setupComplexity":"low","setupSteps":["Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-aaronllee-easy-swap/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-aaronllee-easy-swap/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-aaronllee-easy-swap/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-aaronllee-easy-swap/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-aaronllee-easy-swap/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-aaronllee-easy-swap/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-09T22:21:27.910Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-aaronllee-easy-swap/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-aaronllee-easy-swap/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-aaronllee-easy-swap/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-aaronllee-easy-swap/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"readme":"---\nname: okx-dex-swap\ndescription: >\n  Execute token swaps on-chain via OKX DEX Aggregator API (v6). Use this skill when a user wants to:\n  1. Build a complete swap flow: get swap calldata -> sign transaction -> broadcast to chain\n  2. Execute token-to-token swaps with slippage protection, MEV protection, and Jito tips (Solana)\n  3. Integrate OKX DEX swap + broadcast into applications, bots, or scripts\n  This skill covers the FULL lifecycle: /swap endpoint (get tx data) + /broadcast-transaction endpoint (submit signed tx).\n  For quote-only (no execution), use the okx-dex-quote skill instead.\nversion: 1.0.0\nallowed_tools: [bash_tool, create_file, str_replace, view]\nrequired_context: [api_key, secret_key, passphrase, user_wallet_address, private_key_or_signer]\nlicense: MIT\nauthor: Claude Assistant\ntags: [defi, dex, okx, swap, broadcast, web3, onchain, evm, solana, mev-protection]\n---\n\n# OKX DEX Swap & Broadcast Skill\n\n## Overview\n\nThis skill generates production-ready code for the **complete on-chain swap flow** using the OKX DEX Aggregator:\n\n```\n┌─────────┐     ┌──────────┐     ┌──────────┐     ┌───────────┐\n│  Quote   │ ──▶ │   Swap   │ ──▶ │   Sign   │ ──▶ │ Broadcast │\n│ (optional│     │ API Call │     │   Tx     │     │  to Chain │\n│  preview)│     │          │     │          │     │           │\n└─────────┘     └──────────┘     └──────────┘     └───────────┘\n```\n\n**Two API endpoints involved:**\n\n| Step | Endpoint | Method | Purpose |\n|------|----------|--------|---------|\n| Swap | `/api/v6/dex/aggregator/swap` | GET | Get transaction calldata for the swap |\n| Broadcast | `/api/v6/dex/pre-transaction/broadcast-transaction` | POST | Submit signed transaction to the chain |\n\n**Key features:**\n- Full swap lifecycle with transaction signing\n- Auto-slippage calculation based on market conditions\n- MEV (sandwich attack) protection on ETH, BSC, SOL, BASE\n- Jito tips for Solana priority transactions\n- Token approval handling (ERC-20 approve)\n- Commission/referral fee splitting\n- Price impact protection with configurable thresholds\n\n## Prerequisites\n\n### Required Credentials\n- `OKX_ACCESS_KEY` — API key\n- `OKX_SECRET_KEY` — Secret key for HMAC signing\n- `OKX_PASSPHRASE` — Account passphrase\n\n### Wallet Requirements\n- **EVM chains**: Private key or a signer (e.g., web3.py Account, ethers.js Wallet)\n- **Solana**: Keypair for transaction signing\n- The wallet must have sufficient balance of the `fromToken` and native token for gas\n\n### Environment\n- **Python**: `requests`, `web3` (for EVM signing), `solders` / `solana-py` (for Solana)\n- **Node.js**: `axios`, `ethers` (for EVM signing), `@solana/web3.js` (for Solana)\n\n## Workflow\n\n### Step 1: Call the Swap API\n\n**Endpoint:**\n```\nGET https://web3.okx.com/api/v6/dex/aggregator/swap\n```\n\n**Required parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `chainIndex` | String | Yes | Chain ID (e.g., `1` = Ethereum, `501` = Solana) |\n| `amount` | String | Yes | Amount in raw units with decimals (e.g., `1000000` for 1 USDT) |\n| `swapMode` | String | Yes | `exactIn` (default) or `exactOut` |\n| `fromTokenAddress` | String | Yes | Sell token contract address |\n| `toTokenAddress` | String | Yes | Buy token contract address |\n| `slippagePercent` | String | Yes | Slippage tolerance (e.g., `0.5` = 0.5%). EVM: 0-100, Solana: 0 to <100 |\n| `userWalletAddress` | String | Yes | User's wallet address that will sign and send the tx |\n\n**Important optional parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `approveTransaction` | Boolean | Set `true` to get ERC-20 approval calldata in response |\n| `approveAmount` | String | Custom approval amount (raw units). If omitted, approves exact swap amount |\n| `swapReceiverAddress` | String | Recipient address if different from sender |\n| `feePercent` | String | Commission fee %. Max 3% (EVM) / 10% (Solana) |\n| `fromTokenReferrerWalletAddress` | String | Wallet to receive fromToken commission |\n| `toTokenReferrerWalletAddress` | String | Wallet to receive toToken commission |\n| `autoSlippage` | Boolean | Auto-calculate optimal slippage (overrides `slippagePercent`) |\n| `maxAutoslippagePercent` | String | Cap for auto-slippage |\n| `priceImpactProtectionPercent` | String | Max price impact allowed (0-100, default 90) |\n| `gasLevel` | String | `slow`, `average` (default), or `fast` |\n| `gaslimit` | String | Custom gas limit in wei (EVM only) |\n| `dexIds` | String | Restrict to specific DEX IDs (comma-separated) |\n| `excludeDexIds` | String | Exclude specific DEX IDs (comma-separated) |\n| `directRoute` | Boolean | Single-pool routing only (Solana only) |\n| `disableRFQ` | String | Disable time-sensitive RFQ liquidity sources |\n| `callDataMemo` | String | Custom 64-byte hex data to include on-chain |\n\n**Solana-specific parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `computeUnitPrice` | String | Priority fee (like gasPrice on EVM) |\n| `computeUnitLimit` | String | Compute budget (like gasLimit on EVM) |\n| `tips` | String | Jito tips in SOL (min 0.0000000001, max 2). Set `computeUnitPrice=0` when using tips |\n\n**Swap API response structure:**\n\n```json\n{\n  \"code\": \"0\",\n  \"data\": [{\n    \"routerResult\": {\n      \"chainIndex\": \"1\",\n      \"fromToken\": { \"tokenSymbol\": \"USDC\", \"decimal\": \"6\", ... },\n      \"toToken\": { \"tokenSymbol\": \"WBTC\", \"decimal\": \"8\", ... },\n      \"fromTokenAmount\": \"100000000000\",\n      \"toTokenAmount\": \"90281915\",\n      \"tradeFee\": \"1.35\",\n      \"estimateGasFee\": \"1248837\",\n      \"priceImpactPercent\": \"0.07\",\n      \"dexRouterList\": [...]\n    },\n    \"tx\": {\n      \"from\": \"0x77660f...\",\n      \"to\": \"0x5E1f62...\",\n      \"value\": \"0\",\n      \"data\": \"0xf2c42696...\",\n      \"gas\": \"1248837\",\n      \"gasPrice\": \"557703374\",\n      \"maxPriorityFeePerGas\": \"500000000\",\n      \"minReceiveAmount\": \"90191633\",\n      \"slippagePercent\": \"0.1\",\n      \"signatureData\": [...]\n    }\n  }],\n  \"msg\": \"\"\n}\n```\n\n**Key fields in `tx` object:**\n\n| Field | Description |\n|-------|-------------|\n| `from` | Sender wallet address |\n| `to` | OKX DEX router contract address |\n| `data` | Transaction calldata (the swap instruction) |\n| `value` | Native token amount to send (in wei). `\"0\"` for ERC-20 swaps |\n| `gas` | Estimated gas limit (already padded +50%) |\n| `gasPrice` | Gas price in wei |\n| `maxPriorityFeePerGas` | EIP-1559 priority fee |\n| `minReceiveAmount` | Minimum output at max slippage |\n| `signatureData` | Approval calldata (if `approveTransaction=true`) or Jito tips calldata |\n\n### Step 2: Handle Token Approval (EVM Only)\n\nFor ERC-20 tokens (not native ETH/BNB), you need to approve the DEX router to spend your tokens BEFORE the swap.\n\n**When `approveTransaction=true` in the request:**\nThe response `tx.signatureData` contains the approval info:\n```json\n{\n  \"approveContract\": \"0x40aA958dd87FC8305b97f2BA922CDdCa374bcD7f\",\n  \"approveTxCalldata\": \"0x095ea7b3...\"\n}\n```\n\n**Approval flow:**\n1. Parse `signatureData` to get `approveContract` and `approveTxCalldata`\n2. Send an approval transaction: `to=approveContract`, `data=approveTxCalldata`\n3. Wait for approval tx to be confirmed\n4. Then send the swap transaction\n\n**IMPORTANT**: For native tokens (ETH, BNB, etc. using `0xeeee...eeee`), no approval is needed.\n\n### Step 3: Sign the Transaction\n\n**EVM chains (Python / web3.py):**\n```python\ntx_params = {\n    \"from\": tx_data[\"from\"],\n    \"to\": tx_data[\"to\"],\n    \"value\": int(tx_data[\"value\"]),\n    \"data\": tx_data[\"data\"],\n    \"gas\": int(tx_data[\"gas\"]),\n    \"gasPrice\": int(tx_data[\"gasPrice\"]),\n    \"nonce\": w3.eth.get_transaction_count(wallet_address),\n    \"chainId\": chain_id,\n}\nsigned = w3.eth.account.sign_transaction(tx_params, private_key)\nsigned_tx_hex = signed.raw_transaction.hex()\n```\n\n**EVM chains (Node.js / ethers.js):**\n```javascript\nconst tx = {\n  from: txData.from,\n  to: txData.to,\n  value: txData.value,\n  data: txData.data,\n  gasLimit: txData.gas,\n  gasPrice: txData.gasPrice,\n  nonce: await provider.getTransactionCount(walletAddress),\n  chainId: chainId,\n};\nconst signedTx = await wallet.signTransaction(tx);\n```\n\n**Solana:**\nUse `solders` or `@solana/web3.js` to deserialize, sign, and serialize the transaction from `tx.data`.\n\n### Step 4: Broadcast the Signed Transaction\n\n**Endpoint:**\n```\nPOST https://web3.okx.com/api/v6/dex/pre-transaction/broadcast-transaction\n```\n\n**IMPORTANT**: This is a POST request with a JSON body (unlike the GET-based swap/quote endpoints).\n\n**Request body:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `signedTx` | String | Yes | The hex-encoded signed transaction string |\n| `chainIndex` | String | Yes | Chain ID (e.g., `\"1\"` for Ethereum) |\n| `address` | String | Yes | Sender wallet address |\n| `extraData` | String | No | JSON string with extra options (see below) |\n\n**extraData options (JSON string):**\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `enableMevProtection` | Boolean | Enable MEV (sandwich) protection. Supported: ETH, BSC, SOL, BASE |\n| `jitoSignedTx` | String | Base58-encoded signed Jito transaction (Solana only). Required when `tips` > 0 |\n\n**Signing algorithm for POST requests:**\n```\nprehash = timestamp + \"POST\" + request_path + json_body\nsignature = Base64(HMAC-SHA256(secret_key, prehash))\n```\n\nNote: For POST, the `request_path` has NO query string. The JSON body is appended directly to the prehash string.\n\n**Broadcast response:**\n```json\n{\n  \"code\": \"0\",\n  \"data\": [{\n    \"orderId\": \"0e1d79837afce1e149b6ab54b6e2edce8130c3f8\",\n    \"txHash\": \"0xd394f356a16b618ed839c66c935c9cccc5dde0af832ff9b468677eea38759db5\"\n  }],\n  \"msg\": \"\"\n}\n```\n\n| Field | Description |\n|-------|-------------|\n| `orderId` | OKX internal order tracking ID |\n| `txHash` | On-chain transaction hash. Use this to check status on block explorer |\n\n### Step 5: Verify Transaction\n\nAfter broadcasting, verify the transaction was confirmed:\n- **EVM**: Check `txHash` on Etherscan / block explorer, or use `web3.eth.wait_for_transaction_receipt()`\n- **Solana**: Check on Solscan, or use `connection.confirmTransaction()`\n\n## Best Practices\n\n### Security\n- **NEVER hardcode private keys** in code. Use environment variables, keystore files, or hardware wallets.\n- **NEVER log private keys, signed transactions, or secret keys** in production.\n- Always validate token addresses and amounts before sending.\n- Check `isHoneyPot` on both tokens before proceeding.\n- Use `priceImpactProtectionPercent` (recommend setting to `10` or lower for safety).\n\n### Slippage Configuration\n- **Stable pairs** (USDC/USDT): `0.1%` - `0.5%`\n- **Major pairs** (ETH/USDC): `0.5%` - `1%`\n- **Volatile/low-liquidity tokens**: `1%` - `5%`\n- **Meme coins**: `5%` - `15%` (or higher, but be cautious)\n- Use `autoSlippage=true` with `maxAutoslippagePercent` for optimal auto-calculation.\n\n### MEV Protection\n- Enable `enableMevProtection: true` for large trades on ETH, BSC, SOL, BASE.\n- On Solana, combine with Jito tips for priority + MEV protection.\n- When using Jito tips, set `computeUnitPrice=0` to avoid wasting fees.\n\n### Token Approval Strategy\n- For one-time swaps: approve exact amount (`approveAmount = swap amount`).\n- For repeated swaps: consider a larger approval (e.g., max uint256) to save gas on future swaps, but understand the security trade-off.\n- Always check existing allowance before sending a new approval.\n\n### Uni V3 Liquidity Edge Case\nWhen swapping through Uniswap V3 pools, if the liquidity for the pair is drained mid-swap, the router will only consume part of your input tokens. The OKX DEX Router smart contract will automatically refund the remainder. Ensure your integration contract supports receiving token refunds.\n\n### Amount Handling\n- **Always use strings** for amounts to avoid floating-point precision loss.\n- Python: `int()` for calculations, never `float()`.\n- JavaScript: `BigInt` or `ethers.parseUnits()` for amounts.\n- Formula: `raw_amount = human_amount * 10^decimals`\n\n### Error Handling\n- Check `response[\"code\"] == \"0\"` before processing.\n- If broadcast fails, do NOT automatically retry without checking nonce — you may double-spend.\n- Common errors:\n  - `401` = Signature mismatch (check POST signing includes body)\n  - `429` = Rate limited\n  - Swap returns error = insufficient balance, invalid params, or liquidity issue\n  - Broadcast returns error = already executed, nonce too low, insufficient gas\n\n### Commission/Referral Fees\n- Only ONE of `fromTokenReferrerWalletAddress` or `toTokenReferrerWalletAddress` per tx.\n- Solana: referrer wallet must have SOL deposited for activation.\n- TON: limited DEX support (Stonfi V2, Dedust).\n- BSC: no commission through Four.meme swaps.\n\n## Examples\n\n### Example 1: Python — Complete EVM Swap Flow\n\n```python\nimport os, hmac, hashlib, base64, json, requests\nfrom datetime import datetime, timezone\nfrom urllib.parse import urlencode\nfrom web3 import Web3\n\n# === Configuration ===\nAPI_KEY = os.environ[\"OKX_ACCESS_KEY\"]\nSECRET_KEY = os.environ[\"OKX_SECRET_KEY\"]\nPASSPHRASE = os.environ[\"OKX_PASSPHRASE\"]\nPRIVATE_KEY = os.environ[\"WALLET_PRIVATE_KEY\"]\n\nBASE_URL = \"https://web3.okx.com\"\nCHAIN_INDEX = \"1\"  # Ethereum\nCHAIN_ID = 1\nRPC_URL = \"https://eth.llamarpc.com\"\n\nw3 = Web3(Web3.HTTPProvider(RPC_URL))\naccount = w3.eth.account.from_key(PRIVATE_KEY)\nWALLET = account.address\n\n\ndef _sign_request(timestamp, method, request_path, body=\"\"):\n    prehash = timestamp + method + request_path + body\n    mac = hmac.new(SECRET_KEY.encode(), prehash.encode(), hashlib.sha256)\n    return base64.b64encode(mac.digest()).decode()\n\n\ndef _headers(method, request_path, body=\"\"):\n    timestamp = datetime.now(timezone.utc).strftime(\"%Y-%m-%dT%H:%M:%S.%f\")[:-3] + \"Z\"\n    sig = _sign_request(timestamp, method, request_path, body)\n    return {\n        \"OK-ACCESS-KEY\": API_KEY,\n        \"OK-ACCESS-SIGN\": sig,\n        \"OK-ACCESS-PASSPHRASE\": PASSPHRASE,\n        \"OK-ACCESS-TIMESTAMP\": timestamp,\n        \"Content-Type\": \"application/json\",\n    }\n\n\n# --- Step 1: Get swap calldata ---\ndef get_swap_data(from_token, to_token, amount, slippage=\"0.5\"):\n    params = {\n        \"chainIndex\": CHAIN_INDEX,\n        \"fromTokenAddress\": from_token,\n        \"toTokenAddress\": to_token,\n        \"amount\": amount,\n        \"swapMode\": \"exactIn\",\n        \"slippagePercent\": slippage,\n        \"userWalletAddress\": WALLET,\n        \"approveTransaction\": \"true\",\n    }\n    query = urlencode(params)\n    path = f\"/api/v6/dex/aggregator/swap?{query}\"\n    headers = _headers(\"GET\", path)\n\n    resp = requests.get(BASE_URL + path, headers=headers, timeout=30)\n    resp.raise_for_status()\n    data = resp.json()\n\n    if data[\"code\"] != \"0\":\n        raise Exception(f\"Swap API error: {data['msg']}\")\n    return data[\"data\"][0]\n\n\n# --- Step 2: Handle approval (if needed) ---\ndef send_approval_if_needed(swap_result):\n    sig_data = swap_result[\"tx\"].get(\"signatureData\", [])\n    if not sig_data:\n        return None\n\n    for item in sig_data:\n        parsed = json.loads(item) if isinstance(item, str) else item\n        if \"approveContract\" in parsed:\n            approve_tx = {\n                \"from\": WALLET,\n                \"to\": Web3.to_checksum_address(parsed[\"approveContract\"]),\n                \"data\": parsed[\"approveTxCalldata\"],\n                \"gas\": 60000,\n                \"gasPrice\": w3.eth.gas_price,\n                \"nonce\": w3.eth.get_transaction_count(WALLET),\n                \"chainId\": CHAIN_ID,\n            }\n            signed = w3.eth.account.sign_transaction(approve_tx, PRIVATE_KEY)\n            tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)\n            receipt = w3.eth.wait_for_transaction_receipt(tx_hash, timeout=120)\n            print(f\"Approval confirmed: {tx_hash.hex()}\")\n            return receipt\n    return None\n\n\n# --- Step 3: Sign the swap transaction ---\ndef sign_swap_tx(swap_result):\n    tx_data = swap_result[\"tx\"]\n    tx_params = {\n        \"from\": Web3.to_checksum_address(tx_data[\"from\"]),\n        \"to\": Web3.to_checksum_address(tx_data[\"to\"]),\n        \"value\": int(tx_data[\"value\"]),\n        \"data\": tx_data[\"data\"],\n        \"gas\": int(tx_data[\"gas\"]),\n        \"gasPrice\": int(tx_data[\"gasPrice\"]),\n        \"nonce\": w3.eth.get_transaction_count(WALLET),\n        \"chainId\": CHAIN_ID,\n    }\n    signed = w3.eth.account.sign_transaction(tx_params, PRIVATE_KEY)\n    return signed.raw_transaction.hex()\n\n\n# --- Step 4: Broadcast via OKX ---\ndef broadcast_tx(signed_tx_hex, enable_mev=True):\n    path = \"/api/v6/dex/pre-transaction/broadcast-transaction\"\n    body_dict = {\n        \"chainIndex\": CHAIN_INDEX,\n        \"address\": WALLET,\n        \"signedTx\": signed_tx_hex,\n    }\n    if enable_mev:\n        body_dict[\"extraData\"] = json.dumps({\"enableMevProtection\": True})\n\n    body_str = json.dumps(body_dict)\n    headers = _headers(\"POST\", path, body_str)\n\n    resp = requests.post(BASE_URL + path, headers=headers, data=body_str, timeout=30)\n    resp.raise_for_status()\n    data = resp.json()\n\n    if data[\"code\"] != \"0\":\n        raise Exception(f\"Broadcast error: {data['msg']}\")\n    return data[\"data\"][0]\n\n\n# === Execute full swap ===\nif __name__ == \"__main__\":\n    ETH = \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\"\n    USDC = \"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\"\n    amount = str(10 ** 17)  # 0.1 ETH\n\n    print(\"1. Getting swap data...\")\n    swap = get_swap_data(ETH, USDC, amount, slippage=\"0.5\")\n\n    router = swap[\"routerResult\"]\n    to_dec = int(router[\"toToken\"][\"decimal\"])\n    out_human = int(router[\"toTokenAmount\"]) / (10 ** to_dec)\n    print(f\"   Expected output: {out_human:,.2f} {router['toToken']['tokenSymbol']}\")\n    print(f\"   Price impact: {router.get('priceImpactPercent', 'N/A')}%\")\n    print(f\"   Min receive: {int(swap['tx']['minReceiveAmount']) / (10 ** to_dec):,.2f}\")\n\n    # Honeypot check\n    if router[\"toToken\"].get(\"isHoneyPot\"):\n        print(\"   HONEYPOT DETECTED — aborting!\")\n        exit(1)\n\n    print(\"2. Handling approval...\")\n    send_approval_if_needed(swap)\n\n    print(\"3. Signing swap transaction...\")\n    signed_hex = sign_swap_tx(swap)\n\n    print(\"4. Broadcasting with MEV protection...\")\n    result = broadcast_tx(signed_hex, enable_mev=True)\n    print(f\"   Order ID: {result['orderId']}\")\n    print(f\"   Tx Hash: {result['txHash']}\")\n    print(f\"   View: https://etherscan.io/tx/{result['txHash']}\")\n```\n\n### Example 2: Node.js — Complete EVM Swap Flow\n\n```javascript\nconst crypto = require(\"crypto\");\nconst https = require(\"https\");\nconst { ethers } = require(\"ethers\");\n\nconst API_KEY = process.env.OKX_ACCESS_KEY;\nconst SECRET_KEY = process.env.OKX_SECRET_KEY;\nconst PASSPHRASE = process.env.OKX_PASSPHRASE;\nconst PRIVATE_KEY = process.env.WALLET_PRIVATE_KEY;\n\nconst BASE_URL = \"https://web3.okx.com\";\nconst CHAIN_INDEX = \"1\";\nconst CHAIN_ID = 1;\n\nconst provider = new ethers.JsonRpcProvider(\"https://eth.llamarpc.com\");\nconst wallet = new ethers.Wallet(PRIVATE_KEY, provider);\n\nfunction sign(timestamp, method, path, body = \"\") {\n  return crypto\n    .createHmac(\"sha256\", SECRET_KEY)\n    .update(timestamp + method + path + body)\n    .digest(\"base64\");\n}\n\nfunction headers(method, path, body = \"\") {\n  const ts = new Date().toISOString();\n  return {\n    \"OK-ACCESS-KEY\": API_KEY,\n    \"OK-ACCESS-SIGN\": sign(ts, method, path, body),\n    \"OK-ACCESS-PASSPHRASE\": PASSPHRASE,\n    \"OK-ACCESS-TIMESTAMP\": ts,\n    \"Content-Type\": \"application/json\",\n  };\n}\n\nasync function getSwapData(fromToken, toToken, amount, slippage = \"0.5\") {\n  const params = new URLSearchParams({\n    chainIndex: CHAIN_INDEX,\n    fromTokenAddress: fromToken,\n    toTokenAddress: toToken,\n    amount,\n    swapMode: \"exactIn\",\n    slippagePercent: slippage,\n    userWalletAddress: wallet.address,\n    approveTransaction: \"true\",\n  });\n  const path = `/api/v6/dex/aggregator/swap?${params}`;\n  const h = headers(\"GET\", path);\n\n  const resp = await fetch(`${BASE_URL}${path}`, { headers: h });\n  const data = await resp.json();\n  if (data.code !== \"0\") throw new Error(`Swap error: ${data.msg}`);\n  return data.data[0];\n}\n\nasync function broadcastTx(signedTx, enableMev = true) {\n  const path = \"/api/v6/dex/pre-transaction/broadcast-transaction\";\n  const bodyObj = {\n    chainIndex: CHAIN_INDEX,\n    address: wallet.address,\n    signedTx,\n    ...(enableMev && {\n      extraData: JSON.stringify({ enableMevProtection: true }),\n    }),\n  };\n  const bodyStr = JSON.stringify(bodyObj);\n  const h = headers(\"POST\", path, bodyStr);\n\n  const resp = await fetch(`${BASE_URL}${path}`, {\n    method: \"POST\",\n    headers: h,\n    body: bodyStr,\n  });\n  const data = await resp.json();\n  if (data.code !== \"0\") throw new Error(`Broadcast error: ${data.msg}`);\n  return data.data[0];\n}\n\nasync function main() {\n  const ETH = \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\";\n  const USDC = \"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\";\n  const amount = (10n ** 17n).toString(); // 0.1 ETH\n\n  console.log(\"1. Getting swap data...\");\n  const swap = await getSwapData(ETH, USDC, amount);\n\n  const txData = swap.tx;\n  console.log(`   Min receive: ${txData.minReceiveAmount}`);\n\n  console.log(\"2. Signing transaction...\");\n  const tx = {\n    from: txData.from,\n    to: txData.to,\n    value: txData.value,\n    data: txData.data,\n    gasLimit: txData.gas,\n    gasPrice: txData.gasPrice,\n    nonce: await provider.getTransactionCount(wallet.address),\n    chainId: CHAIN_ID,\n  };\n  const signedTx = await wallet.signTransaction(tx);\n\n  console.log(\"3. Broadcasting with MEV protection...\");\n  const result = await broadcastTx(signedTx);\n  console.log(`   Tx Hash: ${result.txHash}`);\n}\n\nmain().catch(console.error);\n```\n\n### Example 3: Solana Swap with Jito Tips\n\nWhen using Jito tips on Solana:\n1. Set `tips` parameter (e.g., `\"0.001\"` SOL) in the swap request\n2. Set `computeUnitPrice=0` (avoid double-paying for priority)\n3. The `signatureData` in response contains the Jito tips calldata\n4. Sign BOTH the main transaction AND the Jito transaction\n5. Broadcast with both `signedTx` and `jitoSignedTx` in `extraData`\n\n```python\n# Solana-specific broadcast with Jito\nbody = {\n    \"chainIndex\": \"501\",\n    \"address\": solana_wallet_pubkey,\n    \"signedTx\": base58_signed_main_tx,\n    \"extraData\": json.dumps({\n        \"enableMevProtection\": True,\n        \"jitoSignedTx\": base58_signed_jito_tx\n    })\n}\n```\n\n**IMPORTANT**: For Solana, `signedTx` and `jitoSignedTx` must BOTH be provided when using tips.\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `401 Unauthorized` on broadcast | POST signing error | Ensure prehash = `timestamp + \"POST\" + path + jsonBody`. The body must be the exact JSON string. |\n| `401 Unauthorized` on swap | GET signing error | Ensure prehash = `timestamp + \"GET\" + path_with_query_string`. |\n| Approval tx fails | Insufficient ETH for gas | Ensure wallet has native token for gas fees. |\n| Swap tx reverts | Slippage exceeded | Increase `slippagePercent` or use `autoSlippage=true`. |\n| `minReceiveAmount` is 0 | Extreme slippage or bad params | Check token addresses and amounts. Reduce trade size. |\n| Broadcast returns no txHash | MEV protection routing delay | Wait and check `orderId` status. MEV-protected txs may take longer. |\n| \"Nonce too low\" on broadcast | Tx already sent or nonce reused | Fetch fresh nonce before signing. Never reuse nonces. |\n| Solana broadcast fails | Missing `jitoSignedTx` | When `tips > 0`, you must provide both `signedTx` and `jitoSignedTx`. |\n| Token refund not received | Uni V3 liquidity drained | Ensure your contract supports receiving token refunds from the router. |\n| Commission not working on BSC | Four.meme restriction | Commission is not supported for swaps through Four.meme on BSC. |\n| `priceImpactPercent` very negative | Low liquidity | Reduce amount or split into multiple smaller swaps. |\n\n## Reference: POST vs GET Signing\n\nThe OKX API uses different signing for GET and POST:\n\n| Method | Prehash Format |\n|--------|---------------|\n| GET | `timestamp + \"GET\" + path_with_query` |\n| POST | `timestamp + \"POST\" + path + json_body` |\n\nThe Swap endpoint is **GET**, the Broadcast endpoint is **POST**. Getting this wrong is the #1 cause of `401` errors.\n\n## Reference: MEV Protection Support\n\n| Chain | `enableMevProtection` | Jito Tips |\n|-------|----------------------|-----------|\n| Ethereum | Yes | No |\n| BSC | Yes | No |\n| Solana | Yes | Yes |\n| Base | Yes | No |\n| Others | Not yet | Not yet |\n\n## Reference: Common Chain IDs\n\n| Chain | chainIndex | Chain ID (for tx signing) |\n|-------|-----------|--------------------------|\n| Ethereum | 1 | 1 |\n| BSC | 56 | 56 |\n| Polygon | 137 | 137 |\n| Arbitrum | 42161 | 42161 |\n| Optimism | 10 | 10 |\n| Base | 8453 | 8453 |\n| Avalanche | 43114 | 43114 |\n| Solana | 501 | N/A |\n| Unichain | 130 | 130 |\n","readmeExcerpt":"--- name: okx-dex-swap description: > Execute token swaps on-chain via OKX DEX Aggregator API (v6). Use this skill when a user wants to: 1. Build a complete swap flow: get swap calldata -> sign transaction -> broadcast to chain 2. Execute token-to-token swaps with slippage protection, MEV protection, and Jito tips (Solana) 3. Integrate OKX DEX swap + broadcast into applications, bots, or scripts This skill covers the","codeSnippets":[],"executableExamples":[{"language":"text","snippet":"┌─────────┐     ┌──────────┐     ┌──────────┐     ┌───────────┐\n│  Quote   │ ──▶ │   Swap   │ ──▶ │   Sign   │ ──▶ │ Broadcast │\n│ (optional│     │ API Call │     │   Tx     │     │  to Chain │\n│  preview)│     │          │     │          │     │           │\n└─────────┘     └──────────┘     └──────────┘     └───────────┘"},{"language":"text","snippet":"GET https://web3.okx.com/api/v6/dex/aggregator/swap"},{"language":"json","snippet":"{\n  \"code\": \"0\",\n  \"data\": [{\n    \"routerResult\": {\n      \"chainIndex\": \"1\",\n      \"fromToken\": { \"tokenSymbol\": \"USDC\", \"decimal\": \"6\", ... },\n      \"toToken\": { \"tokenSymbol\": \"WBTC\", \"decimal\": \"8\", ... },\n      \"fromTokenAmount\": \"100000000000\",\n      \"toTokenAmount\": \"90281915\",\n      \"tradeFee\": \"1.35\",\n      \"estimateGasFee\": \"1248837\",\n      \"priceImpactPercent\": \"0.07\",\n      \"dexRouterList\": [...]\n    },\n    \"tx\": {\n      \"from\": \"0x77660f...\",\n      \"to\": \"0x5E1f62...\",\n      \"value\": \"0\",\n      \"data\": \"0xf2c42696...\",\n      \"gas\": \"1248837\",\n      \"gasPrice\": \"557703374\",\n      \"maxPriorityFeePerGas\": \"500000000\",\n      \"minReceiveAmount\": \"90191633\",\n      \"slippagePercent\": \"0.1\",\n      \"signatureData\": [...]\n    }\n  }],\n  \"msg\": \"\"\n}"},{"language":"json","snippet":"{\n  \"approveContract\": \"0x40aA958dd87FC8305b97f2BA922CDdCa374bcD7f\",\n  \"approveTxCalldata\": \"0x095ea7b3...\"\n}"},{"language":"python","snippet":"tx_params = {\n    \"from\": tx_data[\"from\"],\n    \"to\": tx_data[\"to\"],\n    \"value\": int(tx_data[\"value\"]),\n    \"data\": tx_data[\"data\"],\n    \"gas\": int(tx_data[\"gas\"]),\n    \"gasPrice\": int(tx_data[\"gasPrice\"]),\n    \"nonce\": w3.eth.get_transaction_count(wallet_address),\n    \"chainId\": chain_id,\n}\nsigned = w3.eth.account.sign_transaction(tx_params, private_key)\nsigned_tx_hex = signed.raw_transaction.hex()"},{"language":"javascript","snippet":"const tx = {\n  from: txData.from,\n  to: txData.to,\n  value: txData.value,\n  data: txData.data,\n  gasLimit: txData.gas,\n  gasPrice: txData.gasPrice,\n  nonce: await provider.getTransactionCount(walletAddress),\n  chainId: chainId,\n};\nconst signedTx = await wallet.signTransaction(tx);"}],"parameters":{},"dependencies":[],"permissions":[],"extractedFiles":[],"languages":["typescript"],"docsSourceLabel":"CLAWHUB","editorialOverview":"Execute token swaps on-chain via OKX DEX Aggregator API (v6). Use this skill when a user wants to: 1. Build a complete swap flow: get swap calldata -> sign transaction -> broadcast to chain 2. Execute token-to-token swaps with slippage protection, MEV protection, and Jito tips (Solana) 3. Integrate OKX DEX swap + broadcast into applications, bots, or scripts This skill covers the FULL lifecycle: /swap endpoint (get tx data) + /broadcast-transaction endpoint (submit signed tx). For quote-only (no execution), use the okx-dex-quote skill instead. --- name: okx-dex-swap description: > Execute token swaps on-chain via OKX DEX Aggregator API (v6). Use this skill when a user wants to: 1. Build a complete swap flow: get swap calldata -> sign transaction -> broadcast to chain 2. Execute token-to-token swaps with slippage protection, MEV protection, and Jito tips (Solana) 3. Integrate OKX DEX swap + broadcast into applications, bots, or scripts This skill covers the","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":456,"uniquenessScore":56,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-09T22:21:27.911Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}