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