如何询问 Web3 RPC 客户端正在使用哪个链?

问题描述 投票:0回答:2

如何询问 Web3 RPC 客户端正在使用哪个链,例如以太坊主网/Polygon 主网/币安智能链/等

blockchain ethereum smartcontracts web3js
2个回答
2
投票

您需要创建一个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];

    }

0
投票

使用 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';
© www.soinside.com 2019 - 2024. All rights reserved.