Swap SDK

Sample code that performs a swap on the Colossus TON/USDT pool.

This example demonstrates how to execute a token swap using the Colossus SDK on the TON blockchain. The example swaps from TON to USDT using the Colossus concentrated liquidity pool.

✅ Make sure your .env file includes MY_MNEMONIC and API_KEY.


TypeScript Code Example

import { TonClient, WalletContractV4, internal } from "@ton/ton";
import { mnemonicToPrivateKey } from "@ton/crypto";
import { DEX, pTON } from "@titan-tg/colossus-sdk";

import dotenv from "dotenv";
dotenv.config();

const deployConfigEnv = ".env";
let myMnemonic: string;
let apiKey: string;

if (!process.env.MY_MNEMONIC) {
  console.log(" - ERROR: No MY_MNEMONIC env variable found, please add it to env");
  process.exit(1);
} else {
  myMnemonic = process.env.MY_MNEMONIC;
}

if (!process.env.API_KEY) {
  console.log(" - ERROR: No API_KEY env variable found, please add it to env");
  process.exit(1);
} else {
  apiKey = process.env.API_KEY;
}

const KNOWN_MAINNET_TOKEN_INFOS = {
  USDT: {
    address: "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs",
    decimals: "6",
    symbol: "USDT",
  },
  tsTON: {
    address: "EQC98_qAmNEptUtPc7W6xdHh_ZHrBUFpw5Ft_IzNU20QAJav",
    decimals: "9",
    symbol: "tsTON",
  },
  TON: {
    address: pTON.v1.address.toString(),
    decimals: "9",
    symbol: "TON",
  },
  NOT: {
    address: "EQAvlWFDxGF2lXm67y4yzC17wYKD9A0guwPkMs1gOsM__NOT",
    decimals: "9",
    symbol: "NOT",
  },
};

async function swapTonForUsdt() {
  const client = new TonClient({
    endpoint: "https://toncenter.com/api/v2/jsonRPC",
    apiKey: apiKey,
  });

  const keyPair = await mnemonicToPrivateKey(myMnemonic.split(" "));
  const wallet = WalletContractV4.create({ workchain: 0, publicKey: keyPair.publicKey });
  const contract = client.open(wallet);

  const token0 = "USDT";
  const token1 = "TON";

  const token0Address = KNOWN_MAINNET_TOKEN_INFOS[token0].address;
  const token1Address = KNOWN_MAINNET_TOKEN_INFOS[token1].address;

  const router = client.open(new DEX.v1.Router(DEX.v1.Router.mainnetAddress));
  const vault0 = client.open(await router.getVault({ token: token0Address }));
  const vault1 = client.open(await router.getVault({ token: token1Address }));

  const allPools = await fetch("https://api.titan.tg/beta/clmm/pools").then(res => res.json());
  const poolInfo = allPools.find(
    (pool: any) =>
      pool.token0.address === token0Address &&
      (token1 === "TON"
        ? pool.token1.address === "EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c"
        : pool.token1.address === token1Address),
  );
  if (!poolInfo) throw new Error("Pool not found");

  const feeParams = {
    lpFee: poolInfo.lpFeeBps,
    protocolFee: poolInfo.protocolFeeBps,
    refFee: poolInfo.refFeeBps,
  };
  const tickSize = poolInfo.tickSize;

  const poolManager = client.open(
    await router.getPoolManager({
      token0: vault0.address,
      token1: vault1.address,
      tickSize,
      feeParams,
    }),
  );
  const poolManagerData = await poolManager.getPoolManagerData();

  const pool = client.open(
    await router.getPool({
      vault0: vault0.address,
      vault1: vault1.address,
      minTick: poolManagerData.shardIndex,
      tickSize,
      feeParams,
    }),
  );

  const amountIn = 1_000n; // 0.001 USDT
  const simResult = await pool.getSwapSimulation({
    isToken0: true,
    amount: amountIn,
    isExactOut: false,
  });
  const simOut = simResult.out;
  console.log(`Simulated swap out: ${simOut}`);
  if (simResult.exitCode !== DEX.v1.Pool.exitCodes.swapOk) {
    throw new Error(
      `Could not simulate swap. Exit code: ${DEX.v1.Pool.parseExitCode(simResult.exitCode)}`,
    );
  }

  let swapTxParams;
  if (token0Address === KNOWN_MAINNET_TOKEN_INFOS.TON.address) {
    swapTxParams = await vault0.getSwapTonToJettonTxParams({
      userWalletAddress: contract.address,
      otherVaultAddress: vault1.address,
      minTick: poolManagerData.shardIndex,
      tickSize,
      feeParams,
      exactOut: false,
      queryId: 12345,
      offerAmount: amountIn,
      outAmount: simOut,
      proxyTon: new pTON.v1(),
    });
  } else {
    swapTxParams = await vault0.getSwapJettonToJettonTxParams({
      userWalletAddress: contract.address,
      otherVaultAddress: vault1.address,
      minTick: poolManagerData.shardIndex,
      tickSize,
      feeParams,
      exactOut: false,
      queryId: 12345,
      offerAmount: amountIn,
      outAmount: simOut,
      offerJettonAddress: token0Address,
    });
  }

  await contract.sendTransfer({
    seqno: await contract.getSeqno(),
    secretKey: keyPair.secretKey,
    messages: [internal(swapTxParams)],
  });
}

swapTonForUsdt()
  .then(() => console.log("Swap completed"))
  .catch(console.error);

Last updated