@unicitylabs/sphere-sdk 0.3.7 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/connect/index.cjs +770 -0
  2. package/dist/connect/index.cjs.map +1 -0
  3. package/dist/connect/index.d.cts +312 -0
  4. package/dist/connect/index.d.ts +312 -0
  5. package/dist/connect/index.js +747 -0
  6. package/dist/connect/index.js.map +1 -0
  7. package/dist/core/index.cjs +90 -2502
  8. package/dist/core/index.cjs.map +1 -1
  9. package/dist/core/index.d.cts +10 -165
  10. package/dist/core/index.d.ts +10 -165
  11. package/dist/core/index.js +86 -2498
  12. package/dist/core/index.js.map +1 -1
  13. package/dist/impl/browser/connect/index.cjs +271 -0
  14. package/dist/impl/browser/connect/index.cjs.map +1 -0
  15. package/dist/impl/browser/connect/index.d.cts +137 -0
  16. package/dist/impl/browser/connect/index.d.ts +137 -0
  17. package/dist/impl/browser/connect/index.js +248 -0
  18. package/dist/impl/browser/connect/index.js.map +1 -0
  19. package/dist/impl/browser/index.cjs +201 -28
  20. package/dist/impl/browser/index.cjs.map +1 -1
  21. package/dist/impl/browser/index.js +201 -28
  22. package/dist/impl/browser/index.js.map +1 -1
  23. package/dist/impl/browser/ipfs.cjs +6 -1
  24. package/dist/impl/browser/ipfs.cjs.map +1 -1
  25. package/dist/impl/browser/ipfs.js +6 -1
  26. package/dist/impl/browser/ipfs.js.map +1 -1
  27. package/dist/impl/nodejs/connect/index.cjs +372 -0
  28. package/dist/impl/nodejs/connect/index.cjs.map +1 -0
  29. package/dist/impl/nodejs/connect/index.d.cts +178 -0
  30. package/dist/impl/nodejs/connect/index.d.ts +178 -0
  31. package/dist/impl/nodejs/connect/index.js +333 -0
  32. package/dist/impl/nodejs/connect/index.js.map +1 -0
  33. package/dist/impl/nodejs/index.cjs +201 -28
  34. package/dist/impl/nodejs/index.cjs.map +1 -1
  35. package/dist/impl/nodejs/index.d.cts +2 -21
  36. package/dist/impl/nodejs/index.d.ts +2 -21
  37. package/dist/impl/nodejs/index.js +201 -28
  38. package/dist/impl/nodejs/index.js.map +1 -1
  39. package/dist/index.cjs +232 -2513
  40. package/dist/index.cjs.map +1 -1
  41. package/dist/index.d.cts +59 -169
  42. package/dist/index.d.ts +59 -169
  43. package/dist/index.js +228 -2506
  44. package/dist/index.js.map +1 -1
  45. package/package.json +31 -1
package/dist/index.cjs CHANGED
@@ -20,15 +20,15 @@ var __copyProps = (to, from, except, desc) => {
20
20
  }
21
21
  return to;
22
22
  };
23
- var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
24
  // If the importer is in node compatibility mode or this is not an ESM
25
25
  // file that has been converted to a CommonJS file using a Babel-
26
26
  // compatible transform (i.e. "__esModule" has not been set), then set
27
27
  // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
29
- mod2
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
30
  ));
31
- var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
33
  // core/bech32.ts
34
34
  function convertBits(data, fromBits, toBits, pad) {
@@ -75,10 +75,10 @@ function bech32Polymod(values) {
75
75
  }
76
76
  function bech32Checksum(hrp, data) {
77
77
  const values = hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]);
78
- const mod2 = bech32Polymod(values) ^ 1;
78
+ const mod = bech32Polymod(values) ^ 1;
79
79
  const ret = [];
80
80
  for (let p = 0; p < 6; p++) {
81
- ret.push(mod2 >> 5 * (5 - p) & 31);
81
+ ret.push(mod >> 5 * (5 - p) & 31);
82
82
  }
83
83
  return ret;
84
84
  }
