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