# Eth.call

Runs a call against the state of a block without sending a transaction, and returns its return
data as hex. It is how you read a contract.

## Usage

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

const TOKEN = Address.makeUnsafe("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");
const HOLDER = Address.makeUnsafe("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");

const program = Eth.call(
  {
    to: TOKEN,
    // balanceOf(address): the selector, then the address padded to 32 bytes
    data: `0x70a08231${HOLDER.slice(2).padStart(64, "0")}`,
  },
  "latest",
);

const result = await program.pipe(
  Effect.provide(Transport.http("http://127.0.0.1:8545")),
  Effect.provide(FetchHttpClient.layer),
  Effect.runPromise,
);
// "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000"
```

The request names the contract in `to` and carries the calldata in `data`. The result is the 32
bytes the contract returned: here a `uint256` of `1000000000000000000`.

This method takes calldata as hex and gives the return data as hex. To call a function by its
name and get typed values, read through a contract: see
[Read and write a contract](https://ethect.dev/guides/contracts/).

The call works over every [transport](https://ethect.dev/guides/transports/). The examples below leave the
transport out.

### Computing a selector

A selector is the first four bytes of the Keccak-256 hash of the function signature, and
[`Hash.keccak256Utf8`](https://ethect.dev/reference/primitives/hash/) hashes a string.

```ts
import { Effect } from "effect";
import { Address, Hash, type Hex } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const TOKEN = Address.makeUnsafe("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");
const HOLDER = Address.makeUnsafe("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");

const balanceOf = Effect.gen(function* () {
  // "0x70a08231"
  const selector = Hash.keccak256Utf8("balanceOf(address)").slice(0, 10);
  const argument = HOLDER.slice(2).padStart(64, "0");
  const data: Hex.Hex = `0x${selector.slice(2)}${argument}`;
  return yield* Eth.call({ to: TOKEN, data }, "latest");
});
```

Each static argument (an address, a `uint256`, a `bool`) is one 32-byte word, padded on the
left.

### Decoding the result

The result is the bytes the function returned.
[`Fn.decodeOutput`](https://ethect.dev/reference/fn/decode-output/) and [`Abi.decode`](https://ethect.dev/reference/abi/decode/)
read them as typed values. By hand, a single `uint256` is one 32-byte word, which `BigInt`
reads.

```ts
import { Effect } from "effect";
import { Address } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const TOKEN = Address.makeUnsafe("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");
const HOLDER = Address.makeUnsafe("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");

const balance = Effect.gen(function* () {
  const result = yield* Eth.call(
    { to: TOKEN, data: `0x70a08231${HOLDER.slice(2).padStart(64, "0")}` },
    "latest",
  );
  // no contract at this address: there is nothing to decode
  if (result === "0x") return null;
  return BigInt(result); // 1000000000000000000n
});
```

A call to an address without code succeeds and returns `"0x"`, which `BigInt` does not accept:
test for it first.

### Catching a revert

A call that reverts fails with an [`RpcError`](https://ethect.dev/reference/errors/rpc-error/#reasons) whose
reason is `ExecutionReverted`.

```ts
import { Effect } from "effect";
import { Address } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const CONTRACT = Address.makeUnsafe("0x5FbDB2315678afecb367f032d93F642f64180aa3");

const outcome = Effect.gen(function* () {
  // a contract that reverts with the custom error 0xdeadbeef when it gets no calldata
  return yield* Eth.call({ to: CONTRACT }, "latest").pipe(
    Effect.map((data) => ({ reverted: false as const, data })),
    Effect.catchReason("RpcError", "ExecutionReverted", (reason) =>
      Effect.succeed({ reverted: true as const, data: reason.data }),
    ),
  );
});
// { reverted: true, data: "0xdeadbeef" }
```

`reason.data` is the revert data: the selector of the error, then its encoded arguments. It is
`undefined` when the node sent none.

## Returns

[`Effect<Hex, Method.Error, Transport>`](https://ethect.dev/rpc/method/#calling-a-method)

The return data of the call, as [`Hex`](https://ethect.dev/reference/primitives/hex/). It is `"0x"` when the call
returns nothing.

## Parameters

### request

- **Type:** [`TransactionRequest.TransactionRequest`](https://ethect.dev/rpc/types/transaction-request/)

The call to run. Every field is optional, and a call uses these:

| Field | Type | Description |
| --- | --- | --- |
| `to` | `Address` | the contract to call |
| `data` | `Hex` | the calldata: the selector, then the encoded arguments |
| `from` | `Address` | the account the call runs as |
| `value` | `bigint` | wei sent with the call |
| `gas` | `bigint` | a gas limit for the call |

```ts
import { Effect } from "effect";
import { Address } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const FROM = Address.makeUnsafe("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");
const TOKEN = Address.makeUnsafe("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");

