# Connection.State

The state of a [connection](https://ethect.dev/reference/connection/): plain data that says which wallet the app
is connected to, with which accounts, on which chain, in one of four cases.

## Usage

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

// What a header shows. `status` tells the four cases apart.
const label = (state: Connection.State): string => {
  switch (state.status) {
    case "disconnected":
      return "Connect a wallet";
    case "connecting":
      return `Confirm in ${state.wallet}`; // its prompt is open
    case "reconnecting": // what storage held, not confirmed yet
      return state.accounts[0] ? Address.checksum(state.accounts[0]) : "Connect a wallet";
    case "connected": // the account the wallet shows as active, in its EIP-55 form
      return Address.checksum(state.accounts[0]);
  }
};

// The label now, and again each time the user changes account, chain or wallet.
const header = (render: (text: string) => void) =>
  Connection.changes.pipe(Stream.runForEach((state) => Effect.sync(() => render(label(state)))));
```

The state is plain data: it has no method and holds no provider. That is what lets it be
[stored in a cookie](https://ethect.dev/reference/connection/cookie/) and rendered on a server.

## The four states

| `status` | Type | Holds | Means |
| --- | --- | --- | --- |
| `"disconnected"` | `Connection.Disconnected` | nothing | No wallet is connected. |
| `"connecting"` | `Connection.Connecting` | `wallet` | That wallet is asking the user: its prompt is open. |
| `"reconnecting"` | `Connection.Reconnecting` | `wallet`, `accounts`, `chainId` | Read from storage. The wallet has not confirmed it yet. |
| `"connected"` | `Connection.Connected` | `wallet`, `accounts`, `chainId` | The wallet gave these accounts, and is listened to. |

| Field | Type | Is |
| --- | --- | --- |
| `wallet` | `string` | The `id` of the [wallet](https://ethect.dev/reference/wallets/#wallet): `"io.metamask"`, `"injected"`. |
| `accounts` | `ReadonlyArray<Address.Address>` | The accounts the wallet gave. The first is the one it shows as active. |
| `chainId` | `number` | The chain the wallet is on. |

- **A `connected` state has an account.** Its `accounts` is typed as a list with a first
  element, so `state.accounts[0]` is an address and needs no check.
- **A `reconnecting` state may have none.** It is whatever storage held.

## get

- **Type:** `Effect<Connection.State, never, Connection.Connection>`

The state now.

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

const account = Effect.gen(function* () {
  const state = yield* Connection.get;
  return state.status === "connected" ? state.accounts[0] : undefined;
});
```

## changes

- **Type:** `Stream<Connection.State, never, Connection.Connection>`

The state now, then each new one. Whoever subscribes late still gets the state as it is, so a
component that mounts after the connection was made has something to show.

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

// Whatever changes, the cookie follows.
const persist = Connection.changes.pipe(
  Stream.runForEach((state) =>
    Effect.sync(() => {
      document.cookie = Connection.toCookie(state);
    }),
  ),
);
```

Two states in a row are never the same: a wallet that says again what it said before changes
nothing.

## What changes the state

| What happens | The state becomes |
| --- | --- |
| [`connect(wallet)`](https://ethect.dev/reference/connection/connect/) starts | `connecting`, with that wallet |
| the user approves | `connected`, with the accounts and the chain of the wallet |
| the user refuses, or the wallet fails | the state it had before |
| [`reconnect`](https://ethect.dev/reference/connection/connect/#reconnect) finds the wallet and its accounts | `connected`, with what the wallet says now |
| `reconnect` finds no wallet in time, or no account | `disconnected` |
| the user changes account in the wallet | `connected`, with the new accounts |
| the user changes chain in the wallet | `connected`, with the new chain |
| the user removes every account | `disconnected` |
| the wallet says it lost its chains, and still gives accounts | `connected`, with those accounts |
| the wallet says it lost its chains, and gives no account or no answer | `disconnected` |
| [`disconnect`](https://ethect.dev/reference/connection/connect/#disconnect) | `disconnected` |
| [`switchChain`](https://ethect.dev/reference/connection/switch-chain/) | `connected`, with the chain the wallet is on afterwards |

## Behavior

- **The chain is the wallet's.** `chainId` is where the wallet is, for the app to show. It is
  not the chain of the program, which is the chain of its
  [`Transport`](https://ethect.dev/reference/transport/), and it is not what a signature is checked against:
  the wallet is asked again before each one.
- **`connecting` hides what is underneath, and loses nothing.** While another wallet is being
  asked, the wallet that was connected still is. What it says in the meantime is kept: when
  the new one refuses, the state is the one the old wallet has by then.
- **The state has changed when the wallet has said so.** A change of account or of chain
  changes the state before the wallet's own call returns.
- **A `disconnect` event is checked before it is believed.** It says that the wallet lost its
  chains, not that the user took the accounts away, and a wallet says it on a blip of its own
  network. The wallet is asked for its accounts once: with accounts the connection stays.
- **What a wallet says is read before it is believed.** Accounts that are not addresses, or a
  chain that is not a number, change nothing. Addresses are lowercase, as everywhere here.

## Under the hood

No request is sent to read the state: it is kept, and the connected wallet's events keep it
true. One event asks the wallet something: `disconnect`.

- `accountsChanged(list)` → the accounts, the first being the active one
- `accountsChanged([])` → `disconnected`, and the wallet is no longer listened to
- `chainChanged(id)` → the chain
- `disconnect`:
  - **the wallet** `eth_accounts`: once, whatever the code of the event
    - accounts → the accounts
    - none, or a failure → `disconnected`, and the wallet is no longer listened to
