Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: initial setup for not globally selected chain ID (useChainId hook) #11753

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
2 changes: 0 additions & 2 deletions app/components/UI/CollectibleContractElement/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import Engine from '../../../core/Engine';
import { removeFavoriteCollectible } from '../../../actions/collectibles';
import { collectibleContractsSelector } from '../../../reducers/collectibles';
import { useTheme } from '../../../util/theme';
import { selectChainId } from '../../../selectors/networkController';
import { selectSelectedInternalAccountChecksummedAddress } from '../../../selectors/accountsController';
import Icon, {
IconName,
Expand Down Expand Up @@ -315,7 +314,6 @@ CollectibleContractElement.propTypes = {

const mapStateToProps = (state) => ({
collectibleContracts: collectibleContractsSelector(state),
chainId: selectChainId(state),
selectedAddress: selectSelectedInternalAccountChecksummedAddress(state),
});

Expand Down
22 changes: 9 additions & 13 deletions app/components/UI/CollectibleContracts/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,7 @@ import { compareTokenIds } from '../../../util/tokens';
import CollectibleDetectionModal from '../CollectibleDetectionModal';
import { useTheme } from '../../../util/theme';
import { MAINNET } from '../../../constants/network';
import {
selectChainId,
selectProviderType,
} from '../../../selectors/networkController';
import { selectProviderType } from '../../../selectors/networkController';
import {
selectDisplayNftMedia,
selectIsIpfsGatewayEnabled,
Expand All @@ -43,6 +40,7 @@ import { WalletViewSelectorsIDs } from '../../../../e2e/selectors/wallet/WalletV
import { useMetrics } from '../../../components/hooks/useMetrics';
import { RefreshTestId, SpinnerTestId } from './constants';
import { debounce } from 'lodash';
import { useChainId } from '../../../selectors/hooks';

const createStyles = (colors) =>
StyleSheet.create({
Expand Down Expand Up @@ -100,7 +98,6 @@ const debouncedNavigation = debounce((navigation, collectible) => {
*/
const CollectibleContracts = ({
selectedAddress,
chainId,
networkType,
navigation,
collectibleContracts,
Expand Down Expand Up @@ -131,6 +128,8 @@ const CollectibleContracts = ({
[navigation],
);

const chainId = useChainId();

/**
* Method that checks if the collectible is inside the collectibles array. If it is not it means the
* collectible has been ignored, hence we should not call the updateMetadata which executes the addNft fct
Expand Down Expand Up @@ -262,10 +261,11 @@ const CollectibleContracts = ({
key={item.address}
contractCollectibles={contractCollectibles}
collectiblesVisible={index === 0}
chainId={chainId}
/>
);
},
[collectibles, onItemPress],
[collectibles, onItemPress, chainId],
);

const renderFavoriteCollectibles = useCallback(() => {
Expand Down Expand Up @@ -388,10 +388,6 @@ CollectibleContracts.propTypes = {
* Network type
*/
networkType: PropTypes.string,
/**
* Chain id
*/
chainId: PropTypes.string,
/**
* Selected address
*/
Expand Down Expand Up @@ -438,7 +434,6 @@ CollectibleContracts.propTypes = {

const mapStateToProps = (state) => ({
networkType: selectProviderType(state),
chainId: selectChainId(state),
selectedAddress: selectSelectedInternalAccountChecksummedAddress(state),
useNftDetection: selectUseNftDetection(state),
collectibleContracts: collectibleContractsSelector(state),
Expand All @@ -450,8 +445,9 @@ const mapStateToProps = (state) => ({
});

const mapDispatchToProps = (dispatch) => ({
removeFavoriteCollectible: (selectedAddress, chainId, collectible) =>
dispatch(removeFavoriteCollectible(selectedAddress, chainId, collectible)),
removeFavoriteCollectible: (selectedAddress, chainId, collectible) => {
dispatch(removeFavoriteCollectible(selectedAddress, chainId, collectible));
},
});

export default connect(
Expand Down
12 changes: 7 additions & 5 deletions app/components/UI/Tokens/TokenList/TokenListItem/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { useTheme } from '../../../../../util/theme';
import { TOKEN_RATE_UNDEFINED } from '../../constants';
import { deriveBalanceFromAssetMarketDetails } from '../../util/deriveBalanceFromAssetMarketDetails';
import {
selectChainId,
selectProviderConfig,
selectTicker,
} from '../../../../../selectors/networkController';
Expand Down Expand Up @@ -54,20 +53,21 @@ interface TokenListItemProps {
showScamWarningModal: boolean;
showRemoveMenu: (arg: TokenI) => void;
setShowScamWarningModal: (arg: boolean) => void;
chainId: string;
}

export const TokenListItem = ({
asset,
showScamWarningModal,
showRemoveMenu,
setShowScamWarningModal,
chainId,
}: TokenListItemProps) => {
const navigation = useNavigation();
const { colors } = useTheme();
const { data: tokenBalances } = useTokenBalancesController();

const { type } = useSelector(selectProviderConfig);
const chainId = useSelector(selectChainId);
const ticker = useSelector(selectTicker);
const isOriginalNativeTokenSymbol = useIsOriginalNativeTokenSymbol(
chainId,
Expand Down Expand Up @@ -95,7 +95,7 @@ export const TokenListItem = ({
currentCurrency,
);

const pricePercentChange1d = itemAddress
const pricePercentChange1d = itemAddress?.startsWith('0x')
? tokenExchangeRates?.[itemAddress as `0x${string}`]?.pricePercentChange1d
: tokenExchangeRates?.[zeroAddress() as Hex]?.pricePercentChange1d;

Expand Down Expand Up @@ -158,10 +158,12 @@ export const TokenListItem = ({

if (isLineaMainnet) return images['LINEA-MAINNET'];

if (CustomNetworkImgMapping[chainId]) {
const isValidChainId = (id: string): id is `0x${string}` =>
/^0x[0-9a-fA-F]+$/.test(id);

if (isValidChainId(chainId) && CustomNetworkImgMapping[chainId]) {
return CustomNetworkImgMapping[chainId];
}

return ticker ? images[ticker] : undefined;
};

Expand Down
5 changes: 3 additions & 2 deletions app/components/UI/Tokens/TokenList/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
} from '../../../../components/hooks/useMetrics';
import { useTheme } from '../../../../util/theme';
import { createDetectedTokensNavDetails } from '../../../Views/DetectedTokens';
import { selectChainId } from '../../../../selectors/networkController';
import { selectDetectedTokens } from '../../../../selectors/tokensController';
import { getDecimalChainId } from '../../../../util/networks';
import createStyles from '../styles';
Expand All @@ -18,6 +17,7 @@ import { TokenI } from '../types';
import { strings } from '../../../../../locales/i18n';
import { TokenListFooter } from './TokenListFooter';
import { TokenListItem } from './TokenListItem';
import { useChainId } from '../../../../selectors/hooks';

interface TokenListProps {
tokens: TokenI[];
Expand All @@ -44,7 +44,7 @@ export const TokenList = ({
const { colors } = useTheme();
const { trackEvent } = useMetrics();

const chainId = useSelector(selectChainId);
const chainId = useChainId();
const detectedTokens = useSelector(selectDetectedTokens);

const [showScamWarningModal, setShowScamWarningModal] = useState(false);
Expand Down Expand Up @@ -80,6 +80,7 @@ export const TokenList = ({
renderItem={({ item }) => (
<TokenListItem
asset={item}
chainId={chainId}
showRemoveMenu={showRemoveMenu}
showScamWarningModal={showScamWarningModal}
setShowScamWarningModal={setShowScamWarningModal}
Expand Down
8 changes: 3 additions & 5 deletions app/components/UI/Tokens/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ import Engine from '../../../core/Engine';
import NotificationManager from '../../../core/NotificationManager';
import { MetaMetricsEvents } from '../../../core/Analytics';
import Logger from '../../../util/Logger';
import {
selectChainId,
selectNetworkClientId,
} from '../../../selectors/networkController';
import { selectNetworkClientId } from '../../../selectors/networkController';
import { getDecimalChainId } from '../../../util/networks';
import { isZero } from '../../../util/lodash';
import createStyles from './styles';
Expand All @@ -21,6 +18,7 @@ import { TokenI, TokensI } from './types';
import { WalletViewSelectorsIDs } from '../../../../e2e/selectors/wallet/WalletView.selectors';
import { strings } from '../../../../locales/i18n';
import { RootState } from '../../../reducers';
import { useChainId } from '../../../selectors/hooks';

// this will be imported from TokenRatesController when it is exported from there
// PR: https://github.com/MetaMask/core/pull/4622
Expand Down Expand Up @@ -53,7 +51,7 @@ const Tokens: React.FC<TokensI> = ({ tokens }) => {
const { trackEvent } = useMetrics();
const { data: tokenBalances } = useTokenBalancesController();

const chainId = useSelector(selectChainId);
const chainId = useChainId();
const networkClientId = useSelector(selectNetworkClientId);
const hideZeroBalanceTokens = useSelector(
(state: RootState) => state.settings.hideZeroBalanceTokens,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,17 @@ import { useNavigation } from '@react-navigation/native';
import Engine from '../../../core/Engine';
import { useMetrics } from '../../../components/hooks/useMetrics';
import { MetaMetricsEvents } from '../../../core/Analytics';
import { selectChainId } from '../../../selectors/networkController';
import { useSelector } from 'react-redux';
import { selectDisplayNftMedia } from '../../../selectors/preferencesController';
import { useChainId } from '../../../selectors/hooks';

const walletImage = require('../../../images/wallet-alpha.png');

const NFTAutoDetectionModal = () => {
const { styles } = useStyles(styleSheet, {});
const sheetRef = useRef<BottomSheetRef>(null);
const navigation = useNavigation();
const chainId = useSelector(selectChainId);
const chainId = useChainId();
const displayNftMedia = useSelector(selectDisplayNftMedia);
const { trackEvent } = useMetrics();
const enableNftDetectionAndDismissModal = useCallback(
Expand Down
8 changes: 3 additions & 5 deletions app/components/Views/NftDetails/NftDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,7 @@ import ClipboardManager from '../../../core/ClipboardManager';
import { useDispatch, useSelector } from 'react-redux';
import { showAlert } from '../../../actions/alert';
import { strings } from '../../../../locales/i18n';
import {
selectChainId,
selectTicker,
} from '../../../selectors/networkController';
import { selectTicker } from '../../../selectors/networkController';
import etherscanLink from '@metamask/etherscan-link';
import {
selectConversionRate,
Expand All @@ -47,11 +44,12 @@ import { renderShortText } from '../../../util/general';
import { prefixUrlWithProtocol } from '../../../util/browser';
import { formatTimestampToYYYYMMDD } from '../../../util/date';
import MAX_TOKEN_ID_LENGTH from './nftDetails.utils';
import { useChainId } from '../../../selectors/hooks';

const NftDetails = () => {
const navigation = useNavigation();
const { collectible } = useParams<NftDetailsParams>();
const chainId = useSelector(selectChainId);
const chainId = useChainId();
const dispatch = useDispatch();
const currentCurrency = useSelector(selectCurrentCurrency);
const ticker = useSelector(selectTicker);
Expand Down
29 changes: 16 additions & 13 deletions app/components/Views/Wallet/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ import { ButtonVariants } from '../../../component-library/components/Buttons/Bu
import { useListNotifications } from '../../../util/notifications/hooks/useNotifications';
import { PortfolioBalance } from '../../UI/Tokens/TokenList/PortfolioBalance';
import { isObject } from 'lodash';
import { useChainId } from '../../../selectors/hooks';

const createStyles = ({ colors, typography }: Theme) =>
StyleSheet.create({
base: {
Expand Down Expand Up @@ -178,6 +180,10 @@ const Wallet = ({
const dispatch = useDispatch();
const networkConfigurations = useSelector(selectNetworkConfigurations);

/**
* Selected chain id (with potential support for per-dapp selected chain)
*/
const chainId = useChainId();
/**
* Object containing the balance of the current selected account
*/
Expand Down Expand Up @@ -215,7 +221,7 @@ const Wallet = ({
* Provider configuration for the current selected network
*/
const providerConfig = useSelector(selectProviderConfig);
const prevChainId = usePrevious(providerConfig.chainId);
const prevChainId = usePrevious(chainId);

const isDataCollectionForMarketingEnabled = useSelector(
(state: RootState) => state.security.dataCollectionForMarketing,
Expand Down Expand Up @@ -324,9 +330,9 @@ const Wallet = ({
screen: Routes.SHEET.NETWORK_SELECTOR,
});
trackEvent(MetaMetricsEvents.NETWORK_SELECTOR_PRESSED, {
chain_id: getDecimalChainId(providerConfig.chainId),
chain_id: getDecimalChainId(chainId),
});
}, [navigate, providerConfig.chainId, trackEvent]);
}, [navigate, chainId, trackEvent]);

const isNetworkDuplicated = Object.values(networkConfigurations).some(
(networkConfiguration) =>
Expand All @@ -336,7 +342,7 @@ const Wallet = ({
);

const checkNftAutoDetectionModal = useCallback(() => {
const isOnMainnet = isMainNet(providerConfig.chainId);
const isOnMainnet = isMainNet(chainId);
if (!useNftDetection && isOnMainnet && !isNFTAutoDetectionModalViewed) {
navigation.navigate(Routes.MODAL.ROOT_MODAL_FLOW, {
screen: Routes.MODAL.NFT_AUTO_DETECTION_MODAL,
Expand All @@ -347,7 +353,7 @@ const Wallet = ({
dispatch,
isNFTAutoDetectionModalViewed,
navigation,
providerConfig.chainId,
chainId,
useNftDetection,
]);

Expand Down Expand Up @@ -380,14 +386,11 @@ const Wallet = ({
*/
useEffect(() => {
const networkOnboarded = getIsNetworkOnboarded(
providerConfig.chainId,
chainId,
networkOnboardingState,
);

if (
wizardStep > 0 ||
(!networkOnboarded && prevChainId !== providerConfig.chainId)
) {
if (wizardStep > 0 || (!networkOnboarded && prevChainId !== chainId)) {
// Do not check since it will conflict with the onboarding wizard and/or network onboarding
return;
}
Expand All @@ -401,7 +404,7 @@ const Wallet = ({
).isZero();
const shouldShowStxOptInModal =
await shouldShowSmartTransactionsOptInModal(
providerConfig.chainId,
chainId,
providerConfig.rpcUrl,
accountHasZeroBalance,
);
Expand All @@ -424,7 +427,7 @@ const Wallet = ({
}, [
wizardStep,
navigation,
providerConfig.chainId,
chainId,
providerConfig.rpcUrl,
networkOnboardingState,
prevChainId,
Expand All @@ -440,7 +443,7 @@ const Wallet = ({
});
},
/* eslint-disable-next-line */
[navigation, providerConfig.chainId],
[navigation, chainId],
);

useLayoutEffect(() => {
Expand Down
Loading
Loading