@unicitylabs/sphere-sdk 0.3.6 → 0.3.8

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.
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) {
@@ -9285,26 +9327,27 @@ var GroupChatModule = class {
9285
9327
  oneshotSubscription(filter, opts) {
9286
9328
  return new Promise((resolve) => {
9287
9329
  let done = false;
9288
- let subId;
9330
+ const state = {};
9289
9331
  const finish = () => {
9290
9332
  if (done) return;
9291
9333
  done = true;
9292
- if (subId) {
9334
+ if (state.subId) {
9293
9335
  try {
9294
- this.client.unsubscribe(subId);
9336
+ this.client.unsubscribe(state.subId);
9295
9337
  } catch {
9296
9338
  }
9297
- const idx = this.subscriptionIds.indexOf(subId);
9339
+ const idx = this.subscriptionIds.indexOf(state.subId);
9298
9340
  if (idx >= 0) this.subscriptionIds.splice(idx, 1);
9299
9341
  }
9300
9342
  resolve(opts.onComplete());
9301
9343
  };
9302
- subId = this.client.subscribe(filter, {
9344
+ const subId = this.client.subscribe(filter, {
9303
9345
  onEvent: (event) => {
9304
9346
  if (!done) opts.onEvent(event);
9305
9347
  },
9306
9348
  onEndOfStoredEvents: finish
9307
9349
  });
9350
+ state.subId = subId;
9308
9351
  this.subscriptionIds.push(subId);
9309
9352
  setTimeout(finish, opts.timeoutMs ?? 5e3);
9310
9353
  });
@@ -9335,2426 +9378,6 @@ function createGroupChatModule(config) {
9335
9378
  return new GroupChatModule(config);
9336
9379
  }
9337
9380
 
9338
- // node_modules/@noble/hashes/utils.js
9339
- function isBytes(a) {
9340
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
9341
- }
9342
- function anumber(n, title = "") {
9343
- if (!Number.isSafeInteger(n) || n < 0) {
9344
- const prefix = title && `"${title}" `;
9345
- throw new Error(`${prefix}expected integer >= 0, got ${n}`);
9346
- }
9347
- }
9348
- function abytes(value, length, title = "") {
9349
- const bytes = isBytes(value);
9350
- const len = value?.length;
9351
- const needsLen = length !== void 0;
9352
- if (!bytes || needsLen && len !== length) {
9353
- const prefix = title && `"${title}" `;
9354
- const ofLen = needsLen ? ` of length ${length}` : "";
9355
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
9356
- throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
9357
- }
9358
- return value;
9359
- }
9360
- function ahash(h) {
9361
- if (typeof h !== "function" || typeof h.create !== "function")
9362
- throw new Error("Hash must wrapped by utils.createHasher");
9363
- anumber(h.outputLen);
9364
- anumber(h.blockLen);
9365
- }
9366
- function aexists(instance, checkFinished = true) {
9367
- if (instance.destroyed)
9368
- throw new Error("Hash instance has been destroyed");
9369
- if (checkFinished && instance.finished)
9370
- throw new Error("Hash#digest() has already been called");
9371
- }
9372
- function aoutput(out, instance) {
9373
- abytes(out, void 0, "digestInto() output");
9374
- const min = instance.outputLen;
9375
- if (out.length < min) {
9376
- throw new Error('"digestInto() output" expected to be of length >=' + min);
9377
- }
9378
- }
9379
- function clean(...arrays) {
9380
- for (let i = 0; i < arrays.length; i++) {
9381
- arrays[i].fill(0);
9382
- }
9383
- }
9384
- function createView(arr) {
9385
- return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
9386
- }
9387
- function rotr(word, shift) {
9388
- return word << 32 - shift | word >>> shift;
9389
- }
9390
- var hasHexBuiltin = /* @__PURE__ */ (() => (
9391
- // @ts-ignore
9392
- typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
9393
- ))();
9394
- var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
9395
- function bytesToHex4(bytes) {
9396
- abytes(bytes);
9397
- if (hasHexBuiltin)
9398
- return bytes.toHex();
9399
- let hex = "";
9400
- for (let i = 0; i < bytes.length; i++) {
9401
- hex += hexes[bytes[i]];
9402
- }
9403
- return hex;
9404
- }
9405
- var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
9406
- function asciiToBase16(ch) {
9407
- if (ch >= asciis._0 && ch <= asciis._9)
9408
- return ch - asciis._0;
9409
- if (ch >= asciis.A && ch <= asciis.F)
9410
- return ch - (asciis.A - 10);
9411
- if (ch >= asciis.a && ch <= asciis.f)
9412
- return ch - (asciis.a - 10);
9413
- return;
9414
- }
9415
- function hexToBytes2(hex) {
9416
- if (typeof hex !== "string")
9417
- throw new Error("hex string expected, got " + typeof hex);
9418
- if (hasHexBuiltin)
9419
- return Uint8Array.fromHex(hex);
9420
- const hl = hex.length;
9421
- const al = hl / 2;
9422
- if (hl % 2)
9423
- throw new Error("hex string expected, got unpadded hex of length " + hl);
9424
- const array = new Uint8Array(al);
9425
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
9426
- const n1 = asciiToBase16(hex.charCodeAt(hi));
9427
- const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
9428
- if (n1 === void 0 || n2 === void 0) {
9429
- const char = hex[hi] + hex[hi + 1];
9430
- throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
9431
- }
9432
- array[ai] = n1 * 16 + n2;
9433
- }
9434
- return array;
9435
- }
9436
- function concatBytes(...arrays) {
9437
- let sum = 0;
9438
- for (let i = 0; i < arrays.length; i++) {
9439
- const a = arrays[i];
9440
- abytes(a);
9441
- sum += a.length;
9442
- }
9443
- const res = new Uint8Array(sum);
9444
- for (let i = 0, pad = 0; i < arrays.length; i++) {
9445
- const a = arrays[i];
9446
- res.set(a, pad);
9447
- pad += a.length;
9448
- }
9449
- return res;
9450
- }
9451
- function createHasher(hashCons, info = {}) {
9452
- const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
9453
- const tmp = hashCons(void 0);
9454
- hashC.outputLen = tmp.outputLen;
9455
- hashC.blockLen = tmp.blockLen;
9456
- hashC.create = (opts) => hashCons(opts);
9457
- Object.assign(hashC, info);
9458
- return Object.freeze(hashC);
9459
- }
9460
- function randomBytes2(bytesLength = 32) {
9461
- const cr = typeof globalThis === "object" ? globalThis.crypto : null;
9462
- if (typeof cr?.getRandomValues !== "function")
9463
- throw new Error("crypto.getRandomValues must be defined");
9464
- return cr.getRandomValues(new Uint8Array(bytesLength));
9465
- }
9466
- var oidNist = (suffix) => ({
9467
- oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
9468
- });
9469
-
9470
- // node_modules/@noble/hashes/_md.js
9471
- function Chi(a, b, c) {
9472
- return a & b ^ ~a & c;
9473
- }
9474
- function Maj(a, b, c) {
9475
- return a & b ^ a & c ^ b & c;
9476
- }
9477
- var HashMD = class {
9478
- blockLen;
9479
- outputLen;
9480
- padOffset;
9481
- isLE;
9482
- // For partial updates less than block size
9483
- buffer;
9484
- view;
9485
- finished = false;
9486
- length = 0;
9487
- pos = 0;
9488
- destroyed = false;
9489
- constructor(blockLen, outputLen, padOffset, isLE) {
9490
- this.blockLen = blockLen;
9491
- this.outputLen = outputLen;
9492
- this.padOffset = padOffset;
9493
- this.isLE = isLE;
9494
- this.buffer = new Uint8Array(blockLen);
9495
- this.view = createView(this.buffer);
9496
- }
9497
- update(data) {
9498
- aexists(this);
9499
- abytes(data);
9500
- const { view, buffer, blockLen } = this;
9501
- const len = data.length;
9502
- for (let pos = 0; pos < len; ) {
9503
- const take = Math.min(blockLen - this.pos, len - pos);
9504
- if (take === blockLen) {
9505
- const dataView = createView(data);
9506
- for (; blockLen <= len - pos; pos += blockLen)
9507
- this.process(dataView, pos);
9508
- continue;
9509
- }
9510
- buffer.set(data.subarray(pos, pos + take), this.pos);
9511
- this.pos += take;
9512
- pos += take;
9513
- if (this.pos === blockLen) {
9514
- this.process(view, 0);
9515
- this.pos = 0;
9516
- }
9517
- }
9518
- this.length += data.length;
9519
- this.roundClean();
9520
- return this;
9521
- }
9522
- digestInto(out) {
9523
- aexists(this);
9524
- aoutput(out, this);
9525
- this.finished = true;
9526
- const { buffer, view, blockLen, isLE } = this;
9527
- let { pos } = this;
9528
- buffer[pos++] = 128;
9529
- clean(this.buffer.subarray(pos));
9530
- if (this.padOffset > blockLen - pos) {
9531
- this.process(view, 0);
9532
- pos = 0;
9533
- }
9534
- for (let i = pos; i < blockLen; i++)
9535
- buffer[i] = 0;
9536
- view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
9537
- this.process(view, 0);
9538
- const oview = createView(out);
9539
- const len = this.outputLen;
9540
- if (len % 4)
9541
- throw new Error("_sha2: outputLen must be aligned to 32bit");
9542
- const outLen = len / 4;
9543
- const state = this.get();
9544
- if (outLen > state.length)
9545
- throw new Error("_sha2: outputLen bigger than state");
9546
- for (let i = 0; i < outLen; i++)
9547
- oview.setUint32(4 * i, state[i], isLE);
9548
- }
9549
- digest() {
9550
- const { buffer, outputLen } = this;
9551
- this.digestInto(buffer);
9552
- const res = buffer.slice(0, outputLen);
9553
- this.destroy();
9554
- return res;
9555
- }
9556
- _cloneInto(to) {
9557
- to ||= new this.constructor();
9558
- to.set(...this.get());
9559
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
9560
- to.destroyed = destroyed;
9561
- to.finished = finished;
9562
- to.length = length;
9563
- to.pos = pos;
9564
- if (length % blockLen)
9565
- to.buffer.set(buffer);
9566
- return to;
9567
- }
9568
- clone() {
9569
- return this._cloneInto();
9570
- }
9571
- };
9572
- var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
9573
- 1779033703,
9574
- 3144134277,
9575
- 1013904242,
9576
- 2773480762,
9577
- 1359893119,
9578
- 2600822924,
9579
- 528734635,
9580
- 1541459225
9581
- ]);
9582
-
9583
- // node_modules/@noble/hashes/sha2.js
9584
- var SHA256_K = /* @__PURE__ */ Uint32Array.from([
9585
- 1116352408,
9586
- 1899447441,
9587
- 3049323471,
9588
- 3921009573,
9589
- 961987163,
9590
- 1508970993,
9591
- 2453635748,
9592
- 2870763221,
9593
- 3624381080,
9594
- 310598401,
9595
- 607225278,
9596
- 1426881987,
9597
- 1925078388,
9598
- 2162078206,
9599
- 2614888103,
9600
- 3248222580,
9601
- 3835390401,
9602
- 4022224774,
9603
- 264347078,
9604
- 604807628,
9605
- 770255983,
9606
- 1249150122,
9607
- 1555081692,
9608
- 1996064986,
9609
- 2554220882,
9610
- 2821834349,
9611
- 2952996808,
9612
- 3210313671,
9613
- 3336571891,
9614
- 3584528711,
9615
- 113926993,
9616
- 338241895,
9617
- 666307205,
9618
- 773529912,
9619
- 1294757372,
9620
- 1396182291,
9621
- 1695183700,
9622
- 1986661051,
9623
- 2177026350,
9624
- 2456956037,
9625
- 2730485921,
9626
- 2820302411,
9627
- 3259730800,
9628
- 3345764771,
9629
- 3516065817,
9630
- 3600352804,
9631
- 4094571909,
9632
- 275423344,
9633
- 430227734,
9634
- 506948616,
9635
- 659060556,
9636
- 883997877,
9637
- 958139571,
9638
- 1322822218,
9639
- 1537002063,
9640
- 1747873779,
9641
- 1955562222,
9642
- 2024104815,
9643
- 2227730452,
9644
- 2361852424,
9645
- 2428436474,
9646
- 2756734187,
9647
- 3204031479,
9648
- 3329325298
9649
- ]);
9650
- var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
9651
- var SHA2_32B = class extends HashMD {
9652
- constructor(outputLen) {
9653
- super(64, outputLen, 8, false);
9654
- }
9655
- get() {
9656
- const { A, B, C, D, E, F, G, H } = this;
9657
- return [A, B, C, D, E, F, G, H];
9658
- }
9659
- // prettier-ignore
9660
- set(A, B, C, D, E, F, G, H) {
9661
- this.A = A | 0;
9662
- this.B = B | 0;
9663
- this.C = C | 0;
9664
- this.D = D | 0;
9665
- this.E = E | 0;
9666
- this.F = F | 0;
9667
- this.G = G | 0;
9668
- this.H = H | 0;
9669
- }
9670
- process(view, offset) {
9671
- for (let i = 0; i < 16; i++, offset += 4)
9672
- SHA256_W[i] = view.getUint32(offset, false);
9673
- for (let i = 16; i < 64; i++) {
9674
- const W15 = SHA256_W[i - 15];
9675
- const W2 = SHA256_W[i - 2];
9676
- const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
9677
- const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
9678
- SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
9679
- }
9680
- let { A, B, C, D, E, F, G, H } = this;
9681
- for (let i = 0; i < 64; i++) {
9682
- const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
9683
- const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
9684
- const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
9685
- const T2 = sigma0 + Maj(A, B, C) | 0;
9686
- H = G;
9687
- G = F;
9688
- F = E;
9689
- E = D + T1 | 0;
9690
- D = C;
9691
- C = B;
9692
- B = A;
9693
- A = T1 + T2 | 0;
9694
- }
9695
- A = A + this.A | 0;
9696
- B = B + this.B | 0;
9697
- C = C + this.C | 0;
9698
- D = D + this.D | 0;
9699
- E = E + this.E | 0;
9700
- F = F + this.F | 0;
9701
- G = G + this.G | 0;
9702
- H = H + this.H | 0;
9703
- this.set(A, B, C, D, E, F, G, H);
9704
- }
9705
- roundClean() {
9706
- clean(SHA256_W);
9707
- }
9708
- destroy() {
9709
- this.set(0, 0, 0, 0, 0, 0, 0, 0);
9710
- clean(this.buffer);
9711
- }
9712
- };
9713
- var _SHA256 = class extends SHA2_32B {
9714
- // We cannot use array here since array allows indexing by variable
9715
- // which means optimizer/compiler cannot use registers.
9716
- A = SHA256_IV[0] | 0;
9717
- B = SHA256_IV[1] | 0;
9718
- C = SHA256_IV[2] | 0;
9719
- D = SHA256_IV[3] | 0;
9720
- E = SHA256_IV[4] | 0;
9721
- F = SHA256_IV[5] | 0;
9722
- G = SHA256_IV[6] | 0;
9723
- H = SHA256_IV[7] | 0;
9724
- constructor() {
9725
- super(32);
9726
- }
9727
- };
9728
- var sha2564 = /* @__PURE__ */ createHasher(
9729
- () => new _SHA256(),
9730
- /* @__PURE__ */ oidNist(1)
9731
- );
9732
-
9733
- // node_modules/@noble/curves/utils.js
9734
- var _0n = /* @__PURE__ */ BigInt(0);
9735
- var _1n = /* @__PURE__ */ BigInt(1);
9736
- function abool(value, title = "") {
9737
- if (typeof value !== "boolean") {
9738
- const prefix = title && `"${title}" `;
9739
- throw new Error(prefix + "expected boolean, got type=" + typeof value);
9740
- }
9741
- return value;
9742
- }
9743
- function abignumber(n) {
9744
- if (typeof n === "bigint") {
9745
- if (!isPosBig(n))
9746
- throw new Error("positive bigint expected, got " + n);
9747
- } else
9748
- anumber(n);
9749
- return n;
9750
- }
9751
- function numberToHexUnpadded(num) {
9752
- const hex = abignumber(num).toString(16);
9753
- return hex.length & 1 ? "0" + hex : hex;
9754
- }
9755
- function hexToNumber(hex) {
9756
- if (typeof hex !== "string")
9757
- throw new Error("hex string expected, got " + typeof hex);
9758
- return hex === "" ? _0n : BigInt("0x" + hex);
9759
- }
9760
- function bytesToNumberBE(bytes) {
9761
- return hexToNumber(bytesToHex4(bytes));
9762
- }
9763
- function bytesToNumberLE(bytes) {
9764
- return hexToNumber(bytesToHex4(copyBytes(abytes(bytes)).reverse()));
9765
- }
9766
- function numberToBytesBE(n, len) {
9767
- anumber(len);
9768
- n = abignumber(n);
9769
- const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
9770
- if (res.length !== len)
9771
- throw new Error("number too large");
9772
- return res;
9773
- }
9774
- function numberToBytesLE(n, len) {
9775
- return numberToBytesBE(n, len).reverse();
9776
- }
9777
- function copyBytes(bytes) {
9778
- return Uint8Array.from(bytes);
9779
- }
9780
- var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
9781
- function inRange(n, min, max) {
9782
- return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
9783
- }
9784
- function aInRange(title, n, min, max) {
9785
- if (!inRange(n, min, max))
9786
- throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
9787
- }
9788
- function bitLen(n) {
9789
- let len;
9790
- for (len = 0; n > _0n; n >>= _1n, len += 1)
9791
- ;
9792
- return len;
9793
- }
9794
- var bitMask = (n) => (_1n << BigInt(n)) - _1n;
9795
- function createHmacDrbg(hashLen, qByteLen, hmacFn) {
9796
- anumber(hashLen, "hashLen");
9797
- anumber(qByteLen, "qByteLen");
9798
- if (typeof hmacFn !== "function")
9799
- throw new Error("hmacFn must be a function");
9800
- const u8n = (len) => new Uint8Array(len);
9801
- const NULL = Uint8Array.of();
9802
- const byte0 = Uint8Array.of(0);
9803
- const byte1 = Uint8Array.of(1);
9804
- const _maxDrbgIters = 1e3;
9805
- let v = u8n(hashLen);
9806
- let k = u8n(hashLen);
9807
- let i = 0;
9808
- const reset = () => {
9809
- v.fill(1);
9810
- k.fill(0);
9811
- i = 0;
9812
- };
9813
- const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
9814
- const reseed = (seed = NULL) => {
9815
- k = h(byte0, seed);
9816
- v = h();
9817
- if (seed.length === 0)
9818
- return;
9819
- k = h(byte1, seed);
9820
- v = h();
9821
- };
9822
- const gen = () => {
9823
- if (i++ >= _maxDrbgIters)
9824
- throw new Error("drbg: tried max amount of iterations");
9825
- let len = 0;
9826
- const out = [];
9827
- while (len < qByteLen) {
9828
- v = h();
9829
- const sl = v.slice();
9830
- out.push(sl);
9831
- len += v.length;
9832
- }
9833
- return concatBytes(...out);
9834
- };
9835
- const genUntil = (seed, pred) => {
9836
- reset();
9837
- reseed(seed);
9838
- let res = void 0;
9839
- while (!(res = pred(gen())))
9840
- reseed();
9841
- reset();
9842
- return res;
9843
- };
9844
- return genUntil;
9845
- }
9846
- function validateObject(object, fields = {}, optFields = {}) {
9847
- if (!object || typeof object !== "object")
9848
- throw new Error("expected valid options object");
9849
- function checkField(fieldName, expectedType, isOpt) {
9850
- const val = object[fieldName];
9851
- if (isOpt && val === void 0)
9852
- return;
9853
- const current = typeof val;
9854
- if (current !== expectedType || val === null)
9855
- throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
9856
- }
9857
- const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
9858
- iter(fields, false);
9859
- iter(optFields, true);
9860
- }
9861
- function memoized(fn) {
9862
- const map = /* @__PURE__ */ new WeakMap();
9863
- return (arg, ...args) => {
9864
- const val = map.get(arg);
9865
- if (val !== void 0)
9866
- return val;
9867
- const computed = fn(arg, ...args);
9868
- map.set(arg, computed);
9869
- return computed;
9870
- };
9871
- }
9872
-
9873
- // node_modules/@noble/curves/abstract/modular.js
9874
- var _0n2 = /* @__PURE__ */ BigInt(0);
9875
- var _1n2 = /* @__PURE__ */ BigInt(1);
9876
- var _2n = /* @__PURE__ */ BigInt(2);
9877
- var _3n = /* @__PURE__ */ BigInt(3);
9878
- var _4n = /* @__PURE__ */ BigInt(4);
9879
- var _5n = /* @__PURE__ */ BigInt(5);
9880
- var _7n = /* @__PURE__ */ BigInt(7);
9881
- var _8n = /* @__PURE__ */ BigInt(8);
9882
- var _9n = /* @__PURE__ */ BigInt(9);
9883
- var _16n = /* @__PURE__ */ BigInt(16);
9884
- function mod(a, b) {
9885
- const result = a % b;
9886
- return result >= _0n2 ? result : b + result;
9887
- }
9888
- function pow2(x, power, modulo) {
9889
- let res = x;
9890
- while (power-- > _0n2) {
9891
- res *= res;
9892
- res %= modulo;
9893
- }
9894
- return res;
9895
- }
9896
- function invert(number, modulo) {
9897
- if (number === _0n2)
9898
- throw new Error("invert: expected non-zero number");
9899
- if (modulo <= _0n2)
9900
- throw new Error("invert: expected positive modulus, got " + modulo);
9901
- let a = mod(number, modulo);
9902
- let b = modulo;
9903
- let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
9904
- while (a !== _0n2) {
9905
- const q = b / a;
9906
- const r = b % a;
9907
- const m = x - u * q;
9908
- const n = y - v * q;
9909
- b = a, a = r, x = u, y = v, u = m, v = n;
9910
- }
9911
- const gcd = b;
9912
- if (gcd !== _1n2)
9913
- throw new Error("invert: does not exist");
9914
- return mod(x, modulo);
9915
- }
9916
- function assertIsSquare(Fp, root, n) {
9917
- if (!Fp.eql(Fp.sqr(root), n))
9918
- throw new Error("Cannot find square root");
9919
- }
9920
- function sqrt3mod4(Fp, n) {
9921
- const p1div4 = (Fp.ORDER + _1n2) / _4n;
9922
- const root = Fp.pow(n, p1div4);
9923
- assertIsSquare(Fp, root, n);
9924
- return root;
9925
- }
9926
- function sqrt5mod8(Fp, n) {
9927
- const p5div8 = (Fp.ORDER - _5n) / _8n;
9928
- const n2 = Fp.mul(n, _2n);
9929
- const v = Fp.pow(n2, p5div8);
9930
- const nv = Fp.mul(n, v);
9931
- const i = Fp.mul(Fp.mul(nv, _2n), v);
9932
- const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
9933
- assertIsSquare(Fp, root, n);
9934
- return root;
9935
- }
9936
- function sqrt9mod16(P) {
9937
- const Fp_ = Field(P);
9938
- const tn = tonelliShanks(P);
9939
- const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
9940
- const c2 = tn(Fp_, c1);
9941
- const c3 = tn(Fp_, Fp_.neg(c1));
9942
- const c4 = (P + _7n) / _16n;
9943
- return (Fp, n) => {
9944
- let tv1 = Fp.pow(n, c4);
9945
- let tv2 = Fp.mul(tv1, c1);
9946
- const tv3 = Fp.mul(tv1, c2);
9947
- const tv4 = Fp.mul(tv1, c3);
9948
- const e1 = Fp.eql(Fp.sqr(tv2), n);
9949
- const e2 = Fp.eql(Fp.sqr(tv3), n);
9950
- tv1 = Fp.cmov(tv1, tv2, e1);
9951
- tv2 = Fp.cmov(tv4, tv3, e2);
9952
- const e3 = Fp.eql(Fp.sqr(tv2), n);
9953
- const root = Fp.cmov(tv1, tv2, e3);
9954
- assertIsSquare(Fp, root, n);
9955
- return root;
9956
- };
9957
- }
9958
- function tonelliShanks(P) {
9959
- if (P < _3n)
9960
- throw new Error("sqrt is not defined for small field");
9961
- let Q = P - _1n2;
9962
- let S = 0;
9963
- while (Q % _2n === _0n2) {
9964
- Q /= _2n;
9965
- S++;
9966
- }
9967
- let Z = _2n;
9968
- const _Fp = Field(P);
9969
- while (FpLegendre(_Fp, Z) === 1) {
9970
- if (Z++ > 1e3)
9971
- throw new Error("Cannot find square root: probably non-prime P");
9972
- }
9973
- if (S === 1)
9974
- return sqrt3mod4;
9975
- let cc = _Fp.pow(Z, Q);
9976
- const Q1div2 = (Q + _1n2) / _2n;
9977
- return function tonelliSlow(Fp, n) {
9978
- if (Fp.is0(n))
9979
- return n;
9980
- if (FpLegendre(Fp, n) !== 1)
9981
- throw new Error("Cannot find square root");
9982
- let M = S;
9983
- let c = Fp.mul(Fp.ONE, cc);
9984
- let t = Fp.pow(n, Q);
9985
- let R = Fp.pow(n, Q1div2);
9986
- while (!Fp.eql(t, Fp.ONE)) {
9987
- if (Fp.is0(t))
9988
- return Fp.ZERO;
9989
- let i = 1;
9990
- let t_tmp = Fp.sqr(t);
9991
- while (!Fp.eql(t_tmp, Fp.ONE)) {
9992
- i++;
9993
- t_tmp = Fp.sqr(t_tmp);
9994
- if (i === M)
9995
- throw new Error("Cannot find square root");
9996
- }
9997
- const exponent = _1n2 << BigInt(M - i - 1);
9998
- const b = Fp.pow(c, exponent);
9999
- M = i;
10000
- c = Fp.sqr(b);
10001
- t = Fp.mul(t, c);
10002
- R = Fp.mul(R, b);
10003
- }
10004
- return R;
10005
- };
10006
- }
10007
- function FpSqrt(P) {
10008
- if (P % _4n === _3n)
10009
- return sqrt3mod4;
10010
- if (P % _8n === _5n)
10011
- return sqrt5mod8;
10012
- if (P % _16n === _9n)
10013
- return sqrt9mod16(P);
10014
- return tonelliShanks(P);
10015
- }
10016
- var FIELD_FIELDS = [
10017
- "create",
10018
- "isValid",
10019
- "is0",
10020
- "neg",
10021
- "inv",
10022
- "sqrt",
10023
- "sqr",
10024
- "eql",
10025
- "add",
10026
- "sub",
10027
- "mul",
10028
- "pow",
10029
- "div",
10030
- "addN",
10031
- "subN",
10032
- "mulN",
10033
- "sqrN"
10034
- ];
10035
- function validateField(field) {
10036
- const initial = {
10037
- ORDER: "bigint",
10038
- BYTES: "number",
10039
- BITS: "number"
10040
- };
10041
- const opts = FIELD_FIELDS.reduce((map, val) => {
10042
- map[val] = "function";
10043
- return map;
10044
- }, initial);
10045
- validateObject(field, opts);
10046
- return field;
10047
- }
10048
- function FpPow(Fp, num, power) {
10049
- if (power < _0n2)
10050
- throw new Error("invalid exponent, negatives unsupported");
10051
- if (power === _0n2)
10052
- return Fp.ONE;
10053
- if (power === _1n2)
10054
- return num;
10055
- let p = Fp.ONE;
10056
- let d = num;
10057
- while (power > _0n2) {
10058
- if (power & _1n2)
10059
- p = Fp.mul(p, d);
10060
- d = Fp.sqr(d);
10061
- power >>= _1n2;
10062
- }
10063
- return p;
10064
- }
10065
- function FpInvertBatch(Fp, nums, passZero = false) {
10066
- const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
10067
- const multipliedAcc = nums.reduce((acc, num, i) => {
10068
- if (Fp.is0(num))
10069
- return acc;
10070
- inverted[i] = acc;
10071
- return Fp.mul(acc, num);
10072
- }, Fp.ONE);
10073
- const invertedAcc = Fp.inv(multipliedAcc);
10074
- nums.reduceRight((acc, num, i) => {
10075
- if (Fp.is0(num))
10076
- return acc;
10077
- inverted[i] = Fp.mul(acc, inverted[i]);
10078
- return Fp.mul(acc, num);
10079
- }, invertedAcc);
10080
- return inverted;
10081
- }
10082
- function FpLegendre(Fp, n) {
10083
- const p1mod2 = (Fp.ORDER - _1n2) / _2n;
10084
- const powered = Fp.pow(n, p1mod2);
10085
- const yes = Fp.eql(powered, Fp.ONE);
10086
- const zero = Fp.eql(powered, Fp.ZERO);
10087
- const no = Fp.eql(powered, Fp.neg(Fp.ONE));
10088
- if (!yes && !zero && !no)
10089
- throw new Error("invalid Legendre symbol result");
10090
- return yes ? 1 : zero ? 0 : -1;
10091
- }
10092
- function nLength(n, nBitLength) {
10093
- if (nBitLength !== void 0)
10094
- anumber(nBitLength);
10095
- const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
10096
- const nByteLength = Math.ceil(_nBitLength / 8);
10097
- return { nBitLength: _nBitLength, nByteLength };
10098
- }
10099
- var _Field = class {
10100
- ORDER;
10101
- BITS;
10102
- BYTES;
10103
- isLE;
10104
- ZERO = _0n2;
10105
- ONE = _1n2;
10106
- _lengths;
10107
- _sqrt;
10108
- // cached sqrt
10109
- _mod;
10110
- constructor(ORDER, opts = {}) {
10111
- if (ORDER <= _0n2)
10112
- throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
10113
- let _nbitLength = void 0;
10114
- this.isLE = false;
10115
- if (opts != null && typeof opts === "object") {
10116
- if (typeof opts.BITS === "number")
10117
- _nbitLength = opts.BITS;
10118
- if (typeof opts.sqrt === "function")
10119
- this.sqrt = opts.sqrt;
10120
- if (typeof opts.isLE === "boolean")
10121
- this.isLE = opts.isLE;
10122
- if (opts.allowedLengths)
10123
- this._lengths = opts.allowedLengths?.slice();
10124
- if (typeof opts.modFromBytes === "boolean")
10125
- this._mod = opts.modFromBytes;
10126
- }
10127
- const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
10128
- if (nByteLength > 2048)
10129
- throw new Error("invalid field: expected ORDER of <= 2048 bytes");
10130
- this.ORDER = ORDER;
10131
- this.BITS = nBitLength;
10132
- this.BYTES = nByteLength;
10133
- this._sqrt = void 0;
10134
- Object.preventExtensions(this);
10135
- }
10136
- create(num) {
10137
- return mod(num, this.ORDER);
10138
- }
10139
- isValid(num) {
10140
- if (typeof num !== "bigint")
10141
- throw new Error("invalid field element: expected bigint, got " + typeof num);
10142
- return _0n2 <= num && num < this.ORDER;
10143
- }
10144
- is0(num) {
10145
- return num === _0n2;
10146
- }
10147
- // is valid and invertible
10148
- isValidNot0(num) {
10149
- return !this.is0(num) && this.isValid(num);
10150
- }
10151
- isOdd(num) {
10152
- return (num & _1n2) === _1n2;
10153
- }
10154
- neg(num) {
10155
- return mod(-num, this.ORDER);
10156
- }
10157
- eql(lhs, rhs) {
10158
- return lhs === rhs;
10159
- }
10160
- sqr(num) {
10161
- return mod(num * num, this.ORDER);
10162
- }
10163
- add(lhs, rhs) {
10164
- return mod(lhs + rhs, this.ORDER);
10165
- }
10166
- sub(lhs, rhs) {
10167
- return mod(lhs - rhs, this.ORDER);
10168
- }
10169
- mul(lhs, rhs) {
10170
- return mod(lhs * rhs, this.ORDER);
10171
- }
10172
- pow(num, power) {
10173
- return FpPow(this, num, power);
10174
- }
10175
- div(lhs, rhs) {
10176
- return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
10177
- }
10178
- // Same as above, but doesn't normalize
10179
- sqrN(num) {
10180
- return num * num;
10181
- }
10182
- addN(lhs, rhs) {
10183
- return lhs + rhs;
10184
- }
10185
- subN(lhs, rhs) {
10186
- return lhs - rhs;
10187
- }
10188
- mulN(lhs, rhs) {
10189
- return lhs * rhs;
10190
- }
10191
- inv(num) {
10192
- return invert(num, this.ORDER);
10193
- }
10194
- sqrt(num) {
10195
- if (!this._sqrt)
10196
- this._sqrt = FpSqrt(this.ORDER);
10197
- return this._sqrt(this, num);
10198
- }
10199
- toBytes(num) {
10200
- return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
10201
- }
10202
- fromBytes(bytes, skipValidation = false) {
10203
- abytes(bytes);
10204
- const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
10205
- if (allowedLengths) {
10206
- if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
10207
- throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
10208
- }
10209
- const padded = new Uint8Array(BYTES);
10210
- padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
10211
- bytes = padded;
10212
- }
10213
- if (bytes.length !== BYTES)
10214
- throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
10215
- let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
10216
- if (modFromBytes)
10217
- scalar = mod(scalar, ORDER);
10218
- if (!skipValidation) {
10219
- if (!this.isValid(scalar))
10220
- throw new Error("invalid field element: outside of range 0..ORDER");
10221
- }
10222
- return scalar;
10223
- }
10224
- // TODO: we don't need it here, move out to separate fn
10225
- invertBatch(lst) {
10226
- return FpInvertBatch(this, lst);
10227
- }
10228
- // We can't move this out because Fp6, Fp12 implement it
10229
- // and it's unclear what to return in there.
10230
- cmov(a, b, condition) {
10231
- return condition ? b : a;
10232
- }
10233
- };
10234
- function Field(ORDER, opts = {}) {
10235
- return new _Field(ORDER, opts);
10236
- }
10237
- function getFieldBytesLength(fieldOrder) {
10238
- if (typeof fieldOrder !== "bigint")
10239
- throw new Error("field order must be bigint");
10240
- const bitLength = fieldOrder.toString(2).length;
10241
- return Math.ceil(bitLength / 8);
10242
- }
10243
- function getMinHashLength(fieldOrder) {
10244
- const length = getFieldBytesLength(fieldOrder);
10245
- return length + Math.ceil(length / 2);
10246
- }
10247
- function mapHashToField(key, fieldOrder, isLE = false) {
10248
- abytes(key);
10249
- const len = key.length;
10250
- const fieldLen = getFieldBytesLength(fieldOrder);
10251
- const minLen = getMinHashLength(fieldOrder);
10252
- if (len < 16 || len < minLen || len > 1024)
10253
- throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
10254
- const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
10255
- const reduced = mod(num, fieldOrder - _1n2) + _1n2;
10256
- return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
10257
- }
10258
-
10259
- // node_modules/@noble/curves/abstract/curve.js
10260
- var _0n3 = /* @__PURE__ */ BigInt(0);
10261
- var _1n3 = /* @__PURE__ */ BigInt(1);
10262
- function negateCt(condition, item) {
10263
- const neg = item.negate();
10264
- return condition ? neg : item;
10265
- }
10266
- function normalizeZ(c, points) {
10267
- const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
10268
- return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
10269
- }
10270
- function validateW(W, bits) {
10271
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
10272
- throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
10273
- }
10274
- function calcWOpts(W, scalarBits) {
10275
- validateW(W, scalarBits);
10276
- const windows = Math.ceil(scalarBits / W) + 1;
10277
- const windowSize = 2 ** (W - 1);
10278
- const maxNumber = 2 ** W;
10279
- const mask = bitMask(W);
10280
- const shiftBy = BigInt(W);
10281
- return { windows, windowSize, mask, maxNumber, shiftBy };
10282
- }
10283
- function calcOffsets(n, window, wOpts) {
10284
- const { windowSize, mask, maxNumber, shiftBy } = wOpts;
10285
- let wbits = Number(n & mask);
10286
- let nextN = n >> shiftBy;
10287
- if (wbits > windowSize) {
10288
- wbits -= maxNumber;
10289
- nextN += _1n3;
10290
- }
10291
- const offsetStart = window * windowSize;
10292
- const offset = offsetStart + Math.abs(wbits) - 1;
10293
- const isZero = wbits === 0;
10294
- const isNeg = wbits < 0;
10295
- const isNegF = window % 2 !== 0;
10296
- const offsetF = offsetStart;
10297
- return { nextN, offset, isZero, isNeg, isNegF, offsetF };
10298
- }
10299
- var pointPrecomputes = /* @__PURE__ */ new WeakMap();
10300
- var pointWindowSizes = /* @__PURE__ */ new WeakMap();
10301
- function getW(P) {
10302
- return pointWindowSizes.get(P) || 1;
10303
- }
10304
- function assert0(n) {
10305
- if (n !== _0n3)
10306
- throw new Error("invalid wNAF");
10307
- }
10308
- var wNAF = class {
10309
- BASE;
10310
- ZERO;
10311
- Fn;
10312
- bits;
10313
- // Parametrized with a given Point class (not individual point)
10314
- constructor(Point, bits) {
10315
- this.BASE = Point.BASE;
10316
- this.ZERO = Point.ZERO;
10317
- this.Fn = Point.Fn;
10318
- this.bits = bits;
10319
- }
10320
- // non-const time multiplication ladder
10321
- _unsafeLadder(elm, n, p = this.ZERO) {
10322
- let d = elm;
10323
- while (n > _0n3) {
10324
- if (n & _1n3)
10325
- p = p.add(d);
10326
- d = d.double();
10327
- n >>= _1n3;
10328
- }
10329
- return p;
10330
- }
10331
- /**
10332
- * Creates a wNAF precomputation window. Used for caching.
10333
- * Default window size is set by `utils.precompute()` and is equal to 8.
10334
- * Number of precomputed points depends on the curve size:
10335
- * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
10336
- * - 𝑊 is the window size
10337
- * - 𝑛 is the bitlength of the curve order.
10338
- * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
10339
- * @param point Point instance
10340
- * @param W window size
10341
- * @returns precomputed point tables flattened to a single array
10342
- */
10343
- precomputeWindow(point, W) {
10344
- const { windows, windowSize } = calcWOpts(W, this.bits);
10345
- const points = [];
10346
- let p = point;
10347
- let base = p;
10348
- for (let window = 0; window < windows; window++) {
10349
- base = p;
10350
- points.push(base);
10351
- for (let i = 1; i < windowSize; i++) {
10352
- base = base.add(p);
10353
- points.push(base);
10354
- }
10355
- p = base.double();
10356
- }
10357
- return points;
10358
- }
10359
- /**
10360
- * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
10361
- * More compact implementation:
10362
- * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
10363
- * @returns real and fake (for const-time) points
10364
- */
10365
- wNAF(W, precomputes, n) {
10366
- if (!this.Fn.isValid(n))
10367
- throw new Error("invalid scalar");
10368
- let p = this.ZERO;
10369
- let f = this.BASE;
10370
- const wo = calcWOpts(W, this.bits);
10371
- for (let window = 0; window < wo.windows; window++) {
10372
- const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
10373
- n = nextN;
10374
- if (isZero) {
10375
- f = f.add(negateCt(isNegF, precomputes[offsetF]));
10376
- } else {
10377
- p = p.add(negateCt(isNeg, precomputes[offset]));
10378
- }
10379
- }
10380
- assert0(n);
10381
- return { p, f };
10382
- }
10383
- /**
10384
- * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
10385
- * @param acc accumulator point to add result of multiplication
10386
- * @returns point
10387
- */
10388
- wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
10389
- const wo = calcWOpts(W, this.bits);
10390
- for (let window = 0; window < wo.windows; window++) {
10391
- if (n === _0n3)
10392
- break;
10393
- const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
10394
- n = nextN;
10395
- if (isZero) {
10396
- continue;
10397
- } else {
10398
- const item = precomputes[offset];
10399
- acc = acc.add(isNeg ? item.negate() : item);
10400
- }
10401
- }
10402
- assert0(n);
10403
- return acc;
10404
- }
10405
- getPrecomputes(W, point, transform) {
10406
- let comp = pointPrecomputes.get(point);
10407
- if (!comp) {
10408
- comp = this.precomputeWindow(point, W);
10409
- if (W !== 1) {
10410
- if (typeof transform === "function")
10411
- comp = transform(comp);
10412
- pointPrecomputes.set(point, comp);
10413
- }
10414
- }
10415
- return comp;
10416
- }
10417
- cached(point, scalar, transform) {
10418
- const W = getW(point);
10419
- return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
10420
- }
10421
- unsafe(point, scalar, transform, prev) {
10422
- const W = getW(point);
10423
- if (W === 1)
10424
- return this._unsafeLadder(point, scalar, prev);
10425
- return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
10426
- }
10427
- // We calculate precomputes for elliptic curve point multiplication
10428
- // using windowed method. This specifies window size and
10429
- // stores precomputed values. Usually only base point would be precomputed.
10430
- createCache(P, W) {
10431
- validateW(W, this.bits);
10432
- pointWindowSizes.set(P, W);
10433
- pointPrecomputes.delete(P);
10434
- }
10435
- hasCache(elm) {
10436
- return getW(elm) !== 1;
10437
- }
10438
- };
10439
- function mulEndoUnsafe(Point, point, k1, k2) {
10440
- let acc = point;
10441
- let p1 = Point.ZERO;
10442
- let p2 = Point.ZERO;
10443
- while (k1 > _0n3 || k2 > _0n3) {
10444
- if (k1 & _1n3)
10445
- p1 = p1.add(acc);
10446
- if (k2 & _1n3)
10447
- p2 = p2.add(acc);
10448
- acc = acc.double();
10449
- k1 >>= _1n3;
10450
- k2 >>= _1n3;
10451
- }
10452
- return { p1, p2 };
10453
- }
10454
- function createField(order, field, isLE) {
10455
- if (field) {
10456
- if (field.ORDER !== order)
10457
- throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
10458
- validateField(field);
10459
- return field;
10460
- } else {
10461
- return Field(order, { isLE });
10462
- }
10463
- }
10464
- function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
10465
- if (FpFnLE === void 0)
10466
- FpFnLE = type === "edwards";
10467
- if (!CURVE || typeof CURVE !== "object")
10468
- throw new Error(`expected valid ${type} CURVE object`);
10469
- for (const p of ["p", "n", "h"]) {
10470
- const val = CURVE[p];
10471
- if (!(typeof val === "bigint" && val > _0n3))
10472
- throw new Error(`CURVE.${p} must be positive bigint`);
10473
- }
10474
- const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
10475
- const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
10476
- const _b = type === "weierstrass" ? "b" : "d";
10477
- const params = ["Gx", "Gy", "a", _b];
10478
- for (const p of params) {
10479
- if (!Fp.isValid(CURVE[p]))
10480
- throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
10481
- }
10482
- CURVE = Object.freeze(Object.assign({}, CURVE));
10483
- return { CURVE, Fp, Fn };
10484
- }
10485
- function createKeygen(randomSecretKey, getPublicKey2) {
10486
- return function keygen(seed) {
10487
- const secretKey = randomSecretKey(seed);
10488
- return { secretKey, publicKey: getPublicKey2(secretKey) };
10489
- };
10490
- }
10491
-
10492
- // node_modules/@noble/hashes/hmac.js
10493
- var _HMAC = class {
10494
- oHash;
10495
- iHash;
10496
- blockLen;
10497
- outputLen;
10498
- finished = false;
10499
- destroyed = false;
10500
- constructor(hash, key) {
10501
- ahash(hash);
10502
- abytes(key, void 0, "key");
10503
- this.iHash = hash.create();
10504
- if (typeof this.iHash.update !== "function")
10505
- throw new Error("Expected instance of class which extends utils.Hash");
10506
- this.blockLen = this.iHash.blockLen;
10507
- this.outputLen = this.iHash.outputLen;
10508
- const blockLen = this.blockLen;
10509
- const pad = new Uint8Array(blockLen);
10510
- pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
10511
- for (let i = 0; i < pad.length; i++)
10512
- pad[i] ^= 54;
10513
- this.iHash.update(pad);
10514
- this.oHash = hash.create();
10515
- for (let i = 0; i < pad.length; i++)
10516
- pad[i] ^= 54 ^ 92;
10517
- this.oHash.update(pad);
10518
- clean(pad);
10519
- }
10520
- update(buf) {
10521
- aexists(this);
10522
- this.iHash.update(buf);
10523
- return this;
10524
- }
10525
- digestInto(out) {
10526
- aexists(this);
10527
- abytes(out, this.outputLen, "output");
10528
- this.finished = true;
10529
- this.iHash.digestInto(out);
10530
- this.oHash.update(out);
10531
- this.oHash.digestInto(out);
10532
- this.destroy();
10533
- }
10534
- digest() {
10535
- const out = new Uint8Array(this.oHash.outputLen);
10536
- this.digestInto(out);
10537
- return out;
10538
- }
10539
- _cloneInto(to) {
10540
- to ||= Object.create(Object.getPrototypeOf(this), {});
10541
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
10542
- to = to;
10543
- to.finished = finished;
10544
- to.destroyed = destroyed;
10545
- to.blockLen = blockLen;
10546
- to.outputLen = outputLen;
10547
- to.oHash = oHash._cloneInto(to.oHash);
10548
- to.iHash = iHash._cloneInto(to.iHash);
10549
- return to;
10550
- }
10551
- clone() {
10552
- return this._cloneInto();
10553
- }
10554
- destroy() {
10555
- this.destroyed = true;
10556
- this.oHash.destroy();
10557
- this.iHash.destroy();
10558
- }
10559
- };
10560
- var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
10561
- hmac.create = (hash, key) => new _HMAC(hash, key);
10562
-
10563
- // node_modules/@noble/curves/abstract/weierstrass.js
10564
- var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
10565
- function _splitEndoScalar(k, basis, n) {
10566
- const [[a1, b1], [a2, b2]] = basis;
10567
- const c1 = divNearest(b2 * k, n);
10568
- const c2 = divNearest(-b1 * k, n);
10569
- let k1 = k - c1 * a1 - c2 * a2;
10570
- let k2 = -c1 * b1 - c2 * b2;
10571
- const k1neg = k1 < _0n4;
10572
- const k2neg = k2 < _0n4;
10573
- if (k1neg)
10574
- k1 = -k1;
10575
- if (k2neg)
10576
- k2 = -k2;
10577
- const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
10578
- if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
10579
- throw new Error("splitScalar (endomorphism): failed, k=" + k);
10580
- }
10581
- return { k1neg, k1, k2neg, k2 };
10582
- }
10583
- function validateSigFormat(format) {
10584
- if (!["compact", "recovered", "der"].includes(format))
10585
- throw new Error('Signature format must be "compact", "recovered", or "der"');
10586
- return format;
10587
- }
10588
- function validateSigOpts(opts, def) {
10589
- const optsn = {};
10590
- for (let optName of Object.keys(def)) {
10591
- optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
10592
- }
10593
- abool(optsn.lowS, "lowS");
10594
- abool(optsn.prehash, "prehash");
10595
- if (optsn.format !== void 0)
10596
- validateSigFormat(optsn.format);
10597
- return optsn;
10598
- }
10599
- var DERErr = class extends Error {
10600
- constructor(m = "") {
10601
- super(m);
10602
- }
10603
- };
10604
- var DER = {
10605
- // asn.1 DER encoding utils
10606
- Err: DERErr,
10607
- // Basic building block is TLV (Tag-Length-Value)
10608
- _tlv: {
10609
- encode: (tag, data) => {
10610
- const { Err: E } = DER;
10611
- if (tag < 0 || tag > 256)
10612
- throw new E("tlv.encode: wrong tag");
10613
- if (data.length & 1)
10614
- throw new E("tlv.encode: unpadded data");
10615
- const dataLen = data.length / 2;
10616
- const len = numberToHexUnpadded(dataLen);
10617
- if (len.length / 2 & 128)
10618
- throw new E("tlv.encode: long form length too big");
10619
- const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
10620
- const t = numberToHexUnpadded(tag);
10621
- return t + lenLen + len + data;
10622
- },
10623
- // v - value, l - left bytes (unparsed)
10624
- decode(tag, data) {
10625
- const { Err: E } = DER;
10626
- let pos = 0;
10627
- if (tag < 0 || tag > 256)
10628
- throw new E("tlv.encode: wrong tag");
10629
- if (data.length < 2 || data[pos++] !== tag)
10630
- throw new E("tlv.decode: wrong tlv");
10631
- const first = data[pos++];
10632
- const isLong = !!(first & 128);
10633
- let length = 0;
10634
- if (!isLong)
10635
- length = first;
10636
- else {
10637
- const lenLen = first & 127;
10638
- if (!lenLen)
10639
- throw new E("tlv.decode(long): indefinite length not supported");
10640
- if (lenLen > 4)
10641
- throw new E("tlv.decode(long): byte length is too big");
10642
- const lengthBytes = data.subarray(pos, pos + lenLen);
10643
- if (lengthBytes.length !== lenLen)
10644
- throw new E("tlv.decode: length bytes not complete");
10645
- if (lengthBytes[0] === 0)
10646
- throw new E("tlv.decode(long): zero leftmost byte");
10647
- for (const b of lengthBytes)
10648
- length = length << 8 | b;
10649
- pos += lenLen;
10650
- if (length < 128)
10651
- throw new E("tlv.decode(long): not minimal encoding");
10652
- }
10653
- const v = data.subarray(pos, pos + length);
10654
- if (v.length !== length)
10655
- throw new E("tlv.decode: wrong value length");
10656
- return { v, l: data.subarray(pos + length) };
10657
- }
10658
- },
10659
- // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
10660
- // since we always use positive integers here. It must always be empty:
10661
- // - add zero byte if exists
10662
- // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
10663
- _int: {
10664
- encode(num) {
10665
- const { Err: E } = DER;
10666
- if (num < _0n4)
10667
- throw new E("integer: negative integers are not allowed");
10668
- let hex = numberToHexUnpadded(num);
10669
- if (Number.parseInt(hex[0], 16) & 8)
10670
- hex = "00" + hex;
10671
- if (hex.length & 1)
10672
- throw new E("unexpected DER parsing assertion: unpadded hex");
10673
- return hex;
10674
- },
10675
- decode(data) {
10676
- const { Err: E } = DER;
10677
- if (data[0] & 128)
10678
- throw new E("invalid signature integer: negative");
10679
- if (data[0] === 0 && !(data[1] & 128))
10680
- throw new E("invalid signature integer: unnecessary leading zero");
10681
- return bytesToNumberBE(data);
10682
- }
10683
- },
10684
- toSig(bytes) {
10685
- const { Err: E, _int: int, _tlv: tlv } = DER;
10686
- const data = abytes(bytes, void 0, "signature");
10687
- const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
10688
- if (seqLeftBytes.length)
10689
- throw new E("invalid signature: left bytes after parsing");
10690
- const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
10691
- const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
10692
- if (sLeftBytes.length)
10693
- throw new E("invalid signature: left bytes after parsing");
10694
- return { r: int.decode(rBytes), s: int.decode(sBytes) };
10695
- },
10696
- hexFromSig(sig) {
10697
- const { _tlv: tlv, _int: int } = DER;
10698
- const rs = tlv.encode(2, int.encode(sig.r));
10699
- const ss = tlv.encode(2, int.encode(sig.s));
10700
- const seq = rs + ss;
10701
- return tlv.encode(48, seq);
10702
- }
10703
- };
10704
- var _0n4 = BigInt(0);
10705
- var _1n4 = BigInt(1);
10706
- var _2n2 = BigInt(2);
10707
- var _3n2 = BigInt(3);
10708
- var _4n2 = BigInt(4);
10709
- function weierstrass(params, extraOpts = {}) {
10710
- const validated = createCurveFields("weierstrass", params, extraOpts);
10711
- const { Fp, Fn } = validated;
10712
- let CURVE = validated.CURVE;
10713
- const { h: cofactor, n: CURVE_ORDER2 } = CURVE;
10714
- validateObject(extraOpts, {}, {
10715
- allowInfinityPoint: "boolean",
10716
- clearCofactor: "function",
10717
- isTorsionFree: "function",
10718
- fromBytes: "function",
10719
- toBytes: "function",
10720
- endo: "object"
10721
- });
10722
- const { endo } = extraOpts;
10723
- if (endo) {
10724
- if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
10725
- throw new Error('invalid endo: expected "beta": bigint and "basises": array');
10726
- }
10727
- }
10728
- const lengths = getWLengths(Fp, Fn);
10729
- function assertCompressionIsSupported() {
10730
- if (!Fp.isOdd)
10731
- throw new Error("compression is not supported: Field does not have .isOdd()");
10732
- }
10733
- function pointToBytes(_c, point, isCompressed) {
10734
- const { x, y } = point.toAffine();
10735
- const bx = Fp.toBytes(x);
10736
- abool(isCompressed, "isCompressed");
10737
- if (isCompressed) {
10738
- assertCompressionIsSupported();
10739
- const hasEvenY = !Fp.isOdd(y);
10740
- return concatBytes(pprefix(hasEvenY), bx);
10741
- } else {
10742
- return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
10743
- }
10744
- }
10745
- function pointFromBytes(bytes) {
10746
- abytes(bytes, void 0, "Point");
10747
- const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
10748
- const length = bytes.length;
10749
- const head = bytes[0];
10750
- const tail = bytes.subarray(1);
10751
- if (length === comp && (head === 2 || head === 3)) {
10752
- const x = Fp.fromBytes(tail);
10753
- if (!Fp.isValid(x))
10754
- throw new Error("bad point: is not on curve, wrong x");
10755
- const y2 = weierstrassEquation(x);
10756
- let y;
10757
- try {
10758
- y = Fp.sqrt(y2);
10759
- } catch (sqrtError) {
10760
- const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
10761
- throw new Error("bad point: is not on curve, sqrt error" + err);
10762
- }
10763
- assertCompressionIsSupported();
10764
- const evenY = Fp.isOdd(y);
10765
- const evenH = (head & 1) === 1;
10766
- if (evenH !== evenY)
10767
- y = Fp.neg(y);
10768
- return { x, y };
10769
- } else if (length === uncomp && head === 4) {
10770
- const L = Fp.BYTES;
10771
- const x = Fp.fromBytes(tail.subarray(0, L));
10772
- const y = Fp.fromBytes(tail.subarray(L, L * 2));
10773
- if (!isValidXY(x, y))
10774
- throw new Error("bad point: is not on curve");
10775
- return { x, y };
10776
- } else {
10777
- throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
10778
- }
10779
- }
10780
- const encodePoint = extraOpts.toBytes || pointToBytes;
10781
- const decodePoint = extraOpts.fromBytes || pointFromBytes;
10782
- function weierstrassEquation(x) {
10783
- const x2 = Fp.sqr(x);
10784
- const x3 = Fp.mul(x2, x);
10785
- return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
10786
- }
10787
- function isValidXY(x, y) {
10788
- const left = Fp.sqr(y);
10789
- const right = weierstrassEquation(x);
10790
- return Fp.eql(left, right);
10791
- }
10792
- if (!isValidXY(CURVE.Gx, CURVE.Gy))
10793
- throw new Error("bad curve params: generator point");
10794
- const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
10795
- const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
10796
- if (Fp.is0(Fp.add(_4a3, _27b2)))
10797
- throw new Error("bad curve params: a or b");
10798
- function acoord(title, n, banZero = false) {
10799
- if (!Fp.isValid(n) || banZero && Fp.is0(n))
10800
- throw new Error(`bad point coordinate ${title}`);
10801
- return n;
10802
- }
10803
- function aprjpoint(other) {
10804
- if (!(other instanceof Point))
10805
- throw new Error("Weierstrass Point expected");
10806
- }
10807
- function splitEndoScalarN(k) {
10808
- if (!endo || !endo.basises)
10809
- throw new Error("no endo");
10810
- return _splitEndoScalar(k, endo.basises, Fn.ORDER);
10811
- }
10812
- const toAffineMemo = memoized((p, iz) => {
10813
- const { X, Y, Z } = p;
10814
- if (Fp.eql(Z, Fp.ONE))
10815
- return { x: X, y: Y };
10816
- const is0 = p.is0();
10817
- if (iz == null)
10818
- iz = is0 ? Fp.ONE : Fp.inv(Z);
10819
- const x = Fp.mul(X, iz);
10820
- const y = Fp.mul(Y, iz);
10821
- const zz = Fp.mul(Z, iz);
10822
- if (is0)
10823
- return { x: Fp.ZERO, y: Fp.ZERO };
10824
- if (!Fp.eql(zz, Fp.ONE))
10825
- throw new Error("invZ was invalid");
10826
- return { x, y };
10827
- });
10828
- const assertValidMemo = memoized((p) => {
10829
- if (p.is0()) {
10830
- if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
10831
- return;
10832
- throw new Error("bad point: ZERO");
10833
- }
10834
- const { x, y } = p.toAffine();
10835
- if (!Fp.isValid(x) || !Fp.isValid(y))
10836
- throw new Error("bad point: x or y not field elements");
10837
- if (!isValidXY(x, y))
10838
- throw new Error("bad point: equation left != right");
10839
- if (!p.isTorsionFree())
10840
- throw new Error("bad point: not in prime-order subgroup");
10841
- return true;
10842
- });
10843
- function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
10844
- k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
10845
- k1p = negateCt(k1neg, k1p);
10846
- k2p = negateCt(k2neg, k2p);
10847
- return k1p.add(k2p);
10848
- }
10849
- class Point {
10850
- // base / generator point
10851
- static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
10852
- // zero / infinity / identity point
10853
- static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
10854
- // 0, 1, 0
10855
- // math field
10856
- static Fp = Fp;
10857
- // scalar field
10858
- static Fn = Fn;
10859
- X;
10860
- Y;
10861
- Z;
10862
- /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
10863
- constructor(X, Y, Z) {
10864
- this.X = acoord("x", X);
10865
- this.Y = acoord("y", Y, true);
10866
- this.Z = acoord("z", Z);
10867
- Object.freeze(this);
10868
- }
10869
- static CURVE() {
10870
- return CURVE;
10871
- }
10872
- /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
10873
- static fromAffine(p) {
10874
- const { x, y } = p || {};
10875
- if (!p || !Fp.isValid(x) || !Fp.isValid(y))
10876
- throw new Error("invalid affine point");
10877
- if (p instanceof Point)
10878
- throw new Error("projective point not allowed");
10879
- if (Fp.is0(x) && Fp.is0(y))
10880
- return Point.ZERO;
10881
- return new Point(x, y, Fp.ONE);
10882
- }
10883
- static fromBytes(bytes) {
10884
- const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
10885
- P.assertValidity();
10886
- return P;
10887
- }
10888
- static fromHex(hex) {
10889
- return Point.fromBytes(hexToBytes2(hex));
10890
- }
10891
- get x() {
10892
- return this.toAffine().x;
10893
- }
10894
- get y() {
10895
- return this.toAffine().y;
10896
- }
10897
- /**
10898
- *
10899
- * @param windowSize
10900
- * @param isLazy true will defer table computation until the first multiplication
10901
- * @returns
10902
- */
10903
- precompute(windowSize = 8, isLazy = true) {
10904
- wnaf.createCache(this, windowSize);
10905
- if (!isLazy)
10906
- this.multiply(_3n2);
10907
- return this;
10908
- }
10909
- // TODO: return `this`
10910
- /** A point on curve is valid if it conforms to equation. */
10911
- assertValidity() {
10912
- assertValidMemo(this);
10913
- }
10914
- hasEvenY() {
10915
- const { y } = this.toAffine();
10916
- if (!Fp.isOdd)
10917
- throw new Error("Field doesn't support isOdd");
10918
- return !Fp.isOdd(y);
10919
- }
10920
- /** Compare one point to another. */
10921
- equals(other) {
10922
- aprjpoint(other);
10923
- const { X: X1, Y: Y1, Z: Z1 } = this;
10924
- const { X: X2, Y: Y2, Z: Z2 } = other;
10925
- const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
10926
- const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
10927
- return U1 && U2;
10928
- }
10929
- /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
10930
- negate() {
10931
- return new Point(this.X, Fp.neg(this.Y), this.Z);
10932
- }
10933
- // Renes-Costello-Batina exception-free doubling formula.
10934
- // There is 30% faster Jacobian formula, but it is not complete.
10935
- // https://eprint.iacr.org/2015/1060, algorithm 3
10936
- // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
10937
- double() {
10938
- const { a, b } = CURVE;
10939
- const b3 = Fp.mul(b, _3n2);
10940
- const { X: X1, Y: Y1, Z: Z1 } = this;
10941
- let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
10942
- let t0 = Fp.mul(X1, X1);
10943
- let t1 = Fp.mul(Y1, Y1);
10944
- let t2 = Fp.mul(Z1, Z1);
10945
- let t3 = Fp.mul(X1, Y1);
10946
- t3 = Fp.add(t3, t3);
10947
- Z3 = Fp.mul(X1, Z1);
10948
- Z3 = Fp.add(Z3, Z3);
10949
- X3 = Fp.mul(a, Z3);
10950
- Y3 = Fp.mul(b3, t2);
10951
- Y3 = Fp.add(X3, Y3);
10952
- X3 = Fp.sub(t1, Y3);
10953
- Y3 = Fp.add(t1, Y3);
10954
- Y3 = Fp.mul(X3, Y3);
10955
- X3 = Fp.mul(t3, X3);
10956
- Z3 = Fp.mul(b3, Z3);
10957
- t2 = Fp.mul(a, t2);
10958
- t3 = Fp.sub(t0, t2);
10959
- t3 = Fp.mul(a, t3);
10960
- t3 = Fp.add(t3, Z3);
10961
- Z3 = Fp.add(t0, t0);
10962
- t0 = Fp.add(Z3, t0);
10963
- t0 = Fp.add(t0, t2);
10964
- t0 = Fp.mul(t0, t3);
10965
- Y3 = Fp.add(Y3, t0);
10966
- t2 = Fp.mul(Y1, Z1);
10967
- t2 = Fp.add(t2, t2);
10968
- t0 = Fp.mul(t2, t3);
10969
- X3 = Fp.sub(X3, t0);
10970
- Z3 = Fp.mul(t2, t1);
10971
- Z3 = Fp.add(Z3, Z3);
10972
- Z3 = Fp.add(Z3, Z3);
10973
- return new Point(X3, Y3, Z3);
10974
- }
10975
- // Renes-Costello-Batina exception-free addition formula.
10976
- // There is 30% faster Jacobian formula, but it is not complete.
10977
- // https://eprint.iacr.org/2015/1060, algorithm 1
10978
- // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
10979
- add(other) {
10980
- aprjpoint(other);
10981
- const { X: X1, Y: Y1, Z: Z1 } = this;
10982
- const { X: X2, Y: Y2, Z: Z2 } = other;
10983
- let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
10984
- const a = CURVE.a;
10985
- const b3 = Fp.mul(CURVE.b, _3n2);
10986
- let t0 = Fp.mul(X1, X2);
10987
- let t1 = Fp.mul(Y1, Y2);
10988
- let t2 = Fp.mul(Z1, Z2);
10989
- let t3 = Fp.add(X1, Y1);
10990
- let t4 = Fp.add(X2, Y2);
10991
- t3 = Fp.mul(t3, t4);
10992
- t4 = Fp.add(t0, t1);
10993
- t3 = Fp.sub(t3, t4);
10994
- t4 = Fp.add(X1, Z1);
10995
- let t5 = Fp.add(X2, Z2);
10996
- t4 = Fp.mul(t4, t5);
10997
- t5 = Fp.add(t0, t2);
10998
- t4 = Fp.sub(t4, t5);
10999
- t5 = Fp.add(Y1, Z1);
11000
- X3 = Fp.add(Y2, Z2);
11001
- t5 = Fp.mul(t5, X3);
11002
- X3 = Fp.add(t1, t2);
11003
- t5 = Fp.sub(t5, X3);
11004
- Z3 = Fp.mul(a, t4);
11005
- X3 = Fp.mul(b3, t2);
11006
- Z3 = Fp.add(X3, Z3);
11007
- X3 = Fp.sub(t1, Z3);
11008
- Z3 = Fp.add(t1, Z3);
11009
- Y3 = Fp.mul(X3, Z3);
11010
- t1 = Fp.add(t0, t0);
11011
- t1 = Fp.add(t1, t0);
11012
- t2 = Fp.mul(a, t2);
11013
- t4 = Fp.mul(b3, t4);
11014
- t1 = Fp.add(t1, t2);
11015
- t2 = Fp.sub(t0, t2);
11016
- t2 = Fp.mul(a, t2);
11017
- t4 = Fp.add(t4, t2);
11018
- t0 = Fp.mul(t1, t4);
11019
- Y3 = Fp.add(Y3, t0);
11020
- t0 = Fp.mul(t5, t4);
11021
- X3 = Fp.mul(t3, X3);
11022
- X3 = Fp.sub(X3, t0);
11023
- t0 = Fp.mul(t3, t1);
11024
- Z3 = Fp.mul(t5, Z3);
11025
- Z3 = Fp.add(Z3, t0);
11026
- return new Point(X3, Y3, Z3);
11027
- }
11028
- subtract(other) {
11029
- return this.add(other.negate());
11030
- }
11031
- is0() {
11032
- return this.equals(Point.ZERO);
11033
- }
11034
- /**
11035
- * Constant time multiplication.
11036
- * Uses wNAF method. Windowed method may be 10% faster,
11037
- * but takes 2x longer to generate and consumes 2x memory.
11038
- * Uses precomputes when available.
11039
- * Uses endomorphism for Koblitz curves.
11040
- * @param scalar by which the point would be multiplied
11041
- * @returns New point
11042
- */
11043
- multiply(scalar) {
11044
- const { endo: endo2 } = extraOpts;
11045
- if (!Fn.isValidNot0(scalar))
11046
- throw new Error("invalid scalar: out of range");
11047
- let point, fake;
11048
- const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
11049
- if (endo2) {
11050
- const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
11051
- const { p: k1p, f: k1f } = mul(k1);
11052
- const { p: k2p, f: k2f } = mul(k2);
11053
- fake = k1f.add(k2f);
11054
- point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
11055
- } else {
11056
- const { p, f } = mul(scalar);
11057
- point = p;
11058
- fake = f;
11059
- }
11060
- return normalizeZ(Point, [point, fake])[0];
11061
- }
11062
- /**
11063
- * Non-constant-time multiplication. Uses double-and-add algorithm.
11064
- * It's faster, but should only be used when you don't care about
11065
- * an exposed secret key e.g. sig verification, which works over *public* keys.
11066
- */
11067
- multiplyUnsafe(sc) {
11068
- const { endo: endo2 } = extraOpts;
11069
- const p = this;
11070
- if (!Fn.isValid(sc))
11071
- throw new Error("invalid scalar: out of range");
11072
- if (sc === _0n4 || p.is0())
11073
- return Point.ZERO;
11074
- if (sc === _1n4)
11075
- return p;
11076
- if (wnaf.hasCache(this))
11077
- return this.multiply(sc);
11078
- if (endo2) {
11079
- const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
11080
- const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
11081
- return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
11082
- } else {
11083
- return wnaf.unsafe(p, sc);
11084
- }
11085
- }
11086
- /**
11087
- * Converts Projective point to affine (x, y) coordinates.
11088
- * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
11089
- */
11090
- toAffine(invertedZ) {
11091
- return toAffineMemo(this, invertedZ);
11092
- }
11093
- /**
11094
- * Checks whether Point is free of torsion elements (is in prime subgroup).
11095
- * Always torsion-free for cofactor=1 curves.
11096
- */
11097
- isTorsionFree() {
11098
- const { isTorsionFree } = extraOpts;
11099
- if (cofactor === _1n4)
11100
- return true;
11101
- if (isTorsionFree)
11102
- return isTorsionFree(Point, this);
11103
- return wnaf.unsafe(this, CURVE_ORDER2).is0();
11104
- }
11105
- clearCofactor() {
11106
- const { clearCofactor } = extraOpts;
11107
- if (cofactor === _1n4)
11108
- return this;
11109
- if (clearCofactor)
11110
- return clearCofactor(Point, this);
11111
- return this.multiplyUnsafe(cofactor);
11112
- }
11113
- isSmallOrder() {
11114
- return this.multiplyUnsafe(cofactor).is0();
11115
- }
11116
- toBytes(isCompressed = true) {
11117
- abool(isCompressed, "isCompressed");
11118
- this.assertValidity();
11119
- return encodePoint(Point, this, isCompressed);
11120
- }
11121
- toHex(isCompressed = true) {
11122
- return bytesToHex4(this.toBytes(isCompressed));
11123
- }
11124
- toString() {
11125
- return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
11126
- }
11127
- }
11128
- const bits = Fn.BITS;
11129
- const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
11130
- Point.BASE.precompute(8);
11131
- return Point;
11132
- }
11133
- function pprefix(hasEvenY) {
11134
- return Uint8Array.of(hasEvenY ? 2 : 3);
11135
- }
11136
- function getWLengths(Fp, Fn) {
11137
- return {
11138
- secretKey: Fn.BYTES,
11139
- publicKey: 1 + Fp.BYTES,
11140
- publicKeyUncompressed: 1 + 2 * Fp.BYTES,
11141
- publicKeyHasPrefix: true,
11142
- signature: 2 * Fn.BYTES
11143
- };
11144
- }
11145
- function ecdh(Point, ecdhOpts = {}) {
11146
- const { Fn } = Point;
11147
- const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
11148
- const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
11149
- function isValidSecretKey(secretKey) {
11150
- try {
11151
- const num = Fn.fromBytes(secretKey);
11152
- return Fn.isValidNot0(num);
11153
- } catch (error) {
11154
- return false;
11155
- }
11156
- }
11157
- function isValidPublicKey(publicKey, isCompressed) {
11158
- const { publicKey: comp, publicKeyUncompressed } = lengths;
11159
- try {
11160
- const l = publicKey.length;
11161
- if (isCompressed === true && l !== comp)
11162
- return false;
11163
- if (isCompressed === false && l !== publicKeyUncompressed)
11164
- return false;
11165
- return !!Point.fromBytes(publicKey);
11166
- } catch (error) {
11167
- return false;
11168
- }
11169
- }
11170
- function randomSecretKey(seed = randomBytes_(lengths.seed)) {
11171
- return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
11172
- }
11173
- function getPublicKey2(secretKey, isCompressed = true) {
11174
- return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
11175
- }
11176
- function isProbPub(item) {
11177
- const { secretKey, publicKey, publicKeyUncompressed } = lengths;
11178
- if (!isBytes(item))
11179
- return void 0;
11180
- if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
11181
- return void 0;
11182
- const l = abytes(item, void 0, "key").length;
11183
- return l === publicKey || l === publicKeyUncompressed;
11184
- }
11185
- function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
11186
- if (isProbPub(secretKeyA) === true)
11187
- throw new Error("first arg must be private key");
11188
- if (isProbPub(publicKeyB) === false)
11189
- throw new Error("second arg must be public key");
11190
- const s = Fn.fromBytes(secretKeyA);
11191
- const b = Point.fromBytes(publicKeyB);
11192
- return b.multiply(s).toBytes(isCompressed);
11193
- }
11194
- const utils = {
11195
- isValidSecretKey,
11196
- isValidPublicKey,
11197
- randomSecretKey
11198
- };
11199
- const keygen = createKeygen(randomSecretKey, getPublicKey2);
11200
- return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
11201
- }
11202
- function ecdsa(Point, hash, ecdsaOpts = {}) {
11203
- ahash(hash);
11204
- validateObject(ecdsaOpts, {}, {
11205
- hmac: "function",
11206
- lowS: "boolean",
11207
- randomBytes: "function",
11208
- bits2int: "function",
11209
- bits2int_modN: "function"
11210
- });
11211
- ecdsaOpts = Object.assign({}, ecdsaOpts);
11212
- const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
11213
- const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
11214
- const { Fp, Fn } = Point;
11215
- const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn;
11216
- const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
11217
- const defaultSigOpts = {
11218
- prehash: true,
11219
- lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
11220
- format: "compact",
11221
- extraEntropy: false
11222
- };
11223
- const hasLargeCofactor = CURVE_ORDER2 * _2n2 < Fp.ORDER;
11224
- function isBiggerThanHalfOrder(number) {
11225
- const HALF = CURVE_ORDER2 >> _1n4;
11226
- return number > HALF;
11227
- }
11228
- function validateRS(title, num) {
11229
- if (!Fn.isValidNot0(num))
11230
- throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
11231
- return num;
11232
- }
11233
- function assertSmallCofactor() {
11234
- if (hasLargeCofactor)
11235
- throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
11236
- }
11237
- function validateSigLength(bytes, format) {
11238
- validateSigFormat(format);
11239
- const size = lengths.signature;
11240
- const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
11241
- return abytes(bytes, sizer);
11242
- }
11243
- class Signature {
11244
- r;
11245
- s;
11246
- recovery;
11247
- constructor(r, s, recovery) {
11248
- this.r = validateRS("r", r);
11249
- this.s = validateRS("s", s);
11250
- if (recovery != null) {
11251
- assertSmallCofactor();
11252
- if (![0, 1, 2, 3].includes(recovery))
11253
- throw new Error("invalid recovery id");
11254
- this.recovery = recovery;
11255
- }
11256
- Object.freeze(this);
11257
- }
11258
- static fromBytes(bytes, format = defaultSigOpts.format) {
11259
- validateSigLength(bytes, format);
11260
- let recid;
11261
- if (format === "der") {
11262
- const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
11263
- return new Signature(r2, s2);
11264
- }
11265
- if (format === "recovered") {
11266
- recid = bytes[0];
11267
- format = "compact";
11268
- bytes = bytes.subarray(1);
11269
- }
11270
- const L = lengths.signature / 2;
11271
- const r = bytes.subarray(0, L);
11272
- const s = bytes.subarray(L, L * 2);
11273
- return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
11274
- }
11275
- static fromHex(hex, format) {
11276
- return this.fromBytes(hexToBytes2(hex), format);
11277
- }
11278
- assertRecovery() {
11279
- const { recovery } = this;
11280
- if (recovery == null)
11281
- throw new Error("invalid recovery id: must be present");
11282
- return recovery;
11283
- }
11284
- addRecoveryBit(recovery) {
11285
- return new Signature(this.r, this.s, recovery);
11286
- }
11287
- recoverPublicKey(messageHash) {
11288
- const { r, s } = this;
11289
- const recovery = this.assertRecovery();
11290
- const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER2 : r;
11291
- if (!Fp.isValid(radj))
11292
- throw new Error("invalid recovery id: sig.r+curve.n != R.x");
11293
- const x = Fp.toBytes(radj);
11294
- const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
11295
- const ir = Fn.inv(radj);
11296
- const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
11297
- const u1 = Fn.create(-h * ir);
11298
- const u2 = Fn.create(s * ir);
11299
- const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
11300
- if (Q.is0())
11301
- throw new Error("invalid recovery: point at infinify");
11302
- Q.assertValidity();
11303
- return Q;
11304
- }
11305
- // Signatures should be low-s, to prevent malleability.
11306
- hasHighS() {
11307
- return isBiggerThanHalfOrder(this.s);
11308
- }
11309
- toBytes(format = defaultSigOpts.format) {
11310
- validateSigFormat(format);
11311
- if (format === "der")
11312
- return hexToBytes2(DER.hexFromSig(this));
11313
- const { r, s } = this;
11314
- const rb = Fn.toBytes(r);
11315
- const sb = Fn.toBytes(s);
11316
- if (format === "recovered") {
11317
- assertSmallCofactor();
11318
- return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
11319
- }
11320
- return concatBytes(rb, sb);
11321
- }
11322
- toHex(format) {
11323
- return bytesToHex4(this.toBytes(format));
11324
- }
11325
- }
11326
- const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
11327
- if (bytes.length > 8192)
11328
- throw new Error("input is too large");
11329
- const num = bytesToNumberBE(bytes);
11330
- const delta = bytes.length * 8 - fnBits;
11331
- return delta > 0 ? num >> BigInt(delta) : num;
11332
- };
11333
- const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
11334
- return Fn.create(bits2int(bytes));
11335
- };
11336
- const ORDER_MASK = bitMask(fnBits);
11337
- function int2octets(num) {
11338
- aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
11339
- return Fn.toBytes(num);
11340
- }
11341
- function validateMsgAndHash(message, prehash) {
11342
- abytes(message, void 0, "message");
11343
- return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
11344
- }
11345
- function prepSig(message, secretKey, opts) {
11346
- const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
11347
- message = validateMsgAndHash(message, prehash);
11348
- const h1int = bits2int_modN(message);
11349
- const d = Fn.fromBytes(secretKey);
11350
- if (!Fn.isValidNot0(d))
11351
- throw new Error("invalid private key");
11352
- const seedArgs = [int2octets(d), int2octets(h1int)];
11353
- if (extraEntropy != null && extraEntropy !== false) {
11354
- const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
11355
- seedArgs.push(abytes(e, void 0, "extraEntropy"));
11356
- }
11357
- const seed = concatBytes(...seedArgs);
11358
- const m = h1int;
11359
- function k2sig(kBytes) {
11360
- const k = bits2int(kBytes);
11361
- if (!Fn.isValidNot0(k))
11362
- return;
11363
- const ik = Fn.inv(k);
11364
- const q = Point.BASE.multiply(k).toAffine();
11365
- const r = Fn.create(q.x);
11366
- if (r === _0n4)
11367
- return;
11368
- const s = Fn.create(ik * Fn.create(m + r * d));
11369
- if (s === _0n4)
11370
- return;
11371
- let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
11372
- let normS = s;
11373
- if (lowS && isBiggerThanHalfOrder(s)) {
11374
- normS = Fn.neg(s);
11375
- recovery ^= 1;
11376
- }
11377
- return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
11378
- }
11379
- return { seed, k2sig };
11380
- }
11381
- function sign(message, secretKey, opts = {}) {
11382
- const { seed, k2sig } = prepSig(message, secretKey, opts);
11383
- const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
11384
- const sig = drbg(seed, k2sig);
11385
- return sig.toBytes(opts.format);
11386
- }
11387
- function verify(signature, message, publicKey, opts = {}) {
11388
- const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
11389
- publicKey = abytes(publicKey, void 0, "publicKey");
11390
- message = validateMsgAndHash(message, prehash);
11391
- if (!isBytes(signature)) {
11392
- const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
11393
- throw new Error("verify expects Uint8Array signature" + end);
11394
- }
11395
- validateSigLength(signature, format);
11396
- try {
11397
- const sig = Signature.fromBytes(signature, format);
11398
- const P = Point.fromBytes(publicKey);
11399
- if (lowS && sig.hasHighS())
11400
- return false;
11401
- const { r, s } = sig;
11402
- const h = bits2int_modN(message);
11403
- const is = Fn.inv(s);
11404
- const u1 = Fn.create(h * is);
11405
- const u2 = Fn.create(r * is);
11406
- const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
11407
- if (R.is0())
11408
- return false;
11409
- const v = Fn.create(R.x);
11410
- return v === r;
11411
- } catch (e) {
11412
- return false;
11413
- }
11414
- }
11415
- function recoverPublicKey(signature, message, opts = {}) {
11416
- const { prehash } = validateSigOpts(opts, defaultSigOpts);
11417
- message = validateMsgAndHash(message, prehash);
11418
- return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
11419
- }
11420
- return Object.freeze({
11421
- keygen,
11422
- getPublicKey: getPublicKey2,
11423
- getSharedSecret,
11424
- utils,
11425
- lengths,
11426
- Point,
11427
- sign,
11428
- verify,
11429
- recoverPublicKey,
11430
- Signature,
11431
- hash
11432
- });
11433
- }
11434
-
11435
- // node_modules/@noble/curves/secp256k1.js
11436
- var secp256k1_CURVE = {
11437
- p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
11438
- n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
11439
- h: BigInt(1),
11440
- a: BigInt(0),
11441
- b: BigInt(7),
11442
- Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
11443
- Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
11444
- };
11445
- var secp256k1_ENDO = {
11446
- beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
11447
- basises: [
11448
- [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
11449
- [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
11450
- ]
11451
- };
11452
- var _2n3 = /* @__PURE__ */ BigInt(2);
11453
- function sqrtMod(y) {
11454
- const P = secp256k1_CURVE.p;
11455
- const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
11456
- const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
11457
- const b2 = y * y * y % P;
11458
- const b3 = b2 * b2 * y % P;
11459
- const b6 = pow2(b3, _3n3, P) * b3 % P;
11460
- const b9 = pow2(b6, _3n3, P) * b3 % P;
11461
- const b11 = pow2(b9, _2n3, P) * b2 % P;
11462
- const b22 = pow2(b11, _11n, P) * b11 % P;
11463
- const b44 = pow2(b22, _22n, P) * b22 % P;
11464
- const b88 = pow2(b44, _44n, P) * b44 % P;
11465
- const b176 = pow2(b88, _88n, P) * b88 % P;
11466
- const b220 = pow2(b176, _44n, P) * b44 % P;
11467
- const b223 = pow2(b220, _3n3, P) * b3 % P;
11468
- const t1 = pow2(b223, _23n, P) * b22 % P;
11469
- const t2 = pow2(t1, _6n, P) * b2 % P;
11470
- const root = pow2(t2, _2n3, P);
11471
- if (!Fpk1.eql(Fpk1.sqr(root), y))
11472
- throw new Error("Cannot find square root");
11473
- return root;
11474
- }
11475
- var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
11476
- var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
11477
- Fp: Fpk1,
11478
- endo: secp256k1_ENDO
11479
- });
11480
- var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha2564);
11481
-
11482
- // modules/market/MarketModule.ts
11483
- function hexToBytes3(hex) {
11484
- const len = hex.length >> 1;
11485
- const bytes = new Uint8Array(len);
11486
- for (let i = 0; i < len; i++) {
11487
- bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
11488
- }
11489
- return bytes;
11490
- }
11491
- function signRequest(body, privateKeyHex) {
11492
- const timestamp = Date.now();
11493
- const payload = JSON.stringify({ body, timestamp });
11494
- const messageHash = sha2564(new TextEncoder().encode(payload));
11495
- const privateKeyBytes = hexToBytes3(privateKeyHex);
11496
- const signature = secp256k1.sign(messageHash, privateKeyBytes);
11497
- const publicKey = bytesToHex4(secp256k1.getPublicKey(privateKeyBytes, true));
11498
- return {
11499
- body: JSON.stringify(body),
11500
- headers: {
11501
- "x-signature": bytesToHex4(signature),
11502
- "x-public-key": publicKey,
11503
- "x-timestamp": String(timestamp),
11504
- "content-type": "application/json"
11505
- }
11506
- };
11507
- }
11508
- function toSnakeCaseIntent(req) {
11509
- const result = {
11510
- description: req.description,
11511
- intent_type: req.intentType
11512
- };
11513
- if (req.category !== void 0) result.category = req.category;
11514
- if (req.price !== void 0) result.price = req.price;
11515
- if (req.currency !== void 0) result.currency = req.currency;
11516
- if (req.location !== void 0) result.location = req.location;
11517
- if (req.contactHandle !== void 0) result.contact_handle = req.contactHandle;
11518
- if (req.expiresInDays !== void 0) result.expires_in_days = req.expiresInDays;
11519
- return result;
11520
- }
11521
- function toSnakeCaseFilters(opts) {
11522
- const result = {};
11523
- if (opts?.filters) {
11524
- const f = opts.filters;
11525
- if (f.intentType !== void 0) result.intent_type = f.intentType;
11526
- if (f.category !== void 0) result.category = f.category;
11527
- if (f.minPrice !== void 0) result.min_price = f.minPrice;
11528
- if (f.maxPrice !== void 0) result.max_price = f.maxPrice;
11529
- if (f.location !== void 0) result.location = f.location;
11530
- }
11531
- if (opts?.limit !== void 0) result.limit = opts.limit;
11532
- return result;
11533
- }
11534
- function mapSearchResult(raw) {
11535
- return {
11536
- id: raw.id,
11537
- score: raw.score,
11538
- agentNametag: raw.agent_nametag ?? void 0,
11539
- agentPublicKey: raw.agent_public_key,
11540
- description: raw.description,
11541
- intentType: raw.intent_type,
11542
- category: raw.category ?? void 0,
11543
- price: raw.price ?? void 0,
11544
- currency: raw.currency,
11545
- location: raw.location ?? void 0,
11546
- contactMethod: raw.contact_method,
11547
- contactHandle: raw.contact_handle ?? void 0,
11548
- createdAt: raw.created_at,
11549
- expiresAt: raw.expires_at
11550
- };
11551
- }
11552
- function mapMyIntent(raw) {
11553
- return {
11554
- id: raw.id,
11555
- intentType: raw.intent_type,
11556
- category: raw.category ?? void 0,
11557
- price: raw.price ?? void 0,
11558
- currency: raw.currency,
11559
- location: raw.location ?? void 0,
11560
- status: raw.status,
11561
- createdAt: raw.created_at,
11562
- expiresAt: raw.expires_at
11563
- };
11564
- }
11565
- function mapFeedListing(raw) {
11566
- return {
11567
- id: raw.id,
11568
- title: raw.title,
11569
- descriptionPreview: raw.description_preview,
11570
- agentName: raw.agent_name,
11571
- agentId: raw.agent_id,
11572
- type: raw.type,
11573
- createdAt: raw.created_at
11574
- };
11575
- }
11576
- function mapFeedMessage(raw) {
11577
- if (raw.type === "initial") {
11578
- return { type: "initial", listings: (raw.listings ?? []).map(mapFeedListing) };
11579
- }
11580
- return { type: "new", listing: mapFeedListing(raw.listing) };
11581
- }
11582
- var MarketModule = class {
11583
- apiUrl;
11584
- timeout;
11585
- identity = null;
11586
- registered = false;
11587
- constructor(config) {
11588
- this.apiUrl = (config?.apiUrl ?? DEFAULT_MARKET_API_URL).replace(/\/+$/, "");
11589
- this.timeout = config?.timeout ?? 3e4;
11590
- }
11591
- /** Called by Sphere after construction */
11592
- initialize(deps) {
11593
- this.identity = deps.identity;
11594
- }
11595
- /** No-op — stateless module */
11596
- async load() {
11597
- }
11598
- /** No-op — stateless module */
11599
- destroy() {
11600
- }
11601
- // ---------------------------------------------------------------------------
11602
- // Public API
11603
- // ---------------------------------------------------------------------------
11604
- /** Post a new intent (agent is auto-registered on first post) */
11605
- async postIntent(intent) {
11606
- const body = toSnakeCaseIntent(intent);
11607
- const data = await this.apiPost("/api/intents", body);
11608
- return {
11609
- intentId: data.intent_id ?? data.intentId,
11610
- message: data.message,
11611
- expiresAt: data.expires_at ?? data.expiresAt
11612
- };
11613
- }
11614
- /** Semantic search for intents (public — no auth required) */
11615
- async search(query, opts) {
11616
- const body = {
11617
- query,
11618
- ...toSnakeCaseFilters(opts)
11619
- };
11620
- const data = await this.apiPublicPost("/api/search", body);
11621
- let results = (data.intents ?? []).map(mapSearchResult);
11622
- const minScore = opts?.filters?.minScore;
11623
- if (minScore != null) {
11624
- results = results.filter((r) => Math.round(r.score * 100) >= Math.round(minScore * 100));
11625
- }
11626
- return { intents: results, count: results.length };
11627
- }
11628
- /** List own intents (authenticated) */
11629
- async getMyIntents() {
11630
- const data = await this.apiGet("/api/intents");
11631
- return (data.intents ?? []).map(mapMyIntent);
11632
- }
11633
- /** Close (delete) an intent */
11634
- async closeIntent(intentId) {
11635
- await this.apiDelete(`/api/intents/${encodeURIComponent(intentId)}`);
11636
- }
11637
- /** Fetch the most recent listings via REST (public — no auth required) */
11638
- async getRecentListings() {
11639
- const res = await fetch(`${this.apiUrl}/api/feed/recent`, {
11640
- signal: AbortSignal.timeout(this.timeout)
11641
- });
11642
- const data = await this.parseResponse(res);
11643
- return (data.listings ?? []).map(mapFeedListing);
11644
- }
11645
- /**
11646
- * Subscribe to the live listing feed via WebSocket.
11647
- * Returns an unsubscribe function that closes the connection.
11648
- *
11649
- * Requires a WebSocket implementation — works natively in browsers
11650
- * and in Node.js 21+ (or with the `ws` package).
11651
- */
11652
- subscribeFeed(listener) {
11653
- const wsUrl = this.apiUrl.replace(/^http/, "ws") + "/ws/feed";
11654
- const ws2 = new WebSocket(wsUrl);
11655
- ws2.onmessage = (event) => {
11656
- try {
11657
- const raw = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
11658
- listener(mapFeedMessage(raw));
11659
- } catch {
11660
- }
11661
- };
11662
- return () => {
11663
- ws2.close();
11664
- };
11665
- }
11666
- // ---------------------------------------------------------------------------
11667
- // Private: HTTP helpers
11668
- // ---------------------------------------------------------------------------
11669
- ensureIdentity() {
11670
- if (!this.identity) {
11671
- throw new Error("MarketModule not initialized \u2014 call initialize() first");
11672
- }
11673
- }
11674
- /** Register the agent's public key with the server (idempotent) */
11675
- async ensureRegistered() {
11676
- if (this.registered) return;
11677
- this.ensureIdentity();
11678
- const publicKey = bytesToHex4(secp256k1.getPublicKey(hexToBytes3(this.identity.privateKey), true));
11679
- const body = { public_key: publicKey };
11680
- if (this.identity.nametag) body.nametag = this.identity.nametag;
11681
- const res = await fetch(`${this.apiUrl}/api/agent/register`, {
11682
- method: "POST",
11683
- headers: { "content-type": "application/json" },
11684
- body: JSON.stringify(body),
11685
- signal: AbortSignal.timeout(this.timeout)
11686
- });
11687
- if (res.ok || res.status === 409) {
11688
- this.registered = true;
11689
- return;
11690
- }
11691
- const text = await res.text();
11692
- let data;
11693
- try {
11694
- data = JSON.parse(text);
11695
- } catch {
11696
- }
11697
- throw new Error(data?.error ?? `Agent registration failed: HTTP ${res.status}`);
11698
- }
11699
- async parseResponse(res) {
11700
- const text = await res.text();
11701
- let data;
11702
- try {
11703
- data = JSON.parse(text);
11704
- } catch {
11705
- throw new Error(`Market API error: HTTP ${res.status} \u2014 unexpected response (not JSON)`);
11706
- }
11707
- if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
11708
- return data;
11709
- }
11710
- async apiPost(path, body) {
11711
- this.ensureIdentity();
11712
- await this.ensureRegistered();
11713
- const signed = signRequest(body, this.identity.privateKey);
11714
- const res = await fetch(`${this.apiUrl}${path}`, {
11715
- method: "POST",
11716
- headers: signed.headers,
11717
- body: signed.body,
11718
- signal: AbortSignal.timeout(this.timeout)
11719
- });
11720
- return this.parseResponse(res);
11721
- }
11722
- async apiGet(path) {
11723
- this.ensureIdentity();
11724
- await this.ensureRegistered();
11725
- const signed = signRequest({}, this.identity.privateKey);
11726
- const res = await fetch(`${this.apiUrl}${path}`, {
11727
- method: "GET",
11728
- headers: signed.headers,
11729
- signal: AbortSignal.timeout(this.timeout)
11730
- });
11731
- return this.parseResponse(res);
11732
- }
11733
- async apiDelete(path) {
11734
- this.ensureIdentity();
11735
- await this.ensureRegistered();
11736
- const signed = signRequest({}, this.identity.privateKey);
11737
- const res = await fetch(`${this.apiUrl}${path}`, {
11738
- method: "DELETE",
11739
- headers: signed.headers,
11740
- signal: AbortSignal.timeout(this.timeout)
11741
- });
11742
- return this.parseResponse(res);
11743
- }
11744
- async apiPublicPost(path, body) {
11745
- const res = await fetch(`${this.apiUrl}${path}`, {
11746
- method: "POST",
11747
- headers: { "content-type": "application/json" },
11748
- body: JSON.stringify(body),
11749
- signal: AbortSignal.timeout(this.timeout)
11750
- });
11751
- return this.parseResponse(res);
11752
- }
11753
- };
11754
- function createMarketModule(config) {
11755
- return new MarketModule(config);
11756
- }
11757
-
11758
9381
  // core/encryption.ts
