[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77D2FZM9NXCH73N8BQGBDWA":3,"skill-same:01M77D2FZM9NXCH73N8BQGBDWA":72},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":49,"commitSha":50,"skillDirectory":51,"forksCount":52,"repositoryHtmlUrl":53,"repositoryHomepageUrl":54,"ownerHtmlUrl":55,"ownerBlogUrl":6,"ownerDescription":56,"updatedAt":57,"install":58,"resources":71},"01M77D2FZM9NXCH73N8BQGBDWA","okx-dex-swap",null,"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: \u002Fswap endpoint (get tx data) + \u002Fbroadcast-transaction endpoint (submit signed tx). For quote-only (no execution), use the okx-dex-quote skill instead.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fe\u002Feasy-swap\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\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: \u002Fswap endpoint (get tx data) + \u002Fbroadcast-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 | `\u002Fapi\u002Fv6\u002Fdex\u002Faggregator\u002Fswap` | GET | Get transaction calldata for the swap |\n| Broadcast | `\u002Fapi\u002Fv6\u002Fdex\u002Fpre-transaction\u002Fbroadcast-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\u002Freferral 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` \u002F `solana-py` (for Solana)\n- **Node.js**: `axios`, `ethers` (for EVM signing), `@solana\u002Fweb3.js` (for Solana)\n\n## Workflow\n\n### Step 1: Call the Swap API\n\n**Endpoint:**\n```\nGET https:\u002F\u002Fweb3.okx.com\u002Fapi\u002Fv6\u002Fdex\u002Faggregator\u002Fswap\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 \u003C100 |\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) \u002F 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\u002FBNB), 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 \u002F 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 \u002F 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\u002Fweb3.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:\u002F\u002Fweb3.okx.com\u002Fapi\u002Fv6\u002Fdex\u002Fpre-transaction\u002Fbroadcast-transaction\n```\n\n**IMPORTANT**: This is a POST request with a JSON body (unlike the GET-based swap\u002Fquote 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 \u002F 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\u002FUSDT): `0.1%` - `0.5%`\n- **Major pairs** (ETH\u002FUSDC): `0.5%` - `1%`\n- **Volatile\u002Flow-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\u002FReferral 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:\u002F\u002Fweb3.okx.com\"\nCHAIN_INDEX = \"1\"  # Ethereum\nCHAIN_ID = 1\nRPC_URL = \"https:\u002F\u002Feth.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\u002Fjson\",\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\"\u002Fapi\u002Fv6\u002Fdex\u002Faggregator\u002Fswap?{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 = \"\u002Fapi\u002Fv6\u002Fdex\u002Fpre-transaction\u002Fbroadcast-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\"]) \u002F (10 ** to_dec)\n    print(f\"   Expected output: {out_human:,.2f} {router['toToken']['tokenSymbol']}\")\n    print(f\"   Price impact: {router.get('priceImpactPercent', 'N\u002FA')}%\")\n    print(f\"   Min receive: {int(swap['tx']['minReceiveAmount']) \u002F (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:\u002F\u002Fetherscan.io\u002Ftx\u002F{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:\u002F\u002Fweb3.okx.com\";\nconst CHAIN_INDEX = \"1\";\nconst CHAIN_ID = 1;\n\nconst provider = new ethers.JsonRpcProvider(\"https:\u002F\u002Feth.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\u002Fjson\",\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 = `\u002Fapi\u002Fv6\u002Fdex\u002Faggregator\u002Fswap?${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 = \"\u002Fapi\u002Fv6\u002Fdex\u002Fpre-transaction\u002Fbroadcast-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(); \u002F\u002F 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\u002FA |\n| Unichain | 130 | 130 |\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 | `\u002Fapi\u002Fv6\u002Fdex\u002Faggregator\u002Fswap` | GET | Get transaction calldata for the swap |\n| Broadcast | `\u002Fapi\u002Fv6\u002Fdex\u002Fpre-transaction\u002Fbroadcast-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\u002Freferral 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` \u002F `solana-py` (for Solana)\n- **Node.js**: `axios`, `ethers` (for EVM signing), `@solana\u002Fweb3.js` (for Solana)\n\n## Workflow\n\n### Step 1: Call the Swap API\n\n**Endpoint:**\n```\nGET https:\u002F\u002Fweb3.okx.com\u002Fapi\u002Fv6\u002Fdex\u002Faggregator\u002Fswap\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 \u003C100 |\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) \u002F 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\u002FBNB), 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 \u002F 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 \u002F 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\u002Fweb3.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:\u002F\u002Fweb3.okx.com\u002Fapi\u002Fv6\u002Fdex\u002Fpre-transaction\u002Fbroadcast-transaction\n```\n\n**IMPORTANT**: This is a POST request with a JSON body (unlike the GET-based swap\u002Fquote 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 \u002F 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\u002FUSDT): `0.1%` - `0.5%`\n- **Major pairs** (ETH\u002FUSDC): `0.5%` - `1%`\n- **Volatile\u002Flow-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\u002FReferral 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:\u002F\u002Fweb3.okx.com\"\nCHAIN_INDEX = \"1\"  # Ethereum\nCHAIN_ID = 1\nRPC_URL = \"https:\u002F\u002Feth.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\u002Fjson\",\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\"\u002Fapi\u002Fv6\u002Fdex\u002Faggregator\u002Fswap?{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 = \"\u002Fapi\u002Fv6\u002Fdex\u002Fpre-transaction\u002Fbroadcast-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\"]) \u002F (10 ** to_dec)\n    print(f\"   Expected output: {out_human:,.2f} {router['toToken']['tokenSymbol']}\")\n    print(f\"   Price impact: {router.get('priceImpactPercent', 'N\u002FA')}%\")\n    print(f\"   Min receive: {int(swap['tx']['minReceiveAmount']) \u002F (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:\u002F\u002Fetherscan.io\u002Ftx\u002F{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:\u002F\u002Fweb3.okx.com\";\nconst CHAIN_INDEX = \"1\";\nconst CHAIN_ID = 1;\n\nconst provider = new ethers.JsonRpcProvider(\"https:\u002F\u002Feth.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\u002Fjson\",\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 = `\u002Fapi\u002Fv6\u002Fdex\u002Faggregator\u002Fswap?${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 = \"\u002Fapi\u002Fv6\u002Fdex\u002Fpre-transaction\u002Fbroadcast-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(); \u002F\u002F 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\u002FA |\n| Unichain | 130 | 130 |\n",{"name":5,"tags":24,"author":35,"license":15,"version":36,"description":37,"allowed_tools":38,"required_context":43},[25,26,27,28,29,30,31,32,33,34],"defi","dex","okx","swap","broadcast","web3","onchain","evm","solana","mev-protection","Claude Assistant","1.0.0","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: \u002Fswap endpoint (get tx data) + \u002Fbroadcast-transaction endpoint (submit signed tx). For quote-only (no execution), use the okx-dex-quote skill instead.\n",[39,40,41,42],"bash_tool","create_file","str_replace","view",[44,45,46,47,48],"api_key","secret_key","passphrase","user_wallet_address","private_key_or_signer","master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fe\u002Feasy-swap",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":59,"prompt":69,"zipAvailable":70},[60,63,66],{"tool":61,"command":62},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill okx-dex-swap",{"tool":64,"command":65},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill okx-dex-swap",{"tool":67,"command":68},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill okx-dex-swap","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fe\u002Feasy-swap\u002FSKILL.md",true,[],[73,80,87,94,101,108],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]