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