# Errors

No effect throws. A failure is a tagged value with a message. How to catch the custom error of a contract in a read and in a send, and every failure the library has.

No effect throws. A failure is a value: it has a `_tag` to match on and a `message` to show, and
the type of a program lists the failures you have not handled. The example catches the custom
error of a contract, in a read and in a send.

```ts title="nft.ts"
import { Effect } from "effect";
import { Abi, Erc721, Signer, Tx, type Address } from "@ethect/core";

// ERC-721 declares no error. This adds the one the collection reverts with.
const Nft = Erc721.extend(Abi.parse(["error ERC721NonexistentToken(uint256 tokenId)"]));

// In a read, the error of the contract is the failure itself.
export const ownerOf = (nft: Address.Address, tokenId: bigint) =>
  Nft.at(nft)
    .ownerOf(tokenId)
    .pipe(Effect.catchTag("ERC721NonexistentToken", () => Effect.succeed(undefined)));
// Effect<Address | undefined, …>: the error is gone from the type

// In a send, the failure is `TxReverted`, and the error of the contract is its `reason`.
export const give = (nft: Address.Address, to: Address.Address, tokenId: bigint) =>
  Effect.gen(function* () {
    const me = yield* Signer.address;
    const receipt = yield* Tx.send(Nft.at(nft).transferFrom(me, to, tokenId));
    return `Sent in block ${receipt.blockNumber}`;
  }).pipe(
    Effect.catchReason("TxReverted", "ERC721NonexistentToken", (reason) =>
      Effect.succeed(`Token ${reason.tokenId} does not exist`),
    ),
  );
```

The error is declared once, as a signature. From then on it is typed: `reason.tokenId` is a
`bigint`, and a typo in the tag does not compile.

- **A read fails with the error itself.** The call did nothing else than revert.
- **A send fails with `TxReverted`.** A send can fail in many other ways, so the revert is one
  case of it, and its `reason` says why. `Effect.catchReason` handles one reason and lets the
  others through. With a key, the revert is found before anything is sent.
- **An error the signatures do not declare** is a `RevertUnknown`, with the raw `data`. It
  still has a tag and a message.

## Catch by tag

`.pipe(a, b)` applies `a`, then `b`. Each of these removes what it handles from the type, so
the compiler tells you what is left.

| Function | Handles |
| --- | --- |
| `Effect.catchTag("SignerRejected", handler)` | one failure, by its tag |
| `Effect.catchTags({ SignerRejected, TxReverted })` | several, one handler each |
| `Effect.catchReason("TxReverted", "ERC721NonexistentToken", handler)` | one `reason` of a failure that has several. The handler gets the reason |
| `Effect.catch(handler)` | everything that is left |

```ts
import { Effect } from "effect";
import type { Address } from "@ethect/core";
import { give } from "./nft";

const said = (nft: Address.Address, to: Address.Address, tokenId: bigint) =>
  give(nft, to, tokenId).pipe(
    Effect.catchTag("SignerRejected", () => Effect.succeed("You refused to sign")),
    // Every failure has a tag and a message: one line turns the rest into text.
    Effect.catch((error) => Effect.succeed(`${error._tag}: ${error.message}`)),
  );
// Effect<string, never, Signer | Transport>: nothing is left to fail
```

A failure you do not handle reaches whoever runs the program: `Effect.runPromise` rejects with
the error value itself. To look at both outcomes yourself, `Effect.result(effect)` gives the
failure as a value.

## Calls passed to a function

The type of a revert's `reason` comes from the type of the calls. A function that takes any
calls keeps their errors with a `const` type parameter.

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

// `C` is the list as it was given: each call keeps the errors of its function.
export const simulate = <const C extends ReadonlyArray<Call.Call<unknown, unknown>>>(calls: C) =>
  Tx.simulate(calls);

// `C` types the reason. `Err.of(calls)` is what the wait decodes the revert with.
export const wait = <const C extends ReadonlyArray<Call.Call<unknown, unknown>>>(
  pending: Tx.Pending,
  calls: C,
) => Tx.wait(pending, { errors: Err.of(calls) });

