What you’ll build
A viem script that checks the WBOT/USDT pools on the 0.05%, 0.30% and 1.00% fee tiers, picks the best quote, and swaps 0.0005 tBOT through the V3 SwapRouter. You send native tBOT asvalue, so you don’t need to wrap or approve anything.
Prerequisites
- The
bot-defiproject and.envfile from Wrap BOT. - At least 0.001 tBOT: 0.0005 for the swap plus gas.
Steps
1
Write the script
swap-v3.ts
2
Understand each part
getPool(tokenA, tokenB, fee)on the V3 factory returns the pool for one fee tier, or the zero address if nobody created it. Token order doesn’t matter.quoteExactInputSingleruns the swap inside the quoter and reverts to return the result. It isn’t aviewfunction, so call it withsimulateContract. A pool with no liquidity at the current price makes it revert, which is why the call is wrapped intry.feeis in hundredths of a basis point:500is 0.05%,3000is 0.30% and10000is 1.00%.amountOutMinimumis the best quote minus 0.5%. If the swap would return less, it reverts.value: amountInsends tBOT with the call. BecausetokenInis WBOT, the router wraps it before the swap.sqrtPriceLimitX96: 0nmeans no price limit. Leave it at zero unless you want the swap to stop at a given price.
3
Run it
Verify it worked
Output
Swap an ERC-20 token instead
To swap a token such as USDT, dropvalue and approve the SwapRouter for amountIn first, the same way as in Swap on BDEX V2. To receive native tBOT instead of WBOT, use the router’s multicall to combine exactInputSingle (with the router as recipient) and unwrapWETH9.
Troubleshooting
Too little received
Too little received
The output fell below
amountOutMinimum. Quote again right before the swap, and raise the slippage only for very thin pools.Transaction too old
Transaction too old
The deadline passed before the transaction was mined. Build the deadline right before sending.
STF
STF
The router couldn’t pull your input token. Approve the SwapRouter for at least
amountIn and check your balance. You won’t see this when you pay with value.Every fee tier prints no quote
Every fee tier prints no quote
No pool has liquidity at the current price for your amount. Try a smaller amount, or use the V2 pool.
Next steps
Slippage and deadlines
Choose safe values for both.
Provide V3 liquidity
Learn how concentrated liquidity works.