Skip to content

Commit

Permalink
refactor for esm
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewlilley committed Dec 6, 2022
1 parent aecfd08 commit ccd68f9
Show file tree
Hide file tree
Showing 59 changed files with 4,638 additions and 1,084 deletions.
1 change: 1 addition & 0 deletions packages/route-processor/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('@sushiswap/eslint-config')
3 changes: 3 additions & 0 deletions packages/route-processor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# ...

...
55 changes: 55 additions & 0 deletions packages/route-processor/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
{
"name": "@sushiswap/route-processor",
"version": "0.0.0",
"private": true,
"description": "Sushi",
"license": "UNLICENSED",
"keywords": [
"sushi"
],
"homepage": "https://www.sushi.com",
"repository": {
"type": "git",
"url": "https://github.com/sushiswap/sushiswap.git",
"directory": "packages/route-processor"
},
"author": "Matthew Lilley <[email protected]>",
"main": "dist/index.js",
"module": "dist/index.mjs",
"source": "src/index.ts",
"typings": "dist/index.d.ts",
"files": [
"dist/**"
],
"scripts": {
"build": "tsup src --format esm,cjs --dts",
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist",
"dev": "tsup src --format esm,cjs --watch --dts",
"lint": "TIMING=1 eslint src --fix",
"prepublishOnly": "pnpm build",
"test": "jest --passWithNoTests"
},
"jest": {
"preset": "@sushiswap/jest-config/node"
},
"dependencies": {
"@ethersproject/solidity": "^5.7.0",
"@sushiswap/amm": "workspace:*",
"@sushiswap/chain": "workspace:*",
"@sushiswap/currency": "workspace:*",
"@sushiswap/tines": "workspace:*",
"@wagmi/core": "^0.7.9",
"ethers": "^5.7.0"
},
"devDependencies": {
"@sushiswap/eslint-config": "workspace:*",
"@sushiswap/jest-config": "workspace:*",
"@sushiswap/prettier-config": "workspace:*",
"@sushiswap/typescript-config": "workspace:*",
"@types/jest": "^29.2.0",
"eslint": "^8.20.0",
"jest": "^29.3.0",
"tsup": "6.5.0",
"typescript": "4.8.2"
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { ChainId } from '@sushiswap/chain'
import { Token } from '@sushiswap/currency'
import { ethers } from 'ethers'
import ethers from 'ethers'

import { Limited } from './Limited'
import { LiquidityProvider2, LiquidityProviders } from './liquidityProviders/LiquidityProvider2'
import { SushiProvider2 } from './liquidityProviders/Sushi2'
import { SushiProvider3 } from './liquidityProviders/Sushi3'
import { PoolCode } from './pools/PoolCode'


// Gathers pools info, creates routing in 'incremental' mode
// This means that new routing recalculates each time new pool fetching data comes
export class DataFetcher {
Expand All @@ -19,23 +18,20 @@ export class DataFetcher {
// Provider to poolAddress to PoolCode
poolCodes: Map<LiquidityProviders, Map<string, PoolCode>> = new Map()
stateId = 0

constructor(
chainDataProvider: ethers.providers.BaseProvider,
chainId: ChainId,
) {

constructor(chainDataProvider: ethers.providers.BaseProvider, chainId: ChainId) {
this.chainId = chainId
this.chainDataProvider = chainDataProvider
}

_providerIsIncluded(lp: LiquidityProviders, liquidity?: LiquidityProviders[]) {
if (!liquidity) return true
return liquidity.some(l => l == lp)
return liquidity.some((l) => l == lp)
}

// Starts pool data fetching
startDataFetching(
providers?: LiquidityProviders[] // all providers if undefined
providers?: LiquidityProviders[] // all providers if undefined
) {
this.stopDataFetching()
this.poolCodes = new Map()
Expand All @@ -44,21 +40,21 @@ export class DataFetcher {
if (this._providerIsIncluded(LiquidityProviders.Sushiswap, providers))
this.providers.push(new SushiProvider3(this.chainDataProvider, this.chainId, this.limited))

this.providers.forEach(p => p.startFetchPoolsData())
this.providers.forEach((p) => p.startFetchPoolsData())
}

// To stop fetch pool data
stopDataFetching() {
this.providers.forEach(p =>p.stopFetchPoolsData())
this.providers.forEach((p) => p.stopFetchPoolsData())
}

fetchPoolsForToken(t0: Token, t1: Token) {
this.providers.forEach(p =>p.fetchPoolsForToken(t0, t1))
this.providers.forEach((p) => p.fetchPoolsForToken(t0, t1))
}

getCurrentPoolCodeMap(providers?: LiquidityProviders[]): Map<string, PoolCode> {
const result:Map<string, PoolCode> = new Map()
this.providers.forEach(p => {
const result: Map<string, PoolCode> = new Map()
this.providers.forEach((p) => {
if (!this._providerIsIncluded(p.getType(), providers)) return
if (p.getCurrentPoolStateId() !== this.lastProviderStates.get(p.getType())) {
this.lastProviderStates.set(p.getType(), p.getCurrentPoolStateId())
Expand All @@ -68,11 +64,10 @@ export class DataFetcher {
pcMap = new Map()
this.poolCodes.set(p.getType(), pcMap)
}
poolCodes.forEach(pc => (pcMap as Map<string, PoolCode>).set(pc.pool.address, pc))
poolCodes.forEach((pc) => (pcMap as Map<string, PoolCode>).set(pc.pool.address, pc))
}
const pcMap = this.poolCodes.get(p.getType())
if (pcMap)
Array.from(pcMap.entries()).forEach(([addr, pc]) => result.set(addr, pc))
if (pcMap) Array.from(pcMap.entries()).forEach(([addr, pc]) => result.set(addr, pc))
})

return result
Expand All @@ -84,9 +79,8 @@ export class DataFetcher {
}

getCurrentPoolStateId() {
const currentStateId = this.providers.reduce((a, b) => a += b.getCurrentPoolStateId(), 0)
const currentStateId = this.providers.reduce((a, b) => (a += b.getCurrentPoolStateId()), 0)
this.stateId = currentStateId
return this.stateId
}

}
}
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { ChainId } from '@sushiswap/chain'
import { Token, WNATIVE } from '@sushiswap/currency'
import { BigintIsh } from '@sushiswap/math'
import { findMultiRouteExactIn, MultiRoute, NetworkInfo, RouteStatus, RToken } from '@sushiswap/tines'
import { BigNumber, BigNumberish, ethers } from 'ethers'
import { BigNumber, ethers } from 'ethers'

import { Limited } from './Limited'
import { LiquidityProvider } from './liquidityProviders/LiquidityProvider'
import { QuickSwapProvider } from './liquidityProviders/QuickSwap'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Token, WNATIVE } from '@sushiswap/currency'
import { findMultiRouteExactIn, MultiRoute, NetworkInfo, RouteStatus, RToken } from '@sushiswap/tines'
import { BigNumber } from 'ethers'

import { DataFetcher } from './DataFetcher'
import { LiquidityProviders } from './liquidityProviders/LiquidityProvider2'
import { convertTokenToBento, getBentoChainId } from './liquidityProviders/Trident'
Expand All @@ -13,112 +14,109 @@ export class Router {
amountIn: BigNumber
toToken: Token
gasPrice: number
providers?: LiquidityProviders[] // all providers if undefined
providers?: LiquidityProviders[] // all providers if undefined
minUpdateDelay: number

dataFetcherPreviousState = 0
routeCallBack?: RouteCallBack
currentBestRoute?: MultiRoute
timer?: any // timer from setInterval
timer?: any // timer from setInterval

constructor(
dataFetcher: DataFetcher,
fromToken: Token,
amountIn: BigNumber,
toToken: Token,
gasPrice: number,
providers?: LiquidityProviders[], // all providers if undefined
minUpdateDelay = 1000 // Minimal delay between routing update
providers?: LiquidityProviders[], // all providers if undefined
minUpdateDelay = 1000 // Minimal delay between routing update
) {
this.dataFetcher = dataFetcher
this.fromToken = fromToken
this.amountIn = amountIn
this.toToken = toToken
this.gasPrice = gasPrice
this.providers = providers,
this.minUpdateDelay = minUpdateDelay
;(this.providers = providers), (this.minUpdateDelay = minUpdateDelay)
}

startRouting(p: RouteCallBack) {
this.stopRouting()
this.routeCallBack = p
this.currentBestRoute = undefined
this.dataFetcherPreviousState = 0
this._checkRouteUpdate() // Maybe a route is ready
this._checkRouteUpdate() // Maybe a route is ready
this.timer = setInterval(() => this._checkRouteUpdate(), this.minUpdateDelay)
}

// To stop gather pool data and routing calculation
stopRouting() {
if (this.timer)
clearInterval(this.timer)
if (this.timer) clearInterval(this.timer)
this.timer = undefined
}

getBestRoute() {
return this.currentBestRoute
}

_checkRouteUpdate() {
_checkRouteUpdate() {
const currentDataFetcherStateId = this.dataFetcher.getCurrentPoolStateId()
if (this.dataFetcherPreviousState != currentDataFetcherStateId) {
this.dataFetcherPreviousState = currentDataFetcherStateId

const networks: NetworkInfo[] = [{
chainId: this.dataFetcher.chainId,
baseToken: WNATIVE[this.dataFetcher.chainId] as RToken,
gasPrice: this.gasPrice as number
}, {
chainId: getBentoChainId(this.dataFetcher.chainId),
baseToken: convertTokenToBento(WNATIVE[this.dataFetcher.chainId]),
gasPrice: this.gasPrice as number
}]


const networks: NetworkInfo[] = [
{
chainId: this.dataFetcher.chainId,
baseToken: WNATIVE[this.dataFetcher.chainId] as RToken,
gasPrice: this.gasPrice as number,
},
{
chainId: getBentoChainId(this.dataFetcher.chainId),
baseToken: convertTokenToBento(WNATIVE[this.dataFetcher.chainId]),
gasPrice: this.gasPrice as number,
},
]

const route = findMultiRouteExactIn(
this.fromToken as RToken,
this.toToken as RToken,
this.fromToken as RToken,
this.toToken as RToken,
this.amountIn,
this.dataFetcher.getCurrentPoolCodeList(this.providers).map(pc => pc.pool),
this.dataFetcher.getCurrentPoolCodeList(this.providers).map((pc) => pc.pool),
networks,
this.gasPrice
)

if (route.status != RouteStatus.NoWay) {
this.currentBestRoute = route
if (this.routeCallBack)
this.routeCallBack(route)
if (this.routeCallBack) this.routeCallBack(route)
}
}
}
}

changeRouteParams(
fromToken: Token,
amountIn: BigNumber,
toToken: Token,
gasPrice: number
) {
changeRouteParams(fromToken: Token, amountIn: BigNumber, toToken: Token, gasPrice: number) {
this.fromToken = fromToken
this.amountIn = amountIn
this.toToken = toToken
this.gasPrice = gasPrice
this._checkRouteUpdate() // Recalc route immediately
this._checkRouteUpdate() // Recalc route immediately
}

// Human-readable route printing
routeToString(route: MultiRoute, fromToken: Token, toToken: Token, shiftPrimary = '', shiftSub = ' '): string {
const poolCodesMap = this.dataFetcher.getCurrentPoolCodeMap()
let res = ''
res += shiftPrimary + 'Route Status: ' + route.status + '\n'
res += shiftPrimary + `Input: ${route.amountIn/Math.pow(10, fromToken.decimals)} ${fromToken.symbol}\n`
res += shiftPrimary + `Input: ${route.amountIn / Math.pow(10, fromToken.decimals)} ${fromToken.symbol}\n`
route.legs.forEach((l, i) => {
res += shiftSub + shiftSub +
`${i+1}. ${l.tokenFrom.name} ${Math.round(l.absolutePortion*100)}%`
+ ` -> [${poolCodesMap.get(l.poolAddress)?.poolName}] -> ${l.tokenTo.name}\n`
res +=
shiftSub +
shiftSub +
`${i + 1}. ${l.tokenFrom.name} ${Math.round(l.absolutePortion * 100)}%` +
` -> [${poolCodesMap.get(l.poolAddress)?.poolName}] -> ${l.tokenTo.name}\n`
//console.log(l.poolAddress, l.assumedAmountIn, l.assumedAmountOut)
})
const output = parseInt(route.amountOutBN.toString())/Math.pow(10, toToken.decimals)
const output = parseInt(route.amountOutBN.toString()) / Math.pow(10, toToken.decimals)
res += shiftPrimary + `Output: ${output} ${route.toToken.name}\n`

return res
}
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { ChainId } from '@sushiswap/chain'
import { Token, WNATIVE } from '@sushiswap/currency'
import { findMultiRouteExactIn, MultiRoute, NetworkInfo, RToken } from '@sushiswap/tines'
import { BigNumber, ethers } from 'ethers'

import { Limited } from './Limited'
import { QuickSwapProvider } from './liquidityProviders/QuickSwap'
import { SushiProvider } from './liquidityProviders/Sushi'
import { getRouteProcessorCode } from './TinesToRouteProcessor'
import { UniswapProvider } from './liquidityProviders/UniswapV2'
import { convertTokenToBento, getBentoChainId, TridentProvider } from './liquidityProviders/Trident'
import { Limited } from './Limited'
import { UniswapProvider } from './liquidityProviders/UniswapV2'
import { PoolCode } from './pools/PoolCode'
import { QuickSwapProvider } from './liquidityProviders/QuickSwap'
import { ChainId } from '@sushiswap/chain'
import { Token, WNATIVE } from '@sushiswap/currency'
import { getRouteProcessorCode } from './TinesToRouteProcessor'

export class Swapper {
routeProcessor: string
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { getBigNumber, MultiRoute, RouteLeg, RouteStatus, RToken } from '@sushiswap/tines'
import { BigNumber } from 'ethers'

import { HEXer } from './HEXer'
import { PoolCode } from './pools/PoolCode'

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { ethers } from 'ethers'
import { ChainId } from '@sushiswap/chain'
import { Token } from '@sushiswap/currency'
import ethers from 'ethers'

import { Limited } from '../Limited'
import { PoolCode } from '../pools/PoolCode'
import { Token } from '@sushiswap/currency'

export abstract class LiquidityProvider {
limited: Limited
Expand Down
Loading

0 comments on commit ccd68f9

Please sign in to comment.