Skip to content

Commit

Permalink
fix(amounts-display): increase precision for small amounts (#4793)
Browse files Browse the repository at this point in the history
* fix: increase precision for small amounts

* feat: add tiny and tiniest precisions

* chore: fix unittests
  • Loading branch information
alfetopito authored Sep 20, 2024
1 parent e4794db commit 4195c68
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
7 changes: 3 additions & 4 deletions libs/common-utils/src/amountFormat/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { USDC_GNOSIS_CHAIN, USDC_SEPOLIA, WETH_SEPOLIA } from '@cowprotocol/common-const'
import { CurrencyAmount, Percent } from '@uniswap/sdk-core'


import { formatAmountWithPrecision, formatFiatAmount, formatPercent, formatTokenAmount } from './index'

describe('Amounts formatting', () => {
Expand All @@ -19,7 +18,7 @@ describe('Amounts formatting', () => {
it('Extra small amount', () => {
const result = formatTokenAmount(getAmount('1', -decimals)) // 1e-18 WETH

expect(result).toBe('< 0.000001')
expect(result).toBe('0.000000000000000001')
})

it('Small amount', () => {
Expand Down Expand Up @@ -150,8 +149,8 @@ describe('Amounts formatting', () => {
CurrencyAmount.fromFractionalAmount(
USDC_GNOSIS_CHAIN,
'994582567877074269904770000000000000000000',
'999200146079960203000000000000000000'
)
'999200146079960203000000000000000000',
),
)

expect(result).toBe('1')
Expand Down
5 changes: 4 additions & 1 deletion libs/common-utils/src/amountFormat/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import JSBI from 'jsbi'
import { FractionUtils } from '../fractionUtils'
import { FractionLike, Nullish } from '../types'


const TINIEST = new Fraction(1, 100_000_000)
const TINY = new Fraction(1, 100_000)
const ONE = JSBI.BigInt(1)
const HUNDRED_K = JSBI.BigInt(100_000)
const MILLION = JSBI.BigInt(1_000_000)
Expand All @@ -14,6 +15,8 @@ const BILLION = JSBI.BigInt(1_000_000_000)
const TRILLION = JSBI.BigInt(1_000_000_000_000)

function getPrecisionForFraction(fraction: Fraction): number {
if (FractionUtils.lte(fraction, TINIEST)) return 18
if (FractionUtils.lte(fraction, TINY)) return 12
if (FractionUtils.lte(fraction, ONE)) return 6
if (FractionUtils.lte(fraction, HUNDRED_K)) return 4
if (FractionUtils.lte(fraction, MILLION)) return 3
Expand Down

0 comments on commit 4195c68

Please sign in to comment.