The Router class is the core of the soroswap-router-sdk, facilitating the discovery of optimal trade routes and quotes for token exchanges on a specified blockchain network. It leverages quote and pair providers to find the best exchange route based on the specified trade type, either exact input or exact output.

const USDC = new Token(Networks.TESTNET, USDC_ADDRESS, 7, "USDC", "USD Coin");
const XLM = new Token(Networks.TESTNET, XLM_ADDRESS, 7, "XLM", "Stellar Lumens");
const amountCurrency = CurrencyAmount.fromRawAmount(USDC, "100000000");
const quoteCurrency = XLM;
const tradeType = TradeType.EXACT_INPUT;

const router = new Router({
pairsCacheInSeconds: 20,
protocols: [Protocol.SOROSWAP],
network: Networks.TESTNET,
})

const route = await router.route(amountCurrency, quoteCurrency, tradeType);
console.log(route.trade.path);
// Output: ['0x...', '0x...', '0x...']

Constructors

  • Initializes a new instance of the Router with configurations for connecting to a specified backend and retrieving pair exchange information.

    Example:

    const router = new Router({
    pairsCacheInSeconds: 20,
    protocols: [Protocol.SOROSWAP],
    network: Networks.TESTNET,
    })

    Parameters

    • options: RouterOptions

    Returns Router

Properties

_maxHops: number = 2
_network: Networks
_pairProvider: PairProvider
_protocols: Protocol[]
_quoteProvider: QuoteProvider

