Agent skill

Okx Dex Swap

by LeoYeAI in LeoYeAI/openclaw-master-skills

Execute token swaps on-chain via OKX DEX Aggregator API (v6).

MITAuto-check passedBackend & APIs

Install Okx Dex Swap

skills CLI
$ npx skills add LeoYeAI/openclaw-master-skills --skill okx-dex-swap -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install LeoYeAI/openclaw-master-skills okx-dex-swap --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/LeoYeAI/openclaw-master-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/easy-swap .claude/skills/okx-dex-swap && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
okx-dex-swap
GitHub stars
2.2k
Token cost
~6.2k tokens
SKILL.md length
1,460 words
Files
3 (incl. scripts)
Skills in repo
1,235
Repo updated
First seen
Licence
MIT

At a glance

Execute token swaps on-chain via OKX DEX Aggregator API (v6).

  • Works in 5 steps: Call the Swap API → Handle Token Approval (EVM Only) → Sign the Transaction → …
  • A user wants to: 1
  • SKILL.md covers Overview, Prerequisites, Workflow and Best Practices, plus 5 more sections
  • Runs Python scripts from its folder; reaches web3.okx.com and eth.llamarpc.com; needs PRIVATE_KEY and OKX_ACCESS_KEY

What it does

Okx Dex Swap is an agent skill from LeoYeAI/openclaw-master-skills. 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…

Its SKILL.md is about 6.2k tokens, which your agent loads only when the skill is triggered. The skill folder holds 3 other files, including scripts (for example `_meta.json` and `scripts/easy_swap.py`).

It sits in Backend & APIs, covering Smart contracts. It works with OKX and Solana. The repository describes itself as: 🧠 Curated collection of 1209+ best OpenClaw skills — weekly updated by MyClaw.ai. The licence is MIT.

When your agent uses it

  • A user wants to: 1
  • Tasks that involve Smart contracts

Example prompts

  • “/okx-dex-swap”

Requirements

  • Python 3
  • Node.js
  • A credential in OKX_ACCESS_KEY
  • A credential in OKX_SECRET_KEY

Workflow steps

5 steps, taken from the step headings in SKILL.md.

  1. Call the Swap API
  2. Handle Token Approval (EVM Only)
  3. Sign the Transaction
  4. Broadcast the Signed Transaction
  5. Verify Transaction

What it can do on your machine

Read from SKILL.md and the folder at commit e5199b5. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Ships 1 file in scripts/ (Python), which the agent can run.

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Hosts in commands or code, which the agent is likely to contact:

    • web3.okx.com
    • eth.llamarpc.com
    • etherscan.io

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • PRIVATE_KEY
    • OKX_ACCESS_KEY
    • OKX_SECRET_KEY
    • API_KEY
    • SECRET_KEY
    • WALLET_PRIVATE_KEY

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Okx Dex Swap loads about 6.2k tokens when it runs. Until then it costs about 141 tokens; SKILL.md has 1,460 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~141
When it runs · the whole SKILL.md, loaded when a task matches
~6.2k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); the scripts in this folder are not scanned.

SKILL.md

The full file from LeoYeAI/openclaw-master-skills at commit e5199b5, republished under its MIT licence (© LeoYeAI). 1,460 words, ~6,195 tokens.

