@unicitylabs/sphere-sdk 0.3.5 → 0.3.7

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.
@@ -59,10 +59,10 @@ function bech32Polymod(values) {
59
59
  }
60
60
  function bech32Checksum(hrp, data) {
61
61
  const values = hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]);
62
- const mod = bech32Polymod(values) ^ 1;
62
+ const mod2 = bech32Polymod(values) ^ 1;
63
63
  const ret = [];
64
64
  for (let p = 0; p < 6; p++) {
65
- ret.push(mod >> 5 * (5 - p) & 31);
65
+ ret.push(mod2 >> 5 * (5 - p) & 31);
66
66
  }
67
67
  return ret;
68
68
  }
@@ -2335,7 +2335,11 @@ var STORAGE_KEYS_GLOBAL = {
2335
2335
  /** Group chat: processed event IDs for deduplication */
2336
2336
  GROUP_CHAT_PROCESSED_EVENTS: "group_chat_processed_events",
2337
2337
  /** Group chat: last used relay URL (stale data detection) */
2338
- GROUP_CHAT_RELAY_URL: "group_chat_relay_url"
2338
+ GROUP_CHAT_RELAY_URL: "group_chat_relay_url",
2339
+ /** Cached token registry JSON (fetched from remote) */
2340
+ TOKEN_REGISTRY_CACHE: "token_registry_cache",
2341
+ /** Timestamp of last token registry cache update (ms since epoch) */
2342
+ TOKEN_REGISTRY_CACHE_TS: "token_registry_cache_ts"
2339
2343
  };
