n3-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,4046 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/data/ws.ts
8
+ var MarketWS = class {
9
+ env;
10
+ WSImpl;
11
+ url;
12
+ ws = null;
13
+ wantsOpen = false;
14
+ timers = {};
15
+ backoffMs = 500;
16
+ maxBackoffMs = 1e4;
17
+ // key -> set of handlers
18
+ subs = /* @__PURE__ */ new Map();
19
+ constructor(env2, WSImpl) {
20
+ this.env = env2;
21
+ this.url = env2.wsUrl.replace(/\/$/, "") + "/ws";
22
+ this.WSImpl = WSImpl ?? globalThis.WebSocket;
23
+ if (!this.WSImpl) throw new Error("No WebSocket implementation; pass WSImpl (e.g. isomorphic-ws) for Node");
24
+ }
25
+ connect() {
26
+ if (this.ws) return;
27
+ this.wantsOpen = true;
28
+ const ws = new this.WSImpl(this.url);
29
+ this.ws = ws;
30
+ ws.addEventListener("open", () => {
31
+ this.backoffMs = 500;
32
+ for (const key of this.subs.keys()) {
33
+ try {
34
+ ws.send(JSON.stringify({ op: "sub", key }));
35
+ } catch {
36
+ }
37
+ }
38
+ this.timers.ping = setInterval(() => {
39
+ try {
40
+ ws.ping?.();
41
+ } catch {
42
+ }
43
+ }, 3e4);
44
+ });
45
+ ws.addEventListener("message", (ev) => {
46
+ let data;
47
+ try {
48
+ data = typeof ev.data === "string" ? JSON.parse(ev.data) : JSON.parse(Buffer.from(ev.data).toString("utf8"));
49
+ } catch {
50
+ return;
51
+ }
52
+ const key = data?.t;
53
+ const msg = data?.d;
54
+ if (!key) return;
55
+ const set = this.subs.get(key);
56
+ if (!set || set.size === 0) return;
57
+ for (const fn of set) {
58
+ try {
59
+ fn(msg);
60
+ } catch {
61
+ }
62
+ }
63
+ });
64
+ const scheduleReconnect = () => {
65
+ this.ws = null;
66
+ if (!this.wantsOpen) return;
67
+ if (this.timers.ping) clearInterval(this.timers.ping);
68
+ if (this.timers.reconnect) clearTimeout(this.timers.reconnect);
69
+ this.timers.reconnect = setTimeout(() => this.connect(), this.backoffMs);
70
+ this.backoffMs = Math.min(this.maxBackoffMs, Math.floor(this.backoffMs * 1.7));
71
+ };
72
+ ws.addEventListener("close", scheduleReconnect);
73
+ ws.addEventListener("error", scheduleReconnect);
74
+ }
75
+ /** Subscribe to a raw topic key (e.g. "n3.indicatives:241"). */
76
+ on(key, fn) {
77
+ let set = this.subs.get(key);
78
+ if (!set) {
79
+ set = /* @__PURE__ */ new Set();
80
+ this.subs.set(key, set);
81
+ }
82
+ set.add(fn);
83
+ if (!this.ws) this.connect();
84
+ else try {
85
+ this.ws.send(JSON.stringify({ op: "sub", key }));
86
+ } catch {
87
+ }
88
+ return {
89
+ off: () => {
90
+ const s = this.subs.get(key);
91
+ if (!s) return;
92
+ s.delete(fn);
93
+ if (s.size === 0) {
94
+ this.subs.delete(key);
95
+ try {
96
+ this.ws?.send(JSON.stringify({ op: "unsub", key }));
97
+ } catch {
98
+ }
99
+ }
100
+ }
101
+ };
102
+ }
103
+ /** Convenience: topic + assetId → "topic:assetId" */
104
+ onTopic(topic, assetId, fn) {
105
+ return this.on(`${topic}:${assetId}`, fn);
106
+ }
107
+ close() {
108
+ this.wantsOpen = false;
109
+ if (this.timers.ping) clearInterval(this.timers.ping);
110
+ if (this.timers.reconnect) clearTimeout(this.timers.reconnect);
111
+ try {
112
+ this.ws?.close();
113
+ } catch {
114
+ }
115
+ this.ws = null;
116
+ }
117
+ };
118
+
119
+ // src/data/auth.ts
120
+ import { sign } from "@noble/ed25519";
121
+ function strip0x(s) {
122
+ return s.startsWith("0x") ? s.slice(2) : s;
123
+ }
124
+ function u8aToHex(u82) {
125
+ return "0x" + Array.from(u82).map((b) => b.toString(16).padStart(2, "0")).join("");
126
+ }
127
+ function normalizeKeyHex(x) {
128
+ if (!x) return void 0;
129
+ return "0x" + strip0x(x).toLowerCase();
130
+ }
131
+ function makeSigner(input) {
132
+ const pubkeyHex = normalizeKeyHex(input.pubkeyHex);
133
+ if (input.signer) {
134
+ return {
135
+ pubkeyHex,
136
+ signMsg: async (msg) => u8aToHex(await input.signer(msg))
137
+ };
138
+ }
139
+ if (input.secretKey) {
140
+ const sk = input.secretKey;
141
+ return {
142
+ pubkeyHex,
143
+ signMsg: async (msg) => u8aToHex(await sign(msg, sk))
144
+ };
145
+ }
146
+ return { pubkeyHex: void 0, signMsg: void 0 };
147
+ }
148
+ async function buildAuthHeaders(signMsg, pubkeyHex, nonce) {
149
+ const hdrs = {};
150
+ if (!signMsg || !pubkeyHex) return hdrs;
151
+ const sig = await signMsg(new TextEncoder().encode(nonce));
152
+ hdrs["x-n3-key"] = normalizeKeyHex(pubkeyHex);
153
+ hdrs["x-n3-sig"] = sig;
154
+ hdrs["x-n3-nonce"] = nonce;
155
+ return hdrs;
156
+ }
157
+
158
+ // src/data/http.ts
159
+ var defaultNonce = () => `${(/* @__PURE__ */ new Date()).toISOString()}-${Math.random().toString(16).slice(2)}`;
160
+ function makeHttp(env2) {
161
+ const fetchFn = env2.fetchFn ?? globalThis.fetch;
162
+ if (!fetchFn) throw new Error("No fetch available; pass env.fetchFn");
163
+ const { signMsg, pubkeyHex } = makeSigner({ pubkeyHex: env2.pubkeyHex, signer: env2.signer, secretKey: env2.secretKey });
164
+ const makeNonce = env2.makeNonce ?? defaultNonce;
165
+ async function postJson(url, body) {
166
+ const nonce = makeNonce();
167
+ const auth = await buildAuthHeaders(signMsg, pubkeyHex, nonce);
168
+ const r = await fetchFn(url, {
169
+ method: "POST",
170
+ headers: { "content-type": "application/json", ...auth },
171
+ body: JSON.stringify(body)
172
+ });
173
+ if (!r.ok) {
174
+ const txt = await r.text().catch(() => "");
175
+ throw new Error(`HTTP ${r.status} ${txt}`);
176
+ }
177
+ return await r.json();
178
+ }
179
+ return { postJson };
180
+ }
181
+
182
+ // src/data/graphql.ts
183
+ function makeGraphQL(env2) {
184
+ const { postJson } = makeHttp(env2);
185
+ const url = env2.gqlUrl;
186
+ async function gql(query, variables) {
187
+ const res = await postJson(url, { query, variables });
188
+ if (res.errors?.length) throw new Error(res.errors.map((e) => e.message).join("; "));
189
+ if (!res.data) throw new Error("no data");
190
+ return res.data;
191
+ }
192
+ return {
193
+ async batches(assetId, limit = 100) {
194
+ const q = (
195
+ /* GraphQL */
196
+ `
197
+ query($assetId: String!, $limit: Int) {
198
+ batches(assetId: $assetId, limit: $limit) {
199
+ ts assetId extOpsHash nfHash batchId kind opsJson
200
+ }
201
+ }`
202
+ );
203
+ const d = await gql(q, { assetId: String(assetId), limit });
204
+ return d.batches;
205
+ },
206
+ async indicatives(assetId, sinceSec) {
207
+ const q = (
208
+ /* GraphQL */
209
+ `
210
+ query($assetId: String!, $sinceSec: Int!) {
211
+ indicatives(assetId: $assetId, sinceSec: $sinceSec) {
212
+ ts assetId midPx bidPx askPx spreadBp src
213
+ mid lo hi liquidityTier rootFrom rootTo
214
+ }
215
+ }`
216
+ );
217
+ const d = await gql(q, { assetId: String(assetId), sinceSec });
218
+ return d.indicatives;
219
+ },
220
+ async candles(assetId, window, limit = 300) {
221
+ const q = (
222
+ /* GraphQL */
223
+ `
224
+ query($assetId: String!, $window: String!, $limit: Int) {
225
+ candles(assetId: $assetId, window: $window, limit: $limit) {
226
+ ts assetId window o h l c v
227
+ }
228
+ }`
229
+ );
230
+ const d = await gql(q, { assetId: String(assetId), window, limit });
231
+ return d.candles;
232
+ }
233
+ };
234
+ }
235
+
236
+ // src/data/_common.ts
237
+ var Topics = {
238
+ Indicatives: "n3.indicatives",
239
+ Candles: "n3.candles",
240
+ Batches: "n3.batches",
241
+ Depth: "n3.depth",
242
+ Trades: "n3.trades"
243
+ };
244
+ var topicKey = (topic, assetId) => `${topic}:${assetId}`;
245
+ function makeInfra(env2, WSImpl) {
246
+ const gql = makeGraphQL(env2);
247
+ const ws = new MarketWS(env2, WSImpl);
248
+ return { gql, ws };
249
+ }
250
+ var SubBag = class {
251
+ subs = [];
252
+ add(s) {
253
+ this.subs.push(s);
254
+ return s;
255
+ }
256
+ clear() {
257
+ for (const s of this.subs) s.off();
258
+ this.subs = [];
259
+ }
260
+ };
261
+
262
+ // src/info/index.ts
263
+ var info_exports = {};
264
+ __export(info_exports, {
265
+ makeBatchesInfo: () => makeBatchesInfo,
266
+ makeCandlesInfo: () => makeCandlesInfo,
267
+ makeDepthInfo: () => makeDepthInfo,
268
+ makeIndicativesInfo: () => makeIndicativesInfo,
269
+ makeTradesInfo: () => makeTradesInfo
270
+ });
271
+
272
+ // src/info/indicatives.ts
273
+ function makeIndicativesInfo(env2) {
274
+ const { gql } = makeInfra(env2);
275
+ return {
276
+ /**
277
+ * List recent indicatives for an asset since N seconds ago.
278
+ * Server decides the exact window; you already expose (assetId, sinceSec).
279
+ */
280
+ list(assetId, sinceSec) {
281
+ return gql.indicatives(assetId, sinceSec);
282
+ },
283
+ /** Convenience: return the latest indicative (or null if none). */
284
+ async latest(assetId, sinceSec = 300) {
285
+ const rows = await gql.indicatives(assetId, sinceSec);
286
+ return rows.length ? rows[rows.length - 1] : null;
287
+ }
288
+ };
289
+ }
290
+
291
+ // src/info/candles.ts
292
+ function makeCandlesInfo(env2) {
293
+ const { gql } = makeInfra(env2);
294
+ return {
295
+ /** Paginated/limited candles (server decides ordering; usually oldest->newest). */
296
+ list(assetId, window, limit = 300) {
297
+ return gql.candles(assetId, window, limit);
298
+ },
299
+ /**
300
+ * Optional: range query if your GraphQL supports it.
301
+ * If not implemented server-side, remove this or let it throw.
302
+ */
303
+ async range(assetId, window, start, end) {
304
+ if (typeof gql.candlesRange !== "function") {
305
+ throw new Error("candles.range not supported by server GraphQL");
306
+ }
307
+ return gql.candlesRange(assetId, window, start, end);
308
+ },
309
+ /** Convenience: last candle (null if missing). */
310
+ async latest(assetId, window) {
311
+ const rows = await gql.candles(assetId, window, 1);
312
+ return rows.length ? rows[rows.length - 1] : null;
313
+ }
314
+ };
315
+ }
316
+
317
+ // src/info/depth.ts
318
+ function makeDepthInfo(env2) {
319
+ const { gql } = makeInfra(env2);
320
+ return {
321
+ /**
322
+ * If server implements gql.depth(assetId, {start?, end?, limit?}),
323
+ * this will work. Otherwise we fail loudly to steer devs to WS.
324
+ */
325
+ async list(assetId, params = {}) {
326
+ if (typeof gql.depth !== "function") {
327
+ throw new Error("depth history not available via GraphQL \u2014 use subscription.depth.stream()");
328
+ }
329
+ return gql.depth(assetId, params);
330
+ }
331
+ };
332
+ }
333
+
334
+ // src/info/trades.ts
335
+ function makeTradesInfo(env2) {
336
+ const { gql } = makeInfra(env2);
337
+ return {
338
+ /**
339
+ * If server implements gql.trades(assetId, {since?, limit?}),
340
+ * this will work. Otherwise we fail loudly to steer devs to WS.
341
+ */
342
+ async list(assetId, params = {}) {
343
+ if (typeof gql.trades !== "function") {
344
+ throw new Error("trades history not available via GraphQL \u2014 use subscription.trades.stream()");
345
+ }
346
+ return gql.trades(assetId, params);
347
+ },
348
+ /** Convenience: last trade (or null). */
349
+ async latest(assetId) {
350
+ if (typeof gql.trades !== "function") {
351
+ throw new Error("trades history not available via GraphQL \u2014 use subscription.trades.stream()");
352
+ }
353
+ const rows = await gql.trades(assetId, { limit: 1 });
354
+ return rows.length ? rows[0] : null;
355
+ }
356
+ };
357
+ }
358
+
359
+ // src/info/batches.ts
360
+ function makeBatchesInfo(env2) {
361
+ const { gql } = makeInfra(env2);
362
+ return {
363
+ /** Latest batches for an asset (or across all if your resolver supports assetId = null). */
364
+ list(assetId, limit = 100) {
365
+ return gql.batches(assetId, limit);
366
+ },
367
+ /** Convenience: latest one (or null). */
368
+ async latest(assetId) {
369
+ const rows = await gql.batches(assetId, 1);
370
+ return rows.length ? rows[0] : null;
371
+ }
372
+ };
373
+ }
374
+
375
+ // src/subscription/index.ts
376
+ var subscription_exports = {};
377
+ __export(subscription_exports, {
378
+ makeBatches: () => makeBatches,
379
+ makeCandles: () => makeCandles,
380
+ makeDepth: () => makeDepth,
381
+ makeIndicatives: () => makeIndicatives,
382
+ makeTrades: () => makeTrades
383
+ });
384
+
385
+ // src/subscription/indicatives.ts
386
+ function makeIndicatives(env2, WSImpl) {
387
+ const { gql, ws } = makeInfra(env2, WSImpl);
388
+ return {
389
+ /** Historical/Recent indicatives via GraphQL (sinceSec seconds lookback). */
390
+ list(assetId, sinceSec) {
391
+ return gql.indicatives(assetId, sinceSec);
392
+ },
393
+ /** Live prices via WS. Message has ts, assetId, midPx/bidPx/askPx/spreadBp/src. */
394
+ stream(assetId, handler) {
395
+ return ws.onTopic(Topics.Indicatives, assetId, handler);
396
+ },
397
+ streamMany(assetIds, handler) {
398
+ const bag = new SubBag();
399
+ for (const a of assetIds) {
400
+ bag.add(ws.on(topicKey(Topics.Indicatives, a), (msg) => handler(String(a), msg)));
401
+ }
402
+ return bag;
403
+ }
404
+ };
405
+ }
406
+
407
+ // src/subscription/candles.ts
408
+ function makeCandles(env2, WSImpl) {
409
+ const { gql, ws } = makeInfra(env2, WSImpl);
410
+ return {
411
+ /** Historical candles from GraphQL. */
412
+ list(assetId, window, limit = 300) {
413
+ return gql.candles(assetId, window, limit);
414
+ },
415
+ /**
416
+ * Live candles via WS fanout.
417
+ * Emits raw candle objects exactly as gateway forwards.
418
+ */
419
+ stream(assetId, handler) {
420
+ return ws.onTopic(Topics.Candles, assetId, handler);
421
+ },
422
+ /**
423
+ * Subscribe to multiple assetIds at once; returns a bag you can .clear()
424
+ */
425
+ streamMany(assetIds, handler) {
426
+ const bag = new SubBag();
427
+ for (const a of assetIds) {
428
+ bag.add(ws.on(topicKey(Topics.Candles, a), (msg) => handler(String(a), msg)));
429
+ }
430
+ return bag;
431
+ }
432
+ };
433
+ }
434
+
435
+ // src/subscription/depth.ts
436
+ function makeDepth(env2, WSImpl) {
437
+ const { ws } = makeInfra(env2, WSImpl);
438
+ return {
439
+ /** Live orderbook rows (snapshots + deltas). You aggregate client-side. */
440
+ stream(assetId, handler) {
441
+ return ws.onTopic(Topics.Depth, assetId, handler);
442
+ },
443
+ streamMany(assetIds, handler) {
444
+ const bag = new SubBag();
445
+ for (const a of assetIds) {
446
+ bag.add(ws.on(topicKey(Topics.Depth, a), (msg) => handler(String(a), msg)));
447
+ }
448
+ return bag;
449
+ }
450
+ };
451
+ }
452
+
453
+ // src/subscription/trades.ts
454
+ function makeTrades(env2, WSImpl) {
455
+ const { ws } = makeInfra(env2, WSImpl);
456
+ return {
457
+ stream(assetId, handler) {
458
+ return ws.onTopic(Topics.Trades, assetId, handler);
459
+ },
460
+ streamMany(assetIds, handler) {
461
+ const bag = new SubBag();
462
+ for (const a of assetIds) {
463
+ bag.add(ws.on(topicKey(Topics.Trades, a), (msg) => handler(String(a), msg)));
464
+ }
465
+ return bag;
466
+ }
467
+ };
468
+ }
469
+
470
+ // src/subscription/batches.ts
471
+ function makeBatches(env2, WSImpl) {
472
+ const { gql, ws } = makeInfra(env2, WSImpl);
473
+ return {
474
+ /** Historical batches via GraphQL. */
475
+ list(assetId, limit = 100) {
476
+ return gql.batches(assetId, limit);
477
+ },
478
+ /** Live batches via WS (preview + submitted). */
479
+ stream(assetId, handler) {
480
+ return ws.onTopic(Topics.Batches, assetId, handler);
481
+ },
482
+ streamMany(assetIds, handler) {
483
+ const bag = new SubBag();
484
+ for (const a of assetIds) {
485
+ bag.add(ws.on(topicKey(Topics.Batches, a), (msg) => handler(String(a), msg)));
486
+ }
487
+ return bag;
488
+ }
489
+ };
490
+ }
491
+
492
+ // src/exchange/index.ts
493
+ var exchange_exports = {};
494
+ __export(exchange_exports, {
495
+ batchCancel: () => batchCancel,
496
+ batchModify: () => batchModify,
497
+ batchOrders: () => batchOrders,
498
+ cancel: () => cancel,
499
+ depositERC20: () => depositERC20,
500
+ depositHYPE: () => depositHYPE,
501
+ modify: () => modify,
502
+ submitOrder: () => submitOrder,
503
+ submitOrderAuto: () => submitOrderAuto,
504
+ withdraw: () => withdraw,
505
+ withdrawAuto: () => withdrawAuto
506
+ });
507
+
508
+ // src/lib/utils/redis.ts
509
+ import Redis from "ioredis";
510
+
511
+ // src/env.ts
512
+ import "dotenv/config";
513
+ var env = {
514
+ CHAIN_ID: Number(process.env.CHAIN_ID ?? 0),
515
+ POOL: process.env.POOL,
516
+ RPC_URL: process.env.RPC_URL,
517
+ REDIS_URL: process.env.REDIS_URL,
518
+ REDIS_STREAM_PREFIX: process.env.REDIS_STREAM_PREFIX ?? "n3",
519
+ PRIVATE_KEY: process.env.RELAYER_KEY,
520
+ SEED: process.env.SEED
521
+ };
522
+ for (const [k, v] of Object.entries(env)) {
523
+ if (!v) throw new Error(`Missing env: ${k}`);
524
+ }
525
+
526
+ // src/lib/utils/redis.ts
527
+ var redis = new Redis(env.REDIS_URL, {
528
+ maxRetriesPerRequest: null,
529
+ enableReadyCheck: true,
530
+ lazyConnect: false
531
+ });
532
+ async function publishIntent(intent) {
533
+ const key = `${env.REDIS_STREAM_PREFIX}:intents`;
534
+ const fields = [];
535
+ for (const [k, v] of Object.entries(intent)) {
536
+ fields.push(k, typeof v === "string" ? v : JSON.stringify(v));
537
+ }
538
+ return redis.xadd(key, "*", ...fields);
539
+ }
540
+
541
+ // src/lib/utils/stripForHyperliquid.ts
542
+ function stripForHyperliquid(intent) {
543
+ const { n3: _omit, ...rest } = intent;
544
+ return rest;
545
+ }
546
+
547
+ // src/lib/utils/toUint160Dec.ts
548
+ function toUint160Dec(addr) {
549
+ if (!addr) throw new Error("empty address");
550
+ const hex = addr.toLowerCase();
551
+ if (!hex.startsWith("0x") || hex.length !== 42) throw new Error(`bad address: ${addr}`);
552
+ return BigInt(hex).toString();
553
+ }
554
+
555
+ // src/lib/utils/getDomains.ts
556
+ function getDomains(params) {
557
+ return {
558
+ domainA: toUint160Dec(params.pool),
559
+ domainB: String(params.chainIdDec),
560
+ DOMAIN: String(params.DOMAIN_DEC)
561
+ };
562
+ }
563
+
564
+ // src/lib/utils/orderControl.ts
565
+ function buildDomains(domain) {
566
+ return getDomains({
567
+ pool: domain.pool,
568
+ chainIdDec: domain.chainIdDec,
569
+ DOMAIN_DEC: domain.DOMAIN_DEC
570
+ });
571
+ }
572
+ function hlEnvelope(action, nonce, signature) {
573
+ return stripForHyperliquid({
574
+ action,
575
+ nonce,
576
+ signature: signature ?? void 0,
577
+ n3: {
578
+ settlement: "",
579
+ pools: [],
580
+ hybrid: {
581
+ internalFirst: false,
582
+ internalCap: "0",
583
+ coreCap: "0"
584
+ },
585
+ spendNotes: false,
586
+ rfq: {
587
+ validUntilMs: 0
588
+ },
589
+ core: {
590
+ route: ""
591
+ }
592
+ }
593
+ });
594
+ }
595
+ function makeIdempotencyKey(op, originalKey, nonce) {
596
+ return `${op}:${String(originalKey)}:${nonce}`;
597
+ }
598
+
599
+ // src/exchange/cancel.ts
600
+ async function cancel(params) {
601
+ const { domain, target, signature, ctx, nonce = Date.now() } = params;
602
+ const hlReq = hlEnvelope(
603
+ {
604
+ type: "cancel",
605
+ ...target.orderId != null ? { orderId: target.orderId } : {},
606
+ ...target.clientOid ? { clientOid: target.clientOid } : {},
607
+ ...target.symbol ? { symbol: target.symbol } : {}
608
+ },
609
+ nonce,
610
+ signature
611
+ );
612
+ const domains = buildDomains(domain);
613
+ const originalKey = target.orderId ?? target.clientOid ?? `${target.symbol ?? "?"}:unknown`;
614
+ const payload = {
615
+ type: "control",
616
+ op: "cancel",
617
+ version: 1,
618
+ idempotencyKey: makeIdempotencyKey("cancel", originalKey, nonce),
619
+ // HL envelope for venue-side cancel
620
+ intent: {
621
+ ...hlReq,
622
+ // Minimal N3 block; explicitly tagged to skip proving/batching
623
+ n3: {
624
+ domains,
625
+ control: { skipProver: true, dropFromBatch: true }
626
+ }
627
+ },
628
+ // Hints for consumers (enclave/batcher/prover)
629
+ control: {
630
+ skipProver: true,
631
+ dropFromBatch: true,
632
+ removePendingOps: true,
633
+ target
634
+ },
635
+ // Telemetry
636
+ userAddress: ctx?.userAddress ?? null,
637
+ receivedAtMs: ctx?.nowMs ?? Date.now()
638
+ };
639
+ return publishIntent(payload);
640
+ }
641
+
642
+ // src/exchange/batchCancel.ts
643
+ async function batchCancel(params) {
644
+ const { domain, targets, signature, ctx, nonce = Date.now() } = params;
645
+ if (!targets?.length) throw new Error("batchCancelOrdersIntent: targets required");
646
+ const byOid = targets.filter((t) => t.orderId != null);
647
+ const byCloid = targets.filter((t) => t.clientOid);
648
+ const domains = buildDomains(domain);
649
+ const publishOne = async (kind) => {
650
+ const groupKey = `${kind}:${targets.length}:${nonce}`;
651
+ const hlReq = kind === "oid" ? hlEnvelope(
652
+ {
653
+ type: "cancel",
654
+ cancels: byOid.map((t) => ({ a: void 0, o: Number(t.orderId) }))
655
+ // a (asset) optional on your side
656
+ },
657
+ nonce,
658
+ signature
659
+ ) : hlEnvelope(
660
+ {
661
+ type: "cancelByCloid",
662
+ cancels: byCloid.map((t) => ({ asset: void 0, cloid: t.clientOid }))
663
+ },
664
+ nonce,
665
+ signature
666
+ );
667
+ const payload = {
668
+ type: "control",
669
+ op: "cancelMany",
670
+ version: 1,
671
+ idempotencyKey: makeIdempotencyKey("cancelMany", groupKey, nonce),
672
+ intent: {
673
+ ...hlReq,
674
+ n3: {
675
+ domains,
676
+ control: { skipProver: true, dropFromBatch: true }
677
+ }
678
+ },
679
+ control: {
680
+ skipProver: true,
681
+ dropFromBatch: true,
682
+ removePendingOps: true,
683
+ targets
684
+ },
685
+ userAddress: ctx?.userAddress ?? null,
686
+ receivedAtMs: ctx?.nowMs ?? Date.now()
687
+ };
688
+ return publishIntent(payload);
689
+ };
690
+ const results = [];
691
+ if (byOid.length) results.push(await publishOne("oid"));
692
+ if (byCloid.length) results.push(await publishOne("cloid"));
693
+ return results.length === 1 ? results[0] : results;
694
+ }
695
+
696
+ // src/exchange/batchModify.ts
697
+ async function batchModify(params) {
698
+ const { domain, modifies, signature, ctx, nonce = Date.now() } = params;
699
+ if (!modifies?.length) throw new Error("batchModifyOrdersIntent: modifies required");
700
+ const hlReq = hlEnvelope(
701
+ {
702
+ type: "batchModify",
703
+ modifies: modifies.map(({ target, order }) => ({
704
+ ...target.orderId != null ? { oid: Number(target.orderId) } : {},
705
+ ...target.clientOid ? { cloid: target.clientOid } : {},
706
+ order
707
+ }))
708
+ },
709
+ nonce,
710
+ signature
711
+ );
712
+ const domains = buildDomains(domain);
713
+ const payload = {
714
+ type: "control",
715
+ op: "batchModify",
716
+ version: 1,
717
+ idempotencyKey: makeIdempotencyKey("batchModify", `n=${modifies.length}`, nonce),
718
+ intent: {
719
+ ...hlReq,
720
+ n3: {
721
+ domains,
722
+ control: { skipProver: true, dropFromBatch: true }
723
+ }
724
+ },
725
+ control: {
726
+ skipProver: true,
727
+ dropFromBatch: true,
728
+ modifies
729
+ },
730
+ userAddress: ctx?.userAddress ?? null,
731
+ receivedAtMs: ctx?.nowMs ?? Date.now()
732
+ };
733
+ return publishIntent(payload);
734
+ }
735
+
736
+ // src/lib/utils/withN3Defaults.ts
737
+ function withN3Defaults(n3, ctx = {}) {
738
+ const settlement = n3?.settlement ?? "pool";
739
+ const pools = {
740
+ allowPools: n3?.pools?.allowPools ?? (ctx.defaultPools ?? []),
741
+ denyPools: n3?.pools?.denyPools ?? [],
742
+ attestations: n3?.pools?.attestations ?? []
743
+ };
744
+ const hybrid = {
745
+ internalFirst: n3?.hybrid?.internalFirst ?? true,
746
+ internalCap: n3?.hybrid?.internalCap ?? (ctx.size ?? "0"),
747
+ coreCap: n3?.hybrid?.coreCap ?? (ctx.size ?? "0")
748
+ };
749
+ const spendNotes = n3?.spendNotes ?? [];
750
+ const now = ctx.nowMs ?? Date.now();
751
+ const rfq = {
752
+ validUntilMs: n3?.rfq?.validUntilMs ?? now + 5 * 6e4,
753
+ // default 5 min
754
+ minFill: n3?.rfq?.minFill ?? "0",
755
+ slippageBps: n3?.rfq?.slippageBps ?? 0,
756
+ makerOnlyInternal: n3?.rfq?.makerOnlyInternal ?? false,
757
+ counterpartyAllow: n3?.rfq?.counterpartyAllow ?? [],
758
+ counterpartyDeny: n3?.rfq?.counterpartyDeny ?? []
759
+ };
760
+ const core = {
761
+ route: n3?.core?.route ?? "",
762
+ extData: n3?.core?.extData ?? ""
763
+ };
764
+ const meta = n3?.meta ?? {};
765
+ return { settlement, pools, hybrid, spendNotes, rfq, core, meta };
766
+ }
767
+
768
+ // src/exchange/batchOrder.ts
769
+ async function batchOrders(params) {
770
+ const {
771
+ orders,
772
+ grouping = "na",
773
+ builder,
774
+ n3,
775
+ domain,
776
+ ctx,
777
+ nonce = Date.now(),
778
+ signature
779
+ } = params;
780
+ if (!orders?.length) throw new Error("submitBatchOrdersIntent: orders required");
781
+ const n3Full = withN3Defaults(n3, {
782
+ defaultPools: ctx?.defaultPools,
783
+ nowMs: ctx?.nowMs,
784
+ size: String(orders.reduce((acc, o) => acc + Number(o.s ?? 0), 0))
785
+ });
786
+ const hlRequest = stripForHyperliquid({
787
+ action: {
788
+ type: "order",
789
+ orders,
790
+ grouping,
791
+ ...builder ? { builder } : {}
792
+ },
793
+ nonce,
794
+ signature: signature ?? void 0
795
+ });
796
+ const domains = getDomains({
797
+ pool: domain.pool,
798
+ chainIdDec: domain.chainIdDec,
799
+ DOMAIN_DEC: domain.DOMAIN_DEC
800
+ });
801
+ const payload = {
802
+ type: "order",
803
+ version: 1,
804
+ intent: {
805
+ ...hlRequest,
806
+ n3: {
807
+ settlement: n3Full.settlement,
808
+ pools: n3Full.pools,
809
+ hybrid: n3Full.hybrid,
810
+ spendNotes: n3Full.spendNotes,
811
+ rfq: n3Full.rfq,
812
+ core: n3Full.core,
813
+ meta: n3Full.meta,
814
+ domains
815
+ }
816
+ },
817
+ // Telemetry
818
+ userAddress: ctx?.userAddress ?? null,
819
+ receivedAtMs: ctx?.nowMs ?? Date.now()
820
+ };
821
+ return publishIntent(payload);
822
+ }
823
+
824
+ // src/exchange/modify.ts
825
+ async function modify(params) {
826
+ const { domain, target, order, signature, ctx, nonce = Date.now() } = params;
827
+ const hlReq = hlEnvelope(
828
+ {
829
+ type: "modify",
830
+ ...target.orderId != null ? { oid: Number(target.orderId) } : {},
831
+ ...target.clientOid ? { cloid: target.clientOid } : {},
832
+ order
833
+ },
834
+ nonce,
835
+ signature
836
+ );
837
+ const domains = buildDomains(domain);
838
+ const originalKey = target.orderId ?? target.clientOid ?? "unknown";
839
+ const payload = {
840
+ type: "control",
841
+ op: "modify",
842
+ version: 1,
843
+ idempotencyKey: makeIdempotencyKey("modify", originalKey, nonce),
844
+ intent: {
845
+ ...hlReq,
846
+ n3: {
847
+ domains,
848
+ control: { skipProver: true, dropFromBatch: true }
849
+ }
850
+ },
851
+ control: {
852
+ skipProver: true,
853
+ dropFromBatch: true,
854
+ target,
855
+ order
856
+ },
857
+ userAddress: ctx?.userAddress ?? null,
858
+ receivedAtMs: ctx?.nowMs ?? Date.now()
859
+ };
860
+ return publishIntent(payload);
861
+ }
862
+
863
+ // src/lib/utils/normalizeOrder.ts
864
+ function normalizeOrder(hl, grouping, builder, n3Full, extra) {
865
+ const tif = "limit" in hl.t ? hl.t.limit.tif : null;
866
+ const trigger = "trigger" in hl.t ? hl.t.trigger : void 0;
867
+ const it = {
868
+ assetId: hl.a,
869
+ isBuy: hl.b,
870
+ price: hl.p,
871
+ size: hl.s,
872
+ reduceOnly: hl.r,
873
+ tif,
874
+ trigger,
875
+ cloid: hl.c,
876
+ grouping,
877
+ builder,
878
+ settlement: n3Full.settlement,
879
+ pools: n3Full.pools,
880
+ hybrid: n3Full.hybrid,
881
+ spendNotes: n3Full.spendNotes,
882
+ rfq: n3Full.rfq,
883
+ core: n3Full.core,
884
+ internalRemaining: n3Full.hybrid.internalFirst ? n3Full.hybrid.internalCap : "0",
885
+ coreRemaining: n3Full.hybrid.coreCap,
886
+ userAddress: extra.userAddress,
887
+ receivedAtMs: extra.receivedAtMs ?? Date.now()
888
+ };
889
+ return it;
890
+ }
891
+
892
+ // src/lib/utils/notesSelect.ts
893
+ function greedySelectNotes(store, params) {
894
+ const assetIdBI = BigInt(params.assetId);
895
+ const need = params.amount;
896
+ const spendables = store.listSpendable({ assetId: assetIdBI }).filter((n) => n.index != null && !!n.commitment);
897
+ const sorted = spendables.slice().sort((a, b) => b.amount > a.amount ? 1 : b.amount < a.amount ? -1 : 0);
898
+ const out = [];
899
+ let acc = 0n;
900
+ for (const n of sorted) {
901
+ out.push(n);
902
+ acc += n.amount;
903
+ if (acc >= need) break;
904
+ }
905
+ return { notes: out, totalSelected: acc, shortfall: acc >= need ? 0n : need - acc };
906
+ }
907
+ function buildSpendNotesFromStore(store, params) {
908
+ const sel = greedySelectNotes(store, params);
909
+ const spendNotes = sel.notes.map((n) => ({
910
+ commitment: n.commitment,
911
+ leafIndex: n.index,
912
+ // anchored by filter above
913
+ assetId: Number(n.assetId),
914
+ maxSpend: n.amount.toString()
915
+ // spend full note; change handled downstream
916
+ }));
917
+ return { spendNotes, totalSelected: sel.totalSelected, shortfall: sel.shortfall };
918
+ }
919
+
920
+ // src/exchange/order.ts
921
+ function toInternalTransferPlan(pl) {
922
+ const internalTarget = pl.settlement === "pool" ? pl.size : pl.settlement === "hybrid" ? pl.internalRemaining : "0";
923
+ return {
924
+ assetId: pl.assetId,
925
+ internalTarget,
926
+ spendNotes: pl.spendNotes ?? [],
927
+ rfq: pl.rfq
928
+ };
929
+ }
930
+ async function submitOrder(params) {
931
+ const {
932
+ hl,
933
+ grouping,
934
+ builder,
935
+ n3,
936
+ ctx,
937
+ domain,
938
+ nonce = Date.now(),
939
+ signature
940
+ } = params;
941
+ const n3Full = withN3Defaults(n3, {
942
+ defaultPools: ctx?.defaultPools,
943
+ nowMs: ctx?.nowMs,
944
+ size: hl.s
945
+ });
946
+ const plannable = normalizeOrder(
947
+ hl,
948
+ grouping,
949
+ builder,
950
+ n3Full,
951
+ { receivedAtMs: ctx?.nowMs ?? Date.now(), userAddress: ctx?.userAddress }
952
+ );
953
+ const hlRequest = stripForHyperliquid({
954
+ action: {
955
+ type: "order",
956
+ orders: [hl],
957
+ grouping,
958
+ ...builder ? { builder } : {}
959
+ },
960
+ nonce,
961
+ signature: signature ?? void 0
962
+ });
963
+ const domains = getDomains({
964
+ pool: domain.pool,
965
+ chainIdDec: domain.chainIdDec,
966
+ DOMAIN_DEC: domain.DOMAIN_DEC
967
+ });
968
+ const intent = {
969
+ ...hlRequest,
970
+ n3: {
971
+ settlement: n3Full.settlement,
972
+ pools: n3Full.pools,
973
+ hybrid: n3Full.hybrid,
974
+ spendNotes: n3Full.spendNotes,
975
+ rfq: n3Full.rfq,
976
+ core: n3Full.core,
977
+ meta: n3Full.meta,
978
+ domains
979
+ }
980
+ };
981
+ const internalPlan = toInternalTransferPlan(plannable);
982
+ const payload = {
983
+ type: "order",
984
+ version: 1,
985
+ intent,
986
+ plannable,
987
+ internalPlan,
988
+ userAddress: plannable.userAddress ?? null,
989
+ receivedAtMs: plannable.receivedAtMs
990
+ };
991
+ return publishIntent(payload);
992
+ }
993
+ async function submitOrderAuto(params) {
994
+ const { store, spend, allowPartial, ...rest } = params;
995
+ const { spendNotes, totalSelected, shortfall } = buildSpendNotesFromStore(store, spend);
996
+ if (shortfall > 0n && !allowPartial) {
997
+ throw new Error(
998
+ `Insufficient spendable balance for asset ${spend.assetId}. Need ${spend.amount}, have ${totalSelected}.`
999
+ );
1000
+ }
1001
+ const n3 = {
1002
+ ...rest.n3,
1003
+ spendNotes: [
1004
+ ...rest.n3?.spendNotes ?? [],
1005
+ ...spendNotes
1006
+ ]
1007
+ };
1008
+ return submitOrder({
1009
+ ...rest,
1010
+ n3
1011
+ });
1012
+ }
1013
+
1014
+ // src/exchange/withdraw3.ts
1015
+ import "dotenv/config";
1016
+
1017
+ // src/lib/consts/domain.ts
1018
+ var POOL = process.env.POOL ?? "0x829f9d77F37BDB3e6519cddc99357f055cb92f97";
1019
+ var CHAIN_ID_DEC = 999;
1020
+ var DOMAIN_DEC = 42;
1021
+ function getDomainEnv(overrides) {
1022
+ const chainIdEnv = Number(process.env.CHAIN_ID ?? 42161);
1023
+ const domainEnv = Number(process.env.DOMAIN_DEC ?? 1);
1024
+ const poolEnv = process.env.POOL ?? "0x0000000000000000000000000000000000000000";
1025
+ return {
1026
+ chainIdDec: overrides?.chainIdDec ?? chainIdEnv,
1027
+ domainDec: overrides?.domainDec ?? domainEnv,
1028
+ pool: overrides?.pool ?? poolEnv
1029
+ };
1030
+ }
1031
+
1032
+ // src/lib/utils/pureSigner.ts
1033
+ import { buildBabyjub, buildEddsa, buildPoseidonReference } from "circomlibjs";
1034
+ globalThis.ffjsconfig = { wasm: "disable" };
1035
+ process.env.FFJS_FORCE_NO_WASM = "1";
1036
+ process.env.FFJSCONFIG = '{"wasm":"disable"}';
1037
+ var babyJub = await buildBabyjub();
1038
+ var eddsa = await buildEddsa();
1039
+ var poseidonRef = await buildPoseidonReference();
1040
+ var Fr = babyJub.F;
1041
+ function toBI(x) {
1042
+ return typeof x === "bigint" ? x : BigInt(x);
1043
+ }
1044
+ function be32FromDec(dec) {
1045
+ let x = toBI(dec);
1046
+ const out = new Uint8Array(32);
1047
+ for (let i = 31; i >= 0; i--) {
1048
+ out[i] = Number(x & 0xffn);
1049
+ x >>= 8n;
1050
+ }
1051
+ return out;
1052
+ }
1053
+ function hexToBytes(hex) {
1054
+ const h = hex.startsWith("0x") ? hex.slice(2) : hex;
1055
+ const s = h.padStart(64, "0");
1056
+ return Uint8Array.from(Buffer.from(s, "hex"));
1057
+ }
1058
+ function H2(a, b) {
1059
+ return Fr.toObject(poseidonRef([Fr.e(a), Fr.e(b)]));
1060
+ }
1061
+ function msgHash(domain, chainDec, poolDec, c_in, oldRoot) {
1062
+ return Fr.toObject(
1063
+ poseidonRef([
1064
+ Fr.e(domain),
1065
+ Fr.e(chainDec),
1066
+ Fr.e(poolDec),
1067
+ Fr.e(c_in),
1068
+ Fr.e(oldRoot)
1069
+ ])
1070
+ );
1071
+ }
1072
+ function poseidonAxAy(Ax, Ay) {
1073
+ return Fr.toObject(
1074
+ poseidonRef([Fr.e(toBI(Ax)), Fr.e(toBI(Ay))])
1075
+ );
1076
+ }
1077
+ function signPoseidonCompat(prvSeed, M, Ax_from_note, Ay_from_note) {
1078
+ const raw = prvSeed.startsWith("0x") ? hexToBytes(prvSeed) : be32FromDec(prvSeed);
1079
+ if (raw.length !== 32) {
1080
+ throw new Error(`signPoseidonCompat: prvSeed must be 32 bytes, got ${raw.length}`);
1081
+ }
1082
+ const prv = Buffer.from(raw);
1083
+ if (Ax_from_note && Ay_from_note) {
1084
+ const A = eddsa.prv2pub(prv);
1085
+ const Ax = Fr.toObject(A[0]);
1086
+ const Ay = Fr.toObject(A[1]);
1087
+ if (Ax.toString() !== Ax_from_note || Ay.toString() !== Ay_from_note) {
1088
+ console.warn("[warn] prv->pub mismatch", {
1089
+ derivedAx: Ax.toString(),
1090
+ derivedAy: Ay.toString(),
1091
+ noteAx: Ax_from_note,
1092
+ noteAy: Ay_from_note
1093
+ });
1094
+ }
1095
+ }
1096
+ const Mfield = Fr.e(M);
1097
+ const sig = eddsa.signPoseidon(prv, Mfield);
1098
+ const R8x = Fr.toObject(sig.R8[0]);
1099
+ const R8y = Fr.toObject(sig.R8[1]);
1100
+ const S = toBI(sig.S);
1101
+ return { R8x: R8x.toString(), R8y: R8y.toString(), S: S.toString() };
1102
+ }
1103
+ function verifyPoseidonCompat(Ax, Ay, M, sig) {
1104
+ const A = [babyJub.F.e(toBI(Ax)), babyJub.F.e(toBI(Ay))];
1105
+ const R8 = [babyJub.F.e(toBI(sig.R8x)), babyJub.F.e(toBI(sig.R8y))];
1106
+ const S = toBI(sig.S);
1107
+ return eddsa.verifyPoseidon(M, { R8, S }, A);
1108
+ }
1109
+
1110
+ // src/lib/utils/poseidon.ts
1111
+ import { buildBabyjub as buildBabyjub2, buildPoseidon, buildEddsa as buildEddsa2 } from "circomlibjs";
1112
+ var _h2 = null;
1113
+ var FR = 21888242871839275222246405745257275088548364400416034343698204186575808495617n;
1114
+ async function babyjubCtx() {
1115
+ const babyjub = await buildBabyjub2();
1116
+ const poseidon = await buildPoseidon();
1117
+ const eddsa3 = await buildEddsa2();
1118
+ const F = babyjub.F;
1119
+ return { babyjub, poseidon, eddsa: eddsa3, F };
1120
+ }
1121
+ function toField(x) {
1122
+ let v = x % FR;
1123
+ if (v < 0n) v += FR;
1124
+ return v;
1125
+ }
1126
+ function hexTo32Bytes(hex) {
1127
+ const s = (hex.startsWith("0x") ? hex.slice(2) : hex).padStart(64, "0");
1128
+ const bytes = new Uint8Array(s.length / 2);
1129
+ for (let i = 0; i < bytes.length; i++) bytes[i] = parseInt(s.slice(2 * i, 2 * i + 2), 16);
1130
+ return bytes;
1131
+ }
1132
+ async function genNote(seed) {
1133
+ const { eddsa: eddsa3, poseidon, F } = await babyjubCtx();
1134
+ const rnd = seed ?? BigInt.asUintN(
1135
+ 256,
1136
+ BigInt(Date.now()) * 0x100000000n + BigInt(Math.floor(Math.random() * 1e9))
1137
+ );
1138
+ const sk = toField(rnd);
1139
+ const blinding = toField(sk ^ 0xB1E55n);
1140
+ const skHex = "0x" + sk.toString(16).padStart(64, "0");
1141
+ const skBytes = hexTo32Bytes(skHex);
1142
+ const pub = eddsa3.prv2pub(skBytes);
1143
+ const Ax = F.toObject(pub[0]);
1144
+ const Ay = F.toObject(pub[1]);
1145
+ const pubkey = F.toObject(poseidon([Ax, Ay]));
1146
+ return { sk, skBytes, Ax, Ay, pubkey, blinding };
1147
+ }
1148
+ function makeDepositCommitments(assetId, amount, pubkey, blinding) {
1149
+ if (!_h2) throw new Error("initPoseidon() must be called before makeDepositCommitments");
1150
+ const poseidon = _h2;
1151
+ const hAmt = poseidon(assetId, amount);
1152
+ const hPK = poseidon(pubkey, blinding);
1153
+ const commitment = poseidon(hAmt, hPK);
1154
+ const hItem = poseidon(commitment, hAmt);
1155
+ return { hAmt, commitment, hItem };
1156
+ }
1157
+ async function initPoseidon() {
1158
+ if (_h2) return;
1159
+ const poseidon = await buildPoseidon();
1160
+ const F = poseidon.F;
1161
+ _h2 = (a, b) => F.toObject(poseidon([a, b]));
1162
+ }
1163
+ function getH2() {
1164
+ if (!_h2) throw new Error("initPoseidon() must be called before using h2");
1165
+ return _h2;
1166
+ }
1167
+
1168
+ // src/lib/utils/computeNullifier.ts
1169
+ async function computeNullifierExact(params) {
1170
+ await initPoseidon();
1171
+ const H22 = getH2();
1172
+ const inner = H22(params.commit, params.index);
1173
+ const nf = H22(params.sk, inner);
1174
+ return nf;
1175
+ }
1176
+
1177
+ // src/exchange/withdraw3.ts
1178
+ import { buildBabyjub as buildBabyjub3, buildEddsa as buildEddsa3 } from "circomlibjs";
1179
+ import crypto2 from "crypto";
1180
+
1181
+ // src/lib/utils/fetchPinFromIndexer.ts
1182
+ async function fetchPinFromIndexer(indexerUrl, poolAddr) {
1183
+ const q = `
1184
+ query Head($pool: String!) {
1185
+ poolStates(where: { id: $pool }, limit: 1) {
1186
+ items { currentRoot depAppliedHash depAppliedLen nextIndex updatedAt }
1187
+ }
1188
+ }`;
1189
+ const r = await fetch(indexerUrl, {
1190
+ method: "POST",
1191
+ headers: { "content-type": "application/json" },
1192
+ body: JSON.stringify({ query: q, variables: { pool: poolAddr.toLowerCase() } })
1193
+ });
1194
+ const j = await r.json();
1195
+ const head = j?.data?.poolStates?.items?.[0];
1196
+ if (!head) throw new Error("indexer head not found for pool");
1197
+ return {
1198
+ depEnqHash: String(head.depAppliedHash),
1199
+ depEnqLen: Number(head.depAppliedLen),
1200
+ nextIndex: Number(head.nextIndex),
1201
+ currentRoot: head.currentRoot,
1202
+ updatedAt: Number(head.updatedAt)
1203
+ };
1204
+ }
1205
+
1206
+ // src/exchange/withdraw3.ts
1207
+ var INDEXER_URL = process.env.INDEXER_URL;
1208
+ var PROOF_URL = process.env.PROOF_URL || (INDEXER_URL.endsWith("/graphql") ? INDEXER_URL.replace(/\/graphql$/, "/proof") : `${INDEXER_URL.replace(/\/+$/, "")}/proof`);
1209
+ var TREE_DEPTH = Number(process.env.TREE_DEPTH || 20);
1210
+ var eddsa2 = await buildEddsa3();
1211
+ var babyJub2 = await buildBabyjub3();
1212
+ var Fr2 = babyJub2.F;
1213
+ function asBytes(x) {
1214
+ if (x instanceof Uint8Array) return x;
1215
+ const a = x;
1216
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer?.(x)) return new Uint8Array(a);
1217
+ if (Array.isArray(a)) return new Uint8Array(a.map((n) => Number(n) & 255));
1218
+ if (a && typeof a === "object") {
1219
+ const keys = Object.keys(a).filter((k) => /^\d+$/.test(k)).map(Number).sort((x2, y) => x2 - y);
1220
+ if (keys.length) {
1221
+ const out = new Uint8Array(keys.length);
1222
+ for (let i = 0; i < keys.length; i++) out[i] = Number(a[keys[i]] ?? 0) & 255;
1223
+ return out;
1224
+ }
1225
+ }
1226
+ return null;
1227
+ }
1228
+ var bi = (x) => BigInt(x ?? 0);
1229
+ var toSeedHex = (u82) => "0x" + Buffer.from(u82).toString("hex");
1230
+ var noteCommit = (assetId, amount, pubkey, blinding) => H2(H2(assetId, amount), H2(pubkey, blinding));
1231
+ async function fetchProof(index, rootHex) {
1232
+ const url = `${PROOF_URL.replace(/\/+$/, "")}?index=${index}&root=${encodeURIComponent(rootHex)}`;
1233
+ const ctl = new AbortController();
1234
+ const to = setTimeout(() => ctl.abort(), 12e3);
1235
+ try {
1236
+ const r = await fetch(url, { method: "GET", signal: ctl.signal });
1237
+ const j = await r.json().catch(() => null);
1238
+ if (!r.ok) throw new Error(`proof server ${r.status}: ${j?.error ?? r.statusText}`);
1239
+ const pathElements = (j?.pathElements ?? []).map((x) => {
1240
+ const s = String(x);
1241
+ return s.startsWith("0x") ? s : "0x" + BigInt(s).toString(16).padStart(64, "0");
1242
+ });
1243
+ const pathIndex = (j?.pathIndex ?? []).map((x) => Number(x));
1244
+ if (pathElements.length !== TREE_DEPTH || pathIndex.length !== TREE_DEPTH) {
1245
+ throw new Error(`proof length mismatch: got ${pathElements.length}/${pathIndex.length}, expected ${TREE_DEPTH}`);
1246
+ }
1247
+ return { pathElements, pathIndex };
1248
+ } finally {
1249
+ clearTimeout(to);
1250
+ }
1251
+ }
1252
+ async function withdraw({
1253
+ assetId,
1254
+ amount,
1255
+ toAddress,
1256
+ spends,
1257
+ out0,
1258
+ out1,
1259
+ fee = 0n,
1260
+ relayer = 0n
1261
+ }) {
1262
+ const spendsArr = (spends ?? []).map((s) => {
1263
+ const base = {
1264
+ notePubkey: s.notePubkey.toString(),
1265
+ Ax: s.Ax.toString(),
1266
+ Ay: s.Ay.toString(),
1267
+ R8x: s.R8x.toString(),
1268
+ R8y: s.R8y.toString(),
1269
+ S: s.S.toString(),
1270
+ commit: s.commit.toString(),
1271
+ index: s.index.toString(),
1272
+ assetId: s.assetId.toString(),
1273
+ amount: s.amount.toString(),
1274
+ blinding: s.blinding.toString(),
1275
+ sk: s.sk.toString()
1276
+ };
1277
+ if (s.pathElements) base.pathElements = s.pathElements.map((x) => x.toString());
1278
+ if (s.pathIndex) base.pathIndex = s.pathIndex.map((x) => x.toString());
1279
+ return base;
1280
+ });
1281
+ const wd_outAssetIds = [out0?.assetId ?? assetId, out1?.assetId ?? assetId].map(String);
1282
+ const wd_outAmounts = [out0?.amount ?? 0n, out1?.amount ?? 0n].map(String);
1283
+ const wd_outPubkeys = [out0?.pubkey ?? 0n, out1?.pubkey ?? 0n].map(String);
1284
+ const wd_outBlindings = [out0?.blinding ?? 0n, out1?.blinding ?? 0n].map(String);
1285
+ const it = {
1286
+ domain: {
1287
+ pool: POOL.toLowerCase(),
1288
+ chainIdDec: String(CHAIN_ID_DEC),
1289
+ DOMAIN_DEC: String(DOMAIN_DEC)
1290
+ },
1291
+ withdraws: [{
1292
+ select: "1",
1293
+ selected: "1",
1294
+ assetId: assetId.toString(),
1295
+ amount: amount.toString(),
1296
+ // external payout
1297
+ to: toAddress,
1298
+ spends: spendsArr,
1299
+ // NEW: explicit WD outputs & accounting
1300
+ outAssetIds: wd_outAssetIds,
1301
+ outAmounts: wd_outAmounts,
1302
+ outPubkeys: wd_outPubkeys,
1303
+ outBlindings: wd_outBlindings,
1304
+ fee: String(fee ?? 0n),
1305
+ relayer: String(relayer ?? 0n)
1306
+ }]
1307
+ };
1308
+ return publishIntent({
1309
+ type: "withdraw",
1310
+ assetId: assetId.toString(),
1311
+ amount: amount.toString(),
1312
+ toAddress,
1313
+ it,
1314
+ ...it.domain,
1315
+ withdraws: it.withdraws
1316
+ });
1317
+ }
1318
+ function randU256() {
1319
+ const b = crypto2.randomBytes(32);
1320
+ return BigInt("0x" + Buffer.from(b).toString("hex"));
1321
+ }
1322
+ async function withdrawAuto({
1323
+ store,
1324
+ assetId,
1325
+ amount,
1326
+ toAddress,
1327
+ allowPartial = false
1328
+ }) {
1329
+ const assetIdBI = BigInt(assetId);
1330
+ const spendable = store.listSpendable().filter((n) => String(n.assetId) === String(assetIdBI));
1331
+ const signable = spendable.filter((n) => {
1332
+ try {
1333
+ const skU8 = asBytes(n.secret?.sk);
1334
+ if (!skU8 || skU8.length !== 32) return false;
1335
+ const A = eddsa2.prv2pub(Buffer.from(skU8));
1336
+ const Ax = Fr2.toObject(A[0]).toString();
1337
+ const Ay = Fr2.toObject(A[1]).toString();
1338
+ return Ax === String(n.ownerPub.x) && Ay === String(n.ownerPub.y);
1339
+ } catch {
1340
+ return false;
1341
+ }
1342
+ });
1343
+ if (!allowPartial) {
1344
+ const total = signable.reduce((a, n) => a + BigInt(n.amount), 0n);
1345
+ if (total < amount) throw new Error(`insufficient signable for asset=${assetIdBI} have=${total} need=${amount}`);
1346
+ }
1347
+ const picked = [];
1348
+ for (let sum = 0n, i = 0; i < signable.length && sum < amount; i++) {
1349
+ picked.push(signable[i]);
1350
+ sum += BigInt(signable[i].amount);
1351
+ }
1352
+ if (picked.length > 1 && BigInt(picked[0].amount) >= amount) picked.splice(1);
1353
+ await initPoseidon();
1354
+ const pin = await fetchPinFromIndexer(INDEXER_URL, POOL);
1355
+ const pinnedRootHex = pin.currentRoot;
1356
+ console.log("[sdk] pinnedRootHex", pinnedRootHex);
1357
+ const oldRoot = BigInt(pinnedRootHex);
1358
+ const poolUint160 = BigInt(toUint160Dec(POOL));
1359
+ const chainDec = BigInt(CHAIN_ID_DEC);
1360
+ const domain = BigInt(DOMAIN_DEC);
1361
+ const spends = await Promise.all(picked.map(async (note) => {
1362
+ if (note.index == null) throw new Error(`note ${note.commitment} missing index`);
1363
+ const pubHash = poseidonAxAy(note.ownerPub.x.toString(), note.ownerPub.y.toString());
1364
+ const commitBI = BigInt(note.commitment);
1365
+ const skU8 = asBytes(note.secret?.sk);
1366
+ if (!skU8 || skU8.length !== 32) throw new Error(`note ${note.commitment}: invalid sk`);
1367
+ const prvSeedHex = toSeedHex(skU8);
1368
+ const blU8 = asBytes(note.secret?.blind);
1369
+ if (!blU8) throw new Error(`note ${note.commitment}: missing blinding`);
1370
+ const blBI = BigInt("0x" + Buffer.from(blU8).toString("hex"));
1371
+ const pkBI = bi(pubHash.toString());
1372
+ const commitLocal = noteCommit(bi(note.assetId), bi(note.amount), pkBI, blBI);
1373
+ if (commitLocal !== commitBI) throw new Error(`commit rebuild mismatch ${note.commitment}`);
1374
+ const M = msgHash(domain, chainDec, poolUint160, commitBI, oldRoot);
1375
+ const sig = signPoseidonCompat(prvSeedHex, M, note.ownerPub.x.toString(), note.ownerPub.y.toString());
1376
+ if (!verifyPoseidonCompat(note.ownerPub.x.toString(), note.ownerPub.y.toString(), M, sig)) {
1377
+ throw new Error(`signature verify failed ${note.commitment}`);
1378
+ }
1379
+ const { pathElements, pathIndex } = await fetchProof(Number(note.index), pinnedRootHex);
1380
+ let acc = commitLocal;
1381
+ for (let d = 0; d < TREE_DEPTH; d++) {
1382
+ const sib = bi(pathElements[d]), bit = bi(pathIndex[d]);
1383
+ acc = bit === 0n ? H2(acc, sib) : H2(sib, acc);
1384
+ }
1385
+ if (acc !== oldRoot) {
1386
+ throw new Error(`walk != pinned root (idx=${note.index}) old=${pinnedRootHex} got=0x${acc.toString(16)}`);
1387
+ }
1388
+ return {
1389
+ notePubkey: BigInt(pubHash.toString()),
1390
+ Ax: note.ownerPub.x,
1391
+ Ay: note.ownerPub.y,
1392
+ R8x: BigInt(sig.R8x),
1393
+ R8y: BigInt(sig.R8y),
1394
+ S: BigInt(sig.S),
1395
+ commit: commitBI,
1396
+ index: BigInt(note.index),
1397
+ assetId: BigInt(note.assetId),
1398
+ amount: BigInt(note.amount),
1399
+ blinding: blBI,
1400
+ sk: BigInt("0x" + Buffer.from(skU8).toString("hex")),
1401
+ pathElements,
1402
+ pathIndex
1403
+ };
1404
+ }));
1405
+ const primary = picked[0];
1406
+ const pkHash = poseidonAxAy(primary.ownerPub.x.toString(), primary.ownerPub.y.toString());
1407
+ const inAmt = BigInt(primary.amount);
1408
+ const fee = 0n;
1409
+ const changeAmt = inAmt - amount - fee;
1410
+ if (changeAmt < 0n) throw new Error(`withdraw > note amount (have ${inAmt}, need ${amount}+${fee})`);
1411
+ const out0 = {
1412
+ // change
1413
+ assetId: BigInt(primary.assetId),
1414
+ amount: changeAmt,
1415
+ pubkey: BigInt(pkHash.toString()),
1416
+ blinding: randU256()
1417
+ };
1418
+ const out1 = {
1419
+ // dummy
1420
+ assetId: BigInt(primary.assetId),
1421
+ amount: 0n,
1422
+ pubkey: BigInt(pkHash.toString()),
1423
+ blinding: randU256()
1424
+ };
1425
+ for (const s of spends) {
1426
+ try {
1427
+ const nf = await computeNullifierExact({ commit: s.commit, index: s.index, sk: s.sk });
1428
+ await store.markPending("0x" + nf.toString(16).padStart(64, "0"));
1429
+ } catch {
1430
+ }
1431
+ }
1432
+ return withdraw({
1433
+ assetId: assetIdBI,
1434
+ amount,
1435
+ // becomes wd_extAmount at prover
1436
+ toAddress,
1437
+ spends,
1438
+ out0,
1439
+ out1,
1440
+ fee,
1441
+ relayer: 0n
1442
+ });
1443
+ }
1444
+
1445
+ // src/exchange/depositERC20.ts
1446
+ import { erc20Abi } from "viem";
1447
+
1448
+ // src/lib/consts/poolAbi.ts
1449
+ import { getAbiItem } from "viem";
1450
+ var PrivatePoolAbi = [{ "type": "constructor", "inputs": [{ "name": "batch", "type": "address", "internalType": "contract IVerifier" }, { "name": "domainDec", "type": "uint256", "internalType": "uint256" }], "stateMutability": "nonpayable" }, { "type": "receive", "stateMutability": "payable" }, { "type": "function", "name": "BATCH_ACTIONS_VERIFIER", "inputs": [], "outputs": [{ "name": "", "type": "address", "internalType": "contract IVerifier" }], "stateMutability": "view" }, { "type": "function", "name": "BATCH_MINT", "inputs": [], "outputs": [{ "name": "", "type": "uint32", "internalType": "uint32" }], "stateMutability": "view" }, { "type": "function", "name": "DOMAIN", "inputs": [], "outputs": [{ "name": "", "type": "uint256", "internalType": "uint256" }], "stateMutability": "view" }, { "type": "function", "name": "FR", "inputs": [], "outputs": [{ "name": "", "type": "uint256", "internalType": "uint256" }], "stateMutability": "view" }, { "type": "function", "name": "HYPE_ASSET_ID", "inputs": [], "outputs": [{ "name": "", "type": "uint256", "internalType": "uint256" }], "stateMutability": "view" }, { "type": "function", "name": "LEVELS", "inputs": [], "outputs": [{ "name": "", "type": "uint32", "internalType": "uint32" }], "stateMutability": "view" }, { "type": "function", "name": "MAXL", "inputs": [], "outputs": [{ "name": "", "type": "uint32", "internalType": "uint32" }], "stateMutability": "view" }, { "type": "function", "name": "MAX_NF", "inputs": [], "outputs": [{ "name": "", "type": "uint32", "internalType": "uint32" }], "stateMutability": "view" }, { "type": "function", "name": "MAX_OPS", "inputs": [], "outputs": [{ "name": "", "type": "uint32", "internalType": "uint32" }], "stateMutability": "view" }, { "type": "function", "name": "N_CO", "inputs": [], "outputs": [{ "name": "", "type": "uint32", "internalType": "uint32" }], "stateMutability": "view" }, { "type": "function", "name": "N_IT", "inputs": [], "outputs": [{ "name": "", "type": "uint32", "internalType": "uint32" }], "stateMutability": "view" }, { "type": "function", "name": "N_WD", "inputs": [], "outputs": [{ "name": "", "type": "uint32", "internalType": "uint32" }], "stateMutability": "view" }, { "type": "function", "name": "ROOT_HISTORY", "inputs": [], "outputs": [{ "name": "", "type": "uint32", "internalType": "uint32" }], "stateMutability": "view" }, { "type": "function", "name": "TAIL_RING", "inputs": [], "outputs": [{ "name": "", "type": "uint32", "internalType": "uint32" }], "stateMutability": "view" }, { "type": "function", "name": "applyBatchActions", "inputs": [{ "name": "a", "type": "uint256[2]", "internalType": "uint256[2]" }, { "name": "b", "type": "uint256[2][2]", "internalType": "uint256[2][2]" }, { "name": "c", "type": "uint256[2]", "internalType": "uint256[2]" }, { "name": "pub", "type": "uint256[10]", "internalType": "uint256[10]" }, { "name": "ops", "type": "tuple[]", "internalType": "struct PrivatePoolV3.ExtOp[]", "components": [{ "name": "kind", "type": "uint8", "internalType": "uint8" }, { "name": "assetId", "type": "uint256", "internalType": "uint256" }, { "name": "to", "type": "address", "internalType": "address" }, { "name": "amount", "type": "uint256", "internalType": "uint256" }] }, { "name": "nfs", "type": "bytes32[]", "internalType": "bytes32[]" }, { "name": "leaves", "type": "uint256[]", "internalType": "uint256[]" }], "outputs": [], "stateMutability": "nonpayable" }, { "type": "function", "name": "cancelOwnershipHandover", "inputs": [], "outputs": [], "stateMutability": "payable" }, { "type": "function", "name": "completeOwnershipHandover", "inputs": [{ "name": "pendingOwner", "type": "address", "internalType": "address" }], "outputs": [], "stateMutability": "payable" }, { "type": "function", "name": "currentRoot", "inputs": [], "outputs": [{ "name": "", "type": "uint256", "internalType": "uint256" }], "stateMutability": "view" }, { "type": "function", "name": "depAppliedHash", "inputs": [], "outputs": [{ "name": "", "type": "uint256", "internalType": "uint256" }], "stateMutability": "view" }, { "type": "function", "name": "depAppliedLen", "inputs": [], "outputs": [{ "name": "", "type": "uint64", "internalType": "uint64" }], "stateMutability": "view" }, { "type": "function", "name": "depEnqHash", "inputs": [], "outputs": [{ "name": "", "type": "uint256", "internalType": "uint256" }], "stateMutability": "view" }, { "type": "function", "name": "depEnqLen", "inputs": [], "outputs": [{ "name": "", "type": "uint64", "internalType": "uint64" }], "stateMutability": "view" }, { "type": "function", "name": "depositERC20", "inputs": [{ "name": "assetId", "type": "uint256", "internalType": "uint256" }, { "name": "amount", "type": "uint256", "internalType": "uint256" }, { "name": "commitment", "type": "uint256", "internalType": "uint256" }, { "name": "token", "type": "address", "internalType": "address" }, { "name": "sys", "type": "address", "internalType": "address" }], "outputs": [], "stateMutability": "nonpayable" }, { "type": "function", "name": "depositHYPE", "inputs": [{ "name": "commitment", "type": "uint256", "internalType": "uint256" }], "outputs": [], "stateMutability": "payable" }, { "type": "function", "name": "frontier", "inputs": [{ "name": "", "type": "uint256", "internalType": "uint256" }], "outputs": [{ "name": "", "type": "uint256", "internalType": "uint256" }], "stateMutability": "view" }, { "type": "function", "name": "initZeros", "inputs": [{ "name": "z", "type": "uint256[]", "internalType": "uint256[]" }], "outputs": [], "stateMutability": "nonpayable" }, { "type": "function", "name": "isKnownRoot", "inputs": [{ "name": "r", "type": "uint256", "internalType": "uint256" }], "outputs": [{ "name": "", "type": "bool", "internalType": "bool" }], "stateMutability": "view" }, { "type": "function", "name": "nextIndex", "inputs": [], "outputs": [{ "name": "", "type": "uint32", "internalType": "uint32" }], "stateMutability": "view" }, { "type": "function", "name": "owner", "inputs": [], "outputs": [{ "name": "result", "type": "address", "internalType": "address" }], "stateMutability": "view" }, { "type": "function", "name": "ownershipHandoverExpiresAt", "inputs": [{ "name": "pendingOwner", "type": "address", "internalType": "address" }], "outputs": [{ "name": "result", "type": "uint256", "internalType": "uint256" }], "stateMutability": "view" }, { "type": "function", "name": "poolBalance", "inputs": [{ "name": "", "type": "uint256", "internalType": "uint256" }], "outputs": [{ "name": "", "type": "uint256", "internalType": "uint256" }], "stateMutability": "view" }, { "type": "function", "name": "renounceOwnership", "inputs": [], "outputs": [], "stateMutability": "payable" }, { "type": "function", "name": "requestOwnershipHandover", "inputs": [], "outputs": [], "stateMutability": "payable" }, { "type": "function", "name": "rootIndex", "inputs": [], "outputs": [{ "name": "", "type": "uint32", "internalType": "uint32" }], "stateMutability": "view" }, { "type": "function", "name": "roots", "inputs": [{ "name": "", "type": "uint256", "internalType": "uint256" }], "outputs": [{ "name": "", "type": "uint256", "internalType": "uint256" }], "stateMutability": "view" }, { "type": "function", "name": "tailWindow", "inputs": [], "outputs": [{ "name": "hashes", "type": "uint256[]", "internalType": "uint256[]" }, { "name": "lens", "type": "uint64[]", "internalType": "uint64[]" }], "stateMutability": "view" }, { "type": "function", "name": "transferOwnership", "inputs": [{ "name": "newOwner", "type": "address", "internalType": "address" }], "outputs": [], "stateMutability": "payable" }, { "type": "function", "name": "zeros", "inputs": [{ "name": "", "type": "uint256", "internalType": "uint256" }], "outputs": [{ "name": "", "type": "uint256", "internalType": "uint256" }], "stateMutability": "view" }, { "type": "function", "name": "zerosInit", "inputs": [], "outputs": [{ "name": "", "type": "bool", "internalType": "bool" }], "stateMutability": "view" }, { "type": "event", "name": "BatchApplied", "inputs": [{ "name": "oldRoot", "type": "uint256", "indexed": false, "internalType": "uint256" }, { "name": "newRoot", "type": "uint256", "indexed": false, "internalType": "uint256" }, { "name": "oldAppliedLen", "type": "uint64", "indexed": false, "internalType": "uint64" }, { "name": "newAppliedLen", "type": "uint64", "indexed": false, "internalType": "uint64" }, { "name": "oldNextIndex", "type": "uint32", "indexed": false, "internalType": "uint32" }, { "name": "newNextIndex", "type": "uint32", "indexed": false, "internalType": "uint32" }, { "name": "opsCount", "type": "uint256", "indexed": false, "internalType": "uint256" }, { "name": "nfCount", "type": "uint256", "indexed": false, "internalType": "uint256" }], "anonymous": false }, { "type": "event", "name": "Deposit", "inputs": [{ "name": "from", "type": "address", "indexed": true, "internalType": "address" }, { "name": "assetId", "type": "uint256", "indexed": true, "internalType": "uint256" }, { "name": "amount", "type": "uint256", "indexed": false, "internalType": "uint256" }], "anonymous": false }, { "type": "event", "name": "DepositEnqueued", "inputs": [{ "name": "idx", "type": "uint64", "indexed": false, "internalType": "uint64" }, { "name": "from", "type": "address", "indexed": true, "internalType": "address" }, { "name": "assetId", "type": "uint256", "indexed": true, "internalType": "uint256" }, { "name": "amount", "type": "uint256", "indexed": false, "internalType": "uint256" }, { "name": "commitment", "type": "uint256", "indexed": false, "internalType": "uint256" }, { "name": "hItem", "type": "uint256", "indexed": false, "internalType": "uint256" }], "anonymous": false }, { "type": "event", "name": "ExternalOpExecuted", "inputs": [{ "name": "kind", "type": "uint8", "indexed": false, "internalType": "uint8" }, { "name": "assetId", "type": "uint256", "indexed": true, "internalType": "uint256" }, { "name": "to", "type": "address", "indexed": true, "internalType": "address" }, { "name": "amount", "type": "uint256", "indexed": false, "internalType": "uint256" }], "anonymous": false }, { "type": "event", "name": "LeavesInserted", "inputs": [{ "name": "startIndex", "type": "uint32", "indexed": false, "internalType": "uint32" }, { "name": "leaves", "type": "uint256[]", "indexed": false, "internalType": "uint256[]" }], "anonymous": false }, { "type": "event", "name": "NewRoot", "inputs": [{ "name": "root", "type": "uint256", "indexed": false, "internalType": "uint256" }], "anonymous": false }, { "type": "event", "name": "OwnershipHandoverCanceled", "inputs": [{ "name": "pendingOwner", "type": "address", "indexed": true, "internalType": "address" }], "anonymous": false }, { "type": "event", "name": "OwnershipHandoverRequested", "inputs": [{ "name": "pendingOwner", "type": "address", "indexed": true, "internalType": "address" }], "anonymous": false }, { "type": "event", "name": "OwnershipTransferred", "inputs": [{ "name": "oldOwner", "type": "address", "indexed": true, "internalType": "address" }, { "name": "newOwner", "type": "address", "indexed": true, "internalType": "address" }], "anonymous": false }, { "type": "event", "name": "Spent", "inputs": [{ "name": "nf", "type": "bytes32", "indexed": false, "internalType": "bytes32" }], "anonymous": false }, { "type": "error", "name": "AlreadyInitialized", "inputs": [] }, { "type": "error", "name": "BadZeros", "inputs": [] }, { "type": "error", "name": "InsufficientPoolBalance", "inputs": [] }, { "type": "error", "name": "InvalidAsset", "inputs": [] }, { "type": "error", "name": "LeavesIdxMismatch", "inputs": [] }, { "type": "error", "name": "LeavesLenMismatch", "inputs": [] }, { "type": "error", "name": "LeavesRootMismatch", "inputs": [] }, { "type": "error", "name": "NewOwnerIsZeroAddress", "inputs": [] }, { "type": "error", "name": "NfHashMismatch", "inputs": [] }, { "type": "error", "name": "NoHandoverRequest", "inputs": [] }, { "type": "error", "name": "NotInitialized", "inputs": [] }, { "type": "error", "name": "OldIndexMismatch", "inputs": [] }, { "type": "error", "name": "OpsHashMismatch", "inputs": [] }, { "type": "error", "name": "QueueHeadMismatch", "inputs": [] }, { "type": "error", "name": "QueueTailMismatch", "inputs": [] }, { "type": "error", "name": "Reentrancy", "inputs": [] }, { "type": "error", "name": "Unauthorized", "inputs": [] }, { "type": "error", "name": "UnknownOpKind", "inputs": [] }, { "type": "error", "name": "UnknownRoot", "inputs": [] }, { "type": "error", "name": "VerifyFail", "inputs": [] }, { "type": "error", "name": "ZeroAmount", "inputs": [] }, { "type": "error", "name": "ZeroCommitment", "inputs": [] }];
1451
+ var EV_NewRoot = getAbiItem({ abi: PrivatePoolAbi, name: "NewRoot" });
1452
+ var EV_LeavesInserted = getAbiItem({ abi: PrivatePoolAbi, name: "LeavesInserted" });
1453
+ var EV_Spent = getAbiItem({ abi: PrivatePoolAbi, name: "Spent" });
1454
+
1455
+ // src/exchange/depositERC20.ts
1456
+ function sysAddressFromAssetId(assetId) {
1457
+ const val = 0x20n << 152n | assetId;
1458
+ return `0x${val.toString(16).padStart(40, "0")}`;
1459
+ }
1460
+ async function depositERC20({
1461
+ clients,
1462
+ pool,
1463
+ chainId,
1464
+ token,
1465
+ assetId,
1466
+ amount,
1467
+ seed,
1468
+ sysAddress,
1469
+ store
1470
+ }) {
1471
+ await initPoseidon();
1472
+ const { sk, skBytes, Ax, Ay, pubkey, blinding } = await genNote(seed);
1473
+ const { commitment } = makeDepositCommitments(assetId, amount, pubkey, blinding);
1474
+ const sys = sysAddress ?? sysAddressFromAssetId(assetId);
1475
+ const { publicClient, walletClient, account } = clients;
1476
+ const allowance = await publicClient.readContract({
1477
+ address: token,
1478
+ abi: erc20Abi,
1479
+ functionName: "allowance",
1480
+ args: [account.address, pool]
1481
+ });
1482
+ if (allowance < amount) {
1483
+ const { request: request2 } = await publicClient.simulateContract({
1484
+ address: token,
1485
+ abi: erc20Abi,
1486
+ functionName: "approve",
1487
+ args: [pool, amount],
1488
+ account
1489
+ });
1490
+ const h = await walletClient.writeContract(request2);
1491
+ await publicClient.waitForTransactionReceipt({ hash: h });
1492
+ }
1493
+ const { request } = await publicClient.simulateContract({
1494
+ address: pool,
1495
+ abi: PrivatePoolAbi,
1496
+ functionName: "depositERC20",
1497
+ args: [assetId, amount, commitment, token, sys],
1498
+ account
1499
+ });
1500
+ const hash = await walletClient.writeContract(request);
1501
+ const receipt = await publicClient.waitForTransactionReceipt({ hash });
1502
+ const note = {
1503
+ version: 1,
1504
+ commitment: `0x${BigInt(commitment).toString(16).padStart(64, "0")}`,
1505
+ chainId,
1506
+ pool,
1507
+ assetId,
1508
+ amount,
1509
+ ownerPub: { x: BigInt(Ax), y: BigInt(Ay) },
1510
+ notePubkey: BigInt(pubkey),
1511
+ secret: {
1512
+ sk: skBytes,
1513
+ blind: (() => {
1514
+ const hex = BigInt(blinding).toString(16).padStart(64, "0");
1515
+ return Uint8Array.from(Buffer.from(hex, "hex"));
1516
+ })()
1517
+ },
1518
+ status: "STAGED",
1519
+ createdAt: Date.now(),
1520
+ updatedAt: Date.now()
1521
+ };
1522
+ if (store) await store.addStagedNotes([note]);
1523
+ return { hash, receipt, note };
1524
+ }
1525
+
1526
+ // src/exchange/depositHYPE.ts
1527
+ var HYPE_ASSET_ID = 150n;
1528
+ async function depositHYPE({
1529
+ clients,
1530
+ pool,
1531
+ chainId,
1532
+ amountWei,
1533
+ seed,
1534
+ store
1535
+ }) {
1536
+ await initPoseidon();
1537
+ const { sk, skBytes, Ax, Ay, pubkey, blinding } = await genNote(seed);
1538
+ const { commitment } = makeDepositCommitments(HYPE_ASSET_ID, amountWei, pubkey, blinding);
1539
+ const { publicClient, walletClient, account } = clients;
1540
+ const { request } = await publicClient.simulateContract({
1541
+ address: pool,
1542
+ abi: PrivatePoolAbi,
1543
+ functionName: "depositHYPE",
1544
+ args: [commitment],
1545
+ value: amountWei,
1546
+ account
1547
+ });
1548
+ const hash = await walletClient.writeContract(request);
1549
+ const receipt = await publicClient.waitForTransactionReceipt({ hash });
1550
+ const note = {
1551
+ version: 1,
1552
+ commitment: `0x${BigInt(commitment).toString(16).padStart(64, "0")}`,
1553
+ chainId,
1554
+ pool,
1555
+ assetId: HYPE_ASSET_ID,
1556
+ amount: amountWei,
1557
+ ownerPub: { x: BigInt(Ax), y: BigInt(Ay) },
1558
+ notePubkey: BigInt(pubkey),
1559
+ secret: {
1560
+ sk: skBytes,
1561
+ blind: (() => {
1562
+ const hex = BigInt(blinding).toString(16).padStart(64, "0");
1563
+ return Uint8Array.from(Buffer.from(hex, "hex"));
1564
+ })()
1565
+ },
1566
+ status: "STAGED",
1567
+ createdAt: Date.now(),
1568
+ updatedAt: Date.now()
1569
+ };
1570
+ if (store) await store.addStagedNotes([note]);
1571
+ return { hash, receipt, note };
1572
+ }
1573
+
1574
+ // node_modules/@noble/ciphers/esm/utils.js
1575
+ function isBytes(a) {
1576
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
1577
+ }
1578
+ function abool(b) {
1579
+ if (typeof b !== "boolean")
1580
+ throw new Error(`boolean expected, not ${b}`);
1581
+ }
1582
+ function anumber(n) {
1583
+ if (!Number.isSafeInteger(n) || n < 0)
1584
+ throw new Error("positive integer expected, got " + n);
1585
+ }
1586
+ function abytes(b, ...lengths) {
1587
+ if (!isBytes(b))
1588
+ throw new Error("Uint8Array expected");
1589
+ if (lengths.length > 0 && !lengths.includes(b.length))
1590
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
1591
+ }
1592
+ function aexists(instance, checkFinished = true) {
1593
+ if (instance.destroyed)
1594
+ throw new Error("Hash instance has been destroyed");
1595
+ if (checkFinished && instance.finished)
1596
+ throw new Error("Hash#digest() has already been called");
1597
+ }
1598
+ function aoutput(out, instance) {
1599
+ abytes(out);
1600
+ const min = instance.outputLen;
1601
+ if (out.length < min) {
1602
+ throw new Error("digestInto() expects output buffer of length at least " + min);
1603
+ }
1604
+ }
1605
+ function u32(arr) {
1606
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
1607
+ }
1608
+ function clean(...arrays) {
1609
+ for (let i = 0; i < arrays.length; i++) {
1610
+ arrays[i].fill(0);
1611
+ }
1612
+ }
1613
+ function createView(arr) {
1614
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
1615
+ }
1616
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
1617
+ function utf8ToBytes(str) {
1618
+ if (typeof str !== "string")
1619
+ throw new Error("string expected");
1620
+ return new Uint8Array(new TextEncoder().encode(str));
1621
+ }
1622
+ function toBytes(data) {
1623
+ if (typeof data === "string")
1624
+ data = utf8ToBytes(data);
1625
+ else if (isBytes(data))
1626
+ data = copyBytes(data);
1627
+ else
1628
+ throw new Error("Uint8Array expected, got " + typeof data);
1629
+ return data;
1630
+ }
1631
+ function checkOpts(defaults, opts) {
1632
+ if (opts == null || typeof opts !== "object")
1633
+ throw new Error("options must be defined");
1634
+ const merged = Object.assign(defaults, opts);
1635
+ return merged;
1636
+ }
1637
+ function equalBytes(a, b) {
1638
+ if (a.length !== b.length)
1639
+ return false;
1640
+ let diff = 0;
1641
+ for (let i = 0; i < a.length; i++)
1642
+ diff |= a[i] ^ b[i];
1643
+ return diff === 0;
1644
+ }
1645
+ var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
1646
+ function wrappedCipher(key, ...args) {
1647
+ abytes(key);
1648
+ if (!isLE)
1649
+ throw new Error("Non little-endian hardware is not yet supported");
1650
+ if (params.nonceLength !== void 0) {
1651
+ const nonce = args[0];
1652
+ if (!nonce)
1653
+ throw new Error("nonce / iv required");
1654
+ if (params.varSizeNonce)
1655
+ abytes(nonce);
1656
+ else
1657
+ abytes(nonce, params.nonceLength);
1658
+ }
1659
+ const tagl = params.tagLength;
1660
+ if (tagl && args[1] !== void 0) {
1661
+ abytes(args[1]);
1662
+ }
1663
+ const cipher = constructor(key, ...args);
1664
+ const checkOutput = (fnLength, output) => {
1665
+ if (output !== void 0) {
1666
+ if (fnLength !== 2)
1667
+ throw new Error("cipher output not supported");
1668
+ abytes(output);
1669
+ }
1670
+ };
1671
+ let called = false;
1672
+ const wrCipher = {
1673
+ encrypt(data, output) {
1674
+ if (called)
1675
+ throw new Error("cannot encrypt() twice with same key + nonce");
1676
+ called = true;
1677
+ abytes(data);
1678
+ checkOutput(cipher.encrypt.length, output);
1679
+ return cipher.encrypt(data, output);
1680
+ },
1681
+ decrypt(data, output) {
1682
+ abytes(data);
1683
+ if (tagl && data.length < tagl)
1684
+ throw new Error("invalid ciphertext length: smaller than tagLength=" + tagl);
1685
+ checkOutput(cipher.decrypt.length, output);
1686
+ return cipher.decrypt(data, output);
1687
+ }
1688
+ };
1689
+ return wrCipher;
1690
+ }
1691
+ Object.assign(wrappedCipher, params);
1692
+ return wrappedCipher;
1693
+ };
1694
+ function getOutput(expectedLength, out, onlyAligned = true) {
1695
+ if (out === void 0)
1696
+ return new Uint8Array(expectedLength);
1697
+ if (out.length !== expectedLength)
1698
+ throw new Error("invalid output length, expected " + expectedLength + ", got: " + out.length);
1699
+ if (onlyAligned && !isAligned32(out))
1700
+ throw new Error("invalid output, must be aligned");
1701
+ return out;
1702
+ }
1703
+ function setBigUint64(view, byteOffset, value, isLE3) {
1704
+ if (typeof view.setBigUint64 === "function")
1705
+ return view.setBigUint64(byteOffset, value, isLE3);
1706
+ const _32n2 = BigInt(32);
1707
+ const _u32_max = BigInt(4294967295);
1708
+ const wh = Number(value >> _32n2 & _u32_max);
1709
+ const wl = Number(value & _u32_max);
1710
+ const h = isLE3 ? 4 : 0;
1711
+ const l = isLE3 ? 0 : 4;
1712
+ view.setUint32(byteOffset + h, wh, isLE3);
1713
+ view.setUint32(byteOffset + l, wl, isLE3);
1714
+ }
1715
+ function u64Lengths(dataLength, aadLength, isLE3) {
1716
+ abool(isLE3);
1717
+ const num = new Uint8Array(16);
1718
+ const view = createView(num);
1719
+ setBigUint64(view, 0, BigInt(aadLength), isLE3);
1720
+ setBigUint64(view, 8, BigInt(dataLength), isLE3);
1721
+ return num;
1722
+ }
1723
+ function isAligned32(bytes) {
1724
+ return bytes.byteOffset % 4 === 0;
1725
+ }
1726
+ function copyBytes(bytes) {
1727
+ return Uint8Array.from(bytes);
1728
+ }
1729
+
1730
+ // node_modules/@noble/ciphers/esm/_arx.js
1731
+ var _utf8ToBytes = (str) => Uint8Array.from(str.split("").map((c) => c.charCodeAt(0)));
1732
+ var sigma16 = _utf8ToBytes("expand 16-byte k");
1733
+ var sigma32 = _utf8ToBytes("expand 32-byte k");
1734
+ var sigma16_32 = u32(sigma16);
1735
+ var sigma32_32 = u32(sigma32);
1736
+ function rotl(a, b) {
1737
+ return a << b | a >>> 32 - b;
1738
+ }
1739
+ function isAligned322(b) {
1740
+ return b.byteOffset % 4 === 0;
1741
+ }
1742
+ var BLOCK_LEN = 64;
1743
+ var BLOCK_LEN32 = 16;
1744
+ var MAX_COUNTER = 2 ** 32 - 1;
1745
+ var U32_EMPTY = new Uint32Array();
1746
+ function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
1747
+ const len = data.length;
1748
+ const block2 = new Uint8Array(BLOCK_LEN);
1749
+ const b32 = u32(block2);
1750
+ const isAligned = isAligned322(data) && isAligned322(output);
1751
+ const d32 = isAligned ? u32(data) : U32_EMPTY;
1752
+ const o32 = isAligned ? u32(output) : U32_EMPTY;
1753
+ for (let pos = 0; pos < len; counter++) {
1754
+ core(sigma, key, nonce, b32, counter, rounds);
1755
+ if (counter >= MAX_COUNTER)
1756
+ throw new Error("arx: counter overflow");
1757
+ const take = Math.min(BLOCK_LEN, len - pos);
1758
+ if (isAligned && take === BLOCK_LEN) {
1759
+ const pos32 = pos / 4;
1760
+ if (pos % 4 !== 0)
1761
+ throw new Error("arx: invalid block position");
1762
+ for (let j = 0, posj; j < BLOCK_LEN32; j++) {
1763
+ posj = pos32 + j;
1764
+ o32[posj] = d32[posj] ^ b32[j];
1765
+ }
1766
+ pos += BLOCK_LEN;
1767
+ continue;
1768
+ }
1769
+ for (let j = 0, posj; j < take; j++) {
1770
+ posj = pos + j;
1771
+ output[posj] = data[posj] ^ block2[j];
1772
+ }
1773
+ pos += take;
1774
+ }
1775
+ }
1776
+ function createCipher(core, opts) {
1777
+ const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
1778
+ if (typeof core !== "function")
1779
+ throw new Error("core must be a function");
1780
+ anumber(counterLength);
1781
+ anumber(rounds);
1782
+ abool(counterRight);
1783
+ abool(allowShortKeys);
1784
+ return (key, nonce, data, output, counter = 0) => {
1785
+ abytes(key);
1786
+ abytes(nonce);
1787
+ abytes(data);
1788
+ const len = data.length;
1789
+ if (output === void 0)
1790
+ output = new Uint8Array(len);
1791
+ abytes(output);
1792
+ anumber(counter);
1793
+ if (counter < 0 || counter >= MAX_COUNTER)
1794
+ throw new Error("arx: counter overflow");
1795
+ if (output.length < len)
1796
+ throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);
1797
+ const toClean = [];
1798
+ let l = key.length;
1799
+ let k;
1800
+ let sigma;
1801
+ if (l === 32) {
1802
+ toClean.push(k = copyBytes(key));
1803
+ sigma = sigma32_32;
1804
+ } else if (l === 16 && allowShortKeys) {
1805
+ k = new Uint8Array(32);
1806
+ k.set(key);
1807
+ k.set(key, 16);
1808
+ sigma = sigma16_32;
1809
+ toClean.push(k);
1810
+ } else {
1811
+ throw new Error(`arx: invalid 32-byte key, got length=${l}`);
1812
+ }
1813
+ if (!isAligned322(nonce))
1814
+ toClean.push(nonce = copyBytes(nonce));
1815
+ const k32 = u32(k);
1816
+ if (extendNonceFn) {
1817
+ if (nonce.length !== 24)
1818
+ throw new Error(`arx: extended nonce must be 24 bytes`);
1819
+ extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);
1820
+ nonce = nonce.subarray(16);
1821
+ }
1822
+ const nonceNcLen = 16 - counterLength;
1823
+ if (nonceNcLen !== nonce.length)
1824
+ throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
1825
+ if (nonceNcLen !== 12) {
1826
+ const nc2 = new Uint8Array(12);
1827
+ nc2.set(nonce, counterRight ? 0 : 12 - nonce.length);
1828
+ nonce = nc2;
1829
+ toClean.push(nonce);
1830
+ }
1831
+ const n32 = u32(nonce);
1832
+ runCipher(core, sigma, k32, n32, data, output, counter, rounds);
1833
+ clean(...toClean);
1834
+ return output;
1835
+ };
1836
+ }
1837
+
1838
+ // node_modules/@noble/ciphers/esm/_poly1305.js
1839
+ var u8to16 = (a, i) => a[i++] & 255 | (a[i++] & 255) << 8;
1840
+ var Poly1305 = class {
1841
+ constructor(key) {
1842
+ this.blockLen = 16;
1843
+ this.outputLen = 16;
1844
+ this.buffer = new Uint8Array(16);
1845
+ this.r = new Uint16Array(10);
1846
+ this.h = new Uint16Array(10);
1847
+ this.pad = new Uint16Array(8);
1848
+ this.pos = 0;
1849
+ this.finished = false;
1850
+ key = toBytes(key);
1851
+ abytes(key, 32);
1852
+ const t0 = u8to16(key, 0);
1853
+ const t1 = u8to16(key, 2);
1854
+ const t2 = u8to16(key, 4);
1855
+ const t3 = u8to16(key, 6);
1856
+ const t4 = u8to16(key, 8);
1857
+ const t5 = u8to16(key, 10);
1858
+ const t6 = u8to16(key, 12);
1859
+ const t7 = u8to16(key, 14);
1860
+ this.r[0] = t0 & 8191;
1861
+ this.r[1] = (t0 >>> 13 | t1 << 3) & 8191;
1862
+ this.r[2] = (t1 >>> 10 | t2 << 6) & 7939;
1863
+ this.r[3] = (t2 >>> 7 | t3 << 9) & 8191;
1864
+ this.r[4] = (t3 >>> 4 | t4 << 12) & 255;
1865
+ this.r[5] = t4 >>> 1 & 8190;
1866
+ this.r[6] = (t4 >>> 14 | t5 << 2) & 8191;
1867
+ this.r[7] = (t5 >>> 11 | t6 << 5) & 8065;
1868
+ this.r[8] = (t6 >>> 8 | t7 << 8) & 8191;
1869
+ this.r[9] = t7 >>> 5 & 127;
1870
+ for (let i = 0; i < 8; i++)
1871
+ this.pad[i] = u8to16(key, 16 + 2 * i);
1872
+ }
1873
+ process(data, offset, isLast = false) {
1874
+ const hibit = isLast ? 0 : 1 << 11;
1875
+ const { h, r } = this;
1876
+ const r0 = r[0];
1877
+ const r1 = r[1];
1878
+ const r2 = r[2];
1879
+ const r3 = r[3];
1880
+ const r4 = r[4];
1881
+ const r5 = r[5];
1882
+ const r6 = r[6];
1883
+ const r7 = r[7];
1884
+ const r8 = r[8];
1885
+ const r9 = r[9];
1886
+ const t0 = u8to16(data, offset + 0);
1887
+ const t1 = u8to16(data, offset + 2);
1888
+ const t2 = u8to16(data, offset + 4);
1889
+ const t3 = u8to16(data, offset + 6);
1890
+ const t4 = u8to16(data, offset + 8);
1891
+ const t5 = u8to16(data, offset + 10);
1892
+ const t6 = u8to16(data, offset + 12);
1893
+ const t7 = u8to16(data, offset + 14);
1894
+ let h0 = h[0] + (t0 & 8191);
1895
+ let h1 = h[1] + ((t0 >>> 13 | t1 << 3) & 8191);
1896
+ let h2 = h[2] + ((t1 >>> 10 | t2 << 6) & 8191);
1897
+ let h3 = h[3] + ((t2 >>> 7 | t3 << 9) & 8191);
1898
+ let h4 = h[4] + ((t3 >>> 4 | t4 << 12) & 8191);
1899
+ let h5 = h[5] + (t4 >>> 1 & 8191);
1900
+ let h6 = h[6] + ((t4 >>> 14 | t5 << 2) & 8191);
1901
+ let h7 = h[7] + ((t5 >>> 11 | t6 << 5) & 8191);
1902
+ let h8 = h[8] + ((t6 >>> 8 | t7 << 8) & 8191);
1903
+ let h9 = h[9] + (t7 >>> 5 | hibit);
1904
+ let c = 0;
1905
+ let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
1906
+ c = d0 >>> 13;
1907
+ d0 &= 8191;
1908
+ d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
1909
+ c += d0 >>> 13;
1910
+ d0 &= 8191;
1911
+ let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
1912
+ c = d1 >>> 13;
1913
+ d1 &= 8191;
1914
+ d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
1915
+ c += d1 >>> 13;
1916
+ d1 &= 8191;
1917
+ let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
1918
+ c = d2 >>> 13;
1919
+ d2 &= 8191;
1920
+ d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
1921
+ c += d2 >>> 13;
1922
+ d2 &= 8191;
1923
+ let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);
1924
+ c = d3 >>> 13;
1925
+ d3 &= 8191;
1926
+ d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
1927
+ c += d3 >>> 13;
1928
+ d3 &= 8191;
1929
+ let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
1930
+ c = d4 >>> 13;
1931
+ d4 &= 8191;
1932
+ d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
1933
+ c += d4 >>> 13;
1934
+ d4 &= 8191;
1935
+ let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;
1936
+ c = d5 >>> 13;
1937
+ d5 &= 8191;
1938
+ d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
1939
+ c += d5 >>> 13;
1940
+ d5 &= 8191;
1941
+ let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;
1942
+ c = d6 >>> 13;
1943
+ d6 &= 8191;
1944
+ d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
1945
+ c += d6 >>> 13;
1946
+ d6 &= 8191;
1947
+ let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;
1948
+ c = d7 >>> 13;
1949
+ d7 &= 8191;
1950
+ d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
1951
+ c += d7 >>> 13;
1952
+ d7 &= 8191;
1953
+ let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;
1954
+ c = d8 >>> 13;
1955
+ d8 &= 8191;
1956
+ d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
1957
+ c += d8 >>> 13;
1958
+ d8 &= 8191;
1959
+ let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;
1960
+ c = d9 >>> 13;
1961
+ d9 &= 8191;
1962
+ d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
1963
+ c += d9 >>> 13;
1964
+ d9 &= 8191;
1965
+ c = (c << 2) + c | 0;
1966
+ c = c + d0 | 0;
1967
+ d0 = c & 8191;
1968
+ c = c >>> 13;
1969
+ d1 += c;
1970
+ h[0] = d0;
1971
+ h[1] = d1;
1972
+ h[2] = d2;
1973
+ h[3] = d3;
1974
+ h[4] = d4;
1975
+ h[5] = d5;
1976
+ h[6] = d6;
1977
+ h[7] = d7;
1978
+ h[8] = d8;
1979
+ h[9] = d9;
1980
+ }
1981
+ finalize() {
1982
+ const { h, pad } = this;
1983
+ const g = new Uint16Array(10);
1984
+ let c = h[1] >>> 13;
1985
+ h[1] &= 8191;
1986
+ for (let i = 2; i < 10; i++) {
1987
+ h[i] += c;
1988
+ c = h[i] >>> 13;
1989
+ h[i] &= 8191;
1990
+ }
1991
+ h[0] += c * 5;
1992
+ c = h[0] >>> 13;
1993
+ h[0] &= 8191;
1994
+ h[1] += c;
1995
+ c = h[1] >>> 13;
1996
+ h[1] &= 8191;
1997
+ h[2] += c;
1998
+ g[0] = h[0] + 5;
1999
+ c = g[0] >>> 13;
2000
+ g[0] &= 8191;
2001
+ for (let i = 1; i < 10; i++) {
2002
+ g[i] = h[i] + c;
2003
+ c = g[i] >>> 13;
2004
+ g[i] &= 8191;
2005
+ }
2006
+ g[9] -= 1 << 13;
2007
+ let mask = (c ^ 1) - 1;
2008
+ for (let i = 0; i < 10; i++)
2009
+ g[i] &= mask;
2010
+ mask = ~mask;
2011
+ for (let i = 0; i < 10; i++)
2012
+ h[i] = h[i] & mask | g[i];
2013
+ h[0] = (h[0] | h[1] << 13) & 65535;
2014
+ h[1] = (h[1] >>> 3 | h[2] << 10) & 65535;
2015
+ h[2] = (h[2] >>> 6 | h[3] << 7) & 65535;
2016
+ h[3] = (h[3] >>> 9 | h[4] << 4) & 65535;
2017
+ h[4] = (h[4] >>> 12 | h[5] << 1 | h[6] << 14) & 65535;
2018
+ h[5] = (h[6] >>> 2 | h[7] << 11) & 65535;
2019
+ h[6] = (h[7] >>> 5 | h[8] << 8) & 65535;
2020
+ h[7] = (h[8] >>> 8 | h[9] << 5) & 65535;
2021
+ let f = h[0] + pad[0];
2022
+ h[0] = f & 65535;
2023
+ for (let i = 1; i < 8; i++) {
2024
+ f = (h[i] + pad[i] | 0) + (f >>> 16) | 0;
2025
+ h[i] = f & 65535;
2026
+ }
2027
+ clean(g);
2028
+ }
2029
+ update(data) {
2030
+ aexists(this);
2031
+ data = toBytes(data);
2032
+ abytes(data);
2033
+ const { buffer, blockLen } = this;
2034
+ const len = data.length;
2035
+ for (let pos = 0; pos < len; ) {
2036
+ const take = Math.min(blockLen - this.pos, len - pos);
2037
+ if (take === blockLen) {
2038
+ for (; blockLen <= len - pos; pos += blockLen)
2039
+ this.process(data, pos);
2040
+ continue;
2041
+ }
2042
+ buffer.set(data.subarray(pos, pos + take), this.pos);
2043
+ this.pos += take;
2044
+ pos += take;
2045
+ if (this.pos === blockLen) {
2046
+ this.process(buffer, 0, false);
2047
+ this.pos = 0;
2048
+ }
2049
+ }
2050
+ return this;
2051
+ }
2052
+ destroy() {
2053
+ clean(this.h, this.r, this.buffer, this.pad);
2054
+ }
2055
+ digestInto(out) {
2056
+ aexists(this);
2057
+ aoutput(out, this);
2058
+ this.finished = true;
2059
+ const { buffer, h } = this;
2060
+ let { pos } = this;
2061
+ if (pos) {
2062
+ buffer[pos++] = 1;
2063
+ for (; pos < 16; pos++)
2064
+ buffer[pos] = 0;
2065
+ this.process(buffer, 0, true);
2066
+ }
2067
+ this.finalize();
2068
+ let opos = 0;
2069
+ for (let i = 0; i < 8; i++) {
2070
+ out[opos++] = h[i] >>> 0;
2071
+ out[opos++] = h[i] >>> 8;
2072
+ }
2073
+ return out;
2074
+ }
2075
+ digest() {
2076
+ const { buffer, outputLen } = this;
2077
+ this.digestInto(buffer);
2078
+ const res = buffer.slice(0, outputLen);
2079
+ this.destroy();
2080
+ return res;
2081
+ }
2082
+ };
2083
+ function wrapConstructorWithKey(hashCons) {
2084
+ const hashC = (msg, key) => hashCons(key).update(toBytes(msg)).digest();
2085
+ const tmp = hashCons(new Uint8Array(32));
2086
+ hashC.outputLen = tmp.outputLen;
2087
+ hashC.blockLen = tmp.blockLen;
2088
+ hashC.create = (key) => hashCons(key);
2089
+ return hashC;
2090
+ }
2091
+ var poly1305 = wrapConstructorWithKey((key) => new Poly1305(key));
2092
+
2093
+ // node_modules/@noble/ciphers/esm/chacha.js
2094
+ function chachaCore(s, k, n, out, cnt, rounds = 20) {
2095
+ let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2];
2096
+ let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
2097
+ for (let r = 0; r < rounds; r += 2) {
2098
+ x00 = x00 + x04 | 0;
2099
+ x12 = rotl(x12 ^ x00, 16);
2100
+ x08 = x08 + x12 | 0;
2101
+ x04 = rotl(x04 ^ x08, 12);
2102
+ x00 = x00 + x04 | 0;
2103
+ x12 = rotl(x12 ^ x00, 8);
2104
+ x08 = x08 + x12 | 0;
2105
+ x04 = rotl(x04 ^ x08, 7);
2106
+ x01 = x01 + x05 | 0;
2107
+ x13 = rotl(x13 ^ x01, 16);
2108
+ x09 = x09 + x13 | 0;
2109
+ x05 = rotl(x05 ^ x09, 12);
2110
+ x01 = x01 + x05 | 0;
2111
+ x13 = rotl(x13 ^ x01, 8);
2112
+ x09 = x09 + x13 | 0;
2113
+ x05 = rotl(x05 ^ x09, 7);
2114
+ x02 = x02 + x06 | 0;
2115
+ x14 = rotl(x14 ^ x02, 16);
2116
+ x10 = x10 + x14 | 0;
2117
+ x06 = rotl(x06 ^ x10, 12);
2118
+ x02 = x02 + x06 | 0;
2119
+ x14 = rotl(x14 ^ x02, 8);
2120
+ x10 = x10 + x14 | 0;
2121
+ x06 = rotl(x06 ^ x10, 7);
2122
+ x03 = x03 + x07 | 0;
2123
+ x15 = rotl(x15 ^ x03, 16);
2124
+ x11 = x11 + x15 | 0;
2125
+ x07 = rotl(x07 ^ x11, 12);
2126
+ x03 = x03 + x07 | 0;
2127
+ x15 = rotl(x15 ^ x03, 8);
2128
+ x11 = x11 + x15 | 0;
2129
+ x07 = rotl(x07 ^ x11, 7);
2130
+ x00 = x00 + x05 | 0;
2131
+ x15 = rotl(x15 ^ x00, 16);
2132
+ x10 = x10 + x15 | 0;
2133
+ x05 = rotl(x05 ^ x10, 12);
2134
+ x00 = x00 + x05 | 0;
2135
+ x15 = rotl(x15 ^ x00, 8);
2136
+ x10 = x10 + x15 | 0;
2137
+ x05 = rotl(x05 ^ x10, 7);
2138
+ x01 = x01 + x06 | 0;
2139
+ x12 = rotl(x12 ^ x01, 16);
2140
+ x11 = x11 + x12 | 0;
2141
+ x06 = rotl(x06 ^ x11, 12);
2142
+ x01 = x01 + x06 | 0;
2143
+ x12 = rotl(x12 ^ x01, 8);
2144
+ x11 = x11 + x12 | 0;
2145
+ x06 = rotl(x06 ^ x11, 7);
2146
+ x02 = x02 + x07 | 0;
2147
+ x13 = rotl(x13 ^ x02, 16);
2148
+ x08 = x08 + x13 | 0;
2149
+ x07 = rotl(x07 ^ x08, 12);
2150
+ x02 = x02 + x07 | 0;
2151
+ x13 = rotl(x13 ^ x02, 8);
2152
+ x08 = x08 + x13 | 0;
2153
+ x07 = rotl(x07 ^ x08, 7);
2154
+ x03 = x03 + x04 | 0;
2155
+ x14 = rotl(x14 ^ x03, 16);
2156
+ x09 = x09 + x14 | 0;
2157
+ x04 = rotl(x04 ^ x09, 12);
2158
+ x03 = x03 + x04 | 0;
2159
+ x14 = rotl(x14 ^ x03, 8);
2160
+ x09 = x09 + x14 | 0;
2161
+ x04 = rotl(x04 ^ x09, 7);
2162
+ }
2163
+ let oi = 0;
2164
+ out[oi++] = y00 + x00 | 0;
2165
+ out[oi++] = y01 + x01 | 0;
2166
+ out[oi++] = y02 + x02 | 0;
2167
+ out[oi++] = y03 + x03 | 0;
2168
+ out[oi++] = y04 + x04 | 0;
2169
+ out[oi++] = y05 + x05 | 0;
2170
+ out[oi++] = y06 + x06 | 0;
2171
+ out[oi++] = y07 + x07 | 0;
2172
+ out[oi++] = y08 + x08 | 0;
2173
+ out[oi++] = y09 + x09 | 0;
2174
+ out[oi++] = y10 + x10 | 0;
2175
+ out[oi++] = y11 + x11 | 0;
2176
+ out[oi++] = y12 + x12 | 0;
2177
+ out[oi++] = y13 + x13 | 0;
2178
+ out[oi++] = y14 + x14 | 0;
2179
+ out[oi++] = y15 + x15 | 0;
2180
+ }
2181
+ function hchacha(s, k, i, o32) {
2182
+ let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3], x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3], x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7], x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3];
2183
+ for (let r = 0; r < 20; r += 2) {
2184
+ x00 = x00 + x04 | 0;
2185
+ x12 = rotl(x12 ^ x00, 16);
2186
+ x08 = x08 + x12 | 0;
2187
+ x04 = rotl(x04 ^ x08, 12);
2188
+ x00 = x00 + x04 | 0;
2189
+ x12 = rotl(x12 ^ x00, 8);
2190
+ x08 = x08 + x12 | 0;
2191
+ x04 = rotl(x04 ^ x08, 7);
2192
+ x01 = x01 + x05 | 0;
2193
+ x13 = rotl(x13 ^ x01, 16);
2194
+ x09 = x09 + x13 | 0;
2195
+ x05 = rotl(x05 ^ x09, 12);
2196
+ x01 = x01 + x05 | 0;
2197
+ x13 = rotl(x13 ^ x01, 8);
2198
+ x09 = x09 + x13 | 0;
2199
+ x05 = rotl(x05 ^ x09, 7);
2200
+ x02 = x02 + x06 | 0;
2201
+ x14 = rotl(x14 ^ x02, 16);
2202
+ x10 = x10 + x14 | 0;
2203
+ x06 = rotl(x06 ^ x10, 12);
2204
+ x02 = x02 + x06 | 0;
2205
+ x14 = rotl(x14 ^ x02, 8);
2206
+ x10 = x10 + x14 | 0;
2207
+ x06 = rotl(x06 ^ x10, 7);
2208
+ x03 = x03 + x07 | 0;
2209
+ x15 = rotl(x15 ^ x03, 16);
2210
+ x11 = x11 + x15 | 0;
2211
+ x07 = rotl(x07 ^ x11, 12);
2212
+ x03 = x03 + x07 | 0;
2213
+ x15 = rotl(x15 ^ x03, 8);
2214
+ x11 = x11 + x15 | 0;
2215
+ x07 = rotl(x07 ^ x11, 7);
2216
+ x00 = x00 + x05 | 0;
2217
+ x15 = rotl(x15 ^ x00, 16);
2218
+ x10 = x10 + x15 | 0;
2219
+ x05 = rotl(x05 ^ x10, 12);
2220
+ x00 = x00 + x05 | 0;
2221
+ x15 = rotl(x15 ^ x00, 8);
2222
+ x10 = x10 + x15 | 0;
2223
+ x05 = rotl(x05 ^ x10, 7);
2224
+ x01 = x01 + x06 | 0;
2225
+ x12 = rotl(x12 ^ x01, 16);
2226
+ x11 = x11 + x12 | 0;
2227
+ x06 = rotl(x06 ^ x11, 12);
2228
+ x01 = x01 + x06 | 0;
2229
+ x12 = rotl(x12 ^ x01, 8);
2230
+ x11 = x11 + x12 | 0;
2231
+ x06 = rotl(x06 ^ x11, 7);
2232
+ x02 = x02 + x07 | 0;
2233
+ x13 = rotl(x13 ^ x02, 16);
2234
+ x08 = x08 + x13 | 0;
2235
+ x07 = rotl(x07 ^ x08, 12);
2236
+ x02 = x02 + x07 | 0;
2237
+ x13 = rotl(x13 ^ x02, 8);
2238
+ x08 = x08 + x13 | 0;
2239
+ x07 = rotl(x07 ^ x08, 7);
2240
+ x03 = x03 + x04 | 0;
2241
+ x14 = rotl(x14 ^ x03, 16);
2242
+ x09 = x09 + x14 | 0;
2243
+ x04 = rotl(x04 ^ x09, 12);
2244
+ x03 = x03 + x04 | 0;
2245
+ x14 = rotl(x14 ^ x03, 8);
2246
+ x09 = x09 + x14 | 0;
2247
+ x04 = rotl(x04 ^ x09, 7);
2248
+ }
2249
+ let oi = 0;
2250
+ o32[oi++] = x00;
2251
+ o32[oi++] = x01;
2252
+ o32[oi++] = x02;
2253
+ o32[oi++] = x03;
2254
+ o32[oi++] = x12;
2255
+ o32[oi++] = x13;
2256
+ o32[oi++] = x14;
2257
+ o32[oi++] = x15;
2258
+ }
2259
+ var chacha20 = /* @__PURE__ */ createCipher(chachaCore, {
2260
+ counterRight: false,
2261
+ counterLength: 4,
2262
+ allowShortKeys: false
2263
+ });
2264
+ var xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {
2265
+ counterRight: false,
2266
+ counterLength: 8,
2267
+ extendNonceFn: hchacha,
2268
+ allowShortKeys: false
2269
+ });
2270
+ var ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
2271
+ var updatePadded = (h, msg) => {
2272
+ h.update(msg);
2273
+ const left = msg.length % 16;
2274
+ if (left)
2275
+ h.update(ZEROS16.subarray(left));
2276
+ };
2277
+ var ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
2278
+ function computeTag(fn, key, nonce, data, AAD) {
2279
+ const authKey = fn(key, nonce, ZEROS32);
2280
+ const h = poly1305.create(authKey);
2281
+ if (AAD)
2282
+ updatePadded(h, AAD);
2283
+ updatePadded(h, data);
2284
+ const num = u64Lengths(data.length, AAD ? AAD.length : 0, true);
2285
+ h.update(num);
2286
+ const res = h.digest();
2287
+ clean(authKey, num);
2288
+ return res;
2289
+ }
2290
+ var _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
2291
+ const tagLength = 16;
2292
+ return {
2293
+ encrypt(plaintext, output) {
2294
+ const plength = plaintext.length;
2295
+ output = getOutput(plength + tagLength, output, false);
2296
+ output.set(plaintext);
2297
+ const oPlain = output.subarray(0, -tagLength);
2298
+ xorStream(key, nonce, oPlain, oPlain, 1);
2299
+ const tag = computeTag(xorStream, key, nonce, oPlain, AAD);
2300
+ output.set(tag, plength);
2301
+ clean(tag);
2302
+ return output;
2303
+ },
2304
+ decrypt(ciphertext, output) {
2305
+ output = getOutput(ciphertext.length - tagLength, output, false);
2306
+ const data = ciphertext.subarray(0, -tagLength);
2307
+ const passedTag = ciphertext.subarray(-tagLength);
2308
+ const tag = computeTag(xorStream, key, nonce, data, AAD);
2309
+ if (!equalBytes(passedTag, tag))
2310
+ throw new Error("invalid tag");
2311
+ output.set(ciphertext.subarray(0, -tagLength));
2312
+ xorStream(key, nonce, output, output, 1);
2313
+ clean(tag);
2314
+ return output;
2315
+ }
2316
+ };
2317
+ };
2318
+ var chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20));
2319
+ var xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, _poly1305_aead(xchacha20));
2320
+
2321
+ // node_modules/@noble/hashes/esm/cryptoNode.js
2322
+ import * as nc from "crypto";
2323
+ var crypto3 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
2324
+
2325
+ // node_modules/@noble/hashes/esm/utils.js
2326
+ function isBytes2(a) {
2327
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
2328
+ }
2329
+ function anumber2(n) {
2330
+ if (!Number.isSafeInteger(n) || n < 0)
2331
+ throw new Error("positive integer expected, got " + n);
2332
+ }
2333
+ function abytes2(b, ...lengths) {
2334
+ if (!isBytes2(b))
2335
+ throw new Error("Uint8Array expected");
2336
+ if (lengths.length > 0 && !lengths.includes(b.length))
2337
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
2338
+ }
2339
+ function aexists2(instance, checkFinished = true) {
2340
+ if (instance.destroyed)
2341
+ throw new Error("Hash instance has been destroyed");
2342
+ if (checkFinished && instance.finished)
2343
+ throw new Error("Hash#digest() has already been called");
2344
+ }
2345
+ function aoutput2(out, instance) {
2346
+ abytes2(out);
2347
+ const min = instance.outputLen;
2348
+ if (out.length < min) {
2349
+ throw new Error("digestInto() expects output buffer of length at least " + min);
2350
+ }
2351
+ }
2352
+ function u8(arr) {
2353
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
2354
+ }
2355
+ function u322(arr) {
2356
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
2357
+ }
2358
+ function clean2(...arrays) {
2359
+ for (let i = 0; i < arrays.length; i++) {
2360
+ arrays[i].fill(0);
2361
+ }
2362
+ }
2363
+ function createView2(arr) {
2364
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
2365
+ }
2366
+ function rotr(word, shift) {
2367
+ return word << 32 - shift | word >>> shift;
2368
+ }
2369
+ var isLE2 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
2370
+ function byteSwap(word) {
2371
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
2372
+ }
2373
+ var swap8IfBE = isLE2 ? (n) => n : (n) => byteSwap(n);
2374
+ function byteSwap32(arr) {
2375
+ for (let i = 0; i < arr.length; i++) {
2376
+ arr[i] = byteSwap(arr[i]);
2377
+ }
2378
+ return arr;
2379
+ }
2380
+ var swap32IfBE = isLE2 ? (u) => u : byteSwap32;
2381
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
2382
+ // @ts-ignore
2383
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
2384
+ ))();
2385
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
2386
+ function bytesToHex(bytes) {
2387
+ abytes2(bytes);
2388
+ if (hasHexBuiltin)
2389
+ return bytes.toHex();
2390
+ let hex = "";
2391
+ for (let i = 0; i < bytes.length; i++) {
2392
+ hex += hexes[bytes[i]];
2393
+ }
2394
+ return hex;
2395
+ }
2396
+ function utf8ToBytes2(str) {
2397
+ if (typeof str !== "string")
2398
+ throw new Error("string expected");
2399
+ return new Uint8Array(new TextEncoder().encode(str));
2400
+ }
2401
+ function toBytes2(data) {
2402
+ if (typeof data === "string")
2403
+ data = utf8ToBytes2(data);
2404
+ abytes2(data);
2405
+ return data;
2406
+ }
2407
+ function kdfInputToBytes(data) {
2408
+ if (typeof data === "string")
2409
+ data = utf8ToBytes2(data);
2410
+ abytes2(data);
2411
+ return data;
2412
+ }
2413
+ var Hash2 = class {
2414
+ };
2415
+ function createHasher(hashCons) {
2416
+ const hashC = (msg) => hashCons().update(toBytes2(msg)).digest();
2417
+ const tmp = hashCons();
2418
+ hashC.outputLen = tmp.outputLen;
2419
+ hashC.blockLen = tmp.blockLen;
2420
+ hashC.create = () => hashCons();
2421
+ return hashC;
2422
+ }
2423
+ function createOptHasher(hashCons) {
2424
+ const hashC = (msg, opts) => hashCons(opts).update(toBytes2(msg)).digest();
2425
+ const tmp = hashCons({});
2426
+ hashC.outputLen = tmp.outputLen;
2427
+ hashC.blockLen = tmp.blockLen;
2428
+ hashC.create = (opts) => hashCons(opts);
2429
+ return hashC;
2430
+ }
2431
+ function randomBytes(bytesLength = 32) {
2432
+ if (crypto3 && typeof crypto3.getRandomValues === "function") {
2433
+ return crypto3.getRandomValues(new Uint8Array(bytesLength));
2434
+ }
2435
+ if (crypto3 && typeof crypto3.randomBytes === "function") {
2436
+ return Uint8Array.from(crypto3.randomBytes(bytesLength));
2437
+ }
2438
+ throw new Error("crypto.getRandomValues must be defined");
2439
+ }
2440
+
2441
+ // node_modules/@noble/hashes/esm/_md.js
2442
+ function setBigUint642(view, byteOffset, value, isLE3) {
2443
+ if (typeof view.setBigUint64 === "function")
2444
+ return view.setBigUint64(byteOffset, value, isLE3);
2445
+ const _32n2 = BigInt(32);
2446
+ const _u32_max = BigInt(4294967295);
2447
+ const wh = Number(value >> _32n2 & _u32_max);
2448
+ const wl = Number(value & _u32_max);
2449
+ const h = isLE3 ? 4 : 0;
2450
+ const l = isLE3 ? 0 : 4;
2451
+ view.setUint32(byteOffset + h, wh, isLE3);
2452
+ view.setUint32(byteOffset + l, wl, isLE3);
2453
+ }
2454
+ function Chi(a, b, c) {
2455
+ return a & b ^ ~a & c;
2456
+ }
2457
+ function Maj(a, b, c) {
2458
+ return a & b ^ a & c ^ b & c;
2459
+ }
2460
+ var HashMD = class extends Hash2 {
2461
+ constructor(blockLen, outputLen, padOffset, isLE3) {
2462
+ super();
2463
+ this.finished = false;
2464
+ this.length = 0;
2465
+ this.pos = 0;
2466
+ this.destroyed = false;
2467
+ this.blockLen = blockLen;
2468
+ this.outputLen = outputLen;
2469
+ this.padOffset = padOffset;
2470
+ this.isLE = isLE3;
2471
+ this.buffer = new Uint8Array(blockLen);
2472
+ this.view = createView2(this.buffer);
2473
+ }
2474
+ update(data) {
2475
+ aexists2(this);
2476
+ data = toBytes2(data);
2477
+ abytes2(data);
2478
+ const { view, buffer, blockLen } = this;
2479
+ const len = data.length;
2480
+ for (let pos = 0; pos < len; ) {
2481
+ const take = Math.min(blockLen - this.pos, len - pos);
2482
+ if (take === blockLen) {
2483
+ const dataView = createView2(data);
2484
+ for (; blockLen <= len - pos; pos += blockLen)
2485
+ this.process(dataView, pos);
2486
+ continue;
2487
+ }
2488
+ buffer.set(data.subarray(pos, pos + take), this.pos);
2489
+ this.pos += take;
2490
+ pos += take;
2491
+ if (this.pos === blockLen) {
2492
+ this.process(view, 0);
2493
+ this.pos = 0;
2494
+ }
2495
+ }
2496
+ this.length += data.length;
2497
+ this.roundClean();
2498
+ return this;
2499
+ }
2500
+ digestInto(out) {
2501
+ aexists2(this);
2502
+ aoutput2(out, this);
2503
+ this.finished = true;
2504
+ const { buffer, view, blockLen, isLE: isLE3 } = this;
2505
+ let { pos } = this;
2506
+ buffer[pos++] = 128;
2507
+ clean2(this.buffer.subarray(pos));
2508
+ if (this.padOffset > blockLen - pos) {
2509
+ this.process(view, 0);
2510
+ pos = 0;
2511
+ }
2512
+ for (let i = pos; i < blockLen; i++)
2513
+ buffer[i] = 0;
2514
+ setBigUint642(view, blockLen - 8, BigInt(this.length * 8), isLE3);
2515
+ this.process(view, 0);
2516
+ const oview = createView2(out);
2517
+ const len = this.outputLen;
2518
+ if (len % 4)
2519
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
2520
+ const outLen = len / 4;
2521
+ const state = this.get();
2522
+ if (outLen > state.length)
2523
+ throw new Error("_sha2: outputLen bigger than state");
2524
+ for (let i = 0; i < outLen; i++)
2525
+ oview.setUint32(4 * i, state[i], isLE3);
2526
+ }
2527
+ digest() {
2528
+ const { buffer, outputLen } = this;
2529
+ this.digestInto(buffer);
2530
+ const res = buffer.slice(0, outputLen);
2531
+ this.destroy();
2532
+ return res;
2533
+ }
2534
+ _cloneInto(to) {
2535
+ to || (to = new this.constructor());
2536
+ to.set(...this.get());
2537
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
2538
+ to.destroyed = destroyed;
2539
+ to.finished = finished;
2540
+ to.length = length;
2541
+ to.pos = pos;
2542
+ if (length % blockLen)
2543
+ to.buffer.set(buffer);
2544
+ return to;
2545
+ }
2546
+ clone() {
2547
+ return this._cloneInto();
2548
+ }
2549
+ };
2550
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
2551
+ 1779033703,
2552
+ 3144134277,
2553
+ 1013904242,
2554
+ 2773480762,
2555
+ 1359893119,
2556
+ 2600822924,
2557
+ 528734635,
2558
+ 1541459225
2559
+ ]);
2560
+
2561
+ // node_modules/@noble/hashes/esm/_u64.js
2562
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
2563
+ var _32n = /* @__PURE__ */ BigInt(32);
2564
+ function fromBig(n, le = false) {
2565
+ if (le)
2566
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
2567
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
2568
+ }
2569
+ var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
2570
+ var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
2571
+ var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
2572
+ var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
2573
+ var rotr32H = (_h, l) => l;
2574
+ var rotr32L = (h, _l) => h;
2575
+ function add(Ah, Al, Bh, Bl) {
2576
+ const l = (Al >>> 0) + (Bl >>> 0);
2577
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
2578
+ }
2579
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
2580
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
2581
+
2582
+ // node_modules/@noble/hashes/esm/sha2.js
2583
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
2584
+ 1116352408,
2585
+ 1899447441,
2586
+ 3049323471,
2587
+ 3921009573,
2588
+ 961987163,
2589
+ 1508970993,
2590
+ 2453635748,
2591
+ 2870763221,
2592
+ 3624381080,
2593
+ 310598401,
2594
+ 607225278,
2595
+ 1426881987,
2596
+ 1925078388,
2597
+ 2162078206,
2598
+ 2614888103,
2599
+ 3248222580,
2600
+ 3835390401,
2601
+ 4022224774,
2602
+ 264347078,
2603
+ 604807628,
2604
+ 770255983,
2605
+ 1249150122,
2606
+ 1555081692,
2607
+ 1996064986,
2608
+ 2554220882,
2609
+ 2821834349,
2610
+ 2952996808,
2611
+ 3210313671,
2612
+ 3336571891,
2613
+ 3584528711,
2614
+ 113926993,
2615
+ 338241895,
2616
+ 666307205,
2617
+ 773529912,
2618
+ 1294757372,
2619
+ 1396182291,
2620
+ 1695183700,
2621
+ 1986661051,
2622
+ 2177026350,
2623
+ 2456956037,
2624
+ 2730485921,
2625
+ 2820302411,
2626
+ 3259730800,
2627
+ 3345764771,
2628
+ 3516065817,
2629
+ 3600352804,
2630
+ 4094571909,
2631
+ 275423344,
2632
+ 430227734,
2633
+ 506948616,
2634
+ 659060556,
2635
+ 883997877,
2636
+ 958139571,
2637
+ 1322822218,
2638
+ 1537002063,
2639
+ 1747873779,
2640
+ 1955562222,
2641
+ 2024104815,
2642
+ 2227730452,
2643
+ 2361852424,
2644
+ 2428436474,
2645
+ 2756734187,
2646
+ 3204031479,
2647
+ 3329325298
2648
+ ]);
2649
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
2650
+ var SHA256 = class extends HashMD {
2651
+ constructor(outputLen = 32) {
2652
+ super(64, outputLen, 8, false);
2653
+ this.A = SHA256_IV[0] | 0;
2654
+ this.B = SHA256_IV[1] | 0;
2655
+ this.C = SHA256_IV[2] | 0;
2656
+ this.D = SHA256_IV[3] | 0;
2657
+ this.E = SHA256_IV[4] | 0;
2658
+ this.F = SHA256_IV[5] | 0;
2659
+ this.G = SHA256_IV[6] | 0;
2660
+ this.H = SHA256_IV[7] | 0;
2661
+ }
2662
+ get() {
2663
+ const { A, B, C, D, E, F, G: G2, H } = this;
2664
+ return [A, B, C, D, E, F, G2, H];
2665
+ }
2666
+ // prettier-ignore
2667
+ set(A, B, C, D, E, F, G2, H) {
2668
+ this.A = A | 0;
2669
+ this.B = B | 0;
2670
+ this.C = C | 0;
2671
+ this.D = D | 0;
2672
+ this.E = E | 0;
2673
+ this.F = F | 0;
2674
+ this.G = G2 | 0;
2675
+ this.H = H | 0;
2676
+ }
2677
+ process(view, offset) {
2678
+ for (let i = 0; i < 16; i++, offset += 4)
2679
+ SHA256_W[i] = view.getUint32(offset, false);
2680
+ for (let i = 16; i < 64; i++) {
2681
+ const W15 = SHA256_W[i - 15];
2682
+ const W2 = SHA256_W[i - 2];
2683
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
2684
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
2685
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
2686
+ }
2687
+ let { A, B, C, D, E, F, G: G2, H } = this;
2688
+ for (let i = 0; i < 64; i++) {
2689
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
2690
+ const T1 = H + sigma1 + Chi(E, F, G2) + SHA256_K[i] + SHA256_W[i] | 0;
2691
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
2692
+ const T2 = sigma0 + Maj(A, B, C) | 0;
2693
+ H = G2;
2694
+ G2 = F;
2695
+ F = E;
2696
+ E = D + T1 | 0;
2697
+ D = C;
2698
+ C = B;
2699
+ B = A;
2700
+ A = T1 + T2 | 0;
2701
+ }
2702
+ A = A + this.A | 0;
2703
+ B = B + this.B | 0;
2704
+ C = C + this.C | 0;
2705
+ D = D + this.D | 0;
2706
+ E = E + this.E | 0;
2707
+ F = F + this.F | 0;
2708
+ G2 = G2 + this.G | 0;
2709
+ H = H + this.H | 0;
2710
+ this.set(A, B, C, D, E, F, G2, H);
2711
+ }
2712
+ roundClean() {
2713
+ clean2(SHA256_W);
2714
+ }
2715
+ destroy() {
2716
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
2717
+ clean2(this.buffer);
2718
+ }
2719
+ };
2720
+ var sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
2721
+
2722
+ // node_modules/@noble/hashes/esm/sha256.js
2723
+ var sha2562 = sha256;
2724
+
2725
+ // src/notes/vault.ts
2726
+ function u8ToB64(u82) {
2727
+ if (typeof Buffer !== "undefined") return Buffer.from(u82).toString("base64");
2728
+ let s = "";
2729
+ for (let i = 0; i < u82.length; i++) s += String.fromCharCode(u82[i]);
2730
+ return btoa(s);
2731
+ }
2732
+ function b64ToU8(b64) {
2733
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(b64, "base64"));
2734
+ const bin = atob(b64);
2735
+ const out = new Uint8Array(bin.length);
2736
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
2737
+ return out;
2738
+ }
2739
+ function replacer(_k, v) {
2740
+ return typeof v === "bigint" ? `bn:${v.toString()}` : v;
2741
+ }
2742
+ function reviver(_k, v) {
2743
+ return typeof v === "string" && v.startsWith("bn:") ? BigInt(v.slice(3)) : v;
2744
+ }
2745
+ function headerOrderA(h) {
2746
+ const { v, createdAt, kdf, seq } = h;
2747
+ const base = { v, createdAt, kdf, seq };
2748
+ if ("prevHashHex" in h) base.prevHashHex = h.prevHashHex;
2749
+ return base;
2750
+ }
2751
+ function headerOrderB(h) {
2752
+ const { v, createdAt, kdf, seq } = h;
2753
+ const base = { v, createdAt, seq, kdf };
2754
+ if ("prevHashHex" in h) base.prevHashHex = h.prevHashHex;
2755
+ return base;
2756
+ }
2757
+ function encAADBytes(h) {
2758
+ return new TextEncoder().encode(JSON.stringify(h));
2759
+ }
2760
+ function encryptBlob(key, body, header) {
2761
+ const plaintext = new TextEncoder().encode(JSON.stringify(body, replacer));
2762
+ const headerBase = { ...header };
2763
+ const hjson = JSON.stringify(headerBase);
2764
+ const hashInput = new TextEncoder().encode(hjson + ":" + plaintext.length);
2765
+ const seqHash = bytesToHex(sha2562(hashInput));
2766
+ const storedHeader = { ...headerBase, prevHashHex: seqHash };
2767
+ const aad = encAADBytes(storedHeader);
2768
+ const nonce = randomBytes(24);
2769
+ const aead = xchacha20poly1305(key, nonce);
2770
+ const ciphertext = aead.encrypt(plaintext, void 0, aad);
2771
+ return {
2772
+ header: storedHeader,
2773
+ nonceB64: u8ToB64(nonce),
2774
+ ciphertextB64: u8ToB64(ciphertext)
2775
+ };
2776
+ }
2777
+ function decryptBlob(key, blob) {
2778
+ const nonce = b64ToU8(blob.nonceB64);
2779
+ const ciphertext = b64ToU8(blob.ciphertextB64);
2780
+ const tryWithHeader = (hdr) => {
2781
+ try {
2782
+ const aead = xchacha20poly1305(key, nonce);
2783
+ const aad = encAADBytes(hdr);
2784
+ return aead.decrypt(ciphertext, void 0, aad);
2785
+ } catch {
2786
+ return null;
2787
+ }
2788
+ };
2789
+ const candidates = [];
2790
+ candidates.push(blob.header);
2791
+ candidates.push(headerOrderA(blob.header));
2792
+ candidates.push(headerOrderB(blob.header));
2793
+ if (blob.header.prevHashHex != null) {
2794
+ const { prevHashHex, ...rest } = blob.header;
2795
+ candidates.push(rest);
2796
+ candidates.push(headerOrderA(rest));
2797
+ candidates.push(headerOrderB(rest));
2798
+ }
2799
+ let plaintext = null;
2800
+ for (const hdr of candidates) {
2801
+ plaintext = tryWithHeader(hdr);
2802
+ if (plaintext) break;
2803
+ }
2804
+ if (!plaintext) throw new Error("vault decrypt failed (invalid tag)");
2805
+ return JSON.parse(new TextDecoder().decode(plaintext), reviver);
2806
+ }
2807
+
2808
+ // node_modules/@noble/hashes/esm/_blake.js
2809
+ var BSIGMA = /* @__PURE__ */ Uint8Array.from([
2810
+ 0,
2811
+ 1,
2812
+ 2,
2813
+ 3,
2814
+ 4,
2815
+ 5,
2816
+ 6,
2817
+ 7,
2818
+ 8,
2819
+ 9,
2820
+ 10,
2821
+ 11,
2822
+ 12,
2823
+ 13,
2824
+ 14,
2825
+ 15,
2826
+ 14,
2827
+ 10,
2828
+ 4,
2829
+ 8,
2830
+ 9,
2831
+ 15,
2832
+ 13,
2833
+ 6,
2834
+ 1,
2835
+ 12,
2836
+ 0,
2837
+ 2,
2838
+ 11,
2839
+ 7,
2840
+ 5,
2841
+ 3,
2842
+ 11,
2843
+ 8,
2844
+ 12,
2845
+ 0,
2846
+ 5,
2847
+ 2,
2848
+ 15,
2849
+ 13,
2850
+ 10,
2851
+ 14,
2852
+ 3,
2853
+ 6,
2854
+ 7,
2855
+ 1,
2856
+ 9,
2857
+ 4,
2858
+ 7,
2859
+ 9,
2860
+ 3,
2861
+ 1,
2862
+ 13,
2863
+ 12,
2864
+ 11,
2865
+ 14,
2866
+ 2,
2867
+ 6,
2868
+ 5,
2869
+ 10,
2870
+ 4,
2871
+ 0,
2872
+ 15,
2873
+ 8,
2874
+ 9,
2875
+ 0,
2876
+ 5,
2877
+ 7,
2878
+ 2,
2879
+ 4,
2880
+ 10,
2881
+ 15,
2882
+ 14,
2883
+ 1,
2884
+ 11,
2885
+ 12,
2886
+ 6,
2887
+ 8,
2888
+ 3,
2889
+ 13,
2890
+ 2,
2891
+ 12,
2892
+ 6,
2893
+ 10,
2894
+ 0,
2895
+ 11,
2896
+ 8,
2897
+ 3,
2898
+ 4,
2899
+ 13,
2900
+ 7,
2901
+ 5,
2902
+ 15,
2903
+ 14,
2904
+ 1,
2905
+ 9,
2906
+ 12,
2907
+ 5,
2908
+ 1,
2909
+ 15,
2910
+ 14,
2911
+ 13,
2912
+ 4,
2913
+ 10,
2914
+ 0,
2915
+ 7,
2916
+ 6,
2917
+ 3,
2918
+ 9,
2919
+ 2,
2920
+ 8,
2921
+ 11,
2922
+ 13,
2923
+ 11,
2924
+ 7,
2925
+ 14,
2926
+ 12,
2927
+ 1,
2928
+ 3,
2929
+ 9,
2930
+ 5,
2931
+ 0,
2932
+ 15,
2933
+ 4,
2934
+ 8,
2935
+ 6,
2936
+ 2,
2937
+ 10,
2938
+ 6,
2939
+ 15,
2940
+ 14,
2941
+ 9,
2942
+ 11,
2943
+ 3,
2944
+ 0,
2945
+ 8,
2946
+ 12,
2947
+ 2,
2948
+ 13,
2949
+ 7,
2950
+ 1,
2951
+ 4,
2952
+ 10,
2953
+ 5,
2954
+ 10,
2955
+ 2,
2956
+ 8,
2957
+ 4,
2958
+ 7,
2959
+ 6,
2960
+ 1,
2961
+ 5,
2962
+ 15,
2963
+ 11,
2964
+ 9,
2965
+ 14,
2966
+ 3,
2967
+ 12,
2968
+ 13,
2969
+ 0,
2970
+ 0,
2971
+ 1,
2972
+ 2,
2973
+ 3,
2974
+ 4,
2975
+ 5,
2976
+ 6,
2977
+ 7,
2978
+ 8,
2979
+ 9,
2980
+ 10,
2981
+ 11,
2982
+ 12,
2983
+ 13,
2984
+ 14,
2985
+ 15,
2986
+ 14,
2987
+ 10,
2988
+ 4,
2989
+ 8,
2990
+ 9,
2991
+ 15,
2992
+ 13,
2993
+ 6,
2994
+ 1,
2995
+ 12,
2996
+ 0,
2997
+ 2,
2998
+ 11,
2999
+ 7,
3000
+ 5,
3001
+ 3,
3002
+ // Blake1, unused in others
3003
+ 11,
3004
+ 8,
3005
+ 12,
3006
+ 0,
3007
+ 5,
3008
+ 2,
3009
+ 15,
3010
+ 13,
3011
+ 10,
3012
+ 14,
3013
+ 3,
3014
+ 6,
3015
+ 7,
3016
+ 1,
3017
+ 9,
3018
+ 4,
3019
+ 7,
3020
+ 9,
3021
+ 3,
3022
+ 1,
3023
+ 13,
3024
+ 12,
3025
+ 11,
3026
+ 14,
3027
+ 2,
3028
+ 6,
3029
+ 5,
3030
+ 10,
3031
+ 4,
3032
+ 0,
3033
+ 15,
3034
+ 8,
3035
+ 9,
3036
+ 0,
3037
+ 5,
3038
+ 7,
3039
+ 2,
3040
+ 4,
3041
+ 10,
3042
+ 15,
3043
+ 14,
3044
+ 1,
3045
+ 11,
3046
+ 12,
3047
+ 6,
3048
+ 8,
3049
+ 3,
3050
+ 13,
3051
+ 2,
3052
+ 12,
3053
+ 6,
3054
+ 10,
3055
+ 0,
3056
+ 11,
3057
+ 8,
3058
+ 3,
3059
+ 4,
3060
+ 13,
3061
+ 7,
3062
+ 5,
3063
+ 15,
3064
+ 14,
3065
+ 1,
3066
+ 9
3067
+ ]);
3068
+
3069
+ // node_modules/@noble/hashes/esm/blake2.js
3070
+ var B2B_IV = /* @__PURE__ */ Uint32Array.from([
3071
+ 4089235720,
3072
+ 1779033703,
3073
+ 2227873595,
3074
+ 3144134277,
3075
+ 4271175723,
3076
+ 1013904242,
3077
+ 1595750129,
3078
+ 2773480762,
3079
+ 2917565137,
3080
+ 1359893119,
3081
+ 725511199,
3082
+ 2600822924,
3083
+ 4215389547,
3084
+ 528734635,
3085
+ 327033209,
3086
+ 1541459225
3087
+ ]);
3088
+ var BBUF = /* @__PURE__ */ new Uint32Array(32);
3089
+ function G1b(a, b, c, d, msg, x) {
3090
+ const Xl = msg[x], Xh = msg[x + 1];
3091
+ let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1];
3092
+ let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1];
3093
+ let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1];
3094
+ let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1];
3095
+ let ll = add3L(Al, Bl, Xl);
3096
+ Ah = add3H(ll, Ah, Bh, Xh);
3097
+ Al = ll | 0;
3098
+ ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
3099
+ ({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) });
3100
+ ({ h: Ch, l: Cl } = add(Ch, Cl, Dh, Dl));
3101
+ ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
3102
+ ({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) });
3103
+ BBUF[2 * a] = Al, BBUF[2 * a + 1] = Ah;
3104
+ BBUF[2 * b] = Bl, BBUF[2 * b + 1] = Bh;
3105
+ BBUF[2 * c] = Cl, BBUF[2 * c + 1] = Ch;
3106
+ BBUF[2 * d] = Dl, BBUF[2 * d + 1] = Dh;
3107
+ }
3108
+ function G2b(a, b, c, d, msg, x) {
3109
+ const Xl = msg[x], Xh = msg[x + 1];
3110
+ let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1];
3111
+ let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1];
3112
+ let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1];
3113
+ let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1];
3114
+ let ll = add3L(Al, Bl, Xl);
3115
+ Ah = add3H(ll, Ah, Bh, Xh);
3116
+ Al = ll | 0;
3117
+ ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
3118
+ ({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) });
3119
+ ({ h: Ch, l: Cl } = add(Ch, Cl, Dh, Dl));
3120
+ ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
3121
+ ({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) });
3122
+ BBUF[2 * a] = Al, BBUF[2 * a + 1] = Ah;
3123
+ BBUF[2 * b] = Bl, BBUF[2 * b + 1] = Bh;
3124
+ BBUF[2 * c] = Cl, BBUF[2 * c + 1] = Ch;
3125
+ BBUF[2 * d] = Dl, BBUF[2 * d + 1] = Dh;
3126
+ }
3127
+ function checkBlake2Opts(outputLen, opts = {}, keyLen, saltLen, persLen) {
3128
+ anumber2(keyLen);
3129
+ if (outputLen < 0 || outputLen > keyLen)
3130
+ throw new Error("outputLen bigger than keyLen");
3131
+ const { key, salt, personalization } = opts;
3132
+ if (key !== void 0 && (key.length < 1 || key.length > keyLen))
3133
+ throw new Error("key length must be undefined or 1.." + keyLen);
3134
+ if (salt !== void 0 && salt.length !== saltLen)
3135
+ throw new Error("salt must be undefined or " + saltLen);
3136
+ if (personalization !== void 0 && personalization.length !== persLen)
3137
+ throw new Error("personalization must be undefined or " + persLen);
3138
+ }
3139
+ var BLAKE2 = class extends Hash2 {
3140
+ constructor(blockLen, outputLen) {
3141
+ super();
3142
+ this.finished = false;
3143
+ this.destroyed = false;
3144
+ this.length = 0;
3145
+ this.pos = 0;
3146
+ anumber2(blockLen);
3147
+ anumber2(outputLen);
3148
+ this.blockLen = blockLen;
3149
+ this.outputLen = outputLen;
3150
+ this.buffer = new Uint8Array(blockLen);
3151
+ this.buffer32 = u322(this.buffer);
3152
+ }
3153
+ update(data) {
3154
+ aexists2(this);
3155
+ data = toBytes2(data);
3156
+ abytes2(data);
3157
+ const { blockLen, buffer, buffer32 } = this;
3158
+ const len = data.length;
3159
+ const offset = data.byteOffset;
3160
+ const buf = data.buffer;
3161
+ for (let pos = 0; pos < len; ) {
3162
+ if (this.pos === blockLen) {
3163
+ swap32IfBE(buffer32);
3164
+ this.compress(buffer32, 0, false);
3165
+ swap32IfBE(buffer32);
3166
+ this.pos = 0;
3167
+ }
3168
+ const take = Math.min(blockLen - this.pos, len - pos);
3169
+ const dataOffset = offset + pos;
3170
+ if (take === blockLen && !(dataOffset % 4) && pos + take < len) {
3171
+ const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4));
3172
+ swap32IfBE(data32);
3173
+ for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {
3174
+ this.length += blockLen;
3175
+ this.compress(data32, pos32, false);
3176
+ }
3177
+ swap32IfBE(data32);
3178
+ continue;
3179
+ }
3180
+ buffer.set(data.subarray(pos, pos + take), this.pos);
3181
+ this.pos += take;
3182
+ this.length += take;
3183
+ pos += take;
3184
+ }
3185
+ return this;
3186
+ }
3187
+ digestInto(out) {
3188
+ aexists2(this);
3189
+ aoutput2(out, this);
3190
+ const { pos, buffer32 } = this;
3191
+ this.finished = true;
3192
+ clean2(this.buffer.subarray(pos));
3193
+ swap32IfBE(buffer32);
3194
+ this.compress(buffer32, 0, true);
3195
+ swap32IfBE(buffer32);
3196
+ const out32 = u322(out);
3197
+ this.get().forEach((v, i) => out32[i] = swap8IfBE(v));
3198
+ }
3199
+ digest() {
3200
+ const { buffer, outputLen } = this;
3201
+ this.digestInto(buffer);
3202
+ const res = buffer.slice(0, outputLen);
3203
+ this.destroy();
3204
+ return res;
3205
+ }
3206
+ _cloneInto(to) {
3207
+ const { buffer, length, finished, destroyed, outputLen, pos } = this;
3208
+ to || (to = new this.constructor({ dkLen: outputLen }));
3209
+ to.set(...this.get());
3210
+ to.buffer.set(buffer);
3211
+ to.destroyed = destroyed;
3212
+ to.finished = finished;
3213
+ to.length = length;
3214
+ to.pos = pos;
3215
+ to.outputLen = outputLen;
3216
+ return to;
3217
+ }
3218
+ clone() {
3219
+ return this._cloneInto();
3220
+ }
3221
+ };
3222
+ var BLAKE2b = class extends BLAKE2 {
3223
+ constructor(opts = {}) {
3224
+ const olen = opts.dkLen === void 0 ? 64 : opts.dkLen;
3225
+ super(128, olen);
3226
+ this.v0l = B2B_IV[0] | 0;
3227
+ this.v0h = B2B_IV[1] | 0;
3228
+ this.v1l = B2B_IV[2] | 0;
3229
+ this.v1h = B2B_IV[3] | 0;
3230
+ this.v2l = B2B_IV[4] | 0;
3231
+ this.v2h = B2B_IV[5] | 0;
3232
+ this.v3l = B2B_IV[6] | 0;
3233
+ this.v3h = B2B_IV[7] | 0;
3234
+ this.v4l = B2B_IV[8] | 0;
3235
+ this.v4h = B2B_IV[9] | 0;
3236
+ this.v5l = B2B_IV[10] | 0;
3237
+ this.v5h = B2B_IV[11] | 0;
3238
+ this.v6l = B2B_IV[12] | 0;
3239
+ this.v6h = B2B_IV[13] | 0;
3240
+ this.v7l = B2B_IV[14] | 0;
3241
+ this.v7h = B2B_IV[15] | 0;
3242
+ checkBlake2Opts(olen, opts, 64, 16, 16);
3243
+ let { key, personalization, salt } = opts;
3244
+ let keyLength = 0;
3245
+ if (key !== void 0) {
3246
+ key = toBytes2(key);
3247
+ keyLength = key.length;
3248
+ }
3249
+ this.v0l ^= this.outputLen | keyLength << 8 | 1 << 16 | 1 << 24;
3250
+ if (salt !== void 0) {
3251
+ salt = toBytes2(salt);
3252
+ const slt = u322(salt);
3253
+ this.v4l ^= swap8IfBE(slt[0]);
3254
+ this.v4h ^= swap8IfBE(slt[1]);
3255
+ this.v5l ^= swap8IfBE(slt[2]);
3256
+ this.v5h ^= swap8IfBE(slt[3]);
3257
+ }
3258
+ if (personalization !== void 0) {
3259
+ personalization = toBytes2(personalization);
3260
+ const pers = u322(personalization);
3261
+ this.v6l ^= swap8IfBE(pers[0]);
3262
+ this.v6h ^= swap8IfBE(pers[1]);
3263
+ this.v7l ^= swap8IfBE(pers[2]);
3264
+ this.v7h ^= swap8IfBE(pers[3]);
3265
+ }
3266
+ if (key !== void 0) {
3267
+ const tmp = new Uint8Array(this.blockLen);
3268
+ tmp.set(key);
3269
+ this.update(tmp);
3270
+ }
3271
+ }
3272
+ // prettier-ignore
3273
+ get() {
3274
+ let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;
3275
+ return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h];
3276
+ }
3277
+ // prettier-ignore
3278
+ set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) {
3279
+ this.v0l = v0l | 0;
3280
+ this.v0h = v0h | 0;
3281
+ this.v1l = v1l | 0;
3282
+ this.v1h = v1h | 0;
3283
+ this.v2l = v2l | 0;
3284
+ this.v2h = v2h | 0;
3285
+ this.v3l = v3l | 0;
3286
+ this.v3h = v3h | 0;
3287
+ this.v4l = v4l | 0;
3288
+ this.v4h = v4h | 0;
3289
+ this.v5l = v5l | 0;
3290
+ this.v5h = v5h | 0;
3291
+ this.v6l = v6l | 0;
3292
+ this.v6h = v6h | 0;
3293
+ this.v7l = v7l | 0;
3294
+ this.v7h = v7h | 0;
3295
+ }
3296
+ compress(msg, offset, isLast) {
3297
+ this.get().forEach((v, i) => BBUF[i] = v);
3298
+ BBUF.set(B2B_IV, 16);
3299
+ let { h, l } = fromBig(BigInt(this.length));
3300
+ BBUF[24] = B2B_IV[8] ^ l;
3301
+ BBUF[25] = B2B_IV[9] ^ h;
3302
+ if (isLast) {
3303
+ BBUF[28] = ~BBUF[28];
3304
+ BBUF[29] = ~BBUF[29];
3305
+ }
3306
+ let j = 0;
3307
+ const s = BSIGMA;
3308
+ for (let i = 0; i < 12; i++) {
3309
+ G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]);
3310
+ G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]);
3311
+ G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]);
3312
+ G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]);
3313
+ G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]);
3314
+ G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]);
3315
+ G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]);
3316
+ G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]);
3317
+ G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]);
3318
+ G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]);
3319
+ G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]);
3320
+ G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]);
3321
+ G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]);
3322
+ G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]);
3323
+ G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]);
3324
+ G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]);
3325
+ }
3326
+ this.v0l ^= BBUF[0] ^ BBUF[16];
3327
+ this.v0h ^= BBUF[1] ^ BBUF[17];
3328
+ this.v1l ^= BBUF[2] ^ BBUF[18];
3329
+ this.v1h ^= BBUF[3] ^ BBUF[19];
3330
+ this.v2l ^= BBUF[4] ^ BBUF[20];
3331
+ this.v2h ^= BBUF[5] ^ BBUF[21];
3332
+ this.v3l ^= BBUF[6] ^ BBUF[22];
3333
+ this.v3h ^= BBUF[7] ^ BBUF[23];
3334
+ this.v4l ^= BBUF[8] ^ BBUF[24];
3335
+ this.v4h ^= BBUF[9] ^ BBUF[25];
3336
+ this.v5l ^= BBUF[10] ^ BBUF[26];
3337
+ this.v5h ^= BBUF[11] ^ BBUF[27];
3338
+ this.v6l ^= BBUF[12] ^ BBUF[28];
3339
+ this.v6h ^= BBUF[13] ^ BBUF[29];
3340
+ this.v7l ^= BBUF[14] ^ BBUF[30];
3341
+ this.v7h ^= BBUF[15] ^ BBUF[31];
3342
+ clean2(BBUF);
3343
+ }
3344
+ destroy() {
3345
+ this.destroyed = true;
3346
+ clean2(this.buffer32);
3347
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
3348
+ }
3349
+ };
3350
+ var blake2b = /* @__PURE__ */ createOptHasher((opts) => new BLAKE2b(opts));
3351
+
3352
+ // node_modules/@noble/hashes/esm/argon2.js
3353
+ var AT = { Argond2d: 0, Argon2i: 1, Argon2id: 2 };
3354
+ var ARGON2_SYNC_POINTS = 4;
3355
+ var abytesOrZero = (buf) => {
3356
+ if (buf === void 0)
3357
+ return Uint8Array.of();
3358
+ return kdfInputToBytes(buf);
3359
+ };
3360
+ function mul(a, b) {
3361
+ const aL = a & 65535;
3362
+ const aH = a >>> 16;
3363
+ const bL = b & 65535;
3364
+ const bH = b >>> 16;
3365
+ const ll = Math.imul(aL, bL);
3366
+ const hl = Math.imul(aH, bL);
3367
+ const lh = Math.imul(aL, bH);
3368
+ const hh = Math.imul(aH, bH);
3369
+ const carry = (ll >>> 16) + (hl & 65535) + lh;
3370
+ const high = hh + (hl >>> 16) + (carry >>> 16) | 0;
3371
+ const low = carry << 16 | ll & 65535;
3372
+ return { h: high, l: low };
3373
+ }
3374
+ function mul2(a, b) {
3375
+ const { h, l } = mul(a, b);
3376
+ return { h: (h << 1 | l >>> 31) & 4294967295, l: l << 1 & 4294967295 };
3377
+ }
3378
+ function blamka(Ah, Al, Bh, Bl) {
3379
+ const { h: Ch, l: Cl } = mul2(Al, Bl);
3380
+ const Rll = add3L(Al, Bl, Cl);
3381
+ return { h: add3H(Rll, Ah, Bh, Ch), l: Rll | 0 };
3382
+ }
3383
+ var A2_BUF = new Uint32Array(256);
3384
+ function G(a, b, c, d) {
3385
+ let Al = A2_BUF[2 * a], Ah = A2_BUF[2 * a + 1];
3386
+ let Bl = A2_BUF[2 * b], Bh = A2_BUF[2 * b + 1];
3387
+ let Cl = A2_BUF[2 * c], Ch = A2_BUF[2 * c + 1];
3388
+ let Dl = A2_BUF[2 * d], Dh = A2_BUF[2 * d + 1];
3389
+ ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl));
3390
+ ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
3391
+ ({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) });
3392
+ ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl));
3393
+ ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
3394
+ ({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) });
3395
+ ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl));
3396
+ ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
3397
+ ({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) });
3398
+ ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl));
3399
+ ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
3400
+ ({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) });
3401
+ A2_BUF[2 * a] = Al, A2_BUF[2 * a + 1] = Ah;
3402
+ A2_BUF[2 * b] = Bl, A2_BUF[2 * b + 1] = Bh;
3403
+ A2_BUF[2 * c] = Cl, A2_BUF[2 * c + 1] = Ch;
3404
+ A2_BUF[2 * d] = Dl, A2_BUF[2 * d + 1] = Dh;
3405
+ }
3406
+ function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) {
3407
+ G(v00, v04, v08, v12);
3408
+ G(v01, v05, v09, v13);
3409
+ G(v02, v06, v10, v14);
3410
+ G(v03, v07, v11, v15);
3411
+ G(v00, v05, v10, v15);
3412
+ G(v01, v06, v11, v12);
3413
+ G(v02, v07, v08, v13);
3414
+ G(v03, v04, v09, v14);
3415
+ }
3416
+ function block(x, xPos, yPos, outPos, needXor) {
3417
+ for (let i = 0; i < 256; i++)
3418
+ A2_BUF[i] = x[xPos + i] ^ x[yPos + i];
3419
+ for (let i = 0; i < 128; i += 16) {
3420
+ P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15);
3421
+ }
3422
+ for (let i = 0; i < 16; i += 2) {
3423
+ P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113);
3424
+ }
3425
+ if (needXor)
3426
+ for (let i = 0; i < 256; i++)
3427
+ x[outPos + i] ^= A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i];
3428
+ else
3429
+ for (let i = 0; i < 256; i++)
3430
+ x[outPos + i] = A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i];
3431
+ clean2(A2_BUF);
3432
+ }
3433
+ function Hp(A, dkLen) {
3434
+ const A8 = u8(A);
3435
+ const T = new Uint32Array(1);
3436
+ const T8 = u8(T);
3437
+ T[0] = dkLen;
3438
+ if (dkLen <= 64)
3439
+ return blake2b.create({ dkLen }).update(T8).update(A8).digest();
3440
+ const out = new Uint8Array(dkLen);
3441
+ let V = blake2b.create({}).update(T8).update(A8).digest();
3442
+ let pos = 0;
3443
+ out.set(V.subarray(0, 32));
3444
+ pos += 32;
3445
+ for (; dkLen - pos > 64; pos += 32) {
3446
+ const Vh = blake2b.create({}).update(V);
3447
+ Vh.digestInto(V);
3448
+ Vh.destroy();
3449
+ out.set(V.subarray(0, 32), pos);
3450
+ }
3451
+ out.set(blake2b(V, { dkLen: dkLen - pos }), pos);
3452
+ clean2(V, T);
3453
+ return u322(out);
3454
+ }
3455
+ function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) {
3456
+ let area;
3457
+ if (r === 0) {
3458
+ if (s === 0)
3459
+ area = index - 1;
3460
+ else if (sameLane)
3461
+ area = s * segmentLen + index - 1;
3462
+ else
3463
+ area = s * segmentLen + (index == 0 ? -1 : 0);
3464
+ } else if (sameLane)
3465
+ area = laneLen - segmentLen + index - 1;
3466
+ else
3467
+ area = laneLen - segmentLen + (index == 0 ? -1 : 0);
3468
+ const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0;
3469
+ const rel = area - 1 - mul(area, mul(randL, randL).h).h;
3470
+ return (startPos + rel) % laneLen;
3471
+ }
3472
+ var maxUint32 = Math.pow(2, 32);
3473
+ function isU32(num) {
3474
+ return Number.isSafeInteger(num) && num >= 0 && num < maxUint32;
3475
+ }
3476
+ function argon2Opts(opts) {
3477
+ const merged = {
3478
+ version: 19,
3479
+ dkLen: 32,
3480
+ maxmem: maxUint32 - 1,
3481
+ asyncTick: 10
3482
+ };
3483
+ for (let [k, v] of Object.entries(opts))
3484
+ if (v != null)
3485
+ merged[k] = v;
3486
+ const { dkLen, p, m, t, version, onProgress } = merged;
3487
+ if (!isU32(dkLen) || dkLen < 4)
3488
+ throw new Error("dkLen should be at least 4 bytes");
3489
+ if (!isU32(p) || p < 1 || p >= Math.pow(2, 24))
3490
+ throw new Error("p should be 1 <= p < 2^24");
3491
+ if (!isU32(m))
3492
+ throw new Error("m should be 0 <= m < 2^32");
3493
+ if (!isU32(t) || t < 1)
3494
+ throw new Error("t (iterations) should be 1 <= t < 2^32");
3495
+ if (onProgress !== void 0 && typeof onProgress !== "function")
3496
+ throw new Error("progressCb should be function");
3497
+ if (!isU32(m) || m < 8 * p)
3498
+ throw new Error("memory should be at least 8*p bytes");
3499
+ if (version !== 16 && version !== 19)
3500
+ throw new Error("unknown version=" + version);
3501
+ return merged;
3502
+ }
3503
+ function argon2Init(password, salt, type, opts) {
3504
+ password = kdfInputToBytes(password);
3505
+ salt = kdfInputToBytes(salt);
3506
+ abytes2(password);
3507
+ abytes2(salt);
3508
+ if (!isU32(password.length))
3509
+ throw new Error("password should be less than 4 GB");
3510
+ if (!isU32(salt.length) || salt.length < 8)
3511
+ throw new Error("salt should be at least 8 bytes and less than 4 GB");
3512
+ if (!Object.values(AT).includes(type))
3513
+ throw new Error("invalid type");
3514
+ let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress, asyncTick } = argon2Opts(opts);
3515
+ key = abytesOrZero(key);
3516
+ personalization = abytesOrZero(personalization);
3517
+ const h = blake2b.create({});
3518
+ const BUF = new Uint32Array(1);
3519
+ const BUF8 = u8(BUF);
3520
+ for (let item of [p, dkLen, m, t, version, type]) {
3521
+ BUF[0] = item;
3522
+ h.update(BUF8);
3523
+ }
3524
+ for (let i of [password, salt, key, personalization]) {
3525
+ BUF[0] = i.length;
3526
+ h.update(BUF8).update(i);
3527
+ }
3528
+ const H0 = new Uint32Array(18);
3529
+ const H0_8 = u8(H0);
3530
+ h.digestInto(H0_8);
3531
+ const lanes = p;
3532
+ const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p));
3533
+ const laneLen = Math.floor(mP / p);
3534
+ const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS);
3535
+ const memUsed = mP * 256;
3536
+ if (!isU32(maxmem) || memUsed > maxmem)
3537
+ throw new Error("mem should be less than 2**32, got: maxmem=" + maxmem + ", memused=" + memUsed);
3538
+ const B = new Uint32Array(memUsed);
3539
+ for (let l = 0; l < p; l++) {
3540
+ const i = 256 * laneLen * l;
3541
+ H0[17] = l;
3542
+ H0[16] = 0;
3543
+ B.set(Hp(H0, 1024), i);
3544
+ H0[16] = 1;
3545
+ B.set(Hp(H0, 1024), i + 256);
3546
+ }
3547
+ let perBlock = () => {
3548
+ };
3549
+ if (onProgress) {
3550
+ const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen;
3551
+ const callbackPer = Math.max(Math.floor(totalBlock / 1e4), 1);
3552
+ let blockCnt = 0;
3553
+ perBlock = () => {
3554
+ blockCnt++;
3555
+ if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock))
3556
+ onProgress(blockCnt / totalBlock);
3557
+ };
3558
+ }
3559
+ clean2(BUF, H0);
3560
+ return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock, asyncTick };
3561
+ }
3562
+ function argon2Output(B, p, laneLen, dkLen) {
3563
+ const B_final = new Uint32Array(256);
3564
+ for (let l = 0; l < p; l++)
3565
+ for (let j = 0; j < 256; j++)
3566
+ B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j];
3567
+ const res = u8(Hp(B_final, dkLen));
3568
+ clean2(B_final);
3569
+ return res;
3570
+ }
3571
+ function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) {
3572
+ if (offset % laneLen)
3573
+ prev = offset - 1;
3574
+ let randL, randH;
3575
+ if (dataIndependent) {
3576
+ let i128 = index % 128;
3577
+ if (i128 === 0) {
3578
+ address[256 + 12]++;
3579
+ block(address, 256, 2 * 256, 0, false);
3580
+ block(address, 0, 2 * 256, 0, false);
3581
+ }
3582
+ randL = address[2 * i128];
3583
+ randH = address[2 * i128 + 1];
3584
+ } else {
3585
+ const T = 256 * prev;
3586
+ randL = B[T];
3587
+ randH = B[T + 1];
3588
+ }
3589
+ const refLane = r === 0 && s === 0 ? l : randH % lanes;
3590
+ const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l);
3591
+ const refBlock = laneLen * refLane + refPos;
3592
+ block(B, 256 * prev, 256 * refBlock, offset * 256, needXor);
3593
+ }
3594
+ function argon2(type, password, salt, opts) {
3595
+ const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(password, salt, type, opts);
3596
+ const address = new Uint32Array(3 * 256);
3597
+ address[256 + 6] = mP;
3598
+ address[256 + 8] = t;
3599
+ address[256 + 10] = type;
3600
+ for (let r = 0; r < t; r++) {
3601
+ const needXor = r !== 0 && version === 19;
3602
+ address[256 + 0] = r;
3603
+ for (let s = 0; s < ARGON2_SYNC_POINTS; s++) {
3604
+ address[256 + 4] = s;
3605
+ const dataIndependent = type == AT.Argon2i || type == AT.Argon2id && r === 0 && s < 2;
3606
+ for (let l = 0; l < p; l++) {
3607
+ address[256 + 2] = l;
3608
+ address[256 + 12] = 0;
3609
+ let startPos = 0;
3610
+ if (r === 0 && s === 0) {
3611
+ startPos = 2;
3612
+ if (dataIndependent) {
3613
+ address[256 + 12]++;
3614
+ block(address, 256, 2 * 256, 0, false);
3615
+ block(address, 0, 2 * 256, 0, false);
3616
+ }
3617
+ }
3618
+ let offset = l * laneLen + s * segmentLen + startPos;
3619
+ let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1;
3620
+ for (let index = startPos; index < segmentLen; index++, offset++, prev++) {
3621
+ perBlock();
3622
+ processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor);
3623
+ }
3624
+ }
3625
+ }
3626
+ }
3627
+ clean2(address);
3628
+ return argon2Output(B, p, laneLen, dkLen);
3629
+ }
3630
+ var argon2id = (password, salt, opts) => argon2(AT.Argon2id, password, salt, opts);
3631
+
3632
+ // src/notes/store.ts
3633
+ var NoteStore = class {
3634
+ constructor(persist) {
3635
+ this.persist = persist;
3636
+ }
3637
+ header = null;
3638
+ body = null;
3639
+ key = null;
3640
+ async unlock(passphrase) {
3641
+ const blob = await this.persist.readBlob();
3642
+ if (!blob) {
3643
+ const salt2 = crypto.getRandomValues(new Uint8Array(16));
3644
+ const key2 = await argon2id(new TextEncoder().encode(passphrase), salt2, {
3645
+ m: 64 * 1024,
3646
+ t: 3,
3647
+ p: 1,
3648
+ dkLen: 32
3649
+ });
3650
+ const header = {
3651
+ v: 1,
3652
+ createdAt: Date.now(),
3653
+ kdf: { algo: "argon2id", params: { m: 64 * 1024, t: 3, p: 1, saltB64: Buffer.from(salt2).toString("base64") } },
3654
+ seq: 1
3655
+ };
3656
+ const body2 = {
3657
+ notes: [],
3658
+ nfs: [],
3659
+ pendingNfs: [],
3660
+ tombstones: [],
3661
+ pendingLinks: [],
3662
+ outByIntent: {}
3663
+ };
3664
+ const enc = encryptBlob(key2, body2, header);
3665
+ await this.persist.writeBlob(enc);
3666
+ this.header = enc.header;
3667
+ this.body = body2;
3668
+ this.key = key2;
3669
+ return;
3670
+ }
3671
+ const { m, t, p, saltB64 } = blob.header.kdf.params;
3672
+ const salt = Buffer.from(saltB64, "base64");
3673
+ const key = await argon2id(new TextEncoder().encode(passphrase), salt, {
3674
+ m,
3675
+ t,
3676
+ p,
3677
+ dkLen: 32
3678
+ });
3679
+ const body = decryptBlob(key, blob);
3680
+ if (!body.pendingLinks) body.pendingLinks = [];
3681
+ if (!body.outByIntent) body.outByIntent = {};
3682
+ this.header = blob.header;
3683
+ this.body = body;
3684
+ this.key = key;
3685
+ }
3686
+ async save() {
3687
+ if (!this.key || !this.header || !this.body) throw new Error("locked");
3688
+ this.header = { ...this.header, seq: this.header.seq + 1 };
3689
+ const enc = encryptBlob(this.key, this.body, this.header);
3690
+ await this.persist.writeBlob(enc);
3691
+ this.header = enc.header;
3692
+ }
3693
+ getBody() {
3694
+ if (!this.body) throw new Error("vault is locked");
3695
+ return this.body;
3696
+ }
3697
+ listSpendable(filter) {
3698
+ const notes = this.getBody().notes.filter((n) => n.status === "SPENDABLE");
3699
+ return filter?.assetId ? notes.filter((n) => n.assetId === filter.assetId) : notes;
3700
+ }
3701
+ getByCommitment(c) {
3702
+ return this.getBody().notes.find((n) => n.commitment === c);
3703
+ }
3704
+ // ----- Planner hooks (call once per plan) -----
3705
+ /** Link an input NF to the input note we’re spending, for auto-SPENT later. */
3706
+ async linkPendingSpend(params) {
3707
+ await this.withTxn((b) => {
3708
+ if (!b.pendingLinks) b.pendingLinks = [];
3709
+ if (!b.pendingNfs) b.pendingNfs = [];
3710
+ const now = Date.now();
3711
+ if (!b.pendingLinks.find((x) => x.nf === params.nf)) {
3712
+ b.pendingLinks.push({ ...params, createdAt: now });
3713
+ }
3714
+ if (!b.pendingNfs.includes(params.nf)) b.pendingNfs.push(params.nf);
3715
+ });
3716
+ }
3717
+ /** Register the output commitments (receive+change) we expect for this intent. */
3718
+ async registerExpectedOutputs(intentId, commitments) {
3719
+ await this.withTxn((b) => {
3720
+ if (!b.outByIntent) b.outByIntent = {};
3721
+ const set = /* @__PURE__ */ new Set([...b.outByIntent[intentId] ?? [], ...commitments]);
3722
+ b.outByIntent[intentId] = [...set];
3723
+ });
3724
+ }
3725
+ async clearExpectedOutputs(intentId) {
3726
+ await this.withTxn((b) => {
3727
+ if (b.outByIntent) delete b.outByIntent[intentId];
3728
+ });
3729
+ }
3730
+ // ----- Notes lifecycle -----
3731
+ /** Stage notes (outputs you locally know you will receive). */
3732
+ async addStagedNotes(notes) {
3733
+ await this.withTxn((b) => {
3734
+ for (const n of notes) {
3735
+ const now = Date.now();
3736
+ const note = {
3737
+ ...n,
3738
+ status: "STAGED",
3739
+ createdAt: n.createdAt ?? now,
3740
+ updatedAt: now
3741
+ };
3742
+ if (!b.notes.find((x) => x.commitment === note.commitment)) {
3743
+ b.notes.push(note);
3744
+ }
3745
+ }
3746
+ });
3747
+ }
3748
+ async listStagedNotes() {
3749
+ const b = this.getBody();
3750
+ return b.notes.filter((n) => n.status === "STAGED");
3751
+ }
3752
+ /** Flip to SPENDABLE once inclusion path is verified. */
3753
+ async markSpendable(commitment, index, root) {
3754
+ await this.withTxn((b) => {
3755
+ const n = b.notes.find((x) => x.commitment === commitment);
3756
+ if (!n) return;
3757
+ n.status = "SPENDABLE";
3758
+ n.index = index;
3759
+ n.root = root;
3760
+ n.rootAtInclusion = root;
3761
+ n.includedAt = n.includedAt ?? Date.now();
3762
+ n.updatedAt = Date.now();
3763
+ });
3764
+ }
3765
+ /** Record observed nullifiers; auto-mark the linked input note SPENT. */
3766
+ async recordSpents(spents) {
3767
+ await this.withTxn((b) => {
3768
+ for (const s of spents) {
3769
+ if (!b.nfs.find((x) => x.nf === s.nf)) {
3770
+ const link = (b.pendingLinks ?? []).find((pl) => pl.nf === s.nf);
3771
+ const merged = { ...s, commitment: s.commitment ?? link?.commitment };
3772
+ b.nfs.push(merged);
3773
+ if (link?.commitment) {
3774
+ const n = b.notes.find((x) => x.commitment === link.commitment);
3775
+ if (n && n.status !== "SPENT") {
3776
+ n.status = "SPENT";
3777
+ n.updatedAt = Date.now();
3778
+ if (!b.tombstones.includes(n.commitment)) b.tombstones.push(n.commitment);
3779
+ }
3780
+ }
3781
+ }
3782
+ b.pendingNfs = (b.pendingNfs ?? []).filter((x) => x !== s.nf);
3783
+ if (b.pendingLinks) b.pendingLinks = b.pendingLinks.filter((x) => x.nf !== s.nf);
3784
+ }
3785
+ });
3786
+ }
3787
+ // Convenience for planners that don’t link (kept for back-compat)
3788
+ async markPending(nf) {
3789
+ const b = this.getBody();
3790
+ if (!b.pendingNfs.includes(nf)) b.pendingNfs.push(nf);
3791
+ await this.save();
3792
+ }
3793
+ async markSpent(commitment, nf, blockNumber) {
3794
+ const b = this.getBody();
3795
+ const n = b.notes.find((x) => x.commitment === commitment);
3796
+ if (n) {
3797
+ n.status = "SPENT";
3798
+ n.updatedAt = Date.now();
3799
+ }
3800
+ b.nfs.push({ nf, commitment, at: Date.now(), blockNumber });
3801
+ if (n && !b.tombstones.includes(commitment)) b.tombstones.push(commitment);
3802
+ b.pendingNfs = b.pendingNfs.filter((x) => x !== nf);
3803
+ if (b.pendingLinks) b.pendingLinks = b.pendingLinks.filter((x) => x.nf !== nf);
3804
+ await this.save();
3805
+ }
3806
+ // Reactor cursor helpers
3807
+ async setLastProcessedBlock(block2) {
3808
+ if (!this.header) throw new Error("vault is locked");
3809
+ this.header = { ...this.header, lastProcessedBlock: block2 };
3810
+ await this.save();
3811
+ }
3812
+ getLastProcessedBlock() {
3813
+ return this.header?.lastProcessedBlock;
3814
+ }
3815
+ // Export / import
3816
+ async exportEncrypted() {
3817
+ const blob = await this.persist.readBlob();
3818
+ if (!blob) throw new Error("no vault");
3819
+ return blob;
3820
+ }
3821
+ async importEncrypted(blob) {
3822
+ const cur = await this.persist.readBlob();
3823
+ if (cur && blob.header.seq < cur.header.seq) throw new Error("rollback detected");
3824
+ await this.persist.writeBlob(blob);
3825
+ }
3826
+ // Best-effort dedupe on startup
3827
+ dedupe() {
3828
+ const b = this.getBody();
3829
+ const seen = /* @__PURE__ */ new Set();
3830
+ b.notes = b.notes.filter(
3831
+ (n) => !seen.has(n.commitment) && (seen.add(n.commitment), true)
3832
+ );
3833
+ if (!b.pendingLinks) b.pendingLinks = [];
3834
+ if (!b.outByIntent) b.outByIntent = {};
3835
+ }
3836
+ /** Atomically mutate & persist. */
3837
+ async withTxn(mutate) {
3838
+ const b = this.getBody();
3839
+ mutate(b);
3840
+ await this.save();
3841
+ }
3842
+ };
3843
+
3844
+ // src/notes/receiver.ts
3845
+ var Receiver = class {
3846
+ constructor(store, chain) {
3847
+ this.store = store;
3848
+ this.chain = chain;
3849
+ }
3850
+ async stageDepositNote(note) {
3851
+ await this.store.addStagedNotes([{ ...note, status: "STAGED" }]);
3852
+ }
3853
+ async stageItOutNotes(notes) {
3854
+ await this.store.addStagedNotes(notes.map((n) => ({ ...n, status: "STAGED" })));
3855
+ }
3856
+ /** One-shot reconcile. Call from a small loop for “always-on”. */
3857
+ async reconcile(fromBlock) {
3858
+ const ev = await this.chain.getEvents(fromBlock);
3859
+ if (ev.spents.length) {
3860
+ await this.store.recordSpents(
3861
+ ev.spents.map((s) => ({ nf: s.nf, blockNumber: s.block, at: Date.now() }))
3862
+ );
3863
+ }
3864
+ const staged = await this.store.listStagedNotes();
3865
+ const includedNow = /* @__PURE__ */ new Set();
3866
+ if (staged.length) {
3867
+ const stagedByCommit = new Map(staged.map((s) => [s.commitment, s]));
3868
+ for (const batch of ev.leaves) {
3869
+ const root = batch.rootAfter ?? ev.newRoots.at(-1)?.root;
3870
+ if (!root) continue;
3871
+ if (!await this.chain.isKnownRoot(root)) continue;
3872
+ for (let i = 0; i < batch.leaves.length; i++) {
3873
+ const c = batch.leaves[i];
3874
+ if (!stagedByCommit.has(c)) continue;
3875
+ const index = batch.start + i;
3876
+ const { path, indices } = await this.chain.getPath(index, root);
3877
+ const ok = this.chain.verifyPath(c, index, root, path, indices);
3878
+ if (!ok) continue;
3879
+ await this.store.markSpendable(c, index, root);
3880
+ includedNow.add(c);
3881
+ stagedByCommit.delete(c);
3882
+ }
3883
+ }
3884
+ }
3885
+ const b = this.store["body"];
3886
+ if (b?.outByIntent) {
3887
+ for (const [intentId, expected] of Object.entries(b.outByIntent)) {
3888
+ if (expected.every((c) => includedNow.has(c))) {
3889
+ await this.store.clearExpectedOutputs(intentId);
3890
+ }
3891
+ }
3892
+ }
3893
+ const maxBlock = Math.max(
3894
+ 0,
3895
+ ...ev.newRoots.map((x) => x.block),
3896
+ ...ev.leaves.map((x) => x.block),
3897
+ ...ev.spents.map((x) => x.block)
3898
+ );
3899
+ if (maxBlock > 0) await this.store.setLastProcessedBlock(maxBlock);
3900
+ }
3901
+ };
3902
+
3903
+ // src/lib/client.ts
3904
+ import "dotenv/config";
3905
+ var RAW_PK = process.env.RELAYER_KEY;
3906
+ var PK = RAW_PK.startsWith("0x") ? RAW_PK : `0x${RAW_PK}`;
3907
+ if (PK.length !== 66) {
3908
+ throw new Error(
3909
+ `RELAYER_KEY must be 32-byte hex (0x + 64 hex chars). Got length=${PK.length}.`
3910
+ );
3911
+ }
3912
+ function toViemFromBlock(fb) {
3913
+ if (fb === void 0) return void 0;
3914
+ return typeof fb === "number" ? BigInt(fb) : fb;
3915
+ }
3916
+ function toReceiverFromBlock(fb) {
3917
+ if (fb === void 0) return void 0;
3918
+ return typeof fb === "bigint" ? Number(fb) : fb;
3919
+ }
3920
+
3921
+ // src/index.ts
3922
+ var N3SDK = class {
3923
+ env;
3924
+ /** GraphQL-backed info endpoints (historical/state) */
3925
+ info;
3926
+ /** WebSocket fanout (live streams) */
3927
+ subscriptions;
3928
+ /** Hyperliquid-aligned exchange actions */
3929
+ exchange;
3930
+ constructor(env2) {
3931
+ this.env = env2;
3932
+ this.info = {
3933
+ indicatives: makeIndicativesInfo(this.env),
3934
+ candles: makeCandlesInfo(this.env),
3935
+ depth: makeDepthInfo(this.env),
3936
+ trades: makeTradesInfo(this.env),
3937
+ batches: makeBatchesInfo(this.env)
3938
+ };
3939
+ this.subscriptions = {
3940
+ indicatives: makeIndicatives(this.env),
3941
+ candles: makeCandles(this.env),
3942
+ depth: makeDepth(this.env),
3943
+ trades: makeTrades(this.env),
3944
+ batches: makeBatches(this.env)
3945
+ };
3946
+ this.exchange = {
3947
+ order: submitOrder,
3948
+ orderAuto: submitOrderAuto,
3949
+ modify,
3950
+ cancel,
3951
+ batchOrder: batchOrders,
3952
+ batchModify,
3953
+ batchCancel,
3954
+ withdraw,
3955
+ withdrawAuto,
3956
+ depositHYPE,
3957
+ depositERC20
3958
+ };
3959
+ }
3960
+ // -------- Receiver sync loop (Merkle confirmations & NF tracking) --------
3961
+ startReceiverSync(store, clients, fromBlock) {
3962
+ const { pool } = getDomainEnv();
3963
+ const receiverFromBlock = (() => {
3964
+ const persisted = store.getLastProcessedBlock?.();
3965
+ if (typeof persisted === "number" && persisted > 0) return persisted;
3966
+ return toReceiverFromBlock(fromBlock);
3967
+ })();
3968
+ const chainAdapter = {
3969
+ getEvents: async (fbNum) => {
3970
+ const { publicClient } = clients;
3971
+ const from = toViemFromBlock(fbNum);
3972
+ const [newRootsLogs, leavesLogs, spentLogs] = await Promise.all([
3973
+ publicClient.getLogs({ address: pool, event: EV_NewRoot, fromBlock: from }).catch(() => []),
3974
+ publicClient.getLogs({ address: pool, event: EV_LeavesInserted, fromBlock: from }).catch(() => []),
3975
+ publicClient.getLogs({ address: pool, event: EV_Spent, fromBlock: from }).catch(() => [])
3976
+ ]);
3977
+ const newRoots = newRootsLogs.map((l) => ({
3978
+ root: l.args.root,
3979
+ block: Number(l.blockNumber ?? 0n)
3980
+ }));
3981
+ const leaves = leavesLogs.map((l) => ({
3982
+ start: Number(l.args.startIndex ?? 0),
3983
+ leaves: l.args.leaves ?? [],
3984
+ block: Number(l.blockNumber ?? 0n),
3985
+ rootAfter: void 0
3986
+ }));
3987
+ const spents = spentLogs.map((l) => ({
3988
+ nf: l.args.nf,
3989
+ block: Number(l.blockNumber ?? 0n)
3990
+ }));
3991
+ return { newRoots, leaves, spents };
3992
+ },
3993
+ getPath: async () => {
3994
+ throw new Error("getPath not provided \u2014 supply an indexer or pass a custom chain adapter to Receiver.");
3995
+ },
3996
+ isKnownRoot: async (root) => {
3997
+ const { publicClient } = clients;
3998
+ return await publicClient.readContract({
3999
+ address: pool,
4000
+ abi: PrivatePoolAbi,
4001
+ functionName: "isKnownRoot",
4002
+ args: [root]
4003
+ });
4004
+ }
4005
+ };
4006
+ const rx = new Receiver(store, chainAdapter);
4007
+ let stop = false;
4008
+ (async () => {
4009
+ let cursor = receiverFromBlock;
4010
+ while (!stop) {
4011
+ try {
4012
+ await rx.reconcile(typeof cursor === "number" ? cursor : void 0);
4013
+ const np = store.getLastProcessedBlock?.();
4014
+ if (typeof np === "number" && np > 0) cursor = np;
4015
+ } catch {
4016
+ }
4017
+ await new Promise((r) => setTimeout(r, 3e3));
4018
+ }
4019
+ })();
4020
+ return () => {
4021
+ stop = true;
4022
+ };
4023
+ }
4024
+ };
4025
+ var index_default = N3SDK;
4026
+ export {
4027
+ exchange_exports as Exchange,
4028
+ info_exports as Info,
4029
+ N3SDK,
4030
+ NoteStore,
4031
+ Receiver,
4032
+ subscription_exports as Subscription,
4033
+ Topics,
4034
+ index_default as default,
4035
+ toReceiverFromBlock,
4036
+ toViemFromBlock
4037
+ };
4038
+ /*! Bundled license information:
4039
+
4040
+ @noble/ciphers/esm/utils.js:
4041
+ (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
4042
+
4043
+ @noble/hashes/esm/utils.js:
4044
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
4045
+ */
4046
+ //# sourceMappingURL=index.js.map