1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-22 01:47:00 +01:00

prefer chainId over networkId in most cases (#10594)

This commit is contained in:
Brad Decker 2021-03-12 16:23:26 -06:00 committed by GitHub
parent 661948cd5b
commit 3d4dfc74a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 159 additions and 145 deletions

View File

@ -1,18 +1,26 @@
import {
GOERLI_CHAIN_ID,
KOVAN_CHAIN_ID,
MAINNET_CHAIN_ID,
RINKEBY_CHAIN_ID,
ROPSTEN_CHAIN_ID,
} from '../../../shared/constants/network';
/**
* Gives the caller a url at which the user can acquire eth, depending on the network they are in
*
* @param {Object} opts - Options required to determine the correct url
* @param {string} opts.network - The network for which to return a url
* @param {string} opts.address - The address the bought ETH should be sent to. Only relevant if network === '1'.
* @returns {string|undefined} The url at which the user can access ETH, while in the given network. If the passed
* network does not match any of the specified cases, or if no network is given, returns undefined.
* @param {string} opts.chainId - The chainId for which to return a url
* @param {string} opts.address - The address the bought ETH should be sent to. Only relevant if chainId === '0x1'.
* @returns {string|undefined} The url at which the user can access ETH, while in the given chain. If the passed
* chainId does not match any of the specified cases, or if no chainId is given, returns undefined.
*
*/
export default function getBuyEthUrl({ network, address, service }) {
export default function getBuyEthUrl({ chainId, address, service }) {
// default service by network if not specified
if (!service) {
// eslint-disable-next-line no-param-reassign
service = getDefaultServiceForNetwork(network);
service = getDefaultServiceForChain(chainId);
}
switch (service) {
@ -33,21 +41,21 @@ export default function getBuyEthUrl({ network, address, service }) {
}
}
function getDefaultServiceForNetwork(network) {
switch (network) {
case '1':
function getDefaultServiceForChain(chainId) {
switch (chainId) {
case MAINNET_CHAIN_ID:
return 'wyre';
case '3':
case ROPSTEN_CHAIN_ID:
return 'metamask-faucet';
case '4':
case RINKEBY_CHAIN_ID:
return 'rinkeby-faucet';
case '42':
case KOVAN_CHAIN_ID:
return 'kovan-faucet';
case '5':
case GOERLI_CHAIN_ID:
return 'goerli-faucet';
default:
throw new Error(
`No default cryptocurrency exchange or faucet for networkId: "${network}"`,
`No default cryptocurrency exchange or faucet for chainId: "${chainId}"`,
);
}
}

View File

@ -24,7 +24,6 @@ import {
CurrencyRateController,
PhishingController,
} from '@metamask/controllers';
import { getBackgroundMetaMetricState } from '../../ui/app/selectors';
import { TRANSACTION_STATUSES } from '../../shared/constants/transaction';
import { MAINNET_CHAIN_ID } from '../../shared/constants/network';
import ComposableObservableStore from './lib/ComposableObservableStore';
@ -330,12 +329,23 @@ export default class MetamaskController extends EventEmitter {
this.platform.showTransactionNotification(txMeta, rpcPrefs);
const { txReceipt } = txMeta;
const metamaskState = await this.getState();
if (txReceipt && txReceipt.status === '0x0') {
this.sendBackgroundMetaMetrics({
action: 'Transactions',
name: 'On Chain Failure',
customVariables: { errorMessage: txMeta.simulationFails?.reason },
});
this.metaMetricsController.trackEvent(
{
category: 'Background',
properties: {
action: 'Transactions',
errorMessage: txMeta.simulationFails?.reason,
numberOfTokens: metamaskState.tokens.length,
numberOfAccounts: Object.keys(metamaskState.accounts).length,
},
},
{
matomoEvent: true,
},
);
}
}
});
@ -577,7 +587,7 @@ export default class MetamaskController extends EventEmitter {
const isInitialized = Boolean(vault);
return {
...{ isInitialized },
isInitialized,
...this.memStore.getFlatState(),
};
}
@ -1058,10 +1068,6 @@ export default class MetamaskController extends EventEmitter {
});
}
getCurrentNetwork = () => {
return this.networkController.store.getState().network;
};
/**
* Collects all the information that we want to share
* with the mobile client for syncing purposes
@ -2414,32 +2420,6 @@ export default class MetamaskController extends EventEmitter {
return nonceLock.nextNonce;
}
async sendBackgroundMetaMetrics({ action, name, customVariables } = {}) {
if (!action || !name) {
throw new Error('Must provide action and name.');
}
const metamaskState = await this.getState();
const additionalProperties = getBackgroundMetaMetricState({
metamask: metamaskState,
});
this.metaMetricsController.trackEvent(
{
event: name,
category: 'Background',
properties: {
action,
...additionalProperties,
...customVariables,
},
},
{
matomoEvent: true,
},
);
}
/**
* Migrate address book state from old to new chainId.
*

View File

@ -10,12 +10,14 @@ export const ROPSTEN_NETWORK_ID = '3';
export const RINKEBY_NETWORK_ID = '4';
export const GOERLI_NETWORK_ID = '5';
export const KOVAN_NETWORK_ID = '42';
export const LOCALHOST_NETWORK_ID = '1337';
export const MAINNET_CHAIN_ID = '0x1';
export const ROPSTEN_CHAIN_ID = '0x3';
export const RINKEBY_CHAIN_ID = '0x4';
export const GOERLI_CHAIN_ID = '0x5';
export const KOVAN_CHAIN_ID = '0x2a';
export const LOCALHOST_CHAIN_ID = '0x539';
/**
* The largest possible chain ID we can handle.

View File

@ -1,20 +1,26 @@
import assert from 'assert';
import getBuyEthUrl from '../../../app/scripts/lib/buy-eth-url';
import {
KOVAN_CHAIN_ID,
MAINNET_CHAIN_ID,
RINKEBY_CHAIN_ID,
ROPSTEN_CHAIN_ID,
} from '../../../shared/constants/network';
describe('buy-eth-url', function () {
const mainnet = {
network: '1',
chainId: MAINNET_CHAIN_ID,
amount: 5,
address: '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc',
};
const ropsten = {
network: '3',
chainId: ROPSTEN_CHAIN_ID,
};
const rinkeby = {
network: '4',
chainId: RINKEBY_CHAIN_ID,
};
const kovan = {
network: '42',
chainId: KOVAN_CHAIN_ID,
};
it('returns wyre url with address for network 1', function () {

View File

@ -21,7 +21,7 @@ export default class LoadingNetworkScreen extends PureComponent {
setProviderArgs: PropTypes.array,
setProviderType: PropTypes.func,
rollbackToPreviousProvider: PropTypes.func,
isLoadingNetwork: PropTypes.bool,
isNetworkLoading: PropTypes.bool,
};
componentDidMount = () => {
@ -99,9 +99,9 @@ export default class LoadingNetworkScreen extends PureComponent {
};
cancelCall = () => {
const { isLoadingNetwork } = this.props;
const { isNetworkLoading } = this.props;
if (isLoadingNetwork) {
if (isNetworkLoading) {
this.setState({ showErrorScreen: true });
}
};

View File

@ -1,12 +1,12 @@
import { connect } from 'react-redux';
import { NETWORK_TYPE_RPC } from '../../../../../shared/constants/network';
import * as actions from '../../../store/actions';
import { getNetworkIdentifier } from '../../../selectors';
import { getNetworkIdentifier, isNetworkLoading } from '../../../selectors';
import LoadingNetworkScreen from './loading-network-screen.component';
const mapStateToProps = (state) => {
const { loadingMessage } = state.appState;
const { provider, network } = state.metamask;
const { provider } = state.metamask;
const { rpcUrl, chainId, ticker, nickname, type } = provider;
const setProviderArgs =
@ -15,7 +15,7 @@ const mapStateToProps = (state) => {
: [provider.type];
return {
isLoadingNetwork: network === 'loading',
isNetworkLoading: isNetworkLoading(state),
loadingMessage,
setProviderArgs,
provider,

View File

@ -1,6 +1,6 @@
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { getNetworkDisplayName } from '../../../../../../app/scripts/controllers/network/util';
import { NETWORK_TO_NAME_MAP } from '../../../../../../shared/constants/network';
import Button from '../../../ui/button';
export default class DepositEtherModal extends Component {
@ -10,7 +10,7 @@ export default class DepositEtherModal extends Component {
};
static propTypes = {
network: PropTypes.string.isRequired,
chainId: PropTypes.string.isRequired,
isTestnet: PropTypes.bool.isRequired,
isMainnet: PropTypes.bool.isRequired,
toWyre: PropTypes.func.isRequired,
@ -21,10 +21,6 @@ export default class DepositEtherModal extends Component {
showAccountDetailModal: PropTypes.func.isRequired,
};
faucetRowText = (networkName) => {
return this.context.t('getEtherFromFaucet', [networkName]);
};
goToAccountDetailsModal = () => {
this.props.hideWarning();
this.props.hideModal();
@ -89,14 +85,14 @@ export default class DepositEtherModal extends Component {
render() {
const {
network,
chainId,
toWyre,
address,
toFaucet,
isTestnet,
isMainnet,
} = this.props;
const networkName = getNetworkDisplayName(network);
const networkName = NETWORK_TO_NAME_MAP[chainId];
return (
<div className="page-container page-container--full-width page-container--full-height">
@ -162,9 +158,9 @@ export default class DepositEtherModal extends Component {
{this.renderRow({
logo: <i className="fa fa-tint fa-2x" />,
title: this.context.t('testFaucet'),
text: this.faucetRowText(networkName),
text: this.context.t('getEtherFromFaucet', [networkName]),
buttonLabel: this.context.t('getEther'),
onButtonClick: () => toFaucet(network),
onButtonClick: () => toFaucet(chainId),
hide: !isTestnet,
})}
</div>

View File

@ -5,15 +5,20 @@ import {
showModal,
hideWarning,
} from '../../../../store/actions';
import { getIsTestnet, getIsMainnet } from '../../../../selectors/selectors';
import {
getIsTestnet,
getIsMainnet,
getCurrentChainId,
getSelectedAddress,
} from '../../../../selectors/selectors';
import DepositEtherModal from './deposit-ether-modal.component';
function mapStateToProps(state) {
return {
network: state.metamask.network,
chainId: getCurrentChainId(state),
isTestnet: getIsTestnet(state),
isMainnet: getIsMainnet(state),
address: state.metamask.selectedAddress,
address: getSelectedAddress(state),
};
}
@ -31,7 +36,7 @@ function mapDispatchToProps(dispatch) {
showAccountDetailModal: () => {
dispatch(showModal({ name: 'ACCOUNT_DETAILS' }));
},
toFaucet: (network) => dispatch(buyEth({ network })),
toFaucet: (chainId) => dispatch(buyEth({ chainId })),
};
}

View File

@ -16,6 +16,7 @@ import {
} from '../../../helpers/constants/design-system';
import Chip from '../../ui/chip/chip';
import { useI18nContext } from '../../../hooks/useI18nContext';
import { isNetworkLoading } from '../../../selectors';
export default function NetworkDisplay({
colored,
@ -27,14 +28,14 @@ export default function NetworkDisplay({
targetNetwork,
onClick,
}) {
const networkIsLoading = useSelector(isNetworkLoading);
const currentNetwork = useSelector((state) => ({
network: state.metamask.network,
nickname: state.metamask.provider.nickname,
type: state.metamask.provider.type,
}));
const t = useI18nContext();
const { network = '', nickname: networkNickname, type: networkType } =
const { nickname: networkNickname, type: networkType } =
targetNetwork ?? currentNetwork;
return (
@ -45,7 +46,7 @@ export default function NetworkDisplay({
<LoadingIndicator
alt={t('attemptingConnect')}
title={t('attemptingConnect')}
isLoading={network === 'loading'}
isLoading={networkIsLoading}
>
<ColorIndicator
color={networkType === NETWORK_TYPE_RPC ? COLORS.UI4 : networkType}

View File

@ -4,6 +4,14 @@ import BigNumber from 'bignumber.js';
import ethUtil from 'ethereumjs-util';
import { DateTime } from 'luxon';
import { addHexPrefix } from '../../../../app/scripts/lib/util';
import {
GOERLI_CHAIN_ID,
KOVAN_CHAIN_ID,
LOCALHOST_CHAIN_ID,
MAINNET_CHAIN_ID,
RINKEBY_CHAIN_ID,
ROPSTEN_CHAIN_ID,
} from '../../../../shared/constants/network';
// formatData :: ( date: <Unix Timestamp> ) -> String
export function formatDate(date, format = "M/d/y 'at' T") {
@ -40,14 +48,19 @@ Object.keys(valueTable).forEach((currency) => {
bnTable[currency] = new ethUtil.BN(valueTable[currency], 10);
});
export function isEthNetwork(netId) {
/**
* Determines if the provided chainId is a default MetaMask chain
* @param {string} chainId - chainId to check
*/
export function isDefaultMetaMaskChain(chainId) {
if (
!netId ||
netId === '1' ||
netId === '3' ||
netId === '4' ||
netId === '42' ||
netId === '1337'
!chainId ||
chainId === MAINNET_CHAIN_ID ||
chainId === ROPSTEN_CHAIN_ID ||
chainId === RINKEBY_CHAIN_ID ||
chainId === KOVAN_CHAIN_ID ||
chainId === GOERLI_CHAIN_ID ||
chainId === LOCALHOST_CHAIN_ID
) {
return true;
}

View File

@ -1,7 +1,7 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import TokenTracker from '@metamask/eth-token-tracker';
import { useSelector } from 'react-redux';
import { getCurrentNetwork, getSelectedAddress } from '../selectors';
import { getCurrentChainId, getSelectedAddress } from '../selectors';
import { useEqualityCheck } from './useEqualityCheck';
export function useTokenTracker(
@ -9,7 +9,7 @@ export function useTokenTracker(
includeFailedTokens = false,
hideZeroBalanceTokens = false,
) {
const network = useSelector(getCurrentNetwork);
const chainId = useSelector(getCurrentChainId);
const userAddress = useSelector(getSelectedAddress);
const [loading, setLoading] = useState(() => tokens?.length >= 0);
const [tokensWithBalances, setTokensWithBalances] = useState([]);
@ -74,14 +74,14 @@ export function useTokenTracker(
// Effect to set loading state and initialize tracker when values change
useEffect(() => {
// This effect will only run initially and when:
// 1. network is updated,
// 1. chainId is updated,
// 2. userAddress is changed,
// 3. token list is updated and not equal to previous list
// in any of these scenarios, we should indicate to the user that their token
// values are in the process of updating by setting loading state.
setLoading(true);
if (!userAddress || network === 'loading' || !global.ethereumProvider) {
if (!userAddress || chainId === undefined || !global.ethereumProvider) {
// If we do not have enough information to build a TokenTracker, we exit early
// When the values above change, the effect will be restarted. We also teardown
// tracker because inevitably this effect will run again momentarily.
@ -98,7 +98,7 @@ export function useTokenTracker(
}, [
userAddress,
teardownTracker,
network,
chainId,
memoizedTokens,
updateBalances,
buildTracker,

View File

@ -72,7 +72,7 @@ export default class Routes extends Component {
loadingMessage: PropTypes.string,
alertMessage: PropTypes.string,
textDirection: PropTypes.string,
network: PropTypes.string,
isNetworkLoading: PropTypes.bool,
provider: PropTypes.object,
frequentRpcListDetail: PropTypes.array,
sidebar: PropTypes.object,
@ -267,7 +267,7 @@ export default class Routes extends Component {
alertMessage,
textDirection,
loadingMessage,
network,
isNetworkLoading,
provider,
frequentRpcListDetail,
setMouseUserState,
@ -276,9 +276,8 @@ export default class Routes extends Component {
isMouseUser,
prepareToLeaveSwaps,
} = this.props;
const isLoadingNetwork = network === 'loading';
const loadMessage =
loadingMessage || isLoadingNetwork
loadingMessage || isNetworkLoading
? this.getConnectingLabel(loadingMessage)
: null;
@ -340,7 +339,7 @@ export default class Routes extends Component {
<AccountMenu />
<div className="main-container-wrapper">
{isLoading && <Loading loadingMessage={loadMessage} />}
{!isLoading && isLoadingNetwork && <LoadingNetwork />}
{!isLoading && isNetworkLoading && <LoadingNetwork />}
{this.renderRoutes()}
</div>
{isUnlocked ? <Alerts history={this.props.history} /> : null}

View File

@ -4,6 +4,7 @@ import { compose } from 'redux';
import {
getNetworkIdentifier,
getPreferences,
isNetworkLoading,
submittedPendingTransactionsSelector,
} from '../../selectors';
import {
@ -37,7 +38,7 @@ function mapStateToProps(state) {
loadingMessage,
isUnlocked: state.metamask.isUnlocked,
submittedPendingTransactions: submittedPendingTransactionsSelector(state),
network: state.metamask.network,
isNetworkLoading: isNetworkLoading(state),
provider: state.metamask.provider,
frequentRpcListDetail: state.metamask.frequentRpcListDetail || [],
currentCurrency: state.metamask.currentCurrency,

View File

@ -12,18 +12,18 @@ import {
import {
isValidAddress,
isEthNetwork,
checkExistingAddresses,
isValidDomainName,
isOriginContractAddress,
isDefaultMetaMaskChain,
} from '../../../../helpers/utils/util';
export function getToErrorObject(to, sendTokenAddress, network) {
export function getToErrorObject(to, sendTokenAddress, chainId) {
let toError = null;
if (!to) {
toError = REQUIRED_ERROR;
} else if (!isValidAddress(to)) {
toError = isEthNetwork(network)
toError = isDefaultMetaMaskChain(chainId)
? INVALID_RECIPIENT_ADDRESS_ERROR
: INVALID_RECIPIENT_ADDRESS_NOT_ETH_NETWORK_ERROR;
} else if (isOriginContractAddress(to, sendTokenAddress)) {

View File

@ -36,7 +36,7 @@ export default class SendTransactionScreen extends Component {
gasPrice: PropTypes.string,
gasTotal: PropTypes.string,
history: PropTypes.object,
network: PropTypes.string,
chainId: PropTypes.string,
primaryCurrency: PropTypes.string,
resetSendState: PropTypes.func.isRequired,
selectedAddress: PropTypes.string,
@ -84,7 +84,7 @@ export default class SendTransactionScreen extends Component {
conversionRate,
from: { address, balance },
gasTotal,
network,
chainId,
primaryCurrency,
sendToken,
tokenBalance,
@ -106,7 +106,7 @@ export default class SendTransactionScreen extends Component {
from: { balance: prevBalance },
gasTotal: prevGasTotal,
tokenBalance: prevTokenBalance,
network: prevNetwork,
chainId: prevChainId,
sendToken: prevSendToken,
to: prevTo,
} = prevProps;
@ -146,7 +146,7 @@ export default class SendTransactionScreen extends Component {
}
if (!uninitialized) {
if (network !== prevNetwork && network !== 'loading') {
if (chainId !== prevChainId && chainId !== undefined) {
updateSendTokenBalance({
sendToken,
tokenContract,
@ -259,7 +259,7 @@ export default class SendTransactionScreen extends Component {
}
validate(query) {
const { tokens, sendToken, network, sendTokenAddress } = this.props;
const { tokens, sendToken, chainId, sendTokenAddress } = this.props;
const { internalSearch } = this.state;
@ -268,7 +268,7 @@ export default class SendTransactionScreen extends Component {
return;
}
const toErrorObject = getToErrorObject(query, sendTokenAddress, network);
const toErrorObject = getToErrorObject(query, sendTokenAddress, chainId);
const toWarningObject = getToWarningObject(query, tokens, sendToken);
this.setState({

View File

@ -5,7 +5,6 @@ import { compose } from 'redux';
import {
getBlockGasLimit,
getConversionRate,
getCurrentNetwork,
getGasLimit,
getGasPrice,
getGasTotal,
@ -24,6 +23,7 @@ import {
getAddressBook,
getSendTokenAddress,
isCustomPriceExcessive,
getCurrentChainId,
} from '../../selectors';
import {
@ -56,7 +56,7 @@ function mapStateToProps(state) {
gasLimit: getGasLimit(state),
gasPrice: getGasPrice(state),
gasTotal: getGasTotal(state),
network: getCurrentNetwork(state),
chainId: getCurrentChainId(state),
primaryCurrency: getPrimaryCurrency(state),
qrCodeData: getQrCodeData(state),
selectedAddress: getSelectedAddress(state),

View File

@ -9,6 +9,10 @@ import AddRecipient from '../send-content/add-recipient/add-recipient.container'
import SendHeader from '../send-header/send-header.container';
import SendContent from '../send-content/send-content.container';
import SendFooter from '../send-footer/send-footer.container';
import {
RINKEBY_CHAIN_ID,
ROPSTEN_CHAIN_ID,
} from '../../../../../shared/constants/network';
describe('Send Component', function () {
let wrapper;
@ -59,7 +63,7 @@ describe('Send Component', function () {
gasPrice="mockGasPrice"
gasTotal="mockGasTotal"
history={{ mockProp: 'history-abc' }}
network="3"
chainId={ROPSTEN_CHAIN_ID}
primaryCurrency="mockPrimaryCurrency"
selectedAddress="mockSelectedAddress"
sendToken={{ address: 'mockTokenAddress', decimals: 18, symbol: 'TST' }}
@ -287,7 +291,7 @@ describe('Send Component', function () {
from: {
balance: 'balanceChanged',
},
network: '3',
chainId: ROPSTEN_CHAIN_ID,
sendToken: { address: 'mockTokenAddress', decimals: 18, symbol: 'TST' }, // Make sure not to hit updateGas when changing asset
});
assert.strictEqual(propsMethodSpies.updateSendTokenBalance.callCount, 0);
@ -298,14 +302,14 @@ describe('Send Component', function () {
});
it('should not call updateSendTokenBalance or this.updateGas if network === loading', function () {
wrapper.setProps({ network: 'loading' });
wrapper.setProps({ chainId: undefined });
SendTransactionScreen.prototype.updateGas.resetHistory();
propsMethodSpies.updateSendTokenBalance.resetHistory();
wrapper.instance().componentDidUpdate({
from: {
balance: 'balanceChanged',
},
network: '3',
chainId: ROPSTEN_CHAIN_ID,
sendToken: { address: 'mockTokenAddress', decimals: 18, symbol: 'TST' }, // Make sure not to hit updateGas when changing asset
});
assert.strictEqual(propsMethodSpies.updateSendTokenBalance.callCount, 0);
@ -322,7 +326,7 @@ describe('Send Component', function () {
from: {
balance: 'balanceChanged',
},
network: '2',
chainId: RINKEBY_CHAIN_ID,
sendToken: { address: 'mockTokenAddress', decimals: 18, symbol: 'TST' }, // Make sure not to hit updateGas when changing asset
});
assert.strictEqual(propsMethodSpies.updateSendTokenBalance.callCount, 1);
@ -355,7 +359,7 @@ describe('Send Component', function () {
from: {
balance: 'balancedChanged',
},
network: '3', // Make sure not to hit updateGas when changing network
chainId: ROPSTEN_CHAIN_ID, // Make sure not to hit updateGas when changing network
sendToken: { address: 'newSelectedToken' },
});
assert.strictEqual(
@ -482,7 +486,7 @@ describe('Send Component', function () {
});
it('should validate when input changes and has error on a bad network', function () {
wrapper.setProps({ network: 'bad' });
wrapper.setProps({ chainId: 'bad' });
const instance = wrapper.instance();
instance.onRecipientInputChange(
'0x80F061544cC398520615B5d3e7a3BedD70cd4510',
@ -498,7 +502,7 @@ describe('Send Component', function () {
});
it('should synchronously validate when input changes to ""', function () {
wrapper.setProps({ network: 'bad' });
wrapper.setProps({ chainId: 'bad' });
const instance = wrapper.instance();
instance.onRecipientInputChange(
'0x80F061544cC398520615B5d3e7a3BedD70cd4510',

View File

@ -11,7 +11,7 @@ import {
} from '../helpers/utils/confirm-tx.util';
import { sumHexes } from '../helpers/utils/transactions.util';
import { transactionMatchesNetwork } from '../../../shared/modules/transaction.utils';
import { getCurrentChainId, getCurrentNetworkId } from './selectors';
import { getCurrentChainId, deprecatedGetCurrentNetworkId } from './selectors';
import { getNativeCurrency } from '.';
const unapprovedTxsSelector = (state) => state.metamask.unapprovedTxs;
@ -32,7 +32,7 @@ export const unconfirmedTransactionsListSelector = createSelector(
unapprovedDecryptMsgsSelector,
unapprovedEncryptionPublicKeyMsgsSelector,
unapprovedTypedMessagesSelector,
getCurrentNetworkId,
deprecatedGetCurrentNetworkId,
getCurrentChainId,
(
unapprovedTxs = {},
@ -63,7 +63,7 @@ export const unconfirmedTransactionsHashSelector = createSelector(
unapprovedDecryptMsgsSelector,
unapprovedEncryptionPublicKeyMsgsSelector,
unapprovedTypedMessagesSelector,
getCurrentNetworkId,
deprecatedGetCurrentNetworkId,
getCurrentChainId,
(
unapprovedTxs = {},
@ -118,7 +118,7 @@ export const unconfirmedTransactionsCountSelector = createSelector(
unapprovedDecryptMsgCountSelector,
unapprovedEncryptionPublicKeyMsgCountSelector,
unapprovedTypedMessagesCountSelector,
getCurrentNetworkId,
deprecatedGetCurrentNetworkId,
getCurrentChainId,
(
unapprovedTxs = {},

View File

@ -17,6 +17,18 @@ import {
} from '../helpers/utils/conversions.util';
import { ETH_SWAPS_TOKEN_OBJECT } from '../helpers/constants/swaps';
/**
* One of the only remaining valid uses of selecting the network subkey of the
* metamask state tree is to determine if the network is currently 'loading'.
*
* This will be used for all cases where this state key is accessed only for that
* purpose.
* @param {Object} state - redux state object
*/
export function isNetworkLoading(state) {
return state.metamask.network === 'loading';
}
export function getNetworkIdentifier(state) {
const {
metamask: {
@ -71,7 +83,16 @@ export function getAccountType(state) {
}
}
export function getCurrentNetworkId(state) {
/**
* get the currently selected networkId which will be 'loading' when the
* network changes. The network id should not be used in most cases,
* instead use chainId in most situations. There are a limited number of
* use cases to use this method still, such as when comparing transaction
* metadata that predates the switch to using chainId.
* @deprecated - use getCurrentChainId instead
* @param {Object} state - redux state object
*/
export function deprecatedGetCurrentNetworkId(state) {
return state.metamask.network;
}
@ -136,7 +157,7 @@ export function getMetaMaskCachedBalances(state) {
// Fallback to fetching cached balances from network id
// this can eventually be removed
const network = getCurrentNetworkId(state);
const network = deprecatedGetCurrentNetworkId(state);
return (
state.metamask.cachedBalances[chainId] ??
@ -347,17 +368,6 @@ export function getDomainMetadata(state) {
return state.metamask.domainMetadata;
}
export const getBackgroundMetaMetricState = (state) => {
return {
network: getCurrentNetworkId(state),
accountType: getAccountType(state),
metaMetricsId: state.metamask.metaMetricsId,
numberOfTokens: getNumberOfTokens(state),
numberOfAccounts: getNumberOfAccounts(state),
participateInMetaMetrics: state.metamask.participateInMetaMetrics,
};
};
export function getRpcPrefsForCurrentProvider(state) {
const { frequentRpcListDetail, provider } = state.metamask;
const selectRpcInfo = frequentRpcListDetail.find(

View File

@ -20,10 +20,6 @@ export function getNativeCurrency(state) {
return state.metamask.nativeCurrency;
}
export function getCurrentNetwork(state) {
return state.metamask.network;
}
export function getGasLimit(state) {
return state.metamask.send.gasLimit || '0';
}

View File

@ -8,7 +8,6 @@ import { TRANSACTION_STATUSES } from '../../../../shared/constants/transaction';
import {
getBlockGasLimit,
getConversionRate,
getCurrentNetwork,
getNativeCurrency,
getGasLimit,
getGasPrice,
@ -116,12 +115,6 @@ describe('send selectors', function () {
});
});
describe('getCurrentNetwork()', function () {
it('should return the id of the currently selected network', function () {
assert.strictEqual(getCurrentNetwork(mockState), '3');
});
});
describe('getGasLimit()', function () {
it('should return the send.gasLimit', function () {
assert.strictEqual(getGasLimit(mockState), '0xFFFF');

View File

@ -10,7 +10,7 @@ import {
TRANSACTION_TYPES,
} from '../../../shared/constants/transaction';
import { transactionMatchesNetwork } from '../../../shared/modules/transaction.utils';
import { getCurrentChainId, getCurrentNetworkId } from './selectors';
import { getCurrentChainId, deprecatedGetCurrentNetworkId } from './selectors';
import { getSelectedAddress } from '.';
export const incomingTxListSelector = (state) => {
@ -58,7 +58,7 @@ export const unapprovedMessagesSelector = createSelector(
unapprovedDecryptMsgsSelector,
unapprovedEncryptionPublicKeyMsgsSelector,
unapprovedTypedMessagesSelector,
getCurrentNetworkId,
deprecatedGetCurrentNetworkId,
getCurrentChainId,
(
unapprovedMsgs = {},