Building a Swap Application on the TON Blockchain – Developer Guide

·

The Ton blockchain has rapidly emerged as a high-performance, scalable Layer-1 solution, attracting developers and decentralized applications (dApps) seeking speed, low fees, and seamless user experiences. With the growing ecosystem of JETTONs (Ton’s equivalent of ERC-20 tokens), building decentralized exchange (DEX) integrations has become a key use case for developers.

In this comprehensive guide, you’ll learn how to build a swap application on the TON blockchain using the OKX DEX Aggregator API. We’ll walk through setting up your development environment, fetching real-time price quotes, and executing token swaps—specifically converting native TON to a JETTON token. Whether you're building a wallet, dApp, or trading interface, this tutorial provides actionable code examples and best practices.

Core Keywords


Step 1: Set Up Your Development Environment

Before making any API calls or interacting with the TON network, you need to configure your local development environment. This includes installing required libraries and setting up authentication for secure API access.

Install Required Dependencies

Use npm to install the essential packages for interacting with the TON blockchain:

npm install @ton/ton @ton/crypto @ton/core buffer @orbs-network/ton-access

These libraries enable:

Environment Variables and Initialization

Set up your base configuration, including API endpoints, chain ID, token addresses, and wallet credentials:

const cryptoJS = require('crypto-js');
const { TonClient, WalletContractV4, internal } = require("@ton/ton");
const { toNano, Cell } = require("@ton/core");
const { mnemonicToPrivateKey } = require("@ton/crypto");
const { getHttpEndpoint } = require("@orbs-network/ton-access");

// Base API URL for OKX DEX Aggregator
const apiBaseUrl = 'https://web3.okx.com/api/v5/dex/aggregator';
const chainId = '607'; // TON mainnet chain ID

// Token contract addresses
const fromTokenAddress = 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c'; // Native TON
const toTokenAddress = 'EQAQXlWJvGbbFfE8F3oS8s87lIgdovS455IsWFaRdmJetTon'; // Example JETTON

// User wallet info
const userWalletAddress = 'UQDoI2kiSNQZxxxxxxxxxxxx6lM2ZSxKkEw3k1';
const privateKey = 'xxxxx'; // Keep this secure!
const fromAmount = '1000000'; // Amount in minimal units (e.g., nano-TON)

// OKX API credentials
const apiKey = 'xxxxx';
const secretKey = 'xxxxx';
const passphrase = 'xxxxxxx';

// Timestamp for request signing
const date = new Date();

// Utility function to build API URLs
function getAggregatorRequestUrl(methodName, queryParams) {
  return apiBaseUrl + methodName + '?' + new URLSearchParams(queryParams).toString();
}

👉 Discover how to securely authenticate your Web3 API requests with HMAC signatures.


Step 2: Request Price Quote from DEX Aggregator API

To ensure users receive accurate swap rates, the first step is to fetch a price quote using the /quote endpoint.

Define Quote Parameters

Specify the tokens involved and the amount to swap:

const quoteParams = {
  amount: fromAmount,
  chainId: chainId,
  fromTokenAddress: fromTokenAddress,
  toTokenAddress: toTokenAddress,
};

This request returns:

Fetch Quote Using Helper Function

Create an asynchronous function to call the API:

const getQuote = async () => {
  const apiRequestUrl = getAggregatorRequestUrl('/quote', quoteParams);

  const headers = {
    'Content-Type': 'application/json',
    'OK-ACCESS-KEY': apiKey,
    'OK-ACCESS-SIGN': cryptoJS.enc.Base64.stringify(
      cryptoJS.HmacSHA256(
        date.toISOString() + 'GET' + '/api/v5/dex/aggregator/quote?' + new URLSearchParams(quoteParams).toString(),
        secretKey
      )
    ),
    'OK-ACCESS-TIMESTAMP': date.toISOString(),
    'OK-ACCESS-PASSPHRASE': passphrase,
  };

  try {
    const response = await fetch(apiRequestUrl, { method: 'GET', headers });
    const result = await response.json();
    console.log('Quote Response:', result);
    return result;
  } catch (error) {
    console.error('Error fetching quote:', error);
  }
};
Note: Always validate the minReceiveAmount field in the response to set appropriate slippage tolerance.

Step 3: Execute the Swap Transaction

Once you have a valid quote, proceed to generate and broadcast the transaction.

Define Swap Parameters

Include slippage tolerance and user wallet address:

const swapParams = {
  chainId: chainId,
  fromTokenAddress: fromTokenAddress,
  toTokenAddress: toTokenAddress,
  amount: fromAmount,
  slippage: '0.03', // 3% tolerance
  userWalletAddress: userWalletAddress,
};

Retrieve Transaction Data

Call the /swap endpoint to get the raw transaction payload:

const getSwapData = async () => {
  const apiRequestUrl = getAggregatorRequestUrl('/swap', swapParams);

  const headers = {
    // Same signed headers as above
  };

  const response = await fetch(apiRequestUrl, { method: 'GET', headers });
  return response.json();
};

Broadcast the Transaction on TON

Use the returned transaction data to sign and send it via your wallet contract:

async function sendTx(tx) {
  const endpoint = await getHttpEndpoint();
  const client = new TonClient({ endpoint });

  const mnemonic = ['range', '...']; // Restore from secure storage
  const keyPair = await mnemonicToPrivateKey(mnemonic);
  const wallet = WalletContractV4.create({ workchain: 0, publicKey: keyPair.publicKey });
  const contract = client.open(wallet);

  let seqno = await contract.getSeqno();
  const body = Cell.fromBase64(tx.data);
  const value = tx.value / 1e9; // Convert from nano to base unit

  await contract.sendTransfer({
    seqno,
    secretKey: keyPair.secretKey,
    messages: [
      internal({
        value: toNano(value),
        to: tx.to,
        body: body,
      }),
    ],
  });

  console.log("Transaction sent! Waiting for confirmation...");
}

👉 Learn how to integrate real-time swap execution into your dApp interface.


Frequently Asked Questions (FAQ)

How do I find a JETTON token’s contract address?

You can locate JETTON addresses using blockchain explorers like tonscan.org or tonviewer.com. Search by token symbol or name and verify the contract under the "Tokens" tab.

What is slippage, and why does it matter?

Slippage is the difference between expected and actual swap price due to market volatility. Setting a slippage tolerance (e.g., 3%) ensures your transaction reverts if prices move unfavorably—protecting users from losses.

Can I use this API for other blockchains?

Yes! The OKX DEX Aggregator supports multiple chains including Ethereum, BSC, Solana, and more. Just update the chainId and token addresses accordingly.

Is it safe to expose my API key in frontend code?

No. API keys should only be used in backend environments. For frontend apps, route all authenticated requests through a secure proxy server to prevent credential leaks.

How are gas fees calculated on TON?

TON uses a dynamic gas model where fees depend on message size and computational complexity. The /swap response includes estimated gas values—always add a small buffer to avoid failures.

What happens if a swap fails?

If a transaction fails due to slippage or insufficient balance, the funds remain in your wallet. Failed transactions still consume gas for computation. Always test swaps with small amounts first.


With this foundation, you can now build robust, user-friendly swap features directly into your TON-based applications. From wallets to DeFi dashboards, integrating decentralized exchange functionality opens new possibilities for engagement and utility.

👉 Start building with powerful Web3 APIs designed for scalability and security.