8

Using web3js it is possible get network ID using the following method:

// Contract ABI Load
const ABISimpleStorage = require("./build/contracts/SimpleStorage.json");

// Besu Connection Web3 Load
let web3 = new Web3(
  new Web3.providers.WebsocketProvider("ws://127.0.0.1:8546")
);
    const netID = await web3.eth.net.getId();

How we could do same thing in ethers.js?

const ABISimpleStorage = require("./build/contracts/SimpleStorage.json");
let provider = new ethers.providers.JsonRpcProvider();

let contract = new ethers.Contract(
  ABISimpleStorage.networks["2020"].address,
  ABISimpleStorage.abi,
  provider
);

Thanks

8

This worked for me:

const { chainId } = await provider.getNetwork()
console.log(chainId) // 42
2
  • is it safe to assume 1 for homestead, 3 for ropsten etc as a constant?
    – dcsan
    Oct 23 at 8:30
  • 1
    @dcsan yes that would be safe to assume Oct 23 at 10:34
3

I was searching this today.

Try provider.getNetwork().chainId.

getNetwork().name gives human readable name like 'homestead'

1
  • catch 22 that to get a provider you need to give a network: let provider = await ethers.getDefaultProvider(network, Settings);
    – dcsan
    Oct 23 at 8:31
2

Use the provider.getNetwork() function. It will return a Network type and in it contain the chainId. You can see in the doc here: https://docs.ethers.io/ethers.js/html/api-providers.html#id2

UPDATE: as it turn out i was wrong the chainID and networkID are the same most of the time, not all of the time and there aren’t any api in etherjs so you need to use json-rpc instead. To do that you use this: https://docs.ethers.io/v5/api/providers/jsonrpc-provider/#JsonRpcProvider-send. Where the method is “net_version” and the params is an empty array. It will return like this: https://eth.wiki/json-rpc/API#net_version.

5
  • Really thanks I've to read
    – brunillopu
    Apr 11 '20 at 18:45
  • Unfortunately, in ethers.js version 5, the chain id returned in provider.getNetwork() differs from the network id. Or in other words, in ethers.js version 4, the network id was returned instead of the chain id. So this does not work anymore. Jul 5 '20 at 13:12
  • @ Marc Wäckerlin chainId and networkId are the same but with different name that's all: ethereum.stackexchange.com/a/37536/50595
    – haxerl
    Jul 7 '20 at 1:46
  • 3
    chainId and networkId are not the same.
    – tuler
    Jul 10 '20 at 19:31
  • catch 22 that to get a provider you need to give a network: let provider = await ethers.getDefaultProvider(network, Settings);
    – dcsan
    Oct 23 at 8:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.