@fastnear/utils 0.9.13 → 0.10.2

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 Utils - IIFE/UMD (@fastnear/utils version 0.9.12) */
2
- /* https://www.npmjs.com/package/@fastnear/utils/v/0.9.12 */
1
+ /* ⋈ 🏃🏻💨 FastNear Utils - IIFE/UMD (@fastnear/utils version 0.10.1) */
2
+ /* https://www.npmjs.com/package/@fastnear/utils/v/0.10.1 */
3
3
  "use strict";
4
4
  var NearUtils = (() => {
5
5
  var __defProp = Object.defineProperty;
@@ -31,6 +31,7 @@ var NearUtils = (() => {
31
31
  canSignWithLAK: () => canSignWithLAK,
32
32
  convertUnit: () => convertUnit,
33
33
  createDefaultStorage: () => createDefaultStorage,
34
+ curveFromKey: () => curveFromKey,
34
35
  deepCopy: () => deepCopy,
35
36
  exp: () => exp,
36
37
  fromBase58: () => base58_to_binary_default,
@@ -85,6 +86,13 @@ var NearUtils = (() => {
85
86
  return value;
86
87
  }
87
88
  __name(abytes, "abytes");
89
+ function ahash(h) {
90
+ if (typeof h !== "function" || typeof h.create !== "function")
91
+ throw new Error("Hash must wrapped by utils.createHasher");
92
+ anumber(h.outputLen);
93
+ anumber(h.blockLen);
94
+ }
95
+ __name(ahash, "ahash");
88
96
  function aexists(instance, checkFinished = true) {
89
97
  if (instance.destroyed)
90
98
  throw new Error("Hash instance has been destroyed");
@@ -762,6 +770,11 @@ var NearUtils = (() => {
762
770
  return n;
763
771
  }
764
772
  __name(abignumber, "abignumber");
773
+ function numberToHexUnpadded(num) {
774
+ const hex = abignumber(num).toString(16);
775
+ return hex.length & 1 ? "0" + hex : hex;
776
+ }
777
+ __name(numberToHexUnpadded, "numberToHexUnpadded");
765
778
  function hexToNumber(hex) {
766
779
  if (typeof hex !== "string")
767
780
  throw new Error("hex string expected, got " + typeof hex);
@@ -803,7 +816,66 @@ var NearUtils = (() => {
803
816
  throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
804
817
  }
805
818
  __name(aInRange, "aInRange");
819
+ function bitLen(n) {
820
+ let len;
821
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
822
+ ;
823
+ return len;
824
+ }
825
+ __name(bitLen, "bitLen");
806
826
  var bitMask = /* @__PURE__ */ __name((n) => (_1n << BigInt(n)) - _1n, "bitMask");
827
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
828
+ anumber(hashLen, "hashLen");
829
+ anumber(qByteLen, "qByteLen");
830
+ if (typeof hmacFn !== "function")
831
+ throw new Error("hmacFn must be a function");
832
+ const u8n = /* @__PURE__ */ __name((len) => new Uint8Array(len), "u8n");
833
+ const NULL = Uint8Array.of();
834
+ const byte0 = Uint8Array.of(0);
835
+ const byte1 = Uint8Array.of(1);
836
+ const _maxDrbgIters = 1e3;
837
+ let v = u8n(hashLen);
838
+ let k = u8n(hashLen);
839
+ let i = 0;
840
+ const reset = /* @__PURE__ */ __name(() => {
841
+ v.fill(1);
842
+ k.fill(0);
843
+ i = 0;
844
+ }, "reset");
845
+ const h = /* @__PURE__ */ __name((...msgs) => hmacFn(k, concatBytes(v, ...msgs)), "h");
846
+ const reseed = /* @__PURE__ */ __name((seed = NULL) => {
847
+ k = h(byte0, seed);
848
+ v = h();
849
+ if (seed.length === 0)
850
+ return;
851
+ k = h(byte1, seed);
852
+ v = h();
853
+ }, "reseed");
854
+ const gen = /* @__PURE__ */ __name(() => {
855
+ if (i++ >= _maxDrbgIters)
856
+ throw new Error("drbg: tried max amount of iterations");
857
+ let len = 0;
858
+ const out = [];
859
+ while (len < qByteLen) {
860
+ v = h();
861
+ const sl = v.slice();
862
+ out.push(sl);
863
+ len += v.length;
864
+ }
865
+ return concatBytes(...out);
866
+ }, "gen");
867
+ const genUntil = /* @__PURE__ */ __name((seed, pred) => {
868
+ reset();
869
+ reseed(seed);
870
+ let res = void 0;
871
+ while (!(res = pred(gen())))
872
+ reseed();
873
+ reset();
874
+ return res;
875
+ }, "genUntil");
876
+ return genUntil;
877
+ }
878
+ __name(createHmacDrbg, "createHmacDrbg");
807
879
  function validateObject(object, fields = {}, optFields = {}) {
808
880
  if (!object || typeof object !== "object")
809
881
  throw new Error("expected valid options object");
@@ -903,13 +975,13 @@ var NearUtils = (() => {
903
975
  return root;
904
976
  }
905
977
  __name(sqrt5mod8, "sqrt5mod8");
906
- function sqrt9mod16(P2) {
907
- const Fp_ = Field(P2);
908
- const tn = tonelliShanks(P2);
978
+ function sqrt9mod16(P) {
979
+ const Fp_ = Field(P);
980
+ const tn = tonelliShanks(P);
909
981
  const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
910
982
  const c2 = tn(Fp_, c1);
911
983
  const c3 = tn(Fp_, Fp_.neg(c1));
912
- const c4 = (P2 + _7n) / _16n;
984
+ const c4 = (P + _7n) / _16n;
913
985
  return (Fp, n) => {
914
986
  let tv1 = Fp.pow(n, c4);
915
987
  let tv2 = Fp.mul(tv1, c1);
@@ -926,17 +998,17 @@ var NearUtils = (() => {
926
998
  };
927
999
  }
928
1000
  __name(sqrt9mod16, "sqrt9mod16");
929
- function tonelliShanks(P2) {
930
- if (P2 < _3n)
1001
+ function tonelliShanks(P) {
1002
+ if (P < _3n)
931
1003
  throw new Error("sqrt is not defined for small field");
932
- let Q = P2 - _1n2;
1004
+ let Q = P - _1n2;
933
1005
  let S = 0;
934
1006
  while (Q % _2n === _0n2) {
935
1007
  Q /= _2n;
936
1008
  S++;
937
1009
  }
938
1010
  let Z = _2n;
939
- const _Fp = Field(P2);
1011
+ const _Fp = Field(P);
940
1012
  while (FpLegendre(_Fp, Z) === 1) {
941
1013
  if (Z++ > 1e3)
942
1014
  throw new Error("Cannot find square root: probably non-prime P");
@@ -976,14 +1048,14 @@ var NearUtils = (() => {
976
1048
  }, "tonelliSlow");
977
1049
  }
978
1050
  __name(tonelliShanks, "tonelliShanks");
979
- function FpSqrt(P2) {
980
- if (P2 % _4n === _3n)
1051
+ function FpSqrt(P) {
1052
+ if (P % _4n === _3n)
981
1053
  return sqrt3mod4;
982
- if (P2 % _8n === _5n)
1054
+ if (P % _8n === _5n)
983
1055
  return sqrt5mod8;
984
- if (P2 % _16n === _9n)
985
- return sqrt9mod16(P2);
986
- return tonelliShanks(P2);
1056
+ if (P % _16n === _9n)
1057
+ return sqrt9mod16(P);
1058
+ return tonelliShanks(P);
987
1059
  }
988
1060
  __name(FpSqrt, "FpSqrt");
989
1061
  var isNegativeLE = /* @__PURE__ */ __name((num, modulo) => (mod(num, modulo) & _1n2) === _1n2, "isNegativeLE");
@@ -1217,6 +1289,30 @@ var NearUtils = (() => {
1217
1289
  return new _Field(ORDER, opts);
1218
1290
  }
1219
1291
  __name(Field, "Field");
1292
+ function getFieldBytesLength(fieldOrder) {
1293
+ if (typeof fieldOrder !== "bigint")
1294
+ throw new Error("field order must be bigint");
1295
+ const bitLength = fieldOrder.toString(2).length;
1296
+ return Math.ceil(bitLength / 8);
1297
+ }
1298
+ __name(getFieldBytesLength, "getFieldBytesLength");
1299
+ function getMinHashLength(fieldOrder) {
1300
+ const length = getFieldBytesLength(fieldOrder);
1301
+ return length + Math.ceil(length / 2);
1302
+ }
1303
+ __name(getMinHashLength, "getMinHashLength");
1304
+ function mapHashToField(key, fieldOrder, isLE = false) {
1305
+ abytes(key);
1306
+ const len = key.length;
1307
+ const fieldLen = getFieldBytesLength(fieldOrder);
1308
+ const minLen = getMinHashLength(fieldOrder);
1309
+ if (len < 16 || len < minLen || len > 1024)
1310
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
1311
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
1312
+ const reduced = mod(num, fieldOrder - _1n2) + _1n2;
1313
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
1314
+ }
1315
+ __name(mapHashToField, "mapHashToField");
1220
1316
 
1221
1317
  // ../../node_modules/@noble/curves/abstract/curve.js
1222
1318
  var _0n3 = /* @__PURE__ */ BigInt(0);
@@ -1265,8 +1361,8 @@ var NearUtils = (() => {
1265
1361
  __name(calcOffsets, "calcOffsets");
1266
1362
  var pointPrecomputes = /* @__PURE__ */ new WeakMap();
1267
1363
  var pointWindowSizes = /* @__PURE__ */ new WeakMap();
1268
- function getW(P2) {
1269
- return pointWindowSizes.get(P2) || 1;
1364
+ function getW(P) {
1365
+ return pointWindowSizes.get(P) || 1;
1270
1366
  }
1271
1367
  __name(getW, "getW");
1272
1368
  function assert0(n) {
@@ -1399,15 +1495,31 @@ var NearUtils = (() => {
1399
1495
  // We calculate precomputes for elliptic curve point multiplication
1400
1496
  // using windowed method. This specifies window size and
1401
1497
  // stores precomputed values. Usually only base point would be precomputed.
1402
- createCache(P2, W) {
1498
+ createCache(P, W) {
1403
1499
  validateW(W, this.bits);
1404
- pointWindowSizes.set(P2, W);
1405
- pointPrecomputes.delete(P2);
1500
+ pointWindowSizes.set(P, W);
1501
+ pointPrecomputes.delete(P);
1406
1502
  }
1407
1503
  hasCache(elm) {
1408
1504
  return getW(elm) !== 1;
1409
1505
  }
1410
1506
  };
1507
+ function mulEndoUnsafe(Point, point, k1, k2) {
1508
+ let acc = point;
1509
+ let p1 = Point.ZERO;
1510
+ let p2 = Point.ZERO;
1511
+ while (k1 > _0n3 || k2 > _0n3) {
1512
+ if (k1 & _1n3)
1513
+ p1 = p1.add(acc);
1514
+ if (k2 & _1n3)
1515
+ p2 = p2.add(acc);
1516
+ acc = acc.double();
1517
+ k1 >>= _1n3;
1518
+ k2 >>= _1n3;
1519
+ }
1520
+ return { p1, p2 };
1521
+ }
1522
+ __name(mulEndoUnsafe, "mulEndoUnsafe");
1411
1523
  function createField(order, field, isLE) {
1412
1524
  if (field) {
1413
1525
  if (field.ORDER !== order)
@@ -1904,19 +2016,19 @@ var NearUtils = (() => {
1904
2016
  }))();
1905
2017
  function ed25519_pow_2_252_3(x) {
1906
2018
  const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
1907
- const P2 = ed25519_CURVE_p;
1908
- const x2 = x * x % P2;
1909
- const b2 = x2 * x % P2;
1910
- const b4 = pow2(b2, _2n3, P2) * b2 % P2;
1911
- const b5 = pow2(b4, _1n5, P2) * x % P2;
1912
- const b10 = pow2(b5, _5n2, P2) * b5 % P2;
1913
- const b20 = pow2(b10, _10n, P2) * b10 % P2;
1914
- const b40 = pow2(b20, _20n, P2) * b20 % P2;
1915
- const b80 = pow2(b40, _40n, P2) * b40 % P2;
1916
- const b160 = pow2(b80, _80n, P2) * b80 % P2;
1917
- const b240 = pow2(b160, _80n, P2) * b80 % P2;
1918
- const b250 = pow2(b240, _10n, P2) * b10 % P2;
1919
- const pow_p_5_8 = pow2(b250, _2n3, P2) * x % P2;
2019
+ const P = ed25519_CURVE_p;
2020
+ const x2 = x * x % P;
2021
+ const b2 = x2 * x % P;
2022
+ const b4 = pow2(b2, _2n3, P) * b2 % P;
2023
+ const b5 = pow2(b4, _1n5, P) * x % P;
2024
+ const b10 = pow2(b5, _5n2, P) * b5 % P;
2025
+ const b20 = pow2(b10, _10n, P) * b10 % P;
2026
+ const b40 = pow2(b20, _20n, P) * b20 % P;
2027
+ const b80 = pow2(b40, _40n, P) * b40 % P;
2028
+ const b160 = pow2(b80, _80n, P) * b80 % P;
2029
+ const b240 = pow2(b160, _80n, P) * b80 % P;
2030
+ const b250 = pow2(b240, _10n, P) * b10 % P;
2031
+ const pow_p_5_8 = pow2(b250, _2n3, P) * x % P;
1920
2032
  return { pow_p_5_8, b2 };
1921
2033
  }
1922
2034
  __name(ed25519_pow_2_252_3, "ed25519_pow_2_252_3");
@@ -1929,23 +2041,23 @@ var NearUtils = (() => {
1929
2041
  __name(adjustScalarBytes, "adjustScalarBytes");
1930
2042
  var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
1931
2043
  function uvRatio(u, v) {
1932
- const P2 = ed25519_CURVE_p;
1933
- const v3 = mod(v * v * v, P2);
1934
- const v7 = mod(v3 * v3 * v, P2);
2044
+ const P = ed25519_CURVE_p;
2045
+ const v3 = mod(v * v * v, P);
2046
+ const v7 = mod(v3 * v3 * v, P);
1935
2047
  const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
1936
- let x = mod(u * v3 * pow, P2);
1937
- const vx2 = mod(v * x * x, P2);
2048
+ let x = mod(u * v3 * pow, P);
2049
+ const vx2 = mod(v * x * x, P);
1938
2050
  const root1 = x;
1939
- const root2 = mod(x * ED25519_SQRT_M1, P2);
2051
+ const root2 = mod(x * ED25519_SQRT_M1, P);
1940
2052
  const useRoot1 = vx2 === u;
1941
- const useRoot2 = vx2 === mod(-u, P2);
1942
- const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P2);
2053
+ const useRoot2 = vx2 === mod(-u, P);
2054
+ const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
1943
2055
  if (useRoot1)
1944
2056
  x = root1;
1945
2057
  if (useRoot2 || noRoot)
1946
2058
  x = root2;
1947
- if (isNegativeLE(x, P2))
1948
- x = mod(-x, P2);
2059
+ if (isNegativeLE(x, P))
2060
+ x = mod(-x, P);
1949
2061
  return { isValid: useRoot1 || useRoot2, value: x };
1950
2062
  }
1951
2063
  __name(uvRatio, "uvRatio");
@@ -1956,6 +2068,1043 @@ var NearUtils = (() => {
1956
2068
  __name(ed, "ed");
1957
2069
  var ed25519 = /* @__PURE__ */ ed({});
1958
2070
 
2071
+ // ../../node_modules/@noble/hashes/hmac.js
2072
+ var _HMAC = class {
2073
+ static {
2074
+ __name(this, "_HMAC");
2075
+ }
2076
+ oHash;
2077
+ iHash;
2078
+ blockLen;
2079
+ outputLen;
2080
+ finished = false;
2081
+ destroyed = false;
2082
+ constructor(hash, key) {
2083
+ ahash(hash);
2084
+ abytes(key, void 0, "key");
2085
+ this.iHash = hash.create();
2086
+ if (typeof this.iHash.update !== "function")
2087
+ throw new Error("Expected instance of class which extends utils.Hash");
2088
+ this.blockLen = this.iHash.blockLen;
2089
+ this.outputLen = this.iHash.outputLen;
2090
+ const blockLen = this.blockLen;
2091
+ const pad = new Uint8Array(blockLen);
2092
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
2093
+ for (let i = 0; i < pad.length; i++)
2094
+ pad[i] ^= 54;
2095
+ this.iHash.update(pad);
2096
+ this.oHash = hash.create();
2097
+ for (let i = 0; i < pad.length; i++)
2098
+ pad[i] ^= 54 ^ 92;
2099
+ this.oHash.update(pad);
2100
+ clean(pad);
2101
+ }
2102
+ update(buf) {
2103
+ aexists(this);
2104
+ this.iHash.update(buf);
2105
+ return this;
2106
+ }
2107
+ digestInto(out) {
2108
+ aexists(this);
2109
+ abytes(out, this.outputLen, "output");
2110
+ this.finished = true;
2111
+ this.iHash.digestInto(out);
2112
+ this.oHash.update(out);
2113
+ this.oHash.digestInto(out);
2114
+ this.destroy();
2115
+ }
2116
+ digest() {
2117
+ const out = new Uint8Array(this.oHash.outputLen);
2118
+ this.digestInto(out);
2119
+ return out;
2120
+ }
2121
+ _cloneInto(to) {
2122
+ to ||= Object.create(Object.getPrototypeOf(this), {});
2123
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
2124
+ to = to;
2125
+ to.finished = finished;
2126
+ to.destroyed = destroyed;
2127
+ to.blockLen = blockLen;
2128
+ to.outputLen = outputLen;
2129
+ to.oHash = oHash._cloneInto(to.oHash);
2130
+ to.iHash = iHash._cloneInto(to.iHash);
2131
+ return to;
2132
+ }
2133
+ clone() {
2134
+ return this._cloneInto();
2135
+ }
2136
+ destroy() {
2137
+ this.destroyed = true;
2138
+ this.oHash.destroy();
2139
+ this.iHash.destroy();
2140
+ }
2141
+ };
2142
+ var hmac = /* @__PURE__ */ __name((hash, key, message) => new _HMAC(hash, key).update(message).digest(), "hmac");
2143
+ hmac.create = (hash, key) => new _HMAC(hash, key);
2144
+
2145
+ // ../../node_modules/@noble/curves/abstract/weierstrass.js
2146
+ var divNearest = /* @__PURE__ */ __name((num, den) => (num + (num >= 0 ? den : -den) / _2n4) / den, "divNearest");
2147
+ function _splitEndoScalar(k, basis, n) {
2148
+ const [[a1, b1], [a2, b2]] = basis;
2149
+ const c1 = divNearest(b2 * k, n);
2150
+ const c2 = divNearest(-b1 * k, n);
2151
+ let k1 = k - c1 * a1 - c2 * a2;
2152
+ let k2 = -c1 * b1 - c2 * b2;
2153
+ const k1neg = k1 < _0n5;
2154
+ const k2neg = k2 < _0n5;
2155
+ if (k1neg)
2156
+ k1 = -k1;
2157
+ if (k2neg)
2158
+ k2 = -k2;
2159
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n6;
2160
+ if (k1 < _0n5 || k1 >= MAX_NUM || k2 < _0n5 || k2 >= MAX_NUM) {
2161
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
2162
+ }
2163
+ return { k1neg, k1, k2neg, k2 };
2164
+ }
2165
+ __name(_splitEndoScalar, "_splitEndoScalar");
2166
+ function validateSigFormat(format) {
2167
+ if (!["compact", "recovered", "der"].includes(format))
2168
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
2169
+ return format;
2170
+ }
2171
+ __name(validateSigFormat, "validateSigFormat");
2172
+ function validateSigOpts(opts, def) {
2173
+ const optsn = {};
2174
+ for (let optName of Object.keys(def)) {
2175
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
2176
+ }
2177
+ abool(optsn.lowS, "lowS");
2178
+ abool(optsn.prehash, "prehash");
2179
+ if (optsn.format !== void 0)
2180
+ validateSigFormat(optsn.format);
2181
+ return optsn;
2182
+ }
2183
+ __name(validateSigOpts, "validateSigOpts");
2184
+ var DERErr = class extends Error {
2185
+ static {
2186
+ __name(this, "DERErr");
2187
+ }
2188
+ constructor(m = "") {
2189
+ super(m);
2190
+ }
2191
+ };
2192
+ var DER = {
2193
+ // asn.1 DER encoding utils
2194
+ Err: DERErr,
2195
+ // Basic building block is TLV (Tag-Length-Value)
2196
+ _tlv: {
2197
+ encode: /* @__PURE__ */ __name((tag, data) => {
2198
+ const { Err: E } = DER;
2199
+ if (tag < 0 || tag > 256)
2200
+ throw new E("tlv.encode: wrong tag");
2201
+ if (data.length & 1)
2202
+ throw new E("tlv.encode: unpadded data");
2203
+ const dataLen = data.length / 2;
2204
+ const len = numberToHexUnpadded(dataLen);
2205
+ if (len.length / 2 & 128)
2206
+ throw new E("tlv.encode: long form length too big");
2207
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
2208
+ const t = numberToHexUnpadded(tag);
2209
+ return t + lenLen + len + data;
2210
+ }, "encode"),
2211
+ // v - value, l - left bytes (unparsed)
2212
+ decode(tag, data) {
2213
+ const { Err: E } = DER;
2214
+ let pos = 0;
2215
+ if (tag < 0 || tag > 256)
2216
+ throw new E("tlv.encode: wrong tag");
2217
+ if (data.length < 2 || data[pos++] !== tag)
2218
+ throw new E("tlv.decode: wrong tlv");
2219
+ const first = data[pos++];
2220
+ const isLong = !!(first & 128);
2221
+ let length = 0;
2222
+ if (!isLong)
2223
+ length = first;
2224
+ else {
2225
+ const lenLen = first & 127;
2226
+ if (!lenLen)
2227
+ throw new E("tlv.decode(long): indefinite length not supported");
2228
+ if (lenLen > 4)
2229
+ throw new E("tlv.decode(long): byte length is too big");
2230
+ const lengthBytes = data.subarray(pos, pos + lenLen);
2231
+ if (lengthBytes.length !== lenLen)
2232
+ throw new E("tlv.decode: length bytes not complete");
2233
+ if (lengthBytes[0] === 0)
2234
+ throw new E("tlv.decode(long): zero leftmost byte");
2235
+ for (const b of lengthBytes)
2236
+ length = length << 8 | b;
2237
+ pos += lenLen;
2238
+ if (length < 128)
2239
+ throw new E("tlv.decode(long): not minimal encoding");
2240
+ }
2241
+ const v = data.subarray(pos, pos + length);
2242
+ if (v.length !== length)
2243
+ throw new E("tlv.decode: wrong value length");
2244
+ return { v, l: data.subarray(pos + length) };
2245
+ }
2246
+ },
2247
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
2248
+ // since we always use positive integers here. It must always be empty:
2249
+ // - add zero byte if exists
2250
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
2251
+ _int: {
2252
+ encode(num) {
2253
+ const { Err: E } = DER;
2254
+ if (num < _0n5)
2255
+ throw new E("integer: negative integers are not allowed");
2256
+ let hex = numberToHexUnpadded(num);
2257
+ if (Number.parseInt(hex[0], 16) & 8)
2258
+ hex = "00" + hex;
2259
+ if (hex.length & 1)
2260
+ throw new E("unexpected DER parsing assertion: unpadded hex");
2261
+ return hex;
2262
+ },
2263
+ decode(data) {
2264
+ const { Err: E } = DER;
2265
+ if (data[0] & 128)
2266
+ throw new E("invalid signature integer: negative");
2267
+ if (data[0] === 0 && !(data[1] & 128))
2268
+ throw new E("invalid signature integer: unnecessary leading zero");
2269
+ return bytesToNumberBE(data);
2270
+ }
2271
+ },
2272
+ toSig(bytes) {
2273
+ const { Err: E, _int: int, _tlv: tlv } = DER;
2274
+ const data = abytes(bytes, void 0, "signature");
2275
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
2276
+ if (seqLeftBytes.length)
2277
+ throw new E("invalid signature: left bytes after parsing");
2278
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
2279
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
2280
+ if (sLeftBytes.length)
2281
+ throw new E("invalid signature: left bytes after parsing");
2282
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
2283
+ },
2284
+ hexFromSig(sig) {
2285
+ const { _tlv: tlv, _int: int } = DER;
2286
+ const rs = tlv.encode(2, int.encode(sig.r));
2287
+ const ss = tlv.encode(2, int.encode(sig.s));
2288
+ const seq = rs + ss;
2289
+ return tlv.encode(48, seq);
2290
+ }
2291
+ };
2292
+ var _0n5 = BigInt(0);
2293
+ var _1n6 = BigInt(1);
2294
+ var _2n4 = BigInt(2);
2295
+ var _3n2 = BigInt(3);
2296
+ var _4n2 = BigInt(4);
2297
+ function weierstrass(params, extraOpts = {}) {
2298
+ const validated = createCurveFields("weierstrass", params, extraOpts);
2299
+ const { Fp, Fn } = validated;
2300
+ let CURVE = validated.CURVE;
2301
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
2302
+ validateObject(extraOpts, {}, {
2303
+ allowInfinityPoint: "boolean",
2304
+ clearCofactor: "function",
2305
+ isTorsionFree: "function",
2306
+ fromBytes: "function",
2307
+ toBytes: "function",
2308
+ endo: "object"
2309
+ });
2310
+ const { endo } = extraOpts;
2311
+ if (endo) {
2312
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
2313
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
2314
+ }
2315
+ }
2316
+ const lengths = getWLengths(Fp, Fn);
2317
+ function assertCompressionIsSupported() {
2318
+ if (!Fp.isOdd)
2319
+ throw new Error("compression is not supported: Field does not have .isOdd()");
2320
+ }
2321
+ __name(assertCompressionIsSupported, "assertCompressionIsSupported");
2322
+ function pointToBytes(_c, point, isCompressed) {
2323
+ const { x, y } = point.toAffine();
2324
+ const bx = Fp.toBytes(x);
2325
+ abool(isCompressed, "isCompressed");
2326
+ if (isCompressed) {
2327
+ assertCompressionIsSupported();
2328
+ const hasEvenY = !Fp.isOdd(y);
2329
+ return concatBytes(pprefix(hasEvenY), bx);
2330
+ } else {
2331
+ return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
2332
+ }
2333
+ }
2334
+ __name(pointToBytes, "pointToBytes");
2335
+ function pointFromBytes(bytes) {
2336
+ abytes(bytes, void 0, "Point");
2337
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
2338
+ const length = bytes.length;
2339
+ const head = bytes[0];
2340
+ const tail = bytes.subarray(1);
2341
+ if (length === comp && (head === 2 || head === 3)) {
2342
+ const x = Fp.fromBytes(tail);
2343
+ if (!Fp.isValid(x))
2344
+ throw new Error("bad point: is not on curve, wrong x");
2345
+ const y2 = weierstrassEquation(x);
2346
+ let y;
2347
+ try {
2348
+ y = Fp.sqrt(y2);
2349
+ } catch (sqrtError) {
2350
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
2351
+ throw new Error("bad point: is not on curve, sqrt error" + err);
2352
+ }
2353
+ assertCompressionIsSupported();
2354
+ const evenY = Fp.isOdd(y);
2355
+ const evenH = (head & 1) === 1;
2356
+ if (evenH !== evenY)
2357
+ y = Fp.neg(y);
2358
+ return { x, y };
2359
+ } else if (length === uncomp && head === 4) {
2360
+ const L = Fp.BYTES;
2361
+ const x = Fp.fromBytes(tail.subarray(0, L));
2362
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
2363
+ if (!isValidXY(x, y))
2364
+ throw new Error("bad point: is not on curve");
2365
+ return { x, y };
2366
+ } else {
2367
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
2368
+ }
2369
+ }
2370
+ __name(pointFromBytes, "pointFromBytes");
2371
+ const encodePoint = extraOpts.toBytes || pointToBytes;
2372
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
2373
+ function weierstrassEquation(x) {
2374
+ const x2 = Fp.sqr(x);
2375
+ const x3 = Fp.mul(x2, x);
2376
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
2377
+ }
2378
+ __name(weierstrassEquation, "weierstrassEquation");
2379
+ function isValidXY(x, y) {
2380
+ const left = Fp.sqr(y);
2381
+ const right = weierstrassEquation(x);
2382
+ return Fp.eql(left, right);
2383
+ }
2384
+ __name(isValidXY, "isValidXY");
2385
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
2386
+ throw new Error("bad curve params: generator point");
2387
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
2388
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
2389
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
2390
+ throw new Error("bad curve params: a or b");
2391
+ function acoord(title, n, banZero = false) {
2392
+ if (!Fp.isValid(n) || banZero && Fp.is0(n))
2393
+ throw new Error(`bad point coordinate ${title}`);
2394
+ return n;
2395
+ }
2396
+ __name(acoord, "acoord");
2397
+ function aprjpoint(other) {
2398
+ if (!(other instanceof Point))
2399
+ throw new Error("Weierstrass Point expected");
2400
+ }
2401
+ __name(aprjpoint, "aprjpoint");
2402
+ function splitEndoScalarN(k) {
2403
+ if (!endo || !endo.basises)
2404
+ throw new Error("no endo");
2405
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
2406
+ }
2407
+ __name(splitEndoScalarN, "splitEndoScalarN");
2408
+ const toAffineMemo = memoized((p, iz) => {
2409
+ const { X, Y, Z } = p;
2410
+ if (Fp.eql(Z, Fp.ONE))
2411
+ return { x: X, y: Y };
2412
+ const is0 = p.is0();
2413
+ if (iz == null)
2414
+ iz = is0 ? Fp.ONE : Fp.inv(Z);
2415
+ const x = Fp.mul(X, iz);
2416
+ const y = Fp.mul(Y, iz);
2417
+ const zz = Fp.mul(Z, iz);
2418
+ if (is0)
2419
+ return { x: Fp.ZERO, y: Fp.ZERO };
2420
+ if (!Fp.eql(zz, Fp.ONE))
2421
+ throw new Error("invZ was invalid");
2422
+ return { x, y };
2423
+ });
2424
+ const assertValidMemo = memoized((p) => {
2425
+ if (p.is0()) {
2426
+ if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
2427
+ return;
2428
+ throw new Error("bad point: ZERO");
2429
+ }
2430
+ const { x, y } = p.toAffine();
2431
+ if (!Fp.isValid(x) || !Fp.isValid(y))
2432
+ throw new Error("bad point: x or y not field elements");
2433
+ if (!isValidXY(x, y))
2434
+ throw new Error("bad point: equation left != right");
2435
+ if (!p.isTorsionFree())
2436
+ throw new Error("bad point: not in prime-order subgroup");
2437
+ return true;
2438
+ });
2439
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
2440
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
2441
+ k1p = negateCt(k1neg, k1p);
2442
+ k2p = negateCt(k2neg, k2p);
2443
+ return k1p.add(k2p);
2444
+ }
2445
+ __name(finishEndo, "finishEndo");
2446
+ class Point {
2447
+ static {
2448
+ __name(this, "Point");
2449
+ }
2450
+ // base / generator point
2451
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
2452
+ // zero / infinity / identity point
2453
+ static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
2454
+ // 0, 1, 0
2455
+ // math field
2456
+ static Fp = Fp;
2457
+ // scalar field
2458
+ static Fn = Fn;
2459
+ X;
2460
+ Y;
2461
+ Z;
2462
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
2463
+ constructor(X, Y, Z) {
2464
+ this.X = acoord("x", X);
2465
+ this.Y = acoord("y", Y, true);
2466
+ this.Z = acoord("z", Z);
2467
+ Object.freeze(this);
2468
+ }
2469
+ static CURVE() {
2470
+ return CURVE;
2471
+ }
2472
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
2473
+ static fromAffine(p) {
2474
+ const { x, y } = p || {};
2475
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
2476
+ throw new Error("invalid affine point");
2477
+ if (p instanceof Point)
2478
+ throw new Error("projective point not allowed");
2479
+ if (Fp.is0(x) && Fp.is0(y))
2480
+ return Point.ZERO;
2481
+ return new Point(x, y, Fp.ONE);
2482
+ }
2483
+ static fromBytes(bytes) {
2484
+ const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
2485
+ P.assertValidity();
2486
+ return P;
2487
+ }
2488
+ static fromHex(hex) {
2489
+ return Point.fromBytes(hexToBytes(hex));
2490
+ }
2491
+ get x() {
2492
+ return this.toAffine().x;
2493
+ }
2494
+ get y() {
2495
+ return this.toAffine().y;
2496
+ }
2497
+ /**
2498
+ *
2499
+ * @param windowSize
2500
+ * @param isLazy true will defer table computation until the first multiplication
2501
+ * @returns
2502
+ */
2503
+ precompute(windowSize = 8, isLazy = true) {
2504
+ wnaf.createCache(this, windowSize);
2505
+ if (!isLazy)
2506
+ this.multiply(_3n2);
2507
+ return this;
2508
+ }
2509
+ // TODO: return `this`
2510
+ /** A point on curve is valid if it conforms to equation. */
2511
+ assertValidity() {
2512
+ assertValidMemo(this);
2513
+ }
2514
+ hasEvenY() {
2515
+ const { y } = this.toAffine();
2516
+ if (!Fp.isOdd)
2517
+ throw new Error("Field doesn't support isOdd");
2518
+ return !Fp.isOdd(y);
2519
+ }
2520
+ /** Compare one point to another. */
2521
+ equals(other) {
2522
+ aprjpoint(other);
2523
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2524
+ const { X: X2, Y: Y2, Z: Z2 } = other;
2525
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
2526
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
2527
+ return U1 && U2;
2528
+ }
2529
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
2530
+ negate() {
2531
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
2532
+ }
2533
+ // Renes-Costello-Batina exception-free doubling formula.
2534
+ // There is 30% faster Jacobian formula, but it is not complete.
2535
+ // https://eprint.iacr.org/2015/1060, algorithm 3
2536
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
2537
+ double() {
2538
+ const { a, b } = CURVE;
2539
+ const b3 = Fp.mul(b, _3n2);
2540
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2541
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
2542
+ let t0 = Fp.mul(X1, X1);
2543
+ let t1 = Fp.mul(Y1, Y1);
2544
+ let t2 = Fp.mul(Z1, Z1);
2545
+ let t3 = Fp.mul(X1, Y1);
2546
+ t3 = Fp.add(t3, t3);
2547
+ Z3 = Fp.mul(X1, Z1);
2548
+ Z3 = Fp.add(Z3, Z3);
2549
+ X3 = Fp.mul(a, Z3);
2550
+ Y3 = Fp.mul(b3, t2);
2551
+ Y3 = Fp.add(X3, Y3);
2552
+ X3 = Fp.sub(t1, Y3);
2553
+ Y3 = Fp.add(t1, Y3);
2554
+ Y3 = Fp.mul(X3, Y3);
2555
+ X3 = Fp.mul(t3, X3);
2556
+ Z3 = Fp.mul(b3, Z3);
2557
+ t2 = Fp.mul(a, t2);
2558
+ t3 = Fp.sub(t0, t2);
2559
+ t3 = Fp.mul(a, t3);
2560
+ t3 = Fp.add(t3, Z3);
2561
+ Z3 = Fp.add(t0, t0);
2562
+ t0 = Fp.add(Z3, t0);
2563
+ t0 = Fp.add(t0, t2);
2564
+ t0 = Fp.mul(t0, t3);
2565
+ Y3 = Fp.add(Y3, t0);
2566
+ t2 = Fp.mul(Y1, Z1);
2567
+ t2 = Fp.add(t2, t2);
2568
+ t0 = Fp.mul(t2, t3);
2569
+ X3 = Fp.sub(X3, t0);
2570
+ Z3 = Fp.mul(t2, t1);
2571
+ Z3 = Fp.add(Z3, Z3);
2572
+ Z3 = Fp.add(Z3, Z3);
2573
+ return new Point(X3, Y3, Z3);
2574
+ }
2575
+ // Renes-Costello-Batina exception-free addition formula.
2576
+ // There is 30% faster Jacobian formula, but it is not complete.
2577
+ // https://eprint.iacr.org/2015/1060, algorithm 1
2578
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
2579
+ add(other) {
2580
+ aprjpoint(other);
2581
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2582
+ const { X: X2, Y: Y2, Z: Z2 } = other;
2583
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
2584
+ const a = CURVE.a;
2585
+ const b3 = Fp.mul(CURVE.b, _3n2);
2586
+ let t0 = Fp.mul(X1, X2);
2587
+ let t1 = Fp.mul(Y1, Y2);
2588
+ let t2 = Fp.mul(Z1, Z2);
2589
+ let t3 = Fp.add(X1, Y1);
2590
+ let t4 = Fp.add(X2, Y2);
2591
+ t3 = Fp.mul(t3, t4);
2592
+ t4 = Fp.add(t0, t1);
2593
+ t3 = Fp.sub(t3, t4);
2594
+ t4 = Fp.add(X1, Z1);
2595
+ let t5 = Fp.add(X2, Z2);
2596
+ t4 = Fp.mul(t4, t5);
2597
+ t5 = Fp.add(t0, t2);
2598
+ t4 = Fp.sub(t4, t5);
2599
+ t5 = Fp.add(Y1, Z1);
2600
+ X3 = Fp.add(Y2, Z2);
2601
+ t5 = Fp.mul(t5, X3);
2602
+ X3 = Fp.add(t1, t2);
2603
+ t5 = Fp.sub(t5, X3);
2604
+ Z3 = Fp.mul(a, t4);
2605
+ X3 = Fp.mul(b3, t2);
2606
+ Z3 = Fp.add(X3, Z3);
2607
+ X3 = Fp.sub(t1, Z3);
2608
+ Z3 = Fp.add(t1, Z3);
2609
+ Y3 = Fp.mul(X3, Z3);
2610
+ t1 = Fp.add(t0, t0);
2611
+ t1 = Fp.add(t1, t0);
2612
+ t2 = Fp.mul(a, t2);
2613
+ t4 = Fp.mul(b3, t4);
2614
+ t1 = Fp.add(t1, t2);
2615
+ t2 = Fp.sub(t0, t2);
2616
+ t2 = Fp.mul(a, t2);
2617
+ t4 = Fp.add(t4, t2);
2618
+ t0 = Fp.mul(t1, t4);
2619
+ Y3 = Fp.add(Y3, t0);
2620
+ t0 = Fp.mul(t5, t4);
2621
+ X3 = Fp.mul(t3, X3);
2622
+ X3 = Fp.sub(X3, t0);
2623
+ t0 = Fp.mul(t3, t1);
2624
+ Z3 = Fp.mul(t5, Z3);
2625
+ Z3 = Fp.add(Z3, t0);
2626
+ return new Point(X3, Y3, Z3);
2627
+ }
2628
+ subtract(other) {
2629
+ return this.add(other.negate());
2630
+ }
2631
+ is0() {
2632
+ return this.equals(Point.ZERO);
2633
+ }
2634
+ /**
2635
+ * Constant time multiplication.
2636
+ * Uses wNAF method. Windowed method may be 10% faster,
2637
+ * but takes 2x longer to generate and consumes 2x memory.
2638
+ * Uses precomputes when available.
2639
+ * Uses endomorphism for Koblitz curves.
2640
+ * @param scalar by which the point would be multiplied
2641
+ * @returns New point
2642
+ */
2643
+ multiply(scalar) {
2644
+ const { endo: endo2 } = extraOpts;
2645
+ if (!Fn.isValidNot0(scalar))
2646
+ throw new Error("invalid scalar: out of range");
2647
+ let point, fake;
2648
+ const mul = /* @__PURE__ */ __name((n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p)), "mul");
2649
+ if (endo2) {
2650
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
2651
+ const { p: k1p, f: k1f } = mul(k1);
2652
+ const { p: k2p, f: k2f } = mul(k2);
2653
+ fake = k1f.add(k2f);
2654
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
2655
+ } else {
2656
+ const { p, f } = mul(scalar);
2657
+ point = p;
2658
+ fake = f;
2659
+ }
2660
+ return normalizeZ(Point, [point, fake])[0];
2661
+ }
2662
+ /**
2663
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
2664
+ * It's faster, but should only be used when you don't care about
2665
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
2666
+ */
2667
+ multiplyUnsafe(sc) {
2668
+ const { endo: endo2 } = extraOpts;
2669
+ const p = this;
2670
+ if (!Fn.isValid(sc))
2671
+ throw new Error("invalid scalar: out of range");
2672
+ if (sc === _0n5 || p.is0())
2673
+ return Point.ZERO;
2674
+ if (sc === _1n6)
2675
+ return p;
2676
+ if (wnaf.hasCache(this))
2677
+ return this.multiply(sc);
2678
+ if (endo2) {
2679
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
2680
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
2681
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
2682
+ } else {
2683
+ return wnaf.unsafe(p, sc);
2684
+ }
2685
+ }
2686
+ /**
2687
+ * Converts Projective point to affine (x, y) coordinates.
2688
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
2689
+ */
2690
+ toAffine(invertedZ) {
2691
+ return toAffineMemo(this, invertedZ);
2692
+ }
2693
+ /**
2694
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
2695
+ * Always torsion-free for cofactor=1 curves.
2696
+ */
2697
+ isTorsionFree() {
2698
+ const { isTorsionFree } = extraOpts;
2699
+ if (cofactor === _1n6)
2700
+ return true;
2701
+ if (isTorsionFree)
2702
+ return isTorsionFree(Point, this);
2703
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
2704
+ }
2705
+ clearCofactor() {
2706
+ const { clearCofactor } = extraOpts;
2707
+ if (cofactor === _1n6)
2708
+ return this;
2709
+ if (clearCofactor)
2710
+ return clearCofactor(Point, this);
2711
+ return this.multiplyUnsafe(cofactor);
2712
+ }
2713
+ isSmallOrder() {
2714
+ return this.multiplyUnsafe(cofactor).is0();
2715
+ }
2716
+ toBytes(isCompressed = true) {
2717
+ abool(isCompressed, "isCompressed");
2718
+ this.assertValidity();
2719
+ return encodePoint(Point, this, isCompressed);
2720
+ }
2721
+ toHex(isCompressed = true) {
2722
+ return bytesToHex(this.toBytes(isCompressed));
2723
+ }
2724
+ toString() {
2725
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
2726
+ }
2727
+ }
2728
+ const bits = Fn.BITS;
2729
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
2730
+ Point.BASE.precompute(8);
2731
+ return Point;
2732
+ }
2733
+ __name(weierstrass, "weierstrass");
2734
+ function pprefix(hasEvenY) {
2735
+ return Uint8Array.of(hasEvenY ? 2 : 3);
2736
+ }
2737
+ __name(pprefix, "pprefix");
2738
+ function getWLengths(Fp, Fn) {
2739
+ return {
2740
+ secretKey: Fn.BYTES,
2741
+ publicKey: 1 + Fp.BYTES,
2742
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
2743
+ publicKeyHasPrefix: true,
2744
+ signature: 2 * Fn.BYTES
2745
+ };
2746
+ }
2747
+ __name(getWLengths, "getWLengths");
2748
+ function ecdh(Point, ecdhOpts = {}) {
2749
+ const { Fn } = Point;
2750
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes;
2751
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
2752
+ function isValidSecretKey(secretKey) {
2753
+ try {
2754
+ const num = Fn.fromBytes(secretKey);
2755
+ return Fn.isValidNot0(num);
2756
+ } catch (error) {
2757
+ return false;
2758
+ }
2759
+ }
2760
+ __name(isValidSecretKey, "isValidSecretKey");
2761
+ function isValidPublicKey(publicKey, isCompressed) {
2762
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
2763
+ try {
2764
+ const l = publicKey.length;
2765
+ if (isCompressed === true && l !== comp)
2766
+ return false;
2767
+ if (isCompressed === false && l !== publicKeyUncompressed)
2768
+ return false;
2769
+ return !!Point.fromBytes(publicKey);
2770
+ } catch (error) {
2771
+ return false;
2772
+ }
2773
+ }
2774
+ __name(isValidPublicKey, "isValidPublicKey");
2775
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
2776
+ return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
2777
+ }
2778
+ __name(randomSecretKey, "randomSecretKey");
2779
+ function getPublicKey(secretKey, isCompressed = true) {
2780
+ return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
2781
+ }
2782
+ __name(getPublicKey, "getPublicKey");
2783
+ function isProbPub(item) {
2784
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
2785
+ if (!isBytes(item))
2786
+ return void 0;
2787
+ if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
2788
+ return void 0;
2789
+ const l = abytes(item, void 0, "key").length;
2790
+ return l === publicKey || l === publicKeyUncompressed;
2791
+ }
2792
+ __name(isProbPub, "isProbPub");
2793
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
2794
+ if (isProbPub(secretKeyA) === true)
2795
+ throw new Error("first arg must be private key");
2796
+ if (isProbPub(publicKeyB) === false)
2797
+ throw new Error("second arg must be public key");
2798
+ const s = Fn.fromBytes(secretKeyA);
2799
+ const b = Point.fromBytes(publicKeyB);
2800
+ return b.multiply(s).toBytes(isCompressed);
2801
+ }
2802
+ __name(getSharedSecret, "getSharedSecret");
2803
+ const utils = {
2804
+ isValidSecretKey,
2805
+ isValidPublicKey,
2806
+ randomSecretKey
2807
+ };
2808
+ const keygen = createKeygen(randomSecretKey, getPublicKey);
2809
+ return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
2810
+ }
2811
+ __name(ecdh, "ecdh");
2812
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
2813
+ ahash(hash);
2814
+ validateObject(ecdsaOpts, {}, {
2815
+ hmac: "function",
2816
+ lowS: "boolean",
2817
+ randomBytes: "function",
2818
+ bits2int: "function",
2819
+ bits2int_modN: "function"
2820
+ });
2821
+ ecdsaOpts = Object.assign({}, ecdsaOpts);
2822
+ const randomBytes2 = ecdsaOpts.randomBytes || randomBytes;
2823
+ const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
2824
+ const { Fp, Fn } = Point;
2825
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
2826
+ const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
2827
+ const defaultSigOpts = {
2828
+ prehash: true,
2829
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
2830
+ format: "compact",
2831
+ extraEntropy: false
2832
+ };
2833
+ const hasLargeCofactor = CURVE_ORDER * _2n4 < Fp.ORDER;
2834
+ function isBiggerThanHalfOrder(number) {
2835
+ const HALF = CURVE_ORDER >> _1n6;
2836
+ return number > HALF;
2837
+ }
2838
+ __name(isBiggerThanHalfOrder, "isBiggerThanHalfOrder");
2839
+ function validateRS(title, num) {
2840
+ if (!Fn.isValidNot0(num))
2841
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
2842
+ return num;
2843
+ }
2844
+ __name(validateRS, "validateRS");
2845
+ function assertSmallCofactor() {
2846
+ if (hasLargeCofactor)
2847
+ throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
2848
+ }
2849
+ __name(assertSmallCofactor, "assertSmallCofactor");
2850
+ function validateSigLength(bytes, format) {
2851
+ validateSigFormat(format);
2852
+ const size = lengths.signature;
2853
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
2854
+ return abytes(bytes, sizer);
2855
+ }
2856
+ __name(validateSigLength, "validateSigLength");
2857
+ class Signature {
2858
+ static {
2859
+ __name(this, "Signature");
2860
+ }
2861
+ r;
2862
+ s;
2863
+ recovery;
2864
+ constructor(r, s, recovery) {
2865
+ this.r = validateRS("r", r);
2866
+ this.s = validateRS("s", s);
2867
+ if (recovery != null) {
2868
+ assertSmallCofactor();
2869
+ if (![0, 1, 2, 3].includes(recovery))
2870
+ throw new Error("invalid recovery id");
2871
+ this.recovery = recovery;
2872
+ }
2873
+ Object.freeze(this);
2874
+ }
2875
+ static fromBytes(bytes, format = defaultSigOpts.format) {
2876
+ validateSigLength(bytes, format);
2877
+ let recid;
2878
+ if (format === "der") {
2879
+ const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
2880
+ return new Signature(r2, s2);
2881
+ }
2882
+ if (format === "recovered") {
2883
+ recid = bytes[0];
2884
+ format = "compact";
2885
+ bytes = bytes.subarray(1);
2886
+ }
2887
+ const L = lengths.signature / 2;
2888
+ const r = bytes.subarray(0, L);
2889
+ const s = bytes.subarray(L, L * 2);
2890
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
2891
+ }
2892
+ static fromHex(hex, format) {
2893
+ return this.fromBytes(hexToBytes(hex), format);
2894
+ }
2895
+ assertRecovery() {
2896
+ const { recovery } = this;
2897
+ if (recovery == null)
2898
+ throw new Error("invalid recovery id: must be present");
2899
+ return recovery;
2900
+ }
2901
+ addRecoveryBit(recovery) {
2902
+ return new Signature(this.r, this.s, recovery);
2903
+ }
2904
+ recoverPublicKey(messageHash) {
2905
+ const { r, s } = this;
2906
+ const recovery = this.assertRecovery();
2907
+ const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;
2908
+ if (!Fp.isValid(radj))
2909
+ throw new Error("invalid recovery id: sig.r+curve.n != R.x");
2910
+ const x = Fp.toBytes(radj);
2911
+ const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
2912
+ const ir = Fn.inv(radj);
2913
+ const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
2914
+ const u1 = Fn.create(-h * ir);
2915
+ const u2 = Fn.create(s * ir);
2916
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
2917
+ if (Q.is0())
2918
+ throw new Error("invalid recovery: point at infinify");
2919
+ Q.assertValidity();
2920
+ return Q;
2921
+ }
2922
+ // Signatures should be low-s, to prevent malleability.
2923
+ hasHighS() {
2924
+ return isBiggerThanHalfOrder(this.s);
2925
+ }
2926
+ toBytes(format = defaultSigOpts.format) {
2927
+ validateSigFormat(format);
2928
+ if (format === "der")
2929
+ return hexToBytes(DER.hexFromSig(this));
2930
+ const { r, s } = this;
2931
+ const rb = Fn.toBytes(r);
2932
+ const sb = Fn.toBytes(s);
2933
+ if (format === "recovered") {
2934
+ assertSmallCofactor();
2935
+ return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
2936
+ }
2937
+ return concatBytes(rb, sb);
2938
+ }
2939
+ toHex(format) {
2940
+ return bytesToHex(this.toBytes(format));
2941
+ }
2942
+ }
2943
+ const bits2int = ecdsaOpts.bits2int || /* @__PURE__ */ __name(function bits2int_def(bytes) {
2944
+ if (bytes.length > 8192)
2945
+ throw new Error("input is too large");
2946
+ const num = bytesToNumberBE(bytes);
2947
+ const delta = bytes.length * 8 - fnBits;
2948
+ return delta > 0 ? num >> BigInt(delta) : num;
2949
+ }, "bits2int_def");
2950
+ const bits2int_modN = ecdsaOpts.bits2int_modN || /* @__PURE__ */ __name(function bits2int_modN_def(bytes) {
2951
+ return Fn.create(bits2int(bytes));
2952
+ }, "bits2int_modN_def");
2953
+ const ORDER_MASK = bitMask(fnBits);
2954
+ function int2octets(num) {
2955
+ aInRange("num < 2^" + fnBits, num, _0n5, ORDER_MASK);
2956
+ return Fn.toBytes(num);
2957
+ }
2958
+ __name(int2octets, "int2octets");
2959
+ function validateMsgAndHash(message, prehash) {
2960
+ abytes(message, void 0, "message");
2961
+ return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
2962
+ }
2963
+ __name(validateMsgAndHash, "validateMsgAndHash");
2964
+ function prepSig(message, secretKey, opts) {
2965
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
2966
+ message = validateMsgAndHash(message, prehash);
2967
+ const h1int = bits2int_modN(message);
2968
+ const d = Fn.fromBytes(secretKey);
2969
+ if (!Fn.isValidNot0(d))
2970
+ throw new Error("invalid private key");
2971
+ const seedArgs = [int2octets(d), int2octets(h1int)];
2972
+ if (extraEntropy != null && extraEntropy !== false) {
2973
+ const e = extraEntropy === true ? randomBytes2(lengths.secretKey) : extraEntropy;
2974
+ seedArgs.push(abytes(e, void 0, "extraEntropy"));
2975
+ }
2976
+ const seed = concatBytes(...seedArgs);
2977
+ const m = h1int;
2978
+ function k2sig(kBytes) {
2979
+ const k = bits2int(kBytes);
2980
+ if (!Fn.isValidNot0(k))
2981
+ return;
2982
+ const ik = Fn.inv(k);
2983
+ const q = Point.BASE.multiply(k).toAffine();
2984
+ const r = Fn.create(q.x);
2985
+ if (r === _0n5)
2986
+ return;
2987
+ const s = Fn.create(ik * Fn.create(m + r * d));
2988
+ if (s === _0n5)
2989
+ return;
2990
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n6);
2991
+ let normS = s;
2992
+ if (lowS && isBiggerThanHalfOrder(s)) {
2993
+ normS = Fn.neg(s);
2994
+ recovery ^= 1;
2995
+ }
2996
+ return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
2997
+ }
2998
+ __name(k2sig, "k2sig");
2999
+ return { seed, k2sig };
3000
+ }
3001
+ __name(prepSig, "prepSig");
3002
+ function sign(message, secretKey, opts = {}) {
3003
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
3004
+ const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
3005
+ const sig = drbg(seed, k2sig);
3006
+ return sig.toBytes(opts.format);
3007
+ }
3008
+ __name(sign, "sign");
3009
+ function verify(signature, message, publicKey, opts = {}) {
3010
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
3011
+ publicKey = abytes(publicKey, void 0, "publicKey");
3012
+ message = validateMsgAndHash(message, prehash);
3013
+ if (!isBytes(signature)) {
3014
+ const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
3015
+ throw new Error("verify expects Uint8Array signature" + end);
3016
+ }
3017
+ validateSigLength(signature, format);
3018
+ try {
3019
+ const sig = Signature.fromBytes(signature, format);
3020
+ const P = Point.fromBytes(publicKey);
3021
+ if (lowS && sig.hasHighS())
3022
+ return false;
3023
+ const { r, s } = sig;
3024
+ const h = bits2int_modN(message);
3025
+ const is = Fn.inv(s);
3026
+ const u1 = Fn.create(h * is);
3027
+ const u2 = Fn.create(r * is);
3028
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
3029
+ if (R.is0())
3030
+ return false;
3031
+ const v = Fn.create(R.x);
3032
+ return v === r;
3033
+ } catch (e) {
3034
+ return false;
3035
+ }
3036
+ }
3037
+ __name(verify, "verify");
3038
+ function recoverPublicKey(signature, message, opts = {}) {
3039
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
3040
+ message = validateMsgAndHash(message, prehash);
3041
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
3042
+ }
3043
+ __name(recoverPublicKey, "recoverPublicKey");
3044
+ return Object.freeze({
3045
+ keygen,
3046
+ getPublicKey,
3047
+ getSharedSecret,
3048
+ utils,
3049
+ lengths,
3050
+ Point,
3051
+ sign,
3052
+ verify,
3053
+ recoverPublicKey,
3054
+ Signature,
3055
+ hash
3056
+ });
3057
+ }
3058
+ __name(ecdsa, "ecdsa");
3059
+
3060
+ // ../../node_modules/@noble/curves/secp256k1.js
3061
+ var secp256k1_CURVE = {
3062
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
3063
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
3064
+ h: BigInt(1),
3065
+ a: BigInt(0),
3066
+ b: BigInt(7),
3067
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
3068
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
3069
+ };
3070
+ var secp256k1_ENDO = {
3071
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
3072
+ basises: [
3073
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
3074
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
3075
+ ]
3076
+ };
3077
+ var _2n5 = /* @__PURE__ */ BigInt(2);
3078
+ function sqrtMod(y) {
3079
+ const P = secp256k1_CURVE.p;
3080
+ const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
3081
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
3082
+ const b2 = y * y * y % P;
3083
+ const b3 = b2 * b2 * y % P;
3084
+ const b6 = pow2(b3, _3n3, P) * b3 % P;
3085
+ const b9 = pow2(b6, _3n3, P) * b3 % P;
3086
+ const b11 = pow2(b9, _2n5, P) * b2 % P;
3087
+ const b22 = pow2(b11, _11n, P) * b11 % P;
3088
+ const b44 = pow2(b22, _22n, P) * b22 % P;
3089
+ const b88 = pow2(b44, _44n, P) * b44 % P;
3090
+ const b176 = pow2(b88, _88n, P) * b88 % P;
3091
+ const b220 = pow2(b176, _44n, P) * b44 % P;
3092
+ const b223 = pow2(b220, _3n3, P) * b3 % P;
3093
+ const t1 = pow2(b223, _23n, P) * b22 % P;
3094
+ const t2 = pow2(t1, _6n, P) * b2 % P;
3095
+ const root = pow2(t2, _2n5, P);
3096
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
3097
+ throw new Error("Cannot find square root");
3098
+ return root;
3099
+ }
3100
+ __name(sqrtMod, "sqrtMod");
3101
+ var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
3102
+ var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
3103
+ Fp: Fpk1,
3104
+ endo: secp256k1_ENDO
3105
+ });
3106
+ var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256);
3107
+
1959
3108
  // node_modules/base58-js/base58_chars.js
1960
3109
  var base58_chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
1961
3110
  var base58_chars_default = base58_chars;
@@ -2025,494 +3174,6 @@ var NearUtils = (() => {
2025
3174
  __name(binary_to_base58, "binary_to_base58");
2026
3175
  var binary_to_base58_default = binary_to_base58;
2027
3176
 
2028
- // ../../node_modules/big.js/big.mjs
2029
- var DP = 20;
2030
- var RM = 1;
2031
- var MAX_DP = 1e6;
2032
- var MAX_POWER = 1e6;
2033
- var NE = -7;
2034
- var PE = 21;
2035
- var STRICT = false;
2036
- var NAME = "[big.js] ";
2037
- var INVALID = NAME + "Invalid ";
2038
- var INVALID_DP = INVALID + "decimal places";
2039
- var INVALID_RM = INVALID + "rounding mode";
2040
- var DIV_BY_ZERO = NAME + "Division by zero";
2041
- var P = {};
2042
- var UNDEFINED = void 0;
2043
- var NUMERIC = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;
2044
- function _Big_() {
2045
- function Big2(n) {
2046
- var x = this;
2047
- if (!(x instanceof Big2)) return n === UNDEFINED ? _Big_() : new Big2(n);
2048
- if (n instanceof Big2) {
2049
- x.s = n.s;
2050
- x.e = n.e;
2051
- x.c = n.c.slice();
2052
- } else {
2053
- if (typeof n !== "string") {
2054
- if (Big2.strict === true && typeof n !== "bigint") {
2055
- throw TypeError(INVALID + "value");
2056
- }
2057
- n = n === 0 && 1 / n < 0 ? "-0" : String(n);
2058
- }
2059
- parse(x, n);
2060
- }
2061
- x.constructor = Big2;
2062
- }
2063
- __name(Big2, "Big");
2064
- Big2.prototype = P;
2065
- Big2.DP = DP;
2066
- Big2.RM = RM;
2067
- Big2.NE = NE;
2068
- Big2.PE = PE;
2069
- Big2.strict = STRICT;
2070
- Big2.roundDown = 0;
2071
- Big2.roundHalfUp = 1;
2072
- Big2.roundHalfEven = 2;
2073
- Big2.roundUp = 3;
2074
- return Big2;
2075
- }
2076
- __name(_Big_, "_Big_");
2077
- function parse(x, n) {
2078
- var e, i, nl;
2079
- if (!NUMERIC.test(n)) {
2080
- throw Error(INVALID + "number");
2081
- }
2082
- x.s = n.charAt(0) == "-" ? (n = n.slice(1), -1) : 1;
2083
- if ((e = n.indexOf(".")) > -1) n = n.replace(".", "");
2084
- if ((i = n.search(/e/i)) > 0) {
2085
- if (e < 0) e = i;
2086
- e += +n.slice(i + 1);
2087
- n = n.substring(0, i);
2088
- } else if (e < 0) {
2089
- e = n.length;
2090
- }
2091
- nl = n.length;
2092
- for (i = 0; i < nl && n.charAt(i) == "0"; ) ++i;
2093
- if (i == nl) {
2094
- x.c = [x.e = 0];
2095
- } else {
2096
- for (; nl > 0 && n.charAt(--nl) == "0"; ) ;
2097
- x.e = e - i - 1;
2098
- x.c = [];
2099
- for (e = 0; i <= nl; ) x.c[e++] = +n.charAt(i++);
2100
- }
2101
- return x;
2102
- }
2103
- __name(parse, "parse");
2104
- function round(x, sd, rm, more) {
2105
- var xc = x.c;
2106
- if (rm === UNDEFINED) rm = x.constructor.RM;
2107
- if (rm !== 0 && rm !== 1 && rm !== 2 && rm !== 3) {
2108
- throw Error(INVALID_RM);
2109
- }
2110
- if (sd < 1) {
2111
- 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)));
2112
- xc.length = 1;
2113
- if (more) {
2114
- x.e = x.e - sd + 1;
2115
- xc[0] = 1;
2116
- } else {
2117
- xc[0] = x.e = 0;
2118
- }
2119
- } else if (sd < xc.length) {
2120
- 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]);
2121
- xc.length = sd;
2122
- if (more) {
2123
- for (; ++xc[--sd] > 9; ) {
2124
- xc[sd] = 0;
2125
- if (sd === 0) {
2126
- ++x.e;
2127
- xc.unshift(1);
2128
- break;
2129
- }
2130
- }
2131
- }
2132
- for (sd = xc.length; !xc[--sd]; ) xc.pop();
2133
- }
2134
- return x;
2135
- }
2136
- __name(round, "round");
2137
- function stringify(x, doExponential, isNonzero) {
2138
- var e = x.e, s = x.c.join(""), n = s.length;
2139
- if (doExponential) {
2140
- s = s.charAt(0) + (n > 1 ? "." + s.slice(1) : "") + (e < 0 ? "e" : "e+") + e;
2141
- } else if (e < 0) {
2142
- for (; ++e; ) s = "0" + s;
2143
- s = "0." + s;
2144
- } else if (e > 0) {
2145
- if (++e > n) {
2146
- for (e -= n; e--; ) s += "0";
2147
- } else if (e < n) {
2148
- s = s.slice(0, e) + "." + s.slice(e);
2149
- }
2150
- } else if (n > 1) {
2151
- s = s.charAt(0) + "." + s.slice(1);
2152
- }
2153
- return x.s < 0 && isNonzero ? "-" + s : s;
2154
- }
2155
- __name(stringify, "stringify");
2156
- P.abs = function() {
2157
- var x = new this.constructor(this);
2158
- x.s = 1;
2159
- return x;
2160
- };
2161
- P.cmp = function(y) {
2162
- 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;
2163
- if (!xc[0] || !yc[0]) return !xc[0] ? !yc[0] ? 0 : -j : i;
2164
- if (i != j) return i;
2165
- isneg = i < 0;
2166
- if (k != l) return k > l ^ isneg ? 1 : -1;
2167
- j = (k = xc.length) < (l = yc.length) ? k : l;
2168
- for (i = -1; ++i < j; ) {
2169
- if (xc[i] != yc[i]) return xc[i] > yc[i] ^ isneg ? 1 : -1;
2170
- }
2171
- return k == l ? 0 : k > l ^ isneg ? 1 : -1;
2172
- };
2173
- P.div = function(y) {
2174
- 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;
2175
- if (dp !== ~~dp || dp < 0 || dp > MAX_DP) {
2176
- throw Error(INVALID_DP);
2177
- }
2178
- if (!b[0]) {
2179
- throw Error(DIV_BY_ZERO);
2180
- }
2181
- if (!a[0]) {
2182
- y.s = k;
2183
- y.c = [y.e = 0];
2184
- return y;
2185
- }
2186
- 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;
2187
- q.s = k;
2188
- k = p < 0 ? 0 : p;
2189
- bz.unshift(0);
2190
- for (; rl++ < bl; ) r.push(0);
2191
- do {
2192
- for (n = 0; n < 10; n++) {
2193
- if (bl != (rl = r.length)) {
2194
- cmp = bl > rl ? 1 : -1;
2195
- } else {
2196
- for (ri = -1, cmp = 0; ++ri < bl; ) {
2197
- if (b[ri] != r[ri]) {
2198
- cmp = b[ri] > r[ri] ? 1 : -1;
2199
- break;
2200
- }
2201
- }
2202
- }
2203
- if (cmp < 0) {
2204
- for (bt = rl == bl ? b : bz; rl; ) {
2205
- if (r[--rl] < bt[rl]) {
2206
- ri = rl;
2207
- for (; ri && !r[--ri]; ) r[ri] = 9;
2208
- --r[ri];
2209
- r[rl] += 10;
2210
- }
2211
- r[rl] -= bt[rl];
2212
- }
2213
- for (; !r[0]; ) r.shift();
2214
- } else {
2215
- break;
2216
- }
2217
- }
2218
- qc[qi++] = cmp ? n : ++n;
2219
- if (r[0] && cmp) r[rl] = a[ai] || 0;
2220
- else r = [a[ai]];
2221
- } while ((ai++ < al || r[0] !== UNDEFINED) && k--);
2222
- if (!qc[0] && qi != 1) {
2223
- qc.shift();
2224
- q.e--;
2225
- p--;
2226
- }
2227
- if (qi > p) round(q, p, Big2.RM, r[0] !== UNDEFINED);
2228
- return q;
2229
- };
2230
- P.eq = function(y) {
2231
- return this.cmp(y) === 0;
2232
- };
2233
- P.gt = function(y) {
2234
- return this.cmp(y) > 0;
2235
- };
2236
- P.gte = function(y) {
2237
- return this.cmp(y) > -1;
2238
- };
2239
- P.lt = function(y) {
2240
- return this.cmp(y) < 0;
2241
- };
2242
- P.lte = function(y) {
2243
- return this.cmp(y) < 1;
2244
- };
2245
- P.minus = P.sub = function(y) {
2246
- var i, j, t, xlty, x = this, Big2 = x.constructor, a = x.s, b = (y = new Big2(y)).s;
2247
- if (a != b) {
2248
- y.s = -b;
2249
- return x.plus(y);
2250
- }
2251
- var xc = x.c.slice(), xe = x.e, yc = y.c, ye = y.e;
2252
- if (!xc[0] || !yc[0]) {
2253
- if (yc[0]) {
2254
- y.s = -b;
2255
- } else if (xc[0]) {
2256
- y = new Big2(x);
2257
- } else {
2258
- y.s = 1;
2259
- }
2260
- return y;
2261
- }
2262
- if (a = xe - ye) {
2263
- if (xlty = a < 0) {
2264
- a = -a;
2265
- t = xc;
2266
- } else {
2267
- ye = xe;
2268
- t = yc;
2269
- }
2270
- t.reverse();
2271
- for (b = a; b--; ) t.push(0);
2272
- t.reverse();
2273
- } else {
2274
- j = ((xlty = xc.length < yc.length) ? xc : yc).length;
2275
- for (a = b = 0; b < j; b++) {
2276
- if (xc[b] != yc[b]) {
2277
- xlty = xc[b] < yc[b];
2278
- break;
2279
- }
2280
- }
2281
- }
2282
- if (xlty) {
2283
- t = xc;
2284
- xc = yc;
2285
- yc = t;
2286
- y.s = -y.s;
2287
- }
2288
- if ((b = (j = yc.length) - (i = xc.length)) > 0) for (; b--; ) xc[i++] = 0;
2289
- for (b = i; j > a; ) {
2290
- if (xc[--j] < yc[j]) {
2291
- for (i = j; i && !xc[--i]; ) xc[i] = 9;
2292
- --xc[i];
2293
- xc[j] += 10;
2294
- }
2295
- xc[j] -= yc[j];
2296
- }
2297
- for (; xc[--b] === 0; ) xc.pop();
2298
- for (; xc[0] === 0; ) {
2299
- xc.shift();
2300
- --ye;
2301
- }
2302
- if (!xc[0]) {
2303
- y.s = 1;
2304
- xc = [ye = 0];
2305
- }
2306
- y.c = xc;
2307
- y.e = ye;
2308
- return y;
2309
- };
2310
- P.mod = function(y) {
2311
- var ygtx, x = this, Big2 = x.constructor, a = x.s, b = (y = new Big2(y)).s;
2312
- if (!y.c[0]) {
2313
- throw Error(DIV_BY_ZERO);
2314
- }
2315
- x.s = y.s = 1;
2316
- ygtx = y.cmp(x) == 1;
2317
- x.s = a;
2318
- y.s = b;
2319
- if (ygtx) return new Big2(x);
2320
- a = Big2.DP;
2321
- b = Big2.RM;
2322
- Big2.DP = Big2.RM = 0;
2323
- x = x.div(y);
2324
- Big2.DP = a;
2325
- Big2.RM = b;
2326
- return this.minus(x.times(y));
2327
- };
2328
- P.neg = function() {
2329
- var x = new this.constructor(this);
2330
- x.s = -x.s;
2331
- return x;
2332
- };
2333
- P.plus = P.add = function(y) {
2334
- var e, k, t, x = this, Big2 = x.constructor;
2335
- y = new Big2(y);
2336
- if (x.s != y.s) {
2337
- y.s = -y.s;
2338
- return x.minus(y);
2339
- }
2340
- var xe = x.e, xc = x.c, ye = y.e, yc = y.c;
2341
- if (!xc[0] || !yc[0]) {
2342
- if (!yc[0]) {
2343
- if (xc[0]) {
2344
- y = new Big2(x);
2345
- } else {
2346
- y.s = x.s;
2347
- }
2348
- }
2349
- return y;
2350
- }
2351
- xc = xc.slice();
2352
- if (e = xe - ye) {
2353
- if (e > 0) {
2354
- ye = xe;
2355
- t = yc;
2356
- } else {
2357
- e = -e;
2358
- t = xc;
2359
- }
2360
- t.reverse();
2361
- for (; e--; ) t.push(0);
2362
- t.reverse();
2363
- }
2364
- if (xc.length - yc.length < 0) {
2365
- t = yc;
2366
- yc = xc;
2367
- xc = t;
2368
- }
2369
- e = yc.length;
2370
- for (k = 0; e; xc[e] %= 10) k = (xc[--e] = xc[e] + yc[e] + k) / 10 | 0;
2371
- if (k) {
2372
- xc.unshift(k);
2373
- ++ye;
2374
- }
2375
- for (e = xc.length; xc[--e] === 0; ) xc.pop();
2376
- y.c = xc;
2377
- y.e = ye;
2378
- return y;
2379
- };
2380
- P.pow = function(n) {
2381
- var x = this, one = new x.constructor("1"), y = one, isneg = n < 0;
2382
- if (n !== ~~n || n < -MAX_POWER || n > MAX_POWER) {
2383
- throw Error(INVALID + "exponent");
2384
- }
2385
- if (isneg) n = -n;
2386
- for (; ; ) {
2387
- if (n & 1) y = y.times(x);
2388
- n >>= 1;
2389
- if (!n) break;
2390
- x = x.times(x);
2391
- }
2392
- return isneg ? one.div(y) : y;
2393
- };
2394
- P.prec = function(sd, rm) {
2395
- if (sd !== ~~sd || sd < 1 || sd > MAX_DP) {
2396
- throw Error(INVALID + "precision");
2397
- }
2398
- return round(new this.constructor(this), sd, rm);
2399
- };
2400
- P.round = function(dp, rm) {
2401
- if (dp === UNDEFINED) dp = 0;
2402
- else if (dp !== ~~dp || dp < -MAX_DP || dp > MAX_DP) {
2403
- throw Error(INVALID_DP);
2404
- }
2405
- return round(new this.constructor(this), dp + this.e + 1, rm);
2406
- };
2407
- P.sqrt = function() {
2408
- var r, c, t, x = this, Big2 = x.constructor, s = x.s, e = x.e, half = new Big2("0.5");
2409
- if (!x.c[0]) return new Big2(x);
2410
- if (s < 0) {
2411
- throw Error(NAME + "No square root");
2412
- }
2413
- s = Math.sqrt(+stringify(x, true, true));
2414
- if (s === 0 || s === 1 / 0) {
2415
- c = x.c.join("");
2416
- if (!(c.length + e & 1)) c += "0";
2417
- s = Math.sqrt(c);
2418
- e = ((e + 1) / 2 | 0) - (e < 0 || e & 1);
2419
- r = new Big2((s == 1 / 0 ? "5e" : (s = s.toExponential()).slice(0, s.indexOf("e") + 1)) + e);
2420
- } else {
2421
- r = new Big2(s + "");
2422
- }
2423
- e = r.e + (Big2.DP += 4);
2424
- do {
2425
- t = r;
2426
- r = half.times(t.plus(x.div(t)));
2427
- } while (t.c.slice(0, e).join("") !== r.c.slice(0, e).join(""));
2428
- return round(r, (Big2.DP -= 4) + r.e + 1, Big2.RM);
2429
- };
2430
- P.times = P.mul = function(y) {
2431
- 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;
2432
- y.s = x.s == y.s ? 1 : -1;
2433
- if (!xc[0] || !yc[0]) {
2434
- y.c = [y.e = 0];
2435
- return y;
2436
- }
2437
- y.e = i + j;
2438
- if (a < b) {
2439
- c = xc;
2440
- xc = yc;
2441
- yc = c;
2442
- j = a;
2443
- a = b;
2444
- b = j;
2445
- }
2446
- for (c = new Array(j = a + b); j--; ) c[j] = 0;
2447
- for (i = b; i--; ) {
2448
- b = 0;
2449
- for (j = a + i; j > i; ) {
2450
- b = c[j] + yc[i] * xc[j - i - 1] + b;
2451
- c[j--] = b % 10;
2452
- b = b / 10 | 0;
2453
- }
2454
- c[j] = b;
2455
- }
2456
- if (b) ++y.e;
2457
- else c.shift();
2458
- for (i = c.length; !c[--i]; ) c.pop();
2459
- y.c = c;
2460
- return y;
2461
- };
2462
- P.toExponential = function(dp, rm) {
2463
- var x = this, n = x.c[0];
2464
- if (dp !== UNDEFINED) {
2465
- if (dp !== ~~dp || dp < 0 || dp > MAX_DP) {
2466
- throw Error(INVALID_DP);
2467
- }
2468
- x = round(new x.constructor(x), ++dp, rm);
2469
- for (; x.c.length < dp; ) x.c.push(0);
2470
- }
2471
- return stringify(x, true, !!n);
2472
- };
2473
- P.toFixed = function(dp, rm) {
2474
- var x = this, n = x.c[0];
2475
- if (dp !== UNDEFINED) {
2476
- if (dp !== ~~dp || dp < 0 || dp > MAX_DP) {
2477
- throw Error(INVALID_DP);
2478
- }
2479
- x = round(new x.constructor(x), dp + x.e + 1, rm);
2480
- for (dp = dp + x.e + 1; x.c.length < dp; ) x.c.push(0);
2481
- }
2482
- return stringify(x, false, !!n);
2483
- };
2484
- P[Symbol.for("nodejs.util.inspect.custom")] = P.toJSON = P.toString = function() {
2485
- var x = this, Big2 = x.constructor;
2486
- return stringify(x, x.e <= Big2.NE || x.e >= Big2.PE, !!x.c[0]);
2487
- };
2488
- P.toNumber = function() {
2489
- var n = +stringify(this, true, true);
2490
- if (this.constructor.strict === true && !this.eq(n.toString())) {
2491
- throw Error(NAME + "Imprecise conversion");
2492
- }
2493
- return n;
2494
- };
2495
- P.toPrecision = function(sd, rm) {
2496
- var x = this, Big2 = x.constructor, n = x.c[0];
2497
- if (sd !== UNDEFINED) {
2498
- if (sd !== ~~sd || sd < 1 || sd > MAX_DP) {
2499
- throw Error(INVALID + "precision");
2500
- }
2501
- x = round(new Big2(x), sd, rm);
2502
- for (; x.c.length < sd; ) x.c.push(0);
2503
- }
2504
- return stringify(x, sd <= x.e || x.e <= Big2.NE || x.e >= Big2.PE, !!n);
2505
- };
2506
- P.valueOf = function() {
2507
- var x = this, Big2 = x.constructor;
2508
- if (Big2.strict === true) {
2509
- throw Error(NAME + "valueOf disallowed");
2510
- }
2511
- return stringify(x, x.e <= Big2.NE || x.e >= Big2.PE, true);
2512
- };
2513
- var Big = _Big_();
2514
- var big_default = Big;
2515
-
2516
3177
  // ../../node_modules/js-base64/base64.mjs
2517
3178
  var _hasBuffer = typeof Buffer === "function";
2518
3179
  var _TD = typeof TextDecoder === "function" ? new TextDecoder() : void 0;
@@ -2669,6 +3330,32 @@ var NearUtils = (() => {
2669
3330
  }
2670
3331
  }
2671
3332
  __name(fromBase64, "fromBase64");
3333
+ var UNIT_DECIMALS = {
3334
+ near: 24,
3335
+ tgas: 12,
3336
+ ggas: 9,
3337
+ gas: 0,
3338
+ yoctonear: 0
3339
+ };
3340
+ function scaleDecimal(amount, shift) {
3341
+ const [whole, frac = ""] = amount.split(".");
3342
+ if (shift >= 0) {
3343
+ const padded = frac.padEnd(shift, "0").slice(0, shift);
3344
+ const extra = frac.length > shift ? frac.slice(shift) : "";
3345
+ if (extra && BigInt(extra) !== 0n) {
3346
+ throw new Error(`Precision loss: "${amount}" has more than ${shift} decimal places`);
3347
+ }
3348
+ return BigInt(whole + padded).toString();
3349
+ }
3350
+ const divisor = 10n ** BigInt(-shift);
3351
+ const bigVal = BigInt(whole);
3352
+ const intPart = bigVal / divisor;
3353
+ const remainder = bigVal % divisor;
3354
+ if (remainder === 0n) return intPart.toString();
3355
+ const fracStr = remainder.toString().padStart(-shift, "0").replace(/0+$/, "");
3356
+ return `${intPart}.${fracStr}`;
3357
+ }
3358
+ __name(scaleDecimal, "scaleDecimal");
2672
3359
  function convertUnit(s, ...args) {
2673
3360
  if (Array.isArray(s)) {
2674
3361
  s = s.reduce((acc, part, i) => {
@@ -2681,25 +3368,15 @@ var NearUtils = (() => {
2681
3368
  const amount = match[1].replace(/[_,]/g, "");
2682
3369
  const unitPart = match[2];
2683
3370
  if (unitPart) {
2684
- switch (unitPart.toLowerCase()) {
2685
- case "near":
2686
- return big_default(amount).mul(big_default(10).pow(24)).toFixed(0);
2687
- case "tgas":
2688
- return big_default(amount).mul(big_default(10).pow(12)).toFixed(0);
2689
- case "ggas":
2690
- return big_default(amount).mul(big_default(10).pow(9)).toFixed(0);
2691
- case "gas":
2692
- case "yoctonear":
2693
- return big_default(amount).toFixed(0);
2694
- default:
2695
- throw new Error(`Unknown unit: ${unitPart}`);
2696
- }
3371
+ const decimals = UNIT_DECIMALS[unitPart.toLowerCase()];
3372
+ if (decimals === void 0) throw new Error(`Unknown unit: ${unitPart}`);
3373
+ return scaleDecimal(amount, decimals);
2697
3374
  } else {
2698
- return big_default(amount).toFixed(0);
3375
+ return scaleDecimal(amount, 0);
2699
3376
  }
2700
3377
  }
2701
3378
  }
2702
- return big_default(`${s}`).toFixed(0);
3379
+ return scaleDecimal(`${s}`, 0);
2703
3380
  }
2704
3381
  __name(convertUnit, "convertUnit");
2705
3382
  function lsSet(key, value) {
@@ -2741,35 +3418,61 @@ var NearUtils = (() => {
2741
3418
  }
2742
3419
  __name(parseJsonFromBytes, "parseJsonFromBytes");
2743
3420
  function canSignWithLAK(actions) {
2744
- return actions.length === 1 && actions[0].type === "FunctionCall" && big_default(actions[0]?.deposit ?? "0").eq(0);
3421
+ return actions.length === 1 && actions[0].type === "FunctionCall" && BigInt(actions[0]?.deposit ?? "0") === 0n;
2745
3422
  }
2746
3423
  __name(canSignWithLAK, "canSignWithLAK");
2747
3424
 
2748
3425
  // src/crypto.ts
3426
+ function curveFromKey(key) {
3427
+ if (!key.includes(":")) return "ed25519";
3428
+ const curve = key.split(":")[0];
3429
+ if (curve === "ed25519" || curve === "secp256k1") return curve;
3430
+ throw new Error(`Unsupported curve: ${curve}`);
3431
+ }
3432
+ __name(curveFromKey, "curveFromKey");
2749
3433
  var keyFromString = /* @__PURE__ */ __name((key) => base58_to_binary_default(
2750
3434
  key.includes(":") ? (() => {
2751
3435
  const [curve, keyPart] = key.split(":");
2752
- if (curve !== "ed25519") {
3436
+ if (curve !== "ed25519" && curve !== "secp256k1") {
2753
3437
  throw new Error(`Unsupported curve: ${curve}`);
2754
3438
  }
2755
3439
  return keyPart;
2756
3440
  })() : key
2757
3441
  ), "keyFromString");
2758
- var keyToString = /* @__PURE__ */ __name((key) => `ed25519:${binary_to_base58_default(key)}`, "keyToString");
3442
+ var keyToString = /* @__PURE__ */ __name((key, curve = "ed25519") => `${curve}:${binary_to_base58_default(key)}`, "keyToString");
2759
3443
  function publicKeyFromPrivate(privateKey) {
3444
+ const curve = curveFromKey(privateKey);
3445
+ if (curve === "secp256k1") {
3446
+ const secret2 = keyFromString(privateKey);
3447
+ const fullPk = secp256k1.getPublicKey(secret2, false);
3448
+ const publicKey2 = fullPk.slice(1);
3449
+ return keyToString(publicKey2, "secp256k1");
3450
+ }
2760
3451
  const secret = keyFromString(privateKey).slice(0, 32);
2761
3452
  const publicKey = ed25519.getPublicKey(secret);
2762
3453
  return keyToString(publicKey);
2763
3454
  }
2764
3455
  __name(publicKeyFromPrivate, "publicKeyFromPrivate");
2765
- function privateKeyFromRandom() {
2766
- const privateKey = crypto.getRandomValues(new Uint8Array(64));
2767
- return keyToString(privateKey);
3456
+ function privateKeyFromRandom(curve = "ed25519") {
3457
+ const size = curve === "secp256k1" ? 32 : 64;
3458
+ const privateKey = crypto.getRandomValues(new Uint8Array(size));
3459
+ return keyToString(privateKey, curve);
2768
3460
  }
2769
3461
  __name(privateKeyFromRandom, "privateKeyFromRandom");
2770
3462
  function signHash(hashBytes, privateKey, opts) {
2771
- const secret = keyFromString(privateKey).slice(0, 32);
2772
- const signature = ed25519.sign(hashBytes, secret);
3463
+ const curve = curveFromKey(privateKey);
3464
+ let signature;
3465
+ if (curve === "secp256k1") {
3466
+ const secret = keyFromString(privateKey);
3467
+ const raw = secp256k1.sign(hashBytes, secret, { prehash: false, format: "recovered" });
3468
+ signature = new Uint8Array(65);
3469
+ signature.set(raw.slice(1, 33), 0);
3470
+ signature.set(raw.slice(33, 65), 32);
3471
+ signature[64] = raw[0];
3472
+ } else {
3473
+ const secret = keyFromString(privateKey).slice(0, 32);
3474
+ signature = ed25519.sign(hashBytes, secret);
3475
+ }
2773
3476
  if (opts?.returnBase58) {
2774
3477
  return binary_to_base58_default(signature);
2775
3478
  }
@@ -2782,533 +3485,275 @@ var NearUtils = (() => {
2782
3485
  }
2783
3486
  __name(signBytes, "signBytes");
2784
3487
 
2785
- // ../../node_modules/borsh/lib/esm/types.js
2786
- var integers = ["u8", "u16", "u32", "u64", "u128", "i8", "i16", "i32", "i64", "i128", "f32", "f64"];
2787
-
2788
- // ../../node_modules/borsh/lib/esm/buffer.js
2789
- var EncodeBuffer = (
2790
- /** @class */
2791
- function() {
2792
- function EncodeBuffer2() {
2793
- this.offset = 0;
2794
- this.buffer_size = 256;
2795
- this.buffer = new ArrayBuffer(this.buffer_size);
2796
- this.view = new DataView(this.buffer);
2797
- }
2798
- __name(EncodeBuffer2, "EncodeBuffer");
2799
- EncodeBuffer2.prototype.resize_if_necessary = function(needed_space) {
2800
- if (this.buffer_size - this.offset < needed_space) {
2801
- this.buffer_size = Math.max(this.buffer_size * 2, this.buffer_size + needed_space);
2802
- var new_buffer = new ArrayBuffer(this.buffer_size);
2803
- new Uint8Array(new_buffer).set(new Uint8Array(this.buffer));
2804
- this.buffer = new_buffer;
2805
- this.view = new DataView(new_buffer);
2806
- }
2807
- };
2808
- EncodeBuffer2.prototype.get_used_buffer = function() {
2809
- return new Uint8Array(this.buffer).slice(0, this.offset);
2810
- };
2811
- EncodeBuffer2.prototype.store_value = function(value, type) {
2812
- var bSize = type.substring(1);
2813
- var size = parseInt(bSize) / 8;
2814
- this.resize_if_necessary(size);
2815
- var toCall = type[0] === "f" ? "setFloat".concat(bSize) : type[0] === "i" ? "setInt".concat(bSize) : "setUint".concat(bSize);
2816
- this.view[toCall](this.offset, value, true);
2817
- this.offset += size;
2818
- };
2819
- EncodeBuffer2.prototype.store_bytes = function(from) {
2820
- this.resize_if_necessary(from.length);
2821
- new Uint8Array(this.buffer).set(new Uint8Array(from), this.offset);
2822
- this.offset += from.length;
2823
- };
2824
- return EncodeBuffer2;
2825
- }()
2826
- );
2827
- var DecodeBuffer = (
2828
- /** @class */
2829
- function() {
2830
- function DecodeBuffer2(buf) {
2831
- this.offset = 0;
2832
- this.buffer_size = buf.length;
2833
- this.buffer = new ArrayBuffer(buf.length);
2834
- new Uint8Array(this.buffer).set(buf);
2835
- this.view = new DataView(this.buffer);
2836
- }
2837
- __name(DecodeBuffer2, "DecodeBuffer");
2838
- DecodeBuffer2.prototype.assert_enough_buffer = function(size) {
2839
- if (this.offset + size > this.buffer.byteLength) {
2840
- throw new Error("Error in schema, the buffer is smaller than expected");
2841
- }
2842
- };
2843
- DecodeBuffer2.prototype.consume_value = function(type) {
2844
- var bSize = type.substring(1);
2845
- var size = parseInt(bSize) / 8;
2846
- this.assert_enough_buffer(size);
2847
- var toCall = type[0] === "f" ? "getFloat".concat(bSize) : type[0] === "i" ? "getInt".concat(bSize) : "getUint".concat(bSize);
2848
- var ret = this.view[toCall](this.offset, true);
2849
- this.offset += size;
2850
- return ret;
2851
- };
2852
- DecodeBuffer2.prototype.consume_bytes = function(size) {
2853
- this.assert_enough_buffer(size);
2854
- var ret = this.buffer.slice(this.offset, this.offset + size);
2855
- this.offset += size;
2856
- return ret;
2857
- };
2858
- return DecodeBuffer2;
2859
- }()
2860
- );
2861
-
2862
- // ../../node_modules/borsh/lib/esm/utils.js
2863
- var __extends = /* @__PURE__ */ function() {
2864
- var extendStatics = /* @__PURE__ */ __name(function(d, b) {
2865
- extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
2866
- d2.__proto__ = b2;
2867
- } || function(d2, b2) {
2868
- for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
2869
- };
2870
- return extendStatics(d, b);
2871
- }, "extendStatics");
2872
- return function(d, b) {
2873
- if (typeof b !== "function" && b !== null)
2874
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
2875
- extendStatics(d, b);
2876
- function __() {
2877
- this.constructor = d;
2878
- }
2879
- __name(__, "__");
2880
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2881
- };
2882
- }();
2883
- function isArrayLike(value) {
2884
- 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);
2885
- }
2886
- __name(isArrayLike, "isArrayLike");
2887
- function expect_type(value, type, fieldPath) {
2888
- if (typeof value !== type) {
2889
- throw new Error("Expected ".concat(type, " not ").concat(typeof value, "(").concat(value, ") at ").concat(fieldPath.join(".")));
3488
+ // ../borsh/src/index.ts
3489
+ var EncodeBuffer = class {
3490
+ static {
3491
+ __name(this, "EncodeBuffer");
3492
+ }
3493
+ offset = 0;
3494
+ bufferSize = 256;
3495
+ buffer = new ArrayBuffer(this.bufferSize);
3496
+ view = new DataView(this.buffer);
3497
+ resize(needed) {
3498
+ if (this.bufferSize - this.offset < needed) {
3499
+ this.bufferSize = Math.max(this.bufferSize * 2, this.bufferSize + needed);
3500
+ const next = new ArrayBuffer(this.bufferSize);
3501
+ new Uint8Array(next).set(new Uint8Array(this.buffer));
3502
+ this.buffer = next;
3503
+ this.view = new DataView(next);
3504
+ }
2890
3505
  }
2891
- }
2892
- __name(expect_type, "expect_type");
2893
- function expect_bigint(value, fieldPath) {
2894
- var basicType = ["number", "string", "bigint", "boolean"].includes(typeof value);
2895
- var strObject = typeof value === "object" && value !== null && "toString" in value;
2896
- if (!basicType && !strObject) {
2897
- throw new Error("Expected bigint, number, boolean or string not ".concat(typeof value, "(").concat(value, ") at ").concat(fieldPath.join(".")));
3506
+ storeU8(v) {
3507
+ this.resize(1);
3508
+ this.view.setUint8(this.offset, v);
3509
+ this.offset += 1;
2898
3510
  }
2899
- }
2900
- __name(expect_bigint, "expect_bigint");
2901
- function expect_same_size(length, expected, fieldPath) {
2902
- if (length !== expected) {
2903
- throw new Error("Array length ".concat(length, " does not match schema length ").concat(expected, " at ").concat(fieldPath.join(".")));
3511
+ storeU16(v) {
3512
+ this.resize(2);
3513
+ this.view.setUint16(this.offset, v, true);
3514
+ this.offset += 2;
2904
3515
  }
2905
- }
2906
- __name(expect_same_size, "expect_same_size");
2907
- function expect_enum(value, fieldPath) {
2908
- if (typeof value !== "object" || value === null) {
2909
- throw new Error("Expected object not ".concat(typeof value, "(").concat(value, ") at ").concat(fieldPath.join(".")));
3516
+ storeU32(v) {
3517
+ this.resize(4);
3518
+ this.view.setUint32(this.offset, v, true);
3519
+ this.offset += 4;
3520
+ }
3521
+ storeBytes(from) {
3522
+ this.resize(from.length);
3523
+ new Uint8Array(this.buffer).set(from, this.offset);
3524
+ this.offset += from.length;
3525
+ }
3526
+ result() {
3527
+ return new Uint8Array(this.buffer).slice(0, this.offset);
3528
+ }
3529
+ };
3530
+ var DecodeBuffer = class {
3531
+ static {
3532
+ __name(this, "DecodeBuffer");
2910
3533
  }
3534
+ offset = 0;
3535
+ view;
3536
+ bytes;
3537
+ constructor(buf) {
3538
+ const ab = new ArrayBuffer(buf.length);
3539
+ new Uint8Array(ab).set(buf);
3540
+ this.view = new DataView(ab);
3541
+ this.bytes = new Uint8Array(ab);
3542
+ }
3543
+ assert(size) {
3544
+ if (this.offset + size > this.bytes.length) {
3545
+ throw new Error("Borsh: buffer overrun");
3546
+ }
3547
+ }
3548
+ readU8() {
3549
+ this.assert(1);
3550
+ const v = this.view.getUint8(this.offset);
3551
+ this.offset += 1;
3552
+ return v;
3553
+ }
3554
+ readU16() {
3555
+ this.assert(2);
3556
+ const v = this.view.getUint16(this.offset, true);
3557
+ this.offset += 2;
3558
+ return v;
3559
+ }
3560
+ readU32() {
3561
+ this.assert(4);
3562
+ const v = this.view.getUint32(this.offset, true);
3563
+ this.offset += 4;
3564
+ return v;
3565
+ }
3566
+ readBytes(len) {
3567
+ this.assert(len);
3568
+ const slice = this.bytes.slice(this.offset, this.offset + len);
3569
+ this.offset += len;
3570
+ return slice;
3571
+ }
3572
+ };
3573
+ function encodeBigint(buf, value, byteLen) {
3574
+ const out = new Uint8Array(byteLen);
3575
+ let v = value;
3576
+ for (let i = 0; i < byteLen; i++) {
3577
+ out[i] = Number(v & 0xffn);
3578
+ v >>= 8n;
3579
+ }
3580
+ buf.storeBytes(out);
3581
+ }
3582
+ __name(encodeBigint, "encodeBigint");
3583
+ function decodeBigint(buf, byteLen) {
3584
+ const bytes = buf.readBytes(byteLen);
3585
+ const hex = bytes.reduceRight((r, x) => r + x.toString(16).padStart(2, "0"), "");
3586
+ return BigInt("0x" + hex);
2911
3587
  }
2912
- __name(expect_enum, "expect_enum");
2913
- var VALID_STRING_TYPES = integers.concat(["bool", "string"]);
2914
- var VALID_OBJECT_KEYS = ["option", "enum", "array", "set", "map", "struct"];
2915
- var ErrorSchema = (
2916
- /** @class */
2917
- function(_super) {
2918
- __extends(ErrorSchema2, _super);
2919
- function ErrorSchema2(schema, expected) {
2920
- var message = "Invalid schema: ".concat(JSON.stringify(schema), " expected ").concat(expected);
2921
- return _super.call(this, message) || this;
3588
+ __name(decodeBigint, "decodeBigint");
3589
+ function utf8Encode(str) {
3590
+ const bytes = [];
3591
+ for (let i = 0; i < str.length; i++) {
3592
+ let c = str.charCodeAt(i);
3593
+ if (c < 128) {
3594
+ bytes.push(c);
3595
+ } else if (c < 2048) {
3596
+ bytes.push(192 | c >> 6, 128 | c & 63);
3597
+ } else if (c < 55296 || c >= 57344) {
3598
+ bytes.push(224 | c >> 12, 128 | c >> 6 & 63, 128 | c & 63);
3599
+ } else {
3600
+ i++;
3601
+ c = 65536 + ((c & 1023) << 10 | str.charCodeAt(i) & 1023);
3602
+ bytes.push(240 | c >> 18, 128 | c >> 12 & 63, 128 | c >> 6 & 63, 128 | c & 63);
2922
3603
  }
2923
- __name(ErrorSchema2, "ErrorSchema");
2924
- return ErrorSchema2;
2925
- }(Error)
2926
- );
2927
- function validate_schema(schema) {
2928
- if (typeof schema === "string" && VALID_STRING_TYPES.includes(schema)) {
2929
- return;
2930
- }
2931
- if (schema && typeof schema === "object") {
2932
- var keys = Object.keys(schema);
2933
- if (keys.length === 1 && VALID_OBJECT_KEYS.includes(keys[0])) {
2934
- var key = keys[0];
2935
- if (key === "option")
2936
- return validate_schema(schema[key]);
2937
- if (key === "enum")
2938
- return validate_enum_schema(schema[key]);
2939
- if (key === "array")
2940
- return validate_array_schema(schema[key]);
2941
- if (key === "set")
2942
- return validate_schema(schema[key]);
2943
- if (key === "map")
2944
- return validate_map_schema(schema[key]);
2945
- if (key === "struct")
2946
- return validate_struct_schema(schema[key]);
2947
- }
2948
- }
2949
- throw new ErrorSchema(schema, VALID_OBJECT_KEYS.join(", ") + " or " + VALID_STRING_TYPES.join(", "));
2950
- }
2951
- __name(validate_schema, "validate_schema");
2952
- function validate_enum_schema(schema) {
2953
- if (!Array.isArray(schema))
2954
- throw new ErrorSchema(schema, "Array");
2955
- for (var _i = 0, schema_1 = schema; _i < schema_1.length; _i++) {
2956
- var sch = schema_1[_i];
2957
- if (typeof sch !== "object" || !("struct" in sch)) {
2958
- throw new Error('Missing "struct" key in enum schema');
2959
- }
2960
- if (typeof sch.struct !== "object" || Object.keys(sch.struct).length !== 1) {
2961
- throw new Error('The "struct" in each enum must have a single key');
2962
- }
2963
- validate_schema({ struct: sch.struct });
2964
- }
2965
- }
2966
- __name(validate_enum_schema, "validate_enum_schema");
2967
- function validate_array_schema(schema) {
2968
- if (typeof schema !== "object")
2969
- throw new ErrorSchema(schema, "{ type, len? }");
2970
- if (schema.len && typeof schema.len !== "number") {
2971
- throw new Error("Invalid schema: ".concat(schema));
2972
- }
2973
- if ("type" in schema)
2974
- return validate_schema(schema.type);
2975
- throw new ErrorSchema(schema, "{ type, len? }");
2976
- }
2977
- __name(validate_array_schema, "validate_array_schema");
2978
- function validate_map_schema(schema) {
2979
- if (typeof schema === "object" && "key" in schema && "value" in schema) {
2980
- validate_schema(schema.key);
2981
- validate_schema(schema.value);
2982
- } else {
2983
- throw new ErrorSchema(schema, "{ key, value }");
2984
3604
  }
3605
+ return new Uint8Array(bytes);
2985
3606
  }
2986
- __name(validate_map_schema, "validate_map_schema");
2987
- function validate_struct_schema(schema) {
2988
- if (typeof schema !== "object")
2989
- throw new ErrorSchema(schema, "object");
2990
- for (var key in schema) {
2991
- validate_schema(schema[key]);
3607
+ __name(utf8Encode, "utf8Encode");
3608
+ function utf8Decode(bytes) {
3609
+ const codePoints = [];
3610
+ for (let i = 0; i < bytes.length; i++) {
3611
+ const b = bytes[i];
3612
+ if (b < 128) {
3613
+ codePoints.push(b);
3614
+ } else if (b < 224) {
3615
+ codePoints.push((b & 31) << 6 | bytes[++i] & 63);
3616
+ } else if (b < 240) {
3617
+ codePoints.push((b & 15) << 12 | (bytes[++i] & 63) << 6 | bytes[++i] & 63);
3618
+ } else {
3619
+ codePoints.push((b & 7) << 18 | (bytes[++i] & 63) << 12 | (bytes[++i] & 63) << 6 | bytes[++i] & 63);
3620
+ }
2992
3621
  }
3622
+ return String.fromCodePoint(...codePoints);
2993
3623
  }
2994
- __name(validate_struct_schema, "validate_struct_schema");
2995
-
2996
- // ../../node_modules/borsh/lib/esm/serialize.js
2997
- var BorshSerializer = (
2998
- /** @class */
2999
- function() {
3000
- function BorshSerializer2(checkTypes) {
3001
- this.encoded = new EncodeBuffer();
3002
- this.fieldPath = ["value"];
3003
- this.checkTypes = checkTypes;
3004
- }
3005
- __name(BorshSerializer2, "BorshSerializer");
3006
- BorshSerializer2.prototype.encode = function(value, schema) {
3007
- this.encode_value(value, schema);
3008
- return this.encoded.get_used_buffer();
3009
- };
3010
- BorshSerializer2.prototype.encode_value = function(value, schema) {
3011
- if (typeof schema === "string") {
3012
- if (integers.includes(schema))
3013
- return this.encode_integer(value, schema);
3014
- if (schema === "string")
3015
- return this.encode_string(value);
3016
- if (schema === "bool")
3017
- return this.encode_boolean(value);
3018
- }
3019
- if (typeof schema === "object") {
3020
- if ("option" in schema)
3021
- return this.encode_option(value, schema);
3022
- if ("enum" in schema)
3023
- return this.encode_enum(value, schema);
3024
- if ("array" in schema)
3025
- return this.encode_array(value, schema);
3026
- if ("set" in schema)
3027
- return this.encode_set(value, schema);
3028
- if ("map" in schema)
3029
- return this.encode_map(value, schema);
3030
- if ("struct" in schema)
3031
- return this.encode_struct(value, schema);
3624
+ __name(utf8Decode, "utf8Decode");
3625
+ function encodeValue(buf, value, schema) {
3626
+ if (typeof schema === "string") {
3627
+ switch (schema) {
3628
+ case "u8":
3629
+ return buf.storeU8(value);
3630
+ case "u16":
3631
+ return buf.storeU16(value);
3632
+ case "u32":
3633
+ return buf.storeU32(value);
3634
+ case "u64":
3635
+ return encodeBigint(buf, BigInt(value), 8);
3636
+ case "u128":
3637
+ return encodeBigint(buf, BigInt(value), 16);
3638
+ case "string": {
3639
+ const encoded = utf8Encode(value);
3640
+ buf.storeU32(encoded.length);
3641
+ buf.storeBytes(encoded);
3642
+ return;
3032
3643
  }
3033
- };
3034
- BorshSerializer2.prototype.encode_integer = function(value, schema) {
3035
- var size = parseInt(schema.substring(1));
3036
- if (size <= 32 || schema == "f64") {
3037
- this.checkTypes && expect_type(value, "number", this.fieldPath);
3038
- this.encoded.store_value(value, schema);
3039
- } else {
3040
- this.checkTypes && expect_bigint(value, this.fieldPath);
3041
- this.encode_bigint(BigInt(value), size);
3042
- }
3043
- };
3044
- BorshSerializer2.prototype.encode_bigint = function(value, size) {
3045
- var buffer_len = size / 8;
3046
- var buffer = new Uint8Array(buffer_len);
3047
- for (var i = 0; i < buffer_len; i++) {
3048
- buffer[i] = Number(value & BigInt(255));
3049
- value = value >> BigInt(8);
3050
- }
3051
- this.encoded.store_bytes(new Uint8Array(buffer));
3052
- };
3053
- BorshSerializer2.prototype.encode_string = function(value) {
3054
- this.checkTypes && expect_type(value, "string", this.fieldPath);
3055
- var _value = value;
3056
- var utf8Bytes = [];
3057
- for (var i = 0; i < _value.length; i++) {
3058
- var charCode = _value.charCodeAt(i);
3059
- if (charCode < 128) {
3060
- utf8Bytes.push(charCode);
3061
- } else if (charCode < 2048) {
3062
- utf8Bytes.push(192 | charCode >> 6, 128 | charCode & 63);
3063
- } else if (charCode < 55296 || charCode >= 57344) {
3064
- utf8Bytes.push(224 | charCode >> 12, 128 | charCode >> 6 & 63, 128 | charCode & 63);
3065
- } else {
3066
- i++;
3067
- charCode = 65536 + ((charCode & 1023) << 10 | _value.charCodeAt(i) & 1023);
3068
- utf8Bytes.push(240 | charCode >> 18, 128 | charCode >> 12 & 63, 128 | charCode >> 6 & 63, 128 | charCode & 63);
3069
- }
3070
- }
3071
- this.encoded.store_value(utf8Bytes.length, "u32");
3072
- this.encoded.store_bytes(new Uint8Array(utf8Bytes));
3073
- };
3074
- BorshSerializer2.prototype.encode_boolean = function(value) {
3075
- this.checkTypes && expect_type(value, "boolean", this.fieldPath);
3076
- this.encoded.store_value(value ? 1 : 0, "u8");
3077
- };
3078
- BorshSerializer2.prototype.encode_option = function(value, schema) {
3644
+ }
3645
+ }
3646
+ if (typeof schema === "object") {
3647
+ if ("option" in schema) {
3079
3648
  if (value === null || value === void 0) {
3080
- this.encoded.store_value(0, "u8");
3649
+ buf.storeU8(0);
3081
3650
  } else {
3082
- this.encoded.store_value(1, "u8");
3083
- this.encode_value(value, schema.option);
3651
+ buf.storeU8(1);
3652
+ encodeValue(buf, value, schema.option);
3084
3653
  }
3085
- };
3086
- BorshSerializer2.prototype.encode_enum = function(value, schema) {
3087
- this.checkTypes && expect_enum(value, this.fieldPath);
3088
- var valueKey = Object.keys(value)[0];
3089
- for (var i = 0; i < schema["enum"].length; i++) {
3090
- var valueSchema = schema["enum"][i];
3091
- if (valueKey === Object.keys(valueSchema.struct)[0]) {
3092
- this.encoded.store_value(i, "u8");
3093
- return this.encode_struct(value, valueSchema);
3094
- }
3095
- }
3096
- throw new Error("Enum key (".concat(valueKey, ") not found in enum schema: ").concat(JSON.stringify(schema), " at ").concat(this.fieldPath.join(".")));
3097
- };
3098
- BorshSerializer2.prototype.encode_array = function(value, schema) {
3099
- if (isArrayLike(value))
3100
- return this.encode_arraylike(value, schema);
3101
- if (value instanceof ArrayBuffer)
3102
- return this.encode_buffer(value, schema);
3103
- throw new Error("Expected Array-like not ".concat(typeof value, "(").concat(value, ") at ").concat(this.fieldPath.join(".")));
3104
- };
3105
- BorshSerializer2.prototype.encode_arraylike = function(value, schema) {
3106
- if (schema.array.len) {
3107
- expect_same_size(value.length, schema.array.len, this.fieldPath);
3108
- } else {
3109
- this.encoded.store_value(value.length, "u32");
3110
- }
3111
- for (var i = 0; i < value.length; i++) {
3112
- this.encode_value(value[i], schema.array.type);
3113
- }
3114
- };
3115
- BorshSerializer2.prototype.encode_buffer = function(value, schema) {
3116
- if (schema.array.len) {
3117
- expect_same_size(value.byteLength, schema.array.len, this.fieldPath);
3118
- } else {
3119
- this.encoded.store_value(value.byteLength, "u32");
3120
- }
3121
- this.encoded.store_bytes(new Uint8Array(value));
3122
- };
3123
- BorshSerializer2.prototype.encode_set = function(value, schema) {
3124
- this.checkTypes && expect_type(value, "object", this.fieldPath);
3125
- var isSet = value instanceof Set;
3126
- var values = isSet ? Array.from(value.values()) : Object.values(value);
3127
- this.encoded.store_value(values.length, "u32");
3128
- for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
3129
- var value_1 = values_1[_i];
3130
- this.encode_value(value_1, schema.set);
3131
- }
3132
- };
3133
- BorshSerializer2.prototype.encode_map = function(value, schema) {
3134
- this.checkTypes && expect_type(value, "object", this.fieldPath);
3135
- var isMap = value instanceof Map;
3136
- var keys = isMap ? Array.from(value.keys()) : Object.keys(value);
3137
- this.encoded.store_value(keys.length, "u32");
3138
- for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
3139
- var key = keys_1[_i];
3140
- this.encode_value(key, schema.map.key);
3141
- this.encode_value(isMap ? value.get(key) : value[key], schema.map.value);
3142
- }
3143
- };
3144
- BorshSerializer2.prototype.encode_struct = function(value, schema) {
3145
- this.checkTypes && expect_type(value, "object", this.fieldPath);
3146
- for (var _i = 0, _a = Object.keys(schema.struct); _i < _a.length; _i++) {
3147
- var key = _a[_i];
3148
- this.fieldPath.push(key);
3149
- this.encode_value(value[key], schema.struct[key]);
3150
- this.fieldPath.pop();
3151
- }
3152
- };
3153
- return BorshSerializer2;
3154
- }()
3155
- );
3156
-
3157
- // ../../node_modules/borsh/lib/esm/deserialize.js
3158
- var BorshDeserializer = (
3159
- /** @class */
3160
- function() {
3161
- function BorshDeserializer2(bufferArray) {
3162
- this.buffer = new DecodeBuffer(bufferArray);
3163
- }
3164
- __name(BorshDeserializer2, "BorshDeserializer");
3165
- BorshDeserializer2.prototype.decode = function(schema) {
3166
- return this.decode_value(schema);
3167
- };
3168
- BorshDeserializer2.prototype.decode_value = function(schema) {
3169
- if (typeof schema === "string") {
3170
- if (integers.includes(schema))
3171
- return this.decode_integer(schema);
3172
- if (schema === "string")
3173
- return this.decode_string();
3174
- if (schema === "bool")
3175
- return this.decode_boolean();
3176
- }
3177
- if (typeof schema === "object") {
3178
- if ("option" in schema)
3179
- return this.decode_option(schema);
3180
- if ("enum" in schema)
3181
- return this.decode_enum(schema);
3182
- if ("array" in schema)
3183
- return this.decode_array(schema);
3184
- if ("set" in schema)
3185
- return this.decode_set(schema);
3186
- if ("map" in schema)
3187
- return this.decode_map(schema);
3188
- if ("struct" in schema)
3189
- return this.decode_struct(schema);
3190
- }
3191
- throw new Error("Unsupported type: ".concat(schema));
3192
- };
3193
- BorshDeserializer2.prototype.decode_integer = function(schema) {
3194
- var size = parseInt(schema.substring(1));
3195
- if (size <= 32 || schema == "f64") {
3196
- return this.buffer.consume_value(schema);
3197
- }
3198
- return this.decode_bigint(size, schema.startsWith("i"));
3199
- };
3200
- BorshDeserializer2.prototype.decode_bigint = function(size, signed) {
3201
- if (signed === void 0) {
3202
- signed = false;
3203
- }
3204
- var buffer_len = size / 8;
3205
- var buffer = new Uint8Array(this.buffer.consume_bytes(buffer_len));
3206
- var bits = buffer.reduceRight(function(r, x) {
3207
- return r + x.toString(16).padStart(2, "0");
3208
- }, "");
3209
- if (signed && buffer[buffer_len - 1]) {
3210
- return BigInt.asIntN(size, BigInt("0x".concat(bits)));
3211
- }
3212
- return BigInt("0x".concat(bits));
3213
- };
3214
- BorshDeserializer2.prototype.decode_string = function() {
3215
- var len = this.decode_integer("u32");
3216
- var buffer = new Uint8Array(this.buffer.consume_bytes(len));
3217
- var codePoints = [];
3218
- for (var i = 0; i < len; ++i) {
3219
- var byte = buffer[i];
3220
- if (byte < 128) {
3221
- codePoints.push(byte);
3222
- } else if (byte < 224) {
3223
- codePoints.push((byte & 31) << 6 | buffer[++i] & 63);
3224
- } else if (byte < 240) {
3225
- codePoints.push((byte & 15) << 12 | (buffer[++i] & 63) << 6 | buffer[++i] & 63);
3226
- } else {
3227
- var codePoint = (byte & 7) << 18 | (buffer[++i] & 63) << 12 | (buffer[++i] & 63) << 6 | buffer[++i] & 63;
3228
- codePoints.push(codePoint);
3654
+ return;
3655
+ }
3656
+ if ("enum" in schema) {
3657
+ const valueKey = Object.keys(value)[0];
3658
+ const variants = schema.enum;
3659
+ for (let i = 0; i < variants.length; i++) {
3660
+ const variantKey = Object.keys(variants[i].struct)[0];
3661
+ if (valueKey === variantKey) {
3662
+ buf.storeU8(i);
3663
+ encodeStruct(buf, value, variants[i]);
3664
+ return;
3229
3665
  }
3230
3666
  }
3231
- return String.fromCodePoint.apply(String, codePoints);
3232
- };
3233
- BorshDeserializer2.prototype.decode_boolean = function() {
3234
- return this.buffer.consume_value("u8") > 0;
3235
- };
3236
- BorshDeserializer2.prototype.decode_option = function(schema) {
3237
- var option = this.buffer.consume_value("u8");
3238
- if (option === 1) {
3239
- return this.decode_value(schema.option);
3667
+ throw new Error(`Borsh: enum key "${valueKey}" not found in schema`);
3668
+ }
3669
+ if ("array" in schema) {
3670
+ if (schema.array.len == null) {
3671
+ buf.storeU32(value.length);
3240
3672
  }
3241
- if (option !== 0) {
3242
- throw new Error("Invalid option ".concat(option));
3673
+ for (let i = 0; i < value.length; i++) {
3674
+ encodeValue(buf, value[i], schema.array.type);
3243
3675
  }
3244
- return null;
3245
- };
3246
- BorshDeserializer2.prototype.decode_enum = function(schema) {
3247
- var _a;
3248
- var valueIndex = this.buffer.consume_value("u8");
3249
- if (valueIndex > schema["enum"].length) {
3250
- throw new Error("Enum option ".concat(valueIndex, " is not available"));
3676
+ return;
3677
+ }
3678
+ if ("struct" in schema) {
3679
+ encodeStruct(buf, value, schema);
3680
+ return;
3681
+ }
3682
+ }
3683
+ }
3684
+ __name(encodeValue, "encodeValue");
3685
+ function encodeStruct(buf, value, schema) {
3686
+ for (const key of Object.keys(schema.struct)) {
3687
+ encodeValue(buf, value[key], schema.struct[key]);
3688
+ }
3689
+ }
3690
+ __name(encodeStruct, "encodeStruct");
3691
+ function decodeValue(buf, schema) {
3692
+ if (typeof schema === "string") {
3693
+ switch (schema) {
3694
+ case "u8":
3695
+ return buf.readU8();
3696
+ case "u16":
3697
+ return buf.readU16();
3698
+ case "u32":
3699
+ return buf.readU32();
3700
+ case "u64":
3701
+ return decodeBigint(buf, 8);
3702
+ case "u128":
3703
+ return decodeBigint(buf, 16);
3704
+ case "string": {
3705
+ const len = buf.readU32();
3706
+ return utf8Decode(buf.readBytes(len));
3251
3707
  }
3252
- var struct = schema["enum"][valueIndex].struct;
3253
- var key = Object.keys(struct)[0];
3254
- return _a = {}, _a[key] = this.decode_value(struct[key]), _a;
3255
- };
3256
- BorshDeserializer2.prototype.decode_array = function(schema) {
3257
- var result = [];
3258
- var len = schema.array.len ? schema.array.len : this.decode_integer("u32");
3259
- for (var i = 0; i < len; ++i) {
3260
- result.push(this.decode_value(schema.array.type));
3708
+ }
3709
+ }
3710
+ if (typeof schema === "object") {
3711
+ if ("option" in schema) {
3712
+ const flag = buf.readU8();
3713
+ if (flag === 1) return decodeValue(buf, schema.option);
3714
+ if (flag === 0) return null;
3715
+ throw new Error(`Borsh: invalid option flag ${flag}`);
3716
+ }
3717
+ if ("enum" in schema) {
3718
+ const idx = buf.readU8();
3719
+ if (idx >= schema.enum.length) {
3720
+ throw new Error(`Borsh: enum index ${idx} out of range`);
3261
3721
  }
3262
- return result;
3263
- };
3264
- BorshDeserializer2.prototype.decode_set = function(schema) {
3265
- var len = this.decode_integer("u32");
3266
- var result = /* @__PURE__ */ new Set();
3267
- for (var i = 0; i < len; ++i) {
3268
- result.add(this.decode_value(schema.set));
3722
+ const variant = schema.enum[idx];
3723
+ const result = {};
3724
+ for (const key of Object.keys(variant.struct)) {
3725
+ result[key] = decodeValue(buf, variant.struct[key]);
3269
3726
  }
3270
3727
  return result;
3271
- };
3272
- BorshDeserializer2.prototype.decode_map = function(schema) {
3273
- var len = this.decode_integer("u32");
3274
- var result = /* @__PURE__ */ new Map();
3275
- for (var i = 0; i < len; ++i) {
3276
- var key = this.decode_value(schema.map.key);
3277
- var value = this.decode_value(schema.map.value);
3278
- result.set(key, value);
3728
+ }
3729
+ if ("array" in schema) {
3730
+ const len = schema.array.len ?? buf.readU32();
3731
+ const result = [];
3732
+ for (let i = 0; i < len; i++) {
3733
+ result.push(decodeValue(buf, schema.array.type));
3279
3734
  }
3280
3735
  return result;
3281
- };
3282
- BorshDeserializer2.prototype.decode_struct = function(schema) {
3283
- var result = {};
3284
- for (var key in schema.struct) {
3285
- result[key] = this.decode_value(schema.struct[key]);
3736
+ }
3737
+ if ("struct" in schema) {
3738
+ const result = {};
3739
+ for (const key in schema.struct) {
3740
+ result[key] = decodeValue(buf, schema.struct[key]);
3286
3741
  }
3287
3742
  return result;
3288
- };
3289
- return BorshDeserializer2;
3290
- }()
3291
- );
3292
-
3293
- // ../../node_modules/borsh/lib/esm/index.js
3294
- function serialize(schema, value, validate) {
3295
- if (validate === void 0) {
3296
- validate = true;
3743
+ }
3297
3744
  }
3298
- if (validate)
3299
- validate_schema(schema);
3300
- var serializer = new BorshSerializer(validate);
3301
- return serializer.encode(value, schema);
3745
+ throw new Error(`Borsh: unsupported schema: ${JSON.stringify(schema)}`);
3746
+ }
3747
+ __name(decodeValue, "decodeValue");
3748
+ function serialize(schema, value) {
3749
+ const buf = new EncodeBuffer();
3750
+ encodeValue(buf, value, schema);
3751
+ return buf.result();
3302
3752
  }
3303
3753
  __name(serialize, "serialize");
3304
- function deserialize(schema, buffer, validate) {
3305
- if (validate === void 0) {
3306
- validate = true;
3307
- }
3308
- if (validate)
3309
- validate_schema(schema);
3310
- var deserializer = new BorshDeserializer(buffer);
3311
- return deserializer.decode(schema);
3754
+ function deserialize(schema, buffer) {
3755
+ const buf = new DecodeBuffer(buffer);
3756
+ return decodeValue(buf, schema);
3312
3757
  }
3313
3758
  __name(deserialize, "deserialize");
3314
3759
 
@@ -3489,14 +3934,22 @@ var NearUtils = (() => {
3489
3934
  var txToJsonStringified = /* @__PURE__ */ __name((tx) => {
3490
3935
  return JSON.stringify(txToJson(tx));
3491
3936
  }, "txToJsonStringified");
3937
+ function mapPublicKey(keyString) {
3938
+ const curve = curveFromKey(keyString);
3939
+ const data = keyFromString(keyString);
3940
+ return curve === "secp256k1" ? { secp256k1Key: { data } } : { ed25519Key: { data } };
3941
+ }
3942
+ __name(mapPublicKey, "mapPublicKey");
3943
+ function mapSignature(sigBase58, signerKeyString) {
3944
+ const curve = curveFromKey(signerKeyString);
3945
+ const data = base58_to_binary_default(sigBase58);
3946
+ return curve === "secp256k1" ? { secp256k1Signature: { data } } : { ed25519Signature: { data } };
3947
+ }
3948
+ __name(mapSignature, "mapSignature");
3492
3949
  function mapTransaction(jsonTransaction) {
3493
3950
  return {
3494
3951
  signerId: jsonTransaction.signerId,
3495
- publicKey: {
3496
- ed25519Key: {
3497
- data: keyFromString(jsonTransaction.publicKey)
3498
- }
3499
- },
3952
+ publicKey: mapPublicKey(jsonTransaction.publicKey),
3500
3953
  nonce: BigInt(jsonTransaction.nonce),
3501
3954
  receiverId: jsonTransaction.receiverId,
3502
3955
  blockHash: base58_to_binary_default(jsonTransaction.blockHash),
@@ -3519,13 +3972,9 @@ var NearUtils = (() => {
3519
3972
  console.log("fastnear: mapped (for borsh schema) signed transaction", mappedSignedTx);
3520
3973
  const plainSignedTransaction = {
3521
3974
  transaction: mappedSignedTx,
3522
- signature: {
3523
- ed25519Signature: {
3524
- data: base58_to_binary_default(signature)
3525
- }
3526
- }
3975
+ signature: mapSignature(signature, jsonTransaction.publicKey)
3527
3976
  };
3528
- const borshSignedTx = serialize(SCHEMA.SignedTransaction, plainSignedTransaction, true);
3977
+ const borshSignedTx = serialize(SCHEMA.SignedTransaction, plainSignedTransaction);
3529
3978
  console.log("fastnear: borsh-serialized signed transaction:", borshSignedTx);
3530
3979
  return borshSignedTx;
3531
3980
  }
@@ -3565,22 +4014,14 @@ var NearUtils = (() => {
3565
4014
  return {
3566
4015
  stake: {
3567
4016
  stake: BigInt(action.stake),
3568
- publicKey: {
3569
- ed25519Key: {
3570
- data: keyFromString(action.publicKey)
3571
- }
3572
- }
4017
+ publicKey: mapPublicKey(action.publicKey)
3573
4018
  }
3574
4019
  };
3575
4020
  }
3576
4021
  case "AddKey": {
3577
4022
  return {
3578
4023
  addKey: {
3579
- publicKey: {
3580
- ed25519Key: {
3581
- data: keyFromString(action.publicKey)
3582
- }
3583
- },
4024
+ publicKey: mapPublicKey(action.publicKey),
3584
4025
  accessKey: {
3585
4026
  nonce: BigInt(action.accessKey.nonce),
3586
4027
  permission: action.accessKey.permission === "FullAccess" ? { fullAccess: {} } : {
@@ -3597,11 +4038,7 @@ var NearUtils = (() => {
3597
4038
  case "DeleteKey": {
3598
4039
  return {
3599
4040
  deleteKey: {
3600
- publicKey: {
3601
- ed25519Key: {
3602
- data: keyFromString(action.publicKey)
3603
- }
3604
- }
4041
+ publicKey: mapPublicKey(action.publicKey)
3605
4042
  }
3606
4043
  };
3607
4044
  }
@@ -3616,9 +4053,7 @@ var NearUtils = (() => {
3616
4053
  return {
3617
4054
  signedDelegate: {
3618
4055
  delegateAction: mapAction(action.delegateAction),
3619
- signature: {
3620
- ed25519Signature: base58_to_binary_default(action.signature)
3621
- }
4056
+ signature: mapSignature(action.signature, action.publicKey)
3622
4057
  }
3623
4058
  };
3624
4059
  }
@@ -3659,6 +4094,12 @@ var NearUtils = (() => {
3659
4094
 
3660
4095
  @noble/curves/ed25519.js:
3661
4096
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4097
+
4098
+ @noble/curves/abstract/weierstrass.js:
4099
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4100
+
4101
+ @noble/curves/secp256k1.js:
4102
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3662
4103
  */
3663
4104
 
3664
4105
  Object.defineProperty(globalThis, 'NearUtils', {