This guide demonstrates how to perform a token swap using the Torch Finance SDK.
Example: Swapping TON for tsTON
1. Import modules & Initialize SDK
import { TorchSDK, generateQueryId, SwapParams, toUnit } from '@torch-finance/sdk';
import { Asset } from '@torch-finance/core';
const sdk = new TorchSDK();
2. Define Swap Parameters
Now, configure the parameters for swapping 0.01 TON for tsTON.
Your transaction will be refunded if your slippage tolerance is too low. Unless you know what you are doing, it is recommended to set the slippageTolerance to 0.01 (1%) or leave it empty to avoid transaction failure.
// recommend to generate queryId for every actions
const queryId = await generateQueryId();
// Define assets
const tonAsset = Asset.ton();
const tsTONAsset = Asset.jetton("EQC98_qAmNEptUtPc7W6xdHh_ZHrBUFpw5Ft_IzNU20QAJav");
// TON has 9 decimals
const assetInDecimals = 9;
// Define the swap
const swapParams: SwapParams = {
mode: 'ExactIn',
queryId: queryId,
assetIn: tonAsset,
assetOut: tsTONAsset,
amountIn: toUnit('0.01', assetInDecimals), // 0.01 TON
slippageTolerance: 0.01, // 1%
};
3. Preview the Swap
Simulate the swap to preview important details like the execution price and the estimated output amount.
Execution Price: 1 tsTON = 1.04 TON (This is human readable execution price)
Estimated Amount Out: 9900000 (You should handle decimal part by yourself)
Min Amount Out: 9801000
4. Execute the Swap
Finally, execute the transaction and retrieve the msgHash, which can be used to track its status.
Invoke the callback function returned by simulate swap method
// Send Transaction and get msghash
const sender = wallet.address;
const senderArgs = await getSwapPayload(sender, {
blockNumber: blockNumber, // Optional, but it will speed up a lot if you provided the latest blockNumber here
});
const msgHash = await send(senderArgs);
console.log(`Transaction sent with msghash: ${msgHash}`);
// ... Query transaction hash by message hash via Toncenter API V3 or TON Console
4.2 Execute Swap Directly with Swap Params
Invoke sdk.getSwapPayload directly
const sender = wallet.address;
const senderArgs = await sdk.getSwapPayload(sender, {
blockNumber: blockNumber, // Optional, but it will speed up a lot if you provided the latest blockNumber here
});
const msgHash = await send(senderArgs);
console.log(`Transaction sent with msghash: ${msgHash}`);