5

I am looking for a solution that I would use in my Dapp to get the network name and the chain Id of the network to which the wallet is connected using Ether.js library

For example, if my wallet is connected to the Goerli network, I should get the network name as 'goerli' and the chain id as 5. What would be the code for that?

4 Answers 4

3

I don't use ether.js, but I try to help with my solution: I use wagmi library with react. wagmi library is simple.

    import { useNetwork } from 'wagmi'

    function App() {
       const { chain, chains } = useNetwork()

       return (
          <div>
             {chain && <div>Connected to {chain.name}</div>}
             {chains && (
                <div>Available chains: {chains.map((chain) => chain.name)} 
                </div>
             )}
          <div/>
       )
    }

wagmi docs: https://wagmi.sh/docs/hooks/useNetwork

2
  • I appreciate your help but I need the code for ether.js library only. Commented Sep 27, 2022 at 8:33
  • heyy Did you find something about this??????? Commented Dec 11, 2022 at 16:57
1
import { ethers } from "ethers";
import abi from '../abi.json';

const contract = new ethers.Contract(contractAddress, abi, signer);

try{
    const tx = await contract.customContractFunction(value1, value2);
    return tx;
}catch(err) {
    console.log(err);
}

try this code

1
  • This is an answer not related to OP question Commented Dec 26, 2022 at 13:00
1

After creating a new ethers provider ( passing in window.ethereum ), to get chainId and name, use the getNetwork() method on your provider which will return an object with fields such as name,chainId,etc. There you have it

1

At the time of writing, the Metamask and other Ethereum-based wallets inject an object called ethereum into the window object. The ethereum object offers a variety of properties and methods that we could use. Let's assume that you have the Metamask wallet installed; open your browser's console, and run > window.ethereum. You should get output similar to this: window.ethereum

As we can see, the ethereum object offers chainId, and networkVersion properties that we can tap into (see example below). However, both of the options are depreciated at this point and are considered to be legacy APIs. I'd like you to, please read more in Ethereum Provider API - Legacy Properties. The recommended way is to use the request() method, which takes an object describing your request and returns a Promise. The promise gets eventually resolved with the requested data. To query chain id, we send the following object to our request() function window.ethereum.request({method: 'eth_chainId'}) and we receive 0x5, which is network id for Goerli network: window.ethereum.request()

The method described above does not offer the network name, so you could create a custom object that maps the network chain id to the network name.

The other method you could use is to employ ethers.providers.getNetwork() function from Ethers Library, which return an object containing chainId and network name properties:

// By Chain ID
getNetwork(5);
// {
//   chainId: 5,
//   ensAddress: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
//   name: 'goerli'
// }

Implementing these concepts might differ and depends mainly on your framework and libraries. However, it could look something like that within Next.js 13 page component:

"use client";
import { useEffect } from "react";
import { ethers } from "ethers";

export default function Home() {
  useEffect(() => {
    console.log("Getting nework name and id...");
    async function getChainId() {
      try {
        const chainId = Number(await window.ethereum.request({ method: "eth_chainId" }));
        const network = ethers.providers.getNetwork(chainId);
        console.log(`Network name: ${network.name}, id:${network.chainId}`);
      } catch (error) {
        console.log(error);
      }
    }
    getChainId();
  }, []);
  return <></>;
}

enter image description here

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.