# Several chains

An app on two chains. One node per chain, each part of the program says which chain it is on, and a send is for that chain whatever chain the wallet is on.

An app on mainnet and on Base: a balance on each, and a transfer on Base. Each part of the
program says which chain it is on.

```ts title="app.ts"
import { Effect, Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { Address, type Eip1193, Erc20, Signer, Transport, Tx } from "@ethect/core";

// The wallet: `window.ethereum`, or the provider a wallet SDK returns.
declare const provider: Eip1193.Provider;

// A token has one address per chain.
const onMainnet = Erc20.at(Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"));
const onBase = Erc20.at(Address.makeUnsafe("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"));
const TO = Address.makeUnsafe("0x70997970C51812dc3A010C7d01b50e0d17dc79C8");

// One node per chain the app is on. The key is the chain id. The wallet signs.
const App = Layer.merge(
  Signer.wallet(provider),
  Transport.chains({
    1: Transport.http("https://ethereum-rpc.publicnode.com"),
    8453: Transport.http("https://mainnet.base.org"),
  }).pipe(Layer.provide(FetchHttpClient.layer)),
);

const program = Effect.gen(function* () {
  const me = yield* Signer.address;
  // A balance on each chain: each read says which chain it is on.
  const [mainnet, base] = yield* Effect.all(
    [onMainnet.balanceOf(me).pipe(Transport.on(1)), onBase.balanceOf(me).pipe(Transport.on(8453))],
    { concurrency: "unbounded" },
  );
  // A send on one: a transaction for Base, whatever chain the wallet is on.
  const receipt = yield* Tx.send(onBase.transfer(TO, 1_000_000n)).pipe(Transport.on(8453));
  return { mainnet, base, receipt };
});

const result = await program.pipe(Effect.provide(App), Effect.runPromise);
```

- **`Effect.all` with `concurrency: "unbounded"`** is `Promise.all`. `.pipe(f)` applies `f` to
  the value on its left.
- **`App`** is what the program runs with: the nodes it reads, and the wallet that signs.
- **`Erc20.at(address)` is an address, and no chain.** The definition is the same on both
  chains. What puts a read on a chain is `Transport.on`.

With viem you make one client per chain and pass the right one around. Here the chain is
said once, around a part of the program.

## One node per chain

`Transport.chains` takes one transport per chain, under its chain id. Any transport fits:
HTTP for one chain, a WebSocket for another.

An app on one chain provides one `Transport`. `Transport.chains` provides none: it provides
the chains, and a read that is on no chain has no node to go to.

```ts
import { Effect, Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { Transport } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const Chains = Transport.chains({
  1: Transport.http("https://ethereum-rpc.publicnode.com"),
  8453: Transport.http("https://mainnet.base.org"),
}).pipe(Layer.provide(FetchHttpClient.layer));

// @ts-expect-error the read does not say its chain: it still needs a Transport
Effect.runPromise(Eth.blockNumber().pipe(Effect.provide(Chains)));
```

**A program that does not say its chain does not compile.**

## Say the chain

`Transport.on(chainId)` puts a part of the program on a chain. Everything inside reads from
the node of that chain, and sends for that chain.

- **Put it around a whole part, not around each call.** A function that reads five things on
  Base takes one `Transport.on(8453)`, at the end.
- **The chain can come from anywhere**: a route, a form, the wallet. It is a number.
- **Each chain has its own blocks and its own nonces.** A key that signs on two chains has a
  counter on each.
- **Inside it, the node is on that chain.** The node you gave for 8453 is asked its chain id
  once. One that is on another chain fails with `TransportUnknownChain`, before anything is read.

**A contract carries no chain.** With one `Transport` and no `Transport.on`, an address is
read on whatever node the program is given, and nothing checks which. A program that must be
on one chain checks it itself, with an error of its own:

