PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 22, 2022

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

 September 22, 2022     blockchain, ethereum, smartcontracts, web3js     No comments   

Issue

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];

    }


Answered By - Yilmaz
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing