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/dist/node.js ADDED
@@ -0,0 +1,1743 @@
1
+ /**
2
+ * node.ts — the execution-only EIP-1193 node.
3
+ *
4
+ * Design: sits BETWEEN bare `EVM.runCall` (no blocks/receipts/logs) and a full
5
+ * node (heavy). Runs on `@ethereumjs/vm` through the engine seam (see ./engine.ts)
6
+ * + a minimal mock blockchain with `SimpleStateManager` (plain Maps, NO trie, NO
7
+ * state-root) and NONE of the node / RPC / mempool / signing bloat.
8
+ *
9
+ * It is EXECUTION-ONLY:
10
+ * - NO account methods (eth_sendTransaction, eth_accounts, eth_sign,
11
+ * personal_x, wallet_x). Signing is client-side; node takes signed RAW txs.
12
+ * - Unsupported methods throw a real JSON-RPC method-not-found (-32601) — it
13
+ * NEVER fakes a success.
14
+ *
15
+ * BOTH halves of execution run on a swappable ENGINE (see ./engine.ts), defaulting
16
+ * to this VM's own `@ethereumjs/evm`: the READ path (`eth_call`,
17
+ * `eth_estimateGas`, `eth_fillTransaction`'s estimation) through `engine.call`,
18
+ * and the MINING path through `engine.transact`. What stays the node's either way:
19
+ * block construction, `cumulativeGasUsed`, receipt assembly, the RPC layer,
20
+ * transaction parsing and sender recovery.
21
+ *
22
+ * Transport-agnostic: just `request()` (async) + mine/dump/load. Knows nothing
23
+ * about Workers — see ./worker-entry.ts for the optional comlink wrapper.
24
+ */
25
+ import { createVM } from '@ethereumjs/vm';
26
+ import { MerkleStateManager } from '@ethereumjs/statemanager';
27
+ import { OverlayStorageStateManager } from './state-manager.js';
28
+ import { Common, Mainnet, Hardfork } from '@ethereumjs/common';
29
+ import { createBlock } from '@ethereumjs/block';
30
+ import { createTxFromRLP, createTx } from '@ethereumjs/tx';
31
+ import { createAddressFromString, createAccountFromRLP, Account, hexToBytes as hexToBytesStrict, bytesToHex, bytesToBigInt, bigIntToHex, setLengthLeft, bigIntToBytes, } from '@ethereumjs/util';
32
+ // `@ethereumjs/util`'s hexToBytes is typed to require a `0x${string}` literal.
33
+ // Our hex comes from runtime sources (RPC params, serialized state) typed as
34
+ // plain `string`, so wrap it once with a runtime 0x-guard rather than casting at
35
+ // every call site. Throws on malformed input (same as the underlying fn).
36
+ function hexToBytes(s) {
37
+ return hexToBytesStrict((s.startsWith('0x') ? s : '0x' + s));
38
+ }
39
+ import { keccak_256 } from '@noble/hashes/sha3.js';
40
+ import { connectEngine, createEthereumjsEngine } from './engine.js';
41
+ // Sender derivation stays the node's on every engine; what an engine may lend it
42
+ // is the CURVE step. See ./sender-recovery.ts.
43
+ import { recoverSender } from './sender-recovery.js';
44
+ // The engine reports EXECUTION gas for a read and the node adds intrinsic gas on top;
45
+ // an engine that charges intrinsic gas itself (revm) subtracts the SAME formula,
46
+ // so it has exactly one home. See ./intrinsic-gas.ts.
47
+ import { accessListGas, intrinsicGas as intrinsicGasOf, } from './intrinsic-gas.js';
48
+ import { RpcError, } from './types.js';
49
+ const ZERO_HASH = '0x' + '00'.repeat(32);
50
+ const ZERO_ADDRESS = '0x' + '00'.repeat(20);
51
+ /**
52
+ * What a block's `logsBloom` reads as when it admits nothing: a block with no
53
+ * logs, and the defensive fallback for a stored header carrying none at all
54
+ * (`loadState` rebuilds one for an older dump, so this is reached only by a
55
+ * hand-built `SerializedBlock`). It is NO LONGER what EVERY block reports, which
56
+ * is what it was until 2026-08-11 — see `blockToRpc`.
57
+ */
58
+ const EMPTY_LOGS_BLOOM = '0x' + '00'.repeat(256);
59
+ /**
60
+ * How much gas an `eth_call` / `eth_estimateGas` that names none may burn. A
61
+ * node-wide CONSTANT, not the node's `blockGasLimit`: the two are the same
62
+ * number by default and are still decided apart, for the reasons recorded at its
63
+ * one use site in `evmCall`.
64
+ */
65
+ const DEFAULT_READ_BUDGET = 30000000n;
66
+ /**
67
+ * HOW MANY EXECUTIONS `eth_estimateGas`'s SEARCH MAY SPEND, after the two it
68
+ * always spends (the run at the upper bound, and the one that confirms the
69
+ * measured consumption).
70
+ *
71
+ * The bound is not a safety net for a search that might not terminate — the
72
+ * search below bisects a bigint window and always does — it is a COST CEILING.
73
+ * This node runs in a browser tab and every probe is a full execution of the
74
+ * request, so an estimate is the one read that can cost tens of them.
75
+ *
76
+ * WHY THIS MANY. Bisection alone closes any window this node can produce
77
+ * (30,000,000 gas at the widest) in 25 halvings, and the search reaches phase 2
78
+ * with a window far narrower than that — so 32 is enough to be EXACT for every
79
+ * transaction whose minimum limit is near what it consumes, which is every
80
+ * transaction that is not deliberately gas-sensitive. What can exhaust it is a
81
+ * contract that reads `GAS` and spends what it finds: there the search stops and
82
+ * returns the smallest limit it has PROVEN to succeed, an over-estimate, which is
83
+ * the safe direction (unused gas is not charged, while an under-estimate is a
84
+ * transaction that runs out of gas in the user's face).
85
+ */
86
+ const MAX_ESTIMATE_PROBES = 32n;
87
+ /**
88
+ * A standard `Error(string)` revert reason, if that is what these bytes are.
89
+ *
90
+ * Used to put WHY into the failure `eth_estimateGas` throws when a request
91
+ * cannot succeed at ANY gas limit. The raw bytes travel on the error's `data`
92
+ * as they always have (a client decodes them), but a human reading a console
93
+ * gets the sentence too.
94
+ *
95
+ * DEFENSIVE BY CONSTRUCTION: it decodes the one shape Solidity emits for
96
+ * `require(false, "...")` / `revert("...")` and answers `undefined` for
97
+ * everything else — a custom error, a bare `revert()`, a halt with no data,
98
+ * truncated bytes. Never throws: an estimate must not fail differently because
99
+ * a callee reverted in a shape this decoder does not know.
100
+ */
101
+ function revertReason(returnValue) {
102
+ // 4-byte selector of `Error(string)` + head (32) + length (32).
103
+ if (returnValue.length < 68)
104
+ return undefined;
105
+ if (returnValue[0] !== 0x08 ||
106
+ returnValue[1] !== 0xc3 ||
107
+ returnValue[2] !== 0x79 ||
108
+ returnValue[3] !== 0xa0)
109
+ return undefined;
110
+ try {
111
+ // THE HEAD OFFSET IS CHECKED, not assumed. A `revert("...")` from any
112
+ // compiler puts the string's data immediately after the head, i.e. offset
113
+ // 0x20, and the length is then the word at [36,68). A legal-but-unusual
114
+ // encoding with a different offset would make that word something else
115
+ // entirely, and decoding it as a length yields a plausible-looking garbled
116
+ // sentence in an error message — worse than no sentence at all.
117
+ if (bytesToBigInt(returnValue.subarray(4, 36)) !== 32n)
118
+ return undefined;
119
+ const length = Number(bytesToBigInt(returnValue.subarray(36, 68)));
120
+ if (length === 0 || 68 + length > returnValue.length)
121
+ return undefined;
122
+ const text = new TextDecoder().decode(returnValue.subarray(68, 68 + length));
123
+ return text.length > 0 ? text : undefined;
124
+ }
125
+ catch {
126
+ return undefined;
127
+ }
128
+ }
129
+ function hex(b) {
130
+ return bytesToHex(b);
131
+ }
132
+ function numHex(n) {
133
+ return bigIntToHex(BigInt(n));
134
+ }
135
+ function txHashOf(tx) {
136
+ return hex(tx.hash());
137
+ }
138
+ /**
139
+ * Intrinsic gas: 21000 base (+32000 create) + calldata (16/non-zero, 4/zero) +
140
+ * the EIP-3860 initcode word cost (2 gas per 32-byte word) for creates, from
141
+ * Shanghai on. An engine reports EXECUTION gas only (`runCall`'s
142
+ * `executionGasUsed` omits all of this), so the node adds it back: it is what a
143
+ * transaction pays before its first opcode, and therefore the part of a gas LIMIT
144
+ * that never reaches the frame. `eth_estimateGas` uses it as the LOWER BOUND of
145
+ * its search (see `estimateGas` below), not as the answer.
146
+ *
147
+ * `common` is threaded rather than captured, and it is THE node's `Common` — the
148
+ * same instance the engine is handed at `connect`, so the two callers of the
149
+ * shared formula cannot name different forks. See ./intrinsic-gas.ts.
150
+ */
151
+ function intrinsicGas(dataHex, isCreate, common) {
152
+ return intrinsicGasOf(hexToBytes(dataHex.startsWith('0x') ? dataHex : '0x' + dataHex), isCreate, common);
153
+ }
154
+ /**
155
+ * WHAT A SENDER MUST BE ABLE TO PAY BEFORE THE TRANSACTION RUNS: its value plus
156
+ * its WHOLE gas limit at the MAXIMUM fee it offered.
157
+ *
158
+ * THE MAX FEE, NOT THE EFFECTIVE ONE, and that is the protocol's own line rather
159
+ * than a conservative choice: EIP-1559 states it as `assert balance >= gas_limit
160
+ * * max_fee_per_gas`, and both engines enforce exactly that — measured to the
161
+ * wei, on both, in
162
+ * `docs/spikes/replayed-and-invalid-transactions-are-rejected-as-the-nodes-own-errors/measurements.md`.
163
+ * A node checking the EFFECTIVE price instead would admit a window of
164
+ * transactions (`gasLimit * (maxFee - effective)` wide) that both engines then
165
+ * refuse in their own words.
166
+ *
167
+ * THIS IS NOT A SECOND IMPLEMENTATION OF THE FEE ARITHMETIC. What a transaction
168
+ * COSTS is the engine's and has exactly one implementation per engine (the
169
+ * `effectiveGasPrice` on the receipt is the engine's own number, never
170
+ * recomputed here — see ./engine.ts and `test/revm-fees.spec.ts`). This is an
171
+ * ADMISSION rule: what the sender must be able to cover for the transaction to be
172
+ * executable at all, which is the node's question because the node decides what
173
+ * goes into the blocks it builds.
174
+ *
175
+ * A TYPE-3 (BLOB) TRANSACTION IS UNDERSTATED HERE by its blob fee
176
+ * (`blobGas * maxFeePerBlobGas`), which is part of the same assertion in EIP-4844.
177
+ * That is the known type-3 gap this node documents rather than closes (the seam
178
+ * carries no blob fields at all), and the engines' own checks are the backstop:
179
+ * the node admits such a transaction and the engine refuses it in its own words.
180
+ */
181
+ function upfrontCost(tx) {
182
+ const anyTx = tx;
183
+ const perGas = anyTx.maxFeePerGas !== undefined && anyTx.maxFeePerGas !== null
184
+ ? anyTx.maxFeePerGas
185
+ : anyTx.gasPrice;
186
+ return (anyTx.value ?? 0n) + tx.gasLimit * perGas;
187
+ }
188
+ export async function createNode(options = {}) {
189
+ const chainId = options.chainId ?? 31337;
190
+ const stateMode = options.stateMode ?? 'none';
191
+ const senderMode = options.senderMode ?? 'recover';
192
+ const miningConfig = options.miningConfig ?? { type: 'auto' };
193
+ const baseFeePerGas = options.baseFeePerGas ?? 1000000000n;
194
+ const gasPrice = options.gasPrice ?? 1000000000n;
195
+ const maxPriorityFeePerGas = options.maxPriorityFeePerGas ?? 1000000000n;
196
+ const blockGasLimit = options.blockGasLimit ?? 30000000n;
197
+ const common = new Common({
198
+ chain: { ...Mainnet, chainId, name: 'webevm' },
199
+ hardfork: Hardfork.Cancun,
200
+ customCrypto: { keccak256: (m) => keccak_256(m) },
201
+ });
202
+ // State backing: SimpleStateManager (no trie, fast — default) or
203
+ // MerkleStateManager (real trie + state root — opt-in, slower, conformance-able).
204
+ // The 'none' manager is our SUBCLASS: storage is per-account with per-checkpoint
205
+ // OVERLAYS (upstream copies the whole flat storage map on every message frame),
206
+ // and it implements the `clearStorage(address)` that upstream ships as an empty
207
+ // no-op — without which a contract created at an address that already holds
208
+ // storage inherits it. See ./state-manager.ts.
209
+ const sm = stateMode === 'trie'
210
+ ? new MerkleStateManager()
211
+ : new OverlayStorageStateManager();
212
+ // Touched-account set for the trie-mode dump (storage is read back via the
213
+ // trie's own dumpStorage). We record the addresses each tx touches at the NODE
214
+ // level (sender / to / created) rather than monkeypatching the state manager —
215
+ // MerkleStateManager's cache/flush path is sensitive to method wrapping.
216
+ const touchedAccounts = new Set();
217
+ const ZERO_ROOT = ZERO_HASH;
218
+ async function currentStateRoot() {
219
+ if (stateMode !== 'trie')
220
+ return ZERO_ROOT;
221
+ const msm = sm;
222
+ await msm.flush(); // write cached trie nodes before reading the root
223
+ return hex(await msm.getStateRoot());
224
+ }
225
+ // Flush cache into the trie after a direct state mutation (trie mode only) so
226
+ // the next getStateRoot() reflects it. No-op in 'none' mode (the Map IS state).
227
+ async function commitIfTrie() {
228
+ if (stateMode !== 'trie')
229
+ return;
230
+ await sm.checkpoint();
231
+ await sm.commit();
232
+ }
233
+ // Read-modify-write an account (creating an empty one if absent), used by the
234
+ // evm_set* cheat methods. Commits into the trie in trie mode.
235
+ async function mutateAccount(addr, fn) {
236
+ const acc = (await sm.getAccount(addr)) ?? new Account();
237
+ fn(acc);
238
+ await sm.putAccount(addr, acc);
239
+ touchedAccounts.add(addr.toString());
240
+ await commitIfTrie();
241
+ }
242
+ // Minimal mock blockchain: `runTx` (inside the default engine) only needs
243
+ // getBlock (for BLOCKHASH) + shallowCopy. In 'none' mode we never compute a
244
+ // canonical state root.
245
+ const blockStore = new Map();
246
+ const blockByHash = new Map();
247
+ const receipts = new Map();
248
+ const transactions = new Map();
249
+ let allLogs = []; // flat, ordered log index for eth_getLogs
250
+ const mockBlockchain = {
251
+ getBlock: async (n) => {
252
+ let num;
253
+ if (n instanceof Uint8Array)
254
+ num = blockByHash.get(hex(n)) ?? 0;
255
+ else
256
+ num = Number(n);
257
+ const sb = blockStore.get(num) ?? blockStore.get(latestNumber);
258
+ return sb.block;
259
+ },
260
+ putBlock: async () => { },
261
+ shallowCopy() {
262
+ return mockBlockchain;
263
+ },
264
+ };
265
+ const vm = await createVM({
266
+ common,
267
+ stateManager: sm,
268
+ blockchain: mockBlockchain,
269
+ });
270
+ // THE ENGINE: what `eth_call` / `eth_estimateGas` / `eth_fillTransaction` read
271
+ // on AND what the mining path executes transactions on. Default = this VM's own
272
+ // `@ethereumjs/evm`, on both halves. An injected engine is connected HERE, during
273
+ // construction, so an engine that cannot serve this node's configuration throws
274
+ // now rather than at the first opcode.
275
+ //
276
+ // `??` is the ONLY place the default is chosen, and it reads an ABSENT option,
277
+ // never a failure: an engine that was supplied and cannot come up fails the
278
+ // construction (see connectEngine). There is deliberately no path from
279
+ // "your engine did not work" to "here is a node on the default engine".
280
+ //
281
+ // ONE ENGINE, BOTH HALVES. There is no per-operation selection here and no
282
+ // capability check: an `Engine` implements `call` AND `transact`, `connectEngine`
283
+ // refuses one that does not, and `node.engine` therefore names the EVM that
284
+ // answered this node's reads and executed its transactions alike.
285
+ const engine = options.engine ?? createEthereumjsEngine({ vm, stateManager: sm });
286
+ await connectEngine(engine, {
287
+ stateManager: sm,
288
+ common,
289
+ stateMode,
290
+ // Block hashes for BLOCKHASH, read LIVE (no block exists yet at this point)
291
+ // and SYNCHRONOUSLY, because an engine answers BLOCKHASH mid-opcode.
292
+ getBlockHash: (blockNumber) => {
293
+ const sb = blockStore.get(Number(blockNumber));
294
+ return sb ? hexToBytes(sb.header.hash) : undefined;
295
+ },
296
+ });
297
+ // THE ENGINE'S secp256k1, IF IT BROUGHT ONE. Read ONCE, after `connect`, so a
298
+ // transaction never pays a property lookup and — more to the point — so which
299
+ // implementation recovers this node's senders is fixed for the node's lifetime
300
+ // rather than able to change under it. `undefined` means the node recovers the
301
+ // way it always did (`tx.getSenderAddress()`); it is NOT filled in with a
302
+ // default, because the fallback IS `@ethereumjs/tx`'s own recovery and wrapping
303
+ // it as an engine method would only add a layer. See ./sender-recovery.ts.
304
+ const engineEcrecover = typeof engine.ecrecover === 'function'
305
+ ? engine.ecrecover.bind(engine)
306
+ : undefined;
307
+ let latestNumber = 0;
308
+ let parentHash = hexToBytes(ZERO_HASH);
309
+ // Initial balances FIRST (so the genesis state root, in trie mode, reflects them).
310
+ if (options.initialBalances) {
311
+ for (const [addr, bal] of Object.entries(options.initialBalances)) {
312
+ await sm.putAccount(createAddressFromString(addr), new Account(0n, bal));
313
+ touchedAccounts.add(createAddressFromString(addr).toString());
314
+ }
315
+ }
316
+ // Full genesis pre-state (balance/nonce/code/storage) — e.g. a GeneralStateTest
317
+ // `pre` section. Applied before block 0 so the trie-mode genesis root reflects
318
+ // it and a post-tx getStateRoot() can be compared to the fixture's hash.
319
+ if (options.initialState) {
320
+ for (const [addr, acc] of Object.entries(options.initialState)) {
321
+ const address = createAddressFromString(addr);
322
+ await sm.putAccount(address, new Account(acc.nonce ?? 0n, acc.balance ?? 0n));
323
+ if (acc.code && acc.code !== '0x')
324
+ await sm.putCode(address, hexToBytes(acc.code));
325
+ for (const [slot, val] of Object.entries(acc.storage ?? {})) {
326
+ await sm.putStorage(address, setLengthLeft(bigIntToBytes(BigInt(slot)), 32), hexToBytes(val));
327
+ }
328
+ touchedAccounts.add(address.toString());
329
+ }
330
+ // Commit the cache into the trie so the genesis root is correct in trie mode.
331
+ if (stateMode === 'trie') {
332
+ await sm.checkpoint();
333
+ await sm.commit();
334
+ }
335
+ }
336
+ const blockEnv = options.blockEnv;
337
+ /**
338
+ * THE GAS LIMIT OF EVERY BLOCK THIS NODE BUILDS, named once so that the block
339
+ * builder and the check that refuses a transaction too large for it cannot
340
+ * drift apart. `blockEnv.gasLimit` is the explicit per-block statement and
341
+ * `blockGasLimit` the node-wide one, in that order, which is the precedence the
342
+ * header below uses, because they are the same number.
343
+ *
344
+ * IT IS A REAL LIMIT, NOT A FORMALITY. The node used to hand `@ethereumjs/vm`
345
+ * a `skipBlockGasLimitValidation`, so a transaction asking for more gas than
346
+ * the block had was mined anyway, against a limit the block did not have, and
347
+ * only on that engine (revm expresses the same relaxation as a simulation
348
+ * switch and refuses to combine any of them with committing, so it rejected the
349
+ * very same transaction with `CallerGasLimitMoreThanBlock`). The flag is gone.
350
+ * A consumer who wants enormous gas limits raises `blockGasLimit`, which makes
351
+ * the permissiveness a VISIBLE property of the block that both engines honour
352
+ * by construction, and an honest one, since `GASLIMIT` then reports that same
353
+ * number to a contract.
354
+ */
355
+ const minedBlockGasLimit = blockEnv?.gasLimit ?? blockGasLimit;
356
+ // Genesis block.
357
+ //
358
+ // IT TAKES `blockEnv`'s COINBASE AND PREVRANDAO, and nothing else from it. Those
359
+ // two describe the environment this CHAIN runs under, so a block 0 reporting a
360
+ // zero miner while every block after it reports the configured one would be the
361
+ // same RPC-vs-EVM disagreement the fields are stored to remove, one block wide.
362
+ // `number`, `timestamp` and `gasLimit` stay the node's own: genesis IS block 0,
363
+ // and `blockEnv.number` places a MINED block rather than renumbering the chain's
364
+ // genesis (`minedBlockGasLimit` above is likewise the MINED block's limit).
365
+ const genesis = createBlock({
366
+ header: {
367
+ number: 0n,
368
+ gasLimit: blockGasLimit,
369
+ baseFeePerGas,
370
+ timestamp: BigInt(Math.floor(Date.now() / 1000)),
371
+ ...(blockEnv?.coinbase
372
+ ? { coinbase: createAddressFromString(blockEnv.coinbase) }
373
+ : {}),
374
+ difficulty: 0n,
375
+ ...(blockEnv?.prevRandao
376
+ ? { mixHash: hexToBytes(blockEnv.prevRandao) }
377
+ : {}),
378
+ },
379
+ }, { common });
380
+ storeBlock(genesis, [], [], await currentStateRoot());
381
+ // Pending raw txs awaiting the next mined block (manual/interval modes). Each
382
+ // carries its SENDER, decided once at parse time by `parseTx`: the node derives
383
+ // the sender (or is told it), never the engine.
384
+ const pending = [];
385
+ // newHeads subscribers.
386
+ const headSubs = new Set();
387
+ let intervalTimer;
388
+ if (miningConfig.type === 'interval') {
389
+ intervalTimer = setInterval(() => {
390
+ void mineBlock();
391
+ }, miningConfig.intervalMs);
392
+ }
393
+ /**
394
+ * THE BLOCK'S LOGS BLOOM: the OR of its receipts' own blooms, which is what a
395
+ * block bloom IS. Derived here rather than carried out of the mining loop so
396
+ * that `loadState` can rebuild it for a dump written before `SerializedBlock`
397
+ * had the field — same function, same answer, both sides of a round trip.
398
+ *
399
+ * IT IS NOT READ OFF `block.header.logsBloom`, unlike the coinbase and the
400
+ * mixHash beside it in `storeBlock`: the header is built (and frozen) BEFORE the
401
+ * block's transactions execute, so the only truthful bloom is this one.
402
+ */
403
+ function bloomOfReceipts(txHashes) {
404
+ const acc = new Uint8Array(256);
405
+ for (const h of txHashes) {
406
+ const r = receipts.get(h);
407
+ if (!r)
408
+ continue;
409
+ const bits = hexToBytes(r.logsBloom);
410
+ for (let i = 0; i < acc.length && i < bits.length; i++)
411
+ acc[i] |= bits[i];
412
+ }
413
+ return hex(acc);
414
+ }
415
+ function storeBlock(block, txHashes, logs, stateRoot) {
416
+ const number = Number(block.header.number);
417
+ const hash = hex(block.hash());
418
+ const header = {
419
+ number,
420
+ hash,
421
+ parentHash: hex(block.header.parentHash),
422
+ timestamp: Number(block.header.timestamp),
423
+ gasUsed: numHex(block.header.gasUsed),
424
+ gasLimit: numHex(block.header.gasLimit),
425
+ baseFeePerGas: numHex(block.header.baseFeePerGas ?? baseFeePerGas),
426
+ stateRoot,
427
+ // THE BLOCK'S OWN COINBASE AND MIXHASH, PERSISTED. They are read off the
428
+ // `Block` the EVM just ran — not off `blockEnv` — so "what the RPC reports"
429
+ // and "what COINBASE / PREVRANDAO returned" are one value with one source,
430
+ // and they are stored HERE because `loadState` rebuilds the block from this
431
+ // record: a reader that went to `sb.block` would answer correctly until a
432
+ // reload and zero afterwards.
433
+ miner: block.header.coinbase.toString(),
434
+ mixHash: hex(block.header.mixHash),
435
+ logsBloom: bloomOfReceipts(txHashes),
436
+ transactions: txHashes,
437
+ logsCount: logs.length,
438
+ };
439
+ blockStore.set(number, { block, header, logs });
440
+ blockByHash.set(hash, number);
441
+ latestNumber = number;
442
+ parentHash = block.hash();
443
+ }
444
+ async function executeAndMine(txs) {
445
+ const number = blockEnv?.number ?? BigInt(latestNumber + 1);
446
+ const blockBaseFee = blockEnv?.baseFeePerGas ?? baseFeePerGas;
447
+ const block = createBlock({
448
+ header: {
449
+ number,
450
+ gasLimit: minedBlockGasLimit,
451
+ baseFeePerGas: blockBaseFee,
452
+ parentHash,
453
+ timestamp: blockEnv?.timestamp ?? BigInt(Math.floor(Date.now() / 1000)),
454
+ ...(blockEnv?.coinbase
455
+ ? { coinbase: createAddressFromString(blockEnv.coinbase) }
456
+ : {}),
457
+ // post-Merge: difficulty must be 0; prevRandao lives in mixHash.
458
+ difficulty: 0n,
459
+ ...(blockEnv?.prevRandao
460
+ ? { mixHash: hexToBytes(blockEnv.prevRandao) }
461
+ : {}),
462
+ },
463
+ }, { common });
464
+ const blockHash = hex(block.hash());
465
+ const blockNumber = Number(number);
466
+ const txHashes = [];
467
+ const blockLogs = [];
468
+ let cumulativeGasUsed = 0n;
469
+ let txIndex = 0;
470
+ for (const { tx, raw, sender } of txs) {
471
+ // THE MINING PATH GOES THROUGH THE ENGINE. What comes back is the neutral
472
+ // `TransactionResult` — everything a receipt needs from an EVM and nothing
473
+ // else — so every line below is the NODE's own half: the block it landed in,
474
+ // the running `cumulativeGasUsed`, log positions, and the receipt itself.
475
+ // THE SENDER IS PASSED, NOT LEFT TO BE FOUND. It is the node's own value
476
+ // (recovered, or claimed in `senderMode:'trusted'`), and the receipt's `from`
477
+ // below is the SAME value — so "who the engine executed as" and "who the
478
+ // receipt names" cannot drift apart by engine.
479
+ //
480
+ // ...AND WHETHER IT MAY SEND IT AT ALL IS ANSWERED FIRST, HERE, against the
481
+ // state this transaction is about to run on and in the node's own words, so
482
+ // that a replayed, unaffordable or unreachable-nonce transaction is refused
483
+ // identically on every engine instead of in whichever vocabulary the
484
+ // installed one happens to speak. Nothing has been committed for this
485
+ // transaction when it throws: no receipt is built, no log is recorded, and
486
+ // the block below is never stored.
487
+ await refuseIfSenderCannotSend(tx, sender);
488
+ const res = await engine.transact({ tx, sender, block });
489
+ cumulativeGasUsed += res.gasUsed;
490
+ const h = txHashOf(tx);
491
+ const from = sender.toString();
492
+ const to = tx.to ? tx.to.toString() : null;
493
+ const created = res.createdAddress ? hex(res.createdAddress) : null;
494
+ // Track touched accounts for the trie-mode dump (sender, recipient, created,
495
+ // and any account that emitted a log — that set covers what changed).
496
+ touchedAccounts.add(from);
497
+ if (to)
498
+ touchedAccounts.add(to);
499
+ if (created)
500
+ touchedAccounts.add(created);
501
+ for (const log of res.logs)
502
+ touchedAccounts.add(hex(log.address));
503
+ const rcptLogs = res.logs.map((log, i) => {
504
+ const sl = {
505
+ address: hex(log.address),
506
+ topics: log.topics.map((t) => hex(t)),
507
+ data: hex(log.data),
508
+ blockNumber,
509
+ blockHash,
510
+ transactionHash: h,
511
+ transactionIndex: txIndex,
512
+ logIndex: blockLogs.length + i,
513
+ };
514
+ return sl;
515
+ });
516
+ blockLogs.push(...rcptLogs);
517
+ const receipt = {
518
+ transactionHash: h,
519
+ transactionIndex: txIndex,
520
+ blockNumber,
521
+ blockHash,
522
+ from,
523
+ to,
524
+ contractAddress: created,
525
+ cumulativeGasUsed: numHex(cumulativeGasUsed),
526
+ gasUsed: numHex(res.gasUsed),
527
+ effectiveGasPrice: numHex(res.effectiveGasPrice),
528
+ status: res.status,
529
+ type: tx.type ?? 0,
530
+ logs: rcptLogs,
531
+ logsBloom: hex(res.logsBloom),
532
+ };
533
+ receipts.set(h, receipt);
534
+ const stx = {
535
+ hash: h,
536
+ raw: hex(raw),
537
+ from,
538
+ to,
539
+ nonce: Number(tx.nonce),
540
+ value: numHex(tx.value ?? 0n),
541
+ input: hex(tx.data ?? new Uint8Array()),
542
+ type: tx.type ?? 0,
543
+ blockNumber,
544
+ blockHash,
545
+ transactionIndex: txIndex,
546
+ gas: numHex(tx.gasLimit),
547
+ gasPrice: tx.gasPrice !== undefined
548
+ ? numHex(tx.gasPrice)
549
+ : null,
550
+ maxFeePerGas: tx.maxFeePerGas !== undefined
551
+ ? numHex(tx.maxFeePerGas)
552
+ : null,
553
+ maxPriorityFeePerGas: tx.maxPriorityFeePerGas !== undefined
554
+ ? numHex(tx.maxPriorityFeePerGas)
555
+ : null,
556
+ };
557
+ transactions.set(h, stx);
558
+ txHashes.push(h);
559
+ txIndex++;
560
+ }
561
+ allLogs.push(...blockLogs);
562
+ storeBlock(block, txHashes, blockLogs, await currentStateRoot());
563
+ // emit newHeads
564
+ for (const cb of headSubs)
565
+ cb({ number: blockNumber, hash: blockHash });
566
+ return { blockNumber, blockHash, txHashes };
567
+ }
568
+ async function mineBlock() {
569
+ const batch = pending.splice(0, pending.length);
570
+ return executeAndMine(batch);
571
+ }
572
+ /**
573
+ * Decode a raw tx AND DECIDE ITS SENDER, once. When `claimedFrom` is supplied
574
+ * (the `evm_*As` methods, `senderMode:'trusted'` only) we SKIP ecrecover and take
575
+ * the caller-supplied address as the sender; otherwise we recover it, as a real
576
+ * node does.
577
+ *
578
+ * THE SENDER IS A VALUE FROM HERE ON. It travels with the transaction (see
579
+ * {@link SubmittedTx}) to the receipt's `from` and across the engine seam as
580
+ * `TransactionRequest.sender`, so exactly ONE place in the node answers "who sent
581
+ * this" and no engine is trusted to answer it again. Recovery is therefore EAGER
582
+ * (at submit, not at mine): a transaction whose signature cannot be recovered is
583
+ * rejected by the `eth_sendRawTransaction*` call that submitted it rather than by
584
+ * a later `mine()`, which is where a `'recover'` node would have failed anyway.
585
+ *
586
+ * WHAT THIS PRIMITIVE IS: "execute this tx as this sender, do not recover".
587
+ * That is all. It is deliberately NOT an impersonation feature — impersonation
588
+ * (an address registry + unsigned `eth_sendTransaction`, anvil/hardhat style) is
589
+ * account POLICY, and this package has no accounts by design. Two DIFFERENT
590
+ * callers want this one primitive:
591
+ *
592
+ * (a) A NORMAL, genuinely-signed tx that just wants to bypass a redundant
593
+ * ecrecover. The client signed it, so it already knows the sender;
594
+ * re-deriving it on a local chain is pure waste. The signature is REAL,
595
+ * merely unverified.
596
+ * (b) A HIGHER LAYER implementing impersonation on top: it has no key, so it
597
+ * FABRICATES a signature, serialises the tx, and passes the claimed
598
+ * sender. Nothing here needs to know that happened.
599
+ *
600
+ * WHY it is worth a cheat method: ecrecover is a FIXED cost per tx and it is the
601
+ * single dominant cost of a small one. Measured 2026-08-11
602
+ * (`docs/spikes/sender-recovery-uses-the-engines-ecrecover/measurements.md`) at
603
+ * ~6.2x on the isolated transaction path (2.09 -> 0.33 ms/tx, signing outside the
604
+ * window) and ~3.6x end-to-end through a viem-style client (2.37 -> 0.66 ms/tx;
605
+ * the residual is the CLIENT's own signing, which only case (b) avoids). Gas and
606
+ * status are byte-identical either way.
607
+ *
608
+ * THE GAP DEPENDS ON THE ENGINE NOW, and it has NARROWED. With an engine that
609
+ * brings its own secp256k1 (`Engine.ecrecover` in ./types.ts —
610
+ * `webevm/revm` does, at zero additional bytes) the recovery itself is
611
+ * ~4.3x cheaper, so `'recover'` costs 0.65 ms/tx isolated instead of 2.02 and the
612
+ * ratio falls to ~2.8x (~1.8x end to end). It stays worth having; it has stopped
613
+ * being the dominant lever. The figures this paragraph used to carry (~13x, ~2.3x)
614
+ * were measured on `runTx` in isolation before the storage re-layer of ADR 0009,
615
+ * and had drifted by roughly half — not because recovery got slower, but because
616
+ * everything around it got faster.
617
+ *
618
+ * HOW: the claimed address becomes this transaction's sender, full stop — nothing
619
+ * on the transaction is touched. Everything else about it stays REAL — same wire
620
+ * bytes, same `tx.hash()`, same signature on the wire — so receipts, block
621
+ * contents and `eth_getTransactionByHash` are unchanged. The ONLY thing dropped is
622
+ * the proof that the signer authorised this sender.
623
+ *
624
+ * IT USED TO SHADOW `tx.getSenderAddress()` on the parsed instance, because
625
+ * `runTx` reads the sender through exactly that one call. That worked only while
626
+ * the node itself ran `runTx`: once transactions cross the engine seam, a pinned
627
+ * method is an undocumented convention an engine has to interrogate the same way,
628
+ * and an engine recovering its own sender would silently execute as the SIGNER —
629
+ * charging that account, advancing its nonce, returning a plausible receipt. So
630
+ * the sender is data now, and the shadowing is gone rather than kept as a second
631
+ * mechanism saying the same thing.
632
+ *
633
+ * ---- CALLER CONTRACT, case (b) / fabricated signatures ONLY ----
634
+ *
635
+ * 1. TX BYTES MUST BE UNIQUE PER SENDER. `from` is NOT part of a transaction —
636
+ * it is the OUTPUT of recovery — so the hash is computed from the bytes
637
+ * alone. Two fabricated txs with the same dummy signature, nonce, `to` and
638
+ * data produce the SAME hash even for different claimed senders, and would
639
+ * silently overwrite each other in the receipt/tx maps. Derive the dummy `r`
640
+ * from the sender address (or otherwise vary the bytes per sender). anvil hit
641
+ * exactly this and fixed it by folding the sender into hash computation
642
+ * (foundry #4210). Genuinely-signed txs — case (a) — are unaffected: real
643
+ * signatures already differ per signer.
644
+ *
645
+ * 2. FABRICATED TXS ARE NOT PORTABLE TO A `'recover'` NODE. `dumpState` stores
646
+ * each tx's raw bytes, so a dump containing fabricated signatures carries txs
647
+ * no authenticated node could ever validate. Fine for a local chain; do not
648
+ * treat such a dump as a replayable chain history. Again, case (a) dumps are
649
+ * unaffected — those signatures are real.
650
+ *
651
+ * SAFETY: gated on `senderMode:'trusted'`. In the default `'recover'` mode these
652
+ * methods do not exist and we throw -32601 rather than silently trusting input.
653
+ */
654
+ function parseTx(rawHex, claimedFrom) {
655
+ const raw = hexToBytes(String(rawHex));
656
+ if (claimedFrom === undefined) {
657
+ const tx = createTxFromRLP(raw, { common });
658
+ // THE CURVE STEP, ON THE ENGINE WHEN THE ENGINE HAS ONE. The DECISION
659
+ // (which message is signed, EIP-2's low-`s` rule, what the wire's `v`
660
+ // means) stays here either way — see ./sender-recovery.ts, and
661
+ // `Engine.ecrecover` in ./types.ts for why it is the seam's one optional
662
+ // operation. With no engine ecrecover this is `@ethereumjs/tx`'s own
663
+ // recovery, unchanged, and the two are proven to authenticate identically
664
+ // (test/helpers/sender-recovery.ts) — on the transactions they ACCEPT and
665
+ // on the ones they must REFUSE.
666
+ return {
667
+ tx,
668
+ raw,
669
+ sender: engineEcrecover
670
+ ? recoverSender(tx, common, engineEcrecover)
671
+ : tx.getSenderAddress(),
672
+ };
673
+ }
674
+ if (senderMode !== 'trusted') {
675
+ throw new RpcError(-32601, "method not available: trusted-sender sends require senderMode:'trusted' " +
676
+ '(create the node with {senderMode:"trusted"} to skip ecrecover). That mode ' +
677
+ 'TRUSTS the caller-supplied sender, so ANY caller can impersonate ANY ' +
678
+ 'address — never enable it where untrusted callers can reach the node.');
679
+ }
680
+ // Throws on a malformed address rather than executing as someone unexpected.
681
+ const from = createAddressFromString(String(claimedFrom));
682
+ // The transaction is parsed FROZEN, like every other one: nothing about it is
683
+ // rewritten to carry the claimed sender, because the sender does not live on it.
684
+ const tx = createTxFromRLP(raw, { common });
685
+ return { tx, raw, sender: from };
686
+ }
687
+ /**
688
+ * REFUSE A TRANSACTION NO BLOCK THIS NODE BUILDS COULD CONTAIN, in the node's
689
+ * own words, before any engine sees it.
690
+ *
691
+ * WHY THE NODE SAYS IT AND NOT THE ENGINE. Both engines enforce this rule
692
+ * themselves now that the default engine no longer skips it (see ./engine.ts),
693
+ * and NEITHER can say it legibly: `@ethereumjs/vm` says "tx has a higher gas
694
+ * limit than the block" and revm says `Transaction(CallerGasLimitMoreThanBlock)`.
695
+ * Neither carries a number, and above all neither mentions `blockGasLimit`, the
696
+ * knob that lifts it, which only the node knows about. The block is the NODE's
697
+ * half of the seam on every engine (it builds it, it configures its gas limit),
698
+ * so "does this transaction fit in a block I will build" is the node's question
699
+ * to answer, and answering it here is what makes the refusal IDENTICAL on both
700
+ * engines rather than merely present on both. The engines' own checks stay as
701
+ * the backstop underneath: this is the same rule (`tx.gasLimit >
702
+ * block.header.gasLimit`, per transaction, not cumulative), so a transaction
703
+ * that passes here passes there.
704
+ *
705
+ * WHY AT SUBMIT rather than at mine: the same reason sender recovery is eager
706
+ * (see {@link parseTx}). The transaction is rejected by the
707
+ * `eth_sendRawTransaction*` call that submitted it, rather than sitting in
708
+ * `pending` and taking a whole later `mine()` batch down with it. Nothing about
709
+ * the answer changes with time: every block this node builds has the same
710
+ * {@link minedBlockGasLimit}.
711
+ */
712
+ function refuseIfOverBlockGasLimit(tx) {
713
+ const gasLimit = tx.gasLimit;
714
+ if (gasLimit <= minedBlockGasLimit)
715
+ return;
716
+ // -32000 (the JSON-RPC server-error range geth uses for a transaction its
717
+ // pool refuses) rather than 3 `execution reverted`: nothing executed, and a
718
+ // client that reads a revert here would look for return data that does not
719
+ // exist.
720
+ throw new RpcError(-32000, `transaction gas limit ${gasLimit} exceeds the block gas limit ${minedBlockGasLimit}, so no block this node builds could contain it. ` +
721
+ `It is REFUSED rather than mined against a limit the block does not have (a real node refuses it too, and this node's other EVM engine always did). ` +
722
+ `To allow it, raise the limit: createNode({blockGasLimit: ${gasLimit}n}). The default is 30000000n, or blockEnv.gasLimit if you set the block environment explicitly. ` +
723
+ `The block then really is that large: GASLIMIT reports the configured value to a contract, and eth_getBlockByNumber reports it too.`);
724
+ }
725
+ /**
726
+ * REFUSE A TRANSACTION THE SENDER'S OWN ACCOUNT FORBIDS — a replay, a nonce this
727
+ * node will never reach, or a bill the sender cannot cover — in the node's own
728
+ * words, before the engine sees it.
729
+ *
730
+ * WHY THE NODE SAYS IT AND NOT THE ENGINE, which is the same argument
731
+ * {@link refuseIfOverBlockGasLimit} makes and the reason this sits beside it.
732
+ * Both engines enforce these three rules already, and neither can say them in a
733
+ * way a client can use: `@ethereumjs/vm` answers a replay with `the tx doesn't
734
+ * have the correct nonce. account has nonce of: 1 tx has nonce of: 0` followed
735
+ * by a dump of the whole block and transaction, and revm answers it with
736
+ * `Transaction(NonceTooLow { tx: 0, state: 1 })`. Same node, same transaction,
737
+ * two unrelated sentences — and the revm one is a wasm-shaped string arriving
738
+ * where a client expects prose, the transaction-path twin of the mistake
739
+ * recorded in the `rejectionMessage` JSDoc of ./revm.ts. The node owns the
740
+ * STATE on every engine (ADR 0010) and it owns the transaction's parsing, so
741
+ * "may this sender send this transaction now" is the node's question, and
742
+ * answering it here is what makes the refusal IDENTICAL across engines rather
743
+ * than merely present on both. The engines' own checks stay as the backstop
744
+ * underneath: these are the same three rules, so a transaction that passes here
745
+ * passes there.
746
+ *
747
+ * IT ALSO FIXES THE ORDER, which no engine agrees about: a transaction that is
748
+ * both replayed and unaffordable is reported as a nonce failure by geth and by
749
+ * this node, and could be reported as either by an engine. One order here means
750
+ * one answer whatever is installed.
751
+ *
752
+ * WHY AT MINE-TIME rather than at submit, unlike its two siblings: these answers
753
+ * CHANGE WITH TIME. In `manual`/`interval` mining a consumer submits nonce 0 and
754
+ * nonce 1 back to back, and at submit the second is a nonce this node has not
755
+ * reached; by the time the batch is mined, the first has advanced it. The same
756
+ * goes for the money. So the reading is taken at the last possible moment —
757
+ * immediately before the engine would execute it — against the state the
758
+ * transaction is actually about to run on.
759
+ *
760
+ * THE VOCABULARY IS geth's leading clause (`nonce too low` / `nonce too high` /
761
+ * `insufficient funds for gas * price + value`), because a client already knows
762
+ * it: viem maps those phrases onto typed errors. Inventing a private dialect for
763
+ * rules the whole ecosystem already names would cost every consumer a
764
+ * translation and buy nothing. What follows the clause is this node's own
765
+ * honest-edge half — what happened and what to do about it — including the one
766
+ * thing a real node would NOT say: that there is no mempool here, so a
767
+ * too-high nonce is refused rather than queued.
768
+ */
769
+ async function refuseIfSenderCannotSend(tx, sender) {
770
+ // ONE READ of the sender's account, for both rules: a missing account is a
771
+ // sender at nonce 0 holding nothing, which is exactly how every other read on
772
+ // this node reports it (`eth_getTransactionCount`, `eth_getBalance`).
773
+ const account = await sm.getAccount(sender);
774
+ const stateNonce = account?.nonce ?? 0n;
775
+ const txNonce = tx.nonce;
776
+ const address = sender.toString();
777
+ if (txNonce < stateNonce) {
778
+ throw new RpcError(-32000, `nonce too low: address ${address}, tx: ${txNonce}, state: ${stateNonce}. ` +
779
+ `The sender has already used that nonce, so this transaction is a REPLAY ` +
780
+ `and is REFUSED rather than mined a second time. Sign it again with nonce ` +
781
+ `${stateNonce} — eth_getTransactionCount reports the sender's next nonce.`);
782
+ }
783
+ if (txNonce > stateNonce) {
784
+ throw new RpcError(-32000, `nonce too high: address ${address}, tx: ${txNonce}, state: ${stateNonce}. ` +
785
+ `This node has NO MEMPOOL, so a transaction that is not executable NOW is ` +
786
+ `refused rather than queued until the gap is filled: waiting will not mine ` +
787
+ `it. Send the missing transactions first, or sign this one with nonce ` +
788
+ `${stateNonce} — eth_getTransactionCount reports the sender's next nonce.`);
789
+ }
790
+ const balance = account?.balance ?? 0n;
791
+ const upfront = upfrontCost(tx);
792
+ if (balance < upfront) {
793
+ throw new RpcError(-32000, `insufficient funds for gas * price + value: address ${address} have ` +
794
+ `${balance} want ${upfront}. The sender must be able to pay for its WHOLE ` +
795
+ `gas limit at the maximum fee it offered, plus the value it sends, BEFORE ` +
796
+ `the transaction runs — even though it is charged less than that once the ` +
797
+ `gas it really used is known. Lower the value, the gas limit or ` +
798
+ `maxFeePerGas, or fund the sender.`);
799
+ }
800
+ }
801
+ /**
802
+ * REFUSE A TRANSACTION THAT COULD NOT REACH ITS FIRST OPCODE, in the node's own
803
+ * words, before any engine sees it.
804
+ *
805
+ * The second of the two refusals a transaction earns ON ITS OWN, which is why it
806
+ * sits beside {@link refuseIfOverBlockGasLimit} and at the same moment: both
807
+ * read the transaction and nothing else, so neither answer can change while the
808
+ * transaction waits in `pending`, and refusing eagerly means the
809
+ * `eth_sendRawTransaction*` call that submitted it is the one that fails. The
810
+ * two that DO depend on the chain's state — the nonce and the money — are
811
+ * checked at the last possible moment instead, in {@link refuseIfSenderCannotSend}.
812
+ *
813
+ * THE FLOOR IS THE TRANSACTION'S OWN `getIntrinsicGas()`, NOT the shared
814
+ * `intrinsicGas()` of ./intrinsic-gas.ts, and the difference is load-bearing:
815
+ * the shared formula has no ACCESS-LIST term, because an `eth_call` carries no
816
+ * access list, so it is 6,200 gas short for a type-1 transaction naming one
817
+ * address and two keys. Both engines charge the access list, so a check built on
818
+ * the shared formula would wave such a transaction through and let the engine
819
+ * refuse it in its own vocabulary — the exact divergence this refusal exists to
820
+ * remove. Measured, on four transaction shapes and against BOTH engines' actual
821
+ * floors, in
822
+ * `docs/spikes/replayed-and-invalid-transactions-are-rejected-as-the-nodes-own-errors/measurements.md`.
823
+ * The two figures answer two different questions and both are the node's: what a
824
+ * READ must be budgeted (and an engine's execution gas topped up by), versus what
825
+ * a TRANSACTION must be able to pay before it starts.
826
+ */
827
+ function refuseIfBelowIntrinsicGas(tx) {
828
+ const gasLimit = tx.gasLimit;
829
+ const minimum = tx.getIntrinsicGas();
830
+ if (gasLimit >= minimum)
831
+ return;
832
+ throw new RpcError(-32000, `intrinsic gas too low: have ${gasLimit}, want ${minimum}. ` +
833
+ `A transaction pays a 21000 base plus its calldata (and its access list, and ` +
834
+ `32000 more to create a contract) before its first opcode runs, so this gas ` +
835
+ `limit could not start it and no block this node builds could contain it. ` +
836
+ `Raise the gas limit to at least ${minimum} — eth_estimateGas reports what a ` +
837
+ `transaction needs, given the same calldata AND the same access list, which ` +
838
+ `it charges too.`);
839
+ }
840
+ /** Queue-or-execute a submitted tx; returns the hash, or the receipt if `sync`. */
841
+ async function submit(submitted, sync) {
842
+ refuseIfOverBlockGasLimit(submitted.tx);
843
+ refuseIfBelowIntrinsicGas(submitted.tx);
844
+ const h = txHashOf(submitted.tx);
845
+ if (miningConfig.type === 'auto') {
846
+ await executeAndMine([submitted]);
847
+ }
848
+ else {
849
+ pending.push(submitted);
850
+ if (sync)
851
+ await mineBlock();
852
+ }
853
+ if (!sync)
854
+ return h;
855
+ const r = receipts.get(h);
856
+ return r ? receiptToRpc(r) : null;
857
+ }
858
+ // ---------- block lookup helpers ----------
859
+ function resolveBlockTag(tag) {
860
+ if (tag === 'latest' ||
861
+ tag === 'pending' ||
862
+ tag === 'safe' ||
863
+ tag === 'finalized' ||
864
+ tag == null)
865
+ return latestNumber;
866
+ if (tag === 'earliest')
867
+ return 0;
868
+ if (typeof tag === 'string')
869
+ return Number(BigInt(tag));
870
+ if (typeof tag === 'number')
871
+ return tag;
872
+ return latestNumber;
873
+ }
874
+ /**
875
+ * The stored block, as `eth_getBlockByNumber` / `eth_getBlockByHash` report it.
876
+ *
877
+ * IT READS THE SERIALISED HEADER AND NOTHING ELSE, deliberately. `sb.block` is
878
+ * right there and carries the same coinbase and mixHash, but it is the object
879
+ * `loadState` REBUILDS, so a field taken from it would be reported correctly by
880
+ * a live node and as zero by the same node after a reload — which is worse than
881
+ * a uniform zero, because nothing tells a consumer which side of the trip they
882
+ * are on. Every value below is therefore one a dump carries.
883
+ *
884
+ * `stateRoot` is the one REAL value among the roots (in `'trie'` mode);
885
+ * `sha3Uncles`, `transactionsRoot` and `receiptsRoot` stay honest zero
886
+ * placeholders, named as such in the README, because this node builds no tries
887
+ * over its transactions or receipts. `logsBloom` used to be in that list and is
888
+ * not any more: it is the OR of the block's receipt blooms, so the standard
889
+ * pre-filter (test the header bloom, then call `eth_getLogs`) finds what is
890
+ * there instead of silently finding nothing.
891
+ */
892
+ function blockToRpc(sb, fullTx) {
893
+ const h = sb.header;
894
+ return {
895
+ number: numHex(h.number),
896
+ hash: h.hash,
897
+ parentHash: h.parentHash,
898
+ nonce: '0x0000000000000000',
899
+ sha3Uncles: ZERO_HASH,
900
+ logsBloom: h.logsBloom ?? EMPTY_LOGS_BLOOM,
901
+ transactionsRoot: ZERO_HASH,
902
+ stateRoot: h.stateRoot,
903
+ receiptsRoot: ZERO_HASH,
904
+ // A dump written before these fields existed carries neither, and absent
905
+ // means ZERO rather than `undefined`: an old state loads into a block that
906
+ // really had a zero coinbase, not into an RPC result missing a field.
907
+ miner: h.miner ?? ZERO_ADDRESS,
908
+ mixHash: h.mixHash ?? ZERO_HASH,
909
+ difficulty: '0x0',
910
+ totalDifficulty: '0x0',
911
+ extraData: '0x',
912
+ size: '0x0',
913
+ gasLimit: h.gasLimit,
914
+ gasUsed: h.gasUsed,
915
+ timestamp: numHex(h.timestamp),
916
+ baseFeePerGas: h.baseFeePerGas,
917
+ uncles: [],
918
+ transactions: fullTx
919
+ ? h.transactions.map((th) => txToRpc(transactions.get(th)))
920
+ : h.transactions,
921
+ };
922
+ }
923
+ function txToRpc(t) {
924
+ // The 1559 fee fields are OMITTED for a legacy transaction rather than emitted as
925
+ // `null`, which is what geth does. The difference is not cosmetic: consumers branch with
926
+ // `'maxFeePerGas' in tx`, so a present-but-null field sends them down the 1559 path and
927
+ // they then blow up on `BigInt(null)`. A key that exists only when it means something
928
+ // keeps that idiom honest.
929
+ return {
930
+ hash: t.hash,
931
+ nonce: numHex(t.nonce),
932
+ blockHash: t.blockHash,
933
+ blockNumber: numHex(t.blockNumber),
934
+ transactionIndex: numHex(t.transactionIndex),
935
+ from: t.from,
936
+ to: t.to,
937
+ value: t.value,
938
+ gas: t.gas,
939
+ gasPrice: t.gasPrice,
940
+ ...(t.maxFeePerGas == null ? {} : { maxFeePerGas: t.maxFeePerGas }),
941
+ ...(t.maxPriorityFeePerGas == null
942
+ ? {}
943
+ : { maxPriorityFeePerGas: t.maxPriorityFeePerGas }),
944
+ input: t.input,
945
+ type: numHex(t.type),
946
+ chainId: numHex(chainId),
947
+ };
948
+ }
949
+ function receiptToRpc(r) {
950
+ return {
951
+ transactionHash: r.transactionHash,
952
+ transactionIndex: numHex(r.transactionIndex),
953
+ blockHash: r.blockHash,
954
+ blockNumber: numHex(r.blockNumber),
955
+ from: r.from,
956
+ to: r.to,
957
+ contractAddress: r.contractAddress,
958
+ cumulativeGasUsed: r.cumulativeGasUsed,
959
+ gasUsed: r.gasUsed,
960
+ effectiveGasPrice: r.effectiveGasPrice,
961
+ status: r.status ? '0x1' : '0x0',
962
+ type: numHex(r.type),
963
+ logs: r.logs.map(logToRpc),
964
+ logsBloom: r.logsBloom,
965
+ };
966
+ }
967
+ function logToRpc(l) {
968
+ return {
969
+ address: l.address,
970
+ topics: l.topics,
971
+ data: l.data,
972
+ blockNumber: numHex(l.blockNumber),
973
+ blockHash: l.blockHash,
974
+ transactionHash: l.transactionHash,
975
+ transactionIndex: numHex(l.transactionIndex),
976
+ logIndex: numHex(l.logIndex),
977
+ removed: false,
978
+ };
979
+ }
980
+ // ---------- eth_call / estimateGas through the ENGINE's READ half (no signing) ----
981
+ /**
982
+ * The node's single pure-read helper, and the read half of the engine seam: it
983
+ * normalises RPC params into a {@link ReadCallRequest} and hands them to the
984
+ * engine's `call`.
985
+ * Three dispatcher cases use it (`eth_call`, `eth_estimateGas` and
986
+ * `eth_fillTransaction`'s estimation).
987
+ *
988
+ * Keeping a read PURE is the engine's job, not this function's — the default
989
+ * `@ethereumjs/evm` engine checkpoints/reverts and resets EIP-2929 warmth
990
+ * because that EVM requires it; an engine that cannot commit pays for neither.
991
+ * See ./engine.ts.
992
+ */
993
+ async function evmCall(params, budget) {
994
+ const from = params.from
995
+ ? createAddressFromString(params.from)
996
+ : createAddressFromString('0x0000000000000000000000000000000000000000');
997
+ const to = params.to ? createAddressFromString(params.to) : undefined;
998
+ const data = params.data
999
+ ? hexToBytes(params.data)
1000
+ : params.input
1001
+ ? hexToBytes(params.input)
1002
+ : new Uint8Array();
1003
+ const value = params.value ? BigInt(params.value) : 0n;
1004
+ // THE DEFAULT READ BUDGET IS A CONSTANT, DELIBERATELY NOT `blockGasLimit`.
1005
+ // They are the same number by default (30,000,000) and it would be easy to
1006
+ // read the second off the first, but they answer different questions and are
1007
+ // DECIDED APART. That is recorded here because a `blockGasLimit` a consumer
1008
+ // may now have to raise (it is what buys back the block-gas-limit relaxation
1009
+ // the engines used to disagree about; see `refuseIfOverBlockGasLimit` above)
1010
+ // makes the link actively harmful:
1011
+ // - A BLOCK GAS LIMIT is a property of the chain a transaction is mined into,
1012
+ // visible to a contract as `GASLIMIT`. A READ BUDGET is how long an
1013
+ // `eth_call` with no `gas` may run before it halts. Linking them means
1014
+ // `createNode({blockGasLimit: 10_000_000_000n})` silently buys every
1015
+ // unbudgeted `eth_call` a 300x longer runaway, and the browser tab that
1016
+ // locks up is nowhere near the option that caused it.
1017
+ // - The constant is also QUOTED as a fixed number by the revm engine's
1018
+ // hardfork refusals (`REVM_REFUSED_HARDFORKS.osaka` compares it against
1019
+ // EIP-7825's 16,777,216 cap in src/revm.ts), which a per-node value would
1020
+ // make wrong for some nodes and right for others.
1021
+ // A caller who wants a bigger budget passes `gas` on the call itself, which is
1022
+ // the standard `eth_call` field for exactly this and needs no configuration.
1023
+ //
1024
+ // `budget` OVERRIDES BOTH, and exactly one caller passes it: the
1025
+ // `estimateGas` search below, which is asking a different question from
1026
+ // "how long may this call run". It probes a candidate gas LIMIT, and the
1027
+ // gas that reaches the frame under that limit is the limit MINUS the
1028
+ // intrinsic cost the transaction pays first — so the search computes the
1029
+ // budget itself and this function must not re-derive one from `params.gas`,
1030
+ // which for `eth_estimateGas` is a CAP on the limit rather than a budget.
1031
+ const gasLimit = budget ?? (params.gas ? BigInt(params.gas) : DEFAULT_READ_BUDGET);
1032
+ return engine.call({
1033
+ from,
1034
+ to,
1035
+ data,
1036
+ value,
1037
+ gasLimit,
1038
+ block: blockStore.get(latestNumber).block,
1039
+ });
1040
+ }
1041
+ /**
1042
+ * THE SMALLEST GAS LIMIT AT WHICH THIS REQUEST SUCCEEDS — a SEARCH, not a
1043
+ * measurement, and the difference is the whole point of this function.
1044
+ *
1045
+ * ## Why measuring is the wrong answer
1046
+ *
1047
+ * This method used to run the request once and report what it CONSUMED
1048
+ * (`executionGasUsed` + intrinsic gas), which is exact and is not what the
1049
+ * caller asked for. A client turns this number into a transaction's gas LIMIT,
1050
+ * and under EIP-150's 63/64 rule a `CALL` or `CREATE` forwards at most 63/64 of
1051
+ * the gas remaining at that point: a transaction whose limit equals its total
1052
+ * consumption therefore starves its own sub-call by the 1/64 the outer frame
1053
+ * keeps. Consumption is a LOWER BOUND on the limit, never the limit.
1054
+ *
1055
+ * That is not theoretical. Deploying through the standard CREATE2 factory
1056
+ * (`0x4e59b448...`, a plain call whose body does one `CREATE2`) with a limit
1057
+ * taken from this method returned a receipt with `status: 0x0` and no created
1058
+ * contract, while the factory itself, the funding transfer and a proxy pointing
1059
+ * at the address that was never deployed all mined fine — so the failure landed
1060
+ * nowhere near its cause: a proxy delegatecalling an address with no code, which
1061
+ * answers `0x` rather than failing. The same shape is recorded from the other
1062
+ * side in `test/helpers/post-state.ts`, where an estimate-sized limit made an
1063
+ * inner `SSTORE` run out of gas while the receipt still said success.
1064
+ *
1065
+ * So this searches for the smallest limit at which the request SUCCEEDS, which
1066
+ * is what geth's `eth_estimateGas` has always done and for exactly this reason.
1067
+ *
1068
+ * ## The shape, and what each step costs
1069
+ *
1070
+ * 1. ONE RUN AT THE UPPER BOUND (the caller's `gas` if it named one, capped at
1071
+ * the block gas limit — see below). If the request fails there it fails
1072
+ * everywhere, and this method throws instead of returning a plausible number
1073
+ * that would fail on submission.
1074
+ * 2. ONE PROBE AT THE MEASURED CONSUMPTION. A request that makes no sub-call and
1075
+ * no create succeeds at exactly what it consumed, so the common case (a
1076
+ * transfer, an `SSTORE`, a deployment) is answered EXACTLY, in one extra
1077
+ * execution, and the search below never runs. This is the short-circuit, and
1078
+ * it is a probe rather than a static "does this request call out?" test
1079
+ * because only the EVM knows: the answer lives in the callee's bytecode.
1080
+ * 3. A SEARCH in `(consumption, upper bound]`, which brackets the answer from
1081
+ * BELOW at the scale of the 63/64 rule before bisecting, so a window that
1082
+ * starts 30,000,000 wide is never walked down from the top. Bounded by
1083
+ * {@link MAX_ESTIMATE_PROBES}; on exhaustion it returns the smallest limit it
1084
+ * has PROVEN to succeed, which over-estimates rather than under-estimates.
1085
+ *
1086
+ * ## Consumption as the lower bound, and the one case it is not one
1087
+ *
1088
+ * `low` starts at the measured consumption and is treated as KNOWN-FAILING
1089
+ * (step 2 has just proven it), which is safe for every transaction whose cost
1090
+ * does not depend on the gas it is given. A transaction that reads `GAS` and
1091
+ * spends what it finds consumes MORE at a higher limit, so its consumption at
1092
+ * the upper bound is not a lower bound on the minimum successful limit. geth
1093
+ * documents the same caveat and makes the same choice: the alternative is to
1094
+ * start the search at the intrinsic floor and pay ~11 more executions on every
1095
+ * estimate, to serve a transaction whose "minimum" limit is meaningless anyway.
1096
+ * The result stays a limit at which the transaction SUCCEEDS, which is the
1097
+ * property that matters.
1098
+ *
1099
+ * ## The intrinsic terms are the search's floor, not an addend to its result
1100
+ *
1101
+ * `overhead` is what the transaction pays before its first opcode: the shared
1102
+ * intrinsic formula (base + calldata + the EIP-3860 initcode term) PLUS the
1103
+ * request's EIP-2930 access list, which the engine never sees (`ReadCallRequest`
1104
+ * carries none on either engine), charged here by the one caller that has a
1105
+ * request to read it off. Every candidate limit is probed as
1106
+ * `budget = limit - overhead`, so the frame gets exactly the gas the mined
1107
+ * transaction would give it, and every number this method can return is at least
1108
+ * `overhead`. That last clause is load-bearing: `refuseIfBelowIntrinsicGas`
1109
+ * points callers HERE for "the number a transaction needs", so the node must
1110
+ * never refuse a limit it has just recommended.
1111
+ */
1112
+ async function estimateGas(p) {
1113
+ const dataHex = p.data ?? p.input ?? '0x';
1114
+ const isCreate = !p.to;
1115
+ const overhead = intrinsicGas(dataHex, isCreate, common) + accessListGas(p.accessList);
1116
+ // THE UPPER BOUND, and why it is capped at the block gas limit even when the
1117
+ // caller named a larger `gas`: a limit above it is REFUSED at submit by
1118
+ // `refuseIfOverBlockGasLimit`, so recommending one would be the node handing
1119
+ // back a number it will not accept. `gas` on an `eth_estimateGas` request is
1120
+ // geth's cap on the SEARCH ("do not consider limits above this"), which is a
1121
+ // different thing from `gas` on an `eth_call` ("let it run this long").
1122
+ const supplied = p.gas != null ? BigInt(p.gas) : undefined;
1123
+ const cap = supplied === undefined || supplied > minedBlockGasLimit
1124
+ ? minedBlockGasLimit
1125
+ : supplied;
1126
+ // Nothing to search: the cap cannot pay for the transaction's own bytes, so
1127
+ // no limit within it reaches an opcode. Said in the vocabulary of the refusal
1128
+ // that would meet such a limit at submit, and NOT as `execution reverted`:
1129
+ // nothing executed, and a client reading a revert here would look for return
1130
+ // data that does not exist.
1131
+ if (cap < overhead) {
1132
+ throw new RpcError(-32000, `gas required exceeds allowance (${cap}): this transaction pays ${overhead} gas ` +
1133
+ `for its 21000 base, its calldata and its access list before its first opcode ` +
1134
+ `runs, so no gas limit within the allowance could start it. ` +
1135
+ (supplied !== undefined && supplied <= minedBlockGasLimit
1136
+ ? `The allowance is the \`gas\` you passed on the request; raise it or omit it.`
1137
+ : `The allowance is this node's block gas limit; raise it with createNode({blockGasLimit: ...}).`));
1138
+ }
1139
+ const probe = (limit) => evmCall(p, limit - overhead);
1140
+ // 1) THE UPPER BOUND, run first: a request that cannot succeed with all the
1141
+ // gas there is cannot succeed at all, and the caller learns that here rather
1142
+ // than from a receipt.
1143
+ const top = await probe(cap);
1144
+ if (top.error) {
1145
+ // TWO WAYS TO FAIL AT THE TOP, AND THEY ARE DIFFERENT PROBLEMS. A request
1146
+ // that BURNED THE WHOLE ALLOWANCE and produced no callee bytes ran out of
1147
+ // gas: nothing reverted, there is no revert data to decode, and the caller's
1148
+ // problem is the allowance rather than the contract. geth says `gas required
1149
+ // exceeds allowance` to that, at -32000, which is what the `cap < overhead`
1150
+ // refusal above already says — so this branch keeps the two consistent
1151
+ // instead of flattening one of them into a revert a client would then hunt
1152
+ // for return data on.
1153
+ //
1154
+ // THE TEST IS STRUCTURAL, not a vocabulary: "did it consume everything it
1155
+ // was given, with nothing to show for it". Both engines report the whole
1156
+ // budget as spent when a frame halts for want of gas (revm's
1157
+ // `totalGasSpent` less the intrinsic the engine added back, the default
1158
+ // engine's `executionGasUsed`), and neither's WORDS for it are the other's
1159
+ // — matching on `out of gas` would be one engine's string asserted on both,
1160
+ // the mistake `rejectionMessage` in ./revm.ts exists to avoid. A REVERT
1161
+ // keeps its bytes and its gas, and a refusal BEFORE execution (an
1162
+ // unaffordable value) spends none, so both fall through to the clause below.
1163
+ // `budget > 0` because a zero budget makes "spent everything" vacuously
1164
+ // true, and a caller who passed `gas` equal to the intrinsic floor exactly
1165
+ // is better served by the engine's own words.
1166
+ const budget = cap - overhead;
1167
+ if (budget > 0n &&
1168
+ top.executionGasUsed >= budget &&
1169
+ top.returnValue.length === 0) {
1170
+ throw new RpcError(-32000, `gas required exceeds allowance (${cap}): the transaction consumed the ENTIRE ` +
1171
+ `allowance and still did not succeed, so it needs more gas than the allowance ` +
1172
+ `permits (or it cannot succeed at all — an invalid opcode also spends everything). ` +
1173
+ `Nothing reverted, so there is no revert reason to decode. ` +
1174
+ (supplied !== undefined && supplied <= minedBlockGasLimit
1175
+ ? `The allowance is the \`gas\` you passed on the request; raise it or omit it.`
1176
+ : `The allowance is this node's block gas limit, which is also the most a transaction ` +
1177
+ `it mines may ask for; raise it with createNode({blockGasLimit: ...}). `) +
1178
+ `The engine reported: ${String(top.error)}.`);
1179
+ }
1180
+ const reason = revertReason(top.returnValue);
1181
+ // The LEADING CLAUSE stays `execution reverted` and the return data stays
1182
+ // on `data`, because that pair is what a client decodes (viem turns it into
1183
+ // a typed revert error and reads the reason out of the bytes) and because
1184
+ // the node flattens every engine failure into it on the read path. What is
1185
+ // added is the part only this method knows: that the failure is not a
1186
+ // shortage of gas (the branch above owns that case), so there is no number
1187
+ // to report.
1188
+ throw new RpcError(3, `execution reverted: the transaction fails at EVERY gas limit up to ${cap}, ` +
1189
+ `so there is no limit that would make it succeed and no estimate to report. ` +
1190
+ (reason !== undefined
1191
+ ? `Revert reason: ${reason}. `
1192
+ : top.returnValue.length > 0
1193
+ ? `It reverted with data (see \`data\`), which is not a standard Error(string). `
1194
+ : `It returned no revert data. `) +
1195
+ `The engine reported: ${String(top.error)}.`, hex(top.returnValue));
1196
+ }
1197
+ // 2) WHAT IT CONSUMED, and the probe that tests whether consumption is also a
1198
+ // workable limit. `consumed >= cap` means the request needs everything the
1199
+ // cap allows, and the cap has just been proven to work, so it IS the answer.
1200
+ const consumed = top.executionGasUsed + overhead;
1201
+ if (consumed >= cap)
1202
+ return cap;
1203
+ if (!(await probe(consumed)).error)
1204
+ return consumed;
1205
+ // 3) THE SEARCH, in two phases. `low` FAILS and `high` SUCCEEDS at every
1206
+ // point, so `high` is at all times a limit this transaction has been PROVEN
1207
+ // to succeed at — including when the probe budget runs out mid-search.
1208
+ let low = consumed;
1209
+ let high = cap;
1210
+ let probes = 0n;
1211
+ // PHASE 1 — BRACKET THE ANSWER FROM BELOW, at the scale of the rule that
1212
+ // causes the gap. A frame that hands 63/64 of its gas to a sub-call is short
1213
+ // by about 1/64 of what it held, and by about another 1/64 per nesting level
1214
+ // below that, so the first candidate above the measured consumption is
1215
+ // `low + low/64` and the step DOUBLES until it brackets the answer. Starting
1216
+ // at the top of the window instead (a plain bisection of `consumption`..`the
1217
+ // block gas limit`) means executing the request at 15,000,000 gas to learn
1218
+ // what a probe 3,000 gas above consumption would have said.
1219
+ let step = low / 64n;
1220
+ if (step < 1n)
1221
+ step = 1n;
1222
+ while (probes < MAX_ESTIMATE_PROBES && low + step < high) {
1223
+ const candidate = low + step;
1224
+ probes++;
1225
+ if ((await probe(candidate)).error) {
1226
+ low = candidate;
1227
+ step *= 2n;
1228
+ }
1229
+ else {
1230
+ high = candidate;
1231
+ break;
1232
+ }
1233
+ }
1234
+ // PHASE 2 — BISECT WHAT PHASE 1 BRACKETED, which is the ordinary binary
1235
+ // search and the only part that can make the answer EXACT.
1236
+ while (probes < MAX_ESTIMATE_PROBES && low + 1n < high) {
1237
+ const mid = low + (high - low) / 2n;
1238
+ probes++;
1239
+ if ((await probe(mid)).error)
1240
+ low = mid;
1241
+ else
1242
+ high = mid;
1243
+ }
1244
+ return high;
1245
+ }
1246
+ // ---------- the EIP-1193 dispatcher ----------
1247
+ async function request(args) {
1248
+ const params = (args.params ?? []);
1249
+ switch (args.method) {
1250
+ case 'eth_chainId':
1251
+ return numHex(chainId);
1252
+ case 'net_version':
1253
+ return String(chainId);
1254
+ case 'eth_blockNumber':
1255
+ return numHex(latestNumber);
1256
+ case 'eth_getBlockByNumber': {
1257
+ const sb = blockStore.get(resolveBlockTag(params[0]));
1258
+ return sb ? blockToRpc(sb, Boolean(params[1])) : null;
1259
+ }
1260
+ case 'eth_getBlockByHash': {
1261
+ const num = blockByHash.get(String(params[0]).toLowerCase());
1262
+ const sb = num != null ? blockStore.get(num) : undefined;
1263
+ return sb ? blockToRpc(sb, Boolean(params[1])) : null;
1264
+ }
1265
+ case 'eth_call': {
1266
+ const r = await evmCall(params[0] ?? {});
1267
+ if (r.error)
1268
+ throw new RpcError(3, 'execution reverted', hex(r.returnValue));
1269
+ return hex(r.returnValue);
1270
+ }
1271
+ case 'eth_estimateGas':
1272
+ // THE SMALLEST GAS LIMIT AT WHICH THIS REQUEST SUCCEEDS, found by
1273
+ // re-executing it. The whole method is {@link estimateGas} above,
1274
+ // including why it is a search rather than the run-and-measure it used to
1275
+ // be, and where the request's EIP-2930 access list is charged.
1276
+ return numHex(await estimateGas(params[0] ?? {}));
1277
+ case 'eth_fillTransaction': {
1278
+ // Fill the missing fields of a tx request and return {tx, raw} like geth
1279
+ // does (the `raw` is the UNSIGNED serialization — the node has no keys; a
1280
+ // client signs client-side). viem's prepareTransactionRequest probes this
1281
+ // to fill nonce/gas/fees in one round-trip; it reads the filled fields off
1282
+ // `tx` and re-signs itself, so an unsigned `raw` is correct here.
1283
+ const p = params[0] ?? {};
1284
+ const from = p.from
1285
+ ? createAddressFromString(p.from)
1286
+ : createAddressFromString('0x0000000000000000000000000000000000000000');
1287
+ const acc = await sm.getAccount(from);
1288
+ const nonce = p.nonce != null ? BigInt(p.nonce) : (acc?.nonce ?? 0n);
1289
+ const value = p.value != null ? BigInt(p.value) : 0n;
1290
+ const dataHex = p.data ?? p.input ?? '0x';
1291
+ const isCreate = !p.to;
1292
+ // Gas: the SAME search `eth_estimateGas` runs, unless the caller fixed it.
1293
+ // It has to be the same one: what this method fills is a gas LIMIT, and a
1294
+ // limit equal to measured consumption starves a sub-call under EIP-150's
1295
+ // 63/64 rule exactly as it does there (see {@link estimateGas}).
1296
+ //
1297
+ // WITH THE ACCESS LIST DELIBERATELY DROPPED, which is this method's one
1298
+ // documented difference and is unchanged: the transaction it FILLS AND
1299
+ // RETURNS carries no access list (it builds a type-0 or type-2 envelope
1300
+ // and drops the field), so charging for a list its own answer does not
1301
+ // contain would hand back a gas limit for a different transaction. See
1302
+ // `accessListGas` in ./intrinsic-gas.ts.
1303
+ const gas = p.gas != null
1304
+ ? BigInt(p.gas)
1305
+ : await estimateGas({ ...p, gas: undefined, accessList: undefined });
1306
+ // Fee fields: legacy iff caller passed gasPrice (and no 1559 fields),
1307
+ // otherwise EIP-1559 with the node's constant fee market.
1308
+ const isLegacy = p.gasPrice != null &&
1309
+ p.maxFeePerGas == null &&
1310
+ p.maxPriorityFeePerGas == null;
1311
+ const type = isLegacy ? 0 : 2;
1312
+ const txData = {
1313
+ nonce,
1314
+ gasLimit: gas,
1315
+ value,
1316
+ data: hexToBytes(dataHex.startsWith('0x') ? dataHex : '0x' + dataHex),
1317
+ to: p.to ?? undefined,
1318
+ type,
1319
+ };
1320
+ if (isLegacy) {
1321
+ txData.gasPrice = p.gasPrice != null ? BigInt(p.gasPrice) : gasPrice;
1322
+ }
1323
+ else {
1324
+ txData.maxFeePerGas =
1325
+ p.maxFeePerGas != null
1326
+ ? BigInt(p.maxFeePerGas)
1327
+ : baseFeePerGas + maxPriorityFeePerGas;
1328
+ txData.maxPriorityFeePerGas =
1329
+ p.maxPriorityFeePerGas != null
1330
+ ? BigInt(p.maxPriorityFeePerGas)
1331
+ : maxPriorityFeePerGas;
1332
+ txData.chainId = chainId;
1333
+ }
1334
+ const unsigned = createTx(txData, { common });
1335
+ // Build the RPC transaction object viem reads its filled fields off of.
1336
+ const tx = {
1337
+ from: from.toString(),
1338
+ to: p.to ?? null,
1339
+ nonce: numHex(nonce),
1340
+ gas: numHex(gas),
1341
+ value: numHex(value),
1342
+ input: hex(txData.data),
1343
+ type: numHex(type),
1344
+ chainId: numHex(chainId),
1345
+ gasPrice: isLegacy ? numHex(txData.gasPrice) : null,
1346
+ maxFeePerGas: isLegacy ? null : numHex(txData.maxFeePerGas),
1347
+ maxPriorityFeePerGas: isLegacy
1348
+ ? null
1349
+ : numHex(txData.maxPriorityFeePerGas),
1350
+ // placeholders viem deletes from the formatted tx (blockHash etc.)
1351
+ hash: ZERO_HASH,
1352
+ blockHash: null,
1353
+ blockNumber: null,
1354
+ transactionIndex: null,
1355
+ v: '0x0',
1356
+ r: ZERO_HASH,
1357
+ s: ZERO_HASH,
1358
+ };
1359
+ return { raw: hex(unsigned.serialize()), tx };
1360
+ }
1361
+ case 'eth_getBalance': {
1362
+ const acc = await sm.getAccount(createAddressFromString(params[0]));
1363
+ return numHex(acc?.balance ?? 0n);
1364
+ }
1365
+ case 'eth_getTransactionCount': {
1366
+ const acc = await sm.getAccount(createAddressFromString(params[0]));
1367
+ return numHex(acc?.nonce ?? 0n);
1368
+ }
1369
+ case 'eth_getCode': {
1370
+ const code = await sm.getCode(createAddressFromString(params[0]));
1371
+ return hex(code);
1372
+ }
1373
+ case 'eth_getStorageAt': {
1374
+ const addr = createAddressFromString(params[0]);
1375
+ const slot = setLengthLeft(bigIntToBytes(BigInt(params[1])), 32);
1376
+ const val = await sm.getStorage(addr, slot);
1377
+ return hex(setLengthLeft(val, 32));
1378
+ }
1379
+ // ---- Runtime state cheats (anvil/hardhat-style; for tests/local tooling) ----
1380
+ // These MUTATE state directly (no tx). Honest about being non-standard: they
1381
+ // are `evm_*`-namespaced. In trie mode each commits into the trie so the next
1382
+ // getStateRoot() reflects the change.
1383
+ case 'evm_setBalance': {
1384
+ // params: [address, valueHex]
1385
+ const addr = createAddressFromString(params[0]);
1386
+ await mutateAccount(addr, (acc) => {
1387
+ acc.balance = BigInt(params[1]);
1388
+ });
1389
+ return true;
1390
+ }
1391
+ case 'evm_setNonce': {
1392
+ // params: [address, nonceHex]
1393
+ const addr = createAddressFromString(params[0]);
1394
+ await mutateAccount(addr, (acc) => {
1395
+ acc.nonce = BigInt(params[1]);
1396
+ });
1397
+ return true;
1398
+ }
1399
+ case 'evm_setCode': {
1400
+ // params: [address, codeHex]
1401
+ const addr = createAddressFromString(params[0]);
1402
+ await sm.putCode(addr, hexToBytes(params[1]));
1403
+ touchedAccounts.add(addr.toString());
1404
+ await commitIfTrie();
1405
+ return true;
1406
+ }
1407
+ case 'evm_setStorageAt': {
1408
+ // params: [address, slotHex, valueHex(32-byte)]
1409
+ const addr = createAddressFromString(params[0]);
1410
+ const slot = setLengthLeft(bigIntToBytes(BigInt(params[1])), 32);
1411
+ await sm.putStorage(addr, slot, setLengthLeft(hexToBytes(params[2]), 32));
1412
+ touchedAccounts.add(addr.toString());
1413
+ await commitIfTrie();
1414
+ return true;
1415
+ }
1416
+ case 'evm_setAccount': {
1417
+ // params: [address, {balance?, nonce?, code?, storage?}] — set all at once.
1418
+ const addr = createAddressFromString(params[0]);
1419
+ const a = params[1] ?? {};
1420
+ await mutateAccount(addr, (acc) => {
1421
+ if (a.balance != null)
1422
+ acc.balance = BigInt(a.balance);
1423
+ if (a.nonce != null)
1424
+ acc.nonce = BigInt(a.nonce);
1425
+ });
1426
+ if (a.code != null && a.code !== '0x')
1427
+ await sm.putCode(addr, hexToBytes(a.code));
1428
+ for (const [slot, val] of Object.entries(a.storage ?? {})) {
1429
+ await sm.putStorage(addr, setLengthLeft(bigIntToBytes(BigInt(slot)), 32), setLengthLeft(hexToBytes(val), 32));
1430
+ }
1431
+ await commitIfTrie();
1432
+ return true;
1433
+ }
1434
+ case 'eth_gasPrice':
1435
+ return numHex(gasPrice);
1436
+ case 'eth_maxPriorityFeePerGas':
1437
+ return numHex(maxPriorityFeePerGas);
1438
+ case 'eth_feeHistory': {
1439
+ const count = Number(BigInt(params[0] ?? '0x1'));
1440
+ // `reward` must carry ONE entry per requested percentile, per block. Returning a
1441
+ // single entry regardless of `rewardPercentiles` breaks any caller that asks for
1442
+ // several and indexes them: rocketh requests [10, 50, 80] and reads index 1 and 2,
1443
+ // which came back `undefined` and blew up as "Cannot mix BigInt and other types"
1444
+ // far from here. This node has a flat fee model, so every percentile is the same
1445
+ // value - but the SHAPE has to match the request.
1446
+ const percentiles = Array.isArray(params[2]) ? params[2] : [];
1447
+ const rewardPerBlock = (percentiles.length > 0 ? percentiles : [50]).map(() => numHex(maxPriorityFeePerGas));
1448
+ return {
1449
+ oldestBlock: numHex(Math.max(0, latestNumber - count + 1)),
1450
+ baseFeePerGas: Array.from({ length: count + 1 }, () => numHex(baseFeePerGas)),
1451
+ gasUsedRatio: Array.from({ length: count }, () => 0.5),
1452
+ reward: Array.from({ length: count }, () => rewardPerBlock),
1453
+ };
1454
+ }
1455
+ case 'eth_sendRawTransaction': {
1456
+ return submit(parseTx(params[0]), false);
1457
+ }
1458
+ case 'eth_sendRawTransactionSync': {
1459
+ // The fast path: send + mine + return receipt in ONE call. Default
1460
+ // behaviour pairs with auto mining (no receipt polling = the latency win).
1461
+ return submit(parseTx(params[0]), true);
1462
+ }
1463
+ // ---- Trusted-sender variants (senderMode:'trusted' ONLY) ----
1464
+ // Same as the eth_* pair above but take an explicit `from` and SKIP
1465
+ // ecrecover. `evm_`-namespaced because they are a cheat, not a standard
1466
+ // method: the signature on the wire is never verified.
1467
+ case 'evm_sendRawTransactionAs': {
1468
+ return submit(parseTx(params[0], params[1]), false);
1469
+ }
1470
+ case 'evm_sendRawTransactionSyncAs': {
1471
+ return submit(parseTx(params[0], params[1]), true);
1472
+ }
1473
+ case 'eth_getTransactionReceipt': {
1474
+ const r = receipts.get(String(params[0]).toLowerCase());
1475
+ return r ? receiptToRpc(r) : null;
1476
+ }
1477
+ case 'eth_getTransactionByHash': {
1478
+ const t = transactions.get(String(params[0]).toLowerCase());
1479
+ return t ? txToRpc(t) : null;
1480
+ }
1481
+ case 'eth_getLogs': {
1482
+ // PERF NOTE: this does a full linear scan + filter over `allLogs` (every
1483
+ // log ever emitted) on EVERY call — O(total_logs) per query, recomputed
1484
+ // each time, no index/cache. `allLogs` is appended in block order. For a
1485
+ // local chain this is fine (in-memory, sub-ms for thousands of logs); it
1486
+ // only matters for a long-lived session with huge log counts + frequent
1487
+ // polling. An optional index (block-range pre-slice / address / topic0)
1488
+ // is deferred — see tasks/slim-node-eth-getlogs-index.md. Keep this scan as
1489
+ // the authoritative semantics if/when an index is added.
1490
+ const f = params[0] ?? {};
1491
+ const from = f.fromBlock != null ? resolveBlockTag(f.fromBlock) : 0;
1492
+ const to = f.toBlock != null ? resolveBlockTag(f.toBlock) : latestNumber;
1493
+ const addrFilter = f.address
1494
+ ? (Array.isArray(f.address) ? f.address : [f.address]).map((a) => a.toLowerCase())
1495
+ : null;
1496
+ const topics = f.topics ?? [];
1497
+ const out = allLogs.filter((l) => {
1498
+ if (l.blockNumber < from || l.blockNumber > to)
1499
+ return false;
1500
+ if (addrFilter && !addrFilter.includes(l.address.toLowerCase()))
1501
+ return false;
1502
+ for (let i = 0; i < topics.length; i++) {
1503
+ const want = topics[i];
1504
+ if (want == null)
1505
+ continue;
1506
+ const have = l.topics[i];
1507
+ if (have == null)
1508
+ return false;
1509
+ if (Array.isArray(want)) {
1510
+ if (!want.map((w) => w.toLowerCase()).includes(have.toLowerCase()))
1511
+ return false;
1512
+ }
1513
+ else if (want.toLowerCase() !== have.toLowerCase())
1514
+ return false;
1515
+ }
1516
+ return true;
1517
+ });
1518
+ return out.map(logToRpc);
1519
+ }
1520
+ case 'eth_subscribe': {
1521
+ if (params[0] !== 'newHeads')
1522
+ throw new RpcError(-32601, `subscription type not supported: ${params[0]}`);
1523
+ // Return an id; consumers using comlink should prefer onNewHead callback.
1524
+ const id = '0x' + Math.floor(Math.random() * 2 ** 48).toString(16);
1525
+ return id;
1526
+ }
1527
+ case 'eth_unsubscribe':
1528
+ return true;
1529
+ // ---- account/signing methods are intentionally NOT here ----
1530
+ case 'eth_sendTransaction':
1531
+ case 'eth_accounts':
1532
+ case 'eth_sign':
1533
+ case 'eth_signTransaction':
1534
+ case 'personal_sign':
1535
+ case 'personal_unlockAccount':
1536
+ case 'wallet_addEthereumChain':
1537
+ case 'wallet_switchEthereumChain':
1538
+ throw new RpcError(-32601, `method not supported (execution-only node — sign client-side and use eth_sendRawTransaction): ${args.method}`);
1539
+ default:
1540
+ throw new RpcError(-32601, `method not found: ${args.method}`);
1541
+ }
1542
+ }
1543
+ // ---------- dump / load ----------
1544
+ async function dumpState() {
1545
+ const accounts = {};
1546
+ const code = {};
1547
+ const storage = {};
1548
+ if (stateMode === 'trie') {
1549
+ // Trie mode dumps accounts + code via the touched-account set. NOTE: it does
1550
+ // NOT dump contract STORAGE — the EVM journals storage on an internal
1551
+ // shallowCopy of the state manager that bypasses any interception, and the
1552
+ // trie's own dumpStorage exposes only keccak-HASHED slot keys (not the raw
1553
+ // slots loadState needs). Full-storage persistence is a 'none'-mode feature
1554
+ // (where the live Map IS the committed state). Trie mode is for the REAL
1555
+ // state root (conformance block roots), not for IndexedDB persist.
1556
+ for (const addr of touchedAccounts) {
1557
+ const address = createAddressFromString(addr);
1558
+ const acc = await sm.getAccount(address);
1559
+ if (acc === undefined)
1560
+ continue;
1561
+ accounts[addr] = hex(acc.serialize());
1562
+ const c = await sm.getCode(address);
1563
+ if (c.length > 0)
1564
+ code[addr] = hex(c);
1565
+ }
1566
+ }
1567
+ else {
1568
+ // 'none' mode: the account and code stacks are still plain Maps whose TOP
1569
+ // frame is the live set, and storage is per-account with per-checkpoint
1570
+ // OVERLAYS, flattened by liveStorage(). Dump both directly (no trie walk).
1571
+ //
1572
+ // THE SERIALISED FORMAT IS NOT THE INTERNAL LAYOUT and must not follow it:
1573
+ // this output is persisted data (IndexedDB, loadState fixtures) with existing
1574
+ // state behind it. It stays `{address: {slot: value}}` in 0x-hex, and
1575
+ // `test/storage-overlay.spec.ts` asserts it byte-identical to a dump taken
1576
+ // from the pre-overlay flat layout.
1577
+ const live = sm;
1578
+ const accMap = live.accountStack[live.accountStack.length - 1];
1579
+ const codeMap = live.codeStack[live.codeStack.length - 1];
1580
+ for (const [addr, acc] of accMap) {
1581
+ if (acc !== undefined)
1582
+ accounts[addr] = hex(acc.serialize());
1583
+ }
1584
+ for (const [addr, c] of codeMap)
1585
+ code[addr] = hex(c);
1586
+ for (const [addr, slots] of live.liveStorage()) {
1587
+ for (const [slot, val] of slots)
1588
+ (storage[addr] ??= {})[slot] = hex(val);
1589
+ }
1590
+ }
1591
+ const blocks = [];
1592
+ for (let i = 0; i <= latestNumber; i++) {
1593
+ const sb = blockStore.get(i);
1594
+ if (sb)
1595
+ blocks.push(sb.header);
1596
+ }
1597
+ return {
1598
+ version: 1,
1599
+ chainId,
1600
+ stateMode,
1601
+ accounts,
1602
+ code,
1603
+ storage,
1604
+ blocks,
1605
+ receipts: Object.fromEntries(receipts),
1606
+ transactions: Object.fromEntries(transactions),
1607
+ };
1608
+ }
1609
+ async function loadState(state) {
1610
+ // Rehydrate accounts/code/storage directly into SimpleStateManager.
1611
+ for (const [addr, accHex] of Object.entries(state.accounts)) {
1612
+ const acc = createAccountFromRLP(hexToBytes(accHex));
1613
+ await sm.putAccount(createAddressFromString(addr), acc);
1614
+ }
1615
+ for (const [addr, c] of Object.entries(state.code)) {
1616
+ await sm.putCode(createAddressFromString(addr), hexToBytes(c));
1617
+ }
1618
+ for (const [addr, slots] of Object.entries(state.storage)) {
1619
+ for (const [slot, val] of Object.entries(slots)) {
1620
+ await sm.putStorage(createAddressFromString(addr), hexToBytes(slot), hexToBytes(val));
1621
+ }
1622
+ }
1623
+ // Rebuild block list / receipts / tx / logs index.
1624
+ receipts.clear();
1625
+ transactions.clear();
1626
+ blockStore.clear();
1627
+ blockByHash.clear();
1628
+ allLogs = [];
1629
+ for (const [h, r] of Object.entries(state.receipts))
1630
+ receipts.set(h, r);
1631
+ for (const [h, t] of Object.entries(state.transactions))
1632
+ transactions.set(h, t);
1633
+ for (const sh of state.blocks) {
1634
+ // THE REBUILT BLOCK CARRIES THE COINBASE AND THE MIXHASH, because it is not
1635
+ // only the RPC that reads it: `eth_call` executes against the STORED `Block`
1636
+ // object of the latest block, so a reconstruction that dropped them would
1637
+ // hand a contract a zero COINBASE / PREVRANDAO after a reload while the same
1638
+ // node's mined blocks used the configured ones. `difficulty` is pinned to 0
1639
+ // here for the same reason it is pinned when mining: post-Merge, PREVRANDAO
1640
+ // lives in `mixHash` and the difficulty must be zero beside it.
1641
+ //
1642
+ // AND ITS OWN HASH HAS TO COME OUT RIGHT, which is the second thing this
1643
+ // list is load-bearing for and the easier one to break. `parentHash` for the
1644
+ // next mined block is taken from THIS object's `hash()` (below), and the
1645
+ // default engine answers BLOCKHASH from it through `mockBlockchain`, so the
1646
+ // header built here must be field-for-field the one `storeBlock` recorded or
1647
+ // a reloaded chain names a parent no lookup resolves. That is an INVARIANT
1648
+ // between three places, not a local property: a header field added to the
1649
+ // mined block in `executeAndMine` has to be recorded in `SerializedBlock` and
1650
+ // restored here, or the hash silently diverges on the far side of a reload.
1651
+ // `test/rpc-block.spec.ts` mines a block after a reload and checks its parent
1652
+ // resolves, which is that invariant stated where a consumer would meet it.
1653
+ const block = createBlock({
1654
+ header: {
1655
+ number: BigInt(sh.number),
1656
+ gasLimit: BigInt(sh.gasLimit),
1657
+ gasUsed: BigInt(sh.gasUsed),
1658
+ baseFeePerGas: BigInt(sh.baseFeePerGas),
1659
+ parentHash: hexToBytes(sh.parentHash),
1660
+ timestamp: BigInt(sh.timestamp),
1661
+ ...(sh.miner ? { coinbase: createAddressFromString(sh.miner) } : {}),
1662
+ difficulty: 0n,
1663
+ ...(sh.mixHash ? { mixHash: hexToBytes(sh.mixHash) } : {}),
1664
+ },
1665
+ }, { common });
1666
+ // Collect this block's logs from receipts (preserves order).
1667
+ const logs = [];
1668
+ for (const th of sh.transactions) {
1669
+ const r = receipts.get(th);
1670
+ if (r)
1671
+ logs.push(...r.logs);
1672
+ }
1673
+ // A dump from before `SerializedBlock` had a bloom gets one REBUILT rather
1674
+ // than defaulted to zero: its receipts carry their own blooms, so the block
1675
+ // bloom is derivable, and an old state that pre-filtered to nothing would be
1676
+ // the very defect this field was added to close.
1677
+ const header = sh.logsBloom === undefined
1678
+ ? { ...sh, logsBloom: bloomOfReceipts(sh.transactions) }
1679
+ : sh;
1680
+ blockStore.set(sh.number, { block, header, logs });
1681
+ blockByHash.set(sh.hash, sh.number);
1682
+ allLogs.push(...logs);
1683
+ latestNumber = sh.number;
1684
+ parentHash = block.hash();
1685
+ }
1686
+ }
1687
+ // ---------- persistence auto-load on creation ----------
1688
+ if (options.persistence) {
1689
+ const saved = await options.persistence.load();
1690
+ if (saved && saved.chainId === chainId)
1691
+ await loadState(saved);
1692
+ }
1693
+ async function persistIfNeeded() {
1694
+ if (options.persistence)
1695
+ await options.persistence.save(await dumpState());
1696
+ }
1697
+ // wrap mine() to persist
1698
+ async function mine() {
1699
+ const r = await mineBlock();
1700
+ await persistIfNeeded();
1701
+ return r;
1702
+ }
1703
+ // wrap request so state-changing methods persist after mining
1704
+ const baseRequest = request;
1705
+ async function persistingRequest(args) {
1706
+ const out = await baseRequest(args);
1707
+ if ((args.method === 'eth_sendRawTransaction' ||
1708
+ args.method === 'eth_sendRawTransactionSync' ||
1709
+ args.method === 'evm_sendRawTransactionAs' ||
1710
+ args.method === 'evm_sendRawTransactionSyncAs') &&
1711
+ miningConfig.type === 'auto') {
1712
+ await persistIfNeeded();
1713
+ }
1714
+ return out;
1715
+ }
1716
+ return {
1717
+ request: persistingRequest,
1718
+ mine,
1719
+ dumpState,
1720
+ loadState,
1721
+ stateMode,
1722
+ senderMode,
1723
+ // Identity only: the engine object itself stays internal, so the reading is a
1724
+ // plain value that survives a Worker/comlink boundary unchanged.
1725
+ engine: { id: engine.id },
1726
+ async getStateRoot() {
1727
+ if (stateMode !== 'trie') {
1728
+ throw new RpcError(-32004, "no state root in 'none' mode — create the node with stateMode:'trie' for a real Merkle-Patricia root");
1729
+ }
1730
+ return currentStateRoot();
1731
+ },
1732
+ onNewHead(cb) {
1733
+ headSubs.add(cb);
1734
+ return () => headSubs.delete(cb);
1735
+ },
1736
+ async dispose() {
1737
+ if (intervalTimer)
1738
+ clearInterval(intervalTimer);
1739
+ headSubs.clear();
1740
+ },
1741
+ };
1742
+ }
1743
+ //# sourceMappingURL=node.js.map