Skip to content

Effect essentials

ethect is built on Effect. You need five ideas from it, and each has a counterpart in the async code you already write. The example reads a balance, sends a transfer and handles one failure: the five are numbered in it.

pay.ts
import { Config, Effect, Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { Address, Erc20, Signer, Transport, Tx } from "@ethect/core";
const token = Erc20.at(Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"));
const TO = Address.makeUnsafe("0x70997970C51812dc3A010C7d01b50e0d17dc79C8");
// 1. A description: calling `pay` sends nothing.
const pay = (amount: bigint) =>
Effect.gen(function* () {
// 2. `yield*` is `await`: a read, then a send.
const balance = yield* token.balanceOf(yield* Signer.address);
const receipt = yield* Tx.send(token.transfer(TO, amount));
return `Sent in block ${receipt.blockNumber}. You had ${balance}`;
}).pipe(
// 3. A failure is a value, caught by its tag.
Effect.catchTag("TxReverted", () => Effect.succeed("The token refused the transfer")),
);
// 4. What the program needs: a node, and someone who signs.
const Script = Layer.unwrap(
Effect.gen(function* () {
const url = yield* Config.Redacted("RPC_URL");
const key = yield* Config.Redacted("PRIVATE_KEY");
return Layer.merge(Signer.privateKey(key), Transport.http(url));
}),
).pipe(Layer.provide(FetchHttpClient.layer));
// 5. It runs here, once, and gives a `Promise`.
const message = await pay(1_000_000n).pipe(Effect.provide(Script), Effect.runPromise);
With promises With Effect
1 the call starts when you make it the call starts when you run the program
2 async function, await Effect.gen(function* () { … }), yield*
3 try { … } catch (error) { … } Effect.catchTag("TxReverted", (error) => …)
4 a client object passed around a node and a signer, provided once with Effect.provide
5 the promise is already running Effect.runPromise, once, where the program ends

A call to a contract builds a value that describes the read. Nothing is asked. Effect.gen is the async function of Effect, and yield* is its await: it runs a step and gives its result.

import { Effect } from "effect";
import { Erc20, type Address } from "@ethect/core";
const richer = (token: Address.Address, a: Address.Address, b: Address.Address) => {
// A description of a read: it can run once, twice, or never.
const read = Erc20.at(token).balanceOf(a);
return Effect.gen(function* () {
// `first` is a bigint, and not an Effect. The steps run in order.
const first = yield* read;
const second = yield* Erc20.at(token).balanceOf(b);
return first > second ? a : b;
});
};
  • A Promise is a call already under way. An Effect is the call itself, which is why it can be retried, timed out or cancelled.
  • Effect.all([a, b], { concurrency: "unbounded" }) is Promise.all. Reads started together leave as one request: see Read many things at once.
  • A Stream is to many values what an Effect is to one. Events are streams.

An Effect has three type parameters: what it succeeds with, what it can fail with, and what it needs. A failure is a value with a _tag. Handling one removes it from the type, so the compiler tells you what is left.

import { Effect } from "effect";
import { Erc20, Tx, type Address } from "@ethect/core";
const pay = (token: Address.Address, to: Address.Address, amount: bigint) =>
Tx.send(Erc20.at(token).transfer(to, amount)).pipe(
Effect.map((receipt) => `Sent in block ${receipt.blockNumber}`),
// one failure, by its tag
Effect.catchTag("TxReverted", () => Effect.succeed("The token refused the transfer")),
// several at once
Effect.catchTags({
Rejected: () => Effect.succeed("You refused in the wallet"),
TransportError: () => Effect.succeed("The node did not answer"),
}),
);
// Effect<string, TxDropped | TxUnsupported | …, Signer | Transport>
  • .pipe(a, b, c) applies a, then b, then c to the value on its left.
  • A failure nobody handled rejects the promise of Effect.runPromise with the error value itself.
  • Every failure of the library, and the custom errors of a contract, are in Errors.

The third type parameter is what a program needs: a Transport to read, and a Signer as well to send. Neither is an argument. Effect.provide gives them once, where the program runs.

import { Effect, Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { Address, Erc20, Transport, Tx } from "@ethect/core";
const token = Erc20.at(Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"));
const TO = Address.makeUnsafe("0x70997970C51812dc3A010C7d01b50e0d17dc79C8");
const read = token.balanceOf(TO); // Effect<bigint, …, Transport>
const send = Tx.send(token.transfer(TO, 1n)); // Effect<Receipt, …, Signer | Transport>
// A layer builds a service. This one builds the `Transport`, and is given the `fetch` it uses.
const Node = Transport.http("https://ethereum-rpc.publicnode.com").pipe(
Layer.provide(FetchHttpClient.layer),
);
const balance = await read.pipe(Effect.provide(Node), Effect.runPromise);
// @ts-expect-error a send needs a Signer too: with a node alone it does not compile
send.pipe(Effect.provide(Node), Effect.runPromise);
  • The program names no URL and no key. The same program runs over HTTP, a WebSocket or a wallet: see Transports.
  • Layer.unwrap, in pay.ts, is a layer built by an effect. There the effect reads two secrets from the environment with Config.Redacted, so neither is ever a plain string.
  • Layer.merge(a, b) is both layers, and Layer.provide gives a layer what it needs.

Effect.runPromise turns a program that needs nothing more into a Promise. Call it once, where your code meets the outside.

Your code is It runs
a script with Effect.runPromise, once, at the end of the file
an app that runs effects from event handlers on a ManagedRuntime built once: see the setup of the wallet picker
a server with Effect.runPromise in each handler: see Render on the server
a test with it.effect of @effect/vitest: see Testing

A layer is built where it is provided. Provide the transport once, around the whole program: two runs that each provide it build two connections.

Effect sends nothing by itself. The requests of pay.ts are those of the two lines that reach a node.

  1. your programpay(1_000_000n): nothing, a description
  2. your programEffect.provide(Script): nothing, the layers are built when the program runs
  3. your programEffect.runPromise: the program starts
  4. your programSigner.address: nothing, the address is computed from the key
  5. your nodeeth_calltoken.balanceOf(me)
  6. your nodeTx.send(token.transfer(…)): the fees
  7. your nodeeth_estimateGas
  8. your nodeeth_sendRawTransaction
  9. your nodeeth_getTransactionReceiptasked firstthen at each block until it is mined
  10. your programEffect.catchTag: nothing, it runs only when the send has failed

A transfer the token refuses fails while its gas is estimated: nothing was sent, and the program gives its message.