@unicitylabs/sphere-sdk 0.14.0-dev.1 → 0.14.0-dev.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4366 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
19
+
20
+ // impl/wallet-api-v2/index.ts
21
+ var wallet_api_v2_exports = {};
22
+ __export(wallet_api_v2_exports, {
23
+ DEFAULT_SESSION_TIMING: () => DEFAULT_SESSION_TIMING,
24
+ JwtGenerationCell: () => JwtGenerationCell,
25
+ WAKE_STREAMS: () => WAKE_STREAMS,
26
+ WalletApiDeliveryPort: () => WalletApiDeliveryPort,
27
+ WalletApiHttpError: () => WalletApiHttpError,
28
+ WalletApiSession: () => WalletApiSession,
29
+ WalletApiSplitCheckpointStore: () => WalletApiSplitCheckpointStore,
30
+ WalletApiStoragePort: () => WalletApiStoragePort,
31
+ WalletApiV2Client: () => WalletApiV2Client,
32
+ assertSecureBaseUrl: () => assertSecureBaseUrl,
33
+ createWalletApiHttp: () => createWalletApiHttp,
34
+ isWalletApiHttpError: () => isWalletApiHttpError,
35
+ refreshTokenKey: () => refreshTokenKey
36
+ });
37
+ module.exports = __toCommonJS(wallet_api_v2_exports);
38
+
39
+ // impl/wallet-api-v2/http.ts
40
+ var WalletApiHttpError = class extends Error {
41
+ status;
42
+ code;
43
+ /** Milliseconds, parsed from a Retry-After header when present. */
44
+ retryAfter;
45
+ constructor(status, code, message, retryAfter) {
46
+ super(message);
47
+ this.name = "WalletApiHttpError";
48
+ this.status = status;
49
+ this.code = code;
50
+ if (retryAfter !== void 0) this.retryAfter = retryAfter;
51
+ }
52
+ };
53
+ function isWalletApiHttpError(err, status) {
54
+ return err instanceof WalletApiHttpError && (status === void 0 || err.status === status);
55
+ }
56
+ function isLoopbackHost(hostname) {
57
+ return hostname === "localhost" || hostname.endsWith(".localhost") || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname) || hostname === "::1" || hostname === "[::1]";
58
+ }
59
+ function assertSecureBaseUrl(baseUrl) {
60
+ let url;
61
+ try {
62
+ url = new URL(baseUrl);
63
+ } catch {
64
+ throw new Error(`Invalid wallet-api base URL: ${baseUrl}`);
65
+ }
66
+ const httpLoopback = url.protocol === "http:" && isLoopbackHost(url.hostname);
67
+ if (url.protocol !== "https:" && !httpLoopback) {
68
+ throw new Error("wallet-api base URL must be https (plain http is allowed only on loopback)");
69
+ }
70
+ return url.toString().replace(/\/$/, "");
71
+ }
72
+ function parseRetryAfter(res) {
73
+ const raw = res.headers?.get("retry-after");
74
+ if (!raw) return void 0;
75
+ const seconds = Number(raw);
76
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
77
+ const when = Date.parse(raw);
78
+ return Number.isNaN(when) ? void 0 : Math.max(0, when - Date.now());
79
+ }
80
+ async function readBodyText(res) {
81
+ try {
82
+ return await res.text();
83
+ } catch {
84
+ return "";
85
+ }
86
+ }
87
+ async function toHttpError(res, what) {
88
+ let code = `HTTP_${res.status}`;
89
+ let message = `${what} failed with status ${res.status}`;
90
+ const text = await readBodyText(res);
91
+ if (text !== "") {
92
+ try {
93
+ const parsed = JSON.parse(text);
94
+ if (parsed?.error?.code) code = parsed.error.code;
95
+ if (parsed?.error?.message) message = `${what}: ${parsed.error.message}`;
96
+ } catch {
97
+ }
98
+ }
99
+ return new WalletApiHttpError(res.status, code, message, parseRetryAfter(res));
100
+ }
101
+ function parseJsonBody(text, what, status) {
102
+ if (text === "") return null;
103
+ try {
104
+ return JSON.parse(text);
105
+ } catch {
106
+ throw new WalletApiHttpError(status, "PROTOCOL", `${what}: response is not JSON`);
107
+ }
108
+ }
109
+ function createWalletApiHttp(config) {
110
+ const baseUrl = assertSecureBaseUrl(config.baseUrl);
111
+ const { fetchFn, getToken } = config;
112
+ const fetchRaw = async (url, init) => {
113
+ try {
114
+ return await fetchFn(url, init);
115
+ } catch (err) {
116
+ throw new WalletApiHttpError(
117
+ 0,
118
+ "NETWORK",
119
+ `wallet-api request failed: ${init.method} ${url}: ${String(err)}`
120
+ );
121
+ }
122
+ };
123
+ const request = async (method, path, body, opts) => {
124
+ const headers = {};
125
+ if (body !== void 0) headers["content-type"] = "application/json";
126
+ if (opts?.auth !== false) {
127
+ const token = getToken();
128
+ if (token !== null) headers["authorization"] = `Bearer ${token}`;
129
+ }
130
+ const res = await fetchRaw(`${baseUrl}${path}`, {
131
+ method,
132
+ headers,
133
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
134
+ });
135
+ const what = `${method} ${path}`;
136
+ if (res.status === 204) return null;
137
+ if (!res.ok) throw await toHttpError(res, what);
138
+ return parseJsonBody(await readBodyText(res), what, res.status);
139
+ };
140
+ return { baseUrl, request, fetchRaw };
141
+ }
142
+
143
+ // node_modules/@noble/hashes/utils.js
144
+ function isBytes(a) {
145
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
146
+ }
147
+ function anumber(n, title = "") {
148
+ if (typeof n !== "number") {
149
+ const prefix = title && `"${title}" `;
150
+ throw new TypeError(`${prefix}expected number, got ${typeof n}`);
151
+ }
152
+ if (!Number.isSafeInteger(n) || n < 0) {
153
+ const prefix = title && `"${title}" `;
154
+ throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
155
+ }
156
+ }
157
+ function abytes(value, length, title = "") {
158
+ const bytes = isBytes(value);
159
+ const len = value?.length;
160
+ const needsLen = length !== void 0;
161
+ if (!bytes || needsLen && len !== length) {
162
+ const prefix = title && `"${title}" `;
163
+ const ofLen = needsLen ? ` of length ${length}` : "";
164
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
165
+ const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
166
+ if (!bytes)
167
+ throw new TypeError(message);
168
+ throw new RangeError(message);
169
+ }
170
+ return value;
171
+ }
172
+ function ahash(h) {
173
+ if (typeof h !== "function" || typeof h.create !== "function")
174
+ throw new TypeError("Hash must wrapped by utils.createHasher");
175
+ anumber(h.outputLen);
176
+ anumber(h.blockLen);
177
+ if (h.outputLen < 1)
178
+ throw new Error('"outputLen" must be >= 1');
179
+ if (h.blockLen < 1)
180
+ throw new Error('"blockLen" must be >= 1');
181
+ }
182
+ function aexists(instance, checkFinished = true) {
183
+ if (instance.destroyed)
184
+ throw new Error("Hash instance has been destroyed");
185
+ if (checkFinished && instance.finished)
186
+ throw new Error("Hash#digest() has already been called");
187
+ }
188
+ function aoutput(out, instance) {
189
+ abytes(out, void 0, "digestInto() output");
190
+ const min = instance.outputLen;
191
+ if (out.length < min) {
192
+ throw new RangeError('"digestInto() output" expected to be of length >=' + min);
193
+ }
194
+ }
195
+ function clean(...arrays) {
196
+ for (let i = 0; i < arrays.length; i++) {
197
+ arrays[i].fill(0);
198
+ }
199
+ }
200
+ function createView(arr) {
201
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
202
+ }
203
+ function rotr(word, shift) {
204
+ return word << 32 - shift | word >>> shift;
205
+ }
206
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
207
+ // @ts-ignore
208
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
209
+ ))();
210
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
211
+ function bytesToHex(bytes) {
212
+ abytes(bytes);
213
+ if (hasHexBuiltin)
214
+ return bytes.toHex();
215
+ let hex = "";
216
+ for (let i = 0; i < bytes.length; i++) {
217
+ hex += hexes[bytes[i]];
218
+ }
219
+ return hex;
220
+ }
221
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
222
+ function asciiToBase16(ch) {
223
+ if (ch >= asciis._0 && ch <= asciis._9)
224
+ return ch - asciis._0;
225
+ if (ch >= asciis.A && ch <= asciis.F)
226
+ return ch - (asciis.A - 10);
227
+ if (ch >= asciis.a && ch <= asciis.f)
228
+ return ch - (asciis.a - 10);
229
+ return;
230
+ }
231
+ function hexToBytes(hex) {
232
+ if (typeof hex !== "string")
233
+ throw new TypeError("hex string expected, got " + typeof hex);
234
+ if (hasHexBuiltin) {
235
+ try {
236
+ return Uint8Array.fromHex(hex);
237
+ } catch (error) {
238
+ if (error instanceof SyntaxError)
239
+ throw new RangeError(error.message);
240
+ throw error;
241
+ }
242
+ }
243
+ const hl = hex.length;
244
+ const al = hl / 2;
245
+ if (hl % 2)
246
+ throw new RangeError("hex string expected, got unpadded hex of length " + hl);
247
+ const array = new Uint8Array(al);
248
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
249
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
250
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
251
+ if (n1 === void 0 || n2 === void 0) {
252
+ const char = hex[hi] + hex[hi + 1];
253
+ throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
254
+ }
255
+ array[ai] = n1 * 16 + n2;
256
+ }
257
+ return array;
258
+ }
259
+ function concatBytes(...arrays) {
260
+ let sum = 0;
261
+ for (let i = 0; i < arrays.length; i++) {
262
+ const a = arrays[i];
263
+ abytes(a);
264
+ sum += a.length;
265
+ }
266
+ const res = new Uint8Array(sum);
267
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
268
+ const a = arrays[i];
269
+ res.set(a, pad);
270
+ pad += a.length;
271
+ }
272
+ return res;
273
+ }
274
+ function createHasher(hashCons, info = {}) {
275
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
276
+ const tmp = hashCons(void 0);
277
+ hashC.outputLen = tmp.outputLen;
278
+ hashC.blockLen = tmp.blockLen;
279
+ hashC.canXOF = tmp.canXOF;
280
+ hashC.create = (opts) => hashCons(opts);
281
+ Object.assign(hashC, info);
282
+ return Object.freeze(hashC);
283
+ }
284
+ function randomBytes(bytesLength = 32) {
285
+ anumber(bytesLength, "bytesLength");
286
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
287
+ if (typeof cr?.getRandomValues !== "function")
288
+ throw new Error("crypto.getRandomValues must be defined");
289
+ if (bytesLength > 65536)
290
+ throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
291
+ return cr.getRandomValues(new Uint8Array(bytesLength));
292
+ }
293
+ var oidNist = (suffix) => ({
294
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
295
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
296
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
297
+ });
298
+
299
+ // node_modules/@noble/hashes/_md.js
300
+ function Chi(a, b, c) {
301
+ return a & b ^ ~a & c;
302
+ }
303
+ function Maj(a, b, c) {
304
+ return a & b ^ a & c ^ b & c;
305
+ }
306
+ var HashMD = class {
307
+ blockLen;
308
+ outputLen;
309
+ canXOF = false;
310
+ padOffset;
311
+ isLE;
312
+ // For partial updates less than block size
313
+ buffer;
314
+ view;
315
+ finished = false;
316
+ length = 0;
317
+ pos = 0;
318
+ destroyed = false;
319
+ constructor(blockLen, outputLen, padOffset, isLE2) {
320
+ this.blockLen = blockLen;
321
+ this.outputLen = outputLen;
322
+ this.padOffset = padOffset;
323
+ this.isLE = isLE2;
324
+ this.buffer = new Uint8Array(blockLen);
325
+ this.view = createView(this.buffer);
326
+ }
327
+ update(data) {
328
+ aexists(this);
329
+ abytes(data);
330
+ const { view, buffer, blockLen } = this;
331
+ const len = data.length;
332
+ for (let pos = 0; pos < len; ) {
333
+ const take = Math.min(blockLen - this.pos, len - pos);
334
+ if (take === blockLen) {
335
+ const dataView = createView(data);
336
+ for (; blockLen <= len - pos; pos += blockLen)
337
+ this.process(dataView, pos);
338
+ continue;
339
+ }
340
+ buffer.set(data.subarray(pos, pos + take), this.pos);
341
+ this.pos += take;
342
+ pos += take;
343
+ if (this.pos === blockLen) {
344
+ this.process(view, 0);
345
+ this.pos = 0;
346
+ }
347
+ }
348
+ this.length += data.length;
349
+ this.roundClean();
350
+ return this;
351
+ }
352
+ digestInto(out) {
353
+ aexists(this);
354
+ aoutput(out, this);
355
+ this.finished = true;
356
+ const { buffer, view, blockLen, isLE: isLE2 } = this;
357
+ let { pos } = this;
358
+ buffer[pos++] = 128;
359
+ clean(this.buffer.subarray(pos));
360
+ if (this.padOffset > blockLen - pos) {
361
+ this.process(view, 0);
362
+ pos = 0;
363
+ }
364
+ for (let i = pos; i < blockLen; i++)
365
+ buffer[i] = 0;
366
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE2);
367
+ this.process(view, 0);
368
+ const oview = createView(out);
369
+ const len = this.outputLen;
370
+ if (len % 4)
371
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
372
+ const outLen = len / 4;
373
+ const state = this.get();
374
+ if (outLen > state.length)
375
+ throw new Error("_sha2: outputLen bigger than state");
376
+ for (let i = 0; i < outLen; i++)
377
+ oview.setUint32(4 * i, state[i], isLE2);
378
+ }
379
+ digest() {
380
+ const { buffer, outputLen } = this;
381
+ this.digestInto(buffer);
382
+ const res = buffer.slice(0, outputLen);
383
+ this.destroy();
384
+ return res;
385
+ }
386
+ _cloneInto(to) {
387
+ to ||= new this.constructor();
388
+ to.set(...this.get());
389
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
390
+ to.destroyed = destroyed;
391
+ to.finished = finished;
392
+ to.length = length;
393
+ to.pos = pos;
394
+ if (length % blockLen)
395
+ to.buffer.set(buffer);
396
+ return to;
397
+ }
398
+ clone() {
399
+ return this._cloneInto();
400
+ }
401
+ };
402
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
403
+ 1779033703,
404
+ 3144134277,
405
+ 1013904242,
406
+ 2773480762,
407
+ 1359893119,
408
+ 2600822924,
409
+ 528734635,
410
+ 1541459225
411
+ ]);
412
+
413
+ // node_modules/@noble/hashes/sha2.js
414
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
415
+ 1116352408,
416
+ 1899447441,
417
+ 3049323471,
418
+ 3921009573,
419
+ 961987163,
420
+ 1508970993,
421
+ 2453635748,
422
+ 2870763221,
423
+ 3624381080,
424
+ 310598401,
425
+ 607225278,
426
+ 1426881987,
427
+ 1925078388,
428
+ 2162078206,
429
+ 2614888103,
430
+ 3248222580,
431
+ 3835390401,
432
+ 4022224774,
433
+ 264347078,
434
+ 604807628,
435
+ 770255983,
436
+ 1249150122,
437
+ 1555081692,
438
+ 1996064986,
439
+ 2554220882,
440
+ 2821834349,
441
+ 2952996808,
442
+ 3210313671,
443
+ 3336571891,
444
+ 3584528711,
445
+ 113926993,
446
+ 338241895,
447
+ 666307205,
448
+ 773529912,
449
+ 1294757372,
450
+ 1396182291,
451
+ 1695183700,
452
+ 1986661051,
453
+ 2177026350,
454
+ 2456956037,
455
+ 2730485921,
456
+ 2820302411,
457
+ 3259730800,
458
+ 3345764771,
459
+ 3516065817,
460
+ 3600352804,
461
+ 4094571909,
462
+ 275423344,
463
+ 430227734,
464
+ 506948616,
465
+ 659060556,
466
+ 883997877,
467
+ 958139571,
468
+ 1322822218,
469
+ 1537002063,
470
+ 1747873779,
471
+ 1955562222,
472
+ 2024104815,
473
+ 2227730452,
474
+ 2361852424,
475
+ 2428436474,
476
+ 2756734187,
477
+ 3204031479,
478
+ 3329325298
479
+ ]);
480
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
481
+ var SHA2_32B = class extends HashMD {
482
+ constructor(outputLen) {
483
+ super(64, outputLen, 8, false);
484
+ }
485
+ get() {
486
+ const { A, B, C, D, E, F, G, H } = this;
487
+ return [A, B, C, D, E, F, G, H];
488
+ }
489
+ // prettier-ignore
490
+ set(A, B, C, D, E, F, G, H) {
491
+ this.A = A | 0;
492
+ this.B = B | 0;
493
+ this.C = C | 0;
494
+ this.D = D | 0;
495
+ this.E = E | 0;
496
+ this.F = F | 0;
497
+ this.G = G | 0;
498
+ this.H = H | 0;
499
+ }
500
+ process(view, offset) {
501
+ for (let i = 0; i < 16; i++, offset += 4)
502
+ SHA256_W[i] = view.getUint32(offset, false);
503
+ for (let i = 16; i < 64; i++) {
504
+ const W15 = SHA256_W[i - 15];
505
+ const W2 = SHA256_W[i - 2];
506
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
507
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
508
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
509
+ }
510
+ let { A, B, C, D, E, F, G, H } = this;
511
+ for (let i = 0; i < 64; i++) {
512
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
513
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
514
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
515
+ const T2 = sigma0 + Maj(A, B, C) | 0;
516
+ H = G;
517
+ G = F;
518
+ F = E;
519
+ E = D + T1 | 0;
520
+ D = C;
521
+ C = B;
522
+ B = A;
523
+ A = T1 + T2 | 0;
524
+ }
525
+ A = A + this.A | 0;
526
+ B = B + this.B | 0;
527
+ C = C + this.C | 0;
528
+ D = D + this.D | 0;
529
+ E = E + this.E | 0;
530
+ F = F + this.F | 0;
531
+ G = G + this.G | 0;
532
+ H = H + this.H | 0;
533
+ this.set(A, B, C, D, E, F, G, H);
534
+ }
535
+ roundClean() {
536
+ clean(SHA256_W);
537
+ }
538
+ destroy() {
539
+ this.destroyed = true;
540
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
541
+ clean(this.buffer);
542
+ }
543
+ };
544
+ var _SHA256 = class extends SHA2_32B {
545
+ // We cannot use array here since array allows indexing by variable
546
+ // which means optimizer/compiler cannot use registers.
547
+ A = SHA256_IV[0] | 0;
548
+ B = SHA256_IV[1] | 0;
549
+ C = SHA256_IV[2] | 0;
550
+ D = SHA256_IV[3] | 0;
551
+ E = SHA256_IV[4] | 0;
552
+ F = SHA256_IV[5] | 0;
553
+ G = SHA256_IV[6] | 0;
554
+ H = SHA256_IV[7] | 0;
555
+ constructor() {
556
+ super(32);
557
+ }
558
+ };
559
+ var sha256 = /* @__PURE__ */ createHasher(
560
+ () => new _SHA256(),
561
+ /* @__PURE__ */ oidNist(1)
562
+ );
563
+
564
+ // impl/wallet-api-v2/client.ts
565
+ function bytesToBase64(bytes) {
566
+ let bin = "";
567
+ for (const b of bytes) bin += String.fromCharCode(b);
568
+ return btoa(bin);
569
+ }
570
+ var WalletApiV2Client = class {
571
+ constructor(http) {
572
+ this.http = http;
573
+ }
574
+ get baseUrl() {
575
+ return this.http.baseUrl;
576
+ }
577
+ // ── auth ─────────────────────────────────────────────────────────────────
578
+ authChallenge(pubkey) {
579
+ return this.http.request("POST", "/v1/auth/challenge", { pubkey }, { auth: false });
580
+ }
581
+ authVerify(input) {
582
+ return this.http.request("POST", "/v1/auth/verify", input, { auth: false });
583
+ }
584
+ authRefresh(refreshToken) {
585
+ return this.http.request("POST", "/v1/auth/refresh", { refreshToken }, { auth: false });
586
+ }
587
+ async authLogout() {
588
+ await this.http.request("POST", "/v1/auth/logout", {});
589
+ }
590
+ // ── inventory / blobs ────────────────────────────────────────────────────
591
+ listInventory(since) {
592
+ const query = since !== void 0 ? `?since=${since}` : "";
593
+ return this.http.request("GET", `/v1/inventory${query}`);
594
+ }
595
+ async balances() {
596
+ const body = await this.http.request("GET", "/v1/balances");
597
+ return body.balances;
598
+ }
599
+ async blobUrls(tokenIds) {
600
+ const body = await this.http.request("POST", "/v1/tokens/blob-urls", { tokenIds });
601
+ return body.urls;
602
+ }
603
+ async uploadUrls(blobs) {
604
+ const body = await this.http.request("POST", "/v1/tokens/upload-urls", { blobs });
605
+ return body.urls;
606
+ }
607
+ apply(delta) {
608
+ return this.http.request("POST", "/v1/inventory/apply", delta);
609
+ }
610
+ async fetchBlob(getUrl) {
611
+ const res = await this.http.fetchRaw(getUrl, { method: "GET" });
612
+ if (!res.ok) {
613
+ throw new WalletApiHttpError(res.status, "BLOB_DOWNLOAD", `blob download failed with status ${res.status}`);
614
+ }
615
+ return new Uint8Array(await res.arrayBuffer());
616
+ }
617
+ /**
618
+ * PUT to a presigned S3 URL. `x-amz-checksum-sha256` (base64) and
619
+ * `If-None-Match: *` are SIGNED headers — sent verbatim. S3 412 = the
620
+ * identical blob already exists = success.
621
+ */
622
+ async uploadBlob(putUrl, bytes) {
623
+ const res = await this.http.fetchRaw(putUrl, {
624
+ method: "PUT",
625
+ headers: {
626
+ "content-type": "application/octet-stream",
627
+ "x-amz-checksum-sha256": bytesToBase64(sha256(bytes)),
628
+ "if-none-match": "*"
629
+ },
630
+ body: bytes
631
+ });
632
+ if (res.ok || res.status === 412) return;
633
+ throw new WalletApiHttpError(res.status, "BLOB_UPLOAD", `blob upload failed with status ${res.status}`);
634
+ }
635
+ // ── intents ──────────────────────────────────────────────────────────────
636
+ async putIntent(transferId, payloadEnvelope, requiresSeedClose = false) {
637
+ const body = requiresSeedClose ? { payload: payloadEnvelope, requiresSeedClose: true } : { payload: payloadEnvelope };
638
+ await this.http.request("PUT", `/v1/intents/${transferId}`, body);
639
+ }
640
+ async listIntents(status = "open") {
641
+ const body = await this.http.request("GET", `/v1/intents?status=${status}`);
642
+ return body.intents;
643
+ }
644
+ async abortIntent(transferId) {
645
+ await this.http.request("POST", `/v1/intents/${transferId}/abort`);
646
+ }
647
+ async completeIntent(transferId, signature) {
648
+ await this.http.request(
649
+ "POST",
650
+ `/v1/intents/${transferId}/complete`,
651
+ signature !== void 0 ? { signature } : void 0
652
+ );
653
+ }
654
+ async postProgress(transferId, opIndex, payloadEnvelope, signature) {
655
+ const body = await this.http.request("POST", `/v1/intents/${transferId}/progress`, {
656
+ opIndex,
657
+ payload: payloadEnvelope,
658
+ signature
659
+ });
660
+ return body.record;
661
+ }
662
+ async getProgress(transferId) {
663
+ const body = await this.http.request("GET", `/v1/intents/${transferId}/progress`);
664
+ return body.records;
665
+ }
666
+ // ── mailbox ──────────────────────────────────────────────────────────────
667
+ async deposit(entry) {
668
+ const body = await this.http.request("POST", "/v1/mailbox", entry);
669
+ return body.entryId;
670
+ }
671
+ async depositBatch(entries) {
672
+ const body = await this.http.request("POST", "/v1/mailbox/batch", { entries });
673
+ return body.entries;
674
+ }
675
+ listMailbox(since) {
676
+ const query = since !== void 0 ? `?since=${since}` : "";
677
+ return this.http.request("GET", `/v1/mailbox${query}`);
678
+ }
679
+ claim(entryIds, intoInventory) {
680
+ return this.http.request("POST", "/v1/mailbox/claim", { entryIds, intoInventory });
681
+ }
682
+ async reject(entryIds, reason, detail) {
683
+ const body = await this.http.request("POST", "/v1/mailbox/reject", {
684
+ entryIds,
685
+ ...reason !== void 0 ? { reason } : {},
686
+ ...detail !== void 0 ? { detail } : {}
687
+ });
688
+ return body.rejected;
689
+ }
690
+ // ── history ──────────────────────────────────────────────────────────────
691
+ async postHistory(records) {
692
+ return await this.http.request("POST", "/v1/history", { records });
693
+ }
694
+ listHistory(options = {}) {
695
+ const params = new URLSearchParams();
696
+ if (options.before !== void 0) params.set("before", options.before);
697
+ if (options.limit !== void 0) params.set("limit", String(options.limit));
698
+ const qs = params.toString();
699
+ return this.http.request("GET", `/v1/history${qs ? `?${qs}` : ""}`);
700
+ }
701
+ // ── payment requests ─────────────────────────────────────────────────────
702
+ createPaymentRequest(input) {
703
+ return this.http.request("POST", "/v1/payment-requests", input);
704
+ }
705
+ listPaymentRequests(params) {
706
+ const query = new URLSearchParams();
707
+ query.set("role", params.role);
708
+ if (params.status !== void 0) query.set("status", params.status);
709
+ if (params.role === "incoming") {
710
+ if (params.since !== void 0) query.set("since", String(params.since));
711
+ } else if (params.before !== void 0) {
712
+ query.set("before", params.before);
713
+ }
714
+ return this.http.request("GET", `/v1/payment-requests?${query.toString()}`);
715
+ }
716
+ respondPaymentRequest(id, response) {
717
+ return this.http.request("POST", `/v1/payment-requests/${id}/respond`, response);
718
+ }
719
+ // ── realtime ─────────────────────────────────────────────────────────────
720
+ async wsTicket() {
721
+ const body = await this.http.request("POST", "/v1/ws-ticket");
722
+ return body.ticket;
723
+ }
724
+ };
725
+
726
+ // modules/payments-v2/stores.ts
727
+ var STORE_KEYS = {
728
+ intentBackstop: "intents",
729
+ checkpointCache: "checkpoints",
730
+ deliveryJournal: "delivery-journal",
731
+ mintJournal: "mint-journal",
732
+ shortfalls: "shortfalls",
733
+ settlingLinks: "settling",
734
+ streamCursor: (s) => `cursor:${s}`,
735
+ epochLatch: "epoch-latch"
736
+ };
737
+
738
+ // impl/wallet-api-v2/session.ts
739
+ var AUTH_CHALLENGE_PREFIX = "unicity:wallet-api:auth:v1\n";
740
+ var MAX_CHALLENGE_WINDOW_MS = 60 * 60 * 1e3;
741
+ var ChallengeTemplateError = class extends Error {
742
+ constructor(message) {
743
+ super(message);
744
+ this.name = "ChallengeTemplateError";
745
+ }
746
+ };
747
+ function parseChallengeFields(body) {
748
+ let parsed;
749
+ try {
750
+ parsed = JSON.parse(body);
751
+ } catch {
752
+ throw new ChallengeTemplateError("challenge body is not the single-line JSON object the backend emits");
753
+ }
754
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
755
+ throw new ChallengeTemplateError("challenge body must be a JSON object");
756
+ }
757
+ const fields = {};
758
+ for (const [key, value] of Object.entries(parsed)) {
759
+ if (typeof value !== "string" || value === "") {
760
+ throw new ChallengeTemplateError(`challenge field "${key}" must be a non-empty string`);
761
+ }
762
+ fields[key] = value;
763
+ }
764
+ return fields;
765
+ }
766
+ function requireChallengeField(fields, key) {
767
+ const value = fields[key];
768
+ if (value === void 0) throw new ChallengeTemplateError(`challenge is missing the "${key}" field`);
769
+ return value;
770
+ }
771
+ function verifyChallengeTemplate(challenge, expect) {
772
+ if (!challenge.startsWith(AUTH_CHALLENGE_PREFIX)) {
773
+ throw new ChallengeTemplateError("challenge does not start with the unicity:wallet-api:auth:v1 prefix");
774
+ }
775
+ const fields = parseChallengeFields(challenge.slice(AUTH_CHALLENGE_PREFIX.length));
776
+ if (requireChallengeField(fields, "pubkey").toLowerCase() !== expect.pubkey.toLowerCase()) {
777
+ throw new ChallengeTemplateError("challenge embeds a different pubkey than this wallet");
778
+ }
779
+ if (requireChallengeField(fields, "nonce") !== expect.nonce) {
780
+ throw new ChallengeTemplateError("challenge nonce does not echo the nonce issued with it");
781
+ }
782
+ if (requireChallengeField(fields, "network") !== expect.network) {
783
+ throw new ChallengeTemplateError("challenge is for a different network than this session");
784
+ }
785
+ const issuedAt = Date.parse(requireChallengeField(fields, "issuedAt"));
786
+ const expiresAt = Date.parse(requireChallengeField(fields, "expiresAt"));
787
+ if (Number.isNaN(issuedAt) || Number.isNaN(expiresAt)) {
788
+ throw new ChallengeTemplateError("challenge timestamps are not parseable");
789
+ }
790
+ if (expiresAt <= issuedAt || expiresAt - issuedAt > MAX_CHALLENGE_WINDOW_MS) {
791
+ throw new ChallengeTemplateError("challenge validity window is implausible");
792
+ }
793
+ }
794
+ var JwtGenerationCell = class {
795
+ gen = 0;
796
+ jwt = null;
797
+ get generation() {
798
+ return this.gen;
799
+ }
800
+ token() {
801
+ return this.jwt;
802
+ }
803
+ install(generation, jwt) {
804
+ if (generation !== this.gen) return false;
805
+ this.jwt = jwt;
806
+ return true;
807
+ }
808
+ /** authGone(G) is a no-op when the cell moved to G+1 (F14). */
809
+ clearIfCurrent(generation) {
810
+ if (generation !== this.gen || this.jwt === null) return false;
811
+ this.jwt = null;
812
+ return true;
813
+ }
814
+ dropIfMatches(generation, jwt) {
815
+ if (generation === this.gen && this.jwt === jwt) this.jwt = null;
816
+ }
817
+ bump() {
818
+ this.gen += 1;
819
+ this.jwt = null;
820
+ return this.gen;
821
+ }
822
+ };
823
+ var WAKE_STREAMS = ["inventory", "mailbox", "payment_requests"];
824
+ var DEFAULT_SESSION_TIMING = {
825
+ pullIntervalMs: 3e4,
826
+ reconnectBaseMs: 1e3,
827
+ reconnectCapMs: 3e4,
828
+ heartbeatTimeoutMs: 12e4,
829
+ offlineAfterFailures: 3
830
+ };
831
+ function refreshTokenKey(deviceId) {
832
+ return `auth:refresh:${deviceId}`;
833
+ }
834
+ var WS_CLOSE_AUTH_GONE = 4401;
835
+ function parseWakeFrame(data) {
836
+ if (typeof data !== "string") return null;
837
+ let json;
838
+ try {
839
+ json = JSON.parse(data);
840
+ } catch {
841
+ return null;
842
+ }
843
+ const frame = json;
844
+ if (frame.type !== "wake") return null;
845
+ if (!WAKE_STREAMS.includes(frame.stream)) return null;
846
+ if (typeof frame.syncEpoch !== "number" && typeof frame.syncEpoch !== "string") return null;
847
+ return { stream: frame.stream, syncEpoch: String(frame.syncEpoch) };
848
+ }
849
+ var GLOBAL_TIMERS = {
850
+ setTimeout: (cb, ms) => setTimeout(cb, ms),
851
+ clearTimeout: (h) => clearTimeout(h),
852
+ setInterval: (cb, ms) => setInterval(cb, ms),
853
+ clearInterval: (h) => clearInterval(h)
854
+ };
855
+ var WalletApiSession = class {
856
+ constructor(deps) {
857
+ this.deps = deps;
858
+ this.timing = { ...DEFAULT_SESSION_TIMING, ...deps.timing };
859
+ this.timers = deps.timers ?? GLOBAL_TIMERS;
860
+ this.random = deps.random ?? Math.random;
861
+ this.refreshKey = refreshTokenKey(deps.deviceId);
862
+ }
863
+ timing;
864
+ timers;
865
+ random;
866
+ refreshKey;
867
+ authFlight = null;
868
+ epochLatch = null;
869
+ reseedChain = Promise.resolve();
870
+ reseedsPending = 0;
871
+ handlers = /* @__PURE__ */ new Map();
872
+ socket = null;
873
+ started = false;
874
+ stopped = false;
875
+ reconnectAttempts = 0;
876
+ reconnectTimer = null;
877
+ heartbeatTimer = null;
878
+ pullTimers = [];
879
+ lastStatus = null;
880
+ // ── lifecycle ─────────────────────────────────────────────────────────────
881
+ async start() {
882
+ if (this.started) return;
883
+ this.started = true;
884
+ this.epochLatch = await this.deps.kv.get(STORE_KEYS.epochLatch);
885
+ this.startPullTimers();
886
+ void this.connect();
887
+ }
888
+ async stop() {
889
+ this.stopped = true;
890
+ for (const t of this.pullTimers) this.timers.clearInterval(t);
891
+ this.pullTimers = [];
892
+ if (this.reconnectTimer !== null) this.timers.clearTimeout(this.reconnectTimer);
893
+ this.reconnectTimer = null;
894
+ this.clearHeartbeat();
895
+ const ws = this.socket;
896
+ this.socket = null;
897
+ ws?.close();
898
+ await this.reseedChain;
899
+ }
900
+ // ── auth cell (F8/F14) ────────────────────────────────────────────────────
901
+ token() {
902
+ return this.deps.cell.token();
903
+ }
904
+ /** Identity switch / lock / logout: supersede every in-flight auth continuation. */
905
+ invalidate() {
906
+ this.deps.cell.bump();
907
+ this.authFlight = null;
908
+ }
909
+ async ensureAuthenticated() {
910
+ const existing = this.deps.cell.token();
911
+ if (existing !== null) return existing;
912
+ await this.runAuthSingleFlight();
913
+ const fresh = this.deps.cell.token();
914
+ if (fresh === null) {
915
+ throw new WalletApiHttpError(401, "AUTH_SUPERSEDED", "authentication superseded before completion");
916
+ }
917
+ return fresh;
918
+ }
919
+ /** Run an authenticated op; one 401 → single-flight re-auth → one retry. */
920
+ async withAuth(op) {
921
+ const jwt = await this.ensureAuthenticated();
922
+ const generation = this.deps.cell.generation;
923
+ try {
924
+ return await op(jwt);
925
+ } catch (err) {
926
+ if (!(err instanceof WalletApiHttpError && err.status === 401)) throw err;
927
+ this.deps.cell.dropIfMatches(generation, jwt);
928
+ return op(await this.ensureAuthenticated());
929
+ }
930
+ }
931
+ runAuthSingleFlight() {
932
+ if (this.authFlight !== null) return this.authFlight;
933
+ const generation = this.deps.cell.generation;
934
+ const flight = this.authenticate(generation).finally(() => {
935
+ if (this.authFlight === flight) this.authFlight = null;
936
+ });
937
+ this.authFlight = flight;
938
+ return flight;
939
+ }
940
+ async authenticate(generation) {
941
+ if (await this.tryRefresh(generation)) return;
942
+ if (this.deps.cell.generation !== generation) return;
943
+ await this.challengeSignIn(generation);
944
+ }
945
+ async tryRefresh(generation) {
946
+ const stored = await this.deps.kv.get(this.refreshKey);
947
+ if (stored === null) return false;
948
+ let tokens;
949
+ try {
950
+ tokens = await this.deps.client.authRefresh(stored);
951
+ } catch (err) {
952
+ if (err instanceof WalletApiHttpError && err.status >= 400 && err.status < 500) {
953
+ if (this.deps.cell.generation === generation) await this.deps.kv.remove(this.refreshKey);
954
+ return false;
955
+ }
956
+ throw err;
957
+ }
958
+ if (!this.deps.cell.install(generation, tokens.jwt)) return true;
959
+ await this.deps.kv.set(this.refreshKey, tokens.refreshToken);
960
+ return true;
961
+ }
962
+ async challengeSignIn(generation) {
963
+ const { pubkey, network } = this.deps.signer;
964
+ const { nonce, challenge } = await this.deps.client.authChallenge(pubkey);
965
+ verifyChallengeTemplate(challenge, { pubkey, nonce, network });
966
+ const signature = await this.deps.signer.sign(challenge);
967
+ const tokens = await this.deps.client.authVerify({ nonce, signature, deviceId: this.deps.deviceId });
968
+ if (!this.deps.cell.install(generation, tokens.jwt)) return;
969
+ await this.deps.kv.set(this.refreshKey, tokens.refreshToken);
970
+ }
971
+ // ── epoch latch (F12) ─────────────────────────────────────────────────────
972
+ noteEpoch(epoch) {
973
+ if (this.epochLatch === epoch) return;
974
+ const previous = this.epochLatch;
975
+ this.epochLatch = epoch;
976
+ if (previous === null) {
977
+ void this.deps.kv.set(STORE_KEYS.epochLatch, epoch).catch(() => void 0);
978
+ return;
979
+ }
980
+ this.reseedsPending += 1;
981
+ this.reseedChain = this.reseedChain.then(() => this.runReseed(epoch, previous));
982
+ }
983
+ async runReseed(epoch, previous) {
984
+ try {
985
+ await this.deps.onEpochChange(epoch);
986
+ await this.deps.kv.set(STORE_KEYS.epochLatch, epoch);
987
+ } catch {
988
+ if (this.epochLatch === epoch) this.epochLatch = previous;
989
+ } finally {
990
+ this.reseedsPending -= 1;
991
+ if (this.reseedsPending === 0) this.nudgeAllStreams();
992
+ }
993
+ }
994
+ // ── streams ───────────────────────────────────────────────────────────────
995
+ subscribeStream(stream, handler) {
996
+ let set = this.handlers.get(stream);
997
+ if (!set) {
998
+ set = /* @__PURE__ */ new Set();
999
+ this.handlers.set(stream, set);
1000
+ }
1001
+ set.add(handler);
1002
+ return () => set.delete(handler);
1003
+ }
1004
+ dispatch(stream) {
1005
+ if (this.reseedsPending > 0) return;
1006
+ const set = this.handlers.get(stream);
1007
+ if (!set) return;
1008
+ for (const handler of set) handler();
1009
+ }
1010
+ nudgeAllStreams() {
1011
+ for (const stream of WAKE_STREAMS) this.dispatch(stream);
1012
+ }
1013
+ startPullTimers() {
1014
+ for (const stream of WAKE_STREAMS) {
1015
+ this.pullTimers.push(this.timers.setInterval(() => this.dispatch(stream), this.timing.pullIntervalMs));
1016
+ }
1017
+ }
1018
+ // ── wake socket ───────────────────────────────────────────────────────────
1019
+ status() {
1020
+ return this.lastStatus ?? "offline";
1021
+ }
1022
+ emitStatus(status) {
1023
+ if (this.stopped || this.lastStatus === status) return;
1024
+ this.lastStatus = status;
1025
+ this.deps.emitStatus(status);
1026
+ }
1027
+ async connect() {
1028
+ if (this.stopped) return;
1029
+ try {
1030
+ const ticket = await this.withAuth(() => this.deps.client.wsTicket());
1031
+ if (this.stopped) return;
1032
+ this.openSocket(ticket, this.deps.cell.generation);
1033
+ } catch {
1034
+ this.scheduleReconnect();
1035
+ }
1036
+ }
1037
+ openSocket(ticket, generation) {
1038
+ const wsBase = this.deps.client.baseUrl.replace(/^http/, "ws");
1039
+ const ws = this.deps.webSocketFactory(`${wsBase}/v1/ws?ticket=${encodeURIComponent(ticket)}`);
1040
+ this.socket = ws;
1041
+ ws.onopen = () => this.handleOpen(ws);
1042
+ ws.onmessage = (ev) => this.handleMessage(ws, ev.data);
1043
+ ws.onclose = (ev) => this.handleClose(ws, generation, ev?.code);
1044
+ ws.onerror = () => void 0;
1045
+ }
1046
+ handleOpen(ws) {
1047
+ if (ws !== this.socket) return;
1048
+ this.reconnectAttempts = 0;
1049
+ this.emitStatus("connected");
1050
+ this.armHeartbeat(ws);
1051
+ this.nudgeAllStreams();
1052
+ }
1053
+ handleMessage(ws, data) {
1054
+ if (ws !== this.socket) return;
1055
+ this.armHeartbeat(ws);
1056
+ const frame = parseWakeFrame(data);
1057
+ if (frame === null) return;
1058
+ this.noteEpoch(frame.syncEpoch);
1059
+ this.dispatch(frame.stream);
1060
+ }
1061
+ handleClose(ws, generation, code) {
1062
+ if (ws !== this.socket) return;
1063
+ this.socket = null;
1064
+ this.clearHeartbeat();
1065
+ if (this.stopped) return;
1066
+ if (code === WS_CLOSE_AUTH_GONE) {
1067
+ this.deps.cell.clearIfCurrent(generation);
1068
+ this.emitStatus("degraded");
1069
+ void this.connect();
1070
+ return;
1071
+ }
1072
+ this.scheduleReconnect();
1073
+ }
1074
+ scheduleReconnect() {
1075
+ if (this.stopped) return;
1076
+ this.reconnectAttempts += 1;
1077
+ this.emitStatus(this.reconnectAttempts >= this.timing.offlineAfterFailures ? "offline" : "degraded");
1078
+ const capped = Math.min(
1079
+ this.timing.reconnectCapMs,
1080
+ this.timing.reconnectBaseMs * 2 ** (this.reconnectAttempts - 1)
1081
+ );
1082
+ const delay = Math.floor(this.random() * capped);
1083
+ this.reconnectTimer = this.timers.setTimeout(() => void this.connect(), delay);
1084
+ }
1085
+ armHeartbeat(ws) {
1086
+ this.clearHeartbeat();
1087
+ this.heartbeatTimer = this.timers.setTimeout(() => {
1088
+ if (ws === this.socket) ws.close();
1089
+ }, this.timing.heartbeatTimeoutMs);
1090
+ }
1091
+ clearHeartbeat() {
1092
+ if (this.heartbeatTimer !== null) this.timers.clearTimeout(this.heartbeatTimer);
1093
+ this.heartbeatTimer = null;
1094
+ }
1095
+ };
1096
+
1097
+ // impl/wallet-api-v2/storage.ts
1098
+ var WALLET_API_V2_FANOUT_WIDTH = 8;
1099
+ var DeltaConflictError = class extends Error {
1100
+ constructor(message, cause) {
1101
+ super(message);
1102
+ this.cause = cause;
1103
+ this.name = "DeltaConflictError";
1104
+ }
1105
+ code = "DELTA_CONFLICT";
1106
+ };
1107
+ var DeltaValidationError = class extends Error {
1108
+ constructor(message, cause) {
1109
+ super(message);
1110
+ this.cause = cause;
1111
+ this.name = "DeltaValidationError";
1112
+ }
1113
+ code = "DELTA_VALIDATION";
1114
+ };
1115
+ var StoragePortProtocolError = class extends Error {
1116
+ code = "PROTOCOL";
1117
+ constructor(message) {
1118
+ super(message);
1119
+ this.name = "StoragePortProtocolError";
1120
+ }
1121
+ };
1122
+ async function mapBounded(items, width, fn) {
1123
+ const out = new Array(items.length);
1124
+ let next = 0;
1125
+ let failed = false;
1126
+ const worker = async () => {
1127
+ for (; ; ) {
1128
+ if (failed) return;
1129
+ const index = next;
1130
+ next += 1;
1131
+ if (index >= items.length) return;
1132
+ try {
1133
+ out[index] = await fn(items[index], index);
1134
+ } catch (err) {
1135
+ failed = true;
1136
+ throw err;
1137
+ }
1138
+ }
1139
+ };
1140
+ const workers = Array.from({ length: Math.max(1, Math.min(width, items.length)) }, worker);
1141
+ await Promise.all(workers);
1142
+ return out;
1143
+ }
1144
+ var WalletApiStoragePort = class {
1145
+ constructor(client) {
1146
+ this.client = client;
1147
+ }
1148
+ async listInventory(since) {
1149
+ const page = await this.client.listInventory(since);
1150
+ return {
1151
+ cursor: page.cursor,
1152
+ syncEpoch: String(page.syncEpoch),
1153
+ more: page.more,
1154
+ items: page.items
1155
+ };
1156
+ }
1157
+ balances() {
1158
+ return this.client.balances();
1159
+ }
1160
+ async getBlobs(tokenIds) {
1161
+ if (tokenIds.length === 0) return /* @__PURE__ */ new Map();
1162
+ const urls = await this.client.blobUrls(tokenIds);
1163
+ const bytes = await mapBounded(urls, WALLET_API_V2_FANOUT_WIDTH, (u) => this.client.fetchBlob(u.getUrl));
1164
+ const result = /* @__PURE__ */ new Map();
1165
+ for (const [i, url] of urls.entries()) {
1166
+ const blob = bytes[i];
1167
+ if (blob !== void 0) result.set(url.tokenId, blob);
1168
+ }
1169
+ return result;
1170
+ }
1171
+ async uploadBlobs(blobs) {
1172
+ if (blobs.length === 0) return /* @__PURE__ */ new Map();
1173
+ const urls = await this.client.uploadUrls(blobs.map((b) => ({ sha256: b.sha256, size: b.bytes.length })));
1174
+ const urlBySha = new Map(urls.map((u) => [u.sha256, u]));
1175
+ const uploads = blobs.map((blob) => {
1176
+ const url = urlBySha.get(blob.sha256);
1177
+ if (url === void 0) {
1178
+ throw new StoragePortProtocolError(`upload-urls response missing sha256 ${blob.sha256}`);
1179
+ }
1180
+ return { blob, url };
1181
+ });
1182
+ await mapBounded(
1183
+ uploads,
1184
+ WALLET_API_V2_FANOUT_WIDTH,
1185
+ ({ blob, url }) => this.client.uploadBlob(url.putUrl, blob.bytes)
1186
+ );
1187
+ return new Map(uploads.map(({ blob, url }) => [blob.sha256, url.key]));
1188
+ }
1189
+ async applyDelta(delta) {
1190
+ try {
1191
+ const result = await this.client.apply(delta);
1192
+ return { cursor: result.cursor, syncEpoch: String(result.syncEpoch) };
1193
+ } catch (err) {
1194
+ if (isWalletApiHttpError(err, 409)) throw new DeltaConflictError(err.message, err);
1195
+ if (isWalletApiHttpError(err, 422)) throw new DeltaValidationError(err.message, err);
1196
+ throw err;
1197
+ }
1198
+ }
1199
+ };
1200
+
1201
+ // node_modules/@noble/hashes/hmac.js
1202
+ var _HMAC = class {
1203
+ oHash;
1204
+ iHash;
1205
+ blockLen;
1206
+ outputLen;
1207
+ canXOF = false;
1208
+ finished = false;
1209
+ destroyed = false;
1210
+ constructor(hash, key) {
1211
+ ahash(hash);
1212
+ abytes(key, void 0, "key");
1213
+ this.iHash = hash.create();
1214
+ if (typeof this.iHash.update !== "function")
1215
+ throw new Error("Expected instance of class which extends utils.Hash");
1216
+ this.blockLen = this.iHash.blockLen;
1217
+ this.outputLen = this.iHash.outputLen;
1218
+ const blockLen = this.blockLen;
1219
+ const pad = new Uint8Array(blockLen);
1220
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
1221
+ for (let i = 0; i < pad.length; i++)
1222
+ pad[i] ^= 54;
1223
+ this.iHash.update(pad);
1224
+ this.oHash = hash.create();
1225
+ for (let i = 0; i < pad.length; i++)
1226
+ pad[i] ^= 54 ^ 92;
1227
+ this.oHash.update(pad);
1228
+ clean(pad);
1229
+ }
1230
+ update(buf) {
1231
+ aexists(this);
1232
+ this.iHash.update(buf);
1233
+ return this;
1234
+ }
1235
+ digestInto(out) {
1236
+ aexists(this);
1237
+ aoutput(out, this);
1238
+ this.finished = true;
1239
+ const buf = out.subarray(0, this.outputLen);
1240
+ this.iHash.digestInto(buf);
1241
+ this.oHash.update(buf);
1242
+ this.oHash.digestInto(buf);
1243
+ this.destroy();
1244
+ }
1245
+ digest() {
1246
+ const out = new Uint8Array(this.oHash.outputLen);
1247
+ this.digestInto(out);
1248
+ return out;
1249
+ }
1250
+ _cloneInto(to) {
1251
+ to ||= Object.create(Object.getPrototypeOf(this), {});
1252
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
1253
+ to = to;
1254
+ to.finished = finished;
1255
+ to.destroyed = destroyed;
1256
+ to.blockLen = blockLen;
1257
+ to.outputLen = outputLen;
1258
+ to.oHash = oHash._cloneInto(to.oHash);
1259
+ to.iHash = iHash._cloneInto(to.iHash);
1260
+ return to;
1261
+ }
1262
+ clone() {
1263
+ return this._cloneInto();
1264
+ }
1265
+ destroy() {
1266
+ this.destroyed = true;
1267
+ this.oHash.destroy();
1268
+ this.iHash.destroy();
1269
+ }
1270
+ };
1271
+ var hmac = /* @__PURE__ */ (() => {
1272
+ const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());
1273
+ hmac_.create = (hash, key) => new _HMAC(hash, key);
1274
+ return hmac_;
1275
+ })();
1276
+
1277
+ // node_modules/@noble/hashes/hkdf.js
1278
+ function extract(hash, ikm, salt) {
1279
+ ahash(hash);
1280
+ if (salt === void 0)
1281
+ salt = new Uint8Array(hash.outputLen);
1282
+ return hmac(hash, salt, ikm);
1283
+ }
1284
+ var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);
1285
+ var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
1286
+ function expand(hash, prk, info, length = 32) {
1287
+ ahash(hash);
1288
+ anumber(length, "length");
1289
+ abytes(prk, void 0, "prk");
1290
+ const olen = hash.outputLen;
1291
+ if (prk.length < olen)
1292
+ throw new Error('"prk" must be at least HashLen octets');
1293
+ if (length > 255 * olen)
1294
+ throw new Error("Length must be <= 255*HashLen");
1295
+ const blocks = Math.ceil(length / olen);
1296
+ if (info === void 0)
1297
+ info = EMPTY_BUFFER;
1298
+ else
1299
+ abytes(info, void 0, "info");
1300
+ const okm = new Uint8Array(blocks * olen);
1301
+ const HMAC = hmac.create(hash, prk);
1302
+ const HMACTmp = HMAC._cloneInto();
1303
+ const T = new Uint8Array(HMAC.outputLen);
1304
+ for (let counter = 0; counter < blocks; counter++) {
1305
+ HKDF_COUNTER[0] = counter + 1;
1306
+ HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info).update(HKDF_COUNTER).digestInto(T);
1307
+ okm.set(T, olen * counter);
1308
+ HMAC._cloneInto(HMACTmp);
1309
+ }
1310
+ HMAC.destroy();
1311
+ HMACTmp.destroy();
1312
+ clean(T, HKDF_COUNTER);
1313
+ return okm.slice(0, length);
1314
+ }
1315
+ var hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
1316
+
1317
+ // node_modules/@noble/curves/utils.js
1318
+ var abytes2 = (value, length, title) => abytes(value, length, title);
1319
+ var anumber2 = anumber;
1320
+ var bytesToHex2 = bytesToHex;
1321
+ var concatBytes2 = (...arrays) => concatBytes(...arrays);
1322
+ var hexToBytes2 = (hex) => hexToBytes(hex);
1323
+ var isBytes2 = isBytes;
1324
+ var randomBytes2 = (bytesLength) => randomBytes(bytesLength);
1325
+ var _0n = /* @__PURE__ */ BigInt(0);
1326
+ var _1n = /* @__PURE__ */ BigInt(1);
1327
+ function abool(value, title = "") {
1328
+ if (typeof value !== "boolean") {
1329
+ const prefix = title && `"${title}" `;
1330
+ throw new TypeError(prefix + "expected boolean, got type=" + typeof value);
1331
+ }
1332
+ return value;
1333
+ }
1334
+ function abignumber(n) {
1335
+ if (typeof n === "bigint") {
1336
+ if (!isPosBig(n))
1337
+ throw new RangeError("positive bigint expected, got " + n);
1338
+ } else
1339
+ anumber2(n);
1340
+ return n;
1341
+ }
1342
+ function asafenumber(value, title = "") {
1343
+ if (typeof value !== "number") {
1344
+ const prefix = title && `"${title}" `;
1345
+ throw new TypeError(prefix + "expected number, got type=" + typeof value);
1346
+ }
1347
+ if (!Number.isSafeInteger(value)) {
1348
+ const prefix = title && `"${title}" `;
1349
+ throw new RangeError(prefix + "expected safe integer, got " + value);
1350
+ }
1351
+ }
1352
+ function numberToHexUnpadded(num) {
1353
+ const hex = abignumber(num).toString(16);
1354
+ return hex.length & 1 ? "0" + hex : hex;
1355
+ }
1356
+ function hexToNumber(hex) {
1357
+ if (typeof hex !== "string")
1358
+ throw new TypeError("hex string expected, got " + typeof hex);
1359
+ return hex === "" ? _0n : BigInt("0x" + hex);
1360
+ }
1361
+ function bytesToNumberBE(bytes) {
1362
+ return hexToNumber(bytesToHex(bytes));
1363
+ }
1364
+ function bytesToNumberLE(bytes) {
1365
+ return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
1366
+ }
1367
+ function numberToBytesBE(n, len) {
1368
+ anumber(len);
1369
+ if (len === 0)
1370
+ throw new RangeError("zero length");
1371
+ n = abignumber(n);
1372
+ const hex = n.toString(16);
1373
+ if (hex.length > len * 2)
1374
+ throw new RangeError("number too large");
1375
+ return hexToBytes(hex.padStart(len * 2, "0"));
1376
+ }
1377
+ function numberToBytesLE(n, len) {
1378
+ return numberToBytesBE(n, len).reverse();
1379
+ }
1380
+ function copyBytes(bytes) {
1381
+ return Uint8Array.from(abytes2(bytes));
1382
+ }
1383
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
1384
+ function inRange(n, min, max) {
1385
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
1386
+ }
1387
+ function aInRange(title, n, min, max) {
1388
+ if (!inRange(n, min, max))
1389
+ throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
1390
+ }
1391
+ function bitLen(n) {
1392
+ if (n < _0n)
1393
+ throw new Error("expected non-negative bigint, got " + n);
1394
+ let len;
1395
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
1396
+ ;
1397
+ return len;
1398
+ }
1399
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
1400
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
1401
+ anumber(hashLen, "hashLen");
1402
+ anumber(qByteLen, "qByteLen");
1403
+ if (typeof hmacFn !== "function")
1404
+ throw new TypeError("hmacFn must be a function");
1405
+ const u8n = (len) => new Uint8Array(len);
1406
+ const NULL = Uint8Array.of();
1407
+ const byte0 = Uint8Array.of(0);
1408
+ const byte1 = Uint8Array.of(1);
1409
+ const _maxDrbgIters = 1e3;
1410
+ let v = u8n(hashLen);
1411
+ let k = u8n(hashLen);
1412
+ let i = 0;
1413
+ const reset = () => {
1414
+ v.fill(1);
1415
+ k.fill(0);
1416
+ i = 0;
1417
+ };
1418
+ const h = (...msgs) => hmacFn(k, concatBytes2(v, ...msgs));
1419
+ const reseed = (seed = NULL) => {
1420
+ k = h(byte0, seed);
1421
+ v = h();
1422
+ if (seed.length === 0)
1423
+ return;
1424
+ k = h(byte1, seed);
1425
+ v = h();
1426
+ };
1427
+ const gen = () => {
1428
+ if (i++ >= _maxDrbgIters)
1429
+ throw new Error("drbg: tried max amount of iterations");
1430
+ let len = 0;
1431
+ const out = [];
1432
+ while (len < qByteLen) {
1433
+ v = h();
1434
+ const sl = v.slice();
1435
+ out.push(sl);
1436
+ len += v.length;
1437
+ }
1438
+ return concatBytes2(...out);
1439
+ };
1440
+ const genUntil = (seed, pred) => {
1441
+ reset();
1442
+ reseed(seed);
1443
+ let res = void 0;
1444
+ while ((res = pred(gen())) === void 0)
1445
+ reseed();
1446
+ reset();
1447
+ return res;
1448
+ };
1449
+ return genUntil;
1450
+ }
1451
+ function validateObject(object, fields = {}, optFields = {}) {
1452
+ if (Object.prototype.toString.call(object) !== "[object Object]")
1453
+ throw new TypeError("expected valid options object");
1454
+ function checkField(fieldName, expectedType, isOpt) {
1455
+ if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName))
1456
+ throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
1457
+ const val = object[fieldName];
1458
+ if (isOpt && val === void 0)
1459
+ return;
1460
+ const current = typeof val;
1461
+ if (current !== expectedType || val === null)
1462
+ throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
1463
+ }
1464
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
1465
+ iter(fields, false);
1466
+ iter(optFields, true);
1467
+ }
1468
+
1469
+ // node_modules/@noble/curves/abstract/modular.js
1470
+ var _0n2 = /* @__PURE__ */ BigInt(0);
1471
+ var _1n2 = /* @__PURE__ */ BigInt(1);
1472
+ var _2n = /* @__PURE__ */ BigInt(2);
1473
+ var _3n = /* @__PURE__ */ BigInt(3);
1474
+ var _4n = /* @__PURE__ */ BigInt(4);
1475
+ var _5n = /* @__PURE__ */ BigInt(5);
1476
+ var _7n = /* @__PURE__ */ BigInt(7);
1477
+ var _8n = /* @__PURE__ */ BigInt(8);
1478
+ var _9n = /* @__PURE__ */ BigInt(9);
1479
+ var _16n = /* @__PURE__ */ BigInt(16);
1480
+ function mod(a, b) {
1481
+ if (b <= _0n2)
1482
+ throw new Error("mod: expected positive modulus, got " + b);
1483
+ const result = a % b;
1484
+ return result >= _0n2 ? result : b + result;
1485
+ }
1486
+ function pow2(x, power, modulo) {
1487
+ if (power < _0n2)
1488
+ throw new Error("pow2: expected non-negative exponent, got " + power);
1489
+ let res = x;
1490
+ while (power-- > _0n2) {
1491
+ res *= res;
1492
+ res %= modulo;
1493
+ }
1494
+ return res;
1495
+ }
1496
+ function invert(number, modulo) {
1497
+ if (number === _0n2)
1498
+ throw new Error("invert: expected non-zero number");
1499
+ if (modulo <= _0n2)
1500
+ throw new Error("invert: expected positive modulus, got " + modulo);
1501
+ let a = mod(number, modulo);
1502
+ let b = modulo;
1503
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
1504
+ while (a !== _0n2) {
1505
+ const q = b / a;
1506
+ const r = b - a * q;
1507
+ const m = x - u * q;
1508
+ const n = y - v * q;
1509
+ b = a, a = r, x = u, y = v, u = m, v = n;
1510
+ }
1511
+ const gcd = b;
1512
+ if (gcd !== _1n2)
1513
+ throw new Error("invert: does not exist");
1514
+ return mod(x, modulo);
1515
+ }
1516
+ function assertIsSquare(Fp, root, n) {
1517
+ const F = Fp;
1518
+ if (!F.eql(F.sqr(root), n))
1519
+ throw new Error("Cannot find square root");
1520
+ }
1521
+ function sqrt3mod4(Fp, n) {
1522
+ const F = Fp;
1523
+ const p1div4 = (F.ORDER + _1n2) / _4n;
1524
+ const root = F.pow(n, p1div4);
1525
+ assertIsSquare(F, root, n);
1526
+ return root;
1527
+ }
1528
+ function sqrt5mod8(Fp, n) {
1529
+ const F = Fp;
1530
+ const p5div8 = (F.ORDER - _5n) / _8n;
1531
+ const n2 = F.mul(n, _2n);
1532
+ const v = F.pow(n2, p5div8);
1533
+ const nv = F.mul(n, v);
1534
+ const i = F.mul(F.mul(nv, _2n), v);
1535
+ const root = F.mul(nv, F.sub(i, F.ONE));
1536
+ assertIsSquare(F, root, n);
1537
+ return root;
1538
+ }
1539
+ function sqrt9mod16(P) {
1540
+ const Fp_ = Field(P);
1541
+ const tn = tonelliShanks(P);
1542
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
1543
+ const c2 = tn(Fp_, c1);
1544
+ const c3 = tn(Fp_, Fp_.neg(c1));
1545
+ const c4 = (P + _7n) / _16n;
1546
+ return ((Fp, n) => {
1547
+ const F = Fp;
1548
+ let tv1 = F.pow(n, c4);
1549
+ let tv2 = F.mul(tv1, c1);
1550
+ const tv3 = F.mul(tv1, c2);
1551
+ const tv4 = F.mul(tv1, c3);
1552
+ const e1 = F.eql(F.sqr(tv2), n);
1553
+ const e2 = F.eql(F.sqr(tv3), n);
1554
+ tv1 = F.cmov(tv1, tv2, e1);
1555
+ tv2 = F.cmov(tv4, tv3, e2);
1556
+ const e3 = F.eql(F.sqr(tv2), n);
1557
+ const root = F.cmov(tv1, tv2, e3);
1558
+ assertIsSquare(F, root, n);
1559
+ return root;
1560
+ });
1561
+ }
1562
+ function tonelliShanks(P) {
1563
+ if (P < _3n)
1564
+ throw new Error("sqrt is not defined for small field");
1565
+ let Q = P - _1n2;
1566
+ let S = 0;
1567
+ while (Q % _2n === _0n2) {
1568
+ Q /= _2n;
1569
+ S++;
1570
+ }
1571
+ let Z = _2n;
1572
+ const _Fp = Field(P);
1573
+ while (FpLegendre(_Fp, Z) === 1) {
1574
+ if (Z++ > 1e3)
1575
+ throw new Error("Cannot find square root: probably non-prime P");
1576
+ }
1577
+ if (S === 1)
1578
+ return sqrt3mod4;
1579
+ let cc = _Fp.pow(Z, Q);
1580
+ const Q1div2 = (Q + _1n2) / _2n;
1581
+ return function tonelliSlow(Fp, n) {
1582
+ const F = Fp;
1583
+ if (F.is0(n))
1584
+ return n;
1585
+ if (FpLegendre(F, n) !== 1)
1586
+ throw new Error("Cannot find square root");
1587
+ let M = S;
1588
+ let c = F.mul(F.ONE, cc);
1589
+ let t = F.pow(n, Q);
1590
+ let R = F.pow(n, Q1div2);
1591
+ while (!F.eql(t, F.ONE)) {
1592
+ if (F.is0(t))
1593
+ return F.ZERO;
1594
+ let i = 1;
1595
+ let t_tmp = F.sqr(t);
1596
+ while (!F.eql(t_tmp, F.ONE)) {
1597
+ i++;
1598
+ t_tmp = F.sqr(t_tmp);
1599
+ if (i === M)
1600
+ throw new Error("Cannot find square root");
1601
+ }
1602
+ const exponent = _1n2 << BigInt(M - i - 1);
1603
+ const b = F.pow(c, exponent);
1604
+ M = i;
1605
+ c = F.sqr(b);
1606
+ t = F.mul(t, c);
1607
+ R = F.mul(R, b);
1608
+ }
1609
+ return R;
1610
+ };
1611
+ }
1612
+ function FpSqrt(P) {
1613
+ if (P % _4n === _3n)
1614
+ return sqrt3mod4;
1615
+ if (P % _8n === _5n)
1616
+ return sqrt5mod8;
1617
+ if (P % _16n === _9n)
1618
+ return sqrt9mod16(P);
1619
+ return tonelliShanks(P);
1620
+ }
1621
+ var FIELD_FIELDS = [
1622
+ "create",
1623
+ "isValid",
1624
+ "is0",
1625
+ "neg",
1626
+ "inv",
1627
+ "sqrt",
1628
+ "sqr",
1629
+ "eql",
1630
+ "add",
1631
+ "sub",
1632
+ "mul",
1633
+ "pow",
1634
+ "div",
1635
+ "addN",
1636
+ "subN",
1637
+ "mulN",
1638
+ "sqrN"
1639
+ ];
1640
+ function validateField(field) {
1641
+ const initial = {
1642
+ ORDER: "bigint",
1643
+ BYTES: "number",
1644
+ BITS: "number"
1645
+ };
1646
+ const opts = FIELD_FIELDS.reduce((map, val) => {
1647
+ map[val] = "function";
1648
+ return map;
1649
+ }, initial);
1650
+ validateObject(field, opts);
1651
+ asafenumber(field.BYTES, "BYTES");
1652
+ asafenumber(field.BITS, "BITS");
1653
+ if (field.BYTES < 1 || field.BITS < 1)
1654
+ throw new Error("invalid field: expected BYTES/BITS > 0");
1655
+ if (field.ORDER <= _1n2)
1656
+ throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
1657
+ return field;
1658
+ }
1659
+ function FpPow(Fp, num, power) {
1660
+ const F = Fp;
1661
+ if (power < _0n2)
1662
+ throw new Error("invalid exponent, negatives unsupported");
1663
+ if (power === _0n2)
1664
+ return F.ONE;
1665
+ if (power === _1n2)
1666
+ return num;
1667
+ let p = F.ONE;
1668
+ let d = num;
1669
+ while (power > _0n2) {
1670
+ if (power & _1n2)
1671
+ p = F.mul(p, d);
1672
+ d = F.sqr(d);
1673
+ power >>= _1n2;
1674
+ }
1675
+ return p;
1676
+ }
1677
+ function FpInvertBatch(Fp, nums, passZero = false) {
1678
+ const F = Fp;
1679
+ const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
1680
+ const multipliedAcc = nums.reduce((acc, num, i) => {
1681
+ if (F.is0(num))
1682
+ return acc;
1683
+ inverted[i] = acc;
1684
+ return F.mul(acc, num);
1685
+ }, F.ONE);
1686
+ const invertedAcc = F.inv(multipliedAcc);
1687
+ nums.reduceRight((acc, num, i) => {
1688
+ if (F.is0(num))
1689
+ return acc;
1690
+ inverted[i] = F.mul(acc, inverted[i]);
1691
+ return F.mul(acc, num);
1692
+ }, invertedAcc);
1693
+ return inverted;
1694
+ }
1695
+ function FpLegendre(Fp, n) {
1696
+ const F = Fp;
1697
+ const p1mod2 = (F.ORDER - _1n2) / _2n;
1698
+ const powered = F.pow(n, p1mod2);
1699
+ const yes = F.eql(powered, F.ONE);
1700
+ const zero = F.eql(powered, F.ZERO);
1701
+ const no = F.eql(powered, F.neg(F.ONE));
1702
+ if (!yes && !zero && !no)
1703
+ throw new Error("invalid Legendre symbol result");
1704
+ return yes ? 1 : zero ? 0 : -1;
1705
+ }
1706
+ function nLength(n, nBitLength) {
1707
+ if (nBitLength !== void 0)
1708
+ anumber2(nBitLength);
1709
+ if (n <= _0n2)
1710
+ throw new Error("invalid n length: expected positive n, got " + n);
1711
+ if (nBitLength !== void 0 && nBitLength < 1)
1712
+ throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
1713
+ const bits = bitLen(n);
1714
+ if (nBitLength !== void 0 && nBitLength < bits)
1715
+ throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
1716
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
1717
+ const nByteLength = Math.ceil(_nBitLength / 8);
1718
+ return { nBitLength: _nBitLength, nByteLength };
1719
+ }
1720
+ var FIELD_SQRT = /* @__PURE__ */ new WeakMap();
1721
+ var _Field = class {
1722
+ ORDER;
1723
+ BITS;
1724
+ BYTES;
1725
+ isLE;
1726
+ ZERO = _0n2;
1727
+ ONE = _1n2;
1728
+ _lengths;
1729
+ _mod;
1730
+ constructor(ORDER, opts = {}) {
1731
+ if (ORDER <= _1n2)
1732
+ throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
1733
+ let _nbitLength = void 0;
1734
+ this.isLE = false;
1735
+ if (opts != null && typeof opts === "object") {
1736
+ if (typeof opts.BITS === "number")
1737
+ _nbitLength = opts.BITS;
1738
+ if (typeof opts.sqrt === "function")
1739
+ Object.defineProperty(this, "sqrt", { value: opts.sqrt, enumerable: true });
1740
+ if (typeof opts.isLE === "boolean")
1741
+ this.isLE = opts.isLE;
1742
+ if (opts.allowedLengths)
1743
+ this._lengths = Object.freeze(opts.allowedLengths.slice());
1744
+ if (typeof opts.modFromBytes === "boolean")
1745
+ this._mod = opts.modFromBytes;
1746
+ }
1747
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
1748
+ if (nByteLength > 2048)
1749
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
1750
+ this.ORDER = ORDER;
1751
+ this.BITS = nBitLength;
1752
+ this.BYTES = nByteLength;
1753
+ Object.freeze(this);
1754
+ }
1755
+ create(num) {
1756
+ return mod(num, this.ORDER);
1757
+ }
1758
+ isValid(num) {
1759
+ if (typeof num !== "bigint")
1760
+ throw new TypeError("invalid field element: expected bigint, got " + typeof num);
1761
+ return _0n2 <= num && num < this.ORDER;
1762
+ }
1763
+ is0(num) {
1764
+ return num === _0n2;
1765
+ }
1766
+ // is valid and invertible
1767
+ isValidNot0(num) {
1768
+ return !this.is0(num) && this.isValid(num);
1769
+ }
1770
+ isOdd(num) {
1771
+ return (num & _1n2) === _1n2;
1772
+ }
1773
+ neg(num) {
1774
+ return mod(-num, this.ORDER);
1775
+ }
1776
+ eql(lhs, rhs) {
1777
+ return lhs === rhs;
1778
+ }
1779
+ sqr(num) {
1780
+ return mod(num * num, this.ORDER);
1781
+ }
1782
+ add(lhs, rhs) {
1783
+ return mod(lhs + rhs, this.ORDER);
1784
+ }
1785
+ sub(lhs, rhs) {
1786
+ return mod(lhs - rhs, this.ORDER);
1787
+ }
1788
+ mul(lhs, rhs) {
1789
+ return mod(lhs * rhs, this.ORDER);
1790
+ }
1791
+ pow(num, power) {
1792
+ return FpPow(this, num, power);
1793
+ }
1794
+ div(lhs, rhs) {
1795
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
1796
+ }
1797
+ // Same as above, but doesn't normalize
1798
+ sqrN(num) {
1799
+ return num * num;
1800
+ }
1801
+ addN(lhs, rhs) {
1802
+ return lhs + rhs;
1803
+ }
1804
+ subN(lhs, rhs) {
1805
+ return lhs - rhs;
1806
+ }
1807
+ mulN(lhs, rhs) {
1808
+ return lhs * rhs;
1809
+ }
1810
+ inv(num) {
1811
+ return invert(num, this.ORDER);
1812
+ }
1813
+ sqrt(num) {
1814
+ let sqrt = FIELD_SQRT.get(this);
1815
+ if (!sqrt)
1816
+ FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
1817
+ return sqrt(this, num);
1818
+ }
1819
+ toBytes(num) {
1820
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
1821
+ }
1822
+ fromBytes(bytes, skipValidation = false) {
1823
+ abytes2(bytes);
1824
+ const { _lengths: allowedLengths, BYTES, isLE: isLE2, ORDER, _mod: modFromBytes } = this;
1825
+ if (allowedLengths) {
1826
+ if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
1827
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
1828
+ }
1829
+ const padded = new Uint8Array(BYTES);
1830
+ padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
1831
+ bytes = padded;
1832
+ }
1833
+ if (bytes.length !== BYTES)
1834
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
1835
+ let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1836
+ if (modFromBytes)
1837
+ scalar = mod(scalar, ORDER);
1838
+ if (!skipValidation) {
1839
+ if (!this.isValid(scalar))
1840
+ throw new Error("invalid field element: outside of range 0..ORDER");
1841
+ }
1842
+ return scalar;
1843
+ }
1844
+ // TODO: we don't need it here, move out to separate fn
1845
+ invertBatch(lst) {
1846
+ return FpInvertBatch(this, lst);
1847
+ }
1848
+ // We can't move this out because Fp6, Fp12 implement it
1849
+ // and it's unclear what to return in there.
1850
+ cmov(a, b, condition) {
1851
+ abool(condition, "condition");
1852
+ return condition ? b : a;
1853
+ }
1854
+ };
1855
+ Object.freeze(_Field.prototype);
1856
+ function Field(ORDER, opts = {}) {
1857
+ return new _Field(ORDER, opts);
1858
+ }
1859
+ function getFieldBytesLength(fieldOrder) {
1860
+ if (typeof fieldOrder !== "bigint")
1861
+ throw new Error("field order must be bigint");
1862
+ if (fieldOrder <= _1n2)
1863
+ throw new Error("field order must be greater than 1");
1864
+ const bitLength = bitLen(fieldOrder - _1n2);
1865
+ return Math.ceil(bitLength / 8);
1866
+ }
1867
+ function getMinHashLength(fieldOrder) {
1868
+ const length = getFieldBytesLength(fieldOrder);
1869
+ return length + Math.ceil(length / 2);
1870
+ }
1871
+ function mapHashToField(key, fieldOrder, isLE2 = false) {
1872
+ abytes2(key);
1873
+ const len = key.length;
1874
+ const fieldLen = getFieldBytesLength(fieldOrder);
1875
+ const minLen = Math.max(getMinHashLength(fieldOrder), 16);
1876
+ if (len < minLen || len > 1024)
1877
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
1878
+ const num = isLE2 ? bytesToNumberLE(key) : bytesToNumberBE(key);
1879
+ const reduced = mod(num, fieldOrder - _1n2) + _1n2;
1880
+ return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
1881
+ }
1882
+
1883
+ // node_modules/@noble/curves/abstract/curve.js
1884
+ var _0n3 = /* @__PURE__ */ BigInt(0);
1885
+ var _1n3 = /* @__PURE__ */ BigInt(1);
1886
+ function negateCt(condition, item) {
1887
+ const neg = item.negate();
1888
+ return condition ? neg : item;
1889
+ }
1890
+ function normalizeZ(c, points) {
1891
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
1892
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
1893
+ }
1894
+ function validateW(W, bits) {
1895
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
1896
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
1897
+ }
1898
+ function calcWOpts(W, scalarBits) {
1899
+ validateW(W, scalarBits);
1900
+ const windows = Math.ceil(scalarBits / W) + 1;
1901
+ const windowSize = 2 ** (W - 1);
1902
+ const maxNumber = 2 ** W;
1903
+ const mask = bitMask(W);
1904
+ const shiftBy = BigInt(W);
1905
+ return { windows, windowSize, mask, maxNumber, shiftBy };
1906
+ }
1907
+ function calcOffsets(n, window, wOpts) {
1908
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
1909
+ let wbits = Number(n & mask);
1910
+ let nextN = n >> shiftBy;
1911
+ if (wbits > windowSize) {
1912
+ wbits -= maxNumber;
1913
+ nextN += _1n3;
1914
+ }
1915
+ const offsetStart = window * windowSize;
1916
+ const offset = offsetStart + Math.abs(wbits) - 1;
1917
+ const isZero = wbits === 0;
1918
+ const isNeg = wbits < 0;
1919
+ const isNegF = window % 2 !== 0;
1920
+ const offsetF = offsetStart;
1921
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
1922
+ }
1923
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
1924
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
1925
+ function getW(P) {
1926
+ return pointWindowSizes.get(P) || 1;
1927
+ }
1928
+ function assert0(n) {
1929
+ if (n !== _0n3)
1930
+ throw new Error("invalid wNAF");
1931
+ }
1932
+ var wNAF = class {
1933
+ BASE;
1934
+ ZERO;
1935
+ Fn;
1936
+ bits;
1937
+ // Parametrized with a given Point class (not individual point)
1938
+ constructor(Point, bits) {
1939
+ this.BASE = Point.BASE;
1940
+ this.ZERO = Point.ZERO;
1941
+ this.Fn = Point.Fn;
1942
+ this.bits = bits;
1943
+ }
1944
+ // non-const time multiplication ladder
1945
+ _unsafeLadder(elm, n, p = this.ZERO) {
1946
+ let d = elm;
1947
+ while (n > _0n3) {
1948
+ if (n & _1n3)
1949
+ p = p.add(d);
1950
+ d = d.double();
1951
+ n >>= _1n3;
1952
+ }
1953
+ return p;
1954
+ }
1955
+ /**
1956
+ * Creates a wNAF precomputation window. Used for caching.
1957
+ * Default window size is set by `utils.precompute()` and is equal to 8.
1958
+ * Number of precomputed points depends on the curve size:
1959
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1960
+ * - 𝑊 is the window size
1961
+ * - 𝑛 is the bitlength of the curve order.
1962
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1963
+ * @param point - Point instance
1964
+ * @param W - window size
1965
+ * @returns precomputed point tables flattened to a single array
1966
+ */
1967
+ precomputeWindow(point, W) {
1968
+ const { windows, windowSize } = calcWOpts(W, this.bits);
1969
+ const points = [];
1970
+ let p = point;
1971
+ let base = p;
1972
+ for (let window = 0; window < windows; window++) {
1973
+ base = p;
1974
+ points.push(base);
1975
+ for (let i = 1; i < windowSize; i++) {
1976
+ base = base.add(p);
1977
+ points.push(base);
1978
+ }
1979
+ p = base.double();
1980
+ }
1981
+ return points;
1982
+ }
1983
+ /**
1984
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1985
+ * More compact implementation:
1986
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
1987
+ * @returns real and fake (for const-time) points
1988
+ */
1989
+ wNAF(W, precomputes, n) {
1990
+ if (!this.Fn.isValid(n))
1991
+ throw new Error("invalid scalar");
1992
+ let p = this.ZERO;
1993
+ let f = this.BASE;
1994
+ const wo = calcWOpts(W, this.bits);
1995
+ for (let window = 0; window < wo.windows; window++) {
1996
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
1997
+ n = nextN;
1998
+ if (isZero) {
1999
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
2000
+ } else {
2001
+ p = p.add(negateCt(isNeg, precomputes[offset]));
2002
+ }
2003
+ }
2004
+ assert0(n);
2005
+ return { p, f };
2006
+ }
2007
+ /**
2008
+ * Implements unsafe EC multiplication using precomputed tables
2009
+ * and w-ary non-adjacent form.
2010
+ * @param acc - accumulator point to add result of multiplication
2011
+ * @returns point
2012
+ */
2013
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
2014
+ const wo = calcWOpts(W, this.bits);
2015
+ for (let window = 0; window < wo.windows; window++) {
2016
+ if (n === _0n3)
2017
+ break;
2018
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
2019
+ n = nextN;
2020
+ if (isZero) {
2021
+ continue;
2022
+ } else {
2023
+ const item = precomputes[offset];
2024
+ acc = acc.add(isNeg ? item.negate() : item);
2025
+ }
2026
+ }
2027
+ assert0(n);
2028
+ return acc;
2029
+ }
2030
+ getPrecomputes(W, point, transform) {
2031
+ let comp = pointPrecomputes.get(point);
2032
+ if (!comp) {
2033
+ comp = this.precomputeWindow(point, W);
2034
+ if (W !== 1) {
2035
+ if (typeof transform === "function")
2036
+ comp = transform(comp);
2037
+ pointPrecomputes.set(point, comp);
2038
+ }
2039
+ }
2040
+ return comp;
2041
+ }
2042
+ cached(point, scalar, transform) {
2043
+ const W = getW(point);
2044
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
2045
+ }
2046
+ unsafe(point, scalar, transform, prev) {
2047
+ const W = getW(point);
2048
+ if (W === 1)
2049
+ return this._unsafeLadder(point, scalar, prev);
2050
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
2051
+ }
2052
+ // We calculate precomputes for elliptic curve point multiplication
2053
+ // using windowed method. This specifies window size and
2054
+ // stores precomputed values. Usually only base point would be precomputed.
2055
+ createCache(P, W) {
2056
+ validateW(W, this.bits);
2057
+ pointWindowSizes.set(P, W);
2058
+ pointPrecomputes.delete(P);
2059
+ }
2060
+ hasCache(elm) {
2061
+ return getW(elm) !== 1;
2062
+ }
2063
+ };
2064
+ function mulEndoUnsafe(Point, point, k1, k2) {
2065
+ let acc = point;
2066
+ let p1 = Point.ZERO;
2067
+ let p2 = Point.ZERO;
2068
+ while (k1 > _0n3 || k2 > _0n3) {
2069
+ if (k1 & _1n3)
2070
+ p1 = p1.add(acc);
2071
+ if (k2 & _1n3)
2072
+ p2 = p2.add(acc);
2073
+ acc = acc.double();
2074
+ k1 >>= _1n3;
2075
+ k2 >>= _1n3;
2076
+ }
2077
+ return { p1, p2 };
2078
+ }
2079
+ function createField(order, field, isLE2) {
2080
+ if (field) {
2081
+ if (field.ORDER !== order)
2082
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
2083
+ validateField(field);
2084
+ return field;
2085
+ } else {
2086
+ return Field(order, { isLE: isLE2 });
2087
+ }
2088
+ }
2089
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
2090
+ if (FpFnLE === void 0)
2091
+ FpFnLE = type === "edwards";
2092
+ if (!CURVE || typeof CURVE !== "object")
2093
+ throw new Error(`expected valid ${type} CURVE object`);
2094
+ for (const p of ["p", "n", "h"]) {
2095
+ const val = CURVE[p];
2096
+ if (!(typeof val === "bigint" && val > _0n3))
2097
+ throw new Error(`CURVE.${p} must be positive bigint`);
2098
+ }
2099
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
2100
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
2101
+ const _b = type === "weierstrass" ? "b" : "d";
2102
+ const params = ["Gx", "Gy", "a", _b];
2103
+ for (const p of params) {
2104
+ if (!Fp.isValid(CURVE[p]))
2105
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
2106
+ }
2107
+ CURVE = Object.freeze(Object.assign({}, CURVE));
2108
+ return { CURVE, Fp, Fn };
2109
+ }
2110
+ function createKeygen(randomSecretKey, getPublicKey) {
2111
+ return function keygen(seed) {
2112
+ const secretKey = randomSecretKey(seed);
2113
+ return { secretKey, publicKey: getPublicKey(secretKey) };
2114
+ };
2115
+ }
2116
+
2117
+ // node_modules/@noble/curves/abstract/weierstrass.js
2118
+ var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
2119
+ function _splitEndoScalar(k, basis, n) {
2120
+ aInRange("scalar", k, _0n4, n);
2121
+ const [[a1, b1], [a2, b2]] = basis;
2122
+ const c1 = divNearest(b2 * k, n);
2123
+ const c2 = divNearest(-b1 * k, n);
2124
+ let k1 = k - c1 * a1 - c2 * a2;
2125
+ let k2 = -c1 * b1 - c2 * b2;
2126
+ const k1neg = k1 < _0n4;
2127
+ const k2neg = k2 < _0n4;
2128
+ if (k1neg)
2129
+ k1 = -k1;
2130
+ if (k2neg)
2131
+ k2 = -k2;
2132
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
2133
+ if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
2134
+ throw new Error("splitScalar (endomorphism): failed for k");
2135
+ }
2136
+ return { k1neg, k1, k2neg, k2 };
2137
+ }
2138
+ function validateSigFormat(format) {
2139
+ if (!["compact", "recovered", "der"].includes(format))
2140
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
2141
+ return format;
2142
+ }
2143
+ function validateSigOpts(opts, def) {
2144
+ validateObject(opts);
2145
+ const optsn = {};
2146
+ for (let optName of Object.keys(def)) {
2147
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
2148
+ }
2149
+ abool(optsn.lowS, "lowS");
2150
+ abool(optsn.prehash, "prehash");
2151
+ if (optsn.format !== void 0)
2152
+ validateSigFormat(optsn.format);
2153
+ return optsn;
2154
+ }
2155
+ var DERErr = class extends Error {
2156
+ constructor(m = "") {
2157
+ super(m);
2158
+ }
2159
+ };
2160
+ var DER = {
2161
+ // asn.1 DER encoding utils
2162
+ Err: DERErr,
2163
+ // Basic building block is TLV (Tag-Length-Value)
2164
+ _tlv: {
2165
+ encode: (tag, data) => {
2166
+ const { Err: E } = DER;
2167
+ asafenumber(tag, "tag");
2168
+ if (tag < 0 || tag > 255)
2169
+ throw new E("tlv.encode: wrong tag");
2170
+ if (typeof data !== "string")
2171
+ throw new TypeError('"data" expected string, got type=' + typeof data);
2172
+ if (data.length & 1)
2173
+ throw new E("tlv.encode: unpadded data");
2174
+ const dataLen = data.length / 2;
2175
+ const len = numberToHexUnpadded(dataLen);
2176
+ if (len.length / 2 & 128)
2177
+ throw new E("tlv.encode: long form length too big");
2178
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
2179
+ const t = numberToHexUnpadded(tag);
2180
+ return t + lenLen + len + data;
2181
+ },
2182
+ // v - value, l - left bytes (unparsed)
2183
+ decode(tag, data) {
2184
+ const { Err: E } = DER;
2185
+ data = abytes2(data, void 0, "DER data");
2186
+ let pos = 0;
2187
+ if (tag < 0 || tag > 255)
2188
+ throw new E("tlv.encode: wrong tag");
2189
+ if (data.length < 2 || data[pos++] !== tag)
2190
+ throw new E("tlv.decode: wrong tlv");
2191
+ const first = data[pos++];
2192
+ const isLong = !!(first & 128);
2193
+ let length = 0;
2194
+ if (!isLong)
2195
+ length = first;
2196
+ else {
2197
+ const lenLen = first & 127;
2198
+ if (!lenLen)
2199
+ throw new E("tlv.decode(long): indefinite length not supported");
2200
+ if (lenLen > 4)
2201
+ throw new E("tlv.decode(long): byte length is too big");
2202
+ const lengthBytes = data.subarray(pos, pos + lenLen);
2203
+ if (lengthBytes.length !== lenLen)
2204
+ throw new E("tlv.decode: length bytes not complete");
2205
+ if (lengthBytes[0] === 0)
2206
+ throw new E("tlv.decode(long): zero leftmost byte");
2207
+ for (const b of lengthBytes)
2208
+ length = length << 8 | b;
2209
+ pos += lenLen;
2210
+ if (length < 128)
2211
+ throw new E("tlv.decode(long): not minimal encoding");
2212
+ }
2213
+ const v = data.subarray(pos, pos + length);
2214
+ if (v.length !== length)
2215
+ throw new E("tlv.decode: wrong value length");
2216
+ return { v, l: data.subarray(pos + length) };
2217
+ }
2218
+ },
2219
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
2220
+ // since we always use positive integers here. It must always be empty:
2221
+ // - add zero byte if exists
2222
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
2223
+ _int: {
2224
+ encode(num) {
2225
+ const { Err: E } = DER;
2226
+ abignumber(num);
2227
+ if (num < _0n4)
2228
+ throw new E("integer: negative integers are not allowed");
2229
+ let hex = numberToHexUnpadded(num);
2230
+ if (Number.parseInt(hex[0], 16) & 8)
2231
+ hex = "00" + hex;
2232
+ if (hex.length & 1)
2233
+ throw new E("unexpected DER parsing assertion: unpadded hex");
2234
+ return hex;
2235
+ },
2236
+ decode(data) {
2237
+ const { Err: E } = DER;
2238
+ if (data.length < 1)
2239
+ throw new E("invalid signature integer: empty");
2240
+ if (data[0] & 128)
2241
+ throw new E("invalid signature integer: negative");
2242
+ if (data.length > 1 && data[0] === 0 && !(data[1] & 128))
2243
+ throw new E("invalid signature integer: unnecessary leading zero");
2244
+ return bytesToNumberBE(data);
2245
+ }
2246
+ },
2247
+ toSig(bytes) {
2248
+ const { Err: E, _int: int, _tlv: tlv } = DER;
2249
+ const data = abytes2(bytes, void 0, "signature");
2250
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
2251
+ if (seqLeftBytes.length)
2252
+ throw new E("invalid signature: left bytes after parsing");
2253
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
2254
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
2255
+ if (sLeftBytes.length)
2256
+ throw new E("invalid signature: left bytes after parsing");
2257
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
2258
+ },
2259
+ hexFromSig(sig) {
2260
+ const { _tlv: tlv, _int: int } = DER;
2261
+ const rs = tlv.encode(2, int.encode(sig.r));
2262
+ const ss = tlv.encode(2, int.encode(sig.s));
2263
+ const seq = rs + ss;
2264
+ return tlv.encode(48, seq);
2265
+ }
2266
+ };
2267
+ Object.freeze(DER._tlv);
2268
+ Object.freeze(DER._int);
2269
+ Object.freeze(DER);
2270
+ var _0n4 = /* @__PURE__ */ BigInt(0);
2271
+ var _1n4 = /* @__PURE__ */ BigInt(1);
2272
+ var _2n2 = /* @__PURE__ */ BigInt(2);
2273
+ var _3n2 = /* @__PURE__ */ BigInt(3);
2274
+ var _4n2 = /* @__PURE__ */ BigInt(4);
2275
+ function weierstrass(params, extraOpts = {}) {
2276
+ const validated = createCurveFields("weierstrass", params, extraOpts);
2277
+ const Fp = validated.Fp;
2278
+ const Fn = validated.Fn;
2279
+ let CURVE = validated.CURVE;
2280
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
2281
+ validateObject(extraOpts, {}, {
2282
+ allowInfinityPoint: "boolean",
2283
+ clearCofactor: "function",
2284
+ isTorsionFree: "function",
2285
+ fromBytes: "function",
2286
+ toBytes: "function",
2287
+ endo: "object"
2288
+ });
2289
+ const { endo, allowInfinityPoint } = extraOpts;
2290
+ if (endo) {
2291
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
2292
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
2293
+ }
2294
+ }
2295
+ const lengths = getWLengths(Fp, Fn);
2296
+ function assertCompressionIsSupported() {
2297
+ if (!Fp.isOdd)
2298
+ throw new Error("compression is not supported: Field does not have .isOdd()");
2299
+ }
2300
+ function pointToBytes(_c, point, isCompressed) {
2301
+ if (allowInfinityPoint && point.is0())
2302
+ return Uint8Array.of(0);
2303
+ const { x, y } = point.toAffine();
2304
+ const bx = Fp.toBytes(x);
2305
+ abool(isCompressed, "isCompressed");
2306
+ if (isCompressed) {
2307
+ assertCompressionIsSupported();
2308
+ const hasEvenY = !Fp.isOdd(y);
2309
+ return concatBytes2(pprefix(hasEvenY), bx);
2310
+ } else {
2311
+ return concatBytes2(Uint8Array.of(4), bx, Fp.toBytes(y));
2312
+ }
2313
+ }
2314
+ function pointFromBytes(bytes) {
2315
+ abytes2(bytes, void 0, "Point");
2316
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
2317
+ const length = bytes.length;
2318
+ const head = bytes[0];
2319
+ const tail = bytes.subarray(1);
2320
+ if (allowInfinityPoint && length === 1 && head === 0)
2321
+ return { x: Fp.ZERO, y: Fp.ZERO };
2322
+ if (length === comp && (head === 2 || head === 3)) {
2323
+ const x = Fp.fromBytes(tail);
2324
+ if (!Fp.isValid(x))
2325
+ throw new Error("bad point: is not on curve, wrong x");
2326
+ const y2 = weierstrassEquation(x);
2327
+ let y;
2328
+ try {
2329
+ y = Fp.sqrt(y2);
2330
+ } catch (sqrtError) {
2331
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
2332
+ throw new Error("bad point: is not on curve, sqrt error" + err);
2333
+ }
2334
+ assertCompressionIsSupported();
2335
+ const evenY = Fp.isOdd(y);
2336
+ const evenH = (head & 1) === 1;
2337
+ if (evenH !== evenY)
2338
+ y = Fp.neg(y);
2339
+ return { x, y };
2340
+ } else if (length === uncomp && head === 4) {
2341
+ const L = Fp.BYTES;
2342
+ const x = Fp.fromBytes(tail.subarray(0, L));
2343
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
2344
+ if (!isValidXY(x, y))
2345
+ throw new Error("bad point: is not on curve");
2346
+ return { x, y };
2347
+ } else {
2348
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
2349
+ }
2350
+ }
2351
+ const encodePoint = extraOpts.toBytes === void 0 ? pointToBytes : extraOpts.toBytes;
2352
+ const decodePoint = extraOpts.fromBytes === void 0 ? pointFromBytes : extraOpts.fromBytes;
2353
+ function weierstrassEquation(x) {
2354
+ const x2 = Fp.sqr(x);
2355
+ const x3 = Fp.mul(x2, x);
2356
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
2357
+ }
2358
+ function isValidXY(x, y) {
2359
+ const left = Fp.sqr(y);
2360
+ const right = weierstrassEquation(x);
2361
+ return Fp.eql(left, right);
2362
+ }
2363
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
2364
+ throw new Error("bad curve params: generator point");
2365
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
2366
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
2367
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
2368
+ throw new Error("bad curve params: a or b");
2369
+ function acoord(title, n, banZero = false) {
2370
+ if (!Fp.isValid(n) || banZero && Fp.is0(n))
2371
+ throw new Error(`bad point coordinate ${title}`);
2372
+ return n;
2373
+ }
2374
+ function aprjpoint(other) {
2375
+ if (!(other instanceof Point))
2376
+ throw new Error("Weierstrass Point expected");
2377
+ }
2378
+ function splitEndoScalarN(k) {
2379
+ if (!endo || !endo.basises)
2380
+ throw new Error("no endo");
2381
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
2382
+ }
2383
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
2384
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
2385
+ k1p = negateCt(k1neg, k1p);
2386
+ k2p = negateCt(k2neg, k2p);
2387
+ return k1p.add(k2p);
2388
+ }
2389
+ class Point {
2390
+ // base / generator point
2391
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
2392
+ // zero / infinity / identity point
2393
+ static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
2394
+ // 0, 1, 0
2395
+ // math field
2396
+ static Fp = Fp;
2397
+ // scalar field
2398
+ static Fn = Fn;
2399
+ X;
2400
+ Y;
2401
+ Z;
2402
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
2403
+ constructor(X, Y, Z) {
2404
+ this.X = acoord("x", X);
2405
+ this.Y = acoord("y", Y, true);
2406
+ this.Z = acoord("z", Z);
2407
+ Object.freeze(this);
2408
+ }
2409
+ static CURVE() {
2410
+ return CURVE;
2411
+ }
2412
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
2413
+ static fromAffine(p) {
2414
+ const { x, y } = p || {};
2415
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
2416
+ throw new Error("invalid affine point");
2417
+ if (p instanceof Point)
2418
+ throw new Error("projective point not allowed");
2419
+ if (Fp.is0(x) && Fp.is0(y))
2420
+ return Point.ZERO;
2421
+ return new Point(x, y, Fp.ONE);
2422
+ }
2423
+ static fromBytes(bytes) {
2424
+ const P = Point.fromAffine(decodePoint(abytes2(bytes, void 0, "point")));
2425
+ P.assertValidity();
2426
+ return P;
2427
+ }
2428
+ static fromHex(hex) {
2429
+ return Point.fromBytes(hexToBytes2(hex));
2430
+ }
2431
+ get x() {
2432
+ return this.toAffine().x;
2433
+ }
2434
+ get y() {
2435
+ return this.toAffine().y;
2436
+ }
2437
+ /**
2438
+ *
2439
+ * @param windowSize
2440
+ * @param isLazy - true will defer table computation until the first multiplication
2441
+ * @returns
2442
+ */
2443
+ precompute(windowSize = 8, isLazy = true) {
2444
+ wnaf.createCache(this, windowSize);
2445
+ if (!isLazy)
2446
+ this.multiply(_3n2);
2447
+ return this;
2448
+ }
2449
+ // TODO: return `this`
2450
+ /** A point on curve is valid if it conforms to equation. */
2451
+ assertValidity() {
2452
+ const p = this;
2453
+ if (p.is0()) {
2454
+ if (extraOpts.allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))
2455
+ return;
2456
+ throw new Error("bad point: ZERO");
2457
+ }
2458
+ const { x, y } = p.toAffine();
2459
+ if (!Fp.isValid(x) || !Fp.isValid(y))
2460
+ throw new Error("bad point: x or y not field elements");
2461
+ if (!isValidXY(x, y))
2462
+ throw new Error("bad point: equation left != right");
2463
+ if (!p.isTorsionFree())
2464
+ throw new Error("bad point: not in prime-order subgroup");
2465
+ }
2466
+ hasEvenY() {
2467
+ const { y } = this.toAffine();
2468
+ if (!Fp.isOdd)
2469
+ throw new Error("Field doesn't support isOdd");
2470
+ return !Fp.isOdd(y);
2471
+ }
2472
+ /** Compare one point to another. */
2473
+ equals(other) {
2474
+ aprjpoint(other);
2475
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2476
+ const { X: X2, Y: Y2, Z: Z2 } = other;
2477
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
2478
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
2479
+ return U1 && U2;
2480
+ }
2481
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
2482
+ negate() {
2483
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
2484
+ }
2485
+ // Renes-Costello-Batina exception-free doubling formula.
2486
+ // There is 30% faster Jacobian formula, but it is not complete.
2487
+ // https://eprint.iacr.org/2015/1060, algorithm 3
2488
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
2489
+ double() {
2490
+ const { a, b } = CURVE;
2491
+ const b3 = Fp.mul(b, _3n2);
2492
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2493
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
2494
+ let t0 = Fp.mul(X1, X1);
2495
+ let t1 = Fp.mul(Y1, Y1);
2496
+ let t2 = Fp.mul(Z1, Z1);
2497
+ let t3 = Fp.mul(X1, Y1);
2498
+ t3 = Fp.add(t3, t3);
2499
+ Z3 = Fp.mul(X1, Z1);
2500
+ Z3 = Fp.add(Z3, Z3);
2501
+ X3 = Fp.mul(a, Z3);
2502
+ Y3 = Fp.mul(b3, t2);
2503
+ Y3 = Fp.add(X3, Y3);
2504
+ X3 = Fp.sub(t1, Y3);
2505
+ Y3 = Fp.add(t1, Y3);
2506
+ Y3 = Fp.mul(X3, Y3);
2507
+ X3 = Fp.mul(t3, X3);
2508
+ Z3 = Fp.mul(b3, Z3);
2509
+ t2 = Fp.mul(a, t2);
2510
+ t3 = Fp.sub(t0, t2);
2511
+ t3 = Fp.mul(a, t3);
2512
+ t3 = Fp.add(t3, Z3);
2513
+ Z3 = Fp.add(t0, t0);
2514
+ t0 = Fp.add(Z3, t0);
2515
+ t0 = Fp.add(t0, t2);
2516
+ t0 = Fp.mul(t0, t3);
2517
+ Y3 = Fp.add(Y3, t0);
2518
+ t2 = Fp.mul(Y1, Z1);
2519
+ t2 = Fp.add(t2, t2);
2520
+ t0 = Fp.mul(t2, t3);
2521
+ X3 = Fp.sub(X3, t0);
2522
+ Z3 = Fp.mul(t2, t1);
2523
+ Z3 = Fp.add(Z3, Z3);
2524
+ Z3 = Fp.add(Z3, Z3);
2525
+ return new Point(X3, Y3, Z3);
2526
+ }
2527
+ // Renes-Costello-Batina exception-free addition formula.
2528
+ // There is 30% faster Jacobian formula, but it is not complete.
2529
+ // https://eprint.iacr.org/2015/1060, algorithm 1
2530
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
2531
+ add(other) {
2532
+ aprjpoint(other);
2533
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2534
+ const { X: X2, Y: Y2, Z: Z2 } = other;
2535
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
2536
+ const a = CURVE.a;
2537
+ const b3 = Fp.mul(CURVE.b, _3n2);
2538
+ let t0 = Fp.mul(X1, X2);
2539
+ let t1 = Fp.mul(Y1, Y2);
2540
+ let t2 = Fp.mul(Z1, Z2);
2541
+ let t3 = Fp.add(X1, Y1);
2542
+ let t4 = Fp.add(X2, Y2);
2543
+ t3 = Fp.mul(t3, t4);
2544
+ t4 = Fp.add(t0, t1);
2545
+ t3 = Fp.sub(t3, t4);
2546
+ t4 = Fp.add(X1, Z1);
2547
+ let t5 = Fp.add(X2, Z2);
2548
+ t4 = Fp.mul(t4, t5);
2549
+ t5 = Fp.add(t0, t2);
2550
+ t4 = Fp.sub(t4, t5);
2551
+ t5 = Fp.add(Y1, Z1);
2552
+ X3 = Fp.add(Y2, Z2);
2553
+ t5 = Fp.mul(t5, X3);
2554
+ X3 = Fp.add(t1, t2);
2555
+ t5 = Fp.sub(t5, X3);
2556
+ Z3 = Fp.mul(a, t4);
2557
+ X3 = Fp.mul(b3, t2);
2558
+ Z3 = Fp.add(X3, Z3);
2559
+ X3 = Fp.sub(t1, Z3);
2560
+ Z3 = Fp.add(t1, Z3);
2561
+ Y3 = Fp.mul(X3, Z3);
2562
+ t1 = Fp.add(t0, t0);
2563
+ t1 = Fp.add(t1, t0);
2564
+ t2 = Fp.mul(a, t2);
2565
+ t4 = Fp.mul(b3, t4);
2566
+ t1 = Fp.add(t1, t2);
2567
+ t2 = Fp.sub(t0, t2);
2568
+ t2 = Fp.mul(a, t2);
2569
+ t4 = Fp.add(t4, t2);
2570
+ t0 = Fp.mul(t1, t4);
2571
+ Y3 = Fp.add(Y3, t0);
2572
+ t0 = Fp.mul(t5, t4);
2573
+ X3 = Fp.mul(t3, X3);
2574
+ X3 = Fp.sub(X3, t0);
2575
+ t0 = Fp.mul(t3, t1);
2576
+ Z3 = Fp.mul(t5, Z3);
2577
+ Z3 = Fp.add(Z3, t0);
2578
+ return new Point(X3, Y3, Z3);
2579
+ }
2580
+ subtract(other) {
2581
+ aprjpoint(other);
2582
+ return this.add(other.negate());
2583
+ }
2584
+ is0() {
2585
+ return this.equals(Point.ZERO);
2586
+ }
2587
+ /**
2588
+ * Constant time multiplication.
2589
+ * Uses wNAF method. Windowed method may be 10% faster,
2590
+ * but takes 2x longer to generate and consumes 2x memory.
2591
+ * Uses precomputes when available.
2592
+ * Uses endomorphism for Koblitz curves.
2593
+ * @param scalar - by which the point would be multiplied
2594
+ * @returns New point
2595
+ */
2596
+ multiply(scalar) {
2597
+ const { endo: endo2 } = extraOpts;
2598
+ if (!Fn.isValidNot0(scalar))
2599
+ throw new RangeError("invalid scalar: out of range");
2600
+ let point, fake;
2601
+ const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
2602
+ if (endo2) {
2603
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
2604
+ const { p: k1p, f: k1f } = mul(k1);
2605
+ const { p: k2p, f: k2f } = mul(k2);
2606
+ fake = k1f.add(k2f);
2607
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
2608
+ } else {
2609
+ const { p, f } = mul(scalar);
2610
+ point = p;
2611
+ fake = f;
2612
+ }
2613
+ return normalizeZ(Point, [point, fake])[0];
2614
+ }
2615
+ /**
2616
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
2617
+ * It's faster, but should only be used when you don't care about
2618
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
2619
+ */
2620
+ multiplyUnsafe(scalar) {
2621
+ const { endo: endo2 } = extraOpts;
2622
+ const p = this;
2623
+ const sc = scalar;
2624
+ if (!Fn.isValid(sc))
2625
+ throw new RangeError("invalid scalar: out of range");
2626
+ if (sc === _0n4 || p.is0())
2627
+ return Point.ZERO;
2628
+ if (sc === _1n4)
2629
+ return p;
2630
+ if (wnaf.hasCache(this))
2631
+ return this.multiply(sc);
2632
+ if (endo2) {
2633
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
2634
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
2635
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
2636
+ } else {
2637
+ return wnaf.unsafe(p, sc);
2638
+ }
2639
+ }
2640
+ /**
2641
+ * Converts Projective point to affine (x, y) coordinates.
2642
+ * (X, Y, Z) ∋ (x=X/Z, y=Y/Z).
2643
+ * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
2644
+ */
2645
+ toAffine(invertedZ) {
2646
+ const p = this;
2647
+ let iz = invertedZ;
2648
+ const { X, Y, Z } = p;
2649
+ if (Fp.eql(Z, Fp.ONE))
2650
+ return { x: X, y: Y };
2651
+ const is0 = p.is0();
2652
+ if (iz == null)
2653
+ iz = is0 ? Fp.ONE : Fp.inv(Z);
2654
+ const x = Fp.mul(X, iz);
2655
+ const y = Fp.mul(Y, iz);
2656
+ const zz = Fp.mul(Z, iz);
2657
+ if (is0)
2658
+ return { x: Fp.ZERO, y: Fp.ZERO };
2659
+ if (!Fp.eql(zz, Fp.ONE))
2660
+ throw new Error("invZ was invalid");
2661
+ return { x, y };
2662
+ }
2663
+ /**
2664
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
2665
+ * Always torsion-free for cofactor=1 curves.
2666
+ */
2667
+ isTorsionFree() {
2668
+ const { isTorsionFree } = extraOpts;
2669
+ if (cofactor === _1n4)
2670
+ return true;
2671
+ if (isTorsionFree)
2672
+ return isTorsionFree(Point, this);
2673
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
2674
+ }
2675
+ clearCofactor() {
2676
+ const { clearCofactor } = extraOpts;
2677
+ if (cofactor === _1n4)
2678
+ return this;
2679
+ if (clearCofactor)
2680
+ return clearCofactor(Point, this);
2681
+ return this.multiplyUnsafe(cofactor);
2682
+ }
2683
+ isSmallOrder() {
2684
+ if (cofactor === _1n4)
2685
+ return this.is0();
2686
+ return this.clearCofactor().is0();
2687
+ }
2688
+ toBytes(isCompressed = true) {
2689
+ abool(isCompressed, "isCompressed");
2690
+ this.assertValidity();
2691
+ return encodePoint(Point, this, isCompressed);
2692
+ }
2693
+ toHex(isCompressed = true) {
2694
+ return bytesToHex2(this.toBytes(isCompressed));
2695
+ }
2696
+ toString() {
2697
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
2698
+ }
2699
+ }
2700
+ const bits = Fn.BITS;
2701
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
2702
+ if (bits >= 8)
2703
+ Point.BASE.precompute(8);
2704
+ Object.freeze(Point.prototype);
2705
+ Object.freeze(Point);
2706
+ return Point;
2707
+ }
2708
+ function pprefix(hasEvenY) {
2709
+ return Uint8Array.of(hasEvenY ? 2 : 3);
2710
+ }
2711
+ function getWLengths(Fp, Fn) {
2712
+ return {
2713
+ secretKey: Fn.BYTES,
2714
+ publicKey: 1 + Fp.BYTES,
2715
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
2716
+ publicKeyHasPrefix: true,
2717
+ // Raw compact `(r || s)` signature width; DER and recovered signatures use
2718
+ // different lengths outside this helper.
2719
+ signature: 2 * Fn.BYTES
2720
+ };
2721
+ }
2722
+ function ecdh(Point, ecdhOpts = {}) {
2723
+ const { Fn } = Point;
2724
+ const randomBytes_ = ecdhOpts.randomBytes === void 0 ? randomBytes2 : ecdhOpts.randomBytes;
2725
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), {
2726
+ seed: Math.max(getMinHashLength(Fn.ORDER), 16)
2727
+ });
2728
+ function isValidSecretKey(secretKey) {
2729
+ try {
2730
+ const num = Fn.fromBytes(secretKey);
2731
+ return Fn.isValidNot0(num);
2732
+ } catch (error) {
2733
+ return false;
2734
+ }
2735
+ }
2736
+ function isValidPublicKey(publicKey, isCompressed) {
2737
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
2738
+ try {
2739
+ const l = publicKey.length;
2740
+ if (isCompressed === true && l !== comp)
2741
+ return false;
2742
+ if (isCompressed === false && l !== publicKeyUncompressed)
2743
+ return false;
2744
+ return !!Point.fromBytes(publicKey);
2745
+ } catch (error) {
2746
+ return false;
2747
+ }
2748
+ }
2749
+ function randomSecretKey(seed) {
2750
+ seed = seed === void 0 ? randomBytes_(lengths.seed) : seed;
2751
+ return mapHashToField(abytes2(seed, lengths.seed, "seed"), Fn.ORDER);
2752
+ }
2753
+ function getPublicKey(secretKey, isCompressed = true) {
2754
+ return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
2755
+ }
2756
+ function isProbPub(item) {
2757
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
2758
+ const allowedLengths = Fn._lengths;
2759
+ if (!isBytes2(item))
2760
+ return void 0;
2761
+ const l = abytes2(item, void 0, "key").length;
2762
+ const isPub = l === publicKey || l === publicKeyUncompressed;
2763
+ const isSec = l === secretKey || !!allowedLengths?.includes(l);
2764
+ if (isPub && isSec)
2765
+ return void 0;
2766
+ return isPub;
2767
+ }
2768
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
2769
+ if (isProbPub(secretKeyA) === true)
2770
+ throw new Error("first arg must be private key");
2771
+ if (isProbPub(publicKeyB) === false)
2772
+ throw new Error("second arg must be public key");
2773
+ const s = Fn.fromBytes(secretKeyA);
2774
+ const b = Point.fromBytes(publicKeyB);
2775
+ return b.multiply(s).toBytes(isCompressed);
2776
+ }
2777
+ const utils = {
2778
+ isValidSecretKey,
2779
+ isValidPublicKey,
2780
+ randomSecretKey
2781
+ };
2782
+ const keygen = createKeygen(randomSecretKey, getPublicKey);
2783
+ Object.freeze(utils);
2784
+ Object.freeze(lengths);
2785
+ return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
2786
+ }
2787
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
2788
+ const hash_ = hash;
2789
+ ahash(hash_);
2790
+ validateObject(ecdsaOpts, {}, {
2791
+ hmac: "function",
2792
+ lowS: "boolean",
2793
+ randomBytes: "function",
2794
+ bits2int: "function",
2795
+ bits2int_modN: "function"
2796
+ });
2797
+ ecdsaOpts = Object.assign({}, ecdsaOpts);
2798
+ const randomBytes4 = ecdsaOpts.randomBytes === void 0 ? randomBytes2 : ecdsaOpts.randomBytes;
2799
+ const hmac2 = ecdsaOpts.hmac === void 0 ? (key, msg) => hmac(hash_, key, msg) : ecdsaOpts.hmac;
2800
+ const { Fp, Fn } = Point;
2801
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
2802
+ const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
2803
+ const defaultSigOpts = {
2804
+ prehash: true,
2805
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
2806
+ format: "compact",
2807
+ extraEntropy: false
2808
+ };
2809
+ const hasLargeRecoveryLifts = CURVE_ORDER * _2n2 + _1n4 < Fp.ORDER;
2810
+ function isBiggerThanHalfOrder(number) {
2811
+ const HALF = CURVE_ORDER >> _1n4;
2812
+ return number > HALF;
2813
+ }
2814
+ function validateRS(title, num) {
2815
+ if (!Fn.isValidNot0(num))
2816
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
2817
+ return num;
2818
+ }
2819
+ function assertRecoverableCurve() {
2820
+ if (hasLargeRecoveryLifts)
2821
+ throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
2822
+ }
2823
+ function validateSigLength(bytes, format) {
2824
+ validateSigFormat(format);
2825
+ const size = lengths.signature;
2826
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
2827
+ return abytes2(bytes, sizer);
2828
+ }
2829
+ class Signature2 {
2830
+ r;
2831
+ s;
2832
+ recovery;
2833
+ constructor(r, s, recovery) {
2834
+ this.r = validateRS("r", r);
2835
+ this.s = validateRS("s", s);
2836
+ if (recovery != null) {
2837
+ assertRecoverableCurve();
2838
+ if (![0, 1, 2, 3].includes(recovery))
2839
+ throw new Error("invalid recovery id");
2840
+ this.recovery = recovery;
2841
+ }
2842
+ Object.freeze(this);
2843
+ }
2844
+ static fromBytes(bytes, format = defaultSigOpts.format) {
2845
+ validateSigLength(bytes, format);
2846
+ let recid;
2847
+ if (format === "der") {
2848
+ const { r: r2, s: s2 } = DER.toSig(abytes2(bytes));
2849
+ return new Signature2(r2, s2);
2850
+ }
2851
+ if (format === "recovered") {
2852
+ recid = bytes[0];
2853
+ format = "compact";
2854
+ bytes = bytes.subarray(1);
2855
+ }
2856
+ const L = lengths.signature / 2;
2857
+ const r = bytes.subarray(0, L);
2858
+ const s = bytes.subarray(L, L * 2);
2859
+ return new Signature2(Fn.fromBytes(r), Fn.fromBytes(s), recid);
2860
+ }
2861
+ static fromHex(hex, format) {
2862
+ return this.fromBytes(hexToBytes2(hex), format);
2863
+ }
2864
+ assertRecovery() {
2865
+ const { recovery } = this;
2866
+ if (recovery == null)
2867
+ throw new Error("invalid recovery id: must be present");
2868
+ return recovery;
2869
+ }
2870
+ addRecoveryBit(recovery) {
2871
+ return new Signature2(this.r, this.s, recovery);
2872
+ }
2873
+ // Unlike the top-level helper below, this method expects a digest that has
2874
+ // already been hashed to the curve's message representative.
2875
+ recoverPublicKey(messageHash) {
2876
+ const { r, s } = this;
2877
+ const recovery = this.assertRecovery();
2878
+ const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;
2879
+ if (!Fp.isValid(radj))
2880
+ throw new Error("invalid recovery id: sig.r+curve.n != R.x");
2881
+ const x = Fp.toBytes(radj);
2882
+ const R = Point.fromBytes(concatBytes2(pprefix((recovery & 1) === 0), x));
2883
+ const ir = Fn.inv(radj);
2884
+ const h = bits2int_modN(abytes2(messageHash, void 0, "msgHash"));
2885
+ const u1 = Fn.create(-h * ir);
2886
+ const u2 = Fn.create(s * ir);
2887
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
2888
+ if (Q.is0())
2889
+ throw new Error("invalid recovery: point at infinify");
2890
+ Q.assertValidity();
2891
+ return Q;
2892
+ }
2893
+ // Signatures should be low-s, to prevent malleability.
2894
+ hasHighS() {
2895
+ return isBiggerThanHalfOrder(this.s);
2896
+ }
2897
+ toBytes(format = defaultSigOpts.format) {
2898
+ validateSigFormat(format);
2899
+ if (format === "der")
2900
+ return hexToBytes2(DER.hexFromSig(this));
2901
+ const { r, s } = this;
2902
+ const rb = Fn.toBytes(r);
2903
+ const sb = Fn.toBytes(s);
2904
+ if (format === "recovered") {
2905
+ assertRecoverableCurve();
2906
+ return concatBytes2(Uint8Array.of(this.assertRecovery()), rb, sb);
2907
+ }
2908
+ return concatBytes2(rb, sb);
2909
+ }
2910
+ toHex(format) {
2911
+ return bytesToHex2(this.toBytes(format));
2912
+ }
2913
+ }
2914
+ Object.freeze(Signature2.prototype);
2915
+ Object.freeze(Signature2);
2916
+ const bits2int = ecdsaOpts.bits2int === void 0 ? function bits2int_def(bytes) {
2917
+ if (bytes.length > 8192)
2918
+ throw new Error("input is too large");
2919
+ const num = bytesToNumberBE(bytes);
2920
+ const delta = bytes.length * 8 - fnBits;
2921
+ return delta > 0 ? num >> BigInt(delta) : num;
2922
+ } : ecdsaOpts.bits2int;
2923
+ const bits2int_modN = ecdsaOpts.bits2int_modN === void 0 ? function bits2int_modN_def(bytes) {
2924
+ return Fn.create(bits2int(bytes));
2925
+ } : ecdsaOpts.bits2int_modN;
2926
+ const ORDER_MASK = bitMask(fnBits);
2927
+ function int2octets(num) {
2928
+ aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
2929
+ return Fn.toBytes(num);
2930
+ }
2931
+ function validateMsgAndHash(message, prehash) {
2932
+ abytes2(message, void 0, "message");
2933
+ return prehash ? abytes2(hash_(message), void 0, "prehashed message") : message;
2934
+ }
2935
+ function prepSig(message, secretKey, opts) {
2936
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
2937
+ message = validateMsgAndHash(message, prehash);
2938
+ const h1int = bits2int_modN(message);
2939
+ const d = Fn.fromBytes(secretKey);
2940
+ if (!Fn.isValidNot0(d))
2941
+ throw new Error("invalid private key");
2942
+ const seedArgs = [int2octets(d), int2octets(h1int)];
2943
+ if (extraEntropy != null && extraEntropy !== false) {
2944
+ const e = extraEntropy === true ? randomBytes4(lengths.secretKey) : extraEntropy;
2945
+ seedArgs.push(abytes2(e, void 0, "extraEntropy"));
2946
+ }
2947
+ const seed = concatBytes2(...seedArgs);
2948
+ const m = h1int;
2949
+ function k2sig(kBytes) {
2950
+ const k = bits2int(kBytes);
2951
+ if (!Fn.isValidNot0(k))
2952
+ return;
2953
+ const ik = Fn.inv(k);
2954
+ const q = Point.BASE.multiply(k).toAffine();
2955
+ const r = Fn.create(q.x);
2956
+ if (r === _0n4)
2957
+ return;
2958
+ const s = Fn.create(ik * Fn.create(m + r * d));
2959
+ if (s === _0n4)
2960
+ return;
2961
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
2962
+ let normS = s;
2963
+ if (lowS && isBiggerThanHalfOrder(s)) {
2964
+ normS = Fn.neg(s);
2965
+ recovery ^= 1;
2966
+ }
2967
+ return new Signature2(r, normS, hasLargeRecoveryLifts ? void 0 : recovery);
2968
+ }
2969
+ return { seed, k2sig };
2970
+ }
2971
+ function sign(message, secretKey, opts = {}) {
2972
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
2973
+ const drbg = createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac2);
2974
+ const sig = drbg(seed, k2sig);
2975
+ return sig.toBytes(opts.format);
2976
+ }
2977
+ function verify(signature, message, publicKey, opts = {}) {
2978
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
2979
+ publicKey = abytes2(publicKey, void 0, "publicKey");
2980
+ message = validateMsgAndHash(message, prehash);
2981
+ if (!isBytes2(signature)) {
2982
+ const end = signature instanceof Signature2 ? ", use sig.toBytes()" : "";
2983
+ throw new Error("verify expects Uint8Array signature" + end);
2984
+ }
2985
+ validateSigLength(signature, format);
2986
+ try {
2987
+ const sig = Signature2.fromBytes(signature, format);
2988
+ const P = Point.fromBytes(publicKey);
2989
+ if (lowS && sig.hasHighS())
2990
+ return false;
2991
+ const { r, s } = sig;
2992
+ const h = bits2int_modN(message);
2993
+ const is = Fn.inv(s);
2994
+ const u1 = Fn.create(h * is);
2995
+ const u2 = Fn.create(r * is);
2996
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
2997
+ if (R.is0())
2998
+ return false;
2999
+ const v = Fn.create(R.x);
3000
+ return v === r;
3001
+ } catch (e) {
3002
+ return false;
3003
+ }
3004
+ }
3005
+ function recoverPublicKey(signature, message, opts = {}) {
3006
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
3007
+ message = validateMsgAndHash(message, prehash);
3008
+ return Signature2.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
3009
+ }
3010
+ return Object.freeze({
3011
+ keygen,
3012
+ getPublicKey,
3013
+ getSharedSecret,
3014
+ utils,
3015
+ lengths,
3016
+ Point,
3017
+ sign,
3018
+ verify,
3019
+ recoverPublicKey,
3020
+ Signature: Signature2,
3021
+ hash: hash_
3022
+ });
3023
+ }
3024
+
3025
+ // node_modules/@noble/curves/secp256k1.js
3026
+ var secp256k1_CURVE = {
3027
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
3028
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
3029
+ h: BigInt(1),
3030
+ a: BigInt(0),
3031
+ b: BigInt(7),
3032
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
3033
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
3034
+ };
3035
+ var secp256k1_ENDO = {
3036
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
3037
+ basises: [
3038
+ [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
3039
+ [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
3040
+ ]
3041
+ };
3042
+ var _2n3 = /* @__PURE__ */ BigInt(2);
3043
+ function sqrtMod(y) {
3044
+ const P = secp256k1_CURVE.p;
3045
+ const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
3046
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
3047
+ const b2 = y * y * y % P;
3048
+ const b3 = b2 * b2 * y % P;
3049
+ const b6 = pow2(b3, _3n3, P) * b3 % P;
3050
+ const b9 = pow2(b6, _3n3, P) * b3 % P;
3051
+ const b11 = pow2(b9, _2n3, P) * b2 % P;
3052
+ const b22 = pow2(b11, _11n, P) * b11 % P;
3053
+ const b44 = pow2(b22, _22n, P) * b22 % P;
3054
+ const b88 = pow2(b44, _44n, P) * b44 % P;
3055
+ const b176 = pow2(b88, _88n, P) * b88 % P;
3056
+ const b220 = pow2(b176, _44n, P) * b44 % P;
3057
+ const b223 = pow2(b220, _3n3, P) * b3 % P;
3058
+ const t1 = pow2(b223, _23n, P) * b22 % P;
3059
+ const t2 = pow2(t1, _6n, P) * b2 % P;
3060
+ const root = pow2(t2, _2n3, P);
3061
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
3062
+ throw new Error("Cannot find square root");
3063
+ return root;
3064
+ }
3065
+ var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
3066
+ var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
3067
+ Fp: Fpk1,
3068
+ endo: secp256k1_ENDO
3069
+ });
3070
+ var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256);
3071
+
3072
+ // node_modules/@noble/ciphers/utils.js
3073
+ function isBytes3(a) {
3074
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
3075
+ }
3076
+ function abool2(b) {
3077
+ if (typeof b !== "boolean")
3078
+ throw new TypeError(`boolean expected, not ${b}`);
3079
+ }
3080
+ function anumber3(n) {
3081
+ if (typeof n !== "number")
3082
+ throw new TypeError("number expected, got " + typeof n);
3083
+ if (!Number.isSafeInteger(n) || n < 0)
3084
+ throw new RangeError("positive integer expected, got " + n);
3085
+ }
3086
+ function abytes3(value, length, title = "") {
3087
+ const bytes = isBytes3(value);
3088
+ const len = value?.length;
3089
+ const needsLen = length !== void 0;
3090
+ if (!bytes || needsLen && len !== length) {
3091
+ const prefix = title && `"${title}" `;
3092
+ const ofLen = needsLen ? ` of length ${length}` : "";
3093
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
3094
+ const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
3095
+ if (!bytes)
3096
+ throw new TypeError(message);
3097
+ throw new RangeError(message);
3098
+ }
3099
+ return value;
3100
+ }
3101
+ function aexists2(instance, checkFinished = true) {
3102
+ if (instance.destroyed)
3103
+ throw new Error("Hash instance has been destroyed");
3104
+ if (checkFinished && instance.finished)
3105
+ throw new Error("Hash#digest() has already been called");
3106
+ }
3107
+ function aoutput2(out, instance, onlyAligned = false) {
3108
+ abytes3(out, void 0, "output");
3109
+ const min = instance.outputLen;
3110
+ if (out.length < min) {
3111
+ throw new RangeError("digestInto() expects output buffer of length at least " + min);
3112
+ }
3113
+ if (onlyAligned && !isAligned32(out))
3114
+ throw new Error("invalid output, must be aligned");
3115
+ }
3116
+ function u32(arr) {
3117
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
3118
+ }
3119
+ function clean2(...arrays) {
3120
+ for (let i = 0; i < arrays.length; i++) {
3121
+ arrays[i].fill(0);
3122
+ }
3123
+ }
3124
+ function createView2(arr) {
3125
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
3126
+ }
3127
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
3128
+ var byteSwap = (word) => word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
3129
+ var swap8IfBE = isLE ? (n) => n : (n) => byteSwap(n) >>> 0;
3130
+ var byteSwap32 = (arr) => {
3131
+ for (let i = 0; i < arr.length; i++)
3132
+ arr[i] = byteSwap(arr[i]);
3133
+ return arr;
3134
+ };
3135
+ var swap32IfBE = isLE ? (u) => u : byteSwap32;
3136
+ function checkOpts(defaults, opts) {
3137
+ if (opts == null || typeof opts !== "object")
3138
+ throw new Error("options must be defined");
3139
+ const merged = Object.assign(defaults, opts);
3140
+ return merged;
3141
+ }
3142
+ function equalBytes(a, b) {
3143
+ if (a.length !== b.length)
3144
+ return false;
3145
+ let diff = 0;
3146
+ for (let i = 0; i < a.length; i++)
3147
+ diff |= a[i] ^ b[i];
3148
+ return diff === 0;
3149
+ }
3150
+ function wrapMacConstructor(keyLen, macCons, fromMsg) {
3151
+ const mac = macCons;
3152
+ const getArgs = fromMsg || (() => []);
3153
+ const macC = (msg, key) => mac(key, ...getArgs(msg)).update(msg).digest();
3154
+ const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));
3155
+ macC.outputLen = tmp.outputLen;
3156
+ macC.blockLen = tmp.blockLen;
3157
+ macC.create = (key, ...args) => mac(key, ...args);
3158
+ return macC;
3159
+ }
3160
+ var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
3161
+ function wrappedCipher(key, ...args) {
3162
+ abytes3(key, void 0, "key");
3163
+ if (params.nonceLength !== void 0) {
3164
+ const nonce = args[0];
3165
+ abytes3(nonce, params.varSizeNonce ? void 0 : params.nonceLength, "nonce");
3166
+ }
3167
+ const tagl = params.tagLength;
3168
+ if (tagl && args[1] !== void 0)
3169
+ abytes3(args[1], void 0, "AAD");
3170
+ const cipher = constructor(key, ...args);
3171
+ const checkOutput = (fnLength, output) => {
3172
+ if (output !== void 0) {
3173
+ if (fnLength !== 2)
3174
+ throw new Error("cipher output not supported");
3175
+ abytes3(output, void 0, "output");
3176
+ }
3177
+ };
3178
+ let called = false;
3179
+ const wrCipher = {
3180
+ encrypt(data, output) {
3181
+ if (called)
3182
+ throw new Error("cannot encrypt() twice with same key + nonce");
3183
+ called = true;
3184
+ abytes3(data);
3185
+ checkOutput(cipher.encrypt.length, output);
3186
+ return cipher.encrypt(data, output);
3187
+ },
3188
+ decrypt(data, output) {
3189
+ abytes3(data);
3190
+ if (tagl && data.length < tagl)
3191
+ throw new Error('"ciphertext" expected length bigger than tagLength=' + tagl);
3192
+ checkOutput(cipher.decrypt.length, output);
3193
+ return cipher.decrypt(data, output);
3194
+ }
3195
+ };
3196
+ return wrCipher;
3197
+ }
3198
+ Object.assign(wrappedCipher, params);
3199
+ return wrappedCipher;
3200
+ };
3201
+ function getOutput(expectedLength, out, onlyAligned = true) {
3202
+ if (out === void 0)
3203
+ return new Uint8Array(expectedLength);
3204
+ abytes3(out, void 0, "output");
3205
+ if (out.length !== expectedLength)
3206
+ throw new Error('"output" expected Uint8Array of length ' + expectedLength + ", got: " + out.length);
3207
+ if (onlyAligned && !isAligned32(out))
3208
+ throw new Error("invalid output, must be aligned");
3209
+ return out;
3210
+ }
3211
+ function u64Lengths(dataLength, aadLength, isLE2) {
3212
+ anumber3(dataLength);
3213
+ anumber3(aadLength);
3214
+ abool2(isLE2);
3215
+ const num = new Uint8Array(16);
3216
+ const view = createView2(num);
3217
+ view.setBigUint64(0, BigInt(aadLength), isLE2);
3218
+ view.setBigUint64(8, BigInt(dataLength), isLE2);
3219
+ return num;
3220
+ }
3221
+ function isAligned32(bytes) {
3222
+ return bytes.byteOffset % 4 === 0;
3223
+ }
3224
+ function copyBytes2(bytes) {
3225
+ return Uint8Array.from(abytes3(bytes));
3226
+ }
3227
+ function randomBytes3(bytesLength = 32) {
3228
+ anumber3(bytesLength);
3229
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
3230
+ if (typeof cr?.getRandomValues !== "function")
3231
+ throw new Error("crypto.getRandomValues must be defined");
3232
+ return cr.getRandomValues(new Uint8Array(bytesLength));
3233
+ }
3234
+
3235
+ // node_modules/@noble/ciphers/_arx.js
3236
+ var encodeStr = (str) => Uint8Array.from(str.split(""), (c) => c.charCodeAt(0));
3237
+ var sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 16-byte k"))))();
3238
+ var sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 32-byte k"))))();
3239
+ function rotl(a, b) {
3240
+ return a << b | a >>> 32 - b;
3241
+ }
3242
+ var BLOCK_LEN = 64;
3243
+ var BLOCK_LEN32 = 16;
3244
+ var MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();
3245
+ var U32_EMPTY = /* @__PURE__ */ Uint32Array.of();
3246
+ function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
3247
+ const len = data.length;
3248
+ const block = new Uint8Array(BLOCK_LEN);
3249
+ const b32 = u32(block);
3250
+ const isAligned = isLE && isAligned32(data) && isAligned32(output);
3251
+ const d32 = isAligned ? u32(data) : U32_EMPTY;
3252
+ const o32 = isAligned ? u32(output) : U32_EMPTY;
3253
+ if (!isLE) {
3254
+ for (let pos = 0; pos < len; counter++) {
3255
+ core(sigma, key, nonce, b32, counter, rounds);
3256
+ swap32IfBE(b32);
3257
+ if (counter >= MAX_COUNTER)
3258
+ throw new Error("arx: counter overflow");
3259
+ const take = Math.min(BLOCK_LEN, len - pos);
3260
+ for (let j = 0, posj; j < take; j++) {
3261
+ posj = pos + j;
3262
+ output[posj] = data[posj] ^ block[j];
3263
+ }
3264
+ pos += take;
3265
+ }
3266
+ return;
3267
+ }
3268
+ for (let pos = 0; pos < len; counter++) {
3269
+ core(sigma, key, nonce, b32, counter, rounds);
3270
+ if (counter >= MAX_COUNTER)
3271
+ throw new Error("arx: counter overflow");
3272
+ const take = Math.min(BLOCK_LEN, len - pos);
3273
+ if (isAligned && take === BLOCK_LEN) {
3274
+ const pos32 = pos / 4;
3275
+ if (pos % 4 !== 0)
3276
+ throw new Error("arx: invalid block position");
3277
+ for (let j = 0, posj; j < BLOCK_LEN32; j++) {
3278
+ posj = pos32 + j;
3279
+ o32[posj] = d32[posj] ^ b32[j];
3280
+ }
3281
+ pos += BLOCK_LEN;
3282
+ continue;
3283
+ }
3284
+ for (let j = 0, posj; j < take; j++) {
3285
+ posj = pos + j;
3286
+ output[posj] = data[posj] ^ block[j];
3287
+ }
3288
+ pos += take;
3289
+ }
3290
+ }
3291
+ function createCipher(core, opts) {
3292
+ const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
3293
+ if (typeof core !== "function")
3294
+ throw new Error("core must be a function");
3295
+ anumber3(counterLength);
3296
+ anumber3(rounds);
3297
+ abool2(counterRight);
3298
+ abool2(allowShortKeys);
3299
+ return (key, nonce, data, output, counter = 0) => {
3300
+ abytes3(key, void 0, "key");
3301
+ abytes3(nonce, void 0, "nonce");
3302
+ abytes3(data, void 0, "data");
3303
+ const len = data.length;
3304
+ output = getOutput(len, output, false);
3305
+ anumber3(counter);
3306
+ if (counter < 0 || counter >= MAX_COUNTER)
3307
+ throw new Error("arx: counter overflow");
3308
+ const toClean = [];
3309
+ let l = key.length;
3310
+ let k;
3311
+ let sigma;
3312
+ if (l === 32) {
3313
+ toClean.push(k = copyBytes2(key));
3314
+ sigma = sigma32_32;
3315
+ } else if (l === 16 && allowShortKeys) {
3316
+ k = new Uint8Array(32);
3317
+ k.set(key);
3318
+ k.set(key, 16);
3319
+ sigma = sigma16_32;
3320
+ toClean.push(k);
3321
+ } else {
3322
+ abytes3(key, 32, "arx key");
3323
+ throw new Error("invalid key size");
3324
+ }
3325
+ if (!isLE || !isAligned32(nonce))
3326
+ toClean.push(nonce = copyBytes2(nonce));
3327
+ let k32 = u32(k);
3328
+ if (extendNonceFn) {
3329
+ if (nonce.length !== 24)
3330
+ throw new Error(`arx: extended nonce must be 24 bytes`);
3331
+ const n16 = nonce.subarray(0, 16);
3332
+ if (isLE)
3333
+ extendNonceFn(sigma, k32, u32(n16), k32);
3334
+ else {
3335
+ const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));
3336
+ extendNonceFn(sigmaRaw, k32, u32(n16), k32);
3337
+ clean2(sigmaRaw);
3338
+ swap32IfBE(k32);
3339
+ }
3340
+ nonce = nonce.subarray(16);
3341
+ } else if (!isLE)
3342
+ swap32IfBE(k32);
3343
+ const nonceNcLen = 16 - counterLength;
3344
+ if (nonceNcLen !== nonce.length)
3345
+ throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
3346
+ if (nonceNcLen !== 12) {
3347
+ const nc = new Uint8Array(12);
3348
+ nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
3349
+ nonce = nc;
3350
+ toClean.push(nonce);
3351
+ }
3352
+ const n32 = swap32IfBE(u32(nonce));
3353
+ try {
3354
+ runCipher(core, sigma, k32, n32, data, output, counter, rounds);
3355
+ return output;
3356
+ } finally {
3357
+ clean2(...toClean);
3358
+ }
3359
+ };
3360
+ }
3361
+
3362
+ // node_modules/@noble/ciphers/_poly1305.js
3363
+ function u8to16(a, i) {
3364
+ return a[i++] & 255 | (a[i++] & 255) << 8;
3365
+ }
3366
+ var Poly1305 = class {
3367
+ blockLen = 16;
3368
+ outputLen = 16;
3369
+ buffer = new Uint8Array(16);
3370
+ r = new Uint16Array(10);
3371
+ // Allocating 1 array with .subarray() here is slower than 3
3372
+ h = new Uint16Array(10);
3373
+ pad = new Uint16Array(8);
3374
+ pos = 0;
3375
+ finished = false;
3376
+ destroyed = false;
3377
+ // Can be speed-up using BigUint64Array, at the cost of complexity
3378
+ constructor(key) {
3379
+ key = copyBytes2(abytes3(key, 32, "key"));
3380
+ const t0 = u8to16(key, 0);
3381
+ const t1 = u8to16(key, 2);
3382
+ const t2 = u8to16(key, 4);
3383
+ const t3 = u8to16(key, 6);
3384
+ const t4 = u8to16(key, 8);
3385
+ const t5 = u8to16(key, 10);
3386
+ const t6 = u8to16(key, 12);
3387
+ const t7 = u8to16(key, 14);
3388
+ this.r[0] = t0 & 8191;
3389
+ this.r[1] = (t0 >>> 13 | t1 << 3) & 8191;
3390
+ this.r[2] = (t1 >>> 10 | t2 << 6) & 7939;
3391
+ this.r[3] = (t2 >>> 7 | t3 << 9) & 8191;
3392
+ this.r[4] = (t3 >>> 4 | t4 << 12) & 255;
3393
+ this.r[5] = t4 >>> 1 & 8190;
3394
+ this.r[6] = (t4 >>> 14 | t5 << 2) & 8191;
3395
+ this.r[7] = (t5 >>> 11 | t6 << 5) & 8065;
3396
+ this.r[8] = (t6 >>> 8 | t7 << 8) & 8191;
3397
+ this.r[9] = t7 >>> 5 & 127;
3398
+ for (let i = 0; i < 8; i++)
3399
+ this.pad[i] = u8to16(key, 16 + 2 * i);
3400
+ }
3401
+ process(data, offset, isLast = false) {
3402
+ const hibit = isLast ? 0 : 1 << 11;
3403
+ const { h, r } = this;
3404
+ const r0 = r[0];
3405
+ const r1 = r[1];
3406
+ const r2 = r[2];
3407
+ const r3 = r[3];
3408
+ const r4 = r[4];
3409
+ const r5 = r[5];
3410
+ const r6 = r[6];
3411
+ const r7 = r[7];
3412
+ const r8 = r[8];
3413
+ const r9 = r[9];
3414
+ const t0 = u8to16(data, offset + 0);
3415
+ const t1 = u8to16(data, offset + 2);
3416
+ const t2 = u8to16(data, offset + 4);
3417
+ const t3 = u8to16(data, offset + 6);
3418
+ const t4 = u8to16(data, offset + 8);
3419
+ const t5 = u8to16(data, offset + 10);
3420
+ const t6 = u8to16(data, offset + 12);
3421
+ const t7 = u8to16(data, offset + 14);
3422
+ let h0 = h[0] + (t0 & 8191);
3423
+ let h1 = h[1] + ((t0 >>> 13 | t1 << 3) & 8191);
3424
+ let h2 = h[2] + ((t1 >>> 10 | t2 << 6) & 8191);
3425
+ let h3 = h[3] + ((t2 >>> 7 | t3 << 9) & 8191);
3426
+ let h4 = h[4] + ((t3 >>> 4 | t4 << 12) & 8191);
3427
+ let h5 = h[5] + (t4 >>> 1 & 8191);
3428
+ let h6 = h[6] + ((t4 >>> 14 | t5 << 2) & 8191);
3429
+ let h7 = h[7] + ((t5 >>> 11 | t6 << 5) & 8191);
3430
+ let h8 = h[8] + ((t6 >>> 8 | t7 << 8) & 8191);
3431
+ let h9 = h[9] + (t7 >>> 5 | hibit);
3432
+ let c = 0;
3433
+ let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
3434
+ c = d0 >>> 13;
3435
+ d0 &= 8191;
3436
+ d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
3437
+ c += d0 >>> 13;
3438
+ d0 &= 8191;
3439
+ let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
3440
+ c = d1 >>> 13;
3441
+ d1 &= 8191;
3442
+ d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
3443
+ c += d1 >>> 13;
3444
+ d1 &= 8191;
3445
+ let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
3446
+ c = d2 >>> 13;
3447
+ d2 &= 8191;
3448
+ d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
3449
+ c += d2 >>> 13;
3450
+ d2 &= 8191;
3451
+ let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);
3452
+ c = d3 >>> 13;
3453
+ d3 &= 8191;
3454
+ d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
3455
+ c += d3 >>> 13;
3456
+ d3 &= 8191;
3457
+ let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
3458
+ c = d4 >>> 13;
3459
+ d4 &= 8191;
3460
+ d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
3461
+ c += d4 >>> 13;
3462
+ d4 &= 8191;
3463
+ let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;
3464
+ c = d5 >>> 13;
3465
+ d5 &= 8191;
3466
+ d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
3467
+ c += d5 >>> 13;
3468
+ d5 &= 8191;
3469
+ let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;
3470
+ c = d6 >>> 13;
3471
+ d6 &= 8191;
3472
+ d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
3473
+ c += d6 >>> 13;
3474
+ d6 &= 8191;
3475
+ let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;
3476
+ c = d7 >>> 13;
3477
+ d7 &= 8191;
3478
+ d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
3479
+ c += d7 >>> 13;
3480
+ d7 &= 8191;
3481
+ let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;
3482
+ c = d8 >>> 13;
3483
+ d8 &= 8191;
3484
+ d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
3485
+ c += d8 >>> 13;
3486
+ d8 &= 8191;
3487
+ let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;
3488
+ c = d9 >>> 13;
3489
+ d9 &= 8191;
3490
+ d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
3491
+ c += d9 >>> 13;
3492
+ d9 &= 8191;
3493
+ c = (c << 2) + c | 0;
3494
+ c = c + d0 | 0;
3495
+ d0 = c & 8191;
3496
+ c = c >>> 13;
3497
+ d1 += c;
3498
+ h[0] = d0;
3499
+ h[1] = d1;
3500
+ h[2] = d2;
3501
+ h[3] = d3;
3502
+ h[4] = d4;
3503
+ h[5] = d5;
3504
+ h[6] = d6;
3505
+ h[7] = d7;
3506
+ h[8] = d8;
3507
+ h[9] = d9;
3508
+ }
3509
+ finalize() {
3510
+ const { h, pad } = this;
3511
+ const g = new Uint16Array(10);
3512
+ let c = h[1] >>> 13;
3513
+ h[1] &= 8191;
3514
+ for (let i = 2; i < 10; i++) {
3515
+ h[i] += c;
3516
+ c = h[i] >>> 13;
3517
+ h[i] &= 8191;
3518
+ }
3519
+ h[0] += c * 5;
3520
+ c = h[0] >>> 13;
3521
+ h[0] &= 8191;
3522
+ h[1] += c;
3523
+ c = h[1] >>> 13;
3524
+ h[1] &= 8191;
3525
+ h[2] += c;
3526
+ g[0] = h[0] + 5;
3527
+ c = g[0] >>> 13;
3528
+ g[0] &= 8191;
3529
+ for (let i = 1; i < 10; i++) {
3530
+ g[i] = h[i] + c;
3531
+ c = g[i] >>> 13;
3532
+ g[i] &= 8191;
3533
+ }
3534
+ g[9] -= 1 << 13;
3535
+ let mask = (c ^ 1) - 1;
3536
+ for (let i = 0; i < 10; i++)
3537
+ g[i] &= mask;
3538
+ mask = ~mask;
3539
+ for (let i = 0; i < 10; i++)
3540
+ h[i] = h[i] & mask | g[i];
3541
+ h[0] = (h[0] | h[1] << 13) & 65535;
3542
+ h[1] = (h[1] >>> 3 | h[2] << 10) & 65535;
3543
+ h[2] = (h[2] >>> 6 | h[3] << 7) & 65535;
3544
+ h[3] = (h[3] >>> 9 | h[4] << 4) & 65535;
3545
+ h[4] = (h[4] >>> 12 | h[5] << 1 | h[6] << 14) & 65535;
3546
+ h[5] = (h[6] >>> 2 | h[7] << 11) & 65535;
3547
+ h[6] = (h[7] >>> 5 | h[8] << 8) & 65535;
3548
+ h[7] = (h[8] >>> 8 | h[9] << 5) & 65535;
3549
+ let f = h[0] + pad[0];
3550
+ h[0] = f & 65535;
3551
+ for (let i = 1; i < 8; i++) {
3552
+ f = (h[i] + pad[i] | 0) + (f >>> 16) | 0;
3553
+ h[i] = f & 65535;
3554
+ }
3555
+ clean2(g);
3556
+ }
3557
+ update(data) {
3558
+ aexists2(this);
3559
+ abytes3(data);
3560
+ data = copyBytes2(data);
3561
+ const { buffer, blockLen } = this;
3562
+ const len = data.length;
3563
+ for (let pos = 0; pos < len; ) {
3564
+ const take = Math.min(blockLen - this.pos, len - pos);
3565
+ if (take === blockLen) {
3566
+ for (; blockLen <= len - pos; pos += blockLen)
3567
+ this.process(data, pos);
3568
+ continue;
3569
+ }
3570
+ buffer.set(data.subarray(pos, pos + take), this.pos);
3571
+ this.pos += take;
3572
+ pos += take;
3573
+ if (this.pos === blockLen) {
3574
+ this.process(buffer, 0, false);
3575
+ this.pos = 0;
3576
+ }
3577
+ }
3578
+ return this;
3579
+ }
3580
+ destroy() {
3581
+ this.destroyed = true;
3582
+ clean2(this.h, this.r, this.buffer, this.pad);
3583
+ }
3584
+ digestInto(out) {
3585
+ aexists2(this);
3586
+ aoutput2(out, this);
3587
+ this.finished = true;
3588
+ const { buffer, h } = this;
3589
+ let { pos } = this;
3590
+ if (pos) {
3591
+ buffer[pos++] = 1;
3592
+ for (; pos < 16; pos++)
3593
+ buffer[pos] = 0;
3594
+ this.process(buffer, 0, true);
3595
+ }
3596
+ this.finalize();
3597
+ let opos = 0;
3598
+ for (let i = 0; i < 8; i++) {
3599
+ out[opos++] = h[i] >>> 0;
3600
+ out[opos++] = h[i] >>> 8;
3601
+ }
3602
+ }
3603
+ digest() {
3604
+ const { buffer, outputLen } = this;
3605
+ this.digestInto(buffer);
3606
+ const res = buffer.slice(0, outputLen);
3607
+ this.destroy();
3608
+ return res;
3609
+ }
3610
+ };
3611
+ var poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key));
3612
+
3613
+ // node_modules/@noble/ciphers/chacha.js
3614
+ function chachaCore(s, k, n, out, cnt, rounds = 20) {
3615
+ let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2];
3616
+ let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
3617
+ for (let r = 0; r < rounds; r += 2) {
3618
+ x00 = x00 + x04 | 0;
3619
+ x12 = rotl(x12 ^ x00, 16);
3620
+ x08 = x08 + x12 | 0;
3621
+ x04 = rotl(x04 ^ x08, 12);
3622
+ x00 = x00 + x04 | 0;
3623
+ x12 = rotl(x12 ^ x00, 8);
3624
+ x08 = x08 + x12 | 0;
3625
+ x04 = rotl(x04 ^ x08, 7);
3626
+ x01 = x01 + x05 | 0;
3627
+ x13 = rotl(x13 ^ x01, 16);
3628
+ x09 = x09 + x13 | 0;
3629
+ x05 = rotl(x05 ^ x09, 12);
3630
+ x01 = x01 + x05 | 0;
3631
+ x13 = rotl(x13 ^ x01, 8);
3632
+ x09 = x09 + x13 | 0;
3633
+ x05 = rotl(x05 ^ x09, 7);
3634
+ x02 = x02 + x06 | 0;
3635
+ x14 = rotl(x14 ^ x02, 16);
3636
+ x10 = x10 + x14 | 0;
3637
+ x06 = rotl(x06 ^ x10, 12);
3638
+ x02 = x02 + x06 | 0;
3639
+ x14 = rotl(x14 ^ x02, 8);
3640
+ x10 = x10 + x14 | 0;
3641
+ x06 = rotl(x06 ^ x10, 7);
3642
+ x03 = x03 + x07 | 0;
3643
+ x15 = rotl(x15 ^ x03, 16);
3644
+ x11 = x11 + x15 | 0;
3645
+ x07 = rotl(x07 ^ x11, 12);
3646
+ x03 = x03 + x07 | 0;
3647
+ x15 = rotl(x15 ^ x03, 8);
3648
+ x11 = x11 + x15 | 0;
3649
+ x07 = rotl(x07 ^ x11, 7);
3650
+ x00 = x00 + x05 | 0;
3651
+ x15 = rotl(x15 ^ x00, 16);
3652
+ x10 = x10 + x15 | 0;
3653
+ x05 = rotl(x05 ^ x10, 12);
3654
+ x00 = x00 + x05 | 0;
3655
+ x15 = rotl(x15 ^ x00, 8);
3656
+ x10 = x10 + x15 | 0;
3657
+ x05 = rotl(x05 ^ x10, 7);
3658
+ x01 = x01 + x06 | 0;
3659
+ x12 = rotl(x12 ^ x01, 16);
3660
+ x11 = x11 + x12 | 0;
3661
+ x06 = rotl(x06 ^ x11, 12);
3662
+ x01 = x01 + x06 | 0;
3663
+ x12 = rotl(x12 ^ x01, 8);
3664
+ x11 = x11 + x12 | 0;
3665
+ x06 = rotl(x06 ^ x11, 7);
3666
+ x02 = x02 + x07 | 0;
3667
+ x13 = rotl(x13 ^ x02, 16);
3668
+ x08 = x08 + x13 | 0;
3669
+ x07 = rotl(x07 ^ x08, 12);
3670
+ x02 = x02 + x07 | 0;
3671
+ x13 = rotl(x13 ^ x02, 8);
3672
+ x08 = x08 + x13 | 0;
3673
+ x07 = rotl(x07 ^ x08, 7);
3674
+ x03 = x03 + x04 | 0;
3675
+ x14 = rotl(x14 ^ x03, 16);
3676
+ x09 = x09 + x14 | 0;
3677
+ x04 = rotl(x04 ^ x09, 12);
3678
+ x03 = x03 + x04 | 0;
3679
+ x14 = rotl(x14 ^ x03, 8);
3680
+ x09 = x09 + x14 | 0;
3681
+ x04 = rotl(x04 ^ x09, 7);
3682
+ }
3683
+ let oi = 0;
3684
+ out[oi++] = y00 + x00 | 0;
3685
+ out[oi++] = y01 + x01 | 0;
3686
+ out[oi++] = y02 + x02 | 0;
3687
+ out[oi++] = y03 + x03 | 0;
3688
+ out[oi++] = y04 + x04 | 0;
3689
+ out[oi++] = y05 + x05 | 0;
3690
+ out[oi++] = y06 + x06 | 0;
3691
+ out[oi++] = y07 + x07 | 0;
3692
+ out[oi++] = y08 + x08 | 0;
3693
+ out[oi++] = y09 + x09 | 0;
3694
+ out[oi++] = y10 + x10 | 0;
3695
+ out[oi++] = y11 + x11 | 0;
3696
+ out[oi++] = y12 + x12 | 0;
3697
+ out[oi++] = y13 + x13 | 0;
3698
+ out[oi++] = y14 + x14 | 0;
3699
+ out[oi++] = y15 + x15 | 0;
3700
+ }
3701
+ function hchacha(s, k, i, out) {
3702
+ let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(s[1]), x02 = swap8IfBE(s[2]), x03 = swap8IfBE(s[3]), x04 = swap8IfBE(k[0]), x05 = swap8IfBE(k[1]), x06 = swap8IfBE(k[2]), x07 = swap8IfBE(k[3]), x08 = swap8IfBE(k[4]), x09 = swap8IfBE(k[5]), x10 = swap8IfBE(k[6]), x11 = swap8IfBE(k[7]), x12 = swap8IfBE(i[0]), x13 = swap8IfBE(i[1]), x14 = swap8IfBE(i[2]), x15 = swap8IfBE(i[3]);
3703
+ for (let r = 0; r < 20; r += 2) {
3704
+ x00 = x00 + x04 | 0;
3705
+ x12 = rotl(x12 ^ x00, 16);
3706
+ x08 = x08 + x12 | 0;
3707
+ x04 = rotl(x04 ^ x08, 12);
3708
+ x00 = x00 + x04 | 0;
3709
+ x12 = rotl(x12 ^ x00, 8);
3710
+ x08 = x08 + x12 | 0;
3711
+ x04 = rotl(x04 ^ x08, 7);
3712
+ x01 = x01 + x05 | 0;
3713
+ x13 = rotl(x13 ^ x01, 16);
3714
+ x09 = x09 + x13 | 0;
3715
+ x05 = rotl(x05 ^ x09, 12);
3716
+ x01 = x01 + x05 | 0;
3717
+ x13 = rotl(x13 ^ x01, 8);
3718
+ x09 = x09 + x13 | 0;
3719
+ x05 = rotl(x05 ^ x09, 7);
3720
+ x02 = x02 + x06 | 0;
3721
+ x14 = rotl(x14 ^ x02, 16);
3722
+ x10 = x10 + x14 | 0;
3723
+ x06 = rotl(x06 ^ x10, 12);
3724
+ x02 = x02 + x06 | 0;
3725
+ x14 = rotl(x14 ^ x02, 8);
3726
+ x10 = x10 + x14 | 0;
3727
+ x06 = rotl(x06 ^ x10, 7);
3728
+ x03 = x03 + x07 | 0;
3729
+ x15 = rotl(x15 ^ x03, 16);
3730
+ x11 = x11 + x15 | 0;
3731
+ x07 = rotl(x07 ^ x11, 12);
3732
+ x03 = x03 + x07 | 0;
3733
+ x15 = rotl(x15 ^ x03, 8);
3734
+ x11 = x11 + x15 | 0;
3735
+ x07 = rotl(x07 ^ x11, 7);
3736
+ x00 = x00 + x05 | 0;
3737
+ x15 = rotl(x15 ^ x00, 16);
3738
+ x10 = x10 + x15 | 0;
3739
+ x05 = rotl(x05 ^ x10, 12);
3740
+ x00 = x00 + x05 | 0;
3741
+ x15 = rotl(x15 ^ x00, 8);
3742
+ x10 = x10 + x15 | 0;
3743
+ x05 = rotl(x05 ^ x10, 7);
3744
+ x01 = x01 + x06 | 0;
3745
+ x12 = rotl(x12 ^ x01, 16);
3746
+ x11 = x11 + x12 | 0;
3747
+ x06 = rotl(x06 ^ x11, 12);
3748
+ x01 = x01 + x06 | 0;
3749
+ x12 = rotl(x12 ^ x01, 8);
3750
+ x11 = x11 + x12 | 0;
3751
+ x06 = rotl(x06 ^ x11, 7);
3752
+ x02 = x02 + x07 | 0;
3753
+ x13 = rotl(x13 ^ x02, 16);
3754
+ x08 = x08 + x13 | 0;
3755
+ x07 = rotl(x07 ^ x08, 12);
3756
+ x02 = x02 + x07 | 0;
3757
+ x13 = rotl(x13 ^ x02, 8);
3758
+ x08 = x08 + x13 | 0;
3759
+ x07 = rotl(x07 ^ x08, 7);
3760
+ x03 = x03 + x04 | 0;
3761
+ x14 = rotl(x14 ^ x03, 16);
3762
+ x09 = x09 + x14 | 0;
3763
+ x04 = rotl(x04 ^ x09, 12);
3764
+ x03 = x03 + x04 | 0;
3765
+ x14 = rotl(x14 ^ x03, 8);
3766
+ x09 = x09 + x14 | 0;
3767
+ x04 = rotl(x04 ^ x09, 7);
3768
+ }
3769
+ let oi = 0;
3770
+ out[oi++] = x00;
3771
+ out[oi++] = x01;
3772
+ out[oi++] = x02;
3773
+ out[oi++] = x03;
3774
+ out[oi++] = x12;
3775
+ out[oi++] = x13;
3776
+ out[oi++] = x14;
3777
+ out[oi++] = x15;
3778
+ swap32IfBE(out);
3779
+ }
3780
+ var xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {
3781
+ counterRight: false,
3782
+ counterLength: 8,
3783
+ extendNonceFn: hchacha,
3784
+ allowShortKeys: false
3785
+ });
3786
+ var ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
3787
+ var updatePadded = (h, msg) => {
3788
+ h.update(msg);
3789
+ const leftover = msg.length % 16;
3790
+ if (leftover)
3791
+ h.update(ZEROS16.subarray(leftover));
3792
+ };
3793
+ var ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
3794
+ function computeTag(fn, key, nonce, ciphertext, AAD) {
3795
+ if (AAD !== void 0)
3796
+ abytes3(AAD, void 0, "AAD");
3797
+ const authKey = fn(key, nonce, ZEROS32);
3798
+ const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);
3799
+ const h = poly1305.create(authKey);
3800
+ if (AAD)
3801
+ updatePadded(h, AAD);
3802
+ updatePadded(h, ciphertext);
3803
+ h.update(lengths);
3804
+ const res = h.digest();
3805
+ clean2(authKey, lengths);
3806
+ return res;
3807
+ }
3808
+ var _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
3809
+ const tagLength = 16;
3810
+ return {
3811
+ encrypt(plaintext, output) {
3812
+ const plength = plaintext.length;
3813
+ output = getOutput(plength + tagLength, output, false);
3814
+ output.set(plaintext);
3815
+ const oPlain = output.subarray(0, -tagLength);
3816
+ xorStream(key, nonce, oPlain, oPlain, 1);
3817
+ const tag = computeTag(xorStream, key, nonce, oPlain, AAD);
3818
+ output.set(tag, plength);
3819
+ clean2(tag);
3820
+ return output;
3821
+ },
3822
+ decrypt(ciphertext, output) {
3823
+ output = getOutput(ciphertext.length - tagLength, output, false);
3824
+ const data = ciphertext.subarray(0, -tagLength);
3825
+ const passedTag = ciphertext.subarray(-tagLength);
3826
+ const tag = computeTag(xorStream, key, nonce, data, AAD);
3827
+ if (!equalBytes(passedTag, tag)) {
3828
+ clean2(tag);
3829
+ throw new Error("invalid tag");
3830
+ }
3831
+ output.set(ciphertext.subarray(0, -tagLength));
3832
+ xorStream(key, nonce, output, output, 1);
3833
+ clean2(tag);
3834
+ return output;
3835
+ }
3836
+ };
3837
+ };
3838
+ var xchacha20poly1305 = /* @__PURE__ */ wrapCipher(
3839
+ { blockSize: 64, nonceLength: 24, tagLength: 16 },
3840
+ /* @__PURE__ */ _poly1305_aead(xchacha20)
3841
+ );
3842
+
3843
+ // core/errors.ts
3844
+ var SphereError = class extends Error {
3845
+ code;
3846
+ cause;
3847
+ /**
3848
+ * #441 deferred-paid linkage: the transferId of the possibly-committed send,
3849
+ * stamped by `sendOnce` before the error leaves so a payment-request consumer
3850
+ * can durably journal request→transfer and resolve 'paid' only when that
3851
+ * transfer actually completes (never optimistically). Present ONLY on
3852
+ * possibly-committed outcomes ({@link isPossiblyCommittedSendOutcome}).
3853
+ */
3854
+ transferId;
3855
+ constructor(message, code, cause) {
3856
+ super(message);
3857
+ this.name = "SphereError";
3858
+ this.code = code;
3859
+ this.cause = cause;
3860
+ }
3861
+ };
3862
+
3863
+ // core/field-encryption.ts
3864
+ var FIELD_ENVELOPE_PREFIX = "enc1.";
3865
+ var FIELD_ENVELOPE_NONCE_BYTES = 24;
3866
+ var POLY1305_TAG_BYTES = 16;
3867
+ var B64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3868
+ var B64_LOOKUP = {};
3869
+ for (let i = 0; i < B64_ALPHABET.length; i++) B64_LOOKUP[B64_ALPHABET[i]] = i;
3870
+ function base64Encode(bytes) {
3871
+ let out = "";
3872
+ for (let i = 0; i < bytes.length; i += 3) {
3873
+ const b0 = bytes[i];
3874
+ const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;
3875
+ const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;
3876
+ out += B64_ALPHABET[b0 >> 2];
3877
+ out += B64_ALPHABET[(b0 & 3) << 4 | b1 >> 4];
3878
+ out += i + 1 < bytes.length ? B64_ALPHABET[(b1 & 15) << 2 | b2 >> 6] : "=";
3879
+ out += i + 2 < bytes.length ? B64_ALPHABET[b2 & 63] : "=";
3880
+ }
3881
+ return out;
3882
+ }
3883
+ function base64Decode(s) {
3884
+ if (s.length % 4 !== 0) {
3885
+ throw new SphereError("Invalid field envelope: base64 length not a multiple of 4", "DECRYPTION_ERROR");
3886
+ }
3887
+ let padding = 0;
3888
+ if (s.endsWith("==")) padding = 2;
3889
+ else if (s.endsWith("=")) padding = 1;
3890
+ const body = s.slice(0, s.length - padding);
3891
+ if (body.includes("=")) {
3892
+ throw new SphereError("Invalid field envelope: misplaced base64 padding", "DECRYPTION_ERROR");
3893
+ }
3894
+ const out = new Uint8Array(s.length / 4 * 3 - padding);
3895
+ let o = 0;
3896
+ for (let i = 0; i < body.length; i += 4) {
3897
+ const n0 = B64_LOOKUP[body[i]];
3898
+ const n1 = B64_LOOKUP[body[i + 1]];
3899
+ const n2 = body[i + 2] !== void 0 ? B64_LOOKUP[body[i + 2]] : 0;
3900
+ const n3 = body[i + 3] !== void 0 ? B64_LOOKUP[body[i + 3]] : 0;
3901
+ if (n0 === void 0 || n1 === void 0 || n2 === void 0 || n3 === void 0) {
3902
+ throw new SphereError("Invalid field envelope: non-base64 character", "DECRYPTION_ERROR");
3903
+ }
3904
+ const triple = n0 << 18 | n1 << 12 | n2 << 6 | n3;
3905
+ if (o < out.length) out[o++] = triple >> 16 & 255;
3906
+ if (o < out.length) out[o++] = triple >> 8 & 255;
3907
+ if (o < out.length) out[o++] = triple & 255;
3908
+ }
3909
+ return out;
3910
+ }
3911
+ function encryptFieldBytes(key, plaintext, aad) {
3912
+ const nonce = randomBytes3(FIELD_ENVELOPE_NONCE_BYTES);
3913
+ const ciphertext = xchacha20poly1305(key, nonce, aad).encrypt(plaintext);
3914
+ const packed = new Uint8Array(nonce.length + ciphertext.length);
3915
+ packed.set(nonce, 0);
3916
+ packed.set(ciphertext, nonce.length);
3917
+ return FIELD_ENVELOPE_PREFIX + base64Encode(packed);
3918
+ }
3919
+ function decryptFieldBytes(key, envelope, aad) {
3920
+ if (typeof envelope !== "string" || !envelope.startsWith(FIELD_ENVELOPE_PREFIX)) {
3921
+ throw new SphereError('Invalid field envelope: missing "enc1." prefix', "DECRYPTION_ERROR");
3922
+ }
3923
+ const packed = base64Decode(envelope.slice(FIELD_ENVELOPE_PREFIX.length));
3924
+ if (packed.length < FIELD_ENVELOPE_NONCE_BYTES + POLY1305_TAG_BYTES) {
3925
+ throw new SphereError("Invalid field envelope: too short for nonce + tag", "DECRYPTION_ERROR");
3926
+ }
3927
+ const nonce = packed.slice(0, FIELD_ENVELOPE_NONCE_BYTES);
3928
+ const ciphertext = packed.slice(FIELD_ENVELOPE_NONCE_BYTES);
3929
+ try {
3930
+ return xchacha20poly1305(key, nonce, aad).decrypt(ciphertext);
3931
+ } catch (err) {
3932
+ throw new SphereError("Field envelope authentication failed (tampered, wrong key, or wrong AAD)", "DECRYPTION_ERROR", err);
3933
+ }
3934
+ }
3935
+ function encryptField(key, plaintext) {
3936
+ return encryptFieldBytes(key, new TextEncoder().encode(plaintext));
3937
+ }
3938
+ function decryptField(key, envelope) {
3939
+ return new TextDecoder().decode(decryptFieldBytes(key, envelope));
3940
+ }
3941
+
3942
+ // core/delivery-envelope.ts
3943
+ var DELIVERY_ENCRYPTION_HKDF_INFO = "sphere-deliveryenc-v1";
3944
+ function hexToBytesStrict(hex, what) {
3945
+ if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex)) {
3946
+ throw new SphereError(`Invalid ${what} hex for delivery-envelope key derivation`, "INVALID_CONFIG");
3947
+ }
3948
+ const out = new Uint8Array(hex.length / 2);
3949
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
3950
+ return out;
3951
+ }
3952
+ function deriveDeliveryEncryptionKey(privKeyHex, peerPubkeyHex) {
3953
+ const priv = hexToBytesStrict(privKeyHex, "private key");
3954
+ const peerPub = hexToBytesStrict(peerPubkeyHex, "peer public key");
3955
+ const shared = secp256k1.getSharedSecret(priv, peerPub);
3956
+ const info = new TextEncoder().encode(DELIVERY_ENCRYPTION_HKDF_INFO);
3957
+ return hkdf(sha256, shared, void 0, info, 32);
3958
+ }
3959
+ function encryptDeliveryBundle(key, bundle) {
3960
+ const compact = {};
3961
+ if (bundle.senderNametag !== void 0 && bundle.senderNametag !== "") compact.n = bundle.senderNametag;
3962
+ if (bundle.memo !== void 0 && bundle.memo !== "") compact.t = bundle.memo;
3963
+ if (compact.n === void 0 && compact.t === void 0) return void 0;
3964
+ return encryptField(key, JSON.stringify(compact));
3965
+ }
3966
+ function decryptDeliveryBundle(key, envelope) {
3967
+ const plaintext = decryptField(key, envelope);
3968
+ let parsed;
3969
+ try {
3970
+ parsed = JSON.parse(plaintext);
3971
+ } catch (err) {
3972
+ throw new SphereError("Delivery envelope payload is not valid JSON", "DECRYPTION_ERROR", err);
3973
+ }
3974
+ if (typeof parsed !== "object" || parsed === null) {
3975
+ throw new SphereError("Delivery envelope payload is not an object", "DECRYPTION_ERROR");
3976
+ }
3977
+ const obj = parsed;
3978
+ const bundle = {};
3979
+ if (typeof obj.n === "string") bundle.senderNametag = obj.n;
3980
+ if (typeof obj.t === "string") bundle.memo = obj.t;
3981
+ return bundle;
3982
+ }
3983
+
3984
+ // impl/wallet-api-v2/mailbox.ts
3985
+ var DeliveryKeysUnboundError = class extends Error {
3986
+ code = "DELIVERY_KEYS_UNBOUND";
3987
+ constructor() {
3988
+ super("deliveryKeys derivation not bound \u2014 bindDeliveryKeys(engine.deliveryKeys) must run first (S7)");
3989
+ this.name = "DeliveryKeysUnboundError";
3990
+ }
3991
+ };
3992
+ var MailboxClaimFailedError = class extends Error {
3993
+ constructor(deliveryId, failureCode) {
3994
+ super(`mailbox claim failed for ${deliveryId}: ${failureCode}`);
3995
+ this.failureCode = failureCode;
3996
+ this.name = "MailboxClaimFailedError";
3997
+ }
3998
+ code = "MAILBOX_CLAIM_FAILED";
3999
+ };
4000
+ var DeliveryProtocolError = class extends Error {
4001
+ code = "PROTOCOL";
4002
+ constructor(message) {
4003
+ super(message);
4004
+ this.name = "DeliveryProtocolError";
4005
+ }
4006
+ };
4007
+ function hexToBytes3(hex) {
4008
+ const out = new Uint8Array(hex.length / 2);
4009
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
4010
+ return out;
4011
+ }
4012
+ function bytesToHex4(bytes) {
4013
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
4014
+ }
4015
+ function computeDeliveryId(tokenIdHex, stateHashHex) {
4016
+ const tokenId = hexToBytes3(tokenIdHex);
4017
+ const stateHash = hexToBytes3(stateHashHex);
4018
+ const joined = new Uint8Array(tokenId.length + stateHash.length);
4019
+ joined.set(tokenId, 0);
4020
+ joined.set(stateHash, tokenId.length);
4021
+ return bytesToHex4(sha256(joined));
4022
+ }
4023
+ var DELIVERY_SEEN_KEY = "delivery:seen";
4024
+ var WalletApiDeliveryPort = class {
4025
+ custody;
4026
+ client;
4027
+ kv;
4028
+ identity;
4029
+ wake;
4030
+ deriveFn;
4031
+ seenChain = Promise.resolve();
4032
+ constructor(config) {
4033
+ this.client = config.client;
4034
+ this.kv = config.kv;
4035
+ this.identity = config.identity;
4036
+ this.custody = config.custody;
4037
+ this.wake = config.wake ?? null;
4038
+ this.deriveFn = config.deliveryKeys ?? null;
4039
+ }
4040
+ bindDeliveryKeys(derive) {
4041
+ this.deriveFn = derive;
4042
+ }
4043
+ deriveKeys(blob) {
4044
+ if (this.deriveFn === null) throw new DeliveryKeysUnboundError();
4045
+ return this.deriveFn(blob);
4046
+ }
4047
+ // ── deliver ────────────────────────────────────────────────────────────────
4048
+ async deliver(recipientPubkey, blob, options) {
4049
+ const receipts = await this.deliverBatch(recipientPubkey, [blob], options);
4050
+ const first = receipts[0];
4051
+ if (first === void 0) throw new DeliveryProtocolError("deliver produced no receipt");
4052
+ return first;
4053
+ }
4054
+ async deliverBatch(recipientPubkey, blobs, options) {
4055
+ if (blobs.length === 0) return [];
4056
+ const prepared = await Promise.all(blobs.map(async (bytes) => this.prepare(bytes)));
4057
+ const envelope = this.buildEnvelope(recipientPubkey, options);
4058
+ const keyBySha = await this.upload(prepared);
4059
+ const entries = prepared.map((p) => {
4060
+ const key = keyBySha.get(p.sha);
4061
+ if (key === void 0) throw new DeliveryProtocolError(`upload returned no key for sha256 ${p.sha}`);
4062
+ return {
4063
+ recipientPubkey,
4064
+ key,
4065
+ transferId: options.transferId,
4066
+ tokenId: p.tokenId,
4067
+ stateHash: p.stateHash,
4068
+ ...envelope !== void 0 ? { memo: envelope } : {}
4069
+ };
4070
+ });
4071
+ return this.depositAll(entries, prepared.map((p) => p.deliveryId));
4072
+ }
4073
+ async prepare(bytes) {
4074
+ const keys = await this.deriveKeys(bytes);
4075
+ return {
4076
+ bytes,
4077
+ tokenId: keys.tokenId,
4078
+ stateHash: keys.stateHash,
4079
+ deliveryId: computeDeliveryId(keys.tokenId, keys.stateHash),
4080
+ sha: bytesToHex4(sha256(bytes))
4081
+ };
4082
+ }
4083
+ buildEnvelope(recipientPubkey, options) {
4084
+ const key = deriveDeliveryEncryptionKey(this.identity.privateKey, recipientPubkey);
4085
+ return encryptDeliveryBundle(key, {
4086
+ senderNametag: options.senderNametag ?? this.identity.nametag,
4087
+ memo: options.memo
4088
+ });
4089
+ }
4090
+ async upload(prepared) {
4091
+ const urls = await this.client.uploadUrls(prepared.map((p) => ({ sha256: p.sha, size: p.bytes.length })));
4092
+ const urlBySha = new Map(urls.map((u) => [u.sha256, u]));
4093
+ const uploads = prepared.map((p) => {
4094
+ const url = urlBySha.get(p.sha);
4095
+ if (url === void 0) throw new DeliveryProtocolError(`upload-urls response missing sha256 ${p.sha}`);
4096
+ return { p, url };
4097
+ });
4098
+ await mapBounded(uploads, WALLET_API_V2_FANOUT_WIDTH, ({ p, url }) => this.client.uploadBlob(url.putUrl, p.bytes));
4099
+ return new Map(uploads.map(({ url }) => [url.sha256, url.key]));
4100
+ }
4101
+ async depositAll(entries, deliveryIds) {
4102
+ if (entries.length > 1) {
4103
+ try {
4104
+ const results = await this.client.depositBatch(entries);
4105
+ if (results.length !== entries.length) {
4106
+ throw new DeliveryProtocolError(
4107
+ `mailbox batch deposit returned ${String(results.length)} entries for ${String(entries.length)}`
4108
+ );
4109
+ }
4110
+ return deliveryIds.map((deliveryId) => ({ deliveryId }));
4111
+ } catch (err) {
4112
+ if (!isWalletApiHttpError(err, 409)) throw err;
4113
+ }
4114
+ }
4115
+ const receipts = [];
4116
+ for (const [i, entry] of entries.entries()) {
4117
+ receipts.push(await this.depositOne(entry, deliveryIds[i]));
4118
+ }
4119
+ return receipts;
4120
+ }
4121
+ async depositOne(entry, deliveryId) {
4122
+ try {
4123
+ await this.client.deposit(entry);
4124
+ } catch (err) {
4125
+ if (!isWalletApiHttpError(err, 409)) throw err;
4126
+ }
4127
+ return { deliveryId };
4128
+ }
4129
+ // ── incoming ───────────────────────────────────────────────────────────────
4130
+ async *incoming(sinceCursor) {
4131
+ const seen = await this.readSeen();
4132
+ let page = await this.client.listMailbox(sinceCursor === void 0 ? 0 : Number(sinceCursor));
4133
+ for (; ; ) {
4134
+ for (const entry of page.entries) {
4135
+ if (entry.status !== "unclaimed") continue;
4136
+ if (seen.has(entry.entryId)) continue;
4137
+ yield this.toIncoming(entry);
4138
+ }
4139
+ if (!page.more) return;
4140
+ page = await this.client.listMailbox(page.cursor);
4141
+ }
4142
+ }
4143
+ toIncoming(entry) {
4144
+ const bundle = this.openEnvelope(entry);
4145
+ return {
4146
+ deliveryId: entry.entryId,
4147
+ ...entry.transferId !== "" ? { transferId: entry.transferId } : {},
4148
+ ...entry.senderPubkey !== "" ? { senderPubkey: entry.senderPubkey } : {},
4149
+ ...bundle.senderNametag !== void 0 ? { senderNametag: bundle.senderNametag } : {},
4150
+ ...bundle.memo !== void 0 ? { memo: bundle.memo } : {},
4151
+ cursor: String(entry.seq),
4152
+ fetchBlob: () => this.fetchVerified(entry)
4153
+ };
4154
+ }
4155
+ openEnvelope(entry) {
4156
+ if (entry.memo === void 0 || entry.senderPubkey === "") return {};
4157
+ try {
4158
+ const key = deriveDeliveryEncryptionKey(this.identity.privateKey, entry.senderPubkey);
4159
+ return decryptDeliveryBundle(key, entry.memo);
4160
+ } catch {
4161
+ return {};
4162
+ }
4163
+ }
4164
+ async fetchVerified(entry) {
4165
+ if (entry.blobCollected === true || entry.getUrl === void 0) {
4166
+ throw new DeliveryProtocolError(`mailbox entry ${entry.entryId} has no fetchable blob (blobCollected)`);
4167
+ }
4168
+ const bytes = await this.client.fetchBlob(entry.getUrl);
4169
+ const keys = await this.deriveKeys(bytes);
4170
+ const derived = computeDeliveryId(keys.tokenId, keys.stateHash);
4171
+ if (derived !== entry.entryId) {
4172
+ throw new DeliveryProtocolError(
4173
+ `mailbox blob does not match its entry id (expected ${entry.entryId}, bytes derive ${derived})`
4174
+ );
4175
+ }
4176
+ return bytes;
4177
+ }
4178
+ // ── ack ────────────────────────────────────────────────────────────────────
4179
+ async ack(deliveryId, disposition, reason) {
4180
+ if (disposition === "claimed") {
4181
+ const result = await this.client.claim([deliveryId], this.custody === "inventory");
4182
+ const failed = result.failed.find((f) => f.entryId === deliveryId);
4183
+ if (failed !== void 0) throw new MailboxClaimFailedError(deliveryId, failed.code);
4184
+ } else {
4185
+ await this.client.reject([deliveryId], reason);
4186
+ }
4187
+ await this.addSeen(deliveryId);
4188
+ }
4189
+ onWake(cb) {
4190
+ if (this.wake === null) return () => void 0;
4191
+ return this.wake.subscribeStream("mailbox", cb);
4192
+ }
4193
+ // ── seen-set (S7) ──────────────────────────────────────────────────────────
4194
+ async readSeen() {
4195
+ const raw = await this.kv.get(DELIVERY_SEEN_KEY);
4196
+ return new Set(raw ?? []);
4197
+ }
4198
+ addSeen(deliveryId) {
4199
+ this.seenChain = this.seenChain.then(async () => {
4200
+ const seen = await this.readSeen();
4201
+ seen.add(deliveryId);
4202
+ await this.kv.set(DELIVERY_SEEN_KEY, [...seen]);
4203
+ });
4204
+ return this.seenChain;
4205
+ }
4206
+ };
4207
+
4208
+ // token-engine/sdk.ts
4209
+ var import_StateTransitionClient = require("@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js");
4210
+ var import_AggregatorClient = require("@unicitylabs/state-transition-sdk/lib/api/AggregatorClient.js");
4211
+ var import_NetworkId = require("@unicitylabs/state-transition-sdk/lib/api/NetworkId.js");
4212
+ var import_CertificationData = require("@unicitylabs/state-transition-sdk/lib/api/CertificationData.js");
4213
+ var import_CertificationResponse = require("@unicitylabs/state-transition-sdk/lib/api/CertificationResponse.js");
4214
+ var import_StateId = require("@unicitylabs/state-transition-sdk/lib/api/StateId.js");
4215
+ var import_InclusionProof = require("@unicitylabs/state-transition-sdk/lib/api/InclusionProof.js");
4216
+ var import_InclusionProofResponse = require("@unicitylabs/state-transition-sdk/lib/api/InclusionProofResponse.js");
4217
+ var import_RootTrustBase = require("@unicitylabs/state-transition-sdk/lib/api/bft/RootTrustBase.js");
4218
+ var import_InclusionProofUtils = require("@unicitylabs/state-transition-sdk/lib/util/InclusionProofUtils.js");
4219
+ var import_InclusionProofVerificationRule = require("@unicitylabs/state-transition-sdk/lib/transaction/verification/rule/InclusionProofVerificationRule.js");
4220
+ var import_Token = require("@unicitylabs/state-transition-sdk/lib/transaction/Token.js");
4221
+ var import_MintTransaction = require("@unicitylabs/state-transition-sdk/lib/transaction/MintTransaction.js");
4222
+ var import_TransferTransaction = require("@unicitylabs/state-transition-sdk/lib/transaction/TransferTransaction.js");
4223
+ var import_CertifiedMintTransaction = require("@unicitylabs/state-transition-sdk/lib/transaction/CertifiedMintTransaction.js");
4224
+ var import_CertifiedTransferTransaction = require("@unicitylabs/state-transition-sdk/lib/transaction/CertifiedTransferTransaction.js");
4225
+ var import_TokenId = require("@unicitylabs/state-transition-sdk/lib/transaction/TokenId.js");
4226
+ var import_TokenType = require("@unicitylabs/state-transition-sdk/lib/transaction/TokenType.js");
4227
+ var import_TokenSalt = require("@unicitylabs/state-transition-sdk/lib/transaction/TokenSalt.js");
4228
+ var import_StateMask = require("@unicitylabs/state-transition-sdk/lib/transaction/StateMask.js");
4229
+ var import_MintJustificationVerifierService = require("@unicitylabs/state-transition-sdk/lib/transaction/verification/MintJustificationVerifierService.js");
4230
+ var import_TokenIssuanceVerifierService = require("@unicitylabs/state-transition-sdk/lib/transaction/verification/TokenIssuanceVerifierService.js");
4231
+ var import_VerificationContext = require("@unicitylabs/state-transition-sdk/lib/transaction/verification/VerificationContext.js");
4232
+ var import_WorkerTokenVerifier = require("@unicitylabs/state-transition-sdk/lib/transaction/verification/worker/WorkerTokenVerifier.js");
4233
+ var import_EncodedPredicate = require("@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js");
4234
+ var import_SignaturePredicate = require("@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicate.js");
4235
+ var import_SignaturePredicateUnlockScript = require("@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicateUnlockScript.js");
4236
+ var import_BurnPredicate = require("@unicitylabs/state-transition-sdk/lib/predicate/builtin/BurnPredicate.js");
4237
+ var import_PredicateVerifierService = require("@unicitylabs/state-transition-sdk/lib/predicate/verification/PredicateVerifierService.js");
4238
+ var import_SigningService = require("@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js");
4239
+ var import_Signature = require("@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/Signature.js");
4240
+ var import_MintSigningService = require("@unicitylabs/state-transition-sdk/lib/crypto/MintSigningService.js");
4241
+ var import_HashAlgorithm = require("@unicitylabs/state-transition-sdk/lib/crypto/hash/HashAlgorithm.js");
4242
+ var import_DataHash = require("@unicitylabs/state-transition-sdk/lib/crypto/hash/DataHash.js");
4243
+ var import_DataHasher = require("@unicitylabs/state-transition-sdk/lib/crypto/hash/DataHasher.js");
4244
+ var import_DataHasherFactory = require("@unicitylabs/state-transition-sdk/lib/crypto/hash/DataHasherFactory.js");
4245
+ var import_CborSerializer = require("@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborSerializer.js");
4246
+ var import_CborDeserializer = require("@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborDeserializer.js");
4247
+ var import_CborError = require("@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborError.js");
4248
+ var import_Asset = require("@unicitylabs/state-transition-sdk/lib/payment/asset/Asset.js");
4249
+ var import_AssetId = require("@unicitylabs/state-transition-sdk/lib/payment/asset/AssetId.js");
4250
+ var import_PaymentAssetCollection = require("@unicitylabs/state-transition-sdk/lib/payment/asset/PaymentAssetCollection.js");
4251
+ var import_TokenSplit = require("@unicitylabs/state-transition-sdk/lib/payment/TokenSplit.js");
4252
+ var import_SplitTokenRequest = require("@unicitylabs/state-transition-sdk/lib/payment/SplitTokenRequest.js");
4253
+ var import_SplitToken = require("@unicitylabs/state-transition-sdk/lib/payment/SplitToken.js");
4254
+ var import_SplitAllocationProof = require("@unicitylabs/state-transition-sdk/lib/payment/SplitAllocationProof.js");
4255
+ var import_SplitMintJustification = require("@unicitylabs/state-transition-sdk/lib/payment/SplitMintJustification.js");
4256
+ var import_SplitMintJustificationVerifier = require("@unicitylabs/state-transition-sdk/lib/payment/SplitMintJustificationVerifier.js");
4257
+ var import_VerificationStatus = require("@unicitylabs/state-transition-sdk/lib/verification/VerificationStatus.js");
4258
+ var import_VerificationResult = require("@unicitylabs/state-transition-sdk/lib/verification/VerificationResult.js");
4259
+ var import_HexConverter = require("@unicitylabs/state-transition-sdk/lib/util/HexConverter.js");
4260
+ var import_BigintConverter = require("@unicitylabs/state-transition-sdk/lib/util/BigintConverter.js");
4261
+ var import_BitString = require("@unicitylabs/state-transition-sdk/lib/util/BitString.js");
4262
+
4263
+ // token-engine/identity.ts
4264
+ var SHA256_IMPRINT_PREFIX = new Uint8Array([0, 0]);
4265
+
4266
+ // token-engine/errors.ts
4267
+ var SplitCheckpointLostError = class extends SphereError {
4268
+ constructor(message, cause) {
4269
+ super(message, "SPLIT_CHECKPOINT_LOST", cause);
4270
+ this.name = "SplitCheckpointLostError";
4271
+ }
4272
+ };
4273
+
4274
+ // token-engine/SphereTokenEngine.ts
4275
+ var CLEAN_REJECT_STATUSES = /* @__PURE__ */ new Set([
4276
+ import_CertificationResponse.CertificationStatus.STATE_ID_MISMATCH,
4277
+ import_CertificationResponse.CertificationStatus.SIGNATURE_VERIFICATION_FAILED,
4278
+ import_CertificationResponse.CertificationStatus.INVALID_SIGNATURE_FORMAT,
4279
+ import_CertificationResponse.CertificationStatus.INVALID_PUBLIC_KEY_FORMAT,
4280
+ import_CertificationResponse.CertificationStatus.INVALID_SOURCE_STATE_HASH_FORMAT,
4281
+ import_CertificationResponse.CertificationStatus.INVALID_TRANSACTION_HASH_FORMAT,
4282
+ import_CertificationResponse.CertificationStatus.UNSUPPORTED_ALGORITHM,
4283
+ import_CertificationResponse.CertificationStatus.INVALID_SHARD
4284
+ ]);
4285
+
4286
+ // impl/wallet-api-v2/checkpoints.ts
4287
+ var PROGRESS_SIGNATURE_PREFIX = "wallet-api.progress.v1";
4288
+ var utf8 = (text) => new TextEncoder().encode(text);
4289
+ function sha256Hex(bytes) {
4290
+ return Array.from(sha256(bytes), (b) => b.toString(16).padStart(2, "0")).join("");
4291
+ }
4292
+ function progressMessage(transferId, opIndex, envelope) {
4293
+ return `${PROGRESS_SIGNATURE_PREFIX}:${transferId}:${String(opIndex)}:${sha256Hex(utf8(envelope))}`;
4294
+ }
4295
+ var WalletApiSplitCheckpointStore = class {
4296
+ constructor(config) {
4297
+ this.config = config;
4298
+ }
4299
+ cacheKey(transferId, opIndex) {
4300
+ return `${STORE_KEYS.checkpointCache}:${transferId}:${String(opIndex)}`;
4301
+ }
4302
+ aad(transferId, opIndex) {
4303
+ return utf8(`${transferId}:${String(opIndex)}`);
4304
+ }
4305
+ async put(transferId, opIndex, bytes) {
4306
+ const { client, kv, fieldKey, signProgress } = this.config;
4307
+ const aad = this.aad(transferId, opIndex);
4308
+ const cacheKey = this.cacheKey(transferId, opIndex);
4309
+ let envelope = await kv.get(cacheKey);
4310
+ if (envelope === null) {
4311
+ envelope = encryptFieldBytes(fieldKey, bytes, aad);
4312
+ await kv.set(cacheKey, envelope);
4313
+ }
4314
+ const signature = await signProgress(progressMessage(transferId, opIndex, envelope));
4315
+ const record = await client.postProgress(transferId, opIndex, envelope, signature);
4316
+ return this.open(record.payload, aad);
4317
+ }
4318
+ async get(transferId, opIndex) {
4319
+ const records = await this.config.client.getProgress(transferId);
4320
+ const record = records.find((r) => r.opIndex === opIndex);
4321
+ if (record === void 0) return null;
4322
+ return this.open(record.payload, this.aad(transferId, opIndex));
4323
+ }
4324
+ open(envelope, aad) {
4325
+ try {
4326
+ return decryptFieldBytes(this.config.fieldKey, envelope, aad);
4327
+ } catch (err) {
4328
+ if (err instanceof SphereError && err.code === "DECRYPTION_ERROR") {
4329
+ throw new SplitCheckpointLostError(
4330
+ "split checkpoint record could not be decrypted (tampered or mis-served)",
4331
+ err
4332
+ );
4333
+ }
4334
+ throw err;
4335
+ }
4336
+ }
4337
+ };
4338
+ // Annotate the CommonJS export names for ESM import in node:
4339
+ 0 && (module.exports = {
4340
+ DEFAULT_SESSION_TIMING,
4341
+ JwtGenerationCell,
4342
+ WAKE_STREAMS,
4343
+ WalletApiDeliveryPort,
4344
+ WalletApiHttpError,
4345
+ WalletApiSession,
4346
+ WalletApiSplitCheckpointStore,
4347
+ WalletApiStoragePort,
4348
+ WalletApiV2Client,
4349
+ assertSecureBaseUrl,
4350
+ createWalletApiHttp,
4351
+ isWalletApiHttpError,
4352
+ refreshTokenKey
4353
+ });
4354
+ /*! Bundled license information:
4355
+
4356
+ @noble/curves/utils.js:
4357
+ @noble/curves/abstract/modular.js:
4358
+ @noble/curves/abstract/curve.js:
4359
+ @noble/curves/abstract/weierstrass.js:
4360
+ @noble/curves/secp256k1.js:
4361
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4362
+
4363
+ @noble/ciphers/utils.js:
4364
+ (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
4365
+ */
4366
+ //# sourceMappingURL=index.cjs.map