# An indexer that survives reorgs

Save every deposit of a vault into a store, and keep going as blocks come. Stop it when you
want: it starts again where it stopped.

```ts title="indexer.ts"
import { Effect, Stream } from "effect";
import { FetchHttpClient } from "effect/http";
import { Address, Erc4626, Ev, Transport } from "@ethect/core";

// The vault whose deposits are kept.
const VAULT = Address.makeUnsafe("0x83F20F44975D03b1b09e64809B757c47f942BEeA");

// The event of the standard, built in, and what one deposit is once decoded.
export const { Deposit } = Erc4626.ev;
export type Deposit = Ev.Of<typeof Deposit>;

// The store, in memory here. Yours is a database: what it keeps, and one function.
export const store = {
  deposits: [] as Array<Deposit>,
  cursor: 19_000_000n, // the first block to read
  save(page: Ev.Page<typeof Deposit>) {
    this.deposits.push(...page.events);
    this.cursor = page.toBlock + 1n; // written with the deposits, in one transaction
  },
};

// The past from the cursor on, then each new block once 64 blocks follow it.
const indexer = Ev.pages(Deposit, { address: VAULT, fromBlock: store.cursor, confirmations: 64 }).pipe(
  Stream.runForEach((page) => Effect.sync(() => store.save(page))),
);

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

- **`Ev.pages`** is a stream: many values over time, where an `Effect` is one. It does not end
  by itself.
- **`Stream.runForEach`** is a `for await` loop over it. `Effect.sync` wraps the plain
  function that saves.
- **`Effect.provide`** gives the program its node. No signer is needed to read.

## A page

A page is a range of blocks, the deposits in it, and where it ends.

| Field | Holds |
| --- | --- |
| `fromBlock`, `toBlock` | the first and the last block of the range |
| `hash` | the hash of block `toBlock` |
| `events` | the deposits of these blocks, in the order of the chain |

- **The past comes in ranges as wide as your node accepts.** A node limits how many blocks or
  logs one request may cover. The limit is found for you: you do not cut ranges by hand.
- **Then each new block is a page.** The same loop reads the past and follows the chain.
- **A range with no deposit is a page too**, with no events. Your cursor moves all the same.
- **Each deposit knows where it comes from**: `deposit.log.blockNumber`,
  `deposit.log.transactionHash`.

## Stop and start again

The cursor is the block after the last page you saved: `page.toBlock + 1n`. It is the
`fromBlock` of the next run.

- **Save the deposits and the cursor in one write.** In a database, that is one transaction.
  A crash then leaves a page saved whole or not at all, and never deposits without their
  cursor.
- **Nothing is missed, and nothing comes twice.** The pages follow each other: each starts at
  the block after the one before it.
- **A failure ends the stream.** A node that is away fails the program with a
  `TransportError`. Start it again: it reads from the cursor.

## Reorgs, the simple way

A reorg replaces the last blocks of the chain by others. A deposit you saved may not be in
the new ones.

With `confirmations: 64`, a page is given once 64 blocks follow its last block. Pick a number
larger than any reorg of your chain: no block that deep is replaced, so **nothing you saved
is ever taken back**. The code above is the whole indexer.

The price is to be that many blocks behind the chain: about thirteen minutes on Ethereum.

## Reorgs, the fast way

Without `confirmations`, a deposit is saved as soon as its block exists. A reorg can then
replace blocks you saved. The next page starts at the first block that changed, and one rule
covers it:

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

The past comes as pages of several blocks, then the head as one page per block, each page ending at its cursor. When a block is replaced, the next page starts earlier than the cursor: everything from that block on is replaced.

```ts title="store.ts"
import type { Ev, Hash } from "@ethect/core";
import type { Deposit } from "./indexer";

export const store = {
  deposits: [] as ReadonlyArray<Deposit>,
  cursor: 19_000_000n,
  hash: undefined as Hash.Hash | undefined,
  save(page: Ev.Page<typeof Deposit>) {
    // The one rule: what was saved from the first block of the page on is replaced.
    const kept = this.deposits.filter((deposit) => deposit.log.blockNumber < page.fromBlock);
    this.deposits = [...kept, ...page.events];
    this.cursor = page.toBlock + 1n;
    this.hash = page.hash; // the hash of the block before the cursor
  },
};
```

For a page that follows the one before it, nothing is at or after its `fromBlock`: the filter
drops nothing. So the same `save` takes every page. In SQL it is a
`DELETE … WHERE block >= fromBlock`, then the inserts, in one transaction.

A reorg that happens while the indexer is stopped is not seen: a new run knows nothing of
what you saved. That is what `hash` is for. Compare it with the chain before you start.

```ts title="start.ts"
import { Effect } from "effect";
import { Eth } from "@ethect/core/rpc";
import { store } from "./store";

/** Deeper than any reorg of the chain. */
const DEPTH = 64n;

/** Where to start: the cursor, or earlier when the last block saved is no longer on the chain. */
export const start = Effect.gen(function* () {
  if (store.hash === undefined) return store.cursor; // nothing was saved yet
  const last = yield* Eth.getBlockByNumber(store.cursor - 1n, false);
  // Replaced while nothing was indexing: start before the reorg, and the rule does the rest.
  return last?.hash === store.hash ? store.cursor : store.cursor - DEPTH;
});
```

Give what `start` returns as `fromBlock`, and leave `confirmations` out. A first page that
starts earlier replaces what follows, like any other.

| | The simple way | The fast way |
| --- | --- | --- |
| `confirmations` | larger than any reorg | none |
| A deposit is saved | that many blocks later | as soon as its block exists |
| `save` | adds | replaces from `page.fromBlock` on, then adds |
| At start | reads from the cursor | compares `hash` with the chain first |
| What it does not see | a reorg deeper than `confirmations` | a reorg deeper than `DEPTH` while it was stopped |

## Under the hood

One service is asked: the `Transport`. The pages are driven by the blocks of
[`Block.watch`](https://ethect.dev/reference/block/), which every watcher of a transport shares.

**the past, from the cursor to the head less the confirmations**

- **your node** `eth_getLogs({ address, topics, fromBlock, toBlock })`: one request per range the node accepts
- **your node** `eth_getBlockByNumber(toBlock, false)`: the hash of the page

**at the head: one page per block**

- **your node** `eth_getBlockByNumber("latest", false)`: a new head, polled. Pushed over a WebSocket
- **your node** `eth_getLogs({ address, topics, blockHash })`: by hash: one version of the block, no other

**a head that does not follow the last one: a reorg**

- **your node** `eth_getBlockByHash(parentHash, false)`: back to a block that was given
- **your program**: the next page starts at the first block that changed

- **The last 64 blocks the pages covered are remembered.** A reorg deeper than that is not
  followed to its start: the page starts 64 blocks before the oldest one remembered.
- **Over a WebSocket the blocks are pushed.** The code does not change: see
  [`Transport.webSocket`](https://ethect.dev/reference/transport/web-socket/).

Every option, and what a page does in each case of a reorg, are on
[`Ev.pages`](https://ethect.dev/reference/ev/pages/). For events as they come, one by one, see
[`Ev.watch`](https://ethect.dev/reference/ev/watch/).
