# Simulate before sending

Show the shares a deposit would give before the user signs anything. Tx.simulate runs calls in order on the state of the chain, each seeing the ones before it, and writes nothing.

Show what a transaction would do before anyone signs it. Here: the shares a deposit would
give, with the approval it needs run first.

```ts title="preview.ts"
import { Effect } from "effect";
import { FetchHttpClient } from "effect/http";
import { Address, Transport, Tx } from "@ethect/core";
import { depositCalls } from "./vault";

/** The shares a deposit would give, approval included. Nothing is signed, nothing is sent. */
export const preview = (usdc: Address.Address, vault: Address.Address, user: Address.Address, amount: bigint) =>
  Effect.gen(function* () {
    // The deposit sees the approval, which no block holds.
    const calls = depositCalls(usdc, vault, user, amount);
    const { results } = yield* Tx.simulate(calls, { from: user });
    const [approved, shares] = results; // a boolean and a bigint: what each function returns
    return { approved, shares };
  });

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

// 100 USDC
const { shares } = await preview(USDC, VAULT, USER, 100_000_000n).pipe(
  Effect.provide(Transport.http("https://ethereum-rpc.publicnode.com")),
  Effect.provide(FetchHttpClient.layer),
  Effect.runPromise,
);
```
```ts title="vault.ts"
import { Abi, Erc20, Erc4626, type Address } from "@ethect/core";

// ERC-4626 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)"]),
);

/** The two calls of a deposit: the approval, then the deposit that needs it. */
export const depositCalls = (usdc: Address.Address, vault: Address.Address, user: Address.Address, amount: bigint) =>
  [Erc20.at(usdc).approve(vault, amount), Vault.at(vault).deposit(amount, user)] as const;
```

