@zelana/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1807 @@
1
+ // node_modules/@noble/ed25519/index.js
2
+ /*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
3
+ var ed25519_CURVE = {
4
+ p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
5
+ n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,
6
+ h: 8n,
7
+ a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,
8
+ d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,
9
+ Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,
10
+ Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n
11
+ };
12
+ var { p: P, n: N, Gx, Gy, a: _a, d: _d } = ed25519_CURVE;
13
+ var h = 8n;
14
+ var L = 32;
15
+ var L2 = 64;
16
+ var err = (m = "") => {
17
+ throw new Error(m);
18
+ };
19
+ var isBig = (n) => typeof n === "bigint";
20
+ var isStr = (s) => typeof s === "string";
21
+ var isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
22
+ var abytes = (a, l) => !isBytes(a) || typeof l === "number" && l > 0 && a.length !== l ? err("Uint8Array expected") : a;
23
+ var u8n = (len) => new Uint8Array(len);
24
+ var u8fr = (buf) => Uint8Array.from(buf);
25
+ var padh = (n, pad) => n.toString(16).padStart(pad, "0");
26
+ var bytesToHex = (b) => Array.from(abytes(b)).map((e) => padh(e, 2)).join("");
27
+ var C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
28
+ var _ch = (ch) => {
29
+ if (ch >= C._0 && ch <= C._9)
30
+ return ch - C._0;
31
+ if (ch >= C.A && ch <= C.F)
32
+ return ch - (C.A - 10);
33
+ if (ch >= C.a && ch <= C.f)
34
+ return ch - (C.a - 10);
35
+ return;
36
+ };
37
+ var hexToBytes = (hex) => {
38
+ const e = "hex invalid";
39
+ if (!isStr(hex))
40
+ return err(e);
41
+ const hl = hex.length;
42
+ const al = hl / 2;
43
+ if (hl % 2)
44
+ return err(e);
45
+ const array = u8n(al);
46
+ for (let ai = 0, hi = 0;ai < al; ai++, hi += 2) {
47
+ const n1 = _ch(hex.charCodeAt(hi));
48
+ const n2 = _ch(hex.charCodeAt(hi + 1));
49
+ if (n1 === undefined || n2 === undefined)
50
+ return err(e);
51
+ array[ai] = n1 * 16 + n2;
52
+ }
53
+ return array;
54
+ };
55
+ var toU8 = (a, len) => abytes(isStr(a) ? hexToBytes(a) : u8fr(abytes(a)), len);
56
+ var cr = () => globalThis?.crypto;
57
+ var subtle = () => cr()?.subtle ?? err("crypto.subtle must be defined");
58
+ var concatBytes = (...arrs) => {
59
+ const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0));
60
+ let pad = 0;
61
+ arrs.forEach((a) => {
62
+ r.set(a, pad);
63
+ pad += a.length;
64
+ });
65
+ return r;
66
+ };
67
+ var randomBytes = (len = L) => {
68
+ const c = cr();
69
+ return c.getRandomValues(u8n(len));
70
+ };
71
+ var big = BigInt;
72
+ var arange = (n, min, max, msg = "bad number: out of range") => isBig(n) && min <= n && n < max ? n : err(msg);
73
+ var M = (a, b = P) => {
74
+ const r = a % b;
75
+ return r >= 0n ? r : b + r;
76
+ };
77
+ var modN = (a) => M(a, N);
78
+ var invert = (num, md) => {
79
+ if (num === 0n || md <= 0n)
80
+ err("no inverse n=" + num + " mod=" + md);
81
+ let a = M(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;
82
+ while (a !== 0n) {
83
+ const q = b / a, r = b % a;
84
+ const m = x - u * q, n = y - v * q;
85
+ b = a, a = r, x = u, y = v, u = m, v = n;
86
+ }
87
+ return b === 1n ? M(x, md) : err("no inverse");
88
+ };
89
+ var callHash = (name) => {
90
+ const fn = etc[name];
91
+ if (typeof fn !== "function")
92
+ err("hashes." + name + " not set");
93
+ return fn;
94
+ };
95
+ var apoint = (p) => p instanceof Point ? p : err("Point expected");
96
+ var B256 = 2n ** 256n;
97
+
98
+ class Point {
99
+ static BASE;
100
+ static ZERO;
101
+ ex;
102
+ ey;
103
+ ez;
104
+ et;
105
+ constructor(ex, ey, ez, et) {
106
+ const max = B256;
107
+ this.ex = arange(ex, 0n, max);
108
+ this.ey = arange(ey, 0n, max);
109
+ this.ez = arange(ez, 1n, max);
110
+ this.et = arange(et, 0n, max);
111
+ Object.freeze(this);
112
+ }
113
+ static fromAffine(p) {
114
+ return new Point(p.x, p.y, 1n, M(p.x * p.y));
115
+ }
116
+ static fromBytes(hex, zip215 = false) {
117
+ const d = _d;
118
+ const normed = u8fr(abytes(hex, L));
119
+ const lastByte = hex[31];
120
+ normed[31] = lastByte & ~128;
121
+ const y = bytesToNumLE(normed);
122
+ const max = zip215 ? B256 : P;
123
+ arange(y, 0n, max);
124
+ const y2 = M(y * y);
125
+ const u = M(y2 - 1n);
126
+ const v = M(d * y2 + 1n);
127
+ let { isValid, value: x } = uvRatio(u, v);
128
+ if (!isValid)
129
+ err("bad point: y not sqrt");
130
+ const isXOdd = (x & 1n) === 1n;
131
+ const isLastByteOdd = (lastByte & 128) !== 0;
132
+ if (!zip215 && x === 0n && isLastByteOdd)
133
+ err("bad point: x==0, isLastByteOdd");
134
+ if (isLastByteOdd !== isXOdd)
135
+ x = M(-x);
136
+ return new Point(x, y, 1n, M(x * y));
137
+ }
138
+ assertValidity() {
139
+ const a = _a;
140
+ const d = _d;
141
+ const p = this;
142
+ if (p.is0())
143
+ throw new Error("bad point: ZERO");
144
+ const { ex: X, ey: Y, ez: Z, et: T } = p;
145
+ const X2 = M(X * X);
146
+ const Y2 = M(Y * Y);
147
+ const Z2 = M(Z * Z);
148
+ const Z4 = M(Z2 * Z2);
149
+ const aX2 = M(X2 * a);
150
+ const left = M(Z2 * M(aX2 + Y2));
151
+ const right = M(Z4 + M(d * M(X2 * Y2)));
152
+ if (left !== right)
153
+ throw new Error("bad point: equation left != right (1)");
154
+ const XY = M(X * Y);
155
+ const ZT = M(Z * T);
156
+ if (XY !== ZT)
157
+ throw new Error("bad point: equation left != right (2)");
158
+ return this;
159
+ }
160
+ equals(other) {
161
+ const { ex: X1, ey: Y1, ez: Z1 } = this;
162
+ const { ex: X2, ey: Y2, ez: Z2 } = apoint(other);
163
+ const X1Z2 = M(X1 * Z2);
164
+ const X2Z1 = M(X2 * Z1);
165
+ const Y1Z2 = M(Y1 * Z2);
166
+ const Y2Z1 = M(Y2 * Z1);
167
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
168
+ }
169
+ is0() {
170
+ return this.equals(I);
171
+ }
172
+ negate() {
173
+ return new Point(M(-this.ex), this.ey, this.ez, M(-this.et));
174
+ }
175
+ double() {
176
+ const { ex: X1, ey: Y1, ez: Z1 } = this;
177
+ const a = _a;
178
+ const A = M(X1 * X1);
179
+ const B = M(Y1 * Y1);
180
+ const C2 = M(2n * M(Z1 * Z1));
181
+ const D = M(a * A);
182
+ const x1y1 = X1 + Y1;
183
+ const E = M(M(x1y1 * x1y1) - A - B);
184
+ const G = D + B;
185
+ const F = G - C2;
186
+ const H = D - B;
187
+ const X3 = M(E * F);
188
+ const Y3 = M(G * H);
189
+ const T3 = M(E * H);
190
+ const Z3 = M(F * G);
191
+ return new Point(X3, Y3, Z3, T3);
192
+ }
193
+ add(other) {
194
+ const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
195
+ const { ex: X2, ey: Y2, ez: Z2, et: T2 } = apoint(other);
196
+ const a = _a;
197
+ const d = _d;
198
+ const A = M(X1 * X2);
199
+ const B = M(Y1 * Y2);
200
+ const C2 = M(T1 * d * T2);
201
+ const D = M(Z1 * Z2);
202
+ const E = M((X1 + Y1) * (X2 + Y2) - A - B);
203
+ const F = M(D - C2);
204
+ const G = M(D + C2);
205
+ const H = M(B - a * A);
206
+ const X3 = M(E * F);
207
+ const Y3 = M(G * H);
208
+ const T3 = M(E * H);
209
+ const Z3 = M(F * G);
210
+ return new Point(X3, Y3, Z3, T3);
211
+ }
212
+ multiply(n, safe = true) {
213
+ if (!safe && (n === 0n || this.is0()))
214
+ return I;
215
+ arange(n, 1n, N);
216
+ if (n === 1n)
217
+ return this;
218
+ if (this.equals(G))
219
+ return wNAF(n).p;
220
+ let p = I;
221
+ let f = G;
222
+ for (let d = this;n > 0n; d = d.double(), n >>= 1n) {
223
+ if (n & 1n)
224
+ p = p.add(d);
225
+ else if (safe)
226
+ f = f.add(d);
227
+ }
228
+ return p;
229
+ }
230
+ toAffine() {
231
+ const { ex: x, ey: y, ez: z } = this;
232
+ if (this.equals(I))
233
+ return { x: 0n, y: 1n };
234
+ const iz = invert(z, P);
235
+ if (M(z * iz) !== 1n)
236
+ err("invalid inverse");
237
+ return { x: M(x * iz), y: M(y * iz) };
238
+ }
239
+ toBytes() {
240
+ const { x, y } = this.assertValidity().toAffine();
241
+ const b = numTo32bLE(y);
242
+ b[31] |= x & 1n ? 128 : 0;
243
+ return b;
244
+ }
245
+ toHex() {
246
+ return bytesToHex(this.toBytes());
247
+ }
248
+ clearCofactor() {
249
+ return this.multiply(big(h), false);
250
+ }
251
+ isSmallOrder() {
252
+ return this.clearCofactor().is0();
253
+ }
254
+ isTorsionFree() {
255
+ let p = this.multiply(N / 2n, false).double();
256
+ if (N % 2n)
257
+ p = p.add(this);
258
+ return p.is0();
259
+ }
260
+ static fromHex(hex, zip215) {
261
+ return Point.fromBytes(toU8(hex), zip215);
262
+ }
263
+ get x() {
264
+ return this.toAffine().x;
265
+ }
266
+ get y() {
267
+ return this.toAffine().y;
268
+ }
269
+ toRawBytes() {
270
+ return this.toBytes();
271
+ }
272
+ }
273
+ var G = new Point(Gx, Gy, 1n, M(Gx * Gy));
274
+ var I = new Point(0n, 1n, 1n, 0n);
275
+ Point.BASE = G;
276
+ Point.ZERO = I;
277
+ var numTo32bLE = (num) => hexToBytes(padh(arange(num, 0n, B256), L2)).reverse();
278
+ var bytesToNumLE = (b) => big("0x" + bytesToHex(u8fr(abytes(b)).reverse()));
279
+ var pow2 = (x, power) => {
280
+ let r = x;
281
+ while (power-- > 0n) {
282
+ r *= r;
283
+ r %= P;
284
+ }
285
+ return r;
286
+ };
287
+ var pow_2_252_3 = (x) => {
288
+ const x2 = x * x % P;
289
+ const b2 = x2 * x % P;
290
+ const b4 = pow2(b2, 2n) * b2 % P;
291
+ const b5 = pow2(b4, 1n) * x % P;
292
+ const b10 = pow2(b5, 5n) * b5 % P;
293
+ const b20 = pow2(b10, 10n) * b10 % P;
294
+ const b40 = pow2(b20, 20n) * b20 % P;
295
+ const b80 = pow2(b40, 40n) * b40 % P;
296
+ const b160 = pow2(b80, 80n) * b80 % P;
297
+ const b240 = pow2(b160, 80n) * b80 % P;
298
+ const b250 = pow2(b240, 10n) * b10 % P;
299
+ const pow_p_5_8 = pow2(b250, 2n) * x % P;
300
+ return { pow_p_5_8, b2 };
301
+ };
302
+ var RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n;
303
+ var uvRatio = (u, v) => {
304
+ const v3 = M(v * v * v);
305
+ const v7 = M(v3 * v3 * v);
306
+ const pow = pow_2_252_3(u * v7).pow_p_5_8;
307
+ let x = M(u * v3 * pow);
308
+ const vx2 = M(v * x * x);
309
+ const root1 = x;
310
+ const root2 = M(x * RM1);
311
+ const useRoot1 = vx2 === u;
312
+ const useRoot2 = vx2 === M(-u);
313
+ const noRoot = vx2 === M(-u * RM1);
314
+ if (useRoot1)
315
+ x = root1;
316
+ if (useRoot2 || noRoot)
317
+ x = root2;
318
+ if ((M(x) & 1n) === 1n)
319
+ x = M(-x);
320
+ return { isValid: useRoot1 || useRoot2, value: x };
321
+ };
322
+ var modL_LE = (hash) => modN(bytesToNumLE(hash));
323
+ var sha512s = (...m) => callHash("sha512Sync")(...m);
324
+ var hash2extK = (hashed) => {
325
+ const head = hashed.slice(0, L);
326
+ head[0] &= 248;
327
+ head[31] &= 127;
328
+ head[31] |= 64;
329
+ const prefix = hashed.slice(L, L2);
330
+ const scalar = modL_LE(head);
331
+ const point = G.multiply(scalar);
332
+ const pointBytes = point.toBytes();
333
+ return { head, prefix, scalar, point, pointBytes };
334
+ };
335
+ var getExtendedPublicKey = (priv) => hash2extK(sha512s(toU8(priv, L)));
336
+ var getPublicKey = (priv) => getExtendedPublicKey(priv).pointBytes;
337
+ var hashFinishS = (res) => res.finish(sha512s(res.hashable));
338
+ var _sign = (e, rBytes, msg) => {
339
+ const { pointBytes: P2, scalar: s } = e;
340
+ const r = modL_LE(rBytes);
341
+ const R = G.multiply(r).toBytes();
342
+ const hashable = concatBytes(R, P2, msg);
343
+ const finish = (hashed) => {
344
+ const S = modN(r + modL_LE(hashed) * s);
345
+ return abytes(concatBytes(R, numTo32bLE(S)), L2);
346
+ };
347
+ return { hashable, finish };
348
+ };
349
+ var sign = (msg, privKey) => {
350
+ const m = toU8(msg);
351
+ const e = getExtendedPublicKey(privKey);
352
+ const rBytes = sha512s(e.prefix, m);
353
+ return hashFinishS(_sign(e, rBytes, m));
354
+ };
355
+ var veriOpts = { zip215: true };
356
+ var _verify = (sig, msg, pub, opts = veriOpts) => {
357
+ sig = toU8(sig, L2);
358
+ msg = toU8(msg);
359
+ pub = toU8(pub, L);
360
+ const { zip215 } = opts;
361
+ let A;
362
+ let R;
363
+ let s;
364
+ let SB;
365
+ let hashable = Uint8Array.of();
366
+ try {
367
+ A = Point.fromHex(pub, zip215);
368
+ R = Point.fromHex(sig.slice(0, L), zip215);
369
+ s = bytesToNumLE(sig.slice(L, L2));
370
+ SB = G.multiply(s, false);
371
+ hashable = concatBytes(R.toBytes(), A.toBytes(), msg);
372
+ } catch (error) {}
373
+ const finish = (hashed) => {
374
+ if (SB == null)
375
+ return false;
376
+ if (!zip215 && A.isSmallOrder())
377
+ return false;
378
+ const k = modL_LE(hashed);
379
+ const RkA = R.add(A.multiply(k, false));
380
+ return RkA.add(SB.negate()).clearCofactor().is0();
381
+ };
382
+ return { hashable, finish };
383
+ };
384
+ var verify = (s, m, p, opts = veriOpts) => hashFinishS(_verify(s, m, p, opts));
385
+ var etc = {
386
+ sha512Async: async (...messages) => {
387
+ const s = subtle();
388
+ const m = concatBytes(...messages);
389
+ return u8n(await s.digest("SHA-512", m.buffer));
390
+ },
391
+ sha512Sync: undefined,
392
+ bytesToHex,
393
+ hexToBytes,
394
+ concatBytes,
395
+ mod: M,
396
+ invert,
397
+ randomBytes
398
+ };
399
+ var W = 8;
400
+ var scalarBits = 256;
401
+ var pwindows = Math.ceil(scalarBits / W) + 1;
402
+ var pwindowSize = 2 ** (W - 1);
403
+ var precompute = () => {
404
+ const points = [];
405
+ let p = G;
406
+ let b = p;
407
+ for (let w = 0;w < pwindows; w++) {
408
+ b = p;
409
+ points.push(b);
410
+ for (let i = 1;i < pwindowSize; i++) {
411
+ b = b.add(p);
412
+ points.push(b);
413
+ }
414
+ p = b.double();
415
+ }
416
+ return points;
417
+ };
418
+ var Gpows = undefined;
419
+ var ctneg = (cnd, p) => {
420
+ const n = p.negate();
421
+ return cnd ? n : p;
422
+ };
423
+ var wNAF = (n) => {
424
+ const comp = Gpows || (Gpows = precompute());
425
+ let p = I;
426
+ let f = G;
427
+ const pow_2_w = 2 ** W;
428
+ const maxNum = pow_2_w;
429
+ const mask = big(pow_2_w - 1);
430
+ const shiftBy = big(W);
431
+ for (let w = 0;w < pwindows; w++) {
432
+ let wbits = Number(n & mask);
433
+ n >>= shiftBy;
434
+ if (wbits > pwindowSize) {
435
+ wbits -= maxNum;
436
+ n += 1n;
437
+ }
438
+ const off = w * pwindowSize;
439
+ const offF = off;
440
+ const offP = off + Math.abs(wbits) - 1;
441
+ const isEven = w % 2 !== 0;
442
+ const isNeg = wbits < 0;
443
+ if (wbits === 0) {
444
+ f = f.add(ctneg(isEven, comp[offF]));
445
+ } else {
446
+ p = p.add(ctneg(isNeg, comp[offP]));
447
+ }
448
+ }
449
+ return { p, f };
450
+ };
451
+
452
+ // node_modules/@noble/hashes/esm/utils.js
453
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
454
+ function isBytes2(a) {
455
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
456
+ }
457
+ function abytes2(b, ...lengths) {
458
+ if (!isBytes2(b))
459
+ throw new Error("Uint8Array expected");
460
+ if (lengths.length > 0 && !lengths.includes(b.length))
461
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
462
+ }
463
+ function aexists(instance, checkFinished = true) {
464
+ if (instance.destroyed)
465
+ throw new Error("Hash instance has been destroyed");
466
+ if (checkFinished && instance.finished)
467
+ throw new Error("Hash#digest() has already been called");
468
+ }
469
+ function aoutput(out, instance) {
470
+ abytes2(out);
471
+ const min = instance.outputLen;
472
+ if (out.length < min) {
473
+ throw new Error("digestInto() expects output buffer of length at least " + min);
474
+ }
475
+ }
476
+ function clean(...arrays) {
477
+ for (let i = 0;i < arrays.length; i++) {
478
+ arrays[i].fill(0);
479
+ }
480
+ }
481
+ function createView(arr) {
482
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
483
+ }
484
+ function utf8ToBytes(str) {
485
+ if (typeof str !== "string")
486
+ throw new Error("string expected");
487
+ return new Uint8Array(new TextEncoder().encode(str));
488
+ }
489
+ function toBytes(data) {
490
+ if (typeof data === "string")
491
+ data = utf8ToBytes(data);
492
+ abytes2(data);
493
+ return data;
494
+ }
495
+ class Hash {
496
+ }
497
+ function createHasher(hashCons) {
498
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
499
+ const tmp = hashCons();
500
+ hashC.outputLen = tmp.outputLen;
501
+ hashC.blockLen = tmp.blockLen;
502
+ hashC.create = () => hashCons();
503
+ return hashC;
504
+ }
505
+
506
+ // node_modules/@noble/hashes/esm/_md.js
507
+ function setBigUint64(view, byteOffset, value, isLE) {
508
+ if (typeof view.setBigUint64 === "function")
509
+ return view.setBigUint64(byteOffset, value, isLE);
510
+ const _32n = BigInt(32);
511
+ const _u32_max = BigInt(4294967295);
512
+ const wh = Number(value >> _32n & _u32_max);
513
+ const wl = Number(value & _u32_max);
514
+ const h2 = isLE ? 4 : 0;
515
+ const l = isLE ? 0 : 4;
516
+ view.setUint32(byteOffset + h2, wh, isLE);
517
+ view.setUint32(byteOffset + l, wl, isLE);
518
+ }
519
+ class HashMD extends Hash {
520
+ constructor(blockLen, outputLen, padOffset, isLE) {
521
+ super();
522
+ this.finished = false;
523
+ this.length = 0;
524
+ this.pos = 0;
525
+ this.destroyed = false;
526
+ this.blockLen = blockLen;
527
+ this.outputLen = outputLen;
528
+ this.padOffset = padOffset;
529
+ this.isLE = isLE;
530
+ this.buffer = new Uint8Array(blockLen);
531
+ this.view = createView(this.buffer);
532
+ }
533
+ update(data) {
534
+ aexists(this);
535
+ data = toBytes(data);
536
+ abytes2(data);
537
+ const { view, buffer, blockLen } = this;
538
+ const len = data.length;
539
+ for (let pos = 0;pos < len; ) {
540
+ const take = Math.min(blockLen - this.pos, len - pos);
541
+ if (take === blockLen) {
542
+ const dataView = createView(data);
543
+ for (;blockLen <= len - pos; pos += blockLen)
544
+ this.process(dataView, pos);
545
+ continue;
546
+ }
547
+ buffer.set(data.subarray(pos, pos + take), this.pos);
548
+ this.pos += take;
549
+ pos += take;
550
+ if (this.pos === blockLen) {
551
+ this.process(view, 0);
552
+ this.pos = 0;
553
+ }
554
+ }
555
+ this.length += data.length;
556
+ this.roundClean();
557
+ return this;
558
+ }
559
+ digestInto(out) {
560
+ aexists(this);
561
+ aoutput(out, this);
562
+ this.finished = true;
563
+ const { buffer, view, blockLen, isLE } = this;
564
+ let { pos } = this;
565
+ buffer[pos++] = 128;
566
+ clean(this.buffer.subarray(pos));
567
+ if (this.padOffset > blockLen - pos) {
568
+ this.process(view, 0);
569
+ pos = 0;
570
+ }
571
+ for (let i = pos;i < blockLen; i++)
572
+ buffer[i] = 0;
573
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
574
+ this.process(view, 0);
575
+ const oview = createView(out);
576
+ const len = this.outputLen;
577
+ if (len % 4)
578
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
579
+ const outLen = len / 4;
580
+ const state = this.get();
581
+ if (outLen > state.length)
582
+ throw new Error("_sha2: outputLen bigger than state");
583
+ for (let i = 0;i < outLen; i++)
584
+ oview.setUint32(4 * i, state[i], isLE);
585
+ }
586
+ digest() {
587
+ const { buffer, outputLen } = this;
588
+ this.digestInto(buffer);
589
+ const res = buffer.slice(0, outputLen);
590
+ this.destroy();
591
+ return res;
592
+ }
593
+ _cloneInto(to) {
594
+ to || (to = new this.constructor);
595
+ to.set(...this.get());
596
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
597
+ to.destroyed = destroyed;
598
+ to.finished = finished;
599
+ to.length = length;
600
+ to.pos = pos;
601
+ if (length % blockLen)
602
+ to.buffer.set(buffer);
603
+ return to;
604
+ }
605
+ clone() {
606
+ return this._cloneInto();
607
+ }
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: h2, l } = fromBig(lst[i], le);
642
+ [Ah[i], Al[i]] = [h2, l];
643
+ }
644
+ return [Ah, Al];
645
+ }
646
+ var shrSH = (h2, _l, s) => h2 >>> s;
647
+ var shrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
648
+ var rotrSH = (h2, l, s) => h2 >>> s | l << 32 - s;
649
+ var rotrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
650
+ var rotrBH = (h2, l, s) => h2 << 64 - s | l >>> s - 32;
651
+ var rotrBL = (h2, l, s) => h2 >>> 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 K512 = /* @__PURE__ */ (() => split([
665
+ "0x428a2f98d728ae22",
666
+ "0x7137449123ef65cd",
667
+ "0xb5c0fbcfec4d3b2f",
668
+ "0xe9b5dba58189dbbc",
669
+ "0x3956c25bf348b538",
670
+ "0x59f111f1b605d019",
671
+ "0x923f82a4af194f9b",
672
+ "0xab1c5ed5da6d8118",
673
+ "0xd807aa98a3030242",
674
+ "0x12835b0145706fbe",
675
+ "0x243185be4ee4b28c",
676
+ "0x550c7dc3d5ffb4e2",
677
+ "0x72be5d74f27b896f",
678
+ "0x80deb1fe3b1696b1",
679
+ "0x9bdc06a725c71235",
680
+ "0xc19bf174cf692694",
681
+ "0xe49b69c19ef14ad2",
682
+ "0xefbe4786384f25e3",
683
+ "0x0fc19dc68b8cd5b5",
684
+ "0x240ca1cc77ac9c65",
685
+ "0x2de92c6f592b0275",
686
+ "0x4a7484aa6ea6e483",
687
+ "0x5cb0a9dcbd41fbd4",
688
+ "0x76f988da831153b5",
689
+ "0x983e5152ee66dfab",
690
+ "0xa831c66d2db43210",
691
+ "0xb00327c898fb213f",
692
+ "0xbf597fc7beef0ee4",
693
+ "0xc6e00bf33da88fc2",
694
+ "0xd5a79147930aa725",
695
+ "0x06ca6351e003826f",
696
+ "0x142929670a0e6e70",
697
+ "0x27b70a8546d22ffc",
698
+ "0x2e1b21385c26c926",
699
+ "0x4d2c6dfc5ac42aed",
700
+ "0x53380d139d95b3df",
701
+ "0x650a73548baf63de",
702
+ "0x766a0abb3c77b2a8",
703
+ "0x81c2c92e47edaee6",
704
+ "0x92722c851482353b",
705
+ "0xa2bfe8a14cf10364",
706
+ "0xa81a664bbc423001",
707
+ "0xc24b8b70d0f89791",
708
+ "0xc76c51a30654be30",
709
+ "0xd192e819d6ef5218",
710
+ "0xd69906245565a910",
711
+ "0xf40e35855771202a",
712
+ "0x106aa07032bbd1b8",
713
+ "0x19a4c116b8d2d0c8",
714
+ "0x1e376c085141ab53",
715
+ "0x2748774cdf8eeb99",
716
+ "0x34b0bcb5e19b48a8",
717
+ "0x391c0cb3c5c95a63",
718
+ "0x4ed8aa4ae3418acb",
719
+ "0x5b9cca4f7763e373",
720
+ "0x682e6ff3d6b2b8a3",
721
+ "0x748f82ee5defb2fc",
722
+ "0x78a5636f43172f60",
723
+ "0x84c87814a1f0ab72",
724
+ "0x8cc702081a6439ec",
725
+ "0x90befffa23631e28",
726
+ "0xa4506cebde82bde9",
727
+ "0xbef9a3f7b2c67915",
728
+ "0xc67178f2e372532b",
729
+ "0xca273eceea26619c",
730
+ "0xd186b8c721c0c207",
731
+ "0xeada7dd6cde0eb1e",
732
+ "0xf57d4f7fee6ed178",
733
+ "0x06f067aa72176fba",
734
+ "0x0a637dc5a2c898a6",
735
+ "0x113f9804bef90dae",
736
+ "0x1b710b35131c471b",
737
+ "0x28db77f523047d84",
738
+ "0x32caab7b40c72493",
739
+ "0x3c9ebe0a15c9bebc",
740
+ "0x431d67c49c100d4c",
741
+ "0x4cc5d4becb3e42b6",
742
+ "0x597f299cfc657e2a",
743
+ "0x5fcb6fab3ad6faec",
744
+ "0x6c44198c4a475817"
745
+ ].map((n) => BigInt(n))))();
746
+ var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
747
+ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
748
+ var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
749
+ var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
750
+
751
+ class SHA512 extends HashMD {
752
+ constructor(outputLen = 64) {
753
+ super(128, outputLen, 16, false);
754
+ this.Ah = SHA512_IV[0] | 0;
755
+ this.Al = SHA512_IV[1] | 0;
756
+ this.Bh = SHA512_IV[2] | 0;
757
+ this.Bl = SHA512_IV[3] | 0;
758
+ this.Ch = SHA512_IV[4] | 0;
759
+ this.Cl = SHA512_IV[5] | 0;
760
+ this.Dh = SHA512_IV[6] | 0;
761
+ this.Dl = SHA512_IV[7] | 0;
762
+ this.Eh = SHA512_IV[8] | 0;
763
+ this.El = SHA512_IV[9] | 0;
764
+ this.Fh = SHA512_IV[10] | 0;
765
+ this.Fl = SHA512_IV[11] | 0;
766
+ this.Gh = SHA512_IV[12] | 0;
767
+ this.Gl = SHA512_IV[13] | 0;
768
+ this.Hh = SHA512_IV[14] | 0;
769
+ this.Hl = SHA512_IV[15] | 0;
770
+ }
771
+ get() {
772
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
773
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
774
+ }
775
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
776
+ this.Ah = Ah | 0;
777
+ this.Al = Al | 0;
778
+ this.Bh = Bh | 0;
779
+ this.Bl = Bl | 0;
780
+ this.Ch = Ch | 0;
781
+ this.Cl = Cl | 0;
782
+ this.Dh = Dh | 0;
783
+ this.Dl = Dl | 0;
784
+ this.Eh = Eh | 0;
785
+ this.El = El | 0;
786
+ this.Fh = Fh | 0;
787
+ this.Fl = Fl | 0;
788
+ this.Gh = Gh | 0;
789
+ this.Gl = Gl | 0;
790
+ this.Hh = Hh | 0;
791
+ this.Hl = Hl | 0;
792
+ }
793
+ process(view, offset) {
794
+ for (let i = 0;i < 16; i++, offset += 4) {
795
+ SHA512_W_H[i] = view.getUint32(offset);
796
+ SHA512_W_L[i] = view.getUint32(offset += 4);
797
+ }
798
+ for (let i = 16;i < 80; i++) {
799
+ const W15h = SHA512_W_H[i - 15] | 0;
800
+ const W15l = SHA512_W_L[i - 15] | 0;
801
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
802
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
803
+ const W2h = SHA512_W_H[i - 2] | 0;
804
+ const W2l = SHA512_W_L[i - 2] | 0;
805
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
806
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
807
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
808
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
809
+ SHA512_W_H[i] = SUMh | 0;
810
+ SHA512_W_L[i] = SUMl | 0;
811
+ }
812
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
813
+ for (let i = 0;i < 80; i++) {
814
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
815
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
816
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
817
+ const CHIl = El & Fl ^ ~El & Gl;
818
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
819
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
820
+ const T1l = T1ll | 0;
821
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
822
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
823
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
824
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
825
+ Hh = Gh | 0;
826
+ Hl = Gl | 0;
827
+ Gh = Fh | 0;
828
+ Gl = Fl | 0;
829
+ Fh = Eh | 0;
830
+ Fl = El | 0;
831
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
832
+ Dh = Ch | 0;
833
+ Dl = Cl | 0;
834
+ Ch = Bh | 0;
835
+ Cl = Bl | 0;
836
+ Bh = Ah | 0;
837
+ Bl = Al | 0;
838
+ const All = add3L(T1l, sigma0l, MAJl);
839
+ Ah = add3H(All, T1h, sigma0h, MAJh);
840
+ Al = All | 0;
841
+ }
842
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
843
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
844
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
845
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
846
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
847
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
848
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
849
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
850
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
851
+ }
852
+ roundClean() {
853
+ clean(SHA512_W_H, SHA512_W_L);
854
+ }
855
+ destroy() {
856
+ clean(this.buffer);
857
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
858
+ }
859
+ }
860
+ var sha512 = /* @__PURE__ */ createHasher(() => new SHA512);
861
+
862
+ // node_modules/@noble/hashes/esm/sha512.js
863
+ var sha5122 = sha512;
864
+
865
+ // src/utils.ts
866
+ var HEX_CHARS = "0123456789abcdef";
867
+ function bytesToHex2(bytes) {
868
+ let hex = "";
869
+ for (let i = 0;i < bytes.length; i++) {
870
+ hex += HEX_CHARS[bytes[i] >> 4];
871
+ hex += HEX_CHARS[bytes[i] & 15];
872
+ }
873
+ return hex;
874
+ }
875
+ function hexToBytes2(hex) {
876
+ if (hex.startsWith("0x")) {
877
+ hex = hex.slice(2);
878
+ }
879
+ if (hex.length % 2 !== 0) {
880
+ throw new Error("Invalid hex string: odd length");
881
+ }
882
+ const bytes = new Uint8Array(hex.length / 2);
883
+ for (let i = 0;i < bytes.length; i++) {
884
+ const hi = parseInt(hex[i * 2], 16);
885
+ const lo = parseInt(hex[i * 2 + 1], 16);
886
+ if (isNaN(hi) || isNaN(lo)) {
887
+ throw new Error(`Invalid hex character at position ${i * 2}`);
888
+ }
889
+ bytes[i] = hi << 4 | lo;
890
+ }
891
+ return bytes;
892
+ }
893
+ var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
894
+ var BASE58_MAP = new Map;
895
+ for (let i = 0;i < BASE58_ALPHABET.length; i++) {
896
+ BASE58_MAP.set(BASE58_ALPHABET[i], i);
897
+ }
898
+ function bytesToBase58(bytes) {
899
+ if (bytes.length === 0)
900
+ return "";
901
+ let zeros = 0;
902
+ while (zeros < bytes.length && bytes[zeros] === 0) {
903
+ zeros++;
904
+ }
905
+ const size = Math.floor((bytes.length - zeros) * 138 / 100) + 1;
906
+ const b58 = new Uint8Array(size);
907
+ let length = 0;
908
+ for (let i = zeros;i < bytes.length; i++) {
909
+ let carry = bytes[i];
910
+ let j = 0;
911
+ for (let it2 = size - 1;(carry !== 0 || j < length) && it2 >= 0; it2--, j++) {
912
+ carry += 256 * b58[it2];
913
+ b58[it2] = carry % 58;
914
+ carry = Math.floor(carry / 58);
915
+ }
916
+ length = j;
917
+ }
918
+ let it = size - length;
919
+ while (it < size && b58[it] === 0) {
920
+ it++;
921
+ }
922
+ let str = "1".repeat(zeros);
923
+ while (it < size) {
924
+ str += BASE58_ALPHABET[b58[it++]];
925
+ }
926
+ return str;
927
+ }
928
+ function base58ToBytes(str) {
929
+ if (str.length === 0)
930
+ return new Uint8Array(0);
931
+ let zeros = 0;
932
+ while (zeros < str.length && str[zeros] === "1") {
933
+ zeros++;
934
+ }
935
+ const size = Math.floor((str.length - zeros) * 733 / 1000) + 1;
936
+ const b256 = new Uint8Array(size);
937
+ let length = 0;
938
+ for (let i = zeros;i < str.length; i++) {
939
+ const value = BASE58_MAP.get(str[i]);
940
+ if (value === undefined) {
941
+ throw new Error(`Invalid base58 character: ${str[i]}`);
942
+ }
943
+ let carry = value;
944
+ let j = 0;
945
+ for (let it2 = size - 1;(carry !== 0 || j < length) && it2 >= 0; it2--, j++) {
946
+ carry += 58 * b256[it2];
947
+ b256[it2] = carry % 256;
948
+ carry = Math.floor(carry / 256);
949
+ }
950
+ length = j;
951
+ }
952
+ let it = size - length;
953
+ const result = new Uint8Array(zeros + (size - it));
954
+ let idx = zeros;
955
+ while (it < size) {
956
+ result[idx++] = b256[it++];
957
+ }
958
+ return result;
959
+ }
960
+ function u64ToLeBytes(value) {
961
+ const bytes = new Uint8Array(8);
962
+ for (let i = 0;i < 8; i++) {
963
+ bytes[i] = Number(value >> BigInt(i * 8) & BigInt(255));
964
+ }
965
+ return bytes;
966
+ }
967
+ function leBytesToU64(bytes) {
968
+ if (bytes.length !== 8) {
969
+ throw new Error("Expected 8 bytes for u64");
970
+ }
971
+ let value = BigInt(0);
972
+ for (let i = 0;i < 8; i++) {
973
+ value |= BigInt(bytes[i]) << BigInt(i * 8);
974
+ }
975
+ return value;
976
+ }
977
+ function concatBytes2(...arrays) {
978
+ const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
979
+ const result = new Uint8Array(totalLength);
980
+ let offset = 0;
981
+ for (const arr of arrays) {
982
+ result.set(arr, offset);
983
+ offset += arr.length;
984
+ }
985
+ return result;
986
+ }
987
+ function bytesEqual(a, b) {
988
+ if (a.length !== b.length)
989
+ return false;
990
+ for (let i = 0;i < a.length; i++) {
991
+ if (a[i] !== b[i])
992
+ return false;
993
+ }
994
+ return true;
995
+ }
996
+ function randomBytes2(length) {
997
+ const bytes = new Uint8Array(length);
998
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) {
999
+ crypto.getRandomValues(bytes);
1000
+ } else {
1001
+ for (let i = 0;i < length; i++) {
1002
+ bytes[i] = Math.floor(Math.random() * 256);
1003
+ }
1004
+ }
1005
+ return bytes;
1006
+ }
1007
+
1008
+ // src/keypair.ts
1009
+ etc.sha512Sync = (...m) => sha5122(etc.concatBytes(...m));
1010
+
1011
+ class Keypair {
1012
+ secretKey;
1013
+ _publicKey;
1014
+ constructor(secretKey, publicKey) {
1015
+ this.secretKey = secretKey;
1016
+ this._publicKey = publicKey;
1017
+ }
1018
+ static generate() {
1019
+ const secretKey = randomBytes2(32);
1020
+ const publicKey = getPublicKey(secretKey);
1021
+ return new Keypair(secretKey, publicKey);
1022
+ }
1023
+ static fromSecretKey(secretKey) {
1024
+ if (secretKey.length !== 32) {
1025
+ throw new Error("Secret key must be 32 bytes");
1026
+ }
1027
+ const publicKey = getPublicKey(secretKey);
1028
+ return new Keypair(new Uint8Array(secretKey), publicKey);
1029
+ }
1030
+ static fromHex(hex) {
1031
+ return Keypair.fromSecretKey(hexToBytes2(hex));
1032
+ }
1033
+ static fromBase58(base58) {
1034
+ return Keypair.fromSecretKey(base58ToBytes(base58));
1035
+ }
1036
+ get publicKey() {
1037
+ return new Uint8Array(this._publicKey);
1038
+ }
1039
+ get publicKeyHex() {
1040
+ return bytesToHex2(this._publicKey);
1041
+ }
1042
+ get publicKeyBase58() {
1043
+ return bytesToBase58(this._publicKey);
1044
+ }
1045
+ get secretKeyHex() {
1046
+ return bytesToHex2(this.secretKey);
1047
+ }
1048
+ get secretKeyBase58() {
1049
+ return bytesToBase58(this.secretKey);
1050
+ }
1051
+ sign(message) {
1052
+ return sign(message, this.secretKey);
1053
+ }
1054
+ static verify(signature, message, publicKey) {
1055
+ try {
1056
+ return verify(signature, message, publicKey);
1057
+ } catch {
1058
+ return false;
1059
+ }
1060
+ }
1061
+ signTransfer(to, amount, nonce, chainId = BigInt(1)) {
1062
+ const message = concatBytes2(this._publicKey, to, u64ToLeBytes(amount), u64ToLeBytes(nonce), u64ToLeBytes(chainId));
1063
+ const signature = this.sign(message);
1064
+ return {
1065
+ from: this.publicKey,
1066
+ to: new Uint8Array(to),
1067
+ amount,
1068
+ nonce,
1069
+ chainId,
1070
+ signature,
1071
+ signerPubkey: this.publicKey
1072
+ };
1073
+ }
1074
+ signWithdrawal(toL1Address, amount, nonce) {
1075
+ const message = concatBytes2(this._publicKey, toL1Address, u64ToLeBytes(amount), u64ToLeBytes(nonce));
1076
+ const signature = this.sign(message);
1077
+ return {
1078
+ from: this.publicKey,
1079
+ toL1Address: new Uint8Array(toL1Address),
1080
+ amount,
1081
+ nonce,
1082
+ signature,
1083
+ signerPubkey: this.publicKey
1084
+ };
1085
+ }
1086
+ }
1087
+
1088
+ class PublicKey {
1089
+ bytes;
1090
+ constructor(input) {
1091
+ if (typeof input === "string") {
1092
+ try {
1093
+ const decoded = base58ToBytes(input);
1094
+ if (decoded.length === 32) {
1095
+ this.bytes = decoded;
1096
+ return;
1097
+ }
1098
+ } catch {}
1099
+ this.bytes = hexToBytes2(input);
1100
+ } else {
1101
+ this.bytes = new Uint8Array(input);
1102
+ }
1103
+ if (this.bytes.length !== 32) {
1104
+ throw new Error("Public key must be 32 bytes");
1105
+ }
1106
+ }
1107
+ toBytes() {
1108
+ return new Uint8Array(this.bytes);
1109
+ }
1110
+ toHex() {
1111
+ return bytesToHex2(this.bytes);
1112
+ }
1113
+ toBase58() {
1114
+ return bytesToBase58(this.bytes);
1115
+ }
1116
+ toString() {
1117
+ return this.toBase58();
1118
+ }
1119
+ equals(other) {
1120
+ const otherBytes = other instanceof PublicKey ? other.bytes : other;
1121
+ if (this.bytes.length !== otherBytes.length)
1122
+ return false;
1123
+ for (let i = 0;i < this.bytes.length; i++) {
1124
+ if (this.bytes[i] !== otherBytes[i])
1125
+ return false;
1126
+ }
1127
+ return true;
1128
+ }
1129
+ }
1130
+
1131
+ // src/types.ts
1132
+ class ZelanaError extends Error {
1133
+ code;
1134
+ cause;
1135
+ constructor(message, code, cause) {
1136
+ super(message);
1137
+ this.code = code;
1138
+ this.cause = cause;
1139
+ this.name = "ZelanaError";
1140
+ }
1141
+ }
1142
+
1143
+ // src/client.ts
1144
+ class ApiClient {
1145
+ baseUrl;
1146
+ timeout;
1147
+ fetch;
1148
+ constructor(config) {
1149
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
1150
+ this.timeout = config.timeout ?? 30000;
1151
+ this.fetch = config.fetch ?? globalThis.fetch;
1152
+ }
1153
+ async request(method, path, body) {
1154
+ const url = `${this.baseUrl}${path}`;
1155
+ const controller = new AbortController;
1156
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
1157
+ try {
1158
+ const response = await this.fetch(url, {
1159
+ method,
1160
+ headers: {
1161
+ "Content-Type": "application/json"
1162
+ },
1163
+ body: body ? JSON.stringify(body, bigIntReplacer) : undefined,
1164
+ signal: controller.signal
1165
+ });
1166
+ clearTimeout(timeoutId);
1167
+ const text = await response.text();
1168
+ let data;
1169
+ try {
1170
+ data = JSON.parse(text, bigIntReviver);
1171
+ } catch {
1172
+ throw new ZelanaError(`Invalid JSON response: ${text}`, "PARSE_ERROR");
1173
+ }
1174
+ if (!response.ok) {
1175
+ const err2 = data;
1176
+ throw new ZelanaError(err2.error || `HTTP ${response.status}`, err2.code || "HTTP_ERROR");
1177
+ }
1178
+ return data;
1179
+ } catch (error) {
1180
+ clearTimeout(timeoutId);
1181
+ if (error instanceof ZelanaError) {
1182
+ throw error;
1183
+ }
1184
+ if (error instanceof Error && error.name === "AbortError") {
1185
+ throw new ZelanaError("Request timeout", "TIMEOUT");
1186
+ }
1187
+ throw new ZelanaError(error instanceof Error ? error.message : "Unknown error", "NETWORK_ERROR", error);
1188
+ }
1189
+ }
1190
+ async get(path) {
1191
+ return this.request("GET", path);
1192
+ }
1193
+ async post(path, body) {
1194
+ return this.request("POST", path, body);
1195
+ }
1196
+ async health() {
1197
+ const resp = await this.get("/health");
1198
+ return {
1199
+ healthy: resp.healthy,
1200
+ version: resp.version,
1201
+ uptimeSecs: BigInt(resp.uptime_secs)
1202
+ };
1203
+ }
1204
+ async getStateRoots() {
1205
+ const resp = await this.get("/status/roots");
1206
+ return {
1207
+ batchId: BigInt(resp.batch_id),
1208
+ stateRoot: resp.state_root,
1209
+ shieldedRoot: resp.shielded_root,
1210
+ commitmentCount: BigInt(resp.commitment_count)
1211
+ };
1212
+ }
1213
+ async getBatchStatus() {
1214
+ const resp = await this.get("/status/batch");
1215
+ return {
1216
+ currentBatchId: BigInt(resp.current_batch_id),
1217
+ currentBatchTxs: resp.current_batch_txs,
1218
+ provingCount: resp.proving_count,
1219
+ pendingSettlement: resp.pending_settlement
1220
+ };
1221
+ }
1222
+ async getStats() {
1223
+ const resp = await this.get("/status/stats");
1224
+ return {
1225
+ totalBatches: BigInt(resp.total_batches),
1226
+ totalTransactions: BigInt(resp.total_transactions),
1227
+ totalDeposited: BigInt(resp.total_deposited),
1228
+ totalWithdrawn: BigInt(resp.total_withdrawn),
1229
+ currentBatchId: BigInt(resp.current_batch_id),
1230
+ activeAccounts: BigInt(resp.active_accounts),
1231
+ shieldedCommitments: BigInt(resp.shielded_commitments),
1232
+ uptimeSecs: BigInt(resp.uptime_secs)
1233
+ };
1234
+ }
1235
+ async getAccount(accountId) {
1236
+ const resp = await this.post("/account", { account_id: accountId });
1237
+ return {
1238
+ accountId: resp.account_id,
1239
+ balance: BigInt(resp.balance),
1240
+ nonce: BigInt(resp.nonce)
1241
+ };
1242
+ }
1243
+ async getAccountByPubkey(pubkey) {
1244
+ return this.getAccount(bytesToHex2(pubkey));
1245
+ }
1246
+ async submitTransfer(request) {
1247
+ const resp = await this.post("/transfer", {
1248
+ from: Array.from(request.from),
1249
+ to: Array.from(request.to),
1250
+ amount: Number(request.amount),
1251
+ nonce: Number(request.nonce),
1252
+ chain_id: Number(request.chainId),
1253
+ signature: Array.from(request.signature),
1254
+ signer_pubkey: Array.from(request.signerPubkey)
1255
+ });
1256
+ return {
1257
+ txHash: resp.tx_hash,
1258
+ accepted: resp.accepted,
1259
+ message: resp.message
1260
+ };
1261
+ }
1262
+ async submitWithdrawal(request) {
1263
+ const resp = await this.post("/withdraw", {
1264
+ from: Array.from(request.from),
1265
+ to_l1_address: Array.from(request.toL1Address),
1266
+ amount: Number(request.amount),
1267
+ nonce: Number(request.nonce),
1268
+ signature: Array.from(request.signature),
1269
+ signer_pubkey: Array.from(request.signerPubkey)
1270
+ });
1271
+ return {
1272
+ txHash: resp.tx_hash,
1273
+ accepted: resp.accepted,
1274
+ estimatedCompletion: resp.estimated_completion,
1275
+ message: resp.message
1276
+ };
1277
+ }
1278
+ async getWithdrawalStatus(txHash) {
1279
+ const resp = await this.post("/withdraw/status", { tx_hash: txHash });
1280
+ return {
1281
+ txHash: resp.tx_hash,
1282
+ state: resp.state,
1283
+ amount: BigInt(resp.amount),
1284
+ toL1Address: resp.to_l1_address,
1285
+ l1TxSig: resp.l1_tx_sig
1286
+ };
1287
+ }
1288
+ async getFastWithdrawQuote(amount) {
1289
+ const resp = await this.post("/withdraw/fast/quote", { amount: Number(amount) });
1290
+ return {
1291
+ available: resp.available,
1292
+ amount: BigInt(resp.amount),
1293
+ fee: BigInt(resp.fee),
1294
+ amountReceived: BigInt(resp.amount_received),
1295
+ feeBps: resp.fee_bps,
1296
+ lpAddress: resp.lp_address
1297
+ };
1298
+ }
1299
+ async submitShielded(request) {
1300
+ const resp = await this.post("/shielded/submit", {
1301
+ proof: Array.from(request.proof),
1302
+ nullifier: Array.from(request.nullifier),
1303
+ commitment: Array.from(request.commitment),
1304
+ ciphertext: Array.from(request.ciphertext),
1305
+ ephemeral_key: Array.from(request.ephemeralKey)
1306
+ });
1307
+ return {
1308
+ txHash: resp.tx_hash,
1309
+ accepted: resp.accepted,
1310
+ position: resp.position,
1311
+ message: resp.message
1312
+ };
1313
+ }
1314
+ async getMerklePath(position) {
1315
+ const resp = await this.post("/shielded/merkle_path", { position });
1316
+ return {
1317
+ position: resp.position,
1318
+ path: resp.path,
1319
+ root: resp.root
1320
+ };
1321
+ }
1322
+ async scanNotes(decryptionKey, ownerPk, fromPosition, limit) {
1323
+ const resp = await this.post("/shielded/scan", {
1324
+ decryption_key: Array.from(decryptionKey),
1325
+ owner_pk: Array.from(ownerPk),
1326
+ from_position: fromPosition,
1327
+ limit
1328
+ });
1329
+ return {
1330
+ notes: resp.notes.map((n) => ({
1331
+ position: n.position,
1332
+ commitment: n.commitment,
1333
+ value: BigInt(n.value),
1334
+ memo: n.memo
1335
+ })),
1336
+ scannedTo: resp.scanned_to
1337
+ };
1338
+ }
1339
+ async getBatch(batchId) {
1340
+ const resp = await this.post("/batch", { batch_id: Number(batchId) });
1341
+ if (!resp.batch)
1342
+ return null;
1343
+ return parseBatchSummary(resp.batch);
1344
+ }
1345
+ async listBatches(params = {}) {
1346
+ const resp = await this.post("/batches", {
1347
+ offset: params.offset ?? 0,
1348
+ limit: params.limit ?? 20
1349
+ });
1350
+ return {
1351
+ batches: resp.batches.map(parseBatchSummary),
1352
+ total: resp.total
1353
+ };
1354
+ }
1355
+ async getTransaction(txHash) {
1356
+ const resp = await this.post("/tx", { tx_hash: txHash });
1357
+ if (!resp.tx)
1358
+ return null;
1359
+ return parseTxSummary(resp.tx);
1360
+ }
1361
+ async listTransactions(params = {}) {
1362
+ const resp = await this.post("/txs", {
1363
+ offset: params.offset ?? 0,
1364
+ limit: params.limit ?? 20,
1365
+ batch_id: params.batchId ? Number(params.batchId) : undefined,
1366
+ tx_type: params.txType,
1367
+ status: params.status
1368
+ });
1369
+ return {
1370
+ transactions: resp.transactions.map(parseTxSummary),
1371
+ total: resp.total
1372
+ };
1373
+ }
1374
+ async getCommittee() {
1375
+ const resp = await this.get("/encrypted/committee");
1376
+ return {
1377
+ enabled: resp.enabled,
1378
+ threshold: resp.threshold,
1379
+ totalMembers: resp.total_members,
1380
+ epoch: BigInt(resp.epoch),
1381
+ members: resp.members.map((m) => ({
1382
+ id: m.id,
1383
+ publicKey: m.public_key,
1384
+ endpoint: m.endpoint
1385
+ })),
1386
+ pendingCount: resp.pending_count
1387
+ };
1388
+ }
1389
+ async devDeposit(to, amount) {
1390
+ const resp = await this.post("/dev/deposit", {
1391
+ to,
1392
+ amount: Number(amount)
1393
+ });
1394
+ return {
1395
+ txHash: resp.tx_hash,
1396
+ accepted: resp.accepted,
1397
+ newBalance: BigInt(resp.new_balance),
1398
+ message: resp.message
1399
+ };
1400
+ }
1401
+ async devSeal(waitForProof = false) {
1402
+ const resp = await this.post("/dev/seal", {
1403
+ wait_for_proof: waitForProof
1404
+ });
1405
+ return {
1406
+ batchId: BigInt(resp.batch_id),
1407
+ txCount: resp.tx_count,
1408
+ message: resp.message
1409
+ };
1410
+ }
1411
+ }
1412
+ function parseBatchSummary(b) {
1413
+ return {
1414
+ batchId: BigInt(b.batch_id),
1415
+ txCount: b.tx_count,
1416
+ stateRoot: b.state_root,
1417
+ shieldedRoot: b.shielded_root,
1418
+ l1TxSig: b.l1_tx_sig,
1419
+ status: b.status,
1420
+ createdAt: BigInt(b.created_at),
1421
+ settledAt: b.settled_at ? BigInt(b.settled_at) : undefined
1422
+ };
1423
+ }
1424
+ function parseTxSummary(t) {
1425
+ return {
1426
+ txHash: t.tx_hash,
1427
+ txType: t.tx_type,
1428
+ batchId: t.batch_id ? BigInt(t.batch_id) : undefined,
1429
+ status: t.status,
1430
+ receivedAt: BigInt(t.received_at),
1431
+ executedAt: t.executed_at ? BigInt(t.executed_at) : undefined,
1432
+ amount: t.amount ? BigInt(t.amount) : undefined,
1433
+ from: t.from,
1434
+ to: t.to
1435
+ };
1436
+ }
1437
+ function bigIntReplacer(_key, value) {
1438
+ if (typeof value === "bigint") {
1439
+ return Number(value);
1440
+ }
1441
+ return value;
1442
+ }
1443
+ function bigIntReviver(_key, value) {
1444
+ return value;
1445
+ }
1446
+
1447
+ // src/zelana.ts
1448
+ class ZelanaClient {
1449
+ api;
1450
+ keypair;
1451
+ chainId;
1452
+ constructor(config) {
1453
+ this.api = new ApiClient(config);
1454
+ this.keypair = config.keypair ?? null;
1455
+ this.chainId = config.chainId ?? BigInt(1);
1456
+ }
1457
+ get apiClient() {
1458
+ return this.api;
1459
+ }
1460
+ get publicKey() {
1461
+ return this.keypair?.publicKey ?? null;
1462
+ }
1463
+ get publicKeyHex() {
1464
+ return this.keypair?.publicKeyHex ?? null;
1465
+ }
1466
+ async isHealthy() {
1467
+ try {
1468
+ const health = await this.api.health();
1469
+ return health.healthy;
1470
+ } catch {
1471
+ return false;
1472
+ }
1473
+ }
1474
+ async health() {
1475
+ return this.api.health();
1476
+ }
1477
+ async getStateRoots() {
1478
+ return this.api.getStateRoots();
1479
+ }
1480
+ async getBatchStatus() {
1481
+ return this.api.getBatchStatus();
1482
+ }
1483
+ async getStats() {
1484
+ return this.api.getStats();
1485
+ }
1486
+ async getAccount() {
1487
+ if (!this.keypair) {
1488
+ throw new ZelanaError("No keypair configured", "NO_KEYPAIR");
1489
+ }
1490
+ return this.api.getAccountByPubkey(this.keypair.publicKey);
1491
+ }
1492
+ async getAccountFor(pubkey) {
1493
+ if (typeof pubkey === "string") {
1494
+ return this.api.getAccount(pubkey);
1495
+ }
1496
+ return this.api.getAccountByPubkey(pubkey);
1497
+ }
1498
+ async getBalance() {
1499
+ const account = await this.getAccount();
1500
+ return account.balance;
1501
+ }
1502
+ async getNonce() {
1503
+ const account = await this.getAccount();
1504
+ return account.nonce;
1505
+ }
1506
+ async transfer(to, amount, nonce) {
1507
+ if (!this.keypair) {
1508
+ throw new ZelanaError("No keypair configured", "NO_KEYPAIR");
1509
+ }
1510
+ const toPubkey = typeof to === "string" ? new PublicKey(to).toBytes() : to;
1511
+ const txNonce = nonce ?? await this.getNonce();
1512
+ const request = this.keypair.signTransfer(toPubkey, amount, txNonce, this.chainId);
1513
+ return this.api.submitTransfer(request);
1514
+ }
1515
+ async transferAll(to, reserve = BigInt(0)) {
1516
+ const account = await this.getAccount();
1517
+ const amount = account.balance - reserve;
1518
+ if (amount <= 0n) {
1519
+ throw new ZelanaError(`Insufficient balance: ${account.balance} (reserve: ${reserve})`, "INSUFFICIENT_BALANCE");
1520
+ }
1521
+ return this.transfer(to, amount, account.nonce);
1522
+ }
1523
+ async withdraw(toL1Address, amount, nonce) {
1524
+ if (!this.keypair) {
1525
+ throw new ZelanaError("No keypair configured", "NO_KEYPAIR");
1526
+ }
1527
+ const l1Pubkey = typeof toL1Address === "string" ? new PublicKey(toL1Address).toBytes() : toL1Address;
1528
+ const txNonce = nonce ?? await this.getNonce();
1529
+ const request = this.keypair.signWithdrawal(l1Pubkey, amount, txNonce);
1530
+ return this.api.submitWithdrawal(request);
1531
+ }
1532
+ async getWithdrawalStatus(txHash) {
1533
+ return this.api.getWithdrawalStatus(txHash);
1534
+ }
1535
+ async getFastWithdrawQuote(amount) {
1536
+ return this.api.getFastWithdrawQuote(amount);
1537
+ }
1538
+ async getTransaction(txHash) {
1539
+ return this.api.getTransaction(txHash);
1540
+ }
1541
+ async listTransactions(params = {}) {
1542
+ return this.api.listTransactions(params);
1543
+ }
1544
+ async getBatch(batchId) {
1545
+ return this.api.getBatch(batchId);
1546
+ }
1547
+ async listBatches(params = {}) {
1548
+ return this.api.listBatches(params);
1549
+ }
1550
+ async waitForTransaction(txHash, targetStatus = "executed", timeoutMs = 60000, pollIntervalMs = 1000) {
1551
+ const statusOrder = ["pending", "included", "executed", "settled"];
1552
+ const targetIndex = statusOrder.indexOf(targetStatus);
1553
+ const startTime = Date.now();
1554
+ while (Date.now() - startTime < timeoutMs) {
1555
+ const tx = await this.getTransaction(txHash);
1556
+ if (!tx) {
1557
+ throw new ZelanaError(`Transaction not found: ${txHash}`, "TX_NOT_FOUND");
1558
+ }
1559
+ if (tx.status === "failed") {
1560
+ throw new ZelanaError(`Transaction failed: ${txHash}`, "TX_FAILED");
1561
+ }
1562
+ const currentIndex = statusOrder.indexOf(tx.status);
1563
+ if (currentIndex >= targetIndex) {
1564
+ return tx;
1565
+ }
1566
+ await sleep(pollIntervalMs);
1567
+ }
1568
+ throw new ZelanaError(`Timeout waiting for transaction ${txHash} to reach ${targetStatus}`, "TIMEOUT");
1569
+ }
1570
+ async waitForBatch(batchId, timeoutMs = 120000, pollIntervalMs = 2000) {
1571
+ const startTime = Date.now();
1572
+ while (Date.now() - startTime < timeoutMs) {
1573
+ const batch = await this.getBatch(batchId);
1574
+ if (!batch) {
1575
+ throw new ZelanaError(`Batch not found: ${batchId}`, "BATCH_NOT_FOUND");
1576
+ }
1577
+ if (batch.status === "failed") {
1578
+ throw new ZelanaError(`Batch failed: ${batchId}`, "BATCH_FAILED");
1579
+ }
1580
+ if (batch.status === "settled") {
1581
+ return batch;
1582
+ }
1583
+ await sleep(pollIntervalMs);
1584
+ }
1585
+ throw new ZelanaError(`Timeout waiting for batch ${batchId} to settle`, "TIMEOUT");
1586
+ }
1587
+ async devDeposit(amount) {
1588
+ if (!this.keypair) {
1589
+ throw new ZelanaError("No keypair configured", "NO_KEYPAIR");
1590
+ }
1591
+ return this.api.devDeposit(this.keypair.publicKeyHex, amount);
1592
+ }
1593
+ async devDepositTo(to, amount) {
1594
+ const toHex = typeof to === "string" ? to : bytesToHex2(to);
1595
+ return this.api.devDeposit(toHex, amount);
1596
+ }
1597
+ async devSeal(waitForProof = false) {
1598
+ return this.api.devSeal(waitForProof);
1599
+ }
1600
+ }
1601
+ function sleep(ms) {
1602
+ return new Promise((resolve) => setTimeout(resolve, ms));
1603
+ }
1604
+ // src/shielded.ts
1605
+ function generateShieldedKeys() {
1606
+ const spendingKey = randomBytes2(32);
1607
+ const viewingKey = deriveViewingKey(spendingKey);
1608
+ const publicKey = derivePublicKey(spendingKey);
1609
+ return { spendingKey, viewingKey, publicKey };
1610
+ }
1611
+ function shieldedKeysFromSpendingKey(spendingKey) {
1612
+ const viewingKey = deriveViewingKey(spendingKey);
1613
+ const publicKey = derivePublicKey(spendingKey);
1614
+ return { spendingKey: new Uint8Array(spendingKey), viewingKey, publicKey };
1615
+ }
1616
+ function deriveViewingKey(spendingKey) {
1617
+ const domain = new TextEncoder().encode("ZelanaIVK");
1618
+ const hash = sha5122(concatBytes2(domain, spendingKey));
1619
+ return hash.slice(0, 32);
1620
+ }
1621
+ function derivePublicKey(spendingKey) {
1622
+ const domain = new TextEncoder().encode("ZelanaPK");
1623
+ const hash = sha5122(concatBytes2(domain, spendingKey));
1624
+ return hash.slice(0, 32);
1625
+ }
1626
+ function createNote(value, ownerPk, position) {
1627
+ return {
1628
+ value,
1629
+ randomness: randomBytes2(32),
1630
+ ownerPk: new Uint8Array(ownerPk),
1631
+ position
1632
+ };
1633
+ }
1634
+ function noteWithRandomness(value, ownerPk, randomness, position) {
1635
+ return {
1636
+ value,
1637
+ randomness: new Uint8Array(randomness),
1638
+ ownerPk: new Uint8Array(ownerPk),
1639
+ position
1640
+ };
1641
+ }
1642
+ function computeCommitment(note) {
1643
+ const domain = new TextEncoder().encode("ZelanaCommit");
1644
+ const message = concatBytes2(domain, u64ToLeBytes(note.value), note.randomness, note.ownerPk);
1645
+ const hash = sha5122(message);
1646
+ return hash.slice(0, 32);
1647
+ }
1648
+ function computeNullifier(note, spendingKey) {
1649
+ if (note.position === undefined) {
1650
+ return null;
1651
+ }
1652
+ const nullifierKey = deriveNullifierKey(spendingKey);
1653
+ const commitment = computeCommitment(note);
1654
+ const domain = new TextEncoder().encode("ZelanaNullifier");
1655
+ const message = concatBytes2(domain, nullifierKey, commitment, u64ToLeBytes(note.position));
1656
+ const hash = sha5122(message);
1657
+ return hash.slice(0, 32);
1658
+ }
1659
+ function deriveNullifierKey(spendingKey) {
1660
+ const domain = new TextEncoder().encode("ZelanaNK");
1661
+ const hash = sha5122(concatBytes2(domain, spendingKey));
1662
+ return hash.slice(0, 32);
1663
+ }
1664
+
1665
+ class ShieldedTransactionBuilder {
1666
+ inputs = [];
1667
+ outputs = [];
1668
+ merkleRoot = null;
1669
+ addInput(input) {
1670
+ if (input.note.position === undefined) {
1671
+ throw new Error("Input note must have a position");
1672
+ }
1673
+ this.inputs.push(input);
1674
+ return this;
1675
+ }
1676
+ addOutput(output) {
1677
+ this.outputs.push(output);
1678
+ return this;
1679
+ }
1680
+ setMerkleRoot(root) {
1681
+ this.merkleRoot = new Uint8Array(root);
1682
+ return this;
1683
+ }
1684
+ validate() {
1685
+ if (this.inputs.length === 0) {
1686
+ return { valid: false, error: "No inputs" };
1687
+ }
1688
+ if (this.outputs.length === 0) {
1689
+ return { valid: false, error: "No outputs" };
1690
+ }
1691
+ if (!this.merkleRoot) {
1692
+ return { valid: false, error: "Merkle root not set" };
1693
+ }
1694
+ const inputSum = this.inputs.reduce((sum, i) => sum + i.note.value, 0n);
1695
+ const outputSum = this.outputs.reduce((sum, o) => sum + o.value, 0n);
1696
+ if (inputSum !== outputSum) {
1697
+ return {
1698
+ valid: false,
1699
+ error: `Balance mismatch: inputs=${inputSum}, outputs=${outputSum}`
1700
+ };
1701
+ }
1702
+ return { valid: true };
1703
+ }
1704
+ prepare() {
1705
+ const validation = this.validate();
1706
+ if (!validation.valid) {
1707
+ throw new Error(`Invalid transaction: ${validation.error}`);
1708
+ }
1709
+ const inputsWithNullifiers = this.inputs.map((input) => {
1710
+ const nullifier = computeNullifier(input.note, input.spendingKey);
1711
+ if (!nullifier) {
1712
+ throw new Error("Failed to compute nullifier");
1713
+ }
1714
+ return {
1715
+ note: input.note,
1716
+ merklePath: input.merklePath,
1717
+ spendingKey: input.spendingKey,
1718
+ nullifier
1719
+ };
1720
+ });
1721
+ const outputsWithCommitments = this.outputs.map((output) => {
1722
+ const note = createNote(output.value, output.recipientPk);
1723
+ const commitment = computeCommitment(note);
1724
+ return { note, commitment, memo: output.memo };
1725
+ });
1726
+ const encryptedOutputs = outputsWithCommitments.map((o) => encryptNote(o.note, o.memo));
1727
+ return {
1728
+ nullifiers: inputsWithNullifiers.map((i) => i.nullifier),
1729
+ commitments: outputsWithCommitments.map((o) => o.commitment),
1730
+ encryptedOutputs,
1731
+ merkleRoot: this.merkleRoot,
1732
+ witness: {
1733
+ inputs: inputsWithNullifiers,
1734
+ outputs: outputsWithCommitments.map((o) => ({
1735
+ note: o.note,
1736
+ commitment: o.commitment
1737
+ }))
1738
+ }
1739
+ };
1740
+ }
1741
+ clear() {
1742
+ this.inputs = [];
1743
+ this.outputs = [];
1744
+ this.merkleRoot = null;
1745
+ return this;
1746
+ }
1747
+ }
1748
+ function encryptNote(note, memo) {
1749
+ const ephemeralPk = randomBytes2(32);
1750
+ const nonce = randomBytes2(12);
1751
+ const plaintext = concatBytes2(u64ToLeBytes(note.value), note.randomness, memo ? new Uint8Array([...u16ToLeBytes(memo.length), ...memo]) : new Uint8Array([0, 0]));
1752
+ const key = sha5122(concatBytes2(ephemeralPk, note.ownerPk)).slice(0, 32);
1753
+ const ciphertext = xorEncrypt(plaintext, key, nonce);
1754
+ return {
1755
+ ephemeralPk,
1756
+ nonce,
1757
+ ciphertext
1758
+ };
1759
+ }
1760
+ function xorEncrypt(data, key, nonce) {
1761
+ const stream = sha5122(concatBytes2(key, nonce));
1762
+ const result = new Uint8Array(data.length);
1763
+ for (let i = 0;i < data.length; i++) {
1764
+ result[i] = data[i] ^ stream[i % stream.length];
1765
+ }
1766
+ return result;
1767
+ }
1768
+ function u16ToLeBytes(value) {
1769
+ return new Uint8Array([value & 255, value >> 8 & 255]);
1770
+ }
1771
+ function tryDecryptNote(encrypted, viewingKey, ownerPk, position) {
1772
+ return null;
1773
+ }
1774
+ var shielded = {
1775
+ generateKeys: generateShieldedKeys,
1776
+ keysFromSpendingKey: shieldedKeysFromSpendingKey,
1777
+ createNote,
1778
+ noteWithRandomness,
1779
+ computeCommitment,
1780
+ computeNullifier,
1781
+ TransactionBuilder: ShieldedTransactionBuilder
1782
+ };
1783
+ export {
1784
+ u64ToLeBytes,
1785
+ tryDecryptNote,
1786
+ shieldedKeysFromSpendingKey,
1787
+ shielded,
1788
+ randomBytes2 as randomBytes,
1789
+ noteWithRandomness,
1790
+ leBytesToU64,
1791
+ hexToBytes2 as hexToBytes,
1792
+ generateShieldedKeys,
1793
+ createNote,
1794
+ concatBytes2 as concatBytes,
1795
+ computeNullifier,
1796
+ computeCommitment,
1797
+ bytesToHex2 as bytesToHex,
1798
+ bytesToBase58,
1799
+ bytesEqual,
1800
+ base58ToBytes,
1801
+ ZelanaError,
1802
+ ZelanaClient,
1803
+ ShieldedTransactionBuilder,
1804
+ PublicKey,
1805
+ Keypair,
1806
+ ApiClient
1807
+ };