Skip to content

Commit

Permalink
Remove getConversionRate usages
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewwalsh0 committed Nov 5, 2024
1 parent 4751ebf commit 64e464e
Show file tree
Hide file tree
Showing 10 changed files with 71 additions and 29 deletions.
7 changes: 6 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,12 @@ module.exports = {
'error',
{
selector:
'ImportSpecifier[imported.name=/(getCurrentChainId)|(getNativeCurrency)|(getProviderConfig)|(getRpcPrefsForCurrentProvider)/]',
'ImportSpecifier[imported.name=/' +
'(getCurrentChainId)|' +
'(getNativeCurrency)|' +
'(getProviderConfig)|' +
'(getRpcPrefsForCurrentProvider)|' +
'(getConversionRate)/]',
message: 'Avoid using global network selectors in confirmations',
},
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ import {
multiplyHexes,
} from '../../../../../../../shared/modules/conversion.utils';
import { Numeric } from '../../../../../../../shared/modules/Numeric';
import { getConversionRate } from '../../../../../../ducks/metamask/metamask';
import { useFiatFormatter } from '../../../../../../hooks/useFiatFormatter';
import { useGasFeeEstimates } from '../../../../../../hooks/useGasFeeEstimates';
import { getCurrentCurrency } from '../../../../../../selectors';
import {
getCurrentCurrency,
selectConversionRateByChainId,
} from '../../../../../../selectors';
import { getMultichainNetwork } from '../../../../../../selectors/multichain';
import { HEX_ZERO } from '../shared/constants';
import { useEIP1559TxFees } from './useEIP1559TxFees';
Expand All @@ -30,9 +32,13 @@ const EMPTY_FEES = {

export function useFeeCalculations(transactionMeta: TransactionMeta) {
const currentCurrency = useSelector(getCurrentCurrency);
const conversionRate = useSelector(getConversionRate);
const { chainId } = transactionMeta;
const fiatFormatter = useFiatFormatter();

const conversionRate = useSelector((state) =>
selectConversionRateByChainId(state, chainId),
);

const multichainNetwork = useSelector(getMultichainNetwork);
const ticker = multichainNetwork?.network?.ticker;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
} from '../../../../../../../components/component-library';
import Tooltip from '../../../../../../../components/ui/tooltip';
import { getIntlLocale } from '../../../../../../../ducks/locale/locale';
import { getConversionRate } from '../../../../../../../ducks/metamask/metamask';
import {
AlignItems,
Display,
Expand All @@ -29,16 +28,22 @@ import {
formatAmountMaxPrecision,
} from '../../../../simulation-details/formatAmount';
import { toNonScientificString } from '../../hooks/use-token-values';
import { selectConversionRateByChainId } from '../../../../../../../selectors';

const NativeSendHeading = () => {
const { currentConfirmation: transactionMeta } =
useConfirmContext<TransactionMeta>();

const { chainId } = transactionMeta;

const nativeAssetTransferValue = new BigNumber(
transactionMeta.txParams.value as string,
).dividedBy(new BigNumber(10).pow(18));

const conversionRate = useSelector(getConversionRate);
const conversionRate = useSelector((state) =>
selectConversionRateByChainId(state, chainId),
);

const fiatValue =
conversionRate &&
nativeAssetTransferValue &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,21 @@ import {
} from '@metamask/transaction-controller';
import { BigNumber } from 'bignumber.js';
import { TokenStandard } from '../../../../../shared/constants/transaction';
import { getConversionRate } from '../../../../ducks/metamask/metamask';
import { getTokenStandardAndDetails } from '../../../../store/actions';
import { fetchTokenExchangeRates } from '../../../../helpers/utils/util';
import { memoizedGetTokenStandardAndDetails } from '../../utils/token';
import { selectConversionRateByChainId } from '../../../../selectors';
import { useBalanceChanges } from './useBalanceChanges';
import { FIAT_UNAVAILABLE } from './types';

jest.mock('react-redux', () => ({
useSelector: jest.fn((selector) => selector()),
}));

jest.mock('../../../../ducks/metamask/metamask', () => ({
getConversionRate: jest.fn(),
}));

jest.mock('../../../../selectors', () => ({
getCurrentChainId: jest.fn(),
getCurrentCurrency: jest.fn(),
selectConversionRateByChainId: jest.fn(),
}));

jest.mock('../../../../helpers/utils/util', () => ({
Expand All @@ -34,7 +31,9 @@ jest.mock('../../../../store/actions', () => ({
getTokenStandardAndDetails: jest.fn(),
}));

const mockGetConversionRate = getConversionRate as jest.Mock;
const mockSelectConversionRateByChainId = jest.mocked(
selectConversionRateByChainId,
);
const mockGetTokenStandardAndDetails = getTokenStandardAndDetails as jest.Mock;
const mockFetchTokenExchangeRates = fetchTokenExchangeRates as jest.Mock;

Expand Down Expand Up @@ -85,7 +84,7 @@ describe('useBalanceChanges', () => {
}
return Promise.reject(new Error('Unable to determine token standard'));
});
mockGetConversionRate.mockReturnValue(ETH_TO_FIAT_RATE);
mockSelectConversionRateByChainId.mockReturnValue(ETH_TO_FIAT_RATE);
mockFetchTokenExchangeRates.mockResolvedValue({
[ERC20_TOKEN_ADDRESS_1_MOCK]: ERC20_TO_FIAT_RATE_1_MOCK,
[ERC20_TOKEN_ADDRESS_2_MOCK]: ERC20_TO_FIAT_RATE_2_MOCK,
Expand Down Expand Up @@ -344,7 +343,7 @@ describe('useBalanceChanges', () => {
});

it('handles native fiat rate with more than 15 significant digits', async () => {
mockGetConversionRate.mockReturnValue(0.1234567890123456);
mockSelectConversionRateByChainId.mockReturnValue(0.1234567890123456);
const { result, waitForNextUpdate } = setupHook({
...dummyBalanceChange,
difference: DIFFERENCE_ETH_MOCK,
Expand All @@ -357,7 +356,7 @@ describe('useBalanceChanges', () => {
});

it('handles unavailable native fiat rate', async () => {
mockGetConversionRate.mockReturnValue(null);
mockSelectConversionRateByChainId.mockReturnValue(null);
const { result, waitForNextUpdate } = setupHook({
...dummyBalanceChange,
difference: DIFFERENCE_ETH_MOCK,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ import { BigNumber } from 'bignumber.js';
import { ContractExchangeRates } from '@metamask/assets-controllers';
import { useAsyncResultOrThrow } from '../../../../hooks/useAsyncResult';
import { TokenStandard } from '../../../../../shared/constants/transaction';
import { getConversionRate } from '../../../../ducks/metamask/metamask';
import { getCurrentCurrency } from '../../../../selectors';
import {
getCurrentCurrency,
selectConversionRateByChainId,
} from '../../../../selectors';
import { fetchTokenExchangeRates } from '../../../../helpers/utils/util';
import { ERC20_DEFAULT_DECIMALS, fetchErc20Decimals } from '../../utils/token';

Expand Down Expand Up @@ -158,7 +160,10 @@ export const useBalanceChanges = ({
simulationData?: SimulationData;
}): { pending: boolean; value: BalanceChange[] } => {
const fiatCurrency = useSelector(getCurrentCurrency);
const nativeFiatRate = useSelector(getConversionRate);

const nativeFiatRate = useSelector((state) =>
selectConversionRateByChainId(state, chainId),
);

const { nativeBalanceChange, tokenBalanceChanges = [] } =
simulationData ?? {};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import { editExistingTransaction } from '../../../ducks/send';
import {
contractExchangeRateSelector,
getCurrentCurrency,
selectConversionRateByChainId,
selectNetworkConfigurationByChainId,
} from '../../../selectors';
import { getConversionRate } from '../../../ducks/metamask/metamask';
import { clearConfirmTransaction } from '../../../ducks/confirm-transaction/confirm-transaction.duck';
import { showSendTokenPage } from '../../../store/actions';
import {
Expand Down Expand Up @@ -47,9 +47,13 @@ export default function ConfirmSendToken({
history.push(SEND_ROUTE);
});
};
const conversionRate = useSelector(getConversionRate);

const { chainId } = transaction;

const conversionRate = useSelector((state) =>
selectConversionRateByChainId(state, chainId),
);

const { nativeCurrency } = useSelector((state) =>
selectNetworkConfigurationByChainId(state, chainId),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,10 @@ import {
contractExchangeRateSelector,
getCurrentCurrency,
getSelectedInternalAccount,
selectConversionRateByChainId,
selectNetworkConfigurationByChainId,
} from '../../../selectors';
import {
getConversionRate,
getNftContracts,
} from '../../../ducks/metamask/metamask';
import { getNftContracts } from '../../../ducks/metamask/metamask';
import { TokenStandard } from '../../../../shared/constants/transaction';
import {
getWeiHexFromDecimalValue,
Expand Down Expand Up @@ -57,7 +55,11 @@ export default function ConfirmTokenTransactionBase({

const blockExplorerUrl = blockExplorerUrls?.[0];
const currentCurrency = useSelector(getCurrentCurrency);
const conversionRate = useSelector(getConversionRate);

const conversionRate = useSelector((state) =>
selectConversionRateByChainId(state, chainId),
);

const { address: userAddress } = useSelector(getSelectedInternalAccount);
const nftCollections = useSelector(getNftContracts);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ import {
getIsGasEstimatesLoading,
getSendToAccounts,
findKeyringForAddress,
getConversionRate,
} from '../../../ducks/metamask/metamask';
import {
addHexPrefix,
Expand All @@ -96,6 +95,7 @@ import { CUSTOM_GAS_ESTIMATE } from '../../../../shared/constants/gas';
import { getIsUsingPaymaster } from '../../../selectors/account-abstraction';

import {
selectConversionRateByChainId,
selectNetworkConfigurationByChainId,
// eslint-disable-next-line import/no-duplicates
} from '../../../selectors/selectors';
Expand Down Expand Up @@ -174,7 +174,6 @@ const mapStateToProps = (state, ownProps) => {
const gasLoadingAnimationIsShowing = getGasLoadingAnimationIsShowing(state);
const isBuyableChain = getIsNativeTokenBuyable(state);
const { confirmTransaction, metamask } = state;
const conversionRate = getConversionRate(state);
const { addressBook, nextNonce } = metamask;
const unapprovedTxs = getUnapprovedTransactions(state);

Expand All @@ -183,6 +182,7 @@ const mapStateToProps = (state, ownProps) => {
const txId = transactionId || paramsTransactionId;
const transaction = getUnapprovedTransaction(state, txId) ?? {};
const { chainId } = transaction;
const conversionRate = selectConversionRateByChainId(state, chainId);

const {
from: fromAddress,
Expand Down
4 changes: 2 additions & 2 deletions ui/pages/confirmations/hooks/test-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import { useSelector } from 'react-redux';
import { useMultichainSelector } from '../../../hooks/useMultichainSelector';

import { GasEstimateTypes } from '../../../../shared/constants/gas';
import { getConversionRate } from '../../../ducks/metamask/metamask';
import {
getCurrentCurrency,
getShouldShowFiat,
txDataSelector,
getCurrentKeyring,
getTokenExchangeRates,
getPreferences,
selectConversionRateByChainId,
} from '../../../selectors';

import {
Expand Down Expand Up @@ -104,7 +104,7 @@ export const generateUseSelectorRouter =
if (selector === getMultichainIsEvm) {
return true;
}
if (selector === getConversionRate) {
if (selector === selectConversionRateByChainId) {
return MOCK_ETH_USD_CONVERSION_RATE;
}
if (selector === getMultichainNativeCurrency) {
Expand Down
16 changes: 16 additions & 0 deletions ui/selectors/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -734,6 +734,22 @@ export const selectDefaultRpcEndpointByChainId = createSelector(
},
);

/**
* @type (state: any, chainId: string) => number | undefined
*/
export const selectConversionRateByChainId = createSelector(
selectNetworkConfigurationByChainId,
(state) => state,
(networkConfiguration, state) => {
if (!networkConfiguration) {
return undefined;
}

const { nativeCurrency } = networkConfiguration;
return state.metamask.currencyRates[nativeCurrency]?.conversionRate;
},
);

export function getRequestingNetworkInfo(state, chainIds) {
// If chainIds is undefined, set it to an empty array
let processedChainIds = chainIds === undefined ? [] : chainIds;
Expand Down

0 comments on commit 64e464e

Please sign in to comment.