# Decode and watch events

The deposits of a vault, three ways. From the past with Ev.logs, from a receipt with Ev.decode, and live with Ev.watch, pushed or polled by the same line.

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.

```ts title="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}`)),
    );
  });
```
```ts title="main.ts"
import { Effect } from "effect";
import { FetchHttpClient } from "effect/http";
import { Address, Transport } from "@ethect/core";
import { program } from "./deposits";

const VAULT = Address.makeUnsafe("0xBEEF01735c132Ada46AA9aA4c54623cAA92A64CB");

await program(VAULT).pipe(
  Effect.provide(Transport.http("https://ethereum-rpc.publicnode.com")),
  Effect.provide(FetchHttpClient.layer),
  Effect.runPromise,
);
```

`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](https://ethect.dev/guides/contracts/#a-contract-that-is-not-a-standard).
`Effect.gen` and `yield*` are the `async` and `await` of [Effect](https://ethect.dev/guides/effect-essentials/).

## From the past

[`Ev.logs`](https://ethect.dev/reference/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.

```ts
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`](https://ethect.dev/reference/ev/pages/), which
  gives one range of blocks at a time.

## From a receipt

[`Ev.decode`](https://ethect.dev/reference/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:

```ts
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.

## Live

[`Ev.watch`](https://ethect.dev/reference/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:

```ts
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`.

## Under the hood

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

- **your node** `eth_blockNumber`: `Call.blockNumber`
- **your node** `eth_getLogs({ address, topics: [Deposit], fromBlock, toBlock })`: `Ev.logs`
- **your node** `eth_getTransactionReceipt(hash)`: `Tx.wait(hash)`: it is in a block, and no block is watched
- **your program**: `Ev.decode`: nothing, the logs are in the receipt
- **your node** `eth_getBlockByNumber("latest", false)`: `Ev.watch`: where to start, the next block
- **your node** `eth_newFilter`: `Ev.watch`, HTTP
- **your node** `eth_getBlockByNumber("latest", false)`: then: the range to read ends at the head
- **your node** `eth_getLogs({ address, topics, fromBlock, toBlock })`: then, once: no block falls between the start and the filter
- **your node** `eth_getFilterChanges`: then, at the pace of the blocks
- **your node** `eth_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`](https://ethect.dev/reference/ev/source/) says how the choice is made and how to force one.
[`Ev.logs`](https://ethect.dev/reference/ev/logs/#under-the-hood) has what happens when a range is refused.
