@unicitylabs/sphere-sdk 0.3.9 → 0.4.2

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.
Files changed (43) hide show
  1. package/dist/connect/index.cjs +79 -3
  2. package/dist/connect/index.cjs.map +1 -1
  3. package/dist/connect/index.d.cts +16 -0
  4. package/dist/connect/index.d.ts +16 -0
  5. package/dist/connect/index.js +79 -3
  6. package/dist/connect/index.js.map +1 -1
  7. package/dist/core/index.cjs +2686 -56
  8. package/dist/core/index.cjs.map +1 -1
  9. package/dist/core/index.d.cts +228 -3
  10. package/dist/core/index.d.ts +228 -3
  11. package/dist/core/index.js +2682 -52
  12. package/dist/core/index.js.map +1 -1
  13. package/dist/impl/browser/connect/index.cjs +11 -2
  14. package/dist/impl/browser/connect/index.cjs.map +1 -1
  15. package/dist/impl/browser/connect/index.js +11 -2
  16. package/dist/impl/browser/connect/index.js.map +1 -1
  17. package/dist/impl/browser/index.cjs +467 -47
  18. package/dist/impl/browser/index.cjs.map +1 -1
  19. package/dist/impl/browser/index.js +468 -47
  20. package/dist/impl/browser/index.js.map +1 -1
  21. package/dist/impl/nodejs/connect/index.cjs +11 -2
  22. package/dist/impl/nodejs/connect/index.cjs.map +1 -1
  23. package/dist/impl/nodejs/connect/index.js +11 -2
  24. package/dist/impl/nodejs/connect/index.js.map +1 -1
  25. package/dist/impl/nodejs/index.cjs +152 -8
  26. package/dist/impl/nodejs/index.cjs.map +1 -1
  27. package/dist/impl/nodejs/index.d.cts +47 -0
  28. package/dist/impl/nodejs/index.d.ts +47 -0
  29. package/dist/impl/nodejs/index.js +153 -8
  30. package/dist/impl/nodejs/index.js.map +1 -1
  31. package/dist/index.cjs +2703 -56
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.d.cts +326 -5
  34. package/dist/index.d.ts +326 -5
  35. package/dist/index.js +2692 -52
  36. package/dist/index.js.map +1 -1
  37. package/dist/l1/index.cjs +5 -1
  38. package/dist/l1/index.cjs.map +1 -1
  39. package/dist/l1/index.d.cts +2 -1
  40. package/dist/l1/index.d.ts +2 -1
  41. package/dist/l1/index.js +5 -1
  42. package/dist/l1/index.js.map +1 -1
  43. package/package.json +1 -1
@@ -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
  }
