@cashu/coco-expo-sqlite 1.0.1 → 2.0.0-rc.1

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