2340
2344
  var STORAGE_KEYS_ADDRESS = {
2341
2345
  /** Pending transfers for this address */
@@ -2416,6 +2420,8 @@ var DEFAULT_BASE_PATH = "m/44'/0'/0'";
2416
2420
  var DEFAULT_DERIVATION_PATH2 = `${DEFAULT_BASE_PATH}/0/0`;
2417
2421
  var DEFAULT_ELECTRUM_URL = "wss://fulcrum.alpha.unicity.network:50004";
2418
2422
  var TEST_ELECTRUM_URL = "wss://fulcrum.alpha.testnet.unicity.network:50004";
2423
+ var TOKEN_REGISTRY_URL = "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/unicity-ids.testnet.json";
2424
+ var TOKEN_REGISTRY_REFRESH_INTERVAL = 36e5;
2419
2425
  var TEST_NOSTR_RELAYS = [
2420
2426
  "wss://nostr-relay.testnet.unicity.network"
2421
2427
  ];
@@ -2429,7 +2435,8 @@ var NETWORKS = {
2429
2435
  nostrRelays: DEFAULT_NOSTR_RELAYS,
2430
2436
  ipfsGateways: DEFAULT_IPFS_GATEWAYS,
2431
2437
  electrumUrl: DEFAULT_ELECTRUM_URL,
2432
- groupRelays: DEFAULT_GROUP_RELAYS
2438
+ groupRelays: DEFAULT_GROUP_RELAYS,
2439
+ tokenRegistryUrl: TOKEN_REGISTRY_URL
2433
2440
  },
2434
2441
  testnet: {
2435
2442
  name: "Testnet",
@@ -2437,7 +2444,8 @@ var NETWORKS = {
2437
2444
  nostrRelays: TEST_NOSTR_RELAYS,
2438
2445
  ipfsGateways: DEFAULT_IPFS_GATEWAYS,
2439
2446
  electrumUrl: TEST_ELECTRUM_URL,
2440
- groupRelays: DEFAULT_GROUP_RELAYS
2447
+ groupRelays: DEFAULT_GROUP_RELAYS,
2448
+ tokenRegistryUrl: TOKEN_REGISTRY_URL
2441
2449
  },
2442
2450
  dev: {
2443
2451
  name: "Development",
@@ -2445,9 +2453,11 @@ var NETWORKS = {
2445
2453
  nostrRelays: TEST_NOSTR_RELAYS,
2446
2454
  ipfsGateways: DEFAULT_IPFS_GATEWAYS,
2447
2455
  electrumUrl: TEST_ELECTRUM_URL,
2448
- groupRelays: DEFAULT_GROUP_RELAYS
2456
+ groupRelays: DEFAULT_GROUP_RELAYS,
2457
+ tokenRegistryUrl: TOKEN_REGISTRY_URL
2449
2458
  }
2450
2459
  };
2460
+ var DEFAULT_MARKET_API_URL = "https://market-api.unicity.network";
2451
2461
 
2452
2462
  // types/txf.ts
2453
2463
  var ARCHIVED_PREFIX = "archived-";
@@ -2488,141 +2498,24 @@ function parseForkedKey(key) {
2488
2498
  };
2489
2499
  }
2490
2500
 
2491
- // registry/token-registry.testnet.json
2492
- var token_registry_testnet_default = [
2493
- {
2494
- network: "unicity:testnet",
2495
- assetKind: "non-fungible",
2496
- name: "unicity",
2497
- description: "Unicity testnet token type",
2498
- id: "f8aa13834268d29355ff12183066f0cb902003629bbc5eb9ef0efbe397867509"
2499
- },
2500
- {
2501
- network: "unicity:testnet",
2502
- assetKind: "fungible",
2503
- name: "unicity",
2504
- symbol: "UCT",
2505
- decimals: 18,
2506
- description: "Unicity testnet native coin",
2507
- icons: [
2508
- { url: "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/unicity_logo_32.png" }
2509
- ],
2510
- id: "455ad8720656b08e8dbd5bac1f3c73eeea5431565f6c1c3af742b1aa12d41d89"
2511
- },
2512
- {
2513
- network: "unicity:testnet",
2514
- assetKind: "fungible",
2515
- name: "unicity-usd",
2516
- symbol: "USDU",
2517
- decimals: 6,
2518
- description: "Unicity testnet USD stablecoin",
2519
- icons: [
2520
- { url: "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/usdu_logo_32.png" }
2521
- ],
2522
- id: "8f0f3d7a5e7297be0ee98c63b81bcebb2740f43f616566fc290f9823a54f52d7"
2523
- },
2524
- {
2525
- network: "unicity:testnet",
2526
- assetKind: "fungible",
2527
- name: "unicity-eur",
2528
- symbol: "EURU",
2529
- decimals: 6,
2530
- description: "Unicity testnet EUR stablecoin",
2531
- icons: [
2532
- { url: "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/euru_logo_32.png" }
2533
- ],
2534
- id: "5e160d5e9fdbb03b553fb9c3f6e6c30efa41fa807be39fb4f18e43776e492925"
2535
- },
2536
- {
2537
- network: "unicity:testnet",
2538
- assetKind: "fungible",
2539
- name: "solana",
2540
- symbol: "SOL",
2541
- decimals: 9,
2542
- description: "Solana testnet coin on Unicity",
2543
- icons: [
2544
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/sol.svg" },
2545
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/sol.png" }
2546
- ],
2547
- id: "dee5f8ce778562eec90e9c38a91296a023210ccc76ff4c29d527ac3eb64ade93"
2548
- },
2549
- {
2550
- network: "unicity:testnet",
2551
- assetKind: "fungible",
2552
- name: "bitcoin",
2553
- symbol: "BTC",
2554
- decimals: 8,
2555
- description: "Bitcoin testnet coin on Unicity",
2556
- icons: [
2557
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/btc.svg" },
2558
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/btc.png" }
2559
- ],
2560
- id: "86bc190fcf7b2d07c6078de93db803578760148b16d4431aa2f42a3241ff0daa"
2561
- },
2562
- {
2563
- network: "unicity:testnet",
2564
- assetKind: "fungible",
2565
- name: "ethereum",
2566
- symbol: "ETH",
2567
- decimals: 18,
2568
- description: "Ethereum testnet coin on Unicity",
2569
- icons: [
2570
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/eth.svg" },
2571
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/eth.png" }
2572
- ],
2573
- id: "3c2450f2fd867e7bb60c6a69d7ad0e53ce967078c201a3ecaa6074ed4c0deafb"
2574
- },
2575
- {
2576
- network: "unicity:testnet",
2577
- assetKind: "fungible",
2578
- name: "alpha_test",
2579
- symbol: "ALPHT",
2580
- decimals: 8,
2581
- description: "ALPHA testnet coin on Unicity",
2582
- icons: [
2583
- { url: "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/alpha_coin.png" }
2584
- ],
2585
- id: "cde78ded16ef65818a51f43138031c4284e519300ab0cb60c30a8f9078080e5f"
2586
- },
2587
- {
2588
- network: "unicity:testnet",
2589
- assetKind: "fungible",
2590
- name: "tether",
2591
- symbol: "USDT",
2592
- decimals: 6,
2593
- description: "Tether (Ethereum) testnet coin on Unicity",
2594
- icons: [
2595
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/usdt.svg" },
2596
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/usdt.png" }
2597
- ],
2598
- id: "40d25444648418fe7efd433e147187a3a6adf049ac62bc46038bda5b960bf690"
2599
- },
2600
- {
2601
- network: "unicity:testnet",
2602
- assetKind: "fungible",
2603
- name: "usd-coin",
2604
- symbol: "USDC",
2605
- decimals: 6,
2606
- description: "USDC (Ethereum) testnet coin on Unicity",
2607
- icons: [
2608
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/usdc.svg" },
2609
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/usdc.png" }
2610
- ],
2611
- id: "2265121770fa6f41131dd9a6cc571e28679263d09a53eb2642e145b5b9a5b0a2"
2612
- }
2613
- ];
2614
-
2615
2501
  // registry/TokenRegistry.ts
2502
+ var FETCH_TIMEOUT_MS = 1e4;
2616
2503
  var TokenRegistry = class _TokenRegistry {
2617
2504
  static instance = null;
2618
2505
  definitionsById;
2619
2506
  definitionsBySymbol;
2620
2507
  definitionsByName;
2508
+ // Remote refresh state
2509
+ remoteUrl = null;
2510
+ storage = null;
2511
+ refreshIntervalMs = TOKEN_REGISTRY_REFRESH_INTERVAL;
2512
+ refreshTimer = null;
2513
+ lastRefreshAt = 0;
2514
+ refreshPromise = null;
2621
2515
  constructor() {
2622
2516
  this.definitionsById = /* @__PURE__ */ new Map();
2623
2517
  this.definitionsBySymbol = /* @__PURE__ */ new Map();
2624
2518
  this.definitionsByName = /* @__PURE__ */ new Map();
2625
- this.loadRegistry();
2626
2519
  }
2627
2520
  /**
2628
2521
  * Get singleton instance of TokenRegistry
@@ -2634,16 +2527,106 @@ var TokenRegistry = class _TokenRegistry {
2634
2527
  return _TokenRegistry.instance;
2635
2528
  }
2636
2529
  /**
2637
- * Reset the singleton instance (useful for testing)
2530
+ * Configure remote registry refresh with persistent caching.
2531
+ *
2532
+ * On first call:
2533
+ * 1. Loads cached data from StorageProvider (if available and fresh)
2534
+ * 2. Starts periodic remote fetch (if autoRefresh is true, which is default)
2535
+ *
2536
+ * @param options - Configuration options
2537
+ * @param options.remoteUrl - Remote URL to fetch definitions from
2538
+ * @param options.storage - StorageProvider for persistent caching
2539
+ * @param options.refreshIntervalMs - Refresh interval in ms (default: 1 hour)
2540
+ * @param options.autoRefresh - Start auto-refresh immediately (default: true)
2541
+ */
2542
+ static configure(options) {
2543
+ const instance = _TokenRegistry.getInstance();
2544
+ if (options.remoteUrl !== void 0) {
2545
+ instance.remoteUrl = options.remoteUrl;
2546
+ }
2547
+ if (options.storage !== void 0) {
2548
+ instance.storage = options.storage;
2549
+ }
2550
+ if (options.refreshIntervalMs !== void 0) {
2551
+ instance.refreshIntervalMs = options.refreshIntervalMs;
2552
+ }
2553
+ if (instance.storage) {
2554
+ instance.loadFromCache();
2555
+ }
2556
+ const autoRefresh = options.autoRefresh ?? true;
2557
+ if (autoRefresh && instance.remoteUrl) {
2558
+ instance.startAutoRefresh();
2559
+ }
2560
+ }
2561
+ /**
2562
+ * Reset the singleton instance (useful for testing).
2563
+ * Stops auto-refresh if running.
2638
2564
  */
2639
2565
  static resetInstance() {
2566
+ if (_TokenRegistry.instance) {
2567
+ _TokenRegistry.instance.stopAutoRefresh();
2568
+ }
2640
2569
  _TokenRegistry.instance = null;
2641
2570
  }
2642
2571
  /**
2643
- * Load registry data from bundled JSON
2572
+ * Destroy the singleton: stop auto-refresh and reset.
2573
+ */
2574
+ static destroy() {
2575
+ _TokenRegistry.resetInstance();
2576
+ }
2577
+ // ===========================================================================
2578
+ // Cache (StorageProvider)
2579
+ // ===========================================================================
2580
+ /**
2581
+ * Load definitions from StorageProvider cache.
2582
+ * Only applies if cache exists and is fresh (within refreshIntervalMs).
2583
+ */
2584
+ async loadFromCache() {
2585
+ if (!this.storage) return false;
2586
+ try {
2587
+ const [cached, cachedTs] = await Promise.all([
2588
+ this.storage.get(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE),
2589
+ this.storage.get(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE_TS)
2590
+ ]);
2591
+ if (!cached || !cachedTs) return false;
2592
+ const ts = parseInt(cachedTs, 10);
2593
+ if (isNaN(ts)) return false;
2594
+ const age = Date.now() - ts;
2595
+ if (age > this.refreshIntervalMs) return false;
2596
+ if (this.lastRefreshAt > ts) return false;
2597
+ const data = JSON.parse(cached);
2598
+ if (!this.isValidDefinitionsArray(data)) return false;
2599
+ this.applyDefinitions(data);
2600
+ this.lastRefreshAt = ts;
2601
+ return true;
2602
+ } catch {
2603
+ return false;
2604
+ }
2605
+ }
2606
+ /**
2607
+ * Save definitions to StorageProvider cache.
2608
+ */
2609
+ async saveToCache(definitions) {
2610
+ if (!this.storage) return;
2611
+ try {
2612
+ await Promise.all([
2613
+ this.storage.set(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE, JSON.stringify(definitions)),
2614
+ this.storage.set(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE_TS, String(Date.now()))
2615
+ ]);
2616
+ } catch {
2617
+ }
2618
+ }
2619
+ // ===========================================================================
2620
+ // Remote Refresh
2621
+ // ===========================================================================
2622
+ /**
2623
+ * Apply an array of token definitions to the internal maps.
2624
+ * Clears existing data before applying.
2644
2625
  */
2645
- loadRegistry() {
2646
- const definitions = token_registry_testnet_default;
2626
+ applyDefinitions(definitions) {
2627
+ this.definitionsById.clear();
2628
+ this.definitionsBySymbol.clear();
2629
+ this.definitionsByName.clear();
2647
2630
  for (const def of definitions) {
2648
2631
  const idLower = def.id.toLowerCase();
2649
2632
  this.definitionsById.set(idLower, def);
@@ -2653,6 +2636,96 @@ var TokenRegistry = class _TokenRegistry {
2653
2636
  this.definitionsByName.set(def.name.toLowerCase(), def);
2654
2637
  }
2655
2638
  }
2639
+ /**
2640
+ * Validate that data is an array of objects with 'id' field
2641
+ */
2642
+ isValidDefinitionsArray(data) {
2643
+ return Array.isArray(data) && data.every((item) => item && typeof item === "object" && "id" in item);
2644
+ }
2645
+ /**
2646
+ * Fetch token definitions from the remote URL and update the registry.
2647
+ * On success, also persists to StorageProvider cache.
2648
+ * Returns true on success, false on failure. On failure, existing data is preserved.
2649
+ * Concurrent calls are deduplicated — only one fetch runs at a time.
2650
+ */
2651
+ async refreshFromRemote() {
2652
+ if (!this.remoteUrl) {
2653
+ return false;
2654
+ }
2655
+ if (this.refreshPromise) {
2656
+ return this.refreshPromise;
2657
+ }
2658
+ this.refreshPromise = this.doRefresh();
2659
+ try {
2660
+ return await this.refreshPromise;
2661
+ } finally {
2662
+ this.refreshPromise = null;
2663
+ }
2664
+ }
2665
+ async doRefresh() {
2666
+ try {
2667
+ const controller = new AbortController();
2668
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
2669
+ let response;
2670
+ try {
2671
+ response = await fetch(this.remoteUrl, {
2672
+ headers: { Accept: "application/json" },
2673
+ signal: controller.signal
2674
+ });
2675
+ } finally {
2676
+ clearTimeout(timer);
2677
+ }
2678
+ if (!response.ok) {
2679
+ console.warn(
2680
+ `[TokenRegistry] Remote fetch failed: HTTP ${response.status} ${response.statusText}`
2681
+ );
2682
+ return false;
2683
+ }
2684
+ const data = await response.json();
2685
+ if (!this.isValidDefinitionsArray(data)) {
2686
+ console.warn("[TokenRegistry] Remote data is not a valid token definitions array");
2687
+ return false;
2688
+ }
2689
+ const definitions = data;
2690
+ this.applyDefinitions(definitions);
2691
+ this.lastRefreshAt = Date.now();
2692
+ this.saveToCache(definitions);
2693
+ return true;
2694
+ } catch (error) {
2695
+ const message = error instanceof Error ? error.message : String(error);
2696
+ console.warn(`[TokenRegistry] Remote refresh failed: ${message}`);
2697
+ return false;
2698
+ }
2699
+ }
2700
+ /**
2701
+ * Start periodic auto-refresh from the remote URL.
2702
+ * Does an immediate fetch, then repeats at the configured interval.
2703
+ */
2704
+ startAutoRefresh(intervalMs) {
2705
+ this.stopAutoRefresh();
2706
+ if (intervalMs !== void 0) {
2707
+ this.refreshIntervalMs = intervalMs;
2708
+ }
2709
+ this.refreshFromRemote();
2710
+ this.refreshTimer = setInterval(() => {
2711
+ this.refreshFromRemote();
2712
+ }, this.refreshIntervalMs);
2713
+ }
2714
+ /**
2715
+ * Stop periodic auto-refresh
2716
+ */
2717
+ stopAutoRefresh() {
2718
+ if (this.refreshTimer !== null) {
2719
+ clearInterval(this.refreshTimer);
2720
+ this.refreshTimer = null;
2721
+ }
2722
+ }
2723
+ /**
2724
+ * Timestamp of the last successful remote refresh (0 if never refreshed)
2725
+ */
2726
+ getLastRefreshAt() {
2727
+ return this.lastRefreshAt;
2728
+ }
2656
2729
  // ===========================================================================
2657
2730
  // Lookup Methods
2658
2731
  // ===========================================================================
@@ -7185,6 +7258,28 @@ var CommunicationsModule = class {
7185
7258
  this.unsubscribeMessages = deps.transport.onMessage((msg) => {
7186
7259
  this.handleIncomingMessage(msg);
7187
7260
  });
7261
+ if (deps.transport.onReadReceipt) {
7262
+ deps.transport.onReadReceipt((receipt) => {
7263
+ const msg = this.messages.get(receipt.messageEventId);
7264
+ if (msg && msg.senderPubkey === this.deps.identity.chainPubkey) {
7265
+ msg.isRead = true;
7266
+ this.save();
7267
+ this.deps.emitEvent("message:read", {
7268
+ messageIds: [receipt.messageEventId],
7269
+ peerPubkey: receipt.senderTransportPubkey
7270
+ });
7271
+ }
7272
+ });
7273
+ }
7274
+ if (deps.transport.onTypingIndicator) {
7275
+ deps.transport.onTypingIndicator((indicator) => {
7276
+ this.deps.emitEvent("message:typing", {
7277
+ senderPubkey: indicator.senderTransportPubkey,
7278
+ senderNametag: indicator.senderNametag,
7279
+ timestamp: indicator.timestamp
7280
+ });
7281
+ });
7282
+ }
7188
7283
  }
7189
7284
  /**
7190
7285
  * Load messages from storage
@@ -7228,7 +7323,7 @@ var CommunicationsModule = class {
7228
7323
  recipientPubkey,
7229
7324
  content,
7230
7325
  timestamp: Date.now(),
7231
- isRead: true
7326
+ isRead: false
7232
7327
  };
7233
7328
  this.messages.set(message.id, message);
7234
7329
  if (this.config.autoSave) {
@@ -7274,6 +7369,16 @@ var CommunicationsModule = class {
7274
7369
  if (this.config.autoSave) {
7275
7370
  await this.save();
7276
7371
  }
7372
+ if (this.config.readReceipts && this.deps?.transport.sendReadReceipt) {
7373
+ for (const id of messageIds) {
7374
+ const msg = this.messages.get(id);
7375
+ if (msg && msg.senderPubkey !== this.deps.identity.chainPubkey) {
7376
+ this.deps.transport.sendReadReceipt(msg.senderPubkey, id).catch((err) => {
7377
+ console.warn("[Communications] Failed to send read receipt:", err);
7378
+ });
7379
+ }
7380
+ }
7381
+ }
7277
7382
  }
7278
7383
  /**
7279
7384
  * Get unread count
@@ -7287,6 +7392,15 @@ var CommunicationsModule = class {
7287
7392
  }
7288
7393
  return messages.length;
7289
7394
  }
7395
+ /**
7396
+ * Send typing indicator to a peer
7397
+ */
7398
+ async sendTypingIndicator(peerPubkey) {
7399
+ this.ensureInitialized();
7400
+ if (this.deps.transport.sendTypingIndicator) {
7401
+ await this.deps.transport.sendTypingIndicator(peerPubkey);
7402
+ }
7403
+ }
7290
7404
  /**
7291
7405
  * Subscribe to incoming DMs
7292
7406
  */
@@ -7356,7 +7470,26 @@ var CommunicationsModule = class {
7356
7470
  // Private: Message Handling
7357
7471
  // ===========================================================================
7358
7472
  handleIncomingMessage(msg) {
7473
+ if (msg.isSelfWrap && msg.recipientTransportPubkey) {
7474
+ if (this.messages.has(msg.id)) return;
7475
+ const message2 = {
7476
+ id: msg.id,
7477
+ senderPubkey: this.deps.identity.chainPubkey,
7478
+ senderNametag: msg.senderNametag,
7479
+ recipientPubkey: msg.recipientTransportPubkey,
7480
+ content: msg.content,
7481
+ timestamp: msg.timestamp,
7482
+ isRead: false
7483
+ };
7484
+ this.messages.set(message2.id, message2);
7485
+ this.deps.emitEvent("message:dm", message2);
7486
+ if (this.config.autoSave) {
7487
+ this.save();
7488
+ }
7489
+ return;
7490
+ }
7359
7491
  if (msg.senderTransportPubkey === this.deps?.identity.chainPubkey) return;
7492
+ if (this.messages.has(msg.id)) return;
7360
7493
  const message = {
7361
7494
  id: msg.id,
7362
7495
  senderPubkey: msg.senderTransportPubkey,
@@ -8817,6 +8950,2426 @@ function createGroupChatModule(config) {
8817
8950
  return new GroupChatModule(config);
8818
8951
  }
8819
8952
 
8953
+ // node_modules/@noble/hashes/utils.js
8954
+ function isBytes(a) {
8955
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
8956
+ }
8957
+ function anumber(n, title = "") {
8958
+ if (!Number.isSafeInteger(n) || n < 0) {
8959
+ const prefix = title && `"${title}" `;
8960
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
8961
+ }
8962
+ }
8963
+ function abytes(value, length, title = "") {
8964
+ const bytes = isBytes(value);
8965
+ const len = value?.length;
8966
+ const needsLen = length !== void 0;
8967
+ if (!bytes || needsLen && len !== length) {
8968
+ const prefix = title && `"${title}" `;
8969
+ const ofLen = needsLen ? ` of length ${length}` : "";
8970
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
8971
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
8972
+ }
8973
+ return value;
8974
+ }
8975
+ function ahash(h) {
8976
+ if (typeof h !== "function" || typeof h.create !== "function")
8977
+ throw new Error("Hash must wrapped by utils.createHasher");
8978
+ anumber(h.outputLen);
8979
+ anumber(h.blockLen);
8980
+ }
8981
+ function aexists(instance, checkFinished = true) {
8982
+ if (instance.destroyed)
8983
+ throw new Error("Hash instance has been destroyed");
8984
+ if (checkFinished && instance.finished)
8985
+ throw new Error("Hash#digest() has already been called");
8986
+ }
8987
+ function aoutput(out, instance) {
8988
+ abytes(out, void 0, "digestInto() output");
8989
+ const min = instance.outputLen;
8990
+ if (out.length < min) {
8991
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
8992
+ }
8993
+ }
8994
+ function clean(...arrays) {
8995
+ for (let i = 0; i < arrays.length; i++) {
8996
+ arrays[i].fill(0);
8997
+ }
8998
+ }
8999
+ function createView(arr) {
9000
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
9001
+ }
9002
+ function rotr(word, shift) {
9003
+ return word << 32 - shift | word >>> shift;
9004
+ }
9005
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
9006
+ // @ts-ignore
9007
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
9008
+ ))();
9009
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
9010
+ function bytesToHex4(bytes) {
9011
+ abytes(bytes);
9012
+ if (hasHexBuiltin)
9013
+ return bytes.toHex();
9014
+ let hex = "";
9015
+ for (let i = 0; i < bytes.length; i++) {
9016
+ hex += hexes[bytes[i]];
9017
+ }
9018
+ return hex;
9019
+ }
9020
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
9021
+ function asciiToBase16(ch) {
9022
+ if (ch >= asciis._0 && ch <= asciis._9)
9023
+ return ch - asciis._0;
9024
+ if (ch >= asciis.A && ch <= asciis.F)
9025
+ return ch - (asciis.A - 10);
9026
+ if (ch >= asciis.a && ch <= asciis.f)
9027
+ return ch - (asciis.a - 10);
9028
+ return;
9029
+ }
9030
+ function hexToBytes2(hex) {
9031
+ if (typeof hex !== "string")
9032
+ throw new Error("hex string expected, got " + typeof hex);
9033
+ if (hasHexBuiltin)
9034
+ return Uint8Array.fromHex(hex);
9035
+ const hl = hex.length;
9036
+ const al = hl / 2;
9037
+ if (hl % 2)
9038
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
9039
+ const array = new Uint8Array(al);
9040
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
9041
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
9042
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
9043
+ if (n1 === void 0 || n2 === void 0) {
9044
+ const char = hex[hi] + hex[hi + 1];
9045
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
9046
+ }
9047
+ array[ai] = n1 * 16 + n2;
9048
+ }
9049
+ return array;
9050
+ }
9051
+ function concatBytes(...arrays) {
9052
+ let sum = 0;
9053
+ for (let i = 0; i < arrays.length; i++) {
9054
+ const a = arrays[i];
9055
+ abytes(a);
9056
+ sum += a.length;
9057
+ }
9058
+ const res = new Uint8Array(sum);
9059
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
9060
+ const a = arrays[i];
9061
+ res.set(a, pad);
9062
+ pad += a.length;
9063
+ }
9064
+ return res;
9065
+ }
9066
+ function createHasher(hashCons, info = {}) {
9067
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
9068
+ const tmp = hashCons(void 0);
9069
+ hashC.outputLen = tmp.outputLen;
9070
+ hashC.blockLen = tmp.blockLen;
9071
+ hashC.create = (opts) => hashCons(opts);
9072
+ Object.assign(hashC, info);
9073
+ return Object.freeze(hashC);
9074
+ }
9075
+ function randomBytes2(bytesLength = 32) {
9076
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
9077
+ if (typeof cr?.getRandomValues !== "function")
9078
+ throw new Error("crypto.getRandomValues must be defined");
9079
+ return cr.getRandomValues(new Uint8Array(bytesLength));
9080
+ }
9081
+ var oidNist = (suffix) => ({
9082
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
9083
+ });
9084
+
9085
+ // node_modules/@noble/hashes/_md.js
9086
+ function Chi(a, b, c) {
9087
+ return a & b ^ ~a & c;
9088
+ }
9089
+ function Maj(a, b, c) {
9090
+ return a & b ^ a & c ^ b & c;
9091
+ }
9092
+ var HashMD = class {
9093
+ blockLen;
9094
+ outputLen;
9095
+ padOffset;
9096
+ isLE;
9097
+ // For partial updates less than block size
9098
+ buffer;
9099
+ view;
9100
+ finished = false;
9101
+ length = 0;
9102
+ pos = 0;
9103
+ destroyed = false;
9104
+ constructor(blockLen, outputLen, padOffset, isLE) {
9105
+ this.blockLen = blockLen;
9106
+ this.outputLen = outputLen;
9107
+ this.padOffset = padOffset;
9108
+ this.isLE = isLE;
9109
+ this.buffer = new Uint8Array(blockLen);
9110
+ this.view = createView(this.buffer);
9111
+ }
9112
+ update(data) {
9113
+ aexists(this);
9114
+ abytes(data);
9115
+ const { view, buffer, blockLen } = this;
9116
+ const len = data.length;
9117
+ for (let pos = 0; pos < len; ) {
9118
+ const take = Math.min(blockLen - this.pos, len - pos);
9119
+ if (take === blockLen) {
9120
+ const dataView = createView(data);
9121
+ for (; blockLen <= len - pos; pos += blockLen)
9122
+ this.process(dataView, pos);
9123
+ continue;
9124
+ }
9125
+ buffer.set(data.subarray(pos, pos + take), this.pos);
9126
+ this.pos += take;
9127
+ pos += take;
9128
+ if (this.pos === blockLen) {
9129
+ this.process(view, 0);
9130
+ this.pos = 0;
9131
+ }
9132
+ }
9133
+ this.length += data.length;
9134
+ this.roundClean();
9135
+ return this;
9136
+ }
9137
+ digestInto(out) {
9138
+ aexists(this);
9139
+ aoutput(out, this);
9140
+ this.finished = true;
9141
+ const { buffer, view, blockLen, isLE } = this;
9142
+ let { pos } = this;
9143
+ buffer[pos++] = 128;
9144
+ clean(this.buffer.subarray(pos));
9145
+ if (this.padOffset > blockLen - pos) {
9146
+ this.process(view, 0);
9147
+ pos = 0;
9148
+ }
9149
+ for (let i = pos; i < blockLen; i++)
9150
+ buffer[i] = 0;
9151
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
9152
+ this.process(view, 0);
9153
+ const oview = createView(out);
9154
+ const len = this.outputLen;
9155
+ if (len % 4)
9156
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
9157
+ const outLen = len / 4;
9158
+ const state = this.get();
9159
+ if (outLen > state.length)
9160
+ throw new Error("_sha2: outputLen bigger than state");
9161
+ for (let i = 0; i < outLen; i++)
9162
+ oview.setUint32(4 * i, state[i], isLE);
9163
+ }
9164
+ digest() {
9165
+ const { buffer, outputLen } = this;
9166
+ this.digestInto(buffer);
9167
+ const res = buffer.slice(0, outputLen);
9168
+ this.destroy();
9169
+ return res;
9170
+ }
9171
+ _cloneInto(to) {
9172
+ to ||= new this.constructor();
9173
+ to.set(...this.get());
9174
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
9175
+ to.destroyed = destroyed;
9176
+ to.finished = finished;
9177
+ to.length = length;
9178
+ to.pos = pos;
9179
+ if (length % blockLen)
9180
+ to.buffer.set(buffer);
9181
+ return to;
9182
+ }
9183
+ clone() {
9184
+ return this._cloneInto();
9185
+ }
9186
+ };
9187
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
9188
+ 1779033703,
9189
+ 3144134277,
9190
+ 1013904242,
9191
+ 2773480762,
9192
+ 1359893119,
9193
+ 2600822924,
9194
+ 528734635,
9195
+ 1541459225
9196
+ ]);
9197
+
9198
+ // node_modules/@noble/hashes/sha2.js
9199
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
9200
+ 1116352408,
9201
+ 1899447441,
9202
+ 3049323471,
9203
+ 3921009573,
9204
+ 961987163,
9205
+ 1508970993,
9206
+ 2453635748,
9207
+ 2870763221,
9208
+ 3624381080,
9209
+ 310598401,
9210
+ 607225278,
9211
+ 1426881987,
9212
+ 1925078388,
9213
+ 2162078206,
9214
+ 2614888103,
9215
+ 3248222580,
9216
+ 3835390401,
9217
+ 4022224774,
9218
+ 264347078,
9219
+ 604807628,
9220
+ 770255983,
9221
+ 1249150122,
9222
+ 1555081692,
9223
+ 1996064986,
9224
+ 2554220882,
9225
+ 2821834349,
9226
+ 2952996808,
9227
+ 3210313671,
9228
+ 3336571891,
9229
+ 3584528711,
9230
+ 113926993,
9231
+ 338241895,
9232
+ 666307205,
9233
+ 773529912,
9234
+ 1294757372,
9235
+ 1396182291,
9236
+ 1695183700,
9237
+ 1986661051,
9238
+ 2177026350,
9239
+ 2456956037,
9240
+ 2730485921,
9241
+ 2820302411,
9242
+ 3259730800,
9243
+ 3345764771,
9244
+ 3516065817,
9245
+ 3600352804,
9246
+ 4094571909,
9247
+ 275423344,
9248
+ 430227734,
9249
+ 506948616,
9250
+ 659060556,
9251
+ 883997877,
9252
+ 958139571,
9253
+ 1322822218,
9254
+ 1537002063,
9255
+ 1747873779,
9256
+ 1955562222,
9257
+ 2024104815,
9258
+ 2227730452,
9259
+ 2361852424,
9260
+ 2428436474,
9261
+ 2756734187,
9262
+ 3204031479,
9263
+ 3329325298
9264
+ ]);
9265
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
9266
+ var SHA2_32B = class extends HashMD {
9267
+ constructor(outputLen) {
9268
+ super(64, outputLen, 8, false);
9269
+ }
9270
+ get() {
9271
+ const { A, B, C, D, E, F, G, H } = this;
9272
+ return [A, B, C, D, E, F, G, H];
9273
+ }
9274
+ // prettier-ignore
9275
+ set(A, B, C, D, E, F, G, H) {
9276
+ this.A = A | 0;
9277
+ this.B = B | 0;
9278
+ this.C = C | 0;
9279
+ this.D = D | 0;
9280
+ this.E = E | 0;
9281
+ this.F = F | 0;
9282
+ this.G = G | 0;
9283
+ this.H = H | 0;
9284
+ }
9285
+ process(view, offset) {
9286
+ for (let i = 0; i < 16; i++, offset += 4)
9287
+ SHA256_W[i] = view.getUint32(offset, false);
9288
+ for (let i = 16; i < 64; i++) {
9289
+ const W15 = SHA256_W[i - 15];
9290
+ const W2 = SHA256_W[i - 2];
9291
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
9292
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
9293
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
9294
+ }
9295
+ let { A, B, C, D, E, F, G, H } = this;
9296
+ for (let i = 0; i < 64; i++) {
9297
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
9298
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
9299
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
9300
+ const T2 = sigma0 + Maj(A, B, C) | 0;
9301
+ H = G;
9302
+ G = F;
9303
+ F = E;
9304
+ E = D + T1 | 0;
9305
+ D = C;
9306
+ C = B;
9307
+ B = A;
9308
+ A = T1 + T2 | 0;
9309
+ }
9310
+ A = A + this.A | 0;
9311
+ B = B + this.B | 0;
9312
+ C = C + this.C | 0;
9313
+ D = D + this.D | 0;
9314
+ E = E + this.E | 0;
9315
+ F = F + this.F | 0;
9316
+ G = G + this.G | 0;
9317
+ H = H + this.H | 0;
9318
+ this.set(A, B, C, D, E, F, G, H);
9319
+ }
9320
+ roundClean() {
9321
+ clean(SHA256_W);
9322
+ }
9323
+ destroy() {
9324
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
9325
+ clean(this.buffer);
9326
+ }
9327
+ };
9328
+ var _SHA256 = class extends SHA2_32B {
9329
+ // We cannot use array here since array allows indexing by variable
9330
+ // which means optimizer/compiler cannot use registers.
9331
+ A = SHA256_IV[0] | 0;
9332
+ B = SHA256_IV[1] | 0;
9333
+ C = SHA256_IV[2] | 0;
9334
+ D = SHA256_IV[3] | 0;
9335
+ E = SHA256_IV[4] | 0;
9336
+ F = SHA256_IV[5] | 0;
9337
+ G = SHA256_IV[6] | 0;
9338
+ H = SHA256_IV[7] | 0;
9339
+ constructor() {
9340
+ super(32);
9341
+ }
9342
+ };
9343
+ var sha2564 = /* @__PURE__ */ createHasher(
9344
+ () => new _SHA256(),
9345
+ /* @__PURE__ */ oidNist(1)
9346
+ );
9347
+
9348
+ // node_modules/@noble/curves/utils.js
9349
+ var _0n = /* @__PURE__ */ BigInt(0);
9350
+ var _1n = /* @__PURE__ */ BigInt(1);
9351
+ function abool(value, title = "") {
9352
+ if (typeof value !== "boolean") {
9353
+ const prefix = title && `"${title}" `;
9354
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
9355
+ }
9356
+ return value;
9357
+ }
9358
+ function abignumber(n) {
9359
+ if (typeof n === "bigint") {
9360
+ if (!isPosBig(n))
9361
+ throw new Error("positive bigint expected, got " + n);
9362
+ } else
9363
+ anumber(n);
9364
+ return n;
9365
+ }
9366
+ function numberToHexUnpadded(num) {
9367
+ const hex = abignumber(num).toString(16);
9368
+ return hex.length & 1 ? "0" + hex : hex;
9369
+ }
9370
+ function hexToNumber(hex) {
9371
+ if (typeof hex !== "string")
9372
+ throw new Error("hex string expected, got " + typeof hex);
9373
+ return hex === "" ? _0n : BigInt("0x" + hex);
9374
+ }
9375
+ function bytesToNumberBE(bytes) {
9376
+ return hexToNumber(bytesToHex4(bytes));
9377
+ }
9378
+ function bytesToNumberLE(bytes) {
9379
+ return hexToNumber(bytesToHex4(copyBytes(abytes(bytes)).reverse()));
9380
+ }
9381
+ function numberToBytesBE(n, len) {
9382
+ anumber(len);
9383
+ n = abignumber(n);
9384
+ const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
9385
+ if (res.length !== len)
9386
+ throw new Error("number too large");
9387
+ return res;
9388
+ }
9389
+ function numberToBytesLE(n, len) {
9390
+ return numberToBytesBE(n, len).reverse();
9391
+ }
9392
+ function copyBytes(bytes) {
9393
+ return Uint8Array.from(bytes);
9394
+ }
9395
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
9396
+ function inRange(n, min, max) {
9397
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
9398
+ }
9399
+ function aInRange(title, n, min, max) {
9400
+ if (!inRange(n, min, max))
9401
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
9402
+ }
9403
+ function bitLen(n) {
9404
+ let len;
9405
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
9406
+ ;
9407
+ return len;
9408
+ }
9409
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
9410
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
9411
+ anumber(hashLen, "hashLen");
9412
+ anumber(qByteLen, "qByteLen");
9413
+ if (typeof hmacFn !== "function")
9414
+ throw new Error("hmacFn must be a function");
9415
+ const u8n = (len) => new Uint8Array(len);
9416
+ const NULL = Uint8Array.of();
9417
+ const byte0 = Uint8Array.of(0);
9418
+ const byte1 = Uint8Array.of(1);
9419
+ const _maxDrbgIters = 1e3;
9420
+ let v = u8n(hashLen);
9421
+ let k = u8n(hashLen);
9422
+ let i = 0;
9423
+ const reset = () => {
9424
+ v.fill(1);
9425
+ k.fill(0);
9426
+ i = 0;
9427
+ };
9428
+ const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
9429
+ const reseed = (seed = NULL) => {
9430
+ k = h(byte0, seed);
9431
+ v = h();
9432
+ if (seed.length === 0)
9433
+ return;
9434
+ k = h(byte1, seed);
9435
+ v = h();
9436
+ };
9437
+ const gen = () => {
9438
+ if (i++ >= _maxDrbgIters)
9439
+ throw new Error("drbg: tried max amount of iterations");
9440
+ let len = 0;
9441
+ const out = [];
9442
+ while (len < qByteLen) {
9443
+ v = h();
9444
+ const sl = v.slice();
9445
+ out.push(sl);
9446
+ len += v.length;
9447
+ }
9448
+ return concatBytes(...out);
9449
+ };
9450
+ const genUntil = (seed, pred) => {
9451
+ reset();
9452
+ reseed(seed);
9453
+ let res = void 0;
9454
+ while (!(res = pred(gen())))
9455
+ reseed();
9456
+ reset();
9457
+ return res;
9458
+ };
9459
+ return genUntil;
9460
+ }
9461
+ function validateObject(object, fields = {}, optFields = {}) {
9462
+ if (!object || typeof object !== "object")
9463
+ throw new Error("expected valid options object");
9464
+ function checkField(fieldName, expectedType, isOpt) {
9465
+ const val = object[fieldName];
9466
+ if (isOpt && val === void 0)
9467
+ return;
9468
+ const current = typeof val;
9469
+ if (current !== expectedType || val === null)
9470
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
9471
+ }
9472
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
9473
+ iter(fields, false);
9474
+ iter(optFields, true);
9475
+ }
9476
+ function memoized(fn) {
9477
+ const map = /* @__PURE__ */ new WeakMap();
9478
+ return (arg, ...args) => {
9479
+ const val = map.get(arg);
9480
+ if (val !== void 0)
9481
+ return val;
9482
+ const computed = fn(arg, ...args);
9483
+ map.set(arg, computed);
9484
+ return computed;
9485
+ };
9486
+ }
9487
+
9488
+ // node_modules/@noble/curves/abstract/modular.js
9489
+ var _0n2 = /* @__PURE__ */ BigInt(0);
9490
+ var _1n2 = /* @__PURE__ */ BigInt(1);
9491
+ var _2n = /* @__PURE__ */ BigInt(2);
9492
+ var _3n = /* @__PURE__ */ BigInt(3);
9493
+ var _4n = /* @__PURE__ */ BigInt(4);
9494
+ var _5n = /* @__PURE__ */ BigInt(5);
9495
+ var _7n = /* @__PURE__ */ BigInt(7);
9496
+ var _8n = /* @__PURE__ */ BigInt(8);
9497
+ var _9n = /* @__PURE__ */ BigInt(9);
9498
+ var _16n = /* @__PURE__ */ BigInt(16);
9499
+ function mod(a, b) {
9500
+ const result = a % b;
9501
+ return result >= _0n2 ? result : b + result;
9502
+ }
9503
+ function pow2(x, power, modulo) {
9504
+ let res = x;
9505
+ while (power-- > _0n2) {
9506
+ res *= res;
9507
+ res %= modulo;
9508
+ }
9509
+ return res;
9510
+ }
9511
+ function invert(number, modulo) {
9512
+ if (number === _0n2)
9513
+ throw new Error("invert: expected non-zero number");
9514
+ if (modulo <= _0n2)
9515
+ throw new Error("invert: expected positive modulus, got " + modulo);
9516
+ let a = mod(number, modulo);
9517
+ let b = modulo;
9518
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
9519
+ while (a !== _0n2) {
9520
+ const q = b / a;
9521
+ const r = b % a;
9522
+ const m = x - u * q;
9523
+ const n = y - v * q;
9524
+ b = a, a = r, x = u, y = v, u = m, v = n;
9525
+ }
9526
+ const gcd = b;
9527
+ if (gcd !== _1n2)
9528
+ throw new Error("invert: does not exist");
9529
+ return mod(x, modulo);
9530
+ }
9531
+ function assertIsSquare(Fp, root, n) {
9532
+ if (!Fp.eql(Fp.sqr(root), n))
9533
+ throw new Error("Cannot find square root");
9534
+ }
9535
+ function sqrt3mod4(Fp, n) {
9536
+ const p1div4 = (Fp.ORDER + _1n2) / _4n;
9537
+ const root = Fp.pow(n, p1div4);
9538
+ assertIsSquare(Fp, root, n);
9539
+ return root;
9540
+ }
9541
+ function sqrt5mod8(Fp, n) {
9542
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
9543
+ const n2 = Fp.mul(n, _2n);
9544
+ const v = Fp.pow(n2, p5div8);
9545
+ const nv = Fp.mul(n, v);
9546
+ const i = Fp.mul(Fp.mul(nv, _2n), v);
9547
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
9548
+ assertIsSquare(Fp, root, n);
9549
+ return root;
9550
+ }
9551
+ function sqrt9mod16(P) {
9552
+ const Fp_ = Field(P);
9553
+ const tn = tonelliShanks(P);
9554
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
9555
+ const c2 = tn(Fp_, c1);
9556
+ const c3 = tn(Fp_, Fp_.neg(c1));
9557
+ const c4 = (P + _7n) / _16n;
9558
+ return (Fp, n) => {
9559
+ let tv1 = Fp.pow(n, c4);
9560
+ let tv2 = Fp.mul(tv1, c1);
9561
+ const tv3 = Fp.mul(tv1, c2);
9562
+ const tv4 = Fp.mul(tv1, c3);
9563
+ const e1 = Fp.eql(Fp.sqr(tv2), n);
9564
+ const e2 = Fp.eql(Fp.sqr(tv3), n);
9565
+ tv1 = Fp.cmov(tv1, tv2, e1);
9566
+ tv2 = Fp.cmov(tv4, tv3, e2);
9567
+ const e3 = Fp.eql(Fp.sqr(tv2), n);
9568
+ const root = Fp.cmov(tv1, tv2, e3);
9569
+ assertIsSquare(Fp, root, n);
9570
+ return root;
9571
+ };
9572
+ }
9573
+ function tonelliShanks(P) {
9574
+ if (P < _3n)
9575
+ throw new Error("sqrt is not defined for small field");
9576
+ let Q = P - _1n2;
9577
+ let S = 0;
9578
+ while (Q % _2n === _0n2) {
9579
+ Q /= _2n;
9580
+ S++;
9581
+ }
9582
+ let Z = _2n;
9583
+ const _Fp = Field(P);
9584
+ while (FpLegendre(_Fp, Z) === 1) {
9585
+ if (Z++ > 1e3)
9586
+ throw new Error("Cannot find square root: probably non-prime P");
9587
+ }
9588
+ if (S === 1)
9589
+ return sqrt3mod4;
9590
+ let cc = _Fp.pow(Z, Q);
9591
+ const Q1div2 = (Q + _1n2) / _2n;
9592
+ return function tonelliSlow(Fp, n) {
9593
+ if (Fp.is0(n))
9594
+ return n;
9595
+ if (FpLegendre(Fp, n) !== 1)
9596
+ throw new Error("Cannot find square root");
9597
+ let M = S;
9598
+ let c = Fp.mul(Fp.ONE, cc);
9599
+ let t = Fp.pow(n, Q);
9600
+ let R = Fp.pow(n, Q1div2);
9601
+ while (!Fp.eql(t, Fp.ONE)) {
9602
+ if (Fp.is0(t))
9603
+ return Fp.ZERO;
9604
+ let i = 1;
9605
+ let t_tmp = Fp.sqr(t);
9606
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
9607
+ i++;
9608
+ t_tmp = Fp.sqr(t_tmp);
9609
+ if (i === M)
9610
+ throw new Error("Cannot find square root");
9611
+ }
9612
+ const exponent = _1n2 << BigInt(M - i - 1);
9613
+ const b = Fp.pow(c, exponent);
9614
+ M = i;
9615
+ c = Fp.sqr(b);
9616
+ t = Fp.mul(t, c);
9617
+ R = Fp.mul(R, b);
9618
+ }
9619
+ return R;
9620
+ };
9621
+ }
9622
+ function FpSqrt(P) {
9623
+ if (P % _4n === _3n)
9624
+ return sqrt3mod4;
9625
+ if (P % _8n === _5n)
9626
+ return sqrt5mod8;
9627
+ if (P % _16n === _9n)
9628
+ return sqrt9mod16(P);
9629
+ return tonelliShanks(P);
9630
+ }
9631
+ var FIELD_FIELDS = [
9632
+ "create",
9633
+ "isValid",
9634
+ "is0",
9635
+ "neg",
9636
+ "inv",
9637
+ "sqrt",
9638
+ "sqr",
9639
+ "eql",
9640
+ "add",
9641
+ "sub",
9642
+ "mul",
9643
+ "pow",
9644
+ "div",
9645
+ "addN",
9646
+ "subN",
9647
+ "mulN",
9648
+ "sqrN"
9649
+ ];
9650
+ function validateField(field) {
9651
+ const initial = {
9652
+ ORDER: "bigint",
9653
+ BYTES: "number",
9654
+ BITS: "number"
9655
+ };
9656
+ const opts = FIELD_FIELDS.reduce((map, val) => {
9657
+ map[val] = "function";
9658
+ return map;
9659
+ }, initial);
9660
+ validateObject(field, opts);
9661
+ return field;
9662
+ }
9663
+ function FpPow(Fp, num, power) {
9664
+ if (power < _0n2)
9665
+ throw new Error("invalid exponent, negatives unsupported");
9666
+ if (power === _0n2)
9667
+ return Fp.ONE;
9668
+ if (power === _1n2)
9669
+ return num;
9670
+ let p = Fp.ONE;
9671
+ let d = num;
9672
+ while (power > _0n2) {
9673
+ if (power & _1n2)
9674
+ p = Fp.mul(p, d);
9675
+ d = Fp.sqr(d);
9676
+ power >>= _1n2;
9677
+ }
9678
+ return p;
9679
+ }
9680
+ function FpInvertBatch(Fp, nums, passZero = false) {
9681
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
9682
+ const multipliedAcc = nums.reduce((acc, num, i) => {
9683
+ if (Fp.is0(num))
9684
+ return acc;
9685
+ inverted[i] = acc;
9686
+ return Fp.mul(acc, num);
9687
+ }, Fp.ONE);
9688
+ const invertedAcc = Fp.inv(multipliedAcc);
9689
+ nums.reduceRight((acc, num, i) => {
9690
+ if (Fp.is0(num))
9691
+ return acc;
9692
+ inverted[i] = Fp.mul(acc, inverted[i]);
9693
+ return Fp.mul(acc, num);
9694
+ }, invertedAcc);
9695
+ return inverted;
9696
+ }
9697
+ function FpLegendre(Fp, n) {
9698
+ const p1mod2 = (Fp.ORDER - _1n2) / _2n;
9699
+ const powered = Fp.pow(n, p1mod2);
9700
+ const yes = Fp.eql(powered, Fp.ONE);
9701
+ const zero = Fp.eql(powered, Fp.ZERO);
9702
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
9703
+ if (!yes && !zero && !no)
9704
+ throw new Error("invalid Legendre symbol result");
9705
+ return yes ? 1 : zero ? 0 : -1;
9706
+ }
9707
+ function nLength(n, nBitLength) {
9708
+ if (nBitLength !== void 0)
9709
+ anumber(nBitLength);
9710
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
9711
+ const nByteLength = Math.ceil(_nBitLength / 8);
9712
+ return { nBitLength: _nBitLength, nByteLength };
9713
+ }
9714
+ var _Field = class {
9715
+ ORDER;
9716
+ BITS;
9717
+ BYTES;
9718
+ isLE;
9719
+ ZERO = _0n2;
9720
+ ONE = _1n2;
9721
+ _lengths;
9722
+ _sqrt;
9723
+ // cached sqrt
9724
+ _mod;
9725
+ constructor(ORDER, opts = {}) {
9726
+ if (ORDER <= _0n2)
9727
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
9728
+ let _nbitLength = void 0;
9729
+ this.isLE = false;
9730
+ if (opts != null && typeof opts === "object") {
9731
+ if (typeof opts.BITS === "number")
9732
+ _nbitLength = opts.BITS;
9733
+ if (typeof opts.sqrt === "function")
9734
+ this.sqrt = opts.sqrt;
9735
+ if (typeof opts.isLE === "boolean")
9736
+ this.isLE = opts.isLE;
9737
+ if (opts.allowedLengths)
9738
+ this._lengths = opts.allowedLengths?.slice();
9739
+ if (typeof opts.modFromBytes === "boolean")
9740
+ this._mod = opts.modFromBytes;
9741
+ }
9742
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
9743
+ if (nByteLength > 2048)
9744
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
9745
+ this.ORDER = ORDER;
9746
+ this.BITS = nBitLength;
9747
+ this.BYTES = nByteLength;
9748
+ this._sqrt = void 0;
9749
+ Object.preventExtensions(this);
9750
+ }
9751
+ create(num) {
9752
+ return mod(num, this.ORDER);
9753
+ }
9754
+ isValid(num) {
9755
+ if (typeof num !== "bigint")
9756
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
9757
+ return _0n2 <= num && num < this.ORDER;
9758
+ }
9759
+ is0(num) {
9760
+ return num === _0n2;
9761
+ }
9762
+ // is valid and invertible
9763
+ isValidNot0(num) {
9764
+ return !this.is0(num) && this.isValid(num);
9765
+ }
9766
+ isOdd(num) {
9767
+ return (num & _1n2) === _1n2;
9768
+ }
9769
+ neg(num) {
9770
+ return mod(-num, this.ORDER);
9771
+ }
9772
+ eql(lhs, rhs) {
9773
+ return lhs === rhs;
9774
+ }
9775
+ sqr(num) {
9776
+ return mod(num * num, this.ORDER);
9777
+ }
9778
+ add(lhs, rhs) {
9779
+ return mod(lhs + rhs, this.ORDER);
9780
+ }
9781
+ sub(lhs, rhs) {
9782
+ return mod(lhs - rhs, this.ORDER);
9783
+ }
9784
+ mul(lhs, rhs) {
9785
+ return mod(lhs * rhs, this.ORDER);
9786
+ }
9787
+ pow(num, power) {
9788
+ return FpPow(this, num, power);
9789
+ }
9790
+ div(lhs, rhs) {
9791
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
9792
+ }
9793
+ // Same as above, but doesn't normalize
9794
+ sqrN(num) {
9795
+ return num * num;
9796
+ }
9797
+ addN(lhs, rhs) {
9798
+ return lhs + rhs;
9799
+ }
9800
+ subN(lhs, rhs) {
9801
+ return lhs - rhs;
9802
+ }
9803
+ mulN(lhs, rhs) {
9804
+ return lhs * rhs;
9805
+ }
9806
+ inv(num) {
9807
+ return invert(num, this.ORDER);
9808
+ }
9809
+ sqrt(num) {
9810
+ if (!this._sqrt)
9811
+ this._sqrt = FpSqrt(this.ORDER);
9812
+ return this._sqrt(this, num);
9813
+ }
9814
+ toBytes(num) {
9815
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
9816
+ }
9817
+ fromBytes(bytes, skipValidation = false) {
9818
+ abytes(bytes);
9819
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
9820
+ if (allowedLengths) {
9821
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
9822
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
9823
+ }
9824
+ const padded = new Uint8Array(BYTES);
9825
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
9826
+ bytes = padded;
9827
+ }
9828
+ if (bytes.length !== BYTES)
9829
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
9830
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
9831
+ if (modFromBytes)
9832
+ scalar = mod(scalar, ORDER);
9833
+ if (!skipValidation) {
9834
+ if (!this.isValid(scalar))
9835
+ throw new Error("invalid field element: outside of range 0..ORDER");
9836
+ }
9837
+ return scalar;
9838
+ }
9839
+ // TODO: we don't need it here, move out to separate fn
9840
+ invertBatch(lst) {
9841
+ return FpInvertBatch(this, lst);
9842
+ }
9843
+ // We can't move this out because Fp6, Fp12 implement it
9844
+ // and it's unclear what to return in there.
9845
+ cmov(a, b, condition) {
9846
+ return condition ? b : a;
9847
+ }
9848
+ };
9849
+ function Field(ORDER, opts = {}) {
9850
+ return new _Field(ORDER, opts);
9851
+ }
9852
+ function getFieldBytesLength(fieldOrder) {
9853
+ if (typeof fieldOrder !== "bigint")
9854
+ throw new Error("field order must be bigint");
9855
+ const bitLength = fieldOrder.toString(2).length;
9856
+ return Math.ceil(bitLength / 8);
9857
+ }
9858
+ function getMinHashLength(fieldOrder) {
9859
+ const length = getFieldBytesLength(fieldOrder);
9860
+ return length + Math.ceil(length / 2);
9861
+ }
9862
+ function mapHashToField(key, fieldOrder, isLE = false) {
9863
+ abytes(key);
9864
+ const len = key.length;
9865
+ const fieldLen = getFieldBytesLength(fieldOrder);
9866
+ const minLen = getMinHashLength(fieldOrder);
9867
+ if (len < 16 || len < minLen || len > 1024)
9868
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
9869
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
9870
+ const reduced = mod(num, fieldOrder - _1n2) + _1n2;
9871
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
9872
+ }
9873
+
9874
+ // node_modules/@noble/curves/abstract/curve.js
9875
+ var _0n3 = /* @__PURE__ */ BigInt(0);
9876
+ var _1n3 = /* @__PURE__ */ BigInt(1);
9877
+ function negateCt(condition, item) {
9878
+ const neg = item.negate();
9879
+ return condition ? neg : item;
9880
+ }
9881
+ function normalizeZ(c, points) {
9882
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
9883
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
9884
+ }
9885
+ function validateW(W, bits) {
9886
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
9887
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
9888
+ }
9889
+ function calcWOpts(W, scalarBits) {
9890
+ validateW(W, scalarBits);
9891
+ const windows = Math.ceil(scalarBits / W) + 1;
9892
+ const windowSize = 2 ** (W - 1);
9893
+ const maxNumber = 2 ** W;
9894
+ const mask = bitMask(W);
9895
+ const shiftBy = BigInt(W);
9896
+ return { windows, windowSize, mask, maxNumber, shiftBy };
9897
+ }
9898
+ function calcOffsets(n, window, wOpts) {
9899
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
9900
+ let wbits = Number(n & mask);
9901
+ let nextN = n >> shiftBy;
9902
+ if (wbits > windowSize) {
9903
+ wbits -= maxNumber;
9904
+ nextN += _1n3;
9905
+ }
9906
+ const offsetStart = window * windowSize;
9907
+ const offset = offsetStart + Math.abs(wbits) - 1;
9908
+ const isZero = wbits === 0;
9909
+ const isNeg = wbits < 0;
9910
+ const isNegF = window % 2 !== 0;
9911
+ const offsetF = offsetStart;
9912
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
9913
+ }
9914
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
9915
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
9916
+ function getW(P) {
9917
+ return pointWindowSizes.get(P) || 1;
9918
+ }
9919
+ function assert0(n) {
9920
+ if (n !== _0n3)
9921
+ throw new Error("invalid wNAF");
9922
+ }
9923
+ var wNAF = class {
9924
+ BASE;
9925
+ ZERO;
9926
+ Fn;
9927
+ bits;
9928
+ // Parametrized with a given Point class (not individual point)
9929
+ constructor(Point, bits) {
9930
+ this.BASE = Point.BASE;
9931
+ this.ZERO = Point.ZERO;
9932
+ this.Fn = Point.Fn;
9933
+ this.bits = bits;
9934
+ }
9935
+ // non-const time multiplication ladder
9936
+ _unsafeLadder(elm, n, p = this.ZERO) {
9937
+ let d = elm;
9938
+ while (n > _0n3) {
9939
+ if (n & _1n3)
9940
+ p = p.add(d);
9941
+ d = d.double();
9942
+ n >>= _1n3;
9943
+ }
9944
+ return p;
9945
+ }
9946
+ /**
9947
+ * Creates a wNAF precomputation window. Used for caching.
9948
+ * Default window size is set by `utils.precompute()` and is equal to 8.
9949
+ * Number of precomputed points depends on the curve size:
9950
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
9951
+ * - 𝑊 is the window size
9952
+ * - 𝑛 is the bitlength of the curve order.
9953
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
9954
+ * @param point Point instance
9955
+ * @param W window size
9956
+ * @returns precomputed point tables flattened to a single array
9957
+ */
9958
+ precomputeWindow(point, W) {
9959
+ const { windows, windowSize } = calcWOpts(W, this.bits);
9960
+ const points = [];
9961
+ let p = point;
9962
+ let base = p;
9963
+ for (let window = 0; window < windows; window++) {
9964
+ base = p;
9965
+ points.push(base);
9966
+ for (let i = 1; i < windowSize; i++) {
9967
+ base = base.add(p);
9968
+ points.push(base);
9969
+ }
9970
+ p = base.double();
9971
+ }
9972
+ return points;
9973
+ }
9974
+ /**
9975
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
9976
+ * More compact implementation:
9977
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
9978
+ * @returns real and fake (for const-time) points
9979
+ */
9980
+ wNAF(W, precomputes, n) {
9981
+ if (!this.Fn.isValid(n))
9982
+ throw new Error("invalid scalar");
9983
+ let p = this.ZERO;
9984
+ let f = this.BASE;
9985
+ const wo = calcWOpts(W, this.bits);
9986
+ for (let window = 0; window < wo.windows; window++) {
9987
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
9988
+ n = nextN;
9989
+ if (isZero) {
9990
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
9991
+ } else {
9992
+ p = p.add(negateCt(isNeg, precomputes[offset]));
9993
+ }
9994
+ }
9995
+ assert0(n);
9996
+ return { p, f };
9997
+ }
9998
+ /**
9999
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
10000
+ * @param acc accumulator point to add result of multiplication
10001
+ * @returns point
10002
+ */
10003
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
10004
+ const wo = calcWOpts(W, this.bits);
10005
+ for (let window = 0; window < wo.windows; window++) {
10006
+ if (n === _0n3)
10007
+ break;
10008
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
10009
+ n = nextN;
10010
+ if (isZero) {
10011
+ continue;
10012
+ } else {
10013
+ const item = precomputes[offset];
10014
+ acc = acc.add(isNeg ? item.negate() : item);
10015
+ }
10016
+ }
10017
+ assert0(n);
10018
+ return acc;
10019
+ }
10020
+ getPrecomputes(W, point, transform) {
10021
+ let comp = pointPrecomputes.get(point);
10022
+ if (!comp) {
10023
+ comp = this.precomputeWindow(point, W);
10024
+ if (W !== 1) {
10025
+ if (typeof transform === "function")
10026
+ comp = transform(comp);
10027
+ pointPrecomputes.set(point, comp);
10028
+ }
10029
+ }
10030
+ return comp;
10031
+ }
10032
+ cached(point, scalar, transform) {
10033
+ const W = getW(point);
10034
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
10035
+ }
10036
+ unsafe(point, scalar, transform, prev) {
10037
+ const W = getW(point);
10038
+ if (W === 1)
10039
+ return this._unsafeLadder(point, scalar, prev);
10040
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
10041
+ }
10042
+ // We calculate precomputes for elliptic curve point multiplication
10043
+ // using windowed method. This specifies window size and
10044
+ // stores precomputed values. Usually only base point would be precomputed.
10045
+ createCache(P, W) {
10046
+ validateW(W, this.bits);
10047
+ pointWindowSizes.set(P, W);
10048
+ pointPrecomputes.delete(P);
10049
+ }
10050
+ hasCache(elm) {
10051
+ return getW(elm) !== 1;
10052
+ }
10053
+ };
10054
+ function mulEndoUnsafe(Point, point, k1, k2) {
10055
+ let acc = point;
10056
+ let p1 = Point.ZERO;
10057
+ let p2 = Point.ZERO;
10058
+ while (k1 > _0n3 || k2 > _0n3) {
10059
+ if (k1 & _1n3)
10060
+ p1 = p1.add(acc);
10061
+ if (k2 & _1n3)
10062
+ p2 = p2.add(acc);
10063
+ acc = acc.double();
10064
+ k1 >>= _1n3;
10065
+ k2 >>= _1n3;
10066
+ }
10067
+ return { p1, p2 };
10068
+ }
10069
+ function createField(order, field, isLE) {
10070
+ if (field) {
10071
+ if (field.ORDER !== order)
10072
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
10073
+ validateField(field);
10074
+ return field;
10075
+ } else {
10076
+ return Field(order, { isLE });
10077
+ }
10078
+ }
10079
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
10080
+ if (FpFnLE === void 0)
10081
+ FpFnLE = type === "edwards";
10082
+ if (!CURVE || typeof CURVE !== "object")
10083
+ throw new Error(`expected valid ${type} CURVE object`);
10084
+ for (const p of ["p", "n", "h"]) {
10085
+ const val = CURVE[p];
10086
+ if (!(typeof val === "bigint" && val > _0n3))
10087
+ throw new Error(`CURVE.${p} must be positive bigint`);
10088
+ }
10089
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
10090
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
10091
+ const _b = type === "weierstrass" ? "b" : "d";
10092
+ const params = ["Gx", "Gy", "a", _b];
10093
+ for (const p of params) {
10094
+ if (!Fp.isValid(CURVE[p]))
10095
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
10096
+ }
10097
+ CURVE = Object.freeze(Object.assign({}, CURVE));
10098
+ return { CURVE, Fp, Fn };
10099
+ }
10100
+ function createKeygen(randomSecretKey, getPublicKey2) {
10101
+ return function keygen(seed) {
10102
+ const secretKey = randomSecretKey(seed);
10103
+ return { secretKey, publicKey: getPublicKey2(secretKey) };
10104
+ };
10105
+ }
10106
+
10107
+ // node_modules/@noble/hashes/hmac.js
10108
+ var _HMAC = class {
10109
+ oHash;
10110
+ iHash;
10111
+ blockLen;
10112
+ outputLen;
10113
+ finished = false;
10114
+ destroyed = false;
10115
+ constructor(hash, key) {
10116
+ ahash(hash);
10117
+ abytes(key, void 0, "key");
10118
+ this.iHash = hash.create();
10119
+ if (typeof this.iHash.update !== "function")
10120
+ throw new Error("Expected instance of class which extends utils.Hash");
10121
+ this.blockLen = this.iHash.blockLen;
10122
+ this.outputLen = this.iHash.outputLen;
10123
+ const blockLen = this.blockLen;
10124
+ const pad = new Uint8Array(blockLen);
10125
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
10126
+ for (let i = 0; i < pad.length; i++)
10127
+ pad[i] ^= 54;
10128
+ this.iHash.update(pad);
10129
+ this.oHash = hash.create();
10130
+ for (let i = 0; i < pad.length; i++)
10131
+ pad[i] ^= 54 ^ 92;
10132
+ this.oHash.update(pad);
10133
+ clean(pad);
10134
+ }
10135
+ update(buf) {
10136
+ aexists(this);
10137
+ this.iHash.update(buf);
10138
+ return this;
10139
+ }
10140
+ digestInto(out) {
10141
+ aexists(this);
10142
+ abytes(out, this.outputLen, "output");
10143
+ this.finished = true;
10144
+ this.iHash.digestInto(out);
10145
+ this.oHash.update(out);
10146
+ this.oHash.digestInto(out);
10147
+ this.destroy();
10148
+ }
10149
+ digest() {
10150
+ const out = new Uint8Array(this.oHash.outputLen);
10151
+ this.digestInto(out);
10152
+ return out;
10153
+ }
10154
+ _cloneInto(to) {
10155
+ to ||= Object.create(Object.getPrototypeOf(this), {});
10156
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
10157
+ to = to;
10158
+ to.finished = finished;
10159
+ to.destroyed = destroyed;
10160
+ to.blockLen = blockLen;
10161
+ to.outputLen = outputLen;
10162
+ to.oHash = oHash._cloneInto(to.oHash);
10163
+ to.iHash = iHash._cloneInto(to.iHash);
10164
+ return to;
10165
+ }
10166
+ clone() {
10167
+ return this._cloneInto();
10168
+ }
10169
+ destroy() {
10170
+ this.destroyed = true;
10171
+ this.oHash.destroy();
10172
+ this.iHash.destroy();
10173
+ }
10174
+ };
10175
+ var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
10176
+ hmac.create = (hash, key) => new _HMAC(hash, key);
10177
+
10178
+ // node_modules/@noble/curves/abstract/weierstrass.js
10179
+ var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
10180
+ function _splitEndoScalar(k, basis, n) {
10181
+ const [[a1, b1], [a2, b2]] = basis;
10182
+ const c1 = divNearest(b2 * k, n);
10183
+ const c2 = divNearest(-b1 * k, n);
10184
+ let k1 = k - c1 * a1 - c2 * a2;
10185
+ let k2 = -c1 * b1 - c2 * b2;
10186
+ const k1neg = k1 < _0n4;
10187
+ const k2neg = k2 < _0n4;
10188
+ if (k1neg)
10189
+ k1 = -k1;
10190
+ if (k2neg)
10191
+ k2 = -k2;
10192
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
10193
+ if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
10194
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
10195
+ }
10196
+ return { k1neg, k1, k2neg, k2 };
10197
+ }
10198
+ function validateSigFormat(format) {
10199
+ if (!["compact", "recovered", "der"].includes(format))
10200
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
10201
+ return format;
10202
+ }
10203
+ function validateSigOpts(opts, def) {
10204
+ const optsn = {};
10205
+ for (let optName of Object.keys(def)) {
10206
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
10207
+ }
10208
+ abool(optsn.lowS, "lowS");
10209
+ abool(optsn.prehash, "prehash");
10210
+ if (optsn.format !== void 0)
10211
+ validateSigFormat(optsn.format);
10212
+ return optsn;
10213
+ }
10214
+ var DERErr = class extends Error {
10215
+ constructor(m = "") {
10216
+ super(m);
10217
+ }
10218
+ };
10219
+ var DER = {
10220
+ // asn.1 DER encoding utils
10221
+ Err: DERErr,
10222
+ // Basic building block is TLV (Tag-Length-Value)
10223
+ _tlv: {
10224
+ encode: (tag, data) => {
10225
+ const { Err: E } = DER;
10226
+ if (tag < 0 || tag > 256)
10227
+ throw new E("tlv.encode: wrong tag");
10228
+ if (data.length & 1)
10229
+ throw new E("tlv.encode: unpadded data");
10230
+ const dataLen = data.length / 2;
10231
+ const len = numberToHexUnpadded(dataLen);
10232
+ if (len.length / 2 & 128)
10233
+ throw new E("tlv.encode: long form length too big");
10234
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
10235
+ const t = numberToHexUnpadded(tag);
10236
+ return t + lenLen + len + data;
10237
+ },
10238
+ // v - value, l - left bytes (unparsed)
10239
+ decode(tag, data) {
10240
+ const { Err: E } = DER;
10241
+ let pos = 0;
10242
+ if (tag < 0 || tag > 256)
10243
+ throw new E("tlv.encode: wrong tag");
10244
+ if (data.length < 2 || data[pos++] !== tag)
10245
+ throw new E("tlv.decode: wrong tlv");
10246
+ const first = data[pos++];
10247
+ const isLong = !!(first & 128);
10248
+ let length = 0;
10249
+ if (!isLong)
10250
+ length = first;
10251
+ else {
10252
+ const lenLen = first & 127;
10253
+ if (!lenLen)
10254
+ throw new E("tlv.decode(long): indefinite length not supported");
10255
+ if (lenLen > 4)
10256
+ throw new E("tlv.decode(long): byte length is too big");
10257
+ const lengthBytes = data.subarray(pos, pos + lenLen);
10258
+ if (lengthBytes.length !== lenLen)
10259
+ throw new E("tlv.decode: length bytes not complete");
10260
+ if (lengthBytes[0] === 0)
10261
+ throw new E("tlv.decode(long): zero leftmost byte");
10262
+ for (const b of lengthBytes)
10263
+ length = length << 8 | b;
10264
+ pos += lenLen;
10265
+ if (length < 128)
10266
+ throw new E("tlv.decode(long): not minimal encoding");
10267
+ }
10268
+ const v = data.subarray(pos, pos + length);
10269
+ if (v.length !== length)
10270
+ throw new E("tlv.decode: wrong value length");
10271
+ return { v, l: data.subarray(pos + length) };
10272
+ }
10273
+ },
10274
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
10275
+ // since we always use positive integers here. It must always be empty:
10276
+ // - add zero byte if exists
10277
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
10278
+ _int: {
10279
+ encode(num) {
10280
+ const { Err: E } = DER;
10281
+ if (num < _0n4)
10282
+ throw new E("integer: negative integers are not allowed");
10283
+ let hex = numberToHexUnpadded(num);
10284
+ if (Number.parseInt(hex[0], 16) & 8)
10285
+ hex = "00" + hex;
10286
+ if (hex.length & 1)
10287
+ throw new E("unexpected DER parsing assertion: unpadded hex");
10288
+ return hex;
10289
+ },
10290
+ decode(data) {
10291
+ const { Err: E } = DER;
10292
+ if (data[0] & 128)
10293
+ throw new E("invalid signature integer: negative");
10294
+ if (data[0] === 0 && !(data[1] & 128))
10295
+ throw new E("invalid signature integer: unnecessary leading zero");
10296
+ return bytesToNumberBE(data);
10297
+ }
10298
+ },
10299
+ toSig(bytes) {
10300
+ const { Err: E, _int: int, _tlv: tlv } = DER;
10301
+ const data = abytes(bytes, void 0, "signature");
10302
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
10303
+ if (seqLeftBytes.length)
10304
+ throw new E("invalid signature: left bytes after parsing");
10305
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
10306
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
10307
+ if (sLeftBytes.length)
10308
+ throw new E("invalid signature: left bytes after parsing");
10309
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
10310
+ },
10311
+ hexFromSig(sig) {
10312
+ const { _tlv: tlv, _int: int } = DER;
10313
+ const rs = tlv.encode(2, int.encode(sig.r));
10314
+ const ss = tlv.encode(2, int.encode(sig.s));
10315
+ const seq = rs + ss;
10316
+ return tlv.encode(48, seq);
10317
+ }
10318
+ };
10319
+ var _0n4 = BigInt(0);
10320
+ var _1n4 = BigInt(1);
10321
+ var _2n2 = BigInt(2);
10322
+ var _3n2 = BigInt(3);
10323
+ var _4n2 = BigInt(4);
10324
+ function weierstrass(params, extraOpts = {}) {
10325
+ const validated = createCurveFields("weierstrass", params, extraOpts);
10326
+ const { Fp, Fn } = validated;
10327
+ let CURVE = validated.CURVE;
10328
+ const { h: cofactor, n: CURVE_ORDER2 } = CURVE;
10329
+ validateObject(extraOpts, {}, {
10330
+ allowInfinityPoint: "boolean",
10331
+ clearCofactor: "function",
10332
+ isTorsionFree: "function",
10333
+ fromBytes: "function",
10334
+ toBytes: "function",
10335
+ endo: "object"
10336
+ });
10337
+ const { endo } = extraOpts;
10338
+ if (endo) {
10339
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
10340
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
10341
+ }
10342
+ }
10343
+ const lengths = getWLengths(Fp, Fn);
10344
+ function assertCompressionIsSupported() {
10345
+ if (!Fp.isOdd)
10346
+ throw new Error("compression is not supported: Field does not have .isOdd()");
10347
+ }
10348
+ function pointToBytes(_c, point, isCompressed) {
10349
+ const { x, y } = point.toAffine();
10350
+ const bx = Fp.toBytes(x);
10351
+ abool(isCompressed, "isCompressed");
10352
+ if (isCompressed) {
10353
+ assertCompressionIsSupported();
10354
+ const hasEvenY = !Fp.isOdd(y);
10355
+ return concatBytes(pprefix(hasEvenY), bx);
10356
+ } else {
10357
+ return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
10358
+ }
10359
+ }
10360
+ function pointFromBytes(bytes) {
10361
+ abytes(bytes, void 0, "Point");
10362
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
10363
+ const length = bytes.length;
10364
+ const head = bytes[0];
10365
+ const tail = bytes.subarray(1);
10366
+ if (length === comp && (head === 2 || head === 3)) {
10367
+ const x = Fp.fromBytes(tail);
10368
+ if (!Fp.isValid(x))
10369
+ throw new Error("bad point: is not on curve, wrong x");
10370
+ const y2 = weierstrassEquation(x);
10371
+ let y;
10372
+ try {
10373
+ y = Fp.sqrt(y2);
10374
+ } catch (sqrtError) {
10375
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
10376
+ throw new Error("bad point: is not on curve, sqrt error" + err);
10377
+ }
10378
+ assertCompressionIsSupported();
10379
+ const evenY = Fp.isOdd(y);
10380
+ const evenH = (head & 1) === 1;
10381
+ if (evenH !== evenY)
10382
+ y = Fp.neg(y);
10383
+ return { x, y };
10384
+ } else if (length === uncomp && head === 4) {
10385
+ const L = Fp.BYTES;
10386
+ const x = Fp.fromBytes(tail.subarray(0, L));
10387
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
10388
+ if (!isValidXY(x, y))
10389
+ throw new Error("bad point: is not on curve");
10390
+ return { x, y };
10391
+ } else {
10392
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
10393
+ }
10394
+ }
10395
+ const encodePoint = extraOpts.toBytes || pointToBytes;
10396
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
10397
+ function weierstrassEquation(x) {
10398
+ const x2 = Fp.sqr(x);
10399
+ const x3 = Fp.mul(x2, x);
10400
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
10401
+ }
10402
+ function isValidXY(x, y) {
10403
+ const left = Fp.sqr(y);
10404
+ const right = weierstrassEquation(x);
10405
+ return Fp.eql(left, right);
10406
+ }
10407
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
10408
+ throw new Error("bad curve params: generator point");
10409
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
10410
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
10411
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
10412
+ throw new Error("bad curve params: a or b");
10413
+ function acoord(title, n, banZero = false) {
10414
+ if (!Fp.isValid(n) || banZero && Fp.is0(n))
10415
+ throw new Error(`bad point coordinate ${title}`);
10416
+ return n;
10417
+ }
10418
+ function aprjpoint(other) {
10419
+ if (!(other instanceof Point))
10420
+ throw new Error("Weierstrass Point expected");
10421
+ }
10422
+ function splitEndoScalarN(k) {
10423
+ if (!endo || !endo.basises)
10424
+ throw new Error("no endo");
10425
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
10426
+ }
10427
+ const toAffineMemo = memoized((p, iz) => {
10428
+ const { X, Y, Z } = p;
10429
+ if (Fp.eql(Z, Fp.ONE))
10430
+ return { x: X, y: Y };
10431
+ const is0 = p.is0();
10432
+ if (iz == null)
10433
+ iz = is0 ? Fp.ONE : Fp.inv(Z);
10434
+ const x = Fp.mul(X, iz);
10435
+ const y = Fp.mul(Y, iz);
10436
+ const zz = Fp.mul(Z, iz);
10437
+ if (is0)
10438
+ return { x: Fp.ZERO, y: Fp.ZERO };
10439
+ if (!Fp.eql(zz, Fp.ONE))
10440
+ throw new Error("invZ was invalid");
10441
+ return { x, y };
10442
+ });
10443
+ const assertValidMemo = memoized((p) => {
10444
+ if (p.is0()) {
10445
+ if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
10446
+ return;
10447
+ throw new Error("bad point: ZERO");
10448
+ }
10449
+ const { x, y } = p.toAffine();
10450
+ if (!Fp.isValid(x) || !Fp.isValid(y))
10451
+ throw new Error("bad point: x or y not field elements");
10452
+ if (!isValidXY(x, y))
10453
+ throw new Error("bad point: equation left != right");
10454
+ if (!p.isTorsionFree())
10455
+ throw new Error("bad point: not in prime-order subgroup");
10456
+ return true;
10457
+ });
10458
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
10459
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
10460
+ k1p = negateCt(k1neg, k1p);
10461
+ k2p = negateCt(k2neg, k2p);
10462
+ return k1p.add(k2p);
10463
+ }
10464
+ class Point {
10465
+ // base / generator point
10466
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
10467
+ // zero / infinity / identity point
10468
+ static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
10469
+ // 0, 1, 0
10470
+ // math field
10471
+ static Fp = Fp;
10472
+ // scalar field
10473
+ static Fn = Fn;
10474
+ X;
10475
+ Y;
10476
+ Z;
10477
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
10478
+ constructor(X, Y, Z) {
10479
+ this.X = acoord("x", X);
10480
+ this.Y = acoord("y", Y, true);
10481
+ this.Z = acoord("z", Z);
10482
+ Object.freeze(this);
10483
+ }
10484
+ static CURVE() {
10485
+ return CURVE;
10486
+ }
10487
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
10488
+ static fromAffine(p) {
10489
+ const { x, y } = p || {};
10490
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
10491
+ throw new Error("invalid affine point");
10492
+ if (p instanceof Point)
10493
+ throw new Error("projective point not allowed");
10494
+ if (Fp.is0(x) && Fp.is0(y))
10495
+ return Point.ZERO;
10496
+ return new Point(x, y, Fp.ONE);
10497
+ }
10498
+ static fromBytes(bytes) {
10499
+ const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
10500
+ P.assertValidity();
10501
+ return P;
10502
+ }
10503
+ static fromHex(hex) {
10504
+ return Point.fromBytes(hexToBytes2(hex));
10505
+ }
10506
+ get x() {
10507
+ return this.toAffine().x;
10508
+ }
10509
+ get y() {
10510
+ return this.toAffine().y;
10511
+ }
10512
+ /**
10513
+ *
10514
+ * @param windowSize
10515
+ * @param isLazy true will defer table computation until the first multiplication
10516
+ * @returns
10517
+ */
10518
+ precompute(windowSize = 8, isLazy = true) {
10519
+ wnaf.createCache(this, windowSize);
10520
+ if (!isLazy)
10521
+ this.multiply(_3n2);
10522
+ return this;
10523
+ }
10524
+ // TODO: return `this`
10525
+ /** A point on curve is valid if it conforms to equation. */
10526
+ assertValidity() {
10527
+ assertValidMemo(this);
10528
+ }
10529
+ hasEvenY() {
10530
+ const { y } = this.toAffine();
10531
+ if (!Fp.isOdd)
10532
+ throw new Error("Field doesn't support isOdd");
10533
+ return !Fp.isOdd(y);
10534
+ }
10535
+ /** Compare one point to another. */
10536
+ equals(other) {
10537
+ aprjpoint(other);
10538
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10539
+ const { X: X2, Y: Y2, Z: Z2 } = other;
10540
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
10541
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
10542
+ return U1 && U2;
10543
+ }
10544
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
10545
+ negate() {
10546
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
10547
+ }
10548
+ // Renes-Costello-Batina exception-free doubling formula.
10549
+ // There is 30% faster Jacobian formula, but it is not complete.
10550
+ // https://eprint.iacr.org/2015/1060, algorithm 3
10551
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
10552
+ double() {
10553
+ const { a, b } = CURVE;
10554
+ const b3 = Fp.mul(b, _3n2);
10555
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10556
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
10557
+ let t0 = Fp.mul(X1, X1);
10558
+ let t1 = Fp.mul(Y1, Y1);
10559
+ let t2 = Fp.mul(Z1, Z1);
10560
+ let t3 = Fp.mul(X1, Y1);
10561
+ t3 = Fp.add(t3, t3);
10562
+ Z3 = Fp.mul(X1, Z1);
10563
+ Z3 = Fp.add(Z3, Z3);
10564
+ X3 = Fp.mul(a, Z3);
10565
+ Y3 = Fp.mul(b3, t2);
10566
+ Y3 = Fp.add(X3, Y3);
10567
+ X3 = Fp.sub(t1, Y3);
10568
+ Y3 = Fp.add(t1, Y3);
10569
+ Y3 = Fp.mul(X3, Y3);
10570
+ X3 = Fp.mul(t3, X3);
10571
+ Z3 = Fp.mul(b3, Z3);
10572
+ t2 = Fp.mul(a, t2);
10573
+ t3 = Fp.sub(t0, t2);
10574
+ t3 = Fp.mul(a, t3);
10575
+ t3 = Fp.add(t3, Z3);
10576
+ Z3 = Fp.add(t0, t0);
10577
+ t0 = Fp.add(Z3, t0);
10578
+ t0 = Fp.add(t0, t2);
10579
+ t0 = Fp.mul(t0, t3);
10580
+ Y3 = Fp.add(Y3, t0);
10581
+ t2 = Fp.mul(Y1, Z1);
10582
+ t2 = Fp.add(t2, t2);
10583
+ t0 = Fp.mul(t2, t3);
10584
+ X3 = Fp.sub(X3, t0);
10585
+ Z3 = Fp.mul(t2, t1);
10586
+ Z3 = Fp.add(Z3, Z3);
10587
+ Z3 = Fp.add(Z3, Z3);
10588
+ return new Point(X3, Y3, Z3);
10589
+ }
10590
+ // Renes-Costello-Batina exception-free addition formula.
10591
+ // There is 30% faster Jacobian formula, but it is not complete.
10592
+ // https://eprint.iacr.org/2015/1060, algorithm 1
10593
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
10594
+ add(other) {
10595
+ aprjpoint(other);
10596
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10597
+ const { X: X2, Y: Y2, Z: Z2 } = other;
10598
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
10599
+ const a = CURVE.a;
10600
+ const b3 = Fp.mul(CURVE.b, _3n2);
10601
+ let t0 = Fp.mul(X1, X2);
10602
+ let t1 = Fp.mul(Y1, Y2);
10603
+ let t2 = Fp.mul(Z1, Z2);
10604
+ let t3 = Fp.add(X1, Y1);
10605
+ let t4 = Fp.add(X2, Y2);
10606
+ t3 = Fp.mul(t3, t4);
10607
+ t4 = Fp.add(t0, t1);
10608
+ t3 = Fp.sub(t3, t4);
10609
+ t4 = Fp.add(X1, Z1);
10610
+ let t5 = Fp.add(X2, Z2);
10611
+ t4 = Fp.mul(t4, t5);
10612
+ t5 = Fp.add(t0, t2);
10613
+ t4 = Fp.sub(t4, t5);
10614
+ t5 = Fp.add(Y1, Z1);
10615
+ X3 = Fp.add(Y2, Z2);
10616
+ t5 = Fp.mul(t5, X3);
10617
+ X3 = Fp.add(t1, t2);
10618
+ t5 = Fp.sub(t5, X3);
10619
+ Z3 = Fp.mul(a, t4);
10620
+ X3 = Fp.mul(b3, t2);
10621
+ Z3 = Fp.add(X3, Z3);
10622
+ X3 = Fp.sub(t1, Z3);
10623
+ Z3 = Fp.add(t1, Z3);
10624
+ Y3 = Fp.mul(X3, Z3);
10625
+ t1 = Fp.add(t0, t0);
10626
+ t1 = Fp.add(t1, t0);
10627
+ t2 = Fp.mul(a, t2);
10628
+ t4 = Fp.mul(b3, t4);
10629
+ t1 = Fp.add(t1, t2);
10630
+ t2 = Fp.sub(t0, t2);
10631
+ t2 = Fp.mul(a, t2);
10632
+ t4 = Fp.add(t4, t2);
10633
+ t0 = Fp.mul(t1, t4);
10634
+ Y3 = Fp.add(Y3, t0);
10635
+ t0 = Fp.mul(t5, t4);
10636
+ X3 = Fp.mul(t3, X3);
10637
+ X3 = Fp.sub(X3, t0);
10638
+ t0 = Fp.mul(t3, t1);
10639
+ Z3 = Fp.mul(t5, Z3);
10640
+ Z3 = Fp.add(Z3, t0);
10641
+ return new Point(X3, Y3, Z3);
10642
+ }
10643
+ subtract(other) {
10644
+ return this.add(other.negate());
10645
+ }
10646
+ is0() {
10647
+ return this.equals(Point.ZERO);
10648
+ }
10649
+ /**
10650
+ * Constant time multiplication.
10651
+ * Uses wNAF method. Windowed method may be 10% faster,
10652
+ * but takes 2x longer to generate and consumes 2x memory.
10653
+ * Uses precomputes when available.
10654
+ * Uses endomorphism for Koblitz curves.
10655
+ * @param scalar by which the point would be multiplied
10656
+ * @returns New point
10657
+ */
10658
+ multiply(scalar) {
10659
+ const { endo: endo2 } = extraOpts;
10660
+ if (!Fn.isValidNot0(scalar))
10661
+ throw new Error("invalid scalar: out of range");
10662
+ let point, fake;
10663
+ const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
10664
+ if (endo2) {
10665
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
10666
+ const { p: k1p, f: k1f } = mul(k1);
10667
+ const { p: k2p, f: k2f } = mul(k2);
10668
+ fake = k1f.add(k2f);
10669
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
10670
+ } else {
10671
+ const { p, f } = mul(scalar);
10672
+ point = p;
10673
+ fake = f;
10674
+ }
10675
+ return normalizeZ(Point, [point, fake])[0];
10676
+ }
10677
+ /**
10678
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
10679
+ * It's faster, but should only be used when you don't care about
10680
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
10681
+ */
10682
+ multiplyUnsafe(sc) {
10683
+ const { endo: endo2 } = extraOpts;
10684
+ const p = this;
10685
+ if (!Fn.isValid(sc))
10686
+ throw new Error("invalid scalar: out of range");
10687
+ if (sc === _0n4 || p.is0())
10688
+ return Point.ZERO;
10689
+ if (sc === _1n4)
10690
+ return p;
10691
+ if (wnaf.hasCache(this))
10692
+ return this.multiply(sc);
10693
+ if (endo2) {
10694
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
10695
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
10696
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
10697
+ } else {
10698
+ return wnaf.unsafe(p, sc);
10699
+ }
10700
+ }
10701
+ /**
10702
+ * Converts Projective point to affine (x, y) coordinates.
10703
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
10704
+ */
10705
+ toAffine(invertedZ) {
10706
+ return toAffineMemo(this, invertedZ);
10707
+ }
10708
+ /**
10709
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
10710
+ * Always torsion-free for cofactor=1 curves.
10711
+ */
10712
+ isTorsionFree() {
10713
+ const { isTorsionFree } = extraOpts;
10714
+ if (cofactor === _1n4)
10715
+ return true;
10716
+ if (isTorsionFree)
10717
+ return isTorsionFree(Point, this);
10718
+ return wnaf.unsafe(this, CURVE_ORDER2).is0();
10719
+ }
10720
+ clearCofactor() {
10721
+ const { clearCofactor } = extraOpts;
10722
+ if (cofactor === _1n4)
10723
+ return this;
10724
+ if (clearCofactor)
10725
+ return clearCofactor(Point, this);
10726
+ return this.multiplyUnsafe(cofactor);
10727
+ }
10728
+ isSmallOrder() {
10729
+ return this.multiplyUnsafe(cofactor).is0();
10730
+ }
10731
+ toBytes(isCompressed = true) {
10732
+ abool(isCompressed, "isCompressed");
10733
+ this.assertValidity();
10734
+ return encodePoint(Point, this, isCompressed);
10735
+ }
10736
+ toHex(isCompressed = true) {
10737
+ return bytesToHex4(this.toBytes(isCompressed));
10738
+ }
10739
+ toString() {
10740
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
10741
+ }
10742
+ }
10743
+ const bits = Fn.BITS;
10744
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
10745
+ Point.BASE.precompute(8);
10746
+ return Point;
10747
+ }
10748
+ function pprefix(hasEvenY) {
10749
+ return Uint8Array.of(hasEvenY ? 2 : 3);
10750
+ }
10751
+ function getWLengths(Fp, Fn) {
10752
+ return {
10753
+ secretKey: Fn.BYTES,
10754
+ publicKey: 1 + Fp.BYTES,
10755
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
10756
+ publicKeyHasPrefix: true,
10757
+ signature: 2 * Fn.BYTES
10758
+ };
10759
+ }
10760
+ function ecdh(Point, ecdhOpts = {}) {
10761
+ const { Fn } = Point;
10762
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
10763
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
10764
+ function isValidSecretKey(secretKey) {
10765
+ try {
10766
+ const num = Fn.fromBytes(secretKey);
10767
+ return Fn.isValidNot0(num);
10768
+ } catch (error) {
10769
+ return false;
10770
+ }
10771
+ }
10772
+ function isValidPublicKey(publicKey, isCompressed) {
10773
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
10774
+ try {
10775
+ const l = publicKey.length;
10776
+ if (isCompressed === true && l !== comp)
10777
+ return false;
10778
+ if (isCompressed === false && l !== publicKeyUncompressed)
10779
+ return false;
10780
+ return !!Point.fromBytes(publicKey);
10781
+ } catch (error) {
10782
+ return false;
10783
+ }
10784
+ }
10785
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
10786
+ return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
10787
+ }
10788
+ function getPublicKey2(secretKey, isCompressed = true) {
10789
+ return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
10790
+ }
10791
+ function isProbPub(item) {
10792
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
10793
+ if (!isBytes(item))
10794
+ return void 0;
10795
+ if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
10796
+ return void 0;
10797
+ const l = abytes(item, void 0, "key").length;
10798
+ return l === publicKey || l === publicKeyUncompressed;
10799
+ }
10800
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
10801
+ if (isProbPub(secretKeyA) === true)
10802
+ throw new Error("first arg must be private key");
10803
+ if (isProbPub(publicKeyB) === false)
10804
+ throw new Error("second arg must be public key");
10805
+ const s = Fn.fromBytes(secretKeyA);
10806
+ const b = Point.fromBytes(publicKeyB);
10807
+ return b.multiply(s).toBytes(isCompressed);
10808
+ }
10809
+ const utils = {
10810
+ isValidSecretKey,
10811
+ isValidPublicKey,
10812
+ randomSecretKey
10813
+ };
10814
+ const keygen = createKeygen(randomSecretKey, getPublicKey2);
10815
+ return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
10816
+ }
10817
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
10818
+ ahash(hash);
10819
+ validateObject(ecdsaOpts, {}, {
10820
+ hmac: "function",
10821
+ lowS: "boolean",
10822
+ randomBytes: "function",
10823
+ bits2int: "function",
10824
+ bits2int_modN: "function"
10825
+ });
10826
+ ecdsaOpts = Object.assign({}, ecdsaOpts);
10827
+ const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
10828
+ const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
10829
+ const { Fp, Fn } = Point;
10830
+ const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn;
10831
+ const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
10832
+ const defaultSigOpts = {
10833
+ prehash: true,
10834
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
10835
+ format: "compact",
10836
+ extraEntropy: false
10837
+ };
10838
+ const hasLargeCofactor = CURVE_ORDER2 * _2n2 < Fp.ORDER;
10839
+ function isBiggerThanHalfOrder(number) {
10840
+ const HALF = CURVE_ORDER2 >> _1n4;
10841
+ return number > HALF;
10842
+ }
10843
+ function validateRS(title, num) {
10844
+ if (!Fn.isValidNot0(num))
10845
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
10846
+ return num;
10847
+ }
10848
+ function assertSmallCofactor() {
10849
+ if (hasLargeCofactor)
10850
+ throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
10851
+ }
10852
+ function validateSigLength(bytes, format) {
10853
+ validateSigFormat(format);
10854
+ const size = lengths.signature;
10855
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
10856
+ return abytes(bytes, sizer);
10857
+ }
10858
+ class Signature {
10859
+ r;
10860
+ s;
10861
+ recovery;
10862
+ constructor(r, s, recovery) {
10863
+ this.r = validateRS("r", r);
10864
+ this.s = validateRS("s", s);
10865
+ if (recovery != null) {
10866
+ assertSmallCofactor();
10867
+ if (![0, 1, 2, 3].includes(recovery))
10868
+ throw new Error("invalid recovery id");
10869
+ this.recovery = recovery;
10870
+ }
10871
+ Object.freeze(this);
10872
+ }
10873
+ static fromBytes(bytes, format = defaultSigOpts.format) {
10874
+ validateSigLength(bytes, format);
10875
+ let recid;
10876
+ if (format === "der") {
10877
+ const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
10878
+ return new Signature(r2, s2);
10879
+ }
10880
+ if (format === "recovered") {
10881
+ recid = bytes[0];
10882
+ format = "compact";
10883
+ bytes = bytes.subarray(1);
10884
+ }
10885
+ const L = lengths.signature / 2;
10886
+ const r = bytes.subarray(0, L);
10887
+ const s = bytes.subarray(L, L * 2);
10888
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
10889
+ }
10890
+ static fromHex(hex, format) {
10891
+ return this.fromBytes(hexToBytes2(hex), format);
10892
+ }
10893
+ assertRecovery() {
10894
+ const { recovery } = this;
10895
+ if (recovery == null)
10896
+ throw new Error("invalid recovery id: must be present");
10897
+ return recovery;
10898
+ }
10899
+ addRecoveryBit(recovery) {
10900
+ return new Signature(this.r, this.s, recovery);
10901
+ }
10902
+ recoverPublicKey(messageHash) {
10903
+ const { r, s } = this;
10904
+ const recovery = this.assertRecovery();
10905
+ const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER2 : r;
10906
+ if (!Fp.isValid(radj))
10907
+ throw new Error("invalid recovery id: sig.r+curve.n != R.x");
10908
+ const x = Fp.toBytes(radj);
10909
+ const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
10910
+ const ir = Fn.inv(radj);
10911
+ const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
10912
+ const u1 = Fn.create(-h * ir);
10913
+ const u2 = Fn.create(s * ir);
10914
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
10915
+ if (Q.is0())
10916
+ throw new Error("invalid recovery: point at infinify");
10917
+ Q.assertValidity();
10918
+ return Q;
10919
+ }
10920
+ // Signatures should be low-s, to prevent malleability.
10921
+ hasHighS() {
10922
+ return isBiggerThanHalfOrder(this.s);
10923
+ }
10924
+ toBytes(format = defaultSigOpts.format) {
10925
+ validateSigFormat(format);
10926
+ if (format === "der")
10927
+ return hexToBytes2(DER.hexFromSig(this));
10928
+ const { r, s } = this;
10929
+ const rb = Fn.toBytes(r);
10930
+ const sb = Fn.toBytes(s);
10931
+ if (format === "recovered") {
10932
+ assertSmallCofactor();
10933
+ return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
10934
+ }
10935
+ return concatBytes(rb, sb);
10936
+ }
10937
+ toHex(format) {
10938
+ return bytesToHex4(this.toBytes(format));
10939
+ }
10940
+ }
10941
+ const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
10942
+ if (bytes.length > 8192)
10943
+ throw new Error("input is too large");
10944
+ const num = bytesToNumberBE(bytes);
10945
+ const delta = bytes.length * 8 - fnBits;
10946
+ return delta > 0 ? num >> BigInt(delta) : num;
10947
+ };
10948
+ const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
10949
+ return Fn.create(bits2int(bytes));
10950
+ };
10951
+ const ORDER_MASK = bitMask(fnBits);
10952
+ function int2octets(num) {
10953
+ aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
10954
+ return Fn.toBytes(num);
10955
+ }
10956
+ function validateMsgAndHash(message, prehash) {
10957
+ abytes(message, void 0, "message");
10958
+ return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
10959
+ }
10960
+ function prepSig(message, secretKey, opts) {
10961
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
10962
+ message = validateMsgAndHash(message, prehash);
10963
+ const h1int = bits2int_modN(message);
10964
+ const d = Fn.fromBytes(secretKey);
10965
+ if (!Fn.isValidNot0(d))
10966
+ throw new Error("invalid private key");
10967
+ const seedArgs = [int2octets(d), int2octets(h1int)];
10968
+ if (extraEntropy != null && extraEntropy !== false) {
10969
+ const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
10970
+ seedArgs.push(abytes(e, void 0, "extraEntropy"));
10971
+ }
10972
+ const seed = concatBytes(...seedArgs);
10973
+ const m = h1int;
10974
+ function k2sig(kBytes) {
10975
+ const k = bits2int(kBytes);
10976
+ if (!Fn.isValidNot0(k))
10977
+ return;
10978
+ const ik = Fn.inv(k);
10979
+ const q = Point.BASE.multiply(k).toAffine();
10980
+ const r = Fn.create(q.x);
10981
+ if (r === _0n4)
10982
+ return;
10983
+ const s = Fn.create(ik * Fn.create(m + r * d));
10984
+ if (s === _0n4)
10985
+ return;
10986
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
10987
+ let normS = s;
10988
+ if (lowS && isBiggerThanHalfOrder(s)) {
10989
+ normS = Fn.neg(s);
10990
+ recovery ^= 1;
10991
+ }
10992
+ return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
10993
+ }
10994
+ return { seed, k2sig };
10995
+ }
10996
+ function sign(message, secretKey, opts = {}) {
10997
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
10998
+ const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
10999
+ const sig = drbg(seed, k2sig);
11000
+ return sig.toBytes(opts.format);
11001
+ }
11002
+ function verify(signature, message, publicKey, opts = {}) {
11003
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
11004
+ publicKey = abytes(publicKey, void 0, "publicKey");
11005
+ message = validateMsgAndHash(message, prehash);
11006
+ if (!isBytes(signature)) {
11007
+ const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
11008
+ throw new Error("verify expects Uint8Array signature" + end);
11009
+ }
11010
+ validateSigLength(signature, format);
11011
+ try {
11012
+ const sig = Signature.fromBytes(signature, format);
11013
+ const P = Point.fromBytes(publicKey);
11014
+ if (lowS && sig.hasHighS())
11015
+ return false;
11016
+ const { r, s } = sig;
11017
+ const h = bits2int_modN(message);
11018
+ const is = Fn.inv(s);
11019
+ const u1 = Fn.create(h * is);
11020
+ const u2 = Fn.create(r * is);
11021
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
11022
+ if (R.is0())
11023
+ return false;
11024
+ const v = Fn.create(R.x);
11025
+ return v === r;
11026
+ } catch (e) {
11027
+ return false;
11028
+ }
11029
+ }
11030
+ function recoverPublicKey(signature, message, opts = {}) {
11031
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
11032
+ message = validateMsgAndHash(message, prehash);
11033
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
11034
+ }
11035
+ return Object.freeze({
11036
+ keygen,
11037
+ getPublicKey: getPublicKey2,
11038
+ getSharedSecret,
11039
+ utils,
11040
+ lengths,
11041
+ Point,
11042
+ sign,
11043
+ verify,
11044
+ recoverPublicKey,
11045
+ Signature,
11046
+ hash
11047
+ });
11048
+ }
11049
+
11050
+ // node_modules/@noble/curves/secp256k1.js
11051
+ var secp256k1_CURVE = {
11052
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
11053
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
11054
+ h: BigInt(1),
11055
+ a: BigInt(0),
11056
+ b: BigInt(7),
11057
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
11058
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
11059
+ };
11060
+ var secp256k1_ENDO = {
11061
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
11062
+ basises: [
11063
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
11064
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
11065
+ ]
11066
+ };
11067
+ var _2n3 = /* @__PURE__ */ BigInt(2);
11068
+ function sqrtMod(y) {
11069
+ const P = secp256k1_CURVE.p;
11070
+ const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
11071
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
11072
+ const b2 = y * y * y % P;
11073
+ const b3 = b2 * b2 * y % P;
11074
+ const b6 = pow2(b3, _3n3, P) * b3 % P;
11075
+ const b9 = pow2(b6, _3n3, P) * b3 % P;
11076
+ const b11 = pow2(b9, _2n3, P) * b2 % P;
11077
+ const b22 = pow2(b11, _11n, P) * b11 % P;
11078
+ const b44 = pow2(b22, _22n, P) * b22 % P;
11079
+ const b88 = pow2(b44, _44n, P) * b44 % P;
11080
+ const b176 = pow2(b88, _88n, P) * b88 % P;
11081
+ const b220 = pow2(b176, _44n, P) * b44 % P;
11082
+ const b223 = pow2(b220, _3n3, P) * b3 % P;
11083
+ const t1 = pow2(b223, _23n, P) * b22 % P;
11084
+ const t2 = pow2(t1, _6n, P) * b2 % P;
11085
+ const root = pow2(t2, _2n3, P);
11086
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
11087
+ throw new Error("Cannot find square root");
11088
+ return root;
11089
+ }
11090
+ var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
11091
+ var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
11092
+ Fp: Fpk1,
11093
+ endo: secp256k1_ENDO
11094
+ });
11095
+ var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha2564);
11096
+
11097
+ // modules/market/MarketModule.ts
11098
+ function hexToBytes3(hex) {
11099
+ const len = hex.length >> 1;
11100
+ const bytes = new Uint8Array(len);
11101
+ for (let i = 0; i < len; i++) {
11102
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
11103
+ }
11104
+ return bytes;
11105
+ }
11106
+ function signRequest(body, privateKeyHex) {
11107
+ const timestamp = Date.now();
11108
+ const payload = JSON.stringify({ body, timestamp });
11109
+ const messageHash = sha2564(new TextEncoder().encode(payload));
11110
+ const privateKeyBytes = hexToBytes3(privateKeyHex);
11111
+ const signature = secp256k1.sign(messageHash, privateKeyBytes);
11112
+ const publicKey = bytesToHex4(secp256k1.getPublicKey(privateKeyBytes, true));
11113
+ return {
11114
+ body: JSON.stringify(body),
11115
+ headers: {
11116
+ "x-signature": bytesToHex4(signature),
11117
+ "x-public-key": publicKey,
11118
+ "x-timestamp": String(timestamp),
11119
+ "content-type": "application/json"
11120
+ }
11121
+ };
11122
+ }
11123
+ function toSnakeCaseIntent(req) {
11124
+ const result = {
11125
+ description: req.description,
11126
+ intent_type: req.intentType
11127
+ };
11128
+ if (req.category !== void 0) result.category = req.category;
11129
+ if (req.price !== void 0) result.price = req.price;
11130
+ if (req.currency !== void 0) result.currency = req.currency;
11131
+ if (req.location !== void 0) result.location = req.location;
11132
+ if (req.contactHandle !== void 0) result.contact_handle = req.contactHandle;
11133
+ if (req.expiresInDays !== void 0) result.expires_in_days = req.expiresInDays;
11134
+ return result;
11135
+ }
11136
+ function toSnakeCaseFilters(opts) {
11137
+ const result = {};
11138
+ if (opts?.filters) {
11139
+ const f = opts.filters;
11140
+ if (f.intentType !== void 0) result.intent_type = f.intentType;
11141
+ if (f.category !== void 0) result.category = f.category;
11142
+ if (f.minPrice !== void 0) result.min_price = f.minPrice;
11143
+ if (f.maxPrice !== void 0) result.max_price = f.maxPrice;
11144
+ if (f.location !== void 0) result.location = f.location;
11145
+ }
11146
+ if (opts?.limit !== void 0) result.limit = opts.limit;
11147
+ return result;
11148
+ }
11149
+ function mapSearchResult(raw) {
11150
+ return {
11151
+ id: raw.id,
11152
+ score: raw.score,
11153
+ agentNametag: raw.agent_nametag ?? void 0,
11154
+ agentPublicKey: raw.agent_public_key,
11155
+ description: raw.description,
11156
+ intentType: raw.intent_type,
11157
+ category: raw.category ?? void 0,
11158
+ price: raw.price ?? void 0,
11159
+ currency: raw.currency,
11160
+ location: raw.location ?? void 0,
11161
+ contactMethod: raw.contact_method,
11162
+ contactHandle: raw.contact_handle ?? void 0,
11163
+ createdAt: raw.created_at,
11164
+ expiresAt: raw.expires_at
11165
+ };
11166
+ }
11167
+ function mapMyIntent(raw) {
11168
+ return {
11169
+ id: raw.id,
11170
+ intentType: raw.intent_type,
11171
+ category: raw.category ?? void 0,
11172
+ price: raw.price ?? void 0,
11173
+ currency: raw.currency,
11174
+ location: raw.location ?? void 0,
11175
+ status: raw.status,
11176
+ createdAt: raw.created_at,
11177
+ expiresAt: raw.expires_at
11178
+ };
11179
+ }
11180
+ function mapFeedListing(raw) {
11181
+ return {
11182
+ id: raw.id,
11183
+ title: raw.title,
11184
+ descriptionPreview: raw.description_preview,
11185
+ agentName: raw.agent_name,
11186
+ agentId: raw.agent_id,
11187
+ type: raw.type,
11188
+ createdAt: raw.created_at
11189
+ };
11190
+ }
11191
+ function mapFeedMessage(raw) {
11192
+ if (raw.type === "initial") {
11193
+ return { type: "initial", listings: (raw.listings ?? []).map(mapFeedListing) };
11194
+ }
11195
+ return { type: "new", listing: mapFeedListing(raw.listing) };
11196
+ }
11197
+ var MarketModule = class {
11198
+ apiUrl;
11199
+ timeout;
11200
+ identity = null;
11201
+ registered = false;
11202
+ constructor(config) {
11203
+ this.apiUrl = (config?.apiUrl ?? DEFAULT_MARKET_API_URL).replace(/\/+$/, "");
11204
+ this.timeout = config?.timeout ?? 3e4;
11205
+ }
11206
+ /** Called by Sphere after construction */
11207
+ initialize(deps) {
11208
+ this.identity = deps.identity;
11209
+ }
11210
+ /** No-op — stateless module */
11211
+ async load() {
11212
+ }
11213
+ /** No-op — stateless module */
11214
+ destroy() {
11215
+ }
11216
+ // ---------------------------------------------------------------------------
11217
+ // Public API
11218
+ // ---------------------------------------------------------------------------
11219
+ /** Post a new intent (agent is auto-registered on first post) */
11220
+ async postIntent(intent) {
11221
+ const body = toSnakeCaseIntent(intent);
11222
+ const data = await this.apiPost("/api/intents", body);
11223
+ return {
11224
+ intentId: data.intent_id ?? data.intentId,
11225
+ message: data.message,
11226
+ expiresAt: data.expires_at ?? data.expiresAt
11227
+ };
11228
+ }
11229
+ /** Semantic search for intents (public — no auth required) */
11230
+ async search(query, opts) {
11231
+ const body = {
11232
+ query,
11233
+ ...toSnakeCaseFilters(opts)
11234
+ };
11235
+ const data = await this.apiPublicPost("/api/search", body);
11236
+ let results = (data.intents ?? []).map(mapSearchResult);
11237
+ const minScore = opts?.filters?.minScore;
11238
+ if (minScore != null) {
11239
+ results = results.filter((r) => Math.round(r.score * 100) >= Math.round(minScore * 100));
11240
+ }
11241
+ return { intents: results, count: results.length };
11242
+ }
11243
+ /** List own intents (authenticated) */
11244
+ async getMyIntents() {
11245
+ const data = await this.apiGet("/api/intents");
11246
+ return (data.intents ?? []).map(mapMyIntent);
11247
+ }
11248
+ /** Close (delete) an intent */
11249
+ async closeIntent(intentId) {
11250
+ await this.apiDelete(`/api/intents/${encodeURIComponent(intentId)}`);
11251
+ }
11252
+ /** Fetch the most recent listings via REST (public — no auth required) */
11253
+ async getRecentListings() {
11254
+ const res = await fetch(`${this.apiUrl}/api/feed/recent`, {
11255
+ signal: AbortSignal.timeout(this.timeout)
11256
+ });
11257
+ const data = await this.parseResponse(res);
11258
+ return (data.listings ?? []).map(mapFeedListing);
11259
+ }
11260
+ /**
11261
+ * Subscribe to the live listing feed via WebSocket.
11262
+ * Returns an unsubscribe function that closes the connection.
11263
+ *
11264
+ * Requires a WebSocket implementation — works natively in browsers
11265
+ * and in Node.js 21+ (or with the `ws` package).
11266
+ */
11267
+ subscribeFeed(listener) {
11268
+ const wsUrl = this.apiUrl.replace(/^http/, "ws") + "/ws/feed";
11269
+ const ws2 = new WebSocket(wsUrl);
11270
+ ws2.onmessage = (event) => {
11271
+ try {
11272
+ const raw = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
11273
+ listener(mapFeedMessage(raw));
11274
+ } catch {
11275
+ }
11276
+ };
11277
+ return () => {
11278
+ ws2.close();
11279
+ };
11280
+ }
11281
+ // ---------------------------------------------------------------------------
11282
+ // Private: HTTP helpers
11283
+ // ---------------------------------------------------------------------------
11284
+ ensureIdentity() {
11285
+ if (!this.identity) {
11286
+ throw new Error("MarketModule not initialized \u2014 call initialize() first");
11287
+ }
11288
+ }
11289
+ /** Register the agent's public key with the server (idempotent) */
11290
+ async ensureRegistered() {
11291
+ if (this.registered) return;
11292
+ this.ensureIdentity();
11293
+ const publicKey = bytesToHex4(secp256k1.getPublicKey(hexToBytes3(this.identity.privateKey), true));
11294
+ const body = { public_key: publicKey };
11295
+ if (this.identity.nametag) body.nametag = this.identity.nametag;
11296
+ const res = await fetch(`${this.apiUrl}/api/agent/register`, {
11297
+ method: "POST",
11298
+ headers: { "content-type": "application/json" },
11299
+ body: JSON.stringify(body),
11300
+ signal: AbortSignal.timeout(this.timeout)
11301
+ });
11302
+ if (res.ok || res.status === 409) {
11303
+ this.registered = true;
11304
+ return;
11305
+ }
11306
+ const text = await res.text();
11307
+ let data;
11308
+ try {
11309
+ data = JSON.parse(text);
11310
+ } catch {
11311
+ }
11312
+ throw new Error(data?.error ?? `Agent registration failed: HTTP ${res.status}`);
11313
+ }
11314
+ async parseResponse(res) {
11315
+ const text = await res.text();
11316
+ let data;
11317
+ try {
11318
+ data = JSON.parse(text);
11319
+ } catch {
11320
+ throw new Error(`Market API error: HTTP ${res.status} \u2014 unexpected response (not JSON)`);
11321
+ }
11322
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
11323
+ return data;
11324
+ }
11325
+ async apiPost(path, body) {
11326
+ this.ensureIdentity();
11327
+ await this.ensureRegistered();
11328
+ const signed = signRequest(body, this.identity.privateKey);
11329
+ const res = await fetch(`${this.apiUrl}${path}`, {
11330
+ method: "POST",
11331
+ headers: signed.headers,
11332
+ body: signed.body,
11333
+ signal: AbortSignal.timeout(this.timeout)
11334
+ });
11335
+ return this.parseResponse(res);
11336
+ }
11337
+ async apiGet(path) {
11338
+ this.ensureIdentity();
11339
+ await this.ensureRegistered();
11340
+ const signed = signRequest({}, this.identity.privateKey);
11341
+ const res = await fetch(`${this.apiUrl}${path}`, {
11342
+ method: "GET",
11343
+ headers: signed.headers,
11344
+ signal: AbortSignal.timeout(this.timeout)
11345
+ });
11346
+ return this.parseResponse(res);
11347
+ }
11348
+ async apiDelete(path) {
11349
+ this.ensureIdentity();
11350
+ await this.ensureRegistered();
11351
+ const signed = signRequest({}, this.identity.privateKey);
11352
+ const res = await fetch(`${this.apiUrl}${path}`, {
11353
+ method: "DELETE",
11354
+ headers: signed.headers,
11355
+ signal: AbortSignal.timeout(this.timeout)
11356
+ });
11357
+ return this.parseResponse(res);
11358
+ }
11359
+ async apiPublicPost(path, body) {
11360
+ const res = await fetch(`${this.apiUrl}${path}`, {
11361
+ method: "POST",
11362
+ headers: { "content-type": "application/json" },
11363
+ body: JSON.stringify(body),
11364
+ signal: AbortSignal.timeout(this.timeout)
11365
+ });
11366
+ return this.parseResponse(res);
11367
+ }
11368
+ };
11369
+ function createMarketModule(config) {
11370
+ return new MarketModule(config);
11371
+ }
11372
+
8820
11373
  // core/encryption.ts
