@fastnear/api 0.9.13 → 0.10.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.
@@ -1,5 +1,5 @@
1
- /* ⋈ 🏃🏻💨 FastNear API - IIFE/UMD (@fastnear/api version 0.9.12) */
2
- /* https://www.npmjs.com/package/@fastnear/api/v/0.9.12 */
1
+ /* ⋈ 🏃🏻💨 FastNear API - IIFE/UMD (@fastnear/api version 0.10.0) */
2
+ /* https://www.npmjs.com/package/@fastnear/api/v/0.10.0 */
3
3
  "use strict";
4
4
  var near = (() => {
5
5
  var __defProp = Object.defineProperty;
@@ -54,494 +54,6 @@ var near = (() => {
54
54
  withBlockId: () => withBlockId
55
55
  });
56
56
 
57
- // ../../node_modules/big.js/big.mjs
58
- var DP = 20;
59
- var RM = 1;
60
- var MAX_DP = 1e6;
61
- var MAX_POWER = 1e6;
62
- var NE = -7;
63
- var PE = 21;
64
- var STRICT = false;
65
- var NAME = "[big.js] ";
66
- var INVALID = NAME + "Invalid ";
67
- var INVALID_DP = INVALID + "decimal places";
68
- var INVALID_RM = INVALID + "rounding mode";
69
- var DIV_BY_ZERO = NAME + "Division by zero";
70
- var P = {};
71
- var UNDEFINED = void 0;
72
- var NUMERIC = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;
73
- function _Big_() {
74
- function Big2(n) {
75
- var x = this;
76
- if (!(x instanceof Big2)) return n === UNDEFINED ? _Big_() : new Big2(n);
77
- if (n instanceof Big2) {
78
- x.s = n.s;
79
- x.e = n.e;
80
- x.c = n.c.slice();
81
- } else {
82
- if (typeof n !== "string") {
83
- if (Big2.strict === true && typeof n !== "bigint") {
84
- throw TypeError(INVALID + "value");
85
- }
86
- n = n === 0 && 1 / n < 0 ? "-0" : String(n);
87
- }
88
- parse(x, n);
89
- }
90
- x.constructor = Big2;
91
- }
92
- __name(Big2, "Big");
93
- Big2.prototype = P;
94
- Big2.DP = DP;
95
- Big2.RM = RM;
96
- Big2.NE = NE;
97
- Big2.PE = PE;
98
- Big2.strict = STRICT;
99
- Big2.roundDown = 0;
100
- Big2.roundHalfUp = 1;
101
- Big2.roundHalfEven = 2;
102
- Big2.roundUp = 3;
103
- return Big2;
104
- }
105
- __name(_Big_, "_Big_");
106
- function parse(x, n) {
107
- var e, i, nl;
108
- if (!NUMERIC.test(n)) {
109
- throw Error(INVALID + "number");
110
- }
111
- x.s = n.charAt(0) == "-" ? (n = n.slice(1), -1) : 1;
112
- if ((e = n.indexOf(".")) > -1) n = n.replace(".", "");
113
- if ((i = n.search(/e/i)) > 0) {
114
- if (e < 0) e = i;
115
- e += +n.slice(i + 1);
116
- n = n.substring(0, i);
117
- } else if (e < 0) {
118
- e = n.length;
119
- }
120
- nl = n.length;
121
- for (i = 0; i < nl && n.charAt(i) == "0"; ) ++i;
122
- if (i == nl) {
123
- x.c = [x.e = 0];
124
- } else {
125
- for (; nl > 0 && n.charAt(--nl) == "0"; ) ;
126
- x.e = e - i - 1;
127
- x.c = [];
128
- for (e = 0; i <= nl; ) x.c[e++] = +n.charAt(i++);
129
- }
130
- return x;
131
- }
132
- __name(parse, "parse");
133
- function round(x, sd, rm, more) {
134
- var xc = x.c;
135
- if (rm === UNDEFINED) rm = x.constructor.RM;
136
- if (rm !== 0 && rm !== 1 && rm !== 2 && rm !== 3) {
137
- throw Error(INVALID_RM);
138
- }
139
- if (sd < 1) {
140
- 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)));
141
- xc.length = 1;
142
- if (more) {
143
- x.e = x.e - sd + 1;
144
- xc[0] = 1;
145
- } else {
146
- xc[0] = x.e = 0;
147
- }
148
- } else if (sd < xc.length) {
149
- 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]);
150
- xc.length = sd;
151
- if (more) {
152
- for (; ++xc[--sd] > 9; ) {
153
- xc[sd] = 0;
154
- if (sd === 0) {
155
- ++x.e;
156
- xc.unshift(1);
157
- break;
158
- }
159
- }
160
- }
161
- for (sd = xc.length; !xc[--sd]; ) xc.pop();
162
- }
163
- return x;
164
- }
165
- __name(round, "round");
166
- function stringify(x, doExponential, isNonzero) {
167
- var e = x.e, s = x.c.join(""), n = s.length;
168
- if (doExponential) {
169
- s = s.charAt(0) + (n > 1 ? "." + s.slice(1) : "") + (e < 0 ? "e" : "e+") + e;
170
- } else if (e < 0) {
171
- for (; ++e; ) s = "0" + s;
172
- s = "0." + s;
173
- } else if (e > 0) {
174
- if (++e > n) {
175
- for (e -= n; e--; ) s += "0";
176
- } else if (e < n) {
177
- s = s.slice(0, e) + "." + s.slice(e);
178
- }
179
- } else if (n > 1) {
180
- s = s.charAt(0) + "." + s.slice(1);
181
- }
182
- return x.s < 0 && isNonzero ? "-" + s : s;
183
- }
184
- __name(stringify, "stringify");
185
- P.abs = function() {
186
- var x = new this.constructor(this);
187
- x.s = 1;
188
- return x;
189
- };
190
- P.cmp = function(y) {
191
- 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;
192
- if (!xc[0] || !yc[0]) return !xc[0] ? !yc[0] ? 0 : -j : i;
193
- if (i != j) return i;
194
- isneg = i < 0;
195
- if (k != l) return k > l ^ isneg ? 1 : -1;
196
- j = (k = xc.length) < (l = yc.length) ? k : l;
197
- for (i = -1; ++i < j; ) {
198
- if (xc[i] != yc[i]) return xc[i] > yc[i] ^ isneg ? 1 : -1;
199
- }
200
- return k == l ? 0 : k > l ^ isneg ? 1 : -1;
201
- };
202
- P.div = function(y) {
203
- 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;
204
- if (dp !== ~~dp || dp < 0 || dp > MAX_DP) {
205
- throw Error(INVALID_DP);
206
- }
207
- if (!b[0]) {
208
- throw Error(DIV_BY_ZERO);
209
- }
210
- if (!a[0]) {
211
- y.s = k;
212
- y.c = [y.e = 0];
213
- return y;
214
- }
215
- 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;
216
- q.s = k;
217
- k = p < 0 ? 0 : p;
218
- bz.unshift(0);
219
- for (; rl++ < bl; ) r.push(0);
220
- do {
221
- for (n = 0; n < 10; n++) {
222
- if (bl != (rl = r.length)) {
223
- cmp = bl > rl ? 1 : -1;
224
- } else {
225
- for (ri = -1, cmp = 0; ++ri < bl; ) {
226
- if (b[ri] != r[ri]) {
227
- cmp = b[ri] > r[ri] ? 1 : -1;
228
- break;
229
- }
230
- }
231
- }
232
- if (cmp < 0) {
233
- for (bt = rl == bl ? b : bz; rl; ) {
234
- if (r[--rl] < bt[rl]) {
235
- ri = rl;
236
- for (; ri && !r[--ri]; ) r[ri] = 9;
237
- --r[ri];
238
- r[rl] += 10;
239
- }
240
- r[rl] -= bt[rl];
241
- }
242
- for (; !r[0]; ) r.shift();
243
- } else {
244
- break;
245
- }
246
- }
247
- qc[qi++] = cmp ? n : ++n;
248
- if (r[0] && cmp) r[rl] = a[ai] || 0;
249
- else r = [a[ai]];
250
- } while ((ai++ < al || r[0] !== UNDEFINED) && k--);
251
- if (!qc[0] && qi != 1) {
252
- qc.shift();
253
- q.e--;
254
- p--;
255
- }
256
- if (qi > p) round(q, p, Big2.RM, r[0] !== UNDEFINED);
257
- return q;
258
- };
259
- P.eq = function(y) {
260
- return this.cmp(y) === 0;
261
- };
262
- P.gt = function(y) {
263
- return this.cmp(y) > 0;
264
- };
265
- P.gte = function(y) {
266
- return this.cmp(y) > -1;
267
- };
268
- P.lt = function(y) {
269
- return this.cmp(y) < 0;
270
- };
271
- P.lte = function(y) {
272
- return this.cmp(y) < 1;
273
- };
274
- P.minus = P.sub = function(y) {
275
- var i, j, t, xlty, x = this, Big2 = x.constructor, a = x.s, b = (y = new Big2(y)).s;
276
- if (a != b) {
277
- y.s = -b;
278
- return x.plus(y);
279
- }
280
- var xc = x.c.slice(), xe = x.e, yc = y.c, ye = y.e;
281
- if (!xc[0] || !yc[0]) {
282
- if (yc[0]) {
283
- y.s = -b;
284
- } else if (xc[0]) {
285
- y = new Big2(x);
286
- } else {
287
- y.s = 1;
288
- }
289
- return y;
290
- }
291
- if (a = xe - ye) {
292
- if (xlty = a < 0) {
293
- a = -a;
294
- t = xc;
295
- } else {
296
- ye = xe;
297
- t = yc;
298
- }
299
- t.reverse();
300
- for (b = a; b--; ) t.push(0);
301
- t.reverse();
302
- } else {
303
- j = ((xlty = xc.length < yc.length) ? xc : yc).length;
304
- for (a = b = 0; b < j; b++) {
305
- if (xc[b] != yc[b]) {
306
- xlty = xc[b] < yc[b];
307
- break;
308
- }
309
- }
310
- }
311
- if (xlty) {
312
- t = xc;
313
- xc = yc;
314
- yc = t;
315
- y.s = -y.s;
316
- }
317
- if ((b = (j = yc.length) - (i = xc.length)) > 0) for (; b--; ) xc[i++] = 0;
318
- for (b = i; j > a; ) {
319
- if (xc[--j] < yc[j]) {
320
- for (i = j; i && !xc[--i]; ) xc[i] = 9;
321
- --xc[i];
322
- xc[j] += 10;
323
- }
324
- xc[j] -= yc[j];
325
- }
326
- for (; xc[--b] === 0; ) xc.pop();
327
- for (; xc[0] === 0; ) {
328
- xc.shift();
329
- --ye;
330
- }
331
- if (!xc[0]) {
332
- y.s = 1;
333
- xc = [ye = 0];
334
- }
335
- y.c = xc;
336
- y.e = ye;
337
- return y;
338
- };
339
- P.mod = function(y) {
340
- var ygtx, x = this, Big2 = x.constructor, a = x.s, b = (y = new Big2(y)).s;
341
- if (!y.c[0]) {
342
- throw Error(DIV_BY_ZERO);
343
- }
344
- x.s = y.s = 1;
345
- ygtx = y.cmp(x) == 1;
346
- x.s = a;
347
- y.s = b;
348
- if (ygtx) return new Big2(x);
349
- a = Big2.DP;
350
- b = Big2.RM;
351
- Big2.DP = Big2.RM = 0;
352
- x = x.div(y);
353
- Big2.DP = a;
354
- Big2.RM = b;
355
- return this.minus(x.times(y));
356
- };
357
- P.neg = function() {
358
- var x = new this.constructor(this);
359
- x.s = -x.s;
360
- return x;
361
- };
362
- P.plus = P.add = function(y) {
363
- var e, k, t, x = this, Big2 = x.constructor;
364
- y = new Big2(y);
365
- if (x.s != y.s) {
366
- y.s = -y.s;
367
- return x.minus(y);
368
- }
369
- var xe = x.e, xc = x.c, ye = y.e, yc = y.c;
370
- if (!xc[0] || !yc[0]) {
371
- if (!yc[0]) {
372
- if (xc[0]) {
373
- y = new Big2(x);
374
- } else {
375
- y.s = x.s;
376
- }
377
- }
378
- return y;
379
- }
380
- xc = xc.slice();
381
- if (e = xe - ye) {
382
- if (e > 0) {
383
- ye = xe;
384
- t = yc;
385
- } else {
386
- e = -e;
387
- t = xc;
388
- }
389
- t.reverse();
390
- for (; e--; ) t.push(0);
391
- t.reverse();
392
- }
393
- if (xc.length - yc.length < 0) {
394
- t = yc;
395
- yc = xc;
396
- xc = t;
397
- }
398
- e = yc.length;
399
- for (k = 0; e; xc[e] %= 10) k = (xc[--e] = xc[e] + yc[e] + k) / 10 | 0;
400
- if (k) {
401
- xc.unshift(k);
402
- ++ye;
403
- }
404
- for (e = xc.length; xc[--e] === 0; ) xc.pop();
405
- y.c = xc;
406
- y.e = ye;
407
- return y;
408
- };
409
- P.pow = function(n) {
410
- var x = this, one = new x.constructor("1"), y = one, isneg = n < 0;
411
- if (n !== ~~n || n < -MAX_POWER || n > MAX_POWER) {
412
- throw Error(INVALID + "exponent");
413
- }
414
- if (isneg) n = -n;
415
- for (; ; ) {
416
- if (n & 1) y = y.times(x);
417
- n >>= 1;
418
- if (!n) break;
419
- x = x.times(x);
420
- }
421
- return isneg ? one.div(y) : y;
422
- };
423
- P.prec = function(sd, rm) {
424
- if (sd !== ~~sd || sd < 1 || sd > MAX_DP) {
425
- throw Error(INVALID + "precision");
426
- }
427
- return round(new this.constructor(this), sd, rm);
428
- };
429
- P.round = function(dp, rm) {
430
- if (dp === UNDEFINED) dp = 0;
431
- else if (dp !== ~~dp || dp < -MAX_DP || dp > MAX_DP) {
432
- throw Error(INVALID_DP);
433
- }
434
- return round(new this.constructor(this), dp + this.e + 1, rm);
435
- };
436
- P.sqrt = function() {
437
- var r, c, t, x = this, Big2 = x.constructor, s = x.s, e = x.e, half = new Big2("0.5");
438
- if (!x.c[0]) return new Big2(x);
439
- if (s < 0) {
440
- throw Error(NAME + "No square root");
441
- }
442
- s = Math.sqrt(+stringify(x, true, true));
443
- if (s === 0 || s === 1 / 0) {
444
- c = x.c.join("");
445
- if (!(c.length + e & 1)) c += "0";
446
- s = Math.sqrt(c);
447
- e = ((e + 1) / 2 | 0) - (e < 0 || e & 1);
448
- r = new Big2((s == 1 / 0 ? "5e" : (s = s.toExponential()).slice(0, s.indexOf("e") + 1)) + e);
449
- } else {
450
- r = new Big2(s + "");
451
- }
452
- e = r.e + (Big2.DP += 4);
453
- do {
454
- t = r;
455
- r = half.times(t.plus(x.div(t)));
456
- } while (t.c.slice(0, e).join("") !== r.c.slice(0, e).join(""));
457
- return round(r, (Big2.DP -= 4) + r.e + 1, Big2.RM);
458
- };
459
- P.times = P.mul = function(y) {
460
- 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;
461
- y.s = x.s == y.s ? 1 : -1;
462
- if (!xc[0] || !yc[0]) {
463
- y.c = [y.e = 0];
464
- return y;
465
- }
466
- y.e = i + j;
467
- if (a < b) {
468
- c = xc;
469
- xc = yc;
470
- yc = c;
471
- j = a;
472
- a = b;
473
- b = j;
474
- }
475
- for (c = new Array(j = a + b); j--; ) c[j] = 0;
476
- for (i = b; i--; ) {
477
- b = 0;
478
- for (j = a + i; j > i; ) {
479
- b = c[j] + yc[i] * xc[j - i - 1] + b;
480
- c[j--] = b % 10;
481
- b = b / 10 | 0;
482
- }
483
- c[j] = b;
484
- }
485
- if (b) ++y.e;
486
- else c.shift();
487
- for (i = c.length; !c[--i]; ) c.pop();
488
- y.c = c;
489
- return y;
490
- };
491
- P.toExponential = function(dp, rm) {
492
- var x = this, n = x.c[0];
493
- if (dp !== UNDEFINED) {
494
- if (dp !== ~~dp || dp < 0 || dp > MAX_DP) {
495
- throw Error(INVALID_DP);
496
- }
497
- x = round(new x.constructor(x), ++dp, rm);
498
- for (; x.c.length < dp; ) x.c.push(0);
499
- }
500
- return stringify(x, true, !!n);
501
- };
502
- P.toFixed = function(dp, rm) {
503
- var x = this, n = x.c[0];
504
- if (dp !== UNDEFINED) {
505
- if (dp !== ~~dp || dp < 0 || dp > MAX_DP) {
506
- throw Error(INVALID_DP);
507
- }
508
- x = round(new x.constructor(x), dp + x.e + 1, rm);
509
- for (dp = dp + x.e + 1; x.c.length < dp; ) x.c.push(0);
510
- }
511
- return stringify(x, false, !!n);
512
- };
513
- P[Symbol.for("nodejs.util.inspect.custom")] = P.toJSON = P.toString = function() {
514
- var x = this, Big2 = x.constructor;
515
- return stringify(x, x.e <= Big2.NE || x.e >= Big2.PE, !!x.c[0]);
516
- };
517
- P.toNumber = function() {
518
- var n = +stringify(this, true, true);
519
- if (this.constructor.strict === true && !this.eq(n.toString())) {
520
- throw Error(NAME + "Imprecise conversion");
521
- }
522
- return n;
523
- };
524
- P.toPrecision = function(sd, rm) {
525
- var x = this, Big2 = x.constructor, n = x.c[0];
526
- if (sd !== UNDEFINED) {
527
- if (sd !== ~~sd || sd < 1 || sd > MAX_DP) {
528
- throw Error(INVALID + "precision");
529
- }
530
- x = round(new Big2(x), sd, rm);
531
- for (; x.c.length < sd; ) x.c.push(0);
532
- }
533
- return stringify(x, sd <= x.e || x.e <= Big2.NE || x.e >= Big2.PE, !!n);
534
- };
535
- P.valueOf = function() {
536
- var x = this, Big2 = x.constructor;
537
- if (Big2.strict === true) {
538
- throw Error(NAME + "valueOf disallowed");
539
- }
540
- return stringify(x, x.e <= Big2.NE || x.e >= Big2.PE, true);
541
- };
542
- var Big = _Big_();
543
- var big_default = Big;
544
-
545
57
  // ../utils/src/index.ts
