# Testing

Test a send against a real local node, with a wallet whose user is the test. A fresh anvil per test, a contract of your own on it, and a reorg when you want one.

Test a payment as a user would make it: once approved in the wallet, once refused. The node
is a real one, started for the test.

```ts title="pay.test.ts"
import { NodeServices } from "@effect/platform-node";
import { assert, layer } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { type Address, Call, Signer, Transport, Tx } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";
import { AnvilNode, TestWallet } from "@ethect/core/testing";

// What is tested: a payment. It names no wallet and no node.
const pay = (to: Address.Address) =>
  Tx.send(Call.make({ to, value: 1n })).pipe(
    Effect.as("paid" as const),
    Effect.catchTag("SignerRejected", () => Effect.succeed("refused" as const)),
  );

// A fresh anvil, and an HTTP transport that reaches it wherever it listens.
const Node = AnvilNode.layer().pipe(Layer.provide(NodeServices.layer));
const Http = Layer.unwrap(Effect.map(AnvilNode.AnvilNode, (node) => Transport.http(node.httpUrl)));
const Chain = Layer.provideMerge(Http, Node).pipe(Layer.provide(FetchHttpClient.layer));

layer(Chain, { buildPerTest: true, excludeTestServices: true })("a payment", (it) => {
  it.effect("is sent when the user approves", () =>
    Effect.gen(function* () {
      const [alice, bob] = yield* Eth.accounts();
      const wallet = yield* TestWallet.make({ accounts: [alice!] });
      const outcome = yield* pay(bob!).pipe(Effect.provide(Signer.wallet(wallet.provider)));
      assert.strictEqual(outcome, "paid");
      assert.strictEqual(yield* Eth.getBalance(bob!, "latest"), 10n ** 22n + 1n);
    }),
  );
  it.effect("is not sent when the user refuses", () =>
    Effect.gen(function* () {
      const [alice, bob] = yield* Eth.accounts();
      const wallet = yield* TestWallet.make({ accounts: [alice!], approve: () => false });
      const outcome = yield* pay(bob!).pipe(Effect.provide(Signer.wallet(wallet.provider)));
      assert.strictEqual(outcome, "refused");
      assert.strictEqual(yield* Eth.getTransactionCount(alice!, "pending"), 0);
    }),
  );
});
```

```sh
bun add -d vitest @effect/vitest @effect/platform-node
```

- **`pay` is ordinary code.** The layers decide where it runs: `Chain` gives it a node, and
  `Signer.wallet(wallet.provider)` a wallet, as `window.ethereum` would be in a browser.
