# Eth.simulateV1

Simulates calls in a sequence of made-up blocks on top of a block you name, each with its own
overrides, and returns the blocks with the outcome of every call.

## Usage

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

const FUNDED = Address.makeUnsafe("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266");
const EMPTY = Address.makeUnsafe("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");

const program = Effect.gen(function* () {
  // an account that holds nothing on a local anvil
  const [block] = yield* Eth.simulateV1(
    {
      blockStateCalls: [
        {
          calls: [
            { from: FUNDED, to: EMPTY, value: 10n ** 18n },
            { from: EMPTY, to: FUNDED, value: 10n ** 17n },
          ],
        },
      ],
    },
    "latest",
  );
  return block?.calls.map((call) => call.status);
});

const statuses = await program.pipe(
  Effect.provide(Transport.http("http://127.0.0.1:8545")),
  Effect.provide(FetchHttpClient.layer),
  Effect.runPromise,
);
// ["success", "success"]
```

The second call spends what the first one sent: every call sees the state the calls before it
left. Nothing is written to the chain.

The examples below leave the transport out.

### Reading the outcome of a call

Each simulated block has a `calls` array, one entry per call, in order. A call that reverts
does not fail the simulation: its entry has the status `"failure"` and an `error`.

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

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

const outcomes = Effect.gen(function* () {
  // a contract that reverts with the custom error 0xdeadbeef when it gets no calldata
  const [block] = yield* Eth.simulateV1(
    { blockStateCalls: [{ calls: [{ from: FROM, to: CONTRACT }] }] },
    "latest",
  );
  return block?.calls.map((call) =>
    call.status === "success"
      ? { returnData: call.returnData, gasUsed: call.gasUsed, logs: call.logs }
      : { code: call.error?.code, data: call.error?.data },
  );
});
// [{ code: 3, data: "0xdeadbeef" }]
```

### Overrides per block

A block takes `stateOverrides` and `blockOverrides`, applied before its calls run.

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

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

const later = Effect.gen(function* () {
  const [block] = yield* Eth.simulateV1(
    {
      blockStateCalls: [
        {
          stateOverrides: { [FROM]: { balance: 10n ** 18n } },
          blockOverrides: { time: 2_000_000_000n },
          calls: [{ from: FROM, to: TO, value: 1n }],
        },
      ],
    },
    "latest",
  );
  return block?.timestamp; // 2000000000n
});
```

### Transactions in full

With `returnFullTransactions: true`, each block carries its transactions as objects, not as
hashes.

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

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

const senders = Effect.gen(function* () {
  const [block] = yield* Eth.simulateV1(
    {
      blockStateCalls: [{ calls: [{ from: FROM, to: TO, value: 1n }] }],
      returnFullTransactions: true,
    },
    "latest",
  );
  return block?.transactions.map((transaction) => transaction.from);
});
```

### Transfers of ether as logs

With `traceTransfers: true`, a transfer of ether shows up in the `logs` of its call as an
ERC-20 `Transfer` event.

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

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

const transfers = Effect.gen(function* () {
  const [block] = yield* Eth.simulateV1(
    {
      blockStateCalls: [{ calls: [{ from: FROM, to: TO, value: 1n }] }],
      traceTransfers: true,
    },
    "latest",
  );
  return block?.calls[0]?.logs?.[0]?.address;
});
// "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
```

The log is emitted by the address `0xeeee…eeee`. Its topics are the event, the sender and the
recipient, and its data is the amount.

## Returns

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

The simulated blocks: each is a [`Block`](https://ethect.dev/rpc/types/block/) with a `calls` array of
[`Simulate.Call`](https://ethect.dev/rpc/types/simulate/). With `returnFullTransactions: true` the result is
a `Simulate.Full`, whose blocks carry their transactions in full.

## Parameters

### payload

- **Type:** [`Simulate.Payload`](https://ethect.dev/rpc/types/simulate/) or `Simulate.FullPayload`

What to simulate.

| Field | Type | Description |
| --- | --- | --- |
| `blockStateCalls` | array | the blocks, in order: each has optional `blockOverrides`, `stateOverrides` and `calls` |
| `traceTransfers` | `boolean` (optional) | report transfers of ether as ERC-20 `Transfer` logs |
| `validation` | `boolean` (optional) | check nonces, balances and fees as a real block would |
| `returnFullTransactions` | `boolean` (optional) | return the transactions of each block in full |

A call is a [`TransactionRequest`](https://ethect.dev/rpc/types/transaction-request/), as for
[`Eth.call`](https://ethect.dev/rpc/eth/call/).

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

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

const blocks = Eth.simulateV1(
  {
    blockStateCalls: [
      { calls: [{ from: FROM, to: TO, value: 1n }] },
      { calls: [{ from: FROM, to: TO, value: 2n }] },
    ],
  },
  "latest",
);
```

Two entries give two blocks, the second built on the first.

### block (optional)

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

The block the simulated blocks are built on: a number, a tag, or an object that names the block
by hash.

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

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

const blocks = Eth.simulateV1(
  { blockStateCalls: [{ calls: [{ from: FROM, to: TO, value: 1n }] }] },
  "finalized",
);
```

## Behavior

- **Blocks follow the one you name.** On top of block 6, the first simulated block is number 7.
- **State carries on.** A call sees what the calls before it did, in its block and in the
  blocks before.
- **A revert is in the result.** The call has the status `"failure"` and an `error` with the
  `code`, `message` and `data` of a JSON-RPC error. The simulation itself succeeds.
- **A gap is filled.** When `blockOverrides.number` skips ahead, anvil returns the empty blocks
  in between too.
- **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).

## 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` | `InvalidParams` | `blockStateCalls` is empty |
| `RpcError` | `InsufficientFunds` | the sender of a call does not hold its `value` (code `-38014`) |
| `RpcError` | `BaseFeeTooLow` | with `validation: true`, the fee of a call is below the base fee (code `-38012`) |

The codes of the simulation each have a reason: see the
[`eth_simulateV1` rows](https://ethect.dev/reference/errors/rpc-error/#reasons) of the table.

## JSON-RPC method

`eth_simulateV1`
