@webevm/devnode 0.0.0-stage → 0.1.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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +221 -2
  3. package/dist/accounts.d.ts +82 -0
  4. package/dist/accounts.d.ts.map +1 -0
  5. package/dist/accounts.js +129 -0
  6. package/dist/accounts.js.map +1 -0
  7. package/dist/allocs.d.ts +26 -0
  8. package/dist/allocs.d.ts.map +1 -0
  9. package/dist/allocs.js +99 -0
  10. package/dist/allocs.js.map +1 -0
  11. package/dist/dev-node.d.ts +63 -0
  12. package/dist/dev-node.d.ts.map +1 -0
  13. package/dist/dev-node.js +166 -0
  14. package/dist/dev-node.js.map +1 -0
  15. package/dist/eip712.d.ts +23 -0
  16. package/dist/eip712.d.ts.map +1 -0
  17. package/dist/eip712.js +333 -0
  18. package/dist/eip712.js.map +1 -0
  19. package/dist/impersonation.d.ts +20 -0
  20. package/dist/impersonation.d.ts.map +1 -0
  21. package/dist/impersonation.js +95 -0
  22. package/dist/impersonation.js.map +1 -0
  23. package/dist/index.d.ts +11 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +8 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/send.d.ts +20 -0
  28. package/dist/send.d.ts.map +1 -0
  29. package/dist/send.js +385 -0
  30. package/dist/send.js.map +1 -0
  31. package/dist/sign.d.ts +14 -0
  32. package/dist/sign.d.ts.map +1 -0
  33. package/dist/sign.js +155 -0
  34. package/dist/sign.js.map +1 -0
  35. package/dist/worker-host.d.ts +87 -0
  36. package/dist/worker-host.d.ts.map +1 -0
  37. package/dist/worker-host.js +112 -0
  38. package/dist/worker-host.js.map +1 -0
  39. package/package.json +79 -3
  40. package/src/accounts.ts +218 -0
  41. package/src/allocs.ts +134 -0
  42. package/src/dev-node.ts +220 -0
  43. package/src/eip712.ts +390 -0
  44. package/src/impersonation.ts +119 -0
  45. package/src/index.ts +25 -0
  46. package/src/send.ts +469 -0
  47. package/src/sign.ts +199 -0
  48. package/src/worker-host.ts +151 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026-present Ronan Sandford
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,222 @@
1
- # Temporary Holding Version
1
+ # @webevm/devnode
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Dev accounts for [webevm](https://github.com/wighawag/webevm), the slim, execution-only, in-browser EIP-1193 node.
4
+
5
+ webevm's core holds no keys: it answers `eth_accounts`, `eth_sendTransaction` and every other account method with a real `-32601`, on purpose. That is right for an application with its own signing client, and not what a deploy tool or a test runner expects from a local chain. This package is the layer those tools need, on top of the core rather than inside it: a node that answers `eth_accounts` with the same test accounts anvil and Hardhat use, funded at genesis as theirs are, and forwards everything else to webevm unchanged.
6
+
7
+ This release covers the dev accounts, their funding, sending and signing with them (`eth_sendTransaction`, `eth_signTransaction`, `personal_sign`, `eth_sign`, `eth_signTypedData_v4`), impersonation (opt-in, on a `senderMode: 'trusted'` node), an alloc export for forge, and running in a Web Worker (keys on the main thread, or inside the worker).
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install webevm @webevm/devnode
13
+ ```
14
+
15
+ `webevm` is a peer dependency, so your app has exactly one copy of the node.
16
+
17
+ ## Usage
18
+
19
+ ```ts
20
+ import {createDevNode} from '@webevm/devnode';
21
+ import {createWalletClient, createPublicClient, custom} from 'viem';
22
+
23
+ const node = await createDevNode(); // anvil's ten accounts, 10,000 ETH each
24
+
25
+ const wallet = createWalletClient({transport: custom(node)});
26
+ const [deployer] = await wallet.getAddresses(); // 0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266
27
+
28
+ const client = createPublicClient({transport: custom(node)});
29
+ await client.getBalance({address: deployer}); // 10000000000000000000000n
30
+ ```
31
+
32
+ `createDevNode(options)` takes every [webevm `createNode` option](https://github.com/wighawag/webevm#readme) (`chainId`, `engine`, `persistence`, `senderMode`, ...) plus:
33
+
34
+ | option | default | meaning |
35
+ |---|---|---|
36
+ | `accounts` | anvil's ten | the dev accounts: `{mnemonic, count, path, initialIndex}`, a number (shorthand for `{count}`), or a list of 32-byte hex private keys |
37
+ | `balance` | 10,000 ETH | each dev account's genesis balance, in wei (a `bigint`) |
38
+ | `fund` | `true` | `false` funds no dev account (`fundAccounts` and `initialBalances` still apply) |
39
+ | `fundAccounts` | none | extra addresses to fund at genesis, address to wei (anvil's `--fund-accounts`) |
40
+ | `impersonation` | `false` | answer `hardhat_impersonateAccount` / `anvil_impersonateAccount` and send from impersonated addresses; creates the node with `senderMode: 'trusted'` (see [Impersonation](#impersonation)) |
41
+
42
+ The mnemonic defaults to `test test test test test test test test test test test junk`, the path to `m/44'/60'/0'/0` (account `i` is at `m/44'/60'/0'/0/{initialIndex + i}`), `count` to 10 and `initialIndex` to 0, exactly as on anvil and Hardhat, so an index-declared account (`deployer: 0`) resolves to the same address here as there. An invalid mnemonic, private key, count or index throws, naming the option.
43
+
44
+ ```ts
45
+ await createDevNode({accounts: {mnemonic: myMnemonic, count: 3}});
46
+ await createDevNode({accounts: [deployerKey, userKey], balance: 100n * 10n ** 18n});
47
+ await createDevNode({fundAccounts: {'0x...': 10n ** 18n}});
48
+ ```
49
+
50
+ ## Funded at genesis
51
+
52
+ The dev accounts' balances go into webevm's `initialBalances` when the node is created, so they are block 0's state, as on anvil and Hardhat: the accounts can send at once, and no balance is rewritten afterwards. The precedence, lowest first, is each dev account's `balance`, then `fundAccounts`, then your own `initialBalances` (compared case-insensitively).
53
+
54
+ Like every `initialBalances`, this applies to a NEW genesis only. A chain restored with `loadState(dump)`, or by `persistence` at construction, keeps its own balances. A dump of a dev chain contains the funded dev accounts, as anvil's state dumps do: they are genesis state.
55
+
56
+ ## Wrapping a node you already have
57
+
58
+ ```ts
59
+ import {createNode} from 'webevm';
60
+ import {wrapDevNode, devAccountBalances} from '@webevm/devnode';
61
+
62
+ const accounts = {mnemonic: myMnemonic};
63
+ const node = wrapDevNode(
64
+ await createNode({initialBalances: devAccountBalances({accounts})}),
65
+ {accounts},
66
+ );
67
+ ```
68
+
69
+ `wrapDevNode(node, {accounts})` FUNDS NOTHING, because genesis is decided when a node is created. To fund a node created elsewhere (a `createWorkerNode()` whose keys stay on the main thread, say), pass `devAccountBalances(options)` as its `initialBalances`: it returns exactly the balances `createDevNode` would fund for the same options.
70
+
71
+ ## In a Web Worker
72
+
73
+ webevm runs a node in a Worker with `createWorkerNode()` (`webevm/worker-client`) and `exposeNode()` (`webevm/worker-host`); both need `comlink`, an optional peer of webevm and of this package. The dev layer goes on either side of that boundary.
74
+
75
+ ### Keys on the main thread
76
+
77
+ ```ts
78
+ import {createWorkerNode} from 'webevm/worker-client';
79
+ import {wrapDevNode, devAccountBalances} from '@webevm/devnode';
80
+
81
+ const accounts = {mnemonic: myMnemonic};
82
+ const worker = new Worker(new URL('webevm/worker-entry', import.meta.url), {type: 'module'});
83
+ const node = wrapDevNode(
84
+ await createWorkerNode({worker, initialBalances: devAccountBalances({accounts})}),
85
+ {accounts},
86
+ );
87
+ ```
88
+
89
+ The EVM runs in the worker; the accounts, sends and signatures are answered on the main thread, which holds the keys. `wrapDevNode` funds nothing, so the genesis balances go to `createWorkerNode()` as its `initialBalances`, exactly the ones `createDevNode` would fund. Any worker module works, a plain `webevm/worker-entry` or your own `exposeNode({createEngine})` one. For impersonation, create the worker node with `senderMode: 'trusted'` as well.
90
+
91
+ ### Keys in the worker
92
+
93
+ ```ts
94
+ // dev-worker.ts
95
+ import {exposeDevNode} from '@webevm/devnode/worker-host';
96
+ import {createRevmEngine} from 'webevm/revm'; // optional: omit createEngine for the default engine
97
+ import wasm from 'revm-wasm/revm.wasm';
98
+
99
+ exposeDevNode({
100
+ createEngine: () => createRevmEngine({wasm}),
101
+ accounts: {mnemonic: myMnemonic},
102
+ impersonation: true,
103
+ });
104
+ ```
105
+
106
+ ```ts
107
+ // main thread: webevm's own client, unchanged
108
+ import {createWorkerNode} from 'webevm/worker-client';
109
+
110
+ const worker = new Worker(new URL('./dev-worker.ts', import.meta.url), {type: 'module'});
111
+ const node = await createWorkerNode({worker, chainId: 31337});
112
+ await node.request({method: 'eth_accounts'}); // the dev accounts, answered in the worker
113
+ ```
114
+
115
+ `exposeDevNode(options)` takes `createEngine` (as `webevm/worker-host`'s `exposeNode` does) and the dev options `accounts`, `balance`, `fund`, `fundAccounts` and `impersonation`. It hands webevm's worker host a node factory, so each `createWorkerNode()` creates the node in the worker with `createDevNode({...mainThreadOptions, ...devOptions})`: the genesis is funded there, and the keys and the mnemonic are written in the worker module and never cross to the main thread. Every other option (`chainId`, `miningConfig`, `senderMode`, `initialBalances`, ...) is the main thread's, passed to `createWorkerNode()` as usual, and its `initialBalances` still win over the dev funding for the same address (which is why `initialBalances` is not an `exposeDevNode` option: the worker funds extra addresses with `fundAccounts`). The node crosses the boundary through webevm's own proxy, so every `SlimNode` member works, and an error the layer raises (`4100` for an address it holds no key for, say) reaches the main thread as a real `RpcError` with its `code`.
116
+
117
+ A bad mnemonic, key, count or `balance` does not throw from `exposeDevNode` (a throw while the worker module evaluates would leave `createWorkerNode()` pending forever): it is logged in the worker at once, and `createWorkerNode()` rejects with the same message. A bad `createEngine` is reported the same way, by webevm. Call `exposeDevNode` once per worker and await nothing at the module's top level before it, as with `exposeNode`. `createDevNodeWorkerApi(options)` returns the same api without exposing it, to compose into a larger comlink api of your own.
118
+
119
+ **Which one serves `serveOn`'s ports.** A layer on the MAIN thread over a worker proxy serves its ports from the main thread (it must, to answer the account methods there), so a consumer holding the other end of a port reaches the worker through the main thread: that shape gives up `serveOn`'s worker-to-worker path. The layer inside the worker keeps it: the port is transferred to the worker, which answers the account methods itself.
120
+
121
+ This needs a `webevm` with `exposeNode`'s node factory (`>=0.10.0`, the peer minimum). On an older webevm the factory would be ignored silently, and the worker would run a plain node with no dev accounts.
122
+
123
+ ## Sending from a dev account
124
+
125
+ ```ts
126
+ const hash = await wallet.sendTransaction({account: deployer, to, value: 1n, chain: null});
127
+ // or, raw: node.request({method: 'eth_sendTransaction', params: [{from: deployer, to, value: '0x1'}]})
128
+ ```
129
+
130
+ `eth_sendTransaction` with a dev account's `from` fills what the request leaves out, signs with that account's key, submits it to the node, and returns the hash. Under auto mining it is mined before the call returns, like any submitted transaction.
131
+
132
+ **What is filled, and only that.** The nonce from the pending nonce (`eth_getTransactionCount` at `pending`, so a send queued behind an unmined one gets the next nonce); `gas` from `eth_estimateGas` on the same request (its access list and authorization list are charged); the fees from the node's fee market as `eth_fillTransaction` fills them: `maxPriorityFeePerGas` is the node's priority fee and `maxFeePerGas` its base fee plus that, or `gasPrice` from `eth_gasPrice` for a legacy transaction. A field you name is sent as named, a stale `nonce` included (which the node then refuses as a replay).
133
+
134
+ **The type follows the fields, and nothing is dropped.** A `gasPrice` sends type 0, or type 1 with an `accessList`; an `authorizationList` sends type 4 (EIP-7702, which the node refuses before Prague, in its own words); anything else is type 2, carrying any `accessList`. An explicit `type` (0, 1, 2 or 4) is honoured. Unlike `eth_fillTransaction`, which drops an access list, a request that cannot be sent as named is refused with `-32602` rather than trimmed: `gasPrice` alongside EIP-1559 fees or an authorization list, an access list on type 0, blob (type 3) fields, `data` and `input` that differ, or a `chainId` that is not the node's.
135
+
136
+ **One at a time.** Each send is filled, signed and submitted as one operation on a queue, so concurrent sends from one account get consecutive nonces.
137
+
138
+ **From an account the node holds no key for**, the request is refused with `4100` (EIP-1193's "Unauthorized"), naming the remedies: configure its key in `accounts`, or impersonate it (with the `impersonation` option on, the message names `hardhat_impersonateAccount` for that address). Nothing is sent and nothing moves.
139
+
140
+ ### The two send paths, by `senderMode`
141
+
142
+ | node | how a dev account's transaction is submitted |
143
+ |---|---|
144
+ | `senderMode: 'recover'` (the default) | `eth_sendRawTransaction(raw)`: the node recovers the sender from the signature, as for any client |
145
+ | `senderMode: 'trusted'` | `evm_sendRawTransactionAs(raw, from)`: the node is told the sender and skips the recovery, which is cheaper |
146
+
147
+ Either way the transaction carries the account's REAL signature. So a chain built on a `'trusted'` dev node is still ordinary chain history: its transactions (`dumpState().transactions[hash].raw`) replay on a `'recover'` node, or any other node of the same chain ID, under the same hash and sender. [ADR 0002](https://github.com/wighawag/webevm/blob/main/docs/adr/0002-trusted-sender-is-a-primitive-impersonation-is-not-our-job.md)'s portability caveat is about fabricated signatures only, which the dev accounts never use. Signing is deterministic (RFC 6979), so the same request on the same state is the same transaction in either mode.
148
+
149
+ ## Signing with a dev account
150
+
151
+ ```ts
152
+ const signature = await wallet.signMessage({account: deployer, message: 'Sign in to example.org'});
153
+ const permit = await wallet.signTypedData({account: deployer, domain, types, primaryType: 'Permit', message});
154
+ const raw = await wallet.signTransaction({account: deployer, to, value: 1n, chain: null});
155
+ ```
156
+
157
+ | method | parameters | signs |
158
+ |---|---|---|
159
+ | `personal_sign` | `[message, address]` (MetaMask's and geth's order) | the EIP-191 personal message: `0x` hex as the bytes it spells, any other string as UTF-8 text, as MetaMask reads it |
160
+ | `eth_sign` | `[address, message]` (geth's order) | the same EIP-191 personal message, `message` as `0x` hex; never a raw hash |
161
+ | `eth_signTypedData_v4` | `[address, typedData]`, an object or its JSON text | the EIP-712 digest of `typedData` |
162
+ | `eth_signTransaction` | `[request]` | the transaction `eth_sendTransaction` would send for the same request, filled the same way; it returns the raw signed transaction as hex and submits nothing (pass it to `eth_sendRawTransaction`) |
163
+
164
+ A signature is the 65 bytes `r ‖ s ‖ v` with `v` 27 or 28, as viem, MetaMask and geth return it, deterministic (RFC 6979) and low-`s`: the same message signs to the same bytes as viem's `privateKeyToAccount(key).signMessage` / `signTypedData`. The EIP-712 encoder is this package's own (no dependency): referenced types sorted by name in the type encoding, nested structs, fixed and dynamic arrays (nested too), `bytes` and `string` hashed, every `intN` / `uintN` / `bytesN`, `bool` and `address`. A missing `EIP712Domain` type is derived from the domain's fields, as viem and ethers derive it; a value that does not fit its type (a missing member, an integer out of range, a `bytesN` of the wrong length) is refused with `-32602` naming its path, never coerced.
165
+
166
+ An address the node holds no key for is refused with `4100`, naming the `accounts` option. Nothing is ever signed for an address without its key, an impersonated one included.
167
+
168
+ ## Impersonation
169
+
170
+ ```ts
171
+ const node = await createDevNode({impersonation: true, fundAccounts: {[whale]: 10n ** 21n}});
172
+ await node.request({method: 'hardhat_impersonateAccount', params: [whale]});
173
+ await node.request({method: 'eth_sendTransaction', params: [{from: whale, to, value: '0x1'}]});
174
+ await node.request({method: 'hardhat_stopImpersonatingAccount', params: [whale]});
175
+ ```
176
+
177
+ Off by default. With `impersonation: true`, `hardhat_impersonateAccount [address]` and `hardhat_stopImpersonatingAccount [address]`, and the same two under their `anvil_` names, add an address to (or remove it from) the impersonated set; each returns `null`, as anvil answers them, and stopping an address that is not impersonated is no error. `eth_sendTransaction` from an impersonated address is filled exactly as a dev account's is, given a FABRICATED signature (a fixed low `s` and an `r` derived from the address, so two impersonated senders sending otherwise identical transactions still get two different hashes), and sent through webevm's `evm_sendRawTransactionAs(raw, from)`: the transaction executes AS that address, its balance charged and its nonce advanced.
178
+
179
+ **It needs a `senderMode: 'trusted'` node**, because that is the only kind that takes a sender it is told rather than one it recovers. `createDevNode({impersonation: true})` creates one, and refuses an explicit `senderMode: 'recover'` alongside the option; `wrapDevNode(node, {impersonation: true})` throws at once on a node that is not `'trusted'`, naming the option. While the option is off, the four methods answer a real `-32601` naming it (rocketh swallows that error, so its message is where you learn what to switch on).
180
+
181
+ **No signature that is not one.** Every signing method (`eth_signTransaction`, `personal_sign`, `eth_sign`, `eth_signTypedData_v4`) refuses an impersonated address with `4100`, saying no key is held for it. A dev account that is also impersonated still signs, and sends, with its own key. `eth_accounts` never lists an impersonated address.
182
+
183
+ **A dump holding impersonated transactions is NOT replayable on a `'recover'` node.** Their signatures are fabricated: a `'recover'` node recovers some unrelated address from them, or none, so `dumpState().transactions` of such a chain is not portable chain history ([ADR 0002](https://github.com/wighawag/webevm/blob/main/docs/adr/0002-trusted-sender-is-a-primitive-impersonation-is-not-our-job.md), Consequences). This is the one exception to the rule [above](#the-two-send-paths-by-sendermode): a dev account's own transactions carry real signatures and replay anywhere, on a `'trusted'` node too. `toAllocs` is unaffected, since an alloc carries state only.
184
+
185
+ ## What the wrapped node is
186
+
187
+ A `SlimNode`, the same interface webevm's own nodes have, so it drops in wherever one goes:
188
+
189
+ - `request` answers `eth_accounts` with the dev accounts, in order, as lowercase hex (as webevm writes every address). It never lists an impersonated address. It answers `eth_sendTransaction` and the signing methods for a dev account, and the impersonation methods (above). Every other method reaches the node unchanged, its result or its error included: the core's own `-32601` for a method nobody implements arrives exactly as the core raised it.
190
+ - `serveOn(port)` serves the dev node's `request`, so a consumer on another thread using `providerOverPort(port)` from `@eip-1193/over-port` sees the dev accounts too.
191
+ - `dispose()` stops answering on the ports it served, then disposes the node.
192
+ - The cheats and snapshots are the core's, and reach it unchanged: `hardhat_setBalance` / `hardhat_setNonce` / `hardhat_setCode` / `hardhat_setStorageAt` and their `anvil_` names, `evm_mine`, `anvil_mine` / `hardhat_mine`, the time cheats, and `evm_snapshot` / `evm_revert` (and `anvil_snapshot` / `anvil_revert`). The layer holds no chain state of its own (a send reads the pending nonce from the node), so a revert also rolls back what the dev node reads: a dev account that sent inside the snapshot's window sends again at the earlier nonce. See webevm's README for each method's wire shape.
193
+ - Every other member (`mine`, `dumpState`, `loadState`, `onNewHead`, `getStateRoot`, `computeStateRoot`, `senderMode`, `engine`) is the node's own.
194
+
195
+ It works with either engine, the default `@ethereumjs/evm` and `webevm/revm`, in any browser webevm runs in (the suite runs on Chromium and WebKit).
196
+
197
+ ## Handing a chain to forge
198
+
199
+ `toAllocs(dump)` turns a dump into the genesis alloc map forge's `vm.loadAllocs` accepts, so a `forge test` loads a deployment instead of replaying it:
200
+
201
+ ```ts
202
+ import {writeFileSync} from 'node:fs';
203
+ import {toAllocs} from '@webevm/devnode';
204
+
205
+ writeFileSync('allocs.json', JSON.stringify(toAllocs(await node.dumpState())));
206
+ ```
207
+
208
+ ```solidity
209
+ function setUp() public {
210
+ vm.loadAllocs("allocs.json");
211
+ }
212
+ ```
213
+
214
+ The result is `{address: {nonce, balance, code, storage}}`: nonces and balances as hex quantities, code as hex (`0x` for none), storage keyed by 32-byte slots with 32-byte values. Every account the dump holds is in it, the funded dev accounts included (they are genesis state); the storage root and code hash are left out, since forge recomputes both. It is a pure function of the dump, so it works in Node (a CLI) as in a browser, on any dump: a live node's, a persisted one, either engine's, and a chain whose transactions used fabricated signatures (`senderMode: 'trusted'`), since the alloc carries state only. A malformed dump throws, naming the address and field.
215
+
216
+ `scripts/forge-load-allocs.mjs` is a MANUAL check that forge really loads it (not run in CI, which has no forge): with forge on the PATH, `pnpm build && node scripts/forge-load-allocs.mjs` deploys a contract whose constructor stores a value, exports the chain, and runs a real `forge test` on it that checks the contract's code, nonce and slot and the dev accounts' balances (`--keep` keeps the generated Foundry project). Its recorded run, under forge 1.7.1: [`docs/spikes/devnode-alloc-export-for-forge/forge-run.md`](https://github.com/wighawag/webevm/blob/main/docs/spikes/devnode-alloc-export-for-forge/forge-run.md).
217
+
218
+ Why this is a separate package and not part of webevm: [ADR 0017](https://github.com/wighawag/webevm/blob/main/docs/adr/0017-dev-accounts-live-in-webevm-devnode-a-slimnode-decorator-funded-at-genesis.md).
219
+
220
+ ## License
221
+
222
+ MIT
@@ -0,0 +1,82 @@
1
+ /** anvil's and Hardhat's default mnemonic. */
2
+ export declare const DEFAULT_MNEMONIC = "test test test test test test test test test test test junk";
3
+ /** The BIP-44 Ethereum path the account index is appended to. */
4
+ export declare const DEFAULT_DERIVATION_PATH = "m/44'/60'/0'/0";
5
+ /** How many accounts a mnemonic yields by default (anvil's `--accounts`). */
6
+ export declare const DEFAULT_ACCOUNT_COUNT = 10;
7
+ /** Each dev account's genesis balance by default: 10,000 ETH, in wei. */
8
+ export declare const DEFAULT_BALANCE: bigint;
9
+ /**
10
+ * Accounts derived from a mnemonic, as Hardhat's `accounts: {mnemonic, path,
11
+ * initialIndex, count}` and anvil's `--mnemonic` / `--derivation-path` /
12
+ * `--accounts` describe them. Account `i` is at `${path}/${initialIndex + i}`.
13
+ */
14
+ export interface MnemonicAccounts {
15
+ /** A BIP-39 English mnemonic. Default: {@link DEFAULT_MNEMONIC}. */
16
+ mnemonic?: string;
17
+ /** How many accounts, a non-negative integer. Default 10. */
18
+ count?: number;
19
+ /**
20
+ * The path the account index is appended to. Default `m/44'/60'/0'/0`
21
+ * (a trailing `/`, anvil's spelling, is accepted too).
22
+ */
23
+ path?: string;
24
+ /** The index of the first account. Default 0. */
25
+ initialIndex?: number;
26
+ }
27
+ /**
28
+ * The dev accounts: a {@link MnemonicAccounts} config, a NUMBER (shorthand for
29
+ * `{count}` on the default mnemonic, as anvil's `--accounts N`), or a list of
30
+ * 32-byte hex private keys (Hardhat's `accounts: [...]`), in that order.
31
+ */
32
+ export type DevAccountsConfig = MnemonicAccounts | number | readonly string[];
33
+ /** A dev account: its lowercase address and the key the layer holds for it. */
34
+ export interface DevAccount {
35
+ readonly address: string;
36
+ readonly privateKey: Uint8Array;
37
+ }
38
+ /** The account options both `createDevNode` and `wrapDevNode` take. */
39
+ export interface DevAccountsOptions {
40
+ /** The dev accounts. Default: anvil's ten. */
41
+ accounts?: DevAccountsConfig;
42
+ }
43
+ /** What decides the genesis balances `createDevNode` funds. */
44
+ export interface DevFundingOptions extends DevAccountsOptions {
45
+ /** Each dev account's genesis balance, in wei. Default 10,000 ETH. */
46
+ balance?: bigint;
47
+ /**
48
+ * Whether the dev accounts are funded at all. Default `true`. `false` funds
49
+ * no dev account; {@link fundAccounts} and `initialBalances` still apply,
50
+ * being explicit per-address requests.
51
+ */
52
+ fund?: boolean;
53
+ /**
54
+ * Extra addresses to fund at genesis, address to balance in wei (anvil's
55
+ * `--fund-accounts`). Wins over {@link balance} for a dev account it names.
56
+ */
57
+ fundAccounts?: Record<string, bigint>;
58
+ /**
59
+ * webevm's own option: an entry here wins over both of the above for the
60
+ * same address (compared case-insensitively).
61
+ */
62
+ initialBalances?: Record<string, bigint>;
63
+ }
64
+ /**
65
+ * The dev accounts a config describes, in order. Throws, naming the option, on
66
+ * an invalid mnemonic, private key, count or index: a dev node with the wrong
67
+ * accounts would answer with plausible addresses nobody asked for.
68
+ */
69
+ export declare function deriveDevAccounts(config?: DevAccountsConfig): DevAccount[];
70
+ /**
71
+ * The `initialBalances` the same options would fund at genesis, for a node
72
+ * created elsewhere (a `createWorkerNode()` whose keys stay on this thread):
73
+ *
74
+ * const worker = await createWorkerNode({worker, initialBalances: devAccountBalances({accounts})});
75
+ * const node = wrapDevNode(worker, {accounts});
76
+ *
77
+ * Precedence, lowest first: each dev account's `balance` (unless `fund` is
78
+ * `false`), then `fundAccounts`, then the caller's own `initialBalances`. Keys
79
+ * are lowercase, so two spellings of one address cannot both reach genesis.
80
+ */
81
+ export declare function devAccountBalances(options?: DevFundingOptions): Record<string, bigint>;
82
+ //# sourceMappingURL=accounts.d.ts.map
@@ -0,0 +1 @@
1
+ {"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AAM,GAAE,iBAAsB,GAC5B,UAAU,EAAE,CA8Cd;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,kBAAkB,CACjC,OAAO,GAAE,iBAAsB,GAC7B,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAmBxB"}
@@ -0,0 +1,129 @@
1
+ /**
2
+ * accounts.ts: the DEV ACCOUNTS, derived from a mnemonic or given as private
3
+ * keys, and the genesis balances they are funded with.
4
+ *
5
+ * THE DEFAULT IS anvil's and Hardhat's: the standard test mnemonic, path
6
+ * `m/44'/60'/0'/0/i`, ten accounts, 10,000 ETH each, so an index-declared
7
+ * account (rocketh's `deployer: 0`) resolves to the same address here as there.
8
+ *
9
+ * ADDRESSES ARE LOWERCASE HEX, which is what webevm writes in every address it
10
+ * returns (receipts, logs, blocks), so a dev account read from `eth_accounts`
11
+ * compares equal to the same account read from a receipt's `from`. anvil returns
12
+ * EIP-55 checksummed addresses and Hardhat lowercase ones; clients compare
13
+ * case-insensitively (viem normalises), so lowercase costs nobody anything and
14
+ * keeps one form across this node's whole surface. (Alternative: EIP-55, as
15
+ * anvil; rejected because a dev account would then be spelled differently in
16
+ * `eth_accounts` and in every receipt.)
17
+ *
18
+ * DECISIONS made here (task `devnode-package-dev-accounts-funded-at-genesis`),
19
+ * each user-visible and each reversible before 1.0:
20
+ *
21
+ * - `accounts` ALSO TAKES A NUMBER, shorthand for `{count}` on the default
22
+ * mnemonic (anvil's `--accounts N`), because webevm's own worker-host JSDoc
23
+ * already shows `createDevNode({...options, accounts: 10})`. Alternative: the
24
+ * object form only.
25
+ * - PRECEDENCE, lowest first: `balance`, then `fundAccounts`, then the caller's
26
+ * `initialBalances` (the task fixes only the last). `fundAccounts` beats
27
+ * `balance` because it names one address, `balance` all of them.
28
+ * - `fund: false` turns off ONLY the dev accounts' `balance`: `fundAccounts` and
29
+ * `initialBalances` still apply, being explicit per-address requests.
30
+ * Alternative: `fund: false` meaning "no funding at all", which would make
31
+ * `fundAccounts` silently do nothing.
32
+ * - A BAD CONFIG THROWS a plain `Error` naming the option (`accounts.mnemonic`,
33
+ * `accounts[i]`, `accounts.count`, `accounts.initialIndex`, `balance`), from
34
+ * `createDevNode` before any node exists and from `wrapDevNode` synchronously.
35
+ * The worker task turns this into a value that rejects `createWorkerNode()`.
36
+ */
37
+ import { HDKey } from '@scure/bip32';
38
+ import { mnemonicToSeedSync, validateMnemonic } from '@scure/bip39';
39
+ import { wordlist } from '@scure/bip39/wordlists/english.js';
40
+ import { secp256k1 } from '@noble/curves/secp256k1.js';
41
+ import { keccak_256 } from '@noble/hashes/sha3.js';
42
+ import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js';
43
+ /** anvil's and Hardhat's default mnemonic. */
44
+ export const DEFAULT_MNEMONIC = 'test test test test test test test test test test test junk';
45
+ /** The BIP-44 Ethereum path the account index is appended to. */
46
+ export const DEFAULT_DERIVATION_PATH = "m/44'/60'/0'/0";
47
+ /** How many accounts a mnemonic yields by default (anvil's `--accounts`). */
48
+ export const DEFAULT_ACCOUNT_COUNT = 10;
49
+ /** Each dev account's genesis balance by default: 10,000 ETH, in wei. */
50
+ export const DEFAULT_BALANCE = 10000n * 10n ** 18n;
51
+ const PRIVATE_KEY = /^0x[0-9a-fA-F]{64}$/;
52
+ /** The address of a secp256k1 private key, lowercase. */
53
+ function addressOf(privateKey) {
54
+ const publicKey = secp256k1.getPublicKey(privateKey, false);
55
+ return `0x${bytesToHex(keccak_256(publicKey.subarray(1)).subarray(12))}`;
56
+ }
57
+ function nonNegativeInteger(value, name) {
58
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
59
+ throw new Error(`@webevm/devnode: \`${name}\` must be a non-negative integer (received ${String(value)}).`);
60
+ }
61
+ return value;
62
+ }
63
+ /**
64
+ * The dev accounts a config describes, in order. Throws, naming the option, on
65
+ * an invalid mnemonic, private key, count or index: a dev node with the wrong
66
+ * accounts would answer with plausible addresses nobody asked for.
67
+ */
68
+ export function deriveDevAccounts(config = {}) {
69
+ if (Array.isArray(config)) {
70
+ return config.map((key, i) => {
71
+ if (typeof key !== 'string' || !PRIVATE_KEY.test(key)) {
72
+ throw new Error(`@webevm/devnode: \`accounts[${i}]\` must be a 0x-prefixed 32-byte hex private key.`);
73
+ }
74
+ const privateKey = hexToBytes(key.slice(2));
75
+ if (!secp256k1.utils.isValidSecretKey(privateKey)) {
76
+ throw new Error(`@webevm/devnode: \`accounts[${i}]\` is not a valid secp256k1 private key (zero, or not below the curve order).`);
77
+ }
78
+ return { address: addressOf(privateKey), privateKey };
79
+ });
80
+ }
81
+ const options = typeof config === 'number' ? { count: config } : config;
82
+ const mnemonic = options.mnemonic ?? DEFAULT_MNEMONIC;
83
+ const count = nonNegativeInteger(options.count ?? DEFAULT_ACCOUNT_COUNT, typeof config === 'number' ? 'accounts' : 'accounts.count');
84
+ const initialIndex = nonNegativeInteger(options.initialIndex ?? 0, 'accounts.initialIndex');
85
+ const path = (options.path ?? DEFAULT_DERIVATION_PATH).replace(/\/$/, '');
86
+ if (typeof mnemonic !== 'string' || !validateMnemonic(mnemonic, wordlist)) {
87
+ throw new Error('@webevm/devnode: `accounts.mnemonic` is not a valid BIP-39 English mnemonic.');
88
+ }
89
+ const root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic));
90
+ const accounts = [];
91
+ for (let i = 0; i < count; i++) {
92
+ const privateKey = root.derive(`${path}/${initialIndex + i}`).privateKey;
93
+ if (!privateKey) {
94
+ throw new Error(`@webevm/devnode: \`accounts.path\` ${path} derived no private key.`);
95
+ }
96
+ accounts.push({ address: addressOf(privateKey), privateKey });
97
+ }
98
+ return accounts;
99
+ }
100
+ /**
101
+ * The `initialBalances` the same options would fund at genesis, for a node
102
+ * created elsewhere (a `createWorkerNode()` whose keys stay on this thread):
103
+ *
104
+ * const worker = await createWorkerNode({worker, initialBalances: devAccountBalances({accounts})});
105
+ * const node = wrapDevNode(worker, {accounts});
106
+ *
107
+ * Precedence, lowest first: each dev account's `balance` (unless `fund` is
108
+ * `false`), then `fundAccounts`, then the caller's own `initialBalances`. Keys
109
+ * are lowercase, so two spellings of one address cannot both reach genesis.
110
+ */
111
+ export function devAccountBalances(options = {}) {
112
+ const balances = {};
113
+ if (options.fund !== false) {
114
+ const balance = options.balance ?? DEFAULT_BALANCE;
115
+ if (typeof balance !== 'bigint' || balance < 0n) {
116
+ throw new Error('@webevm/devnode: `balance` must be a non-negative bigint, in wei.');
117
+ }
118
+ for (const { address } of deriveDevAccounts(options.accounts)) {
119
+ balances[address] = balance;
120
+ }
121
+ }
122
+ for (const extra of [options.fundAccounts, options.initialBalances]) {
123
+ for (const [address, balance] of Object.entries(extra ?? {})) {
124
+ balances[address.toLowerCase()] = balance;
125
+ }
126
+ }
127
+ return balances;
128
+ }
129
+ //# sourceMappingURL=accounts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accounts.js","sourceRoot":"","sources":["../src/accounts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,OAAO,EAAC,KAAK,EAAC,MAAM,cAAc,CAAC;AACnC,OAAO,EAAC,kBAAkB,EAAE,gBAAgB,EAAC,MAAM,cAAc,CAAC;AAClE,OAAO,EAAC,QAAQ,EAAC,MAAM,mCAAmC,CAAC;AAC3D,OAAO,EAAC,SAAS,EAAC,MAAM,4BAA4B,CAAC;AACrD,OAAO,EAAC,UAAU,EAAC,MAAM,uBAAuB,CAAC;AACjD,OAAO,EAAC,UAAU,EAAE,UAAU,EAAC,MAAM,wBAAwB,CAAC;AAE9D,8CAA8C;AAC9C,MAAM,CAAC,MAAM,gBAAgB,GAC5B,6DAA6D,CAAC;AAC/D,iEAAiE;AACjE,MAAM,CAAC,MAAM,uBAAuB,GAAG,gBAAgB,CAAC;AACxD,6EAA6E;AAC7E,MAAM,CAAC,MAAM,qBAAqB,GAAG,EAAE,CAAC;AACxC,yEAAyE;AACzE,MAAM,CAAC,MAAM,eAAe,GAAG,MAAO,GAAG,GAAG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C;YACjB,MAAM,IAAI,KAAK,CACd,sCAAsC,IAAI,0BAA0B,CACpE,CAAC;QACH,CAAC;QACD,QAAQ,CAAC,IAAI,CAAC,EAAC,OAAO,EAAE,SAAS,CAAC,UAAU,CAAC,EAAE,UAAU,EAAC,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,QAAQ,CAAC;AACjB,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,kBAAkB,CACjC,UAA6B,EAAE;IAE/B,MAAM,QAAQ,GAA2B,EAAE,CAAC;IAC5C,IAAI,OAAO,CAAC,IAAI,KAAK,KAAK,EAAE,CAAC;QAC5B,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,eAAe,CAAC;QACnD,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,GAAG,EAAE,EAAE,CAAC;YACjD,MAAM,IAAI,KAAK,CACd,mEAAmE,CACnE,CAAC;QACH,CAAC;QACD,KAAK,MAAM,EAAC,OAAO,EAAC,IAAI,iBAAiB,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC7D,QAAQ,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;QAC7B,CAAC;IACF,CAAC;IACD,KAAK,MAAM,KAAK,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE,OAAO,CAAC,eAAe,CAAC,EAAE,CAAC;QACrE,KAAK,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE,CAAC;YAC9D,QAAQ,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,GAAG,OAAO,CAAC;QAC3C,CAAC;IACF,CAAC;IACD,OAAO,QAAQ,CAAC;AACjB,CAAC"}
@@ -0,0 +1,26 @@
1
+ import type { SerializedState } from 'webevm';
2
+ /** One account in a genesis alloc, as forge's `vm.loadAllocs` reads it. */
3
+ export interface AllocAccount {
4
+ /** The account's nonce, as a hex quantity (`0x0`, `0x1`, ...). */
5
+ nonce: string;
6
+ /** Its balance in wei, as a hex quantity. */
7
+ balance: string;
8
+ /** Its code, `0x` hex (`0x` for none). */
9
+ code: string;
10
+ /** Its storage, 32-byte slot to 32-byte value, both `0x` hex. */
11
+ storage: Record<string, string>;
12
+ }
13
+ /** A genesis alloc map: lowercase address to {@link AllocAccount}. */
14
+ export type Allocs = Record<string, AllocAccount>;
15
+ /**
16
+ * The node's state as a genesis alloc for forge's `vm.loadAllocs`:
17
+ *
18
+ * const allocs = toAllocs(await node.dumpState());
19
+ * writeFileSync('allocs.json', JSON.stringify(allocs));
20
+ * // in Solidity: vm.loadAllocs("allocs.json");
21
+ *
22
+ * Works on any dump (a live one, a persisted one, either engine's, either
23
+ * sender mode's). Throws on a malformed dump, naming the address and field.
24
+ */
25
+ export declare function toAllocs(state: SerializedState): Allocs;
26
+ //# sourceMappingURL=allocs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"allocs.d.ts","sourceRoot":"","sources":["../src/allocs.ts"],"names":[],"mappings":"AA+CA,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,QAAQ,CAAC;AAE5C,2EAA2E;AAC3E,MAAM,WAAW,YAAY;IAC5B,kEAAkE;IAClE,KAAK,EAAE,MAAM,CAAC;IACd,6CAA6C;IAC7C,OAAO,EAAE,MAAM,CAAC;IAChB,0CAA0C;IAC1C,IAAI,EAAE,MAAM,CAAC;IACb,iEAAiE;IACjE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAChC;AAED,sEAAsE;AACtE,MAAM,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;AAwBlD;;;;;;;;;GASG;AACH,wBAAgB,QAAQ,CAAC,KAAK,EAAE,eAAe,GAAG,MAAM,CAqCvD"}
package/dist/allocs.js ADDED
@@ -0,0 +1,99 @@
1
+ /**
2
+ * allocs.ts: the ALLOC EXPORT, a webevm dump as the genesis alloc map forge's
3
+ * `vm.loadAllocs` accepts, so forge loads a deployment instead of replaying it.
4
+ *
5
+ * PURE: it reads a `SerializedState` (from `dumpState()`, a persisted dump, a
6
+ * file) and nothing else, so a CLI calls it in Node as easily as a page does in
7
+ * a browser. It carries STATE ONLY, which is why a chain whose transactions used
8
+ * fabricated signatures (ADR 0002's `'trusted'` mode) exports as well as any:
9
+ * no transaction, signature, block or receipt reaches the alloc.
10
+ *
11
+ * THE FORMS are what forge 1.7.1's `vm.loadAllocs` (alloy's `GenesisAccount`)
12
+ * reads, as rocketh proved by hand from a webevm 0.9.1 dump:
13
+ *
14
+ * - `nonce` and `balance` are hex QUANTITIES (`0x0`, `0x1`, no leading zeros),
15
+ * decoded from the account's RLP `[nonce, balance, storageRoot, codeHash]`;
16
+ * - `code` is the dump's code hex;
17
+ * - `storage` is keyed by 32-byte `0x` slots, and its values are PADDED to 32
18
+ * bytes, because the dump writes them in shortest form and forge reads both
19
+ * sides as 32-byte words;
20
+ * - the storage root and code hash are dropped: forge recomputes both.
21
+ *
22
+ * DECISIONS made here (task `devnode-alloc-export-for-forge`), each reversible
23
+ * before 1.0:
24
+ *
25
+ * - EVERY ENTRY CARRIES ALL FOUR FIELDS, `code: '0x'` and `storage: {}`
26
+ * included, so a consumer reads one shape. Alternative: omitting empty
27
+ * fields, as geth's genesis files often do; forge accepts both.
28
+ * - EVERY ACCOUNT THE DUMP HOLDS IS EXPORTED, an empty one (nonce 0, balance 0,
29
+ * no code, no storage) included, because an existing empty account and an
30
+ * absent one differ to the EVM (`EXTCODEHASH`), and the export should be the
31
+ * dump's state, not a reinterpretation of it. Alternative: dropping empty
32
+ * accounts, which a post-Spurious-Dragon chain rarely holds anyway.
33
+ * - ADDRESSES, SLOTS AND VALUES ARE LOWERCASE, as every address webevm writes.
34
+ * - A dump holding code or storage for an address with NO account RLP still
35
+ * exports it, with nonce and balance `0x0`. A dump webevm wrote never does
36
+ * this; a hand-edited one might, and its code is still state forge can load.
37
+ * - A MALFORMED dump (an account that is not RLP, a slot or value longer than
38
+ * 32 bytes, a non-hex string) THROWS a plain `Error` naming the address and
39
+ * field, rather than writing an alloc forge would reject or misread.
40
+ */
41
+ import { bigIntToHex, bytesToHex, createAccountFromRLP, hexToBytes, setLengthLeft, } from '@ethereumjs/util';
42
+ const HEX = /^0x([0-9a-fA-F]{2})*$/;
43
+ function bytesOf(value, what) {
44
+ if (typeof value !== 'string' || !HEX.test(value)) {
45
+ throw new Error(`@webevm/devnode: toAllocs: ${what} is not even-length 0x hex (received ${String(value)}).`);
46
+ }
47
+ return hexToBytes(value);
48
+ }
49
+ /** A slot or value as a 32-byte word, refusing one that does not fit. */
50
+ function word(value, what) {
51
+ const bytes = bytesOf(value, what);
52
+ if (bytes.length > 32) {
53
+ throw new Error(`@webevm/devnode: toAllocs: ${what} is longer than 32 bytes (${String(value)}).`);
54
+ }
55
+ return bytesToHex(setLengthLeft(bytes, 32));
56
+ }
57
+ /**
58
+ * The node's state as a genesis alloc for forge's `vm.loadAllocs`:
59
+ *
60
+ * const allocs = toAllocs(await node.dumpState());
61
+ * writeFileSync('allocs.json', JSON.stringify(allocs));
62
+ * // in Solidity: vm.loadAllocs("allocs.json");
63
+ *
64
+ * Works on any dump (a live one, a persisted one, either engine's, either
65
+ * sender mode's). Throws on a malformed dump, naming the address and field.
66
+ */
67
+ export function toAllocs(state) {
68
+ const allocs = {};
69
+ const entry = (address) => (allocs[address.toLowerCase()] ??= {
70
+ nonce: '0x0',
71
+ balance: '0x0',
72
+ code: '0x',
73
+ storage: {},
74
+ });
75
+ for (const [address, rlp] of Object.entries(state.accounts ?? {})) {
76
+ const bytes = bytesOf(rlp, `accounts[${address}]`);
77
+ let account;
78
+ try {
79
+ account = createAccountFromRLP(bytes);
80
+ }
81
+ catch (e) {
82
+ throw new Error(`@webevm/devnode: toAllocs: accounts[${address}] is not an account RLP (${e.message}).`);
83
+ }
84
+ const out = entry(address);
85
+ out.nonce = bigIntToHex(account.nonce);
86
+ out.balance = bigIntToHex(account.balance);
87
+ }
88
+ for (const [address, code] of Object.entries(state.code ?? {})) {
89
+ entry(address).code = bytesToHex(bytesOf(code, `code[${address}]`));
90
+ }
91
+ for (const [address, slots] of Object.entries(state.storage ?? {})) {
92
+ const out = entry(address);
93
+ for (const [slot, value] of Object.entries(slots)) {
94
+ out.storage[word(slot, `storage[${address}] slot ${slot}`)] = word(value, `storage[${address}][${slot}]`);
95
+ }
96
+ }
97
+ return allocs;
98
+ }
99
+ //# sourceMappingURL=allocs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"allocs.js","sourceRoot":"","sources":["../src/allocs.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,OAAO,EACN,WAAW,EACX,UAAU,EACV,oBAAoB,EACpB,UAAU,EACV,aAAa,GACb,MAAM,kBAAkB,CAAC;AAkB1B,MAAM,GAAG,GAAG,uBAAuB,CAAC;AAEpC,SAAS,OAAO,CAAC,KAAc,EAAE,IAAY;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QACnD,MAAM,IAAI,KAAK,CACd,8BAA8B,IAAI,wCAAwC,MAAM,CAAC,KAAK,CAAC,IAAI,CAC3F,CAAC;IACH,CAAC;IACD,OAAO,UAAU,CAAC,KAAsB,CAAC,CAAC;AAC3C,CAAC;AAED,yEAAyE;AACzE,SAAS,IAAI,CAAC,KAAc,EAAE,IAAY;IACzC,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACnC,IAAI,KAAK,CAAC,MAAM,GAAG,EAAE,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CACd,8BAA8B,IAAI,6BAA6B,MAAM,CAAC,KAAK,CAAC,IAAI,CAChF,CAAC;IACH,CAAC;IACD,OAAO,UAAU,CAAC,aAAa,CAAC,KAAK,EAAE,EAAE,CAAC,CAA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