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
@@ -0,0 +1,80 @@
1
+ /**
2
+ * persistence.ts — IndexedDB persistence adapter for the node.
3
+ *
4
+ * The node's `dumpState`/`loadState` are async, so the adapter is trivially
5
+ * async (no sync-storage shim needed over async IndexedDB): dump the live-set
6
+ * Maps (+ block list / receipts / tx / logs index) to ONE IndexedDB record and
7
+ * rehydrate on load. Slim, live-set-sized, no trie, no RLP state-root.
8
+ *
9
+ * bigint-safe JSON: we never put bigints in the serialized state (everything is
10
+ * already hex strings in SerializedState), so a plain structured clone works and
11
+ * we don't even need JSON — IndexedDB can store the object directly.
12
+ */
13
+ import type {PersistenceAdapter, SerializedState} from './types.js';
14
+
15
+ export interface IndexedDBPersistenceOptions {
16
+ db?: string;
17
+ store?: string;
18
+ key?: string;
19
+ }
20
+
21
+ export function createIndexedDBPersistence(
22
+ opts: IndexedDBPersistenceOptions = {},
23
+ ): PersistenceAdapter {
24
+ const dbName = opts.db ?? 'webevm';
25
+ const storeName = opts.store ?? 'state';
26
+ const key = opts.key ?? 'node-state';
27
+ let dbPromise: Promise<IDBDatabase> | undefined;
28
+
29
+ function getDb(): Promise<IDBDatabase> {
30
+ if (!dbPromise) {
31
+ dbPromise = new Promise((resolve, reject) => {
32
+ const req = indexedDB.open(dbName, 1);
33
+ req.onupgradeneeded = () => {
34
+ const db = req.result;
35
+ if (!db.objectStoreNames.contains(storeName))
36
+ db.createObjectStore(storeName);
37
+ };
38
+ req.onsuccess = () => resolve(req.result);
39
+ req.onerror = () => reject(req.error);
40
+ });
41
+ }
42
+ return dbPromise;
43
+ }
44
+
45
+ return {
46
+ async load(): Promise<SerializedState | null> {
47
+ const db = await getDb();
48
+ return new Promise((resolve, reject) => {
49
+ const tx = db.transaction(storeName, 'readonly');
50
+ const req = tx.objectStore(storeName).get(key);
51
+ req.onsuccess = () => resolve((req.result as SerializedState) ?? null);
52
+ req.onerror = () => reject(req.error);
53
+ });
54
+ },
55
+ async save(state: SerializedState): Promise<void> {
56
+ const db = await getDb();
57
+ return new Promise((resolve, reject) => {
58
+ const tx = db.transaction(storeName, 'readwrite');
59
+ tx.objectStore(storeName).put(state, key);
60
+ tx.oncomplete = () => resolve();
61
+ tx.onerror = () => reject(tx.error);
62
+ });
63
+ },
64
+ };
65
+ }
66
+
67
+ /** An in-memory adapter (handy for tests / SSR / proving the round-trip). */
68
+ export function createMemoryPersistence(
69
+ initial?: SerializedState | null,
70
+ ): PersistenceAdapter {
71
+ let stored: SerializedState | null = initial ?? null;
72
+ return {
73
+ async load() {
74
+ return stored;
75
+ },
76
+ async save(state) {
77
+ stored = state;
78
+ },
79
+ };
80
+ }
@@ -0,0 +1,455 @@
1
+ /**
2
+ * revm-state-store.ts — a SYNCHRONOUS `StateStore` (revm-wasm) over the node's
3
+ * live `SimpleStateManager`, with NO state copied across and NO state owned.
4
+ *
5
+ * READ AND WRITE, both on demand. The engine reads accounts, code, storage and
6
+ * block hashes as an opcode needs them, and a COMMITTING execute writes back
7
+ * ONLY the accounts revm touched and the slots that changed. There is no bulk
8
+ * sync in either direction and no second copy of state anywhere, which is what
9
+ * keeps the cost proportional to what a transaction touched and why `dumpState`,
10
+ * `loadState`, persistence and the `evm_set*` cheats keep working untouched. See
11
+ * `docs/adr/0010-revm-reads-and-writes-through-host-callbacks-the-node-keeps-owning-state.md`
12
+ * for the ownership decision, its measured cost and the caveat that cuts against
13
+ * it.
14
+ *
15
+ * ## The coupling this buys, stated plainly
16
+ *
17
+ * revm's state reads must be synchronous: the interpreter is a synchronous loop
18
+ * inside wasm and a read happens in the middle of an opcode, so there is no
19
+ * suspension point to await at. Every method on `StateManagerInterface` returns
20
+ * a `Promise`. The ONLY synchronous view of the node's state that exists is the
21
+ * node's own `OverlayStorageStateManager` — `SimpleStateManager`'s two PUBLIC
22
+ * account/code checkpoint stacks plus our storage OVERLAY stack — so this module
23
+ * reaches past the interface into that one implementation, exactly as `node.ts`'s
24
+ * `dumpState` already does in `'none'` mode. The full cost, the alternatives
25
+ * that were rejected, and why `stateMode:'trie'` therefore cannot be served are
26
+ * in `docs/adr/0005-revm-reads-the-nodes-state-through-simplestatemanagers-stacks.md`.
27
+ *
28
+ * Three consequences worth having in your head before editing this file:
29
+ *
30
+ * 1. **Read the TOP of the stack on EVERY access.** A checkpoint pushes a COPY
31
+ * of the account and code maps, so a frame captured once answers from the
32
+ * frame below after the next checkpoint — silently, with no error and
33
+ * plausible values. Storage is read through `storageAt()`, which walks the
34
+ * overlay stack live for the same reason.
35
+ * 2. **The ACCOUNT and CODE key format is the state manager's, not ours**, and
36
+ * must be reproduced byte for byte: `address.toString()`, `0x`-prefixed
37
+ * lowercase hex, because those two stacks are `SimpleStateManager`'s. THE
38
+ * STORAGE KEY IS THE NODE'S (ADR 0009) and is PACKED — two bytes per UTF-16
39
+ * code unit — which is worth 70-73% of every cold access. It is built by
40
+ * `src/storage-keys.ts`, the SAME module `src/state-manager.ts` builds it
41
+ * with, because `@ethereumjs/evm` writes storage through the async
42
+ * `putStorage` while this store reads it through the synchronous `storageAt`:
43
+ * two formats that each work on their own turn every cross-route read into a
44
+ * MISS, and a miss reads as ZERO at identical gas. Storage values are stored
45
+ * in shortest form, so reads left-pad to 32 bytes.
46
+ * 3. **`@ethereumjs/statemanager` is version-pinned deliberately.** Renaming a
47
+ * stack is a compile error here (which is why this file uses the real
48
+ * `OverlayStorageStateManager` type and not `any`); changing the KEY FORMAT or
49
+ * the value padding would compile and return wrong values. {@link assertStateShape}
50
+ * catches the structural half at construction, and the cross-backend gas gate
51
+ * catches the rest, because feeding revm the wrong state changes gas.
52
+ *
53
+ * The `Address` and `Bytes32` arguments on the READ methods are revm's REUSED
54
+ * scratch buffers, valid only for the duration of the call. Everything here
55
+ * consumes them immediately (into a string key, or into a keccak hash); nothing
56
+ * retains one. The WRITE methods receive fresh arrays and may keep them, which
57
+ * is what lets a storage value be stored without a copy.
58
+ */
59
+ import {Account} from '@ethereumjs/util';
60
+ import type {OverlayStorageStateManager} from './state-manager.js';
61
+ // THE storage key encoder, shared with the async half in ./state-manager.ts so
62
+ // the two cannot drift into two formats that both work. See its header.
63
+ import {packAddressKey, packSlotKey} from './storage-keys.js';
64
+ import {keccak_256} from '@noble/hashes/sha3.js';
65
+ import type {AccountState, Address, Bytes32, StateStore} from 'revm-wasm';
66
+
67
+ const HEX = /* @__PURE__ */ (() => {
68
+ const t: string[] = [];
69
+ for (let i = 0; i < 256; i++) t.push(i.toString(16).padStart(2, '0'));
70
+ return t;
71
+ })();
72
+
73
+ /** `0x`-prefixed lowercase hex — the exact key format SimpleStateManager uses. */
74
+ function addrKey(a: Uint8Array): string {
75
+ let s = '0x';
76
+ for (let i = 0; i < 20; i++) s += HEX[a[i]];
77
+ return s;
78
+ }
79
+ function hexOf(b: Uint8Array): string {
80
+ let s = '';
81
+ for (let i = 0; i < b.length; i++) s += HEX[b[i]];
82
+ return s;
83
+ }
84
+
85
+ /** SimpleStateManager stores storage values UNPADDED; revm wants 32 bytes. */
86
+ function pad32(v: Uint8Array): Bytes32 {
87
+ if (v.length === 32) return v;
88
+ const out = new Uint8Array(32);
89
+ out.set(v, 32 - v.length);
90
+ return out;
91
+ }
92
+
93
+ /**
94
+ * The inverse of {@link pad32}: revm hands over 32 padded bytes and this
95
+ * representation holds the SHORTEST form.
96
+ *
97
+ * Not a micro-optimisation — it is what makes a slot written by revm
98
+ * indistinguishable from the same slot written by `@ethereumjs/evm`, which
99
+ * strips leading zeros itself before `putStorage` (`opcodes/functions.js`, the
100
+ * `SSTORE` case: a zero value becomes a ZERO-LENGTH array, anything else
101
+ * `bigIntToBytes`). `dumpState` serialises the stored bytes verbatim, so a
102
+ * padded write would round-trip correctly and dump differently.
103
+ */
104
+ function shortest(v: Uint8Array): Uint8Array {
105
+ let i = 0;
106
+ while (i < v.length && v[i] === 0) i++;
107
+ // A cleared slot is stored EMPTY rather than deleted, exactly as the default
108
+ // engine stores it: `storageAt` stops its overlay walk on a zero-length value,
109
+ // so an overlay below cannot leak a stale value through it.
110
+ return i === 0 ? v : v.subarray(i);
111
+ }
112
+
113
+ /** keccak256 of the empty byte string, i.e. the code hash of every EOA. */
114
+ const EMPTY_CODE_HASH_HEX = /* @__PURE__ */ hexOf(keccak_256(new Uint8Array()));
115
+ const EMPTY_CODE = /* @__PURE__ */ new Uint8Array();
116
+
117
+ /** What the store needs from the node beyond its state manager. */
118
+ export interface SimpleStateStoreOptions {
119
+ /**
120
+ * Answers `BLOCKHASH`, from the node's own blocks. Returning `undefined` (or
121
+ * leaving this unset) makes `BLOCKHASH` answer 32 zero bytes, which is a
122
+ * silently wrong answer for a block the node actually has — so the engine
123
+ * wires this to its `EngineContext` rather than defaulting it.
124
+ */
125
+ blockHash?: (blockNumber: bigint) => Uint8Array | undefined;
126
+ }
127
+
128
+ /**
129
+ * Throw unless `sm` still has the exact representation this adapter reads: the
130
+ * two upstream account/code checkpoint stacks AND the node's own storage overlay
131
+ * stack. Cheap, once, at engine construction.
132
+ *
133
+ * IT MUST CONSTRAIN THE REPRESENTATION, NOT MERELY ITS SHELL. Its predecessor
134
+ * asserted "three non-empty arrays of Maps", which a per-account layout satisfied
135
+ * while every storage read silently answered zero — the guard passed on exactly
136
+ * the change it existed to catch (demonstrated in
137
+ * `docs/spikes/spike-storage-layout-cost-for-the-revm-write-half/measurements.md`).
138
+ * So this asserts the storage side by the two ACCESSORS the adapter actually
139
+ * calls plus the overlay stack's own shape, and `test/storage-overlay.spec.ts`
140
+ * feeds it a stock `SimpleStateManager` (the flat layout) to prove it refuses one.
141
+ */
142
+ export function assertStateShape(sm: OverlayStorageStateManager): void {
143
+ for (const name of ['accountStack', 'codeStack'] as const) {
144
+ const stack = sm[name] as unknown;
145
+ if (
146
+ !Array.isArray(stack) ||
147
+ stack.length === 0 ||
148
+ !(stack[stack.length - 1] instanceof Map)
149
+ ) {
150
+ throw new Error(
151
+ `webevm/revm: the state manager does not have the expected ` +
152
+ `SimpleStateManager.${name} (a non-empty array of Maps). The revm engine ` +
153
+ `reads the node's state through those stacks — see ` +
154
+ `docs/adr/0005-revm-reads-the-nodes-state-through-simplestatemanagers-stacks.md. ` +
155
+ `Check the @ethereumjs/statemanager version.`,
156
+ );
157
+ }
158
+ }
159
+ if (
160
+ typeof sm.storageAt !== 'function' ||
161
+ typeof sm.liveStorage !== 'function' ||
162
+ typeof sm.setStorageAt !== 'function' ||
163
+ typeof sm.clearStorageAt !== 'function'
164
+ ) {
165
+ throw new Error(
166
+ 'webevm/revm: the state manager does not expose storageAt(), ' +
167
+ "liveStorage(), setStorageAt() and clearStorageAt(), so it is not the node's " +
168
+ 'OverlayStorageStateManager. The revm engine reads AND writes storage ' +
169
+ 'synchronously through those accessors; a state manager with a different ' +
170
+ 'storage representation would answer every slot as ZERO rather than failing. ' +
171
+ 'See src/state-manager.ts.',
172
+ );
173
+ }
174
+ const overlays = sm.storageOverlays as unknown;
175
+ const top = Array.isArray(overlays)
176
+ ? (overlays[overlays.length - 1] as StorageOverlayShape | undefined)
177
+ : undefined;
178
+ if (
179
+ !Array.isArray(overlays) ||
180
+ overlays.length === 0 ||
181
+ !(top?.written instanceof Map) ||
182
+ !(top?.cleared instanceof Set)
183
+ ) {
184
+ throw new Error(
185
+ 'webevm/revm: the state manager does not have the expected ' +
186
+ 'storageOverlays (a non-empty array whose top overlay has a `written` Map ' +
187
+ 'and a `cleared` Set). See src/state-manager.ts.',
188
+ );
189
+ }
190
+ }
191
+
192
+ /** Only what {@link assertStateShape} checks, so the guard can look before it leaps. */
193
+ interface StorageOverlayShape {
194
+ written?: unknown;
195
+ cleared?: unknown;
196
+ }
197
+
198
+ /**
199
+ * revm's `StateStore`, backed by the node's live state.
200
+ *
201
+ * Created UNBOUND and bound in the engine's `connect(context)`: an injected
202
+ * engine exists before the node does (ADR 0006), and the wasm instance needs its
203
+ * store at instantiation time, so the store is the thing that waits.
204
+ */
205
+ export class SimpleStateManagerStore implements StateStore {
206
+ #sm: OverlayStorageStateManager | undefined;
207
+ #blockHash: ((blockNumber: bigint) => Uint8Array | undefined) | undefined;
208
+ /** codeHash (unprefixed hex) -> code. Derived, never authoritative. */
209
+ readonly #byCodeHash = new Map<string, Uint8Array>();
210
+ /** Code hashes already looked for and NOT found — see {@link beginExecution}. */
211
+ readonly #absentCodeHashes = new Set<string>();
212
+ /**
213
+ * Code handed over by {@link setCode} during the execution now committing,
214
+ * keyed by hash, waiting for the {@link setAccount} that names the address it
215
+ * belongs to.
216
+ *
217
+ * THE BINDING'S COMMIT ORDER IS WHY THIS EXISTS, and it is measured rather than
218
+ * assumed (`docs/spikes/revm-executes-the-first-transaction-with-commit/`):
219
+ * `setCode(codeHash, code)` arrives BEFORE the `setAccount` carrying that hash,
220
+ * because revm's own state is keyed by code HASH while this node keys code by
221
+ * ADDRESS. Nobody but the account change knows the address, so the code waits
222
+ * one callback.
223
+ *
224
+ * Cleared per execution, not per commit: a hash left here would attach a
225
+ * previous transaction's code to an account of the same code hash, which is
226
+ * harmless (the key IS the content hash) but makes the reasoning harder than
227
+ * clearing it.
228
+ */
229
+ readonly #pendingCode = new Map<string, Uint8Array>();
230
+
231
+ /**
232
+ * Bind to the node's live state manager. Called once, from `connect`.
233
+ *
234
+ * ONE ENGINE SERVES ONE NODE, and a second bind is refused rather than
235
+ * honoured. An engine instance owns one wasm instance and this one store, so
236
+ * rebinding would re-point an ALREADY-RUNNING node's reads at a different
237
+ * node's state — the first node would then answer every `eth_call` from the
238
+ * second node's accounts, with plausible values and no error. The seam
239
+ * documents `connect` as called exactly once (see `Engine.connect` in
240
+ * ./types.ts), so a second call is a consumer sharing one engine across nodes,
241
+ * and it fails at the second construction rather than at the first wrong read.
242
+ */
243
+ bind(
244
+ sm: OverlayStorageStateManager,
245
+ options: SimpleStateStoreOptions = {},
246
+ ): void {
247
+ if (this.#sm !== undefined) {
248
+ throw new Error(
249
+ 'webevm/revm: this engine is already connected to a node. An ' +
250
+ 'engine instance serves ONE node — reconnecting it would re-point the ' +
251
+ "FIRST node's reads at the second node's state, silently. Call " +
252
+ 'createRevmEngine() once per createNode(); pass the same compiled ' +
253
+ 'WebAssembly.Module to each if you want to compile the wasm only once.',
254
+ );
255
+ }
256
+ assertStateShape(sm);
257
+ this.#sm = sm;
258
+ this.#blockHash = options.blockHash;
259
+ }
260
+
261
+ /**
262
+ * Start of one execution — a read-only call OR a committing transaction. Drops
263
+ * the negative code-index cache and any code left waiting for its account.
264
+ *
265
+ * A rebuild-on-miss index cannot cache a miss ACROSS executions: code deployed
266
+ * between two of them would stay invisible, and an invisible contract runs as
267
+ * EMPTY code and returns `success` with empty data — silently wrong (ADR
268
+ * 0005). WITHIN one execution it can, and must, because nothing else can write
269
+ * to the node's state while the interpreter holds the thread: JS runs
270
+ * single-threaded, a read-only call never calls a write method at all, and a
271
+ * transaction's writes all arrive at the END, during commit, after the last
272
+ * opcode. So a hash that is absent at the first opcode is absent at the last,
273
+ * and a contract that is genuinely absent no longer re-scans the whole code map
274
+ * on every access.
275
+ *
276
+ * NOT `beginCall`, which it was called while this store served only `eth_call`:
277
+ * *call* names the seam's READ operation in this codebase (`Engine.call`), and
278
+ * a transaction reaches here too now.
279
+ */
280
+ beginExecution(): void {
281
+ this.#absentCodeHashes.clear();
282
+ this.#pendingCode.clear();
283
+ }
284
+
285
+ // --- the three top-of-stack views -------------------------------------
286
+ // stack[stack.length - 1] on EVERY access. See the header: a cached frame is
287
+ // stale after the next checkpoint, silently.
288
+ get #accounts(): Map<string, Account | undefined> {
289
+ const s = this.#connected().accountStack;
290
+ return s[s.length - 1];
291
+ }
292
+ get #code(): Map<string, Uint8Array> {
293
+ const s = this.#connected().codeStack;
294
+ return s[s.length - 1];
295
+ }
296
+
297
+ #connected(): OverlayStorageStateManager {
298
+ if (this.#sm === undefined)
299
+ throw new Error(
300
+ 'webevm/revm: the engine touched state before connect() bound ' +
301
+ 'it to a node. Pass the engine to createNode() before using it.',
302
+ );
303
+ return this.#sm;
304
+ }
305
+
306
+ getAccount(address: Address): AccountState | undefined {
307
+ const acc = this.#accounts.get(addrKey(address));
308
+ if (acc === undefined) return undefined;
309
+ return {balance: acc.balance, nonce: acc.nonce, codeHash: acc.codeHash};
310
+ }
311
+
312
+ /**
313
+ * THE HOT PATH, and the reason `src/storage-keys.ts` exists: a cold access cost
314
+ * 1.31-1.33 µs through the real wasm module with the `0x`-hex key and costs
315
+ * 0.36-0.39 µs with the packed one, of which 0.17-0.18 µs is the wasm crossing
316
+ * itself (`docs/spikes/revm-state-store-packed-storage-keys/measurements.md`).
317
+ * Both keys are packed, both are built here and nowhere else on this side, and
318
+ * `storageAt` walks the overlay stack afresh on every call because the top of it
319
+ * moves under us (see the header's point 1).
320
+ */
321
+ getStorage(address: Address, slot: Bytes32): Bytes32 | undefined {
322
+ const v = this.#connected().storageAt(
323
+ packAddressKey(address),
324
+ packSlotKey(slot),
325
+ );
326
+ if (v === undefined || v.length === 0) return undefined;
327
+ return pad32(v);
328
+ }
329
+
330
+ getCode(codeHash: Bytes32): Uint8Array | undefined {
331
+ const key = hexOf(codeHash);
332
+ if (key === EMPTY_CODE_HASH_HEX) return EMPTY_CODE;
333
+ const hit = this.#byCodeHash.get(key);
334
+ if (hit !== undefined) return hit;
335
+ const pending = this.#pendingCode.get(key);
336
+ if (pending !== undefined) return pending;
337
+ if (this.#absentCodeHashes.has(key)) return undefined;
338
+ this.#reindexCode();
339
+ const rebuilt = this.#byCodeHash.get(key);
340
+ if (rebuilt === undefined) this.#absentCodeHashes.add(key);
341
+ return rebuilt;
342
+ }
343
+
344
+ getBlockHash(blockNumber: bigint): Bytes32 | undefined {
345
+ return this.#blockHash?.(blockNumber);
346
+ }
347
+
348
+ // --- the write half ------------------------------------------------------
349
+ // ONLY a COMMITTING execute reaches these (`Revm#call` cannot be made to
350
+ // commit, whatever its options say), and they arrive with revm's own commit
351
+ // semantics ALREADY APPLIED: a `SELFDESTRUCT` and an EIP-161 empty-account
352
+ // clearing both arrive as `clearStorage` then `removeAccount`, and a created
353
+ // account arrives with `clearStorage` FIRST so a fresh contract cannot inherit
354
+ // storage from a previous life at its address. None of that is re-derived here;
355
+ // re-deriving it is how a host gets EIP-161 subtly wrong.
356
+ //
357
+ // EACH ONE IS ONE MAP WRITE INTO THE TOP OF THE NODE'S OWN STATE, at the same
358
+ // depth `putAccount` / `putCode` / `putStorage` write to, so a transaction's
359
+ // cost is proportional to what it touched and a `revert()` above still drops it.
360
+ // They are written against the state manager's REPRESENTATION rather than its
361
+ // async interface for the reason in the header: revm's commit runs inside a
362
+ // synchronous wasm callback and every `StateManagerInterface` method returns a
363
+ // `Promise`.
364
+
365
+ setAccount(address: Address, account: AccountState): void {
366
+ const accounts = this.#accounts;
367
+ const key = addrKey(address);
368
+ const existing = accounts.get(key);
369
+ // The storage ROOT is carried over rather than computed: `SimpleStateManager`
370
+ // implements no state-root logic at all, so this field never reflects storage
371
+ // on either engine (ADR 0009 records the EIP-7610 consequence). Carrying it
372
+ // keeps a revm-written account byte-identical to an ethereumjs-written one,
373
+ // which is what `dumpState` serialises.
374
+ accounts.set(
375
+ key,
376
+ new Account(
377
+ account.nonce,
378
+ account.balance,
379
+ existing?.storageRoot,
380
+ account.codeHash,
381
+ ),
382
+ );
383
+ // The code this account's hash names, if it arrived a callback ago. Written
384
+ // HERE because this is the only callback that knows the address, and only when
385
+ // `setCode` actually ran, which the binding does exactly when revm loaded or
386
+ // deposited code for it — never for an account that merely received ether.
387
+ const hashKey = hexOf(account.codeHash);
388
+ const code = this.#pendingCode.get(hashKey);
389
+ if (code !== undefined) this.#code.set(key, code);
390
+ }
391
+
392
+ setCode(codeHash: Bytes32, code: Uint8Array): void {
393
+ // This one method writes only into the store's OWN index (the address it
394
+ // belongs to arrives with the next `setAccount`), so it would otherwise be the
395
+ // one write that an UNBOUND store accepted in silence.
396
+ this.#connected();
397
+ const key = hexOf(codeHash);
398
+ this.#pendingCode.set(key, code);
399
+ // A hash that was absent a moment ago exists now, so the negative cache must
400
+ // forget it or a contract created inside this transaction would read as EMPTY
401
+ // code in the next one.
402
+ this.#absentCodeHashes.delete(key);
403
+ this.#byCodeHash.set(key, code);
404
+ }
405
+
406
+ setStorage(address: Address, slot: Bytes32, value: Bytes32): void {
407
+ this.#connected().setStorageAt(
408
+ packAddressKey(address),
409
+ packSlotKey(slot),
410
+ shortest(value),
411
+ );
412
+ }
413
+
414
+ clearStorage(address: Address): void {
415
+ this.#connected().clearStorageAt(packAddressKey(address));
416
+ }
417
+
418
+ removeAccount(address: Address): void {
419
+ // A TOMBSTONE, not a delete, because that is what `deleteAccount` does
420
+ // upstream (`SimpleStateManager` sets the key to `undefined`) and this store
421
+ // must leave the node's state in the shape the default engine leaves it: a
422
+ // `delete` would let an overlay-free account map answer from nothing while a
423
+ // tombstone answers "absent", and `dumpState` skips both. The account's CODE is
424
+ // deliberately left where it is, again matching upstream, which never removes
425
+ // it either; nothing reads it, since revm asks for code by HASH.
426
+ //
427
+ // THE STORAGE HALF IS NOT DONE HERE and must not be: the binding sends
428
+ // `clearStorage` for this account IMMEDIATELY BEFORE this call, for a
429
+ // `SELFDESTRUCT` and for an EIP-161 clearing alike, so doing it again here
430
+ // would be the host re-deriving a rule the engine already applied. The DEFAULT
431
+ // engine reached the same end state only after `OverlayStorageStateManager`
432
+ // learned to clear storage on `deleteAccount` (ADR 0007's 2026-08-10
433
+ // amendment); before that it left a dead contract's slots readable, and the
434
+ // two engines' post-state differed on exactly this.
435
+ this.#accounts.set(addrKey(address), undefined);
436
+ }
437
+
438
+ /**
439
+ * Rebuild codeHash -> code from the live code map. The node keys code by
440
+ * ADDRESS; revm asks by HASH, so somebody has to hold the inverse, and it is
441
+ * derived state living outside the state manager.
442
+ *
443
+ * Rebuilt on a MISS (and only on a miss), so the cost is one keccak per
444
+ * account-with-code per newly-deployed contract, not per read. Rebuild-on-miss
445
+ * rather than a hook on `putCode`, because code reaches the state manager by
446
+ * several routes (`evm_setCode`, `loadState`, a contract creation inside a
447
+ * transaction) and a hook can be forgotten by the next one. A hash that HITS
448
+ * can never be wrong: the key IS the content hash.
449
+ */
450
+ #reindexCode(): void {
451
+ this.#byCodeHash.clear();
452
+ for (const c of this.#code.values())
453
+ this.#byCodeHash.set(hexOf(keccak_256(c)), c);
454
+ }
455
+ }