@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.
package/dist/index.js CHANGED
@@ -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
  }
@@ -2490,7 +2490,11 @@ var STORAGE_KEYS_GLOBAL = {
2490
2490
  /** Group chat: processed event IDs for deduplication */
2491
2491
  GROUP_CHAT_PROCESSED_EVENTS: "group_chat_processed_events",
2492
2492
  /** Group chat: last used relay URL (stale data detection) */
2493
- GROUP_CHAT_RELAY_URL: "group_chat_relay_url"
2493
+ GROUP_CHAT_RELAY_URL: "group_chat_relay_url",
2494
+ /** Cached token registry JSON (fetched from remote) */
2495
+ TOKEN_REGISTRY_CACHE: "token_registry_cache",
2496
+ /** Timestamp of last token registry cache update (ms since epoch) */
2497
+ TOKEN_REGISTRY_CACHE_TS: "token_registry_cache_ts"
2494
2498
  };
2495
2499
  var STORAGE_KEYS_ADDRESS = {
2496
2500
  /** Pending transfers for this address */
@@ -2598,6 +2602,8 @@ var COIN_TYPES = {
2598
2602
  };
2599
2603
  var DEFAULT_ELECTRUM_URL = "wss://fulcrum.alpha.unicity.network:50004";
2600
2604
  var TEST_ELECTRUM_URL = "wss://fulcrum.alpha.testnet.unicity.network:50004";
2605
+ var TOKEN_REGISTRY_URL = "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/unicity-ids.testnet.json";
2606
+ var TOKEN_REGISTRY_REFRESH_INTERVAL = 36e5;
2601
2607
  var TEST_NOSTR_RELAYS = [
2602
2608
  "wss://nostr-relay.testnet.unicity.network"
2603
2609
  ];
@@ -2611,7 +2617,8 @@ var NETWORKS = {
2611
2617
  nostrRelays: DEFAULT_NOSTR_RELAYS,
2612
2618
  ipfsGateways: DEFAULT_IPFS_GATEWAYS,
2613
2619
  electrumUrl: DEFAULT_ELECTRUM_URL,
2614
- groupRelays: DEFAULT_GROUP_RELAYS
2620
+ groupRelays: DEFAULT_GROUP_RELAYS,
2621
+ tokenRegistryUrl: TOKEN_REGISTRY_URL
2615
2622
  },
2616
2623
  testnet: {
2617
2624
  name: "Testnet",
@@ -2619,7 +2626,8 @@ var NETWORKS = {
2619
2626
  nostrRelays: TEST_NOSTR_RELAYS,
2620
2627
  ipfsGateways: DEFAULT_IPFS_GATEWAYS,
2621
2628
  electrumUrl: TEST_ELECTRUM_URL,
2622
- groupRelays: DEFAULT_GROUP_RELAYS
2629
+ groupRelays: DEFAULT_GROUP_RELAYS,
2630
+ tokenRegistryUrl: TOKEN_REGISTRY_URL
2623
2631
  },
2624
2632
  dev: {
2625
2633
  name: "Development",
@@ -2627,7 +2635,8 @@ var NETWORKS = {
2627
2635
  nostrRelays: TEST_NOSTR_RELAYS,
2628
2636
  ipfsGateways: DEFAULT_IPFS_GATEWAYS,
2629
2637
  electrumUrl: TEST_ELECTRUM_URL,
2630
- groupRelays: DEFAULT_GROUP_RELAYS
2638
+ groupRelays: DEFAULT_GROUP_RELAYS,
2639
+ tokenRegistryUrl: TOKEN_REGISTRY_URL
2631
2640
  }
2632
2641
  };
2633
2642
  var TIMEOUTS = {
@@ -2642,6 +2651,7 @@ var TIMEOUTS = {
2642
2651
  /** Sync interval */
2643
2652
  SYNC_INTERVAL: 6e4
2644
2653
  };
2654
+ var DEFAULT_MARKET_API_URL = "https://market-api.unicity.network";
2645
2655
  var LIMITS = {
2646
2656
  /** Min nametag length */
2647
2657
  NAMETAG_MIN_LENGTH: 3,
@@ -2695,141 +2705,24 @@ function isValidTokenId(tokenId) {
2695
2705
  return /^[0-9a-fA-F]{64}$/.test(tokenId);
2696
2706
  }
2697
2707
 
2698
- // registry/token-registry.testnet.json
2699
- var token_registry_testnet_default = [
2700
- {
2701
- network: "unicity:testnet",
2702
- assetKind: "non-fungible",
2703
- name: "unicity",
2704
- description: "Unicity testnet token type",
2705
- id: "f8aa13834268d29355ff12183066f0cb902003629bbc5eb9ef0efbe397867509"
2706
- },
2707
- {
2708
- network: "unicity:testnet",
2709
- assetKind: "fungible",
2710
- name: "unicity",
2711
- symbol: "UCT",
2712
- decimals: 18,
2713
- description: "Unicity testnet native coin",
2714
- icons: [
2715
- { url: "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/unicity_logo_32.png" }
2716
- ],
2717
- id: "455ad8720656b08e8dbd5bac1f3c73eeea5431565f6c1c3af742b1aa12d41d89"
2718
- },
2719
- {
2720
- network: "unicity:testnet",
2721
- assetKind: "fungible",
2722
- name: "unicity-usd",
2723
- symbol: "USDU",
2724
- decimals: 6,
2725
- description: "Unicity testnet USD stablecoin",
2726
- icons: [
2727
- { url: "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/usdu_logo_32.png" }
2728
- ],
2729
- id: "8f0f3d7a5e7297be0ee98c63b81bcebb2740f43f616566fc290f9823a54f52d7"
2730
- },
2731
- {
2732
- network: "unicity:testnet",
2733
- assetKind: "fungible",
2734
- name: "unicity-eur",
2735
- symbol: "EURU",
2736
- decimals: 6,
2737
- description: "Unicity testnet EUR stablecoin",
2738
- icons: [
2739
- { url: "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/euru_logo_32.png" }
2740
- ],
2741
- id: "5e160d5e9fdbb03b553fb9c3f6e6c30efa41fa807be39fb4f18e43776e492925"
2742
- },
2743
- {
2744
- network: "unicity:testnet",
2745
- assetKind: "fungible",
2746
- name: "solana",
2747
- symbol: "SOL",
2748
- decimals: 9,
2749
- description: "Solana testnet coin on Unicity",
2750
- icons: [
2751
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/sol.svg" },
2752
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/sol.png" }
2753
- ],
2754
- id: "dee5f8ce778562eec90e9c38a91296a023210ccc76ff4c29d527ac3eb64ade93"
2755
- },
2756
- {
2757
- network: "unicity:testnet",
2758
- assetKind: "fungible",
2759
- name: "bitcoin",
2760
- symbol: "BTC",
2761
- decimals: 8,
2762
- description: "Bitcoin testnet coin on Unicity",
2763
- icons: [
2764
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/btc.svg" },
2765
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/btc.png" }
2766
- ],
2767
- id: "86bc190fcf7b2d07c6078de93db803578760148b16d4431aa2f42a3241ff0daa"
2768
- },
2769
- {
2770
- network: "unicity:testnet",
2771
- assetKind: "fungible",
2772
- name: "ethereum",
2773
- symbol: "ETH",
2774
- decimals: 18,
2775
- description: "Ethereum testnet coin on Unicity",
2776
- icons: [
2777
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/eth.svg" },
2778
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/eth.png" }
2779
- ],
2780
- id: "3c2450f2fd867e7bb60c6a69d7ad0e53ce967078c201a3ecaa6074ed4c0deafb"
2781
- },
2782
- {
2783
- network: "unicity:testnet",
2784
- assetKind: "fungible",
2785
- name: "alpha_test",
2786
- symbol: "ALPHT",
2787
- decimals: 8,
2788
- description: "ALPHA testnet coin on Unicity",
2789
- icons: [
2790
- { url: "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/alpha_coin.png" }
2791
- ],
2792
- id: "cde78ded16ef65818a51f43138031c4284e519300ab0cb60c30a8f9078080e5f"
2793
- },
2794
- {
2795
- network: "unicity:testnet",
2796
- assetKind: "fungible",
2797
- name: "tether",
2798
- symbol: "USDT",
2799
- decimals: 6,
2800
- description: "Tether (Ethereum) testnet coin on Unicity",
2801
- icons: [
2802
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/usdt.svg" },
2803
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/usdt.png" }
2804
- ],
2805
- id: "40d25444648418fe7efd433e147187a3a6adf049ac62bc46038bda5b960bf690"
2806
- },
2807
- {
2808
- network: "unicity:testnet",
2809
- assetKind: "fungible",
2810
- name: "usd-coin",
2811
- symbol: "USDC",
2812
- decimals: 6,
2813
- description: "USDC (Ethereum) testnet coin on Unicity",
2814
- icons: [
2815
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/usdc.svg" },
2816
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/usdc.png" }
2817
- ],
2818
- id: "2265121770fa6f41131dd9a6cc571e28679263d09a53eb2642e145b5b9a5b0a2"
2819
- }
2820
- ];
2821
-
2822
2708
  // registry/TokenRegistry.ts
2709
+ var FETCH_TIMEOUT_MS = 1e4;
2823
2710
  var TokenRegistry = class _TokenRegistry {
2824
2711
  static instance = null;
2825
2712
  definitionsById;
2826
2713
  definitionsBySymbol;
2827
2714
  definitionsByName;
2715
+ // Remote refresh state
2716
+ remoteUrl = null;
2717
+ storage = null;
2718
+ refreshIntervalMs = TOKEN_REGISTRY_REFRESH_INTERVAL;
2719
+ refreshTimer = null;
2720
+ lastRefreshAt = 0;
2721
+ refreshPromise = null;
2828
2722
  constructor() {
2829
2723
  this.definitionsById = /* @__PURE__ */ new Map();
2830
2724
  this.definitionsBySymbol = /* @__PURE__ */ new Map();
2831
2725
  this.definitionsByName = /* @__PURE__ */ new Map();
2832
- this.loadRegistry();
2833
2726
  }
2834
2727
  /**
2835
2728
  * Get singleton instance of TokenRegistry
@@ -2841,16 +2734,106 @@ var TokenRegistry = class _TokenRegistry {
2841
2734
  return _TokenRegistry.instance;
2842
2735
  }
2843
2736
  /**
2844
- * Reset the singleton instance (useful for testing)
2737
+ * Configure remote registry refresh with persistent caching.
2738
+ *
2739
+ * On first call:
2740
+ * 1. Loads cached data from StorageProvider (if available and fresh)
2741
+ * 2. Starts periodic remote fetch (if autoRefresh is true, which is default)
2742
+ *
2743
+ * @param options - Configuration options
2744
+ * @param options.remoteUrl - Remote URL to fetch definitions from
2745
+ * @param options.storage - StorageProvider for persistent caching
2746
+ * @param options.refreshIntervalMs - Refresh interval in ms (default: 1 hour)
2747
+ * @param options.autoRefresh - Start auto-refresh immediately (default: true)
2748
+ */
2749
+ static configure(options) {
2750
+ const instance = _TokenRegistry.getInstance();
2751
+ if (options.remoteUrl !== void 0) {
2752
+ instance.remoteUrl = options.remoteUrl;
2753
+ }
2754
+ if (options.storage !== void 0) {
2755
+ instance.storage = options.storage;
2756
+ }
2757
+ if (options.refreshIntervalMs !== void 0) {
2758
+ instance.refreshIntervalMs = options.refreshIntervalMs;
2759
+ }
2760
+ if (instance.storage) {
2761
+ instance.loadFromCache();
2762
+ }
2763
+ const autoRefresh = options.autoRefresh ?? true;
2764
+ if (autoRefresh && instance.remoteUrl) {
2765
+ instance.startAutoRefresh();
2766
+ }
2767
+ }
2768
+ /**
2769
+ * Reset the singleton instance (useful for testing).
2770
+ * Stops auto-refresh if running.
2845
2771
  */
2846
2772
  static resetInstance() {
2773
+ if (_TokenRegistry.instance) {
2774
+ _TokenRegistry.instance.stopAutoRefresh();
2775
+ }
2847
2776
  _TokenRegistry.instance = null;
2848
2777
  }
2849
2778
  /**
2850
- * Load registry data from bundled JSON
2779
+ * Destroy the singleton: stop auto-refresh and reset.
2780
+ */
2781
+ static destroy() {
2782
+ _TokenRegistry.resetInstance();
2783
+ }
2784
+ // ===========================================================================
2785
+ // Cache (StorageProvider)
2786
+ // ===========================================================================
2787
+ /**
2788
+ * Load definitions from StorageProvider cache.
2789
+ * Only applies if cache exists and is fresh (within refreshIntervalMs).
2790
+ */
2791
+ async loadFromCache() {
2792
+ if (!this.storage) return false;
2793
+ try {
2794
+ const [cached, cachedTs] = await Promise.all([
2795
+ this.storage.get(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE),
2796
+ this.storage.get(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE_TS)
2797
+ ]);
2798
+ if (!cached || !cachedTs) return false;
2799
+ const ts = parseInt(cachedTs, 10);
2800
+ if (isNaN(ts)) return false;
2801
+ const age = Date.now() - ts;
2802
+ if (age > this.refreshIntervalMs) return false;
2803
+ if (this.lastRefreshAt > ts) return false;
2804
+ const data = JSON.parse(cached);
2805
+ if (!this.isValidDefinitionsArray(data)) return false;
2806
+ this.applyDefinitions(data);
2807
+ this.lastRefreshAt = ts;
2808
+ return true;
2809
+ } catch {
2810
+ return false;
2811
+ }
2812
+ }
2813
+ /**
2814
+ * Save definitions to StorageProvider cache.
2851
2815
  */
2852
- loadRegistry() {
2853
- const definitions = token_registry_testnet_default;
2816
+ async saveToCache(definitions) {
2817
+ if (!this.storage) return;
2818
+ try {
2819
+ await Promise.all([
2820
+ this.storage.set(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE, JSON.stringify(definitions)),
2821
+ this.storage.set(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE_TS, String(Date.now()))
2822
+ ]);
2823
+ } catch {
2824
+ }
2825
+ }
2826
+ // ===========================================================================
2827
+ // Remote Refresh
2828
+ // ===========================================================================
2829
+ /**
2830
+ * Apply an array of token definitions to the internal maps.
2831
+ * Clears existing data before applying.
2832
+ */
2833
+ applyDefinitions(definitions) {
2834
+ this.definitionsById.clear();
2835
+ this.definitionsBySymbol.clear();
2836
+ this.definitionsByName.clear();
2854
2837
  for (const def of definitions) {
2855
2838
  const idLower = def.id.toLowerCase();
2856
2839
  this.definitionsById.set(idLower, def);
@@ -2860,6 +2843,96 @@ var TokenRegistry = class _TokenRegistry {
2860
2843
  this.definitionsByName.set(def.name.toLowerCase(), def);
2861
2844
  }
2862
2845
  }
2846
+ /**
2847
+ * Validate that data is an array of objects with 'id' field
2848
+ */
2849
+ isValidDefinitionsArray(data) {
2850
+ return Array.isArray(data) && data.every((item) => item && typeof item === "object" && "id" in item);
2851
+ }
2852
+ /**
2853
+ * Fetch token definitions from the remote URL and update the registry.
2854
+ * On success, also persists to StorageProvider cache.
2855
+ * Returns true on success, false on failure. On failure, existing data is preserved.
2856
+ * Concurrent calls are deduplicated — only one fetch runs at a time.
2857
+ */
2858
+ async refreshFromRemote() {
2859
+ if (!this.remoteUrl) {
2860
+ return false;
2861
+ }
2862
+ if (this.refreshPromise) {
2863
+ return this.refreshPromise;
2864
+ }
2865
+ this.refreshPromise = this.doRefresh();
2866
+ try {
2867
+ return await this.refreshPromise;
2868
+ } finally {
2869
+ this.refreshPromise = null;
2870
+ }
2871
+ }
2872
+ async doRefresh() {
2873
+ try {
2874
+ const controller = new AbortController();
2875
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
2876
+ let response;
2877
+ try {
2878
+ response = await fetch(this.remoteUrl, {
2879
+ headers: { Accept: "application/json" },
2880
+ signal: controller.signal
2881
+ });
2882
+ } finally {
2883
+ clearTimeout(timer);
2884
+ }
2885
+ if (!response.ok) {
2886
+ console.warn(
2887
+ `[TokenRegistry] Remote fetch failed: HTTP ${response.status} ${response.statusText}`
2888
+ );
2889
+ return false;
2890
+ }
2891
+ const data = await response.json();
2892
+ if (!this.isValidDefinitionsArray(data)) {
2893
+ console.warn("[TokenRegistry] Remote data is not a valid token definitions array");
2894
+ return false;
2895
+ }
2896
+ const definitions = data;
2897
+ this.applyDefinitions(definitions);
2898
+ this.lastRefreshAt = Date.now();
2899
+ this.saveToCache(definitions);
2900
+ return true;
2901
+ } catch (error) {
2902
+ const message = error instanceof Error ? error.message : String(error);
2903
+ console.warn(`[TokenRegistry] Remote refresh failed: ${message}`);
2904
+ return false;
2905
+ }
2906
+ }
2907
+ /**
2908
+ * Start periodic auto-refresh from the remote URL.
2909
+ * Does an immediate fetch, then repeats at the configured interval.
2910
+ */
2911
+ startAutoRefresh(intervalMs) {
2912
+ this.stopAutoRefresh();
2913
+ if (intervalMs !== void 0) {
2914
+ this.refreshIntervalMs = intervalMs;
2915
+ }
2916
+ this.refreshFromRemote();
2917
+ this.refreshTimer = setInterval(() => {
2918
+ this.refreshFromRemote();
2919
+ }, this.refreshIntervalMs);
2920
+ }
2921
+ /**
2922
+ * Stop periodic auto-refresh
2923
+ */
2924
+ stopAutoRefresh() {
2925
+ if (this.refreshTimer !== null) {
2926
+ clearInterval(this.refreshTimer);
2927
+ this.refreshTimer = null;
2928
+ }
2929
+ }
2930
+ /**
2931
+ * Timestamp of the last successful remote refresh (0 if never refreshed)
2932
+ */
2933
+ getLastRefreshAt() {
2934
+ return this.lastRefreshAt;
2935
+ }
2863
2936
  // ===========================================================================
2864
2937
  // Lookup Methods
2865
2938
  // ===========================================================================
@@ -9109,6 +9182,2426 @@ function createGroupChatModule(config) {
9109
9182
  return new GroupChatModule(config);
9110
9183
  }
9111
9184
 
9185
+ // node_modules/@noble/hashes/utils.js
9186
+ function isBytes(a) {
9187
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
9188
+ }
9189
+ function anumber(n, title = "") {
9190
+ if (!Number.isSafeInteger(n) || n < 0) {
9191
+ const prefix = title && `"${title}" `;
9192
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
9193
+ }
9194
+ }
9195
+ function abytes(value, length, title = "") {
9196
+ const bytes = isBytes(value);
9197
+ const len = value?.length;
9198
+ const needsLen = length !== void 0;
9199
+ if (!bytes || needsLen && len !== length) {
9200
+ const prefix = title && `"${title}" `;
9201
+ const ofLen = needsLen ? ` of length ${length}` : "";
9202
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
9203
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
9204
+ }
9205
+ return value;
9206
+ }
9207
+ function ahash(h) {
9208
+ if (typeof h !== "function" || typeof h.create !== "function")
9209
+ throw new Error("Hash must wrapped by utils.createHasher");
9210
+ anumber(h.outputLen);
9211
+ anumber(h.blockLen);
9212
+ }
9213
+ function aexists(instance, checkFinished = true) {
9214
+ if (instance.destroyed)
9215
+ throw new Error("Hash instance has been destroyed");
9216
+ if (checkFinished && instance.finished)
9217
+ throw new Error("Hash#digest() has already been called");
9218
+ }
9219
+ function aoutput(out, instance) {
9220
+ abytes(out, void 0, "digestInto() output");
9221
+ const min = instance.outputLen;
9222
+ if (out.length < min) {
9223
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
9224
+ }
9225
+ }
9226
+ function clean(...arrays) {
9227
+ for (let i = 0; i < arrays.length; i++) {
9228
+ arrays[i].fill(0);
9229
+ }
9230
+ }
9231
+ function createView(arr) {
9232
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
9233
+ }
9234
+ function rotr(word, shift) {
9235
+ return word << 32 - shift | word >>> shift;
9236
+ }
9237
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
9238
+ // @ts-ignore
9239
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
9240
+ ))();
9241
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
9242
+ function bytesToHex4(bytes) {
9243
+ abytes(bytes);
9244
+ if (hasHexBuiltin)
9245
+ return bytes.toHex();
9246
+ let hex = "";
9247
+ for (let i = 0; i < bytes.length; i++) {
9248
+ hex += hexes[bytes[i]];
9249
+ }
9250
+ return hex;
9251
+ }
9252
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
9253
+ function asciiToBase16(ch) {
9254
+ if (ch >= asciis._0 && ch <= asciis._9)
9255
+ return ch - asciis._0;
9256
+ if (ch >= asciis.A && ch <= asciis.F)
9257
+ return ch - (asciis.A - 10);
9258
+ if (ch >= asciis.a && ch <= asciis.f)
9259
+ return ch - (asciis.a - 10);
9260
+ return;
9261
+ }
9262
+ function hexToBytes2(hex) {
9263
+ if (typeof hex !== "string")
9264
+ throw new Error("hex string expected, got " + typeof hex);
9265
+ if (hasHexBuiltin)
9266
+ return Uint8Array.fromHex(hex);
9267
+ const hl = hex.length;
9268
+ const al = hl / 2;
9269
+ if (hl % 2)
9270
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
9271
+ const array = new Uint8Array(al);
9272
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
9273
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
9274
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
9275
+ if (n1 === void 0 || n2 === void 0) {
9276
+ const char = hex[hi] + hex[hi + 1];
9277
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
9278
+ }
9279
+ array[ai] = n1 * 16 + n2;
9280
+ }
9281
+ return array;
9282
+ }
9283
+ function concatBytes(...arrays) {
9284
+ let sum = 0;
9285
+ for (let i = 0; i < arrays.length; i++) {
9286
+ const a = arrays[i];
9287
+ abytes(a);
9288
+ sum += a.length;
9289
+ }
9290
+ const res = new Uint8Array(sum);
9291
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
9292
+ const a = arrays[i];
9293
+ res.set(a, pad);
9294
+ pad += a.length;
9295
+ }
9296
+ return res;
9297
+ }
9298
+ function createHasher(hashCons, info = {}) {
9299
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
9300
+ const tmp = hashCons(void 0);
9301
+ hashC.outputLen = tmp.outputLen;
9302
+ hashC.blockLen = tmp.blockLen;
9303
+ hashC.create = (opts) => hashCons(opts);
9304
+ Object.assign(hashC, info);
9305
+ return Object.freeze(hashC);
9306
+ }
9307
+ function randomBytes2(bytesLength = 32) {
9308
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
9309
+ if (typeof cr?.getRandomValues !== "function")
9310
+ throw new Error("crypto.getRandomValues must be defined");
9311
+ return cr.getRandomValues(new Uint8Array(bytesLength));
9312
+ }
9313
+ var oidNist = (suffix) => ({
9314
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
9315
+ });
9316
+
9317
+ // node_modules/@noble/hashes/_md.js
9318
+ function Chi(a, b, c) {
9319
+ return a & b ^ ~a & c;
9320
+ }
9321
+ function Maj(a, b, c) {
9322
+ return a & b ^ a & c ^ b & c;
9323
+ }
9324
+ var HashMD = class {
9325
+ blockLen;
9326
+ outputLen;
9327
+ padOffset;
9328
+ isLE;
9329
+ // For partial updates less than block size
9330
+ buffer;
9331
+ view;
9332
+ finished = false;
9333
+ length = 0;
9334
+ pos = 0;
9335
+ destroyed = false;
9336
+ constructor(blockLen, outputLen, padOffset, isLE) {
9337
+ this.blockLen = blockLen;
9338
+ this.outputLen = outputLen;
9339
+ this.padOffset = padOffset;
9340
+ this.isLE = isLE;
9341
+ this.buffer = new Uint8Array(blockLen);
9342
+ this.view = createView(this.buffer);
9343
+ }
9344
+ update(data) {
9345
+ aexists(this);
9346
+ abytes(data);
9347
+ const { view, buffer, blockLen } = this;
9348
+ const len = data.length;
9349
+ for (let pos = 0; pos < len; ) {
9350
+ const take = Math.min(blockLen - this.pos, len - pos);
9351
+ if (take === blockLen) {
9352
+ const dataView = createView(data);
9353
+ for (; blockLen <= len - pos; pos += blockLen)
9354
+ this.process(dataView, pos);
9355
+ continue;
9356
+ }
9357
+ buffer.set(data.subarray(pos, pos + take), this.pos);
9358
+ this.pos += take;
9359
+ pos += take;
9360
+ if (this.pos === blockLen) {
9361
+ this.process(view, 0);
9362
+ this.pos = 0;
9363
+ }
9364
+ }
9365
+ this.length += data.length;
9366
+ this.roundClean();
9367
+ return this;
9368
+ }
9369
+ digestInto(out) {
9370
+ aexists(this);
9371
+ aoutput(out, this);
9372
+ this.finished = true;
9373
+ const { buffer, view, blockLen, isLE } = this;
9374
+ let { pos } = this;
9375
+ buffer[pos++] = 128;
9376
+ clean(this.buffer.subarray(pos));
9377
+ if (this.padOffset > blockLen - pos) {
9378
+ this.process(view, 0);
9379
+ pos = 0;
9380
+ }
9381
+ for (let i = pos; i < blockLen; i++)
9382
+ buffer[i] = 0;
9383
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
9384
+ this.process(view, 0);
9385
+ const oview = createView(out);
9386
+ const len = this.outputLen;
9387
+ if (len % 4)
9388
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
9389
+ const outLen = len / 4;
9390
+ const state = this.get();
9391
+ if (outLen > state.length)
9392
+ throw new Error("_sha2: outputLen bigger than state");
9393
+ for (let i = 0; i < outLen; i++)
9394
+ oview.setUint32(4 * i, state[i], isLE);
9395
+ }
9396
+ digest() {
9397
+ const { buffer, outputLen } = this;
9398
+ this.digestInto(buffer);
9399
+ const res = buffer.slice(0, outputLen);
9400
+ this.destroy();
9401
+ return res;
9402
+ }
9403
+ _cloneInto(to) {
9404
+ to ||= new this.constructor();
9405
+ to.set(...this.get());
9406
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
9407
+ to.destroyed = destroyed;
9408
+ to.finished = finished;
9409
+ to.length = length;
9410
+ to.pos = pos;
9411
+ if (length % blockLen)
9412
+ to.buffer.set(buffer);
9413
+ return to;
9414
+ }
9415
+ clone() {
9416
+ return this._cloneInto();
9417
+ }
9418
+ };
9419
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
9420
+ 1779033703,
9421
+ 3144134277,
9422
+ 1013904242,
9423
+ 2773480762,
9424
+ 1359893119,
9425
+ 2600822924,
9426
+ 528734635,
9427
+ 1541459225
9428
+ ]);
9429
+
9430
+ // node_modules/@noble/hashes/sha2.js
9431
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
9432
+ 1116352408,
9433
+ 1899447441,
9434
+ 3049323471,
9435
+ 3921009573,
9436
+ 961987163,
9437
+ 1508970993,
9438
+ 2453635748,
9439
+ 2870763221,
9440
+ 3624381080,
9441
+ 310598401,
9442
+ 607225278,
9443
+ 1426881987,
9444
+ 1925078388,
9445
+ 2162078206,
9446
+ 2614888103,
9447
+ 3248222580,
9448
+ 3835390401,
9449
+ 4022224774,
9450
+ 264347078,
9451
+ 604807628,
9452
+ 770255983,
9453
+ 1249150122,
9454
+ 1555081692,
9455
+ 1996064986,
9456
+ 2554220882,
9457
+ 2821834349,
9458
+ 2952996808,
9459
+ 3210313671,
9460
+ 3336571891,
9461
+ 3584528711,
9462
+ 113926993,
9463
+ 338241895,
9464
+ 666307205,
9465
+ 773529912,
9466
+ 1294757372,
9467
+ 1396182291,
9468
+ 1695183700,
9469
+ 1986661051,
9470
+ 2177026350,
9471
+ 2456956037,
9472
+ 2730485921,
9473
+ 2820302411,
9474
+ 3259730800,
9475
+ 3345764771,
9476
+ 3516065817,
9477
+ 3600352804,
9478
+ 4094571909,
9479
+ 275423344,
9480
+ 430227734,
9481
+ 506948616,
9482
+ 659060556,
9483
+ 883997877,
9484
+ 958139571,
9485
+ 1322822218,
9486
+ 1537002063,
9487
+ 1747873779,
9488
+ 1955562222,
9489
+ 2024104815,
9490
+ 2227730452,
9491
+ 2361852424,
9492
+ 2428436474,
9493
+ 2756734187,
9494
+ 3204031479,
9495
+ 3329325298
9496
+ ]);
9497
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
9498
+ var SHA2_32B = class extends HashMD {
9499
+ constructor(outputLen) {
9500
+ super(64, outputLen, 8, false);
9501
+ }
9502
+ get() {
9503
+ const { A, B, C, D, E, F, G, H } = this;
9504
+ return [A, B, C, D, E, F, G, H];
9505
+ }
9506
+ // prettier-ignore
9507
+ set(A, B, C, D, E, F, G, H) {
9508
+ this.A = A | 0;
9509
+ this.B = B | 0;
9510
+ this.C = C | 0;
9511
+ this.D = D | 0;
9512
+ this.E = E | 0;
9513
+ this.F = F | 0;
9514
+ this.G = G | 0;
9515
+ this.H = H | 0;
9516
+ }
9517
+ process(view, offset) {
9518
+ for (let i = 0; i < 16; i++, offset += 4)
9519
+ SHA256_W[i] = view.getUint32(offset, false);
9520
+ for (let i = 16; i < 64; i++) {
9521
+ const W15 = SHA256_W[i - 15];
9522
+ const W2 = SHA256_W[i - 2];
9523
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
9524
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
9525
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
9526
+ }
9527
+ let { A, B, C, D, E, F, G, H } = this;
9528
+ for (let i = 0; i < 64; i++) {
9529
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
9530
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
9531
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
9532
+ const T2 = sigma0 + Maj(A, B, C) | 0;
9533
+ H = G;
9534
+ G = F;
9535
+ F = E;
9536
+ E = D + T1 | 0;
9537
+ D = C;
9538
+ C = B;
9539
+ B = A;
9540
+ A = T1 + T2 | 0;
9541
+ }
9542
+ A = A + this.A | 0;
9543
+ B = B + this.B | 0;
9544
+ C = C + this.C | 0;
9545
+ D = D + this.D | 0;
9546
+ E = E + this.E | 0;
9547
+ F = F + this.F | 0;
9548
+ G = G + this.G | 0;
9549
+ H = H + this.H | 0;
9550
+ this.set(A, B, C, D, E, F, G, H);
9551
+ }
9552
+ roundClean() {
9553
+ clean(SHA256_W);
9554
+ }
9555
+ destroy() {
9556
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
9557
+ clean(this.buffer);
9558
+ }
9559
+ };
9560
+ var _SHA256 = class extends SHA2_32B {
9561
+ // We cannot use array here since array allows indexing by variable
9562
+ // which means optimizer/compiler cannot use registers.
9563
+ A = SHA256_IV[0] | 0;
9564
+ B = SHA256_IV[1] | 0;
9565
+ C = SHA256_IV[2] | 0;
9566
+ D = SHA256_IV[3] | 0;
9567
+ E = SHA256_IV[4] | 0;
9568
+ F = SHA256_IV[5] | 0;
9569
+ G = SHA256_IV[6] | 0;
9570
+ H = SHA256_IV[7] | 0;
9571
+ constructor() {
9572
+ super(32);
9573
+ }
9574
+ };
9575
+ var sha2564 = /* @__PURE__ */ createHasher(
9576
+ () => new _SHA256(),
9577
+ /* @__PURE__ */ oidNist(1)
9578
+ );
9579
+
9580
+ // node_modules/@noble/curves/utils.js
9581
+ var _0n = /* @__PURE__ */ BigInt(0);
9582
+ var _1n = /* @__PURE__ */ BigInt(1);
9583
+ function abool(value, title = "") {
9584
+ if (typeof value !== "boolean") {
9585
+ const prefix = title && `"${title}" `;
9586
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
9587
+ }
9588
+ return value;
9589
+ }
9590
+ function abignumber(n) {
9591
+ if (typeof n === "bigint") {
9592
+ if (!isPosBig(n))
9593
+ throw new Error("positive bigint expected, got " + n);
9594
+ } else
9595
+ anumber(n);
9596
+ return n;
9597
+ }
9598
+ function numberToHexUnpadded(num) {
9599
+ const hex = abignumber(num).toString(16);
9600
+ return hex.length & 1 ? "0" + hex : hex;
9601
+ }
9602
+ function hexToNumber(hex) {
9603
+ if (typeof hex !== "string")
9604
+ throw new Error("hex string expected, got " + typeof hex);
9605
+ return hex === "" ? _0n : BigInt("0x" + hex);
9606
+ }
9607
+ function bytesToNumberBE(bytes) {
9608
+ return hexToNumber(bytesToHex4(bytes));
9609
+ }
9610
+ function bytesToNumberLE(bytes) {
9611
+ return hexToNumber(bytesToHex4(copyBytes(abytes(bytes)).reverse()));
9612
+ }
9613
+ function numberToBytesBE(n, len) {
9614
+ anumber(len);
9615
+ n = abignumber(n);
9616
+ const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
9617
+ if (res.length !== len)
9618
+ throw new Error("number too large");
9619
+ return res;
9620
+ }
9621
+ function numberToBytesLE(n, len) {
9622
+ return numberToBytesBE(n, len).reverse();
9623
+ }
9624
+ function copyBytes(bytes) {
9625
+ return Uint8Array.from(bytes);
9626
+ }
9627
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
9628
+ function inRange(n, min, max) {
9629
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
9630
+ }
9631
+ function aInRange(title, n, min, max) {
9632
+ if (!inRange(n, min, max))
9633
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
9634
+ }
9635
+ function bitLen(n) {
9636
+ let len;
9637
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
9638
+ ;
9639
+ return len;
9640
+ }
9641
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
9642
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
9643
+ anumber(hashLen, "hashLen");
9644
+ anumber(qByteLen, "qByteLen");
9645
+ if (typeof hmacFn !== "function")
9646
+ throw new Error("hmacFn must be a function");
9647
+ const u8n = (len) => new Uint8Array(len);
9648
+ const NULL = Uint8Array.of();
9649
+ const byte0 = Uint8Array.of(0);
9650
+ const byte1 = Uint8Array.of(1);
9651
+ const _maxDrbgIters = 1e3;
9652
+ let v = u8n(hashLen);
9653
+ let k = u8n(hashLen);
9654
+ let i = 0;
9655
+ const reset = () => {
9656
+ v.fill(1);
9657
+ k.fill(0);
9658
+ i = 0;
9659
+ };
9660
+ const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
9661
+ const reseed = (seed = NULL) => {
9662
+ k = h(byte0, seed);
9663
+ v = h();
9664
+ if (seed.length === 0)
9665
+ return;
9666
+ k = h(byte1, seed);
9667
+ v = h();
9668
+ };
9669
+ const gen = () => {
9670
+ if (i++ >= _maxDrbgIters)
9671
+ throw new Error("drbg: tried max amount of iterations");
9672
+ let len = 0;
9673
+ const out = [];
9674
+ while (len < qByteLen) {
9675
+ v = h();
9676
+ const sl = v.slice();
9677
+ out.push(sl);
9678
+ len += v.length;
9679
+ }
9680
+ return concatBytes(...out);
9681
+ };
9682
+ const genUntil = (seed, pred) => {
9683
+ reset();
9684
+ reseed(seed);
9685
+ let res = void 0;
9686
+ while (!(res = pred(gen())))
9687
+ reseed();
9688
+ reset();
9689
+ return res;
9690
+ };
9691
+ return genUntil;
9692
+ }
9693
+ function validateObject(object, fields = {}, optFields = {}) {
9694
+ if (!object || typeof object !== "object")
9695
+ throw new Error("expected valid options object");
9696
+ function checkField(fieldName, expectedType, isOpt) {
9697
+ const val = object[fieldName];
9698
+ if (isOpt && val === void 0)
9699
+ return;
9700
+ const current = typeof val;
9701
+ if (current !== expectedType || val === null)
9702
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
9703
+ }
9704
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
9705
+ iter(fields, false);
9706
+ iter(optFields, true);
9707
+ }
9708
+ function memoized(fn) {
9709
+ const map = /* @__PURE__ */ new WeakMap();
9710
+ return (arg, ...args) => {
9711
+ const val = map.get(arg);
9712
+ if (val !== void 0)
9713
+ return val;
9714
+ const computed = fn(arg, ...args);
9715
+ map.set(arg, computed);
9716
+ return computed;
9717
+ };
9718
+ }
9719
+
9720
+ // node_modules/@noble/curves/abstract/modular.js
9721
+ var _0n2 = /* @__PURE__ */ BigInt(0);
9722
+ var _1n2 = /* @__PURE__ */ BigInt(1);
9723
+ var _2n = /* @__PURE__ */ BigInt(2);
9724
+ var _3n = /* @__PURE__ */ BigInt(3);
9725
+ var _4n = /* @__PURE__ */ BigInt(4);
9726
+ var _5n = /* @__PURE__ */ BigInt(5);
9727
+ var _7n = /* @__PURE__ */ BigInt(7);
9728
+ var _8n = /* @__PURE__ */ BigInt(8);
9729
+ var _9n = /* @__PURE__ */ BigInt(9);
9730
+ var _16n = /* @__PURE__ */ BigInt(16);
9731
+ function mod(a, b) {
9732
+ const result = a % b;
9733
+ return result >= _0n2 ? result : b + result;
9734
+ }
9735
+ function pow2(x, power, modulo) {
9736
+ let res = x;
9737
+ while (power-- > _0n2) {
9738
+ res *= res;
9739
+ res %= modulo;
9740
+ }
9741
+ return res;
9742
+ }
9743
+ function invert(number, modulo) {
9744
+ if (number === _0n2)
9745
+ throw new Error("invert: expected non-zero number");
9746
+ if (modulo <= _0n2)
9747
+ throw new Error("invert: expected positive modulus, got " + modulo);
9748
+ let a = mod(number, modulo);
9749
+ let b = modulo;
9750
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
9751
+ while (a !== _0n2) {
9752
+ const q = b / a;
9753
+ const r = b % a;
9754
+ const m = x - u * q;
9755
+ const n = y - v * q;
9756
+ b = a, a = r, x = u, y = v, u = m, v = n;
9757
+ }
9758
+ const gcd = b;
9759
+ if (gcd !== _1n2)
9760
+ throw new Error("invert: does not exist");
9761
+ return mod(x, modulo);
9762
+ }
9763
+ function assertIsSquare(Fp, root, n) {
9764
+ if (!Fp.eql(Fp.sqr(root), n))
9765
+ throw new Error("Cannot find square root");
9766
+ }
9767
+ function sqrt3mod4(Fp, n) {
9768
+ const p1div4 = (Fp.ORDER + _1n2) / _4n;
9769
+ const root = Fp.pow(n, p1div4);
9770
+ assertIsSquare(Fp, root, n);
9771
+ return root;
9772
+ }
9773
+ function sqrt5mod8(Fp, n) {
9774
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
9775
+ const n2 = Fp.mul(n, _2n);
9776
+ const v = Fp.pow(n2, p5div8);
9777
+ const nv = Fp.mul(n, v);
9778
+ const i = Fp.mul(Fp.mul(nv, _2n), v);
9779
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
9780
+ assertIsSquare(Fp, root, n);
9781
+ return root;
9782
+ }
9783
+ function sqrt9mod16(P) {
9784
+ const Fp_ = Field(P);
9785
+ const tn = tonelliShanks(P);
9786
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
9787
+ const c2 = tn(Fp_, c1);
9788
+ const c3 = tn(Fp_, Fp_.neg(c1));
9789
+ const c4 = (P + _7n) / _16n;
9790
+ return (Fp, n) => {
9791
+ let tv1 = Fp.pow(n, c4);
9792
+ let tv2 = Fp.mul(tv1, c1);
9793
+ const tv3 = Fp.mul(tv1, c2);
9794
+ const tv4 = Fp.mul(tv1, c3);
9795
+ const e1 = Fp.eql(Fp.sqr(tv2), n);
9796
+ const e2 = Fp.eql(Fp.sqr(tv3), n);
9797
+ tv1 = Fp.cmov(tv1, tv2, e1);
9798
+ tv2 = Fp.cmov(tv4, tv3, e2);
9799
+ const e3 = Fp.eql(Fp.sqr(tv2), n);
9800
+ const root = Fp.cmov(tv1, tv2, e3);
9801
+ assertIsSquare(Fp, root, n);
9802
+ return root;
9803
+ };
9804
+ }
9805
+ function tonelliShanks(P) {
9806
+ if (P < _3n)
9807
+ throw new Error("sqrt is not defined for small field");
9808
+ let Q = P - _1n2;
9809
+ let S = 0;
9810
+ while (Q % _2n === _0n2) {
9811
+ Q /= _2n;
9812
+ S++;
9813
+ }
9814
+ let Z = _2n;
9815
+ const _Fp = Field(P);
9816
+ while (FpLegendre(_Fp, Z) === 1) {
9817
+ if (Z++ > 1e3)
9818
+ throw new Error("Cannot find square root: probably non-prime P");
9819
+ }
9820
+ if (S === 1)
9821
+ return sqrt3mod4;
9822
+ let cc = _Fp.pow(Z, Q);
9823
+ const Q1div2 = (Q + _1n2) / _2n;
9824
+ return function tonelliSlow(Fp, n) {
9825
+ if (Fp.is0(n))
9826
+ return n;
9827
+ if (FpLegendre(Fp, n) !== 1)
9828
+ throw new Error("Cannot find square root");
9829
+ let M = S;
9830
+ let c = Fp.mul(Fp.ONE, cc);
9831
+ let t = Fp.pow(n, Q);
9832
+ let R = Fp.pow(n, Q1div2);
9833
+ while (!Fp.eql(t, Fp.ONE)) {
9834
+ if (Fp.is0(t))
9835
+ return Fp.ZERO;
9836
+ let i = 1;
9837
+ let t_tmp = Fp.sqr(t);
9838
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
9839
+ i++;
9840
+ t_tmp = Fp.sqr(t_tmp);
9841
+ if (i === M)
9842
+ throw new Error("Cannot find square root");
9843
+ }
9844
+ const exponent = _1n2 << BigInt(M - i - 1);
9845
+ const b = Fp.pow(c, exponent);
9846
+ M = i;
9847
+ c = Fp.sqr(b);
9848
+ t = Fp.mul(t, c);
9849
+ R = Fp.mul(R, b);
9850
+ }
9851
+ return R;
9852
+ };
9853
+ }
9854
+ function FpSqrt(P) {
9855
+ if (P % _4n === _3n)
9856
+ return sqrt3mod4;
9857
+ if (P % _8n === _5n)
9858
+ return sqrt5mod8;
9859
+ if (P % _16n === _9n)
9860
+ return sqrt9mod16(P);
9861
+ return tonelliShanks(P);
9862
+ }
9863
+ var FIELD_FIELDS = [
9864
+ "create",
9865
+ "isValid",
9866
+ "is0",
9867
+ "neg",
9868
+ "inv",
9869
+ "sqrt",
9870
+ "sqr",
9871
+ "eql",
9872
+ "add",
9873
+ "sub",
9874
+ "mul",
9875
+ "pow",
9876
+ "div",
9877
+ "addN",
9878
+ "subN",
9879
+ "mulN",
9880
+ "sqrN"
9881
+ ];
9882
+ function validateField(field) {
9883
+ const initial = {
9884
+ ORDER: "bigint",
9885
+ BYTES: "number",
9886
+ BITS: "number"
9887
+ };
9888
+ const opts = FIELD_FIELDS.reduce((map, val) => {
9889
+ map[val] = "function";
9890
+ return map;
9891
+ }, initial);
9892
+ validateObject(field, opts);
9893
+ return field;
9894
+ }
9895
+ function FpPow(Fp, num, power) {
9896
+ if (power < _0n2)
9897
+ throw new Error("invalid exponent, negatives unsupported");
9898
+ if (power === _0n2)
9899
+ return Fp.ONE;
9900
+ if (power === _1n2)
9901
+ return num;
9902
+ let p = Fp.ONE;
9903
+ let d = num;
9904
+ while (power > _0n2) {
9905
+ if (power & _1n2)
9906
+ p = Fp.mul(p, d);
9907
+ d = Fp.sqr(d);
9908
+ power >>= _1n2;
9909
+ }
9910
+ return p;
9911
+ }
9912
+ function FpInvertBatch(Fp, nums, passZero = false) {
9913
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
9914
+ const multipliedAcc = nums.reduce((acc, num, i) => {
9915
+ if (Fp.is0(num))
9916
+ return acc;
9917
+ inverted[i] = acc;
9918
+ return Fp.mul(acc, num);
9919
+ }, Fp.ONE);
9920
+ const invertedAcc = Fp.inv(multipliedAcc);
9921
+ nums.reduceRight((acc, num, i) => {
9922
+ if (Fp.is0(num))
9923
+ return acc;
9924
+ inverted[i] = Fp.mul(acc, inverted[i]);
9925
+ return Fp.mul(acc, num);
9926
+ }, invertedAcc);
9927
+ return inverted;
9928
+ }
9929
+ function FpLegendre(Fp, n) {
9930
+ const p1mod2 = (Fp.ORDER - _1n2) / _2n;
9931
+ const powered = Fp.pow(n, p1mod2);
9932
+ const yes = Fp.eql(powered, Fp.ONE);
9933
+ const zero = Fp.eql(powered, Fp.ZERO);
9934
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
9935
+ if (!yes && !zero && !no)
9936
+ throw new Error("invalid Legendre symbol result");
9937
+ return yes ? 1 : zero ? 0 : -1;
9938
+ }
9939
+ function nLength(n, nBitLength) {
9940
+ if (nBitLength !== void 0)
9941
+ anumber(nBitLength);
9942
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
9943
+ const nByteLength = Math.ceil(_nBitLength / 8);
9944
+ return { nBitLength: _nBitLength, nByteLength };
9945
+ }
9946
+ var _Field = class {
9947
+ ORDER;
9948
+ BITS;
9949
+ BYTES;
9950
+ isLE;
9951
+ ZERO = _0n2;
9952
+ ONE = _1n2;
9953
+ _lengths;
9954
+ _sqrt;
9955
+ // cached sqrt
9956
+ _mod;
9957
+ constructor(ORDER, opts = {}) {
9958
+ if (ORDER <= _0n2)
9959
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
9960
+ let _nbitLength = void 0;
9961
+ this.isLE = false;
9962
+ if (opts != null && typeof opts === "object") {
9963
+ if (typeof opts.BITS === "number")
9964
+ _nbitLength = opts.BITS;
9965
+ if (typeof opts.sqrt === "function")
9966
+ this.sqrt = opts.sqrt;
9967
+ if (typeof opts.isLE === "boolean")
9968
+ this.isLE = opts.isLE;
9969
+ if (opts.allowedLengths)
9970
+ this._lengths = opts.allowedLengths?.slice();
9971
+ if (typeof opts.modFromBytes === "boolean")
9972
+ this._mod = opts.modFromBytes;
9973
+ }
9974
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
9975
+ if (nByteLength > 2048)
9976
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
9977
+ this.ORDER = ORDER;
9978
+ this.BITS = nBitLength;
9979
+ this.BYTES = nByteLength;
9980
+ this._sqrt = void 0;
9981
+ Object.preventExtensions(this);
9982
+ }
9983
+ create(num) {
9984
+ return mod(num, this.ORDER);
9985
+ }
9986
+ isValid(num) {
9987
+ if (typeof num !== "bigint")
9988
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
9989
+ return _0n2 <= num && num < this.ORDER;
9990
+ }
9991
+ is0(num) {
9992
+ return num === _0n2;
9993
+ }
9994
+ // is valid and invertible
9995
+ isValidNot0(num) {
9996
+ return !this.is0(num) && this.isValid(num);
9997
+ }
9998
+ isOdd(num) {
9999
+ return (num & _1n2) === _1n2;
10000
+ }
10001
+ neg(num) {
10002
+ return mod(-num, this.ORDER);
10003
+ }
10004
+ eql(lhs, rhs) {
10005
+ return lhs === rhs;
10006
+ }
10007
+ sqr(num) {
10008
+ return mod(num * num, this.ORDER);
10009
+ }
10010
+ add(lhs, rhs) {
10011
+ return mod(lhs + rhs, this.ORDER);
10012
+ }
10013
+ sub(lhs, rhs) {
10014
+ return mod(lhs - rhs, this.ORDER);
10015
+ }
10016
+ mul(lhs, rhs) {
10017
+ return mod(lhs * rhs, this.ORDER);
10018
+ }
10019
+ pow(num, power) {
10020
+ return FpPow(this, num, power);
10021
+ }
10022
+ div(lhs, rhs) {
10023
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
10024
+ }
10025
+ // Same as above, but doesn't normalize
10026
+ sqrN(num) {
10027
+ return num * num;
10028
+ }
10029
+ addN(lhs, rhs) {
10030
+ return lhs + rhs;
10031
+ }
10032
+ subN(lhs, rhs) {
10033
+ return lhs - rhs;
10034
+ }
10035
+ mulN(lhs, rhs) {
10036
+ return lhs * rhs;
10037
+ }
10038
+ inv(num) {
10039
+ return invert(num, this.ORDER);
10040
+ }
10041
+ sqrt(num) {
10042
+ if (!this._sqrt)
10043
+ this._sqrt = FpSqrt(this.ORDER);
10044
+ return this._sqrt(this, num);
10045
+ }
10046
+ toBytes(num) {
10047
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
10048
+ }
10049
+ fromBytes(bytes, skipValidation = false) {
10050
+ abytes(bytes);
10051
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
10052
+ if (allowedLengths) {
10053
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
10054
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
10055
+ }
10056
+ const padded = new Uint8Array(BYTES);
10057
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
10058
+ bytes = padded;
10059
+ }
10060
+ if (bytes.length !== BYTES)
10061
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
10062
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
10063
+ if (modFromBytes)
10064
+ scalar = mod(scalar, ORDER);
10065
+ if (!skipValidation) {
10066
+ if (!this.isValid(scalar))
10067
+ throw new Error("invalid field element: outside of range 0..ORDER");
10068
+ }
10069
+ return scalar;
10070
+ }
10071
+ // TODO: we don't need it here, move out to separate fn
10072
+ invertBatch(lst) {
10073
+ return FpInvertBatch(this, lst);
10074
+ }
10075
+ // We can't move this out because Fp6, Fp12 implement it
10076
+ // and it's unclear what to return in there.
10077
+ cmov(a, b, condition) {
10078
+ return condition ? b : a;
10079
+ }
10080
+ };
10081
+ function Field(ORDER, opts = {}) {
10082
+ return new _Field(ORDER, opts);
10083
+ }
10084
+ function getFieldBytesLength(fieldOrder) {
10085
+ if (typeof fieldOrder !== "bigint")
10086
+ throw new Error("field order must be bigint");
10087
+ const bitLength = fieldOrder.toString(2).length;
10088
+ return Math.ceil(bitLength / 8);
10089
+ }
10090
+ function getMinHashLength(fieldOrder) {
10091
+ const length = getFieldBytesLength(fieldOrder);
10092
+ return length + Math.ceil(length / 2);
10093
+ }
10094
+ function mapHashToField(key, fieldOrder, isLE = false) {
10095
+ abytes(key);
10096
+ const len = key.length;
10097
+ const fieldLen = getFieldBytesLength(fieldOrder);
10098
+ const minLen = getMinHashLength(fieldOrder);
10099
+ if (len < 16 || len < minLen || len > 1024)
10100
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
10101
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
10102
+ const reduced = mod(num, fieldOrder - _1n2) + _1n2;
10103
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
10104
+ }
10105
+
10106
+ // node_modules/@noble/curves/abstract/curve.js
10107
+ var _0n3 = /* @__PURE__ */ BigInt(0);
10108
+ var _1n3 = /* @__PURE__ */ BigInt(1);
10109
+ function negateCt(condition, item) {
10110
+ const neg = item.negate();
10111
+ return condition ? neg : item;
10112
+ }
10113
+ function normalizeZ(c, points) {
10114
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
10115
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
10116
+ }
10117
+ function validateW(W, bits) {
10118
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
10119
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
10120
+ }
10121
+ function calcWOpts(W, scalarBits) {
10122
+ validateW(W, scalarBits);
10123
+ const windows = Math.ceil(scalarBits / W) + 1;
10124
+ const windowSize = 2 ** (W - 1);
10125
+ const maxNumber = 2 ** W;
10126
+ const mask = bitMask(W);
10127
+ const shiftBy = BigInt(W);
10128
+ return { windows, windowSize, mask, maxNumber, shiftBy };
10129
+ }
10130
+ function calcOffsets(n, window, wOpts) {
10131
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
10132
+ let wbits = Number(n & mask);
10133
+ let nextN = n >> shiftBy;
10134
+ if (wbits > windowSize) {
10135
+ wbits -= maxNumber;
10136
+ nextN += _1n3;
10137
+ }
10138
+ const offsetStart = window * windowSize;
10139
+ const offset = offsetStart + Math.abs(wbits) - 1;
10140
+ const isZero = wbits === 0;
10141
+ const isNeg = wbits < 0;
10142
+ const isNegF = window % 2 !== 0;
10143
+ const offsetF = offsetStart;
10144
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
10145
+ }
10146
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
10147
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
10148
+ function getW(P) {
10149
+ return pointWindowSizes.get(P) || 1;
10150
+ }
10151
+ function assert0(n) {
10152
+ if (n !== _0n3)
10153
+ throw new Error("invalid wNAF");
10154
+ }
10155
+ var wNAF = class {
10156
+ BASE;
10157
+ ZERO;
10158
+ Fn;
10159
+ bits;
10160
+ // Parametrized with a given Point class (not individual point)
10161
+ constructor(Point, bits) {
10162
+ this.BASE = Point.BASE;
10163
+ this.ZERO = Point.ZERO;
10164
+ this.Fn = Point.Fn;
10165
+ this.bits = bits;
10166
+ }
10167
+ // non-const time multiplication ladder
10168
+ _unsafeLadder(elm, n, p = this.ZERO) {
10169
+ let d = elm;
10170
+ while (n > _0n3) {
10171
+ if (n & _1n3)
10172
+ p = p.add(d);
10173
+ d = d.double();
10174
+ n >>= _1n3;
10175
+ }
10176
+ return p;
10177
+ }
10178
+ /**
10179
+ * Creates a wNAF precomputation window. Used for caching.
10180
+ * Default window size is set by `utils.precompute()` and is equal to 8.
10181
+ * Number of precomputed points depends on the curve size:
10182
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
10183
+ * - 𝑊 is the window size
10184
+ * - 𝑛 is the bitlength of the curve order.
10185
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
10186
+ * @param point Point instance
10187
+ * @param W window size
10188
+ * @returns precomputed point tables flattened to a single array
10189
+ */
10190
+ precomputeWindow(point, W) {
10191
+ const { windows, windowSize } = calcWOpts(W, this.bits);
10192
+ const points = [];
10193
+ let p = point;
10194
+ let base = p;
10195
+ for (let window = 0; window < windows; window++) {
10196
+ base = p;
10197
+ points.push(base);
10198
+ for (let i = 1; i < windowSize; i++) {
10199
+ base = base.add(p);
10200
+ points.push(base);
10201
+ }
10202
+ p = base.double();
10203
+ }
10204
+ return points;
10205
+ }
10206
+ /**
10207
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
10208
+ * More compact implementation:
10209
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
10210
+ * @returns real and fake (for const-time) points
10211
+ */
10212
+ wNAF(W, precomputes, n) {
10213
+ if (!this.Fn.isValid(n))
10214
+ throw new Error("invalid scalar");
10215
+ let p = this.ZERO;
10216
+ let f = this.BASE;
10217
+ const wo = calcWOpts(W, this.bits);
10218
+ for (let window = 0; window < wo.windows; window++) {
10219
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
10220
+ n = nextN;
10221
+ if (isZero) {
10222
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
10223
+ } else {
10224
+ p = p.add(negateCt(isNeg, precomputes[offset]));
10225
+ }
10226
+ }
10227
+ assert0(n);
10228
+ return { p, f };
10229
+ }
10230
+ /**
10231
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
10232
+ * @param acc accumulator point to add result of multiplication
10233
+ * @returns point
10234
+ */
10235
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
10236
+ const wo = calcWOpts(W, this.bits);
10237
+ for (let window = 0; window < wo.windows; window++) {
10238
+ if (n === _0n3)
10239
+ break;
10240
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
10241
+ n = nextN;
10242
+ if (isZero) {
10243
+ continue;
10244
+ } else {
10245
+ const item = precomputes[offset];
10246
+ acc = acc.add(isNeg ? item.negate() : item);
10247
+ }
10248
+ }
10249
+ assert0(n);
10250
+ return acc;
10251
+ }
10252
+ getPrecomputes(W, point, transform) {
10253
+ let comp = pointPrecomputes.get(point);
10254
+ if (!comp) {
10255
+ comp = this.precomputeWindow(point, W);
10256
+ if (W !== 1) {
10257
+ if (typeof transform === "function")
10258
+ comp = transform(comp);
10259
+ pointPrecomputes.set(point, comp);
10260
+ }
10261
+ }
10262
+ return comp;
10263
+ }
10264
+ cached(point, scalar, transform) {
10265
+ const W = getW(point);
10266
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
10267
+ }
10268
+ unsafe(point, scalar, transform, prev) {
10269
+ const W = getW(point);
10270
+ if (W === 1)
10271
+ return this._unsafeLadder(point, scalar, prev);
10272
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
10273
+ }
10274
+ // We calculate precomputes for elliptic curve point multiplication
10275
+ // using windowed method. This specifies window size and
10276
+ // stores precomputed values. Usually only base point would be precomputed.
10277
+ createCache(P, W) {
10278
+ validateW(W, this.bits);
10279
+ pointWindowSizes.set(P, W);
10280
+ pointPrecomputes.delete(P);
10281
+ }
10282
+ hasCache(elm) {
10283
+ return getW(elm) !== 1;
10284
+ }
10285
+ };
10286
+ function mulEndoUnsafe(Point, point, k1, k2) {
10287
+ let acc = point;
10288
+ let p1 = Point.ZERO;
10289
+ let p2 = Point.ZERO;
10290
+ while (k1 > _0n3 || k2 > _0n3) {
10291
+ if (k1 & _1n3)
10292
+ p1 = p1.add(acc);
10293
+ if (k2 & _1n3)
10294
+ p2 = p2.add(acc);
10295
+ acc = acc.double();
10296
+ k1 >>= _1n3;
10297
+ k2 >>= _1n3;
10298
+ }
10299
+ return { p1, p2 };
10300
+ }
10301
+ function createField(order, field, isLE) {
10302
+ if (field) {
10303
+ if (field.ORDER !== order)
10304
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
10305
+ validateField(field);
10306
+ return field;
10307
+ } else {
10308
+ return Field(order, { isLE });
10309
+ }
10310
+ }
10311
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
10312
+ if (FpFnLE === void 0)
10313
+ FpFnLE = type === "edwards";
10314
+ if (!CURVE || typeof CURVE !== "object")
10315
+ throw new Error(`expected valid ${type} CURVE object`);
10316
+ for (const p of ["p", "n", "h"]) {
10317
+ const val = CURVE[p];
10318
+ if (!(typeof val === "bigint" && val > _0n3))
10319
+ throw new Error(`CURVE.${p} must be positive bigint`);
10320
+ }
10321
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
10322
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
10323
+ const _b = type === "weierstrass" ? "b" : "d";
10324
+ const params = ["Gx", "Gy", "a", _b];
10325
+ for (const p of params) {
10326
+ if (!Fp.isValid(CURVE[p]))
10327
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
10328
+ }
10329
+ CURVE = Object.freeze(Object.assign({}, CURVE));
10330
+ return { CURVE, Fp, Fn };
10331
+ }
10332
+ function createKeygen(randomSecretKey, getPublicKey2) {
10333
+ return function keygen(seed) {
10334
+ const secretKey = randomSecretKey(seed);
10335
+ return { secretKey, publicKey: getPublicKey2(secretKey) };
10336
+ };
10337
+ }
10338
+
10339
+ // node_modules/@noble/hashes/hmac.js
10340
+ var _HMAC = class {
10341
+ oHash;
10342
+ iHash;
10343
+ blockLen;
10344
+ outputLen;
10345
+ finished = false;
10346
+ destroyed = false;
10347
+ constructor(hash, key) {
10348
+ ahash(hash);
10349
+ abytes(key, void 0, "key");
10350
+ this.iHash = hash.create();
10351
+ if (typeof this.iHash.update !== "function")
10352
+ throw new Error("Expected instance of class which extends utils.Hash");
10353
+ this.blockLen = this.iHash.blockLen;
10354
+ this.outputLen = this.iHash.outputLen;
10355
+ const blockLen = this.blockLen;
10356
+ const pad = new Uint8Array(blockLen);
10357
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
10358
+ for (let i = 0; i < pad.length; i++)
10359
+ pad[i] ^= 54;
10360
+ this.iHash.update(pad);
10361
+ this.oHash = hash.create();
10362
+ for (let i = 0; i < pad.length; i++)
10363
+ pad[i] ^= 54 ^ 92;
10364
+ this.oHash.update(pad);
10365
+ clean(pad);
10366
+ }
10367
+ update(buf) {
10368
+ aexists(this);
10369
+ this.iHash.update(buf);
10370
+ return this;
10371
+ }
10372
+ digestInto(out) {
10373
+ aexists(this);
10374
+ abytes(out, this.outputLen, "output");
10375
+ this.finished = true;
10376
+ this.iHash.digestInto(out);
10377
+ this.oHash.update(out);
10378
+ this.oHash.digestInto(out);
10379
+ this.destroy();
10380
+ }
10381
+ digest() {
10382
+ const out = new Uint8Array(this.oHash.outputLen);
10383
+ this.digestInto(out);
10384
+ return out;
10385
+ }
10386
+ _cloneInto(to) {
10387
+ to ||= Object.create(Object.getPrototypeOf(this), {});
10388
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
10389
+ to = to;
10390
+ to.finished = finished;
10391
+ to.destroyed = destroyed;
10392
+ to.blockLen = blockLen;
10393
+ to.outputLen = outputLen;
10394
+ to.oHash = oHash._cloneInto(to.oHash);
10395
+ to.iHash = iHash._cloneInto(to.iHash);
10396
+ return to;
10397
+ }
10398
+ clone() {
10399
+ return this._cloneInto();
10400
+ }
10401
+ destroy() {
10402
+ this.destroyed = true;
10403
+ this.oHash.destroy();
10404
+ this.iHash.destroy();
10405
+ }
10406
+ };
10407
+ var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
10408
+ hmac.create = (hash, key) => new _HMAC(hash, key);
10409
+
10410
+ // node_modules/@noble/curves/abstract/weierstrass.js
10411
+ var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
10412
+ function _splitEndoScalar(k, basis, n) {
10413
+ const [[a1, b1], [a2, b2]] = basis;
10414
+ const c1 = divNearest(b2 * k, n);
10415
+ const c2 = divNearest(-b1 * k, n);
10416
+ let k1 = k - c1 * a1 - c2 * a2;
10417
+ let k2 = -c1 * b1 - c2 * b2;
10418
+ const k1neg = k1 < _0n4;
10419
+ const k2neg = k2 < _0n4;
10420
+ if (k1neg)
10421
+ k1 = -k1;
10422
+ if (k2neg)
10423
+ k2 = -k2;
10424
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
10425
+ if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
10426
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
10427
+ }
10428
+ return { k1neg, k1, k2neg, k2 };
10429
+ }
10430
+ function validateSigFormat(format) {
10431
+ if (!["compact", "recovered", "der"].includes(format))
10432
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
10433
+ return format;
10434
+ }
10435
+ function validateSigOpts(opts, def) {
10436
+ const optsn = {};
10437
+ for (let optName of Object.keys(def)) {
10438
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
10439
+ }
10440
+ abool(optsn.lowS, "lowS");
10441
+ abool(optsn.prehash, "prehash");
10442
+ if (optsn.format !== void 0)
10443
+ validateSigFormat(optsn.format);
10444
+ return optsn;
10445
+ }
10446
+ var DERErr = class extends Error {
10447
+ constructor(m = "") {
10448
+ super(m);
10449
+ }
10450
+ };
10451
+ var DER = {
10452
+ // asn.1 DER encoding utils
10453
+ Err: DERErr,
10454
+ // Basic building block is TLV (Tag-Length-Value)
10455
+ _tlv: {
10456
+ encode: (tag, data) => {
10457
+ const { Err: E } = DER;
10458
+ if (tag < 0 || tag > 256)
10459
+ throw new E("tlv.encode: wrong tag");
10460
+ if (data.length & 1)
10461
+ throw new E("tlv.encode: unpadded data");
10462
+ const dataLen = data.length / 2;
10463
+ const len = numberToHexUnpadded(dataLen);
10464
+ if (len.length / 2 & 128)
10465
+ throw new E("tlv.encode: long form length too big");
10466
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
10467
+ const t = numberToHexUnpadded(tag);
10468
+ return t + lenLen + len + data;
10469
+ },
10470
+ // v - value, l - left bytes (unparsed)
10471
+ decode(tag, data) {
10472
+ const { Err: E } = DER;
10473
+ let pos = 0;
10474
+ if (tag < 0 || tag > 256)
10475
+ throw new E("tlv.encode: wrong tag");
10476
+ if (data.length < 2 || data[pos++] !== tag)
10477
+ throw new E("tlv.decode: wrong tlv");
10478
+ const first = data[pos++];
10479
+ const isLong = !!(first & 128);
10480
+ let length = 0;
10481
+ if (!isLong)
10482
+ length = first;
10483
+ else {
10484
+ const lenLen = first & 127;
10485
+ if (!lenLen)
10486
+ throw new E("tlv.decode(long): indefinite length not supported");
10487
+ if (lenLen > 4)
10488
+ throw new E("tlv.decode(long): byte length is too big");
10489
+ const lengthBytes = data.subarray(pos, pos + lenLen);
10490
+ if (lengthBytes.length !== lenLen)
10491
+ throw new E("tlv.decode: length bytes not complete");
10492
+ if (lengthBytes[0] === 0)
10493
+ throw new E("tlv.decode(long): zero leftmost byte");
10494
+ for (const b of lengthBytes)
10495
+ length = length << 8 | b;
10496
+ pos += lenLen;
10497
+ if (length < 128)
10498
+ throw new E("tlv.decode(long): not minimal encoding");
10499
+ }
10500
+ const v = data.subarray(pos, pos + length);
10501
+ if (v.length !== length)
10502
+ throw new E("tlv.decode: wrong value length");
10503
+ return { v, l: data.subarray(pos + length) };
10504
+ }
10505
+ },
10506
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
10507
+ // since we always use positive integers here. It must always be empty:
10508
+ // - add zero byte if exists
10509
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
10510
+ _int: {
10511
+ encode(num) {
10512
+ const { Err: E } = DER;
10513
+ if (num < _0n4)
10514
+ throw new E("integer: negative integers are not allowed");
10515
+ let hex = numberToHexUnpadded(num);
10516
+ if (Number.parseInt(hex[0], 16) & 8)
10517
+ hex = "00" + hex;
10518
+ if (hex.length & 1)
10519
+ throw new E("unexpected DER parsing assertion: unpadded hex");
10520
+ return hex;
10521
+ },
10522
+ decode(data) {
10523
+ const { Err: E } = DER;
10524
+ if (data[0] & 128)
10525
+ throw new E("invalid signature integer: negative");
10526
+ if (data[0] === 0 && !(data[1] & 128))
10527
+ throw new E("invalid signature integer: unnecessary leading zero");
10528
+ return bytesToNumberBE(data);
10529
+ }
10530
+ },
10531
+ toSig(bytes) {
10532
+ const { Err: E, _int: int, _tlv: tlv } = DER;
10533
+ const data = abytes(bytes, void 0, "signature");
10534
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
10535
+ if (seqLeftBytes.length)
10536
+ throw new E("invalid signature: left bytes after parsing");
10537
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
10538
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
10539
+ if (sLeftBytes.length)
10540
+ throw new E("invalid signature: left bytes after parsing");
10541
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
10542
+ },
10543
+ hexFromSig(sig) {
10544
+ const { _tlv: tlv, _int: int } = DER;
10545
+ const rs = tlv.encode(2, int.encode(sig.r));
10546
+ const ss = tlv.encode(2, int.encode(sig.s));
10547
+ const seq = rs + ss;
10548
+ return tlv.encode(48, seq);
10549
+ }
10550
+ };
10551
+ var _0n4 = BigInt(0);
10552
+ var _1n4 = BigInt(1);
10553
+ var _2n2 = BigInt(2);
10554
+ var _3n2 = BigInt(3);
10555
+ var _4n2 = BigInt(4);
10556
+ function weierstrass(params, extraOpts = {}) {
10557
+ const validated = createCurveFields("weierstrass", params, extraOpts);
10558
+ const { Fp, Fn } = validated;
10559
+ let CURVE = validated.CURVE;
10560
+ const { h: cofactor, n: CURVE_ORDER2 } = CURVE;
10561
+ validateObject(extraOpts, {}, {
10562
+ allowInfinityPoint: "boolean",
10563
+ clearCofactor: "function",
10564
+ isTorsionFree: "function",
10565
+ fromBytes: "function",
10566
+ toBytes: "function",
10567
+ endo: "object"
10568
+ });
10569
+ const { endo } = extraOpts;
10570
+ if (endo) {
10571
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
10572
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
10573
+ }
10574
+ }
10575
+ const lengths = getWLengths(Fp, Fn);
10576
+ function assertCompressionIsSupported() {
10577
+ if (!Fp.isOdd)
10578
+ throw new Error("compression is not supported: Field does not have .isOdd()");
10579
+ }
10580
+ function pointToBytes(_c, point, isCompressed) {
10581
+ const { x, y } = point.toAffine();
10582
+ const bx = Fp.toBytes(x);
10583
+ abool(isCompressed, "isCompressed");
10584
+ if (isCompressed) {
10585
+ assertCompressionIsSupported();
10586
+ const hasEvenY = !Fp.isOdd(y);
10587
+ return concatBytes(pprefix(hasEvenY), bx);
10588
+ } else {
10589
+ return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
10590
+ }
10591
+ }
10592
+ function pointFromBytes(bytes) {
10593
+ abytes(bytes, void 0, "Point");
10594
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
10595
+ const length = bytes.length;
10596
+ const head = bytes[0];
10597
+ const tail = bytes.subarray(1);
10598
+ if (length === comp && (head === 2 || head === 3)) {
10599
+ const x = Fp.fromBytes(tail);
10600
+ if (!Fp.isValid(x))
10601
+ throw new Error("bad point: is not on curve, wrong x");
10602
+ const y2 = weierstrassEquation(x);
10603
+ let y;
10604
+ try {
10605
+ y = Fp.sqrt(y2);
10606
+ } catch (sqrtError) {
10607
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
10608
+ throw new Error("bad point: is not on curve, sqrt error" + err);
10609
+ }
10610
+ assertCompressionIsSupported();
10611
+ const evenY = Fp.isOdd(y);
10612
+ const evenH = (head & 1) === 1;
10613
+ if (evenH !== evenY)
10614
+ y = Fp.neg(y);
10615
+ return { x, y };
10616
+ } else if (length === uncomp && head === 4) {
10617
+ const L = Fp.BYTES;
10618
+ const x = Fp.fromBytes(tail.subarray(0, L));
10619
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
10620
+ if (!isValidXY(x, y))
10621
+ throw new Error("bad point: is not on curve");
10622
+ return { x, y };
10623
+ } else {
10624
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
10625
+ }
10626
+ }
10627
+ const encodePoint = extraOpts.toBytes || pointToBytes;
10628
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
10629
+ function weierstrassEquation(x) {
10630
+ const x2 = Fp.sqr(x);
10631
+ const x3 = Fp.mul(x2, x);
10632
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
10633
+ }
10634
+ function isValidXY(x, y) {
10635
+ const left = Fp.sqr(y);
10636
+ const right = weierstrassEquation(x);
10637
+ return Fp.eql(left, right);
10638
+ }
10639
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
10640
+ throw new Error("bad curve params: generator point");
10641
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
10642
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
10643
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
10644
+ throw new Error("bad curve params: a or b");
10645
+ function acoord(title, n, banZero = false) {
10646
+ if (!Fp.isValid(n) || banZero && Fp.is0(n))
10647
+ throw new Error(`bad point coordinate ${title}`);
10648
+ return n;
10649
+ }
10650
+ function aprjpoint(other) {
10651
+ if (!(other instanceof Point))
10652
+ throw new Error("Weierstrass Point expected");
10653
+ }
10654
+ function splitEndoScalarN(k) {
10655
+ if (!endo || !endo.basises)
10656
+ throw new Error("no endo");
10657
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
10658
+ }
10659
+ const toAffineMemo = memoized((p, iz) => {
10660
+ const { X, Y, Z } = p;
10661
+ if (Fp.eql(Z, Fp.ONE))
10662
+ return { x: X, y: Y };
10663
+ const is0 = p.is0();
10664
+ if (iz == null)
10665
+ iz = is0 ? Fp.ONE : Fp.inv(Z);
10666
+ const x = Fp.mul(X, iz);
10667
+ const y = Fp.mul(Y, iz);
10668
+ const zz = Fp.mul(Z, iz);
10669
+ if (is0)
10670
+ return { x: Fp.ZERO, y: Fp.ZERO };
10671
+ if (!Fp.eql(zz, Fp.ONE))
10672
+ throw new Error("invZ was invalid");
10673
+ return { x, y };
10674
+ });
10675
+ const assertValidMemo = memoized((p) => {
10676
+ if (p.is0()) {
10677
+ if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
10678
+ return;
10679
+ throw new Error("bad point: ZERO");
10680
+ }
10681
+ const { x, y } = p.toAffine();
10682
+ if (!Fp.isValid(x) || !Fp.isValid(y))
10683
+ throw new Error("bad point: x or y not field elements");
10684
+ if (!isValidXY(x, y))
10685
+ throw new Error("bad point: equation left != right");
10686
+ if (!p.isTorsionFree())
10687
+ throw new Error("bad point: not in prime-order subgroup");
10688
+ return true;
10689
+ });
10690
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
10691
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
10692
+ k1p = negateCt(k1neg, k1p);
10693
+ k2p = negateCt(k2neg, k2p);
10694
+ return k1p.add(k2p);
10695
+ }
10696
+ class Point {
10697
+ // base / generator point
10698
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
10699
+ // zero / infinity / identity point
10700
+ static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
10701
+ // 0, 1, 0
10702
+ // math field
10703
+ static Fp = Fp;
10704
+ // scalar field
10705
+ static Fn = Fn;
10706
+ X;
10707
+ Y;
10708
+ Z;
10709
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
10710
+ constructor(X, Y, Z) {
10711
+ this.X = acoord("x", X);
10712
+ this.Y = acoord("y", Y, true);
10713
+ this.Z = acoord("z", Z);
10714
+ Object.freeze(this);
10715
+ }
10716
+ static CURVE() {
10717
+ return CURVE;
10718
+ }
10719
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
10720
+ static fromAffine(p) {
10721
+ const { x, y } = p || {};
10722
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
10723
+ throw new Error("invalid affine point");
10724
+ if (p instanceof Point)
10725
+ throw new Error("projective point not allowed");
10726
+ if (Fp.is0(x) && Fp.is0(y))
10727
+ return Point.ZERO;
10728
+ return new Point(x, y, Fp.ONE);
10729
+ }
10730
+ static fromBytes(bytes) {
10731
+ const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
10732
+ P.assertValidity();
10733
+ return P;
10734
+ }
10735
+ static fromHex(hex) {
10736
+ return Point.fromBytes(hexToBytes2(hex));
10737
+ }
10738
+ get x() {
10739
+ return this.toAffine().x;
10740
+ }
10741
+ get y() {
10742
+ return this.toAffine().y;
10743
+ }
10744
+ /**
10745
+ *
10746
+ * @param windowSize
10747
+ * @param isLazy true will defer table computation until the first multiplication
10748
+ * @returns
10749
+ */
10750
+ precompute(windowSize = 8, isLazy = true) {
10751
+ wnaf.createCache(this, windowSize);
10752
+ if (!isLazy)
10753
+ this.multiply(_3n2);
10754
+ return this;
10755
+ }
10756
+ // TODO: return `this`
10757
+ /** A point on curve is valid if it conforms to equation. */
10758
+ assertValidity() {
10759
+ assertValidMemo(this);
10760
+ }
10761
+ hasEvenY() {
10762
+ const { y } = this.toAffine();
10763
+ if (!Fp.isOdd)
10764
+ throw new Error("Field doesn't support isOdd");
10765
+ return !Fp.isOdd(y);
10766
+ }
10767
+ /** Compare one point to another. */
10768
+ equals(other) {
10769
+ aprjpoint(other);
10770
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10771
+ const { X: X2, Y: Y2, Z: Z2 } = other;
10772
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
10773
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
10774
+ return U1 && U2;
10775
+ }
10776
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
10777
+ negate() {
10778
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
10779
+ }
10780
+ // Renes-Costello-Batina exception-free doubling formula.
10781
+ // There is 30% faster Jacobian formula, but it is not complete.
10782
+ // https://eprint.iacr.org/2015/1060, algorithm 3
10783
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
10784
+ double() {
10785
+ const { a, b } = CURVE;
10786
+ const b3 = Fp.mul(b, _3n2);
10787
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10788
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
10789
+ let t0 = Fp.mul(X1, X1);
10790
+ let t1 = Fp.mul(Y1, Y1);
10791
+ let t2 = Fp.mul(Z1, Z1);
10792
+ let t3 = Fp.mul(X1, Y1);
10793
+ t3 = Fp.add(t3, t3);
10794
+ Z3 = Fp.mul(X1, Z1);
10795
+ Z3 = Fp.add(Z3, Z3);
10796
+ X3 = Fp.mul(a, Z3);
10797
+ Y3 = Fp.mul(b3, t2);
10798
+ Y3 = Fp.add(X3, Y3);
10799
+ X3 = Fp.sub(t1, Y3);
10800
+ Y3 = Fp.add(t1, Y3);
10801
+ Y3 = Fp.mul(X3, Y3);
10802
+ X3 = Fp.mul(t3, X3);
10803
+ Z3 = Fp.mul(b3, Z3);
10804
+ t2 = Fp.mul(a, t2);
10805
+ t3 = Fp.sub(t0, t2);
10806
+ t3 = Fp.mul(a, t3);
10807
+ t3 = Fp.add(t3, Z3);
10808
+ Z3 = Fp.add(t0, t0);
10809
+ t0 = Fp.add(Z3, t0);
10810
+ t0 = Fp.add(t0, t2);
10811
+ t0 = Fp.mul(t0, t3);
10812
+ Y3 = Fp.add(Y3, t0);
10813
+ t2 = Fp.mul(Y1, Z1);
10814
+ t2 = Fp.add(t2, t2);
10815
+ t0 = Fp.mul(t2, t3);
10816
+ X3 = Fp.sub(X3, t0);
10817
+ Z3 = Fp.mul(t2, t1);
10818
+ Z3 = Fp.add(Z3, Z3);
10819
+ Z3 = Fp.add(Z3, Z3);
10820
+ return new Point(X3, Y3, Z3);
10821
+ }
10822
+ // Renes-Costello-Batina exception-free addition formula.
10823
+ // There is 30% faster Jacobian formula, but it is not complete.
10824
+ // https://eprint.iacr.org/2015/1060, algorithm 1
10825
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
10826
+ add(other) {
10827
+ aprjpoint(other);
10828
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10829
+ const { X: X2, Y: Y2, Z: Z2 } = other;
10830
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
10831
+ const a = CURVE.a;
10832
+ const b3 = Fp.mul(CURVE.b, _3n2);
10833
+ let t0 = Fp.mul(X1, X2);
10834
+ let t1 = Fp.mul(Y1, Y2);
10835
+ let t2 = Fp.mul(Z1, Z2);
10836
+ let t3 = Fp.add(X1, Y1);
10837
+ let t4 = Fp.add(X2, Y2);
10838
+ t3 = Fp.mul(t3, t4);
10839
+ t4 = Fp.add(t0, t1);
10840
+ t3 = Fp.sub(t3, t4);
10841
+ t4 = Fp.add(X1, Z1);
10842
+ let t5 = Fp.add(X2, Z2);
10843
+ t4 = Fp.mul(t4, t5);
10844
+ t5 = Fp.add(t0, t2);
10845
+ t4 = Fp.sub(t4, t5);
10846
+ t5 = Fp.add(Y1, Z1);
10847
+ X3 = Fp.add(Y2, Z2);
10848
+ t5 = Fp.mul(t5, X3);
10849
+ X3 = Fp.add(t1, t2);
10850
+ t5 = Fp.sub(t5, X3);
10851
+ Z3 = Fp.mul(a, t4);
10852
+ X3 = Fp.mul(b3, t2);
10853
+ Z3 = Fp.add(X3, Z3);
10854
+ X3 = Fp.sub(t1, Z3);
10855
+ Z3 = Fp.add(t1, Z3);
10856
+ Y3 = Fp.mul(X3, Z3);
10857
+ t1 = Fp.add(t0, t0);
10858
+ t1 = Fp.add(t1, t0);
10859
+ t2 = Fp.mul(a, t2);
10860
+ t4 = Fp.mul(b3, t4);
10861
+ t1 = Fp.add(t1, t2);
10862
+ t2 = Fp.sub(t0, t2);
10863
+ t2 = Fp.mul(a, t2);
10864
+ t4 = Fp.add(t4, t2);
10865
+ t0 = Fp.mul(t1, t4);
10866
+ Y3 = Fp.add(Y3, t0);
10867
+ t0 = Fp.mul(t5, t4);
10868
+ X3 = Fp.mul(t3, X3);
10869
+ X3 = Fp.sub(X3, t0);
10870
+ t0 = Fp.mul(t3, t1);
10871
+ Z3 = Fp.mul(t5, Z3);
10872
+ Z3 = Fp.add(Z3, t0);
10873
+ return new Point(X3, Y3, Z3);
10874
+ }
10875
+ subtract(other) {
10876
+ return this.add(other.negate());
10877
+ }
10878
+ is0() {
10879
+ return this.equals(Point.ZERO);
10880
+ }
10881
+ /**
10882
+ * Constant time multiplication.
10883
+ * Uses wNAF method. Windowed method may be 10% faster,
10884
+ * but takes 2x longer to generate and consumes 2x memory.
10885
+ * Uses precomputes when available.
10886
+ * Uses endomorphism for Koblitz curves.
10887
+ * @param scalar by which the point would be multiplied
10888
+ * @returns New point
10889
+ */
10890
+ multiply(scalar) {
10891
+ const { endo: endo2 } = extraOpts;
10892
+ if (!Fn.isValidNot0(scalar))
10893
+ throw new Error("invalid scalar: out of range");
10894
+ let point, fake;
10895
+ const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
10896
+ if (endo2) {
10897
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
10898
+ const { p: k1p, f: k1f } = mul(k1);
10899
+ const { p: k2p, f: k2f } = mul(k2);
10900
+ fake = k1f.add(k2f);
10901
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
10902
+ } else {
10903
+ const { p, f } = mul(scalar);
10904
+ point = p;
10905
+ fake = f;
10906
+ }
10907
+ return normalizeZ(Point, [point, fake])[0];
10908
+ }
10909
+ /**
10910
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
10911
+ * It's faster, but should only be used when you don't care about
10912
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
10913
+ */
10914
+ multiplyUnsafe(sc) {
10915
+ const { endo: endo2 } = extraOpts;
10916
+ const p = this;
10917
+ if (!Fn.isValid(sc))
10918
+ throw new Error("invalid scalar: out of range");
10919
+ if (sc === _0n4 || p.is0())
10920
+ return Point.ZERO;
10921
+ if (sc === _1n4)
10922
+ return p;
10923
+ if (wnaf.hasCache(this))
10924
+ return this.multiply(sc);
10925
+ if (endo2) {
10926
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
10927
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
10928
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
10929
+ } else {
10930
+ return wnaf.unsafe(p, sc);
10931
+ }
10932
+ }
10933
+ /**
10934
+ * Converts Projective point to affine (x, y) coordinates.
10935
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
10936
+ */
10937
+ toAffine(invertedZ) {
10938
+ return toAffineMemo(this, invertedZ);
10939
+ }
10940
+ /**
10941
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
10942
+ * Always torsion-free for cofactor=1 curves.
10943
+ */
10944
+ isTorsionFree() {
10945
+ const { isTorsionFree } = extraOpts;
10946
+ if (cofactor === _1n4)
10947
+ return true;
10948
+ if (isTorsionFree)
10949
+ return isTorsionFree(Point, this);
10950
+ return wnaf.unsafe(this, CURVE_ORDER2).is0();
10951
+ }
10952
+ clearCofactor() {
10953
+ const { clearCofactor } = extraOpts;
10954
+ if (cofactor === _1n4)
10955
+ return this;
10956
+ if (clearCofactor)
10957
+ return clearCofactor(Point, this);
10958
+ return this.multiplyUnsafe(cofactor);
10959
+ }
10960
+ isSmallOrder() {
10961
+ return this.multiplyUnsafe(cofactor).is0();
10962
+ }
10963
+ toBytes(isCompressed = true) {
10964
+ abool(isCompressed, "isCompressed");
10965
+ this.assertValidity();
10966
+ return encodePoint(Point, this, isCompressed);
10967
+ }
10968
+ toHex(isCompressed = true) {
10969
+ return bytesToHex4(this.toBytes(isCompressed));
10970
+ }
10971
+ toString() {
10972
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
10973
+ }
10974
+ }
10975
+ const bits = Fn.BITS;
10976
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
10977
+ Point.BASE.precompute(8);
10978
+ return Point;
10979
+ }
10980
+ function pprefix(hasEvenY) {
10981
+ return Uint8Array.of(hasEvenY ? 2 : 3);
10982
+ }
10983
+ function getWLengths(Fp, Fn) {
10984
+ return {
10985
+ secretKey: Fn.BYTES,
10986
+ publicKey: 1 + Fp.BYTES,
10987
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
10988
+ publicKeyHasPrefix: true,
10989
+ signature: 2 * Fn.BYTES
10990
+ };
10991
+ }
10992
+ function ecdh(Point, ecdhOpts = {}) {
10993
+ const { Fn } = Point;
10994
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
10995
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
10996
+ function isValidSecretKey(secretKey) {
10997
+ try {
10998
+ const num = Fn.fromBytes(secretKey);
10999
+ return Fn.isValidNot0(num);
11000
+ } catch (error) {
11001
+ return false;
11002
+ }
11003
+ }
11004
+ function isValidPublicKey(publicKey, isCompressed) {
11005
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
11006
+ try {
11007
+ const l = publicKey.length;
11008
+ if (isCompressed === true && l !== comp)
11009
+ return false;
11010
+ if (isCompressed === false && l !== publicKeyUncompressed)
11011
+ return false;
11012
+ return !!Point.fromBytes(publicKey);
11013
+ } catch (error) {
11014
+ return false;
11015
+ }
11016
+ }
11017
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
11018
+ return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
11019
+ }
11020
+ function getPublicKey2(secretKey, isCompressed = true) {
11021
+ return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
11022
+ }
11023
+ function isProbPub(item) {
11024
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
11025
+ if (!isBytes(item))
11026
+ return void 0;
11027
+ if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
11028
+ return void 0;
11029
+ const l = abytes(item, void 0, "key").length;
11030
+ return l === publicKey || l === publicKeyUncompressed;
11031
+ }
11032
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
11033
+ if (isProbPub(secretKeyA) === true)
11034
+ throw new Error("first arg must be private key");
11035
+ if (isProbPub(publicKeyB) === false)
11036
+ throw new Error("second arg must be public key");
11037
+ const s = Fn.fromBytes(secretKeyA);
11038
+ const b = Point.fromBytes(publicKeyB);
11039
+ return b.multiply(s).toBytes(isCompressed);
11040
+ }
11041
+ const utils = {
11042
+ isValidSecretKey,
11043
+ isValidPublicKey,
11044
+ randomSecretKey
11045
+ };
11046
+ const keygen = createKeygen(randomSecretKey, getPublicKey2);
11047
+ return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
11048
+ }
11049
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
11050
+ ahash(hash);
11051
+ validateObject(ecdsaOpts, {}, {
11052
+ hmac: "function",
11053
+ lowS: "boolean",
11054
+ randomBytes: "function",
11055
+ bits2int: "function",
11056
+ bits2int_modN: "function"
11057
+ });
11058
+ ecdsaOpts = Object.assign({}, ecdsaOpts);
11059
+ const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
11060
+ const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
11061
+ const { Fp, Fn } = Point;
11062
+ const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn;
11063
+ const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
11064
+ const defaultSigOpts = {
11065
+ prehash: true,
11066
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
11067
+ format: "compact",
11068
+ extraEntropy: false
11069
+ };
11070
+ const hasLargeCofactor = CURVE_ORDER2 * _2n2 < Fp.ORDER;
11071
+ function isBiggerThanHalfOrder(number) {
11072
+ const HALF = CURVE_ORDER2 >> _1n4;
11073
+ return number > HALF;
11074
+ }
11075
+ function validateRS(title, num) {
11076
+ if (!Fn.isValidNot0(num))
11077
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
11078
+ return num;
11079
+ }
11080
+ function assertSmallCofactor() {
11081
+ if (hasLargeCofactor)
11082
+ throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
11083
+ }
11084
+ function validateSigLength(bytes, format) {
11085
+ validateSigFormat(format);
11086
+ const size = lengths.signature;
11087
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
11088
+ return abytes(bytes, sizer);
11089
+ }
11090
+ class Signature {
11091
+ r;
11092
+ s;
11093
+ recovery;
11094
+ constructor(r, s, recovery) {
11095
+ this.r = validateRS("r", r);
11096
+ this.s = validateRS("s", s);
11097
+ if (recovery != null) {
11098
+ assertSmallCofactor();
11099
+ if (![0, 1, 2, 3].includes(recovery))
11100
+ throw new Error("invalid recovery id");
11101
+ this.recovery = recovery;
11102
+ }
11103
+ Object.freeze(this);
11104
+ }
11105
+ static fromBytes(bytes, format = defaultSigOpts.format) {
11106
+ validateSigLength(bytes, format);
11107
+ let recid;
11108
+ if (format === "der") {
11109
+ const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
11110
+ return new Signature(r2, s2);
11111
+ }
11112
+ if (format === "recovered") {
11113
+ recid = bytes[0];
11114
+ format = "compact";
11115
+ bytes = bytes.subarray(1);
11116
+ }
11117
+ const L = lengths.signature / 2;
11118
+ const r = bytes.subarray(0, L);
11119
+ const s = bytes.subarray(L, L * 2);
11120
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
11121
+ }
11122
+ static fromHex(hex, format) {
11123
+ return this.fromBytes(hexToBytes2(hex), format);
11124
+ }
11125
+ assertRecovery() {
11126
+ const { recovery } = this;
11127
+ if (recovery == null)
11128
+ throw new Error("invalid recovery id: must be present");
11129
+ return recovery;
11130
+ }
11131
+ addRecoveryBit(recovery) {
11132
+ return new Signature(this.r, this.s, recovery);
11133
+ }
11134
+ recoverPublicKey(messageHash) {
11135
+ const { r, s } = this;
11136
+ const recovery = this.assertRecovery();
11137
+ const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER2 : r;
11138
+ if (!Fp.isValid(radj))
11139
+ throw new Error("invalid recovery id: sig.r+curve.n != R.x");
11140
+ const x = Fp.toBytes(radj);
11141
+ const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
11142
+ const ir = Fn.inv(radj);
11143
+ const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
11144
+ const u1 = Fn.create(-h * ir);
11145
+ const u2 = Fn.create(s * ir);
11146
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
11147
+ if (Q.is0())
11148
+ throw new Error("invalid recovery: point at infinify");
11149
+ Q.assertValidity();
11150
+ return Q;
11151
+ }
11152
+ // Signatures should be low-s, to prevent malleability.
11153
+ hasHighS() {
11154
+ return isBiggerThanHalfOrder(this.s);
11155
+ }
11156
+ toBytes(format = defaultSigOpts.format) {
11157
+ validateSigFormat(format);
11158
+ if (format === "der")
11159
+ return hexToBytes2(DER.hexFromSig(this));
11160
+ const { r, s } = this;
11161
+ const rb = Fn.toBytes(r);
11162
+ const sb = Fn.toBytes(s);
11163
+ if (format === "recovered") {
11164
+ assertSmallCofactor();
11165
+ return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
11166
+ }
11167
+ return concatBytes(rb, sb);
11168
+ }
11169
+ toHex(format) {
11170
+ return bytesToHex4(this.toBytes(format));
11171
+ }
11172
+ }
11173
+ const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
11174
+ if (bytes.length > 8192)
11175
+ throw new Error("input is too large");
11176
+ const num = bytesToNumberBE(bytes);
11177
+ const delta = bytes.length * 8 - fnBits;
11178
+ return delta > 0 ? num >> BigInt(delta) : num;
11179
+ };
11180
+ const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
11181
+ return Fn.create(bits2int(bytes));
11182
+ };
11183
+ const ORDER_MASK = bitMask(fnBits);
11184
+ function int2octets(num) {
11185
+ aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
11186
+ return Fn.toBytes(num);
11187
+ }
11188
+ function validateMsgAndHash(message, prehash) {
11189
+ abytes(message, void 0, "message");
11190
+ return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
11191
+ }
11192
+ function prepSig(message, secretKey, opts) {
11193
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
11194
+ message = validateMsgAndHash(message, prehash);
11195
+ const h1int = bits2int_modN(message);
11196
+ const d = Fn.fromBytes(secretKey);
11197
+ if (!Fn.isValidNot0(d))
11198
+ throw new Error("invalid private key");
11199
+ const seedArgs = [int2octets(d), int2octets(h1int)];
11200
+ if (extraEntropy != null && extraEntropy !== false) {
11201
+ const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
11202
+ seedArgs.push(abytes(e, void 0, "extraEntropy"));
11203
+ }
11204
+ const seed = concatBytes(...seedArgs);
11205
+ const m = h1int;
11206
+ function k2sig(kBytes) {
11207
+ const k = bits2int(kBytes);
11208
+ if (!Fn.isValidNot0(k))
11209
+ return;
11210
+ const ik = Fn.inv(k);
11211
+ const q = Point.BASE.multiply(k).toAffine();
11212
+ const r = Fn.create(q.x);
11213
+ if (r === _0n4)
11214
+ return;
11215
+ const s = Fn.create(ik * Fn.create(m + r * d));
11216
+ if (s === _0n4)
11217
+ return;
11218
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
11219
+ let normS = s;
11220
+ if (lowS && isBiggerThanHalfOrder(s)) {
11221
+ normS = Fn.neg(s);
11222
+ recovery ^= 1;
11223
+ }
11224
+ return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
11225
+ }
11226
+ return { seed, k2sig };
11227
+ }
11228
+ function sign(message, secretKey, opts = {}) {
11229
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
11230
+ const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
11231
+ const sig = drbg(seed, k2sig);
11232
+ return sig.toBytes(opts.format);
11233
+ }
11234
+ function verify(signature, message, publicKey, opts = {}) {
11235
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
11236
+ publicKey = abytes(publicKey, void 0, "publicKey");
11237
+ message = validateMsgAndHash(message, prehash);
11238
+ if (!isBytes(signature)) {
11239
+ const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
11240
+ throw new Error("verify expects Uint8Array signature" + end);
11241
+ }
11242
+ validateSigLength(signature, format);
11243
+ try {
11244
+ const sig = Signature.fromBytes(signature, format);
11245
+ const P = Point.fromBytes(publicKey);
11246
+ if (lowS && sig.hasHighS())
11247
+ return false;
11248
+ const { r, s } = sig;
11249
+ const h = bits2int_modN(message);
11250
+ const is = Fn.inv(s);
11251
+ const u1 = Fn.create(h * is);
11252
+ const u2 = Fn.create(r * is);
11253
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
11254
+ if (R.is0())
11255
+ return false;
11256
+ const v = Fn.create(R.x);
11257
+ return v === r;
11258
+ } catch (e) {
11259
+ return false;
11260
+ }
11261
+ }
11262
+ function recoverPublicKey(signature, message, opts = {}) {
11263
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
11264
+ message = validateMsgAndHash(message, prehash);
11265
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
11266
+ }
11267
+ return Object.freeze({
11268
+ keygen,
11269
+ getPublicKey: getPublicKey2,
11270
+ getSharedSecret,
11271
+ utils,
11272
+ lengths,
11273
+ Point,
11274
+ sign,
11275
+ verify,
11276
+ recoverPublicKey,
11277
+ Signature,
11278
+ hash
11279
+ });
11280
+ }
11281
+
11282
+ // node_modules/@noble/curves/secp256k1.js
11283
+ var secp256k1_CURVE = {
11284
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
11285
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
11286
+ h: BigInt(1),
11287
+ a: BigInt(0),
11288
+ b: BigInt(7),
11289
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
11290
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
11291
+ };
11292
+ var secp256k1_ENDO = {
11293
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
11294
+ basises: [
11295
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
11296
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
11297
+ ]
11298
+ };
11299
+ var _2n3 = /* @__PURE__ */ BigInt(2);
11300
+ function sqrtMod(y) {
11301
+ const P = secp256k1_CURVE.p;
11302
+ const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
11303
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
11304
+ const b2 = y * y * y % P;
11305
+ const b3 = b2 * b2 * y % P;
11306
+ const b6 = pow2(b3, _3n3, P) * b3 % P;
11307
+ const b9 = pow2(b6, _3n3, P) * b3 % P;
11308
+ const b11 = pow2(b9, _2n3, P) * b2 % P;
11309
+ const b22 = pow2(b11, _11n, P) * b11 % P;
11310
+ const b44 = pow2(b22, _22n, P) * b22 % P;
11311
+ const b88 = pow2(b44, _44n, P) * b44 % P;
11312
+ const b176 = pow2(b88, _88n, P) * b88 % P;
11313
+ const b220 = pow2(b176, _44n, P) * b44 % P;
11314
+ const b223 = pow2(b220, _3n3, P) * b3 % P;
11315
+ const t1 = pow2(b223, _23n, P) * b22 % P;
11316
+ const t2 = pow2(t1, _6n, P) * b2 % P;
11317
+ const root = pow2(t2, _2n3, P);
11318
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
11319
+ throw new Error("Cannot find square root");
11320
+ return root;
11321
+ }
11322
+ var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
11323
+ var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
11324
+ Fp: Fpk1,
11325
+ endo: secp256k1_ENDO
11326
+ });
11327
+ var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha2564);
11328
+
11329
+ // modules/market/MarketModule.ts
11330
+ function hexToBytes3(hex) {
11331
+ const len = hex.length >> 1;
11332
+ const bytes = new Uint8Array(len);
11333
+ for (let i = 0; i < len; i++) {
11334
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
11335
+ }
11336
+ return bytes;
11337
+ }
11338
+ function signRequest(body, privateKeyHex) {
11339
+ const timestamp = Date.now();
11340
+ const payload = JSON.stringify({ body, timestamp });
11341
+ const messageHash = sha2564(new TextEncoder().encode(payload));
11342
+ const privateKeyBytes = hexToBytes3(privateKeyHex);
11343
+ const signature = secp256k1.sign(messageHash, privateKeyBytes);
11344
+ const publicKey = bytesToHex4(secp256k1.getPublicKey(privateKeyBytes, true));
11345
+ return {
11346
+ body: JSON.stringify(body),
11347
+ headers: {
11348
+ "x-signature": bytesToHex4(signature),
11349
+ "x-public-key": publicKey,
11350
+ "x-timestamp": String(timestamp),
11351
+ "content-type": "application/json"
11352
+ }
11353
+ };
11354
+ }
11355
+ function toSnakeCaseIntent(req) {
11356
+ const result = {
11357
+ description: req.description,
11358
+ intent_type: req.intentType
11359
+ };
11360
+ if (req.category !== void 0) result.category = req.category;
11361
+ if (req.price !== void 0) result.price = req.price;
11362
+ if (req.currency !== void 0) result.currency = req.currency;
11363
+ if (req.location !== void 0) result.location = req.location;
11364
+ if (req.contactHandle !== void 0) result.contact_handle = req.contactHandle;
11365
+ if (req.expiresInDays !== void 0) result.expires_in_days = req.expiresInDays;
11366
+ return result;
11367
+ }
11368
+ function toSnakeCaseFilters(opts) {
11369
+ const result = {};
11370
+ if (opts?.filters) {
11371
+ const f = opts.filters;
11372
+ if (f.intentType !== void 0) result.intent_type = f.intentType;
11373
+ if (f.category !== void 0) result.category = f.category;
11374
+ if (f.minPrice !== void 0) result.min_price = f.minPrice;
11375
+ if (f.maxPrice !== void 0) result.max_price = f.maxPrice;
11376
+ if (f.location !== void 0) result.location = f.location;
11377
+ }
11378
+ if (opts?.limit !== void 0) result.limit = opts.limit;
11379
+ return result;
11380
+ }
11381
+ function mapSearchResult(raw) {
11382
+ return {
11383
+ id: raw.id,
11384
+ score: raw.score,
11385
+ agentNametag: raw.agent_nametag ?? void 0,
11386
+ agentPublicKey: raw.agent_public_key,
11387
+ description: raw.description,
11388
+ intentType: raw.intent_type,
11389
+ category: raw.category ?? void 0,
11390
+ price: raw.price ?? void 0,
11391
+ currency: raw.currency,
11392
+ location: raw.location ?? void 0,
11393
+ contactMethod: raw.contact_method,
11394
+ contactHandle: raw.contact_handle ?? void 0,
11395
+ createdAt: raw.created_at,
11396
+ expiresAt: raw.expires_at
11397
+ };
11398
+ }
11399
+ function mapMyIntent(raw) {
11400
+ return {
11401
+ id: raw.id,
11402
+ intentType: raw.intent_type,
11403
+ category: raw.category ?? void 0,
11404
+ price: raw.price ?? void 0,
11405
+ currency: raw.currency,
11406
+ location: raw.location ?? void 0,
11407
+ status: raw.status,
11408
+ createdAt: raw.created_at,
11409
+ expiresAt: raw.expires_at
11410
+ };
11411
+ }
11412
+ function mapFeedListing(raw) {
11413
+ return {
11414
+ id: raw.id,
11415
+ title: raw.title,
11416
+ descriptionPreview: raw.description_preview,
11417
+ agentName: raw.agent_name,
11418
+ agentId: raw.agent_id,
11419
+ type: raw.type,
11420
+ createdAt: raw.created_at
11421
+ };
11422
+ }
11423
+ function mapFeedMessage(raw) {
11424
+ if (raw.type === "initial") {
11425
+ return { type: "initial", listings: (raw.listings ?? []).map(mapFeedListing) };
11426
+ }
11427
+ return { type: "new", listing: mapFeedListing(raw.listing) };
11428
+ }
11429
+ var MarketModule = class {
11430
+ apiUrl;
11431
+ timeout;
11432
+ identity = null;
11433
+ registered = false;
11434
+ constructor(config) {
11435
+ this.apiUrl = (config?.apiUrl ?? DEFAULT_MARKET_API_URL).replace(/\/+$/, "");
11436
+ this.timeout = config?.timeout ?? 3e4;
11437
+ }
11438
+ /** Called by Sphere after construction */
11439
+ initialize(deps) {
11440
+ this.identity = deps.identity;
11441
+ }
11442
+ /** No-op — stateless module */
11443
+ async load() {
11444
+ }
11445
+ /** No-op — stateless module */
11446
+ destroy() {
11447
+ }
11448
+ // ---------------------------------------------------------------------------
11449
+ // Public API
11450
+ // ---------------------------------------------------------------------------
11451
+ /** Post a new intent (agent is auto-registered on first post) */
11452
+ async postIntent(intent) {
11453
+ const body = toSnakeCaseIntent(intent);
11454
+ const data = await this.apiPost("/api/intents", body);
11455
+ return {
11456
+ intentId: data.intent_id ?? data.intentId,
11457
+ message: data.message,
11458
+ expiresAt: data.expires_at ?? data.expiresAt
11459
+ };
11460
+ }
11461
+ /** Semantic search for intents (public — no auth required) */
11462
+ async search(query, opts) {
11463
+ const body = {
11464
+ query,
11465
+ ...toSnakeCaseFilters(opts)
11466
+ };
11467
+ const data = await this.apiPublicPost("/api/search", body);
11468
+ let results = (data.intents ?? []).map(mapSearchResult);
11469
+ const minScore = opts?.filters?.minScore;
11470
+ if (minScore != null) {
11471
+ results = results.filter((r) => Math.round(r.score * 100) >= Math.round(minScore * 100));
11472
+ }
11473
+ return { intents: results, count: results.length };
11474
+ }
11475
+ /** List own intents (authenticated) */
11476
+ async getMyIntents() {
11477
+ const data = await this.apiGet("/api/intents");
11478
+ return (data.intents ?? []).map(mapMyIntent);
11479
+ }
11480
+ /** Close (delete) an intent */
11481
+ async closeIntent(intentId) {
11482
+ await this.apiDelete(`/api/intents/${encodeURIComponent(intentId)}`);
11483
+ }
11484
+ /** Fetch the most recent listings via REST (public — no auth required) */
11485
+ async getRecentListings() {
11486
+ const res = await fetch(`${this.apiUrl}/api/feed/recent`, {
11487
+ signal: AbortSignal.timeout(this.timeout)
11488
+ });
11489
+ const data = await this.parseResponse(res);
11490
+ return (data.listings ?? []).map(mapFeedListing);
11491
+ }
11492
+ /**
11493
+ * Subscribe to the live listing feed via WebSocket.
11494
+ * Returns an unsubscribe function that closes the connection.
11495
+ *
11496
+ * Requires a WebSocket implementation — works natively in browsers
11497
+ * and in Node.js 21+ (or with the `ws` package).
11498
+ */
11499
+ subscribeFeed(listener) {
11500
+ const wsUrl = this.apiUrl.replace(/^http/, "ws") + "/ws/feed";
11501
+ const ws2 = new WebSocket(wsUrl);
11502
+ ws2.onmessage = (event) => {
11503
+ try {
11504
+ const raw = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
11505
+ listener(mapFeedMessage(raw));
11506
+ } catch {
11507
+ }
11508
+ };
11509
+ return () => {
11510
+ ws2.close();
11511
+ };
11512
+ }
11513
+ // ---------------------------------------------------------------------------
11514
+ // Private: HTTP helpers
11515
+ // ---------------------------------------------------------------------------
11516
+ ensureIdentity() {
11517
+ if (!this.identity) {
11518
+ throw new Error("MarketModule not initialized \u2014 call initialize() first");
11519
+ }
11520
+ }
11521
+ /** Register the agent's public key with the server (idempotent) */
11522
+ async ensureRegistered() {
11523
+ if (this.registered) return;
11524
+ this.ensureIdentity();
11525
+ const publicKey = bytesToHex4(secp256k1.getPublicKey(hexToBytes3(this.identity.privateKey), true));
11526
+ const body = { public_key: publicKey };
11527
+ if (this.identity.nametag) body.nametag = this.identity.nametag;
11528
+ const res = await fetch(`${this.apiUrl}/api/agent/register`, {
11529
+ method: "POST",
11530
+ headers: { "content-type": "application/json" },
11531
+ body: JSON.stringify(body),
11532
+ signal: AbortSignal.timeout(this.timeout)
11533
+ });
11534
+ if (res.ok || res.status === 409) {
11535
+ this.registered = true;
11536
+ return;
11537
+ }
11538
+ const text = await res.text();
11539
+ let data;
11540
+ try {
11541
+ data = JSON.parse(text);
11542
+ } catch {
11543
+ }
11544
+ throw new Error(data?.error ?? `Agent registration failed: HTTP ${res.status}`);
11545
+ }
11546
+ async parseResponse(res) {
11547
+ const text = await res.text();
11548
+ let data;
11549
+ try {
11550
+ data = JSON.parse(text);
11551
+ } catch {
11552
+ throw new Error(`Market API error: HTTP ${res.status} \u2014 unexpected response (not JSON)`);
11553
+ }
11554
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
11555
+ return data;
11556
+ }
11557
+ async apiPost(path, body) {
11558
+ this.ensureIdentity();
11559
+ await this.ensureRegistered();
11560
+ const signed = signRequest(body, this.identity.privateKey);
11561
+ const res = await fetch(`${this.apiUrl}${path}`, {
11562
+ method: "POST",
11563
+ headers: signed.headers,
11564
+ body: signed.body,
11565
+ signal: AbortSignal.timeout(this.timeout)
11566
+ });
11567
+ return this.parseResponse(res);
11568
+ }
11569
+ async apiGet(path) {
11570
+ this.ensureIdentity();
11571
+ await this.ensureRegistered();
11572
+ const signed = signRequest({}, this.identity.privateKey);
11573
+ const res = await fetch(`${this.apiUrl}${path}`, {
11574
+ method: "GET",
11575
+ headers: signed.headers,
11576
+ signal: AbortSignal.timeout(this.timeout)
11577
+ });
11578
+ return this.parseResponse(res);
11579
+ }
11580
+ async apiDelete(path) {
11581
+ this.ensureIdentity();
11582
+ await this.ensureRegistered();
11583
+ const signed = signRequest({}, this.identity.privateKey);
11584
+ const res = await fetch(`${this.apiUrl}${path}`, {
11585
+ method: "DELETE",
11586
+ headers: signed.headers,
11587
+ signal: AbortSignal.timeout(this.timeout)
11588
+ });
11589
+ return this.parseResponse(res);
11590
+ }
11591
+ async apiPublicPost(path, body) {
11592
+ const res = await fetch(`${this.apiUrl}${path}`, {
11593
+ method: "POST",
11594
+ headers: { "content-type": "application/json" },
11595
+ body: JSON.stringify(body),
11596
+ signal: AbortSignal.timeout(this.timeout)
11597
+ });
11598
+ return this.parseResponse(res);
11599
+ }
11600
+ };
11601
+ function createMarketModule(config) {
11602
+ return new MarketModule(config);
11603
+ }
11604
+
9112
11605
  // core/encryption.ts
