@webevm/devnode 0.0.0 → 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 (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -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 +81 -13
  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
  49. package/.npm-publish.log +0 -0
@@ -0,0 +1,218 @@
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
+
44
+ /** anvil's and Hardhat's default mnemonic. */
45
+ export const DEFAULT_MNEMONIC =
46
+ 'test test test test test test test test test test test junk';
47
+ /** The BIP-44 Ethereum path the account index is appended to. */
48
+ export const DEFAULT_DERIVATION_PATH = "m/44'/60'/0'/0";
49
+ /** How many accounts a mnemonic yields by default (anvil's `--accounts`). */
50
+ export const DEFAULT_ACCOUNT_COUNT = 10;
51
+ /** Each dev account's genesis balance by default: 10,000 ETH, in wei. */
52
+ export const DEFAULT_BALANCE = 10_000n * 10n ** 18n;
53
+
54
+ /**
55
+ * Accounts derived from a mnemonic, as Hardhat's `accounts: {mnemonic, path,
56
+ * initialIndex, count}` and anvil's `--mnemonic` / `--derivation-path` /
57
+ * `--accounts` describe them. Account `i` is at `${path}/${initialIndex + i}`.
58
+ */
59
+ export interface MnemonicAccounts {
60
+ /** A BIP-39 English mnemonic. Default: {@link DEFAULT_MNEMONIC}. */
61
+ mnemonic?: string;
62
+ /** How many accounts, a non-negative integer. Default 10. */
63
+ count?: number;
64
+ /**
65
+ * The path the account index is appended to. Default `m/44'/60'/0'/0`
66
+ * (a trailing `/`, anvil's spelling, is accepted too).
67
+ */
68
+ path?: string;
69
+ /** The index of the first account. Default 0. */
70
+ initialIndex?: number;
71
+ }
72
+
73
+ /**
74
+ * The dev accounts: a {@link MnemonicAccounts} config, a NUMBER (shorthand for
75
+ * `{count}` on the default mnemonic, as anvil's `--accounts N`), or a list of
76
+ * 32-byte hex private keys (Hardhat's `accounts: [...]`), in that order.
77
+ */
78
+ export type DevAccountsConfig = MnemonicAccounts | number | readonly string[];
79
+
80
+ /** A dev account: its lowercase address and the key the layer holds for it. */
81
+ export interface DevAccount {
82
+ readonly address: string;
83
+ readonly privateKey: Uint8Array;
84
+ }
85
+
86
+ /** The account options both `createDevNode` and `wrapDevNode` take. */
87
+ export interface DevAccountsOptions {
88
+ /** The dev accounts. Default: anvil's ten. */
89
+ accounts?: DevAccountsConfig;
90
+ }
91
+
92
+ /** What decides the genesis balances `createDevNode` funds. */
93
+ export interface DevFundingOptions extends DevAccountsOptions {
94
+ /** Each dev account's genesis balance, in wei. Default 10,000 ETH. */
95
+ balance?: bigint;
96
+ /**
97
+ * Whether the dev accounts are funded at all. Default `true`. `false` funds
98
+ * no dev account; {@link fundAccounts} and `initialBalances` still apply,
99
+ * being explicit per-address requests.
100
+ */
101
+ fund?: boolean;
102
+ /**
103
+ * Extra addresses to fund at genesis, address to balance in wei (anvil's
104
+ * `--fund-accounts`). Wins over {@link balance} for a dev account it names.
105
+ */
106
+ fundAccounts?: Record<string, bigint>;
107
+ /**
108
+ * webevm's own option: an entry here wins over both of the above for the
109
+ * same address (compared case-insensitively).
110
+ */
111
+ initialBalances?: Record<string, bigint>;
112
+ }
113
+
114
+ const PRIVATE_KEY = /^0x[0-9a-fA-F]{64}$/;
115
+
116
+ /** The address of a secp256k1 private key, lowercase. */
117
+ function addressOf(privateKey: Uint8Array): string {
118
+ const publicKey = secp256k1.getPublicKey(privateKey, false);
119
+ return `0x${bytesToHex(keccak_256(publicKey.subarray(1)).subarray(12))}`;
120
+ }
121
+
122
+ function nonNegativeInteger(value: unknown, name: string): number {
123
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
124
+ throw new Error(
125
+ `@webevm/devnode: \`${name}\` must be a non-negative integer (received ${String(value)}).`,
126
+ );
127
+ }
128
+ return value;
129
+ }
130
+
131
+ /**
132
+ * The dev accounts a config describes, in order. Throws, naming the option, on
133
+ * an invalid mnemonic, private key, count or index: a dev node with the wrong
134
+ * accounts would answer with plausible addresses nobody asked for.
135
+ */
136
+ export function deriveDevAccounts(
137
+ config: DevAccountsConfig = {},
138
+ ): DevAccount[] {
139
+ if (Array.isArray(config)) {
140
+ return (config as readonly unknown[]).map((key, i) => {
141
+ if (typeof key !== 'string' || !PRIVATE_KEY.test(key)) {
142
+ throw new Error(
143
+ `@webevm/devnode: \`accounts[${i}]\` must be a 0x-prefixed 32-byte hex private key.`,
144
+ );
145
+ }
146
+ const privateKey = hexToBytes(key.slice(2));
147
+ if (!secp256k1.utils.isValidSecretKey(privateKey)) {
148
+ throw new Error(
149
+ `@webevm/devnode: \`accounts[${i}]\` is not a valid secp256k1 private key (zero, or not below the curve order).`,
150
+ );
151
+ }
152
+ return {address: addressOf(privateKey), privateKey};
153
+ });
154
+ }
155
+ const options: MnemonicAccounts =
156
+ typeof config === 'number' ? {count: config} : (config as MnemonicAccounts);
157
+ const mnemonic = options.mnemonic ?? DEFAULT_MNEMONIC;
158
+ const count = nonNegativeInteger(
159
+ options.count ?? DEFAULT_ACCOUNT_COUNT,
160
+ typeof config === 'number' ? 'accounts' : 'accounts.count',
161
+ );
162
+ const initialIndex = nonNegativeInteger(
163
+ options.initialIndex ?? 0,
164
+ 'accounts.initialIndex',
165
+ );
166
+ const path = (options.path ?? DEFAULT_DERIVATION_PATH).replace(/\/$/, '');
167
+ if (typeof mnemonic !== 'string' || !validateMnemonic(mnemonic, wordlist)) {
168
+ throw new Error(
169
+ '@webevm/devnode: `accounts.mnemonic` is not a valid BIP-39 English mnemonic.',
170
+ );
171
+ }
172
+ const root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic));
173
+ const accounts: DevAccount[] = [];
174
+ for (let i = 0; i < count; i++) {
175
+ const privateKey = root.derive(`${path}/${initialIndex + i}`).privateKey;
176
+ if (!privateKey) {
177
+ throw new Error(
178
+ `@webevm/devnode: \`accounts.path\` ${path} derived no private key.`,
179
+ );
180
+ }
181
+ accounts.push({address: addressOf(privateKey), privateKey});
182
+ }
183
+ return accounts;
184
+ }
185
+
186
+ /**
187
+ * The `initialBalances` the same options would fund at genesis, for a node
188
+ * created elsewhere (a `createWorkerNode()` whose keys stay on this thread):
189
+ *
190
+ * const worker = await createWorkerNode({worker, initialBalances: devAccountBalances({accounts})});
191
+ * const node = wrapDevNode(worker, {accounts});
192
+ *
193
+ * Precedence, lowest first: each dev account's `balance` (unless `fund` is
194
+ * `false`), then `fundAccounts`, then the caller's own `initialBalances`. Keys
195
+ * are lowercase, so two spellings of one address cannot both reach genesis.
196
+ */
197
+ export function devAccountBalances(
198
+ options: DevFundingOptions = {},
199
+ ): Record<string, bigint> {
200
+ const balances: Record<string, bigint> = {};
201
+ if (options.fund !== false) {
202
+ const balance = options.balance ?? DEFAULT_BALANCE;
203
+ if (typeof balance !== 'bigint' || balance < 0n) {
204
+ throw new Error(
205
+ '@webevm/devnode: `balance` must be a non-negative bigint, in wei.',
206
+ );
207
+ }
208
+ for (const {address} of deriveDevAccounts(options.accounts)) {
209
+ balances[address] = balance;
210
+ }
211
+ }
212
+ for (const extra of [options.fundAccounts, options.initialBalances]) {
213
+ for (const [address, balance] of Object.entries(extra ?? {})) {
214
+ balances[address.toLowerCase()] = balance;
215
+ }
216
+ }
217
+ return balances;
218
+ }
package/src/allocs.ts ADDED
@@ -0,0 +1,134 @@
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 {
42
+ bigIntToHex,
43
+ bytesToHex,
44
+ createAccountFromRLP,
45
+ hexToBytes,
46
+ setLengthLeft,
47
+ } from '@ethereumjs/util';
48
+ import type {SerializedState} from 'webevm';
49
+
50
+ /** One account in a genesis alloc, as forge's `vm.loadAllocs` reads it. */
51
+ export interface AllocAccount {
52
+ /** The account's nonce, as a hex quantity (`0x0`, `0x1`, ...). */
53
+ nonce: string;
54
+ /** Its balance in wei, as a hex quantity. */
55
+ balance: string;
56
+ /** Its code, `0x` hex (`0x` for none). */
57
+ code: string;
58
+ /** Its storage, 32-byte slot to 32-byte value, both `0x` hex. */
59
+ storage: Record<string, string>;
60
+ }
61
+
62
+ /** A genesis alloc map: lowercase address to {@link AllocAccount}. */
63
+ export type Allocs = Record<string, AllocAccount>;
64
+
65
+ const HEX = /^0x([0-9a-fA-F]{2})*$/;
66
+
67
+ function bytesOf(value: unknown, what: string): Uint8Array {
68
+ if (typeof value !== 'string' || !HEX.test(value)) {
69
+ throw new Error(
70
+ `@webevm/devnode: toAllocs: ${what} is not even-length 0x hex (received ${String(value)}).`,
71
+ );
72
+ }
73
+ return hexToBytes(value as `0x${string}`);
74
+ }
75
+
76
+ /** A slot or value as a 32-byte word, refusing one that does not fit. */
77
+ function word(value: unknown, what: string): string {
78
+ const bytes = bytesOf(value, what);
79
+ if (bytes.length > 32) {
80
+ throw new Error(
81
+ `@webevm/devnode: toAllocs: ${what} is longer than 32 bytes (${String(value)}).`,
82
+ );
83
+ }
84
+ return bytesToHex(setLengthLeft(bytes, 32));
85
+ }
86
+
87
+ /**
88
+ * The node's state as a genesis alloc for forge's `vm.loadAllocs`:
89
+ *
90
+ * const allocs = toAllocs(await node.dumpState());
91
+ * writeFileSync('allocs.json', JSON.stringify(allocs));
92
+ * // in Solidity: vm.loadAllocs("allocs.json");
93
+ *
94
+ * Works on any dump (a live one, a persisted one, either engine's, either
95
+ * sender mode's). Throws on a malformed dump, naming the address and field.
96
+ */
97
+ export function toAllocs(state: SerializedState): Allocs {
98
+ const allocs: Allocs = {};
99
+ const entry = (address: string): AllocAccount =>
100
+ (allocs[address.toLowerCase()] ??= {
101
+ nonce: '0x0',
102
+ balance: '0x0',
103
+ code: '0x',
104
+ storage: {},
105
+ });
106
+
107
+ for (const [address, rlp] of Object.entries(state.accounts ?? {})) {
108
+ const bytes = bytesOf(rlp, `accounts[${address}]`);
109
+ let account;
110
+ try {
111
+ account = createAccountFromRLP(bytes);
112
+ } catch (e) {
113
+ throw new Error(
114
+ `@webevm/devnode: toAllocs: accounts[${address}] is not an account RLP (${(e as Error).message}).`,
115
+ );
116
+ }
117
+ const out = entry(address);
118
+ out.nonce = bigIntToHex(account.nonce);
119
+ out.balance = bigIntToHex(account.balance);
120
+ }
121
+ for (const [address, code] of Object.entries(state.code ?? {})) {
122
+ entry(address).code = bytesToHex(bytesOf(code, `code[${address}]`));
123
+ }
124
+ for (const [address, slots] of Object.entries(state.storage ?? {})) {
125
+ const out = entry(address);
126
+ for (const [slot, value] of Object.entries(slots)) {
127
+ out.storage[word(slot, `storage[${address}] slot ${slot}`)] = word(
128
+ value,
129
+ `storage[${address}][${slot}]`,
130
+ );
131
+ }
132
+ }
133
+ return allocs;
134
+ }
@@ -0,0 +1,220 @@
1
+ /**
2
+ * dev-node.ts: the `SlimNode` DECORATOR (`wrapDevNode`) and the constructor that
3
+ * funds its accounts at genesis (`createDevNode`).
4
+ *
5
+ * WHY A DECORATOR, AND WHY THIS PACKAGE. webevm's core holds no keys and answers
6
+ * every account method with a real `-32601` (ADR 0004), and offers impersonation
7
+ * only as a primitive for "a higher layer" (ADR 0002). This is that layer:
8
+ * `docs/adr/0017-dev-accounts-live-in-webevm-devnode-a-slimnode-decorator-funded-at-genesis.md`.
9
+ * It returns a NODE rather than a bare EIP-1193 provider so the same object runs
10
+ * on the main thread, over a `createWorkerNode()` proxy, and inside a worker.
11
+ *
12
+ * IT REACHES THE NODE ONLY THROUGH `SlimNode`'s PUBLIC MEMBERS, so it cannot
13
+ * depend on node internals and the core can change underneath it.
14
+ */
15
+ import {serveProvider, type ServedProvider} from '@eip-1193/over-port';
16
+ import {
17
+ createNode,
18
+ type NodeOptions,
19
+ type RequestArguments,
20
+ type SlimNode,
21
+ } from 'webevm';
22
+ import {
23
+ deriveDevAccounts,
24
+ devAccountBalances,
25
+ type DevAccount,
26
+ type DevAccountsOptions,
27
+ type DevFundingOptions,
28
+ } from './accounts.js';
29
+ import {createImpersonation, IMPERSONATION_METHODS} from './impersonation.js';
30
+ import {createTransactionMethods} from './send.js';
31
+ import {createMessageSigner} from './sign.js';
32
+
33
+ /** The impersonation switch, which both constructors take. */
34
+ export interface ImpersonationOptions {
35
+ /**
36
+ * Answer `hardhat_impersonateAccount` / `hardhat_stopImpersonatingAccount`
37
+ * (and their `anvil_` names), and send from an impersonated address with a
38
+ * fabricated signature through `evm_sendRawTransactionAs`. Default `false`,
39
+ * when the four methods answer `-32601` naming this option. Needs a
40
+ * `senderMode: 'trusted'` node: `createDevNode` creates one, `wrapDevNode`
41
+ * refuses any other. See ./impersonation.ts.
42
+ */
43
+ impersonation?: boolean;
44
+ }
45
+
46
+ /** What {@link wrapDevNode} takes: the accounts and the impersonation switch, and nothing that funds. */
47
+ export type WrapDevNodeOptions = DevAccountsOptions & ImpersonationOptions;
48
+
49
+ /** What {@link createDevNode} takes: webevm's options plus the dev accounts, their funding and the impersonation switch. */
50
+ export type DevNodeOptions = NodeOptions &
51
+ DevFundingOptions &
52
+ ImpersonationOptions;
53
+
54
+ /** Why impersonation cannot run on `node`, or `undefined` when it can. */
55
+ function impersonationRefusal(senderMode: unknown): string | undefined {
56
+ if (senderMode === 'trusted') return undefined;
57
+ return (
58
+ `@webevm/devnode: the \`impersonation\` option needs a node created with senderMode: 'trusted', ` +
59
+ `since an impersonated address's transactions carry a fabricated signature and are sent through ` +
60
+ `evm_sendRawTransactionAs, and it was given senderMode: '${String(senderMode)}'. ` +
61
+ `Create the node with senderMode: 'trusted' (createDevNode does so when the option is on), or turn the option off.`
62
+ );
63
+ }
64
+
65
+ /**
66
+ * Wrap an existing node with dev accounts. FUNDS NOTHING: genesis is decided
67
+ * when a node is created, so a node created elsewhere is funded by passing
68
+ * `devAccountBalances(options)` as its `initialBalances` there.
69
+ *
70
+ * The result is a `Required<SlimNode>` (the annotation is the mechanism, as on
71
+ * webevm's worker-host proxy: a member added to `SlimNode` later, optional or
72
+ * not, fails to build here instead of reading as `undefined`):
73
+ *
74
+ * - `request` answers `eth_accounts` with the dev accounts, in order, and
75
+ * `eth_sendTransaction` from one of them (filled, signed with its key and
76
+ * submitted by the node's sender mode; see ./send.ts), signs for them
77
+ * (`eth_signTransaction`, ./send.ts; `personal_sign`, `eth_sign` and
78
+ * `eth_signTypedData_v4`, ./sign.ts), answers the impersonation methods
79
+ * (./impersonation.ts; `-32601` naming the option while it is off), and
80
+ * forwards every other method to the node, its result or its error unchanged
81
+ * (the node's own `-32601` included: the very promise the node returned);
82
+ * - `serveOn` serves THIS `request` on the port, so a served port answers the
83
+ * account methods too;
84
+ * - `dispose` stops answering on the ports it served, then disposes the node
85
+ * (whose own `dispose` closes only the ports IT served);
86
+ * - every other member delegates.
87
+ *
88
+ * Throws on an invalid account config (see `deriveDevAccounts`), and at once
89
+ * when `impersonation` is on and the node is not `senderMode: 'trusted'`.
90
+ */
91
+ export function wrapDevNode(
92
+ node: SlimNode,
93
+ options: WrapDevNodeOptions = {},
94
+ ): Required<SlimNode> {
95
+ const accounts = deriveDevAccounts(options.accounts);
96
+ const impersonation = options.impersonation === true;
97
+ if (impersonation) {
98
+ const refusal = impersonationRefusal(node.senderMode);
99
+ if (refusal) throw new Error(refusal);
100
+ }
101
+ return decorate(node, accounts, impersonation);
102
+ }
103
+
104
+ /** The decorator itself, over accounts already derived (and so validated). */
105
+ function decorate(
106
+ node: SlimNode,
107
+ accounts: readonly DevAccount[],
108
+ impersonationOn: boolean,
109
+ ): Required<SlimNode> {
110
+ const addresses = accounts.map((a) => a.address);
111
+ const servedPorts = new Set<ServedProvider>();
112
+ const impersonation = createImpersonation(impersonationOn);
113
+ const transactions = createTransactionMethods(node, accounts, impersonation);
114
+ const signer = createMessageSigner(accounts, impersonation);
115
+
116
+ async function request(args: RequestArguments): Promise<unknown> {
117
+ switch (args.method) {
118
+ case 'eth_accounts':
119
+ // A fresh array each time, so a caller mutating its answer cannot
120
+ // change the next one.
121
+ return [...addresses];
122
+ case 'eth_sendTransaction':
123
+ return transactions.sendTransaction(args.params);
124
+ case 'eth_signTransaction':
125
+ return transactions.signTransaction(args.params);
126
+ case 'personal_sign':
127
+ return signer.personalSign(args.params);
128
+ case 'eth_sign':
129
+ return signer.ethSign(args.params);
130
+ case 'eth_signTypedData_v4':
131
+ return signer.signTypedDataV4(args.params);
132
+ default:
133
+ if (IMPERSONATION_METHODS.has(args.method))
134
+ // On the send queue, so a send issued before it sees the set as it was.
135
+ return transactions.inOrder(() =>
136
+ impersonation.request(args.method, args.params),
137
+ );
138
+ return node.request(args);
139
+ }
140
+ }
141
+
142
+ const devNode: Required<SlimNode> = {
143
+ request,
144
+ mine: () => node.mine(),
145
+ dumpState: () => node.dumpState(),
146
+ loadState: (state) => node.loadState(state),
147
+ onNewHead: (cb) => node.onNewHead(cb),
148
+ getStateRoot: () => node.getStateRoot(),
149
+ computeStateRoot: node.computeStateRoot,
150
+ senderMode: node.senderMode,
151
+ engine: node.engine,
152
+ async serveOn(port) {
153
+ const server = serveProvider({request}, port);
154
+ servedPorts.add(server);
155
+ return {
156
+ async close() {
157
+ server.close();
158
+ servedPorts.delete(server);
159
+ },
160
+ };
161
+ },
162
+ async dispose() {
163
+ for (const server of servedPorts) server.close();
164
+ servedPorts.clear();
165
+ await node.dispose();
166
+ },
167
+ };
168
+ return devNode;
169
+ }
170
+
171
+ /**
172
+ * Create a webevm node whose dev accounts are FUNDED AT GENESIS, as anvil and
173
+ * Hardhat fund theirs, and return it wrapped (see {@link wrapDevNode}).
174
+ *
175
+ * const node = await createDevNode(); // anvil's ten accounts, 10,000 ETH each
176
+ *
177
+ * The dev accounts' balances (and `fundAccounts`) are merged into webevm's
178
+ * `initialBalances` (see `devAccountBalances` for the precedence), and the node
179
+ * is created with webevm's `createNode`. Like every `initialBalances`, they
180
+ * apply to a NEW genesis only: a state restored by `loadState` or `persistence`
181
+ * keeps its own balances.
182
+ *
183
+ * With `impersonation: true` the node is created with `senderMode: 'trusted'`,
184
+ * which the option needs; an explicit `senderMode: 'recover'` alongside it is
185
+ * refused before any node is created.
186
+ */
187
+ export async function createDevNode(
188
+ options: DevNodeOptions = {},
189
+ ): Promise<Required<SlimNode>> {
190
+ const {
191
+ accounts,
192
+ balance,
193
+ fund,
194
+ fundAccounts,
195
+ initialBalances,
196
+ impersonation,
197
+ ...rest
198
+ } = options;
199
+ const impersonationOn = impersonation === true;
200
+ if (impersonationOn && rest.senderMode !== undefined) {
201
+ const refusal = impersonationRefusal(rest.senderMode);
202
+ if (refusal) throw new Error(refusal);
203
+ }
204
+ // Derive (and so validate) the accounts and their balances BEFORE creating a
205
+ // node, so a bad config throws with nothing left behind to dispose.
206
+ const devAccounts = deriveDevAccounts(accounts);
207
+ const funded = devAccountBalances({
208
+ accounts,
209
+ balance,
210
+ fund,
211
+ fundAccounts,
212
+ initialBalances,
213
+ });
214
+ const node = await createNode({
215
+ ...rest,
216
+ ...(impersonationOn ? {senderMode: 'trusted' as const} : {}),
217
+ initialBalances: funded,
218
+ });
219
+ return decorate(node, devAccounts, impersonationOn);
220
+ }