(Fix) Error when using up to the max amount of decimals for token transfer (#1576)

This commit is contained in:
Fernando 2020-11-09 17:04:28 -03:00 committed by GitHub
parent 0c67c48648
commit 325adda00d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 10 deletions

View File

@ -203,4 +203,32 @@ describe('isERC721Contract', () => {
// then // then
expect(txValue).toEqual(expectedResult) expect(txValue).toEqual(expectedResult)
}) })
it('It should return the right conversion from token to unit with exceeding decimals', () => {
// given
const decimals = Number(18)
const expectedResult = '333333333333333398'
const VALUE = '0.33333333333333339878798333'
// when
const txValue = toTokenUnit(VALUE, decimals)
// then
expect(txValue).toEqual(expectedResult)
})
it('It should return the right conversion from token to unit with exact decimals', () => {
// given
const decimals = Number(18)
const expectedResult = '333333333333333399'
const VALUE = '0.333333333333333399'
// when
const txValue = toTokenUnit(VALUE, decimals)
// then
expect(txValue).toEqual(expectedResult)
})
}) })

View File

@ -7,13 +7,5 @@ export const humanReadableValue = (value: number | string, decimals = 18): strin
export const fromTokenUnit = (amount: number | string, decimals: string | number): string => export const fromTokenUnit = (amount: number | string, decimals: string | number): string =>
new BigNumber(amount).times(`1e-${decimals}`).toFixed() new BigNumber(amount).times(`1e-${decimals}`).toFixed()
export const toTokenUnit = (amount: number | string, decimals: string | number): string => { export const toTokenUnit = (amount: number | string, decimals: string | number): string =>
const amountBN = new BigNumber(amount).times(`1e${decimals}`) new BigNumber(amount).times(`1e${decimals}`).toFixed(0, BigNumber.ROUND_DOWN)
const [, amountDecimalPlaces] = amount.toString().split('.')
if (amountDecimalPlaces?.length >= +decimals) {
return amountBN.toFixed(+decimals, BigNumber.ROUND_DOWN)
}
return amountBN.toFixed()
}