This is the part 4 of Uniswap V3 SDK Swap Tutorial, full source code.
A crucial part of making a swap is creating a swap route. This is the optimal path with swap parameters which Uniswap constructs to make the desired swap.
Swap is conducted in the following way:
Let’s see what we need to specify to ask Uniswap for a route:
After this explanation it should be straightforward. First, let’s ask Uniswap for a route and check if route is returned:
const inAmount = CurrencyAmount.fromRawAmount(tokenIn, amountIn.toString());
const router = new AlphaRouter({ chainId: tokenIn.chainId, provider: provider });
const route = await router.route(
inAmount,
tokenOut,
TradeType.EXACT_INPUT,
// swapOptions
{
recipient: walletAddress,
slippageTolerance: new Percent(5, 100), // Big slippage – for a test
deadline: Math.floor(Date.now() / 1000 + 1800) // add 1800 seconds – 30 mins deadline
},
// router config
{
maxSwapsPerPath: 1 // remove this if you want multi-hop swaps as well.
}
);
if (route == null || route.methodParameters === undefined)
throw "No route loaded";
For example, on Goerli test network as of July 2022 only WETH-UNI swaps are available, so you’d get a null route trying to swap other tokens.
Then let’s print quote and gas fees:
console.log(` You'll get ${route.quote.toFixed()} of ${tokenOut.symbol}`);
// output quote minus gas fees
console.log(` Gas Adjusted Quote: ${route.quoteGasAdjusted.toFixed()}`);
console.log(` Gas Used Quote Token: ${route.estimatedGasUsedQuoteToken.toFixed()}`);
console.log(` Gas Used USD: ${route.estimatedGasUsedUSD.toFixed()}`);
console.log(` Gas Used: ${route.estimatedGasUsed.toString()}`);
console.log(` Gas Price Wei: ${route.gasPriceWei}`);
console.log('');
To those who is confused about gas and gas price like I was. Gas is the amount of computing work Ethereum needs to get the work done. Most simple swaps I tested require 300,000 of computational work and that does not change on network load. Simply put, this is a number of computation steps for Ethereum virtual machine.
Gas price is the amount in wei you pay for each computational step. If you want to speed up execution of your swap than set gas price more than estimated (route.gasPriceWei) so that nodes would be incentivised to process your operation first.
So, we finished part 4 and in this part we asked Uniswap for a swap route and got it afterwards. See part 5 on how to execute actual swap.