# Tx.simulate

Runs calls in order, each seeing the ones before it, and gives what each returns. Nothing is
sent, and no signer is needed.

## Usage

```ts
import { Effect } from "effect";
import { FetchHttpClient } from "effect/http";
import { Address, Erc20, Transport, Tx } from "@ethect/core";
import { Vault } from "./vault";

const USDC = Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
const VAULT = Address.makeUnsafe("0xBEEF01735c132Ada46AA9aA4c54623cAA92A64CB");
const USER = Address.makeUnsafe("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266");

const program = Effect.gen(function* () {
  const amount = 100_000_000n;
  // The deposit sees the approval, which no block holds.
  const {
    results: [approved, shares],
  } = yield* Tx.simulate(
    [Erc20.at(USDC).approve(VAULT, amount), Vault.at(VAULT).deposit(amount, USER)],
    { from: USER },
  );
  return shares; // what `deposit` returns: a bigint
});

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

```ts title="vault.ts"
import { Abi, Erc4626, Fn } from "@ethect/core";

// ERC-4626 is built in, and declares no error. This adds the one the vault reverts with.
export const Vault = Erc4626.extend(
  Abi.parse(["error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max)"]),
);

// Not a standard: WETH takes ether with `deposit()`.
export const wrap = Fn.payable()("deposit", { inputs: [] });
```

The simulation says what sending would do. Here the user has to hold the 100 USDC, or it
fails with `Tx.Reverted` as the deposit would: see [a call that reverts](#a-call-that-reverts).

Give `from`. Without it the sender is the zero address, which holds no token and has approved
nothing. The examples below leave the transport out.

### A call that reverts

The simulation fails with [`Tx.Reverted`](https://ethect.dev/reference/tx/failures/#txreverted). `call` says which call,
and `reason` is one of the errors the calls declare, or a
[plain revert](https://ethect.dev/reference/revert/).

```ts
import { Effect } from "effect";
import { type Address, Erc20, Tx } from "@ethect/core";
import { Vault } from "./vault";

const sharesOrMax = (usdc: Address.Address, vault: Address.Address, user: Address.Address) =>
  Tx.simulate([Erc20.at(usdc).approve(vault, 100n), Vault.at(vault).deposit(100n, user)], {
    from: user,
  }).pipe(
    Effect.map(({ results }) => results[1]),
    // One reason of a `TxReverted`: the vault takes less, and this is how much. Any other
    // revert, and any other failure, goes on as it is.
    Effect.catchReason("TxReverted", "ERC4626ExceededMaxDeposit", (reason) =>
      Effect.succeed(reason.max),
    ),
  );
```

### A gas limit for each call

A call that depends on one that is not mined cannot be estimated on its own. `"simulateV1"`
measures each call as its own transaction, after the ones before it. With that method named,
`gas` is a list and never `undefined`: there is nothing to check before reading it.

```ts
import { Effect } from "effect";
import { type Address, Erc20, Tx } from "@ethect/core";
import { Vault } from "./vault";

const limits = (usdc: Address.Address, vault: Address.Address, user: Address.Address) =>
  Tx.simulate([Erc20.at(usdc).approve(vault, 100n), Vault.at(vault).deposit(100n, user)], {
    from: user,
    method: "simulateV1",
  }).pipe(Effect.map(({ gas }) => gas.map((limit) => ({ gas: limit })))); // one per call
```

### One call

One call is a tuple of one result. It is a plain `eth_call` from the sender.

```ts
import { Effect } from "effect";
import { Tx, type Address } from "@ethect/core";
import { Vault } from "./vault";

const preview = (vault: Address.Address, user: Address.Address) =>
  Tx.simulate(Vault.at(vault).deposit(100n, user), { from: user }).pipe(
    Effect.map(({ results: [shares] }) => shares),
  );
```

### On a state that does not exist

`stateOverride` changes the balance, the code or the storage of accounts for the time of the
simulation. Here the sender is given the ether it wraps.

```ts
import { Tx, type Address } from "@ethect/core";
import { wrap } from "./vault";

const wrapped = (weth: Address.Address, user: Address.Address) =>
  Tx.simulate([wrap.at(weth)({ value: 10n ** 18n })], {
    from: user,
    stateOverride: { [user]: { balance: 10n ** 18n } },
    block: "finalized",
  });
