@unicitylabs/sphere-sdk 0.3.9 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,15 +20,15 @@ var __copyProps = (to, from, except, desc) => {
20
20
  }
21
21
  return to;
22
22
  };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
+ var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
24
24
  // If the importer is in node compatibility mode or this is not an ESM
25
25
  // file that has been converted to a CommonJS file using a Babel-
26
26
  // compatible transform (i.e. "__esModule" has not been set), then set
27
27
  // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
- mod
28
+ isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
29
+ mod2
30
30
  ));
31
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
+ var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
32
32
 
33
33
  // core/bech32.ts
34
34
  function convertBits(data, fromBits, toBits, pad) {
@@ -75,10 +75,10 @@ function bech32Polymod(values) {
75
75
  }
76
76
  function bech32Checksum(hrp, data) {
77
77
  const values = hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]);
78
- const mod = bech32Polymod(values) ^ 1;
78
+ const mod2 = bech32Polymod(values) ^ 1;
79
79
  const ret = [];
80
80
  for (let p = 0; p < 6; p++) {
81
- ret.push(mod >> 5 * (5 - p) & 31);
81
+ ret.push(mod2 >> 5 * (5 - p) & 31);
82
82
  }
83
83
  return ret;
84
84
  }
@@ -776,9 +776,13 @@ var VestingClassifier = class {
776
776
  storeName = "vestingCache";
777
777
  db = null;
778
778
  /**
779
- * Initialize IndexedDB for persistent caching
779
+ * Initialize IndexedDB for persistent caching.
780
+ * In Node.js (no IndexedDB), silently falls back to memory-only caching.
780
781
  */
781
782
  async initDB() {
783
+ if (typeof indexedDB === "undefined") {
784
+ return;
785
+ }
782
786
  return new Promise((resolve, reject) => {
783
787
  const request = indexedDB.open(this.dbName, 1);
784
788
  request.onupgradeneeded = (event) => {
@@ -6727,6 +6731,15 @@ var PaymentsModule = class _PaymentsModule {
6727
6731
  );
6728
6732
  return import_SigningService.SigningService.createFromSecret(privateKeyBytes);
6729
6733
  }
6734
+ /**
6735
+ * Get the wallet's signing public key (used for token ownership predicates).
6736
+ * This is the key that token state predicates are checked against.
6737
+ */
6738
+ async getSigningPublicKey() {
6739
+ this.ensureInitialized();
6740
+ const signer = await this.createSigningService();
6741
+ return signer.publicKey;
6742
+ }
6730
6743
  /**
6731
6744
  * Create DirectAddress from a public key using UnmaskedPredicateReference
6732
6745
  */
@@ -7375,14 +7388,17 @@ var CommunicationsModule = class {
7375
7388
  broadcasts = /* @__PURE__ */ new Map();
7376
7389
  // Subscriptions
7377
7390
  unsubscribeMessages = null;
7391
+ unsubscribeComposing = null;
7378
7392
  broadcastSubscriptions = /* @__PURE__ */ new Map();
7379
7393
  // Handlers
7380
7394
  dmHandlers = /* @__PURE__ */ new Set();
7395
+ composingHandlers = /* @__PURE__ */ new Set();
7381
7396
  broadcastHandlers = /* @__PURE__ */ new Set();
7382
7397
  constructor(config) {
7383
7398
  this.config = {
7384
7399
  autoSave: config?.autoSave ?? true,
7385
7400
  maxMessages: config?.maxMessages ?? 1e3,
7401
+ maxPerConversation: config?.maxPerConversation ?? 200,
7386
7402
  readReceipts: config?.readReceipts ?? true
7387
7403
  };
7388
7404
  }
@@ -7393,6 +7409,8 @@ var CommunicationsModule = class {
7393
7409
  * Initialize module with dependencies
7394
7410
  */
7395
7411
  initialize(deps) {
7412
+ this.unsubscribeMessages?.();
7413
+ this.unsubscribeComposing?.();
7396
7414
  this.deps = deps;
7397
7415
  this.unsubscribeMessages = deps.transport.onMessage((msg) => {
7398
7416
  this.handleIncomingMessage(msg);
@@ -7419,19 +7437,41 @@ var CommunicationsModule = class {
7419
7437
  });
7420
7438
  });
7421
7439
  }
7440
+ this.unsubscribeComposing = deps.transport.onComposing?.((indicator) => {
7441
+ this.handleComposingIndicator(indicator);
7442
+ }) ?? null;
7422
7443
  }
7423
7444
  /**
7424
- * Load messages from storage
7445
+ * Load messages from storage.
7446
+ * Uses per-address key (STORAGE_KEYS_ADDRESS.MESSAGES) which is automatically
7447
+ * scoped by LocalStorageProvider to sphere_DIRECT_xxx_yyy_messages.
7448
+ * Falls back to legacy global 'direct_messages' key for migration.
7425
7449
  */
7426
7450
  async load() {
7427
7451
  this.ensureInitialized();
7428
- const data = await this.deps.storage.get("direct_messages");
7452
+ this.messages.clear();
7453
+ let data = await this.deps.storage.get(STORAGE_KEYS_ADDRESS.MESSAGES);
7429
7454
  if (data) {
7430
7455
  const messages = JSON.parse(data);
7431
- this.messages.clear();
7432
7456
  for (const msg of messages) {
7433
7457
  this.messages.set(msg.id, msg);
7434
7458
  }
7459
+ return;
7460
+ }
7461
+ data = await this.deps.storage.get("direct_messages");
7462
+ if (data) {
7463
+ const allMessages = JSON.parse(data);
7464
+ const myPubkey = this.deps.identity.chainPubkey;
7465
+ const myMessages = allMessages.filter(
7466
+ (m) => m.senderPubkey === myPubkey || m.recipientPubkey === myPubkey
7467
+ );
7468
+ for (const msg of myMessages) {
7469
+ this.messages.set(msg.id, msg);
7470
+ }
7471
+ if (myMessages.length > 0) {
7472
+ await this.save();
7473
+ console.log(`[Communications] Migrated ${myMessages.length} messages to per-address storage`);
7474
+ }
7435
7475
  }
7436
7476
  }
7437
7477
  /**
@@ -7440,6 +7480,8 @@ var CommunicationsModule = class {
7440
7480
  destroy() {
7441
7481
  this.unsubscribeMessages?.();
7442
7482
  this.unsubscribeMessages = null;
7483
+ this.unsubscribeComposing?.();
7484
+ this.unsubscribeComposing = null;
7443
7485
  for (const unsub of this.broadcastSubscriptions.values()) {
7444
7486
  unsub();
7445
7487
  }
@@ -7531,6 +7573,37 @@ var CommunicationsModule = class {
7531
7573
  }
7532
7574
  return messages.length;
7533
7575
  }
7576
+ /**
7577
+ * Get a page of messages from a conversation (for lazy loading).
7578
+ * Returns messages in chronological order with a cursor for loading older messages.
7579
+ */
7580
+ getConversationPage(peerPubkey, options) {
7581
+ const limit = options?.limit ?? 20;
7582
+ const before = options?.before ?? Infinity;
7583
+ const all = Array.from(this.messages.values()).filter(
7584
+ (m) => (m.senderPubkey === peerPubkey || m.recipientPubkey === peerPubkey) && m.timestamp < before
7585
+ ).sort((a, b) => b.timestamp - a.timestamp);
7586
+ const page = all.slice(0, limit);
7587
+ return {
7588
+ messages: page.reverse(),
7589
+ // chronological order for display
7590
+ hasMore: all.length > limit,
7591
+ oldestTimestamp: page.length > 0 ? page[0].timestamp : null
7592
+ };
7593
+ }
7594
+ /**
7595
+ * Delete all messages in a conversation with a peer
7596
+ */
7597
+ async deleteConversation(peerPubkey) {
7598
+ for (const [id, msg] of this.messages) {
7599
+ if (msg.senderPubkey === peerPubkey || msg.recipientPubkey === peerPubkey) {
7600
+ this.messages.delete(id);
7601
+ }
7602
+ }
7603
+ if (this.config.autoSave) {
7604
+ await this.save();
7605
+ }
7606
+ }
7534
7607
  /**
7535
7608
  * Send typing indicator to a peer
7536
7609
  */
@@ -7540,6 +7613,26 @@ var CommunicationsModule = class {
7540
7613
  await this.deps.transport.sendTypingIndicator(peerPubkey);
7541
7614
  }
7542
7615
  }
7616
+ /**
7617
+ * Send a composing indicator to a peer.
7618
+ * Fire-and-forget — does not save to message history.
7619
+ */
7620
+ async sendComposingIndicator(recipientPubkeyOrNametag) {
7621
+ this.ensureInitialized();
7622
+ const recipientPubkey = await this.resolveRecipient(recipientPubkeyOrNametag);
7623
+ const content = JSON.stringify({
7624
+ senderNametag: this.deps.identity.nametag,
7625
+ expiresIn: 3e4
7626
+ });
7627
+ await this.deps.transport.sendComposingIndicator?.(recipientPubkey, content);
7628
+ }
7629
+ /**
7630
+ * Subscribe to incoming composing indicators
7631
+ */
7632
+ onComposingIndicator(handler) {
7633
+ this.composingHandlers.add(handler);
7634
+ return () => this.composingHandlers.delete(handler);
7635
+ }
7543
7636
  /**
7544
7637
  * Subscribe to incoming DMs
7545
7638
  */
@@ -7652,6 +7745,21 @@ var CommunicationsModule = class {
7652
7745
  }
7653
7746
  this.pruneIfNeeded();
7654
7747
  }
7748
+ handleComposingIndicator(indicator) {
7749
+ const composing = {
7750
+ senderPubkey: indicator.senderPubkey,
7751
+ senderNametag: indicator.senderNametag,
7752
+ expiresIn: indicator.expiresIn
7753
+ };
7754
+ this.deps.emitEvent("composing:started", composing);
7755
+ for (const handler of this.composingHandlers) {
7756
+ try {
7757
+ handler(composing);
7758
+ } catch (error) {
7759
+ console.error("[Communications] Composing handler error:", error);
7760
+ }
7761
+ }
7762
+ }
7655
7763
  handleIncomingBroadcast(incoming) {
7656
7764
  const message = {
7657
7765
  id: incoming.id,
@@ -7675,9 +7783,23 @@ var CommunicationsModule = class {
7675
7783
  // ===========================================================================
7676
7784
  async save() {
7677
7785
  const messages = Array.from(this.messages.values());
7678
- await this.deps.storage.set("direct_messages", JSON.stringify(messages));
7786
+ await this.deps.storage.set(STORAGE_KEYS_ADDRESS.MESSAGES, JSON.stringify(messages));
7679
7787
  }
7680
7788
  pruneIfNeeded() {
7789
+ const byPeer = /* @__PURE__ */ new Map();
7790
+ for (const msg of this.messages.values()) {
7791
+ const peer = msg.senderPubkey === this.deps?.identity.chainPubkey ? msg.recipientPubkey : msg.senderPubkey;
7792
+ if (!byPeer.has(peer)) byPeer.set(peer, []);
7793
+ byPeer.get(peer).push(msg);
7794
+ }
7795
+ for (const [, msgs] of byPeer) {
7796
+ if (msgs.length <= this.config.maxPerConversation) continue;
7797
+ msgs.sort((a, b) => a.timestamp - b.timestamp);
7798
+ const toRemove2 = msgs.slice(0, msgs.length - this.config.maxPerConversation);
7799
+ for (const msg of toRemove2) {
7800
+ this.messages.delete(msg.id);
7801
+ }
7802
+ }
7681
7803
  if (this.messages.size <= this.config.maxMessages) return;
7682
7804
  const sorted = Array.from(this.messages.entries()).sort(([, a], [, b]) => a.timestamp - b.timestamp);
7683
7805
  const toRemove = sorted.slice(0, sorted.length - this.config.maxMessages);
@@ -9086,6 +9208,2427 @@ function createGroupChatModule(config) {
9086
9208
  return new GroupChatModule(config);
9087
9209
  }
9088
9210
 
9211
+ // node_modules/@noble/hashes/utils.js
9212
+ function isBytes(a) {
9213
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
9214
+ }
9215
+ function anumber(n, title = "") {
9216
+ if (!Number.isSafeInteger(n) || n < 0) {
9217
+ const prefix = title && `"${title}" `;
9218
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
9219
+ }
9220
+ }
9221
+ function abytes(value, length, title = "") {
9222
+ const bytes = isBytes(value);
9223
+ const len = value?.length;
9224
+ const needsLen = length !== void 0;
9225
+ if (!bytes || needsLen && len !== length) {
9226
+ const prefix = title && `"${title}" `;
9227
+ const ofLen = needsLen ? ` of length ${length}` : "";
9228
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
9229
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
9230
+ }
9231
+ return value;
9232
+ }
9233
+ function ahash(h) {
9234
+ if (typeof h !== "function" || typeof h.create !== "function")
9235
+ throw new Error("Hash must wrapped by utils.createHasher");
9236
+ anumber(h.outputLen);
9237
+ anumber(h.blockLen);
9238
+ }
9239
+ function aexists(instance, checkFinished = true) {
9240
+ if (instance.destroyed)
9241
+ throw new Error("Hash instance has been destroyed");
9242
+ if (checkFinished && instance.finished)
9243
+ throw new Error("Hash#digest() has already been called");
9244
+ }
9245
+ function aoutput(out, instance) {
9246
+ abytes(out, void 0, "digestInto() output");
9247
+ const min = instance.outputLen;
9248
+ if (out.length < min) {
9249
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
9250
+ }
9251
+ }
9252
+ function clean(...arrays) {
9253
+ for (let i = 0; i < arrays.length; i++) {
9254
+ arrays[i].fill(0);
9255
+ }
9256
+ }
9257
+ function createView(arr) {
9258
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
9259
+ }
9260
+ function rotr(word, shift) {
9261
+ return word << 32 - shift | word >>> shift;
9262
+ }
9263
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
9264
+ // @ts-ignore
9265
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
9266
+ ))();
9267
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
9268
+ function bytesToHex4(bytes) {
9269
+ abytes(bytes);
9270
+ if (hasHexBuiltin)
9271
+ return bytes.toHex();
9272
+ let hex = "";
9273
+ for (let i = 0; i < bytes.length; i++) {
9274
+ hex += hexes[bytes[i]];
9275
+ }
9276
+ return hex;
9277
+ }
9278
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
9279
+ function asciiToBase16(ch) {
9280
+ if (ch >= asciis._0 && ch <= asciis._9)
9281
+ return ch - asciis._0;
9282
+ if (ch >= asciis.A && ch <= asciis.F)
9283
+ return ch - (asciis.A - 10);
9284
+ if (ch >= asciis.a && ch <= asciis.f)
9285
+ return ch - (asciis.a - 10);
9286
+ return;
9287
+ }
9288
+ function hexToBytes2(hex) {
9289
+ if (typeof hex !== "string")
9290
+ throw new Error("hex string expected, got " + typeof hex);
9291
+ if (hasHexBuiltin)
9292
+ return Uint8Array.fromHex(hex);
9293
+ const hl = hex.length;
9294
+ const al = hl / 2;
9295
+ if (hl % 2)
9296
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
9297
+ const array = new Uint8Array(al);
9298
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
9299
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
9300
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
9301
+ if (n1 === void 0 || n2 === void 0) {
9302
+ const char = hex[hi] + hex[hi + 1];
9303
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
9304
+ }
9305
+ array[ai] = n1 * 16 + n2;
9306
+ }
9307
+ return array;
9308
+ }
9309
+ function concatBytes(...arrays) {
9310
+ let sum = 0;
9311
+ for (let i = 0; i < arrays.length; i++) {
9312
+ const a = arrays[i];
9313
+ abytes(a);
9314
+ sum += a.length;
9315
+ }
9316
+ const res = new Uint8Array(sum);
9317
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
9318
+ const a = arrays[i];
9319
+ res.set(a, pad);
9320
+ pad += a.length;
9321
+ }
9322
+ return res;
9323
+ }
9324
+ function createHasher(hashCons, info = {}) {
9325
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
9326
+ const tmp = hashCons(void 0);
9327
+ hashC.outputLen = tmp.outputLen;
9328
+ hashC.blockLen = tmp.blockLen;
9329
+ hashC.create = (opts) => hashCons(opts);
9330
+ Object.assign(hashC, info);
9331
+ return Object.freeze(hashC);
9332
+ }
9333
+ function randomBytes2(bytesLength = 32) {
9334
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
9335
+ if (typeof cr?.getRandomValues !== "function")
9336
+ throw new Error("crypto.getRandomValues must be defined");
9337
+ return cr.getRandomValues(new Uint8Array(bytesLength));
9338
+ }
9339
+ var oidNist = (suffix) => ({
9340
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
9341
+ });
9342
+
9343
+ // node_modules/@noble/hashes/_md.js
9344
+ function Chi(a, b, c) {
9345
+ return a & b ^ ~a & c;
9346
+ }
9347
+ function Maj(a, b, c) {
9348
+ return a & b ^ a & c ^ b & c;
9349
+ }
9350
+ var HashMD = class {
9351
+ blockLen;
9352
+ outputLen;
9353
+ padOffset;
9354
+ isLE;
9355
+ // For partial updates less than block size
9356
+ buffer;
9357
+ view;
9358
+ finished = false;
9359
+ length = 0;
9360
+ pos = 0;
9361
+ destroyed = false;
9362
+ constructor(blockLen, outputLen, padOffset, isLE) {
9363
+ this.blockLen = blockLen;
9364
+ this.outputLen = outputLen;
9365
+ this.padOffset = padOffset;
9366
+ this.isLE = isLE;
9367
+ this.buffer = new Uint8Array(blockLen);
9368
+ this.view = createView(this.buffer);
9369
+ }
9370
+ update(data) {
9371
+ aexists(this);
9372
+ abytes(data);
9373
+ const { view, buffer, blockLen } = this;
9374
+ const len = data.length;
9375
+ for (let pos = 0; pos < len; ) {
9376
+ const take = Math.min(blockLen - this.pos, len - pos);
9377
+ if (take === blockLen) {
9378
+ const dataView = createView(data);
9379
+ for (; blockLen <= len - pos; pos += blockLen)
9380
+ this.process(dataView, pos);
9381
+ continue;
9382
+ }
9383
+ buffer.set(data.subarray(pos, pos + take), this.pos);
9384
+ this.pos += take;
9385
+ pos += take;
9386
+ if (this.pos === blockLen) {
9387
+ this.process(view, 0);
9388
+ this.pos = 0;
9389
+ }
9390
+ }
9391
+ this.length += data.length;
9392
+ this.roundClean();
9393
+ return this;
9394
+ }
9395
+ digestInto(out) {
9396
+ aexists(this);
9397
+ aoutput(out, this);
9398
+ this.finished = true;
9399
+ const { buffer, view, blockLen, isLE } = this;
9400
+ let { pos } = this;
9401
+ buffer[pos++] = 128;
9402
+ clean(this.buffer.subarray(pos));
9403
+ if (this.padOffset > blockLen - pos) {
9404
+ this.process(view, 0);
9405
+ pos = 0;
9406
+ }
9407
+ for (let i = pos; i < blockLen; i++)
9408
+ buffer[i] = 0;
9409
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
9410
+ this.process(view, 0);
9411
+ const oview = createView(out);
9412
+ const len = this.outputLen;
9413
+ if (len % 4)
9414
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
9415
+ const outLen = len / 4;
9416
+ const state = this.get();
9417
+ if (outLen > state.length)
9418
+ throw new Error("_sha2: outputLen bigger than state");
9419
+ for (let i = 0; i < outLen; i++)
9420
+ oview.setUint32(4 * i, state[i], isLE);
9421
+ }
9422
+ digest() {
9423
+ const { buffer, outputLen } = this;
9424
+ this.digestInto(buffer);
9425
+ const res = buffer.slice(0, outputLen);
9426
+ this.destroy();
9427
+ return res;
9428
+ }
9429
+ _cloneInto(to) {
9430
+ to ||= new this.constructor();
9431
+ to.set(...this.get());
9432
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
9433
+ to.destroyed = destroyed;
9434
+ to.finished = finished;
9435
+ to.length = length;
9436
+ to.pos = pos;
9437
+ if (length % blockLen)
9438
+ to.buffer.set(buffer);
9439
+ return to;
9440
+ }
9441
+ clone() {
9442
+ return this._cloneInto();
9443
+ }
9444
+ };
9445
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
9446
+ 1779033703,
9447
+ 3144134277,
9448
+ 1013904242,
9449
+ 2773480762,
9450
+ 1359893119,
9451
+ 2600822924,
9452
+ 528734635,
9453
+ 1541459225
9454
+ ]);
9455
+
9456
+ // node_modules/@noble/hashes/sha2.js
9457
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
9458
+ 1116352408,
9459
+ 1899447441,
9460
+ 3049323471,
9461
+ 3921009573,
9462
+ 961987163,
9463
+ 1508970993,
9464
+ 2453635748,
9465
+ 2870763221,
9466
+ 3624381080,
9467
+ 310598401,
9468
+ 607225278,
9469
+ 1426881987,
9470
+ 1925078388,
9471
+ 2162078206,
9472
+ 2614888103,
9473
+ 3248222580,
9474
+ 3835390401,
9475
+ 4022224774,
9476
+ 264347078,
9477
+ 604807628,
9478
+ 770255983,
9479
+ 1249150122,
9480
+ 1555081692,
9481
+ 1996064986,
9482
+ 2554220882,
9483
+ 2821834349,
9484
+ 2952996808,
9485
+ 3210313671,
9486
+ 3336571891,
9487
+ 3584528711,
9488
+ 113926993,
9489
+ 338241895,
9490
+ 666307205,
9491
+ 773529912,
9492
+ 1294757372,
9493
+ 1396182291,
9494
+ 1695183700,
9495
+ 1986661051,
9496
+ 2177026350,
9497
+ 2456956037,
9498
+ 2730485921,
9499
+ 2820302411,
9500
+ 3259730800,
9501
+ 3345764771,
9502
+ 3516065817,
9503
+ 3600352804,
9504
+ 4094571909,
9505
+ 275423344,
9506
+ 430227734,
9507
+ 506948616,
9508
+ 659060556,
9509
+ 883997877,
9510
+ 958139571,
9511
+ 1322822218,
9512
+ 1537002063,
9513
+ 1747873779,
9514
+ 1955562222,
9515
+ 2024104815,
9516
+ 2227730452,
9517
+ 2361852424,
9518
+ 2428436474,
9519
+ 2756734187,
9520
+ 3204031479,
9521
+ 3329325298
9522
+ ]);
9523
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
9524
+ var SHA2_32B = class extends HashMD {
9525
+ constructor(outputLen) {
9526
+ super(64, outputLen, 8, false);
9527
+ }
9528
+ get() {
9529
+ const { A, B, C, D, E, F, G, H } = this;
9530
+ return [A, B, C, D, E, F, G, H];
9531
+ }
9532
+ // prettier-ignore
9533
+ set(A, B, C, D, E, F, G, H) {
9534
+ this.A = A | 0;
9535
+ this.B = B | 0;
9536
+ this.C = C | 0;
9537
+ this.D = D | 0;
9538
+ this.E = E | 0;
9539
+ this.F = F | 0;
9540
+ this.G = G | 0;
9541
+ this.H = H | 0;
9542
+ }
9543
+ process(view, offset) {
9544
+ for (let i = 0; i < 16; i++, offset += 4)
9545
+ SHA256_W[i] = view.getUint32(offset, false);
9546
+ for (let i = 16; i < 64; i++) {
9547
+ const W15 = SHA256_W[i - 15];
9548
+ const W2 = SHA256_W[i - 2];
9549
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
9550
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
9551
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
9552
+ }
9553
+ let { A, B, C, D, E, F, G, H } = this;
9554
+ for (let i = 0; i < 64; i++) {
9555
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
9556
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
9557
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
9558
+ const T2 = sigma0 + Maj(A, B, C) | 0;
9559
+ H = G;
9560
+ G = F;
9561
+ F = E;
9562
+ E = D + T1 | 0;
9563
+ D = C;
9564
+ C = B;
9565
+ B = A;
9566
+ A = T1 + T2 | 0;
9567
+ }
9568
+ A = A + this.A | 0;
9569
+ B = B + this.B | 0;
9570
+ C = C + this.C | 0;
9571
+ D = D + this.D | 0;
9572
+ E = E + this.E | 0;
9573
+ F = F + this.F | 0;
9574
+ G = G + this.G | 0;
9575
+ H = H + this.H | 0;
9576
+ this.set(A, B, C, D, E, F, G, H);
9577
+ }
9578
+ roundClean() {
9579
+ clean(SHA256_W);
9580
+ }
9581
+ destroy() {
9582
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
9583
+ clean(this.buffer);
9584
+ }
9585
+ };
9586
+ var _SHA256 = class extends SHA2_32B {
9587
+ // We cannot use array here since array allows indexing by variable
9588
+ // which means optimizer/compiler cannot use registers.
9589
+ A = SHA256_IV[0] | 0;
9590
+ B = SHA256_IV[1] | 0;
9591
+ C = SHA256_IV[2] | 0;
9592
+ D = SHA256_IV[3] | 0;
9593
+ E = SHA256_IV[4] | 0;
9594
+ F = SHA256_IV[5] | 0;
9595
+ G = SHA256_IV[6] | 0;
9596
+ H = SHA256_IV[7] | 0;
9597
+ constructor() {
9598
+ super(32);
9599
+ }
9600
+ };
9601
+ var sha2564 = /* @__PURE__ */ createHasher(
9602
+ () => new _SHA256(),
9603
+ /* @__PURE__ */ oidNist(1)
9604
+ );
9605
+
9606
+ // node_modules/@noble/curves/utils.js
9607
+ var _0n = /* @__PURE__ */ BigInt(0);
9608
+ var _1n = /* @__PURE__ */ BigInt(1);
9609
+ function abool(value, title = "") {
9610
+ if (typeof value !== "boolean") {
9611
+ const prefix = title && `"${title}" `;
9612
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
9613
+ }
9614
+ return value;
9615
+ }
9616
+ function abignumber(n) {
9617
+ if (typeof n === "bigint") {
9618
+ if (!isPosBig(n))
9619
+ throw new Error("positive bigint expected, got " + n);
9620
+ } else
9621
+ anumber(n);
9622
+ return n;
9623
+ }
9624
+ function numberToHexUnpadded(num) {
9625
+ const hex = abignumber(num).toString(16);
9626
+ return hex.length & 1 ? "0" + hex : hex;
9627
+ }
9628
+ function hexToNumber(hex) {
9629
+ if (typeof hex !== "string")
9630
+ throw new Error("hex string expected, got " + typeof hex);
9631
+ return hex === "" ? _0n : BigInt("0x" + hex);
9632
+ }
9633
+ function bytesToNumberBE(bytes) {
9634
+ return hexToNumber(bytesToHex4(bytes));
9635
+ }
9636
+ function bytesToNumberLE(bytes) {
9637
+ return hexToNumber(bytesToHex4(copyBytes(abytes(bytes)).reverse()));
9638
+ }
9639
+ function numberToBytesBE(n, len) {
9640
+ anumber(len);
9641
+ n = abignumber(n);
9642
+ const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
9643
+ if (res.length !== len)
9644
+ throw new Error("number too large");
9645
+ return res;
9646
+ }
9647
+ function numberToBytesLE(n, len) {
9648
+ return numberToBytesBE(n, len).reverse();
9649
+ }
9650
+ function copyBytes(bytes) {
9651
+ return Uint8Array.from(bytes);
9652
+ }
9653
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
9654
+ function inRange(n, min, max) {
9655
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
9656
+ }
9657
+ function aInRange(title, n, min, max) {
9658
+ if (!inRange(n, min, max))
9659
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
9660
+ }
9661
+ function bitLen(n) {
9662
+ let len;
9663
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
9664
+ ;
9665
+ return len;
9666
+ }
9667
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
9668
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
9669
+ anumber(hashLen, "hashLen");
9670
+ anumber(qByteLen, "qByteLen");
9671
+ if (typeof hmacFn !== "function")
9672
+ throw new Error("hmacFn must be a function");
9673
+ const u8n = (len) => new Uint8Array(len);
9674
+ const NULL = Uint8Array.of();
9675
+ const byte0 = Uint8Array.of(0);
9676
+ const byte1 = Uint8Array.of(1);
9677
+ const _maxDrbgIters = 1e3;
9678
+ let v = u8n(hashLen);
9679
+ let k = u8n(hashLen);
9680
+ let i = 0;
9681
+ const reset = () => {
9682
+ v.fill(1);
9683
+ k.fill(0);
9684
+ i = 0;
9685
+ };
9686
+ const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
9687
+ const reseed = (seed = NULL) => {
9688
+ k = h(byte0, seed);
9689
+ v = h();
9690
+ if (seed.length === 0)
9691
+ return;
9692
+ k = h(byte1, seed);
9693
+ v = h();
9694
+ };
9695
+ const gen = () => {
9696
+ if (i++ >= _maxDrbgIters)
9697
+ throw new Error("drbg: tried max amount of iterations");
9698
+ let len = 0;
9699
+ const out = [];
9700
+ while (len < qByteLen) {
9701
+ v = h();
9702
+ const sl = v.slice();
9703
+ out.push(sl);
9704
+ len += v.length;
9705
+ }
9706
+ return concatBytes(...out);
9707
+ };
9708
+ const genUntil = (seed, pred) => {
9709
+ reset();
9710
+ reseed(seed);
9711
+ let res = void 0;
9712
+ while (!(res = pred(gen())))
9713
+ reseed();
9714
+ reset();
9715
+ return res;
9716
+ };
9717
+ return genUntil;
9718
+ }
9719
+ function validateObject(object, fields = {}, optFields = {}) {
9720
+ if (!object || typeof object !== "object")
9721
+ throw new Error("expected valid options object");
9722
+ function checkField(fieldName, expectedType, isOpt) {
9723
+ const val = object[fieldName];
9724
+ if (isOpt && val === void 0)
9725
+ return;
9726
+ const current = typeof val;
9727
+ if (current !== expectedType || val === null)
9728
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
9729
+ }
9730
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
9731
+ iter(fields, false);
9732
+ iter(optFields, true);
9733
+ }
9734
+ function memoized(fn) {
9735
+ const map = /* @__PURE__ */ new WeakMap();
9736
+ return (arg, ...args) => {
9737
+ const val = map.get(arg);
9738
+ if (val !== void 0)
9739
+ return val;
9740
+ const computed = fn(arg, ...args);
9741
+ map.set(arg, computed);
9742
+ return computed;
9743
+ };
9744
+ }
9745
+
9746
+ // node_modules/@noble/curves/abstract/modular.js
9747
+ var _0n2 = /* @__PURE__ */ BigInt(0);
9748
+ var _1n2 = /* @__PURE__ */ BigInt(1);
9749
+ var _2n = /* @__PURE__ */ BigInt(2);
9750
+ var _3n = /* @__PURE__ */ BigInt(3);
9751
+ var _4n = /* @__PURE__ */ BigInt(4);
9752
+ var _5n = /* @__PURE__ */ BigInt(5);
9753
+ var _7n = /* @__PURE__ */ BigInt(7);
9754
+ var _8n = /* @__PURE__ */ BigInt(8);
9755
+ var _9n = /* @__PURE__ */ BigInt(9);
9756
+ var _16n = /* @__PURE__ */ BigInt(16);
9757
+ function mod(a, b) {
9758
+ const result = a % b;
9759
+ return result >= _0n2 ? result : b + result;
9760
+ }
9761
+ function pow2(x, power, modulo) {
9762
+ let res = x;
9763
+ while (power-- > _0n2) {
9764
+ res *= res;
9765
+ res %= modulo;
9766
+ }
9767
+ return res;
9768
+ }
9769
+ function invert(number, modulo) {
9770
+ if (number === _0n2)
9771
+ throw new Error("invert: expected non-zero number");
9772
+ if (modulo <= _0n2)
9773
+ throw new Error("invert: expected positive modulus, got " + modulo);
9774
+ let a = mod(number, modulo);
9775
+ let b = modulo;
9776
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
9777
+ while (a !== _0n2) {
9778
+ const q = b / a;
9779
+ const r = b % a;
9780
+ const m = x - u * q;
9781
+ const n = y - v * q;
9782
+ b = a, a = r, x = u, y = v, u = m, v = n;
9783
+ }
9784
+ const gcd = b;
9785
+ if (gcd !== _1n2)
9786
+ throw new Error("invert: does not exist");
9787
+ return mod(x, modulo);
9788
+ }
9789
+ function assertIsSquare(Fp, root, n) {
9790
+ if (!Fp.eql(Fp.sqr(root), n))
9791
+ throw new Error("Cannot find square root");
9792
+ }
9793
+ function sqrt3mod4(Fp, n) {
9794
+ const p1div4 = (Fp.ORDER + _1n2) / _4n;
9795
+ const root = Fp.pow(n, p1div4);
9796
+ assertIsSquare(Fp, root, n);
9797
+ return root;
9798
+ }
9799
+ function sqrt5mod8(Fp, n) {
9800
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
9801
+ const n2 = Fp.mul(n, _2n);
9802
+ const v = Fp.pow(n2, p5div8);
9803
+ const nv = Fp.mul(n, v);
9804
+ const i = Fp.mul(Fp.mul(nv, _2n), v);
9805
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
9806
+ assertIsSquare(Fp, root, n);
9807
+ return root;
9808
+ }
9809
+ function sqrt9mod16(P) {
9810
+ const Fp_ = Field(P);
9811
+ const tn = tonelliShanks(P);
9812
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
9813
+ const c2 = tn(Fp_, c1);
9814
+ const c3 = tn(Fp_, Fp_.neg(c1));
9815
+ const c4 = (P + _7n) / _16n;
9816
+ return (Fp, n) => {
9817
+ let tv1 = Fp.pow(n, c4);
9818
+ let tv2 = Fp.mul(tv1, c1);
9819
+ const tv3 = Fp.mul(tv1, c2);
9820
+ const tv4 = Fp.mul(tv1, c3);
9821
+ const e1 = Fp.eql(Fp.sqr(tv2), n);
9822
+ const e2 = Fp.eql(Fp.sqr(tv3), n);
9823
+ tv1 = Fp.cmov(tv1, tv2, e1);
9824
+ tv2 = Fp.cmov(tv4, tv3, e2);
9825
+ const e3 = Fp.eql(Fp.sqr(tv2), n);
9826
+ const root = Fp.cmov(tv1, tv2, e3);
9827
+ assertIsSquare(Fp, root, n);
9828
+ return root;
9829
+ };
9830
+ }
9831
+ function tonelliShanks(P) {
9832
+ if (P < _3n)
9833
+ throw new Error("sqrt is not defined for small field");
9834
+ let Q = P - _1n2;
9835
+ let S = 0;
9836
+ while (Q % _2n === _0n2) {
9837
+ Q /= _2n;
9838
+ S++;
9839
+ }
9840
+ let Z = _2n;
9841
+ const _Fp = Field(P);
9842
+ while (FpLegendre(_Fp, Z) === 1) {
9843
+ if (Z++ > 1e3)
9844
+ throw new Error("Cannot find square root: probably non-prime P");
9845
+ }
9846
+ if (S === 1)
9847
+ return sqrt3mod4;
9848
+ let cc = _Fp.pow(Z, Q);
9849
+ const Q1div2 = (Q + _1n2) / _2n;
9850
+ return function tonelliSlow(Fp, n) {
9851
+ if (Fp.is0(n))
9852
+ return n;
9853
+ if (FpLegendre(Fp, n) !== 1)
9854
+ throw new Error("Cannot find square root");
9855
+ let M = S;
9856
+ let c = Fp.mul(Fp.ONE, cc);
9857
+ let t = Fp.pow(n, Q);
9858
+ let R = Fp.pow(n, Q1div2);
9859
+ while (!Fp.eql(t, Fp.ONE)) {
9860
+ if (Fp.is0(t))
9861
+ return Fp.ZERO;
9862
+ let i = 1;
9863
+ let t_tmp = Fp.sqr(t);
9864
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
9865
+ i++;
9866
+ t_tmp = Fp.sqr(t_tmp);
9867
+ if (i === M)
9868
+ throw new Error("Cannot find square root");
9869
+ }
9870
+ const exponent = _1n2 << BigInt(M - i - 1);
9871
+ const b = Fp.pow(c, exponent);
9872
+ M = i;
9873
+ c = Fp.sqr(b);
9874
+ t = Fp.mul(t, c);
9875
+ R = Fp.mul(R, b);
9876
+ }
9877
+ return R;
9878
+ };
9879
+ }
9880
+ function FpSqrt(P) {
9881
+ if (P % _4n === _3n)
9882
+ return sqrt3mod4;
9883
+ if (P % _8n === _5n)
9884
+ return sqrt5mod8;
9885
+ if (P % _16n === _9n)
9886
+ return sqrt9mod16(P);
9887
+ return tonelliShanks(P);
9888
+ }
9889
+ var FIELD_FIELDS = [
9890
+ "create",
9891
+ "isValid",
9892
+ "is0",
9893
+ "neg",
9894
+ "inv",
9895
+ "sqrt",
9896
+ "sqr",
9897
+ "eql",
9898
+ "add",
9899
+ "sub",
9900
+ "mul",
9901
+ "pow",
9902
+ "div",
9903
+ "addN",
9904
+ "subN",
9905
+ "mulN",
9906
+ "sqrN"
9907
+ ];
9908
+ function validateField(field) {
9909
+ const initial = {
9910
+ ORDER: "bigint",
9911
+ BYTES: "number",
9912
+ BITS: "number"
9913
+ };
9914
+ const opts = FIELD_FIELDS.reduce((map, val) => {
9915
+ map[val] = "function";
9916
+ return map;
9917
+ }, initial);
9918
+ validateObject(field, opts);
9919
+ return field;
9920
+ }
9921
+ function FpPow(Fp, num, power) {
9922
+ if (power < _0n2)
9923
+ throw new Error("invalid exponent, negatives unsupported");
9924
+ if (power === _0n2)
9925
+ return Fp.ONE;
9926
+ if (power === _1n2)
9927
+ return num;
9928
+ let p = Fp.ONE;
9929
+ let d = num;
9930
+ while (power > _0n2) {
9931
+ if (power & _1n2)
9932
+ p = Fp.mul(p, d);
9933
+ d = Fp.sqr(d);
9934
+ power >>= _1n2;
9935
+ }
9936
+ return p;
9937
+ }
9938
+ function FpInvertBatch(Fp, nums, passZero = false) {
9939
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
9940
+ const multipliedAcc = nums.reduce((acc, num, i) => {
9941
+ if (Fp.is0(num))
9942
+ return acc;
9943
+ inverted[i] = acc;
9944
+ return Fp.mul(acc, num);
9945
+ }, Fp.ONE);
9946
+ const invertedAcc = Fp.inv(multipliedAcc);
9947
+ nums.reduceRight((acc, num, i) => {
9948
+ if (Fp.is0(num))
9949
+ return acc;
9950
+ inverted[i] = Fp.mul(acc, inverted[i]);
9951
+ return Fp.mul(acc, num);
9952
+ }, invertedAcc);
9953
+ return inverted;
9954
+ }
9955
+ function FpLegendre(Fp, n) {
9956
+ const p1mod2 = (Fp.ORDER - _1n2) / _2n;
9957
+ const powered = Fp.pow(n, p1mod2);
9958
+ const yes = Fp.eql(powered, Fp.ONE);
9959
+ const zero = Fp.eql(powered, Fp.ZERO);
9960
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
9961
+ if (!yes && !zero && !no)
9962
+ throw new Error("invalid Legendre symbol result");
9963
+ return yes ? 1 : zero ? 0 : -1;
9964
+ }
9965
+ function nLength(n, nBitLength) {
9966
+ if (nBitLength !== void 0)
9967
+ anumber(nBitLength);
9968
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
9969
+ const nByteLength = Math.ceil(_nBitLength / 8);
9970
+ return { nBitLength: _nBitLength, nByteLength };
9971
+ }
9972
+ var _Field = class {
9973
+ ORDER;
9974
+ BITS;
9975
+ BYTES;
9976
+ isLE;
9977
+ ZERO = _0n2;
9978
+ ONE = _1n2;
9979
+ _lengths;
9980
+ _sqrt;
9981
+ // cached sqrt
9982
+ _mod;
9983
+ constructor(ORDER, opts = {}) {
9984
+ if (ORDER <= _0n2)
9985
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
9986
+ let _nbitLength = void 0;
9987
+ this.isLE = false;
9988
+ if (opts != null && typeof opts === "object") {
9989
+ if (typeof opts.BITS === "number")
9990
+ _nbitLength = opts.BITS;
9991
+ if (typeof opts.sqrt === "function")
9992
+ this.sqrt = opts.sqrt;
9993
+ if (typeof opts.isLE === "boolean")
9994
+ this.isLE = opts.isLE;
9995
+ if (opts.allowedLengths)
9996
+ this._lengths = opts.allowedLengths?.slice();
9997
+ if (typeof opts.modFromBytes === "boolean")
9998
+ this._mod = opts.modFromBytes;
9999
+ }
10000
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
10001
+ if (nByteLength > 2048)
10002
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
10003
+ this.ORDER = ORDER;
10004
+ this.BITS = nBitLength;
10005
+ this.BYTES = nByteLength;
10006
+ this._sqrt = void 0;
10007
+ Object.preventExtensions(this);
10008
+ }
10009
+ create(num) {
10010
+ return mod(num, this.ORDER);
10011
+ }
10012
+ isValid(num) {
10013
+ if (typeof num !== "bigint")
10014
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
10015
+ return _0n2 <= num && num < this.ORDER;
10016
+ }
10017
+ is0(num) {
10018
+ return num === _0n2;
10019
+ }
10020
+ // is valid and invertible
10021
+ isValidNot0(num) {
10022
+ return !this.is0(num) && this.isValid(num);
10023
+ }
10024
+ isOdd(num) {
10025
+ return (num & _1n2) === _1n2;
10026
+ }
10027
+ neg(num) {
10028
+ return mod(-num, this.ORDER);
10029
+ }
10030
+ eql(lhs, rhs) {
10031
+ return lhs === rhs;
10032
+ }
10033
+ sqr(num) {
10034
+ return mod(num * num, this.ORDER);
10035
+ }
10036
+ add(lhs, rhs) {
10037
+ return mod(lhs + rhs, this.ORDER);
10038
+ }
10039
+ sub(lhs, rhs) {
10040
+ return mod(lhs - rhs, this.ORDER);
10041
+ }
10042
+ mul(lhs, rhs) {
10043
+ return mod(lhs * rhs, this.ORDER);
10044
+ }
10045
+ pow(num, power) {
10046
+ return FpPow(this, num, power);
10047
+ }
10048
+ div(lhs, rhs) {
10049
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
10050
+ }
10051
+ // Same as above, but doesn't normalize
10052
+ sqrN(num) {
10053
+ return num * num;
10054
+ }
10055
+ addN(lhs, rhs) {
10056
+ return lhs + rhs;
10057
+ }
10058
+ subN(lhs, rhs) {
10059
+ return lhs - rhs;
10060
+ }
10061
+ mulN(lhs, rhs) {
10062
+ return lhs * rhs;
10063
+ }
10064
+ inv(num) {
10065
+ return invert(num, this.ORDER);
10066
+ }
10067
+ sqrt(num) {
10068
+ if (!this._sqrt)
10069
+ this._sqrt = FpSqrt(this.ORDER);
10070
+ return this._sqrt(this, num);
10071
+ }
10072
+ toBytes(num) {
10073
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
10074
+ }
10075
+ fromBytes(bytes, skipValidation = false) {
10076
+ abytes(bytes);
10077
+ const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
10078
+ if (allowedLengths) {
10079
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
10080
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
10081
+ }
10082
+ const padded = new Uint8Array(BYTES);
10083
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
10084
+ bytes = padded;
10085
+ }
10086
+ if (bytes.length !== BYTES)
10087
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
10088
+ let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
10089
+ if (modFromBytes)
10090
+ scalar = mod(scalar, ORDER);
10091
+ if (!skipValidation) {
10092
+ if (!this.isValid(scalar))
10093
+ throw new Error("invalid field element: outside of range 0..ORDER");
10094
+ }
10095
+ return scalar;
10096
+ }
10097
+ // TODO: we don't need it here, move out to separate fn
10098
+ invertBatch(lst) {
10099
+ return FpInvertBatch(this, lst);
10100
+ }
10101
+ // We can't move this out because Fp6, Fp12 implement it
10102
+ // and it's unclear what to return in there.
10103
+ cmov(a, b, condition) {
10104
+ return condition ? b : a;
10105
+ }
10106
+ };
10107
+ function Field(ORDER, opts = {}) {
10108
+ return new _Field(ORDER, opts);
10109
+ }
10110
+ function getFieldBytesLength(fieldOrder) {
10111
+ if (typeof fieldOrder !== "bigint")
10112
+ throw new Error("field order must be bigint");
10113
+ const bitLength = fieldOrder.toString(2).length;
10114
+ return Math.ceil(bitLength / 8);
10115
+ }
10116
+ function getMinHashLength(fieldOrder) {
10117
+ const length = getFieldBytesLength(fieldOrder);
10118
+ return length + Math.ceil(length / 2);
10119
+ }
10120
+ function mapHashToField(key, fieldOrder, isLE = false) {
10121
+ abytes(key);
10122
+ const len = key.length;
10123
+ const fieldLen = getFieldBytesLength(fieldOrder);
10124
+ const minLen = getMinHashLength(fieldOrder);
10125
+ if (len < 16 || len < minLen || len > 1024)
10126
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
10127
+ const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
10128
+ const reduced = mod(num, fieldOrder - _1n2) + _1n2;
10129
+ return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
10130
+ }
10131
+
10132
+ // node_modules/@noble/curves/abstract/curve.js
10133
+ var _0n3 = /* @__PURE__ */ BigInt(0);
10134
+ var _1n3 = /* @__PURE__ */ BigInt(1);
10135
+ function negateCt(condition, item) {
10136
+ const neg = item.negate();
10137
+ return condition ? neg : item;
10138
+ }
10139
+ function normalizeZ(c, points) {
10140
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
10141
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
10142
+ }
10143
+ function validateW(W, bits) {
10144
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
10145
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
10146
+ }
10147
+ function calcWOpts(W, scalarBits) {
10148
+ validateW(W, scalarBits);
10149
+ const windows = Math.ceil(scalarBits / W) + 1;
10150
+ const windowSize = 2 ** (W - 1);
10151
+ const maxNumber = 2 ** W;
10152
+ const mask = bitMask(W);
10153
+ const shiftBy = BigInt(W);
10154
+ return { windows, windowSize, mask, maxNumber, shiftBy };
10155
+ }
10156
+ function calcOffsets(n, window, wOpts) {
10157
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
10158
+ let wbits = Number(n & mask);
10159
+ let nextN = n >> shiftBy;
10160
+ if (wbits > windowSize) {
10161
+ wbits -= maxNumber;
10162
+ nextN += _1n3;
10163
+ }
10164
+ const offsetStart = window * windowSize;
10165
+ const offset = offsetStart + Math.abs(wbits) - 1;
10166
+ const isZero = wbits === 0;
10167
+ const isNeg = wbits < 0;
10168
+ const isNegF = window % 2 !== 0;
10169
+ const offsetF = offsetStart;
10170
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
10171
+ }
10172
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
10173
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
10174
+ function getW(P) {
10175
+ return pointWindowSizes.get(P) || 1;
10176
+ }
10177
+ function assert0(n) {
10178
+ if (n !== _0n3)
10179
+ throw new Error("invalid wNAF");
10180
+ }
10181
+ var wNAF = class {
10182
+ BASE;
10183
+ ZERO;
10184
+ Fn;
10185
+ bits;
10186
+ // Parametrized with a given Point class (not individual point)
10187
+ constructor(Point, bits) {
10188
+ this.BASE = Point.BASE;
10189
+ this.ZERO = Point.ZERO;
10190
+ this.Fn = Point.Fn;
10191
+ this.bits = bits;
10192
+ }
10193
+ // non-const time multiplication ladder
10194
+ _unsafeLadder(elm, n, p = this.ZERO) {
10195
+ let d = elm;
10196
+ while (n > _0n3) {
10197
+ if (n & _1n3)
10198
+ p = p.add(d);
10199
+ d = d.double();
10200
+ n >>= _1n3;
10201
+ }
10202
+ return p;
10203
+ }
10204
+ /**
10205
+ * Creates a wNAF precomputation window. Used for caching.
10206
+ * Default window size is set by `utils.precompute()` and is equal to 8.
10207
+ * Number of precomputed points depends on the curve size:
10208
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
10209
+ * - 𝑊 is the window size
10210
+ * - 𝑛 is the bitlength of the curve order.
10211
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
10212
+ * @param point Point instance
10213
+ * @param W window size
10214
+ * @returns precomputed point tables flattened to a single array
10215
+ */
10216
+ precomputeWindow(point, W) {
10217
+ const { windows, windowSize } = calcWOpts(W, this.bits);
10218
+ const points = [];
10219
+ let p = point;
10220
+ let base = p;
10221
+ for (let window = 0; window < windows; window++) {
10222
+ base = p;
10223
+ points.push(base);
10224
+ for (let i = 1; i < windowSize; i++) {
10225
+ base = base.add(p);
10226
+ points.push(base);
10227
+ }
10228
+ p = base.double();
10229
+ }
10230
+ return points;
10231
+ }
10232
+ /**
10233
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
10234
+ * More compact implementation:
10235
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
10236
+ * @returns real and fake (for const-time) points
10237
+ */
10238
+ wNAF(W, precomputes, n) {
10239
+ if (!this.Fn.isValid(n))
10240
+ throw new Error("invalid scalar");
10241
+ let p = this.ZERO;
10242
+ let f = this.BASE;
10243
+ const wo = calcWOpts(W, this.bits);
10244
+ for (let window = 0; window < wo.windows; window++) {
10245
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
10246
+ n = nextN;
10247
+ if (isZero) {
10248
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
10249
+ } else {
10250
+ p = p.add(negateCt(isNeg, precomputes[offset]));
10251
+ }
10252
+ }
10253
+ assert0(n);
10254
+ return { p, f };
10255
+ }
10256
+ /**
10257
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
10258
+ * @param acc accumulator point to add result of multiplication
10259
+ * @returns point
10260
+ */
10261
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
10262
+ const wo = calcWOpts(W, this.bits);
10263
+ for (let window = 0; window < wo.windows; window++) {
10264
+ if (n === _0n3)
10265
+ break;
10266
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
10267
+ n = nextN;
10268
+ if (isZero) {
10269
+ continue;
10270
+ } else {
10271
+ const item = precomputes[offset];
10272
+ acc = acc.add(isNeg ? item.negate() : item);
10273
+ }
10274
+ }
10275
+ assert0(n);
10276
+ return acc;
10277
+ }
10278
+ getPrecomputes(W, point, transform) {
10279
+ let comp = pointPrecomputes.get(point);
10280
+ if (!comp) {
10281
+ comp = this.precomputeWindow(point, W);
10282
+ if (W !== 1) {
10283
+ if (typeof transform === "function")
10284
+ comp = transform(comp);
10285
+ pointPrecomputes.set(point, comp);
10286
+ }
10287
+ }
10288
+ return comp;
10289
+ }
10290
+ cached(point, scalar, transform) {
10291
+ const W = getW(point);
10292
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
10293
+ }
10294
+ unsafe(point, scalar, transform, prev) {
10295
+ const W = getW(point);
10296
+ if (W === 1)
10297
+ return this._unsafeLadder(point, scalar, prev);
10298
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
10299
+ }
10300
+ // We calculate precomputes for elliptic curve point multiplication
10301
+ // using windowed method. This specifies window size and
10302
+ // stores precomputed values. Usually only base point would be precomputed.
10303
+ createCache(P, W) {
10304
+ validateW(W, this.bits);
10305
+ pointWindowSizes.set(P, W);
10306
+ pointPrecomputes.delete(P);
10307
+ }
10308
+ hasCache(elm) {
10309
+ return getW(elm) !== 1;
10310
+ }
10311
+ };
10312
+ function mulEndoUnsafe(Point, point, k1, k2) {
10313
+ let acc = point;
10314
+ let p1 = Point.ZERO;
10315
+ let p2 = Point.ZERO;
10316
+ while (k1 > _0n3 || k2 > _0n3) {
10317
+ if (k1 & _1n3)
10318
+ p1 = p1.add(acc);
10319
+ if (k2 & _1n3)
10320
+ p2 = p2.add(acc);
10321
+ acc = acc.double();
10322
+ k1 >>= _1n3;
10323
+ k2 >>= _1n3;
10324
+ }
10325
+ return { p1, p2 };
10326
+ }
10327
+ function createField(order, field, isLE) {
10328
+ if (field) {
10329
+ if (field.ORDER !== order)
10330
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
10331
+ validateField(field);
10332
+ return field;
10333
+ } else {
10334
+ return Field(order, { isLE });
10335
+ }
10336
+ }
10337
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
10338
+ if (FpFnLE === void 0)
10339
+ FpFnLE = type === "edwards";
10340
+ if (!CURVE || typeof CURVE !== "object")
10341
+ throw new Error(`expected valid ${type} CURVE object`);
10342
+ for (const p of ["p", "n", "h"]) {
10343
+ const val = CURVE[p];
10344
+ if (!(typeof val === "bigint" && val > _0n3))
10345
+ throw new Error(`CURVE.${p} must be positive bigint`);
10346
+ }
10347
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
10348
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
10349
+ const _b = type === "weierstrass" ? "b" : "d";
10350
+ const params = ["Gx", "Gy", "a", _b];
10351
+ for (const p of params) {
10352
+ if (!Fp.isValid(CURVE[p]))
10353
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
10354
+ }
10355
+ CURVE = Object.freeze(Object.assign({}, CURVE));
10356
+ return { CURVE, Fp, Fn };
10357
+ }
10358
+ function createKeygen(randomSecretKey, getPublicKey2) {
10359
+ return function keygen(seed) {
10360
+ const secretKey = randomSecretKey(seed);
10361
+ return { secretKey, publicKey: getPublicKey2(secretKey) };
10362
+ };
10363
+ }
10364
+
10365
+ // node_modules/@noble/hashes/hmac.js
10366
+ var _HMAC = class {
10367
+ oHash;
10368
+ iHash;
10369
+ blockLen;
10370
+ outputLen;
10371
+ finished = false;
10372
+ destroyed = false;
10373
+ constructor(hash, key) {
10374
+ ahash(hash);
10375
+ abytes(key, void 0, "key");
10376
+ this.iHash = hash.create();
10377
+ if (typeof this.iHash.update !== "function")
10378
+ throw new Error("Expected instance of class which extends utils.Hash");
10379
+ this.blockLen = this.iHash.blockLen;
10380
+ this.outputLen = this.iHash.outputLen;
10381
+ const blockLen = this.blockLen;
10382
+ const pad = new Uint8Array(blockLen);
10383
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
10384
+ for (let i = 0; i < pad.length; i++)
10385
+ pad[i] ^= 54;
10386
+ this.iHash.update(pad);
10387
+ this.oHash = hash.create();
10388
+ for (let i = 0; i < pad.length; i++)
10389
+ pad[i] ^= 54 ^ 92;
10390
+ this.oHash.update(pad);
10391
+ clean(pad);
10392
+ }
10393
+ update(buf) {
10394
+ aexists(this);
10395
+ this.iHash.update(buf);
10396
+ return this;
10397
+ }
10398
+ digestInto(out) {
10399
+ aexists(this);
10400
+ abytes(out, this.outputLen, "output");
10401
+ this.finished = true;
10402
+ this.iHash.digestInto(out);
10403
+ this.oHash.update(out);
10404
+ this.oHash.digestInto(out);
10405
+ this.destroy();
10406
+ }
10407
+ digest() {
10408
+ const out = new Uint8Array(this.oHash.outputLen);
10409
+ this.digestInto(out);
10410
+ return out;
10411
+ }
10412
+ _cloneInto(to) {
10413
+ to ||= Object.create(Object.getPrototypeOf(this), {});
10414
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
10415
+ to = to;
10416
+ to.finished = finished;
10417
+ to.destroyed = destroyed;
10418
+ to.blockLen = blockLen;
10419
+ to.outputLen = outputLen;
10420
+ to.oHash = oHash._cloneInto(to.oHash);
10421
+ to.iHash = iHash._cloneInto(to.iHash);
10422
+ return to;
10423
+ }
10424
+ clone() {
10425
+ return this._cloneInto();
10426
+ }
10427
+ destroy() {
10428
+ this.destroyed = true;
10429
+ this.oHash.destroy();
10430
+ this.iHash.destroy();
10431
+ }
10432
+ };
10433
+ var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
10434
+ hmac.create = (hash, key) => new _HMAC(hash, key);
10435
+
10436
+ // node_modules/@noble/curves/abstract/weierstrass.js
10437
+ var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
10438
+ function _splitEndoScalar(k, basis, n) {
10439
+ const [[a1, b1], [a2, b2]] = basis;
10440
+ const c1 = divNearest(b2 * k, n);
10441
+ const c2 = divNearest(-b1 * k, n);
10442
+ let k1 = k - c1 * a1 - c2 * a2;
10443
+ let k2 = -c1 * b1 - c2 * b2;
10444
+ const k1neg = k1 < _0n4;
10445
+ const k2neg = k2 < _0n4;
10446
+ if (k1neg)
10447
+ k1 = -k1;
10448
+ if (k2neg)
10449
+ k2 = -k2;
10450
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
10451
+ if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
10452
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
10453
+ }
10454
+ return { k1neg, k1, k2neg, k2 };
10455
+ }
10456
+ function validateSigFormat(format) {
10457
+ if (!["compact", "recovered", "der"].includes(format))
10458
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
10459
+ return format;
10460
+ }
10461
+ function validateSigOpts(opts, def) {
10462
+ const optsn = {};
10463
+ for (let optName of Object.keys(def)) {
10464
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
10465
+ }
10466
+ abool(optsn.lowS, "lowS");
10467
+ abool(optsn.prehash, "prehash");
10468
+ if (optsn.format !== void 0)
10469
+ validateSigFormat(optsn.format);
10470
+ return optsn;
10471
+ }
10472
+ var DERErr = class extends Error {
10473
+ constructor(m = "") {
10474
+ super(m);
10475
+ }
10476
+ };
10477
+ var DER = {
10478
+ // asn.1 DER encoding utils
10479
+ Err: DERErr,
10480
+ // Basic building block is TLV (Tag-Length-Value)
10481
+ _tlv: {
10482
+ encode: (tag, data) => {
10483
+ const { Err: E } = DER;
10484
+ if (tag < 0 || tag > 256)
10485
+ throw new E("tlv.encode: wrong tag");
10486
+ if (data.length & 1)
10487
+ throw new E("tlv.encode: unpadded data");
10488
+ const dataLen = data.length / 2;
10489
+ const len = numberToHexUnpadded(dataLen);
10490
+ if (len.length / 2 & 128)
10491
+ throw new E("tlv.encode: long form length too big");
10492
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
10493
+ const t = numberToHexUnpadded(tag);
10494
+ return t + lenLen + len + data;
10495
+ },
10496
+ // v - value, l - left bytes (unparsed)
10497
+ decode(tag, data) {
10498
+ const { Err: E } = DER;
10499
+ let pos = 0;
10500
+ if (tag < 0 || tag > 256)
10501
+ throw new E("tlv.encode: wrong tag");
10502
+ if (data.length < 2 || data[pos++] !== tag)
10503
+ throw new E("tlv.decode: wrong tlv");
10504
+ const first = data[pos++];
10505
+ const isLong = !!(first & 128);
10506
+ let length = 0;
10507
+ if (!isLong)
10508
+ length = first;
10509
+ else {
10510
+ const lenLen = first & 127;
10511
+ if (!lenLen)
10512
+ throw new E("tlv.decode(long): indefinite length not supported");
10513
+ if (lenLen > 4)
10514
+ throw new E("tlv.decode(long): byte length is too big");
10515
+ const lengthBytes = data.subarray(pos, pos + lenLen);
10516
+ if (lengthBytes.length !== lenLen)
10517
+ throw new E("tlv.decode: length bytes not complete");
10518
+ if (lengthBytes[0] === 0)
10519
+ throw new E("tlv.decode(long): zero leftmost byte");
10520
+ for (const b of lengthBytes)
10521
+ length = length << 8 | b;
10522
+ pos += lenLen;
10523
+ if (length < 128)
10524
+ throw new E("tlv.decode(long): not minimal encoding");
10525
+ }
10526
+ const v = data.subarray(pos, pos + length);
10527
+ if (v.length !== length)
10528
+ throw new E("tlv.decode: wrong value length");
10529
+ return { v, l: data.subarray(pos + length) };
10530
+ }
10531
+ },
10532
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
10533
+ // since we always use positive integers here. It must always be empty:
10534
+ // - add zero byte if exists
10535
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
10536
+ _int: {
10537
+ encode(num) {
10538
+ const { Err: E } = DER;
10539
+ if (num < _0n4)
10540
+ throw new E("integer: negative integers are not allowed");
10541
+ let hex = numberToHexUnpadded(num);
10542
+ if (Number.parseInt(hex[0], 16) & 8)
10543
+ hex = "00" + hex;
10544
+ if (hex.length & 1)
10545
+ throw new E("unexpected DER parsing assertion: unpadded hex");
10546
+ return hex;
10547
+ },
10548
+ decode(data) {
10549
+ const { Err: E } = DER;
10550
+ if (data[0] & 128)
10551
+ throw new E("invalid signature integer: negative");
10552
+ if (data[0] === 0 && !(data[1] & 128))
10553
+ throw new E("invalid signature integer: unnecessary leading zero");
10554
+ return bytesToNumberBE(data);
10555
+ }
10556
+ },
10557
+ toSig(bytes) {
10558
+ const { Err: E, _int: int, _tlv: tlv } = DER;
10559
+ const data = abytes(bytes, void 0, "signature");
10560
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
10561
+ if (seqLeftBytes.length)
10562
+ throw new E("invalid signature: left bytes after parsing");
10563
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
10564
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
10565
+ if (sLeftBytes.length)
10566
+ throw new E("invalid signature: left bytes after parsing");
10567
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
10568
+ },
10569
+ hexFromSig(sig) {
10570
+ const { _tlv: tlv, _int: int } = DER;
10571
+ const rs = tlv.encode(2, int.encode(sig.r));
10572
+ const ss = tlv.encode(2, int.encode(sig.s));
10573
+ const seq = rs + ss;
10574
+ return tlv.encode(48, seq);
10575
+ }
10576
+ };
10577
+ var _0n4 = BigInt(0);
10578
+ var _1n4 = BigInt(1);
10579
+ var _2n2 = BigInt(2);
10580
+ var _3n2 = BigInt(3);
10581
+ var _4n2 = BigInt(4);
10582
+ function weierstrass(params, extraOpts = {}) {
10583
+ const validated = createCurveFields("weierstrass", params, extraOpts);
10584
+ const { Fp, Fn } = validated;
10585
+ let CURVE = validated.CURVE;
10586
+ const { h: cofactor, n: CURVE_ORDER2 } = CURVE;
10587
+ validateObject(extraOpts, {}, {
10588
+ allowInfinityPoint: "boolean",
10589
+ clearCofactor: "function",
10590
+ isTorsionFree: "function",
10591
+ fromBytes: "function",
10592
+ toBytes: "function",
10593
+ endo: "object"
10594
+ });
10595
+ const { endo } = extraOpts;
10596
+ if (endo) {
10597
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
10598
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
10599
+ }
10600
+ }
10601
+ const lengths = getWLengths(Fp, Fn);
10602
+ function assertCompressionIsSupported() {
10603
+ if (!Fp.isOdd)
10604
+ throw new Error("compression is not supported: Field does not have .isOdd()");
10605
+ }
10606
+ function pointToBytes(_c, point, isCompressed) {
10607
+ const { x, y } = point.toAffine();
10608
+ const bx = Fp.toBytes(x);
10609
+ abool(isCompressed, "isCompressed");
10610
+ if (isCompressed) {
10611
+ assertCompressionIsSupported();
10612
+ const hasEvenY = !Fp.isOdd(y);
10613
+ return concatBytes(pprefix(hasEvenY), bx);
10614
+ } else {
10615
+ return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
10616
+ }
10617
+ }
10618
+ function pointFromBytes(bytes) {
10619
+ abytes(bytes, void 0, "Point");
10620
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
10621
+ const length = bytes.length;
10622
+ const head = bytes[0];
10623
+ const tail = bytes.subarray(1);
10624
+ if (length === comp && (head === 2 || head === 3)) {
10625
+ const x = Fp.fromBytes(tail);
10626
+ if (!Fp.isValid(x))
10627
+ throw new Error("bad point: is not on curve, wrong x");
10628
+ const y2 = weierstrassEquation(x);
10629
+ let y;
10630
+ try {
10631
+ y = Fp.sqrt(y2);
10632
+ } catch (sqrtError) {
10633
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
10634
+ throw new Error("bad point: is not on curve, sqrt error" + err);
10635
+ }
10636
+ assertCompressionIsSupported();
10637
+ const evenY = Fp.isOdd(y);
10638
+ const evenH = (head & 1) === 1;
10639
+ if (evenH !== evenY)
10640
+ y = Fp.neg(y);
10641
+ return { x, y };
10642
+ } else if (length === uncomp && head === 4) {
10643
+ const L = Fp.BYTES;
10644
+ const x = Fp.fromBytes(tail.subarray(0, L));
10645
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
10646
+ if (!isValidXY(x, y))
10647
+ throw new Error("bad point: is not on curve");
10648
+ return { x, y };
10649
+ } else {
10650
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
10651
+ }
10652
+ }
10653
+ const encodePoint = extraOpts.toBytes || pointToBytes;
10654
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
10655
+ function weierstrassEquation(x) {
10656
+ const x2 = Fp.sqr(x);
10657
+ const x3 = Fp.mul(x2, x);
10658
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
10659
+ }
10660
+ function isValidXY(x, y) {
10661
+ const left = Fp.sqr(y);
10662
+ const right = weierstrassEquation(x);
10663
+ return Fp.eql(left, right);
10664
+ }
10665
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
10666
+ throw new Error("bad curve params: generator point");
10667
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
10668
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
10669
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
10670
+ throw new Error("bad curve params: a or b");
10671
+ function acoord(title, n, banZero = false) {
10672
+ if (!Fp.isValid(n) || banZero && Fp.is0(n))
10673
+ throw new Error(`bad point coordinate ${title}`);
10674
+ return n;
10675
+ }
10676
+ function aprjpoint(other) {
10677
+ if (!(other instanceof Point))
10678
+ throw new Error("Weierstrass Point expected");
10679
+ }
10680
+ function splitEndoScalarN(k) {
10681
+ if (!endo || !endo.basises)
10682
+ throw new Error("no endo");
10683
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
10684
+ }
10685
+ const toAffineMemo = memoized((p, iz) => {
10686
+ const { X, Y, Z } = p;
10687
+ if (Fp.eql(Z, Fp.ONE))
10688
+ return { x: X, y: Y };
10689
+ const is0 = p.is0();
10690
+ if (iz == null)
10691
+ iz = is0 ? Fp.ONE : Fp.inv(Z);
10692
+ const x = Fp.mul(X, iz);
10693
+ const y = Fp.mul(Y, iz);
10694
+ const zz = Fp.mul(Z, iz);
10695
+ if (is0)
10696
+ return { x: Fp.ZERO, y: Fp.ZERO };
10697
+ if (!Fp.eql(zz, Fp.ONE))
10698
+ throw new Error("invZ was invalid");
10699
+ return { x, y };
10700
+ });
10701
+ const assertValidMemo = memoized((p) => {
10702
+ if (p.is0()) {
10703
+ if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
10704
+ return;
10705
+ throw new Error("bad point: ZERO");
10706
+ }
10707
+ const { x, y } = p.toAffine();
10708
+ if (!Fp.isValid(x) || !Fp.isValid(y))
10709
+ throw new Error("bad point: x or y not field elements");
10710
+ if (!isValidXY(x, y))
10711
+ throw new Error("bad point: equation left != right");
10712
+ if (!p.isTorsionFree())
10713
+ throw new Error("bad point: not in prime-order subgroup");
10714
+ return true;
10715
+ });
10716
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
10717
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
10718
+ k1p = negateCt(k1neg, k1p);
10719
+ k2p = negateCt(k2neg, k2p);
10720
+ return k1p.add(k2p);
10721
+ }
10722
+ class Point {
10723
+ // base / generator point
10724
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
10725
+ // zero / infinity / identity point
10726
+ static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
10727
+ // 0, 1, 0
10728
+ // math field
10729
+ static Fp = Fp;
10730
+ // scalar field
10731
+ static Fn = Fn;
10732
+ X;
10733
+ Y;
10734
+ Z;
10735
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
10736
+ constructor(X, Y, Z) {
10737
+ this.X = acoord("x", X);
10738
+ this.Y = acoord("y", Y, true);
10739
+ this.Z = acoord("z", Z);
10740
+ Object.freeze(this);
10741
+ }
10742
+ static CURVE() {
10743
+ return CURVE;
10744
+ }
10745
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
10746
+ static fromAffine(p) {
10747
+ const { x, y } = p || {};
10748
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
10749
+ throw new Error("invalid affine point");
10750
+ if (p instanceof Point)
10751
+ throw new Error("projective point not allowed");
10752
+ if (Fp.is0(x) && Fp.is0(y))
10753
+ return Point.ZERO;
10754
+ return new Point(x, y, Fp.ONE);
10755
+ }
10756
+ static fromBytes(bytes) {
10757
+ const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
10758
+ P.assertValidity();
10759
+ return P;
10760
+ }
10761
+ static fromHex(hex) {
10762
+ return Point.fromBytes(hexToBytes2(hex));
10763
+ }
10764
+ get x() {
10765
+ return this.toAffine().x;
10766
+ }
10767
+ get y() {
10768
+ return this.toAffine().y;
10769
+ }
10770
+ /**
10771
+ *
10772
+ * @param windowSize
10773
+ * @param isLazy true will defer table computation until the first multiplication
10774
+ * @returns
10775
+ */
10776
+ precompute(windowSize = 8, isLazy = true) {
10777
+ wnaf.createCache(this, windowSize);
10778
+ if (!isLazy)
10779
+ this.multiply(_3n2);
10780
+ return this;
10781
+ }
10782
+ // TODO: return `this`
10783
+ /** A point on curve is valid if it conforms to equation. */
10784
+ assertValidity() {
10785
+ assertValidMemo(this);
10786
+ }
10787
+ hasEvenY() {
10788
+ const { y } = this.toAffine();
10789
+ if (!Fp.isOdd)
10790
+ throw new Error("Field doesn't support isOdd");
10791
+ return !Fp.isOdd(y);
10792
+ }
10793
+ /** Compare one point to another. */
10794
+ equals(other) {
10795
+ aprjpoint(other);
10796
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10797
+ const { X: X2, Y: Y2, Z: Z2 } = other;
10798
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
10799
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
10800
+ return U1 && U2;
10801
+ }
10802
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
10803
+ negate() {
10804
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
10805
+ }
10806
+ // Renes-Costello-Batina exception-free doubling formula.
10807
+ // There is 30% faster Jacobian formula, but it is not complete.
10808
+ // https://eprint.iacr.org/2015/1060, algorithm 3
10809
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
10810
+ double() {
10811
+ const { a, b } = CURVE;
10812
+ const b3 = Fp.mul(b, _3n2);
10813
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10814
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
10815
+ let t0 = Fp.mul(X1, X1);
10816
+ let t1 = Fp.mul(Y1, Y1);
10817
+ let t2 = Fp.mul(Z1, Z1);
10818
+ let t3 = Fp.mul(X1, Y1);
10819
+ t3 = Fp.add(t3, t3);
10820
+ Z3 = Fp.mul(X1, Z1);
10821
+ Z3 = Fp.add(Z3, Z3);
10822
+ X3 = Fp.mul(a, Z3);
10823
+ Y3 = Fp.mul(b3, t2);
10824
+ Y3 = Fp.add(X3, Y3);
10825
+ X3 = Fp.sub(t1, Y3);
10826
+ Y3 = Fp.add(t1, Y3);
10827
+ Y3 = Fp.mul(X3, Y3);
10828
+ X3 = Fp.mul(t3, X3);
10829
+ Z3 = Fp.mul(b3, Z3);
10830
+ t2 = Fp.mul(a, t2);
10831
+ t3 = Fp.sub(t0, t2);
10832
+ t3 = Fp.mul(a, t3);
10833
+ t3 = Fp.add(t3, Z3);
10834
+ Z3 = Fp.add(t0, t0);
10835
+ t0 = Fp.add(Z3, t0);
10836
+ t0 = Fp.add(t0, t2);
10837
+ t0 = Fp.mul(t0, t3);
10838
+ Y3 = Fp.add(Y3, t0);
10839
+ t2 = Fp.mul(Y1, Z1);
10840
+ t2 = Fp.add(t2, t2);
10841
+ t0 = Fp.mul(t2, t3);
10842
+ X3 = Fp.sub(X3, t0);
10843
+ Z3 = Fp.mul(t2, t1);
10844
+ Z3 = Fp.add(Z3, Z3);
10845
+ Z3 = Fp.add(Z3, Z3);
10846
+ return new Point(X3, Y3, Z3);
10847
+ }
10848
+ // Renes-Costello-Batina exception-free addition formula.
10849
+ // There is 30% faster Jacobian formula, but it is not complete.
10850
+ // https://eprint.iacr.org/2015/1060, algorithm 1
10851
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
10852
+ add(other) {
10853
+ aprjpoint(other);
10854
+ const { X: X1, Y: Y1, Z: Z1 } = this;
10855
+ const { X: X2, Y: Y2, Z: Z2 } = other;
10856
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
10857
+ const a = CURVE.a;
10858
+ const b3 = Fp.mul(CURVE.b, _3n2);
10859
+ let t0 = Fp.mul(X1, X2);
10860
+ let t1 = Fp.mul(Y1, Y2);
10861
+ let t2 = Fp.mul(Z1, Z2);
10862
+ let t3 = Fp.add(X1, Y1);
10863
+ let t4 = Fp.add(X2, Y2);
10864
+ t3 = Fp.mul(t3, t4);
10865
+ t4 = Fp.add(t0, t1);
10866
+ t3 = Fp.sub(t3, t4);
10867
+ t4 = Fp.add(X1, Z1);
10868
+ let t5 = Fp.add(X2, Z2);
10869
+ t4 = Fp.mul(t4, t5);
10870
+ t5 = Fp.add(t0, t2);
10871
+ t4 = Fp.sub(t4, t5);
10872
+ t5 = Fp.add(Y1, Z1);
10873
+ X3 = Fp.add(Y2, Z2);
10874
+ t5 = Fp.mul(t5, X3);
10875
+ X3 = Fp.add(t1, t2);
10876
+ t5 = Fp.sub(t5, X3);
10877
+ Z3 = Fp.mul(a, t4);
10878
+ X3 = Fp.mul(b3, t2);
10879
+ Z3 = Fp.add(X3, Z3);
10880
+ X3 = Fp.sub(t1, Z3);
10881
+ Z3 = Fp.add(t1, Z3);
10882
+ Y3 = Fp.mul(X3, Z3);
10883
+ t1 = Fp.add(t0, t0);
10884
+ t1 = Fp.add(t1, t0);
10885
+ t2 = Fp.mul(a, t2);
10886
+ t4 = Fp.mul(b3, t4);
10887
+ t1 = Fp.add(t1, t2);
10888
+ t2 = Fp.sub(t0, t2);
10889
+ t2 = Fp.mul(a, t2);
10890
+ t4 = Fp.add(t4, t2);
10891
+ t0 = Fp.mul(t1, t4);
10892
+ Y3 = Fp.add(Y3, t0);
10893
+ t0 = Fp.mul(t5, t4);
10894
+ X3 = Fp.mul(t3, X3);
10895
+ X3 = Fp.sub(X3, t0);
10896
+ t0 = Fp.mul(t3, t1);
10897
+ Z3 = Fp.mul(t5, Z3);
10898
+ Z3 = Fp.add(Z3, t0);
10899
+ return new Point(X3, Y3, Z3);
10900
+ }
10901
+ subtract(other) {
10902
+ return this.add(other.negate());
10903
+ }
10904
+ is0() {
10905
+ return this.equals(Point.ZERO);
10906
+ }
10907
+ /**
10908
+ * Constant time multiplication.
10909
+ * Uses wNAF method. Windowed method may be 10% faster,
10910
+ * but takes 2x longer to generate and consumes 2x memory.
10911
+ * Uses precomputes when available.
10912
+ * Uses endomorphism for Koblitz curves.
10913
+ * @param scalar by which the point would be multiplied
10914
+ * @returns New point
10915
+ */
10916
+ multiply(scalar) {
10917
+ const { endo: endo2 } = extraOpts;
10918
+ if (!Fn.isValidNot0(scalar))
10919
+ throw new Error("invalid scalar: out of range");
10920
+ let point, fake;
10921
+ const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
10922
+ if (endo2) {
10923
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
10924
+ const { p: k1p, f: k1f } = mul(k1);
10925
+ const { p: k2p, f: k2f } = mul(k2);
10926
+ fake = k1f.add(k2f);
10927
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
10928
+ } else {
10929
+ const { p, f } = mul(scalar);
10930
+ point = p;
10931
+ fake = f;
10932
+ }
10933
+ return normalizeZ(Point, [point, fake])[0];
10934
+ }
10935
+ /**
10936
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
10937
+ * It's faster, but should only be used when you don't care about
10938
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
10939
+ */
10940
+ multiplyUnsafe(sc) {
10941
+ const { endo: endo2 } = extraOpts;
10942
+ const p = this;
10943
+ if (!Fn.isValid(sc))
10944
+ throw new Error("invalid scalar: out of range");
10945
+ if (sc === _0n4 || p.is0())
10946
+ return Point.ZERO;
10947
+ if (sc === _1n4)
10948
+ return p;
10949
+ if (wnaf.hasCache(this))
10950
+ return this.multiply(sc);
10951
+ if (endo2) {
10952
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
10953
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
10954
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
10955
+ } else {
10956
+ return wnaf.unsafe(p, sc);
10957
+ }
10958
+ }
10959
+ /**
10960
+ * Converts Projective point to affine (x, y) coordinates.
10961
+ * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
10962
+ */
10963
+ toAffine(invertedZ) {
10964
+ return toAffineMemo(this, invertedZ);
10965
+ }
10966
+ /**
10967
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
10968
+ * Always torsion-free for cofactor=1 curves.
10969
+ */
10970
+ isTorsionFree() {
10971
+ const { isTorsionFree } = extraOpts;
10972
+ if (cofactor === _1n4)
10973
+ return true;
10974
+ if (isTorsionFree)
10975
+ return isTorsionFree(Point, this);
10976
+ return wnaf.unsafe(this, CURVE_ORDER2).is0();
10977
+ }
10978
+ clearCofactor() {
10979
+ const { clearCofactor } = extraOpts;
10980
+ if (cofactor === _1n4)
10981
+ return this;
10982
+ if (clearCofactor)
10983
+ return clearCofactor(Point, this);
10984
+ return this.multiplyUnsafe(cofactor);
10985
+ }
10986
+ isSmallOrder() {
10987
+ return this.multiplyUnsafe(cofactor).is0();
10988
+ }
10989
+ toBytes(isCompressed = true) {
10990
+ abool(isCompressed, "isCompressed");
10991
+ this.assertValidity();
10992
+ return encodePoint(Point, this, isCompressed);
10993
+ }
10994
+ toHex(isCompressed = true) {
10995
+ return bytesToHex4(this.toBytes(isCompressed));
10996
+ }
10997
+ toString() {
10998
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
10999
+ }
11000
+ }
11001
+ const bits = Fn.BITS;
11002
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
11003
+ Point.BASE.precompute(8);
11004
+ return Point;
11005
+ }
11006
+ function pprefix(hasEvenY) {
11007
+ return Uint8Array.of(hasEvenY ? 2 : 3);
11008
+ }
11009
+ function getWLengths(Fp, Fn) {
11010
+ return {
11011
+ secretKey: Fn.BYTES,
11012
+ publicKey: 1 + Fp.BYTES,
11013
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
11014
+ publicKeyHasPrefix: true,
11015
+ signature: 2 * Fn.BYTES
11016
+ };
11017
+ }
11018
+ function ecdh(Point, ecdhOpts = {}) {
11019
+ const { Fn } = Point;
11020
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
11021
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
11022
+ function isValidSecretKey(secretKey) {
11023
+ try {
11024
+ const num = Fn.fromBytes(secretKey);
11025
+ return Fn.isValidNot0(num);
11026
+ } catch (error) {
11027
+ return false;
11028
+ }
11029
+ }
11030
+ function isValidPublicKey(publicKey, isCompressed) {
11031
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
11032
+ try {
11033
+ const l = publicKey.length;
11034
+ if (isCompressed === true && l !== comp)
11035
+ return false;
11036
+ if (isCompressed === false && l !== publicKeyUncompressed)
11037
+ return false;
11038
+ return !!Point.fromBytes(publicKey);
11039
+ } catch (error) {
11040
+ return false;
11041
+ }
11042
+ }
11043
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
11044
+ return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
11045
+ }
11046
+ function getPublicKey2(secretKey, isCompressed = true) {
11047
+ return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
11048
+ }
11049
+ function isProbPub(item) {
11050
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
11051
+ if (!isBytes(item))
11052
+ return void 0;
11053
+ if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
11054
+ return void 0;
11055
+ const l = abytes(item, void 0, "key").length;
11056
+ return l === publicKey || l === publicKeyUncompressed;
11057
+ }
11058
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
11059
+ if (isProbPub(secretKeyA) === true)
11060
+ throw new Error("first arg must be private key");
11061
+ if (isProbPub(publicKeyB) === false)
11062
+ throw new Error("second arg must be public key");
11063
+ const s = Fn.fromBytes(secretKeyA);
11064
+ const b = Point.fromBytes(publicKeyB);
11065
+ return b.multiply(s).toBytes(isCompressed);
11066
+ }
11067
+ const utils = {
11068
+ isValidSecretKey,
11069
+ isValidPublicKey,
11070
+ randomSecretKey
11071
+ };
11072
+ const keygen = createKeygen(randomSecretKey, getPublicKey2);
11073
+ return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
11074
+ }
11075
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
11076
+ ahash(hash);
11077
+ validateObject(ecdsaOpts, {}, {
11078
+ hmac: "function",
11079
+ lowS: "boolean",
11080
+ randomBytes: "function",
11081
+ bits2int: "function",
11082
+ bits2int_modN: "function"
11083
+ });
11084
+ ecdsaOpts = Object.assign({}, ecdsaOpts);
11085
+ const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
11086
+ const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
11087
+ const { Fp, Fn } = Point;
11088
+ const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn;
11089
+ const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
11090
+ const defaultSigOpts = {
11091
+ prehash: true,
11092
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
11093
+ format: "compact",
11094
+ extraEntropy: false
11095
+ };
11096
+ const hasLargeCofactor = CURVE_ORDER2 * _2n2 < Fp.ORDER;
11097
+ function isBiggerThanHalfOrder(number) {
11098
+ const HALF = CURVE_ORDER2 >> _1n4;
11099
+ return number > HALF;
11100
+ }
11101
+ function validateRS(title, num) {
11102
+ if (!Fn.isValidNot0(num))
11103
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
11104
+ return num;
11105
+ }
11106
+ function assertSmallCofactor() {
11107
+ if (hasLargeCofactor)
11108
+ throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
11109
+ }
11110
+ function validateSigLength(bytes, format) {
11111
+ validateSigFormat(format);
11112
+ const size = lengths.signature;
11113
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
11114
+ return abytes(bytes, sizer);
11115
+ }
11116
+ class Signature {
11117
+ r;
11118
+ s;
11119
+ recovery;
11120
+ constructor(r, s, recovery) {
11121
+ this.r = validateRS("r", r);
11122
+ this.s = validateRS("s", s);
11123
+ if (recovery != null) {
11124
+ assertSmallCofactor();
11125
+ if (![0, 1, 2, 3].includes(recovery))
11126
+ throw new Error("invalid recovery id");
11127
+ this.recovery = recovery;
11128
+ }
11129
+ Object.freeze(this);
11130
+ }
11131
+ static fromBytes(bytes, format = defaultSigOpts.format) {
11132
+ validateSigLength(bytes, format);
11133
+ let recid;
11134
+ if (format === "der") {
11135
+ const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
11136
+ return new Signature(r2, s2);
11137
+ }
11138
+ if (format === "recovered") {
11139
+ recid = bytes[0];
11140
+ format = "compact";
11141
+ bytes = bytes.subarray(1);
11142
+ }
11143
+ const L = lengths.signature / 2;
11144
+ const r = bytes.subarray(0, L);
11145
+ const s = bytes.subarray(L, L * 2);
11146
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
11147
+ }
11148
+ static fromHex(hex, format) {
11149
+ return this.fromBytes(hexToBytes2(hex), format);
11150
+ }
11151
+ assertRecovery() {
11152
+ const { recovery } = this;
11153
+ if (recovery == null)
11154
+ throw new Error("invalid recovery id: must be present");
11155
+ return recovery;
11156
+ }
11157
+ addRecoveryBit(recovery) {
11158
+ return new Signature(this.r, this.s, recovery);
11159
+ }
11160
+ recoverPublicKey(messageHash) {
11161
+ const { r, s } = this;
11162
+ const recovery = this.assertRecovery();
11163
+ const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER2 : r;
11164
+ if (!Fp.isValid(radj))
11165
+ throw new Error("invalid recovery id: sig.r+curve.n != R.x");
11166
+ const x = Fp.toBytes(radj);
11167
+ const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
11168
+ const ir = Fn.inv(radj);
11169
+ const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
11170
+ const u1 = Fn.create(-h * ir);
11171
+ const u2 = Fn.create(s * ir);
11172
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
11173
+ if (Q.is0())
11174
+ throw new Error("invalid recovery: point at infinify");
11175
+ Q.assertValidity();
11176
+ return Q;
11177
+ }
11178
+ // Signatures should be low-s, to prevent malleability.
11179
+ hasHighS() {
11180
+ return isBiggerThanHalfOrder(this.s);
11181
+ }
11182
+ toBytes(format = defaultSigOpts.format) {
11183
+ validateSigFormat(format);
11184
+ if (format === "der")
11185
+ return hexToBytes2(DER.hexFromSig(this));
11186
+ const { r, s } = this;
11187
+ const rb = Fn.toBytes(r);
11188
+ const sb = Fn.toBytes(s);
11189
+ if (format === "recovered") {
11190
+ assertSmallCofactor();
11191
+ return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
11192
+ }
11193
+ return concatBytes(rb, sb);
11194
+ }
11195
+ toHex(format) {
11196
+ return bytesToHex4(this.toBytes(format));
11197
+ }
11198
+ }
11199
+ const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
11200
+ if (bytes.length > 8192)
11201
+ throw new Error("input is too large");
11202
+ const num = bytesToNumberBE(bytes);
11203
+ const delta = bytes.length * 8 - fnBits;
11204
+ return delta > 0 ? num >> BigInt(delta) : num;
11205
+ };
11206
+ const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
11207
+ return Fn.create(bits2int(bytes));
11208
+ };
11209
+ const ORDER_MASK = bitMask(fnBits);
11210
+ function int2octets(num) {
11211
+ aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
11212
+ return Fn.toBytes(num);
11213
+ }
11214
+ function validateMsgAndHash(message, prehash) {
11215
+ abytes(message, void 0, "message");
11216
+ return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
11217
+ }
11218
+ function prepSig(message, secretKey, opts) {
11219
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
11220
+ message = validateMsgAndHash(message, prehash);
11221
+ const h1int = bits2int_modN(message);
11222
+ const d = Fn.fromBytes(secretKey);
11223
+ if (!Fn.isValidNot0(d))
11224
+ throw new Error("invalid private key");
11225
+ const seedArgs = [int2octets(d), int2octets(h1int)];
11226
+ if (extraEntropy != null && extraEntropy !== false) {
11227
+ const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
11228
+ seedArgs.push(abytes(e, void 0, "extraEntropy"));
11229
+ }
11230
+ const seed = concatBytes(...seedArgs);
11231
+ const m = h1int;
11232
+ function k2sig(kBytes) {
11233
+ const k = bits2int(kBytes);
11234
+ if (!Fn.isValidNot0(k))
11235
+ return;
11236
+ const ik = Fn.inv(k);
11237
+ const q = Point.BASE.multiply(k).toAffine();
11238
+ const r = Fn.create(q.x);
11239
+ if (r === _0n4)
11240
+ return;
11241
+ const s = Fn.create(ik * Fn.create(m + r * d));
11242
+ if (s === _0n4)
11243
+ return;
11244
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
11245
+ let normS = s;
11246
+ if (lowS && isBiggerThanHalfOrder(s)) {
11247
+ normS = Fn.neg(s);
11248
+ recovery ^= 1;
11249
+ }
11250
+ return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
11251
+ }
11252
+ return { seed, k2sig };
11253
+ }
11254
+ function sign(message, secretKey, opts = {}) {
11255
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
11256
+ const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
11257
+ const sig = drbg(seed, k2sig);
11258
+ return sig.toBytes(opts.format);
11259
+ }
11260
+ function verify(signature, message, publicKey, opts = {}) {
11261
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
11262
+ publicKey = abytes(publicKey, void 0, "publicKey");
11263
+ message = validateMsgAndHash(message, prehash);
11264
+ if (!isBytes(signature)) {
11265
+ const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
11266
+ throw new Error("verify expects Uint8Array signature" + end);
11267
+ }
11268
+ validateSigLength(signature, format);
11269
+ try {
11270
+ const sig = Signature.fromBytes(signature, format);
11271
+ const P = Point.fromBytes(publicKey);
11272
+ if (lowS && sig.hasHighS())
11273
+ return false;
11274
+ const { r, s } = sig;
11275
+ const h = bits2int_modN(message);
11276
+ const is = Fn.inv(s);
11277
+ const u1 = Fn.create(h * is);
11278
+ const u2 = Fn.create(r * is);
11279
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
11280
+ if (R.is0())
11281
+ return false;
11282
+ const v = Fn.create(R.x);
11283
+ return v === r;
11284
+ } catch (e) {
11285
+ return false;
11286
+ }
11287
+ }
11288
+ function recoverPublicKey(signature, message, opts = {}) {
11289
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
11290
+ message = validateMsgAndHash(message, prehash);
11291
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
11292
+ }
11293
+ return Object.freeze({
11294
+ keygen,
11295
+ getPublicKey: getPublicKey2,
11296
+ getSharedSecret,
11297
+ utils,
11298
+ lengths,
11299
+ Point,
11300
+ sign,
11301
+ verify,
11302
+ recoverPublicKey,
11303
+ Signature,
11304
+ hash
11305
+ });
11306
+ }
11307
+
11308
+ // node_modules/@noble/curves/secp256k1.js
11309
+ var secp256k1_CURVE = {
11310
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
11311
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
11312
+ h: BigInt(1),
11313
+ a: BigInt(0),
11314
+ b: BigInt(7),
11315
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
11316
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
11317
+ };
11318
+ var secp256k1_ENDO = {
11319
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
11320
+ basises: [
11321
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
11322
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
11323
+ ]
11324
+ };
11325
+ var _2n3 = /* @__PURE__ */ BigInt(2);
11326
+ function sqrtMod(y) {
11327
+ const P = secp256k1_CURVE.p;
11328
+ const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
11329
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
11330
+ const b2 = y * y * y % P;
11331
+ const b3 = b2 * b2 * y % P;
11332
+ const b6 = pow2(b3, _3n3, P) * b3 % P;
11333
+ const b9 = pow2(b6, _3n3, P) * b3 % P;
11334
+ const b11 = pow2(b9, _2n3, P) * b2 % P;
11335
+ const b22 = pow2(b11, _11n, P) * b11 % P;
11336
+ const b44 = pow2(b22, _22n, P) * b22 % P;
11337
+ const b88 = pow2(b44, _44n, P) * b44 % P;
11338
+ const b176 = pow2(b88, _88n, P) * b88 % P;
11339
+ const b220 = pow2(b176, _44n, P) * b44 % P;
11340
+ const b223 = pow2(b220, _3n3, P) * b3 % P;
11341
+ const t1 = pow2(b223, _23n, P) * b22 % P;
11342
+ const t2 = pow2(t1, _6n, P) * b2 % P;
11343
+ const root = pow2(t2, _2n3, P);
11344
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
11345
+ throw new Error("Cannot find square root");
11346
+ return root;
11347
+ }
11348
+ var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
11349
+ var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
11350
+ Fp: Fpk1,
11351
+ endo: secp256k1_ENDO
11352
+ });
11353
+ var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha2564);
11354
+
11355
+ // modules/market/MarketModule.ts
11356
+ var DEFAULT_MARKET_API_URL = "https://market-api.unicity.network";
11357
+ function hexToBytes3(hex) {
11358
+ const len = hex.length >> 1;
11359
+ const bytes = new Uint8Array(len);
11360
+ for (let i = 0; i < len; i++) {
11361
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
11362
+ }
11363
+ return bytes;
11364
+ }
11365
+ function signRequest(body, privateKeyHex) {
11366
+ const timestamp = Date.now();
11367
+ const payload = JSON.stringify({ body, timestamp });
11368
+ const messageHash = sha2564(new TextEncoder().encode(payload));
11369
+ const privateKeyBytes = hexToBytes3(privateKeyHex);
11370
+ const signature = secp256k1.sign(messageHash, privateKeyBytes);
11371
+ const publicKey = bytesToHex4(secp256k1.getPublicKey(privateKeyBytes, true));
11372
+ return {
11373
+ body: JSON.stringify(body),
11374
+ headers: {
11375
+ "x-signature": bytesToHex4(signature),
11376
+ "x-public-key": publicKey,
11377
+ "x-timestamp": String(timestamp),
11378
+ "content-type": "application/json"
11379
+ }
11380
+ };
11381
+ }
11382
+ function toSnakeCaseIntent(req) {
11383
+ const result = {
11384
+ description: req.description,
11385
+ intent_type: req.intentType
11386
+ };
11387
+ if (req.category !== void 0) result.category = req.category;
11388
+ if (req.price !== void 0) result.price = req.price;
11389
+ if (req.currency !== void 0) result.currency = req.currency;
11390
+ if (req.location !== void 0) result.location = req.location;
11391
+ if (req.contactHandle !== void 0) result.contact_handle = req.contactHandle;
11392
+ if (req.expiresInDays !== void 0) result.expires_in_days = req.expiresInDays;
11393
+ return result;
11394
+ }
11395
+ function toSnakeCaseFilters(opts) {
11396
+ const result = {};
11397
+ if (opts?.filters) {
11398
+ const f = opts.filters;
11399
+ if (f.intentType !== void 0) result.intent_type = f.intentType;
11400
+ if (f.category !== void 0) result.category = f.category;
11401
+ if (f.minPrice !== void 0) result.min_price = f.minPrice;
11402
+ if (f.maxPrice !== void 0) result.max_price = f.maxPrice;
11403
+ if (f.location !== void 0) result.location = f.location;
11404
+ }
11405
+ if (opts?.limit !== void 0) result.limit = opts.limit;
11406
+ return result;
11407
+ }
11408
+ function mapSearchResult(raw) {
11409
+ return {
11410
+ id: raw.id,
11411
+ score: raw.score,
11412
+ agentNametag: raw.agent_nametag ?? void 0,
11413
+ agentPublicKey: raw.agent_public_key,
11414
+ description: raw.description,
11415
+ intentType: raw.intent_type,
11416
+ category: raw.category ?? void 0,
11417
+ price: raw.price ?? void 0,
11418
+ currency: raw.currency,
11419
+ location: raw.location ?? void 0,
11420
+ contactMethod: raw.contact_method,
11421
+ contactHandle: raw.contact_handle ?? void 0,
11422
+ createdAt: raw.created_at,
11423
+ expiresAt: raw.expires_at
11424
+ };
11425
+ }
11426
+ function mapMyIntent(raw) {
11427
+ return {
11428
+ id: raw.id,
11429
+ intentType: raw.intent_type,
11430
+ category: raw.category ?? void 0,
11431
+ price: raw.price ?? void 0,
11432
+ currency: raw.currency,
11433
+ location: raw.location ?? void 0,
11434
+ status: raw.status,
11435
+ createdAt: raw.created_at,
11436
+ expiresAt: raw.expires_at
11437
+ };
11438
+ }
11439
+ function mapFeedListing(raw) {
11440
+ return {
11441
+ id: raw.id,
11442
+ title: raw.title,
11443
+ descriptionPreview: raw.description_preview,
11444
+ agentName: raw.agent_name,
11445
+ agentId: raw.agent_id,
11446
+ type: raw.type,
11447
+ createdAt: raw.created_at
11448
+ };
11449
+ }
11450
+ function mapFeedMessage(raw) {
11451
+ if (raw.type === "initial") {
11452
+ return { type: "initial", listings: (raw.listings ?? []).map(mapFeedListing) };
11453
+ }
11454
+ return { type: "new", listing: mapFeedListing(raw.listing) };
11455
+ }
11456
+ var MarketModule = class {
11457
+ apiUrl;
11458
+ timeout;
11459
+ identity = null;
11460
+ registered = false;
11461
+ constructor(config) {
11462
+ this.apiUrl = (config?.apiUrl ?? DEFAULT_MARKET_API_URL).replace(/\/+$/, "");
11463
+ this.timeout = config?.timeout ?? 3e4;
11464
+ }
11465
+ /** Called by Sphere after construction */
11466
+ initialize(deps) {
11467
+ this.identity = deps.identity;
11468
+ }
11469
+ /** No-op — stateless module */
11470
+ async load() {
11471
+ }
11472
+ /** No-op — stateless module */
11473
+ destroy() {
11474
+ }
11475
+ // ---------------------------------------------------------------------------
11476
+ // Public API
11477
+ // ---------------------------------------------------------------------------
11478
+ /** Post a new intent (agent is auto-registered on first post) */
11479
+ async postIntent(intent) {
11480
+ const body = toSnakeCaseIntent(intent);
11481
+ const data = await this.apiPost("/api/intents", body);
11482
+ return {
11483
+ intentId: data.intent_id ?? data.intentId,
11484
+ message: data.message,
11485
+ expiresAt: data.expires_at ?? data.expiresAt
11486
+ };
11487
+ }
11488
+ /** Semantic search for intents (public — no auth required) */
11489
+ async search(query, opts) {
11490
+ const body = {
11491
+ query,
11492
+ ...toSnakeCaseFilters(opts)
11493
+ };
11494
+ const data = await this.apiPublicPost("/api/search", body);
11495
+ let results = (data.intents ?? []).map(mapSearchResult);
11496
+ const minScore = opts?.filters?.minScore;
11497
+ if (minScore != null) {
11498
+ results = results.filter((r) => Math.round(r.score * 100) >= Math.round(minScore * 100));
11499
+ }
11500
+ return { intents: results, count: results.length };
11501
+ }
11502
+ /** List own intents (authenticated) */
11503
+ async getMyIntents() {
11504
+ const data = await this.apiGet("/api/intents");
11505
+ return (data.intents ?? []).map(mapMyIntent);
11506
+ }
11507
+ /** Close (delete) an intent */
11508
+ async closeIntent(intentId) {
11509
+ await this.apiDelete(`/api/intents/${encodeURIComponent(intentId)}`);
11510
+ }
11511
+ /** Fetch the most recent listings via REST (public — no auth required) */
11512
+ async getRecentListings() {
11513
+ const res = await fetch(`${this.apiUrl}/api/feed/recent`, {
11514
+ signal: AbortSignal.timeout(this.timeout)
11515
+ });
11516
+ const data = await this.parseResponse(res);
11517
+ return (data.listings ?? []).map(mapFeedListing);
11518
+ }
11519
+ /**
11520
+ * Subscribe to the live listing feed via WebSocket.
11521
+ * Returns an unsubscribe function that closes the connection.
11522
+ *
11523
+ * Requires a WebSocket implementation — works natively in browsers
11524
+ * and in Node.js 21+ (or with the `ws` package).
11525
+ */
11526
+ subscribeFeed(listener) {
11527
+ const wsUrl = this.apiUrl.replace(/^http/, "ws") + "/ws/feed";
11528
+ const ws2 = new WebSocket(wsUrl);
11529
+ ws2.onmessage = (event) => {
11530
+ try {
11531
+ const raw = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
11532
+ listener(mapFeedMessage(raw));
11533
+ } catch {
11534
+ }
11535
+ };
11536
+ return () => {
11537
+ ws2.close();
11538
+ };
11539
+ }
11540
+ // ---------------------------------------------------------------------------
11541
+ // Private: HTTP helpers
11542
+ // ---------------------------------------------------------------------------
11543
+ ensureIdentity() {
11544
+ if (!this.identity) {
11545
+ throw new Error("MarketModule not initialized \u2014 call initialize() first");
11546
+ }
11547
+ }
11548
+ /** Register the agent's public key with the server (idempotent) */
11549
+ async ensureRegistered() {
11550
+ if (this.registered) return;
11551
+ this.ensureIdentity();
11552
+ const publicKey = bytesToHex4(secp256k1.getPublicKey(hexToBytes3(this.identity.privateKey), true));
11553
+ const body = { public_key: publicKey };
11554
+ if (this.identity.nametag) body.nametag = this.identity.nametag;
11555
+ const res = await fetch(`${this.apiUrl}/api/agent/register`, {
11556
+ method: "POST",
11557
+ headers: { "content-type": "application/json" },
11558
+ body: JSON.stringify(body),
11559
+ signal: AbortSignal.timeout(this.timeout)
11560
+ });
11561
+ if (res.ok || res.status === 409) {
11562
+ this.registered = true;
11563
+ return;
11564
+ }
11565
+ const text = await res.text();
11566
+ let data;
11567
+ try {
11568
+ data = JSON.parse(text);
11569
+ } catch {
11570
+ }
11571
+ throw new Error(data?.error ?? `Agent registration failed: HTTP ${res.status}`);
11572
+ }
11573
+ async parseResponse(res) {
11574
+ const text = await res.text();
11575
+ let data;
11576
+ try {
11577
+ data = JSON.parse(text);
11578
+ } catch {
11579
+ throw new Error(`Market API error: HTTP ${res.status} \u2014 unexpected response (not JSON)`);
11580
+ }
11581
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
11582
+ return data;
11583
+ }
11584
+ async apiPost(path, body) {
11585
+ this.ensureIdentity();
11586
+ await this.ensureRegistered();
11587
+ const signed = signRequest(body, this.identity.privateKey);
11588
+ const res = await fetch(`${this.apiUrl}${path}`, {
11589
+ method: "POST",
11590
+ headers: signed.headers,
11591
+ body: signed.body,
11592
+ signal: AbortSignal.timeout(this.timeout)
11593
+ });
11594
+ return this.parseResponse(res);
11595
+ }
11596
+ async apiGet(path) {
11597
+ this.ensureIdentity();
11598
+ await this.ensureRegistered();
11599
+ const signed = signRequest({}, this.identity.privateKey);
11600
+ const res = await fetch(`${this.apiUrl}${path}`, {
11601
+ method: "GET",
11602
+ headers: signed.headers,
11603
+ signal: AbortSignal.timeout(this.timeout)
11604
+ });
11605
+ return this.parseResponse(res);
11606
+ }
11607
+ async apiDelete(path) {
11608
+ this.ensureIdentity();
11609
+ await this.ensureRegistered();
11610
+ const signed = signRequest({}, this.identity.privateKey);
11611
+ const res = await fetch(`${this.apiUrl}${path}`, {
11612
+ method: "DELETE",
11613
+ headers: signed.headers,
11614
+ signal: AbortSignal.timeout(this.timeout)
11615
+ });
11616
+ return this.parseResponse(res);
11617
+ }
11618
+ async apiPublicPost(path, body) {
11619
+ const res = await fetch(`${this.apiUrl}${path}`, {
11620
+ method: "POST",
11621
+ headers: { "content-type": "application/json" },
11622
+ body: JSON.stringify(body),
11623
+ signal: AbortSignal.timeout(this.timeout)
11624
+ });
11625
+ return this.parseResponse(res);
11626
+ }
11627
+ };
11628
+ function createMarketModule(config) {
11629
+ return new MarketModule(config);
11630
+ }
11631
+
9089
11632
  // core/encryption.ts