@@ -480,7 +480,6 @@ __export(index_exports, {
480
480
  DEFAULT_GROUP_RELAYS: () => DEFAULT_GROUP_RELAYS,
481
481
  DEFAULT_IPFS_BOOTSTRAP_PEERS: () => DEFAULT_IPFS_BOOTSTRAP_PEERS,
482
482
  DEFAULT_IPFS_GATEWAYS: () => DEFAULT_IPFS_GATEWAYS,
483
- DEFAULT_MARKET_API_URL: () => DEFAULT_MARKET_API_URL,
484
483
  DEFAULT_NOSTR_RELAYS: () => DEFAULT_NOSTR_RELAYS,
485
484
  DEV_AGGREGATOR_URL: () => DEV_AGGREGATOR_URL,
486
485
  GroupChatModule: () => GroupChatModule,
@@ -489,7 +488,6 @@ __export(index_exports, {
489
488
  L1: () => l1_exports,
490
489
  L1PaymentsModule: () => L1PaymentsModule,
491
490
  LIMITS: () => LIMITS,
492
- MarketModule: () => MarketModule,
493
491
  NETWORKS: () => NETWORKS,
494
492
  NIP29_KINDS: () => NIP29_KINDS,
495
493
  NOSTR_EVENT_KINDS: () => NOSTR_EVENT_KINDS,
@@ -517,7 +515,6 @@ __export(index_exports, {
517
515
  createGroupChatModule: () => createGroupChatModule,
518
516
  createKeyPair: () => createKeyPair,
519
517
  createL1PaymentsModule: () => createL1PaymentsModule,
520
- createMarketModule: () => createMarketModule,
521
518
  createPaymentSession: () => createPaymentSession,
522
519
  createPaymentSessionError: () => createPaymentSessionError,
523
520
  createPaymentsModule: () => createPaymentsModule,
@@ -2651,7 +2648,11 @@ var STORAGE_KEYS_GLOBAL = {
2651
2648
  /** Cached token registry JSON (fetched from remote) */
2652
2649
  TOKEN_REGISTRY_CACHE: "token_registry_cache",
2653
2650
  /** Timestamp of last token registry cache update (ms since epoch) */
2654
- TOKEN_REGISTRY_CACHE_TS: "token_registry_cache_ts"
2651
+ TOKEN_REGISTRY_CACHE_TS: "token_registry_cache_ts",
2652
+ /** Cached price data JSON (from CoinGecko or other provider) */
2653
+ PRICE_CACHE: "price_cache",
2654
+ /** Timestamp of last price cache update (ms since epoch) */
2655
+ PRICE_CACHE_TS: "price_cache_ts"
2655
2656
  };
2656
2657
  var STORAGE_KEYS_ADDRESS = {
2657
2658
  /** Pending transfers for this address */
@@ -2808,7 +2809,6 @@ var TIMEOUTS = {
2808
2809
  /** Sync interval */
2809
2810
  SYNC_INTERVAL: 6e4
2810
2811
  };
2811
- var DEFAULT_MARKET_API_URL = "https://market-api.unicity.network";
2812
2812
  var LIMITS = {
2813
2813
  /** Min nametag length */
2814
2814
  NAMETAG_MIN_LENGTH: 3,
@@ -2876,6 +2876,7 @@ var TokenRegistry = class _TokenRegistry {
2876
2876
  refreshTimer = null;
2877
2877
  lastRefreshAt = 0;
2878
2878
  refreshPromise = null;
2879
+ initialLoadPromise = null;
2879
2880
  constructor() {
2880
2881
  this.definitionsById = /* @__PURE__ */ new Map();
2881
2882
  this.definitionsBySymbol = /* @__PURE__ */ new Map();
@@ -2914,13 +2915,8 @@ var TokenRegistry = class _TokenRegistry {
2914
2915
  if (options.refreshIntervalMs !== void 0) {
2915
2916
  instance.refreshIntervalMs = options.refreshIntervalMs;
2916
2917
  }
2917
- if (instance.storage) {
2918
- instance.loadFromCache();
2919
- }
2920
2918
  const autoRefresh = options.autoRefresh ?? true;
2921
- if (autoRefresh && instance.remoteUrl) {
2922
- instance.startAutoRefresh();
2923
- }
2919
+ instance.initialLoadPromise = instance.performInitialLoad(autoRefresh);
2924
2920
  }
2925
2921
  /**
2926
2922
  * Reset the singleton instance (useful for testing).
@@ -2938,6 +2934,53 @@ var TokenRegistry = class _TokenRegistry {
2938
2934
  static destroy() {
2939
2935
  _TokenRegistry.resetInstance();
2940
2936
  }
2937
+ /**
2938
+ * Wait for the initial data load (cache or remote) to complete.
2939
+ * Returns true if data was loaded, false if not (timeout or no data source).
2940
+ *
2941
+ * @param timeoutMs - Maximum wait time in ms (default: 10s). Set to 0 for no timeout.
2942
+ */
2943
+ static async waitForReady(timeoutMs = 1e4) {
2944
+ const instance = _TokenRegistry.getInstance();
2945
+ if (!instance.initialLoadPromise) {
2946
+ return instance.definitionsById.size > 0;
2947
+ }
2948
+ if (timeoutMs <= 0) {
2949
+ return instance.initialLoadPromise;
2950
+ }
2951
+ return Promise.race([
2952
+ instance.initialLoadPromise,
2953
+ new Promise((resolve) => setTimeout(() => resolve(false), timeoutMs))
2954
+ ]);
2955
+ }
2956
+ // ===========================================================================
2957
+ // Initial Load
2958
+ // ===========================================================================
2959
+ /**
2960
+ * Perform initial data load: try cache first, fall back to remote fetch.
2961
+ * After initial data is available, start periodic auto-refresh if configured.
2962
+ */
2963
+ async performInitialLoad(autoRefresh) {
2964
+ let loaded = false;
2965
+ if (this.storage) {
2966
+ loaded = await this.loadFromCache();
2967
+ }
2968
+ if (loaded) {
2969
+ if (autoRefresh && this.remoteUrl) {
2970
+ this.startAutoRefresh();
2971
+ }
2972
+ return true;
2973
+ }
2974
+ if (autoRefresh && this.remoteUrl) {
2975
+ loaded = await this.refreshFromRemote();
2976
+ this.stopAutoRefresh();
2977
+ this.refreshTimer = setInterval(() => {
2978
+ this.refreshFromRemote();
2979
+ }, this.refreshIntervalMs);
2980
+ return loaded;
2981
+ }
2982
+ return false;
2983
+ }
2941
2984
  // ===========================================================================
2942
2985
  // Cache (StorageProvider)
2943
2986
  // ===========================================================================
@@ -4080,7 +4123,7 @@ var InstantSplitProcessor = class {
4080
4123
  console.warn("[InstantSplitProcessor] Sender pubkey mismatch (non-fatal)");
4081
4124
  }
4082
4125
  const burnTxJson = JSON.parse(bundle.burnTransaction);
4083
- const burnTransaction = await import_TransferTransaction.TransferTransaction.fromJSON(burnTxJson);
4126
+ const _burnTransaction = await import_TransferTransaction.TransferTransaction.fromJSON(burnTxJson);
4084
4127
  console.log("[InstantSplitProcessor] Burn transaction validated");
4085
4128
  const mintDataJson = JSON.parse(bundle.recipientMintData);
4086
4129
  const mintData = await import_MintTransactionData2.MintTransactionData.fromJSON(mintDataJson);
@@ -4745,6 +4788,7 @@ var PaymentsModule = class _PaymentsModule {
4745
4788
  */
4746
4789
  async load() {
4747
4790
  this.ensureInitialized();
4791
+ await TokenRegistry.waitForReady();
4748
4792
  const providers = this.getTokenStorageProviders();
4749
4793
  for (const [id, provider] of providers) {
4750
4794
  try {
@@ -6086,7 +6130,6 @@ var PaymentsModule = class _PaymentsModule {
6086
6130
  /**
6087
6131
  * Non-blocking proof check with 500ms timeout.
6088
6132
  */
6089
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
6090
6133
  async quickProofCheck(stClient, trustBase, commitment, timeoutMs = 500) {
6091
6134
  try {
6092
6135
  const proof = await Promise.race([
@@ -6102,7 +6145,6 @@ var PaymentsModule = class _PaymentsModule {
6102
6145
  * Perform V5 bundle finalization from stored bundle data and proofs.
6103
6146
  * Extracted from InstantSplitProcessor.processV5Bundle() steps 4-10.
6104
6147
  */
6105
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
6106
6148
  async finalizeFromV5Bundle(bundle, pending2, signingService, stClient, trustBase) {
6107
6149
  const mintDataJson = JSON.parse(bundle.recipientMintData);
6108
6150
  const mintData = await import_MintTransactionData3.MintTransactionData.fromJSON(mintDataJson);
@@ -6265,7 +6307,7 @@ var PaymentsModule = class _PaymentsModule {
6265
6307
  return false;
6266
6308
  }
6267
6309
  if (incomingStateKey) {
6268
- for (const [existingId, existing] of this.tokens) {
6310
+ for (const [_existingId, existing] of this.tokens) {
6269
6311
  if (isSameTokenState(existing, token)) {
6270
6312
  this.log(`Duplicate token state ignored: ${incomingTokenId?.slice(0, 8)}..._${incomingStateHash?.slice(0, 8)}...`);
6271
6313
  return false;
@@ -7628,7 +7670,7 @@ var PaymentsModule = class _PaymentsModule {
7628
7670
  }
7629
7671
  }
7630
7672
  clearTimeout(timeoutId);
7631
- } catch (err) {
7673
+ } catch (_err) {
7632
7674
  continue;
7633
7675
  }
7634
7676
  if (!inclusionProof) {
@@ -9345,26 +9387,27 @@ var GroupChatModule = class {
9345
9387
  oneshotSubscription(filter, opts) {
9346
9388
  return new Promise((resolve) => {
9347
9389
  let done = false;
9348
- let subId;
9390
+ const state = {};
9349
9391
  const finish = () => {
9350
9392
  if (done) return;
9351
9393
  done = true;
9352
- if (subId) {
9394
+ if (state.subId) {
9353
9395
  try {
9354
- this.client.unsubscribe(subId);
9396
+ this.client.unsubscribe(state.subId);
9355
9397
  } catch {
9356
9398
  }
9357
- const idx = this.subscriptionIds.indexOf(subId);
9399
+ const idx = this.subscriptionIds.indexOf(state.subId);
9358
9400
  if (idx >= 0) this.subscriptionIds.splice(idx, 1);
9359
9401
  }
9360
9402
  resolve(opts.onComplete());
9361
9403
  };
9362
- subId = this.client.subscribe(filter, {
9404
+ const subId = this.client.subscribe(filter, {
9363
9405
  onEvent: (event) => {
9364
9406
  if (!done) opts.onEvent(event);
9365
9407
  },
9366
9408
  onEndOfStoredEvents: finish
9367
9409
  });
9410
+ state.subId = subId;
9368
9411
  this.subscriptionIds.push(subId);
9369
9412
  setTimeout(finish, opts.timeoutMs ?? 5e3);
9370
9413
  });
@@ -9395,2426 +9438,6 @@ function createGroupChatModule(config) {
9395
9438
  return new GroupChatModule(config);
9396
9439
  }
9397
9440
 
9398
- // node_modules/@noble/hashes/utils.js
9399
- function isBytes(a) {
9400
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
9401
- }
9402
- function anumber(n, title = "") {
9403
- if (!Number.isSafeInteger(n) || n < 0) {
9404
- const prefix = title && `"${title}" `;
9405
- throw new Error(`${prefix}expected integer >= 0, got ${n}`);
9406
- }
9407
- }
9408
- function abytes(value, length, title = "") {
9409
- const bytes = isBytes(value);
9410
- const len = value?.length;
9411
- const needsLen = length !== void 0;
9412
- if (!bytes || needsLen && len !== length) {
9413
- const prefix = title && `"${title}" `;
9414
- const ofLen = needsLen ? ` of length ${length}` : "";
9415
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
9416
- throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
9417
- }
9418
- return value;
9419
- }
9420
- function ahash(h) {
9421
- if (typeof h !== "function" || typeof h.create !== "function")
9422
- throw new Error("Hash must wrapped by utils.createHasher");
9423
- anumber(h.outputLen);
9424
- anumber(h.blockLen);
9425
- }
9426
- function aexists(instance, checkFinished = true) {
9427
- if (instance.destroyed)
9428
- throw new Error("Hash instance has been destroyed");
9429
- if (checkFinished && instance.finished)
9430
- throw new Error("Hash#digest() has already been called");
9431
- }
9432
- function aoutput(out, instance) {
9433
- abytes(out, void 0, "digestInto() output");
9434
- const min = instance.outputLen;
9435
- if (out.length < min) {
9436
- throw new Error('"digestInto() output" expected to be of length >=' + min);
9437
- }
9438
- }
9439
- function clean(...arrays) {
9440
- for (let i = 0; i < arrays.length; i++) {
9441
- arrays[i].fill(0);
9442
- }
9443
- }
9444
- function createView(arr) {
9445
- return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
9446
- }
9447
- function rotr(word, shift) {
9448
- return word << 32 - shift | word >>> shift;
9449
- }
9450
- var hasHexBuiltin = /* @__PURE__ */ (() => (
9451
- // @ts-ignore
9452
- typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
9453
- ))();
9454
- var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
9455
- function bytesToHex4(bytes) {
9456
- abytes(bytes);
9457
- if (hasHexBuiltin)
9458
- return bytes.toHex();
9459
- let hex = "";
9460
- for (let i = 0; i < bytes.length; i++) {
9461
- hex += hexes[bytes[i]];
9462
- }
9463
- return hex;
9464
- }
9465
- var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
9466
- function asciiToBase16(ch) {
9467
- if (ch >= asciis._0 && ch <= asciis._9)
9468
- return ch - asciis._0;
9469
- if (ch >= asciis.A && ch <= asciis.F)
9470
- return ch - (asciis.A - 10);
9471
- if (ch >= asciis.a && ch <= asciis.f)
9472
- return ch - (asciis.a - 10);
9473
- return;
9474
- }
9475
- function hexToBytes2(hex) {
9476
- if (typeof hex !== "string")
9477
- throw new Error("hex string expected, got " + typeof hex);
9478
- if (hasHexBuiltin)
9479
- return Uint8Array.fromHex(hex);
9480
- const hl = hex.length;
9481
- const al = hl / 2;
9482
- if (hl % 2)
9483
- throw new Error("hex string expected, got unpadded hex of length " + hl);
9484
- const array = new Uint8Array(al);
9485
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
9486
- const n1 = asciiToBase16(hex.charCodeAt(hi));
9487
- const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
9488
- if (n1 === void 0 || n2 === void 0) {
9489
- const char = hex[hi] + hex[hi + 1];
9490
- throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
9491
- }
9492
- array[ai] = n1 * 16 + n2;
9493
- }
9494
- return array;
9495
- }
9496
- function concatBytes(...arrays) {
9497
- let sum = 0;
9498
- for (let i = 0; i < arrays.length; i++) {
9499
- const a = arrays[i];
9500
- abytes(a);
9501
- sum += a.length;
9502
- }
9503
- const res = new Uint8Array(sum);
9504
- for (let i = 0, pad = 0; i < arrays.length; i++) {
9505
- const a = arrays[i];
9506
- res.set(a, pad);
9507
- pad += a.length;
9508
- }
9509
- return res;
9510
- }
9511
- function createHasher(hashCons, info = {}) {
9512
- const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
9513
- const tmp = hashCons(void 0);
9514
- hashC.outputLen = tmp.outputLen;
9515
- hashC.blockLen = tmp.blockLen;
9516
- hashC.create = (opts) => hashCons(opts);
9517
- Object.assign(hashC, info);
9518
- return Object.freeze(hashC);
9519
- }
9520
- function randomBytes2(bytesLength = 32) {
9521
- const cr = typeof globalThis === "object" ? globalThis.crypto : null;
9522
- if (typeof cr?.getRandomValues !== "function")
9523
- throw new Error("crypto.getRandomValues must be defined");
9524
- return cr.getRandomValues(new Uint8Array(bytesLength));
9525
- }
9526
- var oidNist = (suffix) => ({
9527
- oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
9528
- });
9529
-
9530
- // node_modules/@noble/hashes/_md.js
9531
- function Chi(a, b, c) {
9532
- return a & b ^ ~a & c;
9533
- }
9534
- function Maj(a, b, c) {
9535
- return a & b ^ a & c ^ b & c;
9536
- }
9537
- var HashMD = class {
9538
- blockLen;
9539
- outputLen;
9540
- padOffset;
9541
- isLE;
9542
- // For partial updates less than block size
9543
- buffer;
9544
- view;
9545
- finished = false;
9546
- length = 0;
9547
- pos = 0;
9548
- destroyed = false;
9549
- constructor(blockLen, outputLen, padOffset, isLE) {
9550
- this.blockLen = blockLen;
9551
- this.outputLen = outputLen;
9552
- this.padOffset = padOffset;
9553
- this.isLE = isLE;
9554
- this.buffer = new Uint8Array(blockLen);
9555
- this.view = createView(this.buffer);
9556
- }
9557
- update(data) {
9558
- aexists(this);
9559
- abytes(data);
9560
- const { view, buffer, blockLen } = this;
9561
- const len = data.length;
9562
- for (let pos = 0; pos < len; ) {
9563
- const take = Math.min(blockLen - this.pos, len - pos);
9564
- if (take === blockLen) {
9565
- const dataView = createView(data);
9566
- for (; blockLen <= len - pos; pos += blockLen)
9567
- this.process(dataView, pos);
9568
- continue;
9569
- }
9570
- buffer.set(data.subarray(pos, pos + take), this.pos);
9571
- this.pos += take;
9572
- pos += take;
9573
- if (this.pos === blockLen) {
9574
- this.process(view, 0);
9575
- this.pos = 0;
9576
- }
9577
- }
9578
- this.length += data.length;
9579
- this.roundClean();
9580
- return this;
9581
- }
9582
- digestInto(out) {
9583
- aexists(this);
9584
- aoutput(out, this);
9585
- this.finished = true;
9586
- const { buffer, view, blockLen, isLE } = this;
9587
- let { pos } = this;
9588
- buffer[pos++] = 128;
9589
- clean(this.buffer.subarray(pos));
9590
- if (this.padOffset > blockLen - pos) {
9591
- this.process(view, 0);
9592
- pos = 0;
9593
- }
9594
- for (let i = pos; i < blockLen; i++)
9595
- buffer[i] = 0;
9596
- view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
9597
- this.process(view, 0);
9598
- const oview = createView(out);
9599
- const len = this.outputLen;
9600
- if (len % 4)
9601
- throw new Error("_sha2: outputLen must be aligned to 32bit");
9602
- const outLen = len / 4;
9603
- const state = this.get();
9604
- if (outLen > state.length)
9605
- throw new Error("_sha2: outputLen bigger than state");
9606
- for (let i = 0; i < outLen; i++)
9607
- oview.setUint32(4 * i, state[i], isLE);
9608
- }
9609
- digest() {
9610
- const { buffer, outputLen } = this;
9611
- this.digestInto(buffer);
9612
- const res = buffer.slice(0, outputLen);
9613
- this.destroy();
9614
- return res;
9615
- }
9616
- _cloneInto(to) {
9617
- to ||= new this.constructor();
9618
- to.set(...this.get());
9619
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
9620
- to.destroyed = destroyed;
9621
- to.finished = finished;
9622
- to.length = length;
9623
- to.pos = pos;
9624
- if (length % blockLen)
9625
- to.buffer.set(buffer);
9626
- return to;
9627
- }
9628
- clone() {
9629
- return this._cloneInto();
9630
- }
9631
- };
9632
- var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
9633
- 1779033703,
9634
- 3144134277,
9635
- 1013904242,
9636
- 2773480762,
9637
- 1359893119,
9638
- 2600822924,
9639
- 528734635,
9640
- 1541459225
9641
- ]);
9642
-
9643
- // node_modules/@noble/hashes/sha2.js
9644
- var SHA256_K = /* @__PURE__ */ Uint32Array.from([
9645
- 1116352408,
9646
- 1899447441,
9647
- 3049323471,
9648
- 3921009573,
9649
- 961987163,
9650
- 1508970993,
9651
- 2453635748,
9652
- 2870763221,
9653
- 3624381080,
9654
- 310598401,
9655
- 607225278,
9656
- 1426881987,
9657
- 1925078388,
9658
- 2162078206,
9659
- 2614888103,
9660
- 3248222580,
9661
- 3835390401,
9662
- 4022224774,
9663
- 264347078,
9664
- 604807628,
9665
- 770255983,
9666
- 1249150122,
9667
- 1555081692,
9668
- 1996064986,
9669
- 2554220882,
9670
- 2821834349,
9671
- 2952996808,
9672
- 3210313671,
9673
- 3336571891,
9674
- 3584528711,
9675
- 113926993,
9676
- 338241895,
9677
- 666307205,
9678
- 773529912,
9679
- 1294757372,
9680
- 1396182291,
9681
- 1695183700,
9682
- 1986661051,
9683
- 2177026350,
9684
- 2456956037,
9685
- 2730485921,
9686
- 2820302411,
9687
- 3259730800,
9688
- 3345764771,
9689
- 3516065817,
9690
- 3600352804,
9691
- 4094571909,
9692
- 275423344,
9693
- 430227734,
9694
- 506948616,
9695
- 659060556,
9696
- 883997877,
9697
- 958139571,
9698
- 1322822218,
9699
- 1537002063,
9700
- 1747873779,
9701
- 1955562222,
9702
- 2024104815,
9703
- 2227730452,
9704
- 2361852424,
9705
- 2428436474,
9706
- 2756734187,
9707
- 3204031479,
9708
- 3329325298
9709
- ]);
9710
- var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
9711
- var SHA2_32B = class extends HashMD {
9712
- constructor(outputLen) {
9713
- super(64, outputLen, 8, false);
9714
- }
9715
- get() {
9716
- const { A, B, C, D, E, F, G, H } = this;
9717
- return [A, B, C, D, E, F, G, H];
9718
- }
9719
- // prettier-ignore
9720
- set(A, B, C, D, E, F, G, H) {
9721
- this.A = A | 0;
9722
- this.B = B | 0;
9723
- this.C = C | 0;
9724
- this.D = D | 0;
9725
- this.E = E | 0;
9726
- this.F = F | 0;
9727
- this.G = G | 0;
9728
- this.H = H | 0;
9729
- }
9730
- process(view, offset) {
9731
- for (let i = 0; i < 16; i++, offset += 4)
9732
- SHA256_W[i] = view.getUint32(offset, false);
9733
- for (let i = 16; i < 64; i++) {
9734
- const W15 = SHA256_W[i - 15];
9735
- const W2 = SHA256_W[i - 2];
9736
- const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
9737
- const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
9738
- SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
9739
- }
9740
- let { A, B, C, D, E, F, G, H } = this;
9741
- for (let i = 0; i < 64; i++) {
9742
- const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
9743
- const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
9744
- const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
9745
- const T2 = sigma0 + Maj(A, B, C) | 0;
9746
- H = G;
9747
- G = F;
9748
- F = E;
9749
- E = D + T1 | 0;
9750
- D = C;
9751
- C = B;
9752
- B = A;
9753
- A = T1 + T2 | 0;
9754
- }
9755
- A = A + this.A | 0;
9756
- B = B + this.B | 0;
9757
- C = C + this.C | 0;
9758
- D = D + this.D | 0;
9759
- E = E + this.E | 0;
9760
- F = F + this.F | 0;
9761
- G = G + this.G | 0;
9762
- H = H + this.H | 0;
9763
- this.set(A, B, C, D, E, F, G, H);
9764
- }
9765
- roundClean() {
9766
- clean(SHA256_W);
9767
- }
9768
- destroy() {
9769
- this.set(0, 0, 0, 0, 0, 0, 0, 0);
9770
- clean(this.buffer);
9771
- }
9772
- };
9773
- var _SHA256 = class extends SHA2_32B {
9774
- // We cannot use array here since array allows indexing by variable
9775
- // which means optimizer/compiler cannot use registers.
9776
- A = SHA256_IV[0] | 0;
9777
- B = SHA256_IV[1] | 0;
9778
- C = SHA256_IV[2] | 0;
9779
- D = SHA256_IV[3] | 0;
9780
- E = SHA256_IV[4] | 0;
9781
- F = SHA256_IV[5] | 0;
9782
- G = SHA256_IV[6] | 0;
9783
- H = SHA256_IV[7] | 0;
9784
- constructor() {
9785
- super(32);
9786
- }
9787
- };
9788
- var sha2564 = /* @__PURE__ */ createHasher(
9789
- () => new _SHA256(),
9790
- /* @__PURE__ */ oidNist(1)
9791
- );
9792
-
9793
- // node_modules/@noble/curves/utils.js
9794
- var _0n = /* @__PURE__ */ BigInt(0);
9795
- var _1n = /* @__PURE__ */ BigInt(1);
9796
- function abool(value, title = "") {
9797
- if (typeof value !== "boolean") {
9798
- const prefix = title && `"${title}" `;
9799
- throw new Error(prefix + "expected boolean, got type=" + typeof value);
9800
- }
9801
- return value;
9802
- }
9803
- function abignumber(n) {
9804
- if (typeof n === "bigint") {
9805
- if (!isPosBig(n))
9806
- throw new Error("positive bigint expected, got " + n);
9807
- } else
9808
- anumber(n);
9809
- return n;
9810
- }
9811
- function numberToHexUnpadded(num) {
9812
- const hex = abignumber(num).toString(16);
9813
- return hex.length & 1 ? "0" + hex : hex;
9814
- }
9815
- function hexToNumber(hex) {
9816
- if (typeof hex !== "string")
9817
- throw new Error("hex string expected, got " + typeof hex);
9818
- return hex === "" ? _0n : BigInt("0x" + hex);
9819
- }
9820
- function bytesToNumberBE(bytes) {
9821
- return hexToNumber(bytesToHex4(bytes));
9822
- }
9823
- function bytesToNumberLE(bytes) {
9824
- return hexToNumber(bytesToHex4(copyBytes(abytes(bytes)).reverse()));
9825
- }
9826
- function numberToBytesBE(n, len) {
9827
- anumber(len);
9828
- n = abignumber(n);
9829
- const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
9830
- if (res.length !== len)
9831
- throw new Error("number too large");
9832
- return res;
9833
- }
9834
- function numberToBytesLE(n, len) {
9835
- return numberToBytesBE(n, len).reverse();
9836
- }
9837
- function copyBytes(bytes) {
9838
- return Uint8Array.from(bytes);
9839
- }
9840
- var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
9841
- function inRange(n, min, max) {
9842
- return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
9843
- }
9844
- function aInRange(title, n, min, max) {
9845
- if (!inRange(n, min, max))
9846
- throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
9847
- }
9848
- function bitLen(n) {
9849
- let len;
9850
- for (len = 0; n > _0n; n >>= _1n, len += 1)
9851
- ;
9852
- return len;
9853
- }
9854
- var bitMask = (n) => (_1n << BigInt(n)) - _1n;
9855
- function createHmacDrbg(hashLen, qByteLen, hmacFn) {
9856
- anumber(hashLen, "hashLen");
9857
- anumber(qByteLen, "qByteLen");
9858
- if (typeof hmacFn !== "function")
9859
- throw new Error("hmacFn must be a function");
9860
- const u8n = (len) => new Uint8Array(len);
9861
- const NULL = Uint8Array.of();
9862
- const byte0 = Uint8Array.of(0);
9863
- const byte1 = Uint8Array.of(1);
9864
- const _maxDrbgIters = 1e3;
9865
- let v = u8n(hashLen);
9866
- let k = u8n(hashLen);
9867
- let i = 0;
9868
- const reset = () => {
9869
- v.fill(1);
9870
- k.fill(0);
9871
- i = 0;
9872
- };
9873
- const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
9874
- const reseed = (seed = NULL) => {
9875
- k = h(byte0, seed);
9876
- v = h();
9877
- if (seed.length === 0)
9878
- return;
9879
- k = h(byte1, seed);
9880
- v = h();
9881
- };
9882
- const gen = () => {
9883
- if (i++ >= _maxDrbgIters)
9884
- throw new Error("drbg: tried max amount of iterations");
9885
- let len = 0;
9886
- const out = [];
9887
- while (len < qByteLen) {
9888
- v = h();
9889
- const sl = v.slice();
9890
- out.push(sl);
9891
- len += v.length;
9892
- }
9893
- return concatBytes(...out);
9894
- };
9895
- const genUntil = (seed, pred) => {
9896
- reset();
9897
- reseed(seed);
9898
- let res = void 0;
9899
- while (!(res = pred(gen())))
9900
- reseed();
9901
- reset();
9902
- return res;
9903
- };
9904
- return genUntil;
9905
- }
9906
- function validateObject(object, fields = {}, optFields = {}) {
9907
- if (!object || typeof object !== "object")
9908
- throw new Error("expected valid options object");
9909
- function checkField(fieldName, expectedType, isOpt) {
9910
- const val = object[fieldName];
9911
- if (isOpt && val === void 0)
9912
- return;
9913
- const current = typeof val;
9914
- if (current !== expectedType || val === null)
9915
- throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
9916
- }
9917
- const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
9918
- iter(fields, false);
9919
- iter(optFields, true);
9920
- }
9921
- function memoized(fn) {
9922
- const map = /* @__PURE__ */ new WeakMap();
9923
- return (arg, ...args) => {
9924
- const val = map.get(arg);
9925
- if (val !== void 0)
9926
- return val;
9927
- const computed = fn(arg, ...args);
9928
- map.set(arg, computed);
9929
- return computed;
9930
- };
9931
- }
9932
-
9933
- // node_modules/@noble/curves/abstract/modular.js
9934
- var _0n2 = /* @__PURE__ */ BigInt(0);
9935
- var _1n2 = /* @__PURE__ */ BigInt(1);
9936
- var _2n = /* @__PURE__ */ BigInt(2);
9937
- var _3n = /* @__PURE__ */ BigInt(3);
9938
- var _4n = /* @__PURE__ */ BigInt(4);
9939
- var _5n = /* @__PURE__ */ BigInt(5);
9940
- var _7n = /* @__PURE__ */ BigInt(7);
9941
- var _8n = /* @__PURE__ */ BigInt(8);
9942
- var _9n = /* @__PURE__ */ BigInt(9);
9943
- var _16n = /* @__PURE__ */ BigInt(16);
9944
- function mod(a, b) {
9945
- const result = a % b;
9946
- return result >= _0n2 ? result : b + result;
9947
- }
9948
- function pow2(x, power, modulo) {
9949
- let res = x;
9950
- while (power-- > _0n2) {
9951
- res *= res;
9952
- res %= modulo;
9953
- }
9954
- return res;
9955
- }
9956
- function invert(number, modulo) {
9957
- if (number === _0n2)
9958
- throw new Error("invert: expected non-zero number");
9959
- if (modulo <= _0n2)
9960
- throw new Error("invert: expected positive modulus, got " + modulo);
9961
- let a = mod(number, modulo);
9962
- let b = modulo;
9963
- let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
9964
- while (a !== _0n2) {
9965
- const q = b / a;
9966
- const r = b % a;
9967
- const m = x - u * q;
9968
- const n = y - v * q;
9969
- b = a, a = r, x = u, y = v, u = m, v = n;
9970
- }
9971
- const gcd = b;
9972
- if (gcd !== _1n2)
9973
- throw new Error("invert: does not exist");
9974
- return mod(x, modulo);
9975
- }
9976
- function assertIsSquare(Fp, root, n) {
9977
- if (!Fp.eql(Fp.sqr(root), n))
9978
- throw new Error("Cannot find square root");
9979
- }
9980
- function sqrt3mod4(Fp, n) {
9981
- const p1div4 = (Fp.ORDER + _1n2) / _4n;
9982
- const root = Fp.pow(n, p1div4);
9983
- assertIsSquare(Fp, root, n);
9984
- return root;
9985
- }
9986
- function sqrt5mod8(Fp, n) {
9987
- const p5div8 = (Fp.ORDER - _5n) / _8n;
9988
- const n2 = Fp.mul(n, _2n);
9989
- const v = Fp.pow(n2, p5div8);
9990
- const nv = Fp.mul(n, v);
9991
- const i = Fp.mul(Fp.mul(nv, _2n), v);
9992
- const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
9993
- assertIsSquare(Fp, root, n);
9994
- return root;
9995
- }
9996
- function sqrt9mod16(P) {
9997
- const Fp_ = Field(P);
9998
- const tn = tonelliShanks(P);
9999
- const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
10000
- const c2 = tn(Fp_, c1);
10001
- const c3 = tn(Fp_, Fp_.neg(c1));
10002
- const c4 = (P + _7n) / _16n;
10003
- return (Fp, n) => {
10004
- let tv1 = Fp.pow(n, c4);
10005
- let tv2 = Fp.mul(tv1, c1);
10006
- const tv3 = Fp.mul(tv1, c2);
10007
- const tv4 = Fp.mul(tv1, c3);
10008
- const e1 = Fp.eql(Fp.sqr(tv2), n);
10009
- const e2 = Fp.eql(Fp.sqr(tv3), n);
10010
- tv1 = Fp.cmov(tv1, tv2, e1);
10011
- tv2 = Fp.cmov(tv4, tv3, e2);
10012
- const e3 = Fp.eql(Fp.sqr(tv2), n);
10013
- const root = Fp.cmov(tv1, tv2, e3);
10014
- assertIsSquare(Fp, root, n);
10015
- return root;
10016
- };
10017
- }
10018
- function tonelliShanks(P) {
10019
- if (P < _3n)
10020
- throw new Error("sqrt is not defined for small field");
10021
- let Q = P - _1n2;
10022
- let S = 0;
10023
- while (Q % _2n === _0n2) {
10024
- Q /= _2n;
10025
- S++;
10026
- }
10027
- let Z = _2n;
10028
- const _Fp = Field(P);
10029
- while (FpLegendre(_Fp, Z) === 1) {
10030
- if (Z++ > 1e3)
10031
- throw new Error("Cannot find square root: probably non-prime P");
10032
- }
10033
- if (S === 1)
10034
- return sqrt3mod4;
10035
- let cc = _Fp.pow(Z, Q);
10036
- const Q1div2 = (Q + _1n2) / _2n;
10037
- return function tonelliSlow(Fp, n) {
10038
- if (Fp.is0(n))
10039
- return n;
10040
- if (FpLegendre(Fp, n) !== 1)
10041
- throw new Error("Cannot find square root");
10042
- let M = S;
10043
- let c = Fp.mul(Fp.ONE, cc);
10044
- let t = Fp.pow(n, Q);
10045
- let R = Fp.pow(n, Q1div2);
10046
- while (!Fp.eql(t, Fp.ONE)) {
10047
- if (Fp.is0(t))
10048
- return Fp.ZERO;
10049
- let i = 1;
10050
- let t_tmp = Fp.sqr(t);
10051
- while (!Fp.eql(t_tmp, Fp.ONE)) {
10052
- i++;
10053
- t_tmp = Fp.sqr(t_tmp);
10054
- if (i === M)
10055
- throw new Error("Cannot find square root");
10056
- }
10057
- const exponent = _1n2 << BigInt(M - i - 1);
10058
- const b = Fp.pow(c, exponent);
10059
- M = i;
10060
- c = Fp.sqr(b);
10061
- t = Fp.mul(t, c);
10062
- R = Fp.mul(R, b);
10063
- }
10064
- return R;
10065
- };
10066
- }
10067
- function FpSqrt(P) {
10068
- if (P % _4n === _3n)
10069
- return sqrt3mod4;
10070
- if (P % _8n === _5n)
10071
- return sqrt5mod8;
10072
- if (P % _16n === _9n)
10073
- return sqrt9mod16(P);
10074
- return tonelliShanks(P);
10075
- }
10076
- var FIELD_FIELDS = [
10077
- "create",
10078
- "isValid",
10079
- "is0",
10080
- "neg",
10081
- "inv",
10082
- "sqrt",
10083
- "sqr",
10084
- "eql",
10085
- "add",
10086
- "sub",
10087
- "mul",
10088
- "pow",
10089
- "div",
10090
- "addN",
10091
- "subN",
10092
- "mulN",
10093
- "sqrN"
10094
- ];
10095
- function validateField(field) {
10096
- const initial = {
10097
- ORDER: "bigint",
10098
- BYTES: "number",
10099
- BITS: "number"
10100
- };
10101
- const opts = FIELD_FIELDS.reduce((map, val) => {
10102
- map[val] = "function";
10103
- return map;
10104
- }, initial);
10105
- validateObject(field, opts);
10106
- return field;
10107
- }
10108
- function FpPow(Fp, num, power) {
10109
- if (power < _0n2)
10110
- throw new Error("invalid exponent, negatives unsupported");
10111
- if (power === _0n2)
10112
- return Fp.ONE;
10113
- if (power === _1n2)
10114
- return num;
10115
- let p = Fp.ONE;
10116
- let d = num;
10117
- while (power > _0n2) {
10118
- if (power & _1n2)
10119
- p = Fp.mul(p, d);
10120
- d = Fp.sqr(d);
10121
- power >>= _1n2;
10122
- }
10123
- return p;
10124
- }
10125
- function FpInvertBatch(Fp, nums, passZero = false) {
10126
- const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
10127
- const multipliedAcc = nums.reduce((acc, num, i) => {
10128
- if (Fp.is0(num))
10129
- return acc;
10130
- inverted[i] = acc;
10131
- return Fp.mul(acc, num);
10132
- }, Fp.ONE);
10133
- const invertedAcc = Fp.inv(multipliedAcc);
10134
- nums.reduceRight((acc, num, i) => {
10135
- if (Fp.is0(num))
10136
- return acc;
10137
- inverted[i] = Fp.mul(acc, inverted[i]);
10138
- return Fp.mul(acc, num);
10139
- }, invertedAcc);
10140
- return inverted;
10141
- }
10142
- function FpLegendre(Fp, n) {
10143
- const p1mod2 = (Fp.ORDER - _1n2) / _2n;
10144
- const powered = Fp.pow(n, p1mod2);
10145
- const yes = Fp.eql(powered, Fp.ONE);
10146
- const zero = Fp.eql(powered, Fp.ZERO);
10147
- const no = Fp.eql(powered, Fp.neg(Fp.ONE));
10148
- if (!yes && !zero && !no)
10149
- throw new Error("invalid Legendre symbol result");
10150
- return yes ? 1 : zero ? 0 : -1;
10151
- }
10152
- function nLength(n, nBitLength) {
10153
- if (nBitLength !== void 0)
10154
- anumber(nBitLength);
10155
- const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
10156
- const nByteLength = Math.ceil(_nBitLength / 8);
10157
- return { nBitLength: _nBitLength, nByteLength };
10158
- }
10159
- var _Field = class {
10160
- ORDER;
10161
- BITS;
10162
- BYTES;
10163
- isLE;
10164
- ZERO = _0n2;
10165
- ONE = _1n2;
10166
- _lengths;
10167
- _sqrt;
10168
- // cached sqrt
10169
- _mod;
10170
- constructor(ORDER, opts = {}) {
10171
- if (ORDER <= _0n2)
10172
- throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
10173
- let _nbitLength = void 0;
10174
- this.isLE = false;
10175
- if (opts != null && typeof opts === "object") {
10176
- if (typeof opts.BITS === "number")
10177
- _nbitLength = opts.BITS;
10178
- if (typeof opts.sqrt === "function")
10179
- this.sqrt = opts.sqrt;
10180
- if (typeof opts.isLE === "boolean")
10181
- this.isLE = opts.isLE;
10182
- if (opts.allowedLengths)
10183
- this._lengths = opts.allowedLengths?.slice();
10184
- if (typeof opts.modFromBytes === "boolean")
10185
- this._mod = opts.modFromBytes;
10186
- }
10187
- const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
10188
- if (nByteLength > 2048)
10189
- throw new Error("invalid field: expected ORDER of <= 2048 bytes");
10190
- this.ORDER = ORDER;
10191
- this.BITS = nBitLength;
10192
- this.BYTES = nByteLength;
10193
- this._sqrt = void 0;
10194
- Object.preventExtensions(this);
10195
- }
10196
- create(num) {
10197
- return mod(num, this.ORDER);
10198
- }
10199
- isValid(num) {
10200
- if (typeof num !== "bigint")
10201
- throw new Error("invalid field element: expected bigint, got " + typeof num);
10202
- return _0n2 <= num && num < this.ORDER;
10203
- }
10204
- is0(num) {
10205
- return num === _0n2;
10206
- }
10207
- // is valid and invertible
10208
- isValidNot0(num) {
10209
- return !this.is0(num) && this.isValid(num);
10210
- }
10211
- isOdd(num) {
10212
- return (num & _1n2) === _1n2;
10213
- }
10214
- neg(num) {
10215
- return mod(-num, this.ORDER);
10216
- }
10217
- eql(lhs, rhs) {
10218
- return lhs === rhs;
10219
- }
10220
- sqr(num) {
10221
- return mod(num * num, this.ORDER);
10222
- }
10223
- add(lhs, rhs) {
10224
- return mod(lhs + rhs, this.ORDER);
10225
- }
10226
- sub(lhs, rhs) {
10227
- return mod(lhs - rhs, this.ORDER);
10228
- }
10229
- mul(lhs, rhs) {
10230
- return mod(lhs * rhs, this.ORDER);
10231
- }
10232
- pow(num, power) {
10233
- return FpPow(this, num, power);
10234
- }
10235
- div(lhs, rhs) {
10236
- return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
10237
- }
10238
- // Same as above, but doesn't normalize
10239
- sqrN(num) {
10240
- return num * num;
10241
- }
10242
- addN(lhs, rhs) {
10243
- return lhs + rhs;
10244
- }
10245
- subN(lhs, rhs) {
10246
- return lhs - rhs;
10247
- }
10248
- mulN(lhs, rhs) {
10249
- return lhs * rhs;
10250
- }
10251
- inv(num) {
10252
- return invert(num, this.ORDER);
10253
- }
10254
- sqrt(num) {
10255
- if (!this._sqrt)
10256
- this._sqrt = FpSqrt(this.ORDER);
10257
- return this._sqrt(this, num);
10258
- }
10259
- toBytes(num) {
10260
- return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
10261
- }
10262
- fromBytes(bytes, skipValidation = false) {
10263
- abytes(bytes);
10264
- const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
10265
- if (allowedLengths) {
10266
- if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
10267
- throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
10268
- }
10269
- const padded = new Uint8Array(BYTES);
10270
- padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
10271
- bytes = padded;
10272
- }
10273
- if (bytes.length !== BYTES)
10274
- throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
10275
- let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
10276
- if (modFromBytes)
10277
- scalar = mod(scalar, ORDER);
10278
- if (!skipValidation) {
10279
- if (!this.isValid(scalar))
10280
- throw new Error("invalid field element: outside of range 0..ORDER");
10281
- }
10282
- return scalar;
10283
- }
10284
- // TODO: we don't need it here, move out to separate fn
10285
- invertBatch(lst) {
10286
- return FpInvertBatch(this, lst);
10287
- }
10288
- // We can't move this out because Fp6, Fp12 implement it
10289
- // and it's unclear what to return in there.
10290
- cmov(a, b, condition) {
10291
- return condition ? b : a;
10292
- }
10293
- };
10294
- function Field(ORDER, opts = {}) {
10295
- return new _Field(ORDER, opts);
10296
- }
10297
- function getFieldBytesLength(fieldOrder) {
10298
- if (typeof fieldOrder !== "bigint")
10299
- throw new Error("field order must be bigint");
10300
- const bitLength = fieldOrder.toString(2).length;
10301
- return Math.ceil(bitLength / 8);
10302
- }
10303
- function getMinHashLength(fieldOrder) {
10304
- const length = getFieldBytesLength(fieldOrder);
10305
- return length + Math.ceil(length / 2);
10306
- }
10307
- function mapHashToField(key, fieldOrder, isLE = false) {
10308
- abytes(key);
10309
- const len = key.length;
10310
- const fieldLen = getFieldBytesLength(fieldOrder);
10311
- const minLen = getMinHashLength(fieldOrder);
10312
- if (len < 16 || len < minLen || len > 1024)
10313
- throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
10314
- const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
10315
- const reduced = mod(num, fieldOrder - _1n2) + _1n2;
10316
- return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
10317
- }
10318
-
10319
- // node_modules/@noble/curves/abstract/curve.js
10320
- var _0n3 = /* @__PURE__ */ BigInt(0);
10321
- var _1n3 = /* @__PURE__ */ BigInt(1);
10322
- function negateCt(condition, item) {
10323
- const neg = item.negate();
10324
- return condition ? neg : item;
10325
- }
10326
- function normalizeZ(c, points) {
10327
- const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
10328
- return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
10329
- }
10330
- function validateW(W, bits) {
10331
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
10332
- throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
10333
- }
10334
- function calcWOpts(W, scalarBits) {
10335
- validateW(W, scalarBits);
10336
- const windows = Math.ceil(scalarBits / W) + 1;
10337
- const windowSize = 2 ** (W - 1);
10338
- const maxNumber = 2 ** W;
10339
- const mask = bitMask(W);
10340
- const shiftBy = BigInt(W);
10341
- return { windows, windowSize, mask, maxNumber, shiftBy };
10342
- }
10343
- function calcOffsets(n, window, wOpts) {
10344
- const { windowSize, mask, maxNumber, shiftBy } = wOpts;
10345
- let wbits = Number(n & mask);
10346
- let nextN = n >> shiftBy;
10347
- if (wbits > windowSize) {
10348
- wbits -= maxNumber;
10349
- nextN += _1n3;
10350
- }
10351
- const offsetStart = window * windowSize;
10352
- const offset = offsetStart + Math.abs(wbits) - 1;
10353
- const isZero = wbits === 0;
10354
- const isNeg = wbits < 0;
10355
- const isNegF = window % 2 !== 0;
10356
- const offsetF = offsetStart;
10357
- return { nextN, offset, isZero, isNeg, isNegF, offsetF };
10358
- }
10359
- var pointPrecomputes = /* @__PURE__ */ new WeakMap();
10360
- var pointWindowSizes = /* @__PURE__ */ new WeakMap();
10361
- function getW(P) {
10362
- return pointWindowSizes.get(P) || 1;
10363
- }
10364
- function assert0(n) {
10365
- if (n !== _0n3)
10366
- throw new Error("invalid wNAF");
10367
- }
10368
- var wNAF = class {
10369
- BASE;
10370
- ZERO;
10371
- Fn;
10372
- bits;
10373
- // Parametrized with a given Point class (not individual point)
10374
- constructor(Point, bits) {
10375
- this.BASE = Point.BASE;
10376
- this.ZERO = Point.ZERO;
10377
- this.Fn = Point.Fn;
10378
- this.bits = bits;
10379
- }
10380
- // non-const time multiplication ladder
10381
- _unsafeLadder(elm, n, p = this.ZERO) {
10382
- let d = elm;
10383
- while (n > _0n3) {
10384
- if (n & _1n3)
10385
- p = p.add(d);
10386
- d = d.double();
10387
- n >>= _1n3;
10388
- }
10389
- return p;
10390
- }
10391
- /**
10392
- * Creates a wNAF precomputation window. Used for caching.
10393
- * Default window size is set by `utils.precompute()` and is equal to 8.
10394
- * Number of precomputed points depends on the curve size:
10395
- * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
10396
- * - 𝑊 is the window size
10397
- * - 𝑛 is the bitlength of the curve order.
10398
- * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
10399
- * @param point Point instance
10400
- * @param W window size
10401
- * @returns precomputed point tables flattened to a single array
10402
- */
10403
- precomputeWindow(point, W) {
10404
- const { windows, windowSize } = calcWOpts(W, this.bits);
10405
- const points = [];
10406
- let p = point;
10407
- let base = p;
10408
- for (let window = 0; window < windows; window++) {
10409
- base = p;
10410
- points.push(base);
10411
- for (let i = 1; i < windowSize; i++) {
10412
- base = base.add(p);
10413
- points.push(base);
10414
- }
10415
- p = base.double();
10416
- }
10417
- return points;
10418
- }
10419
- /**
10420
- * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
10421
- * More compact implementation:
10422
- * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
10423
- * @returns real and fake (for const-time) points
10424
- */
10425
- wNAF(W, precomputes, n) {
10426
- if (!this.Fn.isValid(n))
10427
- throw new Error("invalid scalar");
10428
- let p = this.ZERO;
10429
- let f = this.BASE;
10430
- const wo = calcWOpts(W, this.bits);
10431
- for (let window = 0; window < wo.windows; window++) {
10432
- const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
10433
- n = nextN;
10434
- if (isZero) {
10435
- f = f.add(negateCt(isNegF, precomputes[offsetF]));
10436
- } else {
10437
- p = p.add(negateCt(isNeg, precomputes[offset]));
10438
- }
10439
- }
10440
- assert0(n);
10441
- return { p, f };
10442
- }
10443
- /**
10444
- * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
10445
- * @param acc accumulator point to add result of multiplication
10446
- * @returns point
10447
- */
10448
- wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
10449
- const wo = calcWOpts(W, this.bits);
10450
- for (let window = 0; window < wo.windows; window++) {
10451
- if (n === _0n3)
10452
- break;
10453
- const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
10454
- n = nextN;
10455
- if (isZero) {
10456
- continue;
10457
- } else {
10458
- const item = precomputes[offset];
10459
- acc = acc.add(isNeg ? item.negate() : item);
10460
- }
10461
- }
10462
- assert0(n);
10463
- return acc;
10464
- }
10465
- getPrecomputes(W, point, transform) {
10466
- let comp = pointPrecomputes.get(point);
10467
- if (!comp) {
10468
- comp = this.precomputeWindow(point, W);
10469
- if (W !== 1) {
10470
- if (typeof transform === "function")
10471
- comp = transform(comp);
10472
- pointPrecomputes.set(point, comp);
10473
- }
10474
- }
10475
- return comp;
10476
- }
10477
- cached(point, scalar, transform) {
10478
- const W = getW(point);
10479
- return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
10480
- }
10481
- unsafe(point, scalar, transform, prev) {
10482
- const W = getW(point);
10483
- if (W === 1)
10484
- return this._unsafeLadder(point, scalar, prev);
10485
- return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
10486
- }
10487
- // We calculate precomputes for elliptic curve point multiplication
10488
- // using windowed method. This specifies window size and
10489
- // stores precomputed values. Usually only base point would be precomputed.
10490
- createCache(P, W) {
10491
- validateW(W, this.bits);
10492
- pointWindowSizes.set(P, W);
10493
- pointPrecomputes.delete(P);
10494
- }
10495
- hasCache(elm) {
10496
- return getW(elm) !== 1;
10497
- }
10498
- };
10499
- function mulEndoUnsafe(Point, point, k1, k2) {
10500
- let acc = point;
10501
- let p1 = Point.ZERO;
10502
- let p2 = Point.ZERO;
10503
- while (k1 > _0n3 || k2 > _0n3) {
10504
- if (k1 & _1n3)
10505
- p1 = p1.add(acc);
10506
- if (k2 & _1n3)
10507
- p2 = p2.add(acc);
10508
- acc = acc.double();
10509
- k1 >>= _1n3;
10510
- k2 >>= _1n3;
10511
- }
10512
- return { p1, p2 };
10513
- }
10514
- function createField(order, field, isLE) {
10515
- if (field) {
10516
- if (field.ORDER !== order)
10517
- throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
10518
- validateField(field);
10519
- return field;
10520
- } else {
10521
- return Field(order, { isLE });
10522
- }
10523
- }
10524
- function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
10525
- if (FpFnLE === void 0)
10526
- FpFnLE = type === "edwards";
10527
- if (!CURVE || typeof CURVE !== "object")
10528
- throw new Error(`expected valid ${type} CURVE object`);
10529
- for (const p of ["p", "n", "h"]) {
10530
- const val = CURVE[p];
10531
- if (!(typeof val === "bigint" && val > _0n3))
10532
- throw new Error(`CURVE.${p} must be positive bigint`);
10533
- }
10534
- const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
10535
- const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
10536
- const _b = type === "weierstrass" ? "b" : "d";
10537
- const params = ["Gx", "Gy", "a", _b];
10538
- for (const p of params) {
10539
- if (!Fp.isValid(CURVE[p]))
10540
- throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
10541
- }
10542
- CURVE = Object.freeze(Object.assign({}, CURVE));
10543
- return { CURVE, Fp, Fn };
10544
- }
10545
- function createKeygen(randomSecretKey, getPublicKey2) {
10546
- return function keygen(seed) {
10547
- const secretKey = randomSecretKey(seed);
10548
- return { secretKey, publicKey: getPublicKey2(secretKey) };
10549
- };
10550
- }
10551
-
10552
- // node_modules/@noble/hashes/hmac.js
10553
- var _HMAC = class {
10554
- oHash;
10555
- iHash;
10556
- blockLen;
10557
- outputLen;
10558
- finished = false;
10559
- destroyed = false;
10560
- constructor(hash, key) {
10561
- ahash(hash);
10562
- abytes(key, void 0, "key");
10563
- this.iHash = hash.create();
10564
- if (typeof this.iHash.update !== "function")
10565
- throw new Error("Expected instance of class which extends utils.Hash");
10566
- this.blockLen = this.iHash.blockLen;
10567
- this.outputLen = this.iHash.outputLen;
10568
- const blockLen = this.blockLen;
10569
- const pad = new Uint8Array(blockLen);
10570
- pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
10571
- for (let i = 0; i < pad.length; i++)
10572
- pad[i] ^= 54;
10573
- this.iHash.update(pad);
10574
- this.oHash = hash.create();
10575
- for (let i = 0; i < pad.length; i++)
10576
- pad[i] ^= 54 ^ 92;
10577
- this.oHash.update(pad);
10578
- clean(pad);
10579
- }
10580
- update(buf) {
10581
- aexists(this);
10582
- this.iHash.update(buf);
10583
- return this;
10584
- }
10585
- digestInto(out) {
10586
- aexists(this);
10587
- abytes(out, this.outputLen, "output");
10588
- this.finished = true;
10589
- this.iHash.digestInto(out);
10590
- this.oHash.update(out);
10591
- this.oHash.digestInto(out);
10592
- this.destroy();
10593
- }
10594
- digest() {
10595
- const out = new Uint8Array(this.oHash.outputLen);
10596
- this.digestInto(out);
10597
- return out;
10598
- }
10599
- _cloneInto(to) {
10600
- to ||= Object.create(Object.getPrototypeOf(this), {});
10601
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
10602
- to = to;
10603
- to.finished = finished;
10604
- to.destroyed = destroyed;
10605
- to.blockLen = blockLen;
10606
- to.outputLen = outputLen;
10607
- to.oHash = oHash._cloneInto(to.oHash);
10608
- to.iHash = iHash._cloneInto(to.iHash);
10609
- return to;
10610
- }
10611
- clone() {
10612
- return this._cloneInto();
10613
- }
10614
- destroy() {
10615
- this.destroyed = true;
10616
- this.oHash.destroy();
10617
- this.iHash.destroy();
10618
- }
10619
- };
10620
- var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
10621
- hmac.create = (hash, key) => new _HMAC(hash, key);
10622
-
10623
- // node_modules/@noble/curves/abstract/weierstrass.js
10624
- var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
10625
- function _splitEndoScalar(k, basis, n) {
10626
- const [[a1, b1], [a2, b2]] = basis;
10627
- const c1 = divNearest(b2 * k, n);
10628
- const c2 = divNearest(-b1 * k, n);
10629
- let k1 = k - c1 * a1 - c2 * a2;
10630
- let k2 = -c1 * b1 - c2 * b2;
10631
- const k1neg = k1 < _0n4;
10632
- const k2neg = k2 < _0n4;
10633
- if (k1neg)
10634
- k1 = -k1;
10635
- if (k2neg)
10636
- k2 = -k2;
10637
- const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
10638
- if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
10639
- throw new Error("splitScalar (endomorphism): failed, k=" + k);
10640
- }
10641
- return { k1neg, k1, k2neg, k2 };
10642
- }
10643
- function validateSigFormat(format) {
10644
- if (!["compact", "recovered", "der"].includes(format))
10645
- throw new Error('Signature format must be "compact", "recovered", or "der"');
10646
- return format;
10647
- }
10648
- function validateSigOpts(opts, def) {
10649
- const optsn = {};
10650
- for (let optName of Object.keys(def)) {
10651
- optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
10652
- }
10653
- abool(optsn.lowS, "lowS");
10654
- abool(optsn.prehash, "prehash");
10655
- if (optsn.format !== void 0)
10656
- validateSigFormat(optsn.format);
10657
- return optsn;
10658
- }
10659
- var DERErr = class extends Error {
10660
- constructor(m = "") {
10661
- super(m);
10662
- }
10663
- };
10664
- var DER = {
10665
- // asn.1 DER encoding utils
10666
- Err: DERErr,
10667
- // Basic building block is TLV (Tag-Length-Value)
10668
- _tlv: {
10669
- encode: (tag, data) => {
10670
- const { Err: E } = DER;
10671
- if (tag < 0 || tag > 256)
10672
- throw new E("tlv.encode: wrong tag");
10673
- if (data.length & 1)
10674
- throw new E("tlv.encode: unpadded data");
10675
- const dataLen = data.length / 2;
10676
- const len = numberToHexUnpadded(dataLen);
10677
- if (len.length / 2 & 128)
10678
- throw new E("tlv.encode: long form length too big");
10679
- const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
10680
- const t = numberToHexUnpadded(tag);
10681
- return t + lenLen + len + data;
10682
- },
10683
- // v - value, l - left bytes (unparsed)
10684
- decode(tag, data) {
10685
- const { Err: E } = DER;
10686
- let pos = 0;
10687
- if (tag < 0 || tag > 256)
10688
- throw new E("tlv.encode: wrong tag");
10689
- if (data.length < 2 || data[pos++] !== tag)
10690
- throw new E("tlv.decode: wrong tlv");
10691
- const first = data[pos++];
10692
- const isLong = !!(first & 128);
10693
- let length = 0;
10694
- if (!isLong)
10695
- length = first;
10696
- else {
10697
- const lenLen = first & 127;
10698
- if (!lenLen)
10699
- throw new E("tlv.decode(long): indefinite length not supported");
10700
- if (lenLen > 4)
10701
- throw new E("tlv.decode(long): byte length is too big");
10702
- const lengthBytes = data.subarray(pos, pos + lenLen);
10703
- if (lengthBytes.length !== lenLen)
10704
- throw new E("tlv.decode: length bytes not complete");
10705
- if (lengthBytes[0] === 0)
10706
- throw new E("tlv.decode(long): zero leftmost byte");
10707
- for (const b of lengthBytes)
10708
- length = length << 8 | b;
10709
- pos += lenLen;
10710
- if (length < 128)
10711
- throw new E("tlv.decode(long): not minimal encoding");
10712
- }
10713
- const v = data.subarray(pos, pos + length);
10714
- if (v.length !== length)
10715
- throw new E("tlv.decode: wrong value length");
10716
- return { v, l: data.subarray(pos + length) };
10717
- }
10718
- },
10719
- // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
10720
- // since we always use positive integers here. It must always be empty:
10721
- // - add zero byte if exists
10722
- // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
10723
- _int: {
10724
- encode(num) {
10725
- const { Err: E } = DER;
10726
- if (num < _0n4)
10727
- throw new E("integer: negative integers are not allowed");
10728
- let hex = numberToHexUnpadded(num);
10729
- if (Number.parseInt(hex[0], 16) & 8)
10730
- hex = "00" + hex;
10731
- if (hex.length & 1)
10732
- throw new E("unexpected DER parsing assertion: unpadded hex");
10733
- return hex;
10734
- },
10735
- decode(data) {
10736
- const { Err: E } = DER;
10737
- if (data[0] & 128)
10738
- throw new E("invalid signature integer: negative");
10739
- if (data[0] === 0 && !(data[1] & 128))
10740
- throw new E("invalid signature integer: unnecessary leading zero");
10741
- return bytesToNumberBE(data);
10742
- }
10743
- },
10744
- toSig(bytes) {
10745
- const { Err: E, _int: int, _tlv: tlv } = DER;
10746
- const data = abytes(bytes, void 0, "signature");
10747
- const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
10748
- if (seqLeftBytes.length)
10749
- throw new E("invalid signature: left bytes after parsing");
10750
- const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
10751
- const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
10752
- if (sLeftBytes.length)
10753
- throw new E("invalid signature: left bytes after parsing");
10754
- return { r: int.decode(rBytes), s: int.decode(sBytes) };
10755
- },
10756
- hexFromSig(sig) {
10757
- const { _tlv: tlv, _int: int } = DER;
10758
- const rs = tlv.encode(2, int.encode(sig.r));
10759
- const ss = tlv.encode(2, int.encode(sig.s));
10760
- const seq = rs + ss;
10761
- return tlv.encode(48, seq);
10762
- }
10763
- };
10764
- var _0n4 = BigInt(0);
10765
- var _1n4 = BigInt(1);
10766
- var _2n2 = BigInt(2);
10767
- var _3n2 = BigInt(3);
10768
- var _4n2 = BigInt(4);
10769
- function weierstrass(params, extraOpts = {}) {
10770
- const validated = createCurveFields("weierstrass", params, extraOpts);
10771
- const { Fp, Fn } = validated;
10772
- let CURVE = validated.CURVE;
10773
- const { h: cofactor, n: CURVE_ORDER2 } = CURVE;
10774
- validateObject(extraOpts, {}, {
10775
- allowInfinityPoint: "boolean",
10776
- clearCofactor: "function",
10777
- isTorsionFree: "function",
10778
- fromBytes: "function",
10779
- toBytes: "function",
10780
- endo: "object"
10781
- });
10782
- const { endo } = extraOpts;
10783
- if (endo) {
10784
- if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
10785
- throw new Error('invalid endo: expected "beta": bigint and "basises": array');
10786
- }
10787
- }
10788
- const lengths = getWLengths(Fp, Fn);
10789
- function assertCompressionIsSupported() {
10790
- if (!Fp.isOdd)
10791
- throw new Error("compression is not supported: Field does not have .isOdd()");
10792
- }
10793
- function pointToBytes(_c, point, isCompressed) {
10794
- const { x, y } = point.toAffine();
10795
- const bx = Fp.toBytes(x);
10796
- abool(isCompressed, "isCompressed");
10797
- if (isCompressed) {
10798
- assertCompressionIsSupported();
10799
- const hasEvenY = !Fp.isOdd(y);
10800
- return concatBytes(pprefix(hasEvenY), bx);
10801
- } else {
10802
- return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
10803
- }
10804
- }
10805
- function pointFromBytes(bytes) {
10806
- abytes(bytes, void 0, "Point");
10807
- const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
10808
- const length = bytes.length;
10809
- const head = bytes[0];
10810
- const tail = bytes.subarray(1);
10811
- if (length === comp && (head === 2 || head === 3)) {
10812
- const x = Fp.fromBytes(tail);
10813
- if (!Fp.isValid(x))
10814
- throw new Error("bad point: is not on curve, wrong x");
10815
- const y2 = weierstrassEquation(x);
10816
- let y;
10817
- try {
10818
- y = Fp.sqrt(y2);
10819
- } catch (sqrtError) {
10820
- const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
10821
- throw new Error("bad point: is not on curve, sqrt error" + err);
10822
- }
10823
- assertCompressionIsSupported();
10824
- const evenY = Fp.isOdd(y);
10825
- const evenH = (head & 1) === 1;
10826
- if (evenH !== evenY)
10827
- y = Fp.neg(y);
10828
- return { x, y };
10829
- } else if (length === uncomp && head === 4) {
10830
- const L = Fp.BYTES;
10831
- const x = Fp.fromBytes(tail.subarray(0, L));
10832
- const y = Fp.fromBytes(tail.subarray(L, L * 2));
10833
- if (!isValidXY(x, y))
10834
- throw new Error("bad point: is not on curve");
10835
- return { x, y };
10836
- } else {
10837
- throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
10838
- }
10839
- }
10840
- const encodePoint = extraOpts.toBytes || pointToBytes;
10841
- const decodePoint = extraOpts.fromBytes || pointFromBytes;
10842
- function weierstrassEquation(x) {
10843
- const x2 = Fp.sqr(x);
10844
- const x3 = Fp.mul(x2, x);
10845
- return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
10846
- }
10847
- function isValidXY(x, y) {
10848
- const left = Fp.sqr(y);
10849
- const right = weierstrassEquation(x);
10850
- return Fp.eql(left, right);
10851
- }
10852
- if (!isValidXY(CURVE.Gx, CURVE.Gy))
10853
- throw new Error("bad curve params: generator point");
10854
- const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
10855
- const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
10856
- if (Fp.is0(Fp.add(_4a3, _27b2)))
10857
- throw new Error("bad curve params: a or b");
10858
- function acoord(title, n, banZero = false) {
10859
- if (!Fp.isValid(n) || banZero && Fp.is0(n))
10860
- throw new Error(`bad point coordinate ${title}`);
10861
- return n;
10862
- }
10863
- function aprjpoint(other) {
10864
- if (!(other instanceof Point))
10865
- throw new Error("Weierstrass Point expected");
10866
- }
10867
- function splitEndoScalarN(k) {
10868
- if (!endo || !endo.basises)
10869
- throw new Error("no endo");
10870
- return _splitEndoScalar(k, endo.basises, Fn.ORDER);
10871
- }
10872
- const toAffineMemo = memoized((p, iz) => {
10873
- const { X, Y, Z } = p;
10874
- if (Fp.eql(Z, Fp.ONE))
10875
- return { x: X, y: Y };
10876
- const is0 = p.is0();
10877
- if (iz == null)
10878
- iz = is0 ? Fp.ONE : Fp.inv(Z);
10879
- const x = Fp.mul(X, iz);
10880
- const y = Fp.mul(Y, iz);
10881
- const zz = Fp.mul(Z, iz);
10882
- if (is0)
10883
- return { x: Fp.ZERO, y: Fp.ZERO };
10884
- if (!Fp.eql(zz, Fp.ONE))
10885
- throw new Error("invZ was invalid");
10886
- return { x, y };
10887
- });
10888
- const assertValidMemo = memoized((p) => {
10889
- if (p.is0()) {
10890
- if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
10891
- return;
10892
- throw new Error("bad point: ZERO");
10893
- }
10894
- const { x, y } = p.toAffine();
10895
- if (!Fp.isValid(x) || !Fp.isValid(y))
10896
- throw new Error("bad point: x or y not field elements");
10897
- if (!isValidXY(x, y))
10898
- throw new Error("bad point: equation left != right");
10899
- if (!p.isTorsionFree())
10900
- throw new Error("bad point: not in prime-order subgroup");
10901
- return true;
10902
- });
10903
- function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
10904
- k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
10905
- k1p = negateCt(k1neg, k1p);
10906
- k2p = negateCt(k2neg, k2p);
10907
- return k1p.add(k2p);
10908
- }
10909
- class Point {
10910
- // base / generator point
10911
- static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
10912
- // zero / infinity / identity point
10913
- static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
10914
- // 0, 1, 0
10915
- // math field
10916
- static Fp = Fp;
10917
- // scalar field
10918
- static Fn = Fn;
10919
- X;
10920
- Y;
10921
- Z;
10922
- /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
10923
- constructor(X, Y, Z) {
10924
- this.X = acoord("x", X);
10925
- this.Y = acoord("y", Y, true);
10926
- this.Z = acoord("z", Z);
10927
- Object.freeze(this);
10928
- }
10929
- static CURVE() {
10930
- return CURVE;
10931
- }
10932
- /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
10933
- static fromAffine(p) {
10934
- const { x, y } = p || {};
10935
- if (!p || !Fp.isValid(x) || !Fp.isValid(y))
10936
- throw new Error("invalid affine point");
10937
- if (p instanceof Point)
10938
- throw new Error("projective point not allowed");
10939
- if (Fp.is0(x) && Fp.is0(y))
10940
- return Point.ZERO;
10941
- return new Point(x, y, Fp.ONE);
10942
- }
10943
- static fromBytes(bytes) {
10944
- const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
10945
- P.assertValidity();
10946
- return P;
10947
- }
10948
- static fromHex(hex) {
10949
- return Point.fromBytes(hexToBytes2(hex));
10950
- }
10951
- get x() {
10952
- return this.toAffine().x;
10953
- }
10954
- get y() {
10955
- return this.toAffine().y;
10956
- }
10957
- /**
10958
- *
10959
- * @param windowSize
10960
- * @param isLazy true will defer table computation until the first multiplication
10961
- * @returns
10962
- */
10963
- precompute(windowSize = 8, isLazy = true) {
10964
- wnaf.createCache(this, windowSize);
10965
- if (!isLazy)
10966
- this.multiply(_3n2);
10967
- return this;
10968
- }
10969
- // TODO: return `this`
10970
- /** A point on curve is valid if it conforms to equation. */
10971
- assertValidity() {
10972
- assertValidMemo(this);
10973
- }
10974
- hasEvenY() {
10975
- const { y } = this.toAffine();
10976
- if (!Fp.isOdd)
10977
- throw new Error("Field doesn't support isOdd");
10978
- return !Fp.isOdd(y);
10979
- }
10980
- /** Compare one point to another. */
10981
- equals(other) {
10982
- aprjpoint(other);
10983
- const { X: X1, Y: Y1, Z: Z1 } = this;
10984
- const { X: X2, Y: Y2, Z: Z2 } = other;
10985
- const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
10986
- const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
10987
- return U1 && U2;
10988
- }
10989
- /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
10990
- negate() {
10991
- return new Point(this.X, Fp.neg(this.Y), this.Z);
10992
- }
10993
- // Renes-Costello-Batina exception-free doubling formula.
10994
- // There is 30% faster Jacobian formula, but it is not complete.
10995
- // https://eprint.iacr.org/2015/1060, algorithm 3
10996
- // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
10997
- double() {
10998
- const { a, b } = CURVE;
10999
- const b3 = Fp.mul(b, _3n2);
11000
- const { X: X1, Y: Y1, Z: Z1 } = this;
11001
- let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
11002
- let t0 = Fp.mul(X1, X1);
11003
- let t1 = Fp.mul(Y1, Y1);
11004
- let t2 = Fp.mul(Z1, Z1);
11005
- let t3 = Fp.mul(X1, Y1);
11006
- t3 = Fp.add(t3, t3);
11007
- Z3 = Fp.mul(X1, Z1);
11008
- Z3 = Fp.add(Z3, Z3);
11009
- X3 = Fp.mul(a, Z3);
11010
- Y3 = Fp.mul(b3, t2);
11011
- Y3 = Fp.add(X3, Y3);
11012
- X3 = Fp.sub(t1, Y3);
11013
- Y3 = Fp.add(t1, Y3);
11014
- Y3 = Fp.mul(X3, Y3);
11015
- X3 = Fp.mul(t3, X3);
11016
- Z3 = Fp.mul(b3, Z3);
11017
- t2 = Fp.mul(a, t2);
11018
- t3 = Fp.sub(t0, t2);
11019
- t3 = Fp.mul(a, t3);
11020
- t3 = Fp.add(t3, Z3);
11021
- Z3 = Fp.add(t0, t0);
11022
- t0 = Fp.add(Z3, t0);
11023
- t0 = Fp.add(t0, t2);
11024
- t0 = Fp.mul(t0, t3);
11025
- Y3 = Fp.add(Y3, t0);
11026
- t2 = Fp.mul(Y1, Z1);
11027
- t2 = Fp.add(t2, t2);
11028
- t0 = Fp.mul(t2, t3);
11029
- X3 = Fp.sub(X3, t0);
11030
- Z3 = Fp.mul(t2, t1);
11031
- Z3 = Fp.add(Z3, Z3);
11032
- Z3 = Fp.add(Z3, Z3);
11033
- return new Point(X3, Y3, Z3);
11034
- }
11035
- // Renes-Costello-Batina exception-free addition formula.
11036
- // There is 30% faster Jacobian formula, but it is not complete.
11037
- // https://eprint.iacr.org/2015/1060, algorithm 1
11038
- // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
11039
- add(other) {
11040
- aprjpoint(other);
11041
- const { X: X1, Y: Y1, Z: Z1 } = this;
11042
- const { X: X2, Y: Y2, Z: Z2 } = other;
11043
- let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
11044
- const a = CURVE.a;
11045
- const b3 = Fp.mul(CURVE.b, _3n2);
11046
- let t0 = Fp.mul(X1, X2);
11047
- let t1 = Fp.mul(Y1, Y2);
11048
- let t2 = Fp.mul(Z1, Z2);
11049
- let t3 = Fp.add(X1, Y1);
11050
- let t4 = Fp.add(X2, Y2);
11051
- t3 = Fp.mul(t3, t4);
11052
- t4 = Fp.add(t0, t1);
11053
- t3 = Fp.sub(t3, t4);
11054
- t4 = Fp.add(X1, Z1);
11055
- let t5 = Fp.add(X2, Z2);
11056
- t4 = Fp.mul(t4, t5);
11057
- t5 = Fp.add(t0, t2);
11058
- t4 = Fp.sub(t4, t5);
11059
- t5 = Fp.add(Y1, Z1);
11060
- X3 = Fp.add(Y2, Z2);
11061
- t5 = Fp.mul(t5, X3);
11062
- X3 = Fp.add(t1, t2);
11063
- t5 = Fp.sub(t5, X3);
11064
- Z3 = Fp.mul(a, t4);
11065
- X3 = Fp.mul(b3, t2);
11066
- Z3 = Fp.add(X3, Z3);
11067
- X3 = Fp.sub(t1, Z3);
11068
- Z3 = Fp.add(t1, Z3);
11069
- Y3 = Fp.mul(X3, Z3);
11070
- t1 = Fp.add(t0, t0);
11071
- t1 = Fp.add(t1, t0);
11072
- t2 = Fp.mul(a, t2);
11073
- t4 = Fp.mul(b3, t4);
11074
- t1 = Fp.add(t1, t2);
11075
- t2 = Fp.sub(t0, t2);
11076
- t2 = Fp.mul(a, t2);
11077
- t4 = Fp.add(t4, t2);
11078
- t0 = Fp.mul(t1, t4);
11079
- Y3 = Fp.add(Y3, t0);
11080
- t0 = Fp.mul(t5, t4);
11081
- X3 = Fp.mul(t3, X3);
11082
- X3 = Fp.sub(X3, t0);
11083
- t0 = Fp.mul(t3, t1);
11084
- Z3 = Fp.mul(t5, Z3);
11085
- Z3 = Fp.add(Z3, t0);
11086
- return new Point(X3, Y3, Z3);
11087
- }
11088
- subtract(other) {
11089
- return this.add(other.negate());
11090
- }
11091
- is0() {
11092
- return this.equals(Point.ZERO);
11093
- }
11094
- /**
11095
- * Constant time multiplication.
11096
- * Uses wNAF method. Windowed method may be 10% faster,
11097
- * but takes 2x longer to generate and consumes 2x memory.
11098
- * Uses precomputes when available.
11099
- * Uses endomorphism for Koblitz curves.
11100
- * @param scalar by which the point would be multiplied
11101
- * @returns New point
11102
- */
11103
- multiply(scalar) {
11104
- const { endo: endo2 } = extraOpts;
11105
- if (!Fn.isValidNot0(scalar))
11106
- throw new Error("invalid scalar: out of range");
11107
- let point, fake;
11108
- const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
11109
- if (endo2) {
11110
- const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
11111
- const { p: k1p, f: k1f } = mul(k1);
11112
- const { p: k2p, f: k2f } = mul(k2);
11113
- fake = k1f.add(k2f);
11114
- point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
11115
- } else {
11116
- const { p, f } = mul(scalar);
11117
- point = p;
11118
- fake = f;
11119
- }
11120
- return normalizeZ(Point, [point, fake])[0];
11121
- }
11122
- /**
11123
- * Non-constant-time multiplication. Uses double-and-add algorithm.
11124
- * It's faster, but should only be used when you don't care about
11125
- * an exposed secret key e.g. sig verification, which works over *public* keys.
11126
- */
11127
- multiplyUnsafe(sc) {
11128
- const { endo: endo2 } = extraOpts;
11129
- const p = this;
11130
- if (!Fn.isValid(sc))
11131
- throw new Error("invalid scalar: out of range");
11132
- if (sc === _0n4 || p.is0())
11133
- return Point.ZERO;
11134
- if (sc === _1n4)
11135
- return p;
11136
- if (wnaf.hasCache(this))
11137
- return this.multiply(sc);
11138
- if (endo2) {
11139
- const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
11140
- const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
11141
- return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
11142
- } else {
11143
- return wnaf.unsafe(p, sc);
11144
- }
11145
- }
11146
- /**
11147
- * Converts Projective point to affine (x, y) coordinates.
11148
- * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
11149
- */
11150
- toAffine(invertedZ) {
11151
- return toAffineMemo(this, invertedZ);
11152
- }
11153
- /**
11154
- * Checks whether Point is free of torsion elements (is in prime subgroup).
11155
- * Always torsion-free for cofactor=1 curves.
11156
- */
11157
- isTorsionFree() {
11158
- const { isTorsionFree } = extraOpts;
11159
- if (cofactor === _1n4)
11160
- return true;
11161
- if (isTorsionFree)
11162
- return isTorsionFree(Point, this);
11163
- return wnaf.unsafe(this, CURVE_ORDER2).is0();
11164
- }
11165
- clearCofactor() {
11166
- const { clearCofactor } = extraOpts;
11167
- if (cofactor === _1n4)
11168
- return this;
11169
- if (clearCofactor)
11170
- return clearCofactor(Point, this);
11171
- return this.multiplyUnsafe(cofactor);
11172
- }
11173
- isSmallOrder() {
11174
- return this.multiplyUnsafe(cofactor).is0();
11175
- }
11176
- toBytes(isCompressed = true) {
11177
- abool(isCompressed, "isCompressed");
11178
- this.assertValidity();
11179
- return encodePoint(Point, this, isCompressed);
11180
- }
11181
- toHex(isCompressed = true) {
11182
- return bytesToHex4(this.toBytes(isCompressed));
11183
- }
11184
- toString() {
11185
- return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
11186
- }
11187
- }
11188
- const bits = Fn.BITS;
11189
- const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
11190
- Point.BASE.precompute(8);
11191
- return Point;
11192
- }
11193
- function pprefix(hasEvenY) {
11194
- return Uint8Array.of(hasEvenY ? 2 : 3);
11195
- }
11196
- function getWLengths(Fp, Fn) {
11197
- return {
11198
- secretKey: Fn.BYTES,
11199
- publicKey: 1 + Fp.BYTES,
11200
- publicKeyUncompressed: 1 + 2 * Fp.BYTES,
11201
- publicKeyHasPrefix: true,
11202
- signature: 2 * Fn.BYTES
11203
- };
11204
- }
11205
- function ecdh(Point, ecdhOpts = {}) {
11206
- const { Fn } = Point;
11207
- const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
11208
- const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
11209
- function isValidSecretKey(secretKey) {
11210
- try {
11211
- const num = Fn.fromBytes(secretKey);
11212
- return Fn.isValidNot0(num);
11213
- } catch (error) {
11214
- return false;
11215
- }
11216
- }
11217
- function isValidPublicKey(publicKey, isCompressed) {
11218
- const { publicKey: comp, publicKeyUncompressed } = lengths;
11219
- try {
11220
- const l = publicKey.length;
11221
- if (isCompressed === true && l !== comp)
11222
- return false;
11223
- if (isCompressed === false && l !== publicKeyUncompressed)
11224
- return false;
11225
- return !!Point.fromBytes(publicKey);
11226
- } catch (error) {
11227
- return false;
11228
- }
11229
- }
11230
- function randomSecretKey(seed = randomBytes_(lengths.seed)) {
11231
- return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
11232
- }
11233
- function getPublicKey2(secretKey, isCompressed = true) {
11234
- return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
11235
- }
11236
- function isProbPub(item) {
11237
- const { secretKey, publicKey, publicKeyUncompressed } = lengths;
11238
- if (!isBytes(item))
11239
- return void 0;
11240
- if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
11241
- return void 0;
11242
- const l = abytes(item, void 0, "key").length;
11243
- return l === publicKey || l === publicKeyUncompressed;
11244
- }
11245
- function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
11246
- if (isProbPub(secretKeyA) === true)
11247
- throw new Error("first arg must be private key");
11248
- if (isProbPub(publicKeyB) === false)
11249
- throw new Error("second arg must be public key");
11250
- const s = Fn.fromBytes(secretKeyA);
11251
- const b = Point.fromBytes(publicKeyB);
11252
- return b.multiply(s).toBytes(isCompressed);
11253
- }
11254
- const utils = {
11255
- isValidSecretKey,
11256
- isValidPublicKey,
11257
- randomSecretKey
11258
- };
11259
- const keygen = createKeygen(randomSecretKey, getPublicKey2);
11260
- return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
11261
- }
11262
- function ecdsa(Point, hash, ecdsaOpts = {}) {
11263
- ahash(hash);
11264
- validateObject(ecdsaOpts, {}, {
11265
- hmac: "function",
11266
- lowS: "boolean",
11267
- randomBytes: "function",
11268
- bits2int: "function",
11269
- bits2int_modN: "function"
11270
- });
11271
- ecdsaOpts = Object.assign({}, ecdsaOpts);
11272
- const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
11273
- const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
11274
- const { Fp, Fn } = Point;
11275
- const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn;
11276
- const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
11277
- const defaultSigOpts = {
11278
- prehash: true,
11279
- lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
11280
- format: "compact",
11281
- extraEntropy: false
11282
- };
11283
- const hasLargeCofactor = CURVE_ORDER2 * _2n2 < Fp.ORDER;
11284
- function isBiggerThanHalfOrder(number) {
11285
- const HALF = CURVE_ORDER2 >> _1n4;
11286
- return number > HALF;
11287
- }
11288
- function validateRS(title, num) {
11289
- if (!Fn.isValidNot0(num))
11290
- throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
11291
- return num;
11292
- }
11293
- function assertSmallCofactor() {
11294
- if (hasLargeCofactor)
11295
- throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
11296
- }
11297
- function validateSigLength(bytes, format) {
11298
- validateSigFormat(format);
11299
- const size = lengths.signature;
11300
- const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
11301
- return abytes(bytes, sizer);
11302
- }
11303
- class Signature {
11304
- r;
11305
- s;
11306
- recovery;
11307
- constructor(r, s, recovery) {
11308
- this.r = validateRS("r", r);
11309
- this.s = validateRS("s", s);
11310
- if (recovery != null) {
11311
- assertSmallCofactor();
11312
- if (![0, 1, 2, 3].includes(recovery))
11313
- throw new Error("invalid recovery id");
11314
- this.recovery = recovery;
11315
- }
11316
- Object.freeze(this);
11317
- }
11318
- static fromBytes(bytes, format = defaultSigOpts.format) {
11319
- validateSigLength(bytes, format);
11320
- let recid;
11321
- if (format === "der") {
11322
- const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
11323
- return new Signature(r2, s2);
11324
- }
11325
- if (format === "recovered") {
11326
- recid = bytes[0];
11327
- format = "compact";
11328
- bytes = bytes.subarray(1);
11329
- }
11330
- const L = lengths.signature / 2;
11331
- const r = bytes.subarray(0, L);
11332
- const s = bytes.subarray(L, L * 2);
11333
- return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
11334
- }
11335
- static fromHex(hex, format) {
11336
- return this.fromBytes(hexToBytes2(hex), format);
11337
- }
11338
- assertRecovery() {
11339
- const { recovery } = this;
11340
- if (recovery == null)
11341
- throw new Error("invalid recovery id: must be present");
11342
- return recovery;
11343
- }
11344
- addRecoveryBit(recovery) {
11345
- return new Signature(this.r, this.s, recovery);
11346
- }
11347
- recoverPublicKey(messageHash) {
11348
- const { r, s } = this;
11349
- const recovery = this.assertRecovery();
11350
- const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER2 : r;
11351
- if (!Fp.isValid(radj))
11352
- throw new Error("invalid recovery id: sig.r+curve.n != R.x");
11353
- const x = Fp.toBytes(radj);
11354
- const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
11355
- const ir = Fn.inv(radj);
11356
- const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
11357
- const u1 = Fn.create(-h * ir);
11358
- const u2 = Fn.create(s * ir);
11359
- const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
11360
- if (Q.is0())
11361
- throw new Error("invalid recovery: point at infinify");
11362
- Q.assertValidity();
11363
- return Q;
11364
- }
11365
- // Signatures should be low-s, to prevent malleability.
11366
- hasHighS() {
11367
- return isBiggerThanHalfOrder(this.s);
11368
- }
11369
- toBytes(format = defaultSigOpts.format) {
11370
- validateSigFormat(format);
11371
- if (format === "der")
11372
- return hexToBytes2(DER.hexFromSig(this));
11373
- const { r, s } = this;
11374
- const rb = Fn.toBytes(r);
11375
- const sb = Fn.toBytes(s);
11376
- if (format === "recovered") {
11377
- assertSmallCofactor();
11378
- return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
11379
- }
11380
- return concatBytes(rb, sb);
11381
- }
11382
- toHex(format) {
11383
- return bytesToHex4(this.toBytes(format));
11384
- }
11385
- }
11386
- const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
11387
- if (bytes.length > 8192)
11388
- throw new Error("input is too large");
11389
- const num = bytesToNumberBE(bytes);
11390
- const delta = bytes.length * 8 - fnBits;
11391
- return delta > 0 ? num >> BigInt(delta) : num;
11392
- };
11393
- const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
11394
- return Fn.create(bits2int(bytes));
11395
- };
11396
- const ORDER_MASK = bitMask(fnBits);
11397
- function int2octets(num) {
11398
- aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
11399
- return Fn.toBytes(num);
11400
- }
11401
- function validateMsgAndHash(message, prehash) {
11402
- abytes(message, void 0, "message");
11403
- return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
11404
- }
11405
- function prepSig(message, secretKey, opts) {
11406
- const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
11407
- message = validateMsgAndHash(message, prehash);
11408
- const h1int = bits2int_modN(message);
11409
- const d = Fn.fromBytes(secretKey);
11410
- if (!Fn.isValidNot0(d))
11411
- throw new Error("invalid private key");
11412
- const seedArgs = [int2octets(d), int2octets(h1int)];
11413
- if (extraEntropy != null && extraEntropy !== false) {
11414
- const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
11415
- seedArgs.push(abytes(e, void 0, "extraEntropy"));
11416
- }
11417
- const seed = concatBytes(...seedArgs);
11418
- const m = h1int;
11419
- function k2sig(kBytes) {
11420
- const k = bits2int(kBytes);
11421
- if (!Fn.isValidNot0(k))
11422
- return;
11423
- const ik = Fn.inv(k);
11424
- const q = Point.BASE.multiply(k).toAffine();
11425
- const r = Fn.create(q.x);
11426
- if (r === _0n4)
11427
- return;
11428
- const s = Fn.create(ik * Fn.create(m + r * d));
11429
- if (s === _0n4)
11430
- return;
11431
- let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
11432
- let normS = s;
11433
- if (lowS && isBiggerThanHalfOrder(s)) {
11434
- normS = Fn.neg(s);
11435
- recovery ^= 1;
11436
- }
11437
- return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
11438
- }
11439
- return { seed, k2sig };
11440
- }
11441
- function sign(message, secretKey, opts = {}) {
11442
- const { seed, k2sig } = prepSig(message, secretKey, opts);
11443
- const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
11444
- const sig = drbg(seed, k2sig);
11445
- return sig.toBytes(opts.format);
11446
- }
11447
- function verify(signature, message, publicKey, opts = {}) {
11448
- const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
11449
- publicKey = abytes(publicKey, void 0, "publicKey");
11450
- message = validateMsgAndHash(message, prehash);
11451
- if (!isBytes(signature)) {
11452
- const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
11453
- throw new Error("verify expects Uint8Array signature" + end);
11454
- }
11455
- validateSigLength(signature, format);
11456
- try {
11457
- const sig = Signature.fromBytes(signature, format);
11458
- const P = Point.fromBytes(publicKey);
11459
- if (lowS && sig.hasHighS())
11460
- return false;
11461
- const { r, s } = sig;
11462
- const h = bits2int_modN(message);
11463
- const is = Fn.inv(s);
11464
- const u1 = Fn.create(h * is);
11465
- const u2 = Fn.create(r * is);
11466
- const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
11467
- if (R.is0())
11468
- return false;
11469
- const v = Fn.create(R.x);
11470
- return v === r;
11471
- } catch (e) {
11472
- return false;
11473
- }
11474
- }
11475
- function recoverPublicKey(signature, message, opts = {}) {
11476
- const { prehash } = validateSigOpts(opts, defaultSigOpts);
11477
- message = validateMsgAndHash(message, prehash);
11478
- return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
11479
- }
11480
- return Object.freeze({
11481
- keygen,
11482
- getPublicKey: getPublicKey2,
11483
- getSharedSecret,
11484
- utils,
11485
- lengths,
11486
- Point,
11487
- sign,
11488
- verify,
11489
- recoverPublicKey,
11490
- Signature,
11491
- hash
11492
- });
11493
- }
11494
-
11495
- // node_modules/@noble/curves/secp256k1.js
11496
- var secp256k1_CURVE = {
11497
- p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
11498
- n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
11499
- h: BigInt(1),
11500
- a: BigInt(0),
11501
- b: BigInt(7),
11502
- Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
11503
- Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
11504
- };
11505
- var secp256k1_ENDO = {
11506
- beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
11507
- basises: [
11508
- [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
11509
- [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
11510
- ]
11511
- };
11512
- var _2n3 = /* @__PURE__ */ BigInt(2);
11513
- function sqrtMod(y) {
11514
- const P = secp256k1_CURVE.p;
11515
- const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
11516
- const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
11517
- const b2 = y * y * y % P;
11518
- const b3 = b2 * b2 * y % P;
11519
- const b6 = pow2(b3, _3n3, P) * b3 % P;
11520
- const b9 = pow2(b6, _3n3, P) * b3 % P;
11521
- const b11 = pow2(b9, _2n3, P) * b2 % P;
11522
- const b22 = pow2(b11, _11n, P) * b11 % P;
11523
- const b44 = pow2(b22, _22n, P) * b22 % P;
11524
- const b88 = pow2(b44, _44n, P) * b44 % P;
11525
- const b176 = pow2(b88, _88n, P) * b88 % P;
11526
- const b220 = pow2(b176, _44n, P) * b44 % P;
11527
- const b223 = pow2(b220, _3n3, P) * b3 % P;
11528
- const t1 = pow2(b223, _23n, P) * b22 % P;
11529
- const t2 = pow2(t1, _6n, P) * b2 % P;
11530
- const root = pow2(t2, _2n3, P);
11531
- if (!Fpk1.eql(Fpk1.sqr(root), y))
11532
- throw new Error("Cannot find square root");
11533
- return root;
11534
- }
11535
- var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
11536
- var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
11537
- Fp: Fpk1,
11538
- endo: secp256k1_ENDO
11539
- });
11540
- var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha2564);
11541
-
11542
- // modules/market/MarketModule.ts
11543
- function hexToBytes3(hex) {
11544
- const len = hex.length >> 1;
11545
- const bytes = new Uint8Array(len);
11546
- for (let i = 0; i < len; i++) {
11547
- bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
11548
- }
11549
- return bytes;
11550
- }
11551
- function signRequest(body, privateKeyHex) {
11552
- const timestamp = Date.now();
11553
- const payload = JSON.stringify({ body, timestamp });
11554
- const messageHash = sha2564(new TextEncoder().encode(payload));
11555
- const privateKeyBytes = hexToBytes3(privateKeyHex);
11556
- const signature = secp256k1.sign(messageHash, privateKeyBytes);
11557
- const publicKey = bytesToHex4(secp256k1.getPublicKey(privateKeyBytes, true));
11558
- return {
11559
- body: JSON.stringify(body),
11560
- headers: {
11561
- "x-signature": bytesToHex4(signature),
11562
- "x-public-key": publicKey,
11563
- "x-timestamp": String(timestamp),
11564
- "content-type": "application/json"
11565
- }
11566
- };
11567
- }
11568
- function toSnakeCaseIntent(req) {
11569
- const result = {
11570
- description: req.description,
11571
- intent_type: req.intentType
11572
- };
11573
- if (req.category !== void 0) result.category = req.category;
11574
- if (req.price !== void 0) result.price = req.price;
11575
- if (req.currency !== void 0) result.currency = req.currency;
11576
- if (req.location !== void 0) result.location = req.location;
11577
- if (req.contactHandle !== void 0) result.contact_handle = req.contactHandle;
11578
- if (req.expiresInDays !== void 0) result.expires_in_days = req.expiresInDays;
11579
- return result;
11580
- }
11581
- function toSnakeCaseFilters(opts) {
11582
- const result = {};
11583
- if (opts?.filters) {
11584
- const f = opts.filters;
11585
- if (f.intentType !== void 0) result.intent_type = f.intentType;
11586
- if (f.category !== void 0) result.category = f.category;
11587
- if (f.minPrice !== void 0) result.min_price = f.minPrice;
11588
- if (f.maxPrice !== void 0) result.max_price = f.maxPrice;
11589
- if (f.location !== void 0) result.location = f.location;
11590
- }
11591
- if (opts?.limit !== void 0) result.limit = opts.limit;
11592
- return result;
11593
- }
11594
- function mapSearchResult(raw) {
11595
- return {
11596
- id: raw.id,
11597
- score: raw.score,
11598
- agentNametag: raw.agent_nametag ?? void 0,
11599
- agentPublicKey: raw.agent_public_key,
11600
- description: raw.description,
11601
- intentType: raw.intent_type,
11602
- category: raw.category ?? void 0,
11603
- price: raw.price ?? void 0,
11604
- currency: raw.currency,
11605
- location: raw.location ?? void 0,
11606
- contactMethod: raw.contact_method,
11607
- contactHandle: raw.contact_handle ?? void 0,
11608
- createdAt: raw.created_at,
11609
- expiresAt: raw.expires_at
11610
- };
11611
- }
11612
- function mapMyIntent(raw) {
11613
- return {
11614
- id: raw.id,
11615
- intentType: raw.intent_type,
11616
- category: raw.category ?? void 0,
11617
- price: raw.price ?? void 0,
11618
- currency: raw.currency,
11619
- location: raw.location ?? void 0,
11620
- status: raw.status,
11621
- createdAt: raw.created_at,
11622
- expiresAt: raw.expires_at
11623
- };
11624
- }
11625
- function mapFeedListing(raw) {
11626
- return {
11627
- id: raw.id,
11628
- title: raw.title,
11629
- descriptionPreview: raw.description_preview,
11630
- agentName: raw.agent_name,
11631
- agentId: raw.agent_id,
11632
- type: raw.type,
11633
- createdAt: raw.created_at
11634
- };
11635
- }
11636
- function mapFeedMessage(raw) {
11637
- if (raw.type === "initial") {
11638
- return { type: "initial", listings: (raw.listings ?? []).map(mapFeedListing) };
11639
- }
11640
- return { type: "new", listing: mapFeedListing(raw.listing) };
11641
- }
11642
- var MarketModule = class {
11643
- apiUrl;
11644
- timeout;
11645
- identity = null;
11646
- registered = false;
11647
- constructor(config) {
11648
- this.apiUrl = (config?.apiUrl ?? DEFAULT_MARKET_API_URL).replace(/\/+$/, "");
11649
- this.timeout = config?.timeout ?? 3e4;
11650
- }
11651
- /** Called by Sphere after construction */
11652
- initialize(deps) {
11653
- this.identity = deps.identity;
11654
- }
11655
- /** No-op — stateless module */
11656
- async load() {
11657
- }
11658
- /** No-op — stateless module */
11659
- destroy() {
11660
- }
11661
- // ---------------------------------------------------------------------------
11662
- // Public API
11663
- // ---------------------------------------------------------------------------
11664
- /** Post a new intent (agent is auto-registered on first post) */
11665
- async postIntent(intent) {
11666
- const body = toSnakeCaseIntent(intent);
11667
- const data = await this.apiPost("/api/intents", body);
11668
- return {
11669
- intentId: data.intent_id ?? data.intentId,
11670
- message: data.message,
11671
- expiresAt: data.expires_at ?? data.expiresAt
11672
- };
11673
- }
11674
- /** Semantic search for intents (public — no auth required) */
11675
- async search(query, opts) {
11676
- const body = {
11677
- query,
11678
- ...toSnakeCaseFilters(opts)
11679
- };
11680
- const data = await this.apiPublicPost("/api/search", body);
11681
- let results = (data.intents ?? []).map(mapSearchResult);
11682
- const minScore = opts?.filters?.minScore;
11683
- if (minScore != null) {
11684
- results = results.filter((r) => Math.round(r.score * 100) >= Math.round(minScore * 100));
11685
- }
11686
- return { intents: results, count: results.length };
11687
- }
11688
- /** List own intents (authenticated) */
11689
- async getMyIntents() {
11690
- const data = await this.apiGet("/api/intents");
11691
- return (data.intents ?? []).map(mapMyIntent);
11692
- }
11693
- /** Close (delete) an intent */
11694
- async closeIntent(intentId) {
11695
- await this.apiDelete(`/api/intents/${encodeURIComponent(intentId)}`);
11696
- }
11697
- /** Fetch the most recent listings via REST (public — no auth required) */
11698
- async getRecentListings() {
11699
- const res = await fetch(`${this.apiUrl}/api/feed/recent`, {
11700
- signal: AbortSignal.timeout(this.timeout)
11701
- });
11702
- const data = await this.parseResponse(res);
11703
- return (data.listings ?? []).map(mapFeedListing);
11704
- }
11705
- /**
11706
- * Subscribe to the live listing feed via WebSocket.
11707
- * Returns an unsubscribe function that closes the connection.
11708
- *
11709
- * Requires a WebSocket implementation — works natively in browsers
11710
- * and in Node.js 21+ (or with the `ws` package).
11711
- */
11712
- subscribeFeed(listener) {
11713
- const wsUrl = this.apiUrl.replace(/^http/, "ws") + "/ws/feed";
11714
- const ws2 = new WebSocket(wsUrl);
11715
- ws2.onmessage = (event) => {
11716
- try {
11717
- const raw = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
11718
- listener(mapFeedMessage(raw));
11719
- } catch {
11720
- }
11721
- };
11722
- return () => {
11723
- ws2.close();
11724
- };
11725
- }
11726
- // ---------------------------------------------------------------------------
11727
- // Private: HTTP helpers
11728
- // ---------------------------------------------------------------------------
11729
- ensureIdentity() {
11730
- if (!this.identity) {
11731
- throw new Error("MarketModule not initialized \u2014 call initialize() first");
11732
- }
11733
- }
11734
- /** Register the agent's public key with the server (idempotent) */
11735
- async ensureRegistered() {
11736
- if (this.registered) return;
11737
- this.ensureIdentity();
11738
- const publicKey = bytesToHex4(secp256k1.getPublicKey(hexToBytes3(this.identity.privateKey), true));
11739
- const body = { public_key: publicKey };
11740
- if (this.identity.nametag) body.nametag = this.identity.nametag;
11741
- const res = await fetch(`${this.apiUrl}/api/agent/register`, {
11742
- method: "POST",
11743
- headers: { "content-type": "application/json" },
11744
- body: JSON.stringify(body),
11745
- signal: AbortSignal.timeout(this.timeout)
11746
- });
11747
- if (res.ok || res.status === 409) {
11748
- this.registered = true;
11749
- return;
11750
- }
11751
- const text = await res.text();
11752
- let data;
11753
- try {
11754
- data = JSON.parse(text);
11755
- } catch {
11756
- }
11757
- throw new Error(data?.error ?? `Agent registration failed: HTTP ${res.status}`);
11758
- }
11759
- async parseResponse(res) {
11760
- const text = await res.text();
11761
- let data;
11762
- try {
11763
- data = JSON.parse(text);
11764
- } catch {
11765
- throw new Error(`Market API error: HTTP ${res.status} \u2014 unexpected response (not JSON)`);
11766
- }
11767
- if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
11768
- return data;
11769
- }
11770
- async apiPost(path, body) {
11771
- this.ensureIdentity();
11772
- await this.ensureRegistered();
11773
- const signed = signRequest(body, this.identity.privateKey);
11774
- const res = await fetch(`${this.apiUrl}${path}`, {
11775
- method: "POST",
11776
- headers: signed.headers,
11777
- body: signed.body,
11778
- signal: AbortSignal.timeout(this.timeout)
11779
- });
11780
- return this.parseResponse(res);
11781
- }
11782
- async apiGet(path) {
11783
- this.ensureIdentity();
11784
- await this.ensureRegistered();
11785
- const signed = signRequest({}, this.identity.privateKey);
11786
- const res = await fetch(`${this.apiUrl}${path}`, {
11787
- method: "GET",
11788
- headers: signed.headers,
11789
- signal: AbortSignal.timeout(this.timeout)
11790
- });
11791
- return this.parseResponse(res);
11792
- }
11793
- async apiDelete(path) {
11794
- this.ensureIdentity();
11795
- await this.ensureRegistered();
11796
- const signed = signRequest({}, this.identity.privateKey);
11797
- const res = await fetch(`${this.apiUrl}${path}`, {
11798
- method: "DELETE",
11799
- headers: signed.headers,
11800
- signal: AbortSignal.timeout(this.timeout)
11801
- });
11802
- return this.parseResponse(res);
11803
- }
11804
- async apiPublicPost(path, body) {
11805
- const res = await fetch(`${this.apiUrl}${path}`, {
11806
- method: "POST",
11807
- headers: { "content-type": "application/json" },
11808
- body: JSON.stringify(body),
11809
- signal: AbortSignal.timeout(this.timeout)
11810
- });
11811
- return this.parseResponse(res);
11812
- }
11813
- };
11814
- function createMarketModule(config) {
11815
- return new MarketModule(config);
11816
- }
11817
-
11818
9441
  // core/encryption.ts
11819
9442
  var import_crypto_js6 = __toESM(require("crypto-js"), 1);
11820
9443
  function encryptSimple(plaintext, password) {
@@ -12650,7 +10273,6 @@ var Sphere = class _Sphere {
12650
10273
  _payments;
12651
10274
  _communications;
12652
10275
  _groupChat = null;
12653
- _market = null;
12654
10276
  // Events
12655
10277
  eventHandlers = /* @__PURE__ */ new Map();
12656
10278
  // Provider management
@@ -12660,7 +10282,7 @@ var Sphere = class _Sphere {
12660
10282
  // ===========================================================================
12661
10283
  // Constructor (private)
12662
10284
  // ===========================================================================
12663
- constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig, marketConfig) {
10285
+ constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig) {
12664
10286
  this._storage = storage;
12665
10287
  this._transport = transport;
12666
10288
  this._oracle = oracle;
@@ -12671,7 +10293,6 @@ var Sphere = class _Sphere {
12671
10293
  this._payments = createPaymentsModule({ l1: l1Config });
12672
10294
  this._communications = createCommunicationsModule();
12673
10295
  this._groupChat = groupChatConfig ? createGroupChatModule(groupChatConfig) : null;
12674
- this._market = marketConfig ? createMarketModule(marketConfig) : null;
12675
10296
  }
12676
10297
  // ===========================================================================
12677
10298
  // Static Methods - Wallet Management
@@ -12719,8 +10340,8 @@ var Sphere = class _Sphere {
12719
10340
  * ```
12720
10341
  */
12721
10342
  static async init(options) {
10343
+ _Sphere.configureTokenRegistry(options.storage, options.network);
12722
10344
  const groupChat = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12723
- const market = _Sphere.resolveMarketConfig(options.market);
12724
10345
  const walletExists = await _Sphere.exists(options.storage);
12725
10346
  if (walletExists) {
12726
10347
  const sphere2 = await _Sphere.load({
@@ -12731,8 +10352,7 @@ var Sphere = class _Sphere {
12731
10352
  l1: options.l1,
12732
10353
  price: options.price,
12733
10354
  groupChat,
12734
- password: options.password,
12735
- market
10355
+ password: options.password
12736
10356
  });
12737
10357
  return { sphere: sphere2, created: false };
12738
10358
  }
@@ -12759,8 +10379,7 @@ var Sphere = class _Sphere {
12759
10379
  l1: options.l1,
12760
10380
  price: options.price,
12761
10381
  groupChat,
12762
- password: options.password,
12763
- market
10382
+ password: options.password
12764
10383
  });
12765
10384
  return { sphere, created: true, generatedMnemonic };
12766
10385
  }
@@ -12788,20 +10407,17 @@ var Sphere = class _Sphere {
12788
10407
  return config;
12789
10408
  }
12790
10409
  /**
12791
- * Resolve market module config from Sphere.init() options.
12792
- * - `true` → enable with default API URL
12793
- * - `MarketModuleConfig` pass through with defaults
12794
- * - `undefined` no market module
10410
+ * Configure TokenRegistry in the main bundle context.
10411
+ *
10412
+ * The provider factory functions (createBrowserProviders / createNodeProviders)
10413
+ * are compiled into separate bundles by tsup, each with their own inlined copy
10414
+ * of TokenRegistry. Their TokenRegistry.configure() call configures a different
10415
+ * singleton than the one used by PaymentsModule (which lives in the main bundle).
10416
+ * This method ensures the main bundle's TokenRegistry is properly configured.
12795
10417
  */
12796
- static resolveMarketConfig(config) {
12797
- if (!config) return void 0;
12798
- if (config === true) {
12799
- return { apiUrl: DEFAULT_MARKET_API_URL };
12800
- }
12801
- return {
12802
- apiUrl: config.apiUrl ?? DEFAULT_MARKET_API_URL,
12803
- timeout: config.timeout
12804
- };
10418
+ static configureTokenRegistry(storage, network) {
10419
+ const netConfig = network ? NETWORKS[network] : NETWORKS.testnet;
10420
+ TokenRegistry.configure({ remoteUrl: netConfig.tokenRegistryUrl, storage });
12805
10421
  }
12806
10422
  /**
12807
10423
  * Create new wallet with mnemonic
@@ -12813,8 +10429,8 @@ var Sphere = class _Sphere {
12813
10429
  if (await _Sphere.exists(options.storage)) {
12814
10430
  throw new Error("Wallet already exists. Use Sphere.load() or Sphere.clear() first.");
12815
10431
  }
10432
+ _Sphere.configureTokenRegistry(options.storage, options.network);
12816
10433
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12817
- const marketConfig = _Sphere.resolveMarketConfig(options.market);
12818
10434
  const sphere = new _Sphere(
12819
10435
  options.storage,
12820
10436
  options.transport,
@@ -12822,8 +10438,7 @@ var Sphere = class _Sphere {
12822
10438
  options.tokenStorage,
12823
10439
  options.l1,
12824
10440
  options.price,
12825
- groupChatConfig,
12826
- marketConfig
10441
+ groupChatConfig
12827
10442
  );
12828
10443
  sphere._password = options.password ?? null;
12829
10444
  await sphere.storeMnemonic(options.mnemonic, options.derivationPath);
@@ -12849,8 +10464,8 @@ var Sphere = class _Sphere {
12849
10464
  if (!await _Sphere.exists(options.storage)) {
12850
10465
  throw new Error("No wallet found. Use Sphere.create() to create a new wallet.");
12851
10466
  }
10467
+ _Sphere.configureTokenRegistry(options.storage, options.network);
12852
10468
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12853
- const marketConfig = _Sphere.resolveMarketConfig(options.market);
12854
10469
  const sphere = new _Sphere(
12855
10470
  options.storage,
12856
10471
  options.transport,
@@ -12858,8 +10473,7 @@ var Sphere = class _Sphere {
12858
10473
  options.tokenStorage,
12859
10474
  options.l1,
12860
10475
  options.price,
12861
- groupChatConfig,
12862
- marketConfig
10476
+ groupChatConfig
12863
10477
  );
12864
10478
  sphere._password = options.password ?? null;
12865
10479
  await sphere.loadIdentityFromStorage();
@@ -12905,7 +10519,6 @@ var Sphere = class _Sphere {
12905
10519
  console.log("[Sphere.import] Storage reconnected");
12906
10520
  }
12907
10521
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat);
12908
- const marketConfig = _Sphere.resolveMarketConfig(options.market);
12909
10522
  const sphere = new _Sphere(
12910
10523
  options.storage,
12911
10524
  options.transport,
@@ -12913,8 +10526,7 @@ var Sphere = class _Sphere {
12913
10526
  options.tokenStorage,
12914
10527
  options.l1,
12915
10528
  options.price,
12916
- groupChatConfig,
12917
- marketConfig
10529
+ groupChatConfig
12918
10530
  );
12919
10531
  sphere._password = options.password ?? null;
12920
10532
  if (options.mnemonic) {
@@ -13079,10 +10691,6 @@ var Sphere = class _Sphere {
13079
10691
  get groupChat() {
13080
10692
  return this._groupChat;
13081
10693
  }
13082
- /** Market module (intent bulletin board). Null if not configured. */
13083
- get market() {
13084
- return this._market;
13085
- }
13086
10694
  // ===========================================================================
13087
10695
  // Public Properties - State
13088
10696
  // ===========================================================================
@@ -13958,14 +11566,9 @@ var Sphere = class _Sphere {
13958
11566
  storage: this._storage,
13959
11567
  emitEvent
13960
11568
  });
13961
- this._market?.initialize({
13962
- identity: this._identity,
13963
- emitEvent
13964
- });
13965
11569
  await this._payments.load();
13966
11570
  await this._communications.load();
13967
11571
  await this._groupChat?.load();
13968
- await this._market?.load();
13969
11572
  }
13970
11573
  /**
13971
11574
  * Derive address at a specific index
@@ -14790,7 +12393,6 @@ var Sphere = class _Sphere {
14790
12393
  this._payments.destroy();
14791
12394
  this._communications.destroy();
14792
12395
  this._groupChat?.destroy();
14793
- this._market?.destroy();
14794
12396
  await this._transport.disconnect();
14795
12397
  await this._storage.disconnect();
14796
12398
  await this._oracle.disconnect();
@@ -15098,14 +12700,9 @@ var Sphere = class _Sphere {
15098
12700
  storage: this._storage,
15099
12701
  emitEvent
15100
12702
  });
15101
- this._market?.initialize({
15102
- identity: this._identity,
15103
- emitEvent
15104
- });
15105
12703
  await this._payments.load();
15106
12704
  await this._communications.load();
15107
12705
  await this._groupChat?.load();
15108
- await this._market?.load();
15109
12706
  }
15110
12707
  // ===========================================================================
15111
12708
  // Private: Helpers
@@ -15290,7 +12887,7 @@ async function checkWebSocket(url, timeoutMs) {
15290
12887
  resolve({ healthy: true, url, responseTimeMs });
15291
12888
  }
15292
12889
  };
15293
- ws2.onerror = (event) => {
12890
+ ws2.onerror = (_event) => {
15294
12891
  if (!resolved) {
15295
12892
  resolved = true;
15296
12893
  clearTimeout(timer);
@@ -15785,26 +13382,37 @@ var CoinGeckoPriceProvider = class {
15785
13382
  timeout;
15786
13383
  debug;
15787
13384
  baseUrl;
13385
+ storage;
13386
+ /** In-flight fetch promise for deduplication of concurrent getPrices() calls */
13387
+ fetchPromise = null;
13388
+ /** Token names being fetched in the current in-flight request */
13389
+ fetchNames = null;
13390
+ /** Whether persistent cache has been loaded into memory */
13391
+ persistentCacheLoaded = false;
13392
+ /** Promise for loading persistent cache (deduplication) */
13393
+ loadCachePromise = null;
15788
13394
  constructor(config) {
15789
13395
  this.apiKey = config?.apiKey;
15790
13396
  this.cacheTtlMs = config?.cacheTtlMs ?? 6e4;
15791
13397
  this.timeout = config?.timeout ?? 1e4;
15792
13398
  this.debug = config?.debug ?? false;
13399
+ this.storage = config?.storage ?? null;
15793
13400
  this.baseUrl = config?.baseUrl ?? (this.apiKey ? "https://pro-api.coingecko.com/api/v3" : "https://api.coingecko.com/api/v3");
15794
13401
  }
15795
13402
  async getPrices(tokenNames) {
15796
13403
  if (tokenNames.length === 0) {
15797
13404
  return /* @__PURE__ */ new Map();
15798
13405
  }
13406
+ if (!this.persistentCacheLoaded && this.storage) {
13407
+ await this.loadFromStorage();
13408
+ }
15799
13409
  const now = Date.now();
15800
13410
  const result = /* @__PURE__ */ new Map();
15801
13411
  const uncachedNames = [];
15802
13412
  for (const name of tokenNames) {
15803
13413
  const cached = this.cache.get(name);
15804
13414
  if (cached && cached.expiresAt > now) {
15805
- if (cached.price !== null) {
15806
- result.set(name, cached.price);
15807
- }
13415
+ result.set(name, cached.price);
15808
13416
  } else {
15809
13417
  uncachedNames.push(name);
15810
13418
  }
@@ -15812,6 +13420,41 @@ var CoinGeckoPriceProvider = class {
15812
13420
  if (uncachedNames.length === 0) {
15813
13421
  return result;
15814
13422
  }
13423
+ if (this.fetchPromise && this.fetchNames) {
13424
+ const allCovered = uncachedNames.every((n) => this.fetchNames.has(n));
13425
+ if (allCovered) {
13426
+ if (this.debug) {
13427
+ console.log(`[CoinGecko] Deduplicating request, reusing in-flight fetch`);
13428
+ }
13429
+ const fetched = await this.fetchPromise;
13430
+ for (const name of uncachedNames) {
13431
+ const price = fetched.get(name);
13432
+ if (price) {
13433
+ result.set(name, price);
13434
+ }
13435
+ }
13436
+ return result;
13437
+ }
13438
+ }
13439
+ const fetchPromise = this.doFetch(uncachedNames);
13440
+ this.fetchPromise = fetchPromise;
13441
+ this.fetchNames = new Set(uncachedNames);
13442
+ try {
13443
+ const fetched = await fetchPromise;
13444
+ for (const [name, price] of fetched) {
13445
+ result.set(name, price);
13446
+ }
13447
+ } finally {
13448
+ if (this.fetchPromise === fetchPromise) {
13449
+ this.fetchPromise = null;
13450
+ this.fetchNames = null;
13451
+ }
13452
+ }
13453
+ return result;
13454
+ }
13455
+ async doFetch(uncachedNames) {
13456
+ const result = /* @__PURE__ */ new Map();
13457
+ const now = Date.now();
15815
13458
  try {
15816
13459
  const ids = uncachedNames.join(",");
15817
13460
  const url = `${this.baseUrl}/simple/price?ids=${encodeURIComponent(ids)}&vs_currencies=usd,eur&include_24hr_change=true`;
@@ -15827,6 +13470,9 @@ var CoinGeckoPriceProvider = class {
15827
13470
  signal: AbortSignal.timeout(this.timeout)
15828
13471
  });
15829
13472
  if (!response.ok) {
13473
+ if (response.status === 429) {
13474
+ this.extendCacheOnRateLimit(uncachedNames);
13475
+ }
15830
13476
  throw new Error(`CoinGecko API error: ${response.status} ${response.statusText}`);
15831
13477
  }
15832
13478
  const data = await response.json();
@@ -15845,25 +13491,113 @@ var CoinGeckoPriceProvider = class {
15845
13491
  }
15846
13492
  for (const name of uncachedNames) {
15847
13493
  if (!result.has(name)) {
15848
- this.cache.set(name, { price: null, expiresAt: now + this.cacheTtlMs });
13494
+ const zeroPrice = {
13495
+ tokenName: name,
13496
+ priceUsd: 0,
13497
+ priceEur: 0,
13498
+ change24h: 0,
13499
+ timestamp: now
13500
+ };
13501
+ this.cache.set(name, { price: zeroPrice, expiresAt: now + this.cacheTtlMs });
13502
+ result.set(name, zeroPrice);
15849
13503
  }
15850
13504
  }
15851
13505
  if (this.debug) {
15852
13506
  console.log(`[CoinGecko] Fetched ${result.size} prices`);
15853
13507
  }
13508
+ this.saveToStorage();
15854
13509
  } catch (error) {
15855
13510
  if (this.debug) {
15856
13511
  console.warn("[CoinGecko] Fetch failed, using stale cache:", error);
15857
13512
  }
15858
13513
  for (const name of uncachedNames) {
15859
13514
  const stale = this.cache.get(name);
15860
- if (stale?.price) {
13515
+ if (stale) {
15861
13516
  result.set(name, stale.price);
15862
13517
  }
15863
13518
  }
15864
13519
  }
15865
13520
  return result;
15866
13521
  }
13522
+ // ===========================================================================
13523
+ // Persistent Storage
13524
+ // ===========================================================================
13525
+ /**
13526
+ * Load cached prices from StorageProvider into in-memory cache.
13527
+ * Only loads entries that are still within cacheTtlMs.
13528
+ */
13529
+ async loadFromStorage() {
13530
+ if (this.loadCachePromise) {
13531
+ return this.loadCachePromise;
13532
+ }
13533
+ this.loadCachePromise = this.doLoadFromStorage();
13534
+ try {
13535
+ await this.loadCachePromise;
13536
+ } finally {
13537
+ this.loadCachePromise = null;
13538
+ }
13539
+ }
13540
+ async doLoadFromStorage() {
13541
+ this.persistentCacheLoaded = true;
13542
+ if (!this.storage) return;
13543
+ try {
13544
+ const [cached, cachedTs] = await Promise.all([
13545
+ this.storage.get(STORAGE_KEYS_GLOBAL.PRICE_CACHE),
13546
+ this.storage.get(STORAGE_KEYS_GLOBAL.PRICE_CACHE_TS)
13547
+ ]);
13548
+ if (!cached || !cachedTs) return;
13549
+ const ts = parseInt(cachedTs, 10);
13550
+ if (isNaN(ts)) return;
13551
+ const age = Date.now() - ts;
13552
+ if (age > this.cacheTtlMs) return;
13553
+ const data = JSON.parse(cached);
13554
+ const expiresAt = ts + this.cacheTtlMs;
13555
+ for (const [name, price] of Object.entries(data)) {
13556
+ if (!this.cache.has(name)) {
13557
+ this.cache.set(name, { price, expiresAt });
13558
+ }
13559
+ }
13560
+ if (this.debug) {
13561
+ console.log(`[CoinGecko] Loaded ${Object.keys(data).length} prices from persistent cache`);
13562
+ }
13563
+ } catch {
13564
+ }
13565
+ }
13566
+ /**
13567
+ * Save current prices to StorageProvider (fire-and-forget).
13568
+ */
13569
+ saveToStorage() {
13570
+ if (!this.storage) return;
13571
+ const data = {};
13572
+ for (const [name, entry] of this.cache) {
13573
+ data[name] = entry.price;
13574
+ }
13575
+ Promise.all([
13576
+ this.storage.set(STORAGE_KEYS_GLOBAL.PRICE_CACHE, JSON.stringify(data)),
13577
+ this.storage.set(STORAGE_KEYS_GLOBAL.PRICE_CACHE_TS, String(Date.now()))
13578
+ ]).catch(() => {
13579
+ });
13580
+ }
13581
+ // ===========================================================================
13582
+ // Rate-limit handling
13583
+ // ===========================================================================
13584
+ /**
13585
+ * On 429 rate-limit, extend stale cache entries so subsequent calls
13586
+ * don't immediately retry and hammer the API.
13587
+ */
13588
+ extendCacheOnRateLimit(names) {
13589
+ const backoffMs = 6e4;
13590
+ const extendedExpiry = Date.now() + backoffMs;
13591
+ for (const name of names) {
13592
+ const existing = this.cache.get(name);
13593
+ if (existing) {
13594
+ existing.expiresAt = Math.max(existing.expiresAt, extendedExpiry);
13595
+ }
13596
+ }
13597
+ if (this.debug) {
13598
+ console.warn(`[CoinGecko] Rate-limited (429), extended cache TTL by ${backoffMs / 1e3}s`);
13599
+ }
13600
+ }
15867
13601
  async getPrice(tokenName) {
15868
13602
  const prices = await this.getPrices([tokenName]);
15869
13603
  return prices.get(tokenName) ?? null;
@@ -15894,7 +13628,6 @@ function createPriceProvider(config) {
15894
13628
  DEFAULT_GROUP_RELAYS,
15895
13629
  DEFAULT_IPFS_BOOTSTRAP_PEERS,
15896
13630
  DEFAULT_IPFS_GATEWAYS,
15897
- DEFAULT_MARKET_API_URL,
15898
13631
  DEFAULT_NOSTR_RELAYS,
15899
13632
  DEV_AGGREGATOR_URL,
15900
13633
  GroupChatModule,
@@ -15903,7 +13636,6 @@ function createPriceProvider(config) {
15903
13636
  L1,
15904
13637
  L1PaymentsModule,
15905
13638
  LIMITS,
15906
- MarketModule,
15907
13639
  NETWORKS,
15908
13640
  NIP29_KINDS,
15909
13641
  NOSTR_EVENT_KINDS,
@@ -15931,7 +13663,6 @@ function createPriceProvider(config) {
15931
13663
  createGroupChatModule,
15932
13664
  createKeyPair,
15933
13665
  createL1PaymentsModule,
15934
- createMarketModule,
15935
13666
  createPaymentSession,
15936
13667
  createPaymentSessionError,
15937
13668
  createPaymentsModule,
@@ -16019,16 +13750,4 @@ function createPriceProvider(config) {
16019
13750
  txfToToken,
16020
13751
  validateMnemonic
16021
13752
  });
16022
- /*! Bundled license information:
16023
-
16024
- @noble/hashes/utils.js:
16025
- (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
16026
-
16027
- @noble/curves/utils.js:
16028
- @noble/curves/abstract/modular.js:
16029
- @noble/curves/abstract/curve.js:
16030
- @noble/curves/abstract/weierstrass.js:
16031
- @noble/curves/secp256k1.js:
16032
- (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
16033
- */
16034
13753
  //# sourceMappingURL=index.cjs.map