@opaquecash/stellar 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4989 @@
1
+ import { secp256k1 } from '@noble/curves/secp256k1';
2
+ import { keccak_256 } from '@noble/hashes/sha3';
3
+ import { hkdf } from '@noble/hashes/hkdf';
4
+ import { sha256 } from '@noble/hashes/sha2';
5
+ import { Keypair, StrKey, TransactionBuilder, Address, xdr, nativeToScVal, scValToNative, rpc, Horizon, Operation, Asset, BASE_FEE, Contract } from '@stellar/stellar-sdk';
6
+ import { buildPoseidon } from 'circomlibjs';
7
+
8
+ var __create = Object.create;
9
+ var __defProp = Object.defineProperty;
10
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __getProtoOf = Object.getPrototypeOf;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __commonJS = (cb, mod) => function __require() {
15
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26
+ // If the importer is in node compatibility mode or this is not an ESM
27
+ // file that has been converted to a CommonJS file using a Babel-
28
+ // compatible transform (i.e. "__esModule" has not been set), then set
29
+ // "default" to the CommonJS "module.exports" for node compatibility.
30
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
31
+ mod
32
+ ));
33
+
34
+ // node_modules/base64-js/index.js
35
+ var require_base64_js = __commonJS({
36
+ "node_modules/base64-js/index.js"(exports) {
37
+ exports.byteLength = byteLength;
38
+ exports.toByteArray = toByteArray;
39
+ exports.fromByteArray = fromByteArray;
40
+ var lookup = [];
41
+ var revLookup = [];
42
+ var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
43
+ var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
44
+ for (i = 0, len = code.length; i < len; ++i) {
45
+ lookup[i] = code[i];
46
+ revLookup[code.charCodeAt(i)] = i;
47
+ }
48
+ var i;
49
+ var len;
50
+ revLookup["-".charCodeAt(0)] = 62;
51
+ revLookup["_".charCodeAt(0)] = 63;
52
+ function getLens(b64) {
53
+ var len2 = b64.length;
54
+ if (len2 % 4 > 0) {
55
+ throw new Error("Invalid string. Length must be a multiple of 4");
56
+ }
57
+ var validLen = b64.indexOf("=");
58
+ if (validLen === -1) validLen = len2;
59
+ var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
60
+ return [validLen, placeHoldersLen];
61
+ }
62
+ function byteLength(b64) {
63
+ var lens = getLens(b64);
64
+ var validLen = lens[0];
65
+ var placeHoldersLen = lens[1];
66
+ return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
67
+ }
68
+ function _byteLength(b64, validLen, placeHoldersLen) {
69
+ return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
70
+ }
71
+ function toByteArray(b64) {
72
+ var tmp;
73
+ var lens = getLens(b64);
74
+ var validLen = lens[0];
75
+ var placeHoldersLen = lens[1];
76
+ var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
77
+ var curByte = 0;
78
+ var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
79
+ var i2;
80
+ for (i2 = 0; i2 < len2; i2 += 4) {
81
+ tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)];
82
+ arr[curByte++] = tmp >> 16 & 255;
83
+ arr[curByte++] = tmp >> 8 & 255;
84
+ arr[curByte++] = tmp & 255;
85
+ }
86
+ if (placeHoldersLen === 2) {
87
+ tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4;
88
+ arr[curByte++] = tmp & 255;
89
+ }
90
+ if (placeHoldersLen === 1) {
91
+ tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2;
92
+ arr[curByte++] = tmp >> 8 & 255;
93
+ arr[curByte++] = tmp & 255;
94
+ }
95
+ return arr;
96
+ }
97
+ function tripletToBase64(num) {
98
+ return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
99
+ }
100
+ function encodeChunk(uint8, start, end) {
101
+ var tmp;
102
+ var output = [];
103
+ for (var i2 = start; i2 < end; i2 += 3) {
104
+ tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255);
105
+ output.push(tripletToBase64(tmp));
106
+ }
107
+ return output.join("");
108
+ }
109
+ function fromByteArray(uint8) {
110
+ var tmp;
111
+ var len2 = uint8.length;
112
+ var extraBytes = len2 % 3;
113
+ var parts = [];
114
+ var maxChunkLength = 16383;
115
+ for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) {
116
+ parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength));
117
+ }
118
+ if (extraBytes === 1) {
119
+ tmp = uint8[len2 - 1];
120
+ parts.push(
121
+ lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="
122
+ );
123
+ } else if (extraBytes === 2) {
124
+ tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
125
+ parts.push(
126
+ lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="
127
+ );
128
+ }
129
+ return parts.join("");
130
+ }
131
+ }
132
+ });
133
+
134
+ // node_modules/ieee754/index.js
135
+ var require_ieee754 = __commonJS({
136
+ "node_modules/ieee754/index.js"(exports) {
137
+ exports.read = function(buffer, offset, isLE, mLen, nBytes) {
138
+ var e, m;
139
+ var eLen = nBytes * 8 - mLen - 1;
140
+ var eMax = (1 << eLen) - 1;
141
+ var eBias = eMax >> 1;
142
+ var nBits = -7;
143
+ var i = isLE ? nBytes - 1 : 0;
144
+ var d = isLE ? -1 : 1;
145
+ var s = buffer[offset + i];
146
+ i += d;
147
+ e = s & (1 << -nBits) - 1;
148
+ s >>= -nBits;
149
+ nBits += eLen;
150
+ for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {
151
+ }
152
+ m = e & (1 << -nBits) - 1;
153
+ e >>= -nBits;
154
+ nBits += mLen;
155
+ for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {
156
+ }
157
+ if (e === 0) {
158
+ e = 1 - eBias;
159
+ } else if (e === eMax) {
160
+ return m ? NaN : (s ? -1 : 1) * Infinity;
161
+ } else {
162
+ m = m + Math.pow(2, mLen);
163
+ e = e - eBias;
164
+ }
165
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
166
+ };
167
+ exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
168
+ var e, m, c;
169
+ var eLen = nBytes * 8 - mLen - 1;
170
+ var eMax = (1 << eLen) - 1;
171
+ var eBias = eMax >> 1;
172
+ var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
173
+ var i = isLE ? 0 : nBytes - 1;
174
+ var d = isLE ? 1 : -1;
175
+ var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
176
+ value = Math.abs(value);
177
+ if (isNaN(value) || value === Infinity) {
178
+ m = isNaN(value) ? 1 : 0;
179
+ e = eMax;
180
+ } else {
181
+ e = Math.floor(Math.log(value) / Math.LN2);
182
+ if (value * (c = Math.pow(2, -e)) < 1) {
183
+ e--;
184
+ c *= 2;
185
+ }
186
+ if (e + eBias >= 1) {
187
+ value += rt / c;
188
+ } else {
189
+ value += rt * Math.pow(2, 1 - eBias);
190
+ }
191
+ if (value * c >= 2) {
192
+ e++;
193
+ c /= 2;
194
+ }
195
+ if (e + eBias >= eMax) {
196
+ m = 0;
197
+ e = eMax;
198
+ } else if (e + eBias >= 1) {
199
+ m = (value * c - 1) * Math.pow(2, mLen);
200
+ e = e + eBias;
201
+ } else {
202
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
203
+ e = 0;
204
+ }
205
+ }
206
+ for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
207
+ }
208
+ e = e << mLen | m;
209
+ eLen += mLen;
210
+ for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
211
+ }
212
+ buffer[offset + i - d] |= s * 128;
213
+ };
214
+ }
215
+ });
216
+
217
+ // node_modules/buffer/index.js
218
+ var require_buffer = __commonJS({
219
+ "node_modules/buffer/index.js"(exports) {
220
+ var base64 = require_base64_js();
221
+ var ieee754 = require_ieee754();
222
+ var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
223
+ exports.Buffer = Buffer2;
224
+ exports.SlowBuffer = SlowBuffer;
225
+ exports.INSPECT_MAX_BYTES = 50;
226
+ var K_MAX_LENGTH = 2147483647;
227
+ exports.kMaxLength = K_MAX_LENGTH;
228
+ Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport();
229
+ if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
230
+ console.error(
231
+ "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."
232
+ );
233
+ }
234
+ function typedArraySupport() {
235
+ try {
236
+ const arr = new Uint8Array(1);
237
+ const proto = { foo: function() {
238
+ return 42;
239
+ } };
240
+ Object.setPrototypeOf(proto, Uint8Array.prototype);
241
+ Object.setPrototypeOf(arr, proto);
242
+ return arr.foo() === 42;
243
+ } catch (e) {
244
+ return false;
245
+ }
246
+ }
247
+ Object.defineProperty(Buffer2.prototype, "parent", {
248
+ enumerable: true,
249
+ get: function() {
250
+ if (!Buffer2.isBuffer(this)) return void 0;
251
+ return this.buffer;
252
+ }
253
+ });
254
+ Object.defineProperty(Buffer2.prototype, "offset", {
255
+ enumerable: true,
256
+ get: function() {
257
+ if (!Buffer2.isBuffer(this)) return void 0;
258
+ return this.byteOffset;
259
+ }
260
+ });
261
+ function createBuffer(length) {
262
+ if (length > K_MAX_LENGTH) {
263
+ throw new RangeError('The value "' + length + '" is invalid for option "size"');
264
+ }
265
+ const buf = new Uint8Array(length);
266
+ Object.setPrototypeOf(buf, Buffer2.prototype);
267
+ return buf;
268
+ }
269
+ function Buffer2(arg, encodingOrOffset, length) {
270
+ if (typeof arg === "number") {
271
+ if (typeof encodingOrOffset === "string") {
272
+ throw new TypeError(
273
+ 'The "string" argument must be of type string. Received type number'
274
+ );
275
+ }
276
+ return allocUnsafe(arg);
277
+ }
278
+ return from(arg, encodingOrOffset, length);
279
+ }
280
+ Buffer2.poolSize = 8192;
281
+ function from(value, encodingOrOffset, length) {
282
+ if (typeof value === "string") {
283
+ return fromString(value, encodingOrOffset);
284
+ }
285
+ if (ArrayBuffer.isView(value)) {
286
+ return fromArrayView(value);
287
+ }
288
+ if (value == null) {
289
+ throw new TypeError(
290
+ "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
291
+ );
292
+ }
293
+ if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
294
+ return fromArrayBuffer(value, encodingOrOffset, length);
295
+ }
296
+ if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
297
+ return fromArrayBuffer(value, encodingOrOffset, length);
298
+ }
299
+ if (typeof value === "number") {
300
+ throw new TypeError(
301
+ 'The "value" argument must not be of type number. Received type number'
302
+ );
303
+ }
304
+ const valueOf = value.valueOf && value.valueOf();
305
+ if (valueOf != null && valueOf !== value) {
306
+ return Buffer2.from(valueOf, encodingOrOffset, length);
307
+ }
308
+ const b = fromObject(value);
309
+ if (b) return b;
310
+ if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") {
311
+ return Buffer2.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
312
+ }
313
+ throw new TypeError(
314
+ "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
315
+ );
316
+ }
317
+ Buffer2.from = function(value, encodingOrOffset, length) {
318
+ return from(value, encodingOrOffset, length);
319
+ };
320
+ Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype);
321
+ Object.setPrototypeOf(Buffer2, Uint8Array);
322
+ function assertSize(size) {
323
+ if (typeof size !== "number") {
324
+ throw new TypeError('"size" argument must be of type number');
325
+ } else if (size < 0) {
326
+ throw new RangeError('The value "' + size + '" is invalid for option "size"');
327
+ }
328
+ }
329
+ function alloc(size, fill, encoding) {
330
+ assertSize(size);
331
+ if (size <= 0) {
332
+ return createBuffer(size);
333
+ }
334
+ if (fill !== void 0) {
335
+ return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
336
+ }
337
+ return createBuffer(size);
338
+ }
339
+ Buffer2.alloc = function(size, fill, encoding) {
340
+ return alloc(size, fill, encoding);
341
+ };
342
+ function allocUnsafe(size) {
343
+ assertSize(size);
344
+ return createBuffer(size < 0 ? 0 : checked(size) | 0);
345
+ }
346
+ Buffer2.allocUnsafe = function(size) {
347
+ return allocUnsafe(size);
348
+ };
349
+ Buffer2.allocUnsafeSlow = function(size) {
350
+ return allocUnsafe(size);
351
+ };
352
+ function fromString(string, encoding) {
353
+ if (typeof encoding !== "string" || encoding === "") {
354
+ encoding = "utf8";
355
+ }
356
+ if (!Buffer2.isEncoding(encoding)) {
357
+ throw new TypeError("Unknown encoding: " + encoding);
358
+ }
359
+ const length = byteLength(string, encoding) | 0;
360
+ let buf = createBuffer(length);
361
+ const actual = buf.write(string, encoding);
362
+ if (actual !== length) {
363
+ buf = buf.slice(0, actual);
364
+ }
365
+ return buf;
366
+ }
367
+ function fromArrayLike(array) {
368
+ const length = array.length < 0 ? 0 : checked(array.length) | 0;
369
+ const buf = createBuffer(length);
370
+ for (let i = 0; i < length; i += 1) {
371
+ buf[i] = array[i] & 255;
372
+ }
373
+ return buf;
374
+ }
375
+ function fromArrayView(arrayView) {
376
+ if (isInstance(arrayView, Uint8Array)) {
377
+ const copy = new Uint8Array(arrayView);
378
+ return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
379
+ }
380
+ return fromArrayLike(arrayView);
381
+ }
382
+ function fromArrayBuffer(array, byteOffset, length) {
383
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
384
+ throw new RangeError('"offset" is outside of buffer bounds');
385
+ }
386
+ if (array.byteLength < byteOffset + (length || 0)) {
387
+ throw new RangeError('"length" is outside of buffer bounds');
388
+ }
389
+ let buf;
390
+ if (byteOffset === void 0 && length === void 0) {
391
+ buf = new Uint8Array(array);
392
+ } else if (length === void 0) {
393
+ buf = new Uint8Array(array, byteOffset);
394
+ } else {
395
+ buf = new Uint8Array(array, byteOffset, length);
396
+ }
397
+ Object.setPrototypeOf(buf, Buffer2.prototype);
398
+ return buf;
399
+ }
400
+ function fromObject(obj) {
401
+ if (Buffer2.isBuffer(obj)) {
402
+ const len = checked(obj.length) | 0;
403
+ const buf = createBuffer(len);
404
+ if (buf.length === 0) {
405
+ return buf;
406
+ }
407
+ obj.copy(buf, 0, 0, len);
408
+ return buf;
409
+ }
410
+ if (obj.length !== void 0) {
411
+ if (typeof obj.length !== "number" || numberIsNaN(obj.length)) {
412
+ return createBuffer(0);
413
+ }
414
+ return fromArrayLike(obj);
415
+ }
416
+ if (obj.type === "Buffer" && Array.isArray(obj.data)) {
417
+ return fromArrayLike(obj.data);
418
+ }
419
+ }
420
+ function checked(length) {
421
+ if (length >= K_MAX_LENGTH) {
422
+ throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
423
+ }
424
+ return length | 0;
425
+ }
426
+ function SlowBuffer(length) {
427
+ if (+length != length) {
428
+ length = 0;
429
+ }
430
+ return Buffer2.alloc(+length);
431
+ }
432
+ Buffer2.isBuffer = function isBuffer(b) {
433
+ return b != null && b._isBuffer === true && b !== Buffer2.prototype;
434
+ };
435
+ Buffer2.compare = function compare(a, b) {
436
+ if (isInstance(a, Uint8Array)) a = Buffer2.from(a, a.offset, a.byteLength);
437
+ if (isInstance(b, Uint8Array)) b = Buffer2.from(b, b.offset, b.byteLength);
438
+ if (!Buffer2.isBuffer(a) || !Buffer2.isBuffer(b)) {
439
+ throw new TypeError(
440
+ 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
441
+ );
442
+ }
443
+ if (a === b) return 0;
444
+ let x = a.length;
445
+ let y = b.length;
446
+ for (let i = 0, len = Math.min(x, y); i < len; ++i) {
447
+ if (a[i] !== b[i]) {
448
+ x = a[i];
449
+ y = b[i];
450
+ break;
451
+ }
452
+ }
453
+ if (x < y) return -1;
454
+ if (y < x) return 1;
455
+ return 0;
456
+ };
457
+ Buffer2.isEncoding = function isEncoding(encoding) {
458
+ switch (String(encoding).toLowerCase()) {
459
+ case "hex":
460
+ case "utf8":
461
+ case "utf-8":
462
+ case "ascii":
463
+ case "latin1":
464
+ case "binary":
465
+ case "base64":
466
+ case "ucs2":
467
+ case "ucs-2":
468
+ case "utf16le":
469
+ case "utf-16le":
470
+ return true;
471
+ default:
472
+ return false;
473
+ }
474
+ };
475
+ Buffer2.concat = function concat(list, length) {
476
+ if (!Array.isArray(list)) {
477
+ throw new TypeError('"list" argument must be an Array of Buffers');
478
+ }
479
+ if (list.length === 0) {
480
+ return Buffer2.alloc(0);
481
+ }
482
+ let i;
483
+ if (length === void 0) {
484
+ length = 0;
485
+ for (i = 0; i < list.length; ++i) {
486
+ length += list[i].length;
487
+ }
488
+ }
489
+ const buffer = Buffer2.allocUnsafe(length);
490
+ let pos = 0;
491
+ for (i = 0; i < list.length; ++i) {
492
+ let buf = list[i];
493
+ if (isInstance(buf, Uint8Array)) {
494
+ if (pos + buf.length > buffer.length) {
495
+ if (!Buffer2.isBuffer(buf)) buf = Buffer2.from(buf);
496
+ buf.copy(buffer, pos);
497
+ } else {
498
+ Uint8Array.prototype.set.call(
499
+ buffer,
500
+ buf,
501
+ pos
502
+ );
503
+ }
504
+ } else if (!Buffer2.isBuffer(buf)) {
505
+ throw new TypeError('"list" argument must be an Array of Buffers');
506
+ } else {
507
+ buf.copy(buffer, pos);
508
+ }
509
+ pos += buf.length;
510
+ }
511
+ return buffer;
512
+ };
513
+ function byteLength(string, encoding) {
514
+ if (Buffer2.isBuffer(string)) {
515
+ return string.length;
516
+ }
517
+ if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
518
+ return string.byteLength;
519
+ }
520
+ if (typeof string !== "string") {
521
+ throw new TypeError(
522
+ 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string
523
+ );
524
+ }
525
+ const len = string.length;
526
+ const mustMatch = arguments.length > 2 && arguments[2] === true;
527
+ if (!mustMatch && len === 0) return 0;
528
+ let loweredCase = false;
529
+ for (; ; ) {
530
+ switch (encoding) {
531
+ case "ascii":
532
+ case "latin1":
533
+ case "binary":
534
+ return len;
535
+ case "utf8":
536
+ case "utf-8":
537
+ return utf8ToBytes(string).length;
538
+ case "ucs2":
539
+ case "ucs-2":
540
+ case "utf16le":
541
+ case "utf-16le":
542
+ return len * 2;
543
+ case "hex":
544
+ return len >>> 1;
545
+ case "base64":
546
+ return base64ToBytes3(string).length;
547
+ default:
548
+ if (loweredCase) {
549
+ return mustMatch ? -1 : utf8ToBytes(string).length;
550
+ }
551
+ encoding = ("" + encoding).toLowerCase();
552
+ loweredCase = true;
553
+ }
554
+ }
555
+ }
556
+ Buffer2.byteLength = byteLength;
557
+ function slowToString(encoding, start, end) {
558
+ let loweredCase = false;
559
+ if (start === void 0 || start < 0) {
560
+ start = 0;
561
+ }
562
+ if (start > this.length) {
563
+ return "";
564
+ }
565
+ if (end === void 0 || end > this.length) {
566
+ end = this.length;
567
+ }
568
+ if (end <= 0) {
569
+ return "";
570
+ }
571
+ end >>>= 0;
572
+ start >>>= 0;
573
+ if (end <= start) {
574
+ return "";
575
+ }
576
+ if (!encoding) encoding = "utf8";
577
+ while (true) {
578
+ switch (encoding) {
579
+ case "hex":
580
+ return hexSlice(this, start, end);
581
+ case "utf8":
582
+ case "utf-8":
583
+ return utf8Slice(this, start, end);
584
+ case "ascii":
585
+ return asciiSlice(this, start, end);
586
+ case "latin1":
587
+ case "binary":
588
+ return latin1Slice(this, start, end);
589
+ case "base64":
590
+ return base64Slice(this, start, end);
591
+ case "ucs2":
592
+ case "ucs-2":
593
+ case "utf16le":
594
+ case "utf-16le":
595
+ return utf16leSlice(this, start, end);
596
+ default:
597
+ if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
598
+ encoding = (encoding + "").toLowerCase();
599
+ loweredCase = true;
600
+ }
601
+ }
602
+ }
603
+ Buffer2.prototype._isBuffer = true;
604
+ function swap(b, n, m) {
605
+ const i = b[n];
606
+ b[n] = b[m];
607
+ b[m] = i;
608
+ }
609
+ Buffer2.prototype.swap16 = function swap16() {
610
+ const len = this.length;
611
+ if (len % 2 !== 0) {
612
+ throw new RangeError("Buffer size must be a multiple of 16-bits");
613
+ }
614
+ for (let i = 0; i < len; i += 2) {
615
+ swap(this, i, i + 1);
616
+ }
617
+ return this;
618
+ };
619
+ Buffer2.prototype.swap32 = function swap32() {
620
+ const len = this.length;
621
+ if (len % 4 !== 0) {
622
+ throw new RangeError("Buffer size must be a multiple of 32-bits");
623
+ }
624
+ for (let i = 0; i < len; i += 4) {
625
+ swap(this, i, i + 3);
626
+ swap(this, i + 1, i + 2);
627
+ }
628
+ return this;
629
+ };
630
+ Buffer2.prototype.swap64 = function swap64() {
631
+ const len = this.length;
632
+ if (len % 8 !== 0) {
633
+ throw new RangeError("Buffer size must be a multiple of 64-bits");
634
+ }
635
+ for (let i = 0; i < len; i += 8) {
636
+ swap(this, i, i + 7);
637
+ swap(this, i + 1, i + 6);
638
+ swap(this, i + 2, i + 5);
639
+ swap(this, i + 3, i + 4);
640
+ }
641
+ return this;
642
+ };
643
+ Buffer2.prototype.toString = function toString() {
644
+ const length = this.length;
645
+ if (length === 0) return "";
646
+ if (arguments.length === 0) return utf8Slice(this, 0, length);
647
+ return slowToString.apply(this, arguments);
648
+ };
649
+ Buffer2.prototype.toLocaleString = Buffer2.prototype.toString;
650
+ Buffer2.prototype.equals = function equals(b) {
651
+ if (!Buffer2.isBuffer(b)) throw new TypeError("Argument must be a Buffer");
652
+ if (this === b) return true;
653
+ return Buffer2.compare(this, b) === 0;
654
+ };
655
+ Buffer2.prototype.inspect = function inspect() {
656
+ let str = "";
657
+ const max = exports.INSPECT_MAX_BYTES;
658
+ str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim();
659
+ if (this.length > max) str += " ... ";
660
+ return "<Buffer " + str + ">";
661
+ };
662
+ if (customInspectSymbol) {
663
+ Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect;
664
+ }
665
+ Buffer2.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
666
+ if (isInstance(target, Uint8Array)) {
667
+ target = Buffer2.from(target, target.offset, target.byteLength);
668
+ }
669
+ if (!Buffer2.isBuffer(target)) {
670
+ throw new TypeError(
671
+ 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target
672
+ );
673
+ }
674
+ if (start === void 0) {
675
+ start = 0;
676
+ }
677
+ if (end === void 0) {
678
+ end = target ? target.length : 0;
679
+ }
680
+ if (thisStart === void 0) {
681
+ thisStart = 0;
682
+ }
683
+ if (thisEnd === void 0) {
684
+ thisEnd = this.length;
685
+ }
686
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
687
+ throw new RangeError("out of range index");
688
+ }
689
+ if (thisStart >= thisEnd && start >= end) {
690
+ return 0;
691
+ }
692
+ if (thisStart >= thisEnd) {
693
+ return -1;
694
+ }
695
+ if (start >= end) {
696
+ return 1;
697
+ }
698
+ start >>>= 0;
699
+ end >>>= 0;
700
+ thisStart >>>= 0;
701
+ thisEnd >>>= 0;
702
+ if (this === target) return 0;
703
+ let x = thisEnd - thisStart;
704
+ let y = end - start;
705
+ const len = Math.min(x, y);
706
+ const thisCopy = this.slice(thisStart, thisEnd);
707
+ const targetCopy = target.slice(start, end);
708
+ for (let i = 0; i < len; ++i) {
709
+ if (thisCopy[i] !== targetCopy[i]) {
710
+ x = thisCopy[i];
711
+ y = targetCopy[i];
712
+ break;
713
+ }
714
+ }
715
+ if (x < y) return -1;
716
+ if (y < x) return 1;
717
+ return 0;
718
+ };
719
+ function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
720
+ if (buffer.length === 0) return -1;
721
+ if (typeof byteOffset === "string") {
722
+ encoding = byteOffset;
723
+ byteOffset = 0;
724
+ } else if (byteOffset > 2147483647) {
725
+ byteOffset = 2147483647;
726
+ } else if (byteOffset < -2147483648) {
727
+ byteOffset = -2147483648;
728
+ }
729
+ byteOffset = +byteOffset;
730
+ if (numberIsNaN(byteOffset)) {
731
+ byteOffset = dir ? 0 : buffer.length - 1;
732
+ }
733
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
734
+ if (byteOffset >= buffer.length) {
735
+ if (dir) return -1;
736
+ else byteOffset = buffer.length - 1;
737
+ } else if (byteOffset < 0) {
738
+ if (dir) byteOffset = 0;
739
+ else return -1;
740
+ }
741
+ if (typeof val === "string") {
742
+ val = Buffer2.from(val, encoding);
743
+ }
744
+ if (Buffer2.isBuffer(val)) {
745
+ if (val.length === 0) {
746
+ return -1;
747
+ }
748
+ return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
749
+ } else if (typeof val === "number") {
750
+ val = val & 255;
751
+ if (typeof Uint8Array.prototype.indexOf === "function") {
752
+ if (dir) {
753
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
754
+ } else {
755
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
756
+ }
757
+ }
758
+ return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
759
+ }
760
+ throw new TypeError("val must be string, number or Buffer");
761
+ }
762
+ function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
763
+ let indexSize = 1;
764
+ let arrLength = arr.length;
765
+ let valLength = val.length;
766
+ if (encoding !== void 0) {
767
+ encoding = String(encoding).toLowerCase();
768
+ if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
769
+ if (arr.length < 2 || val.length < 2) {
770
+ return -1;
771
+ }
772
+ indexSize = 2;
773
+ arrLength /= 2;
774
+ valLength /= 2;
775
+ byteOffset /= 2;
776
+ }
777
+ }
778
+ function read(buf, i2) {
779
+ if (indexSize === 1) {
780
+ return buf[i2];
781
+ } else {
782
+ return buf.readUInt16BE(i2 * indexSize);
783
+ }
784
+ }
785
+ let i;
786
+ if (dir) {
787
+ let foundIndex = -1;
788
+ for (i = byteOffset; i < arrLength; i++) {
789
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
790
+ if (foundIndex === -1) foundIndex = i;
791
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
792
+ } else {
793
+ if (foundIndex !== -1) i -= i - foundIndex;
794
+ foundIndex = -1;
795
+ }
796
+ }
797
+ } else {
798
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
799
+ for (i = byteOffset; i >= 0; i--) {
800
+ let found = true;
801
+ for (let j = 0; j < valLength; j++) {
802
+ if (read(arr, i + j) !== read(val, j)) {
803
+ found = false;
804
+ break;
805
+ }
806
+ }
807
+ if (found) return i;
808
+ }
809
+ }
810
+ return -1;
811
+ }
812
+ Buffer2.prototype.includes = function includes(val, byteOffset, encoding) {
813
+ return this.indexOf(val, byteOffset, encoding) !== -1;
814
+ };
815
+ Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
816
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
817
+ };
818
+ Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
819
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
820
+ };
821
+ function hexWrite(buf, string, offset, length) {
822
+ offset = Number(offset) || 0;
823
+ const remaining = buf.length - offset;
824
+ if (!length) {
825
+ length = remaining;
826
+ } else {
827
+ length = Number(length);
828
+ if (length > remaining) {
829
+ length = remaining;
830
+ }
831
+ }
832
+ const strLen = string.length;
833
+ if (length > strLen / 2) {
834
+ length = strLen / 2;
835
+ }
836
+ let i;
837
+ for (i = 0; i < length; ++i) {
838
+ const parsed = parseInt(string.substr(i * 2, 2), 16);
839
+ if (numberIsNaN(parsed)) return i;
840
+ buf[offset + i] = parsed;
841
+ }
842
+ return i;
843
+ }
844
+ function utf8Write(buf, string, offset, length) {
845
+ return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
846
+ }
847
+ function asciiWrite(buf, string, offset, length) {
848
+ return blitBuffer(asciiToBytes(string), buf, offset, length);
849
+ }
850
+ function base64Write(buf, string, offset, length) {
851
+ return blitBuffer(base64ToBytes3(string), buf, offset, length);
852
+ }
853
+ function ucs2Write(buf, string, offset, length) {
854
+ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
855
+ }
856
+ Buffer2.prototype.write = function write(string, offset, length, encoding) {
857
+ if (offset === void 0) {
858
+ encoding = "utf8";
859
+ length = this.length;
860
+ offset = 0;
861
+ } else if (length === void 0 && typeof offset === "string") {
862
+ encoding = offset;
863
+ length = this.length;
864
+ offset = 0;
865
+ } else if (isFinite(offset)) {
866
+ offset = offset >>> 0;
867
+ if (isFinite(length)) {
868
+ length = length >>> 0;
869
+ if (encoding === void 0) encoding = "utf8";
870
+ } else {
871
+ encoding = length;
872
+ length = void 0;
873
+ }
874
+ } else {
875
+ throw new Error(
876
+ "Buffer.write(string, encoding, offset[, length]) is no longer supported"
877
+ );
878
+ }
879
+ const remaining = this.length - offset;
880
+ if (length === void 0 || length > remaining) length = remaining;
881
+ if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
882
+ throw new RangeError("Attempt to write outside buffer bounds");
883
+ }
884
+ if (!encoding) encoding = "utf8";
885
+ let loweredCase = false;
886
+ for (; ; ) {
887
+ switch (encoding) {
888
+ case "hex":
889
+ return hexWrite(this, string, offset, length);
890
+ case "utf8":
891
+ case "utf-8":
892
+ return utf8Write(this, string, offset, length);
893
+ case "ascii":
894
+ case "latin1":
895
+ case "binary":
896
+ return asciiWrite(this, string, offset, length);
897
+ case "base64":
898
+ return base64Write(this, string, offset, length);
899
+ case "ucs2":
900
+ case "ucs-2":
901
+ case "utf16le":
902
+ case "utf-16le":
903
+ return ucs2Write(this, string, offset, length);
904
+ default:
905
+ if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
906
+ encoding = ("" + encoding).toLowerCase();
907
+ loweredCase = true;
908
+ }
909
+ }
910
+ };
911
+ Buffer2.prototype.toJSON = function toJSON() {
912
+ return {
913
+ type: "Buffer",
914
+ data: Array.prototype.slice.call(this._arr || this, 0)
915
+ };
916
+ };
917
+ function base64Slice(buf, start, end) {
918
+ if (start === 0 && end === buf.length) {
919
+ return base64.fromByteArray(buf);
920
+ } else {
921
+ return base64.fromByteArray(buf.slice(start, end));
922
+ }
923
+ }
924
+ function utf8Slice(buf, start, end) {
925
+ end = Math.min(buf.length, end);
926
+ const res = [];
927
+ let i = start;
928
+ while (i < end) {
929
+ const firstByte = buf[i];
930
+ let codePoint = null;
931
+ let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
932
+ if (i + bytesPerSequence <= end) {
933
+ let secondByte, thirdByte, fourthByte, tempCodePoint;
934
+ switch (bytesPerSequence) {
935
+ case 1:
936
+ if (firstByte < 128) {
937
+ codePoint = firstByte;
938
+ }
939
+ break;
940
+ case 2:
941
+ secondByte = buf[i + 1];
942
+ if ((secondByte & 192) === 128) {
943
+ tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
944
+ if (tempCodePoint > 127) {
945
+ codePoint = tempCodePoint;
946
+ }
947
+ }
948
+ break;
949
+ case 3:
950
+ secondByte = buf[i + 1];
951
+ thirdByte = buf[i + 2];
952
+ if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
953
+ tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
954
+ if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
955
+ codePoint = tempCodePoint;
956
+ }
957
+ }
958
+ break;
959
+ case 4:
960
+ secondByte = buf[i + 1];
961
+ thirdByte = buf[i + 2];
962
+ fourthByte = buf[i + 3];
963
+ if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
964
+ tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
965
+ if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
966
+ codePoint = tempCodePoint;
967
+ }
968
+ }
969
+ }
970
+ }
971
+ if (codePoint === null) {
972
+ codePoint = 65533;
973
+ bytesPerSequence = 1;
974
+ } else if (codePoint > 65535) {
975
+ codePoint -= 65536;
976
+ res.push(codePoint >>> 10 & 1023 | 55296);
977
+ codePoint = 56320 | codePoint & 1023;
978
+ }
979
+ res.push(codePoint);
980
+ i += bytesPerSequence;
981
+ }
982
+ return decodeCodePointsArray(res);
983
+ }
984
+ var MAX_ARGUMENTS_LENGTH = 4096;
985
+ function decodeCodePointsArray(codePoints) {
986
+ const len = codePoints.length;
987
+ if (len <= MAX_ARGUMENTS_LENGTH) {
988
+ return String.fromCharCode.apply(String, codePoints);
989
+ }
990
+ let res = "";
991
+ let i = 0;
992
+ while (i < len) {
993
+ res += String.fromCharCode.apply(
994
+ String,
995
+ codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
996
+ );
997
+ }
998
+ return res;
999
+ }
1000
+ function asciiSlice(buf, start, end) {
1001
+ let ret = "";
1002
+ end = Math.min(buf.length, end);
1003
+ for (let i = start; i < end; ++i) {
1004
+ ret += String.fromCharCode(buf[i] & 127);
1005
+ }
1006
+ return ret;
1007
+ }
1008
+ function latin1Slice(buf, start, end) {
1009
+ let ret = "";
1010
+ end = Math.min(buf.length, end);
1011
+ for (let i = start; i < end; ++i) {
1012
+ ret += String.fromCharCode(buf[i]);
1013
+ }
1014
+ return ret;
1015
+ }
1016
+ function hexSlice(buf, start, end) {
1017
+ const len = buf.length;
1018
+ if (!start || start < 0) start = 0;
1019
+ if (!end || end < 0 || end > len) end = len;
1020
+ let out = "";
1021
+ for (let i = start; i < end; ++i) {
1022
+ out += hexSliceLookupTable[buf[i]];
1023
+ }
1024
+ return out;
1025
+ }
1026
+ function utf16leSlice(buf, start, end) {
1027
+ const bytes = buf.slice(start, end);
1028
+ let res = "";
1029
+ for (let i = 0; i < bytes.length - 1; i += 2) {
1030
+ res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
1031
+ }
1032
+ return res;
1033
+ }
1034
+ Buffer2.prototype.slice = function slice(start, end) {
1035
+ const len = this.length;
1036
+ start = ~~start;
1037
+ end = end === void 0 ? len : ~~end;
1038
+ if (start < 0) {
1039
+ start += len;
1040
+ if (start < 0) start = 0;
1041
+ } else if (start > len) {
1042
+ start = len;
1043
+ }
1044
+ if (end < 0) {
1045
+ end += len;
1046
+ if (end < 0) end = 0;
1047
+ } else if (end > len) {
1048
+ end = len;
1049
+ }
1050
+ if (end < start) end = start;
1051
+ const newBuf = this.subarray(start, end);
1052
+ Object.setPrototypeOf(newBuf, Buffer2.prototype);
1053
+ return newBuf;
1054
+ };
1055
+ function checkOffset(offset, ext, length) {
1056
+ if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint");
1057
+ if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length");
1058
+ }
1059
+ Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) {
1060
+ offset = offset >>> 0;
1061
+ byteLength2 = byteLength2 >>> 0;
1062
+ if (!noAssert) checkOffset(offset, byteLength2, this.length);
1063
+ let val = this[offset];
1064
+ let mul = 1;
1065
+ let i = 0;
1066
+ while (++i < byteLength2 && (mul *= 256)) {
1067
+ val += this[offset + i] * mul;
1068
+ }
1069
+ return val;
1070
+ };
1071
+ Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) {
1072
+ offset = offset >>> 0;
1073
+ byteLength2 = byteLength2 >>> 0;
1074
+ if (!noAssert) {
1075
+ checkOffset(offset, byteLength2, this.length);
1076
+ }
1077
+ let val = this[offset + --byteLength2];
1078
+ let mul = 1;
1079
+ while (byteLength2 > 0 && (mul *= 256)) {
1080
+ val += this[offset + --byteLength2] * mul;
1081
+ }
1082
+ return val;
1083
+ };
1084
+ Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) {
1085
+ offset = offset >>> 0;
1086
+ if (!noAssert) checkOffset(offset, 1, this.length);
1087
+ return this[offset];
1088
+ };
1089
+ Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
1090
+ offset = offset >>> 0;
1091
+ if (!noAssert) checkOffset(offset, 2, this.length);
1092
+ return this[offset] | this[offset + 1] << 8;
1093
+ };
1094
+ Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
1095
+ offset = offset >>> 0;
1096
+ if (!noAssert) checkOffset(offset, 2, this.length);
1097
+ return this[offset] << 8 | this[offset + 1];
1098
+ };
1099
+ Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
1100
+ offset = offset >>> 0;
1101
+ if (!noAssert) checkOffset(offset, 4, this.length);
1102
+ return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
1103
+ };
1104
+ Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
1105
+ offset = offset >>> 0;
1106
+ if (!noAssert) checkOffset(offset, 4, this.length);
1107
+ return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
1108
+ };
1109
+ Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) {
1110
+ offset = offset >>> 0;
1111
+ validateNumber(offset, "offset");
1112
+ const first = this[offset];
1113
+ const last = this[offset + 7];
1114
+ if (first === void 0 || last === void 0) {
1115
+ boundsError(offset, this.length - 8);
1116
+ }
1117
+ const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24;
1118
+ const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24;
1119
+ return BigInt(lo) + (BigInt(hi) << BigInt(32));
1120
+ });
1121
+ Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) {
1122
+ offset = offset >>> 0;
1123
+ validateNumber(offset, "offset");
1124
+ const first = this[offset];
1125
+ const last = this[offset + 7];
1126
+ if (first === void 0 || last === void 0) {
1127
+ boundsError(offset, this.length - 8);
1128
+ }
1129
+ const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
1130
+ const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last;
1131
+ return (BigInt(hi) << BigInt(32)) + BigInt(lo);
1132
+ });
1133
+ Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) {
1134
+ offset = offset >>> 0;
1135
+ byteLength2 = byteLength2 >>> 0;
1136
+ if (!noAssert) checkOffset(offset, byteLength2, this.length);
1137
+ let val = this[offset];
1138
+ let mul = 1;
1139
+ let i = 0;
1140
+ while (++i < byteLength2 && (mul *= 256)) {
1141
+ val += this[offset + i] * mul;
1142
+ }
1143
+ mul *= 128;
1144
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
1145
+ return val;
1146
+ };
1147
+ Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) {
1148
+ offset = offset >>> 0;
1149
+ byteLength2 = byteLength2 >>> 0;
1150
+ if (!noAssert) checkOffset(offset, byteLength2, this.length);
1151
+ let i = byteLength2;
1152
+ let mul = 1;
1153
+ let val = this[offset + --i];
1154
+ while (i > 0 && (mul *= 256)) {
1155
+ val += this[offset + --i] * mul;
1156
+ }
1157
+ mul *= 128;
1158
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
1159
+ return val;
1160
+ };
1161
+ Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) {
1162
+ offset = offset >>> 0;
1163
+ if (!noAssert) checkOffset(offset, 1, this.length);
1164
+ if (!(this[offset] & 128)) return this[offset];
1165
+ return (255 - this[offset] + 1) * -1;
1166
+ };
1167
+ Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
1168
+ offset = offset >>> 0;
1169
+ if (!noAssert) checkOffset(offset, 2, this.length);
1170
+ const val = this[offset] | this[offset + 1] << 8;
1171
+ return val & 32768 ? val | 4294901760 : val;
1172
+ };
1173
+ Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
1174
+ offset = offset >>> 0;
1175
+ if (!noAssert) checkOffset(offset, 2, this.length);
1176
+ const val = this[offset + 1] | this[offset] << 8;
1177
+ return val & 32768 ? val | 4294901760 : val;
1178
+ };
1179
+ Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
1180
+ offset = offset >>> 0;
1181
+ if (!noAssert) checkOffset(offset, 4, this.length);
1182
+ return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
1183
+ };
1184
+ Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
1185
+ offset = offset >>> 0;
1186
+ if (!noAssert) checkOffset(offset, 4, this.length);
1187
+ return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
1188
+ };
1189
+ Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) {
1190
+ offset = offset >>> 0;
1191
+ validateNumber(offset, "offset");
1192
+ const first = this[offset];
1193
+ const last = this[offset + 7];
1194
+ if (first === void 0 || last === void 0) {
1195
+ boundsError(offset, this.length - 8);
1196
+ }
1197
+ const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24);
1198
+ return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24);
1199
+ });
1200
+ Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) {
1201
+ offset = offset >>> 0;
1202
+ validateNumber(offset, "offset");
1203
+ const first = this[offset];
1204
+ const last = this[offset + 7];
1205
+ if (first === void 0 || last === void 0) {
1206
+ boundsError(offset, this.length - 8);
1207
+ }
1208
+ const val = (first << 24) + // Overflow
1209
+ this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
1210
+ return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last);
1211
+ });
1212
+ Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
1213
+ offset = offset >>> 0;
1214
+ if (!noAssert) checkOffset(offset, 4, this.length);
1215
+ return ieee754.read(this, offset, true, 23, 4);
1216
+ };
1217
+ Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
1218
+ offset = offset >>> 0;
1219
+ if (!noAssert) checkOffset(offset, 4, this.length);
1220
+ return ieee754.read(this, offset, false, 23, 4);
1221
+ };
1222
+ Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
1223
+ offset = offset >>> 0;
1224
+ if (!noAssert) checkOffset(offset, 8, this.length);
1225
+ return ieee754.read(this, offset, true, 52, 8);
1226
+ };
1227
+ Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
1228
+ offset = offset >>> 0;
1229
+ if (!noAssert) checkOffset(offset, 8, this.length);
1230
+ return ieee754.read(this, offset, false, 52, 8);
1231
+ };
1232
+ function checkInt(buf, value, offset, ext, max, min) {
1233
+ if (!Buffer2.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
1234
+ if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
1235
+ if (offset + ext > buf.length) throw new RangeError("Index out of range");
1236
+ }
1237
+ Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) {
1238
+ value = +value;
1239
+ offset = offset >>> 0;
1240
+ byteLength2 = byteLength2 >>> 0;
1241
+ if (!noAssert) {
1242
+ const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
1243
+ checkInt(this, value, offset, byteLength2, maxBytes, 0);
1244
+ }
1245
+ let mul = 1;
1246
+ let i = 0;
1247
+ this[offset] = value & 255;
1248
+ while (++i < byteLength2 && (mul *= 256)) {
1249
+ this[offset + i] = value / mul & 255;
1250
+ }
1251
+ return offset + byteLength2;
1252
+ };
1253
+ Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) {
1254
+ value = +value;
1255
+ offset = offset >>> 0;
1256
+ byteLength2 = byteLength2 >>> 0;
1257
+ if (!noAssert) {
1258
+ const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
1259
+ checkInt(this, value, offset, byteLength2, maxBytes, 0);
1260
+ }
1261
+ let i = byteLength2 - 1;
1262
+ let mul = 1;
1263
+ this[offset + i] = value & 255;
1264
+ while (--i >= 0 && (mul *= 256)) {
1265
+ this[offset + i] = value / mul & 255;
1266
+ }
1267
+ return offset + byteLength2;
1268
+ };
1269
+ Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
1270
+ value = +value;
1271
+ offset = offset >>> 0;
1272
+ if (!noAssert) checkInt(this, value, offset, 1, 255, 0);
1273
+ this[offset] = value & 255;
1274
+ return offset + 1;
1275
+ };
1276
+ Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
1277
+ value = +value;
1278
+ offset = offset >>> 0;
1279
+ if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
1280
+ this[offset] = value & 255;
1281
+ this[offset + 1] = value >>> 8;
1282
+ return offset + 2;
1283
+ };
1284
+ Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
1285
+ value = +value;
1286
+ offset = offset >>> 0;
1287
+ if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
1288
+ this[offset] = value >>> 8;
1289
+ this[offset + 1] = value & 255;
1290
+ return offset + 2;
1291
+ };
1292
+ Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
1293
+ value = +value;
1294
+ offset = offset >>> 0;
1295
+ if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
1296
+ this[offset + 3] = value >>> 24;
1297
+ this[offset + 2] = value >>> 16;
1298
+ this[offset + 1] = value >>> 8;
1299
+ this[offset] = value & 255;
1300
+ return offset + 4;
1301
+ };
1302
+ Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
1303
+ value = +value;
1304
+ offset = offset >>> 0;
1305
+ if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
1306
+ this[offset] = value >>> 24;
1307
+ this[offset + 1] = value >>> 16;
1308
+ this[offset + 2] = value >>> 8;
1309
+ this[offset + 3] = value & 255;
1310
+ return offset + 4;
1311
+ };
1312
+ function wrtBigUInt64LE(buf, value, offset, min, max) {
1313
+ checkIntBI(value, min, max, buf, offset, 7);
1314
+ let lo = Number(value & BigInt(4294967295));
1315
+ buf[offset++] = lo;
1316
+ lo = lo >> 8;
1317
+ buf[offset++] = lo;
1318
+ lo = lo >> 8;
1319
+ buf[offset++] = lo;
1320
+ lo = lo >> 8;
1321
+ buf[offset++] = lo;
1322
+ let hi = Number(value >> BigInt(32) & BigInt(4294967295));
1323
+ buf[offset++] = hi;
1324
+ hi = hi >> 8;
1325
+ buf[offset++] = hi;
1326
+ hi = hi >> 8;
1327
+ buf[offset++] = hi;
1328
+ hi = hi >> 8;
1329
+ buf[offset++] = hi;
1330
+ return offset;
1331
+ }
1332
+ function wrtBigUInt64BE(buf, value, offset, min, max) {
1333
+ checkIntBI(value, min, max, buf, offset, 7);
1334
+ let lo = Number(value & BigInt(4294967295));
1335
+ buf[offset + 7] = lo;
1336
+ lo = lo >> 8;
1337
+ buf[offset + 6] = lo;
1338
+ lo = lo >> 8;
1339
+ buf[offset + 5] = lo;
1340
+ lo = lo >> 8;
1341
+ buf[offset + 4] = lo;
1342
+ let hi = Number(value >> BigInt(32) & BigInt(4294967295));
1343
+ buf[offset + 3] = hi;
1344
+ hi = hi >> 8;
1345
+ buf[offset + 2] = hi;
1346
+ hi = hi >> 8;
1347
+ buf[offset + 1] = hi;
1348
+ hi = hi >> 8;
1349
+ buf[offset] = hi;
1350
+ return offset + 8;
1351
+ }
1352
+ Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) {
1353
+ return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
1354
+ });
1355
+ Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) {
1356
+ return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
1357
+ });
1358
+ Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) {
1359
+ value = +value;
1360
+ offset = offset >>> 0;
1361
+ if (!noAssert) {
1362
+ const limit = Math.pow(2, 8 * byteLength2 - 1);
1363
+ checkInt(this, value, offset, byteLength2, limit - 1, -limit);
1364
+ }
1365
+ let i = 0;
1366
+ let mul = 1;
1367
+ let sub = 0;
1368
+ this[offset] = value & 255;
1369
+ while (++i < byteLength2 && (mul *= 256)) {
1370
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1371
+ sub = 1;
1372
+ }
1373
+ this[offset + i] = (value / mul >> 0) - sub & 255;
1374
+ }
1375
+ return offset + byteLength2;
1376
+ };
1377
+ Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) {
1378
+ value = +value;
1379
+ offset = offset >>> 0;
1380
+ if (!noAssert) {
1381
+ const limit = Math.pow(2, 8 * byteLength2 - 1);
1382
+ checkInt(this, value, offset, byteLength2, limit - 1, -limit);
1383
+ }
1384
+ let i = byteLength2 - 1;
1385
+ let mul = 1;
1386
+ let sub = 0;
1387
+ this[offset + i] = value & 255;
1388
+ while (--i >= 0 && (mul *= 256)) {
1389
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1390
+ sub = 1;
1391
+ }
1392
+ this[offset + i] = (value / mul >> 0) - sub & 255;
1393
+ }
1394
+ return offset + byteLength2;
1395
+ };
1396
+ Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
1397
+ value = +value;
1398
+ offset = offset >>> 0;
1399
+ if (!noAssert) checkInt(this, value, offset, 1, 127, -128);
1400
+ if (value < 0) value = 255 + value + 1;
1401
+ this[offset] = value & 255;
1402
+ return offset + 1;
1403
+ };
1404
+ Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
1405
+ value = +value;
1406
+ offset = offset >>> 0;
1407
+ if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
1408
+ this[offset] = value & 255;
1409
+ this[offset + 1] = value >>> 8;
1410
+ return offset + 2;
1411
+ };
1412
+ Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
1413
+ value = +value;
1414
+ offset = offset >>> 0;
1415
+ if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
1416
+ this[offset] = value >>> 8;
1417
+ this[offset + 1] = value & 255;
1418
+ return offset + 2;
1419
+ };
1420
+ Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
1421
+ value = +value;
1422
+ offset = offset >>> 0;
1423
+ if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
1424
+ this[offset] = value & 255;
1425
+ this[offset + 1] = value >>> 8;
1426
+ this[offset + 2] = value >>> 16;
1427
+ this[offset + 3] = value >>> 24;
1428
+ return offset + 4;
1429
+ };
1430
+ Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
1431
+ value = +value;
1432
+ offset = offset >>> 0;
1433
+ if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
1434
+ if (value < 0) value = 4294967295 + value + 1;
1435
+ this[offset] = value >>> 24;
1436
+ this[offset + 1] = value >>> 16;
1437
+ this[offset + 2] = value >>> 8;
1438
+ this[offset + 3] = value & 255;
1439
+ return offset + 4;
1440
+ };
1441
+ Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) {
1442
+ return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
1443
+ });
1444
+ Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) {
1445
+ return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
1446
+ });
1447
+ function checkIEEE754(buf, value, offset, ext, max, min) {
1448
+ if (offset + ext > buf.length) throw new RangeError("Index out of range");
1449
+ if (offset < 0) throw new RangeError("Index out of range");
1450
+ }
1451
+ function writeFloat(buf, value, offset, littleEndian, noAssert) {
1452
+ value = +value;
1453
+ offset = offset >>> 0;
1454
+ if (!noAssert) {
1455
+ checkIEEE754(buf, value, offset, 4);
1456
+ }
1457
+ ieee754.write(buf, value, offset, littleEndian, 23, 4);
1458
+ return offset + 4;
1459
+ }
1460
+ Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
1461
+ return writeFloat(this, value, offset, true, noAssert);
1462
+ };
1463
+ Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
1464
+ return writeFloat(this, value, offset, false, noAssert);
1465
+ };
1466
+ function writeDouble(buf, value, offset, littleEndian, noAssert) {
1467
+ value = +value;
1468
+ offset = offset >>> 0;
1469
+ if (!noAssert) {
1470
+ checkIEEE754(buf, value, offset, 8);
1471
+ }
1472
+ ieee754.write(buf, value, offset, littleEndian, 52, 8);
1473
+ return offset + 8;
1474
+ }
1475
+ Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
1476
+ return writeDouble(this, value, offset, true, noAssert);
1477
+ };
1478
+ Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
1479
+ return writeDouble(this, value, offset, false, noAssert);
1480
+ };
1481
+ Buffer2.prototype.copy = function copy(target, targetStart, start, end) {
1482
+ if (!Buffer2.isBuffer(target)) throw new TypeError("argument should be a Buffer");
1483
+ if (!start) start = 0;
1484
+ if (!end && end !== 0) end = this.length;
1485
+ if (targetStart >= target.length) targetStart = target.length;
1486
+ if (!targetStart) targetStart = 0;
1487
+ if (end > 0 && end < start) end = start;
1488
+ if (end === start) return 0;
1489
+ if (target.length === 0 || this.length === 0) return 0;
1490
+ if (targetStart < 0) {
1491
+ throw new RangeError("targetStart out of bounds");
1492
+ }
1493
+ if (start < 0 || start >= this.length) throw new RangeError("Index out of range");
1494
+ if (end < 0) throw new RangeError("sourceEnd out of bounds");
1495
+ if (end > this.length) end = this.length;
1496
+ if (target.length - targetStart < end - start) {
1497
+ end = target.length - targetStart + start;
1498
+ }
1499
+ const len = end - start;
1500
+ if (this === target && typeof Uint8Array.prototype.copyWithin === "function") {
1501
+ this.copyWithin(targetStart, start, end);
1502
+ } else {
1503
+ Uint8Array.prototype.set.call(
1504
+ target,
1505
+ this.subarray(start, end),
1506
+ targetStart
1507
+ );
1508
+ }
1509
+ return len;
1510
+ };
1511
+ Buffer2.prototype.fill = function fill(val, start, end, encoding) {
1512
+ if (typeof val === "string") {
1513
+ if (typeof start === "string") {
1514
+ encoding = start;
1515
+ start = 0;
1516
+ end = this.length;
1517
+ } else if (typeof end === "string") {
1518
+ encoding = end;
1519
+ end = this.length;
1520
+ }
1521
+ if (encoding !== void 0 && typeof encoding !== "string") {
1522
+ throw new TypeError("encoding must be a string");
1523
+ }
1524
+ if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) {
1525
+ throw new TypeError("Unknown encoding: " + encoding);
1526
+ }
1527
+ if (val.length === 1) {
1528
+ const code = val.charCodeAt(0);
1529
+ if (encoding === "utf8" && code < 128 || encoding === "latin1") {
1530
+ val = code;
1531
+ }
1532
+ }
1533
+ } else if (typeof val === "number") {
1534
+ val = val & 255;
1535
+ } else if (typeof val === "boolean") {
1536
+ val = Number(val);
1537
+ }
1538
+ if (start < 0 || this.length < start || this.length < end) {
1539
+ throw new RangeError("Out of range index");
1540
+ }
1541
+ if (end <= start) {
1542
+ return this;
1543
+ }
1544
+ start = start >>> 0;
1545
+ end = end === void 0 ? this.length : end >>> 0;
1546
+ if (!val) val = 0;
1547
+ let i;
1548
+ if (typeof val === "number") {
1549
+ for (i = start; i < end; ++i) {
1550
+ this[i] = val;
1551
+ }
1552
+ } else {
1553
+ const bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding);
1554
+ const len = bytes.length;
1555
+ if (len === 0) {
1556
+ throw new TypeError('The value "' + val + '" is invalid for argument "value"');
1557
+ }
1558
+ for (i = 0; i < end - start; ++i) {
1559
+ this[i + start] = bytes[i % len];
1560
+ }
1561
+ }
1562
+ return this;
1563
+ };
1564
+ var errors = {};
1565
+ function E(sym, getMessage, Base) {
1566
+ errors[sym] = class NodeError extends Base {
1567
+ constructor() {
1568
+ super();
1569
+ Object.defineProperty(this, "message", {
1570
+ value: getMessage.apply(this, arguments),
1571
+ writable: true,
1572
+ configurable: true
1573
+ });
1574
+ this.name = `${this.name} [${sym}]`;
1575
+ this.stack;
1576
+ delete this.name;
1577
+ }
1578
+ get code() {
1579
+ return sym;
1580
+ }
1581
+ set code(value) {
1582
+ Object.defineProperty(this, "code", {
1583
+ configurable: true,
1584
+ enumerable: true,
1585
+ value,
1586
+ writable: true
1587
+ });
1588
+ }
1589
+ toString() {
1590
+ return `${this.name} [${sym}]: ${this.message}`;
1591
+ }
1592
+ };
1593
+ }
1594
+ E(
1595
+ "ERR_BUFFER_OUT_OF_BOUNDS",
1596
+ function(name) {
1597
+ if (name) {
1598
+ return `${name} is outside of buffer bounds`;
1599
+ }
1600
+ return "Attempt to access memory outside buffer bounds";
1601
+ },
1602
+ RangeError
1603
+ );
1604
+ E(
1605
+ "ERR_INVALID_ARG_TYPE",
1606
+ function(name, actual) {
1607
+ return `The "${name}" argument must be of type number. Received type ${typeof actual}`;
1608
+ },
1609
+ TypeError
1610
+ );
1611
+ E(
1612
+ "ERR_OUT_OF_RANGE",
1613
+ function(str, range, input) {
1614
+ let msg = `The value of "${str}" is out of range.`;
1615
+ let received = input;
1616
+ if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
1617
+ received = addNumericalSeparator(String(input));
1618
+ } else if (typeof input === "bigint") {
1619
+ received = String(input);
1620
+ if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
1621
+ received = addNumericalSeparator(received);
1622
+ }
1623
+ received += "n";
1624
+ }
1625
+ msg += ` It must be ${range}. Received ${received}`;
1626
+ return msg;
1627
+ },
1628
+ RangeError
1629
+ );
1630
+ function addNumericalSeparator(val) {
1631
+ let res = "";
1632
+ let i = val.length;
1633
+ const start = val[0] === "-" ? 1 : 0;
1634
+ for (; i >= start + 4; i -= 3) {
1635
+ res = `_${val.slice(i - 3, i)}${res}`;
1636
+ }
1637
+ return `${val.slice(0, i)}${res}`;
1638
+ }
1639
+ function checkBounds(buf, offset, byteLength2) {
1640
+ validateNumber(offset, "offset");
1641
+ if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) {
1642
+ boundsError(offset, buf.length - (byteLength2 + 1));
1643
+ }
1644
+ }
1645
+ function checkIntBI(value, min, max, buf, offset, byteLength2) {
1646
+ if (value > max || value < min) {
1647
+ const n = typeof min === "bigint" ? "n" : "";
1648
+ let range;
1649
+ {
1650
+ if (min === 0 || min === BigInt(0)) {
1651
+ range = `>= 0${n} and < 2${n} ** ${(byteLength2 + 1) * 8}${n}`;
1652
+ } else {
1653
+ range = `>= -(2${n} ** ${(byteLength2 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n}`;
1654
+ }
1655
+ }
1656
+ throw new errors.ERR_OUT_OF_RANGE("value", range, value);
1657
+ }
1658
+ checkBounds(buf, offset, byteLength2);
1659
+ }
1660
+ function validateNumber(value, name) {
1661
+ if (typeof value !== "number") {
1662
+ throw new errors.ERR_INVALID_ARG_TYPE(name, "number", value);
1663
+ }
1664
+ }
1665
+ function boundsError(value, length, type) {
1666
+ if (Math.floor(value) !== value) {
1667
+ validateNumber(value, type);
1668
+ throw new errors.ERR_OUT_OF_RANGE("offset", "an integer", value);
1669
+ }
1670
+ if (length < 0) {
1671
+ throw new errors.ERR_BUFFER_OUT_OF_BOUNDS();
1672
+ }
1673
+ throw new errors.ERR_OUT_OF_RANGE(
1674
+ "offset",
1675
+ `>= ${0} and <= ${length}`,
1676
+ value
1677
+ );
1678
+ }
1679
+ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
1680
+ function base64clean(str) {
1681
+ str = str.split("=")[0];
1682
+ str = str.trim().replace(INVALID_BASE64_RE, "");
1683
+ if (str.length < 2) return "";
1684
+ while (str.length % 4 !== 0) {
1685
+ str = str + "=";
1686
+ }
1687
+ return str;
1688
+ }
1689
+ function utf8ToBytes(string, units) {
1690
+ units = units || Infinity;
1691
+ let codePoint;
1692
+ const length = string.length;
1693
+ let leadSurrogate = null;
1694
+ const bytes = [];
1695
+ for (let i = 0; i < length; ++i) {
1696
+ codePoint = string.charCodeAt(i);
1697
+ if (codePoint > 55295 && codePoint < 57344) {
1698
+ if (!leadSurrogate) {
1699
+ if (codePoint > 56319) {
1700
+ if ((units -= 3) > -1) bytes.push(239, 191, 189);
1701
+ continue;
1702
+ } else if (i + 1 === length) {
1703
+ if ((units -= 3) > -1) bytes.push(239, 191, 189);
1704
+ continue;
1705
+ }
1706
+ leadSurrogate = codePoint;
1707
+ continue;
1708
+ }
1709
+ if (codePoint < 56320) {
1710
+ if ((units -= 3) > -1) bytes.push(239, 191, 189);
1711
+ leadSurrogate = codePoint;
1712
+ continue;
1713
+ }
1714
+ codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
1715
+ } else if (leadSurrogate) {
1716
+ if ((units -= 3) > -1) bytes.push(239, 191, 189);
1717
+ }
1718
+ leadSurrogate = null;
1719
+ if (codePoint < 128) {
1720
+ if ((units -= 1) < 0) break;
1721
+ bytes.push(codePoint);
1722
+ } else if (codePoint < 2048) {
1723
+ if ((units -= 2) < 0) break;
1724
+ bytes.push(
1725
+ codePoint >> 6 | 192,
1726
+ codePoint & 63 | 128
1727
+ );
1728
+ } else if (codePoint < 65536) {
1729
+ if ((units -= 3) < 0) break;
1730
+ bytes.push(
1731
+ codePoint >> 12 | 224,
1732
+ codePoint >> 6 & 63 | 128,
1733
+ codePoint & 63 | 128
1734
+ );
1735
+ } else if (codePoint < 1114112) {
1736
+ if ((units -= 4) < 0) break;
1737
+ bytes.push(
1738
+ codePoint >> 18 | 240,
1739
+ codePoint >> 12 & 63 | 128,
1740
+ codePoint >> 6 & 63 | 128,
1741
+ codePoint & 63 | 128
1742
+ );
1743
+ } else {
1744
+ throw new Error("Invalid code point");
1745
+ }
1746
+ }
1747
+ return bytes;
1748
+ }
1749
+ function asciiToBytes(str) {
1750
+ const byteArray = [];
1751
+ for (let i = 0; i < str.length; ++i) {
1752
+ byteArray.push(str.charCodeAt(i) & 255);
1753
+ }
1754
+ return byteArray;
1755
+ }
1756
+ function utf16leToBytes(str, units) {
1757
+ let c, hi, lo;
1758
+ const byteArray = [];
1759
+ for (let i = 0; i < str.length; ++i) {
1760
+ if ((units -= 2) < 0) break;
1761
+ c = str.charCodeAt(i);
1762
+ hi = c >> 8;
1763
+ lo = c % 256;
1764
+ byteArray.push(lo);
1765
+ byteArray.push(hi);
1766
+ }
1767
+ return byteArray;
1768
+ }
1769
+ function base64ToBytes3(str) {
1770
+ return base64.toByteArray(base64clean(str));
1771
+ }
1772
+ function blitBuffer(src, dst, offset, length) {
1773
+ let i;
1774
+ for (i = 0; i < length; ++i) {
1775
+ if (i + offset >= dst.length || i >= src.length) break;
1776
+ dst[i + offset] = src[i];
1777
+ }
1778
+ return i;
1779
+ }
1780
+ function isInstance(obj, type) {
1781
+ return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
1782
+ }
1783
+ function numberIsNaN(obj) {
1784
+ return obj !== obj;
1785
+ }
1786
+ var hexSliceLookupTable = (function() {
1787
+ const alphabet = "0123456789abcdef";
1788
+ const table = new Array(256);
1789
+ for (let i = 0; i < 16; ++i) {
1790
+ const i16 = i * 16;
1791
+ for (let j = 0; j < 16; ++j) {
1792
+ table[i16 + j] = alphabet[i] + alphabet[j];
1793
+ }
1794
+ }
1795
+ return table;
1796
+ })();
1797
+ function defineBigIntMethod(fn) {
1798
+ return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn;
1799
+ }
1800
+ function BufferBigIntNotDefined() {
1801
+ throw new Error("BigInt not supported");
1802
+ }
1803
+ }
1804
+ });
1805
+
1806
+ // src/crypto/bytes.ts
1807
+ function hexToBytes(hex) {
1808
+ const h = hex.startsWith("0x") ? hex.slice(2) : hex;
1809
+ if (h.length % 2) throw new Error("Invalid hex length");
1810
+ const out = new Uint8Array(h.length / 2);
1811
+ for (let i = 0; i < out.length; i++) {
1812
+ out[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16);
1813
+ }
1814
+ return out;
1815
+ }
1816
+ function bytesToHex(b) {
1817
+ return Array.from(b).map((x) => x.toString(16).padStart(2, "0")).join("");
1818
+ }
1819
+ function bytesToBigInt(b) {
1820
+ let x = 0n;
1821
+ for (let i = 0; i < b.length; i++) x = x << 8n | BigInt(b[i]);
1822
+ return x;
1823
+ }
1824
+ function bigIntToBytes32(value) {
1825
+ const out = new Uint8Array(32);
1826
+ let x = value;
1827
+ for (let i = 31; i >= 0; i--) {
1828
+ out[i] = Number(x & 0xffn);
1829
+ x >>= 8n;
1830
+ }
1831
+ return out;
1832
+ }
1833
+ function toHex32(v) {
1834
+ return "0x" + v.toString(16).padStart(64, "0");
1835
+ }
1836
+ function concatBytes(...arrays) {
1837
+ const total = arrays.reduce((n, a) => n + a.length, 0);
1838
+ const out = new Uint8Array(total);
1839
+ let off = 0;
1840
+ for (const a of arrays) {
1841
+ out.set(a, off);
1842
+ off += a.length;
1843
+ }
1844
+ return out;
1845
+ }
1846
+
1847
+ // src/crypto/amount.ts
1848
+ var MAX_DECIMALS = 7;
1849
+ function parseXlmToStroops(xlmString) {
1850
+ const trimmed = xlmString.trim();
1851
+ if (!trimmed) {
1852
+ throw new Error("XLM amount cannot be empty");
1853
+ }
1854
+ if (!/^-?\d+\.?\d*$/.test(trimmed)) {
1855
+ throw new Error(`Invalid XLM amount: ${trimmed}`);
1856
+ }
1857
+ const isNegative = trimmed.startsWith("-");
1858
+ const absolute = isNegative ? trimmed.slice(1) : trimmed;
1859
+ const parts = absolute.split(".");
1860
+ const integerPart = parts[0] || "0";
1861
+ const decimalPart = parts[1] || "";
1862
+ if (decimalPart.length > MAX_DECIMALS) {
1863
+ throw new Error(
1864
+ `XLM amount has too many decimal places (max ${MAX_DECIMALS}): ${trimmed}`
1865
+ );
1866
+ }
1867
+ const paddedDecimal = decimalPart.padEnd(MAX_DECIMALS, "0");
1868
+ const stroops = BigInt(integerPart + paddedDecimal);
1869
+ return isNegative ? -stroops : stroops;
1870
+ }
1871
+ function parseHorizonBalanceToStroops(balanceString) {
1872
+ if (!balanceString || balanceString.trim() === "") return 0n;
1873
+ try {
1874
+ return parseXlmToStroops(balanceString);
1875
+ } catch {
1876
+ return 0n;
1877
+ }
1878
+ }
1879
+ function formatStroopsToXlm(stroops) {
1880
+ const isNegative = stroops < 0n;
1881
+ const absolute = isNegative ? -stroops : stroops;
1882
+ const stroopsString = absolute.toString().padStart(MAX_DECIMALS + 1, "0");
1883
+ const integerPart = stroopsString.slice(0, -MAX_DECIMALS) || "0";
1884
+ const decimalPart = stroopsString.slice(-MAX_DECIMALS);
1885
+ const trimmedDecimal = decimalPart.replace(/0+$/, "");
1886
+ if (trimmedDecimal === "") {
1887
+ return isNegative ? `-${integerPart}` : integerPart;
1888
+ }
1889
+ return isNegative ? `-${integerPart}.${trimmedDecimal}` : `${integerPart}.${trimmedDecimal}`;
1890
+ }
1891
+ var formatXlm = formatStroopsToXlm;
1892
+ var CURVE = secp256k1;
1893
+ var DOMAIN = "opaque-cash-v1";
1894
+ var PROTOCOL_VERSION = "1";
1895
+ function buildDomainSeparatedMessage(opts) {
1896
+ return [
1897
+ `--- Opaque Protocol Key Derivation ---`,
1898
+ `App: Opaque Stellar`,
1899
+ `Origin: ${opts.origin}`,
1900
+ `Network: ${opts.networkPassphrase}`,
1901
+ `Wallet: ${opts.walletPublicKey}`,
1902
+ `Version: ${PROTOCOL_VERSION}`,
1903
+ `Purpose: ${opts.purpose}`,
1904
+ ``,
1905
+ `Warning: Signing this message authorizes key derivation for the Opaque protocol.`,
1906
+ `This is not a transaction and does not move funds.`,
1907
+ `Do not sign this message on untrusted sites or applications.`
1908
+ ].join("\n");
1909
+ }
1910
+ var LEGACY_SETUP_MESSAGE = "Sign this message to derive your Opaque Cash stealth keys on Stellar. This is not a transaction and does not move funds.";
1911
+ function deriveKeysFromSignature(signatureHex) {
1912
+ const sigBytes = typeof signatureHex === "string" ? signatureHex.startsWith("0x") ? signatureHex.slice(2) : signatureHex : signatureHex;
1913
+ const sig = typeof sigBytes === "string" ? hexToBytes(sigBytes) : sigBytes;
1914
+ const okm = hkdf(sha256, sig, void 0, DOMAIN, 64);
1915
+ return { viewingKey: okm.slice(0, 32), spendingKey: okm.slice(32, 64) };
1916
+ }
1917
+ function keysToStealthMetaAddress(viewingKey, spendingKey) {
1918
+ const V = CURVE.getPublicKey(viewingKey, true);
1919
+ const S = CURVE.getPublicKey(spendingKey, true);
1920
+ const metaAddress = new Uint8Array(V.length + S.length);
1921
+ metaAddress.set(V, 0);
1922
+ metaAddress.set(S, V.length);
1923
+ return { V, S, metaAddress };
1924
+ }
1925
+ function stealthMetaAddressToHex(metaAddress) {
1926
+ return "0x" + bytesToHex(metaAddress);
1927
+ }
1928
+ function parseStealthMetaAddress(metaHex) {
1929
+ const raw = typeof metaHex === "string" && metaHex.startsWith("0x") ? metaHex.slice(2) : metaHex;
1930
+ const bytes = hexToBytes(raw);
1931
+ if (bytes.length < 66) {
1932
+ throw new Error("Invalid stealth meta-address: expected 66 bytes");
1933
+ }
1934
+ return { viewPubKey: bytes.slice(0, 33), spendPubKey: bytes.slice(33, 66) };
1935
+ }
1936
+ function sharedSecretFromScalarAndPoint(privScalar, pointBytes) {
1937
+ const P = CURVE.ProjectivePoint.fromHex(pointBytes);
1938
+ const scalar = bytesToBigInt(privScalar) % CURVE.CURVE.n;
1939
+ if (scalar === 0n) throw new Error("Invalid scalar");
1940
+ return P.multiply(scalar).toRawBytes(true);
1941
+ }
1942
+ function hashSharedSecret(sharedSecret) {
1943
+ const sH = keccak_256(sharedSecret);
1944
+ return { sH, viewTag: sH[0] };
1945
+ }
1946
+ function stealthPointAndAddress(spendPubKey, sH) {
1947
+ const n = CURVE.CURVE.n;
1948
+ const sHMod = bytesToBigInt(sH) % n;
1949
+ if (sHMod === 0n) throw new Error("Invalid scalar from hash");
1950
+ const S_h = CURVE.ProjectivePoint.BASE.multiply(sHMod);
1951
+ const P_spend = CURVE.ProjectivePoint.fromHex(spendPubKey);
1952
+ const P_stealth = P_spend.add(S_h);
1953
+ const uncompressed = P_stealth.toRawBytes(false);
1954
+ const hash = keccak_256(uncompressed.slice(1));
1955
+ const addr = "0x" + bytesToHex(hash.slice(12));
1956
+ return { stealthAddress: addr, stealthPubKeyUncompressed: uncompressed };
1957
+ }
1958
+ function computeStealthAddressAndViewTag(recipientMetaAddressHex) {
1959
+ const { viewPubKey, spendPubKey } = parseStealthMetaAddress(
1960
+ recipientMetaAddressHex
1961
+ );
1962
+ const ephemeralPriv = CURVE.utils.randomPrivateKey();
1963
+ const ephemeralPubKey = CURVE.getPublicKey(ephemeralPriv, true);
1964
+ const shared = sharedSecretFromScalarAndPoint(ephemeralPriv, viewPubKey);
1965
+ const { sH, viewTag } = hashSharedSecret(shared);
1966
+ const { stealthAddress, stealthPubKeyUncompressed } = stealthPointAndAddress(
1967
+ spendPubKey,
1968
+ sH
1969
+ );
1970
+ const stealthStellarAddress = deriveStealthStellarAddress(
1971
+ stealthPubKeyUncompressed
1972
+ );
1973
+ return {
1974
+ ephemeralPriv,
1975
+ ephemeralPubKey,
1976
+ stealthAddress,
1977
+ stealthStellarAddress,
1978
+ viewTag,
1979
+ metadata: new Uint8Array([viewTag])
1980
+ };
1981
+ }
1982
+ function buildGhostAnnouncementPayload(recipientMetaAddressHex, ephemeralPrivKeyHex) {
1983
+ const { viewPubKey, spendPubKey } = parseStealthMetaAddress(
1984
+ recipientMetaAddressHex
1985
+ );
1986
+ const h = ephemeralPrivKeyHex.startsWith("0x") ? ephemeralPrivKeyHex.slice(2) : ephemeralPrivKeyHex;
1987
+ const ephemeralPriv = hexToBytes(h);
1988
+ if (ephemeralPriv.length !== 32) {
1989
+ throw new Error("Ephemeral private key must be 32 bytes.");
1990
+ }
1991
+ const ephemeralPubKey = CURVE.getPublicKey(ephemeralPriv, true);
1992
+ const shared = sharedSecretFromScalarAndPoint(ephemeralPriv, viewPubKey);
1993
+ const { sH, viewTag } = hashSharedSecret(shared);
1994
+ const { stealthAddress } = stealthPointAndAddress(spendPubKey, sH);
1995
+ return {
1996
+ stealthAddress,
1997
+ ephemeralPubKey,
1998
+ metadata: new Uint8Array([viewTag]),
1999
+ viewTag
2000
+ };
2001
+ }
2002
+ function recipientSharedSecretHash(viewingKey, ephemeralPubKey) {
2003
+ const shared = sharedSecretFromScalarAndPoint(viewingKey, ephemeralPubKey);
2004
+ return hashSharedSecret(shared);
2005
+ }
2006
+ function checkViewTagMatch(opts) {
2007
+ return recipientSharedSecretHash(opts.viewingKey, opts.ephemeralPubKey).viewTag === opts.viewTag;
2008
+ }
2009
+ function reconstructStealthPrivateKey(opts) {
2010
+ const n = CURVE.CURVE.n;
2011
+ const { sH } = recipientSharedSecretHash(opts.viewingKey, opts.ephemeralPubKey);
2012
+ const sHMod = bytesToBigInt(sH) % n;
2013
+ const spend = bytesToBigInt(opts.spendingKey) % n;
2014
+ const stealth = (spend + sHMod) % n;
2015
+ if (stealth === 0n) throw new Error("Reconstructed stealth key is zero");
2016
+ return bigIntToBytes32(stealth);
2017
+ }
2018
+ var ANNOUNCER_SALT = "opaque-announcer-v1";
2019
+ function deriveAnnouncerEphemeralKey(metaAddressHex) {
2020
+ const raw = typeof metaAddressHex === "string" && metaAddressHex.startsWith("0x") ? metaAddressHex.slice(2) : metaAddressHex;
2021
+ const seed = new TextEncoder().encode(raw + ANNOUNCER_SALT);
2022
+ const okm = hkdf(sha256, seed, void 0, "opaque-announcer-ephemeral", 32);
2023
+ const n = CURVE.CURVE.n;
2024
+ let scalar = bytesToBigInt(okm) % n;
2025
+ if (scalar === 0n) scalar = 1n;
2026
+ return bigIntToBytes32(scalar);
2027
+ }
2028
+ function deriveStealthStellarKeypair(stealthPubKeyUncompressed) {
2029
+ const domain = new TextEncoder().encode("opaque-stellar-stealth-v1");
2030
+ const input = new Uint8Array(domain.length + stealthPubKeyUncompressed.length);
2031
+ input.set(domain, 0);
2032
+ input.set(stealthPubKeyUncompressed, domain.length);
2033
+ const seed = sha256(input);
2034
+ return Keypair.fromRawEd25519Seed(Buffer.from(seed.slice(0, 32)));
2035
+ }
2036
+ function deriveStealthStellarAddress(stealthPubKeyUncompressed) {
2037
+ return deriveStealthStellarKeypair(stealthPubKeyUncompressed).publicKey();
2038
+ }
2039
+ function stealthIdFromPrivateKey(stealthPrivKey) {
2040
+ const uncompressed = CURVE.getPublicKey(stealthPrivKey, false);
2041
+ const hash = keccak_256(uncompressed.slice(1));
2042
+ return "0x" + bytesToHex(hash.slice(12));
2043
+ }
2044
+ function deriveStealthStellarAddressFromStealthPrivKey(stealthPrivKey) {
2045
+ return deriveStealthStellarAddress(CURVE.getPublicKey(stealthPrivKey, false));
2046
+ }
2047
+ function deriveStealthStellarKeypairFromStealthPrivKey(stealthPrivKey) {
2048
+ return deriveStealthStellarKeypair(CURVE.getPublicKey(stealthPrivKey, false));
2049
+ }
2050
+
2051
+ // src/crypto/scan.ts
2052
+ function scanAnnouncements(opts) {
2053
+ const matches = [];
2054
+ for (const announcement of opts.announcements) {
2055
+ if (!checkViewTagMatch({
2056
+ viewingKey: opts.viewingKey,
2057
+ ephemeralPubKey: announcement.ephemeralPubKey,
2058
+ viewTag: announcement.viewTag
2059
+ })) {
2060
+ continue;
2061
+ }
2062
+ const stealthPrivKey = reconstructStealthPrivateKey({
2063
+ viewingKey: opts.viewingKey,
2064
+ spendingKey: opts.spendingKey,
2065
+ ephemeralPubKey: announcement.ephemeralPubKey
2066
+ });
2067
+ if (stealthIdFromPrivateKey(stealthPrivKey).toLowerCase() !== announcement.stealthAddress.toLowerCase()) {
2068
+ continue;
2069
+ }
2070
+ matches.push({
2071
+ announcement,
2072
+ stealthPrivKey,
2073
+ stealthStellarAddress: deriveStealthStellarAddressFromStealthPrivKey(stealthPrivKey)
2074
+ });
2075
+ }
2076
+ return matches;
2077
+ }
2078
+ var POOL_TREE_DEPTH = 20;
2079
+ var BN254_R = 21888242871839275222246405745257275088548364400416034343698204186575808495617n;
2080
+ var _poseidon = null;
2081
+ async function getPoseidon() {
2082
+ if (!_poseidon) {
2083
+ if (typeof globalThis !== "undefined" && !("Buffer" in globalThis)) {
2084
+ const bufferPkg = await Promise.resolve().then(() => __toESM(require_buffer()));
2085
+ globalThis.Buffer = bufferPkg.Buffer;
2086
+ }
2087
+ _poseidon = await buildPoseidon();
2088
+ }
2089
+ return _poseidon;
2090
+ }
2091
+ function hashFields(poseidon, inputs) {
2092
+ return poseidon.F.toObject(poseidon(inputs));
2093
+ }
2094
+ function randomFieldElement() {
2095
+ const bytes = new Uint8Array(31);
2096
+ crypto.getRandomValues(bytes);
2097
+ let v = 0n;
2098
+ for (const b of bytes) v = (v << 8n) + BigInt(b);
2099
+ return (v % BN254_R).toString();
2100
+ }
2101
+ async function deriveDeposit(opts) {
2102
+ const poseidon = await getPoseidon();
2103
+ const h = (xs) => hashFields(poseidon, xs);
2104
+ const label = h([BigInt(opts.scope), BigInt(opts.leafIndex)]);
2105
+ const precommitment = h([opts.nullifier, opts.secret]);
2106
+ const commitment = h([opts.value, label, precommitment]);
2107
+ const nullifierHash = h([opts.nullifier]);
2108
+ return { label, precommitment, commitment, nullifierHash };
2109
+ }
2110
+ function newNoteSecrets() {
2111
+ return { nullifier: randomFieldElement(), secret: randomFieldElement() };
2112
+ }
2113
+ function unspentTotal(notes) {
2114
+ return notes.filter((n) => !n.spent).reduce((sum, n) => sum + BigInt(n.value), 0n);
2115
+ }
2116
+ var MAX_FIELDS = 16;
2117
+ var MAX_FIELD_NAME_LEN = 32;
2118
+ var MAX_STRING_VALUE_LEN = 128;
2119
+ var MAX_ATTESTATION_DATA_LEN = 512;
2120
+ var FIELD_TYPE_IDS = {
2121
+ bool: 0,
2122
+ u8: 1,
2123
+ u16: 2,
2124
+ u32: 3,
2125
+ u64: 4,
2126
+ string: 5,
2127
+ pubkey: 6
2128
+ };
2129
+ var SchemaParseError = class extends Error {
2130
+ constructor(message) {
2131
+ super(message);
2132
+ this.name = "SchemaParseError";
2133
+ }
2134
+ };
2135
+ var AttestationDataError = class extends Error {
2136
+ constructor(message) {
2137
+ super(message);
2138
+ this.name = "AttestationDataError";
2139
+ }
2140
+ };
2141
+ function isValidFieldName(name) {
2142
+ if (!name || name.length > MAX_FIELD_NAME_LEN) return false;
2143
+ return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name);
2144
+ }
2145
+ function parseFieldDefinitions(fieldDefs) {
2146
+ const trimmed = fieldDefs.trim();
2147
+ if (!trimmed) throw new SchemaParseError("Field definitions cannot be empty");
2148
+ const fields = [];
2149
+ for (const segment of trimmed.split(",")) {
2150
+ const seg = segment.trim();
2151
+ if (!seg) throw new SchemaParseError("Malformed field segment");
2152
+ const spaceIdx = seg.indexOf(" ");
2153
+ if (spaceIdx === -1) {
2154
+ throw new SchemaParseError(
2155
+ 'Expected "type name" format (legacy "name:type" is not supported)'
2156
+ );
2157
+ }
2158
+ const type = seg.slice(0, spaceIdx).trim();
2159
+ const name = seg.slice(spaceIdx + 1).trim();
2160
+ if (name.includes(" ") || !Object.hasOwn(FIELD_TYPE_IDS, type)) {
2161
+ throw new SchemaParseError(`Invalid field type: ${type}`);
2162
+ }
2163
+ if (!isValidFieldName(name)) {
2164
+ throw new SchemaParseError(`Invalid field name: ${name}`);
2165
+ }
2166
+ if (fields.some((f) => f.name === name)) {
2167
+ throw new SchemaParseError(`Duplicate field name: ${name}`);
2168
+ }
2169
+ fields.push({ id: String(fields.length), name, type });
2170
+ if (fields.length > MAX_FIELDS) throw new SchemaParseError("Too many fields");
2171
+ }
2172
+ const canonical = fieldDefsToCanonicalString(fields);
2173
+ if (canonical.length > 256) {
2174
+ throw new SchemaParseError("Field definitions too long");
2175
+ }
2176
+ return fields;
2177
+ }
2178
+ function fieldDefsToCanonicalString(fields) {
2179
+ return fields.filter((f) => f.name.trim()).map((f) => `${f.type} ${f.name.trim()}`).join(",");
2180
+ }
2181
+ function encodeCanonicalFieldDefs(fields) {
2182
+ const parts = [fields.length];
2183
+ for (const f of fields) {
2184
+ const nameBytes = new TextEncoder().encode(f.name);
2185
+ parts.push(FIELD_TYPE_IDS[f.type], nameBytes.length, ...nameBytes);
2186
+ }
2187
+ return new Uint8Array(parts);
2188
+ }
2189
+ function addressToAuthorityBytes(address) {
2190
+ return Uint8Array.from(StrKey.decodeEd25519PublicKey(address));
2191
+ }
2192
+ async function computeSchemaIdFromBytes(authorityBytes, name, fieldDefinitions, version = 1) {
2193
+ const fields = parseFieldDefinitions(fieldDefinitions);
2194
+ const canonical = encodeCanonicalFieldDefs(fields);
2195
+ const encoder = new TextEncoder();
2196
+ const nameBytes = encoder.encode(name);
2197
+ const versionBytes = new Uint8Array(4);
2198
+ new DataView(versionBytes.buffer).setUint32(0, version, false);
2199
+ const combined = new Uint8Array(
2200
+ authorityBytes.length + nameBytes.length + versionBytes.length + canonical.length
2201
+ );
2202
+ let off = 0;
2203
+ combined.set(authorityBytes, off);
2204
+ off += authorityBytes.length;
2205
+ combined.set(nameBytes, off);
2206
+ off += nameBytes.length;
2207
+ combined.set(versionBytes, off);
2208
+ off += versionBytes.length;
2209
+ combined.set(canonical, off);
2210
+ const hashBuffer = await crypto.subtle.digest("SHA-256", combined);
2211
+ return new Uint8Array(hashBuffer);
2212
+ }
2213
+ async function computeSchemaId(authority, name, fieldDefinitions, version = 1) {
2214
+ return computeSchemaIdFromBytes(
2215
+ addressToAuthorityBytes(authority),
2216
+ name,
2217
+ fieldDefinitions,
2218
+ version
2219
+ );
2220
+ }
2221
+ function parseBool(value) {
2222
+ const v = value.trim();
2223
+ if (v === "true" || v === "1") return true;
2224
+ if (v === "false" || v === "0" || v === "") return false;
2225
+ throw new AttestationDataError(`Invalid bool: ${value}`);
2226
+ }
2227
+ function parseUint(value, max) {
2228
+ const v = value.trim();
2229
+ if (!v) return 0n;
2230
+ if (!/^\d+$/.test(v)) throw new AttestationDataError(`Invalid integer: ${value}`);
2231
+ const n = BigInt(v);
2232
+ if (n < 0n || n > max) {
2233
+ throw new AttestationDataError(`Integer out of range: ${value}`);
2234
+ }
2235
+ return n;
2236
+ }
2237
+ function parsePubkeyHex(value) {
2238
+ const hex = value.trim().replace(/^0x/i, "");
2239
+ if (hex.length !== 64) throw new AttestationDataError("Invalid pubkey hex");
2240
+ const out = new Uint8Array(32);
2241
+ for (let i = 0; i < 32; i++) {
2242
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
2243
+ }
2244
+ return out;
2245
+ }
2246
+ function encodeAttestationData(fieldValues, fieldDefs) {
2247
+ const parts = [];
2248
+ for (const field of fieldDefs) {
2249
+ const value = fieldValues[field.name] ?? "";
2250
+ switch (field.type) {
2251
+ case "bool":
2252
+ parts.push(new Uint8Array([parseBool(value) ? 1 : 0]));
2253
+ break;
2254
+ case "u8":
2255
+ parts.push(new Uint8Array([Number(parseUint(value, 255n))]));
2256
+ break;
2257
+ case "u16": {
2258
+ const buf = new Uint8Array(2);
2259
+ new DataView(buf.buffer).setUint16(0, Number(parseUint(value, 65535n)), false);
2260
+ parts.push(buf);
2261
+ break;
2262
+ }
2263
+ case "u32": {
2264
+ const buf = new Uint8Array(4);
2265
+ new DataView(buf.buffer).setUint32(0, Number(parseUint(value, 4294967295n)), false);
2266
+ parts.push(buf);
2267
+ break;
2268
+ }
2269
+ case "u64": {
2270
+ const buf = new Uint8Array(8);
2271
+ new DataView(buf.buffer).setBigUint64(
2272
+ 0,
2273
+ parseUint(value, 18446744073709551615n),
2274
+ false
2275
+ );
2276
+ parts.push(buf);
2277
+ break;
2278
+ }
2279
+ case "string": {
2280
+ const bytes = new TextEncoder().encode(value);
2281
+ if (bytes.length > MAX_STRING_VALUE_LEN) {
2282
+ throw new AttestationDataError("String value too long");
2283
+ }
2284
+ const len = new Uint8Array(2);
2285
+ new DataView(len.buffer).setUint16(0, bytes.length, false);
2286
+ parts.push(len, bytes);
2287
+ break;
2288
+ }
2289
+ case "pubkey":
2290
+ parts.push(parsePubkeyHex(value));
2291
+ break;
2292
+ default:
2293
+ throw new AttestationDataError(`Unsupported type: ${field.type}`);
2294
+ }
2295
+ }
2296
+ const total = parts.reduce((a, p) => a + p.length, 0);
2297
+ if (total > MAX_ATTESTATION_DATA_LEN) {
2298
+ throw new AttestationDataError("Attestation data too large");
2299
+ }
2300
+ const out = new Uint8Array(total);
2301
+ let offset = 0;
2302
+ for (const p of parts) {
2303
+ out.set(p, offset);
2304
+ offset += p.length;
2305
+ }
2306
+ return out;
2307
+ }
2308
+ function decodeAttestationData(data, fieldDefs) {
2309
+ const dec = new TextDecoder();
2310
+ const result = {};
2311
+ let offset = 0;
2312
+ for (const field of fieldDefs) {
2313
+ switch (field.type) {
2314
+ case "bool":
2315
+ if (offset >= data.length) throw new AttestationDataError("Truncated bool");
2316
+ result[field.name] = data[offset] === 1 ? "true" : "false";
2317
+ offset += 1;
2318
+ break;
2319
+ case "u8":
2320
+ if (offset >= data.length) throw new AttestationDataError("Truncated u8");
2321
+ result[field.name] = String(data[offset]);
2322
+ offset += 1;
2323
+ break;
2324
+ case "u16": {
2325
+ if (offset + 2 > data.length) throw new AttestationDataError("Truncated u16");
2326
+ result[field.name] = String(
2327
+ new DataView(data.buffer, data.byteOffset + offset, 2).getUint16(0, false)
2328
+ );
2329
+ offset += 2;
2330
+ break;
2331
+ }
2332
+ case "u32": {
2333
+ if (offset + 4 > data.length) throw new AttestationDataError("Truncated u32");
2334
+ result[field.name] = String(
2335
+ new DataView(data.buffer, data.byteOffset + offset, 4).getUint32(0, false)
2336
+ );
2337
+ offset += 4;
2338
+ break;
2339
+ }
2340
+ case "u64": {
2341
+ if (offset + 8 > data.length) throw new AttestationDataError("Truncated u64");
2342
+ result[field.name] = String(
2343
+ new DataView(data.buffer, data.byteOffset + offset, 8).getBigUint64(0, false)
2344
+ );
2345
+ offset += 8;
2346
+ break;
2347
+ }
2348
+ case "string": {
2349
+ if (offset + 2 > data.length) {
2350
+ throw new AttestationDataError("Truncated string length");
2351
+ }
2352
+ const len = new DataView(data.buffer, data.byteOffset + offset, 2).getUint16(0, false);
2353
+ offset += 2;
2354
+ if (offset + len > data.length) throw new AttestationDataError("Truncated string");
2355
+ result[field.name] = dec.decode(data.slice(offset, offset + len));
2356
+ offset += len;
2357
+ break;
2358
+ }
2359
+ case "pubkey": {
2360
+ if (offset + 32 > data.length) throw new AttestationDataError("Truncated pubkey");
2361
+ const slice = data.slice(offset, offset + 32);
2362
+ result[field.name] = "0x" + Array.from(slice).map((b) => b.toString(16).padStart(2, "0")).join("");
2363
+ offset += 32;
2364
+ break;
2365
+ }
2366
+ default:
2367
+ throw new AttestationDataError(`Unsupported type: ${field.type}`);
2368
+ }
2369
+ }
2370
+ if (offset !== data.length) {
2371
+ throw new AttestationDataError("Trailing bytes in attestation data");
2372
+ }
2373
+ return result;
2374
+ }
2375
+
2376
+ // src/crypto/backup.ts
2377
+ var PBKDF2_ITERATIONS = 6e5;
2378
+ var SALT_BYTES = 16;
2379
+ var IV_BYTES = 12;
2380
+ function toArrayBuffer(bytes) {
2381
+ const copy = new Uint8Array(bytes.byteLength);
2382
+ copy.set(bytes);
2383
+ return copy.buffer;
2384
+ }
2385
+ function bytesToBase64(bytes) {
2386
+ let binary = "";
2387
+ for (let i = 0; i < bytes.length; i += 1) binary += String.fromCharCode(bytes[i] ?? 0);
2388
+ return btoa(binary);
2389
+ }
2390
+ function base64ToBytes(base64) {
2391
+ const binary = atob(base64);
2392
+ const out = new Uint8Array(binary.length);
2393
+ for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);
2394
+ return out;
2395
+ }
2396
+ async function deriveKeyFromPassword(password, salt) {
2397
+ const encoder = new TextEncoder();
2398
+ const passwordKey = await crypto.subtle.importKey(
2399
+ "raw",
2400
+ toArrayBuffer(encoder.encode(password)),
2401
+ "PBKDF2",
2402
+ false,
2403
+ ["deriveKey"]
2404
+ );
2405
+ return crypto.subtle.deriveKey(
2406
+ {
2407
+ name: "PBKDF2",
2408
+ salt: toArrayBuffer(salt),
2409
+ iterations: PBKDF2_ITERATIONS,
2410
+ hash: "SHA-256"
2411
+ },
2412
+ passwordKey,
2413
+ { name: "AES-GCM", length: 256 },
2414
+ false,
2415
+ ["encrypt", "decrypt"]
2416
+ );
2417
+ }
2418
+ async function encryptField(plaintext, key) {
2419
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
2420
+ const encoded = new TextEncoder().encode(plaintext);
2421
+ const ciphertext = new Uint8Array(
2422
+ await crypto.subtle.encrypt(
2423
+ { name: "AES-GCM", iv: toArrayBuffer(iv) },
2424
+ key,
2425
+ encoded
2426
+ )
2427
+ );
2428
+ return `${bytesToBase64(iv)}:${bytesToBase64(ciphertext)}`;
2429
+ }
2430
+ async function decryptField(packed, key) {
2431
+ const [ivB64, ctB64] = packed.split(":");
2432
+ if (!ivB64 || !ctB64) throw new Error("Invalid encrypted field format");
2433
+ const iv = base64ToBytes(ivB64);
2434
+ const ciphertext = base64ToBytes(ctB64);
2435
+ const decrypted = await crypto.subtle.decrypt(
2436
+ { name: "AES-GCM", iv: toArrayBuffer(iv) },
2437
+ key,
2438
+ toArrayBuffer(ciphertext)
2439
+ );
2440
+ return new TextDecoder().decode(new Uint8Array(decrypted));
2441
+ }
2442
+ async function encryptGhostEntries(entries, password) {
2443
+ const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES));
2444
+ const key = await deriveKeyFromPassword(password, salt);
2445
+ const encrypted = [];
2446
+ for (const entry of entries) {
2447
+ encrypted.push({
2448
+ cluster: entry.cluster,
2449
+ stealthAddress: entry.stealthAddress,
2450
+ ephemeralPrivKeyEncrypted: entry.ephemeralPrivKeyHex ? await encryptField(entry.ephemeralPrivKeyHex, key) : void 0,
2451
+ createdAt: entry.createdAt
2452
+ });
2453
+ }
2454
+ return { version: 1, salt: bytesToBase64(salt), entries: encrypted };
2455
+ }
2456
+ async function decryptGhostEntries(payload, password) {
2457
+ if (payload.version !== 1) {
2458
+ throw new Error("Unsupported encrypted payload version");
2459
+ }
2460
+ const salt = base64ToBytes(payload.salt);
2461
+ const key = await deriveKeyFromPassword(password, salt);
2462
+ const decrypted = [];
2463
+ for (const entry of payload.entries) {
2464
+ decrypted.push({
2465
+ cluster: entry.cluster,
2466
+ stealthAddress: entry.stealthAddress,
2467
+ ephemeralPrivKeyHex: entry.ephemeralPrivKeyEncrypted ? await decryptField(entry.ephemeralPrivKeyEncrypted, key) : void 0,
2468
+ createdAt: entry.createdAt
2469
+ });
2470
+ }
2471
+ return decrypted;
2472
+ }
2473
+ async function exportEncryptedBackup(entries, password) {
2474
+ return JSON.stringify(await encryptGhostEntries(entries, password));
2475
+ }
2476
+ async function importEncryptedBackup(backupJson, password) {
2477
+ const payload = JSON.parse(backupJson);
2478
+ return decryptGhostEntries(payload, password);
2479
+ }
2480
+
2481
+ // src/crypto/payment-link.ts
2482
+ function isValidMetaAddress(metaAddress) {
2483
+ if (metaAddress.length !== 134) return false;
2484
+ if (!metaAddress.startsWith("0x")) return false;
2485
+ return /^[0-9a-fA-F]{132}$/.test(metaAddress.slice(2));
2486
+ }
2487
+ function isValidNetwork(network) {
2488
+ return ["testnet", "mainnet", "futurenet", "local"].includes(network);
2489
+ }
2490
+ function isValidStellarPublicKey(publicKey) {
2491
+ if (publicKey.length !== 56) return false;
2492
+ if (!publicKey.startsWith("G")) return false;
2493
+ return /^[A-Z2-7]{55}$/.test(publicKey);
2494
+ }
2495
+ function isValidAssetCode(assetCode) {
2496
+ if (assetCode.length < 1 || assetCode.length > 12) return false;
2497
+ return /^[a-zA-Z0-9]+$/.test(assetCode);
2498
+ }
2499
+ function isValidAmount(amount) {
2500
+ if (!amount) return false;
2501
+ const num = parseFloat(amount);
2502
+ if (isNaN(num) || num <= 0) return false;
2503
+ return /^[0-9]+(\.[0-9]+)?$/.test(amount);
2504
+ }
2505
+ function isValidIso8601(timestamp) {
2506
+ try {
2507
+ return !isNaN(new Date(timestamp).getTime());
2508
+ } catch {
2509
+ return false;
2510
+ }
2511
+ }
2512
+ function isValidUrl(url) {
2513
+ try {
2514
+ return new URL(url).protocol === "https:";
2515
+ } catch {
2516
+ return false;
2517
+ }
2518
+ }
2519
+ function encodePaymentLink(link) {
2520
+ if (!isValidMetaAddress(link.metaAddress)) {
2521
+ throw new Error("Invalid meta-address format");
2522
+ }
2523
+ if (!isValidNetwork(link.network)) {
2524
+ throw new Error("Invalid network identifier");
2525
+ }
2526
+ const uri = `opaque://v${link.version}/${link.network}/${link.metaAddress}`;
2527
+ const params = new URLSearchParams();
2528
+ if (link.params.amount) {
2529
+ if (!isValidAmount(link.params.amount)) throw new Error("Invalid amount format");
2530
+ params.set("amount", link.params.amount);
2531
+ }
2532
+ if (link.params.asset) {
2533
+ if (!isValidAssetCode(link.params.asset)) throw new Error("Invalid asset code");
2534
+ params.set("asset", link.params.asset);
2535
+ }
2536
+ if (link.params.issuer) {
2537
+ if (!isValidStellarPublicKey(link.params.issuer)) {
2538
+ throw new Error("Invalid issuer address");
2539
+ }
2540
+ params.set("issuer", link.params.issuer);
2541
+ }
2542
+ if (link.params.memo) params.set("memo", link.params.memo);
2543
+ if (link.params.sep) params.set("sep", link.params.sep);
2544
+ if (link.params.callback) {
2545
+ if (!isValidUrl(link.params.callback)) throw new Error("Invalid callback URL");
2546
+ params.set("callback", link.params.callback);
2547
+ }
2548
+ if (link.params.label) params.set("label", link.params.label);
2549
+ if (link.params.expires) {
2550
+ if (!isValidIso8601(link.params.expires)) {
2551
+ throw new Error("Invalid expiration timestamp");
2552
+ }
2553
+ params.set("expires", link.params.expires);
2554
+ }
2555
+ const queryString = params.toString();
2556
+ return queryString ? `${uri}?${queryString}` : uri;
2557
+ }
2558
+ function decodePaymentLink(linkString, configuredNetwork) {
2559
+ try {
2560
+ const url = new URL(linkString);
2561
+ if (url.protocol !== "opaque:") {
2562
+ return { error: { type: "INVALID_FORMAT", message: "Invalid protocol: must be opaque://" } };
2563
+ }
2564
+ const pathParts = [
2565
+ url.hostname,
2566
+ ...url.pathname.split("/").filter(Boolean)
2567
+ ].filter(Boolean);
2568
+ if (pathParts.length < 3) {
2569
+ return {
2570
+ error: {
2571
+ type: "INVALID_FORMAT",
2572
+ message: "Invalid path format: expected opaque://v{version}/{network}/{meta-address}"
2573
+ }
2574
+ };
2575
+ }
2576
+ const versionMatch = pathParts[0].match(/^v(\d+)$/);
2577
+ if (!versionMatch) {
2578
+ return { error: { type: "INVALID_FORMAT", message: "Invalid version format: expected v{number}" } };
2579
+ }
2580
+ const version = parseInt(versionMatch[1], 10);
2581
+ if (version !== 1) {
2582
+ return {
2583
+ error: {
2584
+ type: "UNSUPPORTED_VERSION",
2585
+ message: `Unsupported version: v${version}. Only v1 is currently supported.`
2586
+ }
2587
+ };
2588
+ }
2589
+ const network = pathParts[1];
2590
+ if (!isValidNetwork(network)) {
2591
+ return {
2592
+ error: {
2593
+ type: "INVALID_FORMAT",
2594
+ message: `Invalid network: ${network}. Must be one of: testnet, mainnet, futurenet, local`
2595
+ }
2596
+ };
2597
+ }
2598
+ if (configuredNetwork && network !== configuredNetwork) {
2599
+ return {
2600
+ error: {
2601
+ type: "NETWORK_MISMATCH",
2602
+ message: `Network mismatch: link is for ${network}, but app is configured for ${configuredNetwork}`,
2603
+ details: { linkNetwork: network, configuredNetwork }
2604
+ }
2605
+ };
2606
+ }
2607
+ const metaAddress = pathParts[2];
2608
+ if (!isValidMetaAddress(metaAddress)) {
2609
+ return {
2610
+ error: {
2611
+ type: "INVALID_META_ADDRESS",
2612
+ message: `Invalid meta-address format: ${metaAddress}. Expected 0x + 132 hex chars.`
2613
+ }
2614
+ };
2615
+ }
2616
+ const params = {};
2617
+ const searchParams = url.searchParams;
2618
+ if (searchParams.has("amount")) {
2619
+ const amount = searchParams.get("amount");
2620
+ if (!isValidAmount(amount)) {
2621
+ return { error: { type: "INVALID_PARAMETER", message: `Invalid amount parameter: ${amount}`, details: { parameter: "amount", value: amount } } };
2622
+ }
2623
+ params.amount = amount;
2624
+ }
2625
+ if (searchParams.has("asset")) {
2626
+ const asset = searchParams.get("asset");
2627
+ if (!isValidAssetCode(asset)) {
2628
+ return { error: { type: "INVALID_PARAMETER", message: `Invalid asset code: ${asset}`, details: { parameter: "asset", value: asset } } };
2629
+ }
2630
+ params.asset = asset;
2631
+ }
2632
+ if (searchParams.has("issuer")) {
2633
+ const issuer = searchParams.get("issuer");
2634
+ if (!isValidStellarPublicKey(issuer)) {
2635
+ return { error: { type: "INVALID_PARAMETER", message: `Invalid issuer address: ${issuer}`, details: { parameter: "issuer", value: issuer } } };
2636
+ }
2637
+ params.issuer = issuer;
2638
+ }
2639
+ if (searchParams.has("memo")) params.memo = searchParams.get("memo");
2640
+ if (searchParams.has("sep")) params.sep = searchParams.get("sep");
2641
+ if (searchParams.has("callback")) {
2642
+ const callback = searchParams.get("callback");
2643
+ if (!isValidUrl(callback)) {
2644
+ return { error: { type: "INVALID_PARAMETER", message: `Invalid callback URL: ${callback}`, details: { parameter: "callback", value: callback } } };
2645
+ }
2646
+ params.callback = callback;
2647
+ }
2648
+ if (searchParams.has("label")) params.label = searchParams.get("label");
2649
+ if (searchParams.has("expires")) {
2650
+ const expires = searchParams.get("expires");
2651
+ if (!isValidIso8601(expires)) {
2652
+ return { error: { type: "INVALID_PARAMETER", message: `Invalid expiration timestamp: ${expires}`, details: { parameter: "expires", value: expires } } };
2653
+ }
2654
+ params.expires = expires;
2655
+ }
2656
+ if (params.expires && new Date(params.expires) < /* @__PURE__ */ new Date()) {
2657
+ return { error: { type: "INVALID_PARAMETER", message: `Payment link has expired: ${params.expires}`, details: { parameter: "expires", value: params.expires } } };
2658
+ }
2659
+ return { link: { version, network, metaAddress, params } };
2660
+ } catch (error) {
2661
+ return {
2662
+ error: {
2663
+ type: "INVALID_FORMAT",
2664
+ message: `Failed to parse payment link: ${error instanceof Error ? error.message : String(error)}`,
2665
+ details: error
2666
+ }
2667
+ };
2668
+ }
2669
+ }
2670
+ function createPaymentLink(metaAddress, network, params = {}) {
2671
+ return encodePaymentLink({ version: 1, network, metaAddress, params });
2672
+ }
2673
+ function isOpaquePaymentLink(linkString) {
2674
+ try {
2675
+ return "link" in decodePaymentLink(linkString);
2676
+ } catch {
2677
+ return false;
2678
+ }
2679
+ }
2680
+ function convertLegacyLink(legacyLink, network, params = {}) {
2681
+ try {
2682
+ const url = new URL(legacyLink);
2683
+ const pathParts = url.pathname.split("/").filter(Boolean);
2684
+ const metaAddress = pathParts[pathParts.length - 1];
2685
+ if (!isValidMetaAddress(metaAddress)) return null;
2686
+ return createPaymentLink(metaAddress, network, params);
2687
+ } catch {
2688
+ return null;
2689
+ }
2690
+ }
2691
+
2692
+ // src/crypto/memo.ts
2693
+ var CUSTODIAL_ADDRESSES = Object.freeze({
2694
+ GA5XIGA5C7QTPTWXQHY6MCJRMTRZDOSHR6EFIBNDQTCQHG262N4GGKTM: {
2695
+ name: "Kraken",
2696
+ recommendedMemoType: "id"
2697
+ },
2698
+ GCGNWKCJ3KHRLPM3TMQN7IPVUMRPMYIPGKDPELDPRBMVUPLNZAJDK4VG: {
2699
+ name: "Binance",
2700
+ recommendedMemoType: "text"
2701
+ },
2702
+ GBJ65CCWNPGFNXIVRZMNQSGNXHJYM3O3HFK2CIHWXVKAFEWZNUQOH53I: {
2703
+ name: "Coinbase",
2704
+ recommendedMemoType: "text"
2705
+ },
2706
+ GDXBP3R6N62YR4MTEGEHDIJWQ6BIRYNG6UCV4XQEFKQGGYS7QUDXMJSX: {
2707
+ name: "KuCoin",
2708
+ recommendedMemoType: "text"
2709
+ }
2710
+ });
2711
+ function memoRiskFor(destination) {
2712
+ if (!destination) return { isKnownCustodian: false };
2713
+ const entry = CUSTODIAL_ADDRESSES[destination.trim()];
2714
+ if (!entry) return { isKnownCustodian: false };
2715
+ return {
2716
+ isKnownCustodian: true,
2717
+ custodianName: entry.name,
2718
+ recommendedMemoType: entry.recommendedMemoType
2719
+ };
2720
+ }
2721
+ function validateMemo(memoType, memo) {
2722
+ const value = (memo ?? "").trim();
2723
+ if (memoType === "none") {
2724
+ if (value.length > 0) {
2725
+ return { ok: false, error: "Memo must be empty when memo type is 'none'." };
2726
+ }
2727
+ return { ok: true };
2728
+ }
2729
+ if (value.length === 0) {
2730
+ return { ok: false, error: "Memo is required for this memo type." };
2731
+ }
2732
+ switch (memoType) {
2733
+ case "text": {
2734
+ const bytes = new TextEncoder().encode(value).byteLength;
2735
+ if (bytes > 28) {
2736
+ return { ok: false, error: "Text memo must be 28 UTF-8 bytes or fewer." };
2737
+ }
2738
+ return { ok: true };
2739
+ }
2740
+ case "id": {
2741
+ if (!/^\d+$/.test(value)) {
2742
+ return { ok: false, error: "ID memo must be a non-negative integer." };
2743
+ }
2744
+ try {
2745
+ const n = BigInt(value);
2746
+ if (n < 0n || n > 0xffffffffffffffffn) {
2747
+ return { ok: false, error: "ID memo must fit in an unsigned 64-bit integer." };
2748
+ }
2749
+ } catch {
2750
+ return { ok: false, error: "ID memo must be a non-negative integer." };
2751
+ }
2752
+ return { ok: true };
2753
+ }
2754
+ case "hash":
2755
+ case "return": {
2756
+ if (!/^[0-9a-fA-F]{64}$/.test(value)) {
2757
+ return { ok: false, error: "Hash/return memo must be 64 hexadecimal characters." };
2758
+ }
2759
+ return { ok: true };
2760
+ }
2761
+ }
2762
+ }
2763
+ function memoWarningCopy(risk, memo) {
2764
+ if (!risk.isKnownCustodian) return null;
2765
+ if (memo && memo.trim().length > 0) return null;
2766
+ return `Destination looks like ${risk.custodianName ?? "an exchange or custodian"}. Sending without a memo may result in lost funds.`;
2767
+ }
2768
+
2769
+ // src/errors/index.ts
2770
+ var OpaqueError = class extends Error {
2771
+ /** Stable, machine-readable error code (e.g. "CONFIG", "CONTRACT"). */
2772
+ code;
2773
+ constructor(message, code, options) {
2774
+ super(message);
2775
+ this.name = new.target.name;
2776
+ this.code = code;
2777
+ if (options?.cause !== void 0) {
2778
+ this.cause = options.cause;
2779
+ }
2780
+ }
2781
+ };
2782
+ var ConfigError = class extends OpaqueError {
2783
+ constructor(message, options) {
2784
+ super(message, "CONFIG", options);
2785
+ }
2786
+ };
2787
+ var SignerError = class extends OpaqueError {
2788
+ constructor(message, options) {
2789
+ super(message, "SIGNER", options);
2790
+ }
2791
+ };
2792
+ var RpcError = class extends OpaqueError {
2793
+ httpStatus;
2794
+ constructor(message, options) {
2795
+ super(message, "RPC", options);
2796
+ this.httpStatus = options?.httpStatus;
2797
+ }
2798
+ };
2799
+ var SimulationError = class extends OpaqueError {
2800
+ diagnostics;
2801
+ constructor(message, options) {
2802
+ super(message, "SIMULATION", options);
2803
+ this.diagnostics = options?.diagnostics;
2804
+ }
2805
+ };
2806
+ var ContractError = class extends OpaqueError {
2807
+ contract;
2808
+ contractCode;
2809
+ /** Human-readable name when the contract's error enum is known. */
2810
+ errorName;
2811
+ constructor(opts) {
2812
+ const label = opts.errorName ? `${opts.errorName} (#${opts.contractCode})` : `#${opts.contractCode}`;
2813
+ super(
2814
+ opts.message ?? `${opts.contract} reverted: ${label}`,
2815
+ "CONTRACT",
2816
+ { cause: opts.cause }
2817
+ );
2818
+ this.contract = opts.contract;
2819
+ this.contractCode = opts.contractCode;
2820
+ this.errorName = opts.errorName;
2821
+ }
2822
+ };
2823
+ var RootUnavailableError = class extends OpaqueError {
2824
+ constructor(message, options) {
2825
+ super(message, "ROOT_UNAVAILABLE", options);
2826
+ }
2827
+ };
2828
+ var ArtifactError = class extends OpaqueError {
2829
+ constructor(message, options) {
2830
+ super(message, "ARTIFACT", options);
2831
+ }
2832
+ };
2833
+ var NotWiredError = class extends OpaqueError {
2834
+ constructor(capability, hint) {
2835
+ super(
2836
+ `${capability} is not wired in this build.` + (hint ? ` ${hint}` : ""),
2837
+ "NOT_WIRED"
2838
+ );
2839
+ }
2840
+ };
2841
+ var CONTRACT_ERROR_NAMES = {
2842
+ "reputation-verifier": {
2843
+ 2: "RootExpired",
2844
+ 4: "NullifierReplay"
2845
+ }
2846
+ };
2847
+ function contractErrorName(contractPackage, code) {
2848
+ return CONTRACT_ERROR_NAMES[contractPackage]?.[code];
2849
+ }
2850
+
2851
+ // src/config/networks.ts
2852
+ var NETWORK_PRESETS = {
2853
+ testnet: {
2854
+ passphrase: "Test SDF Network ; September 2015",
2855
+ rpcUrls: ["https://soroban-testnet.stellar.org"],
2856
+ horizonUrls: ["https://horizon-testnet.stellar.org"]
2857
+ },
2858
+ futurenet: {
2859
+ passphrase: "Test SDF Future Network ; October 2022",
2860
+ rpcUrls: ["https://rpc-futurenet.stellar.org"],
2861
+ horizonUrls: ["https://horizon-futurenet.stellar.org"]
2862
+ },
2863
+ mainnet: {
2864
+ passphrase: "Public Global Stellar Network ; September 2015",
2865
+ // No defaults: mainnet requires explicit production providers.
2866
+ rpcUrls: [],
2867
+ horizonUrls: []
2868
+ },
2869
+ local: {
2870
+ passphrase: "Standalone Network ; February 2017",
2871
+ rpcUrls: ["http://localhost:8000/soroban/rpc"],
2872
+ horizonUrls: ["http://localhost:8000"]
2873
+ }
2874
+ };
2875
+
2876
+ // src/config/addresses.ts
2877
+ var TESTNET_DEPLOYMENT = {
2878
+ contracts: {
2879
+ stealthRegistry: "CAIXWMGYZR3YAQ3CPCXOU42WG62E3ARUSG4GDHHDMNRXUD44YSGE5VXW",
2880
+ stealthAnnouncer: "CB2Y3GJMPY5BUSZLXG3DSIMERCNCTUM63IIEQ2GUNYEJ3DBKPFIZQGCS",
2881
+ groth16Verifier: "CAWXRGFZITZ7TJIZNDLOPJNVEMPAZDWFI22XI76FC67YF2MDRUXLBS2T",
2882
+ reputationVerifier: "CAFVXL6A5N4FVQZ733GLUX27ETPLLINLE75ZABNLFYEKPIYZORFCBSVR",
2883
+ schemaRegistry: "CA5XA2T2DAOZH7QG5RG2372KGDHMCEVQJMBGT7AJMNHRI6C4ZIM37QCP",
2884
+ attestationEngineV2: "CB6KOWOQBFQDX5NNGUJGECHXUF3LHUE77FYD2C6JSWMHYWGCJOUTSDPX",
2885
+ poolVerifier: "CD2SQALXCZDRTWMFGUBRIP2GFH6TJ3GQ3S6YU4R4C2IIEYC43MLUMS7Q",
2886
+ privacyPool: "CAYXZTWB26VPIO6UTKFM22UY6XIMO72IRCFKAU2C6NSMQ4JSJ6VJ7BLE",
2887
+ relayerRegistry: "CCQJFUMMSYOOEJN65E6OH2XSJUESSHRHELFTCSOMIREASXPIJE4AIAMO"
2888
+ },
2889
+ pool: {
2890
+ scope: 1,
2891
+ nativeSac: "CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC"
2892
+ },
2893
+ relayer: {
2894
+ minimumStake: 1000000n,
2895
+ unstakeCooldownLedgers: 720,
2896
+ maxDeadlineLedgers: 17280,
2897
+ gatewayUrls: ["https://g-stelar-relayer.opaque.cash"]
2898
+ },
2899
+ deploymentLedger: 3101e3
2900
+ };
2901
+ var DEPLOYMENTS = {
2902
+ testnet: TESTNET_DEPLOYMENT
2903
+ };
2904
+
2905
+ // src/config/index.ts
2906
+ function mergeContracts(base, overrides) {
2907
+ const merged = { ...base ?? {}, ...overrides ?? {} };
2908
+ const keys = [
2909
+ "stealthRegistry",
2910
+ "stealthAnnouncer",
2911
+ "groth16Verifier",
2912
+ "reputationVerifier",
2913
+ "schemaRegistry",
2914
+ "attestationEngineV2",
2915
+ "poolVerifier",
2916
+ "privacyPool",
2917
+ "relayerRegistry"
2918
+ ];
2919
+ const missing = keys.filter((k) => !merged[k]);
2920
+ if (missing.length > 0) {
2921
+ throw new ConfigError(
2922
+ `Missing contract address(es): ${missing.join(", ")}. Pass them via config.contracts for this network.`
2923
+ );
2924
+ }
2925
+ return merged;
2926
+ }
2927
+ function resolveConfig(config) {
2928
+ const preset = NETWORK_PRESETS[config.network];
2929
+ if (!preset) {
2930
+ throw new ConfigError(`Unknown network: ${String(config.network)}`);
2931
+ }
2932
+ const deployment = DEPLOYMENTS[config.network];
2933
+ const rpcUrls = config.rpcUrls?.length ? config.rpcUrls : preset.rpcUrls;
2934
+ const horizonUrls = config.horizonUrls?.length ? config.horizonUrls : preset.horizonUrls;
2935
+ if (rpcUrls.length === 0) {
2936
+ throw new ConfigError(
2937
+ `No Soroban RPC URL configured for ${config.network}. Set config.rpcUrls.`
2938
+ );
2939
+ }
2940
+ if (horizonUrls.length === 0) {
2941
+ throw new ConfigError(
2942
+ `No Horizon URL configured for ${config.network}. Set config.horizonUrls.`
2943
+ );
2944
+ }
2945
+ const contracts = mergeContracts(deployment?.contracts, config.contracts);
2946
+ if (!deployment && !config.contracts) {
2947
+ throw new ConfigError(
2948
+ `No baked deployment for ${config.network}; pass config.contracts.`
2949
+ );
2950
+ }
2951
+ const pool = deployment?.pool ?? { scope: 1, nativeSac: contracts.privacyPool };
2952
+ const relayer = deployment?.relayer ?? {
2953
+ minimumStake: 0n,
2954
+ unstakeCooldownLedgers: 0,
2955
+ maxDeadlineLedgers: 0,
2956
+ gatewayUrls: []
2957
+ };
2958
+ const relayerGatewayUrls = config.relayerGatewayUrls?.length ? config.relayerGatewayUrls : relayer.gatewayUrls;
2959
+ return {
2960
+ network: config.network,
2961
+ passphrase: preset.passphrase,
2962
+ rpcUrls,
2963
+ horizonUrls,
2964
+ contracts,
2965
+ pool,
2966
+ relayer,
2967
+ relayerGatewayUrls,
2968
+ reputationPublisherUrl: config.reputationPublisherUrl,
2969
+ startLedger: config.startLedger ?? deployment?.deploymentLedger ?? 0
2970
+ };
2971
+ }
2972
+ function keypairSigner(secretOrKeypair) {
2973
+ const keypair = typeof secretOrKeypair === "string" ? Keypair.fromSecret(secretOrKeypair) : secretOrKeypair;
2974
+ return {
2975
+ publicKey: () => keypair.publicKey(),
2976
+ async signTransaction(xdr6, ctx) {
2977
+ try {
2978
+ const tx = TransactionBuilder.fromXDR(xdr6, ctx.networkPassphrase);
2979
+ tx.sign(keypair);
2980
+ return tx.toXDR();
2981
+ } catch (cause) {
2982
+ throw new SignerError("Keypair failed to sign transaction", { cause });
2983
+ }
2984
+ }
2985
+ };
2986
+ }
2987
+ function callbackSigner(opts) {
2988
+ return {
2989
+ publicKey: () => typeof opts.publicKey === "function" ? opts.publicKey() : opts.publicKey,
2990
+ async signTransaction(xdr6) {
2991
+ try {
2992
+ return await opts.signTransaction(xdr6);
2993
+ } catch (cause) {
2994
+ throw new SignerError("Callback signer failed", { cause });
2995
+ }
2996
+ },
2997
+ signMessage: opts.signMessage
2998
+ };
2999
+ }
3000
+
3001
+ // src/logger/index.ts
3002
+ var silentLogger = {
3003
+ debug() {
3004
+ },
3005
+ info() {
3006
+ },
3007
+ warn() {
3008
+ },
3009
+ error() {
3010
+ }
3011
+ };
3012
+ var consoleLogger = {
3013
+ debug: (...a) => console.debug(...a),
3014
+ info: (...a) => console.info(...a),
3015
+ warn: (...a) => console.warn(...a),
3016
+ error: (...a) => console.error(...a)
3017
+ };
3018
+
3019
+ // src/telemetry/index.ts
3020
+ var noopTelemetry = {};
3021
+ function addressToScVal(addr) {
3022
+ return new Address(addr).toScVal();
3023
+ }
3024
+ function bytesToScVal(bytes) {
3025
+ return xdr.ScVal.scvBytes(Buffer.from(bytes));
3026
+ }
3027
+ function u32ToScVal(n) {
3028
+ return nativeToScVal(n, { type: "u32" });
3029
+ }
3030
+ function u64ToScVal(n) {
3031
+ return nativeToScVal(n, { type: "u64" });
3032
+ }
3033
+ function i128ToScVal(n) {
3034
+ return nativeToScVal(n, { type: "i128" });
3035
+ }
3036
+ function u128ToScVal(n) {
3037
+ return nativeToScVal(n, { type: "u128" });
3038
+ }
3039
+ function symbolToScVal(s) {
3040
+ return nativeToScVal(s, { type: "symbol" });
3041
+ }
3042
+ function stringToScVal(s) {
3043
+ return nativeToScVal(s, { type: "string" });
3044
+ }
3045
+ function boolToScVal(b) {
3046
+ return nativeToScVal(b, { type: "bool" });
3047
+ }
3048
+ function optionAddressToScVal(addr) {
3049
+ return addr ? addressToScVal(addr) : nativeToScVal(null, { type: "address" });
3050
+ }
3051
+ function fromScVal(v) {
3052
+ return scValToNative(v);
3053
+ }
3054
+ function describeScError(e) {
3055
+ const type = e.switch().name;
3056
+ if (type === "sceContract") {
3057
+ try {
3058
+ return `ContractError#${e.contractCode()}`;
3059
+ } catch {
3060
+ return "ContractError";
3061
+ }
3062
+ }
3063
+ try {
3064
+ return `${type}/${e.code().name}`;
3065
+ } catch {
3066
+ return type;
3067
+ }
3068
+ }
3069
+ function scValToReadable(v) {
3070
+ try {
3071
+ if (v.switch().name === "scvError") return describeScError(v.error());
3072
+ return scValToNative(v);
3073
+ } catch {
3074
+ try {
3075
+ return v.switch().name;
3076
+ } catch {
3077
+ return "?";
3078
+ }
3079
+ }
3080
+ }
3081
+ function decodeDiagnostics(events) {
3082
+ const parts = [];
3083
+ for (const raw of events) {
3084
+ try {
3085
+ const de = raw;
3086
+ const v0 = de.event().body().v0();
3087
+ const topics = v0.topics().map(scValToReadable);
3088
+ const data = scValToReadable(v0.data());
3089
+ parts.push(JSON.stringify({ topics, data }));
3090
+ } catch {
3091
+ }
3092
+ }
3093
+ return Array.from(new Set(parts)).join(" | ").slice(0, 1500);
3094
+ }
3095
+ function extractContractErrorCode(events) {
3096
+ for (const raw of events) {
3097
+ try {
3098
+ const de = raw;
3099
+ const v0 = de.event().body().v0();
3100
+ for (const t of v0.topics()) {
3101
+ if (t.switch().name === "scvError") {
3102
+ const err = t.error();
3103
+ if (err.switch().name === "sceContract") return err.contractCode();
3104
+ }
3105
+ }
3106
+ const data = v0.data();
3107
+ if (data.switch().name === "scvError") {
3108
+ const err = data.error();
3109
+ if (err.switch().name === "sceContract") return err.contractCode();
3110
+ }
3111
+ } catch {
3112
+ }
3113
+ }
3114
+ return null;
3115
+ }
3116
+ var READ_TIMEOUT_MS = 12e3;
3117
+ var READ_RETRIES_PER_PROVIDER = 2;
3118
+ var TX_POLL_TIMEOUT_MS = 6e4;
3119
+ var TX_POLL_INTERVAL_MS = 1e3;
3120
+ var NEW_ACCOUNT_MIN_RESERVE_STROOPS = 10000000n;
3121
+ function sleep(ms) {
3122
+ return new Promise((resolve) => setTimeout(resolve, ms));
3123
+ }
3124
+ function isRetryableReadError(err) {
3125
+ const status = typeof err === "object" && err !== null && "response" in err ? err.response?.status : void 0;
3126
+ if (status && [408, 429, 500, 502, 503, 504].includes(status)) return true;
3127
+ const message = err instanceof Error ? err.message : String(err);
3128
+ return /timeout|timed out|rate.?limit|too many requests|network|fetch/i.test(message);
3129
+ }
3130
+ async function withTimeout(promise, label) {
3131
+ let timer;
3132
+ const timeout = new Promise((_, reject) => {
3133
+ timer = setTimeout(
3134
+ () => reject(new RpcError(`${label} timed out after ${READ_TIMEOUT_MS}ms`)),
3135
+ READ_TIMEOUT_MS
3136
+ );
3137
+ });
3138
+ try {
3139
+ return await Promise.race([promise, timeout]);
3140
+ } finally {
3141
+ if (timer) clearTimeout(timer);
3142
+ }
3143
+ }
3144
+ var RpcClient = class {
3145
+ config;
3146
+ logger;
3147
+ telemetry;
3148
+ servers;
3149
+ constructor(opts) {
3150
+ this.config = opts.config;
3151
+ this.logger = opts.logger ?? silentLogger;
3152
+ this.telemetry = opts.telemetry ?? noopTelemetry;
3153
+ this.servers = opts.config.rpcUrls.map(
3154
+ (url) => new rpc.Server(url, { allowHttp: url.startsWith("http://") })
3155
+ );
3156
+ if (this.servers.length === 0) {
3157
+ throw new RpcError("RpcClient requires at least one RPC URL");
3158
+ }
3159
+ }
3160
+ /** Primary Soroban RPC server. */
3161
+ get server() {
3162
+ return this.servers[0];
3163
+ }
3164
+ /** Horizon server (first configured Horizon URL). */
3165
+ horizon() {
3166
+ return new Horizon.Server(this.config.horizonUrls[0]);
3167
+ }
3168
+ /** Whether an account exists on-ledger. */
3169
+ async accountExists(publicKey) {
3170
+ try {
3171
+ await this.horizon().loadAccount(publicKey);
3172
+ return true;
3173
+ } catch {
3174
+ return false;
3175
+ }
3176
+ }
3177
+ /**
3178
+ * Send a native XLM transfer. Uses `createAccount` when the destination does
3179
+ * not exist yet (stealth accounts), otherwise a `payment`. Signs via the
3180
+ * provided signer and submits through Horizon.
3181
+ */
3182
+ async sendNativeTransfer(opts) {
3183
+ const source = await opts.signer.publicKey();
3184
+ const horizon = this.horizon();
3185
+ const sourceAccount = await horizon.loadAccount(source);
3186
+ const destExists = await this.accountExists(opts.destination);
3187
+ const amount = formatStroopsToXlm(opts.amountStroops);
3188
+ if (!destExists && opts.amountStroops < NEW_ACCOUNT_MIN_RESERVE_STROOPS) {
3189
+ throw new RpcError(
3190
+ "Destination account does not exist; create-account requires at least 1 XLM."
3191
+ );
3192
+ }
3193
+ const op = destExists ? Operation.payment({ destination: opts.destination, asset: Asset.native(), amount }) : Operation.createAccount({ destination: opts.destination, startingBalance: amount });
3194
+ const tx = new TransactionBuilder(sourceAccount, {
3195
+ fee: BASE_FEE,
3196
+ networkPassphrase: this.config.passphrase
3197
+ }).addOperation(op).setTimeout(180).build();
3198
+ const signedXdr = await opts.signer.signTransaction(tx.toXDR(), {
3199
+ networkPassphrase: this.config.passphrase
3200
+ });
3201
+ const signed = TransactionBuilder.fromXDR(signedXdr, this.config.passphrase);
3202
+ const result = await horizon.submitTransaction(
3203
+ signed
3204
+ );
3205
+ return result.hash;
3206
+ }
3207
+ /** Run a read across providers with retry + timeout; throws RpcError on exhaustion. */
3208
+ async read(fn, label) {
3209
+ let lastError;
3210
+ for (const server of this.servers) {
3211
+ for (let attempt = 0; attempt < READ_RETRIES_PER_PROVIDER; attempt += 1) {
3212
+ try {
3213
+ return await withTimeout(fn(server), label);
3214
+ } catch (err) {
3215
+ lastError = err;
3216
+ if (!isRetryableReadError(err)) throw err;
3217
+ if (attempt + 1 < READ_RETRIES_PER_PROVIDER) await sleep(350 * (attempt + 1));
3218
+ }
3219
+ }
3220
+ }
3221
+ throw lastError instanceof Error ? new RpcError(`${label} failed: ${lastError.message}`, { cause: lastError }) : new RpcError(`${label} failed`);
3222
+ }
3223
+ async poll(txHash) {
3224
+ const start = Date.now();
3225
+ while (Date.now() - start < TX_POLL_TIMEOUT_MS) {
3226
+ const res = await this.server.getTransaction(txHash);
3227
+ if (res.status !== "NOT_FOUND") return res;
3228
+ await sleep(TX_POLL_INTERVAL_MS);
3229
+ }
3230
+ throw new RpcError(`Transaction polling timed out for ${txHash}`);
3231
+ }
3232
+ /** Fetch contract events (paged) with read fallback. */
3233
+ async getEvents(request) {
3234
+ return this.read((s) => s.getEvents(request), "getEvents");
3235
+ }
3236
+ /** Latest ledger sequence. */
3237
+ async getLatestLedger() {
3238
+ const res = await this.read((s) => s.getLatestLedger(), "getLatestLedger");
3239
+ return res.sequence;
3240
+ }
3241
+ /** Read-only contract call via simulation. Returns the decoded return ScVal. */
3242
+ async simulateRead(opts) {
3243
+ const account = await this.read(
3244
+ (s) => s.getAccount(opts.source),
3245
+ "getAccount"
3246
+ );
3247
+ const tx = new TransactionBuilder(account, {
3248
+ fee: BASE_FEE,
3249
+ networkPassphrase: this.config.passphrase
3250
+ }).addOperation(new Contract(opts.contractId).call(opts.method, ...opts.args)).setTimeout(60).build();
3251
+ const sim = await this.read(
3252
+ (s) => s.simulateTransaction(tx),
3253
+ `simulate ${opts.method}`
3254
+ );
3255
+ if (rpc.Api.isSimulationError(sim)) {
3256
+ throw new SimulationError(`Simulation failed for ${opts.method}`, {
3257
+ diagnostics: sim.error
3258
+ });
3259
+ }
3260
+ return sim.result?.retval;
3261
+ }
3262
+ /** Read-only contract call returning the native-decoded value. */
3263
+ async readNative(opts) {
3264
+ const retval = await this.simulateRead(opts);
3265
+ return retval ? scValToNative(retval) : void 0;
3266
+ }
3267
+ /** Invoke a contract method as a signed transaction. Returns the tx hash. */
3268
+ async invoke(opts) {
3269
+ const start = Date.now();
3270
+ try {
3271
+ const account = await this.read(
3272
+ (s) => s.getAccount(opts.source),
3273
+ "getAccount"
3274
+ );
3275
+ const raw = new TransactionBuilder(account, {
3276
+ fee: BASE_FEE,
3277
+ networkPassphrase: this.config.passphrase
3278
+ }).addOperation(new Contract(opts.contractId).call(opts.method, ...opts.args)).setTimeout(180).build();
3279
+ let prepared = raw;
3280
+ if (!opts.skipSimulation) {
3281
+ const sim = await this.server.simulateTransaction(raw);
3282
+ if (rpc.Api.isSimulationError(sim)) {
3283
+ throw new SimulationError(`Simulation failed for ${opts.method}`, {
3284
+ diagnostics: sim.error
3285
+ });
3286
+ }
3287
+ prepared = rpc.assembleTransaction(raw, sim).build();
3288
+ } else {
3289
+ prepared = await this.server.prepareTransaction(raw);
3290
+ }
3291
+ const signedXdr = await opts.signer.signTransaction(prepared.toXDR(), {
3292
+ networkPassphrase: this.config.passphrase
3293
+ });
3294
+ const signed = TransactionBuilder.fromXDR(signedXdr, this.config.passphrase);
3295
+ const send = await this.server.sendTransaction(
3296
+ signed
3297
+ );
3298
+ if (send.status === "ERROR") {
3299
+ throw new RpcError(`sendTransaction rejected: ${JSON.stringify(send.errorResult)}`);
3300
+ }
3301
+ const result = await this.poll(send.hash);
3302
+ if (result.status !== "SUCCESS") {
3303
+ throw this.toContractError(opts, result);
3304
+ }
3305
+ this.telemetry.onContractCall?.({
3306
+ contractId: opts.contractId,
3307
+ method: opts.method,
3308
+ success: true,
3309
+ durationMs: Date.now() - start
3310
+ });
3311
+ return send.hash;
3312
+ } catch (err) {
3313
+ this.telemetry.onContractCall?.({
3314
+ contractId: opts.contractId,
3315
+ method: opts.method,
3316
+ success: false,
3317
+ durationMs: Date.now() - start,
3318
+ error: err instanceof Error ? err.message : String(err)
3319
+ });
3320
+ throw err;
3321
+ }
3322
+ }
3323
+ toContractError(opts, result) {
3324
+ const events = result.diagnosticEventsXdr ?? [];
3325
+ const diagnostics = events.length ? decodeDiagnostics(events) : "";
3326
+ const code = events.length ? extractContractErrorCode(events) : null;
3327
+ if (code !== null) {
3328
+ return new ContractError({
3329
+ contract: opts.contractPackage ?? opts.contractId,
3330
+ contractCode: code,
3331
+ errorName: opts.contractPackage ? contractErrorName(opts.contractPackage, code) : void 0
3332
+ });
3333
+ }
3334
+ this.logger.error(`tx ${result.status}`, diagnostics);
3335
+ return new RpcError(
3336
+ `Transaction ${result.status}` + (diagnostics ? `: ${diagnostics}` : "")
3337
+ );
3338
+ }
3339
+ };
3340
+
3341
+ // src/contracts/payments.ts
3342
+ var SCHEME_ID_SECP256K1 = 1n;
3343
+ var StealthRegistry = class {
3344
+ constructor(rpc2, contractId) {
3345
+ this.rpc = rpc2;
3346
+ this.contractId = contractId;
3347
+ }
3348
+ rpc;
3349
+ contractId;
3350
+ /** Register a stealth meta-address for the signer's account. */
3351
+ async registerKeys(opts) {
3352
+ const source = await opts.signer.publicKey();
3353
+ return this.rpc.invoke({
3354
+ source,
3355
+ contractId: this.contractId,
3356
+ method: "register_keys",
3357
+ contractPackage: "stealth-registry",
3358
+ args: [
3359
+ addressToScVal(source),
3360
+ u64ToScVal(opts.schemeId ?? SCHEME_ID_SECP256K1),
3361
+ bytesToScVal(opts.stealthMetaAddress)
3362
+ ],
3363
+ signer: opts.signer
3364
+ });
3365
+ }
3366
+ };
3367
+ var StealthAnnouncer = class {
3368
+ constructor(rpc2, contractId) {
3369
+ this.rpc = rpc2;
3370
+ this.contractId = contractId;
3371
+ }
3372
+ rpc;
3373
+ contractId;
3374
+ /** Announce a one-time stealth transfer (stealth id + ephemeral key + view tag). */
3375
+ async announce(opts) {
3376
+ const source = await opts.signer.publicKey();
3377
+ return this.rpc.invoke({
3378
+ source,
3379
+ contractId: this.contractId,
3380
+ method: "announce",
3381
+ contractPackage: "stealth-announcer",
3382
+ args: [
3383
+ addressToScVal(source),
3384
+ u64ToScVal(opts.schemeId ?? SCHEME_ID_SECP256K1),
3385
+ bytesToScVal(opts.stealthAddress),
3386
+ bytesToScVal(opts.ephemeralPubKey),
3387
+ bytesToScVal(opts.metadata)
3388
+ ],
3389
+ signer: opts.signer
3390
+ });
3391
+ }
3392
+ };
3393
+ var SchemaRegistry = class {
3394
+ constructor(rpc2, contractId) {
3395
+ this.rpc = rpc2;
3396
+ this.contractId = contractId;
3397
+ }
3398
+ rpc;
3399
+ contractId;
3400
+ /** Register a schema. The signer is the schema authority. */
3401
+ async registerSchema(opts) {
3402
+ const authority = await opts.signer.publicKey();
3403
+ const authorityKey = StrKey.decodeEd25519PublicKey(authority);
3404
+ return this.rpc.invoke({
3405
+ source: authority,
3406
+ contractId: this.contractId,
3407
+ method: "register_schema",
3408
+ contractPackage: "schema-registry",
3409
+ args: [
3410
+ addressToScVal(authority),
3411
+ nativeToScVal(Buffer.from(authorityKey), { type: "bytes" }),
3412
+ bytesToScVal(opts.schemaId),
3413
+ stringToScVal(opts.name),
3414
+ stringToScVal(opts.fieldDefinitions),
3415
+ boolToScVal(opts.revocable),
3416
+ u32ToScVal(opts.version ?? 1),
3417
+ optionAddressToScVal(opts.resolver ?? null),
3418
+ u32ToScVal(opts.schemaExpiryLedger)
3419
+ ],
3420
+ signer: opts.signer
3421
+ });
3422
+ }
3423
+ async deprecateSchema(opts) {
3424
+ const authority = await opts.signer.publicKey();
3425
+ return this.rpc.invoke({
3426
+ source: authority,
3427
+ contractId: this.contractId,
3428
+ method: "deprecate_schema",
3429
+ contractPackage: "schema-registry",
3430
+ args: [addressToScVal(authority), bytesToScVal(opts.schemaId)],
3431
+ signer: opts.signer
3432
+ });
3433
+ }
3434
+ async addDelegate(opts) {
3435
+ this.assertDelegate(opts.delegate);
3436
+ const authority = await opts.signer.publicKey();
3437
+ return this.rpc.invoke({
3438
+ source: authority,
3439
+ contractId: this.contractId,
3440
+ method: "add_delegate",
3441
+ contractPackage: "schema-registry",
3442
+ args: [
3443
+ addressToScVal(authority),
3444
+ bytesToScVal(opts.schemaId),
3445
+ addressToScVal(opts.delegate)
3446
+ ],
3447
+ signer: opts.signer
3448
+ });
3449
+ }
3450
+ async removeDelegate(opts) {
3451
+ this.assertDelegate(opts.delegate);
3452
+ const authority = await opts.signer.publicKey();
3453
+ return this.rpc.invoke({
3454
+ source: authority,
3455
+ contractId: this.contractId,
3456
+ method: "remove_delegate",
3457
+ contractPackage: "schema-registry",
3458
+ args: [
3459
+ addressToScVal(authority),
3460
+ bytesToScVal(opts.schemaId),
3461
+ addressToScVal(opts.delegate)
3462
+ ],
3463
+ signer: opts.signer
3464
+ });
3465
+ }
3466
+ assertDelegate(delegate) {
3467
+ if (!StrKey.isValidEd25519PublicKey(delegate)) {
3468
+ throw new Error("Delegate must be a valid Stellar account address (G...).");
3469
+ }
3470
+ }
3471
+ };
3472
+ var AttestationEngine = class {
3473
+ constructor(rpc2, contractId) {
3474
+ this.rpc = rpc2;
3475
+ this.contractId = contractId;
3476
+ }
3477
+ rpc;
3478
+ contractId;
3479
+ /** Attest to a stealth identity under a schema. The signer is the issuer. */
3480
+ async attest(opts) {
3481
+ const issuer = await opts.signer.publicKey();
3482
+ return this.rpc.invoke({
3483
+ source: issuer,
3484
+ contractId: this.contractId,
3485
+ method: "attest",
3486
+ contractPackage: "attestation-engine-v2",
3487
+ args: [
3488
+ addressToScVal(issuer),
3489
+ bytesToScVal(opts.schemaId),
3490
+ bytesToScVal(opts.stealthAddressHash),
3491
+ bytesToScVal(opts.data),
3492
+ u32ToScVal(opts.expirationLedger),
3493
+ bytesToScVal(opts.refUid)
3494
+ ],
3495
+ signer: opts.signer
3496
+ });
3497
+ }
3498
+ async revokeAttestation(opts) {
3499
+ const revoker = await opts.signer.publicKey();
3500
+ return this.rpc.invoke({
3501
+ source: revoker,
3502
+ contractId: this.contractId,
3503
+ method: "revoke_attestation",
3504
+ contractPackage: "attestation-engine-v2",
3505
+ args: [addressToScVal(revoker), bytesToScVal(opts.uid)],
3506
+ signer: opts.signer
3507
+ });
3508
+ }
3509
+ };
3510
+ var Groth16Verifier = class {
3511
+ constructor(rpc2, contractId) {
3512
+ this.rpc = rpc2;
3513
+ this.contractId = contractId;
3514
+ }
3515
+ rpc;
3516
+ contractId;
3517
+ /** Submit a Groth16 V2 proof. The public signals are passed as an ScMap. */
3518
+ async verifyProofV2(opts) {
3519
+ const source = await opts.signer.publicKey();
3520
+ return this.rpc.invoke({
3521
+ source,
3522
+ contractId: this.contractId,
3523
+ method: "verify_proof_v2",
3524
+ contractPackage: "groth16-verifier",
3525
+ args: [
3526
+ bytesToScVal(opts.proofA),
3527
+ bytesToScVal(opts.proofB),
3528
+ bytesToScVal(opts.proofC),
3529
+ nativeToScVal(
3530
+ {
3531
+ merkle_root: Buffer.from(opts.merkleRoot),
3532
+ attestation_id: Buffer.from(opts.attestationId),
3533
+ external_nullifier: Buffer.from(opts.externalNullifier),
3534
+ nullifier_hash: Buffer.from(opts.nullifierHash)
3535
+ },
3536
+ { type: "map" }
3537
+ )
3538
+ ],
3539
+ signer: opts.signer
3540
+ });
3541
+ }
3542
+ };
3543
+ var ReputationVerifier = class {
3544
+ constructor(rpc2, contractId) {
3545
+ this.rpc = rpc2;
3546
+ this.contractId = contractId;
3547
+ }
3548
+ rpc;
3549
+ contractId;
3550
+ /** Submit a V2 reputation proof for on-chain verification. */
3551
+ async verifyReputation(opts) {
3552
+ const caller = await opts.signer.publicKey();
3553
+ return this.rpc.invoke({
3554
+ source: caller,
3555
+ contractId: this.contractId,
3556
+ method: "verify_reputation",
3557
+ contractPackage: "reputation-verifier",
3558
+ args: [
3559
+ addressToScVal(caller),
3560
+ addressToScVal(opts.groth16VerifierId),
3561
+ bytesToScVal(opts.proofA),
3562
+ bytesToScVal(opts.proofB),
3563
+ bytesToScVal(opts.proofC),
3564
+ bytesToScVal(opts.merkleRoot),
3565
+ bytesToScVal(opts.attestationId),
3566
+ u64ToScVal(opts.externalNullifier),
3567
+ bytesToScVal(opts.nullifierHash),
3568
+ u32ToScVal(opts.expirationLedger ?? 0)
3569
+ ],
3570
+ signer: opts.signer
3571
+ });
3572
+ }
3573
+ /** Read the latest published reputation Merkle root (bytes), or null if none. */
3574
+ async getLatestRoot(source) {
3575
+ const root = await this.rpc.readNative({
3576
+ source,
3577
+ contractId: this.contractId,
3578
+ method: "get_latest_root",
3579
+ args: []
3580
+ });
3581
+ if (!root) return null;
3582
+ const bytes = Uint8Array.from(root);
3583
+ return bytes.every((b) => b === 0) ? null : bytes;
3584
+ }
3585
+ };
3586
+ var POOL_EVENT_LOOKBACK = 16e3;
3587
+ function parseOldestLedgerFromRangeError(err) {
3588
+ const msg = err instanceof Error ? err.message : typeof err === "string" ? err : typeof err?.message === "string" ? err.message : "";
3589
+ const m = /ledger range:\s*(\d+)\s*-\s*(\d+)/.exec(msg);
3590
+ return m ? Number(m[1]) : null;
3591
+ }
3592
+ var PrivacyPool = class {
3593
+ constructor(rpc2, contractId) {
3594
+ this.rpc = rpc2;
3595
+ this.contractId = contractId;
3596
+ }
3597
+ rpc;
3598
+ contractId;
3599
+ /** Deposit `value` stroops under a precomputed commitment at `expectedIndex`. */
3600
+ async deposit(opts) {
3601
+ const depositor = await opts.signer.publicKey();
3602
+ return this.rpc.invoke({
3603
+ source: depositor,
3604
+ contractId: this.contractId,
3605
+ method: "deposit",
3606
+ contractPackage: "privacy-pool",
3607
+ args: [
3608
+ addressToScVal(depositor),
3609
+ i128ToScVal(opts.value),
3610
+ bytesToScVal(opts.commitment),
3611
+ u64ToScVal(BigInt(opts.expectedIndex))
3612
+ ],
3613
+ signer: opts.signer
3614
+ });
3615
+ }
3616
+ /** Withdraw to `recipient` (minus `fee` to `relayer`) with a v3 proof. */
3617
+ async withdraw(opts) {
3618
+ const caller = await opts.signer.publicKey();
3619
+ return this.rpc.invoke({
3620
+ source: caller,
3621
+ contractId: this.contractId,
3622
+ method: "withdraw",
3623
+ contractPackage: "privacy-pool",
3624
+ args: [
3625
+ bytesToScVal(opts.proofA),
3626
+ bytesToScVal(opts.proofB),
3627
+ bytesToScVal(opts.proofC),
3628
+ i128ToScVal(opts.withdrawnValue),
3629
+ bytesToScVal(opts.stateRoot),
3630
+ bytesToScVal(opts.aspRoot),
3631
+ bytesToScVal(opts.nullifierHash),
3632
+ bytesToScVal(opts.newCommitment),
3633
+ addressToScVal(opts.recipient),
3634
+ i128ToScVal(opts.fee),
3635
+ addressToScVal(opts.relayer)
3636
+ ],
3637
+ signer: opts.signer
3638
+ });
3639
+ }
3640
+ /** Publish a tree root (admin only). `kind` selects the state vs ASP root. */
3641
+ async updateRoot(opts) {
3642
+ const admin = await opts.signer.publicKey();
3643
+ return this.rpc.invoke({
3644
+ source: admin,
3645
+ contractId: this.contractId,
3646
+ method: opts.kind === "state" ? "update_state_root" : "update_asp_root",
3647
+ contractPackage: "privacy-pool",
3648
+ args: [
3649
+ addressToScVal(admin),
3650
+ bytesToScVal(opts.root),
3651
+ bytesToScVal(opts.datasetHash)
3652
+ ],
3653
+ signer: opts.signer
3654
+ });
3655
+ }
3656
+ /** Read the next deposit leaf index (the value `deposit` will assign). */
3657
+ async getDepositCount(source) {
3658
+ const count = await this.rpc.readNative({
3659
+ source,
3660
+ contractId: this.contractId,
3661
+ method: "get_deposit_count",
3662
+ args: []
3663
+ });
3664
+ return Number(count);
3665
+ }
3666
+ /** Read the latest published state (or ASP) root, or null if none. */
3667
+ async getLatestRoot(opts) {
3668
+ const root = await this.rpc.readNative({
3669
+ source: opts.source,
3670
+ contractId: this.contractId,
3671
+ method: "get_latest_root",
3672
+ args: [boolToScVal(opts.kind === "state")]
3673
+ });
3674
+ return root ? Uint8Array.from(root) : null;
3675
+ }
3676
+ /**
3677
+ * Reconstruct the pool's commitment leaves from on-chain events. Returns the
3678
+ * commitment at each state-tree index (`stateLeaves`, deposits + withdrawal
3679
+ * remainders) and the state index of each deposit in event order
3680
+ * (`depositIndices`, == ASP-tree order). Feed these into the withdrawal prover.
3681
+ */
3682
+ async reconstructState(opts) {
3683
+ const latest = await this.rpc.getLatestLedger();
3684
+ let startLedger = opts?.startLedger && opts.startLedger > 0 ? opts.startLedger : Math.max(1, latest - POOL_EVENT_LOOKBACK);
3685
+ const depositTopic = xdr.ScVal.scvSymbol("Deposit").toXDR("base64");
3686
+ const withdrawTopic = xdr.ScVal.scvSymbol("Withdraw").toXDR("base64");
3687
+ const byIndex = /* @__PURE__ */ new Map();
3688
+ const depositIndices = [];
3689
+ for (const [topic, isDeposit] of [
3690
+ [depositTopic, true],
3691
+ [withdrawTopic, false]
3692
+ ]) {
3693
+ let cursor;
3694
+ let prevCursor;
3695
+ const filters = [
3696
+ { type: "contract", contractIds: [this.contractId], topics: [[topic, "*"]] }
3697
+ ];
3698
+ for (let page = 0; page < 200; page++) {
3699
+ let res;
3700
+ try {
3701
+ res = await this.rpc.getEvents(
3702
+ cursor ? { cursor, filters, limit: 100 } : { startLedger, filters, limit: 100 }
3703
+ );
3704
+ } catch (err) {
3705
+ const oldest = parseOldestLedgerFromRangeError(err);
3706
+ if (!cursor && oldest != null && startLedger < oldest) {
3707
+ startLedger = oldest;
3708
+ res = await this.rpc.getEvents({ startLedger, filters, limit: 100 });
3709
+ } else {
3710
+ throw err;
3711
+ }
3712
+ }
3713
+ for (const ev of res.events ?? []) {
3714
+ const data = scValToNative(ev.value);
3715
+ if (isDeposit) {
3716
+ const commitment = BigInt(
3717
+ "0x" + Buffer.from(data[0]).toString("hex")
3718
+ );
3719
+ const index = Number(data[1]);
3720
+ byIndex.set(index, commitment);
3721
+ depositIndices.push(index);
3722
+ } else {
3723
+ const newCommitment = BigInt(
3724
+ "0x" + Buffer.from(data[1]).toString("hex")
3725
+ );
3726
+ byIndex.set(Number(data[2]), newCommitment);
3727
+ }
3728
+ }
3729
+ cursor = res.cursor;
3730
+ if (!cursor || cursor === prevCursor) break;
3731
+ prevCursor = cursor;
3732
+ }
3733
+ }
3734
+ const max = byIndex.size === 0 ? -1 : Math.max(...byIndex.keys());
3735
+ const stateLeaves = [];
3736
+ for (let i = 0; i <= max; i++) stateLeaves.push(byIndex.get(i) ?? 0n);
3737
+ depositIndices.sort((a, b) => a - b);
3738
+ return { stateLeaves, depositIndices };
3739
+ }
3740
+ };
3741
+
3742
+ // src/contracts/relayer.ts
3743
+ var RelayerRegistry = class {
3744
+ constructor(rpc2, contractId) {
3745
+ this.rpc = rpc2;
3746
+ this.contractId = contractId;
3747
+ }
3748
+ rpc;
3749
+ contractId;
3750
+ /** Create a blind job with an escrowed fee and a payload hash + deadline. */
3751
+ async createJob(opts) {
3752
+ const creator = await opts.signer.publicKey();
3753
+ return this.rpc.invoke({
3754
+ source: creator,
3755
+ contractId: this.contractId,
3756
+ method: "create_job",
3757
+ contractPackage: "relayer-registry",
3758
+ args: [
3759
+ addressToScVal(creator),
3760
+ bytesToScVal(opts.jobId),
3761
+ bytesToScVal(opts.payloadHash),
3762
+ u32ToScVal(opts.deadlineLedger),
3763
+ i128ToScVal(opts.fee)
3764
+ ],
3765
+ signer: opts.signer
3766
+ });
3767
+ }
3768
+ /** Cancel a never-accepted job after its deadline; refunds the escrow fee. */
3769
+ async cancelJob(opts) {
3770
+ return this.jobAction("cancel_job", opts);
3771
+ }
3772
+ /** Slash an accepted-but-unsubmitted job after its deadline. */
3773
+ async slashJob(opts) {
3774
+ return this.jobAction("slash_job", opts);
3775
+ }
3776
+ async jobAction(method, opts) {
3777
+ const creator = await opts.signer.publicKey();
3778
+ return this.rpc.invoke({
3779
+ source: creator,
3780
+ contractId: this.contractId,
3781
+ method,
3782
+ contractPackage: "relayer-registry",
3783
+ args: [addressToScVal(creator), bytesToScVal(opts.jobId)],
3784
+ signer: opts.signer
3785
+ });
3786
+ }
3787
+ };
3788
+
3789
+ // src/storage/index.ts
3790
+ var MemoryNoteStore = class {
3791
+ notes = /* @__PURE__ */ new Map();
3792
+ async list() {
3793
+ return [...this.notes.values()];
3794
+ }
3795
+ async add(note) {
3796
+ this.notes.set(note.commitment, note);
3797
+ }
3798
+ async markSpent(commitment) {
3799
+ const note = this.notes.get(commitment);
3800
+ if (note) this.notes.set(commitment, { ...note, spent: true });
3801
+ }
3802
+ };
3803
+ var MemoryVaultStore = class {
3804
+ entries = /* @__PURE__ */ new Map();
3805
+ async listGhosts() {
3806
+ return [...this.entries.values()];
3807
+ }
3808
+ async saveGhost(entry) {
3809
+ this.entries.set(entry.stealthAddress, entry);
3810
+ }
3811
+ };
3812
+ var MemoryScanStore = class {
3813
+ cursor = null;
3814
+ async getCursor() {
3815
+ return this.cursor;
3816
+ }
3817
+ async setCursor(ledger) {
3818
+ this.cursor = ledger;
3819
+ }
3820
+ };
3821
+
3822
+ // src/artifacts/index.ts
3823
+ var DEFAULT_ARTIFACT_PATHS = {
3824
+ "reputation-v2": {
3825
+ wasm: "circuits/v2/stealth_reputation.wasm",
3826
+ zkey: "circuits/v2/stealth_reputation_final.zkey"
3827
+ },
3828
+ "pool-v3": {
3829
+ wasm: "circuits/v3/privacy_pool_withdraw.wasm",
3830
+ zkey: "circuits/v3/privacy_pool_withdraw_final.zkey"
3831
+ }
3832
+ };
3833
+ function urlArtifactResolver(opts) {
3834
+ const base = opts.baseUrl.replace(/\/+$/, "");
3835
+ return {
3836
+ async resolve(id, kind) {
3837
+ const path = opts.paths?.[id]?.[kind] ?? DEFAULT_ARTIFACT_PATHS[id]?.[kind];
3838
+ if (!path) {
3839
+ throw new ArtifactError(`No artifact path for ${id}/${kind}`);
3840
+ }
3841
+ return `${base}/${path.replace(/^\/+/, "")}`;
3842
+ }
3843
+ };
3844
+ }
3845
+ function fileArtifactResolver(opts) {
3846
+ const base = opts.baseDir.replace(/\/+$/, "");
3847
+ return {
3848
+ async resolve(id, kind) {
3849
+ const path = opts.paths?.[id]?.[kind] ?? DEFAULT_ARTIFACT_PATHS[id]?.[kind];
3850
+ if (!path) {
3851
+ throw new ArtifactError(`No artifact path for ${id}/${kind}`);
3852
+ }
3853
+ return `${base}/${path.replace(/^\/+/, "")}`;
3854
+ }
3855
+ };
3856
+ }
3857
+
3858
+ // src/prove/serialize.ts
3859
+ function serializeGroth16Proof(proof) {
3860
+ const a = new Uint8Array(64);
3861
+ a.set(bigIntToBytes32(BigInt(proof.pi_a[0])), 0);
3862
+ a.set(bigIntToBytes32(BigInt(proof.pi_a[1])), 32);
3863
+ const flat = proof.pi_b.slice(0, 2).flatMap((pair) => [BigInt(pair[1]), BigInt(pair[0])]);
3864
+ const b = new Uint8Array(128);
3865
+ for (let i = 0; i < 4; i++) b.set(bigIntToBytes32(flat[i]), i * 32);
3866
+ const c = new Uint8Array(64);
3867
+ c.set(bigIntToBytes32(BigInt(proof.pi_c[0])), 0);
3868
+ c.set(bigIntToBytes32(BigInt(proof.pi_c[1])), 32);
3869
+ return { a, b, c };
3870
+ }
3871
+
3872
+ // src/prove/reputation.ts
3873
+ var TREE_DEPTH = 20;
3874
+ async function buildReputationWitnessV2(input) {
3875
+ const poseidon = await getPoseidon();
3876
+ const F = poseidon.F;
3877
+ const stealthPk = F.toObject(F.e(bytesToBigInt(input.stealthPrivKey)));
3878
+ const schemaId = BigInt(input.attestationId);
3879
+ const extNullifier = input.externalNullifier;
3880
+ const issuerPkX = F.toObject(poseidon([stealthPk, 1n]));
3881
+ const traitDataHash = F.toObject(poseidon([schemaId, 2n]));
3882
+ const nonce = F.toObject(poseidon([stealthPk, 3n]));
3883
+ const leaf = F.toObject(
3884
+ poseidon([stealthPk, schemaId, issuerPkX, traitDataHash, nonce])
3885
+ );
3886
+ const zeroHashes = [0n];
3887
+ for (let i = 0; i < TREE_DEPTH; i++) {
3888
+ zeroHashes.push(F.toObject(poseidon([zeroHashes[i], zeroHashes[i]])));
3889
+ }
3890
+ const merklePath = [];
3891
+ const merklePathIndices = [];
3892
+ let current = leaf;
3893
+ for (let i = 0; i < TREE_DEPTH; i++) {
3894
+ merklePath.push(zeroHashes[i].toString());
3895
+ merklePathIndices.push(0);
3896
+ current = F.toObject(poseidon([current, zeroHashes[i]]));
3897
+ }
3898
+ const merkleRoot = current;
3899
+ const nullifierHash = F.toObject(poseidon([stealthPk, extNullifier]));
3900
+ return {
3901
+ stealth_pk: stealthPk.toString(),
3902
+ schema_id: schemaId.toString(),
3903
+ issuer_pk_x: issuerPkX.toString(),
3904
+ trait_data_hash: traitDataHash.toString(),
3905
+ nonce: nonce.toString(),
3906
+ merkle_path: merklePath,
3907
+ merkle_path_indices: merklePathIndices,
3908
+ merkle_root: merkleRoot.toString(),
3909
+ attestation_id: schemaId.toString(),
3910
+ external_nullifier: extNullifier.toString(),
3911
+ nullifier_hash: nullifierHash.toString()
3912
+ };
3913
+ }
3914
+ async function loadSnarkjs() {
3915
+ try {
3916
+ return await import('snarkjs');
3917
+ } catch (cause) {
3918
+ throw new ArtifactError(
3919
+ "snarkjs is required for proof generation; install it as a peer dependency.",
3920
+ { cause }
3921
+ );
3922
+ }
3923
+ }
3924
+ async function proveReputationV2(opts) {
3925
+ const witness = await buildReputationWitnessV2(opts.input);
3926
+ const snarkjs = opts.snarkjs ?? await loadSnarkjs();
3927
+ const [wasm, zkey] = await Promise.all([
3928
+ opts.artifacts.resolve("reputation-v2", "wasm"),
3929
+ opts.artifacts.resolve("reputation-v2", "zkey")
3930
+ ]);
3931
+ const { proof, publicSignals } = await snarkjs.groth16.fullProve(
3932
+ witness,
3933
+ wasm,
3934
+ zkey
3935
+ );
3936
+ const { a, b, c } = serializeGroth16Proof(proof);
3937
+ return {
3938
+ proofA: a,
3939
+ proofB: b,
3940
+ proofC: c,
3941
+ merkleRoot: bigIntToBytes32(BigInt(publicSignals[0])),
3942
+ attestationId: bigIntToBytes32(BigInt(publicSignals[1])),
3943
+ externalNullifier: opts.input.externalNullifier,
3944
+ nullifierHash: bigIntToBytes32(BigInt(publicSignals[3])),
3945
+ publicSignals
3946
+ };
3947
+ }
3948
+ function beBytes(v, len) {
3949
+ const out = new Uint8Array(len);
3950
+ let n = v;
3951
+ for (let i = len - 1; i >= 0; i--) {
3952
+ out[i] = Number(n & 0xffn);
3953
+ n >>= 8n;
3954
+ }
3955
+ return out;
3956
+ }
3957
+ var PoolMerkleTree = class {
3958
+ constructor(poseidon, leaves, depth = POOL_TREE_DEPTH) {
3959
+ this.poseidon = poseidon;
3960
+ this.leaves = leaves;
3961
+ this.depth = depth;
3962
+ this.zero = [0n];
3963
+ for (let i = 0; i < depth; i++) {
3964
+ this.zero.push(hashFields(poseidon, [this.zero[i], this.zero[i]]));
3965
+ }
3966
+ }
3967
+ poseidon;
3968
+ leaves;
3969
+ depth;
3970
+ zero;
3971
+ rootFrom(start, level) {
3972
+ if (start >= this.leaves.length) return this.zero[level];
3973
+ if (level === 0) return this.leaves[start];
3974
+ const half = 1 << level - 1;
3975
+ const left = this.rootFrom(start, level - 1);
3976
+ const right = this.rootFrom(start + half, level - 1);
3977
+ return hashFields(this.poseidon, [left, right]);
3978
+ }
3979
+ root() {
3980
+ return this.rootFrom(0, this.depth);
3981
+ }
3982
+ node(index, level) {
3983
+ return this.rootFrom(index * (1 << level), level);
3984
+ }
3985
+ proof(index) {
3986
+ const siblings = [];
3987
+ const indices = [];
3988
+ let cur = index;
3989
+ for (let level = 0; level < this.depth; level++) {
3990
+ siblings.push(this.node(cur ^ 1, level));
3991
+ indices.push(cur & 1);
3992
+ cur >>= 1;
3993
+ }
3994
+ return { siblings, indices };
3995
+ }
3996
+ };
3997
+ function computeWithdrawContext(opts) {
3998
+ const recXdr = new Uint8Array(new Address(opts.recipient).toScVal().toXDR());
3999
+ const relXdr = new Uint8Array(new Address(opts.relayer).toScVal().toXDR());
4000
+ const parts = [
4001
+ recXdr,
4002
+ beBytes(opts.withdrawn, 16),
4003
+ beBytes(opts.fee, 16),
4004
+ relXdr,
4005
+ beBytes(BigInt(opts.scope), 8)
4006
+ ];
4007
+ const preimage = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
4008
+ let o = 0;
4009
+ for (const p of parts) {
4010
+ preimage.set(p, o);
4011
+ o += p.length;
4012
+ }
4013
+ let v = 0n;
4014
+ for (const b of keccak_256(preimage)) v = (v << 8n) + BigInt(b);
4015
+ return v % BN254_R;
4016
+ }
4017
+ async function loadSnarkjs2() {
4018
+ try {
4019
+ return await import('snarkjs');
4020
+ } catch (cause) {
4021
+ throw new ArtifactError(
4022
+ "snarkjs is required for proof generation; install it as a peer dependency.",
4023
+ { cause }
4024
+ );
4025
+ }
4026
+ }
4027
+ async function provePoolWithdraw(opts) {
4028
+ const { note } = opts;
4029
+ const value = BigInt(note.value);
4030
+ const withdrawnValue = value;
4031
+ const remainder = 0n;
4032
+ const poseidon = await getPoseidon();
4033
+ const h = (xs) => hashFields(poseidon, xs);
4034
+ const aspLeafIndex = opts.depositIndices.indexOf(note.leafIndex);
4035
+ if (aspLeafIndex < 0) {
4036
+ throw new Error(`Leaf #${note.leafIndex} is not among the pool's deposits.`);
4037
+ }
4038
+ const onChain = opts.stateLeaves[note.leafIndex];
4039
+ if (onChain != null && toHex32(onChain).toLowerCase() !== note.commitment.toLowerCase()) {
4040
+ throw new Error(`Leaf #${note.leafIndex} commitment does not match this note.`);
4041
+ }
4042
+ const label = h([BigInt(opts.scope), BigInt(note.leafIndex)]);
4043
+ const aspLeaves = opts.depositIndices.map((i) => h([BigInt(opts.scope), BigInt(i)]));
4044
+ const stateTree = new PoolMerkleTree(poseidon, opts.stateLeaves);
4045
+ const aspTree = new PoolMerkleTree(poseidon, aspLeaves);
4046
+ const statePath = stateTree.proof(note.leafIndex);
4047
+ const aspPath = aspTree.proof(aspLeafIndex);
4048
+ const change = newNoteSecrets();
4049
+ const newPrecommit = h([BigInt(change.nullifier), BigInt(change.secret)]);
4050
+ const newCommitment = h([remainder, label, newPrecommit]);
4051
+ const nullifierHash = h([BigInt(note.nullifier)]);
4052
+ const context = computeWithdrawContext({
4053
+ recipient: opts.recipient,
4054
+ withdrawn: withdrawnValue,
4055
+ fee: opts.fee,
4056
+ relayer: opts.relayer,
4057
+ scope: opts.scope
4058
+ });
4059
+ const input = {
4060
+ withdrawnValue: withdrawnValue.toString(),
4061
+ stateRoot: stateTree.root().toString(),
4062
+ aspRoot: aspTree.root().toString(),
4063
+ nullifierHash: nullifierHash.toString(),
4064
+ newCommitment: newCommitment.toString(),
4065
+ context: context.toString(),
4066
+ value: value.toString(),
4067
+ label: label.toString(),
4068
+ nullifier: note.nullifier,
4069
+ secret: note.secret,
4070
+ newNullifier: change.nullifier,
4071
+ newSecret: change.secret,
4072
+ stateSiblings: statePath.siblings.map((x) => x.toString()),
4073
+ stateIndex: statePath.indices.map((x) => x.toString()),
4074
+ aspSiblings: aspPath.siblings.map((x) => x.toString()),
4075
+ aspIndex: aspPath.indices.map((x) => x.toString())
4076
+ };
4077
+ const snarkjs = opts.snarkjs ?? await loadSnarkjs2();
4078
+ const [wasm, zkey] = await Promise.all([
4079
+ opts.artifacts.resolve("pool-v3", "wasm"),
4080
+ opts.artifacts.resolve("pool-v3", "zkey")
4081
+ ]);
4082
+ const { proof } = await snarkjs.groth16.fullProve(input, wasm, zkey);
4083
+ const { a, b, c } = serializeGroth16Proof(proof);
4084
+ return {
4085
+ proofA: a,
4086
+ proofB: b,
4087
+ proofC: c,
4088
+ withdrawnValue,
4089
+ stateRoot: bigIntToBytes32(stateTree.root()),
4090
+ aspRoot: bigIntToBytes32(aspTree.root()),
4091
+ nullifierHash: bigIntToBytes32(nullifierHash),
4092
+ newCommitment: bigIntToBytes32(newCommitment)
4093
+ };
4094
+ }
4095
+
4096
+ // src/relayer-protocol/bytes.ts
4097
+ function hexToBytes2(hex) {
4098
+ const clean = hex.replace(/^0x/, "");
4099
+ if (!/^[0-9a-f]*$/i.test(clean) || clean.length % 2 !== 0) {
4100
+ throw new Error("Invalid hex string.");
4101
+ }
4102
+ const out = new Uint8Array(clean.length / 2);
4103
+ for (let i = 0; i < out.length; i += 1) {
4104
+ out[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);
4105
+ }
4106
+ return out;
4107
+ }
4108
+ function bytesToHex2(bytes) {
4109
+ return `0x${Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
4110
+ }
4111
+ function base64ToBytes2(value) {
4112
+ if (typeof atob === "function") {
4113
+ const bin = atob(value);
4114
+ return Uint8Array.from(bin, (c) => c.charCodeAt(0));
4115
+ }
4116
+ const buffer = globalThis.Buffer;
4117
+ if (!buffer) throw new Error("No base64 decoder available.");
4118
+ return Uint8Array.from(buffer.from(value, "base64"));
4119
+ }
4120
+ function bytesToBase642(bytes) {
4121
+ if (typeof btoa === "function") {
4122
+ let bin = "";
4123
+ for (const b of bytes) bin += String.fromCharCode(b);
4124
+ return btoa(bin);
4125
+ }
4126
+ const buffer = globalThis.Buffer;
4127
+ if (!buffer) throw new Error("No base64 encoder available.");
4128
+ return buffer.from(bytes).toString("base64");
4129
+ }
4130
+ function concatBytes2(...chunks) {
4131
+ const len = chunks.reduce((n, c) => n + c.length, 0);
4132
+ const out = new Uint8Array(len);
4133
+ let offset = 0;
4134
+ for (const chunk of chunks) {
4135
+ out.set(chunk, offset);
4136
+ offset += chunk.length;
4137
+ }
4138
+ return out;
4139
+ }
4140
+ function assertLength(bytes, len, label) {
4141
+ if (bytes.length !== len) {
4142
+ throw new Error(`${label} must be ${len} bytes, got ${bytes.length}.`);
4143
+ }
4144
+ return bytes;
4145
+ }
4146
+ function i128ToBytes(value) {
4147
+ const min = -(1n << 127n);
4148
+ const max = (1n << 127n) - 1n;
4149
+ if (value < min || value > max) throw new Error("i128 out of range.");
4150
+ let unsigned = value;
4151
+ if (value < 0) unsigned = (1n << 128n) + value;
4152
+ const out = new Uint8Array(16);
4153
+ for (let i = 15; i >= 0; i -= 1) {
4154
+ out[i] = Number(unsigned & 0xffn);
4155
+ unsigned >>= 8n;
4156
+ }
4157
+ return out;
4158
+ }
4159
+
4160
+ // src/relayer-protocol/payload.ts
4161
+ var RELAY_PAYLOAD_DOMAIN = "opaque-stellar-relay-v1";
4162
+ var RELAY_CHAIN_STELLAR = 3e3;
4163
+ function utf8(value) {
4164
+ return new TextEncoder().encode(value);
4165
+ }
4166
+ function addressXdr(address) {
4167
+ return new Uint8Array(new Address(address).toScVal().toXDR());
4168
+ }
4169
+ function symbolXdr(symbol) {
4170
+ return new Uint8Array(xdr.ScVal.scvSymbol(symbol).toXDR());
4171
+ }
4172
+ function poolWithdrawPayloadPreimage(payload) {
4173
+ return concatBytes2(
4174
+ utf8(RELAY_PAYLOAD_DOMAIN),
4175
+ addressXdr(payload.poolId),
4176
+ symbolXdr("withdraw"),
4177
+ assertLength(payload.proofA, 64, "proofA"),
4178
+ assertLength(payload.proofB, 128, "proofB"),
4179
+ assertLength(payload.proofC, 64, "proofC"),
4180
+ i128ToBytes(payload.withdrawnValue),
4181
+ assertLength(payload.stateRoot, 32, "stateRoot"),
4182
+ assertLength(payload.aspRoot, 32, "aspRoot"),
4183
+ assertLength(payload.nullifierHash, 32, "nullifierHash"),
4184
+ assertLength(payload.newCommitment, 32, "newCommitment"),
4185
+ addressXdr(payload.recipient),
4186
+ i128ToBytes(payload.poolFee),
4187
+ addressXdr(payload.poolRelayer)
4188
+ );
4189
+ }
4190
+ function hashPoolWithdrawPayload(payload) {
4191
+ return keccak_256(poolWithdrawPayloadPreimage(payload));
4192
+ }
4193
+ function hashPoolWithdrawPayloadHex(payload) {
4194
+ return bytesToHex2(hashPoolWithdrawPayload(payload));
4195
+ }
4196
+ function serializePoolWithdrawPayload(payload) {
4197
+ return {
4198
+ poolId: payload.poolId,
4199
+ proofA: bytesToHex2(payload.proofA),
4200
+ proofB: bytesToHex2(payload.proofB),
4201
+ proofC: bytesToHex2(payload.proofC),
4202
+ withdrawnValue: payload.withdrawnValue.toString(),
4203
+ stateRoot: bytesToHex2(payload.stateRoot),
4204
+ aspRoot: bytesToHex2(payload.aspRoot),
4205
+ nullifierHash: bytesToHex2(payload.nullifierHash),
4206
+ newCommitment: bytesToHex2(payload.newCommitment),
4207
+ recipient: payload.recipient,
4208
+ poolFee: payload.poolFee.toString(),
4209
+ poolRelayer: payload.poolRelayer
4210
+ };
4211
+ }
4212
+ function parsePoolWithdrawPayload(payload) {
4213
+ return {
4214
+ poolId: payload.poolId,
4215
+ proofA: assertLength(hexToBytes2(payload.proofA), 64, "proofA"),
4216
+ proofB: assertLength(hexToBytes2(payload.proofB), 128, "proofB"),
4217
+ proofC: assertLength(hexToBytes2(payload.proofC), 64, "proofC"),
4218
+ withdrawnValue: BigInt(payload.withdrawnValue),
4219
+ stateRoot: assertLength(hexToBytes2(payload.stateRoot), 32, "stateRoot"),
4220
+ aspRoot: assertLength(hexToBytes2(payload.aspRoot), 32, "aspRoot"),
4221
+ nullifierHash: assertLength(hexToBytes2(payload.nullifierHash), 32, "nullifierHash"),
4222
+ newCommitment: assertLength(hexToBytes2(payload.newCommitment), 32, "newCommitment"),
4223
+ recipient: payload.recipient,
4224
+ poolFee: BigInt(payload.poolFee),
4225
+ poolRelayer: payload.poolRelayer
4226
+ };
4227
+ }
4228
+ function encodePoolWithdrawPayload(payload) {
4229
+ return utf8(
4230
+ JSON.stringify({ t: "pool-withdraw", v: 1, payload: serializePoolWithdrawPayload(payload) })
4231
+ );
4232
+ }
4233
+ function decodePoolWithdrawPayload(bytes) {
4234
+ const decoded = JSON.parse(new TextDecoder().decode(bytes));
4235
+ if (decoded.t !== "pool-withdraw" || decoded.v !== 1 || !decoded.payload) {
4236
+ throw new Error("Unsupported relayer payload.");
4237
+ }
4238
+ return parsePoolWithdrawPayload(decoded.payload);
4239
+ }
4240
+
4241
+ // src/relayer-protocol/box.ts
4242
+ var PUBLIC_KEY_BYTES = 32;
4243
+ var SECRET_KEY_BYTES = 32;
4244
+ var NONCE_BYTES = 24;
4245
+ function randomBytes(len) {
4246
+ const out = new Uint8Array(len);
4247
+ globalThis.crypto.getRandomValues(out);
4248
+ return out;
4249
+ }
4250
+ async function getNacl() {
4251
+ try {
4252
+ return (await import('tweetnacl')).default;
4253
+ } catch (cause) {
4254
+ throw new Error(
4255
+ "tweetnacl is required for relayer payload encryption; install it as a peer dependency.",
4256
+ { cause }
4257
+ );
4258
+ }
4259
+ }
4260
+ async function generateX25519Keypair(seed) {
4261
+ const nacl = await getNacl();
4262
+ if (seed) {
4263
+ const secretKey = assertLength(seed, SECRET_KEY_BYTES, "x25519 seed");
4264
+ const pair2 = nacl.box.keyPair.fromSecretKey(secretKey);
4265
+ return { publicKey: pair2.publicKey, secretKey: pair2.secretKey };
4266
+ }
4267
+ const pair = nacl.box.keyPair();
4268
+ return { publicKey: pair.publicKey, secretKey: pair.secretKey };
4269
+ }
4270
+ async function sealBox(plaintext, recipientPublicKey) {
4271
+ const nacl = await getNacl();
4272
+ const to = assertLength(recipientPublicKey, PUBLIC_KEY_BYTES, "recipient x25519 public key");
4273
+ const eph = nacl.box.keyPair();
4274
+ const nonce = randomBytes(NONCE_BYTES);
4275
+ const ciphertext = nacl.box(plaintext, nonce, to, eph.secretKey);
4276
+ return bytesToBase642(concatBytes2(eph.publicKey, nonce, ciphertext));
4277
+ }
4278
+ async function openBox(box, recipientSecretKey) {
4279
+ const nacl = await getNacl();
4280
+ const secret = assertLength(recipientSecretKey, SECRET_KEY_BYTES, "recipient x25519 secret key");
4281
+ const raw = base64ToBytes2(box);
4282
+ if (raw.length < PUBLIC_KEY_BYTES + NONCE_BYTES + nacl.box.overheadLength) {
4283
+ throw new Error("Encrypted payload is too short.");
4284
+ }
4285
+ const epk = raw.slice(0, PUBLIC_KEY_BYTES);
4286
+ const nonce = raw.slice(PUBLIC_KEY_BYTES, PUBLIC_KEY_BYTES + NONCE_BYTES);
4287
+ const ciphertext = raw.slice(PUBLIC_KEY_BYTES + NONCE_BYTES);
4288
+ const opened = nacl.box.open(ciphertext, nonce, epk, secret);
4289
+ if (!opened) throw new Error("Could not decrypt relayer payload.");
4290
+ return opened;
4291
+ }
4292
+ var BID_DOMAIN = new TextEncoder().encode("opaque-relayer-bid-v1");
4293
+ function makeAdvert(args) {
4294
+ return {
4295
+ t: "advert",
4296
+ v: 1,
4297
+ jobId: bytesToHex2(assertLength(args.jobId, 32, "jobId")),
4298
+ chain: args.chain ?? RELAY_CHAIN_STELLAR,
4299
+ fee: args.fee.toString(),
4300
+ deadline: args.deadline,
4301
+ payloadHash: bytesToHex2(assertLength(args.payloadHash, 32, "payloadHash"))
4302
+ };
4303
+ }
4304
+ function bidSigningDigest(jobId, x25519Pk) {
4305
+ return keccak_256(
4306
+ concatBytes2(
4307
+ BID_DOMAIN,
4308
+ assertLength(jobId, 32, "jobId"),
4309
+ assertLength(x25519Pk, 32, "x25519Pk")
4310
+ )
4311
+ );
4312
+ }
4313
+ function makeBid(args) {
4314
+ const x25519Pk = assertLength(args.x25519Pk, 32, "x25519Pk");
4315
+ const digest = bidSigningDigest(hexToBytes2(args.advert.jobId), x25519Pk);
4316
+ return {
4317
+ t: "bid",
4318
+ v: 1,
4319
+ jobId: args.advert.jobId,
4320
+ chain: args.advert.chain,
4321
+ operator: args.operator.publicKey(),
4322
+ x25519Pk: bytesToHex2(x25519Pk),
4323
+ sig: bytesToBase642(args.operator.sign(Buffer.from(digest))),
4324
+ endpoint: args.endpoint,
4325
+ freeStake: args.freeStake?.toString()
4326
+ };
4327
+ }
4328
+ function verifyBid(bid) {
4329
+ try {
4330
+ const digest = bidSigningDigest(hexToBytes2(bid.jobId), hexToBytes2(bid.x25519Pk));
4331
+ return Keypair.fromPublicKey(bid.operator).verify(
4332
+ Buffer.from(digest),
4333
+ Buffer.from(base64ToBytes2(bid.sig))
4334
+ );
4335
+ } catch {
4336
+ return false;
4337
+ }
4338
+ }
4339
+ function validateAdvert(value) {
4340
+ const v = value;
4341
+ if (v?.t !== "advert" || v.v !== 1 || typeof v.jobId !== "string" || typeof v.payloadHash !== "string" || typeof v.fee !== "string" || typeof v.deadline !== "number") {
4342
+ throw new Error("Invalid relayer advert.");
4343
+ }
4344
+ assertLength(hexToBytes2(v.jobId), 32, "jobId");
4345
+ assertLength(hexToBytes2(v.payloadHash), 32, "payloadHash");
4346
+ return { ...v, chain: v.chain ?? RELAY_CHAIN_STELLAR };
4347
+ }
4348
+ function validateBid(value) {
4349
+ const v = value;
4350
+ if (v?.t !== "bid" || v.v !== 1 || typeof v.jobId !== "string" || typeof v.operator !== "string" || typeof v.x25519Pk !== "string" || typeof v.sig !== "string") {
4351
+ throw new Error("Invalid relayer bid.");
4352
+ }
4353
+ assertLength(hexToBytes2(v.jobId), 32, "jobId");
4354
+ assertLength(hexToBytes2(v.x25519Pk), 32, "x25519Pk");
4355
+ return { ...v, chain: v.chain ?? RELAY_CHAIN_STELLAR };
4356
+ }
4357
+
4358
+ // src/relayer-protocol/gateway.ts
4359
+ var REGISTRY_JOB_STATUS = {
4360
+ 0: "open",
4361
+ 1: "accepted",
4362
+ 2: "submitted",
4363
+ 3: "slashed",
4364
+ 4: "canceled"
4365
+ };
4366
+ function randomJobId() {
4367
+ const out = new Uint8Array(32);
4368
+ globalThis.crypto.getRandomValues(out);
4369
+ return out;
4370
+ }
4371
+ function buildRelayedWithdrawPayload(args) {
4372
+ return {
4373
+ poolId: args.poolId,
4374
+ proofA: args.proof.proofA,
4375
+ proofB: args.proof.proofB,
4376
+ proofC: args.proof.proofC,
4377
+ withdrawnValue: args.proof.withdrawnValue,
4378
+ stateRoot: args.proof.stateRoot,
4379
+ aspRoot: args.proof.aspRoot,
4380
+ nullifierHash: args.proof.nullifierHash,
4381
+ newCommitment: args.proof.newCommitment,
4382
+ recipient: args.recipient,
4383
+ poolFee: 0n,
4384
+ poolRelayer: args.registryId
4385
+ };
4386
+ }
4387
+ function buildRelayerJobDraft(args) {
4388
+ const jobId = assertLength(args.jobId ?? randomJobId(), 32, "jobId");
4389
+ const payloadHash = hashPoolWithdrawPayload(args.payload);
4390
+ return {
4391
+ jobId,
4392
+ jobIdHex: bytesToHex2(jobId),
4393
+ payload: args.payload,
4394
+ payloadHash,
4395
+ payloadHashHex: bytesToHex2(payloadHash),
4396
+ advert: makeAdvert({ jobId, fee: args.fee, deadline: args.deadlineLedger, payloadHash }),
4397
+ deadlineLedger: args.deadlineLedger,
4398
+ fee: args.fee
4399
+ };
4400
+ }
4401
+ function pickStakeWeightedBid(bids) {
4402
+ if (bids.length === 0) return null;
4403
+ const total = bids.reduce((sum, bid) => sum + bid.freeStakeValue, 0n);
4404
+ if (total <= 0n) return bids[0];
4405
+ const rand = new Uint32Array(2);
4406
+ globalThis.crypto.getRandomValues(rand);
4407
+ let target = ((BigInt(rand[0]) << 32n) + BigInt(rand[1])) % total;
4408
+ for (const bid of bids) {
4409
+ if (target < bid.freeStakeValue) return bid;
4410
+ target -= bid.freeStakeValue;
4411
+ }
4412
+ return bids[bids.length - 1];
4413
+ }
4414
+ var RelayerGateway = class {
4415
+ gatewayUrls;
4416
+ registryId;
4417
+ invoker;
4418
+ constructor(opts) {
4419
+ if (opts.gatewayUrls.length === 0) {
4420
+ throw new Error("RelayerGateway requires at least one gateway URL.");
4421
+ }
4422
+ this.gatewayUrls = opts.gatewayUrls;
4423
+ this.registryId = opts.registryId;
4424
+ this.invoker = opts.invoker;
4425
+ }
4426
+ url(path, base = this.gatewayUrls[0]) {
4427
+ return new URL(path, base.endsWith("/") ? base : `${base}/`).toString();
4428
+ }
4429
+ /** A deadline `ledgers` ahead of the current ledger. */
4430
+ async deadlineLedger(ledgers = 720) {
4431
+ return await this.invoker.getLatestLedger() + ledgers;
4432
+ }
4433
+ async publishAdvert(advert, gateway = this.gatewayUrls[0]) {
4434
+ const res = await fetch(this.url("v1/jobs", gateway), {
4435
+ method: "POST",
4436
+ headers: { "content-type": "application/json" },
4437
+ body: JSON.stringify(advert)
4438
+ });
4439
+ if (!res.ok) throw new Error(`Relayer gateway rejected advert (${res.status}).`);
4440
+ }
4441
+ async fetchBids(jobIdHex, gateway = this.gatewayUrls[0]) {
4442
+ const res = await fetch(this.url(`v1/jobs/${encodeURIComponent(jobIdHex)}/bids`, gateway));
4443
+ if (!res.ok) throw new Error(`Could not fetch relayer bids (${res.status}).`);
4444
+ const body = await res.json();
4445
+ const signed = (body.bids ?? []).map((raw) => validateBid(raw)).filter((bid) => verifyBid(bid)).filter((bid) => bid.jobId.toLowerCase() === jobIdHex.toLowerCase()).filter((bid) => bid.chain === RELAY_CHAIN_STELLAR);
4446
+ const checked = await Promise.all(signed.map((bid) => this.verifyBidRegistryState(jobIdHex, bid)));
4447
+ return checked.filter((bid) => bid !== null);
4448
+ }
4449
+ async deliverPayload(args) {
4450
+ const box = await sealBox(
4451
+ encodePoolWithdrawPayload(args.draft.payload),
4452
+ hexToBytes2(args.bid.x25519Pk)
4453
+ );
4454
+ const res = await fetch(
4455
+ this.url(`v1/jobs/${encodeURIComponent(args.draft.jobIdHex)}/payload`, args.gateway ?? this.gatewayUrls[0]),
4456
+ {
4457
+ method: "POST",
4458
+ headers: { "content-type": "application/json" },
4459
+ body: JSON.stringify({ t: "payload", v: 1, jobId: args.draft.jobIdHex, to: args.bid.x25519Pk, box })
4460
+ }
4461
+ );
4462
+ if (!res.ok) throw new Error(`Relayer gateway rejected payload (${res.status}).`);
4463
+ const body = await res.json();
4464
+ return body.result ?? null;
4465
+ }
4466
+ async jobStatus(jobIdHex, source) {
4467
+ const job = await this.registryView(source, "get_job", [
4468
+ bytesToScVal(hexToBytes2(jobIdHex))
4469
+ ]);
4470
+ if (!job) return "unknown";
4471
+ return REGISTRY_JOB_STATUS[Number(job.status)] ?? "unknown";
4472
+ }
4473
+ async verifyBidRegistryState(jobIdHex, bid) {
4474
+ try {
4475
+ const [job, relayer] = await Promise.all([
4476
+ this.registryView(bid.operator, "get_job", [
4477
+ bytesToScVal(hexToBytes2(jobIdHex))
4478
+ ]),
4479
+ this.registryView(bid.operator, "get_relayer", [
4480
+ addressToScVal(bid.operator)
4481
+ ])
4482
+ ]);
4483
+ if (!job || !relayer) return null;
4484
+ const fee = BigInt(job.fee);
4485
+ const freeStakeValue = BigInt(relayer.free_stake);
4486
+ if (Number(job.status) !== 0 || freeStakeValue < fee) return null;
4487
+ const registeredPk = bytesToHex2(Uint8Array.from(relayer.x25519_pubkey));
4488
+ if (registeredPk.toLowerCase() !== bid.x25519Pk.toLowerCase()) return null;
4489
+ return {
4490
+ ...bid,
4491
+ endpoint: relayer.endpoint?.trim() || bid.endpoint,
4492
+ freeStake: freeStakeValue.toString(),
4493
+ freeStakeValue
4494
+ };
4495
+ } catch {
4496
+ return null;
4497
+ }
4498
+ }
4499
+ async registryView(source, method, args) {
4500
+ try {
4501
+ return await this.invoker.readNative({
4502
+ source,
4503
+ contractId: this.registryId,
4504
+ method,
4505
+ args
4506
+ });
4507
+ } catch {
4508
+ return null;
4509
+ }
4510
+ }
4511
+ };
4512
+
4513
+ // src/services/schemas.ts
4514
+ var SchemasService = class {
4515
+ constructor(ctx) {
4516
+ this.ctx = ctx;
4517
+ }
4518
+ ctx;
4519
+ /** Register a schema. The signer is the authority; returns the schema id. */
4520
+ async register(opts) {
4521
+ const signer = this.ctx.requireSigner();
4522
+ const authority = await signer.publicKey();
4523
+ const schemaId = await computeSchemaId(
4524
+ authority,
4525
+ opts.name,
4526
+ opts.fieldDefinitions,
4527
+ opts.version ?? 1
4528
+ );
4529
+ const txHash = await this.ctx.contracts.schemaRegistry.registerSchema({
4530
+ schemaId,
4531
+ name: opts.name,
4532
+ fieldDefinitions: opts.fieldDefinitions,
4533
+ revocable: opts.revocable,
4534
+ version: opts.version,
4535
+ resolver: opts.resolver ?? null,
4536
+ schemaExpiryLedger: opts.schemaExpiryLedger,
4537
+ signer
4538
+ });
4539
+ return { schemaId, txHash };
4540
+ }
4541
+ /** Attest to a stealth identity under a schema. The signer is the issuer. */
4542
+ async attest(opts) {
4543
+ const signer = this.ctx.requireSigner();
4544
+ const fields = parseFieldDefinitions(opts.fieldDefinitions);
4545
+ const data = encodeAttestationData(opts.fieldValues, fields);
4546
+ return this.ctx.contracts.attestationEngine.attest({
4547
+ schemaId: opts.schemaId,
4548
+ stealthAddressHash: opts.stealthAddressHash,
4549
+ data,
4550
+ expirationLedger: opts.expirationLedger,
4551
+ refUid: opts.refUid ?? new Uint8Array(32),
4552
+ signer
4553
+ });
4554
+ }
4555
+ async revoke(opts) {
4556
+ return this.ctx.contracts.attestationEngine.revokeAttestation({
4557
+ uid: opts.uid,
4558
+ signer: this.ctx.requireSigner()
4559
+ });
4560
+ }
4561
+ async deprecate(opts) {
4562
+ return this.ctx.contracts.schemaRegistry.deprecateSchema({
4563
+ schemaId: opts.schemaId,
4564
+ signer: this.ctx.requireSigner()
4565
+ });
4566
+ }
4567
+ async addDelegate(opts) {
4568
+ return this.ctx.contracts.schemaRegistry.addDelegate({
4569
+ ...opts,
4570
+ signer: this.ctx.requireSigner()
4571
+ });
4572
+ }
4573
+ async removeDelegate(opts) {
4574
+ return this.ctx.contracts.schemaRegistry.removeDelegate({
4575
+ ...opts,
4576
+ signer: this.ctx.requireSigner()
4577
+ });
4578
+ }
4579
+ };
4580
+
4581
+ // src/services/payments.ts
4582
+ var PaymentsService = class {
4583
+ constructor(ctx) {
4584
+ this.ctx = ctx;
4585
+ }
4586
+ ctx;
4587
+ /** Derive viewing/spending keys + meta-address from a wallet signature. */
4588
+ deriveIdentity(signatureHex) {
4589
+ const { viewingKey, spendingKey } = deriveKeysFromSignature(signatureHex);
4590
+ const { metaAddress } = keysToStealthMetaAddress(viewingKey, spendingKey);
4591
+ return {
4592
+ viewingKey,
4593
+ spendingKey,
4594
+ metaAddress,
4595
+ metaHex: stealthMetaAddressToHex(metaAddress)
4596
+ };
4597
+ }
4598
+ /** Register a stealth meta-address for the signer's account. */
4599
+ async register(opts) {
4600
+ return this.ctx.contracts.stealthRegistry.registerKeys({
4601
+ stealthMetaAddress: opts.metaAddress,
4602
+ signer: this.ctx.requireSigner()
4603
+ });
4604
+ }
4605
+ /** Pure: compute a one-time stealth address + announcement params for a recipient. */
4606
+ prepareTransfer(recipientMetaHex) {
4607
+ return computeStealthAddressAndViewTag(recipientMetaHex);
4608
+ }
4609
+ /**
4610
+ * Send a stealth XLM payment: pay the one-time stealth Stellar account, then
4611
+ * publish the announcement so the recipient can detect and sweep it.
4612
+ */
4613
+ async send(opts) {
4614
+ const signer = this.ctx.requireSigner();
4615
+ const stealth = computeStealthAddressAndViewTag(opts.to);
4616
+ const amountStroops = parseXlmToStroops(opts.amountXlm);
4617
+ const paymentTxHash = await this.ctx.sendNativeTransfer({
4618
+ destination: stealth.stealthStellarAddress,
4619
+ amountStroops,
4620
+ signer
4621
+ });
4622
+ const announceTxHash = await this.ctx.contracts.stealthAnnouncer.announce({
4623
+ stealthAddress: hexToBytes(stealth.stealthAddress),
4624
+ ephemeralPubKey: stealth.ephemeralPubKey,
4625
+ metadata: stealth.metadata,
4626
+ signer
4627
+ });
4628
+ return {
4629
+ stealthStellarAddress: stealth.stealthStellarAddress,
4630
+ ephemeralPubKey: stealth.ephemeralPubKey,
4631
+ paymentTxHash,
4632
+ announceTxHash
4633
+ };
4634
+ }
4635
+ /**
4636
+ * Sweep a detected stealth account to a destination. The stealth account signs
4637
+ * itself (derived from the one-time key), so the connected wallet is never the
4638
+ * source. `amountStroops` is the exact amount to move (compute the spendable
4639
+ * balance from Horizon, reserving fee + minimum balance).
4640
+ */
4641
+ async sweep(opts) {
4642
+ const keypair = deriveStealthStellarKeypairFromStealthPrivKey(opts.stealthPrivKey);
4643
+ return this.ctx.sendNativeTransfer({
4644
+ destination: opts.destination,
4645
+ amountStroops: opts.amountStroops,
4646
+ signer: keypairSigner(keypair)
4647
+ });
4648
+ }
4649
+ /**
4650
+ * Scan announcements for transfers addressed to `identity`, returning each
4651
+ * match with its reconstructed one-time key and Stellar account. The caller
4652
+ * supplies the announcements (read from the stealth-announcer contract events).
4653
+ */
4654
+ scan(opts) {
4655
+ return scanAnnouncements({
4656
+ announcements: opts.announcements,
4657
+ viewingKey: opts.identity.viewingKey,
4658
+ spendingKey: opts.identity.spendingKey
4659
+ });
4660
+ }
4661
+ };
4662
+
4663
+ // src/services/reputation.ts
4664
+ var ReputationService = class {
4665
+ constructor(ctx, schemas) {
4666
+ this.ctx = ctx;
4667
+ this.schemas = schemas;
4668
+ }
4669
+ ctx;
4670
+ schemas;
4671
+ /** Attest a reputation trait to a stealth identity (delegates to schemas). */
4672
+ attest(opts) {
4673
+ return this.schemas.attest(opts);
4674
+ }
4675
+ /** Submit a precomputed V2 reputation proof for on-chain verification. */
4676
+ async verifyOnChain(opts) {
4677
+ const signer = this.ctx.requireSigner();
4678
+ return this.ctx.contracts.reputationVerifier.verifyReputation({
4679
+ ...opts,
4680
+ groth16VerifierId: this.ctx.config.contracts.groth16Verifier,
4681
+ signer
4682
+ });
4683
+ }
4684
+ /** Read the latest published reputation Merkle root, or null if none. */
4685
+ async getLatestRoot(opts) {
4686
+ const source = opts?.source ?? await this.ctx.requireSigner().publicKey();
4687
+ return this.ctx.contracts.reputationVerifier.getLatestRoot(source);
4688
+ }
4689
+ /**
4690
+ * Generate a V2 reputation proof. Requires an artifact resolver
4691
+ * (`new OpaqueClient({ artifacts })`); otherwise throws {@link NotWiredError}.
4692
+ */
4693
+ async prove(input) {
4694
+ if (!this.ctx.artifacts) {
4695
+ throw new NotWiredError(
4696
+ "Reputation proof generation",
4697
+ "Construct OpaqueClient with { artifacts } (a circuit ArtifactResolver) to enable proving."
4698
+ );
4699
+ }
4700
+ return proveReputationV2({ input, artifacts: this.ctx.artifacts });
4701
+ }
4702
+ /** Generate a proof and submit it on-chain in one call. Returns the tx hash. */
4703
+ async proveAndVerify(input) {
4704
+ return this.verifyOnChain(await this.prove(input));
4705
+ }
4706
+ };
4707
+
4708
+ // src/services/pool.ts
4709
+ var PoolService = class {
4710
+ constructor(ctx) {
4711
+ this.ctx = ctx;
4712
+ }
4713
+ ctx;
4714
+ async source(explicit) {
4715
+ return explicit ?? await this.ctx.requireSigner().publicKey();
4716
+ }
4717
+ /**
4718
+ * Deposit `amountXlm` into the pool. Reads the next leaf index, derives the
4719
+ * commitment from fresh (or provided) secrets, submits, and persists the note.
4720
+ */
4721
+ async deposit(opts) {
4722
+ const signer = this.ctx.requireSigner();
4723
+ const source = await signer.publicKey();
4724
+ const scope = this.ctx.config.pool.scope;
4725
+ const value = parseXlmToStroops(opts.amountXlm);
4726
+ const expectedIndex = await this.ctx.contracts.privacyPool.getDepositCount(source);
4727
+ const secrets = opts.secrets ?? newNoteSecrets();
4728
+ const { commitment } = await deriveDeposit({
4729
+ value,
4730
+ scope,
4731
+ leafIndex: expectedIndex,
4732
+ nullifier: BigInt(secrets.nullifier),
4733
+ secret: BigInt(secrets.secret)
4734
+ });
4735
+ const txHash = await this.ctx.contracts.privacyPool.deposit({
4736
+ value,
4737
+ commitment: bigIntToBytes32(commitment),
4738
+ expectedIndex,
4739
+ signer
4740
+ });
4741
+ const note = {
4742
+ cluster: this.ctx.config.network,
4743
+ poolId: this.ctx.config.contracts.privacyPool,
4744
+ value: value.toString(),
4745
+ scope,
4746
+ leafIndex: expectedIndex,
4747
+ nullifier: secrets.nullifier,
4748
+ secret: secrets.secret,
4749
+ commitment: toHex32(commitment),
4750
+ spent: false,
4751
+ createdAt: opts.createdAt ?? 0
4752
+ };
4753
+ await this.ctx.notes.add(note);
4754
+ return { note, txHash };
4755
+ }
4756
+ /** Withdraw using a precomputed proof bundle. Marks the note spent on success. */
4757
+ async withdraw(opts) {
4758
+ const signer = this.ctx.requireSigner();
4759
+ const txHash = await this.ctx.contracts.privacyPool.withdraw({
4760
+ ...opts.proof,
4761
+ recipient: opts.recipient,
4762
+ fee: opts.fee ?? 0n,
4763
+ relayer: opts.relayer ?? opts.recipient,
4764
+ signer
4765
+ });
4766
+ if (opts.noteCommitment) await this.ctx.notes.markSpent(opts.noteCommitment);
4767
+ return txHash;
4768
+ }
4769
+ /** Read the next deposit leaf index. */
4770
+ async getDepositCount(opts) {
4771
+ return this.ctx.contracts.privacyPool.getDepositCount(await this.source(opts?.source));
4772
+ }
4773
+ /** Read the latest published state and ASP roots (or null when unpublished). */
4774
+ async getRoots(opts) {
4775
+ const source = await this.source(opts?.source);
4776
+ const [state, asp] = await Promise.all([
4777
+ this.ctx.contracts.privacyPool.getLatestRoot({ source, kind: "state" }),
4778
+ this.ctx.contracts.privacyPool.getLatestRoot({ source, kind: "asp" })
4779
+ ]);
4780
+ return { state, asp };
4781
+ }
4782
+ /**
4783
+ * Generate a full-withdrawal proof for a note. Requires an artifact resolver
4784
+ * (`new OpaqueClient({ artifacts })`). The pool leaves are reconstructed from
4785
+ * on-chain Deposit/Withdraw events automatically; pass `stateLeaves` +
4786
+ * `depositIndices` to skip the on-chain read (e.g. in tests).
4787
+ */
4788
+ async proveWithdraw(opts) {
4789
+ if (!this.ctx.artifacts) {
4790
+ throw new NotWiredError(
4791
+ "Pool withdrawal proof generation",
4792
+ "Construct OpaqueClient with { artifacts } to enable proving, or pass a precomputed bundle to withdraw()."
4793
+ );
4794
+ }
4795
+ let { stateLeaves, depositIndices } = opts;
4796
+ if (!stateLeaves || !depositIndices) {
4797
+ const state = await this.ctx.contracts.privacyPool.reconstructState({
4798
+ startLedger: this.ctx.config.startLedger
4799
+ });
4800
+ stateLeaves = state.stateLeaves;
4801
+ depositIndices = state.depositIndices;
4802
+ }
4803
+ return provePoolWithdraw({
4804
+ note: opts.note,
4805
+ recipient: opts.recipient,
4806
+ relayer: opts.relayer ?? opts.recipient,
4807
+ fee: opts.fee ?? 0n,
4808
+ scope: opts.scope ?? this.ctx.config.pool.scope,
4809
+ stateLeaves,
4810
+ depositIndices,
4811
+ artifacts: this.ctx.artifacts
4812
+ });
4813
+ }
4814
+ };
4815
+
4816
+ // src/services/relayer.ts
4817
+ var RelayerService = class {
4818
+ constructor(ctx) {
4819
+ this.ctx = ctx;
4820
+ }
4821
+ ctx;
4822
+ gateway() {
4823
+ return new RelayerGateway({
4824
+ gatewayUrls: this.ctx.config.relayerGatewayUrls,
4825
+ registryId: this.ctx.config.contracts.relayerRegistry,
4826
+ invoker: this.ctx.rpc
4827
+ });
4828
+ }
4829
+ // --- on-chain job lifecycle -------------------------------------------------
4830
+ /** Create a blind withdrawal job (escrows the fee on-chain). */
4831
+ async createJob(opts) {
4832
+ return this.ctx.contracts.relayerRegistry.createJob({
4833
+ ...opts,
4834
+ signer: this.ctx.requireSigner()
4835
+ });
4836
+ }
4837
+ /** Create the on-chain job for a built draft. */
4838
+ async createJobForDraft(draft) {
4839
+ return this.createJob({
4840
+ jobId: draft.jobId,
4841
+ payloadHash: draft.payloadHash,
4842
+ deadlineLedger: draft.deadlineLedger,
4843
+ fee: draft.fee
4844
+ });
4845
+ }
4846
+ /** Cancel a never-accepted job after its deadline (refunds the escrow fee). */
4847
+ async cancelJob(opts) {
4848
+ return this.ctx.contracts.relayerRegistry.cancelJob({
4849
+ ...opts,
4850
+ signer: this.ctx.requireSigner()
4851
+ });
4852
+ }
4853
+ /** Slash an accepted-but-unsubmitted job after its deadline. */
4854
+ async slashJob(opts) {
4855
+ return this.ctx.contracts.relayerRegistry.slashJob({
4856
+ ...opts,
4857
+ signer: this.ctx.requireSigner()
4858
+ });
4859
+ }
4860
+ // --- payload + gateway ------------------------------------------------------
4861
+ /** Build the blind withdrawal payload from a pool proof. */
4862
+ buildWithdrawPayload(opts) {
4863
+ return buildRelayedWithdrawPayload({
4864
+ poolId: this.ctx.config.contracts.privacyPool,
4865
+ registryId: this.ctx.config.contracts.relayerRegistry,
4866
+ proof: opts.proof,
4867
+ recipient: opts.recipient
4868
+ });
4869
+ }
4870
+ /** Build a job draft (job id, payload hash, advert) from a payload. */
4871
+ buildJobDraft(opts) {
4872
+ return buildRelayerJobDraft(opts);
4873
+ }
4874
+ /** A deadline `ledgers` ahead of the current ledger. */
4875
+ async deadlineLedger(ledgers) {
4876
+ return this.gateway().deadlineLedger(ledgers);
4877
+ }
4878
+ /** Advertise a job to the gateway. */
4879
+ async advertise(draft) {
4880
+ return this.gateway().publishAdvert(draft.advert);
4881
+ }
4882
+ /** Fetch and verify bids for a job (signature + on-chain registry state). */
4883
+ async fetchBids(jobIdHex) {
4884
+ return this.gateway().fetchBids(jobIdHex);
4885
+ }
4886
+ /** Stake-weighted random choice among verified bids. */
4887
+ pickBid(bids) {
4888
+ return pickStakeWeightedBid(bids);
4889
+ }
4890
+ /** Encrypt the payload to the chosen relayer and deliver it to the gateway. */
4891
+ async deliverPayload(args) {
4892
+ return this.gateway().deliverPayload(args);
4893
+ }
4894
+ /** Read a job's on-chain status. */
4895
+ async jobStatus(jobIdHex, source) {
4896
+ const src = source ?? await this.ctx.requireSigner().publicKey();
4897
+ return this.gateway().jobStatus(jobIdHex, src);
4898
+ }
4899
+ };
4900
+
4901
+ // src/client/OpaqueClient.ts
4902
+ var OpaqueClient = class {
4903
+ config;
4904
+ rpc;
4905
+ contracts;
4906
+ notes;
4907
+ vault;
4908
+ scanStore;
4909
+ signer;
4910
+ artifacts;
4911
+ payments;
4912
+ pool;
4913
+ reputation;
4914
+ schemas;
4915
+ relayer;
4916
+ rpcClient;
4917
+ constructor(opts) {
4918
+ this.config = resolveConfig(opts);
4919
+ this.rpcClient = opts.invoker ? void 0 : new RpcClient({
4920
+ config: this.config,
4921
+ logger: opts.logger,
4922
+ telemetry: opts.telemetry
4923
+ });
4924
+ this.rpc = opts.invoker ?? this.rpcClient;
4925
+ this.signer = opts.signer;
4926
+ this.artifacts = opts.artifacts;
4927
+ this.notes = opts.storage?.notes ?? new MemoryNoteStore();
4928
+ this.vault = opts.storage?.vault ?? new MemoryVaultStore();
4929
+ this.scanStore = opts.storage?.scan ?? new MemoryScanStore();
4930
+ const c = this.config.contracts;
4931
+ this.contracts = {
4932
+ stealthRegistry: new StealthRegistry(this.rpc, c.stealthRegistry),
4933
+ stealthAnnouncer: new StealthAnnouncer(this.rpc, c.stealthAnnouncer),
4934
+ schemaRegistry: new SchemaRegistry(this.rpc, c.schemaRegistry),
4935
+ attestationEngine: new AttestationEngine(this.rpc, c.attestationEngineV2),
4936
+ groth16Verifier: new Groth16Verifier(this.rpc, c.groth16Verifier),
4937
+ reputationVerifier: new ReputationVerifier(this.rpc, c.reputationVerifier),
4938
+ privacyPool: new PrivacyPool(this.rpc, c.privacyPool),
4939
+ relayerRegistry: new RelayerRegistry(this.rpc, c.relayerRegistry)
4940
+ };
4941
+ this.schemas = new SchemasService(this);
4942
+ this.payments = new PaymentsService(this);
4943
+ this.pool = new PoolService(this);
4944
+ this.relayer = new RelayerService(this);
4945
+ this.reputation = new ReputationService(this, this.schemas);
4946
+ }
4947
+ /** The built-in Soroban/Horizon client, or undefined when a custom invoker was injected. */
4948
+ get soroban() {
4949
+ return this.rpcClient;
4950
+ }
4951
+ /** Returns the configured signer or throws if none was set. */
4952
+ requireSigner() {
4953
+ if (!this.signer) {
4954
+ throw new SignerError(
4955
+ "This operation requires a signer. Construct OpaqueClient with { signer }."
4956
+ );
4957
+ }
4958
+ return this.signer;
4959
+ }
4960
+ /** Send a native XLM transfer through the built-in RpcClient. */
4961
+ sendNativeTransfer(opts) {
4962
+ if (!this.rpcClient) {
4963
+ throw new RpcError(
4964
+ "Native transfers require the built-in RpcClient (unavailable with a custom invoker)."
4965
+ );
4966
+ }
4967
+ return this.rpcClient.sendNativeTransfer(opts);
4968
+ }
4969
+ };
4970
+
4971
+ // src/index.ts
4972
+ var VERSION = "0.1.0";
4973
+ /*! Bundled license information:
4974
+
4975
+ ieee754/index.js:
4976
+ (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
4977
+
4978
+ buffer/index.js:
4979
+ (*!
4980
+ * The buffer module from node.js, for the browser.
4981
+ *
4982
+ * @author Feross Aboukhadijeh <https://feross.org>
4983
+ * @license MIT
4984
+ *)
4985
+ */
4986
+
4987
+ export { ArtifactError, AttestationDataError, AttestationEngine, BN254_R, CONTRACT_ERROR_NAMES, ConfigError, ContractError, DEFAULT_ARTIFACT_PATHS, DEPLOYMENTS, Groth16Verifier, LEGACY_SETUP_MESSAGE, MAX_ATTESTATION_DATA_LEN, MAX_FIELDS, MAX_FIELD_NAME_LEN, MAX_STRING_VALUE_LEN, MemoryNoteStore, MemoryScanStore, MemoryVaultStore, NETWORK_PRESETS, NEW_ACCOUNT_MIN_RESERVE_STROOPS, NotWiredError, OpaqueClient, OpaqueError, POOL_TREE_DEPTH, PaymentsService, PoolMerkleTree, PoolService, PrivacyPool, RELAY_CHAIN_STELLAR, RELAY_PAYLOAD_DOMAIN, RelayerGateway, RelayerRegistry, RelayerService, ReputationService, ReputationVerifier, RootUnavailableError, RpcClient, RpcError, SCHEME_ID_SECP256K1, SchemaParseError, SchemaRegistry, SchemasService, SignerError, SimulationError, StealthAnnouncer, StealthRegistry, TESTNET_DEPLOYMENT, VERSION, addressToAuthorityBytes, addressToScVal, bidSigningDigest, bigIntToBytes32, boolToScVal, buildDomainSeparatedMessage, buildGhostAnnouncementPayload, buildRelayedWithdrawPayload, buildRelayerJobDraft, buildReputationWitnessV2, bytesToBigInt, bytesToHex, bytesToScVal, callbackSigner, checkViewTagMatch, computeSchemaId, computeSchemaIdFromBytes, computeStealthAddressAndViewTag, computeWithdrawContext, concatBytes, consoleLogger, contractErrorName, convertLegacyLink, createPaymentLink, decodeAttestationData, decodeDiagnostics, decodePaymentLink, decodePoolWithdrawPayload, decryptGhostEntries, deriveAnnouncerEphemeralKey, deriveDeposit, deriveKeysFromSignature, deriveStealthStellarAddress, deriveStealthStellarAddressFromStealthPrivKey, deriveStealthStellarKeypair, deriveStealthStellarKeypairFromStealthPrivKey, describeScError, encodeAttestationData, encodeCanonicalFieldDefs, encodePaymentLink, encodePoolWithdrawPayload, encryptGhostEntries, exportEncryptedBackup, extractContractErrorCode, fieldDefsToCanonicalString, fileArtifactResolver, formatStroopsToXlm, formatXlm, fromScVal, generateX25519Keypair, getPoseidon, hashFields, hashPoolWithdrawPayload, hashPoolWithdrawPayloadHex, hexToBytes, i128ToScVal, importEncryptedBackup, isOpaquePaymentLink, isValidAmount, isValidAssetCode, isValidIso8601, isValidMetaAddress, isValidNetwork, isValidStellarPublicKey, isValidUrl, keypairSigner, keysToStealthMetaAddress, makeAdvert, makeBid, memoRiskFor, memoWarningCopy, newNoteSecrets, noopTelemetry, openBox, optionAddressToScVal, parseFieldDefinitions, parseHorizonBalanceToStroops, parsePoolWithdrawPayload, parseStealthMetaAddress, parseXlmToStroops, pickStakeWeightedBid, poolWithdrawPayloadPreimage, provePoolWithdraw, proveReputationV2, randomFieldElement, randomJobId, recipientSharedSecretHash, reconstructStealthPrivateKey, resolveConfig, scanAnnouncements, sealBox, serializeGroth16Proof, serializePoolWithdrawPayload, silentLogger, stealthIdFromPrivateKey, stealthMetaAddressToHex, stringToScVal, symbolToScVal, toHex32, u128ToScVal, u32ToScVal, u64ToScVal, unspentTotal, urlArtifactResolver, validateAdvert, validateBid, validateMemo, verifyBid };
4988
+ //# sourceMappingURL=index.js.map
4989
+ //# sourceMappingURL=index.js.map