# Connection.connect

Connects the app to a wallet. `connect` asks the wallet for its accounts with a prompt,
[`reconnect`](#reconnect) confirms a stored connection without one, and
[`disconnect`](#disconnect) ends it.

## Usage

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

const App = Connection.layer().pipe(Layer.provideMerge(Wallets.browser));

// A click on a wallet of the picker. The wallet prompts, and the state becomes `connected`.
const onPick = (wallet: Wallets.Wallet) =>
  Effect.gen(function* () {
    const state = yield* Connection.connect(wallet);
    // { status: "connected", wallet: "io.metamask", accounts: ["0x…"], chainId: 1 }
    return `Connected as ${Address.checksum(state.accounts[0])}`; // its EIP-55 form, to show
  }).pipe(
    // the user closed the prompt: the state is as it was
    Effect.catchTag("SignerRejected", () => Effect.succeed("You refused the connection")),
    // anything else: every failure has a message
    Effect.catchTag("SignerError", (error) => Effect.succeed(error.message)),
    Effect.provide(App),
  );
```

`connect` takes a [wallet](https://ethect.dev/reference/wallets/#wallet) of the list, and asks that wallet and
no other. While its prompt is open, the state is `connecting`.

In an app, `App` is one of the layers of the runtime, built once: the connection lasts as long
as the page. The examples below leave it out.

### reconnect

Confirms the connection that storage held: it looks for the remembered wallet and asks for its
accounts, without a prompt. Run it once when the page has loaded.

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

const onLoad = Effect.gen(function* () {
  const state = yield* Connection.reconnect;
  // "connected", with what the wallet says now. Or "disconnected": the wallet is gone
  return state.status;
});
```

It only does something while the state is `reconnecting`, which is what a
[stored connection](https://ethect.dev/reference/connection/layer/#what-storage-held) starts as. In any other
state it gives the state, unchanged.

| The remembered wallet | `reconnect` ends as |
| --- | --- |
| is there, and still gives accounts | `connected`, with the accounts and the chain it has now |
| announces itself within `reconnectTimeout` | the same, once it has |
| does not show up in time | `disconnected` |
| is not in a list that cannot grow, such as `Wallets.of([])` on a server | `disconnected`, at once |
| is there, and gives no account: the user removed the app | `disconnected` |
| is there, and does not answer within `reconnectTimeout` | `disconnected` |
| fails, or its provider cannot be had | `disconnected` |

It never fails: a wallet that cannot be reconnected is a connection that is over. And it
always ends, after twice
[`reconnectTimeout`](https://ethect.dev/reference/connection/layer/#optionsreconnecttimeout-optional) at most.

A wallet is waited for only where one may still announce itself: in a browser, with
[`Wallets.browser`](https://ethect.dev/reference/wallets/#browser). The list of
[`Wallets.of`](https://ethect.dev/reference/wallets/#of) cannot grow, and neither can that of `Wallets.browser`
where there is no `window`. There, a wallet that is not listed ends the reconnection at once.

### disconnect

Ends the connection: the wallet is no longer listened to, and the state is `disconnected`.

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

const onDisconnect = Connection.disconnect.pipe(
  Effect.andThen(Connection.get), // { status: "disconnected" }
);
```

The wallet is asked nothing: the app forgets the wallet, and the wallet keeps the permission
it gave. A `connect` whose prompt is still open is given up.

## Returns

| Function | Type | Gives |
| --- | --- | --- |
| `connect(wallet)` | `Effect<Connection.Connected, Signer.Rejected \| Signer.Error, Connection.Connection>` | the `connected` state |
| `reconnect` | `Effect<Connection.State, never, Connection.Connection>` | the state it ended in |
| `disconnect` | `Effect<void, never, Connection.Connection>` | nothing |

## Parameters

### wallet

- **Type:** [`Wallets.Wallet`](https://ethect.dev/reference/wallets/#wallet)

The wallet to connect, as [`Wallets`](https://ethect.dev/reference/wallets/) lists it. Its `provider` is asked
for now: a wallet that loads an SDK does it at this point.

## Behavior

- **A refusal changes nothing.** The state goes back to the one it had: `disconnected`, or
  `connected` to the wallet that was connected before.
- **One prompt at a time.** A second `connect` while one runs interrupts the first. The first
  one does not fail: its fiber is interrupted. The wallet may still show its prompt, and what
  the user answers there is not heard.
- **Giving up is safe.** Interrupt the fiber that runs `connect`, and the state goes back to
  the one it had.
- **One wallet at a time.** When a wallet is connected, the one before is let go: it is no
  longer listened to.
- **`reconnect` is one for all who ask.** Several calls at once share one reconnection, and
  get the same state. A caller that gives up does not stop it: a component that mounts twice
  reconnects once.
- **`reconnect` always ends.** The wallet is waited for up to `reconnectTimeout`, and its
  answer for as long again. What waits for a reconnection, such as a send, cannot hang.
- **`reconnect` does not wait for a list that cannot grow.** The stream of such a list ends
  after its one list, so a wallet that is not in it will never be: the state is `disconnected`
  at once, whatever `reconnectTimeout` is.
- **`reconnect` does not undo what the user did meanwhile.** If the user connects another
  wallet, or disconnects, while it runs, it changes nothing.
- **A wallet without events still connects.** A provider that cannot be listened to is
  connected, and its state stays as it was when it answered.
- **Nothing is thrown.** What a provider throws or rejects with is a failure in the error
  channel.

## Errors

`connect` fails with what the wallet answers, by its error code.

| Error | Reason | When |
| --- | --- | --- |
| `SignerRejected` | | `4001`: the user refused to connect |
| `SignerError` | `"Unauthorized"` | the wallet gave no account, or answered `4100` |
| `SignerError` | `"Disconnected"` | `4900`, `4901`: the wallet has lost the chain |
| `SignerError` | `"Unknown"` | any other answer, with the wallet's error as `cause`. Also an answer that is not JSON-RPC, and one that cannot be read, whose `CodecError` is the `cause` |
| `SignerError` | as the wallet says | its `provider` failed: an SDK that did not load |

`reconnect` and `disconnect` cannot fail.

## Under the hood

Only the wallet is asked. The `Transport` of your program is never used.

**`connect(wallet)`**

- **your program**: the state → `connecting`
- **your program**: the wallet's provider
- **the wallet** `eth_requestAccounts`: the user sees a prompt
  - 4001 → the state it had → fails: `SignerRejected`
  - no account → the state it had → fails: `SignerError` `"Unauthorized"`
- **the wallet** `eth_chainId`
- **your program**: the state → `connected`
- **your program**: listens to `accountsChanged`, `chainChanged` and `disconnect` on that provider
- **your program**: the wallet before, if any, is no longer listened to

**`reconnect`**

  - the state is not `reconnecting`: nothing is asked → the state, unchanged
- **your program**: looks for a wallet with the remembered id among `Wallets`
  - the list may still grow: waits for it, up to `reconnectTimeout` (2 s)
  - the list cannot grow, and lacks it → `disconnected`, at once
  - then, up to `reconnectTimeout` again for the three together:
    - **your program**: the wallet's provider
    - **the wallet** `eth_accounts`: no prompt
    - **the wallet** `eth_chainId`
  - accounts → `connected`, with what the wallet says now, and listened to
  - none, no such wallet, or too late → `disconnected`

**`disconnect`**

- **your program**: no request: the listeners are removed
- **your program**: the state → `disconnected`
