webevm 0.7.0 → 0.9.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 (56) hide show
  1. package/README.md +115 -63
  2. package/dist/derived-trie.d.ts +38 -0
  3. package/dist/derived-trie.d.ts.map +1 -0
  4. package/dist/derived-trie.js +187 -0
  5. package/dist/derived-trie.js.map +1 -0
  6. package/dist/engine.d.ts +1 -2
  7. package/dist/engine.d.ts.map +1 -1
  8. package/dist/engine.js +2 -3
  9. package/dist/engine.js.map +1 -1
  10. package/dist/index.d.ts +1 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js.map +1 -1
  13. package/dist/node.d.ts +45 -0
  14. package/dist/node.d.ts.map +1 -1
  15. package/dist/node.js +1108 -140
  16. package/dist/node.js.map +1 -1
  17. package/dist/revm-state-store.d.ts +5 -0
  18. package/dist/revm-state-store.d.ts.map +1 -1
  19. package/dist/revm-state-store.js +42 -13
  20. package/dist/revm-state-store.js.map +1 -1
  21. package/dist/revm.d.ts.map +1 -1
  22. package/dist/revm.js +5 -19
  23. package/dist/revm.js.map +1 -1
  24. package/dist/state-manager.d.ts +256 -18
  25. package/dist/state-manager.d.ts.map +1 -1
  26. package/dist/state-manager.js +429 -20
  27. package/dist/state-manager.js.map +1 -1
  28. package/dist/storage-keys.d.ts +8 -0
  29. package/dist/storage-keys.d.ts.map +1 -1
  30. package/dist/storage-keys.js +18 -2
  31. package/dist/storage-keys.js.map +1 -1
  32. package/dist/types.d.ts +150 -33
  33. package/dist/types.d.ts.map +1 -1
  34. package/dist/worker-client.d.ts.map +1 -1
  35. package/dist/worker-client.js +20 -12
  36. package/dist/worker-client.js.map +1 -1
  37. package/dist/worker-host.d.ts.map +1 -1
  38. package/dist/worker-host.js +17 -9
  39. package/dist/worker-host.js.map +1 -1
  40. package/dist/worker-rpc-error.d.ts +21 -0
  41. package/dist/worker-rpc-error.d.ts.map +1 -0
  42. package/dist/worker-rpc-error.js +121 -0
  43. package/dist/worker-rpc-error.js.map +1 -0
  44. package/package.json +3 -1
  45. package/src/derived-trie.ts +214 -0
  46. package/src/engine.ts +2 -3
  47. package/src/index.ts +2 -1
  48. package/src/node.ts +1318 -136
  49. package/src/revm-state-store.ts +47 -13
  50. package/src/revm.ts +11 -25
  51. package/src/state-manager.ts +515 -21
  52. package/src/storage-keys.ts +21 -2
  53. package/src/types.ts +152 -34
  54. package/src/worker-client.ts +22 -12
  55. package/src/worker-host.ts +17 -9
  56. package/src/worker-rpc-error.ts +139 -0
package/src/types.ts CHANGED
@@ -61,20 +61,6 @@ export interface PersistenceAdapter {
61
61
  save(state: SerializedState): Promise<void>;
62
62
  }
63
63
 
64
- /**
65
- * State backing mode.
66
- * - `'none'` (DEFAULT): `SimpleStateManager` — plain Maps, NO trie, NO state root.
67
- * The fast path; block `stateRoot`/`receiptsRoot`/`transactionsRoot` are zero
68
- * placeholders (you are a local chain; canonical roots aren't needed). This is
69
- * the recommended mode and what makes the node ~4× faster than the trie path.
70
- * - `'trie'`: `MerkleStateManager` — real Merkle-Patricia trie. SLOWER (recomputes
71
- * the state root each tx) but produces a REAL `stateRoot`, which (a) lets the
72
- * node be conformance-tested against `ethereum/tests` GeneralStateTests (they
73
- * verify the post-state root), and (b) gives honest canonical block roots for
74
- * consumers that need them. Opt-in: pay for the trie only when you want it.
75
- */
76
- export type StateMode = 'none' | 'trie';
77
-
78
64
  /**
79
65
  * Sender-derivation mode.
80
66
  * - `'recover'` (DEFAULT): derive the sender from the signature with ecrecover,
@@ -351,12 +337,6 @@ export interface EngineContext {
351
337
  * rather than an engine-side option to remember to pass.
352
338
  */
