What you’ll build
A viem script that swaps 0.001 WBOT for USDT through the BDEX V2 Router02 at0xD6425a02f0845B8D99e349C34D2E7A576E177345 on testnet.
Prerequisites
- The
bot-defiproject and.envfile from Wrap BOT. - At least 0.001 WBOT and a little tBOT for gas. Run the wrap script first if you have no WBOT.
Steps
1
Write the script
swap-v2.ts
2
Understand each part
getAmountsOut(amountIn, path)returns one amount per token in the path. For a direct pair that’s[amountIn, amountOut]. The 0.30% pool fee is already taken out.pathlists the tokens to swap through. For tokens without a direct pool, route through WBOT, for example[tokenA, wbot, usdt].amountOutMinis the quote minus 0.5%. If the price moves further, the swap reverts.- The approval is for the exact amount. Unlimited approvals save a transaction but leave the router able to move all your WBOT.
deadlineis a Unix timestamp in seconds. After it, the router refuses the swap.
3
Run it
Verify it worked
Output
Swap native tBOT directly
To skip wrapping, useswapExactETHForTokens. It takes no amountIn argument: send the tBOT as value, and start the path with WBOT.
swap-v2-native.ts
amountIn = parseEther("1") quoted 16.177665 USDT and succeeded. There’s no approval step, because you send tBOT as value instead of spending a token.
Troubleshooting
BotDexV2Router: INSUFFICIENT_OUTPUT_AMOUNT
BotDexV2Router: INSUFFICIENT_OUTPUT_AMOUNT
The price moved more than your slippage between the quote and the swap, or your quote is stale. Quote again right before you swap. Raise the slippage only if the pool is very thin.
BotDexV2Router: EXPIRED
BotDexV2Router: EXPIRED
The deadline passed before the transaction was mined. Build the deadline right before sending.
TransferHelper::transferFrom: transferFrom failed
TransferHelper::transferFrom: transferFrom failed
The router couldn’t pull your input token. The approval is missing or too small, or your balance is too low.
The quote reverts
The quote reverts
There’s no V2 pair for the tokens in the path, or the pair is empty, which reverts with
BotDexV2Library: INSUFFICIENT_LIQUIDITY. Check with the factory’s getPair, or list pairs with the BDEX API.Next steps
Swap on BDEX V3
Compare V3 fee tiers for a better price.
Provide V2 liquidity
Earn swap fees by adding to a pool.