# Eth.subscribe.newHeads

A stream of the header of each block added to the chain, pushed by the node as it happens.

## Usage

```ts
import { Effect, Stream } from "effect";
import { Socket } from "effect/socket";
import { Transport } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const program = Eth.subscribe.newHeads().pipe(
  Stream.map((head) => head.number),
  Stream.take(3),
  Stream.runCollect,
);

const numbers = await program.pipe(
  Effect.provide(Transport.webSocket("ws://127.0.0.1:8545")),
  Effect.provide(Socket.layerWebSocketConstructorGlobal),
  Effect.runPromise,
);
// [3n, 4n, 5n]
```

The program subscribes, collects the numbers of the next three blocks, and unsubscribes when
`Stream.take(3)` ends the stream.

A subscription needs a transport that can push: WebSocket here, or IPC or EIP-1193. anvil mines
a block when it gets a transaction, so start it with `anvil --block-time 1` to see blocks
arrive on their own.

The examples below leave the transport out.

### Doing something for each block

`Stream.runForEach` runs an effect per header, for as long as the stream lives.

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

const watch = Eth.subscribe.newHeads().pipe(
  Stream.runForEach((head) =>
    Effect.log(`block ${head.number}: ${head.gasUsed} gas`),
  ),
);
```

```txt
[10:18:38.608] INFO (#15): block 6: 0 gas
[10:18:39.608] INFO (#15): block 7: 0 gas
```

`watch` never ends on its own. Interrupt it, or bound the stream with `Stream.take` or
`Stream.takeUntil`.

### Beside other calls

Fork the stream to keep it running while the program does something else. The subscription and
the calls share one connection.

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

const program = Effect.scoped(
  Effect.gen(function* () {
    yield* Eth.subscribe.newHeads().pipe(
      Stream.runForEach((head) => Effect.log(`block ${head.number}`)),
      Effect.forkScoped,
    );
    const chainId = yield* Eth.chainId();
    yield* Effect.sleep("1 minute");
    return chainId;
  }),
);
```

The fork lives as long as the scope: when `program` returns, the stream is interrupted and the
subscription is closed.

### The full block

A header has no transactions. Ask for the block when you need them.

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

const blocks = Eth.subscribe.newHeads().pipe(
  Stream.mapEffect((head) =>
    head.hash === null ? Effect.succeed(null) : Eth.getBlockByHash(head.hash, true),
  ),
);
```

## Returns

[`Stream<Block.Header, Method.Error, Subscriptions>`](https://ethect.dev/rpc/subscription/#opening-a-subscription)

Each item is a [`Block.Header`](https://ethect.dev/rpc/types/block/): the header fields of a block, without
its transactions.

## Parameters

None.

## Behavior

- **New blocks only.** The first item is the first block added after the subscription is
  opened. No past header is sent.
- **A reorg pushes the same heights again.** When blocks are replaced, the node pushes the new
  headers, with numbers the stream has already seen. Compare `parentHash` with the hash of the
  header before to notice it.
- **Unsubscribes when the stream ends.** When the stream ends or is interrupted, the transport
  sends `eth_unsubscribe`.
- **Carries on over a reconnection.** The subscription is issued again on the new connection.
  The headers of the blocks added in between are not replayed:
  [`Block.watch`](https://ethect.dev/reference/block/) reads them.
- **`bigint` quantities.** `number`, `timestamp`, `gasUsed` and the other quantities of a
  header are `bigint`. See [values on the wire](https://ethect.dev/rpc/guides/values/).

## Errors

The three [errors](https://ethect.dev/reference/errors/) every method can fail with. Here they fail the stream:

| Error | Reason | When |
| --- | --- | --- |
| `RpcError` | the node's own | the node refuses the subscription |
| `CodecError` | `on: "result"` | an item does not have the shape of a header |
| `TransportError` | `Unreachable` | the connection is lost and the reconnect schedule runs out |

With the HTTP transport the program does not compile: nothing provides `Subscriptions`.

## JSON-RPC method

`eth_subscribe` with the kind `newHeads`
