# Transport.chains

Every chain of an app, each with its node. [`Transport.on`](#on) says which chain a part of a
program is on, and [`Transport.chainId`](#chainid) gives the chain of the transport in
context.

## Usage

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

// One node per chain the program reads. The key is the chain id.
const Chains = Transport.chains({
  1: Transport.http("https://ethereum-rpc.publicnode.com"),
  8453: Transport.http("https://mainnet.base.org"),
}).pipe(Layer.provide(FetchHttpClient.layer));

const program = Effect.gen(function* () {
  const mainnet = yield* Eth.blockNumber().pipe(Transport.on(1));
  const base = yield* Eth.blockNumber().pipe(Transport.on(8453));
  return { mainnet, base };
});

const heights = await program.pipe(Effect.provide(Chains), Effect.runPromise);
```

An app on one chain provides one transport, and needs none of this. An app on several
provides `Transport.chains`, and each part of the program says which chain it is on.

### A program that does not say its chain does not compile

`Transport.chains` provides `Transport.Chains`, and no `Transport`. A call that is on no chain
still needs its transport, so it cannot run.

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

const Chains = Transport.chains({
  1: Transport.http("https://ethereum-rpc.publicnode.com"),
}).pipe(Layer.provide(FetchHttpClient.layer));

// Effect<bigint, …, Transport>: the chains were provided, and they are no transport
const height = Eth.blockNumber().pipe(Effect.provide(Chains));

// A program with a requirement left cannot run.
// @ts-expect-error
Effect.runPromise(height);
```

### A chain known only when the program runs

`Transport.on` takes a number, so the chain can come from a wallet, a route or a form. A
chain the app has no node for fails with [`TransportUnknownChain`](#unknownchain).

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

/** The height of the chain a wallet is on, or `undefined` where the app has no node. */
const heightOf = (chainId: number) =>
  Eth.blockNumber().pipe(
    Transport.on(chainId),
    Effect.catchTag("TransportUnknownChain", () => Effect.succeed(undefined)),
  );
// Effect<bigint | undefined, Method.Error, Transport.Chains>
```

### A URL with a key in it

Read it from the environment as a secret, and give it as it is. See
[the `url` of `Transport.http`](https://ethect.dev/reference/transport/http/#url).

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

const Chains = Layer.unwrap(
  Effect.gen(function* () {
    const mainnet = yield* Config.Redacted("MAINNET_RPC_URL");
    return Transport.chains({
      1: Transport.http(mainnet),
      8453: Transport.http("https://mainnet.base.org"),
    });
  }),
).pipe(Layer.provide(FetchHttpClient.layer));
// Layer<Transport.Chains, ConfigError>
```

## Returns

`Layer<Transport.Chains, never, R>`

A layer that provides `Transport.Chains`, and needs what its transports need: an `HttpClient`
for [`Transport.http`](https://ethect.dev/reference/transport/http/), a `WebSocketConstructor` for
[`Transport.webSocket`](https://ethect.dev/reference/transport/web-socket/).

## Parameters

### transports

- **Type:** `Record<number, Layer<Transport, never, R>>`

The transport of each chain, by chain id. Any transport fits, one of your own included. A
transport that can push gives its [`Subscriptions`](https://ethect.dev/reference/transport/#subscriptions) to
what is on its chain.

```ts
import { Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { Socket } from "effect/socket";
import { Transport } from "@ethect/core";

const Chains = Transport.chains({
  1: Transport.webSocket("wss://ethereum-rpc.publicnode.com"),
  8453: Transport.http("https://mainnet.base.org", { batch: {} }),
}).pipe(
  Layer.provide([Socket.layerWebSocketConstructorGlobal, FetchHttpClient.layer]),
);
```

A layer that can fail to be built is refused by the types: build such a transport first, and
handle its failure there.

## on

Says which chain a part of a program is on: the node of that chain is the `Transport` of
everything inside.

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

// An effect: both reads go to the node of Base.
const base = Effect.all([Eth.blockNumber(), Eth.gasPrice()], {
  concurrency: "unbounded",
}).pipe(Transport.on(8453));

// A stream: the blocks of mainnet.
const blocks = Block.watch.pipe(
  Stream.map((head) => head.number),
  Transport.on(1),
);
```

Put it around a whole part of the program, not around each call: everything inside is on
that chain.

### Returns

[`Transport.On<Self>`](https://ethect.dev/reference/transport/#types): the effect or the stream it was given,
which now needs `Transport.Chains` in place of `Transport`, and can fail with
[`TransportUnknownChain`](#unknownchain).

| Given | Returns |
| --- | --- |
| `Effect<A, E, Transport \| R>` | `Effect<A, E \| Transport.UnknownChain, Transport.Chains \| R>` |
| `Stream<A, E, Transport \| R>` | `Stream<A, E \| Transport.UnknownChain, Transport.Chains \| R>` |

### Parameters

| Parameter | Type | Description |
| --- | --- | --- |
| `chainId` | `number` | The id of the chain. It is a key given to `Transport.chains`: another one fails with [`TransportUnknownChain`](#unknownchain). |

## chainId

- **Type:** `Effect<number, Transport.Error, Transport>`

The chain id of the transport in context.

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

const program = Effect.gen(function* () {
  // 8453, and the node is not asked
  const chainId = yield* Transport.chainId;
  return `on chain ${chainId}`;
}).pipe(Transport.on(8453));
```

| The transport | The chain id is | The node is asked |
| --- | --- | --- |
| one of `Transport.chains`, under `Transport.on(id)` | `id`, the key it was given under | never |
| a transport provided alone | what the node answers `eth_chainId` | once: the answer is kept for as long as the transport lives |

A failure is not kept: the next time it is read, the node is asked again.

## UnknownChain

- **Type:** `Transport.UnknownChain`

A chain the program has no node for, or a node that is not on the chain it was given for.

| Property | Type | Holds |
| --- | --- | --- |
| `_tag` | `"TransportUnknownChain"` | the tag `Effect.catchTag` matches |
| `chainId` | `number` | the chain that was asked for |
| `message` | `string` | which of the two cases, with the chains involved |

The class is its own Schema: it is written as
`{ "_tag": "TransportUnknownChain", "chainId": 10, "message": "No transport was given for chain 10: …" }`
and read back as a `Transport.UnknownChain`. `new` checks nothing: with fields of their types, it never throws. Its tag was `"UnknownChain"`
in 0.1.0-alpha.0.

| When | `message` |
| --- | --- |
| `Transport.on(10)` and no transport was given for chain 10 | `No transport was given for chain 10: Transport.chains has 1, 8453` |
| the transport given for chain 1 answers `eth_chainId` with another chain | `The transport given for chain 1 is on chain 8453` |

## Behavior

- **Each transport is built the first time it is used.** A chain nobody is on opens no
  connection. Built once, a transport is kept until the layer is closed, and closed with it.
- **Built once under concurrent use.** Fifty reads that start together on a chain share the
  one transport, so calls made together can still leave [as one batch](https://ethect.dev/rpc/guides/batching/).
- **The node is asked which chain it is on, once.** The first use of a transport sends
  `eth_chainId`. A node on another chain is refused with `TransportUnknownChain`, on that use
  and on every later one, before anything is read from it.
- **A node that cannot be asked is not refused.** When that first `eth_chainId` fails, the
  transport is used unchecked: its calls fail by themselves while the node is away.
- **What is inside sees its chain only.** Under `Transport.on`, the `Transport` and the
  `Subscriptions` are those of the chain. A chain that cannot push hides the `Subscriptions`
  of a chain around it.
- **Shared blocks.** [`Block.watch`](https://ethect.dev/reference/block/) is one stream per transport, so one
  per chain, shared by every part of the program on that chain.
- **What the transports need is taken where the layer is provided.** The `HttpClient` of the
  transports is the one `Transport.chains` was built with.

## Errors

| Error | From | When |
| --- | --- | --- |
| `TransportUnknownChain` | `Transport.on` | no transport was given for the chain, or its node is on another chain |
| `RpcError`, `TransportError` | `Transport.chainId` | a transport provided alone could not say its chain |

Building the layer does not fail: a node that is away shows when it is used.

## Under the hood

Only the `Transport` of the chain is asked.

**`Transport.on(8453)`, the first time anything is on that chain**

- **your program**: the layer given for 8453 is built
- **your node** `eth_chainId`
  - `0x2105`: kept
  - anything else → fails: `TransportUnknownChain`

**`Transport.on(8453)`, every other time**

- **your program**: nothing is sent

**`Transport.chainId` under `Transport.on(8453)`**

- **your program**: nothing is sent

**`Transport.chainId` on a transport provided alone**

- **your node** `eth_chainId`: the first time, then nothing
