# Wallet connection (Connection)

Which wallet an app is connected to, with which accounts, on which chain. It is one state, as
plain data: it can be stored in a cookie and rendered from on a server.
[`Signer.connected`](https://ethect.dev/reference/signer/connected/) signs with the wallet of that state,
whichever it is at the time.

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

// The connection of an app, over the wallets of the browser.
const App = Connection.layer().pipe(Layer.provideMerge(Wallets.browser));

const program = Effect.gen(function* () {
  const [wallet] = yield* Wallets.get;
  if (wallet === undefined) return yield* Connection.get; // no wallet is installed
  return yield* Connection.connect(wallet); // the wallet prompts
  // { status: "connected", wallet: "io.metamask", accounts: ["0x…"], chainId: 1 }
}).pipe(
  // the user closed the prompt: the state is as it was
  Effect.catchTag("SignerRejected", () => Connection.get),
);

const state = await program.pipe(Effect.provide(App), Effect.runPromise);
```

| Export | Kind | Description |
| --- | --- | --- |
| [`Connection.layer(options?)`](https://ethect.dev/reference/connection/layer/) | layer | The connection of an app, over its [`Wallets`](https://ethect.dev/reference/wallets/). `initial` is what storage held. |
| [`Connection.get`](https://ethect.dev/reference/connection/state/#get) | effect | The state now. |
| [`Connection.changes`](https://ethect.dev/reference/connection/state/#changes) | stream | The state now, and again each time the user changes account, chain or wallet. |
| [`Connection.connect(wallet)`](https://ethect.dev/reference/connection/connect/) | function | Asks the wallet for its accounts. The user sees a prompt. |
| [`Connection.reconnect`](https://ethect.dev/reference/connection/connect/#reconnect) | effect | Asks the remembered wallet for its accounts, without a prompt. |
| [`Connection.disconnect`](https://ethect.dev/reference/connection/connect/#disconnect) | effect | Ends the connection. |
| [`Connection.switchChain(chain)`](https://ethect.dev/reference/connection/switch-chain/) | function | Asks the wallet to change chain. With a [`Chain`](https://ethect.dev/reference/chain/), a wallet that does not know it is offered to add it. |
| [`Connection.session`](#session) | effect | The wallet to sign with: its `provider`, for a request that is the wallet's alone. |
| [`Connection.toCookie(state, options?)`](https://ethect.dev/reference/connection/cookie/) | function | The state as a cookie: the text to give to `document.cookie`, or to send as `Set-Cookie`. |
| [`Connection.fromCookie(cookies, options?)`](https://ethect.dev/reference/connection/cookie/#fromcookie) | function | Reads it back from `document.cookie` or a `Cookie` header. It never fails. |
| [`Connection.toJson(state)`](https://ethect.dev/reference/connection/json/) | function | The state as text, for local storage or a framework that holds the cookie. |
| [`Connection.fromJson(text)`](https://ethect.dev/reference/connection/json/#fromjson) | function | Reads it back. It never fails. |
| [`Connection.Connection`](#the-service) | service | The connection: what the functions above go to. |
| [`Connection.State`](https://ethect.dev/reference/connection/state/) | type | Any of the four states below. |
| [`Connection.Session`](#session) | type | The connected wallet, for as long as it is: its `provider` and a `scope`. |

## The three pieces

Three layers, each over the one before. Wallets is the list of what is installed. Connection is the one wallet the user clicked, with its accounts and its chain. Signer.connected sends every signature to that wallet.

Each is a layer, and each needs the one above it:
[`Wallets`](https://ethect.dev/reference/wallets/), [`Connection.layer`](https://ethect.dev/reference/connection/layer/) and
[`Signer.connected`](https://ethect.dev/reference/signer/connected/).

## The states

| Type | `status` | Holds |
| --- | --- | --- |
| `Connection.Disconnected` | `"disconnected"` | nothing |
| `Connection.Connecting` | `"connecting"` | `wallet`: the one that is asking the user |
| `Connection.Reconnecting` | `"reconnecting"` | `wallet`, `accounts`, `chainId`: read from storage, not confirmed by the wallet yet |
| `Connection.Connected` | `"connected"` | `wallet`, `accounts` with the active one first, `chainId` |

[`Connection.State`](https://ethect.dev/reference/connection/state/) says what moves the state from one to the
other.

## Two chains

- **The chain of the program** is the chain of its
  [`Transport`](https://ethect.dev/reference/transport/): the one of a single-chain app, or the one named with
  [`Transport.on`](https://ethect.dev/reference/transport/chains/#on). Reads go to that node, and a transaction
  is for that chain.
- **The chain of the wallet** is `chainId` in the state. The user changes it in the wallet.

Nothing here changes the chain of the program to follow the wallet. An app that wants that
writes `Transport.on(state.chainId)`. When a send is for another chain than the wallet's,
[`Signer.connected`](https://ethect.dev/reference/signer/connected/) asks the wallet to switch, or fails.

## The service

`Connection.Connection` is the service that [`Connection.layer`](https://ethect.dev/reference/connection/layer/)
provides. Each function of the module is one of its members.

| Member | Is |
| --- | --- |
| `get`, `changes` | the state now, and the stream of it |
| `connect(wallet)`, `reconnect`, `disconnect`, `switchChain(chain)` | the functions of the same name |
| `session` | the wallet to sign with: an `Effect<Connection.Session, Signer.Error>` |

## session

- **Type:** `Effect<Connection.Session, Signer.Error, Connection.Connection>`

The wallet to sign with. It is what a signer that follows the connection uses, and what a
program uses for a request that is the wallet's alone, such as
[`wallet_watchAsset`](https://ethect.dev/rpc/wallet/watch-asset/).

```ts
import { Effect } from "effect";
import { type Address, Connection, Transport } from "@ethect/core";
import { Wallet } from "@ethect/core/rpc";

const watch = (address: Address.Address) =>
  Effect.gen(function* () {
    const { provider } = yield* Connection.session;
    const asset = { type: "ERC20", options: { address, symbol: "USDC", decimals: 6 } } as const;
    return yield* Wallet.watchAsset(asset).pipe(Effect.provide(Transport.eip1193(provider)));
  });
```

| Field of `Connection.Session` | Type | Is |
| --- | --- | --- |
| `provider` | [`Eip1193.Provider`](https://ethect.dev/reference/eip1193/#provider) | the provider of the connected wallet |
| `scope` | `Scope` | closed when that wallet is no longer the connected one: what listens to it listens in there |

- **While the state is `reconnecting`, it waits** for a running `reconnect` to end.
- **With no wallet connected, it fails** with `SignerError` `"Disconnected"`.

## Under the hood

Only the wallet is asked, and only by what connects or changes chain.

**`Connection.connect(wallet)`**

- **the wallet** `eth_requestAccounts`: the prompt
- **the wallet** `eth_chainId`
- **your program**: then listens to `accountsChanged`, `chainChanged` and `disconnect`

**`Connection.reconnect`**

- **the wallet** `eth_accounts`: no prompt
- **the wallet** `eth_chainId`

**`Connection.switchChain(chain)`**

- **the wallet** `wallet_switchEthereumChain`: then `wallet_addEthereumChain`, for a `Chain` the wallet does not know
- **the wallet** `eth_chainId`: where the wallet is afterwards

**`Connection.get`, `Connection.changes`, `Connection.disconnect`**

- **your program**: no request: the state is kept, and the wallet's events keep it true

See [`Connection.connect`](https://ethect.dev/reference/connection/connect/#under-the-hood),
[`Connection.switchChain`](https://ethect.dev/reference/connection/switch-chain/#under-the-hood) and
[`Connection.State`](https://ethect.dev/reference/connection/state/#under-the-hood).
