Skip to main content

Method Signature

async buildCrossChainSwap(params: CrossChainSwapParams): Promise<APIResponse<any>>
Builds a transaction for executing a cross-chain token swap. This method extends the quote parameters with user wallet information and returns a transaction ready to be signed and broadcast.

Parameters

Required Parameters

fromChainIndex
string
required
Source chain index identifier (e.g., “1” for Ethereum, “501” for Solana)
toChainIndex
string
required
Destination chain index identifier
fromChainId
string
required
Source chain ID (e.g., “1” for Ethereum mainnet)
toChainId
string
required
Destination chain ID
fromTokenAddress
string
required
Contract address of the token to swap from
toTokenAddress
string
required
Contract address of the token to swap to
amount
string
required
Amount to swap in the smallest unit (e.g., wei for ETH)
slippagePercent
string
required
Maximum acceptable slippage as a decimal (e.g., “0.005” for 0.5%). Must be between 0.002 (0.2%) and 0.5 (50%)
userWalletAddress
string
required
The wallet address that will execute the swap

Optional Parameters

receiveAddress
string
Address to receive the swapped tokens (defaults to userWalletAddress)
referrerAddress
string
Referrer address for fee sharing
feePercent
string
Referrer fee percentage
sort
string
Sort order for bridge options (e.g., “cost”, “time”)
dexIds
string
Comma-separated list of DEX IDs to include in routing
allowBridge
string
Comma-separated list of bridge IDs to allow
denyBridge
string
Comma-separated list of bridge IDs to exclude
onlyBridge
string
Only use bridge transfers, skip DEX aggregation
priceImpactProtectionPercentage
string
Maximum acceptable price impact percentage
memo
string
Optional memo or note for the transaction

Response

code
string
Response code (“0” indicates success)
msg
string
Response message
data
array
Array containing transaction data
tx
object
Transaction object ready for signing
from
string
Sender address
to
string
Recipient contract address
data
string
Encoded transaction data
value
string
ETH/native token value to send
gas
string
Gas limit
gasPrice
string
Gas price in wei
maxPriorityFeePerGas
string
Maximum priority fee per gas (EIP-1559)
minReceiveAmount
string
Minimum amount of tokens to receive (after slippage)
maxSpendAmount
string
Maximum amount of tokens to spend
routerResult
object
Routing information
fromTokenAmount
string
Amount of source tokens
toTokenAmount
string
Expected amount of destination tokens
estimateGasFee
string
Estimated gas fee

Code Example

import { OKXDexSDK } from '@okxweb3/dex-sdk';
import { ethers } from 'ethers';

const sdk = new OKXDexSDK({
  apiKey: 'your-api-key',
  secretKey: 'your-secret-key',
  apiPassphrase: 'your-passphrase',
  projectId: 'your-project-id'
});

// Build a cross-chain swap transaction
const swapTx = await sdk.bridge.buildCrossChainSwap({
  fromChainIndex: '1',        // Ethereum
  toChainIndex: '42161',      // Arbitrum
  fromChainId: '1',
  toChainId: '42161',
  fromTokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC on Ethereum
  toTokenAddress: '0xFF970a61A04b1cA14834A43f5dE4533eBDDB5CC8',   // USDC on Arbitrum
  amount: '1000000000',       // 1000 USDC (6 decimals)
  slippagePercent: '0.005',   // 0.5% slippage
  userWalletAddress: '0x1234...', // Your wallet address
  receiveAddress: '0x5678...'     // Optional: different receive address
});

const txData = swapTx.data[0].tx;

// Sign and send the transaction using ethers.js
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();

const transaction = {
  from: txData.from,
  to: txData.to,
  data: txData.data,
  value: txData.value,
  gasLimit: txData.gas,
  gasPrice: txData.gasPrice
};

const txResponse = await signer.sendTransaction(transaction);
const receipt = await txResponse.wait();

console.log('Transaction hash:', receipt.transactionHash);

Error Handling

try {
  const swapTx = await sdk.bridge.buildCrossChainSwap(params);
} catch (error) {
  if (error.message.includes('userWalletAddress is required')) {
    console.error('Missing wallet address');
  } else if (error.message.includes('Slippage must be between')) {
    console.error('Invalid slippage value');
  } else {
    console.error('Failed to build swap:', error);
  }
}

Validation Rules

  • userWalletAddress is required and must be a valid address
  • Slippage must be between 0.002 (0.2%) and 0.5 (50%)
  • All chain and token parameters must be valid
  • Amount must be sufficient to cover fees and minimum swap amounts

Build docs developers (and LLMs) love