353
339
  getBlockHash(blockNumber: bigint): Uint8Array | undefined;
354
- /**
355
- * The node's state mode. An engine that cannot serve it must THROW here —
356
- * `connect` is called during `createNode()`, so the refusal lands at
357
- * construction rather than at the first opcode.
358
- */
359
- readonly stateMode: StateMode;
360
340
  }
361
341
 
362
342
  /**
@@ -479,9 +459,28 @@ export interface EngineInfo {
479
459
  export interface NodeOptions {
480
460
  /** EIP-155 chain id. Default 31337 (anvil/hardhat-style local). */
481
461
  chainId?: number;
482
- /** State backing: `'none'` (fast, no trie/root — default) or `'trie'` (real
483
- * state root, slower; unlocks GeneralStateTests conformance). */
484
- stateMode?: StateMode;
462
+ /**
463
+ * Whether the node computes a STATE ROOT. Default `false`. EVERY node runs on
464
+ * the same state (our `SimpleStateManager` subclass: plain Maps, no trie);
465
+ * this only decides whether a trie is DERIVED from it.
466
+ * - `false` (DEFAULT): no trie, no state root, no trie work. Block
467
+ * `stateRoot`/`receiptsRoot`/`transactionsRoot` are zero placeholders (you
468
+ * are a local chain; canonical roots aren't needed) and `getStateRoot()`
469
+ * throws.
470
+ * - `true`: additionally keep a Merkle-Patricia trie derived from the state,
471
+ * updated at the end of each block from the keys the block changed, and
472
+ * report its REAL root in each block header and from `getStateRoot()`. That
473
+ * (a) lets the node be conformance-tested against `ethereum/tests`
474
+ * GeneralStateTests (they verify the post-state root), and (b) gives honest
475
+ * canonical block roots for consumers that need them. Execution never reads
476
+ * the trie, so it works on every engine (revm included) and behaves exactly
477
+ * as a node without it in every other respect. See
478
+ * `docs/adr/0014-the-trie-is-derived-from-the-flat-state-not-a-state-manager.md`.
479
+ *
480
+ * Only `true` turns it on; any other value (absent, `false`, or a non-boolean
481
+ * passed from untyped code) leaves it off.
482
+ */
483
+ computeStateRoot?: boolean;
485
484
  /**
486
485
  * Sender derivation: `'recover'` (ecrecover, authenticated — DEFAULT) or
487
486
  * `'trusted'` (skip ecrecover, trust a caller-supplied `from`). See
@@ -513,11 +512,44 @@ export interface NodeOptions {
513
512
  /**
514
513
  * Full genesis pre-state (address -> {balance, nonce, code, storage}). Richer
515
514
  * than `initialBalances` (which only sets balance). Used to load an arbitrary
516
- * starting state — e.g. a GeneralStateTest `pre` section — so that, in
517
- * `stateMode:'trie'`, `getStateRoot()` after a tx can be compared to the
515
+ * starting state (e.g. a GeneralStateTest `pre` section) so that, with
516
+ * `computeStateRoot: true`, `getStateRoot()` after a tx can be compared to the
518
517
  * fixture's expected post-state root. Applied at genesis, before block 0.
519
518
  */
520
519
  initialState?: Record<string, GenesisAccount>;
