@kwespay/widget 1.0.8 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3085 @@
1
+ class KwesPayError extends Error {
2
+ constructor(message, code, cause) {
3
+ super(message);
4
+ this.name = "KwesPayError";
5
+ this.code = code;
6
+ this.cause = cause;
7
+ }
8
+ }
9
+
10
+ const ENDPOINT = "https://f433-154-161-230-28.ngrok-free.app/graphql";
11
+ const TESTNET_CONTRACTS = {
12
+ sepolia: "0xFC0A3A00008B79f080648A12FFb07dDE3C34F789",
13
+ baseSepolia: "0x8662EEA4eACCAef3e5c33c50Ac3a2b9B1B0033c7",
14
+ polygonAmoy: "0xc46E4D2005014990F600741A2Ce189f8118CB58e",
15
+ liskTestnet: "0xe0daD0d9e7413AA06859d26A552fD6a07855B070",
16
+ mezoTestnet: "0xa430B2e0D1273464809f8541286058e90781DA9C",
17
+ };
18
+ const MAINNET_CONTRACTS = {
19
+ // lisk: "0x...",
20
+ };
21
+ const CONTRACT_ADDRESSES = {
22
+ ...TESTNET_CONTRACTS,
23
+ ...MAINNET_CONTRACTS,
24
+ };
25
+ function resolveContractAddress(network) {
26
+ const addr = CONTRACT_ADDRESSES[network];
27
+ if (!addr)
28
+ throw new Error(`No contract deployed on network: ${network}`);
29
+ return addr;
30
+ }
31
+
32
+ async function gqlRequest(query, variables, apiKey) {
33
+ const headers = {
34
+ "Content-Type": "application/json",
35
+ };
36
+ if (apiKey)
37
+ headers["X-API-Key"] = apiKey;
38
+ let response;
39
+ try {
40
+ response = await fetch(ENDPOINT, {
41
+ method: "POST",
42
+ headers,
43
+ body: JSON.stringify({ query, variables }),
44
+ });
45
+ }
46
+ catch (err) {
47
+ throw new KwesPayError("Network request failed — check your connectivity", "NETWORK_ERROR", err);
48
+ }
49
+ if (!response.ok) {
50
+ throw new KwesPayError(`HTTP ${response.status}: ${response.statusText}`, "NETWORK_ERROR");
51
+ }
52
+ const json = await response.json();
53
+ if (json.errors?.length) {
54
+ throw new KwesPayError(json.errors[0]?.message ?? "GraphQL error", "UNKNOWN");
55
+ }
56
+ if (!json.data) {
57
+ throw new KwesPayError("Empty response from server", "UNKNOWN");
58
+ }
59
+ return json.data;
60
+ }
61
+
62
+ const GQL_VALIDATE_KEY = `
63
+ query ValidateAccessKey($accessKey: String!) {
64
+ validateAccessKey(accessKey: $accessKey) {
65
+ isValid
66
+ keyId
67
+ keyLabel
68
+ activeFlag
69
+ expirationDate
70
+ vendorInfo {
71
+ vendorPk
72
+ vendorIdentifier
73
+ businessName
74
+ }
75
+ allowedVendors
76
+ allowedNetworks
77
+ allowedTokens
78
+ error
79
+ }
80
+ }
81
+ `;
82
+ const GQL_CREATE_QUOTE = `
83
+ mutation CreateQuote($input: CreateQuoteInput!) {
84
+ createQuote(input: $input) {
85
+ success
86
+ message
87
+ quoteId
88
+ quoteReference
89
+ cryptoCurrency
90
+ tokenAddress
91
+ amountBaseUnits
92
+ displayAmount
93
+ network
94
+ chainId
95
+ expiresAt
96
+ }
97
+ }
98
+ `;
99
+ // deadline is NOT queried — derived from expiresAt (same point in time, Unix int).
100
+ // Add `deadline` back here after the backend schema is regenerated with the
101
+ // updated BlockchainTransactionResponse type.
102
+ const GQL_CREATE_TRANSACTION = `
103
+ mutation CreateTransaction($input: CreateTransactionInput!) {
104
+ createTransaction(input: $input) {
105
+ success
106
+ message
107
+ paymentIdBytes32
108
+ backendSignature
109
+ tokenAddress
110
+ amountBaseUnits
111
+ chainId
112
+ expiresAt
113
+ transaction {
114
+ transactionReference
115
+ transactionStatus
116
+ }
117
+ }
118
+ }
119
+ `;
120
+ const GQL_TRANSACTION_STATUS = `
121
+ query GetTransactionStatus($transactionReference: String!) {
122
+ getTransactionStatus(transactionReference: $transactionReference) {
123
+ transactionReference
124
+ transactionStatus
125
+ blockchainHash
126
+ blockchainNetwork
127
+ displayAmount
128
+ cryptoCurrency
129
+ payerWalletAddress
130
+ initiatedAt
131
+ }
132
+ }
133
+ `;
134
+
135
+ const version$1 = '1.2.3';
136
+
137
+ let BaseError$1 = class BaseError extends Error {
138
+ constructor(shortMessage, args = {}) {
139
+ const details = args.cause instanceof BaseError
140
+ ? args.cause.details
141
+ : args.cause?.message
142
+ ? args.cause.message
143
+ : args.details;
144
+ const docsPath = args.cause instanceof BaseError
145
+ ? args.cause.docsPath || args.docsPath
146
+ : args.docsPath;
147
+ const message = [
148
+ shortMessage || 'An error occurred.',
149
+ '',
150
+ ...(args.metaMessages ? [...args.metaMessages, ''] : []),
151
+ ...(docsPath ? [`Docs: https://abitype.dev${docsPath}`] : []),
152
+ ...(details ? [`Details: ${details}`] : []),
153
+ `Version: abitype@${version$1}`,
154
+ ].join('\n');
155
+ super(message);
156
+ Object.defineProperty(this, "details", {
157
+ enumerable: true,
158
+ configurable: true,
159
+ writable: true,
160
+ value: void 0
161
+ });
162
+ Object.defineProperty(this, "docsPath", {
163
+ enumerable: true,
164
+ configurable: true,
165
+ writable: true,
166
+ value: void 0
167
+ });
168
+ Object.defineProperty(this, "metaMessages", {
169
+ enumerable: true,
170
+ configurable: true,
171
+ writable: true,
172
+ value: void 0
173
+ });
174
+ Object.defineProperty(this, "shortMessage", {
175
+ enumerable: true,
176
+ configurable: true,
177
+ writable: true,
178
+ value: void 0
179
+ });
180
+ Object.defineProperty(this, "name", {
181
+ enumerable: true,
182
+ configurable: true,
183
+ writable: true,
184
+ value: 'AbiTypeError'
185
+ });
186
+ if (args.cause)
187
+ this.cause = args.cause;
188
+ this.details = details;
189
+ this.docsPath = docsPath;
190
+ this.metaMessages = args.metaMessages;
191
+ this.shortMessage = shortMessage;
192
+ }
193
+ };
194
+
195
+ // TODO: This looks cool. Need to check the performance of `new RegExp` versus defined inline though.
196
+ // https://twitter.com/GabrielVergnaud/status/1622906834343366657
197
+ function execTyped(regex, string) {
198
+ const match = regex.exec(string);
199
+ return match?.groups;
200
+ }
201
+ // `bytes<M>`: binary type of `M` bytes, `0 < M <= 32`
202
+ // https://regexr.com/6va55
203
+ const bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;
204
+ // `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`
205
+ // https://regexr.com/6v8hp
206
+ const integerRegex$1 = /^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;
207
+ const isTupleRegex = /^\(.+?\).*?$/;
208
+
209
+ // https://regexr.com/7f7rv
210
+ const tupleRegex = /^tuple(?<array>(\[(\d*)\])*)$/;
211
+ /**
212
+ * Formats {@link AbiParameter} to human-readable ABI parameter.
213
+ *
214
+ * @param abiParameter - ABI parameter
215
+ * @returns Human-readable ABI parameter
216
+ *
217
+ * @example
218
+ * const result = formatAbiParameter({ type: 'address', name: 'from' })
219
+ * // ^? const result: 'address from'
220
+ */
221
+ function formatAbiParameter(abiParameter) {
222
+ let type = abiParameter.type;
223
+ if (tupleRegex.test(abiParameter.type) && 'components' in abiParameter) {
224
+ type = '(';
225
+ const length = abiParameter.components.length;
226
+ for (let i = 0; i < length; i++) {
227
+ const component = abiParameter.components[i];
228
+ type += formatAbiParameter(component);
229
+ if (i < length - 1)
230
+ type += ', ';
231
+ }
232
+ const result = execTyped(tupleRegex, abiParameter.type);
233
+ type += `)${result?.array || ''}`;
234
+ return formatAbiParameter({
235
+ ...abiParameter,
236
+ type,
237
+ });
238
+ }
239
+ // Add `indexed` to type if in `abiParameter`
240
+ if ('indexed' in abiParameter && abiParameter.indexed)
241
+ type = `${type} indexed`;
242
+ // Return human-readable ABI parameter
243
+ if (abiParameter.name)
244
+ return `${type} ${abiParameter.name}`;
245
+ return type;
246
+ }
247
+
248
+ /**
249
+ * Formats {@link AbiParameter}s to human-readable ABI parameters.
250
+ *
251
+ * @param abiParameters - ABI parameters
252
+ * @returns Human-readable ABI parameters
253
+ *
254
+ * @example
255
+ * const result = formatAbiParameters([
256
+ * // ^? const result: 'address from, uint256 tokenId'
257
+ * { type: 'address', name: 'from' },
258
+ * { type: 'uint256', name: 'tokenId' },
259
+ * ])
260
+ */
261
+ function formatAbiParameters(abiParameters) {
262
+ let params = '';
263
+ const length = abiParameters.length;
264
+ for (let i = 0; i < length; i++) {
265
+ const abiParameter = abiParameters[i];
266
+ params += formatAbiParameter(abiParameter);
267
+ if (i !== length - 1)
268
+ params += ', ';
269
+ }
270
+ return params;
271
+ }
272
+
273
+ /**
274
+ * Formats ABI item (e.g. error, event, function) into human-readable ABI item
275
+ *
276
+ * @param abiItem - ABI item
277
+ * @returns Human-readable ABI item
278
+ */
279
+ function formatAbiItem$1(abiItem) {
280
+ if (abiItem.type === 'function')
281
+ return `function ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability && abiItem.stateMutability !== 'nonpayable'
282
+ ? ` ${abiItem.stateMutability}`
283
+ : ''}${abiItem.outputs?.length
284
+ ? ` returns (${formatAbiParameters(abiItem.outputs)})`
285
+ : ''}`;
286
+ if (abiItem.type === 'event')
287
+ return `event ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`;
288
+ if (abiItem.type === 'error')
289
+ return `error ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`;
290
+ if (abiItem.type === 'constructor')
291
+ return `constructor(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability === 'payable' ? ' payable' : ''}`;
292
+ if (abiItem.type === 'fallback')
293
+ return `fallback() external${abiItem.stateMutability === 'payable' ? ' payable' : ''}`;
294
+ return 'receive() external payable';
295
+ }
296
+
297
+ // https://regexr.com/7gmok
298
+ const errorSignatureRegex = /^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;
299
+ function isErrorSignature(signature) {
300
+ return errorSignatureRegex.test(signature);
301
+ }
302
+ function execErrorSignature(signature) {
303
+ return execTyped(errorSignatureRegex, signature);
304
+ }
305
+ // https://regexr.com/7gmoq
306
+ const eventSignatureRegex = /^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;
307
+ function isEventSignature(signature) {
308
+ return eventSignatureRegex.test(signature);
309
+ }
310
+ function execEventSignature(signature) {
311
+ return execTyped(eventSignatureRegex, signature);
312
+ }
313
+ // https://regexr.com/7gmot
314
+ const functionSignatureRegex = /^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;
315
+ function isFunctionSignature(signature) {
316
+ return functionSignatureRegex.test(signature);
317
+ }
318
+ function execFunctionSignature(signature) {
319
+ return execTyped(functionSignatureRegex, signature);
320
+ }
321
+ // https://regexr.com/7gmp3
322
+ const structSignatureRegex = /^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;
323
+ function isStructSignature(signature) {
324
+ return structSignatureRegex.test(signature);
325
+ }
326
+ function execStructSignature(signature) {
327
+ return execTyped(structSignatureRegex, signature);
328
+ }
329
+ // https://regexr.com/78u01
330
+ const constructorSignatureRegex = /^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;
331
+ function isConstructorSignature(signature) {
332
+ return constructorSignatureRegex.test(signature);
333
+ }
334
+ function execConstructorSignature(signature) {
335
+ return execTyped(constructorSignatureRegex, signature);
336
+ }
337
+ // https://regexr.com/7srtn
338
+ const fallbackSignatureRegex = /^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;
339
+ function isFallbackSignature(signature) {
340
+ return fallbackSignatureRegex.test(signature);
341
+ }
342
+ function execFallbackSignature(signature) {
343
+ return execTyped(fallbackSignatureRegex, signature);
344
+ }
345
+ // https://regexr.com/78u1k
346
+ const receiveSignatureRegex = /^receive\(\) external payable$/;
347
+ function isReceiveSignature(signature) {
348
+ return receiveSignatureRegex.test(signature);
349
+ }
350
+ const eventModifiers = new Set(['indexed']);
351
+ const functionModifiers = new Set([
352
+ 'calldata',
353
+ 'memory',
354
+ 'storage',
355
+ ]);
356
+
357
+ class UnknownTypeError extends BaseError$1 {
358
+ constructor({ type }) {
359
+ super('Unknown type.', {
360
+ metaMessages: [
361
+ `Type "${type}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`,
362
+ ],
363
+ });
364
+ Object.defineProperty(this, "name", {
365
+ enumerable: true,
366
+ configurable: true,
367
+ writable: true,
368
+ value: 'UnknownTypeError'
369
+ });
370
+ }
371
+ }
372
+ class UnknownSolidityTypeError extends BaseError$1 {
373
+ constructor({ type }) {
374
+ super('Unknown type.', {
375
+ metaMessages: [`Type "${type}" is not a valid ABI type.`],
376
+ });
377
+ Object.defineProperty(this, "name", {
378
+ enumerable: true,
379
+ configurable: true,
380
+ writable: true,
381
+ value: 'UnknownSolidityTypeError'
382
+ });
383
+ }
384
+ }
385
+
386
+ class InvalidParameterError extends BaseError$1 {
387
+ constructor({ param }) {
388
+ super('Invalid ABI parameter.', {
389
+ details: param,
390
+ });
391
+ Object.defineProperty(this, "name", {
392
+ enumerable: true,
393
+ configurable: true,
394
+ writable: true,
395
+ value: 'InvalidParameterError'
396
+ });
397
+ }
398
+ }
399
+ class SolidityProtectedKeywordError extends BaseError$1 {
400
+ constructor({ param, name }) {
401
+ super('Invalid ABI parameter.', {
402
+ details: param,
403
+ metaMessages: [
404
+ `"${name}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`,
405
+ ],
406
+ });
407
+ Object.defineProperty(this, "name", {
408
+ enumerable: true,
409
+ configurable: true,
410
+ writable: true,
411
+ value: 'SolidityProtectedKeywordError'
412
+ });
413
+ }
414
+ }
415
+ class InvalidModifierError extends BaseError$1 {
416
+ constructor({ param, type, modifier, }) {
417
+ super('Invalid ABI parameter.', {
418
+ details: param,
419
+ metaMessages: [
420
+ `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ''}.`,
421
+ ],
422
+ });
423
+ Object.defineProperty(this, "name", {
424
+ enumerable: true,
425
+ configurable: true,
426
+ writable: true,
427
+ value: 'InvalidModifierError'
428
+ });
429
+ }
430
+ }
431
+ class InvalidFunctionModifierError extends BaseError$1 {
432
+ constructor({ param, type, modifier, }) {
433
+ super('Invalid ABI parameter.', {
434
+ details: param,
435
+ metaMessages: [
436
+ `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ''}.`,
437
+ `Data location can only be specified for array, struct, or mapping types, but "${modifier}" was given.`,
438
+ ],
439
+ });
440
+ Object.defineProperty(this, "name", {
441
+ enumerable: true,
442
+ configurable: true,
443
+ writable: true,
444
+ value: 'InvalidFunctionModifierError'
445
+ });
446
+ }
447
+ }
448
+ class InvalidAbiTypeParameterError extends BaseError$1 {
449
+ constructor({ abiParameter, }) {
450
+ super('Invalid ABI parameter.', {
451
+ details: JSON.stringify(abiParameter, null, 2),
452
+ metaMessages: ['ABI parameter type is invalid.'],
453
+ });
454
+ Object.defineProperty(this, "name", {
455
+ enumerable: true,
456
+ configurable: true,
457
+ writable: true,
458
+ value: 'InvalidAbiTypeParameterError'
459
+ });
460
+ }
461
+ }
462
+
463
+ class InvalidSignatureError extends BaseError$1 {
464
+ constructor({ signature, type, }) {
465
+ super(`Invalid ${type} signature.`, {
466
+ details: signature,
467
+ });
468
+ Object.defineProperty(this, "name", {
469
+ enumerable: true,
470
+ configurable: true,
471
+ writable: true,
472
+ value: 'InvalidSignatureError'
473
+ });
474
+ }
475
+ }
476
+ class UnknownSignatureError extends BaseError$1 {
477
+ constructor({ signature }) {
478
+ super('Unknown signature.', {
479
+ details: signature,
480
+ });
481
+ Object.defineProperty(this, "name", {
482
+ enumerable: true,
483
+ configurable: true,
484
+ writable: true,
485
+ value: 'UnknownSignatureError'
486
+ });
487
+ }
488
+ }
489
+ class InvalidStructSignatureError extends BaseError$1 {
490
+ constructor({ signature }) {
491
+ super('Invalid struct signature.', {
492
+ details: signature,
493
+ metaMessages: ['No properties exist.'],
494
+ });
495
+ Object.defineProperty(this, "name", {
496
+ enumerable: true,
497
+ configurable: true,
498
+ writable: true,
499
+ value: 'InvalidStructSignatureError'
500
+ });
501
+ }
502
+ }
503
+
504
+ class CircularReferenceError extends BaseError$1 {
505
+ constructor({ type }) {
506
+ super('Circular reference detected.', {
507
+ metaMessages: [`Struct "${type}" is a circular reference.`],
508
+ });
509
+ Object.defineProperty(this, "name", {
510
+ enumerable: true,
511
+ configurable: true,
512
+ writable: true,
513
+ value: 'CircularReferenceError'
514
+ });
515
+ }
516
+ }
517
+
518
+ class InvalidParenthesisError extends BaseError$1 {
519
+ constructor({ current, depth }) {
520
+ super('Unbalanced parentheses.', {
521
+ metaMessages: [
522
+ `"${current.trim()}" has too many ${depth > 0 ? 'opening' : 'closing'} parentheses.`,
523
+ ],
524
+ details: `Depth "${depth}"`,
525
+ });
526
+ Object.defineProperty(this, "name", {
527
+ enumerable: true,
528
+ configurable: true,
529
+ writable: true,
530
+ value: 'InvalidParenthesisError'
531
+ });
532
+ }
533
+ }
534
+
535
+ /**
536
+ * Gets {@link parameterCache} cache key namespaced by {@link type} and {@link structs}. This prevents parameters from being accessible to types that don't allow them (e.g. `string indexed foo` not allowed outside of `type: 'event'`) and ensures different struct definitions with the same name are cached separately.
537
+ * @param param ABI parameter string
538
+ * @param type ABI parameter type
539
+ * @param structs Struct definitions to include in cache key
540
+ * @returns Cache key for {@link parameterCache}
541
+ */
542
+ function getParameterCacheKey(param, type, structs) {
543
+ let structKey = '';
544
+ if (structs)
545
+ for (const struct of Object.entries(structs)) {
546
+ if (!struct)
547
+ continue;
548
+ let propertyKey = '';
549
+ for (const property of struct[1]) {
550
+ propertyKey += `[${property.type}${property.name ? `:${property.name}` : ''}]`;
551
+ }
552
+ structKey += `(${struct[0]}{${propertyKey}})`;
553
+ }
554
+ if (type)
555
+ return `${type}:${param}${structKey}`;
556
+ return `${param}${structKey}`;
557
+ }
558
+ /**
559
+ * Basic cache seeded with common ABI parameter strings.
560
+ *
561
+ * **Note: When seeding more parameters, make sure you benchmark performance. The current number is the ideal balance between performance and having an already existing cache.**
562
+ */
563
+ const parameterCache = new Map([
564
+ // Unnamed
565
+ ['address', { type: 'address' }],
566
+ ['bool', { type: 'bool' }],
567
+ ['bytes', { type: 'bytes' }],
568
+ ['bytes32', { type: 'bytes32' }],
569
+ ['int', { type: 'int256' }],
570
+ ['int256', { type: 'int256' }],
571
+ ['string', { type: 'string' }],
572
+ ['uint', { type: 'uint256' }],
573
+ ['uint8', { type: 'uint8' }],
574
+ ['uint16', { type: 'uint16' }],
575
+ ['uint24', { type: 'uint24' }],
576
+ ['uint32', { type: 'uint32' }],
577
+ ['uint64', { type: 'uint64' }],
578
+ ['uint96', { type: 'uint96' }],
579
+ ['uint112', { type: 'uint112' }],
580
+ ['uint160', { type: 'uint160' }],
581
+ ['uint192', { type: 'uint192' }],
582
+ ['uint256', { type: 'uint256' }],
583
+ // Named
584
+ ['address owner', { type: 'address', name: 'owner' }],
585
+ ['address to', { type: 'address', name: 'to' }],
586
+ ['bool approved', { type: 'bool', name: 'approved' }],
587
+ ['bytes _data', { type: 'bytes', name: '_data' }],
588
+ ['bytes data', { type: 'bytes', name: 'data' }],
589
+ ['bytes signature', { type: 'bytes', name: 'signature' }],
590
+ ['bytes32 hash', { type: 'bytes32', name: 'hash' }],
591
+ ['bytes32 r', { type: 'bytes32', name: 'r' }],
592
+ ['bytes32 root', { type: 'bytes32', name: 'root' }],
593
+ ['bytes32 s', { type: 'bytes32', name: 's' }],
594
+ ['string name', { type: 'string', name: 'name' }],
595
+ ['string symbol', { type: 'string', name: 'symbol' }],
596
+ ['string tokenURI', { type: 'string', name: 'tokenURI' }],
597
+ ['uint tokenId', { type: 'uint256', name: 'tokenId' }],
598
+ ['uint8 v', { type: 'uint8', name: 'v' }],
599
+ ['uint256 balance', { type: 'uint256', name: 'balance' }],
600
+ ['uint256 tokenId', { type: 'uint256', name: 'tokenId' }],
601
+ ['uint256 value', { type: 'uint256', name: 'value' }],
602
+ // Indexed
603
+ [
604
+ 'event:address indexed from',
605
+ { type: 'address', name: 'from', indexed: true },
606
+ ],
607
+ ['event:address indexed to', { type: 'address', name: 'to', indexed: true }],
608
+ [
609
+ 'event:uint indexed tokenId',
610
+ { type: 'uint256', name: 'tokenId', indexed: true },
611
+ ],
612
+ [
613
+ 'event:uint256 indexed tokenId',
614
+ { type: 'uint256', name: 'tokenId', indexed: true },
615
+ ],
616
+ ]);
617
+
618
+ function parseSignature(signature, structs = {}) {
619
+ if (isFunctionSignature(signature))
620
+ return parseFunctionSignature(signature, structs);
621
+ if (isEventSignature(signature))
622
+ return parseEventSignature(signature, structs);
623
+ if (isErrorSignature(signature))
624
+ return parseErrorSignature(signature, structs);
625
+ if (isConstructorSignature(signature))
626
+ return parseConstructorSignature(signature, structs);
627
+ if (isFallbackSignature(signature))
628
+ return parseFallbackSignature(signature);
629
+ if (isReceiveSignature(signature))
630
+ return {
631
+ type: 'receive',
632
+ stateMutability: 'payable',
633
+ };
634
+ throw new UnknownSignatureError({ signature });
635
+ }
636
+ function parseFunctionSignature(signature, structs = {}) {
637
+ const match = execFunctionSignature(signature);
638
+ if (!match)
639
+ throw new InvalidSignatureError({ signature, type: 'function' });
640
+ const inputParams = splitParameters(match.parameters);
641
+ const inputs = [];
642
+ const inputLength = inputParams.length;
643
+ for (let i = 0; i < inputLength; i++) {
644
+ inputs.push(parseAbiParameter(inputParams[i], {
645
+ modifiers: functionModifiers,
646
+ structs,
647
+ type: 'function',
648
+ }));
649
+ }
650
+ const outputs = [];
651
+ if (match.returns) {
652
+ const outputParams = splitParameters(match.returns);
653
+ const outputLength = outputParams.length;
654
+ for (let i = 0; i < outputLength; i++) {
655
+ outputs.push(parseAbiParameter(outputParams[i], {
656
+ modifiers: functionModifiers,
657
+ structs,
658
+ type: 'function',
659
+ }));
660
+ }
661
+ }
662
+ return {
663
+ name: match.name,
664
+ type: 'function',
665
+ stateMutability: match.stateMutability ?? 'nonpayable',
666
+ inputs,
667
+ outputs,
668
+ };
669
+ }
670
+ function parseEventSignature(signature, structs = {}) {
671
+ const match = execEventSignature(signature);
672
+ if (!match)
673
+ throw new InvalidSignatureError({ signature, type: 'event' });
674
+ const params = splitParameters(match.parameters);
675
+ const abiParameters = [];
676
+ const length = params.length;
677
+ for (let i = 0; i < length; i++)
678
+ abiParameters.push(parseAbiParameter(params[i], {
679
+ modifiers: eventModifiers,
680
+ structs,
681
+ type: 'event',
682
+ }));
683
+ return { name: match.name, type: 'event', inputs: abiParameters };
684
+ }
685
+ function parseErrorSignature(signature, structs = {}) {
686
+ const match = execErrorSignature(signature);
687
+ if (!match)
688
+ throw new InvalidSignatureError({ signature, type: 'error' });
689
+ const params = splitParameters(match.parameters);
690
+ const abiParameters = [];
691
+ const length = params.length;
692
+ for (let i = 0; i < length; i++)
693
+ abiParameters.push(parseAbiParameter(params[i], { structs, type: 'error' }));
694
+ return { name: match.name, type: 'error', inputs: abiParameters };
695
+ }
696
+ function parseConstructorSignature(signature, structs = {}) {
697
+ const match = execConstructorSignature(signature);
698
+ if (!match)
699
+ throw new InvalidSignatureError({ signature, type: 'constructor' });
700
+ const params = splitParameters(match.parameters);
701
+ const abiParameters = [];
702
+ const length = params.length;
703
+ for (let i = 0; i < length; i++)
704
+ abiParameters.push(parseAbiParameter(params[i], { structs, type: 'constructor' }));
705
+ return {
706
+ type: 'constructor',
707
+ stateMutability: match.stateMutability ?? 'nonpayable',
708
+ inputs: abiParameters,
709
+ };
710
+ }
711
+ function parseFallbackSignature(signature) {
712
+ const match = execFallbackSignature(signature);
713
+ if (!match)
714
+ throw new InvalidSignatureError({ signature, type: 'fallback' });
715
+ return {
716
+ type: 'fallback',
717
+ stateMutability: match.stateMutability ?? 'nonpayable',
718
+ };
719
+ }
720
+ const abiParameterWithoutTupleRegex = /^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/;
721
+ const abiParameterWithTupleRegex = /^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/;
722
+ const dynamicIntegerRegex = /^u?int$/;
723
+ function parseAbiParameter(param, options) {
724
+ // optional namespace cache by `type`
725
+ const parameterCacheKey = getParameterCacheKey(param, options?.type, options?.structs);
726
+ if (parameterCache.has(parameterCacheKey))
727
+ return parameterCache.get(parameterCacheKey);
728
+ const isTuple = isTupleRegex.test(param);
729
+ const match = execTyped(isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex, param);
730
+ if (!match)
731
+ throw new InvalidParameterError({ param });
732
+ if (match.name && isSolidityKeyword(match.name))
733
+ throw new SolidityProtectedKeywordError({ param, name: match.name });
734
+ const name = match.name ? { name: match.name } : {};
735
+ const indexed = match.modifier === 'indexed' ? { indexed: true } : {};
736
+ const structs = options?.structs ?? {};
737
+ let type;
738
+ let components = {};
739
+ if (isTuple) {
740
+ type = 'tuple';
741
+ const params = splitParameters(match.type);
742
+ const components_ = [];
743
+ const length = params.length;
744
+ for (let i = 0; i < length; i++) {
745
+ // remove `modifiers` from `options` to prevent from being added to tuple components
746
+ components_.push(parseAbiParameter(params[i], { structs }));
747
+ }
748
+ components = { components: components_ };
749
+ }
750
+ else if (match.type in structs) {
751
+ type = 'tuple';
752
+ components = { components: structs[match.type] };
753
+ }
754
+ else if (dynamicIntegerRegex.test(match.type)) {
755
+ type = `${match.type}256`;
756
+ }
757
+ else if (match.type === 'address payable') {
758
+ type = 'address';
759
+ }
760
+ else {
761
+ type = match.type;
762
+ if (!(options?.type === 'struct') && !isSolidityType(type))
763
+ throw new UnknownSolidityTypeError({ type });
764
+ }
765
+ if (match.modifier) {
766
+ // Check if modifier exists, but is not allowed (e.g. `indexed` in `functionModifiers`)
767
+ if (!options?.modifiers?.has?.(match.modifier))
768
+ throw new InvalidModifierError({
769
+ param,
770
+ type: options?.type,
771
+ modifier: match.modifier,
772
+ });
773
+ // Check if resolved `type` is valid if there is a function modifier
774
+ if (functionModifiers.has(match.modifier) &&
775
+ !isValidDataLocation(type, !!match.array))
776
+ throw new InvalidFunctionModifierError({
777
+ param,
778
+ type: options?.type,
779
+ modifier: match.modifier,
780
+ });
781
+ }
782
+ const abiParameter = {
783
+ type: `${type}${match.array ?? ''}`,
784
+ ...name,
785
+ ...indexed,
786
+ ...components,
787
+ };
788
+ parameterCache.set(parameterCacheKey, abiParameter);
789
+ return abiParameter;
790
+ }
791
+ // s/o latika for this
792
+ function splitParameters(params, result = [], current = '', depth = 0) {
793
+ const length = params.trim().length;
794
+ // biome-ignore lint/correctness/noUnreachable: recursive
795
+ for (let i = 0; i < length; i++) {
796
+ const char = params[i];
797
+ const tail = params.slice(i + 1);
798
+ switch (char) {
799
+ case ',':
800
+ return depth === 0
801
+ ? splitParameters(tail, [...result, current.trim()])
802
+ : splitParameters(tail, result, `${current}${char}`, depth);
803
+ case '(':
804
+ return splitParameters(tail, result, `${current}${char}`, depth + 1);
805
+ case ')':
806
+ return splitParameters(tail, result, `${current}${char}`, depth - 1);
807
+ default:
808
+ return splitParameters(tail, result, `${current}${char}`, depth);
809
+ }
810
+ }
811
+ if (current === '')
812
+ return result;
813
+ if (depth !== 0)
814
+ throw new InvalidParenthesisError({ current, depth });
815
+ result.push(current.trim());
816
+ return result;
817
+ }
818
+ function isSolidityType(type) {
819
+ return (type === 'address' ||
820
+ type === 'bool' ||
821
+ type === 'function' ||
822
+ type === 'string' ||
823
+ bytesRegex.test(type) ||
824
+ integerRegex$1.test(type));
825
+ }
826
+ const protectedKeywordsRegex = /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;
827
+ /** @internal */
828
+ function isSolidityKeyword(name) {
829
+ return (name === 'address' ||
830
+ name === 'bool' ||
831
+ name === 'function' ||
832
+ name === 'string' ||
833
+ name === 'tuple' ||
834
+ bytesRegex.test(name) ||
835
+ integerRegex$1.test(name) ||
836
+ protectedKeywordsRegex.test(name));
837
+ }
838
+ /** @internal */
839
+ function isValidDataLocation(type, isArray) {
840
+ return isArray || type === 'bytes' || type === 'string' || type === 'tuple';
841
+ }
842
+
843
+ function parseStructs(signatures) {
844
+ // Create "shallow" version of each struct (and filter out non-structs or invalid structs)
845
+ const shallowStructs = {};
846
+ const signaturesLength = signatures.length;
847
+ for (let i = 0; i < signaturesLength; i++) {
848
+ const signature = signatures[i];
849
+ if (!isStructSignature(signature))
850
+ continue;
851
+ const match = execStructSignature(signature);
852
+ if (!match)
853
+ throw new InvalidSignatureError({ signature, type: 'struct' });
854
+ const properties = match.properties.split(';');
855
+ const components = [];
856
+ const propertiesLength = properties.length;
857
+ for (let k = 0; k < propertiesLength; k++) {
858
+ const property = properties[k];
859
+ const trimmed = property.trim();
860
+ if (!trimmed)
861
+ continue;
862
+ const abiParameter = parseAbiParameter(trimmed, {
863
+ type: 'struct',
864
+ });
865
+ components.push(abiParameter);
866
+ }
867
+ if (!components.length)
868
+ throw new InvalidStructSignatureError({ signature });
869
+ shallowStructs[match.name] = components;
870
+ }
871
+ // Resolve nested structs inside each parameter
872
+ const resolvedStructs = {};
873
+ const entries = Object.entries(shallowStructs);
874
+ const entriesLength = entries.length;
875
+ for (let i = 0; i < entriesLength; i++) {
876
+ const [name, parameters] = entries[i];
877
+ resolvedStructs[name] = resolveStructs(parameters, shallowStructs);
878
+ }
879
+ return resolvedStructs;
880
+ }
881
+ const typeWithoutTupleRegex = /^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;
882
+ function resolveStructs(abiParameters = [], structs = {}, ancestors = new Set()) {
883
+ const components = [];
884
+ const length = abiParameters.length;
885
+ for (let i = 0; i < length; i++) {
886
+ const abiParameter = abiParameters[i];
887
+ const isTuple = isTupleRegex.test(abiParameter.type);
888
+ if (isTuple)
889
+ components.push(abiParameter);
890
+ else {
891
+ const match = execTyped(typeWithoutTupleRegex, abiParameter.type);
892
+ if (!match?.type)
893
+ throw new InvalidAbiTypeParameterError({ abiParameter });
894
+ const { array, type } = match;
895
+ if (type in structs) {
896
+ if (ancestors.has(type))
897
+ throw new CircularReferenceError({ type });
898
+ components.push({
899
+ ...abiParameter,
900
+ type: `tuple${array ?? ''}`,
901
+ components: resolveStructs(structs[type], structs, new Set([...ancestors, type])),
902
+ });
903
+ }
904
+ else {
905
+ if (isSolidityType(type))
906
+ components.push(abiParameter);
907
+ else
908
+ throw new UnknownTypeError({ type });
909
+ }
910
+ }
911
+ }
912
+ return components;
913
+ }
914
+
915
+ /**
916
+ * Parses human-readable ABI into JSON {@link Abi}
917
+ *
918
+ * @param signatures - Human-Readable ABI
919
+ * @returns Parsed {@link Abi}
920
+ *
921
+ * @example
922
+ * const abi = parseAbi([
923
+ * // ^? const abi: readonly [{ name: "balanceOf"; type: "function"; stateMutability:...
924
+ * 'function balanceOf(address owner) view returns (uint256)',
925
+ * 'event Transfer(address indexed from, address indexed to, uint256 amount)',
926
+ * ])
927
+ */
928
+ function parseAbi(signatures) {
929
+ const structs = parseStructs(signatures);
930
+ const abi = [];
931
+ const length = signatures.length;
932
+ for (let i = 0; i < length; i++) {
933
+ const signature = signatures[i];
934
+ if (isStructSignature(signature))
935
+ continue;
936
+ abi.push(parseSignature(signature, structs));
937
+ }
938
+ return abi;
939
+ }
940
+
941
+ function formatAbiItem(abiItem, { includeName = false } = {}) {
942
+ if (abiItem.type !== 'function' &&
943
+ abiItem.type !== 'event' &&
944
+ abiItem.type !== 'error')
945
+ throw new InvalidDefinitionTypeError(abiItem.type);
946
+ return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`;
947
+ }
948
+ function formatAbiParams(params, { includeName = false } = {}) {
949
+ if (!params)
950
+ return '';
951
+ return params
952
+ .map((param) => formatAbiParam(param, { includeName }))
953
+ .join(includeName ? ', ' : ',');
954
+ }
955
+ function formatAbiParam(param, { includeName }) {
956
+ if (param.type.startsWith('tuple')) {
957
+ return `(${formatAbiParams(param.components, { includeName })})${param.type.slice('tuple'.length)}`;
958
+ }
959
+ return param.type + (includeName && param.name ? ` ${param.name}` : '');
960
+ }
961
+
962
+ function isHex(value, { strict = true } = {}) {
963
+ if (!value)
964
+ return false;
965
+ if (typeof value !== 'string')
966
+ return false;
967
+ return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith('0x');
968
+ }
969
+
970
+ /**
971
+ * @description Retrieves the size of the value (in bytes).
972
+ *
973
+ * @param value The value (hex or byte array) to retrieve the size of.
974
+ * @returns The size of the value (in bytes).
975
+ */
976
+ function size(value) {
977
+ if (isHex(value, { strict: false }))
978
+ return Math.ceil((value.length - 2) / 2);
979
+ return value.length;
980
+ }
981
+
982
+ const version = '2.47.10';
983
+
984
+ let errorConfig = {
985
+ getDocsUrl: ({ docsBaseUrl, docsPath = '', docsSlug, }) => docsPath
986
+ ? `${docsBaseUrl ?? 'https://viem.sh'}${docsPath}${docsSlug ? `#${docsSlug}` : ''}`
987
+ : undefined,
988
+ version: `viem@${version}`,
989
+ };
990
+ class BaseError extends Error {
991
+ constructor(shortMessage, args = {}) {
992
+ const details = (() => {
993
+ if (args.cause instanceof BaseError)
994
+ return args.cause.details;
995
+ if (args.cause?.message)
996
+ return args.cause.message;
997
+ return args.details;
998
+ })();
999
+ const docsPath = (() => {
1000
+ if (args.cause instanceof BaseError)
1001
+ return args.cause.docsPath || args.docsPath;
1002
+ return args.docsPath;
1003
+ })();
1004
+ const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath });
1005
+ const message = [
1006
+ shortMessage || 'An error occurred.',
1007
+ '',
1008
+ ...(args.metaMessages ? [...args.metaMessages, ''] : []),
1009
+ ...(docsUrl ? [`Docs: ${docsUrl}`] : []),
1010
+ ...(details ? [`Details: ${details}`] : []),
1011
+ ...(errorConfig.version ? [`Version: ${errorConfig.version}`] : []),
1012
+ ].join('\n');
1013
+ super(message, args.cause ? { cause: args.cause } : undefined);
1014
+ Object.defineProperty(this, "details", {
1015
+ enumerable: true,
1016
+ configurable: true,
1017
+ writable: true,
1018
+ value: void 0
1019
+ });
1020
+ Object.defineProperty(this, "docsPath", {
1021
+ enumerable: true,
1022
+ configurable: true,
1023
+ writable: true,
1024
+ value: void 0
1025
+ });
1026
+ Object.defineProperty(this, "metaMessages", {
1027
+ enumerable: true,
1028
+ configurable: true,
1029
+ writable: true,
1030
+ value: void 0
1031
+ });
1032
+ Object.defineProperty(this, "shortMessage", {
1033
+ enumerable: true,
1034
+ configurable: true,
1035
+ writable: true,
1036
+ value: void 0
1037
+ });
1038
+ Object.defineProperty(this, "version", {
1039
+ enumerable: true,
1040
+ configurable: true,
1041
+ writable: true,
1042
+ value: void 0
1043
+ });
1044
+ Object.defineProperty(this, "name", {
1045
+ enumerable: true,
1046
+ configurable: true,
1047
+ writable: true,
1048
+ value: 'BaseError'
1049
+ });
1050
+ this.details = details;
1051
+ this.docsPath = docsPath;
1052
+ this.metaMessages = args.metaMessages;
1053
+ this.name = args.name ?? this.name;
1054
+ this.shortMessage = shortMessage;
1055
+ this.version = version;
1056
+ }
1057
+ walk(fn) {
1058
+ return walk(this, fn);
1059
+ }
1060
+ }
1061
+ function walk(err, fn) {
1062
+ if (fn?.(err))
1063
+ return err;
1064
+ if (err &&
1065
+ typeof err === 'object' &&
1066
+ 'cause' in err &&
1067
+ err.cause !== undefined)
1068
+ return walk(err.cause, fn);
1069
+ return fn ? null : err;
1070
+ }
1071
+
1072
+ class AbiEncodingArrayLengthMismatchError extends BaseError {
1073
+ constructor({ expectedLength, givenLength, type, }) {
1074
+ super([
1075
+ `ABI encoding array length mismatch for type ${type}.`,
1076
+ `Expected length: ${expectedLength}`,
1077
+ `Given length: ${givenLength}`,
1078
+ ].join('\n'), { name: 'AbiEncodingArrayLengthMismatchError' });
1079
+ }
1080
+ }
1081
+ class AbiEncodingBytesSizeMismatchError extends BaseError {
1082
+ constructor({ expectedSize, value }) {
1083
+ super(`Size of bytes "${value}" (bytes${size(value)}) does not match expected size (bytes${expectedSize}).`, { name: 'AbiEncodingBytesSizeMismatchError' });
1084
+ }
1085
+ }
1086
+ class AbiEncodingLengthMismatchError extends BaseError {
1087
+ constructor({ expectedLength, givenLength, }) {
1088
+ super([
1089
+ 'ABI encoding params/values length mismatch.',
1090
+ `Expected length (params): ${expectedLength}`,
1091
+ `Given length (values): ${givenLength}`,
1092
+ ].join('\n'), { name: 'AbiEncodingLengthMismatchError' });
1093
+ }
1094
+ }
1095
+ class AbiFunctionNotFoundError extends BaseError {
1096
+ constructor(functionName, { docsPath } = {}) {
1097
+ super([
1098
+ `Function ${functionName ? `"${functionName}" ` : ''}not found on ABI.`,
1099
+ 'Make sure you are using the correct ABI and that the function exists on it.',
1100
+ ].join('\n'), {
1101
+ docsPath,
1102
+ name: 'AbiFunctionNotFoundError',
1103
+ });
1104
+ }
1105
+ }
1106
+ class AbiItemAmbiguityError extends BaseError {
1107
+ constructor(x, y) {
1108
+ super('Found ambiguous types in overloaded ABI items.', {
1109
+ metaMessages: [
1110
+ `\`${x.type}\` in \`${formatAbiItem(x.abiItem)}\`, and`,
1111
+ `\`${y.type}\` in \`${formatAbiItem(y.abiItem)}\``,
1112
+ '',
1113
+ 'These types encode differently and cannot be distinguished at runtime.',
1114
+ 'Remove one of the ambiguous items in the ABI.',
1115
+ ],
1116
+ name: 'AbiItemAmbiguityError',
1117
+ });
1118
+ }
1119
+ }
1120
+ class InvalidAbiEncodingTypeError extends BaseError {
1121
+ constructor(type, { docsPath }) {
1122
+ super([
1123
+ `Type "${type}" is not a valid encoding type.`,
1124
+ 'Please provide a valid ABI type.',
1125
+ ].join('\n'), { docsPath, name: 'InvalidAbiEncodingType' });
1126
+ }
1127
+ }
1128
+ class InvalidArrayError extends BaseError {
1129
+ constructor(value) {
1130
+ super([`Value "${value}" is not a valid array.`].join('\n'), {
1131
+ name: 'InvalidArrayError',
1132
+ });
1133
+ }
1134
+ }
1135
+ class InvalidDefinitionTypeError extends BaseError {
1136
+ constructor(type) {
1137
+ super([
1138
+ `"${type}" is not a valid definition type.`,
1139
+ 'Valid types: "function", "event", "error"',
1140
+ ].join('\n'), { name: 'InvalidDefinitionTypeError' });
1141
+ }
1142
+ }
1143
+
1144
+ class SliceOffsetOutOfBoundsError extends BaseError {
1145
+ constructor({ offset, position, size, }) {
1146
+ super(`Slice ${position === 'start' ? 'starting' : 'ending'} at offset "${offset}" is out-of-bounds (size: ${size}).`, { name: 'SliceOffsetOutOfBoundsError' });
1147
+ }
1148
+ }
1149
+ class SizeExceedsPaddingSizeError extends BaseError {
1150
+ constructor({ size, targetSize, type, }) {
1151
+ super(`${type.charAt(0).toUpperCase()}${type
1152
+ .slice(1)
1153
+ .toLowerCase()} size (${size}) exceeds padding size (${targetSize}).`, { name: 'SizeExceedsPaddingSizeError' });
1154
+ }
1155
+ }
1156
+
1157
+ function pad(hexOrBytes, { dir, size = 32 } = {}) {
1158
+ if (typeof hexOrBytes === 'string')
1159
+ return padHex(hexOrBytes, { dir, size });
1160
+ return padBytes(hexOrBytes, { dir, size });
1161
+ }
1162
+ function padHex(hex_, { dir, size = 32 } = {}) {
1163
+ if (size === null)
1164
+ return hex_;
1165
+ const hex = hex_.replace('0x', '');
1166
+ if (hex.length > size * 2)
1167
+ throw new SizeExceedsPaddingSizeError({
1168
+ size: Math.ceil(hex.length / 2),
1169
+ targetSize: size,
1170
+ type: 'hex',
1171
+ });
1172
+ return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}`;
1173
+ }
1174
+ function padBytes(bytes, { dir, size = 32 } = {}) {
1175
+ if (size === null)
1176
+ return bytes;
1177
+ if (bytes.length > size)
1178
+ throw new SizeExceedsPaddingSizeError({
1179
+ size: bytes.length,
1180
+ targetSize: size,
1181
+ type: 'bytes',
1182
+ });
1183
+ const paddedBytes = new Uint8Array(size);
1184
+ for (let i = 0; i < size; i++) {
1185
+ const padEnd = dir === 'right';
1186
+ paddedBytes[padEnd ? i : size - i - 1] =
1187
+ bytes[padEnd ? i : bytes.length - i - 1];
1188
+ }
1189
+ return paddedBytes;
1190
+ }
1191
+
1192
+ class IntegerOutOfRangeError extends BaseError {
1193
+ constructor({ max, min, signed, size, value, }) {
1194
+ super(`Number "${value}" is not in safe ${size ? `${size * 8}-bit ${signed ? 'signed' : 'unsigned'} ` : ''}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: 'IntegerOutOfRangeError' });
1195
+ }
1196
+ }
1197
+ class SizeOverflowError extends BaseError {
1198
+ constructor({ givenSize, maxSize }) {
1199
+ super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: 'SizeOverflowError' });
1200
+ }
1201
+ }
1202
+
1203
+ function assertSize(hexOrBytes, { size: size$1 }) {
1204
+ if (size(hexOrBytes) > size$1)
1205
+ throw new SizeOverflowError({
1206
+ givenSize: size(hexOrBytes),
1207
+ maxSize: size$1,
1208
+ });
1209
+ }
1210
+
1211
+ const hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, '0'));
1212
+ /**
1213
+ * Encodes a string, number, bigint, or ByteArray into a hex string
1214
+ *
1215
+ * - Docs: https://viem.sh/docs/utilities/toHex
1216
+ * - Example: https://viem.sh/docs/utilities/toHex#usage
1217
+ *
1218
+ * @param value Value to encode.
1219
+ * @param opts Options.
1220
+ * @returns Hex value.
1221
+ *
1222
+ * @example
1223
+ * import { toHex } from 'viem'
1224
+ * const data = toHex('Hello world')
1225
+ * // '0x48656c6c6f20776f726c6421'
1226
+ *
1227
+ * @example
1228
+ * import { toHex } from 'viem'
1229
+ * const data = toHex(420)
1230
+ * // '0x1a4'
1231
+ *
1232
+ * @example
1233
+ * import { toHex } from 'viem'
1234
+ * const data = toHex('Hello world', { size: 32 })
1235
+ * // '0x48656c6c6f20776f726c64210000000000000000000000000000000000000000'
1236
+ */
1237
+ function toHex(value, opts = {}) {
1238
+ if (typeof value === 'number' || typeof value === 'bigint')
1239
+ return numberToHex(value, opts);
1240
+ if (typeof value === 'string') {
1241
+ return stringToHex(value, opts);
1242
+ }
1243
+ if (typeof value === 'boolean')
1244
+ return boolToHex(value, opts);
1245
+ return bytesToHex(value, opts);
1246
+ }
1247
+ /**
1248
+ * Encodes a boolean into a hex string
1249
+ *
1250
+ * - Docs: https://viem.sh/docs/utilities/toHex#booltohex
1251
+ *
1252
+ * @param value Value to encode.
1253
+ * @param opts Options.
1254
+ * @returns Hex value.
1255
+ *
1256
+ * @example
1257
+ * import { boolToHex } from 'viem'
1258
+ * const data = boolToHex(true)
1259
+ * // '0x1'
1260
+ *
1261
+ * @example
1262
+ * import { boolToHex } from 'viem'
1263
+ * const data = boolToHex(false)
1264
+ * // '0x0'
1265
+ *
1266
+ * @example
1267
+ * import { boolToHex } from 'viem'
1268
+ * const data = boolToHex(true, { size: 32 })
1269
+ * // '0x0000000000000000000000000000000000000000000000000000000000000001'
1270
+ */
1271
+ function boolToHex(value, opts = {}) {
1272
+ const hex = `0x${Number(value)}`;
1273
+ if (typeof opts.size === 'number') {
1274
+ assertSize(hex, { size: opts.size });
1275
+ return pad(hex, { size: opts.size });
1276
+ }
1277
+ return hex;
1278
+ }
1279
+ /**
1280
+ * Encodes a bytes array into a hex string
1281
+ *
1282
+ * - Docs: https://viem.sh/docs/utilities/toHex#bytestohex
1283
+ *
1284
+ * @param value Value to encode.
1285
+ * @param opts Options.
1286
+ * @returns Hex value.
1287
+ *
1288
+ * @example
1289
+ * import { bytesToHex } from 'viem'
1290
+ * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
1291
+ * // '0x48656c6c6f20576f726c6421'
1292
+ *
1293
+ * @example
1294
+ * import { bytesToHex } from 'viem'
1295
+ * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]), { size: 32 })
1296
+ * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'
1297
+ */
1298
+ function bytesToHex(value, opts = {}) {
1299
+ let string = '';
1300
+ for (let i = 0; i < value.length; i++) {
1301
+ string += hexes[value[i]];
1302
+ }
1303
+ const hex = `0x${string}`;
1304
+ if (typeof opts.size === 'number') {
1305
+ assertSize(hex, { size: opts.size });
1306
+ return pad(hex, { dir: 'right', size: opts.size });
1307
+ }
1308
+ return hex;
1309
+ }
1310
+ /**
1311
+ * Encodes a number or bigint into a hex string
1312
+ *
1313
+ * - Docs: https://viem.sh/docs/utilities/toHex#numbertohex
1314
+ *
1315
+ * @param value Value to encode.
1316
+ * @param opts Options.
1317
+ * @returns Hex value.
1318
+ *
1319
+ * @example
1320
+ * import { numberToHex } from 'viem'
1321
+ * const data = numberToHex(420)
1322
+ * // '0x1a4'
1323
+ *
1324
+ * @example
1325
+ * import { numberToHex } from 'viem'
1326
+ * const data = numberToHex(420, { size: 32 })
1327
+ * // '0x00000000000000000000000000000000000000000000000000000000000001a4'
1328
+ */
1329
+ function numberToHex(value_, opts = {}) {
1330
+ const { signed, size } = opts;
1331
+ const value = BigInt(value_);
1332
+ let maxValue;
1333
+ if (size) {
1334
+ if (signed)
1335
+ maxValue = (1n << (BigInt(size) * 8n - 1n)) - 1n;
1336
+ else
1337
+ maxValue = 2n ** (BigInt(size) * 8n) - 1n;
1338
+ }
1339
+ else if (typeof value_ === 'number') {
1340
+ maxValue = BigInt(Number.MAX_SAFE_INTEGER);
1341
+ }
1342
+ const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0;
1343
+ if ((maxValue && value > maxValue) || value < minValue) {
1344
+ const suffix = typeof value_ === 'bigint' ? 'n' : '';
1345
+ throw new IntegerOutOfRangeError({
1346
+ max: maxValue ? `${maxValue}${suffix}` : undefined,
1347
+ min: `${minValue}${suffix}`,
1348
+ signed,
1349
+ size,
1350
+ value: `${value_}${suffix}`,
1351
+ });
1352
+ }
1353
+ const hex = `0x${(signed && value < 0 ? (1n << BigInt(size * 8)) + BigInt(value) : value).toString(16)}`;
1354
+ if (size)
1355
+ return pad(hex, { size });
1356
+ return hex;
1357
+ }
1358
+ const encoder$1 = /*#__PURE__*/ new TextEncoder();
1359
+ /**
1360
+ * Encodes a UTF-8 string into a hex string
1361
+ *
1362
+ * - Docs: https://viem.sh/docs/utilities/toHex#stringtohex
1363
+ *
1364
+ * @param value Value to encode.
1365
+ * @param opts Options.
1366
+ * @returns Hex value.
1367
+ *
1368
+ * @example
1369
+ * import { stringToHex } from 'viem'
1370
+ * const data = stringToHex('Hello World!')
1371
+ * // '0x48656c6c6f20576f726c6421'
1372
+ *
1373
+ * @example
1374
+ * import { stringToHex } from 'viem'
1375
+ * const data = stringToHex('Hello World!', { size: 32 })
1376
+ * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'
1377
+ */
1378
+ function stringToHex(value_, opts = {}) {
1379
+ const value = encoder$1.encode(value_);
1380
+ return bytesToHex(value, opts);
1381
+ }
1382
+
1383
+ const encoder = /*#__PURE__*/ new TextEncoder();
1384
+ /**
1385
+ * Encodes a UTF-8 string, hex value, bigint, number or boolean to a byte array.
1386
+ *
1387
+ * - Docs: https://viem.sh/docs/utilities/toBytes
1388
+ * - Example: https://viem.sh/docs/utilities/toBytes#usage
1389
+ *
1390
+ * @param value Value to encode.
1391
+ * @param opts Options.
1392
+ * @returns Byte array value.
1393
+ *
1394
+ * @example
1395
+ * import { toBytes } from 'viem'
1396
+ * const data = toBytes('Hello world')
1397
+ * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
1398
+ *
1399
+ * @example
1400
+ * import { toBytes } from 'viem'
1401
+ * const data = toBytes(420)
1402
+ * // Uint8Array([1, 164])
1403
+ *
1404
+ * @example
1405
+ * import { toBytes } from 'viem'
1406
+ * const data = toBytes(420, { size: 4 })
1407
+ * // Uint8Array([0, 0, 1, 164])
1408
+ */
1409
+ function toBytes$1(value, opts = {}) {
1410
+ if (typeof value === 'number' || typeof value === 'bigint')
1411
+ return numberToBytes(value, opts);
1412
+ if (typeof value === 'boolean')
1413
+ return boolToBytes(value, opts);
1414
+ if (isHex(value))
1415
+ return hexToBytes(value, opts);
1416
+ return stringToBytes(value, opts);
1417
+ }
1418
+ /**
1419
+ * Encodes a boolean into a byte array.
1420
+ *
1421
+ * - Docs: https://viem.sh/docs/utilities/toBytes#booltobytes
1422
+ *
1423
+ * @param value Boolean value to encode.
1424
+ * @param opts Options.
1425
+ * @returns Byte array value.
1426
+ *
1427
+ * @example
1428
+ * import { boolToBytes } from 'viem'
1429
+ * const data = boolToBytes(true)
1430
+ * // Uint8Array([1])
1431
+ *
1432
+ * @example
1433
+ * import { boolToBytes } from 'viem'
1434
+ * const data = boolToBytes(true, { size: 32 })
1435
+ * // Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
1436
+ */
1437
+ function boolToBytes(value, opts = {}) {
1438
+ const bytes = new Uint8Array(1);
1439
+ bytes[0] = Number(value);
1440
+ if (typeof opts.size === 'number') {
1441
+ assertSize(bytes, { size: opts.size });
1442
+ return pad(bytes, { size: opts.size });
1443
+ }
1444
+ return bytes;
1445
+ }
1446
+ // We use very optimized technique to convert hex string to byte array
1447
+ const charCodeMap = {
1448
+ zero: 48,
1449
+ nine: 57,
1450
+ A: 65,
1451
+ F: 70,
1452
+ a: 97,
1453
+ f: 102,
1454
+ };
1455
+ function charCodeToBase16(char) {
1456
+ if (char >= charCodeMap.zero && char <= charCodeMap.nine)
1457
+ return char - charCodeMap.zero;
1458
+ if (char >= charCodeMap.A && char <= charCodeMap.F)
1459
+ return char - (charCodeMap.A - 10);
1460
+ if (char >= charCodeMap.a && char <= charCodeMap.f)
1461
+ return char - (charCodeMap.a - 10);
1462
+ return undefined;
1463
+ }
1464
+ /**
1465
+ * Encodes a hex string into a byte array.
1466
+ *
1467
+ * - Docs: https://viem.sh/docs/utilities/toBytes#hextobytes
1468
+ *
1469
+ * @param hex Hex string to encode.
1470
+ * @param opts Options.
1471
+ * @returns Byte array value.
1472
+ *
1473
+ * @example
1474
+ * import { hexToBytes } from 'viem'
1475
+ * const data = hexToBytes('0x48656c6c6f20776f726c6421')
1476
+ * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
1477
+ *
1478
+ * @example
1479
+ * import { hexToBytes } from 'viem'
1480
+ * const data = hexToBytes('0x48656c6c6f20776f726c6421', { size: 32 })
1481
+ * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
1482
+ */
1483
+ function hexToBytes(hex_, opts = {}) {
1484
+ let hex = hex_;
1485
+ if (opts.size) {
1486
+ assertSize(hex, { size: opts.size });
1487
+ hex = pad(hex, { dir: 'right', size: opts.size });
1488
+ }
1489
+ let hexString = hex.slice(2);
1490
+ if (hexString.length % 2)
1491
+ hexString = `0${hexString}`;
1492
+ const length = hexString.length / 2;
1493
+ const bytes = new Uint8Array(length);
1494
+ for (let index = 0, j = 0; index < length; index++) {
1495
+ const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++));
1496
+ const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++));
1497
+ if (nibbleLeft === undefined || nibbleRight === undefined) {
1498
+ throw new BaseError(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`);
1499
+ }
1500
+ bytes[index] = nibbleLeft * 16 + nibbleRight;
1501
+ }
1502
+ return bytes;
1503
+ }
1504
+ /**
1505
+ * Encodes a number into a byte array.
1506
+ *
1507
+ * - Docs: https://viem.sh/docs/utilities/toBytes#numbertobytes
1508
+ *
1509
+ * @param value Number to encode.
1510
+ * @param opts Options.
1511
+ * @returns Byte array value.
1512
+ *
1513
+ * @example
1514
+ * import { numberToBytes } from 'viem'
1515
+ * const data = numberToBytes(420)
1516
+ * // Uint8Array([1, 164])
1517
+ *
1518
+ * @example
1519
+ * import { numberToBytes } from 'viem'
1520
+ * const data = numberToBytes(420, { size: 4 })
1521
+ * // Uint8Array([0, 0, 1, 164])
1522
+ */
1523
+ function numberToBytes(value, opts) {
1524
+ const hex = numberToHex(value, opts);
1525
+ return hexToBytes(hex);
1526
+ }
1527
+ /**
1528
+ * Encodes a UTF-8 string into a byte array.
1529
+ *
1530
+ * - Docs: https://viem.sh/docs/utilities/toBytes#stringtobytes
1531
+ *
1532
+ * @param value String to encode.
1533
+ * @param opts Options.
1534
+ * @returns Byte array value.
1535
+ *
1536
+ * @example
1537
+ * import { stringToBytes } from 'viem'
1538
+ * const data = stringToBytes('Hello world!')
1539
+ * // Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])
1540
+ *
1541
+ * @example
1542
+ * import { stringToBytes } from 'viem'
1543
+ * const data = stringToBytes('Hello world!', { size: 32 })
1544
+ * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
1545
+ */
1546
+ function stringToBytes(value, opts = {}) {
1547
+ const bytes = encoder.encode(value);
1548
+ if (typeof opts.size === 'number') {
1549
+ assertSize(bytes, { size: opts.size });
1550
+ return pad(bytes, { dir: 'right', size: opts.size });
1551
+ }
1552
+ return bytes;
1553
+ }
1554
+
1555
+ /**
1556
+ * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
1557
+ * @todo re-check https://issues.chromium.org/issues/42212588
1558
+ * @module
1559
+ */
1560
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
1561
+ const _32n = /* @__PURE__ */ BigInt(32);
1562
+ function fromBig(n, le = false) {
1563
+ if (le)
1564
+ return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
1565
+ return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
1566
+ }
1567
+ function split(lst, le = false) {
1568
+ const len = lst.length;
1569
+ let Ah = new Uint32Array(len);
1570
+ let Al = new Uint32Array(len);
1571
+ for (let i = 0; i < len; i++) {
1572
+ const { h, l } = fromBig(lst[i], le);
1573
+ [Ah[i], Al[i]] = [h, l];
1574
+ }
1575
+ return [Ah, Al];
1576
+ }
1577
+ // Left rotate for Shift in [1, 32)
1578
+ const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
1579
+ const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
1580
+ // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
1581
+ const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
1582
+ const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
1583
+
1584
+ /**
1585
+ * Utilities for hex, bytes, CSPRNG.
1586
+ * @module
1587
+ */
1588
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1589
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
1590
+ // node.js versions earlier than v19 don't declare it in global scope.
1591
+ // For node.js, package.json#exports field mapping rewrites import
1592
+ // from `crypto` to `cryptoNode`, which imports native module.
1593
+ // Makes the utils un-importable in browsers without a bundler.
1594
+ // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
1595
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
1596
+ function isBytes(a) {
1597
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
1598
+ }
1599
+ /** Asserts something is positive integer. */
1600
+ function anumber(n) {
1601
+ if (!Number.isSafeInteger(n) || n < 0)
1602
+ throw new Error('positive integer expected, got ' + n);
1603
+ }
1604
+ /** Asserts something is Uint8Array. */
1605
+ function abytes(b, ...lengths) {
1606
+ if (!isBytes(b))
1607
+ throw new Error('Uint8Array expected');
1608
+ if (lengths.length > 0 && !lengths.includes(b.length))
1609
+ throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
1610
+ }
1611
+ /** Asserts a hash instance has not been destroyed / finished */
1612
+ function aexists(instance, checkFinished = true) {
1613
+ if (instance.destroyed)
1614
+ throw new Error('Hash instance has been destroyed');
1615
+ if (checkFinished && instance.finished)
1616
+ throw new Error('Hash#digest() has already been called');
1617
+ }
1618
+ /** Asserts output is properly-sized byte array */
1619
+ function aoutput(out, instance) {
1620
+ abytes(out);
1621
+ const min = instance.outputLen;
1622
+ if (out.length < min) {
1623
+ throw new Error('digestInto() expects output buffer of length at least ' + min);
1624
+ }
1625
+ }
1626
+ /** Cast u8 / u16 / u32 to u32. */
1627
+ function u32(arr) {
1628
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
1629
+ }
1630
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
1631
+ function clean(...arrays) {
1632
+ for (let i = 0; i < arrays.length; i++) {
1633
+ arrays[i].fill(0);
1634
+ }
1635
+ }
1636
+ /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
1637
+ const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
1638
+ /** The byte swap operation for uint32 */
1639
+ function byteSwap(word) {
1640
+ return (((word << 24) & 0xff000000) |
1641
+ ((word << 8) & 0xff0000) |
1642
+ ((word >>> 8) & 0xff00) |
1643
+ ((word >>> 24) & 0xff));
1644
+ }
1645
+ /** In place byte swap for Uint32Array */
1646
+ function byteSwap32(arr) {
1647
+ for (let i = 0; i < arr.length; i++) {
1648
+ arr[i] = byteSwap(arr[i]);
1649
+ }
1650
+ return arr;
1651
+ }
1652
+ const swap32IfBE = isLE
1653
+ ? (u) => u
1654
+ : byteSwap32;
1655
+ /**
1656
+ * Converts string to bytes using UTF8 encoding.
1657
+ * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
1658
+ */
1659
+ function utf8ToBytes(str) {
1660
+ if (typeof str !== 'string')
1661
+ throw new Error('string expected');
1662
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
1663
+ }
1664
+ /**
1665
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
1666
+ * Warning: when Uint8Array is passed, it would NOT get copied.
1667
+ * Keep in mind for future mutable operations.
1668
+ */
1669
+ function toBytes(data) {
1670
+ if (typeof data === 'string')
1671
+ data = utf8ToBytes(data);
1672
+ abytes(data);
1673
+ return data;
1674
+ }
1675
+ /** For runtime check if class implements interface */
1676
+ class Hash {
1677
+ }
1678
+ /** Wraps hash function, creating an interface on top of it */
1679
+ function createHasher(hashCons) {
1680
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
1681
+ const tmp = hashCons();
1682
+ hashC.outputLen = tmp.outputLen;
1683
+ hashC.blockLen = tmp.blockLen;
1684
+ hashC.create = () => hashCons();
1685
+ return hashC;
1686
+ }
1687
+
1688
+ /**
1689
+ * SHA3 (keccak) hash function, based on a new "Sponge function" design.
1690
+ * Different from older hashes, the internal state is bigger than output size.
1691
+ *
1692
+ * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
1693
+ * [Website](https://keccak.team/keccak.html),
1694
+ * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).
1695
+ *
1696
+ * Check out `sha3-addons` module for cSHAKE, k12, and others.
1697
+ * @module
1698
+ */
1699
+ // No __PURE__ annotations in sha3 header:
1700
+ // EVERYTHING is in fact used on every export.
1701
+ // Various per round constants calculations
1702
+ const _0n = BigInt(0);
1703
+ const _1n = BigInt(1);
1704
+ const _2n = BigInt(2);
1705
+ const _7n = BigInt(7);
1706
+ const _256n = BigInt(256);
1707
+ const _0x71n = BigInt(0x71);
1708
+ const SHA3_PI = [];
1709
+ const SHA3_ROTL = [];
1710
+ const _SHA3_IOTA = [];
1711
+ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
1712
+ // Pi
1713
+ [x, y] = [y, (2 * x + 3 * y) % 5];
1714
+ SHA3_PI.push(2 * (5 * y + x));
1715
+ // Rotational
1716
+ SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
1717
+ // Iota
1718
+ let t = _0n;
1719
+ for (let j = 0; j < 7; j++) {
1720
+ R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;
1721
+ if (R & _2n)
1722
+ t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);
1723
+ }
1724
+ _SHA3_IOTA.push(t);
1725
+ }
1726
+ const IOTAS = split(_SHA3_IOTA, true);
1727
+ const SHA3_IOTA_H = IOTAS[0];
1728
+ const SHA3_IOTA_L = IOTAS[1];
1729
+ // Left rotation (without 0, 32, 64)
1730
+ const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
1731
+ const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
1732
+ /** `keccakf1600` internal function, additionally allows to adjust round count. */
1733
+ function keccakP(s, rounds = 24) {
1734
+ const B = new Uint32Array(5 * 2);
1735
+ // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
1736
+ for (let round = 24 - rounds; round < 24; round++) {
1737
+ // Theta θ
1738
+ for (let x = 0; x < 10; x++)
1739
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
1740
+ for (let x = 0; x < 10; x += 2) {
1741
+ const idx1 = (x + 8) % 10;
1742
+ const idx0 = (x + 2) % 10;
1743
+ const B0 = B[idx0];
1744
+ const B1 = B[idx0 + 1];
1745
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
1746
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
1747
+ for (let y = 0; y < 50; y += 10) {
1748
+ s[x + y] ^= Th;
1749
+ s[x + y + 1] ^= Tl;
1750
+ }
1751
+ }
1752
+ // Rho (ρ) and Pi (π)
1753
+ let curH = s[2];
1754
+ let curL = s[3];
1755
+ for (let t = 0; t < 24; t++) {
1756
+ const shift = SHA3_ROTL[t];
1757
+ const Th = rotlH(curH, curL, shift);
1758
+ const Tl = rotlL(curH, curL, shift);
1759
+ const PI = SHA3_PI[t];
1760
+ curH = s[PI];
1761
+ curL = s[PI + 1];
1762
+ s[PI] = Th;
1763
+ s[PI + 1] = Tl;
1764
+ }
1765
+ // Chi (χ)
1766
+ for (let y = 0; y < 50; y += 10) {
1767
+ for (let x = 0; x < 10; x++)
1768
+ B[x] = s[y + x];
1769
+ for (let x = 0; x < 10; x++)
1770
+ s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
1771
+ }
1772
+ // Iota (ι)
1773
+ s[0] ^= SHA3_IOTA_H[round];
1774
+ s[1] ^= SHA3_IOTA_L[round];
1775
+ }
1776
+ clean(B);
1777
+ }
1778
+ /** Keccak sponge function. */
1779
+ class Keccak extends Hash {
1780
+ // NOTE: we accept arguments in bytes instead of bits here.
1781
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
1782
+ super();
1783
+ this.pos = 0;
1784
+ this.posOut = 0;
1785
+ this.finished = false;
1786
+ this.destroyed = false;
1787
+ this.enableXOF = false;
1788
+ this.blockLen = blockLen;
1789
+ this.suffix = suffix;
1790
+ this.outputLen = outputLen;
1791
+ this.enableXOF = enableXOF;
1792
+ this.rounds = rounds;
1793
+ // Can be passed from user as dkLen
1794
+ anumber(outputLen);
1795
+ // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
1796
+ // 0 < blockLen < 200
1797
+ if (!(0 < blockLen && blockLen < 200))
1798
+ throw new Error('only keccak-f1600 function is supported');
1799
+ this.state = new Uint8Array(200);
1800
+ this.state32 = u32(this.state);
1801
+ }
1802
+ clone() {
1803
+ return this._cloneInto();
1804
+ }
1805
+ keccak() {
1806
+ swap32IfBE(this.state32);
1807
+ keccakP(this.state32, this.rounds);
1808
+ swap32IfBE(this.state32);
1809
+ this.posOut = 0;
1810
+ this.pos = 0;
1811
+ }
1812
+ update(data) {
1813
+ aexists(this);
1814
+ data = toBytes(data);
1815
+ abytes(data);
1816
+ const { blockLen, state } = this;
1817
+ const len = data.length;
1818
+ for (let pos = 0; pos < len;) {
1819
+ const take = Math.min(blockLen - this.pos, len - pos);
1820
+ for (let i = 0; i < take; i++)
1821
+ state[this.pos++] ^= data[pos++];
1822
+ if (this.pos === blockLen)
1823
+ this.keccak();
1824
+ }
1825
+ return this;
1826
+ }
1827
+ finish() {
1828
+ if (this.finished)
1829
+ return;
1830
+ this.finished = true;
1831
+ const { state, suffix, pos, blockLen } = this;
1832
+ // Do the padding
1833
+ state[pos] ^= suffix;
1834
+ if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
1835
+ this.keccak();
1836
+ state[blockLen - 1] ^= 0x80;
1837
+ this.keccak();
1838
+ }
1839
+ writeInto(out) {
1840
+ aexists(this, false);
1841
+ abytes(out);
1842
+ this.finish();
1843
+ const bufferOut = this.state;
1844
+ const { blockLen } = this;
1845
+ for (let pos = 0, len = out.length; pos < len;) {
1846
+ if (this.posOut >= blockLen)
1847
+ this.keccak();
1848
+ const take = Math.min(blockLen - this.posOut, len - pos);
1849
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
1850
+ this.posOut += take;
1851
+ pos += take;
1852
+ }
1853
+ return out;
1854
+ }
1855
+ xofInto(out) {
1856
+ // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
1857
+ if (!this.enableXOF)
1858
+ throw new Error('XOF is not possible for this instance');
1859
+ return this.writeInto(out);
1860
+ }
1861
+ xof(bytes) {
1862
+ anumber(bytes);
1863
+ return this.xofInto(new Uint8Array(bytes));
1864
+ }
1865
+ digestInto(out) {
1866
+ aoutput(out, this);
1867
+ if (this.finished)
1868
+ throw new Error('digest() was already called');
1869
+ this.writeInto(out);
1870
+ this.destroy();
1871
+ return out;
1872
+ }
1873
+ digest() {
1874
+ return this.digestInto(new Uint8Array(this.outputLen));
1875
+ }
1876
+ destroy() {
1877
+ this.destroyed = true;
1878
+ clean(this.state);
1879
+ }
1880
+ _cloneInto(to) {
1881
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
1882
+ to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
1883
+ to.state32.set(this.state32);
1884
+ to.pos = this.pos;
1885
+ to.posOut = this.posOut;
1886
+ to.finished = this.finished;
1887
+ to.rounds = rounds;
1888
+ // Suffix can change in cSHAKE
1889
+ to.suffix = suffix;
1890
+ to.outputLen = outputLen;
1891
+ to.enableXOF = enableXOF;
1892
+ to.destroyed = this.destroyed;
1893
+ return to;
1894
+ }
1895
+ }
1896
+ const gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
1897
+ /** keccak-256 hash function. Different from SHA3-256. */
1898
+ const keccak_256 = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();
1899
+
1900
+ function keccak256(value, to_) {
1901
+ const to = to_ || 'hex';
1902
+ const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes$1(value) : value);
1903
+ if (to === 'bytes')
1904
+ return bytes;
1905
+ return toHex(bytes);
1906
+ }
1907
+
1908
+ const hash = (value) => keccak256(toBytes$1(value));
1909
+ function hashSignature(sig) {
1910
+ return hash(sig);
1911
+ }
1912
+
1913
+ function normalizeSignature(signature) {
1914
+ let active = true;
1915
+ let current = '';
1916
+ let level = 0;
1917
+ let result = '';
1918
+ let valid = false;
1919
+ for (let i = 0; i < signature.length; i++) {
1920
+ const char = signature[i];
1921
+ // If the character is a separator, we want to reactivate.
1922
+ if (['(', ')', ','].includes(char))
1923
+ active = true;
1924
+ // If the character is a "level" token, we want to increment/decrement.
1925
+ if (char === '(')
1926
+ level++;
1927
+ if (char === ')')
1928
+ level--;
1929
+ // If we aren't active, we don't want to mutate the result.
1930
+ if (!active)
1931
+ continue;
1932
+ // If level === 0, we are at the definition level.
1933
+ if (level === 0) {
1934
+ if (char === ' ' && ['event', 'function', ''].includes(result))
1935
+ result = '';
1936
+ else {
1937
+ result += char;
1938
+ // If we are at the end of the definition, we must be finished.
1939
+ if (char === ')') {
1940
+ valid = true;
1941
+ break;
1942
+ }
1943
+ }
1944
+ continue;
1945
+ }
1946
+ // Ignore spaces
1947
+ if (char === ' ') {
1948
+ // If the previous character is a separator, and the current section isn't empty, we want to deactivate.
1949
+ if (signature[i - 1] !== ',' && current !== ',' && current !== ',(') {
1950
+ current = '';
1951
+ active = false;
1952
+ }
1953
+ continue;
1954
+ }
1955
+ result += char;
1956
+ current += char;
1957
+ }
1958
+ if (!valid)
1959
+ throw new BaseError('Unable to normalize signature.');
1960
+ return result;
1961
+ }
1962
+
1963
+ /**
1964
+ * Returns the signature for a given function or event definition.
1965
+ *
1966
+ * @example
1967
+ * const signature = toSignature('function ownerOf(uint256 tokenId)')
1968
+ * // 'ownerOf(uint256)'
1969
+ *
1970
+ * @example
1971
+ * const signature_3 = toSignature({
1972
+ * name: 'ownerOf',
1973
+ * type: 'function',
1974
+ * inputs: [{ name: 'tokenId', type: 'uint256' }],
1975
+ * outputs: [],
1976
+ * stateMutability: 'view',
1977
+ * })
1978
+ * // 'ownerOf(uint256)'
1979
+ */
1980
+ const toSignature = (def) => {
1981
+ const def_ = (() => {
1982
+ if (typeof def === 'string')
1983
+ return def;
1984
+ return formatAbiItem$1(def);
1985
+ })();
1986
+ return normalizeSignature(def_);
1987
+ };
1988
+
1989
+ /**
1990
+ * Returns the hash (of the function/event signature) for a given event or function definition.
1991
+ */
1992
+ function toSignatureHash(fn) {
1993
+ return hashSignature(toSignature(fn));
1994
+ }
1995
+
1996
+ /**
1997
+ * Returns the event selector for a given event definition.
1998
+ *
1999
+ * @example
2000
+ * const selector = toEventSelector('Transfer(address indexed from, address indexed to, uint256 amount)')
2001
+ * // 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
2002
+ */
2003
+ const toEventSelector = toSignatureHash;
2004
+
2005
+ class InvalidAddressError extends BaseError {
2006
+ constructor({ address }) {
2007
+ super(`Address "${address}" is invalid.`, {
2008
+ metaMessages: [
2009
+ '- Address must be a hex value of 20 bytes (40 hex characters).',
2010
+ '- Address must match its checksum counterpart.',
2011
+ ],
2012
+ name: 'InvalidAddressError',
2013
+ });
2014
+ }
2015
+ }
2016
+
2017
+ /**
2018
+ * Map with a LRU (Least recently used) policy.
2019
+ *
2020
+ * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
2021
+ */
2022
+ class LruMap extends Map {
2023
+ constructor(size) {
2024
+ super();
2025
+ Object.defineProperty(this, "maxSize", {
2026
+ enumerable: true,
2027
+ configurable: true,
2028
+ writable: true,
2029
+ value: void 0
2030
+ });
2031
+ this.maxSize = size;
2032
+ }
2033
+ get(key) {
2034
+ const value = super.get(key);
2035
+ if (super.has(key)) {
2036
+ super.delete(key);
2037
+ super.set(key, value);
2038
+ }
2039
+ return value;
2040
+ }
2041
+ set(key, value) {
2042
+ if (super.has(key))
2043
+ super.delete(key);
2044
+ super.set(key, value);
2045
+ if (this.maxSize && this.size > this.maxSize) {
2046
+ const firstKey = super.keys().next().value;
2047
+ if (firstKey !== undefined)
2048
+ super.delete(firstKey);
2049
+ }
2050
+ return this;
2051
+ }
2052
+ }
2053
+
2054
+ const checksumAddressCache = /*#__PURE__*/ new LruMap(8192);
2055
+ function checksumAddress(address_,
2056
+ /**
2057
+ * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the
2058
+ * wider Ethereum ecosystem, meaning it will break when validated against an application/tool
2059
+ * that relies on EIP-55 checksum encoding (checksum without chainId).
2060
+ *
2061
+ * It is highly recommended to not use this feature unless you
2062
+ * know what you are doing.
2063
+ *
2064
+ * See more: https://github.com/ethereum/EIPs/issues/1121
2065
+ */
2066
+ chainId) {
2067
+ if (checksumAddressCache.has(`${address_}.${chainId}`))
2068
+ return checksumAddressCache.get(`${address_}.${chainId}`);
2069
+ const hexAddress = address_.substring(2).toLowerCase();
2070
+ const hash = keccak256(stringToBytes(hexAddress), 'bytes');
2071
+ const address = (hexAddress).split('');
2072
+ for (let i = 0; i < 40; i += 2) {
2073
+ if (hash[i >> 1] >> 4 >= 8 && address[i]) {
2074
+ address[i] = address[i].toUpperCase();
2075
+ }
2076
+ if ((hash[i >> 1] & 0x0f) >= 8 && address[i + 1]) {
2077
+ address[i + 1] = address[i + 1].toUpperCase();
2078
+ }
2079
+ }
2080
+ const result = `0x${address.join('')}`;
2081
+ checksumAddressCache.set(`${address_}.${chainId}`, result);
2082
+ return result;
2083
+ }
2084
+
2085
+ const addressRegex = /^0x[a-fA-F0-9]{40}$/;
2086
+ /** @internal */
2087
+ const isAddressCache = /*#__PURE__*/ new LruMap(8192);
2088
+ function isAddress(address, options) {
2089
+ const { strict = true } = options ?? {};
2090
+ const cacheKey = `${address}.${strict}`;
2091
+ if (isAddressCache.has(cacheKey))
2092
+ return isAddressCache.get(cacheKey);
2093
+ const result = (() => {
2094
+ if (!addressRegex.test(address))
2095
+ return false;
2096
+ if (address.toLowerCase() === address)
2097
+ return true;
2098
+ if (strict)
2099
+ return checksumAddress(address) === address;
2100
+ return true;
2101
+ })();
2102
+ isAddressCache.set(cacheKey, result);
2103
+ return result;
2104
+ }
2105
+
2106
+ function concat(values) {
2107
+ if (typeof values[0] === 'string')
2108
+ return concatHex(values);
2109
+ return concatBytes(values);
2110
+ }
2111
+ function concatBytes(values) {
2112
+ let length = 0;
2113
+ for (const arr of values) {
2114
+ length += arr.length;
2115
+ }
2116
+ const result = new Uint8Array(length);
2117
+ let offset = 0;
2118
+ for (const arr of values) {
2119
+ result.set(arr, offset);
2120
+ offset += arr.length;
2121
+ }
2122
+ return result;
2123
+ }
2124
+ function concatHex(values) {
2125
+ return `0x${values.reduce((acc, x) => acc + x.replace('0x', ''), '')}`;
2126
+ }
2127
+
2128
+ /**
2129
+ * @description Returns a section of the hex or byte array given a start/end bytes offset.
2130
+ *
2131
+ * @param value The hex or byte array to slice.
2132
+ * @param start The start offset (in bytes).
2133
+ * @param end The end offset (in bytes).
2134
+ */
2135
+ function slice(value, start, end, { strict } = {}) {
2136
+ if (isHex(value, { strict: false }))
2137
+ return sliceHex(value, start, end, {
2138
+ strict,
2139
+ });
2140
+ return sliceBytes(value, start, end, {
2141
+ strict,
2142
+ });
2143
+ }
2144
+ function assertStartOffset(value, start) {
2145
+ if (typeof start === 'number' && start > 0 && start > size(value) - 1)
2146
+ throw new SliceOffsetOutOfBoundsError({
2147
+ offset: start,
2148
+ position: 'start',
2149
+ size: size(value),
2150
+ });
2151
+ }
2152
+ function assertEndOffset(value, start, end) {
2153
+ if (typeof start === 'number' &&
2154
+ typeof end === 'number' &&
2155
+ size(value) !== end - start) {
2156
+ throw new SliceOffsetOutOfBoundsError({
2157
+ offset: end,
2158
+ position: 'end',
2159
+ size: size(value),
2160
+ });
2161
+ }
2162
+ }
2163
+ /**
2164
+ * @description Returns a section of the byte array given a start/end bytes offset.
2165
+ *
2166
+ * @param value The byte array to slice.
2167
+ * @param start The start offset (in bytes).
2168
+ * @param end The end offset (in bytes).
2169
+ */
2170
+ function sliceBytes(value_, start, end, { strict } = {}) {
2171
+ assertStartOffset(value_, start);
2172
+ const value = value_.slice(start, end);
2173
+ if (strict)
2174
+ assertEndOffset(value, start, end);
2175
+ return value;
2176
+ }
2177
+ /**
2178
+ * @description Returns a section of the hex value given a start/end bytes offset.
2179
+ *
2180
+ * @param value The hex value to slice.
2181
+ * @param start The start offset (in bytes).
2182
+ * @param end The end offset (in bytes).
2183
+ */
2184
+ function sliceHex(value_, start, end, { strict } = {}) {
2185
+ assertStartOffset(value_, start);
2186
+ const value = `0x${value_
2187
+ .replace('0x', '')
2188
+ .slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`;
2189
+ if (strict)
2190
+ assertEndOffset(value, start, end);
2191
+ return value;
2192
+ }
2193
+
2194
+ // `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`
2195
+ // https://regexr.com/6v8hp
2196
+ const integerRegex = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;
2197
+
2198
+ /**
2199
+ * @description Encodes a list of primitive values into an ABI-encoded hex value.
2200
+ *
2201
+ * - Docs: https://viem.sh/docs/abi/encodeAbiParameters#encodeabiparameters
2202
+ *
2203
+ * Generates ABI encoded data using the [ABI specification](https://docs.soliditylang.org/en/latest/abi-spec), given a set of ABI parameters (inputs/outputs) and their corresponding values.
2204
+ *
2205
+ * @param params - a set of ABI Parameters (params), that can be in the shape of the inputs or outputs attribute of an ABI Item.
2206
+ * @param values - a set of values (values) that correspond to the given params.
2207
+ * @example
2208
+ * ```typescript
2209
+ * import { encodeAbiParameters } from 'viem'
2210
+ *
2211
+ * const encodedData = encodeAbiParameters(
2212
+ * [
2213
+ * { name: 'x', type: 'string' },
2214
+ * { name: 'y', type: 'uint' },
2215
+ * { name: 'z', type: 'bool' }
2216
+ * ],
2217
+ * ['wagmi', 420n, true]
2218
+ * )
2219
+ * ```
2220
+ *
2221
+ * You can also pass in Human Readable parameters with the parseAbiParameters utility.
2222
+ *
2223
+ * @example
2224
+ * ```typescript
2225
+ * import { encodeAbiParameters, parseAbiParameters } from 'viem'
2226
+ *
2227
+ * const encodedData = encodeAbiParameters(
2228
+ * parseAbiParameters('string x, uint y, bool z'),
2229
+ * ['wagmi', 420n, true]
2230
+ * )
2231
+ * ```
2232
+ */
2233
+ function encodeAbiParameters(params, values) {
2234
+ if (params.length !== values.length)
2235
+ throw new AbiEncodingLengthMismatchError({
2236
+ expectedLength: params.length,
2237
+ givenLength: values.length,
2238
+ });
2239
+ // Prepare the parameters to determine dynamic types to encode.
2240
+ const preparedParams = prepareParams({
2241
+ params: params,
2242
+ values: values,
2243
+ });
2244
+ const data = encodeParams(preparedParams);
2245
+ if (data.length === 0)
2246
+ return '0x';
2247
+ return data;
2248
+ }
2249
+ function prepareParams({ params, values, }) {
2250
+ const preparedParams = [];
2251
+ for (let i = 0; i < params.length; i++) {
2252
+ preparedParams.push(prepareParam({ param: params[i], value: values[i] }));
2253
+ }
2254
+ return preparedParams;
2255
+ }
2256
+ function prepareParam({ param, value, }) {
2257
+ const arrayComponents = getArrayComponents(param.type);
2258
+ if (arrayComponents) {
2259
+ const [length, type] = arrayComponents;
2260
+ return encodeArray(value, { length, param: { ...param, type } });
2261
+ }
2262
+ if (param.type === 'tuple') {
2263
+ return encodeTuple(value, {
2264
+ param: param,
2265
+ });
2266
+ }
2267
+ if (param.type === 'address') {
2268
+ return encodeAddress(value);
2269
+ }
2270
+ if (param.type === 'bool') {
2271
+ return encodeBool(value);
2272
+ }
2273
+ if (param.type.startsWith('uint') || param.type.startsWith('int')) {
2274
+ const signed = param.type.startsWith('int');
2275
+ const [, , size = '256'] = integerRegex.exec(param.type) ?? [];
2276
+ return encodeNumber(value, {
2277
+ signed,
2278
+ size: Number(size),
2279
+ });
2280
+ }
2281
+ if (param.type.startsWith('bytes')) {
2282
+ return encodeBytes(value, { param });
2283
+ }
2284
+ if (param.type === 'string') {
2285
+ return encodeString(value);
2286
+ }
2287
+ throw new InvalidAbiEncodingTypeError(param.type, {
2288
+ docsPath: '/docs/contract/encodeAbiParameters',
2289
+ });
2290
+ }
2291
+ function encodeParams(preparedParams) {
2292
+ // 1. Compute the size of the static part of the parameters.
2293
+ let staticSize = 0;
2294
+ for (let i = 0; i < preparedParams.length; i++) {
2295
+ const { dynamic, encoded } = preparedParams[i];
2296
+ if (dynamic)
2297
+ staticSize += 32;
2298
+ else
2299
+ staticSize += size(encoded);
2300
+ }
2301
+ // 2. Split the parameters into static and dynamic parts.
2302
+ const staticParams = [];
2303
+ const dynamicParams = [];
2304
+ let dynamicSize = 0;
2305
+ for (let i = 0; i < preparedParams.length; i++) {
2306
+ const { dynamic, encoded } = preparedParams[i];
2307
+ if (dynamic) {
2308
+ staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 }));
2309
+ dynamicParams.push(encoded);
2310
+ dynamicSize += size(encoded);
2311
+ }
2312
+ else {
2313
+ staticParams.push(encoded);
2314
+ }
2315
+ }
2316
+ // 3. Concatenate static and dynamic parts.
2317
+ return concat([...staticParams, ...dynamicParams]);
2318
+ }
2319
+ function encodeAddress(value) {
2320
+ if (!isAddress(value))
2321
+ throw new InvalidAddressError({ address: value });
2322
+ return { dynamic: false, encoded: padHex(value.toLowerCase()) };
2323
+ }
2324
+ function encodeArray(value, { length, param, }) {
2325
+ const dynamic = length === null;
2326
+ if (!Array.isArray(value))
2327
+ throw new InvalidArrayError(value);
2328
+ if (!dynamic && value.length !== length)
2329
+ throw new AbiEncodingArrayLengthMismatchError({
2330
+ expectedLength: length,
2331
+ givenLength: value.length,
2332
+ type: `${param.type}[${length}]`,
2333
+ });
2334
+ let dynamicChild = false;
2335
+ const preparedParams = [];
2336
+ for (let i = 0; i < value.length; i++) {
2337
+ const preparedParam = prepareParam({ param, value: value[i] });
2338
+ if (preparedParam.dynamic)
2339
+ dynamicChild = true;
2340
+ preparedParams.push(preparedParam);
2341
+ }
2342
+ if (dynamic || dynamicChild) {
2343
+ const data = encodeParams(preparedParams);
2344
+ if (dynamic) {
2345
+ const length = numberToHex(preparedParams.length, { size: 32 });
2346
+ return {
2347
+ dynamic: true,
2348
+ encoded: preparedParams.length > 0 ? concat([length, data]) : length,
2349
+ };
2350
+ }
2351
+ if (dynamicChild)
2352
+ return { dynamic: true, encoded: data };
2353
+ }
2354
+ return {
2355
+ dynamic: false,
2356
+ encoded: concat(preparedParams.map(({ encoded }) => encoded)),
2357
+ };
2358
+ }
2359
+ function encodeBytes(value, { param }) {
2360
+ const [, paramSize] = param.type.split('bytes');
2361
+ const bytesSize = size(value);
2362
+ if (!paramSize) {
2363
+ let value_ = value;
2364
+ // If the size is not divisible by 32 bytes, pad the end
2365
+ // with empty bytes to the ceiling 32 bytes.
2366
+ if (bytesSize % 32 !== 0)
2367
+ value_ = padHex(value_, {
2368
+ dir: 'right',
2369
+ size: Math.ceil((value.length - 2) / 2 / 32) * 32,
2370
+ });
2371
+ return {
2372
+ dynamic: true,
2373
+ encoded: concat([padHex(numberToHex(bytesSize, { size: 32 })), value_]),
2374
+ };
2375
+ }
2376
+ if (bytesSize !== Number.parseInt(paramSize, 10))
2377
+ throw new AbiEncodingBytesSizeMismatchError({
2378
+ expectedSize: Number.parseInt(paramSize, 10),
2379
+ value,
2380
+ });
2381
+ return { dynamic: false, encoded: padHex(value, { dir: 'right' }) };
2382
+ }
2383
+ function encodeBool(value) {
2384
+ if (typeof value !== 'boolean')
2385
+ throw new BaseError(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`);
2386
+ return { dynamic: false, encoded: padHex(boolToHex(value)) };
2387
+ }
2388
+ function encodeNumber(value, { signed, size = 256 }) {
2389
+ if (typeof size === 'number') {
2390
+ const max = 2n ** (BigInt(size) - (signed ? 1n : 0n)) - 1n;
2391
+ const min = signed ? -max - 1n : 0n;
2392
+ if (value > max || value < min)
2393
+ throw new IntegerOutOfRangeError({
2394
+ max: max.toString(),
2395
+ min: min.toString(),
2396
+ signed,
2397
+ size: size / 8,
2398
+ value: value.toString(),
2399
+ });
2400
+ }
2401
+ return {
2402
+ dynamic: false,
2403
+ encoded: numberToHex(value, {
2404
+ size: 32,
2405
+ signed,
2406
+ }),
2407
+ };
2408
+ }
2409
+ function encodeString(value) {
2410
+ const hexValue = stringToHex(value);
2411
+ const partsLength = Math.ceil(size(hexValue) / 32);
2412
+ const parts = [];
2413
+ for (let i = 0; i < partsLength; i++) {
2414
+ parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), {
2415
+ dir: 'right',
2416
+ }));
2417
+ }
2418
+ return {
2419
+ dynamic: true,
2420
+ encoded: concat([
2421
+ padHex(numberToHex(size(hexValue), { size: 32 })),
2422
+ ...parts,
2423
+ ]),
2424
+ };
2425
+ }
2426
+ function encodeTuple(value, { param }) {
2427
+ let dynamic = false;
2428
+ const preparedParams = [];
2429
+ for (let i = 0; i < param.components.length; i++) {
2430
+ const param_ = param.components[i];
2431
+ const index = Array.isArray(value) ? i : param_.name;
2432
+ const preparedParam = prepareParam({
2433
+ param: param_,
2434
+ value: value[index],
2435
+ });
2436
+ preparedParams.push(preparedParam);
2437
+ if (preparedParam.dynamic)
2438
+ dynamic = true;
2439
+ }
2440
+ return {
2441
+ dynamic,
2442
+ encoded: dynamic
2443
+ ? encodeParams(preparedParams)
2444
+ : concat(preparedParams.map(({ encoded }) => encoded)),
2445
+ };
2446
+ }
2447
+ function getArrayComponents(type) {
2448
+ const matches = type.match(/^(.*)\[(\d+)?\]$/);
2449
+ return matches
2450
+ ? // Return `null` if the array is dynamic.
2451
+ [matches[2] ? Number(matches[2]) : null, matches[1]]
2452
+ : undefined;
2453
+ }
2454
+
2455
+ /**
2456
+ * Returns the function selector for a given function definition.
2457
+ *
2458
+ * @example
2459
+ * const selector = toFunctionSelector('function ownerOf(uint256 tokenId)')
2460
+ * // 0x6352211e
2461
+ */
2462
+ const toFunctionSelector = (fn) => slice(toSignatureHash(fn), 0, 4);
2463
+
2464
+ function getAbiItem(parameters) {
2465
+ const { abi, args = [], name } = parameters;
2466
+ const isSelector = isHex(name, { strict: false });
2467
+ const abiItems = abi.filter((abiItem) => {
2468
+ if (isSelector) {
2469
+ if (abiItem.type === 'function')
2470
+ return toFunctionSelector(abiItem) === name;
2471
+ if (abiItem.type === 'event')
2472
+ return toEventSelector(abiItem) === name;
2473
+ return false;
2474
+ }
2475
+ return 'name' in abiItem && abiItem.name === name;
2476
+ });
2477
+ if (abiItems.length === 0)
2478
+ return undefined;
2479
+ if (abiItems.length === 1)
2480
+ return abiItems[0];
2481
+ let matchedAbiItem;
2482
+ for (const abiItem of abiItems) {
2483
+ if (!('inputs' in abiItem))
2484
+ continue;
2485
+ if (!args || args.length === 0) {
2486
+ if (!abiItem.inputs || abiItem.inputs.length === 0)
2487
+ return abiItem;
2488
+ continue;
2489
+ }
2490
+ if (!abiItem.inputs)
2491
+ continue;
2492
+ if (abiItem.inputs.length === 0)
2493
+ continue;
2494
+ if (abiItem.inputs.length !== args.length)
2495
+ continue;
2496
+ const matched = args.every((arg, index) => {
2497
+ const abiParameter = 'inputs' in abiItem && abiItem.inputs[index];
2498
+ if (!abiParameter)
2499
+ return false;
2500
+ return isArgOfType(arg, abiParameter);
2501
+ });
2502
+ if (matched) {
2503
+ // Check for ambiguity against already matched parameters (e.g. `address` vs `bytes20`).
2504
+ if (matchedAbiItem &&
2505
+ 'inputs' in matchedAbiItem &&
2506
+ matchedAbiItem.inputs) {
2507
+ const ambiguousTypes = getAmbiguousTypes(abiItem.inputs, matchedAbiItem.inputs, args);
2508
+ if (ambiguousTypes)
2509
+ throw new AbiItemAmbiguityError({
2510
+ abiItem,
2511
+ type: ambiguousTypes[0],
2512
+ }, {
2513
+ abiItem: matchedAbiItem,
2514
+ type: ambiguousTypes[1],
2515
+ });
2516
+ }
2517
+ matchedAbiItem = abiItem;
2518
+ }
2519
+ }
2520
+ if (matchedAbiItem)
2521
+ return matchedAbiItem;
2522
+ return abiItems[0];
2523
+ }
2524
+ /** @internal */
2525
+ function isArgOfType(arg, abiParameter) {
2526
+ const argType = typeof arg;
2527
+ const abiParameterType = abiParameter.type;
2528
+ switch (abiParameterType) {
2529
+ case 'address':
2530
+ return isAddress(arg, { strict: false });
2531
+ case 'bool':
2532
+ return argType === 'boolean';
2533
+ case 'function':
2534
+ return argType === 'string';
2535
+ case 'string':
2536
+ return argType === 'string';
2537
+ default: {
2538
+ if (abiParameterType === 'tuple' && 'components' in abiParameter)
2539
+ return Object.values(abiParameter.components).every((component, index) => {
2540
+ return (argType === 'object' &&
2541
+ isArgOfType(Object.values(arg)[index], component));
2542
+ });
2543
+ // `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`
2544
+ // https://regexr.com/6v8hp
2545
+ if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType))
2546
+ return argType === 'number' || argType === 'bigint';
2547
+ // `bytes<M>`: binary type of `M` bytes, `0 < M <= 32`
2548
+ // https://regexr.com/6va55
2549
+ if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType))
2550
+ return argType === 'string' || arg instanceof Uint8Array;
2551
+ // fixed-length (`<type>[M]`) and dynamic (`<type>[]`) arrays
2552
+ // https://regexr.com/6va6i
2553
+ if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) {
2554
+ return (Array.isArray(arg) &&
2555
+ arg.every((x) => isArgOfType(x, {
2556
+ ...abiParameter,
2557
+ // Pop off `[]` or `[M]` from end of type
2558
+ type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, ''),
2559
+ })));
2560
+ }
2561
+ return false;
2562
+ }
2563
+ }
2564
+ }
2565
+ /** @internal */
2566
+ function getAmbiguousTypes(sourceParameters, targetParameters, args) {
2567
+ for (const parameterIndex in sourceParameters) {
2568
+ const sourceParameter = sourceParameters[parameterIndex];
2569
+ const targetParameter = targetParameters[parameterIndex];
2570
+ if (sourceParameter.type === 'tuple' &&
2571
+ targetParameter.type === 'tuple' &&
2572
+ 'components' in sourceParameter &&
2573
+ 'components' in targetParameter)
2574
+ return getAmbiguousTypes(sourceParameter.components, targetParameter.components, args[parameterIndex]);
2575
+ const types = [sourceParameter.type, targetParameter.type];
2576
+ const ambiguous = (() => {
2577
+ if (types.includes('address') && types.includes('bytes20'))
2578
+ return true;
2579
+ if (types.includes('address') && types.includes('string'))
2580
+ return isAddress(args[parameterIndex], { strict: false });
2581
+ if (types.includes('address') && types.includes('bytes'))
2582
+ return isAddress(args[parameterIndex], { strict: false });
2583
+ return false;
2584
+ })();
2585
+ if (ambiguous)
2586
+ return types;
2587
+ }
2588
+ return;
2589
+ }
2590
+
2591
+ const docsPath = '/docs/contract/encodeFunctionData';
2592
+ function prepareEncodeFunctionData(parameters) {
2593
+ const { abi, args, functionName } = parameters;
2594
+ let abiItem = abi[0];
2595
+ if (functionName) {
2596
+ const item = getAbiItem({
2597
+ abi,
2598
+ args,
2599
+ name: functionName,
2600
+ });
2601
+ if (!item)
2602
+ throw new AbiFunctionNotFoundError(functionName, { docsPath });
2603
+ abiItem = item;
2604
+ }
2605
+ if (abiItem.type !== 'function')
2606
+ throw new AbiFunctionNotFoundError(undefined, { docsPath });
2607
+ return {
2608
+ abi: [abiItem],
2609
+ functionName: toFunctionSelector(formatAbiItem(abiItem)),
2610
+ };
2611
+ }
2612
+
2613
+ function encodeFunctionData(parameters) {
2614
+ const { args } = parameters;
2615
+ const { abi, functionName } = (() => {
2616
+ if (parameters.abi.length === 1 &&
2617
+ parameters.functionName?.startsWith('0x'))
2618
+ return parameters;
2619
+ return prepareEncodeFunctionData(parameters);
2620
+ })();
2621
+ const abiItem = abi[0];
2622
+ const signature = functionName;
2623
+ const data = 'inputs' in abiItem && abiItem.inputs
2624
+ ? encodeAbiParameters(abiItem.inputs, args ?? [])
2625
+ : undefined;
2626
+ return concatHex([signature, data ?? '0x']);
2627
+ }
2628
+
2629
+ const ZERO_ADDRESS$1 = "0x0000000000000000000000000000000000000000";
2630
+ const PAYMENT_ABI = parseAbi([
2631
+ "function createPayment(bytes32 paymentId, string vendorId, address token, uint256 amount, uint256 deadline, bytes backendSignature) external payable",
2632
+ ]);
2633
+ const ERC20_ABI = parseAbi([
2634
+ "function allowance(address owner, address spender) view returns (uint256)",
2635
+ "function approve(address spender, uint256 amount) returns (bool)",
2636
+ ]);
2637
+ function ensure0x(hex) {
2638
+ return (hex.startsWith("0x") ? hex : `0x${hex}`);
2639
+ }
2640
+ class ContractService {
2641
+ constructor(provider) {
2642
+ this.provider = provider;
2643
+ }
2644
+ async getAddress() {
2645
+ const accounts = (await this.provider.request({
2646
+ method: "eth_requestAccounts",
2647
+ }));
2648
+ if (!accounts[0]) {
2649
+ throw new KwesPayError("No wallet account available", "WALLET_REJECTED");
2650
+ }
2651
+ return accounts[0];
2652
+ }
2653
+ async waitForReceipt(txHash, timeoutMs = 120000) {
2654
+ const deadline = Date.now() + timeoutMs;
2655
+ while (Date.now() < deadline) {
2656
+ const receipt = (await this.provider.request({
2657
+ method: "eth_getTransactionReceipt",
2658
+ params: [txHash],
2659
+ }));
2660
+ if (receipt) {
2661
+ return {
2662
+ blockNumber: parseInt(receipt.blockNumber, 16),
2663
+ status: parseInt(receipt.status, 16),
2664
+ };
2665
+ }
2666
+ await new Promise((r) => setTimeout(r, 2000));
2667
+ }
2668
+ throw new KwesPayError("Transaction receipt timeout — check wallet or block explorer", "CONTRACT_ERROR");
2669
+ }
2670
+ async ensureApproval(tokenAddress, amountBaseUnits, contractAddress, chainId, onStatus) {
2671
+ if (tokenAddress === ZERO_ADDRESS$1)
2672
+ return;
2673
+ onStatus?.("Checking approval", "Verifying token allowance…");
2674
+ const owner = await this.getAddress();
2675
+ const amount = BigInt(amountBaseUnits);
2676
+ const allowanceData = encodeFunctionData({
2677
+ abi: ERC20_ABI,
2678
+ functionName: "allowance",
2679
+ args: [owner, ensure0x(contractAddress)],
2680
+ });
2681
+ const rawAllowance = (await this.provider.request({
2682
+ method: "eth_call",
2683
+ params: [{ to: ensure0x(tokenAddress), data: allowanceData }, "latest"],
2684
+ }));
2685
+ const allowance = rawAllowance && rawAllowance !== "0x" ? BigInt(rawAllowance) : 0n;
2686
+ if (allowance >= amount)
2687
+ return;
2688
+ onStatus?.("Approve token", "Please approve in your wallet");
2689
+ const approveData = encodeFunctionData({
2690
+ abi: ERC20_ABI,
2691
+ functionName: "approve",
2692
+ args: [ensure0x(contractAddress), amount * 2n],
2693
+ });
2694
+ let txHash;
2695
+ try {
2696
+ txHash = (await this.provider.request({
2697
+ method: "eth_sendTransaction",
2698
+ params: [
2699
+ { from: owner, to: ensure0x(tokenAddress), data: approveData },
2700
+ ],
2701
+ }));
2702
+ }
2703
+ catch (err) {
2704
+ const msg = err instanceof Error ? err.message : String(err);
2705
+ if (msg.includes("rejected") ||
2706
+ msg.includes("denied") ||
2707
+ msg.includes("ACTION_REJECTED")) {
2708
+ throw new KwesPayError("Token approval cancelled by user", "APPROVAL_REJECTED", err);
2709
+ }
2710
+ throw new KwesPayError(`Token approval failed: ${msg}`, "CONTRACT_ERROR", err);
2711
+ }
2712
+ onStatus?.("Waiting for approval", `Tx: ${txHash.slice(0, 10)}…`);
2713
+ const receipt = await this.waitForReceipt(txHash);
2714
+ if (receipt.status !== 1) {
2715
+ throw new KwesPayError("Approval transaction reverted", "CONTRACT_ERROR");
2716
+ }
2717
+ await new Promise((r) => setTimeout(r, 1000));
2718
+ }
2719
+ async createPayment(params, onStatus) {
2720
+ const from = await this.getAddress();
2721
+ const amount = BigInt(params.amountBaseUnits);
2722
+ const isNative = params.tokenAddress === ZERO_ADDRESS$1;
2723
+ const data = encodeFunctionData({
2724
+ abi: PAYMENT_ABI,
2725
+ functionName: "createPayment",
2726
+ args: [
2727
+ ensure0x(params.paymentIdBytes32),
2728
+ params.vendorIdentifier,
2729
+ ensure0x(params.tokenAddress),
2730
+ amount,
2731
+ BigInt(params.deadline),
2732
+ ensure0x(params.backendSignature),
2733
+ ],
2734
+ });
2735
+ onStatus?.("Confirm payment", "Please approve in your wallet");
2736
+ const txParams = {
2737
+ from,
2738
+ to: ensure0x(params.contractAddress),
2739
+ data,
2740
+ };
2741
+ if (isNative)
2742
+ txParams["value"] = `0x${(amount + (amount * 50n) / 10000n).toString(16)}`;
2743
+ let txHash;
2744
+ try {
2745
+ txHash = (await this.provider.request({
2746
+ method: "eth_sendTransaction",
2747
+ params: [txParams],
2748
+ }));
2749
+ }
2750
+ catch (err) {
2751
+ const msg = err instanceof Error ? err.message : String(err);
2752
+ if (msg.includes("rejected") ||
2753
+ msg.includes("denied") ||
2754
+ msg.includes("ACTION_REJECTED") ||
2755
+ msg.includes("User denied")) {
2756
+ throw new KwesPayError("Transaction cancelled by user", "WALLET_REJECTED", err);
2757
+ }
2758
+ throw new KwesPayError(`Contract call failed: ${msg}`, "CONTRACT_ERROR", err);
2759
+ }
2760
+ onStatus?.("Waiting for confirmation", `Tx: ${txHash.slice(0, 10)}…`);
2761
+ const receipt = await this.waitForReceipt(txHash);
2762
+ if (receipt.status !== 1) {
2763
+ throw new KwesPayError("Payment transaction reverted", "CONTRACT_ERROR");
2764
+ }
2765
+ return { txHash, blockNumber: receipt.blockNumber };
2766
+ }
2767
+ }
2768
+
2769
+ const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
2770
+ const GAS_BUFFER = 300000n * 2000000000n;
2771
+ class PaymentService {
2772
+ constructor(provider) {
2773
+ this.provider = provider;
2774
+ this.contractService = new ContractService(provider);
2775
+ }
2776
+ async ensureCorrectNetwork(expectedChainId, expectedNetwork, onStatus) {
2777
+ const raw = (await this.provider.request({
2778
+ method: "eth_chainId",
2779
+ }));
2780
+ const current = parseInt(raw, 16);
2781
+ if (current === expectedChainId)
2782
+ return;
2783
+ onStatus?.("Switching network", `Switching to ${expectedNetwork} (chain ${expectedChainId})…`);
2784
+ try {
2785
+ await this.provider.request({
2786
+ method: "wallet_switchEthereumChain",
2787
+ params: [{ chainId: "0x" + expectedChainId.toString(16) }],
2788
+ });
2789
+ }
2790
+ catch (switchErr) {
2791
+ const errAny = switchErr;
2792
+ if (errAny?.code === 4902) {
2793
+ throw new KwesPayError(`Network ${expectedNetwork} (chain ${expectedChainId}) is not added to your wallet. Please add it manually and retry.`, "WRONG_NETWORK");
2794
+ }
2795
+ const msg = errAny?.message ?? String(switchErr);
2796
+ if (msg.includes("rejected") ||
2797
+ msg.includes("denied") ||
2798
+ msg.includes("ACTION_REJECTED")) {
2799
+ throw new KwesPayError(`Network switch to ${expectedNetwork} was rejected. Please switch manually and retry.`, "WRONG_NETWORK");
2800
+ }
2801
+ throw new KwesPayError(`Failed to switch to ${expectedNetwork}: ${msg}`, "WRONG_NETWORK");
2802
+ }
2803
+ const confirmedRaw = (await this.provider.request({
2804
+ method: "eth_chainId",
2805
+ }));
2806
+ const confirmed = parseInt(confirmedRaw, 16);
2807
+ if (confirmed !== expectedChainId) {
2808
+ throw new KwesPayError(`Wallet is on chain ${confirmed} but payment requires chain ${expectedChainId} (${expectedNetwork}). Please switch your network and retry.`, "WRONG_NETWORK");
2809
+ }
2810
+ }
2811
+ async ensureSufficientBalance(walletAddress, tokenAddress, totalBaseUnits, onStatus) {
2812
+ const total = BigInt(totalBaseUnits);
2813
+ const isNative = tokenAddress === ZERO_ADDRESS;
2814
+ onStatus?.("Checking balance", "Verifying wallet balance…");
2815
+ const nativeRaw = (await this.provider.request({
2816
+ method: "eth_getBalance",
2817
+ params: [walletAddress, "latest"],
2818
+ }));
2819
+ const nativeBalance = nativeRaw && nativeRaw !== "0x" ? BigInt(nativeRaw) : 0n;
2820
+ if (isNative) {
2821
+ const required = total + GAS_BUFFER;
2822
+ if (nativeBalance < required) {
2823
+ throw new KwesPayError(`Insufficient native balance. Required ~${(Number(required) / 1e18).toFixed(8)} (payment + fee + gas), available: ${(Number(nativeBalance) / 1e18).toFixed(8)}.`, "INSUFFICIENT_BALANCE");
2824
+ }
2825
+ return;
2826
+ }
2827
+ if (nativeBalance < GAS_BUFFER) {
2828
+ throw new KwesPayError(`Insufficient gas balance. Need at least ${(Number(GAS_BUFFER) / 1e18).toFixed(8)} for gas, available: ${(Number(nativeBalance) / 1e18).toFixed(8)}.`, "INSUFFICIENT_BALANCE");
2829
+ }
2830
+ const balanceData = "0x70a08231" + walletAddress.slice(2).toLowerCase().padStart(64, "0");
2831
+ const raw = (await this.provider.request({
2832
+ method: "eth_call",
2833
+ params: [{ to: tokenAddress, data: balanceData }, "latest"],
2834
+ }));
2835
+ const tokenBalance = raw && raw !== "0x" ? BigInt(raw) : 0n;
2836
+ if (tokenBalance < total) {
2837
+ throw new KwesPayError(`Insufficient token balance. Required: ${total.toString()} (amount + fee), available: ${tokenBalance.toString()} (base units).`, "INSUFFICIENT_BALANCE");
2838
+ }
2839
+ }
2840
+ async pay(params) {
2841
+ const { payload, onStatus } = params;
2842
+ if (!payload.paymentIdBytes32 || !payload.backendSignature) {
2843
+ throw new KwesPayError("Invalid transaction payload — missing paymentIdBytes32 or backendSignature", "TRANSACTION_FAILED");
2844
+ }
2845
+ if (!payload.vendorIdentifier) {
2846
+ throw new KwesPayError("Invalid transaction payload — missing vendorIdentifier", "TRANSACTION_FAILED");
2847
+ }
2848
+ if (!payload.totalBaseUnits) {
2849
+ throw new KwesPayError("Invalid transaction payload — missing totalBaseUnits", "TRANSACTION_FAILED");
2850
+ }
2851
+ if (!payload.deadline) {
2852
+ throw new KwesPayError("Invalid transaction payload — missing deadline", "TRANSACTION_FAILED");
2853
+ }
2854
+ if (BigInt(payload.totalBaseUnits) < BigInt(payload.amountBaseUnits)) {
2855
+ throw new KwesPayError("Invalid transaction payload — totalBaseUnits cannot be less than amountBaseUnits", "TRANSACTION_FAILED");
2856
+ }
2857
+ await this.ensureCorrectNetwork(payload.chainId, payload.network, onStatus);
2858
+ const accounts = (await this.provider.request({
2859
+ method: "eth_requestAccounts",
2860
+ }));
2861
+ const walletAddress = accounts[0];
2862
+ await this.ensureSufficientBalance(walletAddress, payload.tokenAddress, payload.totalBaseUnits, onStatus);
2863
+ const contractAddress = resolveContractAddress(payload.network);
2864
+ await this.contractService.ensureApproval(payload.tokenAddress, payload.totalBaseUnits, contractAddress, payload.chainId, onStatus);
2865
+ const { txHash, blockNumber } = await this.contractService.createPayment({
2866
+ paymentIdBytes32: payload.paymentIdBytes32,
2867
+ vendorIdentifier: payload.vendorIdentifier,
2868
+ tokenAddress: payload.tokenAddress,
2869
+ amountBaseUnits: payload.amountBaseUnits,
2870
+ totalBaseUnits: payload.totalBaseUnits,
2871
+ backendSignature: payload.backendSignature,
2872
+ contractAddress,
2873
+ deadline: payload.deadline,
2874
+ chainId: payload.chainId,
2875
+ }, onStatus);
2876
+ return {
2877
+ txHash,
2878
+ blockNumber,
2879
+ transactionReference: payload.transactionReference,
2880
+ paymentIdBytes32: payload.paymentIdBytes32,
2881
+ };
2882
+ }
2883
+ }
2884
+
2885
+ const PLATFORM_FEE_BPS = 50n; // 0.5%
2886
+ const BASIS_POINTS = 10000n;
2887
+ function computeFee(amountBaseUnits) {
2888
+ return (BigInt(amountBaseUnits) * PLATFORM_FEE_BPS) / BASIS_POINTS;
2889
+ }
2890
+ function computeTotal(amountBaseUnits) {
2891
+ return (BigInt(amountBaseUnits) + computeFee(amountBaseUnits)).toString();
2892
+ }
2893
+ class KwesPayClient {
2894
+ constructor(config) {
2895
+ if (!config.apiKey)
2896
+ throw new KwesPayError("apiKey is required", "INVALID_KEY");
2897
+ this.apiKey = config.apiKey;
2898
+ }
2899
+ async validateKey() {
2900
+ const data = await gqlRequest(GQL_VALIDATE_KEY, {
2901
+ accessKey: this.apiKey,
2902
+ });
2903
+ const r = data.validateAccessKey;
2904
+ if (!r.isValid) {
2905
+ return {
2906
+ isValid: false,
2907
+ error: r.error ?? "Invalid access key",
2908
+ };
2909
+ }
2910
+ return {
2911
+ isValid: true,
2912
+ keyId: r.keyId,
2913
+ keyLabel: r.keyLabel,
2914
+ activeFlag: r.activeFlag,
2915
+ expirationDate: r.expirationDate,
2916
+ vendorInfo: r.vendorInfo,
2917
+ scope: {
2918
+ allowedVendors: r.allowedVendors ?? null,
2919
+ allowedNetworks: r.allowedNetworks ?? null,
2920
+ allowedTokens: r.allowedTokens ?? null,
2921
+ },
2922
+ };
2923
+ }
2924
+ // getQuote (price preview only — no transaction created)
2925
+ async getQuote(params) {
2926
+ const data = await gqlRequest(GQL_CREATE_QUOTE, {
2927
+ input: {
2928
+ vendorIdentifier: params.vendorIdentifier,
2929
+ fiatAmount: params.fiatAmount,
2930
+ fiatCurrency: params.fiatCurrency ?? "USD",
2931
+ cryptoCurrency: params.cryptoCurrency,
2932
+ network: params.network,
2933
+ },
2934
+ }, this.apiKey);
2935
+ const q = data.createQuote;
2936
+ if (!q.success) {
2937
+ const msg = q.message ?? "Quote creation failed";
2938
+ throw new KwesPayError(msg, _quoteErrCode(msg));
2939
+ }
2940
+ return {
2941
+ quoteId: q.quoteId,
2942
+ cryptoCurrency: q.cryptoCurrency,
2943
+ tokenAddress: q.tokenAddress,
2944
+ amountBaseUnits: q.amountBaseUnits,
2945
+ // totalBaseUnits = amountBaseUnits + fee — safe to compute here for UI
2946
+ totalBaseUnits: computeTotal(q.amountBaseUnits),
2947
+ displayAmount: q.displayAmount,
2948
+ network: q.network,
2949
+ chainId: q.chainId,
2950
+ expiresAt: q.expiresAt,
2951
+ };
2952
+ }
2953
+ // quote() — full flow: price + transaction, returns wallet-ready payload
2954
+ async quote(params) {
2955
+ // Step 1 — get price & lock quote
2956
+ const quoteData = await gqlRequest(GQL_CREATE_QUOTE, {
2957
+ input: {
2958
+ vendorIdentifier: params.vendorIdentifier,
2959
+ fiatAmount: params.fiatAmount,
2960
+ fiatCurrency: params.fiatCurrency ?? "USD",
2961
+ cryptoCurrency: params.cryptoCurrency,
2962
+ network: params.network,
2963
+ },
2964
+ }, this.apiKey);
2965
+ const q = quoteData.createQuote;
2966
+ if (!q.success) {
2967
+ const msg = q.message ?? "Quote creation failed";
2968
+ throw new KwesPayError(msg, _quoteErrCode(msg));
2969
+ }
2970
+ // Step 2 — create transaction (backend signs payment params incl. deadline)
2971
+ const txData = await gqlRequest(GQL_CREATE_TRANSACTION, {
2972
+ input: {
2973
+ quoteId: q.quoteId,
2974
+ payerWalletAddress: params.payerWalletAddress,
2975
+ },
2976
+ }, this.apiKey);
2977
+ const t = txData.createTransaction;
2978
+ if (!t.success) {
2979
+ const msg = t.message ?? "Transaction creation failed";
2980
+ throw new KwesPayError(msg, _txErrCode(msg));
2981
+ }
2982
+ // deadline must be present — it's part of the on-chain signature
2983
+ if (!t.deadline) {
2984
+ throw new KwesPayError("Backend did not return a deadline. Cannot construct a valid payment.", "TRANSACTION_FAILED");
2985
+ }
2986
+ // totalBaseUnits: what the customer must actually send (amount + fee).
2987
+ // We compute this from the signed amountBaseUnits using the same formula
2988
+ // the contract uses: (amount * 50) / 10000. We do NOT trust a
2989
+ // client-side totalBaseUnits for security — but computing it here is safe
2990
+ // because amountBaseUnits came from the backend-signed response.
2991
+ const amountBaseUnits = t.amountBaseUnits;
2992
+ const totalBaseUnits = computeTotal(amountBaseUnits);
2993
+ return {
2994
+ paymentIdBytes32: t.paymentIdBytes32,
2995
+ backendSignature: t.backendSignature,
2996
+ tokenAddress: t.tokenAddress,
2997
+ amountBaseUnits,
2998
+ totalBaseUnits,
2999
+ chainId: t.chainId,
3000
+ deadline: t.deadline, // ← from backend, part of signed hash
3001
+ expiresAt: t.expiresAt,
3002
+ transactionReference: t.transaction.transactionReference,
3003
+ transactionStatus: t.transaction.transactionStatus,
3004
+ network: params.network,
3005
+ vendorIdentifier: params.vendorIdentifier,
3006
+ };
3007
+ }
3008
+ // pay()
3009
+ async pay(params) {
3010
+ return new PaymentService(params.provider).pay(params);
3011
+ }
3012
+ // status polling
3013
+ async getTransactionStatus(transactionReference) {
3014
+ const data = await gqlRequest(GQL_TRANSACTION_STATUS, { transactionReference });
3015
+ const r = data.getTransactionStatus;
3016
+ return {
3017
+ transactionReference: r.transactionReference,
3018
+ transactionStatus: r.transactionStatus,
3019
+ blockchainHash: r.blockchainHash,
3020
+ blockchainNetwork: r.blockchainNetwork,
3021
+ displayAmount: r.displayAmount,
3022
+ cryptoCurrency: r.cryptoCurrency,
3023
+ payerWalletAddress: r.payerWalletAddress,
3024
+ initiatedAt: r.initiatedAt,
3025
+ };
3026
+ }
3027
+ async pollTransactionStatus(transactionReference, options = {}) {
3028
+ const { onStatus, intervalMs = 4000, maxAttempts = 60 } = options;
3029
+ let attempts = 0;
3030
+ const terminal = [
3031
+ "completed",
3032
+ "failed",
3033
+ "expired",
3034
+ "underpaid",
3035
+ "overpaid",
3036
+ "refunded",
3037
+ ];
3038
+ return new Promise((resolve, reject) => {
3039
+ const id = setInterval(async () => {
3040
+ attempts++;
3041
+ try {
3042
+ const status = await this.getTransactionStatus(transactionReference);
3043
+ onStatus?.(status.transactionStatus);
3044
+ if (terminal.includes(status.transactionStatus)) {
3045
+ clearInterval(id);
3046
+ resolve(status);
3047
+ }
3048
+ else if (attempts >= maxAttempts) {
3049
+ clearInterval(id);
3050
+ reject(new KwesPayError("Status polling timed out", "UNKNOWN"));
3051
+ }
3052
+ }
3053
+ catch (err) {
3054
+ if (attempts >= maxAttempts) {
3055
+ clearInterval(id);
3056
+ reject(err);
3057
+ }
3058
+ }
3059
+ }, intervalMs);
3060
+ });
3061
+ }
3062
+ }
3063
+ // Error code helpers
3064
+ function _quoteErrCode(msg) {
3065
+ const m = msg.toLowerCase();
3066
+ if (m.includes("expired"))
3067
+ return "QUOTE_EXPIRED";
3068
+ if (m.includes("key"))
3069
+ return "INVALID_KEY";
3070
+ return "UNKNOWN";
3071
+ }
3072
+ function _txErrCode(msg) {
3073
+ const m = msg.toLowerCase();
3074
+ if (m.includes("expired"))
3075
+ return "QUOTE_EXPIRED";
3076
+ if (m.includes("already been used"))
3077
+ return "QUOTE_USED";
3078
+ if (m.includes("not found"))
3079
+ return "QUOTE_NOT_FOUND";
3080
+ if (m.includes("key"))
3081
+ return "INVALID_KEY";
3082
+ return "UNKNOWN";
3083
+ }
3084
+
3085
+ export { KwesPayClient, KwesPayError };