Introduction

ONTON Finance is a decentralized exchange (DEX) built on the TON blockchain, offering users a seamless and cost-effective way to swap tokens. By leveraging the Automated ONTON DEX (AMM) model, ONTON Finance enables users to trade tokens directly from liquidity pools, ensuring fast and efficient transactions.

Step-by-Step Guide to Swapping Tokens

Follow these simple steps to swap tokens on ONTON Finance:

  1. Connect your wallet: Visit the ONTON Finance website and connect your TON wallet by clicking on the “Connect Wallet” button in the top right corner of the screen.

  2. Select tokens: Choose the token pair you want to swap from the dropdown menus. For example, if you want to swap USDT for ONTON, select USDT in the “From” field and ONTON in the “To” field.

  3. Enter the amount: Enter the amount of tokens you want to swap in the “From” field. The “To” field will automatically display the estimated amount of tokens you will receive based on the current exchange rate.

  4. Review the details: Before confirming the transaction, review the swap details, including the exchange rate, slippage tolerance, and transaction fees. Adjust the slippage tolerance if needed.

  5. Confirm the swap: If you are satisfied with the details, click the “Swap” button to initiate the transaction. Your wallet will prompt you to confirm the transaction and pay the associated fees.

  6. Transaction complete: Once the transaction is confirmed on the TON blockchain, the swapped tokens will be deposited into your wallet. You can view your updated token balances in your wallet or on the ONTON Finance platform.

Detailed Transaction Flow Using SDK

To further illustrate the transaction flow and the use of the ONTON Finance SDK, refer to the mermaid diagram below:

SDK Usage Breakdown

To integrate ONTON Finance SDK into your application for token swapping, follow these steps:

Prerequisites

Ensure you have Node.js (version 18.10.0 or higher) installed on your machine.

Step 1: Install the Onton SDK

Add the Onton SDK to your project using npm:

npm install onton-sdk

Step 2: Import Required Libraries

Import the necessary libraries and configure environment variables:

import dotenv from "dotenv";
import TonWeb from "tonweb";
import { TonClient, toNano } from "@ton/ton";
import { mnemonicToKeyPair } from "tonweb-mnemonic";
import { Factory } from 'onton-sdk';
import { WalletV4ContractR2 } from "tonweb/dist/types/contract/wallet/v4/wallet-v4-contract-r2";

dotenv.config();

Step 3: Define Helper Function to Await Seqno Change

Create a helper function to wait until the sequence number (seqno) changes, ensuring transaction confirmation:

async function awaitSeqno(wallet: WalletV4ContractR2, seqno: number): Promise<boolean> {
  let currentSeqno = seqno;
  while (currentSeqno === seqno) {
    await new Promise((resolve) => setTimeout(resolve, 1500));
    seqno = (await wallet.methods.seqno().call()) ?? 0;
  }
  return Promise.resolve(true);
}

Step 4: Initialize Onton SDK and Execute Operations

Set up the main function to initialize the SDK and perform the token swap:

