Skip to content

Commit

Permalink
fix: convert BalancetoView format + write test
Browse files Browse the repository at this point in the history
  • Loading branch information
tiendn committed May 19, 2023
1 parent 4bd15a8 commit 5142c26
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 27 deletions.
44 changes: 44 additions & 0 deletions utils/__tests__/helper.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { expect, test } from '@jest/globals'
import { convertBalanceToView, getAmountFromBignumber } from 'utils/helper'

describe('helper.getAmountFromBignumber() fnc', () => {
test('with normal bignumber', () => {
expect(getAmountFromBignumber('1111111111111111111')).toBe('1.111111111111111111')
})
test('with decimal point (.)', () => {
expect(getAmountFromBignumber('1111111111111111111.1')).toBe('1.111111111111111111')
})
test('with very small bignumber', () => {
expect(getAmountFromBignumber('0.000000000000000001')).toBe('0.0')
})
test('with small bignumber (.)', () => {
expect(getAmountFromBignumber('0.000001')).toBe('0.0')
})
test('with small bignumber like 500100000000.000000000000000000', () => {
expect(getAmountFromBignumber('500100000000.000000000000000000')).toBe('0.0000005001')
})
test('with negative bignumber (.)', () => {
expect(getAmountFromBignumber('-1111111000000000000')).toBe('-1.111111')
})
test('with small negative bignumber (.)', () => {
expect(getAmountFromBignumber('-11111')).toBe('-0.000000000000011111')
})
test('with very small negative bignumber (.)', () => {
expect(getAmountFromBignumber('-0.0011111')).toBe('0.0')
})
})

describe('helper.convertBalanceToView() fnc', () => {
test('with bignumber', () => {
expect(convertBalanceToView('1000000000000000000')).toBe('1')
})
test('with bignumber and decimal point', () => {
expect(convertBalanceToView('1230000000000000000')).toBe('1.23000')
})
test('with small bignumber and decimal point', () => {
expect(convertBalanceToView('1230000000000')).toBe('0.00000')
})
test('with decimals = 0', () => {
expect(convertBalanceToView('1', '0')).toBe('1')
})
})
8 changes: 4 additions & 4 deletions utils/evm.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { formatUnits } from 'ethers/lib/utils'
import { TransactionRowProps } from 'views/transactions/TransactionRow'
import { ZERO_ADDRESS } from './constants'
import { isERC721 } from './helper'
import { convertBalanceToView } from './helper'