Download SKILL.mdSave it as .claude/skills/okx-dex-swap/SKILL.md (or your agent's skills folder). This skill also uses 2 other files; get the full folder from GitHub.
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 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.
version
1.0.0
required_context
api_key, secret_key, passphrase, user_wallet_address, private_key_or_signer
license
MIT
author
Claude Assistant
tags
defi, dex, okx, swap, broadcast, web3, onchain, evm, solana, mev-protection

OKX DEX Swap & Broadcast Skill

Overview

This skill generates production-ready code for the complete on-chain swap flow using the OKX DEX Aggregator:

┌─────────┐     ┌──────────┐     ┌──────────┐     ┌───────────┐
│  Quote   │ ──▶ │   Swap   │ ──▶ │   Sign   │ ──▶ │ Broadcast │
│ (optional│     │ API Call │     │   Tx     │     │  to Chain │
│  preview)│     │          │     │          │     │           │
└─────────┘     └──────────┘     └──────────┘     └───────────┘

Two API endpoints involved:

StepEndpointMethodPurpose
Swap/api/v6/dex/aggregator/swapGETGet transaction calldata for the swap
Broadcast/api/v6/dex/pre-transaction/broadcast-transactionPOSTSubmit signed transaction to the chain

Key features:

  • Full swap lifecycle with transaction signing
  • Auto-slippage calculation based on market conditions
  • MEV (sandwich attack) protection on ETH, BSC, SOL, BASE
  • Jito tips for Solana priority transactions
  • Token approval handling (ERC-20 approve)
  • Commission/referral fee splitting
  • Price impact protection with configurable thresholds

Prerequisites

Required Credentials
  • OKX_ACCESS_KEY — API key
  • OKX_SECRET_KEY — Secret key for HMAC signing
  • OKX_PASSPHRASE — Account passphrase
Wallet Requirements
  • EVM chains: Private key or a signer (e.g., web3.py Account, ethers.js Wallet)
  • Solana: Keypair for transaction signing
  • The wallet must have sufficient balance of the fromToken and native token for gas
Environment
  • Python: requests, web3 (for EVM signing), solders / solana-py (for Solana)
  • Node.js: axios, ethers (for EVM signing), @solana/web3.js (for Solana)

Workflow

Step 1: Call the Swap API

Endpoint:

GET https://web3.okx.com/api/v6/dex/aggregator/swap

Required parameters:

ParameterTypeRequiredDescription
chainIndexStringYesChain ID (e.g., 1 = Ethereum, 501 = Solana)
amountStringYesAmount in raw units with decimals (e.g., 1000000 for 1 USDT)
swapModeStringYesexactIn (default) or exactOut
fromTokenAddressStringYesSell token contract address
toTokenAddressStringYesBuy token contract address
slippagePercentStringYesSlippage tolerance (e.g., 0.5 = 0.5%). EVM: 0-100, Solana: 0 to <100
userWalletAddressStringYesUser's wallet address that will sign and send the tx

Important optional parameters:

ParameterTypeDescription
approveTransactionBooleanSet true to get ERC-20 approval calldata in response
approveAmountStringCustom approval amount (raw units). If omitted, approves exact swap amount
swapReceiverAddressStringRecipient address if different from sender
feePercentStringCommission fee %. Max 3% (EVM) / 10% (Solana)
fromTokenReferrerWalletAddressStringWallet to receive fromToken commission
toTokenReferrerWalletAddressStringWallet to receive toToken commission
autoSlippageBooleanAuto-calculate optimal slippage (overrides slippagePercent)
maxAutoslippagePercentStringCap for auto-slippage
priceImpactProtectionPercentStringMax price impact allowed (0-100, default 90)
gasLevelStringslow, average (default), or fast
gaslimitStringCustom gas limit in wei (EVM only)
dexIdsStringRestrict to specific DEX IDs (comma-separated)
excludeDexIdsStringExclude specific DEX IDs (comma-separated)
directRouteBooleanSingle-pool routing only (Solana only)
disableRFQStringDisable time-sensitive RFQ liquidity sources
callDataMemoStringCustom 64-byte hex data to include on-chain

Solana-specific parameters:

ParameterTypeDescription
computeUnitPriceStringPriority fee (like gasPrice on EVM)
computeUnitLimitStringCompute budget (like gasLimit on EVM)
tipsStringJito tips in SOL (min 0.0000000001, max 2). Set computeUnitPrice=0 when using tips

Swap API response structure:

json
{
  "code": "0",
  "data": [{
    "routerResult": {
      "chainIndex": "1",
      "fromToken": { "tokenSymbol": "USDC", "decimal": "6", ... },
      "toToken": { "tokenSymbol": "WBTC", "decimal": "8", ... },
      "fromTokenAmount": "100000000000",
      "toTokenAmount": "90281915",
      "tradeFee": "1.35",
      "estimateGasFee": "1248837",
      "priceImpactPercent": "0.07",
      "dexRouterList": [...]
    },
    "tx": {
      "from": "0x77660f...",
      "to": "0x5E1f62...",
      "value": "0",
      "data": "0xf2c42696...",
      "gas": "1248837",
      "gasPrice": "557703374",
      "maxPriorityFeePerGas": "500000000",
      "minReceiveAmount": "90191633",
      "slippagePercent": "0.1",
      "signatureData": [...]
    }
  }],
  "msg": ""
}

Key fields in tx object:

FieldDescription
fromSender wallet address
toOKX DEX router contract address
dataTransaction calldata (the swap instruction)
valueNative token amount to send (in wei). "0" for ERC-20 swaps
gasEstimated gas limit (already padded +50%)
gasPriceGas price in wei
maxPriorityFeePerGasEIP-1559 priority fee
minReceiveAmountMinimum output at max slippage
signatureDataApproval calldata (if approveTransaction=true) or Jito tips calldata
Step 2: Handle Token Approval (EVM Only)

For ERC-20 tokens (not native ETH/BNB), you need to approve the DEX router to spend your tokens BEFORE the swap.

When approveTransaction=true in the request: The response tx.signatureData contains the approval info:

json
{
  "approveContract": "0x40aA958dd87FC8305b97f2BA922CDdCa374bcD7f",
  "approveTxCalldata": "0x095ea7b3..."
}

Approval flow:

  1. Parse signatureData to get approveContract and approveTxCalldata
  2. Send an approval transaction: to=approveContract, data=approveTxCalldata
  3. Wait for approval tx to be confirmed
  4. Then send the swap transaction

IMPORTANT: For native tokens (ETH, BNB, etc. using 0xeeee...eeee), no approval is needed.

Step 3: Sign the Transaction

EVM chains (Python / web3.py):

python
tx_params = {
    "from": tx_data["from"],
    "to": tx_data["to"],
    "value": int(tx_data["value"]),
    "data": tx_data["data"],
    "gas": int(tx_data["gas"]),
    "gasPrice": int(tx_data["gasPrice"]),
    "nonce": w3.eth.get_transaction_count(wallet_address),
    "chainId": chain_id,
}
signed = w3.eth.account.sign_transaction(tx_params, private_key)
signed_tx_hex = signed.raw_transaction.hex()

EVM chains (Node.js / ethers.js):

javascript
const tx = {
  from: txData.from,
  to: txData.to,
  value: txData.value,
  data: txData.data,
  gasLimit: txData.gas,
  gasPrice: txData.gasPrice,
  nonce: await provider.getTransactionCount(walletAddress),
  chainId: chainId,
};
const signedTx = await wallet.signTransaction(tx);

Solana: Use solders or @solana/web3.js to deserialize, sign, and serialize the transaction from tx.data.

Step 4: Broadcast the Signed Transaction

Endpoint:

POST https://web3.okx.com/api/v6/dex/pre-transaction/broadcast-transaction

IMPORTANT: This is a POST request with a JSON body (unlike the GET-based swap/quote endpoints).

Request body:

ParameterTypeRequiredDescription
signedTxStringYesThe hex-encoded signed transaction string
chainIndexStringYesChain ID (e.g., "1" for Ethereum)
addressStringYesSender wallet address
extraDataStringNoJSON string with extra options (see below)

extraData options (JSON string):

FieldTypeDescription
enableMevProtectionBooleanEnable MEV (sandwich) protection. Supported: ETH, BSC, SOL, BASE
jitoSignedTxStringBase58-encoded signed Jito transaction (Solana only). Required when tips > 0

Signing algorithm for POST requests:

prehash = timestamp + "POST" + request_path + json_body
signature = Base64(HMAC-SHA256(secret_key, prehash))

Note: For POST, the request_path has NO query string. The JSON body is appended directly to the prehash string.

Broadcast response:

json
{
  "code": "0",
  "data": [{
    "orderId": "0e1d79837afce1e149b6ab54b6e2edce8130c3f8",
    "txHash": "0xd394f356a16b618ed839c66c935c9cccc5dde0af832ff9b468677eea38759db5"
  }],
  "msg": ""
}
FieldDescription
orderIdOKX internal order tracking ID
txHashOn-chain transaction hash. Use this to check status on block explorer
Step 5: Verify Transaction

After broadcasting, verify the transaction was confirmed:

  • EVM: Check txHash on Etherscan / block explorer, or use web3.eth.wait_for_transaction_receipt()
  • Solana: Check on Solscan, or use connection.confirmTransaction()

Best Practices

Security
  • NEVER hardcode private keys in code. Use environment variables, keystore files, or hardware wallets.
  • NEVER log private keys, signed transactions, or secret keys in production.
  • Always validate token addresses and amounts before sending.
  • Check isHoneyPot on both tokens before proceeding.
  • Use priceImpactProtectionPercent (recommend setting to 10 or lower for safety).
Slippage Configuration
  • Stable pairs (USDC/USDT): 0.1% - 0.5%
  • Major pairs (ETH/USDC): 0.5% - 1%
  • Volatile/low-liquidity tokens: 1% - 5%
  • Meme coins: 5% - 15% (or higher, but be cautious)
  • Use autoSlippage=true with maxAutoslippagePercent for optimal auto-calculation.
MEV Protection
  • Enable enableMevProtection: true for large trades on ETH, BSC, SOL, BASE.
  • On Solana, combine with Jito tips for priority + MEV protection.
  • When using Jito tips, set computeUnitPrice=0 to avoid wasting fees.
Show full SKILL.md (580 more words)Show less
Token Approval Strategy
  • For one-time swaps: approve exact amount (approveAmount = swap amount).
  • For repeated swaps: consider a larger approval (e.g., max uint256) to save gas on future swaps, but understand the security trade-off.
  • Always check existing allowance before sending a new approval.
Uni V3 Liquidity Edge Case

When 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.

Amount Handling
  • Always use strings for amounts to avoid floating-point precision loss.
  • Python: int() for calculations, never float().
  • JavaScript: BigInt or ethers.parseUnits() for amounts.
  • Formula: raw_amount = human_amount * 10^decimals
Error Handling
  • Check response["code"] == "0" before processing.
  • If broadcast fails, do NOT automatically retry without checking nonce — you may double-spend.
  • Common errors:
    • 401 = Signature mismatch (check POST signing includes body)
    • 429 = Rate limited
    • Swap returns error = insufficient balance, invalid params, or liquidity issue
    • Broadcast returns error = already executed, nonce too low, insufficient gas
Commission/Referral Fees
  • Only ONE of fromTokenReferrerWalletAddress or toTokenReferrerWalletAddress per tx.
  • Solana: referrer wallet must have SOL deposited for activation.
  • TON: limited DEX support (Stonfi V2, Dedust).
  • BSC: no commission through Four.meme swaps.

Examples

Example 1: Python — Complete EVM Swap Flow
python
import os, hmac, hashlib, base64, json, requests
from datetime import datetime, timezone
from urllib.parse import urlencode
from web3 import Web3

# === Configuration ===
API_KEY = os.environ["OKX_ACCESS_KEY"]
SECRET_KEY = os.environ["OKX_SECRET_KEY"]
PASSPHRASE = os.environ["OKX_PASSPHRASE"]
PRIVATE_KEY = os.environ["WALLET_PRIVATE_KEY"]

BASE_URL = "https://web3.okx.com"
CHAIN_INDEX = "1"  # Ethereum
CHAIN_ID = 1
RPC_URL = "https://eth.llamarpc.com"

w3 = Web3(Web3.HTTPProvider(RPC_URL))
account = w3.eth.account.from_key(PRIVATE_KEY)
WALLET = account.address


def _sign_request(timestamp, method, request_path, body=""):
    prehash = timestamp + method + request_path + body
    mac = hmac.new(SECRET_KEY.encode(), prehash.encode(), hashlib.sha256)
    return base64.b64encode(mac.digest()).decode()


def _headers(method, request_path, body=""):
    timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
    sig = _sign_request(timestamp, method, request_path, body)
    return {
        "OK-ACCESS-KEY": API_KEY,
        "OK-ACCESS-SIGN": sig,
        "OK-ACCESS-PASSPHRASE": PASSPHRASE,
        "OK-ACCESS-TIMESTAMP": timestamp,
        "Content-Type": "application/json",
    }


# --- Step 1: Get swap calldata ---
def get_swap_data(from_token, to_token, amount, slippage="0.5"):
    params = {
        "chainIndex": CHAIN_INDEX,
        "fromTokenAddress": from_token,
        "toTokenAddress": to_token,
        "amount": amount,
        "swapMode": "exactIn",
        "slippagePercent": slippage,
        "userWalletAddress": WALLET,
        "approveTransaction": "true",
    }
    query = urlencode(params)
    path = f"/api/v6/dex/aggregator/swap?{query}"
    headers = _headers("GET", path)

    resp = requests.get(BASE_URL + path, headers=headers, timeout=30)
    resp.raise_for_status()
    data = resp.json()

    if data["code"] != "0":
        raise Exception(f"Swap API error: {data['msg']}")
    return data["data"][0]


# --- Step 2: Handle approval (if needed) ---
def send_approval_if_needed(swap_result):
    sig_data = swap_result["tx"].get("signatureData", [])
    if not sig_data:
        return None

    for item in sig_data:
        parsed = json.loads(item) if isinstance(item, str) else item
        if "approveContract" in parsed:
            approve_tx = {
                "from": WALLET,
                "to": Web3.to_checksum_address(parsed["approveContract"]),
                "data": parsed["approveTxCalldata"],
                "gas": 60000,
                "gasPrice": w3.eth.gas_price,
                "nonce": w3.eth.get_transaction_count(WALLET),
                "chainId": CHAIN_ID,
            }
            signed = w3.eth.account.sign_transaction(approve_tx, PRIVATE_KEY)
            tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)
            receipt = w3.eth.wait_for_transaction_receipt(tx_hash, timeout=120)
            print(f"Approval confirmed: {tx_hash.hex()}")
            return receipt
    return None


