viem 0.0.0 → 0.0.1-alpha.1

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.
@@ -0,0 +1,1098 @@
1
+ import {
2
+ BaseError,
3
+ __publicField,
4
+ checksumAddress,
5
+ encodeHex,
6
+ format,
7
+ formatBlock,
8
+ formatFeeHistory,
9
+ formatLog,
10
+ formatTransaction,
11
+ formatTransactionReceipt,
12
+ formatTransactionRequest,
13
+ getAddress,
14
+ getCache,
15
+ hexToNumber,
16
+ numberToHex,
17
+ wait,
18
+ withCache
19
+ } from "./chunk-Z6LRV6XI.js";
20
+
21
+ // src/actions/wallet/addChain.ts
22
+ async function addChain(client, chain) {
23
+ const { id, name, nativeCurrency, rpcUrls, blockExplorers } = chain;
24
+ await client.request({
25
+ method: "wallet_addEthereumChain",
26
+ params: [
27
+ {
28
+ chainId: numberToHex(id),
29
+ chainName: name,
30
+ nativeCurrency,
31
+ rpcUrls: rpcUrls.default.http,
32
+ blockExplorerUrls: blockExplorers ? Object.values(blockExplorers).map(({ url }) => url) : void 0
33
+ }
34
+ ]
35
+ });
36
+ }
37
+
38
+ // src/actions/wallet/getAccounts.ts
39
+ async function getAccounts(client) {
40
+ const addresses = await client.request({ method: "eth_accounts" });
41
+ return addresses.map((address) => checksumAddress(address));
42
+ }
43
+
44
+ // src/actions/wallet/getPermissions.ts
45
+ async function getPermissions(client) {
46
+ const permissions = await client.request({ method: "wallet_getPermissions" });
47
+ return permissions;
48
+ }
49
+
50
+ // src/actions/wallet/requestAccounts.ts
51
+ async function requestAccounts(client) {
52
+ const addresses = await client.request({ method: "eth_requestAccounts" });
53
+ return addresses.map((address) => getAddress(address));
54
+ }
55
+
56
+ // src/actions/wallet/requestPermissions.ts
57
+ async function requestPermissions(client, permissions) {
58
+ return client.request({
59
+ method: "wallet_requestPermissions",
60
+ params: [permissions]
61
+ });
62
+ }
63
+
64
+ // src/actions/wallet/sendTransaction.ts
65
+ async function sendTransaction(client, {
66
+ chain,
67
+ from,
68
+ accessList,
69
+ data,
70
+ gas,
71
+ gasPrice,
72
+ maxFeePerGas,
73
+ maxPriorityFeePerGas,
74
+ nonce,
75
+ to,
76
+ value,
77
+ ...rest
78
+ }) {
79
+ if (maxFeePerGas !== void 0 && maxPriorityFeePerGas !== void 0 && maxFeePerGas < maxPriorityFeePerGas)
80
+ throw new InvalidGasArgumentsError();
81
+ const request_ = format(
82
+ {
83
+ from,
84
+ accessList,
85
+ data,
86
+ gas,
87
+ gasPrice,
88
+ maxFeePerGas,
89
+ maxPriorityFeePerGas,
90
+ nonce,
91
+ to,
92
+ value,
93
+ ...rest
94
+ },
95
+ {
96
+ formatter: chain?.formatters?.transactionRequest || formatTransactionRequest
97
+ }
98
+ );
99
+ const hash = await client.request({
100
+ method: "eth_sendTransaction",
101
+ params: [request_]
102
+ });
103
+ return hash;
104
+ }
105
+ var InvalidGasArgumentsError = class extends BaseError {
106
+ constructor() {
107
+ super("`maxFeePerGas` cannot be less than `maxPriorityFeePerGas`");
108
+ __publicField(this, "name", "InvalidGasArgumentsError");
109
+ }
110
+ };
111
+
112
+ // src/actions/wallet/signMessage.ts
113
+ async function signMessage(client, { from, data: data_ }) {
114
+ let data;
115
+ if (typeof data_ === "string") {
116
+ if (!data_.startsWith("0x"))
117
+ throw new BaseError(
118
+ `data ("${data_}") must be a hex value. Encode it first to a hex with the \`encodeHex\` util.`,
119
+ {
120
+ docsPath: "/TODO"
121
+ }
122
+ );
123
+ data = data_;
124
+ } else {
125
+ data = encodeHex(data_);
126
+ }
127
+ const signed = await client.request({
128
+ method: "personal_sign",
129
+ params: [data, from]
130
+ });
131
+ return signed;
132
+ }
133
+
134
+ // src/actions/wallet/switchChain.ts
135
+ async function switchChain(client, { id }) {
136
+ await client.request({
137
+ method: "wallet_switchEthereumChain",
138
+ params: [
139
+ {
140
+ chainId: numberToHex(id)
141
+ }
142
+ ]
143
+ });
144
+ }
145
+
146
+ // src/actions/wallet/watchAsset.ts
147
+ async function watchAsset(client, params) {
148
+ const added = await client.request({
149
+ method: "wallet_watchAsset",
150
+ params: [params]
151
+ });
152
+ return added;
153
+ }
154
+
155
+ // src/actions/public/call.ts
156
+ async function call(client, {
157
+ blockNumber,
158
+ blockTag = "latest",
159
+ chain,
160
+ from,
161
+ accessList,
162
+ data,
163
+ gas,
164
+ gasPrice,
165
+ maxFeePerGas,
166
+ maxPriorityFeePerGas,
167
+ nonce,
168
+ to,
169
+ value,
170
+ ...rest
171
+ }) {
172
+ if (maxFeePerGas !== void 0 && maxPriorityFeePerGas !== void 0 && maxFeePerGas < maxPriorityFeePerGas)
173
+ throw new InvalidGasArgumentsError();
174
+ const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0;
175
+ const request_ = format(
176
+ {
177
+ from,
178
+ accessList,
179
+ data,
180
+ gas,
181
+ gasPrice,
182
+ maxFeePerGas,
183
+ maxPriorityFeePerGas,
184
+ nonce,
185
+ to,
186
+ value,
187
+ ...rest
188
+ },
189
+ {
190
+ formatter: chain?.formatters?.transactionRequest || formatTransactionRequest
191
+ }
192
+ );
193
+ const response = await client.request({
194
+ method: "eth_call",
195
+ params: [request_, blockNumberHex || blockTag]
196
+ });
197
+ if (response === "0x")
198
+ return { data: void 0 };
199
+ return { data: response };
200
+ }
201
+
202
+ // src/actions/public/createPendingTransactionFilter.ts
203
+ async function createPendingTransactionFilter(client) {
204
+ const id = await client.request({
205
+ method: "eth_newPendingTransactionFilter"
206
+ });
207
+ return { id, type: "transaction" };
208
+ }
209
+
210
+ // src/actions/public/createBlockFilter.ts
211
+ async function createBlockFilter(client) {
212
+ const id = await client.request({
213
+ method: "eth_newBlockFilter"
214
+ });
215
+ return { id, type: "block" };
216
+ }
217
+
218
+ // src/actions/public/estimateGas.ts
219
+ async function estimateGas(client, {
220
+ blockNumber,
221
+ blockTag = "latest",
222
+ data,
223
+ from,
224
+ gas,
225
+ gasPrice,
226
+ maxFeePerGas,
227
+ maxPriorityFeePerGas,
228
+ to,
229
+ value
230
+ }) {
231
+ const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0;
232
+ const parameters = {
233
+ data,
234
+ from,
235
+ gas: gas ? numberToHex(gas) : void 0,
236
+ gasPrice: gasPrice ? numberToHex(gasPrice) : void 0,
237
+ maxFeePerGas: maxFeePerGas ? numberToHex(maxFeePerGas) : void 0,
238
+ maxPriorityFeePerGas: maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : void 0,
239
+ to,
240
+ value: value ? numberToHex(value) : void 0
241
+ };
242
+ const balance = await client.request({
243
+ method: "eth_estimateGas",
244
+ params: [parameters, blockNumberHex || blockTag]
245
+ });
246
+ return BigInt(balance);
247
+ }
248
+
249
+ // src/actions/public/getBalance.ts
250
+ async function getBalance(client, { address, blockNumber, blockTag = "latest" }) {
251
+ const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0;
252
+ const balance = await client.request({
253
+ method: "eth_getBalance",
254
+ params: [address, blockNumberHex || blockTag]
255
+ });
256
+ return BigInt(balance);
257
+ }
258
+
259
+ // src/actions/public/getBlock.ts
260
+ async function getBlock(client, {
261
+ blockHash,
262
+ blockNumber,
263
+ blockTag = "latest",
264
+ includeTransactions = false
265
+ } = {}) {
266
+ const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
267
+ let block = null;
268
+ if (blockHash) {
269
+ block = await client.request({
270
+ method: "eth_getBlockByHash",
271
+ params: [blockHash, includeTransactions]
272
+ });
273
+ } else {
274
+ block = await client.request({
275
+ method: "eth_getBlockByNumber",
276
+ params: [blockNumberHex || blockTag, includeTransactions]
277
+ });
278
+ }
279
+ if (!block)
280
+ throw new BlockNotFoundError({ blockHash, blockNumber });
281
+ return format(block, {
282
+ formatter: client.chain?.formatters?.block || formatBlock
283
+ });
284
+ }
285
+ var BlockNotFoundError = class extends BaseError {
286
+ constructor({
287
+ blockHash,
288
+ blockNumber
289
+ }) {
290
+ let identifier = "Block";
291
+ if (blockHash)
292
+ identifier = `Block at hash "${blockHash}"`;
293
+ if (blockNumber)
294
+ identifier = `Block at number "${blockNumber}"`;
295
+ super(`${identifier} could not be found.`);
296
+ __publicField(this, "name", "BlockNotFoundError");
297
+ }
298
+ };
299
+
300
+ // src/actions/public/getBlockNumber.ts
301
+ var cacheKey = (id) => `blockNumber.${id}`;
302
+ function getBlockNumberCache(id) {
303
+ return getCache(cacheKey(id));
304
+ }
305
+ async function getBlockNumber(client, { maxAge = client.pollingInterval } = {}) {
306
+ const blockNumberHex = await withCache(
307
+ () => client.request({
308
+ method: "eth_blockNumber"
309
+ }),
310
+ { cacheKey: cacheKey(client.uid), maxAge }
311
+ );
312
+ return BigInt(blockNumberHex);
313
+ }
314
+
315
+ // src/actions/public/getBlockTransactionCount.ts
316
+ async function getBlockTransactionCount(client, {
317
+ blockHash,
318
+ blockNumber,
319
+ blockTag = "latest"
320
+ } = {}) {
321
+ const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
322
+ let count = null;
323
+ if (blockHash) {
324
+ count = await client.request({
325
+ method: "eth_getBlockTransactionCountByHash",
326
+ params: [blockHash]
327
+ });
328
+ } else {
329
+ count = await client.request({
330
+ method: "eth_getBlockTransactionCountByNumber",
331
+ params: [blockNumberHex || blockTag]
332
+ });
333
+ }
334
+ return hexToNumber(count);
335
+ }
336
+
337
+ // src/actions/public/getChainId.ts
338
+ async function getChainId(client) {
339
+ const chainIdHex = await client.request({ method: "eth_chainId" });
340
+ return hexToNumber(chainIdHex);
341
+ }
342
+
343
+ // src/actions/public/getFeeHistory.ts
344
+ async function getFeeHistory(client, {
345
+ blockCount,
346
+ blockNumber,
347
+ blockTag = "latest",
348
+ rewardPercentiles
349
+ }) {
350
+ const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0;
351
+ const feeHistory = await client.request({
352
+ method: "eth_feeHistory",
353
+ params: [
354
+ numberToHex(blockCount),
355
+ blockNumberHex || blockTag,
356
+ rewardPercentiles
357
+ ]
358
+ });
359
+ return formatFeeHistory(feeHistory);
360
+ }
361
+
362
+ // src/actions/public/getFilterChanges.ts
363
+ async function getFilterChanges(client, { filter }) {
364
+ const logs = await client.request({
365
+ method: "eth_getFilterChanges",
366
+ params: [filter.id]
367
+ });
368
+ return logs.map(
369
+ (log) => typeof log === "string" ? log : formatLog(log)
370
+ );
371
+ }
372
+
373
+ // src/actions/public/getFilterLogs.ts
374
+ async function getFilterLogs(client, { filter }) {
375
+ const logs = await client.request({
376
+ method: "eth_getFilterLogs",
377
+ params: [filter.id]
378
+ });
379
+ return logs.map(formatLog);
380
+ }
381
+
382
+ // src/actions/public/getGasPrice.ts
383
+ async function getGasPrice(client) {
384
+ const gasPrice = await client.request({
385
+ method: "eth_gasPrice"
386
+ });
387
+ return BigInt(gasPrice);
388
+ }
389
+
390
+ // src/actions/public/getTransaction.ts
391
+ async function getTransaction(client, {
392
+ blockHash,
393
+ blockNumber,
394
+ blockTag = "latest",
395
+ hash,
396
+ index
397
+ }) {
398
+ const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
399
+ let transaction = null;
400
+ if (hash) {
401
+ transaction = await client.request({
402
+ method: "eth_getTransactionByHash",
403
+ params: [hash]
404
+ });
405
+ } else if (blockHash) {
406
+ transaction = await client.request({
407
+ method: "eth_getTransactionByBlockHashAndIndex",
408
+ params: [blockHash, numberToHex(index)]
409
+ });
410
+ } else if (blockNumberHex || blockTag) {
411
+ transaction = await client.request({
412
+ method: "eth_getTransactionByBlockNumberAndIndex",
413
+ params: [blockNumberHex || blockTag, numberToHex(index)]
414
+ });
415
+ }
416
+ if (!transaction)
417
+ throw new TransactionNotFoundError({
418
+ blockHash,
419
+ blockNumber,
420
+ blockTag,
421
+ hash,
422
+ index
423
+ });
424
+ return format(transaction, {
425
+ formatter: client.chain?.formatters?.transaction || formatTransaction
426
+ });
427
+ }
428
+ var TransactionNotFoundError = class extends BaseError {
429
+ constructor({
430
+ blockHash,
431
+ blockNumber,
432
+ blockTag,
433
+ hash,
434
+ index
435
+ }) {
436
+ let identifier = "Transaction";
437
+ if (blockTag && index !== void 0)
438
+ identifier = `Transaction at block time "${blockTag}" at index "${index}"`;
439
+ if (blockHash && index !== void 0)
440
+ identifier = `Transaction at block hash "${blockHash}" at index "${index}"`;
441
+ if (blockNumber && index !== void 0)
442
+ identifier = `Transaction at block number "${blockNumber}" at index "${index}"`;
443
+ if (hash)
444
+ identifier = `Transaction with hash "${hash}"`;
445
+ super(`${identifier} could not be found.`);
446
+ __publicField(this, "name", "TransactionNotFoundError");
447
+ }
448
+ };
449
+
450
+ // src/actions/public/getTransactionConfirmations.ts
451
+ async function getTransactionConfirmations(client, { hash, transactionReceipt }) {
452
+ const [blockNumber, transaction] = await Promise.all([
453
+ getBlockNumber(client),
454
+ hash ? getTransaction(client, { hash }) : void 0
455
+ ]);
456
+ const transactionBlockNumber = transactionReceipt?.blockNumber || transaction?.blockNumber;
457
+ if (!transactionBlockNumber)
458
+ return 0n;
459
+ return blockNumber - transactionBlockNumber + 1n;
460
+ }
461
+
462
+ // src/actions/public/getTransactionCount.ts
463
+ async function getTransactionCount(client, { address, blockTag = "latest", blockNumber }) {
464
+ const count = await client.request({
465
+ method: "eth_getTransactionCount",
466
+ params: [address, blockNumber ? numberToHex(blockNumber) : blockTag]
467
+ });
468
+ return hexToNumber(count ?? "0x0");
469
+ }
470
+
471
+ // src/actions/public/getTransactionReceipt.ts
472
+ async function getTransactionReceipt(client, { hash }) {
473
+ const receipt = await client.request({
474
+ method: "eth_getTransactionReceipt",
475
+ params: [hash]
476
+ });
477
+ if (!receipt)
478
+ throw new TransactionReceiptNotFoundError({ hash });
479
+ return format(receipt, {
480
+ formatter: client.chain?.formatters?.transactionReceipt || formatTransactionReceipt
481
+ });
482
+ }
483
+ var TransactionReceiptNotFoundError = class extends BaseError {
484
+ constructor({ hash }) {
485
+ super(
486
+ `Transaction receipt with hash "${hash}" could not be found. The Transaction may not be processed on a block yet.`
487
+ );
488
+ __publicField(this, "name", "TransactionReceiptNotFoundError");
489
+ }
490
+ };
491
+
492
+ // src/actions/public/uninstallFilter.ts
493
+ async function uninstallFilter(client, { filter }) {
494
+ return client.request({
495
+ method: "eth_uninstallFilter",
496
+ params: [filter.id]
497
+ });
498
+ }
499
+
500
+ // src/utils/observe.ts
501
+ var listenersCache = /* @__PURE__ */ new Map();
502
+ var cleanupCache = /* @__PURE__ */ new Map();
503
+ var callbackCount = 0;
504
+ function observe(observerId, callbacks, fn) {
505
+ const callbackId = ++callbackCount;
506
+ const getListeners = () => listenersCache.get(observerId) || [];
507
+ const unsubscribe = () => {
508
+ const listeners2 = getListeners();
509
+ listenersCache.set(
510
+ observerId,
511
+ listeners2.filter((cb) => cb.id !== callbackId)
512
+ );
513
+ };
514
+ const unwatch = () => {
515
+ const cleanup2 = cleanupCache.get(observerId);
516
+ if (getListeners().length === 1 && cleanup2)
517
+ cleanup2();
518
+ unsubscribe();
519
+ };
520
+ const listeners = getListeners();
521
+ listenersCache.set(observerId, [
522
+ ...listeners,
523
+ { id: callbackId, fns: callbacks }
524
+ ]);
525
+ if (listeners && listeners.length > 0)
526
+ return unwatch;
527
+ let emit = {};
528
+ for (const key in callbacks) {
529
+ emit[key] = (...args) => {
530
+ const listeners2 = getListeners();
531
+ if (listeners2.length === 0)
532
+ return;
533
+ listeners2.forEach((listener) => listener.fns[key]?.(...args));
534
+ };
535
+ }
536
+ const cleanup = fn(emit);
537
+ if (typeof cleanup === "function")
538
+ cleanupCache.set(observerId, cleanup);
539
+ return unwatch;
540
+ }
541
+
542
+ // src/actions/public/waitForTransactionReceipt.ts
543
+ async function waitForTransactionReceipt(client, {
544
+ confirmations = 1,
545
+ hash,
546
+ onReplaced,
547
+ pollingInterval = client.pollingInterval,
548
+ timeout
549
+ }) {
550
+ const observerId = JSON.stringify([
551
+ "waitForTransactionReceipt",
552
+ client.uid,
553
+ hash
554
+ ]);
555
+ let transaction;
556
+ let replacedTransaction;
557
+ let receipt;
558
+ return new Promise((resolve, reject) => {
559
+ if (timeout)
560
+ setTimeout(
561
+ () => reject(new WaitForTransactionReceiptTimeoutError({ hash })),
562
+ timeout
563
+ );
564
+ const unobserve = observe(
565
+ observerId,
566
+ { onReplaced, resolve, reject },
567
+ (emit) => {
568
+ const unwatch = watchBlockNumber(client, {
569
+ emitMissed: true,
570
+ emitOnBegin: true,
571
+ pollingInterval,
572
+ async onBlockNumber(blockNumber) {
573
+ const done = async (fn) => {
574
+ unwatch();
575
+ fn();
576
+ unobserve();
577
+ };
578
+ try {
579
+ if (receipt) {
580
+ if (blockNumber - receipt.blockNumber + 1n < confirmations)
581
+ return;
582
+ done(() => emit.resolve(receipt));
583
+ return;
584
+ }
585
+ transaction = await getTransaction(client, { hash });
586
+ receipt = await getTransactionReceipt(client, { hash });
587
+ if (blockNumber - receipt.blockNumber + 1n < confirmations)
588
+ return;
589
+ done(() => emit.resolve(receipt));
590
+ } catch (err) {
591
+ if (transaction && (err instanceof TransactionNotFoundError || err instanceof TransactionReceiptNotFoundError)) {
592
+ replacedTransaction = transaction;
593
+ const block = await getBlock(client, {
594
+ blockNumber,
595
+ includeTransactions: true
596
+ });
597
+ const replacementTransaction = block.transactions.find(
598
+ ({ from, nonce }) => from === replacedTransaction.from && nonce === replacedTransaction.nonce
599
+ );
600
+ if (!replacementTransaction)
601
+ return;
602
+ receipt = await getTransactionReceipt(client, {
603
+ hash: replacementTransaction.hash
604
+ });
605
+ if (blockNumber - receipt.blockNumber + 1n < confirmations)
606
+ return;
607
+ let reason = "replaced";
608
+ if (replacementTransaction.to === replacedTransaction.to && replacementTransaction.value === replacedTransaction.value) {
609
+ reason = "repriced";
610
+ } else if (replacementTransaction.from === replacementTransaction.to && replacementTransaction.value === 0n) {
611
+ reason = "cancelled";
612
+ }
613
+ done(() => {
614
+ emit.onReplaced?.({
615
+ reason,
616
+ replacedTransaction,
617
+ transaction: replacementTransaction,
618
+ transactionReceipt: receipt
619
+ });
620
+ emit.resolve(receipt);
621
+ });
622
+ } else {
623
+ done(() => emit.reject(err));
624
+ }
625
+ }
626
+ }
627
+ });
628
+ return unwatch;
629
+ }
630
+ );
631
+ });
632
+ }
633
+ var WaitForTransactionReceiptTimeoutError = class extends BaseError {
634
+ constructor({ hash }) {
635
+ super(
636
+ `Timed out while waiting for transaction with hash "${hash}" to be confirmed.`
637
+ );
638
+ __publicField(this, "name", "WaitForTransactionReceiptTimeoutError");
639
+ }
640
+ };
641
+
642
+ // src/utils/poll.ts
643
+ function poll(fn, { emitOnBegin, initialWaitTime, interval }) {
644
+ let active = true;
645
+ const unwatch = () => active = false;
646
+ const watch = async () => {
647
+ let data;
648
+ if (emitOnBegin)
649
+ data = await fn({ unpoll: unwatch });
650
+ const initialWait = await initialWaitTime?.(data) ?? interval;
651
+ await wait(initialWait);
652
+ const poll2 = async () => {
653
+ if (!active)
654
+ return;
655
+ await fn({ unpoll: unwatch });
656
+ await wait(interval);
657
+ poll2();
658
+ };
659
+ poll2();
660
+ };
661
+ watch();
662
+ return unwatch;
663
+ }
664
+
665
+ // src/actions/public/watchBlockNumber.ts
666
+ function watchBlockNumber(client, {
667
+ emitOnBegin = false,
668
+ emitMissed = false,
669
+ onBlockNumber,
670
+ onError,
671
+ pollingInterval = client.pollingInterval
672
+ }) {
673
+ const observerId = JSON.stringify([
674
+ "watchBlockNumber",
675
+ client.uid,
676
+ emitOnBegin,
677
+ emitMissed,
678
+ pollingInterval
679
+ ]);
680
+ let prevBlockNumber;
681
+ return observe(
682
+ observerId,
683
+ { onBlockNumber, onError },
684
+ (emit) => poll(
685
+ async () => {
686
+ try {
687
+ const blockNumber = await getBlockNumber(client, { maxAge: 0 });
688
+ if (prevBlockNumber) {
689
+ if (blockNumber === prevBlockNumber)
690
+ return;
691
+ if (blockNumber - prevBlockNumber > 1 && emitMissed) {
692
+ for (let i = prevBlockNumber + 1n; i < blockNumber; i++) {
693
+ emit.onBlockNumber(i, prevBlockNumber);
694
+ prevBlockNumber = i;
695
+ }
696
+ }
697
+ }
698
+ prevBlockNumber = blockNumber;
699
+ emit.onBlockNumber(blockNumber, prevBlockNumber);
700
+ } catch (err) {
701
+ emit.onError?.(err);
702
+ }
703
+ },
704
+ {
705
+ emitOnBegin,
706
+ interval: pollingInterval
707
+ }
708
+ )
709
+ );
710
+ }
711
+
712
+ // src/actions/public/watchBlocks.ts
713
+ function watchBlocks(client, {
714
+ blockTag = "latest",
715
+ emitMissed = false,
716
+ emitOnBegin = false,
717
+ onBlock,
718
+ onError,
719
+ includeTransactions = false,
720
+ pollingInterval = client.pollingInterval
721
+ }) {
722
+ const observerId = JSON.stringify([
723
+ "watchBlocks",
724
+ client.uid,
725
+ emitMissed,
726
+ emitOnBegin,
727
+ includeTransactions,
728
+ pollingInterval
729
+ ]);
730
+ let prevBlock;
731
+ return observe(
732
+ observerId,
733
+ { onBlock, onError },
734
+ (emit) => poll(
735
+ async () => {
736
+ try {
737
+ const block = await getBlock(client, {
738
+ blockTag,
739
+ includeTransactions
740
+ });
741
+ if (block.number && prevBlock?.number) {
742
+ if (block.number === prevBlock.number)
743
+ return;
744
+ if (block.number - prevBlock.number > 1 && emitMissed) {
745
+ for (let i = prevBlock?.number + 1n; i < block.number; i++) {
746
+ const block2 = await getBlock(client, {
747
+ blockNumber: i,
748
+ includeTransactions
749
+ });
750
+ emit.onBlock(block2, prevBlock);
751
+ prevBlock = block2;
752
+ }
753
+ }
754
+ }
755
+ emit.onBlock(block, prevBlock);
756
+ prevBlock = block;
757
+ } catch (err) {
758
+ emit.onError?.(err);
759
+ }
760
+ },
761
+ {
762
+ emitOnBegin,
763
+ interval: pollingInterval
764
+ }
765
+ )
766
+ );
767
+ }
768
+
769
+ // src/actions/public/watchPendingTransactions.ts
770
+ function watchPendingTransactions(client, {
771
+ batch = true,
772
+ onError,
773
+ onTransactions,
774
+ pollingInterval = client.pollingInterval
775
+ }) {
776
+ const observerId = JSON.stringify([
777
+ "watchPendingTransactions",
778
+ client.uid,
779
+ batch,
780
+ pollingInterval
781
+ ]);
782
+ return observe(observerId, { onTransactions, onError }, (emit) => {
783
+ let filter;
784
+ const unwatch = poll(
785
+ async () => {
786
+ try {
787
+ if (!filter) {
788
+ try {
789
+ filter = await createPendingTransactionFilter(client);
790
+ return;
791
+ } catch (err) {
792
+ unwatch();
793
+ throw err;
794
+ }
795
+ }
796
+ const hashes = await getFilterChanges(client, { filter });
797
+ if (batch)
798
+ emit.onTransactions(hashes);
799
+ else
800
+ hashes.forEach((hash) => emit.onTransactions([hash]));
801
+ } catch (err) {
802
+ emit.onError?.(err);
803
+ }
804
+ },
805
+ {
806
+ emitOnBegin: true,
807
+ interval: pollingInterval
808
+ }
809
+ );
810
+ return async () => {
811
+ if (filter)
812
+ await uninstallFilter(client, { filter });
813
+ unwatch();
814
+ };
815
+ });
816
+ }
817
+
818
+ // src/actions/test/dropTransaction.ts
819
+ async function dropTransaction(client, { hash }) {
820
+ return await client.request({
821
+ method: `${client.mode}_dropTransaction`,
822
+ params: [hash]
823
+ });
824
+ }
825
+
826
+ // src/actions/test/getAutomine.ts
827
+ async function getAutomine(client) {
828
+ return await client.request({
829
+ method: `${client.mode}_getAutomine`
830
+ });
831
+ }
832
+
833
+ // src/actions/test/getTxpoolContent.ts
834
+ async function getTxpoolContent(client) {
835
+ return await client.request({
836
+ method: "txpool_content"
837
+ });
838
+ }
839
+
840
+ // src/actions/test/getTxpoolStatus.ts
841
+ async function getTxpoolStatus(client) {
842
+ const { pending, queued } = await client.request({
843
+ method: "txpool_status"
844
+ });
845
+ return {
846
+ pending: hexToNumber(pending),
847
+ queued: hexToNumber(queued)
848
+ };
849
+ }
850
+
851
+ // src/actions/test/impersonateAccount.ts
852
+ async function impersonateAccount(client, { address }) {
853
+ return await client.request({
854
+ method: `${client.mode}_impersonateAccount`,
855
+ params: [address]
856
+ });
857
+ }
858
+
859
+ // src/actions/test/increaseTime.ts
860
+ async function increaseTime(client, { seconds }) {
861
+ return await client.request({
862
+ method: "evm_increaseTime",
863
+ params: [numberToHex(seconds)]
864
+ });
865
+ }
866
+
867
+ // src/actions/test/inspectTxpool.ts
868
+ async function inspectTxpool(client) {
869
+ return await client.request({
870
+ method: "txpool_inspect"
871
+ });
872
+ }
873
+
874
+ // src/actions/test/mine.ts
875
+ async function mine(client, { blocks, interval }) {
876
+ return await client.request({
877
+ method: `${client.mode}_mine`,
878
+ params: [numberToHex(blocks), numberToHex(interval || 0)]
879
+ });
880
+ }
881
+
882
+ // src/actions/test/removeBlockTimestampInterval.ts
883
+ async function removeBlockTimestampInterval(client) {
884
+ return await client.request({
885
+ method: `${client.mode}_removeBlockTimestampInterval`
886
+ });
887
+ }
888
+
889
+ // src/actions/test/reset.ts
890
+ async function reset(client, { blockNumber, jsonRpcUrl } = {}) {
891
+ return await client.request({
892
+ method: `${client.mode}_reset`,
893
+ params: [{ forking: { blockNumber: Number(blockNumber), jsonRpcUrl } }]
894
+ });
895
+ }
896
+
897
+ // src/actions/test/revert.ts
898
+ async function revert(client, { id }) {
899
+ return await client.request({
900
+ method: "evm_revert",
901
+ params: [id]
902
+ });
903
+ }
904
+
905
+ // src/actions/test/sendUnsignedTransaction.ts
906
+ async function sendUnsignedTransaction(client, request) {
907
+ const request_ = formatTransactionRequest(request);
908
+ const hash = await client.request({
909
+ method: "eth_sendUnsignedTransaction",
910
+ params: [request_]
911
+ });
912
+ return hash;
913
+ }
914
+
915
+ // src/actions/test/setAutomine.ts
916
+ async function setAutomine(client, enabled) {
917
+ return await client.request({
918
+ method: "evm_setAutomine",
919
+ params: [enabled]
920
+ });
921
+ }
922
+
923
+ // src/actions/test/setBalance.ts
924
+ async function setBalance(client, { address, value }) {
925
+ return await client.request({
926
+ method: `${client.mode}_setBalance`,
927
+ params: [address, numberToHex(value)]
928
+ });
929
+ }
930
+
931
+ // src/actions/test/setBlockGasLimit.ts
932
+ async function setBlockGasLimit(client, { gasLimit }) {
933
+ return await client.request({
934
+ method: "evm_setBlockGasLimit",
935
+ params: [numberToHex(gasLimit)]
936
+ });
937
+ }
938
+
939
+ // src/actions/test/setBlockTimestampInterval.ts
940
+ async function setBlockTimestampInterval(client, { interval }) {
941
+ return await client.request({
942
+ method: `${client.mode}_setBlockTimestampInterval`,
943
+ params: [interval]
944
+ });
945
+ }
946
+
947
+ // src/actions/test/setCode.ts
948
+ async function setCode(client, { address, bytecode }) {
949
+ return await client.request({
950
+ method: `${client.mode}_setCode`,
951
+ params: [address, bytecode]
952
+ });
953
+ }
954
+
955
+ // src/actions/test/setCoinbase.ts
956
+ async function setCoinbase(client, { address }) {
957
+ return await client.request({
958
+ method: `${client.mode}_setCoinbase`,
959
+ params: [address]
960
+ });
961
+ }
962
+
963
+ // src/actions/test/setIntervalMining.ts
964
+ async function setIntervalMining(client, { interval }) {
965
+ return await client.request({
966
+ method: "evm_setIntervalMining",
967
+ params: [interval]
968
+ });
969
+ }
970
+
971
+ // src/actions/test/setLoggingEnabled.ts
972
+ async function setLoggingEnabled(client, enabled) {
973
+ return await client.request({
974
+ method: `${client.mode}_setLoggingEnabled`,
975
+ params: [enabled]
976
+ });
977
+ }
978
+
979
+ // src/actions/test/setMinGasPrice.ts
980
+ async function setMinGasPrice(client, { gasPrice }) {
981
+ return await client.request({
982
+ method: `${client.mode}_setMinGasPrice`,
983
+ params: [numberToHex(gasPrice)]
984
+ });
985
+ }
986
+
987
+ // src/actions/test/setNextBlockBaseFeePerGas.ts
988
+ async function setNextBlockBaseFeePerGas(client, { baseFeePerGas }) {
989
+ return await client.request({
990
+ method: `${client.mode}_setNextBlockBaseFeePerGas`,
991
+ params: [numberToHex(baseFeePerGas)]
992
+ });
993
+ }
994
+
995
+ // src/actions/test/setNextBlockTimestamp.ts
996
+ async function setNextBlockTimestamp(client, { timestamp }) {
997
+ return await client.request({
998
+ method: "evm_setNextBlockTimestamp",
999
+ params: [numberToHex(timestamp)]
1000
+ });
1001
+ }
1002
+
1003
+ // src/actions/test/setNonce.ts
1004
+ async function setNonce(client, { address, nonce }) {
1005
+ return await client.request({
1006
+ method: `${client.mode}_setNonce`,
1007
+ params: [address, numberToHex(nonce)]
1008
+ });
1009
+ }
1010
+
1011
+ // src/actions/test/setStorageAt.ts
1012
+ async function setStorageAt(client, { address, index, value }) {
1013
+ return await client.request({
1014
+ method: `${client.mode}_setStorageAt`,
1015
+ params: [
1016
+ address,
1017
+ typeof index === "number" ? numberToHex(index) : index,
1018
+ value
1019
+ ]
1020
+ });
1021
+ }
1022
+
1023
+ // src/actions/test/snapshot.ts
1024
+ async function snapshot(client) {
1025
+ return await client.request({
1026
+ method: "evm_snapshot"
1027
+ });
1028
+ }
1029
+
1030
+ // src/actions/test/stopImpersonatingAccount.ts
1031
+ async function stopImpersonatingAccount(client, { address }) {
1032
+ return await client.request({
1033
+ method: `${client.mode}_stopImpersonatingAccount`,
1034
+ params: [address]
1035
+ });
1036
+ }
1037
+
1038
+ export {
1039
+ addChain,
1040
+ getAccounts,
1041
+ getPermissions,
1042
+ requestAccounts,
1043
+ requestPermissions,
1044
+ sendTransaction,
1045
+ signMessage,
1046
+ switchChain,
1047
+ watchAsset,
1048
+ call,
1049
+ createPendingTransactionFilter,
1050
+ createBlockFilter,
1051
+ estimateGas,
1052
+ getBalance,
1053
+ getBlock,
1054
+ getBlockNumberCache,
1055
+ getBlockNumber,
1056
+ getBlockTransactionCount,
1057
+ getChainId,
1058
+ getFeeHistory,
1059
+ getFilterChanges,
1060
+ getFilterLogs,
1061
+ getGasPrice,
1062
+ getTransaction,
1063
+ getTransactionConfirmations,
1064
+ getTransactionCount,
1065
+ getTransactionReceipt,
1066
+ uninstallFilter,
1067
+ waitForTransactionReceipt,
1068
+ watchBlockNumber,
1069
+ watchBlocks,
1070
+ watchPendingTransactions,
1071
+ dropTransaction,
1072
+ getAutomine,
1073
+ getTxpoolContent,
1074
+ getTxpoolStatus,
1075
+ impersonateAccount,
1076
+ increaseTime,
1077
+ inspectTxpool,
1078
+ mine,
1079
+ removeBlockTimestampInterval,
1080
+ reset,
1081
+ revert,
1082
+ sendUnsignedTransaction,
1083
+ setAutomine,
1084
+ setBalance,
1085
+ setBlockGasLimit,
1086
+ setBlockTimestampInterval,
1087
+ setCode,
1088
+ setCoinbase,
1089
+ setIntervalMining,
1090
+ setLoggingEnabled,
1091
+ setMinGasPrice,
1092
+ setNextBlockBaseFeePerGas,
1093
+ setNextBlockTimestamp,
1094
+ setNonce,
1095
+ setStorageAt,
1096
+ snapshot,
1097
+ stopImpersonatingAccount
1098
+ };