const Vault = Erc4626.extend(
  Abi.parse(["error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max)"]),
);

export const check = (usdc: Address.Address, vault: Address.Address, user: Address.Address, amount: bigint) =>
  simulate([Erc20.at(usdc).approve(vault, amount), Vault.at(vault).deposit(amount, user)]).pipe(
    Effect.map(() => "The deposit would go through"),
    Effect.catchReason("TxReverted", "ERC4626ExceededMaxDeposit", (reason) =>
      Effect.succeed(`The vault takes ${reason.max} more`),
    ),
  );

// The same calls typed `ReadonlyArray<Call.Call<unknown, unknown>>`: the reason is `unknown`.
const widened = (calls: ReadonlyArray<Call.Call<unknown, unknown>>) =>
  Tx.simulate(calls).pipe(
    // @ts-expect-error: no error of the calls is known, so none has a tag to catch
    Effect.catchReason("TxReverted", "ERC4626ExceededMaxDeposit", () => Effect.succeed("full")),
  );
```

- **A widened list loses its errors in the type.** `ReadonlyArray<Call.Call<unknown, unknown>>`
  types every call alike, and `reason` is `unknown`.
- **`Tx.wait` still needs `Err.of(calls)`.** A pending holds hashes or the id of a batch, not
  the calls: the wait decodes a revert with the errors you give it, whatever the type says.

## Every failure

| `_tag` | From | Means |
| --- | --- | --- |
| the name of a custom error | a read | The contract reverted with an [error you declared](https://ethect.dev/reference/err/) |
| `RevertReason` | a read | It reverted with a message: `require(…, "paused")` |
| `RevertPanic` | a read | An assertion, an overflow, a division by zero. `code` says [which](https://ethect.dev/reference/revert/#panic-codes) |
| `RevertUnknown` | a read | It reverted with data no declared error matches |
| `TxReverted` | a send | A call reverted. `reason` is one of the four above |
| `TxDropped` | a send | The transaction will not be mined: it left the mempool, or another took its nonce |
| `TxUnsupported` | a send | The signer or the node cannot do what was asked. `reason` says what |
| `TxPartial` | a send | With a key: some calls went out before one was refused. `sent` has them |
| `SignerRejected` | a send, a signature, a connection | The user refused in the wallet |
| `SignerError` | the same | The signer cannot: wrong chain, unknown account, no wallet. `reason` says which |
| `TransportUnknownChain` | [`Transport.on`](https://ethect.dev/reference/transport/chains/), a wait | The program has no node for that chain |
| `AbiError` | a read, a send, `Abi.encode` | A value is not what its Solidity type takes, or bytes are not its encoding |
| `RpcError` | anything that asks a node or a wallet | It answered with an error. `reason` is one [per code](https://ethect.dev/reference/errors/rpc-error/#reasons) |
| `TransportError` | the same | No answer came back. `reason`: `Unreachable`, `HttpStatus`, `ConnectionLost`… |
| `CodecError` | a method of the [JSON-RPC layer](https://ethect.dev/rpc/) | An answer does not have the shape the method promises. `value` holds it as it came |
| `EnsError` | [`Ens`](https://ethect.dev/reference/ens/#failures) | A name that cannot be asked about, or a resolver that misbehaves |
| `InvalidAddressError` | `Address.make` | The text is not an address, or its checksum is wrong |
| `InvalidHexError` | `Hex.toBytes` | The text is not hex of even length |
| `AnvilError` | [`AnvilNode`](https://ethect.dev/reference/testing/anvil-node/) | anvil could not be started |

What a function can fail with is in its type, and in the **Errors** table of its reference
page. [Failures](https://ethect.dev/reference/tx/failures/) has every field of the five failures of a send.

`AbiError`, the three reverts, `TxDropped`, `TxUnsupported`, `SignerRejected`, `SignerError`,
`TransportUnknownChain`, `EnsError`, `RpcError`, `TransportError` and `CodecError` are classes
that are their own Schema. Declared in the failure of a query or of a command, each crosses a
wire as its tag and its fields, and is read back as an instance of its class, with its message.
`Call.Error` and `Transport.Error` are Schemas too, of the types of the same name.

- **What a node sent is written as JSON:** the `data` of an `RpcError`, the `value` of a
  `CodecError`.
- **The `cause` of a `TransportError` is never written.** It is the HTTP client's own error,
  which holds the URL. The cause of a `CodecError` is written as its name and its message, and
  that of a `SignerError` as its own class.
- **A message holds no secret when the URL is `Redacted`.** A server whose failures cross a
  wire reads its URL with `Config.Redacted`.

`InvalidAddressError` and `InvalidHexError` are not Schemas: they are what parsing a person's
input fails with, and a program that only parses ships nothing of Schema.

The one function that throws is
[`Address.makeUnsafe`](https://ethect.dev/reference/primitives/address/#makeunsafe): it checks an address you
wrote in your source, when the file loads, so a typo stops the program before it runs anything.

## The node, not the contract

`RpcError` and `TransportError` are about the node or the wallet, whatever you asked. Each has
a `reason` too: `Effect.catchReason("TransportError", "Unreachable", handler)` handles a node
that is not there. Three rules cover most cases.

```ts
import { Effect, Schedule } from "effect";
import type { Address } from "@ethect/core";
import { ownerOf } from "./nft";