- **`Erc20.at(usdc).approve(vault, amount)` is a call**: a plain value, not sent. The same calls go
  to [`Tx.send`](https://ethect.dev/reference/tx/send/) when the user agrees.
- **`Tx.simulate` needs a node and no signer.** `Effect.provide` gives it the node, and
  `yield*` is `await`.
- **Give `from`.** Every contract sees it as `msg.sender`. Without it the sender is the zero
  address.

With viem, `simulateContract` runs one call: a deposit that needs an approval reverts there.
`simulateCalls` runs several, and only on a node that serves `eth_simulateV1`.

## What comes back

- **`results` has one entry per call, typed by its function**: a `boolean` for the approval,
  a `bigint` for the deposit.
- **Each call sees the ones before it.** The allowance is there for the deposit.
- **Nothing is written.** After the simulation the allowance is what it was, and the account
  has sent nothing.
- **It runs on the latest block.** Pass `block` for another one, and `stateOverride` to
  pretend an account holds what it does not.
- **The user has to hold the 100 USDC.** A simulation says what sending would do: without the
  tokens it fails, as the deposit would.

## A call that would revert

The simulation fails with `TxReverted`. `call` says which call, and `reason` is the error of
the contract, typed by the errors the contracts of the calls declare.

```ts
import { Effect } from "effect";
import { type Address } from "@ethect/core";
import { preview } from "./preview";

/** What to show before the user signs: the shares, or why the deposit would fail. */
export const quote = (usdc: Address.Address, vault: Address.Address, user: Address.Address, amount: bigint) =>
  preview(usdc, vault, user, amount).pipe(
    Effect.map(({ shares }) => `You get ${shares} shares`),
    Effect.catchTag("TxReverted", (error) =>
      Effect.succeed(
        error.reason._tag === "ERC4626ExceededMaxDeposit"
          ? `The vault takes ${error.reason.max} more` // the vault's own error, typed
          : `Call ${error.call} would revert: ${error.reason.message}`,
      ),
    ),
  );
```

| The call | `error.reason` |
| --- | --- |
| reverts with an error the calls declare | that error, with its fields: `reason.max` |
| reverts with `require(…, "paused")` | a `Revert.Reason`: its `message` is `paused` |
| divides by zero, overflows | a `Revert.Panic`, with its `code` |
| reverts with an error no call declares | a `Revert.Unknown`, with the `data` |
| fails with no data | a `Revert.Unknown` whose `data` is `0x` |

A failure with no data has three causes: a `revert()` with no reason, a call that ran out of
gas, or a call that carries more ether than the sender has.

The reason is typed by the type of the calls. A function that takes any calls and types them
`ReadonlyArray<Call.Call<unknown, unknown>>` gets a reason typed `unknown`: [Calls passed to a
function](https://ethect.dev/guides/errors/#calls-passed-to-a-function) keeps the errors.

## The two methods

Several calls run in one of two ways: `"override"` for a sender without code, and
`"simulateV1"` for a sender with code or for a node that refuses `"override"`. `method` names
one.

| | `"override"`, for a sender without code | `"simulateV1"` |
| --- | --- | --- |
| The request | one `eth_call`, with a small executor placed on the sender for its duration | one `eth_simulateV1` |
| What each call returns | yes | yes |
| Which call fails, and why | yes | yes |
| A gas limit for each call | no: `gas` is `undefined` | yes: one limit per call |
| The sender, during the calls | has code | is the account it is |
| The block the calls run in | the block you gave | a block the node makes up after it |
| More ether than the sender has | `TxReverted`, with no data | an `RpcError`: the node refuses the request |
| A sender with code: a contract, a smart account, an account that delegates | its code is replaced: a contract that calls it back reaches the executor, and may revert | its code runs |
| A node that does not serve it | the other method is tried, unless you named this one | `TxUnsupported` |

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

/** A gas limit for each call as its own transaction. */
export const limits = (usdc: Address.Address, vault: Address.Address, user: Address.Address, amount: bigint) =>
  Tx.simulate(depositCalls(usdc, vault, user, amount), { from: user, method: "simulateV1" }).pipe(
    Effect.map(({ gas }) => gas),
  );
```

Name `"simulateV1"` in three cases:

- **You need gas limits.** A deposit cannot be estimated alone before its approval is mined.
- **A contract refuses callers that have code.** Under `"override"` the sender has some.
- **A contract checks a compact signature of the sender**, 64 bytes long. The executor validates the
  sender's signatures of 65 bytes only: the simulation fails where the transaction would pass.

## Then send

The calls that were simulated are the calls to send.

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

export const send = (usdc: Address.Address, vault: Address.Address, user: Address.Address, amount: bigint) =>
  Effect.gen(function* () {
    const gas = yield* limits(usdc, vault, user, amount);
    return yield* Tx.send(depositCalls(usdc, vault, user, amount), {
      transaction: gas.map((limit) => ({ gas: limit })), // one set of fields per call
    });
  });
```

- **The gas is optional.** Without `transaction`, `Tx.send` estimates it.
- **The chain moves between the two.** A simulation is about the block it ran on. In a vault
  that accrues interest, the same deposit gives a little less one block later.

## Under the hood

One service is asked: the `Transport`. A simulation is never merged with other reads.

**one call**

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

**several calls**

- **your node** `eth_getCode(from, block)`: the sender's code, sent together with the next request: one HTTP batch when batching is on
- **your node** `eth_call({ from, to: from, data: the calls, packed }, block, { [from]: { code: EXECUTOR } })`
- **your node** `eth_simulateV1({ blockStateCalls: [{ calls }] }, block)`: when the sender has code, or the node refuses state overrides, or ignores them
- **your program**: not served: `TxUnsupported`

**`method: "simulateV1"`**

- **your node** `eth_simulateV1`: alone

The executor runs at the sender's address: every contract sees the sender as `msg.sender`.
What it answers to a contract that calls it back is on [`Tx.simulate`](https://ethect.dev/reference/tx/simulate/).
A sender with code would lose it to the executor, so its calls go to `eth_simulateV1`, where
its code runs. A sender without code waits for nothing more: its code is asked beside the
call.