```ts title="only-on.ts"
import { Data, Effect } from "effect";
import { Call } from "@ethect/core";

class WrongChain extends Data.TaggedError("WrongChain")<{ expected: number; actual: number }> {}

/** Fails unless the node this runs on is on `expected`. Put it first in the program. */
export const onlyOn = (expected: number) =>
  Effect.flatMap(Call.chainId, (actual) =>
    actual === expected ? Effect.void : Effect.fail(new WrongChain({ expected, actual })),
  );
```

`Call.chainId` asks the node once and keeps the answer. Under `Transport.on` it asks nothing.

## The wallet is on a chain too

A send is for the chain of your program: Base above. The wallet may be on mainnet. Before
every signature the wallet is asked where it is, and `onWrongChain` says what happens when
the two differ.

| The wallet is | `"switch"`, the default | `"fail"` |
| --- | --- | --- |
| on the chain of the send | signs | signs |
| on another chain | is asked to switch, then signs | fails with `SignerError` `"ChainMismatch"`. It is not asked to switch |

```ts
import { Effect } from "effect";
import { type Call, type Eip1193, Signer, Transport, Tx } from "@ethect/core";

declare const provider: Eip1193.Provider;
const Strict = Signer.wallet(provider, { onWrongChain: "fail" });

/** Sends on Base, and never moves the wallet by itself. */
export const send = (call: Call.Call<unknown, unknown>) =>
  Tx.send(call).pipe(
    Effect.catchIf(
      (error) => error._tag === "SignerError" && error.reason === "ChainMismatch",
      () => Effect.succeed("Switch your wallet to Base" as const),
    ),
    Transport.on(8453),
    Effect.provide(Strict),
  );
```

- **Reads never depend on the wallet.** They go to your nodes, whatever chain the wallet is on.
- **A switch is a prompt.** The user can refuse it: the send fails with `SignerRejected`. A wallet
  that does not know the chain fails with `SignerError` `"UnknownChain"`.
- **In an app with a wallet picker**, [`Signer.connected`](https://ethect.dev/reference/signer/connected/) takes
  the same option.

## A chain you have no node for

A wallet can be on a chain your app does not support. `Transport.on` with a chain that
`Transport.chains` was not given fails with `TransportUnknownChain`, before anything is sent.

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

/** The height of the chain a wallet is on, or a message where the app has no node. */
export const heightOf = (chainId: number) =>
  Eth.blockNumber().pipe(
    Transport.on(chainId),
    Effect.map((height) => `block ${height}`),
    // No transport was given for chain 10: Transport.chains has 1, 8453
    Effect.catchTag("TransportUnknownChain", (error) => Effect.succeed(error.message)),
  );
```

Show the chains you support, and offer to switch:
[`Connection.switchChain`](https://ethect.dev/reference/connection/switch-chain/) asks the wallet.

## Under the hood

Each chain has its node, and the wallet is asked only to sign.

**`Transport.on(8453)`**

- **node of 8453** `eth_chainId`: the first time anything is on that chain. 0x2105: kept. Anything else: `TransportUnknownChain`
- **your program**: every other time: nothing is sent

**the two balances**

- **node of 1** `eth_call`: through the reader of that chain
- **node of 8453** `eth_call`

**`Tx.send(…).pipe(Transport.on(8453))`, with a wallet on mainnet**

- **the wallet** `eth_chainId`: 0x1: not the chain of the send
- **the wallet** `wallet_switchEthereumChain`: a prompt. With `"fail"`: `ChainMismatch`, no prompt
- **the wallet** `eth_sendTransaction`: the prompt to sign
- **node of 8453** `eth_getTransactionReceipt`: asked first, then at each block of Base, until it is in one

The transports and their failures are on
[`Transport.chains`](https://ethect.dev/reference/transport/chains/), and what a wallet answers to a switch on
[`Signer.wallet`](https://ethect.dev/reference/signer/wallet/#a-wallet-on-another-chain).
