@cashu/coco-expo-sqlite 1.0.0-rc.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,2204 @@
1
+ import { normalizeMintUrl } from "@cashu/coco-core";
2
+
3
+ //#region src/db.ts
4
+ /**
5
+ * Wrapper around expo-sqlite Database providing transaction management.
6
+ *
7
+ * Transaction behavior:
8
+ * - Nested transactions within the same scope are "rolled up" - they reuse the parent transaction
9
+ * - Concurrent transactions from different scopes are queued and executed serially
10
+ * - Each top-level transaction gets a unique scope token for identification
11
+ */
12
+ var ExpoSqliteDb = class ExpoSqliteDb {
13
+ root;
14
+ /** Unique identifier for this instance's transaction scope (null for root instances) */
15
+ scopeToken;
16
+ constructor(optionsOrRoot, scopeToken = null) {
17
+ if ("database" in optionsOrRoot) {
18
+ this.root = {
19
+ db: optionsOrRoot.database,
20
+ transactionQueue: Promise.resolve(),
21
+ currentScope: null,
22
+ scopeDepth: 0
23
+ };
24
+ this.scopeToken = null;
25
+ } else {
26
+ this.root = optionsOrRoot;
27
+ this.scopeToken = scopeToken;
28
+ }
29
+ }
30
+ get raw() {
31
+ return this.root.db;
32
+ }
33
+ async exec(sql) {
34
+ await this.root.db.execAsync(sql);
35
+ }
36
+ async run(sql, params = []) {
37
+ const result = await this.root.db.runAsync(sql, ...params ?? []);
38
+ return {
39
+ lastID: result.lastInsertRowId ?? 0,
40
+ changes: result.changes ?? 0
41
+ };
42
+ }
43
+ async get(sql, params = []) {
44
+ return await this.root.db.getFirstAsync(sql, ...params ?? []) ?? void 0;
45
+ }
46
+ async all(sql, params = []) {
47
+ return await this.root.db.getAllAsync(sql, ...params ?? []) ?? [];
48
+ }
49
+ /**
50
+ * Execute a function within a database transaction.
51
+ *
52
+ * Transaction Semantics:
53
+ *
54
+ * 1. NESTED TRANSACTIONS (same scope):
55
+ * When transaction() is called from within an active transaction using the same
56
+ * scoped ExpoSqliteDb instance, the inner call is treated as part of the outer transaction.
57
+ * No new BEGIN/COMMIT is issued - the transaction is "rolled up".
58
+ *
59
+ * 2. CONCURRENT TRANSACTIONS (different scopes):
60
+ * When transaction() is called while another transaction is active but from a
61
+ * different scope (e.g., parallel calls), the new transaction waits in a queue.
62
+ * Transactions execute serially to prevent "cannot start a transaction within a transaction".
63
+ *
64
+ * 3. ERROR HANDLING:
65
+ * If the transaction function throws an error, ROLLBACK is executed and the error
66
+ * is re-thrown. The transaction queue is properly released even on error, allowing
67
+ * subsequent transactions to proceed.
68
+ *
69
+ * @param fn - Function to execute within the transaction, receives a scoped ExpoSqliteDb instance
70
+ * @returns Promise that resolves with the return value of fn
71
+ * @throws Re-throws any error from fn after rolling back the transaction
72
+ */
73
+ async transaction(fn) {
74
+ const { root } = this;
75
+ if (this.scopeToken && root.currentScope === this.scopeToken) {
76
+ root.scopeDepth++;
77
+ try {
78
+ return await fn(this);
79
+ } finally {
80
+ root.scopeDepth--;
81
+ }
82
+ }
83
+ const scopeToken = Symbol("expo-sqlite-transaction");
84
+ const scopedDb = new ExpoSqliteDb(root, scopeToken);
85
+ const previousTransaction = root.transactionQueue;
86
+ let resolver;
87
+ root.transactionQueue = new Promise((resolve) => {
88
+ resolver = resolve;
89
+ });
90
+ try {
91
+ await previousTransaction;
92
+ const dbAny = root.db;
93
+ root.currentScope = scopeToken;
94
+ root.scopeDepth = 1;
95
+ if (typeof dbAny.withTransactionAsync === "function") {
96
+ let result;
97
+ await dbAny.withTransactionAsync(async () => {
98
+ result = await fn(scopedDb);
99
+ });
100
+ return result;
101
+ }
102
+ await dbAny.execAsync("BEGIN");
103
+ try {
104
+ const res = await fn(scopedDb);
105
+ await dbAny.execAsync("COMMIT");
106
+ return res;
107
+ } catch (error) {
108
+ try {
109
+ await dbAny.execAsync("ROLLBACK");
110
+ } catch {}
111
+ throw error;
112
+ }
113
+ } finally {
114
+ root.scopeDepth = 0;
115
+ root.currentScope = null;
116
+ resolver();
117
+ }
118
+ }
119
+ };
120
+ function getUnixTimeSeconds() {
121
+ return Math.floor(Date.now() / 1e3);
122
+ }
123
+
124
+ //#endregion
125
+ //#region src/schema.ts
126
+ const MIGRATIONS = [
127
+ {
128
+ id: "001_initial",
129
+ sql: `
130
+ CREATE TABLE IF NOT EXISTS coco_cashu_mints (
131
+ mintUrl TEXT PRIMARY KEY NOT NULL,
132
+ name TEXT NOT NULL,
133
+ mintInfo TEXT NOT NULL,
134
+ createdAt INTEGER NOT NULL,
135
+ updatedAt INTEGER NOT NULL
136
+ );
137
+
138
+ CREATE TABLE IF NOT EXISTS coco_cashu_keysets (
139
+ mintUrl TEXT NOT NULL,
140
+ id TEXT NOT NULL,
141
+ keypairs TEXT NOT NULL,
142
+ active INTEGER NOT NULL,
143
+ feePpk INTEGER NOT NULL,
144
+ updatedAt INTEGER NOT NULL,
145
+ PRIMARY KEY (mintUrl, id)
146
+ );
147
+
148
+ CREATE TABLE IF NOT EXISTS coco_cashu_counters (
149
+ mintUrl TEXT NOT NULL,
150
+ keysetId TEXT NOT NULL,
151
+ counter INTEGER NOT NULL,
152
+ PRIMARY KEY (mintUrl, keysetId)
153
+ );
154
+
155
+ CREATE TABLE IF NOT EXISTS coco_cashu_proofs (
156
+ mintUrl TEXT NOT NULL,
157
+ id TEXT NOT NULL,
158
+ amount INTEGER NOT NULL,
159
+ secret TEXT NOT NULL,
160
+ C TEXT NOT NULL,
161
+ dleqJson TEXT,
162
+ witnessJson TEXT,
163
+ state TEXT NOT NULL CHECK (state IN ('inflight', 'ready', 'spent')),
164
+ createdAt INTEGER NOT NULL,
165
+ PRIMARY KEY (mintUrl, secret)
166
+ );
167
+
168
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_state ON coco_cashu_proofs(state);
169
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_mint_state ON coco_cashu_proofs(mintUrl, state);
170
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_mint_id_state ON coco_cashu_proofs(mintUrl, id, state);
171
+
172
+ CREATE TABLE IF NOT EXISTS coco_cashu_mint_quotes (
173
+ mintUrl TEXT NOT NULL,
174
+ quote TEXT NOT NULL,
175
+ state TEXT NOT NULL CHECK (state IN ('UNPAID','PAID','ISSUED')),
176
+ request TEXT NOT NULL,
177
+ amount INTEGER NOT NULL,
178
+ unit TEXT NOT NULL,
179
+ expiry INTEGER NOT NULL,
180
+ pubkey TEXT,
181
+ PRIMARY KEY (mintUrl, quote)
182
+ );
183
+
184
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_quotes_state ON coco_cashu_mint_quotes(state);
185
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_quotes_mint ON coco_cashu_mint_quotes(mintUrl);
186
+ `
187
+ },
188
+ {
189
+ id: "002_melt_quotes",
190
+ sql: `
191
+ CREATE TABLE IF NOT EXISTS coco_cashu_melt_quotes (
192
+ mintUrl TEXT NOT NULL,
193
+ quote TEXT NOT NULL,
194
+ state TEXT NOT NULL CHECK (state IN ('UNPAID','PENDING','PAID')),
195
+ request TEXT NOT NULL,
196
+ amount INTEGER NOT NULL,
197
+ unit TEXT NOT NULL,
198
+ expiry INTEGER NOT NULL,
199
+ fee_reserve INTEGER NOT NULL,
200
+ payment_preimage TEXT,
201
+ PRIMARY KEY (mintUrl, quote)
202
+ );
203
+
204
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_melt_quotes_state ON coco_cashu_melt_quotes(state);
205
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_melt_quotes_mint ON coco_cashu_melt_quotes(mintUrl);
206
+ `
207
+ },
208
+ {
209
+ id: "003_history",
210
+ sql: `
211
+ CREATE TABLE IF NOT EXISTS coco_cashu_history (
212
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
213
+ mintUrl TEXT NOT NULL,
214
+ type TEXT NOT NULL CHECK (type IN ('mint','melt','send','receive')),
215
+ unit TEXT NOT NULL,
216
+ amount INTEGER NOT NULL,
217
+ createdAt INTEGER NOT NULL,
218
+ quoteId TEXT,
219
+ state TEXT,
220
+ paymentRequest TEXT,
221
+ tokenJson TEXT,
222
+ metadata TEXT
223
+ );
224
+
225
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_history_mint_createdAt
226
+ ON coco_cashu_history(mintUrl, createdAt DESC);
227
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_history_mint_quote
228
+ ON coco_cashu_history(mintUrl, quoteId);
229
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_history_type
230
+ ON coco_cashu_history(type);
231
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_coco_cashu_history_mint_quote_mint
232
+ ON coco_cashu_history(mintUrl, quoteId, type)
233
+ WHERE type = 'mint' AND quoteId IS NOT NULL;
234
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_coco_cashu_history_mint_quote_melt
235
+ ON coco_cashu_history(mintUrl, quoteId, type)
236
+ WHERE type = 'melt' AND quoteId IS NOT NULL;
237
+ `
238
+ },
239
+ {
240
+ id: "004_mint_trusted_field",
241
+ sql: `
242
+ ALTER TABLE coco_cashu_mints ADD COLUMN trusted INTEGER NOT NULL DEFAULT 1;
243
+ `
244
+ },
245
+ {
246
+ id: "005_keyset_unit_field",
247
+ sql: `
248
+ ALTER TABLE coco_cashu_keysets ADD COLUMN unit TEXT;
249
+ `
250
+ },
251
+ {
252
+ id: "006_keypairs",
253
+ sql: `
254
+ CREATE TABLE IF NOT EXISTS coco_cashu_keypairs (
255
+ publicKey TEXT PRIMARY KEY NOT NULL,
256
+ secretKey TEXT NOT NULL,
257
+ createdAt INTEGER NOT NULL,
258
+ derivationIndex INTEGER
259
+ );
260
+
261
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_keypairs_createdAt ON coco_cashu_keypairs(createdAt DESC);
262
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_keypairs_derivationIndex ON coco_cashu_keypairs(derivationIndex DESC) WHERE derivationIndex IS NOT NULL;
263
+ `
264
+ },
265
+ {
266
+ id: "007_normalize_mint_urls",
267
+ run: async (db) => {
268
+ const mints = await db.all("SELECT mintUrl FROM coco_cashu_mints");
269
+ const urlMapping = /* @__PURE__ */ new Map();
270
+ for (const { mintUrl } of mints) {
271
+ const normalized = normalizeMintUrl(mintUrl);
272
+ urlMapping.set(mintUrl, normalized);
273
+ }
274
+ const normalizedToOriginal = /* @__PURE__ */ new Map();
275
+ for (const [original, normalized] of urlMapping) {
276
+ const existing = normalizedToOriginal.get(normalized);
277
+ if (existing && existing !== original) throw new Error(`Mint URL normalization conflict: "${existing}" and "${original}" both normalize to "${normalized}". Please manually resolve this conflict before running the migration.`);
278
+ normalizedToOriginal.set(normalized, original);
279
+ }
280
+ const tables = [
281
+ "coco_cashu_mints",
282
+ "coco_cashu_keysets",
283
+ "coco_cashu_counters",
284
+ "coco_cashu_proofs",
285
+ "coco_cashu_mint_quotes",
286
+ "coco_cashu_melt_quotes",
287
+ "coco_cashu_history"
288
+ ];
289
+ for (const [original, normalized] of urlMapping) {
290
+ if (original === normalized) continue;
291
+ for (const table of tables) await db.run(`UPDATE ${table} SET mintUrl = ? WHERE mintUrl = ?`, [normalized, original]);
292
+ }
293
+ }
294
+ },
295
+ {
296
+ id: "008_send_operations",
297
+ sql: `
298
+ CREATE TABLE IF NOT EXISTS coco_cashu_send_operations (
299
+ id TEXT PRIMARY KEY NOT NULL,
300
+ mintUrl TEXT NOT NULL,
301
+ amount INTEGER NOT NULL,
302
+ state TEXT NOT NULL CHECK (state IN ('init', 'prepared', 'executing', 'pending', 'completed', 'rolling_back', 'rolled_back')),
303
+ createdAt INTEGER NOT NULL,
304
+ updatedAt INTEGER NOT NULL,
305
+ error TEXT,
306
+ needsSwap INTEGER,
307
+ fee INTEGER,
308
+ inputAmount INTEGER,
309
+ inputProofSecretsJson TEXT,
310
+ outputDataJson TEXT
311
+ );
312
+
313
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_send_operations_state ON coco_cashu_send_operations(state);
314
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_send_operations_mint ON coco_cashu_send_operations(mintUrl);
315
+
316
+ ALTER TABLE coco_cashu_proofs ADD COLUMN usedByOperationId TEXT;
317
+ ALTER TABLE coco_cashu_proofs ADD COLUMN createdByOperationId TEXT;
318
+
319
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_usedByOp ON coco_cashu_proofs(usedByOperationId) WHERE usedByOperationId IS NOT NULL;
320
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_createdByOp ON coco_cashu_proofs(createdByOperationId) WHERE createdByOperationId IS NOT NULL;
321
+ `
322
+ },
323
+ {
324
+ id: "009_history_send_operation",
325
+ sql: `
326
+ ALTER TABLE coco_cashu_history ADD COLUMN operationId TEXT;
327
+
328
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_coco_cashu_history_mint_operation_send
329
+ ON coco_cashu_history(mintUrl, operationId)
330
+ WHERE type = 'send' AND operationId IS NOT NULL;
331
+ `
332
+ },
333
+ {
334
+ id: "010_rename_completed_to_finalized",
335
+ run: async (db) => {
336
+ await db.run(`UPDATE coco_cashu_history SET state = 'finalized' WHERE type = 'send' AND state = 'completed'`);
337
+ await db.exec(`
338
+ CREATE TABLE coco_cashu_send_operations_new (
339
+ id TEXT PRIMARY KEY NOT NULL,
340
+ mintUrl TEXT NOT NULL,
341
+ amount INTEGER NOT NULL,
342
+ state TEXT NOT NULL CHECK (state IN ('init', 'prepared', 'executing', 'pending', 'finalized', 'rolling_back', 'rolled_back')),
343
+ createdAt INTEGER NOT NULL,
344
+ updatedAt INTEGER NOT NULL,
345
+ error TEXT,
346
+ needsSwap INTEGER,
347
+ fee INTEGER,
348
+ inputAmount INTEGER,
349
+ inputProofSecretsJson TEXT,
350
+ outputDataJson TEXT
351
+ );
352
+
353
+ INSERT INTO coco_cashu_send_operations_new
354
+ SELECT
355
+ id, mintUrl, amount,
356
+ CASE WHEN state = 'completed' THEN 'finalized' ELSE state END,
357
+ createdAt, updatedAt, error, needsSwap, fee, inputAmount,
358
+ inputProofSecretsJson, outputDataJson
359
+ FROM coco_cashu_send_operations;
360
+
361
+ DROP TABLE coco_cashu_send_operations;
362
+
363
+ ALTER TABLE coco_cashu_send_operations_new RENAME TO coco_cashu_send_operations;
364
+
365
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_send_operations_state ON coco_cashu_send_operations(state);
366
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_send_operations_mint ON coco_cashu_send_operations(mintUrl);
367
+ `);
368
+ }
369
+ },
370
+ {
371
+ id: "011_melt_operations",
372
+ sql: `
373
+ CREATE TABLE IF NOT EXISTS coco_cashu_melt_operations (
374
+ id TEXT PRIMARY KEY NOT NULL,
375
+ mintUrl TEXT NOT NULL,
376
+ state TEXT NOT NULL CHECK (state IN ('init', 'prepared', 'executing', 'pending', 'finalized', 'rolling_back', 'rolled_back')),
377
+ createdAt INTEGER NOT NULL,
378
+ updatedAt INTEGER NOT NULL,
379
+ error TEXT,
380
+ method TEXT NOT NULL,
381
+ methodDataJson TEXT NOT NULL,
382
+ quoteId TEXT,
383
+ amount INTEGER,
384
+ fee_reserve INTEGER,
385
+ swap_fee INTEGER,
386
+ needsSwap INTEGER,
387
+ inputAmount INTEGER,
388
+ inputProofSecretsJson TEXT,
389
+ changeOutputDataJson TEXT,
390
+ swapOutputDataJson TEXT
391
+ );
392
+
393
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_melt_operations_state
394
+ ON coco_cashu_melt_operations(state);
395
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_melt_operations_mint
396
+ ON coco_cashu_melt_operations(mintUrl);
397
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_coco_cashu_melt_operations_mint_quote
398
+ ON coco_cashu_melt_operations(mintUrl, quoteId)
399
+ WHERE quoteId IS NOT NULL;
400
+ `
401
+ },
402
+ {
403
+ id: "012_send_operations_method",
404
+ sql: `
405
+ ALTER TABLE coco_cashu_send_operations ADD COLUMN method TEXT NOT NULL DEFAULT 'default';
406
+ ALTER TABLE coco_cashu_send_operations ADD COLUMN methodDataJson TEXT NOT NULL DEFAULT '{}';
407
+ `
408
+ },
409
+ {
410
+ id: "013_receive_operations",
411
+ sql: `
412
+ CREATE TABLE IF NOT EXISTS coco_cashu_receive_operations (
413
+ id TEXT PRIMARY KEY,
414
+ mintUrl TEXT NOT NULL,
415
+ amount INTEGER NOT NULL,
416
+ state TEXT NOT NULL CHECK (state IN ('init', 'prepared', 'executing', 'finalized', 'rolled_back')),
417
+ createdAt INTEGER NOT NULL,
418
+ updatedAt INTEGER NOT NULL,
419
+ error TEXT,
420
+ fee INTEGER,
421
+ inputProofsJson TEXT NOT NULL,
422
+ outputDataJson TEXT
423
+ );
424
+
425
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_receive_operations_state
426
+ ON coco_cashu_receive_operations(state);
427
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_receive_operations_mint
428
+ ON coco_cashu_receive_operations(mintUrl);
429
+ `
430
+ },
431
+ {
432
+ id: "014_send_operations_token",
433
+ sql: `
434
+ ALTER TABLE coco_cashu_send_operations ADD COLUMN tokenJson TEXT;
435
+ `
436
+ },
437
+ {
438
+ id: "015_reset_keysets_for_string_denoms",
439
+ sql: `
440
+ DELETE FROM coco_cashu_keysets;
441
+ UPDATE coco_cashu_mints SET updatedAt = 0;
442
+ `
443
+ },
444
+ {
445
+ id: "016_melt_settlement_amounts",
446
+ sql: `
447
+ ALTER TABLE coco_cashu_melt_operations ADD COLUMN changeAmount INTEGER;
448
+ ALTER TABLE coco_cashu_melt_operations ADD COLUMN effectiveFee INTEGER;
449
+ `
450
+ },
451
+ {
452
+ id: "017_auth_sessions",
453
+ sql: `
454
+ CREATE TABLE IF NOT EXISTS coco_cashu_auth_sessions (
455
+ mintUrl TEXT PRIMARY KEY NOT NULL,
456
+ accessToken TEXT NOT NULL,
457
+ refreshToken TEXT,
458
+ expiresAt INTEGER NOT NULL,
459
+ scope TEXT,
460
+ batPoolJson TEXT
461
+ );
462
+ `
463
+ },
464
+ {
465
+ id: "018_mint_operations",
466
+ sql: `
467
+ CREATE TABLE IF NOT EXISTS coco_cashu_mint_operations (
468
+ id TEXT PRIMARY KEY NOT NULL,
469
+ mintUrl TEXT NOT NULL,
470
+ quoteId TEXT,
471
+ state TEXT NOT NULL CHECK (state IN ('init', 'pending', 'executing', 'finalized', 'failed')),
472
+ createdAt INTEGER NOT NULL,
473
+ updatedAt INTEGER NOT NULL,
474
+ error TEXT,
475
+ method TEXT NOT NULL,
476
+ methodDataJson TEXT NOT NULL,
477
+ amount INTEGER,
478
+ unit TEXT,
479
+ request TEXT,
480
+ expiry INTEGER,
481
+ pubkey TEXT,
482
+ lastObservedRemoteState TEXT,
483
+ lastObservedRemoteStateAt INTEGER,
484
+ terminalFailureJson TEXT,
485
+ outputDataJson TEXT
486
+ );
487
+
488
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_state
489
+ ON coco_cashu_mint_operations(state);
490
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_mint
491
+ ON coco_cashu_mint_operations(mintUrl);
492
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_mint_quote
493
+ ON coco_cashu_mint_operations(mintUrl, quoteId)
494
+ WHERE quoteId IS NOT NULL;
495
+ `
496
+ },
497
+ {
498
+ id: "019_mint_operations_pending_lifecycle",
499
+ sql: `
500
+ ALTER TABLE coco_cashu_mint_operations RENAME TO coco_cashu_mint_operations_legacy;
501
+
502
+ CREATE TABLE coco_cashu_mint_operations (
503
+ id TEXT PRIMARY KEY NOT NULL,
504
+ mintUrl TEXT NOT NULL,
505
+ quoteId TEXT,
506
+ state TEXT NOT NULL CHECK (state IN ('init', 'pending', 'executing', 'finalized', 'failed')),
507
+ createdAt INTEGER NOT NULL,
508
+ updatedAt INTEGER NOT NULL,
509
+ error TEXT,
510
+ method TEXT NOT NULL,
511
+ methodDataJson TEXT NOT NULL,
512
+ amount INTEGER,
513
+ unit TEXT,
514
+ request TEXT,
515
+ expiry INTEGER,
516
+ pubkey TEXT,
517
+ lastObservedRemoteState TEXT,
518
+ lastObservedRemoteStateAt INTEGER,
519
+ terminalFailureJson TEXT,
520
+ outputDataJson TEXT
521
+ );
522
+
523
+ INSERT INTO coco_cashu_mint_operations (
524
+ id, mintUrl, quoteId, state, createdAt, updatedAt, error, method, methodDataJson, amount, unit, request, expiry, pubkey, lastObservedRemoteState, lastObservedRemoteStateAt, terminalFailureJson, outputDataJson
525
+ )
526
+ SELECT
527
+ id,
528
+ mintUrl,
529
+ quoteId,
530
+ CASE
531
+ WHEN state = 'prepared' THEN 'pending'
532
+ WHEN state = 'rolled_back' THEN 'finalized'
533
+ ELSE state
534
+ END,
535
+ createdAt,
536
+ updatedAt,
537
+ error,
538
+ method,
539
+ methodDataJson,
540
+ amount,
541
+ unit,
542
+ request,
543
+ expiry,
544
+ pubkey,
545
+ lastObservedRemoteState,
546
+ lastObservedRemoteStateAt,
547
+ terminalFailureJson,
548
+ outputDataJson
549
+ FROM coco_cashu_mint_operations_legacy;
550
+
551
+ DROP TABLE coco_cashu_mint_operations_legacy;
552
+
553
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_state
554
+ ON coco_cashu_mint_operations(state);
555
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_mint
556
+ ON coco_cashu_mint_operations(mintUrl);
557
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_mint_quote
558
+ ON coco_cashu_mint_operations(mintUrl, quoteId)
559
+ WHERE quoteId IS NOT NULL;
560
+ `
561
+ },
562
+ {
563
+ id: "020_mint_operations_failed_state",
564
+ sql: `
565
+ ALTER TABLE coco_cashu_mint_operations RENAME TO coco_cashu_mint_operations_legacy;
566
+
567
+ CREATE TABLE coco_cashu_mint_operations (
568
+ id TEXT PRIMARY KEY NOT NULL,
569
+ mintUrl TEXT NOT NULL,
570
+ quoteId TEXT,
571
+ state TEXT NOT NULL CHECK (state IN ('init', 'pending', 'executing', 'finalized', 'failed')),
572
+ createdAt INTEGER NOT NULL,
573
+ updatedAt INTEGER NOT NULL,
574
+ error TEXT,
575
+ method TEXT NOT NULL,
576
+ methodDataJson TEXT NOT NULL,
577
+ amount INTEGER,
578
+ unit TEXT,
579
+ request TEXT,
580
+ expiry INTEGER,
581
+ pubkey TEXT,
582
+ lastObservedRemoteState TEXT,
583
+ lastObservedRemoteStateAt INTEGER,
584
+ terminalFailureJson TEXT,
585
+ outputDataJson TEXT
586
+ );
587
+
588
+ INSERT INTO coco_cashu_mint_operations (
589
+ id, mintUrl, quoteId, state, createdAt, updatedAt, error, method, methodDataJson, amount, unit, request, expiry, pubkey, lastObservedRemoteState, lastObservedRemoteStateAt, terminalFailureJson, outputDataJson
590
+ )
591
+ SELECT
592
+ id,
593
+ mintUrl,
594
+ quoteId,
595
+ state,
596
+ createdAt,
597
+ updatedAt,
598
+ error,
599
+ method,
600
+ methodDataJson,
601
+ amount,
602
+ unit,
603
+ request,
604
+ expiry,
605
+ pubkey,
606
+ lastObservedRemoteState,
607
+ lastObservedRemoteStateAt,
608
+ terminalFailureJson,
609
+ outputDataJson
610
+ FROM coco_cashu_mint_operations_legacy;
611
+
612
+ DROP TABLE coco_cashu_mint_operations_legacy;
613
+
614
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_state
615
+ ON coco_cashu_mint_operations(state);
616
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_mint
617
+ ON coco_cashu_mint_operations(mintUrl);
618
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_mint_quote
619
+ ON coco_cashu_mint_operations(mintUrl, quoteId)
620
+ WHERE quoteId IS NOT NULL;
621
+ `
622
+ },
623
+ {
624
+ id: "021_melt_finalized_data",
625
+ sql: `
626
+ ALTER TABLE coco_cashu_melt_operations ADD COLUMN finalizedDataJson TEXT;
627
+ `
628
+ }
629
+ ];
630
+ /**
631
+ * Ensures the database schema is up to date by running all pending migrations.
632
+ */
633
+ async function ensureSchema(db) {
634
+ await ensureSchemaUpTo(db);
635
+ }
636
+ /**
637
+ * Run migrations up to (but not including) a specific migration ID.
638
+ * If stopBeforeId is not provided, runs all migrations.
639
+ * Used for testing migration behavior.
640
+ */
641
+ async function ensureSchemaUpTo(db, stopBeforeId) {
642
+ await db.exec(`
643
+ CREATE TABLE IF NOT EXISTS coco_cashu_migrations (
644
+ id TEXT PRIMARY KEY NOT NULL,
645
+ appliedAt INTEGER NOT NULL
646
+ );
647
+ `);
648
+ const appliedRows = await db.all("SELECT id FROM coco_cashu_migrations ORDER BY id ASC");
649
+ const applied = new Set(appliedRows.map((r) => r.id));
650
+ for (const migration of MIGRATIONS) {
651
+ if (stopBeforeId && migration.id === stopBeforeId) break;
652
+ if (applied.has(migration.id)) continue;
653
+ await db.transaction(async (tx) => {
654
+ if (migration.sql) await tx.exec(migration.sql);
655
+ if (migration.run) await migration.run(tx);
656
+ await tx.run("INSERT INTO coco_cashu_migrations (id, appliedAt) VALUES (?, ?)", [migration.id, getUnixTimeSeconds()]);
657
+ });
658
+ }
659
+ }
660
+
661
+ //#endregion
662
+ //#region src/repositories/MintRepository.ts
663
+ var ExpoMintRepository = class {
664
+ db;
665
+ constructor(db) {
666
+ this.db = db;
667
+ }
668
+ async isTrustedMint(mintUrl) {
669
+ return (await this.db.get("SELECT trusted FROM coco_cashu_mints WHERE mintUrl = ? LIMIT 1", [mintUrl]))?.trusted === 1;
670
+ }
671
+ async getMintByUrl(mintUrl) {
672
+ const row = await this.db.get("SELECT mintUrl, name, mintInfo, trusted, createdAt, updatedAt FROM coco_cashu_mints WHERE mintUrl = ? LIMIT 1", [mintUrl]);
673
+ if (!row) throw new Error(`Mint not found: ${mintUrl}`);
674
+ return {
675
+ mintUrl: row.mintUrl,
676
+ name: row.name,
677
+ mintInfo: JSON.parse(row.mintInfo),
678
+ trusted: row.trusted === 1,
679
+ createdAt: row.createdAt,
680
+ updatedAt: row.updatedAt
681
+ };
682
+ }
683
+ async getAllMints() {
684
+ return (await this.db.all("SELECT mintUrl, name, mintInfo, trusted, createdAt, updatedAt FROM coco_cashu_mints")).map((r) => ({
685
+ mintUrl: r.mintUrl,
686
+ name: r.name,
687
+ mintInfo: JSON.parse(r.mintInfo),
688
+ trusted: r.trusted === 1,
689
+ createdAt: r.createdAt,
690
+ updatedAt: r.updatedAt
691
+ }));
692
+ }
693
+ async getAllTrustedMints() {
694
+ return (await this.db.all("SELECT mintUrl, name, mintInfo, trusted, createdAt, updatedAt FROM coco_cashu_mints WHERE trusted = 1")).map((r) => ({
695
+ mintUrl: r.mintUrl,
696
+ name: r.name,
697
+ mintInfo: JSON.parse(r.mintInfo),
698
+ trusted: r.trusted === 1,
699
+ createdAt: r.createdAt,
700
+ updatedAt: r.updatedAt
701
+ }));
702
+ }
703
+ async addNewMint(mint) {
704
+ await this.db.run(`INSERT INTO coco_cashu_mints (mintUrl, name, mintInfo, trusted, createdAt, updatedAt)
705
+ VALUES (?, ?, ?, ?, ?, ?)
706
+ ON CONFLICT(mintUrl) DO UPDATE SET
707
+ name=excluded.name,
708
+ mintInfo=excluded.mintInfo,
709
+ trusted=excluded.trusted,
710
+ createdAt=excluded.createdAt,
711
+ updatedAt=excluded.updatedAt`, [
712
+ mint.mintUrl,
713
+ mint.name,
714
+ JSON.stringify(mint.mintInfo),
715
+ mint.trusted ? 1 : 0,
716
+ mint.createdAt,
717
+ mint.updatedAt
718
+ ]);
719
+ }
720
+ async addOrUpdateMint(mint) {
721
+ await this.db.run(`INSERT INTO coco_cashu_mints (mintUrl, name, mintInfo, trusted, createdAt, updatedAt)
722
+ VALUES (?, ?, ?, ?, ?, ?)
723
+ ON CONFLICT(mintUrl) DO UPDATE SET
724
+ name=excluded.name,
725
+ mintInfo=excluded.mintInfo,
726
+ trusted=excluded.trusted,
727
+ updatedAt=excluded.updatedAt`, [
728
+ mint.mintUrl,
729
+ mint.name,
730
+ JSON.stringify(mint.mintInfo),
731
+ mint.trusted ? 1 : 0,
732
+ mint.createdAt,
733
+ mint.updatedAt
734
+ ]);
735
+ }
736
+ async updateMint(mint) {
737
+ await this.addNewMint(mint);
738
+ }
739
+ async setMintTrusted(mintUrl, trusted) {
740
+ await this.db.run("UPDATE coco_cashu_mints SET trusted = ? WHERE mintUrl = ?", [trusted ? 1 : 0, mintUrl]);
741
+ }
742
+ async deleteMint(mintUrl) {
743
+ await this.db.run("DELETE FROM coco_cashu_mints WHERE mintUrl = ?", [mintUrl]);
744
+ }
745
+ };
746
+
747
+ //#endregion
748
+ //#region src/repositories/KeysetRepository.ts
749
+ var ExpoKeysetRepository = class {
750
+ db;
751
+ constructor(db) {
752
+ this.db = db;
753
+ }
754
+ async getKeysetsByMintUrl(mintUrl) {
755
+ return (await this.db.all("SELECT mintUrl, id, unit, keypairs, active, feePpk, updatedAt FROM coco_cashu_keysets WHERE mintUrl = ?", [mintUrl])).map((r) => ({
756
+ mintUrl: r.mintUrl,
757
+ id: r.id,
758
+ unit: r.unit ?? "",
759
+ keypairs: JSON.parse(r.keypairs),
760
+ active: !!r.active,
761
+ feePpk: r.feePpk,
762
+ updatedAt: r.updatedAt
763
+ }));
764
+ }
765
+ async getKeysetById(mintUrl, id) {
766
+ const row = await this.db.get("SELECT mintUrl, id, unit, keypairs, active, feePpk, updatedAt FROM coco_cashu_keysets WHERE mintUrl = ? AND id = ? LIMIT 1", [mintUrl, id]);
767
+ if (!row) return null;
768
+ return {
769
+ mintUrl: row.mintUrl,
770
+ id: row.id,
771
+ unit: row.unit ?? "",
772
+ keypairs: JSON.parse(row.keypairs),
773
+ active: !!row.active,
774
+ feePpk: row.feePpk,
775
+ updatedAt: row.updatedAt
776
+ };
777
+ }
778
+ async updateKeyset(keyset) {
779
+ const now = getUnixTimeSeconds();
780
+ if (!await this.db.get("SELECT keypairs FROM coco_cashu_keysets WHERE mintUrl = ? AND id = ? LIMIT 1", [keyset.mintUrl, keyset.id])) {
781
+ await this.db.run("INSERT INTO coco_cashu_keysets (mintUrl, id, unit, keypairs, active, feePpk, updatedAt) VALUES (?, ?, ?, ?, ?, ?, ?)", [
782
+ keyset.mintUrl,
783
+ keyset.id,
784
+ keyset.unit,
785
+ JSON.stringify({}),
786
+ keyset.active ? 1 : 0,
787
+ keyset.feePpk,
788
+ now
789
+ ]);
790
+ return;
791
+ }
792
+ await this.db.run("UPDATE coco_cashu_keysets SET unit = ?, active = ?, feePpk = ?, updatedAt = ? WHERE mintUrl = ? AND id = ?", [
793
+ keyset.unit,
794
+ keyset.active ? 1 : 0,
795
+ keyset.feePpk,
796
+ now,
797
+ keyset.mintUrl,
798
+ keyset.id
799
+ ]);
800
+ }
801
+ async addKeyset(keyset) {
802
+ const now = getUnixTimeSeconds();
803
+ await this.db.run(`INSERT INTO coco_cashu_keysets (mintUrl, id, unit, keypairs, active, feePpk, updatedAt)
804
+ VALUES (?, ?, ?, ?, ?, ?, ?)
805
+ ON CONFLICT(mintUrl, id) DO UPDATE SET
806
+ unit=excluded.unit,
807
+ keypairs=excluded.keypairs,
808
+ active=excluded.active,
809
+ feePpk=excluded.feePpk,
810
+ updatedAt=excluded.updatedAt`, [
811
+ keyset.mintUrl,
812
+ keyset.id,
813
+ keyset.unit,
814
+ JSON.stringify(keyset.keypairs ?? {}),
815
+ keyset.active ? 1 : 0,
816
+ keyset.feePpk,
817
+ now
818
+ ]);
819
+ }
820
+ async deleteKeyset(mintUrl, keysetId) {
821
+ await this.db.run("DELETE FROM coco_cashu_keysets WHERE mintUrl = ? AND id = ?", [mintUrl, keysetId]);
822
+ }
823
+ };
824
+
825
+ //#endregion
826
+ //#region src/utils.ts
827
+ /**
828
+ * Safely converts a hex string to Uint8Array with validation
829
+ * @throws Error if the hex string is invalid or malformed
830
+ */
831
+ function hexToBytes(hexString) {
832
+ if (!/^[0-9a-fA-F]+$/.test(hexString)) throw new Error(`Invalid hex string: contains non-hex characters`);
833
+ if (hexString.length % 2 !== 0) throw new Error(`Invalid hex string: odd length (${hexString.length})`);
834
+ const matches = hexString.match(/.{2}/g);
835
+ if (!matches) throw new Error(`Failed to parse hex string`);
836
+ return new Uint8Array(matches.map((byte) => parseInt(byte, 16)));
837
+ }
838
+ /**
839
+ * Converts a Uint8Array to hex string
840
+ */
841
+ function bytesToHex(bytes) {
842
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
843
+ }
844
+
845
+ //#endregion
846
+ //#region src/repositories/KeyRingRepository.ts
847
+ var ExpoKeyRingRepository = class {
848
+ db;
849
+ constructor(db) {
850
+ this.db = db;
851
+ }
852
+ async getPersistedKeyPair(publicKey) {
853
+ const row = await this.db.get("SELECT publicKey, secretKey, derivationIndex FROM coco_cashu_keypairs WHERE publicKey = ? LIMIT 1", [publicKey]);
854
+ if (!row) return null;
855
+ try {
856
+ const secretKeyBytes = hexToBytes(row.secretKey);
857
+ return {
858
+ publicKeyHex: row.publicKey,
859
+ secretKey: secretKeyBytes,
860
+ derivationIndex: row.derivationIndex ?? void 0
861
+ };
862
+ } catch (error) {
863
+ throw new Error(`Failed to parse secret key for public key ${publicKey}: ${error instanceof Error ? error.message : "unknown error"}`);
864
+ }
865
+ }
866
+ async setPersistedKeyPair(keyPair) {
867
+ const secretKeyHex = bytesToHex(keyPair.secretKey);
868
+ await this.db.run(`INSERT INTO coco_cashu_keypairs (publicKey, secretKey, createdAt, derivationIndex)
869
+ VALUES (?, ?, ?, ?)
870
+ ON CONFLICT(publicKey) DO UPDATE SET
871
+ secretKey=excluded.secretKey,
872
+ derivationIndex=COALESCE(excluded.derivationIndex, coco_cashu_keypairs.derivationIndex)`, [
873
+ keyPair.publicKeyHex,
874
+ secretKeyHex,
875
+ Date.now(),
876
+ keyPair.derivationIndex ?? null
877
+ ]);
878
+ }
879
+ async deletePersistedKeyPair(publicKey) {
880
+ await this.db.run("DELETE FROM coco_cashu_keypairs WHERE publicKey = ?", [publicKey]);
881
+ }
882
+ async getAllPersistedKeyPairs() {
883
+ return (await this.db.all("SELECT publicKey, secretKey, derivationIndex FROM coco_cashu_keypairs")).map((row) => {
884
+ try {
885
+ const secretKeyBytes = hexToBytes(row.secretKey);
886
+ return {
887
+ publicKeyHex: row.publicKey,
888
+ secretKey: secretKeyBytes,
889
+ derivationIndex: row.derivationIndex ?? void 0
890
+ };
891
+ } catch (error) {
892
+ throw new Error(`Failed to parse secret key for public key ${row.publicKey}: ${error instanceof Error ? error.message : "unknown error"}`);
893
+ }
894
+ });
895
+ }
896
+ async getLatestKeyPair() {
897
+ const row = await this.db.get("SELECT publicKey, secretKey, derivationIndex FROM coco_cashu_keypairs ORDER BY createdAt DESC LIMIT 1");
898
+ if (!row) return null;
899
+ try {
900
+ const secretKeyBytes = hexToBytes(row.secretKey);
901
+ return {
902
+ publicKeyHex: row.publicKey,
903
+ secretKey: secretKeyBytes,
904
+ derivationIndex: row.derivationIndex ?? void 0
905
+ };
906
+ } catch (error) {
907
+ throw new Error(`Failed to parse latest secret key for public key ${row.publicKey}: ${error instanceof Error ? error.message : "unknown error"}`);
908
+ }
909
+ }
910
+ async getLastDerivationIndex() {
911
+ return (await this.db.get("SELECT derivationIndex FROM coco_cashu_keypairs WHERE derivationIndex IS NOT NULL ORDER BY derivationIndex DESC LIMIT 1"))?.derivationIndex ?? -1;
912
+ }
913
+ };
914
+
915
+ //#endregion
916
+ //#region src/repositories/CounterRepository.ts
917
+ var ExpoCounterRepository = class {
918
+ db;
919
+ constructor(db) {
920
+ this.db = db;
921
+ }
922
+ async getCounter(mintUrl, keysetId) {
923
+ const row = await this.db.get("SELECT counter FROM coco_cashu_counters WHERE mintUrl = ? AND keysetId = ? LIMIT 1", [mintUrl, keysetId]);
924
+ if (!row) return null;
925
+ return {
926
+ mintUrl,
927
+ keysetId,
928
+ counter: row.counter
929
+ };
930
+ }
931
+ async setCounter(mintUrl, keysetId, counter) {
932
+ await this.db.run(`INSERT INTO coco_cashu_counters (mintUrl, keysetId, counter)
933
+ VALUES (?, ?, ?)
934
+ ON CONFLICT(mintUrl, keysetId) DO UPDATE SET counter = excluded.counter`, [
935
+ mintUrl,
936
+ keysetId,
937
+ counter
938
+ ]);
939
+ }
940
+ };
941
+
942
+ //#endregion
943
+ //#region src/repositories/ProofRepository.ts
944
+ const MAX_PROOF_SECRET_LOOKUP_BATCH_SIZE = 900;
945
+ function rowToProof(r) {
946
+ return {
947
+ id: r.id,
948
+ amount: r.amount,
949
+ secret: r.secret,
950
+ C: r.C,
951
+ ...r.dleqJson ? { dleq: JSON.parse(r.dleqJson) } : {},
952
+ ...r.witnessJson ? { witness: JSON.parse(r.witnessJson) } : {},
953
+ mintUrl: r.mintUrl,
954
+ state: r.state,
955
+ ...r.usedByOperationId ? { usedByOperationId: r.usedByOperationId } : {},
956
+ ...r.createdByOperationId ? { createdByOperationId: r.createdByOperationId } : {}
957
+ };
958
+ }
959
+ var ExpoProofRepository = class {
960
+ db;
961
+ constructor(db) {
962
+ this.db = db;
963
+ }
964
+ async saveProofs(mintUrl, proofs) {
965
+ if (!proofs || proofs.length === 0) return;
966
+ const now = getUnixTimeSeconds();
967
+ await this.db.transaction(async (tx) => {
968
+ const selectSql = "SELECT 1 AS x FROM coco_cashu_proofs WHERE mintUrl = ? AND secret = ? LIMIT 1";
969
+ for (const p of proofs) if (await tx.get(selectSql, [mintUrl, p.secret])) throw new Error(`Proof with secret already exists: ${p.secret}`);
970
+ const insertSql = "INSERT INTO coco_cashu_proofs (mintUrl, id, amount, secret, C, dleqJson, witnessJson, state, createdAt, usedByOperationId, createdByOperationId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
971
+ for (const p of proofs) {
972
+ const dleqJson = p.dleq ? JSON.stringify(p.dleq) : null;
973
+ const witnessJson = p.witness ? JSON.stringify(p.witness) : null;
974
+ await tx.run(insertSql, [
975
+ mintUrl,
976
+ p.id,
977
+ p.amount,
978
+ p.secret,
979
+ p.C,
980
+ dleqJson,
981
+ witnessJson,
982
+ p.state,
983
+ now,
984
+ p.usedByOperationId ?? null,
985
+ p.createdByOperationId ?? null
986
+ ]);
987
+ }
988
+ });
989
+ }
990
+ async getReadyProofs(mintUrl) {
991
+ return (await this.db.all("SELECT mintUrl, id, amount, secret, C, dleqJson, witnessJson, state, usedByOperationId, createdByOperationId FROM coco_cashu_proofs WHERE mintUrl = ? AND state = \"ready\"", [mintUrl])).map(rowToProof);
992
+ }
993
+ async getInflightProofs(mintUrls) {
994
+ if (!mintUrls || mintUrls.length === 0) return (await this.db.all("SELECT mintUrl, id, amount, secret, C, dleqJson, witnessJson, state, usedByOperationId, createdByOperationId FROM coco_cashu_proofs WHERE state = \"inflight\"")).map(rowToProof);
995
+ const mintUrlList = mintUrls.map((url) => url.trim()).filter((url) => url.length > 0);
996
+ if (mintUrlList.length === 0) return [];
997
+ const uniqueMintUrls = Array.from(new Set(mintUrlList));
998
+ const placeholders = uniqueMintUrls.map(() => "?").join(", ");
999
+ return (await this.db.all(`SELECT mintUrl, id, amount, secret, C, dleqJson, witnessJson, state, usedByOperationId, createdByOperationId FROM coco_cashu_proofs WHERE state = "inflight" AND mintUrl IN (${placeholders})`, uniqueMintUrls)).map(rowToProof);
1000
+ }
1001
+ async getAllReadyProofs() {
1002
+ return (await this.db.all("SELECT mintUrl, id, amount, secret, C, dleqJson, witnessJson, state, usedByOperationId, createdByOperationId FROM coco_cashu_proofs WHERE state = \"ready\"")).map(rowToProof);
1003
+ }
1004
+ async getProofsByKeysetId(mintUrl, keysetId) {
1005
+ return (await this.db.all("SELECT mintUrl, id, amount, secret, C, dleqJson, witnessJson, state, usedByOperationId, createdByOperationId FROM coco_cashu_proofs WHERE mintUrl = ? AND id = ? AND state = \"ready\"", [mintUrl, keysetId])).map(rowToProof);
1006
+ }
1007
+ async setProofState(mintUrl, secrets, state) {
1008
+ if (!secrets || secrets.length === 0) return;
1009
+ await this.db.transaction(async (tx) => {
1010
+ const updateSql = "UPDATE coco_cashu_proofs SET state = ? WHERE mintUrl = ? AND secret = ?";
1011
+ for (const s of secrets) await tx.run(updateSql, [
1012
+ state,
1013
+ mintUrl,
1014
+ s
1015
+ ]);
1016
+ });
1017
+ }
1018
+ async deleteProofs(mintUrl, secrets) {
1019
+ if (!secrets || secrets.length === 0) return;
1020
+ await this.db.transaction(async (tx) => {
1021
+ const delSql = "DELETE FROM coco_cashu_proofs WHERE mintUrl = ? AND secret = ?";
1022
+ for (const s of secrets) await tx.run(delSql, [mintUrl, s]);
1023
+ });
1024
+ }
1025
+ async wipeProofsByKeysetId(mintUrl, keysetId) {
1026
+ await this.db.run("DELETE FROM coco_cashu_proofs WHERE mintUrl = ? AND id = ?;", [mintUrl, keysetId]);
1027
+ }
1028
+ async reserveProofs(mintUrl, secrets, operationId) {
1029
+ if (!secrets || secrets.length === 0) return;
1030
+ await this.db.transaction(async (tx) => {
1031
+ const selectSql = "SELECT secret, state, usedByOperationId FROM coco_cashu_proofs WHERE mintUrl = ? AND secret = ?";
1032
+ for (const secret of secrets) {
1033
+ const row = await tx.get(selectSql, [mintUrl, secret]);
1034
+ if (!row) throw new Error(`Proof with secret not found: ${secret}`);
1035
+ if (row.state !== "ready") throw new Error(`Proof is not ready, cannot reserve: ${secret}`);
1036
+ if (row.usedByOperationId) throw new Error(`Proof already reserved by operation ${row.usedByOperationId}: ${secret}`);
1037
+ }
1038
+ const updateSql = "UPDATE coco_cashu_proofs SET usedByOperationId = ? WHERE mintUrl = ? AND secret = ?";
1039
+ for (const secret of secrets) await tx.run(updateSql, [
1040
+ operationId,
1041
+ mintUrl,
1042
+ secret
1043
+ ]);
1044
+ });
1045
+ }
1046
+ async releaseProofs(mintUrl, secrets) {
1047
+ if (!secrets || secrets.length === 0) return;
1048
+ await this.db.transaction(async (tx) => {
1049
+ const updateSql = "UPDATE coco_cashu_proofs SET usedByOperationId = NULL WHERE mintUrl = ? AND secret = ?";
1050
+ for (const secret of secrets) await tx.run(updateSql, [mintUrl, secret]);
1051
+ });
1052
+ }
1053
+ async setCreatedByOperation(mintUrl, secrets, operationId) {
1054
+ if (!secrets || secrets.length === 0) return;
1055
+ await this.db.transaction(async (tx) => {
1056
+ const updateSql = "UPDATE coco_cashu_proofs SET createdByOperationId = ? WHERE mintUrl = ? AND secret = ?";
1057
+ for (const secret of secrets) await tx.run(updateSql, [
1058
+ operationId,
1059
+ mintUrl,
1060
+ secret
1061
+ ]);
1062
+ });
1063
+ }
1064
+ async getProofBySecret(mintUrl, secret) {
1065
+ const row = await this.db.get("SELECT mintUrl, id, amount, secret, C, dleqJson, witnessJson, state, usedByOperationId, createdByOperationId FROM coco_cashu_proofs WHERE mintUrl = ? AND secret = ?", [mintUrl, secret]);
1066
+ return row ? rowToProof(row) : null;
1067
+ }
1068
+ async getProofsBySecrets(mintUrl, secrets) {
1069
+ if (!secrets || secrets.length === 0) return [];
1070
+ const uniqueSecrets = Array.from(new Set(secrets));
1071
+ const proofsBySecret = /* @__PURE__ */ new Map();
1072
+ for (let i = 0; i < uniqueSecrets.length; i += MAX_PROOF_SECRET_LOOKUP_BATCH_SIZE) {
1073
+ const secretBatch = uniqueSecrets.slice(i, i + MAX_PROOF_SECRET_LOOKUP_BATCH_SIZE);
1074
+ const placeholders = secretBatch.map(() => "?").join(", ");
1075
+ const rows = await this.db.all(`SELECT mintUrl, id, amount, secret, C, dleqJson, witnessJson, state, usedByOperationId, createdByOperationId FROM coco_cashu_proofs WHERE mintUrl = ? AND secret IN (${placeholders})`, [mintUrl, ...secretBatch]);
1076
+ for (const row of rows) proofsBySecret.set(row.secret, rowToProof(row));
1077
+ }
1078
+ return uniqueSecrets.flatMap((secret) => {
1079
+ const proof = proofsBySecret.get(secret);
1080
+ return proof ? [proof] : [];
1081
+ });
1082
+ }
1083
+ async getProofsByOperationId(mintUrl, operationId) {
1084
+ return (await this.db.all("SELECT mintUrl, id, amount, secret, C, dleqJson, witnessJson, state, usedByOperationId, createdByOperationId FROM coco_cashu_proofs WHERE mintUrl = ? AND (usedByOperationId = ? OR createdByOperationId = ?)", [
1085
+ mintUrl,
1086
+ operationId,
1087
+ operationId
1088
+ ])).map(rowToProof);
1089
+ }
1090
+ async getAvailableProofs(mintUrl) {
1091
+ return (await this.db.all("SELECT mintUrl, id, amount, secret, C, dleqJson, witnessJson, state, usedByOperationId, createdByOperationId FROM coco_cashu_proofs WHERE mintUrl = ? AND state = \"ready\" AND usedByOperationId IS NULL", [mintUrl])).map(rowToProof);
1092
+ }
1093
+ async getReservedProofs() {
1094
+ return (await this.db.all("SELECT mintUrl, id, amount, secret, C, dleqJson, witnessJson, state, usedByOperationId, createdByOperationId FROM coco_cashu_proofs WHERE state = \"ready\" AND usedByOperationId IS NOT NULL")).map(rowToProof);
1095
+ }
1096
+ };
1097
+
1098
+ //#endregion
1099
+ //#region src/repositories/MintQuoteRepository.ts
1100
+ var ExpoMintQuoteRepository = class {
1101
+ db;
1102
+ constructor(db) {
1103
+ this.db = db;
1104
+ }
1105
+ async getMintQuote(mintUrl, quoteId) {
1106
+ const row = await this.db.get(`SELECT mintUrl, quote, state, request, amount, unit, expiry, pubkey
1107
+ FROM coco_cashu_mint_quotes WHERE mintUrl = ? AND quote = ? LIMIT 1`, [mintUrl, quoteId]);
1108
+ if (!row) return null;
1109
+ return {
1110
+ mintUrl: row.mintUrl,
1111
+ quote: row.quote,
1112
+ state: row.state,
1113
+ request: row.request,
1114
+ amount: row.amount,
1115
+ unit: row.unit,
1116
+ expiry: row.expiry,
1117
+ pubkey: row.pubkey ?? void 0
1118
+ };
1119
+ }
1120
+ async addMintQuote(quote) {
1121
+ await this.db.run(`INSERT INTO coco_cashu_mint_quotes (mintUrl, quote, state, request, amount, unit, expiry, pubkey)
1122
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
1123
+ ON CONFLICT(mintUrl, quote) DO UPDATE SET
1124
+ state=excluded.state,
1125
+ request=excluded.request,
1126
+ amount=excluded.amount,
1127
+ unit=excluded.unit,
1128
+ expiry=excluded.expiry,
1129
+ pubkey=excluded.pubkey`, [
1130
+ quote.mintUrl,
1131
+ quote.quote,
1132
+ quote.state,
1133
+ quote.request,
1134
+ quote.amount,
1135
+ quote.unit,
1136
+ quote.expiry,
1137
+ quote.pubkey ?? null
1138
+ ]);
1139
+ }
1140
+ async setMintQuoteState(mintUrl, quoteId, state) {
1141
+ await this.db.run("UPDATE coco_cashu_mint_quotes SET state = ? WHERE mintUrl = ? AND quote = ?", [
1142
+ state,
1143
+ mintUrl,
1144
+ quoteId
1145
+ ]);
1146
+ }
1147
+ async getPendingMintQuotes() {
1148
+ return (await this.db.all(`SELECT mintUrl, quote, state, request, amount, unit, expiry, pubkey
1149
+ FROM coco_cashu_mint_quotes WHERE state != 'ISSUED'`)).map((row) => ({
1150
+ mintUrl: row.mintUrl,
1151
+ quote: row.quote,
1152
+ state: row.state,
1153
+ request: row.request,
1154
+ amount: row.amount,
1155
+ unit: row.unit,
1156
+ expiry: row.expiry,
1157
+ pubkey: row.pubkey ?? void 0
1158
+ }));
1159
+ }
1160
+ };
1161
+
1162
+ //#endregion
1163
+ //#region src/repositories/MeltQuoteRepository.ts
1164
+ var ExpoMeltQuoteRepository = class {
1165
+ db;
1166
+ constructor(db) {
1167
+ this.db = db;
1168
+ }
1169
+ async getMeltQuote(mintUrl, quoteId) {
1170
+ const row = await this.db.get(`SELECT mintUrl, quote, state, request, amount, unit, expiry, fee_reserve, payment_preimage
1171
+ FROM coco_cashu_melt_quotes WHERE mintUrl = ? AND quote = ? LIMIT 1`, [mintUrl, quoteId]);
1172
+ if (!row) return null;
1173
+ return {
1174
+ mintUrl: row.mintUrl,
1175
+ quote: row.quote,
1176
+ state: row.state,
1177
+ request: row.request,
1178
+ amount: row.amount,
1179
+ unit: row.unit,
1180
+ expiry: row.expiry,
1181
+ fee_reserve: row.fee_reserve,
1182
+ payment_preimage: row.payment_preimage
1183
+ };
1184
+ }
1185
+ async addMeltQuote(quote) {
1186
+ await this.db.run(`INSERT INTO coco_cashu_melt_quotes (mintUrl, quote, state, request, amount, unit, expiry, fee_reserve, payment_preimage)
1187
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1188
+ ON CONFLICT(mintUrl, quote) DO UPDATE SET
1189
+ state=excluded.state,
1190
+ request=excluded.request,
1191
+ amount=excluded.amount,
1192
+ unit=excluded.unit,
1193
+ expiry=excluded.expiry,
1194
+ fee_reserve=excluded.fee_reserve,
1195
+ payment_preimage=excluded.payment_preimage`, [
1196
+ quote.mintUrl,
1197
+ quote.quote,
1198
+ quote.state,
1199
+ quote.request,
1200
+ quote.amount,
1201
+ quote.unit,
1202
+ quote.expiry,
1203
+ quote.fee_reserve,
1204
+ quote.payment_preimage ?? null
1205
+ ]);
1206
+ }
1207
+ async setMeltQuoteState(mintUrl, quoteId, state) {
1208
+ await this.db.run("UPDATE coco_cashu_melt_quotes SET state = ? WHERE mintUrl = ? AND quote = ?", [
1209
+ state,
1210
+ mintUrl,
1211
+ quoteId
1212
+ ]);
1213
+ }
1214
+ async getPendingMeltQuotes() {
1215
+ return (await this.db.all(`SELECT mintUrl, quote, state, request, amount, unit, expiry, fee_reserve, payment_preimage
1216
+ FROM coco_cashu_melt_quotes WHERE state != 'PAID'`)).map((row) => ({
1217
+ mintUrl: row.mintUrl,
1218
+ quote: row.quote,
1219
+ state: row.state,
1220
+ request: row.request,
1221
+ amount: row.amount,
1222
+ unit: row.unit,
1223
+ expiry: row.expiry,
1224
+ fee_reserve: row.fee_reserve,
1225
+ payment_preimage: row.payment_preimage
1226
+ }));
1227
+ }
1228
+ };
1229
+
1230
+ //#endregion
1231
+ //#region src/repositories/HistoryRepository.ts
1232
+ var ExpoHistoryRepository = class {
1233
+ db;
1234
+ constructor(db) {
1235
+ this.db = db;
1236
+ }
1237
+ async getMintHistoryEntry(mintUrl, quoteId) {
1238
+ const row = await this.db.get(`SELECT id, mintUrl, type, unit, amount, createdAt, quoteId, state, paymentRequest, tokenJson, metadata, operationId
1239
+ FROM coco_cashu_history WHERE mintUrl = ? AND quoteId = ? AND type = 'mint'
1240
+ ORDER BY createdAt DESC, id DESC LIMIT 1`, [mintUrl, quoteId]);
1241
+ if (!row) return null;
1242
+ const entry = this.rowToEntry(row);
1243
+ return entry.type === "mint" ? entry : null;
1244
+ }
1245
+ async getMeltHistoryEntry(mintUrl, quoteId) {
1246
+ const row = await this.db.get(`SELECT id, mintUrl, type, unit, amount, createdAt, quoteId, state, paymentRequest, tokenJson, metadata, operationId
1247
+ FROM coco_cashu_history WHERE mintUrl = ? AND quoteId = ? AND type = 'melt'
1248
+ ORDER BY createdAt DESC, id DESC LIMIT 1`, [mintUrl, quoteId]);
1249
+ if (!row) return null;
1250
+ const entry = this.rowToEntry(row);
1251
+ return entry.type === "melt" ? entry : null;
1252
+ }
1253
+ async getSendHistoryEntry(mintUrl, operationId) {
1254
+ const row = await this.db.get(`SELECT id, mintUrl, type, unit, amount, createdAt, quoteId, state, paymentRequest, tokenJson, metadata, operationId
1255
+ FROM coco_cashu_history WHERE mintUrl = ? AND operationId = ? AND type = 'send'
1256
+ ORDER BY createdAt DESC, id DESC LIMIT 1`, [mintUrl, operationId]);
1257
+ if (!row) return null;
1258
+ const entry = this.rowToEntry(row);
1259
+ return entry.type === "send" ? entry : null;
1260
+ }
1261
+ async getPaginatedHistoryEntries(limit, offset) {
1262
+ return (await this.db.all(`SELECT id, mintUrl, type, unit, amount, createdAt, quoteId, state, paymentRequest, tokenJson, metadata, operationId
1263
+ FROM coco_cashu_history
1264
+ ORDER BY createdAt DESC, id DESC
1265
+ LIMIT ? OFFSET ?`, [limit, offset])).map((r) => this.rowToEntry(r));
1266
+ }
1267
+ async getHistoryEntryById(id) {
1268
+ const row = await this.db.get(`SELECT id, mintUrl, type, unit, amount, createdAt, quoteId, state, paymentRequest, tokenJson, metadata, operationId
1269
+ FROM coco_cashu_history WHERE id = ?`, [id]);
1270
+ if (!row) return null;
1271
+ return this.rowToEntry(row);
1272
+ }
1273
+ async addHistoryEntry(history) {
1274
+ const baseParams = [
1275
+ history.mintUrl,
1276
+ history.type,
1277
+ history.unit,
1278
+ history.amount,
1279
+ history.createdAt
1280
+ ];
1281
+ let quoteId = null;
1282
+ let state = null;
1283
+ let paymentRequest = null;
1284
+ let tokenJson = null;
1285
+ let metadata = history.metadata ? JSON.stringify(history.metadata) : null;
1286
+ let operationId = null;
1287
+ switch (history.type) {
1288
+ case "mint":
1289
+ quoteId = history.quoteId;
1290
+ state = history.state;
1291
+ paymentRequest = history.paymentRequest;
1292
+ break;
1293
+ case "melt":
1294
+ quoteId = history.quoteId;
1295
+ state = history.state;
1296
+ break;
1297
+ case "send":
1298
+ tokenJson = history.token ? JSON.stringify(history.token) : null;
1299
+ operationId = history.operationId;
1300
+ state = history.state;
1301
+ break;
1302
+ case "receive":
1303
+ tokenJson = history.token ? JSON.stringify(history.token) : null;
1304
+ break;
1305
+ }
1306
+ const id = (await this.db.run(`INSERT INTO coco_cashu_history (mintUrl, type, unit, amount, createdAt, quoteId, state, paymentRequest, tokenJson, metadata, operationId)
1307
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
1308
+ ...baseParams,
1309
+ quoteId,
1310
+ state,
1311
+ paymentRequest,
1312
+ tokenJson,
1313
+ metadata,
1314
+ operationId
1315
+ ])).lastID;
1316
+ return this.getById(id);
1317
+ }
1318
+ async updateHistoryMintEntry(mintUrl, quoteId, state) {
1319
+ await this.db.run(`UPDATE coco_cashu_history SET state = ? WHERE mintUrl = ? AND quoteId = ? AND type = 'mint'`, [
1320
+ state,
1321
+ mintUrl,
1322
+ quoteId
1323
+ ]);
1324
+ const row = await this.db.get(`SELECT id, mintUrl, type, unit, amount, createdAt, quoteId, state, paymentRequest, tokenJson, metadata
1325
+ FROM coco_cashu_history WHERE mintUrl = ? AND quoteId = ? AND type = 'mint'
1326
+ ORDER BY createdAt DESC, id DESC LIMIT 1`, [mintUrl, quoteId]);
1327
+ if (!row) throw new Error("Updated mint history entry not found");
1328
+ return this.rowToEntry(row);
1329
+ }
1330
+ async updateHistoryMeltEntry(mintUrl, quoteId, state) {
1331
+ await this.db.run(`UPDATE coco_cashu_history SET state = ? WHERE mintUrl = ? AND quoteId = ? AND type = 'melt'`, [
1332
+ state,
1333
+ mintUrl,
1334
+ quoteId
1335
+ ]);
1336
+ const row = await this.db.get(`SELECT id, mintUrl, type, unit, amount, createdAt, quoteId, state, paymentRequest, tokenJson, metadata
1337
+ FROM coco_cashu_history WHERE mintUrl = ? AND quoteId = ? AND type = 'melt'
1338
+ ORDER BY createdAt DESC, id DESC LIMIT 1`, [mintUrl, quoteId]);
1339
+ if (!row) throw new Error("Updated melt history entry not found");
1340
+ return this.rowToEntry(row);
1341
+ }
1342
+ async updateHistoryEntry(history) {
1343
+ let state = null;
1344
+ let paymentRequest = null;
1345
+ let tokenJson = null;
1346
+ if (history.type === "mint") {
1347
+ if (!history.quoteId) throw new Error("quoteId required for mint entry");
1348
+ state = history.state;
1349
+ paymentRequest = history.paymentRequest;
1350
+ await this.db.run(`UPDATE coco_cashu_history SET unit = ?, amount = ?, state = ?, paymentRequest = ?, metadata = ?
1351
+ WHERE mintUrl = ? AND quoteId = ? AND type = 'mint'`, [
1352
+ history.unit,
1353
+ history.amount,
1354
+ state,
1355
+ paymentRequest,
1356
+ history.metadata ? JSON.stringify(history.metadata) : null,
1357
+ history.mintUrl,
1358
+ history.quoteId
1359
+ ]);
1360
+ const row = await this.db.get(`SELECT id, mintUrl, type, unit, amount, createdAt, quoteId, state, paymentRequest, tokenJson, metadata, operationId
1361
+ FROM coco_cashu_history WHERE mintUrl = ? AND quoteId = ? AND type = 'mint'
1362
+ ORDER BY createdAt DESC, id DESC LIMIT 1`, [history.mintUrl, history.quoteId]);
1363
+ if (!row) throw new Error("Updated history entry not found");
1364
+ return this.rowToEntry(row);
1365
+ } else if (history.type === "melt") {
1366
+ if (!history.quoteId) throw new Error("quoteId required for melt entry");
1367
+ state = history.state;
1368
+ await this.db.run(`UPDATE coco_cashu_history SET unit = ?, amount = ?, state = ?, metadata = ?
1369
+ WHERE mintUrl = ? AND quoteId = ? AND type = 'melt'`, [
1370
+ history.unit,
1371
+ history.amount,
1372
+ state,
1373
+ history.metadata ? JSON.stringify(history.metadata) : null,
1374
+ history.mintUrl,
1375
+ history.quoteId
1376
+ ]);
1377
+ const row = await this.db.get(`SELECT id, mintUrl, type, unit, amount, createdAt, quoteId, state, paymentRequest, tokenJson, metadata, operationId
1378
+ FROM coco_cashu_history WHERE mintUrl = ? AND quoteId = ? AND type = 'melt'
1379
+ ORDER BY createdAt DESC, id DESC LIMIT 1`, [history.mintUrl, history.quoteId]);
1380
+ if (!row) throw new Error("Updated history entry not found");
1381
+ return this.rowToEntry(row);
1382
+ } else if (history.type === "send") {
1383
+ if (!history.operationId) throw new Error("operationId required for send entry");
1384
+ state = history.state;
1385
+ tokenJson = history.token ? JSON.stringify(history.token) : null;
1386
+ await this.db.run(`UPDATE coco_cashu_history SET unit = ?, amount = ?, state = ?, tokenJson = ?, metadata = ?
1387
+ WHERE mintUrl = ? AND operationId = ? AND type = 'send'`, [
1388
+ history.unit,
1389
+ history.amount,
1390
+ state,
1391
+ tokenJson,
1392
+ history.metadata ? JSON.stringify(history.metadata) : null,
1393
+ history.mintUrl,
1394
+ history.operationId
1395
+ ]);
1396
+ const row = await this.db.get(`SELECT id, mintUrl, type, unit, amount, createdAt, quoteId, state, paymentRequest, tokenJson, metadata, operationId
1397
+ FROM coco_cashu_history WHERE mintUrl = ? AND operationId = ? AND type = 'send'
1398
+ ORDER BY createdAt DESC, id DESC LIMIT 1`, [history.mintUrl, history.operationId]);
1399
+ if (!row) throw new Error("Updated history entry not found");
1400
+ return this.rowToEntry(row);
1401
+ } else throw new Error("updateHistoryEntry does not support receive entries");
1402
+ }
1403
+ async updateSendHistoryState(mintUrl, operationId, state) {
1404
+ await this.db.run(`UPDATE coco_cashu_history SET state = ?
1405
+ WHERE mintUrl = ? AND operationId = ? AND type = 'send'`, [
1406
+ state,
1407
+ mintUrl,
1408
+ operationId
1409
+ ]);
1410
+ }
1411
+ async deleteHistoryEntry(mintUrl, quoteId) {
1412
+ await this.db.run("DELETE FROM coco_cashu_history WHERE mintUrl = ? AND quoteId = ?", [mintUrl, quoteId]);
1413
+ }
1414
+ async getById(id) {
1415
+ const row = await this.db.get(`SELECT id, mintUrl, type, unit, amount, createdAt, quoteId, state, paymentRequest, tokenJson, metadata, operationId
1416
+ FROM coco_cashu_history WHERE id = ? LIMIT 1`, [id]);
1417
+ if (!row) throw new Error("History entry not found");
1418
+ return this.rowToEntry(row);
1419
+ }
1420
+ rowToEntry(row) {
1421
+ const base = {
1422
+ id: String(row.id),
1423
+ createdAt: row.createdAt,
1424
+ mintUrl: row.mintUrl,
1425
+ unit: row.unit,
1426
+ metadata: row.metadata ? JSON.parse(row.metadata) : void 0
1427
+ };
1428
+ if (row.type === "mint") return {
1429
+ ...base,
1430
+ type: "mint",
1431
+ paymentRequest: row.paymentRequest ?? "",
1432
+ quoteId: row.quoteId ?? "",
1433
+ state: row.state ?? "UNPAID",
1434
+ amount: row.amount
1435
+ };
1436
+ if (row.type === "melt") return {
1437
+ ...base,
1438
+ type: "melt",
1439
+ quoteId: row.quoteId ?? "",
1440
+ state: row.state ?? "UNPAID",
1441
+ amount: row.amount
1442
+ };
1443
+ if (row.type === "send") return {
1444
+ ...base,
1445
+ type: "send",
1446
+ amount: row.amount,
1447
+ operationId: row.operationId ?? "",
1448
+ state: row.state ?? "pending",
1449
+ token: row.tokenJson ? JSON.parse(row.tokenJson) : void 0
1450
+ };
1451
+ const token = row.tokenJson ? JSON.parse(row.tokenJson) : void 0;
1452
+ return {
1453
+ ...base,
1454
+ type: "receive",
1455
+ amount: row.amount,
1456
+ token
1457
+ };
1458
+ }
1459
+ };
1460
+
1461
+ //#endregion
1462
+ //#region src/repositories/SendOperationRepository.ts
1463
+ function parseToken(tokenJson) {
1464
+ return tokenJson ? JSON.parse(tokenJson) : void 0;
1465
+ }
1466
+ function serializeToken(operation) {
1467
+ const maybeTokenOperation = operation;
1468
+ return maybeTokenOperation.token ? JSON.stringify(maybeTokenOperation.token) : null;
1469
+ }
1470
+ function rowToOperation$3(row) {
1471
+ const base = {
1472
+ id: row.id,
1473
+ mintUrl: row.mintUrl,
1474
+ amount: row.amount,
1475
+ createdAt: row.createdAt * 1e3,
1476
+ updatedAt: row.updatedAt * 1e3,
1477
+ error: row.error ?? void 0,
1478
+ method: row.method,
1479
+ methodData: JSON.parse(row.methodDataJson)
1480
+ };
1481
+ if (row.state === "init") return {
1482
+ ...base,
1483
+ state: "init"
1484
+ };
1485
+ const preparedData = {
1486
+ needsSwap: row.needsSwap === 1,
1487
+ fee: row.fee ?? 0,
1488
+ inputAmount: row.inputAmount ?? 0,
1489
+ inputProofSecrets: row.inputProofSecretsJson ? JSON.parse(row.inputProofSecretsJson) : [],
1490
+ outputData: row.outputDataJson ? JSON.parse(row.outputDataJson) : void 0
1491
+ };
1492
+ switch (row.state) {
1493
+ case "prepared": return {
1494
+ ...base,
1495
+ state: "prepared",
1496
+ ...preparedData
1497
+ };
1498
+ case "executing": return {
1499
+ ...base,
1500
+ state: "executing",
1501
+ ...preparedData
1502
+ };
1503
+ case "pending": return {
1504
+ ...base,
1505
+ state: "pending",
1506
+ ...preparedData,
1507
+ token: parseToken(row.tokenJson)
1508
+ };
1509
+ case "finalized": return {
1510
+ ...base,
1511
+ state: "finalized",
1512
+ ...preparedData,
1513
+ token: parseToken(row.tokenJson)
1514
+ };
1515
+ case "rolling_back": return {
1516
+ ...base,
1517
+ state: "rolling_back",
1518
+ ...preparedData,
1519
+ token: parseToken(row.tokenJson)
1520
+ };
1521
+ case "rolled_back": return {
1522
+ ...base,
1523
+ state: "rolled_back",
1524
+ ...preparedData,
1525
+ token: parseToken(row.tokenJson)
1526
+ };
1527
+ default: throw new Error(`Unknown state: ${row.state}`);
1528
+ }
1529
+ }
1530
+ function operationToParams$3(op) {
1531
+ const createdAtSeconds = Math.floor(op.createdAt / 1e3);
1532
+ const updatedAtSeconds = Math.floor(op.updatedAt / 1e3);
1533
+ if (op.state === "init") return [
1534
+ op.id,
1535
+ op.mintUrl,
1536
+ op.amount,
1537
+ op.state,
1538
+ createdAtSeconds,
1539
+ updatedAtSeconds,
1540
+ op.error ?? null,
1541
+ op.method,
1542
+ JSON.stringify(op.methodData),
1543
+ null,
1544
+ null,
1545
+ null,
1546
+ null,
1547
+ null,
1548
+ null
1549
+ ];
1550
+ return [
1551
+ op.id,
1552
+ op.mintUrl,
1553
+ op.amount,
1554
+ op.state,
1555
+ createdAtSeconds,
1556
+ updatedAtSeconds,
1557
+ op.error ?? null,
1558
+ op.method,
1559
+ JSON.stringify(op.methodData),
1560
+ op.needsSwap ? 1 : 0,
1561
+ op.fee,
1562
+ op.inputAmount,
1563
+ JSON.stringify(op.inputProofSecrets),
1564
+ op.outputData ? JSON.stringify(op.outputData) : null,
1565
+ serializeToken(op)
1566
+ ];
1567
+ }
1568
+ var ExpoSendOperationRepository = class {
1569
+ db;
1570
+ constructor(db) {
1571
+ this.db = db;
1572
+ }
1573
+ async create(operation) {
1574
+ if (await this.db.get("SELECT id FROM coco_cashu_send_operations WHERE id = ? LIMIT 1", [operation.id])) throw new Error(`SendOperation with id ${operation.id} already exists`);
1575
+ const params = operationToParams$3(operation);
1576
+ await this.db.run(`INSERT INTO coco_cashu_send_operations
1577
+ (id, mintUrl, amount, state, createdAt, updatedAt, error, method, methodDataJson, needsSwap, fee, inputAmount, inputProofSecretsJson, outputDataJson, tokenJson)
1578
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, params);
1579
+ }
1580
+ async update(operation) {
1581
+ if (!await this.db.get("SELECT id FROM coco_cashu_send_operations WHERE id = ? LIMIT 1", [operation.id])) throw new Error(`SendOperation with id ${operation.id} not found`);
1582
+ const updatedAtSeconds = getUnixTimeSeconds();
1583
+ if (operation.state === "init") await this.db.run(`UPDATE coco_cashu_send_operations
1584
+ SET state = ?, updatedAt = ?, error = ?
1585
+ WHERE id = ?`, [
1586
+ operation.state,
1587
+ updatedAtSeconds,
1588
+ operation.error ?? null,
1589
+ operation.id
1590
+ ]);
1591
+ else await this.db.run(`UPDATE coco_cashu_send_operations
1592
+ SET state = ?, updatedAt = ?, error = ?, needsSwap = ?, fee = ?, inputAmount = ?, inputProofSecretsJson = ?, outputDataJson = ?, tokenJson = ?
1593
+ WHERE id = ?`, [
1594
+ operation.state,
1595
+ updatedAtSeconds,
1596
+ operation.error ?? null,
1597
+ operation.needsSwap ? 1 : 0,
1598
+ operation.fee,
1599
+ operation.inputAmount,
1600
+ JSON.stringify(operation.inputProofSecrets),
1601
+ operation.outputData ? JSON.stringify(operation.outputData) : null,
1602
+ serializeToken(operation),
1603
+ operation.id
1604
+ ]);
1605
+ }
1606
+ async getById(id) {
1607
+ const row = await this.db.get("SELECT * FROM coco_cashu_send_operations WHERE id = ?", [id]);
1608
+ return row ? rowToOperation$3(row) : null;
1609
+ }
1610
+ async getByState(state) {
1611
+ return (await this.db.all("SELECT * FROM coco_cashu_send_operations WHERE state = ?", [state])).map(rowToOperation$3);
1612
+ }
1613
+ async getPending() {
1614
+ return (await this.db.all(`SELECT * FROM coco_cashu_send_operations WHERE state IN ('executing', 'pending', 'rolling_back')`)).map(rowToOperation$3);
1615
+ }
1616
+ async getByMintUrl(mintUrl) {
1617
+ return (await this.db.all("SELECT * FROM coco_cashu_send_operations WHERE mintUrl = ?", [mintUrl])).map(rowToOperation$3);
1618
+ }
1619
+ async delete(id) {
1620
+ await this.db.run("DELETE FROM coco_cashu_send_operations WHERE id = ?", [id]);
1621
+ }
1622
+ };
1623
+
1624
+ //#endregion
1625
+ //#region src/repositories/MeltOperationRepository.ts
1626
+ const preparedStates = [
1627
+ "prepared",
1628
+ "executing",
1629
+ "pending",
1630
+ "finalized",
1631
+ "rolling_back",
1632
+ "rolled_back"
1633
+ ];
1634
+ const isPreparedState = (state) => preparedStates.includes(state);
1635
+ const rowToOperation$2 = (row) => {
1636
+ const base = {
1637
+ id: row.id,
1638
+ mintUrl: row.mintUrl,
1639
+ method: row.method,
1640
+ methodData: JSON.parse(row.methodDataJson),
1641
+ createdAt: row.createdAt * 1e3,
1642
+ updatedAt: row.updatedAt * 1e3,
1643
+ error: row.error ?? void 0
1644
+ };
1645
+ if (!isPreparedState(row.state)) return {
1646
+ ...base,
1647
+ state: "init"
1648
+ };
1649
+ const preparedData = {
1650
+ quoteId: row.quoteId ?? "",
1651
+ amount: row.amount ?? 0,
1652
+ fee_reserve: row.fee_reserve ?? 0,
1653
+ swap_fee: row.swap_fee ?? 0,
1654
+ needsSwap: row.needsSwap === 1,
1655
+ inputAmount: row.inputAmount ?? 0,
1656
+ inputProofSecrets: row.inputProofSecretsJson ? JSON.parse(row.inputProofSecretsJson) : [],
1657
+ changeOutputData: row.changeOutputDataJson ? JSON.parse(row.changeOutputDataJson) : {
1658
+ keep: [],
1659
+ send: []
1660
+ },
1661
+ swapOutputData: row.swapOutputDataJson ? JSON.parse(row.swapOutputDataJson) : void 0
1662
+ };
1663
+ const operation = {
1664
+ ...base,
1665
+ state: row.state,
1666
+ ...preparedData
1667
+ };
1668
+ if (row.state === "finalized") return {
1669
+ ...operation,
1670
+ changeAmount: row.changeAmount ?? void 0,
1671
+ effectiveFee: row.effectiveFee ?? void 0,
1672
+ finalizedData: row.finalizedDataJson ? JSON.parse(row.finalizedDataJson) : void 0
1673
+ };
1674
+ return operation;
1675
+ };
1676
+ const operationToParams$2 = (operation) => {
1677
+ const createdAtSeconds = Math.floor(operation.createdAt / 1e3);
1678
+ const updatedAtSeconds = Math.floor(operation.updatedAt / 1e3);
1679
+ const methodDataJson = JSON.stringify(operation.methodData);
1680
+ if (operation.state === "init") return [
1681
+ operation.id,
1682
+ operation.mintUrl,
1683
+ operation.state,
1684
+ createdAtSeconds,
1685
+ updatedAtSeconds,
1686
+ operation.error ?? null,
1687
+ operation.method,
1688
+ methodDataJson,
1689
+ null,
1690
+ null,
1691
+ null,
1692
+ null,
1693
+ null,
1694
+ null,
1695
+ null,
1696
+ null,
1697
+ null,
1698
+ null,
1699
+ null,
1700
+ null
1701
+ ];
1702
+ const settlement = operation;
1703
+ const changeAmount = operation.state === "finalized" ? settlement.changeAmount ?? null : null;
1704
+ const effectiveFee = operation.state === "finalized" ? settlement.effectiveFee ?? null : null;
1705
+ const finalizedDataJson = operation.state === "finalized" && settlement.finalizedData !== void 0 ? JSON.stringify(settlement.finalizedData) : null;
1706
+ return [
1707
+ operation.id,
1708
+ operation.mintUrl,
1709
+ operation.state,
1710
+ createdAtSeconds,
1711
+ updatedAtSeconds,
1712
+ operation.error ?? null,
1713
+ operation.method,
1714
+ methodDataJson,
1715
+ operation.quoteId,
1716
+ operation.amount,
1717
+ operation.fee_reserve,
1718
+ operation.swap_fee,
1719
+ operation.needsSwap ? 1 : 0,
1720
+ operation.inputAmount,
1721
+ JSON.stringify(operation.inputProofSecrets),
1722
+ JSON.stringify(operation.changeOutputData),
1723
+ operation.swapOutputData ? JSON.stringify(operation.swapOutputData) : null,
1724
+ changeAmount,
1725
+ effectiveFee,
1726
+ finalizedDataJson
1727
+ ];
1728
+ };
1729
+ var ExpoMeltOperationRepository = class {
1730
+ db;
1731
+ constructor(db) {
1732
+ this.db = db;
1733
+ }
1734
+ async create(operation) {
1735
+ if (operation.state === "failed") throw new Error("Cannot persist failed melt operation");
1736
+ if (await this.db.get("SELECT id FROM coco_cashu_melt_operations WHERE id = ? LIMIT 1", [operation.id])) throw new Error(`MeltOperation with id ${operation.id} already exists`);
1737
+ const params = operationToParams$2(operation);
1738
+ await this.db.run(`INSERT INTO coco_cashu_melt_operations
1739
+ (id, mintUrl, state, createdAt, updatedAt, error, method, methodDataJson, quoteId, amount, fee_reserve, swap_fee, needsSwap, inputAmount, inputProofSecretsJson, changeOutputDataJson, swapOutputDataJson, changeAmount, effectiveFee, finalizedDataJson)
1740
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, params);
1741
+ }
1742
+ async update(operation) {
1743
+ if (operation.state === "failed") throw new Error("Cannot persist failed melt operation");
1744
+ if (!await this.db.get("SELECT id FROM coco_cashu_melt_operations WHERE id = ? LIMIT 1", [operation.id])) throw new Error(`MeltOperation with id ${operation.id} not found`);
1745
+ const updatedAtSeconds = getUnixTimeSeconds();
1746
+ if (operation.state === "init") {
1747
+ await this.db.run(`UPDATE coco_cashu_melt_operations
1748
+ SET state = ?, updatedAt = ?, error = ?, method = ?, methodDataJson = ?
1749
+ WHERE id = ?`, [
1750
+ operation.state,
1751
+ updatedAtSeconds,
1752
+ operation.error ?? null,
1753
+ operation.method,
1754
+ JSON.stringify(operation.methodData),
1755
+ operation.id
1756
+ ]);
1757
+ return;
1758
+ }
1759
+ const settlement = operation;
1760
+ await this.db.run(`UPDATE coco_cashu_melt_operations
1761
+ SET state = ?, updatedAt = ?, error = ?, method = ?, methodDataJson = ?, quoteId = ?, amount = ?, fee_reserve = ?, swap_fee = ?, needsSwap = ?, inputAmount = ?, inputProofSecretsJson = ?, changeOutputDataJson = ?, swapOutputDataJson = ?, changeAmount = ?, effectiveFee = ?, finalizedDataJson = ?
1762
+ WHERE id = ?`, [
1763
+ operation.state,
1764
+ updatedAtSeconds,
1765
+ operation.error ?? null,
1766
+ operation.method,
1767
+ JSON.stringify(operation.methodData),
1768
+ operation.quoteId,
1769
+ operation.amount,
1770
+ operation.fee_reserve,
1771
+ operation.swap_fee,
1772
+ operation.needsSwap ? 1 : 0,
1773
+ operation.inputAmount,
1774
+ JSON.stringify(operation.inputProofSecrets),
1775
+ JSON.stringify(operation.changeOutputData),
1776
+ operation.swapOutputData ? JSON.stringify(operation.swapOutputData) : null,
1777
+ operation.state === "finalized" ? settlement.changeAmount ?? null : null,
1778
+ operation.state === "finalized" ? settlement.effectiveFee ?? null : null,
1779
+ operation.state === "finalized" && settlement.finalizedData !== void 0 ? JSON.stringify(settlement.finalizedData) : null,
1780
+ operation.id
1781
+ ]);
1782
+ }
1783
+ async getById(id) {
1784
+ const row = await this.db.get("SELECT * FROM coco_cashu_melt_operations WHERE id = ?", [id]);
1785
+ return row ? rowToOperation$2(row) : null;
1786
+ }
1787
+ async getByState(state) {
1788
+ return (await this.db.all("SELECT * FROM coco_cashu_melt_operations WHERE state = ?", [state])).map(rowToOperation$2);
1789
+ }
1790
+ async getPending() {
1791
+ return (await this.db.all("SELECT * FROM coco_cashu_melt_operations WHERE state IN (\"executing\", \"pending\")")).map(rowToOperation$2);
1792
+ }
1793
+ async getByMintUrl(mintUrl) {
1794
+ return (await this.db.all("SELECT * FROM coco_cashu_melt_operations WHERE mintUrl = ?", [mintUrl])).map(rowToOperation$2);
1795
+ }
1796
+ async getByQuoteId(mintUrl, quoteId) {
1797
+ return (await this.db.all("SELECT * FROM coco_cashu_melt_operations WHERE mintUrl = ? AND quoteId = ?", [mintUrl, quoteId])).map(rowToOperation$2);
1798
+ }
1799
+ async delete(id) {
1800
+ await this.db.run("DELETE FROM coco_cashu_melt_operations WHERE id = ?", [id]);
1801
+ }
1802
+ };
1803
+
1804
+ //#endregion
1805
+ //#region src/repositories/AuthSessionRepository.ts
1806
+ function rowToSession(row) {
1807
+ return {
1808
+ mintUrl: row.mintUrl,
1809
+ accessToken: row.accessToken,
1810
+ refreshToken: row.refreshToken ?? void 0,
1811
+ expiresAt: row.expiresAt,
1812
+ scope: row.scope ?? void 0,
1813
+ batPool: row.batPoolJson ? JSON.parse(row.batPoolJson) : void 0
1814
+ };
1815
+ }
1816
+ var ExpoAuthSessionRepository = class {
1817
+ db;
1818
+ constructor(db) {
1819
+ this.db = db;
1820
+ }
1821
+ async getSession(mintUrl) {
1822
+ const row = await this.db.get("SELECT mintUrl, accessToken, refreshToken, expiresAt, scope, batPoolJson FROM coco_cashu_auth_sessions WHERE mintUrl = ? LIMIT 1", [mintUrl]);
1823
+ if (!row) return null;
1824
+ return rowToSession(row);
1825
+ }
1826
+ async saveSession(session) {
1827
+ await this.db.run(`INSERT INTO coco_cashu_auth_sessions (mintUrl, accessToken, refreshToken, expiresAt, scope, batPoolJson)
1828
+ VALUES (?, ?, ?, ?, ?, ?)
1829
+ ON CONFLICT(mintUrl) DO UPDATE SET
1830
+ accessToken=excluded.accessToken,
1831
+ refreshToken=excluded.refreshToken,
1832
+ expiresAt=excluded.expiresAt,
1833
+ scope=excluded.scope,
1834
+ batPoolJson=excluded.batPoolJson`, [
1835
+ session.mintUrl,
1836
+ session.accessToken,
1837
+ session.refreshToken ?? null,
1838
+ session.expiresAt,
1839
+ session.scope ?? null,
1840
+ session.batPool ? JSON.stringify(session.batPool) : null
1841
+ ]);
1842
+ }
1843
+ async deleteSession(mintUrl) {
1844
+ await this.db.run("DELETE FROM coco_cashu_auth_sessions WHERE mintUrl = ?", [mintUrl]);
1845
+ }
1846
+ async getAllSessions() {
1847
+ return (await this.db.all("SELECT mintUrl, accessToken, refreshToken, expiresAt, scope, batPoolJson FROM coco_cashu_auth_sessions")).map(rowToSession);
1848
+ }
1849
+ };
1850
+
1851
+ //#endregion
1852
+ //#region src/repositories/MintOperationRepository.ts
1853
+ const persistedStates = [
1854
+ "pending",
1855
+ "executing",
1856
+ "finalized",
1857
+ "failed"
1858
+ ];
1859
+ const isPersistedState = (state) => persistedStates.includes(state);
1860
+ const normalizeState = (state) => {
1861
+ if (state === "pending" || state === "executing" || state === "finalized" || state === "failed") return state;
1862
+ return "init";
1863
+ };
1864
+ const rowToOperation$1 = (row) => {
1865
+ const base = {
1866
+ id: row.id,
1867
+ mintUrl: row.mintUrl,
1868
+ method: row.method,
1869
+ methodData: JSON.parse(row.methodDataJson),
1870
+ createdAt: row.createdAt * 1e3,
1871
+ updatedAt: row.updatedAt * 1e3,
1872
+ error: row.error ?? void 0,
1873
+ ...row.terminalFailureJson ? { terminalFailure: JSON.parse(row.terminalFailureJson) } : {}
1874
+ };
1875
+ const intent = {
1876
+ amount: row.amount ?? 0,
1877
+ unit: row.unit ?? ""
1878
+ };
1879
+ if (!isPersistedState(row.state)) return {
1880
+ ...base,
1881
+ ...intent,
1882
+ state: "init",
1883
+ ...row.quoteId ? { quoteId: row.quoteId } : {}
1884
+ };
1885
+ return {
1886
+ ...base,
1887
+ ...intent,
1888
+ state: normalizeState(row.state),
1889
+ quoteId: row.quoteId ?? "",
1890
+ request: row.request ?? "",
1891
+ expiry: row.expiry ?? 0,
1892
+ pubkey: row.pubkey ?? void 0,
1893
+ lastObservedRemoteState: row.lastObservedRemoteState ?? void 0,
1894
+ lastObservedRemoteStateAt: row.lastObservedRemoteStateAt ?? void 0,
1895
+ outputData: row.outputDataJson ? JSON.parse(row.outputDataJson) : {
1896
+ keep: [],
1897
+ send: []
1898
+ }
1899
+ };
1900
+ };
1901
+ const operationToParams$1 = (operation) => {
1902
+ const createdAtSeconds = Math.floor(operation.createdAt / 1e3);
1903
+ const updatedAtSeconds = Math.floor(operation.updatedAt / 1e3);
1904
+ const methodDataJson = JSON.stringify(operation.methodData);
1905
+ if (operation.state === "init") return [
1906
+ operation.id,
1907
+ operation.mintUrl,
1908
+ operation.quoteId ?? null,
1909
+ operation.state,
1910
+ createdAtSeconds,
1911
+ updatedAtSeconds,
1912
+ operation.error ?? null,
1913
+ operation.method,
1914
+ methodDataJson,
1915
+ operation.amount,
1916
+ operation.unit,
1917
+ null,
1918
+ null,
1919
+ null,
1920
+ null,
1921
+ null,
1922
+ operation.terminalFailure ? JSON.stringify(operation.terminalFailure) : null,
1923
+ null
1924
+ ];
1925
+ return [
1926
+ operation.id,
1927
+ operation.mintUrl,
1928
+ operation.quoteId,
1929
+ operation.state,
1930
+ createdAtSeconds,
1931
+ updatedAtSeconds,
1932
+ operation.error ?? null,
1933
+ operation.method,
1934
+ methodDataJson,
1935
+ operation.amount,
1936
+ operation.unit,
1937
+ operation.request,
1938
+ operation.expiry,
1939
+ operation.pubkey ?? null,
1940
+ operation.lastObservedRemoteState ?? null,
1941
+ operation.lastObservedRemoteStateAt ?? null,
1942
+ operation.terminalFailure ? JSON.stringify(operation.terminalFailure) : null,
1943
+ JSON.stringify(operation.outputData)
1944
+ ];
1945
+ };
1946
+ var ExpoMintOperationRepository = class {
1947
+ db;
1948
+ constructor(db) {
1949
+ this.db = db;
1950
+ }
1951
+ async create(operation) {
1952
+ if (await this.db.get("SELECT id FROM coco_cashu_mint_operations WHERE id = ? LIMIT 1", [operation.id])) throw new Error(`MintOperation with id ${operation.id} already exists`);
1953
+ const params = operationToParams$1(operation);
1954
+ await this.db.run(`INSERT INTO coco_cashu_mint_operations
1955
+ (id, mintUrl, quoteId, state, createdAt, updatedAt, error, method, methodDataJson, amount, unit, request, expiry, pubkey, lastObservedRemoteState, lastObservedRemoteStateAt, terminalFailureJson, outputDataJson)
1956
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, params);
1957
+ }
1958
+ async update(operation) {
1959
+ if (!await this.db.get("SELECT id FROM coco_cashu_mint_operations WHERE id = ? LIMIT 1", [operation.id])) throw new Error(`MintOperation with id ${operation.id} not found`);
1960
+ const updatedAtSeconds = getUnixTimeSeconds();
1961
+ if (operation.state === "init") {
1962
+ await this.db.run(`UPDATE coco_cashu_mint_operations
1963
+ SET quoteId = ?, state = ?, updatedAt = ?, error = ?, method = ?, methodDataJson = ?, amount = ?, unit = ?, terminalFailureJson = ?
1964
+ WHERE id = ?`, [
1965
+ operation.quoteId ?? null,
1966
+ operation.state,
1967
+ updatedAtSeconds,
1968
+ operation.error ?? null,
1969
+ operation.method,
1970
+ JSON.stringify(operation.methodData),
1971
+ operation.amount,
1972
+ operation.unit,
1973
+ operation.terminalFailure ? JSON.stringify(operation.terminalFailure) : null,
1974
+ operation.id
1975
+ ]);
1976
+ return;
1977
+ }
1978
+ await this.db.run(`UPDATE coco_cashu_mint_operations
1979
+ SET quoteId = ?, state = ?, updatedAt = ?, error = ?, method = ?, methodDataJson = ?, amount = ?, unit = ?, request = ?, expiry = ?, pubkey = ?, lastObservedRemoteState = ?, lastObservedRemoteStateAt = ?, terminalFailureJson = ?, outputDataJson = ?
1980
+ WHERE id = ?`, [
1981
+ operation.quoteId,
1982
+ operation.state,
1983
+ updatedAtSeconds,
1984
+ operation.error ?? null,
1985
+ operation.method,
1986
+ JSON.stringify(operation.methodData),
1987
+ operation.amount,
1988
+ operation.unit,
1989
+ operation.request,
1990
+ operation.expiry,
1991
+ operation.pubkey ?? null,
1992
+ operation.lastObservedRemoteState ?? null,
1993
+ operation.lastObservedRemoteStateAt ?? null,
1994
+ operation.terminalFailure ? JSON.stringify(operation.terminalFailure) : null,
1995
+ JSON.stringify(operation.outputData),
1996
+ operation.id
1997
+ ]);
1998
+ }
1999
+ async getById(id) {
2000
+ const row = await this.db.get("SELECT * FROM coco_cashu_mint_operations WHERE id = ?", [id]);
2001
+ return row ? rowToOperation$1(row) : null;
2002
+ }
2003
+ async getByState(state) {
2004
+ return (await this.db.all("SELECT * FROM coco_cashu_mint_operations WHERE state = ?", [state])).map(rowToOperation$1);
2005
+ }
2006
+ async getPending() {
2007
+ return (await this.db.all("SELECT * FROM coco_cashu_mint_operations WHERE state IN (\"pending\", \"executing\")")).map(rowToOperation$1);
2008
+ }
2009
+ async getByMintUrl(mintUrl) {
2010
+ return (await this.db.all("SELECT * FROM coco_cashu_mint_operations WHERE mintUrl = ?", [mintUrl])).map(rowToOperation$1);
2011
+ }
2012
+ async getByQuoteId(mintUrl, quoteId) {
2013
+ return (await this.db.all("SELECT * FROM coco_cashu_mint_operations WHERE mintUrl = ? AND quoteId = ? ORDER BY updatedAt DESC", [mintUrl, quoteId])).map(rowToOperation$1);
2014
+ }
2015
+ async delete(id) {
2016
+ await this.db.run("DELETE FROM coco_cashu_mint_operations WHERE id = ?", [id]);
2017
+ }
2018
+ };
2019
+
2020
+ //#endregion
2021
+ //#region src/repositories/ReceiveOperationRepository.ts
2022
+ function rowToOperation(row) {
2023
+ const base = {
2024
+ id: row.id,
2025
+ mintUrl: row.mintUrl,
2026
+ amount: row.amount,
2027
+ inputProofs: row.inputProofsJson ? JSON.parse(row.inputProofsJson) : [],
2028
+ createdAt: row.createdAt * 1e3,
2029
+ updatedAt: row.updatedAt * 1e3,
2030
+ error: row.error ?? void 0
2031
+ };
2032
+ if (row.state === "init") return {
2033
+ ...base,
2034
+ state: "init"
2035
+ };
2036
+ const preparedData = {
2037
+ fee: row.fee ?? 0,
2038
+ outputData: row.outputDataJson ? JSON.parse(row.outputDataJson) : void 0
2039
+ };
2040
+ switch (row.state) {
2041
+ case "prepared": return {
2042
+ ...base,
2043
+ state: "prepared",
2044
+ ...preparedData
2045
+ };
2046
+ case "executing": return {
2047
+ ...base,
2048
+ state: "executing",
2049
+ ...preparedData
2050
+ };
2051
+ case "finalized": return {
2052
+ ...base,
2053
+ state: "finalized",
2054
+ ...preparedData
2055
+ };
2056
+ case "rolled_back": return {
2057
+ ...base,
2058
+ state: "rolled_back",
2059
+ ...preparedData
2060
+ };
2061
+ default: throw new Error(`Unknown state: ${row.state}`);
2062
+ }
2063
+ }
2064
+ function operationToParams(op) {
2065
+ const createdAtSeconds = Math.floor(op.createdAt / 1e3);
2066
+ const updatedAtSeconds = Math.floor(op.updatedAt / 1e3);
2067
+ if (op.state === "init") return [
2068
+ op.id,
2069
+ op.mintUrl,
2070
+ op.amount,
2071
+ op.state,
2072
+ createdAtSeconds,
2073
+ updatedAtSeconds,
2074
+ op.error ?? null,
2075
+ null,
2076
+ JSON.stringify(op.inputProofs),
2077
+ null
2078
+ ];
2079
+ return [
2080
+ op.id,
2081
+ op.mintUrl,
2082
+ op.amount,
2083
+ op.state,
2084
+ createdAtSeconds,
2085
+ updatedAtSeconds,
2086
+ op.error ?? null,
2087
+ op.fee,
2088
+ JSON.stringify(op.inputProofs),
2089
+ op.outputData ? JSON.stringify(op.outputData) : null
2090
+ ];
2091
+ }
2092
+ var ExpoReceiveOperationRepository = class {
2093
+ db;
2094
+ constructor(db) {
2095
+ this.db = db;
2096
+ }
2097
+ async create(operation) {
2098
+ if (await this.db.get("SELECT id FROM coco_cashu_receive_operations WHERE id = ? LIMIT 1", [operation.id])) throw new Error(`ReceiveOperation with id ${operation.id} already exists`);
2099
+ const params = operationToParams(operation);
2100
+ await this.db.run(`INSERT INTO coco_cashu_receive_operations
2101
+ (id, mintUrl, amount, state, createdAt, updatedAt, error, fee, inputProofsJson, outputDataJson)
2102
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, params);
2103
+ }
2104
+ async update(operation) {
2105
+ if (!await this.db.get("SELECT id FROM coco_cashu_receive_operations WHERE id = ? LIMIT 1", [operation.id])) throw new Error(`ReceiveOperation with id ${operation.id} not found`);
2106
+ const updatedAtSeconds = getUnixTimeSeconds();
2107
+ if (operation.state === "init") await this.db.run(`UPDATE coco_cashu_receive_operations
2108
+ SET state = ?, updatedAt = ?, error = ?, inputProofsJson = ?
2109
+ WHERE id = ?`, [
2110
+ operation.state,
2111
+ updatedAtSeconds,
2112
+ operation.error ?? null,
2113
+ JSON.stringify(operation.inputProofs),
2114
+ operation.id
2115
+ ]);
2116
+ else await this.db.run(`UPDATE coco_cashu_receive_operations
2117
+ SET state = ?, updatedAt = ?, error = ?, fee = ?, inputProofsJson = ?, outputDataJson = ?
2118
+ WHERE id = ?`, [
2119
+ operation.state,
2120
+ updatedAtSeconds,
2121
+ operation.error ?? null,
2122
+ operation.fee,
2123
+ JSON.stringify(operation.inputProofs),
2124
+ operation.outputData ? JSON.stringify(operation.outputData) : null,
2125
+ operation.id
2126
+ ]);
2127
+ }
2128
+ async getById(id) {
2129
+ const row = await this.db.get("SELECT * FROM coco_cashu_receive_operations WHERE id = ?", [id]);
2130
+ return row ? rowToOperation(row) : null;
2131
+ }
2132
+ async getByState(state) {
2133
+ return (await this.db.all("SELECT * FROM coco_cashu_receive_operations WHERE state = ?", [state])).map(rowToOperation);
2134
+ }
2135
+ async getPending() {
2136
+ return (await this.db.all("SELECT * FROM coco_cashu_receive_operations WHERE state IN ('executing')")).map(rowToOperation);
2137
+ }
2138
+ async getByMintUrl(mintUrl) {
2139
+ return (await this.db.all("SELECT * FROM coco_cashu_receive_operations WHERE mintUrl = ?", [mintUrl])).map(rowToOperation);
2140
+ }
2141
+ async delete(id) {
2142
+ await this.db.run("DELETE FROM coco_cashu_receive_operations WHERE id = ?", [id]);
2143
+ }
2144
+ };
2145
+
2146
+ //#endregion
2147
+ //#region src/index.ts
2148
+ var ExpoSqliteRepositories = class {
2149
+ mintRepository;
2150
+ keyRingRepository;
2151
+ counterRepository;
2152
+ keysetRepository;
2153
+ proofRepository;
2154
+ mintQuoteRepository;
2155
+ meltQuoteRepository;
2156
+ historyRepository;
2157
+ sendOperationRepository;
2158
+ meltOperationRepository;
2159
+ authSessionRepository;
2160
+ mintOperationRepository;
2161
+ receiveOperationRepository;
2162
+ db;
2163
+ constructor(options) {
2164
+ this.db = new ExpoSqliteDb(options);
2165
+ this.mintRepository = new ExpoMintRepository(this.db);
2166
+ this.keyRingRepository = new ExpoKeyRingRepository(this.db);
2167
+ this.counterRepository = new ExpoCounterRepository(this.db);
2168
+ this.keysetRepository = new ExpoKeysetRepository(this.db);
2169
+ this.proofRepository = new ExpoProofRepository(this.db);
2170
+ this.mintQuoteRepository = new ExpoMintQuoteRepository(this.db);
2171
+ this.meltQuoteRepository = new ExpoMeltQuoteRepository(this.db);
2172
+ this.historyRepository = new ExpoHistoryRepository(this.db);
2173
+ this.sendOperationRepository = new ExpoSendOperationRepository(this.db);
2174
+ this.meltOperationRepository = new ExpoMeltOperationRepository(this.db);
2175
+ this.authSessionRepository = new ExpoAuthSessionRepository(this.db);
2176
+ this.mintOperationRepository = new ExpoMintOperationRepository(this.db);
2177
+ this.receiveOperationRepository = new ExpoReceiveOperationRepository(this.db);
2178
+ }
2179
+ async init() {
2180
+ await ensureSchema(this.db);
2181
+ }
2182
+ async withTransaction(fn) {
2183
+ return this.db.transaction(async (txDb) => {
2184
+ return fn({
2185
+ mintRepository: new ExpoMintRepository(txDb),
2186
+ keyRingRepository: new ExpoKeyRingRepository(txDb),
2187
+ counterRepository: new ExpoCounterRepository(txDb),
2188
+ keysetRepository: new ExpoKeysetRepository(txDb),
2189
+ proofRepository: new ExpoProofRepository(txDb),
2190
+ mintQuoteRepository: new ExpoMintQuoteRepository(txDb),
2191
+ meltQuoteRepository: new ExpoMeltQuoteRepository(txDb),
2192
+ historyRepository: new ExpoHistoryRepository(txDb),
2193
+ sendOperationRepository: new ExpoSendOperationRepository(txDb),
2194
+ meltOperationRepository: new ExpoMeltOperationRepository(txDb),
2195
+ authSessionRepository: new ExpoAuthSessionRepository(txDb),
2196
+ mintOperationRepository: new ExpoMintOperationRepository(txDb),
2197
+ receiveOperationRepository: new ExpoReceiveOperationRepository(txDb)
2198
+ });
2199
+ });
2200
+ }
2201
+ };
2202
+
2203
+ //#endregion
2204
+ export { ExpoAuthSessionRepository, ExpoCounterRepository, ExpoHistoryRepository, ExpoKeyRingRepository, ExpoKeysetRepository, ExpoMeltOperationRepository, ExpoMeltQuoteRepository, ExpoMintOperationRepository, ExpoMintQuoteRepository, ExpoMintRepository, ExpoProofRepository, ExpoReceiveOperationRepository, ExpoSendOperationRepository, ExpoSqliteDb, ExpoSqliteRepositories, MIGRATIONS, ensureSchema, ensureSchemaUpTo };