> For the complete documentation index, see [llms.txt](https://docs.titan.tg/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.titan.tg/colossus-concentrated-liquidity-amm/examples/swap-sdk.md).

# Swap SDK

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

```ts
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);
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.titan.tg/colossus-concentrated-liquidity-amm/examples/swap-sdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
