# Connection.layer

The [connection](https://ethect.dev/reference/connection/) of an app, as a layer over its
[wallets](https://ethect.dev/reference/wallets/). It starts from what storage held, and asks no wallet anything
until you connect.

## Usage

```ts
import { Layer, ManagedRuntime } from "effect";
import { FetchHttpClient } from "effect/http";
import { Connection, Signer, Transport, Wallets } from "@ethect/core";

// The layers of an app, read from the bottom up.
const App = Signer.connected().pipe( // 4. signs with the connected wallet
  Layer.provideMerge(Connection.layer()), // 3. which wallet is connected
  Layer.provideMerge(Wallets.browser), // 2. which wallets are installed
  Layer.provideMerge(Transport.http("https://ethereum-rpc.publicnode.com")), // 1. the node it reads from
  Layer.provide(FetchHttpClient.layer),
);

// Built once, for the life of the page: the connection is the one of the runtime.
const runtime = ManagedRuntime.make(App);
```

An app on several chains gives
[`Transport.chains`](https://ethect.dev/reference/transport/chains/) in place of `Transport.http`. Nothing else
changes.

### What storage held

`initial` is the state the last visit stored. A stored connection starts as `reconnecting`:
enough to render with, and not yet confirmed by the wallet.

```ts
import { Effect, Layer } from "effect";
import { Connection, Wallets } from "@ethect/core";

// `cookies` is `document.cookie`, which the app wrote to with `Connection.toCookie`.
const App = (cookies: string | undefined) =>
  Connection.layer({ initial: Connection.fromCookie(cookies) }).pipe(
    Layer.provideMerge(Wallets.browser),
  );

// In the browser, on load: ask the remembered wallet for its accounts, without a prompt.
const onLoad = Effect.gen(function* () {
  const before = yield* Connection.get; // { status: "reconnecting", wallet: "io.metamask", … }
  const after = yield* Connection.reconnect; // "connected", or "disconnected" if the wallet is gone
  return { before, after };
});
```

See [`Connection.toCookie`](https://ethect.dev/reference/connection/cookie/) for the cookie,
[`Connection.toJson`](https://ethect.dev/reference/connection/json/) for what it holds, and
[`Connection.reconnect`](https://ethect.dev/reference/connection/connect/#reconnect) for what confirms it.

### On a server

The same layers with no wallet. The state of the cookie is the state, and nothing can sign.

```ts
import { Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { Connection, Signer, Transport, Wallets } from "@ethect/core";

// `cookies` is the `Cookie` header of the request, or `null` when it has none.
const Server = (cookies: string | null) =>
  Signer.connected().pipe(
    Layer.provideMerge(Connection.layer({ initial: Connection.fromCookie(cookies) })),
    Layer.provideMerge(Wallets.of([])),
    Layer.provideMerge(Transport.http("https://ethereum-rpc.publicnode.com")),
    Layer.provide(FetchHttpClient.layer),
  );
```

`Wallets.browser` works there too: where there is no `window` it is an empty list. Building
these layers on a server touches no browser API.

### How long a wallet is waited for

A browser wallet announces itself a moment after the page loads.
[`reconnect`](https://ethect.dev/reference/connection/connect/#reconnect) waits for the remembered one, and
gives up after `reconnectTimeout`. Once the wallet is there, its answer is waited for as long
again.

```ts
import { Connection } from "@ethect/core";

declare const stored: Connection.State;
const Patient = Connection.layer({ initial: stored, reconnectTimeout: "5 seconds" });
```

## Returns

`Layer<Connection.Connection, never, Wallets.Wallets>`

A layer that provides the [`Connection` service](https://ethect.dev/reference/connection/#the-service). It
needs the [`Wallets`](https://ethect.dev/reference/wallets/) of the app, and building it cannot fail.

## Parameters

### options.initial (optional)

- **Type:** [`Connection.State`](https://ethect.dev/reference/connection/state/)
- **Default:** `{ status: "disconnected" }`

What storage held, usually the result of
[`Connection.fromCookie`](https://ethect.dev/reference/connection/cookie/#fromcookie) or of
[`Connection.fromJson`](https://ethect.dev/reference/connection/json/#fromjson).

| `initial` is | The connection starts as |
| --- | --- |
| `reconnecting`, or `connected` | `reconnecting`, with the same wallet, accounts and chain |
| `disconnected`, `connecting`, or not given | `disconnected` |

### options.reconnectTimeout (optional)

- **Type:** `Duration.Input`
- **Default:** `"2 seconds"`

How long [`reconnect`](https://ethect.dev/reference/connection/connect/#reconnect) waits, twice over. A number
is milliseconds.

| It waits for | Up to | Past it |
| --- | --- | --- |
| the remembered wallet to be among the `Wallets` | `reconnectTimeout` | `disconnected` |
| then that wallet's provider and its answer, together | `reconnectTimeout` again | `disconnected` |

So a reconnection takes twice `reconnectTimeout` at most: four seconds by default. It cannot
wait without end, and neither can a send that waits for it.

The first wait is only for a list that may still grow. Over
[`Wallets.of`](https://ethect.dev/reference/wallets/#of), or `Wallets.browser` where there is no `window`, a
wallet that is not listed ends the reconnection at once.

## Behavior

- **One connection per layer.** Build the layer once, in the runtime of the app. Each build
  has a state of its own.
- **No wallet is asked when it is built.** No request, no listener, no prompt: a wallet is
  first asked by `connect` or by `reconnect`.
- **A stored connection is not a connection.** It starts as `reconnecting`, and stays so
  until `reconnect` runs. What it holds comes from a cookie: it is good enough to render
  with, and it proves nothing.
- **One wallet at a time.** Connecting another wallet lets go of the one before.
- **Everything goes when its scope closes.** The listeners on the connected wallet are
  removed, a `connect` that waits for its prompt is interrupted, and a `reconnect` that waits
  for its wallet is too.

## Under the hood

**building the layer**

- **your program**: the state is `initial`, read as above. No wallet is asked

**while a wallet is connected**

- **your program**: listens to `accountsChanged`, `chainChanged` and `disconnect` on its provider
- **the wallet** `eth_accounts`: a `disconnect` asks it, once: the connection stays if the wallet still has accounts

**the layer's scope closes**

- **your program**: the listeners are removed

The requests are sent by [`connect` and `reconnect`](https://ethect.dev/reference/connection/connect/) and by
[`switchChain`](https://ethect.dev/reference/connection/switch-chain/).
