# Blocks (Block)

New blocks, as one stream per transport that everyone who watches shares. A block is pushed
when the transport can push, and polled otherwise: the line you write is the same. This module
is the one of `@ethect/core`: the shape of a block on the wire is
[`Block`](https://ethect.dev/rpc/types/block/) of `@ethect/core/rpc`.

```ts
import { Effect, Layer, Stream } from "effect";
import { FetchHttpClient } from "effect/http";
import { Block, Transport } from "@ethect/core";

const Http = Transport.http("http://127.0.0.1:8545").pipe(
  Layer.provide(FetchHttpClient.layer),
);

// Logs the latest block, then each new one, until the program is stopped.
const watch = Block.watch.pipe(
  Stream.runForEach((head) => Effect.log(`block ${head.number}`)),
);

await watch.pipe(Effect.provide(Http), Effect.runPromise);
```

| Export | Kind | Description |
| --- | --- | --- |
| [`Block.watch`](#watch) | stream | The latest block at once, then every new one. |
| [`Block.Head`](#head) | type | What a watcher gets of a block: `number`, `hash`, `parentHash`, `timestamp`, `baseFeePerGas`. |
| [`Block.Interval`](#interval) | reference | How often to ask a transport that cannot push. |

## watch

The latest block at once, then every new one, in order. It needs a
[`Transport`](https://ethect.dev/reference/transport/#transport) and nothing else.

### Keep a read fresh

Read again at every block, and tell only when the value moved.

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

/** The balance of an account, each time it changes. */
const balanceOf = (account: Address.Address) =>
  Block.watch.pipe(
    Stream.mapEffect((head) => Eth.getBalance(account, { blockHash: head.hash })),
    Stream.changes,
  );
// Stream<bigint, Method.Error, Transport>
```

The read names the block by its hash, so it is the balance at that block whatever a reorg
does next. `Stream.changes` drops a value equal to the one before it.

### Wait for the next block

```ts
import { Effect, Stream } from "effect";
import { Block } from "@ethect/core";

// The latest block is given at once: the block after it is the second.
const nextBlock = Block.watch.pipe(
  Stream.drop(1),
  Stream.runHead,
);
// Effect<Option<Block.Head>, Transport.Error, Transport>
```

### On one of several chains

With [`Transport.chains`](https://ethect.dev/reference/transport/chains/), say the chain of the stream. Each
chain has a stream of its own.

```ts
import { Effect, Stream } from "effect";
import { Block, Transport } from "@ethect/core";

const onBase = Block.watch.pipe(
  Transport.on(8453),
  Stream.runForEach((head) => Effect.log(`Base is at ${head.number}`)),
);
// Effect<void, Transport.Error | Transport.UnknownChain, Transport.Chains>
```

### Returns

`Stream<Block.Head, Transport.Error, Transport>`

A stream of [`Block.Head`](#head). It does not end by itself: it stops when you stop reading
it, with `Stream.take`, `Stream.runHead` or by interrupting its fiber.

### Behavior

- **It starts with the latest block.** Each watcher gets it at once, whenever it starts. A
  page that shows a value per block does not wait for the next block to show the first one.
- **One per transport.** However many watch, there is one subscription or one poller. It
  starts with the first watcher and stops with the last. A watcher that joins gets the latest
  block from the stream, and the node is not asked for it.
- **No block is skipped, up to 256.** When the head moved by more than one block, the blocks
  in between are read and given in order. A head more than 256 blocks ahead of the last block
  given is given alone, and nothing in between is asked for: a process that slept a night does
  not read every block of that night.
- **A reorg is shown.** The new blocks are given from the common ancestor, so a number can
  come twice. See [What a reorg looks like](#what-a-reorg-looks-like).
- **The latest block is read once the node has the subscription.** On each connection the
  node is subscribed to first, and read when it has answered: no block is mined between the
  two without being read or pushed, so none comes late, with the block after it.
- **After a reconnection, what was missed is read.** That same read, on the connection that
  replaces one, gives the blocks mined while there was none.
- **A request that a dropped connection fails does not fail the stream.** What was under way
  on that connection is left, and done again on the next one.
- **A node that refuses the subscription is polled.** Most wallets take `eth_subscribe` and
  answer it with an error. The stream then asks at every interval, as over HTTP.
- **A poller knows the pace of the chain from its first pause.** Under the `"auto"`
  [interval](#interval), it reads the parent of the first block once, after giving that
  block: on a chain of 2 s blocks, the next block is asked for after one second, not four.
- **The last 256 blocks are remembered, and that is as far as the stream goes.** A reorg is
  walked back that far, and a head is walked up to when it is that far ahead. Past that,
  either way, the stream starts over: it gives a block whose parent it never gave. See
  [What a reorg looks like](#what-a-reorg-looks-like).
- **Its requests are spans with no parent.** The stream outlives the watcher that started it,
  so its `eth_getBlockByNumber` are traced on their own, under no span of your program.
- **A failure ends the stream for all who watch.** The next watcher starts it again, from the
  latest block.
- **Blocks are buffered without limit.** A watcher slower than the chain lets its buffer grow.

### Errors

| Error | Reason | When |
| --- | --- | --- |
| `TransportError` | `Unreachable` | over HTTP, a request failed. Over a socket, the transport gave up reconnecting. |
| `TransportError` | `HttpStatus` | the server answered a request with an error status |
| `TransportError` | `MalformedResponse` | a block the node sent does not have the shape of a block |
| `RpcError` | the node's | the node answered a request for a block with an error, such as a rate limit |

A socket transport that is reconnecting does not fail the stream, nor does a request it was
making when the connection went: the stream waits, then reads what it missed. See
[Connection lifecycle](https://ethect.dev/concepts/connection-lifecycle/).

### Under the hood

The `Transport` is asked, and its `Subscriptions` when the transport has one.

**the transport pushes: WebSocket, IPC, a provider that serves `eth_subscribe`**

- **your node** `eth_subscribe("newHeads")`: once per connection, for all who watch
- **your node** `eth_getBlockByNumber("latest", false)`: when the node has answered `eth_subscribe`: on the first connection, and on each one after

**it does not, or the node refuses `eth_subscribe`**

- **your node** `eth_getBlockByNumber("latest", false)`: at once, then at every interval
- **your node** `eth_getBlockByHash(parentHash, false)`: under the `"auto"` interval, once, after the first block is given: its parent, so that the pace is known from the first pause

**the head is more than one block ahead, and 256 at most**

- **your node** `eth_getBlockByNumber(n, false)`: the blocks in between, 16 at a time, together

**the head is more than 256 blocks ahead**

- **your program**: nothing is asked: the head is given alone, and the stream starts over

**the head does not follow the last block given: a reorg**

- **your node** `eth_getBlockByHash(parentHash, false)`: its parents, back to a block that was given, and no further back than 256 blocks

**the head is below every block remembered**

- **your node** `eth_getBlockByNumber(oldest, false)`: the oldest block remembered. Still there: the head is an older block, and nothing new

**the last watcher stops**

- **your node** `eth_unsubscribe(id)`

## Head

- **Type:** `Block.Head`

What a watcher gets of a block: where it is, what it follows, and what its gas costs.

| Field | Type | Holds |
| --- | --- | --- |
| `number` | `bigint` | the height of the block |
| `hash` | [`Hash.Hash`](https://ethect.dev/reference/primitives/hash/) | the hash of the block |
| `parentHash` | [`Hash.Hash`](https://ethect.dev/reference/primitives/hash/) | the hash of the block it follows |
| `timestamp` | `bigint` | when it was mined, in seconds since the Unix epoch |
| `baseFeePerGas` | `bigint`, optional | the base fee of the block, in wei per gas. Absent where a header has none: a chain before London |

The base fee is read from the header, pushed or polled: it costs no request.

For the rest of a block, read it by its hash with
[`Eth.getBlockByHash`](https://ethect.dev/rpc/eth/get-block-by-hash/).

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

/** Each new block in full, with its transactions. */
const blocks = Block.watch.pipe(
  Stream.mapEffect((head) => Eth.getBlockByHash(head.hash, true)),
);
```

## Interval

- **Type:** `Context.Reference<Duration.Input | "auto">`
- **Default:** `"auto"`

How often a transport that cannot push is asked for its latest block. It is read when the
stream of a transport starts, and has no effect on a transport that pushes.

| Value | The node is asked |
| --- | --- |
| `"auto"` | every half of the time between the last two blocks, and never more often than every 250 ms or less often than every 4 s. The parent of the first block is read once when the poller starts, so this holds from the first pause: every second on a chain of 2 s blocks, every 4 s on Ethereum. A node that cannot give that parent is asked every 4 s until a second block is polled. |
| a `Duration` input, such as `"1 second"` | that often |

```ts
import { Effect, Stream } from "effect";
import { Block } from "@ethect/core";

// Asks every second, whatever the pace of the chain.
const watch = Block.watch.pipe(
  Stream.runForEach((head) => Effect.log(`block ${head.number}`)),
  Effect.provideService(Block.Interval, "1 second"),
);
```

The poller is shared: its interval is the one of the watcher that started it. Set it once,
around the whole program.

## What a reorg looks like

A reorg replaces the last blocks of the chain by others. The stream does not hide it: it
gives the new blocks, from the first one that differs.

```text
the chain was     100 ── 101 ── 102
the chain is      100 ── 101'── 102'── 103'

the stream gave   100, 101, 102
then gives        101', 102', 103'
                  ^ its parentHash is the hash of 100, not of 102
```

A number comes twice: `101` and `102` are given again, as other blocks. One rule says what a
block is: look at its `parentHash`.

| The `parentHash` of a block is the hash of | The block | What to do |
| --- | --- | --- |
| the block given before it | is the next block | go on |
| an earlier block that was given | starts a reorg: the blocks given after that one are replaced | do again what you derived from the blocks replaced |
| no block that was given | starts the stream over | read again what you derived from the blocks seen |

The stream starts over when it cannot say what happened in between: after a reorg deeper
than 256 blocks, or with a head more than 256 blocks ahead of the last block given, as when a
process slept. The first block a watcher gets is of that kind too: nothing was given before
it.

```ts
import { Stream } from "effect";
import { Block } from "@ethect/core";

/** Each block, with what it is to the blocks given before it. */
const told = Block.watch.pipe(
  Stream.mapAccum(
    () => [] as ReadonlyArray<Block.Head>,
    (given, head) => {
      const parent = given.findLastIndex((block) => block.hash === head.parentHash);
      const is =
        parent === -1
          ? ("start" as const) // its parent was never given: the first block, or a start over
          : parent === given.length - 1
            ? ("next" as const) // it follows the block before it
            : ("reorg" as const); // it replaces the blocks given after its parent
      // the blocks still on the chain: those up to its parent, then this one
      return [[...given.slice(0, parent + 1), head].slice(-256), [{ head, is }]] as const;
    },
  ),
);
// Stream<{ head: Block.Head, is: "start" | "next" | "reorg" }, Transport.Error, Transport>
```

| The head of the node | The stream gives |
| --- | --- |
| follows the last block given | that block |
| is up to 256 blocks ahead | the blocks in between, then the head |
| is more than 256 blocks ahead | the head alone: the stream starts over |
| is a block already given | nothing |
| follows another block than the last one given | its ancestors that were not given, then the head |
| is on a chain that left the blocks given more than 256 blocks back | the last blocks of that chain: the stream starts over |