# --- Step 3: Sign the swap transaction ---
def sign_swap_tx(swap_result):
    tx_data = swap_result["tx"]
    tx_params = {
        "from": Web3.to_checksum_address(tx_data["from"]),
        "to": Web3.to_checksum_address(tx_data["to"]),
        "value": int(tx_data["value"]),
        "data": tx_data["data"],
        "gas": int(tx_data["gas"]),
        "gasPrice": int(tx_data["gasPrice"]),
        "nonce": w3.eth.get_transaction_count(WALLET),
        "chainId": CHAIN_ID,
    }
    signed = w3.eth.account.sign_transaction(tx_params, PRIVATE_KEY)
    return signed.raw_transaction.hex()


# --- Step 4: Broadcast via OKX ---
def broadcast_tx(signed_tx_hex, enable_mev=True):
    path = "/api/v6/dex/pre-transaction/broadcast-transaction"
    body_dict = {
        "chainIndex": CHAIN_INDEX,
        "address": WALLET,
        "signedTx": signed_tx_hex,
    }
    if enable_mev:
        body_dict["extraData"] = json.dumps({"enableMevProtection": True})

    body_str = json.dumps(body_dict)
    headers = _headers("POST", path, body_str)

    resp = requests.post(BASE_URL + path, headers=headers, data=body_str, timeout=30)
    resp.raise_for_status()
    data = resp.json()

    if data["code"] != "0":
        raise Exception(f"Broadcast error: {data['msg']}")
    return data["data"][0]


