# Call.read

Reads a call of a view function. It gives what the function returns, or fails with the error
it reverts with.

## 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* () {
  // a call of a view is the effect of reading it: these two are the same read
  const now = yield* Erc20.at(USDC).balanceOf(USER);
  // `Call.read` takes options
  const before = yield* Call.read(Erc20.at(USDC).balanceOf(USER), { block: 19_000_000n });
  return now - before;
});

const change = await program.pipe(
  Effect.provide(Transport.http("https://ethereum-rpc.publicnode.com")),
  Effect.provide(FetchHttpClient.layer),
  Effect.runPromise,
);
```

`yield* call` is `Call.read(call)`. Use `Call.read` when a read needs an option. The examples
below leave the transport out.

### As another sender

`from` is the `msg.sender` the contract sees. A view that depends on who asks needs it:
without it, a read that merged with others is called by Multicall3.

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

const asUser = (token: Address.Address, user: Address.Address) =>
  Call.read(Erc20.at(token).balanceOf(user), { from: user });
```

### Over a state that does not exist

`stateOverride` replaces the balance, the code or the storage of accounts for the time of the
read. Nothing is written to the chain.

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

// What would the balance be if this slot of the token held one million?
const whatIf = (token: Address.Address, user: Address.Address, slot: Hex.Hex) =>
  Call.read(Erc20.at(token).balanceOf(user), {
    stateOverride: {
      [token]: { stateDiff: { [slot]: "0xf4240" } },
    },
  });
```

### A declared error

A function fails with the [errors it declares](https://ethect.dev/reference/fn/view/#errors), and with those
[its contract declares](https://ethect.dev/reference/contract/#errors-of-a-contract), as typed failures. Catch
one by its tag.

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

// ERC-721 declares no error. This adds the one the collection reverts with.
const Nft = Erc721.extend(Abi.parse(["error ERC721NonexistentToken(uint256 tokenId)"]));

const owner = (nft: Address.Address, tokenId: bigint) =>
  Call.read(Nft.at(nft).ownerOf(tokenId)).pipe(
    Effect.map(Option.some),
    Effect.catchTag("ERC721NonexistentToken", () => Effect.succeed(Option.none())),
  );
```

## Returns

`Effect<A, E | Call.Error, Transport>`

What the function returns, as its definition types it. `E` is the errors the function
declares, and `Call.Error` is what any read can fail with: see [Errors](#errors).

## Parameters

### call

- **Type:** `Call.View<A, E>`

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

### 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 to read at: a number, a tag, or an object that names the block by its hash.

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

const settled = (token: Address.Address, user: Address.Address) => [
  Call.read(Erc20.at(token).balanceOf(user), { block: "finalized" }),
  Call.read(Erc20.at(token).balanceOf(user), { block: { blockHash: `0x${"ab".repeat(32)}` } }),
];
```

### options.from (optional)

- **Type:** [`Address.Address`](https://ethect.dev/reference/primitives/address/)

The sender of the call: what the contract sees as `msg.sender`. With `from`, the read is sent
alone, as that account.

Without it, the sender depends on how the read left:

| The read | `msg.sender` |
| --- | --- |
| [merged with others](https://ethect.dev/reference/call/batching/#what-joins-a-group), which is the default | Multicall3, `0xcA11bde05977b3631167028862bE2a173976CA11` |
| was sent alone: `batch: false`, a `gas` or an override, nothing to merge with | the one the node picks, most often the zero address |

### options.gas (optional)

- **Type:** `bigint`

The gas the call may use. Without it the node applies its own cap.

### options.stateOverride (optional)

- **Type:** [`StateOverride.StateOverride`](https://ethect.dev/rpc/types/state-override/)

State to pretend is on chain, per account: `balance`, `nonce`, `code`, and `state` or
`stateDiff`. Not every node takes one.

### options.blockOverride (optional)

- **Type:** [`BlockOverride.BlockOverride`](https://ethect.dev/rpc/types/block-override/)

Fields of the block to pretend: `number`, `time`, `baseFeePerGas`, and others. Fewer nodes take
one than take a state override.

### options.batch (optional)

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

`false` keeps the read out of any batch: it is sent as an `eth_call` of its own.

## Behavior

- **Five steps, and nothing else.** The call is encoded. The request is built. The
  [reader](https://ethect.dev/reference/call/reader/) is asked. A revert is decoded with the errors of the
  function. What came back is decoded as what the function returns.
- **A read with `from`, `gas` or an override is never batched.** A batch is one call from one
  sender, over one state. The request says so, whatever `batch` is.
- **The block is decided before the reader is asked.** The option wins over `Call.withBlock`,
  which wins over `"latest"`.
- **Nothing is sent when the arguments do not encode.** The read fails with an `AbiError`
  first.
- **A function that returns nothing reads nothing.** Its result is `void`, whatever came back.
- **One read alone is one request**, sent a few milliseconds later: reads that wait together
  [merge into one](https://ethect.dev/reference/call/batching/). Two `yield*` in a row are two requests.

## Errors

| Error | When |
| --- | --- |
| an error the function declares | the call reverted with it |
| [`Revert.Reason`](https://ethect.dev/reference/revert/) | the call reverted with a message: `require(…, "…")` |
| [`Revert.Panic`](https://ethect.dev/reference/revert/#panic-codes) | an assertion, an overflow, a division by zero |
| [`Revert.Unknown`](https://ethect.dev/reference/revert/#what-is-unknown) | the call reverted with data the function does not declare, or with none |
| [`AbiError`](https://ethect.dev/reference/errors/abi-error/) | an argument is not a value its type takes: nothing was sent |
| `AbiError` | nothing came back and the function returns a value: there may be no contract at that address |
| `AbiError` | what came back is not the encoding of what the function returns |
| [`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 |

## Under the hood

One service is asked: [`Call.Reader`](https://ethect.dev/reference/call/reader/), which asks the `Transport`.
For a read that nothing joined, or with [`Call.direct`](https://ethect.dev/reference/call/reader/#direct):

**`Call.read(call, options)`**

- **encode**: selector + arguments. No request
- **Call.Reader** `eth_call({ to, data, from?, gas? }, block, stateOverride?, blockOverride?)`
  - a revert: the node answers an error with the revert data: decoded with the errors of the function. No request
- **decode**: what the function returns. No request

| Options | Request |
| --- | --- |
| none | `eth_call({ to, data }, "latest")` |
| `block: 19_000_000n` | `eth_call({ to, data }, "0x121eac0")` |
| `from`, `gas` | `eth_call({ to, data, from, gas }, "latest")` |
| `stateOverride` | `eth_call({ to, data }, "latest", { [address]: { … } })` |
| `blockOverride` | `eth_call({ to, data }, "latest", {}, { … })` |