9090
11633
  var import_crypto_js6 = __toESM(require("crypto-js"), 1);
9091
11634
  var DEFAULT_ITERATIONS = 1e5;
@@ -10006,6 +12549,7 @@ var Sphere = class _Sphere {
10006
12549
  _payments;
10007
12550
  _communications;
10008
12551
  _groupChat = null;
12552
+ _market = null;
10009
12553
  // Events
10010
12554
  eventHandlers = /* @__PURE__ */ new Map();
10011
12555
  // Provider management
@@ -10015,7 +12559,7 @@ var Sphere = class _Sphere {
10015
12559
  // ===========================================================================
10016
12560
  // Constructor (private)
10017
12561
  // ===========================================================================
10018
- constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig) {
12562
+ constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig, marketConfig) {
10019
12563
  this._storage = storage;
10020
12564
  this._transport = transport;
10021
12565
  this._oracle = oracle;
@@ -10026,6 +12570,7 @@ var Sphere = class _Sphere {
10026
12570
  this._payments = createPaymentsModule({ l1: l1Config });
10027
12571
  this._communications = createCommunicationsModule();
10028
12572
  this._groupChat = groupChatConfig ? createGroupChatModule(groupChatConfig) : null;
12573
+ this._market = marketConfig ? createMarketModule(marketConfig) : null;
10029
12574
  }
10030
12575
  // ===========================================================================
10031
12576
  // Static Methods - Wallet Management
@@ -10035,13 +12580,17 @@ var Sphere = class _Sphere {
10035
12580
  */
10036
12581
  static async exists(storage) {
10037
12582
  try {
10038
- if (!storage.isConnected()) {
12583
+ const wasConnected = storage.isConnected();
12584
+ if (!wasConnected) {
10039
12585
  await storage.connect();
10040
12586
  }
10041
12587
  const mnemonic = await storage.get(STORAGE_KEYS_GLOBAL.MNEMONIC);
10042
12588
  if (mnemonic) return true;
10043
12589
  const masterKey = await storage.get(STORAGE_KEYS_GLOBAL.MASTER_KEY);
10044
12590
  if (masterKey) return true;
12591
+ if (!wasConnected) {
12592
+ await storage.disconnect();
12593
+ }
10045
12594
  return false;
10046
12595
  } catch {
10047
12596
  return false;
@@ -10075,6 +12624,7 @@ var Sphere = class _Sphere {
10075
12624
  static async init(options) {
10076
12625
  _Sphere.configureTokenRegistry(options.storage, options.network);
10077
12626
  const groupChat = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12627
+ const market = _Sphere.resolveMarketConfig(options.market);
10078
12628
  const walletExists = await _Sphere.exists(options.storage);
10079
12629
  if (walletExists) {
10080
12630
  const sphere2 = await _Sphere.load({
@@ -10085,6 +12635,7 @@ var Sphere = class _Sphere {
10085
12635
  l1: options.l1,
10086
12636
  price: options.price,
10087
12637
  groupChat,
12638
+ market,
10088
12639
  password: options.password
10089
12640
  });
10090
12641
  return { sphere: sphere2, created: false };
@@ -10112,6 +12663,7 @@ var Sphere = class _Sphere {
10112
12663
  l1: options.l1,
10113
12664
  price: options.price,
10114
12665
  groupChat,
12666
+ market,
10115
12667
  password: options.password
10116
12668
  });
10117
12669
  return { sphere, created: true, generatedMnemonic };
@@ -10139,6 +12691,17 @@ var Sphere = class _Sphere {
10139
12691
  }
10140
12692
  return config;
10141
12693
  }
12694
+ /**
12695
+ * Resolve market module config from Sphere.init() options.
12696
+ * - `true` → enable with default API URL
12697
+ * - `MarketModuleConfig` → pass through
12698
+ * - `undefined` → no market module
12699
+ */
12700
+ static resolveMarketConfig(config) {
12701
+ if (!config) return void 0;
12702
+ if (config === true) return {};
12703
+ return config;
12704
+ }
10142
12705
  /**
10143
12706
  * Configure TokenRegistry in the main bundle context.
10144
12707
  *
@@ -10164,6 +12727,7 @@ var Sphere = class _Sphere {
10164
12727
  }
10165
12728
  _Sphere.configureTokenRegistry(options.storage, options.network);
10166
12729
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12730
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10167
12731
  const sphere = new _Sphere(
10168
12732
  options.storage,
10169
12733
  options.transport,
@@ -10171,7 +12735,8 @@ var Sphere = class _Sphere {
10171
12735
  options.tokenStorage,
10172
12736
  options.l1,
10173
12737
  options.price,
10174
- groupChatConfig
12738
+ groupChatConfig,
12739
+ marketConfig
10175
12740
  );
10176
12741
  sphere._password = options.password ?? null;
10177
12742
  await sphere.storeMnemonic(options.mnemonic, options.derivationPath);
@@ -10199,6 +12764,7 @@ var Sphere = class _Sphere {
10199
12764
  }
10200
12765
  _Sphere.configureTokenRegistry(options.storage, options.network);
10201
12766
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
12767
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10202
12768
  const sphere = new _Sphere(
10203
12769
  options.storage,
10204
12770
  options.transport,
@@ -10206,7 +12772,8 @@ var Sphere = class _Sphere {
10206
12772
  options.tokenStorage,
10207
12773
  options.l1,
10208
12774
  options.price,
10209
- groupChatConfig
12775
+ groupChatConfig,
12776
+ marketConfig
10210
12777
  );
10211
12778
  sphere._password = options.password ?? null;
10212
12779
  await sphere.loadIdentityFromStorage();
@@ -10252,6 +12819,7 @@ var Sphere = class _Sphere {
10252
12819
  console.log("[Sphere.import] Storage reconnected");
10253
12820
  }
10254
12821
  const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat);
12822
+ const marketConfig = _Sphere.resolveMarketConfig(options.market);
10255
12823
  const sphere = new _Sphere(
10256
12824
  options.storage,
10257
12825
  options.transport,
@@ -10259,7 +12827,8 @@ var Sphere = class _Sphere {
10259
12827
  options.tokenStorage,
10260
12828
  options.l1,
10261
12829
  options.price,
10262
- groupChatConfig
12830
+ groupChatConfig,
12831
+ marketConfig
10263
12832
  );
10264
12833
  sphere._password = options.password ?? null;
10265
12834
  if (options.mnemonic) {
@@ -10340,46 +12909,58 @@ var Sphere = class _Sphere {
10340
12909
  static async clear(storageOrOptions) {
10341
12910
  const storage = "get" in storageOrOptions ? storageOrOptions : storageOrOptions.storage;
10342
12911
  const tokenStorage = "get" in storageOrOptions ? void 0 : storageOrOptions.tokenStorage;
10343
- if (!storage.isConnected()) {
10344
- await storage.connect();
10345
- }
10346
- console.log("[Sphere.clear] Removing storage keys...");
10347
- await storage.remove(STORAGE_KEYS_GLOBAL.MNEMONIC);
10348
- await storage.remove(STORAGE_KEYS_GLOBAL.MASTER_KEY);
10349
- await storage.remove(STORAGE_KEYS_GLOBAL.CHAIN_CODE);
10350
- await storage.remove(STORAGE_KEYS_GLOBAL.DERIVATION_PATH);
10351
- await storage.remove(STORAGE_KEYS_GLOBAL.BASE_PATH);
10352
- await storage.remove(STORAGE_KEYS_GLOBAL.DERIVATION_MODE);
10353
- await storage.remove(STORAGE_KEYS_GLOBAL.WALLET_SOURCE);
10354
- await storage.remove(STORAGE_KEYS_GLOBAL.WALLET_EXISTS);
10355
- await storage.remove(STORAGE_KEYS_GLOBAL.TRACKED_ADDRESSES);
10356
- await storage.remove(STORAGE_KEYS_GLOBAL.ADDRESS_NAMETAGS);
10357
- await storage.remove(STORAGE_KEYS_ADDRESS.PENDING_TRANSFERS);
10358
- await storage.remove(STORAGE_KEYS_ADDRESS.OUTBOX);
10359
- console.log("[Sphere.clear] Storage keys removed");
10360
- if (tokenStorage?.clear) {
10361
- console.log("[Sphere.clear] Clearing token storage...");
12912
+ if (_Sphere.instance) {
12913
+ console.log("[Sphere.clear] Destroying Sphere instance...");
12914
+ await _Sphere.instance.destroy();
12915
+ console.log("[Sphere.clear] Sphere instance destroyed");
12916
+ }
12917
+ await vestingClassifier.destroy();
12918
+ if (typeof indexedDB !== "undefined" && typeof indexedDB.databases === "function") {
12919
+ console.log("[Sphere.clear] Deleting all sphere IndexedDB databases...");
10362
12920
  try {
10363
- await Promise.race([
10364
- tokenStorage.clear(),
12921
+ const dbs = await Promise.race([
12922
+ indexedDB.databases(),
10365
12923
  new Promise(
10366
- (_, reject) => setTimeout(() => reject(new Error("tokenStorage.clear() timed out after 2s")), 2e3)
12924
+ (_, reject) => setTimeout(() => reject(new Error("timeout")), 2e3)
10367
12925
  )
10368
12926
  ]);
10369
- console.log("[Sphere.clear] Token storage cleared");
12927
+ const sphereDbs = dbs.filter((db) => db.name?.startsWith("sphere"));
12928
+ if (sphereDbs.length > 0) {
12929
+ await Promise.all(sphereDbs.map(
12930
+ (db) => new Promise((resolve) => {
12931
+ const req = indexedDB.deleteDatabase(db.name);
12932
+ req.onsuccess = () => {
12933
+ console.log(`[Sphere.clear] Deleted ${db.name}`);
12934
+ resolve();
12935
+ };
12936
+ req.onerror = () => resolve();
12937
+ req.onblocked = () => {
12938
+ console.warn(`[Sphere.clear] deleteDatabase blocked: ${db.name}`);
12939
+ resolve();
12940
+ };
12941
+ })
12942
+ ));
12943
+ }
12944
+ console.log("[Sphere.clear] IndexedDB cleanup done");
12945
+ } catch {
12946
+ console.warn("[Sphere.clear] IndexedDB enumeration failed");
12947
+ }
12948
+ }
12949
+ if (tokenStorage?.clear) {
12950
+ try {
12951
+ await tokenStorage.clear();
10370
12952
  } catch (err) {
10371
- console.warn("[Sphere.clear] Token storage clear failed/timed out:", err);
12953
+ console.warn("[Sphere.clear] Token storage clear failed:", err);
10372
12954
  }
10373
12955
  }
10374
- console.log("[Sphere.clear] Destroying vesting classifier...");
10375
- await vestingClassifier.destroy();
10376
- console.log("[Sphere.clear] Vesting classifier destroyed");
10377
- if (_Sphere.instance) {
10378
- console.log("[Sphere.clear] Destroying Sphere instance...");
10379
- await _Sphere.instance.destroy();
10380
- console.log("[Sphere.clear] Sphere instance destroyed");
10381
- } else {
10382
- console.log("[Sphere.clear] No Sphere instance to destroy");
12956
+ if (!storage.isConnected()) {
12957
+ try {
12958
+ await storage.connect();
12959
+ } catch {
12960
+ }
12961
+ }
12962
+ if (storage.isConnected()) {
12963
+ await storage.clear();
10383
12964
  }
10384
12965
  }
10385
12966
  /**
@@ -10424,6 +13005,10 @@ var Sphere = class _Sphere {
10424
13005
  get groupChat() {
10425
13006
  return this._groupChat;
10426
13007
  }
13008
+ /** Market module (intent bulletin board). Null if not configured. */
13009
+ get market() {
13010
+ return this._market;
13011
+ }
10427
13012
  // ===========================================================================
10428
13013
  // Public Properties - State
10429
13014
  // ===========================================================================
@@ -11299,9 +13884,14 @@ var Sphere = class _Sphere {
11299
13884
  storage: this._storage,
11300
13885
  emitEvent
11301
13886
  });
13887
+ this._market?.initialize({
13888
+ identity: this._identity,
13889
+ emitEvent
13890
+ });
11302
13891
  await this._payments.load();
11303
13892
  await this._communications.load();
11304
13893
  await this._groupChat?.load();
13894
+ await this._market?.load();
11305
13895
  }
11306
13896
  /**
11307
13897
  * Derive address at a specific index
@@ -12126,6 +14716,7 @@ var Sphere = class _Sphere {
12126
14716
  this._payments.destroy();
12127
14717
  this._communications.destroy();
12128
14718
  this._groupChat?.destroy();
14719
+ this._market?.destroy();
12129
14720
  await this._transport.disconnect();
12130
14721
  await this._storage.disconnect();
12131
14722
  await this._oracle.disconnect();
@@ -12433,9 +15024,14 @@ var Sphere = class _Sphere {
12433
15024
  storage: this._storage,
12434
15025
  emitEvent
12435
15026
  });
15027
+ this._market?.initialize({
15028
+ identity: this._identity,
15029
+ emitEvent
15030
+ });
12436
15031
  await this._payments.load();
12437
15032
  await this._communications.load();
12438
15033
  await this._groupChat?.load();
15034
+ await this._market?.load();
12439
15035
  }
12440
15036
  // ===========================================================================
12441
15037
  // Private: Helpers
@@ -12786,4 +15382,16 @@ async function runCustomCheck(name, checkFn, timeoutMs) {
12786
15382
  toSmallestUnit,
12787
15383
  validateMnemonic
12788
15384
  });
15385
+ /*! Bundled license information:
15386
+
15387
+ @noble/hashes/utils.js:
15388
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
15389
+
15390
+ @noble/curves/utils.js:
15391
+ @noble/curves/abstract/modular.js:
15392
+ @noble/curves/abstract/curve.js:
15393
+ @noble/curves/abstract/weierstrass.js:
15394
+ @noble/curves/secp256k1.js:
15395
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
15396
+ */
12789
15397
  //# sourceMappingURL=index.cjs.map