# Call.all

Reads several calls together, in one request and at one block. A tuple of calls gives a tuple,
a record a record, an array an array.

## Usage

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

const USDC = Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
const USER = Address.makeUnsafe("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266");

const program = Effect.gen(function* () {
  // one eth_call: both are read at the same block
  return yield* Call.all({
    symbol: Erc20.at(USDC).symbol(),
    balance: Erc20.at(USDC).balanceOf(USER),
  });
});

const token = await program.pipe(
  Effect.provide(Transport.http("https://ethereum-rpc.publicnode.com")),
  Effect.provide(FetchHttpClient.layer),
  Effect.runPromise,
); // { symbol: "USDC", balance: 0n }
```

The examples below leave the transport out.

### A tuple

A tuple of calls gives the tuple of what they return, each with its own type.

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

const read = (token: Address.Address, user: Address.Address) =>
  Call.all([Erc20.at(token).symbol(), Erc20.at(token).balanceOf(user)]);
// Effect<readonly [string, bigint], …>

const shown = (token: Address.Address, user: Address.Address) =>
  Effect.map(read(token, user), ([name, balance]) => `${balance} ${name}`);
```

### An array

Any number of calls built at run time: a portfolio, the positions of a list of markets.

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

const balances = (tokens: ReadonlyArray<Address.Address>, user: Address.Address) =>
  Call.all(tokens.map((token) => Erc20.at(token).balanceOf(user)));
// Effect<ReadonlyArray<bigint>, …>
```

### Each call with its own outcome

By default the first call that fails fails the whole. With `mode: "result"` each call has a
`Result` of its own, and a call that reverts fails nothing.

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

const owners = (nft: Address.Address, ids: ReadonlyArray<bigint>) =>
  Call.all(
    ids.map((id) => Erc721.at(nft).ownerOf(id)),
    { mode: "result" },
  ).pipe(
    // a token that does not exist has no owner: its call reverted, the others did not
    Effect.map((outcomes) => outcomes.map((outcome) => Result.getOrUndefined(outcome))),
  );
```

### With the state of the chain

