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