@dvmkit/dvm-cli 0.0.0 → 0.1.5

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 (50) hide show
  1. package/LICENSE +67 -0
  2. package/NOTICE +2 -0
  3. package/README.md +28 -3
  4. package/dist/_esm-MN4BUYV6.js +885 -0
  5. package/dist/_esm-NRGECLJ7.js +35 -0
  6. package/dist/accounts-2WZE4N5F.js +73 -0
  7. package/dist/actions-LR65XILR.js +244 -0
  8. package/dist/ccip-JXYJSXTW.js +18 -0
  9. package/dist/chains-LJ7XK6H3.js +1460 -0
  10. package/dist/chunk-2VVVWBQA.js +15436 -0
  11. package/dist/chunk-3SWX5BQP.js +66 -0
  12. package/dist/chunk-3W2M46WM.js +61142 -0
  13. package/dist/chunk-4JXFXP4Y.js +757 -0
  14. package/dist/chunk-4NWEJTAW.js +16616 -0
  15. package/dist/chunk-65EY7CT4.js +2691 -0
  16. package/dist/chunk-6CC6JGEU.js +1815 -0
  17. package/dist/chunk-6O27TEXD.js +1181 -0
  18. package/dist/chunk-7OK7MBT6.js +258 -0
  19. package/dist/chunk-BECPI5H5.js +30063 -0
  20. package/dist/chunk-CJTE5TS3.js +1298 -0
  21. package/dist/chunk-ECEM3ZAS.js +339 -0
  22. package/dist/chunk-ECK465AY.js +5614 -0
  23. package/dist/chunk-EGY4KDBW.js +5149 -0
  24. package/dist/chunk-EVQERRCP.js +21369 -0
  25. package/dist/chunk-EZHT2RLJ.js +1447 -0
  26. package/dist/chunk-F55NNH2F.js +6484 -0
  27. package/dist/chunk-G5C6E6PJ.js +9063 -0
  28. package/dist/chunk-GZWKCIYN.js +3319 -0
  29. package/dist/chunk-IYHTITNZ.js +45 -0
  30. package/dist/chunk-LH3QPVN6.js +9869 -0
  31. package/dist/chunk-MLDUKBU3.js +2426 -0
  32. package/dist/chunk-N3UJT2NJ.js +3 -0
  33. package/dist/chunk-OWJZYYMG.js +185 -0
  34. package/dist/chunk-RA24J4QM.js +3717 -0
  35. package/dist/chunk-ZJYO7OLO.js +514 -0
  36. package/dist/client-OWIOFBKS.js +54 -0
  37. package/dist/dist-2G3QBGID.js +47 -0
  38. package/dist/dvm.js +56008 -0
  39. package/dist/esm-RQLHAH2K.js +5183 -0
  40. package/dist/internal-QFQ7MJ5V.js +1228 -0
  41. package/dist/mine.wasm-DNBKYCTQ.js +12 -0
  42. package/dist/payout-reporter-3UB5WRCV-XTVZFIAO.js +17 -0
  43. package/dist/pocket-refill-PQ5ZVSBY.js +129 -0
  44. package/dist/revenue-reporter-JIKUPXOK-TYUBTF4P.js +11 -0
  45. package/dist/secp256k1-JLZEQ2H7.js +19 -0
  46. package/dist/tempo-lifecycle-SQL3KLEZ-AATA2SKI.js +28 -0
  47. package/dist/tempo-wallet-QOLEIPCV-SWCXRBDS.js +33 -0
  48. package/dist/x402-FTG2GRAQ-UGAUMUL6.js +80 -0
  49. package/package.json +63 -6
  50. package/skills/dvm/SKILL.md +71 -0