# === Execute full swap ===
if __name__ == "__main__":
    ETH = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
    USDC = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
    amount = str(10 ** 17)  # 0.1 ETH

    print("1. Getting swap data...")
    swap = get_swap_data(ETH, USDC, amount, slippage="0.5")

    router = swap["routerResult"]
    to_dec = int(router["toToken"]["decimal"])
    out_human = int(router["toTokenAmount"]) / (10 ** to_dec)
    print(f"   Expected output: {out_human:,.2f} {router['toToken']['tokenSymbol']}")
    print(f"   Price impact: {router.get('priceImpactPercent', 'N/A')}%")
    print(f"   Min receive: {int(swap['tx']['minReceiveAmount']) / (10 ** to_dec):,.2f}")

    # Honeypot check
    if router["toToken"].get("isHoneyPot"):
        print("   HONEYPOT DETECTED — aborting!")
        exit(1)

    print("2. Handling approval...")
    send_approval_if_needed(swap)

    print("3. Signing swap transaction...")
    signed_hex = sign_swap_tx(swap)

    print("4. Broadcasting with MEV protection...")
    result = broadcast_tx(signed_hex, enable_mev=True)
    print(f"   Order ID: {result['orderId']}")
    print(f"   Tx Hash: {result['txHash']}")
    print(f"   View: https://etherscan.io/tx/{result['txHash']}")