The [state of the chain](https://ethect.dev/reference/call/state/) is a call like any other. Read here, the
block number comes from the `eth_call` that reads the balances: it is the number of their
block, and there is no request before it.

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

const position = (token: Address.Address, user: Address.Address) =>
  Call.all({
    block: Call.blockNumber,
    ether: Call.balance(user),
    tokens: Erc20.at(token).balanceOf(user),
  });
```

### At a block

The options are those of [`Call.read`](https://ethect.dev/reference/call/read/), applied to every call.

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

const settled = (token: Address.Address, user: Address.Address) =>
  Call.all([Erc20.at(token).symbol(), Erc20.at(token).balanceOf(user)], { block: "finalized" });
```

## Returns

`Effect<Results, Errors | Call.Error, Transport>`

| `calls` | Gives |
| --- | --- |
| a tuple `[a, b]` | `readonly [A, B]` |
| a record `{ a, b }` | `{ readonly a: A; readonly b: B }` |
| an array | `ReadonlyArray<A>` |

It fails with the errors every call declares, and with [`Call.Error`](https://ethect.dev/reference/call/#what-a-read-fails-with).

With `mode: "result"`: `Effect<Results, Transport.Error, Transport>`, where each value is a
`Result<A, E | Revert.Revert | AbiError>`: what the call returned, or why it alone failed.

## Parameters

### calls

- **Type:** a tuple, an array or a record of `Call.View<A, E>`

Calls of `view` or `pure` functions, as [`fn.at(address)(...args)`](https://ethect.dev/reference/fn/at/) builds
them, and the [state of the chain](https://ethect.dev/reference/call/state/). A call of a function that writes
is not read: it does not compile.

### options.mode (optional)

- **Type:** `"result"`

Gives each call its own outcome. Only a failure of the node fails the whole. It takes a tuple
or an array of calls.

### options.block (optional)

- **Type:** [`BlockId.BlockId`](https://ethect.dev/rpc/types/block-id/)
- **Default:** the block of [`Call.withBlock`](https://ethect.dev/reference/call/with-block/), else `"latest"`

The block every call is read at.

### options.from, options.gas, options.stateOverride, options.blockOverride (optional)

As for [`Call.read`](https://ethect.dev/reference/call/read/#optionsfrom-optional). Each of them makes every
call a request of its own: a multicall is one call, from one sender, over one state.

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

// two eth_calls, each from `user`
const asUser = (token: Address.Address, user: Address.Address) =>
  Call.all([Erc20.at(token).symbol(), Erc20.at(token).balanceOf(user)], { from: user });
```

### options.batch (optional)

- **Type:** `boolean`
- **Default:** `true`

`false` sends every call as a request of its own.

## Behavior

- **It does not wait.** Reads issued separately wait a few milliseconds for each other.
  `Call.all` is complete when it is called, so its request leaves at once.
- **One block.** Every call is answered from the same block, also when the calls take several
  requests: see [the limits](https://ethect.dev/reference/call/batching/#the-limits).
- **The same call twice is asked once.** Both places get the answer.
- **The first failure fails the whole**, in the order of the calls. A revert is decoded with
  the errors of the call that reverted.
- **In `mode: "result"`, a call that cannot be encoded fails alone too**, with an `AbiError`,
  and the others are read.
- **A failure of the node is not an outcome of a call.** It fails the whole in both modes.
- **Nothing is asked for no call.** `Call.all([])` gives `[]`.
- **A reader that does not batch gets the calls concurrently.** With
  [`Call.batching(false)`](https://ethect.dev/reference/call/batching/#turning-it-off), or a
  [reader](https://ethect.dev/reference/call/reader/) of your own that has no `callMany`, there is one request
  per call, and no common block unless you give one.

## Errors

| Error | When |
| --- | --- |
| an error a call declares | that call reverted with it |
| [`Revert.Revert`](https://ethect.dev/reference/revert/) | a call reverted with something else |
| [`AbiError`](https://ethect.dev/reference/errors/abi-error/) | an argument of a call does not encode, or an answer does not decode |
| [`RpcError`](https://ethect.dev/reference/errors/rpc-error/) | the node answered with an error that is not a revert |
| [`TransportError`](https://ethect.dev/reference/errors/transport-error/) | the node could not be reached, or did not answer |

In `mode: "result"` the first three are in the `Result` of their call, and the effect fails
with the last two only.

## Under the hood

One service is asked: [`Call.Reader`](https://ethect.dev/reference/call/reader/), which asks the `Transport`.
With the reader of this package, on a chain that has Multicall3:

**`Call.all([a, b, c])`**

- **encode**: each call: selector + arguments. No request
- **Call.Reader** `callMany([a, b, c])`: all of them, at once
- **your node** `eth_call({ to: Multicall3, data: aggregate3([a, b, c]) }, block)`
- **decode**: each answer as what its function returns, each revert with the errors of its function. No request

| Calls | Requests |
| --- | --- |
| two or more, same options | one `eth_call` of `aggregate3` |
| one | the `eth_call` of that call |
| with `from`, `gas`, an override or `batch: false` | one `eth_call` per call |
| with [the state of the chain](https://ethect.dev/reference/call/state/) among them | the same `eth_call`: each value is one more call of its `aggregate3` |
| with `Call.baseFee`, on a node that [cannot be paid inside a call](https://ethect.dev/reference/call/state/#basefee) | `eth_getBlockByNumber` first, then the `eth_call` at the hash of that block |
| with `Call.blockHash` of a block [the chain no longer holds](https://ethect.dev/reference/call/state/#blockhash) | the `eth_call`, then `eth_getBlockByNumber` for that hash |
| more than [the limits](https://ethect.dev/reference/call/batching/#the-limits) | `eth_blockNumber` first, then one `eth_call` per piece at that number |

[`Call.batching`](https://ethect.dev/reference/call/batching/#under-the-hood) has the requests of a chain
without Multicall3, and of a node that refuses state overrides.
