0

Is there a way to check name of current blockchain using ethers js For example

const provider = new ethers.providers.JsonRpcProvider(rpcUrl);
  
const chainInfo = await providers.getNetwork() 

gives chain Id and network name but not the blockchain name as etherum or polygon etc

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Mueed
  • 31
  • 5

1 Answers1

1

you can use detectNetwork. You make request to RPC server, so the "name" property depends on the response of the RPC server. For example if you make request binance mainnet

const provider = new ethers.providers.JsonRpcProvider(
  "https://bsc-dataseed.binance.org"
);
const a = provider.detectNetwork().then((x) => console.log(x));

you will get this:

{
    "name": "bnb",
    "chainId": 56,
    "ensAddress": null,
    "_defaultProvider": null
}

But if you make request to "avalance"

const provider = new ethers.providers.JsonRpcProvider(
  "https://api.avax.network/ext/bc/C/rpc"
);
const a = provider.detectNetwork().then((x) => console.log(x));

you will get this:

{
    "chainId": 43114,
    "name": "unknown"
}

It really depends on how the RPC server response is configured. you can find rpc endpoints here

Or you can create a mapping for the most popular networks

const NETWORKS: { [k: string]: string } = {
  1: "Ethereum Main Network",
  5: "Goerli Test Network",
  42: "Kovan Test Network",
  56: "Binance Smart Chain",
  1337: "Ganache",
};

once you get the chainId, you can return

NETWORKS[chainId]
Yilmaz
  • 35,338
  • 10
  • 157
  • 202