@@ -682,9 +682,13 @@ var VestingClassifier = class {
682
682
  storeName = "vestingCache";
683
683
  db = null;
684
684
  /**
685
- * Initialize IndexedDB for persistent caching
685
+ * Initialize IndexedDB for persistent caching.
686
+ * In Node.js (no IndexedDB), silently falls back to memory-only caching.
686
687
  */
687
688
  async initDB() {
689
+ if (typeof indexedDB === "undefined") {
690
+ return;
691
+ }
688
692
  return new Promise((resolve, reject) => {
689
693
  const request = indexedDB.open(this.dbName, 1);
690
694
  request.onupgradeneeded = (event) => {
@@ -6276,6 +6280,29 @@ var PaymentsModule = class _PaymentsModule {
6276
6280
  this.nametags = [];
6277
6281
  await this.save();
6278
6282
  }
6283
+ /**
6284
+ * Reload nametag data from storage providers into memory.
6285
+ *
6286
+ * Used as a recovery mechanism when `this.nametags` is unexpectedly empty
6287
+ * (e.g., wiped by sync or race condition) but nametag data exists in storage.
6288
+ */
6289
+ async reloadNametagsFromStorage() {
6290
+ const providers = this.getTokenStorageProviders();
6291
+ for (const [, provider] of providers) {
6292
+ try {
6293
+ const result = await provider.load();
6294
+ if (result.success && result.data) {
6295
+ const parsed = parseTxfStorageData(result.data);
6296
+ if (parsed.nametags.length > 0) {
6297
+ this.nametags = parsed.nametags;
6298
+ this.log(`Reloaded ${parsed.nametags.length} nametag(s) from storage`);
6299
+ return;
6300
+ }
6301
+ }
6302
+ } catch {
6303
+ }
6304
+ }
6305
+ }
6279
6306
  /**
6280
6307
  * Mint a nametag token on-chain (like Sphere wallet and lottery)
6281
6308
  * This creates the nametag token required for receiving tokens via PROXY addresses
@@ -6400,11 +6427,15 @@ var PaymentsModule = class _PaymentsModule {
6400
6427
  const localData = await this.createStorageData();
6401
6428
  let totalAdded = 0;
6402
6429
  let totalRemoved = 0;
6430
+ const savedNametags = [...this.nametags];
6403
6431
  for (const [providerId, provider] of providers) {
6404
6432
  try {
6405
6433
  const result = await provider.sync(localData);
6406
6434
  if (result.success && result.merged) {
6407
6435
  this.loadFromStorageData(result.merged);
6436
+ if (this.nametags.length === 0 && savedNametags.length > 0) {
6437
+ this.nametags = savedNametags;
6438
+ }
6408
6439
  totalAdded += result.added;
6409
6440
  totalRemoved += result.removed;
6410
6441
  }
@@ -6633,6 +6664,15 @@ var PaymentsModule = class _PaymentsModule {
6633
6664
  );
6634
6665
  return SigningService.createFromSecret(privateKeyBytes);
6635
6666
  }
6667
+ /**
6668
+ * Get the wallet's signing public key (used for token ownership predicates).
6669
+ * This is the key that token state predicates are checked against.
6670
+ */
6671
+ async getSigningPublicKey() {
6672
+ this.ensureInitialized();
6673
+ const signer = await this.createSigningService();
6674
+ return signer.publicKey;
6675
+ }
6636
6676
  /**
6637
6677
  * Create DirectAddress from a public key using UnmaskedPredicateReference
6638
6678
  */
@@ -6783,7 +6823,12 @@ var PaymentsModule = class _PaymentsModule {
6783
6823
  let nametagTokens = [];
6784
6824
  if (addressScheme === AddressScheme.PROXY) {
6785
6825
  const { ProxyAddress } = await import("@unicitylabs/state-transition-sdk/lib/address/ProxyAddress");
6786
- const proxyNametag = this.getNametag();
6826
+ let proxyNametag = this.getNametag();
6827
+ if (!proxyNametag?.token) {
6828
+ this.log("Nametag missing in memory, attempting reload from storage...");
6829
+ await this.reloadNametagsFromStorage();
6830
+ proxyNametag = this.getNametag();
6831
+ }
6787
6832
  if (!proxyNametag?.token) {
6788
6833
  throw new Error("Cannot finalize PROXY transfer - no nametag token");
6789
6834
  }
@@ -7281,14 +7326,17 @@ var CommunicationsModule = class {
7281
7326
  broadcasts = /* @__PURE__ */ new Map();
7282
7327
  // Subscriptions
7283
7328
  unsubscribeMessages = null;
7329
+ unsubscribeComposing = null;
7284
7330
  broadcastSubscriptions = /* @__PURE__ */ new Map();
7285
7331
  // Handlers
7286
7332
  dmHandlers = /* @__PURE__ */ new Set();
7333
+ composingHandlers = /* @__PURE__ */ new Set();
7287
7334
  broadcastHandlers = /* @__PURE__ */ new Set();
7288
7335
  constructor(config) {
7289
7336
  this.config = {
7290
7337
  autoSave: config?.autoSave ?? true,
7291
7338
  maxMessages: config?.maxMessages ?? 1e3,
7339
+ maxPerConversation: config?.maxPerConversation ?? 200,
7292
7340
  readReceipts: config?.readReceipts ?? true
7293
7341
  };
7294
7342
  }
@@ -7299,6 +7347,8 @@ var CommunicationsModule = class {
7299
7347
  * Initialize module with dependencies
7300
7348
  */
7301
7349
  initialize(deps) {
7350
+ this.unsubscribeMessages?.();
7351
+ this.unsubscribeComposing?.();
7302
7352
  this.deps = deps;
7303
7353
  this.unsubscribeMessages = deps.transport.onMessage((msg) => {
7304
7354
  this.handleIncomingMessage(msg);
@@ -7325,19 +7375,41 @@ var CommunicationsModule = class {
7325
7375
  });
7326
7376
  });
7327
7377
  }
7378
+ this.unsubscribeComposing = deps.transport.onComposing?.((indicator) => {
7379
+ this.handleComposingIndicator(indicator);
7380
+ }) ?? null;
7328
7381
  }
7329
7382
  /**
7330
- * Load messages from storage
7383
+ * Load messages from storage.
7384
+ * Uses per-address key (STORAGE_KEYS_ADDRESS.MESSAGES) which is automatically
7385
+ * scoped by LocalStorageProvider to sphere_DIRECT_xxx_yyy_messages.
7386
+ * Falls back to legacy global 'direct_messages' key for migration.
7331
7387
  */
7332
7388
  async load() {
7333
7389
  this.ensureInitialized();
7334
- const data = await this.deps.storage.get("direct_messages");
7390
+ this.messages.clear();
7391
+ let data = await this.deps.storage.get(STORAGE_KEYS_ADDRESS.MESSAGES);
7335
7392
  if (data) {
7336
7393
  const messages = JSON.parse(data);
7337
- this.messages.clear();
7338
7394
  for (const msg of messages) {
7339
7395
  this.messages.set(msg.id, msg);
7340
7396
  }
7397
+ return;
7398
+ }
7399
+ data = await this.deps.storage.get("direct_messages");
7400
+ if (data) {
7401
+ const allMessages = JSON.parse(data);
7402
+ const myPubkey = this.deps.identity.chainPubkey;
7403
+ const myMessages = allMessages.filter(
7404
+ (m) => m.senderPubkey === myPubkey || m.recipientPubkey === myPubkey
7405
+ );
7406
+ for (const msg of myMessages) {
7407
+ this.messages.set(msg.id, msg);
7408
+ }
7409
+ if (myMessages.length > 0) {
7410
+ await this.save();
7411
+ console.log(`[Communications] Migrated ${myMessages.length} messages to per-address storage`);
7412
+ }
7341
7413
  }
7342
7414
  }
7343
7415
  /**
@@ -7346,6 +7418,8 @@ var CommunicationsModule = class {
7346
7418
  destroy() {
7347
7419
  this.unsubscribeMessages?.();
7348
7420
  this.unsubscribeMessages = null;
7421
+ this.unsubscribeComposing?.();
7422
+ this.unsubscribeComposing = null;
7349
7423
  for (const unsub of this.broadcastSubscriptions.values()) {
7350
7424
  unsub();
7351
7425
  }
@@ -7359,13 +7433,14 @@ var CommunicationsModule = class {
7359
7433
  */
7360
7434
  async sendDM(recipient, content) {
7361
7435
  this.ensureInitialized();
7362
- const recipientPubkey = await this.resolveRecipient(recipient);
7363
- const eventId = await this.deps.transport.sendMessage(recipientPubkey, content);
7436
+ const resolved = await this.resolveRecipient(recipient);
7437
+ const eventId = await this.deps.transport.sendMessage(resolved.pubkey, content);
7364
7438
  const message = {
7365
7439
  id: eventId,
7366
7440
  senderPubkey: this.deps.identity.chainPubkey,
7367
7441
  senderNametag: this.deps.identity.nametag,
7368
- recipientPubkey,
7442
+ recipientPubkey: resolved.pubkey,
7443
+ ...resolved.nametag ? { recipientNametag: resolved.nametag } : {},
7369
7444
  content,
7370
7445
  timestamp: Date.now(),
7371
7446
  isRead: false
@@ -7437,6 +7512,37 @@ var CommunicationsModule = class {
7437
7512
  }
7438
7513
  return messages.length;
7439
7514
  }
7515
+ /**
7516
+ * Get a page of messages from a conversation (for lazy loading).
7517
+ * Returns messages in chronological order with a cursor for loading older messages.
7518
+ */
7519
+ getConversationPage(peerPubkey, options) {
7520
+ const limit = options?.limit ?? 20;
7521
+ const before = options?.before ?? Infinity;
7522
+ const all = Array.from(this.messages.values()).filter(
7523
+ (m) => (m.senderPubkey === peerPubkey || m.recipientPubkey === peerPubkey) && m.timestamp < before
7524
+ ).sort((a, b) => b.timestamp - a.timestamp);
7525
+ const page = all.slice(0, limit);
7526
+ return {
7527
+ messages: page.reverse(),
7528
+ // chronological order for display
7529
+ hasMore: all.length > limit,
7530
+ oldestTimestamp: page.length > 0 ? page[0].timestamp : null
7531
+ };
7532
+ }
7533
+ /**
7534
+ * Delete all messages in a conversation with a peer
7535
+ */
7536
+ async deleteConversation(peerPubkey) {
7537
+ for (const [id, msg] of this.messages) {
7538
+ if (msg.senderPubkey === peerPubkey || msg.recipientPubkey === peerPubkey) {
7539
+ this.messages.delete(id);
7540
+ }
7541
+ }
7542
+ if (this.config.autoSave) {
7543
+ await this.save();
7544
+ }
7545
+ }
7440
7546
  /**
7441
7547
  * Send typing indicator to a peer
7442
7548
  */
@@ -7446,6 +7552,26 @@ var CommunicationsModule = class {
7446
7552
  await this.deps.transport.sendTypingIndicator(peerPubkey);
7447
7553
  }
7448
7554
  }
7555
+ /**
7556
+ * Send a composing indicator to a peer.
7557
+ * Fire-and-forget — does not save to message history.
7558
+ */
7559
+ async sendComposingIndicator(recipientPubkeyOrNametag) {
7560
+ this.ensureInitialized();
7561
+ const resolved = await this.resolveRecipient(recipientPubkeyOrNametag);
7562
+ const content = JSON.stringify({
7563
+ senderNametag: this.deps.identity.nametag,
7564
+ expiresIn: 3e4
7565
+ });
7566
+ await this.deps.transport.sendComposingIndicator?.(resolved.pubkey, content);
7567
+ }
7568
+ /**
7569
+ * Subscribe to incoming composing indicators
7570
+ */
7571
+ onComposingIndicator(handler) {
7572
+ this.composingHandlers.add(handler);
7573
+ return () => this.composingHandlers.delete(handler);
7574
+ }
7449
7575
  /**
7450
7576
  * Subscribe to incoming DMs
7451
7577
  */
@@ -7558,6 +7684,21 @@ var CommunicationsModule = class {
7558
7684
  }
7559
7685
  this.pruneIfNeeded();
7560
7686
  }
7687
+ handleComposingIndicator(indicator) {
7688
+ const composing = {
7689
+ senderPubkey: indicator.senderPubkey,
7690
+ senderNametag: indicator.senderNametag,
7691
+ expiresIn: indicator.expiresIn
7692
+ };
7693
+ this.deps.emitEvent("composing:started", composing);
7694
+ for (const handler of this.composingHandlers) {
7695
+ try {
7696
+ handler(composing);
7697
+ } catch (error) {
7698
+ console.error("[Communications] Composing handler error:", error);
7699
+ }
7700
+ }
7701
+ }
7561
7702
  handleIncomingBroadcast(incoming) {
7562
7703
  const message = {
7563
7704
  id: incoming.id,
@@ -7581,9 +7722,23 @@ var CommunicationsModule = class {
7581
7722
  // ===========================================================================
7582
7723
  async save() {
7583
7724
  const messages = Array.from(this.messages.values());
7584
- await this.deps.storage.set("direct_messages", JSON.stringify(messages));
7725
+ await this.deps.storage.set(STORAGE_KEYS_ADDRESS.MESSAGES, JSON.stringify(messages));
7585
7726
  }
7586
7727
  pruneIfNeeded() {
7728
+ const byPeer = /* @__PURE__ */ new Map();
7729
+ for (const msg of this.messages.values()) {
7730
+ const peer = msg.senderPubkey === this.deps?.identity.chainPubkey ? msg.recipientPubkey : msg.senderPubkey;
7731
+ if (!byPeer.has(peer)) byPeer.set(peer, []);
7732
+ byPeer.get(peer).push(msg);
7733
+ }
7734
+ for (const [, msgs] of byPeer) {
7735
+ if (msgs.length <= this.config.maxPerConversation) continue;
7736
+ msgs.sort((a, b) => a.timestamp - b.timestamp);
7737
+ const toRemove2 = msgs.slice(0, msgs.length - this.config.maxPerConversation);
7738
+ for (const msg of toRemove2) {
7739
+ this.messages.delete(msg.id);
7740
+ }
7741
+ }
7587
7742
  if (this.messages.size <= this.config.maxMessages) return;
7588
7743
  const sorted = Array.from(this.messages.entries()).sort(([, a], [, b]) => a.timestamp - b.timestamp);
7589
7744
  const toRemove = sorted.slice(0, sorted.length - this.config.maxMessages);
@@ -7596,13 +7751,14 @@ var CommunicationsModule = class {
7596
7751
  // ===========================================================================
7597
7752
  async resolveRecipient(recipient) {
7598
7753
  if (recipient.startsWith("@")) {
7599
- const pubkey = await this.deps.transport.resolveNametag?.(recipient.slice(1));
7754
+ const nametag = recipient.slice(1);
7755
+ const pubkey = await this.deps.transport.resolveNametag?.(nametag);
7600
7756
  if (!pubkey) {
7601
7757
  throw new Error(`Nametag not found: ${recipient}`);
7602
7758
  }
7603
- return pubkey;
7759
+ return { pubkey, nametag };
7604
7760
  }
7605
- return recipient;
7761
+ return { pubkey: recipient };
7606
7762
  }
7607
7763
  ensureInitialized() {
7608
7764
  if (!this.deps) {
@@ -8996,6 +9152,2427 @@ function createGroupChatModule(config) {
8996
9152
  return new GroupChatModule(config);
8997
9153
  }
8998
9154
 
9155
+ // node_modules/@noble/hashes/utils.js
9156
+ function isBytes(a) {
9157
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
9158
+ }
9159
+ function anumber(n, title = "") {
9160
+ if (!Number.isSafeInteger(n) || n < 0) {
9161
+ const prefix = title && `"${title}" `;
9162
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
9163
+ }
9164
+ }
9165
+ function abytes(value, length, title = "") {
9166
+ const bytes = isBytes(value);
9167
+ const len = value?.length;
9168
+ const needsLen = length !== void 0;
9169
+ if (!bytes || needsLen && len !== length) {
9170
+ const prefix = title && `"${title}" `;
9171
+ const ofLen = needsLen ? ` of length ${length}` : "";
9172
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
9173
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
9174
+ }
9175
+ return value;
9176
+ }
9177
+ function ahash(h) {
9178
+ if (typeof h !== "function" || typeof h.create !== "function")
9179
+ throw new Error("Hash must wrapped by utils.createHasher");
9180
+ anumber(h.outputLen);
9181
+ anumber(h.blockLen);
9182
+ }
9183
+ function aexists(instance, checkFinished = true) {
9184
+ if (instance.destroyed)
9185
+ throw new Error("Hash instance has been destroyed");
9186
+ if (checkFinished && instance.finished)
9187
+ throw new Error("Hash#digest() has already been called");
9188
+ }
9189
+ function aoutput(out, instance) {
9190
+ abytes(out, void 0, "digestInto() output");
9191
+ const min = instance.outputLen;
9192
+ if (out.length < min) {
9193
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
9194
+ }
9195
+ }
9196
+ function clean(...arrays) {
9197
+ for (let i = 0; i < arrays.length; i++) {
9198
+ arrays[i].fill(0);
9199
+ }
9200
+ }
9201
+ function createView(arr) {
9202
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
9203
+ }
9204
+ function rotr(word, shift) {
9205
+ return word << 32 - shift | word >>> shift;
9206
+ }
9207
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
9208
+ // @ts-ignore
9209
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
9210
+ ))();
9211
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
9212
+ function bytesToHex4(bytes) {
9213
+ abytes(bytes);
9214
+ if (hasHexBuiltin)
9215
+ return bytes.toHex();
9216
+ let hex = "";
9217
+ for (let i = 0; i < bytes.length; i++) {
9218
+ hex += hexes[bytes[i]];
9219
+ }
9220
+ return hex;
9221
+ }
9222
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
9223
+ function asciiToBase16(ch) {
9224
+ if (ch >= asciis._0 && ch <= asciis._9)
9225
+ return ch - asciis._0;
9226
+ if (ch >= asciis.A && ch <= asciis.F)
9227
+ return ch - (asciis.A - 10);
9228
+ if (ch >= asciis.a && ch <= asciis.f)
9229
+ return ch - (asciis.a - 10);
9230
+ return;
9231
+ }
9232
+ function hexToBytes2(hex) {
9233
+ if (typeof hex !== "string")
9234
+ throw new Error("hex string expected, got " + typeof hex);
9235
+ if (hasHexBuiltin)
9236
+ return Uint8Array.fromHex(hex);
9237
+ const hl = hex.length;
9238
+ const al = hl / 2;
9239
+ if (hl % 2)
9240
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
9241
+ const array = new Uint8Array(al);
9242
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
9243
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
9244
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
9245
+ if (n1 === void 0 || n2 === void 0) {
9246
+ const char = hex[hi] + hex[hi + 1];
9247
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
9248
+ }
9249
+ array[ai] = n1 * 16 + n2;
9250
+ }
9251
+ return array;
9252
+ }
9253
+ function concatBytes(...arrays) {
9254
+ let sum = 0;
9255
+ for (let i = 0; i < arrays.length; i++) {
9256
+ const a = arrays[i];
9257
+ abytes(a);
9258
+ sum += a.length;
9259
+ }
9260
+ const res = new Uint8Array(sum);
9261
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
9262
+ const a = arrays[i];
9263
+ res.set(a, pad);
9264
+ pad += a.length;
9265
+ }
9266
+ return res;
9267
+ }
9268
+ function createHasher(hashCons, info = {}) {
9269
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
9270
+ const tmp = hashCons(void 0);
9271
+ hashC.outputLen = tmp.outputLen;
9272
+ hashC.blockLen = tmp.blockLen;
9273
+ hashC.create = (opts) => hashCons(opts);
9274
+ Object.assign(hashC, info);
9275
+ return Object.freeze(hashC);
9276
+ }
9277
+ function randomBytes2(bytesLength = 32) {
9278
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
9279
+ if (typeof cr?.getRandomValues !== "function")
9280
+ throw new Error("crypto.getRandomValues must be defined");
9281
+ return cr.getRandomValues(new Uint8Array(bytesLength));
9282
+ }
9283
+ var oidNist = (suffix) => ({
9284
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
9285
+ });
9286
+
9287
+ // node_modules/@noble/hashes/_md.js
9288
+ function Chi(a, b, c) {
9289
+ return a & b ^ ~a & c;
9290
+ }
9291
+ function Maj(a, b, c) {
9292
+ return a & b ^ a & c ^ b & c;
9293
+ }
9294
+ var HashMD = class {
9295
+ blockLen;
9296
+ outputLen;
9297
+ padOffset;
9298
+ isLE;
9299
+ // For partial updates less than block size
9300
+ buffer;
9301
+ view;
9302
+ finished = false;
9303
+ length = 0;
9304
+ pos = 0;
9305
+ destroyed = false;
9306
+ constructor(blockLen, outputLen, padOffset, isLE) {
9307
+ this.blockLen = blockLen;
9308
+ this.outputLen = outputLen;
9309
+ this.padOffset = padOffset;
9310
+ this.isLE = isLE;
9311
+ this.buffer = new Uint8Array(blockLen);
9312
+ this.view = createView(this.buffer);
9313
+ }
9314
+ update(data) {
9315
+ aexists(this);
9316
+ abytes(data);
9317
+ const { view, buffer, blockLen } = this;
9318
+ const len = data.length;
9319
+ for (let pos = 0; pos < len; ) {
9320
+ const take = Math.min(blockLen - this.pos, len - pos);
9321
+ if (take === blockLen) {
9322
+ const dataView = createView(data);
9323
+ for (; blockLen <= len - pos; pos += blockLen)
9324
+ this.process(dataView, pos);
9325
+ continue;
9326
+ }
9327
+ buffer.set(data.subarray(pos, pos + take), this.pos);
9328
+ this.pos += take;
9329
+ pos += take;
9330
+ if (this.pos === blockLen) {
9331
+ this.process(view, 0);
9332
+ this.pos = 0;
9333
+ }
9334
+ }
9335
+ this.length += data.length;
9336
+ this.roundClean();
9337
+ return this;
9338
+ }
9339
+ digestInto(out) {
9340
+ aexists(this);
9341
+ aoutput(out, this);
9342
+ this.finished = true;
9343
+ const { buffer, view, blockLen, isLE } = this;
9344
+ let { pos } = this;
9345
+ buffer[pos++] = 128;
9346
+ clean(this.buffer.subarray(pos));
9347
+ if (this.padOffset > blockLen - pos) {
9348
+ this.process(view, 0);
9349
+ pos = 0;
9350
+ }
9351
+ for (let i = pos; i < blockLen; i++)
9352
+ buffer[i] = 0;
9353
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
9354
+ this.process(view, 0);
9355
+ const oview = createView(out);
9356
+ const len = this.outputLen;
9357
+ if (len % 4)
9358
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
9359
+ const outLen = len / 4;
9360
+ const state = this.get();
9361
+ if (outLen > state.length)
9362
+ throw new Error("_sha2: outputLen bigger than state");
9363
+ for (let i = 0; i < outLen; i++)
9364
+ oview.setUint32(4 * i, state[i], isLE);
9365
+ }
9366
+ digest() {
9367
+ const { buffer, outputLen } = this;
9368
+ this.digestInto(buffer);
9369
+ const res = buffer.slice(0, outputLen);
9370
+ this.destroy();
9371
+ return res;
9372
+ }
9373
+ _cloneInto(to) {
9374
+ to ||= new this.constructor();
9375
+ to.set(...this.get());
9376
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
9377
+ to.destroyed = destroyed;
9378
+ to.finished = finished;
9379
+ to.length = length;
9380
+ to.pos = pos;
9381
+ if (length % blockLen)
9382
+ to.buffer.set(buffer);
9383
+ return to;
9384
+ }
9385
+ clone() {
9386
+ return this._cloneInto();
9387
+ }
9388
+ };
9389
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
9390
+ 1779033703,
9391
+ 3144134277,
9392
+ 1013904242,
9393
+ 2773480762,
9394
+ 1359893119,
9395
+ 2600822924,
9396
+ 528734635,
9397
+ 1541459225
9398
+ ]);
9399
+
9400
+ // node_modules/@noble/hashes/sha2.js
9401
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
9402
+ 1116352408,
9403
+ 1899447441,
9404
+ 3049323471,
9405
+ 3921009573,
9406
+ 961987163,
9407
+ 1508970993,
9408
+ 2453635748,
9409
+ 2870763221,
9410
+ 3624381080,
9411
+ 310598401,
9412
+ 607225278,
9413
+ 1426881987,
9414
+ 1925078388,
9415
+ 2162078206,
9416
+ 2614888103,
9417
+ 3248222580,
9418
+ 3835390401,
9419
+ 4022224774,
9420
+ 264347078,
9421
+ 604807628,
9422
+ 770255983,
9423
+ 1249150122,
9424
+ 1555081692,
9425
+ 1996064986,
9426
+ 2554220882,
9427
+ 2821834349,
9428
+ 2952996808,
9429
+ 3210313671,
9430
+ 3336571891,
9431
+ 3584528711,
9432
+ 113926993,
9433
+ 338241895,
9434
+ 666307205,
9435
+ 773529912,
9436
+ 1294757372,
9437
+ 1396182291,
9438
+ 1695183700,
9439
+ 1986661051,
9440
+ 2177026350,
9441
+ 2456956037,
9442
+ 2730485921,
9443
+ 2820302411,
9444
+ 3259730800,
9445
+ 3345764771,
9446
+ 3516065817,
9447
+ 3600352804,
9448
+ 4094571909,
9449
+ 275423344,
9450
+ 430227734,
9451
+ 506948616,
9452
+ 659060556,
9453
+ 883997877,
9454
+ 958139571,
9455
+ 1322822218,
9456
+ 1537002063,
9457
+ 1747873779,
9458
+ 1955562222,
9459
+ 2024104815,
9460
+ 2227730452,
9461
+ 2361852424,
9462
+ 2428436474,
9463
+ 2756734187,
9464
+ 3204031479,
9465
+ 3329325298
9466
+ ]);
9467
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
9468
+ var SHA2_32B = class extends HashMD {
9469
+ constructor(outputLen) {
9470
+ super(64, outputLen, 8, false);
9471
+ }
9472
+ get() {
9473
+ const { A, B, C, D, E, F, G, H } = this;
9474
+ return [A, B, C, D, E, F, G, H];
9475
+ }
9476
+ // prettier-ignore
9477
+ set(A, B, C, D, E, F, G, H) {
9478
+ this.A = A | 0;
9479
+ this.B = B | 0;
9480
+ this.C = C | 0;
9481
+ this.D = D | 0;
9482
+ this.E = E | 0;
9483
+ this.F = F | 0;
9484
+ this.G = G | 0;
9485
+ this.H = H | 0;
9486
+ }
9487
+ process(view, offset) {
9488
+ for (let i = 0; i < 16; i++, offset += 4)
9489
+ SHA256_W[i] = view.getUint32(offset, false);
9490
+ for (let i = 16; i < 64; i++) {
9491
+ const W15 = SHA256_W[i - 15];
9492
+ const W2 = SHA256_W[i - 2];
9493
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
9494
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
9495
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
9496
+ }
9497
+ let { A, B, C, D, E, F, G, H } = this;
9498
+ for (let i = 0; i < 64; i++) {
9499
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
9500
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
9501
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
9502
+ const T2 = sigma0 + Maj(A, B, C) | 0;
9503
+ H = G;
9504
+ G = F;
9505
+ F = E;
9506
+ E = D + T1 | 0;
9507
+ D = C;
9508
+ C = B;
9509
+ B = A;
9510
+ A = T1 + T2 | 0;
9511
+ }
9512
+ A = A + this.A | 0;
9513
+ B = B + this.B | 0;
9514
+ C = C + this.C | 0;
9515
+ D = D + this.D | 0;
9516
+ E = E + this.E | 0;
9517
+ F = F + this.F | 0;
9518
+ G = G + this.G | 0;
9519
+ H = H + this.H | 0;
9520
+ this.set(A, B, C, D, E, F, G, H);
9521
+ }
9522
+ roundClean() {
9523
+ clean(SHA256_W);
9524
+ }
9525
+ destroy() {
9526
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
9527
+ clean(this.buffer);
9528
+ }
9529
+ };
9530
+ var _SHA256 = class extends SHA2_32B {
9531
+ // We cannot use array here since array allows indexing by variable
9532
+ // which means optimizer/compiler cannot use registers.
9533
+ A = SHA256_IV[0] | 0;
9534
+ B = SHA256_IV[1] | 0;
9535
+ C = SHA256_IV[2] | 0;
9536
+ D = SHA256_IV[3] | 0;
9537
+ E = SHA256_IV[4] | 0;
9538
+ F = SHA256_IV[5] | 0;
9539
+ G = SHA256_IV[6] | 0;
9540
+ H = SHA256_IV[7] | 0;
9541
+ constructor() {
9542
+ super(32);
9543
+ }
9544
+ };
9545
+ var sha2564 = /* @__PURE__ */ createHasher(
9546
+ () => new _SHA256(),
9547
+ /* @__PURE__ */ oidNist(1)
9548
+ );
9549
+
9550
+ // node_modules/@noble/curves/utils.js
9551
+ var _0n = /* @__PURE__ */ BigInt(0);
9552
+ var _1n = /* @__PURE__ */ BigInt(1);
9553
+ function abool(value, title = "") {
9554
+ if (typeof value !== "boolean") {
9555
+ const prefix = title && `"${title}" `;
9556
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
9557
+ }
9558
+ return value;
9559
+ }
9560
+ function abignumber(n) {
9561
+ if (typeof n === "bigint") {
9562
+ if (!isPosBig(n))
9563
+ throw new Error("positive bigint expected, got " + n);
9564
+ } else
9565
+ anumber(n);
9566
+ return n;
9567
+ }
9568
+ function numberToHexUnpadded(num) {
9569
+ const hex = abignumber(num).toString(16);
9570
+ return hex.length & 1 ? "0" + hex : hex;
9571
+ }
9572
+ function hexToNumber(hex) {
9573
+ if (typeof hex !== "string")
9574
+ throw new Error("hex string expected, got " + typeof hex);
9575
+ return hex === "" ? _0n : BigInt("0x" + hex);
9576
+ }
9577
+ function bytesToNumberBE(bytes) {
9578
+ return hexToNumber(bytesToHex4(bytes));
9579
+ }
9580
+ function bytesToNumberLE(bytes) {
9581
+ return hexToNumber(bytesToHex4(copyBytes(abytes(bytes)).reverse()));
9582
+ }
9583
+ function numberToBytesBE(n, len) {
9584
+ anumber(len);
9585
+ n = abignumber(n);
9586
+ const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
9587
+ if (res.length !== len)
9588
+ throw new Error("number too large");
9589
+ return res;
9590
+ }
9591
+ function numberToBytesLE(n, len) {
9592
+ return numberToBytesBE(n, len).reverse();
9593
+ }
9594
+ function copyBytes(bytes) {
9595
+ return Uint8Array.from(bytes);
9596
+ }
9597
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
9598
+ function inRange(n, min, max) {
9599
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
9600
+ }
9601
+ function aInRange(title, n, min, max) {
9602
+ if (!inRange(n, min, max))
9603
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
9604
+ }
9605
+ function bitLen(n) {
9606
+ let len;
9607
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
9608
+ ;
9609
+ return len;
9610
+ }
9611
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
9612
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
9613
+ anumber(hashLen, "hashLen");
9614
+ anumber(qByteLen, "qByteLen");
9615
+ if (typeof hmacFn !== "function")
9616
+ throw new Error("hmacFn must be a function");
9617
+ const u8n = (len) => new Uint8Array(len);
9618
+ const NULL = Uint8Array.of();
9619
+ const byte0 = Uint8Array.of(0);
9620
+ const byte1 = Uint8Array.of(1);
9621
+ const _maxDrbgIters = 1e3;
9622
+ let v = u8n(hashLen);
9623
+ let k = u8n(hashLen);
9624
+ let i = 0;
9625
+ const reset = () => {
9626
+ v.fill(1);
9627
+ k.fill(0);
9628
+ i = 0;
9629
+ };
9630
+ const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
9631
+ const reseed = (seed = NULL) => {
9632
+ k = h(byte0, seed);
9633
+ v = h();
9634
+ if (seed.length === 0)
9635
+ return;
9636
+ k = h(byte1, seed);
9637
+ v = h();
9638
+ };
9639
+ const gen = () => {
9640
+ if (i++ >= _maxDrbgIters)
9641
+ throw new Error("drbg: tried max amount of iterations");
9642
+ let len = 0;
9643
+ const out = [];
9644
+ while (len < qByteLen) {
9645
+ v = h();
9646
+ const sl = v.slice();
9647
+ out.push(sl);
9648
+ len += v.length;
9649
+ }
9650
+ return concatBytes(...out);
9651
+ };
9652
+ const genUntil = (seed, pred) => {
9653
+ reset();
9654
+ reseed(seed);
9655
+ let res = void 0;
9656
+ while (!(res = pred(gen())))
9657
+ reseed();
9658
+ reset();
9659
+ return res;
9660
+ };
9661
+ return genUntil;
9662
+ }
9663
+ function validateObject(object, fields = {}, optFields = {}) {
9664
+ if (!object || typeof object !== "object")
9665
+ throw new Error("expected valid options object");
9666
+ function checkField(fieldName, expectedType, isOpt) {
9667
+ const val = object[fieldName];
9668
+ if (isOpt && val === void 0)
9669
+ return;
9670
+ const current = typeof val;
9671
+ if (current !== expectedType || val === null)
9672
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
9673
+ }
9674
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
9675
+ iter(fields, false);
9676
+ iter(optFields, true);
9677
+ }
9678
+ function memoized(fn) {
9679
+ const map = /* @__PURE__ */ new WeakMap();
9680
+ return (arg, ...args) => {
9681
+ const val = map.get(arg);
9682
+ if (val !== void 0)
9683
+ return val;
9684
+ const computed = fn(arg, ...args);
9685
+ map.set(arg, computed);
9686
+ return computed;
9687
+ };
9688
+ }
9689
+
9690
+ // node_modules/@noble/curves/abstract/modular.js
9691
+ var _0n2 = /* @__PURE__ */ BigInt(0);
9692
+ var _1n2 = /* @__PURE__ */ BigInt(1);
9693
+ var _2n = /* @__PURE__ */ BigInt(2);
9694
+ var _3n = /* @__PURE__ */ BigInt(3);
9695
+ var _4n = /* @__PURE__ */ BigInt(4);
9696
+ var _5n = /* @__PURE__ */ BigInt(5);
9697
+ var _7n = /* @__PURE__ */ BigInt(7);
9698
+ var _8n = /* @__PURE__ */ BigInt(8);
9699
+ var _9n = /* @__PURE__ */ BigInt(9);
9700
+ var _16n = /* @__PURE__ */ BigInt(16);
9701
+ function mod(a, b) {
9702
+ const result = a % b;
9703
+ return result >= _0n2 ? result : b + result;
9704
+ }
9705
+ function pow2(x, power, modulo) {
9706
+ let res = x;
9707
+ while (power-- > _0n2) {
9708
+ res *= res;
9709
+ res %= modulo;
9710
+ }
9711
+ return res;
9712
+ }
9713
+ function invert(number, modulo) {
9714
+ if (number === _0n2)
9715
+ throw new Error("invert: expected non-zero number");
9716
+ if (modulo <= _0n2)
9717
+ throw new Error("invert: expected positive modulus, got " + modulo);
9718
+ let a = mod(number, modulo);
9719
+ let b = modulo;
9720
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
9721
+ while (a !== _0n2) {
9722
+ const q = b / a;
9723
+ const r = b % a;
9724
+ const m = x - u * q;
9725
+ const n = y - v * q;
9726
+ b = a, a = r, x = u, y = v, u = m, v = n;
9727
+ }
9728
+ const gcd = b;
9729
+ if (gcd !== _1n2)
9730
+ throw new Error("invert: does not exist");
9731
+ return mod(x, modulo);
9732
+ }
9733
+ function assertIsSquare(Fp, root, n) {
9734
+ if (!Fp.eql(Fp.sqr(root), n))
9735
+ throw new Error("Cannot find square root");
9736
+ }
9737
+ function sqrt3mod4(Fp, n) {
9738
+ const p1div4 = (Fp.ORDER + _1n2) / _4n;
9739
+ const root = Fp.pow(n, p1div4);
9740
+ assertIsSquare(Fp, root, n);
9741
+ return root;
9742
+ }
9743
+ function sqrt5mod8(Fp, n) {
9744
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
9745
+ const n2 = Fp.mul(n, _2n);
9746
+ const v = Fp.pow(n2, p5div8);
9747
+ const nv = Fp.mul(n, v);
9748
+ const i = Fp.mul(Fp.mul(nv, _2n), v);
9749
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
9750
+ assertIsSquare(Fp, root, n);
9751
+ return root;
9752
+ }
9753
+ function sqrt9mod16(P) {
9754
+ const Fp_ = Field(P);
9755
+ const tn = tonelliShanks(P);
9756
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
9757
+ const c2 = tn(Fp_, c1);
9758
+ const c3 = tn(Fp_, Fp_.neg(c1));
9759
+ const c4 = (P + _7n) / _16n;
9760
+ return (Fp, n) => {
9761
+ let tv1 = Fp.pow(n, c4);
9762
+ let tv2 = Fp.mul(tv1, c1);
9763
+ const tv3 = Fp.mul(tv1, c2);
9764
+ const tv4 = Fp.mul(tv1, c3);
9765
+ const e1 = Fp.eql(Fp.sqr(tv2), n);
9766
+ const e2 = Fp.eql(Fp.sqr(tv3), n);
9767
+ tv1 = Fp.cmov(tv1, tv2, e1);
9768
+ tv2 = Fp.cmov(tv4, tv3, e2);
9769
+ const e3 = Fp.eql(Fp.sqr(tv2), n);
9770
+ const root = Fp.cmov(tv1, tv2, e3);
9771
+ assertIsSquare(Fp, root, n);
9772
+ return root;
9773
+ };
9774
+ }
9775
+ function tonelliShanks(P) {
9776
+ if (P < _3n)
9777
+ throw new Error("sqrt is not defined for small field");
9778
+ let Q = P - _1n2;
9779
+ let S = 0;
9780
+ while (Q % _2n === _0n2) {
9781
+ Q /= _2n;
9782
+ S++;
9783
+ }
9784
+ let Z = _2n;
9785
+ const _Fp = Field(P);
9786
+ while (FpLegendre(_Fp, Z) === 1) {
9787
+ if (Z++ > 1e3)
9788
+ throw new Error("Cannot find square root: probably non-prime P");
9789
+ }
9790
+ if (S === 1)
9791
+ return sqrt3mod4;
9792
+ let cc = _Fp.pow(Z, Q);
9793
+ const Q1div2 = (Q + _1n2) / _2n;
9794
+ return function tonelliSlow(Fp, n) {
9795
+ if (Fp.is0(n))
9796
+ return n;
9797
+ if (FpLegendre(Fp, n) !== 1)
9798
+ throw new Error("Cannot find square root");
9799
+ let M = S;
9800
+ let c = Fp.mul(Fp.ONE, cc);
9801
+ let t = Fp.pow(n, Q);
9802
+ let R = Fp.pow(n, Q1div2);
9803
+ while (!Fp.eql(t, Fp.ONE)) {
9804
+ if (Fp.is0(t))
9805
+ return Fp.ZERO;
9806
+ let i = 1;
9807
+ let t_tmp = Fp.sqr(t);
9808
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
9809
+ i++;
9810
+ t_tmp = Fp.sqr(t_tmp);
9811
+ if (i === M)
9812
+ throw new Error("Cannot find square root");
9813
+ }
9814
+ const exponent = _1n2 << BigInt(M - i - 1);
9815
+ const b = Fp.pow(c, exponent);
9816
+ M = i;
9817
+ c = Fp.sqr(b);
9818
+ t = Fp.mul(t, c);
9819
+ R = Fp.mul(R, b);
9820
+ }
9821
+ return R;
9822
+ };
9823
+ }
9824
+ function FpSqrt(P) {
9825
+ if (P % _4n === _3n)
9826
+ return sqrt3mod4;
9827
+ if (P % _8n === _5n)
9828
+ return sqrt5mod8;
9829
+ if (P % _16n === _9n)
9830
+ return sqrt9mod16(P);
9831
+ return tonelliShanks(P);
9832
+ }
9833
+ var FIELD_FIELDS = [
9834
+ "create",
9835
+ "isValid",
9836
+ "is0",
9837
+ "neg",
9838
+ "inv",
9839
+ "sqrt",
9840
+ "sqr",
9841
+ "eql",
9842
+ "add",
9843
+ "sub",
9844
+ "mul",
9845
+ "pow",
9846
+ "div",
9847
+ "addN",
9848
+ "subN",
9849
+ "mulN",
9850
+ "sqrN"
9851
+ ];
9852
+ function validateField(field) {
9853
+ const initial = {
9854
+ ORDER: "bigint",
9855
+ BYTES: "number",
9856
+ BITS: "number"
9857
+ };
9858
+ const opts = FIELD_FIELDS.reduce((map, val) => {
9859
+ map[val] = "function";
9860
+ return map;
9861
+ }, initial);
9862
+ validateObject(field, opts);
9863
+ return field;
9864
+ }
9865
+ function FpPow(Fp, num, power) {
9866
+ if (power < _0n2)
9867
+ throw new Error("invalid exponent, negatives unsupported");
9868
+ if (power === _0n2)
9869
+ return Fp.ONE;
9870
+ if (power === _1n2)
9871
+ return num;
9872
+ let p = Fp.ONE;
9873
+ let d = num;
9874
+ while (power > _0n2) {
9875
+ if (power & _1n2)
9876
+ p = Fp.mul(p, d);
9877
+ d = Fp.sqr(d);
9878
+ power >>= _1n2;
9879
+ }
9880
+ return p;
9881
+ }
9882
+ function FpInvertBatch(Fp, nums, passZero = false) {
9883
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
9884
+ const multipliedAcc = nums.reduce((acc, num, i) => {
9885
+ if (Fp.is0(num))
9886
+ return acc;
9887
+ inverted[i] = acc;
9888
+ return Fp.mul(acc, num);
9889
+ }, Fp.ONE);
9890
+ const invertedAcc = Fp.inv(multipliedAcc);
9891
+ nums.reduceRight((acc, num, i) => {
9892
+ if (Fp.is0(num))
9893
+ return acc;
9894
+ inverted[i] = Fp.mul(acc, inverted[i]);
9895
+ return Fp.mul(acc, num);
9896
+ }, invertedAcc);
9897
+ return inverted;
9898
+ }
9899
+ function FpLegendre(Fp, n) {
9900
+ const p1mod2 = (Fp.ORDER - _1n2) / _2n;
9901
+ const powered = Fp.pow(n, p1mod2);
9902
+ const yes = Fp.eql(powered, Fp.ONE);
9903
+ const zero = Fp.eql(powered, Fp.ZERO);
9904
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
9905
+ if (!yes && !zero && !no)
9906
+ throw new Error("invalid Legendre symbol result");
9907
+ return yes ? 1 : zero ? 0 : -1;
9908
+ }
9909
+ function nLength(n, nBitLength) {
9910
+ if (nBitLength !== void 0)
9911
+ anumber(nBitLength);
9912
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
9913
+ const nByteLength = Math.ceil(_nBitLength / 8);
9914
+ return { nBitLength: _nBitLength, nByteLength };
9915
+ }
9916
+ var _Field = class {
9917
+ ORDER;
9918
+ BITS;
9919
+ BYTES;
9920
+ isLE;
9921
+ ZERO = _0n2;
9922
+ ONE = _1n2;
9923
+ _lengths;
9924
+ _sqrt;
9925
+ // cached sqrt
9926
+ _mod;
9927
+ constructor(ORDER, opts = {}) {
9928
+ if (ORDER <= _0n2)
9929
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
9930
+ let _nbitLength = void 0;
9931
+ this.isLE = false;
9932
+ if (opts != null && typeof opts === "object") {
9933
+ if (typeof opts.BITS === "number")
9934
+ _nbitLength = opts.BITS;
9935
+ if (typeof opts.sqrt === "function")
9936
+ this.sqrt = opts.sqrt;
9937
+ if (typeof opts.isLE === "boolean")
9938
+ this.isLE = opts.isLE;
9939
+ if (opts.allowedLengths)
9940
+ this._lengths = opts.allowedLengths?.slice();
9941
+ if (typeof opts.modFromBytes === "boolean")
9942
+ this._mod = opts.modFromBytes;
9943
+ }
9944
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
9945
+ if (nByteLength > 2048)
9946
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
9947
+ this.ORDER = ORDER;
9948
+ this.BITS = nBitLength;
9949
+ this.BYTES = nByteLength;
9950
+ this._sqrt = void 0;
9951
+ Object.preventExtensions(this);
9952
+ }
9953
+ create(num) {
9954
+ return mod(num, this.ORDER);
9955
+ }
9956
+ isValid(num) {
9957
+ if (typeof num !== "bigint")
9958
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
9959
+ return _0n2 <= num && num < this.ORDER;
9960
+ }
9961
+ is0(num) {
9962
+ return num === _0n2;
9963
+ }
9964
+ // is valid and invertible
9965
+ isValidNot0(num) {
9966
+ return !this.is0(num) && this.isValid(num);
9967
+ }
9968
+ isOdd(num) {
9969
+ return (num & _1n2) === _1n2;
9970
+ }
9971
+ neg(num) {
9972
+ return mod(-num, this.ORDER);
9973
+ }
9974
+ eql(lhs, rhs) {
9975
+ return lhs === rhs;
9976
+ }
9977
+ sqr(num) {
9978
+ return mod(num * num, this.ORDER);
9979
+ }
9980
+ add(lhs, rhs) {
9981
+ return mod(lhs + rhs, this.ORDER);
9982
+ }
9983
+ sub(lhs, rhs) {
9984
+ return mod(lhs - rhs, this.ORDER);
9985
+ }
9986
+ mul(lhs, rhs) {
9987
+ return mod(lhs * rhs, this.ORDER);
9988
+ }
9989
+ pow(num, power) {
9990
+ return FpPow(this, num, power);
9991
+ }
9992
+ div(lhs, rhs) {
9993
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
9994
+ }
9995
+ // Same as above, but doesn't normalize
9996
+ sqrN(num) {
9997
+ return num * num;
9998
+ }
9999
+ addN(lhs, rhs) {
10000
+ return lhs + rhs;
10001
+ }
10002
+ subN(lhs, rhs) {
10003
+ return lhs - rhs;
10004
+ }
10005
+ mulN(lhs, rhs) {
10006
+ return lhs * rhs;
10007
+ }
10008
+ inv(num) {
10009
+ return invert(num, this.ORDER);
10010
+ }
10011
+ sqrt(num) {
10012
+ if (!this._sqrt)
10013
+ this._sqrt = FpSqrt(this.ORDER);
10014
+ return this._sqrt(this, num);
10015
+ }
10016
+ toBytes(num) {
10017
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
10018
+ }
10019
+ fromBytes(bytes, skipValidation = false) {
10020
+ abytes(bytes);
10021
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
10022
+ if (allowedLengths) {
10023
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
10024
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
10025
+ }
10026
+ const padded = new Uint8Array(BYTES);
10027
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
10028
+ bytes = padded;
10029
+ }
10030
+ if (bytes.length !== BYTES)
10031
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
10032
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
10033
+ if (modFromBytes)
10034
+ scalar = mod(scalar, ORDER);
10035
+ if (!skipValidation) {
10036
+ if (!this.isValid(scalar))
10037
+ throw new Error("invalid field element: outside of range 0..ORDER");
10038
+ }
10039
+ return scalar;
10040
+ }
10041
+ // TODO: we don't need it here, move out to separate fn
10042
+ invertBatch(lst) {
10043
+ return FpInvertBatch(this, lst);
10044
+ }
10045
+ // We can't move this out because Fp6, Fp12 implement it
10046
+ // and it's unclear what to return in there.
10047
+ cmov(a, b, condition) {
10048
+ return condition ? b : a;
10049
+ }
10050
+ };
10051
+ function Field(ORDER, opts = {}) {
10052
+ return new _Field(ORDER, opts);
10053
+ }
10054
+ function getFieldBytesLength(fieldOrder) {
10055
+ if (typeof fieldOrder !== "bigint")
10056
+ throw new Error("field order must be bigint");
10057
+ const bitLength = fieldOrder.toString(2).length;
10058
+ return Math.ceil(bitLength / 8);
10059
+ }
10060
+ function getMinHashLength(fieldOrder) {
10061
+ const length = getFieldBytesLength(fieldOrder);
10062
+ return length + Math.ceil(length / 2);
10063
+ }
10064
+ function mapHashToField(key, fieldOrder, isLE = false) {
10065
+ abytes(key);
10066
+ const len = key.length;
10067
+ const fieldLen = getFieldBytesLength(fieldOrder);
10068
+ const minLen = getMinHashLength(fieldOrder);
10069
+ if (len < 16 || len < minLen || len > 1024)
10070
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
10071
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
10072
+ const reduced = mod(num, fieldOrder - _1n2) + _1n2;
10073
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
10074
+ }
10075
+
10076
+ // node_modules/@noble/curves/abstract/curve.js
10077
+ var _0n3 = /* @__PURE__ */ BigInt(0);
10078
+ var _1n3 = /* @__PURE__ */ BigInt(1);
10079
+ function negateCt(condition, item) {
10080
+ const neg = item.negate();
10081
+ return condition ? neg : item;
10082
+ }
10083
+ function normalizeZ(c, points) {
10084
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
10085
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
10086
+ }
10087
+ function validateW(W, bits) {
10088
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
10089
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
10090
+ }
10091
+ function calcWOpts(W, scalarBits) {
10092
+ validateW(W, scalarBits);
10093
+ const windows = Math.ceil(scalarBits / W) + 1;
10094
+ const windowSize = 2 ** (W - 1);
10095
+ const maxNumber = 2 ** W;
10096
+ const mask = bitMask(W);
10097
+ const shiftBy = BigInt(W);
10098
+ return { windows, windowSize, mask, maxNumber, shiftBy };
10099
+ }
10100
+ function calcOffsets(n, window, wOpts) {
10101
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
10102
+ let wbits = Number(n & mask);
10103
+ let nextN = n >> shiftBy;
10104
+ if (wbits > windowSize) {
10105
+ wbits -= maxNumber;
10106
+ nextN += _1n3;
10107
+ }
10108
+ const offsetStart = window * windowSize;
10109
+ const offset = offsetStart + Math.abs(wbits) - 1;
10110
+ const isZero = wbits === 0;
10111
+ const isNeg = wbits < 0;
10112
+ const isNegF = window % 2 !== 0;
10113
+ const offsetF = offsetStart;
10114
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
10115
+ }
10116
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
10117
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
10118
+ function getW(P) {
10119
+ return pointWindowSizes.get(P) || 1;
10120
+ }
10121
+ function assert0(n) {
10122
+ if (n !== _0n3)
10123
+ throw new Error("invalid wNAF");
10124
+ }
10125
+ var wNAF = class {
10126
+ BASE;
10127
+ ZERO;
10128
+ Fn;
10129
+ bits;
10130
+ // Parametrized with a given Point class (not individual point)
10131
+ constructor(Point, bits) {
10132
+ this.BASE = Point.BASE;
10133
+ this.ZERO = Point.ZERO;
10134
+ this.Fn = Point.Fn;
10135
+ this.bits = bits;
10136
+ }
10137
+ // non-const time multiplication ladder
10138
+ _unsafeLadder(elm, n, p = this.ZERO) {
10139
+ let d = elm;
10140
+ while (n > _0n3) {
10141
+ if (n & _1n3)
10142
+ p = p.add(d);
10143
+ d = d.double();
10144
+ n >>= _1n3;
10145
+ }
10146
+ return p;
10147
+ }
10148
+ /**
10149
+ * Creates a wNAF precomputation window. Used for caching.
10150
+ * Default window size is set by `utils.precompute()` and is equal to 8.
10151
+ * Number of precomputed points depends on the curve size:
10152
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
10153
+ * - 𝑊 is the window size
10154
+ * - 𝑛 is the bitlength of the curve order.
10155
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
10156
+ * @param point Point instance
10157
+ * @param W window size
10158
+ * @returns precomputed point tables flattened to a single array
10159
+ */
10160
+ precomputeWindow(point, W) {
10161
+ const { windows, windowSize } = calcWOpts(W, this.bits);
10162
+ const points = [];
10163
+ let p = point;
10164
+ let base = p;
10165
+ for (let window = 0; window < windows; window++) {
10166
+ base = p;
10167
+ points.push(base);
10168
+ for (let i = 1; i < windowSize; i++) {
10169
+ base = base.add(p);
10170
+ points.push(base);
10171
+ }
10172
+ p = base.double();
10173
+ }
10174
+ return points;
10175
+ }
10176
+ /**
10177
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
10178
+ * More compact implementation:
10179
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
10180
+ * @returns real and fake (for const-time) points
10181
+ */
10182
+ wNAF(W, precomputes, n) {
10183
+ if (!this.Fn.isValid(n))
10184
+ throw new Error("invalid scalar");
10185
+ let p = this.ZERO;
10186
+ let f = this.BASE;
10187
+ const wo = calcWOpts(W, this.bits);
10188
+ for (let window = 0; window < wo.windows; window++) {
10189
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
10190
+ n = nextN;
10191
+ if (isZero) {
10192
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
10193
+ } else {
10194
+ p = p.add(negateCt(isNeg, precomputes[offset]));
10195
+ }
10196
+ }
10197
+ assert0(n);
10198
+ return { p, f };
10199
+ }
10200
+ /**
10201
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
10202
+ * @param acc accumulator point to add result of multiplication
10203
+ * @returns point
10204
+ */
10205
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
10206
+ const wo = calcWOpts(W, this.bits);
10207
+ for (let window = 0; window < wo.windows; window++) {
10208
+ if (n === _0n3)
10209
+ break;
10210
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
10211
+ n = nextN;
10212
+ if (isZero) {
10213
+ continue;
10214
+ } else {
10215
+ const item = precomputes[offset];
10216
+ acc = acc.add(isNeg ? item.negate() : item);
10217
+ }
10218
+ }
10219
+ assert0(n);
10220
+ return acc;
10221
+ }
10222
+ getPrecomputes(W, point, transform) {
10223
+ let comp = pointPrecomputes.get(point);
10224
+ if (!comp) {
10225
+ comp = this.precomputeWindow(point, W);
10226
+ if (W !== 1) {
10227
+ if (typeof transform === "function")
10228
+ comp = transform(comp);
10229
+ pointPrecomputes.set(point, comp);
10230
+ }
10231
+ }
10232
+ return comp;
10233
+ }
10234
+ cached(point, scalar, transform) {
10235
+ const W = getW(point);
10236
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
10237
+ }
10238
+ unsafe(point, scalar, transform, prev) {
10239
+ const W = getW(point);
10240
+ if (W === 1)
10241
+ return this._unsafeLadder(point, scalar, prev);
10242
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
10243
+ }
10244
+ // We calculate precomputes for elliptic curve point multiplication
10245
+ // using windowed method. This specifies window size and
10246
+ // stores precomputed values. Usually only base point would be precomputed.
10247
+ createCache(P, W) {
10248
+ validateW(W, this.bits);
10249
+ pointWindowSizes.set(P, W);
10250
+ pointPrecomputes.delete(P);
10251
+ }
10252
+ hasCache(elm) {
10253
+ return getW(elm) !== 1;
10254
+ }
10255
+ };
10256
+ function mulEndoUnsafe(Point, point, k1, k2) {
10257
+ let acc = point;
10258
+ let p1 = Point.ZERO;
10259
+ let p2 = Point.ZERO;
10260
+ while (k1 > _0n3 || k2 > _0n3) {
10261
+ if (k1 & _1n3)
10262
+ p1 = p1.add(acc);
10263
+ if (k2 & _1n3)
10264
+ p2 = p2.add(acc);
10265
+ acc = acc.double();
10266
+ k1 >>= _1n3;
10267
+ k2 >>= _1n3;
10268
+ }
10269
+ return { p1, p2 };
10270
+ }
10271
+ function createField(order, field, isLE) {
10272
+ if (field) {
10273
+ if (field.ORDER !== order)
10274
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
10275
+ validateField(field);
10276
+ return field;
10277
+ } else {
10278
+ return Field(order, { isLE });
10279
+ }
10280
+ }
10281
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
10282
+ if (FpFnLE === void 0)
10283
+ FpFnLE = type === "edwards";
10284
+ if (!CURVE || typeof CURVE !== "object")
10285
+ throw new Error(`expected valid ${type} CURVE object`);
10286
+ for (const p of ["p", "n", "h"]) {
10287
+ const val = CURVE[p];
10288
+ if (!(typeof val === "bigint" && val > _0n3))
10289
+ throw new Error(`CURVE.${p} must be positive bigint`);
10290
+ }
10291
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
10292
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
10293
+ const _b = type === "weierstrass" ? "b" : "d";
10294
+ const params = ["Gx", "Gy", "a", _b];
10295
+ for (const p of params) {
10296
+ if (!Fp.isValid(CURVE[p]))
10297
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
10298
+ }
10299
+ CURVE = Object.freeze(Object.assign({}, CURVE));
10300
+ return { CURVE, Fp, Fn };
10301
+ }
10302
+ function createKeygen(randomSecretKey, getPublicKey2) {
10303
+ return function keygen(seed) {
10304
+ const secretKey = randomSecretKey(seed);
10305
+ return { secretKey, publicKey: getPublicKey2(secretKey) };
10306
+ };
10307
+ }
10308
+
10309
+ // node_modules/@noble/hashes/hmac.js
10310
+ var _HMAC = class {
10311
+ oHash;
10312
+ iHash;
10313
+ blockLen;
10314
+ outputLen;
10315
+ finished = false;
10316
+ destroyed = false;
10317
+ constructor(hash, key) {
10318
+ ahash(hash);
10319
+ abytes(key, void 0, "key");
10320
+ this.iHash = hash.create();
10321
+ if (typeof this.iHash.update !== "function")
10322
+ throw new Error("Expected instance of class which extends utils.Hash");
10323
+ this.blockLen = this.iHash.blockLen;
10324
+ this.outputLen = this.iHash.outputLen;
10325
+ const blockLen = this.blockLen;
10326
+ const pad = new Uint8Array(blockLen);
10327
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
10328
+ for (let i = 0; i < pad.length; i++)
10329
+ pad[i] ^= 54;
10330
+ this.iHash.update(pad);
10331
+ this.oHash = hash.create();
10332
+ for (let i = 0; i < pad.length; i++)
10333
+ pad[i] ^= 54 ^ 92;
10334
+ this.oHash.update(pad);
10335
+ clean(pad);
10336
+ }
10337
+ update(buf) {
10338
+ aexists(this);
10339
+ this.iHash.update(buf);
10340
+ return this;
10341
+ }
10342
+ digestInto(out) {
10343
+ aexists(this);
10344
+ abytes(out, this.outputLen, "output");
10345
+ this.finished = true;
10346
+ this.iHash.digestInto(out);
10347
+ this.oHash.update(out);
10348
+ this.oHash.digestInto(out);
10349
+ this.destroy();
10350
+ }
10351
+ digest() {
10352
+ const out = new Uint8Array(this.oHash.outputLen);
10353
+ this.digestInto(out);
10354
+ return out;
10355
+ }
10356
+ _cloneInto(to) {
10357
+ to ||= Object.create(Object.getPrototypeOf(this), {});
10358
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
10359
+ to = to;
10360
+ to.finished = finished;
10361
+ to.destroyed = destroyed;
10362
+ to.blockLen = blockLen;
10363
+ to.outputLen = outputLen;
10364
+ to.oHash = oHash._cloneInto(to.oHash);
10365
+ to.iHash = iHash._cloneInto(to.iHash);
10366
+ return to;
10367
+ }
10368
+ clone() {
10369
+ return this._cloneInto();
10370
+ }
10371
+ destroy() {
10372
+ this.destroyed = true;
10373
+ this.oHash.destroy();
10374
+ this.iHash.destroy();
10375
+ }
10376
+ };
10377
+ var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
10378
+ hmac.create = (hash, key) => new _HMAC(hash, key);
10379
+
10380
+ // node_modules/@noble/curves/abstract/weierstrass.js
10381
+ var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
10382
+ function _splitEndoScalar(k, basis, n) {
10383
+ const [[a1, b1], [a2, b2]] = basis;
10384
+ const c1 = divNearest(b2 * k, n);
10385
+ const c2 = divNearest(-b1 * k, n);
10386
+ let k1 = k - c1 * a1 - c2 * a2;
10387
+ let k2 = -c1 * b1 - c2 * b2;
10388
+ const k1neg = k1 < _0n4;
10389
+ const k2neg = k2 < _0n4;
10390
+ if (k1neg)
10391
+ k1 = -k1;
10392
+ if (k2neg)
10393
+ k2 = -k2;
10394
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
10395
+ if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
10396
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
10397
+ }
10398
+ return { k1neg, k1, k2neg, k2 };
10399
+ }
10400
+ function validateSigFormat(format) {
10401
+ if (!["compact", "recovered", "der"].includes(format))
10402
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
10403
+ return format;
10404
+ }
10405
+ function validateSigOpts(opts, def) {
10406
+ const optsn = {};
10407
+ for (let optName of Object.keys(def)) {
10408
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
10409
+ }
10410
+ abool(optsn.lowS, "lowS");
10411
+ abool(optsn.prehash, "prehash");
10412
+ if (optsn.format !== void 0)
10413
+ validateSigFormat(optsn.format);
10414
+ return optsn;
10415
+ }
10416
+ var DERErr = class extends Error {
10417
+ constructor(m = "") {
10418
+ super(m);
10419
+ }
10420
+ };
10421
+ var DER = {
10422
+ // asn.1 DER encoding utils
10423
+ Err: DERErr,
10424
+ // Basic building block is TLV (Tag-Length-Value)
10425
+ _tlv: {
10426
+ encode: (tag, data) => {
10427
+ const { Err: E } = DER;
10428
+ if (tag < 0 || tag > 256)
10429
+ throw new E("tlv.encode: wrong tag");
10430
+ if (data.length & 1)
10431
+ throw new E("tlv.encode: unpadded data");
10432
+ const dataLen = data.length / 2;
10433
+ const len = numberToHexUnpadded(dataLen);
10434
+ if (len.length / 2 & 128)
10435
+ throw new E("tlv.encode: long form length too big");
10436
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
10437
+ const t = numberToHexUnpadded(tag);
10438
+ return t + lenLen + len + data;
10439
+ },
10440
+ // v - value, l - left bytes (unparsed)
10441
+ decode(tag, data) {
10442
+ const { Err: E } = DER;
10443
+ let pos = 0;
10444
+ if (tag < 0 || tag > 256)
10445
+ throw new E("tlv.encode: wrong tag");
10446
+ if (data.length < 2 || data[pos++] !== tag)
10447
+ throw new E("tlv.decode: wrong tlv");
10448
+ const first = data[pos++];
10449
+ const isLong = !!(first & 128);
10450
+ let length = 0;
10451
+ if (!isLong)
10452
+ length = first;
10453
+ else {
10454
+ const lenLen = first & 127;
10455
+ if (!lenLen)
10456
+ throw new E("tlv.decode(long): indefinite length not supported");
10457
+ if (lenLen > 4)
10458
+ throw new E("tlv.decode(long): byte length is too big");
10459
+ const lengthBytes = data.subarray(pos, pos + lenLen);
10460
+ if (lengthBytes.length !== lenLen)
10461
+ throw new E("tlv.decode: length bytes not complete");
10462
+ if (lengthBytes[0] === 0)
10463
+ throw new E("tlv.decode(long): zero leftmost byte");
10464
+ for (const b of lengthBytes)
10465
+ length = length << 8 | b;
10466
+ pos += lenLen;
10467
+ if (length < 128)
10468
+ throw new E("tlv.decode(long): not minimal encoding");
10469
+ }
10470
+ const v = data.subarray(pos, pos + length);
10471
+ if (v.length !== length)
10472
+ throw new E("tlv.decode: wrong value length");
10473
+ return { v, l: data.subarray(pos + length) };
10474
+ }
10475
+ },
10476
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
10477
+ // since we always use positive integers here. It must always be empty:
10478
+ // - add zero byte if exists
10479
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
10480
+ _int: {
10481
+ encode(num) {
10482
+ const { Err: E } = DER;
10483
+ if (num < _0n4)
10484
+ throw new E("integer: negative integers are not allowed");
10485
+ let hex = numberToHexUnpadded(num);
10486
+ if (Number.parseInt(hex[0], 16) & 8)
10487
+ hex = "00" + hex;
10488
+ if (hex.length & 1)
10489
+ throw new E("unexpected DER parsing assertion: unpadded hex");
10490
+ return hex;
10491
+ },
10492
+ decode(data) {
10493
+ const { Err: E } = DER;
10494
+ if (data[0] & 128)
10495
+ throw new E("invalid signature integer: negative");
10496
+ if (data[0] === 0 && !(data[1] & 128))
10497
+ throw new E("invalid signature integer: unnecessary leading zero");
10498
+ return bytesToNumberBE(data);
10499
+ }
10500
+ },
10501
+ toSig(bytes) {
10502
+ const { Err: E, _int: int, _tlv: tlv } = DER;
10503
+ const data = abytes(bytes, void 0, "signature");
10504
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
10505
+ if (seqLeftBytes.length)
10506
+ throw new E("invalid signature: left bytes after parsing");
10507
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
10508
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
10509
+ if (sLeftBytes.length)
10510
+ throw new E("invalid signature: left bytes after parsing");
10511
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
10512
+ },
10513
+ hexFromSig(sig) {
10514
+ const { _tlv: tlv, _int: int } = DER;
10515
+ const rs = tlv.encode(2, int.encode(sig.r));
10516
+ const ss = tlv.encode(2, int.encode(sig.s));
10517
+ const seq = rs + ss;
10518
+ return tlv.encode(48, seq);
10519
+ }
10520
+ };
10521
+ var _0n4 = BigInt(0);
10522
+ var _1n4 = BigInt(1);
10523
+ var _2n2 = BigInt(2);
10524
+ var _3n2 = BigInt(3);
10525
+ var _4n2 = BigInt(4);
10526
+ function weierstrass(params, extraOpts = {}) {
10527
+ const validated = createCurveFields("weierstrass", params, extraOpts);
10528
+ const { Fp, Fn } = validated;
10529
+ let CURVE = validated.CURVE;
10530
+ const { h: cofactor, n: CURVE_ORDER2 } = CURVE;
10531
+ validateObject(extraOpts, {}, {
10532
+ allowInfinityPoint: "boolean",
10533
+ clearCofactor: "function",
10534
+ isTorsionFree: "function",
10535
+ fromBytes: "function",
10536
+ toBytes: "function",
10537
+ endo: "object"
10538
+ });
10539
+ const { endo } = extraOpts;
10540
+ if (endo) {
10541
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
10542
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
10543
+ }
10544
+ }
10545
+ const lengths = getWLengths(Fp, Fn);
10546
+ function assertCompressionIsSupported() {
10547
+ if (!Fp.isOdd)
10548
+ throw new Error("compression is not supported: Field does not have .isOdd()");
10549
+ }
10550
+ function pointToBytes(_c, point, isCompressed) {
10551
+ const { x, y } = point.toAffine();
10552
+ const bx = Fp.toBytes(x);
10553
+ abool(isCompressed, "isCompressed");
10554
+ if (isCompressed) {
10555
+ assertCompressionIsSupported();
10556
+ const hasEvenY = !Fp.isOdd(y);
10557
+ return concatBytes(pprefix(hasEvenY), bx);
10558
+ } else {
10559
+ return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
10560
+ }
10561
+ }
10562
+ function pointFromBytes(bytes) {
10563
+ abytes(bytes, void 0, "Point");
10564
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
10565
+ const length = bytes.length;
10566
+ const head = bytes[0];
10567
+ const tail = bytes.subarray(1);
10568
+ if (length === comp && (head === 2 || head === 3)) {
10569
+ const x = Fp.fromBytes(tail);
10570
+ if (!Fp.isValid(x))
10571
+ throw new Error("bad point: is not on curve, wrong x");
10572
+ const y2 = weierstrassEquation(x);
10573
+ let y;
10574
+ try {
10575
+ y = Fp.sqrt(y2);
10576
+ } catch (sqrtError) {
10577
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
10578
+ throw new Error("bad point: is not on curve, sqrt error" + err);
10579
+ }
10580
+ assertCompressionIsSupported();
10581
+ const evenY = Fp.isOdd(y);
10582
+ const evenH = (head & 1) === 1;
10583
+ if (evenH !== evenY)
10584
+ y = Fp.neg(y);
10585
+ return { x, y };
10586
+ } else if (length === uncomp && head === 4) {
10587
+ const L = Fp.BYTES;
10588
+ const x = Fp.fromBytes(tail.subarray(0, L));
10589
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
10590
+ if (!isValidXY(x, y))
10591
+ throw new Error("bad point: is not on curve");
10592
+ return { x, y };
10593
+ } else {
10594
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
10595
+ }
10596
+ }
10597
+ const encodePoint = extraOpts.toBytes || pointToBytes;
10598
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
10599
+ function weierstrassEquation(x) {
10600
+ const x2 = Fp.sqr(x);
10601
+ const x3 = Fp.mul(x2, x);
10602
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
10603
+ }
10604
+ function isValidXY(x, y) {
10605
+ const left = Fp.sqr(y);
10606
+ const right = weierstrassEquation(x);
10607
+ return Fp.eql(left, right);
10608
+ }
10609
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
10610
+ throw new Error("bad curve params: generator point");
10611
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
10612
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
10613
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
10614
+ throw new Error("bad curve params: a or b");
10615
+ function acoord(title, n, banZero = false) {
10616
+ if (!Fp.isValid(n) || banZero && Fp.is0(n))
10617
+ throw new Error(`bad point coordinate ${title}`);
10618
+ return n;
10619
+ }
10620
+ function aprjpoint(other) {
10621
+ if (!(other instanceof Point))
10622
+ throw new Error("Weierstrass Point expected");
10623
+ }
10624
+ function splitEndoScalarN(k) {
10625
+ if (!endo || !endo.basises)
10626
+ throw new Error("no endo");
10627
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
10628
+ }
10629
+ const toAffineMemo = memoized((p, iz) => {
10630
+ const { X, Y, Z } = p;
10631
+ if (Fp.eql(Z, Fp.ONE))
10632
+ return { x: X, y: Y };
10633
+ const is0 = p.is0();
10634
+ if (iz == null)
10635
+ iz = is0 ? Fp.ONE : Fp.inv(Z);
10636
+ const x = Fp.mul(X, iz);
10637
+ const y = Fp.mul(Y, iz);
10638
+ const zz = Fp.mul(Z, iz);
10639
+ if (is0)
10640
+ return { x: Fp.ZERO, y: Fp.ZERO };
10641
+ if (!Fp.eql(zz, Fp.ONE))
10642
+ throw new Error("invZ was invalid");
10643
+ return { x, y };
10644
+ });
10645
+ const assertValidMemo = memoized((p) => {
10646
+ if (p.is0()) {
10647
+ if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
10648
+ return;
10649
+ throw new Error("bad point: ZERO");
10650
+ }
10651
+ const { x, y } = p.toAffine();
10652
+ if (!Fp.isValid(x) || !Fp.isValid(y))
10653
+ throw new Error("bad point: x or y not field elements");
10654
+ if (!isValidXY(x, y))
10655
+ throw new Error("bad point: equation left != right");
10656
+ if (!p.isTorsionFree())
10657
+ throw new Error("bad point: not in prime-order subgroup");
10658
+ return true;
10659
+ });
10660
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
10661
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
10662
+ k1p = negateCt(k1neg, k1p);
10663
+ k2p = negateCt(k2neg, k2p);
10664
+ return k1p.add(k2p);
10665
+ }
10666
+ class Point {
10667
+ // base / generator point
10668
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
10669
+ // zero / infinity / identity point
10670
+ static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
10671
+ // 0, 1, 0
10672
+ // math field
10673
+ static Fp = Fp;
10674
+ // scalar field
10675
+ static Fn = Fn;
10676
+ X;
10677
+ Y;
10678
+ Z;
10679
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
10680
+ constructor(X, Y, Z) {
10681
+ this.X = acoord("x", X);
10682
+ this.Y = acoord("y", Y, true);
10683
+ this.Z = acoord("z", Z);
10684
+ Object.freeze(this);
10685
+ }
10686
+ static CURVE() {
10687
+ return CURVE;
10688
+ }
10689
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
10690
+ static fromAffine(p) {
10691
+ const { x, y } = p || {};
10692
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
10693
+ throw new Error("invalid affine point");
10694
+ if (p instanceof Point)
10695
+ throw new Error("projective point not allowed");
10696
+ if (Fp.is0(x) && Fp.is0(y))
10697
+ return Point.ZERO;
10698
+ return new Point(x, y, Fp.ONE);
10699
+ }
10700
+ static fromBytes(bytes) {
10701
+ const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
10702
+ P.assertValidity();
10703
+ return P;
10704
+ }
10705
+ static fromHex(hex) {
10706
+ return Point.fromBytes(hexToBytes2(hex));
10707
+ }
10708
+ get x() {
10709
+ return this.toAffine().x;
10710
+ }
10711
+ get y() {
10712
+ return this.toAffine().y;
10713
+ }
10714
+ /**
10715
+ *
10716
+ * @param windowSize
10717
+ * @param isLazy true will defer table computation until the first multiplication
10718
+ * @returns
10719
+ */
10720
+ precompute(windowSize = 8, isLazy = true) {
10721
+ wnaf.createCache(this, windowSize);
10722
+ if (!isLazy)
10723
+ this.multiply(_3n2);
10724
+ return this;
10725
+ }
10726
+ // TODO: return `this`
10727
+ /** A point on curve is valid if it conforms to equation. */
10728
+ assertValidity() {
10729
+ assertValidMemo(this);
10730
+ }
10731
+ hasEvenY() {
10732
+ const { y } = this.toAffine();
10733
+ if (!Fp.isOdd)
10734
+ throw new Error("Field doesn't support isOdd");
10735
+ return !Fp.isOdd(y);
10736
+ }
10737
+ /** Compare one point to another. */
10738
+ equals(other) {
10739
+ aprjpoint(other);
10740
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10741
+ const { X: X2, Y: Y2, Z: Z2 } = other;
10742
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
10743
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
10744
+ return U1 && U2;
10745
+ }
10746
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
10747
+ negate() {
10748
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
10749
+ }
10750
+ // Renes-Costello-Batina exception-free doubling formula.
10751
+ // There is 30% faster Jacobian formula, but it is not complete.
10752
+ // https://eprint.iacr.org/2015/1060, algorithm 3
10753
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
10754
+ double() {
10755
+ const { a, b } = CURVE;
10756
+ const b3 = Fp.mul(b, _3n2);
10757
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10758
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
10759
+ let t0 = Fp.mul(X1, X1);
10760
+ let t1 = Fp.mul(Y1, Y1);
10761
+ let t2 = Fp.mul(Z1, Z1);
10762
+ let t3 = Fp.mul(X1, Y1);
10763
+ t3 = Fp.add(t3, t3);
10764
+ Z3 = Fp.mul(X1, Z1);
10765
+ Z3 = Fp.add(Z3, Z3);
10766
+ X3 = Fp.mul(a, Z3);
10767
+ Y3 = Fp.mul(b3, t2);
10768
+ Y3 = Fp.add(X3, Y3);
10769
+ X3 = Fp.sub(t1, Y3);
10770
+ Y3 = Fp.add(t1, Y3);
10771
+ Y3 = Fp.mul(X3, Y3);
10772
+ X3 = Fp.mul(t3, X3);
10773
+ Z3 = Fp.mul(b3, Z3);
10774
+ t2 = Fp.mul(a, t2);
10775
+ t3 = Fp.sub(t0, t2);
10776
+ t3 = Fp.mul(a, t3);
10777
+ t3 = Fp.add(t3, Z3);
10778
+ Z3 = Fp.add(t0, t0);
10779
+ t0 = Fp.add(Z3, t0);
10780
+ t0 = Fp.add(t0, t2);
10781
+ t0 = Fp.mul(t0, t3);
10782
+ Y3 = Fp.add(Y3, t0);
10783
+ t2 = Fp.mul(Y1, Z1);
10784
+ t2 = Fp.add(t2, t2);
10785
+ t0 = Fp.mul(t2, t3);
10786
+ X3 = Fp.sub(X3, t0);
10787
+ Z3 = Fp.mul(t2, t1);
10788
+ Z3 = Fp.add(Z3, Z3);
10789
+ Z3 = Fp.add(Z3, Z3);
10790
+ return new Point(X3, Y3, Z3);
10791
+ }
10792
+ // Renes-Costello-Batina exception-free addition formula.
10793
+ // There is 30% faster Jacobian formula, but it is not complete.
10794
+ // https://eprint.iacr.org/2015/1060, algorithm 1
10795
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
10796
+ add(other) {
10797
+ aprjpoint(other);
10798
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10799
+ const { X: X2, Y: Y2, Z: Z2 } = other;
10800
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
10801
+ const a = CURVE.a;
10802
+ const b3 = Fp.mul(CURVE.b, _3n2);
10803
+ let t0 = Fp.mul(X1, X2);
10804
+ let t1 = Fp.mul(Y1, Y2);
10805
+ let t2 = Fp.mul(Z1, Z2);
10806
+ let t3 = Fp.add(X1, Y1);
10807
+ let t4 = Fp.add(X2, Y2);
10808
+ t3 = Fp.mul(t3, t4);
10809
+ t4 = Fp.add(t0, t1);
10810
+ t3 = Fp.sub(t3, t4);
10811
+ t4 = Fp.add(X1, Z1);
10812
+ let t5 = Fp.add(X2, Z2);
10813
+ t4 = Fp.mul(t4, t5);
10814
+ t5 = Fp.add(t0, t2);
10815
+ t4 = Fp.sub(t4, t5);
10816
+ t5 = Fp.add(Y1, Z1);
10817
+ X3 = Fp.add(Y2, Z2);
10818
+ t5 = Fp.mul(t5, X3);
10819
+ X3 = Fp.add(t1, t2);
10820
+ t5 = Fp.sub(t5, X3);
10821
+ Z3 = Fp.mul(a, t4);
10822
+ X3 = Fp.mul(b3, t2);
10823
+ Z3 = Fp.add(X3, Z3);
10824
+ X3 = Fp.sub(t1, Z3);
10825
+ Z3 = Fp.add(t1, Z3);
10826
+ Y3 = Fp.mul(X3, Z3);
10827
+ t1 = Fp.add(t0, t0);
10828
+ t1 = Fp.add(t1, t0);
10829
+ t2 = Fp.mul(a, t2);
10830
+ t4 = Fp.mul(b3, t4);
10831
+ t1 = Fp.add(t1, t2);
10832
+ t2 = Fp.sub(t0, t2);
10833
+ t2 = Fp.mul(a, t2);
10834
+ t4 = Fp.add(t4, t2);
10835
+ t0 = Fp.mul(t1, t4);
10836
+ Y3 = Fp.add(Y3, t0);
10837
+ t0 = Fp.mul(t5, t4);
10838
+ X3 = Fp.mul(t3, X3);
10839
+ X3 = Fp.sub(X3, t0);
10840
+ t0 = Fp.mul(t3, t1);
10841
+ Z3 = Fp.mul(t5, Z3);
10842
+ Z3 = Fp.add(Z3, t0);
10843
+ return new Point(X3, Y3, Z3);
10844
+ }
10845
+ subtract(other) {
10846
+ return this.add(other.negate());
10847
+ }
10848
+ is0() {
10849
+ return this.equals(Point.ZERO);
10850
+ }
10851
+ /**
10852
+ * Constant time multiplication.
10853
+ * Uses wNAF method. Windowed method may be 10% faster,
10854
+ * but takes 2x longer to generate and consumes 2x memory.
10855
+ * Uses precomputes when available.
10856
+ * Uses endomorphism for Koblitz curves.
10857
+ * @param scalar by which the point would be multiplied
10858
+ * @returns New point
10859
+ */
10860
+ multiply(scalar) {
10861
+ const { endo: endo2 } = extraOpts;
10862
+ if (!Fn.isValidNot0(scalar))
10863
+ throw new Error("invalid scalar: out of range");
10864
+ let point, fake;
10865
+ const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
10866
+ if (endo2) {
10867
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
10868
+ const { p: k1p, f: k1f } = mul(k1);
10869
+ const { p: k2p, f: k2f } = mul(k2);
10870
+ fake = k1f.add(k2f);
10871
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
10872
+ } else {
10873
+ const { p, f } = mul(scalar);
10874
+ point = p;
10875
+ fake = f;
10876
+ }
10877
+ return normalizeZ(Point, [point, fake])[0];
10878
+ }
10879
+ /**
10880
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
10881
+ * It's faster, but should only be used when you don't care about
10882
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
10883
+ */
10884
+ multiplyUnsafe(sc) {
10885
+ const { endo: endo2 } = extraOpts;
10886
+ const p = this;
10887
+ if (!Fn.isValid(sc))
10888
+ throw new Error("invalid scalar: out of range");
10889
+ if (sc === _0n4 || p.is0())
10890
+ return Point.ZERO;
10891
+ if (sc === _1n4)
10892
+ return p;
10893
+ if (wnaf.hasCache(this))
10894
+ return this.multiply(sc);
10895
+ if (endo2) {
10896
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
10897
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
10898
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
10899
+ } else {
10900
+ return wnaf.unsafe(p, sc);
10901
+ }
10902
+ }
10903
+ /**
10904
+ * Converts Projective point to affine (x, y) coordinates.
10905
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
10906
+ */
10907
+ toAffine(invertedZ) {
10908
+ return toAffineMemo(this, invertedZ);
10909
+ }
10910
+ /**
10911
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
10912
+ * Always torsion-free for cofactor=1 curves.
10913
+ */
10914
+ isTorsionFree() {
10915
+ const { isTorsionFree } = extraOpts;
10916
+ if (cofactor === _1n4)
10917
+ return true;
10918
+ if (isTorsionFree)
10919
+ return isTorsionFree(Point, this);
10920
+ return wnaf.unsafe(this, CURVE_ORDER2).is0();
10921
+ }
10922
+ clearCofactor() {
10923
+ const { clearCofactor } = extraOpts;
10924
+ if (cofactor === _1n4)
10925
+ return this;
10926
+ if (clearCofactor)
10927
+ return clearCofactor(Point, this);
10928
+ return this.multiplyUnsafe(cofactor);
10929
+ }
10930
+ isSmallOrder() {
10931
+ return this.multiplyUnsafe(cofactor).is0();
10932
+ }
10933
+ toBytes(isCompressed = true) {
10934
+ abool(isCompressed, "isCompressed");
10935
+ this.assertValidity();
10936
+ return encodePoint(Point, this, isCompressed);
10937
+ }
10938
+ toHex(isCompressed = true) {
10939
+ return bytesToHex4(this.toBytes(isCompressed));
10940
+ }
10941
+ toString() {
10942
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
10943
+ }
10944
+ }
10945
+ const bits = Fn.BITS;
10946
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
10947
+ Point.BASE.precompute(8);
10948
+ return Point;
10949
+ }
10950
+ function pprefix(hasEvenY) {
10951
+ return Uint8Array.of(hasEvenY ? 2 : 3);
10952
+ }
10953
+ function getWLengths(Fp, Fn) {
10954
+ return {
10955
+ secretKey: Fn.BYTES,
10956
+ publicKey: 1 + Fp.BYTES,
10957
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
10958
+ publicKeyHasPrefix: true,
10959
+ signature: 2 * Fn.BYTES
10960
+ };
10961
+ }
10962
+ function ecdh(Point, ecdhOpts = {}) {
10963
+ const { Fn } = Point;
10964
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
10965
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
10966
+ function isValidSecretKey(secretKey) {
10967
+ try {
10968
+ const num = Fn.fromBytes(secretKey);
10969
+ return Fn.isValidNot0(num);
10970
+ } catch (error) {
10971
+ return false;
10972
+ }
10973
+ }
10974
+ function isValidPublicKey(publicKey, isCompressed) {
10975
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
10976
+ try {
10977
+ const l = publicKey.length;
10978
+ if (isCompressed === true && l !== comp)
10979
+ return false;
10980
+ if (isCompressed === false && l !== publicKeyUncompressed)
10981
+ return false;
10982
+ return !!Point.fromBytes(publicKey);
10983
+ } catch (error) {
10984
+ return false;
10985
+ }
10986
+ }
10987
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
10988
+ return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
10989
+ }
10990
+ function getPublicKey2(secretKey, isCompressed = true) {
10991
+ return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
10992
+ }
10993
+ function isProbPub(item) {
10994
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
10995
+ if (!isBytes(item))
10996
+ return void 0;
10997
+ if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
10998
+ return void 0;
10999
+ const l = abytes(item, void 0, "key").length;
11000
+ return l === publicKey || l === publicKeyUncompressed;
11001
+ }
11002
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
11003
+ if (isProbPub(secretKeyA) === true)
11004
+ throw new Error("first arg must be private key");
11005
+ if (isProbPub(publicKeyB) === false)
11006
+ throw new Error("second arg must be public key");
11007
+ const s = Fn.fromBytes(secretKeyA);
11008
+ const b = Point.fromBytes(publicKeyB);
11009
+ return b.multiply(s).toBytes(isCompressed);
11010
+ }
11011
+ const utils = {
11012
+ isValidSecretKey,
11013
+ isValidPublicKey,
11014
+ randomSecretKey
11015
+ };
11016
+ const keygen = createKeygen(randomSecretKey, getPublicKey2);
11017
+ return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
11018
+ }
11019
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
11020
+ ahash(hash);
11021
+ validateObject(ecdsaOpts, {}, {
11022
+ hmac: "function",
11023
+ lowS: "boolean",
11024
+ randomBytes: "function",
11025
+ bits2int: "function",
11026
+ bits2int_modN: "function"
11027
+ });
11028
+ ecdsaOpts = Object.assign({}, ecdsaOpts);
11029
+ const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
11030
+ const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
11031
+ const { Fp, Fn } = Point;
11032
+ const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn;
11033
+ const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
11034
+ const defaultSigOpts = {
11035
+ prehash: true,
11036
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
11037
+ format: "compact",
11038
+ extraEntropy: false
11039
+ };
11040
+ const hasLargeCofactor = CURVE_ORDER2 * _2n2 < Fp.ORDER;
11041
+ function isBiggerThanHalfOrder(number) {
11042
+ const HALF = CURVE_ORDER2 >> _1n4;
11043
+ return number > HALF;
11044
+ }
11045
+ function validateRS(title, num) {
11046
+ if (!Fn.isValidNot0(num))
11047
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
11048
+ return num;
11049
+ }
11050
+ function assertSmallCofactor() {
11051
+ if (hasLargeCofactor)
11052
+ throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
11053
+ }
11054
+ function validateSigLength(bytes, format) {
11055
+ validateSigFormat(format);
11056
+ const size = lengths.signature;
11057
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
11058
+ return abytes(bytes, sizer);
11059
+ }
11060
+ class Signature {
11061
+ r;
11062
+ s;
11063
+ recovery;
11064
+ constructor(r, s, recovery) {
11065
+ this.r = validateRS("r", r);
11066
+ this.s = validateRS("s", s);
11067
+ if (recovery != null) {
11068
+ assertSmallCofactor();
11069
+ if (![0, 1, 2, 3].includes(recovery))
11070
+ throw new Error("invalid recovery id");
11071
+ this.recovery = recovery;
11072
+ }
11073
+ Object.freeze(this);
11074
+ }
11075
+ static fromBytes(bytes, format = defaultSigOpts.format) {
11076
+ validateSigLength(bytes, format);
11077
+ let recid;
11078
+ if (format === "der") {
11079
+ const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
11080
+ return new Signature(r2, s2);
11081
+ }
11082
+ if (format === "recovered") {
11083
+ recid = bytes[0];
11084
+ format = "compact";
11085
+ bytes = bytes.subarray(1);
11086
+ }
11087
+ const L = lengths.signature / 2;
11088
+ const r = bytes.subarray(0, L);
11089
+ const s = bytes.subarray(L, L * 2);
11090
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
11091
+ }
11092
+ static fromHex(hex, format) {
11093
+ return this.fromBytes(hexToBytes2(hex), format);
11094
+ }
11095
+ assertRecovery() {
11096
+ const { recovery } = this;
11097
+ if (recovery == null)
11098
+ throw new Error("invalid recovery id: must be present");
11099
+ return recovery;
11100
+ }
11101
+ addRecoveryBit(recovery) {
11102
+ return new Signature(this.r, this.s, recovery);
11103
+ }
11104
+ recoverPublicKey(messageHash) {
11105
+ const { r, s } = this;
11106
+ const recovery = this.assertRecovery();
11107
+ const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER2 : r;
11108
+ if (!Fp.isValid(radj))
11109
+ throw new Error("invalid recovery id: sig.r+curve.n != R.x");
11110
+ const x = Fp.toBytes(radj);
11111
+ const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
11112
+ const ir = Fn.inv(radj);
11113
+ const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
11114
+ const u1 = Fn.create(-h * ir);
11115
+ const u2 = Fn.create(s * ir);
11116
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
11117
+ if (Q.is0())
11118
+ throw new Error("invalid recovery: point at infinify");
11119
+ Q.assertValidity();
11120
+ return Q;
11121
+ }
11122
+ // Signatures should be low-s, to prevent malleability.
11123
+ hasHighS() {
11124
+ return isBiggerThanHalfOrder(this.s);
11125
+ }
11126
+ toBytes(format = defaultSigOpts.format) {
11127
+ validateSigFormat(format);
11128
+ if (format === "der")
11129
+ return hexToBytes2(DER.hexFromSig(this));
11130
+ const { r, s } = this;
11131
+ const rb = Fn.toBytes(r);
11132
+ const sb = Fn.toBytes(s);
11133
+ if (format === "recovered") {
11134
+ assertSmallCofactor();
11135
+ return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
11136
+ }
11137
+ return concatBytes(rb, sb);
11138
+ }
11139
+ toHex(format) {
11140
+ return bytesToHex4(this.toBytes(format));
11141
+ }
11142
+ }
11143
+ const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
11144
+ if (bytes.length > 8192)
11145
+ throw new Error("input is too large");
11146
+ const num = bytesToNumberBE(bytes);
11147
+ const delta = bytes.length * 8 - fnBits;
11148
+ return delta > 0 ? num >> BigInt(delta) : num;
11149
+ };
11150
+ const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
11151
+ return Fn.create(bits2int(bytes));
11152
+ };
11153
+ const ORDER_MASK = bitMask(fnBits);
11154
+ function int2octets(num) {
11155
+ aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
11156
+ return Fn.toBytes(num);
11157
+ }
11158
+ function validateMsgAndHash(message, prehash) {
11159
+ abytes(message, void 0, "message");
11160
+ return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
11161
+ }
11162
+ function prepSig(message, secretKey, opts) {
11163
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
11164
+ message = validateMsgAndHash(message, prehash);
11165
+ const h1int = bits2int_modN(message);
11166
+ const d = Fn.fromBytes(secretKey);
11167
+ if (!Fn.isValidNot0(d))
11168
+ throw new Error("invalid private key");
11169
+ const seedArgs = [int2octets(d), int2octets(h1int)];
11170
+ if (extraEntropy != null && extraEntropy !== false) {
11171
+ const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
11172
+ seedArgs.push(abytes(e, void 0, "extraEntropy"));
11173
+ }
11174
+ const seed = concatBytes(...seedArgs);
11175
+ const m = h1int;
11176
+ function k2sig(kBytes) {
11177
+ const k = bits2int(kBytes);
11178
+ if (!Fn.isValidNot0(k))
11179
+ return;
11180
+ const ik = Fn.inv(k);
11181
+ const q = Point.BASE.multiply(k).toAffine();
11182
+ const r = Fn.create(q.x);
11183
+ if (r === _0n4)
11184
+ return;
11185
+ const s = Fn.create(ik * Fn.create(m + r * d));
11186
+ if (s === _0n4)
11187
+ return;
11188
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
11189
+ let normS = s;
11190
+ if (lowS && isBiggerThanHalfOrder(s)) {
11191
+ normS = Fn.neg(s);
11192
+ recovery ^= 1;
11193
+ }
11194
+ return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
11195
+ }
11196
+ return { seed, k2sig };
11197
+ }
11198
+ function sign(message, secretKey, opts = {}) {
11199
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
11200
+ const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
11201
+ const sig = drbg(seed, k2sig);
11202
+ return sig.toBytes(opts.format);
11203
+ }
11204
+ function verify(signature, message, publicKey, opts = {}) {
11205
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
11206
+ publicKey = abytes(publicKey, void 0, "publicKey");
11207
+ message = validateMsgAndHash(message, prehash);
11208
+ if (!isBytes(signature)) {
11209
+ const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
11210
+ throw new Error("verify expects Uint8Array signature" + end);
11211
+ }
11212
+ validateSigLength(signature, format);
11213
+ try {
11214
+ const sig = Signature.fromBytes(signature, format);
11215
+ const P = Point.fromBytes(publicKey);
11216
+ if (lowS && sig.hasHighS())
11217
+ return false;
11218
+ const { r, s } = sig;
11219
+ const h = bits2int_modN(message);
11220
+ const is = Fn.inv(s);
11221
+ const u1 = Fn.create(h * is);
11222
+ const u2 = Fn.create(r * is);
11223
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
11224
+ if (R.is0())
11225
+ return false;
11226
+ const v = Fn.create(R.x);
11227
+ return v === r;
11228
+ } catch (e) {
11229
+ return false;
11230
+ }
11231
+ }
11232
+ function recoverPublicKey(signature, message, opts = {}) {
11233
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
11234
+ message = validateMsgAndHash(message, prehash);
11235
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
11236
+ }
11237
+ return Object.freeze({
11238
+ keygen,
11239
+ getPublicKey: getPublicKey2,
11240
+ getSharedSecret,
11241
+ utils,
11242
+ lengths,
11243
+ Point,
11244
+ sign,
11245
+ verify,
11246
+ recoverPublicKey,
11247
+ Signature,
11248
+ hash
11249
+ });
11250
+ }
11251
+
11252
+ // node_modules/@noble/curves/secp256k1.js
11253
+ var secp256k1_CURVE = {
11254
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
11255
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
11256
+ h: BigInt(1),
11257
+ a: BigInt(0),
11258
+ b: BigInt(7),
11259
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
11260
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
11261
+ };
11262
+ var secp256k1_ENDO = {
11263
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
11264
+ basises: [
11265
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
11266
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
11267
+ ]
11268
+ };
11269
+ var _2n3 = /* @__PURE__ */ BigInt(2);
11270
+ function sqrtMod(y) {
11271
+ const P = secp256k1_CURVE.p;
11272
+ const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
11273
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
11274
+ const b2 = y * y * y % P;
11275
+ const b3 = b2 * b2 * y % P;
11276
+ const b6 = pow2(b3, _3n3, P) * b3 % P;
11277
+ const b9 = pow2(b6, _3n3, P) * b3 % P;
11278
+ const b11 = pow2(b9, _2n3, P) * b2 % P;
11279
+ const b22 = pow2(b11, _11n, P) * b11 % P;
11280
+ const b44 = pow2(b22, _22n, P) * b22 % P;
11281
+ const b88 = pow2(b44, _44n, P) * b44 % P;
11282
+ const b176 = pow2(b88, _88n, P) * b88 % P;
11283
+ const b220 = pow2(b176, _44n, P) * b44 % P;
11284
+ const b223 = pow2(b220, _3n3, P) * b3 % P;
11285
+ const t1 = pow2(b223, _23n, P) * b22 % P;
11286
+ const t2 = pow2(t1, _6n, P) * b2 % P;
11287
+ const root = pow2(t2, _2n3, P);
11288
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
11289
+ throw new Error("Cannot find square root");
11290
+ return root;
11291
+ }
11292
+ var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
11293
+ var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
11294
+ Fp: Fpk1,
11295
+ endo: secp256k1_ENDO
11296
+ });
11297
+ var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha2564);
11298
+
11299
+ // modules/market/MarketModule.ts
11300
+ var DEFAULT_MARKET_API_URL = "https://market-api.unicity.network";
11301
+ function hexToBytes3(hex) {
11302
+ const len = hex.length >> 1;
11303
+ const bytes = new Uint8Array(len);
11304
+ for (let i = 0; i < len; i++) {
11305
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
11306
+ }
11307
+ return bytes;
11308
+ }
11309
+ function signRequest(body, privateKeyHex) {
11310
+ const timestamp = Date.now();
11311
+ const payload = JSON.stringify({ body, timestamp });
11312
+ const messageHash = sha2564(new TextEncoder().encode(payload));
11313
+ const privateKeyBytes = hexToBytes3(privateKeyHex);
11314
+ const signature = secp256k1.sign(messageHash, privateKeyBytes);
11315
+ const publicKey = bytesToHex4(secp256k1.getPublicKey(privateKeyBytes, true));
11316
+ return {
11317
+ body: JSON.stringify(body),
11318
+ headers: {
11319
+ "x-signature": bytesToHex4(signature),
11320
+ "x-public-key": publicKey,
11321
+ "x-timestamp": String(timestamp),
11322
+ "content-type": "application/json"
11323
+ }
11324
+ };
11325
+ }
11326
+ function toSnakeCaseIntent(req) {
11327
+ const result = {
11328
+ description: req.description,
11329
+ intent_type: req.intentType
11330
+ };
11331
+ if (req.category !== void 0) result.category = req.category;
11332
+ if (req.price !== void 0) result.price = req.price;
11333
+ if (req.currency !== void 0) result.currency = req.currency;
11334
+ if (req.location !== void 0) result.location = req.location;
11335
+ if (req.contactHandle !== void 0) result.contact_handle = req.contactHandle;
11336
+ if (req.expiresInDays !== void 0) result.expires_in_days = req.expiresInDays;
11337
+ return result;
11338
+ }
11339
+ function toSnakeCaseFilters(opts) {
11340
+ const result = {};
11341
+ if (opts?.filters) {
11342
+ const f = opts.filters;
11343
+ if (f.intentType !== void 0) result.intent_type = f.intentType;
11344
+ if (f.category !== void 0) result.category = f.category;
11345
+ if (f.minPrice !== void 0) result.min_price = f.minPrice;
11346
+ if (f.maxPrice !== void 0) result.max_price = f.maxPrice;
11347
+ if (f.location !== void 0) result.location = f.location;
11348
+ }
11349
+ if (opts?.limit !== void 0) result.limit = opts.limit;
11350
+ return result;
11351
+ }
11352
+ function mapSearchResult(raw) {
11353
+ return {
11354
+ id: raw.id,
11355
+ score: raw.score,
11356
+ agentNametag: raw.agent_nametag ?? void 0,
11357
+ agentPublicKey: raw.agent_public_key,
11358
+ description: raw.description,
11359
+ intentType: raw.intent_type,
11360
+ category: raw.category ?? void 0,
11361
+ price: raw.price ?? void 0,
11362
+ currency: raw.currency,
11363
+ location: raw.location ?? void 0,
11364
+ contactMethod: raw.contact_method,
11365
+ contactHandle: raw.contact_handle ?? void 0,
11366
+ createdAt: raw.created_at,
11367
+ expiresAt: raw.expires_at
11368
+ };
11369
+ }
11370
+ function mapMyIntent(raw) {
11371
+ return {
11372
+ id: raw.id,
11373
+ intentType: raw.intent_type,
11374
+ category: raw.category ?? void 0,
11375
+ price: raw.price ?? void 0,
11376
+ currency: raw.currency,
11377
+ location: raw.location ?? void 0,
11378
+ status: raw.status,
11379
+ createdAt: raw.created_at,
11380
+ expiresAt: raw.expires_at
11381
+ };
11382
+ }
11383
+ function mapFeedListing(raw) {
11384
+ return {
11385
+ id: raw.id,
11386
+ title: raw.title,
11387
+ descriptionPreview: raw.description_preview,
11388
+ agentName: raw.agent_name,
11389
+ agentId: raw.agent_id,
11390
+ type: raw.type,
11391
+ createdAt: raw.created_at
11392
+ };
11393
+ }
11394
+ function mapFeedMessage(raw) {
11395
+ if (raw.type === "initial") {
11396
+ return { type: "initial", listings: (raw.listings ?? []).map(mapFeedListing) };
11397
+ }
11398
+ return { type: "new", listing: mapFeedListing(raw.listing) };
11399
+ }
11400
+ var MarketModule = class {
11401
+ apiUrl;
11402
+ timeout;
11403
+ identity = null;
11404
+ registered = false;
11405
+ constructor(config) {
11406
+ this.apiUrl = (config?.apiUrl ?? DEFAULT_MARKET_API_URL).replace(/\/+$/, "");
11407
+ this.timeout = config?.timeout ?? 3e4;
11408
+ }
11409
+ /** Called by Sphere after construction */
11410
+ initialize(deps) {
11411
+ this.identity = deps.identity;
11412
+ }
11413
+ /** No-op — stateless module */
11414
+ async load() {
11415
+ }
11416
+ /** No-op — stateless module */
11417
+ destroy() {
11418
+ }
11419
+ // ---------------------------------------------------------------------------
11420
+ // Public API
11421
+ // ---------------------------------------------------------------------------
11422
+ /** Post a new intent (agent is auto-registered on first post) */
11423
+ async postIntent(intent) {
11424
+ const body = toSnakeCaseIntent(intent);
11425
+ const data = await this.apiPost("/api/intents", body);
11426
+ return {
11427
+ intentId: data.intent_id ?? data.intentId,
11428
+ message: data.message,
11429
+ expiresAt: data.expires_at ?? data.expiresAt
11430
+ };
11431
+ }
11432
+ /** Semantic search for intents (public — no auth required) */
11433
+ async search(query, opts) {
11434
+ const body = {
11435
+ query,
11436
+ ...toSnakeCaseFilters(opts)
11437
+ };
11438
+ const data = await this.apiPublicPost("/api/search", body);
11439
+ let results = (data.intents ?? []).map(mapSearchResult);
11440
+ const minScore = opts?.filters?.minScore;
11441
+ if (minScore != null) {
11442
+ results = results.filter((r) => Math.round(r.score * 100) >= Math.round(minScore * 100));
11443
+ }
11444
+ return { intents: results, count: results.length };
11445
+ }
11446
+ /** List own intents (authenticated) */
11447
+ async getMyIntents() {
11448
+ const data = await this.apiGet("/api/intents");
11449
+ return (data.intents ?? []).map(mapMyIntent);
11450
+ }
11451
+ /** Close (delete) an intent */
11452
+ async closeIntent(intentId) {
11453
+ await this.apiDelete(`/api/intents/${encodeURIComponent(intentId)}`);
11454
+ }
11455
+ /** Fetch the most recent listings via REST (public — no auth required) */
11456
+ async getRecentListings() {
11457
+ const res = await fetch(`${this.apiUrl}/api/feed/recent`, {
11458
+ signal: AbortSignal.timeout(this.timeout)
11459
+ });
11460
+ const data = await this.parseResponse(res);
11461
+ return (data.listings ?? []).map(mapFeedListing);
11462
+ }
11463
+ /**
11464
+ * Subscribe to the live listing feed via WebSocket.
11465
+ * Returns an unsubscribe function that closes the connection.
11466
+ *
11467
+ * Requires a WebSocket implementation — works natively in browsers
11468
+ * and in Node.js 21+ (or with the `ws` package).
11469
+ */
11470
+ subscribeFeed(listener) {
11471
+ const wsUrl = this.apiUrl.replace(/^http/, "ws") + "/ws/feed";
11472
+ const ws2 = new WebSocket(wsUrl);
11473
+ ws2.onmessage = (event) => {
11474
+ try {
11475
+ const raw = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
11476
+ listener(mapFeedMessage(raw));
11477
+ } catch {
11478
+ }
11479
+ };
11480
+ return () => {
11481
+ ws2.close();
11482
+ };
11483
+ }
11484
+ // ---------------------------------------------------------------------------
11485
+ // Private: HTTP helpers
11486
+ // ---------------------------------------------------------------------------
11487
+ ensureIdentity() {
11488
+ if (!this.identity) {
11489
+ throw new Error("MarketModule not initialized \u2014 call initialize() first");
11490
+ }
11491
+ }
11492
+ /** Register the agent's public key with the server (idempotent) */
11493
+ async ensureRegistered() {
11494
+ if (this.registered) return;
11495
+ this.ensureIdentity();
11496
+ const publicKey = bytesToHex4(secp256k1.getPublicKey(hexToBytes3(this.identity.privateKey), true));
11497
+ const body = { public_key: publicKey };
11498
+ if (this.identity.nametag) body.nametag = this.identity.nametag;
11499
+ const res = await fetch(`${this.apiUrl}/api/agent/register`, {
11500
+ method: "POST",
11501
+ headers: { "content-type": "application/json" },
11502
+ body: JSON.stringify(body),
11503
+ signal: AbortSignal.timeout(this.timeout)
11504
+ });
11505
+ if (res.ok || res.status === 409) {
11506
+ this.registered = true;
11507
+ return;
11508
+ }
11509
+ const text = await res.text();
11510
+ let data;
11511
+ try {
11512
+ data = JSON.parse(text);
11513
+ } catch {
11514
+ }
11515
+ throw new Error(data?.error ?? `Agent registration failed: HTTP ${res.status}`);
11516
+ }
11517
+ async parseResponse(res) {
11518
+ const text = await res.text();
11519
+ let data;
11520
+ try {
11521
+ data = JSON.parse(text);
11522
+ } catch {
11523
+ throw new Error(`Market API error: HTTP ${res.status} \u2014 unexpected response (not JSON)`);
11524
+ }
11525
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
11526
+ return data;
11527
+ }
11528
+ async apiPost(path, body) {
11529
+ this.ensureIdentity();
11530
+ await this.ensureRegistered();
11531
+ const signed = signRequest(body, this.identity.privateKey);
11532
+ const res = await fetch(`${this.apiUrl}${path}`, {
11533
+ method: "POST",
11534
+ headers: signed.headers,
11535
+ body: signed.body,
11536
+ signal: AbortSignal.timeout(this.timeout)
11537
+ });
11538
+ return this.parseResponse(res);
11539
+ }
11540
+ async apiGet(path) {
11541
+ this.ensureIdentity();
11542
+ await this.ensureRegistered();
11543
+ const signed = signRequest({}, this.identity.privateKey);
11544
+ const res = await fetch(`${this.apiUrl}${path}`, {
11545
+ method: "GET",
11546
+ headers: signed.headers,
11547
+ signal: AbortSignal.timeout(this.timeout)
11548
+ });
11549
+ return this.parseResponse(res);
11550
+ }
11551
+ async apiDelete(path) {
11552
+ this.ensureIdentity();
11553
+ await this.ensureRegistered();
11554
+ const signed = signRequest({}, this.identity.privateKey);
11555
+ const res = await fetch(`${this.apiUrl}${path}`, {
11556
+ method: "DELETE",
11557
+ headers: signed.headers,
11558
+ signal: AbortSignal.timeout(this.timeout)
11559
+ });
11560
+ return this.parseResponse(res);
11561
+ }
11562
+ async apiPublicPost(path, body) {
11563
+ const res = await fetch(`${this.apiUrl}${path}`, {
11564
+ method: "POST",
11565
+ headers: { "content-type": "application/json" },
11566
+ body: JSON.stringify(body),
11567
+ signal: AbortSignal.timeout(this.timeout)
11568
+ });
11569
+ return this.parseResponse(res);
11570
+ }
11571
+ };
11572
+ function createMarketModule(config) {
11573
+ return new MarketModule(config);
11574
+ }
11575
+
8999
11576
  // core/encryption.ts
