Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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');
});
});
});
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)

Copy link
Copy Markdown
Member

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 balanceUsd which would have helped here.

But could we at least re-use useTokenFiatRates which 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.

@OGPoyraz OGPoyraz Jul 15, 2026

Copy link
Copy Markdown
Member Author

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 balanceUsd is not a property for asset entity anymore.
Screenshot 2026-07-15 at 14 33 43

But I leverage using useTokenFiatRates for locking down the pay with token list with USD.

Here is the recording for latest version, settled EUR for preferred currency, send flow has no regression on EVM + nonEVM tokens and kept EUR meanwhile pay with token list locked to USD:

Simulator.Screen.Recording.-.iPhone.17.Pro.-.2026-07-15.at.15.10.09.mov

: 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 };
}
Loading
Loading