webevm 0.0.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +693 -0
  3. package/dist/engine.d.ts +69 -0
  4. package/dist/engine.d.ts.map +1 -0
  5. package/dist/engine.js +269 -0
  6. package/dist/engine.js.map +1 -0
  7. package/dist/index.d.ts +12 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +21 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/intrinsic-gas.d.ts +149 -0
  12. package/dist/intrinsic-gas.d.ts.map +1 -0
  13. package/dist/intrinsic-gas.js +94 -0
  14. package/dist/intrinsic-gas.js.map +1 -0
  15. package/dist/node.d.ts +3 -0
  16. package/dist/node.d.ts.map +1 -0
  17. package/dist/node.js +1931 -0
  18. package/dist/node.js.map +1 -0
  19. package/dist/persistence.d.ts +22 -0
  20. package/dist/persistence.d.ts.map +1 -0
  21. package/dist/persistence.js +54 -0
  22. package/dist/persistence.js.map +1 -0
  23. package/dist/revm-state-store.d.ts +89 -0
  24. package/dist/revm-state-store.d.ts.map +1 -0
  25. package/dist/revm-state-store.js +394 -0
  26. package/dist/revm-state-store.js.map +1 -0
  27. package/dist/revm.d.ts +124 -0
  28. package/dist/revm.d.ts.map +1 -0
  29. package/dist/revm.js +657 -0
  30. package/dist/revm.js.map +1 -0
  31. package/dist/sender-recovery.d.ts +78 -0
  32. package/dist/sender-recovery.d.ts.map +1 -0
  33. package/dist/sender-recovery.js +53 -0
  34. package/dist/sender-recovery.js.map +1 -0
  35. package/dist/state-manager.d.ts +327 -0
  36. package/dist/state-manager.d.ts.map +1 -0
  37. package/dist/state-manager.js +439 -0
  38. package/dist/state-manager.js.map +1 -0
  39. package/dist/storage-keys.d.ts +21 -0
  40. package/dist/storage-keys.d.ts.map +1 -0
  41. package/dist/storage-keys.js +113 -0
  42. package/dist/storage-keys.js.map +1 -0
  43. package/dist/types.d.ts +696 -0
  44. package/dist/types.d.ts.map +1 -0
  45. package/dist/types.js +12 -0
  46. package/dist/types.js.map +1 -0
  47. package/dist/worker-client.d.ts +21 -0
  48. package/dist/worker-client.d.ts.map +1 -0
  49. package/dist/worker-client.js +77 -0
  50. package/dist/worker-client.js.map +1 -0
  51. package/dist/worker-entry.d.ts +32 -0
  52. package/dist/worker-entry.d.ts.map +1 -0
  53. package/dist/worker-entry.js +29 -0
  54. package/dist/worker-entry.js.map +1 -0
  55. package/dist/worker-host.d.ts +75 -0
  56. package/dist/worker-host.d.ts.map +1 -0
  57. package/dist/worker-host.js +188 -0
  58. package/dist/worker-host.js.map +1 -0
  59. package/package.json +90 -2
  60. package/src/engine.ts +300 -0
  61. package/src/index.ts +46 -0
  62. package/src/intrinsic-gas.ts +191 -0
  63. package/src/node.ts +2150 -0
  64. package/src/persistence.ts +80 -0
  65. package/src/revm-state-store.ts +455 -0
  66. package/src/revm.ts +809 -0
  67. package/src/sender-recovery.ts +142 -0
  68. package/src/state-manager.ts +531 -0
  69. package/src/storage-keys.ts +150 -0
  70. package/src/types.ts +717 -0
  71. package/src/worker-client.ts +112 -0
  72. package/src/worker-entry.ts +31 -0
  73. package/src/worker-host.ts +232 -0
