@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.js CHANGED
@@ -59,10 +59,10 @@ function bech32Polymod(values) {
59
59
  }
60
60
  function bech32Checksum(hrp, data) {
61
61
  const values = hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]);
62
- const mod = bech32Polymod(values) ^ 1;
62
+ const mod2 = bech32Polymod(values) ^ 1;
63
63
  const ret = [];
64
64
  for (let p = 0; p < 6; p++) {
65
- ret.push(mod >> 5 * (5 - p) & 31);
65
+ ret.push(mod2 >> 5 * (5 - p) & 31);
66
66
  }
67
67
  return ret;
68
68
  }
@@ -833,9 +833,13 @@ var VestingClassifier = class {
833
833
  storeName = "vestingCache";
834
834
  db = null;
835
835
  /**
836
- * Initialize IndexedDB for persistent caching
836
+ * Initialize IndexedDB for persistent caching.
837
+ * In Node.js (no IndexedDB), silently falls back to memory-only caching.
837
838
  */
838
839
  async initDB() {
840
+ if (typeof indexedDB === "undefined") {
841
+ return;
842
+ }
839
843
  return new Promise((resolve, reject) => {
840
844
  const request = indexedDB.open(this.dbName, 1);
841
845
  request.onupgradeneeded = (event) => {
@@ -2518,6 +2522,9 @@ var STORAGE_KEYS = {
2518
2522
  ...STORAGE_KEYS_GLOBAL,
2519
2523
  ...STORAGE_KEYS_ADDRESS
2520
2524
  };
2525
+ function getAddressStorageKey(addressId, key) {
2526
+ return `${addressId}_${key}`;
2527
+ }
2521
2528
  function getAddressId(directAddress) {
2522
2529
  let hash = directAddress;
2523
2530
  if (hash.startsWith("DIRECT://")) {
@@ -6925,6 +6932,15 @@ var PaymentsModule = class _PaymentsModule {
6925
6932
  );
6926
6933
  return SigningService.createFromSecret(privateKeyBytes);
6927
6934
  }
6935
+ /**
6936
+ * Get the wallet's signing public key (used for token ownership predicates).
6937
+ * This is the key that token state predicates are checked against.
6938
+ */
6939
+ async getSigningPublicKey() {
6940
+ this.ensureInitialized();
6941
+ const signer = await this.createSigningService();
6942
+ return signer.publicKey;
6943
+ }
6928
6944
  /**
6929
6945
  * Create DirectAddress from a public key using UnmaskedPredicateReference
6930
6946
  */
@@ -7573,14 +7589,17 @@ var CommunicationsModule = class {
7573
7589
  broadcasts = /* @__PURE__ */ new Map();
7574
7590
  // Subscriptions
7575
7591
  unsubscribeMessages = null;
7592
+ unsubscribeComposing = null;
7576
7593
  broadcastSubscriptions = /* @__PURE__ */ new Map();
7577
7594
  // Handlers
7578
7595
  dmHandlers = /* @__PURE__ */ new Set();
7596
+ composingHandlers = /* @__PURE__ */ new Set();
7579
7597
  broadcastHandlers = /* @__PURE__ */ new Set();
7580
7598
  constructor(config) {
7581
7599
  this.config = {
7582
7600
  autoSave: config?.autoSave ?? true,
7583
7601
  maxMessages: config?.maxMessages ?? 1e3,
7602
+ maxPerConversation: config?.maxPerConversation ?? 200,
7584
7603
  readReceipts: config?.readReceipts ?? true
7585
7604
  };
7586
7605
  }
@@ -7591,6 +7610,8 @@ var CommunicationsModule = class {
7591
7610
  * Initialize module with dependencies
7592
7611
  */
7593
7612
  initialize(deps) {
7613
+ this.unsubscribeMessages?.();
7614
+ this.unsubscribeComposing?.();
7594
7615
  this.deps = deps;
7595
7616
  this.unsubscribeMessages = deps.transport.onMessage((msg) => {
7596
7617
  this.handleIncomingMessage(msg);
@@ -7617,19 +7638,41 @@ var CommunicationsModule = class {
7617
7638
  });
7618
7639
  });
7619
7640
  }
7641
+ this.unsubscribeComposing = deps.transport.onComposing?.((indicator) => {
7642
+ this.handleComposingIndicator(indicator);
7643
+ }) ?? null;
7620
7644
  }
7621
7645
  /**
7622
- * Load messages from storage
7646
+ * Load messages from storage.
7647
+ * Uses per-address key (STORAGE_KEYS_ADDRESS.MESSAGES) which is automatically
7648
+ * scoped by LocalStorageProvider to sphere_DIRECT_xxx_yyy_messages.
7649
+ * Falls back to legacy global 'direct_messages' key for migration.
7623
7650
  */
7624
7651
  async load() {
7625
7652
  this.ensureInitialized();
7626
- const data = await this.deps.storage.get("direct_messages");
7653
+ this.messages.clear();
7654
+ let data = await this.deps.storage.get(STORAGE_KEYS_ADDRESS.MESSAGES);
7627
7655
  if (data) {
7628
7656
  const messages = JSON.parse(data);
7629
- this.messages.clear();
7630
7657
  for (const msg of messages) {
7631
7658
  this.messages.set(msg.id, msg);
7632
7659
  }
7660
+ return;
7661
+ }
7662
+ data = await this.deps.storage.get("direct_messages");
7663
+ if (data) {
7664
+ const allMessages = JSON.parse(data);
7665
+ const myPubkey = this.deps.identity.chainPubkey;
7666
+ const myMessages = allMessages.filter(
7667
+ (m) => m.senderPubkey === myPubkey || m.recipientPubkey === myPubkey
7668
+ );
7669
+ for (const msg of myMessages) {
7670
+ this.messages.set(msg.id, msg);
7671
+ }
7672
+ if (myMessages.length > 0) {
7673
+ await this.save();
7674
+ console.log(`[Communications] Migrated ${myMessages.length} messages to per-address storage`);
7675
+ }
7633
7676
  }
7634
7677
  }
7635
7678
  /**
@@ -7638,6 +7681,8 @@ var CommunicationsModule = class {
7638
7681
  destroy() {
7639
7682
  this.unsubscribeMessages?.();
7640
7683
  this.unsubscribeMessages = null;
7684
+ this.unsubscribeComposing?.();
7685
+ this.unsubscribeComposing = null;
7641
7686
  for (const unsub of this.broadcastSubscriptions.values()) {
7642
7687
  unsub();
7643
7688
  }
@@ -7729,6 +7774,37 @@ var CommunicationsModule = class {
7729
7774
  }
7730
7775
  return messages.length;
7731
7776
  }
7777
+ /**
7778
+ * Get a page of messages from a conversation (for lazy loading).
7779
+ * Returns messages in chronological order with a cursor for loading older messages.
7780
+ */
7781
+ getConversationPage(peerPubkey, options) {
7782
+ const limit = options?.limit ?? 20;
7783
+ const before = options?.before ?? Infinity;
7784
+ const all = Array.from(this.messages.values()).filter(
7785
+ (m) => (m.senderPubkey === peerPubkey || m.recipientPubkey === peerPubkey) && m.timestamp < before
7786
+ ).sort((a, b) => b.timestamp - a.timestamp);
7787
+ const page = all.slice(0, limit);
7788
+ return {
7789
+ messages: page.reverse(),
7790
+ // chronological order for display
7791
+ hasMore: all.length > limit,
7792
+ oldestTimestamp: page.length > 0 ? page[0].timestamp : null
7793
+ };
7794
+ }
7795
+ /**
7796
+ * Delete all messages in a conversation with a peer
7797
+ */
7798
+ async deleteConversation(peerPubkey) {
7799
+ for (const [id, msg] of this.messages) {
7800
+ if (msg.senderPubkey === peerPubkey || msg.recipientPubkey === peerPubkey) {
7801
+ this.messages.delete(id);
7802
+ }
7803
+ }
7804
+ if (this.config.autoSave) {
7805
+ await this.save();
7806
+ }
7807
+ }
7732
7808
  /**
7733
7809
  * Send typing indicator to a peer
7734
7810
  */
@@ -7738,6 +7814,26 @@ var CommunicationsModule = class {
7738
7814
  await this.deps.transport.sendTypingIndicator(peerPubkey);
7739
7815
  }
7740
7816
  }
7817
+ /**
7818
+ * Send a composing indicator to a peer.
7819
+ * Fire-and-forget — does not save to message history.
7820
+ */
7821
+ async sendComposingIndicator(recipientPubkeyOrNametag) {
7822
+ this.ensureInitialized();
7823
+ const recipientPubkey = await this.resolveRecipient(recipientPubkeyOrNametag);
7824
+ const content = JSON.stringify({
7825
+ senderNametag: this.deps.identity.nametag,
7826
+ expiresIn: 3e4
7827
+ });
7828
+ await this.deps.transport.sendComposingIndicator?.(recipientPubkey, content);
7829
+ }
7830
+ /**
7831
+ * Subscribe to incoming composing indicators
7832
+ */
7833
+ onComposingIndicator(handler) {
7834
+ this.composingHandlers.add(handler);
7835
+ return () => this.composingHandlers.delete(handler);
7836
+ }
7741
7837
  /**
7742
7838
  * Subscribe to incoming DMs
7743
7839
  */
@@ -7850,6 +7946,21 @@ var CommunicationsModule = class {
7850
7946
  }
7851
7947
  this.pruneIfNeeded();
7852
7948
  }
7949
+ handleComposingIndicator(indicator) {
7950
+ const composing = {
7951
+ senderPubkey: indicator.senderPubkey,
7952
+ senderNametag: indicator.senderNametag,
7953
+ expiresIn: indicator.expiresIn
7954
+ };
7955
+ this.deps.emitEvent("composing:started", composing);
7956
+ for (const handler of this.composingHandlers) {
7957
+ try {
7958
+ handler(composing);
7959
+ } catch (error) {
7960
+ console.error("[Communications] Composing handler error:", error);
7961
+ }
7962
+ }
7963
+ }
7853
7964
  handleIncomingBroadcast(incoming) {
7854
7965
  const message = {
7855
7966
  id: incoming.id,
@@ -7873,9 +7984,23 @@ var CommunicationsModule = class {
7873
7984
  // ===========================================================================
7874
7985
  async save() {
7875
7986
  const messages = Array.from(this.messages.values());
7876
- await this.deps.storage.set("direct_messages", JSON.stringify(messages));
7987
+ await this.deps.storage.set(STORAGE_KEYS_ADDRESS.MESSAGES, JSON.stringify(messages));
7877
7988
  }
7878
7989
  pruneIfNeeded() {
7990
+ const byPeer = /* @__PURE__ */ new Map();
7991
+ for (const msg of this.messages.values()) {
7992
+ const peer = msg.senderPubkey === this.deps?.identity.chainPubkey ? msg.recipientPubkey : msg.senderPubkey;
7993
+ if (!byPeer.has(peer)) byPeer.set(peer, []);
7994
+ byPeer.get(peer).push(msg);
7995
+ }
7996
+ for (const [, msgs] of byPeer) {
7997
+ if (msgs.length <= this.config.maxPerConversation) continue;
7998
+ msgs.sort((a, b) => a.timestamp - b.timestamp);
7999
+ const toRemove2 = msgs.slice(0, msgs.length - this.config.maxPerConversation);
8000
+ for (const msg of toRemove2) {
8001
+ this.messages.delete(msg.id);
8002
+ }
8003
+ }
7879
8004
  if (this.messages.size <= this.config.maxMessages) return;
7880
8005
  const sorted = Array.from(this.messages.entries()).sort(([, a], [, b]) => a.timestamp - b.timestamp);
7881
8006
  const toRemove = sorted.slice(0, sorted.length - this.config.maxMessages);
@@ -9288,6 +9413,2427 @@ function createGroupChatModule(config) {
9288
9413
  return new GroupChatModule(config);
9289
9414
  }
9290
9415
 
9416
+ // node_modules/@noble/hashes/utils.js
9417
+ function isBytes(a) {
9418
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
9419
+ }
9420
+ function anumber(n, title = "") {
9421
+ if (!Number.isSafeInteger(n) || n < 0) {
9422
+ const prefix = title && `"${title}" `;
9423
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
9424
+ }
9425
+ }
9426
+ function abytes(value, length, title = "") {
9427
+ const bytes = isBytes(value);
9428
+ const len = value?.length;
9429
+ const needsLen = length !== void 0;
9430
+ if (!bytes || needsLen && len !== length) {
9431
+ const prefix = title && `"${title}" `;
9432
+ const ofLen = needsLen ? ` of length ${length}` : "";
9433
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
9434
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
9435
+ }
9436
+ return value;
9437
+ }
9438
+ function ahash(h) {
9439
+ if (typeof h !== "function" || typeof h.create !== "function")
9440
+ throw new Error("Hash must wrapped by utils.createHasher");
9441
+ anumber(h.outputLen);
9442
+ anumber(h.blockLen);
9443
+ }
9444
+ function aexists(instance, checkFinished = true) {
9445
+ if (instance.destroyed)
9446
+ throw new Error("Hash instance has been destroyed");
9447
+ if (checkFinished && instance.finished)
9448
+ throw new Error("Hash#digest() has already been called");
9449
+ }
9450
+ function aoutput(out, instance) {
9451
+ abytes(out, void 0, "digestInto() output");
9452
+ const min = instance.outputLen;
9453
+ if (out.length < min) {
9454
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
9455
+ }
9456
+ }
9457
+ function clean(...arrays) {
9458
+ for (let i = 0; i < arrays.length; i++) {
9459
+ arrays[i].fill(0);
9460
+ }
9461
+ }
9462
+ function createView(arr) {
9463
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
9464
+ }
9465
+ function rotr(word, shift) {
9466
+ return word << 32 - shift | word >>> shift;
9467
+ }
9468
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
9469
+ // @ts-ignore
9470
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
9471
+ ))();
9472
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
9473
+ function bytesToHex4(bytes) {
9474
+ abytes(bytes);
9475
+ if (hasHexBuiltin)
9476
+ return bytes.toHex();
9477
+ let hex = "";
9478
+ for (let i = 0; i < bytes.length; i++) {
9479
+ hex += hexes[bytes[i]];
9480
+ }
9481
+ return hex;
9482
+ }
9483
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
9484
+ function asciiToBase16(ch) {
9485
+ if (ch >= asciis._0 && ch <= asciis._9)
9486
+ return ch - asciis._0;
9487
+ if (ch >= asciis.A && ch <= asciis.F)
9488
+ return ch - (asciis.A - 10);
9489
+ if (ch >= asciis.a && ch <= asciis.f)
9490
+ return ch - (asciis.a - 10);
9491
+ return;
9492
+ }
9493
+ function hexToBytes2(hex) {
9494
+ if (typeof hex !== "string")
9495
+ throw new Error("hex string expected, got " + typeof hex);
9496
+ if (hasHexBuiltin)
9497
+ return Uint8Array.fromHex(hex);
9498
+ const hl = hex.length;
9499
+ const al = hl / 2;
9500
+ if (hl % 2)
9501
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
9502
+ const array = new Uint8Array(al);
9503
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
9504
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
9505
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
9506
+ if (n1 === void 0 || n2 === void 0) {
9507
+ const char = hex[hi] + hex[hi + 1];
9508
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
9509
+ }
9510
+ array[ai] = n1 * 16 + n2;
9511
+ }
9512
+ return array;
9513
+ }
9514
+ function concatBytes(...arrays) {
9515
+ let sum = 0;
9516
+ for (let i = 0; i < arrays.length; i++) {
9517
+ const a = arrays[i];
9518
+ abytes(a);
9519
+ sum += a.length;
9520
+ }
9521
+ const res = new Uint8Array(sum);
9522
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
9523
+ const a = arrays[i];
9524
+ res.set(a, pad);
9525
+ pad += a.length;
9526
+ }
9527
+ return res;
9528
+ }
9529
+ function createHasher(hashCons, info = {}) {
9530
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
9531
+ const tmp = hashCons(void 0);
9532
+ hashC.outputLen = tmp.outputLen;
9533
+ hashC.blockLen = tmp.blockLen;
9534
+ hashC.create = (opts) => hashCons(opts);
9535
+ Object.assign(hashC, info);
9536
+ return Object.freeze(hashC);
9537
+ }
9538
+ function randomBytes2(bytesLength = 32) {
9539
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
9540
+ if (typeof cr?.getRandomValues !== "function")
9541
+ throw new Error("crypto.getRandomValues must be defined");
9542
+ return cr.getRandomValues(new Uint8Array(bytesLength));
9543
+ }
9544
+ var oidNist = (suffix) => ({
9545
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
9546
+ });
9547
+
9548
+ // node_modules/@noble/hashes/_md.js
9549
+ function Chi(a, b, c) {
9550
+ return a & b ^ ~a & c;
9551
+ }
9552
+ function Maj(a, b, c) {
9553
+ return a & b ^ a & c ^ b & c;
9554
+ }
9555
+ var HashMD = class {
9556
+ blockLen;
9557
+ outputLen;
9558
+ padOffset;
9559
+ isLE;
9560
+ // For partial updates less than block size
9561
+ buffer;
9562
+ view;
9563
+ finished = false;
9564
+ length = 0;
9565
+ pos = 0;
9566
+ destroyed = false;
9567
+ constructor(blockLen, outputLen, padOffset, isLE) {
9568
+ this.blockLen = blockLen;
9569
+ this.outputLen = outputLen;
9570
+ this.padOffset = padOffset;
9571
+ this.isLE = isLE;
9572
+ this.buffer = new Uint8Array(blockLen);
9573
+ this.view = createView(this.buffer);
9574
+ }
9575
+ update(data) {
9576
+ aexists(this);
9577
+ abytes(data);
9578
+ const { view, buffer, blockLen } = this;
9579
+ const len = data.length;
9580
+ for (let pos = 0; pos < len; ) {
9581
+ const take = Math.min(blockLen - this.pos, len - pos);
9582
+ if (take === blockLen) {
9583
+ const dataView = createView(data);
9584
+ for (; blockLen <= len - pos; pos += blockLen)
9585
+ this.process(dataView, pos);
9586
+ continue;
9587
+ }
9588
+ buffer.set(data.subarray(pos, pos + take), this.pos);
9589
+ this.pos += take;
9590
+ pos += take;
9591
+ if (this.pos === blockLen) {
9592
+ this.process(view, 0);
9593
+ this.pos = 0;
9594
+ }
9595
+ }
9596
+ this.length += data.length;
9597
+ this.roundClean();
9598
+ return this;
9599
+ }
9600
+ digestInto(out) {
9601
+ aexists(this);
9602
+ aoutput(out, this);
9603
+ this.finished = true;
9604
+ const { buffer, view, blockLen, isLE } = this;
9605
+ let { pos } = this;
9606
+ buffer[pos++] = 128;
9607
+ clean(this.buffer.subarray(pos));
9608
+ if (this.padOffset > blockLen - pos) {
9609
+ this.process(view, 0);
9610
+ pos = 0;
9611
+ }
9612
+ for (let i = pos; i < blockLen; i++)
9613
+ buffer[i] = 0;
9614
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
9615
+ this.process(view, 0);
9616
+ const oview = createView(out);
9617
+ const len = this.outputLen;
9618
+ if (len % 4)
9619
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
9620
+ const outLen = len / 4;
9621
+ const state = this.get();
9622
+ if (outLen > state.length)
9623
+ throw new Error("_sha2: outputLen bigger than state");
9624
+ for (let i = 0; i < outLen; i++)
9625
+ oview.setUint32(4 * i, state[i], isLE);
9626
+ }
9627
+ digest() {
9628
+ const { buffer, outputLen } = this;
9629
+ this.digestInto(buffer);
9630
+ const res = buffer.slice(0, outputLen);
9631
+ this.destroy();
9632
+ return res;
9633
+ }
9634
+ _cloneInto(to) {
9635
+ to ||= new this.constructor();
9636
+ to.set(...this.get());
9637
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
9638
+ to.destroyed = destroyed;
9639
+ to.finished = finished;
9640
+ to.length = length;
9641
+ to.pos = pos;
9642
+ if (length % blockLen)
9643
+ to.buffer.set(buffer);
9644
+ return to;
9645
+ }
9646
+ clone() {
9647
+ return this._cloneInto();
9648
+ }
9649
+ };
9650
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
9651
+ 1779033703,
9652
+ 3144134277,
9653
+ 1013904242,
9654
+ 2773480762,
9655
+ 1359893119,
9656
+ 2600822924,
9657
+ 528734635,
9658
+ 1541459225
9659
+ ]);
9660
+
9661
+ // node_modules/@noble/hashes/sha2.js
9662
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
9663
+ 1116352408,
9664
+ 1899447441,
9665
+ 3049323471,
9666
+ 3921009573,
9667
+ 961987163,
9668
+ 1508970993,
9669
+ 2453635748,
9670
+ 2870763221,
9671
+ 3624381080,
9672
+ 310598401,
9673
+ 607225278,
9674
+ 1426881987,
9675
+ 1925078388,
9676
+ 2162078206,
9677
+ 2614888103,
9678
+ 3248222580,
9679
+ 3835390401,
9680
+ 4022224774,
9681
+ 264347078,
9682
+ 604807628,
9683
+ 770255983,
9684
+ 1249150122,
9685
+ 1555081692,
9686
+ 1996064986,
9687
+ 2554220882,
9688
+ 2821834349,
9689
+ 2952996808,
9690
+ 3210313671,
9691
+ 3336571891,
9692
+ 3584528711,
9693
+ 113926993,
9694
+ 338241895,
9695
+ 666307205,
9696
+ 773529912,
9697
+ 1294757372,
9698
+ 1396182291,
9699
+ 1695183700,
9700
+ 1986661051,
9701
+ 2177026350,
9702
+ 2456956037,
9703
+ 2730485921,
9704
+ 2820302411,
9705
+ 3259730800,
9706
+ 3345764771,
9707
+ 3516065817,
9708
+ 3600352804,
9709
+ 4094571909,
9710
+ 275423344,
9711
+ 430227734,
9712
+ 506948616,
9713
+ 659060556,
9714
+ 883997877,
9715
+ 958139571,
9716
+ 1322822218,
9717
+ 1537002063,
9718
+ 1747873779,
9719
+ 1955562222,
9720
+ 2024104815,
9721
+ 2227730452,
9722
+ 2361852424,
9723
+ 2428436474,
9724
+ 2756734187,
9725
+ 3204031479,
9726
+ 3329325298
9727
+ ]);
9728
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
9729
+ var SHA2_32B = class extends HashMD {
9730
+ constructor(outputLen) {
9731
+ super(64, outputLen, 8, false);
9732
+ }
9733
+ get() {
9734
+ const { A, B, C, D, E, F, G, H } = this;
9735
+ return [A, B, C, D, E, F, G, H];
9736
+ }
9737
+ // prettier-ignore
9738
+ set(A, B, C, D, E, F, G, H) {
9739
+ this.A = A | 0;
9740
+ this.B = B | 0;
9741
+ this.C = C | 0;
9742
+ this.D = D | 0;
9743
+ this.E = E | 0;
9744
+ this.F = F | 0;
9745
+ this.G = G | 0;
9746
+ this.H = H | 0;
9747
+ }
9748
+ process(view, offset) {
9749
+ for (let i = 0; i < 16; i++, offset += 4)
9750
+ SHA256_W[i] = view.getUint32(offset, false);
9751
+ for (let i = 16; i < 64; i++) {
9752
+ const W15 = SHA256_W[i - 15];
9753
+ const W2 = SHA256_W[i - 2];
9754
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
9755
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
9756
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
9757
+ }
9758
+ let { A, B, C, D, E, F, G, H } = this;
9759
+ for (let i = 0; i < 64; i++) {
9760
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
9761
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
9762
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
9763
+ const T2 = sigma0 + Maj(A, B, C) | 0;
9764
+ H = G;
9765
+ G = F;
9766
+ F = E;
9767
+ E = D + T1 | 0;
9768
+ D = C;
9769
+ C = B;
9770
+ B = A;
9771
+ A = T1 + T2 | 0;
9772
+ }
9773
+ A = A + this.A | 0;
9774
+ B = B + this.B | 0;
9775
+ C = C + this.C | 0;
9776
+ D = D + this.D | 0;
9777
+ E = E + this.E | 0;
9778
+ F = F + this.F | 0;
9779
+ G = G + this.G | 0;
9780
+ H = H + this.H | 0;
9781
+ this.set(A, B, C, D, E, F, G, H);
9782
+ }
9783
+ roundClean() {
9784
+ clean(SHA256_W);
9785
+ }
9786
+ destroy() {
9787
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
9788
+ clean(this.buffer);
9789
+ }
9790
+ };
9791
+ var _SHA256 = class extends SHA2_32B {
9792
+ // We cannot use array here since array allows indexing by variable
9793
+ // which means optimizer/compiler cannot use registers.
9794
+ A = SHA256_IV[0] | 0;
9795
+ B = SHA256_IV[1] | 0;
9796
+ C = SHA256_IV[2] | 0;
9797
+ D = SHA256_IV[3] | 0;
9798
+ E = SHA256_IV[4] | 0;
9799
+ F = SHA256_IV[5] | 0;
9800
+ G = SHA256_IV[6] | 0;
9801
+ H = SHA256_IV[7] | 0;
9802
+ constructor() {
9803
+ super(32);
9804
+ }
9805
+ };
9806
+ var sha2564 = /* @__PURE__ */ createHasher(
9807
+ () => new _SHA256(),
9808
+ /* @__PURE__ */ oidNist(1)
9809
+ );
9810
+
9811
+ // node_modules/@noble/curves/utils.js
9812
+ var _0n = /* @__PURE__ */ BigInt(0);
9813
+ var _1n = /* @__PURE__ */ BigInt(1);
9814
+ function abool(value, title = "") {
9815
+ if (typeof value !== "boolean") {
9816
+ const prefix = title && `"${title}" `;
9817
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
9818
+ }
9819
+ return value;
9820
+ }
9821
+ function abignumber(n) {
9822
+ if (typeof n === "bigint") {
9823
+ if (!isPosBig(n))
9824
+ throw new Error("positive bigint expected, got " + n);
9825
+ } else
9826
+ anumber(n);
9827
+ return n;
9828
+ }
9829
+ function numberToHexUnpadded(num) {
9830
+ const hex = abignumber(num).toString(16);
9831
+ return hex.length & 1 ? "0" + hex : hex;
9832
+ }
9833
+ function hexToNumber(hex) {
9834
+ if (typeof hex !== "string")
9835
+ throw new Error("hex string expected, got " + typeof hex);
9836
+ return hex === "" ? _0n : BigInt("0x" + hex);
9837
+ }
9838
+ function bytesToNumberBE(bytes) {
9839
+ return hexToNumber(bytesToHex4(bytes));
9840
+ }
9841
+ function bytesToNumberLE(bytes) {
9842
+ return hexToNumber(bytesToHex4(copyBytes(abytes(bytes)).reverse()));
9843
+ }
9844
+ function numberToBytesBE(n, len) {
9845
+ anumber(len);
9846
+ n = abignumber(n);
9847
+ const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
9848
+ if (res.length !== len)
9849
+ throw new Error("number too large");
9850
+ return res;
9851
+ }
9852
+ function numberToBytesLE(n, len) {
9853
+ return numberToBytesBE(n, len).reverse();
9854
+ }
9855
+ function copyBytes(bytes) {
9856
+ return Uint8Array.from(bytes);
9857
+ }
9858
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
9859
+ function inRange(n, min, max) {
9860
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
9861
+ }
9862
+ function aInRange(title, n, min, max) {
9863
+ if (!inRange(n, min, max))
9864
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
9865
+ }
9866
+ function bitLen(n) {
9867
+ let len;
9868
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
9869
+ ;
9870
+ return len;
9871
+ }
9872
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
9873
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
9874
+ anumber(hashLen, "hashLen");
9875
+ anumber(qByteLen, "qByteLen");
9876
+ if (typeof hmacFn !== "function")
9877
+ throw new Error("hmacFn must be a function");
9878
+ const u8n = (len) => new Uint8Array(len);
9879
+ const NULL = Uint8Array.of();
9880
+ const byte0 = Uint8Array.of(0);
9881
+ const byte1 = Uint8Array.of(1);
9882
+ const _maxDrbgIters = 1e3;
9883
+ let v = u8n(hashLen);
9884
+ let k = u8n(hashLen);
9885
+ let i = 0;
9886
+ const reset = () => {
9887
+ v.fill(1);
9888
+ k.fill(0);
9889
+ i = 0;
9890
+ };
9891
+ const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
9892
+ const reseed = (seed = NULL) => {
9893
+ k = h(byte0, seed);
9894
+ v = h();
9895
+ if (seed.length === 0)
9896
+ return;
9897
+ k = h(byte1, seed);
9898
+ v = h();
9899
+ };
9900
+ const gen = () => {
9901
+ if (i++ >= _maxDrbgIters)
9902
+ throw new Error("drbg: tried max amount of iterations");
9903
+ let len = 0;
9904
+ const out = [];
9905
+ while (len < qByteLen) {
9906
+ v = h();
9907
+ const sl = v.slice();
9908
+ out.push(sl);
9909
+ len += v.length;
9910
+ }
9911
+ return concatBytes(...out);
9912
+ };
9913
+ const genUntil = (seed, pred) => {
9914
+ reset();
9915
+ reseed(seed);
9916
+ let res = void 0;
9917
+ while (!(res = pred(gen())))
9918
+ reseed();
9919
+ reset();
9920
+ return res;
9921
+ };
9922
+ return genUntil;
9923
+ }
9924
+ function validateObject(object, fields = {}, optFields = {}) {
9925
+ if (!object || typeof object !== "object")
9926
+ throw new Error("expected valid options object");
9927
+ function checkField(fieldName, expectedType, isOpt) {
9928
+ const val = object[fieldName];
9929
+ if (isOpt && val === void 0)
9930
+ return;
9931
+ const current = typeof val;
9932
+ if (current !== expectedType || val === null)
9933
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
9934
+ }
9935
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
9936
+ iter(fields, false);
9937
+ iter(optFields, true);
9938
+ }
9939
+ function memoized(fn) {
9940
+ const map = /* @__PURE__ */ new WeakMap();
9941
+ return (arg, ...args) => {
9942
+ const val = map.get(arg);
9943
+ if (val !== void 0)
9944
+ return val;
9945
+ const computed = fn(arg, ...args);
9946
+ map.set(arg, computed);
9947
+ return computed;
9948
+ };
9949
+ }
9950
+
9951
+ // node_modules/@noble/curves/abstract/modular.js
9952
+ var _0n2 = /* @__PURE__ */ BigInt(0);
9953
+ var _1n2 = /* @__PURE__ */ BigInt(1);
9954
+ var _2n = /* @__PURE__ */ BigInt(2);
9955
+ var _3n = /* @__PURE__ */ BigInt(3);
9956
+ var _4n = /* @__PURE__ */ BigInt(4);
9957
+ var _5n = /* @__PURE__ */ BigInt(5);
9958
+ var _7n = /* @__PURE__ */ BigInt(7);
9959
+ var _8n = /* @__PURE__ */ BigInt(8);
9960
+ var _9n = /* @__PURE__ */ BigInt(9);
9961
+ var _16n = /* @__PURE__ */ BigInt(16);
9962
+ function mod(a, b) {
9963
+ const result = a % b;
9964
+ return result >= _0n2 ? result : b + result;
9965
+ }
9966
+ function pow2(x, power, modulo) {
9967
+ let res = x;
9968
+ while (power-- > _0n2) {
9969
+ res *= res;
9970
+ res %= modulo;
9971
+ }
9972
+ return res;
9973
+ }
9974
+ function invert(number, modulo) {
9975
+ if (number === _0n2)
9976
+ throw new Error("invert: expected non-zero number");
9977
+ if (modulo <= _0n2)
9978
+ throw new Error("invert: expected positive modulus, got " + modulo);
9979
+ let a = mod(number, modulo);
9980
+ let b = modulo;
9981
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
9982
+ while (a !== _0n2) {
9983
+ const q = b / a;
9984
+ const r = b % a;
9985
+ const m = x - u * q;
9986
+ const n = y - v * q;
9987
+ b = a, a = r, x = u, y = v, u = m, v = n;
9988
+ }
9989
+ const gcd = b;
9990
+ if (gcd !== _1n2)
9991
+ throw new Error("invert: does not exist");
9992
+ return mod(x, modulo);
9993
+ }
9994
+ function assertIsSquare(Fp, root, n) {
9995
+ if (!Fp.eql(Fp.sqr(root), n))
9996
+ throw new Error("Cannot find square root");
9997
+ }
9998
+ function sqrt3mod4(Fp, n) {
9999
+ const p1div4 = (Fp.ORDER + _1n2) / _4n;
10000
+ const root = Fp.pow(n, p1div4);
10001
+ assertIsSquare(Fp, root, n);
10002
+ return root;
10003
+ }
10004
+ function sqrt5mod8(Fp, n) {
10005
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
10006
+ const n2 = Fp.mul(n, _2n);
10007
+ const v = Fp.pow(n2, p5div8);
10008
+ const nv = Fp.mul(n, v);
10009
+ const i = Fp.mul(Fp.mul(nv, _2n), v);
10010
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
10011
+ assertIsSquare(Fp, root, n);
10012
+ return root;
10013
+ }
10014
+ function sqrt9mod16(P) {
10015
+ const Fp_ = Field(P);
10016
+ const tn = tonelliShanks(P);
10017
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
10018
+ const c2 = tn(Fp_, c1);
10019
+ const c3 = tn(Fp_, Fp_.neg(c1));
10020
+ const c4 = (P + _7n) / _16n;
10021
+ return (Fp, n) => {
10022
+ let tv1 = Fp.pow(n, c4);
10023
+ let tv2 = Fp.mul(tv1, c1);
10024
+ const tv3 = Fp.mul(tv1, c2);
10025
+ const tv4 = Fp.mul(tv1, c3);
10026
+ const e1 = Fp.eql(Fp.sqr(tv2), n);
10027
+ const e2 = Fp.eql(Fp.sqr(tv3), n);
10028
+ tv1 = Fp.cmov(tv1, tv2, e1);
10029
+ tv2 = Fp.cmov(tv4, tv3, e2);
10030
+ const e3 = Fp.eql(Fp.sqr(tv2), n);
10031
+ const root = Fp.cmov(tv1, tv2, e3);
10032
+ assertIsSquare(Fp, root, n);
10033
+ return root;
10034
+ };
10035
+ }
10036
+ function tonelliShanks(P) {
10037
+ if (P < _3n)
10038
+ throw new Error("sqrt is not defined for small field");
10039
+ let Q = P - _1n2;
10040
+ let S = 0;
10041
+ while (Q % _2n === _0n2) {
10042
+ Q /= _2n;
10043
+ S++;
10044
+ }
10045
+ let Z = _2n;
10046
+ const _Fp = Field(P);
10047
+ while (FpLegendre(_Fp, Z) === 1) {
10048
+ if (Z++ > 1e3)
10049
+ throw new Error("Cannot find square root: probably non-prime P");
10050
+ }
10051
+ if (S === 1)
10052
+ return sqrt3mod4;
10053
+ let cc = _Fp.pow(Z, Q);
10054
+ const Q1div2 = (Q + _1n2) / _2n;
10055
+ return function tonelliSlow(Fp, n) {
10056
+ if (Fp.is0(n))
10057
+ return n;
10058
+ if (FpLegendre(Fp, n) !== 1)
10059
+ throw new Error("Cannot find square root");
10060
+ let M = S;
10061
+ let c = Fp.mul(Fp.ONE, cc);
10062
+ let t = Fp.pow(n, Q);
10063
+ let R = Fp.pow(n, Q1div2);
10064
+ while (!Fp.eql(t, Fp.ONE)) {
10065
+ if (Fp.is0(t))
10066
+ return Fp.ZERO;
10067
+ let i = 1;
10068
+ let t_tmp = Fp.sqr(t);
10069
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
10070
+ i++;
10071
+ t_tmp = Fp.sqr(t_tmp);
10072
+ if (i === M)
10073
+ throw new Error("Cannot find square root");
10074
+ }
10075
+ const exponent = _1n2 << BigInt(M - i - 1);
10076
+ const b = Fp.pow(c, exponent);
10077
+ M = i;
10078
+ c = Fp.sqr(b);
10079
+ t = Fp.mul(t, c);
10080
+ R = Fp.mul(R, b);
10081
+ }
10082
+ return R;
10083
+ };
10084
+ }
10085
+ function FpSqrt(P) {
10086
+ if (P % _4n === _3n)
10087
+ return sqrt3mod4;
10088
+ if (P % _8n === _5n)
10089
+ return sqrt5mod8;
10090
+ if (P % _16n === _9n)
10091
+ return sqrt9mod16(P);
10092
+ return tonelliShanks(P);
10093
+ }
10094
+ var FIELD_FIELDS = [
10095
+ "create",
10096
+ "isValid",
10097
+ "is0",
10098
+ "neg",
10099
+ "inv",
10100
+ "sqrt",
10101
+ "sqr",
10102
+ "eql",
10103
+ "add",
10104
+ "sub",
10105
+ "mul",
10106
+ "pow",
10107
+ "div",
10108
+ "addN",
10109
+ "subN",
10110
+ "mulN",
10111
+ "sqrN"
10112
+ ];
10113
+ function validateField(field) {
10114
+ const initial = {
10115
+ ORDER: "bigint",
10116
+ BYTES: "number",
10117
+ BITS: "number"
10118
+ };
10119
+ const opts = FIELD_FIELDS.reduce((map, val) => {
10120
+ map[val] = "function";
10121
+ return map;
10122
+ }, initial);
10123
+ validateObject(field, opts);
10124
+ return field;
10125
+ }
10126
+ function FpPow(Fp, num, power) {
10127
+ if (power < _0n2)
10128
+ throw new Error("invalid exponent, negatives unsupported");
10129
+ if (power === _0n2)
10130
+ return Fp.ONE;
10131
+ if (power === _1n2)
10132
+ return num;
10133
+ let p = Fp.ONE;
10134
+ let d = num;
10135
+ while (power > _0n2) {
10136
+ if (power & _1n2)
10137
+ p = Fp.mul(p, d);
10138
+ d = Fp.sqr(d);
10139
+ power >>= _1n2;
10140
+ }
10141
+ return p;
10142
+ }
10143
+ function FpInvertBatch(Fp, nums, passZero = false) {
10144
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
10145
+ const multipliedAcc = nums.reduce((acc, num, i) => {
10146
+ if (Fp.is0(num))
10147
+ return acc;
10148
+ inverted[i] = acc;
10149
+ return Fp.mul(acc, num);
10150
+ }, Fp.ONE);
10151
+ const invertedAcc = Fp.inv(multipliedAcc);
10152
+ nums.reduceRight((acc, num, i) => {
10153
+ if (Fp.is0(num))
10154
+ return acc;
10155
+ inverted[i] = Fp.mul(acc, inverted[i]);
10156
+ return Fp.mul(acc, num);
10157
+ }, invertedAcc);
10158
+ return inverted;
10159
+ }
10160
+ function FpLegendre(Fp, n) {
10161
+ const p1mod2 = (Fp.ORDER - _1n2) / _2n;
10162
+ const powered = Fp.pow(n, p1mod2);
10163
+ const yes = Fp.eql(powered, Fp.ONE);
10164
+ const zero = Fp.eql(powered, Fp.ZERO);
10165
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
10166
+ if (!yes && !zero && !no)
10167
+ throw new Error("invalid Legendre symbol result");
10168
+ return yes ? 1 : zero ? 0 : -1;
10169
+ }
10170
+ function nLength(n, nBitLength) {
10171
+ if (nBitLength !== void 0)
10172
+ anumber(nBitLength);
10173
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
10174
+ const nByteLength = Math.ceil(_nBitLength / 8);
10175
+ return { nBitLength: _nBitLength, nByteLength };
10176
+ }
10177
+ var _Field = class {
10178
+ ORDER;
10179
+ BITS;
10180
+ BYTES;
10181
+ isLE;
10182
+ ZERO = _0n2;
10183
+ ONE = _1n2;
10184
+ _lengths;
10185
+ _sqrt;
10186
+ // cached sqrt
10187
+ _mod;
10188
+ constructor(ORDER, opts = {}) {
10189
+ if (ORDER <= _0n2)
10190
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
10191
+ let _nbitLength = void 0;
10192
+ this.isLE = false;
10193
+ if (opts != null && typeof opts === "object") {
10194
+ if (typeof opts.BITS === "number")
10195
+ _nbitLength = opts.BITS;
10196
+ if (typeof opts.sqrt === "function")
10197
+ this.sqrt = opts.sqrt;
10198
+ if (typeof opts.isLE === "boolean")
10199
+ this.isLE = opts.isLE;
10200
+ if (opts.allowedLengths)
10201
+ this._lengths = opts.allowedLengths?.slice();
10202
+ if (typeof opts.modFromBytes === "boolean")
10203
+ this._mod = opts.modFromBytes;
10204
+ }
10205
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
10206
+ if (nByteLength > 2048)
10207
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
10208
+ this.ORDER = ORDER;
10209
+ this.BITS = nBitLength;
10210
+ this.BYTES = nByteLength;
10211
+ this._sqrt = void 0;
10212
+ Object.preventExtensions(this);
10213
+ }
10214
+ create(num) {
10215
+ return mod(num, this.ORDER);
10216
+ }
10217
+ isValid(num) {
10218
+ if (typeof num !== "bigint")
10219
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
10220
+ return _0n2 <= num && num < this.ORDER;
10221
+ }
10222
+ is0(num) {
10223
+ return num === _0n2;
10224
+ }
10225
+ // is valid and invertible
10226
+ isValidNot0(num) {
10227
+ return !this.is0(num) && this.isValid(num);
10228
+ }
10229
+ isOdd(num) {
10230
+ return (num & _1n2) === _1n2;
10231
+ }
10232
+ neg(num) {
10233
+ return mod(-num, this.ORDER);
10234
+ }
10235
+ eql(lhs, rhs) {
10236
+ return lhs === rhs;
10237
+ }
10238
+ sqr(num) {
10239
+ return mod(num * num, this.ORDER);
10240
+ }
10241
+ add(lhs, rhs) {
10242
+ return mod(lhs + rhs, this.ORDER);
10243
+ }
10244
+ sub(lhs, rhs) {
10245
+ return mod(lhs - rhs, this.ORDER);
10246
+ }
10247
+ mul(lhs, rhs) {
10248
+ return mod(lhs * rhs, this.ORDER);
10249
+ }
10250
+ pow(num, power) {
10251
+ return FpPow(this, num, power);
10252
+ }
10253
+ div(lhs, rhs) {
10254
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
10255
+ }
10256
+ // Same as above, but doesn't normalize
10257
+ sqrN(num) {
10258
+ return num * num;
10259
+ }
10260
+ addN(lhs, rhs) {
10261
+ return lhs + rhs;
10262
+ }
10263
+ subN(lhs, rhs) {
10264
+ return lhs - rhs;
10265
+ }
10266
+ mulN(lhs, rhs) {
10267
+ return lhs * rhs;
10268
+ }
10269
+ inv(num) {
10270
+ return invert(num, this.ORDER);
10271
+ }
10272
+ sqrt(num) {
10273
+ if (!this._sqrt)
10274
+ this._sqrt = FpSqrt(this.ORDER);
10275
+ return this._sqrt(this, num);
10276
+ }
10277
+ toBytes(num) {
10278
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
10279
+ }
10280
+ fromBytes(bytes, skipValidation = false) {
10281
+ abytes(bytes);
10282
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
10283
+ if (allowedLengths) {
10284
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
10285
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
10286
+ }
10287
+ const padded = new Uint8Array(BYTES);
10288
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
10289
+ bytes = padded;
10290
+ }
10291
+ if (bytes.length !== BYTES)
10292
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
10293
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
10294
+ if (modFromBytes)
10295
+ scalar = mod(scalar, ORDER);
10296
+ if (!skipValidation) {
10297
+ if (!this.isValid(scalar))
10298
+ throw new Error("invalid field element: outside of range 0..ORDER");
10299
+ }
10300
+ return scalar;
10301
+ }
10302
+ // TODO: we don't need it here, move out to separate fn
10303
+ invertBatch(lst) {
10304
+ return FpInvertBatch(this, lst);
10305
+ }
10306
+ // We can't move this out because Fp6, Fp12 implement it
10307
+ // and it's unclear what to return in there.
10308
+ cmov(a, b, condition) {
10309
+ return condition ? b : a;
10310
+ }
10311
+ };
10312
+ function Field(ORDER, opts = {}) {
10313
+ return new _Field(ORDER, opts);
10314
+ }
10315
+ function getFieldBytesLength(fieldOrder) {
10316
+ if (typeof fieldOrder !== "bigint")
10317
+ throw new Error("field order must be bigint");
10318
+ const bitLength = fieldOrder.toString(2).length;
10319
+ return Math.ceil(bitLength / 8);
10320
+ }
10321
+ function getMinHashLength(fieldOrder) {
10322
+ const length = getFieldBytesLength(fieldOrder);
10323
+ return length + Math.ceil(length / 2);
10324
+ }
10325
+ function mapHashToField(key, fieldOrder, isLE = false) {
10326
+ abytes(key);
10327
+ const len = key.length;
10328
+ const fieldLen = getFieldBytesLength(fieldOrder);
10329
+ const minLen = getMinHashLength(fieldOrder);
10330
+ if (len < 16 || len < minLen || len > 1024)
10331
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
10332
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
10333
+ const reduced = mod(num, fieldOrder - _1n2) + _1n2;
10334
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
10335
+ }
10336
+
10337
+ // node_modules/@noble/curves/abstract/curve.js
10338
+ var _0n3 = /* @__PURE__ */ BigInt(0);
10339
+ var _1n3 = /* @__PURE__ */ BigInt(1);
10340
+ function negateCt(condition, item) {
10341
+ const neg = item.negate();
10342
+ return condition ? neg : item;
10343
+ }
10344
+ function normalizeZ(c, points) {
10345
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
10346
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
10347
+ }
10348
+ function validateW(W, bits) {
10349
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
10350
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
10351
+ }
10352
+ function calcWOpts(W, scalarBits) {
10353
+ validateW(W, scalarBits);
10354
+ const windows = Math.ceil(scalarBits / W) + 1;
10355
+ const windowSize = 2 ** (W - 1);
10356
+ const maxNumber = 2 ** W;
10357
+ const mask = bitMask(W);
10358
+ const shiftBy = BigInt(W);
10359
+ return { windows, windowSize, mask, maxNumber, shiftBy };
10360
+ }
10361
+ function calcOffsets(n, window, wOpts) {
10362
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
10363
+ let wbits = Number(n & mask);
10364
+ let nextN = n >> shiftBy;
10365
+ if (wbits > windowSize) {
10366
+ wbits -= maxNumber;
10367
+ nextN += _1n3;
10368
+ }
10369
+ const offsetStart = window * windowSize;
10370
+ const offset = offsetStart + Math.abs(wbits) - 1;
10371
+ const isZero = wbits === 0;
10372
+ const isNeg = wbits < 0;
10373
+ const isNegF = window % 2 !== 0;
10374
+ const offsetF = offsetStart;
10375
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
10376
+ }
10377
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
10378
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
10379
+ function getW(P) {
10380
+ return pointWindowSizes.get(P) || 1;
10381
+ }
10382
+ function assert0(n) {
10383
+ if (n !== _0n3)
10384
+ throw new Error("invalid wNAF");
10385
+ }
10386
+ var wNAF = class {
10387
+ BASE;
10388
+ ZERO;
10389
+ Fn;
10390
+ bits;
10391
+ // Parametrized with a given Point class (not individual point)
10392
+ constructor(Point, bits) {
10393
+ this.BASE = Point.BASE;
10394
+ this.ZERO = Point.ZERO;
10395
+ this.Fn = Point.Fn;
10396
+ this.bits = bits;
10397
+ }
10398
+ // non-const time multiplication ladder
10399
+ _unsafeLadder(elm, n, p = this.ZERO) {
10400
+ let d = elm;
10401
+ while (n > _0n3) {
10402
+ if (n & _1n3)
10403
+ p = p.add(d);
10404
+ d = d.double();
10405
+ n >>= _1n3;
10406
+ }
10407
+ return p;
10408
+ }
10409
+ /**
10410
+ * Creates a wNAF precomputation window. Used for caching.
10411
+ * Default window size is set by `utils.precompute()` and is equal to 8.
10412
+ * Number of precomputed points depends on the curve size:
10413
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
10414
+ * - 𝑊 is the window size
10415
+ * - 𝑛 is the bitlength of the curve order.
10416
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
10417
+ * @param point Point instance
10418
+ * @param W window size
10419
+ * @returns precomputed point tables flattened to a single array
10420
+ */
10421
+ precomputeWindow(point, W) {
10422
+ const { windows, windowSize } = calcWOpts(W, this.bits);
10423
+ const points = [];
10424
+ let p = point;
10425
+ let base = p;
10426
+ for (let window = 0; window < windows; window++) {
10427
+ base = p;
10428
+ points.push(base);
10429
+ for (let i = 1; i < windowSize; i++) {
10430
+ base = base.add(p);
10431
+ points.push(base);
10432
+ }
10433
+ p = base.double();
10434
+ }
10435
+ return points;
10436
+ }
10437
+ /**
10438
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
10439
+ * More compact implementation:
10440
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
10441
+ * @returns real and fake (for const-time) points
10442
+ */
10443
+ wNAF(W, precomputes, n) {
10444
+ if (!this.Fn.isValid(n))
10445
+ throw new Error("invalid scalar");
10446
+ let p = this.ZERO;
10447
+ let f = this.BASE;
10448
+ const wo = calcWOpts(W, this.bits);
10449
+ for (let window = 0; window < wo.windows; window++) {
10450
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
10451
+ n = nextN;
10452
+ if (isZero) {
10453
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
10454
+ } else {
10455
+ p = p.add(negateCt(isNeg, precomputes[offset]));
10456
+ }
10457
+ }
10458
+ assert0(n);
10459
+ return { p, f };
10460
+ }
10461
+ /**
10462
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
10463
+ * @param acc accumulator point to add result of multiplication
10464
+ * @returns point
10465
+ */
10466
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
10467
+ const wo = calcWOpts(W, this.bits);
10468
+ for (let window = 0; window < wo.windows; window++) {
10469
+ if (n === _0n3)
10470
+ break;
10471
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
10472
+ n = nextN;
10473
+ if (isZero) {
10474
+ continue;
10475
+ } else {
10476
+ const item = precomputes[offset];
10477
+ acc = acc.add(isNeg ? item.negate() : item);
10478
+ }
10479
+ }
10480
+ assert0(n);
10481
+ return acc;
10482
+ }
10483
+ getPrecomputes(W, point, transform) {
10484
+ let comp = pointPrecomputes.get(point);
10485
+ if (!comp) {
10486
+ comp = this.precomputeWindow(point, W);
10487
+ if (W !== 1) {
10488
+ if (typeof transform === "function")
10489
+ comp = transform(comp);
10490
+ pointPrecomputes.set(point, comp);
10491
+ }
10492
+ }
10493
+ return comp;
10494
+ }
10495
+ cached(point, scalar, transform) {
10496
+ const W = getW(point);
10497
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
10498
+ }
10499
+ unsafe(point, scalar, transform, prev) {
10500
+ const W = getW(point);
10501
+ if (W === 1)
10502
+ return this._unsafeLadder(point, scalar, prev);
10503
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
10504
+ }
10505
+ // We calculate precomputes for elliptic curve point multiplication
10506
+ // using windowed method. This specifies window size and
10507
+ // stores precomputed values. Usually only base point would be precomputed.
10508
+ createCache(P, W) {
10509
+ validateW(W, this.bits);
10510
+ pointWindowSizes.set(P, W);
10511
+ pointPrecomputes.delete(P);
10512
+ }
10513
+ hasCache(elm) {
10514
+ return getW(elm) !== 1;
10515
+ }
10516
+ };
10517
+ function mulEndoUnsafe(Point, point, k1, k2) {
10518
+ let acc = point;
10519
+ let p1 = Point.ZERO;
10520
+ let p2 = Point.ZERO;
10521
+ while (k1 > _0n3 || k2 > _0n3) {
10522
+ if (k1 & _1n3)
10523
+ p1 = p1.add(acc);
10524
+ if (k2 & _1n3)
10525
+ p2 = p2.add(acc);
10526
+ acc = acc.double();
10527
+ k1 >>= _1n3;
10528
+ k2 >>= _1n3;
10529
+ }
10530
+ return { p1, p2 };
10531
+ }
10532
+ function createField(order, field, isLE) {
10533
+ if (field) {
10534
+ if (field.ORDER !== order)
10535
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
10536
+ validateField(field);
10537
+ return field;
10538
+ } else {
10539
+ return Field(order, { isLE });
10540
+ }
10541
+ }
10542
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
10543
+ if (FpFnLE === void 0)
10544
+ FpFnLE = type === "edwards";
10545
+ if (!CURVE || typeof CURVE !== "object")
10546
+ throw new Error(`expected valid ${type} CURVE object`);
10547
+ for (const p of ["p", "n", "h"]) {
10548
+ const val = CURVE[p];
10549
+ if (!(typeof val === "bigint" && val > _0n3))
10550
+ throw new Error(`CURVE.${p} must be positive bigint`);
10551
+ }
10552
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
10553
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
10554
+ const _b = type === "weierstrass" ? "b" : "d";
10555
+ const params = ["Gx", "Gy", "a", _b];
10556
+ for (const p of params) {
10557
+ if (!Fp.isValid(CURVE[p]))
10558
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
10559
+ }
10560
+ CURVE = Object.freeze(Object.assign({}, CURVE));
10561
+ return { CURVE, Fp, Fn };
10562
+ }
10563
+ function createKeygen(randomSecretKey, getPublicKey2) {
10564
+ return function keygen(seed) {
10565
+ const secretKey = randomSecretKey(seed);
10566
+ return { secretKey, publicKey: getPublicKey2(secretKey) };
10567
+ };
10568
+ }
10569
+
10570
+ // node_modules/@noble/hashes/hmac.js
10571
+ var _HMAC = class {
10572
+ oHash;
10573
+ iHash;
10574
+ blockLen;
10575
+ outputLen;
10576
+ finished = false;
10577
+ destroyed = false;
10578
+ constructor(hash, key) {
10579
+ ahash(hash);
10580
+ abytes(key, void 0, "key");
10581
+ this.iHash = hash.create();
10582
+ if (typeof this.iHash.update !== "function")
10583
+ throw new Error("Expected instance of class which extends utils.Hash");
10584
+ this.blockLen = this.iHash.blockLen;
10585
+ this.outputLen = this.iHash.outputLen;
10586
+ const blockLen = this.blockLen;
10587
+ const pad = new Uint8Array(blockLen);
10588
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
10589
+ for (let i = 0; i < pad.length; i++)
10590
+ pad[i] ^= 54;
10591
+ this.iHash.update(pad);
10592
+ this.oHash = hash.create();
10593
+ for (let i = 0; i < pad.length; i++)
10594
+ pad[i] ^= 54 ^ 92;
10595
+ this.oHash.update(pad);
10596
+ clean(pad);
10597
+ }
10598
+ update(buf) {
10599
+ aexists(this);
10600
+ this.iHash.update(buf);
10601
+ return this;
10602
+ }
10603
+ digestInto(out) {
10604
+ aexists(this);
10605
+ abytes(out, this.outputLen, "output");
10606
+ this.finished = true;
10607
+ this.iHash.digestInto(out);
10608
+ this.oHash.update(out);
10609
+ this.oHash.digestInto(out);
10610
+ this.destroy();
10611
+ }
10612
+ digest() {
10613
+ const out = new Uint8Array(this.oHash.outputLen);
10614
+ this.digestInto(out);
10615
+ return out;
10616
+ }
10617
+ _cloneInto(to) {
10618
+ to ||= Object.create(Object.getPrototypeOf(this), {});
10619
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
10620
+ to = to;
10621
+ to.finished = finished;
10622
+ to.destroyed = destroyed;
10623
+ to.blockLen = blockLen;
10624
+ to.outputLen = outputLen;
10625
+ to.oHash = oHash._cloneInto(to.oHash);
10626
+ to.iHash = iHash._cloneInto(to.iHash);
10627
+ return to;
10628
+ }
10629
+ clone() {
10630
+ return this._cloneInto();
10631
+ }
10632
+ destroy() {
10633
+ this.destroyed = true;
10634
+ this.oHash.destroy();
10635
+ this.iHash.destroy();
10636
+ }
10637
+ };
10638
+ var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
10639
+ hmac.create = (hash, key) => new _HMAC(hash, key);
10640
+
10641
+ // node_modules/@noble/curves/abstract/weierstrass.js
10642
+ var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
10643
+ function _splitEndoScalar(k, basis, n) {
10644
+ const [[a1, b1], [a2, b2]] = basis;
10645
+ const c1 = divNearest(b2 * k, n);
10646
+ const c2 = divNearest(-b1 * k, n);
10647
+ let k1 = k - c1 * a1 - c2 * a2;
10648
+ let k2 = -c1 * b1 - c2 * b2;
10649
+ const k1neg = k1 < _0n4;
10650
+ const k2neg = k2 < _0n4;
10651
+ if (k1neg)
10652
+ k1 = -k1;
10653
+ if (k2neg)
10654
+ k2 = -k2;
10655
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
10656
+ if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
10657
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
10658
+ }
10659
+ return { k1neg, k1, k2neg, k2 };
10660
+ }
10661
+ function validateSigFormat(format) {
10662
+ if (!["compact", "recovered", "der"].includes(format))
10663
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
10664
+ return format;
10665
+ }
10666
+ function validateSigOpts(opts, def) {
10667
+ const optsn = {};
10668
+ for (let optName of Object.keys(def)) {
10669
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
10670
+ }
10671
+ abool(optsn.lowS, "lowS");
10672
+ abool(optsn.prehash, "prehash");
10673
+ if (optsn.format !== void 0)
10674
+ validateSigFormat(optsn.format);
10675
+ return optsn;
10676
+ }
10677
+ var DERErr = class extends Error {
10678
+ constructor(m = "") {
10679
+ super(m);
10680
+ }
10681
+ };
10682
+ var DER = {
10683
+ // asn.1 DER encoding utils
10684
+ Err: DERErr,
10685
+ // Basic building block is TLV (Tag-Length-Value)
10686
+ _tlv: {
10687
+ encode: (tag, data) => {
10688
+ const { Err: E } = DER;
10689
+ if (tag < 0 || tag > 256)
10690
+ throw new E("tlv.encode: wrong tag");
10691
+ if (data.length & 1)
10692
+ throw new E("tlv.encode: unpadded data");
10693
+ const dataLen = data.length / 2;
10694
+ const len = numberToHexUnpadded(dataLen);
10695
+ if (len.length / 2 & 128)
10696
+ throw new E("tlv.encode: long form length too big");
10697
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
10698
+ const t = numberToHexUnpadded(tag);
10699
+ return t + lenLen + len + data;
10700
+ },
10701
+ // v - value, l - left bytes (unparsed)
10702
+ decode(tag, data) {
10703
+ const { Err: E } = DER;
10704
+ let pos = 0;
10705
+ if (tag < 0 || tag > 256)
10706
+ throw new E("tlv.encode: wrong tag");
10707
+ if (data.length < 2 || data[pos++] !== tag)
10708
+ throw new E("tlv.decode: wrong tlv");
10709
+ const first = data[pos++];
10710
+ const isLong = !!(first & 128);
10711
+ let length = 0;
10712
+ if (!isLong)
10713
+ length = first;
10714
+ else {
10715
+ const lenLen = first & 127;
10716
+ if (!lenLen)
10717
+ throw new E("tlv.decode(long): indefinite length not supported");
10718
+ if (lenLen > 4)
10719
+ throw new E("tlv.decode(long): byte length is too big");
10720
+ const lengthBytes = data.subarray(pos, pos + lenLen);
10721
+ if (lengthBytes.length !== lenLen)
10722
+ throw new E("tlv.decode: length bytes not complete");
10723
+ if (lengthBytes[0] === 0)
10724
+ throw new E("tlv.decode(long): zero leftmost byte");
10725
+ for (const b of lengthBytes)
10726
+ length = length << 8 | b;
10727
+ pos += lenLen;
10728
+ if (length < 128)
10729
+ throw new E("tlv.decode(long): not minimal encoding");
10730
+ }
10731
+ const v = data.subarray(pos, pos + length);
10732
+ if (v.length !== length)
10733
+ throw new E("tlv.decode: wrong value length");
10734
+ return { v, l: data.subarray(pos + length) };
10735
+ }
10736
+ },
10737
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
10738
+ // since we always use positive integers here. It must always be empty:
10739
+ // - add zero byte if exists
10740
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
10741
+ _int: {
10742
+ encode(num) {
10743
+ const { Err: E } = DER;
10744
+ if (num < _0n4)
10745
+ throw new E("integer: negative integers are not allowed");
10746
+ let hex = numberToHexUnpadded(num);
10747
+ if (Number.parseInt(hex[0], 16) & 8)
10748
+ hex = "00" + hex;
10749
+ if (hex.length & 1)
10750
+ throw new E("unexpected DER parsing assertion: unpadded hex");
10751
+ return hex;
10752
+ },
10753
+ decode(data) {
10754
+ const { Err: E } = DER;
10755
+ if (data[0] & 128)
10756
+ throw new E("invalid signature integer: negative");
10757
+ if (data[0] === 0 && !(data[1] & 128))
10758
+ throw new E("invalid signature integer: unnecessary leading zero");
10759
+ return bytesToNumberBE(data);
10760
+ }
10761
+ },
10762
+ toSig(bytes) {
10763
+ const { Err: E, _int: int, _tlv: tlv } = DER;
10764
+ const data = abytes(bytes, void 0, "signature");
10765
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
10766
+ if (seqLeftBytes.length)
10767
+ throw new E("invalid signature: left bytes after parsing");
10768
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
10769
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
10770
+ if (sLeftBytes.length)
10771
+ throw new E("invalid signature: left bytes after parsing");
10772
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
10773
+ },
10774
+ hexFromSig(sig) {
10775
+ const { _tlv: tlv, _int: int } = DER;
10776
+ const rs = tlv.encode(2, int.encode(sig.r));
10777
+ const ss = tlv.encode(2, int.encode(sig.s));
10778
+ const seq = rs + ss;
10779
+ return tlv.encode(48, seq);
10780
+ }
10781
+ };
10782
+ var _0n4 = BigInt(0);
10783
+ var _1n4 = BigInt(1);
10784
+ var _2n2 = BigInt(2);
10785
+ var _3n2 = BigInt(3);
10786
+ var _4n2 = BigInt(4);
10787
+ function weierstrass(params, extraOpts = {}) {
10788
+ const validated = createCurveFields("weierstrass", params, extraOpts);
10789
+ const { Fp, Fn } = validated;
10790
+ let CURVE = validated.CURVE;
10791
+ const { h: cofactor, n: CURVE_ORDER2 } = CURVE;
10792
+ validateObject(extraOpts, {}, {
10793
+ allowInfinityPoint: "boolean",
10794
+ clearCofactor: "function",
10795
+ isTorsionFree: "function",
10796
+ fromBytes: "function",
10797
+ toBytes: "function",
10798
+ endo: "object"
10799
+ });
10800
+ const { endo } = extraOpts;
10801
+ if (endo) {
10802
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
10803
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
10804
+ }
10805
+ }
10806
+ const lengths = getWLengths(Fp, Fn);
10807
+ function assertCompressionIsSupported() {
10808
+ if (!Fp.isOdd)
10809
+ throw new Error("compression is not supported: Field does not have .isOdd()");
10810
+ }
10811
+ function pointToBytes(_c, point, isCompressed) {
10812
+ const { x, y } = point.toAffine();
10813
+ const bx = Fp.toBytes(x);
10814
+ abool(isCompressed, "isCompressed");
10815
+ if (isCompressed) {
10816
+ assertCompressionIsSupported();
10817
+ const hasEvenY = !Fp.isOdd(y);
10818
+ return concatBytes(pprefix(hasEvenY), bx);
10819
+ } else {
10820
+ return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
10821
+ }
10822
+ }
10823
+ function pointFromBytes(bytes) {
10824
+ abytes(bytes, void 0, "Point");
10825
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
10826
+ const length = bytes.length;
10827
+ const head = bytes[0];
10828
+ const tail = bytes.subarray(1);
10829
+ if (length === comp && (head === 2 || head === 3)) {
10830
+ const x = Fp.fromBytes(tail);
10831
+ if (!Fp.isValid(x))
10832
+ throw new Error("bad point: is not on curve, wrong x");
10833
+ const y2 = weierstrassEquation(x);
10834
+ let y;
10835
+ try {
10836
+ y = Fp.sqrt(y2);
10837
+ } catch (sqrtError) {
10838
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
10839
+ throw new Error("bad point: is not on curve, sqrt error" + err);
10840
+ }
10841
+ assertCompressionIsSupported();
10842
+ const evenY = Fp.isOdd(y);
10843
+ const evenH = (head & 1) === 1;
10844
+ if (evenH !== evenY)
10845
+ y = Fp.neg(y);
10846
+ return { x, y };
10847
+ } else if (length === uncomp && head === 4) {
10848
+ const L = Fp.BYTES;
10849
+ const x = Fp.fromBytes(tail.subarray(0, L));
10850
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
10851
+ if (!isValidXY(x, y))
10852
+ throw new Error("bad point: is not on curve");
10853
+ return { x, y };
10854
+ } else {
10855
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
10856
+ }
10857
+ }
10858
+ const encodePoint = extraOpts.toBytes || pointToBytes;
10859
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
10860
+ function weierstrassEquation(x) {
10861
+ const x2 = Fp.sqr(x);
10862
+ const x3 = Fp.mul(x2, x);
10863
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
10864
+ }
10865
+ function isValidXY(x, y) {
10866
+ const left = Fp.sqr(y);
10867
+ const right = weierstrassEquation(x);
10868
+ return Fp.eql(left, right);
10869
+ }
10870
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
10871
+ throw new Error("bad curve params: generator point");
10872
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
10873
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
10874
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
10875
+ throw new Error("bad curve params: a or b");
10876
+ function acoord(title, n, banZero = false) {
10877
+ if (!Fp.isValid(n) || banZero && Fp.is0(n))
10878
+ throw new Error(`bad point coordinate ${title}`);
10879
+ return n;
10880
+ }
10881
+ function aprjpoint(other) {
10882
+ if (!(other instanceof Point))
10883
+ throw new Error("Weierstrass Point expected");
10884
+ }
10885
+ function splitEndoScalarN(k) {
10886
+ if (!endo || !endo.basises)
10887
+ throw new Error("no endo");
10888
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
10889
+ }
10890
+ const toAffineMemo = memoized((p, iz) => {
10891
+ const { X, Y, Z } = p;
10892
+ if (Fp.eql(Z, Fp.ONE))
10893
+ return { x: X, y: Y };
10894
+ const is0 = p.is0();
10895
+ if (iz == null)
10896
+ iz = is0 ? Fp.ONE : Fp.inv(Z);
10897
+ const x = Fp.mul(X, iz);
10898
+ const y = Fp.mul(Y, iz);
10899
+ const zz = Fp.mul(Z, iz);
10900
+ if (is0)
10901
+ return { x: Fp.ZERO, y: Fp.ZERO };
10902
+ if (!Fp.eql(zz, Fp.ONE))
10903
+ throw new Error("invZ was invalid");
10904
+ return { x, y };
10905
+ });
10906
+ const assertValidMemo = memoized((p) => {
10907
+ if (p.is0()) {
10908
+ if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
10909
+ return;
10910
+ throw new Error("bad point: ZERO");
10911
+ }
10912
+ const { x, y } = p.toAffine();
10913
+ if (!Fp.isValid(x) || !Fp.isValid(y))
10914
+ throw new Error("bad point: x or y not field elements");
10915
+ if (!isValidXY(x, y))
10916
+ throw new Error("bad point: equation left != right");
10917
+ if (!p.isTorsionFree())
10918
+ throw new Error("bad point: not in prime-order subgroup");
10919
+ return true;
10920
+ });
10921
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
10922
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
10923
+ k1p = negateCt(k1neg, k1p);
10924
+ k2p = negateCt(k2neg, k2p);
10925
+ return k1p.add(k2p);
10926
+ }
10927
+ class Point {
10928
+ // base / generator point
10929
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
10930
+ // zero / infinity / identity point
10931
+ static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
10932
+ // 0, 1, 0
10933
+ // math field
10934
+ static Fp = Fp;
10935
+ // scalar field
10936
+ static Fn = Fn;
10937
+ X;
10938
+ Y;
10939
+ Z;
10940
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
10941
+ constructor(X, Y, Z) {
10942
+ this.X = acoord("x", X);
10943
+ this.Y = acoord("y", Y, true);
10944
+ this.Z = acoord("z", Z);
10945
+ Object.freeze(this);
10946
+ }
10947
+ static CURVE() {
10948
+ return CURVE;
10949
+ }
10950
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
10951
+ static fromAffine(p) {
10952
+ const { x, y } = p || {};
10953
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
10954
+ throw new Error("invalid affine point");
10955
+ if (p instanceof Point)
10956
+ throw new Error("projective point not allowed");
10957
+ if (Fp.is0(x) && Fp.is0(y))
10958
+ return Point.ZERO;
10959
+ return new Point(x, y, Fp.ONE);
10960
+ }
10961
+ static fromBytes(bytes) {
10962
+ const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
10963
+ P.assertValidity();
10964
+ return P;
10965
+ }
10966
+ static fromHex(hex) {
10967
+ return Point.fromBytes(hexToBytes2(hex));
10968
+ }
10969
+ get x() {
10970
+ return this.toAffine().x;
10971
+ }
10972
+ get y() {
10973
+ return this.toAffine().y;
10974
+ }
10975
+ /**
10976
+ *
10977
+ * @param windowSize
10978
+ * @param isLazy true will defer table computation until the first multiplication
10979
+ * @returns
10980
+ */
10981
+ precompute(windowSize = 8, isLazy = true) {
10982
+ wnaf.createCache(this, windowSize);
10983
+ if (!isLazy)
10984
+ this.multiply(_3n2);
10985
+ return this;
10986
+ }
10987
+ // TODO: return `this`
10988
+ /** A point on curve is valid if it conforms to equation. */
10989
+ assertValidity() {
10990
+ assertValidMemo(this);
10991
+ }
10992
+ hasEvenY() {
10993
+ const { y } = this.toAffine();
10994
+ if (!Fp.isOdd)
10995
+ throw new Error("Field doesn't support isOdd");
10996
+ return !Fp.isOdd(y);
10997
+ }
10998
+ /** Compare one point to another. */
10999
+ equals(other) {
11000
+ aprjpoint(other);
11001
+ const { X: X1, Y: Y1, Z: Z1 } = this;
11002
+ const { X: X2, Y: Y2, Z: Z2 } = other;
11003
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
11004
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
11005
+ return U1 && U2;
11006
+ }
11007
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
11008
+ negate() {
11009
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
11010
+ }
11011
+ // Renes-Costello-Batina exception-free doubling formula.
11012
+ // There is 30% faster Jacobian formula, but it is not complete.
11013
+ // https://eprint.iacr.org/2015/1060, algorithm 3
11014
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
11015
+ double() {
11016
+ const { a, b } = CURVE;
11017
+ const b3 = Fp.mul(b, _3n2);
11018
+ const { X: X1, Y: Y1, Z: Z1 } = this;
11019
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
11020
+ let t0 = Fp.mul(X1, X1);
11021
+ let t1 = Fp.mul(Y1, Y1);
11022
+ let t2 = Fp.mul(Z1, Z1);
11023
+ let t3 = Fp.mul(X1, Y1);
11024
+ t3 = Fp.add(t3, t3);
11025
+ Z3 = Fp.mul(X1, Z1);
11026
+ Z3 = Fp.add(Z3, Z3);
11027
+ X3 = Fp.mul(a, Z3);
11028
+ Y3 = Fp.mul(b3, t2);
11029
+ Y3 = Fp.add(X3, Y3);
11030
+ X3 = Fp.sub(t1, Y3);
11031
+ Y3 = Fp.add(t1, Y3);
11032
+ Y3 = Fp.mul(X3, Y3);
11033
+ X3 = Fp.mul(t3, X3);
11034
+ Z3 = Fp.mul(b3, Z3);
11035
+ t2 = Fp.mul(a, t2);
11036
+ t3 = Fp.sub(t0, t2);
11037
+ t3 = Fp.mul(a, t3);
11038
+ t3 = Fp.add(t3, Z3);
11039
+ Z3 = Fp.add(t0, t0);
11040
+ t0 = Fp.add(Z3, t0);
11041
+ t0 = Fp.add(t0, t2);
11042
+ t0 = Fp.mul(t0, t3);
11043
+ Y3 = Fp.add(Y3, t0);
11044
+ t2 = Fp.mul(Y1, Z1);
11045
+ t2 = Fp.add(t2, t2);
11046
+ t0 = Fp.mul(t2, t3);
11047
+ X3 = Fp.sub(X3, t0);
11048
+ Z3 = Fp.mul(t2, t1);
11049
+ Z3 = Fp.add(Z3, Z3);
11050
+ Z3 = Fp.add(Z3, Z3);
11051
+ return new Point(X3, Y3, Z3);
11052
+ }
11053
+ // Renes-Costello-Batina exception-free addition formula.
11054
+ // There is 30% faster Jacobian formula, but it is not complete.
11055
+ // https://eprint.iacr.org/2015/1060, algorithm 1
11056
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
11057
+ add(other) {
11058
+ aprjpoint(other);
11059
+ const { X: X1, Y: Y1, Z: Z1 } = this;
11060
+ const { X: X2, Y: Y2, Z: Z2 } = other;
11061
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
11062
+ const a = CURVE.a;
11063
+ const b3 = Fp.mul(CURVE.b, _3n2);
11064
+ let t0 = Fp.mul(X1, X2);
11065
+ let t1 = Fp.mul(Y1, Y2);
11066
+ let t2 = Fp.mul(Z1, Z2);
11067
+ let t3 = Fp.add(X1, Y1);
11068
+ let t4 = Fp.add(X2, Y2);
11069
+ t3 = Fp.mul(t3, t4);
11070
+ t4 = Fp.add(t0, t1);
11071
+ t3 = Fp.sub(t3, t4);
11072
+ t4 = Fp.add(X1, Z1);
11073
+ let t5 = Fp.add(X2, Z2);
11074
+ t4 = Fp.mul(t4, t5);
11075
+ t5 = Fp.add(t0, t2);
11076
+ t4 = Fp.sub(t4, t5);
11077
+ t5 = Fp.add(Y1, Z1);
11078
+ X3 = Fp.add(Y2, Z2);
11079
+ t5 = Fp.mul(t5, X3);
11080
+ X3 = Fp.add(t1, t2);
11081
+ t5 = Fp.sub(t5, X3);
11082
+ Z3 = Fp.mul(a, t4);
11083
+ X3 = Fp.mul(b3, t2);
11084
+ Z3 = Fp.add(X3, Z3);
11085
+ X3 = Fp.sub(t1, Z3);
11086
+ Z3 = Fp.add(t1, Z3);
11087
+ Y3 = Fp.mul(X3, Z3);
11088
+ t1 = Fp.add(t0, t0);
11089
+ t1 = Fp.add(t1, t0);
11090
+ t2 = Fp.mul(a, t2);
11091
+ t4 = Fp.mul(b3, t4);
11092
+ t1 = Fp.add(t1, t2);
11093
+ t2 = Fp.sub(t0, t2);
11094
+ t2 = Fp.mul(a, t2);
11095
+ t4 = Fp.add(t4, t2);
11096
+ t0 = Fp.mul(t1, t4);
11097
+ Y3 = Fp.add(Y3, t0);
11098
+ t0 = Fp.mul(t5, t4);
11099
+ X3 = Fp.mul(t3, X3);
11100
+ X3 = Fp.sub(X3, t0);
11101
+ t0 = Fp.mul(t3, t1);
11102
+ Z3 = Fp.mul(t5, Z3);
11103
+ Z3 = Fp.add(Z3, t0);
11104
+ return new Point(X3, Y3, Z3);
11105
+ }
11106
+ subtract(other) {
11107
+ return this.add(other.negate());
11108
+ }
11109
+ is0() {
11110
+ return this.equals(Point.ZERO);
11111
+ }
11112
+ /**
11113
+ * Constant time multiplication.
11114
+ * Uses wNAF method. Windowed method may be 10% faster,
11115
+ * but takes 2x longer to generate and consumes 2x memory.
11116
+ * Uses precomputes when available.
11117
+ * Uses endomorphism for Koblitz curves.
11118
+ * @param scalar by which the point would be multiplied
11119
+ * @returns New point
11120
+ */
11121
+ multiply(scalar) {
11122
+ const { endo: endo2 } = extraOpts;
11123
+ if (!Fn.isValidNot0(scalar))
11124
+ throw new Error("invalid scalar: out of range");
11125
+ let point, fake;
11126
+ const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
11127
+ if (endo2) {
11128
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
11129
+ const { p: k1p, f: k1f } = mul(k1);
11130
+ const { p: k2p, f: k2f } = mul(k2);
11131
+ fake = k1f.add(k2f);
11132
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
11133
+ } else {
11134
+ const { p, f } = mul(scalar);
11135
+ point = p;
11136
+ fake = f;
11137
+ }
11138
+ return normalizeZ(Point, [point, fake])[0];
11139
+ }
11140
+ /**
11141
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
11142
+ * It's faster, but should only be used when you don't care about
11143
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
11144
+ */
11145
+ multiplyUnsafe(sc) {
11146
+ const { endo: endo2 } = extraOpts;
11147
+ const p = this;
11148
+ if (!Fn.isValid(sc))
11149
+ throw new Error("invalid scalar: out of range");
11150
+ if (sc === _0n4 || p.is0())
11151
+ return Point.ZERO;
11152
+ if (sc === _1n4)
11153
+ return p;
11154
+ if (wnaf.hasCache(this))
11155
+ return this.multiply(sc);
11156
+ if (endo2) {
11157
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
11158
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
11159
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
11160
+ } else {
11161
+ return wnaf.unsafe(p, sc);
11162
+ }
11163
+ }
11164
+ /**
11165
+ * Converts Projective point to affine (x, y) coordinates.
11166
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
11167
+ */
11168
+ toAffine(invertedZ) {
11169
+ return toAffineMemo(this, invertedZ);
11170
+ }
11171
+ /**
11172
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
11173
+ * Always torsion-free for cofactor=1 curves.
11174
+ */
11175
+ isTorsionFree() {
11176
+ const { isTorsionFree } = extraOpts;
11177
+ if (cofactor === _1n4)
11178
+ return true;
11179
+ if (isTorsionFree)
11180
+ return isTorsionFree(Point, this);
11181
+ return wnaf.unsafe(this, CURVE_ORDER2).is0();
11182
+ }
11183
+ clearCofactor() {
11184
+ const { clearCofactor } = extraOpts;
11185
+ if (cofactor === _1n4)
11186
+ return this;
11187
+ if (clearCofactor)
11188
+ return clearCofactor(Point, this);
11189
+ return this.multiplyUnsafe(cofactor);
11190
+ }
11191
+ isSmallOrder() {
11192
+ return this.multiplyUnsafe(cofactor).is0();
11193
+ }
11194
+ toBytes(isCompressed = true) {
11195
+ abool(isCompressed, "isCompressed");
11196
+ this.assertValidity();
11197
+ return encodePoint(Point, this, isCompressed);
11198
+ }
11199
+ toHex(isCompressed = true) {
11200
+ return bytesToHex4(this.toBytes(isCompressed));
11201
+ }
11202
+ toString() {
11203
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
11204
+ }
11205
+ }
11206
+ const bits = Fn.BITS;
11207
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
11208
+ Point.BASE.precompute(8);
11209
+ return Point;
11210
+ }
11211
+ function pprefix(hasEvenY) {
11212
+ return Uint8Array.of(hasEvenY ? 2 : 3);
11213
+ }
11214
+ function getWLengths(Fp, Fn) {
11215
+ return {
11216
+ secretKey: Fn.BYTES,
11217
+ publicKey: 1 + Fp.BYTES,
11218
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
11219
+ publicKeyHasPrefix: true,
11220
+ signature: 2 * Fn.BYTES
11221
+ };
11222
+ }
11223
+ function ecdh(Point, ecdhOpts = {}) {
11224
+ const { Fn } = Point;
11225
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
11226
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
11227
+ function isValidSecretKey(secretKey) {
11228
+ try {
11229
+ const num = Fn.fromBytes(secretKey);
11230
+ return Fn.isValidNot0(num);
11231
+ } catch (error) {
11232
+ return false;
11233
+ }
11234
+ }
11235
+ function isValidPublicKey(publicKey, isCompressed) {
11236
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
11237
+ try {
11238
+ const l = publicKey.length;
11239
+ if (isCompressed === true && l !== comp)
11240
+ return false;
11241
+ if (isCompressed === false && l !== publicKeyUncompressed)
11242
+ return false;
11243
+ return !!Point.fromBytes(publicKey);
11244
+ } catch (error) {
11245
+ return false;
11246
+ }
11247
+ }
11248
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
11249
+ return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
11250
+ }
11251
+ function getPublicKey2(secretKey, isCompressed = true) {
11252
+ return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
11253
+ }
11254
+ function isProbPub(item) {
11255
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
11256
+ if (!isBytes(item))
11257
+ return void 0;
11258
+ if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
11259
+ return void 0;
11260
+ const l = abytes(item, void 0, "key").length;
11261
+ return l === publicKey || l === publicKeyUncompressed;
11262
+ }
11263
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
11264
+ if (isProbPub(secretKeyA) === true)
11265
+ throw new Error("first arg must be private key");
11266
+ if (isProbPub(publicKeyB) === false)
11267
+ throw new Error("second arg must be public key");
11268
+ const s = Fn.fromBytes(secretKeyA);
11269
+ const b = Point.fromBytes(publicKeyB);
11270
+ return b.multiply(s).toBytes(isCompressed);
11271
+ }
11272
+ const utils = {
11273
+ isValidSecretKey,
11274
+ isValidPublicKey,
11275
+ randomSecretKey
11276
+ };
11277
+ const keygen = createKeygen(randomSecretKey, getPublicKey2);
11278
+ return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
11279
+ }
11280
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
11281
+ ahash(hash);
11282
+ validateObject(ecdsaOpts, {}, {
11283
+ hmac: "function",
11284
+ lowS: "boolean",
11285
+ randomBytes: "function",
11286
+ bits2int: "function",
11287
+ bits2int_modN: "function"
11288
+ });
11289
+ ecdsaOpts = Object.assign({}, ecdsaOpts);
11290
+ const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
11291
+ const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
11292
+ const { Fp, Fn } = Point;
11293
+ const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn;
11294
+ const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
11295
+ const defaultSigOpts = {
11296
+ prehash: true,
11297
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
11298
+ format: "compact",
11299
+ extraEntropy: false
11300
+ };
11301
+ const hasLargeCofactor = CURVE_ORDER2 * _2n2 < Fp.ORDER;
11302
+ function isBiggerThanHalfOrder(number) {
11303
+ const HALF = CURVE_ORDER2 >> _1n4;
11304
+ return number > HALF;
11305
+ }
11306
+ function validateRS(title, num) {
11307
+ if (!Fn.isValidNot0(num))
11308
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
11309
+ return num;
11310
+ }
11311
+ function assertSmallCofactor() {
11312
+ if (hasLargeCofactor)
11313
+ throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
11314
+ }
11315
+ function validateSigLength(bytes, format) {
11316
+ validateSigFormat(format);
11317
+ const size = lengths.signature;
11318
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
11319
+ return abytes(bytes, sizer);
11320
+ }
11321
+ class Signature {
11322
+ r;
11323
+ s;
11324
+ recovery;
11325
+ constructor(r, s, recovery) {
11326
+ this.r = validateRS("r", r);
11327
+ this.s = validateRS("s", s);
11328
+ if (recovery != null) {
11329
+ assertSmallCofactor();
11330
+ if (![0, 1, 2, 3].includes(recovery))
11331
+ throw new Error("invalid recovery id");
11332
+ this.recovery = recovery;
11333
+ }
11334
+ Object.freeze(this);
11335
+ }
11336
+ static fromBytes(bytes, format = defaultSigOpts.format) {
11337
+ validateSigLength(bytes, format);
11338
+ let recid;
11339
+ if (format === "der") {
11340
+ const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
11341
+ return new Signature(r2, s2);
11342
+ }
11343
+ if (format === "recovered") {
11344
+ recid = bytes[0];
11345
+ format = "compact";
11346
+ bytes = bytes.subarray(1);
11347
+ }
11348
+ const L = lengths.signature / 2;
11349
+ const r = bytes.subarray(0, L);
11350
+ const s = bytes.subarray(L, L * 2);
11351
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
11352
+ }
11353
+ static fromHex(hex, format) {
11354
+ return this.fromBytes(hexToBytes2(hex), format);
11355
+ }
11356
+ assertRecovery() {
11357
+ const { recovery } = this;
11358
+ if (recovery == null)
11359
+ throw new Error("invalid recovery id: must be present");
11360
+ return recovery;
11361
+ }
11362
+ addRecoveryBit(recovery) {
11363
+ return new Signature(this.r, this.s, recovery);
11364
+ }
11365
+ recoverPublicKey(messageHash) {
11366
+ const { r, s } = this;
11367
+ const recovery = this.assertRecovery();
11368
+ const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER2 : r;
11369
+ if (!Fp.isValid(radj))
11370
+ throw new Error("invalid recovery id: sig.r+curve.n != R.x");
11371
+ const x = Fp.toBytes(radj);
11372
+ const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
11373
+ const ir = Fn.inv(radj);
11374
+ const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
11375
+ const u1 = Fn.create(-h * ir);
11376
+ const u2 = Fn.create(s * ir);
11377
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
11378
+ if (Q.is0())
11379
+ throw new Error("invalid recovery: point at infinify");
11380
+ Q.assertValidity();
11381
+ return Q;
11382
+ }
11383
+ // Signatures should be low-s, to prevent malleability.
11384
+ hasHighS() {
11385
+ return isBiggerThanHalfOrder(this.s);
11386
+ }
11387
+ toBytes(format = defaultSigOpts.format) {
11388
+ validateSigFormat(format);
11389
+ if (format === "der")
11390
+ return hexToBytes2(DER.hexFromSig(this));
11391
+ const { r, s } = this;
11392
+ const rb = Fn.toBytes(r);
11393
+ const sb = Fn.toBytes(s);
11394
+ if (format === "recovered") {
11395
+ assertSmallCofactor();
11396
+ return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
11397
+ }
11398
+ return concatBytes(rb, sb);
11399
+ }
11400
+ toHex(format) {
11401
+ return bytesToHex4(this.toBytes(format));
11402
+ }
11403
+ }
11404
+ const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
11405
+ if (bytes.length > 8192)
11406
+ throw new Error("input is too large");
11407
+ const num = bytesToNumberBE(bytes);
11408
+ const delta = bytes.length * 8 - fnBits;
11409
+ return delta > 0 ? num >> BigInt(delta) : num;
11410
+ };
11411
+ const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
11412
+ return Fn.create(bits2int(bytes));
11413
+ };
11414
+ const ORDER_MASK = bitMask(fnBits);
11415
+ function int2octets(num) {
11416
+ aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
11417
+ return Fn.toBytes(num);
11418
+ }
11419
+ function validateMsgAndHash(message, prehash) {
11420
+ abytes(message, void 0, "message");
11421
+ return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
11422
+ }
11423
+ function prepSig(message, secretKey, opts) {
11424
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
11425
+ message = validateMsgAndHash(message, prehash);
11426
+ const h1int = bits2int_modN(message);
11427
+ const d = Fn.fromBytes(secretKey);
11428
+ if (!Fn.isValidNot0(d))
11429
+ throw new Error("invalid private key");
11430
+ const seedArgs = [int2octets(d), int2octets(h1int)];
11431
+ if (extraEntropy != null && extraEntropy !== false) {
11432
+ const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
11433
+ seedArgs.push(abytes(e, void 0, "extraEntropy"));
11434
+ }
11435
+ const seed = concatBytes(...seedArgs);
11436
+ const m = h1int;
11437
+ function k2sig(kBytes) {
11438
+ const k = bits2int(kBytes);
11439
+ if (!Fn.isValidNot0(k))
11440
+ return;
11441
+ const ik = Fn.inv(k);
11442
+ const q = Point.BASE.multiply(k).toAffine();
11443
+ const r = Fn.create(q.x);
11444
+ if (r === _0n4)
11445
+ return;
11446
+ const s = Fn.create(ik * Fn.create(m + r * d));
11447
+ if (s === _0n4)
11448
+ return;
11449
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
11450
+ let normS = s;
11451
+ if (lowS && isBiggerThanHalfOrder(s)) {
11452
+ normS = Fn.neg(s);
11453
+ recovery ^= 1;
11454
+ }
11455
+ return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
11456
+ }
11457
+ return { seed, k2sig };
11458
+ }
11459
+ function sign(message, secretKey, opts = {}) {
11460
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
11461
+ const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
11462
+ const sig = drbg(seed, k2sig);
11463
+ return sig.toBytes(opts.format);
11464
+ }
11465
+ function verify(signature, message, publicKey, opts = {}) {
11466
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
11467
+ publicKey = abytes(publicKey, void 0, "publicKey");
11468
+ message = validateMsgAndHash(message, prehash);
11469
+ if (!isBytes(signature)) {
11470
+ const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
11471
+ throw new Error("verify expects Uint8Array signature" + end);
11472
+ }
11473
+ validateSigLength(signature, format);
11474
+ try {
11475
+ const sig = Signature.fromBytes(signature, format);
11476
+ const P = Point.fromBytes(publicKey);
11477
+ if (lowS && sig.hasHighS())
11478
+ return false;
11479
+ const { r, s } = sig;
11480
+ const h = bits2int_modN(message);
11481
+ const is = Fn.inv(s);
11482
+ const u1 = Fn.create(h * is);
11483
+ const u2 = Fn.create(r * is);
11484
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
11485
+ if (R.is0())
11486
+ return false;
11487
+ const v = Fn.create(R.x);
11488
+ return v === r;
11489
+ } catch (e) {
11490
+ return false;
11491
+ }
11492
+ }
11493
+ function recoverPublicKey(signature, message, opts = {}) {
11494
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
11495
+ message = validateMsgAndHash(message, prehash);
11496
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
11497
+ }
11498
+ return Object.freeze({
11499
+ keygen,
11500
+ getPublicKey: getPublicKey2,
11501
+ getSharedSecret,
11502
+ utils,
11503
+ lengths,
11504
+ Point,
11505
+ sign,
11506
+ verify,
11507
+ recoverPublicKey,
11508
+ Signature,
11509
+ hash
11510
+ });
11511
+ }
11512
+
11513
+ // node_modules/@noble/curves/secp256k1.js
11514
+ var secp256k1_CURVE = {
11515
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
11516
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
11517
+ h: BigInt(1),
11518
+ a: BigInt(0),
11519
+ b: BigInt(7),
11520
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
11521
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
11522
+ };
11523
+ var secp256k1_ENDO = {
11524
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
11525
+ basises: [
11526
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
11527
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
11528
+ ]
11529
+ };
11530
+ var _2n3 = /* @__PURE__ */ BigInt(2);
11531
+ function sqrtMod(y) {
11532
+ const P = secp256k1_CURVE.p;
11533
+ const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
11534
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
11535
+ const b2 = y * y * y % P;
11536
+ const b3 = b2 * b2 * y % P;
11537
+ const b6 = pow2(b3, _3n3, P) * b3 % P;
11538
+ const b9 = pow2(b6, _3n3, P) * b3 % P;
11539
+ const b11 = pow2(b9, _2n3, P) * b2 % P;
11540
+ const b22 = pow2(b11, _11n, P) * b11 % P;
11541
+ const b44 = pow2(b22, _22n, P) * b22 % P;
11542
+ const b88 = pow2(b44, _44n, P) * b44 % P;
11543
+ const b176 = pow2(b88, _88n, P) * b88 % P;
11544
+ const b220 = pow2(b176, _44n, P) * b44 % P;
11545
+ const b223 = pow2(b220, _3n3, P) * b3 % P;
11546
+ const t1 = pow2(b223, _23n, P) * b22 % P;
11547
+ const t2 = pow2(t1, _6n, P) * b2 % P;
11548
+ const root = pow2(t2, _2n3, P);
11549
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
11550
+ throw new Error("Cannot find square root");
11551
+ return root;
11552
+ }
11553
+ var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
11554
+ var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
11555
+ Fp: Fpk1,
11556
+ endo: secp256k1_ENDO
11557
+ });
11558
+ var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha2564);
11559
+
11560
+ // modules/market/MarketModule.ts
11561
+ var DEFAULT_MARKET_API_URL = "https://market-api.unicity.network";
11562
+ function hexToBytes3(hex) {
11563
+ const len = hex.length >> 1;
11564
+ const bytes = new Uint8Array(len);
11565
+ for (let i = 0; i < len; i++) {
11566
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
11567
+ }
11568
+ return bytes;
11569
+ }
11570
+ function signRequest(body, privateKeyHex) {
11571
+ const timestamp = Date.now();
11572
+ const payload = JSON.stringify({ body, timestamp });
11573
+ const messageHash = sha2564(new TextEncoder().encode(payload));
11574
+ const privateKeyBytes = hexToBytes3(privateKeyHex);
11575
+ const signature = secp256k1.sign(messageHash, privateKeyBytes);
11576
+ const publicKey = bytesToHex4(secp256k1.getPublicKey(privateKeyBytes, true));
11577
+ return {
11578
+ body: JSON.stringify(body),
11579
+ headers: {
11580
+ "x-signature": bytesToHex4(signature),
11581
+ "x-public-key": publicKey,
11582
+ "x-timestamp": String(timestamp),
11583
+ "content-type": "application/json"
11584
+ }
11585
+ };
11586
+ }
11587
+ function toSnakeCaseIntent(req) {
11588
+ const result = {
11589
+ description: req.description,
11590
+ intent_type: req.intentType
11591
+ };
11592
+ if (req.category !== void 0) result.category = req.category;
11593
+ if (req.price !== void 0) result.price = req.price;
11594
+ if (req.currency !== void 0) result.currency = req.currency;
11595
+ if (req.location !== void 0) result.location = req.location;
11596
+ if (req.contactHandle !== void 0) result.contact_handle = req.contactHandle;
11597
+ if (req.expiresInDays !== void 0) result.expires_in_days = req.expiresInDays;
11598
+ return result;
11599
+ }
11600
+ function toSnakeCaseFilters(opts) {
11601
+ const result = {};
11602
+ if (opts?.filters) {
11603
+ const f = opts.filters;
11604
+ if (f.intentType !== void 0) result.intent_type = f.intentType;
11605
+ if (f.category !== void 0) result.category = f.category;
11606
+ if (f.minPrice !== void 0) result.min_price = f.minPrice;
11607
+ if (f.maxPrice !== void 0) result.max_price = f.maxPrice;
11608
+ if (f.location !== void 0) result.location = f.location;
11609
+ }
11610
+ if (opts?.limit !== void 0) result.limit = opts.limit;
11611
+ return result;
11612
+ }
11613
+ function mapSearchResult(raw) {
11614
+ return {
11615
+ id: raw.id,
11616
+ score: raw.score,
11617
+ agentNametag: raw.agent_nametag ?? void 0,
11618
+ agentPublicKey: raw.agent_public_key,
11619
+ description: raw.description,
11620
+ intentType: raw.intent_type,
11621
+ category: raw.category ?? void 0,
11622
+ price: raw.price ?? void 0,
11623
+ currency: raw.currency,
11624
+ location: raw.location ?? void 0,
11625
+ contactMethod: raw.contact_method,
11626
+ contactHandle: raw.contact_handle ?? void 0,
11627
+ createdAt: raw.created_at,
11628
+ expiresAt: raw.expires_at
11629
+ };
11630
+ }
11631
+ function mapMyIntent(raw) {
11632
+ return {
11633
+ id: raw.id,
11634
+ intentType: raw.intent_type,
11635
+ category: raw.category ?? void 0,
11636
+ price: raw.price ?? void 0,
11637
+ currency: raw.currency,
11638
+ location: raw.location ?? void 0,
11639
+ status: raw.status,
11640
+ createdAt: raw.created_at,
11641
+ expiresAt: raw.expires_at
11642
+ };
11643
+ }
11644
+ function mapFeedListing(raw) {
11645
+ return {
11646
+ id: raw.id,
11647
+ title: raw.title,
11648
+ descriptionPreview: raw.description_preview,
11649
+ agentName: raw.agent_name,
11650
+ agentId: raw.agent_id,
11651
+ type: raw.type,
11652
+ createdAt: raw.created_at
11653
+ };
11654
+ }
11655
+ function mapFeedMessage(raw) {
11656
+ if (raw.type === "initial") {
11657
+ return { type: "initial", listings: (raw.listings ?? []).map(mapFeedListing) };
11658
+ }
11659
+ return { type: "new", listing: mapFeedListing(raw.listing) };
11660
+ }
11661
+ var MarketModule = class {
11662
+ apiUrl;
11663
+ timeout;
11664
+ identity = null;
11665
+ registered = false;
11666
+ constructor(config) {
11667
+ this.apiUrl = (config?.apiUrl ?? DEFAULT_MARKET_API_URL).replace(/\/+$/, "");
11668
+ this.timeout = config?.timeout ?? 3e4;
11669
+ }
11670
+ /** Called by Sphere after construction */
11671
+ initialize(deps) {
11672
+ this.identity = deps.identity;
11673
+ }
11674
+ /** No-op — stateless module */
11675
+ async load() {
11676
+ }
11677
+ /** No-op — stateless module */
11678
+ destroy() {
11679
+ }
11680
+ // ---------------------------------------------------------------------------
11681
+ // Public API
11682
+ // ---------------------------------------------------------------------------
11683
+ /** Post a new intent (agent is auto-registered on first post) */
11684
+ async postIntent(intent) {
11685
+ const body = toSnakeCaseIntent(intent);
11686
+ const data = await this.apiPost("/api/intents", body);
11687
+ return {
11688
+ intentId: data.intent_id ?? data.intentId,
11689
+ message: data.message,
11690
+ expiresAt: data.expires_at ?? data.expiresAt
11691
+ };
11692
+ }
11693
+ /** Semantic search for intents (public — no auth required) */
11694
+ async search(query, opts) {
11695
+ const body = {
11696
+ query,
11697
+ ...toSnakeCaseFilters(opts)
11698
+ };
11699
+ const data = await this.apiPublicPost("/api/search", body);
11700
+ let results = (data.intents ?? []).map(mapSearchResult);
11701
+ const minScore = opts?.filters?.minScore;
11702
+ if (minScore != null) {
11703
+ results = results.filter((r) => Math.round(r.score * 100) >= Math.round(minScore * 100));
11704
+ }
11705
+ return { intents: results, count: results.length };
11706
+ }
11707
+ /** List own intents (authenticated) */
11708
+ async getMyIntents() {
11709
+ const data = await this.apiGet("/api/intents");
11710
+ return (data.intents ?? []).map(mapMyIntent);
11711
+ }
11712
+ /** Close (delete) an intent */
11713
+ async closeIntent(intentId) {
11714
+ await this.apiDelete(`/api/intents/${encodeURIComponent(intentId)}`);
11715
+ }
11716
+ /** Fetch the most recent listings via REST (public — no auth required) */
11717
+ async getRecentListings() {
11718
+ const res = await fetch(`${this.apiUrl}/api/feed/recent`, {
11719
+ signal: AbortSignal.timeout(this.timeout)
11720
+ });
11721
+ const data = await this.parseResponse(res);
11722
+ return (data.listings ?? []).map(mapFeedListing);
11723
+ }
11724
+ /**
11725
+ * Subscribe to the live listing feed via WebSocket.
11726
+ * Returns an unsubscribe function that closes the connection.
11727
+ *
11728
+ * Requires a WebSocket implementation — works natively in browsers
11729
+ * and in Node.js 21+ (or with the `ws` package).
11730
+ */
11731
+ subscribeFeed(listener) {
11732
+ const wsUrl = this.apiUrl.replace(/^http/, "ws") + "/ws/feed";
11733
+ const ws2 = new WebSocket(wsUrl);
11734
+ ws2.onmessage = (event) => {
11735
+ try {
11736
+ const raw = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
11737
+ listener(mapFeedMessage(raw));
11738
+ } catch {
11739
+ }
11740
+ };
11741
+ return () => {
11742
+ ws2.close();
11743
+ };
11744
+ }
11745
+ // ---------------------------------------------------------------------------
11746
+ // Private: HTTP helpers
11747
+ // ---------------------------------------------------------------------------
11748
+ ensureIdentity() {
11749
+ if (!this.identity) {
11750
+ throw new Error("MarketModule not initialized \u2014 call initialize() first");
11751
+ }
11752
+ }
11753
+ /** Register the agent's public key with the server (idempotent) */
11754
+ async ensureRegistered() {
11755
+ if (this.registered) return;
11756
+ this.ensureIdentity();
11757
+ const publicKey = bytesToHex4(secp256k1.getPublicKey(hexToBytes3(this.identity.privateKey), true));
11758
+ const body = { public_key: publicKey };
11759
+ if (this.identity.nametag) body.nametag = this.identity.nametag;
11760
+ const res = await fetch(`${this.apiUrl}/api/agent/register`, {
11761
+ method: "POST",
11762
+ headers: { "content-type": "application/json" },
11763
+ body: JSON.stringify(body),
11764
+ signal: AbortSignal.timeout(this.timeout)
11765
+ });
11766
+ if (res.ok || res.status === 409) {
11767
+ this.registered = true;
11768
+ return;
11769
+ }
11770
+ const text = await res.text();
11771
+ let data;
11772
+ try {
11773
+ data = JSON.parse(text);
11774
+ } catch {
11775
+ }
11776
+ throw new Error(data?.error ?? `Agent registration failed: HTTP ${res.status}`);
11777
+ }
11778
+ async parseResponse(res) {
11779
+ const text = await res.text();
11780
+ let data;
11781
+ try {
11782
+ data = JSON.parse(text);
11783
+ } catch {
11784
+ throw new Error(`Market API error: HTTP ${res.status} \u2014 unexpected response (not JSON)`);
11785
+ }
11786
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
11787
+ return data;
11788
+ }
11789
+ async apiPost(path, body) {
11790
+ this.ensureIdentity();
11791
+ await this.ensureRegistered();
11792
+ const signed = signRequest(body, this.identity.privateKey);
11793
+ const res = await fetch(`${this.apiUrl}${path}`, {
11794
+ method: "POST",
11795
+ headers: signed.headers,
11796
+ body: signed.body,
11797
+ signal: AbortSignal.timeout(this.timeout)
11798
+ });
11799
+ return this.parseResponse(res);
11800
+ }
11801
+ async apiGet(path) {
11802
+ this.ensureIdentity();
11803
+ await this.ensureRegistered();
11804
+ const signed = signRequest({}, this.identity.privateKey);
11805
+ const res = await fetch(`${this.apiUrl}${path}`, {
11806
+ method: "GET",
11807
+ headers: signed.headers,
11808
+ signal: AbortSignal.timeout(this.timeout)
11809
+ });
11810
+ return this.parseResponse(res);
11811
+ }
11812
+ async apiDelete(path) {
11813
+ this.ensureIdentity();
11814
+ await this.ensureRegistered();
11815
+ const signed = signRequest({}, this.identity.privateKey);
11816
+ const res = await fetch(`${this.apiUrl}${path}`, {
11817
+ method: "DELETE",
11818
+ headers: signed.headers,
11819
+ signal: AbortSignal.timeout(this.timeout)
11820
+ });
11821
+ return this.parseResponse(res);
11822
+ }
11823
+ async apiPublicPost(path, body) {
11824
+ const res = await fetch(`${this.apiUrl}${path}`, {
11825
+ method: "POST",
11826
+ headers: { "content-type": "application/json" },
11827
+ body: JSON.stringify(body),
11828
+ signal: AbortSignal.timeout(this.timeout)
11829
+ });
11830
+ return this.parseResponse(res);
11831
+ }
11832
+ };
11833
+ function createMarketModule(config) {
11834
+ return new MarketModule(config);
11835
+ }
11836
+
9291
11837
  // core/encryption.ts
