@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.cjs CHANGED
@@ -20,15 +20,15 @@ var __copyProps = (to, from, except, desc) => {
20
20
  }
21
21
  return to;
22
22
  };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
+ var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
24
24
  // If the importer is in node compatibility mode or this is not an ESM
25
25
  // file that has been converted to a CommonJS file using a Babel-
26
26
  // compatible transform (i.e. "__esModule" has not been set), then set
27
27
  // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
- mod
28
+ isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
29
+ mod2
30
30
  ));
31
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
+ var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
32
32
 
33
33
  // core/bech32.ts
34
34
  function convertBits(data, fromBits, toBits, pad) {
@@ -75,10 +75,10 @@ function bech32Polymod(values) {
75
75
  }
76
76
  function bech32Checksum(hrp, data) {
77
77
  const values = hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]);
78
- const mod = bech32Polymod(values) ^ 1;
78
+ const mod2 = bech32Polymod(values) ^ 1;
79
79
  const ret = [];
80
80
  for (let p = 0; p < 6; p++) {
81
- ret.push(mod >> 5 * (5 - p) & 31);
81
+ ret.push(mod2 >> 5 * (5 - p) & 31);
82
82
  }
83
83
  return ret;
84
84
  }
@@ -480,6 +480,7 @@ __export(index_exports, {
480
480
  DEFAULT_GROUP_RELAYS: () => DEFAULT_GROUP_RELAYS,
481
481
  DEFAULT_IPFS_BOOTSTRAP_PEERS: () => DEFAULT_IPFS_BOOTSTRAP_PEERS,
482
482
  DEFAULT_IPFS_GATEWAYS: () => DEFAULT_IPFS_GATEWAYS,
483
+ DEFAULT_MARKET_API_URL: () => DEFAULT_MARKET_API_URL,
483
484
  DEFAULT_NOSTR_RELAYS: () => DEFAULT_NOSTR_RELAYS,
484
485
  DEV_AGGREGATOR_URL: () => DEV_AGGREGATOR_URL,
485
486
  GroupChatModule: () => GroupChatModule,
@@ -488,6 +489,7 @@ __export(index_exports, {
488
489
  L1: () => l1_exports,
489
490
  L1PaymentsModule: () => L1PaymentsModule,
490
491
  LIMITS: () => LIMITS,
492
+ MarketModule: () => MarketModule,
491
493
  NETWORKS: () => NETWORKS,
492
494
  NIP29_KINDS: () => NIP29_KINDS,
493
495
  NOSTR_EVENT_KINDS: () => NOSTR_EVENT_KINDS,
@@ -515,6 +517,7 @@ __export(index_exports, {
515
517
  createGroupChatModule: () => createGroupChatModule,
516
518
  createKeyPair: () => createKeyPair,
517
519
  createL1PaymentsModule: () => createL1PaymentsModule,
520
+ createMarketModule: () => createMarketModule,
518
521
  createPaymentSession: () => createPaymentSession,
519
522
  createPaymentSessionError: () => createPaymentSessionError,
520
523
  createPaymentsModule: () => createPaymentsModule,
@@ -2644,7 +2647,11 @@ var STORAGE_KEYS_GLOBAL = {
2644
2647
  /** Group chat: processed event IDs for deduplication */
2645
2648
  GROUP_CHAT_PROCESSED_EVENTS: "group_chat_processed_events",
2646
2649
  /** Group chat: last used relay URL (stale data detection) */
2647
- GROUP_CHAT_RELAY_URL: "group_chat_relay_url"
2650
+ GROUP_CHAT_RELAY_URL: "group_chat_relay_url",
2651
+ /** Cached token registry JSON (fetched from remote) */
2652
+ TOKEN_REGISTRY_CACHE: "token_registry_cache",
2653
+ /** Timestamp of last token registry cache update (ms since epoch) */
2654
+ TOKEN_REGISTRY_CACHE_TS: "token_registry_cache_ts"
2648
2655
  };
2649
2656
  var STORAGE_KEYS_ADDRESS = {
2650
2657
  /** Pending transfers for this address */
@@ -2752,6 +2759,8 @@ var COIN_TYPES = {
2752
2759
  };
2753
2760
  var DEFAULT_ELECTRUM_URL = "wss://fulcrum.alpha.unicity.network:50004";
2754
2761
  var TEST_ELECTRUM_URL = "wss://fulcrum.alpha.testnet.unicity.network:50004";
2762
+ var TOKEN_REGISTRY_URL = "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/unicity-ids.testnet.json";
2763
+ var TOKEN_REGISTRY_REFRESH_INTERVAL = 36e5;
2755
2764
  var TEST_NOSTR_RELAYS = [
2756
2765
  "wss://nostr-relay.testnet.unicity.network"
2757
2766
  ];
@@ -2765,7 +2774,8 @@ var NETWORKS = {
2765
2774
  nostrRelays: DEFAULT_NOSTR_RELAYS,
2766
2775
  ipfsGateways: DEFAULT_IPFS_GATEWAYS,
2767
2776
  electrumUrl: DEFAULT_ELECTRUM_URL,
2768
- groupRelays: DEFAULT_GROUP_RELAYS
2777
+ groupRelays: DEFAULT_GROUP_RELAYS,
2778
+ tokenRegistryUrl: TOKEN_REGISTRY_URL
2769
2779
  },
2770
2780
  testnet: {
2771
2781
  name: "Testnet",
@@ -2773,7 +2783,8 @@ var NETWORKS = {
2773
2783
  nostrRelays: TEST_NOSTR_RELAYS,
2774
2784
  ipfsGateways: DEFAULT_IPFS_GATEWAYS,
2775
2785
  electrumUrl: TEST_ELECTRUM_URL,
2776
- groupRelays: DEFAULT_GROUP_RELAYS
2786
+ groupRelays: DEFAULT_GROUP_RELAYS,
2787
+ tokenRegistryUrl: TOKEN_REGISTRY_URL
2777
2788
  },
2778
2789
  dev: {
2779
2790
  name: "Development",
@@ -2781,7 +2792,8 @@ var NETWORKS = {
2781
2792
  nostrRelays: TEST_NOSTR_RELAYS,
2782
2793
  ipfsGateways: DEFAULT_IPFS_GATEWAYS,
2783
2794
  electrumUrl: TEST_ELECTRUM_URL,
2784
- groupRelays: DEFAULT_GROUP_RELAYS
2795
+ groupRelays: DEFAULT_GROUP_RELAYS,
2796
+ tokenRegistryUrl: TOKEN_REGISTRY_URL
2785
2797
  }
2786
2798
  };
2787
2799
  var TIMEOUTS = {
@@ -2796,6 +2808,7 @@ var TIMEOUTS = {
2796
2808
  /** Sync interval */
2797
2809
  SYNC_INTERVAL: 6e4
2798
2810
  };
2811
+ var DEFAULT_MARKET_API_URL = "https://market-api.unicity.network";
2799
2812
  var LIMITS = {
2800
2813
  /** Min nametag length */
2801
2814
  NAMETAG_MIN_LENGTH: 3,
@@ -2849,141 +2862,24 @@ function isValidTokenId(tokenId) {
2849
2862
  return /^[0-9a-fA-F]{64}$/.test(tokenId);
2850
2863
  }
2851
2864
 
2852
- // registry/token-registry.testnet.json
2853
- var token_registry_testnet_default = [
2854
- {
2855
- network: "unicity:testnet",
2856
- assetKind: "non-fungible",
2857
- name: "unicity",
2858
- description: "Unicity testnet token type",
2859
- id: "f8aa13834268d29355ff12183066f0cb902003629bbc5eb9ef0efbe397867509"
2860
- },
2861
- {
2862
- network: "unicity:testnet",
2863
- assetKind: "fungible",
2864
- name: "unicity",
2865
- symbol: "UCT",
2866
- decimals: 18,
2867
- description: "Unicity testnet native coin",
2868
- icons: [
2869
- { url: "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/unicity_logo_32.png" }
2870
- ],
2871
- id: "455ad8720656b08e8dbd5bac1f3c73eeea5431565f6c1c3af742b1aa12d41d89"
2872
- },
2873
- {
2874
- network: "unicity:testnet",
2875
- assetKind: "fungible",
2876
- name: "unicity-usd",
2877
- symbol: "USDU",
2878
- decimals: 6,
2879
- description: "Unicity testnet USD stablecoin",
2880
- icons: [
2881
- { url: "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/usdu_logo_32.png" }
2882
- ],
2883
- id: "8f0f3d7a5e7297be0ee98c63b81bcebb2740f43f616566fc290f9823a54f52d7"
2884
- },
2885
- {
2886
- network: "unicity:testnet",
2887
- assetKind: "fungible",
2888
- name: "unicity-eur",
2889
- symbol: "EURU",
2890
- decimals: 6,
2891
- description: "Unicity testnet EUR stablecoin",
2892
- icons: [
2893
- { url: "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/euru_logo_32.png" }
2894
- ],
2895
- id: "5e160d5e9fdbb03b553fb9c3f6e6c30efa41fa807be39fb4f18e43776e492925"
2896
- },
2897
- {
2898
- network: "unicity:testnet",
2899
- assetKind: "fungible",
2900
- name: "solana",
2901
- symbol: "SOL",
2902
- decimals: 9,
2903
- description: "Solana testnet coin on Unicity",
2904
- icons: [
2905
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/sol.svg" },
2906
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/sol.png" }
2907
- ],
2908
- id: "dee5f8ce778562eec90e9c38a91296a023210ccc76ff4c29d527ac3eb64ade93"
2909
- },
2910
- {
2911
- network: "unicity:testnet",
2912
- assetKind: "fungible",
2913
- name: "bitcoin",
2914
- symbol: "BTC",
2915
- decimals: 8,
2916
- description: "Bitcoin testnet coin on Unicity",
2917
- icons: [
2918
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/btc.svg" },
2919
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/btc.png" }
2920
- ],
2921
- id: "86bc190fcf7b2d07c6078de93db803578760148b16d4431aa2f42a3241ff0daa"
2922
- },
2923
- {
2924
- network: "unicity:testnet",
2925
- assetKind: "fungible",
2926
- name: "ethereum",
2927
- symbol: "ETH",
2928
- decimals: 18,
2929
- description: "Ethereum testnet coin on Unicity",
2930
- icons: [
2931
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/eth.svg" },
2932
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/eth.png" }
2933
- ],
2934
- id: "3c2450f2fd867e7bb60c6a69d7ad0e53ce967078c201a3ecaa6074ed4c0deafb"
2935
- },
2936
- {
2937
- network: "unicity:testnet",
2938
- assetKind: "fungible",
2939
- name: "alpha_test",
2940
- symbol: "ALPHT",
2941
- decimals: 8,
2942
- description: "ALPHA testnet coin on Unicity",
2943
- icons: [
2944
- { url: "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/alpha_coin.png" }
2945
- ],
2946
- id: "cde78ded16ef65818a51f43138031c4284e519300ab0cb60c30a8f9078080e5f"
2947
- },
2948
- {
2949
- network: "unicity:testnet",
2950
- assetKind: "fungible",
2951
- name: "tether",
2952
- symbol: "USDT",
2953
- decimals: 6,
2954
- description: "Tether (Ethereum) testnet coin on Unicity",
2955
- icons: [
2956
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/usdt.svg" },
2957
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/usdt.png" }
2958
- ],
2959
- id: "40d25444648418fe7efd433e147187a3a6adf049ac62bc46038bda5b960bf690"
2960
- },
2961
- {
2962
- network: "unicity:testnet",
2963
- assetKind: "fungible",
2964
- name: "usd-coin",
2965
- symbol: "USDC",
2966
- decimals: 6,
2967
- description: "USDC (Ethereum) testnet coin on Unicity",
2968
- icons: [
2969
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/usdc.svg" },
2970
- { url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/usdc.png" }
2971
- ],
2972
- id: "2265121770fa6f41131dd9a6cc571e28679263d09a53eb2642e145b5b9a5b0a2"
2973
- }
2974
- ];
2975
-
2976
2865
  // registry/TokenRegistry.ts
2866
+ var FETCH_TIMEOUT_MS = 1e4;
2977
2867
  var TokenRegistry = class _TokenRegistry {
2978
2868
  static instance = null;
2979
2869
  definitionsById;
2980
2870
  definitionsBySymbol;
2981
2871
  definitionsByName;
2872
+ // Remote refresh state
2873
+ remoteUrl = null;
2874
+ storage = null;
2875
+ refreshIntervalMs = TOKEN_REGISTRY_REFRESH_INTERVAL;
2876
+ refreshTimer = null;
2877
+ lastRefreshAt = 0;
2878
+ refreshPromise = null;
2982
2879
  constructor() {
2983
2880
  this.definitionsById = /* @__PURE__ */ new Map();
2984
2881
  this.definitionsBySymbol = /* @__PURE__ */ new Map();
2985
2882
  this.definitionsByName = /* @__PURE__ */ new Map();
2986
- this.loadRegistry();
2987
2883
  }
2988
2884
  /**
2989
2885
  * Get singleton instance of TokenRegistry
@@ -2995,16 +2891,106 @@ var TokenRegistry = class _TokenRegistry {
2995
2891
  return _TokenRegistry.instance;
2996
2892
  }
2997
2893
  /**
2998
- * Reset the singleton instance (useful for testing)
2894
+ * Configure remote registry refresh with persistent caching.
2895
+ *
2896
+ * On first call:
2897
+ * 1. Loads cached data from StorageProvider (if available and fresh)
2898
+ * 2. Starts periodic remote fetch (if autoRefresh is true, which is default)
2899
+ *
2900
+ * @param options - Configuration options
2901
+ * @param options.remoteUrl - Remote URL to fetch definitions from
2902
+ * @param options.storage - StorageProvider for persistent caching
2903
+ * @param options.refreshIntervalMs - Refresh interval in ms (default: 1 hour)
2904
+ * @param options.autoRefresh - Start auto-refresh immediately (default: true)
2905
+ */
2906
+ static configure(options) {
2907
+ const instance = _TokenRegistry.getInstance();
2908
+ if (options.remoteUrl !== void 0) {
2909
+ instance.remoteUrl = options.remoteUrl;
2910
+ }
2911
+ if (options.storage !== void 0) {
2912
+ instance.storage = options.storage;
2913
+ }
2914
+ if (options.refreshIntervalMs !== void 0) {
2915
+ instance.refreshIntervalMs = options.refreshIntervalMs;
2916
+ }
2917
+ if (instance.storage) {
2918
+ instance.loadFromCache();
2919
+ }
2920
+ const autoRefresh = options.autoRefresh ?? true;
2921
+ if (autoRefresh && instance.remoteUrl) {
2922
+ instance.startAutoRefresh();
2923
+ }
2924
+ }
2925
+ /**
2926
+ * Reset the singleton instance (useful for testing).
2927
+ * Stops auto-refresh if running.
2999
2928
  */
3000
2929
  static resetInstance() {
2930
+ if (_TokenRegistry.instance) {
2931
+ _TokenRegistry.instance.stopAutoRefresh();
2932
+ }
3001
2933
  _TokenRegistry.instance = null;
3002
2934
  }
3003
2935
  /**
3004
- * Load registry data from bundled JSON
2936
+ * Destroy the singleton: stop auto-refresh and reset.
2937
+ */
2938
+ static destroy() {
2939
+ _TokenRegistry.resetInstance();
2940
+ }
2941
+ // ===========================================================================
2942
+ // Cache (StorageProvider)
2943
+ // ===========================================================================
2944
+ /**
2945
+ * Load definitions from StorageProvider cache.
2946
+ * Only applies if cache exists and is fresh (within refreshIntervalMs).
2947
+ */
2948
+ async loadFromCache() {
2949
+ if (!this.storage) return false;
2950
+ try {
2951
+ const [cached, cachedTs] = await Promise.all([
2952
+ this.storage.get(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE),
2953
+ this.storage.get(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE_TS)
2954
+ ]);
2955
+ if (!cached || !cachedTs) return false;
2956
+ const ts = parseInt(cachedTs, 10);
2957
+ if (isNaN(ts)) return false;
2958
+ const age = Date.now() - ts;
2959
+ if (age > this.refreshIntervalMs) return false;
2960
+ if (this.lastRefreshAt > ts) return false;
2961
+ const data = JSON.parse(cached);
2962
+ if (!this.isValidDefinitionsArray(data)) return false;
2963
+ this.applyDefinitions(data);
2964
+ this.lastRefreshAt = ts;
2965
+ return true;
2966
+ } catch {
2967
+ return false;
2968
+ }
2969
+ }
2970
+ /**
2971
+ * Save definitions to StorageProvider cache.
3005
2972
  */
3006
- loadRegistry() {
3007
- const definitions = token_registry_testnet_default;
2973
+ async saveToCache(definitions) {
2974
+ if (!this.storage) return;
2975
+ try {
2976
+ await Promise.all([
2977
+ this.storage.set(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE, JSON.stringify(definitions)),
2978
+ this.storage.set(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE_TS, String(Date.now()))
2979
+ ]);
2980
+ } catch {
2981
+ }
2982
+ }
2983
+ // ===========================================================================
2984
+ // Remote Refresh
2985
+ // ===========================================================================
2986
+ /**
2987
+ * Apply an array of token definitions to the internal maps.
2988
+ * Clears existing data before applying.
2989
+ */
2990
+ applyDefinitions(definitions) {
2991
+ this.definitionsById.clear();
2992
+ this.definitionsBySymbol.clear();
2993
+ this.definitionsByName.clear();
3008
2994
  for (const def of definitions) {
3009
2995
  const idLower = def.id.toLowerCase();
3010
2996
  this.definitionsById.set(idLower, def);
@@ -3014,6 +3000,96 @@ var TokenRegistry = class _TokenRegistry {
3014
3000
  this.definitionsByName.set(def.name.toLowerCase(), def);
3015
3001
  }
3016
3002
  }
3003
+ /**
3004
+ * Validate that data is an array of objects with 'id' field
3005
+ */
3006
+ isValidDefinitionsArray(data) {
3007
+ return Array.isArray(data) && data.every((item) => item && typeof item === "object" && "id" in item);
3008
+ }
3009
+ /**
3010
+ * Fetch token definitions from the remote URL and update the registry.
3011
+ * On success, also persists to StorageProvider cache.
3012
+ * Returns true on success, false on failure. On failure, existing data is preserved.
3013
+ * Concurrent calls are deduplicated — only one fetch runs at a time.
3014
+ */
3015
+ async refreshFromRemote() {
3016
+ if (!this.remoteUrl) {
3017
+ return false;
3018
+ }
3019
+ if (this.refreshPromise) {
3020
+ return this.refreshPromise;
3021
+ }
3022
+ this.refreshPromise = this.doRefresh();
3023
+ try {
3024
+ return await this.refreshPromise;
3025
+ } finally {
3026
+ this.refreshPromise = null;
3027
+ }
3028
+ }
3029
+ async doRefresh() {
3030
+ try {
3031
+ const controller = new AbortController();
3032
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
3033
+ let response;
3034
+ try {
3035
+ response = await fetch(this.remoteUrl, {
3036
+ headers: { Accept: "application/json" },
3037
+ signal: controller.signal
3038
+ });
3039
+ } finally {
3040
+ clearTimeout(timer);
3041
+ }
3042
+ if (!response.ok) {
3043
+ console.warn(
3044
+ `[TokenRegistry] Remote fetch failed: HTTP ${response.status} ${response.statusText}`
3045
+ );
3046
+ return false;
3047
+ }
3048
+ const data = await response.json();
3049
+ if (!this.isValidDefinitionsArray(data)) {
3050
+ console.warn("[TokenRegistry] Remote data is not a valid token definitions array");
3051
+ return false;
3052
+ }
3053
+ const definitions = data;
3054
+ this.applyDefinitions(definitions);
3055
+ this.lastRefreshAt = Date.now();
3056
+ this.saveToCache(definitions);
3057
+ return true;
3058
+ } catch (error) {
3059
+ const message = error instanceof Error ? error.message : String(error);
3060
+ console.warn(`[TokenRegistry] Remote refresh failed: ${message}`);
3061
+ return false;
3062
+ }
3063
+ }
3064
+ /**
3065
+ * Start periodic auto-refresh from the remote URL.
3066
+ * Does an immediate fetch, then repeats at the configured interval.
3067
+ */
3068
+ startAutoRefresh(intervalMs) {
3069
+ this.stopAutoRefresh();
3070
+ if (intervalMs !== void 0) {
3071
+ this.refreshIntervalMs = intervalMs;
3072
+ }
3073
+ this.refreshFromRemote();
3074
+ this.refreshTimer = setInterval(() => {
3075
+ this.refreshFromRemote();
3076
+ }, this.refreshIntervalMs);
3077
+ }
3078
+ /**
3079
+ * Stop periodic auto-refresh
3080
+ */
3081
+ stopAutoRefresh() {
3082
+ if (this.refreshTimer !== null) {
3083
+ clearInterval(this.refreshTimer);
3084
+ this.refreshTimer = null;
3085
+ }
3086
+ }
3087
+ /**
3088
+ * Timestamp of the last successful remote refresh (0 if never refreshed)
3089
+ */
3090
+ getLastRefreshAt() {
3091
+ return this.lastRefreshAt;
3092
+ }
3017
3093
  // ===========================================================================
3018
3094
  // Lookup Methods
3019
3095
  // ===========================================================================
@@ -9259,6 +9335,2426 @@ function createGroupChatModule(config) {
9259
9335
  return new GroupChatModule(config);
9260
9336
  }
9261
9337
 
9338
+ // node_modules/@noble/hashes/utils.js
9339
+ function isBytes(a) {
9340
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
9341
+ }
9342
+ function anumber(n, title = "") {
9343
+ if (!Number.isSafeInteger(n) || n < 0) {
9344
+ const prefix = title && `"${title}" `;
9345
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
9346
+ }
9347
+ }
9348
+ function abytes(value, length, title = "") {
9349
+ const bytes = isBytes(value);
9350
+ const len = value?.length;
9351
+ const needsLen = length !== void 0;
9352
+ if (!bytes || needsLen && len !== length) {
9353
+ const prefix = title && `"${title}" `;
9354
+ const ofLen = needsLen ? ` of length ${length}` : "";
9355
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
9356
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
9357
+ }
9358
+ return value;
9359
+ }
9360
+ function ahash(h) {
9361
+ if (typeof h !== "function" || typeof h.create !== "function")
9362
+ throw new Error("Hash must wrapped by utils.createHasher");
9363
+ anumber(h.outputLen);
9364
+ anumber(h.blockLen);
9365
+ }
9366
+ function aexists(instance, checkFinished = true) {
9367
+ if (instance.destroyed)
9368
+ throw new Error("Hash instance has been destroyed");
9369
+ if (checkFinished && instance.finished)
9370
+ throw new Error("Hash#digest() has already been called");
9371
+ }
9372
+ function aoutput(out, instance) {
9373
+ abytes(out, void 0, "digestInto() output");
9374
+ const min = instance.outputLen;
9375
+ if (out.length < min) {
9376
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
9377
+ }
9378
+ }
9379
+ function clean(...arrays) {
9380
+ for (let i = 0; i < arrays.length; i++) {
9381
+ arrays[i].fill(0);
9382
+ }
9383
+ }
9384
+ function createView(arr) {
9385
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
9386
+ }
9387
+ function rotr(word, shift) {
9388
+ return word << 32 - shift | word >>> shift;
9389
+ }
9390
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
9391
+ // @ts-ignore
9392
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
9393
+ ))();
9394
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
9395
+ function bytesToHex4(bytes) {
9396
+ abytes(bytes);
9397
+ if (hasHexBuiltin)
9398
+ return bytes.toHex();
9399
+ let hex = "";
9400
+ for (let i = 0; i < bytes.length; i++) {
9401
+ hex += hexes[bytes[i]];
9402
+ }
9403
+ return hex;
9404
+ }
9405
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
9406
+ function asciiToBase16(ch) {
9407
+ if (ch >= asciis._0 && ch <= asciis._9)
9408
+ return ch - asciis._0;
9409
+ if (ch >= asciis.A && ch <= asciis.F)
9410
+ return ch - (asciis.A - 10);
9411
+ if (ch >= asciis.a && ch <= asciis.f)
9412
+ return ch - (asciis.a - 10);
9413
+ return;
9414
+ }
9415
+ function hexToBytes2(hex) {
9416
+ if (typeof hex !== "string")
9417
+ throw new Error("hex string expected, got " + typeof hex);
9418
+ if (hasHexBuiltin)
9419
+ return Uint8Array.fromHex(hex);
9420
+ const hl = hex.length;
9421
+ const al = hl / 2;
9422
+ if (hl % 2)
9423
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
9424
+ const array = new Uint8Array(al);
9425
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
9426
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
9427
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
9428
+ if (n1 === void 0 || n2 === void 0) {
9429
+ const char = hex[hi] + hex[hi + 1];
9430
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
9431
+ }
9432
+ array[ai] = n1 * 16 + n2;
9433
+ }
9434
+ return array;
9435
+ }
9436
+ function concatBytes(...arrays) {
9437
+ let sum = 0;
9438
+ for (let i = 0; i < arrays.length; i++) {
9439
+ const a = arrays[i];
9440
+ abytes(a);
9441
+ sum += a.length;
9442
+ }
9443
+ const res = new Uint8Array(sum);
9444
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
9445
+ const a = arrays[i];
9446
+ res.set(a, pad);
9447
+ pad += a.length;
9448
+ }
9449
+ return res;
9450
+ }
9451
+ function createHasher(hashCons, info = {}) {
9452
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
9453
+ const tmp = hashCons(void 0);
9454
+ hashC.outputLen = tmp.outputLen;
9455
+ hashC.blockLen = tmp.blockLen;
9456
+ hashC.create = (opts) => hashCons(opts);
9457
+ Object.assign(hashC, info);
9458
+ return Object.freeze(hashC);
9459
+ }
9460
+ function randomBytes2(bytesLength = 32) {
9461
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
9462
+ if (typeof cr?.getRandomValues !== "function")
9463
+ throw new Error("crypto.getRandomValues must be defined");
9464
+ return cr.getRandomValues(new Uint8Array(bytesLength));
9465
+ }
9466
+ var oidNist = (suffix) => ({
9467
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
9468
+ });
9469
+
9470
+ // node_modules/@noble/hashes/_md.js
9471
+ function Chi(a, b, c) {
9472
+ return a & b ^ ~a & c;
9473
+ }
9474
+ function Maj(a, b, c) {
9475
+ return a & b ^ a & c ^ b & c;
9476
+ }
9477
+ var HashMD = class {
9478
+ blockLen;
9479
+ outputLen;
9480
+ padOffset;
9481
+ isLE;
9482
+ // For partial updates less than block size
9483
+ buffer;
9484
+ view;
9485
+ finished = false;
9486
+ length = 0;
9487
+ pos = 0;
9488
+ destroyed = false;
9489
+ constructor(blockLen, outputLen, padOffset, isLE) {
9490
+ this.blockLen = blockLen;
9491
+ this.outputLen = outputLen;
9492
+ this.padOffset = padOffset;
9493
+ this.isLE = isLE;
9494
+ this.buffer = new Uint8Array(blockLen);
9495
+ this.view = createView(this.buffer);
9496
+ }
9497
+ update(data) {
9498
+ aexists(this);
9499
+ abytes(data);
9500
+ const { view, buffer, blockLen } = this;
9501
+ const len = data.length;
9502
+ for (let pos = 0; pos < len; ) {
9503
+ const take = Math.min(blockLen - this.pos, len - pos);
9504
+ if (take === blockLen) {
9505
+ const dataView = createView(data);
9506
+ for (; blockLen <= len - pos; pos += blockLen)
9507
+ this.process(dataView, pos);
9508
+ continue;
9509
+ }
9510
+ buffer.set(data.subarray(pos, pos + take), this.pos);
9511
+ this.pos += take;
9512
+ pos += take;
9513
+ if (this.pos === blockLen) {
9514
+ this.process(view, 0);
9515
+ this.pos = 0;
9516
+ }
9517
+ }
9518
+ this.length += data.length;
9519
+ this.roundClean();
9520
+ return this;
9521
+ }
9522
+ digestInto(out) {
9523
+ aexists(this);
9524
+ aoutput(out, this);
9525
+ this.finished = true;
9526
+ const { buffer, view, blockLen, isLE } = this;
9527
+ let { pos } = this;
9528
+ buffer[pos++] = 128;
9529
+ clean(this.buffer.subarray(pos));
9530
+ if (this.padOffset > blockLen - pos) {
9531
+ this.process(view, 0);
9532
+ pos = 0;
9533
+ }
9534
+ for (let i = pos; i < blockLen; i++)
9535
+ buffer[i] = 0;
9536
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
9537
+ this.process(view, 0);
9538
+ const oview = createView(out);
9539
+ const len = this.outputLen;
9540
+ if (len % 4)
9541
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
9542
+ const outLen = len / 4;
9543
+ const state = this.get();
9544
+ if (outLen > state.length)
9545
+ throw new Error("_sha2: outputLen bigger than state");
9546
+ for (let i = 0; i < outLen; i++)
9547
+ oview.setUint32(4 * i, state[i], isLE);
9548
+ }
9549
+ digest() {
9550
+ const { buffer, outputLen } = this;
9551
+ this.digestInto(buffer);
9552
+ const res = buffer.slice(0, outputLen);
9553
+ this.destroy();
9554
+ return res;
9555
+ }
9556
+ _cloneInto(to) {
9557
+ to ||= new this.constructor();
9558
+ to.set(...this.get());
9559
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
9560
+ to.destroyed = destroyed;
9561
+ to.finished = finished;
9562
+ to.length = length;
9563
+ to.pos = pos;
9564
+ if (length % blockLen)
9565
+ to.buffer.set(buffer);
9566
+ return to;
9567
+ }
9568
+ clone() {
9569
+ return this._cloneInto();
9570
+ }
9571
+ };
9572
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
9573
+ 1779033703,
9574
+ 3144134277,
9575
+ 1013904242,
9576
+ 2773480762,
9577
+ 1359893119,
9578
+ 2600822924,
9579
+ 528734635,
9580
+ 1541459225
9581
+ ]);
9582
+
9583
+ // node_modules/@noble/hashes/sha2.js
9584
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
9585
+ 1116352408,
9586
+ 1899447441,
9587
+ 3049323471,
9588
+ 3921009573,
9589
+ 961987163,
9590
+ 1508970993,
9591
+ 2453635748,
9592
+ 2870763221,
9593
+ 3624381080,
9594
+ 310598401,
9595
+ 607225278,
9596
+ 1426881987,
9597
+ 1925078388,
9598
+ 2162078206,
9599
+ 2614888103,
9600
+ 3248222580,
9601
+ 3835390401,
9602
+ 4022224774,
9603
+ 264347078,
9604
+ 604807628,
9605
+ 770255983,
9606
+ 1249150122,
9607
+ 1555081692,
9608
+ 1996064986,
9609
+ 2554220882,
9610
+ 2821834349,
9611
+ 2952996808,
9612
+ 3210313671,
9613
+ 3336571891,
9614
+ 3584528711,
9615
+ 113926993,
9616
+ 338241895,
9617
+ 666307205,
9618
+ 773529912,
9619
+ 1294757372,
9620
+ 1396182291,
9621
+ 1695183700,
9622
+ 1986661051,
9623
+ 2177026350,
9624
+ 2456956037,
9625
+ 2730485921,
9626
+ 2820302411,
9627
+ 3259730800,
9628
+ 3345764771,
9629
+ 3516065817,
9630
+ 3600352804,
9631
+ 4094571909,
9632
+ 275423344,
9633
+ 430227734,
9634
+ 506948616,
9635
+ 659060556,
9636
+ 883997877,
9637
+ 958139571,
9638
+ 1322822218,
9639
+ 1537002063,
9640
+ 1747873779,
9641
+ 1955562222,
9642
+ 2024104815,
9643
+ 2227730452,
9644
+ 2361852424,
9645
+ 2428436474,
9646
+ 2756734187,
9647
+ 3204031479,
9648
+ 3329325298
9649
+ ]);
9650
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
9651
+ var SHA2_32B = class extends HashMD {
9652
+ constructor(outputLen) {
9653
+ super(64, outputLen, 8, false);
9654
+ }
9655
+ get() {
9656
+ const { A, B, C, D, E, F, G, H } = this;
9657
+ return [A, B, C, D, E, F, G, H];
9658
+ }
9659
+ // prettier-ignore
9660
+ set(A, B, C, D, E, F, G, H) {
9661
+ this.A = A | 0;
9662
+ this.B = B | 0;
9663
+ this.C = C | 0;
9664
+ this.D = D | 0;
9665
+ this.E = E | 0;
9666
+ this.F = F | 0;
9667
+ this.G = G | 0;
9668
+ this.H = H | 0;
9669
+ }
9670
+ process(view, offset) {
9671
+ for (let i = 0; i < 16; i++, offset += 4)
9672
+ SHA256_W[i] = view.getUint32(offset, false);
9673
+ for (let i = 16; i < 64; i++) {
9674
+ const W15 = SHA256_W[i - 15];
9675
+ const W2 = SHA256_W[i - 2];
9676
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
9677
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
9678
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
9679
+ }
9680
+ let { A, B, C, D, E, F, G, H } = this;
9681
+ for (let i = 0; i < 64; i++) {
9682
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
9683
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
9684
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
9685
+ const T2 = sigma0 + Maj(A, B, C) | 0;
9686
+ H = G;
9687
+ G = F;
9688
+ F = E;
9689
+ E = D + T1 | 0;
9690
+ D = C;
9691
+ C = B;
9692
+ B = A;
9693
+ A = T1 + T2 | 0;
9694
+ }
9695
+ A = A + this.A | 0;
9696
+ B = B + this.B | 0;
9697
+ C = C + this.C | 0;
9698
+ D = D + this.D | 0;
9699
+ E = E + this.E | 0;
9700
+ F = F + this.F | 0;
9701
+ G = G + this.G | 0;
9702
+ H = H + this.H | 0;
9703
+ this.set(A, B, C, D, E, F, G, H);
9704
+ }
9705
+ roundClean() {
9706
+ clean(SHA256_W);
9707
+ }
9708
+ destroy() {
9709
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
9710
+ clean(this.buffer);
9711
+ }
9712
+ };
9713
+ var _SHA256 = class extends SHA2_32B {
9714
+ // We cannot use array here since array allows indexing by variable
9715
+ // which means optimizer/compiler cannot use registers.
9716
+ A = SHA256_IV[0] | 0;
9717
+ B = SHA256_IV[1] | 0;
9718
+ C = SHA256_IV[2] | 0;
9719
+ D = SHA256_IV[3] | 0;
9720
+ E = SHA256_IV[4] | 0;
9721
+ F = SHA256_IV[5] | 0;
9722
+ G = SHA256_IV[6] | 0;
9723
+ H = SHA256_IV[7] | 0;
9724
+ constructor() {
9725
+ super(32);
9726
+ }
9727
+ };
9728
+ var sha2564 = /* @__PURE__ */ createHasher(
9729
+ () => new _SHA256(),
9730
+ /* @__PURE__ */ oidNist(1)
9731
+ );
9732
+
9733
+ // node_modules/@noble/curves/utils.js
9734
+ var _0n = /* @__PURE__ */ BigInt(0);
9735
+ var _1n = /* @__PURE__ */ BigInt(1);
9736
+ function abool(value, title = "") {
9737
+ if (typeof value !== "boolean") {
9738
+ const prefix = title && `"${title}" `;
9739
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
9740
+ }
9741
+ return value;
9742
+ }
9743
+ function abignumber(n) {
9744
+ if (typeof n === "bigint") {
9745
+ if (!isPosBig(n))
9746
+ throw new Error("positive bigint expected, got " + n);
9747
+ } else
9748
+ anumber(n);
9749
+ return n;
9750
+ }
9751
+ function numberToHexUnpadded(num) {
9752
+ const hex = abignumber(num).toString(16);
9753
+ return hex.length & 1 ? "0" + hex : hex;
9754
+ }
9755
+ function hexToNumber(hex) {
9756
+ if (typeof hex !== "string")
9757
+ throw new Error("hex string expected, got " + typeof hex);
9758
+ return hex === "" ? _0n : BigInt("0x" + hex);
9759
+ }
9760
+ function bytesToNumberBE(bytes) {
9761
+ return hexToNumber(bytesToHex4(bytes));
9762
+ }
9763
+ function bytesToNumberLE(bytes) {
9764
+ return hexToNumber(bytesToHex4(copyBytes(abytes(bytes)).reverse()));
9765
+ }
9766
+ function numberToBytesBE(n, len) {
9767
+ anumber(len);
9768
+ n = abignumber(n);
9769
+ const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
9770
+ if (res.length !== len)
9771
+ throw new Error("number too large");
9772
+ return res;
9773
+ }
9774
+ function numberToBytesLE(n, len) {
9775
+ return numberToBytesBE(n, len).reverse();
9776
+ }
9777
+ function copyBytes(bytes) {
9778
+ return Uint8Array.from(bytes);
9779
+ }
9780
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
9781
+ function inRange(n, min, max) {
9782
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
9783
+ }
9784
+ function aInRange(title, n, min, max) {
9785
+ if (!inRange(n, min, max))
9786
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
9787
+ }
9788
+ function bitLen(n) {
9789
+ let len;
9790
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
9791
+ ;
9792
+ return len;
9793
+ }
9794
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
9795
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
9796
+ anumber(hashLen, "hashLen");
9797
+ anumber(qByteLen, "qByteLen");
9798
+ if (typeof hmacFn !== "function")
9799
+ throw new Error("hmacFn must be a function");
9800
+ const u8n = (len) => new Uint8Array(len);
9801
+ const NULL = Uint8Array.of();
9802
+ const byte0 = Uint8Array.of(0);
9803
+ const byte1 = Uint8Array.of(1);
9804
+ const _maxDrbgIters = 1e3;
9805
+ let v = u8n(hashLen);
9806
+ let k = u8n(hashLen);
9807
+ let i = 0;
9808
+ const reset = () => {
9809
+ v.fill(1);
9810
+ k.fill(0);
9811
+ i = 0;
9812
+ };
9813
+ const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
9814
+ const reseed = (seed = NULL) => {
9815
+ k = h(byte0, seed);
9816
+ v = h();
9817
+ if (seed.length === 0)
9818
+ return;
9819
+ k = h(byte1, seed);
9820
+ v = h();
9821
+ };
9822
+ const gen = () => {
9823
+ if (i++ >= _maxDrbgIters)
9824
+ throw new Error("drbg: tried max amount of iterations");
9825
+ let len = 0;
9826
+ const out = [];
9827
+ while (len < qByteLen) {
9828
+ v = h();
9829
+ const sl = v.slice();
9830
+ out.push(sl);
9831
+ len += v.length;
9832
+ }
9833
+ return concatBytes(...out);
9834
+ };
9835
+ const genUntil = (seed, pred) => {
9836
+ reset();
9837
+ reseed(seed);
9838
+ let res = void 0;
9839
+ while (!(res = pred(gen())))
9840
+ reseed();
9841
+ reset();
9842
+ return res;
9843
+ };
9844
+ return genUntil;
9845
+ }
9846
+ function validateObject(object, fields = {}, optFields = {}) {
9847
+ if (!object || typeof object !== "object")
9848
+ throw new Error("expected valid options object");
9849
+ function checkField(fieldName, expectedType, isOpt) {
9850
+ const val = object[fieldName];
9851
+ if (isOpt && val === void 0)
9852
+ return;
9853
+ const current = typeof val;
9854
+ if (current !== expectedType || val === null)
9855
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
9856
+ }
9857
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
9858
+ iter(fields, false);
9859
+ iter(optFields, true);
9860
+ }
9861
+ function memoized(fn) {
9862
+ const map = /* @__PURE__ */ new WeakMap();
9863
+ return (arg, ...args) => {
9864
+ const val = map.get(arg);
9865
+ if (val !== void 0)
9866
+ return val;
9867
+ const computed = fn(arg, ...args);
9868
+ map.set(arg, computed);
9869
+ return computed;
9870
+ };
9871
+ }
9872
+
9873
+ // node_modules/@noble/curves/abstract/modular.js
9874
+ var _0n2 = /* @__PURE__ */ BigInt(0);
9875
+ var _1n2 = /* @__PURE__ */ BigInt(1);
9876
+ var _2n = /* @__PURE__ */ BigInt(2);
9877
+ var _3n = /* @__PURE__ */ BigInt(3);
9878
+ var _4n = /* @__PURE__ */ BigInt(4);
9879
+ var _5n = /* @__PURE__ */ BigInt(5);
9880
+ var _7n = /* @__PURE__ */ BigInt(7);
9881
+ var _8n = /* @__PURE__ */ BigInt(8);
9882
+ var _9n = /* @__PURE__ */ BigInt(9);
9883
+ var _16n = /* @__PURE__ */ BigInt(16);
9884
+ function mod(a, b) {
9885
+ const result = a % b;
9886
+ return result >= _0n2 ? result : b + result;
9887
+ }
9888
+ function pow2(x, power, modulo) {
9889
+ let res = x;
9890
+ while (power-- > _0n2) {
9891
+ res *= res;
9892
+ res %= modulo;
9893
+ }
9894
+ return res;
9895
+ }
9896
+ function invert(number, modulo) {
9897
+ if (number === _0n2)
9898
+ throw new Error("invert: expected non-zero number");
9899
+ if (modulo <= _0n2)
9900
+ throw new Error("invert: expected positive modulus, got " + modulo);
9901
+ let a = mod(number, modulo);
9902
+ let b = modulo;
9903
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
9904
+ while (a !== _0n2) {
9905
+ const q = b / a;
9906
+ const r = b % a;
9907
+ const m = x - u * q;
9908
+ const n = y - v * q;
9909
+ b = a, a = r, x = u, y = v, u = m, v = n;
9910
+ }
9911
+ const gcd = b;
9912
+ if (gcd !== _1n2)
9913
+ throw new Error("invert: does not exist");
9914
+ return mod(x, modulo);
9915
+ }
9916
+ function assertIsSquare(Fp, root, n) {
9917
+ if (!Fp.eql(Fp.sqr(root), n))
9918
+ throw new Error("Cannot find square root");
9919
+ }
9920
+ function sqrt3mod4(Fp, n) {
9921
+ const p1div4 = (Fp.ORDER + _1n2) / _4n;
9922
+ const root = Fp.pow(n, p1div4);
9923
+ assertIsSquare(Fp, root, n);
9924
+ return root;
9925
+ }
9926
+ function sqrt5mod8(Fp, n) {
9927
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
9928
+ const n2 = Fp.mul(n, _2n);
9929
+ const v = Fp.pow(n2, p5div8);
9930
+ const nv = Fp.mul(n, v);
9931
+ const i = Fp.mul(Fp.mul(nv, _2n), v);
9932
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
9933
+ assertIsSquare(Fp, root, n);
9934
+ return root;
9935
+ }
9936
+ function sqrt9mod16(P) {
9937
+ const Fp_ = Field(P);
9938
+ const tn = tonelliShanks(P);
9939
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
9940
+ const c2 = tn(Fp_, c1);
9941
+ const c3 = tn(Fp_, Fp_.neg(c1));
9942
+ const c4 = (P + _7n) / _16n;
9943
+ return (Fp, n) => {
9944
+ let tv1 = Fp.pow(n, c4);
9945
+ let tv2 = Fp.mul(tv1, c1);
9946
+ const tv3 = Fp.mul(tv1, c2);
9947
+ const tv4 = Fp.mul(tv1, c3);
9948
+ const e1 = Fp.eql(Fp.sqr(tv2), n);
9949
+ const e2 = Fp.eql(Fp.sqr(tv3), n);
9950
+ tv1 = Fp.cmov(tv1, tv2, e1);
9951
+ tv2 = Fp.cmov(tv4, tv3, e2);
9952
+ const e3 = Fp.eql(Fp.sqr(tv2), n);
9953
+ const root = Fp.cmov(tv1, tv2, e3);
9954
+ assertIsSquare(Fp, root, n);
9955
+ return root;
9956
+ };
9957
+ }
9958
+ function tonelliShanks(P) {
9959
+ if (P < _3n)
9960
+ throw new Error("sqrt is not defined for small field");
9961
+ let Q = P - _1n2;
9962
+ let S = 0;
9963
+ while (Q % _2n === _0n2) {
9964
+ Q /= _2n;
9965
+ S++;
9966
+ }
9967
+ let Z = _2n;
9968
+ const _Fp = Field(P);
9969
+ while (FpLegendre(_Fp, Z) === 1) {
9970
+ if (Z++ > 1e3)
9971
+ throw new Error("Cannot find square root: probably non-prime P");
9972
+ }
9973
+ if (S === 1)
9974
+ return sqrt3mod4;
9975
+ let cc = _Fp.pow(Z, Q);
9976
+ const Q1div2 = (Q + _1n2) / _2n;
9977
+ return function tonelliSlow(Fp, n) {
9978
+ if (Fp.is0(n))
9979
+ return n;
9980
+ if (FpLegendre(Fp, n) !== 1)
9981
+ throw new Error("Cannot find square root");
9982
+ let M = S;
9983
+ let c = Fp.mul(Fp.ONE, cc);
9984
+ let t = Fp.pow(n, Q);
9985
+ let R = Fp.pow(n, Q1div2);
9986
+ while (!Fp.eql(t, Fp.ONE)) {
9987
+ if (Fp.is0(t))
9988
+ return Fp.ZERO;
9989
+ let i = 1;
9990
+ let t_tmp = Fp.sqr(t);
9991
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
9992
+ i++;
9993
+ t_tmp = Fp.sqr(t_tmp);
9994
+ if (i === M)
9995
+ throw new Error("Cannot find square root");
9996
+ }
9997
+ const exponent = _1n2 << BigInt(M - i - 1);
9998
+ const b = Fp.pow(c, exponent);
9999
+ M = i;
10000
+ c = Fp.sqr(b);
10001
+ t = Fp.mul(t, c);
10002
+ R = Fp.mul(R, b);
10003
+ }
10004
+ return R;
10005
+ };
10006
+ }
10007
+ function FpSqrt(P) {
10008
+ if (P % _4n === _3n)
10009
+ return sqrt3mod4;
10010
+ if (P % _8n === _5n)
10011
+ return sqrt5mod8;
10012
+ if (P % _16n === _9n)
10013
+ return sqrt9mod16(P);
10014
+ return tonelliShanks(P);
10015
+ }
10016
+ var FIELD_FIELDS = [
10017
+ "create",
10018
+ "isValid",
10019
+ "is0",
10020
+ "neg",
10021
+ "inv",
10022
+ "sqrt",
10023
+ "sqr",
10024
+ "eql",
10025
+ "add",
10026
+ "sub",
10027
+ "mul",
10028
+ "pow",
10029
+ "div",
10030
+ "addN",
10031
+ "subN",
10032
+ "mulN",
10033
+ "sqrN"
10034
+ ];
10035
+ function validateField(field) {
10036
+ const initial = {
10037
+ ORDER: "bigint",
10038
+ BYTES: "number",
10039
+ BITS: "number"
10040
+ };
10041
+ const opts = FIELD_FIELDS.reduce((map, val) => {
10042
+ map[val] = "function";
10043
+ return map;
10044
+ }, initial);
10045
+ validateObject(field, opts);
10046
+ return field;
10047
+ }
10048
+ function FpPow(Fp, num, power) {
10049
+ if (power < _0n2)
10050
+ throw new Error("invalid exponent, negatives unsupported");
10051
+ if (power === _0n2)
10052
+ return Fp.ONE;
10053
+ if (power === _1n2)
10054
+ return num;
10055
+ let p = Fp.ONE;
10056
+ let d = num;
10057
+ while (power > _0n2) {
10058
+ if (power & _1n2)
10059
+ p = Fp.mul(p, d);
10060
+ d = Fp.sqr(d);
10061
+ power >>= _1n2;
10062
+ }
10063
+ return p;
10064
+ }
10065
+ function FpInvertBatch(Fp, nums, passZero = false) {
10066
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
10067
+ const multipliedAcc = nums.reduce((acc, num, i) => {
10068
+ if (Fp.is0(num))
10069
+ return acc;
10070
+ inverted[i] = acc;
10071
+ return Fp.mul(acc, num);
10072
+ }, Fp.ONE);
10073
+ const invertedAcc = Fp.inv(multipliedAcc);
10074
+ nums.reduceRight((acc, num, i) => {
10075
+ if (Fp.is0(num))
10076
+ return acc;
10077
+ inverted[i] = Fp.mul(acc, inverted[i]);
10078
+ return Fp.mul(acc, num);
10079
+ }, invertedAcc);
10080
+ return inverted;
10081
+ }
10082
+ function FpLegendre(Fp, n) {
10083
+ const p1mod2 = (Fp.ORDER - _1n2) / _2n;
10084
+ const powered = Fp.pow(n, p1mod2);
10085
+ const yes = Fp.eql(powered, Fp.ONE);
10086
+ const zero = Fp.eql(powered, Fp.ZERO);
10087
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
10088
+ if (!yes && !zero && !no)
10089
+ throw new Error("invalid Legendre symbol result");
10090
+ return yes ? 1 : zero ? 0 : -1;
10091
+ }
10092
+ function nLength(n, nBitLength) {
10093
+ if (nBitLength !== void 0)
10094
+ anumber(nBitLength);
10095
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
10096
+ const nByteLength = Math.ceil(_nBitLength / 8);
10097
+ return { nBitLength: _nBitLength, nByteLength };
10098
+ }
10099
+ var _Field = class {
10100
+ ORDER;
10101
+ BITS;
10102
+ BYTES;
10103
+ isLE;
10104
+ ZERO = _0n2;
10105
+ ONE = _1n2;
10106
+ _lengths;
10107
+ _sqrt;
10108
+ // cached sqrt
10109
+ _mod;
10110
+ constructor(ORDER, opts = {}) {
10111
+ if (ORDER <= _0n2)
10112
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
10113
+ let _nbitLength = void 0;
10114
+ this.isLE = false;
10115
+ if (opts != null && typeof opts === "object") {
10116
+ if (typeof opts.BITS === "number")
10117
+ _nbitLength = opts.BITS;
10118
+ if (typeof opts.sqrt === "function")
10119
+ this.sqrt = opts.sqrt;
10120
+ if (typeof opts.isLE === "boolean")
10121
+ this.isLE = opts.isLE;
10122
+ if (opts.allowedLengths)
10123
+ this._lengths = opts.allowedLengths?.slice();
10124
+ if (typeof opts.modFromBytes === "boolean")
10125
+ this._mod = opts.modFromBytes;
10126
+ }
10127
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
10128
+ if (nByteLength > 2048)
10129
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
10130
+ this.ORDER = ORDER;
10131
+ this.BITS = nBitLength;
10132
+ this.BYTES = nByteLength;
10133
+ this._sqrt = void 0;
10134
+ Object.preventExtensions(this);
10135
+ }
10136
+ create(num) {
10137
+ return mod(num, this.ORDER);
10138
+ }
10139
+ isValid(num) {
10140
+ if (typeof num !== "bigint")
10141
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
10142
+ return _0n2 <= num && num < this.ORDER;
10143
+ }
10144
+ is0(num) {
10145
+ return num === _0n2;
10146
+ }
10147
+ // is valid and invertible
10148
+ isValidNot0(num) {
10149
+ return !this.is0(num) && this.isValid(num);
10150
+ }
10151
+ isOdd(num) {
10152
+ return (num & _1n2) === _1n2;
10153
+ }
10154
+ neg(num) {
10155
+ return mod(-num, this.ORDER);
10156
+ }
10157
+ eql(lhs, rhs) {
10158
+ return lhs === rhs;
10159
+ }
10160
+ sqr(num) {
10161
+ return mod(num * num, this.ORDER);
10162
+ }
10163
+ add(lhs, rhs) {
10164
+ return mod(lhs + rhs, this.ORDER);
10165
+ }
10166
+ sub(lhs, rhs) {
10167
+ return mod(lhs - rhs, this.ORDER);
10168
+ }
10169
+ mul(lhs, rhs) {
10170
+ return mod(lhs * rhs, this.ORDER);
10171
+ }
10172
+ pow(num, power) {
10173
+ return FpPow(this, num, power);
10174
+ }
10175
+ div(lhs, rhs) {
10176
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
10177
+ }
10178
+ // Same as above, but doesn't normalize
10179
+ sqrN(num) {
10180
+ return num * num;
10181
+ }
10182
+ addN(lhs, rhs) {
10183
+ return lhs + rhs;
10184
+ }
10185
+ subN(lhs, rhs) {
10186
+ return lhs - rhs;
10187
+ }
10188
+ mulN(lhs, rhs) {
10189
+ return lhs * rhs;
10190
+ }
10191
+ inv(num) {
10192
+ return invert(num, this.ORDER);
10193
+ }
10194
+ sqrt(num) {
10195
+ if (!this._sqrt)
10196
+ this._sqrt = FpSqrt(this.ORDER);
10197
+ return this._sqrt(this, num);
10198
+ }
10199
+ toBytes(num) {
10200
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
10201
+ }
10202
+ fromBytes(bytes, skipValidation = false) {
10203
+ abytes(bytes);
10204
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
10205
+ if (allowedLengths) {
10206
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
10207
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
10208
+ }
10209
+ const padded = new Uint8Array(BYTES);
10210
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
10211
+ bytes = padded;
10212
+ }
10213
+ if (bytes.length !== BYTES)
10214
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
10215
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
10216
+ if (modFromBytes)
10217
+ scalar = mod(scalar, ORDER);
10218
+ if (!skipValidation) {
10219
+ if (!this.isValid(scalar))
10220
+ throw new Error("invalid field element: outside of range 0..ORDER");
10221
+ }
10222
+ return scalar;
10223
+ }
10224
+ // TODO: we don't need it here, move out to separate fn
10225
+ invertBatch(lst) {
10226
+ return FpInvertBatch(this, lst);
10227
+ }
10228
+ // We can't move this out because Fp6, Fp12 implement it
10229
+ // and it's unclear what to return in there.
10230
+ cmov(a, b, condition) {
10231
+ return condition ? b : a;
10232
+ }
10233
+ };
10234
+ function Field(ORDER, opts = {}) {
10235
+ return new _Field(ORDER, opts);
10236
+ }
10237
+ function getFieldBytesLength(fieldOrder) {
10238
+ if (typeof fieldOrder !== "bigint")
10239
+ throw new Error("field order must be bigint");
10240
+ const bitLength = fieldOrder.toString(2).length;
10241
+ return Math.ceil(bitLength / 8);
10242
+ }
10243
+ function getMinHashLength(fieldOrder) {
10244
+ const length = getFieldBytesLength(fieldOrder);
10245
+ return length + Math.ceil(length / 2);
10246
+ }
10247
+ function mapHashToField(key, fieldOrder, isLE = false) {
10248
+ abytes(key);
10249
+ const len = key.length;
10250
+ const fieldLen = getFieldBytesLength(fieldOrder);
10251
+ const minLen = getMinHashLength(fieldOrder);
10252
+ if (len < 16 || len < minLen || len > 1024)
10253
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
10254
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
10255
+ const reduced = mod(num, fieldOrder - _1n2) + _1n2;
10256
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
10257
+ }
10258
+
10259
+ // node_modules/@noble/curves/abstract/curve.js
10260
+ var _0n3 = /* @__PURE__ */ BigInt(0);
10261
+ var _1n3 = /* @__PURE__ */ BigInt(1);
10262
+ function negateCt(condition, item) {
10263
+ const neg = item.negate();
10264
+ return condition ? neg : item;
10265
+ }
10266
+ function normalizeZ(c, points) {
10267
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
10268
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
10269
+ }
10270
+ function validateW(W, bits) {
10271
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
10272
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
10273
+ }
10274
+ function calcWOpts(W, scalarBits) {
10275
+ validateW(W, scalarBits);
10276
+ const windows = Math.ceil(scalarBits / W) + 1;
10277
+ const windowSize = 2 ** (W - 1);
10278
+ const maxNumber = 2 ** W;
10279
+ const mask = bitMask(W);
10280
+ const shiftBy = BigInt(W);
10281
+ return { windows, windowSize, mask, maxNumber, shiftBy };
10282
+ }
10283
+ function calcOffsets(n, window, wOpts) {
10284
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
10285
+ let wbits = Number(n & mask);
10286
+ let nextN = n >> shiftBy;
10287
+ if (wbits > windowSize) {
10288
+ wbits -= maxNumber;
10289
+ nextN += _1n3;
10290
+ }
10291
+ const offsetStart = window * windowSize;
10292
+ const offset = offsetStart + Math.abs(wbits) - 1;
10293
+ const isZero = wbits === 0;
10294
+ const isNeg = wbits < 0;
10295
+ const isNegF = window % 2 !== 0;
10296
+ const offsetF = offsetStart;
10297
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
10298
+ }
10299
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
10300
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
10301
+ function getW(P) {
10302
+ return pointWindowSizes.get(P) || 1;
10303
+ }
10304
+ function assert0(n) {
10305
+ if (n !== _0n3)
10306
+ throw new Error("invalid wNAF");
10307
+ }
10308
+ var wNAF = class {
10309
+ BASE;
10310
+ ZERO;
10311
+ Fn;
10312
+ bits;
10313
+ // Parametrized with a given Point class (not individual point)
10314
+ constructor(Point, bits) {
10315
+ this.BASE = Point.BASE;
10316
+ this.ZERO = Point.ZERO;
10317
+ this.Fn = Point.Fn;
10318
+ this.bits = bits;
10319
+ }
10320
+ // non-const time multiplication ladder
10321
+ _unsafeLadder(elm, n, p = this.ZERO) {
10322
+ let d = elm;
10323
+ while (n > _0n3) {
10324
+ if (n & _1n3)
10325
+ p = p.add(d);
10326
+ d = d.double();
10327
+ n >>= _1n3;
10328
+ }
10329
+ return p;
10330
+ }
10331
+ /**
10332
+ * Creates a wNAF precomputation window. Used for caching.
10333
+ * Default window size is set by `utils.precompute()` and is equal to 8.
10334
+ * Number of precomputed points depends on the curve size:
10335
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
10336
+ * - 𝑊 is the window size
10337
+ * - 𝑛 is the bitlength of the curve order.
10338
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
10339
+ * @param point Point instance
10340
+ * @param W window size
10341
+ * @returns precomputed point tables flattened to a single array
10342
+ */
10343
+ precomputeWindow(point, W) {
10344
+ const { windows, windowSize } = calcWOpts(W, this.bits);
10345
+ const points = [];
10346
+ let p = point;
10347
+ let base = p;
10348
+ for (let window = 0; window < windows; window++) {
10349
+ base = p;
10350
+ points.push(base);
10351
+ for (let i = 1; i < windowSize; i++) {
10352
+ base = base.add(p);
10353
+ points.push(base);
10354
+ }
10355
+ p = base.double();
10356
+ }
10357
+ return points;
10358
+ }
10359
+ /**
10360
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
10361
+ * More compact implementation:
10362
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
10363
+ * @returns real and fake (for const-time) points
10364
+ */
10365
+ wNAF(W, precomputes, n) {
10366
+ if (!this.Fn.isValid(n))
10367
+ throw new Error("invalid scalar");
10368
+ let p = this.ZERO;
10369
+ let f = this.BASE;
10370
+ const wo = calcWOpts(W, this.bits);
10371
+ for (let window = 0; window < wo.windows; window++) {
10372
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
10373
+ n = nextN;
10374
+ if (isZero) {
10375
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
10376
+ } else {
10377
+ p = p.add(negateCt(isNeg, precomputes[offset]));
10378
+ }
10379
+ }
10380
+ assert0(n);
10381
+ return { p, f };
10382
+ }
10383
+ /**
10384
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
10385
+ * @param acc accumulator point to add result of multiplication
10386
+ * @returns point
10387
+ */
10388
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
10389
+ const wo = calcWOpts(W, this.bits);
10390
+ for (let window = 0; window < wo.windows; window++) {
10391
+ if (n === _0n3)
10392
+ break;
10393
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
10394
+ n = nextN;
10395
+ if (isZero) {
10396
+ continue;
10397
+ } else {
10398
+ const item = precomputes[offset];
10399
+ acc = acc.add(isNeg ? item.negate() : item);
10400
+ }
10401
+ }
10402
+ assert0(n);
10403
+ return acc;
10404
+ }
10405
+ getPrecomputes(W, point, transform) {
10406
+ let comp = pointPrecomputes.get(point);
10407
+ if (!comp) {
10408
+ comp = this.precomputeWindow(point, W);
10409
+ if (W !== 1) {
10410
+ if (typeof transform === "function")
10411
+ comp = transform(comp);
10412
+ pointPrecomputes.set(point, comp);
10413
+ }
10414
+ }
10415
+ return comp;
10416
+ }
10417
+ cached(point, scalar, transform) {
10418
+ const W = getW(point);
10419
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
10420
+ }
10421
+ unsafe(point, scalar, transform, prev) {
10422
+ const W = getW(point);
10423
+ if (W === 1)
10424
+ return this._unsafeLadder(point, scalar, prev);
10425
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
10426
+ }
10427
+ // We calculate precomputes for elliptic curve point multiplication
10428
+ // using windowed method. This specifies window size and
10429
+ // stores precomputed values. Usually only base point would be precomputed.
10430
+ createCache(P, W) {
10431
+ validateW(W, this.bits);
10432
+ pointWindowSizes.set(P, W);
10433
+ pointPrecomputes.delete(P);
10434
+ }
10435
+ hasCache(elm) {
10436
+ return getW(elm) !== 1;
10437
+ }
10438
+ };
10439
+ function mulEndoUnsafe(Point, point, k1, k2) {
10440
+ let acc = point;
10441
+ let p1 = Point.ZERO;
10442
+ let p2 = Point.ZERO;
10443
+ while (k1 > _0n3 || k2 > _0n3) {
10444
+ if (k1 & _1n3)
10445
+ p1 = p1.add(acc);
10446
+ if (k2 & _1n3)
10447
+ p2 = p2.add(acc);
10448
+ acc = acc.double();
10449
+ k1 >>= _1n3;
10450
+ k2 >>= _1n3;
10451
+ }
10452
+ return { p1, p2 };
10453
+ }
10454
+ function createField(order, field, isLE) {
10455
+ if (field) {
10456
+ if (field.ORDER !== order)
10457
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
10458
+ validateField(field);
10459
+ return field;
10460
+ } else {
10461
+ return Field(order, { isLE });
10462
+ }
10463
+ }
10464
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
10465
+ if (FpFnLE === void 0)
10466
+ FpFnLE = type === "edwards";
10467
+ if (!CURVE || typeof CURVE !== "object")
10468
+ throw new Error(`expected valid ${type} CURVE object`);
10469
+ for (const p of ["p", "n", "h"]) {
10470
+ const val = CURVE[p];
10471
+ if (!(typeof val === "bigint" && val > _0n3))
10472
+ throw new Error(`CURVE.${p} must be positive bigint`);
10473
+ }
10474
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
10475
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
10476
+ const _b = type === "weierstrass" ? "b" : "d";
10477
+ const params = ["Gx", "Gy", "a", _b];
10478
+ for (const p of params) {
10479
+ if (!Fp.isValid(CURVE[p]))
10480
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
10481
+ }
10482
+ CURVE = Object.freeze(Object.assign({}, CURVE));
10483
+ return { CURVE, Fp, Fn };
10484
+ }
10485
+ function createKeygen(randomSecretKey, getPublicKey2) {
10486
+ return function keygen(seed) {
10487
+ const secretKey = randomSecretKey(seed);
10488
+ return { secretKey, publicKey: getPublicKey2(secretKey) };
10489
+ };
10490
+ }
10491
+
10492
+ // node_modules/@noble/hashes/hmac.js
10493
+ var _HMAC = class {
10494
+ oHash;
10495
+ iHash;
10496
+ blockLen;
10497
+ outputLen;
10498
+ finished = false;
10499
+ destroyed = false;
10500
+ constructor(hash, key) {
10501
+ ahash(hash);
10502
+ abytes(key, void 0, "key");
10503
+ this.iHash = hash.create();
10504
+ if (typeof this.iHash.update !== "function")
10505
+ throw new Error("Expected instance of class which extends utils.Hash");
10506
+ this.blockLen = this.iHash.blockLen;
10507
+ this.outputLen = this.iHash.outputLen;
10508
+ const blockLen = this.blockLen;
10509
+ const pad = new Uint8Array(blockLen);
10510
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
10511
+ for (let i = 0; i < pad.length; i++)
10512
+ pad[i] ^= 54;
10513
+ this.iHash.update(pad);
10514
+ this.oHash = hash.create();
10515
+ for (let i = 0; i < pad.length; i++)
10516
+ pad[i] ^= 54 ^ 92;
10517
+ this.oHash.update(pad);
10518
+ clean(pad);
10519
+ }
10520
+ update(buf) {
10521
+ aexists(this);
10522
+ this.iHash.update(buf);
10523
+ return this;
10524
+ }
10525
+ digestInto(out) {
10526
+ aexists(this);
10527
+ abytes(out, this.outputLen, "output");
10528
+ this.finished = true;
10529
+ this.iHash.digestInto(out);
10530
+ this.oHash.update(out);
10531
+ this.oHash.digestInto(out);
10532
+ this.destroy();
10533
+ }
10534
+ digest() {
10535
+ const out = new Uint8Array(this.oHash.outputLen);
10536
+ this.digestInto(out);
10537
+ return out;
10538
+ }
10539
+ _cloneInto(to) {
10540
+ to ||= Object.create(Object.getPrototypeOf(this), {});
10541
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
10542
+ to = to;
10543
+ to.finished = finished;
10544
+ to.destroyed = destroyed;
10545
+ to.blockLen = blockLen;
10546
+ to.outputLen = outputLen;
10547
+ to.oHash = oHash._cloneInto(to.oHash);
10548
+ to.iHash = iHash._cloneInto(to.iHash);
10549
+ return to;
10550
+ }
10551
+ clone() {
10552
+ return this._cloneInto();
10553
+ }
10554
+ destroy() {
10555
+ this.destroyed = true;
10556
+ this.oHash.destroy();
10557
+ this.iHash.destroy();
10558
+ }
10559
+ };
10560
+ var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
10561
+ hmac.create = (hash, key) => new _HMAC(hash, key);
10562
+
10563
+ // node_modules/@noble/curves/abstract/weierstrass.js
10564
+ var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
10565
+ function _splitEndoScalar(k, basis, n) {
10566
+ const [[a1, b1], [a2, b2]] = basis;
10567
+ const c1 = divNearest(b2 * k, n);
10568
+ const c2 = divNearest(-b1 * k, n);
10569
+ let k1 = k - c1 * a1 - c2 * a2;
10570
+ let k2 = -c1 * b1 - c2 * b2;
10571
+ const k1neg = k1 < _0n4;
10572
+ const k2neg = k2 < _0n4;
10573
+ if (k1neg)
10574
+ k1 = -k1;
10575
+ if (k2neg)
10576
+ k2 = -k2;
10577
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
10578
+ if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
10579
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
10580
+ }
10581
+ return { k1neg, k1, k2neg, k2 };
10582
+ }
10583
+ function validateSigFormat(format) {
10584
+ if (!["compact", "recovered", "der"].includes(format))
10585
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
10586
+ return format;
10587
+ }
10588
+ function validateSigOpts(opts, def) {
10589
+ const optsn = {};
10590
+ for (let optName of Object.keys(def)) {
10591
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
10592
+ }
10593
+ abool(optsn.lowS, "lowS");
10594
+ abool(optsn.prehash, "prehash");
10595
+ if (optsn.format !== void 0)
10596
+ validateSigFormat(optsn.format);
10597
+ return optsn;
10598
+ }
10599
+ var DERErr = class extends Error {
10600
+ constructor(m = "") {
10601
+ super(m);
10602
+ }
10603
+ };
10604
+ var DER = {
10605
+ // asn.1 DER encoding utils
10606
+ Err: DERErr,
10607
+ // Basic building block is TLV (Tag-Length-Value)
10608
+ _tlv: {
10609
+ encode: (tag, data) => {
10610
+ const { Err: E } = DER;
10611
+ if (tag < 0 || tag > 256)
10612
+ throw new E("tlv.encode: wrong tag");
10613
+ if (data.length & 1)
10614
+ throw new E("tlv.encode: unpadded data");
10615
+ const dataLen = data.length / 2;
10616
+ const len = numberToHexUnpadded(dataLen);
10617
+ if (len.length / 2 & 128)
10618
+ throw new E("tlv.encode: long form length too big");
10619
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
10620
+ const t = numberToHexUnpadded(tag);
10621
+ return t + lenLen + len + data;
10622
+ },
10623
+ // v - value, l - left bytes (unparsed)
10624
+ decode(tag, data) {
10625
+ const { Err: E } = DER;
10626
+ let pos = 0;
10627
+ if (tag < 0 || tag > 256)
10628
+ throw new E("tlv.encode: wrong tag");
10629
+ if (data.length < 2 || data[pos++] !== tag)
10630
+ throw new E("tlv.decode: wrong tlv");
10631
+ const first = data[pos++];
10632
+ const isLong = !!(first & 128);
10633
+ let length = 0;
10634
+ if (!isLong)
10635
+ length = first;
10636
+ else {
10637
+ const lenLen = first & 127;
10638
+ if (!lenLen)
10639
+ throw new E("tlv.decode(long): indefinite length not supported");
10640
+ if (lenLen > 4)
10641
+ throw new E("tlv.decode(long): byte length is too big");
10642
+ const lengthBytes = data.subarray(pos, pos + lenLen);
10643
+ if (lengthBytes.length !== lenLen)
10644
+ throw new E("tlv.decode: length bytes not complete");
10645
+ if (lengthBytes[0] === 0)
10646
+ throw new E("tlv.decode(long): zero leftmost byte");
10647
+ for (const b of lengthBytes)
10648
+ length = length << 8 | b;
10649
+ pos += lenLen;
10650
+ if (length < 128)
10651
+ throw new E("tlv.decode(long): not minimal encoding");
10652
+ }
10653
+ const v = data.subarray(pos, pos + length);
10654
+ if (v.length !== length)
10655
+ throw new E("tlv.decode: wrong value length");
10656
+ return { v, l: data.subarray(pos + length) };
10657
+ }
10658
+ },
10659
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
10660
+ // since we always use positive integers here. It must always be empty:
10661
+ // - add zero byte if exists
10662
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
10663
+ _int: {
10664
+ encode(num) {
10665
+ const { Err: E } = DER;
10666
+ if (num < _0n4)
10667
+ throw new E("integer: negative integers are not allowed");
10668
+ let hex = numberToHexUnpadded(num);
10669
+ if (Number.parseInt(hex[0], 16) & 8)
10670
+ hex = "00" + hex;
10671
+ if (hex.length & 1)
10672
+ throw new E("unexpected DER parsing assertion: unpadded hex");
10673
+ return hex;
10674
+ },
10675
+ decode(data) {
10676
+ const { Err: E } = DER;
10677
+ if (data[0] & 128)
10678
+ throw new E("invalid signature integer: negative");
10679
+ if (data[0] === 0 && !(data[1] & 128))
10680
+ throw new E("invalid signature integer: unnecessary leading zero");
10681
+ return bytesToNumberBE(data);
10682
+ }
10683
+ },
10684
+ toSig(bytes) {
10685
+ const { Err: E, _int: int, _tlv: tlv } = DER;
10686
+ const data = abytes(bytes, void 0, "signature");
10687
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
10688
+ if (seqLeftBytes.length)
10689
+ throw new E("invalid signature: left bytes after parsing");
10690
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
10691
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
10692
+ if (sLeftBytes.length)
10693
+ throw new E("invalid signature: left bytes after parsing");
10694
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
10695
+ },
10696
+ hexFromSig(sig) {
10697
+ const { _tlv: tlv, _int: int } = DER;
10698
+ const rs = tlv.encode(2, int.encode(sig.r));
10699
+ const ss = tlv.encode(2, int.encode(sig.s));
10700
+ const seq = rs + ss;
10701
+ return tlv.encode(48, seq);
10702
+ }
10703
+ };
10704
+ var _0n4 = BigInt(0);
10705
+ var _1n4 = BigInt(1);
10706
+ var _2n2 = BigInt(2);
10707
+ var _3n2 = BigInt(3);
10708
+ var _4n2 = BigInt(4);
10709
+ function weierstrass(params, extraOpts = {}) {
10710
+ const validated = createCurveFields("weierstrass", params, extraOpts);
10711
+ const { Fp, Fn } = validated;
10712
+ let CURVE = validated.CURVE;
10713
+ const { h: cofactor, n: CURVE_ORDER2 } = CURVE;
10714
+ validateObject(extraOpts, {}, {
10715
+ allowInfinityPoint: "boolean",
10716
+ clearCofactor: "function",
10717
+ isTorsionFree: "function",
10718
+ fromBytes: "function",
10719
+ toBytes: "function",
10720
+ endo: "object"
10721
+ });
10722
+ const { endo } = extraOpts;
10723
+ if (endo) {
10724
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
10725
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
10726
+ }
10727
+ }
10728
+ const lengths = getWLengths(Fp, Fn);
10729
+ function assertCompressionIsSupported() {
10730
+ if (!Fp.isOdd)
10731
+ throw new Error("compression is not supported: Field does not have .isOdd()");
10732
+ }
10733
+ function pointToBytes(_c, point, isCompressed) {
10734
+ const { x, y } = point.toAffine();
10735
+ const bx = Fp.toBytes(x);
10736
+ abool(isCompressed, "isCompressed");
10737
+ if (isCompressed) {
10738
+ assertCompressionIsSupported();
10739
+ const hasEvenY = !Fp.isOdd(y);
10740
+ return concatBytes(pprefix(hasEvenY), bx);
10741
+ } else {
10742
+ return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
10743
+ }
10744
+ }
10745
+ function pointFromBytes(bytes) {
10746
+ abytes(bytes, void 0, "Point");
10747
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
10748
+ const length = bytes.length;
10749
+ const head = bytes[0];
10750
+ const tail = bytes.subarray(1);
10751
+ if (length === comp && (head === 2 || head === 3)) {
10752
+ const x = Fp.fromBytes(tail);
10753
+ if (!Fp.isValid(x))
10754
+ throw new Error("bad point: is not on curve, wrong x");
10755
+ const y2 = weierstrassEquation(x);
10756
+ let y;
10757
+ try {
10758
+ y = Fp.sqrt(y2);
10759
+ } catch (sqrtError) {
10760
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
10761
+ throw new Error("bad point: is not on curve, sqrt error" + err);
10762
+ }
10763
+ assertCompressionIsSupported();
10764
+ const evenY = Fp.isOdd(y);
10765
+ const evenH = (head & 1) === 1;
10766
+ if (evenH !== evenY)
10767
+ y = Fp.neg(y);
10768
+ return { x, y };
10769
+ } else if (length === uncomp && head === 4) {
10770
+ const L = Fp.BYTES;
10771
+ const x = Fp.fromBytes(tail.subarray(0, L));
10772
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
10773
+ if (!isValidXY(x, y))
10774
+ throw new Error("bad point: is not on curve");
10775
+ return { x, y };
10776
+ } else {
10777
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
10778
+ }
10779
+ }
10780
+ const encodePoint = extraOpts.toBytes || pointToBytes;
10781
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
10782
+ function weierstrassEquation(x) {
10783
+ const x2 = Fp.sqr(x);
10784
+ const x3 = Fp.mul(x2, x);
10785
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
10786
+ }
10787
+ function isValidXY(x, y) {
10788
+ const left = Fp.sqr(y);
10789
+ const right = weierstrassEquation(x);
10790
+ return Fp.eql(left, right);
10791
+ }
10792
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
10793
+ throw new Error("bad curve params: generator point");
10794
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
10795
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
10796
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
10797
+ throw new Error("bad curve params: a or b");
10798
+ function acoord(title, n, banZero = false) {
10799
+ if (!Fp.isValid(n) || banZero && Fp.is0(n))
10800
+ throw new Error(`bad point coordinate ${title}`);
10801
+ return n;
10802
+ }
10803
+ function aprjpoint(other) {
10804
+ if (!(other instanceof Point))
10805
+ throw new Error("Weierstrass Point expected");
10806
+ }
10807
+ function splitEndoScalarN(k) {
10808
+ if (!endo || !endo.basises)
10809
+ throw new Error("no endo");
10810
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
10811
+ }
10812
+ const toAffineMemo = memoized((p, iz) => {
10813
+ const { X, Y, Z } = p;
10814
+ if (Fp.eql(Z, Fp.ONE))
10815
+ return { x: X, y: Y };
10816
+ const is0 = p.is0();
10817
+ if (iz == null)
10818
+ iz = is0 ? Fp.ONE : Fp.inv(Z);
10819
+ const x = Fp.mul(X, iz);
10820
+ const y = Fp.mul(Y, iz);
10821
+ const zz = Fp.mul(Z, iz);
10822
+ if (is0)
10823
+ return { x: Fp.ZERO, y: Fp.ZERO };
10824
+ if (!Fp.eql(zz, Fp.ONE))
10825
+ throw new Error("invZ was invalid");
10826
+ return { x, y };
10827
+ });
10828
+ const assertValidMemo = memoized((p) => {
10829
+ if (p.is0()) {
10830
+ if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
10831
+ return;
10832
+ throw new Error("bad point: ZERO");
10833
+ }
10834
+ const { x, y } = p.toAffine();
10835
+ if (!Fp.isValid(x) || !Fp.isValid(y))
10836
+ throw new Error("bad point: x or y not field elements");
10837
+ if (!isValidXY(x, y))
10838
+ throw new Error("bad point: equation left != right");
10839
+ if (!p.isTorsionFree())
10840
+ throw new Error("bad point: not in prime-order subgroup");
10841
+ return true;
10842
+ });
10843
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
10844
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
10845
+ k1p = negateCt(k1neg, k1p);
10846
+ k2p = negateCt(k2neg, k2p);
10847
+ return k1p.add(k2p);
10848
+ }
10849
+ class Point {
10850
+ // base / generator point
10851
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
10852
+ // zero / infinity / identity point
10853
+ static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
10854
+ // 0, 1, 0
10855
+ // math field
10856
+ static Fp = Fp;
10857
+ // scalar field
10858
+ static Fn = Fn;
10859
+ X;
10860
+ Y;
10861
+ Z;
10862
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
10863
+ constructor(X, Y, Z) {
10864
+ this.X = acoord("x", X);
10865
+ this.Y = acoord("y", Y, true);
10866
+ this.Z = acoord("z", Z);
10867
+ Object.freeze(this);
10868
+ }
10869
+ static CURVE() {
10870
+ return CURVE;
10871
+ }
10872
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
10873
+ static fromAffine(p) {
10874
+ const { x, y } = p || {};
10875
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
10876
+ throw new Error("invalid affine point");
10877
+ if (p instanceof Point)
10878
+ throw new Error("projective point not allowed");
10879
+ if (Fp.is0(x) && Fp.is0(y))
10880
+ return Point.ZERO;
10881
+ return new Point(x, y, Fp.ONE);
10882
+ }
10883
+ static fromBytes(bytes) {
10884
+ const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
10885
+ P.assertValidity();
10886
+ return P;
10887
+ }
10888
+ static fromHex(hex) {
10889
+ return Point.fromBytes(hexToBytes2(hex));
10890
+ }
10891
+ get x() {
10892
+ return this.toAffine().x;
10893
+ }
10894
+ get y() {
10895
+ return this.toAffine().y;
10896
+ }
10897
+ /**
10898
+ *
10899
+ * @param windowSize
10900
+ * @param isLazy true will defer table computation until the first multiplication
10901
+ * @returns
10902
+ */
10903
+ precompute(windowSize = 8, isLazy = true) {
10904
+ wnaf.createCache(this, windowSize);
10905
+ if (!isLazy)
10906
+ this.multiply(_3n2);
10907
+ return this;
10908
+ }
10909
+ // TODO: return `this`
10910
+ /** A point on curve is valid if it conforms to equation. */
10911
+ assertValidity() {
10912
+ assertValidMemo(this);
10913
+ }
10914
+ hasEvenY() {
10915
+ const { y } = this.toAffine();
10916
+ if (!Fp.isOdd)
10917
+ throw new Error("Field doesn't support isOdd");
10918
+ return !Fp.isOdd(y);
10919
+ }
10920
+ /** Compare one point to another. */
10921
+ equals(other) {
10922
+ aprjpoint(other);
10923
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10924
+ const { X: X2, Y: Y2, Z: Z2 } = other;
10925
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
10926
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
10927
+ return U1 && U2;
10928
+ }
10929
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
10930
+ negate() {
10931
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
10932
+ }
10933
+ // Renes-Costello-Batina exception-free doubling formula.
10934
+ // There is 30% faster Jacobian formula, but it is not complete.
10935
+ // https://eprint.iacr.org/2015/1060, algorithm 3
10936
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
10937
+ double() {
10938
+ const { a, b } = CURVE;
10939
+ const b3 = Fp.mul(b, _3n2);
10940
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10941
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
10942
+ let t0 = Fp.mul(X1, X1);
10943
+ let t1 = Fp.mul(Y1, Y1);
10944
+ let t2 = Fp.mul(Z1, Z1);
10945
+ let t3 = Fp.mul(X1, Y1);
10946
+ t3 = Fp.add(t3, t3);
10947
+ Z3 = Fp.mul(X1, Z1);
10948
+ Z3 = Fp.add(Z3, Z3);
10949
+ X3 = Fp.mul(a, Z3);
10950
+ Y3 = Fp.mul(b3, t2);
10951
+ Y3 = Fp.add(X3, Y3);
10952
+ X3 = Fp.sub(t1, Y3);
10953
+ Y3 = Fp.add(t1, Y3);
10954
+ Y3 = Fp.mul(X3, Y3);
10955
+ X3 = Fp.mul(t3, X3);
10956
+ Z3 = Fp.mul(b3, Z3);
10957
+ t2 = Fp.mul(a, t2);
10958
+ t3 = Fp.sub(t0, t2);
10959
+ t3 = Fp.mul(a, t3);
10960
+ t3 = Fp.add(t3, Z3);
10961
+ Z3 = Fp.add(t0, t0);
10962
+ t0 = Fp.add(Z3, t0);
10963
+ t0 = Fp.add(t0, t2);
10964
+ t0 = Fp.mul(t0, t3);
10965
+ Y3 = Fp.add(Y3, t0);
10966
+ t2 = Fp.mul(Y1, Z1);
10967
+ t2 = Fp.add(t2, t2);
10968
+ t0 = Fp.mul(t2, t3);
10969
+ X3 = Fp.sub(X3, t0);
10970
+ Z3 = Fp.mul(t2, t1);
10971
+ Z3 = Fp.add(Z3, Z3);
10972
+ Z3 = Fp.add(Z3, Z3);
10973
+ return new Point(X3, Y3, Z3);
10974
+ }
10975
+ // Renes-Costello-Batina exception-free addition formula.
10976
+ // There is 30% faster Jacobian formula, but it is not complete.
10977
+ // https://eprint.iacr.org/2015/1060, algorithm 1
10978
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
10979
+ add(other) {
10980
+ aprjpoint(other);
10981
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10982
+ const { X: X2, Y: Y2, Z: Z2 } = other;
10983
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
10984
+ const a = CURVE.a;
10985
+ const b3 = Fp.mul(CURVE.b, _3n2);
10986
+ let t0 = Fp.mul(X1, X2);
10987
+ let t1 = Fp.mul(Y1, Y2);
10988
+ let t2 = Fp.mul(Z1, Z2);
10989
+ let t3 = Fp.add(X1, Y1);
10990
+ let t4 = Fp.add(X2, Y2);
10991
+ t3 = Fp.mul(t3, t4);
10992
+ t4 = Fp.add(t0, t1);
10993
+ t3 = Fp.sub(t3, t4);
10994
+ t4 = Fp.add(X1, Z1);
10995
+ let t5 = Fp.add(X2, Z2);
10996
+ t4 = Fp.mul(t4, t5);
10997
+ t5 = Fp.add(t0, t2);
10998
+ t4 = Fp.sub(t4, t5);
10999
+ t5 = Fp.add(Y1, Z1);
11000
+ X3 = Fp.add(Y2, Z2);
11001
+ t5 = Fp.mul(t5, X3);
11002
+ X3 = Fp.add(t1, t2);
11003
+ t5 = Fp.sub(t5, X3);
11004
+ Z3 = Fp.mul(a, t4);
11005
+ X3 = Fp.mul(b3, t2);
11006
+ Z3 = Fp.add(X3, Z3);
11007
+ X3 = Fp.sub(t1, Z3);
11008
+ Z3 = Fp.add(t1, Z3);
11009
+ Y3 = Fp.mul(X3, Z3);
11010
+ t1 = Fp.add(t0, t0);
11011
+ t1 = Fp.add(t1, t0);
11012
+ t2 = Fp.mul(a, t2);
11013
+ t4 = Fp.mul(b3, t4);
11014
+ t1 = Fp.add(t1, t2);
11015
+ t2 = Fp.sub(t0, t2);
11016
+ t2 = Fp.mul(a, t2);
11017
+ t4 = Fp.add(t4, t2);
11018
+ t0 = Fp.mul(t1, t4);
11019
+ Y3 = Fp.add(Y3, t0);
11020
+ t0 = Fp.mul(t5, t4);
11021
+ X3 = Fp.mul(t3, X3);
11022
+ X3 = Fp.sub(X3, t0);
11023
+ t0 = Fp.mul(t3, t1);
11024
+ Z3 = Fp.mul(t5, Z3);
11025
+ Z3 = Fp.add(Z3, t0);
11026
+ return new Point(X3, Y3, Z3);
11027
+ }
11028
+ subtract(other) {
11029
+ return this.add(other.negate());
11030
+ }
11031
+ is0() {
11032
+ return this.equals(Point.ZERO);
11033
+ }
11034
+ /**
11035
+ * Constant time multiplication.
11036
+ * Uses wNAF method. Windowed method may be 10% faster,
11037
+ * but takes 2x longer to generate and consumes 2x memory.
11038
+ * Uses precomputes when available.
11039
+ * Uses endomorphism for Koblitz curves.
11040
+ * @param scalar by which the point would be multiplied
11041
+ * @returns New point
11042
+ */
11043
+ multiply(scalar) {
11044
+ const { endo: endo2 } = extraOpts;
11045
+ if (!Fn.isValidNot0(scalar))
11046
+ throw new Error("invalid scalar: out of range");
11047
+ let point, fake;
11048
+ const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
11049
+ if (endo2) {
11050
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
11051
+ const { p: k1p, f: k1f } = mul(k1);
11052
+ const { p: k2p, f: k2f } = mul(k2);
11053
+ fake = k1f.add(k2f);
11054
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
11055
+ } else {
11056
+ const { p, f } = mul(scalar);
11057
+ point = p;
11058
+ fake = f;
11059
+ }
11060
+ return normalizeZ(Point, [point, fake])[0];
11061
+ }
11062
+ /**
11063
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
11064
+ * It's faster, but should only be used when you don't care about
11065
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
11066
+ */
11067
+ multiplyUnsafe(sc) {
11068
+ const { endo: endo2 } = extraOpts;
11069
+ const p = this;
11070
+ if (!Fn.isValid(sc))
11071
+ throw new Error("invalid scalar: out of range");
11072
+ if (sc === _0n4 || p.is0())
11073
+ return Point.ZERO;
11074
+ if (sc === _1n4)
11075
+ return p;
11076
+ if (wnaf.hasCache(this))
11077
+ return this.multiply(sc);
11078
+ if (endo2) {
11079
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
11080
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
11081
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
11082
+ } else {
11083
+ return wnaf.unsafe(p, sc);
11084
+ }
11085
+ }
11086
+ /**
11087
+ * Converts Projective point to affine (x, y) coordinates.
11088
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
11089
+ */
11090
+ toAffine(invertedZ) {
11091
+ return toAffineMemo(this, invertedZ);
11092
+ }
11093
+ /**
11094
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
11095
+ * Always torsion-free for cofactor=1 curves.
11096
+ */
11097
+ isTorsionFree() {
11098
+ const { isTorsionFree } = extraOpts;
11099
+ if (cofactor === _1n4)
11100
+ return true;
11101
+ if (isTorsionFree)
11102
+ return isTorsionFree(Point, this);
11103
+ return wnaf.unsafe(this, CURVE_ORDER2).is0();
11104
+ }
11105
+ clearCofactor() {
11106
+ const { clearCofactor } = extraOpts;
11107
+ if (cofactor === _1n4)
11108
+ return this;
11109
+ if (clearCofactor)
11110
+ return clearCofactor(Point, this);
11111
+ return this.multiplyUnsafe(cofactor);
11112
+ }
11113
+ isSmallOrder() {
11114
+ return this.multiplyUnsafe(cofactor).is0();
11115
+ }
11116
+ toBytes(isCompressed = true) {
11117
+ abool(isCompressed, "isCompressed");
11118
+ this.assertValidity();
11119
+ return encodePoint(Point, this, isCompressed);
11120
+ }
11121
+ toHex(isCompressed = true) {
11122
+ return bytesToHex4(this.toBytes(isCompressed));
11123
+ }
11124
+ toString() {
11125
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
11126
+ }
11127
+ }
11128
+ const bits = Fn.BITS;
11129
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
11130
+ Point.BASE.precompute(8);
11131
+ return Point;
11132
+ }
11133
+ function pprefix(hasEvenY) {
11134
+ return Uint8Array.of(hasEvenY ? 2 : 3);
11135
+ }
11136
+ function getWLengths(Fp, Fn) {
11137
+ return {
11138
+ secretKey: Fn.BYTES,
11139
+ publicKey: 1 + Fp.BYTES,
11140
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
11141
+ publicKeyHasPrefix: true,
11142
+ signature: 2 * Fn.BYTES
11143
+ };
11144
+ }
11145
+ function ecdh(Point, ecdhOpts = {}) {
11146
+ const { Fn } = Point;
11147
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
11148
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
11149
+ function isValidSecretKey(secretKey) {
11150
+ try {
11151
+ const num = Fn.fromBytes(secretKey);
11152
+ return Fn.isValidNot0(num);
11153
+ } catch (error) {
11154
+ return false;
11155
+ }
11156
+ }
11157
+ function isValidPublicKey(publicKey, isCompressed) {
11158
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
11159
+ try {
11160
+ const l = publicKey.length;
11161
+ if (isCompressed === true && l !== comp)
11162
+ return false;
11163
+ if (isCompressed === false && l !== publicKeyUncompressed)
11164
+ return false;
11165
+ return !!Point.fromBytes(publicKey);
11166
+ } catch (error) {
11167
+ return false;
11168
+ }
11169
+ }
11170
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
11171
+ return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
11172
+ }
11173
+ function getPublicKey2(secretKey, isCompressed = true) {
11174
+ return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
11175
+ }
11176
+ function isProbPub(item) {
11177
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
11178
+ if (!isBytes(item))
11179
+ return void 0;
11180
+ if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
11181
+ return void 0;
11182
+ const l = abytes(item, void 0, "key").length;
11183
+ return l === publicKey || l === publicKeyUncompressed;
11184
+ }
11185
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
11186
+ if (isProbPub(secretKeyA) === true)
11187
+ throw new Error("first arg must be private key");
11188
+ if (isProbPub(publicKeyB) === false)
11189
+ throw new Error("second arg must be public key");
11190
+ const s = Fn.fromBytes(secretKeyA);
11191
+ const b = Point.fromBytes(publicKeyB);
11192
+ return b.multiply(s).toBytes(isCompressed);
11193
+ }
11194
+ const utils = {
11195
+ isValidSecretKey,
11196
+ isValidPublicKey,
11197
+ randomSecretKey
11198
+ };
11199
+ const keygen = createKeygen(randomSecretKey, getPublicKey2);
11200
+ return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
11201
+ }
11202
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
11203
+ ahash(hash);
11204
+ validateObject(ecdsaOpts, {}, {
11205
+ hmac: "function",
11206
+ lowS: "boolean",
11207
+ randomBytes: "function",
11208
+ bits2int: "function",
11209
+ bits2int_modN: "function"
11210
+ });
11211
+ ecdsaOpts = Object.assign({}, ecdsaOpts);
11212
+ const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
11213
+ const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
11214
+ const { Fp, Fn } = Point;
11215
+ const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn;
11216
+ const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
11217
+ const defaultSigOpts = {
11218
+ prehash: true,
11219
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
11220
+ format: "compact",
11221
+ extraEntropy: false
11222
+ };
11223
+ const hasLargeCofactor = CURVE_ORDER2 * _2n2 < Fp.ORDER;
11224
+ function isBiggerThanHalfOrder(number) {
11225
+ const HALF = CURVE_ORDER2 >> _1n4;
11226
+ return number > HALF;
11227
+ }
11228
+ function validateRS(title, num) {
11229
+ if (!Fn.isValidNot0(num))
11230
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
11231
+ return num;
11232
+ }
11233
+ function assertSmallCofactor() {
11234
+ if (hasLargeCofactor)
11235
+ throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
11236
+ }
11237
+ function validateSigLength(bytes, format) {
11238
+ validateSigFormat(format);
11239
+ const size = lengths.signature;
11240
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
11241
+ return abytes(bytes, sizer);
11242
+ }
11243
+ class Signature {
11244
+ r;
11245
+ s;
11246
+ recovery;
11247
+ constructor(r, s, recovery) {
11248
+ this.r = validateRS("r", r);
11249
+ this.s = validateRS("s", s);
11250
+ if (recovery != null) {
11251
+ assertSmallCofactor();
11252
+ if (![0, 1, 2, 3].includes(recovery))
11253
+ throw new Error("invalid recovery id");
11254
+ this.recovery = recovery;
11255
+ }
11256
+ Object.freeze(this);
11257
+ }
11258
+ static fromBytes(bytes, format = defaultSigOpts.format) {
11259
+ validateSigLength(bytes, format);
11260
+ let recid;
11261
+ if (format === "der") {
11262
+ const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
11263
+ return new Signature(r2, s2);
11264
+ }
11265
+ if (format === "recovered") {
11266
+ recid = bytes[0];
11267
+ format = "compact";
11268
+ bytes = bytes.subarray(1);
11269
+ }
11270
+ const L = lengths.signature / 2;
11271
+ const r = bytes.subarray(0, L);
11272
+ const s = bytes.subarray(L, L * 2);
11273
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
11274
+ }
11275
+ static fromHex(hex, format) {
11276
+ return this.fromBytes(hexToBytes2(hex), format);
11277
+ }
11278
+ assertRecovery() {
11279
+ const { recovery } = this;
11280
+ if (recovery == null)
11281
+ throw new Error("invalid recovery id: must be present");
11282
+ return recovery;
11283
+ }
11284
+ addRecoveryBit(recovery) {
11285
+ return new Signature(this.r, this.s, recovery);
11286
+ }
11287
+ recoverPublicKey(messageHash) {
11288
+ const { r, s } = this;
11289
+ const recovery = this.assertRecovery();
11290
+ const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER2 : r;
11291
+ if (!Fp.isValid(radj))
11292
+ throw new Error("invalid recovery id: sig.r+curve.n != R.x");
11293
+ const x = Fp.toBytes(radj);
11294
+ const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
11295
+ const ir = Fn.inv(radj);
11296
+ const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
11297
+ const u1 = Fn.create(-h * ir);
11298
+ const u2 = Fn.create(s * ir);
11299
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
11300
+ if (Q.is0())
11301
+ throw new Error("invalid recovery: point at infinify");
11302
+ Q.assertValidity();
11303
+ return Q;
11304
+ }
11305
+ // Signatures should be low-s, to prevent malleability.
11306
+ hasHighS() {
11307
+ return isBiggerThanHalfOrder(this.s);
11308
+ }
11309
+ toBytes(format = defaultSigOpts.format) {
11310
+ validateSigFormat(format);
11311
+ if (format === "der")
11312
+ return hexToBytes2(DER.hexFromSig(this));
11313
+ const { r, s } = this;
11314
+ const rb = Fn.toBytes(r);
11315
+ const sb = Fn.toBytes(s);
11316
+ if (format === "recovered") {
11317
+ assertSmallCofactor();
11318
+ return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
11319
+ }
11320
+ return concatBytes(rb, sb);
11321
+ }
11322
+ toHex(format) {
11323
+ return bytesToHex4(this.toBytes(format));
11324
+ }
11325
+ }
11326
+ const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
11327
+ if (bytes.length > 8192)
11328
+ throw new Error("input is too large");
11329
+ const num = bytesToNumberBE(bytes);
11330
+ const delta = bytes.length * 8 - fnBits;
11331
+ return delta > 0 ? num >> BigInt(delta) : num;
11332
+ };
11333
+ const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
11334
+ return Fn.create(bits2int(bytes));
11335
+ };
11336
+ const ORDER_MASK = bitMask(fnBits);
11337
+ function int2octets(num) {
11338
+ aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
11339
+ return Fn.toBytes(num);
11340
+ }
11341
+ function validateMsgAndHash(message, prehash) {
11342
+ abytes(message, void 0, "message");
11343
+ return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
11344
+ }
11345
+ function prepSig(message, secretKey, opts) {
11346
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
11347
+ message = validateMsgAndHash(message, prehash);
11348
+ const h1int = bits2int_modN(message);
11349
+ const d = Fn.fromBytes(secretKey);
11350
+ if (!Fn.isValidNot0(d))
11351
+ throw new Error("invalid private key");
11352
+ const seedArgs = [int2octets(d), int2octets(h1int)];
11353
+ if (extraEntropy != null && extraEntropy !== false) {
11354
+ const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
11355
+ seedArgs.push(abytes(e, void 0, "extraEntropy"));
11356
+ }
11357
+ const seed = concatBytes(...seedArgs);
11358
+ const m = h1int;
11359
+ function k2sig(kBytes) {
11360
+ const k = bits2int(kBytes);
11361
+ if (!Fn.isValidNot0(k))
11362
+ return;
11363
+ const ik = Fn.inv(k);
11364
+ const q = Point.BASE.multiply(k).toAffine();
11365
+ const r = Fn.create(q.x);
11366
+ if (r === _0n4)
11367
+ return;
11368
+ const s = Fn.create(ik * Fn.create(m + r * d));
11369
+ if (s === _0n4)
11370
+ return;
11371
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
11372
+ let normS = s;
11373
+ if (lowS && isBiggerThanHalfOrder(s)) {
11374
+ normS = Fn.neg(s);
11375
+ recovery ^= 1;
11376
+ }
11377
+ return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
11378
+ }
11379
+ return { seed, k2sig };
11380
+ }
11381
+ function sign(message, secretKey, opts = {}) {
11382
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
11383
+ const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
11384
+ const sig = drbg(seed, k2sig);
11385
+ return sig.toBytes(opts.format);
11386
+ }
11387
+ function verify(signature, message, publicKey, opts = {}) {
11388
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
11389
+ publicKey = abytes(publicKey, void 0, "publicKey");
11390
+ message = validateMsgAndHash(message, prehash);
11391
+ if (!isBytes(signature)) {
11392
+ const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
11393
+ throw new Error("verify expects Uint8Array signature" + end);
11394
+ }
11395
+ validateSigLength(signature, format);
11396
+ try {
11397
+ const sig = Signature.fromBytes(signature, format);
11398
+ const P = Point.fromBytes(publicKey);
11399
+ if (lowS && sig.hasHighS())
11400
+ return false;
11401
+ const { r, s } = sig;
11402
+ const h = bits2int_modN(message);
11403
+ const is = Fn.inv(s);
11404
+ const u1 = Fn.create(h * is);
11405
+ const u2 = Fn.create(r * is);
11406
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
11407
+ if (R.is0())
11408
+ return false;
11409
+ const v = Fn.create(R.x);
11410
+ return v === r;
11411
+ } catch (e) {
11412
+ return false;
11413
+ }
11414
+ }
11415
+ function recoverPublicKey(signature, message, opts = {}) {
11416
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
11417
+ message = validateMsgAndHash(message, prehash);
11418
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
11419
+ }
11420
+ return Object.freeze({
11421
+ keygen,
11422
+ getPublicKey: getPublicKey2,
11423
+ getSharedSecret,
11424
+ utils,
11425
+ lengths,
11426
+ Point,
11427
+ sign,
11428
+ verify,
11429
+ recoverPublicKey,
11430
+ Signature,
11431
+ hash
11432
+ });
11433
+ }
11434
+
11435
+ // node_modules/@noble/curves/secp256k1.js
11436
+ var secp256k1_CURVE = {
11437
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
11438
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
11439
+ h: BigInt(1),
11440
+ a: BigInt(0),
11441
+ b: BigInt(7),
11442
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
11443
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
11444
+ };
11445
+ var secp256k1_ENDO = {
11446
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
11447
+ basises: [
11448
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
11449
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
11450
+ ]
11451
+ };
11452
+ var _2n3 = /* @__PURE__ */ BigInt(2);
11453
+ function sqrtMod(y) {
11454
+ const P = secp256k1_CURVE.p;
11455
+ const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
11456
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
11457
+ const b2 = y * y * y % P;
11458
+ const b3 = b2 * b2 * y % P;
11459
+ const b6 = pow2(b3, _3n3, P) * b3 % P;
11460
+ const b9 = pow2(b6, _3n3, P) * b3 % P;
11461
+ const b11 = pow2(b9, _2n3, P) * b2 % P;
11462
+ const b22 = pow2(b11, _11n, P) * b11 % P;
11463
+ const b44 = pow2(b22, _22n, P) * b22 % P;
11464
+ const b88 = pow2(b44, _44n, P) * b44 % P;
11465
+ const b176 = pow2(b88, _88n, P) * b88 % P;
11466
+ const b220 = pow2(b176, _44n, P) * b44 % P;
11467
+ const b223 = pow2(b220, _3n3, P) * b3 % P;
11468
+ const t1 = pow2(b223, _23n, P) * b22 % P;
11469
+ const t2 = pow2(t1, _6n, P) * b2 % P;
11470
+ const root = pow2(t2, _2n3, P);
11471
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
11472
+ throw new Error("Cannot find square root");
11473
+ return root;
11474
+ }
11475
+ var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
11476
+ var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
11477
+ Fp: Fpk1,
11478
+ endo: secp256k1_ENDO
11479
+ });
11480
+ var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha2564);
11481
+
11482
+ // modules/market/MarketModule.ts
11483
+ function hexToBytes3(hex) {
11484
+ const len = hex.length >> 1;
11485
+ const bytes = new Uint8Array(len);
11486
+ for (let i = 0; i < len; i++) {
11487
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
11488
+ }
11489
+ return bytes;
11490
+ }
11491
+ function signRequest(body, privateKeyHex) {
11492
+ const timestamp = Date.now();
11493
+ const payload = JSON.stringify({ body, timestamp });
11494
+ const messageHash = sha2564(new TextEncoder().encode(payload));
11495
+ const privateKeyBytes = hexToBytes3(privateKeyHex);
11496
+ const signature = secp256k1.sign(messageHash, privateKeyBytes);
11497
+ const publicKey = bytesToHex4(secp256k1.getPublicKey(privateKeyBytes, true));
11498
+ return {
11499
+ body: JSON.stringify(body),
11500
+ headers: {
11501
+ "x-signature": bytesToHex4(signature),
11502
+ "x-public-key": publicKey,
11503
+ "x-timestamp": String(timestamp),
11504
+ "content-type": "application/json"
11505
+ }
11506
+ };
11507
+ }
11508
+ function toSnakeCaseIntent(req) {
11509
+ const result = {
11510
+ description: req.description,
11511
+ intent_type: req.intentType
11512
+ };
11513
+ if (req.category !== void 0) result.category = req.category;
11514
+ if (req.price !== void 0) result.price = req.price;
11515
+ if (req.currency !== void 0) result.currency = req.currency;
11516
+ if (req.location !== void 0) result.location = req.location;
11517
+ if (req.contactHandle !== void 0) result.contact_handle = req.contactHandle;
11518
+ if (req.expiresInDays !== void 0) result.expires_in_days = req.expiresInDays;
11519
+ return result;
11520
+ }
11521
+ function toSnakeCaseFilters(opts) {
11522
+ const result = {};
11523
+ if (opts?.filters) {
11524
+ const f = opts.filters;
11525
+ if (f.intentType !== void 0) result.intent_type = f.intentType;
11526
+ if (f.category !== void 0) result.category = f.category;
11527
+ if (f.minPrice !== void 0) result.min_price = f.minPrice;
11528
+ if (f.maxPrice !== void 0) result.max_price = f.maxPrice;
11529
+ if (f.location !== void 0) result.location = f.location;
11530
+ }
11531
+ if (opts?.limit !== void 0) result.limit = opts.limit;
11532
+ return result;
11533
+ }
11534
+ function mapSearchResult(raw) {
11535
+ return {
11536
+ id: raw.id,
11537
+ score: raw.score,
11538
+ agentNametag: raw.agent_nametag ?? void 0,
11539
+ agentPublicKey: raw.agent_public_key,
11540
+ description: raw.description,
11541
+ intentType: raw.intent_type,
11542
+ category: raw.category ?? void 0,
11543
+ price: raw.price ?? void 0,
11544
+ currency: raw.currency,
11545
+ location: raw.location ?? void 0,
11546
+ contactMethod: raw.contact_method,
11547
+ contactHandle: raw.contact_handle ?? void 0,
11548
+ createdAt: raw.created_at,
11549
+ expiresAt: raw.expires_at
11550
+ };
11551
+ }
11552
+ function mapMyIntent(raw) {
11553
+ return {
11554
+ id: raw.id,
11555
+ intentType: raw.intent_type,
11556
+ category: raw.category ?? void 0,
11557
+ price: raw.price ?? void 0,
11558
+ currency: raw.currency,
11559
+ location: raw.location ?? void 0,
11560
+ status: raw.status,
11561
+ createdAt: raw.created_at,
11562
+ expiresAt: raw.expires_at
11563
+ };
11564
+ }
11565
+ function mapFeedListing(raw) {
11566
+ return {
11567
+ id: raw.id,
11568
+ title: raw.title,
11569
+ descriptionPreview: raw.description_preview,
11570
+ agentName: raw.agent_name,
11571
+ agentId: raw.agent_id,
11572
+ type: raw.type,
11573
+ createdAt: raw.created_at
11574
+ };
11575
+ }
11576
+ function mapFeedMessage(raw) {
11577
+ if (raw.type === "initial") {
11578
+ return { type: "initial", listings: (raw.listings ?? []).map(mapFeedListing) };
11579
+ }
11580
+ return { type: "new", listing: mapFeedListing(raw.listing) };
11581
+ }
11582
+ var MarketModule = class {
11583
+ apiUrl;
11584
+ timeout;
11585
+ identity = null;
11586
+ registered = false;
11587
+ constructor(config) {
11588
+ this.apiUrl = (config?.apiUrl ?? DEFAULT_MARKET_API_URL).replace(/\/+$/, "");
11589
+ this.timeout = config?.timeout ?? 3e4;
11590
+ }
11591
+ /** Called by Sphere after construction */
11592
+ initialize(deps) {
11593
+ this.identity = deps.identity;
11594
+ }
11595
+ /** No-op — stateless module */
11596
+ async load() {
11597
+ }
11598
+ /** No-op — stateless module */
11599
+ destroy() {
11600
+ }
11601
+ // ---------------------------------------------------------------------------
11602
+ // Public API
11603
+ // ---------------------------------------------------------------------------
11604
+ /** Post a new intent (agent is auto-registered on first post) */
11605
+ async postIntent(intent) {
11606
+ const body = toSnakeCaseIntent(intent);
11607
+ const data = await this.apiPost("/api/intents", body);
11608
+ return {
11609
+ intentId: data.intent_id ?? data.intentId,
11610
+ message: data.message,
11611
+ expiresAt: data.expires_at ?? data.expiresAt
11612
+ };
11613
+ }
11614
+ /** Semantic search for intents (public — no auth required) */
11615
+ async search(query, opts) {
11616
+ const body = {
11617
+ query,
11618
+ ...toSnakeCaseFilters(opts)
11619
+ };
11620
+ const data = await this.apiPublicPost("/api/search", body);
11621
+ let results = (data.intents ?? []).map(mapSearchResult);
11622
+ const minScore = opts?.filters?.minScore;
11623
+ if (minScore != null) {
11624
+ results = results.filter((r) => Math.round(r.score * 100) >= Math.round(minScore * 100));
11625
+ }
11626
+ return { intents: results, count: results.length };
11627
+ }
11628
+ /** List own intents (authenticated) */
11629
+ async getMyIntents() {
11630
+ const data = await this.apiGet("/api/intents");
11631
+ return (data.intents ?? []).map(mapMyIntent);
11632
+ }
11633
+ /** Close (delete) an intent */
11634
+ async closeIntent(intentId) {
11635
+ await this.apiDelete(`/api/intents/${encodeURIComponent(intentId)}`);
11636
+ }
11637
+ /** Fetch the most recent listings via REST (public — no auth required) */
11638
+ async getRecentListings() {
11639
+ const res = await fetch(`${this.apiUrl}/api/feed/recent`, {
11640
+ signal: AbortSignal.timeout(this.timeout)
11641
+ });
11642
+ const data = await this.parseResponse(res);
11643
+ return (data.listings ?? []).map(mapFeedListing);
11644
+ }
11645
+ /**
11646
+ * Subscribe to the live listing feed via WebSocket.
11647
+ * Returns an unsubscribe function that closes the connection.
11648
+ *
11649
+ * Requires a WebSocket implementation — works natively in browsers
11650
+ * and in Node.js 21+ (or with the `ws` package).
11651
+ */
11652
+ subscribeFeed(listener) {
11653
+ const wsUrl = this.apiUrl.replace(/^http/, "ws") + "/ws/feed";
11654
+ const ws2 = new WebSocket(wsUrl);
11655
+ ws2.onmessage = (event) => {
11656
+ try {
11657
+ const raw = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
11658
+ listener(mapFeedMessage(raw));
11659
+ } catch {
11660
+ }
11661
+ };
11662
+ return () => {
11663
+ ws2.close();
11664
+ };
11665
+ }
11666
+ // ---------------------------------------------------------------------------
11667
+ // Private: HTTP helpers
11668
+ // ---------------------------------------------------------------------------
11669
+ ensureIdentity() {
11670
+ if (!this.identity) {
11671
+ throw new Error("MarketModule not initialized \u2014 call initialize() first");
11672
+ }
11673
+ }
11674
+ /** Register the agent's public key with the server (idempotent) */
11675
+ async ensureRegistered() {
11676
+ if (this.registered) return;
11677
+ this.ensureIdentity();
11678
+ const publicKey = bytesToHex4(secp256k1.getPublicKey(hexToBytes3(this.identity.privateKey), true));
11679
+ const body = { public_key: publicKey };
11680
+ if (this.identity.nametag) body.nametag = this.identity.nametag;
11681
+ const res = await fetch(`${this.apiUrl}/api/agent/register`, {
11682
+ method: "POST",
11683
+ headers: { "content-type": "application/json" },
11684
+ body: JSON.stringify(body),
11685
+ signal: AbortSignal.timeout(this.timeout)
11686
+ });
11687
+ if (res.ok || res.status === 409) {
11688
+ this.registered = true;
11689
+ return;
11690
+ }
11691
+ const text = await res.text();
11692
+ let data;
11693
+ try {
11694
+ data = JSON.parse(text);
11695
+ } catch {
11696
+ }
11697
+ throw new Error(data?.error ?? `Agent registration failed: HTTP ${res.status}`);
11698
+ }
11699
+ async parseResponse(res) {
11700
+ const text = await res.text();
11701
+ let data;
11702
+ try {
11703
+ data = JSON.parse(text);
11704
+ } catch {
11705
+ throw new Error(`Market API error: HTTP ${res.status} \u2014 unexpected response (not JSON)`);
11706
+ }
11707
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
11708
+ return data;
11709
+ }
11710
+ async apiPost(path, body) {
11711
+ this.ensureIdentity();
11712
+ await this.ensureRegistered();
11713
+ const signed = signRequest(body, this.identity.privateKey);
11714
+ const res = await fetch(`${this.apiUrl}${path}`, {
11715
+ method: "POST",
11716
+ headers: signed.headers,
11717
+ body: signed.body,
11718
+ signal: AbortSignal.timeout(this.timeout)
11719
+ });
11720
+ return this.parseResponse(res);
11721
+ }
11722
+ async apiGet(path) {
11723
+ this.ensureIdentity();
11724
+ await this.ensureRegistered();
11725
+ const signed = signRequest({}, this.identity.privateKey);
11726
+ const res = await fetch(`${this.apiUrl}${path}`, {
11727
+ method: "GET",
11728
+ headers: signed.headers,
11729
+ signal: AbortSignal.timeout(this.timeout)
11730
+ });
11731
+ return this.parseResponse(res);
11732
+ }
11733
+ async apiDelete(path) {
11734
+ this.ensureIdentity();
11735
+ await this.ensureRegistered();
11736
+ const signed = signRequest({}, this.identity.privateKey);
11737
+ const res = await fetch(`${this.apiUrl}${path}`, {
11738
+ method: "DELETE",
11739
+ headers: signed.headers,
11740
+ signal: AbortSignal.timeout(this.timeout)
11741
+ });
11742
+ return this.parseResponse(res);
11743
+ }
11744
+ async apiPublicPost(path, body) {
11745
+ const res = await fetch(`${this.apiUrl}${path}`, {
11746
+ method: "POST",
11747
+ headers: { "content-type": "application/json" },
11748
+ body: JSON.stringify(body),
11749
+ signal: AbortSignal.timeout(this.timeout)
11750
+ });
11751
+ return this.parseResponse(res);
11752
+ }
11753
+ };
11754
+ function createMarketModule(config) {
11755
+ return new MarketModule(config);
11756
+ }
11757
+
9262
11758
  // core/encryption.ts
