-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
fix: cp-8.3.0 convert pay-flow token amounts to USD instead of relabeling #33321
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
282 changes: 282 additions & 0 deletions
282
app/components/Views/confirmations/hooks/pay/useAssetFiatFormatter.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,282 @@ | ||
| import { renderHook } from '@testing-library/react-hooks'; | ||
| import { useSelector } from 'react-redux'; | ||
|
|
||
| import { useAssetFiatFormatter } from './useAssetFiatFormatter'; | ||
| import { useTransactionPayCurrency } from './useTransactionPayCurrency'; | ||
| import { | ||
| selectCurrencyRates, | ||
| selectCurrentCurrency, | ||
| } from '../../../../../selectors/currencyRateController'; | ||
| import { selectEvmNetworkConfigurationsByChainId } from '../../../../../selectors/networkController'; | ||
| import { getIntlNumberFormatter } from '../../../../../util/intl'; | ||
|
|
||
| jest.mock('react-redux', () => ({ | ||
| useSelector: jest.fn(), | ||
| })); | ||
|
|
||
| jest.mock('./useTransactionPayCurrency', () => ({ | ||
| useTransactionPayCurrency: jest.fn(), | ||
| })); | ||
|
|
||
| jest.mock('../../../../../selectors/currencyRateController', () => ({ | ||
| selectCurrentCurrency: jest.fn(), | ||
| selectCurrencyRates: jest.fn(), | ||
| })); | ||
|
|
||
| jest.mock('../../../../../selectors/networkController', () => ({ | ||
| selectEvmNetworkConfigurationsByChainId: jest.fn(), | ||
| })); | ||
|
|
||
| jest.mock('../../../../../util/intl', () => ({ | ||
| getIntlNumberFormatter: jest.fn(), | ||
| })); | ||
|
|
||
| jest.mock('../../../../../../locales/i18n', () => ({ | ||
| locale: 'en-US', | ||
| strings: jest.fn((key: string) => key), | ||
| })); | ||
|
|
||
| const mockUseSelector = jest.mocked(useSelector); | ||
| const mockUseTransactionPayCurrency = jest.mocked(useTransactionPayCurrency); | ||
| const mockGetIntlNumberFormatter = jest.mocked(getIntlNumberFormatter); | ||
|
|
||
| const mockFormatter = { format: jest.fn() }; | ||
|
|
||
| function buildState({ | ||
| preferredCurrency = 'usd', | ||
| currencyRates = {} as Record< | ||
| string, | ||
| { conversionRate?: number; usdConversionRate?: number } | ||
| >, | ||
| networkConfigs = {} as Record<string, { nativeCurrency: string }>, | ||
| } = {}) { | ||
| mockUseSelector.mockImplementation((selector) => { | ||
| if (selector === selectCurrentCurrency) return preferredCurrency; | ||
| if (selector === selectCurrencyRates) return currencyRates; | ||
| if (selector === selectEvmNetworkConfigurationsByChainId) | ||
| return networkConfigs; | ||
| return undefined; | ||
| }); | ||
| } | ||
|
|
||
| describe('useAssetFiatFormatter', () => { | ||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| mockUseTransactionPayCurrency.mockReturnValue(undefined); | ||
| mockGetIntlNumberFormatter.mockReturnValue( | ||
| mockFormatter as unknown as ReturnType<typeof getIntlNumberFormatter>, | ||
| ); | ||
| mockFormatter.format.mockImplementation((n) => `formatted:${String(n)}`); | ||
| }); | ||
|
|
||
| describe('outside pay flow', () => { | ||
| it('formats using the preferred currency', () => { | ||
| buildState({ preferredCurrency: 'eur' }); | ||
|
|
||
| const { result } = renderHook(() => useAssetFiatFormatter()); | ||
| const output = result.current.format('100', '0x1'); | ||
|
|
||
| expect(mockGetIntlNumberFormatter).toHaveBeenCalledWith( | ||
| 'en-US', | ||
| expect.objectContaining({ style: 'currency', currency: 'eur' }), | ||
| ); | ||
| expect(mockFormatter.format).toHaveBeenCalledWith('100'); | ||
| expect(output).toBe('formatted:100'); | ||
| }); | ||
|
|
||
| it('exposes the fiatCurrency being used', () => { | ||
| buildState({ preferredCurrency: 'eur' }); | ||
|
|
||
| const { result } = renderHook(() => useAssetFiatFormatter()); | ||
| expect(result.current.fiatCurrency).toBe('eur'); | ||
| }); | ||
|
|
||
| it('uses minimumFractionDigits=0 for integer amounts', () => { | ||
| buildState({ preferredCurrency: 'eur' }); | ||
|
|
||
| renderHook(() => useAssetFiatFormatter()).result.current.format( | ||
| '100', | ||
| '0x1', | ||
| ); | ||
|
|
||
| expect(mockGetIntlNumberFormatter).toHaveBeenCalledWith( | ||
| 'en-US', | ||
| expect.objectContaining({ minimumFractionDigits: 0 }), | ||
| ); | ||
| }); | ||
|
|
||
| it('uses minimumFractionDigits=2 for non-integer amounts', () => { | ||
| buildState({ preferredCurrency: 'eur' }); | ||
|
|
||
| renderHook(() => useAssetFiatFormatter()).result.current.format( | ||
| '100.5', | ||
| '0x1', | ||
| ); | ||
|
|
||
| expect(mockGetIntlNumberFormatter).toHaveBeenCalledWith( | ||
| 'en-US', | ||
| expect.objectContaining({ minimumFractionDigits: 2 }), | ||
| ); | ||
| }); | ||
|
|
||
| it('treats undefined/null balances as zero', () => { | ||
| buildState({ preferredCurrency: 'eur' }); | ||
|
|
||
| renderHook(() => useAssetFiatFormatter()).result.current.format( | ||
| undefined, | ||
| '0x1', | ||
| ); | ||
|
|
||
| expect(mockFormatter.format).toHaveBeenCalledWith('0'); | ||
| }); | ||
| }); | ||
|
|
||
| describe('pay flow (USD forced, preferred is EUR)', () => { | ||
| const eurUsdRates = { | ||
| ETH: { conversionRate: 2000, usdConversionRate: 2200 }, | ||
| }; | ||
| const ethChainConfig = { '0x1': { nativeCurrency: 'ETH' } }; | ||
|
|
||
| beforeEach(() => { | ||
| mockUseTransactionPayCurrency.mockReturnValue('USD'); | ||
| }); | ||
|
|
||
| it('re-scales the amount by usdRate/preferredRate', () => { | ||
| buildState({ | ||
| preferredCurrency: 'eur', | ||
| currencyRates: eurUsdRates, | ||
| networkConfigs: ethChainConfig, | ||
| }); | ||
|
|
||
| renderHook(() => useAssetFiatFormatter()).result.current.format( | ||
| '100', | ||
| '0x1', | ||
| ); | ||
|
|
||
| // 100 EUR * (2200 USD/ETH / 2000 EUR/ETH) = 110 USD | ||
| expect(mockFormatter.format).toHaveBeenCalledWith('110'); | ||
| expect(mockGetIntlNumberFormatter).toHaveBeenCalledWith( | ||
| 'en-US', | ||
| expect.objectContaining({ currency: 'USD' }), | ||
| ); | ||
| }); | ||
|
|
||
| it('exposes fiatCurrency as USD', () => { | ||
| buildState({ | ||
| preferredCurrency: 'eur', | ||
| currencyRates: eurUsdRates, | ||
| networkConfigs: ethChainConfig, | ||
| }); | ||
|
|
||
| const { result } = renderHook(() => useAssetFiatFormatter()); | ||
| expect(result.current.fiatCurrency).toBe('USD'); | ||
| }); | ||
|
|
||
| it('returns undefined when usdConversionRate is missing', () => { | ||
| buildState({ | ||
| preferredCurrency: 'eur', | ||
| currencyRates: { ETH: { conversionRate: 2000 } }, | ||
| networkConfigs: ethChainConfig, | ||
| }); | ||
|
|
||
| const { result } = renderHook(() => useAssetFiatFormatter()); | ||
| const output = result.current.format('100', '0x1'); | ||
|
|
||
| expect(output).toBeUndefined(); | ||
| expect(mockFormatter.format).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('returns undefined when preferred conversionRate is missing', () => { | ||
| buildState({ | ||
| preferredCurrency: 'eur', | ||
| currencyRates: { ETH: { usdConversionRate: 2200 } }, | ||
| networkConfigs: ethChainConfig, | ||
| }); | ||
|
|
||
| const { result } = renderHook(() => useAssetFiatFormatter()); | ||
| const output = result.current.format('100', '0x1'); | ||
|
|
||
| expect(output).toBeUndefined(); | ||
| expect(mockFormatter.format).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('returns undefined when chain has no EVM network config', () => { | ||
| buildState({ | ||
| preferredCurrency: 'eur', | ||
| currencyRates: eurUsdRates, | ||
| networkConfigs: {}, | ||
| }); | ||
|
|
||
| const { result } = renderHook(() => useAssetFiatFormatter()); | ||
| const output = result.current.format('100', '0x1'); | ||
|
|
||
| expect(output).toBeUndefined(); | ||
| expect(mockFormatter.format).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('formats zero even when rates or chain config are missing', () => { | ||
| buildState({ | ||
| preferredCurrency: 'eur', | ||
| currencyRates: {}, | ||
| networkConfigs: {}, | ||
| }); | ||
|
|
||
| const { result } = renderHook(() => useAssetFiatFormatter()); | ||
| const output = result.current.format(0, undefined); | ||
|
|
||
| expect(output).toBe('formatted:0'); | ||
| expect(mockGetIntlNumberFormatter).toHaveBeenCalledWith( | ||
| 'en-US', | ||
| expect.objectContaining({ currency: 'USD' }), | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe('pay flow (USD forced, preferred is already USD)', () => { | ||
| it('does not re-scale (identity), so numeric value is unchanged', () => { | ||
| mockUseTransactionPayCurrency.mockReturnValue('USD'); | ||
| buildState({ | ||
| preferredCurrency: 'usd', | ||
| currencyRates: { | ||
| ETH: { conversionRate: 2200, usdConversionRate: 2200 }, | ||
| }, | ||
| networkConfigs: { '0x1': { nativeCurrency: 'ETH' } }, | ||
| }); | ||
|
|
||
| renderHook(() => useAssetFiatFormatter()).result.current.format( | ||
| '100', | ||
| '0x1', | ||
| ); | ||
|
|
||
| expect(mockFormatter.format).toHaveBeenCalledWith('100'); | ||
| }); | ||
|
|
||
| it('still formats when currency rates are missing (no conversion needed)', () => { | ||
| mockUseTransactionPayCurrency.mockReturnValue('USD'); | ||
| buildState({ | ||
| preferredCurrency: 'usd', | ||
| currencyRates: {}, | ||
| networkConfigs: {}, | ||
| }); | ||
|
|
||
| const { result } = renderHook(() => useAssetFiatFormatter()); | ||
| const output = result.current.format('100', '0x1'); | ||
|
|
||
| expect(output).toBe('formatted:100'); | ||
| }); | ||
| }); | ||
|
|
||
| describe('formatter error fallback', () => { | ||
| it('falls back to `${value} ${currency}` when Intl throws', () => { | ||
| buildState({ preferredCurrency: 'eur' }); | ||
| mockGetIntlNumberFormatter.mockImplementation(() => { | ||
| throw new Error('boom'); | ||
| }); | ||
|
|
||
| const { result } = renderHook(() => useAssetFiatFormatter()); | ||
| const output = result.current.format('42', '0x1'); | ||
|
|
||
| expect(output).toBe('42 eur'); | ||
| }); | ||
| }); | ||
| }); |
102 changes: 102 additions & 0 deletions
102
app/components/Views/confirmations/hooks/pay/useAssetFiatFormatter.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| import { useSelector } from 'react-redux'; | ||
| import { useCallback } from 'react'; | ||
| import { BigNumber } from 'bignumber.js'; | ||
| import { Hex } from '@metamask/utils'; | ||
|
|
||
| import I18n from '../../../../../../locales/i18n'; | ||
| import Logger from '../../../../../util/Logger'; | ||
| import { getIntlNumberFormatter } from '../../../../../util/intl'; | ||
| import { | ||
| selectCurrencyRates, | ||
| selectCurrentCurrency, | ||
| } from '../../../../../selectors/currencyRateController'; | ||
| import { selectEvmNetworkConfigurationsByChainId } from '../../../../../selectors/networkController'; | ||
| import { useTransactionPayCurrency } from './useTransactionPayCurrency'; | ||
|
|
||
| export type AssetFiatFormatter = ( | ||
| preferredBalance: BigNumber.Value | undefined, | ||
| chainId: string | undefined, | ||
| ) => string | undefined; | ||
|
|
||
| /** | ||
| * Returns a formatter that converts a preferred-currency fiat balance into a | ||
| * localized currency string, honoring the pay-flow currency override. | ||
| * | ||
| * `asset.fiat.balance` from `@metamask/assets-controllers` is denominated in | ||
| * the user's preferred currency. When the active confirmation forces a | ||
| * different pay currency (currently only USD), the numeric value must be | ||
| * re-scaled by `(native→pay) / (native→preferred)` — not just relabeled. | ||
| * | ||
| * Returns `undefined` when the value cannot be safely rendered in the target | ||
| * currency (missing conversion rate, missing chain config). Callers should | ||
| * treat `undefined` as "hide fiat", matching the existing testnet-hidden | ||
| * fallback in `useAccountTokens`. | ||
| */ | ||
| export function useAssetFiatFormatter(): { | ||
| format: AssetFiatFormatter; | ||
| fiatCurrency: string; | ||
| } { | ||
| const preferredCurrency = useSelector(selectCurrentCurrency); | ||
| const payCurrency = useTransactionPayCurrency(); | ||
| const currencyRates = useSelector(selectCurrencyRates); | ||
| const networkConfigurationsByChainId = useSelector( | ||
| selectEvmNetworkConfigurationsByChainId, | ||
| ); | ||
|
|
||
| const fiatCurrency = payCurrency ?? preferredCurrency; | ||
|
|
||
| const needsConversion = | ||
| payCurrency === 'USD' && | ||
| preferredCurrency?.toLowerCase() !== payCurrency.toLowerCase(); | ||
|
|
||
| const format = useCallback<AssetFiatFormatter>( | ||
| (preferredBalance, chainId) => { | ||
| const preferredAmount = new BigNumber(preferredBalance ?? 0); | ||
|
|
||
| let payAmount: BigNumber | undefined = preferredAmount; | ||
| // Zero is currency-invariant, so we skip the rate lookup even when a | ||
| // pay-currency conversion would otherwise be required. Keeps the | ||
| // enrichment "$0" placeholder working when rates or chain config are | ||
| // missing. | ||
| if (needsConversion && !preferredAmount.isZero()) { | ||
| const nativeCurrency = | ||
| networkConfigurationsByChainId?.[chainId as Hex]?.nativeCurrency; | ||
| const rateEntry = nativeCurrency | ||
| ? currencyRates?.[nativeCurrency] | ||
| : undefined; | ||
| const preferredRate = rateEntry?.conversionRate; | ||
| const usdRate = rateEntry?.usdConversionRate; | ||
|
|
||
| payAmount = | ||
| preferredRate && usdRate | ||
| ? preferredAmount.multipliedBy(usdRate).dividedBy(preferredRate) | ||
| : undefined; | ||
| } | ||
|
|
||
| if (payAmount === undefined) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const hasDecimals = !payAmount.isInteger(); | ||
|
|
||
| try { | ||
| return getIntlNumberFormatter(I18n.locale, { | ||
| style: 'currency', | ||
| currency: fiatCurrency, | ||
| minimumFractionDigits: hasDecimals ? 2 : 0, | ||
| }).format(payAmount.toFixed() as unknown as number); | ||
| } catch (error) { | ||
| Logger.error(error as Error); | ||
| return `${payAmount.toFixed()} ${fiatCurrency}`; | ||
| } | ||
| }, | ||
| [ | ||
| needsConversion, | ||
| networkConfigurationsByChainId, | ||
| currencyRates, | ||
| fiatCurrency, | ||
| ], | ||
| ); | ||
|
|
||
| return { format, fiatCurrency }; | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We have this logic in the pay controller, and elsewhere in the UI.
I recall assets used to have
balanceUsdwhich would have helped here.But could we at least re-use
useTokenFiatRateswhich was my attempt to define this rate derivation once?Plus crucially it factors USD stable-coins which we don't want to convert at all.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the heads up Matthew
Unfortunately

balanceUsdis not a property for asset entity anymore.But I leverage using
useTokenFiatRatesfor locking down the pay with token list withUSD.Here is the recording for latest version, settled
EURfor preferred currency, send flow has no regression on EVM + nonEVM tokens and keptEURmeanwhile pay with token list locked toUSD:Simulator.Screen.Recording.-.iPhone.17.Pro.-.2026-07-15.at.15.10.09.mov