# Signer.wallet

A [signer](https://ethect.dev/reference/signer/) over an EIP-1193 wallet. One call is one `eth_sendTransaction`,
and several calls are one EIP-5792 batch.

## Usage

```ts
import { Effect, Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { type Eip1193, Signer, Transport } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

// The wallet's provider: `window.ethereum`, or the one a wallet SDK returns.
declare const provider: Eip1193.Provider;

const Dapp = Layer.merge(
  Transport.http("https://ethereum-rpc.publicnode.com"), // reads go to your node
  Signer.wallet(provider), // signatures go to the wallet
).pipe(Layer.provide(FetchHttpClient.layer));

const program = Effect.gen(function* () {
  const me = yield* Signer.address; // asked of the wallet
  const balance = yield* Eth.getBalance(me, "latest"); // asked of the node
  return { me, balance };
});

const result = await program.pipe(Effect.provide(Dapp), Effect.runPromise);
```

The wallet signs and your node reads: the signer never replaces the `Transport` of your
program. [`Tx`](https://ethect.dev/reference/tx/) sends through whichever signer is provided, so the same
program runs with a wallet here and with a key in a script.

To find the providers of the installed wallets, see [`Wallets`](https://ethect.dev/reference/wallets/).

The examples below send through [`Tx`](https://ethect.dev/reference/tx/), which asks the
[`Signer` service](https://ethect.dev/reference/signer/#the-service) of this wallet.

### One call

One call, with no capability asked for, is a transaction. The wallet estimates its gas and its
fees: only the fields you set are sent.

```ts
import { Effect } from "effect";
import { type Address, Call, Tx } from "@ethect/core";

const pay = (to: Address.Address, value: bigint) =>
  Tx.send(Call.make({ to, value }), {
    transaction: { gas: 21_000n }, // optional: what you set is not left to the wallet
  }).pipe(
    // the user said no: nothing was sent
    Effect.catchTag("SignerRejected", () => Effect.succeed(undefined)),
  );
```

### Several calls as one

Several calls go to the wallet as one batch, all or nothing. The answer is a handle: only the
wallet knows where its batch stands.

```ts
import { Effect } from "effect";
import { type Call, Tx } from "@ethect/core";

const together = (calls: ReadonlyArray<Call.Call<unknown, unknown>>, id?: string) =>
  Effect.gen(function* () {
    // `id` is yours, to ask about the batch after a reload
    const pending = yield* Tx.submit(calls, id === undefined ? {} : { id });
    // { _tag: "Handle", kind: "eip5792", id, from, chainId }
    return yield* Tx.wait(pending); // asks the wallet about the batch: first, then at each block
  });
```

Whether a wallet takes a batch is what `capabilities` says, before any prompt.

| The wallet says `atomic` is | `capabilities` gives | A batch |
| --- | --- | --- |
| `supported` | `atomic: "supported"` | is sent as one transaction |
| `ready` | `atomic: "ready"` | is sent once the user accepts to upgrade the account |
| `unsupported`, or nothing | `atomic: "unsupported"` | fails with `TxUnsupported` `"atomic"` |
| no `wallet_getCapabilities` at all | `atomic: "unsupported"`, and no capability | fails with `TxUnsupported` `"atomic"` |
| nothing within `capabilitiesRequestTimeout`, or an error other than 4100, 4900 and 4901 | `atomic: "unsupported"`, and no capability, this time | fails with `TxUnsupported` `"atomic"` |

### Capabilities

A capability is asked of the wallet with the batch, so one call that asks for one is a batch
too. Without `optional`, a wallet that lacks it refuses.

```ts
import { type Call, Tx } from "@ethect/core";

const sponsored = (call: Call.Call<unknown, unknown>, url: string) =>
  Tx.send(call, {
    // with `optional`, a wallet that cannot sponsor still sends: as a plain transaction
    capabilities: { paymasterService: { url, optional: true } },
  });
```

### A wallet on another chain

A signature is for a chain: a transaction for the chain of the
[`Transport`](https://ethect.dev/reference/transport/) in context, typed data for the `chainId` of its domain.
The wallet may be on another one, so it is asked where it is before every signature.

```ts
import { Effect } from "effect";
import { type Call, type Eip1193, Signer, Tx } from "@ethect/core";

declare const provider: Eip1193.Provider;

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

const send = (call: Call.Call<unknown, unknown>) =>
  Tx.send(call).pipe(
    Effect.catchIf(
      (error) => error._tag === "SignerError" && error.reason === "ChainMismatch",
      () => Effect.succeed("ask the user to change chain" as const),
    ),
    Effect.provide(Strict),
  );
```

| 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 |

| Asked to switch, the wallet | Failure |
| --- | --- |
| has a user who refuses | `SignerRejected` |
| does not know the chain | `SignerError` `"UnknownChain"` |
| says it switched, and is still on another chain | `SignerError` `"ChainMismatch"` |

Either way, nothing is signed for a chain the wallet is not on.

| What is signed | The chain it is for |
| --- | --- |
| calls, with `submit` | `chainId` of the request: the chain of your transport |
| a transaction, with `signTransaction` | the chain of the transport in context |
| typed data whose domain has a `chainId` | that chain |
| typed data whose domain has none, a message | no chain: the wallet is not asked where it is |

### Signing without sending

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

const proof = (typedData: Signer.TypedData) =>
  Effect.gen(function* () {
    const signer = yield* Signer.Signer;
    const me = yield* Signer.address;
    // the bytes of the message: the wallet shows them as text when they are text
    const hello = yield* signer.signMessage(me, Hex.fromUtf8("hello"));
    // typed data goes to the wallet as JSON, every bigint in decimal
    const signature = yield* signer.signTypedData(me, typedData);
    return { hello, signature };
  });
```

Typed data whose domain names a chain is for that chain: a permit for Base, asked while the
wallet is on mainnet, [brings the wallet to Base first](#a-wallet-on-another-chain), or fails
with `"ChainMismatch"` under `"fail"`.

`signTransaction` asks for `eth_signTransaction`, which most browser wallets do not have: it
then fails with `TxUnsupported` `"signing"`.

## Returns

`Layer<Signer.Signer>`

A layer that provides the [`Signer` service](https://ethect.dev/reference/signer/#the-service). It needs
nothing, and building it cannot fail: the wallet is asked nothing until something is signed or
read.

## Parameters

### provider

- **Type:** [`Eip1193.Provider`](https://ethect.dev/reference/eip1193/#provider)

The wallet: any object with `request`, `on` and `removeListener`.

### 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 `capabilities` waits for `wallet_getCapabilities`. With no answer by then, it gives
no capability, and a plan of several calls is one step per call. The ask is not stopped: its
answer is kept when it comes, and the next plan uses it. A wallet that is locked answers once
its user has typed a password, and a hidden tab may hold the request until it is shown.

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

declare const provider: Eip1193.Provider;

const Patient = Signer.wallet(provider, { capabilitiesRequestTimeout: "10 seconds" });
```

## What the wallet is asked

| You ask | The wallet is asked | It gives |
| --- | --- | --- |
| `accounts` | `eth_accounts` | the accounts, the first being the active one |
| `capabilities(account, chainId)` | `wallet_getCapabilities(account, [chainId])` | `atomic`, `unattended: false`, and `all` it reports for the chain. No capability after `capabilitiesRequestTimeout` |
| `submit`, one call and no capability | `eth_sendTransaction({ from, to, data, value, …fields })` | `{ _tag: "Transactions", hashes: [hash] }` |
| `submit`, several calls or a capability | `wallet_sendCalls({ version: "2.0.0", id, from, chainId, atomicRequired: true, calls, capabilities })` | `{ _tag: "Handle", kind: "eip5792", id }` |
| `status(handle)` | `wallet_getCallsStatus(id)` | [where the batch stands](#the-status-of-a-batch) |
| `signMessage(account, message)` | `personal_sign(message, account)` | the signature |
| `signTypedData(account, data)` | `eth_signTypedData_v4(account, json)`, on the chain of its domain | the signature |
| `signTransaction(account, call, fields)` | `eth_signTransaction({ from, to, data, value, chainId, …fields })` | `raw`, with the `hash`, the `nonce` and the `chainId` read from it |

### The status of a batch

Only hashes are passed on. [`Tx.wait`](https://ethect.dev/reference/tx/wait/) reads the receipts from your node, so a
receipt has the same shape whatever sent the transaction.

| `wallet_getCallsStatus` answers | `status` gives |
| --- | --- |
| a status from 100 to 199 | `{ _tag: "pending" }` |
| 200 to 299 | `{ _tag: "included", hashes }`, the transaction hashes of its receipts |
| 400 to 499 | `{ _tag: "dropped" }` |
| 500 to 699 | `{ _tag: "reverted", hashes }` |
| another status | none: it fails with `SignerError` `"Unknown"` |
| the error 5730: it does not know the id | none: it fails with `SignerError` `"UnknownBatch"` |
| an answer that cannot be read | none: it fails with `SignerError` `"Unknown"`, the `CodecError` as `cause` |

An answer is read as [`CallsStatus`](https://ethect.dev/rpc/types/calls-status/#behavior) reads it, whenever
what the wallet means is unambiguous: `"PENDING"` and `"CONFIRMED"` are 100 and 200, an `id`
that is not a string and a missing `chainId` are not needed, and block numbers may be JSON
numbers. Only an answer without a `status`, or with a receipt that has no 32-byte
`transactionHash`, cannot be read.

A wallet that does not know the batch says nothing of it: it is not the wallet that took it,
or it has forgotten it, and the batch may still be mined. See
[After a failure](https://ethect.dev/reference/tx/failures/#after-a-failure).

## Behavior

- **The app's transport is never the wallet.** The wallet is reached through a transport of
  the signer's own. Your reads, your simulations and your receipts go to your node.
- **One signature at a time.** The chain is checked and the signature asked as one step. Two
  signatures for two chains cannot cross: the second waits for the first to be answered.
- **The wallet's chain is asked before every signature.** `eth_chainId`, each time, and nothing
  it said before is kept: a user changes chain in the wallet, and not every wallet says so.
- **A switch is checked.** After `wallet_switchEthereumChain`, the wallet is asked `eth_chainId`
  again. One that answers before it has switched, or without switching, signs nothing.
- **Typed data is for the chain of its domain.** With a `chainId` in its domain, it is signed
  on that chain, as a transaction is. The `chainId` is read as a number, a bigint, or digits in
  a string. A domain without one is for no chain.
- **Capabilities are kept per account and chain, for the session.** `accountsChanged` forgets
  them all. The chain is in what they are kept by, so `chainChanged` forgets nothing: with
  `onWrongChain: "switch"`, the wallet changes chain before a send, and what it said holds.
  Nothing is kept across a reload: a wallet can upgrade an account between two visits.
- **Every chain of an answer is kept.** Some wallets answer for all their chains, whatever was
  asked: the next plan on another of them asks nothing.
- **Chain `0x0` holds everywhere.** What a wallet reports under chain `0x0` is merged into the
  capabilities of every chain.
- **One ask at a time.** Asked again for the same account and chain while an ask is out,
  `capabilities` waits for that one: two plans at once send one request.
- **A wallet that is slow to answer is not waited for.** After `capabilitiesRequestTimeout`,
  `capabilities` gives none, and that is not kept. The ask goes on as long as the layer lives:
  its answer is kept when it comes.
- **Only a wallet the app may not ask, or one that is gone, fails.** `4100` and `4900`, `4901`
  fail as below. A wallet without the method has no capability, which is kept. Any other
  failure, such as a wallet that does not find the account, is no capability: not kept, and
  logged at the Debug level.
- **A batch gets an id.** Yours, or 32 random bytes in hex. It is sent to the wallet, so the
  batch can be asked about later. The id of the handle is the one the wallet answers.
- **The same id twice is the same batch.** A wallet that answers 5720 already has it: the
  handle of that id is returned, and nothing is sent again.
- **A batch has no transaction fields.** EIP-5792 has no place for a nonce, a gas limit or
  fees. With one of them set, several calls fail with `TxUnsupported` `"atomic"` before the
  wallet is asked.
- **Several calls are atomic or refused.** With `atomic: false`, several calls fail with
  `TxUnsupported` `"atomic"` before the wallet is asked: a wallet takes several calls only as
  one.
- **Every address is sent in its EIP-55 form.** The account of `wallet_getCapabilities`,
  `personal_sign` and `eth_signTypedData_v4`, the `from` and `to` of a transaction or a batch,
  and every address inside typed data. Ambire looks an account up by its checksum, and answers
  that one in lowercase does not exist: a plan of two calls was then two steps. The accounts a
  wallet answers are read in any case, to the lowercase `Address`.
- **Typed data is checked first.** It has to have a digest, as for a local key: the wallet is
  not asked to sign data that does not. `EIP712Domain` is declared from the fields of the
  domain when the types leave it out.
- **A signed transaction is read back.** `nonce` and `chainId` come from the bytes the wallet
  answered. A transaction signed for another chain than the one asked is a failure.
- **A provider without events is asked its capabilities every time.** When `on` throws,
  nothing can say that the accounts changed, so capabilities are not kept.
- **Listeners are removed.** `accountsChanged`, which says when capabilities may have changed,
  and `message` are listened to while the layer lives, and removed when its scope closes.
- **Nothing is thrown.** What a provider throws or rejects with is a failure in the error
  channel.
- **Every request is in the Debug log.** A wallet's requests never show in the Network tab of
  a browser. With `References.MinimumLogLevel` at `"Debug"`, each one is logged with its
  method, how long it took, its params and the answer as the wallet gave it: see
  [`Transport.eip1193`](https://ethect.dev/reference/transport/eip1193/#seeing-what-the-wallet-answers).

## Errors

What the wallet answers, by its error code.

| Error | Reason | When |
| --- | --- | --- |
| `SignerRejected` | | `4001`: the user refused to sign, to send, or to switch chain |
| `SignerError` | `"Unauthorized"` | `4100`: the account is not connected to the app |
| `SignerError` | `"Disconnected"` | `4900`, `4901`: the wallet has lost the chain |
| `SignerError` | `"ChainMismatch"` | the wallet is on another chain, and stays there |
| `SignerError` | `"UnknownChain"` | `4902`: the wallet does not know the chain to switch to |
| `SignerError` | `"UnknownBatch"` | `5730`: the wallet does not know the batch it is asked about |
| `SignerError` | `"Unknown"` | any other answer, with the wallet's error as `cause`. Also an answer that is not JSON-RPC, and a status or a transaction that cannot be read: its `CodecError` is the `cause`, with the answer as `value` |
| `TxUnsupported` | `"atomic"` | a batch, and `wallet_sendCalls` is missing or answers `4200`, `5710`, `5740` (too large) or `5760` |
| `TxUnsupported` | `"capability"` | `5700`: the wallet lacks a capability that is not `optional` |
| `TxUnsupported` | `"upgradeRejected"` | `5750`: the user refused the upgrade a batch needs |
| `TxUnsupported` | `"signing"` | `signTransaction`, and the wallet has no `eth_signTransaction` |

`accounts`, `capabilities` and `status` prompt nobody, so they fail with `SignerError` only.
`capabilities` fails with `"Unauthorized"` and `"Disconnected"` alone: any other error is no
capability.
Every failure has a `message` that says what the wallet was asked and what it answered. An
answer that cannot be read is named as the wallet's: `The wallet answered
wallet_getCallsStatus in a shape EIP-5792 does not allow: Missing key at ["status"]`.

## Under the hood

Only the wallet is asked. The `Transport` in context is asked one thing: its chain id, by
`signTransaction`.

**building the layer**

- **your program**: listens to `accountsChanged` and `message`. No request

**`accounts`**

- **the wallet** `eth_accounts`: every time: the wallet does not prompt

**`capabilities(account, chainId)`**

- **the wallet** `wallet_getCapabilities(account, [chainId])`: once per account and chain, until `accountsChanged`. Waited for `capabilitiesRequestTimeout` at most

**`submit`, `signTransaction`, and `signTypedData` with a `chainId` in its domain: before the signature**

- **the wallet** `eth_chainId`: every time: nothing is kept
  - the wallet is on another chain:
    - `"switch"`:
      - **the wallet** `wallet_switchEthereumChain({ chainId })`
      - **the wallet** `eth_chainId`: again: the wallet has to be there
    - `"fail"`: no request → fails: `SignerError` `"ChainMismatch"`

**`submit`**

- one call, no capability:
  - **the wallet** `eth_sendTransaction`
- several calls, or a capability:
  - **the wallet** `wallet_sendCalls`

**`status(handle)`**

- **the wallet** `wallet_getCallsStatus(id)`

**`signMessage`**

- **the wallet** `personal_sign`

**`signTypedData`**

- **the wallet** `eth_signTypedData_v4`

**`signTransaction`**

- **the wallet** `eth_signTransaction`

**the layer's scope closes**

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