Skip to content

Eth.chainId

Returns the chain id of the network the node is on, as a number.

import { Effect } from "effect";
import { FetchHttpClient } from "effect/http";
import { Transport } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";
const chainId = await Eth.chainId().pipe(
Effect.provide(Transport.http("http://127.0.0.1:8545")),
Effect.provide(FetchHttpClient.layer),
Effect.runPromise,
);
// 31337

The call works over every transport. The examples below leave the transport out.

Compare the id with the one your program expects before it does anything else.

import { Effect } from "effect";
import { Eth } from "@ethect/core/rpc";
const head = Effect.gen(function* () {
const chainId = yield* Eth.chainId();
if (chainId !== 1) {
return yield* Effect.fail(`expected Ethereum mainnet, got chain ${chainId}`);
}
return yield* Eth.blockNumber();
});

Over the EIP-1193 transport the answer is the chain the wallet is on.

import { Effect } from "effect";
import { type Eip1193, Transport } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";
// The wallet's EIP-1193 provider: `window.ethereum`, or the one a wallet SDK returns.
declare const provider: Eip1193.Provider;
const chainId = await Eth.chainId().pipe(
Effect.provide(Transport.eip1193(provider)),
Effect.runPromise,
);

Wallet.chainId is the same function, exported from the Wallet namespace too. To follow the chain as the user switches it, see Eip1193.chainChanged.

Effect<number, Method.Error, Transport>

The chain id defined by EIP-155: 1 for Ethereum mainnet, 31337 for anvil.

None.

  • A number, not a bigint. The node answers "0x7a69" and you get 31337. See values on the wire.
  • One request per call. The result is not cached. Read it once and keep it when you need it often.

eth_chainId