# Transports (Transport)

A transport carries JSON-RPC calls to a node or a wallet. Each one is a `Layer` that provides
the `Transport` service, and the `Subscriptions` service when its connection can push.

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

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

const chainId = await Eth.chainId().pipe(Effect.provide(Http), Effect.runPromise);
```

## Transports

| Constructor | Provides | Needs from the platform | Connects to |
| --- | --- | --- | --- |
| [`Transport.http(url, options?)`](https://ethect.dev/reference/transport/http/) | `Transport` | an `HttpClient` | a node over HTTP |
| [`Transport.webSocket(url, options?)`](https://ethect.dev/reference/transport/web-socket/) | `Transport`, `Subscriptions` | a `WebSocketConstructor` | a node over WebSocket |
| [`Transport.ipc(options?)`](https://ethect.dev/reference/transport/ipc/) | `Transport`, `Subscriptions` | a `Socket` | a node on the same machine |
| [`Transport.eip1193(provider)`](https://ethect.dev/reference/transport/eip1193/) | `Transport`, `Subscriptions` | nothing | a wallet, through its EIP-1193 provider |

The [Transports guide](https://ethect.dev/guides/transports/) explains how to choose one and where the platform
layers come from.

## Transport

- **Type:** a service with one member, `request(method, params)`

Sends one call and returns its `result` as the node sent it, undecoded. Every
[method](https://ethect.dev/rpc/method/) is written against this service, which is why a definition works
over every transport.

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

const version = Effect.gen(function* () {
  const transport = yield* Transport.Transport;
  return yield* transport.request("web3_clientVersion", []);
  // unknown: "anvil/v1.9.0" as the node sent it
});
```

| Member | Type |
| --- | --- |
| `request` | `(method: string, params: Transport.Params) => Effect<unknown, Transport.Error>` |

