on master help sign in
metamask: ensure expected chain ID

Before this change, it was possible to have Metamask connected to another EVM chain (e.g. Optimism), or a testnet (e.g. Goerli) while using Mainnet Bridge. This resolves #1082 by conducting a check for the expected chain ID in the connected wallet during Login, and requesting to update it if necessary.

commit8060db399291c781942322b57eb81c8aa98590d9 authortomholford <tomholford@users.noreply.github.com> dateMon 12 Dec 2022, 04:49 (4 years ago) parent85f8acf
3 files changed+30−1
src/lib/constants.ts+7 src/lib/network.js+8−1 src/views/Login/LoginSelector.tsx+15
src/lib/constants.ts+7
@@ -226,6 +226,11 @@ const INITIAL_NETWORK_KEY_REVISION = 1;
226226
227227const EIP1559_TRANSACTION_TYPE = 2;
228228
229+// Chain IDs
230+// https://chainlist.org/?testnets=true
231+const ETHEREUM_MAINNET_CHAIN_ID = '0x1';
232+const ETHEREUM_GOERLI_CHAIN_ID = '0x5';
233+
229234export {
230235 CHECK_BLOCK_EVERY_MS,
231236 DEFAULT_GAS_PRICE_GWEI,
@@ -275,4 +280,6 @@ export {
275280 PASSPORT_TOOLTIP,
276281 LOCKUP_TOOLTIP,
277282 INITIAL_NETWORK_KEY_REVISION,
283+ ETHEREUM_MAINNET_CHAIN_ID,
284+ ETHEREUM_GOERLI_CHAIN_ID
278285};
src/lib/network.js+8−1
@@ -1,3 +1,6 @@
1+import { isMainnet } from "./flags";
2+import { ETHEREUM_GOERLI_CHAIN_ID, ETHEREUM_MAINNET_CHAIN_ID, } from './constants';
3+
14const NETWORK_TYPES = {
25 OFFLINE: Symbol('OFFLINE'),
36 LOCAL: Symbol('LOCAL'),
@@ -27,4 +30,8 @@ const chainIdToNetworkType = chainId => {
2730 }
2831};
2932
30−export { NETWORK_TYPES, renderNetworkType, chainIdToNetworkType };
33+const expectedChainId = () => {
34+ return isMainnet ? ETHEREUM_MAINNET_CHAIN_ID : ETHEREUM_GOERLI_CHAIN_ID;
35+}
36+
37+export { NETWORK_TYPES, expectedChainId, renderNetworkType, chainIdToNetworkType };
src/views/Login/LoginSelector.tsx+15
@@ -21,6 +21,7 @@ import { useNetwork } from 'store/network';
2121import { WALLET_TYPES } from 'lib/constants';
2222import { useWalletConnect } from 'lib/useWalletConnect';
2323import { MetamaskWallet } from 'lib/metamask';
24+import { expectedChainId } from 'lib/network';
2425import useLoginView from 'lib/useLoginView';
2526import { getAuthToken } from 'lib/authToken';
2627
@@ -94,6 +95,20 @@ export default function LoginSelector({
9495 'Device does not have an Ethereum provider available (is Metamask or Brave Wallet installed?)'
9596 );
9697 }
98+
99+ /**
100+ * Ensure wallet is connected to expected chain
101+ */
102+ if (window.ethereum.chainId !== expectedChainId() ) {
103+ console.log(`unexpected chain: ${window.ethereum.chainId}`);
104+ await window.ethereum.request({
105+ method: 'wallet_switchEthereumChain',
106+ params: [{ chainId: expectedChainId() }],
107+ });
108+ window.location.reload();
109+ return;
110+ }
111+
97112 setMetamask(true);
98113 setMetamaskSelected(true);
99114