1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-23 09:52:26 +01:00

Expand usage of getProviderConfig selector (#18906)

The `getProviderConfig` selector is now used anywhere the `provider`
state was previously referenced directly. This was done to simplify
renaming this state from `provider` to `providerConfig` in a later PR.

Note that there are many opportunities left to use more-specific
selectors (e.g. `getChainId()` over `getProviderConfig().chainId`), but
that was intentionally omitted from this PR to reduce the size. I
started going down this path and it quickly exploded in scope.

Relates to #18902
This commit is contained in:
Mark Stacey 2023-05-02 10:06:24 -02:30 committed by GitHub
parent 7fbc26eebd
commit 88ae10418b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 76 additions and 83 deletions

View File

@ -7,6 +7,7 @@ import { pickBy } from 'lodash';
import Button from '../../ui/button'; import Button from '../../ui/button';
import * as actions from '../../../store/actions'; import * as actions from '../../../store/actions';
import { openAlert as displayInvalidCustomNetworkAlert } from '../../../ducks/alerts/invalid-custom-network'; import { openAlert as displayInvalidCustomNetworkAlert } from '../../../ducks/alerts/invalid-custom-network';
import { getProviderConfig } from '../../../ducks/metamask/metamask';
import { import {
BUILT_IN_NETWORKS, BUILT_IN_NETWORKS,
CHAIN_ID_TO_RPC_URL_MAP, CHAIN_ID_TO_RPC_URL_MAP,
@ -55,7 +56,7 @@ const DROP_DOWN_MENU_ITEM_STYLE = {
function mapStateToProps(state) { function mapStateToProps(state) {
return { return {
provider: state.metamask.provider, provider: getProviderConfig(state),
shouldShowTestNetworks: getShowTestNetworks(state), shouldShowTestNetworks: getShowTestNetworks(state),
networkConfigurations: state.metamask.networkConfigurations, networkConfigurations: state.metamask.networkConfigurations,
networkDropdownOpen: state.appState.networkDropdownOpen, networkDropdownOpen: state.appState.networkDropdownOpen,

View File

@ -2,25 +2,23 @@ import { connect } from 'react-redux';
import { NETWORK_TYPES } from '../../../../shared/constants/network'; import { NETWORK_TYPES } from '../../../../shared/constants/network';
import * as actions from '../../../store/actions'; import * as actions from '../../../store/actions';
import { getNetworkIdentifier, isNetworkLoading } from '../../../selectors'; import { getNetworkIdentifier, isNetworkLoading } from '../../../selectors';
import { getProviderConfig } from '../../../ducks/metamask/metamask';
import LoadingNetworkScreen from './loading-network-screen.component'; import LoadingNetworkScreen from './loading-network-screen.component';
const DEPRECATED_TEST_NET_CHAINIDS = ['0x3', '0x2a', '0x4']; const DEPRECATED_TEST_NET_CHAINIDS = ['0x3', '0x2a', '0x4'];
const mapStateToProps = (state) => { const mapStateToProps = (state) => {
const { loadingMessage } = state.appState; const { loadingMessage } = state.appState;
const { provider } = state.metamask; const provider = getProviderConfig(state);
const { rpcUrl, chainId, ticker, nickname, type } = provider; const { rpcUrl, chainId, ticker, nickname, type } = provider;
const setProviderArgs = const setProviderArgs =
type === NETWORK_TYPES.RPC type === NETWORK_TYPES.RPC ? [rpcUrl, chainId, ticker, nickname] : [type];
? [rpcUrl, chainId, ticker, nickname]
: [provider.type];
const providerChainId = provider?.chainId; const providerChainId = chainId;
const isDeprecatedNetwork = const isDeprecatedNetwork =
DEPRECATED_TEST_NET_CHAINIDS.includes(providerChainId); DEPRECATED_TEST_NET_CHAINIDS.includes(providerChainId);
const isInfuraRpcUrl = const isInfuraRpcUrl = rpcUrl && new URL(rpcUrl).host.endsWith('.infura.io');
provider?.rpcUrl && new URL(provider.rpcUrl).host.endsWith('.infura.io');
const showDeprecatedRpcUrlWarning = isDeprecatedNetwork && isInfuraRpcUrl; const showDeprecatedRpcUrlWarning = isDeprecatedNetwork && isInfuraRpcUrl;
return { return {

View File

@ -19,6 +19,7 @@ import Chip from '../../ui/chip/chip';
import { useI18nContext } from '../../../hooks/useI18nContext'; import { useI18nContext } from '../../../hooks/useI18nContext';
import { isNetworkLoading } from '../../../selectors'; import { isNetworkLoading } from '../../../selectors';
import { Icon, IconName, IconSize } from '../../component-library'; import { Icon, IconName, IconSize } from '../../component-library';
import { getProviderConfig } from '../../../ducks/metamask/metamask';
export default function NetworkDisplay({ export default function NetworkDisplay({
indicatorSize, indicatorSize,
@ -28,13 +29,10 @@ export default function NetworkDisplay({
onClick, onClick,
}) { }) {
const networkIsLoading = useSelector(isNetworkLoading); const networkIsLoading = useSelector(isNetworkLoading);
const currentNetwork = useSelector((state) => ({ const providerConfig = useSelector(getProviderConfig);
nickname: state.metamask.provider.nickname,
type: state.metamask.provider.type,
}));
const t = useI18nContext(); const t = useI18nContext();
const { nickname, type: networkType } = targetNetwork ?? currentNetwork; const { nickname, type: networkType } = targetNetwork ?? providerConfig;
return ( return (
<Chip <Chip

View File

@ -23,6 +23,7 @@ import { getMostRecentOverviewPage } from '../../../ducks/history/history';
import { import {
isAddressLedger, isAddressLedger,
getNativeCurrency, getNativeCurrency,
getProviderConfig,
} from '../../../ducks/metamask/metamask'; } from '../../../ducks/metamask/metamask';
import SignatureRequestOriginal from './signature-request-original.component'; import SignatureRequestOriginal from './signature-request-original.component';
@ -30,7 +31,7 @@ function mapStateToProps(state, ownProps) {
const { const {
msgParams: { from }, msgParams: { from },
} = ownProps.txData; } = ownProps.txData;
const { provider } = state.metamask; const provider = getProviderConfig(state);
const hardwareWalletRequiresConnection = const hardwareWalletRequiresConnection =
doesAddressRequireLedgerHidConnection(state, from); doesAddressRequireLedgerHidConnection(state, from);

View File

@ -17,6 +17,7 @@ import {
import { import {
isAddressLedger, isAddressLedger,
getNativeCurrency, getNativeCurrency,
getProviderConfig,
} from '../../../ducks/metamask/metamask'; } from '../../../ducks/metamask/metamask';
import { getAccountByAddress, valuesFor } from '../../../helpers/utils/util'; import { getAccountByAddress, valuesFor } from '../../../helpers/utils/util';
import { MESSAGE_TYPE } from '../../../../shared/constants/app'; import { MESSAGE_TYPE } from '../../../../shared/constants/app';
@ -30,7 +31,7 @@ function mapStateToProps(state, ownProps) {
const { const {
msgParams: { from }, msgParams: { from },
} = txData; } = txData;
const { provider } = state.metamask; const provider = getProviderConfig(state);
const hardwareWalletRequiresConnection = const hardwareWalletRequiresConnection =
doesAddressRequireLedgerHidConnection(state, from); doesAddressRequireLedgerHidConnection(state, from);

View File

@ -234,7 +234,7 @@ export const getAlertEnabledness = (state) => state.metamask.alertEnabledness;
* Get the provider configuration for the current selected network. * Get the provider configuration for the current selected network.
* *
* @param {object} state - Redux state object. * @param {object} state - Redux state object.
* @returns {object} The provider configuration for the current selected network. * @returns {import('../../../app/scripts/controllers/network/network-controller').NetworkControllerState['provider']} The provider configuration for the current selected network.
*/ */
export function getProviderConfig(state) { export function getProviderConfig(state) {
return state.metamask.provider; return state.metamask.provider;
@ -259,12 +259,9 @@ export function getNftsDropdownState(state) {
export const getNfts = (state) => { export const getNfts = (state) => {
const { const {
metamask: { metamask: { allNfts, selectedAddress },
allNfts,
provider: { chainId },
selectedAddress,
},
} = state; } = state;
const { chainId } = getProviderConfig(state);
const chainIdAsDecimal = hexToDecimal(chainId); const chainIdAsDecimal = hexToDecimal(chainId);
@ -273,12 +270,9 @@ export const getNfts = (state) => {
export const getNftContracts = (state) => { export const getNftContracts = (state) => {
const { const {
metamask: { metamask: { allNftContracts, selectedAddress },
allNftContracts,
provider: { chainId },
selectedAddress,
},
} = state; } = state;
const { chainId } = getProviderConfig(state);
const chainIdAsDecimal = hexToDecimal(chainId); const chainIdAsDecimal = hexToDecimal(chainId);
@ -297,7 +291,7 @@ export function getNativeCurrency(state) {
const useCurrencyRateCheck = getUseCurrencyRateCheck(state); const useCurrencyRateCheck = getUseCurrencyRateCheck(state);
return useCurrencyRateCheck return useCurrencyRateCheck
? state.metamask.nativeCurrency ? state.metamask.nativeCurrency
: state.metamask.provider.ticker; : getProviderConfig(state).ticker;
} }
export function getSendHexDataFeatureFlagState(state) { export function getSendHexDataFeatureFlagState(state) {

View File

@ -78,6 +78,7 @@ import {
} from '../../helpers/utils/util'; } from '../../helpers/utils/util';
import { import {
getGasEstimateType, getGasEstimateType,
getProviderConfig,
getTokens, getTokens,
getUnapprovedTxs, getUnapprovedTxs,
} from '../metamask/metamask'; } from '../metamask/metamask';
@ -1967,7 +1968,7 @@ export function updateRecipientUserInput(userInput) {
export function updateSendAmount(amount) { export function updateSendAmount(amount) {
return async (dispatch, getState) => { return async (dispatch, getState) => {
const state = getState(); const state = getState();
const { metamask } = state; const { ticker } = getProviderConfig(state);
const draftTransaction = const draftTransaction =
state[name].draftTransactions[state[name].currentTransactionUUID]; state[name].draftTransactions[state[name].currentTransactionUUID];
let logAmount = amount; let logAmount = amount;
@ -1992,9 +1993,7 @@ export function updateSendAmount(amount) {
toCurrency: EtherDenomination.ETH, toCurrency: EtherDenomination.ETH,
numberOfDecimals: 8, numberOfDecimals: 8,
}); });
logAmount = `${ethValue} ${ logAmount = `${ethValue} ${ticker || EtherDenomination.ETH}`;
metamask?.provider?.ticker || EtherDenomination.ETH
}`;
} }
await dispatch( await dispatch(
addHistoryEntry(`sendFlow - user set amount to ${logAmount}`), addHistoryEntry(`sendFlow - user set amount to ${logAmount}`),
@ -2024,6 +2023,7 @@ export function updateSendAsset(
) { ) {
return async (dispatch, getState) => { return async (dispatch, getState) => {
const state = getState(); const state = getState();
const { ticker } = getProviderConfig(state);
const draftTransaction = const draftTransaction =
state[name].draftTransactions[state[name].currentTransactionUUID]; state[name].draftTransactions[state[name].currentTransactionUUID];
const sendingAddress = const sendingAddress =
@ -2038,7 +2038,7 @@ export function updateSendAsset(
await dispatch( await dispatch(
addHistoryEntry( addHistoryEntry(
`sendFlow - user set asset of type ${AssetType.native} with symbol ${ `sendFlow - user set asset of type ${AssetType.native} with symbol ${
state.metamask.provider?.ticker ?? EtherDenomination.ETH ticker ?? EtherDenomination.ETH
}`, }`,
), ),
); );

View File

@ -1,5 +1,6 @@
import { useCallback } from 'react'; import { useCallback } from 'react';
import { useSelector } from 'react-redux'; import { useSelector } from 'react-redux';
import type { Hex } from '@metamask/utils';
import { ChainId, CHAIN_IDS } from '../../../shared/constants/network'; import { ChainId, CHAIN_IDS } from '../../../shared/constants/network';
import { getCurrentChainId } from '../../selectors'; import { getCurrentChainId } from '../../selectors';
@ -13,7 +14,7 @@ const portfolioUrl = process.env.PORTFOLIO_URL;
const useRamps = (): IUseRamps => { const useRamps = (): IUseRamps => {
const chainId = useSelector(getCurrentChainId); const chainId = useSelector(getCurrentChainId);
const getBuyURI = useCallback((_chainId: ChainId) => { const getBuyURI = useCallback((_chainId: Hex) => {
switch (_chainId) { switch (_chainId) {
case CHAIN_IDS.SEPOLIA: case CHAIN_IDS.SEPOLIA:
return 'https://faucet.sepolia.dev/'; return 'https://faucet.sepolia.dev/';

View File

@ -1,14 +1,14 @@
import { useSelector } from 'react-redux'; import { useSelector } from 'react-redux';
import { getProviderConfig } from '../ducks/metamask/metamask';
import { hexToDecimal } from '../../shared/modules/conversion.utils'; import { hexToDecimal } from '../../shared/modules/conversion.utils';
import { isEqualCaseInsensitive } from '../../shared/modules/string-utils'; import { isEqualCaseInsensitive } from '../../shared/modules/string-utils';
export const useTransactionInfo = (txData = {}) => { export const useTransactionInfo = (txData = {}) => {
const { const { allNftContracts, selectedAddress } = useSelector(
allNftContracts, (state) => state.metamask,
selectedAddress, );
provider: { chainId }, const { chainId } = useSelector(getProviderConfig);
} = useSelector((state) => state.metamask);
const isNftTransfer = Boolean( const isNftTransfer = Boolean(
allNftContracts?.[selectedAddress]?.[hexToDecimal(chainId)]?.find( allNftContracts?.[selectedAddress]?.[hexToDecimal(chainId)]?.find(

View File

@ -19,6 +19,7 @@ import {
import { MESSAGE_TYPE } from '../../../shared/constants/app'; import { MESSAGE_TYPE } from '../../../shared/constants/app';
import { TransactionStatus } from '../../../shared/constants/transaction'; import { TransactionStatus } from '../../../shared/constants/transaction';
import { getSendTo } from '../../ducks/send'; import { getSendTo } from '../../ducks/send';
import { getProviderConfig } from '../../ducks/metamask/metamask';
const SIGN_MESSAGE_TYPE = { const SIGN_MESSAGE_TYPE = {
MESSAGE: 'message', MESSAGE: 'message',
@ -70,8 +71,8 @@ const ConfirmTxScreen = ({ match }) => {
unapprovedTypedMessages, unapprovedTypedMessages,
networkId, networkId,
blockGasLimit, blockGasLimit,
provider: { chainId },
} = useSelector((state) => state.metamask); } = useSelector((state) => state.metamask);
const { chainId } = useSelector(getProviderConfig);
const { txId: index } = useSelector((state) => state.appState); const { txId: index } = useSelector((state) => state.appState);
///: BEGIN:ONLY_INCLUDE_IN(build-mmi) ///: BEGIN:ONLY_INCLUDE_IN(build-mmi)

View File

@ -46,6 +46,7 @@ import {
getIsGasEstimatesLoading, getIsGasEstimatesLoading,
getNativeCurrency, getNativeCurrency,
getSendToAccounts, getSendToAccounts,
getProviderConfig,
} from '../../ducks/metamask/metamask'; } from '../../ducks/metamask/metamask';
import { addHexPrefix } from '../../../app/scripts/lib/util'; import { addHexPrefix } from '../../../app/scripts/lib/util';
@ -104,8 +105,8 @@ const mapStateToProps = (state, ownProps) => {
networkId, networkId,
unapprovedTxs, unapprovedTxs,
nextNonce, nextNonce,
provider: { chainId },
} = metamask; } = metamask;
const { chainId } = getProviderConfig(state);
const { tokenData, txData, tokenProps, nonce } = confirmTransaction; const { tokenData, txData, tokenProps, nonce } = confirmTransaction;
const { txParams = {}, id: transactionId, type } = txData; const { txParams = {}, id: transactionId, type } = txData;
const txId = transactionId || Number(paramsTransactionId); const txId = transactionId || Number(paramsTransactionId);

View File

@ -18,13 +18,10 @@ import {
CHAIN_ID_TO_NETWORK_IMAGE_URL_MAP, CHAIN_ID_TO_NETWORK_IMAGE_URL_MAP,
NETWORK_TO_NAME_MAP, NETWORK_TO_NAME_MAP,
} from '../../../../../shared/constants/network'; } from '../../../../../shared/constants/network';
import { getProviderConfig } from '../../../../ducks/metamask/metamask';
export default function ConfirmationNetworkSwitch({ newNetwork }) { export default function ConfirmationNetworkSwitch({ newNetwork }) {
const currentNetwork = useSelector((state) => ({ const { chainId, nickname, type } = useSelector(getProviderConfig);
nickname: state.metamask.provider.nickname,
type: state.metamask.provider.type,
chainId: state.metamask.provider.chainId,
}));
return ( return (
<Box <Box
@ -38,10 +35,10 @@ export default function ConfirmationNetworkSwitch({ newNetwork }) {
className="confirmation-network-switch__icon" className="confirmation-network-switch__icon"
display={DISPLAY.BLOCK} display={DISPLAY.BLOCK}
> >
{currentNetwork.chainId in CHAIN_ID_TO_NETWORK_IMAGE_URL_MAP ? ( {chainId in CHAIN_ID_TO_NETWORK_IMAGE_URL_MAP ? (
<SiteIcon <SiteIcon
icon={CHAIN_ID_TO_NETWORK_IMAGE_URL_MAP[currentNetwork.chainId]} icon={CHAIN_ID_TO_NETWORK_IMAGE_URL_MAP[chainId]}
name={currentNetwork.nickname} name={nickname}
size={64} size={64}
/> />
) : ( ) : (
@ -59,7 +56,7 @@ export default function ConfirmationNetworkSwitch({ newNetwork }) {
justifyContent: JustifyContent.center, justifyContent: JustifyContent.center,
}} }}
> >
{currentNetwork.nickname || NETWORK_TO_NAME_MAP[currentNetwork.type]} {nickname || NETWORK_TO_NAME_MAP[type]}
</Typography> </Typography>
</Box> </Box>
<Box <Box

View File

@ -6,6 +6,7 @@ import {
getTokenStandardAndDetails, getTokenStandardAndDetails,
} from '../../store/actions'; } from '../../store/actions';
import { getMostRecentOverviewPage } from '../../ducks/history/history'; import { getMostRecentOverviewPage } from '../../ducks/history/history';
import { getProviderConfig } from '../../ducks/metamask/metamask';
import { import {
getRpcPrefsForCurrentProvider, getRpcPrefsForCurrentProvider,
getIsTokenDetectionSupported, getIsTokenDetectionSupported,
@ -23,11 +24,11 @@ const mapStateToProps = (state) => {
identities, identities,
tokens, tokens,
pendingTokens, pendingTokens,
provider: { chainId },
useTokenDetection, useTokenDetection,
selectedAddress, selectedAddress,
}, },
} = state; } = state;
const { chainId } = getProviderConfig(state);
const isTokenDetectionInactiveOnMainnet = const isTokenDetectionInactiveOnMainnet =
getIsTokenDetectionInactiveOnMainnet(state); getIsTokenDetectionInactiveOnMainnet(state);

View File

@ -24,6 +24,7 @@ import {
import { pageChanged } from '../../ducks/history/history'; import { pageChanged } from '../../ducks/history/history';
import { prepareToLeaveSwaps } from '../../ducks/swaps/swaps'; import { prepareToLeaveSwaps } from '../../ducks/swaps/swaps';
import { getSendStage } from '../../ducks/send'; import { getSendStage } from '../../ducks/send';
import { getProviderConfig } from '../../ducks/metamask/metamask';
import Routes from './routes.component'; import Routes from './routes.component';
function mapStateToProps(state) { function mapStateToProps(state) {
@ -46,7 +47,7 @@ function mapStateToProps(state) {
browserEnvironmentOs: state.metamask.browserEnvironment?.os, browserEnvironmentOs: state.metamask.browserEnvironment?.os,
browserEnvironmentContainter: state.metamask.browserEnvironment?.browser, browserEnvironmentContainter: state.metamask.browserEnvironment?.browser,
providerId: getNetworkIdentifier(state), providerId: getNetworkIdentifier(state),
providerType: state.metamask.provider?.type, providerType: getProviderConfig(state).type,
theme: getTheme(state), theme: getTheme(state),
sendStage: getSendStage(state), sendStage: getSendStage(state),
isNetworkUsed: getIsNetworkUsed(state), isNetworkUsed: getIsNetworkUsed(state),

View File

@ -2,6 +2,7 @@ import { compose } from 'redux';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom'; import { withRouter } from 'react-router-dom';
import { getAddressBookEntry } from '../../../../selectors'; import { getAddressBookEntry } from '../../../../selectors';
import { getProviderConfig } from '../../../../ducks/metamask/metamask';
import { import {
CONTACT_VIEW_ROUTE, CONTACT_VIEW_ROUTE,
CONTACT_LIST_ROUTE, CONTACT_LIST_ROUTE,
@ -25,7 +26,7 @@ const mapStateToProps = (state, ownProps) => {
getAddressBookEntry(state, address) || state.metamask.identities[address]; getAddressBookEntry(state, address) || state.metamask.identities[address];
const { memo, name } = contact || {}; const { memo, name } = contact || {};
const { chainId } = state.metamask.provider; const { chainId } = getProviderConfig(state);
return { return {
address: contact ? address : null, address: contact ? address : null,

View File

@ -1,7 +1,7 @@
import React, { useContext } from 'react'; import React, { useContext } from 'react';
import { useDispatch, useSelector } from 'react-redux'; import { useDispatch, useSelector } from 'react-redux';
import { Redirect, useHistory, useParams } from 'react-router-dom'; import { Redirect, useHistory, useParams } from 'react-router-dom';
import { getTokens } from '../../ducks/metamask/metamask'; import { getProviderConfig, getTokens } from '../../ducks/metamask/metamask';
import { getTokenList } from '../../selectors'; import { getTokenList } from '../../selectors';
import { useCopyToClipboard } from '../../hooks/useCopyToClipboard'; import { useCopyToClipboard } from '../../hooks/useCopyToClipboard';
import Identicon from '../../components/ui/identicon'; import Identicon from '../../components/ui/identicon';
@ -54,12 +54,7 @@ export default function TokenDetailsPage() {
token?.symbol, token?.symbol,
); );
const currentNetwork = useSelector((state) => ({ const { nickname, type: networkType } = useSelector(getProviderConfig);
nickname: state.metamask.provider.nickname,
type: state.metamask.provider.type,
}));
const { nickname, type: networkType } = currentNetwork;
const [copied, handleCopy] = useCopyToClipboard(); const [copied, handleCopy] = useCopyToClipboard();

View File

@ -101,22 +101,18 @@ export function isNetworkLoading(state) {
} }
export function getNetworkIdentifier(state) { export function getNetworkIdentifier(state) {
const { const { type, nickname, rpcUrl } = getProviderConfig(state);
metamask: {
provider: { type, nickname, rpcUrl },
},
} = state;
return nickname || rpcUrl || type; return nickname || rpcUrl || type;
} }
export function getMetricsNetworkIdentifier(state) { export function getMetricsNetworkIdentifier(state) {
const { provider } = state.metamask; const provider = getProviderConfig(state);
return provider.type === NETWORK_TYPES.RPC ? provider.rpcUrl : provider.type; return provider.type === NETWORK_TYPES.RPC ? provider.rpcUrl : provider.type;
} }
export function getCurrentChainId(state) { export function getCurrentChainId(state) {
const { chainId } = state.metamask.provider; const { chainId } = getProviderConfig(state);
return chainId; return chainId;
} }
@ -658,8 +654,8 @@ export function getTargetSubjectMetadata(state, origin) {
} }
export function getRpcPrefsForCurrentProvider(state) { export function getRpcPrefsForCurrentProvider(state) {
const { provider: { rpcPrefs = {} } = {} } = state.metamask; const { rpcPrefs } = getProviderConfig(state);
return rpcPrefs; return rpcPrefs || {};
} }
export function getKnownMethodData(state, data) { export function getKnownMethodData(state, data) {

View File

@ -35,9 +35,9 @@ describe('Selectors', () => {
}); });
describe('#getRpcPrefsForCurrentProvider', () => { describe('#getRpcPrefsForCurrentProvider', () => {
it('returns an empty object if state.metamask.provider is undefined', () => { it('returns an empty object if state.metamask.provider is empty', () => {
expect( expect(
selectors.getRpcPrefsForCurrentProvider({ metamask: {} }), selectors.getRpcPrefsForCurrentProvider({ metamask: { provider: {} } }),
).toStrictEqual({}); ).toStrictEqual({});
}); });
it('returns rpcPrefs from the provider', () => { it('returns rpcPrefs from the provider', () => {

View File

@ -11,6 +11,7 @@ import {
} from '../../shared/constants/transaction'; } from '../../shared/constants/transaction';
import { transactionMatchesNetwork } from '../../shared/modules/transaction.utils'; import { transactionMatchesNetwork } from '../../shared/modules/transaction.utils';
import { hexToDecimal } from '../../shared/modules/conversion.utils'; import { hexToDecimal } from '../../shared/modules/conversion.utils';
import { getProviderConfig } from '../ducks/metamask/metamask';
import { import {
getCurrentChainId, getCurrentChainId,
deprecatedGetCurrentNetworkId, deprecatedGetCurrentNetworkId,
@ -28,10 +29,8 @@ export const incomingTxListSelector = (state) => {
return []; return [];
} }
const { const { networkId } = state.metamask;
networkId, const { chainId } = getProviderConfig(state);
provider: { chainId },
} = state.metamask;
const selectedAddress = getSelectedAddress(state); const selectedAddress = getSelectedAddress(state);
return Object.values(state.metamask.incomingTransactions).filter( return Object.values(state.metamask.incomingTransactions).filter(
(tx) => (tx) =>

View File

@ -43,7 +43,10 @@ import {
DraftTransaction, DraftTransaction,
} from '../ducks/send'; } from '../ducks/send';
import { switchedToUnconnectedAccount } from '../ducks/alerts/unconnected-account'; import { switchedToUnconnectedAccount } from '../ducks/alerts/unconnected-account';
import { getUnconnectedAccountAlertEnabledness } from '../ducks/metamask/metamask'; import {
getProviderConfig,
getUnconnectedAccountAlertEnabledness,
} from '../ducks/metamask/metamask';
import { toChecksumHexAddress } from '../../shared/modules/hexstring-utils'; import { toChecksumHexAddress } from '../../shared/modules/hexstring-utils';
import { import {
HardwareDeviceNames, HardwareDeviceNames,
@ -1765,13 +1768,15 @@ export function updateMetamaskState(
newState: MetaMaskReduxState['metamask'], newState: MetaMaskReduxState['metamask'],
): ThunkAction<void, MetaMaskReduxState, unknown, AnyAction> { ): ThunkAction<void, MetaMaskReduxState, unknown, AnyAction> {
return (dispatch, getState) => { return (dispatch, getState) => {
const { metamask: currentState } = getState(); const state = getState();
const providerConfig = getProviderConfig(state);
const { metamask: currentState } = state;
const { currentLocale, selectedAddress, provider } = currentState; const { currentLocale, selectedAddress } = currentState;
const { const {
currentLocale: newLocale, currentLocale: newLocale,
selectedAddress: newSelectedAddress, selectedAddress: newSelectedAddress,
provider: newProvider, provider: newProviderConfig,
} = newState; } = newState;
if (currentLocale && newLocale && currentLocale !== newLocale) { if (currentLocale && newLocale && currentLocale !== newLocale) {
@ -1782,8 +1787,10 @@ export function updateMetamaskState(
dispatch({ type: actionConstants.SELECTED_ADDRESS_CHANGED }); dispatch({ type: actionConstants.SELECTED_ADDRESS_CHANGED });
} }
const newAddressBook = newState.addressBook?.[newProvider?.chainId] ?? {}; const newAddressBook =
const oldAddressBook = currentState.addressBook?.[provider?.chainId] ?? {}; newState.addressBook?.[newProviderConfig?.chainId] ?? {};
const oldAddressBook =
currentState.addressBook?.[providerConfig?.chainId] ?? {};
const newAccounts: { [address: string]: Record<string, any> } = const newAccounts: { [address: string]: Record<string, any> } =
getMetaMaskAccounts({ metamask: newState }); getMetaMaskAccounts({ metamask: newState });
const oldAccounts: { [address: string]: Record<string, any> } = const oldAccounts: { [address: string]: Record<string, any> } =
@ -1832,10 +1839,10 @@ export function updateMetamaskState(
type: actionConstants.UPDATE_METAMASK_STATE, type: actionConstants.UPDATE_METAMASK_STATE,
value: newState, value: newState,
}); });
if (provider.chainId !== newProvider.chainId) { if (providerConfig.chainId !== newProviderConfig.chainId) {
dispatch({ dispatch({
type: actionConstants.CHAIN_CHANGED, type: actionConstants.CHAIN_CHANGED,
payload: newProvider.chainId, payload: newProviderConfig.chainId,
}); });
// We dispatch this action to ensure that the send state stays up to date // We dispatch this action to ensure that the send state stays up to date
// after the chain changes. This async thunk will fail gracefully in the // after the chain changes. This async thunk will fail gracefully in the
@ -2615,7 +2622,7 @@ export function addToAddressBook(
log.debug(`background.addToAddressBook`); log.debug(`background.addToAddressBook`);
return async (dispatch, getState) => { return async (dispatch, getState) => {
const { chainId } = getState().metamask.provider; const { chainId } = getProviderConfig(getState());
let set; let set;
try { try {