blockchainethereumsmartcontractsweb3js

How to ask a Web3 RPC client which chain it is working with?


How to ask a Web3 RPC client which chain it is working with e.g. Ethereum Mainnet/Polygon Mainnet/Binance Smart Chain/etc.


Solution

  • You need to create a web3 instance. for this you need a provider:

    const NETWORKS = {
      1: "Ethereum Main Network",
      3: "Ropsten Test Network",
      4: "Rinkeby Test Network",
      5: "Goerli Test Network",
      42: "Kovan Test Network",
      56: "Binance Smart Chain",
      1337: "Ganache",
      137: "Polygon",
    };
    
    // you need those 2 npm packages
    import detectEthereumProvider from "@metamask/detect-provider";
    import Web3 from "web3";
    
    const provider = await detectEthereumProvider();
    // Only if you have a provider then create a web3 instance
     if (provider) {
            const web3 = new Web3(provider);
            const chainId = await web3.eth.getChainId();
            if (!chainId) {
            throw new Error("Cannot retreive network");
            return NETWORKS[chainId];
    
        }