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