Methods

  • Constructs a trade object from the provided route and amount details. This method finalizes the trade details, including calculating the minimum amount out for exact input trades, or maximum amount in for exact output trades.

    Parameters

    • tokenInCurrency: Currency

      The currency of the input token.

    • tokenOutCurrency: Currency

      The currency of the output token.

    • tradeType: TradeType

      The type of trade (EXACT_INPUT or EXACT_OUTPUT).

    • routeAmount: V2RouteWithValidQuote

      The selected route and amount details.

    Returns Promise<null | BuildTradeReturn>

    A trade object containing detailed information about the trade, or null if the routeAmount is null.

  • Recursively computes all routes from tokenIn to tokenOut using a depth-first search algorithm, considering a maximum number of hops.

    Parameters

    • tokenIn: Token

      The starting token for route computation.

    • tokenOut: Token

      The destination token for route computation.

    • pairs: Pair[]

      An array of all available pairs to be considered for routing.

    • network: Networks

      The ID of the blockchain network.

    • currentPath: Pair[] = []

      The current path being explored (used for recursion).

    • allPaths: V2Route[] = []

      Accumulator for all valid paths found.

    • startTokenIn: Token = tokenIn

      The original input token (used for recursion).

    • maxHops: number = 2

      The maximum number of hops to consider.

    Returns V2Route[]

    An array of V2Route objects representing all computed routes.

  • Generic function to find the best distribution based on a strategy (minimization or maximization).

    Parameters

    • s: number

      The total amount to distribute.

    • amounts: number[][]
    • comparator: Function

      A function to compare values (e.g., Math.max or Math.min).

    • initialValue: number

      The initial value (positive or negative infinity).

    Returns [number, number[]]

    • A tuple with the result (minimized or maximized) and the distribution array.
  • Finds the best route for a given exact input amount by comparing all possible routes from tokenIn to tokenOut. It selects the route with the best quote.

    Parameters

    • amountIn: CurrencyAmount

      The exact amount of the input token.

    • tokenOut: Token

      The output token for the trade.

    • routes: V2Route[]

      An array of potential routes to evaluate.

    • protocol: Protocol = Protocol.SOROSWAP

    Returns Promise<V2RouteWithValidQuote>

    A promise that resolves to the route with the best quote, or null if no suitable route is found.

  • Finds the best route for a given exact output amount by comparing all possible routes from tokenIn to tokenOut. It selects the route with the best quote suitable for the required output amount.

    Parameters

    • amountOut: CurrencyAmount

      The desired output amount.

    • tokenIn: Token

      The input token for the trade.

    • routes: V2Route[]

      An array of potential routes to evaluate.

    • protocol: Protocol = Protocol.SOROSWAP

    Returns Promise<null | {
        amount: CurrencyAmount;
        pairProvider: PairProvider;
        percent: number;
        quoteToken: Token;
        rawQuote: BigNumber;
        route: V2Route;
        tradeType: TradeType;
    }>

    A promise that resolves to the route with the best quote, or null if no suitable route is found.

  • Parameters

    • s: number
    • values: number[][]

    Returns [number, number[]]

  • Parameters

    • s: number
    • costs: number[][]

    Returns [number, number[]]

  • Retrieves all possible routes between a given input and output token pair by exploring all combinations of pairs provided by the PairProvider.

    Parameters

    • tokenIn: Token

      The input token for generating routes.

    • tokenOut: Token

      The output token for generating routes.

    • protocols: Protocol[]
    • Optional factoryAddress: string
    • Optional sorobanContext: SorobanContextType

    Returns Promise<V2Route[]>

    A promise that resolves to an array of V2Route objects representing all possible routes.

  • Retrieves all routes for swapping tokens based on the specified protocol.

    Parameters

    • tokenIn: Token

      The input token for the swap.

    • tokenOut: Token

      The output token for the swap.

    • protocol: Protocol

      The protocol to use for the swap.

    • Optional factoryAddress: string

      The address of the factory contract.

    • Optional sorobanContext: SorobanContextType

      The Soroban context type.

    Returns Promise<V2Route[]>

    A promise that resolves to the array of routes for swapping tokens.

  • Evaluates all provided routes with their corresponding quotes to determine the best quote based on the specified trade type (exact input or output).

    Parameters

    • routes: V2Route[]

      An array of potential routes to be evaluated.

    • quotesRaw: V2RouteWithQuotes[]

      Raw quote data for each route.

    • quoteToken: Token

      The token for which the quote is provided.

    • routeType: TradeType

      The type of trade, determining how to compare quotes.

    Returns Promise<null | {
        amount: CurrencyAmount;
        pairProvider: PairProvider;
        percent: number;
        quoteToken: Token;
        rawQuote: BigNumber;
        route: V2Route;
        tradeType: TradeType;
    }>

    The best quote found for the given trade type, or null if no suitable quote is found.

  • Returns void

  • This is the main method and calculates the optimal route for a trade given the amount, quote currency, and trade type. Returns the trade route and details if successful; otherwise returns null.

    Example:

    const route = await router.route(amountCurrency, quoteCurrency, tradeType);
    

    Parameters

    • amount: CurrencyAmount

      The amount for the trade.

    • quoteCurrency: Currency

      The currency to quote the trade in.

    • tradeType: TradeType

      The type of trade, either EXACT_INPUT or EXACT_OUTPUT.

    • Optional factoryAddress: string
    • Optional sorobanContext: SorobanContextType

    Returns Promise<null | BuildTradeReturn>

    The trade details including the route, or null if no route is found.

  • Finds the best route for an exact input amount given the input and output currencies and the input amount. Returns the trade details if successful.

    Example:

    if (tradeType === TradeType.EXACT_INPUT) {
    const route = await router.routeExactIn(amountCurrency, quoteCurrency, amount);
    }

    Parameters

    • currencyIn: Currency

      The input currency.

    • currencyOut: Currency

      The output currency.

    • amountIn: CurrencyAmount

      The exact input amount.

    • routes: V2Route[]
    • protocol: Protocol = Protocol.SOROSWAP

    Returns Promise<null | BuildTradeReturn>

    The trade details for the best route, or null if no route is found.

  • Finds the best route for an exact output amount given the input and output currencies and the output amount. Returns the trade details if successful.

    Example:

    if (tradeType === TradeType.EXACT_OUTPUT) {
    const route = await router.routeExactOut(amountCurrency, quoteCurrency, amount);
    }

    Parameters

    • currencyIn: Currency

      The input currency.

    • currencyOut: Currency

      The output currency.

    • amountOut: CurrencyAmount

      The exact output amount.

    • routes: V2Route[]
    • protocol: Protocol = Protocol.SOROSWAP

    Returns Promise<null | BuildTradeReturn>

    The trade details for the best route, or null if no route is found.

  • This method splits a given trade amount into multiple parts and determines the optimal distribution among different protocols.

    Parameters

    • amount: CurrencyAmount

      The total trade amount to be split.

    • quoteCurrency: Currency

      The currency to quote the trade in.

    • tradeType: TradeType

      The type of trade, either EXACT_INPUT or EXACT_OUTPUT.

    • parts: number = 10
    • Optional factoryAddress: string
    • Optional sorobanContext: SorobanContextType

    Returns Promise<{
        amountCurrency: CurrencyAmount;
        priceImpact: Percent;
        quoteCurrency: Currency;
        trade: {
            amountIn: string;
            amountInMax: string;
            amountOut: string;
            amountOutMin: string;
            distribution: {
                is_exact_in: boolean;
                parts: number;
                path: any;
                protocol_id: Protocol;
            }[];
            path: never[];
        };
        tradeType: TradeType;
    }>

    A promise that resolves to an object containing the total value of the split amounts and the distribution details.

    Example

    const result = await router.routeSplit(amountCurrency, quoteCurrency, TradeType.EXACT_INPUT);
    console.log(result.totalAmount); // Output: 150
    console.log(result.distribution);
    // Output:
    // [
    // { protocol: Protocol.SOROSWAP, amount: 100, path: ['0x...', '0x...', '0x...'] },
    // { protocol: Protocol.PHOENIX, amount: 50, path: ['0x...', '0x...', '0x...'] }
    // ]