Routing a Swap
This section explains how to use Storyhunt's router to compute optimal routes and execute swaps.
Introduction
This section explains how to use Storyhunt's routing capabilities to compute optimal routes and execute swaps. Instead of relying on a single pool, smart routing utilizes multiple hops to ensure the best possible price for a swap. This example demonstrates trading between WIP and USDC, but any two currencies and input amounts can be configured.
The process includes:
Getting required Trading Pools
Constructing a route
Executing a swap using the route
Get required Trading Pools
To get the pool data, one can use the graph data to efficiently fetch required pool data.
const tokenPoolResult = await executeGraphQuery<GraphPoolResponse>(
POOLWTOKEN_QUERY,
{
token0: currencyIn.address.toLowerCase(),
token1: currencyOut.address.toLowerCase(),
});
const poolObj = new Pool(
tokenA,
tokenB,
parseInt(pool.feeTier),
JSBI.BigInt(pool.sqrtPrice),
JSBI.BigInt(pool.liquidity),
parseInt(pool.tick),
tickDataProvider
);Getting the optimal a Route
For the trade, get the best possible route from using multihop based on pool data. This example uses an EXACT_INPUT trade:
Before proceeding, check if the route was successfully created:
Swapping Using a Route
First, approve the SwapRouter smart contract to spend the input tokens:
Construct and send the transaction:
Set the swap options, including slippage tolerance and deadline:
Use the SwapRouter to get the call parameters for the trade:
Wait for the approval transaction to be confirmed before executing the trade. Then, use the routeβs computed calldata, value, and gas values to send the transaction:
After executing the trade, you should see the currency balances update once the transaction is confirmed.
Next Steps
Now that you're familiar with routing swaps, you can explore advanced topics such as providing liquidity to Storyhunt pools.