Skip to content

Errors

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.

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.

.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("Rejected", handler) one failure, by its tag
Effect.catchTags({ Rejected, 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
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("Rejected", () => 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.

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.

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.
_tag From Means
the name of a custom error a read The contract reverted with an error you declared
RevertReason a read It reverted with a message: require(…, "paused")
RevertPanic a read An assertion, an overflow, a division by zero. code says which
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
Rejected 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
UnknownChain Transport.on, 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
TransportError the same No answer came back. reason: Unreachable, HttpStatus, ConnectionLost…
CodecError a method of the JSON-RPC layer An answer does not have the shape the method promises. value holds it as it came
EnsError Ens 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 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 has every field of the five failures of a send.

The one function that throws is 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.

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.

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.

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

  1. a read

    1. your nodeeth_callthe node answers with an error that carries the revert data
    2. your programthe first four bytes are compared with the errors of the function
    3. your programa match: an instance of your error
    4. your programError(string): RevertReason
    5. your programPanic(uint256): RevertPanic
    6. your programanything else, none: RevertUnknown
  2. a send, with a key

    1. your nodeeth_estimateGasor eth_simulateV1 for several calls: finds the revert
    2. your programTxReverted, with the reason read the same way. Nothing is sent
  3. a send, with a wallet

    1. the walletthe wallet sends. The receipt says “reverted”, and not why
    2. your nodeeth_callthe call is run again, at the block before its own
    3. your programTxReverted, with the reason
  • Err.decode reads revert data you got another way.
  • RpcError says how each client reports a revert.
  • Tx.wait takes the errors a revert may be, for a transaction you did not send through Tx.send.