9000
11577
  import CryptoJS6 from "crypto-js";
9001
11578
  var DEFAULT_ITERATIONS = 1e5;
@@ -9916,6 +12493,7 @@ var Sphere = class _Sphere {
9916
12493
  _payments;
9917
12494
  _communications;
9918
12495
  _groupChat = null;
12496
+ _market = null;
9919
12497
  // Events
9920
12498
  eventHandlers = /* @__PURE__ */ new Map();
9921
12499
  // Provider management
@@ -9925,7 +12503,7 @@ var Sphere = class _Sphere {
9925
12503
  // ===========================================================================
9926
12504
  // Constructor (private)
9927
12505
  // ===========================================================================
9928
- constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig) {
12506
+ constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig, marketConfig) {
9929
12507
  this._storage = storage;
9930
12508
  this._transport = transport;
9931
12509
  this._oracle = oracle;
@@ -9936,6 +12514,7 @@ var Sphere = class _Sphere {
9936
12514
  this._payments = createPaymentsModule({ l1: l1Config });
9937
12515
  this._communications = createCommunicationsModule();
9938
12516
  this._groupChat = groupChatConfig ? createGroupChatModule(groupChatConfig) : null;
12517
+ this._market = marketConfig ? createMarketModule(marketConfig) : null;
9939
12518
  }
9940
12519
  // ===========================================================================
9941
12520
  // Static Methods - Wallet Management
@@ -9945,13 +12524,17 @@ var Sphere = class _Sphere {
9945
12524
  */
9946
12525
  static async exists(storage) {
9947
12526
  try {
9948
- if (!storage.isConnected()) {
12527
+ const wasConnected = storage.isConnected();
12528
+ if (!wasConnected) {
9949
12529
  await storage.connect();
9950
12530
  }
9951
12531
  const mnemonic = await storage.get(STORAGE_KEYS_GLOBAL.MNEMONIC);
9952
12532
  if (mnemonic) return true;
9953
12533
  const masterKey = await storage.get(STORAGE_KEYS_GLOBAL.MASTER_KEY);
9954
12534
  if (masterKey) return true;
12535
+ if (!wasConnected) {
12536
+ await storage.disconnect();
12537
+ }
9955
12538
  return false;
9956
12539
  } catch {
9957
12540
  return false;
@@ -9985,6 +12568,7 @@ var Sphere = class _Sphere {
9985
12568
  static async init(options) {
9986
12569
  _Sphere.configureTokenRegistry(options.storage, options.network);
9987
12570
  const groupChat = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12571
+ const market = _Sphere.resolveMarketConfig(options.market);
9988
12572
  const walletExists = await _Sphere.exists(options.storage);
9989
12573
  if (walletExists) {
9990
12574
  const sphere2 = await _Sphere.load({
@@ -9995,6 +12579,7 @@ var Sphere = class _Sphere {
9995
12579
  l1: options.l1,
9996
12580
  price: options.price,
9997
12581
  groupChat,
12582
+ market,
9998
12583
  password: options.password
9999
12584
  });
10000
12585
  return { sphere: sphere2, created: false };
@@ -10022,6 +12607,7 @@ var Sphere = class _Sphere {
10022
12607
  l1: options.l1,
10023
12608
  price: options.price,
10024
12609
  groupChat,
12610
+ market,
10025
12611
  password: options.password
10026
12612
  });
10027
12613
  return { sphere, created: true, generatedMnemonic };
@@ -10049,6 +12635,17 @@ var Sphere = class _Sphere {
10049
12635
  }
10050
12636
  return config;
10051
12637
  }
12638
+ /**
12639
+ * Resolve market module config from Sphere.init() options.
12640
+ * - `true` → enable with default API URL
12641
+ * - `MarketModuleConfig` → pass through
12642
+ * - `undefined` → no market module
12643
+ */
12644
+ static resolveMarketConfig(config) {
12645
+ if (!config) return void 0;
12646
+ if (config === true) return {};
12647
+ return config;
12648
+ }
10052
12649
  /**
10053
12650
  * Configure TokenRegistry in the main bundle context.
10054
12651
  *
@@ -10074,6 +12671,7 @@ var Sphere = class _Sphere {
10074
12671
  }
10075
12672
  _Sphere.configureTokenRegistry(options.storage, options.network);
10076
12673
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12674
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10077
12675
  const sphere = new _Sphere(
10078
12676
  options.storage,
10079
12677
  options.transport,
@@ -10081,7 +12679,8 @@ var Sphere = class _Sphere {
10081
12679
  options.tokenStorage,
10082
12680
  options.l1,
10083
12681
  options.price,
10084
- groupChatConfig
12682
+ groupChatConfig,
12683
+ marketConfig
10085
12684
  );
10086
12685
  sphere._password = options.password ?? null;
10087
12686
  await sphere.storeMnemonic(options.mnemonic, options.derivationPath);
@@ -10109,6 +12708,7 @@ var Sphere = class _Sphere {
10109
12708
  }
10110
12709
  _Sphere.configureTokenRegistry(options.storage, options.network);
10111
12710
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12711
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10112
12712
  const sphere = new _Sphere(
10113
12713
  options.storage,
10114
12714
  options.transport,
@@ -10116,7 +12716,8 @@ var Sphere = class _Sphere {
10116
12716
  options.tokenStorage,
10117
12717
  options.l1,
10118
12718
  options.price,
10119
- groupChatConfig
12719
+ groupChatConfig,
12720
+ marketConfig
10120
12721
  );
10121
12722
  sphere._password = options.password ?? null;
10122
12723
  await sphere.loadIdentityFromStorage();
@@ -10162,6 +12763,7 @@ var Sphere = class _Sphere {
10162
12763
  console.log("[Sphere.import] Storage reconnected");
10163
12764
  }
10164
12765
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat);
12766
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10165
12767
  const sphere = new _Sphere(
10166
12768
  options.storage,
10167
12769
  options.transport,
@@ -10169,7 +12771,8 @@ var Sphere = class _Sphere {
10169
12771
  options.tokenStorage,
10170
12772
  options.l1,
10171
12773
  options.price,
10172
- groupChatConfig
12774
+ groupChatConfig,
12775
+ marketConfig
10173
12776
  );
10174
12777
  sphere._password = options.password ?? null;
10175
12778
  if (options.mnemonic) {
@@ -10250,47 +12853,40 @@ var Sphere = class _Sphere {
10250
12853
  static async clear(storageOrOptions) {
10251
12854
  const storage = "get" in storageOrOptions ? storageOrOptions : storageOrOptions.storage;
10252
12855
  const tokenStorage = "get" in storageOrOptions ? void 0 : storageOrOptions.tokenStorage;
10253
- if (!storage.isConnected()) {
10254
- await storage.connect();
10255
- }
10256
- console.log("[Sphere.clear] Removing storage keys...");
10257
- await storage.remove(STORAGE_KEYS_GLOBAL.MNEMONIC);
10258
- await storage.remove(STORAGE_KEYS_GLOBAL.MASTER_KEY);
10259
- await storage.remove(STORAGE_KEYS_GLOBAL.CHAIN_CODE);
10260
- await storage.remove(STORAGE_KEYS_GLOBAL.DERIVATION_PATH);
10261
- await storage.remove(STORAGE_KEYS_GLOBAL.BASE_PATH);
10262
- await storage.remove(STORAGE_KEYS_GLOBAL.DERIVATION_MODE);
10263
- await storage.remove(STORAGE_KEYS_GLOBAL.WALLET_SOURCE);
10264
- await storage.remove(STORAGE_KEYS_GLOBAL.WALLET_EXISTS);
10265
- await storage.remove(STORAGE_KEYS_GLOBAL.TRACKED_ADDRESSES);
10266
- await storage.remove(STORAGE_KEYS_GLOBAL.ADDRESS_NAMETAGS);
10267
- await storage.remove(STORAGE_KEYS_ADDRESS.PENDING_TRANSFERS);
10268
- await storage.remove(STORAGE_KEYS_ADDRESS.OUTBOX);
10269
- console.log("[Sphere.clear] Storage keys removed");
12856
+ if (_Sphere.instance) {
12857
+ console.log("[Sphere.clear] Destroying Sphere instance...");
12858
+ await _Sphere.instance.destroy();
12859
+ console.log("[Sphere.clear] Sphere instance destroyed");
12860
+ }
12861
+ console.log("[Sphere.clear] Clearing L1 vesting cache...");
12862
+ await vestingClassifier.destroy();
12863
+ console.log("[Sphere.clear] Yielding 50ms for IDB transaction settlement...");
12864
+ await new Promise((r) => setTimeout(r, 50));
10270
12865
  if (tokenStorage?.clear) {
10271
12866
  console.log("[Sphere.clear] Clearing token storage...");
10272
12867
  try {
10273
- await Promise.race([
10274
- tokenStorage.clear(),
10275
- new Promise(
10276
- (_, reject) => setTimeout(() => reject(new Error("tokenStorage.clear() timed out after 2s")), 2e3)
10277
- )
10278
- ]);
12868
+ await tokenStorage.clear();
10279
12869
  console.log("[Sphere.clear] Token storage cleared");
10280
12870
  } catch (err) {
10281
- console.warn("[Sphere.clear] Token storage clear failed/timed out:", err);
12871
+ console.warn("[Sphere.clear] Token storage clear failed:", err);
10282
12872
  }
12873
+ } else {
12874
+ console.log("[Sphere.clear] No token storage provider to clear");
10283
12875
  }
10284
- console.log("[Sphere.clear] Destroying vesting classifier...");
10285
- await vestingClassifier.destroy();
10286
- console.log("[Sphere.clear] Vesting classifier destroyed");
10287
- if (_Sphere.instance) {
10288
- console.log("[Sphere.clear] Destroying Sphere instance...");
10289
- await _Sphere.instance.destroy();
10290
- console.log("[Sphere.clear] Sphere instance destroyed");
12876
+ console.log("[Sphere.clear] Clearing KV storage...");
12877
+ if (!storage.isConnected()) {
12878
+ try {
12879
+ await storage.connect();
12880
+ } catch {
12881
+ }
12882
+ }
12883
+ if (storage.isConnected()) {
12884
+ await storage.clear();
12885
+ console.log("[Sphere.clear] KV storage cleared");
10291
12886
  } else {
10292
- console.log("[Sphere.clear] No Sphere instance to destroy");
12887
+ console.log("[Sphere.clear] KV storage not connected, skipping");
10293
12888
  }
12889
+ console.log("[Sphere.clear] Done");
10294
12890
  }
10295
12891
  /**
10296
12892
  * Get current instance
@@ -10334,6 +12930,10 @@ var Sphere = class _Sphere {
10334
12930
  get groupChat() {
10335
12931
  return this._groupChat;
10336
12932
  }
12933
+ /** Market module (intent bulletin board). Null if not configured. */
12934
+ get market() {
12935
+ return this._market;
12936
+ }
10337
12937
  // ===========================================================================
10338
12938
  // Public Properties - State
10339
12939
  // ===========================================================================
@@ -11134,8 +13734,12 @@ var Sphere = class _Sphere {
11134
13734
  await this._storage.set(STORAGE_KEYS_GLOBAL.CURRENT_ADDRESS_INDEX, index.toString());
11135
13735
  this._storage.setIdentity(this._identity);
11136
13736
  await this._transport.setIdentity(this._identity);
11137
- for (const provider of this._tokenStorageProviders.values()) {
13737
+ console.log(`[Sphere] switchToAddress(${index}): re-initializing ${this._tokenStorageProviders.size} token storage provider(s)`);
13738
+ for (const [providerId, provider] of this._tokenStorageProviders.entries()) {
13739
+ console.log(`[Sphere] switchToAddress(${index}): shutdown provider=${providerId}`);
13740
+ await provider.shutdown();
11138
13741
  provider.setIdentity(this._identity);
13742
+ console.log(`[Sphere] switchToAddress(${index}): initialize provider=${providerId}`);
11139
13743
  await provider.initialize();
11140
13744
  }
11141
13745
  await this.reinitializeModulesForNewAddress();
@@ -11209,9 +13813,17 @@ var Sphere = class _Sphere {
11209
13813
  storage: this._storage,
11210
13814
  emitEvent
11211
13815
  });
13816
+ this._market?.initialize({
13817
+ identity: this._identity,
13818
+ emitEvent
13819
+ });
11212
13820
  await this._payments.load();
11213
13821
  await this._communications.load();
11214
13822
  await this._groupChat?.load();
13823
+ await this._market?.load();
13824
+ this._payments.sync().catch((err) => {
13825
+ console.warn("[Sphere] Post-switch sync failed:", err);
13826
+ });
11215
13827
  }
11216
13828
  /**
11217
13829
  * Derive address at a specific index
@@ -12036,6 +14648,7 @@ var Sphere = class _Sphere {
12036
14648
  this._payments.destroy();
12037
14649
  this._communications.destroy();
12038
14650
  this._groupChat?.destroy();
14651
+ this._market?.destroy();
12039
14652
  await this._transport.disconnect();
12040
14653
  await this._storage.disconnect();
12041
14654
  await this._oracle.disconnect();
@@ -12343,9 +14956,14 @@ var Sphere = class _Sphere {
12343
14956
  storage: this._storage,
12344
14957
  emitEvent
12345
14958
  });
14959
+ this._market?.initialize({
14960
+ identity: this._identity,
14961
+ emitEvent
14962
+ });
12346
14963
  await this._payments.load();
12347
14964
  await this._communications.load();
12348
14965
  await this._groupChat?.load();
14966
+ await this._market?.load();
12349
14967
  }
12350
14968
  // ===========================================================================
12351
14969
  // Private: Helpers
@@ -12695,4 +15313,16 @@ export {
12695
15313
  toSmallestUnit,
12696
15314
  validateMnemonic2 as validateMnemonic
12697
15315
  };
15316
+ /*! Bundled license information:
15317
+
15318
+ @noble/hashes/utils.js:
15319
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
15320
+
15321
+ @noble/curves/utils.js:
15322
+ @noble/curves/abstract/modular.js:
15323
+ @noble/curves/abstract/curve.js:
15324
+ @noble/curves/abstract/weierstrass.js:
15325
+ @noble/curves/secp256k1.js:
15326
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
15327
+ */
12698
15328
  //# sourceMappingURL=index.js.map