546
58
  var src_exports2 = {};
547
59
  __export(src_exports2, {
@@ -552,6 +64,7 @@ var near = (() => {
552
64
  canSignWithLAK: () => canSignWithLAK,
553
65
  convertUnit: () => convertUnit,
554
66
  createDefaultStorage: () => createDefaultStorage,
67
+ curveFromKey: () => curveFromKey,
555
68
  deepCopy: () => deepCopy,
556
69
  exp: () => exp,
557
70
  fromBase58: () => base58_to_binary_default,
@@ -606,6 +119,13 @@ var near = (() => {
606
119
  return value;
607
120
  }
608
121
  __name(abytes, "abytes");
122
+ function ahash(h) {
123
+ if (typeof h !== "function" || typeof h.create !== "function")
124
+ throw new Error("Hash must wrapped by utils.createHasher");
125
+ anumber(h.outputLen);
126
+ anumber(h.blockLen);
127
+ }
128
+ __name(ahash, "ahash");
609
129
  function aexists(instance, checkFinished = true) {
610
130
  if (instance.destroyed)
611
131
  throw new Error("Hash instance has been destroyed");
@@ -1283,6 +803,11 @@ var near = (() => {
1283
803
  return n;
1284
804
  }
1285
805
  __name(abignumber, "abignumber");
806
+ function numberToHexUnpadded(num) {
807
+ const hex = abignumber(num).toString(16);
808
+ return hex.length & 1 ? "0" + hex : hex;
809
+ }
810
+ __name(numberToHexUnpadded, "numberToHexUnpadded");
1286
811
  function hexToNumber(hex) {
1287
812
  if (typeof hex !== "string")
1288
813
  throw new Error("hex string expected, got " + typeof hex);
@@ -1324,7 +849,66 @@ var near = (() => {
1324
849
  throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
1325
850
  }
1326
851
  __name(aInRange, "aInRange");
852
+ function bitLen(n) {
853
+ let len;
854
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
855
+ ;
856
+ return len;
857
+ }
858
+ __name(bitLen, "bitLen");
1327
859
  var bitMask = /* @__PURE__ */ __name((n) => (_1n << BigInt(n)) - _1n, "bitMask");
860
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
861
+ anumber(hashLen, "hashLen");
862
+ anumber(qByteLen, "qByteLen");
863
+ if (typeof hmacFn !== "function")
864
+ throw new Error("hmacFn must be a function");
865
+ const u8n = /* @__PURE__ */ __name((len) => new Uint8Array(len), "u8n");
866
+ const NULL = Uint8Array.of();
867
+ const byte0 = Uint8Array.of(0);
868
+ const byte1 = Uint8Array.of(1);
869
+ const _maxDrbgIters = 1e3;
870
+ let v = u8n(hashLen);
871
+ let k = u8n(hashLen);
872
+ let i = 0;
873
+ const reset = /* @__PURE__ */ __name(() => {
874
+ v.fill(1);
875
+ k.fill(0);
876
+ i = 0;
877
+ }, "reset");
878
+ const h = /* @__PURE__ */ __name((...msgs) => hmacFn(k, concatBytes(v, ...msgs)), "h");
879
+ const reseed = /* @__PURE__ */ __name((seed = NULL) => {
880
+ k = h(byte0, seed);
881
+ v = h();
882
+ if (seed.length === 0)
883
+ return;
884
+ k = h(byte1, seed);
885
+ v = h();
886
+ }, "reseed");
887
+ const gen = /* @__PURE__ */ __name(() => {
888
+ if (i++ >= _maxDrbgIters)
889
+ throw new Error("drbg: tried max amount of iterations");
890
+ let len = 0;
891
+ const out = [];
892
+ while (len < qByteLen) {
893
+ v = h();
894
+ const sl = v.slice();
895
+ out.push(sl);
896
+ len += v.length;
897
+ }
898
+ return concatBytes(...out);
899
+ }, "gen");
900
+ const genUntil = /* @__PURE__ */ __name((seed, pred) => {
901
+ reset();
902
+ reseed(seed);
903
+ let res = void 0;
904
+ while (!(res = pred(gen())))
905
+ reseed();
906
+ reset();
907
+ return res;
908
+ }, "genUntil");
909
+ return genUntil;
910
+ }
911
+ __name(createHmacDrbg, "createHmacDrbg");
1328
912
  function validateObject(object, fields = {}, optFields = {}) {
1329
913
  if (!object || typeof object !== "object")
1330
914
  throw new Error("expected valid options object");
@@ -1424,13 +1008,13 @@ var near = (() => {
1424
1008
  return root;
1425
1009
  }
1426
1010
  __name(sqrt5mod8, "sqrt5mod8");
1427
- function sqrt9mod16(P2) {
1428
- const Fp_ = Field(P2);
1429
- const tn = tonelliShanks(P2);
1011
+ function sqrt9mod16(P) {
1012
+ const Fp_ = Field(P);
1013
+ const tn = tonelliShanks(P);
1430
1014
  const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
1431
1015
  const c2 = tn(Fp_, c1);
1432
1016
  const c3 = tn(Fp_, Fp_.neg(c1));
1433
- const c4 = (P2 + _7n) / _16n;
1017
+ const c4 = (P + _7n) / _16n;
1434
1018
  return (Fp, n) => {
1435
1019
  let tv1 = Fp.pow(n, c4);
1436
1020
  let tv2 = Fp.mul(tv1, c1);
@@ -1447,17 +1031,17 @@ var near = (() => {
1447
1031
  };
1448
1032
  }
1449
1033
  __name(sqrt9mod16, "sqrt9mod16");
1450
- function tonelliShanks(P2) {
1451
- if (P2 < _3n)
1034
+ function tonelliShanks(P) {
1035
+ if (P < _3n)
1452
1036
  throw new Error("sqrt is not defined for small field");
1453
- let Q = P2 - _1n2;
1037
+ let Q = P - _1n2;
1454
1038
  let S = 0;
1455
1039
  while (Q % _2n === _0n2) {
1456
1040
  Q /= _2n;
1457
1041
  S++;
1458
1042
  }
1459
1043
  let Z = _2n;
1460
- const _Fp = Field(P2);
1044
+ const _Fp = Field(P);
1461
1045
  while (FpLegendre(_Fp, Z) === 1) {
1462
1046
  if (Z++ > 1e3)
1463
1047
  throw new Error("Cannot find square root: probably non-prime P");
@@ -1497,14 +1081,14 @@ var near = (() => {
1497
1081
  }, "tonelliSlow");
1498
1082
  }
1499
1083
  __name(tonelliShanks, "tonelliShanks");
1500
- function FpSqrt(P2) {
1501
- if (P2 % _4n === _3n)
1084
+ function FpSqrt(P) {
1085
+ if (P % _4n === _3n)
1502
1086
  return sqrt3mod4;
1503
- if (P2 % _8n === _5n)
1087
+ if (P % _8n === _5n)
1504
1088
  return sqrt5mod8;
1505
- if (P2 % _16n === _9n)
1506
- return sqrt9mod16(P2);
1507
- return tonelliShanks(P2);
1089
+ if (P % _16n === _9n)
1090
+ return sqrt9mod16(P);
1091
+ return tonelliShanks(P);
1508
1092
  }
1509
1093
  __name(FpSqrt, "FpSqrt");
1510
1094
  var isNegativeLE = /* @__PURE__ */ __name((num, modulo) => (mod(num, modulo) & _1n2) === _1n2, "isNegativeLE");
@@ -1738,6 +1322,30 @@ var near = (() => {
1738
1322
  return new _Field(ORDER, opts);
1739
1323
  }
1740
1324
  __name(Field, "Field");
1325
+ function getFieldBytesLength(fieldOrder) {
1326
+ if (typeof fieldOrder !== "bigint")
1327
+ throw new Error("field order must be bigint");
1328
+ const bitLength = fieldOrder.toString(2).length;
1329
+ return Math.ceil(bitLength / 8);
1330
+ }
1331
+ __name(getFieldBytesLength, "getFieldBytesLength");
1332
+ function getMinHashLength(fieldOrder) {
1333
+ const length = getFieldBytesLength(fieldOrder);
1334
+ return length + Math.ceil(length / 2);
1335
+ }
1336
+ __name(getMinHashLength, "getMinHashLength");
1337
+ function mapHashToField(key, fieldOrder, isLE = false) {
1338
+ abytes(key);
1339
+ const len = key.length;
1340
+ const fieldLen = getFieldBytesLength(fieldOrder);
1341
+ const minLen = getMinHashLength(fieldOrder);
1342
+ if (len < 16 || len < minLen || len > 1024)
1343
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
1344
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
1345
+ const reduced = mod(num, fieldOrder - _1n2) + _1n2;
1346
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
1347
+ }
1348
+ __name(mapHashToField, "mapHashToField");
1741
1349
 
1742
1350
  // ../../node_modules/@noble/curves/abstract/curve.js
1743
1351
  var _0n3 = /* @__PURE__ */ BigInt(0);
@@ -1786,8 +1394,8 @@ var near = (() => {
1786
1394
  __name(calcOffsets, "calcOffsets");
1787
1395
  var pointPrecomputes = /* @__PURE__ */ new WeakMap();
1788
1396
  var pointWindowSizes = /* @__PURE__ */ new WeakMap();
1789
- function getW(P2) {
1790
- return pointWindowSizes.get(P2) || 1;
1397
+ function getW(P) {
1398
+ return pointWindowSizes.get(P) || 1;
1791
1399
  }
1792
1400
  __name(getW, "getW");
1793
1401
  function assert0(n) {
@@ -1920,15 +1528,31 @@ var near = (() => {
1920
1528
  // We calculate precomputes for elliptic curve point multiplication
1921
1529
  // using windowed method. This specifies window size and
1922
1530
  // stores precomputed values. Usually only base point would be precomputed.
1923
- createCache(P2, W) {
1531
+ createCache(P, W) {
1924
1532
  validateW(W, this.bits);
1925
- pointWindowSizes.set(P2, W);
1926
- pointPrecomputes.delete(P2);
1533
+ pointWindowSizes.set(P, W);
1534
+ pointPrecomputes.delete(P);
1927
1535
  }
1928
1536
  hasCache(elm) {
1929
1537
  return getW(elm) !== 1;
1930
1538
  }
1931
1539
  };
1540
+ function mulEndoUnsafe(Point, point, k1, k2) {
1541
+ let acc = point;
1542
+ let p1 = Point.ZERO;
1543
+ let p2 = Point.ZERO;
1544
+ while (k1 > _0n3 || k2 > _0n3) {
1545
+ if (k1 & _1n3)
1546
+ p1 = p1.add(acc);
1547
+ if (k2 & _1n3)
1548
+ p2 = p2.add(acc);
1549
+ acc = acc.double();
1550
+ k1 >>= _1n3;
1551
+ k2 >>= _1n3;
1552
+ }
1553
+ return { p1, p2 };
1554
+ }
1555
+ __name(mulEndoUnsafe, "mulEndoUnsafe");
1932
1556
  function createField(order, field, isLE) {
1933
1557
  if (field) {
1934
1558
  if (field.ORDER !== order)
@@ -2425,19 +2049,19 @@ var near = (() => {
2425
2049
  }))();
2426
2050
  function ed25519_pow_2_252_3(x) {
2427
2051
  const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
2428
- const P2 = ed25519_CURVE_p;
2429
- const x2 = x * x % P2;
2430
- const b2 = x2 * x % P2;
2431
- const b4 = pow2(b2, _2n3, P2) * b2 % P2;
2432
- const b5 = pow2(b4, _1n5, P2) * x % P2;
2433
- const b10 = pow2(b5, _5n2, P2) * b5 % P2;
2434
- const b20 = pow2(b10, _10n, P2) * b10 % P2;
2435
- const b40 = pow2(b20, _20n, P2) * b20 % P2;
2436
- const b80 = pow2(b40, _40n, P2) * b40 % P2;
2437
- const b160 = pow2(b80, _80n, P2) * b80 % P2;
2438
- const b240 = pow2(b160, _80n, P2) * b80 % P2;
2439
- const b250 = pow2(b240, _10n, P2) * b10 % P2;
2440
- const pow_p_5_8 = pow2(b250, _2n3, P2) * x % P2;
2052
+ const P = ed25519_CURVE_p;
2053
+ const x2 = x * x % P;
2054
+ const b2 = x2 * x % P;
2055
+ const b4 = pow2(b2, _2n3, P) * b2 % P;
2056
+ const b5 = pow2(b4, _1n5, P) * x % P;
2057
+ const b10 = pow2(b5, _5n2, P) * b5 % P;
2058
+ const b20 = pow2(b10, _10n, P) * b10 % P;
2059
+ const b40 = pow2(b20, _20n, P) * b20 % P;
2060
+ const b80 = pow2(b40, _40n, P) * b40 % P;
2061
+ const b160 = pow2(b80, _80n, P) * b80 % P;
2062
+ const b240 = pow2(b160, _80n, P) * b80 % P;
2063
+ const b250 = pow2(b240, _10n, P) * b10 % P;
2064
+ const pow_p_5_8 = pow2(b250, _2n3, P) * x % P;
2441
2065
  return { pow_p_5_8, b2 };
2442
2066
  }
2443
2067
  __name(ed25519_pow_2_252_3, "ed25519_pow_2_252_3");
@@ -2450,23 +2074,23 @@ var near = (() => {
2450
2074
  __name(adjustScalarBytes, "adjustScalarBytes");
2451
2075
  var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
2452
2076
  function uvRatio(u, v) {
2453
- const P2 = ed25519_CURVE_p;
2454
- const v3 = mod(v * v * v, P2);
2455
- const v7 = mod(v3 * v3 * v, P2);
2077
+ const P = ed25519_CURVE_p;
2078
+ const v3 = mod(v * v * v, P);
2079
+ const v7 = mod(v3 * v3 * v, P);
2456
2080
  const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
2457
- let x = mod(u * v3 * pow, P2);
2458
- const vx2 = mod(v * x * x, P2);
2081
+ let x = mod(u * v3 * pow, P);
2082
+ const vx2 = mod(v * x * x, P);
2459
2083
  const root1 = x;
2460
- const root2 = mod(x * ED25519_SQRT_M1, P2);
2084
+ const root2 = mod(x * ED25519_SQRT_M1, P);
2461
2085
  const useRoot1 = vx2 === u;
2462
- const useRoot2 = vx2 === mod(-u, P2);
2463
- const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P2);
2086
+ const useRoot2 = vx2 === mod(-u, P);
2087
+ const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
2464
2088
  if (useRoot1)
2465
2089
  x = root1;
2466
2090
  if (useRoot2 || noRoot)
2467
2091
  x = root2;
2468
- if (isNegativeLE(x, P2))
2469
- x = mod(-x, P2);
2092
+ if (isNegativeLE(x, P))
2093
+ x = mod(-x, P);
2470
2094
  return { isValid: useRoot1 || useRoot2, value: x };
2471
2095
  }
2472
2096
  __name(uvRatio, "uvRatio");
@@ -2477,6 +2101,1043 @@ var near = (() => {
2477
2101
  __name(ed, "ed");
2478
2102
  var ed25519 = /* @__PURE__ */ ed({});
2479
2103
 
2104
+ // ../../node_modules/@noble/hashes/hmac.js
2105
+ var _HMAC = class {
2106
+ static {
2107
+ __name(this, "_HMAC");
2108
+ }
2109
+ oHash;
2110
+ iHash;
2111
+ blockLen;
2112
+ outputLen;
2113
+ finished = false;
2114
+ destroyed = false;
2115
+ constructor(hash, key) {
2116
+ ahash(hash);
2117
+ abytes(key, void 0, "key");
2118
+ this.iHash = hash.create();
2119
+ if (typeof this.iHash.update !== "function")
2120
+ throw new Error("Expected instance of class which extends utils.Hash");
2121
+ this.blockLen = this.iHash.blockLen;
2122
+ this.outputLen = this.iHash.outputLen;
2123
+ const blockLen = this.blockLen;
2124
+ const pad = new Uint8Array(blockLen);
2125
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
2126
+ for (let i = 0; i < pad.length; i++)
2127
+ pad[i] ^= 54;
2128
+ this.iHash.update(pad);
2129
+ this.oHash = hash.create();
2130
+ for (let i = 0; i < pad.length; i++)
2131
+ pad[i] ^= 54 ^ 92;
2132
+ this.oHash.update(pad);
2133
+ clean(pad);
2134
+ }
2135
+ update(buf) {
2136
+ aexists(this);
2137
+ this.iHash.update(buf);
2138
+ return this;
2139
+ }
2140
+ digestInto(out) {
2141
+ aexists(this);
2142
+ abytes(out, this.outputLen, "output");
2143
+ this.finished = true;
2144
+ this.iHash.digestInto(out);
2145
+ this.oHash.update(out);
2146
+ this.oHash.digestInto(out);
2147
+ this.destroy();
2148
+ }
2149
+ digest() {
2150
+ const out = new Uint8Array(this.oHash.outputLen);
2151
+ this.digestInto(out);
2152
+ return out;
2153
+ }
2154
+ _cloneInto(to) {
2155
+ to ||= Object.create(Object.getPrototypeOf(this), {});
2156
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
2157
+ to = to;
2158
+ to.finished = finished;
2159
+ to.destroyed = destroyed;
2160
+ to.blockLen = blockLen;
2161
+ to.outputLen = outputLen;
2162
+ to.oHash = oHash._cloneInto(to.oHash);
2163
+ to.iHash = iHash._cloneInto(to.iHash);
2164
+ return to;
2165
+ }
2166
+ clone() {
2167
+ return this._cloneInto();
2168
+ }
2169
+ destroy() {
2170
+ this.destroyed = true;
2171
+ this.oHash.destroy();
2172
+ this.iHash.destroy();
2173
+ }
2174
+ };
2175
+ var hmac = /* @__PURE__ */ __name((hash, key, message) => new _HMAC(hash, key).update(message).digest(), "hmac");
2176
+ hmac.create = (hash, key) => new _HMAC(hash, key);
2177
+
2178
+ // ../../node_modules/@noble/curves/abstract/weierstrass.js
2179
+ var divNearest = /* @__PURE__ */ __name((num, den) => (num + (num >= 0 ? den : -den) / _2n4) / den, "divNearest");
2180
+ function _splitEndoScalar(k, basis, n) {
2181
+ const [[a1, b1], [a2, b2]] = basis;
2182
+ const c1 = divNearest(b2 * k, n);
2183
+ const c2 = divNearest(-b1 * k, n);
2184
+ let k1 = k - c1 * a1 - c2 * a2;
2185
+ let k2 = -c1 * b1 - c2 * b2;
2186
+ const k1neg = k1 < _0n5;
2187
+ const k2neg = k2 < _0n5;
2188
+ if (k1neg)
2189
+ k1 = -k1;
2190
+ if (k2neg)
2191
+ k2 = -k2;
2192
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n6;
2193
+ if (k1 < _0n5 || k1 >= MAX_NUM || k2 < _0n5 || k2 >= MAX_NUM) {
2194
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
2195
+ }
2196
+ return { k1neg, k1, k2neg, k2 };
2197
+ }
2198
+ __name(_splitEndoScalar, "_splitEndoScalar");
2199
+ function validateSigFormat(format) {
2200
+ if (!["compact", "recovered", "der"].includes(format))
2201
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
2202
+ return format;
2203
+ }
2204
+ __name(validateSigFormat, "validateSigFormat");
2205
+ function validateSigOpts(opts, def) {
2206
+ const optsn = {};
2207
+ for (let optName of Object.keys(def)) {
2208
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
2209
+ }
2210
+ abool(optsn.lowS, "lowS");
2211
+ abool(optsn.prehash, "prehash");
2212
+ if (optsn.format !== void 0)
2213
+ validateSigFormat(optsn.format);
2214
+ return optsn;
2215
+ }
2216
+ __name(validateSigOpts, "validateSigOpts");
2217
+ var DERErr = class extends Error {
2218
+ static {
2219
+ __name(this, "DERErr");
2220
+ }
2221
+ constructor(m = "") {
2222
+ super(m);
2223
+ }
2224
+ };
2225
+ var DER = {
2226
+ // asn.1 DER encoding utils
2227
+ Err: DERErr,
2228
+ // Basic building block is TLV (Tag-Length-Value)
2229
+ _tlv: {
2230
+ encode: /* @__PURE__ */ __name((tag, data) => {
2231
+ const { Err: E } = DER;
2232
+ if (tag < 0 || tag > 256)
2233
+ throw new E("tlv.encode: wrong tag");
2234
+ if (data.length & 1)
2235
+ throw new E("tlv.encode: unpadded data");
2236
+ const dataLen = data.length / 2;
2237
+ const len = numberToHexUnpadded(dataLen);
2238
+ if (len.length / 2 & 128)
2239
+ throw new E("tlv.encode: long form length too big");
2240
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
2241
+ const t = numberToHexUnpadded(tag);
2242
+ return t + lenLen + len + data;
2243
+ }, "encode"),
2244
+ // v - value, l - left bytes (unparsed)
2245
+ decode(tag, data) {
2246
+ const { Err: E } = DER;
2247
+ let pos = 0;
2248
+ if (tag < 0 || tag > 256)
2249
+ throw new E("tlv.encode: wrong tag");
2250
+ if (data.length < 2 || data[pos++] !== tag)
2251
+ throw new E("tlv.decode: wrong tlv");
2252
+ const first = data[pos++];
2253
+ const isLong = !!(first & 128);
2254
+ let length = 0;
2255
+ if (!isLong)
2256
+ length = first;
2257
+ else {
2258
+ const lenLen = first & 127;
2259
+ if (!lenLen)
2260
+ throw new E("tlv.decode(long): indefinite length not supported");
2261
+ if (lenLen > 4)
2262
+ throw new E("tlv.decode(long): byte length is too big");
2263
+ const lengthBytes = data.subarray(pos, pos + lenLen);
2264
+ if (lengthBytes.length !== lenLen)
2265
+ throw new E("tlv.decode: length bytes not complete");
2266
+ if (lengthBytes[0] === 0)
2267
+ throw new E("tlv.decode(long): zero leftmost byte");
2268
+ for (const b of lengthBytes)
2269
+ length = length << 8 | b;
2270
+ pos += lenLen;
2271
+ if (length < 128)
2272
+ throw new E("tlv.decode(long): not minimal encoding");
2273
+ }
2274
+ const v = data.subarray(pos, pos + length);
2275
+ if (v.length !== length)
2276
+ throw new E("tlv.decode: wrong value length");
2277
+ return { v, l: data.subarray(pos + length) };
2278
+ }
2279
+ },
2280
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
2281
+ // since we always use positive integers here. It must always be empty:
2282
+ // - add zero byte if exists
2283
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
2284
+ _int: {
2285
+ encode(num) {
2286
+ const { Err: E } = DER;
2287
+ if (num < _0n5)
2288
+ throw new E("integer: negative integers are not allowed");
2289
+ let hex = numberToHexUnpadded(num);
2290
+ if (Number.parseInt(hex[0], 16) & 8)
2291
+ hex = "00" + hex;
2292
+ if (hex.length & 1)
2293
+ throw new E("unexpected DER parsing assertion: unpadded hex");
2294
+ return hex;
2295
+ },
2296
+ decode(data) {
2297
+ const { Err: E } = DER;
2298
+ if (data[0] & 128)
2299
+ throw new E("invalid signature integer: negative");
2300
+ if (data[0] === 0 && !(data[1] & 128))
2301
+ throw new E("invalid signature integer: unnecessary leading zero");
2302
+ return bytesToNumberBE(data);
2303
+ }
2304
+ },
2305
+ toSig(bytes) {
2306
+ const { Err: E, _int: int, _tlv: tlv } = DER;
2307
+ const data = abytes(bytes, void 0, "signature");
2308
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
2309
+ if (seqLeftBytes.length)
2310
+ throw new E("invalid signature: left bytes after parsing");
2311
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
2312
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
2313
+ if (sLeftBytes.length)
2314
+ throw new E("invalid signature: left bytes after parsing");
2315
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
2316
+ },
2317
+ hexFromSig(sig) {
2318
+ const { _tlv: tlv, _int: int } = DER;
2319
+ const rs = tlv.encode(2, int.encode(sig.r));
2320
+ const ss = tlv.encode(2, int.encode(sig.s));
2321
+ const seq = rs + ss;
2322
+ return tlv.encode(48, seq);
2323
+ }
2324
+ };
2325
+ var _0n5 = BigInt(0);
2326
+ var _1n6 = BigInt(1);
2327
+ var _2n4 = BigInt(2);
2328
+ var _3n2 = BigInt(3);
2329
+ var _4n2 = BigInt(4);
2330
+ function weierstrass(params, extraOpts = {}) {
2331
+ const validated = createCurveFields("weierstrass", params, extraOpts);
2332
+ const { Fp, Fn } = validated;
2333
+ let CURVE = validated.CURVE;
2334
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
2335
+ validateObject(extraOpts, {}, {
2336
+ allowInfinityPoint: "boolean",
2337
+ clearCofactor: "function",
2338
+ isTorsionFree: "function",
2339
+ fromBytes: "function",
2340
+ toBytes: "function",
2341
+ endo: "object"
2342
+ });
2343
+ const { endo } = extraOpts;
2344
+ if (endo) {
2345
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
2346
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
2347
+ }
2348
+ }
2349
+ const lengths = getWLengths(Fp, Fn);
2350
+ function assertCompressionIsSupported() {
2351
+ if (!Fp.isOdd)
2352
+ throw new Error("compression is not supported: Field does not have .isOdd()");
2353
+ }
2354
+ __name(assertCompressionIsSupported, "assertCompressionIsSupported");
2355
+ function pointToBytes(_c, point, isCompressed) {
2356
+ const { x, y } = point.toAffine();
2357
+ const bx = Fp.toBytes(x);
2358
+ abool(isCompressed, "isCompressed");
2359
+ if (isCompressed) {
2360
+ assertCompressionIsSupported();
2361
+ const hasEvenY = !Fp.isOdd(y);
2362
+ return concatBytes(pprefix(hasEvenY), bx);
2363
+ } else {
2364
+ return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
2365
+ }
2366
+ }
2367
+ __name(pointToBytes, "pointToBytes");
2368
+ function pointFromBytes(bytes) {
2369
+ abytes(bytes, void 0, "Point");
2370
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
2371
+ const length = bytes.length;
2372
+ const head = bytes[0];
2373
+ const tail = bytes.subarray(1);
2374
+ if (length === comp && (head === 2 || head === 3)) {
2375
+ const x = Fp.fromBytes(tail);
2376
+ if (!Fp.isValid(x))
2377
+ throw new Error("bad point: is not on curve, wrong x");
2378
+ const y2 = weierstrassEquation(x);
2379
+ let y;
2380
+ try {
2381
+ y = Fp.sqrt(y2);
2382
+ } catch (sqrtError) {
2383
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
2384
+ throw new Error("bad point: is not on curve, sqrt error" + err);
2385
+ }
2386
+ assertCompressionIsSupported();
2387
+ const evenY = Fp.isOdd(y);
2388
+ const evenH = (head & 1) === 1;
2389
+ if (evenH !== evenY)
2390
+ y = Fp.neg(y);
2391
+ return { x, y };
2392
+ } else if (length === uncomp && head === 4) {
2393
+ const L = Fp.BYTES;
2394
+ const x = Fp.fromBytes(tail.subarray(0, L));
2395
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
2396
+ if (!isValidXY(x, y))
2397
+ throw new Error("bad point: is not on curve");
2398
+ return { x, y };
2399
+ } else {
2400
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
2401
+ }
2402
+ }
2403
+ __name(pointFromBytes, "pointFromBytes");
2404
+ const encodePoint = extraOpts.toBytes || pointToBytes;
2405
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
2406
+ function weierstrassEquation(x) {
2407
+ const x2 = Fp.sqr(x);
2408
+ const x3 = Fp.mul(x2, x);
2409
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
2410
+ }
2411
+ __name(weierstrassEquation, "weierstrassEquation");
2412
+ function isValidXY(x, y) {
2413
+ const left = Fp.sqr(y);
2414
+ const right = weierstrassEquation(x);
2415
+ return Fp.eql(left, right);
2416
+ }
2417
+ __name(isValidXY, "isValidXY");
2418
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
2419
+ throw new Error("bad curve params: generator point");
2420
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
2421
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
2422
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
2423
+ throw new Error("bad curve params: a or b");
2424
+ function acoord(title, n, banZero = false) {
2425
+ if (!Fp.isValid(n) || banZero && Fp.is0(n))
2426
+ throw new Error(`bad point coordinate ${title}`);
2427
+ return n;
2428
+ }
2429
+ __name(acoord, "acoord");
2430
+ function aprjpoint(other) {
2431
+ if (!(other instanceof Point))
2432
+ throw new Error("Weierstrass Point expected");
2433
+ }
2434
+ __name(aprjpoint, "aprjpoint");
2435
+ function splitEndoScalarN(k) {
2436
+ if (!endo || !endo.basises)
2437
+ throw new Error("no endo");
2438
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
2439
+ }
2440
+ __name(splitEndoScalarN, "splitEndoScalarN");
2441
+ const toAffineMemo = memoized((p, iz) => {
2442
+ const { X, Y, Z } = p;
2443
+ if (Fp.eql(Z, Fp.ONE))
2444
+ return { x: X, y: Y };
2445
+ const is0 = p.is0();
2446
+ if (iz == null)
2447
+ iz = is0 ? Fp.ONE : Fp.inv(Z);
2448
+ const x = Fp.mul(X, iz);
2449
+ const y = Fp.mul(Y, iz);
2450
+ const zz = Fp.mul(Z, iz);
2451
+ if (is0)
2452
+ return { x: Fp.ZERO, y: Fp.ZERO };
2453
+ if (!Fp.eql(zz, Fp.ONE))
2454
+ throw new Error("invZ was invalid");
2455
+ return { x, y };
2456
+ });
2457
+ const assertValidMemo = memoized((p) => {
2458
+ if (p.is0()) {
2459
+ if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
2460
+ return;
2461
+ throw new Error("bad point: ZERO");
2462
+ }
2463
+ const { x, y } = p.toAffine();
2464
+ if (!Fp.isValid(x) || !Fp.isValid(y))
2465
+ throw new Error("bad point: x or y not field elements");
2466
+ if (!isValidXY(x, y))
2467
+ throw new Error("bad point: equation left != right");
2468
+ if (!p.isTorsionFree())
2469
+ throw new Error("bad point: not in prime-order subgroup");
2470
+ return true;
2471
+ });
2472
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
2473
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
2474
+ k1p = negateCt(k1neg, k1p);
2475
+ k2p = negateCt(k2neg, k2p);
2476
+ return k1p.add(k2p);
2477
+ }
2478
+ __name(finishEndo, "finishEndo");
2479
+ class Point {
2480
+ static {
2481
+ __name(this, "Point");
2482
+ }
2483
+ // base / generator point
2484
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
2485
+ // zero / infinity / identity point
2486
+ static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
2487
+ // 0, 1, 0
2488
+ // math field
2489
+ static Fp = Fp;
2490
+ // scalar field
2491
+ static Fn = Fn;
2492
+ X;
2493
+ Y;
2494
+ Z;
2495
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
2496
+ constructor(X, Y, Z) {
2497
+ this.X = acoord("x", X);
2498
+ this.Y = acoord("y", Y, true);
2499
+ this.Z = acoord("z", Z);
2500
+ Object.freeze(this);
2501
+ }
2502
+ static CURVE() {
2503
+ return CURVE;
2504
+ }
2505
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
2506
+ static fromAffine(p) {
2507
+ const { x, y } = p || {};
2508
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
2509
+ throw new Error("invalid affine point");
2510
+ if (p instanceof Point)
2511
+ throw new Error("projective point not allowed");
2512
+ if (Fp.is0(x) && Fp.is0(y))
2513
+ return Point.ZERO;
2514
+ return new Point(x, y, Fp.ONE);
2515
+ }
2516
+ static fromBytes(bytes) {
2517
+ const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
2518
+ P.assertValidity();
2519
+ return P;
2520
+ }
2521
+ static fromHex(hex) {
2522
+ return Point.fromBytes(hexToBytes(hex));
2523
+ }
2524
+ get x() {
2525
+ return this.toAffine().x;
2526
+ }
2527
+ get y() {
2528
+ return this.toAffine().y;
2529
+ }
2530
+ /**
2531
+ *
2532
+ * @param windowSize
2533
+ * @param isLazy true will defer table computation until the first multiplication
2534
+ * @returns
2535
+ */
2536
+ precompute(windowSize = 8, isLazy = true) {
2537
+ wnaf.createCache(this, windowSize);
2538
+ if (!isLazy)
2539
+ this.multiply(_3n2);
2540
+ return this;
2541
+ }
2542
+ // TODO: return `this`
2543
+ /** A point on curve is valid if it conforms to equation. */
2544
+ assertValidity() {
2545
+ assertValidMemo(this);
2546
+ }
2547
+ hasEvenY() {
2548
+ const { y } = this.toAffine();
2549
+ if (!Fp.isOdd)
2550
+ throw new Error("Field doesn't support isOdd");
2551
+ return !Fp.isOdd(y);
2552
+ }
2553
+ /** Compare one point to another. */
2554
+ equals(other) {
2555
+ aprjpoint(other);
2556
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2557
+ const { X: X2, Y: Y2, Z: Z2 } = other;
2558
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
2559
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
2560
+ return U1 && U2;
2561
+ }
2562
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
2563
+ negate() {
2564
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
2565
+ }
2566
+ // Renes-Costello-Batina exception-free doubling formula.
2567
+ // There is 30% faster Jacobian formula, but it is not complete.
2568
+ // https://eprint.iacr.org/2015/1060, algorithm 3
2569
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
2570
+ double() {
2571
+ const { a, b } = CURVE;
2572
+ const b3 = Fp.mul(b, _3n2);
2573
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2574
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
2575
+ let t0 = Fp.mul(X1, X1);
2576
+ let t1 = Fp.mul(Y1, Y1);
2577
+ let t2 = Fp.mul(Z1, Z1);
2578
+ let t3 = Fp.mul(X1, Y1);
2579
+ t3 = Fp.add(t3, t3);
2580
+ Z3 = Fp.mul(X1, Z1);
2581
+ Z3 = Fp.add(Z3, Z3);
2582
+ X3 = Fp.mul(a, Z3);
2583
+ Y3 = Fp.mul(b3, t2);
2584
+ Y3 = Fp.add(X3, Y3);
2585
+ X3 = Fp.sub(t1, Y3);
2586
+ Y3 = Fp.add(t1, Y3);
2587
+ Y3 = Fp.mul(X3, Y3);
2588
+ X3 = Fp.mul(t3, X3);
2589
+ Z3 = Fp.mul(b3, Z3);
2590
+ t2 = Fp.mul(a, t2);
2591
+ t3 = Fp.sub(t0, t2);
2592
+ t3 = Fp.mul(a, t3);
2593
+ t3 = Fp.add(t3, Z3);
2594
+ Z3 = Fp.add(t0, t0);
2595
+ t0 = Fp.add(Z3, t0);
2596
+ t0 = Fp.add(t0, t2);
2597
+ t0 = Fp.mul(t0, t3);
2598
+ Y3 = Fp.add(Y3, t0);
2599
+ t2 = Fp.mul(Y1, Z1);
2600
+ t2 = Fp.add(t2, t2);
2601
+ t0 = Fp.mul(t2, t3);
2602
+ X3 = Fp.sub(X3, t0);
2603
+ Z3 = Fp.mul(t2, t1);
2604
+ Z3 = Fp.add(Z3, Z3);
2605
+ Z3 = Fp.add(Z3, Z3);
2606
+ return new Point(X3, Y3, Z3);
2607
+ }
2608
+ // Renes-Costello-Batina exception-free addition formula.
2609
+ // There is 30% faster Jacobian formula, but it is not complete.
2610
+ // https://eprint.iacr.org/2015/1060, algorithm 1
2611
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
2612
+ add(other) {
2613
+ aprjpoint(other);
2614
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2615
+ const { X: X2, Y: Y2, Z: Z2 } = other;
2616
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
2617
+ const a = CURVE.a;
2618
+ const b3 = Fp.mul(CURVE.b, _3n2);
2619
+ let t0 = Fp.mul(X1, X2);
2620
+ let t1 = Fp.mul(Y1, Y2);
2621
+ let t2 = Fp.mul(Z1, Z2);
2622
+ let t3 = Fp.add(X1, Y1);
2623
+ let t4 = Fp.add(X2, Y2);
2624
+ t3 = Fp.mul(t3, t4);
2625
+ t4 = Fp.add(t0, t1);
2626
+ t3 = Fp.sub(t3, t4);
2627
+ t4 = Fp.add(X1, Z1);
2628
+ let t5 = Fp.add(X2, Z2);
2629
+ t4 = Fp.mul(t4, t5);
2630
+ t5 = Fp.add(t0, t2);
2631
+ t4 = Fp.sub(t4, t5);
2632
+ t5 = Fp.add(Y1, Z1);
2633
+ X3 = Fp.add(Y2, Z2);
2634
+ t5 = Fp.mul(t5, X3);
2635
+ X3 = Fp.add(t1, t2);
2636
+ t5 = Fp.sub(t5, X3);
2637
+ Z3 = Fp.mul(a, t4);
2638
+ X3 = Fp.mul(b3, t2);
2639
+ Z3 = Fp.add(X3, Z3);
2640
+ X3 = Fp.sub(t1, Z3);
2641
+ Z3 = Fp.add(t1, Z3);
2642
+ Y3 = Fp.mul(X3, Z3);
2643
+ t1 = Fp.add(t0, t0);
2644
+ t1 = Fp.add(t1, t0);
2645
+ t2 = Fp.mul(a, t2);
2646
+ t4 = Fp.mul(b3, t4);
2647
+ t1 = Fp.add(t1, t2);
2648
+ t2 = Fp.sub(t0, t2);
2649
+ t2 = Fp.mul(a, t2);
2650
+ t4 = Fp.add(t4, t2);
2651
+ t0 = Fp.mul(t1, t4);
2652
+ Y3 = Fp.add(Y3, t0);
2653
+ t0 = Fp.mul(t5, t4);
2654
+ X3 = Fp.mul(t3, X3);
2655
+ X3 = Fp.sub(X3, t0);
2656
+ t0 = Fp.mul(t3, t1);
2657
+ Z3 = Fp.mul(t5, Z3);
2658
+ Z3 = Fp.add(Z3, t0);
2659
+ return new Point(X3, Y3, Z3);
2660
+ }
2661
+ subtract(other) {
2662
+ return this.add(other.negate());
2663
+ }
2664
+ is0() {
2665
+ return this.equals(Point.ZERO);
2666
+ }
2667
+ /**
2668
+ * Constant time multiplication.
2669
+ * Uses wNAF method. Windowed method may be 10% faster,
2670
+ * but takes 2x longer to generate and consumes 2x memory.
2671
+ * Uses precomputes when available.
2672
+ * Uses endomorphism for Koblitz curves.
2673
+ * @param scalar by which the point would be multiplied
2674
+ * @returns New point
2675
+ */
2676
+ multiply(scalar) {
2677
+ const { endo: endo2 } = extraOpts;
2678
+ if (!Fn.isValidNot0(scalar))
2679
+ throw new Error("invalid scalar: out of range");
2680
+ let point, fake;
2681
+ const mul = /* @__PURE__ */ __name((n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p)), "mul");
2682
+ if (endo2) {
2683
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
2684
+ const { p: k1p, f: k1f } = mul(k1);
2685
+ const { p: k2p, f: k2f } = mul(k2);
2686
+ fake = k1f.add(k2f);
2687
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
2688
+ } else {
2689
+ const { p, f } = mul(scalar);
2690
+ point = p;
2691
+ fake = f;
2692
+ }
2693
+ return normalizeZ(Point, [point, fake])[0];
2694
+ }
2695
+ /**
2696
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
2697
+ * It's faster, but should only be used when you don't care about
2698
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
2699
+ */
2700
+ multiplyUnsafe(sc) {
2701
+ const { endo: endo2 } = extraOpts;
2702
+ const p = this;
2703
+ if (!Fn.isValid(sc))
2704
+ throw new Error("invalid scalar: out of range");
2705
+ if (sc === _0n5 || p.is0())
2706
+ return Point.ZERO;
2707
+ if (sc === _1n6)
2708
+ return p;
2709
+ if (wnaf.hasCache(this))
2710
+ return this.multiply(sc);
2711
+ if (endo2) {
2712
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
2713
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
2714
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
2715
+ } else {
2716
+ return wnaf.unsafe(p, sc);
2717
+ }
2718
+ }
2719
+ /**
2720
+ * Converts Projective point to affine (x, y) coordinates.
2721
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
2722
+ */
2723
+ toAffine(invertedZ) {
2724
+ return toAffineMemo(this, invertedZ);
2725
+ }
2726
+ /**
2727
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
2728
+ * Always torsion-free for cofactor=1 curves.
2729
+ */
2730
+ isTorsionFree() {
2731
+ const { isTorsionFree } = extraOpts;
2732
+ if (cofactor === _1n6)
2733
+ return true;
2734
+ if (isTorsionFree)
2735
+ return isTorsionFree(Point, this);
2736
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
2737
+ }
2738
+ clearCofactor() {
2739
+ const { clearCofactor } = extraOpts;
2740
+ if (cofactor === _1n6)
2741
+ return this;
2742
+ if (clearCofactor)
2743
+ return clearCofactor(Point, this);
2744
+ return this.multiplyUnsafe(cofactor);
2745
+ }
2746
+ isSmallOrder() {
2747
+ return this.multiplyUnsafe(cofactor).is0();
2748
+ }
2749
+ toBytes(isCompressed = true) {
2750
+ abool(isCompressed, "isCompressed");
2751
+ this.assertValidity();
2752
+ return encodePoint(Point, this, isCompressed);
2753
+ }
2754
+ toHex(isCompressed = true) {
2755
+ return bytesToHex(this.toBytes(isCompressed));
2756
+ }
2757
+ toString() {
2758
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
2759
+ }
2760
+ }
2761
+ const bits = Fn.BITS;
2762
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
2763
+ Point.BASE.precompute(8);
2764
+ return Point;
2765
+ }
2766
+ __name(weierstrass, "weierstrass");
2767
+ function pprefix(hasEvenY) {
2768
+ return Uint8Array.of(hasEvenY ? 2 : 3);
2769
+ }
2770
+ __name(pprefix, "pprefix");
2771
+ function getWLengths(Fp, Fn) {
2772
+ return {
2773
+ secretKey: Fn.BYTES,
2774
+ publicKey: 1 + Fp.BYTES,
2775
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
2776
+ publicKeyHasPrefix: true,
2777
+ signature: 2 * Fn.BYTES
2778
+ };
2779
+ }
2780
+ __name(getWLengths, "getWLengths");
2781
+ function ecdh(Point, ecdhOpts = {}) {
2782
+ const { Fn } = Point;
2783
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes;
2784
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
2785
+ function isValidSecretKey(secretKey) {
2786
+ try {
2787
+ const num = Fn.fromBytes(secretKey);
2788
+ return Fn.isValidNot0(num);
2789
+ } catch (error) {
2790
+ return false;
2791
+ }
2792
+ }
2793
+ __name(isValidSecretKey, "isValidSecretKey");
2794
+ function isValidPublicKey(publicKey2, isCompressed) {
2795
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
2796
+ try {
2797
+ const l = publicKey2.length;
2798
+ if (isCompressed === true && l !== comp)
2799
+ return false;
2800
+ if (isCompressed === false && l !== publicKeyUncompressed)
2801
+ return false;
2802
+ return !!Point.fromBytes(publicKey2);
2803
+ } catch (error) {
2804
+ return false;
2805
+ }
2806
+ }
2807
+ __name(isValidPublicKey, "isValidPublicKey");
2808
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
2809
+ return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
2810
+ }
2811
+ __name(randomSecretKey, "randomSecretKey");
2812
+ function getPublicKey(secretKey, isCompressed = true) {
2813
+ return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
2814
+ }
2815
+ __name(getPublicKey, "getPublicKey");
2816
+ function isProbPub(item) {
2817
+ const { secretKey, publicKey: publicKey2, publicKeyUncompressed } = lengths;
2818
+ if (!isBytes(item))
2819
+ return void 0;
2820
+ if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey2)
2821
+ return void 0;
2822
+ const l = abytes(item, void 0, "key").length;
2823
+ return l === publicKey2 || l === publicKeyUncompressed;
2824
+ }
2825
+ __name(isProbPub, "isProbPub");
2826
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
2827
+ if (isProbPub(secretKeyA) === true)
2828
+ throw new Error("first arg must be private key");
2829
+ if (isProbPub(publicKeyB) === false)
2830
+ throw new Error("second arg must be public key");
2831
+ const s = Fn.fromBytes(secretKeyA);
2832
+ const b = Point.fromBytes(publicKeyB);
2833
+ return b.multiply(s).toBytes(isCompressed);
2834
+ }
2835
+ __name(getSharedSecret, "getSharedSecret");
2836
+ const utils2 = {
2837
+ isValidSecretKey,
2838
+ isValidPublicKey,
2839
+ randomSecretKey
2840
+ };
2841
+ const keygen = createKeygen(randomSecretKey, getPublicKey);
2842
+ return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils: utils2, lengths });
2843
+ }
2844
+ __name(ecdh, "ecdh");
2845
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
2846
+ ahash(hash);
2847
+ validateObject(ecdsaOpts, {}, {
2848
+ hmac: "function",
2849
+ lowS: "boolean",
2850
+ randomBytes: "function",
2851
+ bits2int: "function",
2852
+ bits2int_modN: "function"
2853
+ });
2854
+ ecdsaOpts = Object.assign({}, ecdsaOpts);
2855
+ const randomBytes2 = ecdsaOpts.randomBytes || randomBytes;
2856
+ const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
2857
+ const { Fp, Fn } = Point;
2858
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
2859
+ const { keygen, getPublicKey, getSharedSecret, utils: utils2, lengths } = ecdh(Point, ecdsaOpts);
2860
+ const defaultSigOpts = {
2861
+ prehash: true,
2862
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
2863
+ format: "compact",
2864
+ extraEntropy: false
2865
+ };
2866
+ const hasLargeCofactor = CURVE_ORDER * _2n4 < Fp.ORDER;
2867
+ function isBiggerThanHalfOrder(number) {
2868
+ const HALF = CURVE_ORDER >> _1n6;
2869
+ return number > HALF;
2870
+ }
2871
+ __name(isBiggerThanHalfOrder, "isBiggerThanHalfOrder");
2872
+ function validateRS(title, num) {
2873
+ if (!Fn.isValidNot0(num))
2874
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
2875
+ return num;
2876
+ }
2877
+ __name(validateRS, "validateRS");
2878
+ function assertSmallCofactor() {
2879
+ if (hasLargeCofactor)
2880
+ throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
2881
+ }
2882
+ __name(assertSmallCofactor, "assertSmallCofactor");
2883
+ function validateSigLength(bytes, format) {
2884
+ validateSigFormat(format);
2885
+ const size = lengths.signature;
2886
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
2887
+ return abytes(bytes, sizer);
2888
+ }
2889
+ __name(validateSigLength, "validateSigLength");
2890
+ class Signature {
2891
+ static {
2892
+ __name(this, "Signature");
2893
+ }
2894
+ r;
2895
+ s;
2896
+ recovery;
2897
+ constructor(r, s, recovery) {
2898
+ this.r = validateRS("r", r);
2899
+ this.s = validateRS("s", s);
2900
+ if (recovery != null) {
2901
+ assertSmallCofactor();
2902
+ if (![0, 1, 2, 3].includes(recovery))
2903
+ throw new Error("invalid recovery id");
2904
+ this.recovery = recovery;
2905
+ }
2906
+ Object.freeze(this);
2907
+ }
2908
+ static fromBytes(bytes, format = defaultSigOpts.format) {
2909
+ validateSigLength(bytes, format);
2910
+ let recid;
2911
+ if (format === "der") {
2912
+ const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
2913
+ return new Signature(r2, s2);
2914
+ }
2915
+ if (format === "recovered") {
2916
+ recid = bytes[0];
2917
+ format = "compact";
2918
+ bytes = bytes.subarray(1);
2919
+ }
2920
+ const L = lengths.signature / 2;
2921
+ const r = bytes.subarray(0, L);
2922
+ const s = bytes.subarray(L, L * 2);
2923
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
2924
+ }
2925
+ static fromHex(hex, format) {
2926
+ return this.fromBytes(hexToBytes(hex), format);
2927
+ }
2928
+ assertRecovery() {
2929
+ const { recovery } = this;
2930
+ if (recovery == null)
2931
+ throw new Error("invalid recovery id: must be present");
2932
+ return recovery;
2933
+ }
2934
+ addRecoveryBit(recovery) {
2935
+ return new Signature(this.r, this.s, recovery);
2936
+ }
2937
+ recoverPublicKey(messageHash) {
2938
+ const { r, s } = this;
2939
+ const recovery = this.assertRecovery();
2940
+ const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;
2941
+ if (!Fp.isValid(radj))
2942
+ throw new Error("invalid recovery id: sig.r+curve.n != R.x");
2943
+ const x = Fp.toBytes(radj);
2944
+ const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
2945
+ const ir = Fn.inv(radj);
2946
+ const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
2947
+ const u1 = Fn.create(-h * ir);
2948
+ const u2 = Fn.create(s * ir);
2949
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
2950
+ if (Q.is0())
2951
+ throw new Error("invalid recovery: point at infinify");
2952
+ Q.assertValidity();
2953
+ return Q;
2954
+ }
2955
+ // Signatures should be low-s, to prevent malleability.
2956
+ hasHighS() {
2957
+ return isBiggerThanHalfOrder(this.s);
2958
+ }
2959
+ toBytes(format = defaultSigOpts.format) {
2960
+ validateSigFormat(format);
2961
+ if (format === "der")
2962
+ return hexToBytes(DER.hexFromSig(this));
2963
+ const { r, s } = this;
2964
+ const rb = Fn.toBytes(r);
2965
+ const sb = Fn.toBytes(s);
2966
+ if (format === "recovered") {
2967
+ assertSmallCofactor();
2968
+ return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
2969
+ }
2970
+ return concatBytes(rb, sb);
2971
+ }
2972
+ toHex(format) {
2973
+ return bytesToHex(this.toBytes(format));
2974
+ }
2975
+ }
2976
+ const bits2int = ecdsaOpts.bits2int || /* @__PURE__ */ __name(function bits2int_def(bytes) {
2977
+ if (bytes.length > 8192)
2978
+ throw new Error("input is too large");
2979
+ const num = bytesToNumberBE(bytes);
2980
+ const delta = bytes.length * 8 - fnBits;
2981
+ return delta > 0 ? num >> BigInt(delta) : num;
2982
+ }, "bits2int_def");
2983
+ const bits2int_modN = ecdsaOpts.bits2int_modN || /* @__PURE__ */ __name(function bits2int_modN_def(bytes) {
2984
+ return Fn.create(bits2int(bytes));
2985
+ }, "bits2int_modN_def");
2986
+ const ORDER_MASK = bitMask(fnBits);
2987
+ function int2octets(num) {
2988
+ aInRange("num < 2^" + fnBits, num, _0n5, ORDER_MASK);
2989
+ return Fn.toBytes(num);
2990
+ }
2991
+ __name(int2octets, "int2octets");
2992
+ function validateMsgAndHash(message, prehash) {
2993
+ abytes(message, void 0, "message");
2994
+ return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
2995
+ }
2996
+ __name(validateMsgAndHash, "validateMsgAndHash");
2997
+ function prepSig(message, secretKey, opts) {
2998
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
2999
+ message = validateMsgAndHash(message, prehash);
3000
+ const h1int = bits2int_modN(message);
3001
+ const d = Fn.fromBytes(secretKey);
3002
+ if (!Fn.isValidNot0(d))
3003
+ throw new Error("invalid private key");
3004
+ const seedArgs = [int2octets(d), int2octets(h1int)];
3005
+ if (extraEntropy != null && extraEntropy !== false) {
3006
+ const e = extraEntropy === true ? randomBytes2(lengths.secretKey) : extraEntropy;
3007
+ seedArgs.push(abytes(e, void 0, "extraEntropy"));
3008
+ }
3009
+ const seed = concatBytes(...seedArgs);
3010
+ const m = h1int;
3011
+ function k2sig(kBytes) {
3012
+ const k = bits2int(kBytes);
3013
+ if (!Fn.isValidNot0(k))
3014
+ return;
3015
+ const ik = Fn.inv(k);
3016
+ const q = Point.BASE.multiply(k).toAffine();
3017
+ const r = Fn.create(q.x);
3018
+ if (r === _0n5)
3019
+ return;
3020
+ const s = Fn.create(ik * Fn.create(m + r * d));
3021
+ if (s === _0n5)
3022
+ return;
3023
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n6);
3024
+ let normS = s;
3025
+ if (lowS && isBiggerThanHalfOrder(s)) {
3026
+ normS = Fn.neg(s);
3027
+ recovery ^= 1;
3028
+ }
3029
+ return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
3030
+ }
3031
+ __name(k2sig, "k2sig");
3032
+ return { seed, k2sig };
3033
+ }
3034
+ __name(prepSig, "prepSig");
3035
+ function sign(message, secretKey, opts = {}) {
3036
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
3037
+ const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
3038
+ const sig = drbg(seed, k2sig);
3039
+ return sig.toBytes(opts.format);
3040
+ }
3041
+ __name(sign, "sign");
3042
+ function verify(signature, message, publicKey2, opts = {}) {
3043
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
3044
+ publicKey2 = abytes(publicKey2, void 0, "publicKey");
3045
+ message = validateMsgAndHash(message, prehash);
3046
+ if (!isBytes(signature)) {
3047
+ const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
3048
+ throw new Error("verify expects Uint8Array signature" + end);
3049
+ }
3050
+ validateSigLength(signature, format);
3051
+ try {
3052
+ const sig = Signature.fromBytes(signature, format);
3053
+ const P = Point.fromBytes(publicKey2);
3054
+ if (lowS && sig.hasHighS())
3055
+ return false;
3056
+ const { r, s } = sig;
3057
+ const h = bits2int_modN(message);
3058
+ const is = Fn.inv(s);
3059
+ const u1 = Fn.create(h * is);
3060
+ const u2 = Fn.create(r * is);
3061
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
3062
+ if (R.is0())
3063
+ return false;
3064
+ const v = Fn.create(R.x);
3065
+ return v === r;
3066
+ } catch (e) {
3067
+ return false;
3068
+ }
3069
+ }
3070
+ __name(verify, "verify");
3071
+ function recoverPublicKey(signature, message, opts = {}) {
3072
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
3073
+ message = validateMsgAndHash(message, prehash);
3074
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
3075
+ }
3076
+ __name(recoverPublicKey, "recoverPublicKey");
3077
+ return Object.freeze({
3078
+ keygen,
3079
+ getPublicKey,
3080
+ getSharedSecret,
3081
+ utils: utils2,
3082
+ lengths,
3083
+ Point,
3084
+ sign,
3085
+ verify,
3086
+ recoverPublicKey,
3087
+ Signature,
3088
+ hash
3089
+ });
3090
+ }
3091
+ __name(ecdsa, "ecdsa");
3092
+
3093
+ // ../../node_modules/@noble/curves/secp256k1.js
3094
+ var secp256k1_CURVE = {
3095
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
3096
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
3097
+ h: BigInt(1),
3098
+ a: BigInt(0),
3099
+ b: BigInt(7),
3100
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
3101
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
3102
+ };
3103
+ var secp256k1_ENDO = {
3104
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
3105
+ basises: [
3106
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
3107
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
3108
+ ]
3109
+ };
3110
+ var _2n5 = /* @__PURE__ */ BigInt(2);
3111
+ function sqrtMod(y) {
3112
+ const P = secp256k1_CURVE.p;
3113
+ const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
3114
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
3115
+ const b2 = y * y * y % P;
3116
+ const b3 = b2 * b2 * y % P;
3117
+ const b6 = pow2(b3, _3n3, P) * b3 % P;
3118
+ const b9 = pow2(b6, _3n3, P) * b3 % P;
3119
+ const b11 = pow2(b9, _2n5, P) * b2 % P;
3120
+ const b22 = pow2(b11, _11n, P) * b11 % P;
3121
+ const b44 = pow2(b22, _22n, P) * b22 % P;
3122
+ const b88 = pow2(b44, _44n, P) * b44 % P;
3123
+ const b176 = pow2(b88, _88n, P) * b88 % P;
3124
+ const b220 = pow2(b176, _44n, P) * b44 % P;
3125
+ const b223 = pow2(b220, _3n3, P) * b3 % P;
3126
+ const t1 = pow2(b223, _23n, P) * b22 % P;
3127
+ const t2 = pow2(t1, _6n, P) * b2 % P;
3128
+ const root = pow2(t2, _2n5, P);
3129
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
3130
+ throw new Error("Cannot find square root");
3131
+ return root;
3132
+ }
3133
+ __name(sqrtMod, "sqrtMod");
3134
+ var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
3135
+ var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
3136
+ Fp: Fpk1,
3137
+ endo: secp256k1_ENDO
3138
+ });
3139
+ var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256);
3140
+
2480
3141
  // ../utils/node_modules/base58-js/base58_chars.js
2481
3142
  var base58_chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
2482
3143
  var base58_chars_default = base58_chars;
@@ -2702,6 +3363,32 @@ var near = (() => {
2702
3363
  }
2703
3364
  }
2704
3365
  __name(fromBase64, "fromBase64");
3366
+ var UNIT_DECIMALS = {
3367
+ near: 24,
3368
+ tgas: 12,
3369
+ ggas: 9,
3370
+ gas: 0,
3371
+ yoctonear: 0
3372
+ };
3373
+ function scaleDecimal(amount, shift) {
3374
+ const [whole, frac = ""] = amount.split(".");
3375
+ if (shift >= 0) {
3376
+ const padded = frac.padEnd(shift, "0").slice(0, shift);
3377
+ const extra = frac.length > shift ? frac.slice(shift) : "";
3378
+ if (extra && BigInt(extra) !== 0n) {
3379
+ throw new Error(`Precision loss: "${amount}" has more than ${shift} decimal places`);
3380
+ }
3381
+ return BigInt(whole + padded).toString();
3382
+ }
3383
+ const divisor = 10n ** BigInt(-shift);
3384
+ const bigVal = BigInt(whole);
3385
+ const intPart = bigVal / divisor;
3386
+ const remainder = bigVal % divisor;
3387
+ if (remainder === 0n) return intPart.toString();
3388
+ const fracStr = remainder.toString().padStart(-shift, "0").replace(/0+$/, "");
3389
+ return `${intPart}.${fracStr}`;
3390
+ }
3391
+ __name(scaleDecimal, "scaleDecimal");
2705
3392
  function convertUnit(s, ...args) {
2706
3393
  if (Array.isArray(s)) {
2707
3394
  s = s.reduce((acc, part, i) => {
@@ -2714,25 +3401,15 @@ var near = (() => {
2714
3401
  const amount = match[1].replace(/[_,]/g, "");
2715
3402
  const unitPart = match[2];
2716
3403
  if (unitPart) {
2717
- switch (unitPart.toLowerCase()) {
2718
- case "near":
2719
- return big_default(amount).mul(big_default(10).pow(24)).toFixed(0);
2720
- case "tgas":
2721
- return big_default(amount).mul(big_default(10).pow(12)).toFixed(0);
2722
- case "ggas":
2723
- return big_default(amount).mul(big_default(10).pow(9)).toFixed(0);
2724
- case "gas":
2725
- case "yoctonear":
2726
- return big_default(amount).toFixed(0);
2727
- default:
2728
- throw new Error(`Unknown unit: ${unitPart}`);
2729
- }
3404
+ const decimals = UNIT_DECIMALS[unitPart.toLowerCase()];
3405
+ if (decimals === void 0) throw new Error(`Unknown unit: ${unitPart}`);
3406
+ return scaleDecimal(amount, decimals);
2730
3407
  } else {
2731
- return big_default(amount).toFixed(0);
3408
+ return scaleDecimal(amount, 0);
2732
3409
  }
2733
3410
  }
2734
3411
  }
2735
- return big_default(`${s}`).toFixed(0);
3412
+ return scaleDecimal(`${s}`, 0);
2736
3413
  }
2737
3414
  __name(convertUnit, "convertUnit");
2738
3415
  function lsSet(key, value) {
@@ -2774,35 +3451,61 @@ var near = (() => {
2774
3451
  }
2775
3452
  __name(parseJsonFromBytes, "parseJsonFromBytes");
2776
3453
  function canSignWithLAK(actions2) {
2777
- return actions2.length === 1 && actions2[0].type === "FunctionCall" && big_default(actions2[0]?.deposit ?? "0").eq(0);
3454
+ return actions2.length === 1 && actions2[0].type === "FunctionCall" && BigInt(actions2[0]?.deposit ?? "0") === 0n;
2778
3455
  }
2779
3456
  __name(canSignWithLAK, "canSignWithLAK");
2780
3457
 
2781
3458
  // ../utils/src/crypto.ts
3459
+ function curveFromKey(key) {
3460
+ if (!key.includes(":")) return "ed25519";
3461
+ const curve = key.split(":")[0];
3462
+ if (curve === "ed25519" || curve === "secp256k1") return curve;
3463
+ throw new Error(`Unsupported curve: ${curve}`);
3464
+ }
3465
+ __name(curveFromKey, "curveFromKey");
2782
3466
  var keyFromString = /* @__PURE__ */ __name((key) => base58_to_binary_default(
2783
3467
  key.includes(":") ? (() => {
2784
3468
  const [curve, keyPart] = key.split(":");
2785
- if (curve !== "ed25519") {
3469
+ if (curve !== "ed25519" && curve !== "secp256k1") {
2786
3470
  throw new Error(`Unsupported curve: ${curve}`);
2787
3471
  }
2788
3472
  return keyPart;
2789
3473
  })() : key
2790
3474
  ), "keyFromString");
2791
- var keyToString = /* @__PURE__ */ __name((key) => `ed25519:${binary_to_base58_default(key)}`, "keyToString");
3475
+ var keyToString = /* @__PURE__ */ __name((key, curve = "ed25519") => `${curve}:${binary_to_base58_default(key)}`, "keyToString");
2792
3476
  function publicKeyFromPrivate(privateKey) {
3477
+ const curve = curveFromKey(privateKey);
3478
+ if (curve === "secp256k1") {
3479
+ const secret2 = keyFromString(privateKey);
3480
+ const fullPk = secp256k1.getPublicKey(secret2, false);
3481
+ const publicKey3 = fullPk.slice(1);
3482
+ return keyToString(publicKey3, "secp256k1");
3483
+ }
2793
3484
  const secret = keyFromString(privateKey).slice(0, 32);
2794
3485
  const publicKey2 = ed25519.getPublicKey(secret);
2795
3486
  return keyToString(publicKey2);
2796
3487
  }
2797
3488
  __name(publicKeyFromPrivate, "publicKeyFromPrivate");
2798
- function privateKeyFromRandom() {
2799
- const privateKey = crypto.getRandomValues(new Uint8Array(64));
2800
- return keyToString(privateKey);
3489
+ function privateKeyFromRandom(curve = "ed25519") {
3490
+ const size = curve === "secp256k1" ? 32 : 64;
3491
+ const privateKey = crypto.getRandomValues(new Uint8Array(size));
3492
+ return keyToString(privateKey, curve);
2801
3493
  }
2802
3494
  __name(privateKeyFromRandom, "privateKeyFromRandom");
2803
3495
  function signHash(hashBytes, privateKey, opts) {
2804
- const secret = keyFromString(privateKey).slice(0, 32);
2805
- const signature = ed25519.sign(hashBytes, secret);
3496
+ const curve = curveFromKey(privateKey);
3497
+ let signature;
3498
+ if (curve === "secp256k1") {
3499
+ const secret = keyFromString(privateKey);
3500
+ const raw = secp256k1.sign(hashBytes, secret, { prehash: false, format: "recovered" });
3501
+ signature = new Uint8Array(65);
3502
+ signature.set(raw.slice(1, 33), 0);
3503
+ signature.set(raw.slice(33, 65), 32);
3504
+ signature[64] = raw[0];
3505
+ } else {
3506
+ const secret = keyFromString(privateKey).slice(0, 32);
3507
+ signature = ed25519.sign(hashBytes, secret);
3508
+ }
2806
3509
  if (opts?.returnBase58) {
2807
3510
  return binary_to_base58_default(signature);
2808
3511
  }
@@ -2815,533 +3518,275 @@ var near = (() => {
2815
3518
  }
2816
3519
  __name(signBytes, "signBytes");
2817
3520
 
2818
- // ../../node_modules/borsh/lib/esm/types.js
2819
- var integers = ["u8", "u16", "u32", "u64", "u128", "i8", "i16", "i32", "i64", "i128", "f32", "f64"];
2820
-
2821
- // ../../node_modules/borsh/lib/esm/buffer.js
2822
- var EncodeBuffer = (
2823
- /** @class */
2824
- function() {
2825
- function EncodeBuffer2() {
2826
- this.offset = 0;
2827
- this.buffer_size = 256;
2828
- this.buffer = new ArrayBuffer(this.buffer_size);
2829
- this.view = new DataView(this.buffer);
2830
- }
2831
- __name(EncodeBuffer2, "EncodeBuffer");
2832
- EncodeBuffer2.prototype.resize_if_necessary = function(needed_space) {
2833
- if (this.buffer_size - this.offset < needed_space) {
2834
- this.buffer_size = Math.max(this.buffer_size * 2, this.buffer_size + needed_space);
2835
- var new_buffer = new ArrayBuffer(this.buffer_size);
2836
- new Uint8Array(new_buffer).set(new Uint8Array(this.buffer));
2837
- this.buffer = new_buffer;
2838
- this.view = new DataView(new_buffer);
2839
- }
2840
- };
2841
- EncodeBuffer2.prototype.get_used_buffer = function() {
2842
- return new Uint8Array(this.buffer).slice(0, this.offset);
2843
- };
2844
- EncodeBuffer2.prototype.store_value = function(value, type) {
2845
- var bSize = type.substring(1);
2846
- var size = parseInt(bSize) / 8;
2847
- this.resize_if_necessary(size);
2848
- var toCall = type[0] === "f" ? "setFloat".concat(bSize) : type[0] === "i" ? "setInt".concat(bSize) : "setUint".concat(bSize);
2849
- this.view[toCall](this.offset, value, true);
2850
- this.offset += size;
2851
- };
2852
- EncodeBuffer2.prototype.store_bytes = function(from) {
2853
- this.resize_if_necessary(from.length);
2854
- new Uint8Array(this.buffer).set(new Uint8Array(from), this.offset);
2855
- this.offset += from.length;
2856
- };
2857
- return EncodeBuffer2;
2858
- }()
2859
- );
2860
- var DecodeBuffer = (
2861
- /** @class */
2862
- function() {
2863
- function DecodeBuffer2(buf) {
2864
- this.offset = 0;
2865
- this.buffer_size = buf.length;
2866
- this.buffer = new ArrayBuffer(buf.length);
2867
- new Uint8Array(this.buffer).set(buf);
2868
- this.view = new DataView(this.buffer);
2869
- }
2870
- __name(DecodeBuffer2, "DecodeBuffer");
2871
- DecodeBuffer2.prototype.assert_enough_buffer = function(size) {
2872
- if (this.offset + size > this.buffer.byteLength) {
2873
- throw new Error("Error in schema, the buffer is smaller than expected");
2874
- }
2875
- };
2876
- DecodeBuffer2.prototype.consume_value = function(type) {
2877
- var bSize = type.substring(1);
2878
- var size = parseInt(bSize) / 8;
2879
- this.assert_enough_buffer(size);
2880
- var toCall = type[0] === "f" ? "getFloat".concat(bSize) : type[0] === "i" ? "getInt".concat(bSize) : "getUint".concat(bSize);
2881
- var ret = this.view[toCall](this.offset, true);
2882
- this.offset += size;
2883
- return ret;
2884
- };
2885
- DecodeBuffer2.prototype.consume_bytes = function(size) {
2886
- this.assert_enough_buffer(size);
2887
- var ret = this.buffer.slice(this.offset, this.offset + size);
2888
- this.offset += size;
2889
- return ret;
2890
- };
2891
- return DecodeBuffer2;
2892
- }()
2893
- );
2894
-
2895
- // ../../node_modules/borsh/lib/esm/utils.js
2896
- var __extends = /* @__PURE__ */ function() {
2897
- var extendStatics = /* @__PURE__ */ __name(function(d, b) {
2898
- extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
2899
- d2.__proto__ = b2;
2900
- } || function(d2, b2) {
2901
- for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
2902
- };
2903
- return extendStatics(d, b);
2904
- }, "extendStatics");
2905
- return function(d, b) {
2906
- if (typeof b !== "function" && b !== null)
2907
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
2908
- extendStatics(d, b);
2909
- function __() {
2910
- this.constructor = d;
2911
- }
2912
- __name(__, "__");
2913
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2914
- };
2915
- }();
2916
- function isArrayLike(value) {
2917
- 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);
2918
- }
2919
- __name(isArrayLike, "isArrayLike");
2920
- function expect_type(value, type, fieldPath) {
2921
- if (typeof value !== type) {
2922
- throw new Error("Expected ".concat(type, " not ").concat(typeof value, "(").concat(value, ") at ").concat(fieldPath.join(".")));
3521
+ // ../borsh/src/index.ts
3522
+ var EncodeBuffer = class {
3523
+ static {
3524
+ __name(this, "EncodeBuffer");
3525
+ }
3526
+ offset = 0;
3527
+ bufferSize = 256;
3528
+ buffer = new ArrayBuffer(this.bufferSize);
3529
+ view = new DataView(this.buffer);
3530
+ resize(needed) {
3531
+ if (this.bufferSize - this.offset < needed) {
3532
+ this.bufferSize = Math.max(this.bufferSize * 2, this.bufferSize + needed);
3533
+ const next = new ArrayBuffer(this.bufferSize);
3534
+ new Uint8Array(next).set(new Uint8Array(this.buffer));
3535
+ this.buffer = next;
3536
+ this.view = new DataView(next);
3537
+ }
2923
3538
  }
2924
- }
2925
- __name(expect_type, "expect_type");
2926
- function expect_bigint(value, fieldPath) {
2927
- var basicType = ["number", "string", "bigint", "boolean"].includes(typeof value);
2928
- var strObject = typeof value === "object" && value !== null && "toString" in value;
2929
- if (!basicType && !strObject) {
2930
- throw new Error("Expected bigint, number, boolean or string not ".concat(typeof value, "(").concat(value, ") at ").concat(fieldPath.join(".")));
3539
+ storeU8(v) {
3540
+ this.resize(1);
3541
+ this.view.setUint8(this.offset, v);
3542
+ this.offset += 1;
2931
3543
  }
2932
- }
2933
- __name(expect_bigint, "expect_bigint");
2934
- function expect_same_size(length, expected, fieldPath) {
2935
- if (length !== expected) {
2936
- throw new Error("Array length ".concat(length, " does not match schema length ").concat(expected, " at ").concat(fieldPath.join(".")));
3544
+ storeU16(v) {
3545
+ this.resize(2);
3546
+ this.view.setUint16(this.offset, v, true);
3547
+ this.offset += 2;
2937
3548
  }
2938
- }
2939
- __name(expect_same_size, "expect_same_size");
2940
- function expect_enum(value, fieldPath) {
2941
- if (typeof value !== "object" || value === null) {
2942
- throw new Error("Expected object not ".concat(typeof value, "(").concat(value, ") at ").concat(fieldPath.join(".")));
3549
+ storeU32(v) {
3550
+ this.resize(4);
3551
+ this.view.setUint32(this.offset, v, true);
3552
+ this.offset += 4;
2943
3553
  }
2944
- }
2945
- __name(expect_enum, "expect_enum");
2946
- var VALID_STRING_TYPES = integers.concat(["bool", "string"]);
2947
- var VALID_OBJECT_KEYS = ["option", "enum", "array", "set", "map", "struct"];
2948
- var ErrorSchema = (
2949
- /** @class */
2950
- function(_super) {
2951
- __extends(ErrorSchema2, _super);
2952
- function ErrorSchema2(schema, expected) {
2953
- var message = "Invalid schema: ".concat(JSON.stringify(schema), " expected ").concat(expected);
2954
- return _super.call(this, message) || this;
2955
- }
2956
- __name(ErrorSchema2, "ErrorSchema");
2957
- return ErrorSchema2;
2958
- }(Error)
2959
- );
2960
- function validate_schema(schema) {
2961
- if (typeof schema === "string" && VALID_STRING_TYPES.includes(schema)) {
2962
- return;
3554
+ storeBytes(from) {
3555
+ this.resize(from.length);
3556
+ new Uint8Array(this.buffer).set(from, this.offset);
3557
+ this.offset += from.length;
2963
3558
  }
2964
- if (schema && typeof schema === "object") {
2965
- var keys = Object.keys(schema);
2966
- if (keys.length === 1 && VALID_OBJECT_KEYS.includes(keys[0])) {
2967
- var key = keys[0];
2968
- if (key === "option")
2969
- return validate_schema(schema[key]);
2970
- if (key === "enum")
2971
- return validate_enum_schema(schema[key]);
2972
- if (key === "array")
2973
- return validate_array_schema(schema[key]);
2974
- if (key === "set")
2975
- return validate_schema(schema[key]);
2976
- if (key === "map")
2977
- return validate_map_schema(schema[key]);
2978
- if (key === "struct")
2979
- return validate_struct_schema(schema[key]);
2980
- }
2981
- }
2982
- throw new ErrorSchema(schema, VALID_OBJECT_KEYS.join(", ") + " or " + VALID_STRING_TYPES.join(", "));
2983
- }
2984
- __name(validate_schema, "validate_schema");
2985
- function validate_enum_schema(schema) {
2986
- if (!Array.isArray(schema))
2987
- throw new ErrorSchema(schema, "Array");
2988
- for (var _i = 0, schema_1 = schema; _i < schema_1.length; _i++) {
2989
- var sch = schema_1[_i];
2990
- if (typeof sch !== "object" || !("struct" in sch)) {
2991
- throw new Error('Missing "struct" key in enum schema');
2992
- }
2993
- if (typeof sch.struct !== "object" || Object.keys(sch.struct).length !== 1) {
2994
- throw new Error('The "struct" in each enum must have a single key');
3559
+ result() {
3560
+ return new Uint8Array(this.buffer).slice(0, this.offset);
3561
+ }
3562
+ };
3563
+ var DecodeBuffer = class {
3564
+ static {
3565
+ __name(this, "DecodeBuffer");
3566
+ }
3567
+ offset = 0;
3568
+ view;
3569
+ bytes;
3570
+ constructor(buf) {
3571
+ const ab = new ArrayBuffer(buf.length);
3572
+ new Uint8Array(ab).set(buf);
3573
+ this.view = new DataView(ab);
3574
+ this.bytes = new Uint8Array(ab);
3575
+ }
3576
+ assert(size) {
3577
+ if (this.offset + size > this.bytes.length) {
3578
+ throw new Error("Borsh: buffer overrun");
2995
3579
  }
2996
- validate_schema({ struct: sch.struct });
2997
3580
  }
3581
+ readU8() {
3582
+ this.assert(1);
3583
+ const v = this.view.getUint8(this.offset);
3584
+ this.offset += 1;
3585
+ return v;
3586
+ }
3587
+ readU16() {
3588
+ this.assert(2);
3589
+ const v = this.view.getUint16(this.offset, true);
3590
+ this.offset += 2;
3591
+ return v;
3592
+ }
3593
+ readU32() {
3594
+ this.assert(4);
3595
+ const v = this.view.getUint32(this.offset, true);
3596
+ this.offset += 4;
3597
+ return v;
3598
+ }
3599
+ readBytes(len) {
3600
+ this.assert(len);
3601
+ const slice = this.bytes.slice(this.offset, this.offset + len);
3602
+ this.offset += len;
3603
+ return slice;
3604
+ }
3605
+ };
3606
+ function encodeBigint(buf, value, byteLen) {
3607
+ const out = new Uint8Array(byteLen);
3608
+ let v = value;
3609
+ for (let i = 0; i < byteLen; i++) {
3610
+ out[i] = Number(v & 0xffn);
3611
+ v >>= 8n;
3612
+ }
3613
+ buf.storeBytes(out);
2998
3614
  }
2999
- __name(validate_enum_schema, "validate_enum_schema");
3000
- function validate_array_schema(schema) {
3001
- if (typeof schema !== "object")
3002
- throw new ErrorSchema(schema, "{ type, len? }");
3003
- if (schema.len && typeof schema.len !== "number") {
3004
- throw new Error("Invalid schema: ".concat(schema));
3005
- }
3006
- if ("type" in schema)
3007
- return validate_schema(schema.type);
3008
- throw new ErrorSchema(schema, "{ type, len? }");
3615
+ __name(encodeBigint, "encodeBigint");
3616
+ function decodeBigint(buf, byteLen) {
3617
+ const bytes = buf.readBytes(byteLen);
3618
+ const hex = bytes.reduceRight((r, x) => r + x.toString(16).padStart(2, "0"), "");
3619
+ return BigInt("0x" + hex);
3009
3620
  }
3010
- __name(validate_array_schema, "validate_array_schema");
3011
- function validate_map_schema(schema) {
3012
- if (typeof schema === "object" && "key" in schema && "value" in schema) {
3013
- validate_schema(schema.key);
3014
- validate_schema(schema.value);
3015
- } else {
3016
- throw new ErrorSchema(schema, "{ key, value }");
3621
+ __name(decodeBigint, "decodeBigint");
3622
+ function utf8Encode(str) {
3623
+ const bytes = [];
3624
+ for (let i = 0; i < str.length; i++) {
3625
+ let c = str.charCodeAt(i);
3626
+ if (c < 128) {
3627
+ bytes.push(c);
3628
+ } else if (c < 2048) {
3629
+ bytes.push(192 | c >> 6, 128 | c & 63);
3630
+ } else if (c < 55296 || c >= 57344) {
3631
+ bytes.push(224 | c >> 12, 128 | c >> 6 & 63, 128 | c & 63);
3632
+ } else {
3633
+ i++;
3634
+ c = 65536 + ((c & 1023) << 10 | str.charCodeAt(i) & 1023);
3635
+ bytes.push(240 | c >> 18, 128 | c >> 12 & 63, 128 | c >> 6 & 63, 128 | c & 63);
3636
+ }
3017
3637
  }
3638
+ return new Uint8Array(bytes);
3018
3639
  }
3019
- __name(validate_map_schema, "validate_map_schema");
3020
- function validate_struct_schema(schema) {
3021
- if (typeof schema !== "object")
3022
- throw new ErrorSchema(schema, "object");
3023
- for (var key in schema) {
3024
- validate_schema(schema[key]);
3640
+ __name(utf8Encode, "utf8Encode");
3641
+ function utf8Decode(bytes) {
3642
+ const codePoints = [];
3643
+ for (let i = 0; i < bytes.length; i++) {
3644
+ const b = bytes[i];
3645
+ if (b < 128) {
3646
+ codePoints.push(b);
3647
+ } else if (b < 224) {
3648
+ codePoints.push((b & 31) << 6 | bytes[++i] & 63);
3649
+ } else if (b < 240) {
3650
+ codePoints.push((b & 15) << 12 | (bytes[++i] & 63) << 6 | bytes[++i] & 63);
3651
+ } else {
3652
+ codePoints.push((b & 7) << 18 | (bytes[++i] & 63) << 12 | (bytes[++i] & 63) << 6 | bytes[++i] & 63);
3653
+ }
3025
3654
  }
3655
+ return String.fromCodePoint(...codePoints);
3026
3656
  }
3027
- __name(validate_struct_schema, "validate_struct_schema");
3028
-
3029
- // ../../node_modules/borsh/lib/esm/serialize.js
3030
- var BorshSerializer = (
3031
- /** @class */
3032
- function() {
3033
- function BorshSerializer2(checkTypes) {
3034
- this.encoded = new EncodeBuffer();
3035
- this.fieldPath = ["value"];
3036
- this.checkTypes = checkTypes;
3037
- }
3038
- __name(BorshSerializer2, "BorshSerializer");
3039
- BorshSerializer2.prototype.encode = function(value, schema) {
3040
- this.encode_value(value, schema);
3041
- return this.encoded.get_used_buffer();
3042
- };
3043
- BorshSerializer2.prototype.encode_value = function(value, schema) {
3044
- if (typeof schema === "string") {
3045
- if (integers.includes(schema))
3046
- return this.encode_integer(value, schema);
3047
- if (schema === "string")
3048
- return this.encode_string(value);
3049
- if (schema === "bool")
3050
- return this.encode_boolean(value);
3051
- }
3052
- if (typeof schema === "object") {
3053
- if ("option" in schema)
3054
- return this.encode_option(value, schema);
3055
- if ("enum" in schema)
3056
- return this.encode_enum(value, schema);
3057
- if ("array" in schema)
3058
- return this.encode_array(value, schema);
3059
- if ("set" in schema)
3060
- return this.encode_set(value, schema);
3061
- if ("map" in schema)
3062
- return this.encode_map(value, schema);
3063
- if ("struct" in schema)
3064
- return this.encode_struct(value, schema);
3657
+ __name(utf8Decode, "utf8Decode");
3658
+ function encodeValue(buf, value, schema) {
3659
+ if (typeof schema === "string") {
3660
+ switch (schema) {
3661
+ case "u8":
3662
+ return buf.storeU8(value);
3663
+ case "u16":
3664
+ return buf.storeU16(value);
3665
+ case "u32":
3666
+ return buf.storeU32(value);
3667
+ case "u64":
3668
+ return encodeBigint(buf, BigInt(value), 8);
3669
+ case "u128":
3670
+ return encodeBigint(buf, BigInt(value), 16);
3671
+ case "string": {
3672
+ const encoded = utf8Encode(value);
3673
+ buf.storeU32(encoded.length);
3674
+ buf.storeBytes(encoded);
3675
+ return;
3065
3676
  }
3066
- };
3067
- BorshSerializer2.prototype.encode_integer = function(value, schema) {
3068
- var size = parseInt(schema.substring(1));
3069
- if (size <= 32 || schema == "f64") {
3070
- this.checkTypes && expect_type(value, "number", this.fieldPath);
3071
- this.encoded.store_value(value, schema);
3072
- } else {
3073
- this.checkTypes && expect_bigint(value, this.fieldPath);
3074
- this.encode_bigint(BigInt(value), size);
3075
- }
3076
- };
3077
- BorshSerializer2.prototype.encode_bigint = function(value, size) {
3078
- var buffer_len = size / 8;
3079
- var buffer = new Uint8Array(buffer_len);
3080
- for (var i = 0; i < buffer_len; i++) {
3081
- buffer[i] = Number(value & BigInt(255));
3082
- value = value >> BigInt(8);
3083
- }
3084
- this.encoded.store_bytes(new Uint8Array(buffer));
3085
- };
3086
- BorshSerializer2.prototype.encode_string = function(value) {
3087
- this.checkTypes && expect_type(value, "string", this.fieldPath);
3088
- var _value = value;
3089
- var utf8Bytes = [];
3090
- for (var i = 0; i < _value.length; i++) {
3091
- var charCode = _value.charCodeAt(i);
3092
- if (charCode < 128) {
3093
- utf8Bytes.push(charCode);
3094
- } else if (charCode < 2048) {
3095
- utf8Bytes.push(192 | charCode >> 6, 128 | charCode & 63);
3096
- } else if (charCode < 55296 || charCode >= 57344) {
3097
- utf8Bytes.push(224 | charCode >> 12, 128 | charCode >> 6 & 63, 128 | charCode & 63);
3098
- } else {
3099
- i++;
3100
- charCode = 65536 + ((charCode & 1023) << 10 | _value.charCodeAt(i) & 1023);
3101
- utf8Bytes.push(240 | charCode >> 18, 128 | charCode >> 12 & 63, 128 | charCode >> 6 & 63, 128 | charCode & 63);
3102
- }
3103
- }
3104
- this.encoded.store_value(utf8Bytes.length, "u32");
3105
- this.encoded.store_bytes(new Uint8Array(utf8Bytes));
3106
- };
3107
- BorshSerializer2.prototype.encode_boolean = function(value) {
3108
- this.checkTypes && expect_type(value, "boolean", this.fieldPath);
3109
- this.encoded.store_value(value ? 1 : 0, "u8");
3110
- };
3111
- BorshSerializer2.prototype.encode_option = function(value, schema) {
3677
+ }
3678
+ }
3679
+ if (typeof schema === "object") {
3680
+ if ("option" in schema) {
3112
3681
  if (value === null || value === void 0) {
3113
- this.encoded.store_value(0, "u8");
3114
- } else {
3115
- this.encoded.store_value(1, "u8");
3116
- this.encode_value(value, schema.option);
3117
- }
3118
- };
3119
- BorshSerializer2.prototype.encode_enum = function(value, schema) {
3120
- this.checkTypes && expect_enum(value, this.fieldPath);
3121
- var valueKey = Object.keys(value)[0];
3122
- for (var i = 0; i < schema["enum"].length; i++) {
3123
- var valueSchema = schema["enum"][i];
3124
- if (valueKey === Object.keys(valueSchema.struct)[0]) {
3125
- this.encoded.store_value(i, "u8");
3126
- return this.encode_struct(value, valueSchema);
3127
- }
3128
- }
3129
- throw new Error("Enum key (".concat(valueKey, ") not found in enum schema: ").concat(JSON.stringify(schema), " at ").concat(this.fieldPath.join(".")));
3130
- };
3131
- BorshSerializer2.prototype.encode_array = function(value, schema) {
3132
- if (isArrayLike(value))
3133
- return this.encode_arraylike(value, schema);
3134
- if (value instanceof ArrayBuffer)
3135
- return this.encode_buffer(value, schema);
3136
- throw new Error("Expected Array-like not ".concat(typeof value, "(").concat(value, ") at ").concat(this.fieldPath.join(".")));
3137
- };
3138
- BorshSerializer2.prototype.encode_arraylike = function(value, schema) {
3139
- if (schema.array.len) {
3140
- expect_same_size(value.length, schema.array.len, this.fieldPath);
3682
+ buf.storeU8(0);
3141
3683
  } else {
3142
- this.encoded.store_value(value.length, "u32");
3143
- }
3144
- for (var i = 0; i < value.length; i++) {
3145
- this.encode_value(value[i], schema.array.type);
3146
- }
3147
- };
3148
- BorshSerializer2.prototype.encode_buffer = function(value, schema) {
3149
- if (schema.array.len) {
3150
- expect_same_size(value.byteLength, schema.array.len, this.fieldPath);
3151
- } else {
3152
- this.encoded.store_value(value.byteLength, "u32");
3153
- }
3154
- this.encoded.store_bytes(new Uint8Array(value));
3155
- };
3156
- BorshSerializer2.prototype.encode_set = function(value, schema) {
3157
- this.checkTypes && expect_type(value, "object", this.fieldPath);
3158
- var isSet = value instanceof Set;
3159
- var values = isSet ? Array.from(value.values()) : Object.values(value);
3160
- this.encoded.store_value(values.length, "u32");
3161
- for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
3162
- var value_1 = values_1[_i];
3163
- this.encode_value(value_1, schema.set);
3164
- }
3165
- };
3166
- BorshSerializer2.prototype.encode_map = function(value, schema) {
3167
- this.checkTypes && expect_type(value, "object", this.fieldPath);
3168
- var isMap = value instanceof Map;
3169
- var keys = isMap ? Array.from(value.keys()) : Object.keys(value);
3170
- this.encoded.store_value(keys.length, "u32");
3171
- for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
3172
- var key = keys_1[_i];
3173
- this.encode_value(key, schema.map.key);
3174
- this.encode_value(isMap ? value.get(key) : value[key], schema.map.value);
3175
- }
3176
- };
3177
- BorshSerializer2.prototype.encode_struct = function(value, schema) {
3178
- this.checkTypes && expect_type(value, "object", this.fieldPath);
3179
- for (var _i = 0, _a = Object.keys(schema.struct); _i < _a.length; _i++) {
3180
- var key = _a[_i];
3181
- this.fieldPath.push(key);
3182
- this.encode_value(value[key], schema.struct[key]);
3183
- this.fieldPath.pop();
3184
- }
3185
- };
3186
- return BorshSerializer2;
3187
- }()
3188
- );
3189
-
3190
- // ../../node_modules/borsh/lib/esm/deserialize.js
3191
- var BorshDeserializer = (
3192
- /** @class */
3193
- function() {
3194
- function BorshDeserializer2(bufferArray) {
3195
- this.buffer = new DecodeBuffer(bufferArray);
3196
- }
3197
- __name(BorshDeserializer2, "BorshDeserializer");
3198
- BorshDeserializer2.prototype.decode = function(schema) {
3199
- return this.decode_value(schema);
3200
- };
3201
- BorshDeserializer2.prototype.decode_value = function(schema) {
3202
- if (typeof schema === "string") {
3203
- if (integers.includes(schema))
3204
- return this.decode_integer(schema);
3205
- if (schema === "string")
3206
- return this.decode_string();
3207
- if (schema === "bool")
3208
- return this.decode_boolean();
3684
+ buf.storeU8(1);
3685
+ encodeValue(buf, value, schema.option);
3209
3686
  }
3210
- if (typeof schema === "object") {
3211
- if ("option" in schema)
3212
- return this.decode_option(schema);
3213
- if ("enum" in schema)
3214
- return this.decode_enum(schema);
3215
- if ("array" in schema)
3216
- return this.decode_array(schema);
3217
- if ("set" in schema)
3218
- return this.decode_set(schema);
3219
- if ("map" in schema)
3220
- return this.decode_map(schema);
3221
- if ("struct" in schema)
3222
- return this.decode_struct(schema);
3223
- }
3224
- throw new Error("Unsupported type: ".concat(schema));
3225
- };
3226
- BorshDeserializer2.prototype.decode_integer = function(schema) {
3227
- var size = parseInt(schema.substring(1));
3228
- if (size <= 32 || schema == "f64") {
3229
- return this.buffer.consume_value(schema);
3230
- }
3231
- return this.decode_bigint(size, schema.startsWith("i"));
3232
- };
3233
- BorshDeserializer2.prototype.decode_bigint = function(size, signed) {
3234
- if (signed === void 0) {
3235
- signed = false;
3236
- }
3237
- var buffer_len = size / 8;
3238
- var buffer = new Uint8Array(this.buffer.consume_bytes(buffer_len));
3239
- var bits = buffer.reduceRight(function(r, x) {
3240
- return r + x.toString(16).padStart(2, "0");
3241
- }, "");
3242
- if (signed && buffer[buffer_len - 1]) {
3243
- return BigInt.asIntN(size, BigInt("0x".concat(bits)));
3244
- }
3245
- return BigInt("0x".concat(bits));
3246
- };
3247
- BorshDeserializer2.prototype.decode_string = function() {
3248
- var len = this.decode_integer("u32");
3249
- var buffer = new Uint8Array(this.buffer.consume_bytes(len));
3250
- var codePoints = [];
3251
- for (var i = 0; i < len; ++i) {
3252
- var byte = buffer[i];
3253
- if (byte < 128) {
3254
- codePoints.push(byte);
3255
- } else if (byte < 224) {
3256
- codePoints.push((byte & 31) << 6 | buffer[++i] & 63);
3257
- } else if (byte < 240) {
3258
- codePoints.push((byte & 15) << 12 | (buffer[++i] & 63) << 6 | buffer[++i] & 63);
3259
- } else {
3260
- var codePoint = (byte & 7) << 18 | (buffer[++i] & 63) << 12 | (buffer[++i] & 63) << 6 | buffer[++i] & 63;
3261
- codePoints.push(codePoint);
3687
+ return;
3688
+ }
3689
+ if ("enum" in schema) {
3690
+ const valueKey = Object.keys(value)[0];
3691
+ const variants = schema.enum;
3692
+ for (let i = 0; i < variants.length; i++) {
3693
+ const variantKey = Object.keys(variants[i].struct)[0];
3694
+ if (valueKey === variantKey) {
3695
+ buf.storeU8(i);
3696
+ encodeStruct(buf, value, variants[i]);
3697
+ return;
3262
3698
  }
3263
3699
  }
3264
- return String.fromCodePoint.apply(String, codePoints);
3265
- };
3266
- BorshDeserializer2.prototype.decode_boolean = function() {
3267
- return this.buffer.consume_value("u8") > 0;
3268
- };
3269
- BorshDeserializer2.prototype.decode_option = function(schema) {
3270
- var option = this.buffer.consume_value("u8");
3271
- if (option === 1) {
3272
- return this.decode_value(schema.option);
3700
+ throw new Error(`Borsh: enum key "${valueKey}" not found in schema`);
3701
+ }
3702
+ if ("array" in schema) {
3703
+ if (schema.array.len == null) {
3704
+ buf.storeU32(value.length);
3273
3705
  }
3274
- if (option !== 0) {
3275
- throw new Error("Invalid option ".concat(option));
3706
+ for (let i = 0; i < value.length; i++) {
3707
+ encodeValue(buf, value[i], schema.array.type);
3276
3708
  }
3277
- return null;
3278
- };
3279
- BorshDeserializer2.prototype.decode_enum = function(schema) {
3280
- var _a;
3281
- var valueIndex = this.buffer.consume_value("u8");
3282
- if (valueIndex > schema["enum"].length) {
3283
- throw new Error("Enum option ".concat(valueIndex, " is not available"));
3709
+ return;
3710
+ }
3711
+ if ("struct" in schema) {
3712
+ encodeStruct(buf, value, schema);
3713
+ return;
3714
+ }
3715
+ }
3716
+ }
3717
+ __name(encodeValue, "encodeValue");
3718
+ function encodeStruct(buf, value, schema) {
3719
+ for (const key of Object.keys(schema.struct)) {
3720
+ encodeValue(buf, value[key], schema.struct[key]);
3721
+ }
3722
+ }
3723
+ __name(encodeStruct, "encodeStruct");
3724
+ function decodeValue(buf, schema) {
3725
+ if (typeof schema === "string") {
3726
+ switch (schema) {
3727
+ case "u8":
3728
+ return buf.readU8();
3729
+ case "u16":
3730
+ return buf.readU16();
3731
+ case "u32":
3732
+ return buf.readU32();
3733
+ case "u64":
3734
+ return decodeBigint(buf, 8);
3735
+ case "u128":
3736
+ return decodeBigint(buf, 16);
3737
+ case "string": {
3738
+ const len = buf.readU32();
3739
+ return utf8Decode(buf.readBytes(len));
3284
3740
  }
3285
- var struct = schema["enum"][valueIndex].struct;
3286
- var key = Object.keys(struct)[0];
3287
- return _a = {}, _a[key] = this.decode_value(struct[key]), _a;
3288
- };
3289
- BorshDeserializer2.prototype.decode_array = function(schema) {
3290
- var result = [];
3291
- var len = schema.array.len ? schema.array.len : this.decode_integer("u32");
3292
- for (var i = 0; i < len; ++i) {
3293
- result.push(this.decode_value(schema.array.type));
3741
+ }
3742
+ }
3743
+ if (typeof schema === "object") {
3744
+ if ("option" in schema) {
3745
+ const flag = buf.readU8();
3746
+ if (flag === 1) return decodeValue(buf, schema.option);
3747
+ if (flag === 0) return null;
3748
+ throw new Error(`Borsh: invalid option flag ${flag}`);
3749
+ }
3750
+ if ("enum" in schema) {
3751
+ const idx = buf.readU8();
3752
+ if (idx >= schema.enum.length) {
3753
+ throw new Error(`Borsh: enum index ${idx} out of range`);
3294
3754
  }
3295
- return result;
3296
- };
3297
- BorshDeserializer2.prototype.decode_set = function(schema) {
3298
- var len = this.decode_integer("u32");
3299
- var result = /* @__PURE__ */ new Set();
3300
- for (var i = 0; i < len; ++i) {
3301
- result.add(this.decode_value(schema.set));
3755
+ const variant = schema.enum[idx];
3756
+ const result = {};
3757
+ for (const key of Object.keys(variant.struct)) {
3758
+ result[key] = decodeValue(buf, variant.struct[key]);
3302
3759
  }
3303
3760
  return result;
3304
- };
3305
- BorshDeserializer2.prototype.decode_map = function(schema) {
3306
- var len = this.decode_integer("u32");
3307
- var result = /* @__PURE__ */ new Map();
3308
- for (var i = 0; i < len; ++i) {
3309
- var key = this.decode_value(schema.map.key);
3310
- var value = this.decode_value(schema.map.value);
3311
- result.set(key, value);
3761
+ }
3762
+ if ("array" in schema) {
3763
+ const len = schema.array.len ?? buf.readU32();
3764
+ const result = [];
3765
+ for (let i = 0; i < len; i++) {
3766
+ result.push(decodeValue(buf, schema.array.type));
3312
3767
  }
3313
3768
  return result;
3314
- };
3315
- BorshDeserializer2.prototype.decode_struct = function(schema) {
3316
- var result = {};
3317
- for (var key in schema.struct) {
3318
- result[key] = this.decode_value(schema.struct[key]);
3769
+ }
3770
+ if ("struct" in schema) {
3771
+ const result = {};
3772
+ for (const key in schema.struct) {
3773
+ result[key] = decodeValue(buf, schema.struct[key]);
3319
3774
  }
3320
3775
  return result;
3321
- };
3322
- return BorshDeserializer2;
3323
- }()
3324
- );
3325
-
3326
- // ../../node_modules/borsh/lib/esm/index.js
3327
- function serialize(schema, value, validate) {
3328
- if (validate === void 0) {
3329
- validate = true;
3330
- }
3331
- if (validate)
3332
- validate_schema(schema);
3333
- var serializer = new BorshSerializer(validate);
3334
- return serializer.encode(value, schema);
3776
+ }
3777
+ }
3778
+ throw new Error(`Borsh: unsupported schema: ${JSON.stringify(schema)}`);
3779
+ }
3780
+ __name(decodeValue, "decodeValue");
3781
+ function serialize(schema, value) {
3782
+ const buf = new EncodeBuffer();
3783
+ encodeValue(buf, value, schema);
3784
+ return buf.result();
3335
3785
  }
3336
3786
  __name(serialize, "serialize");
3337
- function deserialize(schema, buffer, validate) {
3338
- if (validate === void 0) {
3339
- validate = true;
3340
- }
3341
- if (validate)
3342
- validate_schema(schema);
3343
- var deserializer = new BorshDeserializer(buffer);
3344
- return deserializer.decode(schema);
3787
+ function deserialize(schema, buffer) {
3788
+ const buf = new DecodeBuffer(buffer);
3789
+ return decodeValue(buf, schema);
3345
3790
  }
3346
3791
  __name(deserialize, "deserialize");
3347
3792
 
@@ -3522,14 +3967,22 @@ var near = (() => {
3522
3967
  var txToJsonStringified = /* @__PURE__ */ __name((tx) => {
3523
3968
  return JSON.stringify(txToJson(tx));
3524
3969
  }, "txToJsonStringified");
3970
+ function mapPublicKey(keyString) {
3971
+ const curve = curveFromKey(keyString);
3972
+ const data = keyFromString(keyString);
3973
+ return curve === "secp256k1" ? { secp256k1Key: { data } } : { ed25519Key: { data } };
3974
+ }
3975
+ __name(mapPublicKey, "mapPublicKey");
3976
+ function mapSignature(sigBase58, signerKeyString) {
3977
+ const curve = curveFromKey(signerKeyString);
3978
+ const data = base58_to_binary_default(sigBase58);
3979
+ return curve === "secp256k1" ? { secp256k1Signature: { data } } : { ed25519Signature: { data } };
3980
+ }
3981
+ __name(mapSignature, "mapSignature");
3525
3982
  function mapTransaction(jsonTransaction) {
3526
3983
  return {
3527
3984
  signerId: jsonTransaction.signerId,
3528
- publicKey: {
3529
- ed25519Key: {
3530
- data: keyFromString(jsonTransaction.publicKey)
3531
- }
3532
- },
3985
+ publicKey: mapPublicKey(jsonTransaction.publicKey),
3533
3986
  nonce: BigInt(jsonTransaction.nonce),
3534
3987
  receiverId: jsonTransaction.receiverId,
3535
3988
  blockHash: base58_to_binary_default(jsonTransaction.blockHash),
@@ -3552,13 +4005,9 @@ var near = (() => {
3552
4005
  console.log("fastnear: mapped (for borsh schema) signed transaction", mappedSignedTx);
3553
4006
  const plainSignedTransaction = {
3554
4007
  transaction: mappedSignedTx,
3555
- signature: {
3556
- ed25519Signature: {
3557
- data: base58_to_binary_default(signature)
3558
- }
3559
- }
4008
+ signature: mapSignature(signature, jsonTransaction.publicKey)
3560
4009
  };
3561
- const borshSignedTx = serialize(SCHEMA.SignedTransaction, plainSignedTransaction, true);
4010
+ const borshSignedTx = serialize(SCHEMA.SignedTransaction, plainSignedTransaction);
3562
4011
  console.log("fastnear: borsh-serialized signed transaction:", borshSignedTx);
3563
4012
  return borshSignedTx;
3564
4013
  }
@@ -3598,22 +4047,14 @@ var near = (() => {
3598
4047
  return {
3599
4048
  stake: {
3600
4049
  stake: BigInt(action.stake),
3601
- publicKey: {
3602
- ed25519Key: {
3603
- data: keyFromString(action.publicKey)
3604
- }
3605
- }
4050
+ publicKey: mapPublicKey(action.publicKey)
3606
4051
  }
3607
4052
  };
3608
4053
  }
3609
4054
  case "AddKey": {
3610
4055
  return {
3611
4056
  addKey: {
3612
- publicKey: {
3613
- ed25519Key: {
3614
- data: keyFromString(action.publicKey)
3615
- }
3616
- },
4057
+ publicKey: mapPublicKey(action.publicKey),
3617
4058
  accessKey: {
3618
4059
  nonce: BigInt(action.accessKey.nonce),
3619
4060
  permission: action.accessKey.permission === "FullAccess" ? { fullAccess: {} } : {
@@ -3630,11 +4071,7 @@ var near = (() => {
3630
4071
  case "DeleteKey": {
3631
4072
  return {
3632
4073
  deleteKey: {
3633
- publicKey: {
3634
- ed25519Key: {
3635
- data: keyFromString(action.publicKey)
3636
- }
3637
- }
4074
+ publicKey: mapPublicKey(action.publicKey)
3638
4075
  }
3639
4076
  };
3640
4077
  }
@@ -3649,9 +4086,7 @@ var near = (() => {
3649
4086
  return {
3650
4087
  signedDelegate: {
3651
4088
  delegateAction: mapAction(action.delegateAction),
3652
- signature: {
3653
- ed25519Signature: base58_to_binary_default(action.signature)
3654
- }
4089
+ signature: mapSignature(action.signature, action.publicKey)
3655
4090
  }
3656
4091
  };
3657
4092
  }
@@ -3816,7 +4251,6 @@ var near = (() => {
3816
4251
  }, "resetTxHistory");
3817
4252
 
3818
4253
  // src/near.ts
3819
- big_default.DP = 27;
3820
4254
  var MaxBlockDelayMs = 1e3 * 60 * 60 * 6;
3821
4255
  function withBlockId(params, blockId) {
3822
4256
  if (blockId === "final" || blockId === "optimistic") {
@@ -4235,6 +4669,12 @@ var near = (() => {
4235
4669
 
4236
4670
  @noble/curves/ed25519.js:
4237
4671
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4672
+
4673
+ @noble/curves/abstract/weierstrass.js:
4674
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4675
+
4676
+ @noble/curves/secp256k1.js:
4677
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4238
4678
  */
4239
4679
 
4240
4680
  try {