Skip to content

Decode and watch events

Read the events of a contract: the past ones, those of one transaction, and the new ones as they happen. The example follows the deposits of a vault.

deposits.ts
import { Effect, Stream } from "effect";
import { Call, Erc4626, Ev, Tx, type Address } from "@ethect/core";
// The events of a vault are built in: its own, and those of the token of its shares.
const { Deposit, Transfer } = Erc4626.ev;
export const program = (vault: Address.Address) =>
Effect.gen(function* () {
// From the past: the deposits of the last thousand blocks, in one array.
const head = yield* Call.blockNumber;
const past = yield* Ev.logs(Deposit, { address: vault, fromBlock: head - 1000n });
yield* Effect.log(`${past.length} deposits since block ${head - 1000n}`);
// From a receipt: what the transaction of the last one did, in one pass over its logs.
const last = past.at(-1);
if (last !== undefined) {
const receipt = yield* Tx.wait(last.log.transactionHash);
for (const event of Ev.decode([Deposit, Transfer], receipt.logs)) {
if (event._tag === "Deposit") yield* Effect.log(`deposit of ${event.assets}`);
else yield* Effect.log(`transfer of ${event.value} to ${event.to}`);
}
}
// Live: each new deposit, until the program is stopped.
yield* Ev.watch(Deposit, { address: vault }).pipe(
Stream.runForEach((deposit) => Effect.log(`${deposit.owner} deposited ${deposit.assets}`)),
);
});

Erc4626.ev.Deposit is a class, and a decoded event is an instance of it: its fields by name, a _tag that is the name of the event, and log, which says where it comes from. An event of a contract that is not a standard is defined by its signature, indexed included: see Read and write a contract. Effect.gen and yield* are the async and await of Effect.

Ev.logs asks for the events of a range of blocks and gives them in one array, in the order of the chain. args narrows the request to values of the indexed fields, which are the only ones a node can match.

import { Erc4626, Ev, type Address } from "@ethect/core";
const { Deposit } = Erc4626.ev;
// The deposits of one owner, or of several: a list is "one of these".
const theirs = (vault: Address.Address, owners: ReadonlyArray<Address.Address>, since: bigint) =>
Ev.logs(Deposit, { address: vault, args: { owner: owners }, fromBlock: since });
const large = (vault: Address.Address) =>
// @ts-expect-error `assets` is not indexed: a node cannot be asked to match it
Ev.logs(Deposit, { address: vault, args: { assets: 100n } });
  • Write the range you want. A node refuses a range that is too wide: it is then read in pieces the node accepts, and you still get one array.
  • A history that does not fit in memory is for Ev.pages, which gives one range of blocks at a time.

Ev.decode turns logs into events. It sends nothing: the logs are already in the receipt. The receipt of a deposit holds the logs of several events: the token that moves, the shares that are minted, the deposit itself. One pass reads them all.

You give You get
one event: Ev.decode(Deposit, logs) an array of deposits
an array: Ev.decode([Deposit, Transfer], logs) one array in the order of the logs. _tag tells the events apart
a record: Ev.decode({ deposits: Deposit, transfers: Transfer }, logs) one array per key

The receipt most often comes from a transaction you just sent:

import { Effect } from "effect";
import { Erc4626, Ev, Tx, type Address } from "@ethect/core";
const sharesFor = (vault: Address.Address, assets: bigint, me: Address.Address) =>
Effect.gen(function* () {
const receipt = yield* Tx.send(Erc4626.at(vault).deposit(assets, me));
const [deposit] = Ev.decode(Erc4626.ev.Deposit, receipt.logs);
return deposit?.shares; // what the vault gave for the assets
});

A log that is none of the events you gave is left out, and decoding cannot fail.

Ev.watch gives a Stream: a value that produces events over time. Stream.runForEach runs an effect for each one, and does not end by itself.

Push or poll, the same line. Over HTTP the node is asked at the pace of its blocks. Over a WebSocket it pushes each event. You change the transport, and nothing in the program:

import { Effect, Layer } from "effect";
import { Socket } from "effect/socket";
import { Address, Transport } from "@ethect/core";
import { program } from "./deposits";
// The same program, with events pushed by the node.
const Pushed = Transport.webSocket("wss://ethereum-rpc.publicnode.com").pipe(
Layer.provide(Socket.layerWebSocketConstructorGlobal),
);
const VAULT = Address.makeUnsafe("0xBEEF01735c132Ada46AA9aA4c54623cAA92A64CB");
await program(VAULT).pipe(Effect.provide(Pushed), Effect.runPromise);
Option What it changes
none Starts with the next block. Each event is given at once
fromBlock The events since that block come first, then the new ones. None comes twice
confirmations: 5 An event is given once five blocks follow its own. A shallower reorg is never seen
args As for Ev.logs: values of the indexed fields

Without confirmations, a reorg can take back an event you were given. It then comes again with deposit.log.removed set to true.

Three requests come before the stream. Then the node is asked again and again, or pushes.

  1. your nodeeth_blockNumberCall.blockNumber
  2. your nodeeth_getLogs({ address, topics: [Deposit], fromBlock, toBlock })Ev.logs
  3. your nodeeth_getTransactionReceipt(hash)Tx.wait(hash): it is in a block, and no block is watched
  4. your programEv.decode: nothing, the logs are in the receipt
  5. your nodeeth_getBlockByNumber("latest", false)Ev.watch: where to start, the next block
  6. your nodeeth_newFilterEv.watch, HTTP
  7. your nodeeth_getBlockByNumber("latest", false)then: the range to read ends at the head
  8. your nodeeth_getLogs({ address, topics, fromBlock, toBlock })then, once: no block falls between the start and the filter
  9. your nodeeth_getFilterChangesthenat the pace of the blocks
  10. your nodeeth_subscribe("logs", { address, topics })Ev.watch, WebSocket: the node pushes, after the same two reads
  • Several events are one request. Ev.watch([Deposit, Transfer]) asks for both topics as alternatives.
  • A node that loses a filter, or has none, is read block by block with eth_getLogs.

Ev.Source says how the choice is made and how to force one. Ev.logs has what happens when a range is refused.