Skip to content

Router

Functionality to interact with the router contract for swaps

We will fetch all required pools for a swap, calculate the best path and pass it to the router contract to swap.

Get all pools

We need to use the PoolFetcher to get all pools. The base token addresses are tokens which can basically be paired with the tokens you want to swap. It is fair to assume that most pairs will have either the native token of the chain or a stable coin (like USDC).

getAllPools.ts
import {PoolFetcher, PathFinder, TokenSwap} from "@kuru-labs/kuru-sdk";
import * as KuruConfig from "./../config.json";
 
(async() => {
    const poolFetcher = new PoolFetcher(KuruConfig.KURU_API_URL as string);
    const pools = await poolFetcher.getAllPools(
        TOKEN_IN_ADDRESS,
        TOKEN_OUT_ADDRESS,
        [
            {
                symbol: "FIRST_BASE_TOKEN",
                address: FIRST_BASE_TOKEN_ADDRESS
            },
            {
                symbol: "SECOND_BASE_TOKEN",
                address: SECOND_BASE_TOKEN_ADDRESS
            }
        ]
    );
    console.log(pools);
})();

Find best path

To find the best path from among these pools, we need to use the PathFinder.

    const bestPath = await PathFinder.findBestPath(
        provider,
        TOKEN_IN_ADDRESS,
        TOKEN_OUT_ADDRESS,
        AMOUNT_TO_SWAP, //in number format, not in erc20 decimals
        "amountIn", //use "amountOut" if you want to calculate exact input amount for a given output amount
        poolFetcher,
        pools
    )

Swap

    const receipt = await KuruSdk.TokenSwap.swap(
        signer,
        routerAddress,
        bestPath,
        AMOUNT_TO_SWAP, //in number format
        IN_TOKEN_DECIMALS,
        OUT_TOKEN_DECIMALS,
        APPROVE_TOKENS, //set to true for approval
        //approval callback
        (txHash: string | null) => {
          console.log(`Transaction hash: ${txHash}`);
        }
      );