```

## Returns

`Effect<Tx.Simulation<Calls>, Tx.Reverted<E> | Tx.Unsupported | AbiError | Transport.Error, Transport>`

A `Tx.Simulation`:

| Field | Type | Holds |
| --- | --- | --- |
| `results` | a tuple, one entry per call | what each call returned, typed by its function. A [raw call](https://ethect.dev/reference/call/make/) gives the bytes it returned |
| `gas` | `ReadonlyArray<bigint> \| undefined` | a gas limit for each call as its own transaction. Only with `"simulateV1"`: `undefined` otherwise |

`E` is the errors the calls declare, all of them. It comes from the type of `calls`: a list
typed `ReadonlyArray<Call.Call<unknown, unknown>>` makes it `unknown`. A function that takes any
calls keeps it with a `const` type parameter: see [Calls passed to a function](https://ethect.dev/guides/errors/#calls-passed-to-a-function).

| Called with | `gas` is |
| --- | --- |
| `method: "simulateV1"`, written in the call | `ReadonlyArray<bigint>`: the success is a `Tx.Simulation<Calls> & { gas: ReadonlyArray<bigint> }` |
| `method: "override"`, no method, or one known only when the program runs | `ReadonlyArray<bigint> \| undefined` |

## Parameters

`options` is a `Tx.SimulateOptions`. Every field of it is optional.

### calls

- **Type:** `Call.Call<A, E>`, or an array of them

One call or several, as [`fn.at(address)(...args)`](https://ethect.dev/reference/fn/at/) and
[`Call.make`](https://ethect.dev/reference/call/make/) build them. They run in order, from one sender. A call of
a `view` function is taken too.

### options.from (optional)

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

The sender of every call: what each contract sees as `msg.sender` and as `tx.origin`. Value is
paid from its balance.

### 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 whose state the calls start from.

### 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`. With `"override"`, the `code` given for the sender is replaced, and everything
else given for it is kept.

With no method named, the `code` given for the sender is the one it has for the calls, and not
the node's: code runs them with `"simulateV1"`, and `"0x"` makes it an account.

### options.method (optional)

- **Type:** `"override" | "simulateV1"`
- **Default:** for several calls, `"override"` when the sender has no code, and `"simulateV1"`
  when it has some or when the node refuses the override. A plain `eth_call` for one

How several calls are run. A method you name is the only one tried, also for one call.