const main = async () => {
  const apiKey = "YOUR_API_KEY_HERE";
  const walletAddress = "YOUR_WALLET_ADDRESS_HERE";
  const token0JettonAddress = "YOUR_TOKEN0_JETTON_ADDRESS_HERE";
  const token1JettonAddress = "YOUR_TOKEN1_JETTON_ADDRESS_HERE";
  const token0Amount = toNano("YOUR_TOKEN0_AMOUNT_HERE");
  const token1Amount = toNano("YOUR_TOKEN1_AMOUNT_HERE");
  const mnemonic = "YOUR_MNEMONIC_HERE".split(" ");
  const referralAddress = "YOUR_REFERRAL_ADDRESS_HERE";
  
  const tonClient = new TonClient({
    endpoint: "https://toncenter.com/api/v2/jsonRPC",
    apiKey: apiKey
  });

  const ontonSDK = tonClient.open(new Factory());

  // Retrieve deposit liquidity transaction messages
  const depositLiquidityTransactionMessages = await ontonSDK.getDepositLiquidity({
    walletAddress: walletAddress,
    token0JettonAddress: token0JettonAddress,
    token0Amount: token0Amount,
    token1JettonAddress: token1JettonAddress,
    token1Amount: token1Amount
  });

  // Initialize TonWeb and wallet
  const provider = new TonWeb.HttpProvider("https://toncenter.com/api/v2/jsonRPC", { apiKey: apiKey });
  const tonweb = new TonWeb(provider);
  const keyPair = await mnemonicToKeyPair(mnemonic);
  const wallet = new tonweb.wallet.all["v4R2"](tonweb.provider, {
    publicKey: keyPair.publicKey,
    wc: 0
  });

  // Execute first transfer
  const response0 = await wallet.methods
    .transfer({
      secretKey: keyPair.secretKey,
      toAddress: depositLiquidityTransactionMessages[0].to.toString(),
      amount: new tonweb.utils.BN(depositLiquidityTransactionMessages[0].value),
      payload: TonWeb.boc.Cell.oneFromBoc(
        TonWeb.utils.base64ToBytes(depositLiquidityTransactionMessages[0].body!.toBoc().toString("base64"))
      ),
      sendMode: 3,
      seqno: (await wallet.methods.seqno().call()) ?? 0
    })
    .send();

  // Wait for seqno change
  let seqno = (await wallet.methods.seqno().call()) ?? 0;
  await awaitSeqno(wallet, seqno);

  // Execute second transfer
  const response1 = await wallet.methods
    .transfer({
      secretKey: keyPair.secretKey,
      toAddress: depositLiquidityTransactionMessages[1].to.toString(),
      amount: new tonweb.utils.BN(depositLiquidityTransactionMessages[1].value),
      payload: TonWeb.boc.Cell.oneFromBoc(
        TonWeb.utils.base64ToBytes(depositLiquidityTransactionMessages[1].body!.toBoc().toString("base64"))
      ),
      sendMode: 3,
      seqno: (await wallet.methods.seqno().call()) ?? 0
    })
    .send();
};

main();

Replace the following environment variables with your actual values:

  • API_KEY
  • WALLET_ADDRESS
  • TOKEN0_JETTON_ADDRESS
  • TOKEN1_JETTON_ADDRESS
  • TOKEN0_AMOUNT
  • TOKEN1_AMOUNT
  • MNEMONIC
  • REFERRAL_ADDRESS

Applications and Integration Examples

Decentralized Finance (DeFi) Platforms

DeFi platforms can integrate the ONTON Finance SDK to offer users token swapping services directly within their interface. This can include yield farming platforms, lending and borrowing protocols, and decentralized exchanges.

Crypto Wallets

Crypto wallets can enhance their functionality by integrating the SDK to enable in-app token swaps. This provides users with a one-stop solution for managing their assets, reducing the need to use multiple platforms.

eCommerce and Payment Solutions

eCommerce platforms and payment solutions can use the SDK to accept a variety of cryptocurrencies, automatically swapping tokens as needed to provide seamless payment options for users.

Gaming and Virtual Worlds

Blockchain-based games and virtual worlds can integrate the SDK to facilitate in-game currency exchanges, enabling players to trade and swap tokens without leaving the game environment.

Tokenized Communities and DAOs

Decentralized Autonomous Organizations (DAOs) and tokenized communities can leverage the SDK to manage their native tokens, facilitate voting mechanisms, and distribute rewards to members.

Cross-Chain Bridges

Developers can build cross-chain bridges that utilize the ONTON Finance SDK to facilitate token swaps between different blockchain networks, enhancing liquidity and accessibility for users.

Investment and Portfolio Management Apps

Investment apps can integrate the SDK to allow users to rebalance their portfolios by swapping tokens directly within the app, providing a streamlined and efficient user experience.

Example: Integrating the SDK into a Crypto Wallet

Here’s an example of how to integrate the ONTON Finance SDK into a crypto wallet application:

Step 1: Install the Onton SDK

Add the Onton SDK to your project using npm:

npm install onton-sdk

Step 2: Import Required Libraries

Import the necessary libraries and configure environment variables:

import dotenv from "dotenv";
import TonWeb from "tonweb";
import { TonClient, toNano } from "@ton/ton";
import { mnemonicToKeyPair } from "tonweb-mnemonic";
import { Factory } from 'onton-sdk';
import { WalletV4ContractR2 } from "tonweb/dist/types/contract/wallet/v4/wallet-v4-contract-r2";

dotenv.config();

Step 3: Define Helper Function to Await Seqno Change

Create a helper function to wait until the sequence number (seqno) changes, ensuring transaction confirmation:

