Skip to content

Releases

v0.3.0

Choose a tag to compare

@github-actions github-actions released this 19 Nov 01:36
Immutable release. Only release title and notes can be modified.
4cc5a9a

This release better aligns mocks to do what they look like they should do. When you mock a contract's function, that mock answers the app's transactions to it, gas estimate included, instead of competing with a general mock.actions mock elsewhere in the setup. A mock that could never match now fails when you register it, instead of silently never answering. When something doesn't match, the error and the history say what the app asked for and which mocks came close.

It's a release with many breaking changes, but most are a rename or a stricter rule, and each one below says what to change. Two API removals that touch the most surface area have before-and-after examples.

⚠️ Breaking Changes

You're affected if your tests use .fails(name), a send resolver's emit() or revert(), action mocks for a contract's functions, match.any() or match.where() in a pin, a send's data, LogsCall, or mock.method() with a typed name. The rest refuse bad setups loudly at registration, or reword messages.

Who answers a transaction

  • Only a contract's mocks answer its functions. An estimate or a send of a registered contract's nonpayable or payable function is answered by that contract's estimateGas and write mocks and its defaults, never by mock.actions.estimateGas() or mock.actions.sendTransaction(). Move those mocks onto the contract: usdc.write.transfer() as the catch-all, and usdc.estimateGas.transfer().returns(n) to set the gas. In practice:

    • a shared mock.actions.estimateGas().returns(n) no longer sets the gas for a contract's writes. A write mock also answers the estimate, with 100,000 gas, unless the contract has its own estimateGas mock;
    • a blanket mock.actions.estimateGas().refuses(…) no longer reaches a contract's functions. Put .refuses() on the contract's mock instead;
    • when the contract's mocks miss a send, the error is the contract's miss, and it lists the action mocks that would have matched. assertAllUsed() reports an action mock left unused this way, and says why.

    ETH sent to a contract with no data, a selector that isn't on its ABI, and an estimate of a view function are still answered by action mocks. eth_call is unchanged.

  • A node's refusal by name is now .refuses(name), not .fails(name). In a resolver, use refuse(name) instead of fail(name). It's typed on simulate, estimateGas, and write mocks, and on mock.actions.estimateGas() and mock.actions.sendTransaction(), with the same names each took before. .fails(), fail(), and failRequests() now take only a fault (an HTTP error, a JSON-RPC error, a timeout, or a network failure). A name passed to them is a type error, and a MockSetupError at runtime. The app receives the same error as before.

    // 0.2.0
    usdc.write.transfer().fails("insufficientFunds");
    mock.actions.sendTransaction().fails("nonceTooLow");
    let attempts = 0;
    usdc.write.approve().returns(({ fail }) => {
      if (++attempts === 1) fail("nonceTooLow");
    });
    
    // 0.3.0
    usdc.write.transfer().refuses("insufficientFunds");
    mock.actions.sendTransaction().refuses("nonceTooLow");
    let attempts = 0;
    usdc.write.approve().returns(({ refuse }) => {
      if (++attempts === 1) refuse("nonceTooLow");
    });

    Beyond the method names:

    • history records a refusal as { type: "refusal", name }, shown as ✗ refused: nonceTooLow;
    • a request repeated after a refusal is no longer marked (retry), because viem doesn't retry a refusal;
    • MockNodeFault is no longer exported.
  • A send mock's resolver returns only what the chain did, so its emit() and revert() are gone. This covers a contract's write resolvers, defaults.write resolvers, and mock.actions.sendTransaction() resolvers; a static .emits() is unchanged. revert() never reverted the call: the estimate passed, and the send was mined reverted. Return { status: "reverted" } to get that outcome, and return the logs instead of emitting them:

    // 0.2.0
    token.write.transfer().returns(({ from, args: [to, amount], emit, revert }) => {
      const have = balances.get(from) ?? 0n;
      if (have < amount)
        revert({ errorName: "ERC20InsufficientBalance", args: [from, have, amount] });
      emit(token.events.Transfer({ from, to, value: amount }));
      balances.set(from, have - amount);
      balances.set(to, (balances.get(to) ?? 0n) + amount);
    });
    
    // 0.3.0
    token.write.transfer().returns(({ from, args: [to, amount] }) => {
      const have = balances.get(from) ?? 0n;
      if (have < amount) return { status: "reverted" };
      balances.set(from, have - amount);
      balances.set(to, (balances.get(to) ?? 0n) + amount);
      return { logs: [token.events.Transfer({ from, to, value: amount })] };
    });

    To revert the call itself, estimate included, so that a local account's writeContract() throws the decoded error before it sends anything, register a .reverts() mock pinned to the args that revert, beside the resolver. It's more specific than the resolver's mock, so it answers those calls and leaves the rest to the resolver: see Resolvers in the README. To decide from the test's state instead, use an estimateGas resolver, which keeps revert(). Also:

    • read, simulate, and estimateGas resolvers keep revert();
    • revert() used to throw, so a helper that called it now has to return its verdict, and the resolver returns that;
    • WriteResolverContext takes one type parameter, the function's args;
    • untyped code that still calls emit() or revert() gets a MockResolverError ending "is not a function". A resolver that returns { logs: null } is refused, as a static .returns({ logs: null }) already was.