Example 2: Node.js — Complete EVM Swap Flow
javascript
const crypto = require("crypto");
const https = require("https");
const { ethers } = require("ethers");

const API_KEY = process.env.OKX_ACCESS_KEY;
const SECRET_KEY = process.env.OKX_SECRET_KEY;
const PASSPHRASE = process.env.OKX_PASSPHRASE;
const PRIVATE_KEY = process.env.WALLET_PRIVATE_KEY;

const BASE_URL = "https://web3.okx.com";
const CHAIN_INDEX = "1";
const CHAIN_ID = 1;

const provider = new ethers.JsonRpcProvider("https://eth.llamarpc.com");
const wallet = new ethers.Wallet(PRIVATE_KEY, provider);

function sign(timestamp, method, path, body = "") {
  return crypto
    .createHmac("sha256", SECRET_KEY)
    .update(timestamp + method + path + body)
    .digest("base64");
}

function headers(method, path, body = "") {
  const ts = new Date().toISOString();
  return {
    "OK-ACCESS-KEY": API_KEY,
    "OK-ACCESS-SIGN": sign(ts, method, path, body),
    "OK-ACCESS-PASSPHRASE": PASSPHRASE,
    "OK-ACCESS-TIMESTAMP": ts,
    "Content-Type": "application/json",
  };
}

