BlockReq
返回全部文章

Rpc Tutorials

使用 ethers v6 接入 BlockReq RPC

配置 ethers v6 JsonRpcProvider 接入 BlockReq RPC,读取网络状态,并明确区分 WebSocket 用法。

BlockReq Engineering2026年7月1日6 分钟阅读

Using BlockReq RPC with ethers v6

ethers v6 uses JsonRpcProvider for HTTP and HTTPS JSON-RPC endpoints. Keep the BlockReq URL outside source code and pass the expected chain id when you construct the provider.

pnpm add ethers
export BLOCKREQ_ETH_RPC_URL="https://ethereum-rpc.blockreq.com/v1/rpc/public"

The example below reads basic network state from Ethereum mainnet. Passing 1 makes the expected network explicit.

import { JsonRpcProvider, formatEther } from "ethers";

const rpcUrl = process.env.BLOCKREQ_ETH_RPC_URL;

if (!rpcUrl) {
  throw new Error("BLOCKREQ_ETH_RPC_URL is required");
}

const provider = new JsonRpcProvider(rpcUrl, 1);

const network = await provider.getNetwork();
const blockNumber = await provider.getBlockNumber();
const balance = await provider.getBalance("0x0000000000000000000000000000000000000000");

console.log({
  chainId: network.chainId.toString(),
  blockNumber,
  balance: formatEther(balance),
});

Calls and logs

Use the provider for reads, calls, logs, receipts, and block data. Keep signer construction in a separate module so read-only code does not accidentally gain transaction authority.

const latestBlock = await provider.getBlock("latest");

if (!latestBlock) {
  throw new Error("latest block was not returned");
}

console.log({
  number: latestBlock.number,
  hash: latestBlock.hash,
  timestamp: latestBlock.timestamp,
});

WebSocket endpoints

Use WebSocketProvider only when you have a WSS BlockReq endpoint and your application needs subscriptions. HTTP polling and WSS subscriptions have different failure modes, so keep them as separate configuration values and health checks.

import { WebSocketProvider } from "ethers";

const wssUrl = process.env.BLOCKREQ_ETH_WSS_URL;

if (wssUrl) {
  const wsProvider = new WebSocketProvider(wssUrl, 1);
  wsProvider.on("block", (blockNumber) => {
    console.log({ blockNumber });
  });
}

Historical state, archive reads, debug_*, and trace_* methods can depend on chain support and upstream capability. When you need them, probe the exact method during deployment validation and surface a clear product error if it is unavailable.