Introduction
This guide will cover how to use smart order routing to compute optimal routes and execute swaps. Rather than trading between a single pool, smart routing may use multiple hops (as many as needed) to ensure that the end result of the swap is the optimal price.If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our background page!
- Creating a router instance
- Creating a route
- Swapping using a route
The
@kingdomdotone/v3-sdk is Ramses’ fork of the Uniswap V3 SDK, tailored for Ramses V3 pools.routing.ts.
The config, which we will use in some code snippets in this guides has this structure:
Creating a router instance
To compute our route, we will use the@uniswap/smart-order-router package, specifically the AlphaRouter class which requires a chainId and a provider. Note that routing is not supported for local forks, so we will use a mainnet provider even when swapping on a local fork:
Creating a route
We will use the SwapRouter contract for our trade. Thesmart-order-router package provides us with a SwapOptionsSwapRouter02 interface, defining the wallet to use, slippage tolerance, and deadline for the transaction that we need to interact with the contract:
TradeType.EXACT_INPUT or TradeType.EXACT_OUTPUT) with the currency and the input amount to use to get a quote. For this example, we’ll use an EXACT_INPUT trade to get a quote outputted in the quote currency.
fromReadableAmount function calculates the amount of tokens in the Token’s smallest unit from the full unit and the Token’s decimals:
src/libs/conversion.ts
route and route.methodParameters are optional as the request can fail, for example if no route exists between the two Tokens or because of networking issues.
We check if the call was succesful:
Swapping using a route
First, we need to give approval to theSwapRouter smart contract to spend our tokens for us:
approve function that accepts the address of the smart contract that we want to allow spending our tokens and the amount the smart contract should be allowed to spend.
We can get the V3_SWAP_ROUTER_ADDRESS for our chain from the Ramses contract addresses.
Keep in mind that different chains might have different deployment addresses for the same contracts.
The deployment address for local forks of a network are the same as in the network you forked, so for a fork of mainnet it would be the address for Mainnet.
We need to wait one block for the approval transaction to be included by the blockchain.
Once the approval has been granted, we can now execute the trade using the route’s computed calldata, values, and gas values:
routing.ts.
