Skip to content

Subscriptions

A subscription is a Stream of what the node pushes: new block headers, logs, pending transactions. It needs a transport that can push, and it unsubscribes when the stream ends.

import { Effect, Layer, Stream } from "effect";
import { Socket } from "effect/socket";
import { Transport } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";
const WebSocket = Transport.webSocket("ws://127.0.0.1:8545").pipe(
Layer.provide(Socket.layerWebSocketConstructorGlobal),
);
// Log the number of each new block, forever.
const watch = Eth.subscribe.newHeads().pipe(
Stream.runForEach((head) => Effect.log(`block ${head.number}`)),
);
await watch.pipe(Effect.provide(WebSocket), Effect.runPromise);

A stream is to many values what an Effect is to one

Section titled “A stream is to many values what an Effect is to one”

Eth.subscribe.newHeads() describes the subscription. Nothing is sent until the stream is run, and running it is an Effect.

To Use
act on every item Stream.runForEach((item) => effect)
take the next item and stop Stream.runHead, which gives an Option
collect the next n items Stream.take(n), then Stream.runCollect
transform or filter items first Stream.map, Stream.filter, Stream.mapEffect
import { Stream } from "effect";
import { Eth } from "@ethect/core/rpc";
const nextThreeNumbers = Eth.subscribe.newHeads().pipe(
Stream.map((head) => head.number),
Stream.take(3),
Stream.runCollect,
);
// Effect<Array<bigint | null>, Method.Error, Subscriptions>

A subscription requires Subscriptions, which WebSocket, IPC and EIP-1193 provide. HTTP does not, so a program that subscribes over HTTP alone does not compile.

import { Effect, Layer, Stream } from "effect";
import { FetchHttpClient } from "effect/http";
import { Transport } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";
const Http = Transport.http("http://127.0.0.1:8545").pipe(
Layer.provide(FetchHttpClient.layer),
);
// Effect<…, …, Subscriptions>: HTTP provided `Transport`, not `Subscriptions`
const head = Eth.subscribe.newHeads().pipe(Stream.runHead, Effect.provide(Http));
// A program with a requirement left cannot run.
// @ts-expect-error
Effect.runPromise(head);

See Polling over HTTP for what to do with an HTTP endpoint.

Kind Item Emits
Eth.subscribe.newHeads() Block.Header the header of each block added to the chain
Eth.subscribe.logs(filter?) Log the logs matching a filter, as blocks are added
Eth.subscribe.newPendingTransactions() Hash the hash of each transaction entering the pending pool
Eth.subscribe.newPendingTransactions(true) Transaction the same transactions in full, where the node supports it
Eth.subscribe.transactionReceipts(filter?) ReadonlyArray<Receipt> the receipts of each new block, all of them or those of the transactions you name
Eth.subscribe.syncing() sync status the status each time the node starts or stops syncing
import { Effect, Stream } from "effect";
import { Address, Hash } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";
// The first topic of a log is the hash of its event signature.
const transfer = Hash.keccak256Utf8("Transfer(address,address,uint256)");
const watchTransfers = (token: Address.Address) =>
Eth.subscribe.logs({ address: token, topics: [transfer] }).pipe(
Stream.filter((log) => log.removed !== true),
Stream.runForEach((log) => Effect.log(`transfer in ${log.transactionHash}`)),
);

The topics and the data of a log are hex. Ev.decode reads them as the events of a contract. Ev.watch is this subscription with the decoding done, and it polls where the transport cannot push.

There is no unsubscribe function. A subscription ends when its stream does, and eth_unsubscribe is sent for you.

import { Effect, Fiber, Stream } from "effect";
import { Eth } from "@ethect/core/rpc";
const program = Effect.gen(function* () {
// Runs in the background, in a fiber of its own.
const watcher = yield* Eth.subscribe.newHeads().pipe(
Stream.runForEach((head) => Effect.log(`block ${head.number}`)),
Effect.forkScoped,
);
// … the rest of the program, on the same connection …
const chainId = yield* Eth.chainId();
yield* Fiber.interrupt(watcher); // unsubscribes
return chainId;
}).pipe(Effect.scoped);
The stream ends because Unsubscribed
it took what it wanted (Stream.take, Stream.runHead) yes
its fiber was interrupted yes
the scope it was forked in closed yes

Calls and subscriptions share the connection, so a watcher in the background does not block the calls of the program.

On WebSocket and IPC, a subscription outlives the connection it was opened on. After a reconnection it is issued again and the stream carries on. What the node emitted in between is not replayed, and the stream itself does not say that there was a gap.

The transport does: opened, on the Subscriptions service, says each time the node takes the subscription, on the first connection and on each one that replaces it. Read what you missed when it does, then take what the node pushes.

import { Effect, Stream } from "effect";
import { Transport } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";
/** The height of the chain each time the node takes the subscription, then its raw headers. */
const headsWithCatchUp = Stream.unwrap(
Effect.map(Transport.Subscriptions, ({ opened }) =>
opened(["newHeads"]).pipe(
Stream.switchMap(({ items }) =>
// the node pushes from its answer on: no block falls between this read and the items
Stream.concat(Stream.fromEffect(Eth.blockNumber()), items),
),
),
),
);
// Stream<unknown, Method.Error, Subscriptions | Transport>

The read comes once the node has answered eth_subscribe, never before: a block mined between a read and a subscription that is not in place yet would be in neither. A subscription opened while the node is away waits for the connection, then is issued once.

For new blocks, Block.watch does this for you: it gives the blocks mined while there was no connection, in order, up to 256 of them. Connection lifecycle describes exactly what happens, and how to fill a gap in logs.

A stream fails with the same three errors as a method.

Failure When
RpcError the node refused the subscription, for example with MethodNotFound where eth_subscribe is not served
TransportError the transport gave up reconnecting, or an EIP-1193 provider has no events to listen to
CodecError an item does not have the shape of the kind
import { Effect, Stream } from "effect";
import { Eth } from "@ethect/core/rpc";
const pending = Eth.subscribe.newPendingTransactions(true).pipe(
Stream.runForEach((transaction) => Effect.log(`pending from ${transaction.from}`)),
Effect.catchTag("RpcError", (error) =>
Effect.log(`the node refused the subscription: ${error.message}`),
),
);

For new blocks, Block.watch needs only a Transport: it polls an HTTP endpoint, and subscribes where the transport can push. For anything else, repeat a call on a schedule and keep the changes. It is a stream too.

import { Effect, Schedule, Stream } from "effect";
import { Eth } from "@ethect/core/rpc";
// Needs only `Transport`: works over HTTP.
const blockNumbers = Stream.fromEffectSchedule(
Eth.blockNumber(),
Schedule.spaced("2 seconds"),
).pipe(Stream.changes);
const watch = blockNumbers.pipe(
Stream.runForEach((number) => Effect.log(`block ${number}`)),
);

Stream.changes drops a value equal to the one before it, so a block number is emitted once. For logs, the filter methods keep the cursor on the node.

  • Items are buffered without limit. A consumer slower than the node lets the buffer grow. Keep the work per item short, or drop items you do not need with Stream.filter first.
  • Each run is a subscription. Running the same stream twice subscribes twice.
  • A wallet relays. Over EIP-1193, items arrive as the provider’s message events, where the wallet serves eth_subscribe.