@p2pdotme/sdk 1.0.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.
Files changed (50) hide show
  1. package/README.md +155 -0
  2. package/dist/fraud-engine.cjs +598 -0
  3. package/dist/fraud-engine.cjs.map +1 -0
  4. package/dist/fraud-engine.d.cts +194 -0
  5. package/dist/fraud-engine.d.ts +194 -0
  6. package/dist/fraud-engine.mjs +549 -0
  7. package/dist/fraud-engine.mjs.map +1 -0
  8. package/dist/index.cjs +75 -0
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.cts +49 -0
  11. package/dist/index.d.ts +49 -0
  12. package/dist/index.mjs +46 -0
  13. package/dist/index.mjs.map +1 -0
  14. package/dist/order-routing.cjs +882 -0
  15. package/dist/order-routing.cjs.map +1 -0
  16. package/dist/order-routing.d.cts +68 -0
  17. package/dist/order-routing.d.ts +68 -0
  18. package/dist/order-routing.mjs +854 -0
  19. package/dist/order-routing.mjs.map +1 -0
  20. package/dist/payload.cjs +3164 -0
  21. package/dist/payload.cjs.map +1 -0
  22. package/dist/payload.d.cts +162 -0
  23. package/dist/payload.d.ts +162 -0
  24. package/dist/payload.mjs +3120 -0
  25. package/dist/payload.mjs.map +1 -0
  26. package/dist/profile.cjs +695 -0
  27. package/dist/profile.cjs.map +1 -0
  28. package/dist/profile.d.cts +133 -0
  29. package/dist/profile.d.ts +133 -0
  30. package/dist/profile.mjs +667 -0
  31. package/dist/profile.mjs.map +1 -0
  32. package/dist/qr-parsers.cjs +366 -0
  33. package/dist/qr-parsers.cjs.map +1 -0
  34. package/dist/qr-parsers.d.cts +41 -0
  35. package/dist/qr-parsers.d.ts +41 -0
  36. package/dist/qr-parsers.mjs +338 -0
  37. package/dist/qr-parsers.mjs.map +1 -0
  38. package/dist/react.cjs +4803 -0
  39. package/dist/react.cjs.map +1 -0
  40. package/dist/react.d.cts +511 -0
  41. package/dist/react.d.ts +511 -0
  42. package/dist/react.mjs +4759 -0
  43. package/dist/react.mjs.map +1 -0
  44. package/dist/zkkyc.cjs +868 -0
  45. package/dist/zkkyc.cjs.map +1 -0
  46. package/dist/zkkyc.d.cts +230 -0
  47. package/dist/zkkyc.d.ts +230 -0
  48. package/dist/zkkyc.mjs +824 -0
  49. package/dist/zkkyc.mjs.map +1 -0
  50. package/package.json +130 -0
