import { BigNumber as OldBigNumber , bnum , ZERO } from '../utils/bignumber' ; import { getHighestLimitAmountsForPaths } from './helpersClass' ; import { formatSwaps , optimizeSwapAmounts } from './sorClass' ; import { NewPath , Swap , SwapTypes } from '../types' ; import { BigNumber , formatFixed } from '@ethersproject/bignumber' ; import { Zero } from '@ethersproject/constants' ; export const getBestPaths = ( paths , swapType , totalSwapAmount , inputDecimals , outputDecimals , maxPools , costReturnToken ) : [ Swap [ ] [ ] , OldBigNumber , OldBigNumber , OldBigNumber ] => { if ( paths . length == 0 || totalSwapAmount . isZero ( ) ) { return [ [ ] , ZERO , ZERO , ZERO ] ; } const highestLimitAmounts = getHighestLimitAmountsForPaths ( paths , maxPools ) ; const sumLimitAmounts = highestLimitAmounts . reduce ( ( r , pathLimit ) => { r . push ( pathLimit . add ( r [ r . length - 1 ] || Zero ) ) ; return r ; } , [ ] ) ; if ( totalSwapAmount . gt ( sumLimitAmounts [ sumLimitAmounts . length - 1 ] ) ) { return [ [ ] , ZERO , ZERO , ZERO ] ; } const initialNumPaths = sumLimitAmounts . findIndex ( ( cumulativeLimit ) => totalSwapAmount . lte ( cumulativeLimit ) ) + 1 ; const initialSwapAmounts = highestLimitAmounts . slice ( 0 , initialNumPaths ) ; const difference = sumLimitAmounts [ initialNumPaths - 1 ] . sub ( totalSwapAmount ) ; initialSwapAmounts [ initialSwapAmounts . length - 1 ] = initialSwapAmounts [ initialSwapAmounts . length - 1 ] . sub ( difference ) ; const [ bestPaths , bestSwapAmounts , bestTotalReturnConsideringFees ] = optimizeSwapAmounts ( paths , swapType , totalSwapAmount , initialSwapAmounts , highestLimitAmounts , inputDecimals , outputDecimals , initialNumPaths , maxPools , costReturnToken ) ; const [ swaps , bestTotalReturn , marketSp ] = formatSwaps ( bestPaths , swapType , bnum ( formatFixed ( totalSwapAmount , inputDecimals ) ) , bestSwapAmounts ) ; if ( bestTotalReturn . eq ( 0 ) ) return [ [ ] , ZERO , ZERO , ZERO ] ; return [ swaps , bestTotalReturn , marketSp , bestTotalReturnConsideringFees ] ; } ;