如何询问Web3 RPC客户端它正在使用哪一条链,例如/Polygon Mainnet/Binance智能链/等等。
发布于 2022-09-08 20:46:19
您需要创建一个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];
}https://stackoverflow.com/questions/73654492
复制相似问题