OKX DEX API Guide: Building a Solana Token Swap Interface

·

Learn how to integrate decentralized exchange (DEX) aggregation into your Solana decentralized application (DApp) using the OKX DEX API. This guide covers Web3.js implementation for seamless token swaps on Solana, including single-chain and cross-chain capabilities.


Core Features


DEX API Utility File Structure

The dexUtils.js utility file includes:

  1. Network configurations for Solana (Chain ID: 501).
  2. Token address constants (e.g., NATIVE_SOL, USDC_SOL).
  3. API call handlers for quotes, swaps, and transaction execution.

Prerequisites


Setup Instructions

Option 1: Local Development

  1. Clone the repository:

    git clone https://github.com/Julian-dev28/okx-os-evm-swap-app.git
    cd okx-os-evm-swap-app
    git checkout solana-cross-chain-swap
  2. Install dependencies:

    npm install
  3. Configure environment variables (.env):

    REACT_APP_API_KEY=your_api_key
    REACT_APP_SECRET_KEY=your_secret_key
    REACT_APP_API_PASSPHRASE=your_passphrase
    REACT_APP_PROJECT_ID=your_project_id

Option 2: Replit Deployment

  1. Fork the Replit project.
  2. Add environment variables under "Secrets" in the Replit dashboard.

Key Code Implementations

1. Fetching Swap Quotes

export async function getSingleChainSwap(params) {
  const headers = getHeaders(timestamp, "GET", "/api/v5/dex/aggregator/swap");
  const response = await fetch(`${apiBaseUrl}/aggregator/swap?${new URLSearchParams(params)}`, { 
    method: "GET", 
    headers 
  });
  return response.json();
}

2. Executing Transactions

export async function executeTransaction(txData) {
  const tx = solanaWeb3.Transaction.from(base58.decode(txData.data));
  const txId = await connection.sendRawTransaction(tx.serialize(), { 
    maxRetries: 5 
  });
  return { 
    txId, 
    explorerUrl: `https://solscan.io/tx/${txId}` 
  };
}

React Component Example

const SolanaSwapTransaction = () => {
  const [amount, setAmount] = useState("1");
  
  const handleSwap = async () => {
    const lamports = new BN(amount * 1e9).toString();
    const swapData = await getSingleChainSwap({
      chainId: "501",
      fromTokenAddress: NATIVE_SOL,
      toTokenAddress: USDC_SOL,
      amount: lamports
    });
    await executeTransaction(swapData);
  };

  return (
    <div>
      <input 
        value={amount} 
        onChange={(e) => setAmount(e.target.value)} 
        placeholder="SOL amount" 
      />
      <button onClick={handleSwap}>Swap</button>
    </div>
  );
};

FAQ

Q1: How do I handle slippage?

A: Set the slippage parameter in getSingleChainSwap() (e.g., "0.5" for 0.5% tolerance).

Q2: What’s the minimum swap amount?

A: The API enforces a minimum of 0.01 SOL (~1e7 lamports).

Q3: Can I swap to non-Solana tokens?

A: Yes! Use the crossChainQuote() function for assets like MATIC on Polygon.


Additional Resources

👉 Start Building with OKX DEX API

Optimize your DApp today with seamless Solana swaps!