如何询问 Web3 RPC 客户端正在使用哪个链,例如以太坊主网/Polygon 主网/币安智能链/等
您需要创建一个web3实例。为此,您需要一个提供者:
const NETWORKS = {
1: "Ethereum Main Network",
3: "Ropsten Test Network",
4: "Rinkeby Test Network",
5: "Goerli Test Network",
42: "Kovan Test Network",
56: "Binance Smart Chain",
1337: "Ganache",
137: "Polygon",
};
// you need those 2 npm packages
import detectEthereumProvider from "@metamask/detect-provider";
import Web3 from "web3";
const provider = await detectEthereumProvider();
// Only if you have a provider then create a web3 instance
if (provider) {
const web3 = new Web3(provider);
const chainId = await web3.eth.getChainId();
if (!chainId) {
throw new Error("Cannot retreive network");
return NETWORKS[chainId];
}
使用 web3.js
4.x
,您应该使用 web3.eth.getChainId()
来获取链 ID,然后自己将其映射到网络名称:
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';
eth-chains
这样的库来获取最新的链信息,而不是手动映射链ID:
const chainId = Number(await web3.eth.getChainId());
const chainInfo = chains.getById(chainId) || null;
const chainName = chainInfo?.name || 'Unsupported Chain';