520
+ /**
521
+ * The TIMESTAMP OF THE GENESIS BLOCK (block 0), in seconds since the epoch: the
522
+ * same unit and type as {@link BlockEnv.timestamp} and the header field.
523
+ * ABSENT MEANS THE WALL CLOCK, in whole seconds at construction, which is what
524
+ * block 0 has always carried.
525
+ *
526
+ * Why it exists: genesis is otherwise the one block a consumer cannot pin, so
527
+ * two nodes running the same chain, created in different seconds, report
528
+ * different hashes for every block. With this set (and `blockEnv.timestamp`
529
+ * pinning the mined blocks), the same chain produces the same hashes and a
530
+ * byte-identical `dumpState`.
531
+ *
532
+ * INDEPENDENT OF `blockEnv`, which still does not touch genesis's timestamp:
533
+ * `blockEnv` pins every MINED block's environment to one fixed value, and
534
+ * stretching it to genesis would stamp block 0 and every block after it alike.
535
+ * The converse holds too: this option moves ONLY block 0. A `genesisTimestamp`
536
+ * in the future does not move mined blocks, which keep the wall clock (or
537
+ * `blockEnv.timestamp`), so a mined block can then carry an EARLIER timestamp
538
+ * than genesis.
539
+ *
540
+ * A NEW GENESIS ONLY: a state loaded with `loadState` (or restored by
541
+ * `persistence` at construction) brings its own block 0, timestamp included,
542
+ * and that one wins. A `dumpState` carries the timestamp like every other
543
+ * header field.
544
+ *
545
+ * Must be a non-negative bigint; anything else (a number, a string, a negative
546
+ * bigint) throws at construction naming this option. It is not bounded above,
547
+ * the same as `blockEnv.timestamp`, but a dump records every block's timestamp
548
+ * as a JS number, so only a value up to `Number.MAX_SAFE_INTEGER` survives a
549
+ * `dumpState` / `loadState` round trip exactly (any real date does). It crosses `createWorkerNode` like every
550
+ * other option (a bigint structured-clones).
551
+ */
552
+ genesisTimestamp?: bigint;
521
553
  /**
522
554
  * Override the header fields of MINED blocks. Lets a consumer run a tx under a
523
555
  * specific block environment (coinbase, base fee, number, timestamp,
@@ -553,6 +585,39 @@ export interface NodeOptions {
553
585
  * `docs/adr/0006-the-engine-is-an-injected-object-not-a-named-string.md`.
554
586
  */
555
587
  engine?: Engine;
588
+ /**
589
+ * OPT-IN, BOUNDED STATE HISTORY. With `{blocks: N}` the node answers
590
+ * `eth_getBalance`, `eth_getCode`, `eth_getStorageAt` and
591
+ * `eth_getTransactionCount` pinned to any of the last N blocks below the head
592
+ * (and the head) exactly as they answered when that block was the head. A
593
+ * block older than `head - N` is refused with `-32000 historical state not
594
+ * available`, naming the oldest block it can serve. `eth_call` and
595
+ * `eth_estimateGas` pinned to a block in the window EXECUTE at it: against
596
+ * its state and its block environment, with state overrides on top. The
597
+ * history is carried by `dumpState` / `loadState` (so IndexedDB persistence
598
+ * keeps the window across a reload).
599
+ *
600
+ * ABSENT MEANS OFF, and there is no default window: a node without it behaves
601
+ * exactly as before (the head is served, anything below it refused) and pays
602
+ * nothing. `N` must be a positive safe integer; anything else throws at
603
+ * construction. It composes with `computeStateRoot: true`.
604
+ *
605
+ * THE COST is memory per changed key per retained block: the node keeps, for
606
+ * each of the last N blocks, the value every account, code entry and storage
607
+ * slot the block changed had before it (an undo log over the one flat state).
608
+ * Measured: about 300 bytes per changed key per retained block, and a
609
+ * historical `eth_call` costs about 0.8 microseconds per distinct key changed
610
+ * since the block it is pinned to; the README's "What it costs" section has a
611
+ * sizing example, from `docs/spikes/bounded-state-history-cost/results.md`.
612
+ * See `docs/adr/0013-bounded-state-history-is-an-undo-log-over-the-flat-state.md`.
613
+ */
614
+ stateHistory?: StateHistoryOptions;
615
+ }
616
+
617
+ /** See {@link NodeOptions.stateHistory}. */
618
+ export interface StateHistoryOptions {
619
+ /** How many blocks below the head stay readable: a positive safe integer. */
620
+ blocks: number;
556
621
  }
557
622
 
558
623
  /** A full genesis account (all fields optional except an implicit zero default). */
