# Signer.connected

A [signer](https://ethect.dev/reference/signer/) that follows the [connection](https://ethect.dev/reference/connection/) of an
app. It signs with the wallet that is connected, whichever it is at the time.

## Usage

```ts
import { Effect, Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { type Address, 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),
);

// A click on a wallet, then a payment from the account the user picked.
const pay = (wallet: Wallets.Wallet, to: Address.Address, value: bigint) =>
  Effect.gen(function* () {
    yield* Connection.connect(wallet); // the wallet prompts
    const signer = yield* Signer.Signer;
    return yield* signer.submit({
      calls: [{ to, data: "0x", value }],
      atomic: false,
      from: yield* Signer.address, // the active account of the connection
      chainId: yield* Transport.chainId, // the chain of your node
    });
    // { _tag: "Transactions", hashes: [hash], from, chainId }
  }).pipe(
    Effect.catchTag("SignerRejected", () => Effect.succeed("refused" as const)),
    Effect.provide(App),
  );
```

The program names no wallet. It needs a `Signer`, and this one goes to the wallet of the
connection: when the user connects another wallet, the same program signs with that one.

The example uses the [`Signer` service](https://ethect.dev/reference/signer/#the-service) itself: what
[`Tx`](https://ethect.dev/reference/tx/) asks of a signer. In an app, `App` is given to the runtime, built once.

### By the state of the connection

| The [state](https://ethect.dev/reference/connection/state/) | `accounts` | Everything else: sending, signing, capabilities |
| --- | --- | --- |
| `connected` | the state's accounts | goes to that wallet, through [`Signer.wallet`](https://ethect.dev/reference/signer/wallet/) built for its provider |
| `reconnecting` | the state's accounts | waits for a running [`reconnect`](https://ethect.dev/reference/connection/connect/#reconnect) to end, then goes as it ended. None running: `SignerError` `"Disconnected"` |
| `disconnected`, `connecting` | `SignerError` `"Disconnected"` | `SignerError` `"Disconnected"` |

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

// Signed by the active account of the connected wallet, whichever wallet it is.
const signIn = Signer.signMessage("Sign in to Example").pipe(
  Effect.catchTag("SignerRejected", () => Effect.succeed(undefined)), // the user said no
  // no wallet is connected: show the picker
  Effect.catchIf(
    (error) => error.reason === "Disconnected",
    () => Effect.succeed(undefined),
  ),
);
```

[`Signer.signMessage`](https://ethect.dev/reference/signer/sign-message/) and the other functions of
[`Signer`](https://ethect.dev/reference/signer/) go to the connected wallet in the same way. With no wallet,
every one of them fails with `SignerError` `"Disconnected"`, and so do
[`Signer.accounts`](https://ethect.dev/reference/signer/accounts/) and
[`Signer.address`](https://ethect.dev/reference/signer/accounts/#address): "No wallet is connected" is what a
send says, whether or not it names its sender.

To show the account, read the [state](https://ethect.dev/reference/connection/state/): a page renders from
`Connection.changes`, and never from a failure.

### On a server

With the [layers of a server](https://ethect.dev/reference/connection/layer/#on-a-server), the state is the one
of the cookie and there is no wallet.

| On a server | Gives |
| --- | --- |
| [`Signer.address`](https://ethect.dev/reference/signer/accounts/#address), [`Signer.accounts`](https://ethect.dev/reference/signer/accounts/) | the accounts of the cookie. With a cookie that holds no connection, `SignerError` `"Disconnected"` |
| a read, through your `Transport` | works |
| a send, a signature | fails at once with `SignerError` `"Disconnected"` |

So a page can show the balance of the account before any wallet answers. The address is what a
cookie says: it is a hint to render with, and proves nothing.

### A wallet on another chain

A send is for the chain of the [`Transport`](https://ethect.dev/reference/transport/) in context. The wallet
may be on another one.

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

// Never asks the wallet to change chain.
const Strict = Signer.connected({ onWrongChain: "fail" });
```

| The wallet is | `"switch"`, the default | `"fail"` |
| --- | --- | --- |
| on the chain of the signature | signs | signs |
| on another chain | is asked to switch, then signs | `SignerError` `"ChainMismatch"`: it is not asked to switch |

When the wallet switches, the [state](https://ethect.dev/reference/connection/state/) follows: its `chainId` is
the wallet's new chain. The rest is as for
[`Signer.wallet`](https://ethect.dev/reference/signer/wallet/#a-wallet-on-another-chain).

## Returns

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

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

## Parameters

### options.onWrongChain (optional)

- **Type:** `"switch" | "fail"`
- **Default:** `"switch"`

What happens when a signature is for another chain than the one the wallet is on: see
[the table above](#a-wallet-on-another-chain).

### options.capabilitiesRequestTimeout (optional)

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

How long a plan waits for the wallet to say what it can do before it plans one step per
call. The ask goes on, and its answer is kept for the next plan. See
[`Signer.wallet`](https://ethect.dev/reference/signer/wallet/#optionscapabilitiesrequesttimeout-optional).

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

const Impatient = Signer.connected({ capabilitiesRequestTimeout: "1 second" });
```

## Behavior

- **The wallet is found at each call.** Nothing is decided when the layer is built: each
  signature goes to the wallet that is connected when it is asked.
- **One signer per connection.** The signer of a wallet is built the first time something is
  signed with it, and kept for as long as that wallet is connected. Its capabilities are
  remembered for that long, and an ask for them that nobody waits for any more runs on until
  the wallet is disconnected.
- **It goes with the wallet.** When the user disconnects or connects another wallet, the
  signer of the wallet before is dropped, and nothing listens to that wallet any more.
- **`accounts` asks no wallet.** They are the accounts of the state, the active one first. A
  user who changes account in the wallet changes them. With no wallet, they fail as a
  signature does.
- **A signature waits for a reconnection, and for nothing else.** While `reconnect` runs, a
  send waits for it to end, which takes twice `reconnectTimeout` at most. With no `reconnect`
  running, it fails at once: it never waits for a wallet that nobody is looking for.
- **`connecting` is not connected.** While a wallet is being asked, nothing is signed, even
  when another wallet was connected before.
- **The chain is checked by the wallet's signer.** The `chainId` of the state is for your
  app to show. Before each signature the wallet is asked where it is.
- **Nothing is thrown.** With no wallet, every function fails with a value.

## Errors

| Error | Reason | When |
| --- | --- | --- |
| `SignerError` | `"Disconnected"` | no wallet is connected: the state is `disconnected` or `connecting`, or it is `reconnecting` and no `reconnect` runs. While `reconnecting`, `accounts` does not fail: it is the stored accounts |
| `SignerError` | `"Unauthorized"` | `Signer.address`, and the stored connection of a `reconnecting` state has no account |
| anything [`Signer.wallet`](https://ethect.dev/reference/signer/wallet/#errors) fails with | | the connected wallet answered it |

## Under the hood

The `Connection` is asked which wallet is connected. The wallet is asked the rest, as
[`Signer.wallet`](https://ethect.dev/reference/signer/wallet/#under-the-hood) does.

**building the layer**

- **your program**: nothing: no wallet is asked, no listener

**`accounts`**

- **your program**: the accounts of a `connected` or `reconnecting` state. No request
  - anything else → fails: `SignerError` `"Disconnected"`

**`capabilities`, `submit`, `status`, `signMessage`, `signTypedData`, `signTransaction`**

- the state is `connected`: the signer of that wallet, built once for its provider: what it sends is on the page of `Signer.wallet`
- the state is `reconnecting`: waits for the reconnect that runs, then as above
- the state is `reconnecting`, and none runs → fails: `SignerError` `"Disconnected"`
- anything else → fails: `SignerError` `"Disconnected"`

**the wallet is disconnected, or another one is connected**

- **your program**: the listeners of its signer are removed, with those of the connection
