# Foundry Anvil Testcontainers > Real anvil nodes for Node.js tests: every flag type-safe and validated, with a pre-configured viem test client. This file contains all documentation content in a single document following the llmstxt.org standard. ## anvil behaviours worth knowing ### Reset A bare `anvil_reset` *detaches* a forked node, and viem's `reset()` fails on a non-forked one. The library's `reset()` returns to genesis or re-forks at the fork block; both discard snapshots. ### Forks A fork's hardfork follows the chain id and block: a local "mainnet" (id 1) at block 3 gets an ancient one, so pin `evm.withHardfork()`. ### Chain id After `setChainId()`, anvil's dev-account signer keeps the old chain id: node-signed transactions fail; local, impersonated and unsigned ones work. ### Watchers Watchers subscribe asynchronously with no "ready" signal: repeat the trigger until observed. `watchBlocks` over WebSocket may report blocks out of order. ### More | Behaviour | Consequence | |---|---| | Writes signed by anvil are mined even when they revert | check the receipt (`confirm()` throws) or simulate first | | With automine, anvil returns the hash just *before* the block is committed | `confirm()` re-reads the receipt with a short backoff | | Writes signed locally are estimated first | the revert is thrown before anything is sent | | `--order fees` ranks pending transactions by `maxFeePerGas` | raise the fee cap, not only the tip, to be mined first | | Reverting a snapshot keeps pending transactions | `useAnvil()` empties the pool; do it yourself around `withSnapshot()` | | Snapshots don't restore node settings | restore them in `finally` | | `setMinGasPrice()` is rejected while EIP-1559 is active | use a pre-London hardfork, or `setNextBlockBaseFeePerGas()` | | Receipts carry `contractAddress` in lower case | normalise with `getAddress()` before comparing | | Two copies of viem (e.g. `npm link`) | match errors by `name`, not `instanceof` | | A transaction with a nonce gap waits in the *queued* pool | it is mined once the gap is filled | | Mixed mining reports `getAutomine() === false` | transactions are still mined on arrival | | JSON ABIs are typed as `Abi` | narrow `readContract` results, or use `parseAbiItem` | | Every genesis `alloc` entry needs a `balance` | add `"balance": "0x0"` to contract entries | | EIP-5792 `sendCalls`, `simulateCalls` asset tracing | not supported by anvil 1.6 | --- ## Architecture: node, test client, cheats ### Three layers | Layer | Style | Use it for | |---|---|---| | `anvil.testClient` | viem actions, one object argument | everything viem can do, plus anvil extras | | `anvil.cheats` | fluent chain, positional arguments, units | scripting several state changes | | `anvil.*` helpers | methods on the node | accounts with keys, receipts, snapshots, files, lifecycle | They share one client; mix them freely. ### How the test client is built Once anvil answers JSON-RPC, `start()`: 1. reads the real chain id (`--chain-id`, the fork's, or 31337); 2. creates a viem test client (`mode: "anvil"`, `cacheTime: 0`, 25 ms polling); 3. adds public, wallet and [anvil extra](../reference/anvil-actions.md) actions; 4. resolves the default account (impersonates, looks up or derives it). The `chain` follows `setChainId()` and `reset()` (also as raw requests), so `eth_chainId` is answered locally. After `stop()`, every request rejects with `CONTAINER_STOPPED`: a forgotten `await` fails instead of hanging. ### Typed default account `TestClientOptions` → `AnvilContainer` → `StartedAnvilContainer` → `AnvilTestClient`: with a default account, actions compile without `account`. ### Why not just viem? viem is the foundation; the library adds a node, validated configuration, chain binding, fixed `reset` / strict `revert`, receipts that don't hang on `--no-mining`, and isolation hooks. Related: [Configure the test client](../tasks/configure/test-client.md), [Script state changes](../tasks/state/script-state-changes.md). --- ## Dedication to quality Every change goes through the same gate on every pull request and push to `main`: build, typecheck, lint, unit tests with coverage, end-to-end tests against real anvil nodes, and a full docs build. Any failure fails CI. ### Code coverage [![Codecov coverage sunburst](https://codecov.io/gh/hella-labs/foundryanvil-testcontainers-nodejs/graphs/sunburst.svg?token=WU523RPLO1)](https://codecov.io/gh/hella-labs/foundryanvil-testcontainers-nodejs) The sunburst is live from [Codecov](https://codecov.io/gh/hella-labs/foundryanvil-testcontainers-nodejs): the inner ring is `src/`, each outer ring a folder or file below it. Size is the number of lines, colour is how much of them the unit tests cover. Coverage is a floor, not a goal: each project fails its own build below these thresholds. | Project | Statements | Branches | Functions | Lines | |---|---|---|---|---| | Library (`src/`) | 95% | 90% | 95% | 95% | | Examples (`examples/`) | 95% | 90% | 95% | 95% | | Docs tooling (`docs/plugins`, `docs/scripts`) | – | 90% | 95% | 95% | At v0.7.0 the library sits at 98.6% statements, 96.9% branches, 99.3% functions and 99.1% lines, and the docs tooling at 100% statements and 98.9% branches. ### Unit tests Fast, no Docker, run on every commit (Node 22 and 24 in CI). | Suite | What it proves | |---|---| | Library: 508 tests in 34 files | every flag renders correctly, every conflict and dependency rule is enforced, the test client, cheats and container helpers behave, every error carries its code | | Examples: 10 files | the examples' own helpers, and that the published package links and exports what the docs promise | | Docs: 96 tests | the snippet sync engine, the reference generators, the content rules and API coverage (below) | ### End-to-end tests Unit tests prove the code follows its rules; end-to-end tests prove the rules match anvil. They start real nodes with Testcontainers. - **CLI parity:** every flag, and every pair of flags the library can render, is run through the real anvil binary's argument parser. The verdict (ok, conflict, missing requirement) must match the library's flag registry. Every flag and every hardfork then boots a node. - **Container and test client:** the container lifecycle and the test client's helpers against a live node. - **Examples:** 18 end-to-end files, one per task area, consume the built package exactly as a user would (via `npm link`), on Node 22 and 24. ### Docs that can't rot No code on this site is written by hand, so samples can't drift from the library. Every sample is a `// #region` of a tested example, copied in by `pnpm docs:sync`; reference tables are generated from the built library. The build fails when: - a sample differs from its region, or a region is missing or unused; - a code block isn't linked to an example; - a generated table differs from the library; - a public API member, flag or error code is undocumented or never shown in a sample; - a link or anchor is broken; - the built pages don't contain the synced samples, or the examples behind them fail against anvil. The full contract: [How the docs are tested](tested-docs.md). ### A fast docs site - **Static HTML:** every page is pre-rendered at build time and readable before any JavaScript runs. - **Small first load:** about 180 KB gzipped for a docs page (HTML, CSS and JavaScript). After that, navigation happens in the browser and linked pages are prefetched. - **No redirects:** URLs match GitHub Pages' files exactly (no trailing slashes). - **Lazy images and swap fonts:** below-the-fold images load on demand, and text renders right away in a fallback font while web fonts load. - **Machine-readable:** a sitemap, plus `llms.txt` and `llms-full.txt` for AI tools. ### Run the gate yourself From the repository root: ```bash pnpm gate # everything, with a local anvil binary pnpm check:docker # everything, with Docker (as CI) ``` See [CONTRIBUTING](https://github.com/hella-labs/foundryanvil-testcontainers-nodejs/blob/main/.github/CONTRIBUTING.md). --- ## Concepts Task pages stay short; the context lives here. | Concept | Read it when | |---|---| | [Architecture](architecture.md) | you wonder which layer to use: test client, cheats or container helpers | | [Isolation and snapshots](isolation.md) | state leaks between tests, or a revert fails | | [Signing](signing.md) | a write reverted (or didn't), or a signature has the wrong chain id | | [Validation](validation.md) | you want to know what is checked when | | [Startup and files](startup-and-files.md) | startup fails, or state files don't show up | | [Runtimes](runtimes.md) | you run without Docker, or with a custom image | | [Performance](performance.md) | your suite is slow | | [anvil behaviours](anvil-behaviours.md) | anvil does something surprising | | [How the docs are tested](tested-docs.md) | you contribute a page or an example | | [Dedication to quality](dedication-to-quality.md) | you want to know how the library and these docs are tested | --- ## Isolation and snapshots ### Per-test isolation With `useAnvil()` (default `isolation: "test"`): 1. `beforeAll`: start, `setup`, baseline `checkpoint()`; 2. `afterEach`: drop pending transactions, restore the baseline; 3. `afterAll`: stop. A restore takes milliseconds; a new node, about a second. ### What a snapshot restores | Restored (chain state) | Not restored (node settings) | |---|---| | balances, code, storage, nonces | automine / interval mining | | blocks and block numbers | impersonation, auto-impersonation | | the clock (block timestamps) | block gas limit, coinbase | | | logging, block timestamp interval, chain id | Restore changed settings in `finally`. Reverting also keeps **pending transactions**: `useAnvil()` empties the pool; around `withSnapshot()` / `checkpoint()`, call `cheats.dropAllTransactions()` yourself. ### Strict snapshots A snapshot can be reverted to once. anvil answers `false` for unknown or used ids, which viem ignores; the library throws `SNAPSHOT_NOT_FOUND` instead. `checkpoint()` re-snapshots after each restore. `reset()` and `loadState()` discard every snapshot: use `isolation: "none"` in files that call them. | Need | API | |---|---| | isolate every test | `useAnvil()` default, or `checkpoint()` + `afterEach(() => base.restore())` | | isolate a block of code | `withSnapshot(async (client) => …)` | | back to genesis / the fork block | `reset()` (use `isolation: "none"`) | | fixtures | `setup`, `loadStateFromFile()`, `state.withLoadState()` | Related: [Share a node](../tasks/test-suites/share-a-node.md), [Isolate state inside a test](../tasks/test-suites/isolate-tests.md). --- ## Performance: fast suites ### Where the time goes | Per… | Operation | Typical cost (local anvil) | |---|---|---| | Jest worker | first import of viem + Testcontainers | ~1.5 s | | test file | importing the library again | ~50–80 ms | | test file | start a node | ~0.1 s, plus container start with Docker | | test | per-test isolation (`useAnvil`) | ~4 ms | | transaction | node-signed send | ~3.5 ms | | transaction | `confirm()` (send + receipt) | ~5 ms | | event | HTTP watcher sees a new block | ~one polling interval (25 ms) | A new node costs about a hundred restores: start one per file, isolate tests with snapshots. ### What the library optimises - **Receipts:** `confirm()` re-reads right away, then with a 1 ms backoff (anvil returns an automined hash just before committing the block). - **Chain id:** answered locally; viem asks before every node-signed send. - **Isolation:** the mempool is emptied while the snapshot is restored. - **Keys:** the default mnemonic's keys are built in; others are derived once. - **Startup:** readiness is probed every 10 ms. - **Polling:** every 25 ms. Measure with `pnpm bench` (see CONTRIBUTING). ### Keep your suite fast - **Deploy fixtures once** in `setup`, not in `beforeEach`. - **Save expensive state** (`dumpStateToFile()`) and boot from it (`state.withLoadState()`) instead of replaying deployments. - **Fewer, larger test files**: fewer node starts. - **Run files in parallel**: each Jest worker gets its own node. - **Batch reads**: `multicall` (even `deployless`) or `withBatch()`. - **`*Sync` actions** (`writeContractSync`, `sendTransactionSync`) return the receipt in one request. - **Don't sleep** in watcher tests: trigger until observed (`triggerUntil`). - **Lower `withPollingInterval()`** for suites waiting on HTTP watchers, or use WebSockets. Related: [Share a node](../tasks/test-suites/share-a-node.md), [Save and load chain state](../tasks/state/save-and-load-state.md). --- ## Runtimes: Docker and local binaries ### Docker (default) `new AnvilContainer(options, image?)` runs `DEFAULT_ANVIL_IMAGE` (the anvil version the library is tested with); any image with `anvil` on its `PATH` works. Docker exercises everything (ports, file copies, graceful stops): use it in CI. ### Local binary (no Docker) Override the protected `startRuntime()`: return a ready `StartedTestContainer` whose `getHost()` / `getMappedPort(port)` reach JSON-RPC (`this.prepare()` has the command). Validation, test client and errors stay the library's. The examples' local runtime binds to `127.0.0.1` on a free port, maps file paths into a temp directory and stops with `SIGTERM`; files copied *out* are not supported. Binary lookup: `ANVIL_BINARY` → `@foundry-rs/anvil` → `PATH` → `~/.foundry/bin/anvil`. Related: [Run without Docker](../get-started/run-without-docker.md), [Run in CI](../get-started/run-in-ci.md). --- ## Signing: anvil-signed vs. locally signed | | Signed by anvil | Signed locally | |---|---|---| | How | `eth_sendTransaction` from an unlocked address | `eth_sendRawTransaction` with a key in the client | | Accounts | dev accounts, impersonated addresses, `autoImpersonate()` | `withLocalAccount()`, `testClientFor(privateKeyToAccount(key))` | | Reverting writes | sent as-is, **mined**, receipt `status: "reverted"` | viem estimates gas first: the decoded revert is thrown, **nothing is sent** | | After `setChainId()` | fail: anvil's signer keeps the startup chain id | work | | Keys needed | no | yes: from the mnemonic, the banner, or your own | To assert a revert *reason*, simulate or sign locally; to test what happens *on chain*, send anvil-signed and check the receipt (`confirm()`). ### Where local keys come from - Default mnemonic: built in. `withMnemonic()`: derived once. - Random or seeded mnemonic: read from anvil's banner, so not with `logs.quiet()` (`withLocalAccount(index)` is then rejected before start). ### `withAccount(address, { impersonate: true })` anvil signs only for dev accounts and impersonated addresses: a non-dev default address needs `{ impersonate: true }` or `account.autoImpersonate()`, or `prepare()` rejects it. Related: [Sign locally](../tasks/accounts/sign-locally.md), [Assert reverts](../tasks/transactions/assert-reverts.md). --- ## Startup, readiness and file transfers ### `start()`, step by step 1. **Prepare** (no Docker): validate all options, register file copies, set the command and port. 2. **Start** the runtime (`startRuntime()`; Docker by default). 3. **Wait** for JSON-RPC, probed every 10 ms, whatever the log settings. If anvil exits, `AnvilStartupError` reports its output at once. 4. **Initialise**: chain id, `--config-out`, test client, default account. `--host` is always `0.0.0.0`; the container port (`withPort()`) is mapped to a host port (`getMappedPort()`). ### Files File options take **host paths** (relative to the working directory): | Flag | Direction | When | |---|---|---| | `--load-state`, `--init` | host → container | before start; the file must exist | | `--state` | host → container, container → host | before start if it exists; after stop | | `--dump-state` | container → host | after stop | | `--config-out` | container → host | right after start | Files land at `CONTAINER_FILE_PATHS`; `containerPath("/abs")` passes files in your image through uncopied. ### Graceful stop anvil writes dumps on exit. With a dump target, `stop()` sends `SIGTERM`, waits up to 30 s (`DEFAULT_GRACEFUL_STOP_TIMEOUT_MS`), copies the file out, then removes the container. Related: [Save and load chain state](../tasks/state/save-and-load-state.md), [Manage the lifecycle](../tasks/test-suites/manage-the-lifecycle.md). --- ## How the docs are tested No code on this site is written by hand. ### Code samples ← tested example regions Every sample is a `// #region` of [`examples/`](https://github.com/hella-labs/foundryanvil-testcontainers-nodejs/tree/main/examples), which is type-checked, linted and tested against real anvil nodes in CI. A fence links to its region: ````text ```ts snippet="examples/test/e2e/time-travel.e2e.test.ts#fast-forward" …copied from the region by `pnpm docs:sync`… ``` ```` "Tested in" under each sample links to its lines. ### Reference tables ← the library `` blocks are rendered from the built library: flags, error codes, enums, constants. ### What fails the build | Check | Where | |---|---| | a sample differs from its region, or a region/file is missing | `pnpm docs:unit` (sync check) and `docusaurus build` | | a code block is not linked (only `shell` / `bash` / `sh` / `text` may be) | same | | an example region is not shown on any page | `pnpm docs:unit` | | a generated table differs from the library | `pnpm docs:unit` | | a public API member, flag or error code is undocumented | `pnpm docs:unit` (API coverage) | | broken links or anchors | `docusaurus build` | | the built pages don't contain the synced samples | `pnpm docs:e2e` | | the examples behind the samples fail | `pnpm docs:e2e` (runs them against anvil) | ### Add or change a sample 1. Wrap the code in an example with `// #region my-sample`. 2. Reference it: `` ```ts snippet="examples/#my-sample" `` (empty body). 3. Run `pnpm docs:sync`, then `pnpm docs:unit`. Scripts: [`docs/README.md`](https://github.com/hella-labs/foundryanvil-testcontainers-nodejs/blob/main/docs/README.md). --- ## Validation model | When | What | Error | |---|---|---| | setter call | value types, ranges and formats (ports, hex, mnemonics, URLs, headers, paths) | `AnvilConfigurationError` (`flag`) | | setter call | conflicts with flags already set | `AnvilConfigurationError` (`flag`, `relatedFlags`) | | `withExtraArgs()` | known flags must use the fluent API | `AnvilConfigurationError` | | `validate()` / `build()` / `prepare()` / `start()` | dependencies between flags, hardfork family | `AnvilConfigurationError` (one listing every problem) | | `prepare()` / `start()` | host files exist and are files | `AnvilConfigurationError` | | test client setter | setting values | `AnvilTestClientConfigurationError` (`setting`) | | `prepare()` / `start()` / `createTestClient()` | test client vs. anvil flags | `AnvilTestClientConfigurationError` (`setting`, `flag`, `relatedFlags`) | | `start()` | anvil exits, never answers, Docker fails | `AnvilStartupError` (`command`, `logs`) | Everything up to `prepare()` runs without Docker ([unit-test it](../tasks/test-suites/catch-misconfiguration.md)). ### Where the rules come from The [flag registry](../reference/flag-rules.md) mirrors `anvil --help`. The end-to-end suite runs every flag and every pair through anvil's own parser, expecting the same verdict, and boots every flag and hardfork. A few rules are stricter than anvil where it ignores a flag. Newer flags: `withExtraArgs()`. Related: [Errors](../reference/errors.md). --- ## Install ```shell pnpm add -D @hellaweb3/foundryanvil-testcontainers-nodejs # npm install -D … / yarn add -D … ``` - Node.js ≥ 22. - A Docker-compatible runtime ([or none](run-without-docker.md)). - A runner with `beforeAll` / `afterAll`: Jest, Vitest, Mocha, Jasmine. Add `viem` yourself when your code imports it. ESM, CommonJS and types are included. The first start pulls `DEFAULT_ANVIL_IMAGE`. ### Concepts - [Runtimes: Docker and local binaries](../concepts/runtimes.md) --- ## Quick start A complete test file: ```ts snippet="examples/test/e2e/quick-start.e2e.test.ts#quick-start" import { AnvilContainer, AnvilOptions, Hardfork, useAnvil, } from "@hellaweb3/foundryanvil-testcontainers-nodejs"; import { parseEther } from "viem"; const options = new AnvilOptions().account .withAccounts(5) .withBalance(1_000) // ETH per dev account .evm.withChainId(1337) .withHardfork(Hardfork.Cancun) .logs.quiet(); // Starts in beforeAll, stops in afterAll, restores the state after every test. const anvil = useAnvil( new AnvilContainer(options).withTestClient((client) => client.withAccount(0)), ); it("sends Ether", async () => { const [, bob] = await anvil.addresses(); // No `account` needed: dev account 0 is the typed default signer. const receipt = await anvil.confirm( anvil.testClient.sendTransaction({ to: bob, value: parseEther("1") }), ); expect(receipt.status).toBe("success"); expect(await anvil.testClient.getChainId()).toBe(1337); }); it("manipulates the chain fluently", async () => { const whale = "0x1111111111111111111111111111111111111111"; await anvil.cheats .setBalanceEther(whale, 1_000) .impersonate(whale) .increaseTime({ days: 7 }) .mine(); expect(await anvil.getBalance(whale)).toBe(parseEther("1000")); }); ``` - `AnvilOptions`: anvil's flags, validated as set. - `withAccount(0)`: dev account 0 signs by default. - `useAnvil()`: start, reset after each test, stop. - `confirm()`: the receipt; throws if reverted. - `cheats`: queued state changes, run when awaited. Next: - [Deploy fixtures once per file](../tasks/test-suites/share-a-node.md) - [Fund and impersonate accounts](../tasks/accounts/impersonate-accounts.md) - [Fast-forward time](../tasks/time-and-blocks/travel-in-time.md) ### Concepts - [Architecture: node, test client, cheats](../concepts/architecture.md) - [How per-test isolation works](../concepts/isolation.md) --- ## Run in CI GitHub Actions runners (`ubuntu-latest`) have Docker: nothing to configure. ```shell pnpm test ``` - **Timeouts.** The first start pulls the image: `useAnvil()` allows 120 s; for manual starts raise the hook timeout and `withStartupTimeout()`: ```ts snippet="examples/test/e2e/lifecycle.e2e.test.ts#manual-lifecycle" let anvil: StartedAnvilContainer; beforeAll(async () => { anvil = await new AnvilContainer(new AnvilOptions().logs.quiet()) .withStartupTimeout(120_000) // first run: image pull .start(); }, 120_000); afterAll(async () => { await anvil?.stop(); }); it("uses the started node", async () => { expect(await anvil.testClient.getBlockNumber()).toBe(0n); }); ``` - **Parallelism.** Each Jest worker's file gets its own node and port. - **Pin the image** for reproducibility: `new AnvilContainer(options, "ghcr.io/foundry-rs/foundry:")`. - **Forks** read the upstream URL from a secret, e.g. `process.env.MAINNET_RPC_URL`. Example: this repository's [`main.yml`](https://github.com/hella-labs/foundryanvil-testcontainers-nodejs/blob/main/.github/workflows/main.yml). ### Concepts - [Performance: fast suites](../concepts/performance.md) - [Runtimes: Docker and local binaries](../concepts/runtimes.md) --- ## Run without Docker Override `AnvilContainer.startRuntime()` to run anvil elsewhere. The examples' local runtime spawns the `anvil` binary on a free port: ```ts snippet="examples/test/support/local-anvil.ts#local-container" /** * An `AnvilContainer` that runs anvil as a local process. Same API, same * validation and the same started node type, without Docker. */ export class LocalAnvilContainer< TAccount extends Account | undefined = undefined, > extends AnvilContainer { protected override startRuntime(): Promise { return startLocal(this.prepare(), this.startupTimeoutMs ?? 60_000); } } ``` Use `new LocalAnvilContainer(options)`, or route every container to it from a setup file (the examples' `--no-docker` mode): ```ts snippet="examples/test/support/setup-runtime.ts#use-local-runtime" type WithRuntime = { startRuntime: unknown }; /** Routes `AnvilContainer.startRuntime()` to the local runtime. */ export function useLocalRuntime(): void { (AnvilContainer.prototype as unknown as WithRuntime).startRuntime = ( LocalAnvilContainer.prototype as unknown as WithRuntime ).startRuntime; } if (E2E_MODE === "local") useLocalRuntime(); ``` Copy [`local-anvil.ts`](https://github.com/hella-labs/foundryanvil-testcontainers-nodejs/blob/main/examples/test/support/local-anvil.ts); get a binary from `@foundry-rs/anvil` or `foundryup`: ```shell npm install -D @foundry-rs/anvil ``` :::warning Local testing only It skips the container (image, ports, file copies): run CI in Docker. Files copied *out* (`withDumpState()`, `withState()`, `withConfigOut()`) aren't supported; use [`dumpStateToFile()`](../tasks/state/save-and-load-state.md). ::: ### Concepts - [Runtimes: Docker and local binaries](../concepts/runtimes.md) - [Startup, readiness and file transfers](../concepts/startup-and-files.md) --- ## Introduction A [Foundry Anvil](https://getfoundry.sh/anvil/overview) node in Docker per test file, with a [viem](https://viem.sh) test client already bound to it. - **Every anvil flag**, validated as you set it. - **One client for everything**: viem's test, public and wallet actions, anvil extras and fluent `cheats`. - **Per-test isolation in milliseconds** with snapshots. New here? Start with the [quick start](get-started/quick-start.md). ### Find your task | I want to… | Go to | |---|---| | Start a node per test file and reset it between tests | [Share a node](tasks/test-suites/share-a-node.md), [Isolate tests](tasks/test-suites/isolate-tests.md) | | Use, fund or impersonate accounts | [Accounts and signing](tasks/accounts/use-dev-accounts.md) | | Send transactions, assert reverts, simulate | [Transactions and contracts](tasks/transactions/send-transactions.md) | | Move time, control mining and block contents | [Time and blocks](tasks/time-and-blocks/travel-in-time.md) | | Mock contracts, save or load state, boot from genesis | [State and mocks](tasks/state/mock-contracts.md) | | Test against mainnet state | [Forking](tasks/forking/fork-a-chain.md) | | React to events | [Events](tasks/events/watch-events.md) | | Configure the chain, EVM, RPC server, logs or client | [Configure the node](tasks/configure/chain.md) | | Find out why something failed | [Debug](tasks/debugging/trace-transactions.md) | | Look up a method, flag or error | [Reference](reference/index.md) | | Understand how it works | [Concepts](concepts/index.md) | ### How to read the samples Every sample is a tested `#region` of [`examples/`](https://github.com/hella-labs/foundryanvil-testcontainers-nodejs/tree/main/examples), linked under the sample. - `anvil` (or `node`, `fork`…) is a started node, usually from [`useAnvil()`](tasks/test-suites/share-a-node.md). - `expect` and `it` are Jest's; any runner works. - `deployToken`, `mint`, `balanceOf`, `exampleToken`, `expectRevert` and `triggerUntil` are helpers from [`examples/src`](https://github.com/hella-labs/foundryanvil-testcontainers-nodejs/tree/main/examples/src). --- ## anvil extras (AnvilActions) Part of `testClient`; add them to your own clients with `client.extend(anvilActions)` ([sample](../tasks/transactions/read-contracts.md#your-own-clients)). | Action | anvil RPC | `cheats` step | Notes | |---|---|---|---| | `addBalance({ address, value })` | `anvil_addBalance` | `addBalance()` | adds wei | | `dealErc20({ token, address, amount })` | `anvil_dealERC20` | `dealErc20()` | ERC-20 balance of standard tokens | | `setErc20Allowance({ token, owner, spender, amount })` | `anvil_setERC20Allowance` | `setErc20Allowance()` | | | `setChainId({ chainId })` | `anvil_setChainId` | `setChainId()` | the container's `chainId`, `chain` and clients follow | | `setTime({ timestamp })` | `evm_setTime` | `setTime()` | later blocks continue from it | | `getIntervalMining()` | `anvil_getIntervalMining` | – | seconds, `undefined` when off | | `setAutoImpersonate(enabled)` | `anvil_autoImpersonateAccount` | `setAutoImpersonate()` | | | `dropAllTransactions()` | `anvil_dropAllTransactions` | `dropAllTransactions()` | | | `removePoolTransactions({ address })` | `anvil_removePoolTransactions` | `removePoolTransactions()` | all pending transactions of a sender | | `rollback({ depth? })` | `anvil_rollback` | `rollback()` | removes the last blocks (default 1) | | `reorg({ depth, transactions? })` | `anvil_reorg` | – | `ReorgTransaction`: `{ transaction, block }` | | `getNodeInfo()` | `anvil_nodeInfo` | – | `AnvilNodeInfo` | | `getMetadata()` | `anvil_metadata` | – | `AnvilMetadata` | | `reset(AnvilResetParameters?)` | `anvil_reset` | `reset()` | see below | | `revert({ id })` | `evm_revert` | – | see below | | `confirmTransaction(ConfirmTransactionParameters)` | – | – | receipt; mines first when automine is off; throws `AnvilTransactionRevertedError` unless `throwOnRevert: false` | ### `reset` and `revert` differ from viem - **`reset()`** returns to genesis, or to the fork block on a fork (viem's fails, a bare `anvil_reset` detaches the fork); `{ blockNumber }` / `{ jsonRpcUrl }` re-fork. Discards snapshots. - **`revert({ id })`** throws `SNAPSHOT_NOT_FOUND` for unknown or used ids (viem ignores anvil's `false`). Types: `AnvilResetParameters` (`blockNumber?`, `jsonRpcUrl?`), `ConfirmTransactionParameters` (`hash`, `throwOnRevert?`, `timeout?`), `ReorgTransaction`, `AnvilNodeInfo`, `AnvilMetadata`. Anything else: [`anvil.rpc(method, params)`](../tasks/debugging/call-any-rpc-method.md). --- ## AnvilContainer `AnvilContainer` extends Testcontainers' `GenericContainer`: every builder stays available (`withStartupTimeout`, `withNetwork`, `withNetworkAliases`, `withEnvironment`, …). `TAccount` is the test client's default account type. | Member | Description | |---|---| | `new AnvilContainer(options?, image?)` | anvil defaults and `DEFAULT_ANVIL_IMAGE` when omitted | | `withTestClient(options \| (c) => c…)` | configures `StartedAnvilContainer.testClient` ([`TestClientOptions`](test-client-options.md)); returns a container typed with the default account | | `testClientOptions` | the test client settings in use | | `anvilOptions` | the `AnvilOptions` in use | | `withArtifactsDir(dir)` | base directory of `contractAbi()` / `contractBytecode()` (default `/test/artifacts`) | | `prepare()` | validates anvil **and** test client options and applies entrypoint, command, port, file copies and wait strategy; returns the `AnvilConfiguration`; needs no Docker | | `start()` | prepares, starts, waits for JSON-RPC, sets up the test client; throws `AnvilConfigurationError` before Docker, `AnvilStartupError` after | | `startRuntime()` | *protected* extension point that starts the prepared container; override it to run anvil elsewhere ([Run without Docker](../get-started/run-without-docker.md)) | | `withWaitStrategy(strategy)` | replaces the default `AnvilReadyWaitStrategy` (rarely needed) | `AnvilReadyWaitStrategy(port, command)` probes JSON-RPC until anvil answers and fails fast with anvil's output when it exits. ```ts snippet="examples/test/unit/configuration.test.ts#container-getters" const options = new AnvilOptions().mining.withBlockTime(2); const container = new AnvilContainer(options).withTestClient((client) => client.withAccount(0), ); expect(container.anvilOptions).toBe(options); expect(container.testClientOptions.build().account?.kind).toBe("index"); expect(container.prepare().command.join(" ")).toBe( "anvil --host 0.0.0.0 --block-time 2", ); ``` Tasks: [Share a node](../tasks/test-suites/share-a-node.md), [Manage the lifecycle](../tasks/test-suites/manage-the-lifecycle.md). --- ## AnvilOptions Every anvil flag, by group. Samples: [quick start](../get-started/quick-start.md), [compose and inspect options](../tasks/configure/compose-options.md). - Groups (`.account`, `.evm`, …) share one configuration and chain freely. - Setters throw `AnvilConfigurationError` at once; dependencies are checked by `validate()` / `build()` / `start()`. - Boolean setters take `enabled = true`; numeric ones `number | bigint`. - `reset()` removes a group's flags. Lists are *generated* from the flag registry; descriptions are anvil's. ### Account - `withAccounts()` → `--accounts` (`-a`)\ Number of dev accounts to generate and configure. - `withBalance()` → `--balance`\ The balance of every dev account in Ether. - `withDerivationPath()` → `--derivation-path`\ Sets the derivation path of the child key to be derived. - `withMnemonic()` → `--mnemonic` (`-m`)\ BIP39 mnemonic phrase used for generating accounts.\ **Rules:** ⟂ `--mnemonic-random`, `--mnemonic-seed-unsafe`. - `withRandomMnemonic()` → `--mnemonic-random`\ Automatically generates a BIP39 mnemonic phrase, and derives accounts from it.\ **Rules:** ⟂ `--mnemonic`, `--mnemonic-seed-unsafe`. - `withMnemonicSeedUnsafe()` → `--mnemonic-seed-unsafe`\ Generates a BIP39 mnemonic phrase from a given seed.\ **Rules:** ⟂ `--mnemonic`, `--mnemonic-random`. - `autoImpersonate()` → `--auto-impersonate` (`--auto-unlock`)\ Enables automatic impersonation on startup. Balance in whole Ether; one mnemonic source at a time. ### EVM - `withHardfork()` → `--hardfork`\ The EVM hardfork to use. - `withBlockBaseFeePerGas()` → `--block-base-fee-per-gas` (`--base-fee`)\ The base fee in a block. - `withChainId()` → `--chain-id` (`--chain`)\ The chain ID. - `withCodeSizeLimit()` → `--code-size-limit`\ EIP-170: Contract code size limit in bytes.\ **Rules:** ⟂ `--disable-code-size-limit`. - `disableBlockGasLimit()` → `--disable-block-gas-limit` (`--no-gas-limit`)\ Disable the `call.gas_limit <= block.gas_limit` constraint.\ **Rules:** ⟂ `--gas-limit`. - `disableCodeSizeLimit()` → `--disable-code-size-limit`\ Disable EIP-170: Contract code size limit.\ **Rules:** ⟂ `--code-size-limit`. - `disableMinPriorityFee()` → `--disable-min-priority-fee` (`--no-priority-fee`)\ Disable the enforcement of a minimum suggested priority fee. - `withGasLimit()` → `--gas-limit` (`--block-gas-limit`)\ The block gas limit.\ **Rules:** ⟂ `--disable-block-gas-limit`. - `withGasPrice()` → `--gas-price`\ The gas price. - `autoImpersonate()` → `--auto-impersonate` (`--auto-unlock`)\ Enables automatic impersonation on startup. - `disableDefaultCreate2Deployer()` → `--disable-default-create2-deployer` (`--no-create2`)\ Disable the default create2 deployer. - `disablePoolBalanceChecks()` → `--disable-pool-balance-checks`\ Disable pool balance checks. - `withMemoryLimit()` → `--memory-limit`\ The memory limit per EVM execution in bytes. - `withPrintTraces()` → `--print-traces` (`--enable-trace-printing`)\ Enable printing of traces for executed transactions and `eth_call` to stdout. - `withStepsTracing()` → `--steps-tracing` (`--tracing`)\ Enable steps tracing used for debug calls returning geth-style traces. Fees in wei, limits in gas or bytes; `OpHardfork` needs `network.withOptimism()`. ### Fork - `withComputeUnitsPerSecond()` → `--compute-units-per-second` (`--cups`)\ Sets the number of assumed available compute units per second for this provider.\ **Rules:** needs `--fork-url`. - `withForkUrl()` → `--fork-url` (`-f`, `--rpc-url`)\ Fetch state over a remote endpoint instead of starting from an empty state. - `withForkBlockNumber()`, `withForkUrl()` → `--fork-block-number`\ Fetch state from a specific block number over a remote endpoint.\ **Rules:** ⟂ `--fork-transaction-hash`; needs `--fork-url`. - `withForkChainId()` → `--fork-chain-id`\ Specify chain id to skip fetching it from remote endpoint (offline-start mode).\ **Rules:** needs `--fork-url`; needs one of `--fork-block-number`, `--fork-transaction-hash`. - `withForkHeader()`, `withForkHeaders()` → `--fork-header`\ Headers to use for the rpc client, e.g. "User-Agent: test-agent".\ **Rules:** needs `--fork-url`. - `withForkRetryBackoff()` → `--fork-retry-backoff`\ Initial retry backoff on encountering errors.\ **Rules:** needs `--fork-url`. - `withForkTransactionHash()` → `--fork-transaction-hash`\ Fetch state from after a specific transaction hash has been applied over a remote endpoint.\ **Rules:** ⟂ `--fork-block-number`; needs `--fork-url`. - `noRateLimit()` → `--no-rate-limit` (`--no-rpc-rate-limit`)\ Disables rate limiting for this node's provider.\ **Rules:** needs `--fork-url`. - `noStorageCaching()` → `--no-storage-caching`\ Explicitly disables the use of RPC caching.\ **Rules:** needs `--fork-url`. - `withRetries()` → `--retries`\ Number of retry requests for spurious networks (timed out requests).\ **Rules:** needs `--fork-url`. - `withTimeout()` → `--timeout`\ Timeout in ms for requests sent to remote JSON-RPC server in forking mode.\ **Rules:** needs `--fork-url`. Every option needs `withForkUrl()`; URLs resolve inside the container (`host.docker.internal` for the host). Negative blocks are relative to the latest; times in ms. `withForkTransactionHash()` forks *before* the transaction ([tested](../tasks/forking/fork-a-chain.md#choose-the-fork-point)), despite anvil's description. ### Mining - `withBlockTime()`, `withMixedMining()` → `--block-time` (`-b`, `--blockTime`)\ Block time in seconds for interval mining.\ **Rules:** ⟂ `--no-mining`. - `withMixedMining()` → `--mixed-mining`\ Enable mixed mining (interval mining plus on-demand/automine).\ **Rules:** needs `--block-time`. - `withNoMining()` → `--no-mining` (`--no-mine`)\ Disable auto and interval mining, and mine on demand instead.\ **Rules:** ⟂ `--block-time`. - `withBlockNumber()` → `--number`\ The number of the genesis block. - `withSlotsInAnEpoch()` → `--slots-in-an-epoch`\ Slots in an epoch. `withAutoMining()` removes the other mining modes (automine is the default). ### Logs - `withColor()` → `--color`\ The color of the log messages.\ **Rules:** ⟂ `--json`. - `jsonLogFormat()` → `--json`\ Format log messages as JSON.\ **Rules:** ⟂ `--color`, `--md`, `--quiet`. - `withMarkdownFormat()` → `--md`\ Format log messages as Markdown.\ **Rules:** ⟂ `--json`. - `quiet()` → `--quiet` (`-q`)\ Do not print log messages.\ **Rules:** ⟂ `--json`, `--verbosity`. - `verboseLogs()` → `--verbosity` (`-v`)\ Verbosity level of the log messages.\ **Rules:** ⟂ `--quiet`. - `disableConsoleLog()` → `--disable-console-log` (`--no-console-log`)\ Disable printing of `console.log` invocations to stdout. `quiet()` doesn't affect readiness, but hides the keys of random mnemonics. ### Network - `withCelo()` → `--celo`\ Enable Celo network features.\ **Rules:** ⟂ `--optimism`. - `withOptimism()` → `--optimism`\ Enable Optimism network features.\ **Rules:** ⟂ `--celo`. ### Server - `withIpc()` → `--ipc` (`--ipcpath`)\ Launch an ipc server at the given path or default path = `/tmp/anvil.ipc`. - `withThreads()` → `--threads` (`-j`, `--jobs`)\ Number of threads to use. Specifying 0 defaults to the number of logical cores. - `withPort()` → `--port` (`-p`)\ Port number to listen on. - `withAllowOrigin()` → `--allow-origin`\ The cors `allow_origin` header.\ **Rules:** ⟂ `--no-cors`. - `withCachePath()` → `--cache-path`\ Path to the cache directory where persisted states are stored. - `noCors()` → `--no-cors`\ Disable CORS.\ **Rules:** ⟂ `--allow-origin`. - `noRequestSizeLimit()` → `--no-request-size-limit`\ Disable the default request body size limit. Ports and paths are inside the container; the host port is mapped. ### State - `withConfigOut()` → `--config-out`\ Writes output of `anvil` as json to user-specified file. - `withDumpState()` → `--dump-state`\ Dump the state and block environment of chain on exit to the given file.\ **Rules:** ⟂ `--init`, `--state`. - `withInit()` → `--init`\ Initialize the genesis block with the given `genesis.json` file.\ **Rules:** ⟂ `--dump-state`, `--load-state`, `--preserve-historical-states`, `--state`. - `withLoadState()` → `--load-state`\ Initialize the chain from a previously saved state snapshot.\ **Rules:** ⟂ `--init`, `--state`. - `withMaxPersistedStates()` → `--max-persisted-states`\ Max number of states to persist on disk.\ **Rules:** ⟂ `--prune-history`. - `withOrder()` → `--order`\ How transactions are sorted in the mempool. - `withPreserveHistoricalStates()` → `--preserve-historical-states`\ Preserve historical state snapshots when dumping the state.\ **Rules:** ⟂ `--init`; needs one of `--dump-state`, `--state`. - `withPruneHistory()` → `--prune-history`\ Don't keep full chain history. If a number argument is specified, at most this number of states is kept in memory.\ **Rules:** ⟂ `--max-persisted-states`. - `withStateInterval()` → `--state-interval` (`-s`)\ Interval in seconds at which the state and block environment is to be dumped to disk.\ **Rules:** needs one of `--dump-state`, `--state`. - `withState()` → `--state`\ This is an alias for both --load-state and --dump-state.\ **Rules:** ⟂ `--dump-state`, `--init`, `--load-state`. - `withTimestamp()` → `--timestamp`\ The timestamp of the genesis block. - `withTransactionBlockKeeper()` → `--transaction-block-keeper`\ Number of blocks with transactions to keep in memory. File options take host paths (copied in / out) or `containerPath("/abs")`. ### Managed flags Set by the container: - `--host`: The hosts the server will listen on. ### Composition and inspection On `AnvilOptions` and every group: | Member | Description | |---|---| | `account`, `evm`, `fork`, `mining`, `logs`, `network`, `server`, `state` | the option groups (same configuration) | | `clone()` | independent deep copy (flags, file transfers, extra args) | | `apply(...presets)` | runs `(options: AnvilOptions) => unknown` presets | | `root()` | the `AnvilOptions` view of this configuration | | `unset(...flags)` | removes flags (and their file transfers); no-op when absent | | `reset()` | groups only: removes the group's flags | | `withExtraArgs(...args)` | raw arguments for flags newer than the library; known flags are rejected | | `has(flag)` / `get(flag)` | whether a flag is set / its raw value | | `flags()` | configured flags in canonical order (without managed flags) | | `toArgs()` / `entryPoint` / `toCommand()` / `toJSON()` | rendered arguments, `["anvil", …]`, a shell-quoted command line, `{ command, flags }` | | `problems()` | every dependency problem, without throwing | | `validate()` | throws one `AnvilConfigurationError` listing every problem | | `build()` | validates and returns a frozen `AnvilConfiguration` | Arguments render in `anvil --help` order. `AnvilConfiguration` has `args`, `command`, `port`, `chainId`, `accounts`, `mnemonic`, `derivationPath`, `quiet`, `forking`, `fileImports` (`FileImport`), `fileExports` (`FileExport`) and `flags` (`FlagValue` by `AnvilFlag`). Tasks: [Compose and inspect options](../tasks/configure/compose-options.md), [Catch misconfiguration](../tasks/test-suites/catch-misconfiguration.md). --- ## Cheats (AnvilCheats) Each `anvil.cheats` starts a chain: steps are validated when added and run in order, once, when awaited. A failing step rejects with `CHEAT_FAILED`. ```ts snippet="examples/test/e2e/cheats.e2e.test.ts#cheat-plan" const chain = anvil.cheats.setBalanceEther(ALICE, 1.5).mine(2); expect(chain.plan).toEqual([`setBalanceEther(${ALICE}, 1.5)`, "mine(2)"]); await chain.run(); // same as `await chain`; a chain runs once expect(await anvil.getBalance(ALICE)).toBe(parseEther("1.5")); ``` | Step | anvil RPC | Arguments | |---|---|---| | `setBalance(address, wei)` | `anvil_setBalance` | | | `setBalanceEther(address, ether)` | `anvil_setBalance` | `"1.5"` or `100` | | `addBalance(address, wei)` | `anvil_addBalance` | | | `dealErc20(token, address, amount)` | `anvil_dealERC20` | token units | | `setErc20Allowance(token, owner, spender, amount)` | `anvil_setERC20Allowance` | | | `setCode(address, bytecode)` | `anvil_setCode` | runtime code; `"0x"` removes it | | `setNonce(address, nonce)` | `anvil_setNonce` | | | `setStorageAt(address, slot, value)` | `anvil_setStorageAt` | slot number or hex; `bigint` value encoded to 32 bytes | | `impersonate(address)` / `stopImpersonating(address)` | `anvil_impersonateAccount` / `anvil_stopImpersonatingAccount` | | | `setAutoImpersonate(enabled)` | `anvil_autoImpersonateAccount` | | | `mine(blocks?, interval?)` | `anvil_mine` | default 1 block | | `setAutomine(enabled)` | `evm_setAutomine` | | | `setIntervalMining(duration)` | `evm_setIntervalMining` | `0` stops it | | `increaseTime(duration)` | `evm_increaseTime` | | | `setNextBlockTimestamp(timestamp)` | `evm_setNextBlockTimestamp` | | | `setTime(timestamp)` | `evm_setTime` | | | `setBlockTimestampInterval(duration)` / `removeBlockTimestampInterval()` | `anvil_setBlockTimestampInterval` / `anvil_removeBlockTimestampInterval` | | | `setCoinbase(address)` | `anvil_setCoinbase` | | | `setMinGasPrice(wei)` | `anvil_setMinGasPrice` | pre-London only | | `setNextBlockBaseFeePerGas(wei)` | `anvil_setNextBlockBaseFeePerGas` | | | `setBlockGasLimit(gas)` | `evm_setBlockGasLimit` | | | `dropTransaction(hash)` / `dropAllTransactions()` | `anvil_dropTransaction` / `anvil_dropAllTransactions` | | | `removePoolTransactions(address)` | `anvil_removePoolTransactions` | | | `setChainId(chainId)` | `anvil_setChainId` | the container follows | | `setRpcUrl(url)` | `anvil_setRpcUrl` | fork RPC URL | | `setLoggingEnabled(enabled)` | `anvil_setLoggingEnabled` | | | `reset(options?)` | `anvil_reset` | fixed version; clears snapshots | | `rollback(depth?)` | `anvil_rollback` | default 1 | | `loadState(state)` | `anvil_loadState` | | | `step(fn, label?)` | – | any `(client) => Promise` between cheats | | Execution | Description | |---|---| | `plan` | labels of the queued steps, e.g. `["mine(2)"]` | | `run()` | runs the steps; later calls return the same promise | | `then()` / `catch()` / `finally()` | a chain is a full promise (`PromiseLike`) | Durations: seconds or `{ weeks, days, hours, minutes, seconds }`; timestamps: seconds or a `Date`. Task: [Script state changes](../tasks/state/script-state-changes.md). --- ## Errors | Error | When | Fields | |---|---|---| | `AnvilConfigurationError` | invalid value, conflict, unmet dependency, missing host file | `flag`, `relatedFlags` | | `AnvilTestClientConfigurationError` | invalid test client setting, or one that contradicts the anvil options (before start); extends `AnvilConfigurationError` | `setting`, `flag`, `relatedFlags` | | `AnvilStartupError` | anvil exited / not ready / Docker failure / default account not resolvable | `command`, `logs`, `cause` | | `AnvilTestClientError` | runtime misuse or failure | `code`, `cause` | | `AnvilTransactionRevertedError` | `confirm()` / `confirmTransaction()` of a reverted transaction; extends `AnvilTestClientError` | `code`, `hash`, `receipt`, `reason` | ### `AnvilTestClientError` codes Generated from `ANVIL_TEST_CLIENT_ERROR_CODES` (type `AnvilTestClientErrorCode`): | `code` | Meaning | |---|---| | `CONTAINER_STOPPED` | the node was stopped; the client can no longer be used | | `SNAPSHOT_NOT_FOUND` | evm_revert target does not exist (already reverted, or cleared by reset / loadState) | | `NOT_STARTED` | useAnvil() handle used before beforeAll started the node | | `TEST_HOOKS_UNAVAILABLE` | useAnvil() found no beforeAll / afterAll hooks | | `ACCOUNT_UNAVAILABLE` | the configured default account could not be resolved on the node | | `TRANSACTION_REVERTED` | a transaction was mined but reverted | | `CHEAT_FAILED` | a step of an AnvilCheats chain failed | | `CHEATS_ALREADY_RUN` | an AnvilCheats chain was extended after it had run | ```ts snippet="examples/test/e2e/lifecycle.e2e.test.ts#after-stop" const anvil = await new AnvilContainer().start(); const client = anvil.testClient; await anvil.stop(); expect(anvil.isStopped).toBe(true); const error = await client.getBlockNumber().catch((e: unknown) => e); expect(error).toBeInstanceOf(AnvilTestClientError); expect((error as AnvilTestClientError).code).toBe("CONTAINER_STOPPED"); ``` viem's own errors (reverts, RPC errors) are thrown as they are: match them by `name`, not `instanceof` ([why](../tasks/transactions/assert-reverts.md)). --- ## Exports ```text import { … } from "@hellaweb3/foundryanvil-testcontainers-nodejs"; ``` ### Classes `AnvilOptions`, the option groups `AccountOptions`, `EvmOptions`, `ForkingOptions`, `LoggingOptions`, `MiningOptions`, `NetworkOptions`, `ServerOptions`, `StateOptions` (bases `OptionsView`, `OptionsGroup`), [`AnvilContainer`](anvil-container.md), [`StartedAnvilContainer`](started-anvil-container.md), [`AnvilReadyWaitStrategy`](anvil-container.md), [`TestClientOptions`](test-client-options.md), [`AnvilCheats`](cheats.md), and the [errors](errors.md). ### Functions | Function | Description | |---|---| | `useAnvil(container, settings?)` | [test lifecycle hooks](use-anvil.md) | | `anvilActions` | decorator adding the [anvil extras](anvil-actions.md) to any viem client | | `loadContractAbi(location, dir?)` | ABI from a plain array or a Foundry/Hardhat artifact | | `loadContractBytecode(location, dir?)` | bytecode from a hex `.bin` or an artifact's `bytecode` | | `containerPath(path)` / `isContainerPath(value)` | mark / detect a path inside the container (not copied) | | `durationToSeconds(duration)` / `timestampToSeconds(timestamp)` | the time conversions used by the helpers | | `getFlagSpec(flag)` / `isAnvilFlag(value)` / `groupFlags(group)` | flag registry lookups | ### Enums | `Hardfork` member | Value | |---|---| | `Hardfork.Frontier` | `"frontier"` | | `Hardfork.Homestead` | `"homestead"` | | `Hardfork.Dao` | `"dao"` | | `Hardfork.Tangerine` | `"tangerine"` | | `Hardfork.SpuriousDragon` | `"spuriousdragon"` | | `Hardfork.Byzantium` | `"byzantium"` | | `Hardfork.Constantinople` | `"constantinople"` | | `Hardfork.Petersburg` | `"petersburg"` | | `Hardfork.Istanbul` | `"istanbul"` | | `Hardfork.MuirGlacier` | `"muirglacier"` | | `Hardfork.Berlin` | `"berlin"` | | `Hardfork.London` | `"london"` | | `Hardfork.ArrowGlacier` | `"arrowglacier"` | | `Hardfork.GrayGlacier` | `"grayglacier"` | | `Hardfork.Paris` | `"paris"` | | `Hardfork.Shanghai` | `"shanghai"` | | `Hardfork.Cancun` | `"cancun"` | | `Hardfork.Prague` | `"prague"` | | `Hardfork.Osaka` | `"osaka"` | | `Hardfork.Latest` | `"latest"` | | `OpHardfork` member | Value | |---|---| | `OpHardfork.Bedrock` | `"bedrock"` | | `OpHardfork.Regolith` | `"regolith"` | | `OpHardfork.Canyon` | `"canyon"` | | `OpHardfork.Ecotone` | `"ecotone"` | | `OpHardfork.Fjord` | `"fjord"` | | `OpHardfork.Granite` | `"granite"` | | `OpHardfork.Holocene` | `"holocene"` | | `OpHardfork.Isthmus` | `"isthmus"` | | `OpHardfork.Interop` | `"interop"` | | `OpHardfork.Jovian` | `"jovian"` | | `Order` member | Value | |---|---| | `Order.Fees` | `"fees"` | | `Order.Fifo` | `"fifo"` | | `Color` member | Value | |---|---| | `Color.Auto` | `"auto"` | | `Color.Always` | `"always"` | | `Color.Never` | `"never"` | | `LogVerbosity` member | Value | |---|---| | `LogVerbosity.One` | `1` | | `LogVerbosity.Two` | `2` | | `LogVerbosity.Three` | `3` | | `LogVerbosity.Four` | `4` | | `LogVerbosity.Five` | `5` | ### Constants Generated from the package's exports: | Constant | Value | |---|---| | `ANVIL_EXECUTABLE` | `"anvil"` | | `ANVIL_HOST` | `"0.0.0.0"` | | `ANVIL_POLLING_INTERVAL_MS` | `25` | | `DEFAULT_ACCOUNT_COUNT` | `10` | | `DEFAULT_ANVIL_IMAGE` | `"ghcr.io/foundry-rs/foundry:v1.6.0-rc1"` | | `DEFAULT_ANVIL_PORT` | `8545` | | `DEFAULT_ARTIFACTS_DIR` | `"test/artifacts"` | | `DEFAULT_CHAIN_ID` | `31337` | | `DEFAULT_DERIVATION_PATH` | `"m/44'/60'/0'/0/"` | | `DEFAULT_GRACEFUL_STOP_TIMEOUT_MS` | `30000` | | `DEFAULT_MNEMONIC` | `"test test test test test test test test test test test junk"` | | `DEFAULT_POLLING_INTERVAL_MS` | `25` | | `DEFAULT_REQUEST_TIMEOUT_MS` | `10000` | | `DEFAULT_RETRY_COUNT` | `3` | | `DEFAULT_RETRY_DELAY_MS` | `150` | | `DEFAULT_USE_ANVIL_TIMEOUT_MS` | `120000` | | `MNEMONIC_WORD_COUNTS` | `[12,15,18,21,24]` | | `MULTICALL3_ADDRESS` | `"0xcA11bde05977b3631167028862bE2a173976CA11"` | Also: `ANVIL_FLAGS` / `ANVIL_FLAG_LIST` (every `FlagSpec`), the group flag lists `ACCOUNT_FLAGS`, `EVM_FLAGS`, `FORK_FLAGS`, `LOGGING_FLAGS`, `MINING_FLAGS`, `NETWORK_FLAGS`, `SERVER_FLAGS`, `STATE_FLAGS`, `CONTAINER_FILE_PATHS` and `ANVIL_TEST_CLIENT_ERROR_CODES` ([Errors](errors.md)). ### Types | Type | Description | |---|---| | `AnvilTestClient` | the [test client](test-client.md) | | `AnvilActions`, `AnvilResetParameters`, `ConfirmTransactionParameters`, `ReorgTransaction`, `AnvilNodeInfo`, `AnvilMetadata` | [anvil extras](anvil-actions.md) | | `TestClientConfiguration`, `TestClientTransport`, `TestClientBatchOptions`, `TestClientChainOverrides`, `TestClientAccountSpec`, `TestClientAccountInput` | [test client settings](test-client-options.md) | | `UseAnvilSettings`, `AnvilTestHooks`, `AnvilStartable` | [`useAnvil()`](use-anvil.md) | | `AnvilCheckpoint` | `{ id, restore() }` from `checkpoint()` | | `AnvilConfiguration`, `AnvilFlag`, `FlagSpec`, `FlagCategory`, `FlagValueKind`, `FlagValue`, `FileImport`, `FileExport`, `OptionsGroupName`, `StoreHandle`, `VerbosityLevel`, `Integerish` | [options and flags](anvil-options.md) | | `AnvilAccount` | `{ index, address, privateKey? }` from `accounts()` | | `Duration`, `Timestamp` | seconds or `{ weeks, days, hours, minutes, seconds }`; seconds or a `Date` | | `AnvilTestClientErrorCode` | [error codes](errors.md) | | `Address`, `HexString`, `TransactionHash`, `ContainerPath`, `FilePath` | hex strings and file paths | --- ## Flag rules - **Conflicts** throw `AnvilConfigurationError` when the second flag is set; swap with `unset()`. - **Dependencies** are checked by `validate()` / `build()` / `start()`. - `OpHardfork` needs `--optimism`; `Hardfork` conflicts with it. Generated from the flag registry: | Flag | Set by | Conflicts with | Requires | Note | |---|---|---|---|---| | `--block-time` | `mining.withBlockTime()`, `mining.withMixedMining()` | `--no-mining` | | | | `--dump-state` | `state.withDumpState()` | `--init`, `--state` | | | | `--init` | `state.withInit()` | `--dump-state`, `--load-state`, `--preserve-historical-states`, `--state` | | | | `--load-state` | `state.withLoadState()` | `--init`, `--state` | | | | `--mnemonic` | `account.withMnemonic()` | `--mnemonic-random`, `--mnemonic-seed-unsafe` | | | | `--max-persisted-states` | `state.withMaxPersistedStates()` | `--prune-history` | | | | `--mixed-mining` | `mining.withMixedMining()` | | `--block-time` | Stricter than anvil: anvil's parser skips this requirement when --no-mining is present; mixed mining without a block time is meaningless, so --block-time is always required. | | `--mnemonic-random` | `account.withRandomMnemonic()` | `--mnemonic`, `--mnemonic-seed-unsafe` | | | | `--mnemonic-seed-unsafe` | `account.withMnemonicSeedUnsafe()` | `--mnemonic`, `--mnemonic-random` | | | | `--no-mining` | `mining.withNoMining()` | `--block-time` | | | | `--preserve-historical-states` | `state.withPreserveHistoricalStates()` | `--init` | one of `--dump-state`, `--state` | Stricter than anvil: anvil accepts the flag without a dump target, where it has no effect. | | `--prune-history` | `state.withPruneHistory()` | `--max-persisted-states` | | | | `--state-interval` | `state.withStateInterval()` | | one of `--dump-state`, `--state` | Stricter than anvil: anvil accepts the flag without a dump target, where it has no effect. | | `--state` | `state.withState()` | `--dump-state`, `--init`, `--load-state` | | | | `--color` | `logs.withColor()` | `--json` | | | | `--json` | `logs.jsonLogFormat()` | `--color`, `--md`, `--quiet` | | | | `--md` | `logs.withMarkdownFormat()` | `--json` | | | | `--quiet` | `logs.quiet()` | `--json`, `--verbosity` | | | | `--verbosity` | `logs.verboseLogs()` | `--quiet` | | | | `--allow-origin` | `server.withAllowOrigin()` | `--no-cors` | | | | `--no-cors` | `server.noCors()` | `--allow-origin` | | | | `--compute-units-per-second` | `fork.withComputeUnitsPerSecond()` | | `--fork-url` | | | `--fork-block-number` | `fork.withForkBlockNumber()`, `fork.withForkUrl()` | `--fork-transaction-hash` | `--fork-url` | | | `--fork-chain-id` | `fork.withForkChainId()` | | `--fork-url`; one of `--fork-block-number`, `--fork-transaction-hash` | | | `--fork-header` | `fork.withForkHeader()`, `fork.withForkHeaders()` | | `--fork-url` | | | `--fork-retry-backoff` | `fork.withForkRetryBackoff()` | | `--fork-url` | | | `--fork-transaction-hash` | `fork.withForkTransactionHash()` | `--fork-block-number` | `--fork-url` | | | `--no-rate-limit` | `fork.noRateLimit()` | | `--fork-url` | | | `--no-storage-caching` | `fork.noStorageCaching()` | | `--fork-url` | | | `--retries` | `fork.withRetries()` | | `--fork-url` | | | `--timeout` | `fork.withTimeout()` | | `--fork-url` | | | `--code-size-limit` | `evm.withCodeSizeLimit()` | `--disable-code-size-limit` | | | | `--disable-block-gas-limit` | `evm.disableBlockGasLimit()` | `--gas-limit` | | | | `--disable-code-size-limit` | `evm.disableCodeSizeLimit()` | `--code-size-limit` | | | | `--gas-limit` | `evm.withGasLimit()` | `--disable-block-gas-limit` | | | | `--celo` | `network.withCelo()` | `--optimism` | | | | `--optimism` | `network.withOptimism()` | `--celo` | | | "Stricter than anvil": anvil accepts the combination but ignores it. Every rule is verified against the real binary. Tasks: [Catch misconfiguration in unit tests](../tasks/test-suites/catch-misconfiguration.md). --- ## API reference | API | What it is | |---|---| | [`AnvilOptions`](anvil-options.md) | fluent, validated configuration of every anvil flag, in groups (`.account`, `.evm`, `.fork`, `.mining`, `.logs`, `.network`, `.server`, `.state`) | | [Flag rules](flag-rules.md) | conflicts and dependencies between flags | | [`AnvilContainer`](anvil-container.md) | the Testcontainers module: options + test client settings → a started node | | [`StartedAnvilContainer`](started-anvil-container.md) | a running node: test client, cheats, account/transaction/time/state helpers | | [Test client](test-client.md) | `AnvilTestClient`: every viem test, public and wallet action, bound to the node | | [anvil extras](anvil-actions.md) | `AnvilActions`: anvil RPC methods viem doesn't wrap, strict `reset` / `revert` | | [Cheats](cheats.md) | `AnvilCheats`: fluent, awaitable chains of state changes | | [`TestClientOptions`](test-client-options.md) | transport, polling, retries, batching, default account, chain metadata | | [`useAnvil()`](use-anvil.md) | test lifecycle hooks with per-test isolation | | [Errors](errors.md) | error classes and `AnvilTestClientError` codes | | [Exports](exports.md) | functions, enums, constants and types | Code samples for every member are on the [task pages](../intro.md); tables marked *generated* are produced from the library itself by `pnpm docs:sync`. --- ## StartedAnvilContainer Returned by `AnvilContainer.start()` (and proxied by `useAnvil()`). `StartedAnvilContainer` extends Testcontainers' `AbstractStartedContainer` (`getHost()`, `getMappedPort()`, …). ### Test client | Member | Description | |---|---| | `testClient` | the [test client](test-client.md) (alias: `client`) | | `cheats` | a new [cheats](cheats.md) chain on `testClient` | | `testClientFor(account)` | a client with the same settings acting as an address (anvil signs) or a viem `LocalAccount` (`TestClientAccountInput`) | | `createTestClient(options)` | a client with its own [`TestClientOptions`](test-client-options.md), validated against the node | | `testClientConfiguration` | the test client settings in effect | ### Connection | Member | Description | |---|---| | `rpcUrl` / `wsUrl` | HTTP / WebSocket JSON-RPC URLs reachable from the host | | `chainId` / `chain` | chain id (follows `setChainId()`) and a viem `Chain` for your own clients | | `configuration` | the `AnvilConfiguration` anvil was started with | | `rpc(method, params?)` | raw JSON-RPC request | ### Accounts | Member | Description | |---|---| | `addresses()` | dev account addresses (`eth_accounts`), checksummed | | `accounts()` | `AnvilAccount[]`: `index`, `address`, `privateKey` when known | | `getBalance(address)` | balance in wei | | `setBalance(address, wei)` / `setBalanceEther(address, ether)` | `anvil_setBalance` | | `impersonate(address)` / `stopImpersonating(address)` | `anvil_impersonateAccount` / `anvil_stopImpersonatingAccount` | | `withImpersonation(address, fn)` | runs `fn(client)` while impersonating; always stops | | `setAutoImpersonate(enabled)` | `anvil_autoImpersonateAccount` | ### Transactions | Member | Description | |---|---| | `confirm(hash \| Promise, { throwOnRevert?, timeout? })` | receipt; mines first when automine is off; throws `AnvilTransactionRevertedError` | | `sendEthTransaction(from, to, ether)` | sends Ether (decimal string) and returns the receipt | | `deployContract(abi, bytecode, from, args?)` | deploys and returns the receipt (`contractAddress`) | ### Mining and time | Member | Description | |---|---| | `mine(blocks?, interval?)` | `anvil_mine` | | `getAutomine()` / `setAutomine(enabled)` | `anvil_getAutomine` / `evm_setAutomine` | | `setIntervalMining(duration)` | `evm_setIntervalMining`; `0` stops it | | `increaseTime(duration)` | `evm_increaseTime`; resolves to the total offset in seconds | | `setNextBlockTimestamp(timestamp)` | `evm_setNextBlockTimestamp` | | `latestTimestamp()` | timestamp of the latest block | ### Fees and limits | Member | Description | |---|---| | `setMinGasPrice(wei)` | `anvil_setMinGasPrice` (pre-London hardforks only) | | `setNextBlockBaseFeePerGas(wei)` | `anvil_setNextBlockBaseFeePerGas` | | `setBlockGasLimit(gas)` | `evm_setBlockGasLimit` | ### State | Member | Description | |---|---| | `snapshot()` / `revert(id)` | `evm_snapshot` / strict `evm_revert` (`SNAPSHOT_NOT_FOUND`) | | `withSnapshot(fn)` | runs `fn(client)` on a snapshot and always reverts | | `checkpoint()` | `AnvilCheckpoint`: `{ id, restore() }`, restorable any number of times | | `reset(options?)` | fixed `anvil_reset` ([anvil extras](anvil-actions.md)); discards snapshots | | `dumpState()` / `loadState(hex)` | `anvil_dumpState` / `anvil_loadState` | | `dumpStateToFile(path)` / `loadStateFromFile(path)` | the `--load-state` JSON format, host paths | ### Diagnostics | Member | Description | |---|---| | `nodeInfo()` / `metadata()` | `anvil_nodeInfo` / `anvil_metadata` | | `setLoggingEnabled(enabled)` | `anvil_setLoggingEnabled` | | `logText(tail?)` | anvil's output so far | ### Artifacts | Member | Description | |---|---| | `contractAbi(location)` / `contractBytecode(location)` | loaders relative to `withArtifactsDir()` | ### Lifecycle | Member | Description | |---|---| | `stop(options?)` | stops; with a state dump configured, gracefully (`DEFAULT_GRACEFUL_STOP_TIMEOUT_MS`) and copies it to the host; closes WebSockets | | `isStopped` | `true` after `stop()`; clients then reject with `CONTAINER_STOPPED` | | `removeStoppedContainer()` | *protected*: removes a container stopped with `remove: false`; override for non-Docker runtimes | Durations: seconds or `{ weeks, days, hours, minutes, seconds }`; timestamps: seconds or a `Date` ([`Duration`, `Timestamp`](exports.md#types)). --- ## TestClientOptions For `AnvilContainer.withTestClient()` and `createTestClient()`. ```ts snippet="examples/test/unit/configuration.test.ts#client-options" const client = new TestClientOptions() .withTransport("webSocket") // eth_subscribe-based watchers .withTimeout(5_000) // per request (default 10 000 ms) .withRetries(0, 50) // count, base delay in ms (default 3, 150) .withCacheTime(1_000) // reuse e.g. the block number for 1 s (default 0) .withPollingInterval(10) // watchers and receipt waits (default 25 ms) .withLocalAccount(0); // dev account 0, signed locally expect(client.build()).toMatchObject({ transport: "webSocket", timeout: 5_000, retryCount: 0, retryDelay: 50, account: { kind: "index", index: 0, signing: "local" }, }); // JSON-RPC batching needs HTTP: expect(() => client.clone().withBatch().build()).toThrow( AnvilTestClientConfigurationError, ); ``` | Method | Default | Notes | |---|---|---| | `withTransport(transport)` | `"http"` | `"http"` or `"webSocket"` (same port) | | `withPollingInterval(ms)` | 25 | watchers, receipt waits | | `withCacheTime(ms)` | 0 | viem's response cache (e.g. block number) | | `withTimeout(ms)` | 10 000 | per JSON-RPC request | | `withRetries(count, delayMs?)` | 3, 150 | exponential backoff | | `withBatch(batch?)` | off | `true`, `{ batchSize, wait }` or `false`; HTTP only | | `withAccount(index \| address, { impersonate? })` | none | default account **signed by anvil**; `impersonate: true` unlocks a non-dev address at startup | | `withLocalAccount(index \| privateKey \| LocalAccount)` | none | default account that **signs locally** | | `withoutAccount()` | – | removes the default account | | `withChain(overrides)` | `Anvil ()`, ETH | `name`, `nativeCurrency`, `contracts`, `blockExplorers`, `testnet` (`TestClientChainOverrides`) | | `withMulticall3(address?, blockCreated?)` | – | registers Multicall3 (`MULTICALL3_ADDRESS` by default) | | `clone()` | – | independent copy | | `build(configuration?)` | – | validated, frozen `TestClientConfiguration`; with an `AnvilConfiguration`, also checked against the flags | Setters validate at once; before start, settings are checked against the anvil options (`AnvilTestClientConfigurationError`): | Rule | Example | |---|---| | A dev account index must exist | `withAccount(5)` with `account.withAccounts(2)` | | Local signing needs a readable key | random / seeded mnemonic + `logs.quiet()` hides the key banner | | anvil must be able to sign for an address | not a dev account, no `{ impersonate: true }`, no `autoImpersonate()` | | Batching needs HTTP | `withBatch()` with `"webSocket"` | Types: `TestClientConfiguration`, `TestClientTransport`, `TestClientBatchOptions`, `TestClientChainOverrides`, `TestClientAccountSpec`. Defaults: `DEFAULT_POLLING_INTERVAL_MS`, `DEFAULT_REQUEST_TIMEOUT_MS`, `DEFAULT_RETRY_COUNT`, `DEFAULT_RETRY_DELAY_MS` ([Exports](exports.md#constants)). Task: [Configure the test client](../tasks/configure/test-client.md). --- ## Test client `anvil.testClient` is an `AnvilTestClient`: a viem test client (`mode: "anvil"`) with public, wallet and [anvil extra](anvil-actions.md) actions, bound to the node's chain. No response cache, 25 ms polling, and `eth_chainId` answered locally. | Layer | Use it for | |---|---| | `anvil.testClient` | everything viem can do: test actions, reads, simulations, watchers, writes, signing | | `anvil.cheats` | fluent chains of state changes ([cheats](cheats.md)) | | `anvil.*` helpers | accounts with keys, receipts, snapshots, state files ([`StartedAnvilContainer`](started-anvil-container.md)) | With a default account, actions compile without `account`. ### viem test actions | viem action | anvil RPC | `cheats` step | Notes | |---|---|---|---| | `dropTransaction` | `anvil_dropTransaction` | `dropTransaction()` | | | `dumpState` | `anvil_dumpState` | – | also `anvil.dumpState()` / `dumpStateToFile()` | | `getAutomine` | `anvil_getAutomine` | – | also `anvil.getAutomine()` | | `getTxpoolContent` | `txpool_content` | – | pending / queued transactions by sender and nonce | | `getTxpoolStatus` | `txpool_status` | – | `{ pending, queued }` counts | | `impersonateAccount` | `anvil_impersonateAccount` | `impersonate()` | also `anvil.impersonate()` / `withImpersonation()` | | `increaseTime` | `evm_increaseTime` | `increaseTime()` | durations in `cheats` / `anvil.increaseTime()` | | `inspectTxpool` | `txpool_inspect` | – | human-readable summary | | `loadState` | `anvil_loadState` | `loadState()` | merges a dump; discards snapshots | | `mine` | `anvil_mine` | `mine()` | blocks, optional interval | | `removeBlockTimestampInterval` | `anvil_removeBlockTimestampInterval` | `removeBlockTimestampInterval()` | | | `reset` | `anvil_reset` | `reset()` | **fixed** version, see [anvil extras](anvil-actions.md) | | `revert` | `evm_revert` | – | **strict**: throws `SNAPSHOT_NOT_FOUND` | | `sendUnsignedTransaction` | `eth_sendUnsignedTransaction` | – | send as any funded address | | `setAutomine` | `evm_setAutomine` | `setAutomine()` | | | `setBalance` | `anvil_setBalance` | `setBalance()` / `setBalanceEther()` | wei / Ether | | `setBlockGasLimit` | `evm_setBlockGasLimit` | `setBlockGasLimit()` | | | `setBlockTimestampInterval` | `anvil_setBlockTimestampInterval` | `setBlockTimestampInterval()` | fixed seconds between blocks | | `setCode` | `anvil_setCode` | `setCode()` | runtime bytecode ("etch") | | `setCoinbase` | `anvil_setCoinbase` | `setCoinbase()` | | | `setIntervalMining` | `evm_setIntervalMining` | `setIntervalMining()` | `0` turns it off | | `setLoggingEnabled` | `anvil_setLoggingEnabled` | `setLoggingEnabled()` | | | `setMinGasPrice` | `anvil_setMinGasPrice` | `setMinGasPrice()` | pre-London hardforks only | | `setNextBlockBaseFeePerGas` | `anvil_setNextBlockBaseFeePerGas` | `setNextBlockBaseFeePerGas()` | | | `setNextBlockTimestamp` | `evm_setNextBlockTimestamp` | `setNextBlockTimestamp()` | seconds, `bigint` or `Date` in `cheats` | | `setNonce` | `anvil_setNonce` | `setNonce()` | | | `setRpcUrl` | `anvil_setRpcUrl` | `setRpcUrl()` | fork RPC URL | | `setStorageAt` | `anvil_setStorageAt` | `setStorageAt()` | a `bigint` value is encoded in `cheats` | | `snapshot` | `evm_snapshot` | – | also `anvil.snapshot()` / `checkpoint()` | | `stopImpersonatingAccount` | `anvil_stopImpersonatingAccount` | `stopImpersonating()` | | ### Public and wallet actions All of [viem's](https://viem.sh/docs/actions/public/introduction): `readContract`, `simulateContract`, `multicall`, `getLogs`, `writeContract`, `signTypedData`, … Tasks: [Act as multiple users](../tasks/accounts/act-as-multiple-users.md), [Configure the test client](../tasks/configure/test-client.md). --- ## useAnvil() ```text useAnvil(container: AnvilStartable, settings?: UseAnvilSettings): StartedAnvilContainer ``` Registers `beforeAll` (start, `setup`, baseline), `afterEach` (restore) and `afterAll` (stop); returns a [`StartedAnvilContainer`](started-anvil-container.md) handle for tests and hooks. | Setting | Default | Description | |---|---|---| | `setup(node)` | – | runs once after start, before the baseline | | `isolation` | `"test"` | `"none"`: state carries over between tests | | `timeout` | `DEFAULT_USE_ANVIL_TIMEOUT_MS` (120 000) | start/stop hook timeout in ms | | `hooks` | globals | `AnvilTestHooks`: `{ beforeAll, afterAll, afterEach? }` | - `AnvilStartable`: anything with `start()`, e.g. `{ start: () => … }`. - Hooks: globals of Jest, Vitest (`globals: true`), Mocha, Jasmine, or `hooks`. - Errors: `NOT_STARTED` (used outside tests), `TEST_HOOKS_UNAVAILABLE`, `SNAPSHOT_NOT_FOUND` (a test called `reset()` / `loadState()`). ```ts snippet="examples/test/e2e/lifecycle.e2e.test.ts#explicit-hooks" // Pass the hooks yourself when your runner has no Jest-style globals. const anvil = useAnvil(new AnvilContainer(), { hooks: { beforeAll, afterAll, afterEach }, timeout: 120_000, // start/stop hook timeout }); ``` Tasks: [Share a node](../tasks/test-suites/share-a-node.md), [Manage the lifecycle](../tasks/test-suites/manage-the-lifecycle.md). --- ## Act as multiple users `testClientFor(account)` returns a client with the node's settings acting as that account — a dev or impersonated address (anvil signs) or a viem `LocalAccount` (signs locally): ```ts snippet="examples/test/e2e/multi-actor-flows.e2e.test.ts#actors" const asAlice = anvil.testClientFor(alice); const asBob = anvil.testClientFor(bob); await anvil.confirm( asAlice.writeContract({ address: token, abi: exampleToken.abi, functionName: "approve", args: [bob, parseEther("10")], }), ); const receipt = await anvil.confirm( asBob.writeContract({ address: token, abi: exampleToken.abi, functionName: "transferFrom", args: [alice, bob, parseEther("4")], }), ); const [transfer] = parseEventLogs({ abi: exampleToken.abi, logs: receipt.logs, eventName: "Transfer", }); expect(transfer.args).toEqual({ from: alice, to: bob, value: parseEther("4"), }); ``` ### A fresh, funded user per test ```ts snippet="examples/test/e2e/signing.e2e.test.ts#fresh-user" const user = privateKeyToAccount(generatePrivateKey()); await anvil.cheats.setBalanceEther(user.address, 1); const asUser = anvil.testClientFor(user); const [alice] = await anvil.addresses(); await anvil.confirm(asUser.sendTransaction({ to: alice, value: 1n })); expect( await anvil.testClient.getTransactionCount({ address: user.address }), ).toBe(1); ``` ### A client with its own settings `createTestClient(options)` builds a client with different settings (default account, transport, batching, cache…), validated against the node: ```ts snippet="examples/test/e2e/whales-and-impersonation.e2e.test.ts#whale-client" const whale = await anvil.createTestClient((client) => client.withAccount(WHALE, { impersonate: true }), ); await anvil.confirm( whale.writeContract({ address: vault, abi: timeLockVault.abi, functionName: "deposit", args: [parseEther("10")], }), ); ``` ### Concepts - [Signing: anvil-signed vs. locally signed](../../concepts/signing.md) - [Configure the test client](../configure/test-client.md) --- ## Fund accounts Write balances, allowances and nonces directly: no minting, no transfers. ### Ether and ERC-20 balances ```ts snippet="examples/test/e2e/whales-and-impersonation.e2e.test.ts#deal" await anvil.cheats .setBalance(WHALE, parseEther("100")) // wei (setBalanceEther takes Ether) .dealErc20(token, WHALE, parseEther("1000000")); expect(await anvil.getBalance(WHALE)).toBe(parseEther("100")); expect(await balanceOf(anvil.testClient, token, WHALE)).toBe( parseEther("1000000"), ); // The balance slot was written directly: totalSupply is untouched. expect( await anvil.testClient.readContract({ address: token, abi: exampleToken.abi, functionName: "totalSupply", }), ).toBe(0n); ``` `setBalance` takes wei; `setBalanceEther` takes Ether (`"1.5"`, `100`). `dealErc20` writes the balance slot of standard tokens (no mint, no `Transfer` event). ### Top up instead of overwrite ```ts snippet="examples/test/e2e/whales-and-impersonation.e2e.test.ts#add-balance" await anvil.cheats .setBalanceEther(WHALE, 1) .addBalance(WHALE, parseEther("2")); // adds instead of overwriting expect(await anvil.getBalance(WHALE)).toBe(parseEther("3")); ``` ### Allowances without `approve()` ```ts snippet="examples/test/e2e/whales-and-impersonation.e2e.test.ts#allowance" await anvil.cheats .setBalanceEther(WHALE, 1) .dealErc20(token, WHALE, parseEther("10")) // Allowances can be written directly too — no approve() transaction. .setErc20Allowance(token, WHALE, vault, parseEther("10")); ``` ### Nonces: predict deployment addresses ```ts snippet="examples/test/e2e/whales-and-impersonation.e2e.test.ts#set-nonce" await anvil.cheats.setNonce(WHALE, 100); const predicted = getContractAddress({ from: WHALE, nonce: 100n }); const receipt = await anvil.withImpersonation(WHALE, (client) => anvil.confirm( client.deployContract({ account: WHALE, abi: exampleToken.abi, bytecode: exampleToken.bytecode, args: ["Whale Token", "WHL"], }), ), ); expect(receipt.contractAddress?.toLowerCase()).toBe( predicted.toLowerCase(), ); expect(await anvil.testClient.getTransactionCount({ address: WHALE })).toBe( 101, ); ``` For non-standard tokens, write the storage slot yourself: [Mock contracts and storage](../state/mock-contracts.md). ### Concepts - Reference: [cheats](../../reference/cheats.md), [anvil extras](../../reference/anvil-actions.md) --- ## Impersonate any address Impersonate an address and anvil signs its transactions, no key needed. ### For a block of code ```ts snippet="examples/test/e2e/whales-and-impersonation.e2e.test.ts#with-impersonation" await anvil.withImpersonation(WHALE, (client) => anvil.confirm( client.writeContract({ account: WHALE, address: token, abi: exampleToken.abi, functionName: "transfer", args: [alice, parseEther("500")], }), ), ); ``` ### As part of a scripted scenario ```ts snippet="examples/test/e2e/whales-and-impersonation.e2e.test.ts#cheat-chain" await anvil.cheats .setBalanceEther(WHALE, 1) .dealErc20(token, WHALE, parseEther("10")) .impersonate(WHALE) .step( (client) => client.writeContract({ account: WHALE, address: token, abi: exampleToken.abi, functionName: "transfer", args: [alice, parseEther("10")], }), "whale pays alice", // label used in error messages ) .stopImpersonating(WHALE) .mine(); ``` ### As the default account of a client ```ts snippet="examples/test/e2e/whales-and-impersonation.e2e.test.ts#whale-client" const whale = await anvil.createTestClient((client) => client.withAccount(WHALE, { impersonate: true }), ); await anvil.confirm( whale.writeContract({ address: vault, abi: timeLockVault.abi, functionName: "deposit", args: [parseEther("10")], }), ); ``` ### Start and stop explicitly ```ts snippet="examples/test/e2e/whales-and-impersonation.e2e.test.ts#stop-impersonating" await anvil.impersonate(WHALE); await anvil.confirm( anvil.testClientFor(WHALE).sendTransaction({ to: alice, value: 1n }), ); await anvil.stopImpersonating(WHALE); await expect( anvil.testClientFor(WHALE).sendTransaction({ to: alice, value: 1n }), ).rejects.toThrow(); // anvil no longer signs for the whale ``` The same with viem's actions: ```ts snippet="examples/test/e2e/whales-and-impersonation.e2e.test.ts#viem-impersonation" await anvil.testClient.impersonateAccount({ address: WHALE }); try { await anvil.confirm( anvil.testClient.sendTransaction({ account: WHALE, to: alice, value: 1n, }), ); } finally { await anvil.testClient.stopImpersonatingAccount({ address: WHALE }); } ``` ### Every sender, always ```ts snippet="examples/test/e2e/whales-and-impersonation.e2e.test.ts#auto-impersonate" // Every sender is impersonated: no per-address impersonate() calls. const node = useAnvil( new AnvilContainer(new AnvilOptions().account.autoImpersonate()), ); it("sends from any address", async () => { const [alice] = await node.addresses(); await node.cheats.setBalanceEther(WHALE, 1); const receipt = await node.confirm( node.testClientFor(WHALE).sendTransaction({ to: alice, value: 1n }), ); expect(receipt.from.toLowerCase()).toBe(WHALE.toLowerCase()); }); it("can be switched off and on at runtime", async () => { const [alice] = await node.addresses(); await node.cheats.setBalanceEther(WHALE, 1).setAutoImpersonate(false); try { await expect( node.testClientFor(WHALE).sendTransaction({ to: alice, value: 1n }), ).rejects.toThrow(); } finally { await node.cheats.setAutoImpersonate(true); // node setting: restore it } await node.confirm( node.testClientFor(WHALE).sendTransaction({ to: alice, value: 1n }), ); }); ``` ### One transaction, no impersonation `sendUnsignedTransaction` sends as any funded address: ```ts snippet="examples/test/e2e/whales-and-impersonation.e2e.test.ts#unsigned" await anvil.confirm( anvil.testClient.sendUnsignedTransaction({ from: WHALE, to: alice, value: parseEther("1"), }), ); ``` Impersonation is a node setting: snapshots do not undo it. ### Concepts - [Signing: anvil-signed vs. locally signed](../../concepts/signing.md) - [How per-test isolation works](../../concepts/isolation.md) --- ## Sign locally like a wallet `withLocalAccount(index | privateKey | account)` makes the default account sign in the client, like a browser wallet: ```ts snippet="examples/test/e2e/signing.e2e.test.ts#local-account" // Dev account 1 signs locally (its key is derived from anvil's mnemonic). const anvil = useAnvil( new AnvilContainer().withTestClient((client) => client.withLocalAccount(1)), { // A contract to delegate EOAs to (EIP-7702), deployed once. setup: async (node) => void (delegate = await deployFixedPriceOracle(node.testClient)), }, ); ``` ### EIP-712 typed data ```ts snippet="examples/test/e2e/signing.e2e.test.ts#typed-data" const order = { domain: { name: "Example Exchange", version: "1", chainId: 31337, verifyingContract: "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", }, types: { Order: [ { name: "maker", type: "address" }, { name: "amount", type: "uint256" }, { name: "nonce", type: "uint256" }, ], }, primaryType: "Order", } as const; ``` ```ts snippet="examples/test/e2e/signing.e2e.test.ts#sign-typed-data" const message = { maker, amount: parseEther("1"), nonce: 0n }; const signature = await anvil.testClient.signTypedData({ ...order, message, }); expect( await verifyTypedData({ ...order, message, address: maker, signature }), ).toBe(true); expect( await recoverTypedDataAddress({ ...order, message, signature }), ).toBe(maker); ``` ### Messages and raw bytes ```ts snippet="examples/test/e2e/signing.e2e.test.ts#recover" const raw = await anvil.testClient.signMessage({ message: { raw: "0xdeadbeef" }, // sign bytes, not their hex text }); expect( await recoverMessageAddress({ message: { raw: "0xdeadbeef" }, signature: raw, }), ).toBe(anvil.testClient.account.address); ``` ### Sign offline, broadcast later ```ts snippet="examples/test/e2e/signing.e2e.test.ts#offline" const request = await anvil.testClient.prepareTransactionRequest({ to: alice, value: parseEther("1"), }); const raw = await anvil.testClient.signTransaction(request); const hash = await anvil.testClient.sendRawTransaction({ serializedTransaction: raw, }); ``` ### EIP-7702: delegate an account to a contract ```ts snippet="examples/test/e2e/signing.e2e.test.ts#eip7702-self" // The sender is also the authority: sign for the nonce after this transaction. const authorization = await anvil.testClient.signAuthorization({ contractAddress: delegate, executor: "self", }); await anvil.confirm( anvil.testClient.sendTransaction({ authorizationList: [authorization], to: account, data: encodeFunctionData({ abi: fixedPriceOracle.abi, functionName: "latestPrice", }), }), ); // The EOA now carries a delegation designator (0xef0100 ‖ delegate)… expect(await anvil.testClient.getCode({ address: account })).toBe( concat(["0xef0100", delegate]).toLowerCase(), ); // …and runs the delegate's code against its own storage. await anvil.cheats.setStorageAt(account, 0, 42n); expect( await anvil.testClient.readContract({ address: account, abi: fixedPriceOracle.abi, functionName: "latestPrice", }), ).toBe(42n); ``` Sponsored: the user signs, someone else pays: ```ts snippet="examples/test/e2e/signing.e2e.test.ts#eip7702-sponsored" // A brand-new user without any Ether signs the authorization… const user = privateKeyToAccount(generatePrivateKey()); const authorization = await anvil .testClientFor(user) .signAuthorization({ contractAddress: delegate }); // …and the default account submits (and pays for) it. await anvil.confirm( anvil.testClient.sendTransaction({ authorizationList: [authorization], to: user.address, data: encodeFunctionData({ abi: fixedPriceOracle.abi, functionName: "latestPrice", }), }), ); expect(await anvil.getBalance(user.address)).toBe(0n); expect(await anvil.testClient.getCode({ address: user.address })).toBe( concat(["0xef0100", delegate]).toLowerCase(), ); ``` :::note Changing the chain id After `setChainId()`, anvil's own signer keeps the startup chain id; local signing keeps working. See [Configure the chain](../configure/chain.md). ::: ### Concepts - [Signing: anvil-signed vs. locally signed](../../concepts/signing.md) --- ## Use dev accounts and keys Configure accounts with `.account`; read them with their keys: ```ts snippet="examples/test/e2e/fixtures-and-isolation.e2e.test.ts#accounts" const accounts = await anvil.accounts(); // addresses + private keys expect(accounts).toHaveLength(3); accounts.forEach(({ index, address, privateKey }) => { expect(privateKey).toBeDefined(); expect(mnemonicToAccount(MNEMONIC, { addressIndex: index }).address).toBe( address, ); }); expect(await anvil.getBalance(accounts[2].address)).toBe( parseEther("1000"), ); ``` `addresses()` returns addresses; `accounts()` adds `privateKey`. ### Choose the key material ```ts snippet="examples/test/e2e/signing.e2e.test.ts#key-material" const MNEMONIC = "legal winner thank year wave sausage worth useful legal winner thank yellow"; // Dev accounts from a second BIP-44 account branch: m/44'/60'/1'/0/i const derived = useAnvil( new AnvilContainer( new AnvilOptions().account .withMnemonic(MNEMONIC) .withDerivationPath("m/44'/60'/1'/0/") .withAccounts(2), ), ); // A fresh random mnemonic per run; keys are read from anvil's startup banner. const random = useAnvil( new AnvilContainer( new AnvilOptions().account.withRandomMnemonic(), ).withTestClient((client) => client.withLocalAccount(0)), ); // Reproducible "random" accounts: the same seed gives the same mnemonic. const seeded = useAnvil( new AnvilContainer(new AnvilOptions().account.withMnemonicSeedUnsafe(42)), ); const seededAgain = useAnvil( new AnvilContainer(new AnvilOptions().account.withMnemonicSeedUnsafe(42)), ); it("derives accounts along the configured path", async () => { const accounts = await derived.accounts(); accounts.forEach(({ index, address }) => expect( mnemonicToAccount(MNEMONIC, { accountIndex: 1, addressIndex: index }) .address, ).toBe(address), ); }); it("reproduces seeded accounts across nodes", async () => { const [first] = await seeded.addresses(); expect(await seededAgain.addresses()).toEqual(await seeded.addresses()); expect(first).not.toBe(mnemonicToAccount(DEFAULT_MNEMONIC).address); }); it("signs locally with keys of a random mnemonic", async () => { const [first] = await random.accounts(); expect(first.privateKey).toBeDefined(); expect(random.testClient.account.address).toBe(first.address); const [, other] = await random.addresses(); const receipt = await random.confirm( random.testClient.sendTransaction({ to: other, value: 1n }), ); expect(receipt.from.toLowerCase()).toBe(first.address.toLowerCase()); }); ``` | Method | anvil flag | Keys known to `accounts()` | |---|---|---| | default | – | yes (`DEFAULT_MNEMONIC`) | | `withMnemonic(phrase)` | `--mnemonic` | yes | | `withDerivationPath(path)` | `--derivation-path` | yes | | `withRandomMnemonic(words?)` | `--mnemonic-random` | from the banner; not with `logs.quiet()` | | `withMnemonicSeedUnsafe(seed)` | `--mnemonic-seed-unsafe` | from the banner; not with `logs.quiet()` | The default is the well-known Foundry/Hardhat mnemonic: ```ts snippet="examples/test/e2e/signing.e2e.test.ts#mnemonic" const expected = mnemonicToAccount(DEFAULT_MNEMONIC, { addressIndex: 1 }); expect(anvil.testClient.account.address).toBe(expected.address); ``` ### Concepts - [Signing: anvil-signed vs. locally signed](../../concepts/signing.md) - Reference: [`.account` options](../../reference/anvil-options.md#account) --- ## Configure the chain ```ts snippet="examples/test/e2e/chain-config-and-reorgs.e2e.test.ts#chain-config" const anvil = useAnvil( new AnvilContainer( new AnvilOptions().evm .withChainId(8453) .withHardfork(Hardfork.Cancun) .withGasLimit(60_000_000) .withBlockBaseFeePerGas(parseGwei("7")), ).withTestClient((client) => client .withAccount(0) .withChain({ name: "Local Base", blockExplorers: { default: { name: "None", url: "http://localhost" }, }, }) .withPollingInterval(50), ), ); ``` `withChain()` sets client metadata; the id and URLs come from the node. ### Change the chain id at runtime ```ts snippet="examples/test/e2e/chain-config-and-reorgs.e2e.test.ts#set-chain-id" await anvil.cheats.setChainId(10); try { expect(anvil.chainId).toBe(10); // the container's clients follow // Sign locally: anvil's own dev-account signer keeps the startup chain id. const signer = anvil.testClientFor( privateKeyToAccount(alice.privateKey!), ); const receipt = await anvil.confirm( signer.sendTransaction({ to: alice.address, value: 1n }), ); expect(receipt.status).toBe("success"); } finally { await anvil.cheats.setChainId(8453); // node setting: restore } ``` ### Gas price Pre-London: pin the suggested gas price: ```ts snippet="examples/test/e2e/node-configuration.e2e.test.ts#gas-price" // Pre-London chains have no base fee: pin the gas price the node suggests. const legacy = useAnvil( new AnvilContainer( new AnvilOptions().evm .withHardfork(Hardfork.Berlin) .withGasPrice(parseGwei("5")), ), ); it("suggests the configured gas price", async () => { expect(await legacy.testClient.getGasPrice()).toBe(parseGwei("5")); }); ``` Post-London: drop anvil's 1 gwei minimum tip: ```ts snippet="examples/test/e2e/node-configuration.e2e.test.ts#no-priority-fee" // By default anvil suggests base fee + 1 gwei; drop the minimum tip. const tipless = useAnvil( new AnvilContainer(new AnvilOptions().evm.disableMinPriorityFee()), ); it("suggests the base fee without a tip", async () => { const { baseFeePerGas } = await tipless.testClient.getBlock(); expect(await tipless.testClient.getGasPrice()).toBe(baseFeePerGas); }); ``` ### Finality (`safe` / `finalized` blocks) ```ts snippet="examples/test/e2e/node-configuration.e2e.test.ts#slots-in-an-epoch" // `safe` trails the head by one epoch, `finalized` by two (default: 32 slots). const node = useAnvil( new AnvilContainer(new AnvilOptions().mining.withSlotsInAnEpoch(1)), ); it("derives the safe and finalized blocks from the epoch length", async () => { await node.mine(5); const safe = await node.testClient.getBlock({ blockTag: "safe" }); const finalized = await node.testClient.getBlock({ blockTag: "finalized", }); expect([safe.number, finalized.number]).toEqual([4n, 3n]); }); ``` ### OP Stack and Celo ```ts snippet="examples/test/unit/options.test.ts#network-modes" const opStack = new AnvilOptions().network .withOptimism() .evm.withHardfork(OpHardfork.Isthmus); expect(opStack.toCommand()).toBe( "anvil --host 0.0.0.0 --hardfork isthmus --optimism", ); // Ethereum hardforks don't apply to OP Stack chains… expect(() => new AnvilOptions().network .withOptimism() .evm.withHardfork(Hardfork.Prague) .validate(), ).toThrow(/use an OpHardfork value instead/); // …and a chain is either OP Stack or Celo. expect(() => new AnvilOptions().network.withCelo().withOptimism()).toThrow( AnvilConfigurationError, ); ``` `OpHardfork` with `withOptimism()`; `Hardfork.Latest` is anvil's default. ### Concepts - [anvil behaviours worth knowing](../../concepts/anvil-behaviours.md#chain-id) - Reference: [`.evm` options](../../reference/anvil-options.md#evm), [`.network` options](../../reference/anvil-options.md#network), [`Hardfork` values](../../reference/exports.md#enums) --- ## Compose and inspect options `AnvilOptions` can be copied, combined and inspected before anything starts. ### Presets and copies ```ts snippet="examples/test/unit/options.test.ts#compose" const richAccounts = (options: AnvilOptions) => options.account.withAccounts(3).withBalance(1_000_000); const fastBlocks = (options: AnvilOptions) => options.mining.withBlockTime(1); const base = new AnvilOptions().apply(richAccounts); // run presets const ci = base.clone().apply(fastBlocks); // independent copy const onDemand = ci.clone().unset("--block-time").mining.withNoMining(); // swap a conflicting flag expect(base.toCommand()).toBe( "anvil --host 0.0.0.0 --accounts 3 --balance 1000000", ); expect(ci.has("--block-time")).toBe(true); expect(onDemand.root().toArgs()).toContain("--no-mining"); ``` ### Reset a group ```ts snippet="examples/test/unit/options.test.ts#group-reset" const options = new AnvilOptions().mining .withBlockTime(2) .withMixedMining() .evm.withChainId(10); options.mining.reset(); // removes every mining flag, nothing else expect(options.toCommand()).toBe("anvil --host 0.0.0.0 --chain-id 10"); // withAutoMining() removes just the mining mode flags. const auto = new AnvilOptions().mining.withNoMining().withAutoMining(); expect(auto.has("--no-mining")).toBe(false); ``` ### Flags newer than the library ```ts snippet="examples/test/unit/options.test.ts#extra-args" const options = new AnvilOptions().withExtraArgs("--some-new-flag", "1"); expect(options.toCommand()).toBe("anvil --host 0.0.0.0 --some-new-flag 1"); // Known flags must use the fluent API, so validation cannot be bypassed. expect(() => new AnvilOptions().withExtraArgs("--accounts", "1")).toThrow( /known anvil flag/, ); ``` ### Inspect ```ts snippet="examples/test/unit/options.test.ts#inspect" const options = new AnvilOptions().account .withAccounts(2) .evm.withChainId(8453); expect(options.has("--chain-id")).toBe(true); expect(options.get("--accounts")).toBe("2"); expect(options.flags()).toEqual({ "--accounts": "2", "--chain-id": "8453", }); // --host is managed by the container: rendered, not configurable expect(options.toArgs()).toEqual([ "--host", "0.0.0.0", "--accounts", "2", "--chain-id", "8453", ]); expect(options.entryPoint[0]).toBe("anvil"); expect(options.toJSON().command).toEqual(options.entryPoint); ``` A container shows its options and the prepared command without Docker: ```ts snippet="examples/test/unit/configuration.test.ts#container-getters" const options = new AnvilOptions().mining.withBlockTime(2); const container = new AnvilContainer(options).withTestClient((client) => client.withAccount(0), ); expect(container.anvilOptions).toBe(options); expect(container.testClientOptions.build().account?.kind).toBe("index"); expect(container.prepare().command.join(" ")).toBe( "anvil --host 0.0.0.0 --block-time 2", ); ``` ### Validate ```ts snippet="examples/test/unit/options.test.ts#validate" // Setters reject conflicts at once; dependencies need the whole picture. const incomplete = new AnvilOptions().fork.withRetries(3); // no fork URL yet expect(() => incomplete.validate()).toThrow(AnvilConfigurationError); const [problem] = incomplete.problems(); // the same, without throwing expect(problem.flag).toBe("--retries"); expect(problem.relatedFlags).toEqual(["--fork-url"]); const configuration = incomplete.fork .withForkUrl("https://rpc.example", 19_000_000) .build(); // validate() + freeze expect(configuration.forking).toBe(true); expect(configuration.command).toContain("--fork-block-number"); expect(Object.isFrozen(configuration)).toBe(true); ``` ### The flag registry ```ts snippet="examples/test/unit/options.test.ts#registry" const spec = getFlagSpec("--fork-url"); expect(spec.aliases).toEqual(["-f", "--rpc-url"]); expect(spec.methods).toEqual(["fork.withForkUrl()"]); expect(isAnvilFlag("--state-interval")).toBe(true); expect(getFlagSpec("--state-interval").requiresAnyOf).toEqual([ "--dump-state", "--state", ]); expect(groupFlags("mining")).toContain("--no-mining"); expect(ANVIL_FLAGS.size).toBe(ANVIL_FLAG_LIST.length); ``` ### Concepts - [Validation model](../../concepts/validation.md) - Reference: [`AnvilOptions`](../../reference/anvil-options.md), [Flag rules](../../reference/flag-rules.md) --- ## Configure EVM limits Set EVM limits with `.evm` options; some can change at runtime. ### Contract size (EIP-170) ```ts snippet="examples/test/e2e/node-configuration.e2e.test.ts#code-size" const strict = useAnvil( new AnvilContainer().withTestClient((client) => client.withAccount(0)), ); const raised = useAnvil( new AnvilContainer( new AnvilOptions().evm.withCodeSizeLimit(32_768), ).withTestClient((client) => client.withAccount(0)), ); it("rejects contracts over 24,576 bytes by default", async () => { const hash = await strict.testClient.deployContract({ abi: oversizedContract.abi, bytecode: oversizedContract.bytecode, // deploys 24,577 bytes }); await expect(strict.confirm(hash)).rejects.toBeInstanceOf( AnvilTransactionRevertedError, ); }); it("deploys them with a raised limit (e.g. unoptimised debug builds)", async () => { const { contractAddress } = await raised.confirm( raised.testClient.deployContract({ abi: oversizedContract.abi, bytecode: oversizedContract.bytecode, }), ); const code = await raised.testClient.getCode({ address: contractAddress!, }); expect((code!.length - 2) / 2).toBe(24_577); }); ``` ```ts snippet="examples/test/e2e/node-configuration.e2e.test.ts#no-code-size-limit" const unlimited = useAnvil( new AnvilContainer( new AnvilOptions().evm.disableCodeSizeLimit(), ).withTestClient((client) => client.withAccount(0)), ); it("deploys contracts of any size without a limit", async () => { const receipt = await unlimited.confirm( unlimited.testClient.deployContract({ abi: oversizedContract.abi, bytecode: oversizedContract.bytecode, }), ); expect(receipt.status).toBe("success"); }); ``` ### Memory ```ts snippet="examples/test/unit/options.test.ts#memory-limit" const options = new AnvilOptions().evm.withMemoryLimit(1n << 30n); // bytes expect(options.toCommand()).toBe( "anvil --host 0.0.0.0 --memory-limit 1073741824", ); ``` ### Block gas limit ```ts snippet="examples/test/e2e/node-configuration.e2e.test.ts#block-gas-limit" const limited = useAnvil(new AnvilContainer()); const unlimited = useAnvil( new AnvilContainer(new AnvilOptions().evm.disableBlockGasLimit()), ); it("rejects transactions above the block gas limit by default", async () => { const [alice, bob] = await limited.addresses(); await expect( limited.testClient.sendTransaction({ account: alice, to: bob, gas: 100_000_000n, }), ).rejects.toThrow(/gas/); }); it("accepts them without a block gas limit (gas-heavy tests, fuzzing)", async () => { const [alice, bob] = await unlimited.addresses(); const receipt = await unlimited.confirm( unlimited.testClient.sendTransaction({ account: alice, to: bob, gas: 100_000_000n, }), ); expect(receipt.status).toBe("success"); }); ``` `evm.withGasLimit(gas)` sets it at start, `cheats.setBlockGasLimit()` at runtime ([Control block contents](../time-and-blocks/build-blocks.md)). ### The default CREATE2 deployer ```ts snippet="examples/test/e2e/node-configuration.e2e.test.ts#create2" const node = useAnvil( new AnvilContainer().withTestClient((client) => client.withAccount(0)), ); const bare = useAnvil( new AnvilContainer( new AnvilOptions().evm.disableDefaultCreate2Deployer(), ), ); it("deploys to a precomputed address through the CREATE2 deployer", async () => { const salt = `0x${"00".repeat(31)}2a` as const; const predicted = getContractAddress({ opcode: "CREATE2", from: CREATE2_DEPLOYER, salt, bytecode: fixedPriceOracle.bytecode, }); // The deployer's calldata is simply salt ‖ creation code. await node.confirm( node.testClient.sendTransaction({ to: CREATE2_DEPLOYER, data: concat([salt, fixedPriceOracle.bytecode]), }), ); expect( await node.testClient.getCode({ address: predicted }), ).toBeDefined(); }); it("can start without the deployer (e.g. to deploy your own)", async () => { expect( await bare.testClient.getCode({ address: CREATE2_DEPLOYER }), ).toBeUndefined(); }); ``` ### Mempool balance checks ```ts snippet="examples/test/e2e/node-configuration.e2e.test.ts#pool-balance-checks" // Accept transactions whose sender cannot pay (yet): fund it before mining. const node = useAnvil( new AnvilContainer( new AnvilOptions().mining.withNoMining().evm.disablePoolBalanceChecks(), ), ); it("queues a transaction from an unfunded sender", async () => { const user = privateKeyToAccount(generatePrivateKey()).address; const [alice] = await node.addresses(); const hash = await node.testClient.sendUnsignedTransaction({ from: user, to: alice, value: parseEther("1"), }); expect((await node.testClient.getTxpoolStatus()).pending).toBe(1); await node.cheats.setBalanceEther(user, 2).mine(); const receipt = await node.testClient.getTransactionReceipt({ hash }); expect(receipt.status).toBe("success"); }); ``` ### Concepts - Reference: [`.evm` options](../../reference/anvil-options.md#evm) --- ## Configure logging Set verbosity and format with `.logs`; toggle logging at runtime. ### Verbose, plain-text traces ```ts snippet="examples/test/e2e/debugging-and-tracing.e2e.test.ts#tracing-node" const anvil = useAnvil( new AnvilContainer( new AnvilOptions().evm .withPrintTraces() // call traces in anvil's log output .withStepsTracing() // opcode-level debug_traceTransaction .logs.verboseLogs(LogVerbosity.Three) .withColor(Color.Never), // plain text, easy to search ).withTestClient((client) => client.withAccount(0)), { setup: async (node) => { const [, alice] = await node.addresses(); token = await deployToken(node.testClient); vault = await deployVault(node.testClient, token, 0n); await mint(node.testClient, token, alice, parseEther("10")); }, }, ); ``` ### Formats ```ts snippet="examples/test/unit/options.test.ts#log-formats" const json = new AnvilOptions().logs.jsonLogFormat().disableConsoleLog(); expect(json.toCommand()).toBe( "anvil --host 0.0.0.0 --json --disable-console-log", ); const markdown = new AnvilOptions().logs .withMarkdownFormat() .verboseLogs(LogVerbosity.Four); expect(markdown.toCommand()).toBe("anvil --host 0.0.0.0 --md -vvvv"); // Conflicting log settings fail as soon as they are set. expect(() => new AnvilOptions().logs.quiet().verboseLogs(2)).toThrow( /cannot be combined with --quiet/, ); ``` `logs.quiet()` hides the startup banner; startup readiness does not depend on logs. With a random mnemonic, quiet nodes cannot report private keys. ### At runtime ```ts snippet="examples/test/e2e/debugging-and-tracing.e2e.test.ts#logging" await anvil.setLoggingEnabled(false); try { const hash = await anvil.testClient.sendTransaction({ to: alice, value: 1n, }); await anvil.confirm(hash); expect(await anvil.logText()).not.toContain(hash); } finally { await anvil.setLoggingEnabled(true); // node setting: restore } ``` ### Concepts - [Inspect the node](../debugging/inspect-the-node.md) - Reference: [`.logs` options](../../reference/anvil-options.md#logs) --- ## Configure the RPC server Configure the server with `.server`; the library maps ports and manages `--host`. ### Port anvil's port inside the container; the host port is mapped automatically: ```ts snippet="examples/test/e2e/node-configuration.e2e.test.ts#server" // anvil listens on 9545 inside the container; the host port is mapped. const custom = useAnvil( new AnvilContainer(new AnvilOptions().server.withPort(9545).logs.quiet()), ); it("maps the configured port to a free host port", async () => { const hostPort = custom.getMappedPort(9545); expect(custom.rpcUrl).toBe(`http://${custom.getHost()}:${hostPort}`); expect(await custom.testClient.getChainId()).toBe(31337); }); it("starts quietly (no banner) and still knows the dev keys", async () => { expect(await custom.logText()).not.toContain("Available Accounts"); const [first] = await custom.accounts(); // derived from the mnemonic expect(first.privateKey).toBeDefined(); }); ``` ### CORS for browser dApps ```ts snippet="examples/test/e2e/node-configuration.e2e.test.ts#cors" const open = useAnvil( new AnvilContainer(new AnvilOptions().server.withAllowOrigin(ORIGIN)), ); const closed = useAnvil( new AnvilContainer(new AnvilOptions().server.noCors()), ); it("allows the configured origin", async () => { const response = await preflight(open.rpcUrl); expect(response.headers.get("access-control-allow-origin")).toBe(ORIGIN); }); it("rejects cross-origin requests with --no-cors", async () => { const response = await preflight(closed.rpcUrl); expect(response.ok).toBe(false); expect(response.headers.get("access-control-allow-origin")).toBeNull(); }); ``` ### Large requests ```ts snippet="examples/test/e2e/node-configuration.e2e.test.ts#request-size" const strict = useAnvil(new AnvilContainer()); const unlimited = useAnvil( new AnvilContainer(new AnvilOptions().server.noRequestSizeLimit()), ); // 2 MB of calldata: a request body of about 4 MB once hex encoded. const bigCall = { to: "0x0000000000000000000000000000000000000001", data: `0x${"00".repeat(2_000_000)}`, gas: 30_000_000n, } as const satisfies { to: Address; data: Hex; gas: bigint }; it("rejects very large requests by default", async () => { await expect(strict.testClient.call(bigCall)).rejects.toThrow( /Invalid request/, ); }); it("accepts them with noRequestSizeLimit()", async () => { await expect(unlimited.testClient.call(bigCall)).resolves.toBeDefined(); }); ``` ### IPC, threads, cache path Paths are inside the container: ```ts snippet="examples/test/unit/options.test.ts#server-paths" const options = new AnvilOptions().server .withIpc() // /tmp/anvil.ipc inside the container .withThreads(4) // 0 = one per logical core .withCachePath("/tmp/anvil-cache"); // container path expect(options.toCommand()).toBe( "anvil --host 0.0.0.0 --ipc --threads 4 --cache-path /tmp/anvil-cache", ); ``` `--host` is managed by the library (always `0.0.0.0` in the container). ### Concepts - [Startup, readiness and file transfers](../../concepts/startup-and-files.md) - Reference: [`.server` options](../../reference/anvil-options.md#server) --- ## Configure the test client Pass `TestClientOptions` (or a function building them) to `withTestClient()`: ```ts snippet="examples/test/unit/configuration.test.ts#client-options" const client = new TestClientOptions() .withTransport("webSocket") // eth_subscribe-based watchers .withTimeout(5_000) // per request (default 10 000 ms) .withRetries(0, 50) // count, base delay in ms (default 3, 150) .withCacheTime(1_000) // reuse e.g. the block number for 1 s (default 0) .withPollingInterval(10) // watchers and receipt waits (default 25 ms) .withLocalAccount(0); // dev account 0, signed locally expect(client.build()).toMatchObject({ transport: "webSocket", timeout: 5_000, retryCount: 0, retryDelay: 50, account: { kind: "index", index: 0, signing: "local" }, }); // JSON-RPC batching needs HTTP: expect(() => client.clone().withBatch().build()).toThrow( AnvilTestClientConfigurationError, ); ``` ### Presets ```ts snippet="examples/test/unit/configuration.test.ts#presets" const base = new TestClientOptions() .withPollingInterval(50) .withRetries(0) // fail fast on a local node .withChain({ name: "Local" }); const asDeployer = base.clone().withAccount(0); const readOnly = asDeployer.clone().withoutAccount(); const mainnetFork = base.clone().withMulticall3(); // Multicall3 exists on forks of mainnet expect(asDeployer.build().account).toEqual({ kind: "index", index: 0, signing: "node", }); expect(readOnly.build().account).toBeUndefined(); expect(mainnetFork.build().chain.contracts?.multicall3?.address).toBe( "0xcA11bde05977b3631167028862bE2a173976CA11", ); expect(base.build().pollingInterval).toBe(50); // presets stay untouched ``` ### Extra clients with other settings ```ts snippet="examples/test/e2e/chain-config-and-reorgs.e2e.test.ts#cache-time" const cached = await anvil.createTestClient((client) => client.withCacheTime(60_000), ); const height = await cached.getBlockNumber(); await anvil.mine(); expect(await cached.getBlockNumber()).toBe(height); // served from cache expect(await anvil.testClient.getBlockNumber()).toBe(height + 1n); // default: no cache ``` ```ts snippet="examples/test/e2e/multi-actor-flows.e2e.test.ts#batching" const batched = await anvil.createTestClient( (client) => client.withBatch({ wait: 5 }), // collect requests for 5 ms per HTTP call ); const balances = await Promise.all( addresses.map((address) => balanceOf(batched, token, address)), ); ``` ### Your own viem clients Use `anvil.chain` and `anvil.rpcUrl` / `anvil.wsUrl`, and add the anvil extras with `anvilActions`: ```ts snippet="examples/test/e2e/multi-actor-flows.e2e.test.ts#own-client" // e.g. the client your application code already creates: const appClient = createPublicClient({ chain: anvil.chain, // id, name and URLs of this node transport: http(anvil.rpcUrl), }).extend(anvilActions); // add the anvil extras to any viem client await appClient.addBalance({ address: alice, value: parseEther("1") }); const balance = await appClient.readContract({ address: token, abi: exampleToken.abi, functionName: "balanceOf", args: [alice], }); expect(balance).toBe(parseEther("50")); ``` | Setting | Default | |---|---| | `withTransport("http" \| "webSocket")` | `"http"` | | `withPollingInterval(ms)` | 25 | | `withCacheTime(ms)` | 0 | | `withTimeout(ms)` | 10 000 | | `withRetries(count, delayMs?)` | 3, 150 | | `withBatch(true \| { batchSize, wait })` | off, HTTP only | | `withAccount()` / `withLocalAccount()` / `withoutAccount()` | none | | `withChain({ name, nativeCurrency, contracts, blockExplorers, testnet })` | `Anvil ()`, ETH | | `withMulticall3(address?)` | – | ### Concepts - [Architecture: node, test client, cheats](../../concepts/architecture.md) - [Validation model](../../concepts/validation.md) - Reference: [`TestClientOptions`](../../reference/test-client-options.md) --- ## Call any RPC method ```ts snippet="examples/test/e2e/debugging-and-tracing.e2e.test.ts#raw-rpc" const { creator } = await anvil.rpc<{ hash: Hash; creator: Address }>( "ots_getContractCreator", [token], ); expect(creator.toLowerCase()).toBe(deployer.toLowerCase()); ``` `anvil.rpc(method, params)` sends a raw JSON-RPC request through the test client (its retries and stop guard included). Type the result with `T`. For anvil methods the library wraps, prefer the typed actions: see [anvil extras](../../reference/anvil-actions.md). ### Concepts - [Architecture: how requests reach the node](../../concepts/architecture.md) - Reference: [`rpc()`](../../reference/started-anvil-container.md#connection) --- ## Inspect the node ```ts snippet="examples/test/e2e/chain-config-and-reorgs.e2e.test.ts#node-info" const info = await anvil.testClient.getNodeInfo(); expect(info.hardFork.toLowerCase()).toBe("cancun"); expect(info.environment.chainId).toBe(8453); expect(BigInt(info.environment.gasLimit)).toBe(60_000_000n); const metadata = await anvil.testClient.getMetadata(); expect(metadata.clientVersion).toMatch(/anvil/); expect(metadata.forkedNetwork).toBeFalsy(); // not a fork // The exact command line anvil was started with, and the client settings: expect(anvil.configuration.command.join(" ")).toContain("--chain-id 8453"); expect(anvil.testClientConfiguration.pollingInterval).toBe(50); expect((await anvil.nodeInfo()).currentBlockNumber).toBeDefined(); ``` | Member | Returns | |---|---| | `nodeInfo()` / `testClient.getNodeInfo()` | `anvil_nodeInfo`: block, hardfork, fees, fork config | | `metadata()` / `testClient.getMetadata()` | `anvil_metadata`: version, chain id, fork, snapshots | | `configuration` | the validated anvil configuration (`command`, `flags`, …) | | `testClientConfiguration` | the test client settings in effect | | `logText(tail?)` | anvil's output so far | | `rpcUrl`, `wsUrl`, `chainId`, `chain` | connection details | ### Logs ```ts snippet="examples/test/e2e/debugging-and-tracing.e2e.test.ts#logging" await anvil.setLoggingEnabled(false); try { const hash = await anvil.testClient.sendTransaction({ to: alice, value: 1n, }); await anvil.confirm(hash); expect(await anvil.logText()).not.toContain(hash); } finally { await anvil.setLoggingEnabled(true); // node setting: restore } ``` ### Concepts - [Configure logging](../configure/logging.md) - Reference: [`StartedAnvilContainer`](../../reference/started-anvil-container.md#diagnostics) --- ## Trace a failed transaction Enable tracing on the node: ```ts snippet="examples/test/e2e/debugging-and-tracing.e2e.test.ts#tracing-node" const anvil = useAnvil( new AnvilContainer( new AnvilOptions().evm .withPrintTraces() // call traces in anvil's log output .withStepsTracing() // opcode-level debug_traceTransaction .logs.verboseLogs(LogVerbosity.Three) .withColor(Color.Never), // plain text, easy to search ).withTestClient((client) => client.withAccount(0)), { setup: async (node) => { const [, alice] = await node.addresses(); token = await deployToken(node.testClient); vault = await deployVault(node.testClient, token, 0n); await mint(node.testClient, token, alice, parseEther("10")); }, }, ); ``` ### The failing inner call ```ts snippet="examples/test/e2e/debugging-and-tracing.e2e.test.ts#call-tracer" const trace = await anvil.rpc("debug_traceTransaction", [ hash, { tracer: "callTracer" }, ]); expect(trace.to.toLowerCase()).toBe(vault.toLowerCase()); expect(trace.error).toBe("execution reverted"); // The revert originated one level down, in the token: const [inner] = trace.calls!; expect(inner.to.toLowerCase()).toBe(token.toLowerCase()); const cause = decodeErrorResult({ abi: exampleToken.abi, data: inner.output!, }); expect(cause.errorName).toBe("InsufficientAllowance"); expect(cause.args).toEqual([vault, 0n, 1n]); // spender, allowance, needed ``` ### Opcodes (`--steps-tracing`) ```ts snippet="examples/test/e2e/debugging-and-tracing.e2e.test.ts#struct-logs" const { structLogs } = await anvil.rpc<{ structLogs: { op: string; depth: number }[]; }>("debug_traceTransaction", [hash, {}]); expect(structLogs.length).toBeGreaterThan(100); expect(structLogs.filter((step) => step.op === "REVERT")).toHaveLength(2); // token, then vault ``` ### A call, without sending it ```ts snippet="examples/test/e2e/debugging-and-tracing.e2e.test.ts#trace-call" const trace = await anvil.rpc("debug_traceCall", [ { from: alice, to: token, data: encodeFunctionData({ abi: exampleToken.abi, functionName: "transfer", args: [bob, 1n], }), }, "latest", { tracer: "callTracer" }, ]); expect(trace.type).toBe("CALL"); expect(trace.error).toBeUndefined(); ``` ### anvil's own trace output (`--print-traces`) ```ts snippet="examples/test/e2e/debugging-and-tracing.e2e.test.ts#print-traces" const logs = await anvil.logText(200); // last 200 lines of anvil's output const selector = "0x192b9e4e"; // InsufficientAllowance(address,uint256,uint256) expect(logs).toContain(`[Revert] custom error ${selector}`); ``` `trace_transaction` (Parity style) works through `anvil.rpc()` too. ### Concepts - [Signing: why anvil-signed reverts are mined](../../concepts/signing.md) - [Assert reverts and custom errors](../transactions/assert-reverts.md) --- ## Query logs and filters Query past events with `getContractEvents` / `getLogs`, or poll a filter. ### By indexed argument ```ts snippet="examples/test/e2e/events-and-subscriptions.e2e.test.ts#history" const toBob = await anvil.testClient.getContractEvents({ address: token, abi: exampleToken.abi, eventName: "Transfer", args: { to: bob }, // indexed topic filter fromBlock: 0n, }); // JSON ABIs are untyped (`Abi`), so decoded args need a type here. const values = toBob.map((log) => (log.args as { value: bigint }).value); expect(values).toEqual([2n, 3n]); ``` ### Typed arguments from an event signature JSON ABIs are untyped; a human-readable signature gives full inference: ```ts snippet="examples/test/e2e/events-and-subscriptions.e2e.test.ts#event-signature" // A human-readable event signature gives full type inference for log args, // even though the JSON ABIs are untyped. const TRANSFER = parseAbiItem( "event Transfer(address indexed from, address indexed to, uint256 value)", ); ``` ```ts snippet="examples/test/e2e/events-and-subscriptions.e2e.test.ts#typed-logs" const mints = await anvil.testClient.getLogs({ address: token, event: TRANSFER, args: { from: zeroAddress }, fromBlock: 0n, toBlock: "latest", }); const last = mints.at(-1)!; expect(last.args.to).toBe(alice); // typed: `0x${string}` | undefined expect(last.args.value).toBe(7n); // typed: bigint | undefined ``` ### Poll a filter ```ts snippet="examples/test/e2e/events-and-subscriptions.e2e.test.ts#filter" const http = await anvil.createTestClient((client) => client.withAccount(0).withTransport("http"), ); const filter = await http.createEventFilter({ address: token, event: TRANSFER, args: { to: bob }, // indexed argument filter }); await mint(http, token, alice, 1n); await mint(http, token, bob, 2n); const changes = await http.getFilterChanges({ filter }); expect(changes).toHaveLength(1); // only the transfer to bob expect(await http.getFilterChanges({ filter })).toHaveLength(0); // consumed await http.uninstallFilter({ filter }); ``` ### Concepts - [JSON ABIs are typed as `Abi`](../../concepts/anvil-behaviours.md#more) - Reference: [test client actions](../../reference/test-client.md#public-and-wallet-actions) --- ## Watch events and blocks Use the WebSocket transport for `eth_subscribe`-based watchers: ```ts snippet="examples/test/e2e/events-and-subscriptions.e2e.test.ts#websocket" const anvil = useAnvil( new AnvilContainer().withTestClient((client) => client.withAccount(0).withTransport("webSocket"), ), { setup: async (node) => void (token = await deployToken(node.testClient)) }, ); ``` ### Contract events ```ts snippet="examples/test/e2e/events-and-subscriptions.e2e.test.ts#watch" const received: Log[] = []; const errors: Error[] = []; const unwatch = anvil.testClient.watchContractEvent({ address: token, abi: exampleToken.abi, eventName: "Transfer", onLogs: (logs) => received.push(...logs), onError: (error) => errors.push(error), }); try { // The subscription starts asynchronously: mint until a log arrives. await triggerUntil( () => mint(anvil.testClient, token, alice, parseEther("5")), () => received.length > 0, ); } finally { unwatch(); } expect(errors).toEqual([]); expect(received[0]).toMatchObject({ eventName: "Transfer", args: { to: alice, value: parseEther("5") }, }); ``` ### New blocks ```ts snippet="examples/test/e2e/events-and-subscriptions.e2e.test.ts#watch-blocks" const start = await anvil.testClient.getBlockNumber(); const seen = new Set(); const unwatch = anvil.testClient.watchBlocks({ // viem fetches each announced block separately, so blocks can be // reported out of order: collect them, don't assume a sequence. onBlock: (block: Block) => seen.add(block.number!), }); try { await triggerUntil( () => anvil.mine(), () => seen.size >= 2, ); } finally { unwatch(); } const latest = await anvil.testClient.getBlockNumber(); for (const number of seen) { expect(number).toBeGreaterThan(start); // only newly mined blocks expect(number).toBeLessThanOrEqual(latest); } ``` ### Pending transactions ```ts snippet="examples/test/e2e/events-and-subscriptions.e2e.test.ts#pending" await anvil.cheats.setAutomine(false); // keep transactions pending const seen = new Set(); const sent: Hash[] = []; const unwatch = anvil.testClient.watchPendingTransactions({ onTransactions: (hashes) => hashes.forEach((hash) => seen.add(hash)), }); try { await triggerUntil( async () => sent.push( await anvil.testClient.sendTransaction({ to: alice, value: 1n }), ), () => sent.some((hash) => seen.has(hash)), ); } finally { unwatch(); await anvil.cheats.setAutomine(true); // node setting: restore } ``` ### Your own WebSocket clients ```ts snippet="examples/test/e2e/events-and-subscriptions.e2e.test.ts#own-websocket" const client = createPublicClient({ chain: anvil.chain, transport: webSocket(anvil.wsUrl), }); const start = await anvil.testClient.getBlockNumber(); let announced: bigint | undefined; const unwatch = client.watchBlockNumber({ onBlockNumber: (blockNumber) => (announced = blockNumber), }); try { await triggerUntil( () => anvil.mine(), () => announced !== undefined, ); expect(announced).toBeGreaterThan(start); } finally { unwatch(); // Clients you create are yours to close (the node closes its own). (await client.transport.getRpcClient()).close(); } ``` ### Don't sleep: trigger until observed Watchers subscribe asynchronously and viem has no "ready" signal. Repeat the trigger until the watcher reports: ```ts snippet="examples/src/watchers.ts#trigger-until" /** * Runs `trigger` (e.g. mine a block, send a transaction), then checks * `observed`, repeating until it returns `true`. * * @example * const seen = new Set(); * const unwatch = client.watchBlocks({ onBlock: (block) => seen.add(block.number!) }); * await triggerUntil(() => anvil.mine(), () => seen.size >= 2); * unwatch(); */ export async function triggerUntil( trigger: () => Promise, observed: () => boolean, { intervalMs = 50, timeoutMs = 10_000 }: TriggerUntilOptions = {}, ): Promise { const deadline = Date.now() + timeoutMs; let attempts = 0; while (!observed()) { if (Date.now() > deadline) { throw new Error( `triggerUntil: not observed after ${attempts} trigger(s) in ${timeoutMs} ms`, ); } await trigger(); attempts++; // Give the watcher a moment to report before triggering again. for (let waited = 0; waited < intervalMs && !observed(); waited += 10) { await new Promise((resolve) => setTimeout(resolve, 10)); } } } ``` ### Concepts - [anvil behaviours worth knowing](../../concepts/anvil-behaviours.md#watchers) - [Configure the test client](../configure/test-client.md) --- ## Fork a live chain Pin the block for reproducible tests: ```ts snippet="examples/test/e2e/forking.e2e.test.ts#fork" const options = new AnvilOptions().fork .withForkUrl(forkUrl, forkBlock) // pin the block: reproducible tests .withRetries(2) // upstream hiccups… .withForkRetryBackoff(500) // …are retried after 500 ms .withTimeout(10_000) // per upstream request .noStorageCaching() // don't persist fetched state to anvil's disk cache .noRateLimit() // a local upstream needs no compute-unit throttling // anvil derives a fork's hardfork from chain id + block number; for // "chain 1 at block 3" that is Frontier, so pin it explicitly. .evm.withHardfork(Hardfork.Cancun); const container = new AnvilContainer(options).withTestClient((client) => // Act as the holder: impersonated at startup, typed default account. client.withAccount(HOLDER, { impersonate: true }), ); ``` `forkUrl` is your provider's URL, resolved *inside the container* (`host.docker.internal` for your machine). The fork sees upstream state at the fork block: ```ts snippet="examples/test/e2e/forking.e2e.test.ts#fork-state" expect(fork.chainId).toBe(1); // the client follows the forked chain expect(await balanceOf(fork.testClient, token, HOLDER)).toBe( parseEther("1000000"), // the later mint is not part of the fork ); const { forkedNetwork } = await fork.metadata(); expect(forkedNetwork).toMatchObject({ chainId: 1, forkBlockNumber: Number(forkBlock), }); ``` Changes stay local: ```ts snippet="examples/test/e2e/forking.e2e.test.ts#fork-local" await fork.cheats.setBalanceEther(HOLDER, 1); // gas for the holder await fork.confirm( fork.testClient.writeContract({ address: token, abi: exampleToken.abi, functionName: "transfer", args: [alice, parseEther("250000")], }), ); expect(await balanceOf(fork.testClient, token, alice)).toBe( parseEther("250000"), ); expect(await balanceOf(mainnet.testClient, token, alice)).toBe(0n); ``` ### Choose the fork point Right before a transaction: ```ts snippet="examples/test/e2e/forking.e2e.test.ts#fork-at-transaction" const fork = await startFork( new AnvilOptions().fork .withForkUrl(forkUrl) .withForkTransactionHash(payment.transactionHash) .evm.withHardfork(Hardfork.Cancun), ); try { // Forked at the block before the payment: it has not happened yet. expect(await fork.testClient.getBlockNumber()).toBe( payment.blockNumber - 1n, ); expect(await fork.getBalance(RECIPIENT)).toBe(0n); } finally { await fork.stop(); } ``` Relative to the latest block: ```ts snippet="examples/test/e2e/forking.e2e.test.ts#fork-relative-block" const latest = await mainnet.testClient.getBlockNumber(); const fork = await startFork( new AnvilOptions().fork .withForkUrl(forkUrl) .withForkBlockNumber(-1) // negative: blocks before the latest .evm.withHardfork(Hardfork.Cancun), ); try { const { forkedNetwork } = await fork.metadata(); expect(forkedNetwork?.forkBlockNumber).toBe(Number(latest - 1n)); } finally { await fork.stop(); } ``` ### Real providers Offline chain id, credentials, rate limits: ```ts snippet="examples/test/e2e/forking.e2e.test.ts#fork-offline-chain-id" const fork = await startFork( new AnvilOptions().fork .withForkUrl(forkUrl, forkBlock) // needs a block number or tx hash .withForkChainId(1) // skips eth_chainId on startup .evm.withHardfork(Hardfork.Cancun), ); try { expect(fork.chainId).toBe(1); expect(await balanceOf(fork.testClient, token, HOLDER)).toBe( parseEther("1000000"), ); } finally { await fork.stop(); } ``` ```ts snippet="examples/test/e2e/forking.e2e.test.ts#fork-provider" const fork = await startFork( new AnvilOptions().fork .withForkUrl(forkUrl, forkBlock) .withForkHeader("Authorization: Bearer ") // every upstream request .withComputeUnitsPerSecond(100) // stay under the provider's rate limit .evm.withHardfork(Hardfork.Cancun), ); try { expect(await balanceOf(fork.testClient, token, HOLDER)).toBe( parseEther("1000000"), ); } finally { await fork.stop(); } ``` ```ts snippet="examples/test/unit/options.test.ts#fork-headers" const options = new AnvilOptions().fork .withForkUrl("https://rpc.example@19000000") // url@block works too .withForkHeaders("Authorization: Bearer ", "X-Team: qa") // replace all .withForkHeader("X-Run: 42"); // add one expect(options.toCommand()).toBe( "anvil --host 0.0.0.0 --fork-url https://rpc.example --fork-block-number 19000000 " + "--fork-header 'Authorization: Bearer ' --fork-header 'X-Team: qa' " + "--fork-header 'X-Run: 42'", ); ``` | Need | Option | |---|---| | retries / backoff | `withRetries(n)`, `withForkRetryBackoff(ms)` | | per-request timeout | `withTimeout(ms)` | | rate limits | `withComputeUnitsPerSecond(cups)`, `noRateLimit()` | | no disk cache | `noStorageCaching()` | | multicall | test client `withMulticall3()` | Slow upstreams may need `container.withStartupTimeout(ms)`. ### Fork a node in another container Join a Docker network with aliases (`withNetwork()`, `withNetworkAliases()`; the examples' `network` helper wraps them): ```ts snippet="examples/test/e2e/forking.e2e.test.ts#upstream" mainnet = await network .attach( new AnvilContainer(new AnvilOptions().evm.withChainId(1)), "mainnet", "mainnet-backup", // a second endpoint, see setRpcUrl below ) .withTestClient((client) => client.withAccount(0)) .start(); token = await deployToken(mainnet.testClient, "Mainnet USD", "mUSD"); await mint(mainnet.testClient, token, HOLDER, parseEther("1000000")); forkBlock = await mainnet.testClient.getBlockNumber(); await mint(mainnet.testClient, token, HOLDER, 1n); // after the fork block forkUrl = network.urlOf(mainnet, "mainnet"); ``` ### Concepts - [A fork's hardfork follows the forked chain](../../concepts/anvil-behaviours.md#forks) - Reference: [`.fork` options](../../reference/anvil-options.md#fork) --- ## Reset or move a fork `reset()` on a forked node re-forks at its fork block, discarding local changes. ### Back to the fork block ```ts snippet="examples/test/e2e/forking.e2e.test.ts#fork-reset" await fork.cheats.dealErc20(token, HOLDER, 0n).mine(10); await fork.reset(); expect(await fork.testClient.getBlockNumber()).toBe(forkBlock); expect(await balanceOf(fork.testClient, token, HOLDER)).toBe( parseEther("1000000"), ); ``` ### Another block ```ts snippet="examples/test/e2e/forking.e2e.test.ts#fork-move" await fork.reset({ blockNumber: forkBlock + 1n }); expect(await balanceOf(fork.testClient, token, HOLDER)).toBe( parseEther("1000000") + 1n, // now includes the later mint ); ``` `reset({ jsonRpcUrl })` re-forks from another URL. ### Another endpoint ```ts snippet="examples/test/e2e/forking.e2e.test.ts#set-rpc-url" const backup = network.urlOf(mainnet, "mainnet-backup"); await fork.cheats.setRpcUrl(backup); // e.g. fail over to another provider expect((await fork.nodeInfo()).forkConfig.forkUrl).toBe(backup); await fork.reset(); // re-forks through the new endpoint expect(await balanceOf(fork.testClient, token, HOLDER)).toBe( parseEther("1000000"), ); ``` `reset()` discards snapshots: don't combine it with `useAnvil()`'s per-test isolation in one file ([Reset the chain](../test-suites/reset-the-chain.md)). ### Concepts - [`reset()` vs. viem's `reset`](../../concepts/anvil-behaviours.md#reset) --- ## Boot from a custom genesis `state.withInit(file)` boots from a genesis file; `withTimestamp()` and `withBlockNumber()` adjust the start. ### Pre-deployed contracts and balances ```ts snippet="examples/test/e2e/state-fixtures.e2e.test.ts#genesis" const ORACLE: Address = "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419"; const TREASURY: Address = "0x1111111111111111111111111111111111111111"; const genesisFile = path.join(directory, "genesis.json"); fs.writeFileSync( genesisFile, JSON.stringify({ config: { chainId: 1337 }, timestamp: numberToHex(1_700_000_000), gasLimit: numberToHex(30_000_000), alloc: { [TREASURY]: { balance: numberToHex(parseEther("1000000")) }, [ORACLE]: { balance: "0x0", // required by anvil for every entry code: oracleCode, // runtime code: the contract exists from block 0 storage: { [numberToHex(0, { size: 32 })]: numberToHex( parseUnits("3000", 8), { size: 32, }, ), }, }, }, }), ); const anvil = await new AnvilContainer( new AnvilOptions().state.withInit(genesisFile), ).start(); try { expect(anvil.chainId).toBe(1337); expect(await anvil.getBalance(TREASURY)).toBe(parseEther("1000000")); expect( await anvil.testClient.readContract({ address: ORACLE, abi: fixedPriceOracle.abi, functionName: "latestPrice", }), ).toBe(parseUnits("3000", 8)); const genesis = await anvil.testClient.getBlock({ blockNumber: 0n }); expect(genesis.timestamp).toBe(1_700_000_000n); } finally { await anvil.stop(); } ``` Every `alloc` entry needs a `balance` (`"0x0"` for contracts); `code` is runtime code. ### A fixed genesis time `state.withTimestamp(seconds | Date)`: ```ts snippet="examples/test/e2e/time-travel.e2e.test.ts#interval-mining" const GENESIS = new Date("2030-06-01T00:00:00Z"); const node = useAnvil( new AnvilContainer( new AnvilOptions().mining .withBlockTime(1) // a block every second, like a real chain .state.withTimestamp(GENESIS), ), { isolation: "none" }, ); it("starts at the configured genesis time and mines on its own", async () => { const genesis = await node.testClient.getBlock({ blockNumber: 0n }); expect(genesis.timestamp).toBe(BigInt(GENESIS.getTime() / 1000)); expect(await node.testClient.getIntervalMining()).toBe(1); const start = await node.testClient.getBlockNumber(); await waitFor(async () => (await node.testClient.getBlockNumber()) > start); }); it("stops and restarts interval mining at runtime", async () => { await node.cheats.setIntervalMining(0); // off: blocks only on demand expect(await node.testClient.getIntervalMining()).toBeUndefined(); const height = await node.testClient.getBlockNumber(); await new Promise((resolve) => setTimeout(resolve, 1_500)); expect(await node.testClient.getBlockNumber()).toBe(height); await node.cheats.setIntervalMining(1); await waitFor( async () => (await node.testClient.getBlockNumber()) > height, ); }); ``` ### A mainnet-like height `mining.withBlockNumber(n)`: ```ts snippet="examples/test/e2e/node-configuration.e2e.test.ts#history" // Long-running suites: keep only the latest state in memory. const pruned = useAnvil( new AnvilContainer(new AnvilOptions().state.withPruneHistory()), { isolation: "none" }, ); // Start at a mainnet-like height. const tall = useAnvil( new AnvilContainer(new AnvilOptions().mining.withBlockNumber(20_000_000)), ); it("answers historical queries only without pruning", async () => { const [alice] = await pruned.addresses(); await pruned.cheats.setBalanceEther(alice, 1).mine(3); await expect( pruned.testClient.getBalance({ address: alice, blockNumber: 1n }), ).rejects.toThrow(/block height/); expect(await pruned.getBalance(alice)).toBe(parseEther("1")); }); it("starts at the configured block number", async () => { expect(await tall.testClient.getBlockNumber()).toBe(20_000_000n); }); ``` ### Concepts - [Startup, readiness and file transfers](../../concepts/startup-and-files.md) --- ## Limit history and memory anvil keeps every state and transaction by default; trim them for long runs. ### Keep only the latest state `state.withPruneHistory()` drops historical states (queries at old blocks fail): ```ts snippet="examples/test/e2e/node-configuration.e2e.test.ts#history" // Long-running suites: keep only the latest state in memory. const pruned = useAnvil( new AnvilContainer(new AnvilOptions().state.withPruneHistory()), { isolation: "none" }, ); // Start at a mainnet-like height. const tall = useAnvil( new AnvilContainer(new AnvilOptions().mining.withBlockNumber(20_000_000)), ); it("answers historical queries only without pruning", async () => { const [alice] = await pruned.addresses(); await pruned.cheats.setBalanceEther(alice, 1).mine(3); await expect( pruned.testClient.getBalance({ address: alice, blockNumber: 1n }), ).rejects.toThrow(/block height/); expect(await pruned.getBalance(alice)).toBe(parseEther("1")); }); it("starts at the configured block number", async () => { expect(await tall.testClient.getBlockNumber()).toBe(20_000_000n); }); ``` ### Forget old transactions ```ts snippet="examples/test/e2e/node-configuration.e2e.test.ts#transaction-keeper" // Keep transactions of the latest block only: older ones are forgotten. const forgetful = useAnvil( new AnvilContainer( new AnvilOptions().state.withTransactionBlockKeeper(1), ).withTestClient((client) => client.withAccount(0)), ); it("forgets transactions of older blocks", async () => { const [, bob] = await forgetful.addresses(); const { transactionHash: hash } = await forgetful.confirm( forgetful.testClient.sendTransaction({ to: bob, value: 1n }), ); expect(await forgetful.testClient.getTransaction({ hash })).toBeDefined(); await forgetful.mine(2); await expect( forgetful.testClient.getTransaction({ hash }), ).rejects.toThrow(/could not be found/); }); ``` ### Bound states on disk ```ts snippet="examples/test/unit/options.test.ts#history-limits" // Long-running nodes: keep at most 5 states on disk… const bounded = new AnvilOptions().state.withMaxPersistedStates(5); expect(bounded.toCommand()).toContain("--max-persisted-states 5"); // …or prune history instead: the two are mutually exclusive. expect(() => bounded.state.withPruneHistory()).toThrow( AnvilConfigurationError, ); ``` ### Concepts - Reference: [`.state` options](../../reference/anvil-options.md#state) --- ## Mock contracts and storage Write runtime code with `setCode` and storage with `setStorageAt`, at any address. ### Etch a test double `setCode` needs *runtime* code: deploy the double once and read it: ```ts snippet="examples/test/e2e/mocking-dependencies.e2e.test.ts#runtime-code" // setCode needs *runtime* code: deploy the test double once from its // creation bytecode (.bin) and read the code the constructor left behind. const template = await deployFixedPriceOracle(node.testClient); oracleCode = (await node.testClient.getCode({ address: template }))!; ``` Write it to the dependency's address, with storage: ```ts snippet="examples/test/e2e/mocking-dependencies.e2e.test.ts#etch" await anvil.cheats .setCode(ORACLE, oracleCode) .setStorageAt(ORACLE, 0, parseUnits("3000", 8)); // slot 0: `price` expect(await quote(anvil.testClient, consumer, parseEther("2"))).toBe( parseUnits("6000", 8), ); ``` `setCode(address, "0x")` removes it. ### Write a mapping entry ```ts snippet="examples/test/e2e/mocking-dependencies.e2e.test.ts#mapping-slot" // balanceOf is the 4th state variable (slot 3): entry = keccak256(key . slot) const slot = keccak256( encodeAbiParameters( [{ type: "address" }, { type: "uint256" }], [alice, 3n], ), ); expect(await anvil.testClient.getStorageAt({ address: token, slot })).toBe( numberToHex(1n, { size: 32 }), ); // confirms the layout await anvil.cheats.setStorageAt(token, slot, parseEther("500")); expect(await balanceOf(anvil.testClient, token, alice)).toBe( parseEther("500"), ); ``` ### Mock for one call only ```ts snippet="examples/test/e2e/mocking-dependencies.e2e.test.ts#state-override" // The override exists only inside this eth_call: nothing is written. const { result } = await anvil.testClient.simulateContract({ address: consumer, abi: priceConsumer.abi, functionName: "quote", args: [parseEther("1")], stateOverride: [ { address: ORACLE, code: oracleCode, stateDiff: [ { slot: numberToHex(0, { size: 32 }), value: numberToHex(parseUnits("2500", 8), { size: 32 }), }, ], }, ], }); expect(result).toBe(parseUnits("2500", 8)); expect(await anvil.testClient.getCode({ address: ORACLE })).toBeUndefined(); ``` ### Concepts - [Simulate before sending](../transactions/simulate-calls.md) - Reference: [cheats](../../reference/cheats.md) --- ## Save and load chain state Dump the state to a file once, then boot or load other nodes from it. ### Save a fixture to a file ```ts snippet="examples/test/e2e/state-fixtures.e2e.test.ts#build-fixture" const builder = await new AnvilContainer() .withTestClient((client) => client.withAccount(0)) .start(); try { token = await deployToken(builder.testClient); holders = await builder.addresses(); for (const holder of holders) { await mint(builder.testClient, token, holder, parseEther("1000")); } await builder.dumpStateToFile(fixtureFile); // the `--load-state` format oracleCode = (await builder.testClient.getCode({ address: await deployFixedPriceOracle(builder.testClient), }))!; } finally { await builder.stop(); } ``` ### Boot a node from it ```ts snippet="examples/test/e2e/state-fixtures.e2e.test.ts#boot-from-fixture" const anvil = await new AnvilContainer( new AnvilOptions().state.withLoadState(fixtureFile), ).start(); try { expect(await balanceOf(anvil.testClient, token, holders[9])).toBe( parseEther("1000"), ); } finally { await anvil.stop(); } ``` ### Load it into a running node ```ts snippet="examples/test/e2e/state-fixtures.e2e.test.ts#load-at-runtime" await anvil.loadStateFromFile(fixtureFile); ``` Loading merges into the current state and discards snapshots. ### In memory ```ts snippet="examples/test/e2e/state-fixtures.e2e.test.ts#dump-in-memory" await anvil.setBalanceEther(alice, 42); const state = await anvil.dumpState(); // hex blob, e.g. to cache between suites await anvil.reset(); // back to genesis: the balance is gone… expect(await anvil.getBalance(alice)).toBe(parseEther("10000")); await anvil.loadState(state); // …and restored expect(await anvil.getBalance(alice)).toBe(parseEther("42")); ``` ### Let anvil dump on stop `withDumpState()` / `withState()` take host paths, copied in and out by `stop()`: ```ts snippet="examples/test/unit/options.test.ts#state-files" const configuration = new AnvilOptions().state .withDumpState("./out/state.json") // copied to the host by stop() .withStateInterval(30) // also dump every 30 s while running .withPreserveHistoricalStates() // include historical states in dumps .build(); expect(configuration.fileExports).toEqual([ { flag: "--dump-state", hostPath: path.resolve("out/state.json"), containerPath: "/tmp/anvil-dump-state.json", when: "stop", }, ]); // --state loads the file when it exists and dumps to it on stop. const persistent = new AnvilOptions().state .withState("./.anvil/state.json") .build(); expect(persistent.fileImports[0].required).toBe(false); expect(persistent.fileExports[0].when).toBe("stop"); ``` anvil's resolved configuration, copied out after start: ```ts snippet="examples/test/unit/options.test.ts#config-out" // anvil's resolved config (incl. dev keys), copied out right after start. const configuration = new AnvilOptions().state .withConfigOut("./out/anvil-config.json") .build(); expect(configuration.fileExports[0]).toMatchObject({ flag: "--config-out", when: "start", }); ``` Files in your image: `containerPath()`: ```ts snippet="examples/test/unit/options.test.ts#container-path" const baked = containerPath("/data/fixture.json"); // not copied const configuration = new AnvilOptions().state.withLoadState(baked).build(); expect(isContainerPath(baked)).toBe(true); expect(configuration.args).toContain("/data/fixture.json"); expect(configuration.fileImports).toEqual([]); ``` ### Concepts - [Startup, readiness and file transfers](../../concepts/startup-and-files.md) - [Performance: fast suites](../../concepts/performance.md) --- ## Script state changes `anvil.cheats` queues steps and runs them in order when awaited: ```ts snippet="examples/test/e2e/whales-and-impersonation.e2e.test.ts#cheat-chain" await anvil.cheats .setBalanceEther(WHALE, 1) .dealErc20(token, WHALE, parseEther("10")) .impersonate(WHALE) .step( (client) => client.writeContract({ account: WHALE, address: token, abi: exampleToken.abi, functionName: "transfer", args: [alice, parseEther("10")], }), "whale pays alice", // label used in error messages ) .stopImpersonating(WHALE) .mine(); ``` `step(fn, label?)` inserts any client call between cheats. ### Inspect and run a chain ```ts snippet="examples/test/e2e/cheats.e2e.test.ts#cheat-plan" const chain = anvil.cheats.setBalanceEther(ALICE, 1.5).mine(2); expect(chain.plan).toEqual([`setBalanceEther(${ALICE}, 1.5)`, "mine(2)"]); await chain.run(); // same as `await chain`; a chain runs once expect(await anvil.getBalance(ALICE)).toBe(parseEther("1.5")); ``` ### Step failures A failing step rejects with `CHEAT_FAILED`, naming the step; the rest are skipped: ```ts snippet="examples/test/e2e/cheats.e2e.test.ts#cheat-errors" const error = await anvil.cheats .mine() .setMinGasPrice(parseGwei("1")) // rejected while EIP-1559 is active .mine() .catch((e: unknown) => e); expect(error).toBeInstanceOf(AnvilTestClientError); expect((error as AnvilTestClientError).code).toBe("CHEAT_FAILED"); expect((error as Error).message).toMatch( /step 2\/3 setMinGasPrice\(1000000000n\) failed: .*\(steps 1–1 were applied\)/, ); ``` A chain runs once (`CHEATS_ALREADY_RUN`): ```ts snippet="examples/test/e2e/cheats.e2e.test.ts#cheat-once" const chain = anvil.cheats.mine(); await chain.finally(() => undefined); // then / catch / finally run it too expect(() => chain.mine()).toThrow( /cheats chain that has already run; start a new chain/, // CHEATS_ALREADY_RUN ); ``` ### Concepts - [Architecture: node, test client, cheats](../../concepts/architecture.md) - Reference: [every cheats step](../../reference/cheats.md) --- ## Catch misconfiguration in unit tests Setters validate immediately and reject conflicting flags: ```ts snippet="examples/test/unit/configuration.test.ts#conflicts" expect(() => new AnvilOptions().mining.withNoMining().mining.withBlockTime(1), ).toThrow(AnvilConfigurationError); ``` `prepare()` checks the test client against the anvil options, without starting anything: ```ts snippet="examples/test/unit/configuration.test.ts#pre-start" const container = new AnvilContainer( new AnvilOptions().account.withAccounts(2), ).withTestClient((client) => client.withAccount(5)); expect(() => container.prepare()).toThrow( AnvilTestClientConfigurationError, ); expect(() => container.prepare()).toThrow( /dev account 5 does not exist: anvil is configured with 2 account\(s\)/, ); ``` Dependencies that need the whole configuration (e.g. fork options without a fork URL) are reported by `validate()`, `problems()` and `build()`: ```ts snippet="examples/test/unit/options.test.ts#validate" // Setters reject conflicts at once; dependencies need the whole picture. const incomplete = new AnvilOptions().fork.withRetries(3); // no fork URL yet expect(() => incomplete.validate()).toThrow(AnvilConfigurationError); const [problem] = incomplete.problems(); // the same, without throwing expect(problem.flag).toBe("--retries"); expect(problem.relatedFlags).toEqual(["--fork-url"]); const configuration = incomplete.fork .withForkUrl("https://rpc.example", 19_000_000) .build(); // validate() + freeze expect(configuration.forking).toBe(true); expect(configuration.command).toContain("--fork-block-number"); expect(Object.isFrozen(configuration)).toBe(true); ``` ### Concepts - [Validation model](../../concepts/validation.md) - Reference: [Flag rules](../../reference/flag-rules.md), [Errors](../../reference/errors.md) --- ## Isolate state inside a test `useAnvil()` already isolates tests from each other. Inside one test: ### Roll back a block of code ```ts snippet="examples/test/e2e/fixtures-and-isolation.e2e.test.ts#what-if" const whatIf = await anvil.withSnapshot(async (client) => { await anvil.cheats.dealErc20(token, alice, 0n); return balanceOf(client, token, alice); }); expect(whatIf).toBe(0n); // inside the snapshot expect(await balanceOf(anvil.testClient, token, alice)).toBe( parseEther("100"), // reverted afterwards ); ``` ### Restore the same state many times `checkpoint()` re-arms after every `restore()`: ```ts snippet="examples/test/e2e/fixtures-and-isolation.e2e.test.ts#checkpoint" const start = await anvil.checkpoint(); // restorable any number of times for (const amount of [1n, 50n, 100n]) { await anvil.confirm( anvil.testClientFor(alice).writeContract({ address: token, abi: exampleToken.abi, functionName: "transfer", args: [vault, parseEther(String(amount))], }), ); expect(await balanceOf(anvil.testClient, token, vault)).toBe( parseEther(String(amount)), ); await start.restore(); // back to the state before the transfer } ``` ### Manage snapshots yourself Each snapshot can be reverted to once; reusing it throws `SNAPSHOT_NOT_FOUND`: ```ts snippet="examples/test/e2e/fixtures-and-isolation.e2e.test.ts#strict-snapshots" const id = await anvil.snapshot(); await anvil.revert(id); const error = await anvil.revert(id).catch((e: unknown) => e); expect(error).toBeInstanceOf(AnvilTestClientError); expect((error as AnvilTestClientError).code).toBe("SNAPSHOT_NOT_FOUND"); ``` ### Pending transactions Reverting keeps pending transactions; `useAnvil()` empties the pool, elsewhere call `anvil.cheats.dropAllTransactions()`. ```ts snippet="examples/test/e2e/mempool-and-blocks.e2e.test.ts#pool-isolation" it("may leave transactions pending…", async () => { const [, alice, bob] = await anvil.addresses(); await anvil.testClientFor(alice).sendTransaction({ to: bob }); expect((await anvil.testClient.getTxpoolStatus()).pending).toBe(1); }); it("…because useAnvil empties the pool between tests", async () => { // Reverting a snapshot alone would keep them (and mine them next block). expect((await anvil.testClient.getTxpoolStatus()).pending).toBe(0); }); ``` :::caution Node settings are not part of snapshots Mining mode, impersonation, gas limit, coinbase, logging and the chain id survive a revert: restore them in `finally`. ::: ### Concepts - [How per-test isolation works](../../concepts/isolation.md) - Reference: [`StartedAnvilContainer` state methods](../../reference/started-anvil-container.md#state) --- ## Load contract artifacts `loadContractAbi()` / `loadContractBytecode()` read plain ABI / `.bin` files or Foundry/Hardhat artifacts: ```ts snippet="examples/src/artifacts.ts#load-artifact" /** Loads `artifacts//.json` and `.bin`. */ export function loadArtifact(name: string): ContractArtifact { return { name, abi: loadContractAbi(`${name}/${name}.json`, ARTIFACTS_DIR), bytecode: loadContractBytecode(`${name}/${name}.bin`, ARTIFACTS_DIR), }; } ``` Relative paths resolve against `/test/artifacts` or `withArtifactsDir()`: ```ts snippet="examples/test/e2e/fixtures-and-isolation.e2e.test.ts#container-artifacts" const abi = anvil.contractAbi("ExampleToken/ExampleToken.json"); const bytecode = anvil.contractBytecode("ExampleToken/ExampleToken.bin"); const [deployer] = await anvil.addresses(); const receipt = await anvil.deployContract(abi, bytecode, deployer, [ "Second", "TWO", ]); expect( await anvil.testClient.readContract({ address: receipt.contractAddress!, abi, functionName: "symbol", }), ).toBe("TWO"); ``` A deploy helper returning a checksummed address: ```ts snippet="examples/src/deploy.ts#deploy-helper" /** * Deploys an artifact and returns the new contract's checksummed address * (receipts carry it lowercase; contract reads return checksummed addresses). */ export async function deployContract( client: SignerClient, artifact: ContractArtifact, args: readonly unknown[] = [], ): Promise
{ const hash = await client.deployContract({ abi: artifact.abi, bytecode: artifact.bytecode, args, }); const { contractAddress } = await client.confirmTransaction({ hash }); if (!contractAddress) throw new Error(`${hash} created no contract`); return getAddress(contractAddress); } ``` JSON ABIs are typed `Abi`, so reads return `unknown`: narrow them in helpers, or use `parseAbiItem` ([Query logs](../events/query-logs.md)). ### Concepts - Reference: [`loadContractAbi` / `loadContractBytecode`](../../reference/exports.md#functions) --- ## Manage the node lifecycle `useAnvil()` fits most suites; start and stop nodes yourself when you need control. ### Start and stop manually ```ts snippet="examples/test/e2e/lifecycle.e2e.test.ts#manual-lifecycle" let anvil: StartedAnvilContainer; beforeAll(async () => { anvil = await new AnvilContainer(new AnvilOptions().logs.quiet()) .withStartupTimeout(120_000) // first run: image pull .start(); }, 120_000); afterAll(async () => { await anvil?.stop(); }); it("uses the started node", async () => { expect(await anvil.testClient.getBlockNumber()).toBe(0n); }); ``` Or `await using anvil = await container.start()` (TypeScript 5.2+). ### Pass hooks explicitly For runners without Jest-style globals: ```ts snippet="examples/test/e2e/lifecycle.e2e.test.ts#explicit-hooks" // Pass the hooks yourself when your runner has no Jest-style globals. const anvil = useAnvil(new AnvilContainer(), { hooks: { beforeAll, afterAll, afterEach }, timeout: 120_000, // start/stop hook timeout }); ``` Mocha is detected automatically but ignores hook timeouts: raise `--timeout`. ### Run custom start logic `useAnvil()` takes anything with `start()`: ```ts snippet="examples/test/e2e/lifecycle.e2e.test.ts#start-function" // Any async start logic: the handle works the same way. const funded = useAnvil({ start: async () => { const node = await new AnvilContainer().start(); const [first] = await node.addresses(); await node.setBalanceEther(first, 1); return node; }, }); ``` ### After `stop()` Clients reject instead of hanging: ```ts snippet="examples/test/e2e/lifecycle.e2e.test.ts#after-stop" const anvil = await new AnvilContainer().start(); const client = anvil.testClient; await anvil.stop(); expect(anvil.isStopped).toBe(true); const error = await client.getBlockNumber().catch((e: unknown) => e); expect(error).toBeInstanceOf(AnvilTestClientError); expect((error as AnvilTestClientError).code).toBe("CONTAINER_STOPPED"); ``` With a state dump configured, `stop()` is graceful and copies the dump out first. ### Concepts - [Startup, readiness and file transfers](../../concepts/startup-and-files.md) - Reference: [`useAnvil()`](../../reference/use-anvil.md), [`AnvilContainer`](../../reference/anvil-container.md) --- ## Reset the chain `anvil.reset()` returns to genesis and discards every snapshot, so such files opt out of per-test isolation: ```ts snippet="examples/test/e2e/fixtures-and-isolation.e2e.test.ts#no-isolation" // reset() discards every snapshot, so this suite opts out of isolation. const node = useAnvil( new AnvilContainer().withTestClient((client) => client.withAccount(0)), { isolation: "none" }, ); let deployed: Address; it("deploys a token…", async () => { deployed = await deployToken(node.testClient); expect(await node.testClient.getCode({ address: deployed })).toBeDefined(); }); it("…which the next test still sees (no isolation)…", async () => { expect(await node.testClient.getCode({ address: deployed })).toBeDefined(); }); it("…until reset() returns the node to genesis", async () => { await node.reset(); expect(await node.testClient.getBlockNumber()).toBe(0n); expect( await node.testClient.getCode({ address: deployed }), ).toBeUndefined(); }); ``` - Forks re-fork at the fork block ([Reset a fork](../forking/reset-a-fork.md)). - Back to a prepared state: [`checkpoint()`](isolate-tests.md) or [`loadState()`](../state/save-and-load-state.md). ### Concepts - [`reset()` vs. viem's `reset`](../../concepts/anvil-behaviours.md#reset) - [How per-test isolation works](../../concepts/isolation.md) --- ## Share one node per test file Wrap the container in `useAnvil()` and deploy fixtures in `setup`: ```ts snippet="examples/test/e2e/fixtures-and-isolation.e2e.test.ts#fixture" let token: Address; let vault: Address; const anvil = useAnvil( new AnvilContainer( new AnvilOptions().account .withMnemonic(MNEMONIC) .withAccounts(3) .withBalance(1_000), // ETH per dev account ) .withArtifactsDir(ARTIFACTS_DIR) // for anvil.contractAbi() / contractBytecode() .withTestClient( (client) => client.withAccount(0), // deployer signs by default ), { // Runs once after start; every test then starts from this state. setup: async (node) => { const [, alice, bob] = await node.addresses(); token = await deployToken(node.testClient); vault = await deployVault(node.testClient, token, 86_400n); await mint(node.testClient, token, alice, parseEther("100")); await mint(node.testClient, token, bob, parseEther("100")); }, }, ); ``` Each test starts from the post-`setup` state: ```ts snippet="examples/test/e2e/fixtures-and-isolation.e2e.test.ts#isolation" it("may change any state…", async () => { const [, alice, bob] = await anvil.addresses(); await anvil.confirm( anvil.testClientFor(alice).writeContract({ address: token, abi: exampleToken.abi, functionName: "transfer", args: [bob, parseEther("100")], }), ); await anvil.cheats.mine(100).increaseTime({ days: 365 }); expect(await balanceOf(anvil.testClient, token, alice)).toBe(0n); }); it("…because the next test starts from the fixture again", async () => { const [, alice] = await anvil.addresses(); expect(await balanceOf(anvil.testClient, token, alice)).toBe( parseEther("100"), ); }); ``` ### Settings | Setting | Default | Use it to | |---|---|---| | `setup: (node) => …` | – | deploy contracts, fund accounts; runs once after start | | `isolation` | `"test"` | `"none"` lets state carry over (e.g. suites that call `reset()`) | | `timeout` | `120_000` ms | give start/stop hooks time to pull the image | | `hooks` | framework globals | pass `beforeAll` / `afterAll` / `afterEach` yourself | Use the handle in tests and hooks only (`NOT_STARTED` at `describe` level). ### Concepts - [How per-test isolation works](../../concepts/isolation.md) - [Performance: fast suites](../../concepts/performance.md) - Reference: [`useAnvil()`](../../reference/use-anvil.md) --- ## Control block contents These samples run on a node with `mining.withNoMining()`. ### Several transactions in one block ```ts snippet="examples/test/e2e/mempool-and-blocks.e2e.test.ts#one-block" const hashes: Hash[] = []; for (const amount of [1n, 2n, 3n]) { hashes.push( await asAlice.writeContract({ address: token, abi: exampleToken.abi, functionName: "transfer", args: [bob, parseEther(String(amount))], }), ); } expect(await anvil.testClient.getTxpoolStatus()).toEqual({ pending: 3, queued: 0, }); await anvil.mine(); const receipts = await Promise.all( hashes.map((hash) => anvil.confirm(hash)), ); expect(new Set(receipts.map((r) => r.blockNumber)).size).toBe(1); ``` ### Ordering By fee (default, `--order fees`): anvil ranks by `maxFeePerGas`. ```ts snippet="examples/test/e2e/mempool-and-blocks.e2e.test.ts#fee-order" // anvil ranks pending transactions by their fee cap (maxFeePerGas). const cheap = await anvil.testClientFor(alice).sendTransaction({ to: bob, maxFeePerGas: parseGwei("20"), maxPriorityFeePerGas: parseGwei("1"), }); const generous = await anvil.testClientFor(bob).sendTransaction({ to: alice, maxFeePerGas: parseGwei("200"), maxPriorityFeePerGas: parseGwei("2"), }); await anvil.mine(); const block = await anvil.testClient.getBlock(); expect(block.transactions).toEqual([generous, cheap]); // sent later, mined first ``` By arrival (`state.withOrder(Order.Fifo)`): ```ts snippet="examples/test/e2e/mempool-and-blocks.e2e.test.ts#fifo" const node = useAnvil( new AnvilContainer( new AnvilOptions().mining.withNoMining().state.withOrder(Order.Fifo), ), ); it("mines in arrival order regardless of fees", async () => { const [alice, bob] = await node.addresses(); const cheap = await node.testClientFor(alice).sendTransaction({ to: bob, maxFeePerGas: parseGwei("20"), maxPriorityFeePerGas: parseGwei("1"), }); const generous = await node.testClientFor(bob).sendTransaction({ to: alice, maxFeePerGas: parseGwei("200"), maxPriorityFeePerGas: parseGwei("2"), }); await node.mine(); expect((await node.testClient.getBlock()).transactions).toEqual([ cheap, generous, ]); }); ``` ### Inspect and edit the mempool ```ts snippet="examples/test/e2e/mempool-and-blocks.e2e.test.ts#txpool" const first = await anvil.testClientFor(alice).sendTransaction({ to: bob }); await anvil.testClientFor(bob).sendTransaction({ to: alice }); const { pending } = await anvil.testClient.getTxpoolContent(); expect(Object.keys(pending)).toHaveLength(2); // two senders await anvil.cheats.dropTransaction(first); // alice's is gone… await anvil.cheats.removePoolTransactions(bob); // …and everything from bob expect(await anvil.testClient.getTxpoolStatus()).toEqual({ pending: 0, queued: 0, }); await anvil.testClientFor(alice).sendTransaction({ to: bob }); await anvil.cheats.dropAllTransactions(); // or clear the pool at once expect((await anvil.testClient.getTxpoolStatus()).pending).toBe(0); ``` ### Block gas limit ```ts snippet="examples/test/e2e/mempool-and-blocks.e2e.test.ts#gas-limit" await anvil.cheats.setBlockGasLimit(50_000n); // room for two 21k transfers try { for (let i = 0; i < 3; i++) { await anvil.testClientFor(alice).sendTransaction({ to: bob }); } await anvil.mine(); expect((await anvil.testClient.getBlock()).transactions).toHaveLength(2); expect((await anvil.testClient.getTxpoolStatus()).pending).toBe(1); } finally { await anvil.cheats.setBlockGasLimit(30_000_000n); // node setting: restore } await anvil.mine(); expect((await anvil.testClient.getBlock()).transactions).toHaveLength(1); ``` ### Base fee and coinbase ```ts snippet="examples/test/e2e/mempool-and-blocks.e2e.test.ts#fees" await anvil.cheats .setCoinbase(BUILDER) .setNextBlockBaseFeePerGas(parseGwei("10")); try { const hash = await anvil.testClientFor(alice).sendTransaction({ to: bob, maxFeePerGas: parseGwei("20"), maxPriorityFeePerGas: parseGwei("2"), }); await anvil.mine(); const receipt = await anvil.confirm(hash); expect((await anvil.testClient.getBlock()).baseFeePerGas).toBe( parseGwei("10"), ); expect(receipt.effectiveGasPrice).toBe(parseGwei("12")); // base fee + tip // The base fee is burned; the coinbase earns only the tip. expect(await anvil.getBalance(BUILDER)).toBe( parseGwei("2") * receipt.gasUsed, ); } finally { await anvil.cheats.setCoinbase(miner); // node setting: restore } ``` ### Legacy gas pricing `setMinGasPrice()` works on pre-London hardforks only: ```ts snippet="examples/test/e2e/mempool-and-blocks.e2e.test.ts#legacy-gas" const node = useAnvil( new AnvilContainer(new AnvilOptions().evm.withHardfork(Hardfork.Berlin)), ); it("sets the gas price the node suggests", async () => { const [alice, bob] = await node.addresses(); await node.cheats.setMinGasPrice(parseGwei("5")); expect(await node.testClient.getGasPrice()).toBe(parseGwei("5")); const receipt = await node.confirm( node.testClient.sendTransaction({ account: alice, to: bob, gasPrice: await node.testClient.getGasPrice(), // explicit on pre-London chains }), ); expect(receipt.type).toBe("legacy"); expect(receipt.effectiveGasPrice).toBe(parseGwei("5")); }); ``` ### Concepts - [anvil behaviours worth knowing](../../concepts/anvil-behaviours.md) - [Control mining](control-mining.md) --- ## Control mining anvil mines a block per transaction by default (automine). ### On demand only ```ts snippet="examples/test/e2e/mempool-and-blocks.e2e.test.ts#no-mining" // Blocks are only mined on demand (anvil --no-mining). confirm() and the // deploy fixtures mine a block when a transaction is still pending. const anvil = useAnvil( new AnvilContainer(new AnvilOptions().mining.withNoMining()).withTestClient( (client) => client.withAccount(0), ), { setup: async (node) => { const [, alice] = await node.addresses(); token = await deployToken(node.testClient); await mint(node.testClient, token, alice, parseEther("100")); }, }, ); ``` `confirm()` mines a block for you when a transaction is still pending. ### Toggle automine at runtime ```ts snippet="examples/test/e2e/mempool-and-blocks.e2e.test.ts#automine-toggle" const hash = await anvil.testClientFor(alice).sendTransaction({ to: bob, value: 5n, }); const { pending } = await anvil.testClient.inspectTxpool(); expect(JSON.stringify(pending)).toMatch(/5 wei \+ 21000 gas/); await anvil.cheats.setAutomine(true); // mines everything pending… try { expect( (await anvil.testClient.getTransactionReceipt({ hash })).status, ).toBe("success"); expect(await anvil.testClient.getAutomine()).toBe(true); } finally { await anvil.cheats.setAutomine(false); // …and back to on-demand mining } ``` ### On an interval ```ts snippet="examples/test/e2e/time-travel.e2e.test.ts#interval-mining" const GENESIS = new Date("2030-06-01T00:00:00Z"); const node = useAnvil( new AnvilContainer( new AnvilOptions().mining .withBlockTime(1) // a block every second, like a real chain .state.withTimestamp(GENESIS), ), { isolation: "none" }, ); it("starts at the configured genesis time and mines on its own", async () => { const genesis = await node.testClient.getBlock({ blockNumber: 0n }); expect(genesis.timestamp).toBe(BigInt(GENESIS.getTime() / 1000)); expect(await node.testClient.getIntervalMining()).toBe(1); const start = await node.testClient.getBlockNumber(); await waitFor(async () => (await node.testClient.getBlockNumber()) > start); }); it("stops and restarts interval mining at runtime", async () => { await node.cheats.setIntervalMining(0); // off: blocks only on demand expect(await node.testClient.getIntervalMining()).toBeUndefined(); const height = await node.testClient.getBlockNumber(); await new Promise((resolve) => setTimeout(resolve, 1_500)); expect(await node.testClient.getBlockNumber()).toBe(height); await node.cheats.setIntervalMining(1); await waitFor( async () => (await node.testClient.getBlockNumber()) > height, ); }); ``` ### Interval and automine together ```ts snippet="examples/test/e2e/time-travel.e2e.test.ts#mixed-mining" // Transactions are mined at once (automine) AND a block comes every second. const node = useAnvil( new AnvilContainer( new AnvilOptions().mining.withBlockTime(1).withMixedMining(), ), { isolation: "none" }, ); it("mines transactions on arrival while time keeps producing blocks", async () => { const [alice, bob] = await node.addresses(); const hash = await node.testClient.sendTransaction({ account: alice, to: bob, value: 1n, }); // No explicit mine(): automine picks the transaction up. const receipt = await node.testClient.waitForTransactionReceipt({ hash }); expect(receipt.status).toBe("success"); const height = await node.testClient.getBlockNumber(); await waitFor( async () => (await node.testClient.getBlockNumber()) > height, ); }); ``` | Mode | Option | Runtime | |---|---|---| | automine (default) | `mining.withAutoMining()` | `setAutomine(true)` | | on demand | `mining.withNoMining()` | `setAutomine(false)` + `mine()` | | interval | `mining.withBlockTime(seconds)` | `setIntervalMining(seconds)`, `0` stops it | | mixed | `mining.withBlockTime(s).withMixedMining()` | – | Mining settings are node settings: snapshots do not restore them. ### Concepts - [How per-test isolation works](../../concepts/isolation.md) - [anvil behaviours worth knowing](../../concepts/anvil-behaviours.md) --- ## Simulate reorgs and rollbacks `reorg()` replaces the last blocks, `rollback()` removes them. ### Reorg: a confirmed transaction disappears ```ts snippet="examples/test/e2e/chain-config-and-reorgs.e2e.test.ts#reorg" const receipt = await anvil.confirm( anvil.testClient.sendTransaction({ to: alice, value: parseEther("1") }), ); await anvil.mine(2); // 3 confirmations // Replace the last 3 blocks with empty ones: the transaction disappears. await anvil.testClient.reorg({ depth: 3 }); expect(await anvil.testClient.getBlockNumber()).toBe( receipt.blockNumber + 2n, // same height, different blocks ); await expect( anvil.testClient.getTransactionReceipt({ hash: receipt.transactionHash }), ).rejects.toThrow(/could not be found/); ``` ### Reorg with different transactions ```ts snippet="examples/test/e2e/chain-config-and-reorgs.e2e.test.ts#reorg-replace" // The new last block contains a payment to bob that never happened before. await anvil.testClient.reorg({ depth: 1, transactions: [ { transaction: { from: deployer, to: bob, value: parseEther("5") }, block: 0, }, ], }); expect(await anvil.getBalance(bob)).toBe(before + parseEther("5")); ``` Each `transactions` entry is a request (from an unlocked or impersonated account) or a signed raw transaction, placed in the `block`-th new block. ### Roll back the tip ```ts snippet="examples/test/e2e/chain-config-and-reorgs.e2e.test.ts#rollback" const height = await anvil.testClient.getBlockNumber(); await anvil.mine(5); await anvil.cheats.rollback(5); // remove the last 5 blocks (default 1) expect(await anvil.testClient.getBlockNumber()).toBe(height); await anvil.mine(); await anvil.testClient.rollback(); // the same as a test client action expect(await anvil.testClient.getBlockNumber()).toBe(height); ``` ### Concepts - Reference: [anvil extras](../../reference/anvil-actions.md) --- ## Fast-forward time Use `anvil.cheats.increaseTime()` and mine a block; time helpers take durations and `Date`s. ### Jump ahead The samples use a vault that locks alice's deposit for 30 days: ```ts snippet="examples/test/e2e/time-travel.e2e.test.ts#withdraw-helper" /** Simulates alice's withdrawal from the vault (throws while locked). */ const withdraw = () => anvil.testClientFor(alice).simulateContract({ address: vault, abi: timeLockVault.abi, functionName: "withdraw", }); ``` ```ts snippet="examples/test/e2e/time-travel.e2e.test.ts#fast-forward" await anvil.cheats.increaseTime({ days: 30 }).mine(); const { request } = await withdraw(); await anvil.confirm(anvil.testClientFor(alice).writeContract(request)); expect(await balanceOf(anvil.testClient, token, alice)).toBe( parseEther("10"), ); ``` Time moves with the next mined block. ### Hit an exact timestamp ```ts snippet="examples/test/e2e/time-travel.e2e.test.ts#boundary" const { unlockTime } = await vaultLock(anvil.testClient, vault, alice); const asAlice = anvil.testClientFor(alice); const sendWithdraw = () => asAlice.writeContract({ address: vault, abi: timeLockVault.abi, functionName: "withdraw", }); // signed by anvil: mined even when it reverts // One second early: mined, but reverted. await anvil.cheats.setNextBlockTimestamp(unlockTime - 1n); await expect(anvil.confirm(sendWithdraw())).rejects.toBeInstanceOf( AnvilTransactionRevertedError, ); // Exactly at the unlock time: succeeds. await anvil.cheats.setNextBlockTimestamp(unlockTime); const receipt = await anvil.confirm(sendWithdraw()); expect(receipt.status).toBe("success"); ``` ### Set the clock ```ts snippet="examples/test/e2e/time-travel.e2e.test.ts#set-time" const launch = new Date("2030-01-01T00:00:00Z"); await anvil.cheats.setTime(launch).mine(); const { timestamp } = await anvil.testClient.getBlock(); expect(timestamp).toBeGreaterThanOrEqual(BigInt(launch.getTime() / 1000)); // 2030 is long past the unlock time: the withdrawal goes through. const { request } = await withdraw(); expect( (await anvil.confirm(anvil.testClientFor(alice).writeContract(request))) .status, ).toBe("success"); ``` ### Regular block times ```ts snippet="examples/test/e2e/time-travel.e2e.test.ts#block-times" // Node settings are not part of snapshots: restore them yourself. await anvil.cheats.setBlockTimestampInterval(12); // 12 s "slots" try { const start = await anvil.latestTimestamp(); await anvil.mine(5); expect(await anvil.latestTimestamp()).toBe(start + 60n); } finally { await anvil.cheats.removeBlockTimestampInterval(); } ``` ### Blocks spaced in time ```ts snippet="examples/test/e2e/time-travel.e2e.test.ts#spaced-blocks" const before = await anvil.testClient.getBlockNumber(); await anvil.mine(3, { hours: 1 }); // three blocks, one hour apart const times = await Promise.all( [1n, 2n, 3n].map( async (offset) => (await anvil.testClient.getBlock({ blockNumber: before + offset })) .timestamp, ), ); expect([times[1] - times[0], times[2] - times[1]]).toEqual([3600n, 3600n]); ``` ### Durations and timestamps Seconds, unit objects and `Date`s: ```ts snippet="examples/test/unit/options.test.ts#units" expect(durationToSeconds({ days: 1, hours: 2 })).toBe(93_600n); expect(durationToSeconds(90)).toBe(90n); expect(timestampToSeconds(new Date("2030-01-01T00:00:00Z"))).toBe( 1_893_456_000n, ); expect(() => durationToSeconds({ days: -1 })).toThrow(RangeError); ``` A fixed start time: [Boot from a custom genesis](../state/custom-genesis.md). ### Concepts - [How per-test isolation works](../../concepts/isolation.md) (the block timestamp interval is a node setting) - Reference: [cheats](../../reference/cheats.md) --- ## Assert reverts and custom errors Simulate and match the decoded error; for mined transactions, check the receipt. ### Custom errors with arguments Simulate and match the decoded error: ```ts snippet="examples/test/e2e/custom-errors.e2e.test.ts#custom-error" await expectRevert( anvil.testClientFor(alice).simulateContract({ address: token, abi: exampleToken.abi, functionName: "transfer", args: [bob, 1n], }), "InsufficientBalance", [alice, 0n, 1n], ); ``` The core of the `expectRevert()` helper: ```ts snippet="examples/src/reverts.ts#decode-revert" /** Finds the decoded revert in an error chain (`undefined` if it is not a revert). */ export function decodeRevert(error: unknown): DecodedRevert | undefined { for ( let current = error as RevertLike | undefined; current && typeof current === "object"; current = current.cause as RevertLike | undefined ) { if (current.name === "ContractFunctionRevertedError") { return { errorName: current.data?.errorName ?? "unknown", args: current.data?.args ?? [], reason: current.reason, }; } } return undefined; } ``` Match by `name`: two copies of viem (e.g. `npm link`) break `instanceof`. ### Writes: who signs decides when it fails ```ts snippet="examples/test/e2e/custom-errors.e2e.test.ts#write-reverts" // Locally signed: viem estimates gas first, so the revert surfaces // immediately, decoded, and nothing is sent. const local = anvil.testClientFor(privateKeyToAccount(mallory.privateKey!)); const revert = await expectRevert( local.writeContract({ address: token, abi: exampleToken.abi, functionName: "mint", args: [mallory.address, parseEther("1000000")], }), "NotOwner", ); expect(revert.args).toEqual([mallory.address]); // Signed by anvil (dev/impersonated account): sent as-is, mined, reverted. const hash = await anvil.testClientFor(mallory.address).writeContract({ address: token, abi: exampleToken.abi, functionName: "mint", args: [mallory.address, parseEther("1000000")], }); await expect(anvil.confirm(hash)).rejects.toBeInstanceOf( AnvilTransactionRevertedError, ); ``` ### Reverted transactions that were mined ```ts snippet="examples/test/e2e/custom-errors.e2e.test.ts#mined-revert" const hash = await anvil.testClientFor(alice).writeContract({ address: token, abi: exampleToken.abi, functionName: "transfer", args: [bob, 1n], }); // signed by anvil: mined even though it reverts const error = await anvil.confirm(hash).catch((e: unknown) => e); expect(error).toBeInstanceOf(AnvilTransactionRevertedError); expect( (error as AnvilTransactionRevertedError).receipt.gasUsed, ).toBeGreaterThan(0n); // Or get the receipt without throwing: const receipt = await anvil.confirm(hash, { throwOnRevert: false }); expect(receipt.status).toBe("reverted"); ``` `AnvilTransactionRevertedError` carries `hash`, `receipt` and, when recoverable, `reason`. ### Panics ```ts snippet="examples/test/e2e/custom-errors.e2e.test.ts#panic" const panic = await expectRevert( anvil.testClient.simulateContract({ address: token, abi: exampleToken.abi, functionName: "mint", args: [alice, 1n], // totalSupply would overflow uint256 }), "Panic", [0x11n], // 0x11: arithmetic underflow or overflow ); expect(panic.reason).toMatch(/overflow/); ``` ### Raw revert data ```ts snippet="examples/test/e2e/custom-errors.e2e.test.ts#raw-revert" const error = (await anvil.testClient .call({ account: alice, to: token, data: encodeFunctionData({ abi: exampleToken.abi, functionName: "transfer", args: [bob, 1n], }), }) .catch((e: unknown) => e)) as BaseError; // The raw revert bytes sit on one error of the chain. const data = ( error.walk((e) => typeof (e as { data?: unknown }).data === "string") as { data?: Hex; } | null )?.data; const decoded = decodeErrorResult({ abi: exampleToken.abi, data: data!, }); expect(decoded.errorName).toBe("InsufficientBalance"); expect(decoded.args).toEqual([alice, 0n, 1n]); ``` ### Concepts - [Signing: anvil-signed vs. locally signed](../../concepts/signing.md) - [Trace a failed transaction](../debugging/trace-transactions.md) - Reference: [Errors](../../reference/errors.md) --- ## Estimate gas and fees viem's estimation actions work as on any chain, against your node. ### Gas and fees ```ts snippet="examples/test/e2e/simulation-and-gas.e2e.test.ts#estimates" const gas = await anvil.testClient.estimateContractGas({ account: alice, address: token, abi: exampleToken.abi, functionName: "transfer", args: [bob, 1n], }); const { maxFeePerGas, maxPriorityFeePerGas } = await anvil.testClient.estimateFeesPerGas(); const history = await anvil.testClient.getFeeHistory({ blockCount: 3, rewardPercentiles: [50], }); expect(gas).toBeGreaterThan(21_000n); expect(maxFeePerGas).toBeGreaterThan(maxPriorityFeePerGas); expect(history.baseFeePerGas.length).toBeGreaterThan(0); ``` ### Access lists (EIP-2930) ```ts snippet="examples/test/e2e/simulation-and-gas.e2e.test.ts#access-list" const data = encodeFunctionData({ abi: exampleToken.abi, functionName: "transfer", args: [bob, 1n], }); const { accessList, gasUsed } = await anvil.testClient.createAccessList({ account: alice, to: token, data, }); expect(accessList[0].address.toLowerCase()).toBe(token.toLowerCase()); expect(accessList[0].storageKeys.length).toBeGreaterThan(0); // both balances expect(gasUsed).toBeGreaterThan(0n); const receipt = await anvil.confirm( anvil .testClientFor(alice) .sendTransaction({ to: token, data, accessList }), ); expect(receipt.type).toBe("eip1559"); ``` ### Let the node fill a transaction ```ts snippet="examples/test/e2e/simulation-and-gas.e2e.test.ts#fill-transaction" const { transaction } = await anvil.testClient.fillTransaction({ account: alice, to: bob, value: 1n, }); expect(transaction).toMatchObject({ nonce: await anvil.testClient.getTransactionCount({ address: alice }), chainId: anvil.chainId, type: "eip1559", }); expect(transaction.gas).toBe(21_000n); ``` ### Storage proofs ```ts snippet="examples/test/e2e/simulation-and-gas.e2e.test.ts#proof" const totalSupplySlot = numberToHex(2, { size: 32 }); // 3rd state variable const proof = await anvil.testClient.getProof({ address: token, storageKeys: [totalSupplySlot], }); expect(proof.storageProof[0].value).toBe(parseEther("10")); expect(proof.accountProof.length).toBeGreaterThan(0); ``` To control the fees themselves (base fee, gas price, tips), see [Build blocks](../time-and-blocks/build-blocks.md) and [Configure the chain](../configure/chain.md). ### Concepts - [anvil behaviours worth knowing](../../concepts/anvil-behaviours.md) --- ## Read contracts efficiently Read through viem; bundle many reads into one call or one HTTP request. ### Contract instances ```ts snippet="examples/test/e2e/multi-actor-flows.e2e.test.ts#contract-instance" const tokenAsAlice = getContract({ address: token, abi: exampleToken.abi, client: anvil.testClientFor(alice), }); const gas = await tokenAsAlice.estimateGas.transfer([bob, 1n]); const hash = await tokenAsAlice.write.transfer([bob, 1n]); const receipt = await anvil.confirm(hash); expect(receipt.gasUsed).toBeLessThanOrEqual(gas); expect(await tokenAsAlice.read.balanceOf([bob])).toBe(1n); ``` ### Many values in one call No Multicall3 on a fresh chain? `deployless` runs it from bytecode: ```ts snippet="examples/test/e2e/multi-actor-flows.e2e.test.ts#multicall" // No Multicall3 on this chain: `deployless` runs it from bytecode in eth_call. const [name, supply, aliceBalance, broken] = await anvil.testClient.multicall({ deployless: true, allowFailure: true, contracts: [ { address: token, abi: exampleToken.abi, functionName: "name" }, { address: token, abi: exampleToken.abi, functionName: "totalSupply", }, { address: token, abi: exampleToken.abi, functionName: "balanceOf", args: [alice], }, { address: bob, abi: exampleToken.abi, functionName: "totalSupply" }, // not a contract ], }); expect(name).toEqual({ status: "success", result: "Example Token" }); expect(supply.result).toBe(parseEther("50")); expect(aliceBalance.result).toBe(parseEther("50")); expect(broken.status).toBe("failure"); // reported, not thrown ``` On forks of chains that have Multicall3, register it instead: `withTestClient((client) => client.withMulticall3())`. ### Batch concurrent requests ```ts snippet="examples/test/e2e/multi-actor-flows.e2e.test.ts#batching" const batched = await anvil.createTestClient( (client) => client.withBatch({ wait: 5 }), // collect requests for 5 ms per HTTP call ); const balances = await Promise.all( addresses.map((address) => balanceOf(batched, token, address)), ); ``` ### Your own clients ```ts snippet="examples/test/e2e/multi-actor-flows.e2e.test.ts#own-client" // e.g. the client your application code already creates: const appClient = createPublicClient({ chain: anvil.chain, // id, name and URLs of this node transport: http(anvil.rpcUrl), }).extend(anvilActions); // add the anvil extras to any viem client await appClient.addBalance({ address: alice, value: parseEther("1") }); const balance = await appClient.readContract({ address: token, abi: exampleToken.abi, functionName: "balanceOf", args: [alice], }); expect(balance).toBe(parseEther("50")); ``` ### Concepts - [Configure the test client](../configure/test-client.md) - [Architecture: node, test client, cheats](../../concepts/architecture.md) --- ## Send transactions and wait for receipts `anvil.confirm(hash | Promise)` returns the receipt (mining a block when automine is off) and throws `AnvilTransactionRevertedError` on revert: ```ts snippet="examples/test/e2e/quick-start.e2e.test.ts#quick-start" import { AnvilContainer, AnvilOptions, Hardfork, useAnvil, } from "@hellaweb3/foundryanvil-testcontainers-nodejs"; import { parseEther } from "viem"; const options = new AnvilOptions().account .withAccounts(5) .withBalance(1_000) // ETH per dev account .evm.withChainId(1337) .withHardfork(Hardfork.Cancun) .logs.quiet(); // Starts in beforeAll, stops in afterAll, restores the state after every test. const anvil = useAnvil( new AnvilContainer(options).withTestClient((client) => client.withAccount(0)), ); it("sends Ether", async () => { const [, bob] = await anvil.addresses(); // No `account` needed: dev account 0 is the typed default signer. const receipt = await anvil.confirm( anvil.testClient.sendTransaction({ to: bob, value: parseEther("1") }), ); expect(receipt.status).toBe("success"); expect(await anvil.testClient.getChainId()).toBe(1337); }); it("manipulates the chain fluently", async () => { const whale = "0x1111111111111111111111111111111111111111"; await anvil.cheats .setBalanceEther(whale, 1_000) .impersonate(whale) .increaseTime({ days: 7 }) .mine(); expect(await anvil.getBalance(whale)).toBe(parseEther("1000")); }); ``` | Option | Default | | |---|---|---| | `throwOnRevert` | `true` | `false` returns the reverted receipt | | `timeout` | `30_000` ms | receipt wait | ### Ether in one line ```ts snippet="examples/test/e2e/multi-actor-flows.e2e.test.ts#send-eth" const receipt = await anvil.sendEthTransaction(alice, bob, "1.5"); // Ether expect(receipt.status).toBe("success"); expect(await anvil.getBalance(bob)).toBe(before + parseEther("1.5")); ``` `anvil.deployContract(abi, bytecode, from, args)` for deployments. ### Receipt in the same call viem's `*Sync` actions (`eth_sendTransactionSync`): ```ts snippet="examples/test/e2e/multi-actor-flows.e2e.test.ts#sync" const receipt = await anvil.testClientFor(alice).writeContractSync({ address: token, abi: exampleToken.abi, functionName: "transfer", args: [bob, parseEther("2")], }); expect(receipt.status).toBe("success"); const payment = await anvil.testClientFor(bob).sendTransactionSync({ to: alice, value: parseEther("1"), }); expect(payment.blockNumber).toBe(receipt.blockNumber + 1n); ``` ### Nonces A nonce gap waits in the *queued* pool until filled: ```ts snippet="examples/test/e2e/multi-actor-flows.e2e.test.ts#nonces" const next = await anvil.testClient.getTransactionCount({ address: alice }); const later = await transfer(next + 1); // skips a nonce… expect(await anvil.testClient.getTxpoolStatus()).toEqual({ pending: 0, queued: 1, // …so it waits in the queue }); const first = await transfer(next); // fills the gap: both are mined const receipts = await Promise.all( [first, later].map((hash) => anvil.confirm(hash)), ); expect(receipts.map((receipt) => receipt.status)).toEqual([ "success", "success", ]); expect(await balanceOf(anvil.testClient, token, bob)).toBe(parseEther("2")); ``` ### Concepts - [Signing: anvil-signed vs. locally signed](../../concepts/signing.md) - Reference: [`confirm()` and transaction helpers](../../reference/started-anvil-container.md#transactions) --- ## Simulate before sending Simulate with viem: results come back, nothing is written. ### Simulate, then send exactly that ```ts snippet="examples/test/e2e/multi-actor-flows.e2e.test.ts#simulate" const { result, request } = await asAlice.simulateContract({ address: token, abi: exampleToken.abi, functionName: "transfer", args: [bob, parseEther("1")], }); expect(result).toBe(true); // typed from the ABI: boolean expect(await balanceOf(anvil.testClient, token, bob)).toBe(0n); // nothing sent yet await anvil.confirm(asAlice.writeContract(request)); expect(await balanceOf(anvil.testClient, token, bob)).toBe(parseEther("1")); ``` ### Several blocks, with time travel `simulateBlocks` (`eth_simulateV1`) runs calls across blocks with block overrides; nothing is written: ```ts snippet="examples/test/e2e/simulation-and-gas.e2e.test.ts#simulate-blocks" const now = (await anvil.testClient.getBlock()).timestamp; const [today, later] = await anvil.testClient.simulateBlocks({ blocks: [ { calls: [ { from: alice, to: token, abi: exampleToken.abi, functionName: "approve", args: [vault, 5n], }, { from: alice, to: vault, abi: timeLockVault.abi, functionName: "deposit", args: [5n], }, ], }, { blockOverrides: { time: now + 2n * LOCK }, // two days later calls: [ { from: alice, to: vault, abi: timeLockVault.abi, functionName: "withdraw", }, ], }, ], }); expect(today.calls.map((call) => call.status)).toEqual([ "success", "success", ]); expect(later.calls[0].status).toBe("success"); expect(later.timestamp).toBe(now + 2n * LOCK); // Nothing happened on chain: expect(await balanceOf(anvil.testClient, token, vault)).toBe(0n); ``` Failing calls are reported, not thrown: ```ts snippet="examples/test/e2e/simulation-and-gas.e2e.test.ts#simulate-failure" const [block] = await anvil.testClient.simulateBlocks({ blocks: [ { calls: [ { from: alice, to: vault, abi: timeLockVault.abi, functionName: "withdraw", }, { from: alice, to: token, abi: exampleToken.abi, functionName: "balanceOf", args: [alice], }, ], }, ], }); expect(block.calls[0].status).toBe("failure"); // NothingToWithdraw expect(block.calls[1]).toMatchObject({ status: "success", result: parseEther("10"), }); ``` ### A sequence of calls from one account ```ts snippet="examples/test/e2e/simulation-and-gas.e2e.test.ts#simulate-calls" const { results } = await anvil.testClient.simulateCalls({ account: alice, calls: [ { to: token, abi: exampleToken.abi, functionName: "transfer", args: [bob, 1n], }, { to: bob, value: parseEther("1") }, ], }); expect(results.map((result) => result.status)).toEqual([ "success", "success", ]); expect(results[0].gasUsed).toBeGreaterThan(0n); ``` ### Override block fields for one call ```ts snippet="examples/test/e2e/simulation-and-gas.e2e.test.ts#block-overrides" const withdraw = { account: alice, to: vault, data: encodeFunctionData({ abi: timeLockVault.abi, functionName: "withdraw", }), }; const { timestamp } = await anvil.testClient.getBlock(); await expect(anvil.testClient.call(withdraw)).rejects.toThrow(); // still locked await expect( anvil.testClient.call({ ...withdraw, blockOverrides: { time: timestamp + LOCK + 1n }, }), ).resolves.toBeDefined(); // would succeed after the lock ``` ### Override state for one call ```ts snippet="examples/test/e2e/mocking-dependencies.e2e.test.ts#state-override" // The override exists only inside this eth_call: nothing is written. const { result } = await anvil.testClient.simulateContract({ address: consumer, abi: priceConsumer.abi, functionName: "quote", args: [parseEther("1")], stateOverride: [ { address: ORACLE, code: oracleCode, stateDiff: [ { slot: numberToHex(0, { size: 32 }), value: numberToHex(parseUnits("2500", 8), { size: 32 }), }, ], }, ], }); expect(result).toBe(parseUnits("2500", 8)); expect(await anvil.testClient.getCode({ address: ORACLE })).toBeUndefined(); ``` ### Concepts - [anvil behaviours worth knowing](../../concepts/anvil-behaviours.md)