@@ -0,0 +1,3319 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __dvmCreateRequire } from "node:module";
3
+ const require = __dvmCreateRequire(import.meta.url);
4
+ import {
5
+ AccountNotFoundError,
6
+ AccountTypeNotSupportedError,
7
+ BlockNotFoundError,
8
+ NotFoundError,
9
+ assertCurrentChain,
10
+ createFilterRequestScope,
11
+ decodeEventLog,
12
+ encode,
13
+ encodeEventTopics,
14
+ estimateGas,
15
+ formatBlock,
16
+ formatLog,
17
+ formatTransactionReceipt,
18
+ formatUnits,
19
+ from5 as from,
20
+ fromAbi,
21
+ getAction,
22
+ getBlock,
23
+ getBlockNumber,
24
+ getChainId,
25
+ getCode,
26
+ getContractError,
27
+ getFilterChanges,
28
+ getLogs,
29
+ getSelector,
30
+ getTransaction,
31
+ getTransactionError,
32
+ observe,
33
+ parseEventLogs,
34
+ parseUnits,
35
+ poll,
36
+ readContract,
37
+ receiptStatuses,
38
+ sendTransaction,
39
+ uninstallFilter,
40
+ verifyHash2 as verifyHash,
41
+ withRetry,
42
+ writeContract,
43
+ writeContractSync
44
+ } from "./chunk-LH3QPVN6.js";
45
+ import {
46
+ getTransactionCount,
47
+ getTypesForEIP712Domain,
48
+ hashMessage,
49
+ hashTypedData,
50
+ serializeTypedData,
51
+ validateTypedData
52
+ } from "./chunk-6O27TEXD.js";
53
+ import {
54
+ AtomicityNotSupportedError,
55
+ ContractFunctionRevertedError,
56
+ InvalidInputRpcError,
57
+ RawContractError,
58
+ UnsupportedNonOptionalCapabilityError,
59
+ addressResolverAbi,
60
+ assertRequest,
61
+ call,
62
+ concat2,
63
+ createBatchScheduler,
64
+ decodeFunctionResult,
65
+ deploylessCallViaBytecodeBytecode,
66
+ encodeDeployData,
67
+ encodeFunctionData,
68
+ erc20Abi,
69
+ extract,
70
+ formatTransactionRequest,
71
+ getCallError,
72
+ getChainContractAddress,
73
+ getNodeError,
74
+ isAddressEqual,
75
+ localBatchGatewayUrl,
76
+ multicall3Abi,
77
+ multicall3Bytecode,
78
+ serializeStateOverride,
79
+ textResolverAbi,
80
+ toRpc,
81
+ universalResolverResolveAbi,
82
+ universalResolverReverseAbi,
83
+ withResolvers
84
+ } from "./chunk-F55NNH2F.js";
85
+ import {
86
+ AbiDecodingZeroDataError,
87
+ BaseError,
88
+ DecodeLogDataMismatch,
89
+ DecodeLogTopicsMismatch,
90
+ TransactionNotFoundError,
91
+ UnknownNodeError,
92
+ bytesToHex,
93
+ checksumAddress,
94
+ concat,
95
+ formatBlockParameter,
96
+ getAddress,
97
+ hexToBigInt,
98
+ hexToNumber,
99
+ isAddress,
100
+ isHex,
101
+ keccak256,
102
+ numberToHex,
103
+ parseAccount,
104
+ size,
105
+ slice,
106
+ sliceHex,
107
+ stringToBytes,
108
+ stringToHex,
109
+ stringify,
110
+ toBytes,
111
+ toHex,
112
+ trim
113
+ } from "./chunk-MLDUKBU3.js";
114
+ import {
115
+ __export
116
+ } from "./chunk-IYHTITNZ.js";
117
+
118
+ // node_modules/viem/_esm/actions/public/estimateContractGas.js
119
+ async function estimateContractGas(client, parameters) {
120
+ const { abi: abi2, address, args, functionName, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, ...request } = parameters;
121
+ const data = encodeFunctionData({
122
+ abi: abi2,
123
+ args,
124
+ functionName
125
+ });
126
+ try {
127
+ const gas = await getAction(client, estimateGas, "estimateGas")({
128
+ data: `${data}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`,
129
+ to: address,
130
+ ...request
131
+ });
132
+ return gas;
133
+ } catch (error) {
134
+ const account = request.account ? parseAccount(request.account) : void 0;
135
+ throw getContractError(error, {
136
+ abi: abi2,
137
+ address,
138
+ args,
139
+ docsPath: "/docs/contract/estimateContractGas",
140
+ functionName,
141
+ sender: account?.address
142
+ });
143
+ }
144
+ }
145
+
146
+ // node_modules/viem/_esm/actions/public/simulateContract.js
147
+ async function simulateContract(client, parameters) {
148
+ const { abi: abi2, address, args, functionName, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, ...callRequest } = parameters;
149
+ const account = callRequest.account ? parseAccount(callRequest.account) : client.account;
150
+ const calldata = encodeFunctionData({ abi: abi2, args, functionName });
151
+ try {
152
+ const { data } = await getAction(client, call, "call")({
153
+ batch: false,
154
+ data: `${calldata}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`,
155
+ to: address,
156
+ ...callRequest,
157
+ account
158
+ });
159
+ const result = decodeFunctionResult({
160
+ abi: abi2,
161
+ args,
162
+ functionName,
163
+ data: data || "0x"
164
+ });
165
+ const minimizedAbi = abi2.filter((abiItem) => "name" in abiItem && abiItem.name === parameters.functionName);
166
+ return {
167
+ result,
168
+ request: {
169
+ abi: minimizedAbi,
170
+ address,
171
+ args,
172
+ dataSuffix,
173
+ functionName,
174
+ ...callRequest,
175
+ account
176
+ }
177
+ };
178
+ } catch (error) {
179
+ throw getContractError(error, {
180
+ abi: abi2,
181
+ address,
182
+ args,
183
+ docsPath: "/docs/contract/simulateContract",
184
+ functionName,
185
+ sender: account?.address
186
+ });
187
+ }
188
+ }
189
+
190
+ // node_modules/viem/_esm/errors/calls.js
191
+ var BundleFailedError = class extends BaseError {
192
+ constructor(result) {
193
+ super(`Call bundle failed with status: ${result.statusCode}`, {
194
+ name: "BundleFailedError"
195
+ });
196
+ Object.defineProperty(this, "result", {
197
+ enumerable: true,
198
+ configurable: true,
199
+ writable: true,
200
+ value: void 0
201
+ });
202
+ this.result = result;
203
+ }
204
+ };
205
+
206
+ // node_modules/viem/_esm/actions/wallet/sendCalls.js
207
+ var fallbackMagicIdentifier = "0x5792579257925792579257925792579257925792579257925792579257925792";
208
+ var fallbackTransactionErrorMagicIdentifier = numberToHex(0, {
209
+ size: 32
210
+ });
211
+ async function sendCalls(client, parameters) {
212
+ const { account: account_ = client.account, chain = client.chain, experimental_fallback, experimental_fallbackDelay = 32, forceAtomic = false, id, version = "2.0.0" } = parameters;
213
+ const account = account_ ? parseAccount(account_) : null;
214
+ let capabilities = parameters.capabilities;
215
+ if (client.dataSuffix && !parameters.capabilities?.dataSuffix) {
216
+ if (typeof client.dataSuffix === "string")
217
+ capabilities = {
218
+ ...parameters.capabilities,
219
+ dataSuffix: { value: client.dataSuffix, optional: true }
220
+ };
221
+ else
222
+ capabilities = {
223
+ ...parameters.capabilities,
224
+ dataSuffix: {
225
+ value: client.dataSuffix.value,
226
+ ...client.dataSuffix.required ? {} : { optional: true }
227
+ }
228
+ };
229
+ }
230
+ const calls = parameters.calls.map((call_) => {
231
+ const call2 = call_;
232
+ const data = call2.abi ? encodeFunctionData({
233
+ abi: call2.abi,
234
+ functionName: call2.functionName,
235
+ args: call2.args
236
+ }) : call2.data;
237
+ return {
238
+ data: call2.dataSuffix && data ? concat([data, call2.dataSuffix]) : data,
239
+ to: call2.to,
240
+ value: call2.value ? numberToHex(call2.value) : void 0
241
+ };
242
+ });
243
+ try {
244
+ const response = await client.request({
245
+ method: "wallet_sendCalls",
246
+ params: [
247
+ {
248
+ atomicRequired: forceAtomic,
249
+ calls,
250
+ capabilities,
251
+ chainId: numberToHex(chain.id),
252
+ from: account?.address,
253
+ id,
254
+ version
255
+ }
256
+ ]
257
+ }, { retryCount: 0 });
258
+ if (typeof response === "string")
259
+ return { id: response };
260
+ return response;
261
+ } catch (err) {
262
+ const error = err;
263
+ if (experimental_fallback && (error.name === "MethodNotFoundRpcError" || error.name === "MethodNotSupportedRpcError" || error.name === "UnknownRpcError" || error.details.toLowerCase().includes("does not exist / is not available") || error.details.toLowerCase().includes("missing or invalid. request()") || error.details.toLowerCase().includes("did not match any variant of untagged enum") || error.details.toLowerCase().includes("account upgraded to unsupported contract") || error.details.toLowerCase().includes("eip-7702 not supported") || error.details.toLowerCase().includes("unsupported wc_ method") || // magic.link
264
+ error.details.toLowerCase().includes("feature toggled misconfigured") || // Trust Wallet
265
+ error.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))) {
266
+ if (capabilities) {
267
+ const hasNonOptionalCapability = Object.values(capabilities).some((capability) => !capability.optional);
268
+ if (hasNonOptionalCapability) {
269
+ const message = "non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";
270
+ throw new UnsupportedNonOptionalCapabilityError(new BaseError(message, {
271
+ details: message
272
+ }));
273
+ }
274
+ }
275
+ if (forceAtomic && calls.length > 1) {
276
+ const message = "`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";
277
+ throw new AtomicityNotSupportedError(new BaseError(message, {
278
+ details: message
279
+ }));
280
+ }
281
+ const results = [];
282
+ for (const call2 of calls) {
283
+ try {
284
+ const value = await sendTransaction(client, {
285
+ account,
286
+ chain,
287
+ data: call2.data,
288
+ to: call2.to,
289
+ value: call2.value ? hexToBigInt(call2.value) : void 0
290
+ });
291
+ results.push({ status: "fulfilled", value });
292
+ } catch (reason) {
293
+ results.push({ reason, status: "rejected" });
294
+ }
295
+ if (experimental_fallbackDelay > 0)
296
+ await new Promise((resolve) => setTimeout(resolve, experimental_fallbackDelay));
297
+ }
298
+ if (results.every((r) => r.status === "rejected"))
299
+ throw results[0].reason;
300
+ const hashes = results.map((result) => {
301
+ if (result.status === "fulfilled")
302
+ return result.value;
303
+ return fallbackTransactionErrorMagicIdentifier;
304
+ });
305
+ return {
306
+ id: concat([
307
+ ...hashes,
308
+ numberToHex(chain.id, { size: 32 }),
309
+ fallbackMagicIdentifier
310
+ ])
311
+ };
312
+ }
313
+ throw getTransactionError(err, {
314
+ ...parameters,
315
+ account,
316
+ chain: parameters.chain
317
+ });
318
+ }
319
+ }
320
+
321
+ // node_modules/viem/_esm/actions/wallet/getCallsStatus.js
322
+ async function getCallsStatus(client, parameters) {
323
+ async function getStatus(id) {
324
+ const isTransactions = id.endsWith(fallbackMagicIdentifier.slice(2));
325
+ if (isTransactions) {
326
+ const chainId2 = trim(sliceHex(id, -64, -32));
327
+ const hashes = sliceHex(id, 0, -64).slice(2).match(/.{1,64}/g);
328
+ const receipts2 = await Promise.all(hashes.map((hash) => fallbackTransactionErrorMagicIdentifier.slice(2) !== hash ? client.request({
329
+ method: "eth_getTransactionReceipt",
330
+ params: [`0x${hash}`]
331
+ }, { dedupe: true }) : void 0));
332
+ const status2 = (() => {
333
+ if (receipts2.some((r) => r === null))
334
+ return 100;
335
+ if (receipts2.every((r) => r?.status === "0x1"))
336
+ return 200;
337
+ if (receipts2.every((r) => r?.status === "0x0"))
338
+ return 500;
339
+ return 600;
340
+ })();
341
+ return {
342
+ atomic: false,
343
+ chainId: hexToNumber(chainId2),
344
+ receipts: receipts2.filter(Boolean),
345
+ status: status2,
346
+ version: "2.0.0"
347
+ };
348
+ }
349
+ return client.request({
350
+ method: "wallet_getCallsStatus",
351
+ params: [id]
352
+ });
353
+ }
354
+ const { atomic = false, chainId, receipts, version = "2.0.0", ...response } = await getStatus(parameters.id);
355
+ const [status, statusCode] = (() => {
356
+ const statusCode2 = response.status;
357
+ if (statusCode2 >= 100 && statusCode2 < 200)
358
+ return ["pending", statusCode2];
359
+ if (statusCode2 >= 200 && statusCode2 < 300)
360
+ return ["success", statusCode2];
361
+ if (statusCode2 >= 300 && statusCode2 < 700)
362
+ return ["failure", statusCode2];
363
+ if (statusCode2 === "CONFIRMED")
364
+ return ["success", 200];
365
+ if (statusCode2 === "PENDING")
366
+ return ["pending", 100];
367
+ return [void 0, statusCode2];
368
+ })();
369
+ return {
370
+ ...response,
371
+ atomic,
372
+ // @ts-expect-error: for backwards compatibility
373
+ chainId: chainId ? hexToNumber(chainId) : void 0,
374
+ receipts: receipts?.map((receipt) => ({
375
+ ...receipt,
376
+ blockNumber: hexToBigInt(receipt.blockNumber),
377
+ gasUsed: hexToBigInt(receipt.gasUsed),
378
+ status: receiptStatuses[receipt.status]
379
+ })) ?? [],
380
+ statusCode,
381
+ status,
382
+ version
383
+ };
384
+ }
385
+
386
+ // node_modules/viem/_esm/actions/wallet/waitForCallsStatus.js
387
+ async function waitForCallsStatus(client, parameters) {
388
+ const {
389
+ id,
390
+ pollingInterval = client.pollingInterval,
391
+ status = ({ statusCode }) => statusCode === 200 || statusCode >= 300,
392
+ retryCount = 4,
393
+ retryDelay = ({ count }) => ~~(1 << count) * 200,
394
+ // exponential backoff
395
+ timeout = 6e4,
396
+ throwOnFailure = false
397
+ } = parameters;
398
+ const observerId = stringify(["waitForCallsStatus", client.uid, id]);
399
+ const { promise, resolve, reject } = withResolvers();
400
+ let timer;
401
+ const unobserve = observe(observerId, { resolve, reject }, (emit) => {
402
+ const unpoll = poll(async () => {
403
+ const done = (fn) => {
404
+ clearTimeout(timer);
405
+ unpoll();
406
+ fn();
407
+ unobserve();
408
+ };
409
+ try {
410
+ const result = await withRetry(async () => {
411
+ const result2 = await getAction(client, getCallsStatus, "getCallsStatus")({ id });
412
+ if (throwOnFailure && result2.status === "failure")
413
+ throw new BundleFailedError(result2);
414
+ return result2;
415
+ }, {
416
+ retryCount,
417
+ delay: retryDelay
418
+ });
419
+ if (!status(result))
420
+ return;
421
+ done(() => emit.resolve(result));
422
+ } catch (error) {
423
+ done(() => emit.reject(error));
424
+ }
425
+ }, {
426
+ interval: pollingInterval,
427
+ emitOnBegin: true
428
+ });
429
+ return unpoll;
430
+ });
431
+ timer = timeout ? setTimeout(() => {
432
+ unobserve();
433
+ clearTimeout(timer);
434
+ reject(new WaitForCallsStatusTimeoutError({ id }));
435
+ }, timeout) : void 0;
436
+ return await promise;
437
+ }
438
+ var WaitForCallsStatusTimeoutError = class extends BaseError {
439
+ constructor({ id }) {
440
+ super(`Timed out while waiting for call bundle with id "${id}" to be confirmed.`, { name: "WaitForCallsStatusTimeoutError" });
441
+ }
442
+ };
443
+
444
+ // node_modules/viem/_esm/utils/ens/encodedLabelToLabelhash.js
445
+ function encodedLabelToLabelhash(label) {
446
+ if (label.length !== 66)
447
+ return null;
448
+ if (label.indexOf("[") !== 0)
449
+ return null;
450
+ if (label.indexOf("]") !== 65)
451
+ return null;
452
+ const hash = `0x${label.slice(1, 65)}`;
453
+ if (!isHex(hash))
454
+ return null;
455
+ return hash;
456
+ }
457
+
458
+ // node_modules/viem/_esm/utils/ens/namehash.js
459
+ function namehash(name) {
460
+ let result = new Uint8Array(32).fill(0);
461
+ if (!name)
462
+ return bytesToHex(result);
463
+ const labels = name.split(".");
464
+ for (let i = labels.length - 1; i >= 0; i -= 1) {
465
+ const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i]);
466
+ const hashed = hashFromEncodedLabel ? toBytes(hashFromEncodedLabel) : keccak256(stringToBytes(labels[i]), "bytes");
467
+ result = keccak256(concat([result, hashed]), "bytes");
468
+ }
469
+ return bytesToHex(result);
470
+ }
471
+
472
+ // node_modules/viem/_esm/utils/ens/labelhash.js
473
+ function labelhash(label) {
474
+ const result = new Uint8Array(32).fill(0);
475
+ if (!label)
476
+ return bytesToHex(result);
477
+ return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label));
478
+ }
479
+
480
+ // node_modules/viem/_esm/utils/ens/errors.js
481
+ function isNullUniversalResolverError(err) {
482
+ if (!(err instanceof BaseError))
483
+ return false;
484
+ const cause = err.walk((e) => e instanceof ContractFunctionRevertedError);
485
+ if (!(cause instanceof ContractFunctionRevertedError))
486
+ return false;
487
+ if (cause.data?.errorName === "HttpError")
488
+ return true;
489
+ if (cause.data?.errorName === "ResolverError")
490
+ return true;
491
+ if (cause.data?.errorName === "ResolverNotContract")
492
+ return true;
493
+ if (cause.data?.errorName === "ResolverNotFound")
494
+ return true;
495
+ if (cause.data?.errorName === "ReverseAddressMismatch")
496
+ return true;
497
+ if (cause.data?.errorName === "UnsupportedResolverProfile")
498
+ return true;
499
+ return false;
500
+ }
501
+
502
+ // node_modules/viem/_esm/utils/ens/encodeLabelhash.js
503
+ function encodeLabelhash(hash) {
504
+ return `[${hash.slice(2)}]`;
505
+ }
506
+
507
+ // node_modules/viem/_esm/utils/ens/packetToBytes.js
508
+ function packetToBytes(packet) {
509
+ const value = packet.replace(/^\.|\.$/gm, "");
510
+ if (value.length === 0)
511
+ return new Uint8Array(1);
512
+ const bytes = new Uint8Array(stringToBytes(value).byteLength + 2);
513
+ let offset = 0;
514
+ const list = value.split(".");
515
+ for (let i = 0; i < list.length; i++) {
516
+ let encoded = stringToBytes(list[i]);
517
+ if (encoded.byteLength > 255)
518
+ encoded = stringToBytes(encodeLabelhash(labelhash(list[i])));
519
+ bytes[offset] = encoded.length;
520
+ bytes.set(encoded, offset + 1);
521
+ offset += encoded.length + 1;
522
+ }
523
+ if (bytes.byteLength !== offset + 1)
524
+ return bytes.slice(0, offset + 1);
525
+ return bytes;
526
+ }
527
+
528
+ // node_modules/viem/_esm/actions/ens/getEnsAddress.js
529
+ async function getEnsAddress(client, parameters) {
530
+ const { blockNumber, blockTag, coinType, name, gatewayUrls, strict } = parameters;
531
+ const { chain } = client;
532
+ const universalResolverAddress = (() => {
533
+ if (parameters.universalResolverAddress)
534
+ return parameters.universalResolverAddress;
535
+ if (!chain)
536
+ throw new Error("client chain not configured. universalResolverAddress is required.");
537
+ return getChainContractAddress({
538
+ blockNumber,
539
+ chain,
540
+ contract: "ensUniversalResolver"
541
+ });
542
+ })();
543
+ const tlds = chain?.ensTlds;
544
+ if (tlds && !tlds.some((tld) => name.endsWith(tld)))
545
+ return null;
546
+ const args = (() => {
547
+ if (coinType != null)
548
+ return [namehash(name), BigInt(coinType)];
549
+ return [namehash(name)];
550
+ })();
551
+ try {
552
+ const functionData = encodeFunctionData({
553
+ abi: addressResolverAbi,
554
+ functionName: "addr",
555
+ args
556
+ });
557
+ const readContractParameters = {
558
+ address: universalResolverAddress,
559
+ abi: universalResolverResolveAbi,
560
+ functionName: "resolveWithGateways",
561
+ args: [
562
+ toHex(packetToBytes(name)),
563
+ functionData,
564
+ gatewayUrls ?? [localBatchGatewayUrl]
565
+ ],
566
+ blockNumber,
567
+ blockTag
568
+ };
569
+ const readContractAction = getAction(client, readContract, "readContract");
570
+ const res = await readContractAction(readContractParameters);
571
+ if (res[0] === "0x")
572
+ return null;
573
+ const address = decodeAddress({ coinType, data: res[0], args });
574
+ if (address === "0x")
575
+ return null;
576
+ if (trim(address) === "0x00")
577
+ return null;
578
+ return address;
579
+ } catch (err) {
580
+ if (strict)
581
+ throw err;
582
+ if (isNullUniversalResolverError(err))
583
+ return null;
584
+ throw err;
585
+ }
586
+ }
587
+ function decodeAddress({ coinType, data, args }) {
588
+ try {
589
+ return decodeFunctionResult({
590
+ abi: addressResolverAbi,
591
+ args,
592
+ functionName: "addr",
593
+ data
594
+ });
595
+ } catch (err) {
596
+ if (coinType == null)
597
+ throw err;
598
+ const address = trim(data);
599
+ if (size(address) === 20)
600
+ return getAddress(address);
601
+ throw err;
602
+ }
603
+ }
604
+
605
+ // node_modules/viem/_esm/errors/ens.js
606
+ var EnsAvatarInvalidMetadataError = class extends BaseError {
607
+ constructor({ data }) {
608
+ super("Unable to extract image from metadata. The metadata may be malformed or invalid.", {
609
+ metaMessages: [
610
+ "- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.",
611
+ "",
612
+ `Provided data: ${JSON.stringify(data)}`
613
+ ],
614
+ name: "EnsAvatarInvalidMetadataError"
615
+ });
616
+ }
617
+ };
618
+ var EnsAvatarInvalidNftUriError = class extends BaseError {
619
+ constructor({ reason }) {
620
+ super(`ENS NFT avatar URI is invalid. ${reason}`, {
621
+ name: "EnsAvatarInvalidNftUriError"
622
+ });
623
+ }
624
+ };
625
+ var EnsAvatarUriResolutionError = class extends BaseError {
626
+ constructor({ uri }) {
627
+ super(`Unable to resolve ENS avatar URI "${uri}". The URI may be malformed, invalid, or does not respond with a valid image.`, { name: "EnsAvatarUriResolutionError" });
628
+ }
629
+ };
630
+ var EnsAvatarUnsupportedNamespaceError = class extends BaseError {
631
+ constructor({ namespace }) {
632
+ super(`ENS NFT avatar namespace "${namespace}" is not supported. Must be "erc721" or "erc1155".`, { name: "EnsAvatarUnsupportedNamespaceError" });
633
+ }
634
+ };
635
+ var EnsInvalidChainIdError = class extends BaseError {
636
+ constructor({ chainId }) {
637
+ super(`Invalid ENSIP-11 chainId: ${chainId}. Must be between 0 and 0x7fffffff, or 1.`, {
638
+ name: "EnsInvalidChainIdError"
639
+ });
640
+ }
641
+ };
642
+
643
+ // node_modules/viem/_esm/actions/ens/getEnsText.js
644
+ async function getEnsText(client, parameters) {
645
+ const { blockNumber, blockTag, key, name, gatewayUrls, strict } = parameters;
646
+ const { chain } = client;
647
+ const universalResolverAddress = (() => {
648
+ if (parameters.universalResolverAddress)
649
+ return parameters.universalResolverAddress;
650
+ if (!chain)
651
+ throw new Error("client chain not configured. universalResolverAddress is required.");
652
+ return getChainContractAddress({
653
+ blockNumber,
654
+ chain,
655
+ contract: "ensUniversalResolver"
656
+ });
657
+ })();
658
+ const tlds = chain?.ensTlds;
659
+ if (tlds && !tlds.some((tld) => name.endsWith(tld)))
660
+ return null;
661
+ try {
662
+ const readContractParameters = {
663
+ address: universalResolverAddress,
664
+ abi: universalResolverResolveAbi,
665
+ args: [
666
+ toHex(packetToBytes(name)),
667
+ encodeFunctionData({
668
+ abi: textResolverAbi,
669
+ functionName: "text",
670
+ args: [namehash(name), key]
671
+ }),
672
+ gatewayUrls ?? [localBatchGatewayUrl]
673
+ ],
674
+ functionName: "resolveWithGateways",
675
+ blockNumber,
676
+ blockTag
677
+ };
678
+ const readContractAction = getAction(client, readContract, "readContract");
679
+ const res = await readContractAction(readContractParameters);
680
+ if (res[0] === "0x")
681
+ return null;
682
+ const record = decodeFunctionResult({
683
+ abi: textResolverAbi,
684
+ functionName: "text",
685
+ data: res[0]
686
+ });
687
+ return record === "" ? null : record;
688
+ } catch (err) {
689
+ if (strict)
690
+ throw err;
691
+ if (isNullUniversalResolverError(err))
692
+ return null;
693
+ throw err;
694
+ }
695
+ }
696
+
697
+ // node_modules/viem/_esm/utils/ens/avatar/utils.js
698
+ var networkRegex = /(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/;
699
+ var ipfsHashRegex = /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/;
700
+ var base64Regex = /^data:([a-zA-Z\-/+]*);base64,([^"].*)/;
701
+ var dataURIRegex = /^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;
702
+ async function isImageUri(uri) {
703
+ try {
704
+ const res = await fetch(uri, { method: "HEAD" });
705
+ if (res.status === 200) {
706
+ const contentType = res.headers.get("content-type");
707
+ return contentType?.startsWith("image/");
708
+ }
709
+ return false;
710
+ } catch (error) {
711
+ if (typeof error === "object" && typeof error.response !== "undefined") {
712
+ return false;
713
+ }
714
+ if (!Object.hasOwn(globalThis, "Image"))
715
+ return false;
716
+ return new Promise((resolve) => {
717
+ const img = new Image();
718
+ img.onload = () => {
719
+ resolve(true);
720
+ };
721
+ img.onerror = () => {
722
+ resolve(false);
723
+ };
724
+ img.src = uri;
725
+ });
726
+ }
727
+ }
728
+ function getGateway(custom, defaultGateway) {
729
+ if (!custom)
730
+ return defaultGateway;
731
+ if (custom.endsWith("/"))
732
+ return custom.slice(0, -1);
733
+ return custom;
734
+ }
735
+ function resolveAvatarUri({ uri, gatewayUrls }) {
736
+ const isEncoded = base64Regex.test(uri);
737
+ if (isEncoded)
738
+ return { uri, isOnChain: true, isEncoded };
739
+ const ipfsGateway = getGateway(gatewayUrls?.ipfs, "https://ipfs.io");
740
+ const arweaveGateway = getGateway(gatewayUrls?.arweave, "https://arweave.net");
741
+ const networkRegexMatch = uri.match(networkRegex);
742
+ const { protocol, subpath, target, subtarget = "" } = networkRegexMatch?.groups || {};
743
+ const isIPNS = protocol === "ipns:/" || subpath === "ipns/";
744
+ const isIPFS = protocol === "ipfs:/" || subpath === "ipfs/" || ipfsHashRegex.test(uri);
745
+ if (uri.startsWith("http") && !isIPNS && !isIPFS) {
746
+ let replacedUri = uri;
747
+ if (gatewayUrls?.arweave)
748
+ replacedUri = uri.replace(/https:\/\/arweave.net/g, gatewayUrls?.arweave);
749
+ return { uri: replacedUri, isOnChain: false, isEncoded: false };
750
+ }
751
+ if ((isIPNS || isIPFS) && target) {
752
+ return {
753
+ uri: `${ipfsGateway}/${isIPNS ? "ipns" : "ipfs"}/${target}${subtarget}`,
754
+ isOnChain: false,
755
+ isEncoded: false
756
+ };
757
+ }
758
+ if (protocol === "ar:/" && target) {
759
+ return {
760
+ uri: `${arweaveGateway}/${target}${subtarget || ""}`,
761
+ isOnChain: false,
762
+ isEncoded: false
763
+ };
764
+ }
765
+ let parsedUri = uri.replace(dataURIRegex, "");
766
+ if (parsedUri.startsWith("<svg")) {
767
+ parsedUri = `data:image/svg+xml;base64,${btoa(parsedUri)}`;
768
+ }
769
+ if (parsedUri.startsWith("data:") || parsedUri.startsWith("{")) {
770
+ return {
771
+ uri: parsedUri,
772
+ isOnChain: true,
773
+ isEncoded: false
774
+ };
775
+ }
776
+ throw new EnsAvatarUriResolutionError({ uri });
777
+ }
778
+ function getJsonImage(data) {
779
+ if (typeof data !== "object" || !("image" in data) && !("image_url" in data) && !("image_data" in data)) {
780
+ throw new EnsAvatarInvalidMetadataError({ data });
781
+ }
782
+ return data.image || data.image_url || data.image_data;
783
+ }
784
+ async function getMetadataAvatarUri({ gatewayUrls, uri }) {
785
+ try {
786
+ const res = await fetch(uri).then((res2) => res2.json());
787
+ const image = await parseAvatarUri({
788
+ gatewayUrls,
789
+ uri: getJsonImage(res)
790
+ });
791
+ return image;
792
+ } catch {
793
+ throw new EnsAvatarUriResolutionError({ uri });
794
+ }
795
+ }
796
+ async function parseAvatarUri({ gatewayUrls, uri }) {
797
+ const { uri: resolvedURI, isOnChain } = resolveAvatarUri({ uri, gatewayUrls });
798
+ if (isOnChain)
799
+ return resolvedURI;
800
+ const isImage = await isImageUri(resolvedURI);
801
+ if (isImage)
802
+ return resolvedURI;
803
+ throw new EnsAvatarUriResolutionError({ uri });
804
+ }
805
+ function parseNftUri(uri_) {
806
+ let uri = uri_;
807
+ if (uri.startsWith("did:nft:")) {
808
+ uri = uri.replace("did:nft:", "").replace(/_/g, "/");
809
+ }
810
+ const [reference, asset_namespace, tokenID] = uri.split("/");
811
+ const [eip_namespace, chainID] = reference.split(":");
812
+ const [erc_namespace, contractAddress] = asset_namespace.split(":");
813
+ if (!eip_namespace || eip_namespace.toLowerCase() !== "eip155")
814
+ throw new EnsAvatarInvalidNftUriError({ reason: "Only EIP-155 supported" });
815
+ if (!chainID)
816
+ throw new EnsAvatarInvalidNftUriError({ reason: "Chain ID not found" });
817
+ if (!contractAddress)
818
+ throw new EnsAvatarInvalidNftUriError({
819
+ reason: "Contract address not found"
820
+ });
821
+ if (!tokenID)
822
+ throw new EnsAvatarInvalidNftUriError({ reason: "Token ID not found" });
823
+ if (!erc_namespace)
824
+ throw new EnsAvatarInvalidNftUriError({ reason: "ERC namespace not found" });
825
+ return {
826
+ chainID: Number.parseInt(chainID, 10),
827
+ namespace: erc_namespace.toLowerCase(),
828
+ contractAddress,
829
+ tokenID
830
+ };
831
+ }
832
+ async function getNftTokenUri(client, { nft }) {
833
+ if (nft.namespace === "erc721") {
834
+ return readContract(client, {
835
+ address: nft.contractAddress,
836
+ abi: [
837
+ {
838
+ name: "tokenURI",
839
+ type: "function",
840
+ stateMutability: "view",
841
+ inputs: [{ name: "tokenId", type: "uint256" }],
842
+ outputs: [{ name: "", type: "string" }]
843
+ }
844
+ ],
845
+ functionName: "tokenURI",
846
+ args: [BigInt(nft.tokenID)]
847
+ });
848
+ }
849
+ if (nft.namespace === "erc1155") {
850
+ return readContract(client, {
851
+ address: nft.contractAddress,
852
+ abi: [
853
+ {
854
+ name: "uri",
855
+ type: "function",
856
+ stateMutability: "view",
857
+ inputs: [{ name: "_id", type: "uint256" }],
858
+ outputs: [{ name: "", type: "string" }]
859
+ }
860
+ ],
861
+ functionName: "uri",
862
+ args: [BigInt(nft.tokenID)]
863
+ });
864
+ }
865
+ throw new EnsAvatarUnsupportedNamespaceError({ namespace: nft.namespace });
866
+ }
867
+
868
+ // node_modules/viem/_esm/utils/ens/avatar/parseAvatarRecord.js
869
+ async function parseAvatarRecord(client, { gatewayUrls, record }) {
870
+ if (/eip155:/i.test(record))
871
+ return parseNftAvatarUri(client, { gatewayUrls, record });
872
+ return parseAvatarUri({ uri: record, gatewayUrls });
873
+ }
874
+ async function parseNftAvatarUri(client, { gatewayUrls, record }) {
875
+ const nft = parseNftUri(record);
876
+ const nftUri = await getNftTokenUri(client, { nft });
877
+ const { uri: resolvedNftUri, isOnChain, isEncoded } = resolveAvatarUri({ uri: nftUri, gatewayUrls });
878
+ if (isOnChain && (resolvedNftUri.includes("data:application/json;base64,") || resolvedNftUri.startsWith("{"))) {
879
+ const encodedJson = isEncoded ? (
880
+ // if it is encoded, decode it
881
+ atob(resolvedNftUri.replace("data:application/json;base64,", ""))
882
+ ) : (
883
+ // if it isn't encoded assume it is a JSON string, but it could be anything (it will error if it is)
884
+ resolvedNftUri
885
+ );
886
+ const decoded = JSON.parse(encodedJson);
887
+ return parseAvatarUri({ uri: getJsonImage(decoded), gatewayUrls });
888
+ }
889
+ let uriTokenId = nft.tokenID;
890
+ if (nft.namespace === "erc1155")
891
+ uriTokenId = uriTokenId.replace("0x", "").padStart(64, "0");
892
+ return getMetadataAvatarUri({
893
+ gatewayUrls,
894
+ uri: resolvedNftUri.replace(/(?:0x)?{id}/, uriTokenId)
895
+ });
896
+ }
897
+
898
+ // node_modules/viem/_esm/actions/ens/getEnsAvatar.js
899
+ async function getEnsAvatar(client, { blockNumber, blockTag, assetGatewayUrls, name, gatewayUrls, strict, universalResolverAddress }) {
900
+ const record = await getAction(client, getEnsText, "getEnsText")({
901
+ blockNumber,
902
+ blockTag,
903
+ key: "avatar",
904
+ name,
905
+ universalResolverAddress,
906
+ gatewayUrls,
907
+ strict
908
+ });
909
+ if (!record)
910
+ return null;
911
+ try {
912
+ return await parseAvatarRecord(client, {
913
+ record,
914
+ gatewayUrls: assetGatewayUrls
915
+ });
916
+ } catch {
917
+ return null;
918
+ }
919
+ }
920
+
921
+ // node_modules/viem/_esm/actions/ens/getEnsName.js
922
+ async function getEnsName(client, parameters) {
923
+ const { address, blockNumber, blockTag, coinType = 60n, gatewayUrls, strict } = parameters;
924
+ const { chain } = client;
925
+ const universalResolverAddress = (() => {
926
+ if (parameters.universalResolverAddress)
927
+ return parameters.universalResolverAddress;
928
+ if (!chain)
929
+ throw new Error("client chain not configured. universalResolverAddress is required.");
930
+ return getChainContractAddress({
931
+ blockNumber,
932
+ chain,
933
+ contract: "ensUniversalResolver"
934
+ });
935
+ })();
936
+ try {
937
+ const readContractParameters = {
938
+ address: universalResolverAddress,
939
+ abi: universalResolverReverseAbi,
940
+ args: [address, coinType, gatewayUrls ?? [localBatchGatewayUrl]],
941
+ functionName: "reverseWithGateways",
942
+ blockNumber,
943
+ blockTag
944
+ };
945
+ const readContractAction = getAction(client, readContract, "readContract");
946
+ const [name] = await readContractAction(readContractParameters);
947
+ return name || null;
948
+ } catch (err) {
949
+ if (strict)
950
+ throw err;
951
+ if (isNullUniversalResolverError(err))
952
+ return null;
953
+ throw err;
954
+ }
955
+ }
956
+
957
+ // node_modules/viem/_esm/actions/ens/getEnsResolver.js
958
+ async function getEnsResolver(client, parameters) {
959
+ const { blockNumber, blockTag, name } = parameters;
960
+ const { chain } = client;
961
+ const universalResolverAddress = (() => {
962
+ if (parameters.universalResolverAddress)
963
+ return parameters.universalResolverAddress;
964
+ if (!chain)
965
+ throw new Error("client chain not configured. universalResolverAddress is required.");
966
+ return getChainContractAddress({
967
+ blockNumber,
968
+ chain,
969
+ contract: "ensUniversalResolver"
970
+ });
971
+ })();
972
+ const tlds = chain?.ensTlds;
973
+ if (tlds && !tlds.some((tld) => name.endsWith(tld)))
974
+ throw new Error(`${name} is not a valid ENS TLD (${tlds?.join(", ")}) for chain "${chain.name}" (id: ${chain.id}).`);
975
+ const [resolverAddress] = await getAction(client, readContract, "readContract")({
976
+ address: universalResolverAddress,
977
+ abi: [
978
+ {
979
+ inputs: [{ type: "bytes" }],
980
+ name: "findResolver",
981
+ outputs: [
982
+ { type: "address" },
983
+ { type: "bytes32" },
984
+ { type: "uint256" }
985
+ ],
986
+ stateMutability: "view",
987
+ type: "function"
988
+ }
989
+ ],
990
+ functionName: "findResolver",
991
+ args: [toHex(packetToBytes(name))],
992
+ blockNumber,
993
+ blockTag
994
+ });
995
+ return resolverAddress;
996
+ }
997
+
998
+ // node_modules/viem/_esm/actions/public/createAccessList.js
999
+ async function createAccessList(client, args) {
1000
+ const { account: account_ = client.account, blockNumber, blockTag = "latest", blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, to, value, ...rest } = args;
1001
+ const account = account_ ? parseAccount(account_) : void 0;
1002
+ try {
1003
+ assertRequest(args);
1004
+ const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : void 0;
1005
+ const block = blockNumberHex || blockTag;
1006
+ const chainFormat = client.chain?.formatters?.transactionRequest?.format;
1007
+ const format = chainFormat || formatTransactionRequest;
1008
+ const request = format({
1009
+ // Pick out extra data that might exist on the chain's transaction request type.
1010
+ ...extract(rest, { format: chainFormat }),
1011
+ account,
1012
+ blobs,
1013
+ data,
1014
+ gas,
1015
+ gasPrice,
1016
+ maxFeePerBlobGas,
1017
+ maxFeePerGas,
1018
+ maxPriorityFeePerGas,
1019
+ to,
1020
+ value
1021
+ }, "createAccessList");
1022
+ const response = await client.request({
1023
+ method: "eth_createAccessList",
1024
+ params: [request, block]
1025
+ });
1026
+ if (response.error)
1027
+ throw new BaseError(response.error, { details: response.error });
1028
+ return {
1029
+ accessList: response.accessList,
1030
+ gasUsed: BigInt(response.gasUsed)
1031
+ };
1032
+ } catch (err) {
1033
+ throw getCallError(err, {
1034
+ ...args,
1035
+ account,
1036
+ chain: client.chain
1037
+ });
1038
+ }
1039
+ }
1040
+
1041
+ // node_modules/viem/_esm/actions/public/createBlockFilter.js
1042
+ async function createBlockFilter(client) {
1043
+ const getRequest = createFilterRequestScope(client, {
1044
+ method: "eth_newBlockFilter"
1045
+ });
1046
+ const id = await client.request({
1047
+ method: "eth_newBlockFilter"
1048
+ });
1049
+ return { id, request: getRequest(id), type: "block" };
1050
+ }
1051
+
1052
+ // node_modules/viem/_esm/actions/public/createEventFilter.js
1053
+ async function createEventFilter(client, { address, args, event, events: events_, fromBlock, strict, toBlock } = {}) {
1054
+ const events = events_ ?? (event ? [event] : void 0);
1055
+ const getRequest = createFilterRequestScope(client, {
1056
+ method: "eth_newFilter"
1057
+ });
1058
+ let topics = [];
1059
+ if (events) {
1060
+ const encoded = events.flatMap((event2) => encodeEventTopics({
1061
+ abi: [event2],
1062
+ eventName: event2.name,
1063
+ args
1064
+ }));
1065
+ topics = [encoded];
1066
+ if (event)
1067
+ topics = topics[0];
1068
+ }
1069
+ const id = await client.request({
1070
+ method: "eth_newFilter",
1071
+ params: [
1072
+ {
1073
+ address,
1074
+ fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock,
1075
+ toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock,
1076
+ ...topics.length ? { topics } : {}
1077
+ }
1078
+ ]
1079
+ });
1080
+ return {
1081
+ abi: events,
1082
+ args,
1083
+ eventName: event ? event.name : void 0,
1084
+ fromBlock,
1085
+ id,
1086
+ request: getRequest(id),
1087
+ strict: Boolean(strict),
1088
+ toBlock,
1089
+ type: "event"
1090
+ };
1091
+ }
1092
+
1093
+ // node_modules/viem/_esm/actions/public/createPendingTransactionFilter.js
1094
+ async function createPendingTransactionFilter(client) {
1095
+ const getRequest = createFilterRequestScope(client, {
1096
+ method: "eth_newPendingTransactionFilter"
1097
+ });
1098
+ const id = await client.request({
1099
+ method: "eth_newPendingTransactionFilter"
1100
+ });
1101
+ return { id, request: getRequest(id), type: "transaction" };
1102
+ }
1103
+
1104
+ // node_modules/viem/_esm/actions/public/getBalance.js
1105
+ async function getBalance(client, { address, blockHash, blockNumber, blockTag = client.experimental_blockTag ?? "latest", requireCanonical }) {
1106
+ const block = formatBlockParameter({
1107
+ blockHash,
1108
+ blockNumber,
1109
+ blockTag,
1110
+ requireCanonical
1111
+ });
1112
+ if (client.batch?.multicall && client.chain?.contracts?.multicall3) {
1113
+ const multicall3Address = client.chain.contracts.multicall3.address;
1114
+ const calldata = encodeFunctionData({
1115
+ abi: multicall3Abi,
1116
+ functionName: "getEthBalance",
1117
+ args: [address]
1118
+ });
1119
+ const { data } = await getAction(client, call, "call")({
1120
+ to: multicall3Address,
1121
+ data: calldata,
1122
+ blockHash,
1123
+ blockNumber,
1124
+ blockTag,
1125
+ requireCanonical
1126
+ });
1127
+ return decodeFunctionResult({
1128
+ abi: multicall3Abi,
1129
+ functionName: "getEthBalance",
1130
+ args: [address],
1131
+ data: data || "0x"
1132
+ });
1133
+ }
1134
+ const balance = await client.request({
1135
+ method: "eth_getBalance",
1136
+ params: [address, block]
1137
+ });
1138
+ return BigInt(balance);
1139
+ }
1140
+
1141
+ // node_modules/viem/_esm/actions/public/getBlobBaseFee.js
1142
+ async function getBlobBaseFee(client) {
1143
+ const baseFee = await client.request({
1144
+ method: "eth_blobBaseFee"
1145
+ });
1146
+ return BigInt(baseFee);
1147
+ }
1148
+
1149
+ // node_modules/viem/_esm/actions/public/getBlockReceipts.js
1150
+ async function getBlockReceipts(client, { blockHash, blockNumber, blockTag = client.experimental_blockTag ?? "latest" } = {}) {
1151
+ const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
1152
+ const receipts = await client.request({
1153
+ method: "eth_getBlockReceipts",
1154
+ params: [blockHash || blockNumberHex || blockTag]
1155
+ }, { dedupe: Boolean(blockHash || blockNumberHex) });
1156
+ if (!receipts)
1157
+ throw new BlockNotFoundError({ blockHash, blockNumber });
1158
+ const format = client.chain?.formatters?.transactionReceipt?.format || formatTransactionReceipt;
1159
+ return receipts.map((receipt) => format(receipt, "getBlockReceipts"));
1160
+ }
1161
+
1162
+ // node_modules/viem/_esm/actions/public/getBlockTransactionCount.js
1163
+ async function getBlockTransactionCount(client, { blockHash, blockNumber, blockTag = "latest" } = {}) {
1164
+ const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
1165
+ let count;
1166
+ if (blockHash) {
1167
+ count = await client.request({
1168
+ method: "eth_getBlockTransactionCountByHash",
1169
+ params: [blockHash]
1170
+ }, { dedupe: true });
1171
+ } else {
1172
+ count = await client.request({
1173
+ method: "eth_getBlockTransactionCountByNumber",
1174
+ params: [blockNumberHex || blockTag]
1175
+ }, { dedupe: Boolean(blockNumberHex) });
1176
+ }
1177
+ return hexToNumber(count);
1178
+ }
1179
+
1180
+ // node_modules/viem/_esm/actions/public/getDelegation.js
1181
+ async function getDelegation(client, { address, blockNumber, blockTag = "latest" }) {
1182
+ const code = await getCode(client, {
1183
+ address,
1184
+ ...blockNumber !== void 0 ? { blockNumber } : { blockTag }
1185
+ });
1186
+ if (!code)
1187
+ return void 0;
1188
+ if (size(code) !== 23)
1189
+ return void 0;
1190
+ if (!code.startsWith("0xef0100"))
1191
+ return void 0;
1192
+ return getAddress(slice(code, 3, 23));
1193
+ }
1194
+
1195
+ // node_modules/viem/_esm/errors/eip712.js
1196
+ var Eip712DomainNotFoundError = class extends BaseError {
1197
+ constructor({ address }) {
1198
+ super(`No EIP-712 domain found on contract "${address}".`, {
1199
+ metaMessages: [
1200
+ "Ensure that:",
1201
+ `- The contract is deployed at the address "${address}".`,
1202
+ "- `eip712Domain()` function exists on the contract.",
1203
+ "- `eip712Domain()` function matches signature to ERC-5267 specification."
1204
+ ],
1205
+ name: "Eip712DomainNotFoundError"
1206
+ });
1207
+ }
1208
+ };
1209
+
1210
+ // node_modules/viem/_esm/actions/public/getEip712Domain.js
1211
+ async function getEip712Domain(client, parameters) {
1212
+ const { address, factory, factoryData } = parameters;
1213
+ try {
1214
+ const [fields, name, version, chainId, verifyingContract, salt, extensions] = await getAction(client, readContract, "readContract")({
1215
+ abi,
1216
+ address,
1217
+ functionName: "eip712Domain",
1218
+ factory,
1219
+ factoryData
1220
+ });
1221
+ return {
1222
+ domain: {
1223
+ name,
1224
+ version,
1225
+ chainId: Number(chainId),
1226
+ verifyingContract,
1227
+ salt
1228
+ },
1229
+ extensions,
1230
+ fields
1231
+ };
1232
+ } catch (e) {
1233
+ const error = e;
1234
+ if (error.name === "ContractFunctionExecutionError" && error.cause.name === "ContractFunctionZeroDataError") {
1235
+ throw new Eip712DomainNotFoundError({ address });
1236
+ }
1237
+ throw error;
1238
+ }
1239
+ }
1240
+ var abi = [
1241
+ {
1242
+ inputs: [],
1243
+ name: "eip712Domain",
1244
+ outputs: [
1245
+ { name: "fields", type: "bytes1" },
1246
+ { name: "name", type: "string" },
1247
+ { name: "version", type: "string" },
1248
+ { name: "chainId", type: "uint256" },
1249
+ { name: "verifyingContract", type: "address" },
1250
+ { name: "salt", type: "bytes32" },
1251
+ { name: "extensions", type: "uint256[]" }
1252
+ ],
1253
+ stateMutability: "view",
1254
+ type: "function"
1255
+ }
1256
+ ];
1257
+
1258
+ // node_modules/viem/_esm/utils/formatters/feeHistory.js
1259
+ function formatFeeHistory(feeHistory) {
1260
+ return {
1261
+ baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)),
1262
+ gasUsedRatio: feeHistory.gasUsedRatio,
1263
+ oldestBlock: BigInt(feeHistory.oldestBlock),
1264
+ reward: feeHistory.reward?.map((reward) => reward.map((value) => BigInt(value)))
1265
+ };
1266
+ }
1267
+
1268
+ // node_modules/viem/_esm/actions/public/getFeeHistory.js
1269
+ async function getFeeHistory(client, { blockCount, blockNumber, blockTag = "latest", rewardPercentiles }) {
1270
+ const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : void 0;
1271
+ const feeHistory = await client.request({
1272
+ method: "eth_feeHistory",
1273
+ params: [
1274
+ numberToHex(blockCount),
1275
+ blockNumberHex || blockTag,
1276
+ rewardPercentiles
1277
+ ]
1278
+ }, { dedupe: Boolean(blockNumberHex) });
1279
+ return formatFeeHistory(feeHistory);
1280
+ }
1281
+
1282
+ // node_modules/viem/_esm/actions/public/getFilterLogs.js
1283
+ async function getFilterLogs(_client, { filter }) {
1284
+ const strict = filter.strict ?? false;
1285
+ const logs = await filter.request({
1286
+ method: "eth_getFilterLogs",
1287
+ params: [filter.id]
1288
+ });
1289
+ const formattedLogs = logs.map((log) => formatLog(log));
1290
+ if (!filter.abi)
1291
+ return formattedLogs;
1292
+ return parseEventLogs({
1293
+ abi: filter.abi,
1294
+ logs: formattedLogs,
1295
+ strict
1296
+ });
1297
+ }
1298
+
1299
+ // node_modules/viem/_esm/utils/formatters/proof.js
1300
+ function formatStorageProof(storageProof) {
1301
+ return storageProof.map((proof) => ({
1302
+ ...proof,
1303
+ value: BigInt(proof.value)
1304
+ }));
1305
+ }
1306
+ function formatProof(proof) {
1307
+ return {
1308
+ ...proof,
1309
+ balance: proof.balance ? BigInt(proof.balance) : void 0,
1310
+ nonce: proof.nonce ? hexToNumber(proof.nonce) : void 0,
1311
+ storageProof: proof.storageProof ? formatStorageProof(proof.storageProof) : void 0
1312
+ };
1313
+ }
1314
+
1315
+ // node_modules/viem/_esm/actions/public/getProof.js
1316
+ async function getProof(client, { address, blockHash, blockNumber, blockTag = "latest", requireCanonical, storageKeys }) {
1317
+ const block = formatBlockParameter({
1318
+ blockHash,
1319
+ blockNumber,
1320
+ blockTag,
1321
+ requireCanonical
1322
+ });
1323
+ const proof = await client.request({
1324
+ method: "eth_getProof",
1325
+ params: [address, storageKeys, block]
1326
+ });
1327
+ return formatProof(proof);
1328
+ }
1329
+
1330
+ // node_modules/viem/_esm/actions/public/getRawTransaction.js
1331
+ async function getRawTransaction(client, { hash }) {
1332
+ const rawTransaction = await client.request({
1333
+ method: "eth_getRawTransactionByHash",
1334
+ params: [hash]
1335
+ }, { dedupe: true });
1336
+ if (!rawTransaction)
1337
+ throw new TransactionNotFoundError({ hash });
1338
+ return rawTransaction;
1339
+ }
1340
+
1341
+ // node_modules/viem/_esm/actions/public/getStorageAt.js
1342
+ async function getStorageAt(client, { address, blockHash, blockNumber, blockTag = "latest", requireCanonical, slot }) {
1343
+ const block = formatBlockParameter({
1344
+ blockHash,
1345
+ blockNumber,
1346
+ blockTag,
1347
+ requireCanonical
1348
+ });
1349
+ const data = await client.request({
1350
+ method: "eth_getStorageAt",
1351
+ params: [address, slot, block]
1352
+ });
1353
+ return data;
1354
+ }
1355
+
1356
+ // node_modules/viem/_esm/actions/public/getTransactionConfirmations.js
1357
+ async function getTransactionConfirmations(client, { hash, transactionReceipt }) {
1358
+ const [blockNumber, transaction] = await Promise.all([
1359
+ getAction(client, getBlockNumber, "getBlockNumber")({}),
1360
+ hash ? getAction(client, getTransaction, "getTransaction")({ hash }) : void 0
1361
+ ]);
1362
+ const transactionBlockNumber = transactionReceipt?.blockNumber || transaction?.blockNumber;
1363
+ if (!transactionBlockNumber)
1364
+ return 0n;
1365
+ return blockNumber - transactionBlockNumber + 1n;
1366
+ }
1367
+
1368
+ // node_modules/viem/_esm/actions/public/multicall.js
1369
+ async function multicall(client, parameters) {
1370
+ const { account, authorizationList, allowFailure = true, blockHash, blockNumber, blockOverrides, blockTag, requireCanonical, stateOverride } = parameters;
1371
+ const contracts = parameters.contracts;
1372
+ const batch = typeof client.batch?.multicall === "object" ? client.batch.multicall : {};
1373
+ const batchSize = parameters.batchSize ?? batch.batchSize ?? 1024;
1374
+ const deployless = parameters.deployless ?? batch.deployless ?? false;
1375
+ const multicallAddress = (() => {
1376
+ if (parameters.multicallAddress)
1377
+ return parameters.multicallAddress;
1378
+ if (deployless)
1379
+ return null;
1380
+ if (client.chain) {
1381
+ return getChainContractAddress({
1382
+ blockNumber,
1383
+ chain: client.chain,
1384
+ contract: "multicall3"
1385
+ });
1386
+ }
1387
+ throw new Error("client chain not configured. multicallAddress is required.");
1388
+ })();
1389
+ const chunkedCalls = [[]];
1390
+ let currentChunk = 0;
1391
+ let currentChunkSize = 0;
1392
+ for (let i = 0; i < contracts.length; i++) {
1393
+ const { abi: abi2, address, args, functionName } = contracts[i];
1394
+ try {
1395
+ const callData = encodeFunctionData({ abi: abi2, args, functionName });
1396
+ currentChunkSize += (callData.length - 2) / 2;
1397
+ if (
1398
+ // Check if batching is enabled.
1399
+ batchSize > 0 && // Check if the current size of the batch exceeds the size limit.
1400
+ currentChunkSize > batchSize && // Check if the current chunk is not already empty.
1401
+ chunkedCalls[currentChunk].length > 0
1402
+ ) {
1403
+ currentChunk++;
1404
+ currentChunkSize = (callData.length - 2) / 2;
1405
+ chunkedCalls[currentChunk] = [];
1406
+ }
1407
+ chunkedCalls[currentChunk] = [
1408
+ ...chunkedCalls[currentChunk],
1409
+ {
1410
+ allowFailure: true,
1411
+ callData,
1412
+ target: address
1413
+ }
1414
+ ];
1415
+ } catch (err) {
1416
+ const error = getContractError(err, {
1417
+ abi: abi2,
1418
+ address,
1419
+ args,
1420
+ docsPath: "/docs/contract/multicall",
1421
+ functionName,
1422
+ sender: account
1423
+ });
1424
+ if (!allowFailure)
1425
+ throw error;
1426
+ chunkedCalls[currentChunk] = [
1427
+ ...chunkedCalls[currentChunk],
1428
+ {
1429
+ allowFailure: true,
1430
+ callData: "0x",
1431
+ target: address
1432
+ }
1433
+ ];
1434
+ }
1435
+ }
1436
+ const batching = Boolean(client.batch?.multicall);
1437
+ const batches = batching ? chunkedCalls.flatMap((calls) => calls.map((call2) => [call2])) : chunkedCalls;
1438
+ const aggregate3Results = await Promise.allSettled(batches.map((calls) => {
1439
+ if (batching)
1440
+ return scheduleMulticall(client, {
1441
+ account,
1442
+ authorizationList,
1443
+ batchSize,
1444
+ blockHash,
1445
+ blockNumber,
1446
+ blockOverrides,
1447
+ blockTag,
1448
+ call: calls[0],
1449
+ multicallAddress,
1450
+ requireCanonical,
1451
+ stateOverride
1452
+ }).then((result) => [result]);
1453
+ return getAction(client, readContract, "readContract")({
1454
+ ...multicallAddress === null ? { code: multicall3Bytecode } : { address: multicallAddress },
1455
+ abi: multicall3Abi,
1456
+ account,
1457
+ args: [calls],
1458
+ authorizationList,
1459
+ blockHash,
1460
+ blockNumber,
1461
+ blockOverrides,
1462
+ blockTag,
1463
+ functionName: "aggregate3",
1464
+ requireCanonical,
1465
+ stateOverride
1466
+ });
1467
+ }));
1468
+ const results = [];
1469
+ for (let i = 0; i < aggregate3Results.length; i++) {
1470
+ const result = aggregate3Results[i];
1471
+ if (result.status === "rejected") {
1472
+ if (!allowFailure)
1473
+ throw result.reason;
1474
+ for (let j = 0; j < batches[i].length; j++) {
1475
+ results.push({
1476
+ status: "failure",
1477
+ error: result.reason,
1478
+ result: void 0
1479
+ });
1480
+ }
1481
+ continue;
1482
+ }
1483
+ const aggregate3Result = result.value;
1484
+ for (let j = 0; j < aggregate3Result.length; j++) {
1485
+ const { returnData, success } = aggregate3Result[j];
1486
+ const { callData } = batches[i][j];
1487
+ const { abi: abi2, address, functionName, args } = contracts[results.length];
1488
+ try {
1489
+ if (callData === "0x")
1490
+ throw new AbiDecodingZeroDataError();
1491
+ if (!success)
1492
+ throw new RawContractError({ data: returnData });
1493
+ const result2 = decodeFunctionResult({
1494
+ abi: abi2,
1495
+ args,
1496
+ data: returnData,
1497
+ functionName
1498
+ });
1499
+ results.push(allowFailure ? { result: result2, status: "success" } : result2);
1500
+ } catch (err) {
1501
+ const error = getContractError(err, {
1502
+ abi: abi2,
1503
+ address,
1504
+ args,
1505
+ docsPath: "/docs/contract/multicall",
1506
+ functionName
1507
+ });
1508
+ if (!allowFailure)
1509
+ throw error;
1510
+ results.push({ error, result: void 0, status: "failure" });
1511
+ }
1512
+ }
1513
+ }
1514
+ if (results.length !== contracts.length)
1515
+ throw new BaseError("multicall results mismatch");
1516
+ return results;
1517
+ }
1518
+ async function scheduleMulticall(client, parameters) {
1519
+ const { batchSize, call: call2, multicallAddress, ...rest } = parameters;
1520
+ const { wait = 0 } = typeof client.batch?.multicall === "object" ? client.batch.multicall : {};
1521
+ const { schedule } = createBatchScheduler({
1522
+ id: stringify(["multicall", client.uid, batchSize, multicallAddress, rest]),
1523
+ wait,
1524
+ shouldSplitBatch(calls) {
1525
+ if (batchSize === 0)
1526
+ return false;
1527
+ const size3 = calls.reduce((size4, { callData }) => size4 + (callData.length - 2) / 2, 0);
1528
+ return size3 > batchSize;
1529
+ },
1530
+ fn: (calls) => getAction(client, readContract, "readContract")({
1531
+ ...multicallAddress === null ? { code: multicall3Bytecode } : { address: multicallAddress },
1532
+ ...rest,
1533
+ abi: multicall3Abi,
1534
+ args: [calls],
1535
+ functionName: "aggregate3"
1536
+ })
1537
+ });
1538
+ const [result] = await schedule(call2);
1539
+ return result;
1540
+ }
1541
+
1542
+ // node_modules/viem/_esm/actions/public/simulateBlocks.js
1543
+ async function simulateBlocks(client, parameters) {
1544
+ const { blockNumber, blockTag = client.experimental_blockTag ?? "latest", blocks, returnFullTransactions, traceTransfers, validation } = parameters;
1545
+ try {
1546
+ const blockStateCalls = [];
1547
+ for (const block2 of blocks) {
1548
+ const blockOverrides = block2.blockOverrides ? toRpc(block2.blockOverrides) : void 0;
1549
+ const calls = block2.calls.map((call_) => {
1550
+ const call2 = call_;
1551
+ const account = call2.account ? parseAccount(call2.account) : void 0;
1552
+ const data = call2.abi ? encodeFunctionData(call2) : call2.data;
1553
+ const request = {
1554
+ ...call2,
1555
+ account,
1556
+ data: call2.dataSuffix ? concat([data || "0x", call2.dataSuffix]) : data,
1557
+ from: call2.from ?? account?.address
1558
+ };
1559
+ assertRequest(request);
1560
+ return formatTransactionRequest(request);
1561
+ });
1562
+ const stateOverrides = block2.stateOverrides ? serializeStateOverride(block2.stateOverrides) : void 0;
1563
+ blockStateCalls.push({
1564
+ blockOverrides,
1565
+ calls,
1566
+ stateOverrides
1567
+ });
1568
+ }
1569
+ const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : void 0;
1570
+ const block = blockNumberHex || blockTag;
1571
+ const result = await client.request({
1572
+ method: "eth_simulateV1",
1573
+ params: [
1574
+ { blockStateCalls, returnFullTransactions, traceTransfers, validation },
1575
+ block
1576
+ ]
1577
+ });
1578
+ return result.map((block2, i) => ({
1579
+ ...formatBlock(block2),
1580
+ calls: block2.calls.map((call2, j) => {
1581
+ const { abi: abi2, args, functionName, to } = blocks[i].calls[j];
1582
+ const data = call2.error?.data ?? call2.returnData;
1583
+ const gasUsed = BigInt(call2.gasUsed);
1584
+ const logs = call2.logs?.map((log) => formatLog(log));
1585
+ const status = call2.status === "0x1" ? "success" : "failure";
1586
+ const result2 = abi2 && status === "success" && data !== "0x" ? decodeFunctionResult({
1587
+ abi: abi2,
1588
+ data,
1589
+ functionName
1590
+ }) : null;
1591
+ const error = (() => {
1592
+ if (status === "success")
1593
+ return void 0;
1594
+ let error2;
1595
+ if (data === "0x")
1596
+ error2 = new AbiDecodingZeroDataError();
1597
+ else if (data)
1598
+ error2 = new RawContractError({ data });
1599
+ if (!error2)
1600
+ return void 0;
1601
+ return getContractError(error2, {
1602
+ abi: abi2 ?? [],
1603
+ address: to ?? "0x",
1604
+ args,
1605
+ functionName: functionName ?? "<unknown>"
1606
+ });
1607
+ })();
1608
+ return {
1609
+ data,
1610
+ gasUsed,
1611
+ logs,
1612
+ status,
1613
+ ...status === "success" ? {
1614
+ result: result2
1615
+ } : {
1616
+ error
1617
+ }
1618
+ };
1619
+ })
1620
+ }));
1621
+ } catch (e) {
1622
+ const cause = e;
1623
+ const error = getNodeError(cause, {});
1624
+ if (error instanceof UnknownNodeError)
1625
+ throw cause;
1626
+ throw error;
1627
+ }
1628
+ }
1629
+
1630
+ // node_modules/viem/_esm/constants/address.js
1631
+ var ethAddress = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
1632
+ var zeroAddress = "0x0000000000000000000000000000000000000000";
1633
+
1634
+ // node_modules/ox/_esm/core/AbiConstructor.js
1635
+ function encode2(...parameters) {
1636
+ const [abiConstructor, options] = (() => {
1637
+ if (Array.isArray(parameters[0])) {
1638
+ const [abi2, options2] = parameters;
1639
+ return [fromAbi2(abi2), options2];
1640
+ }
1641
+ return parameters;
1642
+ })();
1643
+ const { bytecode, args } = options;
1644
+ return concat2(bytecode, abiConstructor.inputs?.length && args?.length ? encode(abiConstructor.inputs, args) : "0x");
1645
+ }
1646
+ function from2(abiConstructor) {
1647
+ return from(abiConstructor);
1648
+ }
1649
+ function fromAbi2(abi2) {
1650
+ const item = abi2.find((item2) => item2.type === "constructor");
1651
+ if (!item)
1652
+ throw new NotFoundError({ name: "constructor" });
1653
+ return item;
1654
+ }
1655
+
1656
+ // node_modules/ox/_esm/core/AbiFunction.js
1657
+ function encodeData(...parameters) {
1658
+ const [abiFunction, args = []] = (() => {
1659
+ if (Array.isArray(parameters[0])) {
1660
+ const [abi2, name, args3] = parameters;
1661
+ return [fromAbi3(abi2, name, { args: args3 }), args3];
1662
+ }
1663
+ const [abiFunction2, args2] = parameters;
1664
+ return [abiFunction2, args2];
1665
+ })();
1666
+ const { overloads } = abiFunction;
1667
+ const item = overloads ? fromAbi3([abiFunction, ...overloads], abiFunction.name, {
1668
+ args
1669
+ }) : abiFunction;
1670
+ const selector = getSelector2(item);
1671
+ const data = args.length > 0 ? encode(item.inputs, args) : void 0;
1672
+ return data ? concat2(selector, data) : selector;
1673
+ }
1674
+ function from3(abiFunction, options = {}) {
1675
+ return from(abiFunction, options);
1676
+ }
1677
+ function fromAbi3(abi2, name, options) {
1678
+ const item = fromAbi(abi2, name, options);
1679
+ if (item.type !== "function")
1680
+ throw new NotFoundError({ name, type: "function" });
1681
+ return item;
1682
+ }
1683
+ function getSelector2(abiItem) {
1684
+ return getSelector(abiItem);
1685
+ }
1686
+
1687
+ // node_modules/viem/_esm/actions/public/simulateCalls.js
1688
+ var getBalanceCode = "0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";
1689
+ async function simulateCalls(client, parameters) {
1690
+ const { blockNumber, blockTag, calls, stateOverrides, traceAssetChanges, traceTransfers, validation } = parameters;
1691
+ const account = parameters.account ? parseAccount(parameters.account) : void 0;
1692
+ if (traceAssetChanges && !account)
1693
+ throw new BaseError("`account` is required when `traceAssetChanges` is true");
1694
+ const getBalanceData = account ? encode2(from2("constructor(bytes, bytes)"), {
1695
+ bytecode: deploylessCallViaBytecodeBytecode,
1696
+ args: [
1697
+ getBalanceCode,
1698
+ encodeData(from3("function getBalance(address)"), [account.address])
1699
+ ]
1700
+ }) : void 0;
1701
+ const assetAddresses = traceAssetChanges ? await Promise.all(parameters.calls.map(async (call2) => {
1702
+ if (!call2.data && !call2.abi)
1703
+ return;
1704
+ const { accessList } = await createAccessList(client, {
1705
+ account: account.address,
1706
+ ...call2,
1707
+ data: call2.abi ? encodeFunctionData(call2) : call2.data
1708
+ });
1709
+ return accessList.map(({ address, storageKeys }) => storageKeys.length > 0 ? address : null);
1710
+ })).then((x) => x.flat().filter(Boolean)) : [];
1711
+ const blocks = await simulateBlocks(client, {
1712
+ blockNumber,
1713
+ blockTag,
1714
+ blocks: [
1715
+ ...traceAssetChanges ? [
1716
+ // ETH pre balances
1717
+ {
1718
+ calls: [{ data: getBalanceData }],
1719
+ stateOverrides
1720
+ },
1721
+ // Asset pre balances
1722
+ {
1723
+ calls: assetAddresses.map((address, i) => ({
1724
+ abi: [
1725
+ from3("function balanceOf(address) returns (uint256)")
1726
+ ],
1727
+ functionName: "balanceOf",
1728
+ args: [account.address],
1729
+ to: address,
1730
+ from: zeroAddress,
1731
+ nonce: i
1732
+ })),
1733
+ stateOverrides: [
1734
+ {
1735
+ address: zeroAddress,
1736
+ nonce: 0
1737
+ }
1738
+ ]
1739
+ }
1740
+ ] : [],
1741
+ {
1742
+ calls: [...calls, { to: zeroAddress }].map((call2) => ({
1743
+ ...call2,
1744
+ from: account?.address
1745
+ })),
1746
+ stateOverrides
1747
+ },
1748
+ ...traceAssetChanges ? [
1749
+ // ETH post balances
1750
+ {
1751
+ calls: [{ data: getBalanceData }]
1752
+ },
1753
+ // Asset post balances
1754
+ {
1755
+ calls: assetAddresses.map((address, i) => ({
1756
+ abi: [
1757
+ from3("function balanceOf(address) returns (uint256)")
1758
+ ],
1759
+ functionName: "balanceOf",
1760
+ args: [account.address],
1761
+ to: address,
1762
+ from: zeroAddress,
1763
+ nonce: i
1764
+ })),
1765
+ stateOverrides: [
1766
+ {
1767
+ address: zeroAddress,
1768
+ nonce: 0
1769
+ }
1770
+ ]
1771
+ },
1772
+ // Decimals
1773
+ {
1774
+ calls: assetAddresses.map((address, i) => ({
1775
+ to: address,
1776
+ abi: [
1777
+ from3("function decimals() returns (uint256)")
1778
+ ],
1779
+ functionName: "decimals",
1780
+ from: zeroAddress,
1781
+ nonce: i
1782
+ })),
1783
+ stateOverrides: [
1784
+ {
1785
+ address: zeroAddress,
1786
+ nonce: 0
1787
+ }
1788
+ ]
1789
+ },
1790
+ // Token URI
1791
+ {
1792
+ calls: assetAddresses.map((address, i) => ({
1793
+ to: address,
1794
+ abi: [
1795
+ from3("function tokenURI(uint256) returns (string)")
1796
+ ],
1797
+ functionName: "tokenURI",
1798
+ args: [0n],
1799
+ from: zeroAddress,
1800
+ nonce: i
1801
+ })),
1802
+ stateOverrides: [
1803
+ {
1804
+ address: zeroAddress,
1805
+ nonce: 0
1806
+ }
1807
+ ]
1808
+ },
1809
+ // Symbols
1810
+ {
1811
+ calls: assetAddresses.map((address, i) => ({
1812
+ to: address,
1813
+ abi: [from3("function symbol() returns (string)")],
1814
+ functionName: "symbol",
1815
+ from: zeroAddress,
1816
+ nonce: i
1817
+ })),
1818
+ stateOverrides: [
1819
+ {
1820
+ address: zeroAddress,
1821
+ nonce: 0
1822
+ }
1823
+ ]
1824
+ }
1825
+ ] : []
1826
+ ],
1827
+ traceTransfers,
1828
+ validation
1829
+ });
1830
+ const block_results = traceAssetChanges ? blocks[2] : blocks[0];
1831
+ const [block_ethPre, block_assetsPre, , block_ethPost, block_assetsPost, block_decimals, block_tokenURI, block_symbols] = traceAssetChanges ? blocks : [];
1832
+ const { calls: block_calls, ...block } = block_results;
1833
+ const results = block_calls.slice(0, -1) ?? [];
1834
+ const ethPre = block_ethPre?.calls ?? [];
1835
+ const assetsPre = block_assetsPre?.calls ?? [];
1836
+ const balancesPre = [...ethPre, ...assetsPre].map((call2) => call2.status === "success" ? hexToBigInt(call2.data) : null);
1837
+ const ethPost = block_ethPost?.calls ?? [];
1838
+ const assetsPost = block_assetsPost?.calls ?? [];
1839
+ const balancesPost = [...ethPost, ...assetsPost].map((call2) => call2.status === "success" ? hexToBigInt(call2.data) : null);
1840
+ const decimals = (block_decimals?.calls ?? []).map((x) => x.status === "success" ? x.result : null);
1841
+ const symbols = (block_symbols?.calls ?? []).map((x) => x.status === "success" ? x.result : null);
1842
+ const tokenURI = (block_tokenURI?.calls ?? []).map((x) => x.status === "success" ? x.result : null);
1843
+ const changes = [];
1844
+ for (const [i, balancePost] of balancesPost.entries()) {
1845
+ const balancePre = balancesPre[i];
1846
+ if (typeof balancePost !== "bigint")
1847
+ continue;
1848
+ if (typeof balancePre !== "bigint")
1849
+ continue;
1850
+ const decimals_ = decimals[i - 1];
1851
+ const symbol_ = symbols[i - 1];
1852
+ const tokenURI_ = tokenURI[i - 1];
1853
+ const token = (() => {
1854
+ if (i === 0)
1855
+ return {
1856
+ address: ethAddress,
1857
+ decimals: 18,
1858
+ symbol: "ETH"
1859
+ };
1860
+ return {
1861
+ address: assetAddresses[i - 1],
1862
+ decimals: tokenURI_ || decimals_ ? Number(decimals_ ?? 1) : void 0,
1863
+ symbol: symbol_ ?? void 0
1864
+ };
1865
+ })();
1866
+ if (changes.some((change) => change.token.address === token.address))
1867
+ continue;
1868
+ changes.push({
1869
+ token,
1870
+ value: {
1871
+ pre: balancePre,
1872
+ post: balancePost,
1873
+ diff: balancePost - balancePre
1874
+ }
1875
+ });
1876
+ }
1877
+ return {
1878
+ assetChanges: changes,
1879
+ block,
1880
+ results
1881
+ };
1882
+ }
1883
+
1884
+ // node_modules/viem/_esm/actions/public/verifyMessage.js
1885
+ async function verifyMessage(client, { address, message, factory, factoryData, signature, ...callRequest }) {
1886
+ const hash = hashMessage(message);
1887
+ return getAction(client, verifyHash, "verifyHash")({
1888
+ address,
1889
+ factory,
1890
+ factoryData,
1891
+ hash,
1892
+ signature,
1893
+ ...callRequest
1894
+ });
1895
+ }
1896
+
1897
+ // node_modules/viem/_esm/actions/public/verifyTypedData.js
1898
+ async function verifyTypedData(client, parameters) {
1899
+ const { address, factory, factoryData, signature, message, primaryType, types, domain, ...callRequest } = parameters;
1900
+ const hash = hashTypedData({ message, primaryType, types, domain });
1901
+ return getAction(client, verifyHash, "verifyHash")({
1902
+ address,
1903
+ factory,
1904
+ factoryData,
1905
+ hash,
1906
+ signature,
1907
+ ...callRequest
1908
+ });
1909
+ }
1910
+
1911
+ // node_modules/viem/_esm/actions/public/watchBlocks.js
1912
+ function watchBlocks(client, { blockTag = client.experimental_blockTag ?? "latest", emitMissed = false, emitOnBegin = false, onBlock, onError, includeTransactions: includeTransactions_, poll: poll_, pollingInterval = client.pollingInterval }) {
1913
+ const enablePolling = (() => {
1914
+ if (typeof poll_ !== "undefined")
1915
+ return poll_;
1916
+ if (client.transport.type === "webSocket" || client.transport.type === "ipc")
1917
+ return false;
1918
+ if (client.transport.type === "fallback" && (client.transport.transports[0].config.type === "webSocket" || client.transport.transports[0].config.type === "ipc"))
1919
+ return false;
1920
+ return true;
1921
+ })();
1922
+ const includeTransactions = includeTransactions_ ?? false;
1923
+ let prevBlock;
1924
+ const pollBlocks = () => {
1925
+ const observerId = stringify([
1926
+ "watchBlocks",
1927
+ client.uid,
1928
+ blockTag,
1929
+ emitMissed,
1930
+ emitOnBegin,
1931
+ includeTransactions,
1932
+ pollingInterval
1933
+ ]);
1934
+ return observe(observerId, { onBlock, onError }, (emit) => poll(async () => {
1935
+ try {
1936
+ const block = await getAction(client, getBlock, "getBlock")({
1937
+ blockTag,
1938
+ includeTransactions
1939
+ });
1940
+ if (block.number !== null && prevBlock?.number != null) {
1941
+ if (block.number === prevBlock.number)
1942
+ return;
1943
+ if (block.number - prevBlock.number > 1 && emitMissed) {
1944
+ for (let i = prevBlock?.number + 1n; i < block.number; i++) {
1945
+ const block2 = await getAction(client, getBlock, "getBlock")({
1946
+ blockNumber: i,
1947
+ includeTransactions
1948
+ });
1949
+ emit.onBlock(block2, prevBlock);
1950
+ prevBlock = block2;
1951
+ }
1952
+ }
1953
+ }
1954
+ if (
1955
+ // If no previous block exists, emit.
1956
+ prevBlock?.number == null || // If the block tag is "pending" with no block number, emit.
1957
+ blockTag === "pending" && block?.number == null || // If the next block number is greater than the previous block number, emit.
1958
+ // We don't want to emit blocks in the past.
1959
+ block.number !== null && block.number > prevBlock.number
1960
+ ) {
1961
+ emit.onBlock(block, prevBlock);
1962
+ prevBlock = block;
1963
+ }
1964
+ } catch (err) {
1965
+ emit.onError?.(err);
1966
+ }
1967
+ }, {
1968
+ emitOnBegin,
1969
+ interval: pollingInterval
1970
+ }));
1971
+ };
1972
+ const subscribeBlocks = () => {
1973
+ let active = true;
1974
+ let emitFetched = true;
1975
+ let unsubscribe = () => active = false;
1976
+ (async () => {
1977
+ try {
1978
+ if (emitOnBegin) {
1979
+ getAction(client, getBlock, "getBlock")({
1980
+ blockTag,
1981
+ includeTransactions
1982
+ }).then((block) => {
1983
+ if (!active)
1984
+ return;
1985
+ if (!emitFetched)
1986
+ return;
1987
+ onBlock(block, void 0);
1988
+ emitFetched = false;
1989
+ }).catch(onError);
1990
+ }
1991
+ const transport = (() => {
1992
+ if (client.transport.type === "fallback") {
1993
+ const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc");
1994
+ if (!transport2)
1995
+ return client.transport;
1996
+ return transport2.value;
1997
+ }
1998
+ return client.transport;
1999
+ })();
2000
+ const { unsubscribe: unsubscribe_ } = await transport.subscribe({
2001
+ params: ["newHeads"],
2002
+ async onData(data) {
2003
+ if (!active)
2004
+ return;
2005
+ const block = await getAction(client, getBlock, "getBlock")({
2006
+ blockNumber: data.result?.number,
2007
+ includeTransactions
2008
+ }).catch(() => {
2009
+ });
2010
+ if (!active)
2011
+ return;
2012
+ onBlock(block, prevBlock);
2013
+ emitFetched = false;
2014
+ prevBlock = block;
2015
+ },
2016
+ onError(error) {
2017
+ onError?.(error);
2018
+ }
2019
+ });
2020
+ unsubscribe = unsubscribe_;
2021
+ if (!active)
2022
+ unsubscribe();
2023
+ } catch (err) {
2024
+ onError?.(err);
2025
+ }
2026
+ })();
2027
+ return () => unsubscribe();
2028
+ };
2029
+ return enablePolling ? pollBlocks() : subscribeBlocks();
2030
+ }
2031
+
2032
+ // node_modules/viem/_esm/actions/public/watchEvent.js
2033
+ function watchEvent(client, { address, args, batch = true, event, events, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client.pollingInterval, strict: strict_ }) {
2034
+ const enablePolling = (() => {
2035
+ if (typeof poll_ !== "undefined")
2036
+ return poll_;
2037
+ if (typeof fromBlock === "bigint")
2038
+ return true;
2039
+ if (client.transport.type === "webSocket" || client.transport.type === "ipc")
2040
+ return false;
2041
+ if (client.transport.type === "fallback" && (client.transport.transports[0].config.type === "webSocket" || client.transport.transports[0].config.type === "ipc"))
2042
+ return false;
2043
+ return true;
2044
+ })();
2045
+ const strict = strict_ ?? false;
2046
+ const pollEvent = () => {
2047
+ const observerId = stringify([
2048
+ "watchEvent",
2049
+ address,
2050
+ args,
2051
+ batch,
2052
+ client.uid,
2053
+ event,
2054
+ pollingInterval,
2055
+ fromBlock
2056
+ ]);
2057
+ return observe(observerId, { onLogs, onError }, (emit) => {
2058
+ let previousBlockNumber;
2059
+ if (fromBlock !== void 0)
2060
+ previousBlockNumber = fromBlock - 1n;
2061
+ let filter;
2062
+ let initialized = false;
2063
+ const unwatch = poll(async () => {
2064
+ if (!initialized) {
2065
+ try {
2066
+ filter = await getAction(client, createEventFilter, "createEventFilter")({
2067
+ address,
2068
+ args,
2069
+ event,
2070
+ events,
2071
+ strict,
2072
+ fromBlock
2073
+ });
2074
+ } catch {
2075
+ }
2076
+ initialized = true;
2077
+ return;
2078
+ }
2079
+ try {
2080
+ let logs;
2081
+ if (filter) {
2082
+ logs = await getAction(client, getFilterChanges, "getFilterChanges")({ filter });
2083
+ } else {
2084
+ const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({});
2085
+ if (previousBlockNumber && previousBlockNumber !== blockNumber) {
2086
+ logs = await getAction(client, getLogs, "getLogs")({
2087
+ address,
2088
+ args,
2089
+ event,
2090
+ events,
2091
+ fromBlock: previousBlockNumber + 1n,
2092
+ toBlock: blockNumber
2093
+ });
2094
+ } else {
2095
+ logs = [];
2096
+ }
2097
+ previousBlockNumber = blockNumber;
2098
+ }
2099
+ if (logs.length === 0)
2100
+ return;
2101
+ if (batch)
2102
+ emit.onLogs(logs);
2103
+ else
2104
+ for (const log of logs)
2105
+ emit.onLogs([log]);
2106
+ } catch (err) {
2107
+ if (filter && err instanceof InvalidInputRpcError)
2108
+ initialized = false;
2109
+ emit.onError?.(err);
2110
+ }
2111
+ }, {
2112
+ emitOnBegin: true,
2113
+ interval: pollingInterval
2114
+ });
2115
+ return async () => {
2116
+ if (filter)
2117
+ await getAction(client, uninstallFilter, "uninstallFilter")({ filter });
2118
+ unwatch();
2119
+ };
2120
+ });
2121
+ };
2122
+ const subscribeEvent = () => {
2123
+ let active = true;
2124
+ let unsubscribe = () => active = false;
2125
+ (async () => {
2126
+ try {
2127
+ const transport = (() => {
2128
+ if (client.transport.type === "fallback") {
2129
+ const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc");
2130
+ if (!transport2)
2131
+ return client.transport;
2132
+ return transport2.value;
2133
+ }
2134
+ return client.transport;
2135
+ })();
2136
+ const events_ = events ?? (event ? [event] : void 0);
2137
+ let topics = [];
2138
+ if (events_) {
2139
+ const encoded = events_.flatMap((event2) => encodeEventTopics({
2140
+ abi: [event2],
2141
+ eventName: event2.name,
2142
+ args
2143
+ }));
2144
+ topics = [encoded];
2145
+ if (event)
2146
+ topics = topics[0];
2147
+ }
2148
+ const { unsubscribe: unsubscribe_ } = await transport.subscribe({
2149
+ params: ["logs", { address, topics }],
2150
+ onData(data) {
2151
+ if (!active)
2152
+ return;
2153
+ const log = data.result;
2154
+ try {
2155
+ const { eventName, args: args2 } = decodeEventLog({
2156
+ abi: events_ ?? [],
2157
+ data: log.data,
2158
+ topics: log.topics,
2159
+ strict
2160
+ });
2161
+ const formatted = formatLog(log, { args: args2, eventName });
2162
+ onLogs([formatted]);
2163
+ } catch (err) {
2164
+ let eventName;
2165
+ let isUnnamed;
2166
+ if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) {
2167
+ if (strict_)
2168
+ return;
2169
+ eventName = err.abiItem.name;
2170
+ isUnnamed = err.abiItem.inputs?.some((x) => !("name" in x && x.name));
2171
+ }
2172
+ const formatted = formatLog(log, {
2173
+ args: isUnnamed ? [] : {},
2174
+ eventName
2175
+ });
2176
+ onLogs([formatted]);
2177
+ }
2178
+ },
2179
+ onError(error) {
2180
+ onError?.(error);
2181
+ }
2182
+ });
2183
+ unsubscribe = unsubscribe_;
2184
+ if (!active)
2185
+ unsubscribe();
2186
+ } catch (err) {
2187
+ onError?.(err);
2188
+ }
2189
+ })();
2190
+ return () => unsubscribe();
2191
+ };
2192
+ return enablePolling ? pollEvent() : subscribeEvent();
2193
+ }
2194
+
2195
+ // node_modules/viem/_esm/actions/public/watchPendingTransactions.js
2196
+ function watchPendingTransactions(client, { batch = true, onError, onTransactions, poll: poll_, pollingInterval = client.pollingInterval }) {
2197
+ const enablePolling = typeof poll_ !== "undefined" ? poll_ : client.transport.type !== "webSocket" && client.transport.type !== "ipc";
2198
+ const pollPendingTransactions = () => {
2199
+ const observerId = stringify([
2200
+ "watchPendingTransactions",
2201
+ client.uid,
2202
+ batch,
2203
+ pollingInterval
2204
+ ]);
2205
+ return observe(observerId, { onTransactions, onError }, (emit) => {
2206
+ let filter;
2207
+ const unwatch = poll(async () => {
2208
+ try {
2209
+ if (!filter) {
2210
+ try {
2211
+ filter = await getAction(client, createPendingTransactionFilter, "createPendingTransactionFilter")({});
2212
+ return;
2213
+ } catch (err) {
2214
+ unwatch();
2215
+ throw err;
2216
+ }
2217
+ }
2218
+ const hashes = await getAction(client, getFilterChanges, "getFilterChanges")({ filter });
2219
+ if (hashes.length === 0)
2220
+ return;
2221
+ if (batch)
2222
+ emit.onTransactions(hashes);
2223
+ else
2224
+ for (const hash of hashes)
2225
+ emit.onTransactions([hash]);
2226
+ } catch (err) {
2227
+ emit.onError?.(err);
2228
+ }
2229
+ }, {
2230
+ emitOnBegin: true,
2231
+ interval: pollingInterval
2232
+ });
2233
+ return async () => {
2234
+ if (filter)
2235
+ await getAction(client, uninstallFilter, "uninstallFilter")({ filter });
2236
+ unwatch();
2237
+ };
2238
+ });
2239
+ };
2240
+ const subscribePendingTransactions = () => {
2241
+ let active = true;
2242
+ let unsubscribe = () => active = false;
2243
+ (async () => {
2244
+ try {
2245
+ const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({
2246
+ params: ["newPendingTransactions"],
2247
+ onData(data) {
2248
+ if (!active)
2249
+ return;
2250
+ const transaction = data.result;
2251
+ onTransactions([transaction]);
2252
+ },
2253
+ onError(error) {
2254
+ onError?.(error);
2255
+ }
2256
+ });
2257
+ unsubscribe = unsubscribe_;
2258
+ if (!active)
2259
+ unsubscribe();
2260
+ } catch (err) {
2261
+ onError?.(err);
2262
+ }
2263
+ })();
2264
+ return () => unsubscribe();
2265
+ };
2266
+ return enablePolling ? pollPendingTransactions() : subscribePendingTransactions();
2267
+ }
2268
+
2269
+ // node_modules/viem/_esm/actions/token/index.js
2270
+ var token_exports = {};
2271
+ __export(token_exports, {
2272
+ approve: () => approve,
2273
+ approveSync: () => approveSync,
2274
+ getAllowance: () => getAllowance,
2275
+ getBalance: () => getBalance2,
2276
+ getMetadata: () => getMetadata,
2277
+ getTotalSupply: () => getTotalSupply,
2278
+ transfer: () => transfer,
2279
+ transferSync: () => transferSync
2280
+ });
2281
+
2282
+ // node_modules/viem/_esm/actions/token/internal.js
2283
+ function toAmount(amount, decimals) {
2284
+ return { amount, decimals, formatted: formatUnits(amount, decimals) };
2285
+ }
2286
+ function toBaseUnits(amount, decimals) {
2287
+ if (typeof amount === "bigint")
2288
+ return amount;
2289
+ const resolved = amount.decimals ?? decimals;
2290
+ return parseUnits(amount.formatted, requireTokenDecimals(resolved));
2291
+ }
2292
+ function requireTokenDecimals(decimals) {
2293
+ if (decimals === void 0)
2294
+ throw new Error("Token decimals are required. Pass `amount.decimals` or select a declared token.");
2295
+ return decimals;
2296
+ }
2297
+ function resolveAmountDecimals(amount, decimals) {
2298
+ if (typeof amount === "bigint")
2299
+ return decimals;
2300
+ return amount.decimals ?? decimals;
2301
+ }
2302
+ function resolveToken(client, parameters) {
2303
+ const { decimals, token } = parameters;
2304
+ const declared = findDeclaredToken(client, token);
2305
+ if (declared)
2306
+ return {
2307
+ address: declared.address,
2308
+ decimals: decimals ?? declared.decimals
2309
+ };
2310
+ if (isAddress(token, { strict: false }))
2311
+ return {
2312
+ address: token,
2313
+ decimals: decimals ?? inferDecimals(client, token)
2314
+ };
2315
+ throw new Error(`Token "${token}" is not a declared ERC-20 token on the client's \`tokens\` array (with an address for the client's chain), and is not a valid address.`);
2316
+ }
2317
+ function findDeclaredToken(client, token) {
2318
+ const tokens = client.tokens;
2319
+ const chainId = client.chain?.id;
2320
+ if (!tokens || chainId === void 0)
2321
+ return void 0;
2322
+ const bySymbol = findTokenBySymbol(tokens, token);
2323
+ if (bySymbol)
2324
+ return resolveTokenForChain(bySymbol, chainId);
2325
+ if (isAddress(token, { strict: false }))
2326
+ for (const token_ of tokens) {
2327
+ const resolved = resolveTokenForChain(token_, chainId);
2328
+ if (resolved && isAddressEqual(resolved.address, token))
2329
+ return resolved;
2330
+ }
2331
+ return void 0;
2332
+ }
2333
+ function resolveTokenForChain(token, chainId) {
2334
+ const address = token.addresses[chainId];
2335
+ if (!address)
2336
+ return void 0;
2337
+ return {
2338
+ address,
2339
+ currency: token.currency,
2340
+ decimals: token.decimals,
2341
+ name: token.name,
2342
+ popular: token.popular,
2343
+ symbol: token.symbol
2344
+ };
2345
+ }
2346
+ function findTokenBySymbol(tokens, symbol) {
2347
+ const lowerSymbol = symbol.toLowerCase();
2348
+ for (const token of tokens) {
2349
+ if (token.symbol?.toLowerCase() === lowerSymbol)
2350
+ return token;
2351
+ }
2352
+ return void 0;
2353
+ }
2354
+ function inferDecimals(client, address) {
2355
+ const tokens = client.tokens;
2356
+ const chainId = client.chain?.id;
2357
+ if (tokens && chainId !== void 0)
2358
+ for (const token of tokens) {
2359
+ const resolved = resolveTokenForChain(token, chainId);
2360
+ if (resolved && isAddressEqual(resolved.address, address))
2361
+ return resolved.decimals;
2362
+ }
2363
+ return void 0;
2364
+ }
2365
+ async function resolveTokenWithDecimals(client, parameters) {
2366
+ const { address, decimals } = resolveToken(client, parameters);
2367
+ if (decimals !== void 0)
2368
+ return { address, decimals };
2369
+ return {
2370
+ address,
2371
+ decimals: await readContract(client, {
2372
+ abi: erc20Abi,
2373
+ address,
2374
+ functionName: "decimals"
2375
+ })
2376
+ };
2377
+ }
2378
+ function pickWriteParameters(parameters) {
2379
+ const { account, chain, gas, maxFeePerGas, maxPriorityFeePerGas, nonce } = parameters;
2380
+ return { account, chain, gas, maxFeePerGas, maxPriorityFeePerGas, nonce };
2381
+ }
2382
+ function defineCall(call2) {
2383
+ return {
2384
+ ...call2,
2385
+ data: encodeFunctionData(call2),
2386
+ to: call2.address
2387
+ };
2388
+ }
2389
+
2390
+ // node_modules/viem/_esm/actions/token/approve.js
2391
+ async function approve(client, parameters) {
2392
+ return approve.inner(writeContract, client, parameters);
2393
+ }
2394
+ (function(approve2) {
2395
+ async function inner(action, client, parameters) {
2396
+ return await action(client, {
2397
+ ...parameters,
2398
+ ...approve2.call(client, parameters)
2399
+ });
2400
+ }
2401
+ approve2.inner = inner;
2402
+ function call2(client, parameters) {
2403
+ return defineCall(getCall(client, parameters));
2404
+ }
2405
+ approve2.call = call2;
2406
+ async function estimateGas2(client, parameters) {
2407
+ return estimateContractGas(client, {
2408
+ ...pickWriteParameters(parameters),
2409
+ ...approve2.call(client, parameters)
2410
+ });
2411
+ }
2412
+ approve2.estimateGas = estimateGas2;
2413
+ async function simulate(client, parameters) {
2414
+ return simulateContract(client, {
2415
+ ...pickWriteParameters(parameters),
2416
+ ...approve2.call(client, parameters)
2417
+ });
2418
+ }
2419
+ approve2.simulate = simulate;
2420
+ function extractEvent(logs) {
2421
+ const [log] = parseEventLogs({
2422
+ abi: erc20Abi,
2423
+ logs,
2424
+ eventName: "Approval",
2425
+ strict: true
2426
+ });
2427
+ if (!log)
2428
+ throw new Error("`Approval` event not found.");
2429
+ return log;
2430
+ }
2431
+ approve2.extractEvent = extractEvent;
2432
+ })(approve || (approve = {}));
2433
+ function getCall(client, parameters) {
2434
+ const { amount, spender, token } = parameters;
2435
+ const { address, decimals } = resolveToken(client, { token });
2436
+ return {
2437
+ abi: erc20Abi,
2438
+ address,
2439
+ args: [spender, toBaseUnits(amount, decimals)],
2440
+ functionName: "approve"
2441
+ };
2442
+ }
2443
+
2444
+ // node_modules/viem/_esm/actions/token/approveSync.js
2445
+ async function approveSync(client, parameters) {
2446
+ const { amount, token, throwOnReceiptRevert = true } = parameters;
2447
+ const { decimals } = resolveToken(client, { token });
2448
+ const resolved = resolveAmountDecimals(amount, decimals);
2449
+ const receipt = await approve.inner(writeContractSync, client, {
2450
+ ...parameters,
2451
+ throwOnReceiptRevert
2452
+ });
2453
+ const { args } = approve.extractEvent(receipt.logs);
2454
+ return {
2455
+ ...args,
2456
+ ...resolved === void 0 ? {} : { decimals: resolved, formatted: formatUnits(args.value, resolved) },
2457
+ receipt
2458
+ };
2459
+ }
2460
+
2461
+ // node_modules/viem/_esm/actions/token/getAllowance.js
2462
+ async function getAllowance(client, parameters) {
2463
+ const { account, decimals, spender, token, ...rest } = parameters;
2464
+ const [amount, { decimals: resolved }] = await Promise.all([
2465
+ readContract(client, {
2466
+ ...rest,
2467
+ ...getAllowance.call(client, { account, spender, token })
2468
+ }),
2469
+ resolveTokenWithDecimals(client, {
2470
+ decimals,
2471
+ token
2472
+ })
2473
+ ]);
2474
+ return toAmount(amount, resolved);
2475
+ }
2476
+ (function(getAllowance2) {
2477
+ function call2(client, args) {
2478
+ return defineCall({
2479
+ address: resolveToken(client, args).address,
2480
+ abi: erc20Abi,
2481
+ functionName: "allowance",
2482
+ args: [args.account, args.spender]
2483
+ });
2484
+ }
2485
+ getAllowance2.call = call2;
2486
+ })(getAllowance || (getAllowance = {}));
2487
+
2488
+ // node_modules/viem/_esm/actions/token/getBalance.js
2489
+ async function getBalance2(client, parameters) {
2490
+ const { account: account_ = client.account, decimals, token, ...rest } = parameters;
2491
+ if (!account_)
2492
+ throw new AccountNotFoundError();
2493
+ const account = parseAccount(account_).address;
2494
+ const [amount, { decimals: resolved }] = await Promise.all([
2495
+ readContract(client, {
2496
+ ...rest,
2497
+ ...getBalance2.call(client, { account, token })
2498
+ }),
2499
+ resolveTokenWithDecimals(client, {
2500
+ decimals,
2501
+ token
2502
+ })
2503
+ ]);
2504
+ return toAmount(amount, resolved);
2505
+ }
2506
+ (function(getBalance3) {
2507
+ function call2(client, args) {
2508
+ const account_ = args.account ?? client.account;
2509
+ if (!account_)
2510
+ throw new AccountNotFoundError();
2511
+ const account = parseAccount(account_).address;
2512
+ return defineCall({
2513
+ address: resolveToken(client, args).address,
2514
+ abi: erc20Abi,
2515
+ functionName: "balanceOf",
2516
+ args: [account]
2517
+ });
2518
+ }
2519
+ getBalance3.call = call2;
2520
+ })(getBalance2 || (getBalance2 = {}));
2521
+
2522
+ // node_modules/viem/_esm/actions/token/getMetadata.js
2523
+ async function getMetadata(client, parameters) {
2524
+ const { token, ...rest } = parameters;
2525
+ const { address } = resolveToken(client, { token });
2526
+ const declared = findDeclaredToken(client, token);
2527
+ const [decimals_, name, symbol] = await Promise.all([
2528
+ declared?.decimals ?? readContract(client, {
2529
+ ...rest,
2530
+ abi: erc20Abi,
2531
+ address,
2532
+ functionName: "decimals"
2533
+ }),
2534
+ declared?.name ?? readContract(client, {
2535
+ ...rest,
2536
+ abi: erc20Abi,
2537
+ address,
2538
+ functionName: "name"
2539
+ }),
2540
+ declared?.symbol ?? readContract(client, {
2541
+ ...rest,
2542
+ abi: erc20Abi,
2543
+ address,
2544
+ functionName: "symbol"
2545
+ })
2546
+ ]);
2547
+ return {
2548
+ decimals: decimals_,
2549
+ name,
2550
+ symbol
2551
+ };
2552
+ }
2553
+
2554
+ // node_modules/viem/_esm/actions/token/getTotalSupply.js
2555
+ async function getTotalSupply(client, parameters) {
2556
+ const { decimals, token, ...rest } = parameters;
2557
+ const [amount, { decimals: resolved }] = await Promise.all([
2558
+ readContract(client, {
2559
+ ...rest,
2560
+ ...getTotalSupply.call(client, { token })
2561
+ }),
2562
+ resolveTokenWithDecimals(client, {
2563
+ decimals,
2564
+ token
2565
+ })
2566
+ ]);
2567
+ return toAmount(amount, resolved);
2568
+ }
2569
+ (function(getTotalSupply2) {
2570
+ function call2(client, args) {
2571
+ return defineCall({
2572
+ address: resolveToken(client, args).address,
2573
+ abi: erc20Abi,
2574
+ args: [],
2575
+ functionName: "totalSupply"
2576
+ });
2577
+ }
2578
+ getTotalSupply2.call = call2;
2579
+ })(getTotalSupply || (getTotalSupply = {}));
2580
+
2581
+ // node_modules/viem/_esm/actions/token/transfer.js
2582
+ async function transfer(client, parameters) {
2583
+ return transfer.inner(writeContract, client, parameters);
2584
+ }
2585
+ (function(transfer2) {
2586
+ async function inner(action, client, parameters) {
2587
+ return await action(client, {
2588
+ ...parameters,
2589
+ ...transfer2.call(client, parameters)
2590
+ });
2591
+ }
2592
+ transfer2.inner = inner;
2593
+ function call2(client, parameters) {
2594
+ return defineCall(getCall2(client, parameters));
2595
+ }
2596
+ transfer2.call = call2;
2597
+ async function estimateGas2(client, parameters) {
2598
+ return estimateContractGas(client, {
2599
+ ...pickWriteParameters(parameters),
2600
+ ...transfer2.call(client, parameters)
2601
+ });
2602
+ }
2603
+ transfer2.estimateGas = estimateGas2;
2604
+ async function simulate(client, parameters) {
2605
+ return simulateContract(client, {
2606
+ ...pickWriteParameters(parameters),
2607
+ ...transfer2.call(client, parameters)
2608
+ });
2609
+ }
2610
+ transfer2.simulate = simulate;
2611
+ function extractEvent(logs) {
2612
+ const [log] = parseEventLogs({
2613
+ abi: erc20Abi,
2614
+ logs,
2615
+ eventName: "Transfer",
2616
+ strict: true
2617
+ });
2618
+ if (!log)
2619
+ throw new Error("`Transfer` event not found.");
2620
+ return log;
2621
+ }
2622
+ transfer2.extractEvent = extractEvent;
2623
+ })(transfer || (transfer = {}));
2624
+ function getCall2(client, parameters) {
2625
+ const { amount, from: from4, to, token } = parameters;
2626
+ const { address, decimals } = resolveToken(client, { token });
2627
+ const value = toBaseUnits(amount, decimals);
2628
+ if (from4)
2629
+ return {
2630
+ abi: erc20Abi,
2631
+ address,
2632
+ args: [from4, to, value],
2633
+ functionName: "transferFrom"
2634
+ };
2635
+ return {
2636
+ abi: erc20Abi,
2637
+ address,
2638
+ args: [to, value],
2639
+ functionName: "transfer"
2640
+ };
2641
+ }
2642
+
2643
+ // node_modules/viem/_esm/actions/token/transferSync.js
2644
+ async function transferSync(client, parameters) {
2645
+ const { amount, token, throwOnReceiptRevert = true } = parameters;
2646
+ const { decimals } = resolveToken(client, { token });
2647
+ const resolved = resolveAmountDecimals(amount, decimals);
2648
+ const receipt = await transfer.inner(writeContractSync, client, {
2649
+ ...parameters,
2650
+ throwOnReceiptRevert
2651
+ });
2652
+ const { args } = transfer.extractEvent(receipt.logs);
2653
+ return {
2654
+ ...args,
2655
+ ...resolved === void 0 ? {} : { decimals: resolved, formatted: formatUnits(args.value, resolved) },
2656
+ receipt
2657
+ };
2658
+ }
2659
+
2660
+ // node_modules/viem/_esm/actions/test/dropTransaction.js
2661
+ async function dropTransaction(client, { hash }) {
2662
+ await client.request({
2663
+ method: `${client.mode}_dropTransaction`,
2664
+ params: [hash]
2665
+ });
2666
+ }
2667
+
2668
+ // node_modules/viem/_esm/actions/test/dumpState.js
2669
+ async function dumpState(client) {
2670
+ return client.request({
2671
+ method: `${client.mode}_dumpState`
2672
+ });
2673
+ }
2674
+
2675
+ // node_modules/viem/_esm/actions/test/getAutomine.js
2676
+ async function getAutomine(client) {
2677
+ if (client.mode === "ganache")
2678
+ return await client.request({
2679
+ method: "eth_mining"
2680
+ });
2681
+ return await client.request({
2682
+ method: `${client.mode}_getAutomine`
2683
+ });
2684
+ }
2685
+
2686
+ // node_modules/viem/_esm/actions/test/getTxpoolContent.js
2687
+ async function getTxpoolContent(client) {
2688
+ return await client.request({
2689
+ method: "txpool_content"
2690
+ });
2691
+ }
2692
+
2693
+ // node_modules/viem/_esm/actions/test/getTxpoolStatus.js
2694
+ async function getTxpoolStatus(client) {
2695
+ const { pending, queued } = await client.request({
2696
+ method: "txpool_status"
2697
+ });
2698
+ return {
2699
+ pending: hexToNumber(pending),
2700
+ queued: hexToNumber(queued)
2701
+ };
2702
+ }
2703
+
2704
+ // node_modules/viem/_esm/actions/test/impersonateAccount.js
2705
+ async function impersonateAccount(client, { address }) {
2706
+ await client.request({
2707
+ method: `${client.mode}_impersonateAccount`,
2708
+ params: [address]
2709
+ });
2710
+ }
2711
+
2712
+ // node_modules/viem/_esm/actions/test/increaseTime.js
2713
+ async function increaseTime(client, { seconds }) {
2714
+ return await client.request({
2715
+ method: "evm_increaseTime",
2716
+ params: [numberToHex(seconds)]
2717
+ });
2718
+ }
2719
+
2720
+ // node_modules/viem/_esm/actions/test/inspectTxpool.js
2721
+ async function inspectTxpool(client) {
2722
+ return await client.request({
2723
+ method: "txpool_inspect"
2724
+ });
2725
+ }
2726
+
2727
+ // node_modules/viem/_esm/actions/test/loadState.js
2728
+ async function loadState(client, { state }) {
2729
+ await client.request({
2730
+ method: `${client.mode}_loadState`,
2731
+ params: [state]
2732
+ });
2733
+ }
2734
+
2735
+ // node_modules/viem/_esm/actions/test/mine.js
2736
+ async function mine(client, { blocks, interval }) {
2737
+ if (client.mode === "ganache")
2738
+ await client.request({
2739
+ method: "evm_mine",
2740
+ params: [{ blocks: numberToHex(blocks) }]
2741
+ });
2742
+ else
2743
+ await client.request({
2744
+ method: `${client.mode}_mine`,
2745
+ params: [numberToHex(blocks), numberToHex(interval || 0)]
2746
+ });
2747
+ }
2748
+
2749
+ // node_modules/viem/_esm/actions/test/removeBlockTimestampInterval.js
2750
+ async function removeBlockTimestampInterval(client) {
2751
+ await client.request({
2752
+ method: `${client.mode}_removeBlockTimestampInterval`
2753
+ });
2754
+ }
2755
+
2756
+ // node_modules/viem/_esm/actions/test/reset.js
2757
+ async function reset(client, { blockNumber, jsonRpcUrl } = {}) {
2758
+ await client.request({
2759
+ method: `${client.mode}_reset`,
2760
+ params: [{ forking: { blockNumber: Number(blockNumber), jsonRpcUrl } }]
2761
+ });
2762
+ }
2763
+
2764
+ // node_modules/viem/_esm/actions/test/revert.js
2765
+ async function revert(client, { id }) {
2766
+ await client.request({
2767
+ method: "evm_revert",
2768
+ params: [id]
2769
+ });
2770
+ }
2771
+
2772
+ // node_modules/viem/_esm/actions/test/sendUnsignedTransaction.js
2773
+ async function sendUnsignedTransaction(client, args) {
2774
+ const { accessList, data, from: from4, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value, ...rest } = args;
2775
+ const chainFormat = client.chain?.formatters?.transactionRequest?.format;
2776
+ const format = chainFormat || formatTransactionRequest;
2777
+ const request = format({
2778
+ // Pick out extra data that might exist on the chain's transaction request type.
2779
+ ...extract(rest, { format: chainFormat }),
2780
+ accessList,
2781
+ data,
2782
+ from: from4,
2783
+ gas,
2784
+ gasPrice,
2785
+ maxFeePerGas,
2786
+ maxPriorityFeePerGas,
2787
+ nonce,
2788
+ to,
2789
+ value
2790
+ }, "sendUnsignedTransaction");
2791
+ const hash = await client.request({
2792
+ method: "eth_sendUnsignedTransaction",
2793
+ params: [request]
2794
+ });
2795
+ return hash;
2796
+ }
2797
+
2798
+ // node_modules/viem/_esm/actions/test/setAutomine.js
2799
+ async function setAutomine(client, enabled) {
2800
+ if (client.mode === "ganache") {
2801
+ if (enabled)
2802
+ await client.request({ method: "miner_start" });
2803
+ else
2804
+ await client.request({ method: "miner_stop" });
2805
+ } else
2806
+ await client.request({
2807
+ method: "evm_setAutomine",
2808
+ params: [enabled]
2809
+ });
2810
+ }
2811
+
2812
+ // node_modules/viem/_esm/actions/test/setBalance.js
2813
+ async function setBalance(client, { address, value }) {
2814
+ if (client.mode === "ganache")
2815
+ await client.request({
2816
+ method: "evm_setAccountBalance",
2817
+ params: [address, numberToHex(value)]
2818
+ });
2819
+ else
2820
+ await client.request({
2821
+ method: `${client.mode}_setBalance`,
2822
+ params: [address, numberToHex(value)]
2823
+ });
2824
+ }
2825
+
2826
+ // node_modules/viem/_esm/actions/test/setBlockGasLimit.js
2827
+ async function setBlockGasLimit(client, { gasLimit }) {
2828
+ await client.request({
2829
+ method: "evm_setBlockGasLimit",
2830
+ params: [numberToHex(gasLimit)]
2831
+ });
2832
+ }
2833
+
2834
+ // node_modules/viem/_esm/actions/test/setBlockTimestampInterval.js
2835
+ async function setBlockTimestampInterval(client, { interval }) {
2836
+ const interval_ = (() => {
2837
+ if (client.mode === "hardhat")
2838
+ return interval * 1e3;
2839
+ return interval;
2840
+ })();
2841
+ await client.request({
2842
+ method: `${client.mode}_setBlockTimestampInterval`,
2843
+ params: [interval_]
2844
+ });
2845
+ }
2846
+
2847
+ // node_modules/viem/_esm/actions/test/setCode.js
2848
+ async function setCode(client, { address, bytecode }) {
2849
+ if (client.mode === "ganache")
2850
+ await client.request({
2851
+ method: "evm_setAccountCode",
2852
+ params: [address, bytecode]
2853
+ });
2854
+ else
2855
+ await client.request({
2856
+ method: `${client.mode}_setCode`,
2857
+ params: [address, bytecode]
2858
+ });
2859
+ }
2860
+
2861
+ // node_modules/viem/_esm/actions/test/setCoinbase.js
2862
+ async function setCoinbase(client, { address }) {
2863
+ await client.request({
2864
+ method: `${client.mode}_setCoinbase`,
2865
+ params: [address]
2866
+ });
2867
+ }
2868
+
2869
+ // node_modules/viem/_esm/actions/test/setIntervalMining.js
2870
+ async function setIntervalMining(client, { interval }) {
2871
+ const interval_ = (() => {
2872
+ if (client.mode === "hardhat")
2873
+ return interval * 1e3;
2874
+ return interval;
2875
+ })();
2876
+ await client.request({
2877
+ method: "evm_setIntervalMining",
2878
+ params: [interval_]
2879
+ });
2880
+ }
2881
+
2882
+ // node_modules/viem/_esm/actions/test/setLoggingEnabled.js
2883
+ async function setLoggingEnabled(client, enabled) {
2884
+ await client.request({
2885
+ method: `${client.mode}_setLoggingEnabled`,
2886
+ params: [enabled]
2887
+ });
2888
+ }
2889
+
2890
+ // node_modules/viem/_esm/actions/test/setMinGasPrice.js
2891
+ async function setMinGasPrice(client, { gasPrice }) {
2892
+ await client.request({
2893
+ method: `${client.mode}_setMinGasPrice`,
2894
+ params: [numberToHex(gasPrice)]
2895
+ });
2896
+ }
2897
+
2898
+ // node_modules/viem/_esm/actions/test/setNextBlockBaseFeePerGas.js
2899
+ async function setNextBlockBaseFeePerGas(client, { baseFeePerGas }) {
2900
+ await client.request({
2901
+ method: `${client.mode}_setNextBlockBaseFeePerGas`,
2902
+ params: [numberToHex(baseFeePerGas)]
2903
+ });
2904
+ }
2905
+
2906
+ // node_modules/viem/_esm/actions/test/setNextBlockTimestamp.js
2907
+ async function setNextBlockTimestamp(client, { timestamp }) {
2908
+ await client.request({
2909
+ method: "evm_setNextBlockTimestamp",
2910
+ params: [numberToHex(timestamp)]
2911
+ });
2912
+ }
2913
+
2914
+ // node_modules/viem/_esm/actions/test/setNonce.js
2915
+ async function setNonce(client, { address, nonce }) {
2916
+ await client.request({
2917
+ method: `${client.mode}_setNonce`,
2918
+ params: [address, numberToHex(nonce)]
2919
+ });
2920
+ }
2921
+
2922
+ // node_modules/viem/_esm/actions/test/setRpcUrl.js
2923
+ async function setRpcUrl(client, jsonRpcUrl) {
2924
+ await client.request({
2925
+ method: `${client.mode}_setRpcUrl`,
2926
+ params: [jsonRpcUrl]
2927
+ });
2928
+ }
2929
+
2930
+ // node_modules/viem/_esm/actions/test/setStorageAt.js
2931
+ async function setStorageAt(client, { address, index, value }) {
2932
+ await client.request({
2933
+ method: `${client.mode}_setStorageAt`,
2934
+ params: [
2935
+ address,
2936
+ typeof index === "number" ? numberToHex(index) : index,
2937
+ value
2938
+ ]
2939
+ });
2940
+ }
2941
+
2942
+ // node_modules/viem/_esm/actions/test/snapshot.js
2943
+ async function snapshot(client) {
2944
+ return await client.request({
2945
+ method: "evm_snapshot"
2946
+ });
2947
+ }
2948
+
2949
+ // node_modules/viem/_esm/actions/test/stopImpersonatingAccount.js
2950
+ async function stopImpersonatingAccount(client, { address }) {
2951
+ await client.request({
2952
+ method: `${client.mode}_stopImpersonatingAccount`,
2953
+ params: [address]
2954
+ });
2955
+ }
2956
+
2957
+ // node_modules/viem/_esm/actions/wallet/addChain.js
2958
+ async function addChain(client, { chain }) {
2959
+ const { id, name, nativeCurrency, rpcUrls, blockExplorers } = chain;
2960
+ await client.request({
2961
+ method: "wallet_addEthereumChain",
2962
+ params: [
2963
+ {
2964
+ chainId: numberToHex(id),
2965
+ chainName: name,
2966
+ nativeCurrency,
2967
+ rpcUrls: rpcUrls.default.http,
2968
+ blockExplorerUrls: blockExplorers ? Object.values(blockExplorers).map(({ url }) => url) : void 0
2969
+ }
2970
+ ]
2971
+ }, { dedupe: true, retryCount: 0 });
2972
+ }
2973
+
2974
+ // node_modules/viem/_esm/actions/wallet/deployContract.js
2975
+ function deployContract(walletClient, parameters) {
2976
+ const { abi: abi2, args, bytecode, ...request } = parameters;
2977
+ const calldata = encodeDeployData({ abi: abi2, args, bytecode });
2978
+ return sendTransaction(walletClient, {
2979
+ ...request,
2980
+ ...request.authorizationList ? { to: null } : {},
2981
+ data: calldata
2982
+ });
2983
+ }
2984
+
2985
+ // node_modules/viem/_esm/actions/wallet/getAddresses.js
2986
+ async function getAddresses(client) {
2987
+ if (client.account?.type === "local")
2988
+ return [client.account.address];
2989
+ const addresses = await client.request({ method: "eth_accounts" }, { dedupe: true });
2990
+ return addresses.map((address) => checksumAddress(address));
2991
+ }
2992
+
2993
+ // node_modules/viem/_esm/actions/wallet/getCapabilities.js
2994
+ async function getCapabilities(client, parameters = {}) {
2995
+ const { account = client.account, chainId } = parameters;
2996
+ const account_ = account ? parseAccount(account) : void 0;
2997
+ const params = chainId ? [account_?.address, [numberToHex(chainId)]] : [account_?.address];
2998
+ const capabilities_raw = await client.request({
2999
+ method: "wallet_getCapabilities",
3000
+ params
3001
+ });
3002
+ const capabilities = {};
3003
+ for (const [chainId2, capabilities_] of Object.entries(capabilities_raw)) {
3004
+ capabilities[Number(chainId2)] = {};
3005
+ for (let [key, value] of Object.entries(capabilities_)) {
3006
+ if (key === "addSubAccount")
3007
+ key = "unstable_addSubAccount";
3008
+ capabilities[Number(chainId2)][key] = value;
3009
+ }
3010
+ }
3011
+ return typeof chainId === "number" ? capabilities[chainId] : capabilities;
3012
+ }
3013
+
3014
+ // node_modules/viem/_esm/actions/wallet/getPermissions.js
3015
+ async function getPermissions(client) {
3016
+ const permissions = await client.request({ method: "wallet_getPermissions" }, { dedupe: true });
3017
+ return permissions;
3018
+ }
3019
+
3020
+ // node_modules/viem/_esm/actions/wallet/prepareAuthorization.js
3021
+ async function prepareAuthorization(client, parameters) {
3022
+ const { account: account_ = client.account, chainId, nonce } = parameters;
3023
+ if (!account_)
3024
+ throw new AccountNotFoundError({
3025
+ docsPath: "/docs/eip7702/prepareAuthorization"
3026
+ });
3027
+ const account = parseAccount(account_);
3028
+ const executor = (() => {
3029
+ if (!parameters.executor)
3030
+ return void 0;
3031
+ if (parameters.executor === "self")
3032
+ return parameters.executor;
3033
+ return parseAccount(parameters.executor);
3034
+ })();
3035
+ const authorization = {
3036
+ address: parameters.contractAddress ?? parameters.address,
3037
+ chainId,
3038
+ nonce
3039
+ };
3040
+ if (typeof authorization.chainId === "undefined")
3041
+ authorization.chainId = client.chain?.id ?? await getAction(client, getChainId, "getChainId")({});
3042
+ if (typeof authorization.nonce === "undefined") {
3043
+ authorization.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({
3044
+ address: account.address,
3045
+ blockTag: "pending"
3046
+ });
3047
+ if (executor === "self" || executor?.address && isAddressEqual(executor.address, account.address))
3048
+ authorization.nonce += 1;
3049
+ }
3050
+ return authorization;
3051
+ }
3052
+
3053
+ // node_modules/viem/_esm/actions/wallet/requestAddresses.js
3054
+ async function requestAddresses(client) {
3055
+ const addresses = await client.request({ method: "eth_requestAccounts" }, { dedupe: true, retryCount: 0 });
3056
+ return addresses.map((address) => getAddress(address));
3057
+ }
3058
+
3059
+ // node_modules/viem/_esm/actions/wallet/requestPermissions.js
3060
+ async function requestPermissions(client, permissions) {
3061
+ return client.request({
3062
+ method: "wallet_requestPermissions",
3063
+ params: [permissions]
3064
+ }, { retryCount: 0 });
3065
+ }
3066
+
3067
+ // node_modules/viem/_esm/actions/wallet/sendCallsSync.js
3068
+ async function sendCallsSync(client, parameters) {
3069
+ const { chain = client.chain } = parameters;
3070
+ const timeout = parameters.timeout ?? Math.max((chain?.blockTime ?? 0) * 3, 5e3);
3071
+ const result = await getAction(client, sendCalls, "sendCalls")(parameters);
3072
+ const status = await getAction(client, waitForCallsStatus, "waitForCallsStatus")({
3073
+ ...parameters,
3074
+ id: result.id,
3075
+ timeout
3076
+ });
3077
+ return status;
3078
+ }
3079
+
3080
+ // node_modules/viem/_esm/actions/wallet/showCallsStatus.js
3081
+ async function showCallsStatus(client, parameters) {
3082
+ const { id } = parameters;
3083
+ await client.request({
3084
+ method: "wallet_showCallsStatus",
3085
+ params: [id]
3086
+ });
3087
+ return;
3088
+ }
3089
+
3090
+ // node_modules/viem/_esm/actions/wallet/signAuthorization.js
3091
+ async function signAuthorization(client, parameters) {
3092
+ const { account: account_ = client.account } = parameters;
3093
+ if (!account_)
3094
+ throw new AccountNotFoundError({
3095
+ docsPath: "/docs/eip7702/signAuthorization"
3096
+ });
3097
+ const account = parseAccount(account_);
3098
+ if (!account.signAuthorization)
3099
+ throw new AccountTypeNotSupportedError({
3100
+ docsPath: "/docs/eip7702/signAuthorization",
3101
+ metaMessages: [
3102
+ "The `signAuthorization` Action does not support JSON-RPC Accounts."
3103
+ ],
3104
+ type: account.type
3105
+ });
3106
+ const authorization = await prepareAuthorization(client, parameters);
3107
+ return account.signAuthorization(authorization);
3108
+ }
3109
+
3110
+ // node_modules/viem/_esm/actions/wallet/signMessage.js
3111
+ async function signMessage(client, { account: account_ = client.account, message }) {
3112
+ if (!account_)
3113
+ throw new AccountNotFoundError({
3114
+ docsPath: "/docs/actions/wallet/signMessage"
3115
+ });
3116
+ const account = parseAccount(account_);
3117
+ if (account.signMessage)
3118
+ return account.signMessage({ message });
3119
+ const message_ = (() => {
3120
+ if (typeof message === "string")
3121
+ return stringToHex(message);
3122
+ if (message.raw instanceof Uint8Array)
3123
+ return toHex(message.raw);
3124
+ return message.raw;
3125
+ })();
3126
+ return client.request({
3127
+ method: "personal_sign",
3128
+ params: [message_, account.address]
3129
+ }, { retryCount: 0 });
3130
+ }
3131
+
3132
+ // node_modules/viem/_esm/actions/wallet/signTransaction.js
3133
+ async function signTransaction(client, parameters) {
3134
+ const { account: account_ = client.account, chain = client.chain, ...transaction } = parameters;
3135
+ if (!account_)
3136
+ throw new AccountNotFoundError({
3137
+ docsPath: "/docs/actions/wallet/signTransaction"
3138
+ });
3139
+ const account = parseAccount(account_);
3140
+ assertRequest({
3141
+ account,
3142
+ ...parameters
3143
+ });
3144
+ const chainId = await getAction(client, getChainId, "getChainId")({});
3145
+ if (chain !== null)
3146
+ assertCurrentChain({
3147
+ currentChainId: chainId,
3148
+ chain
3149
+ });
3150
+ const formatters = chain?.formatters || client.chain?.formatters;
3151
+ const format = formatters?.transactionRequest?.format || formatTransactionRequest;
3152
+ if (account.signTransaction)
3153
+ return account.signTransaction({
3154
+ ...transaction,
3155
+ account,
3156
+ chainId
3157
+ }, { serializer: client.chain?.serializers?.transaction });
3158
+ return await client.request({
3159
+ method: "eth_signTransaction",
3160
+ params: [
3161
+ {
3162
+ ...format({
3163
+ ...transaction,
3164
+ account
3165
+ }, "signTransaction"),
3166
+ chainId: numberToHex(chainId),
3167
+ from: account.address
3168
+ }
3169
+ ]
3170
+ }, { retryCount: 0 });
3171
+ }
3172
+
3173
+ // node_modules/viem/_esm/actions/wallet/signTypedData.js
3174
+ async function signTypedData(client, parameters) {
3175
+ const { account: account_ = client.account, domain, message, primaryType } = parameters;
3176
+ if (!account_)
3177
+ throw new AccountNotFoundError({
3178
+ docsPath: "/docs/actions/wallet/signTypedData"
3179
+ });
3180
+ const account = parseAccount(account_);
3181
+ const types = {
3182
+ EIP712Domain: getTypesForEIP712Domain({ domain }),
3183
+ ...parameters.types
3184
+ };
3185
+ validateTypedData({ domain, message, primaryType, types });
3186
+ if (account.signTypedData)
3187
+ return account.signTypedData({ domain, message, primaryType, types });
3188
+ const typedData = serializeTypedData({ domain, message, primaryType, types });
3189
+ return client.request({
3190
+ method: "eth_signTypedData_v4",
3191
+ params: [account.address, typedData]
3192
+ }, { retryCount: 0 });
3193
+ }
3194
+
3195
+ // node_modules/viem/_esm/actions/wallet/switchChain.js
3196
+ async function switchChain(client, { id }) {
3197
+ await client.request({
3198
+ method: "wallet_switchEthereumChain",
3199
+ params: [
3200
+ {
3201
+ chainId: numberToHex(id)
3202
+ }
3203
+ ]
3204
+ }, { retryCount: 0 });
3205
+ }
3206
+
3207
+ // node_modules/viem/_esm/actions/wallet/watchAsset.js
3208
+ async function watchAsset(client, params) {
3209
+ const added = await client.request({
3210
+ method: "wallet_watchAsset",
3211
+ params
3212
+ }, { retryCount: 0 });
3213
+ return added;
3214
+ }
3215
+
3216
+ export {
3217
+ estimateContractGas,
3218
+ simulateContract,
3219
+ BundleFailedError,
3220
+ sendCalls,
3221
+ getCallsStatus,
3222
+ waitForCallsStatus,
3223
+ WaitForCallsStatusTimeoutError,
3224
+ namehash,
3225
+ labelhash,
3226
+ getEnsAddress,
3227
+ EnsAvatarInvalidNftUriError,
3228
+ EnsAvatarUriResolutionError,
3229
+ EnsAvatarUnsupportedNamespaceError,
3230
+ EnsInvalidChainIdError,
3231
+ getEnsText,
3232
+ getEnsAvatar,
3233
+ getEnsName,
3234
+ getEnsResolver,
3235
+ createAccessList,
3236
+ createBlockFilter,
3237
+ createEventFilter,
3238
+ createPendingTransactionFilter,
3239
+ getBalance,
3240
+ getBlobBaseFee,
3241
+ getBlockReceipts,
3242
+ getBlockTransactionCount,
3243
+ getDelegation,
3244
+ getEip712Domain,
3245
+ getFeeHistory,
3246
+ getFilterLogs,
3247
+ getProof,
3248
+ getRawTransaction,
3249
+ getStorageAt,
3250
+ getTransactionConfirmations,
3251
+ multicall,
3252
+ simulateBlocks,
3253
+ ethAddress,
3254
+ zeroAddress,
3255
+ simulateCalls,
3256
+ verifyMessage,
3257
+ verifyTypedData,
3258
+ watchBlocks,
3259
+ watchEvent,
3260
+ watchPendingTransactions,
3261
+ toAmount,
3262
+ toBaseUnits,
3263
+ resolveAmountDecimals,
3264
+ approve,
3265
+ approveSync,
3266
+ getAllowance,
3267
+ getBalance2,
3268
+ getMetadata,
3269
+ getTotalSupply,
3270
+ transfer,
3271
+ transferSync,
3272
+ token_exports,
3273
+ dropTransaction,
3274
+ dumpState,
3275
+ getAutomine,
3276
+ getTxpoolContent,
3277
+ getTxpoolStatus,
3278
+ impersonateAccount,
3279
+ increaseTime,
3280
+ inspectTxpool,
3281
+ loadState,
3282
+ mine,
3283
+ removeBlockTimestampInterval,
3284
+ reset,
3285
+ revert,
3286
+ sendUnsignedTransaction,
3287
+ setAutomine,
3288
+ setBalance,
3289
+ setBlockGasLimit,
3290
+ setBlockTimestampInterval,
3291
+ setCode,
3292
+ setCoinbase,
3293
+ setIntervalMining,
3294
+ setLoggingEnabled,
3295
+ setMinGasPrice,
3296
+ setNextBlockBaseFeePerGas,
3297
+ setNextBlockTimestamp,
3298
+ setNonce,
3299
+ setRpcUrl,
3300
+ setStorageAt,
3301
+ snapshot,
3302
+ stopImpersonatingAccount,
3303
+ addChain,
3304
+ deployContract,
3305
+ getAddresses,
3306
+ getCapabilities,
3307
+ getPermissions,
3308
+ prepareAuthorization,
3309
+ requestAddresses,
3310
+ requestPermissions,
3311
+ sendCallsSync,
3312
+ showCallsStatus,
3313
+ signAuthorization,
3314
+ signMessage,
3315
+ signTransaction,
3316
+ signTypedData,
3317
+ switchChain,
3318
+ watchAsset
3319
+ };