@@ -0,0 +1,3120 @@
1
+ // src/payload/actions.ts
2
+ import { errAsync } from "neverthrow";
3
+
4
+ // src/constants/orders.ts
5
+ var ORDER_TYPE = {
6
+ BUY: 0,
7
+ SELL: 1,
8
+ PAY: 2
9
+ };
10
+
11
+ // src/validation/errors.ts
12
+ var SdkError = class extends Error {
13
+ code;
14
+ cause;
15
+ context;
16
+ constructor(message, options) {
17
+ super(message);
18
+ this.name = "SdkError";
19
+ this.code = options.code;
20
+ this.cause = options.cause;
21
+ this.context = options.context;
22
+ }
23
+ };
24
+
25
+ // src/validation/schemas.ts
26
+ import { err, ok } from "neverthrow";
27
+ import { isAddress } from "viem";
28
+ import { z } from "zod";
29
+ var ZodAddressSchema = z.string().refine((s) => isAddress(s), { message: "Invalid Ethereum address" });
30
+ var ZodCurrencySchema = z.enum([
31
+ "IDR",
32
+ "INR",
33
+ "BRL",
34
+ "ARS",
35
+ "MEX",
36
+ "VEN",
37
+ "EUR",
38
+ "NGN",
39
+ "USD"
40
+ ]);
41
+ function validate(schema, data, toError) {
42
+ const result = schema.safeParse(data);
43
+ if (result.success) {
44
+ return ok(result.data);
45
+ }
46
+ return err(toError(z.prettifyError(result.error), result.error, data));
47
+ }
48
+
49
+ // src/payload/crypto.ts
50
+ import { ok as ok3, Result, ResultAsync, safeTry } from "neverthrow";
51
+ import { keccak256, serializeSignature, stringToHex } from "viem";
52
+ import { sign } from "viem/accounts";
53
+ import { z as z3 } from "zod";
54
+
55
+ // node_modules/@noble/ciphers/esm/utils.js
56
+ function isBytes(a) {
57
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
58
+ }
59
+ function abytes(b, ...lengths) {
60
+ if (!isBytes(b))
61
+ throw new Error("Uint8Array expected");
62
+ if (lengths.length > 0 && !lengths.includes(b.length))
63
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
64
+ }
65
+ function u32(arr) {
66
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
67
+ }
68
+ function clean(...arrays) {
69
+ for (let i = 0; i < arrays.length; i++) {
70
+ arrays[i].fill(0);
71
+ }
72
+ }
73
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
74
+ function overlapBytes(a, b) {
75
+ return a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
76
+ a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
77
+ b.byteOffset < a.byteOffset + a.byteLength;
78
+ }
79
+ function complexOverlapBytes(input, output) {
80
+ if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
81
+ throw new Error("complex overlap of input and output is not supported");
82
+ }
83
+ var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
84
+ function wrappedCipher(key, ...args) {
85
+ abytes(key);
86
+ if (!isLE)
87
+ throw new Error("Non little-endian hardware is not yet supported");
88
+ if (params.nonceLength !== void 0) {
89
+ const nonce = args[0];
90
+ if (!nonce)
91
+ throw new Error("nonce / iv required");
92
+ if (params.varSizeNonce)
93
+ abytes(nonce);
94
+ else
95
+ abytes(nonce, params.nonceLength);
96
+ }
97
+ const tagl = params.tagLength;
98
+ if (tagl && args[1] !== void 0) {
99
+ abytes(args[1]);
100
+ }
101
+ const cipher = constructor(key, ...args);
102
+ const checkOutput = (fnLength, output) => {
103
+ if (output !== void 0) {
104
+ if (fnLength !== 2)
105
+ throw new Error("cipher output not supported");
106
+ abytes(output);
107
+ }
108
+ };
109
+ let called = false;
110
+ const wrCipher = {
111
+ encrypt(data, output) {
112
+ if (called)
113
+ throw new Error("cannot encrypt() twice with same key + nonce");
114
+ called = true;
115
+ abytes(data);
116
+ checkOutput(cipher.encrypt.length, output);
117
+ return cipher.encrypt(data, output);
118
+ },
119
+ decrypt(data, output) {
120
+ abytes(data);
121
+ if (tagl && data.length < tagl)
122
+ throw new Error("invalid ciphertext length: smaller than tagLength=" + tagl);
123
+ checkOutput(cipher.decrypt.length, output);
124
+ return cipher.decrypt(data, output);
125
+ }
126
+ };
127
+ return wrCipher;
128
+ }
129
+ Object.assign(wrappedCipher, params);
130
+ return wrappedCipher;
131
+ };
132
+ function getOutput(expectedLength, out, onlyAligned = true) {
133
+ if (out === void 0)
134
+ return new Uint8Array(expectedLength);
135
+ if (out.length !== expectedLength)
136
+ throw new Error("invalid output length, expected " + expectedLength + ", got: " + out.length);
137
+ if (onlyAligned && !isAligned32(out))
138
+ throw new Error("invalid output, must be aligned");
139
+ return out;
140
+ }
141
+ function isAligned32(bytes) {
142
+ return bytes.byteOffset % 4 === 0;
143
+ }
144
+ function copyBytes(bytes) {
145
+ return Uint8Array.from(bytes);
146
+ }
147
+
148
+ // node_modules/@noble/ciphers/esm/aes.js
149
+ var BLOCK_SIZE = 16;
150
+ var POLY = 283;
151
+ function mul2(n) {
152
+ return n << 1 ^ POLY & -(n >> 7);
153
+ }
154
+ function mul(a, b) {
155
+ let res = 0;
156
+ for (; b > 0; b >>= 1) {
157
+ res ^= a & -(b & 1);
158
+ a = mul2(a);
159
+ }
160
+ return res;
161
+ }
162
+ var sbox = /* @__PURE__ */ (() => {
163
+ const t = new Uint8Array(256);
164
+ for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))
165
+ t[i] = x;
166
+ const box = new Uint8Array(256);
167
+ box[0] = 99;
168
+ for (let i = 0; i < 255; i++) {
169
+ let x = t[255 - i];
170
+ x |= x << 8;
171
+ box[t[i]] = (x ^ x >> 4 ^ x >> 5 ^ x >> 6 ^ x >> 7 ^ 99) & 255;
172
+ }
173
+ clean(t);
174
+ return box;
175
+ })();
176
+ var invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));
177
+ var rotr32_8 = (n) => n << 24 | n >>> 8;
178
+ var rotl32_8 = (n) => n << 8 | n >>> 24;
179
+ function genTtable(sbox2, fn) {
180
+ if (sbox2.length !== 256)
181
+ throw new Error("Wrong sbox length");
182
+ const T0 = new Uint32Array(256).map((_, j) => fn(sbox2[j]));
183
+ const T1 = T0.map(rotl32_8);
184
+ const T2 = T1.map(rotl32_8);
185
+ const T3 = T2.map(rotl32_8);
186
+ const T01 = new Uint32Array(256 * 256);
187
+ const T23 = new Uint32Array(256 * 256);
188
+ const sbox22 = new Uint16Array(256 * 256);
189
+ for (let i = 0; i < 256; i++) {
190
+ for (let j = 0; j < 256; j++) {
191
+ const idx = i * 256 + j;
192
+ T01[idx] = T0[i] ^ T1[j];
193
+ T23[idx] = T2[i] ^ T3[j];
194
+ sbox22[idx] = sbox2[i] << 8 | sbox2[j];
195
+ }
196
+ }
197
+ return { sbox: sbox2, sbox2: sbox22, T0, T1, T2, T3, T01, T23 };
198
+ }
199
+ var tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => mul(s, 3) << 24 | s << 16 | s << 8 | mul(s, 2));
200
+ var tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => mul(s, 11) << 24 | mul(s, 13) << 16 | mul(s, 9) << 8 | mul(s, 14));
201
+ var xPowers = /* @__PURE__ */ (() => {
202
+ const p = new Uint8Array(16);
203
+ for (let i = 0, x = 1; i < 16; i++, x = mul2(x))
204
+ p[i] = x;
205
+ return p;
206
+ })();
207
+ function expandKeyLE(key) {
208
+ abytes(key);
209
+ const len = key.length;
210
+ if (![16, 24, 32].includes(len))
211
+ throw new Error("aes: invalid key size, should be 16, 24 or 32, got " + len);
212
+ const { sbox2 } = tableEncoding;
213
+ const toClean = [];
214
+ if (!isAligned32(key))
215
+ toClean.push(key = copyBytes(key));
216
+ const k32 = u32(key);
217
+ const Nk = k32.length;
218
+ const subByte = (n) => applySbox(sbox2, n, n, n, n);
219
+ const xk = new Uint32Array(len + 28);
220
+ xk.set(k32);
221
+ for (let i = Nk; i < xk.length; i++) {
222
+ let t = xk[i - 1];
223
+ if (i % Nk === 0)
224
+ t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
225
+ else if (Nk > 6 && i % Nk === 4)
226
+ t = subByte(t);
227
+ xk[i] = xk[i - Nk] ^ t;
228
+ }
229
+ clean(...toClean);
230
+ return xk;
231
+ }
232
+ function expandKeyDecLE(key) {
233
+ const encKey = expandKeyLE(key);
234
+ const xk = encKey.slice();
235
+ const Nk = encKey.length;
236
+ const { sbox2 } = tableEncoding;
237
+ const { T0, T1, T2, T3 } = tableDecoding;
238
+ for (let i = 0; i < Nk; i += 4) {
239
+ for (let j = 0; j < 4; j++)
240
+ xk[i + j] = encKey[Nk - i - 4 + j];
241
+ }
242
+ clean(encKey);
243
+ for (let i = 4; i < Nk - 4; i++) {
244
+ const x = xk[i];
245
+ const w = applySbox(sbox2, x, x, x, x);
246
+ xk[i] = T0[w & 255] ^ T1[w >>> 8 & 255] ^ T2[w >>> 16 & 255] ^ T3[w >>> 24];
247
+ }
248
+ return xk;
249
+ }
250
+ function apply0123(T01, T23, s0, s1, s2, s3) {
251
+ return T01[s0 << 8 & 65280 | s1 >>> 8 & 255] ^ T23[s2 >>> 8 & 65280 | s3 >>> 24 & 255];
252
+ }
253
+ function applySbox(sbox2, s0, s1, s2, s3) {
254
+ return sbox2[s0 & 255 | s1 & 65280] | sbox2[s2 >>> 16 & 255 | s3 >>> 16 & 65280] << 16;
255
+ }
256
+ function encrypt(xk, s0, s1, s2, s3) {
257
+ const { sbox2, T01, T23 } = tableEncoding;
258
+ let k = 0;
259
+ s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++];
260
+ const rounds = xk.length / 4 - 2;
261
+ for (let i = 0; i < rounds; i++) {
262
+ const t02 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
263
+ const t12 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
264
+ const t22 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
265
+ const t32 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
266
+ s0 = t02, s1 = t12, s2 = t22, s3 = t32;
267
+ }
268
+ const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
269
+ const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
270
+ const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
271
+ const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);
272
+ return { s0: t0, s1: t1, s2: t2, s3: t3 };
273
+ }
274
+ function decrypt(xk, s0, s1, s2, s3) {
275
+ const { sbox2, T01, T23 } = tableDecoding;
276
+ let k = 0;
277
+ s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++];
278
+ const rounds = xk.length / 4 - 2;
279
+ for (let i = 0; i < rounds; i++) {
280
+ const t02 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);
281
+ const t12 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);
282
+ const t22 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);
283
+ const t32 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);
284
+ s0 = t02, s1 = t12, s2 = t22, s3 = t32;
285
+ }
286
+ const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);
287
+ const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);
288
+ const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);
289
+ const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);
290
+ return { s0: t0, s1: t1, s2: t2, s3: t3 };
291
+ }
292
+ function validateBlockDecrypt(data) {
293
+ abytes(data);
294
+ if (data.length % BLOCK_SIZE !== 0) {
295
+ throw new Error("aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size " + BLOCK_SIZE);
296
+ }
297
+ }
298
+ function validateBlockEncrypt(plaintext, pcks5, dst) {
299
+ abytes(plaintext);
300
+ let outLen = plaintext.length;
301
+ const remaining = outLen % BLOCK_SIZE;
302
+ if (!pcks5 && remaining !== 0)
303
+ throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");
304
+ if (!isAligned32(plaintext))
305
+ plaintext = copyBytes(plaintext);
306
+ const b = u32(plaintext);
307
+ if (pcks5) {
308
+ let left = BLOCK_SIZE - remaining;
309
+ if (!left)
310
+ left = BLOCK_SIZE;
311
+ outLen = outLen + left;
312
+ }
313
+ dst = getOutput(outLen, dst);
314
+ complexOverlapBytes(plaintext, dst);
315
+ const o = u32(dst);
316
+ return { b, o, out: dst };
317
+ }
318
+ function validatePCKS(data, pcks5) {
319
+ if (!pcks5)
320
+ return data;
321
+ const len = data.length;
322
+ if (!len)
323
+ throw new Error("aes/pcks5: empty ciphertext not allowed");
324
+ const lastByte = data[len - 1];
325
+ if (lastByte <= 0 || lastByte > 16)
326
+ throw new Error("aes/pcks5: wrong padding");
327
+ const out = data.subarray(0, -lastByte);
328
+ for (let i = 0; i < lastByte; i++)
329
+ if (data[len - i - 1] !== lastByte)
330
+ throw new Error("aes/pcks5: wrong padding");
331
+ return out;
332
+ }
333
+ function padPCKS(left) {
334
+ const tmp = new Uint8Array(16);
335
+ const tmp32 = u32(tmp);
336
+ tmp.set(left);
337
+ const paddingByte = BLOCK_SIZE - left.length;
338
+ for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)
339
+ tmp[i] = paddingByte;
340
+ return tmp32;
341
+ }
342
+ var cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) {
343
+ const pcks5 = !opts.disablePadding;
344
+ return {
345
+ encrypt(plaintext, dst) {
346
+ const xk = expandKeyLE(key);
347
+ const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);
348
+ let _iv = iv;
349
+ const toClean = [xk];
350
+ if (!isAligned32(_iv))
351
+ toClean.push(_iv = copyBytes(_iv));
352
+ const n32 = u32(_iv);
353
+ let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
354
+ let i = 0;
355
+ for (; i + 4 <= b.length; ) {
356
+ s0 ^= b[i + 0], s1 ^= b[i + 1], s2 ^= b[i + 2], s3 ^= b[i + 3];
357
+ ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
358
+ o[i++] = s0, o[i++] = s1, o[i++] = s2, o[i++] = s3;
359
+ }
360
+ if (pcks5) {
361
+ const tmp32 = padPCKS(plaintext.subarray(i * 4));
362
+ s0 ^= tmp32[0], s1 ^= tmp32[1], s2 ^= tmp32[2], s3 ^= tmp32[3];
363
+ ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
364
+ o[i++] = s0, o[i++] = s1, o[i++] = s2, o[i++] = s3;
365
+ }
366
+ clean(...toClean);
367
+ return _out;
368
+ },
369
+ decrypt(ciphertext, dst) {
370
+ validateBlockDecrypt(ciphertext);
371
+ const xk = expandKeyDecLE(key);
372
+ let _iv = iv;
373
+ const toClean = [xk];
374
+ if (!isAligned32(_iv))
375
+ toClean.push(_iv = copyBytes(_iv));
376
+ const n32 = u32(_iv);
377
+ dst = getOutput(ciphertext.length, dst);
378
+ if (!isAligned32(ciphertext))
379
+ toClean.push(ciphertext = copyBytes(ciphertext));
380
+ complexOverlapBytes(ciphertext, dst);
381
+ const b = u32(ciphertext);
382
+ const o = u32(dst);
383
+ let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
384
+ for (let i = 0; i + 4 <= b.length; ) {
385
+ const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;
386
+ s0 = b[i + 0], s1 = b[i + 1], s2 = b[i + 2], s3 = b[i + 3];
387
+ const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);
388
+ o[i++] = o0 ^ ps0, o[i++] = o1 ^ ps1, o[i++] = o2 ^ ps2, o[i++] = o3 ^ ps3;
389
+ }
390
+ clean(...toClean);
391
+ return validatePCKS(dst, pcks5);
392
+ }
393
+ };
394
+ });
395
+
396
+ // node_modules/@noble/hashes/esm/cryptoNode.js
397
+ import * as nc from "crypto";
398
+ var crypto = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
399
+
400
+ // node_modules/@noble/hashes/esm/utils.js
401
+ function isBytes2(a) {
402
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
403
+ }
404
+ function anumber(n) {
405
+ if (!Number.isSafeInteger(n) || n < 0)
406
+ throw new Error("positive integer expected, got " + n);
407
+ }
408
+ function abytes2(b, ...lengths) {
409
+ if (!isBytes2(b))
410
+ throw new Error("Uint8Array expected");
411
+ if (lengths.length > 0 && !lengths.includes(b.length))
412
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
413
+ }
414
+ function ahash(h) {
415
+ if (typeof h !== "function" || typeof h.create !== "function")
416
+ throw new Error("Hash should be wrapped by utils.createHasher");
417
+ anumber(h.outputLen);
418
+ anumber(h.blockLen);
419
+ }
420
+ function aexists(instance, checkFinished = true) {
421
+ if (instance.destroyed)
422
+ throw new Error("Hash instance has been destroyed");
423
+ if (checkFinished && instance.finished)
424
+ throw new Error("Hash#digest() has already been called");
425
+ }
426
+ function aoutput(out, instance) {
427
+ abytes2(out);
428
+ const min = instance.outputLen;
429
+ if (out.length < min) {
430
+ throw new Error("digestInto() expects output buffer of length at least " + min);
431
+ }
432
+ }
433
+ function clean2(...arrays) {
434
+ for (let i = 0; i < arrays.length; i++) {
435
+ arrays[i].fill(0);
436
+ }
437
+ }
438
+ function createView2(arr) {
439
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
440
+ }
441
+ function rotr(word, shift) {
442
+ return word << 32 - shift | word >>> shift;
443
+ }
444
+ function utf8ToBytes(str) {
445
+ if (typeof str !== "string")
446
+ throw new Error("string expected");
447
+ return new Uint8Array(new TextEncoder().encode(str));
448
+ }
449
+ function toBytes(data) {
450
+ if (typeof data === "string")
451
+ data = utf8ToBytes(data);
452
+ abytes2(data);
453
+ return data;
454
+ }
455
+ function concatBytes2(...arrays) {
456
+ let sum = 0;
457
+ for (let i = 0; i < arrays.length; i++) {
458
+ const a = arrays[i];
459
+ abytes2(a);
460
+ sum += a.length;
461
+ }
462
+ const res = new Uint8Array(sum);
463
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
464
+ const a = arrays[i];
465
+ res.set(a, pad);
466
+ pad += a.length;
467
+ }
468
+ return res;
469
+ }
470
+ var Hash = class {
471
+ };
472
+ function createHasher(hashCons) {
473
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
474
+ const tmp = hashCons();
475
+ hashC.outputLen = tmp.outputLen;
476
+ hashC.blockLen = tmp.blockLen;
477
+ hashC.create = () => hashCons();
478
+ return hashC;
479
+ }
480
+ function randomBytes(bytesLength = 32) {
481
+ if (crypto && typeof crypto.getRandomValues === "function") {
482
+ return crypto.getRandomValues(new Uint8Array(bytesLength));
483
+ }
484
+ if (crypto && typeof crypto.randomBytes === "function") {
485
+ return Uint8Array.from(crypto.randomBytes(bytesLength));
486
+ }
487
+ throw new Error("crypto.getRandomValues must be defined");
488
+ }
489
+
490
+ // node_modules/@noble/hashes/esm/_md.js
491
+ function setBigUint642(view, byteOffset, value, isLE2) {
492
+ if (typeof view.setBigUint64 === "function")
493
+ return view.setBigUint64(byteOffset, value, isLE2);
494
+ const _32n2 = BigInt(32);
495
+ const _u32_max = BigInt(4294967295);
496
+ const wh = Number(value >> _32n2 & _u32_max);
497
+ const wl = Number(value & _u32_max);
498
+ const h = isLE2 ? 4 : 0;
499
+ const l = isLE2 ? 0 : 4;
500
+ view.setUint32(byteOffset + h, wh, isLE2);
501
+ view.setUint32(byteOffset + l, wl, isLE2);
502
+ }
503
+ function Chi(a, b, c) {
504
+ return a & b ^ ~a & c;
505
+ }
506
+ function Maj(a, b, c) {
507
+ return a & b ^ a & c ^ b & c;
508
+ }
509
+ var HashMD = class extends Hash {
510
+ constructor(blockLen, outputLen, padOffset, isLE2) {
511
+ super();
512
+ this.finished = false;
513
+ this.length = 0;
514
+ this.pos = 0;
515
+ this.destroyed = false;
516
+ this.blockLen = blockLen;
517
+ this.outputLen = outputLen;
518
+ this.padOffset = padOffset;
519
+ this.isLE = isLE2;
520
+ this.buffer = new Uint8Array(blockLen);
521
+ this.view = createView2(this.buffer);
522
+ }
523
+ update(data) {
524
+ aexists(this);
525
+ data = toBytes(data);
526
+ abytes2(data);
527
+ const { view, buffer, blockLen } = this;
528
+ const len = data.length;
529
+ for (let pos = 0; pos < len; ) {
530
+ const take = Math.min(blockLen - this.pos, len - pos);
531
+ if (take === blockLen) {
532
+ const dataView = createView2(data);
533
+ for (; blockLen <= len - pos; pos += blockLen)
534
+ this.process(dataView, pos);
535
+ continue;
536
+ }
537
+ buffer.set(data.subarray(pos, pos + take), this.pos);
538
+ this.pos += take;
539
+ pos += take;
540
+ if (this.pos === blockLen) {
541
+ this.process(view, 0);
542
+ this.pos = 0;
543
+ }
544
+ }
545
+ this.length += data.length;
546
+ this.roundClean();
547
+ return this;
548
+ }
549
+ digestInto(out) {
550
+ aexists(this);
551
+ aoutput(out, this);
552
+ this.finished = true;
553
+ const { buffer, view, blockLen, isLE: isLE2 } = this;
554
+ let { pos } = this;
555
+ buffer[pos++] = 128;
556
+ clean2(this.buffer.subarray(pos));
557
+ if (this.padOffset > blockLen - pos) {
558
+ this.process(view, 0);
559
+ pos = 0;
560
+ }
561
+ for (let i = pos; i < blockLen; i++)
562
+ buffer[i] = 0;
563
+ setBigUint642(view, blockLen - 8, BigInt(this.length * 8), isLE2);
564
+ this.process(view, 0);
565
+ const oview = createView2(out);
566
+ const len = this.outputLen;
567
+ if (len % 4)
568
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
569
+ const outLen = len / 4;
570
+ const state = this.get();
571
+ if (outLen > state.length)
572
+ throw new Error("_sha2: outputLen bigger than state");
573
+ for (let i = 0; i < outLen; i++)
574
+ oview.setUint32(4 * i, state[i], isLE2);
575
+ }
576
+ digest() {
577
+ const { buffer, outputLen } = this;
578
+ this.digestInto(buffer);
579
+ const res = buffer.slice(0, outputLen);
580
+ this.destroy();
581
+ return res;
582
+ }
583
+ _cloneInto(to) {
584
+ to || (to = new this.constructor());
585
+ to.set(...this.get());
586
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
587
+ to.destroyed = destroyed;
588
+ to.finished = finished;
589
+ to.length = length;
590
+ to.pos = pos;
591
+ if (length % blockLen)
592
+ to.buffer.set(buffer);
593
+ return to;
594
+ }
595
+ clone() {
596
+ return this._cloneInto();
597
+ }
598
+ };
599
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
600
+ 1779033703,
601
+ 3144134277,
602
+ 1013904242,
603
+ 2773480762,
604
+ 1359893119,
605
+ 2600822924,
606
+ 528734635,
607
+ 1541459225
608
+ ]);
609
+ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
610
+ 1779033703,
611
+ 4089235720,
612
+ 3144134277,
613
+ 2227873595,
614
+ 1013904242,
615
+ 4271175723,
616
+ 2773480762,
617
+ 1595750129,
618
+ 1359893119,
619
+ 2917565137,
620
+ 2600822924,
621
+ 725511199,
622
+ 528734635,
623
+ 4215389547,
624
+ 1541459225,
625
+ 327033209
626
+ ]);
627
+
628
+ // node_modules/@noble/hashes/esm/_u64.js
629
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
630
+ var _32n = /* @__PURE__ */ BigInt(32);
631
+ function fromBig(n, le = false) {
632
+ if (le)
633
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
634
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
635
+ }
636
+ function split(lst, le = false) {
637
+ const len = lst.length;
638
+ let Ah = new Uint32Array(len);
639
+ let Al = new Uint32Array(len);
640
+ for (let i = 0; i < len; i++) {
641
+ const { h, l } = fromBig(lst[i], le);
642
+ [Ah[i], Al[i]] = [h, l];
643
+ }
644
+ return [Ah, Al];
645
+ }
646
+ var shrSH = (h, _l, s) => h >>> s;
647
+ var shrSL = (h, l, s) => h << 32 - s | l >>> s;
648
+ var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
649
+ var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
650
+ var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
651
+ var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
652
+ function add(Ah, Al, Bh, Bl) {
653
+ const l = (Al >>> 0) + (Bl >>> 0);
654
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
655
+ }
656
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
657
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
658
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
659
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
660
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
661
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
662
+
663
+ // node_modules/@noble/hashes/esm/sha2.js
664
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
665
+ 1116352408,
666
+ 1899447441,
667
+ 3049323471,
668
+ 3921009573,
669
+ 961987163,
670
+ 1508970993,
671
+ 2453635748,
672
+ 2870763221,
673
+ 3624381080,
674
+ 310598401,
675
+ 607225278,
676
+ 1426881987,
677
+ 1925078388,
678
+ 2162078206,
679
+ 2614888103,
680
+ 3248222580,
681
+ 3835390401,
682
+ 4022224774,
683
+ 264347078,
684
+ 604807628,
685
+ 770255983,
686
+ 1249150122,
687
+ 1555081692,
688
+ 1996064986,
689
+ 2554220882,
690
+ 2821834349,
691
+ 2952996808,
692
+ 3210313671,
693
+ 3336571891,
694
+ 3584528711,
695
+ 113926993,
696
+ 338241895,
697
+ 666307205,
698
+ 773529912,
699
+ 1294757372,
700
+ 1396182291,
701
+ 1695183700,
702
+ 1986661051,
703
+ 2177026350,
704
+ 2456956037,
705
+ 2730485921,
706
+ 2820302411,
707
+ 3259730800,
708
+ 3345764771,
709
+ 3516065817,
710
+ 3600352804,
711
+ 4094571909,
712
+ 275423344,
713
+ 430227734,
714
+ 506948616,
715
+ 659060556,
716
+ 883997877,
717
+ 958139571,
718
+ 1322822218,
719
+ 1537002063,
720
+ 1747873779,
721
+ 1955562222,
722
+ 2024104815,
723
+ 2227730452,
724
+ 2361852424,
725
+ 2428436474,
726
+ 2756734187,
727
+ 3204031479,
728
+ 3329325298
729
+ ]);
730
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
731
+ var SHA256 = class extends HashMD {
732
+ constructor(outputLen = 32) {
733
+ super(64, outputLen, 8, false);
734
+ this.A = SHA256_IV[0] | 0;
735
+ this.B = SHA256_IV[1] | 0;
736
+ this.C = SHA256_IV[2] | 0;
737
+ this.D = SHA256_IV[3] | 0;
738
+ this.E = SHA256_IV[4] | 0;
739
+ this.F = SHA256_IV[5] | 0;
740
+ this.G = SHA256_IV[6] | 0;
741
+ this.H = SHA256_IV[7] | 0;
742
+ }
743
+ get() {
744
+ const { A, B, C, D, E, F, G, H } = this;
745
+ return [A, B, C, D, E, F, G, H];
746
+ }
747
+ // prettier-ignore
748
+ set(A, B, C, D, E, F, G, H) {
749
+ this.A = A | 0;
750
+ this.B = B | 0;
751
+ this.C = C | 0;
752
+ this.D = D | 0;
753
+ this.E = E | 0;
754
+ this.F = F | 0;
755
+ this.G = G | 0;
756
+ this.H = H | 0;
757
+ }
758
+ process(view, offset) {
759
+ for (let i = 0; i < 16; i++, offset += 4)
760
+ SHA256_W[i] = view.getUint32(offset, false);
761
+ for (let i = 16; i < 64; i++) {
762
+ const W15 = SHA256_W[i - 15];
763
+ const W2 = SHA256_W[i - 2];
764
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
765
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
766
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
767
+ }
768
+ let { A, B, C, D, E, F, G, H } = this;
769
+ for (let i = 0; i < 64; i++) {
770
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
771
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
772
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
773
+ const T2 = sigma0 + Maj(A, B, C) | 0;
774
+ H = G;
775
+ G = F;
776
+ F = E;
777
+ E = D + T1 | 0;
778
+ D = C;
779
+ C = B;
780
+ B = A;
781
+ A = T1 + T2 | 0;
782
+ }
783
+ A = A + this.A | 0;
784
+ B = B + this.B | 0;
785
+ C = C + this.C | 0;
786
+ D = D + this.D | 0;
787
+ E = E + this.E | 0;
788
+ F = F + this.F | 0;
789
+ G = G + this.G | 0;
790
+ H = H + this.H | 0;
791
+ this.set(A, B, C, D, E, F, G, H);
792
+ }
793
+ roundClean() {
794
+ clean2(SHA256_W);
795
+ }
796
+ destroy() {
797
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
798
+ clean2(this.buffer);
799
+ }
800
+ };
801
+ var K512 = /* @__PURE__ */ (() => split([
802
+ "0x428a2f98d728ae22",
803
+ "0x7137449123ef65cd",
804
+ "0xb5c0fbcfec4d3b2f",
805
+ "0xe9b5dba58189dbbc",
806
+ "0x3956c25bf348b538",
807
+ "0x59f111f1b605d019",
808
+ "0x923f82a4af194f9b",
809
+ "0xab1c5ed5da6d8118",
810
+ "0xd807aa98a3030242",
811
+ "0x12835b0145706fbe",
812
+ "0x243185be4ee4b28c",
813
+ "0x550c7dc3d5ffb4e2",
814
+ "0x72be5d74f27b896f",
815
+ "0x80deb1fe3b1696b1",
816
+ "0x9bdc06a725c71235",
817
+ "0xc19bf174cf692694",
818
+ "0xe49b69c19ef14ad2",
819
+ "0xefbe4786384f25e3",
820
+ "0x0fc19dc68b8cd5b5",
821
+ "0x240ca1cc77ac9c65",
822
+ "0x2de92c6f592b0275",
823
+ "0x4a7484aa6ea6e483",
824
+ "0x5cb0a9dcbd41fbd4",
825
+ "0x76f988da831153b5",
826
+ "0x983e5152ee66dfab",
827
+ "0xa831c66d2db43210",
828
+ "0xb00327c898fb213f",
829
+ "0xbf597fc7beef0ee4",
830
+ "0xc6e00bf33da88fc2",
831
+ "0xd5a79147930aa725",
832
+ "0x06ca6351e003826f",
833
+ "0x142929670a0e6e70",
834
+ "0x27b70a8546d22ffc",
835
+ "0x2e1b21385c26c926",
836
+ "0x4d2c6dfc5ac42aed",
837
+ "0x53380d139d95b3df",
838
+ "0x650a73548baf63de",
839
+ "0x766a0abb3c77b2a8",
840
+ "0x81c2c92e47edaee6",
841
+ "0x92722c851482353b",
842
+ "0xa2bfe8a14cf10364",
843
+ "0xa81a664bbc423001",
844
+ "0xc24b8b70d0f89791",
845
+ "0xc76c51a30654be30",
846
+ "0xd192e819d6ef5218",
847
+ "0xd69906245565a910",
848
+ "0xf40e35855771202a",
849
+ "0x106aa07032bbd1b8",
850
+ "0x19a4c116b8d2d0c8",
851
+ "0x1e376c085141ab53",
852
+ "0x2748774cdf8eeb99",
853
+ "0x34b0bcb5e19b48a8",
854
+ "0x391c0cb3c5c95a63",
855
+ "0x4ed8aa4ae3418acb",
856
+ "0x5b9cca4f7763e373",
857
+ "0x682e6ff3d6b2b8a3",
858
+ "0x748f82ee5defb2fc",
859
+ "0x78a5636f43172f60",
860
+ "0x84c87814a1f0ab72",
861
+ "0x8cc702081a6439ec",
862
+ "0x90befffa23631e28",
863
+ "0xa4506cebde82bde9",
864
+ "0xbef9a3f7b2c67915",
865
+ "0xc67178f2e372532b",
866
+ "0xca273eceea26619c",
867
+ "0xd186b8c721c0c207",
868
+ "0xeada7dd6cde0eb1e",
869
+ "0xf57d4f7fee6ed178",
870
+ "0x06f067aa72176fba",
871
+ "0x0a637dc5a2c898a6",
872
+ "0x113f9804bef90dae",
873
+ "0x1b710b35131c471b",
874
+ "0x28db77f523047d84",
875
+ "0x32caab7b40c72493",
876
+ "0x3c9ebe0a15c9bebc",
877
+ "0x431d67c49c100d4c",
878
+ "0x4cc5d4becb3e42b6",
879
+ "0x597f299cfc657e2a",
880
+ "0x5fcb6fab3ad6faec",
881
+ "0x6c44198c4a475817"
882
+ ].map((n) => BigInt(n))))();
883
+ var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
884
+ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
885
+ var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
886
+ var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
887
+ var SHA512 = class extends HashMD {
888
+ constructor(outputLen = 64) {
889
+ super(128, outputLen, 16, false);
890
+ this.Ah = SHA512_IV[0] | 0;
891
+ this.Al = SHA512_IV[1] | 0;
892
+ this.Bh = SHA512_IV[2] | 0;
893
+ this.Bl = SHA512_IV[3] | 0;
894
+ this.Ch = SHA512_IV[4] | 0;
895
+ this.Cl = SHA512_IV[5] | 0;
896
+ this.Dh = SHA512_IV[6] | 0;
897
+ this.Dl = SHA512_IV[7] | 0;
898
+ this.Eh = SHA512_IV[8] | 0;
899
+ this.El = SHA512_IV[9] | 0;
900
+ this.Fh = SHA512_IV[10] | 0;
901
+ this.Fl = SHA512_IV[11] | 0;
902
+ this.Gh = SHA512_IV[12] | 0;
903
+ this.Gl = SHA512_IV[13] | 0;
904
+ this.Hh = SHA512_IV[14] | 0;
905
+ this.Hl = SHA512_IV[15] | 0;
906
+ }
907
+ // prettier-ignore
908
+ get() {
909
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
910
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
911
+ }
912
+ // prettier-ignore
913
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
914
+ this.Ah = Ah | 0;
915
+ this.Al = Al | 0;
916
+ this.Bh = Bh | 0;
917
+ this.Bl = Bl | 0;
918
+ this.Ch = Ch | 0;
919
+ this.Cl = Cl | 0;
920
+ this.Dh = Dh | 0;
921
+ this.Dl = Dl | 0;
922
+ this.Eh = Eh | 0;
923
+ this.El = El | 0;
924
+ this.Fh = Fh | 0;
925
+ this.Fl = Fl | 0;
926
+ this.Gh = Gh | 0;
927
+ this.Gl = Gl | 0;
928
+ this.Hh = Hh | 0;
929
+ this.Hl = Hl | 0;
930
+ }
931
+ process(view, offset) {
932
+ for (let i = 0; i < 16; i++, offset += 4) {
933
+ SHA512_W_H[i] = view.getUint32(offset);
934
+ SHA512_W_L[i] = view.getUint32(offset += 4);
935
+ }
936
+ for (let i = 16; i < 80; i++) {
937
+ const W15h = SHA512_W_H[i - 15] | 0;
938
+ const W15l = SHA512_W_L[i - 15] | 0;
939
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
940
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
941
+ const W2h = SHA512_W_H[i - 2] | 0;
942
+ const W2l = SHA512_W_L[i - 2] | 0;
943
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
944
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
945
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
946
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
947
+ SHA512_W_H[i] = SUMh | 0;
948
+ SHA512_W_L[i] = SUMl | 0;
949
+ }
950
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
951
+ for (let i = 0; i < 80; i++) {
952
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
953
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
954
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
955
+ const CHIl = El & Fl ^ ~El & Gl;
956
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
957
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
958
+ const T1l = T1ll | 0;
959
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
960
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
961
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
962
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
963
+ Hh = Gh | 0;
964
+ Hl = Gl | 0;
965
+ Gh = Fh | 0;
966
+ Gl = Fl | 0;
967
+ Fh = Eh | 0;
968
+ Fl = El | 0;
969
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
970
+ Dh = Ch | 0;
971
+ Dl = Cl | 0;
972
+ Ch = Bh | 0;
973
+ Cl = Bl | 0;
974
+ Bh = Ah | 0;
975
+ Bl = Al | 0;
976
+ const All = add3L(T1l, sigma0l, MAJl);
977
+ Ah = add3H(All, T1h, sigma0h, MAJh);
978
+ Al = All | 0;
979
+ }
980
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
981
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
982
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
983
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
984
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
985
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
986
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
987
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
988
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
989
+ }
990
+ roundClean() {
991
+ clean2(SHA512_W_H, SHA512_W_L);
992
+ }
993
+ destroy() {
994
+ clean2(this.buffer);
995
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
996
+ }
997
+ };
998
+ var sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
999
+ var sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
1000
+
1001
+ // node_modules/@noble/hashes/esm/hmac.js
1002
+ var HMAC = class extends Hash {
1003
+ constructor(hash, _key) {
1004
+ super();
1005
+ this.finished = false;
1006
+ this.destroyed = false;
1007
+ ahash(hash);
1008
+ const key = toBytes(_key);
1009
+ this.iHash = hash.create();
1010
+ if (typeof this.iHash.update !== "function")
1011
+ throw new Error("Expected instance of class which extends utils.Hash");
1012
+ this.blockLen = this.iHash.blockLen;
1013
+ this.outputLen = this.iHash.outputLen;
1014
+ const blockLen = this.blockLen;
1015
+ const pad = new Uint8Array(blockLen);
1016
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
1017
+ for (let i = 0; i < pad.length; i++)
1018
+ pad[i] ^= 54;
1019
+ this.iHash.update(pad);
1020
+ this.oHash = hash.create();
1021
+ for (let i = 0; i < pad.length; i++)
1022
+ pad[i] ^= 54 ^ 92;
1023
+ this.oHash.update(pad);
1024
+ clean2(pad);
1025
+ }
1026
+ update(buf) {
1027
+ aexists(this);
1028
+ this.iHash.update(buf);
1029
+ return this;
1030
+ }
1031
+ digestInto(out) {
1032
+ aexists(this);
1033
+ abytes2(out, this.outputLen);
1034
+ this.finished = true;
1035
+ this.iHash.digestInto(out);
1036
+ this.oHash.update(out);
1037
+ this.oHash.digestInto(out);
1038
+ this.destroy();
1039
+ }
1040
+ digest() {
1041
+ const out = new Uint8Array(this.oHash.outputLen);
1042
+ this.digestInto(out);
1043
+ return out;
1044
+ }
1045
+ _cloneInto(to) {
1046
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
1047
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
1048
+ to = to;
1049
+ to.finished = finished;
1050
+ to.destroyed = destroyed;
1051
+ to.blockLen = blockLen;
1052
+ to.outputLen = outputLen;
1053
+ to.oHash = oHash._cloneInto(to.oHash);
1054
+ to.iHash = iHash._cloneInto(to.iHash);
1055
+ return to;
1056
+ }
1057
+ clone() {
1058
+ return this._cloneInto();
1059
+ }
1060
+ destroy() {
1061
+ this.destroyed = true;
1062
+ this.oHash.destroy();
1063
+ this.iHash.destroy();
1064
+ }
1065
+ };
1066
+ var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
1067
+ hmac.create = (hash, key) => new HMAC(hash, key);
1068
+
1069
+ // node_modules/@noble/curves/esm/abstract/utils.js
1070
+ var _0n = /* @__PURE__ */ BigInt(0);
1071
+ var _1n = /* @__PURE__ */ BigInt(1);
1072
+ function isBytes3(a) {
1073
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
1074
+ }
1075
+ function abytes3(item) {
1076
+ if (!isBytes3(item))
1077
+ throw new Error("Uint8Array expected");
1078
+ }
1079
+ function abool(title, value) {
1080
+ if (typeof value !== "boolean")
1081
+ throw new Error(title + " boolean expected, got " + value);
1082
+ }
1083
+ function numberToHexUnpadded(num) {
1084
+ const hex = num.toString(16);
1085
+ return hex.length & 1 ? "0" + hex : hex;
1086
+ }
1087
+ function hexToNumber(hex) {
1088
+ if (typeof hex !== "string")
1089
+ throw new Error("hex string expected, got " + typeof hex);
1090
+ return hex === "" ? _0n : BigInt("0x" + hex);
1091
+ }
1092
+ var hasHexBuiltin = (
1093
+ // @ts-ignore
1094
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
1095
+ );
1096
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
1097
+ function bytesToHex(bytes) {
1098
+ abytes3(bytes);
1099
+ if (hasHexBuiltin)
1100
+ return bytes.toHex();
1101
+ let hex = "";
1102
+ for (let i = 0; i < bytes.length; i++) {
1103
+ hex += hexes[bytes[i]];
1104
+ }
1105
+ return hex;
1106
+ }
1107
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
1108
+ function asciiToBase16(ch) {
1109
+ if (ch >= asciis._0 && ch <= asciis._9)
1110
+ return ch - asciis._0;
1111
+ if (ch >= asciis.A && ch <= asciis.F)
1112
+ return ch - (asciis.A - 10);
1113
+ if (ch >= asciis.a && ch <= asciis.f)
1114
+ return ch - (asciis.a - 10);
1115
+ return;
1116
+ }
1117
+ function hexToBytes(hex) {
1118
+ if (typeof hex !== "string")
1119
+ throw new Error("hex string expected, got " + typeof hex);
1120
+ if (hasHexBuiltin)
1121
+ return Uint8Array.fromHex(hex);
1122
+ const hl = hex.length;
1123
+ const al = hl / 2;
1124
+ if (hl % 2)
1125
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
1126
+ const array = new Uint8Array(al);
1127
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
1128
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
1129
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
1130
+ if (n1 === void 0 || n2 === void 0) {
1131
+ const char = hex[hi] + hex[hi + 1];
1132
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
1133
+ }
1134
+ array[ai] = n1 * 16 + n2;
1135
+ }
1136
+ return array;
1137
+ }
1138
+ function bytesToNumberBE(bytes) {
1139
+ return hexToNumber(bytesToHex(bytes));
1140
+ }
1141
+ function bytesToNumberLE(bytes) {
1142
+ abytes3(bytes);
1143
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
1144
+ }
1145
+ function numberToBytesBE(n, len) {
1146
+ return hexToBytes(n.toString(16).padStart(len * 2, "0"));
1147
+ }
1148
+ function numberToBytesLE(n, len) {
1149
+ return numberToBytesBE(n, len).reverse();
1150
+ }
1151
+ function ensureBytes(title, hex, expectedLength) {
1152
+ let res;
1153
+ if (typeof hex === "string") {
1154
+ try {
1155
+ res = hexToBytes(hex);
1156
+ } catch (e) {
1157
+ throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
1158
+ }
1159
+ } else if (isBytes3(hex)) {
1160
+ res = Uint8Array.from(hex);
1161
+ } else {
1162
+ throw new Error(title + " must be hex string or Uint8Array");
1163
+ }
1164
+ const len = res.length;
1165
+ if (typeof expectedLength === "number" && len !== expectedLength)
1166
+ throw new Error(title + " of length " + expectedLength + " expected, got " + len);
1167
+ return res;
1168
+ }
1169
+ function concatBytes3(...arrays) {
1170
+ let sum = 0;
1171
+ for (let i = 0; i < arrays.length; i++) {
1172
+ const a = arrays[i];
1173
+ abytes3(a);
1174
+ sum += a.length;
1175
+ }
1176
+ const res = new Uint8Array(sum);
1177
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
1178
+ const a = arrays[i];
1179
+ res.set(a, pad);
1180
+ pad += a.length;
1181
+ }
1182
+ return res;
1183
+ }
1184
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
1185
+ function inRange(n, min, max) {
1186
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
1187
+ }
1188
+ function aInRange(title, n, min, max) {
1189
+ if (!inRange(n, min, max))
1190
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
1191
+ }
1192
+ function bitLen(n) {
1193
+ let len;
1194
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
1195
+ ;
1196
+ return len;
1197
+ }
1198
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
1199
+ var u8n = (len) => new Uint8Array(len);
1200
+ var u8fr = (arr) => Uint8Array.from(arr);
1201
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
1202
+ if (typeof hashLen !== "number" || hashLen < 2)
1203
+ throw new Error("hashLen must be a number");
1204
+ if (typeof qByteLen !== "number" || qByteLen < 2)
1205
+ throw new Error("qByteLen must be a number");
1206
+ if (typeof hmacFn !== "function")
1207
+ throw new Error("hmacFn must be a function");
1208
+ let v = u8n(hashLen);
1209
+ let k = u8n(hashLen);
1210
+ let i = 0;
1211
+ const reset = () => {
1212
+ v.fill(1);
1213
+ k.fill(0);
1214
+ i = 0;
1215
+ };
1216
+ const h = (...b) => hmacFn(k, v, ...b);
1217
+ const reseed = (seed = u8n(0)) => {
1218
+ k = h(u8fr([0]), seed);
1219
+ v = h();
1220
+ if (seed.length === 0)
1221
+ return;
1222
+ k = h(u8fr([1]), seed);
1223
+ v = h();
1224
+ };
1225
+ const gen = () => {
1226
+ if (i++ >= 1e3)
1227
+ throw new Error("drbg: tried 1000 values");
1228
+ let len = 0;
1229
+ const out = [];
1230
+ while (len < qByteLen) {
1231
+ v = h();
1232
+ const sl = v.slice();
1233
+ out.push(sl);
1234
+ len += v.length;
1235
+ }
1236
+ return concatBytes3(...out);
1237
+ };
1238
+ const genUntil = (seed, pred) => {
1239
+ reset();
1240
+ reseed(seed);
1241
+ let res = void 0;
1242
+ while (!(res = pred(gen())))
1243
+ reseed();
1244
+ reset();
1245
+ return res;
1246
+ };
1247
+ return genUntil;
1248
+ }
1249
+ var validatorFns = {
1250
+ bigint: (val) => typeof val === "bigint",
1251
+ function: (val) => typeof val === "function",
1252
+ boolean: (val) => typeof val === "boolean",
1253
+ string: (val) => typeof val === "string",
1254
+ stringOrUint8Array: (val) => typeof val === "string" || isBytes3(val),
1255
+ isSafeInteger: (val) => Number.isSafeInteger(val),
1256
+ array: (val) => Array.isArray(val),
1257
+ field: (val, object) => object.Fp.isValid(val),
1258
+ hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
1259
+ };
1260
+ function validateObject(object, validators, optValidators = {}) {
1261
+ const checkField = (fieldName, type, isOptional) => {
1262
+ const checkVal = validatorFns[type];
1263
+ if (typeof checkVal !== "function")
1264
+ throw new Error("invalid validator function");
1265
+ const val = object[fieldName];
1266
+ if (isOptional && val === void 0)
1267
+ return;
1268
+ if (!checkVal(val, object)) {
1269
+ throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val);
1270
+ }
1271
+ };
1272
+ for (const [fieldName, type] of Object.entries(validators))
1273
+ checkField(fieldName, type, false);
1274
+ for (const [fieldName, type] of Object.entries(optValidators))
1275
+ checkField(fieldName, type, true);
1276
+ return object;
1277
+ }
1278
+ function memoized(fn) {
1279
+ const map = /* @__PURE__ */ new WeakMap();
1280
+ return (arg, ...args) => {
1281
+ const val = map.get(arg);
1282
+ if (val !== void 0)
1283
+ return val;
1284
+ const computed = fn(arg, ...args);
1285
+ map.set(arg, computed);
1286
+ return computed;
1287
+ };
1288
+ }
1289
+
1290
+ // node_modules/@noble/curves/esm/abstract/modular.js
1291
+ var _0n2 = BigInt(0);
1292
+ var _1n2 = BigInt(1);
1293
+ var _2n = /* @__PURE__ */ BigInt(2);
1294
+ var _3n = /* @__PURE__ */ BigInt(3);
1295
+ var _4n = /* @__PURE__ */ BigInt(4);
1296
+ var _5n = /* @__PURE__ */ BigInt(5);
1297
+ var _8n = /* @__PURE__ */ BigInt(8);
1298
+ function mod(a, b) {
1299
+ const result = a % b;
1300
+ return result >= _0n2 ? result : b + result;
1301
+ }
1302
+ function pow2(x, power, modulo) {
1303
+ let res = x;
1304
+ while (power-- > _0n2) {
1305
+ res *= res;
1306
+ res %= modulo;
1307
+ }
1308
+ return res;
1309
+ }
1310
+ function invert(number, modulo) {
1311
+ if (number === _0n2)
1312
+ throw new Error("invert: expected non-zero number");
1313
+ if (modulo <= _0n2)
1314
+ throw new Error("invert: expected positive modulus, got " + modulo);
1315
+ let a = mod(number, modulo);
1316
+ let b = modulo;
1317
+ let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
1318
+ while (a !== _0n2) {
1319
+ const q = b / a;
1320
+ const r = b % a;
1321
+ const m = x - u * q;
1322
+ const n = y - v * q;
1323
+ b = a, a = r, x = u, y = v, u = m, v = n;
1324
+ }
1325
+ const gcd = b;
1326
+ if (gcd !== _1n2)
1327
+ throw new Error("invert: does not exist");
1328
+ return mod(x, modulo);
1329
+ }
1330
+ function sqrt3mod4(Fp, n) {
1331
+ const p1div4 = (Fp.ORDER + _1n2) / _4n;
1332
+ const root = Fp.pow(n, p1div4);
1333
+ if (!Fp.eql(Fp.sqr(root), n))
1334
+ throw new Error("Cannot find square root");
1335
+ return root;
1336
+ }
1337
+ function sqrt5mod8(Fp, n) {
1338
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
1339
+ const n2 = Fp.mul(n, _2n);
1340
+ const v = Fp.pow(n2, p5div8);
1341
+ const nv = Fp.mul(n, v);
1342
+ const i = Fp.mul(Fp.mul(nv, _2n), v);
1343
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
1344
+ if (!Fp.eql(Fp.sqr(root), n))
1345
+ throw new Error("Cannot find square root");
1346
+ return root;
1347
+ }
1348
+ function tonelliShanks(P) {
1349
+ if (P < BigInt(3))
1350
+ throw new Error("sqrt is not defined for small field");
1351
+ let Q = P - _1n2;
1352
+ let S = 0;
1353
+ while (Q % _2n === _0n2) {
1354
+ Q /= _2n;
1355
+ S++;
1356
+ }
1357
+ let Z = _2n;
1358
+ const _Fp = Field(P);
1359
+ while (FpLegendre(_Fp, Z) === 1) {
1360
+ if (Z++ > 1e3)
1361
+ throw new Error("Cannot find square root: probably non-prime P");
1362
+ }
1363
+ if (S === 1)
1364
+ return sqrt3mod4;
1365
+ let cc = _Fp.pow(Z, Q);
1366
+ const Q1div2 = (Q + _1n2) / _2n;
1367
+ return function tonelliSlow(Fp, n) {
1368
+ if (Fp.is0(n))
1369
+ return n;
1370
+ if (FpLegendre(Fp, n) !== 1)
1371
+ throw new Error("Cannot find square root");
1372
+ let M = S;
1373
+ let c = Fp.mul(Fp.ONE, cc);
1374
+ let t = Fp.pow(n, Q);
1375
+ let R = Fp.pow(n, Q1div2);
1376
+ while (!Fp.eql(t, Fp.ONE)) {
1377
+ if (Fp.is0(t))
1378
+ return Fp.ZERO;
1379
+ let i = 1;
1380
+ let t_tmp = Fp.sqr(t);
1381
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
1382
+ i++;
1383
+ t_tmp = Fp.sqr(t_tmp);
1384
+ if (i === M)
1385
+ throw new Error("Cannot find square root");
1386
+ }
1387
+ const exponent = _1n2 << BigInt(M - i - 1);
1388
+ const b = Fp.pow(c, exponent);
1389
+ M = i;
1390
+ c = Fp.sqr(b);
1391
+ t = Fp.mul(t, c);
1392
+ R = Fp.mul(R, b);
1393
+ }
1394
+ return R;
1395
+ };
1396
+ }
1397
+ function FpSqrt(P) {
1398
+ if (P % _4n === _3n)
1399
+ return sqrt3mod4;
1400
+ if (P % _8n === _5n)
1401
+ return sqrt5mod8;
1402
+ return tonelliShanks(P);
1403
+ }
1404
+ var FIELD_FIELDS = [
1405
+ "create",
1406
+ "isValid",
1407
+ "is0",
1408
+ "neg",
1409
+ "inv",
1410
+ "sqrt",
1411
+ "sqr",
1412
+ "eql",
1413
+ "add",
1414
+ "sub",
1415
+ "mul",
1416
+ "pow",
1417
+ "div",
1418
+ "addN",
1419
+ "subN",
1420
+ "mulN",
1421
+ "sqrN"
1422
+ ];
1423
+ function validateField(field) {
1424
+ const initial = {
1425
+ ORDER: "bigint",
1426
+ MASK: "bigint",
1427
+ BYTES: "isSafeInteger",
1428
+ BITS: "isSafeInteger"
1429
+ };
1430
+ const opts = FIELD_FIELDS.reduce((map, val) => {
1431
+ map[val] = "function";
1432
+ return map;
1433
+ }, initial);
1434
+ return validateObject(field, opts);
1435
+ }
1436
+ function FpPow(Fp, num, power) {
1437
+ if (power < _0n2)
1438
+ throw new Error("invalid exponent, negatives unsupported");
1439
+ if (power === _0n2)
1440
+ return Fp.ONE;
1441
+ if (power === _1n2)
1442
+ return num;
1443
+ let p = Fp.ONE;
1444
+ let d = num;
1445
+ while (power > _0n2) {
1446
+ if (power & _1n2)
1447
+ p = Fp.mul(p, d);
1448
+ d = Fp.sqr(d);
1449
+ power >>= _1n2;
1450
+ }
1451
+ return p;
1452
+ }
1453
+ function FpInvertBatch(Fp, nums, passZero = false) {
1454
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
1455
+ const multipliedAcc = nums.reduce((acc, num, i) => {
1456
+ if (Fp.is0(num))
1457
+ return acc;
1458
+ inverted[i] = acc;
1459
+ return Fp.mul(acc, num);
1460
+ }, Fp.ONE);
1461
+ const invertedAcc = Fp.inv(multipliedAcc);
1462
+ nums.reduceRight((acc, num, i) => {
1463
+ if (Fp.is0(num))
1464
+ return acc;
1465
+ inverted[i] = Fp.mul(acc, inverted[i]);
1466
+ return Fp.mul(acc, num);
1467
+ }, invertedAcc);
1468
+ return inverted;
1469
+ }
1470
+ function FpLegendre(Fp, n) {
1471
+ const p1mod2 = (Fp.ORDER - _1n2) / _2n;
1472
+ const powered = Fp.pow(n, p1mod2);
1473
+ const yes = Fp.eql(powered, Fp.ONE);
1474
+ const zero = Fp.eql(powered, Fp.ZERO);
1475
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
1476
+ if (!yes && !zero && !no)
1477
+ throw new Error("invalid Legendre symbol result");
1478
+ return yes ? 1 : zero ? 0 : -1;
1479
+ }
1480
+ function nLength(n, nBitLength) {
1481
+ if (nBitLength !== void 0)
1482
+ anumber(nBitLength);
1483
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
1484
+ const nByteLength = Math.ceil(_nBitLength / 8);
1485
+ return { nBitLength: _nBitLength, nByteLength };
1486
+ }
1487
+ function Field(ORDER, bitLen2, isLE2 = false, redef = {}) {
1488
+ if (ORDER <= _0n2)
1489
+ throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
1490
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2);
1491
+ if (BYTES > 2048)
1492
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
1493
+ let sqrtP;
1494
+ const f = Object.freeze({
1495
+ ORDER,
1496
+ isLE: isLE2,
1497
+ BITS,
1498
+ BYTES,
1499
+ MASK: bitMask(BITS),
1500
+ ZERO: _0n2,
1501
+ ONE: _1n2,
1502
+ create: (num) => mod(num, ORDER),
1503
+ isValid: (num) => {
1504
+ if (typeof num !== "bigint")
1505
+ throw new Error("invalid field element: expected bigint, got " + typeof num);
1506
+ return _0n2 <= num && num < ORDER;
1507
+ },
1508
+ is0: (num) => num === _0n2,
1509
+ isOdd: (num) => (num & _1n2) === _1n2,
1510
+ neg: (num) => mod(-num, ORDER),
1511
+ eql: (lhs, rhs) => lhs === rhs,
1512
+ sqr: (num) => mod(num * num, ORDER),
1513
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
1514
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
1515
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
1516
+ pow: (num, power) => FpPow(f, num, power),
1517
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
1518
+ // Same as above, but doesn't normalize
1519
+ sqrN: (num) => num * num,
1520
+ addN: (lhs, rhs) => lhs + rhs,
1521
+ subN: (lhs, rhs) => lhs - rhs,
1522
+ mulN: (lhs, rhs) => lhs * rhs,
1523
+ inv: (num) => invert(num, ORDER),
1524
+ sqrt: redef.sqrt || ((n) => {
1525
+ if (!sqrtP)
1526
+ sqrtP = FpSqrt(ORDER);
1527
+ return sqrtP(f, n);
1528
+ }),
1529
+ toBytes: (num) => isLE2 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
1530
+ fromBytes: (bytes) => {
1531
+ if (bytes.length !== BYTES)
1532
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
1533
+ return isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1534
+ },
1535
+ // TODO: we don't need it here, move out to separate fn
1536
+ invertBatch: (lst) => FpInvertBatch(f, lst),
1537
+ // We can't move this out because Fp6, Fp12 implement it
1538
+ // and it's unclear what to return in there.
1539
+ cmov: (a, b, c) => c ? b : a
1540
+ });
1541
+ return Object.freeze(f);
1542
+ }
1543
+ function getFieldBytesLength(fieldOrder) {
1544
+ if (typeof fieldOrder !== "bigint")
1545
+ throw new Error("field order must be bigint");
1546
+ const bitLength = fieldOrder.toString(2).length;
1547
+ return Math.ceil(bitLength / 8);
1548
+ }
1549
+ function getMinHashLength(fieldOrder) {
1550
+ const length = getFieldBytesLength(fieldOrder);
1551
+ return length + Math.ceil(length / 2);
1552
+ }
1553
+ function mapHashToField(key, fieldOrder, isLE2 = false) {
1554
+ const len = key.length;
1555
+ const fieldLen = getFieldBytesLength(fieldOrder);
1556
+ const minLen = getMinHashLength(fieldOrder);
1557
+ if (len < 16 || len < minLen || len > 1024)
1558
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
1559
+ const num = isLE2 ? bytesToNumberLE(key) : bytesToNumberBE(key);
1560
+ const reduced = mod(num, fieldOrder - _1n2) + _1n2;
1561
+ return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
1562
+ }
1563
+
1564
+ // node_modules/@noble/curves/esm/abstract/curve.js
1565
+ var _0n3 = BigInt(0);
1566
+ var _1n3 = BigInt(1);
1567
+ function constTimeNegate(condition, item) {
1568
+ const neg = item.negate();
1569
+ return condition ? neg : item;
1570
+ }
1571
+ function validateW(W, bits) {
1572
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
1573
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
1574
+ }
1575
+ function calcWOpts(W, scalarBits) {
1576
+ validateW(W, scalarBits);
1577
+ const windows = Math.ceil(scalarBits / W) + 1;
1578
+ const windowSize = 2 ** (W - 1);
1579
+ const maxNumber = 2 ** W;
1580
+ const mask = bitMask(W);
1581
+ const shiftBy = BigInt(W);
1582
+ return { windows, windowSize, mask, maxNumber, shiftBy };
1583
+ }
1584
+ function calcOffsets(n, window, wOpts) {
1585
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
1586
+ let wbits = Number(n & mask);
1587
+ let nextN = n >> shiftBy;
1588
+ if (wbits > windowSize) {
1589
+ wbits -= maxNumber;
1590
+ nextN += _1n3;
1591
+ }
1592
+ const offsetStart = window * windowSize;
1593
+ const offset = offsetStart + Math.abs(wbits) - 1;
1594
+ const isZero = wbits === 0;
1595
+ const isNeg = wbits < 0;
1596
+ const isNegF = window % 2 !== 0;
1597
+ const offsetF = offsetStart;
1598
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
1599
+ }
1600
+ function validateMSMPoints(points, c) {
1601
+ if (!Array.isArray(points))
1602
+ throw new Error("array expected");
1603
+ points.forEach((p, i) => {
1604
+ if (!(p instanceof c))
1605
+ throw new Error("invalid point at index " + i);
1606
+ });
1607
+ }
1608
+ function validateMSMScalars(scalars, field) {
1609
+ if (!Array.isArray(scalars))
1610
+ throw new Error("array of scalars expected");
1611
+ scalars.forEach((s, i) => {
1612
+ if (!field.isValid(s))
1613
+ throw new Error("invalid scalar at index " + i);
1614
+ });
1615
+ }
1616
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
1617
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
1618
+ function getW(P) {
1619
+ return pointWindowSizes.get(P) || 1;
1620
+ }
1621
+ function wNAF(c, bits) {
1622
+ return {
1623
+ constTimeNegate,
1624
+ hasPrecomputes(elm) {
1625
+ return getW(elm) !== 1;
1626
+ },
1627
+ // non-const time multiplication ladder
1628
+ unsafeLadder(elm, n, p = c.ZERO) {
1629
+ let d = elm;
1630
+ while (n > _0n3) {
1631
+ if (n & _1n3)
1632
+ p = p.add(d);
1633
+ d = d.double();
1634
+ n >>= _1n3;
1635
+ }
1636
+ return p;
1637
+ },
1638
+ /**
1639
+ * Creates a wNAF precomputation window. Used for caching.
1640
+ * Default window size is set by `utils.precompute()` and is equal to 8.
1641
+ * Number of precomputed points depends on the curve size:
1642
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1643
+ * - 𝑊 is the window size
1644
+ * - 𝑛 is the bitlength of the curve order.
1645
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1646
+ * @param elm Point instance
1647
+ * @param W window size
1648
+ * @returns precomputed point tables flattened to a single array
1649
+ */
1650
+ precomputeWindow(elm, W) {
1651
+ const { windows, windowSize } = calcWOpts(W, bits);
1652
+ const points = [];
1653
+ let p = elm;
1654
+ let base = p;
1655
+ for (let window = 0; window < windows; window++) {
1656
+ base = p;
1657
+ points.push(base);
1658
+ for (let i = 1; i < windowSize; i++) {
1659
+ base = base.add(p);
1660
+ points.push(base);
1661
+ }
1662
+ p = base.double();
1663
+ }
1664
+ return points;
1665
+ },
1666
+ /**
1667
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1668
+ * @param W window size
1669
+ * @param precomputes precomputed tables
1670
+ * @param n scalar (we don't check here, but should be less than curve order)
1671
+ * @returns real and fake (for const-time) points
1672
+ */
1673
+ wNAF(W, precomputes, n) {
1674
+ let p = c.ZERO;
1675
+ let f = c.BASE;
1676
+ const wo = calcWOpts(W, bits);
1677
+ for (let window = 0; window < wo.windows; window++) {
1678
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
1679
+ n = nextN;
1680
+ if (isZero) {
1681
+ f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));
1682
+ } else {
1683
+ p = p.add(constTimeNegate(isNeg, precomputes[offset]));
1684
+ }
1685
+ }
1686
+ return { p, f };
1687
+ },
1688
+ /**
1689
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
1690
+ * @param W window size
1691
+ * @param precomputes precomputed tables
1692
+ * @param n scalar (we don't check here, but should be less than curve order)
1693
+ * @param acc accumulator point to add result of multiplication
1694
+ * @returns point
1695
+ */
1696
+ wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
1697
+ const wo = calcWOpts(W, bits);
1698
+ for (let window = 0; window < wo.windows; window++) {
1699
+ if (n === _0n3)
1700
+ break;
1701
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
1702
+ n = nextN;
1703
+ if (isZero) {
1704
+ continue;
1705
+ } else {
1706
+ const item = precomputes[offset];
1707
+ acc = acc.add(isNeg ? item.negate() : item);
1708
+ }
1709
+ }
1710
+ return acc;
1711
+ },
1712
+ getPrecomputes(W, P, transform) {
1713
+ let comp = pointPrecomputes.get(P);
1714
+ if (!comp) {
1715
+ comp = this.precomputeWindow(P, W);
1716
+ if (W !== 1)
1717
+ pointPrecomputes.set(P, transform(comp));
1718
+ }
1719
+ return comp;
1720
+ },
1721
+ wNAFCached(P, n, transform) {
1722
+ const W = getW(P);
1723
+ return this.wNAF(W, this.getPrecomputes(W, P, transform), n);
1724
+ },
1725
+ wNAFCachedUnsafe(P, n, transform, prev) {
1726
+ const W = getW(P);
1727
+ if (W === 1)
1728
+ return this.unsafeLadder(P, n, prev);
1729
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);
1730
+ },
1731
+ // We calculate precomputes for elliptic curve point multiplication
1732
+ // using windowed method. This specifies window size and
1733
+ // stores precomputed values. Usually only base point would be precomputed.
1734
+ setWindowSize(P, W) {
1735
+ validateW(W, bits);
1736
+ pointWindowSizes.set(P, W);
1737
+ pointPrecomputes.delete(P);
1738
+ }
1739
+ };
1740
+ }
1741
+ function pippenger(c, fieldN, points, scalars) {
1742
+ validateMSMPoints(points, c);
1743
+ validateMSMScalars(scalars, fieldN);
1744
+ const plength = points.length;
1745
+ const slength = scalars.length;
1746
+ if (plength !== slength)
1747
+ throw new Error("arrays of points and scalars must have equal length");
1748
+ const zero = c.ZERO;
1749
+ const wbits = bitLen(BigInt(plength));
1750
+ let windowSize = 1;
1751
+ if (wbits > 12)
1752
+ windowSize = wbits - 3;
1753
+ else if (wbits > 4)
1754
+ windowSize = wbits - 2;
1755
+ else if (wbits > 0)
1756
+ windowSize = 2;
1757
+ const MASK = bitMask(windowSize);
1758
+ const buckets = new Array(Number(MASK) + 1).fill(zero);
1759
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
1760
+ let sum = zero;
1761
+ for (let i = lastBits; i >= 0; i -= windowSize) {
1762
+ buckets.fill(zero);
1763
+ for (let j = 0; j < slength; j++) {
1764
+ const scalar = scalars[j];
1765
+ const wbits2 = Number(scalar >> BigInt(i) & MASK);
1766
+ buckets[wbits2] = buckets[wbits2].add(points[j]);
1767
+ }
1768
+ let resI = zero;
1769
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
1770
+ sumI = sumI.add(buckets[j]);
1771
+ resI = resI.add(sumI);
1772
+ }
1773
+ sum = sum.add(resI);
1774
+ if (i !== 0)
1775
+ for (let j = 0; j < windowSize; j++)
1776
+ sum = sum.double();
1777
+ }
1778
+ return sum;
1779
+ }
1780
+ function validateBasic(curve) {
1781
+ validateField(curve.Fp);
1782
+ validateObject(curve, {
1783
+ n: "bigint",
1784
+ h: "bigint",
1785
+ Gx: "field",
1786
+ Gy: "field"
1787
+ }, {
1788
+ nBitLength: "isSafeInteger",
1789
+ nByteLength: "isSafeInteger"
1790
+ });
1791
+ return Object.freeze({
1792
+ ...nLength(curve.n, curve.nBitLength),
1793
+ ...curve,
1794
+ ...{ p: curve.Fp.ORDER }
1795
+ });
1796
+ }
1797
+
1798
+ // node_modules/@noble/curves/esm/abstract/weierstrass.js
1799
+ function validateSigVerOpts(opts) {
1800
+ if (opts.lowS !== void 0)
1801
+ abool("lowS", opts.lowS);
1802
+ if (opts.prehash !== void 0)
1803
+ abool("prehash", opts.prehash);
1804
+ }
1805
+ function validatePointOpts(curve) {
1806
+ const opts = validateBasic(curve);
1807
+ validateObject(opts, {
1808
+ a: "field",
1809
+ b: "field"
1810
+ }, {
1811
+ allowInfinityPoint: "boolean",
1812
+ allowedPrivateKeyLengths: "array",
1813
+ clearCofactor: "function",
1814
+ fromBytes: "function",
1815
+ isTorsionFree: "function",
1816
+ toBytes: "function",
1817
+ wrapPrivateKey: "boolean"
1818
+ });
1819
+ const { endo, Fp, a } = opts;
1820
+ if (endo) {
1821
+ if (!Fp.eql(a, Fp.ZERO)) {
1822
+ throw new Error("invalid endo: CURVE.a must be 0");
1823
+ }
1824
+ if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") {
1825
+ throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');
1826
+ }
1827
+ }
1828
+ return Object.freeze({ ...opts });
1829
+ }
1830
+ var DERErr = class extends Error {
1831
+ constructor(m = "") {
1832
+ super(m);
1833
+ }
1834
+ };
1835
+ var DER = {
1836
+ // asn.1 DER encoding utils
1837
+ Err: DERErr,
1838
+ // Basic building block is TLV (Tag-Length-Value)
1839
+ _tlv: {
1840
+ encode: (tag, data) => {
1841
+ const { Err: E } = DER;
1842
+ if (tag < 0 || tag > 256)
1843
+ throw new E("tlv.encode: wrong tag");
1844
+ if (data.length & 1)
1845
+ throw new E("tlv.encode: unpadded data");
1846
+ const dataLen = data.length / 2;
1847
+ const len = numberToHexUnpadded(dataLen);
1848
+ if (len.length / 2 & 128)
1849
+ throw new E("tlv.encode: long form length too big");
1850
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
1851
+ const t = numberToHexUnpadded(tag);
1852
+ return t + lenLen + len + data;
1853
+ },
1854
+ // v - value, l - left bytes (unparsed)
1855
+ decode(tag, data) {
1856
+ const { Err: E } = DER;
1857
+ let pos = 0;
1858
+ if (tag < 0 || tag > 256)
1859
+ throw new E("tlv.encode: wrong tag");
1860
+ if (data.length < 2 || data[pos++] !== tag)
1861
+ throw new E("tlv.decode: wrong tlv");
1862
+ const first = data[pos++];
1863
+ const isLong = !!(first & 128);
1864
+ let length = 0;
1865
+ if (!isLong)
1866
+ length = first;
1867
+ else {
1868
+ const lenLen = first & 127;
1869
+ if (!lenLen)
1870
+ throw new E("tlv.decode(long): indefinite length not supported");
1871
+ if (lenLen > 4)
1872
+ throw new E("tlv.decode(long): byte length is too big");
1873
+ const lengthBytes = data.subarray(pos, pos + lenLen);
1874
+ if (lengthBytes.length !== lenLen)
1875
+ throw new E("tlv.decode: length bytes not complete");
1876
+ if (lengthBytes[0] === 0)
1877
+ throw new E("tlv.decode(long): zero leftmost byte");
1878
+ for (const b of lengthBytes)
1879
+ length = length << 8 | b;
1880
+ pos += lenLen;
1881
+ if (length < 128)
1882
+ throw new E("tlv.decode(long): not minimal encoding");
1883
+ }
1884
+ const v = data.subarray(pos, pos + length);
1885
+ if (v.length !== length)
1886
+ throw new E("tlv.decode: wrong value length");
1887
+ return { v, l: data.subarray(pos + length) };
1888
+ }
1889
+ },
1890
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
1891
+ // since we always use positive integers here. It must always be empty:
1892
+ // - add zero byte if exists
1893
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
1894
+ _int: {
1895
+ encode(num) {
1896
+ const { Err: E } = DER;
1897
+ if (num < _0n4)
1898
+ throw new E("integer: negative integers are not allowed");
1899
+ let hex = numberToHexUnpadded(num);
1900
+ if (Number.parseInt(hex[0], 16) & 8)
1901
+ hex = "00" + hex;
1902
+ if (hex.length & 1)
1903
+ throw new E("unexpected DER parsing assertion: unpadded hex");
1904
+ return hex;
1905
+ },
1906
+ decode(data) {
1907
+ const { Err: E } = DER;
1908
+ if (data[0] & 128)
1909
+ throw new E("invalid signature integer: negative");
1910
+ if (data[0] === 0 && !(data[1] & 128))
1911
+ throw new E("invalid signature integer: unnecessary leading zero");
1912
+ return bytesToNumberBE(data);
1913
+ }
1914
+ },
1915
+ toSig(hex) {
1916
+ const { Err: E, _int: int, _tlv: tlv } = DER;
1917
+ const data = ensureBytes("signature", hex);
1918
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
1919
+ if (seqLeftBytes.length)
1920
+ throw new E("invalid signature: left bytes after parsing");
1921
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
1922
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
1923
+ if (sLeftBytes.length)
1924
+ throw new E("invalid signature: left bytes after parsing");
1925
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
1926
+ },
1927
+ hexFromSig(sig) {
1928
+ const { _tlv: tlv, _int: int } = DER;
1929
+ const rs = tlv.encode(2, int.encode(sig.r));
1930
+ const ss = tlv.encode(2, int.encode(sig.s));
1931
+ const seq = rs + ss;
1932
+ return tlv.encode(48, seq);
1933
+ }
1934
+ };
1935
+ function numToSizedHex(num, size) {
1936
+ return bytesToHex(numberToBytesBE(num, size));
1937
+ }
1938
+ var _0n4 = BigInt(0);
1939
+ var _1n4 = BigInt(1);
1940
+ var _2n2 = BigInt(2);
1941
+ var _3n2 = BigInt(3);
1942
+ var _4n2 = BigInt(4);
1943
+ function weierstrassPoints(opts) {
1944
+ const CURVE = validatePointOpts(opts);
1945
+ const { Fp } = CURVE;
1946
+ const Fn = Field(CURVE.n, CURVE.nBitLength);
1947
+ const toBytes2 = CURVE.toBytes || ((_c, point, _isCompressed) => {
1948
+ const a = point.toAffine();
1949
+ return concatBytes3(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y));
1950
+ });
1951
+ const fromBytes = CURVE.fromBytes || ((bytes) => {
1952
+ const tail = bytes.subarray(1);
1953
+ const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
1954
+ const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
1955
+ return { x, y };
1956
+ });
1957
+ function weierstrassEquation(x) {
1958
+ const { a, b } = CURVE;
1959
+ const x2 = Fp.sqr(x);
1960
+ const x3 = Fp.mul(x2, x);
1961
+ return Fp.add(Fp.add(x3, Fp.mul(x, a)), b);
1962
+ }
1963
+ function isValidXY(x, y) {
1964
+ const left = Fp.sqr(y);
1965
+ const right = weierstrassEquation(x);
1966
+ return Fp.eql(left, right);
1967
+ }
1968
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
1969
+ throw new Error("bad curve params: generator point");
1970
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
1971
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
1972
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
1973
+ throw new Error("bad curve params: a or b");
1974
+ function isWithinCurveOrder(num) {
1975
+ return inRange(num, _1n4, CURVE.n);
1976
+ }
1977
+ function normPrivateKeyToScalar(key) {
1978
+ const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;
1979
+ if (lengths && typeof key !== "bigint") {
1980
+ if (isBytes3(key))
1981
+ key = bytesToHex(key);
1982
+ if (typeof key !== "string" || !lengths.includes(key.length))
1983
+ throw new Error("invalid private key");
1984
+ key = key.padStart(nByteLength * 2, "0");
1985
+ }
1986
+ let num;
1987
+ try {
1988
+ num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength));
1989
+ } catch (error) {
1990
+ throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key);
1991
+ }
1992
+ if (wrapPrivateKey)
1993
+ num = mod(num, N);
1994
+ aInRange("private key", num, _1n4, N);
1995
+ return num;
1996
+ }
1997
+ function aprjpoint(other) {
1998
+ if (!(other instanceof Point))
1999
+ throw new Error("ProjectivePoint expected");
2000
+ }
2001
+ const toAffineMemo = memoized((p, iz) => {
2002
+ const { px: x, py: y, pz: z5 } = p;
2003
+ if (Fp.eql(z5, Fp.ONE))
2004
+ return { x, y };
2005
+ const is0 = p.is0();
2006
+ if (iz == null)
2007
+ iz = is0 ? Fp.ONE : Fp.inv(z5);
2008
+ const ax = Fp.mul(x, iz);
2009
+ const ay = Fp.mul(y, iz);
2010
+ const zz = Fp.mul(z5, iz);
2011
+ if (is0)
2012
+ return { x: Fp.ZERO, y: Fp.ZERO };
2013
+ if (!Fp.eql(zz, Fp.ONE))
2014
+ throw new Error("invZ was invalid");
2015
+ return { x: ax, y: ay };
2016
+ });
2017
+ const assertValidMemo = memoized((p) => {
2018
+ if (p.is0()) {
2019
+ if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
2020
+ return;
2021
+ throw new Error("bad point: ZERO");
2022
+ }
2023
+ const { x, y } = p.toAffine();
2024
+ if (!Fp.isValid(x) || !Fp.isValid(y))
2025
+ throw new Error("bad point: x or y not FE");
2026
+ if (!isValidXY(x, y))
2027
+ throw new Error("bad point: equation left != right");
2028
+ if (!p.isTorsionFree())
2029
+ throw new Error("bad point: not in prime-order subgroup");
2030
+ return true;
2031
+ });
2032
+ class Point {
2033
+ constructor(px, py, pz) {
2034
+ if (px == null || !Fp.isValid(px))
2035
+ throw new Error("x required");
2036
+ if (py == null || !Fp.isValid(py) || Fp.is0(py))
2037
+ throw new Error("y required");
2038
+ if (pz == null || !Fp.isValid(pz))
2039
+ throw new Error("z required");
2040
+ this.px = px;
2041
+ this.py = py;
2042
+ this.pz = pz;
2043
+ Object.freeze(this);
2044
+ }
2045
+ // Does not validate if the point is on-curve.
2046
+ // Use fromHex instead, or call assertValidity() later.
2047
+ static fromAffine(p) {
2048
+ const { x, y } = p || {};
2049
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
2050
+ throw new Error("invalid affine point");
2051
+ if (p instanceof Point)
2052
+ throw new Error("projective point not allowed");
2053
+ const is0 = (i) => Fp.eql(i, Fp.ZERO);
2054
+ if (is0(x) && is0(y))
2055
+ return Point.ZERO;
2056
+ return new Point(x, y, Fp.ONE);
2057
+ }
2058
+ get x() {
2059
+ return this.toAffine().x;
2060
+ }
2061
+ get y() {
2062
+ return this.toAffine().y;
2063
+ }
2064
+ /**
2065
+ * Takes a bunch of Projective Points but executes only one
2066
+ * inversion on all of them. Inversion is very slow operation,
2067
+ * so this improves performance massively.
2068
+ * Optimization: converts a list of projective points to a list of identical points with Z=1.
2069
+ */
2070
+ static normalizeZ(points) {
2071
+ const toInv = FpInvertBatch(Fp, points.map((p) => p.pz));
2072
+ return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
2073
+ }
2074
+ /**
2075
+ * Converts hash string or Uint8Array to Point.
2076
+ * @param hex short/long ECDSA hex
2077
+ */
2078
+ static fromHex(hex) {
2079
+ const P = Point.fromAffine(fromBytes(ensureBytes("pointHex", hex)));
2080
+ P.assertValidity();
2081
+ return P;
2082
+ }
2083
+ // Multiplies generator point by privateKey.
2084
+ static fromPrivateKey(privateKey) {
2085
+ return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
2086
+ }
2087
+ // Multiscalar Multiplication
2088
+ static msm(points, scalars) {
2089
+ return pippenger(Point, Fn, points, scalars);
2090
+ }
2091
+ // "Private method", don't use it directly
2092
+ _setWindowSize(windowSize) {
2093
+ wnaf.setWindowSize(this, windowSize);
2094
+ }
2095
+ // A point on curve is valid if it conforms to equation.
2096
+ assertValidity() {
2097
+ assertValidMemo(this);
2098
+ }
2099
+ hasEvenY() {
2100
+ const { y } = this.toAffine();
2101
+ if (Fp.isOdd)
2102
+ return !Fp.isOdd(y);
2103
+ throw new Error("Field doesn't support isOdd");
2104
+ }
2105
+ /**
2106
+ * Compare one point to another.
2107
+ */
2108
+ equals(other) {
2109
+ aprjpoint(other);
2110
+ const { px: X1, py: Y1, pz: Z1 } = this;
2111
+ const { px: X2, py: Y2, pz: Z2 } = other;
2112
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
2113
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
2114
+ return U1 && U2;
2115
+ }
2116
+ /**
2117
+ * Flips point to one corresponding to (x, -y) in Affine coordinates.
2118
+ */
2119
+ negate() {
2120
+ return new Point(this.px, Fp.neg(this.py), this.pz);
2121
+ }
2122
+ // Renes-Costello-Batina exception-free doubling formula.
2123
+ // There is 30% faster Jacobian formula, but it is not complete.
2124
+ // https://eprint.iacr.org/2015/1060, algorithm 3
2125
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
2126
+ double() {
2127
+ const { a, b } = CURVE;
2128
+ const b3 = Fp.mul(b, _3n2);
2129
+ const { px: X1, py: Y1, pz: Z1 } = this;
2130
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
2131
+ let t0 = Fp.mul(X1, X1);
2132
+ let t1 = Fp.mul(Y1, Y1);
2133
+ let t2 = Fp.mul(Z1, Z1);
2134
+ let t3 = Fp.mul(X1, Y1);
2135
+ t3 = Fp.add(t3, t3);
2136
+ Z3 = Fp.mul(X1, Z1);
2137
+ Z3 = Fp.add(Z3, Z3);
2138
+ X3 = Fp.mul(a, Z3);
2139
+ Y3 = Fp.mul(b3, t2);
2140
+ Y3 = Fp.add(X3, Y3);
2141
+ X3 = Fp.sub(t1, Y3);
2142
+ Y3 = Fp.add(t1, Y3);
2143
+ Y3 = Fp.mul(X3, Y3);
2144
+ X3 = Fp.mul(t3, X3);
2145
+ Z3 = Fp.mul(b3, Z3);
2146
+ t2 = Fp.mul(a, t2);
2147
+ t3 = Fp.sub(t0, t2);
2148
+ t3 = Fp.mul(a, t3);
2149
+ t3 = Fp.add(t3, Z3);
2150
+ Z3 = Fp.add(t0, t0);
2151
+ t0 = Fp.add(Z3, t0);
2152
+ t0 = Fp.add(t0, t2);
2153
+ t0 = Fp.mul(t0, t3);
2154
+ Y3 = Fp.add(Y3, t0);
2155
+ t2 = Fp.mul(Y1, Z1);
2156
+ t2 = Fp.add(t2, t2);
2157
+ t0 = Fp.mul(t2, t3);
2158
+ X3 = Fp.sub(X3, t0);
2159
+ Z3 = Fp.mul(t2, t1);
2160
+ Z3 = Fp.add(Z3, Z3);
2161
+ Z3 = Fp.add(Z3, Z3);
2162
+ return new Point(X3, Y3, Z3);
2163
+ }
2164
+ // Renes-Costello-Batina exception-free addition formula.
2165
+ // There is 30% faster Jacobian formula, but it is not complete.
2166
+ // https://eprint.iacr.org/2015/1060, algorithm 1
2167
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
2168
+ add(other) {
2169
+ aprjpoint(other);
2170
+ const { px: X1, py: Y1, pz: Z1 } = this;
2171
+ const { px: X2, py: Y2, pz: Z2 } = other;
2172
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
2173
+ const a = CURVE.a;
2174
+ const b3 = Fp.mul(CURVE.b, _3n2);
2175
+ let t0 = Fp.mul(X1, X2);
2176
+ let t1 = Fp.mul(Y1, Y2);
2177
+ let t2 = Fp.mul(Z1, Z2);
2178
+ let t3 = Fp.add(X1, Y1);
2179
+ let t4 = Fp.add(X2, Y2);
2180
+ t3 = Fp.mul(t3, t4);
2181
+ t4 = Fp.add(t0, t1);
2182
+ t3 = Fp.sub(t3, t4);
2183
+ t4 = Fp.add(X1, Z1);
2184
+ let t5 = Fp.add(X2, Z2);
2185
+ t4 = Fp.mul(t4, t5);
2186
+ t5 = Fp.add(t0, t2);
2187
+ t4 = Fp.sub(t4, t5);
2188
+ t5 = Fp.add(Y1, Z1);
2189
+ X3 = Fp.add(Y2, Z2);
2190
+ t5 = Fp.mul(t5, X3);
2191
+ X3 = Fp.add(t1, t2);
2192
+ t5 = Fp.sub(t5, X3);
2193
+ Z3 = Fp.mul(a, t4);
2194
+ X3 = Fp.mul(b3, t2);
2195
+ Z3 = Fp.add(X3, Z3);
2196
+ X3 = Fp.sub(t1, Z3);
2197
+ Z3 = Fp.add(t1, Z3);
2198
+ Y3 = Fp.mul(X3, Z3);
2199
+ t1 = Fp.add(t0, t0);
2200
+ t1 = Fp.add(t1, t0);
2201
+ t2 = Fp.mul(a, t2);
2202
+ t4 = Fp.mul(b3, t4);
2203
+ t1 = Fp.add(t1, t2);
2204
+ t2 = Fp.sub(t0, t2);
2205
+ t2 = Fp.mul(a, t2);
2206
+ t4 = Fp.add(t4, t2);
2207
+ t0 = Fp.mul(t1, t4);
2208
+ Y3 = Fp.add(Y3, t0);
2209
+ t0 = Fp.mul(t5, t4);
2210
+ X3 = Fp.mul(t3, X3);
2211
+ X3 = Fp.sub(X3, t0);
2212
+ t0 = Fp.mul(t3, t1);
2213
+ Z3 = Fp.mul(t5, Z3);
2214
+ Z3 = Fp.add(Z3, t0);
2215
+ return new Point(X3, Y3, Z3);
2216
+ }
2217
+ subtract(other) {
2218
+ return this.add(other.negate());
2219
+ }
2220
+ is0() {
2221
+ return this.equals(Point.ZERO);
2222
+ }
2223
+ wNAF(n) {
2224
+ return wnaf.wNAFCached(this, n, Point.normalizeZ);
2225
+ }
2226
+ /**
2227
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
2228
+ * It's faster, but should only be used when you don't care about
2229
+ * an exposed private key e.g. sig verification, which works over *public* keys.
2230
+ */
2231
+ multiplyUnsafe(sc) {
2232
+ const { endo: endo2, n: N } = CURVE;
2233
+ aInRange("scalar", sc, _0n4, N);
2234
+ const I = Point.ZERO;
2235
+ if (sc === _0n4)
2236
+ return I;
2237
+ if (this.is0() || sc === _1n4)
2238
+ return this;
2239
+ if (!endo2 || wnaf.hasPrecomputes(this))
2240
+ return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);
2241
+ let { k1neg, k1, k2neg, k2 } = endo2.splitScalar(sc);
2242
+ let k1p = I;
2243
+ let k2p = I;
2244
+ let d = this;
2245
+ while (k1 > _0n4 || k2 > _0n4) {
2246
+ if (k1 & _1n4)
2247
+ k1p = k1p.add(d);
2248
+ if (k2 & _1n4)
2249
+ k2p = k2p.add(d);
2250
+ d = d.double();
2251
+ k1 >>= _1n4;
2252
+ k2 >>= _1n4;
2253
+ }
2254
+ if (k1neg)
2255
+ k1p = k1p.negate();
2256
+ if (k2neg)
2257
+ k2p = k2p.negate();
2258
+ k2p = new Point(Fp.mul(k2p.px, endo2.beta), k2p.py, k2p.pz);
2259
+ return k1p.add(k2p);
2260
+ }
2261
+ /**
2262
+ * Constant time multiplication.
2263
+ * Uses wNAF method. Windowed method may be 10% faster,
2264
+ * but takes 2x longer to generate and consumes 2x memory.
2265
+ * Uses precomputes when available.
2266
+ * Uses endomorphism for Koblitz curves.
2267
+ * @param scalar by which the point would be multiplied
2268
+ * @returns New point
2269
+ */
2270
+ multiply(scalar) {
2271
+ const { endo: endo2, n: N } = CURVE;
2272
+ aInRange("scalar", scalar, _1n4, N);
2273
+ let point, fake;
2274
+ if (endo2) {
2275
+ const { k1neg, k1, k2neg, k2 } = endo2.splitScalar(scalar);
2276
+ let { p: k1p, f: f1p } = this.wNAF(k1);
2277
+ let { p: k2p, f: f2p } = this.wNAF(k2);
2278
+ k1p = wnaf.constTimeNegate(k1neg, k1p);
2279
+ k2p = wnaf.constTimeNegate(k2neg, k2p);
2280
+ k2p = new Point(Fp.mul(k2p.px, endo2.beta), k2p.py, k2p.pz);
2281
+ point = k1p.add(k2p);
2282
+ fake = f1p.add(f2p);
2283
+ } else {
2284
+ const { p, f } = this.wNAF(scalar);
2285
+ point = p;
2286
+ fake = f;
2287
+ }
2288
+ return Point.normalizeZ([point, fake])[0];
2289
+ }
2290
+ /**
2291
+ * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
2292
+ * Not using Strauss-Shamir trick: precomputation tables are faster.
2293
+ * The trick could be useful if both P and Q are not G (not in our case).
2294
+ * @returns non-zero affine point
2295
+ */
2296
+ multiplyAndAddUnsafe(Q, a, b) {
2297
+ const G = Point.BASE;
2298
+ const mul3 = (P, a2) => a2 === _0n4 || a2 === _1n4 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2);
2299
+ const sum = mul3(this, a).add(mul3(Q, b));
2300
+ return sum.is0() ? void 0 : sum;
2301
+ }
2302
+ // Converts Projective point to affine (x, y) coordinates.
2303
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
2304
+ // (x, y, z) ∋ (x=x/z, y=y/z)
2305
+ toAffine(iz) {
2306
+ return toAffineMemo(this, iz);
2307
+ }
2308
+ isTorsionFree() {
2309
+ const { h: cofactor, isTorsionFree } = CURVE;
2310
+ if (cofactor === _1n4)
2311
+ return true;
2312
+ if (isTorsionFree)
2313
+ return isTorsionFree(Point, this);
2314
+ throw new Error("isTorsionFree() has not been declared for the elliptic curve");
2315
+ }
2316
+ clearCofactor() {
2317
+ const { h: cofactor, clearCofactor } = CURVE;
2318
+ if (cofactor === _1n4)
2319
+ return this;
2320
+ if (clearCofactor)
2321
+ return clearCofactor(Point, this);
2322
+ return this.multiplyUnsafe(CURVE.h);
2323
+ }
2324
+ toRawBytes(isCompressed = true) {
2325
+ abool("isCompressed", isCompressed);
2326
+ this.assertValidity();
2327
+ return toBytes2(Point, this, isCompressed);
2328
+ }
2329
+ toHex(isCompressed = true) {
2330
+ abool("isCompressed", isCompressed);
2331
+ return bytesToHex(this.toRawBytes(isCompressed));
2332
+ }
2333
+ }
2334
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
2335
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
2336
+ const { endo, nBitLength } = CURVE;
2337
+ const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);
2338
+ return {
2339
+ CURVE,
2340
+ ProjectivePoint: Point,
2341
+ normPrivateKeyToScalar,
2342
+ weierstrassEquation,
2343
+ isWithinCurveOrder
2344
+ };
2345
+ }
2346
+ function validateOpts(curve) {
2347
+ const opts = validateBasic(curve);
2348
+ validateObject(opts, {
2349
+ hash: "hash",
2350
+ hmac: "function",
2351
+ randomBytes: "function"
2352
+ }, {
2353
+ bits2int: "function",
2354
+ bits2int_modN: "function",
2355
+ lowS: "boolean"
2356
+ });
2357
+ return Object.freeze({ lowS: true, ...opts });
2358
+ }
2359
+ function weierstrass(curveDef) {
2360
+ const CURVE = validateOpts(curveDef);
2361
+ const { Fp, n: CURVE_ORDER, nByteLength, nBitLength } = CURVE;
2362
+ const compressedLen = Fp.BYTES + 1;
2363
+ const uncompressedLen = 2 * Fp.BYTES + 1;
2364
+ function modN(a) {
2365
+ return mod(a, CURVE_ORDER);
2366
+ }
2367
+ function invN(a) {
2368
+ return invert(a, CURVE_ORDER);
2369
+ }
2370
+ const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({
2371
+ ...CURVE,
2372
+ toBytes(_c, point, isCompressed) {
2373
+ const a = point.toAffine();
2374
+ const x = Fp.toBytes(a.x);
2375
+ const cat = concatBytes3;
2376
+ abool("isCompressed", isCompressed);
2377
+ if (isCompressed) {
2378
+ return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
2379
+ } else {
2380
+ return cat(Uint8Array.from([4]), x, Fp.toBytes(a.y));
2381
+ }
2382
+ },
2383
+ fromBytes(bytes) {
2384
+ const len = bytes.length;
2385
+ const head = bytes[0];
2386
+ const tail = bytes.subarray(1);
2387
+ if (len === compressedLen && (head === 2 || head === 3)) {
2388
+ const x = bytesToNumberBE(tail);
2389
+ if (!inRange(x, _1n4, Fp.ORDER))
2390
+ throw new Error("Point is not on curve");
2391
+ const y2 = weierstrassEquation(x);
2392
+ let y;
2393
+ try {
2394
+ y = Fp.sqrt(y2);
2395
+ } catch (sqrtError) {
2396
+ const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : "";
2397
+ throw new Error("Point is not on curve" + suffix);
2398
+ }
2399
+ const isYOdd = (y & _1n4) === _1n4;
2400
+ const isHeadOdd = (head & 1) === 1;
2401
+ if (isHeadOdd !== isYOdd)
2402
+ y = Fp.neg(y);
2403
+ return { x, y };
2404
+ } else if (len === uncompressedLen && head === 4) {
2405
+ const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
2406
+ const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
2407
+ return { x, y };
2408
+ } else {
2409
+ const cl = compressedLen;
2410
+ const ul = uncompressedLen;
2411
+ throw new Error("invalid Point, expected length of " + cl + ", or uncompressed " + ul + ", got " + len);
2412
+ }
2413
+ }
2414
+ });
2415
+ function isBiggerThanHalfOrder(number) {
2416
+ const HALF = CURVE_ORDER >> _1n4;
2417
+ return number > HALF;
2418
+ }
2419
+ function normalizeS(s) {
2420
+ return isBiggerThanHalfOrder(s) ? modN(-s) : s;
2421
+ }
2422
+ const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
2423
+ class Signature {
2424
+ constructor(r, s, recovery) {
2425
+ aInRange("r", r, _1n4, CURVE_ORDER);
2426
+ aInRange("s", s, _1n4, CURVE_ORDER);
2427
+ this.r = r;
2428
+ this.s = s;
2429
+ if (recovery != null)
2430
+ this.recovery = recovery;
2431
+ Object.freeze(this);
2432
+ }
2433
+ // pair (bytes of r, bytes of s)
2434
+ static fromCompact(hex) {
2435
+ const l = nByteLength;
2436
+ hex = ensureBytes("compactSignature", hex, l * 2);
2437
+ return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
2438
+ }
2439
+ // DER encoded ECDSA signature
2440
+ // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
2441
+ static fromDER(hex) {
2442
+ const { r, s } = DER.toSig(ensureBytes("DER", hex));
2443
+ return new Signature(r, s);
2444
+ }
2445
+ /**
2446
+ * @todo remove
2447
+ * @deprecated
2448
+ */
2449
+ assertValidity() {
2450
+ }
2451
+ addRecoveryBit(recovery) {
2452
+ return new Signature(this.r, this.s, recovery);
2453
+ }
2454
+ recoverPublicKey(msgHash) {
2455
+ const { r, s, recovery: rec } = this;
2456
+ const h = bits2int_modN(ensureBytes("msgHash", msgHash));
2457
+ if (rec == null || ![0, 1, 2, 3].includes(rec))
2458
+ throw new Error("recovery id invalid");
2459
+ const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
2460
+ if (radj >= Fp.ORDER)
2461
+ throw new Error("recovery id 2 or 3 invalid");
2462
+ const prefix = (rec & 1) === 0 ? "02" : "03";
2463
+ const R = Point.fromHex(prefix + numToSizedHex(radj, Fp.BYTES));
2464
+ const ir = invN(radj);
2465
+ const u1 = modN(-h * ir);
2466
+ const u2 = modN(s * ir);
2467
+ const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);
2468
+ if (!Q)
2469
+ throw new Error("point at infinify");
2470
+ Q.assertValidity();
2471
+ return Q;
2472
+ }
2473
+ // Signatures should be low-s, to prevent malleability.
2474
+ hasHighS() {
2475
+ return isBiggerThanHalfOrder(this.s);
2476
+ }
2477
+ normalizeS() {
2478
+ return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
2479
+ }
2480
+ // DER-encoded
2481
+ toDERRawBytes() {
2482
+ return hexToBytes(this.toDERHex());
2483
+ }
2484
+ toDERHex() {
2485
+ return DER.hexFromSig(this);
2486
+ }
2487
+ // padded bytes of r, then padded bytes of s
2488
+ toCompactRawBytes() {
2489
+ return hexToBytes(this.toCompactHex());
2490
+ }
2491
+ toCompactHex() {
2492
+ const l = nByteLength;
2493
+ return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);
2494
+ }
2495
+ }
2496
+ const utils = {
2497
+ isValidPrivateKey(privateKey) {
2498
+ try {
2499
+ normPrivateKeyToScalar(privateKey);
2500
+ return true;
2501
+ } catch (error) {
2502
+ return false;
2503
+ }
2504
+ },
2505
+ normPrivateKeyToScalar,
2506
+ /**
2507
+ * Produces cryptographically secure private key from random of size
2508
+ * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
2509
+ */
2510
+ randomPrivateKey: () => {
2511
+ const length = getMinHashLength(CURVE.n);
2512
+ return mapHashToField(CURVE.randomBytes(length), CURVE.n);
2513
+ },
2514
+ /**
2515
+ * Creates precompute table for an arbitrary EC point. Makes point "cached".
2516
+ * Allows to massively speed-up `point.multiply(scalar)`.
2517
+ * @returns cached point
2518
+ * @example
2519
+ * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
2520
+ * fast.multiply(privKey); // much faster ECDH now
2521
+ */
2522
+ precompute(windowSize = 8, point = Point.BASE) {
2523
+ point._setWindowSize(windowSize);
2524
+ point.multiply(BigInt(3));
2525
+ return point;
2526
+ }
2527
+ };
2528
+ function getPublicKey(privateKey, isCompressed = true) {
2529
+ return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
2530
+ }
2531
+ function isProbPub(item) {
2532
+ if (typeof item === "bigint")
2533
+ return false;
2534
+ if (item instanceof Point)
2535
+ return true;
2536
+ const arr = ensureBytes("key", item);
2537
+ const len = arr.length;
2538
+ const fpl = Fp.BYTES;
2539
+ const compLen = fpl + 1;
2540
+ const uncompLen = 2 * fpl + 1;
2541
+ if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {
2542
+ return void 0;
2543
+ } else {
2544
+ return len === compLen || len === uncompLen;
2545
+ }
2546
+ }
2547
+ function getSharedSecret(privateA, publicB, isCompressed = true) {
2548
+ if (isProbPub(privateA) === true)
2549
+ throw new Error("first arg must be private key");
2550
+ if (isProbPub(publicB) === false)
2551
+ throw new Error("second arg must be public key");
2552
+ const b = Point.fromHex(publicB);
2553
+ return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
2554
+ }
2555
+ const bits2int = CURVE.bits2int || function(bytes) {
2556
+ if (bytes.length > 8192)
2557
+ throw new Error("input is too large");
2558
+ const num = bytesToNumberBE(bytes);
2559
+ const delta = bytes.length * 8 - nBitLength;
2560
+ return delta > 0 ? num >> BigInt(delta) : num;
2561
+ };
2562
+ const bits2int_modN = CURVE.bits2int_modN || function(bytes) {
2563
+ return modN(bits2int(bytes));
2564
+ };
2565
+ const ORDER_MASK = bitMask(nBitLength);
2566
+ function int2octets(num) {
2567
+ aInRange("num < 2^" + nBitLength, num, _0n4, ORDER_MASK);
2568
+ return numberToBytesBE(num, nByteLength);
2569
+ }
2570
+ function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
2571
+ if (["recovered", "canonical"].some((k) => k in opts))
2572
+ throw new Error("sign() legacy options not supported");
2573
+ const { hash, randomBytes: randomBytes2 } = CURVE;
2574
+ let { lowS, prehash, extraEntropy: ent } = opts;
2575
+ if (lowS == null)
2576
+ lowS = true;
2577
+ msgHash = ensureBytes("msgHash", msgHash);
2578
+ validateSigVerOpts(opts);
2579
+ if (prehash)
2580
+ msgHash = ensureBytes("prehashed msgHash", hash(msgHash));
2581
+ const h1int = bits2int_modN(msgHash);
2582
+ const d = normPrivateKeyToScalar(privateKey);
2583
+ const seedArgs = [int2octets(d), int2octets(h1int)];
2584
+ if (ent != null && ent !== false) {
2585
+ const e = ent === true ? randomBytes2(Fp.BYTES) : ent;
2586
+ seedArgs.push(ensureBytes("extraEntropy", e));
2587
+ }
2588
+ const seed = concatBytes3(...seedArgs);
2589
+ const m = h1int;
2590
+ function k2sig(kBytes) {
2591
+ const k = bits2int(kBytes);
2592
+ if (!isWithinCurveOrder(k))
2593
+ return;
2594
+ const ik = invN(k);
2595
+ const q = Point.BASE.multiply(k).toAffine();
2596
+ const r = modN(q.x);
2597
+ if (r === _0n4)
2598
+ return;
2599
+ const s = modN(ik * modN(m + r * d));
2600
+ if (s === _0n4)
2601
+ return;
2602
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
2603
+ let normS = s;
2604
+ if (lowS && isBiggerThanHalfOrder(s)) {
2605
+ normS = normalizeS(s);
2606
+ recovery ^= 1;
2607
+ }
2608
+ return new Signature(r, normS, recovery);
2609
+ }
2610
+ return { seed, k2sig };
2611
+ }
2612
+ const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
2613
+ const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
2614
+ function sign2(msgHash, privKey, opts = defaultSigOpts) {
2615
+ const { seed, k2sig } = prepSig(msgHash, privKey, opts);
2616
+ const C = CURVE;
2617
+ const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
2618
+ return drbg(seed, k2sig);
2619
+ }
2620
+ Point.BASE._setWindowSize(8);
2621
+ function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
2622
+ const sg = signature;
2623
+ msgHash = ensureBytes("msgHash", msgHash);
2624
+ publicKey = ensureBytes("publicKey", publicKey);
2625
+ const { lowS, prehash, format } = opts;
2626
+ validateSigVerOpts(opts);
2627
+ if ("strict" in opts)
2628
+ throw new Error("options.strict was renamed to lowS");
2629
+ if (format !== void 0 && format !== "compact" && format !== "der")
2630
+ throw new Error("format must be compact or der");
2631
+ const isHex2 = typeof sg === "string" || isBytes3(sg);
2632
+ const isObj = !isHex2 && !format && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint";
2633
+ if (!isHex2 && !isObj)
2634
+ throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
2635
+ let _sig = void 0;
2636
+ let P;
2637
+ try {
2638
+ if (isObj)
2639
+ _sig = new Signature(sg.r, sg.s);
2640
+ if (isHex2) {
2641
+ try {
2642
+ if (format !== "compact")
2643
+ _sig = Signature.fromDER(sg);
2644
+ } catch (derError) {
2645
+ if (!(derError instanceof DER.Err))
2646
+ throw derError;
2647
+ }
2648
+ if (!_sig && format !== "der")
2649
+ _sig = Signature.fromCompact(sg);
2650
+ }
2651
+ P = Point.fromHex(publicKey);
2652
+ } catch (error) {
2653
+ return false;
2654
+ }
2655
+ if (!_sig)
2656
+ return false;
2657
+ if (lowS && _sig.hasHighS())
2658
+ return false;
2659
+ if (prehash)
2660
+ msgHash = CURVE.hash(msgHash);
2661
+ const { r, s } = _sig;
2662
+ const h = bits2int_modN(msgHash);
2663
+ const is = invN(s);
2664
+ const u1 = modN(h * is);
2665
+ const u2 = modN(r * is);
2666
+ const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine();
2667
+ if (!R)
2668
+ return false;
2669
+ const v = modN(R.x);
2670
+ return v === r;
2671
+ }
2672
+ return {
2673
+ CURVE,
2674
+ getPublicKey,
2675
+ getSharedSecret,
2676
+ sign: sign2,
2677
+ verify,
2678
+ ProjectivePoint: Point,
2679
+ Signature,
2680
+ utils
2681
+ };
2682
+ }
2683
+
2684
+ // node_modules/@noble/curves/esm/_shortw_utils.js
2685
+ function getHash(hash) {
2686
+ return {
2687
+ hash,
2688
+ hmac: (key, ...msgs) => hmac(hash, key, concatBytes2(...msgs)),
2689
+ randomBytes
2690
+ };
2691
+ }
2692
+ function createCurve(curveDef, defHash) {
2693
+ const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
2694
+ return { ...create(defHash), create };
2695
+ }
2696
+
2697
+ // node_modules/@noble/curves/esm/secp256k1.js
2698
+ var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f");
2699
+ var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
2700
+ var _0n5 = BigInt(0);
2701
+ var _1n5 = BigInt(1);
2702
+ var _2n3 = BigInt(2);
2703
+ var divNearest = (a, b) => (a + b / _2n3) / b;
2704
+ function sqrtMod(y) {
2705
+ const P = secp256k1P;
2706
+ const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
2707
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
2708
+ const b2 = y * y * y % P;
2709
+ const b3 = b2 * b2 * y % P;
2710
+ const b6 = pow2(b3, _3n3, P) * b3 % P;
2711
+ const b9 = pow2(b6, _3n3, P) * b3 % P;
2712
+ const b11 = pow2(b9, _2n3, P) * b2 % P;
2713
+ const b22 = pow2(b11, _11n, P) * b11 % P;
2714
+ const b44 = pow2(b22, _22n, P) * b22 % P;
2715
+ const b88 = pow2(b44, _44n, P) * b44 % P;
2716
+ const b176 = pow2(b88, _88n, P) * b88 % P;
2717
+ const b220 = pow2(b176, _44n, P) * b44 % P;
2718
+ const b223 = pow2(b220, _3n3, P) * b3 % P;
2719
+ const t1 = pow2(b223, _23n, P) * b22 % P;
2720
+ const t2 = pow2(t1, _6n, P) * b2 % P;
2721
+ const root = pow2(t2, _2n3, P);
2722
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
2723
+ throw new Error("Cannot find square root");
2724
+ return root;
2725
+ }
2726
+ var Fpk1 = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod });
2727
+ var secp256k1 = createCurve({
2728
+ a: _0n5,
2729
+ b: BigInt(7),
2730
+ Fp: Fpk1,
2731
+ n: secp256k1N,
2732
+ Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),
2733
+ Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),
2734
+ h: BigInt(1),
2735
+ lowS: true,
2736
+ // Allow only low-S signatures by default in sign() and verify()
2737
+ endo: {
2738
+ // Endomorphism, see above
2739
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
2740
+ splitScalar: (k) => {
2741
+ const n = secp256k1N;
2742
+ const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15");
2743
+ const b1 = -_1n5 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3");
2744
+ const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");
2745
+ const b2 = a1;
2746
+ const POW_2_128 = BigInt("0x100000000000000000000000000000000");
2747
+ const c1 = divNearest(b2 * k, n);
2748
+ const c2 = divNearest(-b1 * k, n);
2749
+ let k1 = mod(k - c1 * a1 - c2 * a2, n);
2750
+ let k2 = mod(-c1 * b1 - c2 * b2, n);
2751
+ const k1neg = k1 > POW_2_128;
2752
+ const k2neg = k2 > POW_2_128;
2753
+ if (k1neg)
2754
+ k1 = n - k1;
2755
+ if (k2neg)
2756
+ k2 = n - k2;
2757
+ if (k1 > POW_2_128 || k2 > POW_2_128) {
2758
+ throw new Error("splitScalar: Endomorphism failed, k=" + k);
2759
+ }
2760
+ return { k1neg, k1, k2neg, k2 };
2761
+ }
2762
+ }
2763
+ }, sha256);
2764
+
2765
+ // node_modules/@noble/hashes/esm/sha256.js
2766
+ var sha2562 = sha256;
2767
+
2768
+ // node_modules/@noble/hashes/esm/sha512.js
2769
+ var sha5122 = sha512;
2770
+
2771
+ // src/payload/ecies.ts
2772
+ var MIN_CIPHER_BYTES = 82;
2773
+ function hexToBytes2(hex) {
2774
+ const bytes = new Uint8Array(hex.length / 2);
2775
+ for (let i = 0; i < bytes.length; i++) {
2776
+ bytes[i] = Number.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
2777
+ }
2778
+ return bytes;
2779
+ }
2780
+ function bytesToHex2(bytes) {
2781
+ let hex = "";
2782
+ for (const b of bytes) {
2783
+ hex += b.toString(16).padStart(2, "0");
2784
+ }
2785
+ return hex;
2786
+ }
2787
+ function timingSafeEqual(a, b) {
2788
+ if (a.length !== b.length) return false;
2789
+ let diff = 0;
2790
+ for (let i = 0; i < a.length; i++) {
2791
+ diff |= a[i] ^ b[i];
2792
+ }
2793
+ return diff === 0;
2794
+ }
2795
+ function deriveKeys(sharedSecret) {
2796
+ const hash = sha5122(sharedSecret);
2797
+ return {
2798
+ encKey: hash.slice(0, 32),
2799
+ macKey: hash.slice(32)
2800
+ };
2801
+ }
2802
+ async function encryptWithPublicKey(publicKey, message) {
2803
+ const pubKeyBytes = hexToBytes2(`04${publicKey}`);
2804
+ const ephemPrivKey = randomBytes(32);
2805
+ const ephemPubKey = secp256k1.getPublicKey(ephemPrivKey, false);
2806
+ const sharedPoint = secp256k1.getSharedSecret(ephemPrivKey, pubKeyBytes, true);
2807
+ const sharedSecret = sharedPoint.slice(1);
2808
+ const { encKey, macKey } = deriveKeys(sharedSecret);
2809
+ const iv = randomBytes(16);
2810
+ const plaintext = new TextEncoder().encode(message);
2811
+ const cipher = cbc(encKey, iv);
2812
+ const ciphertext = cipher.encrypt(plaintext);
2813
+ const macData = concatBytes2(iv, ephemPubKey, ciphertext);
2814
+ const mac = hmac(sha2562, macKey, macData);
2815
+ return {
2816
+ iv: bytesToHex2(iv),
2817
+ ephemPublicKey: bytesToHex2(ephemPubKey),
2818
+ ciphertext: bytesToHex2(ciphertext),
2819
+ mac: bytesToHex2(mac)
2820
+ };
2821
+ }
2822
+ async function decryptWithPrivateKey(privateKey, encrypted) {
2823
+ const privKeyBytes = hexToBytes2(privateKey.replace(/^0x/, ""));
2824
+ const ephemPubKeyBytes = hexToBytes2(encrypted.ephemPublicKey);
2825
+ const ivBytes = hexToBytes2(encrypted.iv);
2826
+ const ciphertextBytes = hexToBytes2(encrypted.ciphertext);
2827
+ const macBytes = hexToBytes2(encrypted.mac);
2828
+ const sharedPoint = secp256k1.getSharedSecret(privKeyBytes, ephemPubKeyBytes, true);
2829
+ const sharedSecret = sharedPoint.slice(1);
2830
+ const { encKey, macKey } = deriveKeys(sharedSecret);
2831
+ const macData = concatBytes2(ivBytes, ephemPubKeyBytes, ciphertextBytes);
2832
+ const computedMac = hmac(sha2562, macKey, macData);
2833
+ if (!timingSafeEqual(computedMac, macBytes)) {
2834
+ throw new Error("MAC mismatch \u2014 ciphertext may be corrupted or tampered with");
2835
+ }
2836
+ const cipher = cbc(encKey, ivBytes);
2837
+ const plaintext = cipher.decrypt(ciphertextBytes);
2838
+ return new TextDecoder().decode(plaintext);
2839
+ }
2840
+ function cipherStringify(encrypted) {
2841
+ const ephemPubKeyBytes = hexToBytes2(encrypted.ephemPublicKey);
2842
+ const compressed = secp256k1.ProjectivePoint.fromHex(ephemPubKeyBytes).toRawBytes(true);
2843
+ const iv = hexToBytes2(encrypted.iv);
2844
+ const mac = hexToBytes2(encrypted.mac);
2845
+ const ciphertext = hexToBytes2(encrypted.ciphertext);
2846
+ return bytesToHex2(concatBytes2(iv, compressed, mac, ciphertext));
2847
+ }
2848
+ function cipherParse(str) {
2849
+ const buf = hexToBytes2(str);
2850
+ if (buf.length < MIN_CIPHER_BYTES) {
2851
+ throw new Error(
2852
+ `cipherParse: input too short (${buf.length} bytes, need at least ${MIN_CIPHER_BYTES})`
2853
+ );
2854
+ }
2855
+ const iv = buf.slice(0, 16);
2856
+ const compressed = buf.slice(16, 49);
2857
+ const mac = buf.slice(49, 81);
2858
+ const ciphertext = buf.slice(81);
2859
+ const ephemPubKey = secp256k1.ProjectivePoint.fromHex(compressed).toRawBytes(false);
2860
+ return {
2861
+ iv: bytesToHex2(iv),
2862
+ ephemPublicKey: bytesToHex2(ephemPubKey),
2863
+ ciphertext: bytesToHex2(ciphertext),
2864
+ mac: bytesToHex2(mac)
2865
+ };
2866
+ }
2867
+
2868
+ // src/payload/errors.ts
2869
+ var PayloadError = class extends SdkError {
2870
+ constructor(message, options) {
2871
+ super(message, options);
2872
+ this.name = "PayloadError";
2873
+ }
2874
+ };
2875
+
2876
+ // src/payload/relay-identity.ts
2877
+ import { ok as ok2 } from "neverthrow";
2878
+ import { isAddress as isAddress2, isHex } from "viem";
2879
+ import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
2880
+ import { z as z2 } from "zod";
2881
+ var ZodRelayIdentitySchema = z2.object({
2882
+ address: z2.string().refine(isAddress2, { message: "Invalid relay identity address" }),
2883
+ publicKey: z2.string().refine((val) => isHex(`0x${val}`), {
2884
+ message: "Invalid relay identity public key"
2885
+ }),
2886
+ privateKey: z2.string().refine(isHex, { message: "Invalid relay identity private key" })
2887
+ });
2888
+ var STORAGE_KEY = "@P2PME:RELAY_IDENTITY";
2889
+ function createRelayIdentity() {
2890
+ const privateKey = generatePrivateKey();
2891
+ const account = privateKeyToAccount(privateKey);
2892
+ const rawPubKey = account.publicKey;
2893
+ const publicKey = rawPubKey.slice(4);
2894
+ const identity = {
2895
+ address: account.address,
2896
+ publicKey,
2897
+ privateKey
2898
+ };
2899
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(identity));
2900
+ return identity;
2901
+ }
2902
+ function getRelayIdentity() {
2903
+ const data = localStorage.getItem(STORAGE_KEY);
2904
+ if (!data) {
2905
+ return ok2(createRelayIdentity());
2906
+ }
2907
+ let parsed;
2908
+ try {
2909
+ parsed = JSON.parse(data);
2910
+ } catch {
2911
+ return ok2(createRelayIdentity());
2912
+ }
2913
+ const result = validate(
2914
+ ZodRelayIdentitySchema,
2915
+ parsed,
2916
+ (message, cause, d) => new PayloadError(message, { code: "VALIDATION_ERROR", cause, context: { data: d } })
2917
+ );
2918
+ if (result.isErr()) {
2919
+ return ok2(createRelayIdentity());
2920
+ }
2921
+ return result;
2922
+ }
2923
+
2924
+ // src/payload/crypto.ts
2925
+ function encryptPaymentAddress(paymentAddress, encryptionPublicKey) {
2926
+ return safeTry(async function* () {
2927
+ const relayIdentity = yield* getRelayIdentity().mapErr(
2928
+ (e) => new PayloadError(`Relay identity error: ${e.message}`, {
2929
+ code: "ENCRYPTION_ERROR",
2930
+ cause: e
2931
+ })
2932
+ );
2933
+ const messageHash = keccak256(stringToHex(paymentAddress));
2934
+ const signResult = yield* ResultAsync.fromPromise(
2935
+ sign({ hash: messageHash, privateKey: relayIdentity.privateKey }),
2936
+ (error) => new PayloadError(
2937
+ `Signing error: ${error instanceof Error ? error.message : "Unknown error"}`,
2938
+ { code: "ENCRYPTION_ERROR", cause: error }
2939
+ )
2940
+ );
2941
+ const signature = serializeSignature(signResult);
2942
+ const payload = { message: paymentAddress, signature };
2943
+ const encrypted = yield* ResultAsync.fromPromise(
2944
+ encryptWithPublicKey(encryptionPublicKey, JSON.stringify(payload)),
2945
+ (error) => new PayloadError(
2946
+ `Encryption error: ${error instanceof Error ? error.message : "Unknown error"}`,
2947
+ { code: "ENCRYPTION_ERROR", cause: error }
2948
+ )
2949
+ );
2950
+ const safeCipherStringify = Result.fromThrowable(
2951
+ (encryptedData) => cipherStringify(encryptedData),
2952
+ (error) => new PayloadError(
2953
+ `Stringify error: ${error instanceof Error ? error.message : "Unknown error"}`,
2954
+ { code: "ENCRYPTION_ERROR", cause: error }
2955
+ )
2956
+ );
2957
+ const stringified = yield* safeCipherStringify(encrypted);
2958
+ return ok3(stringified);
2959
+ });
2960
+ }
2961
+ var ZodEncryptedDataSchema = z3.object({
2962
+ ciphertext: z3.string(),
2963
+ iv: z3.string(),
2964
+ mac: z3.string(),
2965
+ ephemPublicKey: z3.string()
2966
+ });
2967
+ function decryptPaymentAddress(encryptedPaymentAddress) {
2968
+ return safeTry(async function* () {
2969
+ const relayIdentity = yield* getRelayIdentity().mapErr(
2970
+ (e) => new PayloadError(`Relay identity error: ${e.message}`, {
2971
+ code: "DECRYPTION_ERROR",
2972
+ cause: e
2973
+ })
2974
+ );
2975
+ const safeJsonParse = Result.fromThrowable(
2976
+ (str) => JSON.parse(str),
2977
+ (error) => new PayloadError(
2978
+ `JSON parse error: ${error instanceof Error ? error.message : "Unknown error"}`,
2979
+ { code: "DECRYPTION_ERROR", cause: error }
2980
+ )
2981
+ );
2982
+ const parsed = yield* safeJsonParse(encryptedPaymentAddress);
2983
+ const encryptedData = yield* validate(
2984
+ ZodEncryptedDataSchema,
2985
+ parsed,
2986
+ (message, cause, data) => new PayloadError(message, { code: "DECRYPTION_ERROR", cause, context: { data } })
2987
+ );
2988
+ const decrypted = yield* ResultAsync.fromPromise(
2989
+ decryptWithPrivateKey(relayIdentity.privateKey, encryptedData),
2990
+ (error) => new PayloadError(
2991
+ `Decryption error: ${error instanceof Error ? error.message : "Unknown error"}`,
2992
+ { code: "DECRYPTION_ERROR", cause: error }
2993
+ )
2994
+ );
2995
+ return ok3(decrypted);
2996
+ });
2997
+ }
2998
+
2999
+ // src/payload/validation.ts
3000
+ import { z as z4 } from "zod";
3001
+ var ZodPlaceOrderParamsSchema = z4.object({
3002
+ amount: z4.bigint(),
3003
+ recipientAddr: ZodAddressSchema,
3004
+ orderType: z4.number().int().min(0).max(2),
3005
+ currency: ZodCurrencySchema,
3006
+ fiatAmount: z4.bigint(),
3007
+ user: ZodAddressSchema,
3008
+ pubKey: z4.string().optional(),
3009
+ preferredPaymentChannelConfigId: z4.bigint().optional(),
3010
+ fiatAmountLimit: z4.bigint().optional().default(0n)
3011
+ });
3012
+ var ZodSetSellOrderUpiParamsSchema = z4.object({
3013
+ orderId: z4.number().int().nonnegative(),
3014
+ paymentAddress: z4.string().min(1),
3015
+ merchantPublicKey: z4.string().min(1),
3016
+ updatedAmount: z4.bigint()
3017
+ });
3018
+
3019
+ // src/payload/actions.ts
3020
+ function buildPlaceOrderPayload(orderRouter, params) {
3021
+ const validation = validate(
3022
+ ZodPlaceOrderParamsSchema,
3023
+ params,
3024
+ (message, cause, data) => new PayloadError(message, { code: "VALIDATION_ERROR", cause, context: { data } })
3025
+ );
3026
+ if (validation.isErr()) {
3027
+ return errAsync(validation.error);
3028
+ }
3029
+ const v = validation.value;
3030
+ const isBuy = v.orderType === ORDER_TYPE.BUY;
3031
+ const pcConfigId = v.preferredPaymentChannelConfigId ?? 0n;
3032
+ const circleResult = orderRouter.selectCircle({
3033
+ currency: v.currency,
3034
+ user: v.user,
3035
+ usdtAmount: v.amount,
3036
+ fiatAmount: v.fiatAmount,
3037
+ orderType: BigInt(v.orderType),
3038
+ preferredPCConfigId: pcConfigId
3039
+ });
3040
+ const relayResult = getRelayIdentity();
3041
+ if (relayResult.isErr()) {
3042
+ return errAsync(relayResult.error);
3043
+ }
3044
+ const common = {
3045
+ amount: v.amount,
3046
+ recipientAddr: v.recipientAddr,
3047
+ orderType: v.orderType,
3048
+ userUpi: "",
3049
+ currency: v.currency,
3050
+ preferredPaymentChannelConfigId: pcConfigId,
3051
+ fiatAmountLimit: v.fiatAmountLimit
3052
+ };
3053
+ const pubKeyValue = v.pubKey ?? relayResult.value.publicKey;
3054
+ return circleResult.map((circleId) => ({
3055
+ ...common,
3056
+ pubKey: isBuy ? pubKeyValue : "",
3057
+ userPubKey: isBuy ? "" : pubKeyValue,
3058
+ circleId
3059
+ })).mapErr(
3060
+ (e) => new PayloadError(e.message, {
3061
+ code: "CIRCLE_SELECTION_ERROR",
3062
+ cause: e
3063
+ })
3064
+ );
3065
+ }
3066
+ function buildSetSellOrderUpiPayload(params) {
3067
+ const validation = validate(
3068
+ ZodSetSellOrderUpiParamsSchema,
3069
+ params,
3070
+ (message, cause, data) => new PayloadError(message, { code: "VALIDATION_ERROR", cause, context: { data } })
3071
+ );
3072
+ if (validation.isErr()) {
3073
+ return errAsync(validation.error);
3074
+ }
3075
+ const v = validation.value;
3076
+ return encryptPaymentAddress(v.paymentAddress, v.merchantPublicKey).map((userEncUpi) => ({
3077
+ orderId: v.orderId,
3078
+ userEncUpi,
3079
+ updatedAmount: v.updatedAmount
3080
+ }));
3081
+ }
3082
+
3083
+ // src/payload/client.ts
3084
+ function createPayloadGenerator(config) {
3085
+ return {
3086
+ placeOrder(params) {
3087
+ return buildPlaceOrderPayload(config.orderRouter, params);
3088
+ },
3089
+ setSellOrderUpi(params) {
3090
+ return buildSetSellOrderUpiPayload(params);
3091
+ }
3092
+ };
3093
+ }
3094
+ export {
3095
+ PayloadError,
3096
+ cipherParse,
3097
+ cipherStringify,
3098
+ createPayloadGenerator,
3099
+ createRelayIdentity,
3100
+ decryptPaymentAddress,
3101
+ encryptPaymentAddress,
3102
+ getRelayIdentity
3103
+ };
3104
+ /*! Bundled license information:
3105
+
3106
+ @noble/ciphers/esm/utils.js:
3107
+ (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
3108
+
3109
+ @noble/hashes/esm/utils.js:
3110
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3111
+
3112
+ @noble/curves/esm/abstract/utils.js:
3113
+ @noble/curves/esm/abstract/modular.js:
3114
+ @noble/curves/esm/abstract/curve.js:
3115
+ @noble/curves/esm/abstract/weierstrass.js:
3116
+ @noble/curves/esm/_shortw_utils.js:
3117
+ @noble/curves/esm/secp256k1.js:
3118
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3119
+ */
3120
+ //# sourceMappingURL=payload.mjs.map