11759
9382
  var import_crypto_js6 = __toESM(require("crypto-js"), 1);
11760
9383
  function encryptSimple(plaintext, password) {
@@ -12590,7 +10213,6 @@ var Sphere = class _Sphere {
12590
10213
  _payments;
12591
10214
  _communications;
12592
10215
  _groupChat = null;
12593
- _market = null;
12594
10216
  // Events
12595
10217
  eventHandlers = /* @__PURE__ */ new Map();
12596
10218
  // Provider management
@@ -12600,7 +10222,7 @@ var Sphere = class _Sphere {
12600
10222
  // ===========================================================================
12601
10223
  // Constructor (private)
12602
10224
  // ===========================================================================
12603
- constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig, marketConfig) {
10225
+ constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig) {
12604
10226
  this._storage = storage;
12605
10227
  this._transport = transport;
12606
10228
  this._oracle = oracle;
@@ -12611,7 +10233,6 @@ var Sphere = class _Sphere {
12611
10233
  this._payments = createPaymentsModule({ l1: l1Config });
12612
10234
  this._communications = createCommunicationsModule();
12613
10235
  this._groupChat = groupChatConfig ? createGroupChatModule(groupChatConfig) : null;
12614
- this._market = marketConfig ? createMarketModule(marketConfig) : null;
12615
10236
  }
12616
10237
  // ===========================================================================
12617
10238
  // Static Methods - Wallet Management
@@ -12659,8 +10280,8 @@ var Sphere = class _Sphere {
12659
10280
  * ```
12660
10281
  */
12661
10282
  static async init(options) {
10283
+ _Sphere.configureTokenRegistry(options.storage, options.network);
12662
10284
  const groupChat = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12663
- const market = _Sphere.resolveMarketConfig(options.market);
12664
10285
  const walletExists = await _Sphere.exists(options.storage);
12665
10286
  if (walletExists) {
12666
10287
  const sphere2 = await _Sphere.load({
@@ -12671,8 +10292,7 @@ var Sphere = class _Sphere {
12671
10292
  l1: options.l1,
12672
10293
  price: options.price,
12673
10294
  groupChat,
12674
- password: options.password,
12675
- market
10295
+ password: options.password
12676
10296
  });
12677
10297
  return { sphere: sphere2, created: false };
12678
10298
  }
@@ -12699,8 +10319,7 @@ var Sphere = class _Sphere {
12699
10319
  l1: options.l1,
12700
10320
  price: options.price,
12701
10321
  groupChat,
12702
- password: options.password,
12703
- market
10322
+ password: options.password
12704
10323
  });
12705
10324
  return { sphere, created: true, generatedMnemonic };
12706
10325
  }
@@ -12728,20 +10347,17 @@ var Sphere = class _Sphere {
12728
10347
  return config;
12729
10348
  }
12730
10349
  /**
12731
- * Resolve market module config from Sphere.init() options.
12732
- * - `true` → enable with default API URL
12733
- * - `MarketModuleConfig` pass through with defaults
12734
- * - `undefined` no market module
10350
+ * Configure TokenRegistry in the main bundle context.
10351
+ *
10352
+ * The provider factory functions (createBrowserProviders / createNodeProviders)
10353
+ * are compiled into separate bundles by tsup, each with their own inlined copy
10354
+ * of TokenRegistry. Their TokenRegistry.configure() call configures a different
10355
+ * singleton than the one used by PaymentsModule (which lives in the main bundle).
10356
+ * This method ensures the main bundle's TokenRegistry is properly configured.
12735
10357
  */
12736
- static resolveMarketConfig(config) {
12737
- if (!config) return void 0;
12738
- if (config === true) {
12739
- return { apiUrl: DEFAULT_MARKET_API_URL };
12740
- }
12741
- return {
12742
- apiUrl: config.apiUrl ?? DEFAULT_MARKET_API_URL,
12743
- timeout: config.timeout
12744
- };
10358
+ static configureTokenRegistry(storage, network) {
10359
+ const netConfig = network ? NETWORKS[network] : NETWORKS.testnet;
10360
+ TokenRegistry.configure({ remoteUrl: netConfig.tokenRegistryUrl, storage });
12745
10361
  }
12746
10362
  /**
12747
10363
  * Create new wallet with mnemonic
@@ -12753,8 +10369,8 @@ var Sphere = class _Sphere {
12753
10369
  if (await _Sphere.exists(options.storage)) {
12754
10370
  throw new Error("Wallet already exists. Use Sphere.load() or Sphere.clear() first.");
12755
10371
  }
10372
+ _Sphere.configureTokenRegistry(options.storage, options.network);
12756
10373
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12757
- const marketConfig = _Sphere.resolveMarketConfig(options.market);
12758
10374
  const sphere = new _Sphere(
12759
10375
  options.storage,
12760
10376
  options.transport,
@@ -12762,8 +10378,7 @@ var Sphere = class _Sphere {
12762
10378
  options.tokenStorage,
12763
10379
  options.l1,
12764
10380
  options.price,
12765
- groupChatConfig,
12766
- marketConfig
10381
+ groupChatConfig
12767
10382
  );
12768
10383
  sphere._password = options.password ?? null;
12769
10384
  await sphere.storeMnemonic(options.mnemonic, options.derivationPath);
@@ -12789,8 +10404,8 @@ var Sphere = class _Sphere {
12789
10404
  if (!await _Sphere.exists(options.storage)) {
12790
10405
  throw new Error("No wallet found. Use Sphere.create() to create a new wallet.");
12791
10406
  }
10407
+ _Sphere.configureTokenRegistry(options.storage, options.network);
12792
10408
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12793
- const marketConfig = _Sphere.resolveMarketConfig(options.market);
12794
10409
  const sphere = new _Sphere(
12795
10410
  options.storage,
12796
10411
  options.transport,
@@ -12798,8 +10413,7 @@ var Sphere = class _Sphere {
12798
10413
  options.tokenStorage,
12799
10414
  options.l1,
12800
10415
  options.price,
12801
- groupChatConfig,
12802
- marketConfig
10416
+ groupChatConfig
12803
10417
  );
12804
10418
  sphere._password = options.password ?? null;
12805
10419
  await sphere.loadIdentityFromStorage();
@@ -12845,7 +10459,6 @@ var Sphere = class _Sphere {
12845
10459
  console.log("[Sphere.import] Storage reconnected");
12846
10460
  }
12847
10461
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat);
12848
- const marketConfig = _Sphere.resolveMarketConfig(options.market);
12849
10462
  const sphere = new _Sphere(
12850
10463
  options.storage,
12851
10464
  options.transport,
@@ -12853,8 +10466,7 @@ var Sphere = class _Sphere {
12853
10466
  options.tokenStorage,
12854
10467
  options.l1,
12855
10468
  options.price,
12856
- groupChatConfig,
12857
- marketConfig
10469
+ groupChatConfig
12858
10470
  );
12859
10471
  sphere._password = options.password ?? null;
12860
10472
  if (options.mnemonic) {
@@ -13019,10 +10631,6 @@ var Sphere = class _Sphere {
13019
10631
  get groupChat() {
13020
10632
  return this._groupChat;
13021
10633
  }
13022
- /** Market module (intent bulletin board). Null if not configured. */
13023
- get market() {
13024
- return this._market;
13025
- }
13026
10634
  // ===========================================================================
13027
10635
  // Public Properties - State
13028
10636
  // ===========================================================================
@@ -13898,14 +11506,9 @@ var Sphere = class _Sphere {
13898
11506
  storage: this._storage,
13899
11507
  emitEvent
13900
11508
  });
13901
- this._market?.initialize({
13902
- identity: this._identity,
13903
- emitEvent
13904
- });
13905
11509
  await this._payments.load();
13906
11510
  await this._communications.load();
13907
11511
  await this._groupChat?.load();
13908
- await this._market?.load();
13909
11512
  }
13910
11513
  /**
13911
11514
  * Derive address at a specific index
@@ -14606,22 +12209,12 @@ var Sphere = class _Sphere {
14606
12209
  return;
14607
12210
  }
14608
12211
  try {
14609
- const transportPubkey = this._identity?.chainPubkey?.slice(2);
14610
- if (transportPubkey && this._transport.resolve) {
12212
+ if (this._identity?.directAddress && this._transport.resolve) {
14611
12213
  try {
14612
- const existing = await this._transport.resolve(transportPubkey);
12214
+ const existing = await this._transport.resolve(this._identity.directAddress);
14613
12215
  if (existing) {
14614
- let recoveredNametag = existing.nametag;
14615
- let fromLegacy = false;
14616
- if (!recoveredNametag && !this._identity?.nametag && this._transport.recoverNametag) {
14617
- try {
14618
- recoveredNametag = await this._transport.recoverNametag() ?? void 0;
14619
- if (recoveredNametag) fromLegacy = true;
14620
- } catch {
14621
- }
14622
- }
14623
- if (recoveredNametag && !this._identity?.nametag) {
14624
- this._identity.nametag = recoveredNametag;
12216
+ if (existing.nametag && !this._identity.nametag) {
12217
+ this._identity.nametag = existing.nametag;
14625
12218
  await this._updateCachedProxyAddress();
14626
12219
  const entry = await this.ensureAddressTracked(this._currentAddressIndex);
14627
12220
  let nametags = this._addressNametags.get(entry.addressId);
@@ -14630,20 +12223,10 @@ var Sphere = class _Sphere {
14630
12223
  this._addressNametags.set(entry.addressId, nametags);
14631
12224
  }
14632
12225
  if (!nametags.has(0)) {
14633
- nametags.set(0, recoveredNametag);
12226
+ nametags.set(0, existing.nametag);
14634
12227
  await this.persistAddressNametags();
14635
12228
  }
14636
- this.emitEvent("nametag:recovered", { nametag: recoveredNametag });
14637
- if (fromLegacy) {
14638
- await this._transport.publishIdentityBinding(
14639
- this._identity.chainPubkey,
14640
- this._identity.l1Address,
14641
- this._identity.directAddress || "",
14642
- recoveredNametag
14643
- );
14644
- console.log(`[Sphere] Migrated legacy binding with nametag @${recoveredNametag}`);
14645
- return;
14646
- }
12229
+ this.emitEvent("nametag:recovered", { nametag: existing.nametag });
14647
12230
  }
14648
12231
  console.log("[Sphere] Existing binding found, skipping re-publish");
14649
12232
  return;
@@ -14730,7 +12313,6 @@ var Sphere = class _Sphere {
14730
12313
  this._payments.destroy();
14731
12314
  this._communications.destroy();
14732
12315
  this._groupChat?.destroy();
14733
- this._market?.destroy();
14734
12316
  await this._transport.disconnect();
14735
12317
  await this._storage.disconnect();
14736
12318
  await this._oracle.disconnect();
@@ -15038,14 +12620,9 @@ var Sphere = class _Sphere {
15038
12620
  storage: this._storage,
15039
12621
  emitEvent
15040
12622
  });
15041
- this._market?.initialize({
15042
- identity: this._identity,
15043
- emitEvent
15044
- });
15045
12623
  await this._payments.load();
15046
12624
  await this._communications.load();
15047
12625
  await this._groupChat?.load();
15048
- await this._market?.load();
15049
12626
  }
15050
12627
  // ===========================================================================
15051
12628
  // Private: Helpers
@@ -15230,7 +12807,7 @@ async function checkWebSocket(url, timeoutMs) {
15230
12807
  resolve({ healthy: true, url, responseTimeMs });
15231
12808
  }
15232
12809
  };
15233
- ws2.onerror = (event) => {
12810
+ ws2.onerror = (_event) => {
15234
12811
  if (!resolved) {
15235
12812
  resolved = true;
15236
12813
  clearTimeout(timer);
@@ -15725,26 +13302,37 @@ var CoinGeckoPriceProvider = class {
15725
13302
  timeout;
15726
13303
  debug;
15727
13304
  baseUrl;
13305
+ storage;
13306
+ /** In-flight fetch promise for deduplication of concurrent getPrices() calls */
13307
+ fetchPromise = null;
13308
+ /** Token names being fetched in the current in-flight request */
13309
+ fetchNames = null;
13310
+ /** Whether persistent cache has been loaded into memory */
13311
+ persistentCacheLoaded = false;
13312
+ /** Promise for loading persistent cache (deduplication) */
13313
+ loadCachePromise = null;
15728
13314
  constructor(config) {
15729
13315
  this.apiKey = config?.apiKey;
15730
13316
  this.cacheTtlMs = config?.cacheTtlMs ?? 6e4;
15731
13317
  this.timeout = config?.timeout ?? 1e4;
15732
13318
  this.debug = config?.debug ?? false;
13319
+ this.storage = config?.storage ?? null;
15733
13320
  this.baseUrl = config?.baseUrl ?? (this.apiKey ? "https://pro-api.coingecko.com/api/v3" : "https://api.coingecko.com/api/v3");
15734
13321
  }
15735
13322
  async getPrices(tokenNames) {
15736
13323
  if (tokenNames.length === 0) {
15737
13324
  return /* @__PURE__ */ new Map();
15738
13325
  }
13326
+ if (!this.persistentCacheLoaded && this.storage) {
13327
+ await this.loadFromStorage();
13328
+ }
15739
13329
  const now = Date.now();
15740
13330
  const result = /* @__PURE__ */ new Map();
15741
13331
  const uncachedNames = [];
15742
13332
  for (const name of tokenNames) {
15743
13333
  const cached = this.cache.get(name);
15744
13334
  if (cached && cached.expiresAt > now) {
15745
- if (cached.price !== null) {
15746
- result.set(name, cached.price);
15747
- }
13335
+ result.set(name, cached.price);
15748
13336
  } else {
15749
13337
  uncachedNames.push(name);
15750
13338
  }
@@ -15752,6 +13340,41 @@ var CoinGeckoPriceProvider = class {
15752
13340
  if (uncachedNames.length === 0) {
15753
13341
  return result;
15754
13342
  }
13343
+ if (this.fetchPromise && this.fetchNames) {
13344
+ const allCovered = uncachedNames.every((n) => this.fetchNames.has(n));
13345
+ if (allCovered) {
13346
+ if (this.debug) {
13347
+ console.log(`[CoinGecko] Deduplicating request, reusing in-flight fetch`);
13348
+ }
13349
+ const fetched = await this.fetchPromise;
13350
+ for (const name of uncachedNames) {
13351
+ const price = fetched.get(name);
13352
+ if (price) {
13353
+ result.set(name, price);
13354
+ }
13355
+ }
13356
+ return result;
13357
+ }
13358
+ }
13359
+ const fetchPromise = this.doFetch(uncachedNames);
13360
+ this.fetchPromise = fetchPromise;
13361
+ this.fetchNames = new Set(uncachedNames);
13362
+ try {
13363
+ const fetched = await fetchPromise;
13364
+ for (const [name, price] of fetched) {
13365
+ result.set(name, price);
13366
+ }
13367
+ } finally {
13368
+ if (this.fetchPromise === fetchPromise) {
13369
+ this.fetchPromise = null;
13370
+ this.fetchNames = null;
13371
+ }
13372
+ }
13373
+ return result;
13374
+ }
13375
+ async doFetch(uncachedNames) {
13376
+ const result = /* @__PURE__ */ new Map();
13377
+ const now = Date.now();
15755
13378
  try {
15756
13379
  const ids = uncachedNames.join(",");
15757
13380
  const url = `${this.baseUrl}/simple/price?ids=${encodeURIComponent(ids)}&vs_currencies=usd,eur&include_24hr_change=true`;
@@ -15767,6 +13390,9 @@ var CoinGeckoPriceProvider = class {
15767
13390
  signal: AbortSignal.timeout(this.timeout)
15768
13391
  });
15769
13392
  if (!response.ok) {
13393
+ if (response.status === 429) {
13394
+ this.extendCacheOnRateLimit(uncachedNames);
13395
+ }
15770
13396
  throw new Error(`CoinGecko API error: ${response.status} ${response.statusText}`);
15771
13397
  }
15772
13398
  const data = await response.json();
@@ -15785,25 +13411,113 @@ var CoinGeckoPriceProvider = class {
15785
13411
  }
15786
13412
  for (const name of uncachedNames) {
15787
13413
  if (!result.has(name)) {
15788
- this.cache.set(name, { price: null, expiresAt: now + this.cacheTtlMs });
13414
+ const zeroPrice = {
13415
+ tokenName: name,
13416
+ priceUsd: 0,
13417
+ priceEur: 0,
13418
+ change24h: 0,
13419
+ timestamp: now
13420
+ };
13421
+ this.cache.set(name, { price: zeroPrice, expiresAt: now + this.cacheTtlMs });
13422
+ result.set(name, zeroPrice);
15789
13423
  }
15790
13424
  }
15791
13425
  if (this.debug) {
15792
13426
  console.log(`[CoinGecko] Fetched ${result.size} prices`);
15793
13427
  }
13428
+ this.saveToStorage();
15794
13429
  } catch (error) {
15795
13430
  if (this.debug) {
15796
13431
  console.warn("[CoinGecko] Fetch failed, using stale cache:", error);
15797
13432
  }
15798
13433
  for (const name of uncachedNames) {
15799
13434
  const stale = this.cache.get(name);
15800
- if (stale?.price) {
13435
+ if (stale) {
15801
13436
  result.set(name, stale.price);
15802
13437
  }
15803
13438
  }
15804
13439
  }
15805
13440
  return result;
15806
13441
  }
13442
+ // ===========================================================================
13443
+ // Persistent Storage
13444
+ // ===========================================================================
13445
+ /**
13446
+ * Load cached prices from StorageProvider into in-memory cache.
13447
+ * Only loads entries that are still within cacheTtlMs.
13448
+ */
13449
+ async loadFromStorage() {
13450
+ if (this.loadCachePromise) {
13451
+ return this.loadCachePromise;
13452
+ }
13453
+ this.loadCachePromise = this.doLoadFromStorage();
13454
+ try {
13455
+ await this.loadCachePromise;
13456
+ } finally {
13457
+ this.loadCachePromise = null;
13458
+ }
13459
+ }
13460
+ async doLoadFromStorage() {
13461
+ this.persistentCacheLoaded = true;
13462
+ if (!this.storage) return;
13463
+ try {
13464
+ const [cached, cachedTs] = await Promise.all([
13465
+ this.storage.get(STORAGE_KEYS_GLOBAL.PRICE_CACHE),
13466
+ this.storage.get(STORAGE_KEYS_GLOBAL.PRICE_CACHE_TS)
13467
+ ]);
13468
+ if (!cached || !cachedTs) return;
13469
+ const ts = parseInt(cachedTs, 10);
13470
+ if (isNaN(ts)) return;
13471
+ const age = Date.now() - ts;
13472
+ if (age > this.cacheTtlMs) return;
13473
+ const data = JSON.parse(cached);
13474
+ const expiresAt = ts + this.cacheTtlMs;
13475
+ for (const [name, price] of Object.entries(data)) {
13476
+ if (!this.cache.has(name)) {
13477
+ this.cache.set(name, { price, expiresAt });
13478
+ }
13479
+ }
13480
+ if (this.debug) {
13481
+ console.log(`[CoinGecko] Loaded ${Object.keys(data).length} prices from persistent cache`);
13482
+ }
13483
+ } catch {
13484
+ }
13485
+ }
13486
+ /**
13487
+ * Save current prices to StorageProvider (fire-and-forget).
13488
+ */
13489
+ saveToStorage() {
13490
+ if (!this.storage) return;
13491
+ const data = {};
13492
+ for (const [name, entry] of this.cache) {
13493
+ data[name] = entry.price;
13494
+ }
13495
+ Promise.all([
13496
+ this.storage.set(STORAGE_KEYS_GLOBAL.PRICE_CACHE, JSON.stringify(data)),
13497
+ this.storage.set(STORAGE_KEYS_GLOBAL.PRICE_CACHE_TS, String(Date.now()))
13498
+ ]).catch(() => {
13499
+ });
13500
+ }
13501
+ // ===========================================================================
13502
+ // Rate-limit handling
13503
+ // ===========================================================================
13504
+ /**
13505
+ * On 429 rate-limit, extend stale cache entries so subsequent calls
13506
+ * don't immediately retry and hammer the API.
13507
+ */
13508
+ extendCacheOnRateLimit(names) {
13509
+ const backoffMs = 6e4;
13510
+ const extendedExpiry = Date.now() + backoffMs;
13511
+ for (const name of names) {
13512
+ const existing = this.cache.get(name);
13513
+ if (existing) {
13514
+ existing.expiresAt = Math.max(existing.expiresAt, extendedExpiry);
13515
+ }
13516
+ }
13517
+ if (this.debug) {
13518
+ console.warn(`[CoinGecko] Rate-limited (429), extended cache TTL by ${backoffMs / 1e3}s`);
13519
+ }
13520
+ }
15807
13521
  async getPrice(tokenName) {
15808
13522
  const prices = await this.getPrices([tokenName]);
15809
13523
  return prices.get(tokenName) ?? null;
@@ -15834,7 +13548,6 @@ function createPriceProvider(config) {
15834
13548
  DEFAULT_GROUP_RELAYS,
15835
13549
  DEFAULT_IPFS_BOOTSTRAP_PEERS,
15836
13550
  DEFAULT_IPFS_GATEWAYS,
15837
- DEFAULT_MARKET_API_URL,
15838
13551
  DEFAULT_NOSTR_RELAYS,
15839
13552
  DEV_AGGREGATOR_URL,
15840
13553
  GroupChatModule,
@@ -15843,7 +13556,6 @@ function createPriceProvider(config) {
15843
13556
  L1,
15844
13557
  L1PaymentsModule,
15845
13558
  LIMITS,
15846
- MarketModule,
15847
13559
  NETWORKS,
15848
13560
  NIP29_KINDS,
15849
13561
  NOSTR_EVENT_KINDS,
@@ -15871,7 +13583,6 @@ function createPriceProvider(config) {
15871
13583
  createGroupChatModule,
15872
13584
  createKeyPair,
15873
13585
  createL1PaymentsModule,
15874
- createMarketModule,
15875
13586
  createPaymentSession,
15876
13587
  createPaymentSessionError,
15877
13588
  createPaymentsModule,
@@ -15959,16 +13670,4 @@ function createPriceProvider(config) {
15959
13670
  txfToToken,
15960
13671
  validateMnemonic
15961
13672
  });
15962
- /*! Bundled license information:
15963
-
15964
- @noble/hashes/utils.js:
15965
- (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
15966
-
15967
- @noble/curves/utils.js:
15968
- @noble/curves/abstract/modular.js:
15969
- @noble/curves/abstract/curve.js:
15970
- @noble/curves/abstract/weierstrass.js:
15971
- @noble/curves/secp256k1.js:
15972
- (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
15973
- */
15974
13673
  //# sourceMappingURL=index.cjs.map