webevm 0.0.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +693 -0
  3. package/dist/engine.d.ts +69 -0
  4. package/dist/engine.d.ts.map +1 -0
  5. package/dist/engine.js +269 -0
  6. package/dist/engine.js.map +1 -0
  7. package/dist/index.d.ts +12 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +21 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/intrinsic-gas.d.ts +149 -0
  12. package/dist/intrinsic-gas.d.ts.map +1 -0
  13. package/dist/intrinsic-gas.js +94 -0
  14. package/dist/intrinsic-gas.js.map +1 -0
  15. package/dist/node.d.ts +3 -0
  16. package/dist/node.d.ts.map +1 -0
  17. package/dist/node.js +1931 -0
  18. package/dist/node.js.map +1 -0
  19. package/dist/persistence.d.ts +22 -0
  20. package/dist/persistence.d.ts.map +1 -0
  21. package/dist/persistence.js +54 -0
  22. package/dist/persistence.js.map +1 -0
  23. package/dist/revm-state-store.d.ts +89 -0
  24. package/dist/revm-state-store.d.ts.map +1 -0
  25. package/dist/revm-state-store.js +394 -0
  26. package/dist/revm-state-store.js.map +1 -0
  27. package/dist/revm.d.ts +124 -0
  28. package/dist/revm.d.ts.map +1 -0
  29. package/dist/revm.js +657 -0
  30. package/dist/revm.js.map +1 -0
  31. package/dist/sender-recovery.d.ts +78 -0
  32. package/dist/sender-recovery.d.ts.map +1 -0
  33. package/dist/sender-recovery.js +53 -0
  34. package/dist/sender-recovery.js.map +1 -0
  35. package/dist/state-manager.d.ts +327 -0
  36. package/dist/state-manager.d.ts.map +1 -0
  37. package/dist/state-manager.js +439 -0
  38. package/dist/state-manager.js.map +1 -0
  39. package/dist/storage-keys.d.ts +21 -0
  40. package/dist/storage-keys.d.ts.map +1 -0
  41. package/dist/storage-keys.js +113 -0
  42. package/dist/storage-keys.js.map +1 -0
  43. package/dist/types.d.ts +696 -0
  44. package/dist/types.d.ts.map +1 -0
  45. package/dist/types.js +12 -0
  46. package/dist/types.js.map +1 -0
  47. package/dist/worker-client.d.ts +21 -0
  48. package/dist/worker-client.d.ts.map +1 -0
  49. package/dist/worker-client.js +77 -0
  50. package/dist/worker-client.js.map +1 -0
  51. package/dist/worker-entry.d.ts +32 -0
  52. package/dist/worker-entry.d.ts.map +1 -0
  53. package/dist/worker-entry.js +29 -0
  54. package/dist/worker-entry.js.map +1 -0
  55. package/dist/worker-host.d.ts +75 -0
  56. package/dist/worker-host.d.ts.map +1 -0
  57. package/dist/worker-host.js +188 -0
  58. package/dist/worker-host.js.map +1 -0
  59. package/package.json +90 -2
  60. package/src/engine.ts +300 -0
  61. package/src/index.ts +46 -0
  62. package/src/intrinsic-gas.ts +191 -0
  63. package/src/node.ts +2150 -0
  64. package/src/persistence.ts +80 -0
  65. package/src/revm-state-store.ts +455 -0
  66. package/src/revm.ts +809 -0
  67. package/src/sender-recovery.ts +142 -0
  68. package/src/state-manager.ts +531 -0
  69. package/src/storage-keys.ts +150 -0
  70. package/src/types.ts +717 -0
  71. package/src/worker-client.ts +112 -0
  72. package/src/worker-entry.ts +31 -0
  73. package/src/worker-host.ts +232 -0
