mtok-relay 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.
Files changed (2) hide show
  1. package/dist/mtok-relay.mjs +4922 -0
  2. package/package.json +20 -0
@@ -0,0 +1,4922 @@
1
+ #!/usr/bin/env node
2
+ // GENERATED by scripts/build-relay-bundle.mjs from relay/mtok-relay.mjs — do not edit by hand.
3
+
4
+ // mtok-relay.mjs
5
+ import http from "node:http";
6
+
7
+ // lib.mjs
8
+ function enforceModelEcho(upstreamModel, offerModel) {
9
+ if (String(upstreamModel) !== String(offerModel))
10
+ throw new Error(`model mismatch: upstream ${upstreamModel} != offer ${offerModel}`);
11
+ }
12
+ var buildFundReport = ({ offerId: offerId2, buyerId, bookingId, n, priceUsd, sellerTxHash, feeTxHash }) => ({
13
+ offerId: offerId2,
14
+ buyerId,
15
+ ...bookingId ? { bookingId } : {},
16
+ n,
17
+ priceUsd,
18
+ sellerTxHash,
19
+ feeTxHash
20
+ });
21
+ var buildDrawReport = ({ offerId: offerId2, buyerId, bookingId, n, usage }) => ({
22
+ offerId: offerId2,
23
+ buyerId,
24
+ bookingId,
25
+ n,
26
+ inputTokens: usage?.prompt_tokens ?? 0,
27
+ outputTokens: usage?.completion_tokens ?? 0
28
+ });
29
+
30
+ // node_modules/@noble/hashes/esm/cryptoNode.js
31
+ import * as nc from "node:crypto";
32
+ var crypto = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
33
+
34
+ // node_modules/@noble/hashes/esm/utils.js
35
+ function isBytes(a) {
36
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
37
+ }
38
+ function anumber(n) {
39
+ if (!Number.isSafeInteger(n) || n < 0)
40
+ throw new Error("positive integer expected, got " + n);
41
+ }
42
+ function abytes(b, ...lengths) {
43
+ if (!isBytes(b))
44
+ throw new Error("Uint8Array expected");
45
+ if (lengths.length > 0 && !lengths.includes(b.length))
46
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
47
+ }
48
+ function ahash(h) {
49
+ if (typeof h !== "function" || typeof h.create !== "function")
50
+ throw new Error("Hash should be wrapped by utils.createHasher");
51
+ anumber(h.outputLen);
52
+ anumber(h.blockLen);
53
+ }
54
+ function aexists(instance, checkFinished = true) {
55
+ if (instance.destroyed)
56
+ throw new Error("Hash instance has been destroyed");
57
+ if (checkFinished && instance.finished)
58
+ throw new Error("Hash#digest() has already been called");
59
+ }
60
+ function aoutput(out, instance) {
61
+ abytes(out);
62
+ const min = instance.outputLen;
63
+ if (out.length < min) {
64
+ throw new Error("digestInto() expects output buffer of length at least " + min);
65
+ }
66
+ }
67
+ function u32(arr) {
68
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
69
+ }
70
+ function clean(...arrays) {
71
+ for (let i = 0; i < arrays.length; i++) {
72
+ arrays[i].fill(0);
73
+ }
74
+ }
75
+ function createView(arr) {
76
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
77
+ }
78
+ function rotr(word, shift) {
79
+ return word << 32 - shift | word >>> shift;
80
+ }
81
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
82
+ function byteSwap(word) {
83
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
84
+ }
85
+ function byteSwap32(arr) {
86
+ for (let i = 0; i < arr.length; i++) {
87
+ arr[i] = byteSwap(arr[i]);
88
+ }
89
+ return arr;
90
+ }
91
+ var swap32IfBE = isLE ? (u) => u : byteSwap32;
92
+ function utf8ToBytes(str) {
93
+ if (typeof str !== "string")
94
+ throw new Error("string expected");
95
+ return new Uint8Array(new TextEncoder().encode(str));
96
+ }
97
+ function toBytes(data) {
98
+ if (typeof data === "string")
99
+ data = utf8ToBytes(data);
100
+ abytes(data);
101
+ return data;
102
+ }
103
+ function concatBytes(...arrays) {
104
+ let sum = 0;
105
+ for (let i = 0; i < arrays.length; i++) {
106
+ const a = arrays[i];
107
+ abytes(a);
108
+ sum += a.length;
109
+ }
110
+ const res = new Uint8Array(sum);
111
+ for (let i = 0, pad2 = 0; i < arrays.length; i++) {
112
+ const a = arrays[i];
113
+ res.set(a, pad2);
114
+ pad2 += a.length;
115
+ }
116
+ return res;
117
+ }
118
+ var Hash = class {
119
+ };
120
+ function createHasher(hashCons) {
121
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
122
+ const tmp = hashCons();
123
+ hashC.outputLen = tmp.outputLen;
124
+ hashC.blockLen = tmp.blockLen;
125
+ hashC.create = () => hashCons();
126
+ return hashC;
127
+ }
128
+ function randomBytes(bytesLength = 32) {
129
+ if (crypto && typeof crypto.getRandomValues === "function") {
130
+ return crypto.getRandomValues(new Uint8Array(bytesLength));
131
+ }
132
+ if (crypto && typeof crypto.randomBytes === "function") {
133
+ return Uint8Array.from(crypto.randomBytes(bytesLength));
134
+ }
135
+ throw new Error("crypto.getRandomValues must be defined");
136
+ }
137
+
138
+ // node_modules/@noble/curves/esm/abstract/utils.js
139
+ var _0n = /* @__PURE__ */ BigInt(0);
140
+ var _1n = /* @__PURE__ */ BigInt(1);
141
+ function isBytes2(a) {
142
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
143
+ }
144
+ function abytes2(item) {
145
+ if (!isBytes2(item))
146
+ throw new Error("Uint8Array expected");
147
+ }
148
+ function abool(title, value) {
149
+ if (typeof value !== "boolean")
150
+ throw new Error(title + " boolean expected, got " + value);
151
+ }
152
+ function numberToHexUnpadded(num) {
153
+ const hex = num.toString(16);
154
+ return hex.length & 1 ? "0" + hex : hex;
155
+ }
156
+ function hexToNumber(hex) {
157
+ if (typeof hex !== "string")
158
+ throw new Error("hex string expected, got " + typeof hex);
159
+ return hex === "" ? _0n : BigInt("0x" + hex);
160
+ }
161
+ var hasHexBuiltin = (
162
+ // @ts-ignore
163
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
164
+ );
165
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
166
+ function bytesToHex(bytes) {
167
+ abytes2(bytes);
168
+ if (hasHexBuiltin)
169
+ return bytes.toHex();
170
+ let hex = "";
171
+ for (let i = 0; i < bytes.length; i++) {
172
+ hex += hexes[bytes[i]];
173
+ }
174
+ return hex;
175
+ }
176
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
177
+ function asciiToBase16(ch) {
178
+ if (ch >= asciis._0 && ch <= asciis._9)
179
+ return ch - asciis._0;
180
+ if (ch >= asciis.A && ch <= asciis.F)
181
+ return ch - (asciis.A - 10);
182
+ if (ch >= asciis.a && ch <= asciis.f)
183
+ return ch - (asciis.a - 10);
184
+ return;
185
+ }
186
+ function hexToBytes(hex) {
187
+ if (typeof hex !== "string")
188
+ throw new Error("hex string expected, got " + typeof hex);
189
+ if (hasHexBuiltin)
190
+ return Uint8Array.fromHex(hex);
191
+ const hl = hex.length;
192
+ const al = hl / 2;
193
+ if (hl % 2)
194
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
195
+ const array = new Uint8Array(al);
196
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
197
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
198
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
199
+ if (n1 === void 0 || n2 === void 0) {
200
+ const char = hex[hi] + hex[hi + 1];
201
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
202
+ }
203
+ array[ai] = n1 * 16 + n2;
204
+ }
205
+ return array;
206
+ }
207
+ function bytesToNumberBE(bytes) {
208
+ return hexToNumber(bytesToHex(bytes));
209
+ }
210
+ function bytesToNumberLE(bytes) {
211
+ abytes2(bytes);
212
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
213
+ }
214
+ function numberToBytesBE(n, len) {
215
+ return hexToBytes(n.toString(16).padStart(len * 2, "0"));
216
+ }
217
+ function numberToBytesLE(n, len) {
218
+ return numberToBytesBE(n, len).reverse();
219
+ }
220
+ function ensureBytes(title, hex, expectedLength) {
221
+ let res;
222
+ if (typeof hex === "string") {
223
+ try {
224
+ res = hexToBytes(hex);
225
+ } catch (e) {
226
+ throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
227
+ }
228
+ } else if (isBytes2(hex)) {
229
+ res = Uint8Array.from(hex);
230
+ } else {
231
+ throw new Error(title + " must be hex string or Uint8Array");
232
+ }
233
+ const len = res.length;
234
+ if (typeof expectedLength === "number" && len !== expectedLength)
235
+ throw new Error(title + " of length " + expectedLength + " expected, got " + len);
236
+ return res;
237
+ }
238
+ function concatBytes2(...arrays) {
239
+ let sum = 0;
240
+ for (let i = 0; i < arrays.length; i++) {
241
+ const a = arrays[i];
242
+ abytes2(a);
243
+ sum += a.length;
244
+ }
245
+ const res = new Uint8Array(sum);
246
+ for (let i = 0, pad2 = 0; i < arrays.length; i++) {
247
+ const a = arrays[i];
248
+ res.set(a, pad2);
249
+ pad2 += a.length;
250
+ }
251
+ return res;
252
+ }
253
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
254
+ function inRange(n, min, max) {
255
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
256
+ }
257
+ function aInRange(title, n, min, max) {
258
+ if (!inRange(n, min, max))
259
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
260
+ }
261
+ function bitLen(n) {
262
+ let len;
263
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
264
+ ;
265
+ return len;
266
+ }
267
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
268
+ var u8n = (len) => new Uint8Array(len);
269
+ var u8fr = (arr) => Uint8Array.from(arr);
270
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
271
+ if (typeof hashLen !== "number" || hashLen < 2)
272
+ throw new Error("hashLen must be a number");
273
+ if (typeof qByteLen !== "number" || qByteLen < 2)
274
+ throw new Error("qByteLen must be a number");
275
+ if (typeof hmacFn !== "function")
276
+ throw new Error("hmacFn must be a function");
277
+ let v = u8n(hashLen);
278
+ let k = u8n(hashLen);
279
+ let i = 0;
280
+ const reset = () => {
281
+ v.fill(1);
282
+ k.fill(0);
283
+ i = 0;
284
+ };
285
+ const h = (...b) => hmacFn(k, v, ...b);
286
+ const reseed = (seed = u8n(0)) => {
287
+ k = h(u8fr([0]), seed);
288
+ v = h();
289
+ if (seed.length === 0)
290
+ return;
291
+ k = h(u8fr([1]), seed);
292
+ v = h();
293
+ };
294
+ const gen2 = () => {
295
+ if (i++ >= 1e3)
296
+ throw new Error("drbg: tried 1000 values");
297
+ let len = 0;
298
+ const out = [];
299
+ while (len < qByteLen) {
300
+ v = h();
301
+ const sl = v.slice();
302
+ out.push(sl);
303
+ len += v.length;
304
+ }
305
+ return concatBytes2(...out);
306
+ };
307
+ const genUntil = (seed, pred) => {
308
+ reset();
309
+ reseed(seed);
310
+ let res = void 0;
311
+ while (!(res = pred(gen2())))
312
+ reseed();
313
+ reset();
314
+ return res;
315
+ };
316
+ return genUntil;
317
+ }
318
+ var validatorFns = {
319
+ bigint: (val) => typeof val === "bigint",
320
+ function: (val) => typeof val === "function",
321
+ boolean: (val) => typeof val === "boolean",
322
+ string: (val) => typeof val === "string",
323
+ stringOrUint8Array: (val) => typeof val === "string" || isBytes2(val),
324
+ isSafeInteger: (val) => Number.isSafeInteger(val),
325
+ array: (val) => Array.isArray(val),
326
+ field: (val, object) => object.Fp.isValid(val),
327
+ hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
328
+ };
329
+ function validateObject(object, validators, optValidators = {}) {
330
+ const checkField = (fieldName, type, isOptional) => {
331
+ const checkVal = validatorFns[type];
332
+ if (typeof checkVal !== "function")
333
+ throw new Error("invalid validator function");
334
+ const val = object[fieldName];
335
+ if (isOptional && val === void 0)
336
+ return;
337
+ if (!checkVal(val, object)) {
338
+ throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val);
339
+ }
340
+ };
341
+ for (const [fieldName, type] of Object.entries(validators))
342
+ checkField(fieldName, type, false);
343
+ for (const [fieldName, type] of Object.entries(optValidators))
344
+ checkField(fieldName, type, true);
345
+ return object;
346
+ }
347
+ function memoized(fn) {
348
+ const map = /* @__PURE__ */ new WeakMap();
349
+ return (arg, ...args2) => {
350
+ const val = map.get(arg);
351
+ if (val !== void 0)
352
+ return val;
353
+ const computed = fn(arg, ...args2);
354
+ map.set(arg, computed);
355
+ return computed;
356
+ };
357
+ }
358
+
359
+ // node_modules/@noble/curves/esm/abstract/modular.js
360
+ var _0n2 = BigInt(0);
361
+ var _1n2 = BigInt(1);
362
+ var _2n = /* @__PURE__ */ BigInt(2);
363
+ var _3n = /* @__PURE__ */ BigInt(3);
364
+ var _4n = /* @__PURE__ */ BigInt(4);
365
+ var _5n = /* @__PURE__ */ BigInt(5);
366
+ var _8n = /* @__PURE__ */ BigInt(8);
367
+ function mod(a, b) {
368
+ const result = a % b;
369
+ return result >= _0n2 ? result : b + result;
370
+ }
371
+ function pow2(x, power, modulo) {
372
+ let res = x;
373
+ while (power-- > _0n2) {
374
+ res *= res;
375
+ res %= modulo;
376
+ }
377
+ return res;
378
+ }
379
+ function invert(number, modulo) {
380
+ if (number === _0n2)
381
+ throw new Error("invert: expected non-zero number");
382
+ if (modulo <= _0n2)
383
+ throw new Error("invert: expected positive modulus, got " + modulo);
384
+ let a = mod(number, modulo);
385
+ let b = modulo;
386
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
387
+ while (a !== _0n2) {
388
+ const q = b / a;
389
+ const r = b % a;
390
+ const m = x - u * q;
391
+ const n = y - v * q;
392
+ b = a, a = r, x = u, y = v, u = m, v = n;
393
+ }
394
+ const gcd = b;
395
+ if (gcd !== _1n2)
396
+ throw new Error("invert: does not exist");
397
+ return mod(x, modulo);
398
+ }
399
+ function sqrt3mod4(Fp, n) {
400
+ const p1div4 = (Fp.ORDER + _1n2) / _4n;
401
+ const root = Fp.pow(n, p1div4);
402
+ if (!Fp.eql(Fp.sqr(root), n))
403
+ throw new Error("Cannot find square root");
404
+ return root;
405
+ }
406
+ function sqrt5mod8(Fp, n) {
407
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
408
+ const n2 = Fp.mul(n, _2n);
409
+ const v = Fp.pow(n2, p5div8);
410
+ const nv = Fp.mul(n, v);
411
+ const i = Fp.mul(Fp.mul(nv, _2n), v);
412
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
413
+ if (!Fp.eql(Fp.sqr(root), n))
414
+ throw new Error("Cannot find square root");
415
+ return root;
416
+ }
417
+ function tonelliShanks(P) {
418
+ if (P < BigInt(3))
419
+ throw new Error("sqrt is not defined for small field");
420
+ let Q = P - _1n2;
421
+ let S = 0;
422
+ while (Q % _2n === _0n2) {
423
+ Q /= _2n;
424
+ S++;
425
+ }
426
+ let Z = _2n;
427
+ const _Fp = Field(P);
428
+ while (FpLegendre(_Fp, Z) === 1) {
429
+ if (Z++ > 1e3)
430
+ throw new Error("Cannot find square root: probably non-prime P");
431
+ }
432
+ if (S === 1)
433
+ return sqrt3mod4;
434
+ let cc = _Fp.pow(Z, Q);
435
+ const Q1div2 = (Q + _1n2) / _2n;
436
+ return function tonelliSlow(Fp, n) {
437
+ if (Fp.is0(n))
438
+ return n;
439
+ if (FpLegendre(Fp, n) !== 1)
440
+ throw new Error("Cannot find square root");
441
+ let M = S;
442
+ let c = Fp.mul(Fp.ONE, cc);
443
+ let t = Fp.pow(n, Q);
444
+ let R = Fp.pow(n, Q1div2);
445
+ while (!Fp.eql(t, Fp.ONE)) {
446
+ if (Fp.is0(t))
447
+ return Fp.ZERO;
448
+ let i = 1;
449
+ let t_tmp = Fp.sqr(t);
450
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
451
+ i++;
452
+ t_tmp = Fp.sqr(t_tmp);
453
+ if (i === M)
454
+ throw new Error("Cannot find square root");
455
+ }
456
+ const exponent = _1n2 << BigInt(M - i - 1);
457
+ const b = Fp.pow(c, exponent);
458
+ M = i;
459
+ c = Fp.sqr(b);
460
+ t = Fp.mul(t, c);
461
+ R = Fp.mul(R, b);
462
+ }
463
+ return R;
464
+ };
465
+ }
466
+ function FpSqrt(P) {
467
+ if (P % _4n === _3n)
468
+ return sqrt3mod4;
469
+ if (P % _8n === _5n)
470
+ return sqrt5mod8;
471
+ return tonelliShanks(P);
472
+ }
473
+ var FIELD_FIELDS = [
474
+ "create",
475
+ "isValid",
476
+ "is0",
477
+ "neg",
478
+ "inv",
479
+ "sqrt",
480
+ "sqr",
481
+ "eql",
482
+ "add",
483
+ "sub",
484
+ "mul",
485
+ "pow",
486
+ "div",
487
+ "addN",
488
+ "subN",
489
+ "mulN",
490
+ "sqrN"
491
+ ];
492
+ function validateField(field) {
493
+ const initial = {
494
+ ORDER: "bigint",
495
+ MASK: "bigint",
496
+ BYTES: "isSafeInteger",
497
+ BITS: "isSafeInteger"
498
+ };
499
+ const opts = FIELD_FIELDS.reduce((map, val) => {
500
+ map[val] = "function";
501
+ return map;
502
+ }, initial);
503
+ return validateObject(field, opts);
504
+ }
505
+ function FpPow(Fp, num, power) {
506
+ if (power < _0n2)
507
+ throw new Error("invalid exponent, negatives unsupported");
508
+ if (power === _0n2)
509
+ return Fp.ONE;
510
+ if (power === _1n2)
511
+ return num;
512
+ let p = Fp.ONE;
513
+ let d = num;
514
+ while (power > _0n2) {
515
+ if (power & _1n2)
516
+ p = Fp.mul(p, d);
517
+ d = Fp.sqr(d);
518
+ power >>= _1n2;
519
+ }
520
+ return p;
521
+ }
522
+ function FpInvertBatch(Fp, nums, passZero = false) {
523
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
524
+ const multipliedAcc = nums.reduce((acc, num, i) => {
525
+ if (Fp.is0(num))
526
+ return acc;
527
+ inverted[i] = acc;
528
+ return Fp.mul(acc, num);
529
+ }, Fp.ONE);
530
+ const invertedAcc = Fp.inv(multipliedAcc);
531
+ nums.reduceRight((acc, num, i) => {
532
+ if (Fp.is0(num))
533
+ return acc;
534
+ inverted[i] = Fp.mul(acc, inverted[i]);
535
+ return Fp.mul(acc, num);
536
+ }, invertedAcc);
537
+ return inverted;
538
+ }
539
+ function FpLegendre(Fp, n) {
540
+ const p1mod2 = (Fp.ORDER - _1n2) / _2n;
541
+ const powered = Fp.pow(n, p1mod2);
542
+ const yes = Fp.eql(powered, Fp.ONE);
543
+ const zero = Fp.eql(powered, Fp.ZERO);
544
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
545
+ if (!yes && !zero && !no)
546
+ throw new Error("invalid Legendre symbol result");
547
+ return yes ? 1 : zero ? 0 : -1;
548
+ }
549
+ function nLength(n, nBitLength) {
550
+ if (nBitLength !== void 0)
551
+ anumber(nBitLength);
552
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
553
+ const nByteLength = Math.ceil(_nBitLength / 8);
554
+ return { nBitLength: _nBitLength, nByteLength };
555
+ }
556
+ function Field(ORDER, bitLen2, isLE2 = false, redef = {}) {
557
+ if (ORDER <= _0n2)
558
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
559
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2);
560
+ if (BYTES > 2048)
561
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
562
+ let sqrtP;
563
+ const f = Object.freeze({
564
+ ORDER,
565
+ isLE: isLE2,
566
+ BITS,
567
+ BYTES,
568
+ MASK: bitMask(BITS),
569
+ ZERO: _0n2,
570
+ ONE: _1n2,
571
+ create: (num) => mod(num, ORDER),
572
+ isValid: (num) => {
573
+ if (typeof num !== "bigint")
574
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
575
+ return _0n2 <= num && num < ORDER;
576
+ },
577
+ is0: (num) => num === _0n2,
578
+ isOdd: (num) => (num & _1n2) === _1n2,
579
+ neg: (num) => mod(-num, ORDER),
580
+ eql: (lhs, rhs) => lhs === rhs,
581
+ sqr: (num) => mod(num * num, ORDER),
582
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
583
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
584
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
585
+ pow: (num, power) => FpPow(f, num, power),
586
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
587
+ // Same as above, but doesn't normalize
588
+ sqrN: (num) => num * num,
589
+ addN: (lhs, rhs) => lhs + rhs,
590
+ subN: (lhs, rhs) => lhs - rhs,
591
+ mulN: (lhs, rhs) => lhs * rhs,
592
+ inv: (num) => invert(num, ORDER),
593
+ sqrt: redef.sqrt || ((n) => {
594
+ if (!sqrtP)
595
+ sqrtP = FpSqrt(ORDER);
596
+ return sqrtP(f, n);
597
+ }),
598
+ toBytes: (num) => isLE2 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
599
+ fromBytes: (bytes) => {
600
+ if (bytes.length !== BYTES)
601
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
602
+ return isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
603
+ },
604
+ // TODO: we don't need it here, move out to separate fn
605
+ invertBatch: (lst) => FpInvertBatch(f, lst),
606
+ // We can't move this out because Fp6, Fp12 implement it
607
+ // and it's unclear what to return in there.
608
+ cmov: (a, b, c) => c ? b : a
609
+ });
610
+ return Object.freeze(f);
611
+ }
612
+ function getFieldBytesLength(fieldOrder) {
613
+ if (typeof fieldOrder !== "bigint")
614
+ throw new Error("field order must be bigint");
615
+ const bitLength = fieldOrder.toString(2).length;
616
+ return Math.ceil(bitLength / 8);
617
+ }
618
+ function getMinHashLength(fieldOrder) {
619
+ const length = getFieldBytesLength(fieldOrder);
620
+ return length + Math.ceil(length / 2);
621
+ }
622
+ function mapHashToField(key, fieldOrder, isLE2 = false) {
623
+ const len = key.length;
624
+ const fieldLen = getFieldBytesLength(fieldOrder);
625
+ const minLen = getMinHashLength(fieldOrder);
626
+ if (len < 16 || len < minLen || len > 1024)
627
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
628
+ const num = isLE2 ? bytesToNumberLE(key) : bytesToNumberBE(key);
629
+ const reduced = mod(num, fieldOrder - _1n2) + _1n2;
630
+ return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
631
+ }
632
+
633
+ // node_modules/@noble/hashes/esm/_md.js
634
+ function setBigUint64(view, byteOffset, value, isLE2) {
635
+ if (typeof view.setBigUint64 === "function")
636
+ return view.setBigUint64(byteOffset, value, isLE2);
637
+ const _32n2 = BigInt(32);
638
+ const _u32_max = BigInt(4294967295);
639
+ const wh = Number(value >> _32n2 & _u32_max);
640
+ const wl = Number(value & _u32_max);
641
+ const h = isLE2 ? 4 : 0;
642
+ const l = isLE2 ? 0 : 4;
643
+ view.setUint32(byteOffset + h, wh, isLE2);
644
+ view.setUint32(byteOffset + l, wl, isLE2);
645
+ }
646
+ function Chi(a, b, c) {
647
+ return a & b ^ ~a & c;
648
+ }
649
+ function Maj(a, b, c) {
650
+ return a & b ^ a & c ^ b & c;
651
+ }
652
+ var HashMD = class extends Hash {
653
+ constructor(blockLen, outputLen, padOffset, isLE2) {
654
+ super();
655
+ this.finished = false;
656
+ this.length = 0;
657
+ this.pos = 0;
658
+ this.destroyed = false;
659
+ this.blockLen = blockLen;
660
+ this.outputLen = outputLen;
661
+ this.padOffset = padOffset;
662
+ this.isLE = isLE2;
663
+ this.buffer = new Uint8Array(blockLen);
664
+ this.view = createView(this.buffer);
665
+ }
666
+ update(data) {
667
+ aexists(this);
668
+ data = toBytes(data);
669
+ abytes(data);
670
+ const { view, buffer, blockLen } = this;
671
+ const len = data.length;
672
+ for (let pos = 0; pos < len; ) {
673
+ const take = Math.min(blockLen - this.pos, len - pos);
674
+ if (take === blockLen) {
675
+ const dataView = createView(data);
676
+ for (; blockLen <= len - pos; pos += blockLen)
677
+ this.process(dataView, pos);
678
+ continue;
679
+ }
680
+ buffer.set(data.subarray(pos, pos + take), this.pos);
681
+ this.pos += take;
682
+ pos += take;
683
+ if (this.pos === blockLen) {
684
+ this.process(view, 0);
685
+ this.pos = 0;
686
+ }
687
+ }
688
+ this.length += data.length;
689
+ this.roundClean();
690
+ return this;
691
+ }
692
+ digestInto(out) {
693
+ aexists(this);
694
+ aoutput(out, this);
695
+ this.finished = true;
696
+ const { buffer, view, blockLen, isLE: isLE2 } = this;
697
+ let { pos } = this;
698
+ buffer[pos++] = 128;
699
+ clean(this.buffer.subarray(pos));
700
+ if (this.padOffset > blockLen - pos) {
701
+ this.process(view, 0);
702
+ pos = 0;
703
+ }
704
+ for (let i = pos; i < blockLen; i++)
705
+ buffer[i] = 0;
706
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2);
707
+ this.process(view, 0);
708
+ const oview = createView(out);
709
+ const len = this.outputLen;
710
+ if (len % 4)
711
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
712
+ const outLen = len / 4;
713
+ const state = this.get();
714
+ if (outLen > state.length)
715
+ throw new Error("_sha2: outputLen bigger than state");
716
+ for (let i = 0; i < outLen; i++)
717
+ oview.setUint32(4 * i, state[i], isLE2);
718
+ }
719
+ digest() {
720
+ const { buffer, outputLen } = this;
721
+ this.digestInto(buffer);
722
+ const res = buffer.slice(0, outputLen);
723
+ this.destroy();
724
+ return res;
725
+ }
726
+ _cloneInto(to) {
727
+ to || (to = new this.constructor());
728
+ to.set(...this.get());
729
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
730
+ to.destroyed = destroyed;
731
+ to.finished = finished;
732
+ to.length = length;
733
+ to.pos = pos;
734
+ if (length % blockLen)
735
+ to.buffer.set(buffer);
736
+ return to;
737
+ }
738
+ clone() {
739
+ return this._cloneInto();
740
+ }
741
+ };
742
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
743
+ 1779033703,
744
+ 3144134277,
745
+ 1013904242,
746
+ 2773480762,
747
+ 1359893119,
748
+ 2600822924,
749
+ 528734635,
750
+ 1541459225
751
+ ]);
752
+
753
+ // node_modules/@noble/hashes/esm/_u64.js
754
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
755
+ var _32n = /* @__PURE__ */ BigInt(32);
756
+ function fromBig(n, le = false) {
757
+ if (le)
758
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
759
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
760
+ }
761
+ function split(lst, le = false) {
762
+ const len = lst.length;
763
+ let Ah = new Uint32Array(len);
764
+ let Al = new Uint32Array(len);
765
+ for (let i = 0; i < len; i++) {
766
+ const { h, l } = fromBig(lst[i], le);
767
+ [Ah[i], Al[i]] = [h, l];
768
+ }
769
+ return [Ah, Al];
770
+ }
771
+ var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
772
+ var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
773
+ var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
774
+ var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
775
+
776
+ // node_modules/@noble/hashes/esm/sha2.js
777
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
778
+ 1116352408,
779
+ 1899447441,
780
+ 3049323471,
781
+ 3921009573,
782
+ 961987163,
783
+ 1508970993,
784
+ 2453635748,
785
+ 2870763221,
786
+ 3624381080,
787
+ 310598401,
788
+ 607225278,
789
+ 1426881987,
790
+ 1925078388,
791
+ 2162078206,
792
+ 2614888103,
793
+ 3248222580,
794
+ 3835390401,
795
+ 4022224774,
796
+ 264347078,
797
+ 604807628,
798
+ 770255983,
799
+ 1249150122,
800
+ 1555081692,
801
+ 1996064986,
802
+ 2554220882,
803
+ 2821834349,
804
+ 2952996808,
805
+ 3210313671,
806
+ 3336571891,
807
+ 3584528711,
808
+ 113926993,
809
+ 338241895,
810
+ 666307205,
811
+ 773529912,
812
+ 1294757372,
813
+ 1396182291,
814
+ 1695183700,
815
+ 1986661051,
816
+ 2177026350,
817
+ 2456956037,
818
+ 2730485921,
819
+ 2820302411,
820
+ 3259730800,
821
+ 3345764771,
822
+ 3516065817,
823
+ 3600352804,
824
+ 4094571909,
825
+ 275423344,
826
+ 430227734,
827
+ 506948616,
828
+ 659060556,
829
+ 883997877,
830
+ 958139571,
831
+ 1322822218,
832
+ 1537002063,
833
+ 1747873779,
834
+ 1955562222,
835
+ 2024104815,
836
+ 2227730452,
837
+ 2361852424,
838
+ 2428436474,
839
+ 2756734187,
840
+ 3204031479,
841
+ 3329325298
842
+ ]);
843
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
844
+ var SHA256 = class extends HashMD {
845
+ constructor(outputLen = 32) {
846
+ super(64, outputLen, 8, false);
847
+ this.A = SHA256_IV[0] | 0;
848
+ this.B = SHA256_IV[1] | 0;
849
+ this.C = SHA256_IV[2] | 0;
850
+ this.D = SHA256_IV[3] | 0;
851
+ this.E = SHA256_IV[4] | 0;
852
+ this.F = SHA256_IV[5] | 0;
853
+ this.G = SHA256_IV[6] | 0;
854
+ this.H = SHA256_IV[7] | 0;
855
+ }
856
+ get() {
857
+ const { A, B, C, D, E, F, G, H } = this;
858
+ return [A, B, C, D, E, F, G, H];
859
+ }
860
+ // prettier-ignore
861
+ set(A, B, C, D, E, F, G, H) {
862
+ this.A = A | 0;
863
+ this.B = B | 0;
864
+ this.C = C | 0;
865
+ this.D = D | 0;
866
+ this.E = E | 0;
867
+ this.F = F | 0;
868
+ this.G = G | 0;
869
+ this.H = H | 0;
870
+ }
871
+ process(view, offset) {
872
+ for (let i = 0; i < 16; i++, offset += 4)
873
+ SHA256_W[i] = view.getUint32(offset, false);
874
+ for (let i = 16; i < 64; i++) {
875
+ const W15 = SHA256_W[i - 15];
876
+ const W2 = SHA256_W[i - 2];
877
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
878
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
879
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
880
+ }
881
+ let { A, B, C, D, E, F, G, H } = this;
882
+ for (let i = 0; i < 64; i++) {
883
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
884
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
885
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
886
+ const T2 = sigma0 + Maj(A, B, C) | 0;
887
+ H = G;
888
+ G = F;
889
+ F = E;
890
+ E = D + T1 | 0;
891
+ D = C;
892
+ C = B;
893
+ B = A;
894
+ A = T1 + T2 | 0;
895
+ }
896
+ A = A + this.A | 0;
897
+ B = B + this.B | 0;
898
+ C = C + this.C | 0;
899
+ D = D + this.D | 0;
900
+ E = E + this.E | 0;
901
+ F = F + this.F | 0;
902
+ G = G + this.G | 0;
903
+ H = H + this.H | 0;
904
+ this.set(A, B, C, D, E, F, G, H);
905
+ }
906
+ roundClean() {
907
+ clean(SHA256_W);
908
+ }
909
+ destroy() {
910
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
911
+ clean(this.buffer);
912
+ }
913
+ };
914
+ var sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
915
+
916
+ // node_modules/@noble/hashes/esm/hmac.js
917
+ var HMAC = class extends Hash {
918
+ constructor(hash, _key) {
919
+ super();
920
+ this.finished = false;
921
+ this.destroyed = false;
922
+ ahash(hash);
923
+ const key = toBytes(_key);
924
+ this.iHash = hash.create();
925
+ if (typeof this.iHash.update !== "function")
926
+ throw new Error("Expected instance of class which extends utils.Hash");
927
+ this.blockLen = this.iHash.blockLen;
928
+ this.outputLen = this.iHash.outputLen;
929
+ const blockLen = this.blockLen;
930
+ const pad2 = new Uint8Array(blockLen);
931
+ pad2.set(key.length > blockLen ? hash.create().update(key).digest() : key);
932
+ for (let i = 0; i < pad2.length; i++)
933
+ pad2[i] ^= 54;
934
+ this.iHash.update(pad2);
935
+ this.oHash = hash.create();
936
+ for (let i = 0; i < pad2.length; i++)
937
+ pad2[i] ^= 54 ^ 92;
938
+ this.oHash.update(pad2);
939
+ clean(pad2);
940
+ }
941
+ update(buf) {
942
+ aexists(this);
943
+ this.iHash.update(buf);
944
+ return this;
945
+ }
946
+ digestInto(out) {
947
+ aexists(this);
948
+ abytes(out, this.outputLen);
949
+ this.finished = true;
950
+ this.iHash.digestInto(out);
951
+ this.oHash.update(out);
952
+ this.oHash.digestInto(out);
953
+ this.destroy();
954
+ }
955
+ digest() {
956
+ const out = new Uint8Array(this.oHash.outputLen);
957
+ this.digestInto(out);
958
+ return out;
959
+ }
960
+ _cloneInto(to) {
961
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
962
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
963
+ to = to;
964
+ to.finished = finished;
965
+ to.destroyed = destroyed;
966
+ to.blockLen = blockLen;
967
+ to.outputLen = outputLen;
968
+ to.oHash = oHash._cloneInto(to.oHash);
969
+ to.iHash = iHash._cloneInto(to.iHash);
970
+ return to;
971
+ }
972
+ clone() {
973
+ return this._cloneInto();
974
+ }
975
+ destroy() {
976
+ this.destroyed = true;
977
+ this.oHash.destroy();
978
+ this.iHash.destroy();
979
+ }
980
+ };
981
+ var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
982
+ hmac.create = (hash, key) => new HMAC(hash, key);
983
+
984
+ // node_modules/@noble/curves/esm/abstract/curve.js
985
+ var _0n3 = BigInt(0);
986
+ var _1n3 = BigInt(1);
987
+ function constTimeNegate(condition, item) {
988
+ const neg = item.negate();
989
+ return condition ? neg : item;
990
+ }
991
+ function validateW(W, bits) {
992
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
993
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
994
+ }
995
+ function calcWOpts(W, scalarBits) {
996
+ validateW(W, scalarBits);
997
+ const windows = Math.ceil(scalarBits / W) + 1;
998
+ const windowSize = 2 ** (W - 1);
999
+ const maxNumber = 2 ** W;
1000
+ const mask = bitMask(W);
1001
+ const shiftBy = BigInt(W);
1002
+ return { windows, windowSize, mask, maxNumber, shiftBy };
1003
+ }
1004
+ function calcOffsets(n, window, wOpts) {
1005
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
1006
+ let wbits = Number(n & mask);
1007
+ let nextN = n >> shiftBy;
1008
+ if (wbits > windowSize) {
1009
+ wbits -= maxNumber;
1010
+ nextN += _1n3;
1011
+ }
1012
+ const offsetStart = window * windowSize;
1013
+ const offset = offsetStart + Math.abs(wbits) - 1;
1014
+ const isZero = wbits === 0;
1015
+ const isNeg = wbits < 0;
1016
+ const isNegF = window % 2 !== 0;
1017
+ const offsetF = offsetStart;
1018
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
1019
+ }
1020
+ function validateMSMPoints(points, c) {
1021
+ if (!Array.isArray(points))
1022
+ throw new Error("array expected");
1023
+ points.forEach((p, i) => {
1024
+ if (!(p instanceof c))
1025
+ throw new Error("invalid point at index " + i);
1026
+ });
1027
+ }
1028
+ function validateMSMScalars(scalars, field) {
1029
+ if (!Array.isArray(scalars))
1030
+ throw new Error("array of scalars expected");
1031
+ scalars.forEach((s, i) => {
1032
+ if (!field.isValid(s))
1033
+ throw new Error("invalid scalar at index " + i);
1034
+ });
1035
+ }
1036
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
1037
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
1038
+ function getW(P) {
1039
+ return pointWindowSizes.get(P) || 1;
1040
+ }
1041
+ function wNAF(c, bits) {
1042
+ return {
1043
+ constTimeNegate,
1044
+ hasPrecomputes(elm) {
1045
+ return getW(elm) !== 1;
1046
+ },
1047
+ // non-const time multiplication ladder
1048
+ unsafeLadder(elm, n, p = c.ZERO) {
1049
+ let d = elm;
1050
+ while (n > _0n3) {
1051
+ if (n & _1n3)
1052
+ p = p.add(d);
1053
+ d = d.double();
1054
+ n >>= _1n3;
1055
+ }
1056
+ return p;
1057
+ },
1058
+ /**
1059
+ * Creates a wNAF precomputation window. Used for caching.
1060
+ * Default window size is set by `utils.precompute()` and is equal to 8.
1061
+ * Number of precomputed points depends on the curve size:
1062
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1063
+ * - 𝑊 is the window size
1064
+ * - 𝑛 is the bitlength of the curve order.
1065
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1066
+ * @param elm Point instance
1067
+ * @param W window size
1068
+ * @returns precomputed point tables flattened to a single array
1069
+ */
1070
+ precomputeWindow(elm, W) {
1071
+ const { windows, windowSize } = calcWOpts(W, bits);
1072
+ const points = [];
1073
+ let p = elm;
1074
+ let base = p;
1075
+ for (let window = 0; window < windows; window++) {
1076
+ base = p;
1077
+ points.push(base);
1078
+ for (let i = 1; i < windowSize; i++) {
1079
+ base = base.add(p);
1080
+ points.push(base);
1081
+ }
1082
+ p = base.double();
1083
+ }
1084
+ return points;
1085
+ },
1086
+ /**
1087
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1088
+ * @param W window size
1089
+ * @param precomputes precomputed tables
1090
+ * @param n scalar (we don't check here, but should be less than curve order)
1091
+ * @returns real and fake (for const-time) points
1092
+ */
1093
+ wNAF(W, precomputes, n) {
1094
+ let p = c.ZERO;
1095
+ let f = c.BASE;
1096
+ const wo = calcWOpts(W, bits);
1097
+ for (let window = 0; window < wo.windows; window++) {
1098
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
1099
+ n = nextN;
1100
+ if (isZero) {
1101
+ f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));
1102
+ } else {
1103
+ p = p.add(constTimeNegate(isNeg, precomputes[offset]));
1104
+ }
1105
+ }
1106
+ return { p, f };
1107
+ },
1108
+ /**
1109
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
1110
+ * @param W window size
1111
+ * @param precomputes precomputed tables
1112
+ * @param n scalar (we don't check here, but should be less than curve order)
1113
+ * @param acc accumulator point to add result of multiplication
1114
+ * @returns point
1115
+ */
1116
+ wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
1117
+ const wo = calcWOpts(W, bits);
1118
+ for (let window = 0; window < wo.windows; window++) {
1119
+ if (n === _0n3)
1120
+ break;
1121
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
1122
+ n = nextN;
1123
+ if (isZero) {
1124
+ continue;
1125
+ } else {
1126
+ const item = precomputes[offset];
1127
+ acc = acc.add(isNeg ? item.negate() : item);
1128
+ }
1129
+ }
1130
+ return acc;
1131
+ },
1132
+ getPrecomputes(W, P, transform) {
1133
+ let comp = pointPrecomputes.get(P);
1134
+ if (!comp) {
1135
+ comp = this.precomputeWindow(P, W);
1136
+ if (W !== 1)
1137
+ pointPrecomputes.set(P, transform(comp));
1138
+ }
1139
+ return comp;
1140
+ },
1141
+ wNAFCached(P, n, transform) {
1142
+ const W = getW(P);
1143
+ return this.wNAF(W, this.getPrecomputes(W, P, transform), n);
1144
+ },
1145
+ wNAFCachedUnsafe(P, n, transform, prev) {
1146
+ const W = getW(P);
1147
+ if (W === 1)
1148
+ return this.unsafeLadder(P, n, prev);
1149
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);
1150
+ },
1151
+ // We calculate precomputes for elliptic curve point multiplication
1152
+ // using windowed method. This specifies window size and
1153
+ // stores precomputed values. Usually only base point would be precomputed.
1154
+ setWindowSize(P, W) {
1155
+ validateW(W, bits);
1156
+ pointWindowSizes.set(P, W);
1157
+ pointPrecomputes.delete(P);
1158
+ }
1159
+ };
1160
+ }
1161
+ function pippenger(c, fieldN, points, scalars) {
1162
+ validateMSMPoints(points, c);
1163
+ validateMSMScalars(scalars, fieldN);
1164
+ const plength = points.length;
1165
+ const slength = scalars.length;
1166
+ if (plength !== slength)
1167
+ throw new Error("arrays of points and scalars must have equal length");
1168
+ const zero = c.ZERO;
1169
+ const wbits = bitLen(BigInt(plength));
1170
+ let windowSize = 1;
1171
+ if (wbits > 12)
1172
+ windowSize = wbits - 3;
1173
+ else if (wbits > 4)
1174
+ windowSize = wbits - 2;
1175
+ else if (wbits > 0)
1176
+ windowSize = 2;
1177
+ const MASK = bitMask(windowSize);
1178
+ const buckets = new Array(Number(MASK) + 1).fill(zero);
1179
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
1180
+ let sum = zero;
1181
+ for (let i = lastBits; i >= 0; i -= windowSize) {
1182
+ buckets.fill(zero);
1183
+ for (let j = 0; j < slength; j++) {
1184
+ const scalar = scalars[j];
1185
+ const wbits2 = Number(scalar >> BigInt(i) & MASK);
1186
+ buckets[wbits2] = buckets[wbits2].add(points[j]);
1187
+ }
1188
+ let resI = zero;
1189
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
1190
+ sumI = sumI.add(buckets[j]);
1191
+ resI = resI.add(sumI);
1192
+ }
1193
+ sum = sum.add(resI);
1194
+ if (i !== 0)
1195
+ for (let j = 0; j < windowSize; j++)
1196
+ sum = sum.double();
1197
+ }
1198
+ return sum;
1199
+ }
1200
+ function validateBasic(curve) {
1201
+ validateField(curve.Fp);
1202
+ validateObject(curve, {
1203
+ n: "bigint",
1204
+ h: "bigint",
1205
+ Gx: "field",
1206
+ Gy: "field"
1207
+ }, {
1208
+ nBitLength: "isSafeInteger",
1209
+ nByteLength: "isSafeInteger"
1210
+ });
1211
+ return Object.freeze({
1212
+ ...nLength(curve.n, curve.nBitLength),
1213
+ ...curve,
1214
+ ...{ p: curve.Fp.ORDER }
1215
+ });
1216
+ }
1217
+
1218
+ // node_modules/@noble/curves/esm/abstract/weierstrass.js
1219
+ function validateSigVerOpts(opts) {
1220
+ if (opts.lowS !== void 0)
1221
+ abool("lowS", opts.lowS);
1222
+ if (opts.prehash !== void 0)
1223
+ abool("prehash", opts.prehash);
1224
+ }
1225
+ function validatePointOpts(curve) {
1226
+ const opts = validateBasic(curve);
1227
+ validateObject(opts, {
1228
+ a: "field",
1229
+ b: "field"
1230
+ }, {
1231
+ allowInfinityPoint: "boolean",
1232
+ allowedPrivateKeyLengths: "array",
1233
+ clearCofactor: "function",
1234
+ fromBytes: "function",
1235
+ isTorsionFree: "function",
1236
+ toBytes: "function",
1237
+ wrapPrivateKey: "boolean"
1238
+ });
1239
+ const { endo, Fp, a } = opts;
1240
+ if (endo) {
1241
+ if (!Fp.eql(a, Fp.ZERO)) {
1242
+ throw new Error("invalid endo: CURVE.a must be 0");
1243
+ }
1244
+ if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") {
1245
+ throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');
1246
+ }
1247
+ }
1248
+ return Object.freeze({ ...opts });
1249
+ }
1250
+ var DERErr = class extends Error {
1251
+ constructor(m = "") {
1252
+ super(m);
1253
+ }
1254
+ };
1255
+ var DER = {
1256
+ // asn.1 DER encoding utils
1257
+ Err: DERErr,
1258
+ // Basic building block is TLV (Tag-Length-Value)
1259
+ _tlv: {
1260
+ encode: (tag, data) => {
1261
+ const { Err: E } = DER;
1262
+ if (tag < 0 || tag > 256)
1263
+ throw new E("tlv.encode: wrong tag");
1264
+ if (data.length & 1)
1265
+ throw new E("tlv.encode: unpadded data");
1266
+ const dataLen = data.length / 2;
1267
+ const len = numberToHexUnpadded(dataLen);
1268
+ if (len.length / 2 & 128)
1269
+ throw new E("tlv.encode: long form length too big");
1270
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
1271
+ const t = numberToHexUnpadded(tag);
1272
+ return t + lenLen + len + data;
1273
+ },
1274
+ // v - value, l - left bytes (unparsed)
1275
+ decode(tag, data) {
1276
+ const { Err: E } = DER;
1277
+ let pos = 0;
1278
+ if (tag < 0 || tag > 256)
1279
+ throw new E("tlv.encode: wrong tag");
1280
+ if (data.length < 2 || data[pos++] !== tag)
1281
+ throw new E("tlv.decode: wrong tlv");
1282
+ const first = data[pos++];
1283
+ const isLong = !!(first & 128);
1284
+ let length = 0;
1285
+ if (!isLong)
1286
+ length = first;
1287
+ else {
1288
+ const lenLen = first & 127;
1289
+ if (!lenLen)
1290
+ throw new E("tlv.decode(long): indefinite length not supported");
1291
+ if (lenLen > 4)
1292
+ throw new E("tlv.decode(long): byte length is too big");
1293
+ const lengthBytes = data.subarray(pos, pos + lenLen);
1294
+ if (lengthBytes.length !== lenLen)
1295
+ throw new E("tlv.decode: length bytes not complete");
1296
+ if (lengthBytes[0] === 0)
1297
+ throw new E("tlv.decode(long): zero leftmost byte");
1298
+ for (const b of lengthBytes)
1299
+ length = length << 8 | b;
1300
+ pos += lenLen;
1301
+ if (length < 128)
1302
+ throw new E("tlv.decode(long): not minimal encoding");
1303
+ }
1304
+ const v = data.subarray(pos, pos + length);
1305
+ if (v.length !== length)
1306
+ throw new E("tlv.decode: wrong value length");
1307
+ return { v, l: data.subarray(pos + length) };
1308
+ }
1309
+ },
1310
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
1311
+ // since we always use positive integers here. It must always be empty:
1312
+ // - add zero byte if exists
1313
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
1314
+ _int: {
1315
+ encode(num) {
1316
+ const { Err: E } = DER;
1317
+ if (num < _0n4)
1318
+ throw new E("integer: negative integers are not allowed");
1319
+ let hex = numberToHexUnpadded(num);
1320
+ if (Number.parseInt(hex[0], 16) & 8)
1321
+ hex = "00" + hex;
1322
+ if (hex.length & 1)
1323
+ throw new E("unexpected DER parsing assertion: unpadded hex");
1324
+ return hex;
1325
+ },
1326
+ decode(data) {
1327
+ const { Err: E } = DER;
1328
+ if (data[0] & 128)
1329
+ throw new E("invalid signature integer: negative");
1330
+ if (data[0] === 0 && !(data[1] & 128))
1331
+ throw new E("invalid signature integer: unnecessary leading zero");
1332
+ return bytesToNumberBE(data);
1333
+ }
1334
+ },
1335
+ toSig(hex) {
1336
+ const { Err: E, _int: int, _tlv: tlv } = DER;
1337
+ const data = ensureBytes("signature", hex);
1338
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
1339
+ if (seqLeftBytes.length)
1340
+ throw new E("invalid signature: left bytes after parsing");
1341
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
1342
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
1343
+ if (sLeftBytes.length)
1344
+ throw new E("invalid signature: left bytes after parsing");
1345
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
1346
+ },
1347
+ hexFromSig(sig) {
1348
+ const { _tlv: tlv, _int: int } = DER;
1349
+ const rs = tlv.encode(2, int.encode(sig.r));
1350
+ const ss = tlv.encode(2, int.encode(sig.s));
1351
+ const seq = rs + ss;
1352
+ return tlv.encode(48, seq);
1353
+ }
1354
+ };
1355
+ function numToSizedHex(num, size2) {
1356
+ return bytesToHex(numberToBytesBE(num, size2));
1357
+ }
1358
+ var _0n4 = BigInt(0);
1359
+ var _1n4 = BigInt(1);
1360
+ var _2n2 = BigInt(2);
1361
+ var _3n2 = BigInt(3);
1362
+ var _4n2 = BigInt(4);
1363
+ function weierstrassPoints(opts) {
1364
+ const CURVE = validatePointOpts(opts);
1365
+ const { Fp } = CURVE;
1366
+ const Fn = Field(CURVE.n, CURVE.nBitLength);
1367
+ const toBytes3 = CURVE.toBytes || ((_c, point, _isCompressed) => {
1368
+ const a = point.toAffine();
1369
+ return concatBytes2(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y));
1370
+ });
1371
+ const fromBytes = CURVE.fromBytes || ((bytes) => {
1372
+ const tail = bytes.subarray(1);
1373
+ const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
1374
+ const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
1375
+ return { x, y };
1376
+ });
1377
+ function weierstrassEquation(x) {
1378
+ const { a, b } = CURVE;
1379
+ const x2 = Fp.sqr(x);
1380
+ const x3 = Fp.mul(x2, x);
1381
+ return Fp.add(Fp.add(x3, Fp.mul(x, a)), b);
1382
+ }
1383
+ function isValidXY(x, y) {
1384
+ const left = Fp.sqr(y);
1385
+ const right = weierstrassEquation(x);
1386
+ return Fp.eql(left, right);
1387
+ }
1388
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
1389
+ throw new Error("bad curve params: generator point");
1390
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
1391
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
1392
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
1393
+ throw new Error("bad curve params: a or b");
1394
+ function isWithinCurveOrder(num) {
1395
+ return inRange(num, _1n4, CURVE.n);
1396
+ }
1397
+ function normPrivateKeyToScalar(key) {
1398
+ const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;
1399
+ if (lengths && typeof key !== "bigint") {
1400
+ if (isBytes2(key))
1401
+ key = bytesToHex(key);
1402
+ if (typeof key !== "string" || !lengths.includes(key.length))
1403
+ throw new Error("invalid private key");
1404
+ key = key.padStart(nByteLength * 2, "0");
1405
+ }
1406
+ let num;
1407
+ try {
1408
+ num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength));
1409
+ } catch (error) {
1410
+ throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key);
1411
+ }
1412
+ if (wrapPrivateKey)
1413
+ num = mod(num, N);
1414
+ aInRange("private key", num, _1n4, N);
1415
+ return num;
1416
+ }
1417
+ function aprjpoint(other) {
1418
+ if (!(other instanceof Point))
1419
+ throw new Error("ProjectivePoint expected");
1420
+ }
1421
+ const toAffineMemo = memoized((p, iz) => {
1422
+ const { px: x, py: y, pz: z } = p;
1423
+ if (Fp.eql(z, Fp.ONE))
1424
+ return { x, y };
1425
+ const is0 = p.is0();
1426
+ if (iz == null)
1427
+ iz = is0 ? Fp.ONE : Fp.inv(z);
1428
+ const ax = Fp.mul(x, iz);
1429
+ const ay = Fp.mul(y, iz);
1430
+ const zz = Fp.mul(z, iz);
1431
+ if (is0)
1432
+ return { x: Fp.ZERO, y: Fp.ZERO };
1433
+ if (!Fp.eql(zz, Fp.ONE))
1434
+ throw new Error("invZ was invalid");
1435
+ return { x: ax, y: ay };
1436
+ });
1437
+ const assertValidMemo = memoized((p) => {
1438
+ if (p.is0()) {
1439
+ if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
1440
+ return;
1441
+ throw new Error("bad point: ZERO");
1442
+ }
1443
+ const { x, y } = p.toAffine();
1444
+ if (!Fp.isValid(x) || !Fp.isValid(y))
1445
+ throw new Error("bad point: x or y not FE");
1446
+ if (!isValidXY(x, y))
1447
+ throw new Error("bad point: equation left != right");
1448
+ if (!p.isTorsionFree())
1449
+ throw new Error("bad point: not in prime-order subgroup");
1450
+ return true;
1451
+ });
1452
+ class Point {
1453
+ constructor(px, py, pz) {
1454
+ if (px == null || !Fp.isValid(px))
1455
+ throw new Error("x required");
1456
+ if (py == null || !Fp.isValid(py) || Fp.is0(py))
1457
+ throw new Error("y required");
1458
+ if (pz == null || !Fp.isValid(pz))
1459
+ throw new Error("z required");
1460
+ this.px = px;
1461
+ this.py = py;
1462
+ this.pz = pz;
1463
+ Object.freeze(this);
1464
+ }
1465
+ // Does not validate if the point is on-curve.
1466
+ // Use fromHex instead, or call assertValidity() later.
1467
+ static fromAffine(p) {
1468
+ const { x, y } = p || {};
1469
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
1470
+ throw new Error("invalid affine point");
1471
+ if (p instanceof Point)
1472
+ throw new Error("projective point not allowed");
1473
+ const is0 = (i) => Fp.eql(i, Fp.ZERO);
1474
+ if (is0(x) && is0(y))
1475
+ return Point.ZERO;
1476
+ return new Point(x, y, Fp.ONE);
1477
+ }
1478
+ get x() {
1479
+ return this.toAffine().x;
1480
+ }
1481
+ get y() {
1482
+ return this.toAffine().y;
1483
+ }
1484
+ /**
1485
+ * Takes a bunch of Projective Points but executes only one
1486
+ * inversion on all of them. Inversion is very slow operation,
1487
+ * so this improves performance massively.
1488
+ * Optimization: converts a list of projective points to a list of identical points with Z=1.
1489
+ */
1490
+ static normalizeZ(points) {
1491
+ const toInv = FpInvertBatch(Fp, points.map((p) => p.pz));
1492
+ return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
1493
+ }
1494
+ /**
1495
+ * Converts hash string or Uint8Array to Point.
1496
+ * @param hex short/long ECDSA hex
1497
+ */
1498
+ static fromHex(hex) {
1499
+ const P = Point.fromAffine(fromBytes(ensureBytes("pointHex", hex)));
1500
+ P.assertValidity();
1501
+ return P;
1502
+ }
1503
+ // Multiplies generator point by privateKey.
1504
+ static fromPrivateKey(privateKey) {
1505
+ return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
1506
+ }
1507
+ // Multiscalar Multiplication
1508
+ static msm(points, scalars) {
1509
+ return pippenger(Point, Fn, points, scalars);
1510
+ }
1511
+ // "Private method", don't use it directly
1512
+ _setWindowSize(windowSize) {
1513
+ wnaf.setWindowSize(this, windowSize);
1514
+ }
1515
+ // A point on curve is valid if it conforms to equation.
1516
+ assertValidity() {
1517
+ assertValidMemo(this);
1518
+ }
1519
+ hasEvenY() {
1520
+ const { y } = this.toAffine();
1521
+ if (Fp.isOdd)
1522
+ return !Fp.isOdd(y);
1523
+ throw new Error("Field doesn't support isOdd");
1524
+ }
1525
+ /**
1526
+ * Compare one point to another.
1527
+ */
1528
+ equals(other) {
1529
+ aprjpoint(other);
1530
+ const { px: X1, py: Y1, pz: Z1 } = this;
1531
+ const { px: X2, py: Y2, pz: Z2 } = other;
1532
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
1533
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
1534
+ return U1 && U2;
1535
+ }
1536
+ /**
1537
+ * Flips point to one corresponding to (x, -y) in Affine coordinates.
1538
+ */
1539
+ negate() {
1540
+ return new Point(this.px, Fp.neg(this.py), this.pz);
1541
+ }
1542
+ // Renes-Costello-Batina exception-free doubling formula.
1543
+ // There is 30% faster Jacobian formula, but it is not complete.
1544
+ // https://eprint.iacr.org/2015/1060, algorithm 3
1545
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
1546
+ double() {
1547
+ const { a, b } = CURVE;
1548
+ const b3 = Fp.mul(b, _3n2);
1549
+ const { px: X1, py: Y1, pz: Z1 } = this;
1550
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
1551
+ let t0 = Fp.mul(X1, X1);
1552
+ let t1 = Fp.mul(Y1, Y1);
1553
+ let t2 = Fp.mul(Z1, Z1);
1554
+ let t3 = Fp.mul(X1, Y1);
1555
+ t3 = Fp.add(t3, t3);
1556
+ Z3 = Fp.mul(X1, Z1);
1557
+ Z3 = Fp.add(Z3, Z3);
1558
+ X3 = Fp.mul(a, Z3);
1559
+ Y3 = Fp.mul(b3, t2);
1560
+ Y3 = Fp.add(X3, Y3);
1561
+ X3 = Fp.sub(t1, Y3);
1562
+ Y3 = Fp.add(t1, Y3);
1563
+ Y3 = Fp.mul(X3, Y3);
1564
+ X3 = Fp.mul(t3, X3);
1565
+ Z3 = Fp.mul(b3, Z3);
1566
+ t2 = Fp.mul(a, t2);
1567
+ t3 = Fp.sub(t0, t2);
1568
+ t3 = Fp.mul(a, t3);
1569
+ t3 = Fp.add(t3, Z3);
1570
+ Z3 = Fp.add(t0, t0);
1571
+ t0 = Fp.add(Z3, t0);
1572
+ t0 = Fp.add(t0, t2);
1573
+ t0 = Fp.mul(t0, t3);
1574
+ Y3 = Fp.add(Y3, t0);
1575
+ t2 = Fp.mul(Y1, Z1);
1576
+ t2 = Fp.add(t2, t2);
1577
+ t0 = Fp.mul(t2, t3);
1578
+ X3 = Fp.sub(X3, t0);
1579
+ Z3 = Fp.mul(t2, t1);
1580
+ Z3 = Fp.add(Z3, Z3);
1581
+ Z3 = Fp.add(Z3, Z3);
1582
+ return new Point(X3, Y3, Z3);
1583
+ }
1584
+ // Renes-Costello-Batina exception-free addition formula.
1585
+ // There is 30% faster Jacobian formula, but it is not complete.
1586
+ // https://eprint.iacr.org/2015/1060, algorithm 1
1587
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
1588
+ add(other) {
1589
+ aprjpoint(other);
1590
+ const { px: X1, py: Y1, pz: Z1 } = this;
1591
+ const { px: X2, py: Y2, pz: Z2 } = other;
1592
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
1593
+ const a = CURVE.a;
1594
+ const b3 = Fp.mul(CURVE.b, _3n2);
1595
+ let t0 = Fp.mul(X1, X2);
1596
+ let t1 = Fp.mul(Y1, Y2);
1597
+ let t2 = Fp.mul(Z1, Z2);
1598
+ let t3 = Fp.add(X1, Y1);
1599
+ let t4 = Fp.add(X2, Y2);
1600
+ t3 = Fp.mul(t3, t4);
1601
+ t4 = Fp.add(t0, t1);
1602
+ t3 = Fp.sub(t3, t4);
1603
+ t4 = Fp.add(X1, Z1);
1604
+ let t5 = Fp.add(X2, Z2);
1605
+ t4 = Fp.mul(t4, t5);
1606
+ t5 = Fp.add(t0, t2);
1607
+ t4 = Fp.sub(t4, t5);
1608
+ t5 = Fp.add(Y1, Z1);
1609
+ X3 = Fp.add(Y2, Z2);
1610
+ t5 = Fp.mul(t5, X3);
1611
+ X3 = Fp.add(t1, t2);
1612
+ t5 = Fp.sub(t5, X3);
1613
+ Z3 = Fp.mul(a, t4);
1614
+ X3 = Fp.mul(b3, t2);
1615
+ Z3 = Fp.add(X3, Z3);
1616
+ X3 = Fp.sub(t1, Z3);
1617
+ Z3 = Fp.add(t1, Z3);
1618
+ Y3 = Fp.mul(X3, Z3);
1619
+ t1 = Fp.add(t0, t0);
1620
+ t1 = Fp.add(t1, t0);
1621
+ t2 = Fp.mul(a, t2);
1622
+ t4 = Fp.mul(b3, t4);
1623
+ t1 = Fp.add(t1, t2);
1624
+ t2 = Fp.sub(t0, t2);
1625
+ t2 = Fp.mul(a, t2);
1626
+ t4 = Fp.add(t4, t2);
1627
+ t0 = Fp.mul(t1, t4);
1628
+ Y3 = Fp.add(Y3, t0);
1629
+ t0 = Fp.mul(t5, t4);
1630
+ X3 = Fp.mul(t3, X3);
1631
+ X3 = Fp.sub(X3, t0);
1632
+ t0 = Fp.mul(t3, t1);
1633
+ Z3 = Fp.mul(t5, Z3);
1634
+ Z3 = Fp.add(Z3, t0);
1635
+ return new Point(X3, Y3, Z3);
1636
+ }
1637
+ subtract(other) {
1638
+ return this.add(other.negate());
1639
+ }
1640
+ is0() {
1641
+ return this.equals(Point.ZERO);
1642
+ }
1643
+ wNAF(n) {
1644
+ return wnaf.wNAFCached(this, n, Point.normalizeZ);
1645
+ }
1646
+ /**
1647
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
1648
+ * It's faster, but should only be used when you don't care about
1649
+ * an exposed private key e.g. sig verification, which works over *public* keys.
1650
+ */
1651
+ multiplyUnsafe(sc) {
1652
+ const { endo: endo2, n: N } = CURVE;
1653
+ aInRange("scalar", sc, _0n4, N);
1654
+ const I = Point.ZERO;
1655
+ if (sc === _0n4)
1656
+ return I;
1657
+ if (this.is0() || sc === _1n4)
1658
+ return this;
1659
+ if (!endo2 || wnaf.hasPrecomputes(this))
1660
+ return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);
1661
+ let { k1neg, k1, k2neg, k2 } = endo2.splitScalar(sc);
1662
+ let k1p = I;
1663
+ let k2p = I;
1664
+ let d = this;
1665
+ while (k1 > _0n4 || k2 > _0n4) {
1666
+ if (k1 & _1n4)
1667
+ k1p = k1p.add(d);
1668
+ if (k2 & _1n4)
1669
+ k2p = k2p.add(d);
1670
+ d = d.double();
1671
+ k1 >>= _1n4;
1672
+ k2 >>= _1n4;
1673
+ }
1674
+ if (k1neg)
1675
+ k1p = k1p.negate();
1676
+ if (k2neg)
1677
+ k2p = k2p.negate();
1678
+ k2p = new Point(Fp.mul(k2p.px, endo2.beta), k2p.py, k2p.pz);
1679
+ return k1p.add(k2p);
1680
+ }
1681
+ /**
1682
+ * Constant time multiplication.
1683
+ * Uses wNAF method. Windowed method may be 10% faster,
1684
+ * but takes 2x longer to generate and consumes 2x memory.
1685
+ * Uses precomputes when available.
1686
+ * Uses endomorphism for Koblitz curves.
1687
+ * @param scalar by which the point would be multiplied
1688
+ * @returns New point
1689
+ */
1690
+ multiply(scalar) {
1691
+ const { endo: endo2, n: N } = CURVE;
1692
+ aInRange("scalar", scalar, _1n4, N);
1693
+ let point, fake;
1694
+ if (endo2) {
1695
+ const { k1neg, k1, k2neg, k2 } = endo2.splitScalar(scalar);
1696
+ let { p: k1p, f: f1p } = this.wNAF(k1);
1697
+ let { p: k2p, f: f2p } = this.wNAF(k2);
1698
+ k1p = wnaf.constTimeNegate(k1neg, k1p);
1699
+ k2p = wnaf.constTimeNegate(k2neg, k2p);
1700
+ k2p = new Point(Fp.mul(k2p.px, endo2.beta), k2p.py, k2p.pz);
1701
+ point = k1p.add(k2p);
1702
+ fake = f1p.add(f2p);
1703
+ } else {
1704
+ const { p, f } = this.wNAF(scalar);
1705
+ point = p;
1706
+ fake = f;
1707
+ }
1708
+ return Point.normalizeZ([point, fake])[0];
1709
+ }
1710
+ /**
1711
+ * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
1712
+ * Not using Strauss-Shamir trick: precomputation tables are faster.
1713
+ * The trick could be useful if both P and Q are not G (not in our case).
1714
+ * @returns non-zero affine point
1715
+ */
1716
+ multiplyAndAddUnsafe(Q, a, b) {
1717
+ const G = Point.BASE;
1718
+ const mul = (P, a2) => a2 === _0n4 || a2 === _1n4 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2);
1719
+ const sum = mul(this, a).add(mul(Q, b));
1720
+ return sum.is0() ? void 0 : sum;
1721
+ }
1722
+ // Converts Projective point to affine (x, y) coordinates.
1723
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
1724
+ // (x, y, z) ∋ (x=x/z, y=y/z)
1725
+ toAffine(iz) {
1726
+ return toAffineMemo(this, iz);
1727
+ }
1728
+ isTorsionFree() {
1729
+ const { h: cofactor, isTorsionFree } = CURVE;
1730
+ if (cofactor === _1n4)
1731
+ return true;
1732
+ if (isTorsionFree)
1733
+ return isTorsionFree(Point, this);
1734
+ throw new Error("isTorsionFree() has not been declared for the elliptic curve");
1735
+ }
1736
+ clearCofactor() {
1737
+ const { h: cofactor, clearCofactor } = CURVE;
1738
+ if (cofactor === _1n4)
1739
+ return this;
1740
+ if (clearCofactor)
1741
+ return clearCofactor(Point, this);
1742
+ return this.multiplyUnsafe(CURVE.h);
1743
+ }
1744
+ toRawBytes(isCompressed = true) {
1745
+ abool("isCompressed", isCompressed);
1746
+ this.assertValidity();
1747
+ return toBytes3(Point, this, isCompressed);
1748
+ }
1749
+ toHex(isCompressed = true) {
1750
+ abool("isCompressed", isCompressed);
1751
+ return bytesToHex(this.toRawBytes(isCompressed));
1752
+ }
1753
+ }
1754
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
1755
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
1756
+ const { endo, nBitLength } = CURVE;
1757
+ const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);
1758
+ return {
1759
+ CURVE,
1760
+ ProjectivePoint: Point,
1761
+ normPrivateKeyToScalar,
1762
+ weierstrassEquation,
1763
+ isWithinCurveOrder
1764
+ };
1765
+ }
1766
+ function validateOpts(curve) {
1767
+ const opts = validateBasic(curve);
1768
+ validateObject(opts, {
1769
+ hash: "hash",
1770
+ hmac: "function",
1771
+ randomBytes: "function"
1772
+ }, {
1773
+ bits2int: "function",
1774
+ bits2int_modN: "function",
1775
+ lowS: "boolean"
1776
+ });
1777
+ return Object.freeze({ lowS: true, ...opts });
1778
+ }
1779
+ function weierstrass(curveDef) {
1780
+ const CURVE = validateOpts(curveDef);
1781
+ const { Fp, n: CURVE_ORDER, nByteLength, nBitLength } = CURVE;
1782
+ const compressedLen = Fp.BYTES + 1;
1783
+ const uncompressedLen = 2 * Fp.BYTES + 1;
1784
+ function modN(a) {
1785
+ return mod(a, CURVE_ORDER);
1786
+ }
1787
+ function invN(a) {
1788
+ return invert(a, CURVE_ORDER);
1789
+ }
1790
+ const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({
1791
+ ...CURVE,
1792
+ toBytes(_c, point, isCompressed) {
1793
+ const a = point.toAffine();
1794
+ const x = Fp.toBytes(a.x);
1795
+ const cat = concatBytes2;
1796
+ abool("isCompressed", isCompressed);
1797
+ if (isCompressed) {
1798
+ return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
1799
+ } else {
1800
+ return cat(Uint8Array.from([4]), x, Fp.toBytes(a.y));
1801
+ }
1802
+ },
1803
+ fromBytes(bytes) {
1804
+ const len = bytes.length;
1805
+ const head = bytes[0];
1806
+ const tail = bytes.subarray(1);
1807
+ if (len === compressedLen && (head === 2 || head === 3)) {
1808
+ const x = bytesToNumberBE(tail);
1809
+ if (!inRange(x, _1n4, Fp.ORDER))
1810
+ throw new Error("Point is not on curve");
1811
+ const y2 = weierstrassEquation(x);
1812
+ let y;
1813
+ try {
1814
+ y = Fp.sqrt(y2);
1815
+ } catch (sqrtError) {
1816
+ const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : "";
1817
+ throw new Error("Point is not on curve" + suffix);
1818
+ }
1819
+ const isYOdd = (y & _1n4) === _1n4;
1820
+ const isHeadOdd = (head & 1) === 1;
1821
+ if (isHeadOdd !== isYOdd)
1822
+ y = Fp.neg(y);
1823
+ return { x, y };
1824
+ } else if (len === uncompressedLen && head === 4) {
1825
+ const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
1826
+ const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
1827
+ return { x, y };
1828
+ } else {
1829
+ const cl = compressedLen;
1830
+ const ul = uncompressedLen;
1831
+ throw new Error("invalid Point, expected length of " + cl + ", or uncompressed " + ul + ", got " + len);
1832
+ }
1833
+ }
1834
+ });
1835
+ function isBiggerThanHalfOrder(number) {
1836
+ const HALF = CURVE_ORDER >> _1n4;
1837
+ return number > HALF;
1838
+ }
1839
+ function normalizeS(s) {
1840
+ return isBiggerThanHalfOrder(s) ? modN(-s) : s;
1841
+ }
1842
+ const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
1843
+ class Signature {
1844
+ constructor(r, s, recovery) {
1845
+ aInRange("r", r, _1n4, CURVE_ORDER);
1846
+ aInRange("s", s, _1n4, CURVE_ORDER);
1847
+ this.r = r;
1848
+ this.s = s;
1849
+ if (recovery != null)
1850
+ this.recovery = recovery;
1851
+ Object.freeze(this);
1852
+ }
1853
+ // pair (bytes of r, bytes of s)
1854
+ static fromCompact(hex) {
1855
+ const l = nByteLength;
1856
+ hex = ensureBytes("compactSignature", hex, l * 2);
1857
+ return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
1858
+ }
1859
+ // DER encoded ECDSA signature
1860
+ // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
1861
+ static fromDER(hex) {
1862
+ const { r, s } = DER.toSig(ensureBytes("DER", hex));
1863
+ return new Signature(r, s);
1864
+ }
1865
+ /**
1866
+ * @todo remove
1867
+ * @deprecated
1868
+ */
1869
+ assertValidity() {
1870
+ }
1871
+ addRecoveryBit(recovery) {
1872
+ return new Signature(this.r, this.s, recovery);
1873
+ }
1874
+ recoverPublicKey(msgHash) {
1875
+ const { r, s, recovery: rec } = this;
1876
+ const h = bits2int_modN(ensureBytes("msgHash", msgHash));
1877
+ if (rec == null || ![0, 1, 2, 3].includes(rec))
1878
+ throw new Error("recovery id invalid");
1879
+ const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
1880
+ if (radj >= Fp.ORDER)
1881
+ throw new Error("recovery id 2 or 3 invalid");
1882
+ const prefix = (rec & 1) === 0 ? "02" : "03";
1883
+ const R = Point.fromHex(prefix + numToSizedHex(radj, Fp.BYTES));
1884
+ const ir = invN(radj);
1885
+ const u1 = modN(-h * ir);
1886
+ const u2 = modN(s * ir);
1887
+ const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);
1888
+ if (!Q)
1889
+ throw new Error("point at infinify");
1890
+ Q.assertValidity();
1891
+ return Q;
1892
+ }
1893
+ // Signatures should be low-s, to prevent malleability.
1894
+ hasHighS() {
1895
+ return isBiggerThanHalfOrder(this.s);
1896
+ }
1897
+ normalizeS() {
1898
+ return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
1899
+ }
1900
+ // DER-encoded
1901
+ toDERRawBytes() {
1902
+ return hexToBytes(this.toDERHex());
1903
+ }
1904
+ toDERHex() {
1905
+ return DER.hexFromSig(this);
1906
+ }
1907
+ // padded bytes of r, then padded bytes of s
1908
+ toCompactRawBytes() {
1909
+ return hexToBytes(this.toCompactHex());
1910
+ }
1911
+ toCompactHex() {
1912
+ const l = nByteLength;
1913
+ return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);
1914
+ }
1915
+ }
1916
+ const utils = {
1917
+ isValidPrivateKey(privateKey) {
1918
+ try {
1919
+ normPrivateKeyToScalar(privateKey);
1920
+ return true;
1921
+ } catch (error) {
1922
+ return false;
1923
+ }
1924
+ },
1925
+ normPrivateKeyToScalar,
1926
+ /**
1927
+ * Produces cryptographically secure private key from random of size
1928
+ * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
1929
+ */
1930
+ randomPrivateKey: () => {
1931
+ const length = getMinHashLength(CURVE.n);
1932
+ return mapHashToField(CURVE.randomBytes(length), CURVE.n);
1933
+ },
1934
+ /**
1935
+ * Creates precompute table for an arbitrary EC point. Makes point "cached".
1936
+ * Allows to massively speed-up `point.multiply(scalar)`.
1937
+ * @returns cached point
1938
+ * @example
1939
+ * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
1940
+ * fast.multiply(privKey); // much faster ECDH now
1941
+ */
1942
+ precompute(windowSize = 8, point = Point.BASE) {
1943
+ point._setWindowSize(windowSize);
1944
+ point.multiply(BigInt(3));
1945
+ return point;
1946
+ }
1947
+ };
1948
+ function getPublicKey(privateKey, isCompressed = true) {
1949
+ return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
1950
+ }
1951
+ function isProbPub(item) {
1952
+ if (typeof item === "bigint")
1953
+ return false;
1954
+ if (item instanceof Point)
1955
+ return true;
1956
+ const arr = ensureBytes("key", item);
1957
+ const len = arr.length;
1958
+ const fpl = Fp.BYTES;
1959
+ const compLen = fpl + 1;
1960
+ const uncompLen = 2 * fpl + 1;
1961
+ if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {
1962
+ return void 0;
1963
+ } else {
1964
+ return len === compLen || len === uncompLen;
1965
+ }
1966
+ }
1967
+ function getSharedSecret(privateA, publicB, isCompressed = true) {
1968
+ if (isProbPub(privateA) === true)
1969
+ throw new Error("first arg must be private key");
1970
+ if (isProbPub(publicB) === false)
1971
+ throw new Error("second arg must be public key");
1972
+ const b = Point.fromHex(publicB);
1973
+ return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
1974
+ }
1975
+ const bits2int = CURVE.bits2int || function(bytes) {
1976
+ if (bytes.length > 8192)
1977
+ throw new Error("input is too large");
1978
+ const num = bytesToNumberBE(bytes);
1979
+ const delta = bytes.length * 8 - nBitLength;
1980
+ return delta > 0 ? num >> BigInt(delta) : num;
1981
+ };
1982
+ const bits2int_modN = CURVE.bits2int_modN || function(bytes) {
1983
+ return modN(bits2int(bytes));
1984
+ };
1985
+ const ORDER_MASK = bitMask(nBitLength);
1986
+ function int2octets(num) {
1987
+ aInRange("num < 2^" + nBitLength, num, _0n4, ORDER_MASK);
1988
+ return numberToBytesBE(num, nByteLength);
1989
+ }
1990
+ function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
1991
+ if (["recovered", "canonical"].some((k) => k in opts))
1992
+ throw new Error("sign() legacy options not supported");
1993
+ const { hash, randomBytes: randomBytes2 } = CURVE;
1994
+ let { lowS, prehash, extraEntropy: ent } = opts;
1995
+ if (lowS == null)
1996
+ lowS = true;
1997
+ msgHash = ensureBytes("msgHash", msgHash);
1998
+ validateSigVerOpts(opts);
1999
+ if (prehash)
2000
+ msgHash = ensureBytes("prehashed msgHash", hash(msgHash));
2001
+ const h1int = bits2int_modN(msgHash);
2002
+ const d = normPrivateKeyToScalar(privateKey);
2003
+ const seedArgs = [int2octets(d), int2octets(h1int)];
2004
+ if (ent != null && ent !== false) {
2005
+ const e = ent === true ? randomBytes2(Fp.BYTES) : ent;
2006
+ seedArgs.push(ensureBytes("extraEntropy", e));
2007
+ }
2008
+ const seed = concatBytes2(...seedArgs);
2009
+ const m = h1int;
2010
+ function k2sig(kBytes) {
2011
+ const k = bits2int(kBytes);
2012
+ if (!isWithinCurveOrder(k))
2013
+ return;
2014
+ const ik = invN(k);
2015
+ const q = Point.BASE.multiply(k).toAffine();
2016
+ const r = modN(q.x);
2017
+ if (r === _0n4)
2018
+ return;
2019
+ const s = modN(ik * modN(m + r * d));
2020
+ if (s === _0n4)
2021
+ return;
2022
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
2023
+ let normS = s;
2024
+ if (lowS && isBiggerThanHalfOrder(s)) {
2025
+ normS = normalizeS(s);
2026
+ recovery ^= 1;
2027
+ }
2028
+ return new Signature(r, normS, recovery);
2029
+ }
2030
+ return { seed, k2sig };
2031
+ }
2032
+ const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
2033
+ const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
2034
+ function sign2(msgHash, privKey, opts = defaultSigOpts) {
2035
+ const { seed, k2sig } = prepSig(msgHash, privKey, opts);
2036
+ const C = CURVE;
2037
+ const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
2038
+ return drbg(seed, k2sig);
2039
+ }
2040
+ Point.BASE._setWindowSize(8);
2041
+ function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
2042
+ const sg = signature;
2043
+ msgHash = ensureBytes("msgHash", msgHash);
2044
+ publicKey = ensureBytes("publicKey", publicKey);
2045
+ const { lowS, prehash, format } = opts;
2046
+ validateSigVerOpts(opts);
2047
+ if ("strict" in opts)
2048
+ throw new Error("options.strict was renamed to lowS");
2049
+ if (format !== void 0 && format !== "compact" && format !== "der")
2050
+ throw new Error("format must be compact or der");
2051
+ const isHex2 = typeof sg === "string" || isBytes2(sg);
2052
+ const isObj = !isHex2 && !format && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint";
2053
+ if (!isHex2 && !isObj)
2054
+ throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
2055
+ let _sig = void 0;
2056
+ let P;
2057
+ try {
2058
+ if (isObj)
2059
+ _sig = new Signature(sg.r, sg.s);
2060
+ if (isHex2) {
2061
+ try {
2062
+ if (format !== "compact")
2063
+ _sig = Signature.fromDER(sg);
2064
+ } catch (derError) {
2065
+ if (!(derError instanceof DER.Err))
2066
+ throw derError;
2067
+ }
2068
+ if (!_sig && format !== "der")
2069
+ _sig = Signature.fromCompact(sg);
2070
+ }
2071
+ P = Point.fromHex(publicKey);
2072
+ } catch (error) {
2073
+ return false;
2074
+ }
2075
+ if (!_sig)
2076
+ return false;
2077
+ if (lowS && _sig.hasHighS())
2078
+ return false;
2079
+ if (prehash)
2080
+ msgHash = CURVE.hash(msgHash);
2081
+ const { r, s } = _sig;
2082
+ const h = bits2int_modN(msgHash);
2083
+ const is = invN(s);
2084
+ const u1 = modN(h * is);
2085
+ const u2 = modN(r * is);
2086
+ const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine();
2087
+ if (!R)
2088
+ return false;
2089
+ const v = modN(R.x);
2090
+ return v === r;
2091
+ }
2092
+ return {
2093
+ CURVE,
2094
+ getPublicKey,
2095
+ getSharedSecret,
2096
+ sign: sign2,
2097
+ verify,
2098
+ ProjectivePoint: Point,
2099
+ Signature,
2100
+ utils
2101
+ };
2102
+ }
2103
+
2104
+ // node_modules/@noble/curves/esm/_shortw_utils.js
2105
+ function getHash(hash) {
2106
+ return {
2107
+ hash,
2108
+ hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),
2109
+ randomBytes
2110
+ };
2111
+ }
2112
+ function createCurve(curveDef, defHash) {
2113
+ const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
2114
+ return { ...create(defHash), create };
2115
+ }
2116
+
2117
+ // node_modules/@noble/curves/esm/secp256k1.js
2118
+ var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f");
2119
+ var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
2120
+ var _0n5 = BigInt(0);
2121
+ var _1n5 = BigInt(1);
2122
+ var _2n3 = BigInt(2);
2123
+ var divNearest = (a, b) => (a + b / _2n3) / b;
2124
+ function sqrtMod(y) {
2125
+ const P = secp256k1P;
2126
+ const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
2127
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
2128
+ const b2 = y * y * y % P;
2129
+ const b3 = b2 * b2 * y % P;
2130
+ const b6 = pow2(b3, _3n3, P) * b3 % P;
2131
+ const b9 = pow2(b6, _3n3, P) * b3 % P;
2132
+ const b11 = pow2(b9, _2n3, P) * b2 % P;
2133
+ const b22 = pow2(b11, _11n, P) * b11 % P;
2134
+ const b44 = pow2(b22, _22n, P) * b22 % P;
2135
+ const b88 = pow2(b44, _44n, P) * b44 % P;
2136
+ const b176 = pow2(b88, _88n, P) * b88 % P;
2137
+ const b220 = pow2(b176, _44n, P) * b44 % P;
2138
+ const b223 = pow2(b220, _3n3, P) * b3 % P;
2139
+ const t1 = pow2(b223, _23n, P) * b22 % P;
2140
+ const t2 = pow2(t1, _6n, P) * b2 % P;
2141
+ const root = pow2(t2, _2n3, P);
2142
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
2143
+ throw new Error("Cannot find square root");
2144
+ return root;
2145
+ }
2146
+ var Fpk1 = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod });
2147
+ var secp256k1 = createCurve({
2148
+ a: _0n5,
2149
+ b: BigInt(7),
2150
+ Fp: Fpk1,
2151
+ n: secp256k1N,
2152
+ Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),
2153
+ Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),
2154
+ h: BigInt(1),
2155
+ lowS: true,
2156
+ // Allow only low-S signatures by default in sign() and verify()
2157
+ endo: {
2158
+ // Endomorphism, see above
2159
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
2160
+ splitScalar: (k) => {
2161
+ const n = secp256k1N;
2162
+ const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15");
2163
+ const b1 = -_1n5 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3");
2164
+ const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");
2165
+ const b2 = a1;
2166
+ const POW_2_128 = BigInt("0x100000000000000000000000000000000");
2167
+ const c1 = divNearest(b2 * k, n);
2168
+ const c2 = divNearest(-b1 * k, n);
2169
+ let k1 = mod(k - c1 * a1 - c2 * a2, n);
2170
+ let k2 = mod(-c1 * b1 - c2 * b2, n);
2171
+ const k1neg = k1 > POW_2_128;
2172
+ const k2neg = k2 > POW_2_128;
2173
+ if (k1neg)
2174
+ k1 = n - k1;
2175
+ if (k2neg)
2176
+ k2 = n - k2;
2177
+ if (k1 > POW_2_128 || k2 > POW_2_128) {
2178
+ throw new Error("splitScalar: Endomorphism failed, k=" + k);
2179
+ }
2180
+ return { k1neg, k1, k2neg, k2 };
2181
+ }
2182
+ }
2183
+ }, sha256);
2184
+
2185
+ // node_modules/viem/_esm/errors/version.js
2186
+ var version = "2.53.1";
2187
+
2188
+ // node_modules/viem/_esm/errors/base.js
2189
+ var errorConfig = {
2190
+ getDocsUrl: ({ docsBaseUrl, docsPath = "", docsSlug }) => docsPath ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath}${docsSlug ? `#${docsSlug}` : ""}` : void 0,
2191
+ version: `viem@${version}`
2192
+ };
2193
+ var BaseError = class _BaseError extends Error {
2194
+ constructor(shortMessage, args2 = {}) {
2195
+ const details = (() => {
2196
+ if (args2.cause instanceof _BaseError)
2197
+ return args2.cause.details;
2198
+ if (args2.cause?.message)
2199
+ return args2.cause.message;
2200
+ return args2.details;
2201
+ })();
2202
+ const docsPath = (() => {
2203
+ if (args2.cause instanceof _BaseError)
2204
+ return args2.cause.docsPath || args2.docsPath;
2205
+ return args2.docsPath;
2206
+ })();
2207
+ const docsUrl = errorConfig.getDocsUrl?.({ ...args2, docsPath });
2208
+ const message = [
2209
+ shortMessage || "An error occurred.",
2210
+ "",
2211
+ ...args2.metaMessages ? [...args2.metaMessages, ""] : [],
2212
+ ...docsUrl ? [`Docs: ${docsUrl}`] : [],
2213
+ ...details ? [`Details: ${details}`] : [],
2214
+ ...errorConfig.version ? [`Version: ${errorConfig.version}`] : []
2215
+ ].join("\n");
2216
+ super(message, args2.cause ? { cause: args2.cause } : void 0);
2217
+ Object.defineProperty(this, "details", {
2218
+ enumerable: true,
2219
+ configurable: true,
2220
+ writable: true,
2221
+ value: void 0
2222
+ });
2223
+ Object.defineProperty(this, "docsPath", {
2224
+ enumerable: true,
2225
+ configurable: true,
2226
+ writable: true,
2227
+ value: void 0
2228
+ });
2229
+ Object.defineProperty(this, "metaMessages", {
2230
+ enumerable: true,
2231
+ configurable: true,
2232
+ writable: true,
2233
+ value: void 0
2234
+ });
2235
+ Object.defineProperty(this, "shortMessage", {
2236
+ enumerable: true,
2237
+ configurable: true,
2238
+ writable: true,
2239
+ value: void 0
2240
+ });
2241
+ Object.defineProperty(this, "version", {
2242
+ enumerable: true,
2243
+ configurable: true,
2244
+ writable: true,
2245
+ value: void 0
2246
+ });
2247
+ Object.defineProperty(this, "name", {
2248
+ enumerable: true,
2249
+ configurable: true,
2250
+ writable: true,
2251
+ value: "BaseError"
2252
+ });
2253
+ this.details = details;
2254
+ this.docsPath = docsPath;
2255
+ this.metaMessages = args2.metaMessages;
2256
+ this.name = args2.name ?? this.name;
2257
+ this.shortMessage = shortMessage;
2258
+ this.version = version;
2259
+ }
2260
+ walk(fn) {
2261
+ return walk(this, fn);
2262
+ }
2263
+ };
2264
+ function walk(err, fn) {
2265
+ if (fn?.(err))
2266
+ return err;
2267
+ if (err && typeof err === "object" && "cause" in err && err.cause !== void 0)
2268
+ return walk(err.cause, fn);
2269
+ return fn ? null : err;
2270
+ }
2271
+
2272
+ // node_modules/viem/_esm/errors/encoding.js
2273
+ var IntegerOutOfRangeError = class extends BaseError {
2274
+ constructor({ max, min, signed, size: size2, value }) {
2275
+ super(`Number "${value}" is not in safe ${size2 ? `${size2 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: "IntegerOutOfRangeError" });
2276
+ }
2277
+ };
2278
+ var SizeOverflowError = class extends BaseError {
2279
+ constructor({ givenSize, maxSize }) {
2280
+ super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: "SizeOverflowError" });
2281
+ }
2282
+ };
2283
+
2284
+ // node_modules/viem/_esm/errors/data.js
2285
+ var SliceOffsetOutOfBoundsError = class extends BaseError {
2286
+ constructor({ offset, position, size: size2 }) {
2287
+ super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset}" is out-of-bounds (size: ${size2}).`, { name: "SliceOffsetOutOfBoundsError" });
2288
+ }
2289
+ };
2290
+ var SizeExceedsPaddingSizeError = class extends BaseError {
2291
+ constructor({ size: size2, targetSize, type }) {
2292
+ super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" });
2293
+ }
2294
+ };
2295
+
2296
+ // node_modules/viem/_esm/utils/data/pad.js
2297
+ function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) {
2298
+ if (typeof hexOrBytes === "string")
2299
+ return padHex(hexOrBytes, { dir, size: size2 });
2300
+ return padBytes(hexOrBytes, { dir, size: size2 });
2301
+ }
2302
+ function padHex(hex_, { dir, size: size2 = 32 } = {}) {
2303
+ if (size2 === null)
2304
+ return hex_;
2305
+ const hex = hex_.replace("0x", "");
2306
+ if (hex.length > size2 * 2)
2307
+ throw new SizeExceedsPaddingSizeError({
2308
+ size: Math.ceil(hex.length / 2),
2309
+ targetSize: size2,
2310
+ type: "hex"
2311
+ });
2312
+ return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size2 * 2, "0")}`;
2313
+ }
2314
+ function padBytes(bytes, { dir, size: size2 = 32 } = {}) {
2315
+ if (size2 === null)
2316
+ return bytes;
2317
+ if (bytes.length > size2)
2318
+ throw new SizeExceedsPaddingSizeError({
2319
+ size: bytes.length,
2320
+ targetSize: size2,
2321
+ type: "bytes"
2322
+ });
2323
+ const paddedBytes = new Uint8Array(size2);
2324
+ for (let i = 0; i < size2; i++) {
2325
+ const padEnd = dir === "right";
2326
+ paddedBytes[padEnd ? i : size2 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
2327
+ }
2328
+ return paddedBytes;
2329
+ }
2330
+
2331
+ // node_modules/viem/_esm/utils/data/isHex.js
2332
+ function isHex(value, { strict = true } = {}) {
2333
+ if (!value)
2334
+ return false;
2335
+ if (typeof value !== "string")
2336
+ return false;
2337
+ return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith("0x");
2338
+ }
2339
+
2340
+ // node_modules/viem/_esm/utils/data/size.js
2341
+ function size(value) {
2342
+ if (isHex(value, { strict: false }))
2343
+ return Math.ceil((value.length - 2) / 2);
2344
+ return value.length;
2345
+ }
2346
+
2347
+ // node_modules/viem/_esm/utils/data/trim.js
2348
+ function trim(hexOrBytes, { dir = "left" } = {}) {
2349
+ let data = typeof hexOrBytes === "string" ? hexOrBytes.replace("0x", "") : hexOrBytes;
2350
+ let sliceLength = 0;
2351
+ for (let i = 0; i < data.length - 1; i++) {
2352
+ if (data[dir === "left" ? i : data.length - i - 1].toString() === "0")
2353
+ sliceLength++;
2354
+ else
2355
+ break;
2356
+ }
2357
+ data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength);
2358
+ if (typeof hexOrBytes === "string") {
2359
+ if (data.length === 1 && dir === "right")
2360
+ data = `${data}0`;
2361
+ return `0x${data.length % 2 === 1 ? `0${data}` : data}`;
2362
+ }
2363
+ return data;
2364
+ }
2365
+
2366
+ // node_modules/viem/_esm/utils/encoding/toBytes.js
2367
+ var encoder = /* @__PURE__ */ new TextEncoder();
2368
+ function toBytes2(value, opts = {}) {
2369
+ if (typeof value === "number" || typeof value === "bigint")
2370
+ return numberToBytes(value, opts);
2371
+ if (typeof value === "boolean")
2372
+ return boolToBytes(value, opts);
2373
+ if (isHex(value))
2374
+ return hexToBytes2(value, opts);
2375
+ return stringToBytes(value, opts);
2376
+ }
2377
+ function boolToBytes(value, opts = {}) {
2378
+ const bytes = new Uint8Array(1);
2379
+ bytes[0] = Number(value);
2380
+ if (typeof opts.size === "number") {
2381
+ assertSize(bytes, { size: opts.size });
2382
+ return pad(bytes, { size: opts.size });
2383
+ }
2384
+ return bytes;
2385
+ }
2386
+ var charCodeMap = {
2387
+ zero: 48,
2388
+ nine: 57,
2389
+ A: 65,
2390
+ F: 70,
2391
+ a: 97,
2392
+ f: 102
2393
+ };
2394
+ function charCodeToBase16(char) {
2395
+ if (char >= charCodeMap.zero && char <= charCodeMap.nine)
2396
+ return char - charCodeMap.zero;
2397
+ if (char >= charCodeMap.A && char <= charCodeMap.F)
2398
+ return char - (charCodeMap.A - 10);
2399
+ if (char >= charCodeMap.a && char <= charCodeMap.f)
2400
+ return char - (charCodeMap.a - 10);
2401
+ return void 0;
2402
+ }
2403
+ function hexToBytes2(hex_, opts = {}) {
2404
+ let hex = hex_;
2405
+ if (opts.size) {
2406
+ assertSize(hex, { size: opts.size });
2407
+ hex = pad(hex, { dir: "right", size: opts.size });
2408
+ }
2409
+ let hexString = hex.slice(2);
2410
+ if (hexString.length % 2)
2411
+ hexString = `0${hexString}`;
2412
+ const length = hexString.length / 2;
2413
+ const bytes = new Uint8Array(length);
2414
+ for (let index = 0, j = 0; index < length; index++) {
2415
+ const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++));
2416
+ const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++));
2417
+ if (nibbleLeft === void 0 || nibbleRight === void 0) {
2418
+ throw new BaseError(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`);
2419
+ }
2420
+ bytes[index] = nibbleLeft * 16 + nibbleRight;
2421
+ }
2422
+ return bytes;
2423
+ }
2424
+ function numberToBytes(value, opts) {
2425
+ const hex = numberToHex(value, opts);
2426
+ return hexToBytes2(hex);
2427
+ }
2428
+ function stringToBytes(value, opts = {}) {
2429
+ const bytes = encoder.encode(value);
2430
+ if (typeof opts.size === "number") {
2431
+ assertSize(bytes, { size: opts.size });
2432
+ return pad(bytes, { dir: "right", size: opts.size });
2433
+ }
2434
+ return bytes;
2435
+ }
2436
+
2437
+ // node_modules/viem/_esm/utils/encoding/fromHex.js
2438
+ function assertSize(hexOrBytes, { size: size2 }) {
2439
+ if (size(hexOrBytes) > size2)
2440
+ throw new SizeOverflowError({
2441
+ givenSize: size(hexOrBytes),
2442
+ maxSize: size2
2443
+ });
2444
+ }
2445
+ function hexToBigInt(hex, opts = {}) {
2446
+ const { signed } = opts;
2447
+ if (opts.size)
2448
+ assertSize(hex, { size: opts.size });
2449
+ const value = BigInt(hex);
2450
+ if (!signed)
2451
+ return value;
2452
+ const size2 = (hex.length - 2) / 2;
2453
+ const max = (1n << BigInt(size2) * 8n - 1n) - 1n;
2454
+ if (value <= max)
2455
+ return value;
2456
+ return value - BigInt(`0x${"f".padStart(size2 * 2, "f")}`) - 1n;
2457
+ }
2458
+ function hexToNumber2(hex, opts = {}) {
2459
+ const value = hexToBigInt(hex, opts);
2460
+ const number = Number(value);
2461
+ if (!Number.isSafeInteger(number))
2462
+ throw new IntegerOutOfRangeError({
2463
+ max: `${Number.MAX_SAFE_INTEGER}`,
2464
+ min: `${Number.MIN_SAFE_INTEGER}`,
2465
+ signed: opts.signed,
2466
+ size: opts.size,
2467
+ value: `${value}n`
2468
+ });
2469
+ return number;
2470
+ }
2471
+
2472
+ // node_modules/viem/_esm/utils/encoding/toHex.js
2473
+ var hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0"));
2474
+ function toHex(value, opts = {}) {
2475
+ if (typeof value === "number" || typeof value === "bigint")
2476
+ return numberToHex(value, opts);
2477
+ if (typeof value === "string") {
2478
+ return stringToHex(value, opts);
2479
+ }
2480
+ if (typeof value === "boolean")
2481
+ return boolToHex(value, opts);
2482
+ return bytesToHex2(value, opts);
2483
+ }
2484
+ function boolToHex(value, opts = {}) {
2485
+ const hex = `0x${Number(value)}`;
2486
+ if (typeof opts.size === "number") {
2487
+ assertSize(hex, { size: opts.size });
2488
+ return pad(hex, { size: opts.size });
2489
+ }
2490
+ return hex;
2491
+ }
2492
+ function bytesToHex2(value, opts = {}) {
2493
+ let string = "";
2494
+ for (let i = 0; i < value.length; i++) {
2495
+ string += hexes2[value[i]];
2496
+ }
2497
+ const hex = `0x${string}`;
2498
+ if (typeof opts.size === "number") {
2499
+ assertSize(hex, { size: opts.size });
2500
+ return pad(hex, { dir: "right", size: opts.size });
2501
+ }
2502
+ return hex;
2503
+ }
2504
+ function numberToHex(value_, opts = {}) {
2505
+ const { signed, size: size2 } = opts;
2506
+ const value = BigInt(value_);
2507
+ let maxValue;
2508
+ if (size2) {
2509
+ if (signed)
2510
+ maxValue = (1n << BigInt(size2) * 8n - 1n) - 1n;
2511
+ else
2512
+ maxValue = 2n ** (BigInt(size2) * 8n) - 1n;
2513
+ } else if (typeof value_ === "number") {
2514
+ maxValue = BigInt(Number.MAX_SAFE_INTEGER);
2515
+ }
2516
+ const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0;
2517
+ if (maxValue && value > maxValue || value < minValue) {
2518
+ const suffix = typeof value_ === "bigint" ? "n" : "";
2519
+ throw new IntegerOutOfRangeError({
2520
+ max: maxValue ? `${maxValue}${suffix}` : void 0,
2521
+ min: `${minValue}${suffix}`,
2522
+ signed,
2523
+ size: size2,
2524
+ value: `${value_}${suffix}`
2525
+ });
2526
+ }
2527
+ const hex = `0x${(signed && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`;
2528
+ if (size2)
2529
+ return pad(hex, { size: size2 });
2530
+ return hex;
2531
+ }
2532
+ var encoder2 = /* @__PURE__ */ new TextEncoder();
2533
+ function stringToHex(value_, opts = {}) {
2534
+ const value = encoder2.encode(value_);
2535
+ return bytesToHex2(value, opts);
2536
+ }
2537
+
2538
+ // node_modules/viem/_esm/utils/lru.js
2539
+ var LruMap = class extends Map {
2540
+ constructor(size2) {
2541
+ super();
2542
+ Object.defineProperty(this, "maxSize", {
2543
+ enumerable: true,
2544
+ configurable: true,
2545
+ writable: true,
2546
+ value: void 0
2547
+ });
2548
+ this.maxSize = size2;
2549
+ }
2550
+ get(key) {
2551
+ const value = super.get(key);
2552
+ if (super.has(key)) {
2553
+ super.delete(key);
2554
+ super.set(key, value);
2555
+ }
2556
+ return value;
2557
+ }
2558
+ set(key, value) {
2559
+ if (super.has(key))
2560
+ super.delete(key);
2561
+ super.set(key, value);
2562
+ if (this.maxSize && this.size > this.maxSize) {
2563
+ const firstKey = super.keys().next().value;
2564
+ if (firstKey !== void 0)
2565
+ super.delete(firstKey);
2566
+ }
2567
+ return this;
2568
+ }
2569
+ };
2570
+
2571
+ // node_modules/viem/_esm/utils/signature/serializeSignature.js
2572
+ function serializeSignature({ r, s, to = "hex", v, yParity }) {
2573
+ const yParity_ = (() => {
2574
+ if (yParity === 0 || yParity === 1)
2575
+ return yParity;
2576
+ if (v && (v === 27n || v === 28n || v >= 35n))
2577
+ return v % 2n === 0n ? 1 : 0;
2578
+ throw new Error("Invalid `v` or `yParity` value");
2579
+ })();
2580
+ const signature = `0x${new secp256k1.Signature(hexToBigInt(r), hexToBigInt(s)).toCompactHex()}${yParity_ === 0 ? "1b" : "1c"}`;
2581
+ if (to === "hex")
2582
+ return signature;
2583
+ return hexToBytes2(signature);
2584
+ }
2585
+
2586
+ // node_modules/viem/_esm/errors/address.js
2587
+ var InvalidAddressError = class extends BaseError {
2588
+ constructor({ address }) {
2589
+ super(`Address "${address}" is invalid.`, {
2590
+ metaMessages: [
2591
+ "- Address must be a hex value of 20 bytes (40 hex characters).",
2592
+ "- Address must match its checksum counterpart."
2593
+ ],
2594
+ name: "InvalidAddressError"
2595
+ });
2596
+ }
2597
+ };
2598
+
2599
+ // node_modules/@noble/hashes/esm/sha3.js
2600
+ var _0n6 = BigInt(0);
2601
+ var _1n6 = BigInt(1);
2602
+ var _2n4 = BigInt(2);
2603
+ var _7n = BigInt(7);
2604
+ var _256n = BigInt(256);
2605
+ var _0x71n = BigInt(113);
2606
+ var SHA3_PI = [];
2607
+ var SHA3_ROTL = [];
2608
+ var _SHA3_IOTA = [];
2609
+ for (let round = 0, R = _1n6, x = 1, y = 0; round < 24; round++) {
2610
+ [x, y] = [y, (2 * x + 3 * y) % 5];
2611
+ SHA3_PI.push(2 * (5 * y + x));
2612
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
2613
+ let t = _0n6;
2614
+ for (let j = 0; j < 7; j++) {
2615
+ R = (R << _1n6 ^ (R >> _7n) * _0x71n) % _256n;
2616
+ if (R & _2n4)
2617
+ t ^= _1n6 << (_1n6 << /* @__PURE__ */ BigInt(j)) - _1n6;
2618
+ }
2619
+ _SHA3_IOTA.push(t);
2620
+ }
2621
+ var IOTAS = split(_SHA3_IOTA, true);
2622
+ var SHA3_IOTA_H = IOTAS[0];
2623
+ var SHA3_IOTA_L = IOTAS[1];
2624
+ var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
2625
+ var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
2626
+ function keccakP(s, rounds = 24) {
2627
+ const B = new Uint32Array(5 * 2);
2628
+ for (let round = 24 - rounds; round < 24; round++) {
2629
+ for (let x = 0; x < 10; x++)
2630
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
2631
+ for (let x = 0; x < 10; x += 2) {
2632
+ const idx1 = (x + 8) % 10;
2633
+ const idx0 = (x + 2) % 10;
2634
+ const B0 = B[idx0];
2635
+ const B1 = B[idx0 + 1];
2636
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
2637
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
2638
+ for (let y = 0; y < 50; y += 10) {
2639
+ s[x + y] ^= Th;
2640
+ s[x + y + 1] ^= Tl;
2641
+ }
2642
+ }
2643
+ let curH = s[2];
2644
+ let curL = s[3];
2645
+ for (let t = 0; t < 24; t++) {
2646
+ const shift = SHA3_ROTL[t];
2647
+ const Th = rotlH(curH, curL, shift);
2648
+ const Tl = rotlL(curH, curL, shift);
2649
+ const PI = SHA3_PI[t];
2650
+ curH = s[PI];
2651
+ curL = s[PI + 1];
2652
+ s[PI] = Th;
2653
+ s[PI + 1] = Tl;
2654
+ }
2655
+ for (let y = 0; y < 50; y += 10) {
2656
+ for (let x = 0; x < 10; x++)
2657
+ B[x] = s[y + x];
2658
+ for (let x = 0; x < 10; x++)
2659
+ s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
2660
+ }
2661
+ s[0] ^= SHA3_IOTA_H[round];
2662
+ s[1] ^= SHA3_IOTA_L[round];
2663
+ }
2664
+ clean(B);
2665
+ }
2666
+ var Keccak = class _Keccak extends Hash {
2667
+ // NOTE: we accept arguments in bytes instead of bits here.
2668
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
2669
+ super();
2670
+ this.pos = 0;
2671
+ this.posOut = 0;
2672
+ this.finished = false;
2673
+ this.destroyed = false;
2674
+ this.enableXOF = false;
2675
+ this.blockLen = blockLen;
2676
+ this.suffix = suffix;
2677
+ this.outputLen = outputLen;
2678
+ this.enableXOF = enableXOF;
2679
+ this.rounds = rounds;
2680
+ anumber(outputLen);
2681
+ if (!(0 < blockLen && blockLen < 200))
2682
+ throw new Error("only keccak-f1600 function is supported");
2683
+ this.state = new Uint8Array(200);
2684
+ this.state32 = u32(this.state);
2685
+ }
2686
+ clone() {
2687
+ return this._cloneInto();
2688
+ }
2689
+ keccak() {
2690
+ swap32IfBE(this.state32);
2691
+ keccakP(this.state32, this.rounds);
2692
+ swap32IfBE(this.state32);
2693
+ this.posOut = 0;
2694
+ this.pos = 0;
2695
+ }
2696
+ update(data) {
2697
+ aexists(this);
2698
+ data = toBytes(data);
2699
+ abytes(data);
2700
+ const { blockLen, state } = this;
2701
+ const len = data.length;
2702
+ for (let pos = 0; pos < len; ) {
2703
+ const take = Math.min(blockLen - this.pos, len - pos);
2704
+ for (let i = 0; i < take; i++)
2705
+ state[this.pos++] ^= data[pos++];
2706
+ if (this.pos === blockLen)
2707
+ this.keccak();
2708
+ }
2709
+ return this;
2710
+ }
2711
+ finish() {
2712
+ if (this.finished)
2713
+ return;
2714
+ this.finished = true;
2715
+ const { state, suffix, pos, blockLen } = this;
2716
+ state[pos] ^= suffix;
2717
+ if ((suffix & 128) !== 0 && pos === blockLen - 1)
2718
+ this.keccak();
2719
+ state[blockLen - 1] ^= 128;
2720
+ this.keccak();
2721
+ }
2722
+ writeInto(out) {
2723
+ aexists(this, false);
2724
+ abytes(out);
2725
+ this.finish();
2726
+ const bufferOut = this.state;
2727
+ const { blockLen } = this;
2728
+ for (let pos = 0, len = out.length; pos < len; ) {
2729
+ if (this.posOut >= blockLen)
2730
+ this.keccak();
2731
+ const take = Math.min(blockLen - this.posOut, len - pos);
2732
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
2733
+ this.posOut += take;
2734
+ pos += take;
2735
+ }
2736
+ return out;
2737
+ }
2738
+ xofInto(out) {
2739
+ if (!this.enableXOF)
2740
+ throw new Error("XOF is not possible for this instance");
2741
+ return this.writeInto(out);
2742
+ }
2743
+ xof(bytes) {
2744
+ anumber(bytes);
2745
+ return this.xofInto(new Uint8Array(bytes));
2746
+ }
2747
+ digestInto(out) {
2748
+ aoutput(out, this);
2749
+ if (this.finished)
2750
+ throw new Error("digest() was already called");
2751
+ this.writeInto(out);
2752
+ this.destroy();
2753
+ return out;
2754
+ }
2755
+ digest() {
2756
+ return this.digestInto(new Uint8Array(this.outputLen));
2757
+ }
2758
+ destroy() {
2759
+ this.destroyed = true;
2760
+ clean(this.state);
2761
+ }
2762
+ _cloneInto(to) {
2763
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
2764
+ to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
2765
+ to.state32.set(this.state32);
2766
+ to.pos = this.pos;
2767
+ to.posOut = this.posOut;
2768
+ to.finished = this.finished;
2769
+ to.rounds = rounds;
2770
+ to.suffix = suffix;
2771
+ to.outputLen = outputLen;
2772
+ to.enableXOF = enableXOF;
2773
+ to.destroyed = this.destroyed;
2774
+ return to;
2775
+ }
2776
+ };
2777
+ var gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
2778
+ var keccak_256 = /* @__PURE__ */ (() => gen(1, 136, 256 / 8))();
2779
+
2780
+ // node_modules/viem/_esm/utils/hash/keccak256.js
2781
+ function keccak256(value, to_) {
2782
+ const to = to_ || "hex";
2783
+ const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes2(value) : value);
2784
+ if (to === "bytes")
2785
+ return bytes;
2786
+ return toHex(bytes);
2787
+ }
2788
+
2789
+ // node_modules/viem/_esm/utils/address/getAddress.js
2790
+ var checksumAddressCache = /* @__PURE__ */ new LruMap(8192);
2791
+ function checksumAddress(address_, chainId) {
2792
+ if (checksumAddressCache.has(`${address_}.${chainId}`))
2793
+ return checksumAddressCache.get(`${address_}.${chainId}`);
2794
+ const hexAddress = chainId ? `${chainId}${address_.toLowerCase()}` : address_.substring(2).toLowerCase();
2795
+ const hash = keccak256(stringToBytes(hexAddress), "bytes");
2796
+ const address = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split("");
2797
+ for (let i = 0; i < 40; i += 2) {
2798
+ if (hash[i >> 1] >> 4 >= 8 && address[i]) {
2799
+ address[i] = address[i].toUpperCase();
2800
+ }
2801
+ if ((hash[i >> 1] & 15) >= 8 && address[i + 1]) {
2802
+ address[i + 1] = address[i + 1].toUpperCase();
2803
+ }
2804
+ }
2805
+ const result = `0x${address.join("")}`;
2806
+ checksumAddressCache.set(`${address_}.${chainId}`, result);
2807
+ return result;
2808
+ }
2809
+
2810
+ // node_modules/viem/_esm/utils/address/isAddress.js
2811
+ var addressRegex = /^0x[a-fA-F0-9]{40}$/;
2812
+ var isAddressCache = /* @__PURE__ */ new LruMap(8192);
2813
+ function isAddress(address, options) {
2814
+ const { strict = true } = options ?? {};
2815
+ const cacheKey = `${address}.${strict}`;
2816
+ if (isAddressCache.has(cacheKey))
2817
+ return isAddressCache.get(cacheKey);
2818
+ const result = (() => {
2819
+ if (!addressRegex.test(address))
2820
+ return false;
2821
+ if (address.toLowerCase() === address)
2822
+ return true;
2823
+ if (strict)
2824
+ return checksumAddress(address) === address;
2825
+ return true;
2826
+ })();
2827
+ isAddressCache.set(cacheKey, result);
2828
+ return result;
2829
+ }
2830
+
2831
+ // node_modules/viem/_esm/accounts/toAccount.js
2832
+ function toAccount(source) {
2833
+ if (typeof source === "string") {
2834
+ if (!isAddress(source, { strict: false }))
2835
+ throw new InvalidAddressError({ address: source });
2836
+ return {
2837
+ address: source,
2838
+ type: "json-rpc"
2839
+ };
2840
+ }
2841
+ if (!isAddress(source.address, { strict: false }))
2842
+ throw new InvalidAddressError({ address: source.address });
2843
+ return {
2844
+ address: source.address,
2845
+ nonceManager: source.nonceManager,
2846
+ sign: source.sign,
2847
+ signAuthorization: source.signAuthorization,
2848
+ signMessage: source.signMessage,
2849
+ signTransaction: source.signTransaction,
2850
+ signTypedData: source.signTypedData,
2851
+ source: "custom",
2852
+ type: "local"
2853
+ };
2854
+ }
2855
+
2856
+ // node_modules/viem/_esm/accounts/utils/publicKeyToAddress.js
2857
+ function publicKeyToAddress(publicKey) {
2858
+ const address = keccak256(`0x${publicKey.substring(4)}`).substring(26);
2859
+ return checksumAddress(`0x${address}`);
2860
+ }
2861
+
2862
+ // node_modules/viem/_esm/accounts/utils/sign.js
2863
+ var extraEntropy = false;
2864
+ async function sign({ hash, privateKey, to = "object" }) {
2865
+ const { r, s, recovery } = secp256k1.sign(hash.slice(2), privateKey.slice(2), {
2866
+ lowS: true,
2867
+ extraEntropy: isHex(extraEntropy, { strict: false }) ? hexToBytes2(extraEntropy) : extraEntropy
2868
+ });
2869
+ const signature = {
2870
+ r: numberToHex(r, { size: 32 }),
2871
+ s: numberToHex(s, { size: 32 }),
2872
+ v: recovery ? 28n : 27n,
2873
+ yParity: recovery
2874
+ };
2875
+ return (() => {
2876
+ if (to === "bytes" || to === "hex")
2877
+ return serializeSignature({ ...signature, to });
2878
+ return signature;
2879
+ })();
2880
+ }
2881
+
2882
+ // node_modules/viem/_esm/utils/data/concat.js
2883
+ function concat(values) {
2884
+ if (typeof values[0] === "string")
2885
+ return concatHex(values);
2886
+ return concatBytes3(values);
2887
+ }
2888
+ function concatBytes3(values) {
2889
+ let length = 0;
2890
+ for (const arr of values) {
2891
+ length += arr.length;
2892
+ }
2893
+ const result = new Uint8Array(length);
2894
+ let offset = 0;
2895
+ for (const arr of values) {
2896
+ result.set(arr, offset);
2897
+ offset += arr.length;
2898
+ }
2899
+ return result;
2900
+ }
2901
+ function concatHex(values) {
2902
+ return `0x${values.reduce((acc, x) => acc + x.replace("0x", ""), "")}`;
2903
+ }
2904
+
2905
+ // node_modules/viem/_esm/errors/cursor.js
2906
+ var NegativeOffsetError = class extends BaseError {
2907
+ constructor({ offset }) {
2908
+ super(`Offset \`${offset}\` cannot be negative.`, {
2909
+ name: "NegativeOffsetError"
2910
+ });
2911
+ }
2912
+ };
2913
+ var PositionOutOfBoundsError = class extends BaseError {
2914
+ constructor({ length, position }) {
2915
+ super(`Position \`${position}\` is out of bounds (\`0 < position < ${length}\`).`, { name: "PositionOutOfBoundsError" });
2916
+ }
2917
+ };
2918
+ var RecursiveReadLimitExceededError = class extends BaseError {
2919
+ constructor({ count, limit }) {
2920
+ super(`Recursive read limit of \`${limit}\` exceeded (recursive read count: \`${count}\`).`, { name: "RecursiveReadLimitExceededError" });
2921
+ }
2922
+ };
2923
+
2924
+ // node_modules/viem/_esm/utils/cursor.js
2925
+ var staticCursor = {
2926
+ bytes: new Uint8Array(),
2927
+ dataView: new DataView(new ArrayBuffer(0)),
2928
+ position: 0,
2929
+ positionReadCount: /* @__PURE__ */ new Map(),
2930
+ recursiveReadCount: 0,
2931
+ recursiveReadLimit: Number.POSITIVE_INFINITY,
2932
+ assertReadLimit() {
2933
+ if (this.recursiveReadCount >= this.recursiveReadLimit)
2934
+ throw new RecursiveReadLimitExceededError({
2935
+ count: this.recursiveReadCount + 1,
2936
+ limit: this.recursiveReadLimit
2937
+ });
2938
+ },
2939
+ assertPosition(position) {
2940
+ if (position < 0 || position > this.bytes.length - 1)
2941
+ throw new PositionOutOfBoundsError({
2942
+ length: this.bytes.length,
2943
+ position
2944
+ });
2945
+ },
2946
+ decrementPosition(offset) {
2947
+ if (offset < 0)
2948
+ throw new NegativeOffsetError({ offset });
2949
+ const position = this.position - offset;
2950
+ this.assertPosition(position);
2951
+ this.position = position;
2952
+ },
2953
+ getReadCount(position) {
2954
+ return this.positionReadCount.get(position || this.position) || 0;
2955
+ },
2956
+ incrementPosition(offset) {
2957
+ if (offset < 0)
2958
+ throw new NegativeOffsetError({ offset });
2959
+ const position = this.position + offset;
2960
+ this.assertPosition(position);
2961
+ this.position = position;
2962
+ },
2963
+ inspectByte(position_) {
2964
+ const position = position_ ?? this.position;
2965
+ this.assertPosition(position);
2966
+ return this.bytes[position];
2967
+ },
2968
+ inspectBytes(length, position_) {
2969
+ const position = position_ ?? this.position;
2970
+ this.assertPosition(position + length - 1);
2971
+ return this.bytes.subarray(position, position + length);
2972
+ },
2973
+ inspectUint8(position_) {
2974
+ const position = position_ ?? this.position;
2975
+ this.assertPosition(position);
2976
+ return this.bytes[position];
2977
+ },
2978
+ inspectUint16(position_) {
2979
+ const position = position_ ?? this.position;
2980
+ this.assertPosition(position + 1);
2981
+ return this.dataView.getUint16(position);
2982
+ },
2983
+ inspectUint24(position_) {
2984
+ const position = position_ ?? this.position;
2985
+ this.assertPosition(position + 2);
2986
+ return (this.dataView.getUint16(position) << 8) + this.dataView.getUint8(position + 2);
2987
+ },
2988
+ inspectUint32(position_) {
2989
+ const position = position_ ?? this.position;
2990
+ this.assertPosition(position + 3);
2991
+ return this.dataView.getUint32(position);
2992
+ },
2993
+ pushByte(byte) {
2994
+ this.assertPosition(this.position);
2995
+ this.bytes[this.position] = byte;
2996
+ this.position++;
2997
+ },
2998
+ pushBytes(bytes) {
2999
+ this.assertPosition(this.position + bytes.length - 1);
3000
+ this.bytes.set(bytes, this.position);
3001
+ this.position += bytes.length;
3002
+ },
3003
+ pushUint8(value) {
3004
+ this.assertPosition(this.position);
3005
+ this.bytes[this.position] = value;
3006
+ this.position++;
3007
+ },
3008
+ pushUint16(value) {
3009
+ this.assertPosition(this.position + 1);
3010
+ this.dataView.setUint16(this.position, value);
3011
+ this.position += 2;
3012
+ },
3013
+ pushUint24(value) {
3014
+ this.assertPosition(this.position + 2);
3015
+ this.dataView.setUint16(this.position, value >> 8);
3016
+ this.dataView.setUint8(this.position + 2, value & ~4294967040);
3017
+ this.position += 3;
3018
+ },
3019
+ pushUint32(value) {
3020
+ this.assertPosition(this.position + 3);
3021
+ this.dataView.setUint32(this.position, value);
3022
+ this.position += 4;
3023
+ },
3024
+ readByte() {
3025
+ this.assertReadLimit();
3026
+ this._touch();
3027
+ const value = this.inspectByte();
3028
+ this.position++;
3029
+ return value;
3030
+ },
3031
+ readBytes(length, size2) {
3032
+ this.assertReadLimit();
3033
+ this._touch();
3034
+ const value = this.inspectBytes(length);
3035
+ this.position += size2 ?? length;
3036
+ return value;
3037
+ },
3038
+ readUint8() {
3039
+ this.assertReadLimit();
3040
+ this._touch();
3041
+ const value = this.inspectUint8();
3042
+ this.position += 1;
3043
+ return value;
3044
+ },
3045
+ readUint16() {
3046
+ this.assertReadLimit();
3047
+ this._touch();
3048
+ const value = this.inspectUint16();
3049
+ this.position += 2;
3050
+ return value;
3051
+ },
3052
+ readUint24() {
3053
+ this.assertReadLimit();
3054
+ this._touch();
3055
+ const value = this.inspectUint24();
3056
+ this.position += 3;
3057
+ return value;
3058
+ },
3059
+ readUint32() {
3060
+ this.assertReadLimit();
3061
+ this._touch();
3062
+ const value = this.inspectUint32();
3063
+ this.position += 4;
3064
+ return value;
3065
+ },
3066
+ get remaining() {
3067
+ return this.bytes.length - this.position;
3068
+ },
3069
+ setPosition(position) {
3070
+ const oldPosition = this.position;
3071
+ this.assertPosition(position);
3072
+ this.position = position;
3073
+ return () => this.position = oldPosition;
3074
+ },
3075
+ _touch() {
3076
+ if (this.recursiveReadLimit === Number.POSITIVE_INFINITY)
3077
+ return;
3078
+ const count = this.getReadCount();
3079
+ this.positionReadCount.set(this.position, count + 1);
3080
+ if (count > 0)
3081
+ this.recursiveReadCount++;
3082
+ }
3083
+ };
3084
+ function createCursor(bytes, { recursiveReadLimit = 8192 } = {}) {
3085
+ const cursor = Object.create(staticCursor);
3086
+ cursor.bytes = bytes;
3087
+ cursor.dataView = new DataView(bytes.buffer ?? bytes, bytes.byteOffset, bytes.byteLength);
3088
+ cursor.positionReadCount = /* @__PURE__ */ new Map();
3089
+ cursor.recursiveReadLimit = recursiveReadLimit;
3090
+ return cursor;
3091
+ }
3092
+
3093
+ // node_modules/viem/_esm/utils/encoding/toRlp.js
3094
+ function toRlp(bytes, to = "hex") {
3095
+ const encodable = getEncodable(bytes);
3096
+ const cursor = createCursor(new Uint8Array(encodable.length));
3097
+ encodable.encode(cursor);
3098
+ if (to === "hex")
3099
+ return bytesToHex2(cursor.bytes);
3100
+ return cursor.bytes;
3101
+ }
3102
+ function getEncodable(bytes) {
3103
+ if (Array.isArray(bytes))
3104
+ return getEncodableList(bytes.map((x) => getEncodable(x)));
3105
+ return getEncodableBytes(bytes);
3106
+ }
3107
+ function getEncodableList(list) {
3108
+ const bodyLength = list.reduce((acc, x) => acc + x.length, 0);
3109
+ const sizeOfBodyLength = getSizeOfLength(bodyLength);
3110
+ const length = (() => {
3111
+ if (bodyLength <= 55)
3112
+ return 1 + bodyLength;
3113
+ return 1 + sizeOfBodyLength + bodyLength;
3114
+ })();
3115
+ return {
3116
+ length,
3117
+ encode(cursor) {
3118
+ if (bodyLength <= 55) {
3119
+ cursor.pushByte(192 + bodyLength);
3120
+ } else {
3121
+ cursor.pushByte(192 + 55 + sizeOfBodyLength);
3122
+ if (sizeOfBodyLength === 1)
3123
+ cursor.pushUint8(bodyLength);
3124
+ else if (sizeOfBodyLength === 2)
3125
+ cursor.pushUint16(bodyLength);
3126
+ else if (sizeOfBodyLength === 3)
3127
+ cursor.pushUint24(bodyLength);
3128
+ else
3129
+ cursor.pushUint32(bodyLength);
3130
+ }
3131
+ for (const { encode } of list) {
3132
+ encode(cursor);
3133
+ }
3134
+ }
3135
+ };
3136
+ }
3137
+ function getEncodableBytes(bytesOrHex) {
3138
+ const bytes = typeof bytesOrHex === "string" ? hexToBytes2(bytesOrHex) : bytesOrHex;
3139
+ const sizeOfBytesLength = getSizeOfLength(bytes.length);
3140
+ const length = (() => {
3141
+ if (bytes.length === 1 && bytes[0] < 128)
3142
+ return 1;
3143
+ if (bytes.length <= 55)
3144
+ return 1 + bytes.length;
3145
+ return 1 + sizeOfBytesLength + bytes.length;
3146
+ })();
3147
+ return {
3148
+ length,
3149
+ encode(cursor) {
3150
+ if (bytes.length === 1 && bytes[0] < 128) {
3151
+ cursor.pushBytes(bytes);
3152
+ } else if (bytes.length <= 55) {
3153
+ cursor.pushByte(128 + bytes.length);
3154
+ cursor.pushBytes(bytes);
3155
+ } else {
3156
+ cursor.pushByte(128 + 55 + sizeOfBytesLength);
3157
+ if (sizeOfBytesLength === 1)
3158
+ cursor.pushUint8(bytes.length);
3159
+ else if (sizeOfBytesLength === 2)
3160
+ cursor.pushUint16(bytes.length);
3161
+ else if (sizeOfBytesLength === 3)
3162
+ cursor.pushUint24(bytes.length);
3163
+ else
3164
+ cursor.pushUint32(bytes.length);
3165
+ cursor.pushBytes(bytes);
3166
+ }
3167
+ }
3168
+ };
3169
+ }
3170
+ function getSizeOfLength(length) {
3171
+ if (length < 2 ** 8)
3172
+ return 1;
3173
+ if (length < 2 ** 16)
3174
+ return 2;
3175
+ if (length < 2 ** 24)
3176
+ return 3;
3177
+ if (length < 2 ** 32)
3178
+ return 4;
3179
+ throw new BaseError("Length is too large.");
3180
+ }
3181
+
3182
+ // node_modules/viem/_esm/utils/authorization/hashAuthorization.js
3183
+ function hashAuthorization(parameters) {
3184
+ const { chainId, nonce, to } = parameters;
3185
+ const address = parameters.contractAddress ?? parameters.address;
3186
+ const hash = keccak256(concatHex([
3187
+ "0x05",
3188
+ toRlp([
3189
+ chainId ? numberToHex(chainId) : "0x",
3190
+ address,
3191
+ nonce ? numberToHex(nonce) : "0x"
3192
+ ])
3193
+ ]));
3194
+ if (to === "bytes")
3195
+ return hexToBytes2(hash);
3196
+ return hash;
3197
+ }
3198
+
3199
+ // node_modules/viem/_esm/accounts/utils/signAuthorization.js
3200
+ async function signAuthorization(parameters) {
3201
+ const { chainId, nonce, privateKey, to = "object" } = parameters;
3202
+ const address = parameters.contractAddress ?? parameters.address;
3203
+ const signature = await sign({
3204
+ hash: hashAuthorization({ address, chainId, nonce }),
3205
+ privateKey,
3206
+ to
3207
+ });
3208
+ if (to === "object")
3209
+ return {
3210
+ address,
3211
+ chainId,
3212
+ nonce,
3213
+ ...signature
3214
+ };
3215
+ return signature;
3216
+ }
3217
+
3218
+ // node_modules/viem/_esm/constants/strings.js
3219
+ var presignMessagePrefix = "Ethereum Signed Message:\n";
3220
+
3221
+ // node_modules/viem/_esm/utils/signature/toPrefixedMessage.js
3222
+ function toPrefixedMessage(message_) {
3223
+ const message = (() => {
3224
+ if (typeof message_ === "string")
3225
+ return stringToHex(message_);
3226
+ if (typeof message_.raw === "string")
3227
+ return message_.raw;
3228
+ return bytesToHex2(message_.raw);
3229
+ })();
3230
+ const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`);
3231
+ return concat([prefix, message]);
3232
+ }
3233
+
3234
+ // node_modules/viem/_esm/utils/signature/hashMessage.js
3235
+ function hashMessage(message, to_) {
3236
+ return keccak256(toPrefixedMessage(message), to_);
3237
+ }
3238
+
3239
+ // node_modules/viem/_esm/accounts/utils/signMessage.js
3240
+ async function signMessage({ message, privateKey }) {
3241
+ return await sign({ hash: hashMessage(message), privateKey, to: "hex" });
3242
+ }
3243
+
3244
+ // node_modules/viem/_esm/constants/unit.js
3245
+ var gweiUnits = {
3246
+ ether: -9,
3247
+ wei: 9
3248
+ };
3249
+
3250
+ // node_modules/viem/_esm/utils/unit/formatUnits.js
3251
+ function formatUnits(value, decimals) {
3252
+ let display = value.toString();
3253
+ const negative = display.startsWith("-");
3254
+ if (negative)
3255
+ display = display.slice(1);
3256
+ display = display.padStart(decimals, "0");
3257
+ let [integer, fraction] = [
3258
+ display.slice(0, display.length - decimals),
3259
+ display.slice(display.length - decimals)
3260
+ ];
3261
+ fraction = fraction.replace(/(0+)$/, "");
3262
+ return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`;
3263
+ }
3264
+
3265
+ // node_modules/viem/_esm/utils/unit/formatGwei.js
3266
+ function formatGwei(wei, unit = "wei") {
3267
+ return formatUnits(wei, gweiUnits[unit]);
3268
+ }
3269
+
3270
+ // node_modules/viem/_esm/errors/transaction.js
3271
+ function prettyPrint(args2) {
3272
+ const entries = Object.entries(args2).map(([key, value]) => {
3273
+ if (value === void 0 || value === false)
3274
+ return null;
3275
+ return [key, value];
3276
+ }).filter(Boolean);
3277
+ const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0);
3278
+ return entries.map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`).join("\n");
3279
+ }
3280
+ var InvalidLegacyVError = class extends BaseError {
3281
+ constructor({ v }) {
3282
+ super(`Invalid \`v\` value "${v}". Expected 27 or 28.`, {
3283
+ name: "InvalidLegacyVError"
3284
+ });
3285
+ }
3286
+ };
3287
+ var InvalidSerializableTransactionError = class extends BaseError {
3288
+ constructor({ transaction }) {
3289
+ super("Cannot infer a transaction type from provided transaction.", {
3290
+ metaMessages: [
3291
+ "Provided Transaction:",
3292
+ "{",
3293
+ prettyPrint(transaction),
3294
+ "}",
3295
+ "",
3296
+ "To infer the type, either provide:",
3297
+ "- a `type` to the Transaction, or",
3298
+ "- an EIP-1559 Transaction with `maxFeePerGas`, or",
3299
+ "- an EIP-2930 Transaction with `gasPrice` & `accessList`, or",
3300
+ "- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or",
3301
+ "- an EIP-7702 Transaction with `authorizationList`, or",
3302
+ "- a Legacy Transaction with `gasPrice`"
3303
+ ],
3304
+ name: "InvalidSerializableTransactionError"
3305
+ });
3306
+ }
3307
+ };
3308
+ var InvalidStorageKeySizeError = class extends BaseError {
3309
+ constructor({ storageKey }) {
3310
+ super(`Size for storage key "${storageKey}" is invalid. Expected 32 bytes. Got ${Math.floor((storageKey.length - 2) / 2)} bytes.`, { name: "InvalidStorageKeySizeError" });
3311
+ }
3312
+ };
3313
+
3314
+ // node_modules/viem/_esm/utils/authorization/serializeAuthorizationList.js
3315
+ function serializeAuthorizationList(authorizationList) {
3316
+ if (!authorizationList || authorizationList.length === 0)
3317
+ return [];
3318
+ const serializedAuthorizationList = [];
3319
+ for (const authorization of authorizationList) {
3320
+ const { chainId, nonce, ...signature } = authorization;
3321
+ const contractAddress = authorization.address;
3322
+ serializedAuthorizationList.push([
3323
+ chainId ? toHex(chainId) : "0x",
3324
+ contractAddress,
3325
+ nonce ? toHex(nonce) : "0x",
3326
+ ...toYParitySignatureArray({}, signature)
3327
+ ]);
3328
+ }
3329
+ return serializedAuthorizationList;
3330
+ }
3331
+
3332
+ // node_modules/viem/_esm/utils/blob/blobsToCommitments.js
3333
+ function blobsToCommitments(parameters) {
3334
+ const { kzg } = parameters;
3335
+ const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes");
3336
+ const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes2(x)) : parameters.blobs;
3337
+ const commitments = [];
3338
+ for (const blob of blobs)
3339
+ commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)));
3340
+ return to === "bytes" ? commitments : commitments.map((x) => bytesToHex2(x));
3341
+ }
3342
+
3343
+ // node_modules/viem/_esm/utils/blob/blobsToProofs.js
3344
+ function blobsToProofs(parameters) {
3345
+ const { kzg } = parameters;
3346
+ const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes");
3347
+ const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes2(x)) : parameters.blobs;
3348
+ const commitments = typeof parameters.commitments[0] === "string" ? parameters.commitments.map((x) => hexToBytes2(x)) : parameters.commitments;
3349
+ const proofs = [];
3350
+ for (let i = 0; i < blobs.length; i++) {
3351
+ const blob = blobs[i];
3352
+ const commitment = commitments[i];
3353
+ proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)));
3354
+ }
3355
+ return to === "bytes" ? proofs : proofs.map((x) => bytesToHex2(x));
3356
+ }
3357
+
3358
+ // node_modules/@noble/hashes/esm/sha256.js
3359
+ var sha2562 = sha256;
3360
+
3361
+ // node_modules/viem/_esm/utils/hash/sha256.js
3362
+ function sha2563(value, to_) {
3363
+ const to = to_ || "hex";
3364
+ const bytes = sha2562(isHex(value, { strict: false }) ? toBytes2(value) : value);
3365
+ if (to === "bytes")
3366
+ return bytes;
3367
+ return toHex(bytes);
3368
+ }
3369
+
3370
+ // node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js
3371
+ function commitmentToVersionedHash(parameters) {
3372
+ const { commitment, version: version2 = 1 } = parameters;
3373
+ const to = parameters.to ?? (typeof commitment === "string" ? "hex" : "bytes");
3374
+ const versionedHash = sha2563(commitment, "bytes");
3375
+ versionedHash.set([version2], 0);
3376
+ return to === "bytes" ? versionedHash : bytesToHex2(versionedHash);
3377
+ }
3378
+
3379
+ // node_modules/viem/_esm/utils/blob/commitmentsToVersionedHashes.js
3380
+ function commitmentsToVersionedHashes(parameters) {
3381
+ const { commitments, version: version2 } = parameters;
3382
+ const to = parameters.to ?? (typeof commitments[0] === "string" ? "hex" : "bytes");
3383
+ const hashes = [];
3384
+ for (const commitment of commitments) {
3385
+ hashes.push(commitmentToVersionedHash({
3386
+ commitment,
3387
+ to,
3388
+ version: version2
3389
+ }));
3390
+ }
3391
+ return hashes;
3392
+ }
3393
+
3394
+ // node_modules/viem/_esm/constants/blob.js
3395
+ var blobsPerTransaction = 6;
3396
+ var bytesPerFieldElement = 32;
3397
+ var fieldElementsPerBlob = 4096;
3398
+ var bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob;
3399
+ var maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction - // terminator byte (0x80).
3400
+ 1 - // zero byte (0x00) appended to each field element.
3401
+ 1 * fieldElementsPerBlob * blobsPerTransaction;
3402
+
3403
+ // node_modules/viem/_esm/constants/kzg.js
3404
+ var versionedHashVersionKzg = 1;
3405
+
3406
+ // node_modules/viem/_esm/errors/blob.js
3407
+ var BlobSizeTooLargeError = class extends BaseError {
3408
+ constructor({ maxSize, size: size2 }) {
3409
+ super("Blob size is too large.", {
3410
+ metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size2} bytes`],
3411
+ name: "BlobSizeTooLargeError"
3412
+ });
3413
+ }
3414
+ };
3415
+ var EmptyBlobError = class extends BaseError {
3416
+ constructor() {
3417
+ super("Blob data must not be empty.", { name: "EmptyBlobError" });
3418
+ }
3419
+ };
3420
+ var InvalidVersionedHashSizeError = class extends BaseError {
3421
+ constructor({ hash, size: size2 }) {
3422
+ super(`Versioned hash "${hash}" size is invalid.`, {
3423
+ metaMessages: ["Expected: 32", `Received: ${size2}`],
3424
+ name: "InvalidVersionedHashSizeError"
3425
+ });
3426
+ }
3427
+ };
3428
+ var InvalidVersionedHashVersionError = class extends BaseError {
3429
+ constructor({ hash, version: version2 }) {
3430
+ super(`Versioned hash "${hash}" version is invalid.`, {
3431
+ metaMessages: [
3432
+ `Expected: ${versionedHashVersionKzg}`,
3433
+ `Received: ${version2}`
3434
+ ],
3435
+ name: "InvalidVersionedHashVersionError"
3436
+ });
3437
+ }
3438
+ };
3439
+
3440
+ // node_modules/viem/_esm/utils/blob/toBlobs.js
3441
+ function toBlobs(parameters) {
3442
+ const to = parameters.to ?? (typeof parameters.data === "string" ? "hex" : "bytes");
3443
+ const data = typeof parameters.data === "string" ? hexToBytes2(parameters.data) : parameters.data;
3444
+ const size_ = size(data);
3445
+ if (!size_)
3446
+ throw new EmptyBlobError();
3447
+ if (size_ > maxBytesPerTransaction)
3448
+ throw new BlobSizeTooLargeError({
3449
+ maxSize: maxBytesPerTransaction,
3450
+ size: size_
3451
+ });
3452
+ const blobs = [];
3453
+ let active = true;
3454
+ let position = 0;
3455
+ while (active) {
3456
+ const blob = createCursor(new Uint8Array(bytesPerBlob));
3457
+ let size2 = 0;
3458
+ while (size2 < fieldElementsPerBlob) {
3459
+ const bytes = data.slice(position, position + (bytesPerFieldElement - 1));
3460
+ blob.pushByte(0);
3461
+ blob.pushBytes(bytes);
3462
+ if (bytes.length < 31) {
3463
+ blob.pushByte(128);
3464
+ active = false;
3465
+ break;
3466
+ }
3467
+ size2++;
3468
+ position += 31;
3469
+ }
3470
+ blobs.push(blob);
3471
+ }
3472
+ return to === "bytes" ? blobs.map((x) => x.bytes) : blobs.map((x) => bytesToHex2(x.bytes));
3473
+ }
3474
+
3475
+ // node_modules/viem/_esm/utils/blob/toBlobSidecars.js
3476
+ function toBlobSidecars(parameters) {
3477
+ const { data, kzg, to } = parameters;
3478
+ const blobs = parameters.blobs ?? toBlobs({ data, to });
3479
+ const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg, to });
3480
+ const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg, to });
3481
+ const sidecars = [];
3482
+ for (let i = 0; i < blobs.length; i++)
3483
+ sidecars.push({
3484
+ blob: blobs[i],
3485
+ commitment: commitments[i],
3486
+ proof: proofs[i]
3487
+ });
3488
+ return sidecars;
3489
+ }
3490
+
3491
+ // node_modules/viem/_esm/constants/number.js
3492
+ var maxInt8 = 2n ** (8n - 1n) - 1n;
3493
+ var maxInt16 = 2n ** (16n - 1n) - 1n;
3494
+ var maxInt24 = 2n ** (24n - 1n) - 1n;
3495
+ var maxInt32 = 2n ** (32n - 1n) - 1n;
3496
+ var maxInt40 = 2n ** (40n - 1n) - 1n;
3497
+ var maxInt48 = 2n ** (48n - 1n) - 1n;
3498
+ var maxInt56 = 2n ** (56n - 1n) - 1n;
3499
+ var maxInt64 = 2n ** (64n - 1n) - 1n;
3500
+ var maxInt72 = 2n ** (72n - 1n) - 1n;
3501
+ var maxInt80 = 2n ** (80n - 1n) - 1n;
3502
+ var maxInt88 = 2n ** (88n - 1n) - 1n;
3503
+ var maxInt96 = 2n ** (96n - 1n) - 1n;
3504
+ var maxInt104 = 2n ** (104n - 1n) - 1n;
3505
+ var maxInt112 = 2n ** (112n - 1n) - 1n;
3506
+ var maxInt120 = 2n ** (120n - 1n) - 1n;
3507
+ var maxInt128 = 2n ** (128n - 1n) - 1n;
3508
+ var maxInt136 = 2n ** (136n - 1n) - 1n;
3509
+ var maxInt144 = 2n ** (144n - 1n) - 1n;
3510
+ var maxInt152 = 2n ** (152n - 1n) - 1n;
3511
+ var maxInt160 = 2n ** (160n - 1n) - 1n;
3512
+ var maxInt168 = 2n ** (168n - 1n) - 1n;
3513
+ var maxInt176 = 2n ** (176n - 1n) - 1n;
3514
+ var maxInt184 = 2n ** (184n - 1n) - 1n;
3515
+ var maxInt192 = 2n ** (192n - 1n) - 1n;
3516
+ var maxInt200 = 2n ** (200n - 1n) - 1n;
3517
+ var maxInt208 = 2n ** (208n - 1n) - 1n;
3518
+ var maxInt216 = 2n ** (216n - 1n) - 1n;
3519
+ var maxInt224 = 2n ** (224n - 1n) - 1n;
3520
+ var maxInt232 = 2n ** (232n - 1n) - 1n;
3521
+ var maxInt240 = 2n ** (240n - 1n) - 1n;
3522
+ var maxInt248 = 2n ** (248n - 1n) - 1n;
3523
+ var maxInt256 = 2n ** (256n - 1n) - 1n;
3524
+ var minInt8 = -(2n ** (8n - 1n));
3525
+ var minInt16 = -(2n ** (16n - 1n));
3526
+ var minInt24 = -(2n ** (24n - 1n));
3527
+ var minInt32 = -(2n ** (32n - 1n));
3528
+ var minInt40 = -(2n ** (40n - 1n));
3529
+ var minInt48 = -(2n ** (48n - 1n));
3530
+ var minInt56 = -(2n ** (56n - 1n));
3531
+ var minInt64 = -(2n ** (64n - 1n));
3532
+ var minInt72 = -(2n ** (72n - 1n));
3533
+ var minInt80 = -(2n ** (80n - 1n));
3534
+ var minInt88 = -(2n ** (88n - 1n));
3535
+ var minInt96 = -(2n ** (96n - 1n));
3536
+ var minInt104 = -(2n ** (104n - 1n));
3537
+ var minInt112 = -(2n ** (112n - 1n));
3538
+ var minInt120 = -(2n ** (120n - 1n));
3539
+ var minInt128 = -(2n ** (128n - 1n));
3540
+ var minInt136 = -(2n ** (136n - 1n));
3541
+ var minInt144 = -(2n ** (144n - 1n));
3542
+ var minInt152 = -(2n ** (152n - 1n));
3543
+ var minInt160 = -(2n ** (160n - 1n));
3544
+ var minInt168 = -(2n ** (168n - 1n));
3545
+ var minInt176 = -(2n ** (176n - 1n));
3546
+ var minInt184 = -(2n ** (184n - 1n));
3547
+ var minInt192 = -(2n ** (192n - 1n));
3548
+ var minInt200 = -(2n ** (200n - 1n));
3549
+ var minInt208 = -(2n ** (208n - 1n));
3550
+ var minInt216 = -(2n ** (216n - 1n));
3551
+ var minInt224 = -(2n ** (224n - 1n));
3552
+ var minInt232 = -(2n ** (232n - 1n));
3553
+ var minInt240 = -(2n ** (240n - 1n));
3554
+ var minInt248 = -(2n ** (248n - 1n));
3555
+ var minInt256 = -(2n ** (256n - 1n));
3556
+ var maxUint8 = 2n ** 8n - 1n;
3557
+ var maxUint16 = 2n ** 16n - 1n;
3558
+ var maxUint24 = 2n ** 24n - 1n;
3559
+ var maxUint32 = 2n ** 32n - 1n;
3560
+ var maxUint40 = 2n ** 40n - 1n;
3561
+ var maxUint48 = 2n ** 48n - 1n;
3562
+ var maxUint56 = 2n ** 56n - 1n;
3563
+ var maxUint64 = 2n ** 64n - 1n;
3564
+ var maxUint72 = 2n ** 72n - 1n;
3565
+ var maxUint80 = 2n ** 80n - 1n;
3566
+ var maxUint88 = 2n ** 88n - 1n;
3567
+ var maxUint96 = 2n ** 96n - 1n;
3568
+ var maxUint104 = 2n ** 104n - 1n;
3569
+ var maxUint112 = 2n ** 112n - 1n;
3570
+ var maxUint120 = 2n ** 120n - 1n;
3571
+ var maxUint128 = 2n ** 128n - 1n;
3572
+ var maxUint136 = 2n ** 136n - 1n;
3573
+ var maxUint144 = 2n ** 144n - 1n;
3574
+ var maxUint152 = 2n ** 152n - 1n;
3575
+ var maxUint160 = 2n ** 160n - 1n;
3576
+ var maxUint168 = 2n ** 168n - 1n;
3577
+ var maxUint176 = 2n ** 176n - 1n;
3578
+ var maxUint184 = 2n ** 184n - 1n;
3579
+ var maxUint192 = 2n ** 192n - 1n;
3580
+ var maxUint200 = 2n ** 200n - 1n;
3581
+ var maxUint208 = 2n ** 208n - 1n;
3582
+ var maxUint216 = 2n ** 216n - 1n;
3583
+ var maxUint224 = 2n ** 224n - 1n;
3584
+ var maxUint232 = 2n ** 232n - 1n;
3585
+ var maxUint240 = 2n ** 240n - 1n;
3586
+ var maxUint248 = 2n ** 248n - 1n;
3587
+ var maxUint256 = 2n ** 256n - 1n;
3588
+
3589
+ // node_modules/viem/_esm/errors/chain.js
3590
+ var InvalidChainIdError = class extends BaseError {
3591
+ constructor({ chainId }) {
3592
+ super(typeof chainId === "number" ? `Chain ID "${chainId}" is invalid.` : "Chain ID is invalid.", { name: "InvalidChainIdError" });
3593
+ }
3594
+ };
3595
+
3596
+ // node_modules/viem/_esm/errors/node.js
3597
+ var ExecutionRevertedError = class extends BaseError {
3598
+ constructor({ cause, message } = {}) {
3599
+ const reason = message?.replace("execution reverted: ", "")?.replace("execution reverted", "");
3600
+ super(`Execution reverted ${reason ? `with reason: ${reason}` : "for an unknown reason"}.`, {
3601
+ cause,
3602
+ name: "ExecutionRevertedError"
3603
+ });
3604
+ }
3605
+ };
3606
+ Object.defineProperty(ExecutionRevertedError, "code", {
3607
+ enumerable: true,
3608
+ configurable: true,
3609
+ writable: true,
3610
+ value: 3
3611
+ });
3612
+ Object.defineProperty(ExecutionRevertedError, "nodeMessage", {
3613
+ enumerable: true,
3614
+ configurable: true,
3615
+ writable: true,
3616
+ value: /execution reverted|gas required exceeds allowance/
3617
+ });
3618
+ var FeeCapTooHighError = class extends BaseError {
3619
+ constructor({ cause, maxFeePerGas } = {}) {
3620
+ super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}) cannot be higher than the maximum allowed value (2^256-1).`, {
3621
+ cause,
3622
+ name: "FeeCapTooHighError"
3623
+ });
3624
+ }
3625
+ };
3626
+ Object.defineProperty(FeeCapTooHighError, "nodeMessage", {
3627
+ enumerable: true,
3628
+ configurable: true,
3629
+ writable: true,
3630
+ value: /max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/
3631
+ });
3632
+ var FeeCapTooLowError = class extends BaseError {
3633
+ constructor({ cause, maxFeePerGas } = {}) {
3634
+ super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ""} gwei) cannot be lower than the block base fee.`, {
3635
+ cause,
3636
+ name: "FeeCapTooLowError"
3637
+ });
3638
+ }
3639
+ };
3640
+ Object.defineProperty(FeeCapTooLowError, "nodeMessage", {
3641
+ enumerable: true,
3642
+ configurable: true,
3643
+ writable: true,
3644
+ value: /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/
3645
+ });
3646
+ var NonceTooHighError = class extends BaseError {
3647
+ constructor({ cause, nonce } = {}) {
3648
+ super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is higher than the next one expected.`, { cause, name: "NonceTooHighError" });
3649
+ }
3650
+ };
3651
+ Object.defineProperty(NonceTooHighError, "nodeMessage", {
3652
+ enumerable: true,
3653
+ configurable: true,
3654
+ writable: true,
3655
+ value: /nonce too high/
3656
+ });
3657
+ var NonceTooLowError = class extends BaseError {
3658
+ constructor({ cause, nonce } = {}) {
3659
+ super([
3660
+ `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is lower than the current nonce of the account.`,
3661
+ "Try increasing the nonce or find the latest nonce with `getTransactionCount`."
3662
+ ].join("\n"), { cause, name: "NonceTooLowError" });
3663
+ }
3664
+ };
3665
+ Object.defineProperty(NonceTooLowError, "nodeMessage", {
3666
+ enumerable: true,
3667
+ configurable: true,
3668
+ writable: true,
3669
+ value: /nonce too low|transaction already imported|already known/
3670
+ });
3671
+ var NonceMaxValueError = class extends BaseError {
3672
+ constructor({ cause, nonce } = {}) {
3673
+ super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}exceeds the maximum allowed nonce.`, { cause, name: "NonceMaxValueError" });
3674
+ }
3675
+ };
3676
+ Object.defineProperty(NonceMaxValueError, "nodeMessage", {
3677
+ enumerable: true,
3678
+ configurable: true,
3679
+ writable: true,
3680
+ value: /nonce has max value/
3681
+ });
3682
+ var InsufficientFundsError = class extends BaseError {
3683
+ constructor({ cause } = {}) {
3684
+ super([
3685
+ "The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."
3686
+ ].join("\n"), {
3687
+ cause,
3688
+ metaMessages: [
3689
+ "This error could arise when the account does not have enough funds to:",
3690
+ " - pay for the total gas fee,",
3691
+ " - pay for the value to send.",
3692
+ " ",
3693
+ "The cost of the transaction is calculated as `gas * gas fee + value`, where:",
3694
+ " - `gas` is the amount of gas needed for transaction to execute,",
3695
+ " - `gas fee` is the gas fee,",
3696
+ " - `value` is the amount of ether to send to the recipient."
3697
+ ],
3698
+ name: "InsufficientFundsError"
3699
+ });
3700
+ }
3701
+ };
3702
+ Object.defineProperty(InsufficientFundsError, "nodeMessage", {
3703
+ enumerable: true,
3704
+ configurable: true,
3705
+ writable: true,
3706
+ value: /insufficient funds|exceeds transaction sender account balance/
3707
+ });
3708
+ var IntrinsicGasTooHighError = class extends BaseError {
3709
+ constructor({ cause, gas } = {}) {
3710
+ super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction exceeds the limit allowed for the block.`, {
3711
+ cause,
3712
+ name: "IntrinsicGasTooHighError"
3713
+ });
3714
+ }
3715
+ };
3716
+ Object.defineProperty(IntrinsicGasTooHighError, "nodeMessage", {
3717
+ enumerable: true,
3718
+ configurable: true,
3719
+ writable: true,
3720
+ value: /intrinsic gas too high|gas limit reached/
3721
+ });
3722
+ var IntrinsicGasTooLowError = class extends BaseError {
3723
+ constructor({ cause, gas } = {}) {
3724
+ super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction is too low.`, {
3725
+ cause,
3726
+ name: "IntrinsicGasTooLowError"
3727
+ });
3728
+ }
3729
+ };
3730
+ Object.defineProperty(IntrinsicGasTooLowError, "nodeMessage", {
3731
+ enumerable: true,
3732
+ configurable: true,
3733
+ writable: true,
3734
+ value: /intrinsic gas too low/
3735
+ });
3736
+ var TransactionTypeNotSupportedError = class extends BaseError {
3737
+ constructor({ cause }) {
3738
+ super("The transaction type is not supported for this chain.", {
3739
+ cause,
3740
+ name: "TransactionTypeNotSupportedError"
3741
+ });
3742
+ }
3743
+ };
3744
+ Object.defineProperty(TransactionTypeNotSupportedError, "nodeMessage", {
3745
+ enumerable: true,
3746
+ configurable: true,
3747
+ writable: true,
3748
+ value: /transaction type not valid/
3749
+ });
3750
+ var TipAboveFeeCapError = class extends BaseError {
3751
+ constructor({ cause, maxPriorityFeePerGas, maxFeePerGas } = {}) {
3752
+ super([
3753
+ `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei` : ""}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}).`
3754
+ ].join("\n"), {
3755
+ cause,
3756
+ name: "TipAboveFeeCapError"
3757
+ });
3758
+ }
3759
+ };
3760
+ Object.defineProperty(TipAboveFeeCapError, "nodeMessage", {
3761
+ enumerable: true,
3762
+ configurable: true,
3763
+ writable: true,
3764
+ value: /max priority fee per gas higher than max fee per gas|tip higher than fee cap/
3765
+ });
3766
+
3767
+ // node_modules/viem/_esm/utils/data/slice.js
3768
+ function slice(value, start, end, { strict } = {}) {
3769
+ if (isHex(value, { strict: false }))
3770
+ return sliceHex(value, start, end, {
3771
+ strict
3772
+ });
3773
+ return sliceBytes(value, start, end, {
3774
+ strict
3775
+ });
3776
+ }
3777
+ function assertStartOffset(value, start) {
3778
+ if (typeof start === "number" && start > 0 && start > size(value) - 1)
3779
+ throw new SliceOffsetOutOfBoundsError({
3780
+ offset: start,
3781
+ position: "start",
3782
+ size: size(value)
3783
+ });
3784
+ }
3785
+ function assertEndOffset(value, start, end) {
3786
+ if (typeof start === "number" && typeof end === "number" && size(value) !== end - start) {
3787
+ throw new SliceOffsetOutOfBoundsError({
3788
+ offset: end,
3789
+ position: "end",
3790
+ size: size(value)
3791
+ });
3792
+ }
3793
+ }
3794
+ function sliceBytes(value_, start, end, { strict } = {}) {
3795
+ assertStartOffset(value_, start);
3796
+ const value = value_.slice(start, end);
3797
+ if (strict)
3798
+ assertEndOffset(value, start, end);
3799
+ return value;
3800
+ }
3801
+ function sliceHex(value_, start, end, { strict } = {}) {
3802
+ assertStartOffset(value_, start);
3803
+ const value = `0x${value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`;
3804
+ if (strict)
3805
+ assertEndOffset(value, start, end);
3806
+ return value;
3807
+ }
3808
+
3809
+ // node_modules/viem/_esm/utils/transaction/assertTransaction.js
3810
+ function assertTransactionEIP7702(transaction) {
3811
+ const { authorizationList } = transaction;
3812
+ if (authorizationList) {
3813
+ for (const authorization of authorizationList) {
3814
+ const { chainId } = authorization;
3815
+ const address = authorization.address;
3816
+ if (!isAddress(address))
3817
+ throw new InvalidAddressError({ address });
3818
+ if (chainId < 0)
3819
+ throw new InvalidChainIdError({ chainId });
3820
+ }
3821
+ }
3822
+ assertTransactionEIP1559(transaction);
3823
+ }
3824
+ function assertTransactionEIP4844(transaction) {
3825
+ const { blobVersionedHashes } = transaction;
3826
+ if (blobVersionedHashes) {
3827
+ if (blobVersionedHashes.length === 0)
3828
+ throw new EmptyBlobError();
3829
+ for (const hash of blobVersionedHashes) {
3830
+ const size_ = size(hash);
3831
+ const version2 = hexToNumber2(slice(hash, 0, 1));
3832
+ if (size_ !== 32)
3833
+ throw new InvalidVersionedHashSizeError({ hash, size: size_ });
3834
+ if (version2 !== versionedHashVersionKzg)
3835
+ throw new InvalidVersionedHashVersionError({
3836
+ hash,
3837
+ version: version2
3838
+ });
3839
+ }
3840
+ }
3841
+ assertTransactionEIP1559(transaction);
3842
+ }
3843
+ function assertTransactionEIP1559(transaction) {
3844
+ const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction;
3845
+ if (chainId <= 0)
3846
+ throw new InvalidChainIdError({ chainId });
3847
+ if (to && !isAddress(to))
3848
+ throw new InvalidAddressError({ address: to });
3849
+ if (maxFeePerGas && maxFeePerGas > maxUint256)
3850
+ throw new FeeCapTooHighError({ maxFeePerGas });
3851
+ if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas)
3852
+ throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });
3853
+ }
3854
+ function assertTransactionEIP2930(transaction) {
3855
+ const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;
3856
+ if (chainId <= 0)
3857
+ throw new InvalidChainIdError({ chainId });
3858
+ if (to && !isAddress(to))
3859
+ throw new InvalidAddressError({ address: to });
3860
+ if (maxPriorityFeePerGas || maxFeePerGas)
3861
+ throw new BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");
3862
+ if (gasPrice && gasPrice > maxUint256)
3863
+ throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });
3864
+ }
3865
+ function assertTransactionLegacy(transaction) {
3866
+ const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;
3867
+ if (to && !isAddress(to))
3868
+ throw new InvalidAddressError({ address: to });
3869
+ if (typeof chainId !== "undefined" && chainId <= 0)
3870
+ throw new InvalidChainIdError({ chainId });
3871
+ if (maxPriorityFeePerGas || maxFeePerGas)
3872
+ throw new BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");
3873
+ if (gasPrice && gasPrice > maxUint256)
3874
+ throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });
3875
+ }
3876
+
3877
+ // node_modules/viem/_esm/utils/transaction/getTransactionType.js
3878
+ function getTransactionType(transaction) {
3879
+ if (transaction.type)
3880
+ return transaction.type;
3881
+ if (typeof transaction.authorizationList !== "undefined")
3882
+ return "eip7702";
3883
+ if (typeof transaction.blobs !== "undefined" || typeof transaction.blobVersionedHashes !== "undefined" || typeof transaction.maxFeePerBlobGas !== "undefined" || typeof transaction.sidecars !== "undefined")
3884
+ return "eip4844";
3885
+ if (typeof transaction.maxFeePerGas !== "undefined" || typeof transaction.maxPriorityFeePerGas !== "undefined") {
3886
+ return "eip1559";
3887
+ }
3888
+ if (typeof transaction.gasPrice !== "undefined") {
3889
+ if (typeof transaction.accessList !== "undefined")
3890
+ return "eip2930";
3891
+ return "legacy";
3892
+ }
3893
+ throw new InvalidSerializableTransactionError({ transaction });
3894
+ }
3895
+
3896
+ // node_modules/viem/_esm/utils/transaction/serializeAccessList.js
3897
+ function serializeAccessList(accessList) {
3898
+ if (!accessList || accessList.length === 0)
3899
+ return [];
3900
+ const serializedAccessList = [];
3901
+ for (let i = 0; i < accessList.length; i++) {
3902
+ const { address, storageKeys } = accessList[i];
3903
+ for (let j = 0; j < storageKeys.length; j++) {
3904
+ if (storageKeys[j].length - 2 !== 64) {
3905
+ throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] });
3906
+ }
3907
+ }
3908
+ if (!isAddress(address, { strict: false })) {
3909
+ throw new InvalidAddressError({ address });
3910
+ }
3911
+ serializedAccessList.push([address, storageKeys]);
3912
+ }
3913
+ return serializedAccessList;
3914
+ }
3915
+
3916
+ // node_modules/viem/_esm/utils/transaction/serializeTransaction.js
3917
+ function serializeTransaction(transaction, signature) {
3918
+ const type = getTransactionType(transaction);
3919
+ if (type === "eip1559")
3920
+ return serializeTransactionEIP1559(transaction, signature);
3921
+ if (type === "eip2930")
3922
+ return serializeTransactionEIP2930(transaction, signature);
3923
+ if (type === "eip4844")
3924
+ return serializeTransactionEIP4844(transaction, signature);
3925
+ if (type === "eip7702")
3926
+ return serializeTransactionEIP7702(transaction, signature);
3927
+ return serializeTransactionLegacy(transaction, signature);
3928
+ }
3929
+ function serializeTransactionEIP7702(transaction, signature) {
3930
+ const { authorizationList, chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
3931
+ assertTransactionEIP7702(transaction);
3932
+ const serializedAccessList = serializeAccessList(accessList);
3933
+ const serializedAuthorizationList = serializeAuthorizationList(authorizationList);
3934
+ return concatHex([
3935
+ "0x04",
3936
+ toRlp([
3937
+ numberToHex(chainId),
3938
+ nonce ? numberToHex(nonce) : "0x",
3939
+ maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x",
3940
+ maxFeePerGas ? numberToHex(maxFeePerGas) : "0x",
3941
+ gas ? numberToHex(gas) : "0x",
3942
+ to ?? "0x",
3943
+ value ? numberToHex(value) : "0x",
3944
+ data ?? "0x",
3945
+ serializedAccessList,
3946
+ serializedAuthorizationList,
3947
+ ...toYParitySignatureArray(transaction, signature)
3948
+ ])
3949
+ ]);
3950
+ }
3951
+ function serializeTransactionEIP4844(transaction, signature) {
3952
+ const { chainId, gas, nonce, to, value, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
3953
+ assertTransactionEIP4844(transaction);
3954
+ let blobVersionedHashes = transaction.blobVersionedHashes;
3955
+ let sidecars = transaction.sidecars;
3956
+ if (transaction.blobs && (typeof blobVersionedHashes === "undefined" || typeof sidecars === "undefined")) {
3957
+ const blobs2 = typeof transaction.blobs[0] === "string" ? transaction.blobs : transaction.blobs.map((x) => bytesToHex2(x));
3958
+ const kzg = transaction.kzg;
3959
+ const commitments2 = blobsToCommitments({
3960
+ blobs: blobs2,
3961
+ kzg
3962
+ });
3963
+ if (typeof blobVersionedHashes === "undefined")
3964
+ blobVersionedHashes = commitmentsToVersionedHashes({
3965
+ commitments: commitments2
3966
+ });
3967
+ if (typeof sidecars === "undefined") {
3968
+ const proofs2 = blobsToProofs({ blobs: blobs2, commitments: commitments2, kzg });
3969
+ sidecars = toBlobSidecars({ blobs: blobs2, commitments: commitments2, proofs: proofs2 });
3970
+ }
3971
+ }
3972
+ const serializedAccessList = serializeAccessList(accessList);
3973
+ const serializedTransaction = [
3974
+ numberToHex(chainId),
3975
+ nonce ? numberToHex(nonce) : "0x",
3976
+ maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x",
3977
+ maxFeePerGas ? numberToHex(maxFeePerGas) : "0x",
3978
+ gas ? numberToHex(gas) : "0x",
3979
+ to ?? "0x",
3980
+ value ? numberToHex(value) : "0x",
3981
+ data ?? "0x",
3982
+ serializedAccessList,
3983
+ maxFeePerBlobGas ? numberToHex(maxFeePerBlobGas) : "0x",
3984
+ blobVersionedHashes ?? [],
3985
+ ...toYParitySignatureArray(transaction, signature)
3986
+ ];
3987
+ const blobs = [];
3988
+ const commitments = [];
3989
+ const proofs = [];
3990
+ if (sidecars)
3991
+ for (let i = 0; i < sidecars.length; i++) {
3992
+ const { blob, commitment, proof } = sidecars[i];
3993
+ blobs.push(blob);
3994
+ commitments.push(commitment);
3995
+ proofs.push(proof);
3996
+ }
3997
+ return concatHex([
3998
+ "0x03",
3999
+ sidecars ? (
4000
+ // If sidecars are enabled, envelope turns into a "wrapper":
4001
+ toRlp([serializedTransaction, blobs, commitments, proofs])
4002
+ ) : (
4003
+ // If sidecars are disabled, standard envelope is used:
4004
+ toRlp(serializedTransaction)
4005
+ )
4006
+ ]);
4007
+ }
4008
+ function serializeTransactionEIP1559(transaction, signature) {
4009
+ const { chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
4010
+ assertTransactionEIP1559(transaction);
4011
+ const serializedAccessList = serializeAccessList(accessList);
4012
+ const serializedTransaction = [
4013
+ numberToHex(chainId),
4014
+ nonce ? numberToHex(nonce) : "0x",
4015
+ maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x",
4016
+ maxFeePerGas ? numberToHex(maxFeePerGas) : "0x",
4017
+ gas ? numberToHex(gas) : "0x",
4018
+ to ?? "0x",
4019
+ value ? numberToHex(value) : "0x",
4020
+ data ?? "0x",
4021
+ serializedAccessList,
4022
+ ...toYParitySignatureArray(transaction, signature)
4023
+ ];
4024
+ return concatHex([
4025
+ "0x02",
4026
+ toRlp(serializedTransaction)
4027
+ ]);
4028
+ }
4029
+ function serializeTransactionEIP2930(transaction, signature) {
4030
+ const { chainId, gas, data, nonce, to, value, accessList, gasPrice } = transaction;
4031
+ assertTransactionEIP2930(transaction);
4032
+ const serializedAccessList = serializeAccessList(accessList);
4033
+ const serializedTransaction = [
4034
+ numberToHex(chainId),
4035
+ nonce ? numberToHex(nonce) : "0x",
4036
+ gasPrice ? numberToHex(gasPrice) : "0x",
4037
+ gas ? numberToHex(gas) : "0x",
4038
+ to ?? "0x",
4039
+ value ? numberToHex(value) : "0x",
4040
+ data ?? "0x",
4041
+ serializedAccessList,
4042
+ ...toYParitySignatureArray(transaction, signature)
4043
+ ];
4044
+ return concatHex([
4045
+ "0x01",
4046
+ toRlp(serializedTransaction)
4047
+ ]);
4048
+ }
4049
+ function serializeTransactionLegacy(transaction, signature) {
4050
+ const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction;
4051
+ assertTransactionLegacy(transaction);
4052
+ let serializedTransaction = [
4053
+ nonce ? numberToHex(nonce) : "0x",
4054
+ gasPrice ? numberToHex(gasPrice) : "0x",
4055
+ gas ? numberToHex(gas) : "0x",
4056
+ to ?? "0x",
4057
+ value ? numberToHex(value) : "0x",
4058
+ data ?? "0x"
4059
+ ];
4060
+ if (signature) {
4061
+ const v = (() => {
4062
+ if (signature.v >= 35n) {
4063
+ const inferredChainId = (signature.v - 35n) / 2n;
4064
+ if (inferredChainId > 0)
4065
+ return signature.v;
4066
+ return 27n + (signature.v === 35n ? 0n : 1n);
4067
+ }
4068
+ if (chainId > 0)
4069
+ return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n);
4070
+ const v2 = 27n + (signature.v === 27n ? 0n : 1n);
4071
+ if (signature.v !== v2)
4072
+ throw new InvalidLegacyVError({ v: signature.v });
4073
+ return v2;
4074
+ })();
4075
+ const r = trim(signature.r);
4076
+ const s = trim(signature.s);
4077
+ serializedTransaction = [
4078
+ ...serializedTransaction,
4079
+ numberToHex(v),
4080
+ r === "0x00" ? "0x" : r,
4081
+ s === "0x00" ? "0x" : s
4082
+ ];
4083
+ } else if (chainId > 0) {
4084
+ serializedTransaction = [
4085
+ ...serializedTransaction,
4086
+ numberToHex(chainId),
4087
+ "0x",
4088
+ "0x"
4089
+ ];
4090
+ }
4091
+ return toRlp(serializedTransaction);
4092
+ }
4093
+ function toYParitySignatureArray(transaction, signature_) {
4094
+ const signature = signature_ ?? transaction;
4095
+ const { v, yParity } = signature;
4096
+ if (typeof signature.r === "undefined")
4097
+ return [];
4098
+ if (typeof signature.s === "undefined")
4099
+ return [];
4100
+ if (typeof v === "undefined" && typeof yParity === "undefined")
4101
+ return [];
4102
+ const r = trim(signature.r);
4103
+ const s = trim(signature.s);
4104
+ const yParity_ = (() => {
4105
+ if (typeof yParity === "number")
4106
+ return yParity ? numberToHex(1) : "0x";
4107
+ if (v === 0n)
4108
+ return "0x";
4109
+ if (v === 1n)
4110
+ return numberToHex(1);
4111
+ return v === 27n ? "0x" : numberToHex(1);
4112
+ })();
4113
+ return [yParity_, r === "0x00" ? "0x" : r, s === "0x00" ? "0x" : s];
4114
+ }
4115
+
4116
+ // node_modules/viem/_esm/accounts/utils/signTransaction.js
4117
+ async function signTransaction(parameters) {
4118
+ const { privateKey, transaction, serializer = serializeTransaction } = parameters;
4119
+ const signableTransaction = (() => {
4120
+ if (transaction.type === "eip4844")
4121
+ return {
4122
+ ...transaction,
4123
+ sidecars: false
4124
+ };
4125
+ return transaction;
4126
+ })();
4127
+ const signature = await sign({
4128
+ hash: keccak256(await serializer(signableTransaction)),
4129
+ privateKey
4130
+ });
4131
+ return await serializer(transaction, signature);
4132
+ }
4133
+
4134
+ // node_modules/viem/_esm/errors/abi.js
4135
+ var AbiEncodingArrayLengthMismatchError = class extends BaseError {
4136
+ constructor({ expectedLength, givenLength, type }) {
4137
+ super([
4138
+ `ABI encoding array length mismatch for type ${type}.`,
4139
+ `Expected length: ${expectedLength}`,
4140
+ `Given length: ${givenLength}`
4141
+ ].join("\n"), { name: "AbiEncodingArrayLengthMismatchError" });
4142
+ }
4143
+ };
4144
+ var AbiEncodingBytesSizeMismatchError = class extends BaseError {
4145
+ constructor({ expectedSize, value }) {
4146
+ super(`Size of bytes "${value}" (bytes${size(value)}) does not match expected size (bytes${expectedSize}).`, { name: "AbiEncodingBytesSizeMismatchError" });
4147
+ }
4148
+ };
4149
+ var AbiEncodingLengthMismatchError = class extends BaseError {
4150
+ constructor({ expectedLength, givenLength }) {
4151
+ super([
4152
+ "ABI encoding params/values length mismatch.",
4153
+ `Expected length (params): ${expectedLength}`,
4154
+ `Given length (values): ${givenLength}`
4155
+ ].join("\n"), { name: "AbiEncodingLengthMismatchError" });
4156
+ }
4157
+ };
4158
+ var BytesSizeMismatchError = class extends BaseError {
4159
+ constructor({ expectedSize, givenSize }) {
4160
+ super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, {
4161
+ name: "BytesSizeMismatchError"
4162
+ });
4163
+ }
4164
+ };
4165
+ var InvalidAbiEncodingTypeError = class extends BaseError {
4166
+ constructor(type, { docsPath }) {
4167
+ super([
4168
+ `Type "${type}" is not a valid encoding type.`,
4169
+ "Please provide a valid ABI type."
4170
+ ].join("\n"), { docsPath, name: "InvalidAbiEncodingType" });
4171
+ }
4172
+ };
4173
+ var InvalidArrayError = class extends BaseError {
4174
+ constructor(value) {
4175
+ super([`Value "${value}" is not a valid array.`].join("\n"), {
4176
+ name: "InvalidArrayError"
4177
+ });
4178
+ }
4179
+ };
4180
+
4181
+ // node_modules/viem/_esm/utils/regex.js
4182
+ var bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;
4183
+ var integerRegex = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;
4184
+
4185
+ // node_modules/viem/_esm/utils/abi/encodeAbiParameters.js
4186
+ function encodeAbiParameters(params, values) {
4187
+ if (params.length !== values.length)
4188
+ throw new AbiEncodingLengthMismatchError({
4189
+ expectedLength: params.length,
4190
+ givenLength: values.length
4191
+ });
4192
+ const preparedParams = prepareParams({
4193
+ params,
4194
+ values
4195
+ });
4196
+ const data = encodeParams(preparedParams);
4197
+ if (data.length === 0)
4198
+ return "0x";
4199
+ return data;
4200
+ }
4201
+ function prepareParams({ params, values }) {
4202
+ const preparedParams = [];
4203
+ for (let i = 0; i < params.length; i++) {
4204
+ preparedParams.push(prepareParam({ param: params[i], value: values[i] }));
4205
+ }
4206
+ return preparedParams;
4207
+ }
4208
+ function prepareParam({ param, value }) {
4209
+ const arrayComponents = getArrayComponents(param.type);
4210
+ if (arrayComponents) {
4211
+ const [length, type] = arrayComponents;
4212
+ return encodeArray(value, { length, param: { ...param, type } });
4213
+ }
4214
+ if (param.type === "tuple") {
4215
+ return encodeTuple(value, {
4216
+ param
4217
+ });
4218
+ }
4219
+ if (param.type === "address") {
4220
+ return encodeAddress(value);
4221
+ }
4222
+ if (param.type === "bool") {
4223
+ return encodeBool(value);
4224
+ }
4225
+ if (param.type.startsWith("uint") || param.type.startsWith("int")) {
4226
+ const signed = param.type.startsWith("int");
4227
+ const [, , size2 = "256"] = integerRegex.exec(param.type) ?? [];
4228
+ return encodeNumber(value, {
4229
+ signed,
4230
+ size: Number(size2)
4231
+ });
4232
+ }
4233
+ if (param.type.startsWith("bytes")) {
4234
+ return encodeBytes(value, { param });
4235
+ }
4236
+ if (param.type === "string") {
4237
+ return encodeString(value);
4238
+ }
4239
+ throw new InvalidAbiEncodingTypeError(param.type, {
4240
+ docsPath: "/docs/contract/encodeAbiParameters"
4241
+ });
4242
+ }
4243
+ function encodeParams(preparedParams) {
4244
+ let staticSize = 0;
4245
+ for (let i = 0; i < preparedParams.length; i++) {
4246
+ const { dynamic, encoded } = preparedParams[i];
4247
+ if (dynamic)
4248
+ staticSize += 32;
4249
+ else
4250
+ staticSize += size(encoded);
4251
+ }
4252
+ const staticParams = [];
4253
+ const dynamicParams = [];
4254
+ let dynamicSize = 0;
4255
+ for (let i = 0; i < preparedParams.length; i++) {
4256
+ const { dynamic, encoded } = preparedParams[i];
4257
+ if (dynamic) {
4258
+ staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 }));
4259
+ dynamicParams.push(encoded);
4260
+ dynamicSize += size(encoded);
4261
+ } else {
4262
+ staticParams.push(encoded);
4263
+ }
4264
+ }
4265
+ return concat([...staticParams, ...dynamicParams]);
4266
+ }
4267
+ function encodeAddress(value) {
4268
+ if (!isAddress(value))
4269
+ throw new InvalidAddressError({ address: value });
4270
+ return { dynamic: false, encoded: padHex(value.toLowerCase()) };
4271
+ }
4272
+ function encodeArray(value, { length, param }) {
4273
+ const dynamic = length === null;
4274
+ if (!Array.isArray(value))
4275
+ throw new InvalidArrayError(value);
4276
+ if (!dynamic && value.length !== length)
4277
+ throw new AbiEncodingArrayLengthMismatchError({
4278
+ expectedLength: length,
4279
+ givenLength: value.length,
4280
+ type: `${param.type}[${length}]`
4281
+ });
4282
+ let dynamicChild = false;
4283
+ const preparedParams = [];
4284
+ for (let i = 0; i < value.length; i++) {
4285
+ const preparedParam = prepareParam({ param, value: value[i] });
4286
+ if (preparedParam.dynamic)
4287
+ dynamicChild = true;
4288
+ preparedParams.push(preparedParam);
4289
+ }
4290
+ if (dynamic || dynamicChild) {
4291
+ const data = encodeParams(preparedParams);
4292
+ if (dynamic) {
4293
+ const length2 = numberToHex(preparedParams.length, { size: 32 });
4294
+ return {
4295
+ dynamic: true,
4296
+ encoded: preparedParams.length > 0 ? concat([length2, data]) : length2
4297
+ };
4298
+ }
4299
+ if (dynamicChild)
4300
+ return { dynamic: true, encoded: data };
4301
+ }
4302
+ return {
4303
+ dynamic: false,
4304
+ encoded: concat(preparedParams.map(({ encoded }) => encoded))
4305
+ };
4306
+ }
4307
+ function encodeBytes(value, { param }) {
4308
+ const [, paramSize] = param.type.split("bytes");
4309
+ const bytesSize = size(value);
4310
+ if (!paramSize) {
4311
+ let value_ = value;
4312
+ if (bytesSize % 32 !== 0)
4313
+ value_ = padHex(value_, {
4314
+ dir: "right",
4315
+ size: Math.ceil((value.length - 2) / 2 / 32) * 32
4316
+ });
4317
+ return {
4318
+ dynamic: true,
4319
+ encoded: concat([padHex(numberToHex(bytesSize, { size: 32 })), value_])
4320
+ };
4321
+ }
4322
+ if (bytesSize !== Number.parseInt(paramSize, 10))
4323
+ throw new AbiEncodingBytesSizeMismatchError({
4324
+ expectedSize: Number.parseInt(paramSize, 10),
4325
+ value
4326
+ });
4327
+ return { dynamic: false, encoded: padHex(value, { dir: "right" }) };
4328
+ }
4329
+ function encodeBool(value) {
4330
+ if (typeof value !== "boolean")
4331
+ throw new BaseError(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`);
4332
+ return { dynamic: false, encoded: padHex(boolToHex(value)) };
4333
+ }
4334
+ function encodeNumber(value, { signed, size: size2 = 256 }) {
4335
+ if (typeof size2 === "number") {
4336
+ const max = 2n ** (BigInt(size2) - (signed ? 1n : 0n)) - 1n;
4337
+ const min = signed ? -max - 1n : 0n;
4338
+ if (value > max || value < min)
4339
+ throw new IntegerOutOfRangeError({
4340
+ max: max.toString(),
4341
+ min: min.toString(),
4342
+ signed,
4343
+ size: size2 / 8,
4344
+ value: value.toString()
4345
+ });
4346
+ }
4347
+ return {
4348
+ dynamic: false,
4349
+ encoded: numberToHex(value, {
4350
+ size: 32,
4351
+ signed
4352
+ })
4353
+ };
4354
+ }
4355
+ function encodeString(value) {
4356
+ const hexValue = stringToHex(value);
4357
+ const partsLength = Math.ceil(size(hexValue) / 32);
4358
+ const parts = [];
4359
+ for (let i = 0; i < partsLength; i++) {
4360
+ parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), {
4361
+ dir: "right"
4362
+ }));
4363
+ }
4364
+ return {
4365
+ dynamic: true,
4366
+ encoded: concat([
4367
+ padHex(numberToHex(size(hexValue), { size: 32 })),
4368
+ ...parts
4369
+ ])
4370
+ };
4371
+ }
4372
+ function encodeTuple(value, { param }) {
4373
+ let dynamic = false;
4374
+ const preparedParams = [];
4375
+ for (let i = 0; i < param.components.length; i++) {
4376
+ const param_ = param.components[i];
4377
+ const index = Array.isArray(value) ? i : param_.name;
4378
+ const preparedParam = prepareParam({
4379
+ param: param_,
4380
+ value: value[index]
4381
+ });
4382
+ preparedParams.push(preparedParam);
4383
+ if (preparedParam.dynamic)
4384
+ dynamic = true;
4385
+ }
4386
+ return {
4387
+ dynamic,
4388
+ encoded: dynamic ? encodeParams(preparedParams) : concat(preparedParams.map(({ encoded }) => encoded))
4389
+ };
4390
+ }
4391
+ function getArrayComponents(type) {
4392
+ const matches = type.match(/^(.*)\[(\d+)?\]$/);
4393
+ return matches ? (
4394
+ // Return `null` if the array is dynamic.
4395
+ [matches[2] ? Number(matches[2]) : null, matches[1]]
4396
+ ) : void 0;
4397
+ }
4398
+
4399
+ // node_modules/viem/_esm/utils/stringify.js
4400
+ var stringify = (value, replacer, space) => JSON.stringify(value, (key, value_) => {
4401
+ const value2 = typeof value_ === "bigint" ? value_.toString() : value_;
4402
+ return typeof replacer === "function" ? replacer(key, value2) : value2;
4403
+ }, space);
4404
+
4405
+ // node_modules/viem/_esm/errors/typedData.js
4406
+ var InvalidDomainError = class extends BaseError {
4407
+ constructor({ domain }) {
4408
+ super(`Invalid domain "${stringify(domain)}".`, {
4409
+ metaMessages: ["Must be a valid EIP-712 domain."]
4410
+ });
4411
+ }
4412
+ };
4413
+ var InvalidPrimaryTypeError = class extends BaseError {
4414
+ constructor({ primaryType, types }) {
4415
+ super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types))}\`.`, {
4416
+ docsPath: "/api/glossary/Errors#typeddatainvalidprimarytypeerror",
4417
+ metaMessages: ["Check that the primary type is a key in `types`."]
4418
+ });
4419
+ }
4420
+ };
4421
+ var InvalidStructTypeError = class extends BaseError {
4422
+ constructor({ type }) {
4423
+ super(`Struct type "${type}" is invalid.`, {
4424
+ metaMessages: ["Struct type must not be a Solidity type."],
4425
+ name: "InvalidStructTypeError"
4426
+ });
4427
+ }
4428
+ };
4429
+
4430
+ // node_modules/viem/_esm/utils/typedData.js
4431
+ function validateTypedData(parameters) {
4432
+ const { domain, message, primaryType, types } = parameters;
4433
+ const validateData = (struct, data) => {
4434
+ for (const param of struct) {
4435
+ const { name, type } = param;
4436
+ const value = data[name];
4437
+ const integerMatch = type.match(integerRegex);
4438
+ if (integerMatch && (typeof value === "number" || typeof value === "bigint")) {
4439
+ const [_type, base, size_] = integerMatch;
4440
+ numberToHex(value, {
4441
+ signed: base === "int",
4442
+ size: Number.parseInt(size_, 10) / 8
4443
+ });
4444
+ }
4445
+ if (type === "address" && typeof value === "string" && !isAddress(value))
4446
+ throw new InvalidAddressError({ address: value });
4447
+ const bytesMatch = type.match(bytesRegex);
4448
+ if (bytesMatch) {
4449
+ const [_type, size_] = bytesMatch;
4450
+ if (size_ && size(value) !== Number.parseInt(size_, 10))
4451
+ throw new BytesSizeMismatchError({
4452
+ expectedSize: Number.parseInt(size_, 10),
4453
+ givenSize: size(value)
4454
+ });
4455
+ }
4456
+ const struct2 = types[type];
4457
+ if (struct2) {
4458
+ validateReference(type);
4459
+ validateData(struct2, value);
4460
+ }
4461
+ }
4462
+ };
4463
+ if (types.EIP712Domain && domain) {
4464
+ if (typeof domain !== "object")
4465
+ throw new InvalidDomainError({ domain });
4466
+ validateData(types.EIP712Domain, domain);
4467
+ }
4468
+ if (primaryType !== "EIP712Domain") {
4469
+ if (types[primaryType])
4470
+ validateData(types[primaryType], message);
4471
+ else
4472
+ throw new InvalidPrimaryTypeError({ primaryType, types });
4473
+ }
4474
+ }
4475
+ function getTypesForEIP712Domain({ domain }) {
4476
+ return [
4477
+ typeof domain?.name === "string" && { name: "name", type: "string" },
4478
+ domain?.version && { name: "version", type: "string" },
4479
+ (typeof domain?.chainId === "number" || typeof domain?.chainId === "bigint") && {
4480
+ name: "chainId",
4481
+ type: "uint256"
4482
+ },
4483
+ domain?.verifyingContract && {
4484
+ name: "verifyingContract",
4485
+ type: "address"
4486
+ },
4487
+ domain?.salt && { name: "salt", type: "bytes32" }
4488
+ ].filter(Boolean);
4489
+ }
4490
+ function validateReference(type) {
4491
+ if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int"))
4492
+ throw new InvalidStructTypeError({ type });
4493
+ }
4494
+
4495
+ // node_modules/viem/_esm/utils/signature/hashTypedData.js
4496
+ function hashTypedData(parameters) {
4497
+ const { domain = {}, message, primaryType } = parameters;
4498
+ const types = {
4499
+ EIP712Domain: getTypesForEIP712Domain({ domain }),
4500
+ ...parameters.types
4501
+ };
4502
+ validateTypedData({
4503
+ domain,
4504
+ message,
4505
+ primaryType,
4506
+ types
4507
+ });
4508
+ const parts = ["0x1901"];
4509
+ if (domain)
4510
+ parts.push(hashDomain({
4511
+ domain,
4512
+ types
4513
+ }));
4514
+ if (primaryType !== "EIP712Domain")
4515
+ parts.push(hashStruct({
4516
+ data: message,
4517
+ primaryType,
4518
+ types
4519
+ }));
4520
+ return keccak256(concat(parts));
4521
+ }
4522
+ function hashDomain({ domain, types }) {
4523
+ return hashStruct({
4524
+ data: domain,
4525
+ primaryType: "EIP712Domain",
4526
+ types
4527
+ });
4528
+ }
4529
+ function hashStruct({ data, primaryType, types }) {
4530
+ const encoded = encodeData({
4531
+ data,
4532
+ primaryType,
4533
+ types
4534
+ });
4535
+ return keccak256(encoded);
4536
+ }
4537
+ function encodeData({ data, primaryType, types }) {
4538
+ const encodedTypes = [{ type: "bytes32" }];
4539
+ const encodedValues = [hashType({ primaryType, types })];
4540
+ for (const field of types[primaryType]) {
4541
+ const [type, value] = encodeField({
4542
+ types,
4543
+ name: field.name,
4544
+ type: field.type,
4545
+ value: data[field.name]
4546
+ });
4547
+ encodedTypes.push(type);
4548
+ encodedValues.push(value);
4549
+ }
4550
+ return encodeAbiParameters(encodedTypes, encodedValues);
4551
+ }
4552
+ function hashType({ primaryType, types }) {
4553
+ const encodedHashType = toHex(encodeType({ primaryType, types }));
4554
+ return keccak256(encodedHashType);
4555
+ }
4556
+ function encodeType({ primaryType, types }) {
4557
+ let result = "";
4558
+ const unsortedDeps = findTypeDependencies({ primaryType, types });
4559
+ unsortedDeps.delete(primaryType);
4560
+ const deps = [primaryType, ...Array.from(unsortedDeps).sort()];
4561
+ for (const type of deps) {
4562
+ result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`;
4563
+ }
4564
+ return result;
4565
+ }
4566
+ function findTypeDependencies({ primaryType: primaryType_, types }, results = /* @__PURE__ */ new Set()) {
4567
+ const match = primaryType_.match(/^\w*/u);
4568
+ const primaryType = match?.[0];
4569
+ if (results.has(primaryType) || types[primaryType] === void 0) {
4570
+ return results;
4571
+ }
4572
+ results.add(primaryType);
4573
+ for (const field of types[primaryType]) {
4574
+ findTypeDependencies({ primaryType: field.type, types }, results);
4575
+ }
4576
+ return results;
4577
+ }
4578
+ function encodeField({ types, name, type, value }) {
4579
+ if (types[type] !== void 0) {
4580
+ return [
4581
+ { type: "bytes32" },
4582
+ keccak256(encodeData({ data: value, primaryType: type, types }))
4583
+ ];
4584
+ }
4585
+ if (type === "bytes")
4586
+ return [{ type: "bytes32" }, keccak256(value)];
4587
+ if (type === "string")
4588
+ return [{ type: "bytes32" }, keccak256(toHex(value))];
4589
+ if (type.lastIndexOf("]") === type.length - 1) {
4590
+ const parsedType = type.slice(0, type.lastIndexOf("["));
4591
+ const typeValuePairs = value.map((item) => encodeField({
4592
+ name,
4593
+ type: parsedType,
4594
+ types,
4595
+ value: item
4596
+ }));
4597
+ return [
4598
+ { type: "bytes32" },
4599
+ keccak256(encodeAbiParameters(typeValuePairs.map(([t]) => t), typeValuePairs.map(([, v]) => v)))
4600
+ ];
4601
+ }
4602
+ return [{ type }, value];
4603
+ }
4604
+
4605
+ // node_modules/viem/_esm/accounts/utils/signTypedData.js
4606
+ async function signTypedData(parameters) {
4607
+ const { privateKey, ...typedData } = parameters;
4608
+ return await sign({
4609
+ hash: hashTypedData(typedData),
4610
+ privateKey,
4611
+ to: "hex"
4612
+ });
4613
+ }
4614
+
4615
+ // node_modules/viem/_esm/accounts/privateKeyToAccount.js
4616
+ function privateKeyToAccount(privateKey, options = {}) {
4617
+ const { nonceManager } = options;
4618
+ const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false));
4619
+ const address = publicKeyToAddress(publicKey);
4620
+ const account = toAccount({
4621
+ address,
4622
+ nonceManager,
4623
+ async sign({ hash }) {
4624
+ return sign({ hash, privateKey, to: "hex" });
4625
+ },
4626
+ async signAuthorization(authorization) {
4627
+ return signAuthorization({ ...authorization, privateKey });
4628
+ },
4629
+ async signMessage({ message }) {
4630
+ return signMessage({ message, privateKey });
4631
+ },
4632
+ async signTransaction(transaction, { serializer } = {}) {
4633
+ return signTransaction({ privateKey, transaction, serializer });
4634
+ },
4635
+ async signTypedData(typedData) {
4636
+ return signTypedData({ ...typedData, privateKey });
4637
+ }
4638
+ });
4639
+ return {
4640
+ ...account,
4641
+ publicKey,
4642
+ source: "privateKey"
4643
+ };
4644
+ }
4645
+
4646
+ // ../api/src/core/errors.js
4647
+ function apiError(status, code, message, details) {
4648
+ const err = new Error(message);
4649
+ err.status = status;
4650
+ err.code = code;
4651
+ if (details !== void 0) err.details = details;
4652
+ return err;
4653
+ }
4654
+
4655
+ // ../api/src/core/onchain.js
4656
+ var TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
4657
+ var topicToAddress = (topic) => "0x" + String(topic).slice(-40).toLowerCase();
4658
+ var lc = (a) => String(a || "").toLowerCase();
4659
+ function createOnchainVerifier({
4660
+ rpcUrl,
4661
+ rpcUrls,
4662
+ usdcAddress,
4663
+ fetchImpl = globalThis.fetch,
4664
+ // A just-submitted payment can be mined on the payer's RPC yet not YET indexed by
4665
+ // ours (cross-RPC propagation lag), so a single receipt lookup returns null and the
4666
+ // chunk/settlement is wrongly rejected as tx_not_found_or_pending. Retry the receipt
4667
+ // a few times before giving up. Bounded so a genuinely-missing tx still fails fast.
4668
+ receiptRetries = 3,
4669
+ receiptRetryMs = 700,
4670
+ sleepImpl = (ms) => new Promise((r) => setTimeout(r, ms))
4671
+ } = {}) {
4672
+ const urls = (rpcUrls?.length ? rpcUrls : String(rpcUrl || "").split(",")).map((s) => String(s).trim()).filter(Boolean);
4673
+ const configured = Boolean(urls.length && usdcAddress);
4674
+ const usdc = lc(usdcAddress);
4675
+ async function rpc(method, params) {
4676
+ let lastErr;
4677
+ for (const url of urls) {
4678
+ try {
4679
+ const res = await fetchImpl(url, {
4680
+ method: "POST",
4681
+ headers: { "content-type": "application/json" },
4682
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params })
4683
+ });
4684
+ if (!res.ok) {
4685
+ lastErr = apiError(502, "rpc_error", `chain RPC returned ${res.status}`);
4686
+ continue;
4687
+ }
4688
+ const body = await res.json();
4689
+ if (body.error) {
4690
+ lastErr = apiError(502, "rpc_error", `chain RPC: ${body.error.message ?? "unknown"}`);
4691
+ continue;
4692
+ }
4693
+ return body.result;
4694
+ } catch (e) {
4695
+ lastErr = e;
4696
+ }
4697
+ }
4698
+ throw lastErr ?? apiError(502, "rpc_error", "no chain RPC configured");
4699
+ }
4700
+ return {
4701
+ configured,
4702
+ // Confirm txHash is a successful USDC transfer of >= minAtomic to `to`.
4703
+ // Returns { ok, reason?, from?, amount? }; never throws on a bad payment
4704
+ // (only on an RPC transport failure).
4705
+ async verifyTransfer(txHash, { to, minAtomic }) {
4706
+ let receipt = await rpc("eth_getTransactionReceipt", [txHash]);
4707
+ for (let i = 0; !receipt && i < receiptRetries; i++) {
4708
+ await sleepImpl(receiptRetryMs);
4709
+ receipt = await rpc("eth_getTransactionReceipt", [txHash]);
4710
+ }
4711
+ if (!receipt) return { ok: false, reason: "tx_not_found_or_pending" };
4712
+ if (receipt.status !== "0x1") return { ok: false, reason: "tx_failed" };
4713
+ const want = lc(to);
4714
+ const log = (receipt.logs || []).find(
4715
+ (l) => lc(l.address) === usdc && l.topics?.[0] === TRANSFER_TOPIC && topicToAddress(l.topics[2]) === want
4716
+ );
4717
+ if (!log) return { ok: false, reason: "no_matching_usdc_transfer" };
4718
+ const amount = BigInt(log.data);
4719
+ if (amount < BigInt(minAtomic)) return { ok: false, reason: "amount_too_low" };
4720
+ return { ok: true, from: topicToAddress(log.topics[1]), amount: amount.toString() };
4721
+ }
4722
+ };
4723
+ }
4724
+ function usdToAtomic(usd) {
4725
+ return BigInt(Math.round(Number(usd) * 1e6));
4726
+ }
4727
+
4728
+ // mtok-relay.mjs
4729
+ var CONTEXT_CEIL = 4096;
4730
+ var BALANCE_EPSILON = 1e-6;
4731
+ var args = process.argv.slice(2);
4732
+ var flag = (name) => {
4733
+ const i = args.indexOf(name);
4734
+ return i !== -1 ? args[i + 1] : null;
4735
+ };
4736
+ var offerId = flag("--offer");
4737
+ var MODEL = flag("--model");
4738
+ var upstream = (flag("--upstream") ?? "").replace(/\/$/, "");
4739
+ var apiBase = (flag("--api") ?? "https://mtok.market").replace(/\/$/, "");
4740
+ var port = Number(flag("--port") ?? 8788);
4741
+ var rpcFlag = flag("--rpc");
4742
+ var settlementPubkeyFlag = flag("--settlement-pubkey");
4743
+ var outPrice = Number(flag("--out-price") ?? 0);
4744
+ if (!offerId) {
4745
+ console.error("mtok-relay: --offer <id> is required");
4746
+ process.exit(1);
4747
+ }
4748
+ if (!MODEL) {
4749
+ console.error("mtok-relay: --model <id> is required (the offer model you serve)");
4750
+ process.exit(1);
4751
+ }
4752
+ if (!upstream) {
4753
+ console.error("mtok-relay: --upstream <url> is required");
4754
+ process.exit(1);
4755
+ }
4756
+ var MTOK_API_KEY = process.env.MTOK_API_KEY;
4757
+ var UPSTREAM_KEY = process.env.UPSTREAM_KEY;
4758
+ var RELAY_WALLET_KEY = process.env.RELAY_WALLET_KEY;
4759
+ if (!MTOK_API_KEY) {
4760
+ console.error("mtok-relay: MTOK_API_KEY env var is required");
4761
+ process.exit(1);
4762
+ }
4763
+ if (!UPSTREAM_KEY) {
4764
+ console.error("mtok-relay: UPSTREAM_KEY env var is required");
4765
+ process.exit(1);
4766
+ }
4767
+ if (!RELAY_WALLET_KEY && !settlementPubkeyFlag) {
4768
+ console.error("mtok-relay: RELAY_WALLET_KEY env var (or --settlement-pubkey) is required");
4769
+ process.exit(1);
4770
+ }
4771
+ var SETTLEMENT_ADDR;
4772
+ if (settlementPubkeyFlag) {
4773
+ SETTLEMENT_ADDR = settlementPubkeyFlag;
4774
+ } else {
4775
+ try {
4776
+ SETTLEMENT_ADDR = privateKeyToAccount(RELAY_WALLET_KEY.startsWith("0x") ? RELAY_WALLET_KEY : "0x" + RELAY_WALLET_KEY).address;
4777
+ } catch (e) {
4778
+ console.error("mtok-relay: invalid RELAY_WALLET_KEY \u2014", e.message);
4779
+ process.exit(1);
4780
+ }
4781
+ }
4782
+ function readBody(req) {
4783
+ return new Promise((resolve, reject) => {
4784
+ let raw = "";
4785
+ req.on("data", (d) => {
4786
+ raw += d;
4787
+ });
4788
+ req.on("end", () => {
4789
+ try {
4790
+ resolve(JSON.parse(raw || "{}"));
4791
+ } catch {
4792
+ resolve({});
4793
+ }
4794
+ });
4795
+ req.on("error", reject);
4796
+ });
4797
+ }
4798
+ function send(res, status, body) {
4799
+ const payload = JSON.stringify(body);
4800
+ res.writeHead(status, { "content-type": "application/json", "content-length": Buffer.byteLength(payload) });
4801
+ res.end(payload);
4802
+ }
4803
+ var feeAddress;
4804
+ var feeBps;
4805
+ var verifier;
4806
+ async function boot() {
4807
+ const r = await fetch(apiBase + "/api/config");
4808
+ if (!r.ok) throw new Error("config fetch failed: " + r.status);
4809
+ const config = await r.json();
4810
+ feeAddress = config.feeAddress;
4811
+ feeBps = config.feeBps;
4812
+ const chainId = Number(config.chainId ?? 8453);
4813
+ const rpcUrls = rpcFlag ? [rpcFlag] : chainId === 8453 ? ["https://mainnet.base.org", "https://base.llamarpc.com", "https://base-rpc.publicnode.com", "https://base.drpc.org"] : ["https://sepolia.base.org", "https://base-sepolia-rpc.publicnode.com"];
4814
+ verifier = createOnchainVerifier({ rpcUrls, usdcAddress: config.usdcAddress });
4815
+ if (!verifier.configured) throw new Error("onchain verifier not configured (missing usdcAddress in /api/config)");
4816
+ }
4817
+ async function reportToPlatform(reportBody) {
4818
+ const rr = await fetch(apiBase + "/api/chunks/report", {
4819
+ method: "POST",
4820
+ headers: { "content-type": "application/json", "x-api-key": MTOK_API_KEY },
4821
+ body: JSON.stringify(reportBody)
4822
+ });
4823
+ const body = await rr.json().catch(() => ({}));
4824
+ return { ok: rr.status === 201, status: rr.status, body, booking: body?.booking ?? null };
4825
+ }
4826
+ async function handleFund(body, res) {
4827
+ const { bookingId, n, sellerTxHash, feeTxHash, priceUsd, buyerId } = body;
4828
+ try {
4829
+ const sellerOk = (await verifier.verifyTransfer(sellerTxHash, { to: SETTLEMENT_ADDR, minAtomic: usdToAtomic(priceUsd) })).ok;
4830
+ const feeAtomic = usdToAtomic((Number(priceUsd) || 0) * (Number(feeBps) || 0) / 1e4);
4831
+ const feeOk = (await verifier.verifyTransfer(feeTxHash, { to: feeAddress, minAtomic: feeAtomic })).ok;
4832
+ if (!sellerOk || !feeOk) return send(res, 402, { error: "payment_unverified", detail: `seller=${sellerOk} fee=${feeOk}` });
4833
+ } catch (e) {
4834
+ return send(res, 402, { error: "payment_unverified", detail: e.message });
4835
+ }
4836
+ let rep;
4837
+ try {
4838
+ rep = await reportToPlatform(buildFundReport({ offerId, buyerId, bookingId, n, priceUsd, sellerTxHash, feeTxHash }));
4839
+ } catch (e) {
4840
+ return send(res, 502, { error: "report_failed", detail: e.message });
4841
+ }
4842
+ if (!rep.ok || !rep.booking) {
4843
+ console.error("mtok-relay: FUND report rejected (%d) for n=%d offerId=%s: %s", rep.status, n, offerId, JSON.stringify(rep.body));
4844
+ return send(res, 502, { error: "report_failed", detail: rep.body?.error || rep.status });
4845
+ }
4846
+ return send(res, 200, { ...rep.booking, _bookingId: rep.booking.id, remainingUsd: rep.booking.remainingUsd });
4847
+ }
4848
+ async function handleDraw(body, res) {
4849
+ const { bookingId, n, buyerId, request } = body;
4850
+ if (!bookingId) return send(res, 400, { error: "bad_request", detail: "DRAW needs bookingId" });
4851
+ let booking;
4852
+ try {
4853
+ const r = await fetch(apiBase + `/api/bookings/${encodeURIComponent(bookingId)}`, { headers: { "x-api-key": MTOK_API_KEY } });
4854
+ const rb = await r.json().catch(() => ({}));
4855
+ if (r.status !== 200 || !rb?.booking) return send(res, 502, { error: "booking_read_failed", detail: rb?.error || r.status });
4856
+ booking = rb.booking;
4857
+ } catch (e) {
4858
+ return send(res, 502, { error: "booking_read_failed", detail: e.message });
4859
+ }
4860
+ const remainingUsd = Number(booking.remainingUsd) || 0;
4861
+ if (remainingUsd <= BALANCE_EPSILON) {
4862
+ return send(res, 402, { error: "balance_exhausted", detail: `remainingUsd=${remainingUsd}`, _bookingId: bookingId, remainingUsd });
4863
+ }
4864
+ let maxTok = CONTEXT_CEIL;
4865
+ const reqMax = Number(request?.max_tokens);
4866
+ if (reqMax > 0) maxTok = Math.min(maxTok, Math.floor(reqMax));
4867
+ if (outPrice > 0) maxTok = Math.min(maxTok, Math.floor(remainingUsd / outPrice * 1e6));
4868
+ const safeRequest = { ...request, max_tokens: Math.max(1, maxTok) };
4869
+ let completion;
4870
+ try {
4871
+ const upstreamRes = await fetch(upstream + "/v1/chat/completions", {
4872
+ method: "POST",
4873
+ headers: { "content-type": "application/json", authorization: "Bearer " + UPSTREAM_KEY },
4874
+ body: JSON.stringify(safeRequest)
4875
+ });
4876
+ completion = await upstreamRes.json();
4877
+ } catch (e) {
4878
+ return send(res, 502, { error: "upstream_error", detail: e.message });
4879
+ }
4880
+ try {
4881
+ enforceModelEcho(completion.model, MODEL);
4882
+ } catch (e) {
4883
+ return send(res, 502, { error: "model_mismatch", detail: e.message });
4884
+ }
4885
+ let rep;
4886
+ try {
4887
+ rep = await reportToPlatform(buildDrawReport({ offerId, buyerId, bookingId, n, usage: completion.usage }));
4888
+ } catch (e) {
4889
+ console.error("mtok-relay: DRAW report failed (network) for n=%d offerId=%s: %s", n, offerId, e.message);
4890
+ return send(res, 502, { error: "report_failed", detail: e.message, completion });
4891
+ }
4892
+ if (!rep.ok || !rep.booking) {
4893
+ console.error("mtok-relay: DRAW report rejected (%d) for n=%d offerId=%s: %s", rep.status, n, offerId, JSON.stringify(rep.body));
4894
+ return send(res, rep.status === 402 ? 402 : 502, { error: rep.body?.error?.code || rep.body?.error || "report_failed", detail: rep.body?.error?.message || rep.status, completion, _bookingId: bookingId });
4895
+ }
4896
+ return send(res, 200, { ...completion, _bookingId: rep.booking.id, remainingUsd: rep.booking.remainingUsd });
4897
+ }
4898
+ var server = http.createServer(async (req, res) => {
4899
+ if (req.method !== "POST" || req.url !== "/chunk") {
4900
+ return send(res, 404, { error: "not found" });
4901
+ }
4902
+ let body;
4903
+ try {
4904
+ body = await readBody(req);
4905
+ } catch {
4906
+ return send(res, 400, { error: "bad body" });
4907
+ }
4908
+ const hasFund = body.sellerTxHash != null && body.sellerTxHash !== "";
4909
+ const hasDraw = body.request != null;
4910
+ if (hasFund && hasDraw) return send(res, 400, { error: "bad_request", detail: "send a FUND (sellerTxHash) or a DRAW (request), not both" });
4911
+ if (hasFund) return handleFund(body, res);
4912
+ if (hasDraw) return handleDraw(body, res);
4913
+ return send(res, 400, { error: "bad_request", detail: "need a FUND (sellerTxHash) or a DRAW (request)" });
4914
+ });
4915
+ boot().then(() => {
4916
+ server.listen(port, () => {
4917
+ console.log(`mtok-relay: listening on port ${port} offer=${offerId} model=${MODEL} upstream=${upstream} api=${apiBase} settlement=${SETTLEMENT_ADDR}`);
4918
+ });
4919
+ }).catch((e) => {
4920
+ console.error("mtok-relay: boot failed \u2014", e.message);
4921
+ process.exit(1);
4922
+ });