@bsv/expo-wallet-toolbox 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/LICENSE.txt +28 -0
  2. package/README.md +512 -0
  3. package/assets/sounds/payment-receive.wav +0 -0
  4. package/assets/sounds/payment-send.wav +0 -0
  5. package/assets/sounds/vault-close.wav +0 -0
  6. package/assets/sounds/vault-open.wav +0 -0
  7. package/core/amountFormatHelpers.ts +330 -0
  8. package/core/backup/RemoteSyncReader.ts +94 -0
  9. package/core/backup/client.ts +111 -0
  10. package/core/backup/codec.ts +218 -0
  11. package/core/backup/constants.ts +88 -0
  12. package/core/backup/cursor.ts +138 -0
  13. package/core/backup/derive.ts +46 -0
  14. package/core/backup/deviceId.ts +33 -0
  15. package/core/backup/erase.ts +67 -0
  16. package/core/backup/preference.ts +33 -0
  17. package/core/backup/push.ts +295 -0
  18. package/core/backup/restore.ts +152 -0
  19. package/core/backup/restoreOnImport.ts +119 -0
  20. package/core/backup/status.ts +46 -0
  21. package/core/config.tsx +47 -0
  22. package/core/constants.ts +35 -0
  23. package/core/context/ExchangeRateContext.tsx +69 -0
  24. package/core/context/LocalStorageProvider.tsx +225 -0
  25. package/core/context/UserContext.tsx +129 -0
  26. package/core/context/VaultContext.tsx +79 -0
  27. package/core/context/WalletConnectionContext.tsx +454 -0
  28. package/core/context/WalletContext.tsx +2938 -0
  29. package/core/context/buildGeneration.ts +37 -0
  30. package/core/deviceTier.ts +89 -0
  31. package/core/diskSpace.ts +62 -0
  32. package/core/displayCurrencies.ts +56 -0
  33. package/core/headers/OfflineFirstChaintracks.ts +176 -0
  34. package/core/headers/checkpoints.ts +39 -0
  35. package/core/headers/fs.ts +119 -0
  36. package/core/headers/headerStore.ts +333 -0
  37. package/core/headers/prewarm.ts +36 -0
  38. package/core/headers/syncHeaders.ts +73 -0
  39. package/core/hooks/useConfirmationSound.ts +135 -0
  40. package/core/hooks/useHaptics.ts +51 -0
  41. package/core/hooks/usePermissionQueue.ts +69 -0
  42. package/core/i18n/translations.tsx +6692 -0
  43. package/core/index.ts +295 -0
  44. package/core/localpay/blePermissions.ts +32 -0
  45. package/core/localpay/build.ts +392 -0
  46. package/core/localpay/codec.ts +338 -0
  47. package/core/localpay/deviceCaps.ts +175 -0
  48. package/core/localpay/nearbyAdvisory.ts +32 -0
  49. package/core/localpay/nearbyPermissions.ts +34 -0
  50. package/core/localpay/pending.ts +385 -0
  51. package/core/localpay/pendingAborts.ts +67 -0
  52. package/core/localpay/qr.ts +16 -0
  53. package/core/localpay/session.ts +277 -0
  54. package/core/localpay/sessionPolicy.ts +5 -0
  55. package/core/localpay/transport/awdl.ts +11 -0
  56. package/core/localpay/transport/ble.ts +159 -0
  57. package/core/localpay/transport/nearby.ts +12 -0
  58. package/core/localpay/transport/race.ts +110 -0
  59. package/core/localpay/transport/select.ts +128 -0
  60. package/core/localpay/transport/socket.ts +244 -0
  61. package/core/localpay/types.ts +82 -0
  62. package/core/localpay/verify.ts +204 -0
  63. package/core/logging.config.ts +10 -0
  64. package/core/logging.ts +77 -0
  65. package/core/mnemonicWallet.ts +180 -0
  66. package/core/monitor/TaskBackupPush.ts +168 -0
  67. package/core/monitor/TaskCreditInbox.ts +116 -0
  68. package/core/monitor/TaskDrainOutbox.ts +122 -0
  69. package/core/monitor/TaskSendOffline.ts +123 -0
  70. package/core/monitor/unfailRetry.ts +116 -0
  71. package/core/net/chainMatch.ts +34 -0
  72. package/core/net/online.ts +34 -0
  73. package/core/offline/cancelParked.ts +56 -0
  74. package/core/offline/hold.ts +127 -0
  75. package/core/offline/order.ts +109 -0
  76. package/core/offline/payerHold.ts +144 -0
  77. package/core/offline/plan.ts +264 -0
  78. package/core/offline/queueGrace.ts +52 -0
  79. package/core/parsePeerPayURI.ts +119 -0
  80. package/core/pay/beefRepair.ts +106 -0
  81. package/core/pay/creditErrors.ts +46 -0
  82. package/core/pay/creditInbox.ts +202 -0
  83. package/core/pay/damagedInbox.ts +64 -0
  84. package/core/pay/proofNudge.ts +23 -0
  85. package/core/pay/provenTxFromBump.ts +31 -0
  86. package/core/pay/rails/address.ts +329 -0
  87. package/core/pay/rails/handle.ts +617 -0
  88. package/core/pay/rails/index.ts +197 -0
  89. package/core/pay/rails/nearby.ts +79 -0
  90. package/core/pay/receiveFocus.ts +13 -0
  91. package/core/pay/recordProof.ts +91 -0
  92. package/core/pay/refreshProofGuard.ts +34 -0
  93. package/core/pay/sweeper.ts +75 -0
  94. package/core/pay/tokenAmount.ts +18 -0
  95. package/core/pay/userError.ts +18 -0
  96. package/core/pay/watchlist.ts +126 -0
  97. package/core/peerpay/control.ts +122 -0
  98. package/core/peerpay/handleResendRequests.ts +475 -0
  99. package/core/peerpay/inboxAttempts.ts +33 -0
  100. package/core/peerpay/metadataDecryptor.ts +42 -0
  101. package/core/peerpay/offlineNacks.ts +96 -0
  102. package/core/peerpay/outbox.ts +209 -0
  103. package/core/peerpay/rebuildToken.ts +76 -0
  104. package/core/peerpay/resendBeef.ts +115 -0
  105. package/core/services/arcadeBroadcastProvider.ts +214 -0
  106. package/core/services/capWalletArgs.ts +99 -0
  107. package/core/services/exchangeRate.ts +63 -0
  108. package/core/services/secrets/envelope.ts +102 -0
  109. package/core/services/secrets/hkdf.ts +37 -0
  110. package/core/services/secrets/index.ts +63 -0
  111. package/core/services/secrets/kek.ts +274 -0
  112. package/core/services/secrets/migration.ts +188 -0
  113. package/core/services/secrets/policy.ts +120 -0
  114. package/core/services/secrets/storage.ts +54 -0
  115. package/core/services/secrets/store.ts +125 -0
  116. package/core/services/secrets/types.ts +85 -0
  117. package/core/services/usdFxRates.ts +101 -0
  118. package/core/services/vault/VaultKeyService.ts +312 -0
  119. package/core/services/vault/backupAttestation.ts +136 -0
  120. package/core/services/vault/ceremony.ts +972 -0
  121. package/core/services/vault/ceremonyHost.ts +46 -0
  122. package/core/services/vault/devMock.ts +22 -0
  123. package/core/services/vault/driver.ts +197 -0
  124. package/core/services/vault/guard.ts +90 -0
  125. package/core/services/vault/k1.ts +75 -0
  126. package/core/services/vault/mockYubiKey.ts +217 -0
  127. package/core/services/vault/random.ts +20 -0
  128. package/core/services/vault/sealing.ts +84 -0
  129. package/core/services/vault/session.ts +59 -0
  130. package/core/services/vault/transfers.ts +1151 -0
  131. package/core/services/vault/types.ts +109 -0
  132. package/core/services/vault/vaultDerivation.ts +152 -0
  133. package/core/services/vault/vaultPassphrase.ts +287 -0
  134. package/core/services/vault/vaultStore.ts +104 -0
  135. package/core/services/walletArgLimits.ts +234 -0
  136. package/core/services/walletServiceConfig.ts +170 -0
  137. package/core/storage/LocalStorageAdapter.ts +58 -0
  138. package/core/storage/README.md +391 -0
  139. package/core/storage/StorageExpoSQLite.ts +2008 -0
  140. package/core/storage/errors.ts +73 -0
  141. package/core/storage/index.ts +3 -0
  142. package/core/storage/methods/findSql.ts +286 -0
  143. package/core/storage/methods/historyNotes.ts +61 -0
  144. package/core/storage/methods/listActionsSql.ts +212 -0
  145. package/core/storage/methods/listOutputsSql.ts +211 -0
  146. package/core/storage/methods/offlineActions.ts +156 -0
  147. package/core/storage/methods/processOfflineActions.ts +503 -0
  148. package/core/storage/methods/reclaim.ts +135 -0
  149. package/core/storage/methods/reviewStatusSql.ts +167 -0
  150. package/core/storage/methods/unprovenWithoutReqSql.ts +26 -0
  151. package/core/storage/methods/walletBalanceSql.ts +55 -0
  152. package/core/storage/schema/createTables.ts +385 -0
  153. package/core/storage/skipQueuedAncestors.ts +29 -0
  154. package/core/storage/sqlUpdateValue.ts +12 -0
  155. package/core/stores/ConnectionStore.ts +71 -0
  156. package/core/theme/ThemeContext.tsx +182 -0
  157. package/core/theme/assertThemeContrast.ts +109 -0
  158. package/core/theme/motion.ts +50 -0
  159. package/core/theme/tokens.ts +232 -0
  160. package/core/theme/useThemeStyles.tsx +156 -0
  161. package/core/walletDbRegistry.ts +110 -0
  162. package/core/walletMonitor.ts +149 -0
  163. package/core/walletRepair/runWalletCheck.ts +195 -0
  164. package/core/walletRepair/shouldReleaseUtxo.ts +18 -0
  165. package/package.json +86 -0
  166. package/ui/backupShares.ts +367 -0
  167. package/ui/components/QRScanner.tsx +353 -0
  168. package/ui/components/pay/AddressReceive.tsx +507 -0
  169. package/ui/components/pay/AvailableBalance.tsx +61 -0
  170. package/ui/components/pay/HandleReceive.tsx +896 -0
  171. package/ui/components/pay/MessageBoxConfig.tsx +256 -0
  172. package/ui/components/pay/NearbyAdvisoryModal.tsx +111 -0
  173. package/ui/components/pay/NearbyFlow.tsx +2542 -0
  174. package/ui/components/pay/OfflineNotice.tsx +337 -0
  175. package/ui/components/pay/PayCellRow.tsx +101 -0
  176. package/ui/components/pay/PayForm.tsx +223 -0
  177. package/ui/components/pay/PaymentQrDisplay.tsx +105 -0
  178. package/ui/components/pay/PaymentSuccessOverlay.tsx +266 -0
  179. package/ui/components/pay/RecipientField.tsx +308 -0
  180. package/ui/components/pay/RequestHub.tsx +75 -0
  181. package/ui/components/pay/ResultBanner.tsx +69 -0
  182. package/ui/components/pay/UniversalSend.tsx +687 -0
  183. package/ui/components/pay/useRecipientInput.ts +270 -0
  184. package/ui/components/security/WalletLockNotice.tsx +138 -0
  185. package/ui/components/ui/AlertCard.tsx +223 -0
  186. package/ui/components/ui/AppLogo.tsx +166 -0
  187. package/ui/components/ui/BlurChrome.tsx +72 -0
  188. package/ui/components/ui/Celebration.tsx +84 -0
  189. package/ui/components/ui/ChoiceSheet.ts +69 -0
  190. package/ui/components/ui/CustomSafeArea.tsx +74 -0
  191. package/ui/components/ui/ErrorBoundary.tsx +154 -0
  192. package/ui/components/ui/GroupedList.tsx +125 -0
  193. package/ui/components/ui/IconButton.tsx +105 -0
  194. package/ui/components/ui/ListRow.tsx +197 -0
  195. package/ui/components/ui/PermissionSheet.tsx +920 -0
  196. package/ui/components/ui/PresenceRow.tsx +215 -0
  197. package/ui/components/ui/PressableScale.tsx +105 -0
  198. package/ui/components/ui/ScreenGradient.tsx +47 -0
  199. package/ui/components/ui/ScrollFade.tsx +76 -0
  200. package/ui/components/ui/Sheet.tsx +342 -0
  201. package/ui/components/ui/Toast.tsx +142 -0
  202. package/ui/components/ui/index.ts +8 -0
  203. package/ui/components/vault/EnrollWizard.tsx +627 -0
  204. package/ui/components/vault/PassphraseField.tsx +306 -0
  205. package/ui/components/vault/PhraseBackupSheet.tsx +227 -0
  206. package/ui/components/vault/VaultBackdrop.tsx +354 -0
  207. package/ui/components/vault/VaultCeremonySheet.tsx +327 -0
  208. package/ui/components/wallet/ActivityRow.tsx +408 -0
  209. package/ui/components/wallet/AmountDisplay.tsx +48 -0
  210. package/ui/components/wallet/AmountInput.tsx +256 -0
  211. package/ui/components/wallet/BackupReminderSheet.tsx +168 -0
  212. package/ui/components/wallet/Balance.tsx +144 -0
  213. package/ui/components/wallet/BiometricAdvisoryModal.tsx +133 -0
  214. package/ui/components/wallet/ImportFromBackupPrompt.tsx +93 -0
  215. package/ui/exportDatabases.ts +122 -0
  216. package/ui/exportTransactions.ts +129 -0
  217. package/ui/hooks/useOfflineNoticeActions.ts +136 -0
  218. package/ui/hooks/useOnline.ts +70 -0
  219. package/ui/hooks/useSpendableBalance.ts +58 -0
  220. package/ui/hooks/useVaultBalance.ts +50 -0
  221. package/ui/importDatabases.ts +170 -0
  222. package/ui/index.ts +136 -0
  223. package/ui/isImageUrl.ts +10 -0
  224. package/ui/printRecoveryShares.ts +93 -0
  225. package/ui/resolveIdentity.ts +125 -0
  226. package/ui/screens/ConnectionsScreen.tsx +438 -0
  227. package/ui/screens/LogsScreen.tsx +432 -0
  228. package/ui/screens/PairScreen.tsx +288 -0
  229. package/ui/screens/PayScreen.tsx +479 -0
  230. package/ui/screens/SettingsScreen.tsx +180 -0
  231. package/ui/screens/TrustScreen.tsx +831 -0
  232. package/ui/screens/VaultRecoverScreen.tsx +226 -0
  233. package/ui/screens/VaultScreen.tsx +423 -0
  234. package/ui/screens/VaultTransferScreen.tsx +293 -0
  235. package/ui/screens/WalletCheckScreen.tsx +539 -0
  236. package/ui/screens/WalletConfigScreen.tsx +1095 -0
  237. package/ui/screens/WalletHomeScreen.tsx +1597 -0
  238. package/ui/screens/homeBadges.ts +18 -0
  239. package/ui/txStatus.ts +79 -0
  240. package/ui/validateTrust.ts +44 -0
