# Ev.watch

Events as they happen, as a stream. With a block to start from, the past ones first.

## Usage

```ts
import { Effect, Stream } from "effect";
import { FetchHttpClient } from "effect/http";
import { Address, Erc20, Ev, Transport } from "@ethect/core";

const { Transfer } = Erc20.ev;

const USDC = Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");

const program = Effect.gen(function* () {
  // logs each transfer of the token, until the program is stopped
  yield* Ev.watch(Transfer, { address: USDC }).pipe(
    Stream.runForEach((transfer) =>
      Effect.log(`${transfer.from} sent ${transfer.value} to ${transfer.to}`),
    ),
  );
});

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

The line is the same over HTTP, a WebSocket, IPC or a wallet: events are pushed where the
transport can push, and asked for otherwise. See [`Ev.Source`](https://ethect.dev/reference/ev/source/). The
examples below leave the transport out.

### The past first

With `fromBlock`, the events since that block come first, then the stream goes on with what
happens. No event comes twice.

```ts
import { Erc4626, Ev, type Address } from "@ethect/core";

const { Deposit } = Erc4626.ev;

// every deposit of a user since a block, then each new one
const deposits = (vault: Address.Address, user: Address.Address) =>
  Ev.watch(Deposit, { address: vault, args: { owner: user }, fromBlock: 19_000_000n });
```

### Only once deep enough

With `confirmations`, an event is given once that many blocks follow its own. A reorg
shallower than that is never seen.

```ts
import { Erc4626, Ev, type Address } from "@ethect/core";

const { Deposit } = Erc4626.ev;

// each deposit, five blocks after it happened
const settled = (vault: Address.Address) =>
  Ev.watch(Deposit, { address: vault, confirmations: 5 });
```

### An event a reorg took back

Without `confirmations`, an event is given at once, and the chain may still replace its block.
The event then comes again, with `log.removed` set.

```ts
import { Stream } from "effect";
import { Erc4626, Ev, type Address } from "@ethect/core";

const { Deposit } = Erc4626.ev;

// the deposits that stand, as a running total
const total = (vault: Address.Address) =>
  Ev.watch(Deposit, { address: vault }).pipe(
    Stream.scan(
      () => 0n,
      (sum, deposit) => (deposit.log.removed ? sum - deposit.assets : sum + deposit.assets),
    ),
  );
```

### Several events

Give an array. `_tag` tells the events apart.

```ts
import { Effect, Stream } from "effect";
import { Erc4626, Ev, type Address } from "@ethect/core";

const { Deposit, Transfer } = Erc4626.ev;

const activity = (vault: Address.Address) =>
  Ev.watch([Transfer, Deposit], { address: vault }).pipe(
    Stream.runForEach((event) =>
      Effect.log(event._tag === "Transfer" ? `moved ${event.value}` : `deposited ${event.assets}`),
    ),
  );
```

## Returns

`Stream<Ev.Of<E>, Transport.Error | AbiError, Transport>`

A stream of events. It does not end by itself: it stops when you stop reading it, with
`Stream.take`, `Stream.runHead` or by interrupting its fiber.

## Parameters

### events

- **Type:** `Ev.Any` or `ReadonlyArray<Ev.Any>`

The events to watch, each a class of [`Ev.make`](https://ethect.dev/reference/ev/make/).

### options.address (optional)

- **Type:** [`Address.Address`](https://ethect.dev/reference/primitives/address/) or `ReadonlyArray<Address.Address>`

The contract the logs come from, or several.

### options.args (optional)

- **Type:** the indexed fields of the event, each a value or a `ReadonlyArray` of values

Values to match, by field, as for [`Ev.logs`](https://ethect.dev/reference/ev/logs/#filterargs-optional).

### options.fromBlock (optional)

- **Type:** [`BlockId.BlockId`](https://ethect.dev/rpc/types/block-id/)
- **Default:** the block after the latest

The first block whose events are given. In the past, its events and those since come first.

### options.confirmations (optional)

- **Type:** `number`
- **Default:** `0`

How many blocks follow the block of an event before the event is given.

### options.interval (optional)

- **Type:** `Duration.Input`
- **Default:** the pace of the blocks

How often a transport that cannot push is asked. It sets
[`Block.Interval`](https://ethect.dev/reference/block/#interval) for this stream.

## Behavior

- **Without `fromBlock`, it starts with the next block.** The events of the latest block
  already happened: they are not given.
- **With `fromBlock`, the past comes first**, read as [`Ev.logs`](https://ethect.dev/reference/ev/logs/) reads
  it: in pieces when the node refuses the range. What was mined while the past was read comes
  next, and no event is given twice.
- **Without `confirmations`, an event is given at once.** A reorg that replaces its block gives
  it again with `log.removed`, then the events of the new blocks.
- **With `confirmations`, it is [`Ev.pages`](https://ethect.dev/reference/ev/pages/), one event after the
  other.** A reorg shallower than the confirmations changes nothing. A deeper one gives the
  events of the new blocks, and takes none back: use the pages when that can happen.
- **How events arrive is picked from the transport**: pushed, collected by a filter of the
  node, or read block by block. [`Ev.Source`](https://ethect.dev/reference/ev/source/) says which, and how to
  force one.
- **No event waits for the next one.** Over a transport that pushes, the past is read once
  the node has the subscription: an event of that instant is read or pushed, and given at
  once.
- **An event lost while there was no connection is taken back.** On a new connection the
  blocks of the events given are asked for: one that a reorg replaced meanwhile comes again
  with `log.removed`, then the events of the new blocks.
- **A list of no value matches nothing.** `args: { to: [] }` gives a stream that never gives an
  event, and the node is not asked.
- **A value its field does not take fails the stream** with an `AbiError`, before anything is
  sent.

## Errors

| Error | When |
| --- | --- |
| [`AbiError`](https://ethect.dev/reference/errors/abi-error/) | a value of `args` is not one its field takes: nothing was sent |
| [`RpcError`](https://ethect.dev/reference/errors/rpc-error/) | the node answered a request with an error that a narrower range does not avoid |
| [`TransportError`](https://ethect.dev/reference/errors/transport-error/) | over HTTP, a request failed. Over a socket, the transport gave up reconnecting. |

A socket transport that is reconnecting does not fail a stream of pushed events: the stream
waits, then reads what it missed.

## Under the hood

One service is asked: the `Transport`, and its `Subscriptions` when the transport has one.

**`Ev.watch(events, options)`**

- **the filter**: topics from the events and `args`. No request
- **where to start** `eth_getBlockByNumber("latest", false)`: without `fromBlock`: the next block
  - for a block number: nothing is asked
  - `confirmations: 0`:
    - **Ev.Source**: from that block on: `eth_subscribe("logs")`, or `eth_newFilter`, or `eth_getLogs` per block
  - `confirmations > 0`:
    - **Ev.pages**: from that block on

The requests of each source are on [`Ev.Source`](https://ethect.dev/reference/ev/source/#under-the-hood), and
those of the pages on [`Ev.pages`](https://ethect.dev/reference/ev/pages/#under-the-hood).
