@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,2530 @@
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://149b-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
+ // TODO: This looks cool. Need to check the performance of `new RegExp` versus defined inline though.
136
+ // https://twitter.com/GabrielVergnaud/status/1622906834343366657
137
+ function execTyped(regex, string) {
138
+ const match = regex.exec(string);
139
+ return match?.groups;
140
+ }
141
+
142
+ // https://regexr.com/7f7rv
143
+ const tupleRegex = /^tuple(?<array>(\[(\d*)\])*)$/;
144
+ /**
145
+ * Formats {@link AbiParameter} to human-readable ABI parameter.
146
+ *
147
+ * @param abiParameter - ABI parameter
148
+ * @returns Human-readable ABI parameter
149
+ *
150
+ * @example
151
+ * const result = formatAbiParameter({ type: 'address', name: 'from' })
152
+ * // ^? const result: 'address from'
153
+ */
154
+ function formatAbiParameter(abiParameter) {
155
+ let type = abiParameter.type;
156
+ if (tupleRegex.test(abiParameter.type) && 'components' in abiParameter) {
157
+ type = '(';
158
+ const length = abiParameter.components.length;
159
+ for (let i = 0; i < length; i++) {
160
+ const component = abiParameter.components[i];
161
+ type += formatAbiParameter(component);
162
+ if (i < length - 1)
163
+ type += ', ';
164
+ }
165
+ const result = execTyped(tupleRegex, abiParameter.type);
166
+ type += `)${result?.array || ''}`;
167
+ return formatAbiParameter({
168
+ ...abiParameter,
169
+ type,
170
+ });
171
+ }
172
+ // Add `indexed` to type if in `abiParameter`
173
+ if ('indexed' in abiParameter && abiParameter.indexed)
174
+ type = `${type} indexed`;
175
+ // Return human-readable ABI parameter
176
+ if (abiParameter.name)
177
+ return `${type} ${abiParameter.name}`;
178
+ return type;
179
+ }
180
+
181
+ /**
182
+ * Formats {@link AbiParameter}s to human-readable ABI parameters.
183
+ *
184
+ * @param abiParameters - ABI parameters
185
+ * @returns Human-readable ABI parameters
186
+ *
187
+ * @example
188
+ * const result = formatAbiParameters([
189
+ * // ^? const result: 'address from, uint256 tokenId'
190
+ * { type: 'address', name: 'from' },
191
+ * { type: 'uint256', name: 'tokenId' },
192
+ * ])
193
+ */
194
+ function formatAbiParameters(abiParameters) {
195
+ let params = '';
196
+ const length = abiParameters.length;
197
+ for (let i = 0; i < length; i++) {
198
+ const abiParameter = abiParameters[i];
199
+ params += formatAbiParameter(abiParameter);
200
+ if (i !== length - 1)
201
+ params += ', ';
202
+ }
203
+ return params;
204
+ }
205
+
206
+ /**
207
+ * Formats ABI item (e.g. error, event, function) into human-readable ABI item
208
+ *
209
+ * @param abiItem - ABI item
210
+ * @returns Human-readable ABI item
211
+ */
212
+ function formatAbiItem$1(abiItem) {
213
+ if (abiItem.type === 'function')
214
+ return `function ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability && abiItem.stateMutability !== 'nonpayable'
215
+ ? ` ${abiItem.stateMutability}`
216
+ : ''}${abiItem.outputs?.length
217
+ ? ` returns (${formatAbiParameters(abiItem.outputs)})`
218
+ : ''}`;
219
+ if (abiItem.type === 'event')
220
+ return `event ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`;
221
+ if (abiItem.type === 'error')
222
+ return `error ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`;
223
+ if (abiItem.type === 'constructor')
224
+ return `constructor(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability === 'payable' ? ' payable' : ''}`;
225
+ if (abiItem.type === 'fallback')
226
+ return `fallback() external${abiItem.stateMutability === 'payable' ? ' payable' : ''}`;
227
+ return 'receive() external payable';
228
+ }
229
+
230
+ function formatAbiItem(abiItem, { includeName = false } = {}) {
231
+ if (abiItem.type !== 'function' &&
232
+ abiItem.type !== 'event' &&
233
+ abiItem.type !== 'error')
234
+ throw new InvalidDefinitionTypeError(abiItem.type);
235
+ return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`;
236
+ }
237
+ function formatAbiParams(params, { includeName = false } = {}) {
238
+ if (!params)
239
+ return '';
240
+ return params
241
+ .map((param) => formatAbiParam(param, { includeName }))
242
+ .join(includeName ? ', ' : ',');
243
+ }
244
+ function formatAbiParam(param, { includeName }) {
245
+ if (param.type.startsWith('tuple')) {
246
+ return `(${formatAbiParams(param.components, { includeName })})${param.type.slice('tuple'.length)}`;
247
+ }
248
+ return param.type + (includeName && param.name ? ` ${param.name}` : '');
249
+ }
250
+
251
+ function isHex(value, { strict = true } = {}) {
252
+ if (!value)
253
+ return false;
254
+ if (typeof value !== 'string')
255
+ return false;
256
+ return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith('0x');
257
+ }
258
+
259
+ /**
260
+ * @description Retrieves the size of the value (in bytes).
261
+ *
262
+ * @param value The value (hex or byte array) to retrieve the size of.
263
+ * @returns The size of the value (in bytes).
264
+ */
265
+ function size(value) {
266
+ if (isHex(value, { strict: false }))
267
+ return Math.ceil((value.length - 2) / 2);
268
+ return value.length;
269
+ }
270
+
271
+ const version = '2.47.10';
272
+
273
+ let errorConfig = {
274
+ getDocsUrl: ({ docsBaseUrl, docsPath = '', docsSlug, }) => docsPath
275
+ ? `${docsBaseUrl ?? 'https://viem.sh'}${docsPath}${docsSlug ? `#${docsSlug}` : ''}`
276
+ : undefined,
277
+ version: `viem@${version}`,
278
+ };
279
+ class BaseError extends Error {
280
+ constructor(shortMessage, args = {}) {
281
+ const details = (() => {
282
+ if (args.cause instanceof BaseError)
283
+ return args.cause.details;
284
+ if (args.cause?.message)
285
+ return args.cause.message;
286
+ return args.details;
287
+ })();
288
+ const docsPath = (() => {
289
+ if (args.cause instanceof BaseError)
290
+ return args.cause.docsPath || args.docsPath;
291
+ return args.docsPath;
292
+ })();
293
+ const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath });
294
+ const message = [
295
+ shortMessage || 'An error occurred.',
296
+ '',
297
+ ...(args.metaMessages ? [...args.metaMessages, ''] : []),
298
+ ...(docsUrl ? [`Docs: ${docsUrl}`] : []),
299
+ ...(details ? [`Details: ${details}`] : []),
300
+ ...(errorConfig.version ? [`Version: ${errorConfig.version}`] : []),
301
+ ].join('\n');
302
+ super(message, args.cause ? { cause: args.cause } : undefined);
303
+ Object.defineProperty(this, "details", {
304
+ enumerable: true,
305
+ configurable: true,
306
+ writable: true,
307
+ value: void 0
308
+ });
309
+ Object.defineProperty(this, "docsPath", {
310
+ enumerable: true,
311
+ configurable: true,
312
+ writable: true,
313
+ value: void 0
314
+ });
315
+ Object.defineProperty(this, "metaMessages", {
316
+ enumerable: true,
317
+ configurable: true,
318
+ writable: true,
319
+ value: void 0
320
+ });
321
+ Object.defineProperty(this, "shortMessage", {
322
+ enumerable: true,
323
+ configurable: true,
324
+ writable: true,
325
+ value: void 0
326
+ });
327
+ Object.defineProperty(this, "version", {
328
+ enumerable: true,
329
+ configurable: true,
330
+ writable: true,
331
+ value: void 0
332
+ });
333
+ Object.defineProperty(this, "name", {
334
+ enumerable: true,
335
+ configurable: true,
336
+ writable: true,
337
+ value: 'BaseError'
338
+ });
339
+ this.details = details;
340
+ this.docsPath = docsPath;
341
+ this.metaMessages = args.metaMessages;
342
+ this.name = args.name ?? this.name;
343
+ this.shortMessage = shortMessage;
344
+ this.version = version;
345
+ }
346
+ walk(fn) {
347
+ return walk(this, fn);
348
+ }
349
+ }
350
+ function walk(err, fn) {
351
+ if (fn?.(err))
352
+ return err;
353
+ if (err &&
354
+ typeof err === 'object' &&
355
+ 'cause' in err &&
356
+ err.cause !== undefined)
357
+ return walk(err.cause, fn);
358
+ return fn ? null : err;
359
+ }
360
+
361
+ class AbiEncodingArrayLengthMismatchError extends BaseError {
362
+ constructor({ expectedLength, givenLength, type, }) {
363
+ super([
364
+ `ABI encoding array length mismatch for type ${type}.`,
365
+ `Expected length: ${expectedLength}`,
366
+ `Given length: ${givenLength}`,
367
+ ].join('\n'), { name: 'AbiEncodingArrayLengthMismatchError' });
368
+ }
369
+ }
370
+ class AbiEncodingBytesSizeMismatchError extends BaseError {
371
+ constructor({ expectedSize, value }) {
372
+ super(`Size of bytes "${value}" (bytes${size(value)}) does not match expected size (bytes${expectedSize}).`, { name: 'AbiEncodingBytesSizeMismatchError' });
373
+ }
374
+ }
375
+ class AbiEncodingLengthMismatchError extends BaseError {
376
+ constructor({ expectedLength, givenLength, }) {
377
+ super([
378
+ 'ABI encoding params/values length mismatch.',
379
+ `Expected length (params): ${expectedLength}`,
380
+ `Given length (values): ${givenLength}`,
381
+ ].join('\n'), { name: 'AbiEncodingLengthMismatchError' });
382
+ }
383
+ }
384
+ class AbiFunctionNotFoundError extends BaseError {
385
+ constructor(functionName, { docsPath } = {}) {
386
+ super([
387
+ `Function ${functionName ? `"${functionName}" ` : ''}not found on ABI.`,
388
+ 'Make sure you are using the correct ABI and that the function exists on it.',
389
+ ].join('\n'), {
390
+ docsPath,
391
+ name: 'AbiFunctionNotFoundError',
392
+ });
393
+ }
394
+ }
395
+ class AbiItemAmbiguityError extends BaseError {
396
+ constructor(x, y) {
397
+ super('Found ambiguous types in overloaded ABI items.', {
398
+ metaMessages: [
399
+ `\`${x.type}\` in \`${formatAbiItem(x.abiItem)}\`, and`,
400
+ `\`${y.type}\` in \`${formatAbiItem(y.abiItem)}\``,
401
+ '',
402
+ 'These types encode differently and cannot be distinguished at runtime.',
403
+ 'Remove one of the ambiguous items in the ABI.',
404
+ ],
405
+ name: 'AbiItemAmbiguityError',
406
+ });
407
+ }
408
+ }
409
+ class InvalidAbiEncodingTypeError extends BaseError {
410
+ constructor(type, { docsPath }) {
411
+ super([
412
+ `Type "${type}" is not a valid encoding type.`,
413
+ 'Please provide a valid ABI type.',
414
+ ].join('\n'), { docsPath, name: 'InvalidAbiEncodingType' });
415
+ }
416
+ }
417
+ class InvalidArrayError extends BaseError {
418
+ constructor(value) {
419
+ super([`Value "${value}" is not a valid array.`].join('\n'), {
420
+ name: 'InvalidArrayError',
421
+ });
422
+ }
423
+ }
424
+ class InvalidDefinitionTypeError extends BaseError {
425
+ constructor(type) {
426
+ super([
427
+ `"${type}" is not a valid definition type.`,
428
+ 'Valid types: "function", "event", "error"',
429
+ ].join('\n'), { name: 'InvalidDefinitionTypeError' });
430
+ }
431
+ }
432
+
433
+ class SliceOffsetOutOfBoundsError extends BaseError {
434
+ constructor({ offset, position, size, }) {
435
+ super(`Slice ${position === 'start' ? 'starting' : 'ending'} at offset "${offset}" is out-of-bounds (size: ${size}).`, { name: 'SliceOffsetOutOfBoundsError' });
436
+ }
437
+ }
438
+ class SizeExceedsPaddingSizeError extends BaseError {
439
+ constructor({ size, targetSize, type, }) {
440
+ super(`${type.charAt(0).toUpperCase()}${type
441
+ .slice(1)
442
+ .toLowerCase()} size (${size}) exceeds padding size (${targetSize}).`, { name: 'SizeExceedsPaddingSizeError' });
443
+ }
444
+ }
445
+
446
+ function pad(hexOrBytes, { dir, size = 32 } = {}) {
447
+ if (typeof hexOrBytes === 'string')
448
+ return padHex(hexOrBytes, { dir, size });
449
+ return padBytes(hexOrBytes, { dir, size });
450
+ }
451
+ function padHex(hex_, { dir, size = 32 } = {}) {
452
+ if (size === null)
453
+ return hex_;
454
+ const hex = hex_.replace('0x', '');
455
+ if (hex.length > size * 2)
456
+ throw new SizeExceedsPaddingSizeError({
457
+ size: Math.ceil(hex.length / 2),
458
+ targetSize: size,
459
+ type: 'hex',
460
+ });
461
+ return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}`;
462
+ }
463
+ function padBytes(bytes, { dir, size = 32 } = {}) {
464
+ if (size === null)
465
+ return bytes;
466
+ if (bytes.length > size)
467
+ throw new SizeExceedsPaddingSizeError({
468
+ size: bytes.length,
469
+ targetSize: size,
470
+ type: 'bytes',
471
+ });
472
+ const paddedBytes = new Uint8Array(size);
473
+ for (let i = 0; i < size; i++) {
474
+ const padEnd = dir === 'right';
475
+ paddedBytes[padEnd ? i : size - i - 1] =
476
+ bytes[padEnd ? i : bytes.length - i - 1];
477
+ }
478
+ return paddedBytes;
479
+ }
480
+
481
+ class IntegerOutOfRangeError extends BaseError {
482
+ constructor({ max, min, signed, size, value, }) {
483
+ super(`Number "${value}" is not in safe ${size ? `${size * 8}-bit ${signed ? 'signed' : 'unsigned'} ` : ''}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: 'IntegerOutOfRangeError' });
484
+ }
485
+ }
486
+ class SizeOverflowError extends BaseError {
487
+ constructor({ givenSize, maxSize }) {
488
+ super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: 'SizeOverflowError' });
489
+ }
490
+ }
491
+
492
+ function assertSize(hexOrBytes, { size: size$1 }) {
493
+ if (size(hexOrBytes) > size$1)
494
+ throw new SizeOverflowError({
495
+ givenSize: size(hexOrBytes),
496
+ maxSize: size$1,
497
+ });
498
+ }
499
+
500
+ const hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, '0'));
501
+ /**
502
+ * Encodes a string, number, bigint, or ByteArray into a hex string
503
+ *
504
+ * - Docs: https://viem.sh/docs/utilities/toHex
505
+ * - Example: https://viem.sh/docs/utilities/toHex#usage
506
+ *
507
+ * @param value Value to encode.
508
+ * @param opts Options.
509
+ * @returns Hex value.
510
+ *
511
+ * @example
512
+ * import { toHex } from 'viem'
513
+ * const data = toHex('Hello world')
514
+ * // '0x48656c6c6f20776f726c6421'
515
+ *
516
+ * @example
517
+ * import { toHex } from 'viem'
518
+ * const data = toHex(420)
519
+ * // '0x1a4'
520
+ *
521
+ * @example
522
+ * import { toHex } from 'viem'
523
+ * const data = toHex('Hello world', { size: 32 })
524
+ * // '0x48656c6c6f20776f726c64210000000000000000000000000000000000000000'
525
+ */
526
+ function toHex(value, opts = {}) {
527
+ if (typeof value === 'number' || typeof value === 'bigint')
528
+ return numberToHex(value, opts);
529
+ if (typeof value === 'string') {
530
+ return stringToHex(value, opts);
531
+ }
532
+ if (typeof value === 'boolean')
533
+ return boolToHex(value, opts);
534
+ return bytesToHex(value, opts);
535
+ }
536
+ /**
537
+ * Encodes a boolean into a hex string
538
+ *
539
+ * - Docs: https://viem.sh/docs/utilities/toHex#booltohex
540
+ *
541
+ * @param value Value to encode.
542
+ * @param opts Options.
543
+ * @returns Hex value.
544
+ *
545
+ * @example
546
+ * import { boolToHex } from 'viem'
547
+ * const data = boolToHex(true)
548
+ * // '0x1'
549
+ *
550
+ * @example
551
+ * import { boolToHex } from 'viem'
552
+ * const data = boolToHex(false)
553
+ * // '0x0'
554
+ *
555
+ * @example
556
+ * import { boolToHex } from 'viem'
557
+ * const data = boolToHex(true, { size: 32 })
558
+ * // '0x0000000000000000000000000000000000000000000000000000000000000001'
559
+ */
560
+ function boolToHex(value, opts = {}) {
561
+ const hex = `0x${Number(value)}`;
562
+ if (typeof opts.size === 'number') {
563
+ assertSize(hex, { size: opts.size });
564
+ return pad(hex, { size: opts.size });
565
+ }
566
+ return hex;
567
+ }
568
+ /**
569
+ * Encodes a bytes array into a hex string
570
+ *
571
+ * - Docs: https://viem.sh/docs/utilities/toHex#bytestohex
572
+ *
573
+ * @param value Value to encode.
574
+ * @param opts Options.
575
+ * @returns Hex value.
576
+ *
577
+ * @example
578
+ * import { bytesToHex } from 'viem'
579
+ * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
580
+ * // '0x48656c6c6f20576f726c6421'
581
+ *
582
+ * @example
583
+ * import { bytesToHex } from 'viem'
584
+ * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]), { size: 32 })
585
+ * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'
586
+ */
587
+ function bytesToHex(value, opts = {}) {
588
+ let string = '';
589
+ for (let i = 0; i < value.length; i++) {
590
+ string += hexes[value[i]];
591
+ }
592
+ const hex = `0x${string}`;
593
+ if (typeof opts.size === 'number') {
594
+ assertSize(hex, { size: opts.size });
595
+ return pad(hex, { dir: 'right', size: opts.size });
596
+ }
597
+ return hex;
598
+ }
599
+ /**
600
+ * Encodes a number or bigint into a hex string
601
+ *
602
+ * - Docs: https://viem.sh/docs/utilities/toHex#numbertohex
603
+ *
604
+ * @param value Value to encode.
605
+ * @param opts Options.
606
+ * @returns Hex value.
607
+ *
608
+ * @example
609
+ * import { numberToHex } from 'viem'
610
+ * const data = numberToHex(420)
611
+ * // '0x1a4'
612
+ *
613
+ * @example
614
+ * import { numberToHex } from 'viem'
615
+ * const data = numberToHex(420, { size: 32 })
616
+ * // '0x00000000000000000000000000000000000000000000000000000000000001a4'
617
+ */
618
+ function numberToHex(value_, opts = {}) {
619
+ const { signed, size } = opts;
620
+ const value = BigInt(value_);
621
+ let maxValue;
622
+ if (size) {
623
+ if (signed)
624
+ maxValue = (1n << (BigInt(size) * 8n - 1n)) - 1n;
625
+ else
626
+ maxValue = 2n ** (BigInt(size) * 8n) - 1n;
627
+ }
628
+ else if (typeof value_ === 'number') {
629
+ maxValue = BigInt(Number.MAX_SAFE_INTEGER);
630
+ }
631
+ const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0;
632
+ if ((maxValue && value > maxValue) || value < minValue) {
633
+ const suffix = typeof value_ === 'bigint' ? 'n' : '';
634
+ throw new IntegerOutOfRangeError({
635
+ max: maxValue ? `${maxValue}${suffix}` : undefined,
636
+ min: `${minValue}${suffix}`,
637
+ signed,
638
+ size,
639
+ value: `${value_}${suffix}`,
640
+ });
641
+ }
642
+ const hex = `0x${(signed && value < 0 ? (1n << BigInt(size * 8)) + BigInt(value) : value).toString(16)}`;
643
+ if (size)
644
+ return pad(hex, { size });
645
+ return hex;
646
+ }
647
+ const encoder$1 = /*#__PURE__*/ new TextEncoder();
648
+ /**
649
+ * Encodes a UTF-8 string into a hex string
650
+ *
651
+ * - Docs: https://viem.sh/docs/utilities/toHex#stringtohex
652
+ *
653
+ * @param value Value to encode.
654
+ * @param opts Options.
655
+ * @returns Hex value.
656
+ *
657
+ * @example
658
+ * import { stringToHex } from 'viem'
659
+ * const data = stringToHex('Hello World!')
660
+ * // '0x48656c6c6f20576f726c6421'
661
+ *
662
+ * @example
663
+ * import { stringToHex } from 'viem'
664
+ * const data = stringToHex('Hello World!', { size: 32 })
665
+ * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'
666
+ */
667
+ function stringToHex(value_, opts = {}) {
668
+ const value = encoder$1.encode(value_);
669
+ return bytesToHex(value, opts);
670
+ }
671
+
672
+ const encoder = /*#__PURE__*/ new TextEncoder();
673
+ /**
674
+ * Encodes a UTF-8 string, hex value, bigint, number or boolean to a byte array.
675
+ *
676
+ * - Docs: https://viem.sh/docs/utilities/toBytes
677
+ * - Example: https://viem.sh/docs/utilities/toBytes#usage
678
+ *
679
+ * @param value Value to encode.
680
+ * @param opts Options.
681
+ * @returns Byte array value.
682
+ *
683
+ * @example
684
+ * import { toBytes } from 'viem'
685
+ * const data = toBytes('Hello world')
686
+ * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
687
+ *
688
+ * @example
689
+ * import { toBytes } from 'viem'
690
+ * const data = toBytes(420)
691
+ * // Uint8Array([1, 164])
692
+ *
693
+ * @example
694
+ * import { toBytes } from 'viem'
695
+ * const data = toBytes(420, { size: 4 })
696
+ * // Uint8Array([0, 0, 1, 164])
697
+ */
698
+ function toBytes$1(value, opts = {}) {
699
+ if (typeof value === 'number' || typeof value === 'bigint')
700
+ return numberToBytes(value, opts);
701
+ if (typeof value === 'boolean')
702
+ return boolToBytes(value, opts);
703
+ if (isHex(value))
704
+ return hexToBytes(value, opts);
705
+ return stringToBytes(value, opts);
706
+ }
707
+ /**
708
+ * Encodes a boolean into a byte array.
709
+ *
710
+ * - Docs: https://viem.sh/docs/utilities/toBytes#booltobytes
711
+ *
712
+ * @param value Boolean value to encode.
713
+ * @param opts Options.
714
+ * @returns Byte array value.
715
+ *
716
+ * @example
717
+ * import { boolToBytes } from 'viem'
718
+ * const data = boolToBytes(true)
719
+ * // Uint8Array([1])
720
+ *
721
+ * @example
722
+ * import { boolToBytes } from 'viem'
723
+ * const data = boolToBytes(true, { size: 32 })
724
+ * // 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])
725
+ */
726
+ function boolToBytes(value, opts = {}) {
727
+ const bytes = new Uint8Array(1);
728
+ bytes[0] = Number(value);
729
+ if (typeof opts.size === 'number') {
730
+ assertSize(bytes, { size: opts.size });
731
+ return pad(bytes, { size: opts.size });
732
+ }
733
+ return bytes;
734
+ }
735
+ // We use very optimized technique to convert hex string to byte array
736
+ const charCodeMap = {
737
+ zero: 48,
738
+ nine: 57,
739
+ A: 65,
740
+ F: 70,
741
+ a: 97,
742
+ f: 102,
743
+ };
744
+ function charCodeToBase16(char) {
745
+ if (char >= charCodeMap.zero && char <= charCodeMap.nine)
746
+ return char - charCodeMap.zero;
747
+ if (char >= charCodeMap.A && char <= charCodeMap.F)
748
+ return char - (charCodeMap.A - 10);
749
+ if (char >= charCodeMap.a && char <= charCodeMap.f)
750
+ return char - (charCodeMap.a - 10);
751
+ return undefined;
752
+ }
753
+ /**
754
+ * Encodes a hex string into a byte array.
755
+ *
756
+ * - Docs: https://viem.sh/docs/utilities/toBytes#hextobytes
757
+ *
758
+ * @param hex Hex string to encode.
759
+ * @param opts Options.
760
+ * @returns Byte array value.
761
+ *
762
+ * @example
763
+ * import { hexToBytes } from 'viem'
764
+ * const data = hexToBytes('0x48656c6c6f20776f726c6421')
765
+ * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
766
+ *
767
+ * @example
768
+ * import { hexToBytes } from 'viem'
769
+ * const data = hexToBytes('0x48656c6c6f20776f726c6421', { size: 32 })
770
+ * // 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])
771
+ */
772
+ function hexToBytes(hex_, opts = {}) {
773
+ let hex = hex_;
774
+ if (opts.size) {
775
+ assertSize(hex, { size: opts.size });
776
+ hex = pad(hex, { dir: 'right', size: opts.size });
777
+ }
778
+ let hexString = hex.slice(2);
779
+ if (hexString.length % 2)
780
+ hexString = `0${hexString}`;
781
+ const length = hexString.length / 2;
782
+ const bytes = new Uint8Array(length);
783
+ for (let index = 0, j = 0; index < length; index++) {
784
+ const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++));
785
+ const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++));
786
+ if (nibbleLeft === undefined || nibbleRight === undefined) {
787
+ throw new BaseError(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`);
788
+ }
789
+ bytes[index] = nibbleLeft * 16 + nibbleRight;
790
+ }
791
+ return bytes;
792
+ }
793
+ /**
794
+ * Encodes a number into a byte array.
795
+ *
796
+ * - Docs: https://viem.sh/docs/utilities/toBytes#numbertobytes
797
+ *
798
+ * @param value Number to encode.
799
+ * @param opts Options.
800
+ * @returns Byte array value.
801
+ *
802
+ * @example
803
+ * import { numberToBytes } from 'viem'
804
+ * const data = numberToBytes(420)
805
+ * // Uint8Array([1, 164])
806
+ *
807
+ * @example
808
+ * import { numberToBytes } from 'viem'
809
+ * const data = numberToBytes(420, { size: 4 })
810
+ * // Uint8Array([0, 0, 1, 164])
811
+ */
812
+ function numberToBytes(value, opts) {
813
+ const hex = numberToHex(value, opts);
814
+ return hexToBytes(hex);
815
+ }
816
+ /**
817
+ * Encodes a UTF-8 string into a byte array.
818
+ *
819
+ * - Docs: https://viem.sh/docs/utilities/toBytes#stringtobytes
820
+ *
821
+ * @param value String to encode.
822
+ * @param opts Options.
823
+ * @returns Byte array value.
824
+ *
825
+ * @example
826
+ * import { stringToBytes } from 'viem'
827
+ * const data = stringToBytes('Hello world!')
828
+ * // Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])
829
+ *
830
+ * @example
831
+ * import { stringToBytes } from 'viem'
832
+ * const data = stringToBytes('Hello world!', { size: 32 })
833
+ * // 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])
834
+ */
835
+ function stringToBytes(value, opts = {}) {
836
+ const bytes = encoder.encode(value);
837
+ if (typeof opts.size === 'number') {
838
+ assertSize(bytes, { size: opts.size });
839
+ return pad(bytes, { dir: 'right', size: opts.size });
840
+ }
841
+ return bytes;
842
+ }
843
+
844
+ /**
845
+ * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
846
+ * @todo re-check https://issues.chromium.org/issues/42212588
847
+ * @module
848
+ */
849
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
850
+ const _32n = /* @__PURE__ */ BigInt(32);
851
+ function fromBig(n, le = false) {
852
+ if (le)
853
+ return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
854
+ return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
855
+ }
856
+ function split(lst, le = false) {
857
+ const len = lst.length;
858
+ let Ah = new Uint32Array(len);
859
+ let Al = new Uint32Array(len);
860
+ for (let i = 0; i < len; i++) {
861
+ const { h, l } = fromBig(lst[i], le);
862
+ [Ah[i], Al[i]] = [h, l];
863
+ }
864
+ return [Ah, Al];
865
+ }
866
+ // Left rotate for Shift in [1, 32)
867
+ const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
868
+ const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
869
+ // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
870
+ const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
871
+ const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
872
+
873
+ /**
874
+ * Utilities for hex, bytes, CSPRNG.
875
+ * @module
876
+ */
877
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
878
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
879
+ // node.js versions earlier than v19 don't declare it in global scope.
880
+ // For node.js, package.json#exports field mapping rewrites import
881
+ // from `crypto` to `cryptoNode`, which imports native module.
882
+ // Makes the utils un-importable in browsers without a bundler.
883
+ // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
884
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
885
+ function isBytes(a) {
886
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
887
+ }
888
+ /** Asserts something is positive integer. */
889
+ function anumber(n) {
890
+ if (!Number.isSafeInteger(n) || n < 0)
891
+ throw new Error('positive integer expected, got ' + n);
892
+ }
893
+ /** Asserts something is Uint8Array. */
894
+ function abytes(b, ...lengths) {
895
+ if (!isBytes(b))
896
+ throw new Error('Uint8Array expected');
897
+ if (lengths.length > 0 && !lengths.includes(b.length))
898
+ throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
899
+ }
900
+ /** Asserts a hash instance has not been destroyed / finished */
901
+ function aexists(instance, checkFinished = true) {
902
+ if (instance.destroyed)
903
+ throw new Error('Hash instance has been destroyed');
904
+ if (checkFinished && instance.finished)
905
+ throw new Error('Hash#digest() has already been called');
906
+ }
907
+ /** Asserts output is properly-sized byte array */
908
+ function aoutput(out, instance) {
909
+ abytes(out);
910
+ const min = instance.outputLen;
911
+ if (out.length < min) {
912
+ throw new Error('digestInto() expects output buffer of length at least ' + min);
913
+ }
914
+ }
915
+ /** Cast u8 / u16 / u32 to u32. */
916
+ function u32(arr) {
917
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
918
+ }
919
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
920
+ function clean(...arrays) {
921
+ for (let i = 0; i < arrays.length; i++) {
922
+ arrays[i].fill(0);
923
+ }
924
+ }
925
+ /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
926
+ const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
927
+ /** The byte swap operation for uint32 */
928
+ function byteSwap(word) {
929
+ return (((word << 24) & 0xff000000) |
930
+ ((word << 8) & 0xff0000) |
931
+ ((word >>> 8) & 0xff00) |
932
+ ((word >>> 24) & 0xff));
933
+ }
934
+ /** In place byte swap for Uint32Array */
935
+ function byteSwap32(arr) {
936
+ for (let i = 0; i < arr.length; i++) {
937
+ arr[i] = byteSwap(arr[i]);
938
+ }
939
+ return arr;
940
+ }
941
+ const swap32IfBE = isLE
942
+ ? (u) => u
943
+ : byteSwap32;
944
+ /**
945
+ * Converts string to bytes using UTF8 encoding.
946
+ * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
947
+ */
948
+ function utf8ToBytes(str) {
949
+ if (typeof str !== 'string')
950
+ throw new Error('string expected');
951
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
952
+ }
953
+ /**
954
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
955
+ * Warning: when Uint8Array is passed, it would NOT get copied.
956
+ * Keep in mind for future mutable operations.
957
+ */
958
+ function toBytes(data) {
959
+ if (typeof data === 'string')
960
+ data = utf8ToBytes(data);
961
+ abytes(data);
962
+ return data;
963
+ }
964
+ /** For runtime check if class implements interface */
965
+ class Hash {
966
+ }
967
+ /** Wraps hash function, creating an interface on top of it */
968
+ function createHasher(hashCons) {
969
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
970
+ const tmp = hashCons();
971
+ hashC.outputLen = tmp.outputLen;
972
+ hashC.blockLen = tmp.blockLen;
973
+ hashC.create = () => hashCons();
974
+ return hashC;
975
+ }
976
+
977
+ /**
978
+ * SHA3 (keccak) hash function, based on a new "Sponge function" design.
979
+ * Different from older hashes, the internal state is bigger than output size.
980
+ *
981
+ * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
982
+ * [Website](https://keccak.team/keccak.html),
983
+ * [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).
984
+ *
985
+ * Check out `sha3-addons` module for cSHAKE, k12, and others.
986
+ * @module
987
+ */
988
+ // No __PURE__ annotations in sha3 header:
989
+ // EVERYTHING is in fact used on every export.
990
+ // Various per round constants calculations
991
+ const _0n = BigInt(0);
992
+ const _1n = BigInt(1);
993
+ const _2n = BigInt(2);
994
+ const _7n = BigInt(7);
995
+ const _256n = BigInt(256);
996
+ const _0x71n = BigInt(0x71);
997
+ const SHA3_PI = [];
998
+ const SHA3_ROTL = [];
999
+ const _SHA3_IOTA = [];
1000
+ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
1001
+ // Pi
1002
+ [x, y] = [y, (2 * x + 3 * y) % 5];
1003
+ SHA3_PI.push(2 * (5 * y + x));
1004
+ // Rotational
1005
+ SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
1006
+ // Iota
1007
+ let t = _0n;
1008
+ for (let j = 0; j < 7; j++) {
1009
+ R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;
1010
+ if (R & _2n)
1011
+ t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);
1012
+ }
1013
+ _SHA3_IOTA.push(t);
1014
+ }
1015
+ const IOTAS = split(_SHA3_IOTA, true);
1016
+ const SHA3_IOTA_H = IOTAS[0];
1017
+ const SHA3_IOTA_L = IOTAS[1];
1018
+ // Left rotation (without 0, 32, 64)
1019
+ const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
1020
+ const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
1021
+ /** `keccakf1600` internal function, additionally allows to adjust round count. */
1022
+ function keccakP(s, rounds = 24) {
1023
+ const B = new Uint32Array(5 * 2);
1024
+ // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
1025
+ for (let round = 24 - rounds; round < 24; round++) {
1026
+ // Theta θ
1027
+ for (let x = 0; x < 10; x++)
1028
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
1029
+ for (let x = 0; x < 10; x += 2) {
1030
+ const idx1 = (x + 8) % 10;
1031
+ const idx0 = (x + 2) % 10;
1032
+ const B0 = B[idx0];
1033
+ const B1 = B[idx0 + 1];
1034
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
1035
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
1036
+ for (let y = 0; y < 50; y += 10) {
1037
+ s[x + y] ^= Th;
1038
+ s[x + y + 1] ^= Tl;
1039
+ }
1040
+ }
1041
+ // Rho (ρ) and Pi (π)
1042
+ let curH = s[2];
1043
+ let curL = s[3];
1044
+ for (let t = 0; t < 24; t++) {
1045
+ const shift = SHA3_ROTL[t];
1046
+ const Th = rotlH(curH, curL, shift);
1047
+ const Tl = rotlL(curH, curL, shift);
1048
+ const PI = SHA3_PI[t];
1049
+ curH = s[PI];
1050
+ curL = s[PI + 1];
1051
+ s[PI] = Th;
1052
+ s[PI + 1] = Tl;
1053
+ }
1054
+ // Chi (χ)
1055
+ for (let y = 0; y < 50; y += 10) {
1056
+ for (let x = 0; x < 10; x++)
1057
+ B[x] = s[y + x];
1058
+ for (let x = 0; x < 10; x++)
1059
+ s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
1060
+ }
1061
+ // Iota (ι)
1062
+ s[0] ^= SHA3_IOTA_H[round];
1063
+ s[1] ^= SHA3_IOTA_L[round];
1064
+ }
1065
+ clean(B);
1066
+ }
1067
+ /** Keccak sponge function. */
1068
+ class Keccak extends Hash {
1069
+ // NOTE: we accept arguments in bytes instead of bits here.
1070
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
1071
+ super();
1072
+ this.pos = 0;
1073
+ this.posOut = 0;
1074
+ this.finished = false;
1075
+ this.destroyed = false;
1076
+ this.enableXOF = false;
1077
+ this.blockLen = blockLen;
1078
+ this.suffix = suffix;
1079
+ this.outputLen = outputLen;
1080
+ this.enableXOF = enableXOF;
1081
+ this.rounds = rounds;
1082
+ // Can be passed from user as dkLen
1083
+ anumber(outputLen);
1084
+ // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
1085
+ // 0 < blockLen < 200
1086
+ if (!(0 < blockLen && blockLen < 200))
1087
+ throw new Error('only keccak-f1600 function is supported');
1088
+ this.state = new Uint8Array(200);
1089
+ this.state32 = u32(this.state);
1090
+ }
1091
+ clone() {
1092
+ return this._cloneInto();
1093
+ }
1094
+ keccak() {
1095
+ swap32IfBE(this.state32);
1096
+ keccakP(this.state32, this.rounds);
1097
+ swap32IfBE(this.state32);
1098
+ this.posOut = 0;
1099
+ this.pos = 0;
1100
+ }
1101
+ update(data) {
1102
+ aexists(this);
1103
+ data = toBytes(data);
1104
+ abytes(data);
1105
+ const { blockLen, state } = this;
1106
+ const len = data.length;
1107
+ for (let pos = 0; pos < len;) {
1108
+ const take = Math.min(blockLen - this.pos, len - pos);
1109
+ for (let i = 0; i < take; i++)
1110
+ state[this.pos++] ^= data[pos++];
1111
+ if (this.pos === blockLen)
1112
+ this.keccak();
1113
+ }
1114
+ return this;
1115
+ }
1116
+ finish() {
1117
+ if (this.finished)
1118
+ return;
1119
+ this.finished = true;
1120
+ const { state, suffix, pos, blockLen } = this;
1121
+ // Do the padding
1122
+ state[pos] ^= suffix;
1123
+ if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
1124
+ this.keccak();
1125
+ state[blockLen - 1] ^= 0x80;
1126
+ this.keccak();
1127
+ }
1128
+ writeInto(out) {
1129
+ aexists(this, false);
1130
+ abytes(out);
1131
+ this.finish();
1132
+ const bufferOut = this.state;
1133
+ const { blockLen } = this;
1134
+ for (let pos = 0, len = out.length; pos < len;) {
1135
+ if (this.posOut >= blockLen)
1136
+ this.keccak();
1137
+ const take = Math.min(blockLen - this.posOut, len - pos);
1138
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
1139
+ this.posOut += take;
1140
+ pos += take;
1141
+ }
1142
+ return out;
1143
+ }
1144
+ xofInto(out) {
1145
+ // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
1146
+ if (!this.enableXOF)
1147
+ throw new Error('XOF is not possible for this instance');
1148
+ return this.writeInto(out);
1149
+ }
1150
+ xof(bytes) {
1151
+ anumber(bytes);
1152
+ return this.xofInto(new Uint8Array(bytes));
1153
+ }
1154
+ digestInto(out) {
1155
+ aoutput(out, this);
1156
+ if (this.finished)
1157
+ throw new Error('digest() was already called');
1158
+ this.writeInto(out);
1159
+ this.destroy();
1160
+ return out;
1161
+ }
1162
+ digest() {
1163
+ return this.digestInto(new Uint8Array(this.outputLen));
1164
+ }
1165
+ destroy() {
1166
+ this.destroyed = true;
1167
+ clean(this.state);
1168
+ }
1169
+ _cloneInto(to) {
1170
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
1171
+ to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
1172
+ to.state32.set(this.state32);
1173
+ to.pos = this.pos;
1174
+ to.posOut = this.posOut;
1175
+ to.finished = this.finished;
1176
+ to.rounds = rounds;
1177
+ // Suffix can change in cSHAKE
1178
+ to.suffix = suffix;
1179
+ to.outputLen = outputLen;
1180
+ to.enableXOF = enableXOF;
1181
+ to.destroyed = this.destroyed;
1182
+ return to;
1183
+ }
1184
+ }
1185
+ const gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
1186
+ /** keccak-256 hash function. Different from SHA3-256. */
1187
+ const keccak_256 = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();
1188
+
1189
+ function keccak256(value, to_) {
1190
+ const to = to_ || 'hex';
1191
+ const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes$1(value) : value);
1192
+ if (to === 'bytes')
1193
+ return bytes;
1194
+ return toHex(bytes);
1195
+ }
1196
+
1197
+ const hash = (value) => keccak256(toBytes$1(value));
1198
+ function hashSignature(sig) {
1199
+ return hash(sig);
1200
+ }
1201
+
1202
+ function normalizeSignature(signature) {
1203
+ let active = true;
1204
+ let current = '';
1205
+ let level = 0;
1206
+ let result = '';
1207
+ let valid = false;
1208
+ for (let i = 0; i < signature.length; i++) {
1209
+ const char = signature[i];
1210
+ // If the character is a separator, we want to reactivate.
1211
+ if (['(', ')', ','].includes(char))
1212
+ active = true;
1213
+ // If the character is a "level" token, we want to increment/decrement.
1214
+ if (char === '(')
1215
+ level++;
1216
+ if (char === ')')
1217
+ level--;
1218
+ // If we aren't active, we don't want to mutate the result.
1219
+ if (!active)
1220
+ continue;
1221
+ // If level === 0, we are at the definition level.
1222
+ if (level === 0) {
1223
+ if (char === ' ' && ['event', 'function', ''].includes(result))
1224
+ result = '';
1225
+ else {
1226
+ result += char;
1227
+ // If we are at the end of the definition, we must be finished.
1228
+ if (char === ')') {
1229
+ valid = true;
1230
+ break;
1231
+ }
1232
+ }
1233
+ continue;
1234
+ }
1235
+ // Ignore spaces
1236
+ if (char === ' ') {
1237
+ // If the previous character is a separator, and the current section isn't empty, we want to deactivate.
1238
+ if (signature[i - 1] !== ',' && current !== ',' && current !== ',(') {
1239
+ current = '';
1240
+ active = false;
1241
+ }
1242
+ continue;
1243
+ }
1244
+ result += char;
1245
+ current += char;
1246
+ }
1247
+ if (!valid)
1248
+ throw new BaseError('Unable to normalize signature.');
1249
+ return result;
1250
+ }
1251
+
1252
+ /**
1253
+ * Returns the signature for a given function or event definition.
1254
+ *
1255
+ * @example
1256
+ * const signature = toSignature('function ownerOf(uint256 tokenId)')
1257
+ * // 'ownerOf(uint256)'
1258
+ *
1259
+ * @example
1260
+ * const signature_3 = toSignature({
1261
+ * name: 'ownerOf',
1262
+ * type: 'function',
1263
+ * inputs: [{ name: 'tokenId', type: 'uint256' }],
1264
+ * outputs: [],
1265
+ * stateMutability: 'view',
1266
+ * })
1267
+ * // 'ownerOf(uint256)'
1268
+ */
1269
+ const toSignature = (def) => {
1270
+ const def_ = (() => {
1271
+ if (typeof def === 'string')
1272
+ return def;
1273
+ return formatAbiItem$1(def);
1274
+ })();
1275
+ return normalizeSignature(def_);
1276
+ };
1277
+
1278
+ /**
1279
+ * Returns the hash (of the function/event signature) for a given event or function definition.
1280
+ */
1281
+ function toSignatureHash(fn) {
1282
+ return hashSignature(toSignature(fn));
1283
+ }
1284
+
1285
+ /**
1286
+ * Returns the event selector for a given event definition.
1287
+ *
1288
+ * @example
1289
+ * const selector = toEventSelector('Transfer(address indexed from, address indexed to, uint256 amount)')
1290
+ * // 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
1291
+ */
1292
+ const toEventSelector = toSignatureHash;
1293
+
1294
+ class InvalidAddressError extends BaseError {
1295
+ constructor({ address }) {
1296
+ super(`Address "${address}" is invalid.`, {
1297
+ metaMessages: [
1298
+ '- Address must be a hex value of 20 bytes (40 hex characters).',
1299
+ '- Address must match its checksum counterpart.',
1300
+ ],
1301
+ name: 'InvalidAddressError',
1302
+ });
1303
+ }
1304
+ }
1305
+
1306
+ /**
1307
+ * Map with a LRU (Least recently used) policy.
1308
+ *
1309
+ * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
1310
+ */
1311
+ class LruMap extends Map {
1312
+ constructor(size) {
1313
+ super();
1314
+ Object.defineProperty(this, "maxSize", {
1315
+ enumerable: true,
1316
+ configurable: true,
1317
+ writable: true,
1318
+ value: void 0
1319
+ });
1320
+ this.maxSize = size;
1321
+ }
1322
+ get(key) {
1323
+ const value = super.get(key);
1324
+ if (super.has(key)) {
1325
+ super.delete(key);
1326
+ super.set(key, value);
1327
+ }
1328
+ return value;
1329
+ }
1330
+ set(key, value) {
1331
+ if (super.has(key))
1332
+ super.delete(key);
1333
+ super.set(key, value);
1334
+ if (this.maxSize && this.size > this.maxSize) {
1335
+ const firstKey = super.keys().next().value;
1336
+ if (firstKey !== undefined)
1337
+ super.delete(firstKey);
1338
+ }
1339
+ return this;
1340
+ }
1341
+ }
1342
+
1343
+ const checksumAddressCache = /*#__PURE__*/ new LruMap(8192);
1344
+ function checksumAddress(address_,
1345
+ /**
1346
+ * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the
1347
+ * wider Ethereum ecosystem, meaning it will break when validated against an application/tool
1348
+ * that relies on EIP-55 checksum encoding (checksum without chainId).
1349
+ *
1350
+ * It is highly recommended to not use this feature unless you
1351
+ * know what you are doing.
1352
+ *
1353
+ * See more: https://github.com/ethereum/EIPs/issues/1121
1354
+ */
1355
+ chainId) {
1356
+ if (checksumAddressCache.has(`${address_}.${chainId}`))
1357
+ return checksumAddressCache.get(`${address_}.${chainId}`);
1358
+ const hexAddress = address_.substring(2).toLowerCase();
1359
+ const hash = keccak256(stringToBytes(hexAddress), 'bytes');
1360
+ const address = (hexAddress).split('');
1361
+ for (let i = 0; i < 40; i += 2) {
1362
+ if (hash[i >> 1] >> 4 >= 8 && address[i]) {
1363
+ address[i] = address[i].toUpperCase();
1364
+ }
1365
+ if ((hash[i >> 1] & 0x0f) >= 8 && address[i + 1]) {
1366
+ address[i + 1] = address[i + 1].toUpperCase();
1367
+ }
1368
+ }
1369
+ const result = `0x${address.join('')}`;
1370
+ checksumAddressCache.set(`${address_}.${chainId}`, result);
1371
+ return result;
1372
+ }
1373
+
1374
+ const addressRegex = /^0x[a-fA-F0-9]{40}$/;
1375
+ /** @internal */
1376
+ const isAddressCache = /*#__PURE__*/ new LruMap(8192);
1377
+ function isAddress(address, options) {
1378
+ const { strict = true } = options ?? {};
1379
+ const cacheKey = `${address}.${strict}`;
1380
+ if (isAddressCache.has(cacheKey))
1381
+ return isAddressCache.get(cacheKey);
1382
+ const result = (() => {
1383
+ if (!addressRegex.test(address))
1384
+ return false;
1385
+ if (address.toLowerCase() === address)
1386
+ return true;
1387
+ if (strict)
1388
+ return checksumAddress(address) === address;
1389
+ return true;
1390
+ })();
1391
+ isAddressCache.set(cacheKey, result);
1392
+ return result;
1393
+ }
1394
+
1395
+ function concat(values) {
1396
+ if (typeof values[0] === 'string')
1397
+ return concatHex(values);
1398
+ return concatBytes(values);
1399
+ }
1400
+ function concatBytes(values) {
1401
+ let length = 0;
1402
+ for (const arr of values) {
1403
+ length += arr.length;
1404
+ }
1405
+ const result = new Uint8Array(length);
1406
+ let offset = 0;
1407
+ for (const arr of values) {
1408
+ result.set(arr, offset);
1409
+ offset += arr.length;
1410
+ }
1411
+ return result;
1412
+ }
1413
+ function concatHex(values) {
1414
+ return `0x${values.reduce((acc, x) => acc + x.replace('0x', ''), '')}`;
1415
+ }
1416
+
1417
+ /**
1418
+ * @description Returns a section of the hex or byte array given a start/end bytes offset.
1419
+ *
1420
+ * @param value The hex or byte array to slice.
1421
+ * @param start The start offset (in bytes).
1422
+ * @param end The end offset (in bytes).
1423
+ */
1424
+ function slice(value, start, end, { strict } = {}) {
1425
+ if (isHex(value, { strict: false }))
1426
+ return sliceHex(value, start, end, {
1427
+ strict,
1428
+ });
1429
+ return sliceBytes(value, start, end, {
1430
+ strict,
1431
+ });
1432
+ }
1433
+ function assertStartOffset(value, start) {
1434
+ if (typeof start === 'number' && start > 0 && start > size(value) - 1)
1435
+ throw new SliceOffsetOutOfBoundsError({
1436
+ offset: start,
1437
+ position: 'start',
1438
+ size: size(value),
1439
+ });
1440
+ }
1441
+ function assertEndOffset(value, start, end) {
1442
+ if (typeof start === 'number' &&
1443
+ typeof end === 'number' &&
1444
+ size(value) !== end - start) {
1445
+ throw new SliceOffsetOutOfBoundsError({
1446
+ offset: end,
1447
+ position: 'end',
1448
+ size: size(value),
1449
+ });
1450
+ }
1451
+ }
1452
+ /**
1453
+ * @description Returns a section of the byte array given a start/end bytes offset.
1454
+ *
1455
+ * @param value The byte array to slice.
1456
+ * @param start The start offset (in bytes).
1457
+ * @param end The end offset (in bytes).
1458
+ */
1459
+ function sliceBytes(value_, start, end, { strict } = {}) {
1460
+ assertStartOffset(value_, start);
1461
+ const value = value_.slice(start, end);
1462
+ if (strict)
1463
+ assertEndOffset(value, start, end);
1464
+ return value;
1465
+ }
1466
+ /**
1467
+ * @description Returns a section of the hex value given a start/end bytes offset.
1468
+ *
1469
+ * @param value The hex value to slice.
1470
+ * @param start The start offset (in bytes).
1471
+ * @param end The end offset (in bytes).
1472
+ */
1473
+ function sliceHex(value_, start, end, { strict } = {}) {
1474
+ assertStartOffset(value_, start);
1475
+ const value = `0x${value_
1476
+ .replace('0x', '')
1477
+ .slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`;
1478
+ if (strict)
1479
+ assertEndOffset(value, start, end);
1480
+ return value;
1481
+ }
1482
+
1483
+ // `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`
1484
+ // https://regexr.com/6v8hp
1485
+ 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)?$/;
1486
+
1487
+ /**
1488
+ * @description Encodes a list of primitive values into an ABI-encoded hex value.
1489
+ *
1490
+ * - Docs: https://viem.sh/docs/abi/encodeAbiParameters#encodeabiparameters
1491
+ *
1492
+ * 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.
1493
+ *
1494
+ * @param params - a set of ABI Parameters (params), that can be in the shape of the inputs or outputs attribute of an ABI Item.
1495
+ * @param values - a set of values (values) that correspond to the given params.
1496
+ * @example
1497
+ * ```typescript
1498
+ * import { encodeAbiParameters } from 'viem'
1499
+ *
1500
+ * const encodedData = encodeAbiParameters(
1501
+ * [
1502
+ * { name: 'x', type: 'string' },
1503
+ * { name: 'y', type: 'uint' },
1504
+ * { name: 'z', type: 'bool' }
1505
+ * ],
1506
+ * ['wagmi', 420n, true]
1507
+ * )
1508
+ * ```
1509
+ *
1510
+ * You can also pass in Human Readable parameters with the parseAbiParameters utility.
1511
+ *
1512
+ * @example
1513
+ * ```typescript
1514
+ * import { encodeAbiParameters, parseAbiParameters } from 'viem'
1515
+ *
1516
+ * const encodedData = encodeAbiParameters(
1517
+ * parseAbiParameters('string x, uint y, bool z'),
1518
+ * ['wagmi', 420n, true]
1519
+ * )
1520
+ * ```
1521
+ */
1522
+ function encodeAbiParameters(params, values) {
1523
+ if (params.length !== values.length)
1524
+ throw new AbiEncodingLengthMismatchError({
1525
+ expectedLength: params.length,
1526
+ givenLength: values.length,
1527
+ });
1528
+ // Prepare the parameters to determine dynamic types to encode.
1529
+ const preparedParams = prepareParams({
1530
+ params: params,
1531
+ values: values,
1532
+ });
1533
+ const data = encodeParams(preparedParams);
1534
+ if (data.length === 0)
1535
+ return '0x';
1536
+ return data;
1537
+ }
1538
+ function prepareParams({ params, values, }) {
1539
+ const preparedParams = [];
1540
+ for (let i = 0; i < params.length; i++) {
1541
+ preparedParams.push(prepareParam({ param: params[i], value: values[i] }));
1542
+ }
1543
+ return preparedParams;
1544
+ }
1545
+ function prepareParam({ param, value, }) {
1546
+ const arrayComponents = getArrayComponents(param.type);
1547
+ if (arrayComponents) {
1548
+ const [length, type] = arrayComponents;
1549
+ return encodeArray(value, { length, param: { ...param, type } });
1550
+ }
1551
+ if (param.type === 'tuple') {
1552
+ return encodeTuple(value, {
1553
+ param: param,
1554
+ });
1555
+ }
1556
+ if (param.type === 'address') {
1557
+ return encodeAddress(value);
1558
+ }
1559
+ if (param.type === 'bool') {
1560
+ return encodeBool(value);
1561
+ }
1562
+ if (param.type.startsWith('uint') || param.type.startsWith('int')) {
1563
+ const signed = param.type.startsWith('int');
1564
+ const [, , size = '256'] = integerRegex.exec(param.type) ?? [];
1565
+ return encodeNumber(value, {
1566
+ signed,
1567
+ size: Number(size),
1568
+ });
1569
+ }
1570
+ if (param.type.startsWith('bytes')) {
1571
+ return encodeBytes(value, { param });
1572
+ }
1573
+ if (param.type === 'string') {
1574
+ return encodeString(value);
1575
+ }
1576
+ throw new InvalidAbiEncodingTypeError(param.type, {
1577
+ docsPath: '/docs/contract/encodeAbiParameters',
1578
+ });
1579
+ }
1580
+ function encodeParams(preparedParams) {
1581
+ // 1. Compute the size of the static part of the parameters.
1582
+ let staticSize = 0;
1583
+ for (let i = 0; i < preparedParams.length; i++) {
1584
+ const { dynamic, encoded } = preparedParams[i];
1585
+ if (dynamic)
1586
+ staticSize += 32;
1587
+ else
1588
+ staticSize += size(encoded);
1589
+ }
1590
+ // 2. Split the parameters into static and dynamic parts.
1591
+ const staticParams = [];
1592
+ const dynamicParams = [];
1593
+ let dynamicSize = 0;
1594
+ for (let i = 0; i < preparedParams.length; i++) {
1595
+ const { dynamic, encoded } = preparedParams[i];
1596
+ if (dynamic) {
1597
+ staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 }));
1598
+ dynamicParams.push(encoded);
1599
+ dynamicSize += size(encoded);
1600
+ }
1601
+ else {
1602
+ staticParams.push(encoded);
1603
+ }
1604
+ }
1605
+ // 3. Concatenate static and dynamic parts.
1606
+ return concat([...staticParams, ...dynamicParams]);
1607
+ }
1608
+ function encodeAddress(value) {
1609
+ if (!isAddress(value))
1610
+ throw new InvalidAddressError({ address: value });
1611
+ return { dynamic: false, encoded: padHex(value.toLowerCase()) };
1612
+ }
1613
+ function encodeArray(value, { length, param, }) {
1614
+ const dynamic = length === null;
1615
+ if (!Array.isArray(value))
1616
+ throw new InvalidArrayError(value);
1617
+ if (!dynamic && value.length !== length)
1618
+ throw new AbiEncodingArrayLengthMismatchError({
1619
+ expectedLength: length,
1620
+ givenLength: value.length,
1621
+ type: `${param.type}[${length}]`,
1622
+ });
1623
+ let dynamicChild = false;
1624
+ const preparedParams = [];
1625
+ for (let i = 0; i < value.length; i++) {
1626
+ const preparedParam = prepareParam({ param, value: value[i] });
1627
+ if (preparedParam.dynamic)
1628
+ dynamicChild = true;
1629
+ preparedParams.push(preparedParam);
1630
+ }
1631
+ if (dynamic || dynamicChild) {
1632
+ const data = encodeParams(preparedParams);
1633
+ if (dynamic) {
1634
+ const length = numberToHex(preparedParams.length, { size: 32 });
1635
+ return {
1636
+ dynamic: true,
1637
+ encoded: preparedParams.length > 0 ? concat([length, data]) : length,
1638
+ };
1639
+ }
1640
+ if (dynamicChild)
1641
+ return { dynamic: true, encoded: data };
1642
+ }
1643
+ return {
1644
+ dynamic: false,
1645
+ encoded: concat(preparedParams.map(({ encoded }) => encoded)),
1646
+ };
1647
+ }
1648
+ function encodeBytes(value, { param }) {
1649
+ const [, paramSize] = param.type.split('bytes');
1650
+ const bytesSize = size(value);
1651
+ if (!paramSize) {
1652
+ let value_ = value;
1653
+ // If the size is not divisible by 32 bytes, pad the end
1654
+ // with empty bytes to the ceiling 32 bytes.
1655
+ if (bytesSize % 32 !== 0)
1656
+ value_ = padHex(value_, {
1657
+ dir: 'right',
1658
+ size: Math.ceil((value.length - 2) / 2 / 32) * 32,
1659
+ });
1660
+ return {
1661
+ dynamic: true,
1662
+ encoded: concat([padHex(numberToHex(bytesSize, { size: 32 })), value_]),
1663
+ };
1664
+ }
1665
+ if (bytesSize !== Number.parseInt(paramSize, 10))
1666
+ throw new AbiEncodingBytesSizeMismatchError({
1667
+ expectedSize: Number.parseInt(paramSize, 10),
1668
+ value,
1669
+ });
1670
+ return { dynamic: false, encoded: padHex(value, { dir: 'right' }) };
1671
+ }
1672
+ function encodeBool(value) {
1673
+ if (typeof value !== 'boolean')
1674
+ throw new BaseError(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`);
1675
+ return { dynamic: false, encoded: padHex(boolToHex(value)) };
1676
+ }
1677
+ function encodeNumber(value, { signed, size = 256 }) {
1678
+ if (typeof size === 'number') {
1679
+ const max = 2n ** (BigInt(size) - (signed ? 1n : 0n)) - 1n;
1680
+ const min = signed ? -max - 1n : 0n;
1681
+ if (value > max || value < min)
1682
+ throw new IntegerOutOfRangeError({
1683
+ max: max.toString(),
1684
+ min: min.toString(),
1685
+ signed,
1686
+ size: size / 8,
1687
+ value: value.toString(),
1688
+ });
1689
+ }
1690
+ return {
1691
+ dynamic: false,
1692
+ encoded: numberToHex(value, {
1693
+ size: 32,
1694
+ signed,
1695
+ }),
1696
+ };
1697
+ }
1698
+ function encodeString(value) {
1699
+ const hexValue = stringToHex(value);
1700
+ const partsLength = Math.ceil(size(hexValue) / 32);
1701
+ const parts = [];
1702
+ for (let i = 0; i < partsLength; i++) {
1703
+ parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), {
1704
+ dir: 'right',
1705
+ }));
1706
+ }
1707
+ return {
1708
+ dynamic: true,
1709
+ encoded: concat([
1710
+ padHex(numberToHex(size(hexValue), { size: 32 })),
1711
+ ...parts,
1712
+ ]),
1713
+ };
1714
+ }
1715
+ function encodeTuple(value, { param }) {
1716
+ let dynamic = false;
1717
+ const preparedParams = [];
1718
+ for (let i = 0; i < param.components.length; i++) {
1719
+ const param_ = param.components[i];
1720
+ const index = Array.isArray(value) ? i : param_.name;
1721
+ const preparedParam = prepareParam({
1722
+ param: param_,
1723
+ value: value[index],
1724
+ });
1725
+ preparedParams.push(preparedParam);
1726
+ if (preparedParam.dynamic)
1727
+ dynamic = true;
1728
+ }
1729
+ return {
1730
+ dynamic,
1731
+ encoded: dynamic
1732
+ ? encodeParams(preparedParams)
1733
+ : concat(preparedParams.map(({ encoded }) => encoded)),
1734
+ };
1735
+ }
1736
+ function getArrayComponents(type) {
1737
+ const matches = type.match(/^(.*)\[(\d+)?\]$/);
1738
+ return matches
1739
+ ? // Return `null` if the array is dynamic.
1740
+ [matches[2] ? Number(matches[2]) : null, matches[1]]
1741
+ : undefined;
1742
+ }
1743
+
1744
+ /**
1745
+ * Returns the function selector for a given function definition.
1746
+ *
1747
+ * @example
1748
+ * const selector = toFunctionSelector('function ownerOf(uint256 tokenId)')
1749
+ * // 0x6352211e
1750
+ */
1751
+ const toFunctionSelector = (fn) => slice(toSignatureHash(fn), 0, 4);
1752
+
1753
+ function getAbiItem(parameters) {
1754
+ const { abi, args = [], name } = parameters;
1755
+ const isSelector = isHex(name, { strict: false });
1756
+ const abiItems = abi.filter((abiItem) => {
1757
+ if (isSelector) {
1758
+ if (abiItem.type === 'function')
1759
+ return toFunctionSelector(abiItem) === name;
1760
+ if (abiItem.type === 'event')
1761
+ return toEventSelector(abiItem) === name;
1762
+ return false;
1763
+ }
1764
+ return 'name' in abiItem && abiItem.name === name;
1765
+ });
1766
+ if (abiItems.length === 0)
1767
+ return undefined;
1768
+ if (abiItems.length === 1)
1769
+ return abiItems[0];
1770
+ let matchedAbiItem;
1771
+ for (const abiItem of abiItems) {
1772
+ if (!('inputs' in abiItem))
1773
+ continue;
1774
+ if (!args || args.length === 0) {
1775
+ if (!abiItem.inputs || abiItem.inputs.length === 0)
1776
+ return abiItem;
1777
+ continue;
1778
+ }
1779
+ if (!abiItem.inputs)
1780
+ continue;
1781
+ if (abiItem.inputs.length === 0)
1782
+ continue;
1783
+ if (abiItem.inputs.length !== args.length)
1784
+ continue;
1785
+ const matched = args.every((arg, index) => {
1786
+ const abiParameter = 'inputs' in abiItem && abiItem.inputs[index];
1787
+ if (!abiParameter)
1788
+ return false;
1789
+ return isArgOfType(arg, abiParameter);
1790
+ });
1791
+ if (matched) {
1792
+ // Check for ambiguity against already matched parameters (e.g. `address` vs `bytes20`).
1793
+ if (matchedAbiItem &&
1794
+ 'inputs' in matchedAbiItem &&
1795
+ matchedAbiItem.inputs) {
1796
+ const ambiguousTypes = getAmbiguousTypes(abiItem.inputs, matchedAbiItem.inputs, args);
1797
+ if (ambiguousTypes)
1798
+ throw new AbiItemAmbiguityError({
1799
+ abiItem,
1800
+ type: ambiguousTypes[0],
1801
+ }, {
1802
+ abiItem: matchedAbiItem,
1803
+ type: ambiguousTypes[1],
1804
+ });
1805
+ }
1806
+ matchedAbiItem = abiItem;
1807
+ }
1808
+ }
1809
+ if (matchedAbiItem)
1810
+ return matchedAbiItem;
1811
+ return abiItems[0];
1812
+ }
1813
+ /** @internal */
1814
+ function isArgOfType(arg, abiParameter) {
1815
+ const argType = typeof arg;
1816
+ const abiParameterType = abiParameter.type;
1817
+ switch (abiParameterType) {
1818
+ case 'address':
1819
+ return isAddress(arg, { strict: false });
1820
+ case 'bool':
1821
+ return argType === 'boolean';
1822
+ case 'function':
1823
+ return argType === 'string';
1824
+ case 'string':
1825
+ return argType === 'string';
1826
+ default: {
1827
+ if (abiParameterType === 'tuple' && 'components' in abiParameter)
1828
+ return Object.values(abiParameter.components).every((component, index) => {
1829
+ return (argType === 'object' &&
1830
+ isArgOfType(Object.values(arg)[index], component));
1831
+ });
1832
+ // `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`
1833
+ // https://regexr.com/6v8hp
1834
+ 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))
1835
+ return argType === 'number' || argType === 'bigint';
1836
+ // `bytes<M>`: binary type of `M` bytes, `0 < M <= 32`
1837
+ // https://regexr.com/6va55
1838
+ if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType))
1839
+ return argType === 'string' || arg instanceof Uint8Array;
1840
+ // fixed-length (`<type>[M]`) and dynamic (`<type>[]`) arrays
1841
+ // https://regexr.com/6va6i
1842
+ if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) {
1843
+ return (Array.isArray(arg) &&
1844
+ arg.every((x) => isArgOfType(x, {
1845
+ ...abiParameter,
1846
+ // Pop off `[]` or `[M]` from end of type
1847
+ type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, ''),
1848
+ })));
1849
+ }
1850
+ return false;
1851
+ }
1852
+ }
1853
+ }
1854
+ /** @internal */
1855
+ function getAmbiguousTypes(sourceParameters, targetParameters, args) {
1856
+ for (const parameterIndex in sourceParameters) {
1857
+ const sourceParameter = sourceParameters[parameterIndex];
1858
+ const targetParameter = targetParameters[parameterIndex];
1859
+ if (sourceParameter.type === 'tuple' &&
1860
+ targetParameter.type === 'tuple' &&
1861
+ 'components' in sourceParameter &&
1862
+ 'components' in targetParameter)
1863
+ return getAmbiguousTypes(sourceParameter.components, targetParameter.components, args[parameterIndex]);
1864
+ const types = [sourceParameter.type, targetParameter.type];
1865
+ const ambiguous = (() => {
1866
+ if (types.includes('address') && types.includes('bytes20'))
1867
+ return true;
1868
+ if (types.includes('address') && types.includes('string'))
1869
+ return isAddress(args[parameterIndex], { strict: false });
1870
+ if (types.includes('address') && types.includes('bytes'))
1871
+ return isAddress(args[parameterIndex], { strict: false });
1872
+ return false;
1873
+ })();
1874
+ if (ambiguous)
1875
+ return types;
1876
+ }
1877
+ return;
1878
+ }
1879
+
1880
+ const docsPath = '/docs/contract/encodeFunctionData';
1881
+ function prepareEncodeFunctionData(parameters) {
1882
+ const { abi, args, functionName } = parameters;
1883
+ let abiItem = abi[0];
1884
+ if (functionName) {
1885
+ const item = getAbiItem({
1886
+ abi,
1887
+ args,
1888
+ name: functionName,
1889
+ });
1890
+ if (!item)
1891
+ throw new AbiFunctionNotFoundError(functionName, { docsPath });
1892
+ abiItem = item;
1893
+ }
1894
+ if (abiItem.type !== 'function')
1895
+ throw new AbiFunctionNotFoundError(undefined, { docsPath });
1896
+ return {
1897
+ abi: [abiItem],
1898
+ functionName: toFunctionSelector(formatAbiItem(abiItem)),
1899
+ };
1900
+ }
1901
+
1902
+ function encodeFunctionData(parameters) {
1903
+ const { args } = parameters;
1904
+ const { abi, functionName } = (() => {
1905
+ if (parameters.abi.length === 1 &&
1906
+ parameters.functionName?.startsWith('0x'))
1907
+ return parameters;
1908
+ return prepareEncodeFunctionData(parameters);
1909
+ })();
1910
+ const abiItem = abi[0];
1911
+ const signature = functionName;
1912
+ const data = 'inputs' in abiItem && abiItem.inputs
1913
+ ? encodeAbiParameters(abiItem.inputs, args ?? [])
1914
+ : undefined;
1915
+ return concatHex([signature, data ?? '0x']);
1916
+ }
1917
+
1918
+ const ZERO_ADDRESS$1 = "0x0000000000000000000000000000000000000000";
1919
+ const PAYMENT_ABI = [
1920
+ {
1921
+ name: "createPayment",
1922
+ type: "function",
1923
+ stateMutability: "payable",
1924
+ inputs: [
1925
+ {
1926
+ name: "p",
1927
+ type: "tuple",
1928
+ components: [
1929
+ { name: "paymentId", type: "bytes32" },
1930
+ { name: "vendorId", type: "string" },
1931
+ { name: "token", type: "address" },
1932
+ { name: "amount", type: "uint256" },
1933
+ { name: "deadline", type: "uint256" },
1934
+ { name: "backendSignature", type: "bytes" },
1935
+ ],
1936
+ },
1937
+ ],
1938
+ outputs: [],
1939
+ },
1940
+ ];
1941
+ const ERC20_ABI = [
1942
+ {
1943
+ name: "allowance",
1944
+ type: "function",
1945
+ stateMutability: "view",
1946
+ inputs: [
1947
+ { name: "owner", type: "address" },
1948
+ { name: "spender", type: "address" },
1949
+ ],
1950
+ outputs: [{ type: "uint256" }],
1951
+ },
1952
+ {
1953
+ name: "approve",
1954
+ type: "function",
1955
+ stateMutability: "nonpayable",
1956
+ inputs: [
1957
+ { name: "spender", type: "address" },
1958
+ { name: "amount", type: "uint256" },
1959
+ ],
1960
+ outputs: [{ type: "bool" }],
1961
+ },
1962
+ ];
1963
+ function ensure0x(hex) {
1964
+ return (hex.startsWith("0x") ? hex : `0x${hex}`);
1965
+ }
1966
+ function extractErrorMessage(err) {
1967
+ if (err === null || err === undefined)
1968
+ return "Unknown error";
1969
+ if (typeof err === "string")
1970
+ return err;
1971
+ if (err instanceof Error)
1972
+ return err.message;
1973
+ if (typeof err === "object") {
1974
+ const e = err;
1975
+ if (typeof e["message"] === "string")
1976
+ return e["message"];
1977
+ if (typeof e["shortMessage"] === "string")
1978
+ return e["shortMessage"];
1979
+ if (e["data"] && typeof e["data"] === "object") {
1980
+ const d = e["data"];
1981
+ if (typeof d["message"] === "string")
1982
+ return d["message"];
1983
+ }
1984
+ try {
1985
+ return JSON.stringify(err);
1986
+ }
1987
+ catch {
1988
+ return "Contract error";
1989
+ }
1990
+ }
1991
+ return String(err);
1992
+ }
1993
+ // Decode a revert reason from an eth_call response hex string.
1994
+ // Handles the standard Error(string) ABI encoding: 0x08c379a0 + abi-encoded string.
1995
+ function decodeRevertReason(hex) {
1996
+ try {
1997
+ if (!hex || hex === "0x")
1998
+ return null;
1999
+ const ERROR_SELECTOR = "08c379a0";
2000
+ if (hex.startsWith("0x" + ERROR_SELECTOR)) {
2001
+ const data = hex.slice(10); // strip 0x + 4-byte selector
2002
+ const offset = parseInt(data.slice(0, 64), 16) * 2;
2003
+ const length = parseInt(data.slice(offset, offset + 64), 16) * 2;
2004
+ const msgHex = data.slice(offset + 64, offset + 64 + length);
2005
+ const bytes = new Uint8Array(msgHex.match(/.{1,2}/g).map((b) => parseInt(b, 16)));
2006
+ return new TextDecoder().decode(bytes);
2007
+ }
2008
+ // Custom error or panic — return raw
2009
+ return `raw revert: ${hex.slice(0, 66)}`;
2010
+ }
2011
+ catch {
2012
+ return null;
2013
+ }
2014
+ }
2015
+ class ContractService {
2016
+ constructor(provider) {
2017
+ this.provider = provider;
2018
+ }
2019
+ async getAddress() {
2020
+ const accounts = (await this.provider.request({
2021
+ method: "eth_requestAccounts",
2022
+ }));
2023
+ if (!accounts[0]) {
2024
+ throw new KwesPayError("No wallet account available", "WALLET_REJECTED");
2025
+ }
2026
+ return accounts[0];
2027
+ }
2028
+ async waitForReceipt(txHash, timeoutMs = 120000) {
2029
+ const deadline = Date.now() + timeoutMs;
2030
+ while (Date.now() < deadline) {
2031
+ const receipt = (await this.provider.request({
2032
+ method: "eth_getTransactionReceipt",
2033
+ params: [txHash],
2034
+ }));
2035
+ if (receipt) {
2036
+ return {
2037
+ blockNumber: parseInt(receipt.blockNumber, 16),
2038
+ status: parseInt(receipt.status, 16),
2039
+ };
2040
+ }
2041
+ await new Promise((r) => setTimeout(r, 2000));
2042
+ }
2043
+ throw new KwesPayError("Transaction receipt timeout — check wallet or block explorer", "CONTRACT_ERROR");
2044
+ }
2045
+ async ensureApproval(tokenAddress, amountBaseUnits, contractAddress, chainId, onStatus) {
2046
+ if (tokenAddress === ZERO_ADDRESS$1)
2047
+ return;
2048
+ onStatus?.("Checking approval", "Verifying token allowance...");
2049
+ const owner = await this.getAddress();
2050
+ const amount = BigInt(amountBaseUnits);
2051
+ const allowanceData = encodeFunctionData({
2052
+ abi: ERC20_ABI,
2053
+ functionName: "allowance",
2054
+ args: [owner, ensure0x(contractAddress)],
2055
+ });
2056
+ const rawAllowance = (await this.provider.request({
2057
+ method: "eth_call",
2058
+ params: [{ to: ensure0x(tokenAddress), data: allowanceData }, "latest"],
2059
+ }));
2060
+ const allowance = rawAllowance && rawAllowance !== "0x" ? BigInt(rawAllowance) : 0n;
2061
+ if (allowance >= amount)
2062
+ return;
2063
+ onStatus?.("Approve token", "Please approve in your wallet");
2064
+ const approveData = encodeFunctionData({
2065
+ abi: ERC20_ABI,
2066
+ functionName: "approve",
2067
+ args: [ensure0x(contractAddress), amount * 2n],
2068
+ });
2069
+ let txHash;
2070
+ try {
2071
+ txHash = (await this.provider.request({
2072
+ method: "eth_sendTransaction",
2073
+ params: [
2074
+ { from: owner, to: ensure0x(tokenAddress), data: approveData },
2075
+ ],
2076
+ }));
2077
+ }
2078
+ catch (err) {
2079
+ const msg = extractErrorMessage(err);
2080
+ if (msg.includes("rejected") ||
2081
+ msg.includes("denied") ||
2082
+ msg.includes("ACTION_REJECTED")) {
2083
+ throw new KwesPayError("Token approval cancelled by user", "APPROVAL_REJECTED", err);
2084
+ }
2085
+ throw new KwesPayError(`Token approval failed: ${msg}`, "CONTRACT_ERROR", err);
2086
+ }
2087
+ onStatus?.("Waiting for approval", `Tx: ${txHash.slice(0, 10)}...`);
2088
+ const receipt = await this.waitForReceipt(txHash);
2089
+ if (receipt.status !== 1) {
2090
+ throw new KwesPayError("Approval transaction reverted", "CONTRACT_ERROR");
2091
+ }
2092
+ await new Promise((r) => setTimeout(r, 1000));
2093
+ }
2094
+ async createPayment(params, onStatus) {
2095
+ const from = await this.getAddress();
2096
+ const amount = BigInt(params.amountBaseUnits);
2097
+ const total = BigInt(params.totalBaseUnits);
2098
+ const isNative = params.tokenAddress === ZERO_ADDRESS$1;
2099
+ const nowUnix = Math.floor(Date.now() / 1000);
2100
+ // Log everything going into the contract call so mismatches are visible.
2101
+ console.log("[ContractService] createPayment params:", {
2102
+ from,
2103
+ contractAddress: params.contractAddress,
2104
+ paymentIdBytes32: params.paymentIdBytes32,
2105
+ vendorIdentifier: params.vendorIdentifier,
2106
+ tokenAddress: params.tokenAddress,
2107
+ amountBaseUnits: params.amountBaseUnits,
2108
+ totalBaseUnits: params.totalBaseUnits,
2109
+ deadline: params.deadline,
2110
+ deadlineReadable: new Date(params.deadline * 1000).toISOString(),
2111
+ nowUnix,
2112
+ deadlineValid: params.deadline > nowUnix,
2113
+ chainId: params.chainId,
2114
+ isNative,
2115
+ backendSignature: params.backendSignature,
2116
+ });
2117
+ if (params.deadline <= nowUnix) {
2118
+ throw new KwesPayError(`Deadline already expired (deadline=${params.deadline}, now=${nowUnix})`, "CONTRACT_ERROR");
2119
+ }
2120
+ const data = encodeFunctionData({
2121
+ abi: PAYMENT_ABI,
2122
+ functionName: "createPayment",
2123
+ args: [
2124
+ {
2125
+ paymentId: ensure0x(params.paymentIdBytes32),
2126
+ vendorId: params.vendorIdentifier,
2127
+ token: ensure0x(params.tokenAddress),
2128
+ amount,
2129
+ deadline: BigInt(params.deadline),
2130
+ backendSignature: ensure0x(params.backendSignature),
2131
+ },
2132
+ ],
2133
+ });
2134
+ const txParams = {
2135
+ from,
2136
+ to: ensure0x(params.contractAddress),
2137
+ data,
2138
+ };
2139
+ if (isNative) {
2140
+ txParams["value"] = `0x${total.toString(16)}`;
2141
+ }
2142
+ console.log("[ContractService] eth_call dry-run — checking for revert before sending...");
2143
+ // Dry-run via eth_call to surface the revert reason without spending gas.
2144
+ try {
2145
+ await this.provider.request({
2146
+ method: "eth_call",
2147
+ params: [txParams, "latest"],
2148
+ });
2149
+ console.log("[ContractService] eth_call passed — no revert detected");
2150
+ }
2151
+ catch (callErr) {
2152
+ // Log full raw error — MetaMask wraps revert data several levels deep
2153
+ console.error("[ContractService] eth_call raw error dump:", JSON.stringify(callErr, null, 2));
2154
+ const e = callErr;
2155
+ const inner = e?.["error"];
2156
+ const innerData = inner?.["data"];
2157
+ const revertHex =
2158
+ // ethers-style: err.data
2159
+ (typeof e?.["data"] === "string" ? e["data"] : undefined) ||
2160
+ // MetaMask EIP-1193: err.error.data (string)
2161
+ (typeof inner?.["data"] === "string"
2162
+ ? inner["data"]
2163
+ : undefined) ||
2164
+ // MetaMask nested: err.error.data.data
2165
+ (typeof innerData === "object" && innerData !== null
2166
+ ? innerData["data"]
2167
+ : undefined) ||
2168
+ // viem-style: err.cause.data
2169
+ (typeof e?.["cause"]?.["data"] === "string"
2170
+ ? (e?.["cause"])["data"]
2171
+ : undefined);
2172
+ const decoded = revertHex ? decodeRevertReason(revertHex) : null;
2173
+ const fallback = extractErrorMessage(callErr);
2174
+ console.error("[ContractService] eth_call revert parsed:", {
2175
+ revertHex,
2176
+ decoded,
2177
+ fallback,
2178
+ });
2179
+ throw new KwesPayError(decoded ?? fallback ?? "Transaction would revert", "CONTRACT_ERROR", callErr);
2180
+ }
2181
+ onStatus?.("Confirm payment", "Please approve in your wallet");
2182
+ let txHash;
2183
+ try {
2184
+ txHash = (await this.provider.request({
2185
+ method: "eth_sendTransaction",
2186
+ params: [txParams],
2187
+ }));
2188
+ }
2189
+ catch (err) {
2190
+ const msg = extractErrorMessage(err);
2191
+ if (msg.includes("rejected") ||
2192
+ msg.includes("denied") ||
2193
+ msg.includes("ACTION_REJECTED") ||
2194
+ msg.includes("User denied")) {
2195
+ throw new KwesPayError("Transaction cancelled by user", "WALLET_REJECTED", err);
2196
+ }
2197
+ throw new KwesPayError(`Contract call failed: ${msg}`, "CONTRACT_ERROR", err);
2198
+ }
2199
+ console.log("[ContractService] tx submitted:", txHash);
2200
+ onStatus?.("Waiting for confirmation", `Tx: ${txHash.slice(0, 10)}...`);
2201
+ const receipt = await this.waitForReceipt(txHash);
2202
+ console.log("[ContractService] receipt:", {
2203
+ txHash,
2204
+ status: receipt.status,
2205
+ blockNumber: receipt.blockNumber,
2206
+ });
2207
+ if (receipt.status !== 1) {
2208
+ throw new KwesPayError("Payment transaction reverted", "CONTRACT_ERROR");
2209
+ }
2210
+ return { txHash, blockNumber: receipt.blockNumber };
2211
+ }
2212
+ }
2213
+
2214
+ const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
2215
+ const GAS_BUFFER = 300000n * 2000000000n;
2216
+ class PaymentService {
2217
+ constructor(provider) {
2218
+ this.provider = provider;
2219
+ this.contractService = new ContractService(provider);
2220
+ }
2221
+ async ensureCorrectNetwork(expectedChainId, expectedNetwork, onStatus) {
2222
+ const raw = (await this.provider.request({
2223
+ method: "eth_chainId",
2224
+ }));
2225
+ const current = parseInt(raw, 16);
2226
+ if (current === expectedChainId)
2227
+ return;
2228
+ onStatus?.("Switching network", `Switching to ${expectedNetwork} (chain ${expectedChainId})…`);
2229
+ try {
2230
+ await this.provider.request({
2231
+ method: "wallet_switchEthereumChain",
2232
+ params: [{ chainId: "0x" + expectedChainId.toString(16) }],
2233
+ });
2234
+ }
2235
+ catch (switchErr) {
2236
+ const errAny = switchErr;
2237
+ if (errAny?.code === 4902) {
2238
+ throw new KwesPayError(`Network ${expectedNetwork} (chain ${expectedChainId}) is not added to your wallet. Please add it manually and retry.`, "WRONG_NETWORK");
2239
+ }
2240
+ const msg = errAny?.message ?? String(switchErr);
2241
+ if (msg.includes("rejected") ||
2242
+ msg.includes("denied") ||
2243
+ msg.includes("ACTION_REJECTED")) {
2244
+ throw new KwesPayError(`Network switch to ${expectedNetwork} was rejected. Please switch manually and retry.`, "WRONG_NETWORK");
2245
+ }
2246
+ throw new KwesPayError(`Failed to switch to ${expectedNetwork}: ${msg}`, "WRONG_NETWORK");
2247
+ }
2248
+ const confirmedRaw = (await this.provider.request({
2249
+ method: "eth_chainId",
2250
+ }));
2251
+ const confirmed = parseInt(confirmedRaw, 16);
2252
+ if (confirmed !== expectedChainId) {
2253
+ throw new KwesPayError(`Wallet is on chain ${confirmed} but payment requires chain ${expectedChainId} (${expectedNetwork}). Please switch your network and retry.`, "WRONG_NETWORK");
2254
+ }
2255
+ }
2256
+ async ensureSufficientBalance(walletAddress, tokenAddress, totalBaseUnits, onStatus) {
2257
+ const total = BigInt(totalBaseUnits);
2258
+ const isNative = tokenAddress === ZERO_ADDRESS;
2259
+ onStatus?.("Checking balance", "Verifying wallet balance…");
2260
+ const nativeRaw = (await this.provider.request({
2261
+ method: "eth_getBalance",
2262
+ params: [walletAddress, "latest"],
2263
+ }));
2264
+ const nativeBalance = nativeRaw && nativeRaw !== "0x" ? BigInt(nativeRaw) : 0n;
2265
+ if (isNative) {
2266
+ const required = total + GAS_BUFFER;
2267
+ if (nativeBalance < required) {
2268
+ throw new KwesPayError(`Insufficient native balance. Required ~${(Number(required) / 1e18).toFixed(8)} (payment + fee + gas), available: ${(Number(nativeBalance) / 1e18).toFixed(8)}.`, "INSUFFICIENT_BALANCE");
2269
+ }
2270
+ return;
2271
+ }
2272
+ if (nativeBalance < GAS_BUFFER) {
2273
+ 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");
2274
+ }
2275
+ const balanceData = "0x70a08231" + walletAddress.slice(2).toLowerCase().padStart(64, "0");
2276
+ const raw = (await this.provider.request({
2277
+ method: "eth_call",
2278
+ params: [{ to: tokenAddress, data: balanceData }, "latest"],
2279
+ }));
2280
+ const tokenBalance = raw && raw !== "0x" ? BigInt(raw) : 0n;
2281
+ if (tokenBalance < total) {
2282
+ throw new KwesPayError(`Insufficient token balance. Required: ${total.toString()} (amount + fee), available: ${tokenBalance.toString()} (base units).`, "INSUFFICIENT_BALANCE");
2283
+ }
2284
+ }
2285
+ async pay(params) {
2286
+ const { payload, onStatus } = params;
2287
+ if (!payload.paymentIdBytes32 || !payload.backendSignature) {
2288
+ throw new KwesPayError("Invalid transaction payload — missing paymentIdBytes32 or backendSignature", "TRANSACTION_FAILED");
2289
+ }
2290
+ if (!payload.vendorIdentifier) {
2291
+ throw new KwesPayError("Invalid transaction payload — missing vendorIdentifier", "TRANSACTION_FAILED");
2292
+ }
2293
+ if (!payload.totalBaseUnits) {
2294
+ throw new KwesPayError("Invalid transaction payload — missing totalBaseUnits", "TRANSACTION_FAILED");
2295
+ }
2296
+ if (!payload.deadline) {
2297
+ throw new KwesPayError("Invalid transaction payload — missing deadline", "TRANSACTION_FAILED");
2298
+ }
2299
+ if (BigInt(payload.totalBaseUnits) < BigInt(payload.amountBaseUnits)) {
2300
+ throw new KwesPayError("Invalid transaction payload — totalBaseUnits cannot be less than amountBaseUnits", "TRANSACTION_FAILED");
2301
+ }
2302
+ await this.ensureCorrectNetwork(payload.chainId, payload.network, onStatus);
2303
+ const accounts = (await this.provider.request({
2304
+ method: "eth_requestAccounts",
2305
+ }));
2306
+ const walletAddress = accounts[0];
2307
+ await this.ensureSufficientBalance(walletAddress, payload.tokenAddress, payload.totalBaseUnits, onStatus);
2308
+ const contractAddress = resolveContractAddress(payload.network);
2309
+ await this.contractService.ensureApproval(payload.tokenAddress, payload.totalBaseUnits, contractAddress, payload.chainId, onStatus);
2310
+ const { txHash, blockNumber } = await this.contractService.createPayment({
2311
+ paymentIdBytes32: payload.paymentIdBytes32,
2312
+ vendorIdentifier: payload.vendorIdentifier,
2313
+ tokenAddress: payload.tokenAddress,
2314
+ amountBaseUnits: payload.amountBaseUnits,
2315
+ totalBaseUnits: payload.totalBaseUnits,
2316
+ backendSignature: payload.backendSignature,
2317
+ contractAddress,
2318
+ deadline: payload.deadline,
2319
+ chainId: payload.chainId,
2320
+ }, onStatus);
2321
+ return {
2322
+ txHash,
2323
+ blockNumber,
2324
+ transactionReference: payload.transactionReference,
2325
+ paymentIdBytes32: payload.paymentIdBytes32,
2326
+ };
2327
+ }
2328
+ }
2329
+
2330
+ const PLATFORM_FEE_BPS = 50n; // 0.5%
2331
+ const BASIS_POINTS = 10000n;
2332
+ function computeFee(amountBaseUnits) {
2333
+ return (BigInt(amountBaseUnits) * PLATFORM_FEE_BPS) / BASIS_POINTS;
2334
+ }
2335
+ function computeTotal(amountBaseUnits) {
2336
+ return (BigInt(amountBaseUnits) + computeFee(amountBaseUnits)).toString();
2337
+ }
2338
+ class KwesPayClient {
2339
+ constructor(config) {
2340
+ if (!config.apiKey)
2341
+ throw new KwesPayError("apiKey is required", "INVALID_KEY");
2342
+ this.apiKey = config.apiKey;
2343
+ }
2344
+ async validateKey() {
2345
+ const data = await gqlRequest(GQL_VALIDATE_KEY, {
2346
+ accessKey: this.apiKey,
2347
+ });
2348
+ const r = data.validateAccessKey;
2349
+ if (!r.isValid) {
2350
+ return {
2351
+ isValid: false,
2352
+ error: r.error ?? "Invalid access key",
2353
+ };
2354
+ }
2355
+ return {
2356
+ isValid: true,
2357
+ keyId: r.keyId,
2358
+ keyLabel: r.keyLabel,
2359
+ activeFlag: r.activeFlag,
2360
+ expirationDate: r.expirationDate,
2361
+ vendorInfo: r.vendorInfo,
2362
+ scope: {
2363
+ allowedVendors: r.allowedVendors ?? null,
2364
+ allowedNetworks: r.allowedNetworks ?? null,
2365
+ allowedTokens: r.allowedTokens ?? null,
2366
+ },
2367
+ };
2368
+ }
2369
+ // getQuote (price preview only — no transaction created)
2370
+ async getQuote(params) {
2371
+ const data = await gqlRequest(GQL_CREATE_QUOTE, {
2372
+ input: {
2373
+ vendorIdentifier: params.vendorIdentifier,
2374
+ fiatAmount: params.fiatAmount,
2375
+ fiatCurrency: params.fiatCurrency ?? "USD",
2376
+ cryptoCurrency: params.cryptoCurrency,
2377
+ network: params.network,
2378
+ },
2379
+ }, this.apiKey);
2380
+ const q = data.createQuote;
2381
+ if (!q.success) {
2382
+ const msg = q.message ?? "Quote creation failed";
2383
+ throw new KwesPayError(msg, _quoteErrCode(msg));
2384
+ }
2385
+ return {
2386
+ quoteId: q.quoteId,
2387
+ cryptoCurrency: q.cryptoCurrency,
2388
+ tokenAddress: q.tokenAddress,
2389
+ amountBaseUnits: q.amountBaseUnits,
2390
+ // totalBaseUnits = amountBaseUnits + fee — safe to compute here for UI
2391
+ totalBaseUnits: computeTotal(q.amountBaseUnits),
2392
+ displayAmount: q.displayAmount,
2393
+ network: q.network,
2394
+ chainId: q.chainId,
2395
+ expiresAt: q.expiresAt,
2396
+ };
2397
+ }
2398
+ // quote() — full flow: price + transaction, returns wallet-ready payload
2399
+ async quote(params) {
2400
+ // Step 1 — get price & lock quote
2401
+ const quoteData = await gqlRequest(GQL_CREATE_QUOTE, {
2402
+ input: {
2403
+ vendorIdentifier: params.vendorIdentifier,
2404
+ fiatAmount: params.fiatAmount,
2405
+ fiatCurrency: params.fiatCurrency ?? "USD",
2406
+ cryptoCurrency: params.cryptoCurrency,
2407
+ network: params.network,
2408
+ },
2409
+ }, this.apiKey);
2410
+ const q = quoteData.createQuote;
2411
+ if (!q.success) {
2412
+ const msg = q.message ?? "Quote creation failed";
2413
+ throw new KwesPayError(msg, _quoteErrCode(msg));
2414
+ }
2415
+ // Step 2 — create transaction (backend signs payment params incl. deadline)
2416
+ const txData = await gqlRequest(GQL_CREATE_TRANSACTION, {
2417
+ input: {
2418
+ quoteId: q.quoteId,
2419
+ payerWalletAddress: params.payerWalletAddress,
2420
+ },
2421
+ }, this.apiKey);
2422
+ const t = txData.createTransaction;
2423
+ if (!t.success) {
2424
+ const msg = t.message ?? "Transaction creation failed";
2425
+ throw new KwesPayError(msg, _txErrCode(msg));
2426
+ }
2427
+ // deadline must be present — it's part of the on-chain signature
2428
+ if (!t.deadline) {
2429
+ throw new KwesPayError("Backend did not return a deadline. Cannot construct a valid payment.", "TRANSACTION_FAILED");
2430
+ }
2431
+ // totalBaseUnits: what the customer must actually send (amount + fee).
2432
+ // We compute this from the signed amountBaseUnits using the same formula
2433
+ // the contract uses: (amount * 50) / 10000. We do NOT trust a
2434
+ // client-side totalBaseUnits for security — but computing it here is safe
2435
+ // because amountBaseUnits came from the backend-signed response.
2436
+ const amountBaseUnits = t.amountBaseUnits;
2437
+ const totalBaseUnits = computeTotal(amountBaseUnits);
2438
+ return {
2439
+ paymentIdBytes32: t.paymentIdBytes32,
2440
+ backendSignature: t.backendSignature,
2441
+ tokenAddress: t.tokenAddress,
2442
+ amountBaseUnits,
2443
+ totalBaseUnits,
2444
+ chainId: t.chainId,
2445
+ deadline: t.deadline, // ← from backend, part of signed hash
2446
+ expiresAt: t.expiresAt,
2447
+ transactionReference: t.transaction.transactionReference,
2448
+ transactionStatus: t.transaction.transactionStatus,
2449
+ network: params.network,
2450
+ vendorIdentifier: params.vendorIdentifier,
2451
+ };
2452
+ }
2453
+ // pay()
2454
+ async pay(params) {
2455
+ return new PaymentService(params.provider).pay(params);
2456
+ }
2457
+ // status polling
2458
+ async getTransactionStatus(transactionReference) {
2459
+ const data = await gqlRequest(GQL_TRANSACTION_STATUS, { transactionReference });
2460
+ const r = data.getTransactionStatus;
2461
+ return {
2462
+ transactionReference: r.transactionReference,
2463
+ transactionStatus: r.transactionStatus,
2464
+ blockchainHash: r.blockchainHash,
2465
+ blockchainNetwork: r.blockchainNetwork,
2466
+ displayAmount: r.displayAmount,
2467
+ cryptoCurrency: r.cryptoCurrency,
2468
+ payerWalletAddress: r.payerWalletAddress,
2469
+ initiatedAt: r.initiatedAt,
2470
+ };
2471
+ }
2472
+ async pollTransactionStatus(transactionReference, options = {}) {
2473
+ const { onStatus, intervalMs = 4000, maxAttempts = 60 } = options;
2474
+ let attempts = 0;
2475
+ const terminal = [
2476
+ "completed",
2477
+ "failed",
2478
+ "expired",
2479
+ "underpaid",
2480
+ "overpaid",
2481
+ "refunded",
2482
+ ];
2483
+ return new Promise((resolve, reject) => {
2484
+ const id = setInterval(async () => {
2485
+ attempts++;
2486
+ try {
2487
+ const status = await this.getTransactionStatus(transactionReference);
2488
+ onStatus?.(status.transactionStatus);
2489
+ if (terminal.includes(status.transactionStatus)) {
2490
+ clearInterval(id);
2491
+ resolve(status);
2492
+ }
2493
+ else if (attempts >= maxAttempts) {
2494
+ clearInterval(id);
2495
+ reject(new KwesPayError("Status polling timed out", "UNKNOWN"));
2496
+ }
2497
+ }
2498
+ catch (err) {
2499
+ if (attempts >= maxAttempts) {
2500
+ clearInterval(id);
2501
+ reject(err);
2502
+ }
2503
+ }
2504
+ }, intervalMs);
2505
+ });
2506
+ }
2507
+ }
2508
+ // Error code helpers
2509
+ function _quoteErrCode(msg) {
2510
+ const m = msg.toLowerCase();
2511
+ if (m.includes("expired"))
2512
+ return "QUOTE_EXPIRED";
2513
+ if (m.includes("key"))
2514
+ return "INVALID_KEY";
2515
+ return "UNKNOWN";
2516
+ }
2517
+ function _txErrCode(msg) {
2518
+ const m = msg.toLowerCase();
2519
+ if (m.includes("expired"))
2520
+ return "QUOTE_EXPIRED";
2521
+ if (m.includes("already been used"))
2522
+ return "QUOTE_USED";
2523
+ if (m.includes("not found"))
2524
+ return "QUOTE_NOT_FOUND";
2525
+ if (m.includes("key"))
2526
+ return "INVALID_KEY";
2527
+ return "UNKNOWN";
2528
+ }
2529
+
2530
+ export { KwesPayClient, KwesPayError };