import { BigNumber } from '@ethersproject/bignumber' ; import { formatEther , parseEther } from '@ethersproject/units' ; import BigNumberJs from 'bignumber.js' ; import { DEFAULT_ASSET_DECIMAL } from '@config' ; import { StoreAsset } from '@types' ; import { bigify } from './bigify' ; import { fromTokenBase } from './units' ; export const convertToFiatFromAsset = ( asset , rate = 1 ) : string => { const splitRate = rate . toString ( ) . split ( '.' ) ; const decimals = splitRate . length > 1 ? splitRate [ 1 ] . length : 0 ; const rateDivisor = Math . pow ( 10 , decimals ) ; const rateBN = BigNumber . from ( Math . round ( rate * rateDivisor ) ) ; const convertedFloat = weiToFloat ( asset . balance . mul ( rateBN ) , asset . decimal ) ; return convertedFloat . dividedBy ( rateDivisor ) . toString ( ) ; } ; export const convertToFiat = ( userViewableBalance , rate = 1 ) : BigNumberJs => { return bigify ( userViewableBalance ) . multipliedBy ( bigify ( rate ) ) ; } ; export const convertToBN = ( asset ) : BigNumber => { const assetBN = parseEther ( asset . toString ( ) ) ; return assetBN ; } ; export const multiplyBNFloats = ( asset , rate ) : BigNumber => { const assetBN = bigify ( asset ) ; const rateBN = bigify ( rate ) ; return BigNumber . from ( parseEther ( trimBN ( assetBN . times ( rateBN ) . toFixed ( DEFAULT_ASSET_DECIMAL ) ) ) ) ; } ; export const divideBNFloats = ( asset , divisor ) : BigNumber => { const assetBN = bigify ( asset ) ; const divisorBN = bigify ( divisor ) ; return BigNumber . from ( parseEther ( trimBN ( assetBN . dividedBy ( divisorBN ) . toFixed ( DEFAULT_ASSET_DECIMAL ) ) ) ) ; } ; export const subtractBNFloats = ( asset , subtractor ) : BigNumber => { const assetBN = bigify ( asset ) ; const subtractorBN = bigify ( subtractor ) ; return BigNumber . from ( parseEther ( trimBN ( BigNumberJs . sum ( assetBN , subtractorBN . negated ( ) ) . toFixed ( DEFAULT_ASSET_DECIMAL ) ) ) ) ; } ; export const addBNFloats = ( asset , additor ) : BigNumber => { const assetBN = bigify ( asset ) ; const additorBN = bigify ( additor ) ; return BigNumber . from ( parseEther ( trimBN ( BigNumberJs . sum ( assetBN , additorBN ) . toFixed ( DEFAULT_ASSET_DECIMAL ) ) ) ) ; } ; export const trimBN = ( bigNumberString , numOfPlaces = DEFAULT_ASSET_DECIMAL ) : string => { if ( bigNumberString . length <= numOfPlaces ) return bigNumberString ; return bigNumberString . substr ( 0 , numOfPlaces ) ; } ; export const weiToFloat = ( wei , decimal ? ) : BigNumberJs => bigify ( fromTokenBase ( bigify ( wei ) , decimal ) ) ; export const withCommission = ( { amount , rate , subtract } ) : BigNumberJs => { const commission = subtract ? 1.0 - rate : 1.0 + rate ; const outputBN = multiplyBNFloats ( weiToFloat ( amount ) , commission ) ; return bigify ( trimBN ( formatEther ( outputBN ) ) ) ; } ;