Implementing the Moralis Providers and trying to have a user connect their wallet and mint an NFT.
This is what I have implemented
import { useMoralis } from "react-moralis";
export default function ConnectWallet() {
const {
authenticate,
isAuthenticated,
logout,
user,
web3,
enableWeb3,
isWeb3Enabled,
web3EnableError,
} = useMoralis();
const networks = {
1: "Ethereum Mainnet",
4: "Rinkeby Testnet",
97: "Binance Smart Chain Testnet",
80001: "Polygon Mumbai Testnet",
};
async function authMetamask() {
const localChainId = web3.network.chainId;
const checkMetaMask = web3.provider.isMetaMask;
if (localChainId == 1 && checkMetaMask) {
await authenticate({ provider: "metamask", signingMessage: "ThePeepsProject Auth" });
} else {
handleError();
}
}
async function login() {
if (!isWeb3Enabled) {
web3Enabler();
} else {
await authMetamask();
}
}
const web3Enabler = async () => {
await enableWeb3({
onSuccess: () => {
const localChainId = web3.network.chainId;
const checkMetaMask = web3.provider.isMetaMask;
console.log("Web3 Provider: ", web3.connection.url);
console.log("Network Name: ", networks[localChainId]);
if (localChainId == 1 && checkMetaMask) {
authMetamask();
} else if (!checkMetaMask) {
console.log("checkMetaMask: ", checkMetaMask);
console.log("Please install MetaMask");
} else if (localChainId != 1) {
console.log("Must use Eth Mainnet");
} else {
console.log("Something went wrong");
}
},
onError: (error) => {
console.log("Web3 Enable Error: ", error.message);
if (error.message == "Non ethereum enabled browser") {
alert("Metamask is not installed.\nPlease install it and setup a wallet to continue");
}
},
});
};
function handleError(message) {
const localChainId = web3.network.chainId;
const checkMetaMask = web3.provider.isMetaMask;
if (!checkMetaMask) {
alert("Metamask is not installed.\nPlease install it and setup a wallet to continue");
} else if (localChainId != 1 && localChainId != 4) {
alert("Please ensure you are on the Etherium Mainnet to mint");
}
}
return (
<div>
<main>
<div>
{isAuthenticated ? (
<button onClick={logout}>
Logout ({user.get("ethAddress").slice(0, 6)}...{user.get("ethAddress").slice(37, 41)})
</button>
) : (
<button type="button" onClick={() => login()}>
Connect with MetaMask
</button>
)}
</div>
</main>
</div>
);
}
Everytime a wallet gets connected, it shows an error in the console:
Web3 Enable Error: Cannot read properties of null (reading 'network')
Coming from the lines:
onError: (error) => {
console.log("Web3 Enable Error: ", error.message);
The function is doing itβs job of catching an error, but what is this error and how can I fix it?
How can I check if the user has metamask installed and ensure that they are on the Mainnet before they can run the function?