Need some help figuring out how to do network tracking using react + typescript

I need some help figuring out how to do network tracking using typescript

According to the video the javascript code looks like the following:

Moralis.initialize(""); // Application ID
Moralis.serverUrl = ""; // Server URL
var web3;
checkWeb3();

function displayMessage(messageType, message) {
  messages = {
    "00": `<div class= "alert alert-success"> ${message} </div>`,
    "01": `<div class= "alert alert-danger"> ${message} </div>`,
  };
  document.getElementById("resultSpace").innerHTML = messages[messageType];
}

async function checkWeb3() {
  const ethereum = window.ethereum;
  if (!ethereum || !ethereum.on) {
    displayMessage("01", "This App Requires MetaMask, Please Install MetaMask");
  } else {
    //displayMessage("00", "Metamask is Installed");
    setWeb3Environment();
  }
}

function setWeb3Environment() {
  web3 = new Web3(window.ethereum);
  getNetwork();
  monitorNetwork();
}

async function getNetwork() {
  chainID = await web3.eth.net.getId();
  displayMessage("00", "Active network is " + getNetworkName(chainID));
}

function getNetworkName(chainID) {
  networks = {
    1: "Ethereum Mainnet",
    4: "Ethereum Rinkeby",
    97: "Binance Smart Chain Testnet",
    80001: "Polygon Mumbai Testnet",
  };
  return networks[chainID];
}

function monitorNetwork() {
  Moralis.onChainChanged(function () {
    window.location.reload();
  });
}

So I have build this react application and want to track the user’s metamask network, if for example he is connected to the main network I want to throw an error message on the screen mentioning the user to switch to rinkeby.

Code that I’ve written and tried to transform it to typescript, NetworkTracker.tsx :

import Web3 from "web3";
import Moralis from "moralis";
import { ChainType } from "./ChainType";

let web3: Web3;

function displayMessage(type: number, message: string) {
  //this can be updated in a component itself
  const messages: string[] = [
    `<div class= "alert alert-success"> ${message} </div>`,
    `<div class= "alert alert-danger"> ${message} </div>`,
  ];
  return messages[type];
}

async function checkWeb3() {
  const ethereum = window.ethereum; //somehow this gives the error: Property 'ethereum' does not exist on type 'Window & typeof globalThis'.
  if (!ethereum || !ethereum.on) {
    displayMessage(1, "This App Requires MetaMask, Please Install MetaMask");
  } else {
    //displayMessage("00", "Metamask is Installed");
    setWeb3Environment();
  }
}

function setWeb3Environment() {
  web3 = new Web3(window.ethereum); //somehow this gives the error: Property 'ethereum' does not exist on type 'Window & typeof globalThis'.
  getNetwork();
  monitorNetwork();
}

async function getNetwork() {
  const chainID: number = await web3.eth.net.getId();
  displayMessage(0, "Active network is " + getNetworkName(chainID));
}

function getNetworkName(chainID: number) {
  //ChainType is an interface that has a chainId and chainName.
  const network: ChainType[] = [
    { ChainId: 1, ChainName: "Ethereum Mainnet" },
    { ChainId: 4, ChainName: "Ethereum Rinkeby" },
    { ChainId: 97, ChainName: "Binance Smart Chain Testnet" },
    { ChainId: 80001, ChainName: "Polygon Mumbai Testnet" },
  ];

  return network.find((i) => i.ChainId === chainID);
}

function monitorNetwork() {
  Moralis.Web3.onChainChanged(function () {
    window.location.reload();
  });
}

export default checkWeb3;

What should be the window.ethereum version of typescript?

Hi @Ectrizz

Try this solution for declaring a window type

Or you can use web3 instead of window.ethereum take a look at https://github.com/MoralisWeb3/react-moralis#web3

1 Like

Got it working I think! Thanks! Used the hook instead.

import Moralis from "moralis";
import { ChainType } from "./ChainType";
import { useMoralis } from "react-moralis";

async function checkWeb3() {
  SetWeb3Environment();
}

async function SetWeb3Environment() {
  const { logout, web3 } = useMoralis();

  let web3Provided = web3?.setProvider(
    web3.givenProvider || "http://localhost:3000"
  );

  Moralis.Web3.onChainChanged(function () {
    window.location.reload();
  });
  Moralis.Web3.onAccountsChanged(function () {
    window.location.reload();
    logout();
  });

  await web3?.eth.net.getId().then((res) => console.log(res));
  const chainID: number = await web3?.eth.net.getId()!;
  console.log("Active network is " + getNetworkName(chainID)?.ChainName);
}

function getNetworkName(chainID: number) {
  //ChainType is an interface that has a chainId and chainName.
  const network: ChainType[] = [
    { ChainId: 1, ChainName: "Ethereum Mainnet" },
    { ChainId: 4, ChainName: "Ethereum Rinkeby" },
    { ChainId: 97, ChainName: "Binance Smart Chain Testnet" },
    { ChainId: 80001, ChainName: "Polygon Mumbai Testnet" },
  ];

  return network.find((i) => i.ChainId === chainID);
}

export default checkWeb3;

Still very new to moralis and web3 packages, thanks for the clarifications!

Great job :star_struck:

Also thanks for sharing the solution with the Moralis community. Really appreciate this :mage:

Happy BUIDLing :man_mechanic:

1 Like