@unicitylabs/sphere-sdk 0.3.9 → 0.4.0

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,11 +489,14 @@ __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,
494
496
  PaymentsModule: () => PaymentsModule,
495
497
  STORAGE_KEYS: () => STORAGE_KEYS,
498
+ STORAGE_KEYS_ADDRESS: () => STORAGE_KEYS_ADDRESS,
499
+ STORAGE_KEYS_GLOBAL: () => STORAGE_KEYS_GLOBAL,
496
500
  STORAGE_PREFIX: () => STORAGE_PREFIX,
497
501
  Sphere: () => Sphere,
498
502
  SphereError: () => SphereError,
@@ -515,6 +519,7 @@ __export(index_exports, {
515
519
  createGroupChatModule: () => createGroupChatModule,
516
520
  createKeyPair: () => createKeyPair,
517
521
  createL1PaymentsModule: () => createL1PaymentsModule,
522
+ createMarketModule: () => createMarketModule,
518
523
  createPaymentSession: () => createPaymentSession,
519
524
  createPaymentSessionError: () => createPaymentSessionError,
520
525
  createPaymentsModule: () => createPaymentsModule,
@@ -538,6 +543,8 @@ __export(index_exports, {
538
543
  generateMasterKey: () => generateMasterKey,
539
544
  generateMnemonic: () => generateMnemonic2,
540
545
  getAddressHrp: () => getAddressHrp,
546
+ getAddressId: () => getAddressId,
547
+ getAddressStorageKey: () => getAddressStorageKey,
541
548
  getCoinIdByName: () => getCoinIdByName,
542
549
  getCoinIdBySymbol: () => getCoinIdBySymbol,
543
550
  getCurrentStateHash: () => getCurrentStateHash,
@@ -987,9 +994,13 @@ var VestingClassifier = class {
987
994
  storeName = "vestingCache";
988
995
  db = null;
989
996
  /**
990
- * Initialize IndexedDB for persistent caching
997
+ * Initialize IndexedDB for persistent caching.
998
+ * In Node.js (no IndexedDB), silently falls back to memory-only caching.
991
999
  */
992
1000
  async initDB() {
1001
+ if (typeof indexedDB === "undefined") {
1002
+ return;
1003
+ }
993
1004
  return new Promise((resolve, reject) => {
994
1005
  const request = indexedDB.open(this.dbName, 1);
995
1006
  request.onupgradeneeded = (event) => {
@@ -2672,6 +2683,9 @@ var STORAGE_KEYS = {
2672
2683
  ...STORAGE_KEYS_GLOBAL,
2673
2684
  ...STORAGE_KEYS_ADDRESS
2674
2685
  };
2686
+ function getAddressStorageKey(addressId, key) {
2687
+ return `${addressId}_${key}`;
2688
+ }
2675
2689
  function getAddressId(directAddress) {
2676
2690
  let hash = directAddress;
2677
2691
  if (hash.startsWith("DIRECT://")) {
@@ -7079,6 +7093,15 @@ var PaymentsModule = class _PaymentsModule {
7079
7093
  );
7080
7094
  return import_SigningService.SigningService.createFromSecret(privateKeyBytes);
7081
7095
  }
7096
+ /**
7097
+ * Get the wallet's signing public key (used for token ownership predicates).
7098
+ * This is the key that token state predicates are checked against.
7099
+ */
7100
+ async getSigningPublicKey() {
7101
+ this.ensureInitialized();
7102
+ const signer = await this.createSigningService();
7103
+ return signer.publicKey;
7104
+ }
7082
7105
  /**
7083
7106
  * Create DirectAddress from a public key using UnmaskedPredicateReference
7084
7107
  */
@@ -7727,14 +7750,17 @@ var CommunicationsModule = class {
7727
7750
  broadcasts = /* @__PURE__ */ new Map();
7728
7751
  // Subscriptions
7729
7752
  unsubscribeMessages = null;
7753
+ unsubscribeComposing = null;
7730
7754
  broadcastSubscriptions = /* @__PURE__ */ new Map();
7731
7755
  // Handlers
7732
7756
  dmHandlers = /* @__PURE__ */ new Set();
7757
+ composingHandlers = /* @__PURE__ */ new Set();
7733
7758
  broadcastHandlers = /* @__PURE__ */ new Set();
7734
7759
  constructor(config) {
7735
7760
  this.config = {
7736
7761
  autoSave: config?.autoSave ?? true,
7737
7762
  maxMessages: config?.maxMessages ?? 1e3,
7763
+ maxPerConversation: config?.maxPerConversation ?? 200,
7738
7764
  readReceipts: config?.readReceipts ?? true
7739
7765
  };
7740
7766
  }
@@ -7745,6 +7771,8 @@ var CommunicationsModule = class {
7745
7771
  * Initialize module with dependencies
7746
7772
  */
7747
7773
  initialize(deps) {
7774
+ this.unsubscribeMessages?.();
7775
+ this.unsubscribeComposing?.();
7748
7776
  this.deps = deps;
7749
7777
  this.unsubscribeMessages = deps.transport.onMessage((msg) => {
7750
7778
  this.handleIncomingMessage(msg);
@@ -7771,19 +7799,41 @@ var CommunicationsModule = class {
7771
7799
  });
7772
7800
  });
7773
7801
  }
7802
+ this.unsubscribeComposing = deps.transport.onComposing?.((indicator) => {
7803
+ this.handleComposingIndicator(indicator);
7804
+ }) ?? null;
7774
7805
  }
7775
7806
  /**
7776
- * Load messages from storage
7807
+ * Load messages from storage.
7808
+ * Uses per-address key (STORAGE_KEYS_ADDRESS.MESSAGES) which is automatically
7809
+ * scoped by LocalStorageProvider to sphere_DIRECT_xxx_yyy_messages.
7810
+ * Falls back to legacy global 'direct_messages' key for migration.
7777
7811
  */
7778
7812
  async load() {
7779
7813
  this.ensureInitialized();
7780
- const data = await this.deps.storage.get("direct_messages");
7814
+ this.messages.clear();
7815
+ let data = await this.deps.storage.get(STORAGE_KEYS_ADDRESS.MESSAGES);
7781
7816
  if (data) {
7782
7817
  const messages = JSON.parse(data);
7783
- this.messages.clear();
7784
7818
  for (const msg of messages) {
7785
7819
  this.messages.set(msg.id, msg);
7786
7820
  }
7821
+ return;
7822
+ }
7823
+ data = await this.deps.storage.get("direct_messages");
7824
+ if (data) {
7825
+ const allMessages = JSON.parse(data);
7826
+ const myPubkey = this.deps.identity.chainPubkey;
7827
+ const myMessages = allMessages.filter(
7828
+ (m) => m.senderPubkey === myPubkey || m.recipientPubkey === myPubkey
7829
+ );
7830
+ for (const msg of myMessages) {
7831
+ this.messages.set(msg.id, msg);
7832
+ }
7833
+ if (myMessages.length > 0) {
7834
+ await this.save();
7835
+ console.log(`[Communications] Migrated ${myMessages.length} messages to per-address storage`);
7836
+ }
7787
7837
  }
7788
7838
  }
7789
7839
  /**
@@ -7792,6 +7842,8 @@ var CommunicationsModule = class {
7792
7842
  destroy() {
7793
7843
  this.unsubscribeMessages?.();
7794
7844
  this.unsubscribeMessages = null;
7845
+ this.unsubscribeComposing?.();
7846
+ this.unsubscribeComposing = null;
7795
7847
  for (const unsub of this.broadcastSubscriptions.values()) {
7796
7848
  unsub();
7797
7849
  }
@@ -7883,6 +7935,37 @@ var CommunicationsModule = class {
7883
7935
  }
7884
7936
  return messages.length;
7885
7937
  }
7938
+ /**
7939
+ * Get a page of messages from a conversation (for lazy loading).
7940
+ * Returns messages in chronological order with a cursor for loading older messages.
7941
+ */
7942
+ getConversationPage(peerPubkey, options) {
7943
+ const limit = options?.limit ?? 20;
7944
+ const before = options?.before ?? Infinity;
7945
+ const all = Array.from(this.messages.values()).filter(
7946
+ (m) => (m.senderPubkey === peerPubkey || m.recipientPubkey === peerPubkey) && m.timestamp < before
7947
+ ).sort((a, b) => b.timestamp - a.timestamp);
7948
+ const page = all.slice(0, limit);
7949
+ return {
7950
+ messages: page.reverse(),
7951
+ // chronological order for display
7952
+ hasMore: all.length > limit,
7953
+ oldestTimestamp: page.length > 0 ? page[0].timestamp : null
7954
+ };
7955
+ }
7956
+ /**
7957
+ * Delete all messages in a conversation with a peer
7958
+ */
7959
+ async deleteConversation(peerPubkey) {
7960
+ for (const [id, msg] of this.messages) {
7961
+ if (msg.senderPubkey === peerPubkey || msg.recipientPubkey === peerPubkey) {
7962
+ this.messages.delete(id);
7963
+ }
7964
+ }
7965
+ if (this.config.autoSave) {
7966
+ await this.save();
7967
+ }
7968
+ }
7886
7969
  /**
7887
7970
  * Send typing indicator to a peer
7888
7971
  */
@@ -7892,6 +7975,26 @@ var CommunicationsModule = class {
7892
7975
  await this.deps.transport.sendTypingIndicator(peerPubkey);
7893
7976
  }
7894
7977
  }
7978
+ /**
7979
+ * Send a composing indicator to a peer.
7980
+ * Fire-and-forget — does not save to message history.
7981
+ */
7982
+ async sendComposingIndicator(recipientPubkeyOrNametag) {
7983
+ this.ensureInitialized();
7984
+ const recipientPubkey = await this.resolveRecipient(recipientPubkeyOrNametag);
7985
+ const content = JSON.stringify({
7986
+ senderNametag: this.deps.identity.nametag,
7987
+ expiresIn: 3e4
7988
+ });
7989
+ await this.deps.transport.sendComposingIndicator?.(recipientPubkey, content);
7990
+ }
7991
+ /**
7992
+ * Subscribe to incoming composing indicators
7993
+ */
7994
+ onComposingIndicator(handler) {
7995
+ this.composingHandlers.add(handler);
7996
+ return () => this.composingHandlers.delete(handler);
7997
+ }
7895
7998
  /**
7896
7999
  * Subscribe to incoming DMs
7897
8000
  */
@@ -8004,6 +8107,21 @@ var CommunicationsModule = class {
8004
8107
  }
8005
8108
  this.pruneIfNeeded();
8006
8109
  }
8110
+ handleComposingIndicator(indicator) {
8111
+ const composing = {
8112
+ senderPubkey: indicator.senderPubkey,
8113
+ senderNametag: indicator.senderNametag,
8114
+ expiresIn: indicator.expiresIn
8115
+ };
8116
+ this.deps.emitEvent("composing:started", composing);
8117
+ for (const handler of this.composingHandlers) {
8118
+ try {
8119
+ handler(composing);
8120
+ } catch (error) {
8121
+ console.error("[Communications] Composing handler error:", error);
8122
+ }
8123
+ }
8124
+ }
8007
8125
  handleIncomingBroadcast(incoming) {
8008
8126
  const message = {
8009
8127
  id: incoming.id,
@@ -8027,9 +8145,23 @@ var CommunicationsModule = class {
8027
8145
  // ===========================================================================
8028
8146
  async save() {
8029
8147
  const messages = Array.from(this.messages.values());
8030
- await this.deps.storage.set("direct_messages", JSON.stringify(messages));
8148
+ await this.deps.storage.set(STORAGE_KEYS_ADDRESS.MESSAGES, JSON.stringify(messages));
8031
8149
  }
8032
8150
  pruneIfNeeded() {
8151
+ const byPeer = /* @__PURE__ */ new Map();
8152
+ for (const msg of this.messages.values()) {
8153
+ const peer = msg.senderPubkey === this.deps?.identity.chainPubkey ? msg.recipientPubkey : msg.senderPubkey;
8154
+ if (!byPeer.has(peer)) byPeer.set(peer, []);
8155
+ byPeer.get(peer).push(msg);
8156
+ }
8157
+ for (const [, msgs] of byPeer) {
8158
+ if (msgs.length <= this.config.maxPerConversation) continue;
8159
+ msgs.sort((a, b) => a.timestamp - b.timestamp);
8160
+ const toRemove2 = msgs.slice(0, msgs.length - this.config.maxPerConversation);
8161
+ for (const msg of toRemove2) {
8162
+ this.messages.delete(msg.id);
8163
+ }
8164
+ }
8033
8165
  if (this.messages.size <= this.config.maxMessages) return;
8034
8166
  const sorted = Array.from(this.messages.entries()).sort(([, a], [, b]) => a.timestamp - b.timestamp);
8035
8167
  const toRemove = sorted.slice(0, sorted.length - this.config.maxMessages);
@@ -9438,6 +9570,2427 @@ function createGroupChatModule(config) {
9438
9570
  return new GroupChatModule(config);
9439
9571
  }
9440
9572
 
9573
+ // node_modules/@noble/hashes/utils.js
9574
+ function isBytes(a) {
9575
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
9576
+ }
9577
+ function anumber(n, title = "") {
9578
+ if (!Number.isSafeInteger(n) || n < 0) {
9579
+ const prefix = title && `"${title}" `;
9580
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
9581
+ }
9582
+ }
9583
+ function abytes(value, length, title = "") {
9584
+ const bytes = isBytes(value);
9585
+ const len = value?.length;
9586
+ const needsLen = length !== void 0;
9587
+ if (!bytes || needsLen && len !== length) {
9588
+ const prefix = title && `"${title}" `;
9589
+ const ofLen = needsLen ? ` of length ${length}` : "";
9590
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
9591
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
9592
+ }
9593
+ return value;
9594
+ }
9595
+ function ahash(h) {
9596
+ if (typeof h !== "function" || typeof h.create !== "function")
9597
+ throw new Error("Hash must wrapped by utils.createHasher");
9598
+ anumber(h.outputLen);
9599
+ anumber(h.blockLen);
9600
+ }
9601
+ function aexists(instance, checkFinished = true) {
9602
+ if (instance.destroyed)
9603
+ throw new Error("Hash instance has been destroyed");
9604
+ if (checkFinished && instance.finished)
9605
+ throw new Error("Hash#digest() has already been called");
9606
+ }
9607
+ function aoutput(out, instance) {
9608
+ abytes(out, void 0, "digestInto() output");
9609
+ const min = instance.outputLen;
9610
+ if (out.length < min) {
9611
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
9612
+ }
9613
+ }
9614
+ function clean(...arrays) {
9615
+ for (let i = 0; i < arrays.length; i++) {
9616
+ arrays[i].fill(0);
9617
+ }
9618
+ }
9619
+ function createView(arr) {
9620
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
9621
+ }
9622
+ function rotr(word, shift) {
9623
+ return word << 32 - shift | word >>> shift;
9624
+ }
9625
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
9626
+ // @ts-ignore
9627
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
9628
+ ))();
9629
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
9630
+ function bytesToHex4(bytes) {
9631
+ abytes(bytes);
9632
+ if (hasHexBuiltin)
9633
+ return bytes.toHex();
9634
+ let hex = "";
9635
+ for (let i = 0; i < bytes.length; i++) {
9636
+ hex += hexes[bytes[i]];
9637
+ }
9638
+ return hex;
9639
+ }
9640
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
9641
+ function asciiToBase16(ch) {
9642
+ if (ch >= asciis._0 && ch <= asciis._9)
9643
+ return ch - asciis._0;
9644
+ if (ch >= asciis.A && ch <= asciis.F)
9645
+ return ch - (asciis.A - 10);
9646
+ if (ch >= asciis.a && ch <= asciis.f)
9647
+ return ch - (asciis.a - 10);
9648
+ return;
9649
+ }
9650
+ function hexToBytes2(hex) {
9651
+ if (typeof hex !== "string")
9652
+ throw new Error("hex string expected, got " + typeof hex);
9653
+ if (hasHexBuiltin)
9654
+ return Uint8Array.fromHex(hex);
9655
+ const hl = hex.length;
9656
+ const al = hl / 2;
9657
+ if (hl % 2)
9658
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
9659
+ const array = new Uint8Array(al);
9660
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
9661
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
9662
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
9663
+ if (n1 === void 0 || n2 === void 0) {
9664
+ const char = hex[hi] + hex[hi + 1];
9665
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
9666
+ }
9667
+ array[ai] = n1 * 16 + n2;
9668
+ }
9669
+ return array;
9670
+ }
9671
+ function concatBytes(...arrays) {
9672
+ let sum = 0;
9673
+ for (let i = 0; i < arrays.length; i++) {
9674
+ const a = arrays[i];
9675
+ abytes(a);
9676
+ sum += a.length;
9677
+ }
9678
+ const res = new Uint8Array(sum);
9679
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
9680
+ const a = arrays[i];
9681
+ res.set(a, pad);
9682
+ pad += a.length;
9683
+ }
9684
+ return res;
9685
+ }
9686
+ function createHasher(hashCons, info = {}) {
9687
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
9688
+ const tmp = hashCons(void 0);
9689
+ hashC.outputLen = tmp.outputLen;
9690
+ hashC.blockLen = tmp.blockLen;
9691
+ hashC.create = (opts) => hashCons(opts);
9692
+ Object.assign(hashC, info);
9693
+ return Object.freeze(hashC);
9694
+ }
9695
+ function randomBytes2(bytesLength = 32) {
9696
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
9697
+ if (typeof cr?.getRandomValues !== "function")
9698
+ throw new Error("crypto.getRandomValues must be defined");
9699
+ return cr.getRandomValues(new Uint8Array(bytesLength));
9700
+ }
9701
+ var oidNist = (suffix) => ({
9702
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
9703
+ });
9704
+
9705
+ // node_modules/@noble/hashes/_md.js
9706
+ function Chi(a, b, c) {
9707
+ return a & b ^ ~a & c;
9708
+ }
9709
+ function Maj(a, b, c) {
9710
+ return a & b ^ a & c ^ b & c;
9711
+ }
9712
+ var HashMD = class {
9713
+ blockLen;
9714
+ outputLen;
9715
+ padOffset;
9716
+ isLE;
9717
+ // For partial updates less than block size
9718
+ buffer;
9719
+ view;
9720
+ finished = false;
9721
+ length = 0;
9722
+ pos = 0;
9723
+ destroyed = false;
9724
+ constructor(blockLen, outputLen, padOffset, isLE) {
9725
+ this.blockLen = blockLen;
9726
+ this.outputLen = outputLen;
9727
+ this.padOffset = padOffset;
9728
+ this.isLE = isLE;
9729
+ this.buffer = new Uint8Array(blockLen);
9730
+ this.view = createView(this.buffer);
9731
+ }
9732
+ update(data) {
9733
+ aexists(this);
9734
+ abytes(data);
9735
+ const { view, buffer, blockLen } = this;
9736
+ const len = data.length;
9737
+ for (let pos = 0; pos < len; ) {
9738
+ const take = Math.min(blockLen - this.pos, len - pos);
9739
+ if (take === blockLen) {
9740
+ const dataView = createView(data);
9741
+ for (; blockLen <= len - pos; pos += blockLen)
9742
+ this.process(dataView, pos);
9743
+ continue;
9744
+ }
9745
+ buffer.set(data.subarray(pos, pos + take), this.pos);
9746
+ this.pos += take;
9747
+ pos += take;
9748
+ if (this.pos === blockLen) {
9749
+ this.process(view, 0);
9750
+ this.pos = 0;
9751
+ }
9752
+ }
9753
+ this.length += data.length;
9754
+ this.roundClean();
9755
+ return this;
9756
+ }
9757
+ digestInto(out) {
9758
+ aexists(this);
9759
+ aoutput(out, this);
9760
+ this.finished = true;
9761
+ const { buffer, view, blockLen, isLE } = this;
9762
+ let { pos } = this;
9763
+ buffer[pos++] = 128;
9764
+ clean(this.buffer.subarray(pos));
9765
+ if (this.padOffset > blockLen - pos) {
9766
+ this.process(view, 0);
9767
+ pos = 0;
9768
+ }
9769
+ for (let i = pos; i < blockLen; i++)
9770
+ buffer[i] = 0;
9771
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
9772
+ this.process(view, 0);
9773
+ const oview = createView(out);
9774
+ const len = this.outputLen;
9775
+ if (len % 4)
9776
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
9777
+ const outLen = len / 4;
9778
+ const state = this.get();
9779
+ if (outLen > state.length)
9780
+ throw new Error("_sha2: outputLen bigger than state");
9781
+ for (let i = 0; i < outLen; i++)
9782
+ oview.setUint32(4 * i, state[i], isLE);
9783
+ }
9784
+ digest() {
9785
+ const { buffer, outputLen } = this;
9786
+ this.digestInto(buffer);
9787
+ const res = buffer.slice(0, outputLen);
9788
+ this.destroy();
9789
+ return res;
9790
+ }
9791
+ _cloneInto(to) {
9792
+ to ||= new this.constructor();
9793
+ to.set(...this.get());
9794
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
9795
+ to.destroyed = destroyed;
9796
+ to.finished = finished;
9797
+ to.length = length;
9798
+ to.pos = pos;
9799
+ if (length % blockLen)
9800
+ to.buffer.set(buffer);
9801
+ return to;
9802
+ }
9803
+ clone() {
9804
+ return this._cloneInto();
9805
+ }
9806
+ };
9807
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
9808
+ 1779033703,
9809
+ 3144134277,
9810
+ 1013904242,
9811
+ 2773480762,
9812
+ 1359893119,
9813
+ 2600822924,
9814
+ 528734635,
9815
+ 1541459225
9816
+ ]);
9817
+
9818
+ // node_modules/@noble/hashes/sha2.js
9819
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
9820
+ 1116352408,
9821
+ 1899447441,
9822
+ 3049323471,
9823
+ 3921009573,
9824
+ 961987163,
9825
+ 1508970993,
9826
+ 2453635748,
9827
+ 2870763221,
9828
+ 3624381080,
9829
+ 310598401,
9830
+ 607225278,
9831
+ 1426881987,
9832
+ 1925078388,
9833
+ 2162078206,
9834
+ 2614888103,
9835
+ 3248222580,
9836
+ 3835390401,
9837
+ 4022224774,
9838
+ 264347078,
9839
+ 604807628,
9840
+ 770255983,
9841
+ 1249150122,
9842
+ 1555081692,
9843
+ 1996064986,
9844
+ 2554220882,
9845
+ 2821834349,
9846
+ 2952996808,
9847
+ 3210313671,
9848
+ 3336571891,
9849
+ 3584528711,
9850
+ 113926993,
9851
+ 338241895,
9852
+ 666307205,
9853
+ 773529912,
9854
+ 1294757372,
9855
+ 1396182291,
9856
+ 1695183700,
9857
+ 1986661051,
9858
+ 2177026350,
9859
+ 2456956037,
9860
+ 2730485921,
9861
+ 2820302411,
9862
+ 3259730800,
9863
+ 3345764771,
9864
+ 3516065817,
9865
+ 3600352804,
9866
+ 4094571909,
9867
+ 275423344,
9868
+ 430227734,
9869
+ 506948616,
9870
+ 659060556,
9871
+ 883997877,
9872
+ 958139571,
9873
+ 1322822218,
9874
+ 1537002063,
9875
+ 1747873779,
9876
+ 1955562222,
9877
+ 2024104815,
9878
+ 2227730452,
9879
+ 2361852424,
9880
+ 2428436474,
9881
+ 2756734187,
9882
+ 3204031479,
9883
+ 3329325298
9884
+ ]);
9885
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
9886
+ var SHA2_32B = class extends HashMD {
9887
+ constructor(outputLen) {
9888
+ super(64, outputLen, 8, false);
9889
+ }
9890
+ get() {
9891
+ const { A, B, C, D, E, F, G, H } = this;
9892
+ return [A, B, C, D, E, F, G, H];
9893
+ }
9894
+ // prettier-ignore
9895
+ set(A, B, C, D, E, F, G, H) {
9896
+ this.A = A | 0;
9897
+ this.B = B | 0;
9898
+ this.C = C | 0;
9899
+ this.D = D | 0;
9900
+ this.E = E | 0;
9901
+ this.F = F | 0;
9902
+ this.G = G | 0;
9903
+ this.H = H | 0;
9904
+ }
9905
+ process(view, offset) {
9906
+ for (let i = 0; i < 16; i++, offset += 4)
9907
+ SHA256_W[i] = view.getUint32(offset, false);
9908
+ for (let i = 16; i < 64; i++) {
9909
+ const W15 = SHA256_W[i - 15];
9910
+ const W2 = SHA256_W[i - 2];
9911
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
9912
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
9913
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
9914
+ }
9915
+ let { A, B, C, D, E, F, G, H } = this;
9916
+ for (let i = 0; i < 64; i++) {
9917
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
9918
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
9919
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
9920
+ const T2 = sigma0 + Maj(A, B, C) | 0;
9921
+ H = G;
9922
+ G = F;
9923
+ F = E;
9924
+ E = D + T1 | 0;
9925
+ D = C;
9926
+ C = B;
9927
+ B = A;
9928
+ A = T1 + T2 | 0;
9929
+ }
9930
+ A = A + this.A | 0;
9931
+ B = B + this.B | 0;
9932
+ C = C + this.C | 0;
9933
+ D = D + this.D | 0;
9934
+ E = E + this.E | 0;
9935
+ F = F + this.F | 0;
9936
+ G = G + this.G | 0;
9937
+ H = H + this.H | 0;
9938
+ this.set(A, B, C, D, E, F, G, H);
9939
+ }
9940
+ roundClean() {
9941
+ clean(SHA256_W);
9942
+ }
9943
+ destroy() {
9944
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
9945
+ clean(this.buffer);
9946
+ }
9947
+ };
9948
+ var _SHA256 = class extends SHA2_32B {
9949
+ // We cannot use array here since array allows indexing by variable
9950
+ // which means optimizer/compiler cannot use registers.
9951
+ A = SHA256_IV[0] | 0;
9952
+ B = SHA256_IV[1] | 0;
9953
+ C = SHA256_IV[2] | 0;
9954
+ D = SHA256_IV[3] | 0;
9955
+ E = SHA256_IV[4] | 0;
9956
+ F = SHA256_IV[5] | 0;
9957
+ G = SHA256_IV[6] | 0;
9958
+ H = SHA256_IV[7] | 0;
9959
+ constructor() {
9960
+ super(32);
9961
+ }
9962
+ };
9963
+ var sha2564 = /* @__PURE__ */ createHasher(
9964
+ () => new _SHA256(),
9965
+ /* @__PURE__ */ oidNist(1)
9966
+ );
9967
+
9968
+ // node_modules/@noble/curves/utils.js
9969
+ var _0n = /* @__PURE__ */ BigInt(0);
9970
+ var _1n = /* @__PURE__ */ BigInt(1);
9971
+ function abool(value, title = "") {
9972
+ if (typeof value !== "boolean") {
9973
+ const prefix = title && `"${title}" `;
9974
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
9975
+ }
9976
+ return value;
9977
+ }
9978
+ function abignumber(n) {
9979
+ if (typeof n === "bigint") {
9980
+ if (!isPosBig(n))
9981
+ throw new Error("positive bigint expected, got " + n);
9982
+ } else
9983
+ anumber(n);
9984
+ return n;
9985
+ }
9986
+ function numberToHexUnpadded(num) {
9987
+ const hex = abignumber(num).toString(16);
9988
+ return hex.length & 1 ? "0" + hex : hex;
9989
+ }
9990
+ function hexToNumber(hex) {
9991
+ if (typeof hex !== "string")
9992
+ throw new Error("hex string expected, got " + typeof hex);
9993
+ return hex === "" ? _0n : BigInt("0x" + hex);
9994
+ }
9995
+ function bytesToNumberBE(bytes) {
9996
+ return hexToNumber(bytesToHex4(bytes));
9997
+ }
9998
+ function bytesToNumberLE(bytes) {
9999
+ return hexToNumber(bytesToHex4(copyBytes(abytes(bytes)).reverse()));
10000
+ }
10001
+ function numberToBytesBE(n, len) {
10002
+ anumber(len);
10003
+ n = abignumber(n);
10004
+ const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
10005
+ if (res.length !== len)
10006
+ throw new Error("number too large");
10007
+ return res;
10008
+ }
10009
+ function numberToBytesLE(n, len) {
10010
+ return numberToBytesBE(n, len).reverse();
10011
+ }
10012
+ function copyBytes(bytes) {
10013
+ return Uint8Array.from(bytes);
10014
+ }
10015
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
10016
+ function inRange(n, min, max) {
10017
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
10018
+ }
10019
+ function aInRange(title, n, min, max) {
10020
+ if (!inRange(n, min, max))
10021
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
10022
+ }
10023
+ function bitLen(n) {
10024
+ let len;
10025
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
10026
+ ;
10027
+ return len;
10028
+ }
10029
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
10030
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
10031
+ anumber(hashLen, "hashLen");
10032
+ anumber(qByteLen, "qByteLen");
10033
+ if (typeof hmacFn !== "function")
10034
+ throw new Error("hmacFn must be a function");
10035
+ const u8n = (len) => new Uint8Array(len);
10036
+ const NULL = Uint8Array.of();
10037
+ const byte0 = Uint8Array.of(0);
10038
+ const byte1 = Uint8Array.of(1);
10039
+ const _maxDrbgIters = 1e3;
10040
+ let v = u8n(hashLen);
10041
+ let k = u8n(hashLen);
10042
+ let i = 0;
10043
+ const reset = () => {
10044
+ v.fill(1);
10045
+ k.fill(0);
10046
+ i = 0;
10047
+ };
10048
+ const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
10049
+ const reseed = (seed = NULL) => {
10050
+ k = h(byte0, seed);
10051
+ v = h();
10052
+ if (seed.length === 0)
10053
+ return;
10054
+ k = h(byte1, seed);
10055
+ v = h();
10056
+ };
10057
+ const gen = () => {
10058
+ if (i++ >= _maxDrbgIters)
10059
+ throw new Error("drbg: tried max amount of iterations");
10060
+ let len = 0;
10061
+ const out = [];
10062
+ while (len < qByteLen) {
10063
+ v = h();
10064
+ const sl = v.slice();
10065
+ out.push(sl);
10066
+ len += v.length;
10067
+ }
10068
+ return concatBytes(...out);
10069
+ };
10070
+ const genUntil = (seed, pred) => {
10071
+ reset();
10072
+ reseed(seed);
10073
+ let res = void 0;
10074
+ while (!(res = pred(gen())))
10075
+ reseed();
10076
+ reset();
10077
+ return res;
10078
+ };
10079
+ return genUntil;
10080
+ }
10081
+ function validateObject(object, fields = {}, optFields = {}) {
10082
+ if (!object || typeof object !== "object")
10083
+ throw new Error("expected valid options object");
10084
+ function checkField(fieldName, expectedType, isOpt) {
10085
+ const val = object[fieldName];
10086
+ if (isOpt && val === void 0)
10087
+ return;
10088
+ const current = typeof val;
10089
+ if (current !== expectedType || val === null)
10090
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
10091
+ }
10092
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
10093
+ iter(fields, false);
10094
+ iter(optFields, true);
10095
+ }
10096
+ function memoized(fn) {
10097
+ const map = /* @__PURE__ */ new WeakMap();
10098
+ return (arg, ...args) => {
10099
+ const val = map.get(arg);
10100
+ if (val !== void 0)
10101
+ return val;
10102
+ const computed = fn(arg, ...args);
10103
+ map.set(arg, computed);
10104
+ return computed;
10105
+ };
10106
+ }
10107
+
10108
+ // node_modules/@noble/curves/abstract/modular.js
10109
+ var _0n2 = /* @__PURE__ */ BigInt(0);
10110
+ var _1n2 = /* @__PURE__ */ BigInt(1);
10111
+ var _2n = /* @__PURE__ */ BigInt(2);
10112
+ var _3n = /* @__PURE__ */ BigInt(3);
10113
+ var _4n = /* @__PURE__ */ BigInt(4);
10114
+ var _5n = /* @__PURE__ */ BigInt(5);
10115
+ var _7n = /* @__PURE__ */ BigInt(7);
10116
+ var _8n = /* @__PURE__ */ BigInt(8);
10117
+ var _9n = /* @__PURE__ */ BigInt(9);
10118
+ var _16n = /* @__PURE__ */ BigInt(16);
10119
+ function mod(a, b) {
10120
+ const result = a % b;
10121
+ return result >= _0n2 ? result : b + result;
10122
+ }
10123
+ function pow2(x, power, modulo) {
10124
+ let res = x;
10125
+ while (power-- > _0n2) {
10126
+ res *= res;
10127
+ res %= modulo;
10128
+ }
10129
+ return res;
10130
+ }
10131
+ function invert(number, modulo) {
10132
+ if (number === _0n2)
10133
+ throw new Error("invert: expected non-zero number");
10134
+ if (modulo <= _0n2)
10135
+ throw new Error("invert: expected positive modulus, got " + modulo);
10136
+ let a = mod(number, modulo);
10137
+ let b = modulo;
10138
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
10139
+ while (a !== _0n2) {
10140
+ const q = b / a;
10141
+ const r = b % a;
10142
+ const m = x - u * q;
10143
+ const n = y - v * q;
10144
+ b = a, a = r, x = u, y = v, u = m, v = n;
10145
+ }
10146
+ const gcd = b;
10147
+ if (gcd !== _1n2)
10148
+ throw new Error("invert: does not exist");
10149
+ return mod(x, modulo);
10150
+ }
10151
+ function assertIsSquare(Fp, root, n) {
10152
+ if (!Fp.eql(Fp.sqr(root), n))
10153
+ throw new Error("Cannot find square root");
10154
+ }
10155
+ function sqrt3mod4(Fp, n) {
10156
+ const p1div4 = (Fp.ORDER + _1n2) / _4n;
10157
+ const root = Fp.pow(n, p1div4);
10158
+ assertIsSquare(Fp, root, n);
10159
+ return root;
10160
+ }
10161
+ function sqrt5mod8(Fp, n) {
10162
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
10163
+ const n2 = Fp.mul(n, _2n);
10164
+ const v = Fp.pow(n2, p5div8);
10165
+ const nv = Fp.mul(n, v);
10166
+ const i = Fp.mul(Fp.mul(nv, _2n), v);
10167
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
10168
+ assertIsSquare(Fp, root, n);
10169
+ return root;
10170
+ }
10171
+ function sqrt9mod16(P) {
10172
+ const Fp_ = Field(P);
10173
+ const tn = tonelliShanks(P);
10174
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
10175
+ const c2 = tn(Fp_, c1);
10176
+ const c3 = tn(Fp_, Fp_.neg(c1));
10177
+ const c4 = (P + _7n) / _16n;
10178
+ return (Fp, n) => {
10179
+ let tv1 = Fp.pow(n, c4);
10180
+ let tv2 = Fp.mul(tv1, c1);
10181
+ const tv3 = Fp.mul(tv1, c2);
10182
+ const tv4 = Fp.mul(tv1, c3);
10183
+ const e1 = Fp.eql(Fp.sqr(tv2), n);
10184
+ const e2 = Fp.eql(Fp.sqr(tv3), n);
10185
+ tv1 = Fp.cmov(tv1, tv2, e1);
10186
+ tv2 = Fp.cmov(tv4, tv3, e2);
10187
+ const e3 = Fp.eql(Fp.sqr(tv2), n);
10188
+ const root = Fp.cmov(tv1, tv2, e3);
10189
+ assertIsSquare(Fp, root, n);
10190
+ return root;
10191
+ };
10192
+ }
10193
+ function tonelliShanks(P) {
10194
+ if (P < _3n)
10195
+ throw new Error("sqrt is not defined for small field");
10196
+ let Q = P - _1n2;
10197
+ let S = 0;
10198
+ while (Q % _2n === _0n2) {
10199
+ Q /= _2n;
10200
+ S++;
10201
+ }
10202
+ let Z = _2n;
10203
+ const _Fp = Field(P);
10204
+ while (FpLegendre(_Fp, Z) === 1) {
10205
+ if (Z++ > 1e3)
10206
+ throw new Error("Cannot find square root: probably non-prime P");
10207
+ }
10208
+ if (S === 1)
10209
+ return sqrt3mod4;
10210
+ let cc = _Fp.pow(Z, Q);
10211
+ const Q1div2 = (Q + _1n2) / _2n;
10212
+ return function tonelliSlow(Fp, n) {
10213
+ if (Fp.is0(n))
10214
+ return n;
10215
+ if (FpLegendre(Fp, n) !== 1)
10216
+ throw new Error("Cannot find square root");
10217
+ let M = S;
10218
+ let c = Fp.mul(Fp.ONE, cc);
10219
+ let t = Fp.pow(n, Q);
10220
+ let R = Fp.pow(n, Q1div2);
10221
+ while (!Fp.eql(t, Fp.ONE)) {
10222
+ if (Fp.is0(t))
10223
+ return Fp.ZERO;
10224
+ let i = 1;
10225
+ let t_tmp = Fp.sqr(t);
10226
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
10227
+ i++;
10228
+ t_tmp = Fp.sqr(t_tmp);
10229
+ if (i === M)
10230
+ throw new Error("Cannot find square root");
10231
+ }
10232
+ const exponent = _1n2 << BigInt(M - i - 1);
10233
+ const b = Fp.pow(c, exponent);
10234
+ M = i;
10235
+ c = Fp.sqr(b);
10236
+ t = Fp.mul(t, c);
10237
+ R = Fp.mul(R, b);
10238
+ }
10239
+ return R;
10240
+ };
10241
+ }
10242
+ function FpSqrt(P) {
10243
+ if (P % _4n === _3n)
10244
+ return sqrt3mod4;
10245
+ if (P % _8n === _5n)
10246
+ return sqrt5mod8;
10247
+ if (P % _16n === _9n)
10248
+ return sqrt9mod16(P);
10249
+ return tonelliShanks(P);
10250
+ }
10251
+ var FIELD_FIELDS = [
10252
+ "create",
10253
+ "isValid",
10254
+ "is0",
10255
+ "neg",
10256
+ "inv",
10257
+ "sqrt",
10258
+ "sqr",
10259
+ "eql",
10260
+ "add",
10261
+ "sub",
10262
+ "mul",
10263
+ "pow",
10264
+ "div",
10265
+ "addN",
10266
+ "subN",
10267
+ "mulN",
10268
+ "sqrN"
10269
+ ];
10270
+ function validateField(field) {
10271
+ const initial = {
10272
+ ORDER: "bigint",
10273
+ BYTES: "number",
10274
+ BITS: "number"
10275
+ };
10276
+ const opts = FIELD_FIELDS.reduce((map, val) => {
10277
+ map[val] = "function";
10278
+ return map;
10279
+ }, initial);
10280
+ validateObject(field, opts);
10281
+ return field;
10282
+ }
10283
+ function FpPow(Fp, num, power) {
10284
+ if (power < _0n2)
10285
+ throw new Error("invalid exponent, negatives unsupported");
10286
+ if (power === _0n2)
10287
+ return Fp.ONE;
10288
+ if (power === _1n2)
10289
+ return num;
10290
+ let p = Fp.ONE;
10291
+ let d = num;
10292
+ while (power > _0n2) {
10293
+ if (power & _1n2)
10294
+ p = Fp.mul(p, d);
10295
+ d = Fp.sqr(d);
10296
+ power >>= _1n2;
10297
+ }
10298
+ return p;
10299
+ }
10300
+ function FpInvertBatch(Fp, nums, passZero = false) {
10301
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
10302
+ const multipliedAcc = nums.reduce((acc, num, i) => {
10303
+ if (Fp.is0(num))
10304
+ return acc;
10305
+ inverted[i] = acc;
10306
+ return Fp.mul(acc, num);
10307
+ }, Fp.ONE);
10308
+ const invertedAcc = Fp.inv(multipliedAcc);
10309
+ nums.reduceRight((acc, num, i) => {
10310
+ if (Fp.is0(num))
10311
+ return acc;
10312
+ inverted[i] = Fp.mul(acc, inverted[i]);
10313
+ return Fp.mul(acc, num);
10314
+ }, invertedAcc);
10315
+ return inverted;
10316
+ }
10317
+ function FpLegendre(Fp, n) {
10318
+ const p1mod2 = (Fp.ORDER - _1n2) / _2n;
10319
+ const powered = Fp.pow(n, p1mod2);
10320
+ const yes = Fp.eql(powered, Fp.ONE);
10321
+ const zero = Fp.eql(powered, Fp.ZERO);
10322
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
10323
+ if (!yes && !zero && !no)
10324
+ throw new Error("invalid Legendre symbol result");
10325
+ return yes ? 1 : zero ? 0 : -1;
10326
+ }
10327
+ function nLength(n, nBitLength) {
10328
+ if (nBitLength !== void 0)
10329
+ anumber(nBitLength);
10330
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
10331
+ const nByteLength = Math.ceil(_nBitLength / 8);
10332
+ return { nBitLength: _nBitLength, nByteLength };
10333
+ }
10334
+ var _Field = class {
10335
+ ORDER;
10336
+ BITS;
10337
+ BYTES;
10338
+ isLE;
10339
+ ZERO = _0n2;
10340
+ ONE = _1n2;
10341
+ _lengths;
10342
+ _sqrt;
10343
+ // cached sqrt
10344
+ _mod;
10345
+ constructor(ORDER, opts = {}) {
10346
+ if (ORDER <= _0n2)
10347
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
10348
+ let _nbitLength = void 0;
10349
+ this.isLE = false;
10350
+ if (opts != null && typeof opts === "object") {
10351
+ if (typeof opts.BITS === "number")
10352
+ _nbitLength = opts.BITS;
10353
+ if (typeof opts.sqrt === "function")
10354
+ this.sqrt = opts.sqrt;
10355
+ if (typeof opts.isLE === "boolean")
10356
+ this.isLE = opts.isLE;
10357
+ if (opts.allowedLengths)
10358
+ this._lengths = opts.allowedLengths?.slice();
10359
+ if (typeof opts.modFromBytes === "boolean")
10360
+ this._mod = opts.modFromBytes;
10361
+ }
10362
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
10363
+ if (nByteLength > 2048)
10364
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
10365
+ this.ORDER = ORDER;
10366
+ this.BITS = nBitLength;
10367
+ this.BYTES = nByteLength;
10368
+ this._sqrt = void 0;
10369
+ Object.preventExtensions(this);
10370
+ }
10371
+ create(num) {
10372
+ return mod(num, this.ORDER);
10373
+ }
10374
+ isValid(num) {
10375
+ if (typeof num !== "bigint")
10376
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
10377
+ return _0n2 <= num && num < this.ORDER;
10378
+ }
10379
+ is0(num) {
10380
+ return num === _0n2;
10381
+ }
10382
+ // is valid and invertible
10383
+ isValidNot0(num) {
10384
+ return !this.is0(num) && this.isValid(num);
10385
+ }
10386
+ isOdd(num) {
10387
+ return (num & _1n2) === _1n2;
10388
+ }
10389
+ neg(num) {
10390
+ return mod(-num, this.ORDER);
10391
+ }
10392
+ eql(lhs, rhs) {
10393
+ return lhs === rhs;
10394
+ }
10395
+ sqr(num) {
10396
+ return mod(num * num, this.ORDER);
10397
+ }
10398
+ add(lhs, rhs) {
10399
+ return mod(lhs + rhs, this.ORDER);
10400
+ }
10401
+ sub(lhs, rhs) {
10402
+ return mod(lhs - rhs, this.ORDER);
10403
+ }
10404
+ mul(lhs, rhs) {
10405
+ return mod(lhs * rhs, this.ORDER);
10406
+ }
10407
+ pow(num, power) {
10408
+ return FpPow(this, num, power);
10409
+ }
10410
+ div(lhs, rhs) {
10411
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
10412
+ }
10413
+ // Same as above, but doesn't normalize
10414
+ sqrN(num) {
10415
+ return num * num;
10416
+ }
10417
+ addN(lhs, rhs) {
10418
+ return lhs + rhs;
10419
+ }
10420
+ subN(lhs, rhs) {
10421
+ return lhs - rhs;
10422
+ }
10423
+ mulN(lhs, rhs) {
10424
+ return lhs * rhs;
10425
+ }
10426
+ inv(num) {
10427
+ return invert(num, this.ORDER);
10428
+ }
10429
+ sqrt(num) {
10430
+ if (!this._sqrt)
10431
+ this._sqrt = FpSqrt(this.ORDER);
10432
+ return this._sqrt(this, num);
10433
+ }
10434
+ toBytes(num) {
10435
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
10436
+ }
10437
+ fromBytes(bytes, skipValidation = false) {
10438
+ abytes(bytes);
10439
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
10440
+ if (allowedLengths) {
10441
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
10442
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
10443
+ }
10444
+ const padded = new Uint8Array(BYTES);
10445
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
10446
+ bytes = padded;
10447
+ }
10448
+ if (bytes.length !== BYTES)
10449
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
10450
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
10451
+ if (modFromBytes)
10452
+ scalar = mod(scalar, ORDER);
10453
+ if (!skipValidation) {
10454
+ if (!this.isValid(scalar))
10455
+ throw new Error("invalid field element: outside of range 0..ORDER");
10456
+ }
10457
+ return scalar;
10458
+ }
10459
+ // TODO: we don't need it here, move out to separate fn
10460
+ invertBatch(lst) {
10461
+ return FpInvertBatch(this, lst);
10462
+ }
10463
+ // We can't move this out because Fp6, Fp12 implement it
10464
+ // and it's unclear what to return in there.
10465
+ cmov(a, b, condition) {
10466
+ return condition ? b : a;
10467
+ }
10468
+ };
10469
+ function Field(ORDER, opts = {}) {
10470
+ return new _Field(ORDER, opts);
10471
+ }
10472
+ function getFieldBytesLength(fieldOrder) {
10473
+ if (typeof fieldOrder !== "bigint")
10474
+ throw new Error("field order must be bigint");
10475
+ const bitLength = fieldOrder.toString(2).length;
10476
+ return Math.ceil(bitLength / 8);
10477
+ }
10478
+ function getMinHashLength(fieldOrder) {
10479
+ const length = getFieldBytesLength(fieldOrder);
10480
+ return length + Math.ceil(length / 2);
10481
+ }
10482
+ function mapHashToField(key, fieldOrder, isLE = false) {
10483
+ abytes(key);
10484
+ const len = key.length;
10485
+ const fieldLen = getFieldBytesLength(fieldOrder);
10486
+ const minLen = getMinHashLength(fieldOrder);
10487
+ if (len < 16 || len < minLen || len > 1024)
10488
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
10489
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
10490
+ const reduced = mod(num, fieldOrder - _1n2) + _1n2;
10491
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
10492
+ }
10493
+
10494
+ // node_modules/@noble/curves/abstract/curve.js
10495
+ var _0n3 = /* @__PURE__ */ BigInt(0);
10496
+ var _1n3 = /* @__PURE__ */ BigInt(1);
10497
+ function negateCt(condition, item) {
10498
+ const neg = item.negate();
10499
+ return condition ? neg : item;
10500
+ }
10501
+ function normalizeZ(c, points) {
10502
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
10503
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
10504
+ }
10505
+ function validateW(W, bits) {
10506
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
10507
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
10508
+ }
10509
+ function calcWOpts(W, scalarBits) {
10510
+ validateW(W, scalarBits);
10511
+ const windows = Math.ceil(scalarBits / W) + 1;
10512
+ const windowSize = 2 ** (W - 1);
10513
+ const maxNumber = 2 ** W;
10514
+ const mask = bitMask(W);
10515
+ const shiftBy = BigInt(W);
10516
+ return { windows, windowSize, mask, maxNumber, shiftBy };
10517
+ }
10518
+ function calcOffsets(n, window, wOpts) {
10519
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
10520
+ let wbits = Number(n & mask);
10521
+ let nextN = n >> shiftBy;
10522
+ if (wbits > windowSize) {
10523
+ wbits -= maxNumber;
10524
+ nextN += _1n3;
10525
+ }
10526
+ const offsetStart = window * windowSize;
10527
+ const offset = offsetStart + Math.abs(wbits) - 1;
10528
+ const isZero = wbits === 0;
10529
+ const isNeg = wbits < 0;
10530
+ const isNegF = window % 2 !== 0;
10531
+ const offsetF = offsetStart;
10532
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
10533
+ }
10534
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
10535
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
10536
+ function getW(P) {
10537
+ return pointWindowSizes.get(P) || 1;
10538
+ }
10539
+ function assert0(n) {
10540
+ if (n !== _0n3)
10541
+ throw new Error("invalid wNAF");
10542
+ }
10543
+ var wNAF = class {
10544
+ BASE;
10545
+ ZERO;
10546
+ Fn;
10547
+ bits;
10548
+ // Parametrized with a given Point class (not individual point)
10549
+ constructor(Point, bits) {
10550
+ this.BASE = Point.BASE;
10551
+ this.ZERO = Point.ZERO;
10552
+ this.Fn = Point.Fn;
10553
+ this.bits = bits;
10554
+ }
10555
+ // non-const time multiplication ladder
10556
+ _unsafeLadder(elm, n, p = this.ZERO) {
10557
+ let d = elm;
10558
+ while (n > _0n3) {
10559
+ if (n & _1n3)
10560
+ p = p.add(d);
10561
+ d = d.double();
10562
+ n >>= _1n3;
10563
+ }
10564
+ return p;
10565
+ }
10566
+ /**
10567
+ * Creates a wNAF precomputation window. Used for caching.
10568
+ * Default window size is set by `utils.precompute()` and is equal to 8.
10569
+ * Number of precomputed points depends on the curve size:
10570
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
10571
+ * - 𝑊 is the window size
10572
+ * - 𝑛 is the bitlength of the curve order.
10573
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
10574
+ * @param point Point instance
10575
+ * @param W window size
10576
+ * @returns precomputed point tables flattened to a single array
10577
+ */
10578
+ precomputeWindow(point, W) {
10579
+ const { windows, windowSize } = calcWOpts(W, this.bits);
10580
+ const points = [];
10581
+ let p = point;
10582
+ let base = p;
10583
+ for (let window = 0; window < windows; window++) {
10584
+ base = p;
10585
+ points.push(base);
10586
+ for (let i = 1; i < windowSize; i++) {
10587
+ base = base.add(p);
10588
+ points.push(base);
10589
+ }
10590
+ p = base.double();
10591
+ }
10592
+ return points;
10593
+ }
10594
+ /**
10595
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
10596
+ * More compact implementation:
10597
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
10598
+ * @returns real and fake (for const-time) points
10599
+ */
10600
+ wNAF(W, precomputes, n) {
10601
+ if (!this.Fn.isValid(n))
10602
+ throw new Error("invalid scalar");
10603
+ let p = this.ZERO;
10604
+ let f = this.BASE;
10605
+ const wo = calcWOpts(W, this.bits);
10606
+ for (let window = 0; window < wo.windows; window++) {
10607
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
10608
+ n = nextN;
10609
+ if (isZero) {
10610
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
10611
+ } else {
10612
+ p = p.add(negateCt(isNeg, precomputes[offset]));
10613
+ }
10614
+ }
10615
+ assert0(n);
10616
+ return { p, f };
10617
+ }
10618
+ /**
10619
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
10620
+ * @param acc accumulator point to add result of multiplication
10621
+ * @returns point
10622
+ */
10623
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
10624
+ const wo = calcWOpts(W, this.bits);
10625
+ for (let window = 0; window < wo.windows; window++) {
10626
+ if (n === _0n3)
10627
+ break;
10628
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
10629
+ n = nextN;
10630
+ if (isZero) {
10631
+ continue;
10632
+ } else {
10633
+ const item = precomputes[offset];
10634
+ acc = acc.add(isNeg ? item.negate() : item);
10635
+ }
10636
+ }
10637
+ assert0(n);
10638
+ return acc;
10639
+ }
10640
+ getPrecomputes(W, point, transform) {
10641
+ let comp = pointPrecomputes.get(point);
10642
+ if (!comp) {
10643
+ comp = this.precomputeWindow(point, W);
10644
+ if (W !== 1) {
10645
+ if (typeof transform === "function")
10646
+ comp = transform(comp);
10647
+ pointPrecomputes.set(point, comp);
10648
+ }
10649
+ }
10650
+ return comp;
10651
+ }
10652
+ cached(point, scalar, transform) {
10653
+ const W = getW(point);
10654
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
10655
+ }
10656
+ unsafe(point, scalar, transform, prev) {
10657
+ const W = getW(point);
10658
+ if (W === 1)
10659
+ return this._unsafeLadder(point, scalar, prev);
10660
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
10661
+ }
10662
+ // We calculate precomputes for elliptic curve point multiplication
10663
+ // using windowed method. This specifies window size and
10664
+ // stores precomputed values. Usually only base point would be precomputed.
10665
+ createCache(P, W) {
10666
+ validateW(W, this.bits);
10667
+ pointWindowSizes.set(P, W);
10668
+ pointPrecomputes.delete(P);
10669
+ }
10670
+ hasCache(elm) {
10671
+ return getW(elm) !== 1;
10672
+ }
10673
+ };
10674
+ function mulEndoUnsafe(Point, point, k1, k2) {
10675
+ let acc = point;
10676
+ let p1 = Point.ZERO;
10677
+ let p2 = Point.ZERO;
10678
+ while (k1 > _0n3 || k2 > _0n3) {
10679
+ if (k1 & _1n3)
10680
+ p1 = p1.add(acc);
10681
+ if (k2 & _1n3)
10682
+ p2 = p2.add(acc);
10683
+ acc = acc.double();
10684
+ k1 >>= _1n3;
10685
+ k2 >>= _1n3;
10686
+ }
10687
+ return { p1, p2 };
10688
+ }
10689
+ function createField(order, field, isLE) {
10690
+ if (field) {
10691
+ if (field.ORDER !== order)
10692
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
10693
+ validateField(field);
10694
+ return field;
10695
+ } else {
10696
+ return Field(order, { isLE });
10697
+ }
10698
+ }
10699
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
10700
+ if (FpFnLE === void 0)
10701
+ FpFnLE = type === "edwards";
10702
+ if (!CURVE || typeof CURVE !== "object")
10703
+ throw new Error(`expected valid ${type} CURVE object`);
10704
+ for (const p of ["p", "n", "h"]) {
10705
+ const val = CURVE[p];
10706
+ if (!(typeof val === "bigint" && val > _0n3))
10707
+ throw new Error(`CURVE.${p} must be positive bigint`);
10708
+ }
10709
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
10710
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
10711
+ const _b = type === "weierstrass" ? "b" : "d";
10712
+ const params = ["Gx", "Gy", "a", _b];
10713
+ for (const p of params) {
10714
+ if (!Fp.isValid(CURVE[p]))
10715
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
10716
+ }
10717
+ CURVE = Object.freeze(Object.assign({}, CURVE));
10718
+ return { CURVE, Fp, Fn };
10719
+ }
10720
+ function createKeygen(randomSecretKey, getPublicKey2) {
10721
+ return function keygen(seed) {
10722
+ const secretKey = randomSecretKey(seed);
10723
+ return { secretKey, publicKey: getPublicKey2(secretKey) };
10724
+ };
10725
+ }
10726
+
10727
+ // node_modules/@noble/hashes/hmac.js
10728
+ var _HMAC = class {
10729
+ oHash;
10730
+ iHash;
10731
+ blockLen;
10732
+ outputLen;
10733
+ finished = false;
10734
+ destroyed = false;
10735
+ constructor(hash, key) {
10736
+ ahash(hash);
10737
+ abytes(key, void 0, "key");
10738
+ this.iHash = hash.create();
10739
+ if (typeof this.iHash.update !== "function")
10740
+ throw new Error("Expected instance of class which extends utils.Hash");
10741
+ this.blockLen = this.iHash.blockLen;
10742
+ this.outputLen = this.iHash.outputLen;
10743
+ const blockLen = this.blockLen;
10744
+ const pad = new Uint8Array(blockLen);
10745
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
10746
+ for (let i = 0; i < pad.length; i++)
10747
+ pad[i] ^= 54;
10748
+ this.iHash.update(pad);
10749
+ this.oHash = hash.create();
10750
+ for (let i = 0; i < pad.length; i++)
10751
+ pad[i] ^= 54 ^ 92;
10752
+ this.oHash.update(pad);
10753
+ clean(pad);
10754
+ }
10755
+ update(buf) {
10756
+ aexists(this);
10757
+ this.iHash.update(buf);
10758
+ return this;
10759
+ }
10760
+ digestInto(out) {
10761
+ aexists(this);
10762
+ abytes(out, this.outputLen, "output");
10763
+ this.finished = true;
10764
+ this.iHash.digestInto(out);
10765
+ this.oHash.update(out);
10766
+ this.oHash.digestInto(out);
10767
+ this.destroy();
10768
+ }
10769
+ digest() {
10770
+ const out = new Uint8Array(this.oHash.outputLen);
10771
+ this.digestInto(out);
10772
+ return out;
10773
+ }
10774
+ _cloneInto(to) {
10775
+ to ||= Object.create(Object.getPrototypeOf(this), {});
10776
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
10777
+ to = to;
10778
+ to.finished = finished;
10779
+ to.destroyed = destroyed;
10780
+ to.blockLen = blockLen;
10781
+ to.outputLen = outputLen;
10782
+ to.oHash = oHash._cloneInto(to.oHash);
10783
+ to.iHash = iHash._cloneInto(to.iHash);
10784
+ return to;
10785
+ }
10786
+ clone() {
10787
+ return this._cloneInto();
10788
+ }
10789
+ destroy() {
10790
+ this.destroyed = true;
10791
+ this.oHash.destroy();
10792
+ this.iHash.destroy();
10793
+ }
10794
+ };
10795
+ var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
10796
+ hmac.create = (hash, key) => new _HMAC(hash, key);
10797
+
10798
+ // node_modules/@noble/curves/abstract/weierstrass.js
10799
+ var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
10800
+ function _splitEndoScalar(k, basis, n) {
10801
+ const [[a1, b1], [a2, b2]] = basis;
10802
+ const c1 = divNearest(b2 * k, n);
10803
+ const c2 = divNearest(-b1 * k, n);
10804
+ let k1 = k - c1 * a1 - c2 * a2;
10805
+ let k2 = -c1 * b1 - c2 * b2;
10806
+ const k1neg = k1 < _0n4;
10807
+ const k2neg = k2 < _0n4;
10808
+ if (k1neg)
10809
+ k1 = -k1;
10810
+ if (k2neg)
10811
+ k2 = -k2;
10812
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
10813
+ if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
10814
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
10815
+ }
10816
+ return { k1neg, k1, k2neg, k2 };
10817
+ }
10818
+ function validateSigFormat(format) {
10819
+ if (!["compact", "recovered", "der"].includes(format))
10820
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
10821
+ return format;
10822
+ }
10823
+ function validateSigOpts(opts, def) {
10824
+ const optsn = {};
10825
+ for (let optName of Object.keys(def)) {
10826
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
10827
+ }
10828
+ abool(optsn.lowS, "lowS");
10829
+ abool(optsn.prehash, "prehash");
10830
+ if (optsn.format !== void 0)
10831
+ validateSigFormat(optsn.format);
10832
+ return optsn;
10833
+ }
10834
+ var DERErr = class extends Error {
10835
+ constructor(m = "") {
10836
+ super(m);
10837
+ }
10838
+ };
10839
+ var DER = {
10840
+ // asn.1 DER encoding utils
10841
+ Err: DERErr,
10842
+ // Basic building block is TLV (Tag-Length-Value)
10843
+ _tlv: {
10844
+ encode: (tag, data) => {
10845
+ const { Err: E } = DER;
10846
+ if (tag < 0 || tag > 256)
10847
+ throw new E("tlv.encode: wrong tag");
10848
+ if (data.length & 1)
10849
+ throw new E("tlv.encode: unpadded data");
10850
+ const dataLen = data.length / 2;
10851
+ const len = numberToHexUnpadded(dataLen);
10852
+ if (len.length / 2 & 128)
10853
+ throw new E("tlv.encode: long form length too big");
10854
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
10855
+ const t = numberToHexUnpadded(tag);
10856
+ return t + lenLen + len + data;
10857
+ },
10858
+ // v - value, l - left bytes (unparsed)
10859
+ decode(tag, data) {
10860
+ const { Err: E } = DER;
10861
+ let pos = 0;
10862
+ if (tag < 0 || tag > 256)
10863
+ throw new E("tlv.encode: wrong tag");
10864
+ if (data.length < 2 || data[pos++] !== tag)
10865
+ throw new E("tlv.decode: wrong tlv");
10866
+ const first = data[pos++];
10867
+ const isLong = !!(first & 128);
10868
+ let length = 0;
10869
+ if (!isLong)
10870
+ length = first;
10871
+ else {
10872
+ const lenLen = first & 127;
10873
+ if (!lenLen)
10874
+ throw new E("tlv.decode(long): indefinite length not supported");
10875
+ if (lenLen > 4)
10876
+ throw new E("tlv.decode(long): byte length is too big");
10877
+ const lengthBytes = data.subarray(pos, pos + lenLen);
10878
+ if (lengthBytes.length !== lenLen)
10879
+ throw new E("tlv.decode: length bytes not complete");
10880
+ if (lengthBytes[0] === 0)
10881
+ throw new E("tlv.decode(long): zero leftmost byte");
10882
+ for (const b of lengthBytes)
10883
+ length = length << 8 | b;
10884
+ pos += lenLen;
10885
+ if (length < 128)
10886
+ throw new E("tlv.decode(long): not minimal encoding");
10887
+ }
10888
+ const v = data.subarray(pos, pos + length);
10889
+ if (v.length !== length)
10890
+ throw new E("tlv.decode: wrong value length");
10891
+ return { v, l: data.subarray(pos + length) };
10892
+ }
10893
+ },
10894
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
10895
+ // since we always use positive integers here. It must always be empty:
10896
+ // - add zero byte if exists
10897
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
10898
+ _int: {
10899
+ encode(num) {
10900
+ const { Err: E } = DER;
10901
+ if (num < _0n4)
10902
+ throw new E("integer: negative integers are not allowed");
10903
+ let hex = numberToHexUnpadded(num);
10904
+ if (Number.parseInt(hex[0], 16) & 8)
10905
+ hex = "00" + hex;
10906
+ if (hex.length & 1)
10907
+ throw new E("unexpected DER parsing assertion: unpadded hex");
10908
+ return hex;
10909
+ },
10910
+ decode(data) {
10911
+ const { Err: E } = DER;
10912
+ if (data[0] & 128)
10913
+ throw new E("invalid signature integer: negative");
10914
+ if (data[0] === 0 && !(data[1] & 128))
10915
+ throw new E("invalid signature integer: unnecessary leading zero");
10916
+ return bytesToNumberBE(data);
10917
+ }
10918
+ },
10919
+ toSig(bytes) {
10920
+ const { Err: E, _int: int, _tlv: tlv } = DER;
10921
+ const data = abytes(bytes, void 0, "signature");
10922
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
10923
+ if (seqLeftBytes.length)
10924
+ throw new E("invalid signature: left bytes after parsing");
10925
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
10926
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
10927
+ if (sLeftBytes.length)
10928
+ throw new E("invalid signature: left bytes after parsing");
10929
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
10930
+ },
10931
+ hexFromSig(sig) {
10932
+ const { _tlv: tlv, _int: int } = DER;
10933
+ const rs = tlv.encode(2, int.encode(sig.r));
10934
+ const ss = tlv.encode(2, int.encode(sig.s));
10935
+ const seq = rs + ss;
10936
+ return tlv.encode(48, seq);
10937
+ }
10938
+ };
10939
+ var _0n4 = BigInt(0);
10940
+ var _1n4 = BigInt(1);
10941
+ var _2n2 = BigInt(2);
10942
+ var _3n2 = BigInt(3);
10943
+ var _4n2 = BigInt(4);
10944
+ function weierstrass(params, extraOpts = {}) {
10945
+ const validated = createCurveFields("weierstrass", params, extraOpts);
10946
+ const { Fp, Fn } = validated;
10947
+ let CURVE = validated.CURVE;
10948
+ const { h: cofactor, n: CURVE_ORDER2 } = CURVE;
10949
+ validateObject(extraOpts, {}, {
10950
+ allowInfinityPoint: "boolean",
10951
+ clearCofactor: "function",
10952
+ isTorsionFree: "function",
10953
+ fromBytes: "function",
10954
+ toBytes: "function",
10955
+ endo: "object"
10956
+ });
10957
+ const { endo } = extraOpts;
10958
+ if (endo) {
10959
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
10960
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
10961
+ }
10962
+ }
10963
+ const lengths = getWLengths(Fp, Fn);
10964
+ function assertCompressionIsSupported() {
10965
+ if (!Fp.isOdd)
10966
+ throw new Error("compression is not supported: Field does not have .isOdd()");
10967
+ }
10968
+ function pointToBytes(_c, point, isCompressed) {
10969
+ const { x, y } = point.toAffine();
10970
+ const bx = Fp.toBytes(x);
10971
+ abool(isCompressed, "isCompressed");
10972
+ if (isCompressed) {
10973
+ assertCompressionIsSupported();
10974
+ const hasEvenY = !Fp.isOdd(y);
10975
+ return concatBytes(pprefix(hasEvenY), bx);
10976
+ } else {
10977
+ return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
10978
+ }
10979
+ }
10980
+ function pointFromBytes(bytes) {
10981
+ abytes(bytes, void 0, "Point");
10982
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
10983
+ const length = bytes.length;
10984
+ const head = bytes[0];
10985
+ const tail = bytes.subarray(1);
10986
+ if (length === comp && (head === 2 || head === 3)) {
10987
+ const x = Fp.fromBytes(tail);
10988
+ if (!Fp.isValid(x))
10989
+ throw new Error("bad point: is not on curve, wrong x");
10990
+ const y2 = weierstrassEquation(x);
10991
+ let y;
10992
+ try {
10993
+ y = Fp.sqrt(y2);
10994
+ } catch (sqrtError) {
10995
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
10996
+ throw new Error("bad point: is not on curve, sqrt error" + err);
10997
+ }
10998
+ assertCompressionIsSupported();
10999
+ const evenY = Fp.isOdd(y);
11000
+ const evenH = (head & 1) === 1;
11001
+ if (evenH !== evenY)
11002
+ y = Fp.neg(y);
11003
+ return { x, y };
11004
+ } else if (length === uncomp && head === 4) {
11005
+ const L = Fp.BYTES;
11006
+ const x = Fp.fromBytes(tail.subarray(0, L));
11007
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
11008
+ if (!isValidXY(x, y))
11009
+ throw new Error("bad point: is not on curve");
11010
+ return { x, y };
11011
+ } else {
11012
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
11013
+ }
11014
+ }
11015
+ const encodePoint = extraOpts.toBytes || pointToBytes;
11016
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
11017
+ function weierstrassEquation(x) {
11018
+ const x2 = Fp.sqr(x);
11019
+ const x3 = Fp.mul(x2, x);
11020
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
11021
+ }
11022
+ function isValidXY(x, y) {
11023
+ const left = Fp.sqr(y);
11024
+ const right = weierstrassEquation(x);
11025
+ return Fp.eql(left, right);
11026
+ }
11027
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
11028
+ throw new Error("bad curve params: generator point");
11029
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
11030
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
11031
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
11032
+ throw new Error("bad curve params: a or b");
11033
+ function acoord(title, n, banZero = false) {
11034
+ if (!Fp.isValid(n) || banZero && Fp.is0(n))
11035
+ throw new Error(`bad point coordinate ${title}`);
11036
+ return n;
11037
+ }
11038
+ function aprjpoint(other) {
11039
+ if (!(other instanceof Point))
11040
+ throw new Error("Weierstrass Point expected");
11041
+ }
11042
+ function splitEndoScalarN(k) {
11043
+ if (!endo || !endo.basises)
11044
+ throw new Error("no endo");
11045
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
11046
+ }
11047
+ const toAffineMemo = memoized((p, iz) => {
11048
+ const { X, Y, Z } = p;
11049
+ if (Fp.eql(Z, Fp.ONE))
11050
+ return { x: X, y: Y };
11051
+ const is0 = p.is0();
11052
+ if (iz == null)
11053
+ iz = is0 ? Fp.ONE : Fp.inv(Z);
11054
+ const x = Fp.mul(X, iz);
11055
+ const y = Fp.mul(Y, iz);
11056
+ const zz = Fp.mul(Z, iz);
11057
+ if (is0)
11058
+ return { x: Fp.ZERO, y: Fp.ZERO };
11059
+ if (!Fp.eql(zz, Fp.ONE))
11060
+ throw new Error("invZ was invalid");
11061
+ return { x, y };
11062
+ });
11063
+ const assertValidMemo = memoized((p) => {
11064
+ if (p.is0()) {
11065
+ if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
11066
+ return;
11067
+ throw new Error("bad point: ZERO");
11068
+ }
11069
+ const { x, y } = p.toAffine();
11070
+ if (!Fp.isValid(x) || !Fp.isValid(y))
11071
+ throw new Error("bad point: x or y not field elements");
11072
+ if (!isValidXY(x, y))
11073
+ throw new Error("bad point: equation left != right");
11074
+ if (!p.isTorsionFree())
11075
+ throw new Error("bad point: not in prime-order subgroup");
11076
+ return true;
11077
+ });
11078
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
11079
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
11080
+ k1p = negateCt(k1neg, k1p);
11081
+ k2p = negateCt(k2neg, k2p);
11082
+ return k1p.add(k2p);
11083
+ }
11084
+ class Point {
11085
+ // base / generator point
11086
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
11087
+ // zero / infinity / identity point
11088
+ static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
11089
+ // 0, 1, 0
11090
+ // math field
11091
+ static Fp = Fp;
11092
+ // scalar field
11093
+ static Fn = Fn;
11094
+ X;
11095
+ Y;
11096
+ Z;
11097
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
11098
+ constructor(X, Y, Z) {
11099
+ this.X = acoord("x", X);
11100
+ this.Y = acoord("y", Y, true);
11101
+ this.Z = acoord("z", Z);
11102
+ Object.freeze(this);
11103
+ }
11104
+ static CURVE() {
11105
+ return CURVE;
11106
+ }
11107
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
11108
+ static fromAffine(p) {
11109
+ const { x, y } = p || {};
11110
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
11111
+ throw new Error("invalid affine point");
11112
+ if (p instanceof Point)
11113
+ throw new Error("projective point not allowed");
11114
+ if (Fp.is0(x) && Fp.is0(y))
11115
+ return Point.ZERO;
11116
+ return new Point(x, y, Fp.ONE);
11117
+ }
11118
+ static fromBytes(bytes) {
11119
+ const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
11120
+ P.assertValidity();
11121
+ return P;
11122
+ }
11123
+ static fromHex(hex) {
11124
+ return Point.fromBytes(hexToBytes2(hex));
11125
+ }
11126
+ get x() {
11127
+ return this.toAffine().x;
11128
+ }
11129
+ get y() {
11130
+ return this.toAffine().y;
11131
+ }
11132
+ /**
11133
+ *
11134
+ * @param windowSize
11135
+ * @param isLazy true will defer table computation until the first multiplication
11136
+ * @returns
11137
+ */
11138
+ precompute(windowSize = 8, isLazy = true) {
11139
+ wnaf.createCache(this, windowSize);
11140
+ if (!isLazy)
11141
+ this.multiply(_3n2);
11142
+ return this;
11143
+ }
11144
+ // TODO: return `this`
11145
+ /** A point on curve is valid if it conforms to equation. */
11146
+ assertValidity() {
11147
+ assertValidMemo(this);
11148
+ }
11149
+ hasEvenY() {
11150
+ const { y } = this.toAffine();
11151
+ if (!Fp.isOdd)
11152
+ throw new Error("Field doesn't support isOdd");
11153
+ return !Fp.isOdd(y);
11154
+ }
11155
+ /** Compare one point to another. */
11156
+ equals(other) {
11157
+ aprjpoint(other);
11158
+ const { X: X1, Y: Y1, Z: Z1 } = this;
11159
+ const { X: X2, Y: Y2, Z: Z2 } = other;
11160
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
11161
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
11162
+ return U1 && U2;
11163
+ }
11164
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
11165
+ negate() {
11166
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
11167
+ }
11168
+ // Renes-Costello-Batina exception-free doubling formula.
11169
+ // There is 30% faster Jacobian formula, but it is not complete.
11170
+ // https://eprint.iacr.org/2015/1060, algorithm 3
11171
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
11172
+ double() {
11173
+ const { a, b } = CURVE;
11174
+ const b3 = Fp.mul(b, _3n2);
11175
+ const { X: X1, Y: Y1, Z: Z1 } = this;
11176
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
11177
+ let t0 = Fp.mul(X1, X1);
11178
+ let t1 = Fp.mul(Y1, Y1);
11179
+ let t2 = Fp.mul(Z1, Z1);
11180
+ let t3 = Fp.mul(X1, Y1);
11181
+ t3 = Fp.add(t3, t3);
11182
+ Z3 = Fp.mul(X1, Z1);
11183
+ Z3 = Fp.add(Z3, Z3);
11184
+ X3 = Fp.mul(a, Z3);
11185
+ Y3 = Fp.mul(b3, t2);
11186
+ Y3 = Fp.add(X3, Y3);
11187
+ X3 = Fp.sub(t1, Y3);
11188
+ Y3 = Fp.add(t1, Y3);
11189
+ Y3 = Fp.mul(X3, Y3);
11190
+ X3 = Fp.mul(t3, X3);
11191
+ Z3 = Fp.mul(b3, Z3);
11192
+ t2 = Fp.mul(a, t2);
11193
+ t3 = Fp.sub(t0, t2);
11194
+ t3 = Fp.mul(a, t3);
11195
+ t3 = Fp.add(t3, Z3);
11196
+ Z3 = Fp.add(t0, t0);
11197
+ t0 = Fp.add(Z3, t0);
11198
+ t0 = Fp.add(t0, t2);
11199
+ t0 = Fp.mul(t0, t3);
11200
+ Y3 = Fp.add(Y3, t0);
11201
+ t2 = Fp.mul(Y1, Z1);
11202
+ t2 = Fp.add(t2, t2);
11203
+ t0 = Fp.mul(t2, t3);
11204
+ X3 = Fp.sub(X3, t0);
11205
+ Z3 = Fp.mul(t2, t1);
11206
+ Z3 = Fp.add(Z3, Z3);
11207
+ Z3 = Fp.add(Z3, Z3);
11208
+ return new Point(X3, Y3, Z3);
11209
+ }
11210
+ // Renes-Costello-Batina exception-free addition formula.
11211
+ // There is 30% faster Jacobian formula, but it is not complete.
11212
+ // https://eprint.iacr.org/2015/1060, algorithm 1
11213
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
11214
+ add(other) {
11215
+ aprjpoint(other);
11216
+ const { X: X1, Y: Y1, Z: Z1 } = this;
11217
+ const { X: X2, Y: Y2, Z: Z2 } = other;
11218
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
11219
+ const a = CURVE.a;
11220
+ const b3 = Fp.mul(CURVE.b, _3n2);
11221
+ let t0 = Fp.mul(X1, X2);
11222
+ let t1 = Fp.mul(Y1, Y2);
11223
+ let t2 = Fp.mul(Z1, Z2);
11224
+ let t3 = Fp.add(X1, Y1);
11225
+ let t4 = Fp.add(X2, Y2);
11226
+ t3 = Fp.mul(t3, t4);
11227
+ t4 = Fp.add(t0, t1);
11228
+ t3 = Fp.sub(t3, t4);
11229
+ t4 = Fp.add(X1, Z1);
11230
+ let t5 = Fp.add(X2, Z2);
11231
+ t4 = Fp.mul(t4, t5);
11232
+ t5 = Fp.add(t0, t2);
11233
+ t4 = Fp.sub(t4, t5);
11234
+ t5 = Fp.add(Y1, Z1);
11235
+ X3 = Fp.add(Y2, Z2);
11236
+ t5 = Fp.mul(t5, X3);
11237
+ X3 = Fp.add(t1, t2);
11238
+ t5 = Fp.sub(t5, X3);
11239
+ Z3 = Fp.mul(a, t4);
11240
+ X3 = Fp.mul(b3, t2);
11241
+ Z3 = Fp.add(X3, Z3);
11242
+ X3 = Fp.sub(t1, Z3);
11243
+ Z3 = Fp.add(t1, Z3);
11244
+ Y3 = Fp.mul(X3, Z3);
11245
+ t1 = Fp.add(t0, t0);
11246
+ t1 = Fp.add(t1, t0);
11247
+ t2 = Fp.mul(a, t2);
11248
+ t4 = Fp.mul(b3, t4);
11249
+ t1 = Fp.add(t1, t2);
11250
+ t2 = Fp.sub(t0, t2);
11251
+ t2 = Fp.mul(a, t2);
11252
+ t4 = Fp.add(t4, t2);
11253
+ t0 = Fp.mul(t1, t4);
11254
+ Y3 = Fp.add(Y3, t0);
11255
+ t0 = Fp.mul(t5, t4);
11256
+ X3 = Fp.mul(t3, X3);
11257
+ X3 = Fp.sub(X3, t0);
11258
+ t0 = Fp.mul(t3, t1);
11259
+ Z3 = Fp.mul(t5, Z3);
11260
+ Z3 = Fp.add(Z3, t0);
11261
+ return new Point(X3, Y3, Z3);
11262
+ }
11263
+ subtract(other) {
11264
+ return this.add(other.negate());
11265
+ }
11266
+ is0() {
11267
+ return this.equals(Point.ZERO);
11268
+ }
11269
+ /**
11270
+ * Constant time multiplication.
11271
+ * Uses wNAF method. Windowed method may be 10% faster,
11272
+ * but takes 2x longer to generate and consumes 2x memory.
11273
+ * Uses precomputes when available.
11274
+ * Uses endomorphism for Koblitz curves.
11275
+ * @param scalar by which the point would be multiplied
11276
+ * @returns New point
11277
+ */
11278
+ multiply(scalar) {
11279
+ const { endo: endo2 } = extraOpts;
11280
+ if (!Fn.isValidNot0(scalar))
11281
+ throw new Error("invalid scalar: out of range");
11282
+ let point, fake;
11283
+ const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
11284
+ if (endo2) {
11285
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
11286
+ const { p: k1p, f: k1f } = mul(k1);
11287
+ const { p: k2p, f: k2f } = mul(k2);
11288
+ fake = k1f.add(k2f);
11289
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
11290
+ } else {
11291
+ const { p, f } = mul(scalar);
11292
+ point = p;
11293
+ fake = f;
11294
+ }
11295
+ return normalizeZ(Point, [point, fake])[0];
11296
+ }
11297
+ /**
11298
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
11299
+ * It's faster, but should only be used when you don't care about
11300
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
11301
+ */
11302
+ multiplyUnsafe(sc) {
11303
+ const { endo: endo2 } = extraOpts;
11304
+ const p = this;
11305
+ if (!Fn.isValid(sc))
11306
+ throw new Error("invalid scalar: out of range");
11307
+ if (sc === _0n4 || p.is0())
11308
+ return Point.ZERO;
11309
+ if (sc === _1n4)
11310
+ return p;
11311
+ if (wnaf.hasCache(this))
11312
+ return this.multiply(sc);
11313
+ if (endo2) {
11314
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
11315
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
11316
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
11317
+ } else {
11318
+ return wnaf.unsafe(p, sc);
11319
+ }
11320
+ }
11321
+ /**
11322
+ * Converts Projective point to affine (x, y) coordinates.
11323
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
11324
+ */
11325
+ toAffine(invertedZ) {
11326
+ return toAffineMemo(this, invertedZ);
11327
+ }
11328
+ /**
11329
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
11330
+ * Always torsion-free for cofactor=1 curves.
11331
+ */
11332
+ isTorsionFree() {
11333
+ const { isTorsionFree } = extraOpts;
11334
+ if (cofactor === _1n4)
11335
+ return true;
11336
+ if (isTorsionFree)
11337
+ return isTorsionFree(Point, this);
11338
+ return wnaf.unsafe(this, CURVE_ORDER2).is0();
11339
+ }
11340
+ clearCofactor() {
11341
+ const { clearCofactor } = extraOpts;
11342
+ if (cofactor === _1n4)
11343
+ return this;
11344
+ if (clearCofactor)
11345
+ return clearCofactor(Point, this);
11346
+ return this.multiplyUnsafe(cofactor);
11347
+ }
11348
+ isSmallOrder() {
11349
+ return this.multiplyUnsafe(cofactor).is0();
11350
+ }
11351
+ toBytes(isCompressed = true) {
11352
+ abool(isCompressed, "isCompressed");
11353
+ this.assertValidity();
11354
+ return encodePoint(Point, this, isCompressed);
11355
+ }
11356
+ toHex(isCompressed = true) {
11357
+ return bytesToHex4(this.toBytes(isCompressed));
11358
+ }
11359
+ toString() {
11360
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
11361
+ }
11362
+ }
11363
+ const bits = Fn.BITS;
11364
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
11365
+ Point.BASE.precompute(8);
11366
+ return Point;
11367
+ }
11368
+ function pprefix(hasEvenY) {
11369
+ return Uint8Array.of(hasEvenY ? 2 : 3);
11370
+ }
11371
+ function getWLengths(Fp, Fn) {
11372
+ return {
11373
+ secretKey: Fn.BYTES,
11374
+ publicKey: 1 + Fp.BYTES,
11375
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
11376
+ publicKeyHasPrefix: true,
11377
+ signature: 2 * Fn.BYTES
11378
+ };
11379
+ }
11380
+ function ecdh(Point, ecdhOpts = {}) {
11381
+ const { Fn } = Point;
11382
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
11383
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
11384
+ function isValidSecretKey(secretKey) {
11385
+ try {
11386
+ const num = Fn.fromBytes(secretKey);
11387
+ return Fn.isValidNot0(num);
11388
+ } catch (error) {
11389
+ return false;
11390
+ }
11391
+ }
11392
+ function isValidPublicKey(publicKey, isCompressed) {
11393
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
11394
+ try {
11395
+ const l = publicKey.length;
11396
+ if (isCompressed === true && l !== comp)
11397
+ return false;
11398
+ if (isCompressed === false && l !== publicKeyUncompressed)
11399
+ return false;
11400
+ return !!Point.fromBytes(publicKey);
11401
+ } catch (error) {
11402
+ return false;
11403
+ }
11404
+ }
11405
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
11406
+ return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
11407
+ }
11408
+ function getPublicKey2(secretKey, isCompressed = true) {
11409
+ return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
11410
+ }
11411
+ function isProbPub(item) {
11412
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
11413
+ if (!isBytes(item))
11414
+ return void 0;
11415
+ if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
11416
+ return void 0;
11417
+ const l = abytes(item, void 0, "key").length;
11418
+ return l === publicKey || l === publicKeyUncompressed;
11419
+ }
11420
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
11421
+ if (isProbPub(secretKeyA) === true)
11422
+ throw new Error("first arg must be private key");
11423
+ if (isProbPub(publicKeyB) === false)
11424
+ throw new Error("second arg must be public key");
11425
+ const s = Fn.fromBytes(secretKeyA);
11426
+ const b = Point.fromBytes(publicKeyB);
11427
+ return b.multiply(s).toBytes(isCompressed);
11428
+ }
11429
+ const utils = {
11430
+ isValidSecretKey,
11431
+ isValidPublicKey,
11432
+ randomSecretKey
11433
+ };
11434
+ const keygen = createKeygen(randomSecretKey, getPublicKey2);
11435
+ return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
11436
+ }
11437
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
11438
+ ahash(hash);
11439
+ validateObject(ecdsaOpts, {}, {
11440
+ hmac: "function",
11441
+ lowS: "boolean",
11442
+ randomBytes: "function",
11443
+ bits2int: "function",
11444
+ bits2int_modN: "function"
11445
+ });
11446
+ ecdsaOpts = Object.assign({}, ecdsaOpts);
11447
+ const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
11448
+ const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
11449
+ const { Fp, Fn } = Point;
11450
+ const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn;
11451
+ const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
11452
+ const defaultSigOpts = {
11453
+ prehash: true,
11454
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
11455
+ format: "compact",
11456
+ extraEntropy: false
11457
+ };
11458
+ const hasLargeCofactor = CURVE_ORDER2 * _2n2 < Fp.ORDER;
11459
+ function isBiggerThanHalfOrder(number) {
11460
+ const HALF = CURVE_ORDER2 >> _1n4;
11461
+ return number > HALF;
11462
+ }
11463
+ function validateRS(title, num) {
11464
+ if (!Fn.isValidNot0(num))
11465
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
11466
+ return num;
11467
+ }
11468
+ function assertSmallCofactor() {
11469
+ if (hasLargeCofactor)
11470
+ throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
11471
+ }
11472
+ function validateSigLength(bytes, format) {
11473
+ validateSigFormat(format);
11474
+ const size = lengths.signature;
11475
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
11476
+ return abytes(bytes, sizer);
11477
+ }
11478
+ class Signature {
11479
+ r;
11480
+ s;
11481
+ recovery;
11482
+ constructor(r, s, recovery) {
11483
+ this.r = validateRS("r", r);
11484
+ this.s = validateRS("s", s);
11485
+ if (recovery != null) {
11486
+ assertSmallCofactor();
11487
+ if (![0, 1, 2, 3].includes(recovery))
11488
+ throw new Error("invalid recovery id");
11489
+ this.recovery = recovery;
11490
+ }
11491
+ Object.freeze(this);
11492
+ }
11493
+ static fromBytes(bytes, format = defaultSigOpts.format) {
11494
+ validateSigLength(bytes, format);
11495
+ let recid;
11496
+ if (format === "der") {
11497
+ const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
11498
+ return new Signature(r2, s2);
11499
+ }
11500
+ if (format === "recovered") {
11501
+ recid = bytes[0];
11502
+ format = "compact";
11503
+ bytes = bytes.subarray(1);
11504
+ }
11505
+ const L = lengths.signature / 2;
11506
+ const r = bytes.subarray(0, L);
11507
+ const s = bytes.subarray(L, L * 2);
11508
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
11509
+ }
11510
+ static fromHex(hex, format) {
11511
+ return this.fromBytes(hexToBytes2(hex), format);
11512
+ }
11513
+ assertRecovery() {
11514
+ const { recovery } = this;
11515
+ if (recovery == null)
11516
+ throw new Error("invalid recovery id: must be present");
11517
+ return recovery;
11518
+ }
11519
+ addRecoveryBit(recovery) {
11520
+ return new Signature(this.r, this.s, recovery);
11521
+ }
11522
+ recoverPublicKey(messageHash) {
11523
+ const { r, s } = this;
11524
+ const recovery = this.assertRecovery();
11525
+ const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER2 : r;
11526
+ if (!Fp.isValid(radj))
11527
+ throw new Error("invalid recovery id: sig.r+curve.n != R.x");
11528
+ const x = Fp.toBytes(radj);
11529
+ const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
11530
+ const ir = Fn.inv(radj);
11531
+ const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
11532
+ const u1 = Fn.create(-h * ir);
11533
+ const u2 = Fn.create(s * ir);
11534
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
11535
+ if (Q.is0())
11536
+ throw new Error("invalid recovery: point at infinify");
11537
+ Q.assertValidity();
11538
+ return Q;
11539
+ }
11540
+ // Signatures should be low-s, to prevent malleability.
11541
+ hasHighS() {
11542
+ return isBiggerThanHalfOrder(this.s);
11543
+ }
11544
+ toBytes(format = defaultSigOpts.format) {
11545
+ validateSigFormat(format);
11546
+ if (format === "der")
11547
+ return hexToBytes2(DER.hexFromSig(this));
11548
+ const { r, s } = this;
11549
+ const rb = Fn.toBytes(r);
11550
+ const sb = Fn.toBytes(s);
11551
+ if (format === "recovered") {
11552
+ assertSmallCofactor();
11553
+ return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
11554
+ }
11555
+ return concatBytes(rb, sb);
11556
+ }
11557
+ toHex(format) {
11558
+ return bytesToHex4(this.toBytes(format));
11559
+ }
11560
+ }
11561
+ const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
11562
+ if (bytes.length > 8192)
11563
+ throw new Error("input is too large");
11564
+ const num = bytesToNumberBE(bytes);
11565
+ const delta = bytes.length * 8 - fnBits;
11566
+ return delta > 0 ? num >> BigInt(delta) : num;
11567
+ };
11568
+ const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
11569
+ return Fn.create(bits2int(bytes));
11570
+ };
11571
+ const ORDER_MASK = bitMask(fnBits);
11572
+ function int2octets(num) {
11573
+ aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
11574
+ return Fn.toBytes(num);
11575
+ }
11576
+ function validateMsgAndHash(message, prehash) {
11577
+ abytes(message, void 0, "message");
11578
+ return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
11579
+ }
11580
+ function prepSig(message, secretKey, opts) {
11581
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
11582
+ message = validateMsgAndHash(message, prehash);
11583
+ const h1int = bits2int_modN(message);
11584
+ const d = Fn.fromBytes(secretKey);
11585
+ if (!Fn.isValidNot0(d))
11586
+ throw new Error("invalid private key");
11587
+ const seedArgs = [int2octets(d), int2octets(h1int)];
11588
+ if (extraEntropy != null && extraEntropy !== false) {
11589
+ const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
11590
+ seedArgs.push(abytes(e, void 0, "extraEntropy"));
11591
+ }
11592
+ const seed = concatBytes(...seedArgs);
11593
+ const m = h1int;
11594
+ function k2sig(kBytes) {
11595
+ const k = bits2int(kBytes);
11596
+ if (!Fn.isValidNot0(k))
11597
+ return;
11598
+ const ik = Fn.inv(k);
11599
+ const q = Point.BASE.multiply(k).toAffine();
11600
+ const r = Fn.create(q.x);
11601
+ if (r === _0n4)
11602
+ return;
11603
+ const s = Fn.create(ik * Fn.create(m + r * d));
11604
+ if (s === _0n4)
11605
+ return;
11606
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
11607
+ let normS = s;
11608
+ if (lowS && isBiggerThanHalfOrder(s)) {
11609
+ normS = Fn.neg(s);
11610
+ recovery ^= 1;
11611
+ }
11612
+ return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
11613
+ }
11614
+ return { seed, k2sig };
11615
+ }
11616
+ function sign(message, secretKey, opts = {}) {
11617
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
11618
+ const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
11619
+ const sig = drbg(seed, k2sig);
11620
+ return sig.toBytes(opts.format);
11621
+ }
11622
+ function verify(signature, message, publicKey, opts = {}) {
11623
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
11624
+ publicKey = abytes(publicKey, void 0, "publicKey");
11625
+ message = validateMsgAndHash(message, prehash);
11626
+ if (!isBytes(signature)) {
11627
+ const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
11628
+ throw new Error("verify expects Uint8Array signature" + end);
11629
+ }
11630
+ validateSigLength(signature, format);
11631
+ try {
11632
+ const sig = Signature.fromBytes(signature, format);
11633
+ const P = Point.fromBytes(publicKey);
11634
+ if (lowS && sig.hasHighS())
11635
+ return false;
11636
+ const { r, s } = sig;
11637
+ const h = bits2int_modN(message);
11638
+ const is = Fn.inv(s);
11639
+ const u1 = Fn.create(h * is);
11640
+ const u2 = Fn.create(r * is);
11641
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
11642
+ if (R.is0())
11643
+ return false;
11644
+ const v = Fn.create(R.x);
11645
+ return v === r;
11646
+ } catch (e) {
11647
+ return false;
11648
+ }
11649
+ }
11650
+ function recoverPublicKey(signature, message, opts = {}) {
11651
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
11652
+ message = validateMsgAndHash(message, prehash);
11653
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
11654
+ }
11655
+ return Object.freeze({
11656
+ keygen,
11657
+ getPublicKey: getPublicKey2,
11658
+ getSharedSecret,
11659
+ utils,
11660
+ lengths,
11661
+ Point,
11662
+ sign,
11663
+ verify,
11664
+ recoverPublicKey,
11665
+ Signature,
11666
+ hash
11667
+ });
11668
+ }
11669
+
11670
+ // node_modules/@noble/curves/secp256k1.js
11671
+ var secp256k1_CURVE = {
11672
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
11673
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
11674
+ h: BigInt(1),
11675
+ a: BigInt(0),
11676
+ b: BigInt(7),
11677
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
11678
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
11679
+ };
11680
+ var secp256k1_ENDO = {
11681
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
11682
+ basises: [
11683
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
11684
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
11685
+ ]
11686
+ };
11687
+ var _2n3 = /* @__PURE__ */ BigInt(2);
11688
+ function sqrtMod(y) {
11689
+ const P = secp256k1_CURVE.p;
11690
+ const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
11691
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
11692
+ const b2 = y * y * y % P;
11693
+ const b3 = b2 * b2 * y % P;
11694
+ const b6 = pow2(b3, _3n3, P) * b3 % P;
11695
+ const b9 = pow2(b6, _3n3, P) * b3 % P;
11696
+ const b11 = pow2(b9, _2n3, P) * b2 % P;
11697
+ const b22 = pow2(b11, _11n, P) * b11 % P;
11698
+ const b44 = pow2(b22, _22n, P) * b22 % P;
11699
+ const b88 = pow2(b44, _44n, P) * b44 % P;
11700
+ const b176 = pow2(b88, _88n, P) * b88 % P;
11701
+ const b220 = pow2(b176, _44n, P) * b44 % P;
11702
+ const b223 = pow2(b220, _3n3, P) * b3 % P;
11703
+ const t1 = pow2(b223, _23n, P) * b22 % P;
11704
+ const t2 = pow2(t1, _6n, P) * b2 % P;
11705
+ const root = pow2(t2, _2n3, P);
11706
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
11707
+ throw new Error("Cannot find square root");
11708
+ return root;
11709
+ }
11710
+ var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
11711
+ var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
11712
+ Fp: Fpk1,
11713
+ endo: secp256k1_ENDO
11714
+ });
11715
+ var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha2564);
11716
+
11717
+ // modules/market/MarketModule.ts
11718
+ var DEFAULT_MARKET_API_URL = "https://market-api.unicity.network";
11719
+ function hexToBytes3(hex) {
11720
+ const len = hex.length >> 1;
11721
+ const bytes = new Uint8Array(len);
11722
+ for (let i = 0; i < len; i++) {
11723
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
11724
+ }
11725
+ return bytes;
11726
+ }
11727
+ function signRequest(body, privateKeyHex) {
11728
+ const timestamp = Date.now();
11729
+ const payload = JSON.stringify({ body, timestamp });
11730
+ const messageHash = sha2564(new TextEncoder().encode(payload));
11731
+ const privateKeyBytes = hexToBytes3(privateKeyHex);
11732
+ const signature = secp256k1.sign(messageHash, privateKeyBytes);
11733
+ const publicKey = bytesToHex4(secp256k1.getPublicKey(privateKeyBytes, true));
11734
+ return {
11735
+ body: JSON.stringify(body),
11736
+ headers: {
11737
+ "x-signature": bytesToHex4(signature),
11738
+ "x-public-key": publicKey,
11739
+ "x-timestamp": String(timestamp),
11740
+ "content-type": "application/json"
11741
+ }
11742
+ };
11743
+ }
11744
+ function toSnakeCaseIntent(req) {
11745
+ const result = {
11746
+ description: req.description,
11747
+ intent_type: req.intentType
11748
+ };
11749
+ if (req.category !== void 0) result.category = req.category;
11750
+ if (req.price !== void 0) result.price = req.price;
11751
+ if (req.currency !== void 0) result.currency = req.currency;
11752
+ if (req.location !== void 0) result.location = req.location;
11753
+ if (req.contactHandle !== void 0) result.contact_handle = req.contactHandle;
11754
+ if (req.expiresInDays !== void 0) result.expires_in_days = req.expiresInDays;
11755
+ return result;
11756
+ }
11757
+ function toSnakeCaseFilters(opts) {
11758
+ const result = {};
11759
+ if (opts?.filters) {
11760
+ const f = opts.filters;
11761
+ if (f.intentType !== void 0) result.intent_type = f.intentType;
11762
+ if (f.category !== void 0) result.category = f.category;
11763
+ if (f.minPrice !== void 0) result.min_price = f.minPrice;
11764
+ if (f.maxPrice !== void 0) result.max_price = f.maxPrice;
11765
+ if (f.location !== void 0) result.location = f.location;
11766
+ }
11767
+ if (opts?.limit !== void 0) result.limit = opts.limit;
11768
+ return result;
11769
+ }
11770
+ function mapSearchResult(raw) {
11771
+ return {
11772
+ id: raw.id,
11773
+ score: raw.score,
11774
+ agentNametag: raw.agent_nametag ?? void 0,
11775
+ agentPublicKey: raw.agent_public_key,
11776
+ description: raw.description,
11777
+ intentType: raw.intent_type,
11778
+ category: raw.category ?? void 0,
11779
+ price: raw.price ?? void 0,
11780
+ currency: raw.currency,
11781
+ location: raw.location ?? void 0,
11782
+ contactMethod: raw.contact_method,
11783
+ contactHandle: raw.contact_handle ?? void 0,
11784
+ createdAt: raw.created_at,
11785
+ expiresAt: raw.expires_at
11786
+ };
11787
+ }
11788
+ function mapMyIntent(raw) {
11789
+ return {
11790
+ id: raw.id,
11791
+ intentType: raw.intent_type,
11792
+ category: raw.category ?? void 0,
11793
+ price: raw.price ?? void 0,
11794
+ currency: raw.currency,
11795
+ location: raw.location ?? void 0,
11796
+ status: raw.status,
11797
+ createdAt: raw.created_at,
11798
+ expiresAt: raw.expires_at
11799
+ };
11800
+ }
11801
+ function mapFeedListing(raw) {
11802
+ return {
11803
+ id: raw.id,
11804
+ title: raw.title,
11805
+ descriptionPreview: raw.description_preview,
11806
+ agentName: raw.agent_name,
11807
+ agentId: raw.agent_id,
11808
+ type: raw.type,
11809
+ createdAt: raw.created_at
11810
+ };
11811
+ }
11812
+ function mapFeedMessage(raw) {
11813
+ if (raw.type === "initial") {
11814
+ return { type: "initial", listings: (raw.listings ?? []).map(mapFeedListing) };
11815
+ }
11816
+ return { type: "new", listing: mapFeedListing(raw.listing) };
11817
+ }
11818
+ var MarketModule = class {
11819
+ apiUrl;
11820
+ timeout;
11821
+ identity = null;
11822
+ registered = false;
11823
+ constructor(config) {
11824
+ this.apiUrl = (config?.apiUrl ?? DEFAULT_MARKET_API_URL).replace(/\/+$/, "");
11825
+ this.timeout = config?.timeout ?? 3e4;
11826
+ }
11827
+ /** Called by Sphere after construction */
11828
+ initialize(deps) {
11829
+ this.identity = deps.identity;
11830
+ }
11831
+ /** No-op — stateless module */
11832
+ async load() {
11833
+ }
11834
+ /** No-op — stateless module */
11835
+ destroy() {
11836
+ }
11837
+ // ---------------------------------------------------------------------------
11838
+ // Public API
11839
+ // ---------------------------------------------------------------------------
11840
+ /** Post a new intent (agent is auto-registered on first post) */
11841
+ async postIntent(intent) {
11842
+ const body = toSnakeCaseIntent(intent);
11843
+ const data = await this.apiPost("/api/intents", body);
11844
+ return {
11845
+ intentId: data.intent_id ?? data.intentId,
11846
+ message: data.message,
11847
+ expiresAt: data.expires_at ?? data.expiresAt
11848
+ };
11849
+ }
11850
+ /** Semantic search for intents (public — no auth required) */
11851
+ async search(query, opts) {
11852
+ const body = {
11853
+ query,
11854
+ ...toSnakeCaseFilters(opts)
11855
+ };
11856
+ const data = await this.apiPublicPost("/api/search", body);
11857
+ let results = (data.intents ?? []).map(mapSearchResult);
11858
+ const minScore = opts?.filters?.minScore;
11859
+ if (minScore != null) {
11860
+ results = results.filter((r) => Math.round(r.score * 100) >= Math.round(minScore * 100));
11861
+ }
11862
+ return { intents: results, count: results.length };
11863
+ }
11864
+ /** List own intents (authenticated) */
11865
+ async getMyIntents() {
11866
+ const data = await this.apiGet("/api/intents");
11867
+ return (data.intents ?? []).map(mapMyIntent);
11868
+ }
11869
+ /** Close (delete) an intent */
11870
+ async closeIntent(intentId) {
11871
+ await this.apiDelete(`/api/intents/${encodeURIComponent(intentId)}`);
11872
+ }
11873
+ /** Fetch the most recent listings via REST (public — no auth required) */
11874
+ async getRecentListings() {
11875
+ const res = await fetch(`${this.apiUrl}/api/feed/recent`, {
11876
+ signal: AbortSignal.timeout(this.timeout)
11877
+ });
11878
+ const data = await this.parseResponse(res);
11879
+ return (data.listings ?? []).map(mapFeedListing);
11880
+ }
11881
+ /**
11882
+ * Subscribe to the live listing feed via WebSocket.
11883
+ * Returns an unsubscribe function that closes the connection.
11884
+ *
11885
+ * Requires a WebSocket implementation — works natively in browsers
11886
+ * and in Node.js 21+ (or with the `ws` package).
11887
+ */
11888
+ subscribeFeed(listener) {
11889
+ const wsUrl = this.apiUrl.replace(/^http/, "ws") + "/ws/feed";
11890
+ const ws2 = new WebSocket(wsUrl);
11891
+ ws2.onmessage = (event) => {
11892
+ try {
11893
+ const raw = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
11894
+ listener(mapFeedMessage(raw));
11895
+ } catch {
11896
+ }
11897
+ };
11898
+ return () => {
11899
+ ws2.close();
11900
+ };
11901
+ }
11902
+ // ---------------------------------------------------------------------------
11903
+ // Private: HTTP helpers
11904
+ // ---------------------------------------------------------------------------
11905
+ ensureIdentity() {
11906
+ if (!this.identity) {
11907
+ throw new Error("MarketModule not initialized \u2014 call initialize() first");
11908
+ }
11909
+ }
11910
+ /** Register the agent's public key with the server (idempotent) */
11911
+ async ensureRegistered() {
11912
+ if (this.registered) return;
11913
+ this.ensureIdentity();
11914
+ const publicKey = bytesToHex4(secp256k1.getPublicKey(hexToBytes3(this.identity.privateKey), true));
11915
+ const body = { public_key: publicKey };
11916
+ if (this.identity.nametag) body.nametag = this.identity.nametag;
11917
+ const res = await fetch(`${this.apiUrl}/api/agent/register`, {
11918
+ method: "POST",
11919
+ headers: { "content-type": "application/json" },
11920
+ body: JSON.stringify(body),
11921
+ signal: AbortSignal.timeout(this.timeout)
11922
+ });
11923
+ if (res.ok || res.status === 409) {
11924
+ this.registered = true;
11925
+ return;
11926
+ }
11927
+ const text = await res.text();
11928
+ let data;
11929
+ try {
11930
+ data = JSON.parse(text);
11931
+ } catch {
11932
+ }
11933
+ throw new Error(data?.error ?? `Agent registration failed: HTTP ${res.status}`);
11934
+ }
11935
+ async parseResponse(res) {
11936
+ const text = await res.text();
11937
+ let data;
11938
+ try {
11939
+ data = JSON.parse(text);
11940
+ } catch {
11941
+ throw new Error(`Market API error: HTTP ${res.status} \u2014 unexpected response (not JSON)`);
11942
+ }
11943
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
11944
+ return data;
11945
+ }
11946
+ async apiPost(path, body) {
11947
+ this.ensureIdentity();
11948
+ await this.ensureRegistered();
11949
+ const signed = signRequest(body, this.identity.privateKey);
11950
+ const res = await fetch(`${this.apiUrl}${path}`, {
11951
+ method: "POST",
11952
+ headers: signed.headers,
11953
+ body: signed.body,
11954
+ signal: AbortSignal.timeout(this.timeout)
11955
+ });
11956
+ return this.parseResponse(res);
11957
+ }
11958
+ async apiGet(path) {
11959
+ this.ensureIdentity();
11960
+ await this.ensureRegistered();
11961
+ const signed = signRequest({}, this.identity.privateKey);
11962
+ const res = await fetch(`${this.apiUrl}${path}`, {
11963
+ method: "GET",
11964
+ headers: signed.headers,
11965
+ signal: AbortSignal.timeout(this.timeout)
11966
+ });
11967
+ return this.parseResponse(res);
11968
+ }
11969
+ async apiDelete(path) {
11970
+ this.ensureIdentity();
11971
+ await this.ensureRegistered();
11972
+ const signed = signRequest({}, this.identity.privateKey);
11973
+ const res = await fetch(`${this.apiUrl}${path}`, {
11974
+ method: "DELETE",
11975
+ headers: signed.headers,
11976
+ signal: AbortSignal.timeout(this.timeout)
11977
+ });
11978
+ return this.parseResponse(res);
11979
+ }
11980
+ async apiPublicPost(path, body) {
11981
+ const res = await fetch(`${this.apiUrl}${path}`, {
11982
+ method: "POST",
11983
+ headers: { "content-type": "application/json" },
11984
+ body: JSON.stringify(body),
11985
+ signal: AbortSignal.timeout(this.timeout)
11986
+ });
11987
+ return this.parseResponse(res);
11988
+ }
11989
+ };
11990
+ function createMarketModule(config) {
11991
+ return new MarketModule(config);
11992
+ }
11993
+
9441
11994
  // core/encryption.ts
