# Read many things at once

Twenty token balances and the number of their block, in one eth_call. What merges into one request, what does not, and what a read sees inside a multicall.

Read many values in one request, all at the same block. The example is a portfolio: the
balances of twenty tokens, with the number of the block they are read at.

```ts title="portfolio.ts"
import { Effect } from "effect";
import { FetchHttpClient } from "effect/http";
import { Address, Call, Erc20, Transport } from "@ethect/core";

const portfolio = (tokens: ReadonlyArray<Address.Address>, user: Address.Address) =>
  Effect.gen(function* () {
    // One list: the number of the block, then one read per token.
    const [block, ...balances] = yield* Call.all([
      Call.blockNumber,
      ...tokens.map((token) => Erc20.at(token).balanceOf(user)),
    ]);
    return { block, balances };
  });

const USER = Address.makeUnsafe("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");
const TOKENS = [
  "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC
  "0xdAC17F958D2ee523a2206206994597C13D831ec7", // USDT
  "0x6B175474E89094C44Da98b954EedeAC495271d0F", // DAI
  // … and seventeen more
].map(Address.makeUnsafe);

const result = await portfolio(TOKENS, USER).pipe(
  Effect.provide(Transport.http("https://ethereum-rpc.publicnode.com")),
  Effect.provide(FetchHttpClient.layer),
  Effect.runPromise,
); // { block: 26534066n, balances: [42191050n, 337290488n, 14372082162212001768n] }
```

`Effect.gen` is an `async` function and `yield*` its `await`: see
[Effect essentials](https://ethect.dev/guides/effect-essentials/). The node is given on the last lines, and a
read needs nothing else.

## One request, one block

[`Call.all`](https://ethect.dev/reference/call/all/) takes calls and reads them together. Every answer comes
from the same block, so the balances are consistent with each other.

Reads issued together are merged into one eth_call to Multicall3. The node runs them at one block and answers once, and each read gets its own result back.

| You give | You get |
| --- | --- |
| a tuple `[a, b]` | a tuple, each value with its own type |
| a record `{ a, b }` | a record with the same keys |
| an array built at run time | an array |

`Call.blockNumber` is a call like any other, and so are the other
[values of the chain](https://ethect.dev/reference/call/state/): `Call.timestamp`, `Call.balance(account)`,
`Call.chainId`. Read beside the balances, the number is that of the block the balances are
read at.

```ts
import { Call, Erc20, type Address } from "@ethect/core";

const position = (token: Address.Address, user: Address.Address) =>
  Call.all({
    symbol: Erc20.at(token).symbol(), // string
    tokens: Erc20.at(token).balanceOf(user), // bigint
    ether: Call.balance(user), // bigint, in wei
    time: Call.timestamp, // bigint, in seconds
  });
```

## Reads you did not group

You do not have to gather the calls yourself. Reads issued at the same moment wait up to 5 ms
for each other, then leave as one request. A component, a loader or a function that knows no
other can each read alone.

```ts
import { Effect } from "effect";
import { Erc20, type Address } from "@ethect/core";

// One request: the twenty reads are issued together.
const together = (tokens: ReadonlyArray<Address.Address>, user: Address.Address) =>
  Effect.forEach(tokens, (token) => Erc20.at(token).balanceOf(user), {
    concurrency: "unbounded",
  });

// Two requests: the second read is issued when the first has answered.
const inARow = (a: Address.Address, b: Address.Address, user: Address.Address) =>
  Effect.gen(function* () {
    const first = yield* Erc20.at(a).balanceOf(user);
    const second = yield* Erc20.at(b).balanceOf(user);
    return [first, second];
  });
```

Without `concurrency`, `Effect.forEach` and `Effect.all` run one step after the other, like
`inARow`. `Call.all` does not wait at all: it is complete when you call it.

## What merges, and what does not

| A read | Goes |
| --- | --- |
| in a `Call.all` | with the others of that `Call.all`, at once |
| issued together with others, on the same node and block | with them, after 5 ms at most |
| after a `yield*` | in a request of its own: the one before has left |
| with `from`, `gas` or a state override | alone |
| with `batch: false` | alone |
| at another block, or on another chain | with the reads of that block and that chain |
| `Call.blockNumber`, `Call.baseFee` and the other values of the chain | with the others, inside their `eth_call`: they are of its block |
| twice the same call | once: both places get the answer |

The merged request is one `eth_call` to Multicall3. So inside it, the contract you read sees
Multicall3 as `msg.sender`, and not you. A view that depends on who asks takes `from`:

```ts
import { Abi, Call, Erc4626, type Address } from "@ethect/core";

const Gated = Abi.parse(["function myLimit() view returns (uint256)"]);

const limits = (vault: Address.Address, gated: Address.Address, user: Address.Address) => [
  // takes the account as an argument: it merges
  Erc4626.at(vault).maxWithdraw(user),
  // reads `msg.sender`: sent alone, as `user`
  Call.read(Gated.at(gated).myLimit(), { from: user }),
];
```

[`Call.batching`](https://ethect.dev/reference/call/batching/) has the full table, the size limits, and how to
turn merging off.

## When one read fails

By default the first read that fails fails the whole `Call.all`. With `mode: "result"`, each
read has its own outcome, and one that reverts fails nothing else.

```ts
import { Effect, Result } from "effect";
import { Call, Erc20, type Address } from "@ethect/core";

// A list anyone can add to: one address may be no token at all.
const listed = (tokens: ReadonlyArray<Address.Address>, user: Address.Address) =>
  Call.all(
    tokens.map((token) => Erc20.at(token).balanceOf(user)),
    { mode: "result" },
  ).pipe(
    // `undefined` for the reads that failed, a balance for the others
    Effect.map((outcomes) => outcomes.map((outcome) => Result.getOrUndefined(outcome))),
  );
```

A `Result` is a success or a failure as a value: `Result.isSuccess(outcome)` tells which.
Reads that merged on their own already behave this way: each fails alone.

## Under the hood

The portfolio is one request, for twenty tokens as for five hundred.

**`Call.all([Call.blockNumber, balanceOf × 20])`**

- **your node** `eth_call({ to: Multicall3, data: aggregate3([getBlockNumber(), balanceOf × 20]) }, "latest")`

- **The block number is read inside the call**, so it is the number of the block the balances
  are of. Nothing is asked before, and one question beside the first request of a node:
  whether its chain is [ArbOS](https://ethect.dev/reference/call/state/#blocknumber).
- **A chain without Multicall3 needs nothing from you.** Its code is placed at its address for
  the length of the request, with a state override.
- **More than a thousand calls are cut in pieces**, each one `eth_call`, all at one block.

The requests of every case are on [`Call.all`](https://ethect.dev/reference/call/all/#under-the-hood) and
[`Call.batching`](https://ethect.dev/reference/call/batching/#under-the-hood).