const supply = Effect.gen(function* () {
  // totalSupply(): a selector and no argument
  return yield* Eth.call({ from: FROM, to: TOKEN, data: "0x18160ddd" }, "latest");
});
```

Write the calldata as `data`. `input` is sent too, so a transaction read from a node can be
passed back: see [`TransactionRequest`](https://ethect.dev/rpc/types/transaction-request/#a-transaction-read-from-a-node).

### block (optional)

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

The block whose state the call runs on: a number, a tag (`"latest"`, `"earliest"`, `"pending"`,
`"safe"`, `"finalized"`), or an object that names the block by hash.

```ts
import { Effect } from "effect";
import { Address } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const TOKEN = Address.makeUnsafe("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");

const supplyThen = Effect.gen(function* () {
  // totalSupply()
  return yield* Eth.call({ to: TOKEN, data: "0x18160ddd" }, 19_000_000n);
});
```

### stateOverride (optional)

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

State the call pretends is on chain, per account: a balance, a nonce, code or storage slots.
Nothing is written to the chain.

```ts
import { Address } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const FROM = Address.makeUnsafe("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");
const TO = Address.makeUnsafe("0x70997970C51812dc3A010C7d01b50e0d17dc79C8");

const funded = Eth.call(
  { from: FROM, to: TO, value: 10n ** 18n },
  "latest",
  { [FROM]: { balance: 10n ** 19n } },
);
```

Without the override, the same call fails on an account that does not hold the `value`.

### blockOverride (optional)

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

Header fields the call pretends its block has: its number, its timestamp, its base fee and
others.

```ts
import { Effect } from "effect";
import { Address } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const ADDRESS = Address.makeUnsafe("0x70997970C51812dc3A010C7d01b50e0d17dc79C8");

const at = Effect.gen(function* () {
  // TIMESTAMP PUSH0 MSTORE PUSH1 32 PUSH0 RETURN: returns the block's timestamp
  const code = "0x425f5260205ff3";
  return yield* Eth.call(
    { to: ADDRESS },
    "latest",
    { [ADDRESS]: { code } },
    { time: 2_000_000_000n },
  );
});
// "0x0000000000000000000000000000000000000000000000000000000077359400"
```

The call runs code planted by the state override, in a block whose timestamp is
`2000000000`.

## Behavior

- **No ABI coding here.** `data` goes out as you wrote it and the result comes back as the
  node sent it. [`Call.read`](https://ethect.dev/reference/call/read/) is the read that encodes the arguments,
  decodes the result and types the revert.
- **No default block.** Left out, the param is not sent and the node chooses the block:
  see [Naming a block](https://ethect.dev/rpc/guides/calling-methods/#naming-a-block).
- **Any `from`.** Nothing is signed, so `from` can be an account you hold no key for.
- **No code, no data.** A call to an address without code succeeds with `"0x"`.
- **Params are positional.** To pass a `blockOverride` without a state override, pass `{}` as
  `stateOverride`. An `undefined` in the middle fails with a `CodecError` and nothing is sent.

## Errors

The three [errors](https://ethect.dev/reference/errors/) every method can fail with. The cases specific to this
method, as anvil 1.9 reports them:

| Error | Reason | When |
| --- | --- | --- |
| `RpcError` | `ExecutionReverted` | the call reverts: `reason.data` is the revert data |
| `RpcError` | `TransactionRejected` | `from` does not hold the `value` |
| `RpcError` | `InvalidInput` | `gas` is below the intrinsic gas of the call |
| `RpcError` | `InvalidParams` | the block number is above the chain's head |
| `RpcError` | `InvalidParams` | an account of `stateOverride` has both `state` and `stateDiff` |
| `RpcError` | `ResourceNotFound` | no block has the given `blockHash` |
| `CodecError` | `on: "params"` | a quantity is negative, or a param is skipped: nothing is sent |

## JSON-RPC method

`eth_call`
