@fastnear/api 0.1.0 → 0.4.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 (44) hide show
  1. package/dist/cjs/cryptoUtils.js +89 -0
  2. package/dist/cjs/cryptoUtils.js.map +7 -0
  3. package/dist/cjs/index.esm.js +1219 -0
  4. package/dist/cjs/index.esm.js.map +7 -0
  5. package/dist/cjs/index.js +1274 -0
  6. package/dist/cjs/index.js.map +7 -0
  7. package/dist/cjs/near.js +1219 -0
  8. package/dist/cjs/near.js.map +7 -0
  9. package/dist/cjs/transaction.js +360 -0
  10. package/dist/cjs/transaction.js.map +7 -0
  11. package/dist/cjs/utils.js +105 -0
  12. package/dist/cjs/utils.js.map +7 -0
  13. package/dist/esm/chunk-2SCAGR3F.js +68 -0
  14. package/dist/esm/chunk-2SCAGR3F.js.map +7 -0
  15. package/dist/esm/chunk-OR3WITSY.js +842 -0
  16. package/dist/esm/chunk-OR3WITSY.js.map +7 -0
  17. package/dist/esm/chunk-S5Q2EM2B.js +48 -0
  18. package/dist/esm/chunk-S5Q2EM2B.js.map +7 -0
  19. package/{src/transaction.js → dist/esm/chunk-YKPILPMX.js} +113 -99
  20. package/dist/esm/chunk-YKPILPMX.js.map +7 -0
  21. package/dist/esm/cryptoUtils.js +21 -0
  22. package/dist/esm/cryptoUtils.js.map +7 -0
  23. package/dist/esm/index.esm.js +13 -0
  24. package/dist/esm/index.esm.js.map +7 -0
  25. package/dist/esm/index.js +63 -0
  26. package/dist/esm/index.js.map +7 -0
  27. package/dist/esm/near.js +15 -0
  28. package/dist/esm/near.js.map +7 -0
  29. package/dist/esm/transaction.js +16 -0
  30. package/dist/esm/transaction.js.map +7 -0
  31. package/dist/esm/utils.js +24 -0
  32. package/dist/esm/utils.js.map +7 -0
  33. package/dist/umd/index.js +4227 -0
  34. package/dist/umd/index.js.map +7 -0
  35. package/package.json +35 -25
  36. package/README.md +0 -76
  37. package/dist/fastnear.cjs +0 -35
  38. package/dist/fastnear.ejs +0 -24
  39. package/dist/fastnear.js +0 -35
  40. package/src/crypto.js +0 -37
  41. package/src/index.esm.js +0 -3
  42. package/src/index.js +0 -8
  43. package/src/near.js +0 -566
  44. package/src/utils.js +0 -48