What a mock matches

  • No pin matches a value that the call leaves out. A mock that pins a field doesn't match a call without that field, whatever the pin: match.any() needs a value, and a match.where() predicate is never called with undefined. So sendTransaction({ to, gas: match.any() }) means "a send that gives gas", where before it behaved as if gas were left out. To match a call with or without a field, leave the key out. null is a value, so it does match match.any(). To select the calls that leave a field out, use a predicate for the whole params: sendTransaction(match.where((call) => call.gas === undefined)). A contract's from pin already worked this way. Now an action's fields and a raw method's params do too. The call is what the mock decodes (BalanceCall, SendTransactionCall, …), not the args the app passed, and it fills in what a node would assume. So a block is always set (blockNumber, or a log range's fromBlock and toBlock), as are a send's or an estimate's value and data, and match.any() matches them whether the app gave them or not.

  • An explicit undefined in a pin means the key was left out. getBalance({ address, blockNumber: undefined }) now matches any block, and no longer outranks a later mock that leaves the key out. match.where((v) => v === undefined) never matches (see above).

  • A send's and an estimate's call always have data, "0x" when the request has none, the same as value is sent as 0n. So sendTransaction({ to, data: "0x" }) pins a plain transfer, where before it never matched one. An estimate of a deploy has to: null, as a send's call does. In types:

    • SendTransactionCall.data and EstimateGasCall.data are a required Hex;
    • EstimateGasCall.to is Address | null.

    What a test may see change:

    • a match.where() at data is called with "0x" for a plain transfer, so one that decodes calldata throws there;
    • a resolver that tests for a missing data, or for an estimate's missing to, takes the other branch;
    • { data: match.any() } matches every send;
    • exact assertions on a plain send's .calls, its history line (data: 0x), or its record in mock.transactions (input: "0x") need the new field.
  • Which mock answers:

    • match.any() now counts toward a mock's rank, after exact values and predicates. A mock that pins a key with match.any() answers ahead of one that's otherwise as specific and leaves the key out, whichever was registered first. Before, the one registered last answered;
    • an empty list in args or params (totalOf([[]]), getLogs({ topics: [] })) counts as an exact value, so its mock answers ahead of one with match.any() or match.where() in that place, whichever was registered first;
    • one match.any() in place of all of an action's or a raw method's params counts as nothing, since it matches every call. A mock that pins any param answers ahead of it. It ties with {} or [] params, where it used to answer ahead of them, so the one registered last answers. It still answers ahead of a mock with no params, such as getBalance().
  • A mock that could never match is refused at registration with a MockSetupError that names what's wrong. Before, it registered and never answered. That covers:

    • a contract mock's args that don't fit its function: the wrong count, a value of the wrong type ("5" for a uint256), a key that isn't one of the struct's fields, or args that aren't a list. A malformed address still throws viem's InvalidAddressError, as it does wherever a mock takes an address;
    • an undefined in the middle of a list, where match.any() is what's needed;
    • a Jest or Vitest matcher passed as an action's whole params, such as sendTransaction(expect.objectContaining({ to })).
  • A mock of an overloaded function picks its overload by how its args fit: by count, then by type. A struct with fields left out that fits several overloads is now refused as ambiguous. Before, it registered on the first overload.

Types and messages

  • **LogsCall is either a block ran...
Read more

v0.2.0

Choose a tag to compare

@github-actions github-actions released this 08 Nov 20:19
Immutable release. Only release title and notes can be modified.
dcbf328

This release tightens how the mock checks what a test gives it. A value the mock can't use is refused where it's given, with a message that names the call and field (e.g. mock.addTransaction()'s gasUsed must be a non-negative bigint; got -1n.), instead of being ignored or turned into a plausible-looking answer. An explicit undefined now always means the same as leaving the key out, so spreading a partial fixture behaves as expected.

⚠️ Breaking Changes

  • MockEventLog is renamed MockLogContent. It's the type for any log's content, testLog()'s included, not only an event's.
  • A revert spec takes one form: data, panic, or errorName with args. A spec with fields of two forms is a type error, and is refused at runtime.
  • A defaults: entry set to undefined registers no mock. Before, read, simulate and write answered zero for it.
  • Newly refused at registration:
    • a count past Number.MAX_SAFE_INTEGER in times(), failRequests()' times, historyLimit, historyOnFailure or chain.blockTime;
    • a matcher (match.any() and the rest) anywhere a value goes, such as a revert spec's args. Matchers go in a mock's args, params and pins;
    • a failRequests() method that isn't a method name or a list of them, e.g. a regex;
    • a receipt's status that isn't "success" or "reverted", e.g. "0x1" copied from a node;
    • a field that isn't a fee in createMockRpc({ fees }) or mock.setFees(), e.g. the maxFeePerGas of a client.estimateFeesPerGas() result;
    • a receipt mock with logs over a transaction that reverted.
  • Error classes: a negative balance, gas price, fee or fee history value is the mock's MockSetupError, not viem's IntegerOutOfRangeError.
  • Messages: most setup errors are reworded. Assert on the error class (toThrow(MockSetupError)) or its code, not its text.

Bug Fixes

  • An undefined field is left out everywhere: fees, revert specs, a mock's answer fields, and an unknown key holding undefined.
  • A pending transaction can null only some of its block fields.
  • An ABI function named after an Object.prototype member (toString, valueOf) can be mocked.
  • A bigint request param after a fault no longer crashes the request.
  • Errors and warnings use the package's current name. The hint for an estimate or send nothing answers also mentions .reverts().

👉 Changelog

compare changes

🩹 Fixes

  • ⚠️ Refuse a revert spec with fields of two forms (4a53ae7)
  • Point the reverted-receipt refusal at the record (19e25ed)
  • ⚠️ Register no default for a defaults entry that's undefined (5b2dc8f)
  • Refuse a receipt mock with logs over a reverted transaction (caa0b0c)
  • Treat an explicit undefined in a mock's fields as left out (d2c90c1)
  • Treat an undefined panic or data in a revert spec as left out (5aa21ed)
  • Accept a pending transaction that nulls only some of its block fields (06257b8)
  • Treat an undefined fee as left out in createMockRpc and setFees (2304007)
  • Don't crash on bigint request params after a fault (3cc82c8)
  • Mock ABI functions named after Object.prototype members (c98f109)
  • Update package name in errors and warnings; add .reverts() to the estimate and send hint (22ce5c5)

💅 Refactors

  • Refuse placed logs in the log content check, and name each log's call (0fbd443)
  • Hint at fixes for revert-arg matchers, left-out estimates and estimate-shaped fees, and let checkFields take a plain hint (ddb0fb0)
  • ⚠️ Rename MockEventLog to MockLogContent (f6bdc32)
  • Check hex, lists, and objects with helper functions (1d94337)
  • Check fee history fields one-by-one with checkAmount, and word answer object checks alike (b8ca1e6)
  • Note MockInternalError can also come from a value its types don't allow (e78c7a6)
  • Drop typeof checks that isHex and isHash already make, and a dead branch (706da38)
  • Refuse matchers in revert specs and failRequests' method, naming each place (dc28e7a)
  • Check transaction status with one shared checkStatus (aef5e57)
  • Check objects of known fields with one shared checkFields (f2d1853)
  • Check counts with one shared checkCount, and word both helpers alike (b5b5860)
  • Move mock.buildLog()'s placement out of logs/events.ts (e45b449)
  • ⚠️ Check bigint setup values with one shared checkAmount (bdfb78a)
  • Name setup checks check*, keeping assert* for public checks (23cbdb8)

📖 Documentation

  • Name the test command, where domain checks go, multi-call subjects, and how tests pin errors (c031105)
  • Add setup check rules to AGENTS.md and match architecture and notes (9b373c0)
  • Clarify leftOut's comment, notes.md's undefined wording and a test name (3d935b8)
  • Treat an explicit undefined as a key left out (2006149)
  • Only fix and review bugs that real use plausibly hits (9dc6b03)
  • Assert on MockSetupError's class or code, not message text (c489764)
  • Clarify that addTransaction mines a new block by default (96dc5cf)

✅ Tests

  • Set no-isolate on test script (c8c000f)
  • Cover fee history's list checks and failRequests' method lists (b56e23d)

❤️ Contributors

v0.1.1

Choose a tag to compare

@github-actions github-actions released this 07 Nov 01:22
4c0d864

v0.1.1 is the next patch release.

👉 Changelog

compare changes

🏡 Chore

  • ci: Add trusted publishing and uppt release flow (8d2a2c2)

❤️ Contributors

v0.1.0

Choose a tag to compare

@nadaniels nadaniels released this 06 Nov 20:35
d37e95b

Initial release

Ethergeist - a mock Ethereum node behind a viem transport, for tests and demos. Each JSON-RPC request is answered with what the test registered; nothing executes.

Added

  • createMockRpc({ chain, blockNumber, timestamp, fees, debug }), with mock.transport() and mock.publicClient() for viem, and mock.request() for a raw JSON-RPC request.
  • Mocked contracts: mock.contract({ abi, address, defaults }), with typed read, simulate, estimateGas, and write namespaces that mirror viem's getContract. A function mock .returns() a value or a resolver, .reverts() with the ABI's errors, .fails() as a node would, and takes .once() or .times(n). Multicall3 batches are answered call by call.
  • Matching on pinned args, with match.any(), match.where(), and match.partial(): the most specific mock answers. When two are equally specific, limited ones (.once(), .times(n)) answer first, in the order they were registered; otherwise the one registered last answers.
  • Typed mocks for viem's public actions in mock.actions (balances, code, storage, blocks, transactions, receipts, logs, gas prices and fee history, nonces, estimates, and sends), and mock.method() for any other JSON-RPC method.
  • A chain that sends build on: mock.addTransaction(), mock.mine(), mock.setFees(), and contract.emit and contract.events (with contractEvents() and testLog()) for logs that getLogs(), watchers, and receipts find.
  • mock.buildTransaction(), mock.buildReceipt(), and mock.buildLog() for values in viem's types, and testAddress() and testHash() for stable test values.
  • Node failures: mock.failRequests() for HTTP errors, JSON-RPC errors, timeouts, and network failures, and named node errors (insufficient funds, nonce too low, and others) that viem sorts into its own error classes.
  • What the app asked: mock.history, mock.calls, contract.calls, mock.unhandled, mock.formatHistory(), and the debug option.
  • Checks: mock.assertNoUnhandled() and mock.assertAllUsed(), and the MockError family (MockCheckError, MockSetupError, MockNotFoundError, MockResolverError, MockInternalError) with stable error codes.
  • Shared setup: mock.checkpoint() and restore(), mock.reset(), and mock.clearCalls().
  • ESM only, for Node 22.12 or later and browsers, with viem ^2.50.3 and ox ^0.14.22 as peers, and types for TypeScript 5.8 or later.