Building a Token Swap Application on the Ton Blockchain: A Comprehensive Guide

·

This guide provides a step-by-step walkthrough for creating a token swap application using OKX DEX API to exchange TON for JETTON tokens on the Ton blockchain. We'll cover environment setup, price quotation, and transaction execution processes.

1. Environment Configuration

1.1 Package Installation

Begin by installing required dependencies:

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

1.2 Initial Setup

Configure your development environment with these essential parameters:

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");

// Environment variables
const apiBaseUrl = 'https://web3.okx.com/api/v5/dex/aggregator';
const chainId = '607';
const fromTokenAddress = 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c'; // TON native token
const toTokenAddress = 'EQAQXlWJvGbbFfE8F3oS8s87lIgdovS455IsWFaRdmJetTon'; // JETTON token
const userWallet = 'UQDoI2kiSNQZxxxxxxxxxxxx6lM2ZSxKkEw3k1';
const fromAmount = '1000000';

👉 Get started with Ton blockchain development

2. Obtaining Price Quotations

2.1 Defining Quote Parameters

Configure the swap parameters for price estimation:

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

2.2 Requesting Price Data

Create a function to fetch price quotes:

const getQuote = async () => {
  const queryString = new URLSearchParams(quoteParams).toString();
  return fetch(`${apiBaseUrl}/quote?${queryString}`, {
    method: 'GET',
    headers: generateHeaders()
  }).then(res => res.json());
};

3. Executing the Token Swap

3.1 Swap Parameters Configuration

Set up transaction parameters:

const swapParams = {
  chainId: chainId,
  fromTokenAddress: fromTokenAddress,
  toTokenAddress: toTokenAddress,
  amount: fromAmount,
  slippage: '0.03',
  userWalletAddress: userWallet
};

3.2 Transaction Preparation

Function to prepare swap transaction:

const prepareSwap = async () => {
  const queryString = new URLSearchParams(swapParams).toString();
  return fetch(`${apiBaseUrl}/swap?${queryString}`, {
    method: 'GET',
    headers: generateHeaders()
  }).then(res => res.json());
};

3.3 Transaction Execution

Send the prepared transaction to the network:

async function executeSwap(txData) {
  const endpoint = await getHttpEndpoint();
  const client = new TonClient({ endpoint });
  const wallet = WalletContractV4.create({ /* ... */ });
  
  const body = Cell.fromBase64(txData.data);
  await wallet.sendTransfer({
    messages: [internal({
      value: toNano(txData.value),
      to: txData.to,
      body: body
    })]
  });
}

👉 Explore advanced DEX API features

Frequently Asked Questions

What is the minimum amount for swapping tokens?

The minimum swap amount depends on liquidity pools and current market conditions. The API will return an error if the amount is too small.

How do I handle failed transactions?

Check the transaction hash in a Ton blockchain explorer. If the transaction fails, you may need to adjust parameters like slippage tolerance or gas fees.

Can I swap any token on Ton blockchain?

Our API supports swaps between TON and verified JETTON tokens. Check the documentation for the complete list of supported tokens.

How long does a swap typically take?

Most swaps complete within 2-5 minutes, depending on network congestion and gas fees you've set.

What's the difference between swap and quote endpoints?

The quote endpoint provides price estimation without executing a transaction, while the swap endpoint prepares and submits the actual transaction.

Is there a limit to swap frequency?

There are no hard limits, but frequent large swaps might temporarily impact price due to liquidity pool dynamics.