# A button with steps

An approval and a deposit behind one button, each signature shown as a row. A wallet that
batches gets one row and one click. Any other wallet gets one row per call. The component does
not know which wallet it has. It uses the `ethect.tsx` of [Let the user pick a wallet](https://ethect.dev/guides/wallet-selection/#the-setup),
unchanged: the runtime of the app, `run` and `useConnection`.

```tsx title="DepositButton.tsx"
import { useMemo } from "react";
import { Abi, type Address, Erc20, Erc4626 } from "@ethect/core";
import { useConnection } from "./ethect";
import { label, useFlow } from "./flow";

// The standard, and the error this vault reverts with.
const Vault = Erc4626.extend(
  Abi.parse(["error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max)"]),
);

type Props = { usdc: Address.Address; vault: Address.Address; amount: bigint };

export function DepositButton({ usdc, vault, amount }: Props) {
  const connection = useConnection({ status: "disconnected" });
  const account = connection.status === "connected" ? connection.accounts[0] : undefined;
  // Calls are plain data: building them sends nothing. The same array until an input changes.
  const calls = useMemo(() => {
    if (!account) return [];
    return [Erc20.at(usdc).approve(vault, amount), Vault.at(vault).deposit(amount, account)];
  }, [usdc, vault, amount, account]);
  const flow = useFlow(calls, account);

  if (!account) return <button disabled>Connect a wallet</button>;
  if (!flow.rows) return <button disabled>…</button>;
  return (
    <>
      <ol>
        {flow.rows.map((row, i) => (
          <li key={i}>
            {label(row)}: {row.status} {row.error?.message}
          </li>
        ))}
      </ol>
      <button onClick={flow.next} disabled={flow.busy || !flow.row}>
        {flow.row ? label(flow.row) : "Done"}
      </button>
    </>
  );
}
```
```tsx title="flow.tsx"
import { useEffect, useState } from "react";
import { Effect, Fiber } from "effect";
import { type Address, Tx } from "@ethect/core";
import { run, runtime } from "./ethect";
import { type Calls, key, resume, settled } from "./settled";

// What the page shows for one signature.
export interface Row {
  readonly step: Tx.Step; // the calls, whether they are atomic, the account, the chain
  readonly status: "todo" | "signing" | "pending" | "done" | "failed";
  readonly error?: { readonly _tag: string; readonly message: string };
}

// "approve + deposit": the calls name themselves.
export const label = ({ step }: Row) =>
  step.calls.map((call) => call.fn?.name ?? "transfer").join(" + ");

// One click: one signature, then its block. `update` is the `setState` of that row.
const sign = (step: Tx.Step, update: (change: Partial<Row>) => void) =>
  Effect.gen(function* () {
    update({ status: "signing" });
    yield* resume(step.from); // no signature while an earlier batch may still be mined
    const pending = yield* Tx.submit(step); // the wallet prompts
    localStorage.setItem(key(step.from), Tx.toJson(pending)); // plain data, for a reload
    update({ status: "pending" });
    yield* settled(pending, step.calls);
    update({ status: "done" });
  }).pipe(Effect.catch((error) => Effect.sync(() => update({ status: "failed", error }))));

export function useFlow(calls: Calls, account: Address.Address | undefined) {
  const [batch, setBatch] = useState<"auto" | "never">("auto");
  const [rows, setRows] = useState<ReadonlyArray<Row>>();

  // One row on a wallet that batches, one per call otherwise. Planned again for another account.
  useEffect(() => {
    setRows(undefined);
    const planned = Effect.andThen(Effect.ignore(resume(account)), Tx.plan(calls, { batch })).pipe(
      Effect.map((steps) => setRows(steps.map((step) => ({ step, status: "todo" })))),
      Effect.ignore, // no wallet is connected: no row
    );
    const fiber = runtime.runFork(planned);
    return () => void runtime.runFork(Fiber.interrupt(fiber));
  }, [calls, batch, account]);

  const row = rows?.find((row) => row.status !== "done"); // the one the button is for
  const next = () => {
    const { step } = row!;
    const update = (change: Partial<Row>) => {
      // The wallet will not take the calls as one after all: plan again, one row per call.
      if (change.error?._tag === "TxUnsupported") setBatch("never");
      setRows((rows) => rows?.map((row) => (row.step === step ? { ...row, ...change } : row)));
    };
    void run(sign(step, update));
  };
  const busy = rows?.some(({ status }) => status === "signing" || status === "pending") ?? true;

  return { rows, row, next, busy };
}
```
```ts title="settled.ts"
import { Effect, Option, Schedule } from "effect";
import { type Address, type Call, Err, Signer, Tx } from "@ethect/core";

export type Calls = ReadonlyArray<Call.Call<unknown, unknown>>;

// One pending per account: a batch is only known to the wallet of the account that sent it.
export const key = (account: Address.Address) => `pending:${account}`;

// A wallet that does not know the batch never will, and the batch may still be mined.
const unknown = (error: unknown) =>
  error instanceof Signer.Error && error.reason === "UnknownBatch";

// In a block, over (Tx.isOutcome: reverted, or dropped), or unknown. Anything else means
// nobody could say: it is asked again.
export const settled = (pending: Tx.Pending, calls: Calls = []) => {
  const forget = () => Effect.sync(() => localStorage.removeItem(key(pending.from)));
  return Tx.wait(pending, { errors: Err.of(calls) }).pipe(
    Effect.retry({
      while: (error) => !Tx.isOutcome(error) && !unknown(error),
      schedule: Schedule.spaced("5 seconds"),
    }),
    Effect.tap(forget),
    // over: forgotten. An unknown one is kept
  Effect.tapError((error) => (Tx.isOutcome(error) ? forget() : Effect.void)),
  );
};

// What this account left pending is waited for. It fails while its wallet does not know it.
export const resume = (account: Address.Address | undefined) =>
  Effect.suspend(() => {
    const stored = Tx.fromJson(account && localStorage.getItem(key(account)));
    if (Option.isNone(stored)) return Effect.void; // nothing stored, or what is no pending
    return Effect.catchIf(settled(stored.value), Tx.isOutcome, () => Effect.void);
  });
```

If you do not show the steps, you need none of this: `run(Tx.send(calls))` from a click asks
for one signature or two and waits for the blocks. See [`Tx.send`](https://ethect.dev/reference/tx/send/).

## The hook

`useFlow` is the three functions `Tx.send` is made of, with a state between them. The plan
gives one step per signature and asks the user nothing: the steps are the rows. A click
submits the first row that is not done, then waits for its block.

## What the user can do

| The user | The rows | The button |
| --- | --- | --- |
| has a wallet that batches | one, `approve + deposit`: all or nothing | one click |
| has a wallet that does not | two, `approve` then `deposit` | one click each, the second once the first is in a block |
| refuses a signature | that row is `failed`, with `SignerRejected` | asks again for the same row |
| declines the upgrade a batch needs, or has a wallet that refuses the batch | planned again: two rows, and no error shown | one click each |
| sees a call revert | that row is `failed`, with the reason | asks again for the same row |
| changes account in the wallet | planned again, for that account | starts over |
| comes back with a wallet that does not know their batch | `failed`, with what the wallet said | asks that wallet again, and signs nothing |

A revert reads as a sentence when its error is declared:
`ERC4626ExceededMaxDeposit(receiver: 0x…, assets: 101, max: 100)`. In a batch, the reason is
what the wallet's own code reverted with, which may be raw data.

`Calls` types every call alike, so in `settled` the reason is typed `unknown`: a row shows only
its `message`. `Err.of(calls)` still decodes it when the program runs. To match on the reason,
keep the type of the list: see [Calls passed to a function](https://ethect.dev/guides/errors/#calls-passed-to-a-function).

## A reload

What the wallet answers is a [`Tx.Pending`](https://ethect.dev/reference/tx/wait/#txpending): plain data. `sign`
stores it under its account, and that account's next visit waits for it before it plans.

Hashes are followed on your node, and the id of a batch by the wallet that took it. Receipts,
`TxReverted` and `TxDropped` end a wait for good, and a `failed` row can be signed again. Any
other wallet does not know the batch: `SignerError` `"UnknownBatch"`, which says nothing of it.
It may still be mined, so the pending is kept, and a click signs nothing until the wallet that
took it answers. To give up on it is the user's call: `localStorage.removeItem(key(account))`.
Anything else means nobody could say yet, which [`Tx.isOutcome`](https://ethect.dev/reference/tx/failures/#txisoutcome)
tells apart: `settled` asks again, and the button stays disabled. A wallet that could not say
where the batch stands is already asked again by `Tx.wait`, at the next block, three times.

## Keep the action as data

A framework that keeps its state as data, such as `effect/ui`, a page rendered on a server or a
store, cannot hold a `Tx.Step`. Keep the action instead, what to deposit, and call `Tx.plan`
again where you sign.

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

// The action: a prop, a message, the arguments of a command. It encodes as any data.
const Deposit = Schema.Struct({
  usdc: Address.schema,
  vault: Address.schema,
  amount: Schema.BigIntFromString,
  from: Address.schema,
});
type Deposit = typeof Deposit.Type;

const calls = ({ usdc, vault, amount, from }: Deposit) => [
  Erc20.at(usdc).approve(vault, amount),
  Erc4626.at(vault).deposit(amount, from),
];

// Where the rows are shown: one per signature.
export const rows = (deposit: Deposit) => Tx.plan(calls(deposit), { from: deposit.from });

// A click on a row: the same plan, made again where the wallet signs.
export const sign = (deposit: Deposit, row: number) =>
  Effect.gen(function* () {
    const steps = yield* Tx.plan(calls(deposit), { from: deposit.from });
    const pending = yield* Tx.submit(steps[row]!);
    return yield* Schema.encodeEffect(Tx.pendingSchema)(pending); // data again, for the state
  });
```

- **A step is not data.** Its calls hold their function, with its ABI and the errors it
  declares. `Tx.submit` reads a revert with them, as the contract's own error. A step
  encoded and decoded back would have lost them.
- **Planning again asks the wallet nothing.** The account is in the action, the chain id was
  asked of your node once, and the answers to `wallet_getCapabilities` are kept per account and
  chain for as long as the wallet is connected. They are forgotten only when the wallet says
  `accountsChanged`. A provider that cannot be listened to keeps none: it is asked each time.
- **The plan is the one shown.** `Tx.plan` reads nothing from the chain: no balance, no
  allowance. Its steps follow from the calls, the account, the chain and the capabilities, so
  the same action gives the same steps. One exception: a wallet that took more than 3 s to say
  what it can do was planned with none, one row per call, and its late answer is kept for the
  next plan.

What the wallet answers is data. Keep it in the state with
[`Tx.pendingSchema`](https://ethect.dev/reference/tx/wait/#txpendingschema), or as text with `Tx.toJson`, and
`Tx.wait` takes it back as it was.

## Under the hood

- **the wallet** `wallet_getCapabilities`: the rows, `Tx.plan`: once per account and chain, 3 s at most. No prompt, unless the wallet is locked
- **the wallet** `eth_chainId`: a click, `Tx.submit`
- **the wallet** `eth_sendTransaction, or wallet_sendCalls`: then: a hash for one call, the id of a batch for several
- **your node** `eth_getTransactionReceipt`: then, `Tx.wait`: asked first, then at each new block
- **the wallet** `wallet_getCallsStatus`: for a batch, on the wallet first, then at each new block, while it is pending

See [`Tx.plan`](https://ethect.dev/reference/tx/plan/#under-the-hood), [`Tx.submit`](https://ethect.dev/reference/tx/submit/#under-the-hood) and [`Tx.wait`](https://ethect.dev/reference/tx/wait/#under-the-hood).