8821
11374
  import CryptoJS6 from "crypto-js";
8822
11375
  var DEFAULT_ITERATIONS = 1e5;
@@ -9737,6 +12290,7 @@ var Sphere = class _Sphere {
9737
12290
  _payments;
9738
12291
  _communications;
9739
12292
  _groupChat = null;
12293
+ _market = null;
9740
12294
  // Events
9741
12295
  eventHandlers = /* @__PURE__ */ new Map();
9742
12296
  // Provider management
@@ -9746,7 +12300,7 @@ var Sphere = class _Sphere {
9746
12300
  // ===========================================================================
9747
12301
  // Constructor (private)
9748
12302
  // ===========================================================================
9749
- constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig) {
12303
+ constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig, marketConfig) {
9750
12304
  this._storage = storage;
9751
12305
  this._transport = transport;
9752
12306
  this._oracle = oracle;
@@ -9757,6 +12311,7 @@ var Sphere = class _Sphere {
9757
12311
  this._payments = createPaymentsModule({ l1: l1Config });
9758
12312
  this._communications = createCommunicationsModule();
9759
12313
  this._groupChat = groupChatConfig ? createGroupChatModule(groupChatConfig) : null;
12314
+ this._market = marketConfig ? createMarketModule(marketConfig) : null;
9760
12315
  }
9761
12316
  // ===========================================================================
9762
12317
  // Static Methods - Wallet Management
@@ -9805,6 +12360,7 @@ var Sphere = class _Sphere {
9805
12360
  */
9806
12361
  static async init(options) {
9807
12362
  const groupChat = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12363
+ const market = _Sphere.resolveMarketConfig(options.market);
9808
12364
  const walletExists = await _Sphere.exists(options.storage);
9809
12365
  if (walletExists) {
9810
12366
  const sphere2 = await _Sphere.load({
@@ -9815,7 +12371,8 @@ var Sphere = class _Sphere {
9815
12371
  l1: options.l1,
9816
12372
  price: options.price,
9817
12373
  groupChat,
9818
- password: options.password
12374
+ password: options.password,
12375
+ market
9819
12376
  });
9820
12377
  return { sphere: sphere2, created: false };
9821
12378
  }
@@ -9842,7 +12399,8 @@ var Sphere = class _Sphere {
9842
12399
  l1: options.l1,
9843
12400
  price: options.price,
9844
12401
  groupChat,
9845
- password: options.password
12402
+ password: options.password,
12403
+ market
9846
12404
  });
9847
12405
  return { sphere, created: true, generatedMnemonic };
9848
12406
  }
@@ -9869,6 +12427,22 @@ var Sphere = class _Sphere {
9869
12427
  }
9870
12428
  return config;
9871
12429
  }
12430
+ /**
12431
+ * Resolve market module config from Sphere.init() options.
12432
+ * - `true` → enable with default API URL
12433
+ * - `MarketModuleConfig` → pass through with defaults
12434
+ * - `undefined` → no market module
12435
+ */
12436
+ static resolveMarketConfig(config) {
12437
+ if (!config) return void 0;
12438
+ if (config === true) {
12439
+ return { apiUrl: DEFAULT_MARKET_API_URL };
12440
+ }
12441
+ return {
12442
+ apiUrl: config.apiUrl ?? DEFAULT_MARKET_API_URL,
12443
+ timeout: config.timeout
12444
+ };
12445
+ }
9872
12446
  /**
9873
12447
  * Create new wallet with mnemonic
9874
12448
  */
@@ -9880,6 +12454,7 @@ var Sphere = class _Sphere {
9880
12454
  throw new Error("Wallet already exists. Use Sphere.load() or Sphere.clear() first.");
9881
12455
  }
9882
12456
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12457
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
9883
12458
  const sphere = new _Sphere(
9884
12459
  options.storage,
9885
12460
  options.transport,
@@ -9887,7 +12462,8 @@ var Sphere = class _Sphere {
9887
12462
  options.tokenStorage,
9888
12463
  options.l1,
9889
12464
  options.price,
9890
- groupChatConfig
12465
+ groupChatConfig,
12466
+ marketConfig
9891
12467
  );
9892
12468
  sphere._password = options.password ?? null;
9893
12469
  await sphere.storeMnemonic(options.mnemonic, options.derivationPath);
@@ -9914,6 +12490,7 @@ var Sphere = class _Sphere {
9914
12490
  throw new Error("No wallet found. Use Sphere.create() to create a new wallet.");
9915
12491
  }
9916
12492
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12493
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
9917
12494
  const sphere = new _Sphere(
9918
12495
  options.storage,
9919
12496
  options.transport,
@@ -9921,7 +12498,8 @@ var Sphere = class _Sphere {
9921
12498
  options.tokenStorage,
9922
12499
  options.l1,
9923
12500
  options.price,
9924
- groupChatConfig
12501
+ groupChatConfig,
12502
+ marketConfig
9925
12503
  );
9926
12504
  sphere._password = options.password ?? null;
9927
12505
  await sphere.loadIdentityFromStorage();
@@ -9967,6 +12545,7 @@ var Sphere = class _Sphere {
9967
12545
  console.log("[Sphere.import] Storage reconnected");
9968
12546
  }
9969
12547
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat);
12548
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
9970
12549
  const sphere = new _Sphere(
9971
12550
  options.storage,
9972
12551
  options.transport,
@@ -9974,7 +12553,8 @@ var Sphere = class _Sphere {
9974
12553
  options.tokenStorage,
9975
12554
  options.l1,
9976
12555
  options.price,
9977
- groupChatConfig
12556
+ groupChatConfig,
12557
+ marketConfig
9978
12558
  );
9979
12559
  sphere._password = options.password ?? null;
9980
12560
  if (options.mnemonic) {
@@ -10139,6 +12719,10 @@ var Sphere = class _Sphere {
10139
12719
  get groupChat() {
10140
12720
  return this._groupChat;
10141
12721
  }
12722
+ /** Market module (intent bulletin board). Null if not configured. */
12723
+ get market() {
12724
+ return this._market;
12725
+ }
10142
12726
  // ===========================================================================
10143
12727
  // Public Properties - State
10144
12728
  // ===========================================================================
@@ -11014,9 +13598,14 @@ var Sphere = class _Sphere {
11014
13598
  storage: this._storage,
11015
13599
  emitEvent
11016
13600
  });
13601
+ this._market?.initialize({
13602
+ identity: this._identity,
13603
+ emitEvent
13604
+ });
11017
13605
  await this._payments.load();
11018
13606
  await this._communications.load();
11019
13607
  await this._groupChat?.load();
13608
+ await this._market?.load();
11020
13609
  }
11021
13610
  /**
11022
13611
  * Derive address at a specific index
@@ -11717,12 +14306,22 @@ var Sphere = class _Sphere {
11717
14306
  return;
11718
14307
  }
11719
14308
  try {
11720
- if (this._identity?.directAddress && this._transport.resolve) {
14309
+ const transportPubkey = this._identity?.chainPubkey?.slice(2);
14310
+ if (transportPubkey && this._transport.resolve) {
11721
14311
  try {
11722
- const existing = await this._transport.resolve(this._identity.directAddress);
14312
+ const existing = await this._transport.resolve(transportPubkey);
11723
14313
  if (existing) {
11724
- if (existing.nametag && !this._identity.nametag) {
11725
- this._identity.nametag = existing.nametag;
14314
+ let recoveredNametag = existing.nametag;
14315
+ let fromLegacy = false;
14316
+ if (!recoveredNametag && !this._identity?.nametag && this._transport.recoverNametag) {
14317
+ try {
14318
+ recoveredNametag = await this._transport.recoverNametag() ?? void 0;
14319
+ if (recoveredNametag) fromLegacy = true;
14320
+ } catch {
14321
+ }
14322
+ }
14323
+ if (recoveredNametag && !this._identity?.nametag) {
14324
+ this._identity.nametag = recoveredNametag;
11726
14325
  await this._updateCachedProxyAddress();
11727
14326
  const entry = await this.ensureAddressTracked(this._currentAddressIndex);
11728
14327
  let nametags = this._addressNametags.get(entry.addressId);
@@ -11731,10 +14330,20 @@ var Sphere = class _Sphere {
11731
14330
  this._addressNametags.set(entry.addressId, nametags);
11732
14331
  }
11733
14332
  if (!nametags.has(0)) {
11734
- nametags.set(0, existing.nametag);
14333
+ nametags.set(0, recoveredNametag);
11735
14334
  await this.persistAddressNametags();
11736
14335
  }
11737
- this.emitEvent("nametag:recovered", { nametag: existing.nametag });
14336
+ this.emitEvent("nametag:recovered", { nametag: recoveredNametag });
14337
+ if (fromLegacy) {
14338
+ await this._transport.publishIdentityBinding(
14339
+ this._identity.chainPubkey,
14340
+ this._identity.l1Address,
14341
+ this._identity.directAddress || "",
14342
+ recoveredNametag
14343
+ );
14344
+ console.log(`[Sphere] Migrated legacy binding with nametag @${recoveredNametag}`);
14345
+ return;
14346
+ }
11738
14347
  }
11739
14348
  console.log("[Sphere] Existing binding found, skipping re-publish");
11740
14349
  return;
@@ -11821,6 +14430,7 @@ var Sphere = class _Sphere {
11821
14430
  this._payments.destroy();
11822
14431
  this._communications.destroy();
11823
14432
  this._groupChat?.destroy();
14433
+ this._market?.destroy();
11824
14434
  await this._transport.disconnect();
11825
14435
  await this._storage.disconnect();
11826
14436
  await this._oracle.disconnect();
@@ -12128,9 +14738,14 @@ var Sphere = class _Sphere {
12128
14738
  storage: this._storage,
12129
14739
  emitEvent
12130
14740
  });
14741
+ this._market?.initialize({
14742
+ identity: this._identity,
14743
+ emitEvent
14744
+ });
12131
14745
  await this._payments.load();
12132
14746
  await this._communications.load();
12133
14747
  await this._groupChat?.load();
14748
+ await this._market?.load();
12134
14749
  }
12135
14750
  // ===========================================================================
12136
14751
  // Private: Helpers
@@ -12480,4 +15095,16 @@ export {
12480
15095
  toSmallestUnit,
12481
15096
  validateMnemonic2 as validateMnemonic
12482
15097
  };
15098
+ /*! Bundled license information:
15099
+
15100
+ @noble/hashes/utils.js:
15101
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
15102
+
15103
+ @noble/curves/utils.js:
15104
+ @noble/curves/abstract/modular.js:
15105
+ @noble/curves/abstract/curve.js:
15106
+ @noble/curves/abstract/weierstrass.js:
15107
+ @noble/curves/secp256k1.js:
15108
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
15109
+ */
12483
15110
  //# sourceMappingURL=index.js.map