- **`@effect/vitest`** makes [Vitest](https://vitest.dev) run a test that is an `Effect`.
  `layer(Chain)` gives every test of the block what `Chain` provides.
- **`AnvilNode` needs [Foundry](https://getfoundry.sh)** installed, on your machine and in CI.

## A node per test

`AnvilNode.layer()` starts anvil on a port the OS assigns, and stops it when the layer is
released. Its service says where it listens: `httpUrl`, `wsUrl`, `ipcPath`.

| Option of `layer(…)` | Does |
| --- | --- |
| `buildPerTest: true` | builds the layer once per test: each has its own anvil and its own chain. Tests cannot affect each other, and run together |
| left out | builds it once: the tests of the block share the chain, and their order matters |
| `excludeTestServices: true` | keeps the real clock. A node is a real process: under a test clock its answers never arrive |

- **A test with no node runs under the test clock**, where time does not pass. A read then
  waits for ever for others to join it: provide `Call.batching({ window: 0 })`.
- **Over HTTP, new blocks are asked for every four seconds at first.** A test that mines its
  own blocks, and waits for a receipt, sets `Block.Interval`:
  `Effect.provideService(Block.Interval, "10 millis")`.
- **`Tx.send` waits for its block.** In the JSON-RPC layer, send with
  `Eth.sendTransactionSync`: anvil answers `eth_sendTransaction` before the block is mined.
- **Set the state a test needs with the [`Anvil`](https://ethect.dev/rpc/anvil/) namespace.**

| To | Use |
| --- | --- |
| set balances, code, storage | [`Anvil.setBalance`](https://ethect.dev/rpc/anvil/state/#setbalance) and the other [state methods](https://ethect.dev/rpc/anvil/state/) |
| send from an account you have no key for | [`Anvil.impersonateAccount`](https://ethect.dev/rpc/anvil/accounts/#impersonateaccount) |
| mine blocks, or stop mining | [`Anvil.mine`](https://ethect.dev/rpc/anvil/mining/#mine), [`Anvil.setAutomine`](https://ethect.dev/rpc/anvil/mining/#setautomine) |
| move the clock | [`Anvil.increaseTime`](https://ethect.dev/rpc/anvil/time/#increasetime) |
| save and restore the chain | [`Anvil.snapshot`](https://ethect.dev/rpc/anvil/history/#snapshot), [`Anvil.revert`](https://ethect.dev/rpc/anvil/history/#revert) |
| start from mainnet | `AnvilNode.layer({ args: ["--fork-url", url] })` |

## The user is the test

`TestWallet` is a wallet over the node: what it signs and sends really happens there. The
test says what its user does.

| The user | In the test |
| --- | --- |
| approves, or refuses | `approve: (request) => boolean`. The request is what your app sent: refuse by `method` |
| changes account, or chain | `wallet.setAccounts([bob])`, `wallet.setChain(1)`: the wallet emits the event a wallet emits |
| has a wallet that batches, or not | `atomic: "supported"`, `"ready"`, `"unsupported"` or `"none"` |
| has Ambire, MetaMask, Rainbow or Rabby | `like: TestWallet.profiles.ambire`: the wallet answers as that one does |
| has a wallet that is locked | `silent: ["wallet_getCapabilities"]`, until `wallet.unlock` |
| disconnects | `wallet.disconnect` |

`wallet.requests` gives every request the wallet received: the place to check what your code
asked. For what a wallet over a node does not cover:

| You want | Use |
| --- | --- |
| to send with no wallet and no key, as a script does | [`TestSigner.layer({ unattended: true })`](https://ethect.dev/reference/testing/test-signer/): the node signs |
| the same wallet in a list, for a picker | `wallet.wallet`, a [`Wallets.Wallet`](https://ethect.dev/reference/wallets/) |
| an answer of a precise shape, or a method anvil does not serve | [`MockProvider`](https://ethect.dev/reference/testing/mock-provider/): it answers what its handlers say, and nothing happens anywhere |

## Wallets as they are

`TestWallet` answers as EIP-5792 writes it. Real wallets do not all do so, and an app that works
with one can hang or fail with another. Does the button work with an Ambire? With `like`, the
wallet answers as Ambire does, read in its source.

```ts title="split.test.ts"
import { NodeServices } from "@effect/platform-node";
import { assert, layer } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { type Address, Call, Signer, Transport, Tx } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";
import { AnvilNode, TestWallet } from "@ethect/core/testing";

const Node = AnvilNode.layer().pipe(Layer.provide(NodeServices.layer));
const Http = Layer.unwrap(Effect.map(AnvilNode.AnvilNode, (node) => Transport.http(node.httpUrl)));
const Chain = Layer.provideMerge(Http, Node).pipe(Layer.provide(FetchHttpClient.layer));

// What the button does: plan, then a signature and a wait for each step.
const split = (friends: ReadonlyArray<Address.Address>) =>
  Effect.gen(function* () {
    const calls = friends.map((to) => Call.make({ to, value: 1n }));
    for (const step of yield* Tx.plan(calls)) {
      yield* Tx.wait(yield* Tx.submit(step)); // the wallet prompts at the submit
    }
  });

layer(Chain, { buildPerTest: true, excludeTestServices: true })("the split button", (it) => {
  it.effect("works with each wallet", () =>
    Effect.gen(function* () {
      for (const like of Object.values(TestWallet.profiles)) {
        const [alice, bob, carol] = yield* Eth.accounts();
        const wallet = yield* TestWallet.make({ accounts: [alice!], like });
        const before = yield* Eth.getBalance(carol!, "latest");
        yield* split([bob!, carol!]).pipe(Effect.provide(Signer.wallet(wallet.provider)));
        assert.strictEqual(yield* Eth.getBalance(carol!, "latest"), before + 1n);
      }
    }),
  );

  it.effect("works with an Ambire that is locked", () =>
    Effect.gen(function* () {
      const [alice, bob, carol] = yield* Eth.accounts();
      const wallet = yield* TestWallet.make({
        accounts: [alice!],
        like: TestWallet.profiles.ambire,
        silent: ["wallet_getCapabilities"], // it waits for a password nobody types
      });
      const signer = Signer.wallet(wallet.provider, { capabilitiesRequestTimeout: "1 second" });
      // no answer within 1 s: one signature per payment
      yield* split([bob!, carol!]).pipe(Effect.provide(signer));
      assert.strictEqual(yield* Eth.getBalance(carol!, "latest"), 10n ** 22n + 1n);
    }),
  );
});
```

- **The button is the same for every wallet.** `Tx.plan` asks what the wallet can do: one
  that batches gets one signature, any other one per payment.
- **Each profile holds what that wallet does differently, and nothing else.** Ambire answers
  `wallet_getCallsStatus` off the shape EIP-5792 gives, MetaMask batches only on the chains of
  its EIP-7702 list, Rainbow needs a `from`, Rabby has no EIP-5792 at all. Every profile, and the
  file each behaviour was read in: [`TestWallet`](https://ethect.dev/reference/testing/test-wallet/#profiles).
- **A locked wallet does not answer.** Ambire opens its unlock popup and waits.
  `capabilitiesRequestTimeout` is how long a plan waits before it goes on without the answer.
  `wallet.unlock` gives the late answer, which the next plan uses.

## A contract of your own

A call with no `to` is a deployment. Send the creation code your compiler gives, and the
receipt has the address.

```ts title="token.ts"
import { Effect } from "effect";
import { Abi, type Address, Call, Erc20, type Hex, Tx } from "@ethect/core";
import { TestSigner } from "@ethect/core/testing";

/** Deploys a contract from its creation code, and gives its address. */
export const deploy = (creation: Hex.Hex) =>
  Effect.map(Tx.send(Call.make({ data: creation })), (receipt) => receipt.contractAddress!);

// ERC-20 is built in. This adds what the token of the test has more: anyone mints.
export const Token = Erc20.extend(
  Abi.parse(["function mint(address to, uint256 value)"]),
);

/** In a test: a token of its own on the test's chain, with five units for `owner`. */
export const staged = (creation: Hex.Hex, owner: Address.Address) =>
  Effect.gen(function* () {
    const token = Token.at(yield* deploy(creation));
    yield* Tx.send(token.mint(owner, 5n));
    return token; // `yield* token.balanceOf(owner)` is 5n
  }).pipe(Effect.provide(TestSigner.layer({ unattended: true })));
```

- **The creation code comes from your build.** With Foundry, `forge inspect Token bytecode`
  prints it.
- **`TestSigner` sends from the accounts of the node**: no wallet and no key. Use it for what
  a test sets up, and `TestWallet` for what its user does.
- **Each test deploys what it needs.** With a node per test, there is nothing to clean up.
- **A fresh anvil has no Multicall3.** To assert that merged reads are one `eth_call`, put it
  there first: [`AnvilNode.placeMulticall3`](https://ethect.dev/reference/testing/place-multicall3/).

## A reorg in a test

A reorg replaces the last blocks of the chain by others. On the anvil of a test,
[`AnvilNode.reorg`](https://ethect.dev/reference/testing/reorg/) rolls the chain back and mines as many empty blocks.

```ts title="reorg.ts"
import { Effect } from "effect";
import { type Address, Call, Tx } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";
import { AnvilNode } from "@ethect/core/testing";

/** A payment, then a reorg that takes it back. Gives what the node says of it afterwards. */
export const takenBack = (to: Address.Address) =>
  Effect.gen(function* () {
    const receipt = yield* Tx.send(Call.make({ to, value: 1n }));
    yield* AnvilNode.reorg(1); // the last block is replaced by an empty one
    return yield* Eth.getTransactionReceipt(receipt.transactionHash); // null
  });
```

After `AnvilNode.reorg(1)`, a payment of the last block is gone: its receipt is `null`, the
block at that height has another hash, and the balance is what it was.

- **Use it to test what follows the chain**: an [indexer](https://ethect.dev/guides/indexer/), a wait for
  several confirmations, a page that shows a balance per block.
- **A transaction that was rolled back is not pending either.** To have it mined again in another
  block, send its bytes again: `Eth.getRawTransactionByHash` gives them before the reorg.
- **Test a reorg with plain transactions.** A batch of `TestWallet` runs once: mined again in
  another block, it does nothing.
- **[`Anvil.reorg`](https://ethect.dev/rpc/anvil/reorg/) is one request**, and puts transactions of your choice
  in the new blocks. Empty blocks replaced by empty ones come back the same:
  `AnvilNode.reorg` moves the clock for that.

## Under the hood

What a test sends goes to the anvil of the test, and nowhere else.

- **your program**: `AnvilNode.layer()`: `anvil --port 0`, in a directory of its own. Stopped with the layer
- **your node** `eth_sendTransaction`: `TestWallet`: `approve(request)`, then the same request to the node
- **your program**: `TestWallet`, a refusal: error 4001, nothing reaches the node. Your code sees `SignerRejected`
- **your program**: `TestWallet` `like` a wallet: what that wallet answers differently, from the wallet itself
- **your node**: `TestWallet`, `wallet_sendCalls`: one transaction that runs the calls, all or nothing
- **your node** `eth_estimateGas`: `TestSigner`: then `eth_sendTransaction`, the node signs
- **your node** `anvil_rollback`: `AnvilNode.reorg(depth)`: then `anvil_setNextBlockTimestamp`, `anvil_mine`
- **your node** `anvil_setCode`: `AnvilNode.placeMulticall3()`: Multicall3, where every chain has it

Every option and every answer are on [`AnvilNode`](https://ethect.dev/reference/testing/anvil-node/),
[`TestWallet`](https://ethect.dev/reference/testing/test-wallet/), [`TestSigner`](https://ethect.dev/reference/testing/test-signer/) and
[`MockProvider`](https://ethect.dev/reference/testing/mock-provider/). `AnvilNode` needs a POSIX shell: it does not
run on Windows.
