@unicitylabs/sphere-sdk 0.3.4 → 0.3.6

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