async function getSwapData(fromToken, toToken, amount, slippage = "0.5") {
  const params = new URLSearchParams({
    chainIndex: CHAIN_INDEX,
    fromTokenAddress: fromToken,
    toTokenAddress: toToken,
    amount,
    swapMode: "exactIn",
    slippagePercent: slippage,
    userWalletAddress: wallet.address,
    approveTransaction: "true",
  });
  const path = `/api/v6/dex/aggregator/swap?${params}`;
  const h = headers("GET", path);

  const resp = await fetch(`${BASE_URL}${path}`, { headers: h });
  const data = await resp.json();
  if (data.code !== "0") throw new Error(`Swap error: ${data.msg}`);
  return data.data[0];
}

async function broadcastTx(signedTx, enableMev = true) {
  const path = "/api/v6/dex/pre-transaction/broadcast-transaction";
  const bodyObj = {
    chainIndex: CHAIN_INDEX,
    address: wallet.address,
    signedTx,
    ...(enableMev && {
      extraData: JSON.stringify({ enableMevProtection: true }),
    }),
  };
  const bodyStr = JSON.stringify(bodyObj);
  const h = headers("POST", path, bodyStr);

  const resp = await fetch(`${BASE_URL}${path}`, {
    method: "POST",
    headers: h,
    body: bodyStr,
  });
  const data = await resp.json();
  if (data.code !== "0") throw new Error(`Broadcast error: ${data.msg}`);
  return data.data[0];
}

async function main() {
  const ETH = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
  const USDC = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48";
  const amount = (10n ** 17n).toString(); // 0.1 ETH

  console.log("1. Getting swap data...");
  const swap = await getSwapData(ETH, USDC, amount);

  const txData = swap.tx;
  console.log(`   Min receive: ${txData.minReceiveAmount}`);

  console.log("2. Signing transaction...");
  const tx = {
    from: txData.from,
    to: txData.to,
    value: txData.value,
    data: txData.data,
    gasLimit: txData.gas,
    gasPrice: txData.gasPrice,
    nonce: await provider.getTransactionCount(wallet.address),
    chainId: CHAIN_ID,
  };
  const signedTx = await wallet.signTransaction(tx);

  console.log("3. Broadcasting with MEV protection...");
  const result = await broadcastTx(signedTx);
  console.log(`   Tx Hash: ${result.txHash}`);
}

main().catch(console.error);
Example 3: Solana Swap with Jito Tips

When using Jito tips on Solana:

  1. Set tips parameter (e.g., "0.001" SOL) in the swap request
  2. Set computeUnitPrice=0 (avoid double-paying for priority)
  3. The signatureData in response contains the Jito tips calldata
  4. Sign BOTH the main transaction AND the Jito transaction
  5. Broadcast with both signedTx and jitoSignedTx in extraData
python
# Solana-specific broadcast with Jito
body = {
    "chainIndex": "501",
    "address": solana_wallet_pubkey,
    "signedTx": base58_signed_main_tx,
    "extraData": json.dumps({
        "enableMevProtection": True,
        "jitoSignedTx": base58_signed_jito_tx
    })
}

IMPORTANT: For Solana, signedTx and jitoSignedTx must BOTH be provided when using tips.

Troubleshooting

ProblemCauseSolution
401 Unauthorized on broadcastPOST signing errorEnsure prehash = timestamp + "POST" + path + jsonBody. The body must be the exact JSON string.
401 Unauthorized on swapGET signing errorEnsure prehash = timestamp + "GET" + path_with_query_string.
Approval tx failsInsufficient ETH for gasEnsure wallet has native token for gas fees.
Swap tx revertsSlippage exceededIncrease slippagePercent or use autoSlippage=true.
minReceiveAmount is 0Extreme slippage or bad paramsCheck token addresses and amounts. Reduce trade size.
Broadcast returns no txHashMEV protection routing delayWait and check orderId status. MEV-protected txs may take longer.
"Nonce too low" on broadcastTx already sent or nonce reusedFetch fresh nonce before signing. Never reuse nonces.
Solana broadcast failsMissing jitoSignedTxWhen tips > 0, you must provide both signedTx and jitoSignedTx.
Token refund not receivedUni V3 liquidity drainedEnsure your contract supports receiving token refunds from the router.
Commission not working on BSCFour.meme restrictionCommission is not supported for swaps through Four.meme on BSC.
priceImpactPercent very negativeLow liquidityReduce amount or split into multiple smaller swaps.

