# Tx.plan

Says how many signatures the calls take, and what is in each. Nothing is signed, simulated or
asked of the user.

## Usage

```ts title="steps.ts"
import { Effect } from "effect";
import { type Address, Erc20, Erc4626, Tx } from "@ethect/core";

const deposit = (usdc: Address.Address, vault: Address.Address, amount: bigint, me: Address.Address) =>
  Effect.gen(function* () {
    const calls = [
      Erc20.at(usdc).approve(vault, amount),
      Erc4626.at(vault).deposit(amount, me),
    ];
    const steps = yield* Tx.plan(calls);
    // One step on a wallet that batches or with a local key, two on a wallet that does not.
    for (const step of steps) {
      const pending = yield* Tx.submit(step); // one signature
      yield* Tx.wait(pending);
    }
    return steps.length;
  });
```

A plan is what a page shows before the user clicks: one row per signature. It needs a
[`Signer`](https://ethect.dev/reference/signer/), which says what it can do, and a
[`Transport`](https://ethect.dev/reference/transport/), whose chain the steps are for.

### The table

What `batch` gives for several calls, by what the signer says of itself
([`Signer.capabilities`](https://ethect.dev/reference/signer/accounts/#capabilities)).

| The signer | `"auto"`, the default | `"atomic"` | `"never"` |
| --- | --- | --- | --- |
| runs calls as one: `atomic` is `"supported"` or `"ready"` | one step, atomic | one step, atomic | one step per call |
| signs without asking anyone: `unattended`, a local key | one step, not atomic | `TxUnsupported` | one step per call |
| neither: a wallet that does not batch | one step per call | `TxUnsupported` | one step per call |

- **One call is one step**, whatever `batch` says. Its `atomic` is `true`: one call succeeds or
  fails alone.
- **No call is no step.**
- **A step that is not atomic** is sent together and not as one. With a local key the calls
  are transactions with nonces in a row: a later one can fail after an earlier one is mined.

### One row per signature

`batch: "never"` gives one step per call from any signer, and asks the signer nothing.

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

const rows = (calls: ReadonlyArray<Call.Call<unknown, unknown>>) =>
  Tx.plan(calls, { batch: "never" }).pipe(
    Effect.map((steps) => steps.map((step) => step.calls[0]?.fn?.name ?? "transfer")),
  );
```

### All or nothing

`batch: "atomic"` fails before any prompt when the signer cannot run the calls as one.

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

const canBeOne = (calls: ReadonlyArray<Call.Call<unknown, unknown>>) =>
  Tx.plan(calls, { batch: "atomic" }).pipe(
    Effect.as(true),
    Effect.catchTag("TxUnsupported", () => Effect.succeed(false)),
  );
```

### A wallet that is slow to answer

A wallet that is locked may answer `wallet_getCapabilities` only once its user has typed a
password, and a hidden tab may hold the request until it is shown. A plan waits 3 seconds at
most: then it has no capability, and plans one step per call (`"atomic"` fails with
`TxUnsupported`). The ask is not stopped. Its answer is kept, and the next plan has it at
once.

The wait is `capabilitiesRequestTimeout`, an option of
[`Signer.wallet`](https://ethect.dev/reference/signer/wallet/#parameters) and
[`Signer.connected`](https://ethect.dev/reference/signer/connected/). Asked when the wallet connects, while it is
unlocked, the answer is there before the first plan:

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

// What the wallet can do, asked as soon as it connects: kept for the first plan.
const warm = Connection.changes.pipe(
  Stream.filter((state) => state.status === "connected"),
  Stream.runForEach(() => Effect.ignore(Signer.capabilities({ chainId: 8453 }))),
);
```

## Returns

`Effect<ReadonlyArray<Tx.Step<E>>, Tx.Unsupported | Signer.Error | Transport.Error, Signer | Transport>`

The steps, in the order of the calls. `E` is the errors the calls declare: a step carries them
to [`Tx.submit`](https://ethect.dev/reference/tx/submit/), and [`Err.of(step.calls)`](https://ethect.dev/reference/err/of/) gives
them to [`Tx.wait`](https://ethect.dev/reference/tx/wait/).

### Tx.Step

One thing to sign. An open union, told apart by `_tag`: today it has one member,
`Tx.Step.Calls`.

| Field | Type | Holds |
| --- | --- | --- |
| `_tag` | `"Calls"` | the kind of step |
| `calls` | `ReadonlyArray<Call.Call<unknown, E>>` | the calls of this signature, as you gave them |
| `atomic` | `boolean` | whether they succeed or fail as one |
| `from` | [`Address.Address`](https://ethect.dev/reference/primitives/address/) | the account that signs |
| `chainId` | `number` | the chain they are for |

A step is plain data. It names its calls, so a page can label a button with them:
`step.calls.map((call) => call.fn?.name)`.

## Parameters

### calls

- **Type:** `Call.Call<A, E> | ReadonlyArray<Call.Call<any, any>>`

One [call](https://ethect.dev/reference/call/), or several.

### options.batch (optional)

- **Type:** `"auto" | "atomic" | "never"`
- **Default:** `"auto"`

How several calls may share a signature: see [the table](#the-table). This type is
`Tx.PlanOptions["batch"]`.

### options.from (optional)

- **Type:** [`Address.Address`](https://ethect.dev/reference/primitives/address/)
- **Default:** the signer's first account

The account that sends. The signer is asked what it can do for that account.

## Behavior

- **It asks the user nothing.** No prompt, no signature, no simulation. A wallet is asked what
  it can do, which shows nothing, unless it is locked: it may ask for its password first, and
  the plan does not wait more than 3 seconds for it. See
  [a wallet that is slow to answer](#a-wallet-that-is-slow-to-answer).
- **The signer is asked only when its answer changes the plan.** One call, or `batch:
  "never"`, is planned without it.
- **The chain is the transport's.** A step is for the chain of the
  [`Transport`](https://ethect.dev/reference/transport/) in context: under
  [`Transport.on(8453)`](https://ethect.dev/reference/transport/chains/), that is Base.
- **A plan is a snapshot.** Another account or another chain is another plan: plan again when
  the connection changes.
- **A wallet can still refuse what it said it can do.** A `"ready"` wallet asks its user to
  upgrade the account when the batch is submitted. A user who declines fails the submit with
  `TxUnsupported` `"upgradeRejected"`: plan again with `batch: "never"`, which is what
  [`Tx.send`](https://ethect.dev/reference/tx/send/#behavior) does.

## Errors

| Error | Reason | When |
| --- | --- | --- |
| [`Tx.Unsupported`](https://ethect.dev/reference/tx/failures/#txunsupported) | `"atomic"` | `batch: "atomic"`, several calls, and a signer that cannot run them as one |
| [`Signer.Error`](https://ethect.dev/reference/signer/) | `"Unauthorized"` | the signer holds no account, or not the one asked for. Or the wallet refuses to say what it can do (4100) |
| `Signer.Error` | `"Disconnected"` | the wallet is gone. Asked what it can do: 4900, 4901 |
| `Signer.Error` | `"Unknown"` | the wallet could not say what it holds. Any other failure to say what it can do is no capability, logged at the Debug level |
| [`RpcError`](https://ethect.dev/reference/errors/rpc-error/), [`TransportError`](https://ethect.dev/reference/errors/transport-error/) | | the node could not say its chain |

## Under the hood

Two services are asked, and nothing is sent to a chain.

**`Tx.plan(calls, { batch, from })`**

- **the signer** `accounts`: the sender, unless `from` is given
  - a wallet:
    - **the wallet** `eth_accounts`
  - a local key: no request
- **Transport** `eth_chainId`: once per transport. Not asked under `Transport.on`
- **the signer** `capabilities(from, chainId)`: only for several calls, unless `batch` is `"never"`
  - a wallet:
    - **the wallet** `wallet_getCapabilities`: once per account and chain, for the session. 3 s at most: then no capability, and the answer is kept when it comes
  - a local key: no request
