From 86fc15907a20bcfa08900891853b3b2d1a5891f6 Mon Sep 17 00:00:00 2001 From: cartcrom <39385577+cartcrom@users.noreply.github.com> Date: Wed, 18 Oct 2023 14:34:37 -0400 Subject: [PATCH] refactor: consolidate percent formatting util (#7467) * refactor: consolidate percent formatting util * refactor: use generic percent formatter * fix: add descriptive comment for formatDelta --- .../AccountDrawer/AuthenticatedHeader.tsx | 4 +- .../MiniPortfolio/Tokens/index.tsx | 4 +- src/components/Charts/PriceChart/index.tsx | 4 +- .../CurrencyInputPanel/FiatValue.tsx | 4 +- src/components/NavBar/SuggestionRow.tsx | 4 +- .../Settings/MaxSlippageSettings/index.tsx | 18 ++-- src/components/Settings/MenuButton/index.tsx | 4 +- src/components/Tokens/TokenTable/TokenRow.tsx | 4 +- src/components/swap/PriceImpactModal.tsx | 4 +- src/components/swap/PriceImpactWarning.tsx | 4 +- src/components/swap/SwapLineItem.tsx | 15 +-- src/components/swap/SwapRoute.tsx | 4 +- .../SwapDetailsDropdown.test.tsx.snap | 2 +- .../__snapshots__/SwapLineItem.test.tsx.snap | 10 +- .../SwapModalFooter.test.tsx.snap | 2 +- src/pages/PoolDetails/PoolDetailsStats.tsx | 4 +- src/utils/formatNumbers.test.ts | 94 ++++++------------- src/utils/formatNumbers.ts | 46 +++------ 18 files changed, 91 insertions(+), 140 deletions(-) diff --git a/src/components/AccountDrawer/AuthenticatedHeader.tsx b/src/components/AccountDrawer/AuthenticatedHeader.tsx index db9c25f308..a43e7ddefd 100644 --- a/src/components/AccountDrawer/AuthenticatedHeader.tsx +++ b/src/components/AccountDrawer/AuthenticatedHeader.tsx @@ -161,7 +161,7 @@ export default function AuthenticatedHeader({ account, openSettings }: { account const clearCollectionFilters = useWalletCollections((state) => state.clearCollectionFilters) const isClaimAvailable = useIsNftClaimAvailable((state) => state.isClaimAvailable) const shouldShowBuyFiatButton = useIsNotOriginCountry('GB') - const { formatNumber, formatPercent } = useFormatter() + const { formatNumber, formatDelta } = useFormatter() const shouldDisableNFTRoutes = useDisableNFTRoutes() @@ -284,7 +284,7 @@ export default function AuthenticatedHeader({ account, openSettings }: { account {`${formatNumber({ input: Math.abs(absoluteChange as number), type: NumberType.PortfolioBalance, - })} (${formatPercent(percentChange)})`} + })} (${formatDelta(percentChange)})`} )} diff --git a/src/components/AccountDrawer/MiniPortfolio/Tokens/index.tsx b/src/components/AccountDrawer/MiniPortfolio/Tokens/index.tsx index 8423b07a5b..e512837d04 100644 --- a/src/components/AccountDrawer/MiniPortfolio/Tokens/index.tsx +++ b/src/components/AccountDrawer/MiniPortfolio/Tokens/index.tsx @@ -72,7 +72,7 @@ const TokenNameText = styled(ThemedText.SubHeader)` type PortfolioToken = NonNullable function TokenRow({ token, quantity, denominatedValue, tokenProjectMarket }: TokenBalance & { token: PortfolioToken }) { - const { formatPercent } = useFormatter() + const { formatDelta } = useFormatter() const percentChange = tokenProjectMarket?.pricePercentChange?.value ?? 0 const navigate = useNavigate() @@ -124,7 +124,7 @@ function TokenRow({ token, quantity, denominatedValue, tokenProjectMarket }: Tok - {formatPercent(percentChange)} + {formatDelta(percentChange)} ) diff --git a/src/components/Charts/PriceChart/index.tsx b/src/components/Charts/PriceChart/index.tsx index a8a72fd3c6..3562328dc8 100644 --- a/src/components/Charts/PriceChart/index.tsx +++ b/src/components/Charts/PriceChart/index.tsx @@ -52,11 +52,11 @@ interface ChartDeltaProps { function ChartDelta({ startingPrice, endingPrice, noColor }: ChartDeltaProps) { const delta = calculateDelta(startingPrice.value, endingPrice.value) - const { formatPercent } = useFormatter() + const { formatDelta } = useFormatter() return ( - {formatPercent(delta)} + {formatDelta(delta)} ) diff --git a/src/components/CurrencyInputPanel/FiatValue.tsx b/src/components/CurrencyInputPanel/FiatValue.tsx index 128d283b48..cf7a3bde54 100644 --- a/src/components/CurrencyInputPanel/FiatValue.tsx +++ b/src/components/CurrencyInputPanel/FiatValue.tsx @@ -22,7 +22,7 @@ export function FiatValue({ fiatValue: { data?: number; isLoading: boolean } priceImpact?: Percent }) { - const { formatNumber, formatPriceImpact } = useFormatter() + const { formatNumber, formatPercent } = useFormatter() const priceImpactColor = useMemo(() => { if (!priceImpact) return undefined @@ -54,7 +54,7 @@ export function FiatValue({ The estimated difference between the USD values of input and output amounts.} > - ({formatPriceImpact(priceImpact)}) + ({formatPercent(priceImpact.multiply(-1))}) )} diff --git a/src/components/NavBar/SuggestionRow.tsx b/src/components/NavBar/SuggestionRow.tsx index 61c15f2941..ed581a6f12 100644 --- a/src/components/NavBar/SuggestionRow.tsx +++ b/src/components/NavBar/SuggestionRow.tsx @@ -129,7 +129,7 @@ interface TokenRowProps { export const TokenRow = ({ token, isHovered, setHoveredIndex, toggleOpen, index, eventProperties }: TokenRowProps) => { const addRecentlySearchedAsset = useAddRecentlySearchedAsset() const navigate = useNavigate() - const { formatFiatPrice, formatPercent } = useFormatter() + const { formatFiatPrice, formatDelta } = useFormatter() const handleClick = useCallback(() => { const address = !token.address && token.standard === TokenStandard.Native ? 'NATIVE' : token.address @@ -194,7 +194,7 @@ export const TokenRow = ({ token, isHovered, setHoveredIndex, toggleOpen, index, - {formatPercent(Math.abs(token.market?.pricePercentChange?.value ?? 0))} + {formatDelta(Math.abs(token.market?.pricePercentChange?.value ?? 0))} diff --git a/src/components/Settings/MaxSlippageSettings/index.tsx b/src/components/Settings/MaxSlippageSettings/index.tsx index f65251befa..e9c8f9786b 100644 --- a/src/components/Settings/MaxSlippageSettings/index.tsx +++ b/src/components/Settings/MaxSlippageSettings/index.tsx @@ -38,23 +38,23 @@ const NUMBER_WITH_MAX_TWO_DECIMAL_PLACES = /^(?:\d*\.\d{0,2}|\d+)$/ const MINIMUM_RECOMMENDED_SLIPPAGE = new Percent(5, 10_000) const MAXIMUM_RECOMMENDED_SLIPPAGE = new Percent(1, 100) -function useFormatSlippageInput() { - const { formatSlippage } = useFormatter() +function useFormatPercentInput() { + const { formatPercent } = useFormatter() - return (slippage: Percent) => formatSlippage(slippage).slice(0, -1) // remove % sign + return (slippage: Percent) => formatPercent(slippage).slice(0, -1) // remove % sign } export default function MaxSlippageSettings({ autoSlippage }: { autoSlippage: Percent }) { const [userSlippageTolerance, setUserSlippageTolerance] = useUserSlippageTolerance() - const { formatSlippage } = useFormatter() - const formatSlippageInput = useFormatSlippageInput() + const { formatPercent } = useFormatter() + const formatPercentInput = useFormatPercentInput() // In order to trigger `custom` mode, we need to set `userSlippageTolerance` to a value that is not `auto`. // To do so, we use `autoSlippage` value. However, since users are likely to change that value, // we render it as a placeholder instead of a value. const defaultSlippageInputValue = userSlippageTolerance !== SlippageTolerance.Auto && !userSlippageTolerance.equalTo(autoSlippage) - ? formatSlippageInput(userSlippageTolerance) + ? formatPercentInput(userSlippageTolerance) : '' // If user has previously entered a custom slippage, we want to show that value in the input field @@ -124,7 +124,7 @@ export default function MaxSlippageSettings({ autoSlippage }: { autoSlippage: Pe {userSlippageTolerance === SlippageTolerance.Auto ? ( Auto ) : ( - formatSlippage(userSlippageTolerance) + formatPercent(userSlippageTolerance) )} } @@ -158,7 +158,7 @@ export default function MaxSlippageSettings({ autoSlippage }: { autoSlippage: Pe parseSlippageInput(e.target.value)} onBlur={() => { @@ -176,7 +176,7 @@ export default function MaxSlippageSettings({ autoSlippage }: { autoSlippage: Pe {tooLow ? ( - Slippage below {formatSlippage(MINIMUM_RECOMMENDED_SLIPPAGE)} may result in a failed transaction + Slippage below {formatPercent(MINIMUM_RECOMMENDED_SLIPPAGE)} may result in a failed transaction ) : ( Your transaction may be frontrun and result in an unfavorable trade. diff --git a/src/components/Settings/MenuButton/index.tsx b/src/components/Settings/MenuButton/index.tsx index 4a7a4c1726..f4b49eedaa 100644 --- a/src/components/Settings/MenuButton/index.tsx +++ b/src/components/Settings/MenuButton/index.tsx @@ -49,7 +49,7 @@ const IconContainerWithSlippage = styled(IconContainer)<{ displayWarning?: boole const ButtonContent = ({ trade }: { trade?: InterfaceTrade }) => { const [userSlippageTolerance] = useUserSlippageTolerance() - const { formatSlippage } = useFormatter() + const { formatPercent } = useFormatter() if (userSlippageTolerance === SlippageTolerance.Auto || isUniswapXTrade(trade)) { return ( @@ -64,7 +64,7 @@ const ButtonContent = ({ trade }: { trade?: InterfaceTrade }) => { return ( - {formatSlippage(userSlippageTolerance)} slippage + {formatPercent(userSlippageTolerance)} slippage diff --git a/src/components/Tokens/TokenTable/TokenRow.tsx b/src/components/Tokens/TokenTable/TokenRow.tsx index ee33e7b7b8..e7e80feff9 100644 --- a/src/components/Tokens/TokenTable/TokenRow.tsx +++ b/src/components/Tokens/TokenTable/TokenRow.tsx @@ -442,7 +442,7 @@ interface LoadedRowProps { /* Loaded State: row component with token information */ export const LoadedRow = forwardRef((props: LoadedRowProps, ref: ForwardedRef) => { - const { formatFiatPrice, formatNumber, formatPercent } = useFormatter() + const { formatFiatPrice, formatNumber, formatDelta } = useFormatter() const { tokenListIndex, tokenListLength, token, sortRank } = props const filterString = useAtomValue(filterStringAtom) @@ -451,7 +451,7 @@ export const LoadedRow = forwardRef((props: LoadedRowProps, ref: ForwardedRef @@ -56,7 +56,7 @@ export default function PriceImpactModal({ priceImpact, onDismiss, onContinue }: This transaction will result in a{' '} - {formatPriceImpact(priceImpact)} + ~{formatPercent(priceImpact)} {' '} price impact on the market price of this pool. Do you wish to continue? diff --git a/src/components/swap/PriceImpactWarning.tsx b/src/components/swap/PriceImpactWarning.tsx index 1cfb2e03a1..26fd2f5fb0 100644 --- a/src/components/swap/PriceImpactWarning.tsx +++ b/src/components/swap/PriceImpactWarning.tsx @@ -20,7 +20,7 @@ interface PriceImpactWarningProps { } export default function PriceImpactWarning({ priceImpact }: PriceImpactWarningProps) { - const { formatPriceImpact } = useFormatter() + const { formatPercent } = useFormatter() const theme = useTheme() return ( @@ -41,7 +41,7 @@ export default function PriceImpactWarning({ priceImpact }: PriceImpactWarningPr - {formatPriceImpact(priceImpact)} + ~{formatPercent(priceImpact)} diff --git a/src/components/swap/SwapLineItem.tsx b/src/components/swap/SwapLineItem.tsx index 92bf5397fc..d3f7571fe3 100644 --- a/src/components/swap/SwapLineItem.tsx +++ b/src/components/swap/SwapLineItem.tsx @@ -103,9 +103,10 @@ function Loading({ width = 50 }: { width?: number }) { return } -function ColoredPercentRow({ percent }: { percent: Percent }) { - const { formatSlippage } = useFormatter() - return {formatSlippage(percent)} +function ColoredPercentRow({ percent, estimate }: { percent: Percent; estimate?: boolean }) { + const { formatPercent } = useFormatter() + const formattedPercent = (estimate ? '~' : '') + formatPercent(percent) + return {formattedPercent} } function CurrencyAmountRow({ amount }: { amount: CurrencyAmount }) { @@ -136,7 +137,7 @@ type LineItemData = { function useLineItem(props: SwapLineItemProps): LineItemData | undefined { const { trade, syncing, allowedSlippage, type } = props - const { formatNumber, formatSlippage } = useFormatter() + const { formatNumber, formatPercent } = useFormatter() const isAutoSlippage = useUserSlippageTolerance()[0] === SlippageTolerance.Auto const feesEnabled = useFeesEnabled() @@ -179,7 +180,7 @@ function useLineItem(props: SwapLineItemProps): LineItemData | undefined { return { Label: () => Price impact, TooltipBody: () => The impact your trade has on the market price of this pool., - Value: () => (isPreview ? : ), + Value: () => (isPreview ? : ), } case SwapLineItemType.MAX_SLIPPAGE: return { @@ -187,7 +188,7 @@ function useLineItem(props: SwapLineItemProps): LineItemData | undefined { TooltipBody: () => , Value: () => ( - {isAutoSlippage && } {formatSlippage(allowedSlippage)} + {isAutoSlippage && } {formatPercent(allowedSlippage)} ), } @@ -197,7 +198,7 @@ function useLineItem(props: SwapLineItemProps): LineItemData | undefined { return { Label: () => ( <> - Fee {trade.swapFee && `(${formatSlippage(trade.swapFee.percent)})`} + Fee {trade.swapFee && `(${formatPercent(trade.swapFee.percent)})`} ), TooltipBody: () => , diff --git a/src/components/swap/SwapRoute.tsx b/src/components/swap/SwapRoute.tsx index 9fbebb663b..38825bf8d7 100644 --- a/src/components/swap/SwapRoute.tsx +++ b/src/components/swap/SwapRoute.tsx @@ -32,12 +32,12 @@ function RouteLabel({ trade }: { trade: SubmittableTrade }) { } function PriceImpactRow({ trade }: { trade: ClassicTrade }) { - const { formatPriceImpact } = useFormatter() + const { formatPercent } = useFormatter() return ( Price Impact -
{formatPriceImpact(trade.priceImpact)}
+
{formatPercent(trade.priceImpact)}
) diff --git a/src/components/swap/__snapshots__/SwapDetailsDropdown.test.tsx.snap b/src/components/swap/__snapshots__/SwapDetailsDropdown.test.tsx.snap index eeedc6b508..19dea1fe1f 100644 --- a/src/components/swap/__snapshots__/SwapDetailsDropdown.test.tsx.snap +++ b/src/components/swap/__snapshots__/SwapDetailsDropdown.test.tsx.snap @@ -347,7 +347,7 @@ exports[`SwapDetailsDropdown.tsx renders a trade 1`] = ` - -105566.373% + ~-105566.373% diff --git a/src/components/swap/__snapshots__/SwapLineItem.test.tsx.snap b/src/components/swap/__snapshots__/SwapLineItem.test.tsx.snap index cc60fbf351..0ac8eae691 100644 --- a/src/components/swap/__snapshots__/SwapLineItem.test.tsx.snap +++ b/src/components/swap/__snapshots__/SwapLineItem.test.tsx.snap @@ -1661,7 +1661,7 @@ exports[`SwapLineItem.tsx exact input 1`] = ` - -105566.373% + ~-105566.373% @@ -3328,7 +3328,7 @@ exports[`SwapLineItem.tsx exact input api 1`] = ` - -105566.373% + ~-105566.373% @@ -4995,7 +4995,7 @@ exports[`SwapLineItem.tsx exact output 1`] = ` - -105566.373% + ~-105566.373% @@ -6870,7 +6870,7 @@ exports[`SwapLineItem.tsx fee on buy 1`] = ` - -105566.373% + ~-105566.373% @@ -8745,7 +8745,7 @@ exports[`SwapLineItem.tsx fee on sell 1`] = ` - -105566.373% + ~-105566.373% diff --git a/src/components/swap/__snapshots__/SwapModalFooter.test.tsx.snap b/src/components/swap/__snapshots__/SwapModalFooter.test.tsx.snap index 3fff80cb44..922a085afd 100644 --- a/src/components/swap/__snapshots__/SwapModalFooter.test.tsx.snap +++ b/src/components/swap/__snapshots__/SwapModalFooter.test.tsx.snap @@ -287,7 +287,7 @@ exports[`SwapModalFooter.tsx matches base snapshot, test trade exact input 1`] = - -105566.373% + ~-105566.373% diff --git a/src/pages/PoolDetails/PoolDetailsStats.tsx b/src/pages/PoolDetails/PoolDetailsStats.tsx index a72ebf15a2..cbf58f9c5a 100644 --- a/src/pages/PoolDetails/PoolDetailsStats.tsx +++ b/src/pages/PoolDetails/PoolDetailsStats.tsx @@ -204,7 +204,7 @@ const StatItemText = styled(Text)` ` function StatItem({ title, value, delta }: { title: ReactNode; value: number; delta?: number }) { - const { formatNumber, formatPercent } = useFormatter() + const { formatNumber, formatDelta } = useFormatter() return ( @@ -219,7 +219,7 @@ function StatItem({ title, value, delta }: { title: ReactNode; value: number; de {!!delta && ( - {formatPercent(delta)} + {formatDelta(delta)} )} diff --git a/src/utils/formatNumbers.test.ts b/src/utils/formatNumbers.test.ts index ed281d0a22..e36003ac00 100644 --- a/src/utils/formatNumbers.test.ts +++ b/src/utils/formatNumbers.test.ts @@ -356,71 +356,37 @@ describe('formatUSDPrice', () => { }) }) -describe('formatPriceImpact', () => { +describe('formatPercent', () => { beforeEach(() => { mocked(useLocalCurrencyConversionRate).mockReturnValue({ data: 1.0, isLoading: false }) mocked(useCurrencyConversionFlagEnabled).mockReturnValue(true) }) it('should correctly format undefined', () => { - const { formatPriceImpact } = renderHook(() => useFormatter()).result.current + const { formatPercent } = renderHook(() => useFormatter()).result.current - expect(formatPriceImpact(undefined)).toBe('-') - }) - - it('correctly formats a percent with 3 significant digits', () => { - const { formatPriceImpact } = renderHook(() => useFormatter()).result.current - - expect(formatPriceImpact(new Percent(-1, 100000))).toBe('0.001%') - expect(formatPriceImpact(new Percent(-1, 1000))).toBe('0.100%') - expect(formatPriceImpact(new Percent(-1, 100))).toBe('1.000%') - expect(formatPriceImpact(new Percent(-1, 10))).toBe('10.000%') - expect(formatPriceImpact(new Percent(-1, 1))).toBe('100.000%') - }) - - it('correctly formats a percent with 3 significant digits with french locale', () => { - mocked(useActiveLocale).mockReturnValue('fr-FR') - const { formatPriceImpact } = renderHook(() => useFormatter()).result.current - - expect(formatPriceImpact(new Percent(-1, 100000))).toBe('0,001%') - expect(formatPriceImpact(new Percent(-1, 1000))).toBe('0,100%') - expect(formatPriceImpact(new Percent(-1, 100))).toBe('1,000%') - expect(formatPriceImpact(new Percent(-1, 10))).toBe('10,000%') - expect(formatPriceImpact(new Percent(-1, 1))).toBe('100,000%') - }) -}) - -describe('formatSlippage', () => { - beforeEach(() => { - mocked(useLocalCurrencyConversionRate).mockReturnValue({ data: 1.0, isLoading: false }) - mocked(useCurrencyConversionFlagEnabled).mockReturnValue(true) - }) - - it('should correctly format undefined', () => { - const { formatSlippage } = renderHook(() => useFormatter()).result.current - - expect(formatSlippage(undefined)).toBe('-') + expect(formatPercent(undefined)).toBe('-') }) it('correctly formats a percent with no trailing digits', () => { - const { formatSlippage } = renderHook(() => useFormatter()).result.current + const { formatPercent } = renderHook(() => useFormatter()).result.current - expect(formatSlippage(new Percent(1, 100000))).toBe('0.001%') - expect(formatSlippage(new Percent(1, 1000))).toBe('0.1%') - expect(formatSlippage(new Percent(1, 100))).toBe('1%') - expect(formatSlippage(new Percent(1, 10))).toBe('10%') - expect(formatSlippage(new Percent(1, 1))).toBe('100%') + expect(formatPercent(new Percent(1, 100000))).toBe('0.001%') + expect(formatPercent(new Percent(1, 1000))).toBe('0.1%') + expect(formatPercent(new Percent(1, 100))).toBe('1%') + expect(formatPercent(new Percent(1, 10))).toBe('10%') + expect(formatPercent(new Percent(1, 1))).toBe('100%') }) it('correctly formats a percent with french locale', () => { mocked(useActiveLocale).mockReturnValue('fr-FR') - const { formatSlippage } = renderHook(() => useFormatter()).result.current + const { formatPercent } = renderHook(() => useFormatter()).result.current - expect(formatSlippage(new Percent(1, 100000))).toBe('0,001%') - expect(formatSlippage(new Percent(1, 1000))).toBe('0,1%') - expect(formatSlippage(new Percent(1, 100))).toBe('1%') - expect(formatSlippage(new Percent(1, 10))).toBe('10%') - expect(formatSlippage(new Percent(1, 1))).toBe('100%') + expect(formatPercent(new Percent(1, 100000))).toBe('0,001%') + expect(formatPercent(new Percent(1, 1000))).toBe('0,1%') + expect(formatPercent(new Percent(1, 100))).toBe('1%') + expect(formatPercent(new Percent(1, 10))).toBe('10%') + expect(formatPercent(new Percent(1, 1))).toBe('100%') }) }) @@ -461,36 +427,36 @@ describe('formatReviewSwapCurrencyAmount', () => { }) }) -describe('formatPercent', () => { +describe('formatDelta', () => { beforeEach(() => { mocked(useLocalCurrencyConversionRate).mockReturnValue({ data: 1.0, isLoading: false }) mocked(useCurrencyConversionFlagEnabled).mockReturnValue(true) }) it.each([[null], [undefined], [Infinity], [NaN]])('should correctly format %p', (value) => { - const { formatPercent } = renderHook(() => useFormatter()).result.current + const { formatDelta } = renderHook(() => useFormatter()).result.current - expect(formatPercent(value)).toBe('-') + expect(formatDelta(value)).toBe('-') }) it('correctly formats a percent with 2 decimal places', () => { - const { formatPercent } = renderHook(() => useFormatter()).result.current + const { formatDelta } = renderHook(() => useFormatter()).result.current - expect(formatPercent(0)).toBe('0.00%') - expect(formatPercent(0.1)).toBe('0.10%') - expect(formatPercent(1)).toBe('1.00%') - expect(formatPercent(10)).toBe('10.00%') - expect(formatPercent(100)).toBe('100.00%') + expect(formatDelta(0)).toBe('0.00%') + expect(formatDelta(0.1)).toBe('0.10%') + expect(formatDelta(1)).toBe('1.00%') + expect(formatDelta(10)).toBe('10.00%') + expect(formatDelta(100)).toBe('100.00%') }) it('correctly formats a percent with 2 decimal places in french locale', () => { mocked(useActiveLocale).mockReturnValue('fr-FR') - const { formatPercent } = renderHook(() => useFormatter()).result.current + const { formatDelta } = renderHook(() => useFormatter()).result.current - expect(formatPercent(0)).toBe('0,00%') - expect(formatPercent(0.1)).toBe('0,10%') - expect(formatPercent(1)).toBe('1,00%') - expect(formatPercent(10)).toBe('10,00%') - expect(formatPercent(100)).toBe('100,00%') + expect(formatDelta(0)).toBe('0,00%') + expect(formatDelta(0.1)).toBe('0,10%') + expect(formatDelta(1)).toBe('1,00%') + expect(formatDelta(10)).toBe('10,00%') + expect(formatDelta(100)).toBe('100,00%') }) }) diff --git a/src/utils/formatNumbers.ts b/src/utils/formatNumbers.ts index 33644aed42..f3bc8656dc 100644 --- a/src/utils/formatNumbers.ts +++ b/src/utils/formatNumbers.ts @@ -466,31 +466,22 @@ function formatCurrencyAmount({ }) } -function formatPriceImpact(priceImpact: Percent | undefined, locale: SupportedLocale = DEFAULT_LOCALE): string { - if (!priceImpact) return '-' +function formatPercent(percent: Percent | undefined, locale: SupportedLocale = DEFAULT_LOCALE) { + if (!percent) return '-' - return `${Number(priceImpact.multiply(-1).toFixed(3)).toLocaleString(locale, { - minimumFractionDigits: 3, + return `${Number(percent.toFixed(3)).toLocaleString(locale, { maximumFractionDigits: 3, useGrouping: false, })}%` } -function formatSlippage(slippage: Percent | undefined, locale: SupportedLocale = DEFAULT_LOCALE) { - if (!slippage) return '-' - - return `${Number(slippage.toFixed(3)).toLocaleString(locale, { - maximumFractionDigits: 3, - useGrouping: false, - })}%` -} - -function formatPercent(percent: Nullish, locale: SupportedLocale = DEFAULT_LOCALE) { - if (percent === null || percent === undefined || percent === Infinity || isNaN(percent)) { +// Used to format floats representing percent change with fixed decimal places +function formatDelta(delta: Nullish, locale: SupportedLocale = DEFAULT_LOCALE) { + if (delta === null || delta === undefined || delta === Infinity || isNaN(delta)) { return '-' } - return `${Number(Math.abs(percent).toFixed(2)).toLocaleString(locale, { + return `${Number(Math.abs(delta).toFixed(2)).toLocaleString(locale, { minimumFractionDigits: 2, maximumFractionDigits: 2, useGrouping: false, @@ -694,21 +685,11 @@ export function useFormatter() { [currencyToFormatWith, formatterLocale, localCurrencyConversionRateToFormatWith] ) - const formatPriceImpactWithLocales = useCallback( - (priceImpact: Percent | undefined) => formatPriceImpact(priceImpact, formatterLocale), - [formatterLocale] - ) - const formatReviewSwapCurrencyAmountWithLocales = useCallback( (amount: CurrencyAmount) => formatReviewSwapCurrencyAmount(amount, formatterLocale), [formatterLocale] ) - const formatSlippageWithLocales = useCallback( - (slippage: Percent | undefined) => formatSlippage(slippage, formatterLocale), - [formatterLocale] - ) - const formatTickPriceWithLocales = useCallback( (options: Omit) => formatTickPrice({ @@ -742,8 +723,13 @@ export function useFormatter() { [currencyToFormatWith, formatterLocale, localCurrencyConversionRateToFormatWith] ) + const formatDeltaWithLocales = useCallback( + (percent: Nullish) => formatDelta(percent, formatterLocale), + [formatterLocale] + ) + const formatPercentWithLocales = useCallback( - (percent: Nullish) => formatPercent(percent, formatterLocale), + (percent: Percent | undefined) => formatPercent(percent, formatterLocale), [formatterLocale] ) @@ -753,11 +739,10 @@ export function useFormatter() { formatFiatPrice: formatFiatPriceWithLocales, formatNumber: formatNumberWithLocales, formatNumberOrString: formatNumberOrStringWithLocales, + formatDelta: formatDeltaWithLocales, formatPercent: formatPercentWithLocales, formatPrice: formatPriceWithLocales, - formatPriceImpact: formatPriceImpactWithLocales, formatReviewSwapCurrencyAmount: formatReviewSwapCurrencyAmountWithLocales, - formatSlippage: formatSlippageWithLocales, formatTickPrice: formatTickPriceWithLocales, }), [ @@ -765,11 +750,10 @@ export function useFormatter() { formatFiatPriceWithLocales, formatNumberOrStringWithLocales, formatNumberWithLocales, + formatDeltaWithLocales, formatPercentWithLocales, - formatPriceImpactWithLocales, formatPriceWithLocales, formatReviewSwapCurrencyAmountWithLocales, - formatSlippageWithLocales, formatTickPriceWithLocales, ] )