9292
11838
  import CryptoJS6 from "crypto-js";
9293
11839
  function encryptSimple(plaintext, password) {
@@ -10123,6 +12669,7 @@ var Sphere = class _Sphere {
10123
12669
  _payments;
10124
12670
  _communications;
10125
12671
  _groupChat = null;
12672
+ _market = null;
10126
12673
  // Events
10127
12674
  eventHandlers = /* @__PURE__ */ new Map();
10128
12675
  // Provider management
@@ -10132,7 +12679,7 @@ var Sphere = class _Sphere {
10132
12679
  // ===========================================================================
10133
12680
  // Constructor (private)
10134
12681
  // ===========================================================================
10135
- constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig) {
12682
+ constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig, marketConfig) {
10136
12683
  this._storage = storage;
10137
12684
  this._transport = transport;
10138
12685
  this._oracle = oracle;
@@ -10143,6 +12690,7 @@ var Sphere = class _Sphere {
10143
12690
  this._payments = createPaymentsModule({ l1: l1Config });
10144
12691
  this._communications = createCommunicationsModule();
10145
12692
  this._groupChat = groupChatConfig ? createGroupChatModule(groupChatConfig) : null;
12693
+ this._market = marketConfig ? createMarketModule(marketConfig) : null;
10146
12694
  }
10147
12695
  // ===========================================================================
10148
12696
  // Static Methods - Wallet Management
@@ -10152,13 +12700,17 @@ var Sphere = class _Sphere {
10152
12700
  */
10153
12701
  static async exists(storage) {
10154
12702
  try {
10155
- if (!storage.isConnected()) {
12703
+ const wasConnected = storage.isConnected();
12704
+ if (!wasConnected) {
10156
12705
  await storage.connect();
10157
12706
  }
10158
12707
  const mnemonic = await storage.get(STORAGE_KEYS_GLOBAL.MNEMONIC);
10159
12708
  if (mnemonic) return true;
10160
12709
  const masterKey = await storage.get(STORAGE_KEYS_GLOBAL.MASTER_KEY);
10161
12710
  if (masterKey) return true;
12711
+ if (!wasConnected) {
12712
+ await storage.disconnect();
12713
+ }
10162
12714
  return false;
10163
12715
  } catch {
10164
12716
  return false;
@@ -10192,6 +12744,7 @@ var Sphere = class _Sphere {
10192
12744
  static async init(options) {
10193
12745
  _Sphere.configureTokenRegistry(options.storage, options.network);
10194
12746
  const groupChat = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12747
+ const market = _Sphere.resolveMarketConfig(options.market);
10195
12748
  const walletExists = await _Sphere.exists(options.storage);
10196
12749
  if (walletExists) {
10197
12750
  const sphere2 = await _Sphere.load({
@@ -10202,6 +12755,7 @@ var Sphere = class _Sphere {
10202
12755
  l1: options.l1,
10203
12756
  price: options.price,
10204
12757
  groupChat,
12758
+ market,
10205
12759
  password: options.password
10206
12760
  });
10207
12761
  return { sphere: sphere2, created: false };
@@ -10229,6 +12783,7 @@ var Sphere = class _Sphere {
10229
12783
  l1: options.l1,
10230
12784
  price: options.price,
10231
12785
  groupChat,
12786
+ market,
10232
12787
  password: options.password
10233
12788
  });
10234
12789
  return { sphere, created: true, generatedMnemonic };
@@ -10256,6 +12811,17 @@ var Sphere = class _Sphere {
10256
12811
  }
10257
12812
  return config;
10258
12813
  }
12814
+ /**
12815
+ * Resolve market module config from Sphere.init() options.
12816
+ * - `true` → enable with default API URL
12817
+ * - `MarketModuleConfig` → pass through
12818
+ * - `undefined` → no market module
12819
+ */
12820
+ static resolveMarketConfig(config) {
12821
+ if (!config) return void 0;
12822
+ if (config === true) return {};
12823
+ return config;
12824
+ }
10259
12825
  /**
10260
12826
  * Configure TokenRegistry in the main bundle context.
10261
12827
  *
@@ -10281,6 +12847,7 @@ var Sphere = class _Sphere {
10281
12847
  }
10282
12848
  _Sphere.configureTokenRegistry(options.storage, options.network);
10283
12849
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12850
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10284
12851
  const sphere = new _Sphere(
10285
12852
  options.storage,
10286
12853
  options.transport,
@@ -10288,7 +12855,8 @@ var Sphere = class _Sphere {
10288
12855
  options.tokenStorage,
10289
12856
  options.l1,
10290
12857
  options.price,
10291
- groupChatConfig
12858
+ groupChatConfig,
12859
+ marketConfig
10292
12860
  );
10293
12861
  sphere._password = options.password ?? null;
10294
12862
  await sphere.storeMnemonic(options.mnemonic, options.derivationPath);
@@ -10316,6 +12884,7 @@ var Sphere = class _Sphere {
10316
12884
  }
10317
12885
  _Sphere.configureTokenRegistry(options.storage, options.network);
10318
12886
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12887
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10319
12888
  const sphere = new _Sphere(
10320
12889
  options.storage,
10321
12890
  options.transport,
@@ -10323,7 +12892,8 @@ var Sphere = class _Sphere {
10323
12892
  options.tokenStorage,
10324
12893
  options.l1,
10325
12894
  options.price,
10326
- groupChatConfig
12895
+ groupChatConfig,
12896
+ marketConfig
10327
12897
  );
10328
12898
  sphere._password = options.password ?? null;
10329
12899
  await sphere.loadIdentityFromStorage();
@@ -10369,6 +12939,7 @@ var Sphere = class _Sphere {
10369
12939
  console.log("[Sphere.import] Storage reconnected");
10370
12940
  }
10371
12941
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat);
12942
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10372
12943
  const sphere = new _Sphere(
10373
12944
  options.storage,
10374
12945
  options.transport,
@@ -10376,7 +12947,8 @@ var Sphere = class _Sphere {
10376
12947
  options.tokenStorage,
10377
12948
  options.l1,
10378
12949
  options.price,
10379
- groupChatConfig
12950
+ groupChatConfig,
12951
+ marketConfig
10380
12952
  );
10381
12953
  sphere._password = options.password ?? null;
10382
12954
  if (options.mnemonic) {
@@ -10457,46 +13029,58 @@ var Sphere = class _Sphere {
10457
13029
  static async clear(storageOrOptions) {
10458
13030
  const storage = "get" in storageOrOptions ? storageOrOptions : storageOrOptions.storage;
10459
13031
  const tokenStorage = "get" in storageOrOptions ? void 0 : storageOrOptions.tokenStorage;
10460
- if (!storage.isConnected()) {
10461
- await storage.connect();
10462
- }
10463
- console.log("[Sphere.clear] Removing storage keys...");
10464
- await storage.remove(STORAGE_KEYS_GLOBAL.MNEMONIC);
10465
- await storage.remove(STORAGE_KEYS_GLOBAL.MASTER_KEY);
10466
- await storage.remove(STORAGE_KEYS_GLOBAL.CHAIN_CODE);
10467
- await storage.remove(STORAGE_KEYS_GLOBAL.DERIVATION_PATH);
10468
- await storage.remove(STORAGE_KEYS_GLOBAL.BASE_PATH);
10469
- await storage.remove(STORAGE_KEYS_GLOBAL.DERIVATION_MODE);
10470
- await storage.remove(STORAGE_KEYS_GLOBAL.WALLET_SOURCE);
10471
- await storage.remove(STORAGE_KEYS_GLOBAL.WALLET_EXISTS);
10472
- await storage.remove(STORAGE_KEYS_GLOBAL.TRACKED_ADDRESSES);
10473
- await storage.remove(STORAGE_KEYS_GLOBAL.ADDRESS_NAMETAGS);
10474
- await storage.remove(STORAGE_KEYS_ADDRESS.PENDING_TRANSFERS);
10475
- await storage.remove(STORAGE_KEYS_ADDRESS.OUTBOX);
10476
- console.log("[Sphere.clear] Storage keys removed");
10477
- if (tokenStorage?.clear) {
10478
- console.log("[Sphere.clear] Clearing token storage...");
13032
+ if (_Sphere.instance) {
13033
+ console.log("[Sphere.clear] Destroying Sphere instance...");
13034
+ await _Sphere.instance.destroy();
13035
+ console.log("[Sphere.clear] Sphere instance destroyed");
13036
+ }
13037
+ await vestingClassifier.destroy();
13038
+ if (typeof indexedDB !== "undefined" && typeof indexedDB.databases === "function") {
13039
+ console.log("[Sphere.clear] Deleting all sphere IndexedDB databases...");
10479
13040
  try {
10480
- await Promise.race([
10481
- tokenStorage.clear(),
13041
+ const dbs = await Promise.race([
13042
+ indexedDB.databases(),
10482
13043
  new Promise(
10483
- (_, reject) => setTimeout(() => reject(new Error("tokenStorage.clear() timed out after 2s")), 2e3)
13044
+ (_, reject) => setTimeout(() => reject(new Error("timeout")), 2e3)
10484
13045
  )
10485
13046
  ]);
10486
- console.log("[Sphere.clear] Token storage cleared");
13047
+ const sphereDbs = dbs.filter((db) => db.name?.startsWith("sphere"));
13048
+ if (sphereDbs.length > 0) {
13049
+ await Promise.all(sphereDbs.map(
13050
+ (db) => new Promise((resolve) => {
13051
+ const req = indexedDB.deleteDatabase(db.name);
13052
+ req.onsuccess = () => {
13053
+ console.log(`[Sphere.clear] Deleted ${db.name}`);
13054
+ resolve();
13055
+ };
13056
+ req.onerror = () => resolve();
13057
+ req.onblocked = () => {
13058
+ console.warn(`[Sphere.clear] deleteDatabase blocked: ${db.name}`);
13059
+ resolve();
13060
+ };
13061
+ })
13062
+ ));
13063
+ }
13064
+ console.log("[Sphere.clear] IndexedDB cleanup done");
13065
+ } catch {
13066
+ console.warn("[Sphere.clear] IndexedDB enumeration failed");
13067
+ }
13068
+ }
13069
+ if (tokenStorage?.clear) {
13070
+ try {
13071
+ await tokenStorage.clear();
10487
13072
  } catch (err) {
10488
- console.warn("[Sphere.clear] Token storage clear failed/timed out:", err);
13073
+ console.warn("[Sphere.clear] Token storage clear failed:", err);
10489
13074
  }
10490
13075
  }
10491
- console.log("[Sphere.clear] Destroying vesting classifier...");
10492
- await vestingClassifier.destroy();
10493
- console.log("[Sphere.clear] Vesting classifier destroyed");
10494
- if (_Sphere.instance) {
10495
- console.log("[Sphere.clear] Destroying Sphere instance...");
10496
- await _Sphere.instance.destroy();
10497
- console.log("[Sphere.clear] Sphere instance destroyed");
10498
- } else {
10499
- console.log("[Sphere.clear] No Sphere instance to destroy");
13076
+ if (!storage.isConnected()) {
13077
+ try {
13078
+ await storage.connect();
13079
+ } catch {
13080
+ }
13081
+ }
13082
+ if (storage.isConnected()) {
13083
+ await storage.clear();
10500
13084
  }
10501
13085
  }
10502
13086
  /**
@@ -10541,6 +13125,10 @@ var Sphere = class _Sphere {
10541
13125
  get groupChat() {
10542
13126
  return this._groupChat;
10543
13127
  }
13128
+ /** Market module (intent bulletin board). Null if not configured. */
13129
+ get market() {
13130
+ return this._market;
13131
+ }
10544
13132
  // ===========================================================================
10545
13133
  // Public Properties - State
10546
13134
  // ===========================================================================
@@ -11416,9 +14004,14 @@ var Sphere = class _Sphere {
11416
14004
  storage: this._storage,
11417
14005
  emitEvent
11418
14006
  });
14007
+ this._market?.initialize({
14008
+ identity: this._identity,
14009
+ emitEvent
14010
+ });
11419
14011
  await this._payments.load();
11420
14012
  await this._communications.load();
11421
14013
  await this._groupChat?.load();
14014
+ await this._market?.load();
11422
14015
  }
11423
14016
  /**
11424
14017
  * Derive address at a specific index
@@ -12243,6 +14836,7 @@ var Sphere = class _Sphere {
12243
14836
  this._payments.destroy();
12244
14837
  this._communications.destroy();
12245
14838
  this._groupChat?.destroy();
14839
+ this._market?.destroy();
12246
14840
  await this._transport.disconnect();
12247
14841
  await this._storage.disconnect();
12248
14842
  await this._oracle.disconnect();
@@ -12550,9 +15144,14 @@ var Sphere = class _Sphere {
12550
15144
  storage: this._storage,
12551
15145
  emitEvent
12552
15146
  });
15147
+ this._market?.initialize({
15148
+ identity: this._identity,
15149
+ emitEvent
15150
+ });
12553
15151
  await this._payments.load();
12554
15152
  await this._communications.load();
12555
15153
  await this._groupChat?.load();
15154
+ await this._market?.load();
12556
15155
  }
12557
15156
  // ===========================================================================
12558
15157
  // Private: Helpers
@@ -13482,6 +16081,7 @@ export {
13482
16081
  DEFAULT_GROUP_RELAYS,
13483
16082
  DEFAULT_IPFS_BOOTSTRAP_PEERS,
13484
16083
  DEFAULT_IPFS_GATEWAYS,
16084
+ DEFAULT_MARKET_API_URL,
13485
16085
  DEFAULT_NOSTR_RELAYS,
13486
16086
  DEV_AGGREGATOR_URL,
13487
16087
  GroupChatModule,
@@ -13490,11 +16090,14 @@ export {
13490
16090
  l1_exports as L1,
13491
16091
  L1PaymentsModule,
13492
16092
  LIMITS,
16093
+ MarketModule,
13493
16094
  NETWORKS,
13494
16095
  NIP29_KINDS,
13495
16096
  NOSTR_EVENT_KINDS,
13496
16097
  PaymentsModule,
13497
16098
  STORAGE_KEYS,
16099
+ STORAGE_KEYS_ADDRESS,
16100
+ STORAGE_KEYS_GLOBAL,
13498
16101
  STORAGE_PREFIX,
13499
16102
  Sphere,
13500
16103
  SphereError,
@@ -13517,6 +16120,7 @@ export {
13517
16120
  createGroupChatModule,
13518
16121
  createKeyPair,
13519
16122
  createL1PaymentsModule,
16123
+ createMarketModule,
13520
16124
  createPaymentSession,
13521
16125
  createPaymentSessionError,
13522
16126
  createPaymentsModule,
@@ -13540,6 +16144,8 @@ export {
13540
16144
  generateMasterKey,
13541
16145
  generateMnemonic2 as generateMnemonic,
13542
16146
  getAddressHrp,
16147
+ getAddressId,
16148
+ getAddressStorageKey,
13543
16149
  getCoinIdByName,
13544
16150
  getCoinIdBySymbol,
13545
16151
  getCurrentStateHash,
@@ -13604,4 +16210,16 @@ export {
13604
16210
  txfToToken,
13605
16211
  validateMnemonic2 as validateMnemonic
13606
16212
  };
16213
+ /*! Bundled license information:
16214
+
16215
+ @noble/hashes/utils.js:
16216
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
16217
+
16218
+ @noble/curves/utils.js:
16219
+ @noble/curves/abstract/modular.js:
16220
+ @noble/curves/abstract/curve.js:
16221
+ @noble/curves/abstract/weierstrass.js:
16222
+ @noble/curves/secp256k1.js:
16223
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
16224
+ */
13607
16225
  //# sourceMappingURL=index.js.map