@@ -0,0 +1,4227 @@
1
+ /* ⋈ 🏃🏻💨 FastNEAR API - https://github.com/fastnear */
2
+ var FastNear = (() => {
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
20
+
21
+ // src/index.ts
22
+ var src_exports = {};
23
+ __export(src_exports, {
24
+ SCHEMA: () => SCHEMA,
25
+ api: () => api,
26
+ canSignWithLAK: () => canSignWithLAK,
27
+ convertUnit: () => convertUnit,
28
+ deepCopy: () => deepCopy,
29
+ fromBase58: () => base58_to_binary_default,
30
+ fromBase64: () => fromBase64,
31
+ keyFromString: () => keyFromString,
32
+ keyToString: () => keyToString,
33
+ lsGet: () => lsGet,
34
+ lsSet: () => lsSet,
35
+ mapAction: () => mapAction,
36
+ near: () => api,
37
+ parseJsonFromBytes: () => parseJsonFromBytes,
38
+ privateKeyFromRandom: () => privateKeyFromRandom,
39
+ publicKeyFromPrivate: () => publicKeyFromPrivate,
40
+ serializeSignedTransaction: () => serializeSignedTransaction,
41
+ serializeTransaction: () => serializeTransaction,
42
+ sha256: () => sha256,
43
+ signBytes: () => signBytes,
44
+ signHash: () => signHash,
45
+ toBase58: () => binary_to_base58_default,
46
+ toBase64: () => toBase64,
47
+ tryParseJson: () => tryParseJson
48
+ });
49
+
50
+ // ../../node_modules/big.js/big.mjs
51
+ var DP = 20;
52
+ var RM = 1;
53
+ var MAX_DP = 1e6;
54
+ var MAX_POWER = 1e6;
55
+ var NE = -7;
56
+ var PE = 21;
57
+ var STRICT = false;
58
+ var NAME = "[big.js] ";
59
+ var INVALID = NAME + "Invalid ";
60
+ var INVALID_DP = INVALID + "decimal places";
61
+ var INVALID_RM = INVALID + "rounding mode";
62
+ var DIV_BY_ZERO = NAME + "Division by zero";
63
+ var P = {};
64
+ var UNDEFINED = void 0;
65
+ var NUMERIC = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;
66
+ function _Big_() {
67
+ function Big2(n) {
68
+ var x = this;
69
+ if (!(x instanceof Big2)) return n === UNDEFINED ? _Big_() : new Big2(n);
70
+ if (n instanceof Big2) {
71
+ x.s = n.s;
72
+ x.e = n.e;
73
+ x.c = n.c.slice();
74
+ } else {
75
+ if (typeof n !== "string") {
76
+ if (Big2.strict === true && typeof n !== "bigint") {
77
+ throw TypeError(INVALID + "value");
78
+ }
79
+ n = n === 0 && 1 / n < 0 ? "-0" : String(n);
80
+ }
81
+ parse(x, n);
82
+ }
83
+ x.constructor = Big2;
84
+ }
85
+ Big2.prototype = P;
86
+ Big2.DP = DP;
87
+ Big2.RM = RM;
88
+ Big2.NE = NE;
89
+ Big2.PE = PE;
90
+ Big2.strict = STRICT;
91
+ Big2.roundDown = 0;
92
+ Big2.roundHalfUp = 1;
93
+ Big2.roundHalfEven = 2;
94
+ Big2.roundUp = 3;
95
+ return Big2;
96
+ }
97
+ function parse(x, n) {
98
+ var e, i, nl;
99
+ if (!NUMERIC.test(n)) {
100
+ throw Error(INVALID + "number");
101
+ }
102
+ x.s = n.charAt(0) == "-" ? (n = n.slice(1), -1) : 1;
103
+ if ((e = n.indexOf(".")) > -1) n = n.replace(".", "");
104
+ if ((i = n.search(/e/i)) > 0) {
105
+ if (e < 0) e = i;
106
+ e += +n.slice(i + 1);
107
+ n = n.substring(0, i);
108
+ } else if (e < 0) {
109
+ e = n.length;
110
+ }
111
+ nl = n.length;
112
+ for (i = 0; i < nl && n.charAt(i) == "0"; ) ++i;
113
+ if (i == nl) {
114
+ x.c = [x.e = 0];
115
+ } else {
116
+ for (; nl > 0 && n.charAt(--nl) == "0"; ) ;
117
+ x.e = e - i - 1;
118
+ x.c = [];
119
+ for (e = 0; i <= nl; ) x.c[e++] = +n.charAt(i++);
120
+ }
121
+ return x;
122
+ }
123
+ function round(x, sd, rm, more) {
124
+ var xc = x.c;
125
+ if (rm === UNDEFINED) rm = x.constructor.RM;
126
+ if (rm !== 0 && rm !== 1 && rm !== 2 && rm !== 3) {
127
+ throw Error(INVALID_RM);
128
+ }
129
+ if (sd < 1) {
130
+ more = rm === 3 && (more || !!xc[0]) || sd === 0 && (rm === 1 && xc[0] >= 5 || rm === 2 && (xc[0] > 5 || xc[0] === 5 && (more || xc[1] !== UNDEFINED)));
131
+ xc.length = 1;
132
+ if (more) {
133
+ x.e = x.e - sd + 1;
134
+ xc[0] = 1;
135
+ } else {
136
+ xc[0] = x.e = 0;
137
+ }
138
+ } else if (sd < xc.length) {
139
+ more = rm === 1 && xc[sd] >= 5 || rm === 2 && (xc[sd] > 5 || xc[sd] === 5 && (more || xc[sd + 1] !== UNDEFINED || xc[sd - 1] & 1)) || rm === 3 && (more || !!xc[0]);
140
+ xc.length = sd;
141
+ if (more) {
142
+ for (; ++xc[--sd] > 9; ) {
143
+ xc[sd] = 0;
144
+ if (sd === 0) {
145
+ ++x.e;
146
+ xc.unshift(1);
147
+ break;
148
+ }
149
+ }
150
+ }
151
+ for (sd = xc.length; !xc[--sd]; ) xc.pop();
152
+ }
153
+ return x;
154
+ }
155
+ function stringify(x, doExponential, isNonzero) {
156
+ var e = x.e, s = x.c.join(""), n = s.length;
157
+ if (doExponential) {
158
+ s = s.charAt(0) + (n > 1 ? "." + s.slice(1) : "") + (e < 0 ? "e" : "e+") + e;
159
+ } else if (e < 0) {
160
+ for (; ++e; ) s = "0" + s;
161
+ s = "0." + s;
162
+ } else if (e > 0) {
163
+ if (++e > n) {
164
+ for (e -= n; e--; ) s += "0";
165
+ } else if (e < n) {
166
+ s = s.slice(0, e) + "." + s.slice(e);
167
+ }
168
+ } else if (n > 1) {
169
+ s = s.charAt(0) + "." + s.slice(1);
170
+ }
171
+ return x.s < 0 && isNonzero ? "-" + s : s;
172
+ }
173
+ P.abs = function() {
174
+ var x = new this.constructor(this);
175
+ x.s = 1;
176
+ return x;
177
+ };
178
+ P.cmp = function(y) {
179
+ var isneg, x = this, xc = x.c, yc = (y = new x.constructor(y)).c, i = x.s, j = y.s, k = x.e, l = y.e;
180
+ if (!xc[0] || !yc[0]) return !xc[0] ? !yc[0] ? 0 : -j : i;
181
+ if (i != j) return i;
182
+ isneg = i < 0;
183
+ if (k != l) return k > l ^ isneg ? 1 : -1;
184
+ j = (k = xc.length) < (l = yc.length) ? k : l;
185
+ for (i = -1; ++i < j; ) {
186
+ if (xc[i] != yc[i]) return xc[i] > yc[i] ^ isneg ? 1 : -1;
187
+ }
188
+ return k == l ? 0 : k > l ^ isneg ? 1 : -1;
189
+ };
190
+ P.div = function(y) {
191
+ var x = this, Big2 = x.constructor, a = x.c, b = (y = new Big2(y)).c, k = x.s == y.s ? 1 : -1, dp = Big2.DP;
192
+ if (dp !== ~~dp || dp < 0 || dp > MAX_DP) {
193
+ throw Error(INVALID_DP);
194
+ }
195
+ if (!b[0]) {
196
+ throw Error(DIV_BY_ZERO);
197
+ }
198
+ if (!a[0]) {
199
+ y.s = k;
200
+ y.c = [y.e = 0];
201
+ return y;
202
+ }
203
+ var bl, bt, n, cmp, ri, bz = b.slice(), ai = bl = b.length, al = a.length, r = a.slice(0, bl), rl = r.length, q = y, qc = q.c = [], qi = 0, p = dp + (q.e = x.e - y.e) + 1;
204
+ q.s = k;
205
+ k = p < 0 ? 0 : p;
206
+ bz.unshift(0);
207
+ for (; rl++ < bl; ) r.push(0);
208
+ do {
209
+ for (n = 0; n < 10; n++) {
210
+ if (bl != (rl = r.length)) {
211
+ cmp = bl > rl ? 1 : -1;
212
+ } else {
213
+ for (ri = -1, cmp = 0; ++ri < bl; ) {
214
+ if (b[ri] != r[ri]) {
215
+ cmp = b[ri] > r[ri] ? 1 : -1;
216
+ break;
217
+ }
218
+ }
219
+ }
220
+ if (cmp < 0) {
221
+ for (bt = rl == bl ? b : bz; rl; ) {
222
+ if (r[--rl] < bt[rl]) {
223
+ ri = rl;
224
+ for (; ri && !r[--ri]; ) r[ri] = 9;
225
+ --r[ri];
226
+ r[rl] += 10;
227
+ }
228
+ r[rl] -= bt[rl];
229
+ }
230
+ for (; !r[0]; ) r.shift();
231
+ } else {
232
+ break;
233
+ }
234
+ }
235
+ qc[qi++] = cmp ? n : ++n;
236
+ if (r[0] && cmp) r[rl] = a[ai] || 0;
237
+ else r = [a[ai]];
238
+ } while ((ai++ < al || r[0] !== UNDEFINED) && k--);
239
+ if (!qc[0] && qi != 1) {
240
+ qc.shift();
241
+ q.e--;
242
+ p--;
243
+ }
244
+ if (qi > p) round(q, p, Big2.RM, r[0] !== UNDEFINED);
245
+ return q;
246
+ };
247
+ P.eq = function(y) {
248
+ return this.cmp(y) === 0;
249
+ };
250
+ P.gt = function(y) {
251
+ return this.cmp(y) > 0;
252
+ };
253
+ P.gte = function(y) {
254
+ return this.cmp(y) > -1;
255
+ };
256
+ P.lt = function(y) {
257
+ return this.cmp(y) < 0;
258
+ };
259
+ P.lte = function(y) {
260
+ return this.cmp(y) < 1;
261
+ };
262
+ P.minus = P.sub = function(y) {
263
+ var i, j, t, xlty, x = this, Big2 = x.constructor, a = x.s, b = (y = new Big2(y)).s;
264
+ if (a != b) {
265
+ y.s = -b;
266
+ return x.plus(y);
267
+ }
268
+ var xc = x.c.slice(), xe = x.e, yc = y.c, ye = y.e;
269
+ if (!xc[0] || !yc[0]) {
270
+ if (yc[0]) {
271
+ y.s = -b;
272
+ } else if (xc[0]) {
273
+ y = new Big2(x);
274
+ } else {
275
+ y.s = 1;
276
+ }
277
+ return y;
278
+ }
279
+ if (a = xe - ye) {
280
+ if (xlty = a < 0) {
281
+ a = -a;
282
+ t = xc;
283
+ } else {
284
+ ye = xe;
285
+ t = yc;
286
+ }
287
+ t.reverse();
288
+ for (b = a; b--; ) t.push(0);
289
+ t.reverse();
290
+ } else {
291
+ j = ((xlty = xc.length < yc.length) ? xc : yc).length;
292
+ for (a = b = 0; b < j; b++) {
293
+ if (xc[b] != yc[b]) {
294
+ xlty = xc[b] < yc[b];
295
+ break;
296
+ }
297
+ }
298
+ }
299
+ if (xlty) {
300
+ t = xc;
301
+ xc = yc;
302
+ yc = t;
303
+ y.s = -y.s;
304
+ }
305
+ if ((b = (j = yc.length) - (i = xc.length)) > 0) for (; b--; ) xc[i++] = 0;
306
+ for (b = i; j > a; ) {
307
+ if (xc[--j] < yc[j]) {
308
+ for (i = j; i && !xc[--i]; ) xc[i] = 9;
309
+ --xc[i];
310
+ xc[j] += 10;
311
+ }
312
+ xc[j] -= yc[j];
313
+ }
314
+ for (; xc[--b] === 0; ) xc.pop();
315
+ for (; xc[0] === 0; ) {
316
+ xc.shift();
317
+ --ye;
318
+ }
319
+ if (!xc[0]) {
320
+ y.s = 1;
321
+ xc = [ye = 0];
322
+ }
323
+ y.c = xc;
324
+ y.e = ye;
325
+ return y;
326
+ };
327
+ P.mod = function(y) {
328
+ var ygtx, x = this, Big2 = x.constructor, a = x.s, b = (y = new Big2(y)).s;
329
+ if (!y.c[0]) {
330
+ throw Error(DIV_BY_ZERO);
331
+ }
332
+ x.s = y.s = 1;
333
+ ygtx = y.cmp(x) == 1;
334
+ x.s = a;
335
+ y.s = b;
336
+ if (ygtx) return new Big2(x);
337
+ a = Big2.DP;
338
+ b = Big2.RM;
339
+ Big2.DP = Big2.RM = 0;
340
+ x = x.div(y);
341
+ Big2.DP = a;
342
+ Big2.RM = b;
343
+ return this.minus(x.times(y));
344
+ };
345
+ P.neg = function() {
346
+ var x = new this.constructor(this);
347
+ x.s = -x.s;
348
+ return x;
349
+ };
350
+ P.plus = P.add = function(y) {
351
+ var e, k, t, x = this, Big2 = x.constructor;
352
+ y = new Big2(y);
353
+ if (x.s != y.s) {
354
+ y.s = -y.s;
355
+ return x.minus(y);
356
+ }
357
+ var xe = x.e, xc = x.c, ye = y.e, yc = y.c;
358
+ if (!xc[0] || !yc[0]) {
359
+ if (!yc[0]) {
360
+ if (xc[0]) {
361
+ y = new Big2(x);
362
+ } else {
363
+ y.s = x.s;
364
+ }
365
+ }
366
+ return y;
367
+ }
368
+ xc = xc.slice();
369
+ if (e = xe - ye) {
370
+ if (e > 0) {
371
+ ye = xe;
372
+ t = yc;
373
+ } else {
374
+ e = -e;
375
+ t = xc;
376
+ }
377
+ t.reverse();
378
+ for (; e--; ) t.push(0);
379
+ t.reverse();
380
+ }
381
+ if (xc.length - yc.length < 0) {
382
+ t = yc;
383
+ yc = xc;
384
+ xc = t;
385
+ }
386
+ e = yc.length;
387
+ for (k = 0; e; xc[e] %= 10) k = (xc[--e] = xc[e] + yc[e] + k) / 10 | 0;
388
+ if (k) {
389
+ xc.unshift(k);
390
+ ++ye;
391
+ }
392
+ for (e = xc.length; xc[--e] === 0; ) xc.pop();
393
+ y.c = xc;
394
+ y.e = ye;
395
+ return y;
396
+ };
397
+ P.pow = function(n) {
398
+ var x = this, one = new x.constructor("1"), y = one, isneg = n < 0;
399
+ if (n !== ~~n || n < -MAX_POWER || n > MAX_POWER) {
400
+ throw Error(INVALID + "exponent");
401
+ }
402
+ if (isneg) n = -n;
403
+ for (; ; ) {
404
+ if (n & 1) y = y.times(x);
405
+ n >>= 1;
406
+ if (!n) break;
407
+ x = x.times(x);
408
+ }
409
+ return isneg ? one.div(y) : y;
410
+ };
411
+ P.prec = function(sd, rm) {
412
+ if (sd !== ~~sd || sd < 1 || sd > MAX_DP) {
413
+ throw Error(INVALID + "precision");
414
+ }
415
+ return round(new this.constructor(this), sd, rm);
416
+ };
417
+ P.round = function(dp, rm) {
418
+ if (dp === UNDEFINED) dp = 0;
419
+ else if (dp !== ~~dp || dp < -MAX_DP || dp > MAX_DP) {
420
+ throw Error(INVALID_DP);
421
+ }
422
+ return round(new this.constructor(this), dp + this.e + 1, rm);
423
+ };
424
+ P.sqrt = function() {
425
+ var r, c, t, x = this, Big2 = x.constructor, s = x.s, e = x.e, half = new Big2("0.5");
426
+ if (!x.c[0]) return new Big2(x);
427
+ if (s < 0) {
428
+ throw Error(NAME + "No square root");
429
+ }
430
+ s = Math.sqrt(+stringify(x, true, true));
431
+ if (s === 0 || s === 1 / 0) {
432
+ c = x.c.join("");
433
+ if (!(c.length + e & 1)) c += "0";
434
+ s = Math.sqrt(c);
435
+ e = ((e + 1) / 2 | 0) - (e < 0 || e & 1);
436
+ r = new Big2((s == 1 / 0 ? "5e" : (s = s.toExponential()).slice(0, s.indexOf("e") + 1)) + e);
437
+ } else {
438
+ r = new Big2(s + "");
439
+ }
440
+ e = r.e + (Big2.DP += 4);
441
+ do {
442
+ t = r;
443
+ r = half.times(t.plus(x.div(t)));
444
+ } while (t.c.slice(0, e).join("") !== r.c.slice(0, e).join(""));
445
+ return round(r, (Big2.DP -= 4) + r.e + 1, Big2.RM);
446
+ };
447
+ P.times = P.mul = function(y) {
448
+ var c, x = this, Big2 = x.constructor, xc = x.c, yc = (y = new Big2(y)).c, a = xc.length, b = yc.length, i = x.e, j = y.e;
449
+ y.s = x.s == y.s ? 1 : -1;
450
+ if (!xc[0] || !yc[0]) {
451
+ y.c = [y.e = 0];
452
+ return y;
453
+ }
454
+ y.e = i + j;
455
+ if (a < b) {
456
+ c = xc;
457
+ xc = yc;
458
+ yc = c;
459
+ j = a;
460
+ a = b;
461
+ b = j;
462
+ }
463
+ for (c = new Array(j = a + b); j--; ) c[j] = 0;
464
+ for (i = b; i--; ) {
465
+ b = 0;
466
+ for (j = a + i; j > i; ) {
467
+ b = c[j] + yc[i] * xc[j - i - 1] + b;
468
+ c[j--] = b % 10;
469
+ b = b / 10 | 0;
470
+ }
471
+ c[j] = b;
472
+ }
473
+ if (b) ++y.e;
474
+ else c.shift();
475
+ for (i = c.length; !c[--i]; ) c.pop();
476
+ y.c = c;
477
+ return y;
478
+ };
479
+ P.toExponential = function(dp, rm) {
480
+ var x = this, n = x.c[0];
481
+ if (dp !== UNDEFINED) {
482
+ if (dp !== ~~dp || dp < 0 || dp > MAX_DP) {
483
+ throw Error(INVALID_DP);
484
+ }
485
+ x = round(new x.constructor(x), ++dp, rm);
486
+ for (; x.c.length < dp; ) x.c.push(0);
487
+ }
488
+ return stringify(x, true, !!n);
489
+ };
490
+ P.toFixed = function(dp, rm) {
491
+ var x = this, n = x.c[0];
492
+ if (dp !== UNDEFINED) {
493
+ if (dp !== ~~dp || dp < 0 || dp > MAX_DP) {
494
+ throw Error(INVALID_DP);
495
+ }
496
+ x = round(new x.constructor(x), dp + x.e + 1, rm);
497
+ for (dp = dp + x.e + 1; x.c.length < dp; ) x.c.push(0);
498
+ }
499
+ return stringify(x, false, !!n);
500
+ };
501
+ P[Symbol.for("nodejs.util.inspect.custom")] = P.toJSON = P.toString = function() {
502
+ var x = this, Big2 = x.constructor;
503
+ return stringify(x, x.e <= Big2.NE || x.e >= Big2.PE, !!x.c[0]);
504
+ };
505
+ P.toNumber = function() {
506
+ var n = +stringify(this, true, true);
507
+ if (this.constructor.strict === true && !this.eq(n.toString())) {
508
+ throw Error(NAME + "Imprecise conversion");
509
+ }
510
+ return n;
511
+ };
512
+ P.toPrecision = function(sd, rm) {
513
+ var x = this, Big2 = x.constructor, n = x.c[0];
514
+ if (sd !== UNDEFINED) {
515
+ if (sd !== ~~sd || sd < 1 || sd > MAX_DP) {
516
+ throw Error(INVALID + "precision");
517
+ }
518
+ x = round(new Big2(x), sd, rm);
519
+ for (; x.c.length < sd; ) x.c.push(0);
520
+ }
521
+ return stringify(x, sd <= x.e || x.e <= Big2.NE || x.e >= Big2.PE, !!n);
522
+ };
523
+ P.valueOf = function() {
524
+ var x = this, Big2 = x.constructor;
525
+ if (Big2.strict === true) {
526
+ throw Error(NAME + "valueOf disallowed");
527
+ }
528
+ return stringify(x, x.e <= Big2.NE || x.e >= Big2.PE, true);
529
+ };
530
+ var Big = _Big_();
531
+ var big_default = Big;
532
+
533
+ // ../wallet-adapter/src/index.ts
534
+ var WalletAdapter = class _WalletAdapter {
535
+ /** @type {HTMLIFrameElement} */
536
+ #iframe = null;
537
+ /** @type {string} */
538
+ #targetOrigin;
539
+ /** @type {string} */
540
+ #widgetUrl;
541
+ /** @type {Map<string, Function>} */
542
+ #pending = /* @__PURE__ */ new Map();
543
+ /** @type {WalletState} */
544
+ #state;
545
+ /** @type {Function} */
546
+ #onStateUpdate;
547
+ /** @type {string} */
548
+ #callbackUrl;
549
+ /** @type {string} */
550
+ static defaultWidgetUrl = "https://wallet-adapter.fastnear.com";
551
+ /**
552
+ * @param {WalletAdapterConfig} [config]
553
+ */
554
+ constructor({
555
+ widgetUrl = _WalletAdapter.defaultWidgetUrl,
556
+ targetOrigin = "*",
557
+ onStateUpdate,
558
+ lastState,
559
+ callbackUrl = window.location.href
560
+ } = {}) {
561
+ this.#targetOrigin = targetOrigin;
562
+ this.#widgetUrl = widgetUrl;
563
+ this.#onStateUpdate = onStateUpdate;
564
+ this.#callbackUrl = callbackUrl;
565
+ this.#state = lastState || {};
566
+ window.addEventListener("message", this.#handleMessage.bind(this));
567
+ }
568
+ /**
569
+ * Creates an iframe for wallet interaction
570
+ * @param {string} path - Path to load in iframe
571
+ * @returns {HTMLIFrameElement}
572
+ */
573
+ #createIframe(path) {
574
+ if (this.#iframe) {
575
+ this.#iframe.remove();
576
+ }
577
+ const url = new URL(path, this.#widgetUrl);
578
+ const iframe = document.createElement("iframe");
579
+ iframe.src = url.toString();
580
+ iframe.allow = "usb";
581
+ iframe.style.border = "none";
582
+ iframe.style.zIndex = "10000";
583
+ iframe.style.position = "fixed";
584
+ iframe.style.display = "block";
585
+ iframe.style.top = "0";
586
+ iframe.style.left = "0";
587
+ iframe.style.width = "100%";
588
+ iframe.style.height = "100%";
589
+ document.body.appendChild(iframe);
590
+ this.#iframe = iframe;
591
+ return iframe;
592
+ }
593
+ /**
594
+ * Handles messages from the wallet widget
595
+ * @param {MessageEvent} event
596
+ */
597
+ #handleMessage(event) {
598
+ if (this.#targetOrigin !== "*" && event.origin !== this.#targetOrigin) {
599
+ return;
600
+ }
601
+ const { id, type, action, payload } = event.data;
602
+ if (type !== "wallet-adapter") return;
603
+ if (action === "close") {
604
+ this.#iframe?.remove();
605
+ this.#iframe = null;
606
+ return;
607
+ }
608
+ if (payload?.state) {
609
+ this.#state = { ...this.#state, ...payload.state };
610
+ this.#onStateUpdate?.(this.#state);
611
+ }
612
+ const resolve = this.#pending.get(id);
613
+ if (resolve) {
614
+ this.#pending.delete(id);
615
+ this.#iframe?.remove();
616
+ this.#iframe = null;
617
+ resolve(payload);
618
+ }
619
+ }
620
+ /**
621
+ * Sends a message to the wallet widget
622
+ * @param {string} path - Path to load in iframe
623
+ * @param {string} method - Method to call
624
+ * @param {Object} params - Parameters to pass
625
+ * @returns {Promise<any>}
626
+ */
627
+ async #sendMessage(path, method, params) {
628
+ return new Promise((resolve) => {
629
+ const id = Math.random().toString(36).slice(2);
630
+ this.#pending.set(id, resolve);
631
+ const iframe = this.#createIframe(path);
632
+ iframe.onload = () => {
633
+ iframe.contentWindow?.postMessage(
634
+ {
635
+ type: "wallet-adapter",
636
+ method,
637
+ params: {
638
+ id,
639
+ ...params,
640
+ state: this.#state,
641
+ callbackUrl: params.callbackUrl || this.#callbackUrl
642
+ }
643
+ },
644
+ this.#targetOrigin
645
+ );
646
+ };
647
+ });
648
+ }
649
+ /**
650
+ * Get current wallet state
651
+ * @returns {WalletState}
652
+ */
653
+ getState() {
654
+ return { ...this.#state };
655
+ }
656
+ /**
657
+ * Set current wallet state
658
+ * @param state
659
+ */
660
+ setState(state) {
661
+ this.#state = state;
662
+ }
663
+ /**
664
+ * Sign in with a NEAR wallet
665
+ * @param {SignInConfig} config
666
+ * @returns {Promise<SignInResult>}
667
+ */
668
+ async signIn(config) {
669
+ return this.#sendMessage("/login.html", "signIn", config);
670
+ }
671
+ /**
672
+ * Send a transaction using connected wallet
673
+ * @param {TransactionConfig} config
674
+ * @returns {Promise<TransactionResult>}
675
+ */
676
+ async sendTransactions(config) {
677
+ return this.#sendMessage("/send.html", "sendTransactions", config);
678
+ }
679
+ /**
680
+ * Clean up adapter resources
681
+ */
682
+ destroy() {
683
+ window.removeEventListener("message", this.#handleMessage);
684
+ this.#iframe?.remove();
685
+ this.#iframe = null;
686
+ }
687
+ };
688
+
689
+ // ../../node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js
690
+ function isBytes(a) {
691
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
692
+ }
693
+ function abytes(b, ...lengths) {
694
+ if (!isBytes(b))
695
+ throw new Error("Uint8Array expected");
696
+ if (lengths.length > 0 && !lengths.includes(b.length))
697
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
698
+ }
699
+ function aexists(instance, checkFinished = true) {
700
+ if (instance.destroyed)
701
+ throw new Error("Hash instance has been destroyed");
702
+ if (checkFinished && instance.finished)
703
+ throw new Error("Hash#digest() has already been called");
704
+ }
705
+ function aoutput(out, instance) {
706
+ abytes(out);
707
+ const min = instance.outputLen;
708
+ if (out.length < min) {
709
+ throw new Error("digestInto() expects output buffer of length at least " + min);
710
+ }
711
+ }
712
+
713
+ // ../../node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js
714
+ var crypto2 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
715
+
716
+ // ../../node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js
717
+ var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
718
+ function utf8ToBytes(str) {
719
+ if (typeof str !== "string")
720
+ throw new Error("utf8ToBytes expected string, got " + typeof str);
721
+ return new Uint8Array(new TextEncoder().encode(str));
722
+ }
723
+ function toBytes(data) {
724
+ if (typeof data === "string")
725
+ data = utf8ToBytes(data);
726
+ abytes(data);
727
+ return data;
728
+ }
729
+ var Hash = class {
730
+ // Safe version that clones internal state
731
+ clone() {
732
+ return this._cloneInto();
733
+ }
734
+ };
735
+ function wrapConstructor(hashCons) {
736
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
737
+ const tmp = hashCons();
738
+ hashC.outputLen = tmp.outputLen;
739
+ hashC.blockLen = tmp.blockLen;
740
+ hashC.create = () => hashCons();
741
+ return hashC;
742
+ }
743
+ function randomBytes(bytesLength = 32) {
744
+ if (crypto2 && typeof crypto2.getRandomValues === "function") {
745
+ return crypto2.getRandomValues(new Uint8Array(bytesLength));
746
+ }
747
+ if (crypto2 && typeof crypto2.randomBytes === "function") {
748
+ return crypto2.randomBytes(bytesLength);
749
+ }
750
+ throw new Error("crypto.getRandomValues must be defined");
751
+ }
752
+
753
+ // ../../node_modules/@noble/curves/node_modules/@noble/hashes/esm/_md.js
754
+ function setBigUint64(view, byteOffset, value, isLE) {
755
+ if (typeof view.setBigUint64 === "function")
756
+ return view.setBigUint64(byteOffset, value, isLE);
757
+ const _32n2 = BigInt(32);
758
+ const _u32_max = BigInt(4294967295);
759
+ const wh = Number(value >> _32n2 & _u32_max);
760
+ const wl = Number(value & _u32_max);
761
+ const h = isLE ? 4 : 0;
762
+ const l = isLE ? 0 : 4;
763
+ view.setUint32(byteOffset + h, wh, isLE);
764
+ view.setUint32(byteOffset + l, wl, isLE);
765
+ }
766
+ var HashMD = class extends Hash {
767
+ constructor(blockLen, outputLen, padOffset, isLE) {
768
+ super();
769
+ this.blockLen = blockLen;
770
+ this.outputLen = outputLen;
771
+ this.padOffset = padOffset;
772
+ this.isLE = isLE;
773
+ this.finished = false;
774
+ this.length = 0;
775
+ this.pos = 0;
776
+ this.destroyed = false;
777
+ this.buffer = new Uint8Array(blockLen);
778
+ this.view = createView(this.buffer);
779
+ }
780
+ update(data) {
781
+ aexists(this);
782
+ const { view, buffer, blockLen } = this;
783
+ data = toBytes(data);
784
+ const len = data.length;
785
+ for (let pos = 0; pos < len; ) {
786
+ const take = Math.min(blockLen - this.pos, len - pos);
787
+ if (take === blockLen) {
788
+ const dataView = createView(data);
789
+ for (; blockLen <= len - pos; pos += blockLen)
790
+ this.process(dataView, pos);
791
+ continue;
792
+ }
793
+ buffer.set(data.subarray(pos, pos + take), this.pos);
794
+ this.pos += take;
795
+ pos += take;
796
+ if (this.pos === blockLen) {
797
+ this.process(view, 0);
798
+ this.pos = 0;
799
+ }
800
+ }
801
+ this.length += data.length;
802
+ this.roundClean();
803
+ return this;
804
+ }
805
+ digestInto(out) {
806
+ aexists(this);
807
+ aoutput(out, this);
808
+ this.finished = true;
809
+ const { buffer, view, blockLen, isLE } = this;
810
+ let { pos } = this;
811
+ buffer[pos++] = 128;
812
+ this.buffer.subarray(pos).fill(0);
813
+ if (this.padOffset > blockLen - pos) {
814
+ this.process(view, 0);
815
+ pos = 0;
816
+ }
817
+ for (let i = pos; i < blockLen; i++)
818
+ buffer[i] = 0;
819
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
820
+ this.process(view, 0);
821
+ const oview = createView(out);
822
+ const len = this.outputLen;
823
+ if (len % 4)
824
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
825
+ const outLen = len / 4;
826
+ const state = this.get();
827
+ if (outLen > state.length)
828
+ throw new Error("_sha2: outputLen bigger than state");
829
+ for (let i = 0; i < outLen; i++)
830
+ oview.setUint32(4 * i, state[i], isLE);
831
+ }
832
+ digest() {
833
+ const { buffer, outputLen } = this;
834
+ this.digestInto(buffer);
835
+ const res = buffer.slice(0, outputLen);
836
+ this.destroy();
837
+ return res;
838
+ }
839
+ _cloneInto(to) {
840
+ to || (to = new this.constructor());
841
+ to.set(...this.get());
842
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
843
+ to.length = length;
844
+ to.pos = pos;
845
+ to.finished = finished;
846
+ to.destroyed = destroyed;
847
+ if (length % blockLen)
848
+ to.buffer.set(buffer);
849
+ return to;
850
+ }
851
+ };
852
+
853
+ // ../../node_modules/@noble/curves/node_modules/@noble/hashes/esm/_u64.js
854
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
855
+ var _32n = /* @__PURE__ */ BigInt(32);
856
+ function fromBig(n, le = false) {
857
+ if (le)
858
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
859
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
860
+ }
861
+ function split(lst, le = false) {
862
+ let Ah = new Uint32Array(lst.length);
863
+ let Al = new Uint32Array(lst.length);
864
+ for (let i = 0; i < lst.length; i++) {
865
+ const { h, l } = fromBig(lst[i], le);
866
+ [Ah[i], Al[i]] = [h, l];
867
+ }
868
+ return [Ah, Al];
869
+ }
870
+ var toBig = (h, l) => BigInt(h >>> 0) << _32n | BigInt(l >>> 0);
871
+ var shrSH = (h, _l, s) => h >>> s;
872
+ var shrSL = (h, l, s) => h << 32 - s | l >>> s;
873
+ var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
874
+ var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
875
+ var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
876
+ var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
877
+ var rotr32H = (_h, l) => l;
878
+ var rotr32L = (h, _l) => h;
879
+ var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
880
+ var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
881
+ var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
882
+ var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
883
+ function add(Ah, Al, Bh, Bl) {
884
+ const l = (Al >>> 0) + (Bl >>> 0);
885
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
886
+ }
887
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
888
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
889
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
890
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
891
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
892
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
893
+ var u64 = {
894
+ fromBig,
895
+ split,
896
+ toBig,
897
+ shrSH,
898
+ shrSL,
899
+ rotrSH,
900
+ rotrSL,
901
+ rotrBH,
902
+ rotrBL,
903
+ rotr32H,
904
+ rotr32L,
905
+ rotlSH,
906
+ rotlSL,
907
+ rotlBH,
908
+ rotlBL,
909
+ add,
910
+ add3L,
911
+ add3H,
912
+ add4L,
913
+ add4H,
914
+ add5H,
915
+ add5L
916
+ };
917
+ var u64_default = u64;
918
+
919
+ // ../../node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha512.js
920
+ var [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64_default.split([
921
+ "0x428a2f98d728ae22",
922
+ "0x7137449123ef65cd",
923
+ "0xb5c0fbcfec4d3b2f",
924
+ "0xe9b5dba58189dbbc",
925
+ "0x3956c25bf348b538",
926
+ "0x59f111f1b605d019",
927
+ "0x923f82a4af194f9b",
928
+ "0xab1c5ed5da6d8118",
929
+ "0xd807aa98a3030242",
930
+ "0x12835b0145706fbe",
931
+ "0x243185be4ee4b28c",
932
+ "0x550c7dc3d5ffb4e2",
933
+ "0x72be5d74f27b896f",
934
+ "0x80deb1fe3b1696b1",
935
+ "0x9bdc06a725c71235",
936
+ "0xc19bf174cf692694",
937
+ "0xe49b69c19ef14ad2",
938
+ "0xefbe4786384f25e3",
939
+ "0x0fc19dc68b8cd5b5",
940
+ "0x240ca1cc77ac9c65",
941
+ "0x2de92c6f592b0275",
942
+ "0x4a7484aa6ea6e483",
943
+ "0x5cb0a9dcbd41fbd4",
944
+ "0x76f988da831153b5",
945
+ "0x983e5152ee66dfab",
946
+ "0xa831c66d2db43210",
947
+ "0xb00327c898fb213f",
948
+ "0xbf597fc7beef0ee4",
949
+ "0xc6e00bf33da88fc2",
950
+ "0xd5a79147930aa725",
951
+ "0x06ca6351e003826f",
952
+ "0x142929670a0e6e70",
953
+ "0x27b70a8546d22ffc",
954
+ "0x2e1b21385c26c926",
955
+ "0x4d2c6dfc5ac42aed",
956
+ "0x53380d139d95b3df",
957
+ "0x650a73548baf63de",
958
+ "0x766a0abb3c77b2a8",
959
+ "0x81c2c92e47edaee6",
960
+ "0x92722c851482353b",
961
+ "0xa2bfe8a14cf10364",
962
+ "0xa81a664bbc423001",
963
+ "0xc24b8b70d0f89791",
964
+ "0xc76c51a30654be30",
965
+ "0xd192e819d6ef5218",
966
+ "0xd69906245565a910",
967
+ "0xf40e35855771202a",
968
+ "0x106aa07032bbd1b8",
969
+ "0x19a4c116b8d2d0c8",
970
+ "0x1e376c085141ab53",
971
+ "0x2748774cdf8eeb99",
972
+ "0x34b0bcb5e19b48a8",
973
+ "0x391c0cb3c5c95a63",
974
+ "0x4ed8aa4ae3418acb",
975
+ "0x5b9cca4f7763e373",
976
+ "0x682e6ff3d6b2b8a3",
977
+ "0x748f82ee5defb2fc",
978
+ "0x78a5636f43172f60",
979
+ "0x84c87814a1f0ab72",
980
+ "0x8cc702081a6439ec",
981
+ "0x90befffa23631e28",
982
+ "0xa4506cebde82bde9",
983
+ "0xbef9a3f7b2c67915",
984
+ "0xc67178f2e372532b",
985
+ "0xca273eceea26619c",
986
+ "0xd186b8c721c0c207",
987
+ "0xeada7dd6cde0eb1e",
988
+ "0xf57d4f7fee6ed178",
989
+ "0x06f067aa72176fba",
990
+ "0x0a637dc5a2c898a6",
991
+ "0x113f9804bef90dae",
992
+ "0x1b710b35131c471b",
993
+ "0x28db77f523047d84",
994
+ "0x32caab7b40c72493",
995
+ "0x3c9ebe0a15c9bebc",
996
+ "0x431d67c49c100d4c",
997
+ "0x4cc5d4becb3e42b6",
998
+ "0x597f299cfc657e2a",
999
+ "0x5fcb6fab3ad6faec",
1000
+ "0x6c44198c4a475817"
1001
+ ].map((n) => BigInt(n))))();
1002
+ var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
1003
+ var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
1004
+ var SHA512 = class extends HashMD {
1005
+ constructor() {
1006
+ super(128, 64, 16, false);
1007
+ this.Ah = 1779033703 | 0;
1008
+ this.Al = 4089235720 | 0;
1009
+ this.Bh = 3144134277 | 0;
1010
+ this.Bl = 2227873595 | 0;
1011
+ this.Ch = 1013904242 | 0;
1012
+ this.Cl = 4271175723 | 0;
1013
+ this.Dh = 2773480762 | 0;
1014
+ this.Dl = 1595750129 | 0;
1015
+ this.Eh = 1359893119 | 0;
1016
+ this.El = 2917565137 | 0;
1017
+ this.Fh = 2600822924 | 0;
1018
+ this.Fl = 725511199 | 0;
1019
+ this.Gh = 528734635 | 0;
1020
+ this.Gl = 4215389547 | 0;
1021
+ this.Hh = 1541459225 | 0;
1022
+ this.Hl = 327033209 | 0;
1023
+ }
1024
+ // prettier-ignore
1025
+ get() {
1026
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1027
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
1028
+ }
1029
+ // prettier-ignore
1030
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
1031
+ this.Ah = Ah | 0;
1032
+ this.Al = Al | 0;
1033
+ this.Bh = Bh | 0;
1034
+ this.Bl = Bl | 0;
1035
+ this.Ch = Ch | 0;
1036
+ this.Cl = Cl | 0;
1037
+ this.Dh = Dh | 0;
1038
+ this.Dl = Dl | 0;
1039
+ this.Eh = Eh | 0;
1040
+ this.El = El | 0;
1041
+ this.Fh = Fh | 0;
1042
+ this.Fl = Fl | 0;
1043
+ this.Gh = Gh | 0;
1044
+ this.Gl = Gl | 0;
1045
+ this.Hh = Hh | 0;
1046
+ this.Hl = Hl | 0;
1047
+ }
1048
+ process(view, offset) {
1049
+ for (let i = 0; i < 16; i++, offset += 4) {
1050
+ SHA512_W_H[i] = view.getUint32(offset);
1051
+ SHA512_W_L[i] = view.getUint32(offset += 4);
1052
+ }
1053
+ for (let i = 16; i < 80; i++) {
1054
+ const W15h = SHA512_W_H[i - 15] | 0;
1055
+ const W15l = SHA512_W_L[i - 15] | 0;
1056
+ const s0h = u64_default.rotrSH(W15h, W15l, 1) ^ u64_default.rotrSH(W15h, W15l, 8) ^ u64_default.shrSH(W15h, W15l, 7);
1057
+ const s0l = u64_default.rotrSL(W15h, W15l, 1) ^ u64_default.rotrSL(W15h, W15l, 8) ^ u64_default.shrSL(W15h, W15l, 7);
1058
+ const W2h = SHA512_W_H[i - 2] | 0;
1059
+ const W2l = SHA512_W_L[i - 2] | 0;
1060
+ const s1h = u64_default.rotrSH(W2h, W2l, 19) ^ u64_default.rotrBH(W2h, W2l, 61) ^ u64_default.shrSH(W2h, W2l, 6);
1061
+ const s1l = u64_default.rotrSL(W2h, W2l, 19) ^ u64_default.rotrBL(W2h, W2l, 61) ^ u64_default.shrSL(W2h, W2l, 6);
1062
+ const SUMl = u64_default.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
1063
+ const SUMh = u64_default.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
1064
+ SHA512_W_H[i] = SUMh | 0;
1065
+ SHA512_W_L[i] = SUMl | 0;
1066
+ }
1067
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1068
+ for (let i = 0; i < 80; i++) {
1069
+ const sigma1h = u64_default.rotrSH(Eh, El, 14) ^ u64_default.rotrSH(Eh, El, 18) ^ u64_default.rotrBH(Eh, El, 41);
1070
+ const sigma1l = u64_default.rotrSL(Eh, El, 14) ^ u64_default.rotrSL(Eh, El, 18) ^ u64_default.rotrBL(Eh, El, 41);
1071
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
1072
+ const CHIl = El & Fl ^ ~El & Gl;
1073
+ const T1ll = u64_default.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
1074
+ const T1h = u64_default.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
1075
+ const T1l = T1ll | 0;
1076
+ const sigma0h = u64_default.rotrSH(Ah, Al, 28) ^ u64_default.rotrBH(Ah, Al, 34) ^ u64_default.rotrBH(Ah, Al, 39);
1077
+ const sigma0l = u64_default.rotrSL(Ah, Al, 28) ^ u64_default.rotrBL(Ah, Al, 34) ^ u64_default.rotrBL(Ah, Al, 39);
1078
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
1079
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
1080
+ Hh = Gh | 0;
1081
+ Hl = Gl | 0;
1082
+ Gh = Fh | 0;
1083
+ Gl = Fl | 0;
1084
+ Fh = Eh | 0;
1085
+ Fl = El | 0;
1086
+ ({ h: Eh, l: El } = u64_default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
1087
+ Dh = Ch | 0;
1088
+ Dl = Cl | 0;
1089
+ Ch = Bh | 0;
1090
+ Cl = Bl | 0;
1091
+ Bh = Ah | 0;
1092
+ Bl = Al | 0;
1093
+ const All = u64_default.add3L(T1l, sigma0l, MAJl);
1094
+ Ah = u64_default.add3H(All, T1h, sigma0h, MAJh);
1095
+ Al = All | 0;
1096
+ }
1097
+ ({ h: Ah, l: Al } = u64_default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
1098
+ ({ h: Bh, l: Bl } = u64_default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
1099
+ ({ h: Ch, l: Cl } = u64_default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
1100
+ ({ h: Dh, l: Dl } = u64_default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
1101
+ ({ h: Eh, l: El } = u64_default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
1102
+ ({ h: Fh, l: Fl } = u64_default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
1103
+ ({ h: Gh, l: Gl } = u64_default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
1104
+ ({ h: Hh, l: Hl } = u64_default.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1105
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1106
+ }
1107
+ roundClean() {
1108
+ SHA512_W_H.fill(0);
1109
+ SHA512_W_L.fill(0);
1110
+ }
1111
+ destroy() {
1112
+ this.buffer.fill(0);
1113
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1114
+ }
1115
+ };
1116
+ var sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
1117
+
1118
+ // ../../node_modules/@noble/curves/esm/abstract/utils.js
1119
+ var _0n = /* @__PURE__ */ BigInt(0);
1120
+ var _1n = /* @__PURE__ */ BigInt(1);
1121
+ var _2n = /* @__PURE__ */ BigInt(2);
1122
+ function isBytes2(a) {
1123
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
1124
+ }
1125
+ function abytes2(item) {
1126
+ if (!isBytes2(item))
1127
+ throw new Error("Uint8Array expected");
1128
+ }
1129
+ function abool(title, value) {
1130
+ if (typeof value !== "boolean")
1131
+ throw new Error(title + " boolean expected, got " + value);
1132
+ }
1133
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
1134
+ function bytesToHex(bytes) {
1135
+ abytes2(bytes);
1136
+ let hex = "";
1137
+ for (let i = 0; i < bytes.length; i++) {
1138
+ hex += hexes[bytes[i]];
1139
+ }
1140
+ return hex;
1141
+ }
1142
+ function hexToNumber(hex) {
1143
+ if (typeof hex !== "string")
1144
+ throw new Error("hex string expected, got " + typeof hex);
1145
+ return hex === "" ? _0n : BigInt("0x" + hex);
1146
+ }
1147
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
1148
+ function asciiToBase16(ch) {
1149
+ if (ch >= asciis._0 && ch <= asciis._9)
1150
+ return ch - asciis._0;
1151
+ if (ch >= asciis.A && ch <= asciis.F)
1152
+ return ch - (asciis.A - 10);
1153
+ if (ch >= asciis.a && ch <= asciis.f)
1154
+ return ch - (asciis.a - 10);
1155
+ return;
1156
+ }
1157
+ function hexToBytes(hex) {
1158
+ if (typeof hex !== "string")
1159
+ throw new Error("hex string expected, got " + typeof hex);
1160
+ const hl = hex.length;
1161
+ const al = hl / 2;
1162
+ if (hl % 2)
1163
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
1164
+ const array = new Uint8Array(al);
1165
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
1166
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
1167
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
1168
+ if (n1 === void 0 || n2 === void 0) {
1169
+ const char = hex[hi] + hex[hi + 1];
1170
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
1171
+ }
1172
+ array[ai] = n1 * 16 + n2;
1173
+ }
1174
+ return array;
1175
+ }
1176
+ function bytesToNumberBE(bytes) {
1177
+ return hexToNumber(bytesToHex(bytes));
1178
+ }
1179
+ function bytesToNumberLE(bytes) {
1180
+ abytes2(bytes);
1181
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
1182
+ }
1183
+ function numberToBytesBE(n, len) {
1184
+ return hexToBytes(n.toString(16).padStart(len * 2, "0"));
1185
+ }
1186
+ function numberToBytesLE(n, len) {
1187
+ return numberToBytesBE(n, len).reverse();
1188
+ }
1189
+ function ensureBytes(title, hex, expectedLength) {
1190
+ let res;
1191
+ if (typeof hex === "string") {
1192
+ try {
1193
+ res = hexToBytes(hex);
1194
+ } catch (e) {
1195
+ throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
1196
+ }
1197
+ } else if (isBytes2(hex)) {
1198
+ res = Uint8Array.from(hex);
1199
+ } else {
1200
+ throw new Error(title + " must be hex string or Uint8Array");
1201
+ }
1202
+ const len = res.length;
1203
+ if (typeof expectedLength === "number" && len !== expectedLength)
1204
+ throw new Error(title + " of length " + expectedLength + " expected, got " + len);
1205
+ return res;
1206
+ }
1207
+ function concatBytes(...arrays) {
1208
+ let sum = 0;
1209
+ for (let i = 0; i < arrays.length; i++) {
1210
+ const a = arrays[i];
1211
+ abytes2(a);
1212
+ sum += a.length;
1213
+ }
1214
+ const res = new Uint8Array(sum);
1215
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
1216
+ const a = arrays[i];
1217
+ res.set(a, pad);
1218
+ pad += a.length;
1219
+ }
1220
+ return res;
1221
+ }
1222
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
1223
+ function inRange(n, min, max) {
1224
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
1225
+ }
1226
+ function aInRange(title, n, min, max) {
1227
+ if (!inRange(n, min, max))
1228
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
1229
+ }
1230
+ function bitLen(n) {
1231
+ let len;
1232
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
1233
+ ;
1234
+ return len;
1235
+ }
1236
+ var bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;
1237
+ var validatorFns = {
1238
+ bigint: (val) => typeof val === "bigint",
1239
+ function: (val) => typeof val === "function",
1240
+ boolean: (val) => typeof val === "boolean",
1241
+ string: (val) => typeof val === "string",
1242
+ stringOrUint8Array: (val) => typeof val === "string" || isBytes2(val),
1243
+ isSafeInteger: (val) => Number.isSafeInteger(val),
1244
+ array: (val) => Array.isArray(val),
1245
+ field: (val, object) => object.Fp.isValid(val),
1246
+ hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
1247
+ };
1248
+ function validateObject(object, validators, optValidators = {}) {
1249
+ const checkField = (fieldName, type, isOptional) => {
1250
+ const checkVal = validatorFns[type];
1251
+ if (typeof checkVal !== "function")
1252
+ throw new Error("invalid validator function");
1253
+ const val = object[fieldName];
1254
+ if (isOptional && val === void 0)
1255
+ return;
1256
+ if (!checkVal(val, object)) {
1257
+ throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val);
1258
+ }
1259
+ };
1260
+ for (const [fieldName, type] of Object.entries(validators))
1261
+ checkField(fieldName, type, false);
1262
+ for (const [fieldName, type] of Object.entries(optValidators))
1263
+ checkField(fieldName, type, true);
1264
+ return object;
1265
+ }
1266
+ function memoized(fn) {
1267
+ const map = /* @__PURE__ */ new WeakMap();
1268
+ return (arg, ...args) => {
1269
+ const val = map.get(arg);
1270
+ if (val !== void 0)
1271
+ return val;
1272
+ const computed = fn(arg, ...args);
1273
+ map.set(arg, computed);
1274
+ return computed;
1275
+ };
1276
+ }
1277
+
1278
+ // ../../node_modules/@noble/curves/esm/abstract/modular.js
1279
+ var _0n2 = BigInt(0);
1280
+ var _1n2 = BigInt(1);
1281
+ var _2n2 = /* @__PURE__ */ BigInt(2);
1282
+ var _3n = /* @__PURE__ */ BigInt(3);
1283
+ var _4n = /* @__PURE__ */ BigInt(4);
1284
+ var _5n = /* @__PURE__ */ BigInt(5);
1285
+ var _8n = /* @__PURE__ */ BigInt(8);
1286
+ var _9n = /* @__PURE__ */ BigInt(9);
1287
+ var _16n = /* @__PURE__ */ BigInt(16);
1288
+ function mod(a, b) {
1289
+ const result = a % b;
1290
+ return result >= _0n2 ? result : b + result;
1291
+ }
1292
+ function pow(num, power, modulo) {
1293
+ if (power < _0n2)
1294
+ throw new Error("invalid exponent, negatives unsupported");
1295
+ if (modulo <= _0n2)
1296
+ throw new Error("invalid modulus");
1297
+ if (modulo === _1n2)
1298
+ return _0n2;
1299
+ let res = _1n2;
1300
+ while (power > _0n2) {
1301
+ if (power & _1n2)
1302
+ res = res * num % modulo;
1303
+ num = num * num % modulo;
1304
+ power >>= _1n2;
1305
+ }
1306
+ return res;
1307
+ }
1308
+ function pow2(x, power, modulo) {
1309
+ let res = x;
1310
+ while (power-- > _0n2) {
1311
+ res *= res;
1312
+ res %= modulo;
1313
+ }
1314
+ return res;
1315
+ }
1316
+ function invert(number, modulo) {
1317
+ if (number === _0n2)
1318
+ throw new Error("invert: expected non-zero number");
1319
+ if (modulo <= _0n2)
1320
+ throw new Error("invert: expected positive modulus, got " + modulo);
1321
+ let a = mod(number, modulo);
1322
+ let b = modulo;
1323
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
1324
+ while (a !== _0n2) {
1325
+ const q = b / a;
1326
+ const r = b % a;
1327
+ const m = x - u * q;
1328
+ const n = y - v * q;
1329
+ b = a, a = r, x = u, y = v, u = m, v = n;
1330
+ }
1331
+ const gcd = b;
1332
+ if (gcd !== _1n2)
1333
+ throw new Error("invert: does not exist");
1334
+ return mod(x, modulo);
1335
+ }
1336
+ function tonelliShanks(P2) {
1337
+ const legendreC = (P2 - _1n2) / _2n2;
1338
+ let Q, S, Z;
1339
+ for (Q = P2 - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++)
1340
+ ;
1341
+ for (Z = _2n2; Z < P2 && pow(Z, legendreC, P2) !== P2 - _1n2; Z++) {
1342
+ if (Z > 1e3)
1343
+ throw new Error("Cannot find square root: likely non-prime P");
1344
+ }
1345
+ if (S === 1) {
1346
+ const p1div4 = (P2 + _1n2) / _4n;
1347
+ return function tonelliFast(Fp2, n) {
1348
+ const root = Fp2.pow(n, p1div4);
1349
+ if (!Fp2.eql(Fp2.sqr(root), n))
1350
+ throw new Error("Cannot find square root");
1351
+ return root;
1352
+ };
1353
+ }
1354
+ const Q1div2 = (Q + _1n2) / _2n2;
1355
+ return function tonelliSlow(Fp2, n) {
1356
+ if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE))
1357
+ throw new Error("Cannot find square root");
1358
+ let r = S;
1359
+ let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z), Q);
1360
+ let x = Fp2.pow(n, Q1div2);
1361
+ let b = Fp2.pow(n, Q);
1362
+ while (!Fp2.eql(b, Fp2.ONE)) {
1363
+ if (Fp2.eql(b, Fp2.ZERO))
1364
+ return Fp2.ZERO;
1365
+ let m = 1;
1366
+ for (let t2 = Fp2.sqr(b); m < r; m++) {
1367
+ if (Fp2.eql(t2, Fp2.ONE))
1368
+ break;
1369
+ t2 = Fp2.sqr(t2);
1370
+ }
1371
+ const ge = Fp2.pow(g, _1n2 << BigInt(r - m - 1));
1372
+ g = Fp2.sqr(ge);
1373
+ x = Fp2.mul(x, ge);
1374
+ b = Fp2.mul(b, g);
1375
+ r = m;
1376
+ }
1377
+ return x;
1378
+ };
1379
+ }
1380
+ function FpSqrt(P2) {
1381
+ if (P2 % _4n === _3n) {
1382
+ const p1div4 = (P2 + _1n2) / _4n;
1383
+ return function sqrt3mod4(Fp2, n) {
1384
+ const root = Fp2.pow(n, p1div4);
1385
+ if (!Fp2.eql(Fp2.sqr(root), n))
1386
+ throw new Error("Cannot find square root");
1387
+ return root;
1388
+ };
1389
+ }
1390
+ if (P2 % _8n === _5n) {
1391
+ const c1 = (P2 - _5n) / _8n;
1392
+ return function sqrt5mod8(Fp2, n) {
1393
+ const n2 = Fp2.mul(n, _2n2);
1394
+ const v = Fp2.pow(n2, c1);
1395
+ const nv = Fp2.mul(n, v);
1396
+ const i = Fp2.mul(Fp2.mul(nv, _2n2), v);
1397
+ const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE));
1398
+ if (!Fp2.eql(Fp2.sqr(root), n))
1399
+ throw new Error("Cannot find square root");
1400
+ return root;
1401
+ };
1402
+ }
1403
+ if (P2 % _16n === _9n) {
1404
+ }
1405
+ return tonelliShanks(P2);
1406
+ }
1407
+ var isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n2) === _1n2;
1408
+ var FIELD_FIELDS = [
1409
+ "create",
1410
+ "isValid",
1411
+ "is0",
1412
+ "neg",
1413
+ "inv",
1414
+ "sqrt",
1415
+ "sqr",
1416
+ "eql",
1417
+ "add",
1418
+ "sub",
1419
+ "mul",
1420
+ "pow",
1421
+ "div",
1422
+ "addN",
1423
+ "subN",
1424
+ "mulN",
1425
+ "sqrN"
1426
+ ];
1427
+ function validateField(field) {
1428
+ const initial = {
1429
+ ORDER: "bigint",
1430
+ MASK: "bigint",
1431
+ BYTES: "isSafeInteger",
1432
+ BITS: "isSafeInteger"
1433
+ };
1434
+ const opts = FIELD_FIELDS.reduce((map, val) => {
1435
+ map[val] = "function";
1436
+ return map;
1437
+ }, initial);
1438
+ return validateObject(field, opts);
1439
+ }
1440
+ function FpPow(f, num, power) {
1441
+ if (power < _0n2)
1442
+ throw new Error("invalid exponent, negatives unsupported");
1443
+ if (power === _0n2)
1444
+ return f.ONE;
1445
+ if (power === _1n2)
1446
+ return num;
1447
+ let p = f.ONE;
1448
+ let d = num;
1449
+ while (power > _0n2) {
1450
+ if (power & _1n2)
1451
+ p = f.mul(p, d);
1452
+ d = f.sqr(d);
1453
+ power >>= _1n2;
1454
+ }
1455
+ return p;
1456
+ }
1457
+ function FpInvertBatch(f, nums) {
1458
+ const tmp = new Array(nums.length);
1459
+ const lastMultiplied = nums.reduce((acc, num, i) => {
1460
+ if (f.is0(num))
1461
+ return acc;
1462
+ tmp[i] = acc;
1463
+ return f.mul(acc, num);
1464
+ }, f.ONE);
1465
+ const inverted = f.inv(lastMultiplied);
1466
+ nums.reduceRight((acc, num, i) => {
1467
+ if (f.is0(num))
1468
+ return acc;
1469
+ tmp[i] = f.mul(acc, tmp[i]);
1470
+ return f.mul(acc, num);
1471
+ }, inverted);
1472
+ return tmp;
1473
+ }
1474
+ function nLength(n, nBitLength) {
1475
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
1476
+ const nByteLength = Math.ceil(_nBitLength / 8);
1477
+ return { nBitLength: _nBitLength, nByteLength };
1478
+ }
1479
+ function Field(ORDER, bitLen2, isLE = false, redef = {}) {
1480
+ if (ORDER <= _0n2)
1481
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
1482
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2);
1483
+ if (BYTES > 2048)
1484
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
1485
+ let sqrtP;
1486
+ const f = Object.freeze({
1487
+ ORDER,
1488
+ BITS,
1489
+ BYTES,
1490
+ MASK: bitMask(BITS),
1491
+ ZERO: _0n2,
1492
+ ONE: _1n2,
1493
+ create: (num) => mod(num, ORDER),
1494
+ isValid: (num) => {
1495
+ if (typeof num !== "bigint")
1496
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
1497
+ return _0n2 <= num && num < ORDER;
1498
+ },
1499
+ is0: (num) => num === _0n2,
1500
+ isOdd: (num) => (num & _1n2) === _1n2,
1501
+ neg: (num) => mod(-num, ORDER),
1502
+ eql: (lhs, rhs) => lhs === rhs,
1503
+ sqr: (num) => mod(num * num, ORDER),
1504
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
1505
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
1506
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
1507
+ pow: (num, power) => FpPow(f, num, power),
1508
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
1509
+ // Same as above, but doesn't normalize
1510
+ sqrN: (num) => num * num,
1511
+ addN: (lhs, rhs) => lhs + rhs,
1512
+ subN: (lhs, rhs) => lhs - rhs,
1513
+ mulN: (lhs, rhs) => lhs * rhs,
1514
+ inv: (num) => invert(num, ORDER),
1515
+ sqrt: redef.sqrt || ((n) => {
1516
+ if (!sqrtP)
1517
+ sqrtP = FpSqrt(ORDER);
1518
+ return sqrtP(f, n);
1519
+ }),
1520
+ invertBatch: (lst) => FpInvertBatch(f, lst),
1521
+ // TODO: do we really need constant cmov?
1522
+ // We don't have const-time bigints anyway, so probably will be not very useful
1523
+ cmov: (a, b, c) => c ? b : a,
1524
+ toBytes: (num) => isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
1525
+ fromBytes: (bytes) => {
1526
+ if (bytes.length !== BYTES)
1527
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
1528
+ return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1529
+ }
1530
+ });
1531
+ return Object.freeze(f);
1532
+ }
1533
+
1534
+ // ../../node_modules/@noble/curves/esm/abstract/curve.js
1535
+ var _0n3 = BigInt(0);
1536
+ var _1n3 = BigInt(1);
1537
+ function constTimeNegate(condition, item) {
1538
+ const neg = item.negate();
1539
+ return condition ? neg : item;
1540
+ }
1541
+ function validateW(W, bits) {
1542
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
1543
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
1544
+ }
1545
+ function calcWOpts(W, bits) {
1546
+ validateW(W, bits);
1547
+ const windows = Math.ceil(bits / W) + 1;
1548
+ const windowSize = 2 ** (W - 1);
1549
+ return { windows, windowSize };
1550
+ }
1551
+ function validateMSMPoints(points, c) {
1552
+ if (!Array.isArray(points))
1553
+ throw new Error("array expected");
1554
+ points.forEach((p, i) => {
1555
+ if (!(p instanceof c))
1556
+ throw new Error("invalid point at index " + i);
1557
+ });
1558
+ }
1559
+ function validateMSMScalars(scalars, field) {
1560
+ if (!Array.isArray(scalars))
1561
+ throw new Error("array of scalars expected");
1562
+ scalars.forEach((s, i) => {
1563
+ if (!field.isValid(s))
1564
+ throw new Error("invalid scalar at index " + i);
1565
+ });
1566
+ }
1567
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
1568
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
1569
+ function getW(P2) {
1570
+ return pointWindowSizes.get(P2) || 1;
1571
+ }
1572
+ function wNAF(c, bits) {
1573
+ return {
1574
+ constTimeNegate,
1575
+ hasPrecomputes(elm) {
1576
+ return getW(elm) !== 1;
1577
+ },
1578
+ // non-const time multiplication ladder
1579
+ unsafeLadder(elm, n, p = c.ZERO) {
1580
+ let d = elm;
1581
+ while (n > _0n3) {
1582
+ if (n & _1n3)
1583
+ p = p.add(d);
1584
+ d = d.double();
1585
+ n >>= _1n3;
1586
+ }
1587
+ return p;
1588
+ },
1589
+ /**
1590
+ * Creates a wNAF precomputation window. Used for caching.
1591
+ * Default window size is set by `utils.precompute()` and is equal to 8.
1592
+ * Number of precomputed points depends on the curve size:
1593
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1594
+ * - 𝑊 is the window size
1595
+ * - 𝑛 is the bitlength of the curve order.
1596
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1597
+ * @param elm Point instance
1598
+ * @param W window size
1599
+ * @returns precomputed point tables flattened to a single array
1600
+ */
1601
+ precomputeWindow(elm, W) {
1602
+ const { windows, windowSize } = calcWOpts(W, bits);
1603
+ const points = [];
1604
+ let p = elm;
1605
+ let base = p;
1606
+ for (let window2 = 0; window2 < windows; window2++) {
1607
+ base = p;
1608
+ points.push(base);
1609
+ for (let i = 1; i < windowSize; i++) {
1610
+ base = base.add(p);
1611
+ points.push(base);
1612
+ }
1613
+ p = base.double();
1614
+ }
1615
+ return points;
1616
+ },
1617
+ /**
1618
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1619
+ * @param W window size
1620
+ * @param precomputes precomputed tables
1621
+ * @param n scalar (we don't check here, but should be less than curve order)
1622
+ * @returns real and fake (for const-time) points
1623
+ */
1624
+ wNAF(W, precomputes, n) {
1625
+ const { windows, windowSize } = calcWOpts(W, bits);
1626
+ let p = c.ZERO;
1627
+ let f = c.BASE;
1628
+ const mask = BigInt(2 ** W - 1);
1629
+ const maxNumber = 2 ** W;
1630
+ const shiftBy = BigInt(W);
1631
+ for (let window2 = 0; window2 < windows; window2++) {
1632
+ const offset = window2 * windowSize;
1633
+ let wbits = Number(n & mask);
1634
+ n >>= shiftBy;
1635
+ if (wbits > windowSize) {
1636
+ wbits -= maxNumber;
1637
+ n += _1n3;
1638
+ }
1639
+ const offset1 = offset;
1640
+ const offset2 = offset + Math.abs(wbits) - 1;
1641
+ const cond1 = window2 % 2 !== 0;
1642
+ const cond2 = wbits < 0;
1643
+ if (wbits === 0) {
1644
+ f = f.add(constTimeNegate(cond1, precomputes[offset1]));
1645
+ } else {
1646
+ p = p.add(constTimeNegate(cond2, precomputes[offset2]));
1647
+ }
1648
+ }
1649
+ return { p, f };
1650
+ },
1651
+ /**
1652
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
1653
+ * @param W window size
1654
+ * @param precomputes precomputed tables
1655
+ * @param n scalar (we don't check here, but should be less than curve order)
1656
+ * @param acc accumulator point to add result of multiplication
1657
+ * @returns point
1658
+ */
1659
+ wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
1660
+ const { windows, windowSize } = calcWOpts(W, bits);
1661
+ const mask = BigInt(2 ** W - 1);
1662
+ const maxNumber = 2 ** W;
1663
+ const shiftBy = BigInt(W);
1664
+ for (let window2 = 0; window2 < windows; window2++) {
1665
+ const offset = window2 * windowSize;
1666
+ if (n === _0n3)
1667
+ break;
1668
+ let wbits = Number(n & mask);
1669
+ n >>= shiftBy;
1670
+ if (wbits > windowSize) {
1671
+ wbits -= maxNumber;
1672
+ n += _1n3;
1673
+ }
1674
+ if (wbits === 0)
1675
+ continue;
1676
+ let curr = precomputes[offset + Math.abs(wbits) - 1];
1677
+ if (wbits < 0)
1678
+ curr = curr.negate();
1679
+ acc = acc.add(curr);
1680
+ }
1681
+ return acc;
1682
+ },
1683
+ getPrecomputes(W, P2, transform) {
1684
+ let comp = pointPrecomputes.get(P2);
1685
+ if (!comp) {
1686
+ comp = this.precomputeWindow(P2, W);
1687
+ if (W !== 1)
1688
+ pointPrecomputes.set(P2, transform(comp));
1689
+ }
1690
+ return comp;
1691
+ },
1692
+ wNAFCached(P2, n, transform) {
1693
+ const W = getW(P2);
1694
+ return this.wNAF(W, this.getPrecomputes(W, P2, transform), n);
1695
+ },
1696
+ wNAFCachedUnsafe(P2, n, transform, prev) {
1697
+ const W = getW(P2);
1698
+ if (W === 1)
1699
+ return this.unsafeLadder(P2, n, prev);
1700
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, P2, transform), n, prev);
1701
+ },
1702
+ // We calculate precomputes for elliptic curve point multiplication
1703
+ // using windowed method. This specifies window size and
1704
+ // stores precomputed values. Usually only base point would be precomputed.
1705
+ setWindowSize(P2, W) {
1706
+ validateW(W, bits);
1707
+ pointWindowSizes.set(P2, W);
1708
+ pointPrecomputes.delete(P2);
1709
+ }
1710
+ };
1711
+ }
1712
+ function pippenger(c, fieldN, points, scalars) {
1713
+ validateMSMPoints(points, c);
1714
+ validateMSMScalars(scalars, fieldN);
1715
+ if (points.length !== scalars.length)
1716
+ throw new Error("arrays of points and scalars must have equal length");
1717
+ const zero = c.ZERO;
1718
+ const wbits = bitLen(BigInt(points.length));
1719
+ const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1;
1720
+ const MASK = (1 << windowSize) - 1;
1721
+ const buckets = new Array(MASK + 1).fill(zero);
1722
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
1723
+ let sum = zero;
1724
+ for (let i = lastBits; i >= 0; i -= windowSize) {
1725
+ buckets.fill(zero);
1726
+ for (let j = 0; j < scalars.length; j++) {
1727
+ const scalar = scalars[j];
1728
+ const wbits2 = Number(scalar >> BigInt(i) & BigInt(MASK));
1729
+ buckets[wbits2] = buckets[wbits2].add(points[j]);
1730
+ }
1731
+ let resI = zero;
1732
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
1733
+ sumI = sumI.add(buckets[j]);
1734
+ resI = resI.add(sumI);
1735
+ }
1736
+ sum = sum.add(resI);
1737
+ if (i !== 0)
1738
+ for (let j = 0; j < windowSize; j++)
1739
+ sum = sum.double();
1740
+ }
1741
+ return sum;
1742
+ }
1743
+ function validateBasic(curve) {
1744
+ validateField(curve.Fp);
1745
+ validateObject(curve, {
1746
+ n: "bigint",
1747
+ h: "bigint",
1748
+ Gx: "field",
1749
+ Gy: "field"
1750
+ }, {
1751
+ nBitLength: "isSafeInteger",
1752
+ nByteLength: "isSafeInteger"
1753
+ });
1754
+ return Object.freeze({
1755
+ ...nLength(curve.n, curve.nBitLength),
1756
+ ...curve,
1757
+ ...{ p: curve.Fp.ORDER }
1758
+ });
1759
+ }
1760
+
1761
+ // ../../node_modules/@noble/curves/esm/abstract/edwards.js
1762
+ var _0n4 = BigInt(0);
1763
+ var _1n4 = BigInt(1);
1764
+ var _2n3 = BigInt(2);
1765
+ var _8n2 = BigInt(8);
1766
+ var VERIFY_DEFAULT = { zip215: true };
1767
+ function validateOpts(curve) {
1768
+ const opts = validateBasic(curve);
1769
+ validateObject(curve, {
1770
+ hash: "function",
1771
+ a: "bigint",
1772
+ d: "bigint",
1773
+ randomBytes: "function"
1774
+ }, {
1775
+ adjustScalarBytes: "function",
1776
+ domain: "function",
1777
+ uvRatio: "function",
1778
+ mapToCurve: "function"
1779
+ });
1780
+ return Object.freeze({ ...opts });
1781
+ }
1782
+ function twistedEdwards(curveDef) {
1783
+ const CURVE = validateOpts(curveDef);
1784
+ const { Fp: Fp2, n: CURVE_ORDER, prehash, hash: cHash, randomBytes: randomBytes2, nByteLength, h: cofactor } = CURVE;
1785
+ const MASK = _2n3 << BigInt(nByteLength * 8) - _1n4;
1786
+ const modP = Fp2.create;
1787
+ const Fn = Field(CURVE.n, CURVE.nBitLength);
1788
+ const uvRatio2 = CURVE.uvRatio || ((u, v) => {
1789
+ try {
1790
+ return { isValid: true, value: Fp2.sqrt(u * Fp2.inv(v)) };
1791
+ } catch (e) {
1792
+ return { isValid: false, value: _0n4 };
1793
+ }
1794
+ });
1795
+ const adjustScalarBytes2 = CURVE.adjustScalarBytes || ((bytes) => bytes);
1796
+ const domain = CURVE.domain || ((data, ctx, phflag) => {
1797
+ abool("phflag", phflag);
1798
+ if (ctx.length || phflag)
1799
+ throw new Error("Contexts/pre-hash are not supported");
1800
+ return data;
1801
+ });
1802
+ function aCoordinate(title, n) {
1803
+ aInRange("coordinate " + title, n, _0n4, MASK);
1804
+ }
1805
+ function assertPoint(other) {
1806
+ if (!(other instanceof Point))
1807
+ throw new Error("ExtendedPoint expected");
1808
+ }
1809
+ const toAffineMemo = memoized((p, iz) => {
1810
+ const { ex: x, ey: y, ez: z } = p;
1811
+ const is0 = p.is0();
1812
+ if (iz == null)
1813
+ iz = is0 ? _8n2 : Fp2.inv(z);
1814
+ const ax = modP(x * iz);
1815
+ const ay = modP(y * iz);
1816
+ const zz = modP(z * iz);
1817
+ if (is0)
1818
+ return { x: _0n4, y: _1n4 };
1819
+ if (zz !== _1n4)
1820
+ throw new Error("invZ was invalid");
1821
+ return { x: ax, y: ay };
1822
+ });
1823
+ const assertValidMemo = memoized((p) => {
1824
+ const { a, d } = CURVE;
1825
+ if (p.is0())
1826
+ throw new Error("bad point: ZERO");
1827
+ const { ex: X, ey: Y, ez: Z, et: T } = p;
1828
+ const X2 = modP(X * X);
1829
+ const Y2 = modP(Y * Y);
1830
+ const Z2 = modP(Z * Z);
1831
+ const Z4 = modP(Z2 * Z2);
1832
+ const aX2 = modP(X2 * a);
1833
+ const left = modP(Z2 * modP(aX2 + Y2));
1834
+ const right = modP(Z4 + modP(d * modP(X2 * Y2)));
1835
+ if (left !== right)
1836
+ throw new Error("bad point: equation left != right (1)");
1837
+ const XY = modP(X * Y);
1838
+ const ZT = modP(Z * T);
1839
+ if (XY !== ZT)
1840
+ throw new Error("bad point: equation left != right (2)");
1841
+ return true;
1842
+ });
1843
+ class Point {
1844
+ constructor(ex, ey, ez, et) {
1845
+ this.ex = ex;
1846
+ this.ey = ey;
1847
+ this.ez = ez;
1848
+ this.et = et;
1849
+ aCoordinate("x", ex);
1850
+ aCoordinate("y", ey);
1851
+ aCoordinate("z", ez);
1852
+ aCoordinate("t", et);
1853
+ Object.freeze(this);
1854
+ }
1855
+ get x() {
1856
+ return this.toAffine().x;
1857
+ }
1858
+ get y() {
1859
+ return this.toAffine().y;
1860
+ }
1861
+ static fromAffine(p) {
1862
+ if (p instanceof Point)
1863
+ throw new Error("extended point not allowed");
1864
+ const { x, y } = p || {};
1865
+ aCoordinate("x", x);
1866
+ aCoordinate("y", y);
1867
+ return new Point(x, y, _1n4, modP(x * y));
1868
+ }
1869
+ static normalizeZ(points) {
1870
+ const toInv = Fp2.invertBatch(points.map((p) => p.ez));
1871
+ return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
1872
+ }
1873
+ // Multiscalar Multiplication
1874
+ static msm(points, scalars) {
1875
+ return pippenger(Point, Fn, points, scalars);
1876
+ }
1877
+ // "Private method", don't use it directly
1878
+ _setWindowSize(windowSize) {
1879
+ wnaf.setWindowSize(this, windowSize);
1880
+ }
1881
+ // Not required for fromHex(), which always creates valid points.
1882
+ // Could be useful for fromAffine().
1883
+ assertValidity() {
1884
+ assertValidMemo(this);
1885
+ }
1886
+ // Compare one point to another.
1887
+ equals(other) {
1888
+ assertPoint(other);
1889
+ const { ex: X1, ey: Y1, ez: Z1 } = this;
1890
+ const { ex: X2, ey: Y2, ez: Z2 } = other;
1891
+ const X1Z2 = modP(X1 * Z2);
1892
+ const X2Z1 = modP(X2 * Z1);
1893
+ const Y1Z2 = modP(Y1 * Z2);
1894
+ const Y2Z1 = modP(Y2 * Z1);
1895
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
1896
+ }
1897
+ is0() {
1898
+ return this.equals(Point.ZERO);
1899
+ }
1900
+ negate() {
1901
+ return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));
1902
+ }
1903
+ // Fast algo for doubling Extended Point.
1904
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
1905
+ // Cost: 4M + 4S + 1*a + 6add + 1*2.
1906
+ double() {
1907
+ const { a } = CURVE;
1908
+ const { ex: X1, ey: Y1, ez: Z1 } = this;
1909
+ const A = modP(X1 * X1);
1910
+ const B = modP(Y1 * Y1);
1911
+ const C = modP(_2n3 * modP(Z1 * Z1));
1912
+ const D = modP(a * A);
1913
+ const x1y1 = X1 + Y1;
1914
+ const E = modP(modP(x1y1 * x1y1) - A - B);
1915
+ const G2 = D + B;
1916
+ const F = G2 - C;
1917
+ const H = D - B;
1918
+ const X3 = modP(E * F);
1919
+ const Y3 = modP(G2 * H);
1920
+ const T3 = modP(E * H);
1921
+ const Z3 = modP(F * G2);
1922
+ return new Point(X3, Y3, Z3, T3);
1923
+ }
1924
+ // Fast algo for adding 2 Extended Points.
1925
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
1926
+ // Cost: 9M + 1*a + 1*d + 7add.
1927
+ add(other) {
1928
+ assertPoint(other);
1929
+ const { a, d } = CURVE;
1930
+ const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
1931
+ const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;
1932
+ if (a === BigInt(-1)) {
1933
+ const A2 = modP((Y1 - X1) * (Y2 + X2));
1934
+ const B2 = modP((Y1 + X1) * (Y2 - X2));
1935
+ const F2 = modP(B2 - A2);
1936
+ if (F2 === _0n4)
1937
+ return this.double();
1938
+ const C2 = modP(Z1 * _2n3 * T2);
1939
+ const D2 = modP(T1 * _2n3 * Z2);
1940
+ const E2 = D2 + C2;
1941
+ const G3 = B2 + A2;
1942
+ const H2 = D2 - C2;
1943
+ const X32 = modP(E2 * F2);
1944
+ const Y32 = modP(G3 * H2);
1945
+ const T32 = modP(E2 * H2);
1946
+ const Z32 = modP(F2 * G3);
1947
+ return new Point(X32, Y32, Z32, T32);
1948
+ }
1949
+ const A = modP(X1 * X2);
1950
+ const B = modP(Y1 * Y2);
1951
+ const C = modP(T1 * d * T2);
1952
+ const D = modP(Z1 * Z2);
1953
+ const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
1954
+ const F = D - C;
1955
+ const G2 = D + C;
1956
+ const H = modP(B - a * A);
1957
+ const X3 = modP(E * F);
1958
+ const Y3 = modP(G2 * H);
1959
+ const T3 = modP(E * H);
1960
+ const Z3 = modP(F * G2);
1961
+ return new Point(X3, Y3, Z3, T3);
1962
+ }
1963
+ subtract(other) {
1964
+ return this.add(other.negate());
1965
+ }
1966
+ wNAF(n) {
1967
+ return wnaf.wNAFCached(this, n, Point.normalizeZ);
1968
+ }
1969
+ // Constant-time multiplication.
1970
+ multiply(scalar) {
1971
+ const n = scalar;
1972
+ aInRange("scalar", n, _1n4, CURVE_ORDER);
1973
+ const { p, f } = this.wNAF(n);
1974
+ return Point.normalizeZ([p, f])[0];
1975
+ }
1976
+ // Non-constant-time multiplication. Uses double-and-add algorithm.
1977
+ // It's faster, but should only be used when you don't care about
1978
+ // an exposed private key e.g. sig verification.
1979
+ // Does NOT allow scalars higher than CURVE.n.
1980
+ // Accepts optional accumulator to merge with multiply (important for sparse scalars)
1981
+ multiplyUnsafe(scalar, acc = Point.ZERO) {
1982
+ const n = scalar;
1983
+ aInRange("scalar", n, _0n4, CURVE_ORDER);
1984
+ if (n === _0n4)
1985
+ return I;
1986
+ if (this.is0() || n === _1n4)
1987
+ return this;
1988
+ return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, acc);
1989
+ }
1990
+ // Checks if point is of small order.
1991
+ // If you add something to small order point, you will have "dirty"
1992
+ // point with torsion component.
1993
+ // Multiplies point by cofactor and checks if the result is 0.
1994
+ isSmallOrder() {
1995
+ return this.multiplyUnsafe(cofactor).is0();
1996
+ }
1997
+ // Multiplies point by curve order and checks if the result is 0.
1998
+ // Returns `false` is the point is dirty.
1999
+ isTorsionFree() {
2000
+ return wnaf.unsafeLadder(this, CURVE_ORDER).is0();
2001
+ }
2002
+ // Converts Extended point to default (x, y) coordinates.
2003
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
2004
+ toAffine(iz) {
2005
+ return toAffineMemo(this, iz);
2006
+ }
2007
+ clearCofactor() {
2008
+ const { h: cofactor2 } = CURVE;
2009
+ if (cofactor2 === _1n4)
2010
+ return this;
2011
+ return this.multiplyUnsafe(cofactor2);
2012
+ }
2013
+ // Converts hash string or Uint8Array to Point.
2014
+ // Uses algo from RFC8032 5.1.3.
2015
+ static fromHex(hex, zip215 = false) {
2016
+ const { d, a } = CURVE;
2017
+ const len = Fp2.BYTES;
2018
+ hex = ensureBytes("pointHex", hex, len);
2019
+ abool("zip215", zip215);
2020
+ const normed = hex.slice();
2021
+ const lastByte = hex[len - 1];
2022
+ normed[len - 1] = lastByte & ~128;
2023
+ const y = bytesToNumberLE(normed);
2024
+ const max = zip215 ? MASK : Fp2.ORDER;
2025
+ aInRange("pointHex.y", y, _0n4, max);
2026
+ const y2 = modP(y * y);
2027
+ const u = modP(y2 - _1n4);
2028
+ const v = modP(d * y2 - a);
2029
+ let { isValid, value: x } = uvRatio2(u, v);
2030
+ if (!isValid)
2031
+ throw new Error("Point.fromHex: invalid y coordinate");
2032
+ const isXOdd = (x & _1n4) === _1n4;
2033
+ const isLastByteOdd = (lastByte & 128) !== 0;
2034
+ if (!zip215 && x === _0n4 && isLastByteOdd)
2035
+ throw new Error("Point.fromHex: x=0 and x_0=1");
2036
+ if (isLastByteOdd !== isXOdd)
2037
+ x = modP(-x);
2038
+ return Point.fromAffine({ x, y });
2039
+ }
2040
+ static fromPrivateKey(privKey) {
2041
+ return getExtendedPublicKey(privKey).point;
2042
+ }
2043
+ toRawBytes() {
2044
+ const { x, y } = this.toAffine();
2045
+ const bytes = numberToBytesLE(y, Fp2.BYTES);
2046
+ bytes[bytes.length - 1] |= x & _1n4 ? 128 : 0;
2047
+ return bytes;
2048
+ }
2049
+ toHex() {
2050
+ return bytesToHex(this.toRawBytes());
2051
+ }
2052
+ }
2053
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n4, modP(CURVE.Gx * CURVE.Gy));
2054
+ Point.ZERO = new Point(_0n4, _1n4, _1n4, _0n4);
2055
+ const { BASE: G, ZERO: I } = Point;
2056
+ const wnaf = wNAF(Point, nByteLength * 8);
2057
+ function modN(a) {
2058
+ return mod(a, CURVE_ORDER);
2059
+ }
2060
+ function modN_LE(hash) {
2061
+ return modN(bytesToNumberLE(hash));
2062
+ }
2063
+ function getExtendedPublicKey(key) {
2064
+ const len = Fp2.BYTES;
2065
+ key = ensureBytes("private key", key, len);
2066
+ const hashed = ensureBytes("hashed private key", cHash(key), 2 * len);
2067
+ const head = adjustScalarBytes2(hashed.slice(0, len));
2068
+ const prefix = hashed.slice(len, 2 * len);
2069
+ const scalar = modN_LE(head);
2070
+ const point = G.multiply(scalar);
2071
+ const pointBytes = point.toRawBytes();
2072
+ return { head, prefix, scalar, point, pointBytes };
2073
+ }
2074
+ function getPublicKey(privKey) {
2075
+ return getExtendedPublicKey(privKey).pointBytes;
2076
+ }
2077
+ function hashDomainToScalar(context = new Uint8Array(), ...msgs) {
2078
+ const msg = concatBytes(...msgs);
2079
+ return modN_LE(cHash(domain(msg, ensureBytes("context", context), !!prehash)));
2080
+ }
2081
+ function sign(msg, privKey, options = {}) {
2082
+ msg = ensureBytes("message", msg);
2083
+ if (prehash)
2084
+ msg = prehash(msg);
2085
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);
2086
+ const r = hashDomainToScalar(options.context, prefix, msg);
2087
+ const R = G.multiply(r).toRawBytes();
2088
+ const k = hashDomainToScalar(options.context, R, pointBytes, msg);
2089
+ const s = modN(r + k * scalar);
2090
+ aInRange("signature.s", s, _0n4, CURVE_ORDER);
2091
+ const res = concatBytes(R, numberToBytesLE(s, Fp2.BYTES));
2092
+ return ensureBytes("result", res, Fp2.BYTES * 2);
2093
+ }
2094
+ const verifyOpts = VERIFY_DEFAULT;
2095
+ function verify(sig, msg, publicKey, options = verifyOpts) {
2096
+ const { context, zip215 } = options;
2097
+ const len = Fp2.BYTES;
2098
+ sig = ensureBytes("signature", sig, 2 * len);
2099
+ msg = ensureBytes("message", msg);
2100
+ publicKey = ensureBytes("publicKey", publicKey, len);
2101
+ if (zip215 !== void 0)
2102
+ abool("zip215", zip215);
2103
+ if (prehash)
2104
+ msg = prehash(msg);
2105
+ const s = bytesToNumberLE(sig.slice(len, 2 * len));
2106
+ let A, R, SB;
2107
+ try {
2108
+ A = Point.fromHex(publicKey, zip215);
2109
+ R = Point.fromHex(sig.slice(0, len), zip215);
2110
+ SB = G.multiplyUnsafe(s);
2111
+ } catch (error) {
2112
+ return false;
2113
+ }
2114
+ if (!zip215 && A.isSmallOrder())
2115
+ return false;
2116
+ const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);
2117
+ const RkA = R.add(A.multiplyUnsafe(k));
2118
+ return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);
2119
+ }
2120
+ G._setWindowSize(8);
2121
+ const utils = {
2122
+ getExtendedPublicKey,
2123
+ // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.
2124
+ randomPrivateKey: () => randomBytes2(Fp2.BYTES),
2125
+ /**
2126
+ * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT
2127
+ * values. This slows down first getPublicKey() by milliseconds (see Speed section),
2128
+ * but allows to speed-up subsequent getPublicKey() calls up to 20x.
2129
+ * @param windowSize 2, 4, 8, 16
2130
+ */
2131
+ precompute(windowSize = 8, point = Point.BASE) {
2132
+ point._setWindowSize(windowSize);
2133
+ point.multiply(BigInt(3));
2134
+ return point;
2135
+ }
2136
+ };
2137
+ return {
2138
+ CURVE,
2139
+ getPublicKey,
2140
+ sign,
2141
+ verify,
2142
+ ExtendedPoint: Point,
2143
+ utils
2144
+ };
2145
+ }
2146
+
2147
+ // ../../node_modules/@noble/curves/esm/ed25519.js
2148
+ var ED25519_P = BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");
2149
+ var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
2150
+ var _0n5 = BigInt(0);
2151
+ var _1n5 = BigInt(1);
2152
+ var _2n4 = BigInt(2);
2153
+ var _3n2 = BigInt(3);
2154
+ var _5n2 = BigInt(5);
2155
+ var _8n3 = BigInt(8);
2156
+ function ed25519_pow_2_252_3(x) {
2157
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
2158
+ const P2 = ED25519_P;
2159
+ const x2 = x * x % P2;
2160
+ const b2 = x2 * x % P2;
2161
+ const b4 = pow2(b2, _2n4, P2) * b2 % P2;
2162
+ const b5 = pow2(b4, _1n5, P2) * x % P2;
2163
+ const b10 = pow2(b5, _5n2, P2) * b5 % P2;
2164
+ const b20 = pow2(b10, _10n, P2) * b10 % P2;
2165
+ const b40 = pow2(b20, _20n, P2) * b20 % P2;
2166
+ const b80 = pow2(b40, _40n, P2) * b40 % P2;
2167
+ const b160 = pow2(b80, _80n, P2) * b80 % P2;
2168
+ const b240 = pow2(b160, _80n, P2) * b80 % P2;
2169
+ const b250 = pow2(b240, _10n, P2) * b10 % P2;
2170
+ const pow_p_5_8 = pow2(b250, _2n4, P2) * x % P2;
2171
+ return { pow_p_5_8, b2 };
2172
+ }
2173
+ function adjustScalarBytes(bytes) {
2174
+ bytes[0] &= 248;
2175
+ bytes[31] &= 127;
2176
+ bytes[31] |= 64;
2177
+ return bytes;
2178
+ }
2179
+ function uvRatio(u, v) {
2180
+ const P2 = ED25519_P;
2181
+ const v3 = mod(v * v * v, P2);
2182
+ const v7 = mod(v3 * v3 * v, P2);
2183
+ const pow3 = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
2184
+ let x = mod(u * v3 * pow3, P2);
2185
+ const vx2 = mod(v * x * x, P2);
2186
+ const root1 = x;
2187
+ const root2 = mod(x * ED25519_SQRT_M1, P2);
2188
+ const useRoot1 = vx2 === u;
2189
+ const useRoot2 = vx2 === mod(-u, P2);
2190
+ const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P2);
2191
+ if (useRoot1)
2192
+ x = root1;
2193
+ if (useRoot2 || noRoot)
2194
+ x = root2;
2195
+ if (isNegativeLE(x, P2))
2196
+ x = mod(-x, P2);
2197
+ return { isValid: useRoot1 || useRoot2, value: x };
2198
+ }
2199
+ var Fp = /* @__PURE__ */ (() => Field(ED25519_P, void 0, true))();
2200
+ var ed25519Defaults = /* @__PURE__ */ (() => ({
2201
+ // Param: a
2202
+ a: BigInt(-1),
2203
+ // Fp.create(-1) is proper; our way still works and is faster
2204
+ // d is equal to -121665/121666 over finite field.
2205
+ // Negative number is P - number, and division is invert(number, P)
2206
+ d: BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),
2207
+ // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n
2208
+ Fp,
2209
+ // Subgroup order: how many points curve has
2210
+ // 2n**252n + 27742317777372353535851937790883648493n;
2211
+ n: BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),
2212
+ // Cofactor
2213
+ h: _8n3,
2214
+ // Base point (x, y) aka generator point
2215
+ Gx: BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),
2216
+ Gy: BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),
2217
+ hash: sha512,
2218
+ randomBytes,
2219
+ adjustScalarBytes,
2220
+ // dom2
2221
+ // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
2222
+ // Constant-time, u/√v
2223
+ uvRatio
2224
+ }))();
2225
+ var ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
2226
+
2227
+ // ../../node_modules/@noble/hashes/esm/_assert.js
2228
+ function isBytes3(a) {
2229
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
2230
+ }
2231
+ function abytes3(b, ...lengths) {
2232
+ if (!isBytes3(b))
2233
+ throw new Error("Uint8Array expected");
2234
+ if (lengths.length > 0 && !lengths.includes(b.length))
2235
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
2236
+ }
2237
+ function aexists2(instance, checkFinished = true) {
2238
+ if (instance.destroyed)
2239
+ throw new Error("Hash instance has been destroyed");
2240
+ if (checkFinished && instance.finished)
2241
+ throw new Error("Hash#digest() has already been called");
2242
+ }
2243
+ function aoutput2(out, instance) {
2244
+ abytes3(out);
2245
+ const min = instance.outputLen;
2246
+ if (out.length < min) {
2247
+ throw new Error("digestInto() expects output buffer of length at least " + min);
2248
+ }
2249
+ }
2250
+
2251
+ // ../../node_modules/@noble/hashes/esm/utils.js
2252
+ var createView2 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
2253
+ var rotr = (word, shift) => word << 32 - shift | word >>> shift;
2254
+ function utf8ToBytes2(str) {
2255
+ if (typeof str !== "string")
2256
+ throw new Error("utf8ToBytes expected string, got " + typeof str);
2257
+ return new Uint8Array(new TextEncoder().encode(str));
2258
+ }
2259
+ function toBytes2(data) {
2260
+ if (typeof data === "string")
2261
+ data = utf8ToBytes2(data);
2262
+ abytes3(data);
2263
+ return data;
2264
+ }
2265
+ var Hash2 = class {
2266
+ // Safe version that clones internal state
2267
+ clone() {
2268
+ return this._cloneInto();
2269
+ }
2270
+ };
2271
+ function wrapConstructor2(hashCons) {
2272
+ const hashC = (msg) => hashCons().update(toBytes2(msg)).digest();
2273
+ const tmp = hashCons();
2274
+ hashC.outputLen = tmp.outputLen;
2275
+ hashC.blockLen = tmp.blockLen;
2276
+ hashC.create = () => hashCons();
2277
+ return hashC;
2278
+ }
2279
+
2280
+ // ../../node_modules/@noble/hashes/esm/_md.js
2281
+ function setBigUint642(view, byteOffset, value, isLE) {
2282
+ if (typeof view.setBigUint64 === "function")
2283
+ return view.setBigUint64(byteOffset, value, isLE);
2284
+ const _32n2 = BigInt(32);
2285
+ const _u32_max = BigInt(4294967295);
2286
+ const wh = Number(value >> _32n2 & _u32_max);
2287
+ const wl = Number(value & _u32_max);
2288
+ const h = isLE ? 4 : 0;
2289
+ const l = isLE ? 0 : 4;
2290
+ view.setUint32(byteOffset + h, wh, isLE);
2291
+ view.setUint32(byteOffset + l, wl, isLE);
2292
+ }
2293
+ var Chi = (a, b, c) => a & b ^ ~a & c;
2294
+ var Maj = (a, b, c) => a & b ^ a & c ^ b & c;
2295
+ var HashMD2 = class extends Hash2 {
2296
+ constructor(blockLen, outputLen, padOffset, isLE) {
2297
+ super();
2298
+ this.blockLen = blockLen;
2299
+ this.outputLen = outputLen;
2300
+ this.padOffset = padOffset;
2301
+ this.isLE = isLE;
2302
+ this.finished = false;
2303
+ this.length = 0;
2304
+ this.pos = 0;
2305
+ this.destroyed = false;
2306
+ this.buffer = new Uint8Array(blockLen);
2307
+ this.view = createView2(this.buffer);
2308
+ }
2309
+ update(data) {
2310
+ aexists2(this);
2311
+ const { view, buffer, blockLen } = this;
2312
+ data = toBytes2(data);
2313
+ const len = data.length;
2314
+ for (let pos = 0; pos < len; ) {
2315
+ const take = Math.min(blockLen - this.pos, len - pos);
2316
+ if (take === blockLen) {
2317
+ const dataView = createView2(data);
2318
+ for (; blockLen <= len - pos; pos += blockLen)
2319
+ this.process(dataView, pos);
2320
+ continue;
2321
+ }
2322
+ buffer.set(data.subarray(pos, pos + take), this.pos);
2323
+ this.pos += take;
2324
+ pos += take;
2325
+ if (this.pos === blockLen) {
2326
+ this.process(view, 0);
2327
+ this.pos = 0;
2328
+ }
2329
+ }
2330
+ this.length += data.length;
2331
+ this.roundClean();
2332
+ return this;
2333
+ }
2334
+ digestInto(out) {
2335
+ aexists2(this);
2336
+ aoutput2(out, this);
2337
+ this.finished = true;
2338
+ const { buffer, view, blockLen, isLE } = this;
2339
+ let { pos } = this;
2340
+ buffer[pos++] = 128;
2341
+ this.buffer.subarray(pos).fill(0);
2342
+ if (this.padOffset > blockLen - pos) {
2343
+ this.process(view, 0);
2344
+ pos = 0;
2345
+ }
2346
+ for (let i = pos; i < blockLen; i++)
2347
+ buffer[i] = 0;
2348
+ setBigUint642(view, blockLen - 8, BigInt(this.length * 8), isLE);
2349
+ this.process(view, 0);
2350
+ const oview = createView2(out);
2351
+ const len = this.outputLen;
2352
+ if (len % 4)
2353
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
2354
+ const outLen = len / 4;
2355
+ const state = this.get();
2356
+ if (outLen > state.length)
2357
+ throw new Error("_sha2: outputLen bigger than state");
2358
+ for (let i = 0; i < outLen; i++)
2359
+ oview.setUint32(4 * i, state[i], isLE);
2360
+ }
2361
+ digest() {
2362
+ const { buffer, outputLen } = this;
2363
+ this.digestInto(buffer);
2364
+ const res = buffer.slice(0, outputLen);
2365
+ this.destroy();
2366
+ return res;
2367
+ }
2368
+ _cloneInto(to) {
2369
+ to || (to = new this.constructor());
2370
+ to.set(...this.get());
2371
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
2372
+ to.length = length;
2373
+ to.pos = pos;
2374
+ to.finished = finished;
2375
+ to.destroyed = destroyed;
2376
+ if (length % blockLen)
2377
+ to.buffer.set(buffer);
2378
+ return to;
2379
+ }
2380
+ };
2381
+
2382
+ // ../../node_modules/@noble/hashes/esm/sha256.js
2383
+ var SHA256_K = /* @__PURE__ */ new Uint32Array([
2384
+ 1116352408,
2385
+ 1899447441,
2386
+ 3049323471,
2387
+ 3921009573,
2388
+ 961987163,
2389
+ 1508970993,
2390
+ 2453635748,
2391
+ 2870763221,
2392
+ 3624381080,
2393
+ 310598401,
2394
+ 607225278,
2395
+ 1426881987,
2396
+ 1925078388,
2397
+ 2162078206,
2398
+ 2614888103,
2399
+ 3248222580,
2400
+ 3835390401,
2401
+ 4022224774,
2402
+ 264347078,
2403
+ 604807628,
2404
+ 770255983,
2405
+ 1249150122,
2406
+ 1555081692,
2407
+ 1996064986,
2408
+ 2554220882,
2409
+ 2821834349,
2410
+ 2952996808,
2411
+ 3210313671,
2412
+ 3336571891,
2413
+ 3584528711,
2414
+ 113926993,
2415
+ 338241895,
2416
+ 666307205,
2417
+ 773529912,
2418
+ 1294757372,
2419
+ 1396182291,
2420
+ 1695183700,
2421
+ 1986661051,
2422
+ 2177026350,
2423
+ 2456956037,
2424
+ 2730485921,
2425
+ 2820302411,
2426
+ 3259730800,
2427
+ 3345764771,
2428
+ 3516065817,
2429
+ 3600352804,
2430
+ 4094571909,
2431
+ 275423344,
2432
+ 430227734,
2433
+ 506948616,
2434
+ 659060556,
2435
+ 883997877,
2436
+ 958139571,
2437
+ 1322822218,
2438
+ 1537002063,
2439
+ 1747873779,
2440
+ 1955562222,
2441
+ 2024104815,
2442
+ 2227730452,
2443
+ 2361852424,
2444
+ 2428436474,
2445
+ 2756734187,
2446
+ 3204031479,
2447
+ 3329325298
2448
+ ]);
2449
+ var SHA256_IV = /* @__PURE__ */ new Uint32Array([
2450
+ 1779033703,
2451
+ 3144134277,
2452
+ 1013904242,
2453
+ 2773480762,
2454
+ 1359893119,
2455
+ 2600822924,
2456
+ 528734635,
2457
+ 1541459225
2458
+ ]);
2459
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
2460
+ var SHA256 = class extends HashMD2 {
2461
+ constructor() {
2462
+ super(64, 32, 8, false);
2463
+ this.A = SHA256_IV[0] | 0;
2464
+ this.B = SHA256_IV[1] | 0;
2465
+ this.C = SHA256_IV[2] | 0;
2466
+ this.D = SHA256_IV[3] | 0;
2467
+ this.E = SHA256_IV[4] | 0;
2468
+ this.F = SHA256_IV[5] | 0;
2469
+ this.G = SHA256_IV[6] | 0;
2470
+ this.H = SHA256_IV[7] | 0;
2471
+ }
2472
+ get() {
2473
+ const { A, B, C, D, E, F, G, H } = this;
2474
+ return [A, B, C, D, E, F, G, H];
2475
+ }
2476
+ // prettier-ignore
2477
+ set(A, B, C, D, E, F, G, H) {
2478
+ this.A = A | 0;
2479
+ this.B = B | 0;
2480
+ this.C = C | 0;
2481
+ this.D = D | 0;
2482
+ this.E = E | 0;
2483
+ this.F = F | 0;
2484
+ this.G = G | 0;
2485
+ this.H = H | 0;
2486
+ }
2487
+ process(view, offset) {
2488
+ for (let i = 0; i < 16; i++, offset += 4)
2489
+ SHA256_W[i] = view.getUint32(offset, false);
2490
+ for (let i = 16; i < 64; i++) {
2491
+ const W15 = SHA256_W[i - 15];
2492
+ const W2 = SHA256_W[i - 2];
2493
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
2494
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
2495
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
2496
+ }
2497
+ let { A, B, C, D, E, F, G, H } = this;
2498
+ for (let i = 0; i < 64; i++) {
2499
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
2500
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
2501
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
2502
+ const T2 = sigma0 + Maj(A, B, C) | 0;
2503
+ H = G;
2504
+ G = F;
2505
+ F = E;
2506
+ E = D + T1 | 0;
2507
+ D = C;
2508
+ C = B;
2509
+ B = A;
2510
+ A = T1 + T2 | 0;
2511
+ }
2512
+ A = A + this.A | 0;
2513
+ B = B + this.B | 0;
2514
+ C = C + this.C | 0;
2515
+ D = D + this.D | 0;
2516
+ E = E + this.E | 0;
2517
+ F = F + this.F | 0;
2518
+ G = G + this.G | 0;
2519
+ H = H + this.H | 0;
2520
+ this.set(A, B, C, D, E, F, G, H);
2521
+ }
2522
+ roundClean() {
2523
+ SHA256_W.fill(0);
2524
+ }
2525
+ destroy() {
2526
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
2527
+ this.buffer.fill(0);
2528
+ }
2529
+ };
2530
+ var sha256 = /* @__PURE__ */ wrapConstructor2(() => new SHA256());
2531
+
2532
+ // ../../node_modules/base58-js/base58_chars.mjs
2533
+ var base58_chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
2534
+ var base58_chars_default = base58_chars;
2535
+
2536
+ // ../../node_modules/base58-js/base58_to_binary.mjs
2537
+ function base58_to_binary(base58String) {
2538
+ if (!base58String || typeof base58String !== "string")
2539
+ throw new Error(`Expected base58 string but got \u201C${base58String}\u201D`);
2540
+ if (base58String.match(/[IOl0]/gmu))
2541
+ throw new Error(
2542
+ `Invalid base58 character \u201C${base58String.match(/[IOl0]/gmu)}\u201D`
2543
+ );
2544
+ const lz = base58String.match(/^1+/gmu);
2545
+ const psz = lz ? lz[0].length : 0;
2546
+ const size = (base58String.length - psz) * (Math.log(58) / Math.log(256)) + 1 >>> 0;
2547
+ return new Uint8Array([
2548
+ ...new Uint8Array(psz),
2549
+ ...base58String.match(/.{1}/gmu).map((i) => base58_chars_default.indexOf(i)).reduce((acc, i) => {
2550
+ acc = acc.map((j) => {
2551
+ const x = j * 58 + i;
2552
+ i = x >> 8;
2553
+ return x;
2554
+ });
2555
+ return acc;
2556
+ }, new Uint8Array(size)).reverse().filter(
2557
+ /* @__PURE__ */ ((lastValue) => (value) => (
2558
+ // @ts-ignore
2559
+ lastValue = lastValue || value
2560
+ ))(false)
2561
+ )
2562
+ ]);
2563
+ }
2564
+ var base58_to_binary_default = base58_to_binary;
2565
+
2566
+ // ../../node_modules/base58-js/create_base58_map.mjs
2567
+ var create_base58_map = () => {
2568
+ const base58M = Array(256).fill(-1);
2569
+ for (let i = 0; i < base58_chars_default.length; ++i)
2570
+ base58M[base58_chars_default.charCodeAt(i)] = i;
2571
+ return base58M;
2572
+ };
2573
+ var create_base58_map_default = create_base58_map;
2574
+
2575
+ // ../../node_modules/base58-js/binary_to_base58.mjs
2576
+ var base58Map = create_base58_map_default();
2577
+ function binary_to_base58(uint8array) {
2578
+ const result = [];
2579
+ for (const byte of uint8array) {
2580
+ let carry = byte;
2581
+ for (let j = 0; j < result.length; ++j) {
2582
+ const x = (base58Map[result[j]] << 8) + carry;
2583
+ result[j] = base58_chars_default.charCodeAt(x % 58);
2584
+ carry = x / 58 | 0;
2585
+ }
2586
+ while (carry) {
2587
+ result.push(base58_chars_default.charCodeAt(carry % 58));
2588
+ carry = carry / 58 | 0;
2589
+ }
2590
+ }
2591
+ for (const byte of uint8array)
2592
+ if (byte) break;
2593
+ else result.push("1".charCodeAt(0));
2594
+ result.reverse();
2595
+ return String.fromCharCode(...result);
2596
+ }
2597
+ var binary_to_base58_default = binary_to_base58;
2598
+
2599
+ // ../../node_modules/js-base64/base64.mjs
2600
+ var _hasBuffer = typeof Buffer === "function";
2601
+ var _TD = typeof TextDecoder === "function" ? new TextDecoder() : void 0;
2602
+ var _TE = typeof TextEncoder === "function" ? new TextEncoder() : void 0;
2603
+ var b64ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
2604
+ var b64chs = Array.prototype.slice.call(b64ch);
2605
+ var b64tab = ((a) => {
2606
+ let tab = {};
2607
+ a.forEach((c, i) => tab[c] = i);
2608
+ return tab;
2609
+ })(b64chs);
2610
+ var b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
2611
+ var _fromCC = String.fromCharCode.bind(String);
2612
+ var _U8Afrom = typeof Uint8Array.from === "function" ? Uint8Array.from.bind(Uint8Array) : (it) => new Uint8Array(Array.prototype.slice.call(it, 0));
2613
+ var _mkUriSafe = (src) => src.replace(/=/g, "").replace(/[+\/]/g, (m0) => m0 == "+" ? "-" : "_");
2614
+ var _tidyB64 = (s) => s.replace(/[^A-Za-z0-9\+\/]/g, "");
2615
+ var btoaPolyfill = (bin) => {
2616
+ let u32, c0, c1, c2, asc = "";
2617
+ const pad = bin.length % 3;
2618
+ for (let i = 0; i < bin.length; ) {
2619
+ if ((c0 = bin.charCodeAt(i++)) > 255 || (c1 = bin.charCodeAt(i++)) > 255 || (c2 = bin.charCodeAt(i++)) > 255)
2620
+ throw new TypeError("invalid character found");
2621
+ u32 = c0 << 16 | c1 << 8 | c2;
2622
+ asc += b64chs[u32 >> 18 & 63] + b64chs[u32 >> 12 & 63] + b64chs[u32 >> 6 & 63] + b64chs[u32 & 63];
2623
+ }
2624
+ return pad ? asc.slice(0, pad - 3) + "===".substring(pad) : asc;
2625
+ };
2626
+ var _btoa = typeof btoa === "function" ? (bin) => btoa(bin) : _hasBuffer ? (bin) => Buffer.from(bin, "binary").toString("base64") : btoaPolyfill;
2627
+ var _fromUint8Array = _hasBuffer ? (u8a) => Buffer.from(u8a).toString("base64") : (u8a) => {
2628
+ const maxargs = 4096;
2629
+ let strs = [];
2630
+ for (let i = 0, l = u8a.length; i < l; i += maxargs) {
2631
+ strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs)));
2632
+ }
2633
+ return _btoa(strs.join(""));
2634
+ };
2635
+ var cb_utob = (c) => {
2636
+ if (c.length < 2) {
2637
+ var cc = c.charCodeAt(0);
2638
+ return cc < 128 ? c : cc < 2048 ? _fromCC(192 | cc >>> 6) + _fromCC(128 | cc & 63) : _fromCC(224 | cc >>> 12 & 15) + _fromCC(128 | cc >>> 6 & 63) + _fromCC(128 | cc & 63);
2639
+ } else {
2640
+ var cc = 65536 + (c.charCodeAt(0) - 55296) * 1024 + (c.charCodeAt(1) - 56320);
2641
+ return _fromCC(240 | cc >>> 18 & 7) + _fromCC(128 | cc >>> 12 & 63) + _fromCC(128 | cc >>> 6 & 63) + _fromCC(128 | cc & 63);
2642
+ }
2643
+ };
2644
+ var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
2645
+ var utob = (u) => u.replace(re_utob, cb_utob);
2646
+ var _encode = _hasBuffer ? (s) => Buffer.from(s, "utf8").toString("base64") : _TE ? (s) => _fromUint8Array(_TE.encode(s)) : (s) => _btoa(utob(s));
2647
+ var encode = (src, urlsafe = false) => urlsafe ? _mkUriSafe(_encode(src)) : _encode(src);
2648
+ var re_btou = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g;
2649
+ var cb_btou = (cccc) => {
2650
+ switch (cccc.length) {
2651
+ case 4:
2652
+ var cp = (7 & cccc.charCodeAt(0)) << 18 | (63 & cccc.charCodeAt(1)) << 12 | (63 & cccc.charCodeAt(2)) << 6 | 63 & cccc.charCodeAt(3), offset = cp - 65536;
2653
+ return _fromCC((offset >>> 10) + 55296) + _fromCC((offset & 1023) + 56320);
2654
+ case 3:
2655
+ return _fromCC((15 & cccc.charCodeAt(0)) << 12 | (63 & cccc.charCodeAt(1)) << 6 | 63 & cccc.charCodeAt(2));
2656
+ default:
2657
+ return _fromCC((31 & cccc.charCodeAt(0)) << 6 | 63 & cccc.charCodeAt(1));
2658
+ }
2659
+ };
2660
+ var btou = (b) => b.replace(re_btou, cb_btou);
2661
+ var atobPolyfill = (asc) => {
2662
+ asc = asc.replace(/\s+/g, "");
2663
+ if (!b64re.test(asc))
2664
+ throw new TypeError("malformed base64.");
2665
+ asc += "==".slice(2 - (asc.length & 3));
2666
+ let u24, bin = "", r1, r2;
2667
+ for (let i = 0; i < asc.length; ) {
2668
+ u24 = b64tab[asc.charAt(i++)] << 18 | b64tab[asc.charAt(i++)] << 12 | (r1 = b64tab[asc.charAt(i++)]) << 6 | (r2 = b64tab[asc.charAt(i++)]);
2669
+ bin += r1 === 64 ? _fromCC(u24 >> 16 & 255) : r2 === 64 ? _fromCC(u24 >> 16 & 255, u24 >> 8 & 255) : _fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255);
2670
+ }
2671
+ return bin;
2672
+ };
2673
+ var _atob = typeof atob === "function" ? (asc) => atob(_tidyB64(asc)) : _hasBuffer ? (asc) => Buffer.from(asc, "base64").toString("binary") : atobPolyfill;
2674
+ var _toUint8Array = _hasBuffer ? (a) => _U8Afrom(Buffer.from(a, "base64")) : (a) => _U8Afrom(_atob(a).split("").map((c) => c.charCodeAt(0)));
2675
+ var _decode = _hasBuffer ? (a) => Buffer.from(a, "base64").toString("utf8") : _TD ? (a) => _TD.decode(_toUint8Array(a)) : (a) => btou(_atob(a));
2676
+ var _unURI = (a) => _tidyB64(a.replace(/[-_]/g, (m0) => m0 == "-" ? "+" : "/"));
2677
+ var decode = (src) => _decode(_unURI(src));
2678
+
2679
+ // src/utils.ts
2680
+ var LsPrefix = "__fastnear_";
2681
+ function toBase64(data) {
2682
+ if (typeof data === "string") {
2683
+ return encode(data);
2684
+ } else {
2685
+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
2686
+ const str = String.fromCharCode(...bytes);
2687
+ return encode(str);
2688
+ }
2689
+ }
2690
+ function fromBase64(str) {
2691
+ const binaryString = decode(str);
2692
+ const len = binaryString.length;
2693
+ const bytes = new Uint8Array(len);
2694
+ for (let i = 0; i < len; i++) {
2695
+ bytes[i] = binaryString.charCodeAt(i);
2696
+ }
2697
+ return bytes;
2698
+ }
2699
+ function lsSet(key, value) {
2700
+ if (value === null || value === void 0) {
2701
+ localStorage.removeItem(LsPrefix + key);
2702
+ } else {
2703
+ localStorage.setItem(LsPrefix + key, JSON.stringify(value));
2704
+ }
2705
+ }
2706
+ function lsGet(key) {
2707
+ const value = localStorage.getItem(LsPrefix + key);
2708
+ return tryParseJson(value, null);
2709
+ }
2710
+ function deepCopy(obj) {
2711
+ return JSON.parse(JSON.stringify(obj));
2712
+ }
2713
+ function tryParseJson(...args) {
2714
+ try {
2715
+ return JSON.parse(args[0]);
2716
+ } catch {
2717
+ if (args.length > 1) {
2718
+ return args[1];
2719
+ }
2720
+ return args[0];
2721
+ }
2722
+ }
2723
+ function canSignWithLAK(actions) {
2724
+ return actions.length === 1 && actions[0].type === "FunctionCall" && big_default(actions[0]?.deposit ?? "0").eq(0);
2725
+ }
2726
+
2727
+ // src/cryptoUtils.ts
2728
+ var keyFromString = (key) => base58_to_binary_default(
2729
+ key.includes(":") ? (() => {
2730
+ const [curve, keyPart] = key.split(":");
2731
+ if (curve !== "ed25519") {
2732
+ throw new Error(`Unsupported curve: ${curve}`);
2733
+ }
2734
+ return keyPart;
2735
+ })() : key
2736
+ );
2737
+ var keyToString = (key) => `ed25519:${binary_to_base58_default(key)}`;
2738
+ function publicKeyFromPrivate(privateKey) {
2739
+ privateKey = keyFromString(privateKey).slice(0, 32);
2740
+ const publicKey = ed25519.getPublicKey(privateKey);
2741
+ return keyToString(publicKey);
2742
+ }
2743
+ function privateKeyFromRandom() {
2744
+ const privateKey = crypto.getRandomValues(new Uint8Array(64));
2745
+ return keyToString(privateKey);
2746
+ }
2747
+ function signHash(hash, privateKey) {
2748
+ privateKey = keyFromString(privateKey).slice(0, 32);
2749
+ const signature = ed25519.sign(base58_to_binary_default(hash), privateKey);
2750
+ return binary_to_base58_default(signature);
2751
+ }
2752
+ function signBytes(bytes, privateKey) {
2753
+ const hash = sha256(bytes);
2754
+ return signHash(binary_to_base58_default(hash), privateKey);
2755
+ }
2756
+
2757
+ // ../../node_modules/borsh/lib/esm/types.js
2758
+ var integers = ["u8", "u16", "u32", "u64", "u128", "i8", "i16", "i32", "i64", "i128", "f32", "f64"];
2759
+
2760
+ // ../../node_modules/borsh/lib/esm/buffer.js
2761
+ var EncodeBuffer = (
2762
+ /** @class */
2763
+ function() {
2764
+ function EncodeBuffer2() {
2765
+ this.offset = 0;
2766
+ this.buffer_size = 256;
2767
+ this.buffer = new ArrayBuffer(this.buffer_size);
2768
+ this.view = new DataView(this.buffer);
2769
+ }
2770
+ EncodeBuffer2.prototype.resize_if_necessary = function(needed_space) {
2771
+ if (this.buffer_size - this.offset < needed_space) {
2772
+ this.buffer_size = Math.max(this.buffer_size * 2, this.buffer_size + needed_space);
2773
+ var new_buffer = new ArrayBuffer(this.buffer_size);
2774
+ new Uint8Array(new_buffer).set(new Uint8Array(this.buffer));
2775
+ this.buffer = new_buffer;
2776
+ this.view = new DataView(new_buffer);
2777
+ }
2778
+ };
2779
+ EncodeBuffer2.prototype.get_used_buffer = function() {
2780
+ return new Uint8Array(this.buffer).slice(0, this.offset);
2781
+ };
2782
+ EncodeBuffer2.prototype.store_value = function(value, type) {
2783
+ var bSize = type.substring(1);
2784
+ var size = parseInt(bSize) / 8;
2785
+ this.resize_if_necessary(size);
2786
+ var toCall = type[0] === "f" ? "setFloat".concat(bSize) : type[0] === "i" ? "setInt".concat(bSize) : "setUint".concat(bSize);
2787
+ this.view[toCall](this.offset, value, true);
2788
+ this.offset += size;
2789
+ };
2790
+ EncodeBuffer2.prototype.store_bytes = function(from) {
2791
+ this.resize_if_necessary(from.length);
2792
+ new Uint8Array(this.buffer).set(new Uint8Array(from), this.offset);
2793
+ this.offset += from.length;
2794
+ };
2795
+ return EncodeBuffer2;
2796
+ }()
2797
+ );
2798
+ var DecodeBuffer = (
2799
+ /** @class */
2800
+ function() {
2801
+ function DecodeBuffer2(buf) {
2802
+ this.offset = 0;
2803
+ this.buffer_size = buf.length;
2804
+ this.buffer = new ArrayBuffer(buf.length);
2805
+ new Uint8Array(this.buffer).set(buf);
2806
+ this.view = new DataView(this.buffer);
2807
+ }
2808
+ DecodeBuffer2.prototype.assert_enough_buffer = function(size) {
2809
+ if (this.offset + size > this.buffer.byteLength) {
2810
+ throw new Error("Error in schema, the buffer is smaller than expected");
2811
+ }
2812
+ };
2813
+ DecodeBuffer2.prototype.consume_value = function(type) {
2814
+ var bSize = type.substring(1);
2815
+ var size = parseInt(bSize) / 8;
2816
+ this.assert_enough_buffer(size);
2817
+ var toCall = type[0] === "f" ? "getFloat".concat(bSize) : type[0] === "i" ? "getInt".concat(bSize) : "getUint".concat(bSize);
2818
+ var ret = this.view[toCall](this.offset, true);
2819
+ this.offset += size;
2820
+ return ret;
2821
+ };
2822
+ DecodeBuffer2.prototype.consume_bytes = function(size) {
2823
+ this.assert_enough_buffer(size);
2824
+ var ret = this.buffer.slice(this.offset, this.offset + size);
2825
+ this.offset += size;
2826
+ return ret;
2827
+ };
2828
+ return DecodeBuffer2;
2829
+ }()
2830
+ );
2831
+
2832
+ // ../../node_modules/borsh/lib/esm/utils.js
2833
+ var __extends = /* @__PURE__ */ function() {
2834
+ var extendStatics = function(d, b) {
2835
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
2836
+ d2.__proto__ = b2;
2837
+ } || function(d2, b2) {
2838
+ for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
2839
+ };
2840
+ return extendStatics(d, b);
2841
+ };
2842
+ return function(d, b) {
2843
+ if (typeof b !== "function" && b !== null)
2844
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
2845
+ extendStatics(d, b);
2846
+ function __() {
2847
+ this.constructor = d;
2848
+ }
2849
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2850
+ };
2851
+ }();
2852
+ function isArrayLike(value) {
2853
+ return Array.isArray(value) || !!value && typeof value === "object" && "length" in value && typeof value.length === "number" && (value.length === 0 || value.length > 0 && value.length - 1 in value);
2854
+ }
2855
+ function expect_type(value, type, fieldPath) {
2856
+ if (typeof value !== type) {
2857
+ throw new Error("Expected ".concat(type, " not ").concat(typeof value, "(").concat(value, ") at ").concat(fieldPath.join(".")));
2858
+ }
2859
+ }
2860
+ function expect_bigint(value, fieldPath) {
2861
+ var basicType = ["number", "string", "bigint", "boolean"].includes(typeof value);
2862
+ var strObject = typeof value === "object" && value !== null && "toString" in value;
2863
+ if (!basicType && !strObject) {
2864
+ throw new Error("Expected bigint, number, boolean or string not ".concat(typeof value, "(").concat(value, ") at ").concat(fieldPath.join(".")));
2865
+ }
2866
+ }
2867
+ function expect_same_size(length, expected, fieldPath) {
2868
+ if (length !== expected) {
2869
+ throw new Error("Array length ".concat(length, " does not match schema length ").concat(expected, " at ").concat(fieldPath.join(".")));
2870
+ }
2871
+ }
2872
+ function expect_enum(value, fieldPath) {
2873
+ if (typeof value !== "object" || value === null) {
2874
+ throw new Error("Expected object not ".concat(typeof value, "(").concat(value, ") at ").concat(fieldPath.join(".")));
2875
+ }
2876
+ }
2877
+ var VALID_STRING_TYPES = integers.concat(["bool", "string"]);
2878
+ var VALID_OBJECT_KEYS = ["option", "enum", "array", "set", "map", "struct"];
2879
+ var ErrorSchema = (
2880
+ /** @class */
2881
+ function(_super) {
2882
+ __extends(ErrorSchema2, _super);
2883
+ function ErrorSchema2(schema, expected) {
2884
+ var message = "Invalid schema: ".concat(JSON.stringify(schema), " expected ").concat(expected);
2885
+ return _super.call(this, message) || this;
2886
+ }
2887
+ return ErrorSchema2;
2888
+ }(Error)
2889
+ );
2890
+ function validate_schema(schema) {
2891
+ if (typeof schema === "string" && VALID_STRING_TYPES.includes(schema)) {
2892
+ return;
2893
+ }
2894
+ if (schema && typeof schema === "object") {
2895
+ var keys = Object.keys(schema);
2896
+ if (keys.length === 1 && VALID_OBJECT_KEYS.includes(keys[0])) {
2897
+ var key = keys[0];
2898
+ if (key === "option")
2899
+ return validate_schema(schema[key]);
2900
+ if (key === "enum")
2901
+ return validate_enum_schema(schema[key]);
2902
+ if (key === "array")
2903
+ return validate_array_schema(schema[key]);
2904
+ if (key === "set")
2905
+ return validate_schema(schema[key]);
2906
+ if (key === "map")
2907
+ return validate_map_schema(schema[key]);
2908
+ if (key === "struct")
2909
+ return validate_struct_schema(schema[key]);
2910
+ }
2911
+ }
2912
+ throw new ErrorSchema(schema, VALID_OBJECT_KEYS.join(", ") + " or " + VALID_STRING_TYPES.join(", "));
2913
+ }
2914
+ function validate_enum_schema(schema) {
2915
+ if (!Array.isArray(schema))
2916
+ throw new ErrorSchema(schema, "Array");
2917
+ for (var _i = 0, schema_1 = schema; _i < schema_1.length; _i++) {
2918
+ var sch = schema_1[_i];
2919
+ if (typeof sch !== "object" || !("struct" in sch)) {
2920
+ throw new Error('Missing "struct" key in enum schema');
2921
+ }
2922
+ if (typeof sch.struct !== "object" || Object.keys(sch.struct).length !== 1) {
2923
+ throw new Error('The "struct" in each enum must have a single key');
2924
+ }
2925
+ validate_schema({ struct: sch.struct });
2926
+ }
2927
+ }
2928
+ function validate_array_schema(schema) {
2929
+ if (typeof schema !== "object")
2930
+ throw new ErrorSchema(schema, "{ type, len? }");
2931
+ if (schema.len && typeof schema.len !== "number") {
2932
+ throw new Error("Invalid schema: ".concat(schema));
2933
+ }
2934
+ if ("type" in schema)
2935
+ return validate_schema(schema.type);
2936
+ throw new ErrorSchema(schema, "{ type, len? }");
2937
+ }
2938
+ function validate_map_schema(schema) {
2939
+ if (typeof schema === "object" && "key" in schema && "value" in schema) {
2940
+ validate_schema(schema.key);
2941
+ validate_schema(schema.value);
2942
+ } else {
2943
+ throw new ErrorSchema(schema, "{ key, value }");
2944
+ }
2945
+ }
2946
+ function validate_struct_schema(schema) {
2947
+ if (typeof schema !== "object")
2948
+ throw new ErrorSchema(schema, "object");
2949
+ for (var key in schema) {
2950
+ validate_schema(schema[key]);
2951
+ }
2952
+ }
2953
+
2954
+ // ../../node_modules/borsh/lib/esm/serialize.js
2955
+ var BorshSerializer = (
2956
+ /** @class */
2957
+ function() {
2958
+ function BorshSerializer2(checkTypes) {
2959
+ this.encoded = new EncodeBuffer();
2960
+ this.fieldPath = ["value"];
2961
+ this.checkTypes = checkTypes;
2962
+ }
2963
+ BorshSerializer2.prototype.encode = function(value, schema) {
2964
+ this.encode_value(value, schema);
2965
+ return this.encoded.get_used_buffer();
2966
+ };
2967
+ BorshSerializer2.prototype.encode_value = function(value, schema) {
2968
+ if (typeof schema === "string") {
2969
+ if (integers.includes(schema))
2970
+ return this.encode_integer(value, schema);
2971
+ if (schema === "string")
2972
+ return this.encode_string(value);
2973
+ if (schema === "bool")
2974
+ return this.encode_boolean(value);
2975
+ }
2976
+ if (typeof schema === "object") {
2977
+ if ("option" in schema)
2978
+ return this.encode_option(value, schema);
2979
+ if ("enum" in schema)
2980
+ return this.encode_enum(value, schema);
2981
+ if ("array" in schema)
2982
+ return this.encode_array(value, schema);
2983
+ if ("set" in schema)
2984
+ return this.encode_set(value, schema);
2985
+ if ("map" in schema)
2986
+ return this.encode_map(value, schema);
2987
+ if ("struct" in schema)
2988
+ return this.encode_struct(value, schema);
2989
+ }
2990
+ };
2991
+ BorshSerializer2.prototype.encode_integer = function(value, schema) {
2992
+ var size = parseInt(schema.substring(1));
2993
+ if (size <= 32 || schema == "f64") {
2994
+ this.checkTypes && expect_type(value, "number", this.fieldPath);
2995
+ this.encoded.store_value(value, schema);
2996
+ } else {
2997
+ this.checkTypes && expect_bigint(value, this.fieldPath);
2998
+ this.encode_bigint(BigInt(value), size);
2999
+ }
3000
+ };
3001
+ BorshSerializer2.prototype.encode_bigint = function(value, size) {
3002
+ var buffer_len = size / 8;
3003
+ var buffer = new Uint8Array(buffer_len);
3004
+ for (var i = 0; i < buffer_len; i++) {
3005
+ buffer[i] = Number(value & BigInt(255));
3006
+ value = value >> BigInt(8);
3007
+ }
3008
+ this.encoded.store_bytes(new Uint8Array(buffer));
3009
+ };
3010
+ BorshSerializer2.prototype.encode_string = function(value) {
3011
+ this.checkTypes && expect_type(value, "string", this.fieldPath);
3012
+ var _value = value;
3013
+ var utf8Bytes = [];
3014
+ for (var i = 0; i < _value.length; i++) {
3015
+ var charCode = _value.charCodeAt(i);
3016
+ if (charCode < 128) {
3017
+ utf8Bytes.push(charCode);
3018
+ } else if (charCode < 2048) {
3019
+ utf8Bytes.push(192 | charCode >> 6, 128 | charCode & 63);
3020
+ } else if (charCode < 55296 || charCode >= 57344) {
3021
+ utf8Bytes.push(224 | charCode >> 12, 128 | charCode >> 6 & 63, 128 | charCode & 63);
3022
+ } else {
3023
+ i++;
3024
+ charCode = 65536 + ((charCode & 1023) << 10 | _value.charCodeAt(i) & 1023);
3025
+ utf8Bytes.push(240 | charCode >> 18, 128 | charCode >> 12 & 63, 128 | charCode >> 6 & 63, 128 | charCode & 63);
3026
+ }
3027
+ }
3028
+ this.encoded.store_value(utf8Bytes.length, "u32");
3029
+ this.encoded.store_bytes(new Uint8Array(utf8Bytes));
3030
+ };
3031
+ BorshSerializer2.prototype.encode_boolean = function(value) {
3032
+ this.checkTypes && expect_type(value, "boolean", this.fieldPath);
3033
+ this.encoded.store_value(value ? 1 : 0, "u8");
3034
+ };
3035
+ BorshSerializer2.prototype.encode_option = function(value, schema) {
3036
+ if (value === null || value === void 0) {
3037
+ this.encoded.store_value(0, "u8");
3038
+ } else {
3039
+ this.encoded.store_value(1, "u8");
3040
+ this.encode_value(value, schema.option);
3041
+ }
3042
+ };
3043
+ BorshSerializer2.prototype.encode_enum = function(value, schema) {
3044
+ this.checkTypes && expect_enum(value, this.fieldPath);
3045
+ var valueKey = Object.keys(value)[0];
3046
+ for (var i = 0; i < schema["enum"].length; i++) {
3047
+ var valueSchema = schema["enum"][i];
3048
+ if (valueKey === Object.keys(valueSchema.struct)[0]) {
3049
+ this.encoded.store_value(i, "u8");
3050
+ return this.encode_struct(value, valueSchema);
3051
+ }
3052
+ }
3053
+ throw new Error("Enum key (".concat(valueKey, ") not found in enum schema: ").concat(JSON.stringify(schema), " at ").concat(this.fieldPath.join(".")));
3054
+ };
3055
+ BorshSerializer2.prototype.encode_array = function(value, schema) {
3056
+ if (isArrayLike(value))
3057
+ return this.encode_arraylike(value, schema);
3058
+ if (value instanceof ArrayBuffer)
3059
+ return this.encode_buffer(value, schema);
3060
+ throw new Error("Expected Array-like not ".concat(typeof value, "(").concat(value, ") at ").concat(this.fieldPath.join(".")));
3061
+ };
3062
+ BorshSerializer2.prototype.encode_arraylike = function(value, schema) {
3063
+ if (schema.array.len) {
3064
+ expect_same_size(value.length, schema.array.len, this.fieldPath);
3065
+ } else {
3066
+ this.encoded.store_value(value.length, "u32");
3067
+ }
3068
+ for (var i = 0; i < value.length; i++) {
3069
+ this.encode_value(value[i], schema.array.type);
3070
+ }
3071
+ };
3072
+ BorshSerializer2.prototype.encode_buffer = function(value, schema) {
3073
+ if (schema.array.len) {
3074
+ expect_same_size(value.byteLength, schema.array.len, this.fieldPath);
3075
+ } else {
3076
+ this.encoded.store_value(value.byteLength, "u32");
3077
+ }
3078
+ this.encoded.store_bytes(new Uint8Array(value));
3079
+ };
3080
+ BorshSerializer2.prototype.encode_set = function(value, schema) {
3081
+ this.checkTypes && expect_type(value, "object", this.fieldPath);
3082
+ var isSet = value instanceof Set;
3083
+ var values = isSet ? Array.from(value.values()) : Object.values(value);
3084
+ this.encoded.store_value(values.length, "u32");
3085
+ for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
3086
+ var value_1 = values_1[_i];
3087
+ this.encode_value(value_1, schema.set);
3088
+ }
3089
+ };
3090
+ BorshSerializer2.prototype.encode_map = function(value, schema) {
3091
+ this.checkTypes && expect_type(value, "object", this.fieldPath);
3092
+ var isMap = value instanceof Map;
3093
+ var keys = isMap ? Array.from(value.keys()) : Object.keys(value);
3094
+ this.encoded.store_value(keys.length, "u32");
3095
+ for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
3096
+ var key = keys_1[_i];
3097
+ this.encode_value(key, schema.map.key);
3098
+ this.encode_value(isMap ? value.get(key) : value[key], schema.map.value);
3099
+ }
3100
+ };
3101
+ BorshSerializer2.prototype.encode_struct = function(value, schema) {
3102
+ this.checkTypes && expect_type(value, "object", this.fieldPath);
3103
+ for (var _i = 0, _a = Object.keys(schema.struct); _i < _a.length; _i++) {
3104
+ var key = _a[_i];
3105
+ this.fieldPath.push(key);
3106
+ this.encode_value(value[key], schema.struct[key]);
3107
+ this.fieldPath.pop();
3108
+ }
3109
+ };
3110
+ return BorshSerializer2;
3111
+ }()
3112
+ );
3113
+
3114
+ // ../../node_modules/borsh/lib/esm/deserialize.js
3115
+ var BorshDeserializer = (
3116
+ /** @class */
3117
+ function() {
3118
+ function BorshDeserializer2(bufferArray) {
3119
+ this.buffer = new DecodeBuffer(bufferArray);
3120
+ }
3121
+ BorshDeserializer2.prototype.decode = function(schema) {
3122
+ return this.decode_value(schema);
3123
+ };
3124
+ BorshDeserializer2.prototype.decode_value = function(schema) {
3125
+ if (typeof schema === "string") {
3126
+ if (integers.includes(schema))
3127
+ return this.decode_integer(schema);
3128
+ if (schema === "string")
3129
+ return this.decode_string();
3130
+ if (schema === "bool")
3131
+ return this.decode_boolean();
3132
+ }
3133
+ if (typeof schema === "object") {
3134
+ if ("option" in schema)
3135
+ return this.decode_option(schema);
3136
+ if ("enum" in schema)
3137
+ return this.decode_enum(schema);
3138
+ if ("array" in schema)
3139
+ return this.decode_array(schema);
3140
+ if ("set" in schema)
3141
+ return this.decode_set(schema);
3142
+ if ("map" in schema)
3143
+ return this.decode_map(schema);
3144
+ if ("struct" in schema)
3145
+ return this.decode_struct(schema);
3146
+ }
3147
+ throw new Error("Unsupported type: ".concat(schema));
3148
+ };
3149
+ BorshDeserializer2.prototype.decode_integer = function(schema) {
3150
+ var size = parseInt(schema.substring(1));
3151
+ if (size <= 32 || schema == "f64") {
3152
+ return this.buffer.consume_value(schema);
3153
+ }
3154
+ return this.decode_bigint(size, schema.startsWith("i"));
3155
+ };
3156
+ BorshDeserializer2.prototype.decode_bigint = function(size, signed) {
3157
+ if (signed === void 0) {
3158
+ signed = false;
3159
+ }
3160
+ var buffer_len = size / 8;
3161
+ var buffer = new Uint8Array(this.buffer.consume_bytes(buffer_len));
3162
+ var bits = buffer.reduceRight(function(r, x) {
3163
+ return r + x.toString(16).padStart(2, "0");
3164
+ }, "");
3165
+ if (signed && buffer[buffer_len - 1]) {
3166
+ return BigInt.asIntN(size, BigInt("0x".concat(bits)));
3167
+ }
3168
+ return BigInt("0x".concat(bits));
3169
+ };
3170
+ BorshDeserializer2.prototype.decode_string = function() {
3171
+ var len = this.decode_integer("u32");
3172
+ var buffer = new Uint8Array(this.buffer.consume_bytes(len));
3173
+ var codePoints = [];
3174
+ for (var i = 0; i < len; ++i) {
3175
+ var byte = buffer[i];
3176
+ if (byte < 128) {
3177
+ codePoints.push(byte);
3178
+ } else if (byte < 224) {
3179
+ codePoints.push((byte & 31) << 6 | buffer[++i] & 63);
3180
+ } else if (byte < 240) {
3181
+ codePoints.push((byte & 15) << 12 | (buffer[++i] & 63) << 6 | buffer[++i] & 63);
3182
+ } else {
3183
+ var codePoint = (byte & 7) << 18 | (buffer[++i] & 63) << 12 | (buffer[++i] & 63) << 6 | buffer[++i] & 63;
3184
+ codePoints.push(codePoint);
3185
+ }
3186
+ }
3187
+ return String.fromCodePoint.apply(String, codePoints);
3188
+ };
3189
+ BorshDeserializer2.prototype.decode_boolean = function() {
3190
+ return this.buffer.consume_value("u8") > 0;
3191
+ };
3192
+ BorshDeserializer2.prototype.decode_option = function(schema) {
3193
+ var option = this.buffer.consume_value("u8");
3194
+ if (option === 1) {
3195
+ return this.decode_value(schema.option);
3196
+ }
3197
+ if (option !== 0) {
3198
+ throw new Error("Invalid option ".concat(option));
3199
+ }
3200
+ return null;
3201
+ };
3202
+ BorshDeserializer2.prototype.decode_enum = function(schema) {
3203
+ var _a;
3204
+ var valueIndex = this.buffer.consume_value("u8");
3205
+ if (valueIndex > schema["enum"].length) {
3206
+ throw new Error("Enum option ".concat(valueIndex, " is not available"));
3207
+ }
3208
+ var struct = schema["enum"][valueIndex].struct;
3209
+ var key = Object.keys(struct)[0];
3210
+ return _a = {}, _a[key] = this.decode_value(struct[key]), _a;
3211
+ };
3212
+ BorshDeserializer2.prototype.decode_array = function(schema) {
3213
+ var result = [];
3214
+ var len = schema.array.len ? schema.array.len : this.decode_integer("u32");
3215
+ for (var i = 0; i < len; ++i) {
3216
+ result.push(this.decode_value(schema.array.type));
3217
+ }
3218
+ return result;
3219
+ };
3220
+ BorshDeserializer2.prototype.decode_set = function(schema) {
3221
+ var len = this.decode_integer("u32");
3222
+ var result = /* @__PURE__ */ new Set();
3223
+ for (var i = 0; i < len; ++i) {
3224
+ result.add(this.decode_value(schema.set));
3225
+ }
3226
+ return result;
3227
+ };
3228
+ BorshDeserializer2.prototype.decode_map = function(schema) {
3229
+ var len = this.decode_integer("u32");
3230
+ var result = /* @__PURE__ */ new Map();
3231
+ for (var i = 0; i < len; ++i) {
3232
+ var key = this.decode_value(schema.map.key);
3233
+ var value = this.decode_value(schema.map.value);
3234
+ result.set(key, value);
3235
+ }
3236
+ return result;
3237
+ };
3238
+ BorshDeserializer2.prototype.decode_struct = function(schema) {
3239
+ var result = {};
3240
+ for (var key in schema.struct) {
3241
+ result[key] = this.decode_value(schema.struct[key]);
3242
+ }
3243
+ return result;
3244
+ };
3245
+ return BorshDeserializer2;
3246
+ }()
3247
+ );
3248
+
3249
+ // ../../node_modules/borsh/lib/esm/index.js
3250
+ function serialize(schema, value, validate) {
3251
+ if (validate === void 0) {
3252
+ validate = true;
3253
+ }
3254
+ if (validate)
3255
+ validate_schema(schema);
3256
+ var serializer = new BorshSerializer(validate);
3257
+ return serializer.encode(value, schema);
3258
+ }
3259
+
3260
+ // src/transaction.ts
3261
+ function mapTransaction(jsonTransaction) {
3262
+ return {
3263
+ signerId: jsonTransaction.signerId,
3264
+ publicKey: {
3265
+ ed25519Key: {
3266
+ data: keyFromString(jsonTransaction.publicKey)
3267
+ }
3268
+ },
3269
+ nonce: BigInt(jsonTransaction.nonce),
3270
+ receiverId: jsonTransaction.receiverId,
3271
+ blockHash: base58_to_binary_default(jsonTransaction.blockHash),
3272
+ actions: jsonTransaction.actions.map(mapAction)
3273
+ };
3274
+ }
3275
+ function serializeTransaction(jsonTransaction) {
3276
+ const transaction = mapTransaction(jsonTransaction);
3277
+ return serialize(SCHEMA.Transaction, transaction);
3278
+ }
3279
+ function serializeSignedTransaction(jsonTransaction, signature) {
3280
+ const signedTransaction = {
3281
+ transaction: mapTransaction(jsonTransaction),
3282
+ signature: {
3283
+ ed25519Signature: {
3284
+ data: base58_to_binary_default(signature)
3285
+ }
3286
+ }
3287
+ };
3288
+ return serialize(SCHEMA.SignedTransaction, signedTransaction);
3289
+ }
3290
+ function mapAction(action) {
3291
+ switch (action.type) {
3292
+ case "CreateAccount": {
3293
+ return {
3294
+ createAccount: {}
3295
+ };
3296
+ }
3297
+ case "DeployContract": {
3298
+ return {
3299
+ deployContract: {
3300
+ code: fromBase64(action.codeBase64)
3301
+ }
3302
+ };
3303
+ }
3304
+ case "FunctionCall": {
3305
+ return {
3306
+ functionCall: {
3307
+ methodName: action.methodName,
3308
+ args: action.argsBase64 ? fromBase64(action.argsBase64) : new TextEncoder().encode(JSON.stringify(action.args)),
3309
+ gas: BigInt(action.gas),
3310
+ deposit: BigInt(action.deposit)
3311
+ }
3312
+ };
3313
+ }
3314
+ case "Transfer": {
3315
+ return {
3316
+ transfer: {
3317
+ deposit: BigInt(action.deposit)
3318
+ }
3319
+ };
3320
+ }
3321
+ case "Stake": {
3322
+ return {
3323
+ stake: {
3324
+ stake: BigInt(action.stake),
3325
+ publicKey: {
3326
+ ed25519Key: {
3327
+ data: keyFromString(action.publicKey)
3328
+ }
3329
+ }
3330
+ }
3331
+ };
3332
+ }
3333
+ case "AddKey": {
3334
+ return {
3335
+ addKey: {
3336
+ publicKey: {
3337
+ ed25519Key: {
3338
+ data: keyFromString(action.publicKey)
3339
+ }
3340
+ },
3341
+ accessKey: {
3342
+ nonce: BigInt(action.accessKey.nonce),
3343
+ permission: action.accessKey.permission === "FullAccess" ? { fullAccess: {} } : {
3344
+ functionCall: {
3345
+ allowance: action.accessKey.allowance ? BigInt(action.accessKey.allowance) : null,
3346
+ receiverId: action.accessKey.receiverId,
3347
+ methodNames: action.accessKey.methodNames
3348
+ }
3349
+ }
3350
+ }
3351
+ }
3352
+ };
3353
+ }
3354
+ case "DeleteKey": {
3355
+ return {
3356
+ deleteKey: {
3357
+ publicKey: {
3358
+ ed25519Key: {
3359
+ data: keyFromString(action.publicKey)
3360
+ }
3361
+ }
3362
+ }
3363
+ };
3364
+ }
3365
+ case "DeleteAccount": {
3366
+ return {
3367
+ deleteAccount: {
3368
+ beneficiaryId: action.beneficiaryId
3369
+ }
3370
+ };
3371
+ }
3372
+ case "SignedDelegate": {
3373
+ return {
3374
+ signedDelegate: {
3375
+ delegateAction: mapAction(action.delegateAction),
3376
+ signature: {
3377
+ ed25519Signature: base58_to_binary_default(action.signature)
3378
+ }
3379
+ }
3380
+ };
3381
+ }
3382
+ default: {
3383
+ throw new Error("Not implemented action: " + action.type);
3384
+ }
3385
+ }
3386
+ }
3387
+ var SCHEMA = new class BorshSchema {
3388
+ Ed25519Signature = {
3389
+ struct: {
3390
+ data: { array: { type: "u8", len: 64 } }
3391
+ }
3392
+ };
3393
+ Secp256k1Signature = {
3394
+ struct: {
3395
+ data: { array: { type: "u8", len: 65 } }
3396
+ }
3397
+ };
3398
+ Signature = {
3399
+ enum: [
3400
+ { struct: { ed25519Signature: this.Ed25519Signature } },
3401
+ { struct: { secp256k1Signature: this.Secp256k1Signature } }
3402
+ ]
3403
+ };
3404
+ Ed25519Data = {
3405
+ struct: {
3406
+ data: { array: { type: "u8", len: 32 } }
3407
+ }
3408
+ };
3409
+ Secp256k1Data = {
3410
+ struct: {
3411
+ data: { array: { type: "u8", len: 64 } }
3412
+ }
3413
+ };
3414
+ PublicKey = {
3415
+ enum: [
3416
+ { struct: { ed25519Key: this.Ed25519Data } },
3417
+ { struct: { secp256k1Key: this.Secp256k1Data } }
3418
+ ]
3419
+ };
3420
+ FunctionCallPermission = {
3421
+ struct: {
3422
+ allowance: { option: "u128" },
3423
+ receiverId: "string",
3424
+ methodNames: { array: { type: "string" } }
3425
+ }
3426
+ };
3427
+ FullAccessPermission = {
3428
+ struct: {}
3429
+ };
3430
+ AccessKeyPermission = {
3431
+ enum: [
3432
+ { struct: { functionCall: this.FunctionCallPermission } },
3433
+ { struct: { fullAccess: this.FullAccessPermission } }
3434
+ ]
3435
+ };
3436
+ AccessKey = {
3437
+ struct: {
3438
+ nonce: "u64",
3439
+ permission: this.AccessKeyPermission
3440
+ }
3441
+ };
3442
+ CreateAccount = {
3443
+ struct: {}
3444
+ };
3445
+ DeployContract = {
3446
+ struct: {
3447
+ code: { array: { type: "u8" } }
3448
+ }
3449
+ };
3450
+ FunctionCall = {
3451
+ struct: {
3452
+ methodName: "string",
3453
+ args: { array: { type: "u8" } },
3454
+ gas: "u64",
3455
+ deposit: "u128"
3456
+ }
3457
+ };
3458
+ Transfer = {
3459
+ struct: {
3460
+ deposit: "u128"
3461
+ }
3462
+ };
3463
+ Stake = {
3464
+ struct: {
3465
+ stake: "u128",
3466
+ publicKey: this.PublicKey
3467
+ }
3468
+ };
3469
+ AddKey = {
3470
+ struct: {
3471
+ publicKey: this.PublicKey,
3472
+ accessKey: this.AccessKey
3473
+ }
3474
+ };
3475
+ DeleteKey = {
3476
+ struct: {
3477
+ publicKey: this.PublicKey
3478
+ }
3479
+ };
3480
+ DeleteAccount = {
3481
+ struct: {
3482
+ beneficiaryId: "string"
3483
+ }
3484
+ };
3485
+ ClassicAction = {
3486
+ enum: [
3487
+ { struct: { createAccount: this.CreateAccount } },
3488
+ { struct: { deployContract: this.DeployContract } },
3489
+ { struct: { functionCall: this.FunctionCall } },
3490
+ { struct: { transfer: this.Transfer } },
3491
+ { struct: { stake: this.Stake } },
3492
+ { struct: { addKey: this.AddKey } },
3493
+ { struct: { deleteKey: this.DeleteKey } },
3494
+ { struct: { deleteAccount: this.DeleteAccount } }
3495
+ ]
3496
+ };
3497
+ DelegateAction = {
3498
+ struct: {
3499
+ senderId: "string",
3500
+ receiverId: "string",
3501
+ actions: { array: { type: this.ClassicAction } },
3502
+ nonce: "u64",
3503
+ maxBlockHeight: "u64",
3504
+ publicKey: this.PublicKey
3505
+ }
3506
+ };
3507
+ SignedDelegate = {
3508
+ struct: {
3509
+ delegateAction: this.DelegateAction,
3510
+ signature: this.Signature
3511
+ }
3512
+ };
3513
+ Action = {
3514
+ enum: [
3515
+ { struct: { createAccount: this.CreateAccount } },
3516
+ { struct: { deployContract: this.DeployContract } },
3517
+ { struct: { functionCall: this.FunctionCall } },
3518
+ { struct: { transfer: this.Transfer } },
3519
+ { struct: { stake: this.Stake } },
3520
+ { struct: { addKey: this.AddKey } },
3521
+ { struct: { deleteKey: this.DeleteKey } },
3522
+ { struct: { deleteAccount: this.DeleteAccount } },
3523
+ { struct: { signedDelegate: this.SignedDelegate } }
3524
+ ]
3525
+ };
3526
+ Transaction = {
3527
+ struct: {
3528
+ signerId: "string",
3529
+ publicKey: this.PublicKey,
3530
+ nonce: "u64",
3531
+ receiverId: "string",
3532
+ blockHash: { array: { type: "u8", len: 32 } },
3533
+ actions: { array: { type: this.Action } }
3534
+ }
3535
+ };
3536
+ SignedTransaction = {
3537
+ struct: {
3538
+ transaction: this.Transaction,
3539
+ signature: this.Signature
3540
+ }
3541
+ };
3542
+ }();
3543
+
3544
+ // src/near.ts
3545
+ big_default.DP = 27;
3546
+ var MaxBlockDelayMs = 1e3 * 60 * 60 * 6;
3547
+ var WIDGET_URL = "http://localhost:3000/";
3548
+ var DEFAULT_NETWORK_ID = "mainnet";
3549
+ var NETWORKS = {
3550
+ testnet: {
3551
+ networkId: "testnet",
3552
+ nodeUrl: "https://rpc.testnet.fastnear.com/"
3553
+ },
3554
+ mainnet: {
3555
+ networkId: "mainnet",
3556
+ nodeUrl: "https://rpc.mainnet.fastnear.com/"
3557
+ }
3558
+ };
3559
+ var _config = lsGet("config") || { ...NETWORKS[DEFAULT_NETWORK_ID] };
3560
+ var _state = lsGet("state") || {};
3561
+ try {
3562
+ _state.publicKey = _state.privateKey ? publicKeyFromPrivate(_state.privateKey) : null;
3563
+ } catch (e) {
3564
+ console.error("Error parsing private key:", e);
3565
+ _state.privateKey = null;
3566
+ lsSet("nonce", null);
3567
+ }
3568
+ var _txHistory = lsGet("txHistory") || {};
3569
+ var _eventListeners = {
3570
+ account: /* @__PURE__ */ new Set(),
3571
+ tx: /* @__PURE__ */ new Set()
3572
+ };
3573
+ var _unbroadcastedEvents = {
3574
+ account: [],
3575
+ tx: []
3576
+ };
3577
+ function getWalletAdapterState() {
3578
+ return {
3579
+ publicKey: _state.publicKey,
3580
+ accountId: _state.accountId,
3581
+ lastWalletId: _state.lastWalletId,
3582
+ networkId: DEFAULT_NETWORK_ID
3583
+ };
3584
+ }
3585
+ var _adapter;
3586
+ function updateState(newState) {
3587
+ const oldState = _state;
3588
+ _state = { ..._state, ...newState };
3589
+ lsSet("state", {
3590
+ accountId: _state.accountId,
3591
+ privateKey: _state.privateKey,
3592
+ lastWalletId: _state.lastWalletId,
3593
+ accessKeyContractId: _state.accessKeyContractId
3594
+ });
3595
+ if (newState.hasOwnProperty("privateKey") && newState.privateKey !== oldState.privateKey) {
3596
+ _state.publicKey = newState.privateKey ? publicKeyFromPrivate(newState.privateKey) : null;
3597
+ lsSet("nonce", null);
3598
+ }
3599
+ if (newState.accountId !== oldState.accountId) {
3600
+ notifyAccountListeners(newState.accountId);
3601
+ }
3602
+ if (newState.hasOwnProperty("lastWalletId") && newState.lastWalletId !== oldState.lastWalletId || newState.hasOwnProperty("accountId") && newState.accountId !== oldState.accountId || newState.hasOwnProperty("privateKey") && newState.privateKey !== oldState.privateKey) {
3603
+ _adapter.setState(getWalletAdapterState());
3604
+ }
3605
+ }
3606
+ function updateTxHistory(txStatus) {
3607
+ const txId = txStatus.txId;
3608
+ _txHistory[txId] = {
3609
+ ..._txHistory[txId] ?? {},
3610
+ ...txStatus,
3611
+ updateTimestamp: Date.now()
3612
+ };
3613
+ lsSet("txHistory", _txHistory);
3614
+ notifyTxListeners(_txHistory[txId]);
3615
+ }
3616
+ function onAdapterStateUpdate(state) {
3617
+ console.log("Adapter state update:", state);
3618
+ const { accountId, lastWalletId, privateKey } = state;
3619
+ updateState({
3620
+ accountId,
3621
+ lastWalletId,
3622
+ ...privateKey && { privateKey }
3623
+ });
3624
+ }
3625
+ _adapter = new WalletAdapter({
3626
+ onStateUpdate: onAdapterStateUpdate,
3627
+ lastState: getWalletAdapterState(),
3628
+ widgetUrl: WIDGET_URL
3629
+ });
3630
+ function parseJsonFromBytes(bytes) {
3631
+ try {
3632
+ const decoder = new TextDecoder();
3633
+ return JSON.parse(decoder.decode(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)));
3634
+ } catch (e) {
3635
+ try {
3636
+ return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
3637
+ } catch (e2) {
3638
+ return bytes;
3639
+ }
3640
+ }
3641
+ }
3642
+ function withBlockId(params, blockId) {
3643
+ return blockId === "final" || blockId === "optimistic" ? { ...params, finality: blockId } : blockId ? { ...params, block_id: blockId } : { ...params, finality: "optimistic" };
3644
+ }
3645
+ async function queryRpc(method, params) {
3646
+ const response = await fetch(_config.nodeUrl, {
3647
+ method: "POST",
3648
+ headers: { "Content-Type": "application/json" },
3649
+ body: JSON.stringify({
3650
+ jsonrpc: "2.0",
3651
+ id: `fastnear-${Date.now()}`,
3652
+ method,
3653
+ params
3654
+ })
3655
+ });
3656
+ const result = await response.json();
3657
+ if (result.error) {
3658
+ throw new Error(JSON.stringify(result.error));
3659
+ }
3660
+ return result.result;
3661
+ }
3662
+ function afterTxSent(txId) {
3663
+ queryRpc("tx", {
3664
+ tx_hash: _txHistory[txId].txHash,
3665
+ sender_account_id: _txHistory[txId].tx.signerId,
3666
+ wait_until: "EXECUTED_OPTIMISTIC"
3667
+ }).then((result) => {
3668
+ const successValue = result?.status?.SuccessValue;
3669
+ updateTxHistory({
3670
+ txId,
3671
+ status: "Executed",
3672
+ result,
3673
+ successValue: successValue ? tryParseJson(fromBase64(successValue)) : void 0,
3674
+ finalState: true
3675
+ });
3676
+ }).catch((error) => {
3677
+ updateTxHistory({
3678
+ txId,
3679
+ status: "ErrorAfterIncluded",
3680
+ error: tryParseJson(error.message),
3681
+ finalState: true
3682
+ });
3683
+ });
3684
+ }
3685
+ function sendTxToRpc(signedTxBase64, waitUntil, txId) {
3686
+ queryRpc("send_tx", {
3687
+ signed_tx_base64: signedTxBase64,
3688
+ wait_until: waitUntil ?? "INCLUDED"
3689
+ }).then((result) => {
3690
+ console.log("Transaction included:", result);
3691
+ updateTxHistory({
3692
+ txId,
3693
+ status: "Included",
3694
+ finalState: false
3695
+ });
3696
+ afterTxSent(txId);
3697
+ }).catch((error) => {
3698
+ updateTxHistory({
3699
+ txId,
3700
+ status: "Error",
3701
+ error: tryParseJson(error.message),
3702
+ finalState: false
3703
+ });
3704
+ });
3705
+ }
3706
+ function notifyAccountListeners(accountId) {
3707
+ if (_eventListeners.account.size === 0) {
3708
+ _unbroadcastedEvents.account.push(accountId);
3709
+ return;
3710
+ }
3711
+ _eventListeners.account.forEach((callback) => {
3712
+ try {
3713
+ callback(accountId);
3714
+ } catch (e) {
3715
+ console.error(e);
3716
+ }
3717
+ });
3718
+ }
3719
+ function notifyTxListeners(tx) {
3720
+ if (_eventListeners.tx.size === 0) {
3721
+ _unbroadcastedEvents.tx.push(tx);
3722
+ return;
3723
+ }
3724
+ _eventListeners.tx.forEach((callback) => {
3725
+ try {
3726
+ callback(tx);
3727
+ } catch (e) {
3728
+ console.error(e);
3729
+ }
3730
+ });
3731
+ }
3732
+ function convertUnit(s, ...args) {
3733
+ if (Array.isArray(s)) {
3734
+ s = s.reduce((acc, part, i) => {
3735
+ return acc + (args[i - 1] ?? "") + part;
3736
+ });
3737
+ }
3738
+ if (typeof s == "string") {
3739
+ const match = s.match(/([0-9.,_]+)\s*([a-zA-Z]+)?/);
3740
+ if (match) {
3741
+ const amount = match[1].replace(/[_,]/g, "");
3742
+ const unitPart = match[2];
3743
+ if (unitPart) {
3744
+ switch (unitPart.toLowerCase()) {
3745
+ case "near":
3746
+ return big_default(amount).mul(big_default(10).pow(24)).toFixed(0);
3747
+ case "tgas":
3748
+ return big_default(amount).mul(big_default(10).pow(12)).toFixed(0);
3749
+ case "ggas":
3750
+ return big_default(amount).mul(big_default(10).pow(9)).toFixed(0);
3751
+ case "gas":
3752
+ case "yoctonear":
3753
+ return big_default(amount).toFixed(0);
3754
+ default:
3755
+ throw new Error(`Unknown unit: ${unitPart}`);
3756
+ }
3757
+ } else {
3758
+ return big_default(amount).toFixed(0);
3759
+ }
3760
+ }
3761
+ }
3762
+ return big_default(s).toFixed(0);
3763
+ }
3764
+ var api = {
3765
+ // Context
3766
+ get accountId() {
3767
+ return _state.accountId;
3768
+ },
3769
+ get publicKey() {
3770
+ return _state.publicKey;
3771
+ },
3772
+ config(newConfig) {
3773
+ if (newConfig) {
3774
+ if (newConfig.networkId && _config.networkId !== newConfig.networkId) {
3775
+ _config = { ...NETWORKS[newConfig.networkId] };
3776
+ updateState({
3777
+ accountId: null,
3778
+ privateKey: null,
3779
+ lastWalletId: null
3780
+ });
3781
+ lsSet("block", null);
3782
+ _txHistory = {};
3783
+ lsSet("txHistory", _txHistory);
3784
+ }
3785
+ _config = { ..._config, ...newConfig };
3786
+ lsSet("config", _config);
3787
+ }
3788
+ return _config;
3789
+ },
3790
+ get authStatus() {
3791
+ if (!_state.accountId) {
3792
+ return "SignedOut";
3793
+ }
3794
+ const accessKey = _state.publicKey;
3795
+ const contractId = _state.accessKeyContractId;
3796
+ if (accessKey && contractId && _state.privateKey) {
3797
+ return {
3798
+ type: "SignedInWithLimitedAccessKey",
3799
+ accessKey,
3800
+ contractId
3801
+ };
3802
+ }
3803
+ return "SignedIn";
3804
+ },
3805
+ // Query Methods
3806
+ async view({
3807
+ contractId,
3808
+ methodName,
3809
+ args,
3810
+ argsBase64,
3811
+ blockId
3812
+ }) {
3813
+ const encodedArgs = argsBase64 || (args ? toBase64(JSON.stringify(args)) : "");
3814
+ const result = await queryRpc(
3815
+ "query",
3816
+ withBlockId(
3817
+ {
3818
+ request_type: "call_function",
3819
+ account_id: contractId,
3820
+ method_name: methodName,
3821
+ args_base64: encodedArgs
3822
+ },
3823
+ blockId
3824
+ )
3825
+ );
3826
+ return parseJsonFromBytes(result.result);
3827
+ },
3828
+ async account({
3829
+ accountId,
3830
+ blockId
3831
+ }) {
3832
+ return queryRpc(
3833
+ "query",
3834
+ withBlockId(
3835
+ {
3836
+ request_type: "view_account",
3837
+ account_id: accountId
3838
+ },
3839
+ blockId
3840
+ )
3841
+ );
3842
+ },
3843
+ async block({ blockId }) {
3844
+ return queryRpc("block", withBlockId({}, blockId));
3845
+ },
3846
+ async accessKey({
3847
+ accountId,
3848
+ publicKey,
3849
+ blockId
3850
+ }) {
3851
+ return queryRpc(
3852
+ "query",
3853
+ withBlockId(
3854
+ {
3855
+ request_type: "view_access_key",
3856
+ account_id: accountId,
3857
+ public_key: publicKey
3858
+ },
3859
+ blockId
3860
+ )
3861
+ );
3862
+ },
3863
+ async tx({ txHash, accountId }) {
3864
+ return queryRpc("tx", [txHash, accountId]);
3865
+ },
3866
+ localTxHistory() {
3867
+ return [..._txHistory];
3868
+ },
3869
+ // Transaction Methods
3870
+ async sendTx({
3871
+ receiverId,
3872
+ actions,
3873
+ waitUntil
3874
+ }) {
3875
+ const signerId = _state.accountId;
3876
+ if (!signerId) {
3877
+ throw new Error("Not signed in");
3878
+ }
3879
+ const publicKey = _state.publicKey;
3880
+ const privateKey = _state.privateKey;
3881
+ const txId = `tx-${Date.now()}-${Math.random()}`;
3882
+ if (!privateKey || receiverId !== _state.accessKeyContractId || !canSignWithLAK(actions)) {
3883
+ const jsonTransaction2 = {
3884
+ signerId,
3885
+ receiverId,
3886
+ actions
3887
+ };
3888
+ updateTxHistory({
3889
+ status: "Pending",
3890
+ txId,
3891
+ tx: jsonTransaction2,
3892
+ finalState: false
3893
+ });
3894
+ const url = new URL(typeof window !== "undefined" ? window.location.href : "");
3895
+ url.searchParams.set("txIds", txId);
3896
+ _adapter.sendTransactions({
3897
+ transactions: [jsonTransaction2],
3898
+ callbackUrl: url.toString()
3899
+ }).then((result) => {
3900
+ console.log("Transaction result:", result);
3901
+ if (result.url) {
3902
+ console.log("Redirecting to wallet:", result.url);
3903
+ if (typeof window !== "undefined") {
3904
+ setTimeout(() => {
3905
+ window.location.href = result.url;
3906
+ }, 100);
3907
+ }
3908
+ } else if (result.outcomes) {
3909
+ result.outcomes.forEach((r) => {
3910
+ updateTxHistory({
3911
+ txId,
3912
+ status: "Executed",
3913
+ result: r,
3914
+ txHash: r.transaction.hash,
3915
+ finalState: true
3916
+ });
3917
+ });
3918
+ } else if (result.rejected) {
3919
+ updateTxHistory({
3920
+ txId,
3921
+ status: "RejectedByUser",
3922
+ finalState: true
3923
+ });
3924
+ } else if (result.error) {
3925
+ updateTxHistory({
3926
+ txId,
3927
+ status: "Error",
3928
+ error: tryParseJson(result.error),
3929
+ finalState: true
3930
+ });
3931
+ }
3932
+ }).catch((error) => {
3933
+ updateTxHistory({
3934
+ txId,
3935
+ status: "Error",
3936
+ error: tryParseJson(error.message),
3937
+ finalState: true
3938
+ });
3939
+ });
3940
+ return txId;
3941
+ }
3942
+ let nonce = lsGet("nonce");
3943
+ let block = lsGet("block");
3944
+ const toDoPromises = {};
3945
+ if (nonce === null || nonce === void 0) {
3946
+ toDoPromises.nonce = api.accessKey({
3947
+ accountId: signerId,
3948
+ publicKey
3949
+ }).then((accessKey) => {
3950
+ if (accessKey.error) {
3951
+ throw new Error(`Access key error: ${accessKey.error}`);
3952
+ }
3953
+ lsSet("nonce", accessKey.nonce);
3954
+ return accessKey.nonce;
3955
+ });
3956
+ }
3957
+ if (!block || !block.header || parseFloat(block.header.timestamp_nanosec) / 1e6 + MaxBlockDelayMs < Date.now()) {
3958
+ toDoPromises.block = api.block({ blockId: "final" }).then((b) => {
3959
+ const newBlock = {
3960
+ header: {
3961
+ prev_hash: b.header.prev_hash,
3962
+ timestamp_nanosec: b.header.timestamp_nanosec
3963
+ }
3964
+ };
3965
+ lsSet("block", newBlock);
3966
+ return newBlock;
3967
+ });
3968
+ }
3969
+ if (Object.keys(toDoPromises).length > 0) {
3970
+ const results = await Promise.all(Object.values(toDoPromises));
3971
+ const keys = Object.keys(toDoPromises);
3972
+ results.forEach((res, i) => {
3973
+ if (keys[i] === "nonce") {
3974
+ nonce = res;
3975
+ } else if (keys[i] === "block") {
3976
+ block = res;
3977
+ }
3978
+ });
3979
+ }
3980
+ const newNonce = (nonce ?? 0) + 1;
3981
+ lsSet("nonce", newNonce);
3982
+ const blockHash = block.header.prev_hash;
3983
+ const jsonTransaction = {
3984
+ signerId,
3985
+ publicKey,
3986
+ nonce: newNonce,
3987
+ receiverId,
3988
+ blockHash,
3989
+ actions
3990
+ };
3991
+ console.log("Transaction:", jsonTransaction);
3992
+ const transaction = serializeTransaction(jsonTransaction);
3993
+ const txHash = binary_to_base58_default(sha256(transaction));
3994
+ const signature = signHash(txHash, privateKey);
3995
+ const signedTransaction = serializeSignedTransaction(jsonTransaction, signature);
3996
+ const signedTxBase64 = toBase64(signedTransaction);
3997
+ updateTxHistory({
3998
+ status: "Pending",
3999
+ txId,
4000
+ tx: jsonTransaction,
4001
+ signature,
4002
+ signedTxBase64,
4003
+ txHash,
4004
+ finalState: false
4005
+ });
4006
+ sendTxToRpc(signedTxBase64, waitUntil, txId);
4007
+ return txId;
4008
+ },
4009
+ // Authentication Methods
4010
+ async requestSignIn({ contractId }) {
4011
+ const privateKey = privateKeyFromRandom();
4012
+ updateState({
4013
+ accessKeyContractId: contractId,
4014
+ accountId: null,
4015
+ privateKey
4016
+ });
4017
+ const publicKey = publicKeyFromPrivate(privateKey);
4018
+ const result = await _adapter.signIn({
4019
+ networkId: _config.networkId,
4020
+ contractId,
4021
+ publicKey
4022
+ });
4023
+ console.log("Sign in result:", result);
4024
+ if (result.error) {
4025
+ throw new Error(`Wallet error: ${result.error}`);
4026
+ }
4027
+ if (result.url) {
4028
+ console.log("Redirecting to wallet:", result.url);
4029
+ if (typeof window !== "undefined") {
4030
+ setTimeout(() => {
4031
+ window.location.href = result.url;
4032
+ }, 100);
4033
+ }
4034
+ } else if (result.accountId) {
4035
+ updateState({
4036
+ accountId: result.accountId
4037
+ });
4038
+ }
4039
+ },
4040
+ signOut() {
4041
+ updateState({
4042
+ accountId: null,
4043
+ privateKey: null,
4044
+ contractId: null
4045
+ });
4046
+ },
4047
+ // Event Handlers
4048
+ onAccount(callback) {
4049
+ _eventListeners.account.add(callback);
4050
+ if (_unbroadcastedEvents.account.length > 0) {
4051
+ const events = _unbroadcastedEvents.account;
4052
+ _unbroadcastedEvents.account = [];
4053
+ events.forEach(notifyAccountListeners);
4054
+ }
4055
+ },
4056
+ onTx(callback) {
4057
+ _eventListeners.tx.add(callback);
4058
+ if (_unbroadcastedEvents.tx.length > 0) {
4059
+ const events = _unbroadcastedEvents.tx;
4060
+ _unbroadcastedEvents.tx = [];
4061
+ events.forEach(notifyTxListeners);
4062
+ }
4063
+ },
4064
+ // Action Helpers
4065
+ actions: {
4066
+ functionCall: ({
4067
+ methodName,
4068
+ gas,
4069
+ deposit,
4070
+ args,
4071
+ argsBase64
4072
+ }) => ({
4073
+ type: "FunctionCall",
4074
+ methodName,
4075
+ args,
4076
+ argsBase64,
4077
+ gas,
4078
+ deposit
4079
+ }),
4080
+ transfer: (yoctoAmount) => ({
4081
+ type: "Transfer",
4082
+ deposit: yoctoAmount
4083
+ }),
4084
+ stakeNEAR: ({ amount, publicKey }) => ({
4085
+ type: "Stake",
4086
+ stake: amount,
4087
+ publicKey
4088
+ }),
4089
+ addFullAccessKey: ({ publicKey }) => ({
4090
+ type: "AddKey",
4091
+ publicKey,
4092
+ accessKey: { permission: "FullAccess" }
4093
+ }),
4094
+ addLimitedAccessKey: ({
4095
+ publicKey,
4096
+ allowance,
4097
+ accountId,
4098
+ methodNames
4099
+ }) => ({
4100
+ type: "AddKey",
4101
+ publicKey,
4102
+ accessKey: {
4103
+ permission: "FunctionCall",
4104
+ allowance,
4105
+ receiverId: accountId,
4106
+ methodNames
4107
+ }
4108
+ }),
4109
+ deleteKey: ({ publicKey }) => ({
4110
+ type: "DeleteKey",
4111
+ publicKey
4112
+ }),
4113
+ deleteAccount: ({ beneficiaryId }) => ({
4114
+ type: "DeleteAccount",
4115
+ beneficiaryId
4116
+ }),
4117
+ createAccount: () => ({
4118
+ type: "CreateAccount"
4119
+ }),
4120
+ deployContract: ({ codeBase64 }) => ({
4121
+ type: "DeployContract",
4122
+ codeBase64
4123
+ })
4124
+ },
4125
+ utils: {
4126
+ toBase64,
4127
+ fromBase64,
4128
+ toBase58: binary_to_base58_default,
4129
+ fromBase58: base58_to_binary_default
4130
+ }
4131
+ };
4132
+ try {
4133
+ if (typeof window !== "undefined") {
4134
+ const url = new URL(window.location.href);
4135
+ const accountId = url.searchParams.get("account_id");
4136
+ const publicKey = url.searchParams.get("public_key");
4137
+ const errorCode = url.searchParams.get("errorCode");
4138
+ const errorMessage = url.searchParams.get("errorMessage");
4139
+ const transactionHashes = url.searchParams.get("transactionHashes");
4140
+ const txIds = url.searchParams.get("txIds");
4141
+ if (errorCode || errorMessage) {
4142
+ console.warn(new Error(`Wallet error: ${errorCode} ${errorMessage}`));
4143
+ }
4144
+ if (accountId && publicKey) {
4145
+ if (publicKey === _state.publicKey) {
4146
+ updateState({
4147
+ accountId
4148
+ });
4149
+ } else {
4150
+ console.error(
4151
+ new Error("Public key mismatch from wallet redirect"),
4152
+ publicKey,
4153
+ _state.publicKey
4154
+ );
4155
+ }
4156
+ }
4157
+ if (transactionHashes || txIds) {
4158
+ const txHashes = transactionHashes ? transactionHashes.split(",") : [];
4159
+ const txIdsArray = txIds ? txIds.split(",") : [];
4160
+ if (txIdsArray.length > txHashes.length) {
4161
+ txIdsArray.forEach((txId, i) => {
4162
+ updateTxHistory({
4163
+ txId,
4164
+ status: "RejectedByUser",
4165
+ finalState: true
4166
+ });
4167
+ });
4168
+ } else if (txIdsArray.length === txHashes.length) {
4169
+ txIdsArray.forEach((txId, i) => {
4170
+ updateTxHistory({
4171
+ txId,
4172
+ status: "PendingGotTxHash",
4173
+ txHash: txHashes[i],
4174
+ finalState: false
4175
+ });
4176
+ afterTxSent(txId);
4177
+ });
4178
+ } else {
4179
+ console.error(
4180
+ new Error("Transaction hash mismatch from wallet redirect"),
4181
+ txIdsArray,
4182
+ txHashes
4183
+ );
4184
+ }
4185
+ }
4186
+ url.searchParams.delete("account_id");
4187
+ url.searchParams.delete("public_key");
4188
+ url.searchParams.delete("errorCode");
4189
+ url.searchParams.delete("errorMessage");
4190
+ url.searchParams.delete("all_keys");
4191
+ url.searchParams.delete("transactionHashes");
4192
+ url.searchParams.delete("txIds");
4193
+ window.history.replaceState({}, "", url.toString());
4194
+ }
4195
+ } catch (e) {
4196
+ console.error("Error handling wallet redirect:", e);
4197
+ }
4198
+
4199
+ // src/index.ts
4200
+ window.near = api;
4201
+ window.$$ = convertUnit;
4202
+ return __toCommonJS(src_exports);
4203
+ })();
4204
+ /*! Bundled license information:
4205
+
4206
+ @noble/hashes/esm/utils.js:
4207
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4208
+
4209
+ @noble/curves/esm/abstract/utils.js:
4210
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4211
+
4212
+ @noble/curves/esm/abstract/modular.js:
4213
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4214
+
4215
+ @noble/curves/esm/abstract/curve.js:
4216
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4217
+
4218
+ @noble/curves/esm/abstract/edwards.js:
4219
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4220
+
4221
+ @noble/curves/esm/ed25519.js:
4222
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4223
+
4224
+ @noble/hashes/esm/utils.js:
4225
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4226
+ */
4227
+ //# sourceMappingURL=index.js.map