@lombard.finance/sdk-agentkit 0.1.0

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.
package/dist/index.cjs ADDED
@@ -0,0 +1,3738 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4
+
5
+ require('reflect-metadata');
6
+ const agentkit = require('@coinbase/agentkit');
7
+ const sdk = require('@lombard.finance/sdk');
8
+ const zod = require('zod');
9
+ const sdkCommon = require('@lombard.finance/sdk-common');
10
+ const viem = require('viem');
11
+
12
+ function defineChain(chain) {
13
+ const chainInstance = {
14
+ formatters: undefined,
15
+ fees: undefined,
16
+ serializers: undefined,
17
+ ...chain,
18
+ };
19
+ function extend(base) {
20
+ return (fnOrExtended) => {
21
+ const properties = (typeof fnOrExtended === 'function' ? fnOrExtended(base) : fnOrExtended);
22
+ const combined = { ...base, ...properties };
23
+ return Object.assign(combined, { extend: extend(combined) });
24
+ };
25
+ }
26
+ return Object.assign(chainInstance, {
27
+ extend: extend(chainInstance),
28
+ });
29
+ }
30
+
31
+ const version = '2.47.6';
32
+
33
+ let errorConfig = {
34
+ getDocsUrl: ({ docsBaseUrl, docsPath = '', docsSlug, }) => docsPath
35
+ ? `${docsBaseUrl ?? 'https://viem.sh'}${docsPath}${docsSlug ? `#${docsSlug}` : ''}`
36
+ : undefined,
37
+ version: `viem@${version}`,
38
+ };
39
+ class BaseError extends Error {
40
+ constructor(shortMessage, args = {}) {
41
+ const details = (() => {
42
+ if (args.cause instanceof BaseError)
43
+ return args.cause.details;
44
+ if (args.cause?.message)
45
+ return args.cause.message;
46
+ return args.details;
47
+ })();
48
+ const docsPath = (() => {
49
+ if (args.cause instanceof BaseError)
50
+ return args.cause.docsPath || args.docsPath;
51
+ return args.docsPath;
52
+ })();
53
+ const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath });
54
+ const message = [
55
+ shortMessage || 'An error occurred.',
56
+ '',
57
+ ...(args.metaMessages ? [...args.metaMessages, ''] : []),
58
+ ...(docsUrl ? [`Docs: ${docsUrl}`] : []),
59
+ ...(details ? [`Details: ${details}`] : []),
60
+ ...(errorConfig.version ? [`Version: ${errorConfig.version}`] : []),
61
+ ].join('\n');
62
+ super(message, args.cause ? { cause: args.cause } : undefined);
63
+ Object.defineProperty(this, "details", {
64
+ enumerable: true,
65
+ configurable: true,
66
+ writable: true,
67
+ value: void 0
68
+ });
69
+ Object.defineProperty(this, "docsPath", {
70
+ enumerable: true,
71
+ configurable: true,
72
+ writable: true,
73
+ value: void 0
74
+ });
75
+ Object.defineProperty(this, "metaMessages", {
76
+ enumerable: true,
77
+ configurable: true,
78
+ writable: true,
79
+ value: void 0
80
+ });
81
+ Object.defineProperty(this, "shortMessage", {
82
+ enumerable: true,
83
+ configurable: true,
84
+ writable: true,
85
+ value: void 0
86
+ });
87
+ Object.defineProperty(this, "version", {
88
+ enumerable: true,
89
+ configurable: true,
90
+ writable: true,
91
+ value: void 0
92
+ });
93
+ Object.defineProperty(this, "name", {
94
+ enumerable: true,
95
+ configurable: true,
96
+ writable: true,
97
+ value: 'BaseError'
98
+ });
99
+ this.details = details;
100
+ this.docsPath = docsPath;
101
+ this.metaMessages = args.metaMessages;
102
+ this.name = args.name ?? this.name;
103
+ this.shortMessage = shortMessage;
104
+ this.version = version;
105
+ }
106
+ walk(fn) {
107
+ return walk(this, fn);
108
+ }
109
+ }
110
+ function walk(err, fn) {
111
+ if (fn?.(err))
112
+ return err;
113
+ if (err &&
114
+ typeof err === 'object' &&
115
+ 'cause' in err &&
116
+ err.cause !== undefined)
117
+ return walk(err.cause, fn);
118
+ return fn ? null : err;
119
+ }
120
+
121
+ class IntegerOutOfRangeError extends BaseError {
122
+ constructor({ max, min, signed, size, value, }) {
123
+ super(`Number "${value}" is not in safe ${size ? `${size * 8}-bit ${signed ? 'signed' : 'unsigned'} ` : ''}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: 'IntegerOutOfRangeError' });
124
+ }
125
+ }
126
+ class SizeOverflowError extends BaseError {
127
+ constructor({ givenSize, maxSize }) {
128
+ super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: 'SizeOverflowError' });
129
+ }
130
+ }
131
+
132
+ function isHex(value, { strict = true } = {}) {
133
+ if (!value)
134
+ return false;
135
+ if (typeof value !== 'string')
136
+ return false;
137
+ return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith('0x');
138
+ }
139
+
140
+ /**
141
+ * @description Retrieves the size of the value (in bytes).
142
+ *
143
+ * @param value The value (hex or byte array) to retrieve the size of.
144
+ * @returns The size of the value (in bytes).
145
+ */
146
+ function size(value) {
147
+ if (isHex(value, { strict: false }))
148
+ return Math.ceil((value.length - 2) / 2);
149
+ return value.length;
150
+ }
151
+
152
+ function trim(hexOrBytes, { dir = 'left' } = {}) {
153
+ let data = typeof hexOrBytes === 'string' ? hexOrBytes.replace('0x', '') : hexOrBytes;
154
+ let sliceLength = 0;
155
+ for (let i = 0; i < data.length - 1; i++) {
156
+ if (data[dir === 'left' ? i : data.length - i - 1].toString() === '0')
157
+ sliceLength++;
158
+ else
159
+ break;
160
+ }
161
+ data =
162
+ dir === 'left'
163
+ ? data.slice(sliceLength)
164
+ : data.slice(0, data.length - sliceLength);
165
+ if (typeof hexOrBytes === 'string') {
166
+ if (data.length === 1 && dir === 'right')
167
+ data = `${data}0`;
168
+ return `0x${data.length % 2 === 1 ? `0${data}` : data}`;
169
+ }
170
+ return data;
171
+ }
172
+
173
+ class SliceOffsetOutOfBoundsError extends BaseError {
174
+ constructor({ offset, position, size, }) {
175
+ super(`Slice ${position === 'start' ? 'starting' : 'ending'} at offset "${offset}" is out-of-bounds (size: ${size}).`, { name: 'SliceOffsetOutOfBoundsError' });
176
+ }
177
+ }
178
+ class SizeExceedsPaddingSizeError extends BaseError {
179
+ constructor({ size, targetSize, type, }) {
180
+ super(`${type.charAt(0).toUpperCase()}${type
181
+ .slice(1)
182
+ .toLowerCase()} size (${size}) exceeds padding size (${targetSize}).`, { name: 'SizeExceedsPaddingSizeError' });
183
+ }
184
+ }
185
+
186
+ function pad(hexOrBytes, { dir, size = 32 } = {}) {
187
+ if (typeof hexOrBytes === 'string')
188
+ return padHex(hexOrBytes, { dir, size });
189
+ return padBytes(hexOrBytes, { dir, size });
190
+ }
191
+ function padHex(hex_, { dir, size = 32 } = {}) {
192
+ if (size === null)
193
+ return hex_;
194
+ const hex = hex_.replace('0x', '');
195
+ if (hex.length > size * 2)
196
+ throw new SizeExceedsPaddingSizeError({
197
+ size: Math.ceil(hex.length / 2),
198
+ targetSize: size,
199
+ type: 'hex',
200
+ });
201
+ return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}`;
202
+ }
203
+ function padBytes(bytes, { dir, size = 32 } = {}) {
204
+ if (size === null)
205
+ return bytes;
206
+ if (bytes.length > size)
207
+ throw new SizeExceedsPaddingSizeError({
208
+ size: bytes.length,
209
+ targetSize: size,
210
+ type: 'bytes',
211
+ });
212
+ const paddedBytes = new Uint8Array(size);
213
+ for (let i = 0; i < size; i++) {
214
+ const padEnd = dir === 'right';
215
+ paddedBytes[padEnd ? i : size - i - 1] =
216
+ bytes[padEnd ? i : bytes.length - i - 1];
217
+ }
218
+ return paddedBytes;
219
+ }
220
+
221
+ const hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, '0'));
222
+ /**
223
+ * Encodes a string, number, bigint, or ByteArray into a hex string
224
+ *
225
+ * - Docs: https://viem.sh/docs/utilities/toHex
226
+ * - Example: https://viem.sh/docs/utilities/toHex#usage
227
+ *
228
+ * @param value Value to encode.
229
+ * @param opts Options.
230
+ * @returns Hex value.
231
+ *
232
+ * @example
233
+ * import { toHex } from 'viem'
234
+ * const data = toHex('Hello world')
235
+ * // '0x48656c6c6f20776f726c6421'
236
+ *
237
+ * @example
238
+ * import { toHex } from 'viem'
239
+ * const data = toHex(420)
240
+ * // '0x1a4'
241
+ *
242
+ * @example
243
+ * import { toHex } from 'viem'
244
+ * const data = toHex('Hello world', { size: 32 })
245
+ * // '0x48656c6c6f20776f726c64210000000000000000000000000000000000000000'
246
+ */
247
+ function toHex(value, opts = {}) {
248
+ if (typeof value === 'number' || typeof value === 'bigint')
249
+ return numberToHex(value, opts);
250
+ if (typeof value === 'string') {
251
+ return stringToHex(value, opts);
252
+ }
253
+ if (typeof value === 'boolean')
254
+ return boolToHex(value, opts);
255
+ return bytesToHex(value, opts);
256
+ }
257
+ /**
258
+ * Encodes a boolean into a hex string
259
+ *
260
+ * - Docs: https://viem.sh/docs/utilities/toHex#booltohex
261
+ *
262
+ * @param value Value to encode.
263
+ * @param opts Options.
264
+ * @returns Hex value.
265
+ *
266
+ * @example
267
+ * import { boolToHex } from 'viem'
268
+ * const data = boolToHex(true)
269
+ * // '0x1'
270
+ *
271
+ * @example
272
+ * import { boolToHex } from 'viem'
273
+ * const data = boolToHex(false)
274
+ * // '0x0'
275
+ *
276
+ * @example
277
+ * import { boolToHex } from 'viem'
278
+ * const data = boolToHex(true, { size: 32 })
279
+ * // '0x0000000000000000000000000000000000000000000000000000000000000001'
280
+ */
281
+ function boolToHex(value, opts = {}) {
282
+ const hex = `0x${Number(value)}`;
283
+ if (typeof opts.size === 'number') {
284
+ assertSize(hex, { size: opts.size });
285
+ return pad(hex, { size: opts.size });
286
+ }
287
+ return hex;
288
+ }
289
+ /**
290
+ * Encodes a bytes array into a hex string
291
+ *
292
+ * - Docs: https://viem.sh/docs/utilities/toHex#bytestohex
293
+ *
294
+ * @param value Value to encode.
295
+ * @param opts Options.
296
+ * @returns Hex value.
297
+ *
298
+ * @example
299
+ * import { bytesToHex } from 'viem'
300
+ * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
301
+ * // '0x48656c6c6f20576f726c6421'
302
+ *
303
+ * @example
304
+ * import { bytesToHex } from 'viem'
305
+ * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]), { size: 32 })
306
+ * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'
307
+ */
308
+ function bytesToHex(value, opts = {}) {
309
+ let string = '';
310
+ for (let i = 0; i < value.length; i++) {
311
+ string += hexes[value[i]];
312
+ }
313
+ const hex = `0x${string}`;
314
+ if (typeof opts.size === 'number') {
315
+ assertSize(hex, { size: opts.size });
316
+ return pad(hex, { dir: 'right', size: opts.size });
317
+ }
318
+ return hex;
319
+ }
320
+ /**
321
+ * Encodes a number or bigint into a hex string
322
+ *
323
+ * - Docs: https://viem.sh/docs/utilities/toHex#numbertohex
324
+ *
325
+ * @param value Value to encode.
326
+ * @param opts Options.
327
+ * @returns Hex value.
328
+ *
329
+ * @example
330
+ * import { numberToHex } from 'viem'
331
+ * const data = numberToHex(420)
332
+ * // '0x1a4'
333
+ *
334
+ * @example
335
+ * import { numberToHex } from 'viem'
336
+ * const data = numberToHex(420, { size: 32 })
337
+ * // '0x00000000000000000000000000000000000000000000000000000000000001a4'
338
+ */
339
+ function numberToHex(value_, opts = {}) {
340
+ const { signed, size } = opts;
341
+ const value = BigInt(value_);
342
+ let maxValue;
343
+ if (size) {
344
+ if (signed)
345
+ maxValue = (1n << (BigInt(size) * 8n - 1n)) - 1n;
346
+ else
347
+ maxValue = 2n ** (BigInt(size) * 8n) - 1n;
348
+ }
349
+ else if (typeof value_ === 'number') {
350
+ maxValue = BigInt(Number.MAX_SAFE_INTEGER);
351
+ }
352
+ const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0;
353
+ if ((maxValue && value > maxValue) || value < minValue) {
354
+ const suffix = typeof value_ === 'bigint' ? 'n' : '';
355
+ throw new IntegerOutOfRangeError({
356
+ max: maxValue ? `${maxValue}${suffix}` : undefined,
357
+ min: `${minValue}${suffix}`,
358
+ signed,
359
+ size,
360
+ value: `${value_}${suffix}`,
361
+ });
362
+ }
363
+ const hex = `0x${(signed && value < 0 ? (1n << BigInt(size * 8)) + BigInt(value) : value).toString(16)}`;
364
+ if (size)
365
+ return pad(hex, { size });
366
+ return hex;
367
+ }
368
+ const encoder$1 = /*#__PURE__*/ new TextEncoder();
369
+ /**
370
+ * Encodes a UTF-8 string into a hex string
371
+ *
372
+ * - Docs: https://viem.sh/docs/utilities/toHex#stringtohex
373
+ *
374
+ * @param value Value to encode.
375
+ * @param opts Options.
376
+ * @returns Hex value.
377
+ *
378
+ * @example
379
+ * import { stringToHex } from 'viem'
380
+ * const data = stringToHex('Hello World!')
381
+ * // '0x48656c6c6f20576f726c6421'
382
+ *
383
+ * @example
384
+ * import { stringToHex } from 'viem'
385
+ * const data = stringToHex('Hello World!', { size: 32 })
386
+ * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'
387
+ */
388
+ function stringToHex(value_, opts = {}) {
389
+ const value = encoder$1.encode(value_);
390
+ return bytesToHex(value, opts);
391
+ }
392
+
393
+ const encoder = /*#__PURE__*/ new TextEncoder();
394
+ /**
395
+ * Encodes a UTF-8 string, hex value, bigint, number or boolean to a byte array.
396
+ *
397
+ * - Docs: https://viem.sh/docs/utilities/toBytes
398
+ * - Example: https://viem.sh/docs/utilities/toBytes#usage
399
+ *
400
+ * @param value Value to encode.
401
+ * @param opts Options.
402
+ * @returns Byte array value.
403
+ *
404
+ * @example
405
+ * import { toBytes } from 'viem'
406
+ * const data = toBytes('Hello world')
407
+ * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
408
+ *
409
+ * @example
410
+ * import { toBytes } from 'viem'
411
+ * const data = toBytes(420)
412
+ * // Uint8Array([1, 164])
413
+ *
414
+ * @example
415
+ * import { toBytes } from 'viem'
416
+ * const data = toBytes(420, { size: 4 })
417
+ * // Uint8Array([0, 0, 1, 164])
418
+ */
419
+ function toBytes$1(value, opts = {}) {
420
+ if (typeof value === 'number' || typeof value === 'bigint')
421
+ return numberToBytes(value, opts);
422
+ if (typeof value === 'boolean')
423
+ return boolToBytes(value, opts);
424
+ if (isHex(value))
425
+ return hexToBytes(value, opts);
426
+ return stringToBytes(value, opts);
427
+ }
428
+ /**
429
+ * Encodes a boolean into a byte array.
430
+ *
431
+ * - Docs: https://viem.sh/docs/utilities/toBytes#booltobytes
432
+ *
433
+ * @param value Boolean value to encode.
434
+ * @param opts Options.
435
+ * @returns Byte array value.
436
+ *
437
+ * @example
438
+ * import { boolToBytes } from 'viem'
439
+ * const data = boolToBytes(true)
440
+ * // Uint8Array([1])
441
+ *
442
+ * @example
443
+ * import { boolToBytes } from 'viem'
444
+ * const data = boolToBytes(true, { size: 32 })
445
+ * // 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])
446
+ */
447
+ function boolToBytes(value, opts = {}) {
448
+ const bytes = new Uint8Array(1);
449
+ bytes[0] = Number(value);
450
+ if (typeof opts.size === 'number') {
451
+ assertSize(bytes, { size: opts.size });
452
+ return pad(bytes, { size: opts.size });
453
+ }
454
+ return bytes;
455
+ }
456
+ // We use very optimized technique to convert hex string to byte array
457
+ const charCodeMap = {
458
+ zero: 48,
459
+ nine: 57,
460
+ A: 65,
461
+ F: 70,
462
+ a: 97,
463
+ f: 102,
464
+ };
465
+ function charCodeToBase16(char) {
466
+ if (char >= charCodeMap.zero && char <= charCodeMap.nine)
467
+ return char - charCodeMap.zero;
468
+ if (char >= charCodeMap.A && char <= charCodeMap.F)
469
+ return char - (charCodeMap.A - 10);
470
+ if (char >= charCodeMap.a && char <= charCodeMap.f)
471
+ return char - (charCodeMap.a - 10);
472
+ return undefined;
473
+ }
474
+ /**
475
+ * Encodes a hex string into a byte array.
476
+ *
477
+ * - Docs: https://viem.sh/docs/utilities/toBytes#hextobytes
478
+ *
479
+ * @param hex Hex string to encode.
480
+ * @param opts Options.
481
+ * @returns Byte array value.
482
+ *
483
+ * @example
484
+ * import { hexToBytes } from 'viem'
485
+ * const data = hexToBytes('0x48656c6c6f20776f726c6421')
486
+ * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])
487
+ *
488
+ * @example
489
+ * import { hexToBytes } from 'viem'
490
+ * const data = hexToBytes('0x48656c6c6f20776f726c6421', { size: 32 })
491
+ * // 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])
492
+ */
493
+ function hexToBytes(hex_, opts = {}) {
494
+ let hex = hex_;
495
+ if (opts.size) {
496
+ assertSize(hex, { size: opts.size });
497
+ hex = pad(hex, { dir: 'right', size: opts.size });
498
+ }
499
+ let hexString = hex.slice(2);
500
+ if (hexString.length % 2)
501
+ hexString = `0${hexString}`;
502
+ const length = hexString.length / 2;
503
+ const bytes = new Uint8Array(length);
504
+ for (let index = 0, j = 0; index < length; index++) {
505
+ const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++));
506
+ const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++));
507
+ if (nibbleLeft === undefined || nibbleRight === undefined) {
508
+ throw new BaseError(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`);
509
+ }
510
+ bytes[index] = nibbleLeft * 16 + nibbleRight;
511
+ }
512
+ return bytes;
513
+ }
514
+ /**
515
+ * Encodes a number into a byte array.
516
+ *
517
+ * - Docs: https://viem.sh/docs/utilities/toBytes#numbertobytes
518
+ *
519
+ * @param value Number to encode.
520
+ * @param opts Options.
521
+ * @returns Byte array value.
522
+ *
523
+ * @example
524
+ * import { numberToBytes } from 'viem'
525
+ * const data = numberToBytes(420)
526
+ * // Uint8Array([1, 164])
527
+ *
528
+ * @example
529
+ * import { numberToBytes } from 'viem'
530
+ * const data = numberToBytes(420, { size: 4 })
531
+ * // Uint8Array([0, 0, 1, 164])
532
+ */
533
+ function numberToBytes(value, opts) {
534
+ const hex = numberToHex(value, opts);
535
+ return hexToBytes(hex);
536
+ }
537
+ /**
538
+ * Encodes a UTF-8 string into a byte array.
539
+ *
540
+ * - Docs: https://viem.sh/docs/utilities/toBytes#stringtobytes
541
+ *
542
+ * @param value String to encode.
543
+ * @param opts Options.
544
+ * @returns Byte array value.
545
+ *
546
+ * @example
547
+ * import { stringToBytes } from 'viem'
548
+ * const data = stringToBytes('Hello world!')
549
+ * // Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])
550
+ *
551
+ * @example
552
+ * import { stringToBytes } from 'viem'
553
+ * const data = stringToBytes('Hello world!', { size: 32 })
554
+ * // 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])
555
+ */
556
+ function stringToBytes(value, opts = {}) {
557
+ const bytes = encoder.encode(value);
558
+ if (typeof opts.size === 'number') {
559
+ assertSize(bytes, { size: opts.size });
560
+ return pad(bytes, { dir: 'right', size: opts.size });
561
+ }
562
+ return bytes;
563
+ }
564
+
565
+ function assertSize(hexOrBytes, { size: size$1 }) {
566
+ if (size(hexOrBytes) > size$1)
567
+ throw new SizeOverflowError({
568
+ givenSize: size(hexOrBytes),
569
+ maxSize: size$1,
570
+ });
571
+ }
572
+ /**
573
+ * Decodes a hex value into a bigint.
574
+ *
575
+ * - Docs: https://viem.sh/docs/utilities/fromHex#hextobigint
576
+ *
577
+ * @param hex Hex value to decode.
578
+ * @param opts Options.
579
+ * @returns BigInt value.
580
+ *
581
+ * @example
582
+ * import { hexToBigInt } from 'viem'
583
+ * const data = hexToBigInt('0x1a4', { signed: true })
584
+ * // 420n
585
+ *
586
+ * @example
587
+ * import { hexToBigInt } from 'viem'
588
+ * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })
589
+ * // 420n
590
+ */
591
+ function hexToBigInt(hex, opts = {}) {
592
+ const { signed } = opts;
593
+ if (opts.size)
594
+ assertSize(hex, { size: opts.size });
595
+ const value = BigInt(hex);
596
+ if (!signed)
597
+ return value;
598
+ const size = (hex.length - 2) / 2;
599
+ const max = (1n << (BigInt(size) * 8n - 1n)) - 1n;
600
+ if (value <= max)
601
+ return value;
602
+ return value - BigInt(`0x${'f'.padStart(size * 2, 'f')}`) - 1n;
603
+ }
604
+ /**
605
+ * Decodes a hex string into a number.
606
+ *
607
+ * - Docs: https://viem.sh/docs/utilities/fromHex#hextonumber
608
+ *
609
+ * @param hex Hex value to decode.
610
+ * @param opts Options.
611
+ * @returns Number value.
612
+ *
613
+ * @example
614
+ * import { hexToNumber } from 'viem'
615
+ * const data = hexToNumber('0x1a4')
616
+ * // 420
617
+ *
618
+ * @example
619
+ * import { hexToNumber } from 'viem'
620
+ * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })
621
+ * // 420
622
+ */
623
+ function hexToNumber(hex, opts = {}) {
624
+ const value = hexToBigInt(hex, opts);
625
+ const number = Number(value);
626
+ if (!Number.isSafeInteger(number))
627
+ throw new IntegerOutOfRangeError({
628
+ max: `${Number.MAX_SAFE_INTEGER}`,
629
+ min: `${Number.MIN_SAFE_INTEGER}`,
630
+ signed: opts.signed,
631
+ size: opts.size,
632
+ value: `${value}n`,
633
+ });
634
+ return number;
635
+ }
636
+
637
+ function defineFormatter(type, format) {
638
+ return ({ exclude, format: overrides, }) => {
639
+ return {
640
+ exclude,
641
+ format: (args, action) => {
642
+ const formatted = format(args, action);
643
+ if (exclude) {
644
+ for (const key of exclude) {
645
+ delete formatted[key];
646
+ }
647
+ }
648
+ return {
649
+ ...formatted,
650
+ ...overrides(args, action),
651
+ };
652
+ },
653
+ type,
654
+ };
655
+ };
656
+ }
657
+
658
+ const transactionType = {
659
+ '0x0': 'legacy',
660
+ '0x1': 'eip2930',
661
+ '0x2': 'eip1559',
662
+ '0x3': 'eip4844',
663
+ '0x4': 'eip7702',
664
+ };
665
+ function formatTransaction(transaction, _) {
666
+ const transaction_ = {
667
+ ...transaction,
668
+ blockHash: transaction.blockHash ? transaction.blockHash : null,
669
+ blockNumber: transaction.blockNumber
670
+ ? BigInt(transaction.blockNumber)
671
+ : null,
672
+ chainId: transaction.chainId ? hexToNumber(transaction.chainId) : undefined,
673
+ gas: transaction.gas ? BigInt(transaction.gas) : undefined,
674
+ gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : undefined,
675
+ maxFeePerBlobGas: transaction.maxFeePerBlobGas
676
+ ? BigInt(transaction.maxFeePerBlobGas)
677
+ : undefined,
678
+ maxFeePerGas: transaction.maxFeePerGas
679
+ ? BigInt(transaction.maxFeePerGas)
680
+ : undefined,
681
+ maxPriorityFeePerGas: transaction.maxPriorityFeePerGas
682
+ ? BigInt(transaction.maxPriorityFeePerGas)
683
+ : undefined,
684
+ nonce: transaction.nonce ? hexToNumber(transaction.nonce) : undefined,
685
+ to: transaction.to ? transaction.to : null,
686
+ transactionIndex: transaction.transactionIndex
687
+ ? Number(transaction.transactionIndex)
688
+ : null,
689
+ type: transaction.type
690
+ ? transactionType[transaction.type]
691
+ : undefined,
692
+ typeHex: transaction.type ? transaction.type : undefined,
693
+ value: transaction.value ? BigInt(transaction.value) : undefined,
694
+ v: transaction.v ? BigInt(transaction.v) : undefined,
695
+ };
696
+ if (transaction.authorizationList)
697
+ transaction_.authorizationList = formatAuthorizationList(transaction.authorizationList);
698
+ transaction_.yParity = (() => {
699
+ // If `yParity` is provided, we will use it.
700
+ if (transaction.yParity)
701
+ return Number(transaction.yParity);
702
+ // If no `yParity` provided, try derive from `v`.
703
+ if (typeof transaction_.v === 'bigint') {
704
+ if (transaction_.v === 0n || transaction_.v === 27n)
705
+ return 0;
706
+ if (transaction_.v === 1n || transaction_.v === 28n)
707
+ return 1;
708
+ if (transaction_.v >= 35n)
709
+ return transaction_.v % 2n === 0n ? 1 : 0;
710
+ }
711
+ return undefined;
712
+ })();
713
+ if (transaction_.type === 'legacy') {
714
+ delete transaction_.accessList;
715
+ delete transaction_.maxFeePerBlobGas;
716
+ delete transaction_.maxFeePerGas;
717
+ delete transaction_.maxPriorityFeePerGas;
718
+ delete transaction_.yParity;
719
+ }
720
+ if (transaction_.type === 'eip2930') {
721
+ delete transaction_.maxFeePerBlobGas;
722
+ delete transaction_.maxFeePerGas;
723
+ delete transaction_.maxPriorityFeePerGas;
724
+ }
725
+ if (transaction_.type === 'eip1559')
726
+ delete transaction_.maxFeePerBlobGas;
727
+ return transaction_;
728
+ }
729
+ const defineTransaction = /*#__PURE__*/ defineFormatter('transaction', formatTransaction);
730
+ //////////////////////////////////////////////////////////////////////////////
731
+ function formatAuthorizationList(authorizationList) {
732
+ return authorizationList.map((authorization) => ({
733
+ address: authorization.address,
734
+ chainId: Number(authorization.chainId),
735
+ nonce: Number(authorization.nonce),
736
+ r: authorization.r,
737
+ s: authorization.s,
738
+ yParity: Number(authorization.yParity),
739
+ }));
740
+ }
741
+
742
+ function formatBlock(block, _) {
743
+ const transactions = (block.transactions ?? []).map((transaction) => {
744
+ if (typeof transaction === 'string')
745
+ return transaction;
746
+ return formatTransaction(transaction);
747
+ });
748
+ return {
749
+ ...block,
750
+ baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,
751
+ blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : undefined,
752
+ difficulty: block.difficulty ? BigInt(block.difficulty) : undefined,
753
+ excessBlobGas: block.excessBlobGas
754
+ ? BigInt(block.excessBlobGas)
755
+ : undefined,
756
+ gasLimit: block.gasLimit ? BigInt(block.gasLimit) : undefined,
757
+ gasUsed: block.gasUsed ? BigInt(block.gasUsed) : undefined,
758
+ hash: block.hash ? block.hash : null,
759
+ logsBloom: block.logsBloom ? block.logsBloom : null,
760
+ nonce: block.nonce ? block.nonce : null,
761
+ number: block.number ? BigInt(block.number) : null,
762
+ size: block.size ? BigInt(block.size) : undefined,
763
+ timestamp: block.timestamp ? BigInt(block.timestamp) : undefined,
764
+ transactions,
765
+ totalDifficulty: block.totalDifficulty
766
+ ? BigInt(block.totalDifficulty)
767
+ : null,
768
+ };
769
+ }
770
+ const defineBlock = /*#__PURE__*/ defineFormatter('block', formatBlock);
771
+
772
+ function formatLog(log, { args, eventName, } = {}) {
773
+ return {
774
+ ...log,
775
+ blockHash: log.blockHash ? log.blockHash : null,
776
+ blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,
777
+ blockTimestamp: log.blockTimestamp
778
+ ? BigInt(log.blockTimestamp)
779
+ : log.blockTimestamp === null
780
+ ? null
781
+ : undefined,
782
+ logIndex: log.logIndex ? Number(log.logIndex) : null,
783
+ transactionHash: log.transactionHash ? log.transactionHash : null,
784
+ transactionIndex: log.transactionIndex
785
+ ? Number(log.transactionIndex)
786
+ : null,
787
+ ...(eventName ? { args, eventName } : {}),
788
+ };
789
+ }
790
+
791
+ const receiptStatuses = {
792
+ '0x0': 'reverted',
793
+ '0x1': 'success',
794
+ };
795
+ function formatTransactionReceipt(transactionReceipt, _) {
796
+ const receipt = {
797
+ ...transactionReceipt,
798
+ blockNumber: transactionReceipt.blockNumber
799
+ ? BigInt(transactionReceipt.blockNumber)
800
+ : null,
801
+ contractAddress: transactionReceipt.contractAddress
802
+ ? transactionReceipt.contractAddress
803
+ : null,
804
+ cumulativeGasUsed: transactionReceipt.cumulativeGasUsed
805
+ ? BigInt(transactionReceipt.cumulativeGasUsed)
806
+ : null,
807
+ effectiveGasPrice: transactionReceipt.effectiveGasPrice
808
+ ? BigInt(transactionReceipt.effectiveGasPrice)
809
+ : null,
810
+ gasUsed: transactionReceipt.gasUsed
811
+ ? BigInt(transactionReceipt.gasUsed)
812
+ : null,
813
+ logs: transactionReceipt.logs
814
+ ? transactionReceipt.logs.map((log) => formatLog(log))
815
+ : null,
816
+ to: transactionReceipt.to ? transactionReceipt.to : null,
817
+ transactionIndex: transactionReceipt.transactionIndex
818
+ ? hexToNumber(transactionReceipt.transactionIndex)
819
+ : null,
820
+ status: transactionReceipt.status
821
+ ? receiptStatuses[transactionReceipt.status]
822
+ : null,
823
+ type: transactionReceipt.type
824
+ ? transactionType[transactionReceipt.type] || transactionReceipt.type
825
+ : null,
826
+ };
827
+ if (transactionReceipt.blobGasPrice)
828
+ receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice);
829
+ if (transactionReceipt.blobGasUsed)
830
+ receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed);
831
+ return receipt;
832
+ }
833
+ const defineTransactionReceipt = /*#__PURE__*/ defineFormatter('transactionReceipt', formatTransactionReceipt);
834
+
835
+ const maxUint256 = 2n ** 256n - 1n;
836
+
837
+ function concatHex(values) {
838
+ return `0x${values.reduce((acc, x) => acc + x.replace('0x', ''), '')}`;
839
+ }
840
+
841
+ class NegativeOffsetError extends BaseError {
842
+ constructor({ offset }) {
843
+ super(`Offset \`${offset}\` cannot be negative.`, {
844
+ name: 'NegativeOffsetError',
845
+ });
846
+ }
847
+ }
848
+ class PositionOutOfBoundsError extends BaseError {
849
+ constructor({ length, position }) {
850
+ super(`Position \`${position}\` is out of bounds (\`0 < position < ${length}\`).`, { name: 'PositionOutOfBoundsError' });
851
+ }
852
+ }
853
+ class RecursiveReadLimitExceededError extends BaseError {
854
+ constructor({ count, limit }) {
855
+ super(`Recursive read limit of \`${limit}\` exceeded (recursive read count: \`${count}\`).`, { name: 'RecursiveReadLimitExceededError' });
856
+ }
857
+ }
858
+
859
+ const staticCursor = {
860
+ bytes: new Uint8Array(),
861
+ dataView: new DataView(new ArrayBuffer(0)),
862
+ position: 0,
863
+ positionReadCount: new Map(),
864
+ recursiveReadCount: 0,
865
+ recursiveReadLimit: Number.POSITIVE_INFINITY,
866
+ assertReadLimit() {
867
+ if (this.recursiveReadCount >= this.recursiveReadLimit)
868
+ throw new RecursiveReadLimitExceededError({
869
+ count: this.recursiveReadCount + 1,
870
+ limit: this.recursiveReadLimit,
871
+ });
872
+ },
873
+ assertPosition(position) {
874
+ if (position < 0 || position > this.bytes.length - 1)
875
+ throw new PositionOutOfBoundsError({
876
+ length: this.bytes.length,
877
+ position,
878
+ });
879
+ },
880
+ decrementPosition(offset) {
881
+ if (offset < 0)
882
+ throw new NegativeOffsetError({ offset });
883
+ const position = this.position - offset;
884
+ this.assertPosition(position);
885
+ this.position = position;
886
+ },
887
+ getReadCount(position) {
888
+ return this.positionReadCount.get(position || this.position) || 0;
889
+ },
890
+ incrementPosition(offset) {
891
+ if (offset < 0)
892
+ throw new NegativeOffsetError({ offset });
893
+ const position = this.position + offset;
894
+ this.assertPosition(position);
895
+ this.position = position;
896
+ },
897
+ inspectByte(position_) {
898
+ const position = position_ ?? this.position;
899
+ this.assertPosition(position);
900
+ return this.bytes[position];
901
+ },
902
+ inspectBytes(length, position_) {
903
+ const position = position_ ?? this.position;
904
+ this.assertPosition(position + length - 1);
905
+ return this.bytes.subarray(position, position + length);
906
+ },
907
+ inspectUint8(position_) {
908
+ const position = position_ ?? this.position;
909
+ this.assertPosition(position);
910
+ return this.bytes[position];
911
+ },
912
+ inspectUint16(position_) {
913
+ const position = position_ ?? this.position;
914
+ this.assertPosition(position + 1);
915
+ return this.dataView.getUint16(position);
916
+ },
917
+ inspectUint24(position_) {
918
+ const position = position_ ?? this.position;
919
+ this.assertPosition(position + 2);
920
+ return ((this.dataView.getUint16(position) << 8) +
921
+ this.dataView.getUint8(position + 2));
922
+ },
923
+ inspectUint32(position_) {
924
+ const position = position_ ?? this.position;
925
+ this.assertPosition(position + 3);
926
+ return this.dataView.getUint32(position);
927
+ },
928
+ pushByte(byte) {
929
+ this.assertPosition(this.position);
930
+ this.bytes[this.position] = byte;
931
+ this.position++;
932
+ },
933
+ pushBytes(bytes) {
934
+ this.assertPosition(this.position + bytes.length - 1);
935
+ this.bytes.set(bytes, this.position);
936
+ this.position += bytes.length;
937
+ },
938
+ pushUint8(value) {
939
+ this.assertPosition(this.position);
940
+ this.bytes[this.position] = value;
941
+ this.position++;
942
+ },
943
+ pushUint16(value) {
944
+ this.assertPosition(this.position + 1);
945
+ this.dataView.setUint16(this.position, value);
946
+ this.position += 2;
947
+ },
948
+ pushUint24(value) {
949
+ this.assertPosition(this.position + 2);
950
+ this.dataView.setUint16(this.position, value >> 8);
951
+ this.dataView.setUint8(this.position + 2, value & 255);
952
+ this.position += 3;
953
+ },
954
+ pushUint32(value) {
955
+ this.assertPosition(this.position + 3);
956
+ this.dataView.setUint32(this.position, value);
957
+ this.position += 4;
958
+ },
959
+ readByte() {
960
+ this.assertReadLimit();
961
+ this._touch();
962
+ const value = this.inspectByte();
963
+ this.position++;
964
+ return value;
965
+ },
966
+ readBytes(length, size) {
967
+ this.assertReadLimit();
968
+ this._touch();
969
+ const value = this.inspectBytes(length);
970
+ this.position += size ?? length;
971
+ return value;
972
+ },
973
+ readUint8() {
974
+ this.assertReadLimit();
975
+ this._touch();
976
+ const value = this.inspectUint8();
977
+ this.position += 1;
978
+ return value;
979
+ },
980
+ readUint16() {
981
+ this.assertReadLimit();
982
+ this._touch();
983
+ const value = this.inspectUint16();
984
+ this.position += 2;
985
+ return value;
986
+ },
987
+ readUint24() {
988
+ this.assertReadLimit();
989
+ this._touch();
990
+ const value = this.inspectUint24();
991
+ this.position += 3;
992
+ return value;
993
+ },
994
+ readUint32() {
995
+ this.assertReadLimit();
996
+ this._touch();
997
+ const value = this.inspectUint32();
998
+ this.position += 4;
999
+ return value;
1000
+ },
1001
+ get remaining() {
1002
+ return this.bytes.length - this.position;
1003
+ },
1004
+ setPosition(position) {
1005
+ const oldPosition = this.position;
1006
+ this.assertPosition(position);
1007
+ this.position = position;
1008
+ return () => (this.position = oldPosition);
1009
+ },
1010
+ _touch() {
1011
+ if (this.recursiveReadLimit === Number.POSITIVE_INFINITY)
1012
+ return;
1013
+ const count = this.getReadCount();
1014
+ this.positionReadCount.set(this.position, count + 1);
1015
+ if (count > 0)
1016
+ this.recursiveReadCount++;
1017
+ },
1018
+ };
1019
+ function createCursor(bytes, { recursiveReadLimit = 8_192 } = {}) {
1020
+ const cursor = Object.create(staticCursor);
1021
+ cursor.bytes = bytes;
1022
+ cursor.dataView = new DataView(bytes.buffer ?? bytes, bytes.byteOffset, bytes.byteLength);
1023
+ cursor.positionReadCount = new Map();
1024
+ cursor.recursiveReadLimit = recursiveReadLimit;
1025
+ return cursor;
1026
+ }
1027
+
1028
+ function toRlp(bytes, to = 'hex') {
1029
+ const encodable = getEncodable(bytes);
1030
+ const cursor = createCursor(new Uint8Array(encodable.length));
1031
+ encodable.encode(cursor);
1032
+ if (to === 'hex')
1033
+ return bytesToHex(cursor.bytes);
1034
+ return cursor.bytes;
1035
+ }
1036
+ function getEncodable(bytes) {
1037
+ if (Array.isArray(bytes))
1038
+ return getEncodableList(bytes.map((x) => getEncodable(x)));
1039
+ return getEncodableBytes(bytes);
1040
+ }
1041
+ function getEncodableList(list) {
1042
+ const bodyLength = list.reduce((acc, x) => acc + x.length, 0);
1043
+ const sizeOfBodyLength = getSizeOfLength(bodyLength);
1044
+ const length = (() => {
1045
+ if (bodyLength <= 55)
1046
+ return 1 + bodyLength;
1047
+ return 1 + sizeOfBodyLength + bodyLength;
1048
+ })();
1049
+ return {
1050
+ length,
1051
+ encode(cursor) {
1052
+ if (bodyLength <= 55) {
1053
+ cursor.pushByte(0xc0 + bodyLength);
1054
+ }
1055
+ else {
1056
+ cursor.pushByte(0xc0 + 55 + sizeOfBodyLength);
1057
+ if (sizeOfBodyLength === 1)
1058
+ cursor.pushUint8(bodyLength);
1059
+ else if (sizeOfBodyLength === 2)
1060
+ cursor.pushUint16(bodyLength);
1061
+ else if (sizeOfBodyLength === 3)
1062
+ cursor.pushUint24(bodyLength);
1063
+ else
1064
+ cursor.pushUint32(bodyLength);
1065
+ }
1066
+ for (const { encode } of list) {
1067
+ encode(cursor);
1068
+ }
1069
+ },
1070
+ };
1071
+ }
1072
+ function getEncodableBytes(bytesOrHex) {
1073
+ const bytes = typeof bytesOrHex === 'string' ? hexToBytes(bytesOrHex) : bytesOrHex;
1074
+ const sizeOfBytesLength = getSizeOfLength(bytes.length);
1075
+ const length = (() => {
1076
+ if (bytes.length === 1 && bytes[0] < 0x80)
1077
+ return 1;
1078
+ if (bytes.length <= 55)
1079
+ return 1 + bytes.length;
1080
+ return 1 + sizeOfBytesLength + bytes.length;
1081
+ })();
1082
+ return {
1083
+ length,
1084
+ encode(cursor) {
1085
+ if (bytes.length === 1 && bytes[0] < 0x80) {
1086
+ cursor.pushBytes(bytes);
1087
+ }
1088
+ else if (bytes.length <= 55) {
1089
+ cursor.pushByte(0x80 + bytes.length);
1090
+ cursor.pushBytes(bytes);
1091
+ }
1092
+ else {
1093
+ cursor.pushByte(0x80 + 55 + sizeOfBytesLength);
1094
+ if (sizeOfBytesLength === 1)
1095
+ cursor.pushUint8(bytes.length);
1096
+ else if (sizeOfBytesLength === 2)
1097
+ cursor.pushUint16(bytes.length);
1098
+ else if (sizeOfBytesLength === 3)
1099
+ cursor.pushUint24(bytes.length);
1100
+ else
1101
+ cursor.pushUint32(bytes.length);
1102
+ cursor.pushBytes(bytes);
1103
+ }
1104
+ },
1105
+ };
1106
+ }
1107
+ function getSizeOfLength(length) {
1108
+ if (length < 2 ** 8)
1109
+ return 1;
1110
+ if (length < 2 ** 16)
1111
+ return 2;
1112
+ if (length < 2 ** 24)
1113
+ return 3;
1114
+ if (length < 2 ** 32)
1115
+ return 4;
1116
+ throw new BaseError('Length is too large.');
1117
+ }
1118
+
1119
+ const gweiUnits = {
1120
+ ether: -9,
1121
+ wei: 9,
1122
+ };
1123
+
1124
+ /**
1125
+ * Divides a number by a given exponent of base 10 (10exponent), and formats it into a string representation of the number..
1126
+ *
1127
+ * - Docs: https://viem.sh/docs/utilities/formatUnits
1128
+ *
1129
+ * @example
1130
+ * import { formatUnits } from 'viem'
1131
+ *
1132
+ * formatUnits(420000000000n, 9)
1133
+ * // '420'
1134
+ */
1135
+ function formatUnits(value, decimals) {
1136
+ let display = value.toString();
1137
+ const negative = display.startsWith('-');
1138
+ if (negative)
1139
+ display = display.slice(1);
1140
+ display = display.padStart(decimals, '0');
1141
+ let [integer, fraction] = [
1142
+ display.slice(0, display.length - decimals),
1143
+ display.slice(display.length - decimals),
1144
+ ];
1145
+ fraction = fraction.replace(/(0+)$/, '');
1146
+ return `${negative ? '-' : ''}${integer || '0'}${fraction ? `.${fraction}` : ''}`;
1147
+ }
1148
+
1149
+ /**
1150
+ * Converts numerical wei to a string representation of gwei.
1151
+ *
1152
+ * - Docs: https://viem.sh/docs/utilities/formatGwei
1153
+ *
1154
+ * @example
1155
+ * import { formatGwei } from 'viem'
1156
+ *
1157
+ * formatGwei(1000000000n)
1158
+ * // '1'
1159
+ */
1160
+ function formatGwei(wei, unit = 'wei') {
1161
+ return formatUnits(wei, gweiUnits[unit]);
1162
+ }
1163
+
1164
+ function prettyPrint(args) {
1165
+ const entries = Object.entries(args)
1166
+ .map(([key, value]) => {
1167
+ if (value === undefined || value === false)
1168
+ return null;
1169
+ return [key, value];
1170
+ })
1171
+ .filter(Boolean);
1172
+ const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0);
1173
+ return entries
1174
+ .map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`)
1175
+ .join('\n');
1176
+ }
1177
+ class InvalidLegacyVError extends BaseError {
1178
+ constructor({ v }) {
1179
+ super(`Invalid \`v\` value "${v}". Expected 27 or 28.`, {
1180
+ name: 'InvalidLegacyVError',
1181
+ });
1182
+ }
1183
+ }
1184
+ class InvalidSerializableTransactionError extends BaseError {
1185
+ constructor({ transaction }) {
1186
+ super('Cannot infer a transaction type from provided transaction.', {
1187
+ metaMessages: [
1188
+ 'Provided Transaction:',
1189
+ '{',
1190
+ prettyPrint(transaction),
1191
+ '}',
1192
+ '',
1193
+ 'To infer the type, either provide:',
1194
+ '- a `type` to the Transaction, or',
1195
+ '- an EIP-1559 Transaction with `maxFeePerGas`, or',
1196
+ '- an EIP-2930 Transaction with `gasPrice` & `accessList`, or',
1197
+ '- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or',
1198
+ '- an EIP-7702 Transaction with `authorizationList`, or',
1199
+ '- a Legacy Transaction with `gasPrice`',
1200
+ ],
1201
+ name: 'InvalidSerializableTransactionError',
1202
+ });
1203
+ }
1204
+ }
1205
+ class InvalidStorageKeySizeError extends BaseError {
1206
+ constructor({ storageKey }) {
1207
+ super(`Size for storage key "${storageKey}" is invalid. Expected 32 bytes. Got ${Math.floor((storageKey.length - 2) / 2)} bytes.`, { name: 'InvalidStorageKeySizeError' });
1208
+ }
1209
+ }
1210
+
1211
+ /*
1212
+ * Serializes an EIP-7702 authorization list.
1213
+ */
1214
+ function serializeAuthorizationList(authorizationList) {
1215
+ if (!authorizationList || authorizationList.length === 0)
1216
+ return [];
1217
+ const serializedAuthorizationList = [];
1218
+ for (const authorization of authorizationList) {
1219
+ const { chainId, nonce, ...signature } = authorization;
1220
+ const contractAddress = authorization.address;
1221
+ serializedAuthorizationList.push([
1222
+ chainId ? toHex(chainId) : '0x',
1223
+ contractAddress,
1224
+ nonce ? toHex(nonce) : '0x',
1225
+ ...toYParitySignatureArray({}, signature),
1226
+ ]);
1227
+ }
1228
+ return serializedAuthorizationList;
1229
+ }
1230
+
1231
+ /**
1232
+ * Compute commitments from a list of blobs.
1233
+ *
1234
+ * @example
1235
+ * ```ts
1236
+ * import { blobsToCommitments, toBlobs } from 'viem'
1237
+ * import { kzg } from './kzg'
1238
+ *
1239
+ * const blobs = toBlobs({ data: '0x1234' })
1240
+ * const commitments = blobsToCommitments({ blobs, kzg })
1241
+ * ```
1242
+ */
1243
+ function blobsToCommitments(parameters) {
1244
+ const { kzg } = parameters;
1245
+ const to = parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes');
1246
+ const blobs = (typeof parameters.blobs[0] === 'string'
1247
+ ? parameters.blobs.map((x) => hexToBytes(x))
1248
+ : parameters.blobs);
1249
+ const commitments = [];
1250
+ for (const blob of blobs)
1251
+ commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)));
1252
+ return (to === 'bytes'
1253
+ ? commitments
1254
+ : commitments.map((x) => bytesToHex(x)));
1255
+ }
1256
+
1257
+ /**
1258
+ * Compute the proofs for a list of blobs and their commitments.
1259
+ *
1260
+ * @example
1261
+ * ```ts
1262
+ * import {
1263
+ * blobsToCommitments,
1264
+ * toBlobs
1265
+ * } from 'viem'
1266
+ * import { kzg } from './kzg'
1267
+ *
1268
+ * const blobs = toBlobs({ data: '0x1234' })
1269
+ * const commitments = blobsToCommitments({ blobs, kzg })
1270
+ * const proofs = blobsToProofs({ blobs, commitments, kzg })
1271
+ * ```
1272
+ */
1273
+ function blobsToProofs(parameters) {
1274
+ const { kzg } = parameters;
1275
+ const to = parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes');
1276
+ const blobs = (typeof parameters.blobs[0] === 'string'
1277
+ ? parameters.blobs.map((x) => hexToBytes(x))
1278
+ : parameters.blobs);
1279
+ const commitments = (typeof parameters.commitments[0] === 'string'
1280
+ ? parameters.commitments.map((x) => hexToBytes(x))
1281
+ : parameters.commitments);
1282
+ const proofs = [];
1283
+ for (let i = 0; i < blobs.length; i++) {
1284
+ const blob = blobs[i];
1285
+ const commitment = commitments[i];
1286
+ proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)));
1287
+ }
1288
+ return (to === 'bytes'
1289
+ ? proofs
1290
+ : proofs.map((x) => bytesToHex(x)));
1291
+ }
1292
+
1293
+ /**
1294
+ * Utilities for hex, bytes, CSPRNG.
1295
+ * @module
1296
+ */
1297
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1298
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
1299
+ // node.js versions earlier than v19 don't declare it in global scope.
1300
+ // For node.js, package.json#exports field mapping rewrites import
1301
+ // from `crypto` to `cryptoNode`, which imports native module.
1302
+ // Makes the utils un-importable in browsers without a bundler.
1303
+ // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
1304
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
1305
+ function isBytes(a) {
1306
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
1307
+ }
1308
+ /** Asserts something is positive integer. */
1309
+ function anumber(n) {
1310
+ if (!Number.isSafeInteger(n) || n < 0)
1311
+ throw new Error('positive integer expected, got ' + n);
1312
+ }
1313
+ /** Asserts something is Uint8Array. */
1314
+ function abytes(b, ...lengths) {
1315
+ if (!isBytes(b))
1316
+ throw new Error('Uint8Array expected');
1317
+ if (lengths.length > 0 && !lengths.includes(b.length))
1318
+ throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
1319
+ }
1320
+ /** Asserts a hash instance has not been destroyed / finished */
1321
+ function aexists(instance, checkFinished = true) {
1322
+ if (instance.destroyed)
1323
+ throw new Error('Hash instance has been destroyed');
1324
+ if (checkFinished && instance.finished)
1325
+ throw new Error('Hash#digest() has already been called');
1326
+ }
1327
+ /** Asserts output is properly-sized byte array */
1328
+ function aoutput(out, instance) {
1329
+ abytes(out);
1330
+ const min = instance.outputLen;
1331
+ if (out.length < min) {
1332
+ throw new Error('digestInto() expects output buffer of length at least ' + min);
1333
+ }
1334
+ }
1335
+ /** Cast u8 / u16 / u32 to u32. */
1336
+ function u32(arr) {
1337
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
1338
+ }
1339
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
1340
+ function clean(...arrays) {
1341
+ for (let i = 0; i < arrays.length; i++) {
1342
+ arrays[i].fill(0);
1343
+ }
1344
+ }
1345
+ /** Create DataView of an array for easy byte-level manipulation. */
1346
+ function createView(arr) {
1347
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
1348
+ }
1349
+ /** The rotate right (circular right shift) operation for uint32 */
1350
+ function rotr(word, shift) {
1351
+ return (word << (32 - shift)) | (word >>> shift);
1352
+ }
1353
+ /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
1354
+ const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
1355
+ /** The byte swap operation for uint32 */
1356
+ function byteSwap(word) {
1357
+ return (((word << 24) & 0xff000000) |
1358
+ ((word << 8) & 0xff0000) |
1359
+ ((word >>> 8) & 0xff00) |
1360
+ ((word >>> 24) & 0xff));
1361
+ }
1362
+ /** In place byte swap for Uint32Array */
1363
+ function byteSwap32(arr) {
1364
+ for (let i = 0; i < arr.length; i++) {
1365
+ arr[i] = byteSwap(arr[i]);
1366
+ }
1367
+ return arr;
1368
+ }
1369
+ const swap32IfBE = isLE
1370
+ ? (u) => u
1371
+ : byteSwap32;
1372
+ /**
1373
+ * Converts string to bytes using UTF8 encoding.
1374
+ * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
1375
+ */
1376
+ function utf8ToBytes(str) {
1377
+ if (typeof str !== 'string')
1378
+ throw new Error('string expected');
1379
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
1380
+ }
1381
+ /**
1382
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
1383
+ * Warning: when Uint8Array is passed, it would NOT get copied.
1384
+ * Keep in mind for future mutable operations.
1385
+ */
1386
+ function toBytes(data) {
1387
+ if (typeof data === 'string')
1388
+ data = utf8ToBytes(data);
1389
+ abytes(data);
1390
+ return data;
1391
+ }
1392
+ /** For runtime check if class implements interface */
1393
+ class Hash {
1394
+ }
1395
+ /** Wraps hash function, creating an interface on top of it */
1396
+ function createHasher(hashCons) {
1397
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
1398
+ const tmp = hashCons();
1399
+ hashC.outputLen = tmp.outputLen;
1400
+ hashC.blockLen = tmp.blockLen;
1401
+ hashC.create = () => hashCons();
1402
+ return hashC;
1403
+ }
1404
+
1405
+ /**
1406
+ * Internal Merkle-Damgard hash utils.
1407
+ * @module
1408
+ */
1409
+ /** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
1410
+ function setBigUint64(view, byteOffset, value, isLE) {
1411
+ if (typeof view.setBigUint64 === 'function')
1412
+ return view.setBigUint64(byteOffset, value, isLE);
1413
+ const _32n = BigInt(32);
1414
+ const _u32_max = BigInt(0xffffffff);
1415
+ const wh = Number((value >> _32n) & _u32_max);
1416
+ const wl = Number(value & _u32_max);
1417
+ const h = isLE ? 4 : 0;
1418
+ const l = isLE ? 0 : 4;
1419
+ view.setUint32(byteOffset + h, wh, isLE);
1420
+ view.setUint32(byteOffset + l, wl, isLE);
1421
+ }
1422
+ /** Choice: a ? b : c */
1423
+ function Chi(a, b, c) {
1424
+ return (a & b) ^ (~a & c);
1425
+ }
1426
+ /** Majority function, true if any two inputs is true. */
1427
+ function Maj(a, b, c) {
1428
+ return (a & b) ^ (a & c) ^ (b & c);
1429
+ }
1430
+ /**
1431
+ * Merkle-Damgard hash construction base class.
1432
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
1433
+ */
1434
+ class HashMD extends Hash {
1435
+ constructor(blockLen, outputLen, padOffset, isLE) {
1436
+ super();
1437
+ this.finished = false;
1438
+ this.length = 0;
1439
+ this.pos = 0;
1440
+ this.destroyed = false;
1441
+ this.blockLen = blockLen;
1442
+ this.outputLen = outputLen;
1443
+ this.padOffset = padOffset;
1444
+ this.isLE = isLE;
1445
+ this.buffer = new Uint8Array(blockLen);
1446
+ this.view = createView(this.buffer);
1447
+ }
1448
+ update(data) {
1449
+ aexists(this);
1450
+ data = toBytes(data);
1451
+ abytes(data);
1452
+ const { view, buffer, blockLen } = this;
1453
+ const len = data.length;
1454
+ for (let pos = 0; pos < len;) {
1455
+ const take = Math.min(blockLen - this.pos, len - pos);
1456
+ // Fast path: we have at least one block in input, cast it to view and process
1457
+ if (take === blockLen) {
1458
+ const dataView = createView(data);
1459
+ for (; blockLen <= len - pos; pos += blockLen)
1460
+ this.process(dataView, pos);
1461
+ continue;
1462
+ }
1463
+ buffer.set(data.subarray(pos, pos + take), this.pos);
1464
+ this.pos += take;
1465
+ pos += take;
1466
+ if (this.pos === blockLen) {
1467
+ this.process(view, 0);
1468
+ this.pos = 0;
1469
+ }
1470
+ }
1471
+ this.length += data.length;
1472
+ this.roundClean();
1473
+ return this;
1474
+ }
1475
+ digestInto(out) {
1476
+ aexists(this);
1477
+ aoutput(out, this);
1478
+ this.finished = true;
1479
+ // Padding
1480
+ // We can avoid allocation of buffer for padding completely if it
1481
+ // was previously not allocated here. But it won't change performance.
1482
+ const { buffer, view, blockLen, isLE } = this;
1483
+ let { pos } = this;
1484
+ // append the bit '1' to the message
1485
+ buffer[pos++] = 0b10000000;
1486
+ clean(this.buffer.subarray(pos));
1487
+ // we have less than padOffset left in buffer, so we cannot put length in
1488
+ // current block, need process it and pad again
1489
+ if (this.padOffset > blockLen - pos) {
1490
+ this.process(view, 0);
1491
+ pos = 0;
1492
+ }
1493
+ // Pad until full block byte with zeros
1494
+ for (let i = pos; i < blockLen; i++)
1495
+ buffer[i] = 0;
1496
+ // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
1497
+ // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
1498
+ // So we just write lowest 64 bits of that value.
1499
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
1500
+ this.process(view, 0);
1501
+ const oview = createView(out);
1502
+ const len = this.outputLen;
1503
+ // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
1504
+ if (len % 4)
1505
+ throw new Error('_sha2: outputLen should be aligned to 32bit');
1506
+ const outLen = len / 4;
1507
+ const state = this.get();
1508
+ if (outLen > state.length)
1509
+ throw new Error('_sha2: outputLen bigger than state');
1510
+ for (let i = 0; i < outLen; i++)
1511
+ oview.setUint32(4 * i, state[i], isLE);
1512
+ }
1513
+ digest() {
1514
+ const { buffer, outputLen } = this;
1515
+ this.digestInto(buffer);
1516
+ const res = buffer.slice(0, outputLen);
1517
+ this.destroy();
1518
+ return res;
1519
+ }
1520
+ _cloneInto(to) {
1521
+ to || (to = new this.constructor());
1522
+ to.set(...this.get());
1523
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
1524
+ to.destroyed = destroyed;
1525
+ to.finished = finished;
1526
+ to.length = length;
1527
+ to.pos = pos;
1528
+ if (length % blockLen)
1529
+ to.buffer.set(buffer);
1530
+ return to;
1531
+ }
1532
+ clone() {
1533
+ return this._cloneInto();
1534
+ }
1535
+ }
1536
+ /**
1537
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
1538
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
1539
+ */
1540
+ /** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
1541
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
1542
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
1543
+ ]);
1544
+
1545
+ /**
1546
+ * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
1547
+ * @todo re-check https://issues.chromium.org/issues/42212588
1548
+ * @module
1549
+ */
1550
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
1551
+ const _32n = /* @__PURE__ */ BigInt(32);
1552
+ function fromBig(n, le = false) {
1553
+ if (le)
1554
+ return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
1555
+ return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
1556
+ }
1557
+ function split(lst, le = false) {
1558
+ const len = lst.length;
1559
+ let Ah = new Uint32Array(len);
1560
+ let Al = new Uint32Array(len);
1561
+ for (let i = 0; i < len; i++) {
1562
+ const { h, l } = fromBig(lst[i], le);
1563
+ [Ah[i], Al[i]] = [h, l];
1564
+ }
1565
+ return [Ah, Al];
1566
+ }
1567
+ // Left rotate for Shift in [1, 32)
1568
+ const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
1569
+ const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
1570
+ // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
1571
+ const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
1572
+ const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
1573
+
1574
+ /**
1575
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
1576
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
1577
+ * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
1578
+ * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
1579
+ * @module
1580
+ */
1581
+ /**
1582
+ * Round constants:
1583
+ * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
1584
+ */
1585
+ // prettier-ignore
1586
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
1587
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
1588
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
1589
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
1590
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
1591
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
1592
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
1593
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
1594
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
1595
+ ]);
1596
+ /** Reusable temporary buffer. "W" comes straight from spec. */
1597
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
1598
+ class SHA256 extends HashMD {
1599
+ constructor(outputLen = 32) {
1600
+ super(64, outputLen, 8, false);
1601
+ // We cannot use array here since array allows indexing by variable
1602
+ // which means optimizer/compiler cannot use registers.
1603
+ this.A = SHA256_IV[0] | 0;
1604
+ this.B = SHA256_IV[1] | 0;
1605
+ this.C = SHA256_IV[2] | 0;
1606
+ this.D = SHA256_IV[3] | 0;
1607
+ this.E = SHA256_IV[4] | 0;
1608
+ this.F = SHA256_IV[5] | 0;
1609
+ this.G = SHA256_IV[6] | 0;
1610
+ this.H = SHA256_IV[7] | 0;
1611
+ }
1612
+ get() {
1613
+ const { A, B, C, D, E, F, G, H } = this;
1614
+ return [A, B, C, D, E, F, G, H];
1615
+ }
1616
+ // prettier-ignore
1617
+ set(A, B, C, D, E, F, G, H) {
1618
+ this.A = A | 0;
1619
+ this.B = B | 0;
1620
+ this.C = C | 0;
1621
+ this.D = D | 0;
1622
+ this.E = E | 0;
1623
+ this.F = F | 0;
1624
+ this.G = G | 0;
1625
+ this.H = H | 0;
1626
+ }
1627
+ process(view, offset) {
1628
+ // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
1629
+ for (let i = 0; i < 16; i++, offset += 4)
1630
+ SHA256_W[i] = view.getUint32(offset, false);
1631
+ for (let i = 16; i < 64; i++) {
1632
+ const W15 = SHA256_W[i - 15];
1633
+ const W2 = SHA256_W[i - 2];
1634
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
1635
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
1636
+ SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
1637
+ }
1638
+ // Compression function main loop, 64 rounds
1639
+ let { A, B, C, D, E, F, G, H } = this;
1640
+ for (let i = 0; i < 64; i++) {
1641
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
1642
+ const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
1643
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
1644
+ const T2 = (sigma0 + Maj(A, B, C)) | 0;
1645
+ H = G;
1646
+ G = F;
1647
+ F = E;
1648
+ E = (D + T1) | 0;
1649
+ D = C;
1650
+ C = B;
1651
+ B = A;
1652
+ A = (T1 + T2) | 0;
1653
+ }
1654
+ // Add the compressed chunk to the current hash value
1655
+ A = (A + this.A) | 0;
1656
+ B = (B + this.B) | 0;
1657
+ C = (C + this.C) | 0;
1658
+ D = (D + this.D) | 0;
1659
+ E = (E + this.E) | 0;
1660
+ F = (F + this.F) | 0;
1661
+ G = (G + this.G) | 0;
1662
+ H = (H + this.H) | 0;
1663
+ this.set(A, B, C, D, E, F, G, H);
1664
+ }
1665
+ roundClean() {
1666
+ clean(SHA256_W);
1667
+ }
1668
+ destroy() {
1669
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
1670
+ clean(this.buffer);
1671
+ }
1672
+ }
1673
+ /**
1674
+ * SHA2-256 hash function from RFC 4634.
1675
+ *
1676
+ * It is the fastest JS hash, even faster than Blake3.
1677
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
1678
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
1679
+ */
1680
+ const sha256$2 = /* @__PURE__ */ createHasher(() => new SHA256());
1681
+
1682
+ /**
1683
+ * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.
1684
+ *
1685
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
1686
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
1687
+ *
1688
+ * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
1689
+ * @module
1690
+ * @deprecated
1691
+ */
1692
+ /** @deprecated Use import from `noble/hashes/sha2` module */
1693
+ const sha256$1 = sha256$2;
1694
+
1695
+ function sha256(value, to_) {
1696
+ const bytes = sha256$1(isHex(value, { strict: false }) ? toBytes$1(value) : value);
1697
+ return bytes;
1698
+ }
1699
+
1700
+ /**
1701
+ * Transform a commitment to it's versioned hash.
1702
+ *
1703
+ * @example
1704
+ * ```ts
1705
+ * import {
1706
+ * blobsToCommitments,
1707
+ * commitmentToVersionedHash,
1708
+ * toBlobs
1709
+ * } from 'viem'
1710
+ * import { kzg } from './kzg'
1711
+ *
1712
+ * const blobs = toBlobs({ data: '0x1234' })
1713
+ * const [commitment] = blobsToCommitments({ blobs, kzg })
1714
+ * const versionedHash = commitmentToVersionedHash({ commitment })
1715
+ * ```
1716
+ */
1717
+ function commitmentToVersionedHash(parameters) {
1718
+ const { commitment, version = 1 } = parameters;
1719
+ const to = parameters.to ?? (typeof commitment === 'string' ? 'hex' : 'bytes');
1720
+ const versionedHash = sha256(commitment);
1721
+ versionedHash.set([version], 0);
1722
+ return (to === 'bytes' ? versionedHash : bytesToHex(versionedHash));
1723
+ }
1724
+
1725
+ /**
1726
+ * Transform a list of commitments to their versioned hashes.
1727
+ *
1728
+ * @example
1729
+ * ```ts
1730
+ * import {
1731
+ * blobsToCommitments,
1732
+ * commitmentsToVersionedHashes,
1733
+ * toBlobs
1734
+ * } from 'viem'
1735
+ * import { kzg } from './kzg'
1736
+ *
1737
+ * const blobs = toBlobs({ data: '0x1234' })
1738
+ * const commitments = blobsToCommitments({ blobs, kzg })
1739
+ * const versionedHashes = commitmentsToVersionedHashes({ commitments })
1740
+ * ```
1741
+ */
1742
+ function commitmentsToVersionedHashes(parameters) {
1743
+ const { commitments, version } = parameters;
1744
+ const to = parameters.to ?? (typeof commitments[0] === 'string' ? 'hex' : 'bytes');
1745
+ const hashes = [];
1746
+ for (const commitment of commitments) {
1747
+ hashes.push(commitmentToVersionedHash({
1748
+ commitment,
1749
+ to,
1750
+ version,
1751
+ }));
1752
+ }
1753
+ return hashes;
1754
+ }
1755
+
1756
+ // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters
1757
+ /** Blob limit per transaction. */
1758
+ const blobsPerTransaction = 6;
1759
+ /** The number of bytes in a BLS scalar field element. */
1760
+ const bytesPerFieldElement = 32;
1761
+ /** The number of field elements in a blob. */
1762
+ const fieldElementsPerBlob = 4096;
1763
+ /** The number of bytes in a blob. */
1764
+ const bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob;
1765
+ /** Blob bytes limit per transaction. */
1766
+ const maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction -
1767
+ // terminator byte (0x80).
1768
+ 1 -
1769
+ // zero byte (0x00) appended to each field element.
1770
+ 1 * fieldElementsPerBlob * blobsPerTransaction;
1771
+
1772
+ // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters
1773
+ const versionedHashVersionKzg = 1;
1774
+
1775
+ class BlobSizeTooLargeError extends BaseError {
1776
+ constructor({ maxSize, size }) {
1777
+ super('Blob size is too large.', {
1778
+ metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size} bytes`],
1779
+ name: 'BlobSizeTooLargeError',
1780
+ });
1781
+ }
1782
+ }
1783
+ class EmptyBlobError extends BaseError {
1784
+ constructor() {
1785
+ super('Blob data must not be empty.', { name: 'EmptyBlobError' });
1786
+ }
1787
+ }
1788
+ class InvalidVersionedHashSizeError extends BaseError {
1789
+ constructor({ hash, size, }) {
1790
+ super(`Versioned hash "${hash}" size is invalid.`, {
1791
+ metaMessages: ['Expected: 32', `Received: ${size}`],
1792
+ name: 'InvalidVersionedHashSizeError',
1793
+ });
1794
+ }
1795
+ }
1796
+ class InvalidVersionedHashVersionError extends BaseError {
1797
+ constructor({ hash, version, }) {
1798
+ super(`Versioned hash "${hash}" version is invalid.`, {
1799
+ metaMessages: [
1800
+ `Expected: ${versionedHashVersionKzg}`,
1801
+ `Received: ${version}`,
1802
+ ],
1803
+ name: 'InvalidVersionedHashVersionError',
1804
+ });
1805
+ }
1806
+ }
1807
+
1808
+ /**
1809
+ * Transforms arbitrary data to blobs.
1810
+ *
1811
+ * @example
1812
+ * ```ts
1813
+ * import { toBlobs, stringToHex } from 'viem'
1814
+ *
1815
+ * const blobs = toBlobs({ data: stringToHex('hello world') })
1816
+ * ```
1817
+ */
1818
+ function toBlobs(parameters) {
1819
+ const to = parameters.to ?? (typeof parameters.data === 'string' ? 'hex' : 'bytes');
1820
+ const data = (typeof parameters.data === 'string'
1821
+ ? hexToBytes(parameters.data)
1822
+ : parameters.data);
1823
+ const size_ = size(data);
1824
+ if (!size_)
1825
+ throw new EmptyBlobError();
1826
+ if (size_ > maxBytesPerTransaction)
1827
+ throw new BlobSizeTooLargeError({
1828
+ maxSize: maxBytesPerTransaction,
1829
+ size: size_,
1830
+ });
1831
+ const blobs = [];
1832
+ let active = true;
1833
+ let position = 0;
1834
+ while (active) {
1835
+ const blob = createCursor(new Uint8Array(bytesPerBlob));
1836
+ let size = 0;
1837
+ while (size < fieldElementsPerBlob) {
1838
+ const bytes = data.slice(position, position + (bytesPerFieldElement - 1));
1839
+ // Push a zero byte so the field element doesn't overflow the BLS modulus.
1840
+ blob.pushByte(0x00);
1841
+ // Push the current segment of data bytes.
1842
+ blob.pushBytes(bytes);
1843
+ // If we detect that the current segment of data bytes is less than 31 bytes,
1844
+ // we can stop processing and push a terminator byte to indicate the end of the blob.
1845
+ if (bytes.length < 31) {
1846
+ blob.pushByte(0x80);
1847
+ active = false;
1848
+ break;
1849
+ }
1850
+ size++;
1851
+ position += 31;
1852
+ }
1853
+ blobs.push(blob);
1854
+ }
1855
+ return (to === 'bytes'
1856
+ ? blobs.map((x) => x.bytes)
1857
+ : blobs.map((x) => bytesToHex(x.bytes)));
1858
+ }
1859
+
1860
+ /**
1861
+ * Transforms arbitrary data (or blobs, commitments, & proofs) into a sidecar array.
1862
+ *
1863
+ * @example
1864
+ * ```ts
1865
+ * import { toBlobSidecars, stringToHex } from 'viem'
1866
+ *
1867
+ * const sidecars = toBlobSidecars({ data: stringToHex('hello world') })
1868
+ * ```
1869
+ *
1870
+ * @example
1871
+ * ```ts
1872
+ * import {
1873
+ * blobsToCommitments,
1874
+ * toBlobs,
1875
+ * blobsToProofs,
1876
+ * toBlobSidecars,
1877
+ * stringToHex
1878
+ * } from 'viem'
1879
+ *
1880
+ * const blobs = toBlobs({ data: stringToHex('hello world') })
1881
+ * const commitments = blobsToCommitments({ blobs, kzg })
1882
+ * const proofs = blobsToProofs({ blobs, commitments, kzg })
1883
+ *
1884
+ * const sidecars = toBlobSidecars({ blobs, commitments, proofs })
1885
+ * ```
1886
+ */
1887
+ function toBlobSidecars(parameters) {
1888
+ const { data, kzg, to } = parameters;
1889
+ const blobs = parameters.blobs ?? toBlobs({ data: data, to });
1890
+ const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg: kzg, to });
1891
+ const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg: kzg, to });
1892
+ const sidecars = [];
1893
+ for (let i = 0; i < blobs.length; i++)
1894
+ sidecars.push({
1895
+ blob: blobs[i],
1896
+ commitment: commitments[i],
1897
+ proof: proofs[i],
1898
+ });
1899
+ return sidecars;
1900
+ }
1901
+
1902
+ class InvalidAddressError extends BaseError {
1903
+ constructor({ address }) {
1904
+ super(`Address "${address}" is invalid.`, {
1905
+ metaMessages: [
1906
+ '- Address must be a hex value of 20 bytes (40 hex characters).',
1907
+ '- Address must match its checksum counterpart.',
1908
+ ],
1909
+ name: 'InvalidAddressError',
1910
+ });
1911
+ }
1912
+ }
1913
+
1914
+ class InvalidChainIdError extends BaseError {
1915
+ constructor({ chainId }) {
1916
+ super(typeof chainId === 'number'
1917
+ ? `Chain ID "${chainId}" is invalid.`
1918
+ : 'Chain ID is invalid.', { name: 'InvalidChainIdError' });
1919
+ }
1920
+ }
1921
+
1922
+ class FeeCapTooHighError extends BaseError {
1923
+ constructor({ cause, maxFeePerGas, } = {}) {
1924
+ super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ''}) cannot be higher than the maximum allowed value (2^256-1).`, {
1925
+ cause,
1926
+ name: 'FeeCapTooHighError',
1927
+ });
1928
+ }
1929
+ }
1930
+ Object.defineProperty(FeeCapTooHighError, "nodeMessage", {
1931
+ enumerable: true,
1932
+ configurable: true,
1933
+ writable: true,
1934
+ value: /max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/
1935
+ });
1936
+ class TipAboveFeeCapError extends BaseError {
1937
+ constructor({ cause, maxPriorityFeePerGas, maxFeePerGas, } = {}) {
1938
+ super([
1939
+ `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas
1940
+ ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei`
1941
+ : ''}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ''}).`,
1942
+ ].join('\n'), {
1943
+ cause,
1944
+ name: 'TipAboveFeeCapError',
1945
+ });
1946
+ }
1947
+ }
1948
+ Object.defineProperty(TipAboveFeeCapError, "nodeMessage", {
1949
+ enumerable: true,
1950
+ configurable: true,
1951
+ writable: true,
1952
+ value: /max priority fee per gas higher than max fee per gas|tip higher than fee cap/
1953
+ });
1954
+
1955
+ /**
1956
+ * Map with a LRU (Least recently used) policy.
1957
+ *
1958
+ * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
1959
+ */
1960
+ class LruMap extends Map {
1961
+ constructor(size) {
1962
+ super();
1963
+ Object.defineProperty(this, "maxSize", {
1964
+ enumerable: true,
1965
+ configurable: true,
1966
+ writable: true,
1967
+ value: void 0
1968
+ });
1969
+ this.maxSize = size;
1970
+ }
1971
+ get(key) {
1972
+ const value = super.get(key);
1973
+ if (super.has(key)) {
1974
+ super.delete(key);
1975
+ super.set(key, value);
1976
+ }
1977
+ return value;
1978
+ }
1979
+ set(key, value) {
1980
+ if (super.has(key))
1981
+ super.delete(key);
1982
+ super.set(key, value);
1983
+ if (this.maxSize && this.size > this.maxSize) {
1984
+ const firstKey = super.keys().next().value;
1985
+ if (firstKey !== undefined)
1986
+ super.delete(firstKey);
1987
+ }
1988
+ return this;
1989
+ }
1990
+ }
1991
+
1992
+ /**
1993
+ * SHA3 (keccak) hash function, based on a new "Sponge function" design.
1994
+ * Different from older hashes, the internal state is bigger than output size.
1995
+ *
1996
+ * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
1997
+ * [Website](https://keccak.team/keccak.html),
1998
+ * [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).
1999
+ *
2000
+ * Check out `sha3-addons` module for cSHAKE, k12, and others.
2001
+ * @module
2002
+ */
2003
+ // No __PURE__ annotations in sha3 header:
2004
+ // EVERYTHING is in fact used on every export.
2005
+ // Various per round constants calculations
2006
+ const _0n = BigInt(0);
2007
+ const _1n = BigInt(1);
2008
+ const _2n = BigInt(2);
2009
+ const _7n = BigInt(7);
2010
+ const _256n = BigInt(256);
2011
+ const _0x71n = BigInt(0x71);
2012
+ const SHA3_PI = [];
2013
+ const SHA3_ROTL = [];
2014
+ const _SHA3_IOTA = [];
2015
+ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
2016
+ // Pi
2017
+ [x, y] = [y, (2 * x + 3 * y) % 5];
2018
+ SHA3_PI.push(2 * (5 * y + x));
2019
+ // Rotational
2020
+ SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
2021
+ // Iota
2022
+ let t = _0n;
2023
+ for (let j = 0; j < 7; j++) {
2024
+ R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;
2025
+ if (R & _2n)
2026
+ t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);
2027
+ }
2028
+ _SHA3_IOTA.push(t);
2029
+ }
2030
+ const IOTAS = split(_SHA3_IOTA, true);
2031
+ const SHA3_IOTA_H = IOTAS[0];
2032
+ const SHA3_IOTA_L = IOTAS[1];
2033
+ // Left rotation (without 0, 32, 64)
2034
+ const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
2035
+ const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
2036
+ /** `keccakf1600` internal function, additionally allows to adjust round count. */
2037
+ function keccakP(s, rounds = 24) {
2038
+ const B = new Uint32Array(5 * 2);
2039
+ // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
2040
+ for (let round = 24 - rounds; round < 24; round++) {
2041
+ // Theta θ
2042
+ for (let x = 0; x < 10; x++)
2043
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
2044
+ for (let x = 0; x < 10; x += 2) {
2045
+ const idx1 = (x + 8) % 10;
2046
+ const idx0 = (x + 2) % 10;
2047
+ const B0 = B[idx0];
2048
+ const B1 = B[idx0 + 1];
2049
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
2050
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
2051
+ for (let y = 0; y < 50; y += 10) {
2052
+ s[x + y] ^= Th;
2053
+ s[x + y + 1] ^= Tl;
2054
+ }
2055
+ }
2056
+ // Rho (ρ) and Pi (π)
2057
+ let curH = s[2];
2058
+ let curL = s[3];
2059
+ for (let t = 0; t < 24; t++) {
2060
+ const shift = SHA3_ROTL[t];
2061
+ const Th = rotlH(curH, curL, shift);
2062
+ const Tl = rotlL(curH, curL, shift);
2063
+ const PI = SHA3_PI[t];
2064
+ curH = s[PI];
2065
+ curL = s[PI + 1];
2066
+ s[PI] = Th;
2067
+ s[PI + 1] = Tl;
2068
+ }
2069
+ // Chi (χ)
2070
+ for (let y = 0; y < 50; y += 10) {
2071
+ for (let x = 0; x < 10; x++)
2072
+ B[x] = s[y + x];
2073
+ for (let x = 0; x < 10; x++)
2074
+ s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
2075
+ }
2076
+ // Iota (ι)
2077
+ s[0] ^= SHA3_IOTA_H[round];
2078
+ s[1] ^= SHA3_IOTA_L[round];
2079
+ }
2080
+ clean(B);
2081
+ }
2082
+ /** Keccak sponge function. */
2083
+ class Keccak extends Hash {
2084
+ // NOTE: we accept arguments in bytes instead of bits here.
2085
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
2086
+ super();
2087
+ this.pos = 0;
2088
+ this.posOut = 0;
2089
+ this.finished = false;
2090
+ this.destroyed = false;
2091
+ this.enableXOF = false;
2092
+ this.blockLen = blockLen;
2093
+ this.suffix = suffix;
2094
+ this.outputLen = outputLen;
2095
+ this.enableXOF = enableXOF;
2096
+ this.rounds = rounds;
2097
+ // Can be passed from user as dkLen
2098
+ anumber(outputLen);
2099
+ // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
2100
+ // 0 < blockLen < 200
2101
+ if (!(0 < blockLen && blockLen < 200))
2102
+ throw new Error('only keccak-f1600 function is supported');
2103
+ this.state = new Uint8Array(200);
2104
+ this.state32 = u32(this.state);
2105
+ }
2106
+ clone() {
2107
+ return this._cloneInto();
2108
+ }
2109
+ keccak() {
2110
+ swap32IfBE(this.state32);
2111
+ keccakP(this.state32, this.rounds);
2112
+ swap32IfBE(this.state32);
2113
+ this.posOut = 0;
2114
+ this.pos = 0;
2115
+ }
2116
+ update(data) {
2117
+ aexists(this);
2118
+ data = toBytes(data);
2119
+ abytes(data);
2120
+ const { blockLen, state } = this;
2121
+ const len = data.length;
2122
+ for (let pos = 0; pos < len;) {
2123
+ const take = Math.min(blockLen - this.pos, len - pos);
2124
+ for (let i = 0; i < take; i++)
2125
+ state[this.pos++] ^= data[pos++];
2126
+ if (this.pos === blockLen)
2127
+ this.keccak();
2128
+ }
2129
+ return this;
2130
+ }
2131
+ finish() {
2132
+ if (this.finished)
2133
+ return;
2134
+ this.finished = true;
2135
+ const { state, suffix, pos, blockLen } = this;
2136
+ // Do the padding
2137
+ state[pos] ^= suffix;
2138
+ if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
2139
+ this.keccak();
2140
+ state[blockLen - 1] ^= 0x80;
2141
+ this.keccak();
2142
+ }
2143
+ writeInto(out) {
2144
+ aexists(this, false);
2145
+ abytes(out);
2146
+ this.finish();
2147
+ const bufferOut = this.state;
2148
+ const { blockLen } = this;
2149
+ for (let pos = 0, len = out.length; pos < len;) {
2150
+ if (this.posOut >= blockLen)
2151
+ this.keccak();
2152
+ const take = Math.min(blockLen - this.posOut, len - pos);
2153
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
2154
+ this.posOut += take;
2155
+ pos += take;
2156
+ }
2157
+ return out;
2158
+ }
2159
+ xofInto(out) {
2160
+ // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
2161
+ if (!this.enableXOF)
2162
+ throw new Error('XOF is not possible for this instance');
2163
+ return this.writeInto(out);
2164
+ }
2165
+ xof(bytes) {
2166
+ anumber(bytes);
2167
+ return this.xofInto(new Uint8Array(bytes));
2168
+ }
2169
+ digestInto(out) {
2170
+ aoutput(out, this);
2171
+ if (this.finished)
2172
+ throw new Error('digest() was already called');
2173
+ this.writeInto(out);
2174
+ this.destroy();
2175
+ return out;
2176
+ }
2177
+ digest() {
2178
+ return this.digestInto(new Uint8Array(this.outputLen));
2179
+ }
2180
+ destroy() {
2181
+ this.destroyed = true;
2182
+ clean(this.state);
2183
+ }
2184
+ _cloneInto(to) {
2185
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
2186
+ to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
2187
+ to.state32.set(this.state32);
2188
+ to.pos = this.pos;
2189
+ to.posOut = this.posOut;
2190
+ to.finished = this.finished;
2191
+ to.rounds = rounds;
2192
+ // Suffix can change in cSHAKE
2193
+ to.suffix = suffix;
2194
+ to.outputLen = outputLen;
2195
+ to.enableXOF = enableXOF;
2196
+ to.destroyed = this.destroyed;
2197
+ return to;
2198
+ }
2199
+ }
2200
+ const gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
2201
+ /** keccak-256 hash function. Different from SHA3-256. */
2202
+ const keccak_256 = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();
2203
+
2204
+ function keccak256(value, to_) {
2205
+ const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes$1(value) : value);
2206
+ return bytes;
2207
+ }
2208
+
2209
+ const checksumAddressCache = /*#__PURE__*/ new LruMap(8192);
2210
+ function checksumAddress(address_,
2211
+ /**
2212
+ * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the
2213
+ * wider Ethereum ecosystem, meaning it will break when validated against an application/tool
2214
+ * that relies on EIP-55 checksum encoding (checksum without chainId).
2215
+ *
2216
+ * It is highly recommended to not use this feature unless you
2217
+ * know what you are doing.
2218
+ *
2219
+ * See more: https://github.com/ethereum/EIPs/issues/1121
2220
+ */
2221
+ chainId) {
2222
+ if (checksumAddressCache.has(`${address_}.${chainId}`))
2223
+ return checksumAddressCache.get(`${address_}.${chainId}`);
2224
+ const hexAddress = address_.substring(2).toLowerCase();
2225
+ const hash = keccak256(stringToBytes(hexAddress));
2226
+ const address = (hexAddress).split('');
2227
+ for (let i = 0; i < 40; i += 2) {
2228
+ if (hash[i >> 1] >> 4 >= 8 && address[i]) {
2229
+ address[i] = address[i].toUpperCase();
2230
+ }
2231
+ if ((hash[i >> 1] & 0x0f) >= 8 && address[i + 1]) {
2232
+ address[i + 1] = address[i + 1].toUpperCase();
2233
+ }
2234
+ }
2235
+ const result = `0x${address.join('')}`;
2236
+ checksumAddressCache.set(`${address_}.${chainId}`, result);
2237
+ return result;
2238
+ }
2239
+
2240
+ const addressRegex = /^0x[a-fA-F0-9]{40}$/;
2241
+ /** @internal */
2242
+ const isAddressCache = /*#__PURE__*/ new LruMap(8192);
2243
+ function isAddress(address, options) {
2244
+ const { strict = true } = options ?? {};
2245
+ const cacheKey = `${address}.${strict}`;
2246
+ if (isAddressCache.has(cacheKey))
2247
+ return isAddressCache.get(cacheKey);
2248
+ const result = (() => {
2249
+ if (!addressRegex.test(address))
2250
+ return false;
2251
+ if (address.toLowerCase() === address)
2252
+ return true;
2253
+ if (strict)
2254
+ return checksumAddress(address) === address;
2255
+ return true;
2256
+ })();
2257
+ isAddressCache.set(cacheKey, result);
2258
+ return result;
2259
+ }
2260
+
2261
+ /**
2262
+ * @description Returns a section of the hex or byte array given a start/end bytes offset.
2263
+ *
2264
+ * @param value The hex or byte array to slice.
2265
+ * @param start The start offset (in bytes).
2266
+ * @param end The end offset (in bytes).
2267
+ */
2268
+ function slice(value, start, end, { strict } = {}) {
2269
+ if (isHex(value, { strict: false }))
2270
+ return sliceHex(value, start, end, {
2271
+ strict,
2272
+ });
2273
+ return sliceBytes(value, start, end, {
2274
+ strict,
2275
+ });
2276
+ }
2277
+ function assertEndOffset(value, start, end) {
2278
+ if (size(value) !== end - start) {
2279
+ throw new SliceOffsetOutOfBoundsError({
2280
+ offset: end,
2281
+ position: 'end',
2282
+ size: size(value),
2283
+ });
2284
+ }
2285
+ }
2286
+ /**
2287
+ * @description Returns a section of the byte array given a start/end bytes offset.
2288
+ *
2289
+ * @param value The byte array to slice.
2290
+ * @param start The start offset (in bytes).
2291
+ * @param end The end offset (in bytes).
2292
+ */
2293
+ function sliceBytes(value_, start, end, { strict } = {}) {
2294
+ const value = value_.slice(start, end);
2295
+ if (strict)
2296
+ assertEndOffset(value, start, end);
2297
+ return value;
2298
+ }
2299
+ /**
2300
+ * @description Returns a section of the hex value given a start/end bytes offset.
2301
+ *
2302
+ * @param value The hex value to slice.
2303
+ * @param start The start offset (in bytes).
2304
+ * @param end The end offset (in bytes).
2305
+ */
2306
+ function sliceHex(value_, start, end, { strict } = {}) {
2307
+ const value = `0x${value_
2308
+ .replace('0x', '')
2309
+ .slice((start) * 2, (end) * 2)}`;
2310
+ if (strict)
2311
+ assertEndOffset(value, start, end);
2312
+ return value;
2313
+ }
2314
+
2315
+ function assertTransactionEIP7702(transaction) {
2316
+ const { authorizationList } = transaction;
2317
+ if (authorizationList) {
2318
+ for (const authorization of authorizationList) {
2319
+ const { chainId } = authorization;
2320
+ const address = authorization.address;
2321
+ if (!isAddress(address))
2322
+ throw new InvalidAddressError({ address });
2323
+ if (chainId < 0)
2324
+ throw new InvalidChainIdError({ chainId });
2325
+ }
2326
+ }
2327
+ assertTransactionEIP1559(transaction);
2328
+ }
2329
+ function assertTransactionEIP4844(transaction) {
2330
+ const { blobVersionedHashes } = transaction;
2331
+ if (blobVersionedHashes) {
2332
+ if (blobVersionedHashes.length === 0)
2333
+ throw new EmptyBlobError();
2334
+ for (const hash of blobVersionedHashes) {
2335
+ const size_ = size(hash);
2336
+ const version = hexToNumber(slice(hash, 0, 1));
2337
+ if (size_ !== 32)
2338
+ throw new InvalidVersionedHashSizeError({ hash, size: size_ });
2339
+ if (version !== versionedHashVersionKzg)
2340
+ throw new InvalidVersionedHashVersionError({
2341
+ hash,
2342
+ version,
2343
+ });
2344
+ }
2345
+ }
2346
+ assertTransactionEIP1559(transaction);
2347
+ }
2348
+ function assertTransactionEIP1559(transaction) {
2349
+ const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction;
2350
+ if (chainId <= 0)
2351
+ throw new InvalidChainIdError({ chainId });
2352
+ if (to && !isAddress(to))
2353
+ throw new InvalidAddressError({ address: to });
2354
+ if (maxFeePerGas && maxFeePerGas > maxUint256)
2355
+ throw new FeeCapTooHighError({ maxFeePerGas });
2356
+ if (maxPriorityFeePerGas &&
2357
+ maxFeePerGas &&
2358
+ maxPriorityFeePerGas > maxFeePerGas)
2359
+ throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });
2360
+ }
2361
+ function assertTransactionEIP2930(transaction) {
2362
+ const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;
2363
+ if (chainId <= 0)
2364
+ throw new InvalidChainIdError({ chainId });
2365
+ if (to && !isAddress(to))
2366
+ throw new InvalidAddressError({ address: to });
2367
+ if (maxPriorityFeePerGas || maxFeePerGas)
2368
+ throw new BaseError('`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.');
2369
+ if (gasPrice && gasPrice > maxUint256)
2370
+ throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });
2371
+ }
2372
+ function assertTransactionLegacy(transaction) {
2373
+ const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;
2374
+ if (to && !isAddress(to))
2375
+ throw new InvalidAddressError({ address: to });
2376
+ if (typeof chainId !== 'undefined' && chainId <= 0)
2377
+ throw new InvalidChainIdError({ chainId });
2378
+ if (maxPriorityFeePerGas || maxFeePerGas)
2379
+ throw new BaseError('`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.');
2380
+ if (gasPrice && gasPrice > maxUint256)
2381
+ throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });
2382
+ }
2383
+
2384
+ function getTransactionType(transaction) {
2385
+ if (transaction.type)
2386
+ return transaction.type;
2387
+ if (typeof transaction.authorizationList !== 'undefined')
2388
+ return 'eip7702';
2389
+ if (typeof transaction.blobs !== 'undefined' ||
2390
+ typeof transaction.blobVersionedHashes !== 'undefined' ||
2391
+ typeof transaction.maxFeePerBlobGas !== 'undefined' ||
2392
+ typeof transaction.sidecars !== 'undefined')
2393
+ return 'eip4844';
2394
+ if (typeof transaction.maxFeePerGas !== 'undefined' ||
2395
+ typeof transaction.maxPriorityFeePerGas !== 'undefined') {
2396
+ return 'eip1559';
2397
+ }
2398
+ if (typeof transaction.gasPrice !== 'undefined') {
2399
+ if (typeof transaction.accessList !== 'undefined')
2400
+ return 'eip2930';
2401
+ return 'legacy';
2402
+ }
2403
+ throw new InvalidSerializableTransactionError({ transaction });
2404
+ }
2405
+
2406
+ /*
2407
+ * Serialize an EIP-2930 access list
2408
+ * @remarks
2409
+ * Use to create a transaction serializer with support for EIP-2930 access lists
2410
+ *
2411
+ * @param accessList - Array of objects of address and arrays of Storage Keys
2412
+ * @throws InvalidAddressError, InvalidStorageKeySizeError
2413
+ * @returns Array of hex strings
2414
+ */
2415
+ function serializeAccessList(accessList) {
2416
+ if (!accessList || accessList.length === 0)
2417
+ return [];
2418
+ const serializedAccessList = [];
2419
+ for (let i = 0; i < accessList.length; i++) {
2420
+ const { address, storageKeys } = accessList[i];
2421
+ for (let j = 0; j < storageKeys.length; j++) {
2422
+ if (storageKeys[j].length - 2 !== 64) {
2423
+ throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] });
2424
+ }
2425
+ }
2426
+ if (!isAddress(address, { strict: false })) {
2427
+ throw new InvalidAddressError({ address });
2428
+ }
2429
+ serializedAccessList.push([address, storageKeys]);
2430
+ }
2431
+ return serializedAccessList;
2432
+ }
2433
+
2434
+ function serializeTransaction$1(transaction, signature) {
2435
+ const type = getTransactionType(transaction);
2436
+ if (type === 'eip1559')
2437
+ return serializeTransactionEIP1559(transaction, signature);
2438
+ if (type === 'eip2930')
2439
+ return serializeTransactionEIP2930(transaction, signature);
2440
+ if (type === 'eip4844')
2441
+ return serializeTransactionEIP4844(transaction, signature);
2442
+ if (type === 'eip7702')
2443
+ return serializeTransactionEIP7702(transaction, signature);
2444
+ return serializeTransactionLegacy(transaction, signature);
2445
+ }
2446
+ function serializeTransactionEIP7702(transaction, signature) {
2447
+ const { authorizationList, chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data, } = transaction;
2448
+ assertTransactionEIP7702(transaction);
2449
+ const serializedAccessList = serializeAccessList(accessList);
2450
+ const serializedAuthorizationList = serializeAuthorizationList(authorizationList);
2451
+ return concatHex([
2452
+ '0x04',
2453
+ toRlp([
2454
+ numberToHex(chainId),
2455
+ nonce ? numberToHex(nonce) : '0x',
2456
+ maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',
2457
+ maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',
2458
+ gas ? numberToHex(gas) : '0x',
2459
+ to ?? '0x',
2460
+ value ? numberToHex(value) : '0x',
2461
+ data ?? '0x',
2462
+ serializedAccessList,
2463
+ serializedAuthorizationList,
2464
+ ...toYParitySignatureArray(transaction, signature),
2465
+ ]),
2466
+ ]);
2467
+ }
2468
+ function serializeTransactionEIP4844(transaction, signature) {
2469
+ const { chainId, gas, nonce, to, value, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, accessList, data, } = transaction;
2470
+ assertTransactionEIP4844(transaction);
2471
+ let blobVersionedHashes = transaction.blobVersionedHashes;
2472
+ let sidecars = transaction.sidecars;
2473
+ // If `blobs` are passed, we will need to compute the KZG commitments & proofs.
2474
+ if (transaction.blobs &&
2475
+ (typeof blobVersionedHashes === 'undefined' ||
2476
+ typeof sidecars === 'undefined')) {
2477
+ const blobs = (typeof transaction.blobs[0] === 'string'
2478
+ ? transaction.blobs
2479
+ : transaction.blobs.map((x) => bytesToHex(x)));
2480
+ const kzg = transaction.kzg;
2481
+ const commitments = blobsToCommitments({
2482
+ blobs,
2483
+ kzg,
2484
+ });
2485
+ if (typeof blobVersionedHashes === 'undefined')
2486
+ blobVersionedHashes = commitmentsToVersionedHashes({
2487
+ commitments,
2488
+ });
2489
+ if (typeof sidecars === 'undefined') {
2490
+ const proofs = blobsToProofs({ blobs, commitments, kzg });
2491
+ sidecars = toBlobSidecars({ blobs, commitments, proofs });
2492
+ }
2493
+ }
2494
+ const serializedAccessList = serializeAccessList(accessList);
2495
+ const serializedTransaction = [
2496
+ numberToHex(chainId),
2497
+ nonce ? numberToHex(nonce) : '0x',
2498
+ maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',
2499
+ maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',
2500
+ gas ? numberToHex(gas) : '0x',
2501
+ to ?? '0x',
2502
+ value ? numberToHex(value) : '0x',
2503
+ data ?? '0x',
2504
+ serializedAccessList,
2505
+ maxFeePerBlobGas ? numberToHex(maxFeePerBlobGas) : '0x',
2506
+ blobVersionedHashes ?? [],
2507
+ ...toYParitySignatureArray(transaction, signature),
2508
+ ];
2509
+ const blobs = [];
2510
+ const commitments = [];
2511
+ const proofs = [];
2512
+ if (sidecars)
2513
+ for (let i = 0; i < sidecars.length; i++) {
2514
+ const { blob, commitment, proof } = sidecars[i];
2515
+ blobs.push(blob);
2516
+ commitments.push(commitment);
2517
+ proofs.push(proof);
2518
+ }
2519
+ return concatHex([
2520
+ '0x03',
2521
+ sidecars
2522
+ ? // If sidecars are enabled, envelope turns into a "wrapper":
2523
+ toRlp([serializedTransaction, blobs, commitments, proofs])
2524
+ : // If sidecars are disabled, standard envelope is used:
2525
+ toRlp(serializedTransaction),
2526
+ ]);
2527
+ }
2528
+ function serializeTransactionEIP1559(transaction, signature) {
2529
+ const { chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data, } = transaction;
2530
+ assertTransactionEIP1559(transaction);
2531
+ const serializedAccessList = serializeAccessList(accessList);
2532
+ const serializedTransaction = [
2533
+ numberToHex(chainId),
2534
+ nonce ? numberToHex(nonce) : '0x',
2535
+ maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',
2536
+ maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',
2537
+ gas ? numberToHex(gas) : '0x',
2538
+ to ?? '0x',
2539
+ value ? numberToHex(value) : '0x',
2540
+ data ?? '0x',
2541
+ serializedAccessList,
2542
+ ...toYParitySignatureArray(transaction, signature),
2543
+ ];
2544
+ return concatHex([
2545
+ '0x02',
2546
+ toRlp(serializedTransaction),
2547
+ ]);
2548
+ }
2549
+ function serializeTransactionEIP2930(transaction, signature) {
2550
+ const { chainId, gas, data, nonce, to, value, accessList, gasPrice } = transaction;
2551
+ assertTransactionEIP2930(transaction);
2552
+ const serializedAccessList = serializeAccessList(accessList);
2553
+ const serializedTransaction = [
2554
+ numberToHex(chainId),
2555
+ nonce ? numberToHex(nonce) : '0x',
2556
+ gasPrice ? numberToHex(gasPrice) : '0x',
2557
+ gas ? numberToHex(gas) : '0x',
2558
+ to ?? '0x',
2559
+ value ? numberToHex(value) : '0x',
2560
+ data ?? '0x',
2561
+ serializedAccessList,
2562
+ ...toYParitySignatureArray(transaction, signature),
2563
+ ];
2564
+ return concatHex([
2565
+ '0x01',
2566
+ toRlp(serializedTransaction),
2567
+ ]);
2568
+ }
2569
+ function serializeTransactionLegacy(transaction, signature) {
2570
+ const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction;
2571
+ assertTransactionLegacy(transaction);
2572
+ let serializedTransaction = [
2573
+ nonce ? numberToHex(nonce) : '0x',
2574
+ gasPrice ? numberToHex(gasPrice) : '0x',
2575
+ gas ? numberToHex(gas) : '0x',
2576
+ to ?? '0x',
2577
+ value ? numberToHex(value) : '0x',
2578
+ data ?? '0x',
2579
+ ];
2580
+ if (signature) {
2581
+ const v = (() => {
2582
+ // EIP-155 (inferred chainId)
2583
+ if (signature.v >= 35n) {
2584
+ const inferredChainId = (signature.v - 35n) / 2n;
2585
+ if (inferredChainId > 0)
2586
+ return signature.v;
2587
+ return 27n + (signature.v === 35n ? 0n : 1n);
2588
+ }
2589
+ // EIP-155 (explicit chainId)
2590
+ if (chainId > 0)
2591
+ return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n);
2592
+ // Pre-EIP-155 (no chainId)
2593
+ const v = 27n + (signature.v === 27n ? 0n : 1n);
2594
+ if (signature.v !== v)
2595
+ throw new InvalidLegacyVError({ v: signature.v });
2596
+ return v;
2597
+ })();
2598
+ const r = trim(signature.r);
2599
+ const s = trim(signature.s);
2600
+ serializedTransaction = [
2601
+ ...serializedTransaction,
2602
+ numberToHex(v),
2603
+ r === '0x00' ? '0x' : r,
2604
+ s === '0x00' ? '0x' : s,
2605
+ ];
2606
+ }
2607
+ else if (chainId > 0) {
2608
+ serializedTransaction = [
2609
+ ...serializedTransaction,
2610
+ numberToHex(chainId),
2611
+ '0x',
2612
+ '0x',
2613
+ ];
2614
+ }
2615
+ return toRlp(serializedTransaction);
2616
+ }
2617
+ function toYParitySignatureArray(transaction, signature_) {
2618
+ const signature = signature_ ?? transaction;
2619
+ const { v, yParity } = signature;
2620
+ if (typeof signature.r === 'undefined')
2621
+ return [];
2622
+ if (typeof signature.s === 'undefined')
2623
+ return [];
2624
+ if (typeof v === 'undefined' && typeof yParity === 'undefined')
2625
+ return [];
2626
+ const r = trim(signature.r);
2627
+ const s = trim(signature.s);
2628
+ const yParity_ = (() => {
2629
+ if (typeof yParity === 'number')
2630
+ return yParity ? numberToHex(1) : '0x';
2631
+ if (v === 0n)
2632
+ return '0x';
2633
+ if (v === 1n)
2634
+ return numberToHex(1);
2635
+ return v === 27n ? '0x' : numberToHex(1);
2636
+ })();
2637
+ return [yParity_, r === '0x00' ? '0x' : r, s === '0x00' ? '0x' : s];
2638
+ }
2639
+
2640
+ /**
2641
+ * Predeploy contracts for OP Stack.
2642
+ * @see https://github.com/ethereum-optimism/optimism/blob/develop/specs/predeploys.md
2643
+ */
2644
+ const contracts = {
2645
+ gasPriceOracle: { address: '0x420000000000000000000000000000000000000F' },
2646
+ l1Block: { address: '0x4200000000000000000000000000000000000015' },
2647
+ l2CrossDomainMessenger: {
2648
+ address: '0x4200000000000000000000000000000000000007',
2649
+ },
2650
+ l2Erc721Bridge: { address: '0x4200000000000000000000000000000000000014' },
2651
+ l2StandardBridge: { address: '0x4200000000000000000000000000000000000010' },
2652
+ l2ToL1MessagePasser: {
2653
+ address: '0x4200000000000000000000000000000000000016',
2654
+ },
2655
+ };
2656
+
2657
+ const formatters = {
2658
+ block: /*#__PURE__*/ defineBlock({
2659
+ format(args) {
2660
+ const transactions = args.transactions?.map((transaction) => {
2661
+ if (typeof transaction === 'string')
2662
+ return transaction;
2663
+ const formatted = formatTransaction(transaction);
2664
+ if (formatted.typeHex === '0x7e') {
2665
+ formatted.isSystemTx = transaction.isSystemTx;
2666
+ formatted.mint = transaction.mint
2667
+ ? hexToBigInt(transaction.mint)
2668
+ : undefined;
2669
+ formatted.sourceHash = transaction.sourceHash;
2670
+ formatted.type = 'deposit';
2671
+ }
2672
+ return formatted;
2673
+ });
2674
+ return {
2675
+ transactions,
2676
+ stateRoot: args.stateRoot,
2677
+ };
2678
+ },
2679
+ }),
2680
+ transaction: /*#__PURE__*/ defineTransaction({
2681
+ format(args) {
2682
+ const transaction = {};
2683
+ if (args.type === '0x7e') {
2684
+ transaction.isSystemTx = args.isSystemTx;
2685
+ transaction.mint = args.mint ? hexToBigInt(args.mint) : undefined;
2686
+ transaction.sourceHash = args.sourceHash;
2687
+ transaction.type = 'deposit';
2688
+ }
2689
+ return transaction;
2690
+ },
2691
+ }),
2692
+ transactionReceipt: /*#__PURE__*/ defineTransactionReceipt({
2693
+ format(args) {
2694
+ return {
2695
+ l1GasPrice: args.l1GasPrice ? hexToBigInt(args.l1GasPrice) : null,
2696
+ l1GasUsed: args.l1GasUsed ? hexToBigInt(args.l1GasUsed) : null,
2697
+ l1Fee: args.l1Fee ? hexToBigInt(args.l1Fee) : null,
2698
+ l1FeeScalar: args.l1FeeScalar ? Number(args.l1FeeScalar) : null,
2699
+ };
2700
+ },
2701
+ }),
2702
+ };
2703
+
2704
+ function serializeTransaction(transaction, signature) {
2705
+ if (isDeposit(transaction))
2706
+ return serializeTransactionDeposit(transaction);
2707
+ return serializeTransaction$1(transaction, signature);
2708
+ }
2709
+ const serializers = {
2710
+ transaction: serializeTransaction,
2711
+ };
2712
+ function serializeTransactionDeposit(transaction) {
2713
+ assertTransactionDeposit(transaction);
2714
+ const { sourceHash, data, from, gas, isSystemTx, mint, to, value } = transaction;
2715
+ const serializedTransaction = [
2716
+ sourceHash,
2717
+ from,
2718
+ to ?? '0x',
2719
+ mint ? toHex(mint) : '0x',
2720
+ value ? toHex(value) : '0x',
2721
+ gas ? toHex(gas) : '0x',
2722
+ isSystemTx ? '0x1' : '0x',
2723
+ data ?? '0x',
2724
+ ];
2725
+ return concatHex([
2726
+ '0x7e',
2727
+ toRlp(serializedTransaction),
2728
+ ]);
2729
+ }
2730
+ function isDeposit(transaction) {
2731
+ if (transaction.type === 'deposit')
2732
+ return true;
2733
+ if (typeof transaction.sourceHash !== 'undefined')
2734
+ return true;
2735
+ return false;
2736
+ }
2737
+ function assertTransactionDeposit(transaction) {
2738
+ const { from, to } = transaction;
2739
+ if (from && !isAddress(from))
2740
+ throw new InvalidAddressError({ address: from });
2741
+ if (to && !isAddress(to))
2742
+ throw new InvalidAddressError({ address: to });
2743
+ }
2744
+
2745
+ const chainConfig = {
2746
+ blockTime: 2_000,
2747
+ contracts,
2748
+ formatters,
2749
+ serializers,
2750
+ };
2751
+
2752
+ const sourceId$1 = 1; // mainnet
2753
+ const base = /*#__PURE__*/ defineChain({
2754
+ ...chainConfig,
2755
+ id: 8453,
2756
+ name: 'Base',
2757
+ nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
2758
+ rpcUrls: {
2759
+ default: {
2760
+ http: ['https://mainnet.base.org'],
2761
+ },
2762
+ },
2763
+ blockExplorers: {
2764
+ default: {
2765
+ name: 'Basescan',
2766
+ url: 'https://basescan.org',
2767
+ apiUrl: 'https://api.basescan.org/api',
2768
+ },
2769
+ },
2770
+ contracts: {
2771
+ ...chainConfig.contracts,
2772
+ disputeGameFactory: {
2773
+ [sourceId$1]: {
2774
+ address: '0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e',
2775
+ },
2776
+ },
2777
+ l2OutputOracle: {
2778
+ [sourceId$1]: {
2779
+ address: '0x56315b90c40730925ec5485cf004d835058518A0',
2780
+ },
2781
+ },
2782
+ multicall3: {
2783
+ address: '0xca11bde05977b3631167028862be2a173976ca11',
2784
+ blockCreated: 5022,
2785
+ },
2786
+ portal: {
2787
+ [sourceId$1]: {
2788
+ address: '0x49048044D57e1C92A77f79988d21Fa8fAF74E97e',
2789
+ blockCreated: 17482143,
2790
+ },
2791
+ },
2792
+ l1StandardBridge: {
2793
+ [sourceId$1]: {
2794
+ address: '0x3154Cf16ccdb4C6d922629664174b904d80F2C35',
2795
+ blockCreated: 17482143,
2796
+ },
2797
+ },
2798
+ },
2799
+ sourceId: sourceId$1,
2800
+ });
2801
+ /*#__PURE__*/ defineChain({
2802
+ ...base,
2803
+ experimental_preconfirmationTime: 200,
2804
+ rpcUrls: {
2805
+ default: {
2806
+ http: ['https://mainnet-preconf.base.org'],
2807
+ },
2808
+ },
2809
+ });
2810
+
2811
+ const sourceId = 11_155_111; // sepolia
2812
+ const baseSepolia = /*#__PURE__*/ defineChain({
2813
+ ...chainConfig,
2814
+ id: 84532,
2815
+ network: 'base-sepolia',
2816
+ name: 'Base Sepolia',
2817
+ nativeCurrency: { name: 'Sepolia Ether', symbol: 'ETH', decimals: 18 },
2818
+ rpcUrls: {
2819
+ default: {
2820
+ http: ['https://sepolia.base.org'],
2821
+ },
2822
+ },
2823
+ blockExplorers: {
2824
+ default: {
2825
+ name: 'Basescan',
2826
+ url: 'https://sepolia.basescan.org',
2827
+ apiUrl: 'https://api-sepolia.basescan.org/api',
2828
+ },
2829
+ },
2830
+ contracts: {
2831
+ ...chainConfig.contracts,
2832
+ disputeGameFactory: {
2833
+ [sourceId]: {
2834
+ address: '0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1',
2835
+ },
2836
+ },
2837
+ l2OutputOracle: {
2838
+ [sourceId]: {
2839
+ address: '0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254',
2840
+ },
2841
+ },
2842
+ portal: {
2843
+ [sourceId]: {
2844
+ address: '0x49f53e41452c74589e85ca1677426ba426459e85',
2845
+ blockCreated: 4446677,
2846
+ },
2847
+ },
2848
+ l1StandardBridge: {
2849
+ [sourceId]: {
2850
+ address: '0xfd0Bf71F60660E2f608ed56e1659C450eB113120',
2851
+ blockCreated: 4446677,
2852
+ },
2853
+ },
2854
+ multicall3: {
2855
+ address: '0xca11bde05977b3631167028862be2a173976ca11',
2856
+ blockCreated: 1059647,
2857
+ },
2858
+ },
2859
+ testnet: true,
2860
+ sourceId,
2861
+ });
2862
+ /*#__PURE__*/ defineChain({
2863
+ ...baseSepolia,
2864
+ experimental_preconfirmationTime: 200,
2865
+ rpcUrls: {
2866
+ default: {
2867
+ http: ['https://sepolia-preconf.base.org'],
2868
+ },
2869
+ },
2870
+ });
2871
+
2872
+ const mainnet = /*#__PURE__*/ defineChain({
2873
+ id: 1,
2874
+ name: 'Ethereum',
2875
+ nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
2876
+ blockTime: 12_000,
2877
+ rpcUrls: {
2878
+ default: {
2879
+ http: ['https://eth.merkle.io'],
2880
+ },
2881
+ },
2882
+ blockExplorers: {
2883
+ default: {
2884
+ name: 'Etherscan',
2885
+ url: 'https://etherscan.io',
2886
+ apiUrl: 'https://api.etherscan.io/api',
2887
+ },
2888
+ },
2889
+ contracts: {
2890
+ ensUniversalResolver: {
2891
+ address: '0xeeeeeeee14d718c2b47d9923deab1335e144eeee',
2892
+ blockCreated: 23_085_558,
2893
+ },
2894
+ multicall3: {
2895
+ address: '0xca11bde05977b3631167028862be2a173976ca11',
2896
+ blockCreated: 14_353_601,
2897
+ },
2898
+ },
2899
+ });
2900
+
2901
+ const sepolia = /*#__PURE__*/ defineChain({
2902
+ id: 11_155_111,
2903
+ name: 'Sepolia',
2904
+ nativeCurrency: { name: 'Sepolia Ether', symbol: 'ETH', decimals: 18 },
2905
+ rpcUrls: {
2906
+ default: {
2907
+ http: ['https://11155111.rpc.thirdweb.com'],
2908
+ },
2909
+ },
2910
+ blockExplorers: {
2911
+ default: {
2912
+ name: 'Etherscan',
2913
+ url: 'https://sepolia.etherscan.io',
2914
+ apiUrl: 'https://api-sepolia.etherscan.io/api',
2915
+ },
2916
+ },
2917
+ contracts: {
2918
+ multicall3: {
2919
+ address: '0xca11bde05977b3631167028862be2a173976ca11',
2920
+ blockCreated: 751532,
2921
+ },
2922
+ ensUniversalResolver: {
2923
+ address: '0xeeeeeeee14d718c2b47d9923deab1335e144eeee',
2924
+ blockCreated: 8_928_790,
2925
+ },
2926
+ },
2927
+ testnet: true,
2928
+ });
2929
+
2930
+ /**
2931
+ * Maps AgentKit network IDs to Lombard SDK ChainId values.
2932
+ *
2933
+ * Only includes networks where Lombard contracts are deployed.
2934
+ */ const NETWORK_ID_TO_LOMBARD_CHAIN = {
2935
+ "ethereum-mainnet": sdk.ChainId.ethereum,
2936
+ "ethereum-sepolia": sdk.ChainId.sepolia,
2937
+ "base-mainnet": sdk.ChainId.base,
2938
+ "base-sepolia": sdk.ChainId.baseSepoliaTestnet
2939
+ };
2940
+ /**
2941
+ * Maps AgentKit network IDs to Lombard SDK Env values.
2942
+ */ const NETWORK_ID_TO_ENV = {
2943
+ "ethereum-mainnet": sdkCommon.Env.prod,
2944
+ "ethereum-sepolia": sdkCommon.Env.testnet,
2945
+ "base-mainnet": sdkCommon.Env.prod,
2946
+ "base-sepolia": sdkCommon.Env.testnet
2947
+ };
2948
+ /**
2949
+ * Maps AgentKit network IDs to viem `Chain` objects, for callers that need
2950
+ * to construct a wallet/public client outside of the action provider.
2951
+ */ const NETWORK_ID_TO_VIEM_CHAIN = {
2952
+ "ethereum-mainnet": mainnet,
2953
+ "ethereum-sepolia": sepolia,
2954
+ "base-mainnet": base,
2955
+ "base-sepolia": baseSepolia
2956
+ };
2957
+ /**
2958
+ * Resolves an AgentKit Network to Lombard SDK chain parameters.
2959
+ *
2960
+ * @returns ResolvedNetwork or null if the network is not supported
2961
+ */ function resolveNetwork(network) {
2962
+ const networkId = network.networkId;
2963
+ if (!networkId) return null;
2964
+ const chainId = NETWORK_ID_TO_LOMBARD_CHAIN[networkId];
2965
+ const env = NETWORK_ID_TO_ENV[networkId];
2966
+ if (chainId === undefined || !env) return null;
2967
+ return {
2968
+ chainId,
2969
+ env,
2970
+ networkId
2971
+ };
2972
+ }
2973
+ /**
2974
+ * Resolves a user-supplied chain name string to Lombard SDK chain parameters.
2975
+ *
2976
+ * Accepts both AgentKit network IDs (e.g., "ethereum-mainnet") and
2977
+ * friendly names (e.g., "ethereum", "base-sepolia").
2978
+ */ function resolveChainName(chainName) {
2979
+ const normalized = chainName.toLowerCase().trim();
2980
+ // Try direct match on network ID
2981
+ if (NETWORK_ID_TO_LOMBARD_CHAIN[normalized] !== undefined) {
2982
+ return {
2983
+ chainId: NETWORK_ID_TO_LOMBARD_CHAIN[normalized],
2984
+ env: NETWORK_ID_TO_ENV[normalized],
2985
+ networkId: normalized
2986
+ };
2987
+ }
2988
+ // Friendly name aliases
2989
+ const aliases = {
2990
+ ethereum: "ethereum-mainnet",
2991
+ eth: "ethereum-mainnet",
2992
+ mainnet: "ethereum-mainnet",
2993
+ sepolia: "ethereum-sepolia",
2994
+ base: "base-mainnet",
2995
+ "base-sep": "base-sepolia"
2996
+ };
2997
+ const resolved = aliases[normalized];
2998
+ if (resolved && NETWORK_ID_TO_LOMBARD_CHAIN[resolved] !== undefined) {
2999
+ return {
3000
+ chainId: NETWORK_ID_TO_LOMBARD_CHAIN[resolved],
3001
+ env: NETWORK_ID_TO_ENV[resolved],
3002
+ networkId: resolved
3003
+ };
3004
+ }
3005
+ return null;
3006
+ }
3007
+ /**
3008
+ * Checks if a given AgentKit Network is supported by the Lombard provider.
3009
+ */ function isLombardSupportedNetwork(network) {
3010
+ return resolveNetwork(network) !== null;
3011
+ }
3012
+
3013
+ const StakeBtcbToLbtcSchema = zod.z.object({
3014
+ amount: zod.z.string().describe("Amount of BTC.b to stake in human-readable format (e.g. '0.1' for 0.1 BTC.b). Will be converted to LBTC.").refine((v)=>/^\d+(\.\d+)?$/.test(v), "Amount must be a numeric string").refine((v)=>parseFloat(v) > 0, "Amount must be positive").refine((v)=>parseFloat(v) < 1000, "Amount must be under 1000 BTC")
3015
+ });
3016
+ const UnstakeLbtcSchema = zod.z.object({
3017
+ amount: zod.z.string().describe("Amount of LBTC to unstake in human-readable format (e.g. '0.1')").refine((v)=>/^\d+(\.\d+)?$/.test(v), "Amount must be a numeric string").refine((v)=>parseFloat(v) > 0, "Amount must be positive").refine((v)=>parseFloat(v) < 1000, "Amount must be under 1000 BTC"),
3018
+ recipient: zod.z.string().describe("Destination address. For BTC output, use a Bitcoin address (e.g. bc1q...). For BTCb output, use an EVM address (e.g. 0x...).").refine((v)=>/^0x[a-fA-F0-9]{40}$/.test(v) || /^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,62}$/.test(v), "Invalid address: must be an EVM address (0x...) or a Bitcoin address (bc1.../1.../3...)"),
3019
+ outputAsset: zod.z.enum([
3020
+ "BTC",
3021
+ "BTCb"
3022
+ ]).describe("Output asset: 'BTC' for native Bitcoin (cross-chain, takes longer), 'BTCb' for wrapped BTC on the same EVM chain (faster)")
3023
+ });
3024
+ const RedeemLbtcToBtcbSchema = zod.z.object({
3025
+ amount: zod.z.string().describe("Amount of LBTC to redeem in human-readable format (e.g. '0.1'). Will be converted to BTC.b on the same chain.").refine((v)=>/^\d+(\.\d+)?$/.test(v), "Amount must be a numeric string").refine((v)=>parseFloat(v) > 0, "Amount must be positive").refine((v)=>parseFloat(v) < 1000, "Amount must be under 1000 BTC")
3026
+ });
3027
+ const DeployToDefiSchema = zod.z.object({
3028
+ amount: zod.z.string().describe("Amount to deploy in human-readable format (e.g. '0.1')").refine((v)=>/^\d+(\.\d+)?$/.test(v), "Amount must be a numeric string").refine((v)=>parseFloat(v) > 0, "Amount must be positive").refine((v)=>parseFloat(v) < 1000, "Amount must be under 1000 BTC")
3029
+ });
3030
+ const ClaimDepositSchema = zod.z.object({
3031
+ depositTxHash: zod.z.string().describe("Transaction hash of the original deposit to claim. Use get_deposit_status first to check if the deposit is claimable.")
3032
+ });
3033
+ const GetLbtcBalanceSchema = zod.z.object({
3034
+ address: zod.z.string().regex(/^0x[a-fA-F0-9]{40}$/, "Invalid EVM address").optional().describe("EVM address to check balance for. If omitted, uses the connected wallet address.")
3035
+ });
3036
+ const GetBtcbBalanceSchema = zod.z.object({
3037
+ address: zod.z.string().regex(/^0x[a-fA-F0-9]{40}$/, "Invalid EVM address").optional().describe("EVM address to check balance for. If omitted, uses the connected wallet address.")
3038
+ });
3039
+ const GetLbtcExchangeRateSchema = zod.z.object({});
3040
+ const GetDepositStatusSchema = zod.z.object({
3041
+ address: zod.z.string().regex(/^0x[a-fA-F0-9]{40}$/, "Invalid EVM address").optional().describe("EVM address to check deposits for. If omitted, uses the connected wallet address.")
3042
+ });
3043
+ const GetUnstakeStatusSchema = zod.z.object({
3044
+ address: zod.z.string().regex(/^0x[a-fA-F0-9]{40}$/, "Invalid EVM address").optional().describe("EVM address to check unstakes for. If omitted, uses the connected wallet address.")
3045
+ });
3046
+
3047
+ /**
3048
+ * Adapts a Coinbase AgentKit EvmWalletProvider into a viem-compatible
3049
+ * EIP1193Provider that the Lombard SDK contract functions expect.
3050
+ *
3051
+ * The adapter implements the `request` method by delegating to the
3052
+ * appropriate EvmWalletProvider method for each JSON-RPC call.
3053
+ */ function toEIP1193Provider(walletProvider, chainId) {
3054
+ const chain = sdk.CHAIN_ID_TO_VIEM_CHAIN_MAP[chainId];
3055
+ // Use the SDK's makePublicClient for reliable RPC calls
3056
+ const publicClient = chain ? sdk.makePublicClient({
3057
+ chainId
3058
+ }) : null;
3059
+ // Use a Proxy to implement the EIP1193 request interface.
3060
+ // This avoids complex viem type gymnastics while correctly routing
3061
+ // wallet operations to the AgentKit provider and reads to a public client.
3062
+ const handler = async ({ method, params })=>{
3063
+ switch(method){
3064
+ case "eth_accounts":
3065
+ return [
3066
+ walletProvider.getAddress()
3067
+ ];
3068
+ case "eth_chainId":
3069
+ return `0x${chainId.toString(16)}`;
3070
+ case "eth_sendTransaction":
3071
+ {
3072
+ if (!params || params.length === 0) {
3073
+ throw new Error("eth_sendTransaction requires transaction parameter");
3074
+ }
3075
+ const tx = params[0];
3076
+ return walletProvider.sendTransaction({
3077
+ to: tx.to,
3078
+ value: tx.value ? BigInt(tx.value) : undefined,
3079
+ data: tx.data,
3080
+ gas: tx.gas ? BigInt(tx.gas) : undefined
3081
+ });
3082
+ }
3083
+ case "personal_sign":
3084
+ {
3085
+ const [message] = params;
3086
+ return walletProvider.signMessage(message);
3087
+ }
3088
+ case "eth_signTypedData_v4":
3089
+ {
3090
+ const [, typedDataJson] = params;
3091
+ const typedData = typeof typedDataJson === "string" ? JSON.parse(typedDataJson) : typedDataJson;
3092
+ return walletProvider.signTypedData(typedData);
3093
+ }
3094
+ default:
3095
+ {
3096
+ if (!publicClient) {
3097
+ throw new Error(`Unsupported RPC method: ${method}`);
3098
+ }
3099
+ return publicClient.request({
3100
+ method,
3101
+ params
3102
+ });
3103
+ }
3104
+ }
3105
+ };
3106
+ return {
3107
+ request: handler
3108
+ };
3109
+ }
3110
+ /**
3111
+ * Reads an ERC20 token balance using the AgentKit wallet provider's
3112
+ * readContract method directly (avoids needing EIP1193 adapter for reads).
3113
+ */ async function getTokenBalance(walletProvider, token, chainId, address, env) {
3114
+ const tokenInfo = await sdk.getTokenContractInfo(token, chainId, env);
3115
+ const tokenAddress = tokenInfo.address;
3116
+ const balance = await walletProvider.readContract({
3117
+ address: tokenAddress,
3118
+ abi: [
3119
+ {
3120
+ name: "balanceOf",
3121
+ type: "function",
3122
+ stateMutability: "view",
3123
+ inputs: [
3124
+ {
3125
+ name: "account",
3126
+ type: "address"
3127
+ }
3128
+ ],
3129
+ outputs: [
3130
+ {
3131
+ name: "",
3132
+ type: "uint256"
3133
+ }
3134
+ ]
3135
+ }
3136
+ ],
3137
+ functionName: "balanceOf",
3138
+ args: [
3139
+ address
3140
+ ]
3141
+ });
3142
+ // Use decimals from token info when available, default to 8 for BTC-like tokens
3143
+ const decimals = "decimals" in tokenInfo && typeof tokenInfo.decimals === "number" ? tokenInfo.decimals : 8;
3144
+ const formatted = viem.formatUnits(balance, decimals);
3145
+ return {
3146
+ balance: balance,
3147
+ formatted,
3148
+ decimals
3149
+ };
3150
+ }
3151
+ /**
3152
+ * Format a result string for AgentKit action responses.
3153
+ */ function formatSuccess(action, details) {
3154
+ return JSON.stringify({
3155
+ success: true,
3156
+ action,
3157
+ ...details
3158
+ });
3159
+ }
3160
+ function formatError(action, error) {
3161
+ let message;
3162
+ if (error instanceof Error) {
3163
+ // Strip RPC URLs and internal details
3164
+ message = error.message.replace(/https?:\/\/[^\s]+/g, "[redacted-url]").replace(/0x[a-fA-F0-9]{64,}/g, "[redacted-data]");
3165
+ } else {
3166
+ message = String(error);
3167
+ }
3168
+ return JSON.stringify({
3169
+ success: false,
3170
+ action,
3171
+ error: message
3172
+ });
3173
+ }
3174
+
3175
+ function _ts_decorate(decorators, target, key, desc) {
3176
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3177
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
3178
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3179
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3180
+ }
3181
+ function _ts_metadata(k, v) {
3182
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
3183
+ }
3184
+ /**
3185
+ * LombardActionProvider exposes Lombard protocol operations
3186
+ * (stake, unstake, redeem, deploy, claim) as Coinbase AgentKit actions.
3187
+ *
3188
+ * SECURITY: This provider executes real transactions. Configure your wallet
3189
+ * provider with appropriate spending limits. All amounts are validated to be
3190
+ * positive numeric strings under 1000 BTC equivalent.
3191
+ *
3192
+ * Usage:
3193
+ * ```ts
3194
+ * import { lombardActionProvider } from '@lombard.finance/sdk-agentkit';
3195
+ *
3196
+ * const agentkit = await AgentKit.from({
3197
+ * walletProvider,
3198
+ * actionProviders: [lombardActionProvider()],
3199
+ * });
3200
+ * ```
3201
+ */ class LombardActionProvider extends agentkit.ActionProvider {
3202
+ constructor(){
3203
+ super("lombard", []);
3204
+ }
3205
+ supportsNetwork = (network)=>{
3206
+ return isLombardSupportedNetwork(network);
3207
+ };
3208
+ // ─── Write Actions ──────────────────────────────────────────────────
3209
+ async stakeBtcbToLbtc(walletProvider, args) {
3210
+ try {
3211
+ const resolved = resolveNetwork(walletProvider.getNetwork());
3212
+ if (!resolved) {
3213
+ return formatError("stake_btcb_to_lbtc", "Current network is not supported by Lombard");
3214
+ }
3215
+ const { chainId, env } = resolved;
3216
+ const account = walletProvider.getAddress();
3217
+ const provider = toEIP1193Provider(walletProvider, chainId);
3218
+ // Handle fee authorization for chains that require it
3219
+ await this.ensureFeeAuthorization(walletProvider, chainId, env, account, provider);
3220
+ // Check allowance and approve if needed
3221
+ const routerAddress = await sdk.getAssetRouterAddress({
3222
+ tokenIn: sdk.Token.BTCb,
3223
+ chainId,
3224
+ env
3225
+ });
3226
+ const allowance = await sdk.getTokenAllowance({
3227
+ token: sdk.Token.BTCb,
3228
+ owner: account,
3229
+ spender: routerAddress,
3230
+ chainId,
3231
+ env
3232
+ });
3233
+ if (allowance.isLessThan(args.amount)) {
3234
+ await sdk.approveToken({
3235
+ token: sdk.Token.BTCb,
3236
+ spender: routerAddress,
3237
+ amount: args.amount,
3238
+ account,
3239
+ chainId,
3240
+ provider,
3241
+ env
3242
+ });
3243
+ }
3244
+ const txHash = await sdk.depositToken({
3245
+ amount: args.amount,
3246
+ tokenIn: sdk.Token.BTCb,
3247
+ tokenOut: sdk.Token.LBTC,
3248
+ account,
3249
+ chainId,
3250
+ provider,
3251
+ env
3252
+ });
3253
+ return formatSuccess("stake_btcb_to_lbtc", {
3254
+ txHash,
3255
+ amount: args.amount,
3256
+ from: "BTC.b",
3257
+ to: "LBTC"
3258
+ });
3259
+ } catch (error) {
3260
+ return formatError("stake_btcb_to_lbtc", error);
3261
+ }
3262
+ }
3263
+ async unstakeLbtc(walletProvider, args) {
3264
+ try {
3265
+ const resolved = resolveNetwork(walletProvider.getNetwork());
3266
+ if (!resolved) {
3267
+ return formatError("unstake_lbtc", "Current network is not supported by Lombard");
3268
+ }
3269
+ const { chainId, env } = resolved;
3270
+ const account = walletProvider.getAddress();
3271
+ const provider = toEIP1193Provider(walletProvider, chainId);
3272
+ // Handle fee authorization for chains that require it
3273
+ await this.ensureFeeAuthorization(walletProvider, chainId, env, account, provider);
3274
+ if (args.outputAsset === "BTC") {
3275
+ const txHash = await sdk.unstakeLBTC({
3276
+ amount: args.amount,
3277
+ btcAddress: args.recipient,
3278
+ tokenIn: sdk.Token.LBTC,
3279
+ account,
3280
+ chainId,
3281
+ provider,
3282
+ env
3283
+ });
3284
+ return formatSuccess("unstake_lbtc", {
3285
+ txHash,
3286
+ amount: args.amount,
3287
+ to: "BTC",
3288
+ recipient: args.recipient,
3289
+ note: "Cross-chain unstake initiated. BTC will arrive after processing (may take hours)."
3290
+ });
3291
+ }
3292
+ // BTCb output - same chain redeem (always sends to caller's address)
3293
+ const txHash = await sdk.redeemToken({
3294
+ amount: args.amount,
3295
+ tokenIn: sdk.Token.LBTC,
3296
+ tokenOut: sdk.Token.BTCb,
3297
+ account,
3298
+ chainId,
3299
+ provider,
3300
+ env
3301
+ });
3302
+ const result = {
3303
+ txHash,
3304
+ amount: args.amount,
3305
+ to: "BTC.b"
3306
+ };
3307
+ if (args.recipient && args.recipient.toLowerCase() !== account.toLowerCase()) {
3308
+ result.warning = "BTC.b redemption always sends to the connected wallet. The recipient address was ignored.";
3309
+ }
3310
+ return formatSuccess("unstake_lbtc", result);
3311
+ } catch (error) {
3312
+ return formatError("unstake_lbtc", error);
3313
+ }
3314
+ }
3315
+ async redeemLbtcToBtcb(walletProvider, args) {
3316
+ try {
3317
+ const resolved = resolveNetwork(walletProvider.getNetwork());
3318
+ if (!resolved) {
3319
+ return formatError("redeem_lbtc_to_btcb", "Current network is not supported by Lombard");
3320
+ }
3321
+ const { chainId, env } = resolved;
3322
+ const account = walletProvider.getAddress();
3323
+ const provider = toEIP1193Provider(walletProvider, chainId);
3324
+ await this.ensureFeeAuthorization(walletProvider, chainId, env, account, provider);
3325
+ const txHash = await sdk.redeemToken({
3326
+ amount: args.amount,
3327
+ tokenIn: sdk.Token.LBTC,
3328
+ tokenOut: sdk.Token.BTCb,
3329
+ account,
3330
+ chainId,
3331
+ provider,
3332
+ env
3333
+ });
3334
+ return formatSuccess("redeem_lbtc_to_btcb", {
3335
+ txHash,
3336
+ amount: args.amount,
3337
+ from: "LBTC",
3338
+ to: "BTC.b"
3339
+ });
3340
+ } catch (error) {
3341
+ return formatError("redeem_lbtc_to_btcb", error);
3342
+ }
3343
+ }
3344
+ async deployToDefi(walletProvider, args) {
3345
+ try {
3346
+ const resolved = resolveNetwork(walletProvider.getNetwork());
3347
+ if (!resolved) {
3348
+ return formatError("deploy_to_defi", "Current network is not supported by Lombard");
3349
+ }
3350
+ const { chainId } = resolved;
3351
+ const account = walletProvider.getAddress();
3352
+ const provider = toEIP1193Provider(walletProvider, chainId);
3353
+ const txHash = await sdk.depositEarn({
3354
+ amount: args.amount,
3355
+ approve: true,
3356
+ token: sdk.Token.LBTC,
3357
+ account,
3358
+ chainId,
3359
+ provider,
3360
+ rpcUrl: undefined,
3361
+ env: resolved.env
3362
+ });
3363
+ return formatSuccess("deploy_to_defi", {
3364
+ txHash,
3365
+ amount: args.amount,
3366
+ asset: "LBTC"
3367
+ });
3368
+ } catch (error) {
3369
+ return formatError("deploy_to_defi", error);
3370
+ }
3371
+ }
3372
+ async claimDeposit(walletProvider, args) {
3373
+ try {
3374
+ const resolved = resolveNetwork(walletProvider.getNetwork());
3375
+ if (!resolved) {
3376
+ return formatError("claim_deposit", "Current network is not supported by Lombard");
3377
+ }
3378
+ const { chainId, env } = resolved;
3379
+ const account = walletProvider.getAddress();
3380
+ const provider = toEIP1193Provider(walletProvider, chainId);
3381
+ // Find the claimable deposit by tx hash
3382
+ const deposits = await sdk.getDepositsByAddress({
3383
+ address: account,
3384
+ env
3385
+ });
3386
+ const deposit = deposits.find((d)=>d.txHash === args.depositTxHash);
3387
+ if (!deposit) {
3388
+ return formatError("claim_deposit", `No deposit found with txHash: ${args.depositTxHash}`);
3389
+ }
3390
+ const status = sdk.getDepositStatus(deposit);
3391
+ if (status !== "claimable") {
3392
+ const display = sdk.getDepositStatusDisplay(status);
3393
+ return formatError("claim_deposit", `Deposit is not claimable. Current status: ${display.label} - ${display.description}`);
3394
+ }
3395
+ if (!deposit.rawPayload || !deposit.proof) {
3396
+ return formatError("claim_deposit", "Deposit proof data is not yet available");
3397
+ }
3398
+ const txHash = await sdk.claimLBTC({
3399
+ data: deposit.rawPayload,
3400
+ proofSignature: deposit.proof,
3401
+ account,
3402
+ chainId,
3403
+ provider,
3404
+ env
3405
+ });
3406
+ return formatSuccess("claim_deposit", {
3407
+ txHash,
3408
+ depositTxHash: args.depositTxHash
3409
+ });
3410
+ } catch (error) {
3411
+ return formatError("claim_deposit", error);
3412
+ }
3413
+ }
3414
+ // ─── Read Actions ───────────────────────────────────────────────────
3415
+ async getLbtcBalance(walletProvider, args) {
3416
+ try {
3417
+ const resolved = resolveNetwork(walletProvider.getNetwork());
3418
+ if (!resolved) {
3419
+ return formatError("get_lbtc_balance", "Current network is not supported by Lombard");
3420
+ }
3421
+ const { chainId, env } = resolved;
3422
+ const address = args.address || walletProvider.getAddress();
3423
+ const { formatted } = await getTokenBalance(walletProvider, sdk.Token.LBTC, chainId, address, env);
3424
+ return formatSuccess("get_lbtc_balance", {
3425
+ address,
3426
+ balance: formatted,
3427
+ token: "LBTC",
3428
+ chain: resolved.networkId
3429
+ });
3430
+ } catch (error) {
3431
+ return formatError("get_lbtc_balance", error);
3432
+ }
3433
+ }
3434
+ async getBtcbBalance(walletProvider, args) {
3435
+ try {
3436
+ const resolved = resolveNetwork(walletProvider.getNetwork());
3437
+ if (!resolved) {
3438
+ return formatError("get_btcb_balance", "Current network is not supported by Lombard");
3439
+ }
3440
+ const { chainId, env } = resolved;
3441
+ const address = args.address || walletProvider.getAddress();
3442
+ const { formatted } = await getTokenBalance(walletProvider, sdk.Token.BTCb, chainId, address, env);
3443
+ return formatSuccess("get_btcb_balance", {
3444
+ address,
3445
+ balance: formatted,
3446
+ token: "BTC.b",
3447
+ chain: resolved.networkId
3448
+ });
3449
+ } catch (error) {
3450
+ return formatError("get_btcb_balance", error);
3451
+ }
3452
+ }
3453
+ async getLbtcExchangeRate(_walletProvider, _args) {
3454
+ try {
3455
+ const resolved = resolveNetwork(_walletProvider.getNetwork());
3456
+ if (!resolved) {
3457
+ return formatError("get_lbtc_exchange_rate", "Current network is not supported by Lombard");
3458
+ }
3459
+ const env = resolved.env;
3460
+ const rate = await sdk.getLBTCExchangeRate({
3461
+ env
3462
+ });
3463
+ return formatSuccess("get_lbtc_exchange_rate", {
3464
+ exchangeRate: rate.exchangeRate,
3465
+ minStakeAmountBtc: sdk.fromSatoshi(rate.minAmount).toString()
3466
+ });
3467
+ } catch (error) {
3468
+ return formatError("get_lbtc_exchange_rate", error);
3469
+ }
3470
+ }
3471
+ async getDepositStatusAction(walletProvider, args) {
3472
+ try {
3473
+ const resolved = resolveNetwork(walletProvider.getNetwork());
3474
+ if (!resolved) {
3475
+ return formatError("get_deposit_status", "Current network is not supported by Lombard");
3476
+ }
3477
+ const { env } = resolved;
3478
+ const address = args.address || walletProvider.getAddress();
3479
+ const deposits = await sdk.getDepositsByAddress({
3480
+ address,
3481
+ env
3482
+ });
3483
+ if (deposits.length === 0) {
3484
+ return formatSuccess("get_deposit_status", {
3485
+ address,
3486
+ deposits: [],
3487
+ message: "No deposits found for this address"
3488
+ });
3489
+ }
3490
+ const summaries = deposits.map((d)=>{
3491
+ const status = sdk.getDepositStatus(d);
3492
+ const display = sdk.getDepositStatusDisplay(status);
3493
+ return {
3494
+ txHash: d.txHash,
3495
+ amount: d.amount?.toString(),
3496
+ status,
3497
+ statusLabel: display.label,
3498
+ description: display.description,
3499
+ requiresAction: display.requiresAction,
3500
+ isTerminal: display.isTerminal,
3501
+ claimTxHash: d.claimTxHash || null
3502
+ };
3503
+ });
3504
+ return formatSuccess("get_deposit_status", {
3505
+ address,
3506
+ totalDeposits: deposits.length,
3507
+ deposits: summaries
3508
+ });
3509
+ } catch (error) {
3510
+ return formatError("get_deposit_status", error);
3511
+ }
3512
+ }
3513
+ async getUnstakeStatus(walletProvider, args) {
3514
+ try {
3515
+ const resolved = resolveNetwork(walletProvider.getNetwork());
3516
+ if (!resolved) {
3517
+ return formatError("get_unstake_status", "Current network is not supported by Lombard");
3518
+ }
3519
+ const { env } = resolved;
3520
+ const address = args.address || walletProvider.getAddress();
3521
+ const unstakes = await sdk.getUnstakesByAddress({
3522
+ address,
3523
+ env
3524
+ });
3525
+ if (unstakes.length === 0) {
3526
+ return formatSuccess("get_unstake_status", {
3527
+ address,
3528
+ unstakes: [],
3529
+ message: "No unstakes found for this address"
3530
+ });
3531
+ }
3532
+ const summaries = unstakes.map((u)=>({
3533
+ txHash: u.txHash,
3534
+ amount: u.amount?.toString(),
3535
+ payoutStatus: u.payoutTxStatus,
3536
+ payoutTxHash: u.payoutTxHash || null,
3537
+ toAddress: u.toAddress || null
3538
+ }));
3539
+ return formatSuccess("get_unstake_status", {
3540
+ address,
3541
+ totalUnstakes: unstakes.length,
3542
+ unstakes: summaries
3543
+ });
3544
+ } catch (error) {
3545
+ return formatError("get_unstake_status", error);
3546
+ }
3547
+ }
3548
+ // ─── Private Helpers ────────────────────────────────────────────────
3549
+ /**
3550
+ * Ensures fee authorization is in place for chains that require it.
3551
+ * On Ethereum and Sepolia, staking/unstaking requires an EIP-712 fee
3552
+ * signature stored with the backend before the transaction can proceed.
3553
+ */ async ensureFeeAuthorization(_walletProvider, chainId, env, account, provider) {
3554
+ if (!sdk.requiresAutoMintFee(chainId)) {
3555
+ return;
3556
+ }
3557
+ // Check if a valid fee signature already exists
3558
+ const existing = await sdk.getNetworkFeeSignature({
3559
+ address: account,
3560
+ chainId,
3561
+ env
3562
+ });
3563
+ if (existing.hasSignature) {
3564
+ // Check expiration
3565
+ const expirationMs = new Date(existing.expirationDate).getTime();
3566
+ const bufferMs = 60 * 60 * 1000; // 1 hour buffer
3567
+ if (expirationMs > Date.now() + bufferMs) {
3568
+ return; // Existing signature is still valid
3569
+ }
3570
+ }
3571
+ // Need to sign a new fee authorization
3572
+ const mintingFee = await sdk.getLBTCMintingFee({
3573
+ chainId,
3574
+ env
3575
+ });
3576
+ const { signature, typedData } = await sdk.signNetworkFee({
3577
+ fee: mintingFee,
3578
+ account,
3579
+ chainId,
3580
+ provider,
3581
+ env
3582
+ });
3583
+ await sdk.storeNetworkFeeSignature({
3584
+ signature,
3585
+ typedData,
3586
+ address: account,
3587
+ env
3588
+ });
3589
+ }
3590
+ }
3591
+ _ts_decorate([
3592
+ agentkit.CreateAction({
3593
+ name: "stake_btcb_to_lbtc",
3594
+ description: "Stake BTC.b (cross-chain Bitcoin) to receive LBTC (Lombard Staked Bitcoin). " + "This converts BTC.b into LBTC which earns staking yield. " + "Handles token approval and fee authorization automatically.",
3595
+ schema: StakeBtcbToLbtcSchema
3596
+ }),
3597
+ _ts_metadata("design:type", Function),
3598
+ _ts_metadata("design:paramtypes", [
3599
+ typeof agentkit.EvmWalletProvider === "undefined" ? Object : agentkit.EvmWalletProvider,
3600
+ typeof zod.z === "undefined" || typeof zod.z.infer === "undefined" ? Object : zod.z.infer
3601
+ ]),
3602
+ _ts_metadata("design:returntype", Promise)
3603
+ ], LombardActionProvider.prototype, "stakeBtcbToLbtc", null);
3604
+ _ts_decorate([
3605
+ agentkit.CreateAction({
3606
+ name: "unstake_lbtc",
3607
+ description: "Unstake LBTC (Lombard Staked Bitcoin). " + "Output can be native BTC (cross-chain, requires a Bitcoin address) or BTC.b (same EVM chain). " + "BTC unstaking takes longer as it crosses chains. BTC.b is faster, same-chain.",
3608
+ schema: UnstakeLbtcSchema
3609
+ }),
3610
+ _ts_metadata("design:type", Function),
3611
+ _ts_metadata("design:paramtypes", [
3612
+ typeof agentkit.EvmWalletProvider === "undefined" ? Object : agentkit.EvmWalletProvider,
3613
+ typeof zod.z === "undefined" || typeof zod.z.infer === "undefined" ? Object : zod.z.infer
3614
+ ]),
3615
+ _ts_metadata("design:returntype", Promise)
3616
+ ], LombardActionProvider.prototype, "unstakeLbtc", null);
3617
+ _ts_decorate([
3618
+ agentkit.CreateAction({
3619
+ name: "redeem_lbtc_to_btcb",
3620
+ description: "Use this for simple same-chain LBTC to BTC.b conversion. " + "For cross-chain unstaking to native BTC, use unstake_lbtc instead.",
3621
+ schema: RedeemLbtcToBtcbSchema
3622
+ }),
3623
+ _ts_metadata("design:type", Function),
3624
+ _ts_metadata("design:paramtypes", [
3625
+ typeof agentkit.EvmWalletProvider === "undefined" ? Object : agentkit.EvmWalletProvider,
3626
+ typeof zod.z === "undefined" || typeof zod.z.infer === "undefined" ? Object : zod.z.infer
3627
+ ]),
3628
+ _ts_metadata("design:returntype", Promise)
3629
+ ], LombardActionProvider.prototype, "redeemLbtcToBtcb", null);
3630
+ _ts_decorate([
3631
+ agentkit.CreateAction({
3632
+ name: "deploy_to_defi",
3633
+ description: "Deploy LBTC into a DeFi vault to earn additional yield. " + "Currently supports the Veda vault. " + "Handles approval automatically.",
3634
+ schema: DeployToDefiSchema
3635
+ }),
3636
+ _ts_metadata("design:type", Function),
3637
+ _ts_metadata("design:paramtypes", [
3638
+ typeof agentkit.EvmWalletProvider === "undefined" ? Object : agentkit.EvmWalletProvider,
3639
+ typeof zod.z === "undefined" || typeof zod.z.infer === "undefined" ? Object : zod.z.infer
3640
+ ]),
3641
+ _ts_metadata("design:returntype", Promise)
3642
+ ], LombardActionProvider.prototype, "deployToDefi", null);
3643
+ _ts_decorate([
3644
+ agentkit.CreateAction({
3645
+ name: "claim_deposit",
3646
+ description: "Claim a notarized deposit to mint LBTC. " + "Use get_deposit_status first to check if a deposit is claimable. " + 'Only deposits with status "claimable" can be claimed.',
3647
+ schema: ClaimDepositSchema
3648
+ }),
3649
+ _ts_metadata("design:type", Function),
3650
+ _ts_metadata("design:paramtypes", [
3651
+ typeof agentkit.EvmWalletProvider === "undefined" ? Object : agentkit.EvmWalletProvider,
3652
+ typeof zod.z === "undefined" || typeof zod.z.infer === "undefined" ? Object : zod.z.infer
3653
+ ]),
3654
+ _ts_metadata("design:returntype", Promise)
3655
+ ], LombardActionProvider.prototype, "claimDeposit", null);
3656
+ _ts_decorate([
3657
+ agentkit.CreateAction({
3658
+ name: "get_lbtc_balance",
3659
+ description: "Check the LBTC (Lombard Staked Bitcoin) balance for an address on the current chain.",
3660
+ schema: GetLbtcBalanceSchema
3661
+ }),
3662
+ _ts_metadata("design:type", Function),
3663
+ _ts_metadata("design:paramtypes", [
3664
+ typeof agentkit.EvmWalletProvider === "undefined" ? Object : agentkit.EvmWalletProvider,
3665
+ typeof zod.z === "undefined" || typeof zod.z.infer === "undefined" ? Object : zod.z.infer
3666
+ ]),
3667
+ _ts_metadata("design:returntype", Promise)
3668
+ ], LombardActionProvider.prototype, "getLbtcBalance", null);
3669
+ _ts_decorate([
3670
+ agentkit.CreateAction({
3671
+ name: "get_btcb_balance",
3672
+ description: "Check the BTC.b (cross-chain Bitcoin) balance for an address on the current chain.",
3673
+ schema: GetBtcbBalanceSchema
3674
+ }),
3675
+ _ts_metadata("design:type", Function),
3676
+ _ts_metadata("design:paramtypes", [
3677
+ typeof agentkit.EvmWalletProvider === "undefined" ? Object : agentkit.EvmWalletProvider,
3678
+ typeof zod.z === "undefined" || typeof zod.z.infer === "undefined" ? Object : zod.z.infer
3679
+ ]),
3680
+ _ts_metadata("design:returntype", Promise)
3681
+ ], LombardActionProvider.prototype, "getBtcbBalance", null);
3682
+ _ts_decorate([
3683
+ agentkit.CreateAction({
3684
+ name: "get_lbtc_exchange_rate",
3685
+ description: "Get the current LBTC/BTC exchange rate and minimum stake amount. " + "LBTC is a rebasing token, so the rate is typically close to 1:1.",
3686
+ schema: GetLbtcExchangeRateSchema
3687
+ }),
3688
+ _ts_metadata("design:type", Function),
3689
+ _ts_metadata("design:paramtypes", [
3690
+ typeof agentkit.EvmWalletProvider === "undefined" ? Object : agentkit.EvmWalletProvider,
3691
+ typeof zod.z === "undefined" || typeof zod.z.infer === "undefined" ? Object : zod.z.infer
3692
+ ]),
3693
+ _ts_metadata("design:returntype", Promise)
3694
+ ], LombardActionProvider.prototype, "getLbtcExchangeRate", null);
3695
+ _ts_decorate([
3696
+ agentkit.CreateAction({
3697
+ name: "get_deposit_status",
3698
+ description: "Check the status of all deposits for an address. " + "Shows pending, claimable, claimed, and failed deposits. " + "Use this to find claimable deposits before calling claim_deposit.",
3699
+ schema: GetDepositStatusSchema
3700
+ }),
3701
+ _ts_metadata("design:type", Function),
3702
+ _ts_metadata("design:paramtypes", [
3703
+ typeof agentkit.EvmWalletProvider === "undefined" ? Object : agentkit.EvmWalletProvider,
3704
+ typeof zod.z === "undefined" || typeof zod.z.infer === "undefined" ? Object : zod.z.infer
3705
+ ]),
3706
+ _ts_metadata("design:returntype", Promise)
3707
+ ], LombardActionProvider.prototype, "getDepositStatusAction", null);
3708
+ _ts_decorate([
3709
+ agentkit.CreateAction({
3710
+ name: "get_unstake_status",
3711
+ description: "Check the status of all unstake/redeem operations for an address. " + "Shows pending and completed unstakes with payout transaction details.",
3712
+ schema: GetUnstakeStatusSchema
3713
+ }),
3714
+ _ts_metadata("design:type", Function),
3715
+ _ts_metadata("design:paramtypes", [
3716
+ typeof agentkit.EvmWalletProvider === "undefined" ? Object : agentkit.EvmWalletProvider,
3717
+ typeof zod.z === "undefined" || typeof zod.z.infer === "undefined" ? Object : zod.z.infer
3718
+ ]),
3719
+ _ts_metadata("design:returntype", Promise)
3720
+ ], LombardActionProvider.prototype, "getUnstakeStatus", null);
3721
+ const lombardActionProvider = ()=>new LombardActionProvider();
3722
+
3723
+ exports.ClaimDepositSchema = ClaimDepositSchema;
3724
+ exports.DeployToDefiSchema = DeployToDefiSchema;
3725
+ exports.GetBtcbBalanceSchema = GetBtcbBalanceSchema;
3726
+ exports.GetDepositStatusSchema = GetDepositStatusSchema;
3727
+ exports.GetLbtcBalanceSchema = GetLbtcBalanceSchema;
3728
+ exports.GetLbtcExchangeRateSchema = GetLbtcExchangeRateSchema;
3729
+ exports.GetUnstakeStatusSchema = GetUnstakeStatusSchema;
3730
+ exports.LombardActionProvider = LombardActionProvider;
3731
+ exports.NETWORK_ID_TO_VIEM_CHAIN = NETWORK_ID_TO_VIEM_CHAIN;
3732
+ exports.RedeemLbtcToBtcbSchema = RedeemLbtcToBtcbSchema;
3733
+ exports.StakeBtcbToLbtcSchema = StakeBtcbToLbtcSchema;
3734
+ exports.UnstakeLbtcSchema = UnstakeLbtcSchema;
3735
+ exports.isLombardSupportedNetwork = isLombardSupportedNetwork;
3736
+ exports.lombardActionProvider = lombardActionProvider;
3737
+ exports.resolveChainName = resolveChainName;
3738
+ exports.resolveNetwork = resolveNetwork;