package/src/revm.ts ADDED
@@ -0,0 +1,809 @@
1
+ /**
2
+ * revm.ts — `webevm/revm`: the node's EVM, backed by `revm-wasm`.
3
+ *
4
+ * ```ts
5
+ * import {createNode} from 'webevm';
6
+ * import {createRevmEngine} from 'webevm/revm';
7
+ * import {wasmUrl} from 'revm-wasm/wasm-url'; // bundler-resolved asset
8
+ *
9
+ * const node = await createNode({engine: await createRevmEngine({wasm: wasmUrl})});
10
+ * ```
11
+ *
12
+ * OPT-IN, AND IN ITS OWN ENTRY POINT. The core never imports this module, so a
13
+ * consumer who does not import it ships no revm (ADR 0006, and the bundle-size
14
+ * assertion in `packages/benchmarks/test/evm.spec.ts` enforces it). `revm-wasm`
15
+ * is nevertheless a plain `dependency`: a JS-only consumer pays install bytes
16
+ * and ZERO bundle bytes.
17
+ *
18
+ * BOTH HALVES OF THE SEAM. `call` serves `eth_call`, `eth_estimateGas` and
19
+ * `eth_fillTransaction`'s estimation; `transact` executes a signed transaction
20
+ * AND COMMITS it, which is the node's mining path. They are asymmetric in ONE
21
+ * respect and it is a transaction's VALIDITY: `call` relaxes base fee, block gas
22
+ * limit and EIP-3607 because a simulation is not a transaction, and `transact`
23
+ * relaxes NOTHING — `revm-wasm` refuses to combine any of those switches with
24
+ * committing, so the asymmetry is enforced by the binding rather than merely
25
+ * intended. `Revm#call` is additionally incapable of committing whatever its
26
+ * options say, so a read needs neither the checkpoint/revert nor the EIP-2929
27
+ * reset the default `@ethereumjs/evm` engine pays for.
28
+ *
29
+ * WASM DELIVERY IS ONE CODE PATH. `revm-wasm` accepts bytes, a `URL`, a string,
30
+ * a `Response` or an already-compiled `WebAssembly.Module`, so whatever the
31
+ * caller has (a bundler-resolved asset, a URL fetched at runtime, a module
32
+ * compiled once and reused) is passed straight through. NOTE FOR NODE: the
33
+ * `revm-wasm/wasm-url` export is a `file:` URL, and Node's `fetch` cannot
34
+ * resolve that scheme — in Node, read the bytes first
35
+ * (`readFileSync(fileURLToPath(wasmUrl))`) and pass those. In a browser the URL
36
+ * works as-is.
37
+ *
38
+ * WHAT IT COSTS. State is read AND WRITTEN through `SimpleStateManager`'s public
39
+ * checkpoint stacks plus the node's own storage overlays (see
40
+ * ./revm-state-store.ts, ADR 0005 for the reach-through and ADR 0010 for the
41
+ * ownership decision), which is the only synchronous view of the node's state
42
+ * that exists — so this engine serves `stateMode:'none'` ONLY, and refuses
43
+ * `'trie'` at construction rather than at the first opcode. THE NODE KEEPS
44
+ * OWNING STATE: nothing is copied into wasm, and a transaction writes back only
45
+ * the accounts it touched and the slots that changed.
46
+ *
47
+ * AND WHICH FORKS. It serves the hardforks whose transaction costing the node's
48
+ * own arithmetic reproduces AND the PROTOCOL agrees with
49
+ * (`REVM_SPEC_BY_HARDFORK` — Berlin through Cancun today), and refuses the rest
50
+ * BY NAME at construction (`REVM_REFUSED_HARDFORKS`): Prague and Osaka, because
51
+ * `./intrinsic-gas.ts` does not compute the EIP-7623 calldata floor that revm
52
+ * enforces. See ADR 0008.
53
+ */
54
+ import type {Common} from '@ethereumjs/common';
55
+ import type {Block} from '@ethereumjs/block';
56
+ import {bigIntToBytes, equalsBytes, generateAddress} from '@ethereumjs/util';
57
+ import type {OverlayStorageStateManager} from './state-manager.js';
58
+ import {createRevm, type SpecName, type WasmSource} from 'revm-wasm';
59
+ import type {BlockEnv, ExecuteOptions, Outcome, Revm} from 'revm-wasm';
60
+ import {intrinsicGas} from './intrinsic-gas.js';
61
+ import {SimpleStateManagerStore} from './revm-state-store.js';
62
+ import type {
63
+ Engine,
64
+ EngineContext,
65
+ ReadCallRequest,
66
+ ReadCallResult,
67
+ TransactionRequest,
68
+ TransactionResult,
69
+ } from './types.js';
70
+
71
+ /** This engine's stable identifier, as reported by `node.engine.id`. */
72
+ export const REVM_ENGINE_ID = 'revm-wasm';
73
+
74
+ export interface RevmEngineOptions {
75
+ /**
76
+ * The `revm-wasm` module: bytes, a `URL`, a string URL, a `Response`, or an
77
+ * already-compiled `WebAssembly.Module` (the one to prefer when several nodes
78
+ * share one compilation). Passed through to `revm-wasm` untouched.
79
+ */
80
+ wasm: WasmSource;
81
+ }
82
+
83
+ /**
84
+ * ethereumjs hardfork name -> revm spec: the hardforks this engine ADMITS.
85
+ *
86
+ * The node runs Cancun today and nothing here can change that, so this table is
87
+ * a GUARD rather than a feature: if the node's hardfork ever moves, an engine
88
+ * that silently kept running Cancun rules would charge different gas from the
89
+ * default engine and nothing would say so.
90
+ *
91
+ * WHAT MAKES A FORK ADMISSIBLE is not that revm has a spec for it, and it is not
92
+ * that the node and revm AGREE about it either. Agreement is necessary and not
93
+ * sufficient: everything the node computes ABOUT a transaction — today the
94
+ * shared intrinsic-gas arithmetic in ./intrinsic-gas.ts, and the read budget
95
+ * assembled in `call` below — must (a) still agree with what revm ENFORCES under
96
+ * that spec, and (b) be what the PROTOCOL charges at that fork, judged by
97
+ * something that is neither of the two. Clause (b) is not decoration: the engine
98
+ * SUBTRACTS `intrinsicGas()` from what revm spent and the node adds the same
99
+ * number back, so the two sides agree about intrinsic gas by construction and a
100
+ * term that is wrong at a fork is wrong on both sides at once.
101
+ *
102
+ * Prague and Osaka fail (a). Berlin, London and Paris once failed (b) — both
103
+ * this node and `revm-wasm@0.3.0` charged EIP-3860's initcode word cost there,
104
+ * and EIP-3860 arrived in Shanghai. `revm-wasm@0.3.1` fixed its half, and
105
+ * ./intrinsic-gas.ts now gates the term on the node's `Common`, so all three are
106
+ * back.
107
+ *
108
+ * ADDING A FORK BELOW BERLIN COSTS MORE THAN A LINE HERE. ./intrinsic-gas.ts is
109
+ * protocol-correct over Istanbul..Cancun only: it hardcodes EIP-2028's 16 gas per
110
+ * non-zero calldata byte, which was 68 before Istanbul, so a pre-Istanbul entry in
111
+ * this table would make `eth_estimateGas` UNDER-estimate by 52 gas per non-zero
112
+ * byte — and a client uses an estimate as the transaction's gas limit. Anything
113
+ * in NEITHER table is refused by the unknown-fork guard in `connect` below, which
114
+ * is what keeps that unreachable today. Gate the term the way EIP-3860's is gated
115
+ * first, then move the entry; the clause-(b) assertions in
116
+ * `test/revm-engine.spec.ts` measure that boundary from both sides and will fail
117
+ * the build otherwise. See {@link REVM_REFUSED_HARDFORKS} and
118
+ * `docs/adr/0008-the-revm-engine-admits-only-hardforks-it-can-cost.md`.
119
+ * Anything not in either table is refused by name.
120
+ *
121
+ * FROZEN, AND NOT MERELY `Readonly`. The type annotation is erased at runtime, so
122
+ * until this was frozen a consumer could re-admit a refused fork with a single
123
+ * assignment through the export (`REVM_SPEC_BY_HARDFORK.prague = 'PRAGUE'`) and
124
+ * `connect` below would wave it through — an `eth_estimateGas` revm itself then
125
+ * rejects (`GasFloorMoreThanGasLimit`). A guard a stray assignment removes is
126
+ * weaker than it reads, and these tables are PUBLIC precisely so the admitted set
127
+ * can be read without provoking a throw, which is a reading surface, not an
128
+ * editing one. The freeze is shallow and that is total here: every value is a
129
+ * string. Asserted in `test/revm-engine.spec.ts` as a RUNTIME property (both
130
+ * tables frozen, a re-admitting edit leaves them unchanged, and the guard still
131
+ * refuses the fork afterwards), because a type cannot be measured.
132
+ *
133
+ * THE DECISION UNDER THAT, since the alternative was live: freezing is enough,
134
+ * and `connect` deliberately keeps reading these objects rather than a snapshot
135
+ * taken at module load. A snapshot would make the GUARD robust while leaving the
136
+ * EXPORT a lie — a consumer who assigned `prague` would read a table saying
137
+ * `prague` is served while every read of it was refused, i.e. two answers to the
138
+ * one question these exports exist to answer. It would also fork the truth in
139
+ * two: the table a reader inspects and the table the guard consults, kept in step
140
+ * by nothing. Freezing removes the divergence at its source instead of tolerating
141
+ * it, and it fails at the CONSUMER's own line (a `TypeError` under strict mode,
142
+ * a dropped write under sloppy mode) rather than silently somewhere else. If a
143
+ * later table ever has to be built at runtime rather than written literally here,
144
+ * freeze it at the end of construction; do not reach for the snapshot.
145
+ */
146
+ export const REVM_SPEC_BY_HARDFORK: Readonly<Record<string, SpecName>> =
147
+ Object.freeze({
148
+ berlin: 'BERLIN',
149
+ london: 'LONDON',
150
+ paris: 'MERGE',
151
+ shanghai: 'SHANGHAI',
152
+ cancun: 'CANCUN',
153
+ });
154
+
155
+ /**
156
+ * Hardforks revm HAS a spec for and this engine still refuses, each with the
157
+ * reason quoted verbatim in the refusal.
158
+ *
159
+ * These are the silent-wrong-answer cases. From Prague on, revm ENFORCES rules
160
+ * the node's own arithmetic does not implement, so `eth_estimateGas` could return
161
+ * a number the engine that produced it would REJECT — and viem uses that number
162
+ * as the transaction's gas limit. A loud refusal at construction is the honest
163
+ * edge (ADR 0004); a plausible estimate is not.
164
+ *
165
+ * To admit one of these, make the node's arithmetic BOTH agree with revm under
166
+ * that spec AND match the protocol at that fork: implement the missing rule in
167
+ * ./intrinsic-gas.ts and in the read budget here, then prove it against the
168
+ * engine and move the entry to {@link REVM_SPEC_BY_HARDFORK}. Note that the
169
+ * EIP-7623 floor is not a TERM of the intrinsic-gas formula but a floor on the
170
+ * transaction's total, so unlike the EIP-3860 fork gate it cannot be threaded
171
+ * through ./intrinsic-gas.ts alone — both callers have to learn about it. The
172
+ * measurements behind each line are in
173
+ * `docs/spikes/prague-intrinsic-gas-floor-or-refuse/` and
174
+ * `docs/spikes/intrinsic-gas-charges-eip-3860-on-forks-that-predate-it/` (§6 for
175
+ * the re-measurement on `revm-wasm@0.3.1`, which left both of these standing).
176
+ *
177
+ * FROZEN for the same reason as {@link REVM_SPEC_BY_HARDFORK}, where the freeze
178
+ * decision (and why the guard reads these objects rather than a load-time
179
+ * snapshot) is recorded: deleting an entry here is the other half of the
180
+ * one-assignment re-admission the freeze exists to refuse.
181
+ */
182
+ export const REVM_REFUSED_HARDFORKS: Readonly<Record<string, string>> =
183
+ Object.freeze({
184
+ prague:
185
+ `revm enforces the EIP-7623 calldata floor (a transaction pays at least ` +
186
+ `21000 + 10 gas per calldata token, tokens being 1 per zero byte and 4 per ` +
187
+ `non-zero byte) and this node's shared intrinsic-gas arithmetic ` +
188
+ `(src/intrinsic-gas.ts) computes only the pre-Prague formula, so ` +
189
+ `eth_estimateGas would return a gas limit revm itself rejects with ` +
190
+ `GasFloorMoreThanGasLimit for a calldata-heavy call — and a client uses an ` +
191
+ `estimate as the transaction's gas limit`,
192
+ osaka:
193
+ `it inherits Prague's EIP-7623 calldata floor, which src/intrinsic-gas.ts ` +
194
+ `does not compute, and adds the EIP-7825 transaction gas limit cap of ` +
195
+ `16777216, which is below the node's default read budget of 30000000 — so ` +
196
+ `an ordinary eth_call would be rejected outright with TxGasLimitGreaterThanCap`,
197
+ });
198
+
199
+ /**
200
+ * Build a revm-backed engine, serving BOTH halves of the seam: `call` for the
201
+ * node's reads and `transact` for the transactions it mines and commits (see the
202
+ * module header for how the two differ, which is validity and nothing else).
203
+ *
204
+ * The wasm is fetched and compiled HERE, so a consumer can start the download
205
+ * while the UI paints and hand the finished engine to `createNode()` afterwards.
206
+ * The engine binds to the node's state later, through the seam's
207
+ * `connect(context)` hook (ADR 0006: an injected engine exists before the node
208
+ * does, so it cannot capture anything at construction).
209
+ *
210
+ * ONE ENGINE PER NODE. The returned engine binds to the first node it is given
211
+ * to and REFUSES a second, because rebinding would silently re-point the first
212
+ * node's reads and transactions at the second node's state. To pay the wasm
213
+ * compilation only once, compile it yourself and pass the same
214
+ * `WebAssembly.Module` to each `createRevmEngine()` call — that is what the
215
+ * `wasm` option accepting a compiled module is for.
216
+ */
217
+ export async function createRevmEngine(
218
+ options: RevmEngineOptions,
219
+ ): Promise<Engine> {
220
+ // The store is created UNBOUND: `createRevm` needs its store at instantiation
221
+ // time, and the node's state manager does not exist yet. It reads nothing
222
+ // until `connect` binds it, and throws if asked to.
223
+ const store = new SimpleStateManagerStore();
224
+ const revm: Revm = await createRevm({wasm: options.wasm, state: store});
225
+
226
+ let spec: SpecName = 'CANCUN';
227
+ let chainId = 1n;
228
+ // THE NODE'S OWN `Common`, captured at connect and passed straight back into
229
+ // the shared `intrinsicGas()` below. Not a hardfork name and not a derived
230
+ // flag: `node.ts` asks the very same instance the very same question when it
231
+ // ADDS the intrinsic gas this engine SUBTRACTS, so the two halves of an
232
+ // `eth_estimateGas` cannot name different forks. See ./intrinsic-gas.ts.
233
+ // (`nodeCommon`, not `common`: inside `call` below, `common` already names the
234
+ // request fields COMMON to `revm.call` and `revm.create`.)
235
+ let nodeCommon: Common | undefined;
236
+
237
+ return {
238
+ id: REVM_ENGINE_ID,
239
+
240
+ connect(context: EngineContext): void {
241
+ // A MODE THIS ENGINE CANNOT SERVE, refused out loud and at construction.
242
+ // `MerkleStateManager` has no synchronous view of state at any depth, and
243
+ // revm's reads must be synchronous, so there is nothing to reach through
244
+ // to. A consumer who asked for revm and silently got something else would
245
+ // measure the wrong thing forever, so this throws out of `createNode()`
246
+ // rather than at the first opcode. See ADR 0005.
247
+ if (context.stateMode !== 'none') {
248
+ throw new Error(
249
+ `webevm/revm: the revm engine cannot serve stateMode:'${context.stateMode}'. ` +
250
+ `It reads the node's state SYNCHRONOUSLY through SimpleStateManager's ` +
251
+ `checkpoint stacks (stateMode:'none'), and MerkleStateManager has no ` +
252
+ `synchronous view at any depth — revm's interpreter has no suspension ` +
253
+ `point to await a trie read at. Use stateMode:'none' with this engine, ` +
254
+ `or the default @ethereumjs/evm engine with stateMode:'trie'. See ` +
255
+ `docs/adr/0005-revm-reads-the-nodes-state-through-simplestatemanagers-stacks.md.`,
256
+ );
257
+ }
258
+ // A HARDFORK THIS ENGINE CANNOT COST, refused the same way and for the same
259
+ // reason as the state mode above: revm would run it and charge rules the
260
+ // node's own arithmetic does not implement. Unreachable while the node is
261
+ // pinned to Cancun, which is the point — it fires the day that moves,
262
+ // rather than letting `eth_estimateGas` return a number this engine would
263
+ // then reject.
264
+ const hardfork = context.common.hardfork();
265
+ const refused = REVM_REFUSED_HARDFORKS[hardfork];
266
+ if (refused !== undefined) {
267
+ throw new Error(
268
+ `webevm/revm: the revm engine does not admit hardfork '${hardfork}': ` +
269
+ `${refused}. Use a hardfork this engine costs correctly ` +
270
+ `(${Object.keys(REVM_SPEC_BY_HARDFORK).join(', ')}), or the default ` +
271
+ `@ethereumjs/evm engine. See ` +
272
+ `docs/adr/0008-the-revm-engine-admits-only-hardforks-it-can-cost.md.`,
273
+ );
274
+ }
275
+ const mapped = REVM_SPEC_BY_HARDFORK[hardfork];
276
+ if (mapped === undefined) {
277
+ throw new Error(
278
+ `webevm/revm: no revm spec is known for hardfork '${hardfork}'. ` +
279
+ `Running a read on a different fork from the transactions would charge ` +
280
+ `different gas without saying so.`,
281
+ );
282
+ }
283
+ spec = mapped;
284
+ chainId = context.common.chainId();
285
+ nodeCommon = context.common;
286
+ // The one cast: `StateManagerInterface` does not declare the stacks, but
287
+ // `'none'` mode IS the node's `OverlayStorageStateManager`. Cast to the REAL
288
+ // type (never to `any`) so every field access below is still typechecked and
289
+ // a rename in `@ethereumjs/statemanager` — or in our own state manager — is a
290
+ // compile error here. `bind` also asserts the shape at runtime, which is the
291
+ // half the compiler cannot see.
292
+ store.bind(
293
+ context.stateManager as unknown as OverlayStorageStateManager,
294
+ {
295
+ blockHash: context.getBlockHash,
296
+ },
297
+ );
298
+ },
299
+
300
+ async call(request: ReadCallRequest): Promise<ReadCallResult> {
301
+ // Same shape as the store's own unbound guard (./revm-state-store.ts): an
302
+ // engine used without a node has no fork to cost against, and guessing one
303
+ // would answer with an estimate computed under rules the caller never chose.
304
+ if (nodeCommon === undefined) {
305
+ throw new Error(
306
+ 'webevm/revm: the engine was asked for a read before connect() ' +
307
+ 'bound it to a node, so it has no hardfork to compute intrinsic gas at. ' +
308
+ 'Pass the engine to createNode() before using it.',
309
+ );
310
+ }
311
+ store.beginExecution();
312
+ const isCreate = request.to === undefined;
313
+ const intrinsic = intrinsicGas(request.data, isCreate, nodeCommon);
314
+ const header = request.block.header;
315
+
316
+ // GAS BUDGETS, and why they are not the obvious mapping. The node hands an
317
+ // engine the gas available to EXECUTION (it adds intrinsic gas itself, on
318
+ // top of what the engine reports), and `@ethereumjs/evm`'s `runCall` gives
319
+ // all of it to execution because it charges no intrinsic gas. revm charges
320
+ // intrinsic out of the TRANSACTION gas limit, so the equivalent budget is
321
+ // `request.gasLimit + intrinsic`, passed WHOLE: `disableBlockGasLimit`
322
+ // below removes the block-limit check that used to force a cap here
323
+ // (`CallerGasLimitMoreThanBlock`), and with it the divergence window where
324
+ // a call needing within `intrinsic` gas of the entire block gas limit ran
325
+ // out of gas on revm and completed on the default engine.
326
+ const gasLimit = request.gasLimit + intrinsic;
327
+ const block = blockEnvOf(request.block);
328
+
329
+ const common = {
330
+ from: request.from.bytes,
331
+ data: request.data,
332
+ value: request.value,
333
+ gasLimit,
334
+ spec,
335
+ chainId,
336
+ block,
337
+ // THE SIMULATION SWITCHES, and they are the whole reason this engine can
338
+ // pass an honest block environment. Each one turns off a TRANSACTION
339
+ // validity rule that a READ is not subject to, and every real client
340
+ // turns the same ones off to serve `eth_call`:
341
+ //
342
+ // disableBaseFee the read's gas price is 0 and the block's base
343
+ // fee is not (`GasPriceLessThanBasefee`). This is
344
+ // ALSO what keeps a read from an unfunded address
345
+ // working, see `disableBalanceCheck` below;
346
+ // disableBlockGasLimit a read can be handed a gas budget EQUAL to the
347
+ // block gas limit, on any node: that is what
348
+ // `DEFAULT_READ_BUDGET` does on a default node (the
349
+ // two numbers coincide at 30,000,000, and are still
350
+ // decided apart, see src/node.ts), and an explicit
351
+ // `gas` argument does it whatever `blockGasLimit`
352
+ // is. revm then charges intrinsic gas out of the
353
+ // transaction limit while `@ethereumjs/evm`'s
354
+ // `runCall` charges none, so the equivalent budget
355
+ // is `gasLimit + intrinsic`, which is over the
356
+ // block limit by exactly `intrinsic`
357
+ // (`CallerGasLimitMoreThanBlock`). READ PATH ONLY,
358
+ // and NOT made removable by the node now enforcing
359
+ // that limit: what it enforces is a rule about a
360
+ // transaction being MINED (`transact` below, and
361
+ // `refuseIfOverBlockGasLimit` in ./node.ts ahead of
362
+ // it), and a read is not mined;
363
+ // disableEip3607 EIP-3607 rejects a caller that holds code, which
364
+ // is a rule about SENDING a transaction. Simulating
365
+ // from a contract address is ordinary practice
366
+ // (smart accounts, ERC-4337, multicall
367
+ // aggregators), and `@ethereumjs/evm`'s `runCall`
368
+ // never enforced it, so without this the two
369
+ // engines disagree about whether the call runs.
370
+ //
371
+ // THEY BELONG TO THIS METHOD AND TO NOTHING ELSE. `revm-wasm` REFUSES to
372
+ // combine any of them with committing (a committed transaction from a
373
+ // contract address is one the chain would reject), so `transact` below must
374
+ // not reach for them — and a `commit:false` simulation that copied this
375
+ // object would run a transaction with relaxed VALIDITY and no field of the
376
+ // result would show it. `test/revm-engine.spec.ts` asserts their ABSENCE on
377
+ // the transaction path rather than trusting this comment.
378
+ //
379
+ // AND THE ONE THAT IS DELIBERATELY NOT SET: `disableBalanceCheck`.
380
+ // Relaxing a TRANSACTION's validity rules must not relax the VALUE
381
+ // TRANSFER. geth's `eth_call` skips the fee checks and still fails an
382
+ // unaffordable value with `ErrInsufficientBalance`, and
383
+ // `@ethereumjs/evm` agrees (`_reduceSenderBalance` throws
384
+ // `insufficient balance`). The switch would raise the caller's balance
385
+ // to at least `value`, so a value-bearing read would succeed here and
386
+ // fail on the default engine: the same class of lie as the zeroed base
387
+ // fee, and just as invisible to a gas bar, since a rejected read charges
388
+ // no gas at all.
389
+ //
390
+ // It is not needed for the property it was taken for, and that is
391
+ // MEASURED, not assumed (probe + numbers:
392
+ // docs/spikes/revm-wasm-upgrade-honest-block-environment/). A read has no
393
+ // gas price (`ReadCallRequest` carries none, so it is 0), which reduces
394
+ // revm's demand from `gasLimit * gasPrice + value` to exactly `value`.
395
+ // A zero-value read from an address holding no ether (the node defaults
396
+ // `from` to the zero address) therefore passes the check untouched, and
397
+ // the only case the switch would change is precisely the one that must
398
+ // fail. If a gas price is ever plumbed into a read, revisit this: the
399
+ // answer is then `disableBaseFee`-style relief for the FEE half only,
400
+ // never a fabricated balance.
401
+ disableBaseFee: true,
402
+ disableBlockGasLimit: true,
403
+ disableEip3607: true,
404
+ // Logs and the post-state map are not part of a read's answer, and
405
+ // building them costs ~0.9 microseconds per call.
406
+ returnState: false,
407
+ };
408
+
409
+ // A CREATE-shaped read (`eth_estimateGas` for a deployment) has to go
410
+ // through `create`, where `data` is init code — `call` would treat it as
411
+ // calldata to the zero address and return a plausible, wrong estimate.
412
+ // `commit: false` + `checkNonce: false` make it the simulation `eth_call`
413
+ // semantics ask for. They are stated EXPLICITLY here because `create`
414
+ // defaults BOTH the other way (it is a transaction entry point), which is
415
+ // the mirror image of `transact` below, where both defaults are what a
416
+ // transaction wants and passing either would be a value a refactor can flip.
417
+ const outcome = isCreate
418
+ ? revm.create({...common, commit: false, checkNonce: false})
419
+ : revm.call({...common, to: request.to!.bytes});
420
+
421
+ // A REJECTION IS NOT A REVERT, and the difference decides what this read
422
+ // hands back. revm reports a transaction it refused BEFORE execution as
423
+ // `status: 'validation-error'` and REUSES the outcome's return-data slot for
424
+ // the `InvalidTransaction` variant's text, so `outcome.returnData` is then
425
+ // the UTF-8 of `Transaction(LackOfFundForMaxFee { fee: 1, balance: 0 })` —
426
+ // not bytes any callee produced, because no callee ran. Forwarding it made
427
+ // `node.ts` throw `RpcError(3, 'execution reverted', '0x5472616e…')`, and
428
+ // `data` on that error means ONE thing to a client: the callee's revert
429
+ // payload, which viem tries to decode as a revert reason. The default
430
+ // `@ethereumjs/evm` engine returns nothing for the same call, so this was
431
+ // also the last known behavioural divergence between the two engines on the
432
+ // forks this one admits.
433
+ //
434
+ // THE DISTINCTION IS REVM'S OWN, not a substring of its message: `status`
435
+ // separates a rejection (`validation-error`, zero gas, nothing executed)
436
+ // from a REVERT or a HALT, and `outcome.error` is defined for the first and
437
+ // only the first. Measured across all four statuses, including a callee that
438
+ // reverts WITH data while the transfer is unaffordable, in
439
+ // `docs/spikes/stop-forwarding-revms-validation-error-text-as-eth-call-return-data/`.
440
+ // A REVERT KEEPS ITS BYTES: a contract that reverted with a reason produced
441
+ // an ANSWER, and it must arrive on both engines alike.
442
+ //
443
+ // THE EXPLANATION IS NOT THROWN AWAY, it MOVES: revm is the only party that
444
+ // knows why it refused, so its text goes verbatim into the seam result's
445
+ // `error` — the same field the default engine puts `insufficient balance`
446
+ // in, and a place nothing can decode as a contract's revert reason.
447
+ const rejected = outcome.status === 'validation-error';
448
+
449
+ // EXECUTION gas, matching what `@ethereumjs/evm` reports: gas spent BEFORE
450
+ // refunds (revm's `gasUsed` is net of them, `totalGasSpent` is not), less
451
+ // the intrinsic gas the node adds back itself.
452
+ const spent = outcome.totalGasSpent;
453
+ return {
454
+ returnValue: rejected ? NO_RETURN_DATA : outcome.returnData,
455
+ executionGasUsed: spent > intrinsic ? spent - intrinsic : 0n,
456
+ error: outcome.success
457
+ ? undefined
458
+ : rejected
459
+ ? rejectionMessage(outcome.error)
460
+ : (outcome.error ?? `revm ${outcome.status}`),
461
+ };
462
+ },
463
+
464
+ async transact(request: TransactionRequest): Promise<TransactionResult> {
465
+ store.beginExecution();
466
+ const tx = request.tx as TransactionFields;
467
+
468
+ // THE SENDER IS THE SEAM'S VALUE, and this engine must never derive one of
469
+ // its own — not by `Revm#recoverSigner`, and not by asking the transaction
470
+ // (`tx.getSenderAddress()`), which recovers too. `senderMode:'trusted'`
471
+ // exists so that the CLAIMED sender may differ from the recoverable one (see
472
+ // `parseTx` in ./node.ts and ADR 0002), so either would execute the
473
+ // transaction as the WRONG address, charge that account, advance its nonce
474
+ // and hand back a receipt that looks completely right. revm agrees by
475
+ // construction: `transact` takes `from` directly and recovers nothing.
476
+ const sender = request.sender.bytes;
477
+ const options: ExecuteOptions = {
478
+ from: sender,
479
+ data: tx.data ?? EMPTY_DATA,
480
+ value: tx.value ?? 0n,
481
+ gasLimit: tx.gasLimit,
482
+ // THE NONCE IS SUPPLIED AND THE CHECK IS NOT MENTIONED. `Revm#transact`
483
+ // and `Revm#create` default `checkNonce` ON precisely because a caller who
484
+ // forgets it gets a silently replayable transaction, and the node's
485
+ // callers must not be able to reach that choice at all: it is decided by
486
+ // WHICH METHOD OF THIS ENGINE was called (story 10 of the spec), so there
487
+ // is no `checkNonce` here to flip and no option on
488
+ // `TransactionRequest` to pass one through.
489
+ nonce: tx.nonce,
490
+ ...feesOf(tx),
491
+ // EIP-2930/1559 access list, in revm's own shape. Charged and warmed by
492
+ // revm; the node does not price it. DROPPING it is not caught by a
493
+ // cross-engine gas diff alone, because a list the node also failed to charge
494
+ // on the other engine AGREES: that run is in
495
+ // `docs/spikes/eip-2930-access-lists-are-charged-and-warmed/measurements.md`,
496
+ // with an empty `mismatches` beside seven wrong gas figures. What catches it
497
+ // is absolute and lives in `test/revm-access-list.spec.ts`: the same
498
+ // transaction WITH the list and with an EMPTY one, held to the protocol's own
499
+ // arithmetic on both engines. Listing an entry the transaction touches is 100
500
+ // gas CHEAPER (charged 2,400/1,900, warmed for 2,500/2,000); listing entries
501
+ // it never touches is +6,200 exactly; a dropped list is 0.
502
+ ...(tx.accessList !== undefined && tx.accessList.length > 0
503
+ ? {
504
+ accessList: tx.accessList.map(([address, storageKeys]) => ({
505
+ address,
506
+ storageKeys,
507
+ })),
508
+ }
509
+ : {}),
510
+ // NOT MAPPED, and named so it is a known gap rather than an oversight:
511
+ // EIP-4844's `blobVersionedHashes` / `maxFeePerBlobGas` (a type-3
512
+ // transaction) and EIP-7702's `authorizationList` (post-Cancun, so
513
+ // unreachable while this engine admits Berlin..Cancun). The type-3 receipt
514
+ // is incomplete on BOTH engines — `blobGasUsed` / `blobGasPrice` are
515
+ // absent from the seam's result altogether — and that limitation is
516
+ // documented where it would be met by
517
+ // `document-the-type-3-receipt-gap-where-it-would-be-met`.
518
+ spec,
519
+ chainId,
520
+ block: blockEnvOf(request.block),
521
+ // AND NOTHING ELSE. No `commit` (it defaults to committing, which is what
522
+ // this method IS), no `returnState` (the logs, the bloom and the account
523
+ // changes are all part of a transaction's answer, and `returnState:false`
524
+ // cannot be combined with committing anyway), and above all NONE of the
525
+ // read path's simulation switches: `disableBaseFee`,
526
+ // `disableBlockGasLimit`, `disableEip3607` and `disableBalanceCheck` each
527
+ // relax a transaction's VALIDITY, and a transaction that runs with them
528
+ // relaxed is not a transaction. `revm-wasm` refuses to combine them with
529
+ // committing, so copying the read path's options object here would throw
530
+ // rather than lie — but that is the binding protecting us, not a design,
531
+ // and the absence is asserted in `test/revm-engine.spec.ts`.
532
+ //
533
+ // THE ONE CONSEQUENCE THAT USED TO BE AN ASYMMETRY, now settled: this
534
+ // engine rejects a transaction whose gas limit exceeds the block's
535
+ // (`Transaction(CallerGasLimitMoreThanBlock)`) because it cannot relax that
536
+ // rule while committing, and the default engine used to ACCEPT the same
537
+ // transaction because it passed `skipBlockGasLimitValidation` to `runTx`.
538
+ // That flag is gone (./engine.ts): both engines enforce the block's limit,
539
+ // and a consumer who wants a bigger one raises `blockGasLimit` so the block
540
+ // REALLY is bigger, which this engine honours by construction, since the
541
+ // limit it validates against is the one in `block` just above. The node
542
+ // refuses such a transaction before it reaches either engine, in words that
543
+ // name the knob (`refuseIfOverBlockGasLimit` in ./node.ts); this rejection
544
+ // is the backstop under it, in revm's own vocabulary.
545
+ };
546
+
547
+ // A DEPLOYMENT GOES THROUGH `create`, where `data` is INIT CODE: `transact`
548
+ // would treat it as calldata to the zero address, mine a receipt with no
549
+ // contract address and deploy nothing — measured, before this branch existed.
550
+ // Same split as the read half makes for a CREATE-shaped estimate, and for the
551
+ // same reason. BOTH entry points commit and check the nonce by default, which
552
+ // is why neither is mentioned in `options`.
553
+ const outcome =
554
+ tx.to === undefined
555
+ ? revm.create(options)
556
+ : revm.transact({...options, to: tx.to.bytes});
557
+
558
+ // A TRANSACTION THAT NEVER RAN IS NOT A RECEIPT. revm reports an invalid
559
+ // transaction as an OUTCOME (`status: 'validation-error'`, zero gas, nothing
560
+ // committed) where `runTx` THROWS, and the node's mining path is written
561
+ // against the throwing shape: `eth_sendRawTransaction` must fail rather than
562
+ // mine a block containing a zero-gas receipt for a transaction that was
563
+ // rejected. So this converts. The MESSAGE is revm's own, verbatim, because
564
+ // it is the only thing that knows why (`NonceTooLow { tx: 0, state: 1 }`).
565
+ //
566
+ // IT IS A BACKSTOP NOW, NOT THE ANSWER A CALLER GETS. The node refuses a
567
+ // replayed nonce, an unreachable nonce, an unaffordable transaction and a
568
+ // gas limit below intrinsic gas ITSELF, above the seam and before this
569
+ // method is called (`refuseIfSenderCannotSend` and
570
+ // `refuseIfBelowIntrinsicGas` in ./node.ts), because those four are the
571
+ // same rules on every engine and only the node can state them in one
572
+ // vocabulary. What still reaches this line is a cause the node does not
573
+ // pre-check — EIP-3607, a type-3 transaction's blob fee, anything a later
574
+ // revm adds — and for those, revm's own words are the only ones there are.
575
+ if (outcome.status === 'validation-error') {
576
+ throw new Error(
577
+ `webevm/revm: the transaction is invalid and was NOT executed: ` +
578
+ `${outcome.error ?? 'revm reported no reason'}`,
579
+ );
580
+ }
581
+
582
+ const created = createdAddressOf(outcome, tx, sender);
583
+ return {
584
+ status: outcome.success ? 1 : 0,
585
+ // `gasUsed`, NOT `totalGasSpent`, and the two are different fields with
586
+ // different meanings on this outcome: `gasUsed` is NET of refunds and
587
+ // `totalGasSpent` is the gross number before them. A receipt reports the
588
+ // net one — it is what the sender paid for, and what `@ethereumjs/vm`'s
589
+ // `totalGasSpent` (confusingly) already is, since `runTx` subtracts the
590
+ // refund from it before returning. THE READ PATH ABOVE TAKES THE OTHER
591
+ // ONE, deliberately: a read has no refund and `eth_estimateGas` wants the
592
+ // gross figure. Copying that mapping down here would put gas BEFORE
593
+ // refunds on every receipt, which a value transfer (zero refund) cannot
594
+ // detect — measured: a storage-clearing transaction reports
595
+ // `totalGasSpent` 26004, `gasRefunded` 4800 and `gasUsed` 21204
596
+ // (docs/spikes/revm-executes-the-first-transaction-with-commit/).
597
+ gasUsed: outcome.gasUsed,
598
+ // revm's OWN `Transaction::effective_gas_price`, not a second
599
+ // implementation of `min(maxFee, baseFee + tip)`: the engine that charged
600
+ // the sender is the engine that reports what it charged.
601
+ effectiveGasPrice: outcome.effectiveGasPrice,
602
+ // Emission order, reverted frames already excluded by revm.
603
+ logs: outcome.logs ?? [],
604
+ // ALWAYS 256 BYTES HERE, and that is the package's decoder doing work:
605
+ // the wire format OMITS the bloom when the log count is zero, and the
606
+ // decoder materialises the all-zero one. A hand-rolled reader of the blob
607
+ // would either mis-parse everything after it or hand the node a 0-byte
608
+ // `logsBloom`, which is why this path uses `revm-wasm`'s own decoder.
609
+ logsBloom: outcome.logsBloom ?? EMPTY_BLOOM,
610
+ ...(created !== undefined ? {createdAddress: created} : {}),
611
+ };
612
+ },
613
+
614
+ /**
615
+ * THE secp256k1 THIS MODULE WAS ALREADY CARRYING, lent to the node for
616
+ * `senderMode:'recover'`. It is the `0x01` precompile's own k256, reached
617
+ * with no database, no gas limit, no block environment and no journal — which
618
+ * is what makes it callable BEFORE `connect`, and before a transaction has
619
+ * anything to run against. Zero additional bytes: this code is in the module
620
+ * whether the node calls it or not.
621
+ *
622
+ * IT IS THE RAW CURVE OPERATION AND NOTHING ELSE, deliberately. The node
623
+ * hands over a message hash and a 0/1 recovery id — never the wire's `v` —
624
+ * and keeps every protocol rule on its own side, EIP-2's low-`s` rule
625
+ * especially: the precompile NORMALISES a high-`s` signature and returns an
626
+ * address, correctly, since EIP-2 constrains transactions rather than the
627
+ * precompile. An engine that added that opinion here would make the same
628
+ * transaction valid on one engine and invalid on the other. See
629
+ * `Engine.ecrecover` in ./types.ts and ../src/sender-recovery.ts.
630
+ *
631
+ * `revm-wasm`'s `recoverSigner` takes `v` as the recovery byte and answers
632
+ * `undefined` when the signature recovers to nothing, which is exactly the
633
+ * seam's contract, so this is a rename and not an adapter.
634
+ */
635
+ ecrecover(
636
+ hash: Uint8Array,
637
+ recoveryId: number,
638
+ r: Uint8Array,
639
+ s: Uint8Array,
640
+ ): Uint8Array | undefined {
641
+ return revm.recoverSigner({hash, v: recoveryId, r, s});
642
+ },
643
+ };
644
+ }
645
+
646
+ /** Calldata for a transaction that carries none. */
647
+ const EMPTY_DATA = /* @__PURE__ */ new Uint8Array();
648
+ /**
649
+ * What a read that was REJECTED before execution returns: nothing at all, which
650
+ * is what the default `@ethereumjs/evm` engine returns for the same call. Its
651
+ * own constant rather than {@link EMPTY_DATA} because the two say different
652
+ * things (calldata nobody sent, versus an answer nobody produced) and a later
653
+ * change to either must not silently move the other.
654
+ */
655
+ const NO_RETURN_DATA = /* @__PURE__ */ new Uint8Array();
656
+ /** The bloom of no logs, for the impossible case where the decoder omits it. */
657
+ const EMPTY_BLOOM = /* @__PURE__ */ new Uint8Array(256);
658
+
659
+ /**
660
+ * What a read REFUSED before execution says, in the node's own honest-edge voice
661
+ * with revm's reason quoted verbatim inside it.
662
+ *
663
+ * SAME SHAPE AS `transact`'s rejection message above, deliberately: both are
664
+ * "revm would not run this at all", and a reader who has met one should not have
665
+ * to learn a second sentence for the other.
666
+ *
667
+ * REVM'S WORDS ARE QUOTED, NOT TRANSLATED. That vocabulary now EXISTS — `nonce
668
+ * too low`, `nonce too high`, `insufficient funds for gas * price + value`,
669
+ * `intrinsic gas too low`, geth's phrasing so a client recognises it — and it
670
+ * lives in exactly ONE place: `src/node.ts`, ABOVE the seam, where the node
671
+ * refuses a transaction before any engine sees it. It is deliberately not
672
+ * reached for here, and the reason is not tidiness: a READ IS NOT A
673
+ * TRANSACTION. `call` relaxes a transaction's validity rules on purpose (base
674
+ * fee, block gas limit, EIP-3607), so there is no pre-flight above it to speak
675
+ * that vocabulary and nothing here to translate INTO it — the one rule a read
676
+ * keeps is the value transfer, and it is the engine, not this wrapper, that
677
+ * knows whether the shortfall was the value, the fee or the gas. Building a
678
+ * second, read-only half of the vocabulary here would fork it in two.
679
+ *
680
+ * IT DOES NOT BECOME AN RPC MESSAGE, and that is the point of the seam: `node.ts`
681
+ * flattens EVERY engine failure into `RpcError(3, 'execution reverted')` on both
682
+ * engines, so this text lives exactly where `@ethereumjs/evm`'s
683
+ * `insufficient balance` lives — on {@link ReadCallResult.error}, readable by
684
+ * anything holding the engine, and identical in KIND across engines. Surfacing
685
+ * it in the RPC message instead would put a per-engine sentence back on the wire
686
+ * and re-create, one field over, the divergence this change removes.
687
+ */
688
+ function rejectionMessage(reason: string | undefined): string {
689
+ return (
690
+ `webevm/revm: the call is invalid and was NOT executed: ` +
691
+ `${reason ?? 'revm reported no reason'}. Nothing ran, so this is a refusal ` +
692
+ `rather than a revert and there is no return data to decode — correct the ` +
693
+ `request itself (its sender, its value or its gas) rather than looking for a ` +
694
+ `revert reason.`
695
+ );
696
+ }
697
+
698
+ /**
699
+ * The transaction fields this engine reads, named once.
700
+ *
701
+ * `TypedTransaction` is a UNION of five classes and the fee fields exist on
702
+ * different members of it (`gasPrice` on legacy and EIP-2930, `maxFeePerGas` on
703
+ * the 1559 family), so reading them off the union directly does not typecheck and
704
+ * reading them off `any` typechecks anything. This is the narrow middle: exactly
705
+ * the fields that are read, all optional, so a missing one is a branch rather
706
+ * than a runtime surprise.
707
+ */
708
+ interface TransactionFields {
709
+ readonly to?: {readonly bytes: Uint8Array};
710
+ readonly data?: Uint8Array;
711
+ readonly value?: bigint;
712
+ readonly gasLimit: bigint;
713
+ readonly nonce: bigint;
714
+ readonly gasPrice?: bigint;
715
+ readonly maxFeePerGas?: bigint;
716
+ readonly maxPriorityFeePerGas?: bigint;
717
+ readonly accessList?: readonly [Uint8Array, Uint8Array[]][];
718
+ }
719
+
720
+ /**
721
+ * The node's block, as revm's block environment. ONE mapping, shared by both
722
+ * operations, because a read and a transaction observe the SAME block and an
723
+ * engine that described it two ways could disagree with itself about `BASEFEE`.
724
+ *
725
+ * THE NODE'S REAL VALUES, never convenient ones. `BASEFEE` inside a contract
726
+ * must report the block the node actually has; on the read path the validation
727
+ * the real base fee would otherwise trip is turned off explicitly
728
+ * (`disableBaseFee`) rather than bought with a zeroed base fee, which is a lie
729
+ * the contract sees.
730
+ *
731
+ * PREVRANDAO is read off `mixHash`. Post-Merge it IS `mixHash` (the node writes
732
+ * `NodeOptions.blockEnv.prevRandao` there and pins difficulty to 0), and the
733
+ * `prevRandao` getter THROWS on a pre-Merge fork — which stopped being belt and
734
+ * braces the moment `berlin` and `london` were admitted.
735
+ */
736
+ function blockEnvOf(block: Block): BlockEnv {
737
+ const header = block.header;
738
+ return {
739
+ number: header.number,
740
+ timestamp: header.timestamp,
741
+ gasLimit: header.gasLimit,
742
+ coinbase: header.coinbase.bytes,
743
+ baseFeePerGas: header.baseFeePerGas ?? 0n,
744
+ prevRandao: header.mixHash,
745
+ ...(header.excessBlobGas !== undefined
746
+ ? {excessBlobGas: header.excessBlobGas}
747
+ : {}),
748
+ };
749
+ }
750
+
751
+ /**
752
+ * The transaction's fee fields, in revm's vocabulary.
753
+ *
754
+ * revm keeps `gasPrice` and `maxFeePerGas` in ONE field and derives the EIP-2718
755
+ * transaction type from which fields are present, so the two families are passed
756
+ * as the two families and the type is left to the binding — whose own
757
+ * documentation says the derivation is the part most easily got wrong by hand.
758
+ * The PRESENCE of `maxPriorityFeePerGas` is what makes it derive a 1559-family
759
+ * transaction, so an undefined one is not the same as a zero one.
760
+ */
761
+ function feesOf(tx: TransactionFields): {
762
+ gasPrice?: bigint;
763
+ maxFeePerGas?: bigint;
764
+ maxPriorityFeePerGas?: bigint;
765
+ } {
766
+ if (tx.maxFeePerGas !== undefined) {
767
+ return {
768
+ maxFeePerGas: tx.maxFeePerGas,
769
+ maxPriorityFeePerGas: tx.maxPriorityFeePerGas ?? 0n,
770
+ };
771
+ }
772
+ return {gasPrice: tx.gasPrice ?? 0n};
773
+ }
774
+
775
+ /**
776
+ * The address a TOP-LEVEL creation produced, derived rather than reported — and
777
+ * the ONE place that derivation lives.
778
+ *
779
+ * revm's outcome has no created-address field, so it comes out of the account
780
+ * changes: the entry flagged `created`. THAT IS AMBIGUOUS THE MOMENT A
781
+ * TRANSACTION PERFORMS NESTED CREATIONS, because every one of them is flagged the
782
+ * same way, and the receipt's `contractAddress` names only the top-level one. Two
783
+ * things narrow it here:
784
+ *
785
+ * 1. a transaction with a `to` creates nothing AT THE TOP LEVEL, whatever it
786
+ * creates inside, so it has no `contractAddress` at all;
787
+ * 2. among several created entries, the top-level one is the address the
788
+ * PROTOCOL says a creation transaction produces, `keccak(rlp(sender, nonce))`
789
+ * — which `@ethereumjs/util` already computes, and which is unambiguous
790
+ * because a transaction's own creation is always a plain CREATE.
791
+ *
792
+ * The nested case is DISCHARGED, on a transaction that actually performs one:
793
+ * `test/revm-post-state.spec.ts` sends a creation whose init code CREATEs a
794
+ * child, so TWO account changes arrive flagged `created`, and asserts that the
795
+ * receipt's `contractAddress` is the top-level address on BOTH engines and is
796
+ * NOT the child's. Taking `created[0]` passes every simple deploy and fails
797
+ * there.
798
+ */
799
+ function createdAddressOf(
800
+ outcome: Outcome,
801
+ tx: TransactionFields,
802
+ sender: Uint8Array,
803
+ ): Uint8Array | undefined {
804
+ if (tx.to !== undefined) return undefined;
805
+ const created = (outcome.stateChanges ?? []).filter((c) => c.created);
806
+ if (created.length <= 1) return created[0]?.address;
807
+ const topLevel = generateAddress(sender, bigIntToBytes(tx.nonce));
808
+ return created.find((c) => equalsBytes(c.address, topLevel))?.address;
809
+ }