# Ev.Source

How the logs of [`Ev.watch`](https://ethect.dev/reference/ev/watch/) arrive: pushed by the node, collected by a
filter of the node, or read block by block. The default picks from what the transport can do,
and you can force one.

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

const { Transfer } = Erc20.ev;

// read block by block, whatever the transport can do
const transfers = (token: Address.Address) =>
  Ev.watch(Transfer, { address: token }).pipe(Stream.provideService(Ev.Source, Ev.polling));
```

| Export | Kind | How the logs arrive |
| --- | --- | --- |
| [`Ev.Source`](#source) | reference | the source `Ev.watch` reads. Default: `Ev.subscription`. |
| [`Ev.subscription`](#subscription) | source | `eth_subscribe("logs")`: pushed by the node |
| [`Ev.filter`](#filter) | source | `eth_newFilter`, then `eth_getFilterChanges` at every interval |
| [`Ev.polling`](#polling) | source | `eth_getLogs` for each new block, by its hash |

## Which one is used

Each source falls back on the next when it cannot work, so the default works over every
transport.

```text
Ev.subscription
  the transport cannot push, or the node refuses eth_subscribe   → Ev.filter
Ev.filter
  the node has no filters, or does not keep one                  → Ev.polling, for good
Ev.polling
  works wherever eth_getLogs does
```

| Source | After a gap | Reorgs |
| --- | --- | --- |
| `Ev.subscription` | on a new connection, `eth_getLogs` from 64 blocks before the last log given | the node sends the lost logs again, as `removed` |
| `Ev.filter` | a filter the node forgot is replaced, with `eth_getLogs` from 64 blocks before the last log given | the node sends the lost logs again, as `removed` |
| `Ev.polling` | [`Block.watch`](https://ethect.dev/reference/block/#watch) skips no block up to 256. Past that, `eth_getLogs` over the blocks in between. | it remembers 64 blocks, and gives their logs again as `removed` |

Forcing a source chooses where that chain starts. `Ev.filter` never subscribes, and
`Ev.polling` neither subscribes nor installs a filter.

A source is read by `Ev.watch` without `confirmations`. With `confirmations`, and in
[`Ev.pages`](https://ethect.dev/reference/ev/pages/), the logs are read block by block and no source is asked.

## Source

- **Type:** `Context.Reference<Ev.Source>`
- **Default:** `Ev.subscription`

The source of what is inside. Replace it around a stream, or around a whole program.

```ts
import { Effect } from "effect";
import { Ev } from "@ethect/core";

// every watch of the program asks through a filter, also over a WebSocket
const withFilters = Effect.provideService(Ev.Source, Ev.filter);
```

`Ev.Source` is also the type of a source: one function.

| Member | Type | Gives |
| --- | --- | --- |
| `logs` | `(filter) => Stream<Log.Log, Transport.Error, Transport>` | every log that matches, from a block on |

| `filter` | Type | Holds |
| --- | --- | --- |
| `address` (optional) | `Address.Address` or `ReadonlyArray<Address.Address>` | the contracts the logs come from |
| `topics` | `ReadonlyArray<Hex.Hex \| ReadonlyArray<Hex.Hex> \| null>` | the topics to match, as [`eth_getLogs`](https://ethect.dev/rpc/eth/get-logs/) takes them |
| `fromBlock` | `bigint` | the first block whose logs are asked for |

### A source of your own

A source gives the [logs](https://ethect.dev/rpc/types/log/) of the blocks from `fromBlock` on, the past ones
first, each once. A log the chain took back is given again with `removed`.

```ts
import { Stream } from "effect";
import { Ev } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

// the logs there are now, and none after: for a test, or a chain that is at rest
const once: Ev.Source = {
  logs: ({ fromBlock, ...criteria }) =>
    Stream.fromIterableEffect(Eth.getLogs({ ...criteria, fromBlock, toBlock: "latest" })).pipe(
      // a source fails as a transport does: a log that does not read is a defect
      Stream.catchTag("CodecError", (error) => Stream.die(error)),
    ),
};
```

## subscription

- **Type:** `Ev.Source`

The node pushes each log as its block is added: `eth_subscribe("logs")`.

- **On each connection, what the socket did not carry is read**, with `eth_getLogs`. That is
  the past, on the first connection, and what was mined while there was no connection, on each
  one that replaces it. The read starts 64 blocks before the last log given: the events of a
  reorg that happened meanwhile are in it.
- **The read comes once the node has the subscription.** The node is subscribed to first, and
  read when it has answered `eth_subscribe`: no log is mined between the two without being
  read or pushed, so none waits for the next one.
- **No log is given twice**, whether it was read or pushed.
- **A reorg is the node's to tell**: it pushes the lost logs again with `removed`. Only a log
  that was given is taken back.
- **A reorg while there was no connection is found by asking.** The node had nobody to tell.
  On each new connection, every block that held a log given is asked for by its number, the
  last 64 blocks at most. The logs of a block that is no longer there are given again with
  `removed`, before the logs that replaced them.
- **A connection that goes during that read leaves it to the next one.**
- **A transport that cannot push is asked through `Ev.filter`**, and so is a node that answers
  `eth_subscribe` with an error, as most wallets do.

## filter

- **Type:** `Ev.Source`

The node collects the logs in a filter, and is asked for them at every interval:
`eth_newFilter`, then `eth_getFilterChanges`.

- **The filter is installed first, then the past is read.** The node answers with the filter
  once it has it, so no block falls between the two.
- **It is asked with each new block**, or as often as [`Block.Interval`](https://ethect.dev/reference/block/#interval)
  says when one is set. The `interval` of `Ev.watch` sets it.
- **A filter the node forgot is replaced.** A node drops a filter that is not asked for a few
  minutes, and loses them all when it restarts. A new one is installed, and the logs are read
  from 64 blocks before the last one given.
- **A reorg between two filters is found by asking**, as between two connections of a
  subscription: every block that held a log given is asked for, and the logs of one that is
  no longer there are given again with `removed`.
- **The filter is removed when the stream ends**: `eth_uninstallFilter`. The stream does not
  wait for the answer.
- **A reorg is the node's to tell**: the lost logs come again with `removed` among the
  changes. Only a log that was given is taken back.
- **A node that has no filters is read with `Ev.polling`, for good.** So is one that takes a
  filter and does not know it when first asked, as behind a gateway that sends each request to
  another node.

## polling

- **Type:** `Ev.Source`

The logs of each new block are read by the hash of the block: `eth_getLogs({ blockHash })`,
with each head of [`Block.watch`](https://ethect.dev/reference/block/#watch).

- **One request per block**, whether or not it holds a log.
- **The past is read as a range** before the first block, as [`Ev.logs`](https://ethect.dev/reference/ev/logs/)
  reads it.
- **It tells the reorgs itself.** The logs given for the last 64 blocks are remembered. When a
  head replaces blocks, their logs are given again with `removed`, oldest first, then the logs
  of the new blocks.
- **When it cannot tell where a reorg starts, it reads further back.** That is right after the
  past was read as a range, of which only the last block is remembered. Up to 64 blocks are
  read again: what is no longer there is taken back, and what still is is not given twice.
- **A head the chain replaced before its block was read is not read.** The block that took
  its place comes with a next head.
- **When the stream of blocks starts over**, after more than 256 blocks were missed, the
  blocks remembered are checked by number, and the blocks in between are read as a range.
- **It works wherever `eth_getLogs` does.** It is what the two others fall back on.

## Under the hood

The `Transport` is asked, and its `Subscriptions` by `Ev.subscription`.

**`Ev.subscription`, on each connection**

- **your node** `eth_subscribe("logs", { address, topics })`
  - when the node has answered:
    - **your node** `eth_getBlockByNumber(n, false)`: each block that held a log given: 64 at most
    - **your node** `eth_getBlockByNumber("latest", false)`: the range to read ends at the head
    - **your node** `eth_getLogs({ address, topics, fromBlock: last, toBlock: "latest" })`
  - the stream ends:
    - **your node** `eth_unsubscribe(id)`

**`Ev.filter`**

- **your node** `eth_newFilter({ address, topics })`
- **your node** `eth_getBlockByNumber(n, false)`: each block that held a log given: 64 at most
- **your node** `eth_getBlockByNumber("latest", false)`
- **your node** `eth_getLogs({ address, topics, fromBlock: last, toBlock: "latest" })`
- **your node** `eth_getFilterChanges(id)`: with each new block, or at every interval
  - the node answers it with an error: a new filter, from the top
  - the stream ends:
    - **your node** `eth_uninstallFilter(id)`

**`Ev.polling`, on every head of `Block.watch`**

- **your node** `eth_getLogs({ address, topics, blockHash })`
  - the first head, or a head whose parent was never given:
    - **your node** `eth_getBlockByNumber(n, false)`: the blocks remembered, until one did not change
    - **your node** `eth_getLogs({ address, topics, fromBlock: last, toBlock: head - 1 })`

For `Ev.subscription` and `Ev.filter`, `last` is 64 blocks before the last log given, and no
earlier than the block they were asked from. After a read that gave nothing, it is the block
after the head. For `Ev.polling` it is the first block that was not read. A range the node
refuses is read in pieces, as [`Ev.logs`](https://ethect.dev/reference/ev/logs/#under-the-hood) does.

With `"auto"`, the default of `Block.Interval`, `Ev.filter` asks with each head of
[`Block.watch`](https://ethect.dev/reference/block/#under-the-hood), whose own requests are on its page.
