# Call.batching

Reads are merged into multicalls without asking. `Call.batching` is the layer that tunes how,
or turns it off with `false`.

## Usage

Fifty balances, each read on its own, are one request. No layer is needed for that: it is what
[`Call.Reader`](https://ethect.dev/reference/call/reader/) does when you provide nothing.

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

const balances = (tokens: ReadonlyArray<Address.Address>, user: Address.Address) =>
  // each read is issued on its own: a component, a loader, a function that knows no other.
  // They wait up to 5 ms for each other, then leave as one eth_call
  Effect.forEach(tokens, (token) => Erc20.at(token).balanceOf(user), {
    concurrency: "unbounded",
  });

const read = (tokens: ReadonlyArray<Address.Address>, user: Address.Address) =>
  balances(tokens, user).pipe(
    // optional: a longer wait, and smaller requests
    Effect.provide(Call.batching({ window: "20 millis", maxCalls: 200 })),
    Effect.provide(Transport.http("https://ethereum-rpc.publicnode.com")),
    Effect.provide(FetchHttpClient.layer),
  );
```

### Turning it off

`false` puts [`Call.direct`](https://ethect.dev/reference/call/reader/#direct) in place: one request per read.

```ts
import { Effect } from "effect";
import { Call } from "@ethect/core";

const unbatched = <A, E, R>(program: Effect.Effect<A, E, R>) =>
  Effect.provide(program, Call.batching(false));
```

One read out of the groups, the others in: [`batch: false`](https://ethect.dev/reference/call/read/#optionsbatch-optional)
on that read.

### On a chain without Multicall3

Nothing to do. Where Multicall3 does not answer, its code is placed at its address for the
length of the request, and the node is remembered: see [the three tiers](#the-three-tiers).
When you know beforehand, `"deployless"` skips the first try.

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

// never looks for a deployed Multicall3: always places it
const placed = Call.batching({ multicall: "deployless" });

// a chain whose Multicall3 is at another address
const elsewhere = (aggregator: Address.Address) =>
  Call.batching({ multicall: aggregator });
```

### In a test

Under a test clock, time does not pass on its own, so a read would wait for its window for
ever. A window of no length waits for no clock: the reads issued together still leave together.

```ts
import { Effect } from "effect";
import { Call } from "@ethect/core";

const inTest = <A, E, R>(program: Effect.Effect<A, E, R>) =>
  Effect.provide(program, Call.batching({ window: 0 }));
```

[`Call.all`](https://ethect.dev/reference/call/all/) never waits, with any window.

## Returns

`Layer.Layer<never>`

A layer that sets [`Call.Reader`](https://ethect.dev/reference/call/reader/). It needs nothing, and a program
reads with or without it.

## Parameters

### options

- **Type:** `Call.Batching | false`

`false` turns batching off. An object tunes it: every field is optional, and `{}` is the
default reader with a memory of its own.

### options.window (optional)

- **Type:** `Duration.Input`
- **Default:** `"5 millis"`

How long a group waits for more reads, from the first one. `0` waits for nothing but the reads
issued in the same tick.

### options.maxCalls (optional)

- **Type:** `number`
- **Default:** `1000`

The most calls one `eth_call` carries.

### options.maxBytes (optional)

- **Type:** `number`
- **Default:** `262144` (256 KiB)

The most calldata one `eth_call` carries, as `aggregate3` encodes its calls: a call whose own
calldata is 36 bytes takes 224. A thousand such calls fit.

### options.multicall (optional)

- **Type:** [`Address.Address`](https://ethect.dev/reference/primitives/address/) `| "deployless"`
- **Default:** Multicall3 at `0xcA11bde05977b3631167028862bE2a173976CA11`

The aggregator to call. `"deployless"` says there is none on the chain: its code is placed at
the usual address on every request, without trying first.

## What joins a group

A group is the reads of one transport at one block. One group is one `eth_call`.

| A read | Goes |
| --- | --- |
| with only an address and calldata | into the group of its transport and block |
| with `from`, `gas`, `stateOverride` or `blockOverride` | alone, at once |
| with `batch: false` | alone, at once |
| the same call as another of its group | with it: sent once, answered twice |
| at another block, or on another chain ([`Transport.on`](https://ethect.dev/reference/transport/chains/)) | into another group |
| [`Call.blockNumber` and its kind](https://ethect.dev/reference/call/state/) | into the group, as one more call of its `aggregate3` |
| alone in its group when the window closes | as the request it would be without batching |

- **Reads issued separately** wait for the window: they merge when they wait together. Two
  `yield*` in a row are two groups of one, so two requests.
- **[`Call.all`](https://ethect.dev/reference/call/all/)** is a group that is complete: it leaves at once.

## The limits

A group larger than `maxCalls` or `maxBytes` is cut in pieces, one `eth_call` each, sent
together. Every piece is read at the same block: when the block is a tag, its number is asked
first and the pieces run at that number. The pieces are tied by that number, not by a hash:
if the chain reorganises that block between two pieces, they read the two blocks that had
that number.

The defaults are far below what nodes take. Measured with calls of `balanceOf`:

| Node | 1,000 calls | 5,000 calls | 10,000 calls | 1 MiB of calldata |
| --- | --- | --- | --- | --- |
| anvil 1.9 | answered | refused: a request body over 2 MiB | refused | refused |
| Geth 1.17, mainnet | answered, 0.2 s | answered, 0.6 s | out of gas: 50 million per call | answered |
| reth 2.11, mainnet | answered, 0.2 s | answered, 0.5 s | request too large | answered |

A thousand calls are a request body of about 440 KiB.

## The three tiers

Tried in order, and remembered for each transport.

| Tier | When | The request |
| --- | --- | --- |
| 1 | by default | `eth_call` to Multicall3 |
| 2 | Multicall3 answered nothing: it is not deployed, or not yet at that block | the same `eth_call`, with a state override that puts Multicall3's code at its address |
| 3 | the node refuses state overrides, or does nothing of them | every read alone, through `Call.direct` |

- **Per block.** A chain that has Multicall3 did not have it before it was deployed. The
  highest block it did not answer at is remembered: a read at or below it starts at tier 2.
- **Per transport.** What is remembered is kept with the transport, for as long as it lives.
  Another transport to the same node learns again, with one request more.

## Behavior

- **A revert fails only its own read.** Every call of a multicall may fail. The read that
  reverted fails with its typed error, and the others are answered.
- **The sender is the aggregator.** Inside a multicall, `msg.sender` is Multicall3. A view
  that depends on who asks takes `from`, which sends it alone.
- **A piece that fails as a whole is halved**, and each half is tried, down to one call, which
  is sent alone. A gas cap, a response too large or a timeout fails fewer calls each time. At
  worst this is twice the requests of reading unbatched.
- **A node that is not reached is not asked again.** Every read of the piece fails with that
  one failure. So does a request the server refuses with a status of 401, 403 or 429.
- **One block, also when it goes wrong.** Halves, and the reads of tier 3, are read at one
  block number, asked first when the block is a tag. `"pending"` has no number: there, each
  request reads the pending block as it is.
- **One caller giving up cancels nothing.** A read that is interrupted before its group leaves
  is not asked for. After, the group goes on for the others.
- **The requests of a group that waited are spans with no parent.** They are no reader's own.
  The request of a `Call.all` is a child of its caller's span.
- **The state of the chain joins.** [`Call.blockNumber`, `Call.baseFee` and their
  kind](https://ethect.dev/reference/call/state/) are calls inside the `eth_call` of the group, most to
  Multicall3 itself. So they are of the block the other reads ran at, with nothing asked
  before and no block named.
- **A group that reads the base fee offers a fee.** A node runs a call that offers none with
  a base fee of zero. The `eth_call` has a `maxFeePerGas`, and a state override that gives
  its sender, the zero address, the balance to pay it. Its other reads see `tx.gasprice` as
  the base fee, and that balance at the zero address.

## Under the hood

The reader asks the `Transport` of whoever reads. With `calls` the reads of one group, and
`Multicall3` the aggregator's address:

**a group of one call**

- **your node**: the request of that call alone: see `Call.direct`

**tier 1**

- **your node** `eth_call({ to: Multicall3, data: aggregate3(calls) }, block)`: each call is `{ target, allowFailure: true, callData }`
  - `(success, returnData)` per call: its bytes, or its revert data
  - `"0x"`: no code there at that block. Remembered, then tier 2

**tier 2**

- **your node** `eth_call({ to: Multicall3, data: aggregate3(calls) }, block, { [Multicall3]: { code: the runtime code of Multicall3 } })`
  - `(success, returnData)` per call: remembered: the node takes overrides
  - `"0x"`: the node ignored the override. Remembered, then tier 3
  - an error, the first time:
    - **your node** `eth_call({ to: Multicall3, data: aggregate3([getChainId()]) }, block, { … })`
      - answered: the node takes overrides, the piece was too much. Halve it
      - not answered: remembered, then tier 3

**tier 3**

- **your node** `eth_blockNumber`: when the block is a tag
- **your node**: one request per call, at that number: see `Call.direct`

A group that reads the state of the chain adds calls to its `aggregate3`, and nothing else:

```text
Call.blockNumber      { target: Multicall3, callData: getBlockNumber() }
  on ArbOS            { target: ArbSys (0x…64), callData: arbBlockNumber() }
Call.blockHash(n)     { target: 0x0000F908…2935, callData: n }     the contract of EIP-2935
                      { target: Multicall3, callData: getBlockHash(n) }
  on ArbOS            { target: ArbSys, callData: arbBlockHash(n) } in place of the second
Call.baseFee          { target: Multicall3, callData: getBasefee() }
                      and on the eth_call: maxFeePerGas: 2^64 - 1, maxPriorityFeePerGas: 0,
                      with { [0x0000…0000]: { balance: 2^200 } } added to its state override
every other value     its getter of Multicall3
```

What a group has to know of its node for that is asked once per transport:

**is the chain ArbOS? Asked beside the first group that reads a block number or a hash**

- **your node** `eth_getCode(ArbSys, "latest")`
  - no code: not ArbOS
  - code: who is it?
    - **your node** `eth_call({ to: ArbSys, data: arbChainID(), gas: 100000 }, "latest")`
      - the chain id: ArbOS. That one group is asked again, of ArbSys
      - anything else, or a revert: not ArbOS

**does a fee make the base fee true? Asked before the first group that reads the base fee**

- **your node** `eth_call({ to: Multicall3, data: aggregate3([getBasefee()]), maxFeePerGas, … }, block, { [Multicall3]: { code }, [0x0000…0000]: { balance } })`
  - a base fee: yes
  - the fee it offered (zkSync Era), or an error (no state override): no. The base fee is then the node's:
    - **your node** `eth_getBlockByNumber(block, false)`: its base fee, and its hash H
    - **your node**: the group at `{ blockHash: H }`

When a group needs the number of its block (it is cut, or a piece of it is halved) and its
block is a tag:

  - `"latest"`:
    - **your node** `eth_blockNumber`
  - `"safe"`, `"finalized"`:
    - **your node** `eth_getBlockByNumber(tag, false)`
- **your node**: then every request of the group at that number

A page of fifty reads at `"latest"`, as requests:

| | First group | Every group after |
| --- | --- | --- |
| `Call.batching(false)` | 50 | 50 |
| Multicall3 is deployed | 1 | 1 |
| it is not | 2 | 1 |
| it is not, and the node refuses overrides | 54 | 51 |
