The getBestRoute function finds the optimal trading route for a token swap through Fibrous Finance’s liquidity pools.

Function Signature

/**
 * Gets the best route from the API
 * @param amount: Amount to swap, formatted
 * @param tokenInAddress: Token to swap from
 * @param tokenOutAddress: Token to swap to
 * @param chainName: Chain name where the transaction will take place
 * @param options: Optional parameters such as slippage and excluded protocols
 * @returns Promise<RouteResponse>
 * @throws Error if the API returns an error
 */
async getBestRoute(
    amount: BigNumber,
    tokenInAddress: string,
    tokenOutAddress: string,
    chainName: string,
    options?: Partial<RouteOverrides>
): Promise<RouteResponse>;

Parameters

ParameterTypeDescription
amountBigNumberAmount to swap, formatted according to token decimals
tokenInAddressstringToken address to swap from
tokenOutAddressstringToken address to swap to
chainNamestringChain name where the transaction will take place
optionsRouteOverridesOptional parameters for route customization

RouteOverrides Type

type RouteOverrides = {
  reverse: boolean;
  direct: boolean;
  excludeProtocols: string[];
};
  • excludeProtocols: This is where you list the IDs of the AMMs you don’t want to include. For example, if there are certain AMMs you prefer not to use due to high fees or other reasons, you simply put their unique IDs in this list.
  • Use supportPairs to get a list of supported AMMs and their IDs.

RouteResponse Type

type RouteResponse = {
  success: true;
  inputToken: Token;
  inputAmount: string;
  outputToken: Token;
  outputAmount: string;
  estimatedGasUsed: string;
  route: Route[];
  time: number;
  swapType?: string; // Specific to EVM
};

Example Usage

import { Router as FibrousRouter } from "fibrous-router-sdk";
import { BigNumber } from "@ethersproject/bignumber";
import { parseUnits } from "ethers";

const router = new FibrousRouter();
const chainName = "base";
const inputToken = await fibrous.getToken(
  "0xfde4c96c8593536e31f229ea8f37b2ada2699bb2",
  "base",
);

if (!inputToken) {
  throw new Error("Input token not found");
}

const tokenInAddress = inputToken.address;
const tokenOutAddress = tokens["usdc"].address;
const tokenInDecimals = Number(inputToken.decimals);
const inputAmount = BigNumber.from(parseUnits("5", tokenInDecimals));

const route = await fibrous.getBestRoute(
  inputAmount, // amount
  tokenInAddress, // token input
  tokenOutAddress, // token output
  chainName,
);
// returns route type (src/types/route.ts)