# Tx.wait

Waits for what was submitted to be in a block, as deep as asked, and gives the receipts. Fails
if a transaction reverted or was dropped.

## Usage

```ts title="pay.ts"
import { Effect } from "effect";
import { type Address, type Hash, Tx } from "@ethect/core";
import { Token } from "./token";

const pay = (usdc: Address.Address, to: Address.Address) =>
  Effect.gen(function* () {
    const pending = yield* Tx.submit(Token.at(usdc).transfer(to, 1_000_000n));
    const receipts = yield* Tx.wait(pending); // one receipt per transaction, in order
    // deeper: the same transaction, once five blocks are on top of its own
    const [receipt] = yield* Tx.wait(pending, { confirmations: 6 });
    return [receipts.length, receipt?.blockNumber];
  });

// A hash from anywhere: one receipt, and no signer needed.
const other = (hash: Hash.Hash) => Tx.wait(hash);
```

```ts title="token.ts"
import { Abi, Erc20 } from "@ethect/core";

// ERC-20 is built in, and declares no error. This adds the one the token reverts with.
export const Token = Erc20.extend(
  Abi.parse(["error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)"]),
);
```

What [`Tx.submit`](https://ethect.dev/reference/tx/submit/) returned decides who is asked. Transaction hashes
are followed on your node. A handle is followed on the signer that gave it, since only that
signer knows its id.

### What is waited for

| Given | Asked | Needs | Gives |
| --- | --- | --- | --- |
| a hash | the node | `Transport` | one `Receipt` |
| [`Tx.Transactions`](#txtransactions) | the node | `Transport` | one receipt per hash, in order |
| [`Tx.Handle`](#txhandle) | the signer, then the node | `Signer` and `Transport` | the receipts of the transactions the signer names |

### It asks first

Whoever knows where things stand is asked first. Blocks are watched only when the answer says
it is not over: a transaction mined long ago costs its one request.

| Given | Sent |
| --- | --- |
| a hash, in a block | `eth_getTransactionReceipt`, and that is all |
| the same, with `confirmations: 3` or `"finalized"` | one more request, for how deep it is |
| the same, and it reverted | the receipt, then [what finds the reason](#under-the-hood) |
| a hash, in no block yet | the receipt, then the heads of [`Block.watch`](https://ethect.dev/reference/block/): pushed over a transport that pushes, polled otherwise |
| several hashes | their receipts first, together. The heads only if one is missing, or not deep enough |
| a handle | the signer first, once. The heads only if it says the batch is pending, or could not say |

To ask once and not wait at all, use [`Tx.receipt`](https://ethect.dev/reference/tx/receipt/): it gives none for
a transaction that is in no block yet.

### On the chain it was submitted on

What a signer answered says its chain, and is waited for on a transport of that chain. On
another one, the wait fails with `TransportUnknownChain` and asks nothing: a node of another chain
would say the transaction does not exist. A hash alone says no chain, and is waited for where
the program is.

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

// With several chains: the pending says which one it is on.
const resume = (pending: Tx.Pending) => Tx.wait(pending).pipe(Transport.on(pending.chainId));

// With one transport: a pending of another chain is a failure to show, not a wait.
const onThisChain = (pending: Tx.Pending) =>
  Tx.wait(pending).pipe(Effect.catchTag("TransportUnknownChain", (error) => Effect.succeed(error.message)));
```

### How deep

`confirmations` is a number of blocks, the one of the transaction included, or a tag of the
chain.

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

const depths = (hash: Hash.Hash) => [
  Tx.wait(hash), // 1, the default: in a block
  // two blocks on top of its own
  Tx.wait(hash, { confirmations: 3 }),
  // the chain's finalized block has reached its block
  Tx.wait(hash, { confirmations: "finalized" }),
];
```

### What a revert may be

A receipt says that a transaction reverted, and not why. `errors` gives the custom errors to
read the reason with: [`Err.of(calls)`](https://ethect.dev/reference/err/of/) gives those of the calls.

```ts
import { Effect } from "effect";
import { type Address, Err, Tx } from "@ethect/core";
import { Token } from "./token";

const pay = (usdc: Address.Address, to: Address.Address) =>
  Effect.gen(function* () {
    const call = Token.at(usdc).transfer(to, 1_000_000n);
    const pending = yield* Tx.submit(call, { transaction: { gas: 80_000n } });
    return yield* Tx.wait(pending, { errors: Err.of([call]) }).pipe(
      Effect.catchReason("TxReverted", "ERC20InsufficientBalance", (reason) =>
        Effect.succeed(reason.needed),
      ),
    );
  });
```

Without `errors`, the reason is a plain [`Revert`](https://ethect.dev/reference/revert/): a message, a panic, or
the data as it is.

The type of the reason comes from the type of the calls given to `Err.of`. Calls typed
`ReadonlyArray<Call.Call<unknown, unknown>>` still decode the revert, and type its reason
`unknown`: see [Calls passed to a function](https://ethect.dev/guides/errors/#calls-passed-to-a-function).

### A transaction that is replaced

A wallet lets its user speed a transaction up, or cancel it. Both send another transaction at
the same nonce.

| What took the nonce | The wait |
| --- | --- |
| the same call with other fees: same `to`, data and value | follows the new hash, and gives its receipt |
| anything else: a cancellation, another call | fails with `TxDropped`, with `replacedBy` |
| a transaction mined before the wait began | fails with `TxDropped`, without `replacedBy` |

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

const followed = (hash: Hash.Hash) =>
  Tx.wait(hash).pipe(
    // the hash of the receipt is the new one when the wallet sped the transaction up
    Effect.map((receipt) => receipt.transactionHash),
    Effect.catchTag("TxDropped", (error) =>
      Effect.succeed(error.replacedBy ?? "gone, and nothing says what took its place"),
    ),
  );
```

A fee bump is told from a cancellation by what the first transaction carried, which the node
is asked once. A [`Tx.Transactions`](#txtransactions) that says the nonce of each transaction,
as a local signer gives, saves that request: any replacement then drops it, and `replacedBy` is
what to wait for instead.

## Returns

`Effect<Receipt, Tx.Reverted<never> | Tx.Dropped | Transport.Error, Transport>` for a hash.

`Effect<ReadonlyArray<Receipt>, Tx.Reverted<E> | Tx.Dropped | Transport.UnknownChain | Transport.Error, Transport>`
for a `Tx.Transactions`.

`Effect<ReadonlyArray<Receipt>, Tx.Reverted<E> | Tx.Dropped | Transport.UnknownChain | Signer.Error | Transport.Error, Signer | Transport>`
for a `Tx.Pending`, which may be a handle.

The [receipts](https://ethect.dev/rpc/types/receipt/), all of transactions that succeeded. `E` is the errors
given in `errors`.

## Parameters

### pending

- **Type:** [`Hash.Hash`](https://ethect.dev/reference/primitives/hash/) `|` [`Tx.Pending`](#txpending)

A transaction hash, or what `Tx.submit` returned.

### options.confirmations (optional)

- **Type:** `number | "safe" | "finalized"`
- **Default:** `1`

How deep the transactions must be.

| Value | Deep enough when |
| --- | --- |
| a number `n` | `head.number - receipt.blockNumber + 1 >= n`. `1`, or less, is any block |
| `"safe"`, `"finalized"` | the block the node gives for that tag is at or past the receipt's |

### options.errors (optional)

- **Type:** `ReadonlyArray<new (value: any) => unknown>`

The custom errors a revert may be, as [`Err.make`](https://ethect.dev/reference/err/make/) builds them. They type
the `reason` of a `TxReverted`. This type and the one above are `Tx.WaitOptions`.

## What is given to it

### Tx.Pending

- **Type:** `Tx.Transactions | Tx.Handle`

What a signer answered. Plain data, told apart by `_tag`: it can be stored and waited for
later.

### Storing a pending

[`Tx.toJson`](#txtojson) writes a pending as text, and [`Tx.fromJson`](#txfromjson) reads it
back: for local storage, a cookie, a row of a database. For a pending in data of your own, the
arguments of a command or a message, use [`Tx.pendingSchema`](#txpendingschema).

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

const remember = (pending: Tx.Pending) => localStorage.setItem("transfer", Tx.toJson(pending));

// After a reload. None when nothing was stored, or when what is there is no pending.
const resume = Effect.gen(function* () {
  const pending = Tx.fromJson(localStorage.getItem("transfer"));
  return Option.isSome(pending) ? yield* Tx.wait(pending.value) : [];
});
```

### Tx.toJson

- **Type:** `(pending: Tx.Pending) => string`

A pending as text: `JSON.stringify` of the data [`Tx.pendingSchema`](#txpendingschema) encodes it
to. It is the pending as it is, with each `bigint` written as the hex quantity a node writes,
and each address in its EIP-55 form, as every address ethect writes:

```json
{"_tag":"Transactions","hashes":["0x5e…"],"nonces":[7],"fields":[{"nonce":7,"gas":"0x5208","maxFeePerGas":"0x4a817c800","maxPriorityFeePerGas":"0x3b9aca00"}],"from":"0xf39F…","chainId":1}
```

`JSON.stringify(pending)` throws on a pending of a local signer, whose fees are `bigint`s. Use
`Tx.toJson`.

It cannot fail. A pending no signer gives, such as one with a chain id that is no count, which
the schema refuses, is written all the same, and `Tx.fromJson` reads none from it.

### Tx.fromJson

- **Type:** `(text: string | null | undefined) => Option<Tx.Pending>`

The pending a text holds. It never throws: nothing stored, text that is not JSON and JSON that
is no pending all give none. A field it does not know is left out.

It reads what `Tx.toJson` wrote. It also reads what `JSON.stringify` wrote of a pending before
a pending held its fees, and what `Tx.toJson` wrote before addresses were checksummed, in
lowercase: what an app has stored is still read. An address is read in any case, as the
lowercase `Address`.

### Tx.pendingSchema

The schema of a pending, for a pending in data of your own: the arguments of a command, a
message, the state of a store. A framework that keeps all of it as encoded data, such as
`effect/ui`, takes it as any other field. It decodes JSON data to a [`Tx.Pending`](#txpending),
and encodes one to the data `Tx.toJson` writes as text.

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

// The message that says a deposit went out.
const Submitted = Schema.Struct({ amount: Schema.BigIntFromString, pending: Tx.pendingSchema });

// { amount: "100", pending: { _tag: "Transactions", hashes: ["0x5e…"], from: "0xf39F…", chainId: 1 } }
const message = (amount: bigint, pending: Tx.Pending) =>
  Schema.encodeEffect(Submitted)({ amount, pending });

// After a reload, or on another side of the app.
const received = (data: unknown) =>
  Effect.map(Schema.decodeUnknownEffect(Submitted)(data), ({ pending }) => pending);
```

- **Type:** `Tx.Pending`. **Encoded:** `Tx.pendingSchema.Encoded`, plain JSON data.

| What the pending holds | Encoded as |
| --- | --- |
| a `bigint`: `gas`, the fees | a hex quantity: `"0x5208"` |
| an address: `from`, those of an access list | its EIP-55 form |
| a count: `chainId`, the nonces | a number |
| a key set to `undefined` | nothing: the key is left out |

- **Decoding reads what `Tx.fromJson` reads**: an address in any case, as the lowercase
  `Address`, and a pending stored before it held its fees. A key it does not know is left out.
- **Data that is no pending fails**, with a `SchemaError`, where `Tx.fromJson` gives none. So
  does encoding a pending no signer gives, such as one with a chain id that is no count.
- **A pending is the data to keep, and a [step](https://ethect.dev/reference/tx/plan/#txstep) is not**: its calls
  hold their functions. See [Keep the action as data](https://ethect.dev/guides/transaction-button/#keep-the-action-as-data).

### Tx.Transactions

Transaction hashes: any node knows where they stand.

| Field | Type | Holds |
| --- | --- | --- |
| `_tag` | `"Transactions"` | |
| `hashes` | `ReadonlyArray<Hash.Hash>` | one per call, in order |
| `nonces` | `ReadonlyArray<number>`, optional | the nonce of each, when the signer knows them: a local key does |
| `fields` | `ReadonlyArray<`[`Tx.Fields`](https://ethect.dev/reference/tx/submit/#txfields)`>`, optional | what each transaction went out with, one per hash, when the signer knows it |
| `from` | [`Address.Address`](https://ethect.dev/reference/primitives/address/) | the account that sent them |
| `chainId` | `number` | the chain they are on |

`fields` is what [replaces a stuck transaction](https://ethect.dev/reference/tx/submit/#a-stuck-transaction):
given back as the `transaction` of a submit, with more fees, nothing has to be kept aside.
What a signer does not know is absent, and never guessed.

| The signer | `nonces` | `fields`, per transaction |
| --- | --- | --- |
| a local key | its nonce | `nonce`, `gas`, and its fees: `maxFeePerGas` and `maxPriorityFeePerGas`, or `gasPrice` alone. `accessList` and `type` when they were set |
| a wallet, one call | absent | absent. A wallet answers the hash, and decides the rest itself, also when `transaction` set some |
| [`TestSigner`](https://ethect.dev/reference/testing/test-signer/) | absent | absent: the node signs |

### Tx.Handle

An id only its signer can resolve: a wallet batch today, a user operation tomorrow.

| Field | Type | Holds |
| --- | --- | --- |
| `_tag` | `"Handle"` | |
| `kind` | `"eip5792"`, or a signer's own | what the id is: a signer refuses a kind it did not give |
| `id` | `string` | the id |
| `from` | `Address.Address` | the account that sent the calls |
| `chainId` | `number` | the chain they are on |

`Tx.Handle.Status` is where a handle stands, as its signer says.

| Status | The wait |
| --- | --- |
| `{ _tag: "pending" }` | goes on, and asks again at each head |
| `{ _tag: "included", hashes }` | asks the node for the receipts of the hashes, and waits for the depth. With no hash, it asks the signer again at the next head |
| `{ _tag: "reverted", hashes }` | reads the receipts, and fails with `TxReverted` |
| `{ _tag: "dropped" }` | fails with `TxDropped` |

A signer that could not say gives no status. That may pass, so it is asked again at the next
head: an answer that did not read, a wallet that did not answer, or no wallet connected yet.
At the third failure in a row, the first answer included, the wait fails with it.

A signer that does not know the handle never will: the wait fails at once. A wallet answers
so, with the error 5730, when it is not the wallet that took the batch or when it has
forgotten it. The wait fails with `SignerError` `"UnknownBatch"`, and the batch may still be
mined.

## Behavior

- **It asks before it watches.** The receipts, or the signer of a handle, are asked before any
  block is read. When every transaction is in a block, as deep as asked, that is the whole
  wait: nothing is subscribed to and no head is read.
- **Then it looks once per block.** What is left follows [`Block.watch`](https://ethect.dev/reference/block/):
  pushed over a WebSocket, polled over HTTP. Nothing else is polled.
- **The first head asks for no receipt again.** What was read a moment before stands. A block
  may have come in between: the node is asked whether the transaction is in one, or its nonce
  taken, and its receipt is asked for at that head when it says so.
- **A wait that is slower than the blocks looks at the latest one.** It never queues behind
  blocks it has not looked at.
- **A receipt that is deep enough is asked for once more.** Gone, or in another block: a reorg
  took it. The wait goes on with what the node says now.
- **A reorg is seen at once.** A head that does not follow the one before it makes the wait
  ask again for every receipt it holds. That covers a stream that started over, after more
  than 256 blocks were missed.
- **A transaction with no receipt is still looked after.** The nonce of its sender is read at
  each head. Taken at two heads in a row, with no receipt, it went to another transaction,
  which is looked for in the blocks since the nonce was last free.
- **A hash the node has never heard of is given three heads in a row and two minutes.** A
  wallet sends through a node of its own, and yours may not know the transaction until it is
  in a block: on a chain whose blocks come four a second, three heads are under a second. Past
  both, the wait fails with `TxDropped`. To give up sooner, use `Effect.timeout`.
- **A transaction whose nonce is known is waited for until that nonce is used.**
- **What a signer answered is waited for on its chain.** A `Tx.Transactions` or a `Tx.Handle`
  whose `chainId` is not the transport's fails with `TransportUnknownChain`, before anything is asked.
- **A handle that is included and names no transaction is asked again.** A wallet may list the
  receipts of a batch a moment after it says the batch is in. With none named at three heads
  in a row, the wait fails with `SignerError` `"Unknown"`: there is no receipt to give. The
  answer before any head is not one of the three.
- **A signer that could not say is asked again at the next head.** Three failures in a row,
  the first answer included, fail the wait with the last one. A status in between starts them
  over. `"UnknownBatch"` fails at once. Once a status names the transactions, only the node is
  asked.
- **Every transaction is waited for before the wait judges.** When all are as deep as asked,
  one that reverted fails the wait, with all the receipts.
- **The reason of a revert is found by running the transaction again**, with `eth_call` on the
  block before its own. A run that does not revert again, or a node that no longer has that
  state, leaves a `Revert.Unknown` with no data.
- **A handle names no call.** The transactions of a wallet batch are not one per call: its
  `TxReverted` has no `call`. A hash from anywhere has none either.
- **`call` counts among what was waited for.** For a `Tx.Transactions`, it is the index of the
  transaction among its hashes: among the calls of one step, not of a whole plan.
- **The reason of a batch is what the wallet's code reverted with.** A wallet runs a batch with
  code of its own, so the reason may be a `Revert.Unknown` even when the error of the contract
  is in `errors`. [`TestWallet`](https://ethect.dev/reference/testing/test-wallet/) reverts with the index of
  the call that failed, as 32 bytes, followed by what that call reverted with.
- **A wallet that does not know a batch has not dropped it.** `TxDropped` is for a wallet that
  says so, with a status from 400 to 499. One that answers 5730 fails the wait with
  `SignerError` `"UnknownBatch"`: wait again with the wallet that took the batch.
- **Many waits share their requests.** Waits on one transport follow the same heads. What one
  asks at a head, the others do not ask again: the nonce of a sender, the block of a tag. What
  each asks first, before any head, is its own. With
  more than eight transactions waited for, the receipts of each new block are asked for in one
  request, `eth_getBlockReceipts`, in place of one request per transaction.
- **It has no timeout.** Compose one: `Tx.wait(pending).pipe(Effect.timeout("5 minutes"))`.

## Errors

| Error | When |
| --- | --- |
| [`Tx.Reverted`](https://ethect.dev/reference/tx/failures/#txreverted) | a transaction is in a block and reverted. `reason` is one of `errors`, or a plain revert |
| [`Tx.Dropped`](https://ethect.dev/reference/tx/failures/#txdropped) | another transaction took its nonce, the node never heard of it, or the signer gave up on the batch |
| [`Transport.UnknownChain`](https://ethect.dev/reference/transport/chains/#unknownchain) | what a signer answered is on another chain than the transport in context. Nothing was asked |
| [`Signer.Error`](https://ethect.dev/reference/signer/#failures) | a handle, and the signer could not say where it stands, three times in a row. `"UnknownBatch"`: the wallet does not know the id, at once. Or it says included and names no transaction, three heads in a row |
| [`RpcError`](https://ethect.dev/reference/errors/rpc-error/), [`TransportError`](https://ethect.dev/reference/errors/transport-error/) | the node refused, or could not be reached |

`TxReverted` and `TxDropped` are over, which [`Tx.isOutcome`](https://ethect.dev/reference/tx/failures/#txisoutcome)
says. The others mean that nobody could say, and what was submitted may still be mined: wait
again, and do not sign again. See [after a failure](https://ethect.dev/reference/tx/failures/#after-a-failure).

## Under the hood

For transaction hashes, only the `Transport` is asked.

**`Tx.wait(pending, { confirmations, errors })`: what a signer answered**

- **your node** `eth_chainId`: once per transport. Not asked under `Transport.on`
  - another chain → fails: `TransportUnknownChain`

**first, before any head**

- **your node** `eth_getTransactionReceipt(hash)`: one per transaction, together
  - each has a receipt: how deep?
    - 1, the default: no request: a receipt is a block
    - a number:
      - **your node** `eth_blockNumber`
    - `"safe"`, `"finalized"`:
      - **your node** `eth_getBlockByNumber(tag)`
  - all are deep enough: judged, as below. No head was read

**one is in no block, or not deep enough**

- **your program** `Block.watch`: one stream of heads per transport, shared

**at the first head, when one had no receipt: what was read a moment ago stands**

- a receipt that is deep enough: no request
- no receipt: not asked for again, unless:
  - **your node** `eth_getTransactionByHash(hash)`: says it is in a block
  - **your node** `eth_getTransactionCount(sender, "latest")`: is past its nonce

**at each head after it, for a transaction with no receipt**

- **your node** `eth_getTransactionReceipt(hash)`: or `eth_getBlockReceipts(head)`, once for every wait, when more than eight transactions are waited for
  - none, and nobody said who sent it:
    - **your node** `eth_getTransactionByHash(hash)`: once: its sender, its nonce, what it carries
      - unknown to the node at three heads in a row, two minutes into the wait → fails: `TxDropped`
  - none, and its sender is known:
    - **your node** `eth_getTransactionCount(sender, "latest")`: once per sender and head
      - past its nonce at two heads in a row:
        - **your node** `eth_getBlockByNumber(n, true)`: the blocks since the nonce was last free, 256 at most
          - the same call under another hash: the new hash is followed
          - anything else, or nothing → fails: `TxDropped { transaction, replacedBy }`

**at each head, for a transaction with a receipt**

- a number: no request: the head says how deep it is
- `"safe"`, `"finalized"`:
  - **your node** `eth_getBlockByNumber(tag)`: once per head
- deep enough:
  - **your node** `eth_getTransactionReceipt(hash)`: once more
- a head that does not follow the last:
  - **your node** `eth_getTransactionReceipt(hash)`: a reorg

**every transaction is deep enough**

- one reverted:
  - **your node** `eth_getTransactionByHash(hash)`
  - **your node** `eth_call({ from, to, data, value, gas }, block - 1)`
  - → fails: `TxReverted`
- otherwise → the receipts

For a handle, the `Signer` is asked first.

**first**

- **the signer** `status(handle)`: a wallet: `wallet_getCallsStatus(id)`
  - included: its hashes are waited for on the node, as above: their receipts first
  - reverted: the same, then → fails: `TxReverted`
  - dropped → fails: `TxDropped`
  - the signer does not know the handle, as a wallet that answers 5730: not dropped, it may still be mined → fails: `SignerError` `"UnknownBatch"`
  - pending, included with no transaction named, or it could not say:
    - **your program** `Block.watch`
    - **the signer** `status(handle)`: as above, at each head, the first one too
      - pending: the wait goes on
      - none named: asked again. At three heads in a row → fails: `SignerError`
      - it could not say: asked again. At three in a row, the first answer included → fails: `SignerError`