Call it directly only for a method you have no definition for and do not want to define. A
[definition](https://ethect.dev/rpc/method/make/) is one line and types both directions.

## Subscriptions

- **Type:** a service with two members: `subscribe(params)` and `opened(params)`

Opens an `eth_subscribe` subscription and streams the items the node pushes, undecoded. HTTP
does not provide it, so a program that subscribes does not compile against HTTP alone.

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

const firstHead = Effect.gen(function* () {
  const subscriptions = yield* Transport.Subscriptions;
  return yield* subscriptions.subscribe(["newHeads"]).pipe(Stream.runHead);
});
```

| Member | Type |
| --- | --- |
| `subscribe` | `(params: ReadonlyArray<unknown>) => Stream<unknown, Transport.Error>` |
| [`opened`](#opened) | `(params: ReadonlyArray<unknown>) => Stream<Transport.Opened, Transport.Error>` |

`params` are the params of `eth_subscribe`: the kind, then its own params. The subscription is
cancelled with `eth_unsubscribe` when the stream ends. The typed kinds are under
[`Eth.subscribe`](https://ethect.dev/rpc/eth/subscribe/), and
[`Subscription.make`](https://ethect.dev/rpc/subscription/make/) defines another.

[`Transport.subscriptionsOver(connection)`](https://ethect.dev/reference/transport/subscriptions-over/) builds
this service for a transport of your own.

### opened

The same subscription, said each time the node takes it: when it answers `eth_subscribe` on
the connection that is open, then on each connection that replaces it. Use it when you read
the node besides listening to it.

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

/** What a subscription pushes, with `catchUp` read first each time the node takes it. */
const withCatchUp = <A, E, R>(params: ReadonlyArray<unknown>, catchUp: Effect.Effect<A, E, R>) =>
  Stream.unwrap(
    Effect.map(Transport.Subscriptions, ({ opened }) =>
      opened(params).pipe(
        // the node has the subscription: nothing happens between this read and what it pushes
        Stream.switchMap(({ items }) => Stream.concat(Stream.fromEffect(catchUp), items)),
      ),
    ),
  );
// Stream<unknown, E | Transport.Error, R | Subscriptions>
```

A `Transport.Opened` is the answer of the node, and what follows it.

| Field | Type | Holds |
| --- | --- | --- |
| `id` | `string` | the id the node answered `eth_subscribe` with |
| `items` | `Stream<unknown, Transport.Error>` | the items the node pushes under that id |

- **The read comes after the answer.** A node pushes from the moment it answers. What you read
  when an `Opened` comes, with its `items`, misses nothing: neither what happened while there
  was no connection, nor what happens while the subscription is being made. A read made when
  the stream starts, or when a connection is established, can be followed by something that is
  neither read nor pushed.
- **No item is missed, however late you read them.** The items are listened to from before the
  request is sent. Those pushed while your read is under way wait, and come after it.
- **Some of them you have already read.** What the node pushes between its answer and your
  read is in both: tell an item you have by its hash, or by its place in its block.
- **The items of one end with it.** Read them inside the stream, with `Stream.switchMap`: when
  the next `Opened` comes, or when the stream is no longer run, the subscription is cancelled.
- **`subscribe` is `opened` for whoever does not read**:
  `opened(params).pipe(Stream.switchMap(({ items }) => items))`.

| The transport | `opened` emits |
| --- | --- |
| WebSocket, IPC | each time the node answers `eth_subscribe` on a connection. It fails with the node's error when the node refuses the subscription, and when the transport gives up reconnecting. |
| EIP-1193, or one of your own with a single connection | once. A wallet that relays to a node may answer before its node has the subscription: the answer is the wallet's. |

[`Block.watch`](https://ethect.dev/reference/block/) and [`Ev.subscription`](https://ethect.dev/reference/ev/source/#subscription)
are built on it.

## Several chains

An app on one chain provides one transport. An app on several provides one per chain, and each
part of the program says which chain it is on.

| Export | Kind | Description |
| --- | --- | --- |
| [`Transport.chains(transports)`](https://ethect.dev/reference/transport/chains/) | layer | Every chain of an app, each with its node, by chain id. Each transport is built the first time it is used, and kept. |
| [`Transport.on(chainId)`](https://ethect.dev/reference/transport/chains/#on) | function | Says which chain an effect or a stream is on: the node of that chain is its `Transport`. |
| [`Transport.chainId`](https://ethect.dev/reference/transport/chains/#chainid) | effect | The chain id of the transport in context. Under `Transport.on` it is the id given. For a transport alone, the node is asked once, with `eth_chainId`, and the answer is kept for as long as the transport lives. |
| [`Transport.Chains`](https://ethect.dev/reference/transport/chains/#returns) | service | What `Transport.chains` provides. It is not a `Transport`: against several chains, a program that does not say its chain does not compile. |
| [`Transport.UnknownChain`](https://ethect.dev/reference/transport/chains/#unknownchain) | error | A chain the program has no node for, or a node that is not on the chain it was given for. It holds the `chainId`. |

## Types

| Type | Is |
| --- | --- |
| `Transport.Error` | what a transport can fail with: `RpcError \| TransportError`. Also a value: the Schema of that type, to declare in the failure of a query or of a command |
| `Transport.Url` | where a node is: a `string`, or a `Redacted<string>` for a URL with a key in it, which is then [never written](https://ethect.dev/reference/transport/http/#url) |
| `Transport.On` | what `Transport.on` makes of an effect or a stream: it needs `Transport.Chains` in place of `Transport`, and can fail with `Transport.UnknownChain` |
| `Transport.Params` | the `params` of a request: an array, or an object for the few methods that take them by name |
| `Transport.HttpOptions` | the options of [`Transport.http`](https://ethect.dev/reference/transport/http/#options-optional) |
| `Transport.SocketOptions` | the options of [`Transport.webSocket`](https://ethect.dev/reference/transport/web-socket/#options-optional) and [`Transport.ipc`](https://ethect.dev/reference/transport/ipc/#options-optional) |
| `Transport.Opened` | a subscription as the node holds it on one connection: the `id` it answered `eth_subscribe` with, and the `items` it pushes under it. What [`opened`](#opened) emits. |
| `Transport.PushConnection` | what [`Transport.subscriptionsOver`](https://ethect.dev/reference/transport/subscriptions-over/#connection) takes: `request`, `items`, `scope`, and `connections` and `isLive` for a transport that reconnects |
| `Transport.PushedItem` | an item a node pushed, under the id of its subscription: `{ subscription, result }` |

## Behavior

- **Plain JSON-RPC 2.0.** A request is `jsonrpc`, `id`, `method` and `params`, and nothing
  else.
- **A layer is built where it is provided.** Each `Effect.provide(transport)` that reaches
  `Effect.runPromise` builds a transport of its own: a new HTTP batcher, or a new socket
  connection. Provide it once, around the whole program. See
  [Transports](https://ethect.dev/guides/transports/#provide-it-once).
- **A transport is scoped.** A socket transport closes its connection when the scope that
  built its layer closes, which is when the program it was provided to ends.
- **No timeout.** No transport gives up on a slow call. Use `Effect.timeout` on the call.
- **No retry.** A failed call is not sent again. Use `Effect.retry` on the calls that are safe
  to repeat.

[Custom transports](https://ethect.dev/guides/custom-transports/) shows how to write a layer that provides these
services.