Reference: POST vs GET Signing

The OKX API uses different signing for GET and POST:

MethodPrehash Format
GETtimestamp + "GET" + path_with_query
POSTtimestamp + "POST" + path + json_body

The Swap endpoint is GET, the Broadcast endpoint is POST. Getting this wrong is the #1 cause of 401 errors.

Reference: MEV Protection Support

ChainenableMevProtectionJito Tips
EthereumYesNo
BSCYesNo
SolanaYesYes
BaseYesNo
OthersNot yetNot yet

Reference: Common Chain IDs

ChainchainIndexChain ID (for tx signing)
Ethereum11
BSC5656
Polygon137137
Arbitrum4216142161
Optimism1010
Base84538453
Avalanche4311443114
Solana501N/A
Unichain130130

© LeoYeAI, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 2 other files (scripts) in skills/easy-swap of LeoYeAI/openclaw-master-skills.

  • SKILL.md
  • _meta.json
  • scripts/easy_swap.py

Open the folder on GitHubat commit e5199b5

Compare with similar skills

Okx Dex Swap next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Okx Dex Swap compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Okx Dex Swap this skillLeoYeAI/openclaw-master-skills2.2k—~6.2kAutomated safety check: PassMIT
Agent Payment X402affaan-m/ECC276k—~6.8kAutomated safety check: PassMIT
Agent Payment X402affaan-m/ECC276k—~4.9kAutomated safety check: PassMIT
Agent Payment X402affaan-m/ECC276k—~5.4kAutomated safety check: PassMIT
Okx Dex Trenchesnirholas/three.ws229—~2.6kAutomated safety check: PassMIT
Solana Devsolana-foundation/solana-dev-skill573—~3.8kAutomated safety check: PassMIT

Similar skills

  • Agent Payment X402

    affaan-m/ECC

    Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets.

    276k GitHub stars~6.8k tokensUpdated yesterday
    Backend & APIsAuto-check passed
  • Agent Payment X402

    affaan-m/ECC

    将 x402 支付执行添加到 AI 代理中,具备每任务预算、支出控制和非托管钱包。通过 agentwallet-sdk 支持 Base,通过 OKX Payments / OKX 代理支付协议支持 X Layer,并通过上游 x402 包与基于结算器的结算支持 Solana 及多网络 EVM。

    276k GitHub stars~4.9k tokensUpdated yesterday
    Backend & APIsAuto-check passed
  • Agent Payment X402

    affaan-m/ECC

    タスクごとのバジェット、支出コントロール、ノンカストディアルウォレットを備えた x402 決済実行を AI エージェントに追加します。agentwallet-sdk を通じて Base を、OKX Payments / OKX エージェント決済プロトコルを通じて X Layer を、アップストリームの x402 パッケージとファシリテーターベースの決済を通じて Solana…

    276k GitHub stars~5.4k tokensUpdated yesterday
    Backend & APIsAuto-check passed
  • Okx Dex Trenches

    nirholas/three.ws

    Read-only on-chain research for pump.fun and other meme-token launchpads (Solana / BSC / X Layer / TRON).

    229 GitHub stars~2.6k tokensUpdated yesterday
    Backend & APIsAuto-check passed
  • Solana Dev

    solana-foundation/solana-dev-skill

    A skill your agent uses when user asks to "build a Solana dapp", "write an Anchor program", "create a token", "debug Solana errors", "set up wallet connection", "test my Solana program", "fuzz my…

    573 GitHub stars~3.8k tokensUpdated 2 days ago
    Backend & APIsAuto-check passed
  • Radar

    Auditware/radar

    Use radar for smart contract security analysis, AST generation, and detection template development.

    154 GitHub stars~2.1k tokensUpdated 1 mo ago
    Backend & APIsAuto-check passed

More from LeoYeAI/openclaw-master-skills

