[SOLVED] How to set default chain ID, and prompt if incorrect chainID is set?

Hey guys,

I’m trying to set up my dapp such that it connects to the Polygon Mainnet by default, and if the user is not connected to the mainnet, then I’d like to prompt them to do so.

This is my current setup:

      try {
        setAuthError(null);
        setIsAuthenticating(true);
  
        // Enable web3 to get user address and chain
        await enableWeb3({ throwOnError: true, provider });
        const { account, chainId } = Moralis;
  
        if (!account) {
          throw new Error('Connecting to chain failed, as no connected account was found');
        }
        if (!chainId) {
          throw new Error('Connecting to chain failed, as no connected chain was found');
        }
  
        // Get message to sign from the auth api
        const { message } = await Moralis.Cloud.run('requestMessage', {
          address: account,
          chain: parseInt(chainId, 16),
          networkType: 'evm',
        });
  
        // Authenticate and login via parse
        await authenticate({
          provider,
          signingMessage: message,
          throwOnError: true,
        });
        onClose();

I tried replacing chain: parseInt(chainId, 16), with await authenticate({ chainId: 137 }) as suggested here: https://v1docs.moralis.io/moralis-dapp/users/web3-login/walletconnect however when I do this I’m not able to authenticate at all.

How can I set default chainID, and prompt users to switch networks if they are on the wrong chain?
Thanks!

you can try to change the chain before you authenticate, you read current chain, you check it and if it is not the expected chain then you try to change it

I’m using this function, however it says Cannot invoke an object which is possibly 'undefined'.

    useEffect(() => {
      if (typeof window == 'undefined') return;
      if (
          !isWeb3Enabled &&
          !isWeb3EnableLoading &&
          isAuthenticated
      ) {
          // @ts-ignore
          enableWeb3({ throwOnError: true, provider: 'metamask' | 'walletconnect' });
          const switchNetworkMumbai = async () => {
          const web3Provider = await Moralis.enableWeb3();
            try {
              await web3Provider.provider.request({
                method: "wallet_switchEthereumChain",
                params: [{ chainId: "0x13881" }],
              });
            } catch (error) {
              if (error.code === 4902) {
                try {
                  await web3Provider.provider.request({
                    method: "wallet_addEthereumChain",
                    params: [
                      {
                        chainId: "0x13881",
                        chainName: "Mumbai",
                        rpcUrls: ["https://rpc-mumbai.matic.today"],
                        nativeCurrency: {
                          name: "Matic",
                          symbol: "Matic",
                          decimals: 18,
                        },
                        blockExplorerUrls: ["https://explorer-mumbai.maticvigil.com"],
                      },
                    ],
                  });
                } catch (error) {
                  alert(error.message);
                }
              }
            }
          }
          switchNetworkMumbai()
      }
  }, [isWeb3Enabled, isWeb3EnableLoading, isAuthenticated]);

At what line it returns that error?

At this line. Is there anyway I can do it using useChain?

Maybe it is because it is ethers instead of web3 now and maybe the syntax is different with ethers

I just used await switchNetwork("xxx") after await enableWeb(). This automatically prompts Metamask to switch chains. Thanks!

1 Like