Switch Network - Missing web3 Instance

Hi guys,

I am having an issue with the following JavaScript. I would like to switch the user’s network in MetaMask on page load. The error that I am receiving states “Uncaught Error: Missing web3 instance, make sure to call Moralis.enableWeb3() or Moralis.authenticate()”. As you can see, I am running the enableWeb3() function. Any help would be appreciated.

Moralis.enableWeb3();

const currentUser = Moralis.User.current();

if (currentUser.attributes.sessionToken) {
	$('#connect').hide();
	$('#disconnect').show();

	const ethAddress = currentUser.get('ethAddress');
    console.log("Wallet Address: " + ethAddress);

	if (web3.currentProvider.chainId != "0x38")
	{
		Moralis.switchNetwork("0x38");
	}
}
else {
	$('#connect').show();
	$('#disconnect').hide();
}

Thanks in advance

Try an await here at the beginning of the line

Excellent, thank you!

There’s a new issue that I’m having, still on the switchNetwork topic.

		if (web3.currentProvider.chainId != "0x38")
		{
			Moralis.switchNetwork("0x38");
		}
		console.log(web3.currentProvider.chainId);

If I am on the Ethereum network, the popup asks me to change to the BSC but then console logs 0x1 instead of 0x38. Do I need to reconnect the website to the BSC? Am I missing a step?

Thanks in advance

You could try to run enableWeb3 again after the network was changed

I gave that a go and unfortunately no change.

Can you try to switch the network directly with web3?

I’ve just tried - web3 works perfectly! Strange!

Thanks

1 Like