9442
11995
  var import_crypto_js6 = __toESM(require("crypto-js"), 1);
9443
11996
  function encryptSimple(plaintext, password) {
@@ -10273,6 +12826,7 @@ var Sphere = class _Sphere {
10273
12826
  _payments;
10274
12827
  _communications;
10275
12828
  _groupChat = null;
12829
+ _market = null;
10276
12830
  // Events
10277
12831
  eventHandlers = /* @__PURE__ */ new Map();
10278
12832
  // Provider management
@@ -10282,7 +12836,7 @@ var Sphere = class _Sphere {
10282
12836
  // ===========================================================================
10283
12837
  // Constructor (private)
10284
12838
  // ===========================================================================
10285
- constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig) {
12839
+ constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig, marketConfig) {
10286
12840
  this._storage = storage;
10287
12841
  this._transport = transport;
10288
12842
  this._oracle = oracle;
@@ -10293,6 +12847,7 @@ var Sphere = class _Sphere {
10293
12847
  this._payments = createPaymentsModule({ l1: l1Config });
10294
12848
  this._communications = createCommunicationsModule();
10295
12849
  this._groupChat = groupChatConfig ? createGroupChatModule(groupChatConfig) : null;
12850
+ this._market = marketConfig ? createMarketModule(marketConfig) : null;
10296
12851
  }
10297
12852
  // ===========================================================================
10298
12853
  // Static Methods - Wallet Management
@@ -10302,13 +12857,17 @@ var Sphere = class _Sphere {
10302
12857
  */
10303
12858
  static async exists(storage) {
10304
12859
  try {
10305
- if (!storage.isConnected()) {
12860
+ const wasConnected = storage.isConnected();
12861
+ if (!wasConnected) {
10306
12862
  await storage.connect();
10307
12863
  }
10308
12864
  const mnemonic = await storage.get(STORAGE_KEYS_GLOBAL.MNEMONIC);
10309
12865
  if (mnemonic) return true;
10310
12866
  const masterKey = await storage.get(STORAGE_KEYS_GLOBAL.MASTER_KEY);
10311
12867
  if (masterKey) return true;
12868
+ if (!wasConnected) {
12869
+ await storage.disconnect();
12870
+ }
10312
12871
  return false;
10313
12872
  } catch {
10314
12873
  return false;
@@ -10342,6 +12901,7 @@ var Sphere = class _Sphere {
10342
12901
  static async init(options) {
10343
12902
  _Sphere.configureTokenRegistry(options.storage, options.network);
10344
12903
  const groupChat = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12904
+ const market = _Sphere.resolveMarketConfig(options.market);
10345
12905
  const walletExists = await _Sphere.exists(options.storage);
10346
12906
  if (walletExists) {
10347
12907
  const sphere2 = await _Sphere.load({
@@ -10352,6 +12912,7 @@ var Sphere = class _Sphere {
10352
12912
  l1: options.l1,
10353
12913
  price: options.price,
10354
12914
  groupChat,
12915
+ market,
10355
12916
  password: options.password
10356
12917
  });
10357
12918
  return { sphere: sphere2, created: false };
@@ -10379,6 +12940,7 @@ var Sphere = class _Sphere {
10379
12940
  l1: options.l1,
10380
12941
  price: options.price,
10381
12942
  groupChat,
12943
+ market,
10382
12944
  password: options.password
10383
12945
  });
10384
12946
  return { sphere, created: true, generatedMnemonic };
@@ -10406,6 +12968,17 @@ var Sphere = class _Sphere {
10406
12968
  }
10407
12969
  return config;
10408
12970
  }
12971
+ /**
12972
+ * Resolve market module config from Sphere.init() options.
12973
+ * - `true` → enable with default API URL
12974
+ * - `MarketModuleConfig` → pass through
12975
+ * - `undefined` → no market module
12976
+ */
12977
+ static resolveMarketConfig(config) {
12978
+ if (!config) return void 0;
12979
+ if (config === true) return {};
12980
+ return config;
12981
+ }
10409
12982
  /**
10410
12983
  * Configure TokenRegistry in the main bundle context.
10411
12984
  *
@@ -10431,6 +13004,7 @@ var Sphere = class _Sphere {
10431
13004
  }
10432
13005
  _Sphere.configureTokenRegistry(options.storage, options.network);
10433
13006
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
13007
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10434
13008
  const sphere = new _Sphere(
10435
13009
  options.storage,
10436
13010
  options.transport,
@@ -10438,7 +13012,8 @@ var Sphere = class _Sphere {
10438
13012
  options.tokenStorage,
10439
13013
  options.l1,
10440
13014
  options.price,
10441
- groupChatConfig
13015
+ groupChatConfig,
13016
+ marketConfig
10442
13017
  );
10443
13018
  sphere._password = options.password ?? null;
10444
13019
  await sphere.storeMnemonic(options.mnemonic, options.derivationPath);
@@ -10466,6 +13041,7 @@ var Sphere = class _Sphere {
10466
13041
  }
10467
13042
  _Sphere.configureTokenRegistry(options.storage, options.network);
10468
13043
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
13044
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10469
13045
  const sphere = new _Sphere(
10470
13046
  options.storage,
10471
13047
  options.transport,
@@ -10473,7 +13049,8 @@ var Sphere = class _Sphere {
10473
13049
  options.tokenStorage,
10474
13050
  options.l1,
10475
13051
  options.price,
10476
- groupChatConfig
13052
+ groupChatConfig,
13053
+ marketConfig
10477
13054
  );
10478
13055
  sphere._password = options.password ?? null;
10479
13056
  await sphere.loadIdentityFromStorage();
@@ -10519,6 +13096,7 @@ var Sphere = class _Sphere {
10519
13096
  console.log("[Sphere.import] Storage reconnected");
10520
13097
  }
10521
13098
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat);
13099
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10522
13100
  const sphere = new _Sphere(
10523
13101
  options.storage,
10524
13102
  options.transport,
@@ -10526,7 +13104,8 @@ var Sphere = class _Sphere {
10526
13104
  options.tokenStorage,
10527
13105
  options.l1,
10528
13106
  options.price,
10529
- groupChatConfig
13107
+ groupChatConfig,
13108
+ marketConfig
10530
13109
  );
10531
13110
  sphere._password = options.password ?? null;
10532
13111
  if (options.mnemonic) {
@@ -10607,46 +13186,58 @@ var Sphere = class _Sphere {
10607
13186
  static async clear(storageOrOptions) {
10608
13187
  const storage = "get" in storageOrOptions ? storageOrOptions : storageOrOptions.storage;
10609
13188
  const tokenStorage = "get" in storageOrOptions ? void 0 : storageOrOptions.tokenStorage;
10610
- if (!storage.isConnected()) {
10611
- await storage.connect();
10612
- }
10613
- console.log("[Sphere.clear] Removing storage keys...");
10614
- await storage.remove(STORAGE_KEYS_GLOBAL.MNEMONIC);
10615
- await storage.remove(STORAGE_KEYS_GLOBAL.MASTER_KEY);
10616
- await storage.remove(STORAGE_KEYS_GLOBAL.CHAIN_CODE);
10617
- await storage.remove(STORAGE_KEYS_GLOBAL.DERIVATION_PATH);
10618
- await storage.remove(STORAGE_KEYS_GLOBAL.BASE_PATH);
10619
- await storage.remove(STORAGE_KEYS_GLOBAL.DERIVATION_MODE);
10620
- await storage.remove(STORAGE_KEYS_GLOBAL.WALLET_SOURCE);
10621
- await storage.remove(STORAGE_KEYS_GLOBAL.WALLET_EXISTS);
10622
- await storage.remove(STORAGE_KEYS_GLOBAL.TRACKED_ADDRESSES);
10623
- await storage.remove(STORAGE_KEYS_GLOBAL.ADDRESS_NAMETAGS);
10624
- await storage.remove(STORAGE_KEYS_ADDRESS.PENDING_TRANSFERS);
10625
- await storage.remove(STORAGE_KEYS_ADDRESS.OUTBOX);
10626
- console.log("[Sphere.clear] Storage keys removed");
10627
- if (tokenStorage?.clear) {
10628
- console.log("[Sphere.clear] Clearing token storage...");
13189
+ if (_Sphere.instance) {
13190
+ console.log("[Sphere.clear] Destroying Sphere instance...");
13191
+ await _Sphere.instance.destroy();
13192
+ console.log("[Sphere.clear] Sphere instance destroyed");
13193
+ }
13194
+ await vestingClassifier.destroy();
13195
+ if (typeof indexedDB !== "undefined" && typeof indexedDB.databases === "function") {
13196
+ console.log("[Sphere.clear] Deleting all sphere IndexedDB databases...");
10629
13197
  try {
10630
- await Promise.race([
10631
- tokenStorage.clear(),
13198
+ const dbs = await Promise.race([
13199
+ indexedDB.databases(),
10632
13200
  new Promise(
10633
- (_, reject) => setTimeout(() => reject(new Error("tokenStorage.clear() timed out after 2s")), 2e3)
13201
+ (_, reject) => setTimeout(() => reject(new Error("timeout")), 2e3)
10634
13202
  )
10635
13203
  ]);
10636
- console.log("[Sphere.clear] Token storage cleared");
13204
+ const sphereDbs = dbs.filter((db) => db.name?.startsWith("sphere"));
13205
+ if (sphereDbs.length > 0) {
13206
+ await Promise.all(sphereDbs.map(
13207
+ (db) => new Promise((resolve) => {
13208
+ const req = indexedDB.deleteDatabase(db.name);
13209
+ req.onsuccess = () => {
13210
+ console.log(`[Sphere.clear] Deleted ${db.name}`);
13211
+ resolve();
13212
+ };
13213
+ req.onerror = () => resolve();
13214
+ req.onblocked = () => {
13215
+ console.warn(`[Sphere.clear] deleteDatabase blocked: ${db.name}`);
13216
+ resolve();
13217
+ };
13218
+ })
13219
+ ));
13220
+ }
13221
+ console.log("[Sphere.clear] IndexedDB cleanup done");
13222
+ } catch {
13223
+ console.warn("[Sphere.clear] IndexedDB enumeration failed");
13224
+ }
13225
+ }
13226
+ if (tokenStorage?.clear) {
13227
+ try {
13228
+ await tokenStorage.clear();
10637
13229
  } catch (err) {
10638
- console.warn("[Sphere.clear] Token storage clear failed/timed out:", err);
13230
+ console.warn("[Sphere.clear] Token storage clear failed:", err);
10639
13231
  }
10640
13232
  }
10641
- console.log("[Sphere.clear] Destroying vesting classifier...");
10642
- await vestingClassifier.destroy();
10643
- console.log("[Sphere.clear] Vesting classifier destroyed");
10644
- if (_Sphere.instance) {
10645
- console.log("[Sphere.clear] Destroying Sphere instance...");
10646
- await _Sphere.instance.destroy();
10647
- console.log("[Sphere.clear] Sphere instance destroyed");
10648
- } else {
10649
- console.log("[Sphere.clear] No Sphere instance to destroy");
13233
+ if (!storage.isConnected()) {
13234
+ try {
13235
+ await storage.connect();
13236
+ } catch {
13237
+ }
13238
+ }
13239
+ if (storage.isConnected()) {
13240
+ await storage.clear();
10650
13241
  }
10651
13242
  }
10652
13243
  /**
@@ -10691,6 +13282,10 @@ var Sphere = class _Sphere {
10691
13282
  get groupChat() {
10692
13283
  return this._groupChat;
10693
13284
  }
13285
+ /** Market module (intent bulletin board). Null if not configured. */
13286
+ get market() {
13287
+ return this._market;
13288
+ }
10694
13289
  // ===========================================================================
10695
13290
  // Public Properties - State
10696
13291
  // ===========================================================================
@@ -11566,9 +14161,14 @@ var Sphere = class _Sphere {
11566
14161
  storage: this._storage,
11567
14162
  emitEvent
11568
14163
  });
14164
+ this._market?.initialize({
14165
+ identity: this._identity,
14166
+ emitEvent
14167
+ });
11569
14168
  await this._payments.load();
11570
14169
  await this._communications.load();
11571
14170
  await this._groupChat?.load();
14171
+ await this._market?.load();
11572
14172
  }
11573
14173
  /**
11574
14174
  * Derive address at a specific index
@@ -12393,6 +14993,7 @@ var Sphere = class _Sphere {
12393
14993
  this._payments.destroy();
12394
14994
  this._communications.destroy();
12395
14995
  this._groupChat?.destroy();
14996
+ this._market?.destroy();
12396
14997
  await this._transport.disconnect();
12397
14998
  await this._storage.disconnect();
12398
14999
  await this._oracle.disconnect();
@@ -12700,9 +15301,14 @@ var Sphere = class _Sphere {
12700
15301
  storage: this._storage,
12701
15302
  emitEvent
12702
15303
  });
15304
+ this._market?.initialize({
15305
+ identity: this._identity,
15306
+ emitEvent
15307
+ });
12703
15308
  await this._payments.load();
12704
15309
  await this._communications.load();
12705
15310
  await this._groupChat?.load();
15311
+ await this._market?.load();
12706
15312
  }
12707
15313
  // ===========================================================================
12708
15314
  // Private: Helpers
@@ -13628,6 +16234,7 @@ function createPriceProvider(config) {
13628
16234
  DEFAULT_GROUP_RELAYS,
13629
16235
  DEFAULT_IPFS_BOOTSTRAP_PEERS,
13630
16236
  DEFAULT_IPFS_GATEWAYS,
16237
+ DEFAULT_MARKET_API_URL,
13631
16238
  DEFAULT_NOSTR_RELAYS,
13632
16239
  DEV_AGGREGATOR_URL,
13633
16240
  GroupChatModule,
@@ -13636,11 +16243,14 @@ function createPriceProvider(config) {
13636
16243
  L1,
13637
16244
  L1PaymentsModule,
13638
16245
  LIMITS,
16246
+ MarketModule,
13639
16247
  NETWORKS,
13640
16248
  NIP29_KINDS,
13641
16249
  NOSTR_EVENT_KINDS,
13642
16250
  PaymentsModule,
13643
16251
  STORAGE_KEYS,
16252
+ STORAGE_KEYS_ADDRESS,
16253
+ STORAGE_KEYS_GLOBAL,
13644
16254
  STORAGE_PREFIX,
13645
16255
  Sphere,
13646
16256
  SphereError,
@@ -13663,6 +16273,7 @@ function createPriceProvider(config) {
13663
16273
  createGroupChatModule,
13664
16274
  createKeyPair,
13665
16275
  createL1PaymentsModule,
16276
+ createMarketModule,
13666
16277
  createPaymentSession,
13667
16278
  createPaymentSessionError,
13668
16279
  createPaymentsModule,
@@ -13686,6 +16297,8 @@ function createPriceProvider(config) {
13686
16297
  generateMasterKey,
13687
16298
  generateMnemonic,
13688
16299
  getAddressHrp,
16300
+ getAddressId,
16301
+ getAddressStorageKey,
13689
16302
  getCoinIdByName,
13690
16303
  getCoinIdBySymbol,
13691
16304
  getCurrentStateHash,
@@ -13750,4 +16363,16 @@ function createPriceProvider(config) {
13750
16363
  txfToToken,
13751
16364
  validateMnemonic
13752
16365
  });
16366
+ /*! Bundled license information:
16367
+
16368
+ @noble/hashes/utils.js:
16369
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
16370
+
16371
+ @noble/curves/utils.js:
16372
+ @noble/curves/abstract/modular.js:
16373
+ @noble/curves/abstract/curve.js:
16374
+ @noble/curves/abstract/weierstrass.js:
16375
+ @noble/curves/secp256k1.js:
16376
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
16377
+ */
13753
16378
  //# sourceMappingURL=index.cjs.map