如何连接确定我在 Ganache 中连接的网络
我试过这个 const networkId =等待Web3.eth.net.getId()
但是我得到的错误是这样的
未处理的拒绝(TypeError):无法读取未定义的属性“net”
由于您使用的是大写的
Web3
W
,我假设它是类的名称 - 而不是实例的名称。
您需要访问 instance 属性
net
及其方法 getId()
。
// instantiate the class first
const web3 = new Web3();
// mind the lowercase `w` in `web3`, accessing the instance
const networkId = await web3.eth.net.getId();
对于那些寻找最新答案的人(2024 年 4 月):
您应该使用链 ID 而不是网络 ID。有关更多信息,请参阅 Pedro Gomes(WalletConnect 创始人)的这篇文章。
要使用 web3.js
4.x
获取链 ID,您应该使用 web3.eth.getChainId()
来代替,并将其映射到自己的网络名称:
const SUPPORTED_CHAINS_NAMES: Record<string, string> = {
'1': 'Ethereum Mainnet',
'11155111': 'Sepolia',
};
const chainId = (await web3.eth.getChainId()).toString();
const chainName = SUPPORTED_CHAINS_NAMES[chainId] || 'Unsupported Chain';
eth-chains
这样的库来获取最新的链信息,而不是手动映射链ID:
const chainId = Number(await web3.eth.getChainId());
const chainInfo = chains.getById(chainId) || null;
const chainName = chainInfo?.name || 'Unsupported Chain';
另外,请参阅 web3.js 的迁移指南。