import { BigNumber } from '@ethersproject/bignumber' ; import cloneDeep from 'lodash.clonedeep' ; import { bnum , scale } from './utils/bignumber' ; import { EMPTY_SWAPINFO } from './constants' ; import { SwapTypes , SwapV2 , Swap , SwapInfo } from './types' ; import { Zero } from '@ethersproject/constants' ; returns const getTokenAddresses = ( swaps ) : string [ ] => { const tokenAddressesSet = new Set ( swaps . flatMap ( ( sequence ) => sequence . flatMap ( ( swap ) : [ string , string ] => [ swap . tokenIn , swap . tokenOut , ] ) ) ) ; return [ ... tokenAddressesSet ] ; } ; dev returns const getTotalSwapAmount = ( swaps ) => { return swaps . reduce ( ( acc , { amount } ) => acc . add ( amount ) , Zero ) ; } ; dev param swapKind param sequence param tokenAddresses returns const formatSequence = ( swapKind , sequence , tokenAddresses ) : SwapV2 [ ] => { if ( swapKind === SwapTypes . SwapExactOut ) { sequence = sequence . reverse ( ) ; } return sequence . map ( ( swap , i ) => { let amountScaled = '0' ; if ( i === 0 ) { const scalingFactor = swapKind === SwapTypes . SwapExactIn ? swap . tokenInDecimals : swap . tokenOutDecimals ; amountScaled = scale ( bnum ( swap . swapAmount as string ) , scalingFactor ) . decimalPlaces ( 0 , 1 ) . toString ( ) ; } const assetInIndex = tokenAddresses . indexOf ( swap . tokenIn ) ; const assetOutIndex = tokenAddresses . indexOf ( swap . tokenOut ) ; return { poolId : swap . pool , assetInIndex , assetOutIndex , amount : amountScaled , userData : '0x' , } ; } ) ; } ; export function formatSwaps ( swapsOriginal , swapType , swapAmount , tokenIn , tokenOut , returnAmount , returnAmountConsideringFees , marketSp ) { if ( swapsOriginal . length === 0 ) { return cloneDeep ( EMPTY_SWAPINFO ) ; } const swapsClone = cloneDeep ( swapsOriginal ) ; const tokenAddresses = getTokenAddresses ( swapsClone ) ; const swaps = swapsClone . flatMap ( ( sequence ) => formatSequence ( swapType , sequence , tokenAddresses ) ) ; const dust = swapAmount . sub ( getTotalSwapAmount ( swaps ) ) ; if ( dust . gt ( 0 ) ) { swaps [ 0 ] . amount = BigNumber . from ( swaps [ 0 ] . amount ) . add ( dust ) . toString ( ) ; } const swapInfo = { swapAmount , returnAmount , returnAmountConsideringFees , swaps , tokenAddresses , tokenIn , tokenOut , marketSp , } ; return swapInfo ; }