package/src/types.ts ADDED
@@ -0,0 +1,717 @@
1
+ /**
2
+ * types.ts — the public shape of the slim node. Deliberately tiny and
3
+ * transport-agnostic: a node is just an object with an async EIP-1193 `request()`
4
+ * plus a few node-owned controls (`mine`/`dumpState`/`loadState`). It knows
5
+ * NOTHING about Workers — because `request()` is already async, the exact same
6
+ * object works unchanged whether called on the main thread or across a thread
7
+ * boundary (see ../worker.ts for the optional comlink wrapper).
8
+ *
9
+ * The `@ethereumjs/*` imports below are TYPE-ONLY (erased at build time), so this
10
+ * module — and the core entry point that re-exports it — adds no runtime import.
11
+ */
12
+ import type {Address} from '@ethereumjs/util';
13
+ import type {Block} from '@ethereumjs/block';
14
+ import type {TypedTransaction} from '@ethereumjs/tx';
15
+ import type {StateManagerInterface} from '@ethereumjs/common';
16
+ import type {Common} from '@ethereumjs/common';
17
+
18
+ /** Minimal EIP-1193 request args. */
19
+ export interface RequestArguments {
20
+ readonly method: string;
21
+ readonly params?: readonly unknown[] | object;
22
+ }
23
+
24
+ /** EIP-1193-style JSON-RPC error (what we throw for honest gaps). */
25
+ export class RpcError extends Error {
26
+ readonly code: number;
27
+ readonly data?: unknown;
28
+ constructor(code: number, message: string, data?: unknown) {
29
+ super(message);
30
+ this.name = 'RpcError';
31
+ this.code = code;
32
+ this.data = data;
33
+ }
34
+ }
35
+
36
+ export type MiningConfig =
37
+ | {type: 'auto'} // mine one block per raw tx (pairs with eth_sendRawTransactionSync)
38
+ | {type: 'manual'} // only mine on explicit node.mine()
39
+ | {type: 'interval'; intervalMs: number}; // mine on a timer
40
+
41
+ export interface PersistenceAdapter {
42
+ /** Load the single serialized state record (or null on first run). */
43
+ load(): Promise<SerializedState | null>;
44
+ /**
45
+ * Persist the single serialized state record.
46
+ *
47
+ * DO NOT CALL BACK INTO THE NODE FROM HERE. A node serves one request at a
48
+ * time, and this hook is AWAITED inside the request that triggered it — that
49
+ * is what makes `state` a snapshot of a settled chain rather than one caught
50
+ * mid-transaction, and what stops a request resolving before its state is
51
+ * durable. A `node.request(...)` awaited from inside this function therefore
52
+ * waits for a queue that is waiting for this function, and the node stops.
53
+ * Everything you could ask it for is already in `state`; if you need the node
54
+ * itself, do that work after `save()` resolves.
55
+ *
56
+ * It is a rule rather than a check because the two cases cannot be told apart:
57
+ * see `docs/adr/0012-one-request-at-a-time-the-node-serialises-its-whole-public-surface.md`.
58
+ * Other callers are unaffected — a request issued elsewhere while this hook is
59
+ * running simply queues behind it.
60
+ */
61
+ save(state: SerializedState): Promise<void>;
62
+ }
63
+
64
+ /**
65
+ * State backing mode.
66
+ * - `'none'` (DEFAULT): `SimpleStateManager` — plain Maps, NO trie, NO state root.
67
+ * The fast path; block `stateRoot`/`receiptsRoot`/`transactionsRoot` are zero
68
+ * placeholders (you are a local chain; canonical roots aren't needed). This is
69
+ * the recommended mode and what makes the node ~4× faster than the trie path.
70
+ * - `'trie'`: `MerkleStateManager` — real Merkle-Patricia trie. SLOWER (recomputes
71
+ * the state root each tx) but produces a REAL `stateRoot`, which (a) lets the
72
+ * node be conformance-tested against `ethereum/tests` GeneralStateTests (they
73
+ * verify the post-state root), and (b) gives honest canonical block roots for
74
+ * consumers that need them. Opt-in: pay for the trie only when you want it.
75
+ */
76
+ export type StateMode = 'none' | 'trie';
77
+
78
+ /**
79
+ * Sender-derivation mode.
80
+ * - `'recover'` (DEFAULT): derive the sender from the signature with ecrecover,
81
+ * exactly as a real node does. The tx is self-authenticating: a caller cannot
82
+ * claim to be an address it does not hold the key for. This is the only mode
83
+ * that is safe when the node is reachable by a caller you do not control.
84
+ * - `'trusted'`: TRUST a caller-supplied sender and SKIP ecrecover entirely.
85
+ * Enables `evm_sendRawTransactionAs` / `evm_sendRawTransactionSyncAs`, which
86
+ * take an explicit `from`. The signature is still carried on the wire and the
87
+ * tx hash is still the real one, but it is NEVER verified, so ANY caller can
88
+ * claim to be ANY address.
89
+ *
90
+ * Why it exists: ecrecover is a FIXED cost per tx and it dominates small ones. A
91
+ * client that signed the tx already knows the sender, so re-deriving it is pure
92
+ * waste in a local chain. Measured (2026-08-11,
93
+ * `docs/spikes/sender-recovery-uses-the-engines-ecrecover/measurements.md`) at
94
+ * ~6.2x on the isolated transaction path (2.09 -> 0.33 ms/tx, signing outside the
95
+ * window) and ~3.6x end-to-end through a viem-style client, with byte-identical
96
+ * gas and status.
97
+ *
98
+ * HOW BIG THE GAP IS DEPENDS ON THE ENGINE NOW. `'recover'` recovers with the
99
+ * INSTALLED ENGINE's secp256k1 when it has one ({@link Engine.ecrecover}, which
100
+ * `webevm/revm` implements at zero additional bytes — the `0x01`
101
+ * precompile is already in that module), and that makes the expensive half of
102
+ * `'recover'` about 4.3x cheaper: 2.02 -> 0.65 ms/tx isolated, so the gap narrows
103
+ * to ~2.8x (~1.8x end to end). `'trusted'` is still worth having and has stopped
104
+ * being the dominant lever. With no such engine, recovery is `@ethereumjs/tx`'s
105
+ * as before, and so is the ~6.2x.
106
+ *
107
+ * The primitive is just "execute as this sender, do not recover". It serves BOTH
108
+ * an ordinary signed tx that wants to skip a redundant recovery AND a higher
109
+ * layer building anvil-style impersonation on top with a fabricated signature.
110
+ * Impersonation itself is account POLICY and is deliberately NOT this package's
111
+ * job — see the `parseTx` docblock in node.ts for the full caller contract
112
+ * (notably: fabricated txs must be made unique per sender, or their hashes
113
+ * collide).
114
+ *
115
+ * The trade is real and one-directional: `'trusted'` removes the ONLY thing that
116
+ * binds a tx to its sender. Use it for a local, same-origin dev chain or an
117
+ * in-browser game. Never expose a `'trusted'` node over a transport that an
118
+ * untrusted caller can reach.
119
+ */
120
+ export type SenderMode = 'recover' | 'trusted';
121
+
122
+ /**
123
+ * One read-only call for an {@link Engine} to execute: exactly the inputs the
124
+ * node's pure-read helper has always handed `runCall`, and nothing more.
125
+ *
126
+ * The value types are `@ethereumjs/*`'s own (`Address`, `Block`) rather than hex
127
+ * strings, because the node already holds them in that form and the default
128
+ * engine passes them straight through — converting at the seam would add cost and
129
+ * a chance to change behaviour, in a refactor whose whole point is changing none.
130
+ */
131
+ export interface ReadCallRequest {
132
+ /** Caller (`msg.sender`). The node defaults it to the zero address. */
133
+ readonly from: Address;
134
+ /** Callee, or `undefined` for a CREATE-shaped call (gas estimation). */
135
+ readonly to?: Address;
136
+ /** Calldata (or init code when `to` is absent). */
137
+ readonly data: Uint8Array;
138
+ readonly value: bigint;
139
+ /** Gas made available to EXECUTION (intrinsic gas is the node's business). */
140
+ readonly gasLimit: bigint;
141
+ /** The block the call observes (NUMBER, TIMESTAMP, COINBASE, BASEFEE...). */
142
+ readonly block: Block;
143
+ }
144
+
145
+ /** What an engine reports back for a read-only call. */
146
+ export interface ReadCallResult {
147
+ /**
148
+ * Return data (or the revert data when {@link error} is set) — the CALLEE's
149
+ * bytes, and nothing else. `eth_call` surfaces exactly these as the `data` of
150
+ * its `execution reverted` error, where a client decodes them as a revert
151
+ * reason, so a failure that ran NO code (a call the engine refused before
152
+ * execution: an unaffordable value, a gas budget below the intrinsic cost)
153
+ * reports EMPTY here on every engine and puts its explanation in
154
+ * {@link error}. An engine whose own diagnostics arrive in this field must
155
+ * drop them rather than pass them on — `src/revm.ts` does, and
156
+ * `test/helpers/revm-engine.ts` holds both engines to the same bytes.
157
+ */
158
+ readonly returnValue: Uint8Array;
159
+ /**
160
+ * EXECUTION gas only — NOT a transaction's total, and NOT by itself an answer
161
+ * to `eth_estimateGas`. The node adds the intrinsic gas (21000 base, +32000
162
+ * create, calldata bytes, EIP-3860 initcode) to it, exactly as it did before
163
+ * the seam existed, and that sum is what a request CONSUMES. `eth_estimateGas`
164
+ * uses it as the FLOOR of a search for the smallest gas LIMIT the request
165
+ * succeeds at, because EIP-150's 63/64 rule makes consumption unusable as a
166
+ * limit for anything that calls out or creates (see `estimateGas` in
167
+ * ./node.ts) — so an engine may be asked for the same call several times, at
168
+ * descending {@link ReadCallRequest.gasLimit}s.
169
+ *
170
+ * WHEN A FRAME HALTS FOR WANT OF GAS, THIS IS THE WHOLE BUDGET IT WAS GIVEN,
171
+ * and that is load-bearing rather than incidental: it is how the node tells
172
+ * "needs more gas than the allowance" apart from "reverted" without matching on
173
+ * either engine's words for it.
174
+ */
175
+ readonly executionGasUsed: bigint;
176
+ /**
177
+ * Set iff the call did not succeed (a revert, a halt, or a refusal BEFORE
178
+ * execution); the EVM's own error string, which is where an engine's words for
179
+ * a failure belong. The two engines differ here by design — `insufficient
180
+ * balance` against revm's quoted `Transaction(LackOfFundForMaxFee { .. })` —
181
+ * and `node.ts` flattens both into one `execution reverted`, so nothing above
182
+ * the seam can tell the engines apart by it.
183
+ */
184
+ readonly error?: string;
185
+ }
186
+
187
+ /**
188
+ * One SIGNED transaction for an {@link Engine} to execute AND COMMIT, plus the
189
+ * block it is being mined in.
190
+ *
191
+ * NOT an RPC-level transaction request: there is nothing to fill in here and
192
+ * nothing optional. `eth_sendTransaction` does not exist on this node, and
193
+ * `eth_fillTransaction` returns its own object, one layer above the seam.
194
+ *
195
+ * THE TRANSACTION CROSSES AS THE NODE PARSED IT, for the reason
196
+ * {@link ReadCallRequest} carries `Address`/`Block`: the node already holds it in
197
+ * that form and the default engine hands it straight to `runTx`.
198
+ *
199
+ * THE SENDER CROSSES AS A SEPARATE VALUE ({@link sender}) rather than as something
200
+ * an engine reads off {@link tx}, and that is the whole reason this field exists.
201
+ *
202
+ * WHAT IS DELIBERATELY ABSENT: any switch that relaxes this transaction's
203
+ * VALIDITY. The read path's simulation switches (base fee, block gas limit,
204
+ * EIP-3607 — see the `call` side of `src/revm.ts`) have no counterpart here, and
205
+ * `@ethereumjs/vm`'s own `skipHardForkValidation` stays INSIDE the default engine
206
+ * where it means something (see `src/engine.ts`). Its `skipBlockGasLimitValidation`
207
+ * is not here either, and it is no longer there: it relaxed a rule only ONE engine
208
+ * could relax, so the relaxation was dropped rather than relocated, and a consumer
209
+ * who wants gas limits above the block's raises `NodeOptions.blockGasLimit` so that
210
+ * the block really is that large. A transaction that runs with relaxed validity is
211
+ * not a transaction.
212
+ */
213
+ export interface TransactionRequest {
214
+ /** The signed transaction, parsed by the node (which owns parsing). */
215
+ readonly tx: TypedTransaction;
216
+ /**
217
+ * WHO SENT IT, as a VALUE the node states: `msg.sender` of the top-level frame,
218
+ * the account whose balance and nonce this transaction moves, and the `from` on
219
+ * the receipt the node builds. AUTHORITATIVE. An engine executes on behalf of
220
+ * THIS address and must never derive one of its own.
221
+ *
222
+ * WHY IT IS A FIELD AND NOT A CALL. Sender derivation is the NODE's (`ADR 0006`)
223
+ * — an engine may LEND it the curve step ({@link Engine.ecrecover}) but never the
224
+ * decision, which is the distinction that entry draws —
225
+ * and in `senderMode:'trusted'` (the `evm_*As` cheats, ADR 0002) the node is TOLD
226
+ * the sender and deliberately skips ecrecover — so the authoritative sender may
227
+ * differ from whatever {@link tx}'s signature recovers to, and for a FABRICATED
228
+ * signature there is no meaningful recoverable sender at all. An engine that
229
+ * recovers the sender itself does not fail loudly on such a transaction: it
230
+ * charges a different account, advances a different nonce, and hands back a
231
+ * receipt that looks completely right. The only way that cannot happen is for the
232
+ * sender to be DATA on the request, so that an engine which ignores it is
233
+ * ignoring a stated input rather than merely disagreeing with a convention.
234
+ *
235
+ * It is therefore REQUIRED and non-optional: `{tx, block}` with no sender is not
236
+ * a transaction request, and an engine written against this type cannot be handed
237
+ * one. What an engine does with it is the engine's: the default `@ethereumjs/evm`
238
+ * engine pins it onto the `runTx` call (`src/engine.ts` — `runTx` reads the sender
239
+ * through exactly one method), and `webevm/revm` passes it as revm's
240
+ * `from`, which takes a sender directly and recovers nothing.
241
+ *
242
+ * `sender`, NOT `from`, deliberately — the two words are not synonyms here.
243
+ * {@link ReadCallRequest.from} is `eth_call`'s own parameter: caller-supplied,
244
+ * unauthenticated by nature, defaulted to the zero address. A transaction's
245
+ * `from` is the RPC RENDERING of this value on the receipt. What crosses here is
246
+ * the SENDER, which is this repo's word for the thing `senderMode` chooses how to
247
+ * obtain (recover it, or be told it) — so the field name says which concept it is
248
+ * rather than borrowing the read path's parameter name for something stronger.
249
+ */
250
+ readonly sender: Address;
251
+ /** The block it is mined in (NUMBER, TIMESTAMP, COINBASE, BASEFEE, GASLIMIT). */
252
+ readonly block: Block;
253
+ }
254
+
255
+ /**
256
+ * One log, as the seam carries it: raw bytes, no `@ethereumjs/*` types, no
257
+ * position. Block/transaction position (`blockNumber`, `logIndex`, ...) is the
258
+ * NODE's — an engine executing one transaction cannot know where in a block it
259
+ * sits.
260
+ */
261
+ export interface TransactionLog {
262
+ /** Emitting contract, 20 bytes. */
263
+ readonly address: Uint8Array;
264
+ /** 0-4 topics, 32 bytes each. */
265
+ readonly topics: readonly Uint8Array[];
266
+ readonly data: Uint8Array;
267
+ }
268
+
269
+ /**
270
+ * What an engine reports back for an executed transaction: EVERYTHING A RECEIPT
271
+ * NEEDS FROM AN EVM, and nothing else.
272
+ *
273
+ * THIS TYPE IS THE SEAM'S POINT. It is what makes two EVMs comparable field by
274
+ * field: the default engine fills it from a `runTx` result, another fills it from
275
+ * its own outcome, and the node builds the same receipt either way. So it is
276
+ * designed from the RECEIPT backwards, not from what `@ethereumjs/vm` happens to
277
+ * return — `amountSpent`, `gasRefund`, `minerValue`, `accessList` and the
278
+ * `execResult` are all absent because no receipt reads them.
279
+ *
280
+ * WHAT STAYS THE NODE'S, and is therefore not here: `cumulativeGasUsed` (a
281
+ * block-level accumulation over several transactions), the transaction hash,
282
+ * index, type, `from`/`to`, the block it landed in, and log positions. An engine
283
+ * executes one transaction; it does not build blocks.
284
+ *
285
+ * THE VALUES ARE RAW BYTES AND BIGINTS on purpose. An engine that is not
286
+ * `@ethereumjs/*` (revm-wasm, next) produces bytes, and a seam typed in one
287
+ * engine's classes would make every other engine convert into a vocabulary it
288
+ * does not speak.
289
+ */
290
+ export interface TransactionResult {
291
+ /**
292
+ * `1` succeeded, `0` failed — the receipt's own status, and the only thing a
293
+ * receipt says about failure. A revert REASON is deliberately absent: a receipt
294
+ * has no field for it (the read path's {@link ReadCallResult.error} is what
295
+ * surfaces engine words, to `eth_call`).
296
+ */
297
+ readonly status: 0 | 1;
298
+ /**
299
+ * Gas the sender PAYS FOR: NET of refunds, which is what the receipt reports
300
+ * and what `cumulativeGasUsed` accumulates. Not the gross gas spent before
301
+ * refunds — an engine reporting both must map the net one here (the read path
302
+ * wants the gross one, because a read has no refund).
303
+ */
304
+ readonly gasUsed: bigint;
305
+ /**
306
+ * Wei per gas actually charged — `min(maxFeePerGas, baseFee + tip)` for a 1559
307
+ * transaction, `gasPrice` for a legacy one. It comes from the engine that
308
+ * executed the transaction because that engine is what CHARGED it, so there is
309
+ * exactly one implementation of the fee arithmetic per engine and none in the
310
+ * node.
311
+ */
312
+ readonly effectiveGasPrice: bigint;
313
+ /**
314
+ * Logs in EMISSION order, and only the ones that SURVIVED: a log emitted inside
315
+ * a reverted sub-call is not here.
316
+ */
317
+ readonly logs: readonly TransactionLog[];
318
+ /** The 256-byte bloom over {@link logs} (all zero when there are none). */
319
+ readonly logsBloom: Uint8Array;
320
+ /**
321
+ * The address a top-level CREATE produced, 20 bytes; absent for a call, and
322
+ * absent for the nested creations a transaction performs (they are not the
323
+ * receipt's `contractAddress`).
324
+ */
325
+ readonly createdAddress?: Uint8Array;
326
+ }
327
+
328
+ /**
329
+ * What the node hands an engine once, at construction, so the engine can reach
330
+ * the node's AUTHORITATIVE state. Deliberately minimal: a later engine that needs
331
+ * more adds a field here rather than the node guessing now (ADR 0006 names this
332
+ * additive widening as the sanctioned way to grow the seam — `getBlockHash`
333
+ * arrived that way, for `webevm/revm`).
334
+ */
335
+ export interface EngineContext {
336
+ /** The node's live state manager. The node keeps ownership; do not fork it. */
337
+ readonly stateManager: StateManagerInterface;
338
+ /** Chain params (chain id, hardfork, custom crypto) the node runs under. */
339
+ readonly common: Common;
340
+ /**
341
+ * The hash of one of the node's blocks, by number, for the `BLOCKHASH` opcode
342
+ * — `undefined` for a block the node does not have (the EVM then reads zero).
343
+ *
344
+ * SYNCHRONOUS, unlike everything else the node does with blocks, because
345
+ * `BLOCKHASH` is answered in the middle of an opcode and a wasm interpreter has
346
+ * no suspension point to await at. It is a live lookup, not a snapshot: the
347
+ * node has mined no blocks yet when `connect` runs.
348
+ *
349
+ * An engine that leaves this unwired makes `BLOCKHASH` answer nothing for
350
+ * blocks the node actually has, silently — which is why it is on the context
351
+ * rather than an engine-side option to remember to pass.
352
+ */
353
+ getBlockHash(blockNumber: bigint): Uint8Array | undefined;
354
+ /**
355
+ * The node's state mode. An engine that cannot serve it must THROW here —
356
+ * `connect` is called during `createNode()`, so the refusal lands at
357
+ * construction rather than at the first opcode.
358
+ */
359
+ readonly stateMode: StateMode;
360
+ }
361
+
362
+ /**
363
+ * THE EVM BEHIND THE NODE, in ONE interface with TWO REQUIRED operations: execute
364
+ * a read-only {@link call} (`eth_call`, `eth_estimateGas`, `eth_fillTransaction`'s
365
+ * estimation) and execute a committing {@link transact} (the mining path).
366
+ *
367
+ * ONE INTERFACE, NOT TWO, and neither operation is a capability an engine may
368
+ * decline. What differs between them is a transaction's VALIDITY rules, not their
369
+ * engine-ness: a read RELAXES them (base fee, block gas limit, EIP-3607) and
370
+ * cannot commit, a transaction relaxes nothing and commits. That asymmetry belongs
371
+ * to the operations, and stating it in one place where both are visible beats
372
+ * splitting it across two interfaces that could be pointed at two different EVMs
373
+ * (two identifiers that can disagree, for no gain).
374
+ *
375
+ * An engine is an INJECTED OBJECT, never a name the core resolves — see
376
+ * `docs/adr/0006-the-engine-is-an-injected-object-not-a-named-string.md`.
377
+ *
378
+ * A read-only call MUST NOT mutate the node's state. Whatever it takes to hold
379
+ * that (a checkpoint/revert, a warm-slot reset, or nothing at all) is the
380
+ * ENGINE's business, not the node's: the default `@ethereumjs/evm` engine needs
381
+ * both and pays for both, an engine that is structurally incapable of committing
382
+ * pays for neither.
383
+ */
384
+ export interface Engine {
385
+ /**
386
+ * Stable identifier for bug reports (`'@ethereumjs/evm'` for the default).
387
+ * Surfaced verbatim as `node.engine.id`.
388
+ */
389
+ readonly id: string;
390
+ /**
391
+ * Bind to the node's state + chain context. Called EXACTLY once, during
392
+ * `createNode()`, before any call. Optional: an engine the node itself builds
393
+ * already has what it needs. Throwing here fails node construction.
394
+ */
395
+ connect?(context: EngineContext): void | Promise<void>;
396
+ /** Execute one read-only call against the node's CURRENT state. */
397
+ call(request: ReadCallRequest): Promise<ReadCallResult>;
398
+ /**
399
+ * Execute one signed transaction against the node's state AND COMMIT it,
400
+ * reporting what a receipt needs. Full validity: nonce checked, fees charged,
401
+ * no simulation switch anywhere near it.
402
+ *
403
+ * REQUIRED, like {@link call}, and refused at construction if it is missing or
404
+ * is not callable (`connectEngine` in `src/engine.ts`). The node does not fill
405
+ * it in with its own `@ethereumjs/vm`: a node running one EVM for reads and
406
+ * another for transactions has two chances to disagree with itself, and a
407
+ * receipt from it could not be attributed to the engine `node.engine` names.
408
+ *
409
+ * NONCE CHECKING IS THE CALL PATH'S CHOICE, NOT A PARAMETER. It is ON here
410
+ * because this method is the transaction path, and OFF for {@link call} because
411
+ * that is `eth_call` semantics. Nothing on {@link TransactionRequest} can turn
412
+ * it off, and nothing should be added that can: a transaction executed without
413
+ * the check is silently replayable, so the property worth having is that
414
+ * forgetting it is impossible rather than merely discouraged.
415
+ *
416
+ * THROW to reject a transaction the chain would not accept (a replayed nonce, an
417
+ * unaffordable fee). The node's mining path is written against that shape —
418
+ * `@ethereumjs/vm`'s `runTx` throws — so an engine reporting an invalid
419
+ * transaction as a zero-gas result would have the node mine a block containing a
420
+ * receipt for a transaction that never ran.
421
+ */
422
+ transact(request: TransactionRequest): Promise<TransactionResult>;
423
+ /**
424
+ * secp256k1 PUBLIC-KEY RECOVERY, offered as a PRIMITIVE: recover the 20-byte
425
+ * address that produced `(r, s)` over `hash` with `recoveryId`, or `undefined`
426
+ * when it recovers to nothing. Synchronous, stateless, and callable BEFORE
427
+ * {@link connect} — it touches no state, no block and no hardfork.
428
+ *
429
+ * OPTIONAL, and the ONLY optional operation on this interface. {@link call} and
430
+ * {@link transact} are capabilities the node cannot supply for an engine that
431
+ * omits them, so they are refused at construction; this one the node can, and
432
+ * always could — with no engine ecrecover it recovers the sender through
433
+ * `@ethereumjs/tx` as it always did. An engine implements it when its module
434
+ * ALREADY carries secp256k1 (`webevm/revm` does: the `0x01`
435
+ * precompile's own k256, reached without a database or a journal), which is why
436
+ * it costs zero additional bytes to offer and why offering it is not a
437
+ * requirement anyone should be held to.
438
+ *
439
+ * IT IS NOT "SENDER DERIVATION", and the distinction is the whole reason this
440
+ * is shaped as `(hash, recoveryId, r, s)` rather than as a transaction. Deciding
441
+ * WHO SENT A TRANSACTION stays the node's, on every engine (see
442
+ * {@link TransactionRequest.sender}): the node computes the message hash,
443
+ * enforces EIP-2's low-`s` rule, turns the wire's `v` — 27/28, `chainId * 2 +
444
+ * 35/36`, or a bare y-parity — into a 0/1 recovery id, and only THEN asks the
445
+ * curve. An engine is handed a question about a signature and never one about a
446
+ * transaction, so it needs to know nothing about EIP-155, EIP-2718 or
447
+ * `senderMode`, and it can neither admit a transaction the node would refuse nor
448
+ * refuse one the node would admit.
449
+ *
450
+ * EIP-2 IN PARTICULAR IS NOT YOURS TO ENFORCE. revm's implementation of this is
451
+ * the `0x01` precompile's, which NORMALISES a high-`s` signature and returns an
452
+ * address — correctly, because EIP-2 constrains transactions, not the
453
+ * precompile. The node refuses such a transaction above the seam so that the
454
+ * answer is the same on every engine. Implement this as the raw curve operation
455
+ * and add no protocol opinions to it.
456
+ *
457
+ * RETURN `undefined` rather than throwing when the signature does not recover:
458
+ * the node turns that into its own refusal, in the same shape on every engine.
459
+ *
460
+ * @param hash 32-byte message digest that was signed.
461
+ * @param recoveryId 0 or 1. Never the wire's `v`.
462
+ * @param r 32 bytes, big-endian.
463
+ * @param s 32 bytes, big-endian.
464
+ */
465
+ ecrecover?(
466
+ hash: Uint8Array,
467
+ recoveryId: number,
468
+ r: Uint8Array,
469
+ s: Uint8Array,
470
+ ): Uint8Array | undefined;
471
+ }
472
+
473
+ /** Which EVM a node is running on (see {@link SlimNode.engine}). */
474
+ export interface EngineInfo {
475
+ /** The engine's stable identifier, e.g. `'@ethereumjs/evm'`. */
476
+ readonly id: string;
477
+ }
478
+
479
+ export interface NodeOptions {
480
+ /** EIP-155 chain id. Default 31337 (anvil/hardhat-style local). */
481
+ chainId?: number;
482
+ /** State backing: `'none'` (fast, no trie/root — default) or `'trie'` (real
483
+ * state root, slower; unlocks GeneralStateTests conformance). */
484
+ stateMode?: StateMode;
485
+ /**
486
+ * Sender derivation: `'recover'` (ecrecover, authenticated — DEFAULT) or
487
+ * `'trusted'` (skip ecrecover, trust a caller-supplied `from`). See
488
+ * {@link SenderMode}. `'trusted'` is ~6.2x faster per small tx on the default
489
+ * engine, ~2.8x with a revm engine installed (which recovers with its own
490
+ * secp256k1), and it lets ANY caller impersonate ANY address — opt in only for a
491
+ * local chain you control.
492
+ */
493
+ senderMode?: SenderMode;
494
+ /** Mining strategy. Default {type:'auto'}. */
495
+ miningConfig?: MiningConfig;
496
+ /** Optional persistence adapter (e.g. IndexedDB). */
497
+ persistence?: PersistenceAdapter;
498
+ /** Constant gas-fee values (slim node — no real fee market). */
499
+ baseFeePerGas?: bigint;
500
+ gasPrice?: bigint;
501
+ maxPriorityFeePerGas?: bigint;
502
+ /**
503
+ * Block gas limit. Default 30_000_000n, and a REAL limit: a transaction whose
504
+ * own gas limit exceeds it is refused (identically on every engine) rather than
505
+ * mined against a limit the block does not have. Raise it to admit bigger
506
+ * transactions; the block then really is that large, so `GASLIMIT` reports this
507
+ * number to a contract. It does NOT change the default `eth_call` read budget,
508
+ * which stays 30_000_000 (pass `gas` on the call for more).
509
+ */
510
+ blockGasLimit?: bigint;
511
+ /** Pre-fund accounts at genesis (address -> balance wei). */
512
+ initialBalances?: Record<string, bigint>;
513
+ /**
514
+ * Full genesis pre-state (address -> {balance, nonce, code, storage}). Richer
515
+ * than `initialBalances` (which only sets balance). Used to load an arbitrary
516
+ * starting state — e.g. a GeneralStateTest `pre` section — so that, in
517
+ * `stateMode:'trie'`, `getStateRoot()` after a tx can be compared to the
518
+ * fixture's expected post-state root. Applied at genesis, before block 0.
519
+ */
520
+ initialState?: Record<string, GenesisAccount>;
521
+ /**
522
+ * Override the header fields of MINED blocks. Lets a consumer run a tx under a
523
+ * specific block environment (coinbase, base fee, number, timestamp,
524
+ * prevRandao) — required to reproduce a GeneralStateTest `env` (the coinbase is
525
+ * credited tx fees, so it affects the post-state root). When omitted, the node
526
+ * uses its own constant fee market + a zero coinbase.
527
+ *
528
+ * GENESIS TAKES `coinbase` AND `prevRandao` FROM HERE TOO, and nothing else:
529
+ * they describe the CHAIN's environment rather than one block's position in it,
530
+ * so a block 0 that reported a zero miner while every block after it reported
531
+ * the configured one would be the same disagreement this option's two fields
532
+ * were made honest to remove. `number`, `timestamp` and `gasLimit` stay the
533
+ * node's own for block 0 — genesis IS block 0 by definition, and `blockEnv.number`
534
+ * exists to place a MINED block, not to renumber the genesis of the chain.
535
+ *
536
+ * Whatever is set here is REPORTED by `eth_getBlockByNumber` as `miner` and
537
+ * `mixHash`, and survives a `dumpState` / `loadState` round trip, so the block
538
+ * a consumer reads and the block a contract ran in cannot disagree.
539
+ */
540
+ blockEnv?: BlockEnv;
541
+ /**
542
+ * The EVM this node runs on, BOTH halves: reads (`eth_call`,
543
+ * `eth_estimateGas`, `eth_fillTransaction`'s estimation) through
544
+ * {@link Engine.call} and transactions through {@link Engine.transact}.
545
+ * Default: `@ethereumjs/evm`, i.e. exactly what the node has always run.
546
+ *
547
+ * An engine that implements only one half is refused at construction rather
548
+ * than half-served — see {@link Engine.transact}.
549
+ *
550
+ * An engine is passed as an OBJECT, never named by a string: the core must not
551
+ * reference engines it does not use, or a consumer of the JS-only path would
552
+ * pay (in bundle size) for an engine they never import. See
553
+ * `docs/adr/0006-the-engine-is-an-injected-object-not-a-named-string.md`.
554
+ */
555
+ engine?: Engine;
556
+ }
557
+
558
+ /** A full genesis account (all fields optional except an implicit zero default). */
559
+ export interface GenesisAccount {
560
+ balance?: bigint;
561
+ nonce?: bigint;
562
+ code?: string; // 0x-prefixed hex (omit/`0x` for EOA)
563
+ storage?: Record<string, string>; // slot hex -> value hex
564
+ }
565
+
566
+ /** Mined-block header overrides (e.g. to honor a GeneralStateTest `env`). */
567
+ export interface BlockEnv {
568
+ coinbase?: string;
569
+ baseFeePerGas?: bigint;
570
+ number?: bigint;
571
+ timestamp?: bigint;
572
+ gasLimit?: bigint;
573
+ prevRandao?: string; // 0x-prefixed 32-byte hex (mixHash, post-Merge)
574
+ }
575
+
576
+ /** A slim node: transport-agnostic EIP-1193 + node-owned controls. */
577
+ export interface SlimNode {
578
+ /** EIP-1193 request. Async ⇒ same object works on main thread or over comlink. */
579
+ request(args: RequestArguments): Promise<unknown>;
580
+ /** Mine one block now (only matters in manual/interval modes). */
581
+ mine(): Promise<{blockNumber: number; blockHash: string; txHashes: string[]}>;
582
+ /** Serialize all state to a plain object (live-set-sized; no trie/RLP walk). */
583
+ dumpState(): Promise<SerializedState>;
584
+ /** Restore state previously produced by dumpState (replaces current state). */
585
+ loadState(state: SerializedState): Promise<void>;
586
+ /** Subscribe to newHeads locally (used by eth_subscribe and consumers). */
587
+ onNewHead(cb: (head: {number: number; hash: string}) => void): () => void;
588
+ /**
589
+ * Current canonical state root. In `'trie'` mode this is the REAL
590
+ * Merkle-Patricia root (usable for GeneralStateTests conformance); in `'none'`
591
+ * mode the trie is absent so this throws (honest — there is no root to give).
592
+ */
593
+ getStateRoot(): Promise<string>;
594
+ /** The state mode this node was created with. */
595
+ readonly stateMode: 'none' | 'trie';
596
+ /** The sender mode this node was created with. */
597
+ readonly senderMode: SenderMode;
598
+ /**
599
+ * The engine this node was created with — `{id: '@ethereumjs/evm'}` unless one
600
+ * was injected. It answered this node's reads AND executed its transactions, so
601
+ * a receipt from this node can be attributed to this id.
602
+ */
603
+ readonly engine: EngineInfo;
604
+ /** Stop timers / release resources. */
605
+ dispose(): Promise<void>;
606
+ }
607
+
608
+ /**
609
+ * Slim, live-set-sized serialized state. No trie, no RLP state-root walk.
610
+ *
611
+ * `version` IS STILL 1 AFTER THE BLOCK HEADER GREW `miner` / `mixHash` /
612
+ * `logsBloom` (2026-08-11), because those three fields were added as OPTIONAL
613
+ * reads rather than as a new shape: a dump written by an older version carries
614
+ * none of them and loads into this one unchanged (absent `miner` / `mixHash` read
615
+ * as zero, and the bloom is rebuilt from the receipts the dump already carries).
616
+ * A bump would have bought nothing a reader can act on and would have invalidated
617
+ * every IndexedDB record in the wild for a format they can still be read as. Bump
618
+ * it when a dump stops being loadable by the code that wrote it, which is the only
619
+ * question `version` can usefully answer.
620
+ */
621
+ export interface SerializedState {
622
+ version: 1;
623
+ chainId: number;
624
+ /** State mode the dump was produced in (informational). */
625
+ stateMode?: 'none' | 'trie';
626
+ /** SimpleStateManager Maps: address -> hex-encoded account/code/storage. */
627
+ accounts: Record<string, string>; // addr -> rlp/hex account
628
+ code: Record<string, string>; // addr -> code hex
629
+ storage: Record<string, Record<string, string>>; // addr -> (slot hex -> value hex)
630
+ /** Block list (header fields we keep) keyed by number. */
631
+ blocks: SerializedBlock[];
632
+ /** Receipts keyed by tx hash. */
633
+ receipts: Record<string, SerializedReceipt>;
634
+ /** Raw tx + meta keyed by tx hash (for eth_getTransactionByHash). */
635
+ transactions: Record<string, SerializedTx>;
636
+ }
637
+
638
+ export interface SerializedBlock {
639
+ number: number;
640
+ hash: string;
641
+ parentHash: string;
642
+ timestamp: number;
643
+ gasUsed: string;
644
+ gasLimit: string;
645
+ baseFeePerGas: string;
646
+ /** Real Merkle-Patricia state root in `'trie'` mode; zero placeholder in `'none'`. */
647
+ stateRoot: string;
648
+ /**
649
+ * The block's coinbase, under the name `eth_getBlockByNumber` reports it. Named
650
+ * for the RPC rather than for the header (`coinbase`) or the option
651
+ * ({@link BlockEnv.coinbase}) because this record exists to be SERVED: every
652
+ * other field here already carries its RPC name.
653
+ *
654
+ * OPTIONAL, and absent means the zero address — a dump written before this field
655
+ * existed has none. It is persisted rather than read off the `Block` object next
656
+ * to it because `loadState` rebuilds that object from THIS record, so a node that
657
+ * read the object would answer correctly until a reload and zero after one.
658
+ */
659
+ miner?: string;
660
+ /** The block's `mixHash`, i.e. post-Merge its PREVRANDAO. Absent means zero. */
661
+ mixHash?: string;
662
+ /**
663
+ * The block's logs bloom: the OR of its receipts' blooms, so a consumer
664
+ * pre-filtering blocks by it before calling `eth_getLogs` finds the logs that
665
+ * are really there. Absent (an older dump) means it is REBUILT on load from the
666
+ * receipts, which the dump carries either way.
667
+ */
668
+ logsBloom?: string;
669
+ transactions: string[]; // tx hashes
670
+ logsCount: number;
671
+ }
672
+
673
+ export interface SerializedLog {
674
+ address: string;
675
+ topics: string[];
676
+ data: string;
677
+ blockNumber: number;
678
+ blockHash: string;
679
+ transactionHash: string;
680
+ transactionIndex: number;
681
+ logIndex: number;
682
+ }
683
+
684
+ export interface SerializedReceipt {
685
+ transactionHash: string;
686
+ transactionIndex: number;
687
+ blockNumber: number;
688
+ blockHash: string;
689
+ from: string;
690
+ to: string | null;
691
+ contractAddress: string | null;
692
+ cumulativeGasUsed: string;
693
+ gasUsed: string;
694
+ effectiveGasPrice: string;
695
+ status: 0 | 1;
696
+ type: number;
697
+ logs: SerializedLog[];
698
+ logsBloom: string;
699
+ }
700
+
701
+ export interface SerializedTx {
702
+ hash: string;
703
+ raw: string;
704
+ from: string;
705
+ to: string | null;
706
+ nonce: number;
707
+ value: string;
708
+ input: string;
709
+ type: number;
710
+ blockNumber: number;
711
+ blockHash: string;
712
+ transactionIndex: number;
713
+ gas: string;
714
+ gasPrice: string | null;
715
+ maxFeePerGas: string | null;
716
+ maxPriorityFeePerGas: string | null;
717
+ }