1

I use Metamask. Until now I used the goerli testnet network for my development project. I use ethers.js also in my project. Now how can I implement a test for knowing the network if it is goerli or the main network Ethereum ? Here is my code, but I dont see any clue for my needs :

const { ethers } = require("ethers");

async function main() {
  const provider = new ethers.providers.InfuraProvider();
  let ntwrk = await provider.getNetwork();
  console.log("============= selected network =", ntwrk);
}

main();

At runtime the console log shows :

{
  name: 'homestead',
  chainId: 1,
  ensAddress: '0x....',
  _defaultProvider: [Function: func] { renetwork: [Function (anonymous)] }
}

When I change the network then the name is always 'homestead', and the chainId is always 1

edit :

full code

const { ethers } = require("ethers");

async function main() {
  // Configuring the connection to an Ethereum node
  const provider = new ethers.providers.InfuraProvider(
    
  );
  let ntwrk = await provider.getNetwork();
  console.log("============= selected network =", ntwrk);
}

main();

1 Answer 1

1

In the code you provided, the InfuraProvider is created without any network specified, so it connects to the mainnet by default.

The line

let ntwrk = await provider.getNetwork();

If you wanted to connect to a different Ethereum network, such as the Goerli testnet, you would need to specify the network when creating the InfuraProvider

const { ethers } = require("ethers");

async function main() {
  const provider = new ethers.providers.InfuraProvider(
    "goerli", // Specify the Goerli testnet
    "your-infura-project-id" // Replace with your Infura project ID
  );

  let ntwrk = await provider.getNetwork();
  console.log("============= selected network =", ntwrk);
}

main();

It should work for you now. Just make sure to get your project ID from infura

11
  • The chainId is still 1 whenether the network is mainnet or goerli. So what is wrong in my code ?
    – pheromix
    Feb 27, 2023 at 8:05
  • can you share full code? or env file or config file Feb 27, 2023 at 8:24
  • I updated the post to include the full code, the env file, named .env, is empty.
    – pheromix
    Feb 27, 2023 at 8:31
  • Adding an updated answer have a look at that ! Feb 27, 2023 at 10:05
  • sorry : I misplaced the code when I tried to update my post ; I didnt realize it was yours
    – pheromix
    Feb 27, 2023 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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