CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-uniswap--router-sdk

SDK for routing swaps across Uniswap V2, V3, and V4 protocols with automatic route optimization and gas-efficient execution.

Pending
Overview
Eval results
Files

trade-management.mddocs/

Trade Management

Multi-protocol trade aggregation system supporting V2, V3, V4, and mixed routes. The Trade class provides price impact calculation, slippage protection, and execution optimization across different Uniswap protocols.

Capabilities

Trade Class

Generic trade class for aggregating trades across V2, V3, V4, and mixed routes with comprehensive trade analysis and optimization.

/**
 * Aggregated trade class supporting multiple Uniswap protocols
 */
class Trade<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType> {
  /** Array of routes that make up this trade */
  readonly routes: IRoute<TInput, TOutput, Pair | V3Pool | V4Pool>[];
  
  /** Type of trade - exact input or exact output */
  readonly tradeType: TTradeType;
  
  /** Individual swap details for each route */
  readonly swaps: {
    route: IRoute<TInput, TOutput, Pair | V3Pool | V4Pool>;
    inputAmount: CurrencyAmount<TInput>;
    outputAmount: CurrencyAmount<TOutput>;
  }[];
  
  /**
   * Create a trade from individual protocol routes
   * @param routes - Configuration containing v2, v3, v4, and mixed routes
   */
  constructor({
    v2Routes?: {
      routev2: V2RouteSDK<TInput, TOutput>;
      inputAmount: CurrencyAmount<TInput>;
      outputAmount: CurrencyAmount<TOutput>;
    }[];
    v3Routes?: {
      routev3: V3RouteSDK<TInput, TOutput>;
      inputAmount: CurrencyAmount<TInput>;
      outputAmount: CurrencyAmount<TOutput>;
    }[];
    v4Routes?: {
      routev4: V4RouteSDK<TInput, TOutput>;
      inputAmount: CurrencyAmount<TInput>;
      outputAmount: CurrencyAmount<TOutput>;
    }[];
    mixedRoutes?: {
      mixedRoute: MixedRouteSDK<TInput, TOutput>;
      inputAmount: CurrencyAmount<TInput>;
      outputAmount: CurrencyAmount<TOutput>;
    }[];
    tradeType: TTradeType;
  });
}

Trade Properties and Analysis

Comprehensive trade analysis including amounts, price impact, and execution details.

class Trade<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType> {
  /** Total input amount for the trade */
  get inputAmount(): CurrencyAmount<TInput>;
  
  /** Total output amount for the trade */
  get outputAmount(): CurrencyAmount<TOutput>;
  
  /** 
   * Detailed amount breakdown including native currency amounts
   * @returns inputAmount, outputAmount, and native amounts where applicable
   */
  get amounts(): {
    inputAmount: CurrencyAmount<TInput>;
    inputAmountNative: CurrencyAmount<TInput> | undefined;
    outputAmount: CurrencyAmount<TOutput>;
    outputAmountNative: CurrencyAmount<TOutput> | undefined;
  };
  
  /** Number of input wraps required if input is native ETH */
  get numberOfInputWraps(): number;
  
  /** Number of input unwraps required if input is WETH */
  get numberOfInputUnwraps(): number;
  
  /** Routes that use native ETH as input */
  get nativeInputRoutes(): IRoute<TInput, TOutput, Pair | V3Pool | V4Pool>[];
  
  /** Routes that use WETH as input */
  get wethInputRoutes(): IRoute<TInput, TOutput, Pair | V3Pool | V4Pool>[];
  
  /** The price expressed in terms of output amount/input amount */
  get executionPrice(): Price<TInput, TOutput>;
  
  /** Returns the sell tax of the input token */
  get inputTax(): Percent;
  
  /** Returns the buy tax of the output token */
  get outputTax(): Percent;
  
  /** 
   * Returns the percent difference between the route's mid price and the expected execution price
   * Excludes token taxes from the price impact calculation
   */
  get priceImpact(): Percent;
}

Slippage Protection

Methods for calculating minimum and maximum amounts with slippage protection.

class Trade<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType> {
  /**
   * Get the minimum amount that must be received from this trade for the given slippage tolerance
   * @param slippageTolerance - The tolerance of unfavorable slippage from the execution price
   * @param amountOut - Optional specific amount out to calculate minimum for
   * @returns The minimum amount out
   */
  minimumAmountOut(
    slippageTolerance: Percent, 
    amountOut?: CurrencyAmount<TOutput>
  ): CurrencyAmount<TOutput>;
  
  /**
   * Get the maximum amount in that can be spent via this trade for the given slippage tolerance
   * @param slippageTolerance - The tolerance of unfavorable slippage from the execution price
   * @param amountIn - Optional specific amount in to calculate maximum for
   * @returns The maximum amount in
   */
  maximumAmountIn(
    slippageTolerance: Percent, 
    amountIn?: CurrencyAmount<TInput>
  ): CurrencyAmount<TInput>;
  
