Skip to content

Commit

Permalink
refactor: Use Redux network controller state
Browse files Browse the repository at this point in the history
Various UI components have been updated to use Redux network controller
state (via selectors) rather than directly accessing the controller
state using the `Engine` global.

Relates to MetaMask/mobile-planning#1016
  • Loading branch information
Gudahtt committed Jun 29, 2023
1 parent 9e1a7a9 commit 4f92edd
Show file tree
Hide file tree
Showing 12 changed files with 58 additions and 45 deletions.
10 changes: 6 additions & 4 deletions app/components/UI/AddCustomToken/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ export default class AddCustomToken extends PureComponent {
};

static propTypes = {
/**
* The chain ID for the current selected network
*/
chainId: PropTypes.string,
/**
/* navigation object required to push new views
*/
Expand All @@ -96,8 +100,7 @@ export default class AddCustomToken extends PureComponent {

getAnalyticsParams = () => {
try {
const { NetworkController } = Engine.context;
const { chainId } = NetworkController?.state?.providerConfig || {};
const { chainId } = this.props;
const { address, symbol } = this.state;
return {
token_address: address,
Expand Down Expand Up @@ -184,8 +187,7 @@ export default class AddCustomToken extends PureComponent {
let validated = true;
const address = this.state.address;
const isValidTokenAddress = isValidAddress(address);
const { NetworkController } = Engine.context;
const { chainId } = NetworkController?.state?.providerConfig || {};
const { chainId } = this.props;
const toSmartContract =
isValidTokenAddress && (await isSmartContractAddress(address, chainId));
const addressWithoutSpaces = address.replace(/\s/g, '');
Expand Down
5 changes: 2 additions & 3 deletions app/components/UI/ApproveTransactionReview/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -503,14 +503,13 @@ class ApproveTransactionReview extends PureComponent {

getAnalyticsParams = () => {
try {
const { activeTabUrl, transaction, onSetAnalyticsParams } = this.props;
const { activeTabUrl, chainId, transaction, onSetAnalyticsParams } =
this.props;
const {
token: { tokenSymbol },
originalApproveAmount,
encodedAmount,
} = this.state;
const { NetworkController } = Engine.context;
const { chainId } = NetworkController?.state?.providerConfig || {};
const isDapp = !Object.values(AppConstants.DEEPLINKS).includes(
transaction?.origin,
);
Expand Down
7 changes: 5 additions & 2 deletions app/components/UI/MessageSign/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ const createStyles = (colors) =>
*/
class MessageSign extends PureComponent {
static propTypes = {
/**
* The chain ID of the current selected network
*/
chainId: PropTypes.string,
/**
* react-navigation object used for switching between screens
*/
Expand Down Expand Up @@ -75,11 +79,10 @@ class MessageSign extends PureComponent {
getAnalyticsParams = () => {
try {
const {
chainId,
currentPageInformation,
messageParams: { from },
} = this.props;
const { NetworkController } = Engine.context;
const { chainId } = NetworkController?.state?.providerConfig || {};
const url = new URL(currentPageInformation?.url);
return {
account_type: getAddressAccountType(from),
Expand Down
1 change: 1 addition & 0 deletions app/components/UI/MessageSign/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ function createWrapper({ origin = messageParamsMock.origin } = {}) {
return shallow(
<Provider store={store}>
<MessageSign
chainId={1}
currentPageInformation={{ title: 'title', url: 'url' }}
messageParams={{ ...messageParamsMock, origin }}
onConfirm={() => undefined}
Expand Down
8 changes: 5 additions & 3 deletions app/components/UI/PersonalSign/PersonalSign.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, InteractionManager } from 'react-native';
import { useSelector } from 'react-redux';
import Engine from '../../../core/Engine';
import SignatureRequest from '../SignatureRequest';
import ExpandedMessage from '../SignatureRequest/ExpandedMessage';
Expand All @@ -17,6 +18,7 @@ import { PersonalSignProps } from './types';
import { useNavigation } from '@react-navigation/native';
import createStyles from './styles';
import AppConstants from '../../../core/AppConstants';
import { selectChainId } from '../../../selectors/networkController';

/**
* Component that supports personal_sign
Expand All @@ -32,6 +34,8 @@ const PersonalSign = ({
const navigation = useNavigation();
const [truncateMessage, setTruncateMessage] = useState<boolean>(false);

const chainId = useSelector(selectChainId);

const { colors }: any = useTheme();
const styles = createStyles(colors);

Expand All @@ -46,8 +50,6 @@ const PersonalSign = ({

const getAnalyticsParams = useCallback((): AnalyticsParams => {
try {
const { NetworkController }: any = Engine.context;
const { chainId } = NetworkController?.state?.providerConfig || {};
const url = new URL(currentPageInformation?.url);

return {
Expand All @@ -61,7 +63,7 @@ const PersonalSign = ({
} catch (error) {
return {};
}
}, [currentPageInformation, messageParams]);
}, [chainId, currentPageInformation, messageParams]);

useEffect(() => {
AnalyticsV2.trackEvent(
Expand Down
5 changes: 5 additions & 0 deletions app/components/UI/SignatureRequest/Root/Root.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import Modal from 'react-native-modal';
import React, { useState } from 'react';
import { StyleSheet } from 'react-native';
import { useSelector } from 'react-redux';
import { useNavigation } from '@react-navigation/native';
import { useTheme } from '../../../../util/theme';
import MessageSign from '../../../UI/MessageSign';
import PersonalSign from '../../../UI/PersonalSign';
import TypedSign from '../../../UI/TypedSign';
import { MessageParams } from '../types';
import { ApprovalTypes } from '../../../../core/RPCMethods/RPCMethodMiddleware';
import { selectChainId } from '../../../../selectors/networkController';

interface RootProps {
messageParams?: MessageParams;
Expand All @@ -26,6 +28,7 @@ const Root = ({ messageParams, approvalType, onSign }: RootProps) => {
const navigation = useNavigation();
const { colors } = useTheme();
const [showExpandedMessage, setShowExpandedMessage] = useState(false);
const chainId = useSelector(selectChainId);

const toggleExpandedMessage = () =>
setShowExpandedMessage(!showExpandedMessage);
Expand Down Expand Up @@ -64,6 +67,7 @@ const Root = ({ messageParams, approvalType, onSign }: RootProps) => {
)}
{approvalType === ApprovalTypes.ETH_SIGN_TYPED_DATA && (
<TypedSign
chainId={chainId}
navigation={navigation}
messageParams={messageParams}
onCancel={onSign}
Expand All @@ -75,6 +79,7 @@ const Root = ({ messageParams, approvalType, onSign }: RootProps) => {
)}
{approvalType === ApprovalTypes.ETH_SIGN && (
<MessageSign
chainId={chainId}
navigation={navigation}
messageParams={messageParams}
onCancel={onSign}
Expand Down
8 changes: 5 additions & 3 deletions app/components/UI/TypedSign/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ const createStyles = (colors) =>
*/
class TypedSign extends PureComponent {
static propTypes = {
/**
* The chain ID of the current selected network
*/
chainId: PropTypes.string,
/**
* react-navigation object used for switching between screens
*/
Expand Down Expand Up @@ -85,9 +89,7 @@ class TypedSign extends PureComponent {

getAnalyticsParams = () => {
try {
const { currentPageInformation, messageParams } = this.props;
const { NetworkController } = Engine.context;
const { chainId } = NetworkController?.state?.providerConfig || {};
const { chainId, currentPageInformation, messageParams } = this.props;
const url = new URL(currentPageInformation?.url);
return {
account_type: getAddressAccountType(messageParams.from),
Expand Down
6 changes: 3 additions & 3 deletions app/components/UI/WatchAssetRequest/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,20 @@ import React from 'react';
import PropTypes from 'prop-types';
import { StyleSheet, View, Text, InteractionManager } from 'react-native';
import URL from 'url-parse';
import { useSelector } from 'react-redux';
import { fontStyles } from '../../../styles/common';
import { strings } from '../../../../locales/i18n';
import ActionView from '../ActionView';
import { renderFromTokenMinimalUnit } from '../../../util/number';
import TokenImage from '../../UI/TokenImage';
import Device from '../../../util/device';
import Engine from '../../../core/Engine';
import { MetaMetricsEvents } from '../../../core/Analytics';
import AnalyticsV2 from '../../../util/analyticsV2';

import useTokenBalance from '../../hooks/useTokenBalance';
import { useTheme } from '../../../util/theme';
import NotificationManager from '../../../core/NotificationManager';
import { selectChainId } from '../../../selectors/networkController';

const createStyles = (colors) =>
StyleSheet.create({
Expand Down Expand Up @@ -97,14 +98,13 @@ const WatchAssetRequest = ({
const { colors } = useTheme();
const styles = createStyles(colors);
const [balance, , error] = useTokenBalance(asset.address, interactingAddress);
const chainId = useSelector(selectChainId);
const balanceWithSymbol = error
? strings('transaction.failed')
: `${renderFromTokenMinimalUnit(balance, asset.decimals)} ${asset.symbol}`;

const getAnalyticsParams = () => {
try {
const { NetworkController } = Engine.context;
const { chainId } = NetworkController?.state?.providerConfig || {};
const url = new URL(currentPageInformation?.url);

return {
Expand Down
1 change: 1 addition & 0 deletions app/components/Views/AddAsset/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ class AddAsset extends PureComponent {
/>
)}
<AddCustomToken
chainId={chainId}
navigation={navigation}
tabLabel={strings('add_asset.custom_token')}
testID={'tab-add-custom-token'}
Expand Down
19 changes: 12 additions & 7 deletions app/components/Views/Asset/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
} from '../../../reducers/swaps';
import {
selectChainId,
selectNetwork,
selectRpcTarget,
} from '../../../selectors/networkController';
import { sortTransactions } from '../../../util/activity';
Expand Down Expand Up @@ -133,7 +134,11 @@ class Asset extends PureComponent {
*/
selectedAddress: PropTypes.string,
/**
* A string representing the network name
* The network ID for the current selected network
*/
networkId: PropTypes.string,
/**
* The chain ID for the current selected network
*/
chainId: PropTypes.string,
/**
Expand Down Expand Up @@ -257,18 +262,17 @@ class Asset extends PureComponent {
this.txsPending.length !== newTxsPending.length;

ethFilter = (tx) => {
const { selectedAddress, chainId } = this.props;
const { selectedAddress, chainId, networkId } = this.props;
const {
transaction: { from, to },
isTransfer,
transferInformation,
} = tx;

const network = Engine.context.NetworkController.state.network;
if (
(safeToChecksumAddress(from) === selectedAddress ||
safeToChecksumAddress(to) === selectedAddress) &&
(chainId === tx.chainId || (!tx.chainId && network === tx.networkID)) &&
(chainId === tx.chainId || (!tx.chainId && networkId === tx.networkID)) &&
tx.status !== 'unapproved'
) {
if (isTransfer)
Expand All @@ -281,17 +285,17 @@ class Asset extends PureComponent {
};

noEthFilter = (tx) => {
const { chainId, swapsTransactions, selectedAddress } = this.props;
const { chainId, networkId, swapsTransactions, selectedAddress } =
this.props;
const {
transaction: { to, from },
isTransfer,
transferInformation,
} = tx;
const network = Engine.context.NetworkController.state.network;
if (
(safeToChecksumAddress(from) === selectedAddress ||
safeToChecksumAddress(to) === selectedAddress) &&
(chainId === tx.chainId || (!tx.chainId && network === tx.networkID)) &&
(chainId === tx.chainId || (!tx.chainId && networkId === tx.networkID)) &&
tx.status !== 'unapproved'
) {
if (to?.toLowerCase() === this.navAddress) return true;
Expand Down Expand Up @@ -566,6 +570,7 @@ const mapStateToProps = (state) => ({
state.engine.backgroundState.PreferencesController.selectedAddress,
identities: state.engine.backgroundState.PreferencesController.identities,
chainId: selectChainId(state),
networkId: selectNetwork(state),
tokens: state.engine.backgroundState.TokensController.tokens,
transactions: state.engine.backgroundState.TransactionController.transactions,
thirdPartyApiMode: state.privacy.thirdPartyApiMode,
Expand Down
12 changes: 7 additions & 5 deletions app/components/Views/AssetDetails/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ import { useTheme } from '../../../util/theme';
import { MetaMetricsEvents } from '../../../core/Analytics';
import AnalyticsV2 from '../../../util/analyticsV2';
import Routes from '../../../constants/navigation/Routes';
import { selectProviderConfig } from '../../../selectors/networkController';
import {
selectChainId,
selectProviderConfig,
} from '../../../selectors/networkController';

const createStyles = (colors: any) =>
StyleSheet.create({
Expand Down Expand Up @@ -98,6 +101,7 @@ const AssetDetails = (props: Props) => {
const navigation = useNavigation();
const dispatch = useDispatch();
const providerConfig = useSelector(selectProviderConfig);
const chainId = useSelector(selectChainId);
const tokens = useSelector(
(state: any) =>
state.engine.backgroundState.TokensController.tokens as TokenType[],
Expand Down Expand Up @@ -165,7 +169,7 @@ const AssetDetails = (props: Props) => {
};

const triggerHideToken = () => {
const { TokensController, NetworkController } = Engine.context as any;
const { TokensController } = Engine.context as any;
navigation.navigate(Routes.MODAL.ROOT_MODAL_FLOW, {
screen: 'AssetHideConfirmation',
params: {
Expand All @@ -187,9 +191,7 @@ const AssetDetails = (props: Props) => {
token_standard: 'ERC20',
asset_type: 'token',
tokens: [`${symbol} - ${address}`],
chain_id: getDecimalChainId(
NetworkController?.state?.providerConfig?.chainId,
),
chain_id: getDecimalChainId(chainId),
});
} catch (err) {
Logger.log(err, 'AssetDetails: Failed to hide token!');
Expand Down
Loading

0 comments on commit 4f92edd

Please sign in to comment.