# Ev.pages

Past then live events, one range of blocks at a time. Each page says where it ends, so an
indexer can stop and start again without missing or repeating an event.

## 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* () {
  let transfers = 0;
  // every transfer since a block, then each new one once it is twelve blocks deep
  yield* Ev.pages(Transfer, { address: USDC, fromBlock: 19_000_000n, confirmations: 12 }).pipe(
    Stream.runForEach((page) =>
      Effect.sync(() => {
        transfers += page.events.length;
        console.log(`blocks ${page.fromBlock} to ${page.toBlock}: ${transfers} transfers so far`);
      }),
    ),
  );
});

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

The past comes in ranges as wide as the node accepts. Once the stream has caught up with the
chain, each new block is a page. The examples below leave the transport out.

### A page

A page is a range of blocks, the events in it, and the hash of its last block.

| Field | Type | Holds |
| --- | --- | --- |
| `fromBlock` | `bigint` | the first block of the range |
| `toBlock` | `bigint` | the last block of the range |
| `hash` | [`Hash.Hash`](https://ethect.dev/reference/primitives/hash/) | the hash of block `toBlock` |
| `events` | `ReadonlyArray<Ev.Of<E>>` | the events of these blocks, in the order of the chain |

A range that holds no event is a page too, with no events: your cursor moves all the same.

### Stop and start again

Save each page with the block after its last one: that is where to start again.

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

const { Transfer } = Erc20.ev;
type Transfer = Ev.Of<typeof Transfer>; // one transfer, decoded

/** Saves the events of a page and the cursor, together. */
declare const save: (
  events: ReadonlyArray<Transfer>,
  cursor: bigint,
) => Effect.Effect<void>;

const index = (token: Address.Address, cursor: bigint) =>
  Ev.pages(Transfer, { address: token, fromBlock: cursor, confirmations: 12 }).pipe(
    Stream.runForEach((page) => save(page.events, page.toBlock + 1n)),
  );
```

A page saved whole, with its cursor, is never read again, and no block is skipped.

### A page that starts earlier

Without `confirmations`, a page can be about blocks the chain later replaces. The next page
then starts at the first block that changed, and not after the last one you saw. One rule
covers it:

**a page whose `fromBlock` is not the previous `toBlock + 1` replaces everything from its
`fromBlock` on.**

```ts
import { Erc20, Ev } from "@ethect/core";

const { Transfer } = Erc20.ev;
type Transfer = Ev.Of<typeof Transfer>; // one transfer, decoded

type Stored = { readonly events: ReadonlyArray<Transfer>; readonly cursor: bigint };

/** What is stored once a page is saved: the rule needs no other case. */
const saved = ({ events }: Stored, page: Ev.Page<typeof Transfer>): Stored => ({
  events: [...events.filter((event) => event.log.blockNumber < page.fromBlock), ...page.events],
  cursor: page.toBlock + 1n,
});
```

Dropping what is at or after `fromBlock` does nothing for a page that follows the one before
it, so the same line saves every page.

### With confirmations

With `confirmations` larger than any reorg of the chain, a page never starts earlier: nothing
you saved is ever replaced. It is the simple way to index, at the price of being that many
blocks behind.

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

const { Transfer } = Erc20.ev;

const settled = (token: Address.Address, cursor: bigint) =>
  Ev.pages(Transfer, { address: token, fromBlock: cursor, confirmations: 64 });
```

### Up to a block

With `toBlock`, the stream ends with the page of that block. Before the chain is there, it
waits for it.

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

const { Transfer } = Erc20.ev;

const backfill = (token: Address.Address) =>
  Ev.pages(Transfer, { address: token, fromBlock: 19_000_000n, toBlock: 19_999_999n }).pipe(
    Stream.runCollect,
  );
```

## Returns

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

A stream of [pages](#a-page). Without `toBlock` it does not end by itself.

## Parameters

### events

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

The events to ask for, 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 of the first page: your cursor.

### options.toBlock (optional)

- **Type:** `bigint`

The last block of the last page. The stream ends there.

### options.confirmations (optional)

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

How many blocks follow the last block of a page before the page is given.

### options.interval (optional)

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

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

## Behavior

- **Driven by the blocks.** Each head of [`Block.watch`](https://ethect.dev/reference/block/#watch) says how far
  the pages may go: up to the head, less the confirmations.
- **Pages follow each other.** Each starts at the block after the one before it, except the
  one a reorg brings: see [the rule](#a-page-that-starts-earlier).
- **A range with no event is still a page.**
- **The past is read in ranges the node accepts**, as [`Ev.logs`](https://ethect.dev/reference/ev/logs/#behavior)
  reads them: each range that is read is a page.
- **A page of one block is read by the hash of the block**, so it holds one version of that
  block and no other. At the head of the chain every page is one block.
- **A reorg gives a page that starts at the first block that changed, or before it.** The
  number and the hash of the last 64 blocks the pages covered are remembered. Of a range read
  at once, only the last block is. When the pages cannot tell where a reorg starts, the page
  starts earlier: after the last block they know did not change, or 64 blocks before the
  oldest one they remember. A reorg deeper than that is not followed to its start.
- **A block the chain replaced before it was read gives no page.** A node may not know such a
  block any more. The block that took its place comes with a next head, and its page follows
  the page before.
- **When the stream of blocks starts over, the pages check what they gave.** That is after
  more than 256 blocks were missed, or a very deep reorg. The block before the cursor is read
  by its number. When its hash is not the one remembered, the blocks remembered are read back
  to one that did not change, and the next page starts after it. Otherwise the pages go on.
- **With `confirmations` larger than any reorg, no page ever starts earlier.**
- **Starting again knows nothing of what you saved.** A reorg that happened while nothing was
  indexing is not seen. Use `confirmations`, or compare the `hash` you saved with the chain
  before you start.
- **A range is read by number.** Behind a gateway whose nodes are not at the same block, use
  `confirmations`.
- **A list of no value matches nothing.** The pages come, with no event, and no log is asked
  for.

## 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 refused one block that is on the chain |
| [`TransportError`](https://ethect.dev/reference/errors/transport-error/) | over HTTP, a request failed. Over a socket, the transport gave up reconnecting. |
| `TransportError` | the node does not have a block it was asked for by number |

A failure ends the stream. Start again from your cursor.

## Under the hood

One service is asked: the `Transport`. The blocks come from
[`Block.watch`](https://ethect.dev/reference/block/#under-the-hood), which every watcher of a transport shares.

**`Ev.pages(events, { fromBlock, confirmations })`**

- **your program**: `cursor = fromBlock`

**on every head of `Block.watch`**

- **your program**: `target = head.number - confirmations`
  - while `cursor <= target`:
      - one block:
        - **your node** `eth_getLogs({ address, topics, blockHash })`
      - several:
        - **your node** `eth_getLogs({ address, topics, fromBlock: cursor, toBlock: end })`
        - **your node** `eth_getBlockByNumber(end, false)`: its hash, when the stream of blocks did not give it
    - **your program**: emits `{ fromBlock: cursor, toBlock: end, hash, events }`
    - **your program**: `cursor = end + 1`

| The head | What the pages do |
| --- | --- |
| follows the last one | the page of the block that is now deep enough |
| replaces blocks a page covered | `cursor` goes back to the first block that changed |
| replaces blocks no page covered yet | nothing: they were not deep enough |
| has a parent that was never given | `eth_getBlockByNumber(cursor - 1)`, and further back while the hash differs |
| was replaced before its block was read | `eth_getBlockByNumber(n)` after the node refused the block: another hash, so no page |

At the head of the chain, a new block costs one `eth_getLogs`.