const patient = (nft: Address.Address, tokenId: bigint) =>
  ownerOf(nft, tokenId).pipe(
    // A read can be repeated: it changes nothing.
    Effect.retry({
      while: (error) => error._tag === "TransportError",
      schedule: Schedule.exponential("250 millis"),
      times: 4,
    }),
    // No transport gives up by itself: the limit is yours.
    Effect.timeout("10 seconds"),
  );
```

- **Retry a read, not a send.** When no answer comes back, the node may still have taken the
  transaction. A second `Tx.send` signs a second transaction.
- **Nothing times out by itself.** `Effect.timeout` interrupts the call: over HTTP the request
  is aborted.
- **Not found is not a failure.** A block or a receipt the node does not have is `null`, and
  an ENS name with no address is an empty `Option`.

> **Caution: A reverted transaction, in the JSON-RPC layer**
>
> `Tx.send` and `Tx.wait` fail with `TxReverted` when a transaction reverts. The raw methods do
> not: [`Eth.getTransactionReceipt`](https://ethect.dev/rpc/eth/get-transaction-receipt/) succeeds with a receipt
> whose `status` is `"reverted"`.

## Under the hood

A custom error is the revert data of a call: four bytes that name the error, then its fields.

**a read**

- **your node** `eth_call`: the node answers with an error that carries the revert data
- **your program**: the first four bytes are compared with the errors of the function
- **your program**: a match: an instance of your error
- **your program**: `Error(string)`: `RevertReason`
- **your program**: `Panic(uint256)`: `RevertPanic`
- **your program**: anything else, none: `RevertUnknown`

**a send, with a key**

- **your node** `eth_estimateGas`: or `eth_simulateV1` for several calls: finds the revert
- **your program**: `TxReverted`, with the reason read the same way. Nothing is sent

**a send, with a wallet**

- **the wallet**: the wallet sends. The receipt says "reverted", and not why
- **your node** `eth_call`: the call is run again, at the block before its own
- **your program**: `TxReverted`, with the reason

- [`Err.decode`](https://ethect.dev/reference/err/decode/) reads revert data you got another way.
- [`RpcError`](https://ethect.dev/reference/errors/rpc-error/#reverts) says how each client reports a revert.
- [`Tx.wait`](https://ethect.dev/reference/tx/wait/#what-a-revert-may-be) takes the `errors` a revert may be,
  for a transaction you did not send through `Tx.send`.