@@ -586,13 +651,14 @@ export interface SlimNode {
586
651
  /** Subscribe to newHeads locally (used by eth_subscribe and consumers). */
587
652
  onNewHead(cb: (head: {number: number; hash: string}) => void): () => void;
588
653
  /**
589
- * Current canonical state root. In `'trie'` mode this is the REAL
590
- * Merkle-Patricia root (usable for GeneralStateTests conformance); in `'none'`
591
- * mode the trie is absent so this throws (honest — there is no root to give).
654
+ * Current canonical state root. With `computeStateRoot: true` this is the REAL
655
+ * Merkle-Patricia root of the current state, `evm_set*` cheats since the last
656
+ * block included (usable for GeneralStateTests conformance); without it there
657
+ * is no trie so this throws (honest: there is no root to give).
592
658
  */
593
659
  getStateRoot(): Promise<string>;
594
- /** The state mode this node was created with. */
595
- readonly stateMode: 'none' | 'trie';
660
+ /** Whether this node computes a state root (its `computeStateRoot` option). */
661
+ readonly computeStateRoot: boolean;
596
662
  /** The sender mode this node was created with. */
597
663
  readonly senderMode: SenderMode;
598
664
  /**
@@ -647,13 +713,23 @@ export interface ServedPort {
647
713
  * every IndexedDB record in the wild for a format they can still be read as. Bump
648
714
  * it when a dump stops being loadable by the code that wrote it, which is the only
649
715
  * question `version` can usefully answer.
716
+ *
717
+ * The same holds for `history` (2026-09-28, `state-history-persistence`): an
718
+ * OPTIONAL field, absent from every dump written before it and from every dump
719
+ * of a node without `stateHistory`, so it is still `version: 1`.
720
+ *
721
+ * And for a field REMOVED (2026-09-28, `rename-statemode-to-computestateroot`):
722
+ * dumps written before the node's `computeStateRoot` option replaced the old
723
+ * `'none' | 'trie'` mode option carry that mode as an informational string
724
+ * field. It is no longer written and it was never read, so such a dump loads
725
+ * unchanged with the field ignored (proved by `test/dumpstate-layout.spec.ts`'s
726
+ * fixture, which still carries it), and the format is still `version: 1`.
650
727
  */
651
728
  export interface SerializedState {
652
729
  version: 1;
653
730
  chainId: number;
654
- /** State mode the dump was produced in (informational). */
655
- stateMode?: 'none' | 'trie';
656
- /** SimpleStateManager Maps: address -> hex-encoded account/code/storage. */
731
+ /** The node's state, on every node: address -> hex-encoded account/code/storage.
732
+ * A `computeStateRoot` node's trie is not serialised; `loadState` rebuilds it. */
657
733
  accounts: Record<string, string>; // addr -> rlp/hex account
658
734
  code: Record<string, string>; // addr -> code hex
659
735
  storage: Record<string, Record<string, string>>; // addr -> (slot hex -> value hex)
@@ -663,6 +739,48 @@ export interface SerializedState {
663
739
  receipts: Record<string, SerializedReceipt>;
664
740
  /** Raw tx + meta keyed by tx hash (for eth_getTransactionByHash). */
665
741
  transactions: Record<string, SerializedTx>;
742
+ /**
743
+ * The `stateHistory` UNDO LOG, oldest first: one record per retained block,
744
+ * holding the value every key that block changed had at the END of the block
745
+ * before it (ADR 0013). Written only by a node created with `stateHistory`
746
+ * (possibly empty), and read only by one: a node without the option ignores it.
747
+ *
748
+ * OPTIONAL, and absent means "no history": a dump written before this field
749
+ * existed loads with history starting at its head, as it always did. A dump
750
+ * carrying more blocks than the loading node's window is truncated to that
751
+ * window; one carrying fewer serves what it has. `loadState` restores the
752
+ * CONTIGUOUS run of records ending at the dump's head block and drops anything
753
+ * older than a gap, since a read below a gap would be answered from a later
754
+ * state than the one asked for.
755
+ */
756
+ history?: SerializedHistoryBlock[];
757
+ }
758
+
759
+ /**
760
+ * One block's undo record in {@link SerializedState.history}, hex-encoded like
761
+ * the rest of the dump. Every map is keyed by `0x` lowercase hex (addresses of
762
+ * 20 bytes, slots of 32), and `null` means the key was ABSENT at the end of the
763
+ * block before (`number - 1`): no account, no code, an unset slot. That is not
764
+ * the same as an empty value, and a loader must not conflate them: an absent
765
+ * account reads as absent (EXTCODEHASH zero), an existing empty one does not.
766
+ */
767
+ export interface SerializedHistoryBlock {
768
+ /** The block this record undoes: its keys' values are the ones before it. */
769
+ number: number;
770
+ /** Account RLP (as in {@link SerializedState.accounts}), or `null` if absent. */
771
+ accounts: Record<string, string | null>;
772
+ /** Code hex, or `null` if the address had none. */
773
+ code: Record<string, string | null>;
774
+ /** Address -> (slot -> value hex, or `null` if the slot was unset). */
775
+ storage: Record<string, Record<string, string | null>>;
776
+ /**
777
+ * Addresses whose storage the block CLEARED (creation over storage,
778
+ * `SELFDESTRUCT`, EIP-161 removal). The clear also recorded every slot the
779
+ * account held in `storage`, so this marker restores no value on its own: it
780
+ * tells a historical `eth_call` to clear the account's live storage before
781
+ * applying those slots, dropping the ones written since.
782
+ */
783
+ storageCleared: string[];
666
784
  }
667
785
 
668
786
  export interface SerializedBlock {
@@ -673,7 +791,7 @@ export interface SerializedBlock {
673
791
  gasUsed: string;
674
792
  gasLimit: string;
675
793
  baseFeePerGas: string;
676
- /** Real Merkle-Patricia state root in `'trie'` mode; zero placeholder in `'none'`. */
794
+ /** Real Merkle-Patricia state root with `computeStateRoot: true`; zero placeholder without. */
677
795
  stateRoot: string;
678
796
  /**
679
797
  * The block's coinbase, under the name `eth_getBlockByNumber` reports it. Named
@@ -11,6 +11,9 @@ import {wrap, proxy, transfer, releaseProxy, type Remote} from 'comlink';
11
11
  // own `exposeNode({createEngine})` module. Type-only, so nothing is imported at
12
12
  // runtime and no `expose()` side effect is dragged onto the main thread.
13
13
  import type {NodeWorkerApi} from './worker-host.js';
14
+ // ...and the ONE runtime import besides comlink: rebuilding an `RpcError` the
15
+ // worker sent, which comlink alone would deliver without its `code` and `data`.
16
+ import {receivingRpcErrors} from './worker-rpc-error.js';
14
17
  import type {
15
18
  NodeOptions,
16
19
  SlimNode,
@@ -75,26 +78,33 @@ export async function createWorkerNode(
75
78
  }
76
79
  const api = wrap<NodeWorkerApi>(worker);
77
80
  const remote = await api.createNode(nodeOptions);
78
- // stateMode/senderMode/engine are plain values on the node; over comlink
81
+ // computeStateRoot/senderMode/engine are plain values on the node; over comlink
79
82
  // they read as promises.
80
83
  //
81
84
  // NO `as any` HERE, and that is load-bearing. The remote is a `SlimNode` (the
82
85
  // one proxy in ./worker-host.ts is typed as one), so these three reads are
83
86
  // CHECKED: `senderMode` was silently absent from that proxy for a month, and
84
87
  // what hid it from the compiler was the cast that used to be on this line.
85
- const stateMode = await remote.stateMode;
88
+ const computeStateRoot = await remote.computeStateRoot;
86
89
  const senderMode = await remote.senderMode;
87
90
  const engineInfo = await remote.engine;
88
91
 
92
+ // EVERY ASYNC METHOD IS WRAPPED IN `receivingRpcErrors`, the other half of the
93
+ // host proxy's `sendingRpcErrors`: an `RpcError` the node raises reaches the
94
+ // caller as a real `RpcError` with its `code` and `data`, the same error a
95
+ // main-thread node rejects with (./worker-rpc-error.ts). Any other error is
96
+ // comlink's, unchanged.
89
97
  return {
90
- request: (args: RequestArguments) => remote.request(args),
91
- mine: () => remote.mine(),
92
- dumpState: () => remote.dumpState(),
93
- loadState: (s: SerializedState) => remote.loadState(s),
94
- stateMode,
98
+ request: receivingRpcErrors((args: RequestArguments) =>
99
+ remote.request(args),
100
+ ),
101
+ mine: receivingRpcErrors(() => remote.mine()),
102
+ dumpState: receivingRpcErrors(() => remote.dumpState()),
103
+ loadState: receivingRpcErrors((s: SerializedState) => remote.loadState(s)),
104
+ computeStateRoot,
95
105
  senderMode,
96
106
  engine: engineInfo,
97
- getStateRoot: () => remote.getStateRoot(),
107
+ getStateRoot: receivingRpcErrors(() => remote.getStateRoot()),
98
108
  onNewHead(cb) {
99
109
  // The callback must cross the thread boundary as a comlink proxy.
100
110
  let unsub: (() => void) | undefined;
@@ -105,7 +115,7 @@ export async function createWorkerNode(
105
115
  void unsub?.();
106
116
  };
107
117
  },
108
- async serveOn(port: MessagePort) {
118
+ serveOn: receivingRpcErrors(async (port: MessagePort) => {
109
119
  // TRANSFERRED, never cloned: a MessagePort cannot be cloned at all, and the
110
120
  // point is that the port now belongs to the node's worker, so a consumer
111
121
  // holding the other end reaches that worker without this thread in between.
@@ -122,12 +132,12 @@ export async function createWorkerNode(
122
132
  served[releaseProxy]();
123
133
  },
124
134
  };
125
- },
135
+ }),
126
136
  // Terminating the worker also ends every port it was serving: a consumer's
127
137
  // requests then get no answer, as they would from a stopped port.
128
- async dispose() {
138
+ dispose: receivingRpcErrors(async () => {
129
139
  await remote.dispose();
130
140
  worker.terminate();
131
- },
141
+ }),
132
142
  };
133
143
  }
@@ -47,6 +47,7 @@
47
47
  import {expose, proxy} from 'comlink';
48
48
  import {createNode} from './node.js';
49
49
  import type {Engine, NodeOptions, SlimNode} from './types.js';
50
+ import {sendingRpcErrors} from './worker-rpc-error.js';
50
51
 
51
52
  /**
52
53
  * Builds the {@link Engine} for ONE node, on the thread that will run it.
@@ -92,17 +93,24 @@ export interface WorkerHostOptions {
92
93
  * (which a bare `SlimNode` annotation would let through, since it demands only
93
94
  * the required members). `SlimNode` has no optional members today, so this costs
94
95
  * nothing now and stops the one thing the guarantee otherwise missed. The plain
95
- * values (`stateMode`, `senderMode`, `engine`) clone across as-is; the client
96
+ * values (`computeStateRoot`, `senderMode`, `engine`) clone across as-is; the client
96
97
  * reads them off the remote as promises.
98
+ *
99
+ * EVERY ASYNC METHOD IS WRAPPED IN {@link sendingRpcErrors}, so an `RpcError` it
100
+ * throws crosses with its `code` and `data` (comlink alone keeps only the
101
+ * message; `./worker-rpc-error.ts` has why, and why this is not a comlink
102
+ * transfer handler). All of them, not only `request`: `getStateRoot` raises
103
+ * `-32004`, and a method that raises none today costs nothing to cover.
104
+ * `onNewHead` is the exception because it is synchronous and throws nothing.
97
105
  */
98
106
  function nodeProxy(node: SlimNode): SlimNode {
99
107
  const forwarded: Required<SlimNode> = {
100
- request: (args) => node.request(args),
101
- mine: () => node.mine(),
102
- dumpState: () => node.dumpState(),
103
- loadState: (state) => node.loadState(state),
104
- getStateRoot: () => node.getStateRoot(),
105
- stateMode: node.stateMode,
108
+ request: sendingRpcErrors((args) => node.request(args)),
109
+ mine: sendingRpcErrors(() => node.mine()),
110
+ dumpState: sendingRpcErrors(() => node.dumpState()),
111
+ loadState: sendingRpcErrors((state) => node.loadState(state)),
112
+ getStateRoot: sendingRpcErrors(() => node.getStateRoot()),
113
+ computeStateRoot: node.computeStateRoot,
106
114
  senderMode: node.senderMode,
107
115
  engine: node.engine,
108
116
  // newHeads over comlink: the callback arrives as a comlink proxy, and the
@@ -112,8 +120,8 @@ function nodeProxy(node: SlimNode): SlimNode {
112
120
  // thread's: the node serves it right here, and a consumer holding the other
113
121
  // end talks to this worker directly. The handle going back carries a
114
122
  // function, so it crosses as a proxy, like the unsubscribe above.
115
- serveOn: async (port) => proxy(await node.serveOn(port)),
116
- dispose: () => node.dispose(),
123
+ serveOn: sendingRpcErrors(async (port) => proxy(await node.serveOn(port))),
124
+ dispose: sendingRpcErrors(() => node.dispose()),
117
125
  };
118
126
  return forwarded;
119
127
  }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * worker-rpc-error.ts: HOW AN `RpcError` CROSSES THE WORKER BOUNDARY WHOLE.
3
+ * Shared by the two ends of it: `./worker-host.ts` (the node's thread) turns a
4
+ * thrown `RpcError` into a plain {@link WireRpcError}, and `./worker-client.ts`
5
+ * (the caller's thread) turns that back into a real `RpcError`.
6
+ *
7
+ * WHY IT IS NEEDED. comlink carries a thrown `Error` across as
8
+ * `{message, name, stack}` and nothing else (its built-in `throw` transfer
9
+ * handler), so every `RpcError` a worker-hosted node raised used to reach the
10
+ * caller with `code === undefined` and no `data`: a `-32000` refusal, a `-32601`
11
+ * method not found, and above all a `3 execution reverted` whose `data` is the
12
+ * revert payload a viem client decodes into a custom error. A node served over a
13
+ * port (`node.serveOn`, through `@eip-1193/over-port`) never had the gap, so the
14
+ * two worker transports disagreed, and a worker node was not interchangeable
15
+ * with a main-thread one for anything that branches on `code`.
16
+ *
17
+ * THE CHOICE: THROW A PLAIN OBJECT, NOT AN `Error`, AND TOUCH NO COMLINK STATE.
18
+ * comlink's `throw` handler passes a thrown NON-Error value through structured
19
+ * clone unchanged and rethrows it as-is on the other side. So the host throws
20
+ * `{name: 'RpcError', code, message, data, stack}` in place of the `RpcError`,
21
+ * which crosses with every field, and the client rebuilds the `RpcError` from it.
22
+ * Rejected alternatives, and why:
23
+ *
24
+ * - A custom comlink transfer handler (or replacing the built-in `throw` one).
25
+ * comlink's `transferHandlers` is a MODULE-GLOBAL map, so registering one
26
+ * changes error handling for every other comlink use in the consumer's app,
27
+ * which this package does not own (and a consumer's own `throw` handler, set
28
+ * before or after ours, would silently win or lose).
29
+ * - An envelope (`{ok: value}` / `{error: {...}}`) returned by every proxied
30
+ * method. Also global-state-free, but it rewraps EVERY SUCCESSFUL answer and
31
+ * changes every method's return type on the wire, which breaks the
32
+ * `Required<SlimNode>` typing of the host proxy the client relies on. The
33
+ * thrown object only changes the failure path, and only for `RpcError`.
34
+ *
35
+ * WHAT A DIRECT COMLINK CONSUMER SEES. Someone who `wrap()`s the worker-host api
36
+ * themselves instead of using `createWorkerNode` now gets the plain object as the
37
+ * rejection rather than an `Error` with only a message: it carries `code`,
38
+ * `message` and `data` at the top level, so code reading `e.code` / `e.message`
39
+ * works, and `e instanceof Error` does not. Every other error (a plain `Error`, a
40
+ * `RangeError` from malformed input, the misused-`createEngine` refusal) is
41
+ * left to comlink's own handling, exactly as before.
42
+ *
43
+ * `data` MUST BE STRUCTURED-CLONEABLE, as any value crossing a thread is. Every
44
+ * `data` this package raises is (a hex string, or absent); a non-cloneable one
45
+ * makes comlink report its own "Unserializable return value" instead.
46
+ */
47
+ import {RpcError} from './types.js';
48
+
49
+ /** An `RpcError` rendered as a plain, structured-cloneable value. */
50
+ export interface WireRpcError {
51
+ /** The marker the client recognises it by (with a numeric `code`). */
52
+ webevmRpcError: true;
53
+ name: 'RpcError';
54
+ code: number;
55
+ message: string;
56
+ data: unknown;
57
+ stack?: string;
58
+ }
59
+
60
+ /**
61
+ * An `RpcError`, by class or by shape: a consumer's engine may throw one built
62
+ * from ANOTHER copy of this package, which fails `instanceof` but is the same
63
+ * error. The name AND a numeric code are required, since a numeric `code` alone
64
+ * is also what a `DOMException` has.
65
+ */
66
+ function isRpcError(e: unknown): e is RpcError {
67
+ return (
68
+ e instanceof RpcError ||
69
+ (e instanceof Error &&
70
+ e.name === 'RpcError' &&
71
+ typeof (e as {code?: unknown}).code === 'number')
72
+ );
73
+ }
74
+
75
+ function isWireRpcError(e: unknown): e is WireRpcError {
76
+ return (
77
+ typeof e === 'object' &&
78
+ e !== null &&
79
+ (e as {webevmRpcError?: unknown}).webevmRpcError === true &&
80
+ typeof (e as {code?: unknown}).code === 'number' &&
81
+ typeof (e as {message?: unknown}).message === 'string'
82
+ );
83
+ }
84
+
85
+ /** HOST SIDE: an `RpcError` becomes a {@link WireRpcError}; anything else is unchanged. */
86
+ function toWire(e: unknown): unknown {
87
+ if (!isRpcError(e)) return e;
88
+ const wire: WireRpcError = {
89
+ webevmRpcError: true,
90
+ name: 'RpcError',
91
+ code: e.code,
92
+ message: e.message,
93
+ data: e.data,
94
+ };
95
+ if (typeof e.stack === 'string') wire.stack = e.stack;
96
+ return wire;
97
+ }
98
+
99
+ /** CLIENT SIDE: a {@link WireRpcError} becomes a real `RpcError`; anything else is unchanged. */
100
+ function fromWire(e: unknown): unknown {
101
+ if (!isWireRpcError(e)) return e;
102
+ const error = new RpcError(e.code, e.message, e.data);
103
+ // The worker's stack, as comlink keeps it for a plain Error: it is where the
104
+ // error was raised, which is what a reader of the stack wants.
105
+ if (typeof e.stack === 'string') error.stack = e.stack;
106
+ return error;
107
+ }
108
+
109
+ /**
110
+ * HOST SIDE: `fn`, rejecting with a {@link WireRpcError} wherever it would have
111
+ * rejected with an `RpcError`. Every other rejection passes through untouched.
112
+ */
113
+ export function sendingRpcErrors<A extends unknown[], R>(
114
+ fn: (...args: A) => Promise<R>,
115
+ ): (...args: A) => Promise<R> {
116
+ return async (...args) => {
117
+ try {
118
+ return await fn(...args);
119
+ } catch (e) {
120
+ throw toWire(e);
121
+ }
122
+ };
123
+ }
124
+
125
+ /**
126
+ * CLIENT SIDE: `fn`, rejecting with a real `RpcError` wherever the worker sent a
127
+ * {@link WireRpcError}. Every other rejection passes through untouched.
128
+ */
129
+ export function receivingRpcErrors<A extends unknown[], R>(
130
+ fn: (...args: A) => Promise<R>,
131
+ ): (...args: A) => Promise<R> {
132
+ return async (...args) => {
133
+ try {
134
+ return await fn(...args);
135
+ } catch (e) {
136
+ throw fromWire(e);
137
+ }
138
+ };
139
+ }