# RpcError

The error a node or wallet answers a call with. It keeps the JSON-RPC `code`, `message` and
`data`, and classifies them into a `reason`.

```ts
import { Effect } from "effect";
import { Address } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const TO = Address.makeUnsafe("0x70997970C51812dc3A010C7d01b50e0d17dc79C8");

const sent = Eth.sendTransaction({ to: TO, value: 1n }).pipe(
  Effect.catchReason("RpcError", "UserRejectedRequest", () =>
    Effect.succeed(undefined),
  ),
);
// Effect<Hash | undefined, …>: undefined when the user refused
```

## Properties

| Property | Type | Holds |
| --- | --- | --- |
| `_tag` | `"RpcError"` | the tag `Effect.catchTag` matches |
| `code` | `number` | the JSON-RPC error code, as sent |
| `message` | `string` | the message, as sent |
| `data` | `unknown` (optional) | the `data` of the error object, as sent |
| `reason` | `RpcError.Reason` | the classification of the three above |

```ts
import { Effect } from "effect";
import { Eth } from "@ethect/core/rpc";

const logged = Eth.chainId().pipe(
  Effect.tapErrorTag("RpcError", (error) =>
    Effect.logWarning(`${error.reason._tag} (${error.code}): ${error.message}`),
  ),
);
```

## As a Schema

`RpcError.RpcError` is its own Schema. Declared in the failure of a query or of a command, it is
written as its tag and its fields, and read back as an `RpcError.RpcError`: its `reason` is
caught with `Effect.catchReason` on either side.

| The error | Written as |
| --- | --- |
| a node that rate-limits | `{ "_tag": "RpcError", "code": -32005, "message": "Too many requests", "data": { "retryAfter": "0x3c" }, "reason": { "_tag": "LimitExceeded" } }` |
| a revert with data | `{ "_tag": "RpcError", "code": 3, "message": "execution reverted", "data": "0xdeadbeef", "reason": { "_tag": "ExecutionReverted", "data": "0xdeadbeef" } }` |
| a revert the node gave no data for | `{ "_tag": "RpcError", "code": 3, "message": "execution reverted", "reason": { "_tag": "ExecutionReverted" } }` |

- **`data` is written as the JSON the node sent.** A provider in the page can give more than
  JSON holds: a `bigint` is written as hex, and an `Error` as its `name` and its `message`.
- **No data is no key.** A revert without data has no `data`, written or read, and reads back
  with `reason.data` `undefined`.
