1

I want to check the user's network.

How I can implement something like that:

enter image description here

4 Answers 4

0

You can get the current chain with ethereum.chainId.

To listen to chainId changes, you can set up an event handler like this

ethereum.on('chainChanged', (chainId) => {
    //logic for chain change
});
0

returns Number: The network ID.

web3.eth.net.getId()
.then( netID => {
console.log(netID);
});
0
        async function getChainID() {chainId = await ethereum.request({ method: 'eth_chainId' }).then(chainSymbol => { if (chainSymbol == 0x38) {
            //bsc network
         }else if(chainSymbol == 0x1){ 
            //eth network
         }
     });     
}
0

For those looking for an up-to-date answer (April 2024):

You should be using chain ids rather than network ids. More on that on this post by Pedro Gomes (WalletConnect's founder).

To get the chain id with web3.js 4.x, you should use web3.eth.getChainId() instead, and map that to the network name yourself:

const SUPPORTED_CHAINS_NAMES: Record<number, string> = {
  1: 'Ethereum  Mainnet',
  11155111: 'Sepolia',
};

const chainId = Number(await web3.eth.getChainId());
const chainName = SUPPORTED_CHAINS_NAMES[chainId] || 'Unsupported Chain';

Or use a library like eth-chains to get up-to-date chain information, instead of manually mapping the chain id:

const chainId = Number(await web3.eth.getChainId());
const chainInfo = chains.getById(chainId) || null;
const chainName = chainInfo?.name || 'Unsupported Chain';

Also, see web3.js' migration guide.

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.