9113
11606
  import CryptoJS6 from "crypto-js";
9114
11607
  function encryptSimple(plaintext, password) {
@@ -9327,7 +11820,9 @@ function decryptTextFormatKey(encryptedKey, password) {
9327
11820
  const key = deriveLegacyKey(password);
9328
11821
  const decrypted = CryptoJS7.AES.decrypt(encryptedKey, key);
9329
11822
  const result = decrypted.toString(CryptoJS7.enc.Utf8);
9330
- return result || null;
11823
+ if (!result) return null;
11824
+ if (!/^[0-9a-fA-F]+$/.test(result)) return null;
11825
+ return result;
9331
11826
  } catch {
9332
11827
  return null;
9333
11828
  }
@@ -9942,6 +12437,7 @@ var Sphere = class _Sphere {
9942
12437
  _payments;
9943
12438
  _communications;
9944
12439
  _groupChat = null;
12440
+ _market = null;
9945
12441
  // Events
9946
12442
  eventHandlers = /* @__PURE__ */ new Map();
9947
12443
  // Provider management
@@ -9951,7 +12447,7 @@ var Sphere = class _Sphere {
9951
12447
  // ===========================================================================
9952
12448
  // Constructor (private)
9953
12449
  // ===========================================================================
9954
- constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig) {
12450
+ constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig, marketConfig) {
9955
12451
  this._storage = storage;
9956
12452
  this._transport = transport;
9957
12453
  this._oracle = oracle;
@@ -9962,6 +12458,7 @@ var Sphere = class _Sphere {
9962
12458
  this._payments = createPaymentsModule({ l1: l1Config });
9963
12459
  this._communications = createCommunicationsModule();
9964
12460
  this._groupChat = groupChatConfig ? createGroupChatModule(groupChatConfig) : null;
12461
+ this._market = marketConfig ? createMarketModule(marketConfig) : null;
9965
12462
  }
9966
12463
  // ===========================================================================
9967
12464
  // Static Methods - Wallet Management
@@ -10010,6 +12507,7 @@ var Sphere = class _Sphere {
10010
12507
  */
10011
12508
  static async init(options) {
10012
12509
  const groupChat = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12510
+ const market = _Sphere.resolveMarketConfig(options.market);
10013
12511
  const walletExists = await _Sphere.exists(options.storage);
10014
12512
  if (walletExists) {
10015
12513
  const sphere2 = await _Sphere.load({
@@ -10020,7 +12518,8 @@ var Sphere = class _Sphere {
10020
12518
  l1: options.l1,
10021
12519
  price: options.price,
10022
12520
  groupChat,
10023
- password: options.password
12521
+ password: options.password,
12522
+ market
10024
12523
  });
10025
12524
  return { sphere: sphere2, created: false };
10026
12525
  }
@@ -10047,7 +12546,8 @@ var Sphere = class _Sphere {
10047
12546
  l1: options.l1,
10048
12547
  price: options.price,
10049
12548
  groupChat,
10050
- password: options.password
12549
+ password: options.password,
12550
+ market
10051
12551
  });
10052
12552
  return { sphere, created: true, generatedMnemonic };
10053
12553
  }
@@ -10074,6 +12574,22 @@ var Sphere = class _Sphere {
10074
12574
  }
10075
12575
  return config;
10076
12576
  }
12577
+ /**
12578
+ * Resolve market module config from Sphere.init() options.
12579
+ * - `true` → enable with default API URL
12580
+ * - `MarketModuleConfig` → pass through with defaults
12581
+ * - `undefined` → no market module
12582
+ */
12583
+ static resolveMarketConfig(config) {
12584
+ if (!config) return void 0;
12585
+ if (config === true) {
12586
+ return { apiUrl: DEFAULT_MARKET_API_URL };
12587
+ }
12588
+ return {
12589
+ apiUrl: config.apiUrl ?? DEFAULT_MARKET_API_URL,
12590
+ timeout: config.timeout
12591
+ };
12592
+ }
10077
12593
  /**
10078
12594
  * Create new wallet with mnemonic
10079
12595
  */
@@ -10085,6 +12601,7 @@ var Sphere = class _Sphere {
10085
12601
  throw new Error("Wallet already exists. Use Sphere.load() or Sphere.clear() first.");
10086
12602
  }
10087
12603
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12604
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10088
12605
  const sphere = new _Sphere(
10089
12606
  options.storage,
10090
12607
  options.transport,
@@ -10092,7 +12609,8 @@ var Sphere = class _Sphere {
10092
12609
  options.tokenStorage,
10093
12610
  options.l1,
10094
12611
  options.price,
10095
- groupChatConfig
12612
+ groupChatConfig,
12613
+ marketConfig
10096
12614
  );
10097
12615
  sphere._password = options.password ?? null;
10098
12616
  await sphere.storeMnemonic(options.mnemonic, options.derivationPath);
@@ -10119,6 +12637,7 @@ var Sphere = class _Sphere {
10119
12637
  throw new Error("No wallet found. Use Sphere.create() to create a new wallet.");
10120
12638
  }
10121
12639
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12640
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10122
12641
  const sphere = new _Sphere(
10123
12642
  options.storage,
10124
12643
  options.transport,
@@ -10126,7 +12645,8 @@ var Sphere = class _Sphere {
10126
12645
  options.tokenStorage,
10127
12646
  options.l1,
10128
12647
  options.price,
10129
- groupChatConfig
12648
+ groupChatConfig,
12649
+ marketConfig
10130
12650
  );
10131
12651
  sphere._password = options.password ?? null;
10132
12652
  await sphere.loadIdentityFromStorage();
@@ -10172,6 +12692,7 @@ var Sphere = class _Sphere {
10172
12692
  console.log("[Sphere.import] Storage reconnected");
10173
12693
  }
10174
12694
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat);
12695
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10175
12696
  const sphere = new _Sphere(
10176
12697
  options.storage,
10177
12698
  options.transport,
@@ -10179,7 +12700,8 @@ var Sphere = class _Sphere {
10179
12700
  options.tokenStorage,
10180
12701
  options.l1,
10181
12702
  options.price,
10182
- groupChatConfig
12703
+ groupChatConfig,
12704
+ marketConfig
10183
12705
  );
10184
12706
  sphere._password = options.password ?? null;
10185
12707
  if (options.mnemonic) {
@@ -10344,6 +12866,10 @@ var Sphere = class _Sphere {
10344
12866
  get groupChat() {
10345
12867
  return this._groupChat;
10346
12868
  }
12869
+ /** Market module (intent bulletin board). Null if not configured. */
12870
+ get market() {
12871
+ return this._market;
12872
+ }
10347
12873
  // ===========================================================================
10348
12874
  // Public Properties - State
10349
12875
  // ===========================================================================
@@ -11149,7 +13675,7 @@ var Sphere = class _Sphere {
11149
13675
  await provider.initialize();
11150
13676
  }
11151
13677
  await this.reinitializeModulesForNewAddress();
11152
- if (this._identity.nametag) {
13678
+ if (!newNametag) {
11153
13679
  await this.syncIdentityWithTransport();
11154
13680
  }
11155
13681
  if (newNametag) {
@@ -11219,9 +13745,14 @@ var Sphere = class _Sphere {
11219
13745
  storage: this._storage,
11220
13746
  emitEvent
11221
13747
  });
13748
+ this._market?.initialize({
13749
+ identity: this._identity,
13750
+ emitEvent
13751
+ });
11222
13752
  await this._payments.load();
11223
13753
  await this._communications.load();
11224
13754
  await this._groupChat?.load();
13755
+ await this._market?.load();
11225
13756
  }
11226
13757
  /**
11227
13758
  * Derive address at a specific index
@@ -11922,12 +14453,22 @@ var Sphere = class _Sphere {
11922
14453
  return;
11923
14454
  }
11924
14455
  try {
11925
- if (this._identity?.directAddress && this._transport.resolve) {
14456
+ const transportPubkey = this._identity?.chainPubkey?.slice(2);
14457
+ if (transportPubkey && this._transport.resolve) {
11926
14458
  try {
11927
- const existing = await this._transport.resolve(this._identity.directAddress);
14459
+ const existing = await this._transport.resolve(transportPubkey);
11928
14460
  if (existing) {
11929
- if (existing.nametag && !this._identity.nametag) {
11930
- this._identity.nametag = existing.nametag;
14461
+ let recoveredNametag = existing.nametag;
14462
+ let fromLegacy = false;
14463
+ if (!recoveredNametag && !this._identity?.nametag && this._transport.recoverNametag) {
14464
+ try {
14465
+ recoveredNametag = await this._transport.recoverNametag() ?? void 0;
14466
+ if (recoveredNametag) fromLegacy = true;
14467
+ } catch {
14468
+ }
14469
+ }
14470
+ if (recoveredNametag && !this._identity?.nametag) {
14471
+ this._identity.nametag = recoveredNametag;
11931
14472
  await this._updateCachedProxyAddress();
11932
14473
  const entry = await this.ensureAddressTracked(this._currentAddressIndex);
11933
14474
  let nametags = this._addressNametags.get(entry.addressId);
@@ -11936,10 +14477,20 @@ var Sphere = class _Sphere {
11936
14477
  this._addressNametags.set(entry.addressId, nametags);
11937
14478
  }
11938
14479
  if (!nametags.has(0)) {
11939
- nametags.set(0, existing.nametag);
14480
+ nametags.set(0, recoveredNametag);
11940
14481
  await this.persistAddressNametags();
11941
14482
  }
11942
- this.emitEvent("nametag:recovered", { nametag: existing.nametag });
14483
+ this.emitEvent("nametag:recovered", { nametag: recoveredNametag });
14484
+ if (fromLegacy) {
14485
+ await this._transport.publishIdentityBinding(
14486
+ this._identity.chainPubkey,
14487
+ this._identity.l1Address,
14488
+ this._identity.directAddress || "",
14489
+ recoveredNametag
14490
+ );
14491
+ console.log(`[Sphere] Migrated legacy binding with nametag @${recoveredNametag}`);
14492
+ return;
14493
+ }
11943
14494
  }
11944
14495
  console.log("[Sphere] Existing binding found, skipping re-publish");
11945
14496
  return;
@@ -12026,6 +14577,7 @@ var Sphere = class _Sphere {
12026
14577
  this._payments.destroy();
12027
14578
  this._communications.destroy();
12028
14579
  this._groupChat?.destroy();
14580
+ this._market?.destroy();
12029
14581
  await this._transport.disconnect();
12030
14582
  await this._storage.disconnect();
12031
14583
  await this._oracle.disconnect();
@@ -12333,9 +14885,14 @@ var Sphere = class _Sphere {
12333
14885
  storage: this._storage,
12334
14886
  emitEvent
12335
14887
  });
14888
+ this._market?.initialize({
14889
+ identity: this._identity,
14890
+ emitEvent
14891
+ });
12336
14892
  await this._payments.load();
12337
14893
  await this._communications.load();
12338
14894
  await this._groupChat?.load();
14895
+ await this._market?.load();
12339
14896
  }
12340
14897
  // ===========================================================================
12341
14898
  // Private: Helpers
@@ -13128,6 +15685,7 @@ export {
13128
15685
  DEFAULT_GROUP_RELAYS,
13129
15686
  DEFAULT_IPFS_BOOTSTRAP_PEERS,
13130
15687
  DEFAULT_IPFS_GATEWAYS,
15688
+ DEFAULT_MARKET_API_URL,
13131
15689
  DEFAULT_NOSTR_RELAYS,
13132
15690
  DEV_AGGREGATOR_URL,
13133
15691
  GroupChatModule,
@@ -13136,6 +15694,7 @@ export {
13136
15694
  l1_exports as L1,
13137
15695
  L1PaymentsModule,
13138
15696
  LIMITS,
15697
+ MarketModule,
13139
15698
  NETWORKS,
13140
15699
  NIP29_KINDS,
13141
15700
  NOSTR_EVENT_KINDS,
@@ -13163,6 +15722,7 @@ export {
13163
15722
  createGroupChatModule,
13164
15723
  createKeyPair,
13165
15724
  createL1PaymentsModule,
15725
+ createMarketModule,
13166
15726
  createPaymentSession,
13167
15727
  createPaymentSessionError,
13168
15728
  createPaymentsModule,
@@ -13250,4 +15810,16 @@ export {
13250
15810
  txfToToken,
13251
15811
  validateMnemonic2 as validateMnemonic
13252
15812
  };
15813
+ /*! Bundled license information:
15814
+
15815
+ @noble/hashes/utils.js:
15816
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
15817
+
15818
+ @noble/curves/utils.js:
15819
+ @noble/curves/abstract/modular.js:
15820
+ @noble/curves/abstract/curve.js:
15821
+ @noble/curves/abstract/weierstrass.js:
15822
+ @noble/curves/secp256k1.js:
15823
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
15824
+ */
13253
15825
  //# sourceMappingURL=index.js.map