export const evmTransactionType = (type: number): string => {
if (type === 2) {
Expand All @@ -27,8 +26,9 @@ export const evmConvertTokenTransferToTransactionRow = (
const isBurn = item.toAddress === ZERO_ADDRESS
const labelStatus = (isCreate && 'Create') || (isMint && 'Mint') || (isBurn && 'Burn')

const isNft = isERC721(item.tokenType)
const value = isNft ? '1' : formatUnits(item.amount || '0', item.decimals)
// const isNft = isERC721(item.tokenType)
// const value = isNft ? '1' : formatUnits(item.amount || '0', item.decimals)
const value = convertBalanceToView(item.amount, item.decimals)

rows.push({
style: 'inject',
Expand Down
26 changes: 12 additions & 14 deletions utils/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,38 +30,38 @@ export const ellipseLeftText = (address: string, to: number) => {
return `${address.slice(-to)}...`
}

export const getValueFromWei = (wei: string) => {
if (parseFloat(wei) == 0) return 0
export const formatValueFromWei = (wei: string): string => {
if (parseFloat(wei) == 0) return '0'
if (parseFloat(wei) < CONFIG.APPROXIMATE_ZERO) return parseFloat(wei).toExponential()
return wei
}

export const getAmountFromBignumber = (value: number | string, decimals: string = '18') => {
export const getAmountFromBignumber = (value: number | string, decimals: string = '18'): string => {
if (!value) return '0'

if (!decimals) decimals = '1'
if (!decimals) decimals = '0'
const parsedDecimals = parseInt(decimals)

try {
const big = BigNumber.from(value)
const valueInWei = formatUnits(big, parsedDecimals).valueOf()
return getValueFromWei(valueInWei)
return valueInWei
} catch (err) {
// bignumber (ethers) error with 500100000000.000000000000000000
// bignumber.js caught this. but ethers not
// must convert value to decimal, sometimes round this value
return getValueFromWei(formatEther(BN(value).integerValue(BN.ROUND_DOWN).toString(10)))
return formatEther(BN(value).integerValue(BN.ROUND_DOWN).toString(10))
}
}

export const convertBalanceToView = (value: number | string, decimals = '18'): string => {
const amount = getAmountFromBignumber(value, decimals)
return numeral(amount).format('0,0.00000')
const amount = formatValueFromWei(getAmountFromBignumber(value, decimals))
return isInt(amount) ? numeral(amount).format('0,0') : numeral(amount).format('0,0.00000')
}

export const calculateGasFee = (gasUsed: string, gasPrice: string) => +gasUsed * +gasPrice
export const calculateAmountInVND = (asaAmount: number, asaPrice: string) => asaAmount * +asaPrice

export const calculateGasFee = (gasUsed: string, gasPrice: string): number => +gasUsed * +gasPrice
export const calculateAmountInVND = (asaAmount: number, asaPrice: string): number => asaAmount * +asaPrice
export const isInt = n => n % 1 === 0

/**
* return format text of date
Expand Down Expand Up @@ -197,9 +197,7 @@ export const capitalizeFirstLetter = (text: string) => {
return text.charAt(0).toUpperCase() + text.slice(1)
}

export const isERC721 = (type: string): boolean => {
return type === ErcTypeEnum.ERC721
}
export const isERC721 = (type: string): boolean => type === ErcTypeEnum.ERC721

export const getTransactionInOrOut = (
address: string = '',
Expand Down
2 changes: 1 addition & 1 deletion views/accounts/components/account/AccountVesting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const VestingView = ({
<TypographyUI.Balance
size="sm"
currency={`(${formatCurrencyValue(
calculateAmountInVND(getAmountFromBignumber(value), astraPrice),
calculateAmountInVND(parseFloat(getAmountFromBignumber(value)), astraPrice),
'VND'
)})`}
icon={<CryptoIcon name={process.env.NEXT_PUBLIC_NATIVE_TOKEN as CryptoIconNames} size="sm" />}
Expand Down
2 changes: 1 addition & 1 deletion views/tokens/TokenOverview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const TokenOverview = ({ token, tokenData }: Props) => {
tokenData.totalSupply
? isNFT
? tokenData.totalSupply
: convertBalanceToView(tokenData.totalSupply, tokenData.decimals || '1')
: convertBalanceToView(tokenData.totalSupply, tokenData.decimals)
: ''
}
fixNumber={5}
Expand Down
2 changes: 1 addition & 1 deletion views/tokens/TokenRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export default function TokenRow({ index, token }: Props) {

<div className={clsx(styles.borderLeft, styles.colTotalSupply, 'col padding-left-lg col-3')}>
<span className={clsx('money money-sm money-bold padding-right-xs')}>
{isNFT ? 1 : convertBalanceToView(token.totalSupply, token.decimals || '1')}
{convertBalanceToView(token.totalSupply, token.decimals)}
</span>
<span className={clsx(styles.currency, 'money money-sm money-bold')}>{token.symbol}</span>
</div>
Expand Down
5 changes: 4 additions & 1 deletion views/transactions/hook/useConvertData.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ export default function useConvertData({
if (data.result !== 'Error') {
internalTokenTransfers = internalTransactionRows
// filter tx
.filter((t: InternalTransactionItem) => t.callType === 'call' && getAmountFromBignumber(t.value) > 0)
.filter(
(t: InternalTransactionItem) =>
t.callType === 'call' && parseFloat(getAmountFromBignumber(t.value)) > 0
)
// Reformat value
.map((t: InternalTransactionItem) => ({
...t,
Expand Down
7 changes: 2 additions & 5 deletions views/transactions/hook/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@ import { astraToEth } from '@astradefi/address-converter'
import { ellipseBetweenText, formatNumber, IconEnum } from '@astraprotocol/astra-ui'
import { CardRowItem } from 'components/Card/CardInfo'
import { LabelTypes } from 'components/Typography/Label'
import { formatUnits } from 'ethers/lib/utils'
import { isArray, isBoolean, isEmpty, isNumber, isObject, isString } from 'lodash'
import { CONFIG } from 'utils/constants'
import { CardInfoLabels, TransactionCardTypeEnum } from 'utils/enum'
import { evmAddressName } from 'utils/evm'
import { formatCurrencyValue, LinkMaker } from 'utils/helper'
import { convertBalanceToView, formatCurrencyValue, LinkMaker } from 'utils/helper'

export const _cardData = (data: TransactionDetail, astraPrice: string) => {
const keys = Object.keys(data)
Expand Down Expand Up @@ -200,9 +199,7 @@ export const _cardData = (data: TransactionDetail, astraPrice: string) => {
transfer.toAddressName,
ellipseBetweenText(transfer.toAddress, 6, 6)
),
value: transfer.amount
? Number(formatUnits(transfer.amount, transfer.decimals || '1'))
: '',
value: transfer.amount ? convertBalanceToView(transfer.amount, transfer.decimals) : '',
tokenAddress: transfer.tokenContractAddress,
tokenSymbol: transfer.tokenSymbol,
tokenName: transfer.tokenName,
Expand Down

0 comments on commit 5142c26

Please sign in to comment.