All 1,200 skills in this repo
  • DevOps Pipeline Management

    LeoYeAI/openclaw-master-skills

    Manages pipelines on a DevOps quality and efficiency platform through its OpenAPI: list workspaces and templates, create, update, run and cancel pipelines, and read run records.

    2.2k GitHub stars~4.2k tokensUpdated 2 mo ago
    Auto-check: notes
  • Feishu Document Collaboration

    LeoYeAI/openclaw-master-skills

    Patches OpenClaw's Feishu extension so an edited document triggers an isolated agent session that reads the doc and replies inline, turning it into a live chat space.

    2.2k GitHub stars~2k tokensUpdated 2 mo ago
    Auto-check passed
  • Files Memory System

    LeoYeAI/openclaw-master-skills

    Multi-context memory management system for OpenClaw agents with group-isolated storage, global shared memory, workspace organization, and group-specific skills isolation.

    2.2k GitHub stars~3.8k tokensUpdated 2 mo ago
    Auto-check passed
  • GEO-Claw AI Visibility Agent

    LeoYeAI/openclaw-master-skills

    Runs a brand's AI-search visibility work end to end: diagnosing how AI platforms represent it, repositioning it, producing AI-optimized content and monitoring ongoing mentions.

    2.2k GitHub stars~4.7k tokensUpdated 2 mo ago
    Auto-check passed
  • Google Workspace CLI

    LeoYeAI/openclaw-master-skills

    Installs and authenticates the gws CLI, then automates Gmail, Drive, Sheets, Calendar, Docs, Chat and Tasks with ready-made recipes, persona bundles and security audits.

    2.2k GitHub stars~2.6k tokensUpdated 2 mo ago
    Auto-check: notes
  • HealthFit Health Advisors

    LeoYeAI/openclaw-master-skills

    Runs four advisor roles, a fitness coach, nutritionist, data analyst and TCM practitioner, to build a health profile and track workouts, diet and wellness over time.

    2.2k GitHub stars~4.4k tokensUpdated 2 mo ago
    Auto-check passed

Works with

Categories

Questions about Okx Dex Swap

What does Okx Dex Swap do?

Execute token swaps on-chain via OKX DEX Aggregator API (v6). Okx Dex Swap is an agent skill from LeoYeAI/openclaw-master-skills. Execute token swaps on-chain via OKX DEX Aggregator API (v6).

When should I use Okx Dex Swap?

Okx Dex Swap fits situations like: A user wants to: 1; tasks that involve Smart contracts.

How do I install Okx Dex Swap in Claude Code?

Run `npx skills add LeoYeAI/openclaw-master-skills --skill okx-dex-swap -a claude-code`. Or copy the skill folder (skills/easy-swap in LeoYeAI/openclaw-master-skills) into .claude/skills/okx-dex-swap in your project. Claude Code loads it when a task matches its description.

How do I install Okx Dex Swap in Codex?

Run `npx skills add LeoYeAI/openclaw-master-skills --skill okx-dex-swap -a codex`. Or copy the skill folder (skills/easy-swap in LeoYeAI/openclaw-master-skills) into .agents/skills/okx-dex-swap in your project. Codex loads it when a task matches its description.

Can I use Okx Dex Swap in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add LeoYeAI/openclaw-master-skills --skill okx-dex-swap -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/okx-dex-swap, .gemini/skills/okx-dex-swap, .github/skills/okx-dex-swap and .opencode/skills/okx-dex-swap in your project.

What does Okx Dex Swap need to run?

Going by SKILL.md and its folder, Okx Dex Swap needs Python for the scripts in its folder and credentials named PRIVATE_KEY, OKX_ACCESS_KEY, OKX_SECRET_KEY and API_KEY. Our summary lists: Python 3; Node.js; A credential in OKX_ACCESS_KEY; A credential in OKX_SECRET_KEY.

Does Okx Dex Swap access the network?

SKILL.md names 3 domains. In commands or code: web3.okx.com, eth.llamarpc.com and etherscan.io; the agent is likely to contact these when it follows the instructions. This is read from the text; nothing was executed.

Is Okx Dex Swap safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. The check reads SKILL.md only: the scripts in the folder are not scanned, so read them before running anything.

What licence does Okx Dex Swap use?

Okx Dex Swap is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Okx Dex Swap use?

About 6.2k tokens (SKILL.md is roughly 25k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Okx Dex Swap?

Skills that share tags, products or a category with Okx Dex Swap: Agent Payment X402 (affaan-m/ECC, 276k stars), Agent Payment X402 (affaan-m/ECC, 276k stars), Agent Payment X402 (affaan-m/ECC, 276k stars) and Okx Dex Trenches (nirholas/three.ws, 229 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Okx Dex Swap?

LeoYeAI (a GitHub user) maintains it in LeoYeAI/openclaw-master-skills, which has 2,161 GitHub stars. The repository holds 1,235 skills in this directory. The repository was last updated on July 20, 2026.

Source: LeoYeAI/openclaw-master-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.