# Effect essentials

The five things to know about Effect to use ethect. A program is a description, yield* reads a step, a failure is a value in the type, what a program needs is provided, and it runs once at the edge.

ethect is built on [Effect](https://effect.website). 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.

```ts title="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 program is a description

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.

```ts
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](https://ethect.dev/guides/reading/).
- **A `Stream` is to many values what an `Effect` is to one.**
  [Events](https://ethect.dev/guides/events/#live) are streams.

## A failure is in the type

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.

```ts
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({
      SignerRejected: () => 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](https://ethect.dev/guides/errors/).

## What it needs is provided

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.

```ts
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](https://ethect.dev/guides/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.

## Run it at the edge

`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](https://ethect.dev/guides/wallet-selection/#the-setup) |
| a server | with `Effect.runPromise` in each handler: see [Render on the server](https://ethect.dev/guides/ssr/#reading-on-the-server) |
| a test | with `it.effect` of `@effect/vitest`: see [Testing](https://ethect.dev/guides/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.

## Under the hood

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

- **your program**: `pay(1_000_000n)`: nothing, a description
- **your program**: `Effect.provide(Script)`: nothing, the layers are built when the program runs
- **your program**: `Effect.runPromise`: the program starts
- **your program**: `Signer.address`: nothing, the address is computed from the key
- **your node** `eth_call`: `token.balanceOf(me)`
- **your node**: `Tx.send(token.transfer(…))`: the fees
- **your node** `eth_estimateGas`
- **your node** `eth_sendRawTransaction`
- **your node** `eth_getTransactionReceipt`: asked first, then at each block until it is mined
- **your program**: `Effect.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.

- [Read and write a contract](https://ethect.dev/guides/contracts/): the same program, step by step.
- [Errors](https://ethect.dev/guides/errors/): every failure, and how to catch one by its tag or by its reason.
- [Transports](https://ethect.dev/guides/transports/): which layer to provide, and where.