- **`message` and `data` are what the node said.** The package adds nothing to them. Over a
  [secret URL](https://ethect.dev/reference/transport/http/#url), the message is written without it.
- **`new` checks nothing.** With fields of their types, it never throws.

[`Transport.Error`](https://ethect.dev/reference/transport/#types) is the Schema of an `RpcError` or a
`TransportError`.

## Reasons

`reason` is a tagged value: match on `reason._tag`, or let `Effect.catchReason` do it.

| Reason | Code | Defined by | Means |
| --- | --- | --- | --- |
| `ExecutionReverted` | `3`, and [others](#reverts) | clients | The EVM reverted. Carries `data`. |
| `ParseError` | `-32700` | JSON-RPC 2.0 | The request was not valid JSON. |
| `InvalidRequest` | `-32600` | JSON-RPC 2.0 | The request was not a valid request object. |
| `MethodNotFound` | `-32601` | JSON-RPC 2.0 | The method does not exist or is not available. |
| `InvalidParams` | `-32602` | JSON-RPC 2.0 | The params are not valid for the method. |
| `InternalError` | `-32603` | JSON-RPC 2.0 | An internal error of the node or wallet. |
| `InvalidInput` | `-32000` | EIP-1474 | Missing or invalid input. Clients use it for many failures. |
| `ResourceNotFound` | `-32001` | EIP-1474 | The requested resource was not found. |
| `ResourceUnavailable` | `-32002` | EIP-1474 | The requested resource is not available. |
| `TransactionRejected` | `-32003` | EIP-1474 | The transaction could not be created. |
| `MethodNotSupported` | `-32004` | EIP-1474 | The method is not implemented. |
| `LimitExceeded` | `-32005` | EIP-1474 | The request exceeds a limit, such as a rate limit. |
| `JsonRpcVersionNotSupported` | `-32006` | EIP-1474 | The version of JSON-RPC is not supported. |
| `ExecutionError` | `-32015` | `eth_simulateV1` | The EVM failed while executing, other than by a revert. |
| `ExecutionTimeout` | `-32016` | `eth_simulateV1` | The execution took too long. |
| `NonceTooLow` | `-38010` | `eth_simulateV1` | The nonce of a transaction is too low. |
| `NonceTooHigh` | `-38011` | `eth_simulateV1` | The nonce of a transaction is too high. |
| `BaseFeeTooLow` | `-38012` | `eth_simulateV1` | The fee of a transaction is below the base fee of its block. |
| `IntrinsicGasTooLow` | `-38013` | `eth_simulateV1` | The gas of a transaction does not cover its intrinsic cost. |
| `InsufficientFunds` | `-38014` | `eth_simulateV1` | The sender cannot pay for the gas and the value. |
| `BlockGasLimitExceeded` | `-38015` | `eth_simulateV1` | The transactions of a block use more gas than its limit. |
| `BlockNumberNotIncreasing` | `-38020` | `eth_simulateV1` | A simulated block has a number that does not follow the one before. |
| `BlockTimestampNotIncreasing` | `-38021` | `eth_simulateV1` | A simulated block has a timestamp earlier than the one before. |
| `MovePrecompileToSelf` | `-38022` | `eth_simulateV1` | A state override moves a precompile to its own address. |
| `SenderNotEoa` | `-38024` | `eth_simulateV1` | The sender of a transaction is a contract. |
| `MaxInitCodeSizeExceeded` | `-38025` | `eth_simulateV1` | The creation code of a transaction is too large. |
| `ClientLimitExceeded` | `-38026` | `eth_simulateV1` | A limit the client sets was reached. |
| `TransactionNotMinedInTime` | `4` | EIP-7966 | The transaction was not mined within the timeout. `data` is its hash. |
| `TransactionNotReady` | `5` | EIP-7966 | The transaction cannot be mined yet. `data` is its hash. |
| `NonceGap` | `6` | EIP-7966 | The nonce of the transaction leaves a gap. `data` is the nonce the node expected. |
| `UserRejectedRequest` | `4001` | EIP-1193 | The user rejected the request. |
| `Unauthorized` | `4100` | EIP-1193 | The user has not authorized the method or the account. |
| `UnsupportedMethod` | `4200` | EIP-1193 | The provider does not support the method. |
| `Disconnected` | `4900` | EIP-1193 | The provider is disconnected from all chains. |
| `ChainDisconnected` | `4901` | EIP-1193 | The provider is not connected to the requested chain. |
| `UnrecognizedChain` | `4902` | wallets | The wallet does not know the chain it was asked to switch to. |
| `PrunedHistoryUnavailable` | `4444` | EIP-4444 | The node has pruned the history asked for. |
| `UnsupportedNonOptionalCapability` | `5700` | EIP-5792 | The wallet lacks a capability that was not marked optional. |
| `UnsupportedChainId` | `5710` | EIP-5792 | The wallet does not support the chain of the batch. |
| `DuplicateId` | `5720` | EIP-5792 | A batch with this id exists already. |
| `UnknownBundleId` | `5730` | EIP-5792 | No batch has this id. |
| `BundleTooLarge` | `5740` | EIP-5792 | The batch has more calls than the wallet takes. |
| `AtomicReadyWalletRejectedUpgrade` | `5750` | EIP-5792 | The wallet could run the batch atomically after an upgrade, which the user rejected. |
| `AtomicityNotSupported` | `5760` | EIP-5792 | The wallet cannot run the batch atomically. |
| `Unknown` | any other | | A code no standard defines. Read `code` and `message`. |

Only `ExecutionReverted` carries a field. Every other reason is its tag alone: what a node
attached is in `error.data`, typed `unknown`.

The `eth_simulateV1` codes are those of the execution API specification, which defines them
for [`Eth.simulateV1`](https://ethect.dev/rpc/eth/simulate-v1/). The EIP-7966 ones are answered by
[`Eth.sendRawTransactionSync`](https://ethect.dev/rpc/eth/send-raw-transaction-sync/).

```ts
import { Effect } from "effect";
import { Eth } from "@ethect/core/rpc";

const head = Eth.blockNumber().pipe(
  Effect.map((number) => `block ${number}`),
  Effect.catchReasons("RpcError", {
    MethodNotFound: () => Effect.succeed("not served by this node"),
    LimitExceeded: () => Effect.succeed("rate limited"),
  }),
);
```

## Reverts

A revert is the one failure whose shape differs from client to client. The classification
reads all of these as `ExecutionReverted`:

| The error object has | Sent by |
| --- | --- |
| code `3` | geth, anvil, reth |
| code `-32000` or `-32015` and a message containing the word `reverted` | clients that report a revert as a server error. Rootstock answers `-32015` with `transaction reverted`. |
| code `-32015` and `data` starting with `Reverted ` | Nethermind, OpenEthereum |
| code `-32603` and, as `data`, an error object that is one of the above | a wallet relaying its node's error |

`reason.data` is the revert data when the node returned it, and `undefined` otherwise. It is
found as `data` itself, with or without the `Reverted ` prefix, or one level down as
`data.data`.

```ts
import { Effect } from "effect";
import { Address } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const TO = Address.makeUnsafe("0x5FbDB2315678afecb367f032d93F642f64180aa3");

const outcome = Eth.call({ to: TO }, "latest").pipe(
  Effect.catchReason("RpcError", "ExecutionReverted", (reason) =>
    Effect.succeed(`reverted with ${reason.data}`), // "reverted with 0xdeadbeef"
  ),
);
```

- **The data is hex.** [`Err.decode`](https://ethect.dev/reference/err/decode/) reads it as a custom error, a
  message or a panic. A read through a contract does it for you: it fails with the error
  itself.
- **`code` and `message` stay as sent.** For an error a wallet relayed, they are the outer
  ones (`-32603`), while `reason` is the inner revert.
- **A reverted transaction is not an error of this kind.** A transaction that reverts once
  mined has a receipt with `status: "reverted"`. Only `Eth.call`, `Eth.estimateGas` and the
  other methods that execute before answering fail with `ExecutionReverted`.
  [`Tx.wait`](https://ethect.dev/reference/tx/wait/) turns such a receipt into a failure, `TxReverted`.
- **Not every `-32000` is a revert.** `nonce too low` is `InvalidInput`.
- **Not every `-32015` is a revert.** Without the word `reverted` in its message, or `data`
  that starts with `Reverted `, it is `ExecutionError`.

## Functions

### fromWire

Classifies a JSON-RPC error object into an `RpcError`.

```ts
import { RpcError } from "@ethect/core";

const error = RpcError.fromWire({ code: 4001, message: "User rejected the request." });

error.reason; // { _tag: "UserRejectedRequest" }
error.code; // 4001
```

- **Parameters:** `error`, an object with a numeric `code`, a string `message` and an optional
  `data`.
- **Returns:** `RpcError.RpcError`

A [custom transport](https://ethect.dev/guides/custom-transports/) calls it to turn the error of a response into
the failure of the call.

- **A relayed error is looked into one level.** When the code is `-32603` and `data` is itself
  an error object, `reason` classifies that inner error. An error nested deeper is not
  followed: the reason is then `InternalError`.
- **An `Error` instance works.** A wallet often rejects with an `Error` that has a `code`:
  its `message` is kept.
- **A simulated call's error works too.** `RpcError.fromWire(call.error)` classifies the
  `error` of a [`Simulate.Call`](https://ethect.dev/rpc/types/simulate/#call-fields).

### Wire

- **Type:** an Effect `Schema`

The schema of the error object of a JSON-RPC response, which is also what an EIP-1193 provider
rejects with: `code`, `message` and an optional `data`.

```ts
import { Schema } from "effect";
import { RpcError } from "@ethect/core";

const isErrorObject = Schema.is(RpcError.Wire);

isErrorObject({ code: -32601, message: "Method not found" }); // true
isErrorObject(new Error("socket hang up")); // false: no numeric code
```

## Types

| Type | Is |
| --- | --- |
| `RpcError.RpcError` | the error class |
| `RpcError.Reason` | the union of the reasons above |
