# Call.Reader

The service that runs reads. [`Call.read`](https://ethect.dev/reference/call/read/) builds a request and asks
it. `Call.direct` is the reader that sends one request per read.

## Usage

Replace the reader to change how reads reach the node. This one counts them.

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

const count = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
  Effect.gen(function* () {
    let reads = 0;
    const counting: Call.Reader = {
      call: (request) => {
        reads++;
        return Call.direct.call(request);
      },
    };
    const result = yield* Effect.provideService(effect, Call.Reader, counting);
    return [result, reads] as const;
  });

const twice = (token: Address.Address, user: Address.Address) => {
  const balance = Erc20.at(token).balanceOf(user);
  return count(Effect.all([balance, balance])); // [[…, …], 2]
};
```

`Call.Reader` is a `Context.Reference`: it has a default, so a program that provides none
still reads. The default merges reads into multicalls:
[`Call.batching`](https://ethect.dev/reference/call/batching/) tunes it, or turns it off.

### In a test

A reader that answers from memory tests a program without a node.

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

// what the contract would return: one word, 42
const fortyTwo: Hex.Hex = `0x${"2a".padStart(64, "0")}`;
const fake: Call.Reader = { call: () => Effect.succeed(fortyTwo) };

const balance = (token: Address.Address, user: Address.Address) =>
  Erc20.at(token)
    .balanceOf(user)
    .pipe(
      Effect.provideService(Call.Reader, fake),
      // a read is typed as needing a transport: this one is never asked
      Effect.provideService(
        Transport.Transport,
        Transport.Transport.of({ request: () => Effect.die("no node in this test") }),
      ),
    ); // 42n
```

## Reader

```ts
import type { Effect, Result } from "effect";
import type { Call, Hex, Revert, Transport } from "@ethect/core";

interface Reader {
  readonly call: (
    request: Call.Request,
  ) => Effect.Effect<Hex.Hex, Revert.Unknown | Transport.Error, Transport.Transport>;
  readonly callMany?: (
    requests: ReadonlyArray<Call.Request>,
  ) => Effect.Effect<
    ReadonlyArray<Result.Result<Hex.Hex, Revert.Unknown>>,
    Transport.Error,
    Transport.Transport
  >;
}
```

| Member | Gives |
| --- | --- |
| `call(request)` | the bytes the call returned. A revert is a failure: a [`Revert.Unknown`](https://ethect.dev/reference/revert/) with the revert data, which `Call.read` then decodes |
| `callMany(requests)` (optional) | the same for several requests at once, each with its own outcome. [`Call.all`](https://ethect.dev/reference/call/all/) uses it to leave without waiting. Without it, `Call.all` asks `call` for each, concurrently |

## Request

`Call.Request` is one read as a reader gets it: the call is encoded, and its block is decided.

| Field | Type | Is |
| --- | --- | --- |
| `to` | `Address.Address \| undefined` | the address called |
| `data` | `Hex.Hex` | the calldata |
| `block` | [`BlockId.BlockId`](https://ethect.dev/rpc/types/block-id/) | the block to read at: `"latest"` when nothing was said |
| `from`, `gas` | optional | the sender and the gas limit, when the read set them |
| `stateOverride`, `blockOverride` | optional | the overrides, when the read set them |
| `batch` | `boolean` | whether the read may share a request with others. `false` with `from`, `gas` or an override, and when the read said `batch: false` |
| `state` | optional | set for a call that reads the state of the chain itself, such as its block number: a reader may answer it with a plain method |

## direct

`Call.direct` is the reader that does not batch: one request per read.
[`Call.batching(false)`](https://ethect.dev/reference/call/batching/#turning-it-off) puts it in place for a
whole program.

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

const unbatched = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
  Effect.provideService(effect, Call.Reader, Call.direct);
```

## Behavior

- **A reader sees no ABI.** It gets bytes and gives bytes. Encoding the call and decoding its
  answer and its revert are done by `Call.read`, around it.
- **A revert is a failure of `call`**, never a success with odd bytes. `Call.direct` turns
  the node's "execution reverted" into a `Revert.Unknown` with the data the node gave, or with
  `0x` when it gave none.
- **Any other error of the node goes through as it is**: an
  [`RpcError`](https://ethect.dev/reference/errors/rpc-error/) or a
  [`TransportError`](https://ethect.dev/reference/errors/transport-error/).
- **A reader uses the `Transport` of whoever reads.** It keeps none of its own, so the same
  reader serves every chain of a program.

## Under the hood

`Call.direct` asks the `Transport`, once per request.

**a request**

- **your node** `eth_call({ to, data, from?, gas? }, block, stateOverride?, blockOverride?)`
  - the node answers a revert → fails: `Revert.Unknown { selector, data }`

**a request with `state`: the plain method that gives it**

- **blockNumber** `eth_blockNumber`: nothing when the read is at a block number
- **chainId** `eth_chainId`: asked once per transport
- **balance** `eth_getBalance(account, block)`
- **timestamp, gasLimit, baseFee** `eth_getBlockByNumber(block, false)`: or `eth_getBlockByHash`
- **blockHash** `eth_getBlockByNumber(thatBlock, false)`
- **any, with an override**: the `eth_call` above, to its getter: only a contract sees one

The answer to a request with `state` is given as one word, as a contract would return it, so
that it decodes like any other read.
