# Eth.subscribe.logs

A stream of the event logs matching a filter, pushed by the node as blocks are added to the
chain.

## Usage

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

const TOKEN = Address.makeUnsafe("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");

const program = Eth.subscribe
  .logs({
    address: TOKEN,
    // the first topic of an event is the hash of its signature
    topics: [Hash.keccak256Utf8("Transfer(address,address,uint256)")],
  })
  .pipe(Stream.take(5), Stream.runCollect);

const logs = await program.pipe(
  Effect.provide(Transport.webSocket("ws://127.0.0.1:8545")),
  Effect.provide(Socket.layerWebSocketConstructorGlobal),
  Effect.runPromise,
);
```

The program subscribes, collects the next five `Transfer` events of the contract, and
unsubscribes when `Stream.take(5)` ends the stream.

A subscription needs a transport that can push: WebSocket here, or IPC or EIP-1193. The
examples below leave the transport out.

The `topics` and the `data` of a log are hex. [`Ev.decode`](https://ethect.dev/reference/ev/decode/) reads them
as the events of a contract, and [`Ev.watch`](https://ethect.dev/reference/ev/watch/) is this subscription with
the decoding done.

### Doing something for each log

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

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

const TOKEN = Address.makeUnsafe("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");

const watch = Effect.gen(function* () {
  yield* Eth.subscribe.logs({ address: TOKEN }).pipe(
    Stream.runForEach((log) =>
      Effect.log(`${log.transactionHash} emitted ${log.topics[0]}`),
    ),
  );
});
```

### Every log

Without a filter, the node pushes every log of every new block.

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

const firstLog = Eth.subscribe.logs().pipe(Stream.take(1), Stream.runCollect);
```

### Handling a reorg

When a block is dropped, the node pushes its logs again with `removed` set. Undo what you did
with them.

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

const seen = new Set<Hash.Hash>();

const TOKEN = Address.makeUnsafe("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");

const track = Effect.gen(function* () {
  yield* Eth.subscribe.logs({ address: TOKEN }).pipe(
    Stream.runForEach((log) =>
      Effect.sync(() => {
        if (log.transactionHash === null) return;
        if (log.removed) seen.delete(log.transactionHash);
        else seen.add(log.transactionHash);
      }),
    ),
  );
});
```

## Returns

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

Each item is a [`Log`](https://ethect.dev/rpc/types/log/).

## Parameters

### filter (optional)

- **Type:** the `address` and `topics` of a [`Filter.Filter`](https://ethect.dev/rpc/types/filter/)

Which logs to push. Both fields are optional.

| Field | Type | Description |
| --- | --- | --- |
| `address` | `Address` or `ReadonlyArray<Address>` | the contract or contracts that emit the log |
| `topics` | `Filter.Topics` | the topics to match, by position: a hash, an array of alternatives, or `null` for any value |

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

const WETH = Address.makeUnsafe("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");
const USDC = Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
const RECIPIENT = Address.makeUnsafe("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");

const received = Effect.gen(function* () {
  return Eth.subscribe.logs({
    address: [WETH, USDC],
    topics: [
      Hash.keccak256Utf8("Transfer(address,address,uint256)"),
      null, // from: anyone
      `0x${RECIPIENT.slice(2).padStart(64, "0")}`, // to: padded to 32 bytes
    ],
  });
}).pipe(Stream.unwrap);
```

## Behavior

- **No block range.** The filter has no `fromBlock`, `toBlock` or `blockHash`: passing one is a
  type error. For logs that are already on chain, use
  [`Eth.getLogs`](https://ethect.dev/rpc/eth/get-logs/).
- **New logs only.** The stream starts with the logs of the first block added after the
  subscription is opened.
- **A reorg pushes dropped logs again.** The logs of a block that is replaced come a second
  time, with `removed: true`.
- **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 logs of the blocks added in between are not replayed: fetch them with `Eth.getLogs`.

## 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: "params"` | a topic is not 32 bytes: nothing is sent |
| `CodecError` | `on: "result"` | an item does not have the shape of a log |
| `TransportError` | `Unreachable` | the connection is lost and the reconnect schedule runs out |

## JSON-RPC method

`eth_subscribe` with the kind `logs`