@@ -0,0 +1,2008 @@
1
+ import * as SQLite from 'expo-sqlite'
2
+ import type { SQLiteDatabase } from 'expo-sqlite'
3
+ import { createTables, ensureOfflineActionsColumns } from './schema/createTables'
4
+ import {
5
+ PROVEN_HEIGHTS_SQL,
6
+ buildFindSql,
7
+ columnsExcluding,
8
+ rangeReadSql,
9
+ RELEASE_STALE_VAULT_STAGING_SPENTBY_SQL,
10
+ RELEASE_STRANDED_VAULT_STAGING_SQL,
11
+ spendingReferencesSql,
12
+ splitOutpoint
13
+ } from './methods/findSql'
14
+ import { scrubHistoryJson } from './methods/historyNotes'
15
+ import { sqlBindValue } from './sqlUpdateValue'
16
+ import { StorageError, storageErrorFromSqlite } from './errors'
17
+ import {
18
+ RECLAIM_CANDIDATES_SQL,
19
+ RECLAIM_EXCLUDED_SQL,
20
+ RECLAIM_INPUT_BEEF_SQL,
21
+ RECLAIM_SIZES_SQL,
22
+ type ReclaimReport
23
+ } from './methods/reclaim'
24
+ import { availableDiskBytes, diskPressure } from '../diskSpace'
25
+ import { devLog } from '../logging'
26
+ import { StorageProvider } from '@bsv/wallet-toolbox-mobile'
27
+ import type { StorageProviderOptions } from '@bsv/wallet-toolbox-mobile'
28
+ import type {
29
+ AuthId,
30
+ FindCertificateFieldsArgs,
31
+ FindCertificatesArgs,
32
+ FindCommissionsArgs,
33
+ FindMonitorEventsArgs,
34
+ FindOutputBasketsArgs,
35
+ FindOutputsArgs,
36
+ FindOutputTagsArgs,
37
+ FindOutputTagMapsArgs,
38
+ FindProvenTxReqsArgs,
39
+ FindProvenTxsArgs,
40
+ FindSyncStatesArgs,
41
+ FindTransactionsArgs,
42
+ FindTxLabelsArgs,
43
+ FindTxLabelMapsArgs,
44
+ FindUsersArgs,
45
+ FindForUserSincePagedArgs,
46
+ ProcessSyncChunkResult,
47
+ ProvenOrRawTx,
48
+ PurgeParams,
49
+ PurgeResults,
50
+ RequestSyncChunkArgs,
51
+ SyncChunk,
52
+ TrxToken
53
+ } from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
54
+ import type { AdminStatsResult } from '@bsv/wallet-toolbox-mobile/out/src/storage/StorageProvider'
55
+ import type {
56
+ TableCertificate,
57
+ TableCertificateField,
58
+ TableCertificateX,
59
+ TableCommission,
60
+ TableMonitorEvent,
61
+ TableOutput,
62
+ TableOutputBasket,
63
+ TableOutputTag,
64
+ TableOutputTagMap,
65
+ TableProvenTx,
66
+ TableProvenTxReq,
67
+ TableSettings,
68
+ TableSyncState,
69
+ TableTransaction,
70
+ TableTxLabel,
71
+ TableTxLabelMap,
72
+ TableUser
73
+ } from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/tables'
74
+ import type { ListActionsResult, ListOutputsResult, Validation, WalletLoggerInterface } from '@bsv/sdk'
75
+ import { Beef } from '@bsv/sdk'
76
+ import type { EntityProvenTxReq } from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/entities'
77
+ import type { PostReqsToNetworkResult } from '@bsv/wallet-toolbox-mobile/out/src/storage/methods/attemptToPostReqsToNetwork'
78
+ import { listActionsSql } from './methods/listActionsSql'
79
+ import { listOutputsSql } from './methods/listOutputsSql'
80
+ import { findUnprovenTxidsWithoutReq } from './methods/unprovenWithoutReqSql'
81
+ import { insertOfflineAction, type OfflineActionRole } from './methods/offlineActions'
82
+ import {
83
+ LIVE_OFFLINE_SKIP_TXIDS_SQL,
84
+ REVIEW_FAILED_TXS_SQL,
85
+ REVIEW_INVALID_REQ_TXS_SQL,
86
+ REVIEW_OUTPUTS_SQL,
87
+ REVIEW_REQ_STATUSES_SQL,
88
+ collectFailedTransactionIds,
89
+ failInvalidReqTxs,
90
+ outputReviewAction,
91
+ type ReviewFailedTx,
92
+ type ReviewOutput
93
+ } from './methods/reviewStatusSql'
94
+ import { buildOfflineHoldResult, groupOfflineHolds } from '../offline/hold'
95
+ import { getOnline } from '../net/online'
96
+ import { TaskSendOffline } from '../monitor/TaskSendOffline'
97
+
98
+ export interface StorageExpoSQLiteOptions extends StorageProviderOptions {
99
+ databaseName?: string
100
+ identityKey?: string
101
+ }
102
+
103
+ /** Per-connection wait before a lock contention becomes "database is locked". */
104
+ export const BUSY_TIMEOUT_MS = 5000
105
+
106
+ /**
107
+ * The token `transaction()` hands its scope. Carrying the connection on the
108
+ * token is what lets `getDB(trx)` route a statement to the transaction without
109
+ * touching `this.db`.
110
+ */
111
+ interface SqliteTrxToken {
112
+ _inTrx: true
113
+ db: SQLiteDatabase
114
+ }
115
+
116
+ /**
117
+ * SQLite storage provider for BSV wallet using expo-sqlite.
118
+ * Extends StorageProvider to inherit business logic (createAction, internalizeAction, etc.)
119
+ * while implementing only the abstract CRUD methods.
120
+ */
121
+ export class StorageExpoSQLite extends StorageProvider {
122
+ dbName: string
123
+ db?: SQLiteDatabase
124
+
125
+ constructor(options: StorageExpoSQLiteOptions) {
126
+ super(options)
127
+ const keySuffix = (options.identityKey || 'default').slice(-8)
128
+ this.dbName = options.databaseName || `wallet-${keySuffix}-${this.chain}net.db`
129
+ }
130
+
131
+ // ============================================================================
132
+ // Infrastructure methods
133
+ // ============================================================================
134
+
135
+ async migrate(storageName: string, storageIdentityKey: string): Promise<string> {
136
+ this.db = await this.openDatabase()
137
+ // Two connections share this file whenever a transaction is open (see
138
+ // `transaction()`), and expo-sqlite sets no busy handler, so without these
139
+ // any overlap fails instantly with "database is locked". WAL lets readers
140
+ // proceed while the transaction connection writes; the busy timeout turns a
141
+ // writer-writer overlap into a short wait. WAL persists in the file, the
142
+ // timeout is per connection.
143
+ await this.db.execAsync(`PRAGMA journal_mode = WAL`)
144
+ await this.db.execAsync(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`)
145
+ await createTables(this.db)
146
+ await ensureOfflineActionsColumns(this.db)
147
+
148
+ // Check/insert settings
149
+ const existing = (await this.db.getFirstAsync('SELECT * FROM settings WHERE storageIdentityKey = ?', [
150
+ storageIdentityKey
151
+ ])) as any
152
+ if (!existing) {
153
+ const now = new Date().toISOString()
154
+ await this.db.runAsync(
155
+ `INSERT INTO settings (storageIdentityKey, storageName, chain, dbtype, maxOutputScript, created_at, updated_at)
156
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
157
+ [storageIdentityKey, storageName, this.chain, 'SQLite', 1024, now, now]
158
+ )
159
+ }
160
+
161
+ this._settings = await this.readSettings()
162
+ this.whenLastAccess = new Date()
163
+ return '1'
164
+ }
165
+
166
+ /** Seam for tests, which inject a fake connection instead of a native one. */
167
+ protected async openDatabase(): Promise<SQLiteDatabase> {
168
+ return await SQLite.openDatabaseAsync(this.dbName)
169
+ }
170
+
171
+ async readSettings(trx?: TrxToken): Promise<TableSettings> {
172
+ const db = this.getDB(trx)
173
+ const row = (await db.getFirstAsync('SELECT * FROM settings LIMIT 1')) as any
174
+ if (!row) throw new Error('Settings not found. Call migrate() first.')
175
+ return this.validateEntity({ ...row })
176
+ }
177
+
178
+ async destroy(): Promise<void> {
179
+ if (this.db) {
180
+ await this.db.closeAsync()
181
+ }
182
+ this.db = undefined
183
+ this._settings = undefined
184
+ }
185
+
186
+ // ============================================================================
187
+ // Key-value store (for app-level state like SSE lastEventId)
188
+ // ============================================================================
189
+
190
+ async getKeyValue(key: string): Promise<string | undefined> {
191
+ const db = this.getDB()
192
+ const row = (await db.getFirstAsync('SELECT value FROM key_value_store WHERE key = ?', [key])) as {
193
+ value: string
194
+ } | null
195
+ return row?.value
196
+ }
197
+
198
+ async setKeyValue(key: string, value: string): Promise<void> {
199
+ const db = this.getDB()
200
+ await db.runAsync(
201
+ `INSERT INTO key_value_store (key, value, updated_at) VALUES (?, ?, ?)
202
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,
203
+ [key, value, new Date().toISOString()]
204
+ )
205
+ }
206
+
207
+ /**
208
+ * Every wallet write funnels through here, which makes it the one place a
209
+ * storage-pressure gate and a failure classifier need to live.
210
+ *
211
+ * The pre-flight check is not belt-and-braces, it is the only reliable
212
+ * diagnosis: withExclusiveTransactionAsync awaits ROLLBACK inside its own
213
+ * catch BEFORE recording the error, so a rollback that also fails under disk
214
+ * pressure propagates instead and the original cause is destroyed.
215
+ * (node_modules/expo-sqlite/src/SQLiteDatabase.ts:184-189.)
216
+ *
217
+ * 'unknown' pressure proceeds. The reading can be null on either platform, and
218
+ * refusing writes because the disk could not be read would be worse than the
219
+ * problem — see utils/diskSpace.ts.
220
+ */
221
+ async transaction<T>(scope: (trx: TrxToken) => Promise<T>, trx?: TrxToken): Promise<T> {
222
+ // If already inside a transaction, reuse it — no nested BEGIN.
223
+ if (trx) return await scope(trx)
224
+
225
+ if (diskPressure() === 'block') {
226
+ throw new StorageError(
227
+ 'disk-full',
228
+ 'Not enough free storage to write to the wallet database. Free some space and try again.'
229
+ )
230
+ }
231
+
232
+ const db = this.getDB()
233
+
234
+ // withExclusiveTransactionAsync opens a dedicated connection for the
235
+ // transaction and CLOSES it when the scope ends. That connection must be
236
+ // reachable only through the token: an earlier version swapped `this.db`
237
+ // to it for the scope's duration, so any concurrent caller without a token
238
+ // (a monitor task, a balance refresh, a raw `sqliteDb` user) prepared
239
+ // statements on a connection that was then closed under it — a native
240
+ // SIGSEGV in exsqlite3_reset on Android. Everything without a token now
241
+ // stays on the main connection, and WAL + busy_timeout (see `migrate`)
242
+ // handle the two connections overlapping.
243
+ //
244
+ // Transactions are also serialised here. Two exclusive connections at once
245
+ // would each BEGIN deferred, and in WAL the second one's first write fails
246
+ // with SQLITE_BUSY_SNAPSHOT — which no busy handler can wait out.
247
+ const unlock = await this.acquireTransactionLock()
248
+ let result!: T
249
+ try {
250
+ await db.withExclusiveTransactionAsync(async txn => {
251
+ // Fresh connection, so the main connection's busy timeout does not
252
+ // apply to it.
253
+ await txn.execAsync(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`)
254
+ const token: SqliteTrxToken = { _inTrx: true, db: txn as unknown as SQLiteDatabase }
255
+ result = await scope(token as unknown as TrxToken)
256
+ })
257
+ } catch (e) {
258
+ // Rethrow a recognisable storage failure as a typed one so the UI can say
259
+ // something true about it. Anything unrecognised passes through untouched:
260
+ // guessing would turn a schema bug into a "free up space" prompt.
261
+ const classified = storageErrorFromSqlite(e)
262
+ throw classified ?? e
263
+ } finally {
264
+ unlock()
265
+ }
266
+ return result
267
+ }
268
+
269
+ /**
270
+ * How long a transaction may wait for the previous one before failing. A
271
+ * wait this long means a scope is stuck (most likely a nested `transaction()`
272
+ * call that forgot to pass its token); failing beats hanging the wallet.
273
+ */
274
+ transactionLockTimeoutMs = 30_000
275
+ private transactionLock: Promise<void> = Promise.resolve()
276
+
277
+ private async acquireTransactionLock(): Promise<() => void> {
278
+ let release!: () => void
279
+ const held = new Promise<void>(r => (release = r))
280
+ const previous = this.transactionLock
281
+ this.transactionLock = previous.then(() => held)
282
+ let timer: ReturnType<typeof setTimeout> | undefined
283
+ const timedOut = new Promise<never>((_, reject) => {
284
+ timer = setTimeout(
285
+ () => reject(new Error(`transaction lock wait exceeded ${this.transactionLockTimeoutMs}ms`)),
286
+ this.transactionLockTimeoutMs
287
+ )
288
+ })
289
+ try {
290
+ await Promise.race([previous, timedOut])
291
+ } catch (e) {
292
+ // Give the slot back so the chain is not left waiting on a promise that
293
+ // no scope will ever resolve.
294
+ release()
295
+ throw e
296
+ } finally {
297
+ if (timer) clearTimeout(timer)
298
+ }
299
+ return release
300
+ }
301
+
302
+ /**
303
+ * Fold the write-ahead log back into the main file. In WAL mode (see
304
+ * `migrate`) recent commits live in `<name>.db-wal` until a checkpoint, so
305
+ * anything that copies the `.db` file as bytes — the iOS export — must call
306
+ * this first or ship a snapshot missing the newest transactions.
307
+ */
308
+ async checkpointWal(): Promise<void> {
309
+ await this.getDB().execAsync('PRAGMA wal_checkpoint(TRUNCATE)')
310
+ }
311
+
312
+ async dropAllData(): Promise<void> {
313
+ throw new Error('dropAllData is not supported — this database contains critical wallet data')
314
+ }
315
+
316
+ // ============================================================================
317
+ // Validation helpers (matching StorageIdb patterns)
318
+ // ============================================================================
319
+
320
+ verifyReadyForDatabaseAccess(_trx?: TrxToken): string {
321
+ if (!this._settings) {
322
+ throw new Error('Settings not loaded. Call migrate() first.')
323
+ }
324
+ return this._settings.dbtype as string
325
+ }
326
+
327
+ /**
328
+ * The connection a statement must run on. Inside a `transaction()` scope
329
+ * that is the token's own connection; everywhere else it is the shared main
330
+ * connection. The token is the ONLY route to the transaction connection —
331
+ * see `transaction()` for why `this.db` is never swapped.
332
+ */
333
+ private getDB(trx?: TrxToken): SQLiteDatabase {
334
+ const bound = (trx as SqliteTrxToken | undefined)?.db
335
+ if (bound) {
336
+ this.whenLastAccess = new Date()
337
+ return bound
338
+ }
339
+ if (!this.db) throw new Error('Database not initialized. Call migrate() first.')
340
+ this.whenLastAccess = new Date()
341
+ return this.db
342
+ }
343
+
344
+ validateEntity(entity: any, dateFields?: string[], booleanFields?: string[]): any {
345
+ entity.created_at = this.validateDate(entity.created_at)
346
+ entity.updated_at = this.validateDate(entity.updated_at)
347
+ if (dateFields) {
348
+ for (const df of dateFields) {
349
+ if (entity[df]) entity[df] = this.validateDate(entity[df])
350
+ }
351
+ }
352
+ if (booleanFields) {
353
+ for (const df of booleanFields) {
354
+ if (entity[df] !== undefined) entity[df] = !!entity[df]
355
+ }
356
+ }
357
+ for (const key of Object.keys(entity)) {
358
+ const val = entity[key]
359
+ if (val === null) {
360
+ entity[key] = undefined
361
+ } else if (val instanceof Uint8Array) {
362
+ entity[key] = Array.from(val)
363
+ }
364
+ }
365
+ return entity
366
+ }
367
+
368
+ validateEntities(entities: any[], dateFields?: string[], booleanFields?: string[]): any[] {
369
+ for (let i = 0; i < entities.length; i++) {
370
+ entities[i] = this.validateEntity(entities[i], dateFields, booleanFields)
371
+ }
372
+ return entities
373
+ }
374
+
375
+ validatePartialForUpdate(update: any, dateFields?: string[], booleanFields?: string[]): any {
376
+ this.verifyReadyForDatabaseAccess()
377
+ const v = { ...update } as any
378
+ if (v.created_at) v.created_at = this.validateEntityDate(v.created_at)
379
+ if (v.updated_at) v.updated_at = this.validateEntityDate(v.updated_at)
380
+ if (!v.created_at) delete v.created_at
381
+ if (!v.updated_at) v.updated_at = this.validateEntityDate(new Date())
382
+ if (dateFields) {
383
+ for (const df of dateFields) {
384
+ if (v[df]) v[df] = this.validateOptionalEntityDate(v[df])
385
+ }
386
+ }
387
+ if (booleanFields) {
388
+ for (const df of booleanFields) {
389
+ if (update[df] !== undefined) v[df] = !!update[df] ? 1 : 0
390
+ }
391
+ }
392
+ for (const key of Object.keys(v)) {
393
+ const val = v[key]
394
+ if (Array.isArray(val) && (val.length === 0 || Number.isInteger(val[0]))) {
395
+ v[key] = Uint8Array.from(val)
396
+ } else if (val === null) {
397
+ v[key] = undefined
398
+ } else if (typeof val === 'boolean') {
399
+ // SQLite: always convert booleans to 0/1
400
+ v[key] = val ? 1 : 0
401
+ }
402
+ }
403
+ this.isDirty = true
404
+ return v
405
+ }
406
+
407
+ async validateEntityForInsert(
408
+ entity: any,
409
+ trx?: TrxToken,
410
+ dateFields?: string[],
411
+ booleanFields?: string[]
412
+ ): Promise<any> {
413
+ this.verifyReadyForDatabaseAccess(trx)
414
+ const v = { ...entity } as any
415
+ v.created_at = this.validateOptionalEntityDate(v.created_at, true)
416
+ v.updated_at = this.validateOptionalEntityDate(v.updated_at, true)
417
+ if (!v.created_at) delete v.created_at
418
+ if (!v.updated_at) delete v.updated_at
419
+ if (dateFields) {
420
+ for (const df of dateFields) {
421
+ if (v[df]) v[df] = this.validateOptionalEntityDate(v[df])
422
+ }
423
+ }
424
+ if (booleanFields) {
425
+ for (const df of booleanFields) {
426
+ if (entity[df] !== undefined) v[df] = !!entity[df] ? 1 : 0
427
+ }
428
+ }
429
+ for (const key of Object.keys(v)) {
430
+ const val = v[key]
431
+ if (Array.isArray(val) && (val.length === 0 || Number.isInteger(val[0]))) {
432
+ v[key] = Uint8Array.from(val)
433
+ } else if (val === null) {
434
+ v[key] = undefined
435
+ } else if (typeof val === 'boolean') {
436
+ // SQLite: always convert booleans to 0/1
437
+ v[key] = val ? 1 : 0
438
+ }
439
+ }
440
+ this.isDirty = true
441
+ return v
442
+ }
443
+
444
+ // ============================================================================
445
+ // Generic SQL helpers
446
+ // ============================================================================
447
+
448
+ private buildWhere(partial: Record<string, any>, extras?: string[]): { sql: string; params: any[] } {
449
+ const conditions: string[] = []
450
+ const params: any[] = []
451
+ for (const [key, value] of Object.entries(partial)) {
452
+ if (value !== undefined) {
453
+ conditions.push(`"${key}" = ?`)
454
+ // Convert booleans to 0/1 for SQLite, Dates to strings
455
+ const v =
456
+ typeof value === 'boolean'
457
+ ? value
458
+ ? 1
459
+ : 0
460
+ : value instanceof Date
461
+ ? this.validateDateForWhere(value)
462
+ : value
463
+ params.push(v)
464
+ }
465
+ }
466
+ if (extras) {
467
+ for (const e of extras) conditions.push(e)
468
+ }
469
+ const sql = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
470
+ return { sql, params }
471
+ }
472
+
473
+ /**
474
+ * @param columns explicit projection. Omit for `SELECT *`. Passing the
475
+ * non-blob columns is what makes `noRawTx`/`noScript` actually cheap: without
476
+ * it every BLOB is read off disk and `Array.from`-expanded by validateEntity
477
+ * before being discarded. See storage/methods/findSql.ts.
478
+ */
479
+ private async sqlFind<T>(
480
+ table: string,
481
+ args: {
482
+ partial: Record<string, any>
483
+ since?: Date
484
+ paged?: { limit?: number; offset?: number }
485
+ orderDescending?: boolean
486
+ trx?: TrxToken
487
+ },
488
+ pkCol: string,
489
+ extraClauses?: { conditions: string[]; params: any[] },
490
+ columns?: string[]
491
+ ): Promise<T[]> {
492
+ const db = this.getDB(args.trx)
493
+ const { sql: whereSql, params } = this.buildWhere(args.partial)
494
+
495
+ // Params must be pushed in the same order buildFindSql emits their
496
+ // placeholders: where, then since, then the extra conditions.
497
+ if (args.since) params.push(this.validateDateForWhere(args.since))
498
+ if (extraClauses) params.push(...extraClauses.params)
499
+
500
+ const query = buildFindSql({
501
+ table,
502
+ whereSql,
503
+ hasSince: args.since !== undefined,
504
+ extraConditions: extraClauses?.conditions,
505
+ pkCol,
506
+ orderDescending: args.orderDescending,
507
+ limit: args.paged?.limit,
508
+ offset: args.paged?.offset,
509
+ columns
510
+ })
511
+ return (await db.getAllAsync(query, params)) as T[]
512
+ }
513
+
514
+ private async sqlCount(
515
+ table: string,
516
+ args: { partial: Record<string, any>; since?: Date; trx?: TrxToken },
517
+ extraClauses?: { conditions: string[]; params: any[] }
518
+ ): Promise<number> {
519
+ const db = this.getDB(args.trx)
520
+ const { sql: whereSql, params } = this.buildWhere(args.partial)
521
+ let query = `SELECT COUNT(*) as count FROM "${table}" ${whereSql}`
522
+
523
+ if (args.since) {
524
+ query += `${whereSql ? ' AND' : ' WHERE'} updated_at >= ?`
525
+ params.push(this.validateDateForWhere(args.since))
526
+ }
527
+ if (extraClauses) {
528
+ for (const c of extraClauses.conditions) {
529
+ query += `${whereSql || args.since ? ' AND' : ' WHERE'} ${c}`
530
+ }
531
+ params.push(...extraClauses.params)
532
+ }
533
+ const result = (await db.getFirstAsync(query, params)) as any
534
+ return result?.count || 0
535
+ }
536
+
537
+ /**
538
+ * The same shape as sqlCount, for a SUM over one column — so a total can be
539
+ * computed by SQLite instead of by marshalling every row into JS to add it up.
540
+ * `column` is never caller-supplied; it names a schema column literally.
541
+ */
542
+ private async sqlSum(
543
+ table: string,
544
+ column: string,
545
+ args: { partial: Record<string, any>; since?: Date; trx?: TrxToken },
546
+ extraClauses?: { conditions: string[]; params: any[] }
547
+ ): Promise<{ count: number; total: number }> {
548
+ const db = this.getDB(args.trx)
549
+ const { sql: whereSql, params } = this.buildWhere(args.partial)
550
+ let query = `SELECT COUNT(*) as count, COALESCE(SUM("${column}"), 0) as total FROM "${table}" ${whereSql}`
551
+
552
+ if (args.since) {
553
+ query += `${whereSql ? ' AND' : ' WHERE'} updated_at >= ?`
554
+ params.push(this.validateDateForWhere(args.since))
555
+ }
556
+ if (extraClauses) {
557
+ for (const c of extraClauses.conditions) {
558
+ query += `${whereSql || args.since ? ' AND' : ' WHERE'} ${c}`
559
+ }
560
+ params.push(...extraClauses.params)
561
+ }
562
+ const result = (await db.getFirstAsync(query, params)) as any
563
+ return { count: result?.count || 0, total: result?.total || 0 }
564
+ }
565
+
566
+ /**
567
+ * Column names of a table, cached for the life of this connection.
568
+ *
569
+ * Read from the database rather than hardcoded so that a column added by a
570
+ * later migration cannot silently disappear from reads that project columns
571
+ * explicitly (see findOutputs' noScript path).
572
+ */
573
+ private tableColumnsCache = new Map<string, string[]>()
574
+ private async tableColumns(table: string): Promise<string[]> {
575
+ const cached = this.tableColumnsCache.get(table)
576
+ if (cached) return cached
577
+ const rows = (await this.getDB().getAllAsync(`PRAGMA table_info("${table}")`, [])) as { name: string }[]
578
+ const names = rows.map(r => r.name)
579
+ this.tableColumnsCache.set(table, names)
580
+ return names
581
+ }
582
+
583
+ private async sqlInsert(
584
+ table: string,
585
+ entity: Record<string, any>,
586
+ pkCol: string,
587
+ trx?: TrxToken
588
+ ): Promise<number> {
589
+ const db = this.getDB(trx)
590
+ const cols: string[] = []
591
+ const placeholders: string[] = []
592
+ const vals: any[] = []
593
+ for (const [key, value] of Object.entries(entity)) {
594
+ if (value !== undefined) {
595
+ cols.push(`"${key}"`)
596
+ placeholders.push('?')
597
+ vals.push(value)
598
+ }
599
+ }
600
+ const sql = `INSERT INTO "${table}" (${cols.join(', ')}) VALUES (${placeholders.join(', ')})`
601
+ try {
602
+ const result = await db.runAsync(sql, vals)
603
+ return result.lastInsertRowId
604
+ } catch (e: any) {
605
+ console.error(`[StorageExpoSQLite] INSERT into ${table} failed:`, e.message, '\nSQL:', sql, '\nCols:', cols)
606
+ throw e
607
+ }
608
+ }
609
+
610
+ private async sqlUpdate(
611
+ table: string,
612
+ ids: number | number[],
613
+ update: Record<string, any>,
614
+ pkCol: string,
615
+ trx?: TrxToken
616
+ ): Promise<number> {
617
+ const db = this.getDB(trx)
618
+ const setClauses: string[] = []
619
+ const vals: any[] = []
620
+ for (const [key, value] of Object.entries(update)) {
621
+ if (key === pkCol) continue
622
+ const bind = sqlBindValue(table, key, value)
623
+ if (bind.omit) continue
624
+ setClauses.push(`"${key}" = ?`)
625
+ vals.push(bind.value instanceof Date ? this.validateDateForWhere(bind.value) : bind.value)
626
+ }
627
+ if (setClauses.length === 0) return 0
628
+ const idArr = Array.isArray(ids) ? ids : [ids]
629
+ const placeholders = idArr.map(() => '?').join(', ')
630
+ vals.push(...idArr)
631
+ const result = await db.runAsync(
632
+ `UPDATE "${table}" SET ${setClauses.join(', ')} WHERE "${pkCol}" IN (${placeholders})`,
633
+ vals
634
+ )
635
+ return result.changes
636
+ }
637
+
638
+ private async sqlUpdateComposite(
639
+ table: string,
640
+ keyMap: Record<string, any>,
641
+ update: Record<string, any>,
642
+ trx?: TrxToken
643
+ ): Promise<number> {
644
+ const db = this.getDB(trx)
645
+ const setClauses: string[] = []
646
+ const vals: any[] = []
647
+ for (const [key, value] of Object.entries(update)) {
648
+ if (key in keyMap) continue
649
+ const bind = sqlBindValue(table, key, value)
650
+ if (bind.omit) continue
651
+ setClauses.push(`"${key}" = ?`)
652
+ vals.push(bind.value)
653
+ }
654
+ if (setClauses.length === 0) return 0
655
+ const whereClauses: string[] = []
656
+ for (const [key, value] of Object.entries(keyMap)) {
657
+ whereClauses.push(`"${key}" = ?`)
658
+ vals.push(value)
659
+ }
660
+ const result = await db.runAsync(
661
+ `UPDATE "${table}" SET ${setClauses.join(', ')} WHERE ${whereClauses.join(' AND ')}`,
662
+ vals
663
+ )
664
+ return result.changes
665
+ }
666
+
667
+ // ============================================================================
668
+ // INSERT methods (15)
669
+ // ============================================================================
670
+
671
+ async insertUser(user: TableUser, trx?: TrxToken): Promise<number> {
672
+ const e = await this.validateEntityForInsert(user, trx)
673
+ if (e.userId === 0) delete e.userId
674
+ const id = await this.sqlInsert('users', e, 'userId', trx)
675
+ user.userId = id
676
+ return id
677
+ }
678
+
679
+ async insertProvenTx(tx: TableProvenTx, trx?: TrxToken): Promise<number> {
680
+ const e = await this.validateEntityForInsert(tx, trx)
681
+ if (e.provenTxId === 0) delete e.provenTxId
682
+ const id = await this.sqlInsert('proven_txs', e, 'provenTxId', trx)
683
+ tx.provenTxId = id
684
+ return id
685
+ }
686
+
687
+ async insertProvenTxReq(tx: TableProvenTxReq, trx?: TrxToken): Promise<number> {
688
+ const e = await this.validateEntityForInsert(tx, trx)
689
+ if (e.provenTxReqId === 0) delete e.provenTxReqId
690
+ // See methods/historyNotes.ts: provider error notes carry the full EF/rawTx
691
+ // hex and reach this column untruncated.
692
+ e.history = scrubHistoryJson(e.history)
693
+ const id = await this.sqlInsert('proven_tx_reqs', e, 'provenTxReqId', trx)
694
+ tx.provenTxReqId = id
695
+ return id
696
+ }
697
+
698
+ async insertCertificate(certificate: TableCertificate, trx?: TrxToken): Promise<number> {
699
+ const e = await this.validateEntityForInsert(certificate, trx, undefined, ['isDeleted'])
700
+ const fields = (e as any).fields
701
+ if (e.fields) delete (e as any).fields
702
+ if (e.certificateId === 0) delete (e as any).certificateId
703
+ const id = await this.sqlInsert('certificates', e, 'certificateId', trx)
704
+ certificate.certificateId = id
705
+ if (fields) {
706
+ for (const field of fields) {
707
+ field.certificateId = id
708
+ field.userId = certificate.userId
709
+ await this.insertCertificateField(field, trx)
710
+ }
711
+ }
712
+ return id
713
+ }
714
+
715
+ async insertCertificateField(certificateField: TableCertificateField, trx?: TrxToken): Promise<void> {
716
+ const e = await this.validateEntityForInsert(certificateField, trx)
717
+ await this.sqlInsert('certificate_fields', e, 'certificateId', trx)
718
+ }
719
+
720
+ async insertCommission(commission: TableCommission, trx?: TrxToken): Promise<number> {
721
+ const e = await this.validateEntityForInsert(commission, trx)
722
+ if (e.commissionId === 0) delete (e as any).commissionId
723
+ const id = await this.sqlInsert('commissions', e, 'commissionId', trx)
724
+ commission.commissionId = id
725
+ return id
726
+ }
727
+
728
+ async insertMonitorEvent(event: TableMonitorEvent, trx?: TrxToken): Promise<number> {
729
+ const e = await this.validateEntityForInsert(event, trx)
730
+ if (e.id === 0) delete (e as any).id
731
+ const id = await this.sqlInsert('monitor_events', e, 'id', trx)
732
+ event.id = id
733
+ return id
734
+ }
735
+
736
+ async insertOutput(output: TableOutput, trx?: TrxToken): Promise<number> {
737
+ const e = await this.validateEntityForInsert(output, trx)
738
+ if (e.outputId === 0) delete (e as any).outputId
739
+ const id = await this.sqlInsert('outputs', e, 'outputId', trx)
740
+ output.outputId = id
741
+ return id
742
+ }
743
+
744
+ async insertOutputBasket(basket: TableOutputBasket, trx?: TrxToken): Promise<number> {
745
+ const e = await this.validateEntityForInsert(basket, trx, undefined, ['isDeleted'])
746
+ if (e.basketId === 0) delete (e as any).basketId
747
+ const id = await this.sqlInsert('output_baskets', e, 'basketId', trx)
748
+ basket.basketId = id
749
+ return id
750
+ }
751
+
752
+ async insertOutputTag(tag: TableOutputTag, trx?: TrxToken): Promise<number> {
753
+ const e = await this.validateEntityForInsert(tag, trx, undefined, ['isDeleted'])
754
+ if (e.outputTagId === 0) delete (e as any).outputTagId
755
+ const id = await this.sqlInsert('output_tags', e, 'outputTagId', trx)
756
+ tag.outputTagId = id
757
+ return id
758
+ }
759
+
760
+ async insertOutputTagMap(tagMap: TableOutputTagMap, trx?: TrxToken): Promise<void> {
761
+ const e = await this.validateEntityForInsert(tagMap, trx, undefined, ['isDeleted'])
762
+ await this.sqlInsert('output_tags_map', e, 'outputTagId', trx)
763
+ }
764
+
765
+ async insertSyncState(syncState: TableSyncState, trx?: TrxToken): Promise<number> {
766
+ const e = await this.validateEntityForInsert(syncState, trx, ['when'], ['init'])
767
+ if (e.syncStateId === 0) delete (e as any).syncStateId
768
+ const id = await this.sqlInsert('sync_states', e, 'syncStateId', trx)
769
+ syncState.syncStateId = id
770
+ return id
771
+ }
772
+
773
+ async insertTransaction(tx: TableTransaction, trx?: TrxToken): Promise<number> {
774
+ const e = await this.validateEntityForInsert(tx, trx)
775
+ if (e.transactionId === 0) delete (e as any).transactionId
776
+ const id = await this.sqlInsert('transactions', e, 'transactionId', trx)
777
+ tx.transactionId = id
778
+ return id
779
+ }
780
+
781
+ async insertTxLabel(label: TableTxLabel, trx?: TrxToken): Promise<number> {
782
+ const e = await this.validateEntityForInsert(label, trx, undefined, ['isDeleted'])
783
+ if (e.txLabelId === 0) delete (e as any).txLabelId
784
+ const id = await this.sqlInsert('tx_labels', e, 'txLabelId', trx)
785
+ label.txLabelId = id
786
+ return id
787
+ }
788
+
789
+ async insertTxLabelMap(labelMap: TableTxLabelMap, trx?: TrxToken): Promise<void> {
790
+ const e = await this.validateEntityForInsert(labelMap, trx, undefined, ['isDeleted'])
791
+ await this.sqlInsert('tx_labels_map', e, 'txLabelId', trx)
792
+ }
793
+
794
+ // ============================================================================
795
+ // UPDATE methods (15)
796
+ // ============================================================================
797
+
798
+ async updateUser(id: number, update: Partial<TableUser>, trx?: TrxToken): Promise<number> {
799
+ const u = this.validatePartialForUpdate(update)
800
+ return await this.sqlUpdate('users', id, u as any, 'userId', trx)
801
+ }
802
+
803
+ async updateProvenTx(id: number, update: Partial<TableProvenTx>, trx?: TrxToken): Promise<number> {
804
+ const u = this.validatePartialForUpdate(update) as any
805
+ return await this.sqlUpdate('proven_txs', id, u, 'provenTxId', trx)
806
+ }
807
+
808
+ /**
809
+ * The single write path for proven_tx_reqs, and therefore the backstop for the
810
+ * history column: every note the toolbox's own broadcast providers produce
811
+ * arrives here, and they capture whole Extended Format payloads as hex.
812
+ */
813
+ async updateProvenTxReq(id: number | number[], update: Partial<TableProvenTxReq>, trx?: TrxToken): Promise<number> {
814
+ const u = this.validatePartialForUpdate(update) as any
815
+ if ('history' in u) u.history = scrubHistoryJson(u.history)
816
+ return await this.sqlUpdate('proven_tx_reqs', id, u, 'provenTxReqId', trx)
817
+ }
818
+
819
+ async updateCertificate(id: number, update: Partial<TableCertificate>, trx?: TrxToken): Promise<number> {
820
+ const u = this.validatePartialForUpdate(update, undefined, ['isDeleted'])
821
+ return await this.sqlUpdate('certificates', id, u as any, 'certificateId', trx)
822
+ }
823
+
824
+ async updateCertificateField(
825
+ certificateId: number,
826
+ fieldName: string,
827
+ update: Partial<TableCertificateField>,
828
+ trx?: TrxToken
829
+ ): Promise<number> {
830
+ const u = this.validatePartialForUpdate(update)
831
+ return await this.sqlUpdateComposite('certificate_fields', { certificateId, fieldName }, u as any, trx)
832
+ }
833
+
834
+ async updateCommission(id: number, update: Partial<TableCommission>, trx?: TrxToken): Promise<number> {
835
+ const u = this.validatePartialForUpdate(update)
836
+ return await this.sqlUpdate('commissions', id, u as any, 'commissionId', trx)
837
+ }
838
+
839
+ async updateMonitorEvent(id: number, update: Partial<TableMonitorEvent>, trx?: TrxToken): Promise<number> {
840
+ const u = this.validatePartialForUpdate(update)
841
+ return await this.sqlUpdate('monitor_events', id, u as any, 'id', trx)
842
+ }
843
+
844
+ async updateOutput(id: number, update: Partial<TableOutput>, trx?: TrxToken): Promise<number> {
845
+ const u = this.validatePartialForUpdate(update) as any
846
+ return await this.sqlUpdate('outputs', id, u, 'outputId', trx)
847
+ }
848
+
849
+ async updateOutputBasket(id: number, update: Partial<TableOutputBasket>, trx?: TrxToken): Promise<number> {
850
+ const u = this.validatePartialForUpdate(update, undefined, ['isDeleted'])
851
+ return await this.sqlUpdate('output_baskets', id, u as any, 'basketId', trx)
852
+ }
853
+
854
+ async updateOutputTag(id: number, update: Partial<TableOutputTag>, trx?: TrxToken): Promise<number> {
855
+ const u = this.validatePartialForUpdate(update, undefined, ['isDeleted'])
856
+ return await this.sqlUpdate('output_tags', id, u as any, 'outputTagId', trx)
857
+ }
858
+
859
+ async updateOutputTagMap(
860
+ outputId: number,
861
+ tagId: number,
862
+ update: Partial<TableOutputTagMap>,
863
+ trx?: TrxToken
864
+ ): Promise<number> {
865
+ const u = this.validatePartialForUpdate(update, undefined, ['isDeleted'])
866
+ return await this.sqlUpdateComposite('output_tags_map', { outputTagId: tagId, outputId }, u as any, trx)
867
+ }
868
+
869
+ async updateSyncState(id: number, update: Partial<TableSyncState>, trx?: TrxToken): Promise<number> {
870
+ const u = this.validatePartialForUpdate(update, ['when'], ['init'])
871
+ return await this.sqlUpdate('sync_states', id, u as any, 'syncStateId', trx)
872
+ }
873
+
874
+ async updateTransaction(id: number | number[], update: Partial<TableTransaction>, trx?: TrxToken): Promise<number> {
875
+ const u = this.validatePartialForUpdate(update) as any
876
+ return await this.sqlUpdate('transactions', id, u, 'transactionId', trx)
877
+ }
878
+
879
+ async updateTxLabel(id: number, update: Partial<TableTxLabel>, trx?: TrxToken): Promise<number> {
880
+ const u = this.validatePartialForUpdate(update, undefined, ['isDeleted'])
881
+ return await this.sqlUpdate('tx_labels', id, u as any, 'txLabelId', trx)
882
+ }
883
+
884
+ async updateTxLabelMap(
885
+ transactionId: number,
886
+ txLabelId: number,
887
+ update: Partial<TableTxLabelMap>,
888
+ trx?: TrxToken
889
+ ): Promise<number> {
890
+ const u = this.validatePartialForUpdate(update, undefined, ['isDeleted'])
891
+ return await this.sqlUpdateComposite('tx_labels_map', { txLabelId, transactionId }, u as any, trx)
892
+ }
893
+
894
+ // ============================================================================
895
+ // FIND methods (StorageReader: 11, StorageReaderWriter: 4 = 15)
896
+ // ============================================================================
897
+
898
+ async findUsers(args: FindUsersArgs): Promise<TableUser[]> {
899
+ const rows = await this.sqlFind<any>('users', args, 'userId')
900
+ return this.validateEntities(rows)
901
+ }
902
+
903
+ async findCertificateFields(args: FindCertificateFieldsArgs): Promise<TableCertificateField[]> {
904
+ const rows = await this.sqlFind<any>('certificate_fields', args, 'certificateId')
905
+ return this.validateEntities(rows)
906
+ }
907
+
908
+ async findCertificates(args: FindCertificatesArgs): Promise<TableCertificateX[]> {
909
+ // Handle extra filters: certifiers, types
910
+ const partial = { ...args.partial } as any
911
+ // Remove certifiers/types from partial - we handle them as extra clauses
912
+ const extraConditions: string[] = []
913
+ const extraParams: any[] = []
914
+ if (args.certifiers && args.certifiers.length > 0) {
915
+ extraConditions.push(`certifier IN (${args.certifiers.map(() => '?').join(',')})`)
916
+ extraParams.push(...args.certifiers)
917
+ }
918
+ if (args.types && args.types.length > 0) {
919
+ extraConditions.push(`type IN (${args.types.map(() => '?').join(',')})`)
920
+ extraParams.push(...args.types)
921
+ }
922
+ const rows = await this.sqlFind<any>(
923
+ 'certificates',
924
+ { ...args, partial },
925
+ 'certificateId',
926
+ extraConditions.length > 0 ? { conditions: extraConditions, params: extraParams } : undefined
927
+ )
928
+ const results = this.validateEntities(rows, undefined, ['isDeleted'])
929
+ if (args.includeFields) {
930
+ for (const c of results) {
931
+ const fields = await this.findCertificateFields({ partial: { certificateId: c.certificateId }, trx: args.trx })
932
+ ;(c as any).fields = fields
933
+ }
934
+ }
935
+ return results as TableCertificateX[]
936
+ }
937
+
938
+ async findCommissions(args: FindCommissionsArgs): Promise<TableCommission[]> {
939
+ if ((args.partial as any).lockingScript) {
940
+ throw new Error('Commissions may not be found by lockingScript value.')
941
+ }
942
+ const rows = await this.sqlFind<any>('commissions', args, 'commissionId')
943
+ return this.validateEntities(rows)
944
+ }
945
+
946
+ async findMonitorEvents(args: FindMonitorEventsArgs): Promise<TableMonitorEvent[]> {
947
+ const rows = await this.sqlFind<any>('monitor_events', args, 'id')
948
+ return this.validateEntities(rows)
949
+ }
950
+
951
+ async findOutputBaskets(args: FindOutputBasketsArgs): Promise<TableOutputBasket[]> {
952
+ const rows = await this.sqlFind<any>('output_baskets', args, 'basketId')
953
+ return this.validateEntities(rows, undefined, ['isDeleted'])
954
+ }
955
+
956
+ /** The txStatus and tag filters shared by every outputs query — one
957
+ * definition so a find, a count and a sum can never drift apart. */
958
+ private outputExtraClauses(
959
+ args: FindOutputsArgs,
960
+ tagIds?: number[],
961
+ isQueryModeAll?: boolean
962
+ ): { conditions: string[]; params: any[] } | undefined {
963
+ const extraConditions: string[] = []
964
+ const extraParams: any[] = []
965
+
966
+ // Handle txStatus filter via subquery
967
+ if (args.txStatus && args.txStatus.length > 0) {
968
+ const placeholders = args.txStatus.map(() => '?').join(',')
969
+ extraConditions.push(
970
+ `transactionId IN (SELECT transactionId FROM transactions WHERE status IN (${placeholders}))`
971
+ )
972
+ extraParams.push(...args.txStatus)
973
+ }
974
+
975
+ // Handle tagIds filter
976
+ if (tagIds && tagIds.length > 0) {
977
+ const tagPlaceholders = tagIds.map(() => '?').join(',')
978
+ if (isQueryModeAll) {
979
+ // Must have ALL tags
980
+ extraConditions.push(`outputId IN (
981
+ SELECT outputId FROM output_tags_map
982
+ WHERE outputTagId IN (${tagPlaceholders}) AND isDeleted = 0
983
+ GROUP BY outputId HAVING COUNT(DISTINCT outputTagId) = ${tagIds.length}
984
+ )`)
985
+ } else {
986
+ // Must have ANY tag
987
+ extraConditions.push(`outputId IN (
988
+ SELECT outputId FROM output_tags_map
989
+ WHERE outputTagId IN (${tagPlaceholders}) AND isDeleted = 0
990
+ )`)
991
+ }
992
+ extraParams.push(...tagIds)
993
+ }
994
+
995
+ return extraConditions.length > 0 ? { conditions: extraConditions, params: extraParams } : undefined
996
+ }
997
+
998
+ async findOutputs(args: FindOutputsArgs, tagIds?: number[], isQueryModeAll?: boolean): Promise<TableOutput[]> {
999
+ if ((args.partial as any).lockingScript) {
1000
+ throw new Error('Outputs may not be found by lockingScript value.')
1001
+ }
1002
+ const partial = { ...args.partial } as any
1003
+
1004
+ // `noScript` callers throw the script away the moment it arrives, so do not
1005
+ // fetch it at all: `SELECT *` would copy every matching output's
1006
+ // lockingScript out of SQLite and across the bridge into JS — on the JS
1007
+ // thread — only to be discarded below, which adds up across a page of them.
1008
+ const columns = args.noScript
1009
+ ? (await this.tableColumns('outputs')).filter(c => c !== 'lockingScript')
1010
+ : undefined
1011
+
1012
+ const rows = await this.sqlFind<any>(
1013
+ 'outputs',
1014
+ { ...args, partial },
1015
+ 'outputId',
1016
+ this.outputExtraClauses(args, tagIds, isQueryModeAll),
1017
+ // noScript callers get a projection that never reads the column. The
1018
+ // post-hoc `o.lockingScript = undefined` below stays as the contract for
1019
+ // any future caller that reaches here without the projection.
1020
+ columns
1021
+ )
1022
+
1023
+ const results = this.validateEntities(rows, undefined, ['spendable', 'change'])
1024
+
1025
+ for (const o of results) {
1026
+ if (!args.noScript) {
1027
+ await this.validateOutputScript(o, args.trx)
1028
+ } else {
1029
+ o.lockingScript = undefined
1030
+ }
1031
+ }
1032
+ return results
1033
+ }
1034
+
1035
+ /**
1036
+ * Count and total the satoshis of the outputs a findOutputs with these same
1037
+ * args would return, without materialising a single row.
1038
+ *
1039
+ * This is the wallet balance: summing it in SQLite rather than pulling every
1040
+ * output into JS is the difference between one number crossing the bridge and
1041
+ * a few hundred full rows crossing it.
1042
+ */
1043
+ async sumOutputSatoshis(
1044
+ args: FindOutputsArgs,
1045
+ tagIds?: number[],
1046
+ isQueryModeAll?: boolean
1047
+ ): Promise<{ count: number; total: number }> {
1048
+ return await this.sqlSum(
1049
+ 'outputs',
1050
+ 'satoshis',
1051
+ args as any,
1052
+ this.outputExtraClauses(args, tagIds, isQueryModeAll)
1053
+ )
1054
+ }
1055
+
1056
+ async findOutputTags(args: FindOutputTagsArgs): Promise<TableOutputTag[]> {
1057
+ const rows = await this.sqlFind<any>('output_tags', args, 'outputTagId')
1058
+ return this.validateEntities(rows, undefined, ['isDeleted'])
1059
+ }
1060
+
1061
+ async findSyncStates(args: FindSyncStatesArgs): Promise<TableSyncState[]> {
1062
+ if ((args.partial as any).syncMap) {
1063
+ throw new Error('SyncStates may not be found by syncMap value.')
1064
+ }
1065
+ const rows = await this.sqlFind<any>('sync_states', args, 'syncStateId')
1066
+ return this.validateEntities(rows, ['when'], ['init'])
1067
+ }
1068
+
1069
+ async findTransactions(
1070
+ args: FindTransactionsArgs,
1071
+ labelIds?: number[],
1072
+ isQueryModeAll?: boolean
1073
+ ): Promise<TableTransaction[]> {
1074
+ if ((args.partial as any).rawTx) throw new Error('Transactions may not be found by rawTx value.')
1075
+ if ((args.partial as any).inputBEEF) throw new Error('Transactions may not be found by inputBEEF value.')
1076
+
1077
+ const extraConditions: string[] = []
1078
+ const extraParams: any[] = []
1079
+
1080
+ // Status filter (array of statuses)
1081
+ if (args.status && args.status.length > 0) {
1082
+ extraConditions.push(`status IN (${args.status.map(() => '?').join(',')})`)
1083
+ extraParams.push(...args.status)
1084
+ // Remove status from partial if also in status array
1085
+ if ((args.partial as any).status) delete (args.partial as any).status
1086
+ }
1087
+
1088
+ // Date range
1089
+ if (args.from) {
1090
+ extraConditions.push('created_at >= ?')
1091
+ extraParams.push(this.validateDateForWhere(args.from))
1092
+ }
1093
+ if (args.to) {
1094
+ extraConditions.push('created_at < ?')
1095
+ extraParams.push(this.validateDateForWhere(args.to))
1096
+ }
1097
+
1098
+ // Label filtering
1099
+ if (labelIds && labelIds.length > 0) {
1100
+ const labelPlaceholders = labelIds.map(() => '?').join(',')
1101
+ if (isQueryModeAll) {
1102
+ extraConditions.push(`transactionId IN (
1103
+ SELECT transactionId FROM tx_labels_map
1104
+ WHERE txLabelId IN (${labelPlaceholders}) AND isDeleted = 0
1105
+ GROUP BY transactionId HAVING COUNT(DISTINCT txLabelId) = ${labelIds.length}
1106
+ )`)
1107
+ } else {
1108
+ extraConditions.push(`transactionId IN (
1109
+ SELECT transactionId FROM tx_labels_map
1110
+ WHERE txLabelId IN (${labelPlaceholders}) AND isDeleted = 0
1111
+ )`)
1112
+ }
1113
+ extraParams.push(...labelIds)
1114
+ }
1115
+
1116
+ const rows = await this.sqlFind<any>(
1117
+ 'transactions',
1118
+ args,
1119
+ 'transactionId',
1120
+ extraConditions.length > 0 ? { conditions: extraConditions, params: extraParams } : undefined,
1121
+ args.noRawTx ? columnsExcluding('transactions', ['rawTx', 'inputBEEF']) : undefined
1122
+ )
1123
+
1124
+ const results = this.validateEntities(rows, undefined, ['isOutgoing'])
1125
+
1126
+ for (const t of results) {
1127
+ if (!args.noRawTx) {
1128
+ await this.validateRawTransaction(t, args.trx)
1129
+ } else {
1130
+ t.rawTx = undefined
1131
+ t.inputBEEF = undefined
1132
+ }
1133
+ }
1134
+ return results
1135
+ }
1136
+
1137
+ async findTxLabels(args: FindTxLabelsArgs): Promise<TableTxLabel[]> {
1138
+ const rows = await this.sqlFind<any>('tx_labels', args, 'txLabelId')
1139
+ return this.validateEntities(rows, undefined, ['isDeleted'])
1140
+ }
1141
+
1142
+ // StorageReaderWriter find methods
1143
+ async findOutputTagMaps(args: FindOutputTagMapsArgs): Promise<TableOutputTagMap[]> {
1144
+ const extraConditions: string[] = []
1145
+ const extraParams: any[] = []
1146
+ if (args.tagIds && args.tagIds.length > 0) {
1147
+ extraConditions.push(`outputTagId IN (${args.tagIds.map(() => '?').join(',')})`)
1148
+ extraParams.push(...args.tagIds)
1149
+ }
1150
+ const rows = await this.sqlFind<any>(
1151
+ 'output_tags_map',
1152
+ args,
1153
+ 'outputTagId',
1154
+ extraConditions.length > 0 ? { conditions: extraConditions, params: extraParams } : undefined
1155
+ )
1156
+ return this.validateEntities(rows, undefined, ['isDeleted'])
1157
+ }
1158
+
1159
+ async findProvenTxReqs(args: FindProvenTxReqsArgs): Promise<TableProvenTxReq[]> {
1160
+ if ((args.partial as any).rawTx) throw new Error('ProvenTxReqs may not be found by rawTx value.')
1161
+ if ((args.partial as any).inputBEEF) throw new Error('ProvenTxReqs may not be found by inputBEEF value.')
1162
+ const extraConditions: string[] = []
1163
+ const extraParams: any[] = []
1164
+ if (args.status && args.status.length > 0) {
1165
+ extraConditions.push(`status IN (${args.status.map(() => '?').join(',')})`)
1166
+ extraParams.push(...args.status)
1167
+ if ((args.partial as any).status) delete (args.partial as any).status
1168
+ }
1169
+ if (args.txids && args.txids.length > 0) {
1170
+ extraConditions.push(`txid IN (${args.txids.map(() => '?').join(',')})`)
1171
+ extraParams.push(...args.txids)
1172
+ }
1173
+ const rows = await this.sqlFind<any>(
1174
+ 'proven_tx_reqs',
1175
+ args,
1176
+ 'provenTxReqId',
1177
+ extraConditions.length > 0 ? { conditions: extraConditions, params: extraParams } : undefined
1178
+ )
1179
+ const reqs = this.validateEntities(rows, undefined, ['notified', 'wasBroadcast'])
1180
+ return reqs
1181
+ }
1182
+
1183
+ async findProvenTxs(args: FindProvenTxsArgs): Promise<TableProvenTx[]> {
1184
+ if ((args.partial as any).rawTx) throw new Error('ProvenTxs may not be found by rawTx value.')
1185
+ if ((args.partial as any).merklePath) throw new Error('ProvenTxs may not be found by merklePath value.')
1186
+ const rows = await this.sqlFind<any>('proven_txs', args, 'provenTxId')
1187
+ const proven = this.validateEntities(rows)
1188
+ return proven
1189
+ }
1190
+
1191
+ async findTxLabelMaps(args: FindTxLabelMapsArgs): Promise<TableTxLabelMap[]> {
1192
+ const extraConditions: string[] = []
1193
+ const extraParams: any[] = []
1194
+ if (args.labelIds && args.labelIds.length > 0) {
1195
+ extraConditions.push(`txLabelId IN (${args.labelIds.map(() => '?').join(',')})`)
1196
+ extraParams.push(...args.labelIds)
1197
+ }
1198
+ const rows = await this.sqlFind<any>(
1199
+ 'tx_labels_map',
1200
+ args,
1201
+ 'txLabelId',
1202
+ extraConditions.length > 0 ? { conditions: extraConditions, params: extraParams } : undefined
1203
+ )
1204
+ return this.validateEntities(rows, undefined, ['isDeleted'])
1205
+ }
1206
+
1207
+ // ============================================================================
1208
+ // COUNT methods (StorageReader: 11, StorageReaderWriter: 4 = 15)
1209
+ // ============================================================================
1210
+
1211
+ async countUsers(args: FindUsersArgs): Promise<number> {
1212
+ return this.sqlCount('users', args)
1213
+ }
1214
+ async countCertificateFields(args: FindCertificateFieldsArgs): Promise<number> {
1215
+ return this.sqlCount('certificate_fields', args)
1216
+ }
1217
+
1218
+ async countCertificates(args: FindCertificatesArgs): Promise<number> {
1219
+ const extraConditions: string[] = []
1220
+ const extraParams: any[] = []
1221
+ if (args.certifiers && args.certifiers.length > 0) {
1222
+ extraConditions.push(`certifier IN (${args.certifiers.map(() => '?').join(',')})`)
1223
+ extraParams.push(...args.certifiers)
1224
+ }
1225
+ if (args.types && args.types.length > 0) {
1226
+ extraConditions.push(`type IN (${args.types.map(() => '?').join(',')})`)
1227
+ extraParams.push(...args.types)
1228
+ }
1229
+ return this.sqlCount(
1230
+ 'certificates',
1231
+ args,
1232
+ extraConditions.length > 0 ? { conditions: extraConditions, params: extraParams } : undefined
1233
+ )
1234
+ }
1235
+
1236
+ async countCommissions(args: FindCommissionsArgs): Promise<number> {
1237
+ return this.sqlCount('commissions', args)
1238
+ }
1239
+ async countMonitorEvents(args: FindMonitorEventsArgs): Promise<number> {
1240
+ return this.sqlCount('monitor_events', args)
1241
+ }
1242
+ async countOutputBaskets(args: FindOutputBasketsArgs): Promise<number> {
1243
+ return this.sqlCount('output_baskets', args)
1244
+ }
1245
+
1246
+ async countOutputs(args: FindOutputsArgs, tagIds?: number[], isQueryModeAll?: boolean): Promise<number> {
1247
+ return this.sqlCount('outputs', args, this.outputExtraClauses(args, tagIds, isQueryModeAll))
1248
+ }
1249
+
1250
+ async countOutputTags(args: FindOutputTagsArgs): Promise<number> {
1251
+ return this.sqlCount('output_tags', args)
1252
+ }
1253
+ async countSyncStates(args: FindSyncStatesArgs): Promise<number> {
1254
+ return this.sqlCount('sync_states', args)
1255
+ }
1256
+
1257
+ async countTransactions(args: FindTransactionsArgs, labelIds?: number[], isQueryModeAll?: boolean): Promise<number> {
1258
+ const extraConditions: string[] = []
1259
+ const extraParams: any[] = []
1260
+ if (args.status && args.status.length > 0) {
1261
+ extraConditions.push(`status IN (${args.status.map(() => '?').join(',')})`)
1262
+ extraParams.push(...args.status)
1263
+ if ((args.partial as any).status) delete (args.partial as any).status
1264
+ }
1265
+ if (args.from) {
1266
+ extraConditions.push('created_at >= ?')
1267
+ extraParams.push(this.validateDateForWhere(args.from))
1268
+ }
1269
+ if (args.to) {
1270
+ extraConditions.push('created_at < ?')
1271
+ extraParams.push(this.validateDateForWhere(args.to))
1272
+ }
1273
+ if (labelIds && labelIds.length > 0) {
1274
+ const labelPlaceholders = labelIds.map(() => '?').join(',')
1275
+ if (isQueryModeAll) {
1276
+ extraConditions.push(`transactionId IN (
1277
+ SELECT transactionId FROM tx_labels_map WHERE txLabelId IN (${labelPlaceholders}) AND isDeleted = 0
1278
+ GROUP BY transactionId HAVING COUNT(DISTINCT txLabelId) = ${labelIds.length}
1279
+ )`)
1280
+ } else {
1281
+ extraConditions.push(`transactionId IN (
1282
+ SELECT transactionId FROM tx_labels_map WHERE txLabelId IN (${labelPlaceholders}) AND isDeleted = 0
1283
+ )`)
1284
+ }
1285
+ extraParams.push(...labelIds)
1286
+ }
1287
+ return this.sqlCount(
1288
+ 'transactions',
1289
+ args,
1290
+ extraConditions.length > 0 ? { conditions: extraConditions, params: extraParams } : undefined
1291
+ )
1292
+ }
1293
+
1294
+ async countTxLabels(args: FindTxLabelsArgs): Promise<number> {
1295
+ return this.sqlCount('tx_labels', args)
1296
+ }
1297
+
1298
+ // StorageReaderWriter count methods
1299
+ async countOutputTagMaps(args: FindOutputTagMapsArgs): Promise<number> {
1300
+ const extraConditions: string[] = []
1301
+ const extraParams: any[] = []
1302
+ if (args.tagIds && args.tagIds.length > 0) {
1303
+ extraConditions.push(`outputTagId IN (${args.tagIds.map(() => '?').join(',')})`)
1304
+ extraParams.push(...args.tagIds)
1305
+ }
1306
+ return this.sqlCount(
1307
+ 'output_tags_map',
1308
+ args,
1309
+ extraConditions.length > 0 ? { conditions: extraConditions, params: extraParams } : undefined
1310
+ )
1311
+ }
1312
+
1313
+ async countProvenTxReqs(args: FindProvenTxReqsArgs): Promise<number> {
1314
+ const extraConditions: string[] = []
1315
+ const extraParams: any[] = []
1316
+ if (args.status && args.status.length > 0) {
1317
+ extraConditions.push(`status IN (${args.status.map(() => '?').join(',')})`)
1318
+ extraParams.push(...args.status)
1319
+ }
1320
+ if (args.txids && args.txids.length > 0) {
1321
+ extraConditions.push(`txid IN (${args.txids.map(() => '?').join(',')})`)
1322
+ extraParams.push(...args.txids)
1323
+ }
1324
+ return this.sqlCount(
1325
+ 'proven_tx_reqs',
1326
+ args,
1327
+ extraConditions.length > 0 ? { conditions: extraConditions, params: extraParams } : undefined
1328
+ )
1329
+ }
1330
+
1331
+ async countProvenTxs(args: FindProvenTxsArgs): Promise<number> {
1332
+ return this.sqlCount('proven_txs', args)
1333
+ }
1334
+
1335
+ async countTxLabelMaps(args: FindTxLabelMapsArgs): Promise<number> {
1336
+ const extraConditions: string[] = []
1337
+ const extraParams: any[] = []
1338
+ if (args.labelIds && args.labelIds.length > 0) {
1339
+ extraConditions.push(`txLabelId IN (${args.labelIds.map(() => '?').join(',')})`)
1340
+ extraParams.push(...args.labelIds)
1341
+ }
1342
+ return this.sqlCount(
1343
+ 'tx_labels_map',
1344
+ args,
1345
+ extraConditions.length > 0 ? { conditions: extraConditions, params: extraParams } : undefined
1346
+ )
1347
+ }
1348
+
1349
+ // ============================================================================
1350
+ // getForUser methods (4)
1351
+ // ============================================================================
1352
+
1353
+ /**
1354
+ * Own SQL rather than a call through findProvenTxs, so this and
1355
+ * getProvenTxReqsForUser below can join straight on userId. Both are what
1356
+ * getSyncChunk reads to build a backup chunk.
1357
+ */
1358
+ async getProvenTxsForUser(args: FindForUserSincePagedArgs): Promise<TableProvenTx[]> {
1359
+ const db = this.getDB()
1360
+ let query = `SELECT pt.* FROM proven_txs pt
1361
+ WHERE EXISTS (SELECT 1 FROM transactions t WHERE t.provenTxId = pt.provenTxId AND t.userId = ?)`
1362
+ const params: any[] = [args.userId]
1363
+ if (args.since) {
1364
+ query += ' AND pt.updated_at >= ?'
1365
+ params.push(this.validateDateForWhere(args.since))
1366
+ }
1367
+ query += ' ORDER BY pt.provenTxId ASC'
1368
+ if (args.paged?.limit) {
1369
+ query += ` LIMIT ${args.paged.limit}`
1370
+ if (args.paged.offset) query += ` OFFSET ${args.paged.offset}`
1371
+ }
1372
+ const rows = (await db.getAllAsync(query, params)) as any[]
1373
+ return this.validateEntities(rows)
1374
+ }
1375
+
1376
+ async getProvenTxReqsForUser(args: FindForUserSincePagedArgs): Promise<TableProvenTxReq[]> {
1377
+ const db = this.getDB()
1378
+ let query = `SELECT ptr.* FROM proven_tx_reqs ptr
1379
+ WHERE EXISTS (SELECT 1 FROM transactions t WHERE t.txid = ptr.txid AND t.userId = ?)`
1380
+ const params: any[] = [args.userId]
1381
+ if (args.since) {
1382
+ query += ' AND ptr.updated_at >= ?'
1383
+ params.push(this.validateDateForWhere(args.since))
1384
+ }
1385
+ query += ' ORDER BY ptr.provenTxReqId ASC'
1386
+ if (args.paged?.limit) {
1387
+ query += ` LIMIT ${args.paged.limit}`
1388
+ if (args.paged.offset) query += ` OFFSET ${args.paged.offset}`
1389
+ }
1390
+ const rows = (await db.getAllAsync(query, params)) as any[]
1391
+ return this.validateEntities(rows, undefined, ['notified', 'wasBroadcast'])
1392
+ }
1393
+
1394
+ async getTxLabelMapsForUser(args: FindForUserSincePagedArgs): Promise<TableTxLabelMap[]> {
1395
+ const db = this.getDB()
1396
+ let query = `SELECT tlm.* FROM tx_labels_map tlm
1397
+ WHERE EXISTS (SELECT 1 FROM tx_labels tl WHERE tl.txLabelId = tlm.txLabelId AND tl.userId = ?)`
1398
+ const params: any[] = [args.userId]
1399
+ if (args.since) {
1400
+ query += ' AND tlm.updated_at >= ?'
1401
+ params.push(this.validateDateForWhere(args.since))
1402
+ }
1403
+ query += ' ORDER BY tlm.txLabelId ASC'
1404
+ if (args.paged?.limit) {
1405
+ query += ` LIMIT ${args.paged.limit}`
1406
+ if (args.paged.offset) query += ` OFFSET ${args.paged.offset}`
1407
+ }
1408
+ const rows = (await db.getAllAsync(query, params)) as any[]
1409
+ return this.validateEntities(rows, undefined, ['isDeleted'])
1410
+ }
1411
+
1412
+ async getOutputTagMapsForUser(args: FindForUserSincePagedArgs): Promise<TableOutputTagMap[]> {
1413
+ const db = this.getDB()
1414
+ let query = `SELECT otm.* FROM output_tags_map otm
1415
+ WHERE EXISTS (SELECT 1 FROM output_tags ot WHERE ot.outputTagId = otm.outputTagId AND ot.userId = ?)`
1416
+ const params: any[] = [args.userId]
1417
+ if (args.since) {
1418
+ query += ' AND otm.updated_at >= ?'
1419
+ params.push(this.validateDateForWhere(args.since))
1420
+ }
1421
+ query += ' ORDER BY otm.outputTagId ASC'
1422
+ if (args.paged?.limit) {
1423
+ query += ` LIMIT ${args.paged.limit}`
1424
+ if (args.paged.offset) query += ` OFFSET ${args.paged.offset}`
1425
+ }
1426
+ const rows = (await db.getAllAsync(query, params)) as any[]
1427
+ return this.validateEntities(rows, undefined, ['isDeleted'])
1428
+ }
1429
+
1430
+ // ============================================================================
1431
+ // StorageProvider abstract methods
1432
+ // ============================================================================
1433
+
1434
+ // Auth delegations
1435
+ async findCertificatesAuth(auth: AuthId, args: FindCertificatesArgs): Promise<TableCertificateX[]> {
1436
+ if (!auth.userId || (args.partial.userId && args.partial.userId !== auth.userId))
1437
+ throw new Error('WERR_UNAUTHORIZED')
1438
+ args.partial.userId = auth.userId
1439
+ return await this.findCertificates(args)
1440
+ }
1441
+
1442
+ async findOutputBasketsAuth(auth: AuthId, args: FindOutputBasketsArgs): Promise<TableOutputBasket[]> {
1443
+ if (!auth.userId || (args.partial.userId && args.partial.userId !== auth.userId))
1444
+ throw new Error('WERR_UNAUTHORIZED')
1445
+ args.partial.userId = auth.userId
1446
+ return await this.findOutputBaskets(args)
1447
+ }
1448
+
1449
+ async findOutputsAuth(auth: AuthId, args: FindOutputsArgs): Promise<TableOutput[]> {
1450
+ if (!auth.userId || (args.partial.userId && args.partial.userId !== auth.userId))
1451
+ throw new Error('WERR_UNAUTHORIZED')
1452
+ args.partial.userId = auth.userId
1453
+ return await this.findOutputs(args)
1454
+ }
1455
+
1456
+ async insertCertificateAuth(auth: AuthId, certificate: TableCertificateX): Promise<number> {
1457
+ if (!auth.userId || (certificate.userId && certificate.userId !== auth.userId)) throw new Error('WERR_UNAUTHORIZED')
1458
+ certificate.userId = auth.userId
1459
+ return await this.insertCertificate(certificate)
1460
+ }
1461
+
1462
+ // Data retrieval
1463
+ /**
1464
+ * Every identity-deriving and BEEF-assembling consumer in the toolbox reaches
1465
+ * bytes through here, including three that bypass the find* hooks entirely.
1466
+ */
1467
+ async getProvenOrRawTx(txid: string, trx?: TrxToken): Promise<ProvenOrRawTx> {
1468
+ const r: ProvenOrRawTx = { proven: undefined, rawTx: undefined, inputBEEF: undefined }
1469
+ const provenResults = await this.findProvenTxs({ partial: { txid }, trx })
1470
+ r.proven = provenResults.length === 1 ? provenResults[0] : undefined
1471
+ if (!r.proven) {
1472
+ const reqResults = await this.findProvenTxReqs({ partial: { txid }, trx })
1473
+ const req: any = reqResults.length === 1 ? reqResults[0] : undefined
1474
+ if (req && ['unsent', 'unmined', 'unconfirmed', 'sending', 'nosend', 'completed'].includes(req.status)) {
1475
+ r.rawTx = req.rawTx
1476
+ r.inputBEEF = req.inputBEEF
1477
+ }
1478
+ }
1479
+ return r
1480
+ }
1481
+
1482
+ /**
1483
+ * txid -> height for every proven transaction.
1484
+ *
1485
+ * The CSV export used findProvenTxs({ partial: {} }) for this: an unbounded
1486
+ * SELECT * that reads and Array.from-expands every rawTx and merklePath in the
1487
+ * wallet to build a map of two small columns. On a wallet with vault history
1488
+ * that is hundreds of megabytes of transient heap.
1489
+ */
1490
+ /**
1491
+ * The transactions reserving the given outpoints, by `reference`.
1492
+ *
1493
+ * Answers in one indexed query (outputs.spentBy is indexed) what the vault's
1494
+ * reservation heal previously answered by paging up to 5,000 actions with
1495
+ * includeInputs — where listActionsSql loads each action's full rawTx and runs
1496
+ * Transaction.fromBinary on it just to read a sequence number.
1497
+ *
1498
+ * `reference`, not `txid`: the reservation being healed belongs to an attempt
1499
+ * that died before signing, so it has no txid. abortAction takes a reference.
1500
+ */
1501
+ async findSpendingReferences(outpoints: string[]): Promise<{ reference: string; status: string }[]> {
1502
+ if (outpoints.length === 0) return []
1503
+ if (!this.isAvailable()) await this.makeAvailable()
1504
+ const pairs = outpoints.map(splitOutpoint).filter((p): p is { txid: string; vout: number } => p !== null)
1505
+ if (pairs.length === 0) return []
1506
+ const params = pairs.flatMap(p => [p.txid, p.vout])
1507
+ const rows = (await this.getDB().getAllAsync(spendingReferencesSql(pairs.length), params)) as {
1508
+ reference?: string
1509
+ status?: string
1510
+ }[]
1511
+ return rows
1512
+ .filter(r => typeof r.reference === 'string' && typeof r.status === 'string')
1513
+ .map(r => ({ reference: r.reference as string, status: r.status as string }))
1514
+ }
1515
+
1516
+ /**
1517
+ * Release every input a definitively-invalid vault deposit tx2 still holds.
1518
+ * Returns how many outputs were made spendable again.
1519
+ *
1520
+ * The shape being healed (production, 2026-08-21): tx2 was rejected by every
1521
+ * broadcaster (proven_tx_reqs.status = 'invalid', transactions.status =
1522
+ * 'failed'), the toolbox's own release of its inputs was then OVERRIDDEN by
1523
+ * markStaleInputsAsSpent — which asked the indexers about tx1's staging
1524
+ * output seconds after tx1 broadcast, and indexer lag said "not a UTXO" —
1525
+ * and abortAction cannot help because 'failed' is in its unAbortable list.
1526
+ * The staging coin (and any change the toolbox pulled in as extra funding)
1527
+ * sits spendable=0 forever while it is live on chain.
1528
+ *
1529
+ * The predicate is deliberately narrow, every clause load-bearing:
1530
+ * - spentBy transaction has status 'failed' AND its proven_tx_req is
1531
+ * 'invalid' — the network REJECTED the spender outright; it can never be
1532
+ * mined, so releasing its inputs cannot enable a real double-spend. A
1533
+ * 'failed' tx without an 'invalid' req (e.g. a broadcast that timed out
1534
+ * but may have propagated) is NOT touched.
1535
+ * - the spender carries the 'vault-deposit' label — this heal exists for
1536
+ * the deposit flow and must not reinterpret failures of anything else.
1537
+ */
1538
+ async releaseVaultStagingStrandedByInvalidTx(): Promise<number> {
1539
+ if (!this.isAvailable()) await this.makeAvailable()
1540
+ const r = await this.getDB().runAsync(RELEASE_STRANDED_VAULT_STAGING_SQL, [])
1541
+ // The other arm: coins already spendable=1 but with a stale spentBy still
1542
+ // naming the failed spender (updateOutput's spentBy: undefined is dropped
1543
+ // by sqlUpdate). createAction refuses those with WERR_REVIEW_ACTIONS, so
1544
+ // they are just as stuck as the spendable=0 arm until cleared.
1545
+ const r2 = await this.getDB().runAsync(RELEASE_STALE_VAULT_STAGING_SPENTBY_SQL, [])
1546
+ const released = (r?.changes ?? 0) + (r2?.changes ?? 0)
1547
+ if (released > 0) console.log('[vault] released %d output(s) stranded by invalid deposit tx', released)
1548
+ return released
1549
+ }
1550
+
1551
+ /** Size of the database file on disk, or null when it cannot be read. */
1552
+ async databaseFileBytes(): Promise<number | null> {
1553
+ try {
1554
+ const path = (this.db as unknown as { databasePath?: string })?.databasePath
1555
+ if (!path) return null
1556
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
1557
+ const { File } = require('expo-file-system') as typeof import('expo-file-system')
1558
+ const size = new File(path).size
1559
+ // Deliberately NOT gated on .exists: the Android exists getter is
1560
+ // permission-gated while size is not. A zero is treated as unknown rather
1561
+ // than as an empty database.
1562
+ return typeof size === 'number' && size > 0 ? size : null
1563
+ } catch {
1564
+ return null
1565
+ }
1566
+ }
1567
+
1568
+ /**
1569
+ * What could be reclaimed, and what is being held back.
1570
+ *
1571
+ * Read-only by design: this ships before anything destructive so the decision
1572
+ * can be made from real device numbers. See storage/methods/reclaim.ts for why
1573
+ * row deletion is not on offer at all.
1574
+ */
1575
+ async reclaimReport(tipHeight: number, cutoff: string): Promise<ReclaimReport> {
1576
+ if (!this.isAvailable()) await this.makeAvailable()
1577
+ const db = this.getDB()
1578
+
1579
+ const perTable = (await db.getAllAsync(RECLAIM_SIZES_SQL)) as {
1580
+ table: string
1581
+ rows: number
1582
+ blobBytes: number
1583
+ }[]
1584
+ const candidates = (await db.getAllAsync(RECLAIM_CANDIDATES_SQL, [tipHeight, cutoff])) as { bytes: number }[]
1585
+ const excluded = (await db.getAllAsync(RECLAIM_EXCLUDED_SQL, [tipHeight, tipHeight, cutoff])) as {
1586
+ reason: string
1587
+ rows: number
1588
+ bytes: number
1589
+ }[]
1590
+
1591
+ return {
1592
+ dbBytes: await this.databaseFileBytes(),
1593
+ freeBytes: availableDiskBytes(),
1594
+ perTable,
1595
+ reclaimable: {
1596
+ rows: candidates.length,
1597
+ bytes: candidates.reduce((sum, c) => sum + (c.bytes ?? 0), 0)
1598
+ },
1599
+ excluded
1600
+ }
1601
+ }
1602
+
1603
+ /**
1604
+ * Null transactions.inputBEEF for settled transactions.
1605
+ *
1606
+ * The one destructive operation here, and the only blob whose clearing is both
1607
+ * safe and effective — nothing reads this column for BEEF. Raw SQL because
1608
+ * updateTransaction cannot write NULL: sqlUpdate skips undefined values, so an
1609
+ * update meaning "clear this" is silently dropped.
1610
+ *
1611
+ * Not wired to the low-disk trigger: on a nearly full volume this UPDATE's own
1612
+ * rollback journal can fail with SQLITE_FULL, and with no WAL and no
1613
+ * auto_vacuum the file does not shrink afterwards.
1614
+ */
1615
+ async reclaimInputBeef(tipHeight: number, cutoff: string): Promise<{ rows: number }> {
1616
+ if (!this.isAvailable()) await this.makeAvailable()
1617
+ const result = await this.getDB().runAsync(RECLAIM_INPUT_BEEF_SQL, [
1618
+ new Date().toISOString(),
1619
+ tipHeight,
1620
+ cutoff
1621
+ ])
1622
+ return { rows: result.changes ?? 0 }
1623
+ }
1624
+
1625
+ /**
1626
+ * Transactions no monitor task will ever prove: `unproven` with neither a
1627
+ * proven_tx_req nor a proven_tx. See methods/unprovenWithoutReqSql.ts.
1628
+ */
1629
+ async findUnprovenTxidsWithoutReq(): Promise<string[]> {
1630
+ return await findUnprovenTxidsWithoutReq(this.getDB())
1631
+ }
1632
+
1633
+ async getProvenTxHeights(): Promise<Map<string, number>> {
1634
+ if (!this.isAvailable()) await this.makeAvailable()
1635
+ const rows = (await this.getDB().getAllAsync(PROVEN_HEIGHTS_SQL)) as { txid?: string; height?: number }[]
1636
+ const map = new Map<string, number>()
1637
+ for (const r of rows) {
1638
+ if (r.txid && typeof r.height === 'number') map.set(r.txid, r.height)
1639
+ }
1640
+ return map
1641
+ }
1642
+
1643
+ async getRawTxOfKnownValidTransaction(
1644
+ txid?: string,
1645
+ offset?: number,
1646
+ length?: number,
1647
+ trx?: TrxToken
1648
+ ): Promise<number[] | undefined> {
1649
+ if (!txid) return undefined
1650
+ if (!this.isAvailable()) await this.makeAvailable()
1651
+
1652
+ // Range reads are served in SQL. The caller here is almost always
1653
+ // validateOutputScript re-slicing one output's locking script out of its
1654
+ // source transaction — doing the slice in SQL means a large rawTx never
1655
+ // has to be loaded whole and Array.from-ed into JS just to keep a few
1656
+ // hundred bytes of it.
1657
+ //
1658
+ // Table order and the status filter mirror getProvenOrRawTx exactly (see
1659
+ // rangeReadSql), so a range read can never see a row the full read refuses.
1660
+ if (offset !== undefined && length !== undefined && Number.isInteger(offset) && Number.isInteger(length)) {
1661
+ const db = this.getDB(trx)
1662
+ // substr is 1-indexed over bytes; a JS offset of n starts at n + 1.
1663
+ const args = [offset + 1, length, txid]
1664
+ type RangeRow = { chunk?: Uint8Array } | null
1665
+ let row = (await db.getFirstAsync(rangeReadSql('proven_txs'), args)) as RangeRow
1666
+ if (!row) {
1667
+ row = (await db.getFirstAsync(rangeReadSql('proven_tx_reqs'), args)) as RangeRow
1668
+ }
1669
+ if (!row?.chunk) return undefined
1670
+ return Array.from(row.chunk)
1671
+ }
1672
+
1673
+ const r = await this.getProvenOrRawTx(txid, trx)
1674
+ return r.proven ? r.proven.rawTx : r.rawTx
1675
+ }
1676
+
1677
+ async getLabelsForTransactionId(transactionId?: number, trx?: TrxToken): Promise<TableTxLabel[]> {
1678
+ if (!transactionId) return []
1679
+ const maps = await this.findTxLabelMaps({ partial: { transactionId, isDeleted: false } as any, trx })
1680
+ const labels: any[] = []
1681
+ for (const m of maps) {
1682
+ const results = await this.findTxLabels({ partial: { txLabelId: m.txLabelId, isDeleted: false } as any, trx })
1683
+ if (results.length > 0) labels.push(results[0])
1684
+ }
1685
+ return labels
1686
+ }
1687
+
1688
+ async getTagsForOutputId(outputId: number, trx?: TrxToken): Promise<TableOutputTag[]> {
1689
+ const maps = await this.findOutputTagMaps({ partial: { outputId, isDeleted: false } as any, trx })
1690
+ const tags: any[] = []
1691
+ for (const m of maps) {
1692
+ const results = await this.findOutputTags({
1693
+ partial: { outputTagId: m.outputTagId, isDeleted: false } as any,
1694
+ trx
1695
+ })
1696
+ if (results.length > 0) tags.push(results[0])
1697
+ }
1698
+ return tags
1699
+ }
1700
+
1701
+ // Change input allocation
1702
+ async allocateChangeInput(
1703
+ userId: number,
1704
+ basketId: number,
1705
+ targetSatoshis: number,
1706
+ exactSatoshis: number | undefined,
1707
+ excludeSending: boolean,
1708
+ transactionId: number
1709
+ ): Promise<TableOutput | undefined> {
1710
+ const txStatus: string[] = ['completed', 'unproven']
1711
+ if (!excludeSending) txStatus.push('sending')
1712
+ const outputs = await this.findOutputs({
1713
+ partial: { userId, basketId, spendable: true as any },
1714
+ txStatus: txStatus as any
1715
+ })
1716
+ devLog(
1717
+ `[StorageExpoSQLite] allocateChangeInput: userId=${userId} basketId=${basketId} target=${targetSatoshis} found ${outputs.length} spendable outputs, satoshis: [${outputs.map(o => o.satoshis).join(',')}]`
1718
+ )
1719
+ let output: TableOutput | undefined
1720
+ let scores: { output: TableOutput; score: number }[] = []
1721
+ for (const o of outputs) {
1722
+ if (exactSatoshis && o.satoshis === exactSatoshis) {
1723
+ output = o
1724
+ break
1725
+ }
1726
+ scores.push({ output: o, score: o.satoshis - targetSatoshis })
1727
+ }
1728
+ if (!output) {
1729
+ scores = scores.sort((a, b) => a.score - b.score)
1730
+ const found = scores.find(s => s.score >= 0)
1731
+ if (found) {
1732
+ output = found.output
1733
+ } else if (scores.length > 0) {
1734
+ output = scores[scores.length - 1].output
1735
+ }
1736
+ }
1737
+ if (output) {
1738
+ await this.updateOutput(output.outputId, { spendable: false, spentBy: transactionId } as any)
1739
+ }
1740
+ return output
1741
+ }
1742
+
1743
+ async countChangeInputs(userId: number, basketId: number, excludeSending: boolean): Promise<number> {
1744
+ const txStatus: string[] = ['completed', 'unproven']
1745
+ if (!excludeSending) txStatus.push('sending')
1746
+ return await this.countOutputs({
1747
+ partial: { userId, basketId, spendable: true as any },
1748
+ txStatus: txStatus as any
1749
+ })
1750
+ }
1751
+
1752
+ // listActions and listOutputs — delegate to SQL-native implementations
1753
+ async listActions(auth: AuthId, vargs: Validation.ValidListActionsArgs): Promise<ListActionsResult> {
1754
+ if (!auth.userId) throw new Error('WERR_UNAUTHORIZED')
1755
+ return await listActionsSql(this, auth, vargs)
1756
+ }
1757
+
1758
+ async listOutputs(auth: AuthId, vargs: Validation.ValidListOutputsArgs): Promise<ListOutputsResult> {
1759
+ if (!auth.userId) throw new Error('WERR_UNAUTHORIZED')
1760
+ return await listOutputsSql(this, auth, vargs)
1761
+ }
1762
+
1763
+ async reviewStatus(args: { agedLimit: Date; trx?: TrxToken }): Promise<{ log: string }> {
1764
+ return await this.transaction(async trx => {
1765
+ const db = this.getDB(trx)
1766
+ const skipRows = (await db.getAllAsync(LIVE_OFFLINE_SKIP_TXIDS_SQL, [])) as { txid: string }[]
1767
+ const skipTxids = new Set(skipRows.map(row => row.txid))
1768
+ let log = ''
1769
+
1770
+ const invalid = (await db.getAllAsync(REVIEW_INVALID_REQ_TXS_SQL, [])) as {
1771
+ transactionId: number
1772
+ txid: string | null
1773
+ status: string
1774
+ }[]
1775
+ const statusById = new Map(invalid.map(tx => [tx.transactionId, tx.status]))
1776
+ await failInvalidReqTxs({
1777
+ rows: invalid,
1778
+ skipTxids,
1779
+ fail: async transactionId => {
1780
+ await this.updateTransactionStatus('failed', transactionId, undefined, undefined, trx)
1781
+ log += `transaction ${transactionId} updated to status of 'failed' was ${statusById.get(transactionId)}\n`
1782
+ }
1783
+ })
1784
+
1785
+ const failedTxs = (await db.getAllAsync(REVIEW_FAILED_TXS_SQL, [])) as ReviewFailedTx[]
1786
+ const reqStatusesByTxid = new Map<string, string[]>()
1787
+ for (const tx of failedTxs) {
1788
+ if (tx.txid == null || tx.txid === '' || reqStatusesByTxid.has(tx.txid)) continue
1789
+ const reqs = (await db.getAllAsync(REVIEW_REQ_STATUSES_SQL, [tx.txid])) as { status: string }[]
1790
+ reqStatusesByTxid.set(
1791
+ tx.txid,
1792
+ reqs.map(row => row.status)
1793
+ )
1794
+ }
1795
+ const { failedTransactionIds, safeFailedTransactionIds } = collectFailedTransactionIds(
1796
+ failedTxs,
1797
+ reqStatusesByTxid,
1798
+ skipTxids
1799
+ )
1800
+
1801
+ const outputs = (await db.getAllAsync(REVIEW_OUTPUTS_SQL, [])) as ReviewOutput[]
1802
+ for (const output of outputs) {
1803
+ const action = outputReviewAction(output, failedTransactionIds, safeFailedTransactionIds)
1804
+ if (action === 'restore') {
1805
+ await this.updateOutput(output.outputId, { spendable: true, spentBy: undefined }, trx)
1806
+ log += `output ${output.outputId} updated to spendable because spentBy is failed\n`
1807
+ } else if (action === 'unspend') {
1808
+ await this.updateOutput(output.outputId, { spendable: false, spentBy: undefined }, trx)
1809
+ log += `output ${output.outputId} updated to not spendable because transaction is failed\n`
1810
+ }
1811
+ }
1812
+
1813
+ return { log }
1814
+ }, args.trx)
1815
+ }
1816
+
1817
+ async purgeData(_params: PurgeParams, _trx?: TrxToken): Promise<PurgeResults> {
1818
+ return { count: 0, log: '' }
1819
+ }
1820
+
1821
+ async adminStats(_adminIdentityKey: string): Promise<AdminStatsResult> {
1822
+ throw new Error('Method intentionally not implemented for personal storage.')
1823
+ }
1824
+
1825
+ /**
1826
+ * The raw database, for the offline-actions modules only. `db` above is
1827
+ * already public (no access modifier) — this isn't a narrower type, just a
1828
+ * named, deliberate access point for that use so call sites read as
1829
+ * intentional rather than reaching into an implementation-shaped field.
1830
+ */
1831
+ get sqliteDb(): SQLiteDatabase | undefined {
1832
+ return this.db
1833
+ }
1834
+
1835
+ // Override internalizeAction for debugging
1836
+ async internalizeAction(auth: AuthId, args: any): Promise<any> {
1837
+ devLog('[StorageExpoSQLite] internalizeAction called, userId:', auth.userId)
1838
+ try {
1839
+ const result = await super.internalizeAction(auth, args)
1840
+ devLog(
1841
+ '[StorageExpoSQLite] internalizeAction result:',
1842
+ JSON.stringify({
1843
+ accepted: result.accepted,
1844
+ isMerge: result.isMerge,
1845
+ txid: result.txid,
1846
+ satoshis: result.satoshis,
1847
+ hasSendWithResults: !!result.sendWithResults,
1848
+ hasNotDelayedResults: !!result.notDelayedResults
1849
+ })
1850
+ )
1851
+ return result
1852
+ } catch (e: any) {
1853
+ console.error('[StorageExpoSQLite] internalizeAction ERROR:', e.message, e.stack?.slice(0, 500))
1854
+ throw e
1855
+ }
1856
+ }
1857
+
1858
+ /**
1859
+ * Park requests for later delivery instead of broadcasting them now.
1860
+ *
1861
+ * Each request goes to 'nosend': held, ignored by every monitor task
1862
+ * (`TaskSendWaiting` selects 'unsent'/'sending', `TaskCheckNoSends` is barred
1863
+ * from counting attempts against nosend rows, `TaskFailAbandoned` sweeps
1864
+ * *transactions* in 'unprocessed'/'unsigned'), yet still releasable later via
1865
+ * `options.sendWith` because `readyToSendStatuses` includes it
1866
+ * (`storage/storageProviderHelpers.js:14`). A row in `offline_actions` then
1867
+ * records that it still needs sending.
1868
+ *
1869
+ * The transaction row is deliberately left untouched, which makes its current
1870
+ * status a **precondition** rather than an afterthought: callers must only
1871
+ * pass requests whose transaction is already in `holdSafeTxStatuses`. For the
1872
+ * internalize path that is 'unproven'
1873
+ * (`storage/methods/internalizeAction.js:352`), the status that keeps the
1874
+ * received outputs spendable while the broadcast waits — the whole point of
1875
+ * holding rather than failing. See `utils/offline/hold.ts` for what the other
1876
+ * statuses would cost.
1877
+ *
1878
+ * Both writes are idempotent (a repeat 'nosend' is a no-op, and the queue
1879
+ * insert is `INSERT OR IGNORE` on a UNIQUE txid, so it neither duplicates a
1880
+ * row nor disturbs an existing `seq`), so a partial failure is safe to retry.
1881
+ *
1882
+ * Public and upstream-shaped: this is the method that becomes
1883
+ * `StorageProvider.holdReqsOffline` in wallet-toolbox.
1884
+ */
1885
+ async holdReqsOffline(reqs: { txid: string }[], userId: number, role: OfflineActionRole = 'received'): Promise<void> {
1886
+ const db = this.getDB()
1887
+ for (const req of reqs) {
1888
+ const row = (await this.findProvenTxReqs({ partial: { txid: req.txid } }))[0]
1889
+ if (row) await this.updateProvenTxReq(row.provenTxReqId, { status: 'nosend' })
1890
+ await insertOfflineAction(db, { userId, txid: req.txid, role })
1891
+ }
1892
+ TaskSendOffline.noteEnqueued()
1893
+ }
1894
+
1895
+ /**
1896
+ * Offline, hold the requests. Online, behave exactly as before.
1897
+ *
1898
+ * This override is reached only from `shareReqsWithWorld`
1899
+ * (`storage/methods/processAction.js:146`, a method call on storage), which
1900
+ * covers the forced broadcast inside `internalizeAction` and the non-delayed
1901
+ * create/`sendWith` path. `TaskSendWaiting` invokes the module function
1902
+ * directly (`monitor/tasks/TaskSendWaiting.js:180`), so the monitor's
1903
+ * ordinary broadcast retries are deliberately NOT intercepted.
1904
+ *
1905
+ * Narrower than "offline means hold": only requests whose transaction is
1906
+ * already in a hold-safe status are parked, so in practice this holds the
1907
+ * internalize path the feature needs and leaves the non-delayed `createAction`
1908
+ * path with the `serviceError` and automatic `TaskSendWaiting` retry it has
1909
+ * today. `groupOfflineHolds` makes that call; see `utils/offline/hold.ts`.
1910
+ *
1911
+ * The returned 'success' means "accepted for delivery", not "the network has
1912
+ * it"; see `utils/offline/hold.ts` for why nothing persisted claims otherwise.
1913
+ */
1914
+ async attemptToPostReqsToNetwork(
1915
+ reqs: EntityProvenTxReq[],
1916
+ trx?: TrxToken,
1917
+ logger?: WalletLoggerInterface
1918
+ ): Promise<PostReqsToNetworkResult> {
1919
+ if (reqs.length === 0) return await super.attemptToPostReqsToNetwork(reqs, trx, logger)
1920
+
1921
+ let online = true
1922
+ try {
1923
+ online = await getOnline()
1924
+ } catch (e) {
1925
+ // A failed connectivity probe must never change posting behaviour: assume
1926
+ // online so the real post runs exactly as it did before this override.
1927
+ devLog('[StorageExpoSQLite] connectivity probe failed, assuming online:', e)
1928
+ }
1929
+ if (online) return await super.attemptToPostReqsToNetwork(reqs, trx, logger)
1930
+
1931
+ const pairs = await this.resolveHoldPairs(reqs)
1932
+ const holds = groupOfflineHolds(pairs)
1933
+ if (!holds) {
1934
+ // Either a request could not be attributed to a user, so we could not
1935
+ // record that it still needs sending, or its transaction is not in a
1936
+ // status that survives being held (see `holdSafeTxStatuses`). Refuse the
1937
+ // whole call and let the ordinary broadcast run: offline its failure takes
1938
+ // the pre-existing paths, either `internalizeAction`'s rollback or a
1939
+ // `serviceError` that leaves the request for `TaskSendWaiting` to retry.
1940
+ devLog(
1941
+ '[StorageExpoSQLite] offline: not holding, delegating to the real post:',
1942
+ pairs.map(p => `${p.req.txid} ${p.tx ? `tx ${p.tx.status}` : 'unattributed'}`).join(', ')
1943
+ )
1944
+ return await super.attemptToPostReqsToNetwork(reqs, trx, logger)
1945
+ }
1946
+
1947
+ devLog(`[StorageExpoSQLite] offline: holding ${reqs.length} req(s) for later delivery`)
1948
+ for (const hold of holds.values()) {
1949
+ await this.holdReqsOffline(hold.reqs, hold.userId, hold.role)
1950
+ }
1951
+ return { ...buildOfflineHoldResult(reqs), beef: new Beef(), log: '' }
1952
+ }
1953
+
1954
+ /**
1955
+ * Pair each request with the transaction row it notifies
1956
+ * (`EntityProvenTxReq.addNotifyTransactionId`, populated by
1957
+ * `storage/methods/internalizeAction.js:523` and
1958
+ * `storage/methods/processAction.js:241`).
1959
+ *
1960
+ * Database reads only: every rule applied to these pairs lives in
1961
+ * `groupOfflineHolds`, which is pure and unit-tested. Read-only on purpose, so
1962
+ * the whole set is resolved before any write and a refusal can never leave a
1963
+ * request half-held.
1964
+ */
1965
+ private async resolveHoldPairs(
1966
+ reqs: EntityProvenTxReq[]
1967
+ ): Promise<{ req: EntityProvenTxReq; tx: TableTransaction | undefined }[]> {
1968
+ const pairs: { req: EntityProvenTxReq; tx: TableTransaction | undefined }[] = []
1969
+ for (const req of reqs) {
1970
+ let tx: TableTransaction | undefined
1971
+ for (const transactionId of req.notify?.transactionIds ?? []) {
1972
+ tx = (await this.findTransactions({ partial: { transactionId }, noRawTx: true }))[0]
1973
+ if (tx) break
1974
+ }
1975
+ pairs.push({ req, tx })
1976
+ }
1977
+ return pairs
1978
+ }
1979
+
1980
+ /**
1981
+ * Backup defense for pre-scrub rows.
1982
+ *
1983
+ * Rows written before the write-time scrub landed (2026-08-19) can carry the
1984
+ * full EF/rawTx hex in provider error notes. getProvenTxReqsForUser is a
1985
+ * SELECT *, so without this a single pre-scrub row would carry that hex
1986
+ * straight into a backup chunk.
1987
+ */
1988
+ async getSyncChunk(args: RequestSyncChunkArgs): Promise<SyncChunk> {
1989
+ const chunk = await super.getSyncChunk(args)
1990
+ for (const req of chunk.provenTxReqs ?? []) {
1991
+ req.history = scrubHistoryJson(req.history) as typeof req.history
1992
+ }
1993
+ return chunk
1994
+ }
1995
+
1996
+ // processSyncChunk — delegate to inherited implementation if available, stub otherwise
1997
+ async processSyncChunk(args: RequestSyncChunkArgs, chunk: SyncChunk): Promise<ProcessSyncChunkResult> {
1998
+ // The base StorageProvider class provides the implementation via super
1999
+ return await super.processSyncChunk(args, chunk)
2000
+ }
2001
+
2002
+ // Helper: validate raw transaction (fill from proven if missing)
2003
+ private async validateRawTransaction(t: TableTransaction, trx?: TrxToken): Promise<void> {
2004
+ if (t.rawTx || !t.txid) return
2005
+ const rawTx = await this.getRawTxOfKnownValidTransaction(t.txid, undefined, undefined, trx)
2006
+ if (rawTx) t.rawTx = rawTx
2007
+ }
2008
+ }