9263
11759
  var import_crypto_js6 = __toESM(require("crypto-js"), 1);
9264
11760
  function encryptSimple(plaintext, password) {
@@ -9477,7 +11973,9 @@ function decryptTextFormatKey(encryptedKey, password) {
9477
11973
  const key = deriveLegacyKey(password);
9478
11974
  const decrypted = import_crypto_js7.default.AES.decrypt(encryptedKey, key);
9479
11975
  const result = decrypted.toString(import_crypto_js7.default.enc.Utf8);
9480
- return result || null;
11976
+ if (!result) return null;
11977
+ if (!/^[0-9a-fA-F]+$/.test(result)) return null;
11978
+ return result;
9481
11979
  } catch {
9482
11980
  return null;
9483
11981
  }
@@ -10092,6 +12590,7 @@ var Sphere = class _Sphere {
10092
12590
  _payments;
10093
12591
  _communications;
10094
12592
  _groupChat = null;
12593
+ _market = null;
10095
12594
  // Events
10096
12595
  eventHandlers = /* @__PURE__ */ new Map();
10097
12596
  // Provider management
@@ -10101,7 +12600,7 @@ var Sphere = class _Sphere {
10101
12600
  // ===========================================================================
10102
12601
  // Constructor (private)
10103
12602
  // ===========================================================================
10104
- constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig) {
12603
+ constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig, marketConfig) {
10105
12604
  this._storage = storage;
10106
12605
  this._transport = transport;
10107
12606
  this._oracle = oracle;
@@ -10112,6 +12611,7 @@ var Sphere = class _Sphere {
10112
12611
  this._payments = createPaymentsModule({ l1: l1Config });
10113
12612
  this._communications = createCommunicationsModule();
10114
12613
  this._groupChat = groupChatConfig ? createGroupChatModule(groupChatConfig) : null;
12614
+ this._market = marketConfig ? createMarketModule(marketConfig) : null;
10115
12615
  }
10116
12616
  // ===========================================================================
10117
12617
  // Static Methods - Wallet Management
@@ -10160,6 +12660,7 @@ var Sphere = class _Sphere {
10160
12660
  */
10161
12661
  static async init(options) {
10162
12662
  const groupChat = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12663
+ const market = _Sphere.resolveMarketConfig(options.market);
10163
12664
  const walletExists = await _Sphere.exists(options.storage);
10164
12665
  if (walletExists) {
10165
12666
  const sphere2 = await _Sphere.load({
@@ -10170,7 +12671,8 @@ var Sphere = class _Sphere {
10170
12671
  l1: options.l1,
10171
12672
  price: options.price,
10172
12673
  groupChat,
10173
- password: options.password
12674
+ password: options.password,
12675
+ market
10174
12676
  });
10175
12677
  return { sphere: sphere2, created: false };
10176
12678
  }
@@ -10197,7 +12699,8 @@ var Sphere = class _Sphere {
10197
12699
  l1: options.l1,
10198
12700
  price: options.price,
10199
12701
  groupChat,
10200
- password: options.password
12702
+ password: options.password,
12703
+ market
10201
12704
  });
10202
12705
  return { sphere, created: true, generatedMnemonic };
10203
12706
  }
@@ -10224,6 +12727,22 @@ var Sphere = class _Sphere {
10224
12727
  }
10225
12728
  return config;
10226
12729
  }
12730
+ /**
12731
+ * Resolve market module config from Sphere.init() options.
12732
+ * - `true` → enable with default API URL
12733
+ * - `MarketModuleConfig` → pass through with defaults
12734
+ * - `undefined` → no market module
12735
+ */
12736
+ static resolveMarketConfig(config) {
12737
+ if (!config) return void 0;
12738
+ if (config === true) {
12739
+ return { apiUrl: DEFAULT_MARKET_API_URL };
12740
+ }
12741
+ return {
12742
+ apiUrl: config.apiUrl ?? DEFAULT_MARKET_API_URL,
12743
+ timeout: config.timeout
12744
+ };
12745
+ }
10227
12746
  /**
10228
12747
  * Create new wallet with mnemonic
10229
12748
  */
@@ -10235,6 +12754,7 @@ var Sphere = class _Sphere {
10235
12754
  throw new Error("Wallet already exists. Use Sphere.load() or Sphere.clear() first.");
10236
12755
  }
10237
12756
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12757
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10238
12758
  const sphere = new _Sphere(
10239
12759
  options.storage,
10240
12760
  options.transport,
@@ -10242,7 +12762,8 @@ var Sphere = class _Sphere {
10242
12762
  options.tokenStorage,
10243
12763
  options.l1,
10244
12764
  options.price,
10245
- groupChatConfig
12765
+ groupChatConfig,
12766
+ marketConfig
10246
12767
  );
10247
12768
  sphere._password = options.password ?? null;
10248
12769
  await sphere.storeMnemonic(options.mnemonic, options.derivationPath);
@@ -10269,6 +12790,7 @@ var Sphere = class _Sphere {
10269
12790
  throw new Error("No wallet found. Use Sphere.create() to create a new wallet.");
10270
12791
  }
10271
12792
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12793
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10272
12794
  const sphere = new _Sphere(
10273
12795
  options.storage,
10274
12796
  options.transport,
@@ -10276,7 +12798,8 @@ var Sphere = class _Sphere {
10276
12798
  options.tokenStorage,
10277
12799
  options.l1,
10278
12800
  options.price,
10279
- groupChatConfig
12801
+ groupChatConfig,
12802
+ marketConfig
10280
12803
  );
10281
12804
  sphere._password = options.password ?? null;
10282
12805
  await sphere.loadIdentityFromStorage();
@@ -10322,6 +12845,7 @@ var Sphere = class _Sphere {
10322
12845
  console.log("[Sphere.import] Storage reconnected");
10323
12846
  }
10324
12847
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat);
12848
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10325
12849
  const sphere = new _Sphere(
10326
12850
  options.storage,
10327
12851
  options.transport,
@@ -10329,7 +12853,8 @@ var Sphere = class _Sphere {
10329
12853
  options.tokenStorage,
10330
12854
  options.l1,
10331
12855
  options.price,
10332
- groupChatConfig
12856
+ groupChatConfig,
12857
+ marketConfig
10333
12858
  );
10334
12859
  sphere._password = options.password ?? null;
10335
12860
  if (options.mnemonic) {
@@ -10494,6 +13019,10 @@ var Sphere = class _Sphere {
10494
13019
  get groupChat() {
10495
13020
  return this._groupChat;
10496
13021
  }
13022
+ /** Market module (intent bulletin board). Null if not configured. */
13023
+ get market() {
13024
+ return this._market;
13025
+ }
10497
13026
  // ===========================================================================
10498
13027
  // Public Properties - State
10499
13028
  // ===========================================================================
@@ -11299,7 +13828,7 @@ var Sphere = class _Sphere {
11299
13828
  await provider.initialize();
11300
13829
  }
11301
13830
  await this.reinitializeModulesForNewAddress();
11302
- if (this._identity.nametag) {
13831
+ if (!newNametag) {
11303
13832
  await this.syncIdentityWithTransport();
11304
13833
  }
11305
13834
  if (newNametag) {
@@ -11369,9 +13898,14 @@ var Sphere = class _Sphere {
11369
13898
  storage: this._storage,
11370
13899
  emitEvent
11371
13900
  });
13901
+ this._market?.initialize({
13902
+ identity: this._identity,
13903
+ emitEvent
13904
+ });
11372
13905
  await this._payments.load();
11373
13906
  await this._communications.load();
11374
13907
  await this._groupChat?.load();
13908
+ await this._market?.load();
11375
13909
  }
11376
13910
  /**
11377
13911
  * Derive address at a specific index
@@ -12072,12 +14606,22 @@ var Sphere = class _Sphere {
12072
14606
  return;
12073
14607
  }
12074
14608
  try {
12075
- if (this._identity?.directAddress && this._transport.resolve) {
14609
+ const transportPubkey = this._identity?.chainPubkey?.slice(2);
14610
+ if (transportPubkey && this._transport.resolve) {
12076
14611
  try {
12077
- const existing = await this._transport.resolve(this._identity.directAddress);
14612
+ const existing = await this._transport.resolve(transportPubkey);
12078
14613
  if (existing) {
12079
- if (existing.nametag && !this._identity.nametag) {
12080
- this._identity.nametag = existing.nametag;
14614
+ let recoveredNametag = existing.nametag;
14615
+ let fromLegacy = false;
14616
+ if (!recoveredNametag && !this._identity?.nametag && this._transport.recoverNametag) {
14617
+ try {
14618
+ recoveredNametag = await this._transport.recoverNametag() ?? void 0;
14619
+ if (recoveredNametag) fromLegacy = true;
14620
+ } catch {
14621
+ }
14622
+ }
14623
+ if (recoveredNametag && !this._identity?.nametag) {
14624
+ this._identity.nametag = recoveredNametag;
12081
14625
  await this._updateCachedProxyAddress();
12082
14626
  const entry = await this.ensureAddressTracked(this._currentAddressIndex);
12083
14627
  let nametags = this._addressNametags.get(entry.addressId);
@@ -12086,10 +14630,20 @@ var Sphere = class _Sphere {
12086
14630
  this._addressNametags.set(entry.addressId, nametags);
12087
14631
  }
12088
14632
  if (!nametags.has(0)) {
12089
- nametags.set(0, existing.nametag);
14633
+ nametags.set(0, recoveredNametag);
12090
14634
  await this.persistAddressNametags();
12091
14635
  }
12092
- this.emitEvent("nametag:recovered", { nametag: existing.nametag });
14636
+ this.emitEvent("nametag:recovered", { nametag: recoveredNametag });
14637
+ if (fromLegacy) {
14638
+ await this._transport.publishIdentityBinding(
14639
+ this._identity.chainPubkey,
14640
+ this._identity.l1Address,
14641
+ this._identity.directAddress || "",
14642
+ recoveredNametag
14643
+ );
14644
+ console.log(`[Sphere] Migrated legacy binding with nametag @${recoveredNametag}`);
14645
+ return;
14646
+ }
12093
14647
  }
12094
14648
  console.log("[Sphere] Existing binding found, skipping re-publish");
12095
14649
  return;
@@ -12176,6 +14730,7 @@ var Sphere = class _Sphere {
12176
14730
  this._payments.destroy();
12177
14731
  this._communications.destroy();
12178
14732
  this._groupChat?.destroy();
14733
+ this._market?.destroy();
12179
14734
  await this._transport.disconnect();
12180
14735
  await this._storage.disconnect();
12181
14736
  await this._oracle.disconnect();
@@ -12483,9 +15038,14 @@ var Sphere = class _Sphere {
12483
15038
  storage: this._storage,
12484
15039
  emitEvent
12485
15040
  });
15041
+ this._market?.initialize({
15042
+ identity: this._identity,
15043
+ emitEvent
15044
+ });
12486
15045
  await this._payments.load();
12487
15046
  await this._communications.load();
12488
15047
  await this._groupChat?.load();
15048
+ await this._market?.load();
12489
15049
  }
12490
15050
  // ===========================================================================
12491
15051
  // Private: Helpers
@@ -13274,6 +15834,7 @@ function createPriceProvider(config) {
13274
15834
  DEFAULT_GROUP_RELAYS,
13275
15835
  DEFAULT_IPFS_BOOTSTRAP_PEERS,
13276
15836
  DEFAULT_IPFS_GATEWAYS,
15837
+ DEFAULT_MARKET_API_URL,
13277
15838
  DEFAULT_NOSTR_RELAYS,
13278
15839
  DEV_AGGREGATOR_URL,
13279
15840
  GroupChatModule,
@@ -13282,6 +15843,7 @@ function createPriceProvider(config) {
13282
15843
  L1,
13283
15844
  L1PaymentsModule,
13284
15845
  LIMITS,
15846
+ MarketModule,
13285
15847
  NETWORKS,
13286
15848
  NIP29_KINDS,
13287
15849
  NOSTR_EVENT_KINDS,
@@ -13309,6 +15871,7 @@ function createPriceProvider(config) {
13309
15871
  createGroupChatModule,
13310
15872
  createKeyPair,
13311
15873
  createL1PaymentsModule,
15874
+ createMarketModule,
13312
15875
  createPaymentSession,
13313
15876
  createPaymentSessionError,
13314
15877
  createPaymentsModule,
@@ -13396,4 +15959,16 @@ function createPriceProvider(config) {
13396
15959
  txfToToken,
13397
15960
  validateMnemonic
13398
15961
  });
15962
+ /*! Bundled license information:
15963
+
15964
+ @noble/hashes/utils.js:
15965
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
15966
+
15967
+ @noble/curves/utils.js:
15968
+ @noble/curves/abstract/modular.js:
15969
+ @noble/curves/abstract/curve.js:
15970
+ @noble/curves/abstract/weierstrass.js:
15971
+ @noble/curves/secp256k1.js:
15972
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
15973
+ */
13399
15974
  //# sourceMappingURL=index.cjs.map