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