Named, `"override"` places the executor on a sender that has code too: a contract, or an
account that delegates. A call that reaches back to such a sender reaches the executor, and
can revert where the transaction would not. See
[what the executor cannot do](#what-the-executor-cannot-do).

```ts
import { type Address, Erc20, Tx } from "@ethect/core";
import { Vault } from "./vault";

const asAnAccount = (usdc: Address.Address, vault: Address.Address, user: Address.Address) =>
  Tx.simulate([Erc20.at(usdc).approve(vault, 100n), Vault.at(vault).deposit(100n, user)], {
    method: "simulateV1",
    from: user,
  });
```

## The two methods

| | `"override"` | `"simulateV1"` |
| --- | --- | --- |
| Request | one `eth_call` | one `eth_simulateV1` |
| How | the code of an executor is placed on the sender for the call. It runs the calls | each call is a transaction of a block the node makes up |
| Picked | for a sender without code | for a sender with code, when the node refuses the override, or when a call creates a contract |
| The sender, during the calls | has code, 386 bytes | is the account it is |
| The block the calls run in | the block given | a block the node makes up after it, with a later number and timestamp |
| `gas` | `undefined` | a limit for each call |
| A call that creates a contract | not run: `Tx.Unsupported` when you name the method | run |
| After a call fails | nothing runs | the node runs the rest. The first failure is the one you get |
| A call that fails without reverting, such as out of gas | `Tx.Reverted`, with no data | `Tx.Reverted`, with no data and a `cause`: what the node said of it |
| A call that carries more ether than the sender has | `Tx.Reverted`, with no data | an `RpcError`: the node refuses the request |
| Served by | every node tried but Rootstock | every node tried but Scroll, zkSync Era and Rootstock |

Tried on Geth, reth, Nethermind (Gnosis), Base, Optimism, Arbitrum, BSC, Polygon, Scroll,
zkSync Era, Rootstock and anvil. Where both are served, the calls return the same with both,
unless what they return depends on the block. A deposit of 100 USDC in a vault that accrues
interest gave 86.947191675 shares with `"override"` and 86.947190552 with `"simulateV1"`, one
block later.

### What the executor cannot do

- **Give a gas limit per call.** A call is cheaper after another one touched the same
  contract, and the executor measures nothing of what a transaction costs. The same write
  measured 2,126 gas as the second call of a sequence, where `eth_simulateV1` measured 28,003
  for it as a transaction of its own. Gas limits come from `"simulateV1"` only.
- **Hide that the sender has code.** `msg.sender.code.length` is 386, not 0. A contract that
  refuses callers with code refuses the simulation. `tx.origin == msg.sender` still holds,
  except on zkSync Era, where the origin of a sender with code is the zero address.
- **Run the sender's own code.** A sender that is a contract, or an account that delegates
  (EIP-7702), has the executor in place of its code for the call. Its balance and its storage
  stay. A contract that calls it back reaches the executor, and gets nothing back: it often
  reverts with no data where the transaction succeeds. A callback, an ERC-1271 check of the
  sender, a vault that supplies into Morpho Blue when Blue is the sender. This is why the
  calls of a sender with code run with `"simulateV1"`, unless you name `"override"`.
- **Create a contract.**
- **Return logs.** Neither method gives them here.
  [`Eth.simulateV1`](https://ethect.dev/rpc/eth/simulate-v1/) does.

### What the executor answers

During the calls, a contract may call the sender. The executor answers as an account with no
code would, with two exceptions: questions such an account is never asked.

| Called by | With | It does |
| --- | --- | --- |
| the sender | the calls, in the one `eth_call` | runs them in order, stops after the first that fails |
| the sender, as one of the calls | anything | nothing: the call succeeds and returns nothing. It fails when it carries more ether than the sender has |
| anyone else | ether, with no data | takes it, returns nothing. It fits the 2,300 gas of a `transfer` |
| anyone else | `onERC721Received`, `onERC1155Received`, `onERC1155BatchReceived` | accepts the token: returns the selector |
| anyone else | `isValidSignature(bytes32,bytes)`, of ERC-1271 | returns the magic value when the signature is the sender's own, and `0xffffffff` otherwise |
| anyone else | anything else | returns nothing. The call succeeds, as a call to an account does |

A signature is the sender's own when it is 65 bytes, `r`, `s`, then `v` as 27 or 28, with `s`
in the lower half of the curve's order, and recovers to the sender. That is what every check
of an account's signature takes. A compact signature of 64 bytes is refused, though some
contracts take one from an account.

## Behavior

- **Each call sees the ones before it.** An approval is there for the deposit that follows.
- **Nothing is written.** The chain is as it was. Nothing is signed, and no signer is asked.
- **The first call that fails is the failure.** It says which call. What the calls before it
  returned is not given.
- **A revert is read with the errors of the call that failed, then with those of the other
  calls.** A call often reverts with an error of a contract it calls, such as the token a
  vault pulls from.
- **A sender with code runs its own code.** A contract, a smart account, or an account that
  delegates (its code is `0xef0100` and an address): the calls run with `eth_simulateV1`, and
  what the executor answered is not taken. A node without `eth_simulateV1` fails with
  `Tx.Unsupported`, never with a revert that the transaction would not have.
- **The sender's code is asked together with the executor's call.** A sender without code
  waits for no request more, and with batching on the two go in one HTTP request. A
  `stateOverride` that gives the sender code is taken for its code, and nothing is asked.
- **One call is a plain `eth_call`.** Nothing is placed on the sender, which keeps its code.
- **A refusal is remembered.** A transport that refused the override and ran the same calls
  with `eth_simulateV1` is asked for `eth_simulateV1` at once the next time, without the
  sender's code. A method you name is always asked for.
- **An override the node ignores is not a success.** When what comes back is not what the
  executor returns, the node is taken as one that refuses overrides.
- **A call that fails with no data is a revert with no data.** One that ran out of gas, for
  instance: `reason` is a `Revert.Unknown` whose `data` is `0x`.
- **What the node said of such a call is its `cause`.** `eth_simulateV1` gives an error for
  each call that failed. When that error is no revert, it is the `cause` of the failure, an
  [`RpcError`](https://ethect.dev/reference/errors/rpc-error/), and the `message` ends with it:
  `The call at index 1 reverted: Reverted without data (the node said: out of gas)`. The
  executor learns that a call failed and nothing of why, so `"override"` gives no `cause`.
- **Nothing is sent when a call does not encode.** The simulation fails with an `AbiError`
  first.
- **No call, no request.** `results` is empty.

## Errors

| Error | Reason | When |
| --- | --- | --- |
| [`Tx.Reverted`](https://ethect.dev/reference/tx/failures/#txreverted) | an error the calls declare | a call reverted with it. `call` is its index, `receipts` is empty |
| `Tx.Reverted` | [`Revert.Reason`](https://ethect.dev/reference/revert/), [`Revert.Panic`](https://ethect.dev/reference/revert/#panic-codes), [`Revert.Unknown`](https://ethect.dev/reference/revert/#what-is-unknown) | a call reverted with a message, a panic, or data no call declares |
| `Tx.Reverted` | `Revert.Unknown`, with no data | a call failed without reverting: out of gas, an invalid opcode. With `"simulateV1"`, `cause` is what the node said |
| [`Tx.Unsupported`](https://ethect.dev/reference/tx/failures/#txunsupported) | `"simulation"` | the node serves neither method, or not the one you named. The `message` holds what the node answered |
| `Tx.Unsupported` | `"simulation"` | the sender has code, and the node does not serve `eth_simulateV1`. The executor's answer is not taken: it may be a revert that the transaction would not have |
| `Tx.Unsupported` | `"simulation"` | `method: "override"` with a call that creates a contract. Nothing is sent |
| [`AbiError`](https://ethect.dev/reference/errors/abi-error/) | | an argument is not a value its type takes: nothing is sent |
| `AbiError` | | a call returned what its function does not: there may be no contract at that address |
| [`RpcError`](https://ethect.dev/reference/errors/rpc-error/) | | the node answered with an error that is no revert and no refusal of the method |
| [`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: the `Transport`. No [`Call.Reader`](https://ethect.dev/reference/call/reader/) is used, so
a simulation is never batched with reads.

**`Tx.simulate(calls, { from, block, stateOverride, method })`**

- **your program**: every call is encoded. No request

**one call, no method named**

- **your node** `eth_call({ from, to, data, value }, block, stateOverride?)`

**several calls, no method named**

- 1. together, one HTTP batch when batching is on. The code is not asked when `stateOverride` gives it, and neither is sent when a call creates a contract or the transport refused the override before:
  - **your node** `eth_getCode(from, block)`: the sender's code
  - **your node** `eth_call({ from, to: from, data: packed }, block, { ...stateOverride, [from]: { ...stateOverride[from], code: EXECUTOR } })`
- 2. the sender has no code → the executor's answer
- 3. `"simulateV1"`: the sender has code, or the node refused the override or ignored it:
  - **your node** `eth_simulateV1({ blockStateCalls: [{ stateOverrides: stateOverride, calls }] }, block)`
- 4. not served → fails: `Tx.Unsupported`

**a method named**

- **your node**: that request alone
  - not served → fails: `Tx.Unsupported`

`packed` is the calls one after the other, and what comes back is one outcome per call:

```text
in    [to (20 bytes) | value (32) | length of the data (4) | data] for each call
out   [success (1) | gas used (8) | length (4) | return data] for each call, up to the first that fails
```

| The node answers | Read as |
| --- | --- |
| `eth_getCode` with code, any code | the sender runs its own: `eth_simulateV1`, whatever `eth_call` answered |
| `eth_call` with error `-32602`, `-32601`, `-32004` or `4200` | it refuses state overrides: `eth_simulateV1` is tried |
| `eth_call` with bytes that are not outcomes | it ignored the override: `eth_simulateV1` is tried |
| `eth_simulateV1` with error `-32601`, `-32004` or `4200` | it does not serve the method |
| a failed call in the outcomes | `Tx.Reverted`, with its data read as an error |
| a failed call of `eth_simulateV1` whose `error` is no revert | `Tx.Reverted` with no data, and that error as its `cause` |
| any other error | passed on as it is |

The `gas` of `"simulateV1"` is what the node says each call used, and half as much again: a
refund lowers what is used below what had to be there.
