Skip to content

Commit

Permalink
Remove additional selector usages
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewwalsh0 committed Nov 5, 2024
1 parent 64e464e commit 43317f9
Show file tree
Hide file tree
Showing 17 changed files with 102 additions and 28 deletions.
21 changes: 14 additions & 7 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -478,13 +478,20 @@ module.exports = {
'no-restricted-syntax': [
'error',
{
selector:
'ImportSpecifier[imported.name=/' +
'(getCurrentChainId)|' +
'(getNativeCurrency)|' +
'(getProviderConfig)|' +
'(getRpcPrefsForCurrentProvider)|' +
'(getConversionRate)/]',
selector: `ImportSpecifier[imported.name=/${[
'getConversionRate',
'getCurrentChainId',
'getNativeCurrency',
'getNetworkIdentifier',
'getNftContracts',
'getNfts',
'getProviderConfig',
'getRpcPrefsForCurrentProvider',
'getUSDConversionRate',
'isCurrentProviderCustom',
]
.map((method) => `(${method})`)
.join('|')}/]`,
message: 'Avoid using global network selectors in confirmations',
},
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
} from '../../../../../helpers/constants/design-system';
import {
getAdvancedGasFeeValues,
getNetworkIdentifier,
selectNetworkIdentifierByChainId,
} from '../../../../../selectors';
import { setAdvancedGasFee } from '../../../../../store/actions';
import { useGasFeeContext } from '../../../../../contexts/gasFee';
Expand All @@ -34,10 +34,14 @@ const AdvancedGasFeeDefaults = () => {
10,
).toString();
const advancedGasFeeValues = useSelector(getAdvancedGasFeeValues);
const networkIdentifier = useSelector(getNetworkIdentifier);
const { updateTransactionEventFragment } = useTransactionEventFragment();
const { editGasMode, transaction } = useGasFeeContext();
const { chainId } = transaction;

const networkIdentifier = useSelector((state) =>
selectNetworkIdentifierByChainId(state, chainId),
);

const [isDefaultSettingsSelected, setDefaultSettingsSelected] = useState(
Boolean(advancedGasFeeValues) &&
advancedGasFeeValues.maxBaseFee === maxBaseFee &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { mockNetworkState } from '../../../../../../test/stub/networks';
import AdvancedGasFeeDefaults from './advanced-gas-fee-defaults';

const TEXT_SELECTOR = 'Save these values as my default for the Goerli network.';
const CHAIN_ID_MOCK = CHAIN_IDS.GOERLI;

jest.mock('../../../../../store/actions', () => ({
gasFeeStartPollingByNetworkClientId: jest
Expand All @@ -43,7 +44,7 @@ const render = async (defaultGasParams, contextParams) => {
metamask: {
...mockState.metamask,
...defaultGasParams,
...mockNetworkState({ chainId: CHAIN_IDS.GOERLI }),
...mockNetworkState({ chainId: CHAIN_ID_MOCK }),
accounts: {
[mockSelectedInternalAccount.address]: {
address: mockSelectedInternalAccount.address,
Expand Down Expand Up @@ -71,6 +72,7 @@ const render = async (defaultGasParams, contextParams) => {
(result = renderWithProvider(
<GasFeeContextProvider
transaction={{
chainId: CHAIN_ID_MOCK,
userFeeLevel: 'medium',
}}
{...contextParams}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ import {
getAddressBookEntry,
getInternalAccounts,
getMetadataContractName,
getNetworkIdentifier,
getSwapsDefaultToken,
selectNetworkIdentifierByChainId,
} from '../../../../selectors';
import useRamps from '../../../../hooks/ramps/useRamps/useRamps';
///: BEGIN:ONLY_INCLUDE_IF(build-main,build-beta,build-flask)
Expand Down Expand Up @@ -120,7 +120,6 @@ const ConfirmPageContainer = (props) => {
useState(false);
const isBuyableChain = useSelector(getIsNativeTokenBuyable);
const contact = useSelector((state) => getAddressBookEntry(state, toAddress));
const networkIdentifier = useSelector(getNetworkIdentifier);
const defaultToken = useSelector(getSwapsDefaultToken);
const accountBalance = defaultToken.string;
const internalAccounts = useSelector(getInternalAccounts);
Expand All @@ -139,8 +138,13 @@ const ConfirmPageContainer = (props) => {
const shouldDisplayWarning =
contentComponent && disabled && (errorKey || errorMessage);

const networkName =
NETWORK_TO_NAME_MAP[currentTransaction.chainId] || networkIdentifier;
const { chainId } = currentTransaction;

const networkIdentifier = useSelector((state) =>
selectNetworkIdentifierByChainId(state, chainId),
);

const networkName = NETWORK_TO_NAME_MAP[chainId] || networkIdentifier;

const fetchCollectionBalance = useCallback(async () => {
const tokenBalance = await fetchTokenBalance(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { connect } from 'react-redux';
import {
getAddressBookEntry,
getNetworkIdentifier,
getSwapsDefaultToken,
getMetadataContractName,
getAccountName,
Expand All @@ -12,7 +11,6 @@ import ConfirmPageContainer from './confirm-page-container.component';
function mapStateToProps(state, ownProps) {
const to = ownProps.toAddress;
const contact = getAddressBookEntry(state, to);
const networkIdentifier = getNetworkIdentifier(state);
const defaultToken = getSwapsDefaultToken(state);
const accountBalance = defaultToken.string;
const internalAccounts = getInternalAccounts(state);
Expand All @@ -26,7 +24,6 @@ function mapStateToProps(state, ownProps) {
toMetadataName,
recipientIsOwnedAccount: Boolean(ownedAccountName),
to,
networkIdentifier,
accountBalance,
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export const ApproveStaticSimulation = () => {
transactionMeta?.txParams?.to,
transactionMeta?.txParams?.from,
transactionMeta?.txParams?.data,
transactionMeta?.chainId,
);

const decimals = initialDecimals || '0';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const ApproveInfo = () => {
transactionMeta.txParams.to,
transactionMeta.txParams.from,
transactionMeta.txParams.data,
transactionMeta.chainId,
);

const { spendingCap, pending } = useApproveTokenSimulation(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export const EditSpendingCapModal = ({
transactionMeta.txParams.to,
transactionMeta.txParams.from,
transactionMeta.txParams.data,
transactionMeta.chainId,
);

const accountBalance = calcTokenAmount(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ export const SpendingCap = ({
transactionMeta.txParams.to,
transactionMeta.txParams.from,
transactionMeta.txParams.data,
transactionMeta.chainId,
);

const accountBalance = calcTokenAmount(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export const useTokenValues = (transactionMeta: TransactionMeta) => {
transactionMeta.txParams.to,
transactionMeta.txParams.from,
transactionMeta.txParams.data,
transactionMeta.chainId,
);

const decodedResponse = useDecodedTransactionData();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ const NFTSendHeading = () => {
const tokenAddress = transactionMeta.txParams.to;
const userAddress = transactionMeta.txParams.from;
const { data } = transactionMeta.txParams;
const { chainId } = transactionMeta;

const { assetName, tokenImage, tokenId } = useAssetDetails(
tokenAddress,
userAddress,
data,
chainId,
);

const TokenImage = <AvatarToken src={tokenImage} size={AvatarTokenSize.Xl} />;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,14 @@ export function useCurrentSpendingCap(currentConfirmation: Confirmation) {
const txParamsData = isTxWithSpendingCap
? currentConfirmation.txParams.data
: null;
const chainId = isTxWithSpendingCap ? currentConfirmation.chainId : null;

const { decimals } = useAssetDetails(txParamsTo, txParamsFrom, txParamsData);
const { decimals } = useAssetDetails(
txParamsTo,
txParamsFrom,
txParamsData,
chainId,
);

const { spendingCap, pending } = useApproveTokenSimulation(
currentConfirmation as TransactionMeta,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ import {
getSelectedInternalAccount,
selectConversionRateByChainId,
selectNetworkConfigurationByChainId,
selectNftContractsByChainId,
} from '../../../selectors';
import { getNftContracts } from '../../../ducks/metamask/metamask';
import { TokenStandard } from '../../../../shared/constants/transaction';
import {
getWeiHexFromDecimalValue,
Expand Down Expand Up @@ -61,7 +61,10 @@ export default function ConfirmTokenTransactionBase({
);

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

const nftCollections = useSelector((state) =>
selectNftContractsByChainId(state, chainId),
);

const ethTransactionTotalMaxAmount = Number(
hexWEIToDecETH(hexMaximumTransactionFee),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { useAssetDetails } from '../hooks/useAssetDetails';

export default function ConfirmTokenTransactionSwitch({ transaction }) {
const {
chainId,
txParams: { data, to: tokenAddress, from: userAddress } = {},
layer1GasFee,
} = transaction;
Expand All @@ -44,7 +45,7 @@ export default function ConfirmTokenTransactionSwitch({ transaction }) {
tokenAmount,
tokenId,
toAddress,
} = useAssetDetails(tokenAddress, userAddress, data);
} = useAssetDetails(tokenAddress, userAddress, data, chainId);

const {
ethTransactionTotal,
Expand Down Expand Up @@ -221,6 +222,7 @@ export default function ConfirmTokenTransactionSwitch({ transaction }) {

ConfirmTokenTransactionSwitch.propTypes = {
transaction: PropTypes.shape({
chainId: PropTypes.string,
origin: PropTypes.string,
txParams: PropTypes.shape({
data: PropTypes.string,
Expand Down
13 changes: 10 additions & 3 deletions ui/pages/confirmations/hooks/useAssetDetails.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { isEqual } from 'lodash';
import { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { getNfts, getTokens } from '../../../ducks/metamask/metamask';
import { getTokens } from '../../../ducks/metamask/metamask';
import { getAssetDetails } from '../../../helpers/utils/token-util';
import {
hideLoadingIndication,
Expand All @@ -10,11 +10,18 @@ import {
import { isEqualCaseInsensitive } from '../../../../shared/modules/string-utils';
import { usePrevious } from '../../../hooks/usePrevious';
import { useTokenTracker } from '../../../hooks/useTokenTracker';
import { selectNftsByChainId } from '../../../selectors';

export function useAssetDetails(tokenAddress, userAddress, transactionData) {
export function useAssetDetails(
tokenAddress,
userAddress,
transactionData,
chainId,
) {
const dispatch = useDispatch();

// state selectors
const nfts = useSelector(getNfts);
const nfts = useSelector((state) => selectNftsByChainId(state, chainId));
const tokens = useSelector(getTokens, isEqual);
const currentToken = tokens.find((token) =>
isEqualCaseInsensitive(token.address, tokenAddress),
Expand Down
14 changes: 10 additions & 4 deletions ui/pages/confirmations/token-allowance/token-allowance.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import { PageContainerFooter } from '../../../components/ui/page-container';
import ContractDetailsModal from '../components/contract-details-modal/contract-details-modal';
import {
getCustomTokenAmount,
getNetworkIdentifier,
transactionFeeSelector,
getKnownMethodData,
getUnapprovedTxCount,
Expand Down Expand Up @@ -76,8 +75,11 @@ import FeeDetailsComponent from '../components/fee-details-component/fee-details
import { BlockaidResultType } from '../../../../shared/constants/security-provider';
import { QueuedRequestsBannerAlert } from '../confirmation/components/queued-requests-banner-alert/queued-requests-banner-alert';

// eslint-disable-next-line import/no-duplicates
import { selectNetworkConfigurationByChainId } from '../../../selectors/selectors';
import {
selectNetworkConfigurationByChainId,
selectNetworkIdentifierByChainId,
// eslint-disable-next-line import/no-duplicates
} from '../../../selectors/selectors';

///: BEGIN:ONLY_INCLUDE_IF(build-mmi)
// eslint-disable-next-line import/no-duplicates
Expand Down Expand Up @@ -145,9 +147,13 @@ export default function TokenAllowance({
const fromAccount = useSelector((state) =>
getTargetAccountWithSendEtherInfo(state, userAddress),
);
const networkIdentifier = useSelector(getNetworkIdentifier);

const { chainId } = txData;

const networkIdentifier = useSelector((state) =>
selectNetworkIdentifierByChainId(state, chainId),
);

const { blockExplorerUrls } =
useSelector((state) =>
selectNetworkConfigurationByChainId(state, chainId),
Expand Down
29 changes: 29 additions & 0 deletions ui/selectors/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -750,6 +750,35 @@ export const selectConversionRateByChainId = createSelector(
},
);

export const selectNftsByChainId = createSelector(
getSelectedInternalAccount,
(state) => state.metamask.allNfts,
(_state, chainId) => chainId,
(selectedAccount, nfts, chainId) => {
return nfts?.[selectedAccount.address]?.[chainId] ?? [];
},
);

export const selectNftContractsByChainId = createSelector(
getSelectedInternalAccount,
(state) => state.metamask.allNftContracts,
(_state, chainId) => chainId,
(selectedAccount, nftContracts, chainId) => {
return nftContracts?.[selectedAccount.address]?.[chainId] ?? [];
},
);

export const selectNetworkIdentifierByChainId = createSelector(
selectNetworkConfigurationByChainId,
selectDefaultRpcEndpointByChainId,
(networkConfiguration, defaultRpcEndpoint) => {
const { name: nickname } = networkConfiguration ?? {};
const { url: rpcUrl, networkClientId } = defaultRpcEndpoint ?? {};

return nickname || rpcUrl || networkClientId;
},
);

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 43317f9

Please sign in to comment.