npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

uniswapv2-path-optimizer

v1.2.2

Published

Optimal swap path finder for UniswapV2-based AMM DEX model

Downloads

35

Readme

uniswapv2-path-optimizer

Optimal swap path finder for UniswapV2-based AMM DEX model

Installation

npm i uniswapv2-path-optimizer

Initialize

import Optimizer from "uniswapv2-path-optimizer";
const provider = new providers.JsonRpcProvider("RPC_NODE_URL");
const UniswapFactoryAddress = "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f";
const UniswapRouterAddress = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D";

const optimizer = new Optimizer({
    provider,
    factoryAddress: UniswapFactoryAddress,
    routerAddress: UniswapRouterAddress,
    feeBps: 30                  // optional, default 30 (0.3%)
    multicallAddress: "0x..."   // optional for some major chains
});

const WETH = "0x...";
const USDC = "0x...";
// and so on...

// method `optimizer.init` is async function to get token & pair info from blockchain.
// initiate for target tokens, 
// Each element of the array is address of ERC20 tokens
await optimizer.init([WETH, USDC, USDT, DAI, WBTC, BNB, UNI, SUSHI]);

Optimal Path for largest amountOut

const optimalResult = optimizer.getOptimalInPathOffChain({
    from: USDC,     // address of ERC20 token 
    to: WBTC,       // address of ERC20 token 
    amountIn: '1000000', 
    maxLength: 4
});

Optimal Path for smallest amountIn

const optimalResult = optimizer.getOptimalInPathOffChain({
    from: WBTC,     // address of ERC20 token 
    to: USDC,       // address of ERC20 token 
    amountOut: '1000000', 
    maxLength: 4
});

Refresh tokens & pairs

await optimizer.refresh();

Core Entities

UniswapV2PathOptimizer

functions for get tokens & pools

  • ready(): boolean
    Check fetching tokens/pools info process is finished.
  • tokens(): Token[]
    Returns array of all tokens
  • pools(): Pool[]
    Returns array of all pools(pairs)
  • getToken(id: number): Token get specific token by index of tokens array
  • getTokenByAddress(address: address): Token|undefined
    Get specific token by address
  • getTokenId(address: address): number
    Get token's array index
  • getPoolByTokenId(tokenAId: number, tokenBId: number): Pool
    Get specific pool by index of pools array
  • getPoolByAddress(tokenA: address, tokenB: address): Pool
    Get specific pool by pair tokens' addresses. It doesn't matter the order of the tokens is changed.

functions for setting

  • async init(tokens: address[]): Promise<void>
    fetch tokens & pools info from blockchain

  • async refresh()
    refresh pools' reserved amounts

  • setFee(tokenA: address, tokenB: address, newFeeBps: number)
    change the feeBps of pool

Calculate path on-chain

  • async getOutPathsOnChain(props: GetOutPathParams):Promise<AmountsOutResult[]>
    Calculate all possible paths of getAmountsOut function from onChain.
  • async getOptimalOutPathOnChain(props: GetOutPathParams):Promise<AmountsOutResult>
    Returns the path with the most optimal value among the results of the getOutPathsOnChain function.
  • async getInPathsOnChain(props: GetInPathParams):Promise<AmountsInResult[]>
    Calculate all possible paths of getAmountsIn function from onChain.
  • async getOptimalInPathOnChain(props: GetOptimalInPathParams):Promise<AmountsInResult>
    Returns the path with the most optimal value among the results of the getInPathsOnChain function.

Calculate path off-chain

  • getOutPathsOffChain(props: GetOutPathParams):AmountsOutResult[]
    Calculate all possible paths of getAmountsOut function from offChain(client-side).

  • getOptimalOutPathOffChain(props: GetOptimalOutPathParams):AmountsOutResult
    Returns the path with the most optimal value among the results of the getOutPathsOffChain function.

  • getInPathsOffChain(props: GetInPathParams):AmountsInResult[]
    Calculate all possible paths of getAmountsIn function from offChain(client-side).

  • getOptimalInPathOffChain(props: GetOptimalInPathParams):AmountsInResult
    Returns the path with the most optimal value among the results of the getInPathsOffChain function.

Basic calculator

  • quote(tokenInId: number, tokenOutId: number, amountIn: BigNumberish): BigNumber

  • getAmountOut(tokenAId: number, tokenBId: number, amountIn: BigNumberish, priceImpact?:boolean)
    priceImpact: boolean if false, calculates without considering the fee. default: true

  • getAmountIn(tokenAId: number, tokenBId: number, amountOut: BigNumberish, priceImpact?:boolean)
    priceImpact: boolean if false, calculates without considering the fee. default: true

  • getAmountsOut(amountIn: BigNumberish, path: number[], priceImpact?:boolean): BigNumber[]
    priceImpact: boolean if false, calculates without considering the fee. default: true

  • getAmountsIn(amountOut: BigNumberish, path: number[], priceImpact?:boolean): BigNumber[]
    priceImpact: boolean if false, calculates without considering the fee. default: true

PathResult

extended by AmountsInResult, AmountsOutResult

Properties

| property | type | |----------- |---------------------------------------- | | path | TokenWithAmount[] | | amountIn | BigNumber | | amountOut | BigNumber |

Methods

  • format(): String[]
    returns array of formatted strings from amounts in path tokens using tokens' own decimals.

  • formatWithoutPriceImpact(): String[]
    returns array of formatted strings from amountsWithoutPriceImpact in path tokens using tokens' own decimals.

  • priceImpactBps(): number
    returns price impact when swapping with path in basis point.
    ex) 1234 => 12.34% (0.1234)

  • amountInWithToken():TokenWithAmount
    returns amountIn amount with "from" token info.

  • amountOutWithToken():TokenWithAmount
    returns amountOut amount with "to" token info.

TokenWithAmount

Properties

| property | type | |-------------------------- |----------- | | address | string | | symbol | string | | decimals | number | | amount | BigNumber | | amountWithoutPriceImpact | BigNumber |

Methods

  • format(): string
    returns formatted string from amount using decimals.

  • formatWithoutPriceImpact(): string returns formatted string from amountWithoutPriceImpact using decimals.