async function awaitSeqno(wallet: WalletV4ContractR2, seqno: number): Promise<boolean> {
  let currentSeqno = seqno;
  while (currentSeqno === seqno) {
    await new Promise((resolve) => setTimeout(resolve, 1500));
    seqno = (await wallet.methods.seqno().call()) ?? 0;
  }
  return Promise.resolve(true);
}

Step 4: Initialize Onton SDK and Execute Operations

Set up the main function to initialize the SDK and perform the token swap:

const main = async () => {
  const apiKey = "YOUR_API_KEY_HERE";
  const walletAddress = "YOUR_WALLET_ADDRESS_HERE";
  const token0JettonAddress = "YOUR_SEND_JETTON_ADDRESS";
  const token1JettonAddress = "YOUR_RECEIVE_JETTON_ADDRESS";
  const token0Amount = toNano("30"); // Example amount
  const mnemonic = "YOUR_MNEMONIC_HERE".split(" ");
  const referralAddress = "YOUR_REFERRAL_ADDRESS_HERE";
  
  const tonClient = new TonClient({
    endpoint: "https://toncenter.com/api/v2/jsonRPC",
    apiKey: apiKey
  });

  const ontonSDK = tonClient.open(new Factory());

  // Retrieve swap transaction message
  const swapTransactionMessage = await ontonSDK.getSwap({
    walletAddress: walletAddress,
    sendJettonAddress: token0JettonAddress,
    receiveJettonAddress: token1JettonAddress,
    referralAddress: referralAddress,
    tokenAmount: token0Amount
  });

  // Initialize TonWeb and wallet
  const provider = new TonWeb.HttpProvider("https://toncenter.com/api/v2/jsonRPC", { apiKey: apiKey });
  const tonweb = new TonWeb(provider);
  const keyPair = await mnemonicToKeyPair(mnemonic);
  const wallet = new tonweb.wallet.all["v4R2"](tonweb.provider, {
    publicKey: keyPair.publicKey,
    wc: 0
  });

  // Execute transfer
  const response = await wallet.methods
    .transfer({
      secretKey: keyPair.secretKey,
      toAddress: swapTransactionMessage.to.toString(),
      amount: new tonweb.utils.BN(swapTransactionMessage.value),
      payload: TonWeb.boc.Cell.oneFromBoc(
        TonWeb.utils.base64ToBytes(swapTransactionMessage.body!.toBoc().toString("base64"))
      ),
      sendMode: 3,
      seqno: (await wallet.methods.seqno().call()) ?? 0
    })
    .send();

  // Wait for seqno change
  let seqno = (await wallet.methods.seqno().call()) ?? 0;
  await awaitSeqno(wallet, seqno);

  console.log(response);
};

main();

Replace the following environment variables with your actual values:

  • YOUR_API_KEY_HERE
  • YOUR_WALLET_ADDRESS_HERE
  • YOUR_SEND_JETTON_ADDRESS
  • YOUR_RECEIVE_JETTON_ADDRESS
  • YOUR_MNEMONIC_HERE
  • YOUR_REFERRAL_ADDRESS_HERE

By integrating the ONTON Finance SDK, developers can unlock a wide range of possibilities for enhancing their applications and providing users with a seamless, secure, and efficient token swapping experience.

Onton SDK Version

Ensure you are using the latest version of the Onton SDK to access the newest features and improvements.

npm install onton-sdk@latest

Deployment

ONTON Finance is built on the TON blockchain, ensuring fast and secure transactions.

When you deploy your application using the Onton SDK, it interacts directly with the TON blockchain. No additional deployment steps are required.

Troubleshooting

Below are some common issues you might encounter while using the Onton SDK and their solutions:

Invalid Private Key

Ensure that you are using a valid private key when initializing the OntonSDK instance. Double-check your private key and ensure it is in the correct format.

Insufficient Balance

Make sure the account associated with your private key has enough balance to perform the required operations, such as swapping tokens or providing liquidity.

Network Connection Issues

Check your network connection and ensure you can successfully connect to the TON blockchain network. Verify that your firewall or network settings are not blocking the connection.

If you encounter any other issues or have questions, please contact our support team or consult the ONTON Finance community forum for assistance.

For the latest updates and changes to the Onton SDK, please refer to the SDK Changelog.

Quick Start

For a quick start with the Onton SDK, follow the steps outlined above in the SDK Usage Breakdown section. Ensure you have all prerequisites installed and environment variables configured correctly.