Testing
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.
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("Rejected", () => 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); }), );});bun add -d vitest @effect/vitest @effect/platform-nodepayis ordinary code. The layers decide where it runs:Chaingives it a node, andSigner.wallet(wallet.provider)a wallet, aswindow.ethereumwould be in a browser.@effect/vitestmakes Vitest run a test that is anEffect.layer(Chain)gives every test of the block whatChainprovides.AnvilNodeneeds Foundry installed, on your machine and in CI.
A node per test
Section titled “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.sendwaits for its block. In the JSON-RPC layer, send withEth.sendTransactionSync: anvil answerseth_sendTransactionbefore the block is mined.- Set the state a test needs with the
Anvilnamespace.
| To | Use |
|---|---|
| set balances, code, storage | Anvil.setBalance and the other state methods |
| send from an account you have no key for | Anvil.impersonateAccount |
| mine blocks, or stop mining | Anvil.mine, Anvil.setAutomine |
| move the clock | Anvil.increaseTime |
| save and restore the chain | Anvil.snapshot, Anvil.revert |
| start from mainnet | AnvilNode.layer({ args: ["--fork-url", url] }) |
The user is the test
Section titled “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 }): the node signs |
| the same wallet in a list, for a picker | wallet.wallet, a Wallets.Wallet |
| an answer of a precise shape, or a method anvil does not serve | MockProvider: it answers what its handlers say, and nothing happens anywhere |
Wallets as they are
Section titled “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.
11 collapsed lines
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.planasks 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_getCallsStatusoff the shape EIP-5792 gives, MetaMask batches only on the chains of its EIP-7702 list, Rainbow needs afrom, Rabby has no EIP-5792 at all. Every profile, and the file each behaviour was read in:TestWallet. - A locked wallet does not answer. Ambire opens its unlock popup and waits.
capabilitiesRequestTimeoutis how long a plan waits before it goes on without the answer.wallet.unlockgives the late answer, which the next plan uses.
A contract of your own
Section titled “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.
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 bytecodeprints it. TestSignersends from the accounts of the node: no wallet and no key. Use it for what a test sets up, andTestWalletfor 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.
A reorg in a test
Section titled “A reorg in a test”A reorg replaces the last blocks of the chain by others. On the anvil of a test,
AnvilNode.reorg rolls the chain back and mines as many empty blocks.
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, 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.getRawTransactionByHashgives them before the reorg. - Test a reorg with plain transactions. A batch of
TestWalletruns once: mined again in another block, it does nothing. Anvil.reorgis one request, and puts transactions of your choice in the new blocks. Empty blocks replaced by empty ones come back the same:AnvilNode.reorgmoves the clock for that.
Under the hood
Section titled “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_sendTransactionTestWallet:approve(request), then the same request to the node - your program
TestWallet, a refusal: error 4001, nothing reaches the node. Your code seesRejected - your program
TestWalletlikea 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_estimateGasTestSigner: theneth_sendTransaction, the node signs - your node
anvil_rollbackAnvilNode.reorg(depth): thenanvil_setNextBlockTimestamp,anvil_mine - your node
anvil_setCodeAnvilNode.placeMulticall3(): Multicall3, where every chain has it
Every option and every answer are on AnvilNode,
TestWallet, TestSigner and
MockProvider. AnvilNode needs a POSIX shell: it does not
run on Windows.