  /**
   * Return the execution price after accounting for slippage tolerance
   * @param slippageTolerance - The allowed tolerated slippage
   * @returns The worst-case execution price
   */
  worstExecutionPrice(slippageTolerance: Percent): Price<TInput, TOutput>;
}

Static Factory Methods

Factory methods for creating trades from routes with automatic simulation.

class Trade<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType> {
  /**
   * Create a trade from multiple protocol routes with automatic quote simulation
   * @param v2Routes - Array of V2 routes with amounts
   * @param v3Routes - Array of V3 routes with amounts  
   * @param tradeType - Type of trade (exact input or exact output)
   * @param mixedRoutes - Optional array of mixed routes
   * @param v4Routes - Optional array of V4 routes
   * @returns Promise resolving to constructed Trade
   */
  static async fromRoutes<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(
    v2Routes: {
      routev2: V2RouteSDK<TInput, TOutput>;
      amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>;
    }[],
    v3Routes: {
      routev3: V3RouteSDK<TInput, TOutput>;
      amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>;
    }[],
    tradeType: TTradeType,
    mixedRoutes?: {
      mixedRoute: MixedRouteSDK<TInput, TOutput>;
      amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>;
    }[],
    v4Routes?: {
      routev4: V4RouteSDK<TInput, TOutput>;
      amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>;
    }[]
  ): Promise<Trade<TInput, TOutput, TTradeType>>;
  
  /**
   * Create a trade from a single route of any protocol
   * @param route - Single route (V2, V3, V4, or Mixed)
   * @param amount - Amount to trade
   * @param tradeType - Type of trade (exact input or exact output)
   * @returns Promise resolving to constructed Trade
   */
  static async fromRoute<TInput extends Currency, TOutput extends Currency, TTradeType extends TradeType>(
    route: V2RouteSDK<TInput, TOutput> | V3RouteSDK<TInput, TOutput> | V4RouteSDK<TInput, TOutput> | MixedRouteSDK<TInput, TOutput>,
    amount: TTradeType extends TradeType.EXACT_INPUT ? CurrencyAmount<TInput> : CurrencyAmount<TOutput>,
    tradeType: TTradeType
  ): Promise<Trade<TInput, TOutput, TTradeType>>;
}

Usage Examples:

import { Trade, Protocol } from "@uniswap/router-sdk";
import { CurrencyAmount, TradeType, Percent, Token } from "@uniswap/sdk-core";
import { Route as V3Route, Pool as V3Pool } from "@uniswap/v3-sdk";

// Create a multi-protocol trade
const trade = new Trade({
  v2Routes: [{
    routev2: v2Route,
    inputAmount: CurrencyAmount.fromRawAmount(tokenA, "1000000"),
    outputAmount: CurrencyAmount.fromRawAmount(tokenB, "2000000")
  }],
  v3Routes: [{
    routev3: v3Route,
    inputAmount: CurrencyAmount.fromRawAmount(tokenA, "500000"),
    outputAmount: CurrencyAmount.fromRawAmount(tokenB, "1100000")
  }],
  tradeType: TradeType.EXACT_INPUT
});

// Analyze the trade
console.log("Input amount:", trade.inputAmount.toExact());
console.log("Output amount:", trade.outputAmount.toExact());
console.log("Execution price:", trade.executionPrice.toSignificant(6));
console.log("Price impact:", trade.priceImpact.toFixed(2) + "%");

// Calculate slippage-protected amounts
const slippage = new Percent(50, 10000); // 0.5%
const minOut = trade.minimumAmountOut(slippage);
console.log("Minimum out with 0.5% slippage:", minOut.toExact());
// Create trade from routes with automatic simulation
const trade = await Trade.fromRoutes(
  [], // No V2 routes
  [{
    routev3: new V3Route([pool1, pool2], tokenA, tokenB),
    amount: CurrencyAmount.fromRawAmount(tokenA, "1000000")
  }],
  TradeType.EXACT_INPUT
);

// Check if this is a better trade than another
if (trade.outputAmount.greaterThan(otherTrade.outputAmount)) {
  console.log("This trade provides more output");
}
// Analyze native ETH wrapping requirements
if (trade.numberOfInputWraps > 0) {
  console.log(`Trade requires ${trade.numberOfInputWraps} ETH wraps`);
}

// Get detailed amounts including native portions
const { inputAmountNative, outputAmountNative } = trade.amounts;
if (inputAmountNative) {
  console.log("Native ETH input:", inputAmountNative.toExact());
}

Install with Tessl CLI

npx tessl i tessl/npm-uniswap--router-sdk

docs

approval-liquidity.md

index.md

mixed-routes.md

route-handling.md

swap-routing.md

trade-management.md

utilities.md

tile.json