@cashu/coco-expo-sqlite 1.0.0 → 2.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,158 +1,11 @@
1
- import { normalizeMintUrl } from "@cashu/coco-core";
1
+ import { DEFAULT_UNIT, QuoteIdentityConflictError, deserializeAmount, deserializeToken, getMintQuoteAmount, getMintQuoteRemoteState, isMintQuotePending, isStatefulMintQuote, normalizeMeltMethodData, normalizeMintUrl, normalizeUnit, operationHistoryId, parseHistoryEntryId, projectLegacyHistoryRow, serializeAmount, stringifyJson } from "@cashu/coco-core/adapter";
2
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
3
+ //#region ../sql-storage/src/schema.ts
154
4
  const SEND_OPERATION_METHOD_MIGRATION_IDS = ["012_send_operations_method", "013_send_operations_method"];
155
5
  const RECEIVE_OPERATION_MIGRATION_IDS = ["013_receive_operations", "012_receive_operations"];
6
+ function getUnixTimeSeconds$1() {
7
+ return Math.floor(Date.now() / 1e3);
8
+ }
156
9
  async function tableExists(db, tableName) {
157
10
  return !!await db.get(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`, [tableName]);
158
11
  }
@@ -161,7 +14,7 @@ async function getTableColumns(db, tableName) {
161
14
  return new Set(rows.map((row) => row.name));
162
15
  }
163
16
  async function insertMigrationIds(db, ids) {
164
- const appliedAt = getUnixTimeSeconds();
17
+ const appliedAt = getUnixTimeSeconds$1();
165
18
  for (const id of ids) await db.run("INSERT OR IGNORE INTO coco_cashu_migrations (id, appliedAt) VALUES (?, ?)", [id, appliedAt]);
166
19
  }
167
20
  async function addSendOperationMethodColumns(db) {
@@ -169,6 +22,387 @@ async function addSendOperationMethodColumns(db) {
169
22
  if (!columns.has("method")) await db.run(`ALTER TABLE coco_cashu_send_operations ADD COLUMN method TEXT NOT NULL DEFAULT 'default'`);
170
23
  if (!columns.has("methodDataJson")) await db.run(`ALTER TABLE coco_cashu_send_operations ADD COLUMN methodDataJson TEXT NOT NULL DEFAULT '{}'`);
171
24
  }
25
+ async function addProofUnitColumn(db) {
26
+ if (!(await getTableColumns(db, "coco_cashu_proofs")).has("unit")) await db.run(`ALTER TABLE coco_cashu_proofs ADD COLUMN unit TEXT NOT NULL DEFAULT 'sat'`);
27
+ await db.run(`
28
+ UPDATE coco_cashu_proofs
29
+ SET unit = COALESCE(
30
+ (
31
+ SELECT LOWER(TRIM(coco_cashu_keysets.unit))
32
+ FROM coco_cashu_keysets
33
+ WHERE coco_cashu_keysets.mintUrl = coco_cashu_proofs.mintUrl
34
+ AND coco_cashu_keysets.id = coco_cashu_proofs.id
35
+ AND coco_cashu_keysets.unit IS NOT NULL
36
+ AND TRIM(coco_cashu_keysets.unit) <> ''
37
+ LIMIT 1
38
+ ),
39
+ CASE
40
+ WHEN unit IS NULL OR TRIM(unit) = '' THEN 'sat'
41
+ ELSE LOWER(TRIM(unit))
42
+ END
43
+ )
44
+ `);
45
+ await db.run("CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_mint_unit_state ON coco_cashu_proofs(mintUrl, unit, state)");
46
+ await db.run("CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_mint_unit_id_state ON coco_cashu_proofs(mintUrl, unit, id, state)");
47
+ await db.run("CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_unit_state ON coco_cashu_proofs(unit, state)");
48
+ }
49
+ async function addSendOperationUnitColumn(db) {
50
+ if (!(await getTableColumns(db, "coco_cashu_send_operations")).has("unit")) await db.run(`ALTER TABLE coco_cashu_send_operations ADD COLUMN unit TEXT NOT NULL DEFAULT 'sat'`);
51
+ await db.run("UPDATE coco_cashu_send_operations SET unit = 'sat' WHERE unit IS NULL OR TRIM(unit) = ''");
52
+ await db.run("UPDATE coco_cashu_send_operations SET unit = LOWER(TRIM(unit))");
53
+ }
54
+ async function backfillSendOperationTokensFromHistory(db) {
55
+ await db.run(`
56
+ UPDATE coco_cashu_send_operations
57
+ SET tokenJson = (
58
+ SELECT h.tokenJson
59
+ FROM coco_cashu_history h
60
+ WHERE h.type = 'send'
61
+ AND h.operationId = coco_cashu_send_operations.id
62
+ AND h.mintUrl = coco_cashu_send_operations.mintUrl
63
+ AND h.tokenJson IS NOT NULL
64
+ ORDER BY h.createdAt DESC, h.id DESC
65
+ LIMIT 1
66
+ )
67
+ WHERE tokenJson IS NULL
68
+ AND EXISTS (
69
+ SELECT 1
70
+ FROM coco_cashu_history h
71
+ WHERE h.type = 'send'
72
+ AND h.operationId = coco_cashu_send_operations.id
73
+ AND h.mintUrl = coco_cashu_send_operations.mintUrl
74
+ AND h.tokenJson IS NOT NULL
75
+ )
76
+ `);
77
+ }
78
+ async function migrateAmountColumnsToText(db) {
79
+ if (await tableExists(db, "coco_cashu_proofs")) await db.exec(`
80
+ ALTER TABLE coco_cashu_proofs RENAME TO coco_cashu_proofs_legacy_amounts;
81
+
82
+ CREATE TABLE coco_cashu_proofs (
83
+ mintUrl TEXT NOT NULL,
84
+ id TEXT NOT NULL,
85
+ unit TEXT NOT NULL DEFAULT 'sat',
86
+ amount TEXT NOT NULL,
87
+ secret TEXT NOT NULL,
88
+ C TEXT NOT NULL,
89
+ dleqJson TEXT,
90
+ witnessJson TEXT,
91
+ state TEXT NOT NULL CHECK (state IN ('inflight', 'ready', 'spent')),
92
+ createdAt INTEGER NOT NULL,
93
+ usedByOperationId TEXT,
94
+ createdByOperationId TEXT,
95
+ PRIMARY KEY (mintUrl, secret)
96
+ );
97
+
98
+ INSERT INTO coco_cashu_proofs (
99
+ mintUrl, id, unit, amount, secret, C, dleqJson, witnessJson, state, createdAt,
100
+ usedByOperationId, createdByOperationId
101
+ )
102
+ SELECT
103
+ mintUrl,
104
+ id,
105
+ COALESCE(
106
+ (
107
+ SELECT LOWER(TRIM(coco_cashu_keysets.unit))
108
+ FROM coco_cashu_keysets
109
+ WHERE coco_cashu_keysets.mintUrl = coco_cashu_proofs_legacy_amounts.mintUrl
110
+ AND coco_cashu_keysets.id = coco_cashu_proofs_legacy_amounts.id
111
+ AND coco_cashu_keysets.unit IS NOT NULL
112
+ AND TRIM(coco_cashu_keysets.unit) <> ''
113
+ LIMIT 1
114
+ ),
115
+ 'sat'
116
+ ),
117
+ CAST(amount AS TEXT), secret, C, dleqJson, witnessJson, state, createdAt,
118
+ usedByOperationId, createdByOperationId
119
+ FROM coco_cashu_proofs_legacy_amounts;
120
+
121
+ DROP TABLE coco_cashu_proofs_legacy_amounts;
122
+
123
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_state ON coco_cashu_proofs(state);
124
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_mint_state ON coco_cashu_proofs(mintUrl, state);
125
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_mint_id_state ON coco_cashu_proofs(mintUrl, id, state);
126
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_mint_unit_state ON coco_cashu_proofs(mintUrl, unit, state);
127
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_mint_unit_id_state ON coco_cashu_proofs(mintUrl, unit, id, state);
128
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_unit_state ON coco_cashu_proofs(unit, state);
129
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_usedByOp ON coco_cashu_proofs(usedByOperationId) WHERE usedByOperationId IS NOT NULL;
130
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_createdByOp ON coco_cashu_proofs(createdByOperationId) WHERE createdByOperationId IS NOT NULL;
131
+ `);
132
+ if (await tableExists(db, "coco_cashu_mint_quotes")) await db.exec(`
133
+ ALTER TABLE coco_cashu_mint_quotes RENAME TO coco_cashu_mint_quotes_legacy_amounts;
134
+
135
+ CREATE TABLE coco_cashu_mint_quotes (
136
+ mintUrl TEXT NOT NULL,
137
+ quote TEXT NOT NULL,
138
+ state TEXT NOT NULL CHECK (state IN ('UNPAID','PAID','ISSUED')),
139
+ request TEXT NOT NULL,
140
+ amount TEXT NOT NULL,
141
+ unit TEXT NOT NULL,
142
+ expiry INTEGER,
143
+ pubkey TEXT,
144
+ PRIMARY KEY (mintUrl, quote)
145
+ );
146
+
147
+ INSERT INTO coco_cashu_mint_quotes (
148
+ mintUrl, quote, state, request, amount, unit, expiry, pubkey
149
+ )
150
+ SELECT mintUrl, quote, state, request, CAST(amount AS TEXT), unit, expiry, pubkey
151
+ FROM coco_cashu_mint_quotes_legacy_amounts;
152
+
153
+ DROP TABLE coco_cashu_mint_quotes_legacy_amounts;
154
+
155
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_quotes_state ON coco_cashu_mint_quotes(state);
156
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_quotes_mint ON coco_cashu_mint_quotes(mintUrl);
157
+ `);
158
+ if (await tableExists(db, "coco_cashu_melt_quotes")) await db.exec(`
159
+ ALTER TABLE coco_cashu_melt_quotes RENAME TO coco_cashu_melt_quotes_legacy_amounts;
160
+
161
+ CREATE TABLE coco_cashu_melt_quotes (
162
+ mintUrl TEXT NOT NULL,
163
+ quote TEXT NOT NULL,
164
+ state TEXT NOT NULL CHECK (state IN ('UNPAID','PENDING','PAID')),
165
+ request TEXT NOT NULL,
166
+ amount TEXT NOT NULL,
167
+ unit TEXT NOT NULL,
168
+ expiry INTEGER NOT NULL,
169
+ fee_reserve TEXT NOT NULL,
170
+ payment_preimage TEXT,
171
+ PRIMARY KEY (mintUrl, quote)
172
+ );
173
+
174
+ INSERT INTO coco_cashu_melt_quotes (
175
+ mintUrl, quote, state, request, amount, unit, expiry, fee_reserve, payment_preimage
176
+ )
177
+ SELECT
178
+ mintUrl, quote, state, request, CAST(amount AS TEXT), unit, expiry,
179
+ CAST(fee_reserve AS TEXT), payment_preimage
180
+ FROM coco_cashu_melt_quotes_legacy_amounts;
181
+
182
+ DROP TABLE coco_cashu_melt_quotes_legacy_amounts;
183
+
184
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_melt_quotes_state ON coco_cashu_melt_quotes(state);
185
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_melt_quotes_mint ON coco_cashu_melt_quotes(mintUrl);
186
+ `);
187
+ if (await tableExists(db, "coco_cashu_history")) await db.exec(`
188
+ ALTER TABLE coco_cashu_history RENAME TO coco_cashu_history_legacy_amounts;
189
+
190
+ CREATE TABLE coco_cashu_history (
191
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
192
+ mintUrl TEXT NOT NULL,
193
+ type TEXT NOT NULL CHECK (type IN ('mint','melt','send','receive')),
194
+ unit TEXT NOT NULL,
195
+ amount TEXT NOT NULL,
196
+ createdAt INTEGER NOT NULL,
197
+ quoteId TEXT,
198
+ state TEXT,
199
+ paymentRequest TEXT,
200
+ tokenJson TEXT,
201
+ metadata TEXT,
202
+ operationId TEXT
203
+ );
204
+
205
+ INSERT INTO coco_cashu_history (
206
+ id, mintUrl, type, unit, amount, createdAt, quoteId, state, paymentRequest,
207
+ tokenJson, metadata, operationId
208
+ )
209
+ SELECT
210
+ id, mintUrl, type, unit, CAST(amount AS TEXT), createdAt, quoteId, state,
211
+ paymentRequest, tokenJson, metadata, operationId
212
+ FROM coco_cashu_history_legacy_amounts;
213
+
214
+ DROP TABLE coco_cashu_history_legacy_amounts;
215
+
216
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_history_mint_createdAt
217
+ ON coco_cashu_history(mintUrl, createdAt DESC);
218
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_history_mint_quote
219
+ ON coco_cashu_history(mintUrl, quoteId);
220
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_history_type
221
+ ON coco_cashu_history(type);
222
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_coco_cashu_history_mint_quote_mint
223
+ ON coco_cashu_history(mintUrl, quoteId, type)
224
+ WHERE type = 'mint' AND quoteId IS NOT NULL;
225
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_coco_cashu_history_mint_quote_melt
226
+ ON coco_cashu_history(mintUrl, quoteId, type)
227
+ WHERE type = 'melt' AND quoteId IS NOT NULL;
228
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_coco_cashu_history_mint_operation_send
229
+ ON coco_cashu_history(mintUrl, operationId)
230
+ WHERE type = 'send' AND operationId IS NOT NULL;
231
+ `);
232
+ if (await tableExists(db, "coco_cashu_send_operations")) await db.exec(`
233
+ ALTER TABLE coco_cashu_send_operations RENAME TO coco_cashu_send_operations_legacy_amounts;
234
+
235
+ CREATE TABLE coco_cashu_send_operations (
236
+ id TEXT PRIMARY KEY,
237
+ mintUrl TEXT NOT NULL,
238
+ amount TEXT NOT NULL,
239
+ unit TEXT NOT NULL DEFAULT 'sat',
240
+ state TEXT NOT NULL CHECK (state IN ('init', 'prepared', 'executing', 'pending', 'finalized', 'rolling_back', 'rolled_back')),
241
+ createdAt INTEGER NOT NULL,
242
+ updatedAt INTEGER NOT NULL,
243
+ error TEXT,
244
+ needsSwap INTEGER,
245
+ fee TEXT,
246
+ inputAmount TEXT,
247
+ inputProofSecretsJson TEXT,
248
+ outputDataJson TEXT,
249
+ method TEXT NOT NULL,
250
+ methodDataJson TEXT NOT NULL,
251
+ tokenJson TEXT
252
+ );
253
+
254
+ INSERT INTO coco_cashu_send_operations (
255
+ id, mintUrl, amount, unit, state, createdAt, updatedAt, error, needsSwap, fee,
256
+ inputAmount, inputProofSecretsJson, outputDataJson, method, methodDataJson, tokenJson
257
+ )
258
+ SELECT
259
+ id, mintUrl, CAST(amount AS TEXT), 'sat', state, createdAt, updatedAt, error, needsSwap,
260
+ CASE WHEN fee IS NULL THEN NULL ELSE CAST(fee AS TEXT) END,
261
+ CASE WHEN inputAmount IS NULL THEN NULL ELSE CAST(inputAmount AS TEXT) END,
262
+ inputProofSecretsJson, outputDataJson, method, methodDataJson, tokenJson
263
+ FROM coco_cashu_send_operations_legacy_amounts;
264
+
265
+ DROP TABLE coco_cashu_send_operations_legacy_amounts;
266
+
267
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_send_operations_state ON coco_cashu_send_operations(state);
268
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_send_operations_mint ON coco_cashu_send_operations(mintUrl);
269
+ `);
270
+ if (await tableExists(db, "coco_cashu_melt_operations")) await db.exec(`
271
+ ALTER TABLE coco_cashu_melt_operations RENAME TO coco_cashu_melt_operations_legacy_amounts;
272
+
273
+ CREATE TABLE coco_cashu_melt_operations (
274
+ id TEXT PRIMARY KEY,
275
+ mintUrl TEXT NOT NULL,
276
+ state TEXT NOT NULL CHECK (state IN ('init', 'prepared', 'executing', 'pending', 'finalized', 'rolling_back', 'rolled_back')),
277
+ createdAt INTEGER NOT NULL,
278
+ updatedAt INTEGER NOT NULL,
279
+ error TEXT,
280
+ method TEXT NOT NULL,
281
+ methodDataJson TEXT NOT NULL,
282
+ quoteId TEXT,
283
+ amount TEXT,
284
+ fee_reserve TEXT,
285
+ swap_fee TEXT,
286
+ needsSwap INTEGER,
287
+ inputAmount TEXT,
288
+ inputProofSecretsJson TEXT,
289
+ changeOutputDataJson TEXT,
290
+ swapOutputDataJson TEXT,
291
+ changeAmount TEXT,
292
+ effectiveFee TEXT,
293
+ finalizedDataJson TEXT,
294
+ unit TEXT
295
+ );
296
+
297
+ INSERT INTO coco_cashu_melt_operations (
298
+ id, mintUrl, state, createdAt, updatedAt, error, method, methodDataJson, quoteId,
299
+ amount, fee_reserve, swap_fee, needsSwap, inputAmount, inputProofSecretsJson,
300
+ changeOutputDataJson, swapOutputDataJson, changeAmount, effectiveFee, finalizedDataJson, unit
301
+ )
302
+ SELECT
303
+ id, mintUrl, state, createdAt, updatedAt, error, method, methodDataJson, quoteId,
304
+ CASE WHEN amount IS NULL THEN NULL ELSE CAST(amount AS TEXT) END,
305
+ CASE WHEN fee_reserve IS NULL THEN NULL ELSE CAST(fee_reserve AS TEXT) END,
306
+ CASE WHEN swap_fee IS NULL THEN NULL ELSE CAST(swap_fee AS TEXT) END,
307
+ needsSwap,
308
+ CASE WHEN inputAmount IS NULL THEN NULL ELSE CAST(inputAmount AS TEXT) END,
309
+ inputProofSecretsJson, changeOutputDataJson, swapOutputDataJson,
310
+ CASE WHEN changeAmount IS NULL THEN NULL ELSE CAST(changeAmount AS TEXT) END,
311
+ CASE WHEN effectiveFee IS NULL THEN NULL ELSE CAST(effectiveFee AS TEXT) END,
312
+ finalizedDataJson, unit
313
+ FROM coco_cashu_melt_operations_legacy_amounts;
314
+
315
+ DROP TABLE coco_cashu_melt_operations_legacy_amounts;
316
+
317
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_melt_operations_state
318
+ ON coco_cashu_melt_operations(state);
319
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_melt_operations_mint
320
+ ON coco_cashu_melt_operations(mintUrl);
321
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_coco_cashu_melt_operations_mint_quote
322
+ ON coco_cashu_melt_operations(mintUrl, quoteId)
323
+ WHERE quoteId IS NOT NULL;
324
+ `);
325
+ if (await tableExists(db, "coco_cashu_receive_operations")) await db.exec(`
326
+ ALTER TABLE coco_cashu_receive_operations RENAME TO coco_cashu_receive_operations_legacy_amounts;
327
+
328
+ CREATE TABLE coco_cashu_receive_operations (
329
+ id TEXT PRIMARY KEY,
330
+ mintUrl TEXT NOT NULL,
331
+ amount TEXT NOT NULL,
332
+ state TEXT NOT NULL CHECK (state IN ('init', 'prepared', 'executing', 'finalized', 'rolled_back')),
333
+ createdAt INTEGER NOT NULL,
334
+ updatedAt INTEGER NOT NULL,
335
+ error TEXT,
336
+ fee TEXT,
337
+ inputProofsJson TEXT NOT NULL,
338
+ outputDataJson TEXT,
339
+ unit TEXT NOT NULL DEFAULT 'sat'
340
+ );
341
+
342
+ INSERT INTO coco_cashu_receive_operations (
343
+ id, mintUrl, amount, state, createdAt, updatedAt, error, fee,
344
+ inputProofsJson, outputDataJson, unit
345
+ )
346
+ SELECT
347
+ id, mintUrl, CAST(amount AS TEXT), state, createdAt, updatedAt, error,
348
+ CASE WHEN fee IS NULL THEN NULL ELSE CAST(fee AS TEXT) END,
349
+ inputProofsJson, outputDataJson, unit
350
+ FROM coco_cashu_receive_operations_legacy_amounts;
351
+
352
+ DROP TABLE coco_cashu_receive_operations_legacy_amounts;
353
+
354
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_receive_operations_state
355
+ ON coco_cashu_receive_operations(state);
356
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_receive_operations_mint
357
+ ON coco_cashu_receive_operations(mintUrl);
358
+ `);
359
+ if (await tableExists(db, "coco_cashu_mint_operations")) await db.exec(`
360
+ ALTER TABLE coco_cashu_mint_operations RENAME TO coco_cashu_mint_operations_legacy_amounts;
361
+
362
+ CREATE TABLE coco_cashu_mint_operations (
363
+ id TEXT PRIMARY KEY,
364
+ mintUrl TEXT NOT NULL,
365
+ quoteId TEXT,
366
+ state TEXT NOT NULL CHECK (state IN ('init', 'pending', 'executing', 'finalized', 'failed')),
367
+ createdAt INTEGER NOT NULL,
368
+ updatedAt INTEGER NOT NULL,
369
+ error TEXT,
370
+ method TEXT NOT NULL,
371
+ methodDataJson TEXT NOT NULL,
372
+ amount TEXT,
373
+ unit TEXT,
374
+ request TEXT,
375
+ expiry INTEGER,
376
+ pubkey TEXT,
377
+ lastObservedRemoteState TEXT,
378
+ lastObservedRemoteStateAt INTEGER,
379
+ terminalFailureJson TEXT,
380
+ outputDataJson TEXT
381
+ );
382
+
383
+ INSERT INTO coco_cashu_mint_operations (
384
+ id, mintUrl, quoteId, state, createdAt, updatedAt, error, method, methodDataJson,
385
+ amount, unit, request, expiry, pubkey, lastObservedRemoteState,
386
+ lastObservedRemoteStateAt, terminalFailureJson, outputDataJson
387
+ )
388
+ SELECT
389
+ id, mintUrl, quoteId, state, createdAt, updatedAt, error, method, methodDataJson,
390
+ CASE WHEN amount IS NULL THEN NULL ELSE CAST(amount AS TEXT) END,
391
+ unit, request, expiry, pubkey, lastObservedRemoteState,
392
+ lastObservedRemoteStateAt, terminalFailureJson, outputDataJson
393
+ FROM coco_cashu_mint_operations_legacy_amounts;
394
+
395
+ DROP TABLE coco_cashu_mint_operations_legacy_amounts;
396
+
397
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_state
398
+ ON coco_cashu_mint_operations(state);
399
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_mint
400
+ ON coco_cashu_mint_operations(mintUrl);
401
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_mint_quote
402
+ ON coco_cashu_mint_operations(mintUrl, quoteId)
403
+ WHERE quoteId IS NOT NULL;
404
+ `);
405
+ }
172
406
  async function reconcileMigrationAliases(db) {
173
407
  if (await tableExists(db, "coco_cashu_send_operations")) {
174
408
  const sendColumns = await getTableColumns(db, "coco_cashu_send_operations");
@@ -181,7 +415,7 @@ const MIGRATIONS = [
181
415
  id: "001_initial",
182
416
  sql: `
183
417
  CREATE TABLE IF NOT EXISTS coco_cashu_mints (
184
- mintUrl TEXT PRIMARY KEY NOT NULL,
418
+ mintUrl TEXT PRIMARY KEY,
185
419
  name TEXT NOT NULL,
186
420
  mintInfo TEXT NOT NULL,
187
421
  createdAt INTEGER NOT NULL,
@@ -208,6 +442,7 @@ const MIGRATIONS = [
208
442
  CREATE TABLE IF NOT EXISTS coco_cashu_proofs (
209
443
  mintUrl TEXT NOT NULL,
210
444
  id TEXT NOT NULL,
445
+ unit TEXT NOT NULL DEFAULT 'sat',
211
446
  amount INTEGER NOT NULL,
212
447
  secret TEXT NOT NULL,
213
448
  C TEXT NOT NULL,
@@ -221,6 +456,9 @@ const MIGRATIONS = [
221
456
  CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_state ON coco_cashu_proofs(state);
222
457
  CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_mint_state ON coco_cashu_proofs(mintUrl, state);
223
458
  CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_mint_id_state ON coco_cashu_proofs(mintUrl, id, state);
459
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_mint_unit_state ON coco_cashu_proofs(mintUrl, unit, state);
460
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_mint_unit_id_state ON coco_cashu_proofs(mintUrl, unit, id, state);
461
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_proofs_unit_state ON coco_cashu_proofs(unit, state);
224
462
 
225
463
  CREATE TABLE IF NOT EXISTS coco_cashu_mint_quotes (
226
464
  mintUrl TEXT NOT NULL,
@@ -305,7 +543,7 @@ const MIGRATIONS = [
305
543
  id: "006_keypairs",
306
544
  sql: `
307
545
  CREATE TABLE IF NOT EXISTS coco_cashu_keypairs (
308
- publicKey TEXT PRIMARY KEY NOT NULL,
546
+ publicKey TEXT PRIMARY KEY,
309
547
  secretKey TEXT NOT NULL,
310
548
  createdAt INTEGER NOT NULL,
311
549
  derivationIndex INTEGER
@@ -349,7 +587,7 @@ const MIGRATIONS = [
349
587
  id: "008_send_operations",
350
588
  sql: `
351
589
  CREATE TABLE IF NOT EXISTS coco_cashu_send_operations (
352
- id TEXT PRIMARY KEY NOT NULL,
590
+ id TEXT PRIMARY KEY,
353
591
  mintUrl TEXT NOT NULL,
354
592
  amount INTEGER NOT NULL,
355
593
  state TEXT NOT NULL CHECK (state IN ('init', 'prepared', 'executing', 'pending', 'completed', 'rolling_back', 'rolled_back')),
@@ -389,7 +627,7 @@ const MIGRATIONS = [
389
627
  await db.run(`UPDATE coco_cashu_history SET state = 'finalized' WHERE type = 'send' AND state = 'completed'`);
390
628
  await db.exec(`
391
629
  CREATE TABLE coco_cashu_send_operations_new (
392
- id TEXT PRIMARY KEY NOT NULL,
630
+ id TEXT PRIMARY KEY,
393
631
  mintUrl TEXT NOT NULL,
394
632
  amount INTEGER NOT NULL,
395
633
  state TEXT NOT NULL CHECK (state IN ('init', 'prepared', 'executing', 'pending', 'finalized', 'rolling_back', 'rolled_back')),
@@ -424,7 +662,7 @@ const MIGRATIONS = [
424
662
  id: "011_melt_operations",
425
663
  sql: `
426
664
  CREATE TABLE IF NOT EXISTS coco_cashu_melt_operations (
427
- id TEXT PRIMARY KEY NOT NULL,
665
+ id TEXT PRIMARY KEY,
428
666
  mintUrl TEXT NOT NULL,
429
667
  state TEXT NOT NULL CHECK (state IN ('init', 'prepared', 'executing', 'pending', 'finalized', 'rolling_back', 'rolled_back')),
430
668
  createdAt INTEGER NOT NULL,
@@ -515,7 +753,7 @@ const MIGRATIONS = [
515
753
  id: "018_mint_operations",
516
754
  sql: `
517
755
  CREATE TABLE IF NOT EXISTS coco_cashu_mint_operations (
518
- id TEXT PRIMARY KEY NOT NULL,
756
+ id TEXT PRIMARY KEY,
519
757
  mintUrl TEXT NOT NULL,
520
758
  quoteId TEXT,
521
759
  state TEXT NOT NULL CHECK (state IN ('init', 'pending', 'executing', 'finalized', 'failed')),
@@ -550,7 +788,7 @@ const MIGRATIONS = [
550
788
  ALTER TABLE coco_cashu_mint_operations RENAME TO coco_cashu_mint_operations_legacy;
551
789
 
552
790
  CREATE TABLE coco_cashu_mint_operations (
553
- id TEXT PRIMARY KEY NOT NULL,
791
+ id TEXT PRIMARY KEY,
554
792
  mintUrl TEXT NOT NULL,
555
793
  quoteId TEXT,
556
794
  state TEXT NOT NULL CHECK (state IN ('init', 'pending', 'executing', 'finalized', 'failed')),
@@ -615,7 +853,7 @@ const MIGRATIONS = [
615
853
  ALTER TABLE coco_cashu_mint_operations RENAME TO coco_cashu_mint_operations_legacy;
616
854
 
617
855
  CREATE TABLE coco_cashu_mint_operations (
618
- id TEXT PRIMARY KEY NOT NULL,
856
+ id TEXT PRIMARY KEY,
619
857
  mintUrl TEXT NOT NULL,
620
858
  quoteId TEXT,
621
859
  state TEXT NOT NULL CHECK (state IN ('init', 'pending', 'executing', 'finalized', 'failed')),
@@ -659,33 +897,432 @@ const MIGRATIONS = [
659
897
  outputDataJson
660
898
  FROM coco_cashu_mint_operations_legacy;
661
899
 
662
- DROP TABLE coco_cashu_mint_operations_legacy;
900
+ DROP TABLE coco_cashu_mint_operations_legacy;
901
+
902
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_state
903
+ ON coco_cashu_mint_operations(state);
904
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_mint
905
+ ON coco_cashu_mint_operations(mintUrl);
906
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_mint_quote
907
+ ON coco_cashu_mint_operations(mintUrl, quoteId)
908
+ WHERE quoteId IS NOT NULL;
909
+ `
910
+ },
911
+ {
912
+ id: "021_melt_finalized_data",
913
+ sql: `
914
+ ALTER TABLE coco_cashu_melt_operations ADD COLUMN finalizedDataJson TEXT;
915
+ `
916
+ },
917
+ {
918
+ id: "022_melt_operation_unit",
919
+ sql: `
920
+ ALTER TABLE coco_cashu_melt_operations ADD COLUMN unit TEXT;
921
+ `
922
+ },
923
+ {
924
+ id: "023_receive_operation_unit",
925
+ sql: `
926
+ ALTER TABLE coco_cashu_receive_operations ADD COLUMN unit TEXT NOT NULL DEFAULT 'sat';
927
+ `
928
+ },
929
+ {
930
+ id: "024_amount_columns_text",
931
+ run: migrateAmountColumnsToText
932
+ },
933
+ {
934
+ id: "025_proof_unit",
935
+ run: addProofUnitColumn
936
+ },
937
+ {
938
+ id: "026_send_operation_unit",
939
+ run: addSendOperationUnitColumn
940
+ },
941
+ {
942
+ id: "027_payment_request_receive",
943
+ sql: `
944
+ ALTER TABLE coco_cashu_receive_operations ADD COLUMN sourceJson TEXT;
945
+
946
+ CREATE TABLE IF NOT EXISTS coco_cashu_payment_request_receive_operations (
947
+ id TEXT PRIMARY KEY,
948
+ requestId TEXT,
949
+ encodedRequest TEXT NOT NULL,
950
+ state TEXT NOT NULL CHECK (state IN ('active', 'completed', 'cancelled')),
951
+ transport TEXT NOT NULL CHECK (transport IN ('inband', 'nostr', 'post')),
952
+ amount TEXT NOT NULL,
953
+ unit TEXT NOT NULL,
954
+ mintsJson TEXT NOT NULL,
955
+ singleUse INTEGER NOT NULL,
956
+ description TEXT,
957
+ createdAt INTEGER NOT NULL,
958
+ updatedAt INTEGER NOT NULL,
959
+ error TEXT,
960
+ completedAt INTEGER
961
+ );
962
+
963
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_pr_receive_operations_state
964
+ ON coco_cashu_payment_request_receive_operations(state);
965
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_pr_receive_operations_request_id
966
+ ON coco_cashu_payment_request_receive_operations(requestId);
967
+
968
+ CREATE TABLE IF NOT EXISTS coco_cashu_payment_request_receive_attempts (
969
+ id TEXT PRIMARY KEY,
970
+ requestOperationId TEXT NOT NULL,
971
+ requestId TEXT,
972
+ transport TEXT NOT NULL CHECK (transport IN ('inband', 'nostr', 'post')),
973
+ transportMessageId TEXT,
974
+ payloadHash TEXT NOT NULL,
975
+ senderPubkey TEXT,
976
+ memo TEXT,
977
+ mintUrl TEXT NOT NULL,
978
+ unit TEXT NOT NULL,
979
+ grossAmount TEXT NOT NULL,
980
+ fee TEXT,
981
+ netAmount TEXT,
982
+ receiveOperationId TEXT,
983
+ state TEXT NOT NULL CHECK (state IN ('received', 'validating', 'receiving', 'finalized', 'rejected')),
984
+ error TEXT,
985
+ payloadJson TEXT,
986
+ createdAt INTEGER NOT NULL,
987
+ updatedAt INTEGER NOT NULL
988
+ );
989
+
990
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_pr_receive_attempts_request_operation
991
+ ON coco_cashu_payment_request_receive_attempts(requestOperationId);
992
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_pr_receive_attempts_state
993
+ ON coco_cashu_payment_request_receive_attempts(state);
994
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_coco_cashu_pr_receive_attempts_message
995
+ ON coco_cashu_payment_request_receive_attempts(transportMessageId)
996
+ WHERE transportMessageId IS NOT NULL;
997
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_coco_cashu_pr_receive_attempts_payload
998
+ ON coco_cashu_payment_request_receive_attempts(requestOperationId, payloadHash);
999
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_coco_cashu_pr_receive_attempts_receive
1000
+ ON coco_cashu_payment_request_receive_attempts(receiveOperationId)
1001
+ WHERE receiveOperationId IS NOT NULL;
1002
+ `
1003
+ },
1004
+ {
1005
+ id: "028_history_projection_indexes",
1006
+ sql: `
1007
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_send_operations_createdAt
1008
+ ON coco_cashu_send_operations(createdAt DESC, id DESC);
1009
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_melt_operations_createdAt
1010
+ ON coco_cashu_melt_operations(createdAt DESC, id DESC);
1011
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_createdAt
1012
+ ON coco_cashu_mint_operations(createdAt DESC, id DESC);
1013
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_receive_operations_createdAt
1014
+ ON coco_cashu_receive_operations(createdAt DESC, id DESC);
1015
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_history_createdAt
1016
+ ON coco_cashu_history(createdAt DESC, id DESC);
1017
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_history_type_operation
1018
+ ON coco_cashu_history(type, operationId)
1019
+ WHERE operationId IS NOT NULL;
1020
+ `
1021
+ },
1022
+ {
1023
+ id: "029_backfill_send_operation_tokens",
1024
+ run: backfillSendOperationTokensFromHistory
1025
+ },
1026
+ {
1027
+ id: "030_method_aware_mint_quotes",
1028
+ sql: `
1029
+ CREATE TABLE IF NOT EXISTS coco_cashu_canonical_mint_quotes (
1030
+ mintUrl TEXT NOT NULL,
1031
+ method TEXT NOT NULL,
1032
+ quoteId TEXT NOT NULL,
1033
+ state TEXT NOT NULL CHECK (state IN ('UNPAID','PAID','ISSUED')),
1034
+ request TEXT NOT NULL,
1035
+ amount TEXT NOT NULL,
1036
+ unit TEXT NOT NULL,
1037
+ expiry INTEGER,
1038
+ pubkey TEXT,
1039
+ lastObservedRemoteState TEXT,
1040
+ lastObservedRemoteStateAt INTEGER,
1041
+ reusable INTEGER NOT NULL DEFAULT 0,
1042
+ createdAt INTEGER NOT NULL,
1043
+ updatedAt INTEGER NOT NULL,
1044
+ PRIMARY KEY (mintUrl, method, quoteId)
1045
+ );
1046
+
1047
+ INSERT INTO coco_cashu_canonical_mint_quotes (
1048
+ mintUrl, method, quoteId, state, request, amount, unit, expiry, pubkey,
1049
+ lastObservedRemoteState, lastObservedRemoteStateAt, reusable, createdAt, updatedAt
1050
+ )
1051
+ SELECT
1052
+ mintUrl,
1053
+ method,
1054
+ quoteId,
1055
+ CASE
1056
+ WHEN lastObservedRemoteState IN ('UNPAID','PAID','ISSUED') THEN lastObservedRemoteState
1057
+ WHEN state = 'finalized' THEN 'ISSUED'
1058
+ ELSE 'UNPAID'
1059
+ END,
1060
+ request,
1061
+ amount,
1062
+ unit,
1063
+ expiry,
1064
+ pubkey,
1065
+ CASE
1066
+ WHEN lastObservedRemoteState IN ('UNPAID','PAID','ISSUED') THEN lastObservedRemoteState
1067
+ WHEN state = 'finalized' THEN 'ISSUED'
1068
+ ELSE 'UNPAID'
1069
+ END,
1070
+ COALESCE(lastObservedRemoteStateAt, updatedAt * 1000),
1071
+ 0,
1072
+ createdAt * 1000,
1073
+ updatedAt * 1000
1074
+ FROM coco_cashu_mint_operations
1075
+ WHERE quoteId IS NOT NULL
1076
+ AND request IS NOT NULL
1077
+ AND amount IS NOT NULL
1078
+ AND unit IS NOT NULL
1079
+ ON CONFLICT(mintUrl, method, quoteId) DO UPDATE SET
1080
+ state = excluded.state,
1081
+ request = excluded.request,
1082
+ amount = excluded.amount,
1083
+ unit = excluded.unit,
1084
+ expiry = excluded.expiry,
1085
+ pubkey = excluded.pubkey,
1086
+ lastObservedRemoteState = excluded.lastObservedRemoteState,
1087
+ lastObservedRemoteStateAt = excluded.lastObservedRemoteStateAt,
1088
+ updatedAt = excluded.updatedAt;
1089
+
1090
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_canonical_mint_quotes_state
1091
+ ON coco_cashu_canonical_mint_quotes(state);
1092
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_canonical_mint_quotes_mint
1093
+ ON coco_cashu_canonical_mint_quotes(mintUrl);
1094
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_canonical_mint_quotes_method
1095
+ ON coco_cashu_canonical_mint_quotes(method);
1096
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_mint_operations_mint_method_quote
1097
+ ON coco_cashu_mint_operations(mintUrl, method, quoteId)
1098
+ WHERE quoteId IS NOT NULL;
1099
+ `
1100
+ },
1101
+ {
1102
+ id: "031_method_aware_melt_quotes",
1103
+ sql: `
1104
+ ALTER TABLE coco_cashu_melt_quotes RENAME TO coco_cashu_melt_quotes_legacy;
1105
+
1106
+ CREATE TABLE coco_cashu_melt_quotes (
1107
+ mintUrl TEXT NOT NULL,
1108
+ method TEXT NOT NULL,
1109
+ quoteId TEXT NOT NULL,
1110
+ state TEXT NOT NULL CHECK (state IN ('UNPAID','PENDING','PAID')),
1111
+ request TEXT NOT NULL,
1112
+ amount TEXT NOT NULL,
1113
+ unit TEXT NOT NULL,
1114
+ expiry INTEGER NOT NULL,
1115
+ fee_reserve TEXT NOT NULL,
1116
+ payment_preimage TEXT,
1117
+ changeJson TEXT,
1118
+ lastObservedRemoteState TEXT,
1119
+ lastObservedRemoteStateAt INTEGER,
1120
+ createdAt INTEGER NOT NULL,
1121
+ updatedAt INTEGER NOT NULL,
1122
+ PRIMARY KEY (mintUrl, method, quoteId)
1123
+ );
1124
+
1125
+ INSERT INTO coco_cashu_melt_quotes (
1126
+ mintUrl, method, quoteId, state, request, amount, unit, expiry, fee_reserve,
1127
+ payment_preimage, changeJson, lastObservedRemoteState, lastObservedRemoteStateAt,
1128
+ createdAt, updatedAt
1129
+ )
1130
+ SELECT
1131
+ mintUrl,
1132
+ 'bolt11',
1133
+ quote,
1134
+ state,
1135
+ request,
1136
+ amount,
1137
+ unit,
1138
+ expiry,
1139
+ fee_reserve,
1140
+ payment_preimage,
1141
+ NULL,
1142
+ state,
1143
+ CAST(strftime('%s', 'now') AS INTEGER) * 1000,
1144
+ CAST(strftime('%s', 'now') AS INTEGER) * 1000,
1145
+ CAST(strftime('%s', 'now') AS INTEGER) * 1000
1146
+ FROM coco_cashu_melt_quotes_legacy;
1147
+
1148
+ INSERT INTO coco_cashu_melt_quotes (
1149
+ mintUrl, method, quoteId, state, request, amount, unit, expiry, fee_reserve,
1150
+ payment_preimage, changeJson, lastObservedRemoteState, lastObservedRemoteStateAt,
1151
+ createdAt, updatedAt
1152
+ )
1153
+ SELECT
1154
+ mintUrl,
1155
+ method,
1156
+ quoteId,
1157
+ CASE
1158
+ WHEN state = 'finalized' THEN 'PAID'
1159
+ WHEN state IN ('pending','executing') THEN 'PENDING'
1160
+ ELSE 'UNPAID'
1161
+ END,
1162
+ COALESCE(json_extract(methodDataJson, '$.invoice'), quoteId),
1163
+ amount,
1164
+ unit,
1165
+ 0,
1166
+ fee_reserve,
1167
+ json_extract(finalizedDataJson, '$.preimage'),
1168
+ NULL,
1169
+ CASE
1170
+ WHEN state = 'finalized' THEN 'PAID'
1171
+ WHEN state IN ('pending','executing') THEN 'PENDING'
1172
+ ELSE 'UNPAID'
1173
+ END,
1174
+ updatedAt * 1000,
1175
+ createdAt * 1000,
1176
+ updatedAt * 1000
1177
+ FROM coco_cashu_melt_operations
1178
+ WHERE quoteId IS NOT NULL
1179
+ AND amount IS NOT NULL
1180
+ AND fee_reserve IS NOT NULL
1181
+ AND unit IS NOT NULL
1182
+ ON CONFLICT(mintUrl, method, quoteId) DO UPDATE SET
1183
+ state = excluded.state,
1184
+ request = excluded.request,
1185
+ amount = excluded.amount,
1186
+ unit = excluded.unit,
1187
+ fee_reserve = excluded.fee_reserve,
1188
+ payment_preimage = excluded.payment_preimage,
1189
+ lastObservedRemoteState = excluded.lastObservedRemoteState,
1190
+ lastObservedRemoteStateAt = excluded.lastObservedRemoteStateAt,
1191
+ updatedAt = excluded.updatedAt;
1192
+
1193
+ DROP TABLE coco_cashu_melt_quotes_legacy;
1194
+
1195
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_melt_quotes_state
1196
+ ON coco_cashu_melt_quotes(state);
1197
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_melt_quotes_mint
1198
+ ON coco_cashu_melt_quotes(mintUrl);
1199
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_melt_quotes_method
1200
+ ON coco_cashu_melt_quotes(method);
1201
+ `
1202
+ },
1203
+ {
1204
+ id: "032_onchain_melt_quotes",
1205
+ sql: `
1206
+ ALTER TABLE coco_cashu_melt_quotes RENAME TO coco_cashu_melt_quotes_pre_onchain;
1207
+
1208
+ CREATE TABLE coco_cashu_melt_quotes (
1209
+ mintUrl TEXT NOT NULL,
1210
+ method TEXT NOT NULL,
1211
+ quoteId TEXT NOT NULL,
1212
+ state TEXT NOT NULL CHECK (state IN ('UNPAID','PENDING','PAID')),
1213
+ request TEXT NOT NULL,
1214
+ amount TEXT NOT NULL,
1215
+ unit TEXT NOT NULL,
1216
+ expiry INTEGER NOT NULL,
1217
+ fee_reserve TEXT,
1218
+ payment_preimage TEXT,
1219
+ fee_options_json TEXT,
1220
+ outpoint TEXT,
1221
+ changeJson TEXT,
1222
+ lastObservedRemoteState TEXT,
1223
+ lastObservedRemoteStateAt INTEGER,
1224
+ createdAt INTEGER NOT NULL,
1225
+ updatedAt INTEGER NOT NULL,
1226
+ PRIMARY KEY (mintUrl, method, quoteId)
1227
+ );
1228
+
1229
+ INSERT INTO coco_cashu_melt_quotes (
1230
+ mintUrl, method, quoteId, state, request, amount, unit, expiry, fee_reserve,
1231
+ payment_preimage, fee_options_json, outpoint, changeJson, lastObservedRemoteState,
1232
+ lastObservedRemoteStateAt, createdAt, updatedAt
1233
+ )
1234
+ SELECT
1235
+ mintUrl, method, quoteId, state, request, amount, unit, expiry, fee_reserve,
1236
+ payment_preimage, NULL, NULL, changeJson, lastObservedRemoteState,
1237
+ lastObservedRemoteStateAt, createdAt, updatedAt
1238
+ FROM coco_cashu_melt_quotes_pre_onchain;
1239
+
1240
+ DROP TABLE coco_cashu_melt_quotes_pre_onchain;
1241
+
1242
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_melt_quotes_state
1243
+ ON coco_cashu_melt_quotes(state);
1244
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_melt_quotes_mint
1245
+ ON coco_cashu_melt_quotes(mintUrl);
1246
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_melt_quotes_method
1247
+ ON coco_cashu_melt_quotes(method);
1248
+ `
1249
+ },
1250
+ {
1251
+ id: "032_mint_quote_method_data",
1252
+ sql: `
1253
+ ALTER TABLE coco_cashu_canonical_mint_quotes
1254
+ RENAME TO coco_cashu_canonical_mint_quotes_legacy_quote_data;
1255
+
1256
+ CREATE TABLE coco_cashu_canonical_mint_quotes (
1257
+ mintUrl TEXT NOT NULL,
1258
+ method TEXT NOT NULL,
1259
+ quoteId TEXT NOT NULL,
1260
+ state TEXT CHECK (state IS NULL OR state IN ('UNPAID','PAID','ISSUED')),
1261
+ request TEXT NOT NULL,
1262
+ amount TEXT,
1263
+ unit TEXT NOT NULL,
1264
+ expiry INTEGER,
1265
+ pubkey TEXT,
1266
+ quoteDataJson TEXT NOT NULL DEFAULT '{}',
1267
+ lastObservedRemoteState TEXT,
1268
+ lastObservedRemoteStateAt INTEGER,
1269
+ reusable INTEGER NOT NULL DEFAULT 0,
1270
+ createdAt INTEGER NOT NULL,
1271
+ updatedAt INTEGER NOT NULL,
1272
+ PRIMARY KEY (mintUrl, method, quoteId)
1273
+ );
1274
+
1275
+ INSERT INTO coco_cashu_canonical_mint_quotes (
1276
+ mintUrl, method, quoteId, state, request, amount, unit, expiry, pubkey, quoteDataJson,
1277
+ lastObservedRemoteState, lastObservedRemoteStateAt, reusable, createdAt, updatedAt
1278
+ )
1279
+ SELECT
1280
+ mintUrl, method, quoteId, state, request, amount, unit, expiry, pubkey, '{}',
1281
+ lastObservedRemoteState, lastObservedRemoteStateAt, reusable, createdAt, updatedAt
1282
+ FROM coco_cashu_canonical_mint_quotes_legacy_quote_data;
1283
+
1284
+ DROP TABLE coco_cashu_canonical_mint_quotes_legacy_quote_data;
663
1285
 
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;
1286
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_canonical_mint_quotes_state
1287
+ ON coco_cashu_canonical_mint_quotes(state);
1288
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_canonical_mint_quotes_mint
1289
+ ON coco_cashu_canonical_mint_quotes(mintUrl);
1290
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_canonical_mint_quotes_method
1291
+ ON coco_cashu_canonical_mint_quotes(method);
671
1292
  `
672
1293
  },
673
1294
  {
674
- id: "021_melt_finalized_data",
1295
+ id: "033_keypair_purpose",
675
1296
  sql: `
676
- ALTER TABLE coco_cashu_melt_operations ADD COLUMN finalizedDataJson TEXT;
1297
+ ALTER TABLE coco_cashu_keypairs ADD COLUMN purpose TEXT NOT NULL DEFAULT 'p2pk';
1298
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_keypairs_purpose_createdAt
1299
+ ON coco_cashu_keypairs(purpose, createdAt DESC);
1300
+ CREATE INDEX IF NOT EXISTS idx_coco_cashu_keypairs_purpose_derivationIndex
1301
+ ON coco_cashu_keypairs(purpose, derivationIndex DESC)
1302
+ WHERE derivationIndex IS NOT NULL;
677
1303
  `
678
1304
  },
679
1305
  {
680
- id: "022_melt_operation_unit",
1306
+ id: "034_clean_unquoted_mint_operations",
681
1307
  sql: `
682
- ALTER TABLE coco_cashu_melt_operations ADD COLUMN unit TEXT;
1308
+ DELETE FROM coco_cashu_mint_operations
1309
+ WHERE quoteId IS NULL OR TRIM(quoteId) = '';
683
1310
  `
684
1311
  },
685
1312
  {
686
- id: "023_receive_operation_unit",
1313
+ id: "035_duplicate_quote_ids",
687
1314
  sql: `
688
- ALTER TABLE coco_cashu_receive_operations ADD COLUMN unit TEXT NOT NULL DEFAULT 'sat';
1315
+ DROP INDEX IF EXISTS ux_coco_cashu_history_mint_quote_mint;
1316
+ DROP INDEX IF EXISTS ux_coco_cashu_history_mint_quote_melt;
1317
+ `
1318
+ },
1319
+ {
1320
+ id: "036_quote_identity_unique_indexes",
1321
+ sql: `
1322
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_coco_cashu_canonical_mint_quotes_identity
1323
+ ON coco_cashu_canonical_mint_quotes(mintUrl, quoteId);
1324
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_coco_cashu_melt_quotes_identity
1325
+ ON coco_cashu_melt_quotes(mintUrl, quoteId);
689
1326
  `
690
1327
  }
691
1328
  ];
@@ -702,8 +1339,13 @@ async function ensureSchema(db) {
702
1339
  */
703
1340
  async function ensureSchemaUpTo(db, stopBeforeId) {
704
1341
  await db.exec(`
1342
+ PRAGMA foreign_keys = ON;
1343
+ PRAGMA journal_mode = WAL;
1344
+ PRAGMA synchronous = NORMAL;
1345
+ `);
1346
+ await db.exec(`
705
1347
  CREATE TABLE IF NOT EXISTS coco_cashu_migrations (
706
- id TEXT PRIMARY KEY NOT NULL,
1348
+ id TEXT PRIMARY KEY,
707
1349
  appliedAt INTEGER NOT NULL
708
1350
  );
709
1351
  `);
@@ -716,15 +1358,15 @@ async function ensureSchemaUpTo(db, stopBeforeId) {
716
1358
  await db.transaction(async (tx) => {
717
1359
  if (migration.sql) await tx.exec(migration.sql);
718
1360
  if (migration.run) await migration.run(tx);
719
- await tx.run("INSERT INTO coco_cashu_migrations (id, appliedAt) VALUES (?, ?)", [migration.id, getUnixTimeSeconds()]);
1361
+ await tx.run("INSERT INTO coco_cashu_migrations (id, appliedAt) VALUES (?, ?)", [migration.id, getUnixTimeSeconds$1()]);
720
1362
  });
721
1363
  }
722
1364
  await reconcileMigrationAliases(db);
723
1365
  }
724
1366
 
725
1367
  //#endregion
726
- //#region src/repositories/MintRepository.ts
727
- var ExpoMintRepository = class {
1368
+ //#region ../sql-storage/src/repositories/MintRepository.ts
1369
+ var SqliteMintRepository = class {
728
1370
  db;
729
1371
  constructor(db) {
730
1372
  this.db = db;
@@ -809,8 +1451,24 @@ var ExpoMintRepository = class {
809
1451
  };
810
1452
 
811
1453
  //#endregion
812
- //#region src/repositories/KeysetRepository.ts
813
- var ExpoKeysetRepository = class {
1454
+ //#region ../sql-storage/src/utils.ts
1455
+ function getUnixTimeSeconds() {
1456
+ return Math.floor(Date.now() / 1e3);
1457
+ }
1458
+ function hexToBytes(hexString) {
1459
+ if (!/^[0-9a-fA-F]+$/.test(hexString)) throw new Error("Invalid hex string: contains non-hex characters");
1460
+ if (hexString.length % 2 !== 0) throw new Error(`Invalid hex string: odd length (${hexString.length})`);
1461
+ const matches = hexString.match(/.{2}/g);
1462
+ if (!matches) throw new Error("Failed to parse hex string");
1463
+ return new Uint8Array(matches.map((byte) => parseInt(byte, 16)));
1464
+ }
1465
+ function bytesToHex(bytes) {
1466
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
1467
+ }
1468
+
1469
+ //#endregion
1470
+ //#region ../sql-storage/src/repositories/KeysetRepository.ts
1471
+ var SqliteKeysetRepository = class {
814
1472
  db;
815
1473
  constructor(db) {
816
1474
  this.db = db;
@@ -887,98 +1545,83 @@ var ExpoKeysetRepository = class {
887
1545
  };
888
1546
 
889
1547
  //#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("");
1548
+ //#region ../sql-storage/src/repositories/KeyRingRepository.ts
1549
+ const DEFAULT_KEYPAIR_PURPOSE = "p2pk";
1550
+ function rowToKeypair(row) {
1551
+ return {
1552
+ publicKeyHex: row.publicKey,
1553
+ secretKey: hexToBytes(row.secretKey),
1554
+ derivationIndex: row.derivationIndex ?? void 0,
1555
+ purpose: row.purpose ?? DEFAULT_KEYPAIR_PURPOSE
1556
+ };
907
1557
  }
908
-
909
- //#endregion
910
- //#region src/repositories/KeyRingRepository.ts
911
- var ExpoKeyRingRepository = class {
1558
+ var SqliteKeyRingRepository = class {
912
1559
  db;
913
1560
  constructor(db) {
914
1561
  this.db = db;
915
1562
  }
916
- async getPersistedKeyPair(publicKey) {
917
- const row = await this.db.get("SELECT publicKey, secretKey, derivationIndex FROM coco_cashu_keypairs WHERE publicKey = ? LIMIT 1", [publicKey]);
1563
+ async getPersistedKeyPair(publicKey, purpose) {
1564
+ const row = await this.db.get(`SELECT publicKey, secretKey, derivationIndex, purpose
1565
+ FROM coco_cashu_keypairs
1566
+ WHERE publicKey = ? ${purpose ? "AND purpose = ?" : ""} LIMIT 1`, purpose ? [publicKey, purpose] : [publicKey]);
918
1567
  if (!row) return null;
919
1568
  try {
920
- const secretKeyBytes = hexToBytes(row.secretKey);
921
- return {
922
- publicKeyHex: row.publicKey,
923
- secretKey: secretKeyBytes,
924
- derivationIndex: row.derivationIndex ?? void 0
925
- };
1569
+ return rowToKeypair(row);
926
1570
  } catch (error) {
927
1571
  throw new Error(`Failed to parse secret key for public key ${publicKey}: ${error instanceof Error ? error.message : "unknown error"}`);
928
1572
  }
929
1573
  }
930
1574
  async setPersistedKeyPair(keyPair) {
931
1575
  const secretKeyHex = bytesToHex(keyPair.secretKey);
932
- await this.db.run(`INSERT INTO coco_cashu_keypairs (publicKey, secretKey, createdAt, derivationIndex)
933
- VALUES (?, ?, ?, ?)
1576
+ const purpose = keyPair.purpose ?? DEFAULT_KEYPAIR_PURPOSE;
1577
+ await this.db.run(`INSERT INTO coco_cashu_keypairs (publicKey, secretKey, createdAt, derivationIndex, purpose)
1578
+ VALUES (?, ?, ?, ?, ?)
934
1579
  ON CONFLICT(publicKey) DO UPDATE SET
935
1580
  secretKey=excluded.secretKey,
936
- derivationIndex=COALESCE(excluded.derivationIndex, coco_cashu_keypairs.derivationIndex)`, [
1581
+ derivationIndex=COALESCE(excluded.derivationIndex, coco_cashu_keypairs.derivationIndex),
1582
+ purpose=excluded.purpose`, [
937
1583
  keyPair.publicKeyHex,
938
1584
  secretKeyHex,
939
1585
  Date.now(),
940
- keyPair.derivationIndex ?? null
1586
+ keyPair.derivationIndex ?? null,
1587
+ purpose
941
1588
  ]);
942
1589
  }
943
- async deletePersistedKeyPair(publicKey) {
944
- await this.db.run("DELETE FROM coco_cashu_keypairs WHERE publicKey = ?", [publicKey]);
1590
+ async deletePersistedKeyPair(publicKey, purpose) {
1591
+ await this.db.run(`DELETE FROM coco_cashu_keypairs WHERE publicKey = ? ${purpose ? "AND purpose = ?" : ""}`, purpose ? [publicKey, purpose] : [publicKey]);
945
1592
  }
946
- async getAllPersistedKeyPairs() {
947
- return (await this.db.all("SELECT publicKey, secretKey, derivationIndex FROM coco_cashu_keypairs")).map((row) => {
1593
+ async getAllPersistedKeyPairs(purpose) {
1594
+ return (await this.db.all(`SELECT publicKey, secretKey, derivationIndex, purpose
1595
+ FROM coco_cashu_keypairs ${purpose ? "WHERE purpose = ?" : ""}`, purpose ? [purpose] : [])).map((row) => {
948
1596
  try {
949
- const secretKeyBytes = hexToBytes(row.secretKey);
950
- return {
951
- publicKeyHex: row.publicKey,
952
- secretKey: secretKeyBytes,
953
- derivationIndex: row.derivationIndex ?? void 0
954
- };
1597
+ return rowToKeypair(row);
955
1598
  } catch (error) {
956
1599
  throw new Error(`Failed to parse secret key for public key ${row.publicKey}: ${error instanceof Error ? error.message : "unknown error"}`);
957
1600
  }
958
1601
  });
959
1602
  }
960
- async getLatestKeyPair() {
961
- const row = await this.db.get("SELECT publicKey, secretKey, derivationIndex FROM coco_cashu_keypairs ORDER BY createdAt DESC LIMIT 1");
1603
+ async getLatestKeyPair(purpose) {
1604
+ const row = await this.db.get(`SELECT publicKey, secretKey, derivationIndex, purpose
1605
+ FROM coco_cashu_keypairs
1606
+ ${purpose ? "WHERE purpose = ?" : ""}
1607
+ ORDER BY createdAt DESC LIMIT 1`, purpose ? [purpose] : []);
962
1608
  if (!row) return null;
963
1609
  try {
964
- const secretKeyBytes = hexToBytes(row.secretKey);
965
- return {
966
- publicKeyHex: row.publicKey,
967
- secretKey: secretKeyBytes,
968
- derivationIndex: row.derivationIndex ?? void 0
969
- };
1610
+ return rowToKeypair(row);
970
1611
  } catch (error) {
971
1612
  throw new Error(`Failed to parse latest secret key for public key ${row.publicKey}: ${error instanceof Error ? error.message : "unknown error"}`);
972
1613
  }
973
1614
  }
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;
1615
+ async getLastDerivationIndex(purpose) {
1616
+ return (await this.db.get(`SELECT derivationIndex FROM coco_cashu_keypairs
1617
+ WHERE derivationIndex IS NOT NULL ${purpose ? "AND purpose = ?" : ""}
1618
+ ORDER BY derivationIndex DESC LIMIT 1`, purpose ? [purpose] : []))?.derivationIndex ?? -1;
976
1619
  }
977
1620
  };
978
1621
 
979
1622
  //#endregion
980
- //#region src/repositories/CounterRepository.ts
981
- var ExpoCounterRepository = class {
1623
+ //#region ../sql-storage/src/repositories/CounterRepository.ts
1624
+ var SqliteCounterRepository = class {
982
1625
  db;
983
1626
  constructor(db) {
984
1627
  this.db = db;
@@ -1004,23 +1647,44 @@ var ExpoCounterRepository = class {
1004
1647
  };
1005
1648
 
1006
1649
  //#endregion
1007
- //#region src/repositories/ProofRepository.ts
1650
+ //#region ../sql-storage/src/repositories/ProofRepository.ts
1008
1651
  const MAX_PROOF_SECRET_LOOKUP_BATCH_SIZE = 900;
1652
+ const PROOF_COLUMNS = "mintUrl, id, unit, amount, secret, C, dleqJson, witnessJson, state, usedByOperationId, createdByOperationId";
1653
+ function normalizeProofUnit(proof) {
1654
+ return normalizeUnit(proof.unit);
1655
+ }
1656
+ function getUnitFilter(filter) {
1657
+ const units = [...filter?.units ?? [], ...filter?.unit ? [filter.unit] : []];
1658
+ if (units.length === 0) return void 0;
1659
+ return Array.from(new Set(units.map((unit) => normalizeUnit(unit))));
1660
+ }
1661
+ function appendUnitFilter(sql, params, filter) {
1662
+ const units = getUnitFilter(filter);
1663
+ if (!units || units.length === 0) return sql;
1664
+ if (units.length === 1) {
1665
+ const [unit] = units;
1666
+ params.push(unit);
1667
+ return `${sql} AND unit = ?`;
1668
+ }
1669
+ params.push(...units);
1670
+ return `${sql} AND unit IN (${units.map(() => "?").join(", ")})`;
1671
+ }
1009
1672
  function rowToProof(r) {
1010
1673
  return {
1011
1674
  id: r.id,
1012
- amount: r.amount,
1675
+ amount: deserializeAmount(r.amount),
1013
1676
  secret: r.secret,
1014
1677
  C: r.C,
1015
1678
  ...r.dleqJson ? { dleq: JSON.parse(r.dleqJson) } : {},
1016
1679
  ...r.witnessJson ? { witness: JSON.parse(r.witnessJson) } : {},
1017
1680
  mintUrl: r.mintUrl,
1681
+ unit: normalizeUnit(r.unit ?? void 0, { defaultUnit: DEFAULT_UNIT }),
1018
1682
  state: r.state,
1019
1683
  ...r.usedByOperationId ? { usedByOperationId: r.usedByOperationId } : {},
1020
1684
  ...r.createdByOperationId ? { createdByOperationId: r.createdByOperationId } : {}
1021
1685
  };
1022
1686
  }
1023
- var ExpoProofRepository = class {
1687
+ var SqliteProofRepository = class {
1024
1688
  db;
1025
1689
  constructor(db) {
1026
1690
  this.db = db;
@@ -1028,17 +1692,22 @@ var ExpoProofRepository = class {
1028
1692
  async saveProofs(mintUrl, proofs) {
1029
1693
  if (!proofs || proofs.length === 0) return;
1030
1694
  const now = getUnixTimeSeconds();
1695
+ const normalizedProofs = proofs.map((proof) => ({
1696
+ ...proof,
1697
+ unit: normalizeProofUnit(proof)
1698
+ }));
1031
1699
  await this.db.transaction(async (tx) => {
1032
1700
  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) {
1701
+ for (const p of normalizedProofs) if (await tx.get(selectSql, [mintUrl, p.secret])) throw new Error(`Proof with secret already exists: ${p.secret}`);
1702
+ const insertSql = "INSERT INTO coco_cashu_proofs (mintUrl, id, unit, amount, secret, C, dleqJson, witnessJson, state, createdAt, usedByOperationId, createdByOperationId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
1703
+ for (const p of normalizedProofs) {
1036
1704
  const dleqJson = p.dleq ? JSON.stringify(p.dleq) : null;
1037
1705
  const witnessJson = p.witness ? JSON.stringify(p.witness) : null;
1038
1706
  await tx.run(insertSql, [
1039
1707
  mintUrl,
1040
1708
  p.id,
1041
- p.amount,
1709
+ p.unit,
1710
+ serializeAmount(p.amount),
1042
1711
  p.secret,
1043
1712
  p.C,
1044
1713
  dleqJson,
@@ -1051,22 +1720,29 @@ var ExpoProofRepository = class {
1051
1720
  }
1052
1721
  });
1053
1722
  }
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);
1723
+ async getReadyProofs(mintUrl, filter) {
1724
+ const params = [mintUrl];
1725
+ return (await this.db.all(appendUnitFilter(`SELECT ${PROOF_COLUMNS} FROM coco_cashu_proofs WHERE mintUrl = ? AND state = 'ready'`, params, filter), params)).map(rowToProof);
1056
1726
  }
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);
1727
+ async getInflightProofs(mintUrls, filter) {
1728
+ if (!mintUrls || mintUrls.length === 0) {
1729
+ const params = [];
1730
+ return (await this.db.all(appendUnitFilter(`SELECT ${PROOF_COLUMNS} FROM coco_cashu_proofs WHERE state = 'inflight'`, params, filter), params)).map(rowToProof);
1731
+ }
1059
1732
  const mintUrlList = mintUrls.map((url) => url.trim()).filter((url) => url.length > 0);
1060
1733
  if (mintUrlList.length === 0) return [];
1061
1734
  const uniqueMintUrls = Array.from(new Set(mintUrlList));
1062
1735
  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);
1736
+ const params = uniqueMintUrls;
1737
+ return (await this.db.all(appendUnitFilter(`SELECT ${PROOF_COLUMNS} FROM coco_cashu_proofs WHERE state = 'inflight' AND mintUrl IN (${placeholders})`, params, filter), params)).map(rowToProof);
1064
1738
  }
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);
1739
+ async getAllReadyProofs(filter) {
1740
+ const params = [];
1741
+ return (await this.db.all(appendUnitFilter(`SELECT ${PROOF_COLUMNS} FROM coco_cashu_proofs WHERE state = 'ready'`, params, filter), params)).map(rowToProof);
1067
1742
  }
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);
1743
+ async getProofsByKeysetId(mintUrl, keysetId, filter) {
1744
+ const params = [mintUrl, keysetId];
1745
+ return (await this.db.all(appendUnitFilter(`SELECT ${PROOF_COLUMNS} FROM coco_cashu_proofs WHERE mintUrl = ? AND id = ? AND state = 'ready'`, params, filter), params)).map(rowToProof);
1070
1746
  }
1071
1747
  async setProofState(mintUrl, secrets, state) {
1072
1748
  if (!secrets || secrets.length === 0) return;
@@ -1126,7 +1802,7 @@ var ExpoProofRepository = class {
1126
1802
  });
1127
1803
  }
1128
1804
  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]);
1805
+ const row = await this.db.get(`SELECT ${PROOF_COLUMNS} FROM coco_cashu_proofs WHERE mintUrl = ? AND secret = ?`, [mintUrl, secret]);
1130
1806
  return row ? rowToProof(row) : null;
1131
1807
  }
1132
1808
  async getProofsBySecrets(mintUrl, secrets) {
@@ -1136,7 +1812,7 @@ var ExpoProofRepository = class {
1136
1812
  for (let i = 0; i < uniqueSecrets.length; i += MAX_PROOF_SECRET_LOOKUP_BATCH_SIZE) {
1137
1813
  const secretBatch = uniqueSecrets.slice(i, i + MAX_PROOF_SECRET_LOOKUP_BATCH_SIZE);
1138
1814
  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]);
1815
+ const rows = await this.db.all(`SELECT ${PROOF_COLUMNS} FROM coco_cashu_proofs WHERE mintUrl = ? AND secret IN (${placeholders})`, [mintUrl, ...secretBatch]);
1140
1816
  for (const row of rows) proofsBySecret.set(row.secret, rowToProof(row));
1141
1817
  }
1142
1818
  return uniqueSecrets.flatMap((secret) => {
@@ -1145,442 +1821,663 @@ var ExpoProofRepository = class {
1145
1821
  });
1146
1822
  }
1147
1823
  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 = ?)", [
1824
+ return (await this.db.all(`SELECT ${PROOF_COLUMNS} FROM coco_cashu_proofs WHERE mintUrl = ? AND (usedByOperationId = ? OR createdByOperationId = ?)`, [
1149
1825
  mintUrl,
1150
1826
  operationId,
1151
1827
  operationId
1152
1828
  ])).map(rowToProof);
1153
1829
  }
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);
1830
+ async getAvailableProofs(mintUrl, filter) {
1831
+ const params = [mintUrl];
1832
+ return (await this.db.all(appendUnitFilter(`SELECT ${PROOF_COLUMNS} FROM coco_cashu_proofs WHERE mintUrl = ? AND state = 'ready' AND usedByOperationId IS NULL`, params, filter), params)).map(rowToProof);
1156
1833
  }
1157
1834
  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);
1835
+ return (await this.db.all(`SELECT ${PROOF_COLUMNS} FROM coco_cashu_proofs WHERE state = 'ready' AND usedByOperationId IS NOT NULL`)).map(rowToProof);
1159
1836
  }
1160
1837
  };
1161
1838
 
1162
1839
  //#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;
1840
+ //#region ../sql-storage/src/repositories/MeltQuoteRepository.ts
1841
+ function rowToQuote(row) {
1842
+ const base = {
1843
+ mintUrl: row.mintUrl,
1844
+ method: row.method,
1845
+ quoteId: row.quoteId,
1846
+ quote: row.quoteId,
1847
+ state: row.state,
1848
+ request: row.request,
1849
+ amount: deserializeAmount(row.amount),
1850
+ unit: row.unit,
1851
+ expiry: row.expiry,
1852
+ change: row.changeJson ? JSON.parse(row.changeJson) : void 0,
1853
+ lastObservedRemoteState: row.lastObservedRemoteState ?? void 0,
1854
+ lastObservedRemoteStateAt: row.lastObservedRemoteStateAt ?? void 0,
1855
+ createdAt: row.createdAt,
1856
+ updatedAt: row.updatedAt
1857
+ };
1858
+ if (row.method === "onchain") {
1859
+ const feeOptions = row.fee_options_json ? JSON.parse(row.fee_options_json) : void 0;
1860
+ if (!Array.isArray(feeOptions) || feeOptions.length === 0) throw new Error(`Stored onchain melt quote ${row.quoteId} is missing fee_options`);
1173
1861
  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
1862
+ ...base,
1863
+ method: "onchain",
1864
+ fee_options: feeOptions.map((option) => ({
1865
+ ...option,
1866
+ fee_reserve: deserializeAmount(option.fee_reserve)
1867
+ })),
1868
+ outpoint: row.outpoint ?? void 0
1182
1869
  };
1183
1870
  }
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
1871
+ if (row.fee_reserve === null || row.fee_reserve === void 0) throw new Error(`Stored BOLT melt quote ${row.quoteId} is missing fee_reserve`);
1872
+ return {
1873
+ ...base,
1874
+ method: row.method,
1875
+ fee_reserve: deserializeAmount(row.fee_reserve),
1876
+ payment_preimage: row.payment_preimage ?? void 0
1877
+ };
1878
+ }
1879
+ var SqliteMeltQuoteRepository = class {
1880
+ constructor(db) {
1881
+ this.db = db;
1882
+ }
1883
+ async getMeltQuoteById(identity) {
1884
+ const normalizedMintUrl = normalizeMintUrl(identity.mintUrl);
1885
+ const rows = await this.db.all(`SELECT mintUrl, method, quoteId, state, request, amount, unit, fee_reserve, expiry,
1886
+ payment_preimage, fee_options_json, outpoint, changeJson, lastObservedRemoteState, lastObservedRemoteStateAt,
1887
+ createdAt, updatedAt
1888
+ FROM coco_cashu_melt_quotes
1889
+ WHERE mintUrl = ? AND quoteId = ?`, [normalizedMintUrl, identity.quoteId]);
1890
+ if (rows.length > 1) throw new QuoteIdentityConflictError("melt", normalizedMintUrl, identity.quoteId, rows.map((row) => row.method));
1891
+ return rows[0] ? rowToQuote(rows[0]) : null;
1892
+ }
1893
+ async getMeltQuote(mintUrl, method, quoteId) {
1894
+ const row = await this.db.get(`SELECT mintUrl, method, quoteId, state, request, amount, unit, fee_reserve, expiry,
1895
+ payment_preimage, fee_options_json, outpoint, changeJson, lastObservedRemoteState, lastObservedRemoteStateAt,
1896
+ createdAt, updatedAt
1897
+ FROM coco_cashu_melt_quotes
1898
+ WHERE mintUrl = ? AND method = ? AND quoteId = ? LIMIT 1`, [
1899
+ normalizeMintUrl(mintUrl),
1900
+ method,
1901
+ quoteId
1902
+ ]);
1903
+ return row ? rowToQuote(row) : null;
1904
+ }
1905
+ async upsertMeltQuote(quote) {
1906
+ const now = Date.now();
1907
+ const normalizedMintUrl = normalizeMintUrl(quote.mintUrl);
1908
+ const identityOwner = await this.getMeltQuoteById({
1909
+ mintUrl: normalizedMintUrl,
1910
+ quoteId: quote.quoteId
1911
+ });
1912
+ if (identityOwner && identityOwner.method !== quote.method) throw new QuoteIdentityConflictError("melt", normalizedMintUrl, quote.quoteId, [identityOwner.method, quote.method], `Melt quote ${quote.quoteId} at ${normalizedMintUrl} already exists for method ${identityOwner.method}`);
1913
+ await this.db.run(`INSERT INTO coco_cashu_melt_quotes
1914
+ (mintUrl, method, quoteId, state, request, amount, unit, fee_reserve, expiry,
1915
+ payment_preimage, fee_options_json, outpoint, changeJson, lastObservedRemoteState,
1916
+ lastObservedRemoteStateAt, createdAt, updatedAt)
1917
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1918
+ ON CONFLICT(mintUrl, method, quoteId) DO UPDATE SET
1188
1919
  state=excluded.state,
1189
1920
  request=excluded.request,
1190
1921
  amount=excluded.amount,
1191
1922
  unit=excluded.unit,
1923
+ fee_reserve=excluded.fee_reserve,
1192
1924
  expiry=excluded.expiry,
1193
- pubkey=excluded.pubkey`, [
1194
- quote.mintUrl,
1195
- quote.quote,
1925
+ payment_preimage=excluded.payment_preimage,
1926
+ fee_options_json=excluded.fee_options_json,
1927
+ outpoint=excluded.outpoint,
1928
+ changeJson=excluded.changeJson,
1929
+ lastObservedRemoteState=excluded.lastObservedRemoteState,
1930
+ lastObservedRemoteStateAt=excluded.lastObservedRemoteStateAt,
1931
+ updatedAt=excluded.updatedAt`, [
1932
+ normalizedMintUrl,
1933
+ quote.method,
1934
+ quote.quoteId,
1196
1935
  quote.state,
1197
1936
  quote.request,
1198
- quote.amount,
1937
+ serializeAmount(quote.amount),
1199
1938
  quote.unit,
1939
+ quote.method === "onchain" ? null : serializeAmount(quote.fee_reserve),
1200
1940
  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
1941
+ quote.method === "onchain" ? null : quote.payment_preimage ?? null,
1942
+ quote.method === "onchain" ? stringifyJson(quote.fee_options.map((option) => ({
1943
+ ...option,
1944
+ fee_reserve: serializeAmount(option.fee_reserve)
1945
+ }))) : null,
1946
+ quote.method === "onchain" ? quote.outpoint ?? null : null,
1947
+ quote.change ? stringifyJson(quote.change) : null,
1948
+ quote.lastObservedRemoteState ?? quote.state,
1949
+ quote.lastObservedRemoteStateAt ?? now,
1950
+ quote.createdAt,
1951
+ quote.updatedAt || now
1209
1952
  ]);
1210
1953
  }
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
- }));
1954
+ async getPendingMeltQuotes(method) {
1955
+ return (await this.db.all(`SELECT mintUrl, method, quoteId, state, request, amount, unit, fee_reserve, expiry,
1956
+ payment_preimage, fee_options_json, outpoint, changeJson, lastObservedRemoteState, lastObservedRemoteStateAt,
1957
+ createdAt, updatedAt
1958
+ FROM coco_cashu_melt_quotes
1959
+ WHERE state != 'PAID' ${method ? "AND method = ?" : ""}`, method ? [method] : [])).map(rowToQuote);
1223
1960
  }
1224
1961
  };
1225
1962
 
1226
1963
  //#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;
1964
+ //#region ../sql-storage/src/repositories/MintQuoteRepository.ts
1965
+ function parseQuoteData(value) {
1966
+ if (!value) return {};
1967
+ const parsed = JSON.parse(value);
1968
+ return parsed && typeof parsed === "object" ? parsed : {};
1969
+ }
1970
+ function rowToMintQuote(row) {
1971
+ const quoteData = parseQuoteData(row.quoteDataJson);
1972
+ if (row.method === "onchain" || row.method === "bolt12") {
1973
+ const pubkey = quoteData.pubkey ?? row.pubkey ?? "";
1974
+ const amountValue = quoteData.amount ?? row.amount ?? void 0;
1975
+ const amount = row.method === "bolt12" && amountValue !== void 0 ? deserializeAmount(amountValue) : void 0;
1237
1976
  return {
1238
1977
  mintUrl: row.mintUrl,
1239
- quote: row.quote,
1240
- state: row.state,
1978
+ method: row.method,
1979
+ quoteId: row.quoteId,
1980
+ quote: row.quoteId,
1241
1981
  request: row.request,
1242
- amount: row.amount,
1243
1982
  unit: row.unit,
1983
+ ...amount !== void 0 ? { amount } : {},
1244
1984
  expiry: row.expiry,
1245
- fee_reserve: row.fee_reserve,
1246
- payment_preimage: row.payment_preimage
1985
+ pubkey,
1986
+ reusable: true,
1987
+ quoteData: {
1988
+ pubkey,
1989
+ ...amount !== void 0 ? { amount } : {},
1990
+ amountPaid: deserializeAmount(quoteData.amountPaid ?? 0),
1991
+ amountIssued: deserializeAmount(quoteData.amountIssued ?? 0)
1992
+ },
1993
+ lastObservedRemoteStateAt: row.lastObservedRemoteStateAt ?? void 0,
1994
+ createdAt: row.createdAt,
1995
+ updatedAt: row.updatedAt
1247
1996
  };
1248
1997
  }
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
1998
+ const amount = deserializeAmount(quoteData.amount ?? row.amount ?? 0);
1999
+ const state = row.state ?? row.lastObservedRemoteState ?? "UNPAID";
2000
+ return {
2001
+ mintUrl: row.mintUrl,
2002
+ method: "bolt11",
2003
+ quoteId: row.quoteId,
2004
+ quote: row.quoteId,
2005
+ state,
2006
+ request: row.request,
2007
+ amount,
2008
+ unit: row.unit,
2009
+ expiry: row.expiry,
2010
+ pubkey: row.pubkey ?? void 0,
2011
+ lastObservedRemoteState: row.lastObservedRemoteState ?? state,
2012
+ lastObservedRemoteStateAt: row.lastObservedRemoteStateAt ?? void 0,
2013
+ reusable: false,
2014
+ quoteData: { amount },
2015
+ createdAt: row.createdAt,
2016
+ updatedAt: row.updatedAt
2017
+ };
2018
+ }
2019
+ function serializeQuoteData(quote) {
2020
+ if (isStatefulMintQuote(quote)) return stringifyJson({ amount: serializeAmount(quote.quoteData.amount) });
2021
+ if (quote.method === "bolt12") {
2022
+ const amount = quote.quoteData.amount ?? quote.amount;
2023
+ return stringifyJson({
2024
+ pubkey: quote.quoteData.pubkey,
2025
+ ...amount !== void 0 ? { amount: serializeAmount(amount) } : {},
2026
+ amountPaid: serializeAmount(quote.quoteData.amountPaid),
2027
+ amountIssued: serializeAmount(quote.quoteData.amountIssued)
2028
+ });
2029
+ }
2030
+ return stringifyJson({
2031
+ pubkey: quote.quoteData.pubkey,
2032
+ amountPaid: serializeAmount(quote.quoteData.amountPaid),
2033
+ amountIssued: serializeAmount(quote.quoteData.amountIssued)
2034
+ });
2035
+ }
2036
+ var SqliteMintQuoteRepository = class {
2037
+ db;
2038
+ constructor(db) {
2039
+ this.db = db;
2040
+ }
2041
+ async getMintQuoteById(identity) {
2042
+ const normalizedMintUrl = normalizeMintUrl(identity.mintUrl);
2043
+ const rows = await this.db.all(`SELECT mintUrl, method, quoteId, state, request, amount, unit, expiry, pubkey,
2044
+ quoteDataJson, lastObservedRemoteState, lastObservedRemoteStateAt, reusable,
2045
+ createdAt, updatedAt
2046
+ FROM coco_cashu_canonical_mint_quotes
2047
+ WHERE mintUrl = ? AND quoteId = ?`, [normalizedMintUrl, identity.quoteId]);
2048
+ if (rows.length > 1) throw new QuoteIdentityConflictError("mint", normalizedMintUrl, identity.quoteId, rows.map((row) => row.method));
2049
+ return rows[0] ? rowToMintQuote(rows[0]) : null;
2050
+ }
2051
+ async getMintQuote(mintUrl, method, quoteId) {
2052
+ const row = await this.db.get(`SELECT mintUrl, method, quoteId, state, request, amount, unit, expiry, pubkey,
2053
+ quoteDataJson, lastObservedRemoteState, lastObservedRemoteStateAt, reusable,
2054
+ createdAt, updatedAt
2055
+ FROM coco_cashu_canonical_mint_quotes
2056
+ WHERE mintUrl = ? AND method = ? AND quoteId = ? LIMIT 1`, [
2057
+ normalizeMintUrl(mintUrl),
2058
+ method,
2059
+ quoteId
2060
+ ]);
2061
+ return row ? rowToMintQuote(row) : null;
2062
+ }
2063
+ async upsertMintQuote(quote) {
2064
+ const now = Date.now();
2065
+ const normalizedMintUrl = normalizeMintUrl(quote.mintUrl);
2066
+ const identityOwner = await this.getMintQuoteById({
2067
+ mintUrl: normalizedMintUrl,
2068
+ quoteId: quote.quoteId
2069
+ });
2070
+ if (identityOwner && identityOwner.method !== quote.method) throw new QuoteIdentityConflictError("mint", normalizedMintUrl, quote.quoteId, [identityOwner.method, quote.method], `Mint quote ${quote.quoteId} at ${normalizedMintUrl} already exists for method ${identityOwner.method}`);
2071
+ const state = getMintQuoteRemoteState(quote) ?? null;
2072
+ const amount = getMintQuoteAmount(quote);
2073
+ await this.db.run(`INSERT INTO coco_cashu_canonical_mint_quotes
2074
+ (mintUrl, method, quoteId, state, request, amount, unit, expiry, pubkey, quoteDataJson,
2075
+ lastObservedRemoteState, lastObservedRemoteStateAt, reusable, createdAt, updatedAt)
2076
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2077
+ ON CONFLICT(mintUrl, method, quoteId) DO UPDATE SET
1253
2078
  state=excluded.state,
1254
2079
  request=excluded.request,
1255
2080
  amount=excluded.amount,
1256
2081
  unit=excluded.unit,
1257
2082
  expiry=excluded.expiry,
1258
- fee_reserve=excluded.fee_reserve,
1259
- payment_preimage=excluded.payment_preimage`, [
1260
- quote.mintUrl,
1261
- quote.quote,
1262
- quote.state,
2083
+ pubkey=excluded.pubkey,
2084
+ quoteDataJson=excluded.quoteDataJson,
2085
+ lastObservedRemoteState=excluded.lastObservedRemoteState,
2086
+ lastObservedRemoteStateAt=excluded.lastObservedRemoteStateAt,
2087
+ reusable=excluded.reusable,
2088
+ updatedAt=excluded.updatedAt`, [
2089
+ normalizedMintUrl,
2090
+ quote.method,
2091
+ quote.quoteId,
2092
+ state,
1263
2093
  quote.request,
1264
- quote.amount,
2094
+ amount ? serializeAmount(amount) : null,
1265
2095
  quote.unit,
1266
2096
  quote.expiry,
1267
- quote.fee_reserve,
1268
- quote.payment_preimage ?? null
2097
+ quote.pubkey ?? null,
2098
+ serializeQuoteData(quote),
2099
+ getMintQuoteRemoteState(quote) ?? null,
2100
+ quote.lastObservedRemoteStateAt ?? now,
2101
+ quote.reusable ? 1 : 0,
2102
+ quote.createdAt,
2103
+ quote.updatedAt || now
1269
2104
  ]);
1270
2105
  }
1271
- async setMeltQuoteState(mintUrl, quoteId, state) {
1272
- await this.db.run("UPDATE coco_cashu_melt_quotes SET state = ? WHERE mintUrl = ? AND quote = ?", [
2106
+ async setMintQuoteState(mintUrl, method, quoteId, state, observedAt = Date.now()) {
2107
+ await this.db.run(`UPDATE coco_cashu_canonical_mint_quotes
2108
+ SET state = ?, lastObservedRemoteState = ?, lastObservedRemoteStateAt = ?, updatedAt = ?
2109
+ WHERE mintUrl = ? AND method = ? AND quoteId = ?`, [
1273
2110
  state,
1274
- mintUrl,
2111
+ state,
2112
+ observedAt,
2113
+ observedAt,
2114
+ normalizeMintUrl(mintUrl),
2115
+ method,
1275
2116
  quoteId
1276
2117
  ]);
1277
2118
  }
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) => ({
2119
+ async getPendingMintQuotes(method) {
2120
+ return (await this.db.all(`SELECT mintUrl, method, quoteId, state, request, amount, unit, expiry, pubkey,
2121
+ quoteDataJson, lastObservedRemoteState, lastObservedRemoteStateAt, reusable,
2122
+ createdAt, updatedAt
2123
+ FROM coco_cashu_canonical_mint_quotes
2124
+ WHERE (state IS NULL OR state != 'ISSUED') ${method ? "AND method = ?" : ""}`, method ? [method] : [])).map(rowToMintQuote).filter(isMintQuotePending);
2125
+ }
2126
+ };
2127
+
2128
+ //#endregion
2129
+ //#region ../sql-storage/src/repositories/LegacyMintQuoteRepository.ts
2130
+ var SqliteLegacyMintQuoteRepository = class {
2131
+ constructor(db) {
2132
+ this.db = db;
2133
+ }
2134
+ async getPendingLegacyMintQuotes(mintUrl) {
2135
+ const normalizedMintUrl = mintUrl ? normalizeMintUrl(mintUrl) : void 0;
2136
+ const rows = await this.db.all(`SELECT mintUrl, quote, state, request, amount, unit, expiry, pubkey
2137
+ FROM coco_cashu_mint_quotes
2138
+ WHERE state != 'ISSUED' ${normalizedMintUrl ? "AND mintUrl = ?" : ""}`, normalizedMintUrl ? [normalizedMintUrl] : []);
2139
+ const now = Date.now();
2140
+ return rows.map((row) => ({
1281
2141
  mintUrl: row.mintUrl,
2142
+ method: "bolt11",
2143
+ quoteId: row.quote,
1282
2144
  quote: row.quote,
1283
2145
  state: row.state,
1284
2146
  request: row.request,
1285
- amount: row.amount,
2147
+ amount: deserializeAmount(row.amount),
1286
2148
  unit: row.unit,
1287
2149
  expiry: row.expiry,
1288
- fee_reserve: row.fee_reserve,
1289
- payment_preimage: row.payment_preimage
2150
+ pubkey: row.pubkey ?? void 0,
2151
+ lastObservedRemoteState: row.state,
2152
+ lastObservedRemoteStateAt: now,
2153
+ reusable: false,
2154
+ quoteData: { amount: deserializeAmount(row.amount) },
2155
+ createdAt: now,
2156
+ updatedAt: now
1290
2157
  }));
1291
2158
  }
1292
2159
  };
1293
2160
 
1294
2161
  //#endregion
1295
- //#region src/repositories/HistoryRepository.ts
1296
- var ExpoHistoryRepository = class {
2162
+ //#region ../sql-storage/src/repositories/HistoryRepository.ts
2163
+ const projectionSelect = `
2164
+ SELECT *
2165
+ FROM (
2166
+ SELECT
2167
+ 'operation' AS source,
2168
+ 'send:' || id AS id,
2169
+ NULL AS legacyHistoryId,
2170
+ 'send' AS type,
2171
+ mintUrl,
2172
+ COALESCE(unit, 'sat') AS unit,
2173
+ amount,
2174
+ createdAt * 1000 AS createdAt,
2175
+ updatedAt * 1000 AS updatedAt,
2176
+ state,
2177
+ NULL AS quoteId,
2178
+ NULL AS paymentRequest,
2179
+ tokenJson,
2180
+ NULL AS inputProofsJson,
2181
+ NULL AS metadata,
2182
+ id AS operationId,
2183
+ NULL AS remoteState,
2184
+ error
2185
+ FROM coco_cashu_send_operations
2186
+ WHERE state != 'init'
2187
+
2188
+ UNION ALL
2189
+
2190
+ SELECT
2191
+ 'operation' AS source,
2192
+ 'melt:' || id AS id,
2193
+ NULL AS legacyHistoryId,
2194
+ 'melt' AS type,
2195
+ mintUrl,
2196
+ COALESCE(unit, 'sat') AS unit,
2197
+ amount,
2198
+ createdAt * 1000 AS createdAt,
2199
+ updatedAt * 1000 AS updatedAt,
2200
+ state,
2201
+ quoteId,
2202
+ NULL AS paymentRequest,
2203
+ NULL AS tokenJson,
2204
+ NULL AS inputProofsJson,
2205
+ NULL AS metadata,
2206
+ id AS operationId,
2207
+ NULL AS remoteState,
2208
+ error
2209
+ FROM coco_cashu_melt_operations
2210
+ WHERE state IN ('prepared', 'executing', 'pending', 'finalized', 'rolling_back', 'rolled_back')
2211
+
2212
+ UNION ALL
2213
+
2214
+ SELECT
2215
+ 'operation' AS source,
2216
+ 'mint:' || op.id AS id,
2217
+ NULL AS legacyHistoryId,
2218
+ 'mint' AS type,
2219
+ op.mintUrl,
2220
+ op.unit,
2221
+ op.amount,
2222
+ op.createdAt * 1000 AS createdAt,
2223
+ op.updatedAt * 1000 AS updatedAt,
2224
+ op.state,
2225
+ op.quoteId,
2226
+ op.request AS paymentRequest,
2227
+ NULL AS tokenJson,
2228
+ NULL AS inputProofsJson,
2229
+ NULL AS metadata,
2230
+ op.id AS operationId,
2231
+ q.lastObservedRemoteState AS remoteState,
2232
+ op.error
2233
+ FROM coco_cashu_mint_operations op
2234
+ LEFT JOIN coco_cashu_canonical_mint_quotes q
2235
+ ON q.mintUrl = op.mintUrl
2236
+ AND q.method = op.method
2237
+ AND q.quoteId = op.quoteId
2238
+ WHERE op.state != 'init'
2239
+
2240
+ UNION ALL
2241
+
2242
+ SELECT
2243
+ 'operation' AS source,
2244
+ 'receive:' || id AS id,
2245
+ NULL AS legacyHistoryId,
2246
+ 'receive' AS type,
2247
+ mintUrl,
2248
+ COALESCE(unit, 'sat') AS unit,
2249
+ amount,
2250
+ createdAt * 1000 AS createdAt,
2251
+ updatedAt * 1000 AS updatedAt,
2252
+ state,
2253
+ NULL AS quoteId,
2254
+ NULL AS paymentRequest,
2255
+ NULL AS tokenJson,
2256
+ inputProofsJson,
2257
+ sourceJson AS metadata,
2258
+ id AS operationId,
2259
+ NULL AS remoteState,
2260
+ error
2261
+ FROM coco_cashu_receive_operations
2262
+ WHERE state IN ('finalized', 'rolled_back')
2263
+
2264
+ UNION ALL
2265
+
2266
+ SELECT
2267
+ 'legacy' AS source,
2268
+ 'legacy:' || h.id AS id,
2269
+ CAST(h.id AS TEXT) AS legacyHistoryId,
2270
+ h.type,
2271
+ h.mintUrl,
2272
+ h.unit,
2273
+ h.amount,
2274
+ h.createdAt,
2275
+ h.createdAt AS updatedAt,
2276
+ COALESCE(h.state, '') AS state,
2277
+ h.quoteId,
2278
+ h.paymentRequest,
2279
+ h.tokenJson,
2280
+ NULL AS inputProofsJson,
2281
+ h.metadata,
2282
+ h.operationId,
2283
+ NULL AS remoteState,
2284
+ NULL AS error
2285
+ FROM coco_cashu_history h
2286
+ WHERE NOT (
2287
+ h.operationId IS NOT NULL AND EXISTS (
2288
+ SELECT 1 FROM (
2289
+ SELECT 'send' AS type, id AS operationId
2290
+ FROM coco_cashu_send_operations
2291
+ WHERE state != 'init'
2292
+ UNION ALL
2293
+ SELECT 'melt' AS type, id AS operationId
2294
+ FROM coco_cashu_melt_operations
2295
+ WHERE state IN (
2296
+ 'prepared',
2297
+ 'executing',
2298
+ 'pending',
2299
+ 'finalized',
2300
+ 'rolling_back',
2301
+ 'rolled_back'
2302
+ )
2303
+ UNION ALL
2304
+ SELECT 'mint' AS type, id AS operationId
2305
+ FROM coco_cashu_mint_operations
2306
+ WHERE state != 'init'
2307
+ UNION ALL
2308
+ SELECT 'receive' AS type, id AS operationId
2309
+ FROM coco_cashu_receive_operations
2310
+ WHERE state IN ('finalized', 'rolled_back')
2311
+ ) op
2312
+ WHERE op.type = h.type AND op.operationId = h.operationId
2313
+ )
2314
+ )
2315
+ AND NOT (
2316
+ h.operationId IS NULL
2317
+ AND h.type IN ('mint', 'melt')
2318
+ AND h.quoteId IS NOT NULL
2319
+ AND EXISTS (
2320
+ SELECT 1
2321
+ FROM (
2322
+ SELECT 'mint' AS type, mintUrl, quoteId
2323
+ FROM coco_cashu_mint_operations
2324
+ WHERE state != 'init'
2325
+ UNION ALL
2326
+ SELECT 'melt' AS type, mintUrl, quoteId
2327
+ FROM coco_cashu_melt_operations
2328
+ WHERE state IN (
2329
+ 'prepared',
2330
+ 'executing',
2331
+ 'pending',
2332
+ 'finalized',
2333
+ 'rolling_back',
2334
+ 'rolled_back'
2335
+ )
2336
+ ) opq
2337
+ WHERE opq.type = h.type AND opq.mintUrl = h.mintUrl AND opq.quoteId = h.quoteId
2338
+ )
2339
+ )
2340
+ )
2341
+ `;
2342
+ function parseToken$1(tokenJson) {
2343
+ return tokenJson ? deserializeToken(JSON.parse(tokenJson)) : void 0;
2344
+ }
2345
+ function parseMetadata(metadata) {
2346
+ return metadata ? JSON.parse(metadata) : void 0;
2347
+ }
2348
+ function parseReceiveSourceMetadata(sourceJson) {
2349
+ if (!sourceJson) return void 0;
2350
+ const source = JSON.parse(sourceJson);
2351
+ if (source.type !== "payment-request" || typeof source.requestOperationId !== "string" || typeof source.attemptId !== "string" || typeof source.transport !== "string") return;
2352
+ return {
2353
+ source: "payment-request",
2354
+ requestOperationId: source.requestOperationId,
2355
+ attemptId: source.attemptId,
2356
+ ...typeof source.requestId === "string" ? { requestId: source.requestId } : {},
2357
+ transport: source.transport,
2358
+ ...typeof source.transportMessageId === "string" ? { transportMessageId: source.transportMessageId } : {},
2359
+ ...typeof source.senderPubkey === "string" ? { senderPubkey: source.senderPubkey } : {},
2360
+ ...typeof source.memo === "string" ? { memo: source.memo } : {}
2361
+ };
2362
+ }
2363
+ var SqliteHistoryRepository = class {
1297
2364
  db;
1298
2365
  constructor(db) {
1299
2366
  this.db = db;
1300
2367
  }
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
2368
  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
2369
+ return (await this.db.all(`${projectionSelect}
1336
2370
  ORDER BY createdAt DESC, id DESC
1337
- LIMIT ? OFFSET ?`, [limit, offset])).map((r) => this.rowToEntry(r));
2371
+ LIMIT ? OFFSET ?`, [limit, offset])).map(rowToEntry);
1338
2372
  }
1339
2373
  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;
2374
+ const parsed = parseHistoryEntryId(id);
2375
+ if (!parsed) return null;
2376
+ if (parsed.source === "legacy") {
2377
+ const row = await this.db.get(`${projectionSelect}
2378
+ WHERE source = 'legacy' AND legacyHistoryId = ?
2379
+ LIMIT 1`, [parsed.legacyHistoryId]);
2380
+ return row ? rowToEntry(row) : null;
1381
2381
  }
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]);
2382
+ const row = await this.db.get(`${projectionSelect}
2383
+ WHERE source = 'operation' AND type = ? AND operationId = ?
2384
+ LIMIT 1`, [parsed.type, parsed.operationId]);
2385
+ return row ? rowToEntry(row) : null;
1518
2386
  }
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 {
2387
+ };
2388
+ function rowToEntry(row) {
2389
+ if (row.source === "legacy") return projectLegacyHistoryRow(rowToLegacyInput(row));
2390
+ const base = {
2391
+ id: operationHistoryId(row.type, row.operationId ?? ""),
2392
+ source: "operation",
2393
+ type: row.type,
2394
+ createdAt: row.createdAt,
2395
+ updatedAt: row.updatedAt,
2396
+ mintUrl: row.mintUrl,
2397
+ unit: row.unit ?? "sat",
2398
+ operationId: row.operationId ?? "",
2399
+ amount: deserializeAmount(row.amount),
2400
+ state: row.state,
2401
+ ...row.error ? { error: row.error } : {}
2402
+ };
2403
+ switch (row.type) {
2404
+ case "mint": return {
1534
2405
  ...base,
1535
2406
  type: "mint",
1536
- paymentRequest: row.paymentRequest ?? "",
1537
2407
  quoteId: row.quoteId ?? "",
1538
- operationId: row.operationId ?? void 0,
1539
- state: row.state ?? "UNPAID",
1540
- amount: row.amount
2408
+ paymentRequest: row.paymentRequest ?? "",
2409
+ state: row.state,
2410
+ ...row.remoteState ? { remoteState: row.remoteState } : {}
1541
2411
  };
1542
- if (row.type === "melt") return {
2412
+ case "melt": return {
1543
2413
  ...base,
1544
2414
  type: "melt",
1545
2415
  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
2416
+ state: row.state
1566
2417
  };
2418
+ case "send": {
2419
+ const token = parseToken$1(row.tokenJson);
2420
+ return {
2421
+ ...base,
2422
+ type: "send",
2423
+ state: row.state,
2424
+ ...token ? { token } : {}
2425
+ };
2426
+ }
2427
+ case "receive": {
2428
+ const metadata = parseReceiveSourceMetadata(row.metadata);
2429
+ return {
2430
+ ...base,
2431
+ type: "receive",
2432
+ state: row.state,
2433
+ ...metadata ? { metadata } : {},
2434
+ ...row.state === "finalized" ? { token: {
2435
+ mint: row.mintUrl,
2436
+ proofs: parseTokenProofs(row.inputProofsJson),
2437
+ unit: row.unit ?? "sat"
2438
+ } } : {}
2439
+ };
2440
+ }
1567
2441
  }
1568
- };
2442
+ }
2443
+ function rowToLegacyInput(row) {
2444
+ return {
2445
+ legacyHistoryId: row.legacyHistoryId ?? row.id.slice(7),
2446
+ type: row.type,
2447
+ createdAt: row.createdAt,
2448
+ mintUrl: row.mintUrl,
2449
+ unit: row.unit ?? "sat",
2450
+ amount: deserializeAmount(row.amount),
2451
+ quoteId: row.quoteId,
2452
+ state: row.state || null,
2453
+ paymentRequest: row.paymentRequest,
2454
+ token: parseToken$1(row.tokenJson),
2455
+ metadata: parseMetadata(row.metadata),
2456
+ operationId: row.operationId
2457
+ };
2458
+ }
2459
+ function parseTokenProofs(inputProofsJson) {
2460
+ return (inputProofsJson ? JSON.parse(inputProofsJson) : []).map((proof) => ({
2461
+ ...proof,
2462
+ amount: deserializeAmount(proof.amount)
2463
+ }));
2464
+ }
1569
2465
 
1570
2466
  //#endregion
1571
- //#region src/repositories/SendOperationRepository.ts
2467
+ //#region ../sql-storage/src/repositories/SendOperationRepository.ts
1572
2468
  function parseToken(tokenJson) {
1573
- return tokenJson ? JSON.parse(tokenJson) : void 0;
2469
+ return tokenJson ? deserializeToken(JSON.parse(tokenJson)) : void 0;
1574
2470
  }
1575
2471
  function serializeToken(operation) {
1576
2472
  const maybeTokenOperation = operation;
1577
2473
  return maybeTokenOperation.token ? JSON.stringify(maybeTokenOperation.token) : null;
1578
2474
  }
1579
- function rowToOperation$3(row) {
2475
+ function rowToOperation$4(row) {
1580
2476
  const base = {
1581
2477
  id: row.id,
1582
2478
  mintUrl: row.mintUrl,
1583
- amount: row.amount,
2479
+ amount: deserializeAmount(row.amount),
2480
+ unit: normalizeUnit(row.unit ?? "sat"),
1584
2481
  createdAt: row.createdAt * 1e3,
1585
2482
  updatedAt: row.updatedAt * 1e3,
1586
2483
  error: row.error ?? void 0,
@@ -1593,8 +2490,8 @@ function rowToOperation$3(row) {
1593
2490
  };
1594
2491
  const preparedData = {
1595
2492
  needsSwap: row.needsSwap === 1,
1596
- fee: row.fee ?? 0,
1597
- inputAmount: row.inputAmount ?? 0,
2493
+ fee: deserializeAmount(row.fee ?? 0),
2494
+ inputAmount: deserializeAmount(row.inputAmount ?? 0),
1598
2495
  inputProofSecrets: row.inputProofSecretsJson ? JSON.parse(row.inputProofSecretsJson) : [],
1599
2496
  outputData: row.outputDataJson ? JSON.parse(row.outputDataJson) : void 0
1600
2497
  };
@@ -1642,13 +2539,14 @@ function operationToParams$3(op) {
1642
2539
  if (op.state === "init") return [
1643
2540
  op.id,
1644
2541
  op.mintUrl,
1645
- op.amount,
2542
+ serializeAmount(op.amount),
2543
+ op.unit,
1646
2544
  op.state,
1647
2545
  createdAtSeconds,
1648
2546
  updatedAtSeconds,
1649
2547
  op.error ?? null,
1650
2548
  op.method,
1651
- JSON.stringify(op.methodData),
2549
+ stringifyJson(op.methodData),
1652
2550
  null,
1653
2551
  null,
1654
2552
  null,
@@ -1659,22 +2557,23 @@ function operationToParams$3(op) {
1659
2557
  return [
1660
2558
  op.id,
1661
2559
  op.mintUrl,
1662
- op.amount,
2560
+ serializeAmount(op.amount),
2561
+ op.unit,
1663
2562
  op.state,
1664
2563
  createdAtSeconds,
1665
2564
  updatedAtSeconds,
1666
2565
  op.error ?? null,
1667
2566
  op.method,
1668
- JSON.stringify(op.methodData),
2567
+ stringifyJson(op.methodData),
1669
2568
  op.needsSwap ? 1 : 0,
1670
- op.fee,
1671
- op.inputAmount,
2569
+ serializeAmount(op.fee),
2570
+ serializeAmount(op.inputAmount),
1672
2571
  JSON.stringify(op.inputProofSecrets),
1673
2572
  op.outputData ? JSON.stringify(op.outputData) : null,
1674
2573
  serializeToken(op)
1675
2574
  ];
1676
2575
  }
1677
- var ExpoSendOperationRepository = class {
2576
+ var SqliteSendOperationRepository = class {
1678
2577
  db;
1679
2578
  constructor(db) {
1680
2579
  this.db = db;
@@ -1683,29 +2582,31 @@ var ExpoSendOperationRepository = class {
1683
2582
  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
2583
  const params = operationToParams$3(operation);
1685
2584
  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);
2585
+ (id, mintUrl, amount, unit, state, createdAt, updatedAt, error, method, methodDataJson, needsSwap, fee, inputAmount, inputProofSecretsJson, outputDataJson, tokenJson)
2586
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, params);
1688
2587
  }
1689
2588
  async update(operation) {
1690
2589
  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
2590
  const updatedAtSeconds = getUnixTimeSeconds();
1692
2591
  if (operation.state === "init") await this.db.run(`UPDATE coco_cashu_send_operations
1693
- SET state = ?, updatedAt = ?, error = ?
2592
+ SET state = ?, updatedAt = ?, error = ?, unit = ?
1694
2593
  WHERE id = ?`, [
1695
2594
  operation.state,
1696
2595
  updatedAtSeconds,
1697
2596
  operation.error ?? null,
2597
+ operation.unit,
1698
2598
  operation.id
1699
2599
  ]);
1700
2600
  else await this.db.run(`UPDATE coco_cashu_send_operations
1701
- SET state = ?, updatedAt = ?, error = ?, needsSwap = ?, fee = ?, inputAmount = ?, inputProofSecretsJson = ?, outputDataJson = ?, tokenJson = ?
2601
+ SET state = ?, updatedAt = ?, error = ?, unit = ?, needsSwap = ?, fee = ?, inputAmount = ?, inputProofSecretsJson = ?, outputDataJson = ?, tokenJson = ?
1702
2602
  WHERE id = ?`, [
1703
2603
  operation.state,
1704
2604
  updatedAtSeconds,
1705
2605
  operation.error ?? null,
2606
+ operation.unit,
1706
2607
  operation.needsSwap ? 1 : 0,
1707
- operation.fee,
1708
- operation.inputAmount,
2608
+ serializeAmount(operation.fee),
2609
+ serializeAmount(operation.inputAmount),
1709
2610
  JSON.stringify(operation.inputProofSecrets),
1710
2611
  operation.outputData ? JSON.stringify(operation.outputData) : null,
1711
2612
  serializeToken(operation),
@@ -1714,16 +2615,16 @@ var ExpoSendOperationRepository = class {
1714
2615
  }
1715
2616
  async getById(id) {
1716
2617
  const row = await this.db.get("SELECT * FROM coco_cashu_send_operations WHERE id = ?", [id]);
1717
- return row ? rowToOperation$3(row) : null;
2618
+ return row ? rowToOperation$4(row) : null;
1718
2619
  }
1719
2620
  async getByState(state) {
1720
- return (await this.db.all("SELECT * FROM coco_cashu_send_operations WHERE state = ?", [state])).map(rowToOperation$3);
2621
+ return (await this.db.all("SELECT * FROM coco_cashu_send_operations WHERE state = ?", [state])).map(rowToOperation$4);
1721
2622
  }
1722
2623
  async getPending() {
1723
- return (await this.db.all(`SELECT * FROM coco_cashu_send_operations WHERE state IN ('executing', 'pending', 'rolling_back')`)).map(rowToOperation$3);
2624
+ return (await this.db.all("SELECT * FROM coco_cashu_send_operations WHERE state IN ('executing', 'pending', 'rolling_back')")).map(rowToOperation$4);
1724
2625
  }
1725
2626
  async getByMintUrl(mintUrl) {
1726
- return (await this.db.all("SELECT * FROM coco_cashu_send_operations WHERE mintUrl = ?", [mintUrl])).map(rowToOperation$3);
2627
+ return (await this.db.all("SELECT * FROM coco_cashu_send_operations WHERE mintUrl = ?", [mintUrl])).map(rowToOperation$4);
1727
2628
  }
1728
2629
  async delete(id) {
1729
2630
  await this.db.run("DELETE FROM coco_cashu_send_operations WHERE id = ?", [id]);
@@ -1731,7 +2632,8 @@ var ExpoSendOperationRepository = class {
1731
2632
  };
1732
2633
 
1733
2634
  //#endregion
1734
- //#region src/repositories/MeltOperationRepository.ts
2635
+ //#region ../sql-storage/src/repositories/MeltOperationRepository.ts
2636
+ const getOperationQuoteId = (operation) => "quoteId" in operation && operation.quoteId ? operation.quoteId : void 0;
1735
2637
  const preparedStates = [
1736
2638
  "prepared",
1737
2639
  "executing",
@@ -1741,28 +2643,30 @@ const preparedStates = [
1741
2643
  "rolled_back"
1742
2644
  ];
1743
2645
  const isPreparedState = (state) => preparedStates.includes(state);
1744
- const rowToOperation$2 = (row) => {
2646
+ const parseMethodData = (row) => normalizeMeltMethodData(JSON.parse(row.methodDataJson));
2647
+ const rowToOperation$3 = (row) => {
1745
2648
  const base = {
1746
2649
  id: row.id,
1747
2650
  mintUrl: row.mintUrl,
1748
2651
  method: row.method,
1749
- methodData: JSON.parse(row.methodDataJson),
2652
+ methodData: parseMethodData(row),
2653
+ unit: normalizeUnit(row.unit ?? "sat"),
1750
2654
  createdAt: row.createdAt * 1e3,
1751
2655
  updatedAt: row.updatedAt * 1e3,
1752
2656
  error: row.error ?? void 0
1753
2657
  };
1754
2658
  if (!isPreparedState(row.state)) return {
1755
2659
  ...base,
1756
- state: "init"
2660
+ state: "init",
2661
+ ...row.quoteId ? { quoteId: row.quoteId } : {}
1757
2662
  };
1758
2663
  const preparedData = {
1759
2664
  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,
2665
+ amount: deserializeAmount(row.amount ?? 0),
2666
+ fee_reserve: deserializeAmount(row.fee_reserve ?? 0),
2667
+ swap_fee: deserializeAmount(row.swap_fee ?? 0),
1764
2668
  needsSwap: row.needsSwap === 1,
1765
- inputAmount: row.inputAmount ?? 0,
2669
+ inputAmount: deserializeAmount(row.inputAmount ?? 0),
1766
2670
  inputProofSecrets: row.inputProofSecretsJson ? JSON.parse(row.inputProofSecretsJson) : [],
1767
2671
  changeOutputData: row.changeOutputDataJson ? JSON.parse(row.changeOutputDataJson) : {
1768
2672
  keep: [],
@@ -1777,8 +2681,8 @@ const rowToOperation$2 = (row) => {
1777
2681
  };
1778
2682
  if (row.state === "finalized") return {
1779
2683
  ...operation,
1780
- changeAmount: row.changeAmount ?? void 0,
1781
- effectiveFee: row.effectiveFee ?? void 0,
2684
+ changeAmount: row.changeAmount !== null ? deserializeAmount(row.changeAmount) : void 0,
2685
+ effectiveFee: row.effectiveFee !== null ? deserializeAmount(row.effectiveFee) : void 0,
1782
2686
  finalizedData: row.finalizedDataJson ? JSON.parse(row.finalizedDataJson) : void 0
1783
2687
  };
1784
2688
  return operation;
@@ -1786,7 +2690,7 @@ const rowToOperation$2 = (row) => {
1786
2690
  const operationToParams$2 = (operation) => {
1787
2691
  const createdAtSeconds = Math.floor(operation.createdAt / 1e3);
1788
2692
  const updatedAtSeconds = Math.floor(operation.updatedAt / 1e3);
1789
- const methodDataJson = JSON.stringify(operation.methodData);
2693
+ const methodDataJson = stringifyJson(operation.methodData);
1790
2694
  if (operation.state === "init") return [
1791
2695
  operation.id,
1792
2696
  operation.mintUrl,
@@ -1796,8 +2700,8 @@ const operationToParams$2 = (operation) => {
1796
2700
  operation.error ?? null,
1797
2701
  operation.method,
1798
2702
  methodDataJson,
1799
- null,
1800
- null,
2703
+ operation.quoteId ?? null,
2704
+ operation.unit,
1801
2705
  null,
1802
2706
  null,
1803
2707
  null,
@@ -1811,8 +2715,8 @@ const operationToParams$2 = (operation) => {
1811
2715
  null
1812
2716
  ];
1813
2717
  const settlement = operation;
1814
- const changeAmount = operation.state === "finalized" ? settlement.changeAmount ?? null : null;
1815
- const effectiveFee = operation.state === "finalized" ? settlement.effectiveFee ?? null : null;
2718
+ const changeAmount = operation.state === "finalized" && settlement.changeAmount !== void 0 ? serializeAmount(settlement.changeAmount) : null;
2719
+ const effectiveFee = operation.state === "finalized" && settlement.effectiveFee !== void 0 ? serializeAmount(settlement.effectiveFee) : null;
1816
2720
  const finalizedDataJson = operation.state === "finalized" && settlement.finalizedData !== void 0 ? JSON.stringify(settlement.finalizedData) : null;
1817
2721
  return [
1818
2722
  operation.id,
@@ -1825,11 +2729,11 @@ const operationToParams$2 = (operation) => {
1825
2729
  methodDataJson,
1826
2730
  operation.quoteId,
1827
2731
  operation.unit,
1828
- operation.amount,
1829
- operation.fee_reserve,
1830
- operation.swap_fee,
2732
+ serializeAmount(operation.amount),
2733
+ serializeAmount(operation.fee_reserve),
2734
+ serializeAmount(operation.swap_fee),
1831
2735
  operation.needsSwap ? 1 : 0,
1832
- operation.inputAmount,
2736
+ serializeAmount(operation.inputAmount),
1833
2737
  JSON.stringify(operation.inputProofSecrets),
1834
2738
  JSON.stringify(operation.changeOutputData),
1835
2739
  operation.swapOutputData ? JSON.stringify(operation.swapOutputData) : null,
@@ -1838,7 +2742,7 @@ const operationToParams$2 = (operation) => {
1838
2742
  finalizedDataJson
1839
2743
  ];
1840
2744
  };
1841
- var ExpoMeltOperationRepository = class {
2745
+ var SqliteMeltOperationRepository = class {
1842
2746
  db;
1843
2747
  constructor(db) {
1844
2748
  this.db = db;
@@ -1846,6 +2750,7 @@ var ExpoMeltOperationRepository = class {
1846
2750
  async create(operation) {
1847
2751
  if (operation.state === "failed") throw new Error("Cannot persist failed melt operation");
1848
2752
  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`);
2753
+ await this.assertNoDuplicateQuoteOperation(operation);
1849
2754
  const params = operationToParams$2(operation);
1850
2755
  await this.db.run(`INSERT INTO coco_cashu_melt_operations
1851
2756
  (id, mintUrl, state, createdAt, updatedAt, error, method, methodDataJson, quoteId, unit, amount, fee_reserve, swap_fee, needsSwap, inputAmount, inputProofSecretsJson, changeOutputDataJson, swapOutputDataJson, changeAmount, effectiveFee, finalizedDataJson)
@@ -1854,16 +2759,19 @@ var ExpoMeltOperationRepository = class {
1854
2759
  async update(operation) {
1855
2760
  if (operation.state === "failed") throw new Error("Cannot persist failed melt operation");
1856
2761
  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`);
2762
+ await this.assertNoDuplicateQuoteOperation(operation);
1857
2763
  const updatedAtSeconds = getUnixTimeSeconds();
1858
2764
  if (operation.state === "init") {
1859
2765
  await this.db.run(`UPDATE coco_cashu_melt_operations
1860
- SET state = ?, updatedAt = ?, error = ?, method = ?, methodDataJson = ?
2766
+ SET state = ?, updatedAt = ?, error = ?, method = ?, methodDataJson = ?, quoteId = ?, unit = ?
1861
2767
  WHERE id = ?`, [
1862
2768
  operation.state,
1863
2769
  updatedAtSeconds,
1864
2770
  operation.error ?? null,
1865
2771
  operation.method,
1866
- JSON.stringify(operation.methodData),
2772
+ stringifyJson(operation.methodData),
2773
+ operation.quoteId ?? null,
2774
+ operation.unit,
1867
2775
  operation.id
1868
2776
  ]);
1869
2777
  return;
@@ -1876,46 +2784,62 @@ var ExpoMeltOperationRepository = class {
1876
2784
  updatedAtSeconds,
1877
2785
  operation.error ?? null,
1878
2786
  operation.method,
1879
- JSON.stringify(operation.methodData),
2787
+ stringifyJson(operation.methodData),
1880
2788
  operation.quoteId,
1881
2789
  operation.unit,
1882
- operation.amount,
1883
- operation.fee_reserve,
1884
- operation.swap_fee,
2790
+ serializeAmount(operation.amount),
2791
+ serializeAmount(operation.fee_reserve),
2792
+ serializeAmount(operation.swap_fee),
1885
2793
  operation.needsSwap ? 1 : 0,
1886
- operation.inputAmount,
2794
+ serializeAmount(operation.inputAmount),
1887
2795
  JSON.stringify(operation.inputProofSecrets),
1888
2796
  JSON.stringify(operation.changeOutputData),
1889
2797
  operation.swapOutputData ? JSON.stringify(operation.swapOutputData) : null,
1890
- operation.state === "finalized" ? settlement.changeAmount ?? null : null,
1891
- operation.state === "finalized" ? settlement.effectiveFee ?? null : null,
2798
+ operation.state === "finalized" && settlement.changeAmount !== void 0 ? serializeAmount(settlement.changeAmount) : null,
2799
+ operation.state === "finalized" && settlement.effectiveFee !== void 0 ? serializeAmount(settlement.effectiveFee) : null,
1892
2800
  operation.state === "finalized" && settlement.finalizedData !== void 0 ? JSON.stringify(settlement.finalizedData) : null,
1893
2801
  operation.id
1894
2802
  ]);
1895
2803
  }
1896
2804
  async getById(id) {
1897
2805
  const row = await this.db.get("SELECT * FROM coco_cashu_melt_operations WHERE id = ?", [id]);
1898
- return row ? rowToOperation$2(row) : null;
2806
+ return row ? rowToOperation$3(row) : null;
1899
2807
  }
1900
2808
  async getByState(state) {
1901
- return (await this.db.all("SELECT * FROM coco_cashu_melt_operations WHERE state = ?", [state])).map(rowToOperation$2);
2809
+ return (await this.db.all("SELECT * FROM coco_cashu_melt_operations WHERE state = ?", [state])).map(rowToOperation$3);
1902
2810
  }
1903
2811
  async getPending() {
1904
- return (await this.db.all("SELECT * FROM coco_cashu_melt_operations WHERE state IN (\"executing\", \"pending\")")).map(rowToOperation$2);
2812
+ return (await this.db.all("SELECT * FROM coco_cashu_melt_operations WHERE state IN ('executing', 'pending')")).map(rowToOperation$3);
1905
2813
  }
1906
2814
  async getByMintUrl(mintUrl) {
1907
- return (await this.db.all("SELECT * FROM coco_cashu_melt_operations WHERE mintUrl = ?", [mintUrl])).map(rowToOperation$2);
2815
+ return (await this.db.all("SELECT * FROM coco_cashu_melt_operations WHERE mintUrl = ?", [mintUrl])).map(rowToOperation$3);
1908
2816
  }
1909
2817
  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);
2818
+ return (await this.db.all("SELECT * FROM coco_cashu_melt_operations WHERE mintUrl = ? AND quoteId = ?", [mintUrl, quoteId])).map(rowToOperation$3);
1911
2819
  }
1912
2820
  async delete(id) {
1913
2821
  await this.db.run("DELETE FROM coco_cashu_melt_operations WHERE id = ?", [id]);
1914
2822
  }
2823
+ async assertNoDuplicateQuoteOperation(operation) {
2824
+ const quoteId = getOperationQuoteId(operation);
2825
+ if (!quoteId) return;
2826
+ if (await this.db.get("SELECT id FROM coco_cashu_melt_operations WHERE mintUrl = ? AND quoteId = ? AND id <> ? LIMIT 1", [
2827
+ operation.mintUrl,
2828
+ quoteId,
2829
+ operation.id
2830
+ ])) throw new Error(`MeltOperation already exists for mint ${operation.mintUrl} and quote ${quoteId}`);
2831
+ }
1915
2832
  };
1916
2833
 
1917
2834
  //#endregion
1918
- //#region src/repositories/AuthSessionRepository.ts
2835
+ //#region ../sql-storage/src/repositories/AuthSessionRepository.ts
2836
+ function parseBatPool(batPoolJson) {
2837
+ if (!batPoolJson) return void 0;
2838
+ return JSON.parse(batPoolJson)?.map((proof) => ({
2839
+ ...proof,
2840
+ amount: deserializeAmount(proof.amount)
2841
+ }));
2842
+ }
1919
2843
  function rowToSession(row) {
1920
2844
  return {
1921
2845
  mintUrl: row.mintUrl,
@@ -1923,10 +2847,10 @@ function rowToSession(row) {
1923
2847
  refreshToken: row.refreshToken ?? void 0,
1924
2848
  expiresAt: row.expiresAt,
1925
2849
  scope: row.scope ?? void 0,
1926
- batPool: row.batPoolJson ? JSON.parse(row.batPoolJson) : void 0
2850
+ batPool: parseBatPool(row.batPoolJson)
1927
2851
  };
1928
2852
  }
1929
- var ExpoAuthSessionRepository = class {
2853
+ var SqliteAuthSessionRepository = class {
1930
2854
  db;
1931
2855
  constructor(db) {
1932
2856
  this.db = db;
@@ -1962,7 +2886,7 @@ var ExpoAuthSessionRepository = class {
1962
2886
  };
1963
2887
 
1964
2888
  //#endregion
1965
- //#region src/repositories/MintOperationRepository.ts
2889
+ //#region ../sql-storage/src/repositories/MintOperationRepository.ts
1966
2890
  const persistedStates = [
1967
2891
  "pending",
1968
2892
  "executing",
@@ -1974,7 +2898,12 @@ const normalizeState = (state) => {
1974
2898
  if (state === "pending" || state === "executing" || state === "finalized" || state === "failed") return state;
1975
2899
  return "init";
1976
2900
  };
1977
- const rowToOperation$1 = (row) => {
2901
+ const requireQuoteId = (row) => {
2902
+ if (!row.quoteId || row.quoteId.trim() === "") throw new Error(`MintOperation ${row.id} is missing required quoteId`);
2903
+ return row.quoteId;
2904
+ };
2905
+ const rowToOperation$2 = (row) => {
2906
+ const quoteId = requireQuoteId(row);
1978
2907
  const base = {
1979
2908
  id: row.id,
1980
2909
  mintUrl: row.mintUrl,
@@ -1986,25 +2915,23 @@ const rowToOperation$1 = (row) => {
1986
2915
  ...row.terminalFailureJson ? { terminalFailure: JSON.parse(row.terminalFailureJson) } : {}
1987
2916
  };
1988
2917
  const intent = {
1989
- amount: row.amount ?? 0,
2918
+ amount: deserializeAmount(row.amount ?? 0),
1990
2919
  unit: row.unit ?? ""
1991
2920
  };
1992
2921
  if (!isPersistedState(row.state)) return {
1993
2922
  ...base,
1994
2923
  ...intent,
1995
2924
  state: "init",
1996
- ...row.quoteId ? { quoteId: row.quoteId } : {}
2925
+ quoteId
1997
2926
  };
1998
2927
  return {
1999
2928
  ...base,
2000
2929
  ...intent,
2001
2930
  state: normalizeState(row.state),
2002
- quoteId: row.quoteId ?? "",
2931
+ quoteId,
2003
2932
  request: row.request ?? "",
2004
- expiry: row.expiry ?? 0,
2933
+ expiry: row.expiry ?? null,
2005
2934
  pubkey: row.pubkey ?? void 0,
2006
- lastObservedRemoteState: row.lastObservedRemoteState ?? void 0,
2007
- lastObservedRemoteStateAt: row.lastObservedRemoteStateAt ?? void 0,
2008
2935
  outputData: row.outputDataJson ? JSON.parse(row.outputDataJson) : {
2009
2936
  keep: [],
2010
2937
  send: []
@@ -2014,18 +2941,18 @@ const rowToOperation$1 = (row) => {
2014
2941
  const operationToParams$1 = (operation) => {
2015
2942
  const createdAtSeconds = Math.floor(operation.createdAt / 1e3);
2016
2943
  const updatedAtSeconds = Math.floor(operation.updatedAt / 1e3);
2017
- const methodDataJson = JSON.stringify(operation.methodData);
2944
+ const methodDataJson = stringifyJson(operation.methodData);
2018
2945
  if (operation.state === "init") return [
2019
2946
  operation.id,
2020
2947
  operation.mintUrl,
2021
- operation.quoteId ?? null,
2948
+ operation.quoteId,
2022
2949
  operation.state,
2023
2950
  createdAtSeconds,
2024
2951
  updatedAtSeconds,
2025
2952
  operation.error ?? null,
2026
2953
  operation.method,
2027
2954
  methodDataJson,
2028
- operation.amount,
2955
+ serializeAmount(operation.amount),
2029
2956
  operation.unit,
2030
2957
  null,
2031
2958
  null,
@@ -2045,18 +2972,18 @@ const operationToParams$1 = (operation) => {
2045
2972
  operation.error ?? null,
2046
2973
  operation.method,
2047
2974
  methodDataJson,
2048
- operation.amount,
2975
+ serializeAmount(operation.amount),
2049
2976
  operation.unit,
2050
2977
  operation.request,
2051
2978
  operation.expiry,
2052
2979
  operation.pubkey ?? null,
2053
- operation.lastObservedRemoteState ?? null,
2054
- operation.lastObservedRemoteStateAt ?? null,
2980
+ null,
2981
+ null,
2055
2982
  operation.terminalFailure ? JSON.stringify(operation.terminalFailure) : null,
2056
2983
  JSON.stringify(operation.outputData)
2057
2984
  ];
2058
2985
  };
2059
- var ExpoMintOperationRepository = class {
2986
+ var SqliteMintOperationRepository = class {
2060
2987
  db;
2061
2988
  constructor(db) {
2062
2989
  this.db = db;
@@ -2075,13 +3002,13 @@ var ExpoMintOperationRepository = class {
2075
3002
  await this.db.run(`UPDATE coco_cashu_mint_operations
2076
3003
  SET quoteId = ?, state = ?, updatedAt = ?, error = ?, method = ?, methodDataJson = ?, amount = ?, unit = ?, terminalFailureJson = ?
2077
3004
  WHERE id = ?`, [
2078
- operation.quoteId ?? null,
3005
+ operation.quoteId,
2079
3006
  operation.state,
2080
3007
  updatedAtSeconds,
2081
3008
  operation.error ?? null,
2082
3009
  operation.method,
2083
- JSON.stringify(operation.methodData),
2084
- operation.amount,
3010
+ stringifyJson(operation.methodData),
3011
+ serializeAmount(operation.amount),
2085
3012
  operation.unit,
2086
3013
  operation.terminalFailure ? JSON.stringify(operation.terminalFailure) : null,
2087
3014
  operation.id
@@ -2096,14 +3023,14 @@ var ExpoMintOperationRepository = class {
2096
3023
  updatedAtSeconds,
2097
3024
  operation.error ?? null,
2098
3025
  operation.method,
2099
- JSON.stringify(operation.methodData),
2100
- operation.amount,
3026
+ stringifyJson(operation.methodData),
3027
+ serializeAmount(operation.amount),
2101
3028
  operation.unit,
2102
3029
  operation.request,
2103
3030
  operation.expiry,
2104
3031
  operation.pubkey ?? null,
2105
- operation.lastObservedRemoteState ?? null,
2106
- operation.lastObservedRemoteStateAt ?? null,
3032
+ null,
3033
+ null,
2107
3034
  operation.terminalFailure ? JSON.stringify(operation.terminalFailure) : null,
2108
3035
  JSON.stringify(operation.outputData),
2109
3036
  operation.id
@@ -2111,19 +3038,25 @@ var ExpoMintOperationRepository = class {
2111
3038
  }
2112
3039
  async getById(id) {
2113
3040
  const row = await this.db.get("SELECT * FROM coco_cashu_mint_operations WHERE id = ?", [id]);
2114
- return row ? rowToOperation$1(row) : null;
3041
+ return row ? rowToOperation$2(row) : null;
2115
3042
  }
2116
3043
  async getByState(state) {
2117
- return (await this.db.all("SELECT * FROM coco_cashu_mint_operations WHERE state = ?", [state])).map(rowToOperation$1);
3044
+ return (await this.db.all("SELECT * FROM coco_cashu_mint_operations WHERE state = ?", [state])).map(rowToOperation$2);
2118
3045
  }
2119
3046
  async getPending() {
2120
- return (await this.db.all("SELECT * FROM coco_cashu_mint_operations WHERE state IN (\"pending\", \"executing\")")).map(rowToOperation$1);
3047
+ return (await this.db.all("SELECT * FROM coco_cashu_mint_operations WHERE state IN ('pending', 'executing')")).map(rowToOperation$2);
2121
3048
  }
2122
3049
  async getByMintUrl(mintUrl) {
2123
- return (await this.db.all("SELECT * FROM coco_cashu_mint_operations WHERE mintUrl = ?", [mintUrl])).map(rowToOperation$1);
3050
+ return (await this.db.all("SELECT * FROM coco_cashu_mint_operations WHERE mintUrl = ?", [mintUrl])).map(rowToOperation$2);
2124
3051
  }
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);
3052
+ async getByQuoteId(mintUrl, method, quoteId) {
3053
+ return (await this.db.all(`SELECT * FROM coco_cashu_mint_operations
3054
+ WHERE mintUrl = ? AND method = ? AND quoteId = ?
3055
+ ORDER BY createdAt ASC, id ASC`, [
3056
+ mintUrl,
3057
+ method,
3058
+ quoteId
3059
+ ])).map(rowToOperation$2);
2127
3060
  }
2128
3061
  async delete(id) {
2129
3062
  await this.db.run("DELETE FROM coco_cashu_mint_operations WHERE id = ?", [id]);
@@ -2131,27 +3064,34 @@ var ExpoMintOperationRepository = class {
2131
3064
  };
2132
3065
 
2133
3066
  //#endregion
2134
- //#region src/repositories/ReceiveOperationRepository.ts
3067
+ //#region ../sql-storage/src/repositories/ReceiveOperationRepository.ts
2135
3068
  function getOperationUnit(op) {
2136
3069
  return op.unit ?? "sat";
2137
3070
  }
2138
- function rowToOperation(row) {
3071
+ function parseInputProofs(inputProofsJson) {
3072
+ return (inputProofsJson ? JSON.parse(inputProofsJson) : []).map((proof) => ({
3073
+ ...proof,
3074
+ amount: deserializeAmount(proof.amount)
3075
+ }));
3076
+ }
3077
+ function rowToOperation$1(row) {
2139
3078
  const base = {
2140
3079
  id: row.id,
2141
3080
  mintUrl: row.mintUrl,
2142
3081
  unit: row.unit ?? "sat",
2143
- amount: row.amount,
2144
- inputProofs: row.inputProofsJson ? JSON.parse(row.inputProofsJson) : [],
3082
+ amount: deserializeAmount(row.amount),
3083
+ inputProofs: parseInputProofs(row.inputProofsJson),
2145
3084
  createdAt: row.createdAt * 1e3,
2146
3085
  updatedAt: row.updatedAt * 1e3,
2147
- error: row.error ?? void 0
3086
+ error: row.error ?? void 0,
3087
+ source: row.sourceJson ? JSON.parse(row.sourceJson) : void 0
2148
3088
  };
2149
3089
  if (row.state === "init") return {
2150
3090
  ...base,
2151
3091
  state: "init"
2152
3092
  };
2153
3093
  const preparedData = {
2154
- fee: row.fee ?? 0,
3094
+ fee: deserializeAmount(row.fee ?? 0),
2155
3095
  outputData: row.outputDataJson ? JSON.parse(row.outputDataJson) : void 0
2156
3096
  };
2157
3097
  switch (row.state) {
@@ -2185,30 +3125,32 @@ function operationToParams(op) {
2185
3125
  op.id,
2186
3126
  op.mintUrl,
2187
3127
  getOperationUnit(op),
2188
- op.amount,
3128
+ serializeAmount(op.amount),
2189
3129
  op.state,
2190
3130
  createdAtSeconds,
2191
3131
  updatedAtSeconds,
2192
3132
  op.error ?? null,
2193
3133
  null,
2194
3134
  JSON.stringify(op.inputProofs),
2195
- null
3135
+ null,
3136
+ op.source ? JSON.stringify(op.source) : null
2196
3137
  ];
2197
3138
  return [
2198
3139
  op.id,
2199
3140
  op.mintUrl,
2200
3141
  getOperationUnit(op),
2201
- op.amount,
3142
+ serializeAmount(op.amount),
2202
3143
  op.state,
2203
3144
  createdAtSeconds,
2204
3145
  updatedAtSeconds,
2205
3146
  op.error ?? null,
2206
- op.fee,
3147
+ serializeAmount(op.fee),
2207
3148
  JSON.stringify(op.inputProofs),
2208
- op.outputData ? JSON.stringify(op.outputData) : null
3149
+ op.outputData ? JSON.stringify(op.outputData) : null,
3150
+ op.source ? JSON.stringify(op.source) : null
2209
3151
  ];
2210
3152
  }
2211
- var ExpoReceiveOperationRepository = class {
3153
+ var SqliteReceiveOperationRepository = class {
2212
3154
  db;
2213
3155
  constructor(db) {
2214
3156
  this.db = db;
@@ -2217,47 +3159,52 @@ var ExpoReceiveOperationRepository = class {
2217
3159
  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
3160
  const params = operationToParams(operation);
2219
3161
  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);
3162
+ (id, mintUrl, unit, amount, state, createdAt, updatedAt, error, fee, inputProofsJson, outputDataJson, sourceJson)
3163
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, params);
2222
3164
  }
2223
3165
  async update(operation) {
2224
3166
  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
3167
  const updatedAtSeconds = getUnixTimeSeconds();
2226
3168
  if (operation.state === "init") await this.db.run(`UPDATE coco_cashu_receive_operations
2227
- SET state = ?, updatedAt = ?, error = ?, unit = ?, inputProofsJson = ?
3169
+ SET state = ?, updatedAt = ?, error = ?, unit = ?, inputProofsJson = ?, sourceJson = ?
2228
3170
  WHERE id = ?`, [
2229
3171
  operation.state,
2230
3172
  updatedAtSeconds,
2231
3173
  operation.error ?? null,
2232
3174
  getOperationUnit(operation),
2233
3175
  JSON.stringify(operation.inputProofs),
3176
+ operation.source ? JSON.stringify(operation.source) : null,
2234
3177
  operation.id
2235
3178
  ]);
2236
3179
  else await this.db.run(`UPDATE coco_cashu_receive_operations
2237
- SET state = ?, updatedAt = ?, error = ?, unit = ?, fee = ?, inputProofsJson = ?, outputDataJson = ?
3180
+ SET state = ?, updatedAt = ?, error = ?, unit = ?, fee = ?, inputProofsJson = ?, outputDataJson = ?, sourceJson = ?
2238
3181
  WHERE id = ?`, [
2239
3182
  operation.state,
2240
3183
  updatedAtSeconds,
2241
3184
  operation.error ?? null,
2242
3185
  getOperationUnit(operation),
2243
- operation.fee,
3186
+ serializeAmount(operation.fee),
2244
3187
  JSON.stringify(operation.inputProofs),
2245
3188
  operation.outputData ? JSON.stringify(operation.outputData) : null,
3189
+ operation.source ? JSON.stringify(operation.source) : null,
2246
3190
  operation.id
2247
3191
  ]);
2248
3192
  }
2249
3193
  async getById(id) {
2250
3194
  const row = await this.db.get("SELECT * FROM coco_cashu_receive_operations WHERE id = ?", [id]);
2251
- return row ? rowToOperation(row) : null;
3195
+ return row ? rowToOperation$1(row) : null;
2252
3196
  }
2253
3197
  async getByState(state) {
2254
- return (await this.db.all("SELECT * FROM coco_cashu_receive_operations WHERE state = ?", [state])).map(rowToOperation);
3198
+ return (await this.db.all("SELECT * FROM coco_cashu_receive_operations WHERE state = ?", [state])).map(rowToOperation$1);
2255
3199
  }
2256
3200
  async getPending() {
2257
- return (await this.db.all("SELECT * FROM coco_cashu_receive_operations WHERE state IN ('executing')")).map(rowToOperation);
3201
+ return (await this.db.all("SELECT * FROM coco_cashu_receive_operations WHERE state IN ('executing')")).map(rowToOperation$1);
2258
3202
  }
2259
3203
  async getByMintUrl(mintUrl) {
2260
- return (await this.db.all("SELECT * FROM coco_cashu_receive_operations WHERE mintUrl = ?", [mintUrl])).map(rowToOperation);
3204
+ return (await this.db.all("SELECT * FROM coco_cashu_receive_operations WHERE mintUrl = ?", [mintUrl])).map(rowToOperation$1);
3205
+ }
3206
+ async getByPaymentRequestAttemptId(attemptId) {
3207
+ return (await this.db.all("SELECT * FROM coco_cashu_receive_operations WHERE sourceJson IS NOT NULL")).map(rowToOperation$1).find((candidate) => candidate.source?.type === "payment-request" && candidate.source.attemptId === attemptId) ?? null;
2261
3208
  }
2262
3209
  async delete(id) {
2263
3210
  await this.db.run("DELETE FROM coco_cashu_receive_operations WHERE id = ?", [id]);
@@ -2265,61 +3212,478 @@ var ExpoReceiveOperationRepository = class {
2265
3212
  };
2266
3213
 
2267
3214
  //#endregion
2268
- //#region src/index.ts
2269
- var ExpoSqliteRepositories = class {
3215
+ //#region ../sql-storage/src/repositories/PaymentRequestReceiveRepository.ts
3216
+ function operationToRow(operation) {
3217
+ return {
3218
+ id: operation.id,
3219
+ requestId: operation.requestId ?? null,
3220
+ encodedRequest: operation.encodedRequest,
3221
+ state: operation.state,
3222
+ transport: operation.transport,
3223
+ amount: serializeAmount(operation.amount),
3224
+ unit: operation.unit,
3225
+ mintsJson: JSON.stringify(operation.mints),
3226
+ singleUse: operation.singleUse ? 1 : 0,
3227
+ description: operation.description ?? null,
3228
+ createdAt: Math.floor(operation.createdAt / 1e3),
3229
+ updatedAt: Math.floor(operation.updatedAt / 1e3),
3230
+ error: operation.error ?? null,
3231
+ completedAt: operation.completedAt ? Math.floor(operation.completedAt / 1e3) : null
3232
+ };
3233
+ }
3234
+ function rowToOperation(row) {
3235
+ return {
3236
+ id: row.id,
3237
+ requestId: row.requestId ?? void 0,
3238
+ encodedRequest: row.encodedRequest,
3239
+ state: row.state,
3240
+ transport: row.transport,
3241
+ amount: deserializeAmount(row.amount),
3242
+ unit: row.unit,
3243
+ mints: JSON.parse(row.mintsJson),
3244
+ singleUse: row.singleUse === 1,
3245
+ description: row.description ?? void 0,
3246
+ createdAt: row.createdAt * 1e3,
3247
+ updatedAt: row.updatedAt * 1e3,
3248
+ error: row.error ?? void 0,
3249
+ completedAt: row.completedAt ? row.completedAt * 1e3 : void 0
3250
+ };
3251
+ }
3252
+ function attemptToRow(attempt) {
3253
+ return {
3254
+ id: attempt.id,
3255
+ requestOperationId: attempt.requestOperationId,
3256
+ requestId: attempt.requestId ?? null,
3257
+ transport: attempt.transport,
3258
+ transportMessageId: attempt.transportMessageId ?? null,
3259
+ payloadHash: attempt.payloadHash,
3260
+ senderPubkey: attempt.senderPubkey ?? null,
3261
+ memo: attempt.memo ?? null,
3262
+ mintUrl: attempt.mintUrl,
3263
+ unit: attempt.unit,
3264
+ grossAmount: serializeAmount(attempt.grossAmount),
3265
+ fee: attempt.fee ? serializeAmount(attempt.fee) : null,
3266
+ netAmount: attempt.netAmount ? serializeAmount(attempt.netAmount) : null,
3267
+ receiveOperationId: attempt.receiveOperationId ?? null,
3268
+ state: attempt.state,
3269
+ error: attempt.error ?? null,
3270
+ payloadJson: attempt.payload ? JSON.stringify(attempt.payload) : null,
3271
+ createdAt: Math.floor(attempt.createdAt / 1e3),
3272
+ updatedAt: Math.floor(attempt.updatedAt / 1e3)
3273
+ };
3274
+ }
3275
+ function rowToAttempt(row) {
3276
+ const payload = row.payloadJson ? JSON.parse(row.payloadJson) : void 0;
3277
+ return {
3278
+ id: row.id,
3279
+ requestOperationId: row.requestOperationId,
3280
+ requestId: row.requestId ?? void 0,
3281
+ transport: row.transport,
3282
+ transportMessageId: row.transportMessageId ?? void 0,
3283
+ payloadHash: row.payloadHash,
3284
+ senderPubkey: row.senderPubkey ?? void 0,
3285
+ memo: row.memo ?? void 0,
3286
+ mintUrl: row.mintUrl,
3287
+ unit: row.unit,
3288
+ grossAmount: deserializeAmount(row.grossAmount),
3289
+ fee: row.fee === null ? void 0 : deserializeAmount(row.fee),
3290
+ netAmount: row.netAmount === null ? void 0 : deserializeAmount(row.netAmount),
3291
+ receiveOperationId: row.receiveOperationId ?? void 0,
3292
+ state: row.state,
3293
+ error: row.error ?? void 0,
3294
+ payload,
3295
+ createdAt: row.createdAt * 1e3,
3296
+ updatedAt: row.updatedAt * 1e3
3297
+ };
3298
+ }
3299
+ var SqlitePaymentRequestReceiveOperationRepository = class {
3300
+ constructor(db) {
3301
+ this.db = db;
3302
+ }
3303
+ async create(operation) {
3304
+ const row = operationToRow(operation);
3305
+ await this.db.run(`INSERT INTO coco_cashu_payment_request_receive_operations
3306
+ (id, requestId, encodedRequest, state, transport, amount, unit, mintsJson, singleUse, description, createdAt, updatedAt, error, completedAt)
3307
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, Object.values(row));
3308
+ }
3309
+ async update(operation) {
3310
+ const row = operationToRow({
3311
+ ...operation,
3312
+ updatedAt: Date.now()
3313
+ });
3314
+ await this.db.run(`UPDATE coco_cashu_payment_request_receive_operations
3315
+ SET requestId = ?, encodedRequest = ?, state = ?, transport = ?, amount = ?, unit = ?,
3316
+ mintsJson = ?, singleUse = ?, description = ?, updatedAt = ?, error = ?, completedAt = ?
3317
+ WHERE id = ?`, [
3318
+ row.requestId,
3319
+ row.encodedRequest,
3320
+ row.state,
3321
+ row.transport,
3322
+ row.amount,
3323
+ row.unit,
3324
+ row.mintsJson,
3325
+ row.singleUse,
3326
+ row.description,
3327
+ getUnixTimeSeconds(),
3328
+ row.error,
3329
+ row.completedAt,
3330
+ row.id
3331
+ ]);
3332
+ }
3333
+ async getById(id) {
3334
+ const row = await this.db.get("SELECT * FROM coco_cashu_payment_request_receive_operations WHERE id = ?", [id]);
3335
+ return row ? rowToOperation(row) : null;
3336
+ }
3337
+ async getByState(state) {
3338
+ return (await this.db.all("SELECT * FROM coco_cashu_payment_request_receive_operations WHERE state = ?", [state])).map(rowToOperation);
3339
+ }
3340
+ async getActiveByRequestId(requestId) {
3341
+ return (await this.db.all("SELECT * FROM coco_cashu_payment_request_receive_operations WHERE state = 'active' AND requestId = ?", [requestId])).map(rowToOperation);
3342
+ }
3343
+ async list(filter) {
3344
+ return (filter?.state ? await this.db.all("SELECT * FROM coco_cashu_payment_request_receive_operations WHERE state = ?", [filter.state]) : await this.db.all("SELECT * FROM coco_cashu_payment_request_receive_operations")).map(rowToOperation);
3345
+ }
3346
+ };
3347
+ var SqlitePaymentRequestReceiveAttemptRepository = class {
3348
+ constructor(db) {
3349
+ this.db = db;
3350
+ }
3351
+ async create(attempt) {
3352
+ const row = attemptToRow(attempt);
3353
+ await this.db.run(`INSERT INTO coco_cashu_payment_request_receive_attempts
3354
+ (id, requestOperationId, requestId, transport, transportMessageId, payloadHash, senderPubkey,
3355
+ memo, mintUrl, unit, grossAmount, fee, netAmount, receiveOperationId, state, error,
3356
+ payloadJson, createdAt, updatedAt)
3357
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, Object.values(row));
3358
+ }
3359
+ async update(attempt) {
3360
+ const row = attemptToRow({
3361
+ ...attempt,
3362
+ updatedAt: Date.now()
3363
+ });
3364
+ await this.db.run(`UPDATE coco_cashu_payment_request_receive_attempts
3365
+ SET requestId = ?, transport = ?, transportMessageId = ?, payloadHash = ?, senderPubkey = ?,
3366
+ memo = ?, mintUrl = ?, unit = ?, grossAmount = ?, fee = ?, netAmount = ?,
3367
+ receiveOperationId = ?, state = ?, error = ?, payloadJson = ?, updatedAt = ?
3368
+ WHERE id = ?`, [
3369
+ row.requestId,
3370
+ row.transport,
3371
+ row.transportMessageId,
3372
+ row.payloadHash,
3373
+ row.senderPubkey,
3374
+ row.memo,
3375
+ row.mintUrl,
3376
+ row.unit,
3377
+ row.grossAmount,
3378
+ row.fee,
3379
+ row.netAmount,
3380
+ row.receiveOperationId,
3381
+ row.state,
3382
+ row.error,
3383
+ row.payloadJson,
3384
+ getUnixTimeSeconds(),
3385
+ row.id
3386
+ ]);
3387
+ }
3388
+ async getById(id) {
3389
+ const row = await this.db.get("SELECT * FROM coco_cashu_payment_request_receive_attempts WHERE id = ?", [id]);
3390
+ return row ? rowToAttempt(row) : null;
3391
+ }
3392
+ async getByRequestOperationId(requestOperationId) {
3393
+ return (await this.db.all("SELECT * FROM coco_cashu_payment_request_receive_attempts WHERE requestOperationId = ?", [requestOperationId])).map(rowToAttempt);
3394
+ }
3395
+ async getByReceiveOperationId(receiveOperationId) {
3396
+ const row = await this.db.get("SELECT * FROM coco_cashu_payment_request_receive_attempts WHERE receiveOperationId = ?", [receiveOperationId]);
3397
+ return row ? rowToAttempt(row) : null;
3398
+ }
3399
+ async getByTransportMessageId(transportMessageId) {
3400
+ const row = await this.db.get("SELECT * FROM coco_cashu_payment_request_receive_attempts WHERE transportMessageId = ?", [transportMessageId]);
3401
+ return row ? rowToAttempt(row) : null;
3402
+ }
3403
+ async getByPayloadHash(requestOperationId, payloadHash) {
3404
+ const row = await this.db.get("SELECT * FROM coco_cashu_payment_request_receive_attempts WHERE requestOperationId = ? AND payloadHash = ?", [requestOperationId, payloadHash]);
3405
+ return row ? rowToAttempt(row) : null;
3406
+ }
3407
+ async getByRequestIdAndPayloadHash(requestId, payloadHash) {
3408
+ const row = await this.db.get(`SELECT * FROM coco_cashu_payment_request_receive_attempts
3409
+ WHERE requestId = ? AND payloadHash = ?
3410
+ ORDER BY CASE WHEN state = 'finalized' THEN 0 ELSE 1 END, createdAt ASC
3411
+ LIMIT 1`, [requestId, payloadHash]);
3412
+ return row ? rowToAttempt(row) : null;
3413
+ }
3414
+ async getByState(state) {
3415
+ return (await this.db.all("SELECT * FROM coco_cashu_payment_request_receive_attempts WHERE state = ?", [state])).map(rowToAttempt);
3416
+ }
3417
+ async delete(id) {
3418
+ await this.db.run("DELETE FROM coco_cashu_payment_request_receive_attempts WHERE id = ?", [id]);
3419
+ }
3420
+ };
3421
+
3422
+ //#endregion
3423
+ //#region ../sql-storage/src/repositories.ts
3424
+ function createRepositoryScope(database) {
3425
+ return {
3426
+ mintRepository: new SqliteMintRepository(database),
3427
+ keyRingRepository: new SqliteKeyRingRepository(database),
3428
+ counterRepository: new SqliteCounterRepository(database),
3429
+ keysetRepository: new SqliteKeysetRepository(database),
3430
+ proofRepository: new SqliteProofRepository(database),
3431
+ meltQuoteRepository: new SqliteMeltQuoteRepository(database),
3432
+ mintQuoteRepository: new SqliteMintQuoteRepository(database),
3433
+ legacyMintQuoteRepository: new SqliteLegacyMintQuoteRepository(database),
3434
+ historyRepository: new SqliteHistoryRepository(database),
3435
+ sendOperationRepository: new SqliteSendOperationRepository(database),
3436
+ meltOperationRepository: new SqliteMeltOperationRepository(database),
3437
+ authSessionRepository: new SqliteAuthSessionRepository(database),
3438
+ mintOperationRepository: new SqliteMintOperationRepository(database),
3439
+ receiveOperationRepository: new SqliteReceiveOperationRepository(database),
3440
+ paymentRequestReceiveOperationRepository: new SqlitePaymentRequestReceiveOperationRepository(database),
3441
+ paymentRequestReceiveAttemptRepository: new SqlitePaymentRequestReceiveAttemptRepository(database)
3442
+ };
3443
+ }
3444
+ var SqlStorageRepositories = class {
2270
3445
  mintRepository;
2271
3446
  keyRingRepository;
2272
3447
  counterRepository;
2273
3448
  keysetRepository;
2274
3449
  proofRepository;
3450
+ meltQuoteRepository;
2275
3451
  mintQuoteRepository;
3452
+ legacyMintQuoteRepository;
3453
+ historyRepository;
3454
+ sendOperationRepository;
3455
+ meltOperationRepository;
3456
+ authSessionRepository;
3457
+ mintOperationRepository;
3458
+ receiveOperationRepository;
3459
+ paymentRequestReceiveOperationRepository;
3460
+ paymentRequestReceiveAttemptRepository;
3461
+ database;
3462
+ constructor(options) {
3463
+ this.database = options.database;
3464
+ const repositories = createRepositoryScope(this.database);
3465
+ this.mintRepository = repositories.mintRepository;
3466
+ this.keyRingRepository = repositories.keyRingRepository;
3467
+ this.counterRepository = repositories.counterRepository;
3468
+ this.keysetRepository = repositories.keysetRepository;
3469
+ this.proofRepository = repositories.proofRepository;
3470
+ this.meltQuoteRepository = repositories.meltQuoteRepository;
3471
+ this.mintQuoteRepository = repositories.mintQuoteRepository;
3472
+ this.legacyMintQuoteRepository = repositories.legacyMintQuoteRepository;
3473
+ this.historyRepository = repositories.historyRepository;
3474
+ this.sendOperationRepository = repositories.sendOperationRepository;
3475
+ this.meltOperationRepository = repositories.meltOperationRepository;
3476
+ this.authSessionRepository = repositories.authSessionRepository;
3477
+ this.mintOperationRepository = repositories.mintOperationRepository;
3478
+ this.receiveOperationRepository = repositories.receiveOperationRepository;
3479
+ this.paymentRequestReceiveOperationRepository = repositories.paymentRequestReceiveOperationRepository;
3480
+ this.paymentRequestReceiveAttemptRepository = repositories.paymentRequestReceiveAttemptRepository;
3481
+ }
3482
+ async init() {
3483
+ await ensureSchema(this.database);
3484
+ }
3485
+ async withTransaction(fn) {
3486
+ return this.database.transaction((txDatabase) => fn(createRepositoryScope(txDatabase)));
3487
+ }
3488
+ };
3489
+
3490
+ //#endregion
3491
+ //#region src/db.ts
3492
+ function isWebRuntime() {
3493
+ const runtime = globalThis;
3494
+ return typeof runtime.window === "object" && typeof runtime.document === "object";
3495
+ }
3496
+ /**
3497
+ * Wrapper around expo-sqlite Database providing transaction management.
3498
+ *
3499
+ * Transaction behavior:
3500
+ * - Nested transactions within the same scope are "rolled up" - they reuse the parent transaction
3501
+ * - Concurrent transactions from different scopes are queued and executed serially
3502
+ * - Each top-level transaction gets a unique scope token for identification
3503
+ */
3504
+ var ExpoSqliteDb = class ExpoSqliteDb {
3505
+ root;
3506
+ operationDb;
3507
+ /** Unique identifier for this instance's transaction scope (null for root instances) */
3508
+ scopeToken;
3509
+ constructor(optionsOrRoot, scopeToken = null, operationDb) {
3510
+ if ("database" in optionsOrRoot) {
3511
+ this.root = {
3512
+ db: optionsOrRoot.database,
3513
+ transactionQueue: Promise.resolve(),
3514
+ currentScope: null,
3515
+ scopeDepth: 0,
3516
+ pendingTransactionCount: 0
3517
+ };
3518
+ this.scopeToken = null;
3519
+ this.operationDb = optionsOrRoot.database;
3520
+ } else {
3521
+ this.root = optionsOrRoot;
3522
+ this.scopeToken = scopeToken;
3523
+ this.operationDb = operationDb ?? optionsOrRoot.db;
3524
+ }
3525
+ }
3526
+ get raw() {
3527
+ return this.operationDb;
3528
+ }
3529
+ shouldWaitForTransaction() {
3530
+ return this.root.pendingTransactionCount > 0 && (!this.scopeToken || this.root.currentScope !== this.scopeToken);
3531
+ }
3532
+ async waitForActiveTransaction() {
3533
+ while (this.root.pendingTransactionCount > 0 && (!this.scopeToken || this.root.currentScope !== this.scopeToken)) await this.root.transactionQueue;
3534
+ }
3535
+ async exec(sql) {
3536
+ if (this.shouldWaitForTransaction()) await this.waitForActiveTransaction();
3537
+ await this.operationDb.execAsync(sql);
3538
+ }
3539
+ async run(sql, params = []) {
3540
+ if (this.shouldWaitForTransaction()) await this.waitForActiveTransaction();
3541
+ const result = await this.operationDb.runAsync(sql, ...params ?? []);
3542
+ const lastInsertRowId = result.lastInsertRowId ?? 0;
3543
+ return {
3544
+ lastID: lastInsertRowId,
3545
+ lastInsertRowId,
3546
+ changes: result.changes ?? 0
3547
+ };
3548
+ }
3549
+ async get(sql, params = []) {
3550
+ if (this.shouldWaitForTransaction()) await this.waitForActiveTransaction();
3551
+ return await this.operationDb.getFirstAsync(sql, ...params ?? []) ?? void 0;
3552
+ }
3553
+ async all(sql, params = []) {
3554
+ if (this.shouldWaitForTransaction()) await this.waitForActiveTransaction();
3555
+ return await this.operationDb.getAllAsync(sql, ...params ?? []) ?? [];
3556
+ }
3557
+ /**
3558
+ * Execute a function within a database transaction.
3559
+ *
3560
+ * Transaction Semantics:
3561
+ *
3562
+ * 1. NESTED TRANSACTIONS (same scope):
3563
+ * When transaction() is called from within an active transaction using the same
3564
+ * scoped ExpoSqliteDb instance, the inner call is treated as part of the outer transaction.
3565
+ * No new BEGIN/COMMIT is issued - the transaction is "rolled up".
3566
+ *
3567
+ * 2. CONCURRENT TRANSACTIONS (different scopes):
3568
+ * When transaction() is called while another transaction is active but from a
3569
+ * different scope (e.g., parallel calls), the new transaction waits in a queue.
3570
+ * Transactions execute serially to prevent "cannot start a transaction within a transaction".
3571
+ *
3572
+ * 3. ERROR HANDLING:
3573
+ * If the transaction function throws an error, ROLLBACK is executed and the error
3574
+ * is re-thrown. The transaction queue is properly released even on error, allowing
3575
+ * subsequent transactions to proceed.
3576
+ *
3577
+ * @param fn - Function to execute within the transaction, receives a scoped ExpoSqliteDb instance
3578
+ * @returns Promise that resolves with the return value of fn
3579
+ * @throws Re-throws any error from fn after rolling back the transaction
3580
+ */
3581
+ async transaction(fn) {
3582
+ const { root } = this;
3583
+ if (this.scopeToken && root.currentScope === this.scopeToken) {
3584
+ root.scopeDepth++;
3585
+ try {
3586
+ return await fn(this);
3587
+ } finally {
3588
+ root.scopeDepth--;
3589
+ }
3590
+ }
3591
+ const scopeToken = Symbol("expo-sqlite-transaction");
3592
+ const previousTransaction = root.transactionQueue;
3593
+ let resolver;
3594
+ root.transactionQueue = new Promise((resolve) => {
3595
+ resolver = resolve;
3596
+ });
3597
+ root.pendingTransactionCount++;
3598
+ try {
3599
+ await previousTransaction;
3600
+ const dbAny = root.db;
3601
+ root.currentScope = scopeToken;
3602
+ root.scopeDepth = 1;
3603
+ if (typeof dbAny.withExclusiveTransactionAsync === "function" && !isWebRuntime()) {
3604
+ let result;
3605
+ await dbAny.withExclusiveTransactionAsync(async (txn) => {
3606
+ result = await fn(new ExpoSqliteDb(root, scopeToken, txn));
3607
+ });
3608
+ return result;
3609
+ }
3610
+ if (typeof dbAny.withTransactionAsync === "function") {
3611
+ const scopedDb = new ExpoSqliteDb(root, scopeToken);
3612
+ let result;
3613
+ await dbAny.withTransactionAsync(async () => {
3614
+ result = await fn(scopedDb);
3615
+ });
3616
+ return result;
3617
+ }
3618
+ const scopedDb = new ExpoSqliteDb(root, scopeToken);
3619
+ await dbAny.execAsync("BEGIN");
3620
+ try {
3621
+ const res = await fn(scopedDb);
3622
+ await dbAny.execAsync("COMMIT");
3623
+ return res;
3624
+ } catch (error) {
3625
+ try {
3626
+ await dbAny.execAsync("ROLLBACK");
3627
+ } catch {}
3628
+ throw error;
3629
+ }
3630
+ } finally {
3631
+ root.scopeDepth = 0;
3632
+ root.currentScope = null;
3633
+ root.pendingTransactionCount--;
3634
+ resolver();
3635
+ }
3636
+ }
3637
+ };
3638
+
3639
+ //#endregion
3640
+ //#region src/index.ts
3641
+ var SqliteRepositories = class {
3642
+ mintRepository;
3643
+ keyRingRepository;
3644
+ counterRepository;
3645
+ keysetRepository;
3646
+ proofRepository;
2276
3647
  meltQuoteRepository;
3648
+ mintQuoteRepository;
3649
+ legacyMintQuoteRepository;
2277
3650
  historyRepository;
2278
3651
  sendOperationRepository;
2279
3652
  meltOperationRepository;
2280
3653
  authSessionRepository;
2281
3654
  mintOperationRepository;
2282
3655
  receiveOperationRepository;
3656
+ paymentRequestReceiveOperationRepository;
3657
+ paymentRequestReceiveAttemptRepository;
2283
3658
  db;
3659
+ repositories;
2284
3660
  constructor(options) {
2285
3661
  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);
3662
+ this.repositories = new SqlStorageRepositories({ database: this.db });
3663
+ this.mintRepository = this.repositories.mintRepository;
3664
+ this.keyRingRepository = this.repositories.keyRingRepository;
3665
+ this.counterRepository = this.repositories.counterRepository;
3666
+ this.keysetRepository = this.repositories.keysetRepository;
3667
+ this.proofRepository = this.repositories.proofRepository;
3668
+ this.meltQuoteRepository = this.repositories.meltQuoteRepository;
3669
+ this.mintQuoteRepository = this.repositories.mintQuoteRepository;
3670
+ this.legacyMintQuoteRepository = this.repositories.legacyMintQuoteRepository;
3671
+ this.historyRepository = this.repositories.historyRepository;
3672
+ this.sendOperationRepository = this.repositories.sendOperationRepository;
3673
+ this.meltOperationRepository = this.repositories.meltOperationRepository;
3674
+ this.authSessionRepository = this.repositories.authSessionRepository;
3675
+ this.mintOperationRepository = this.repositories.mintOperationRepository;
3676
+ this.receiveOperationRepository = this.repositories.receiveOperationRepository;
3677
+ this.paymentRequestReceiveOperationRepository = this.repositories.paymentRequestReceiveOperationRepository;
3678
+ this.paymentRequestReceiveAttemptRepository = this.repositories.paymentRequestReceiveAttemptRepository;
2299
3679
  }
2300
3680
  async init() {
2301
- await ensureSchema(this.db);
3681
+ await this.repositories.init();
2302
3682
  }
2303
3683
  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
- });
3684
+ return this.repositories.withTransaction(fn);
2321
3685
  }
2322
3686
  };
2323
3687
 
2324
3688
  //#endregion
2325
- export { ExpoAuthSessionRepository, ExpoCounterRepository, ExpoHistoryRepository, ExpoKeyRingRepository, ExpoKeysetRepository, ExpoMeltOperationRepository, ExpoMeltQuoteRepository, ExpoMintOperationRepository, ExpoMintQuoteRepository, ExpoMintRepository, ExpoProofRepository, ExpoReceiveOperationRepository, ExpoSendOperationRepository, ExpoSqliteDb, ExpoSqliteRepositories, MIGRATIONS, ensureSchema, ensureSchemaUpTo };
3689
+ export { SqliteRepositories as ExpoSqliteRepositories, SqliteRepositories };