@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,211 @@
1
+ /**
2
+ * SQL-native listOutputs implementation.
3
+ * Replaces IDB cursor-based filtering with SQL queries.
4
+ * Handles specOp patterns (wallet balance, invalid change, etc.)
5
+ */
6
+ import type { ListOutputsResult, Validation } from '@bsv/sdk'
7
+ import type { AuthId } from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
8
+ import type { StorageExpoSQLite } from '../StorageExpoSQLite'
9
+ import { getListOutputsSpecOp } from '@bsv/wallet-toolbox-mobile/out/src/storage/methods/ListOutputsSpecOp'
10
+ import { devLog, isLoggingEnabled } from '../../logging'
11
+
12
+ export async function listOutputsSql(
13
+ storage: StorageExpoSQLite,
14
+ auth: AuthId,
15
+ vargs: Validation.ValidListOutputsArgs
16
+ ): Promise<ListOutputsResult> {
17
+ const userId = auth.userId!
18
+ const limit = vargs.limit || 10
19
+ const offset = vargs.offset || 0
20
+ const includeCustomInstructions = vargs.includeCustomInstructions || false
21
+ const includeTags = vargs.includeTags || false
22
+ const includeLabels = vargs.includeLabels || false
23
+ const includeLockingScripts = vargs.includeLockingScripts || false
24
+ const knownTxids = vargs.knownTxids || []
25
+
26
+ const r: ListOutputsResult = { totalOutputs: 0, outputs: [] }
27
+
28
+ // Check for specOp (wallet balance, invalid change, etc.)
29
+ let { specOp, basket, tags: remainingTags } = getListOutputsSpecOp(vargs.basket, vargs.tags)
30
+ let tags = remainingTags || []
31
+
32
+ // Resolve basket
33
+ let basketId: number | undefined
34
+ if (basket) {
35
+ const baskets = await storage.findOutputBaskets({ partial: { userId, name: basket } })
36
+ devLog(`[listOutputsSql] basket="${basket}" found ${baskets.length} matches${baskets.length > 0 ? ` (id=${baskets[0].basketId})` : ''}`)
37
+ if (baskets.length !== 1) return r
38
+ basketId = baskets[0].basketId
39
+ }
40
+
41
+ // Handle specOp tag interception
42
+ const specOpTags: string[] = []
43
+ if (specOp && specOp.tagsParamsCount) {
44
+ specOpTags.push(...tags.splice(0, Math.min(tags.length, specOp.tagsParamsCount)))
45
+ }
46
+ if (specOp && specOp.tagsToIntercept) {
47
+ const ts = tags
48
+ tags = []
49
+ for (const t of ts) {
50
+ if (specOp.tagsToIntercept.length === 0 || specOp.tagsToIntercept.indexOf(t) >= 0) {
51
+ specOpTags.push(t)
52
+ if (t === 'all') basketId = undefined
53
+ } else {
54
+ tags.push(t)
55
+ }
56
+ }
57
+ }
58
+
59
+ // Early return for specOps that only need tags
60
+ if (specOp && specOp.resultFromTags) {
61
+ return await specOp.resultFromTags(storage, auth, vargs, specOpTags)
62
+ }
63
+
64
+ // Resolve tags to tagIds
65
+ let tagIds: number[] = []
66
+ const isQueryModeAll = (vargs.tagQueryMode || 'any') === 'all'
67
+
68
+ if (tags.length > 0) {
69
+ const foundTags = await storage.findOutputTags({
70
+ partial: { userId, isDeleted: false } as any
71
+ })
72
+ const matchedTags = foundTags.filter((t: any) => tags.includes(t.tag))
73
+ tagIds = matchedTags.map((t: any) => t.outputTagId as number)
74
+
75
+ if (isQueryModeAll && tagIds.length < tags.length) return r
76
+ if (!isQueryModeAll && tagIds.length === 0) return r
77
+ }
78
+
79
+ // Build partial for query
80
+ const partial: Record<string, any> = { userId, spendable: true }
81
+ if (basketId !== undefined) partial.basketId = basketId
82
+
83
+ // Build find args — specOps with ignoreLimit fetch ALL outputs
84
+ const findArgs: any = {
85
+ partial,
86
+ txStatus: ['completed', 'unproven', 'nosend'],
87
+ noScript: true
88
+ }
89
+ if (!specOp || !specOp.ignoreLimit) {
90
+ findArgs.paged = { limit, offset }
91
+ }
92
+
93
+ // The wallet-balance specOp wants ONE NUMBER: the sum of the satoshis of the
94
+ // outputs this query would return. Let SQLite add them up rather than reading
95
+ // every row into JS to do it here — for a wallet with a few hundred change
96
+ // outputs that is a few hundred full rows crossing the bridge, on the JS
97
+ // thread, to produce a single integer. Same filter, same answer; the row path
98
+ // below still serves every other specOp.
99
+ if (specOp?.totalOutputsIsSumOfSatoshis && !specOp.filterOutputs) {
100
+ const { total } = await storage.sumOutputSatoshis(
101
+ findArgs,
102
+ tagIds.length > 0 ? tagIds : undefined,
103
+ isQueryModeAll
104
+ )
105
+ return { totalOutputs: total, outputs: [] }
106
+ }
107
+
108
+ let outputs = await storage.findOutputs(
109
+ findArgs,
110
+ tagIds.length > 0 ? tagIds : undefined,
111
+ isQueryModeAll
112
+ )
113
+ if (outputs.length === 0 && basketId !== undefined && isLoggingEnabled()) {
114
+ // Debug aid for an empty basket: what IS in there, before the filters. The
115
+ // query is gated with the log — running it unconditionally cost a second
116
+ // full-basket read on every empty result, in production too.
117
+ const db = (storage as any).getDB()
118
+ const raw = await db.getAllAsync(
119
+ `SELECT o.outputId, o.spendable, o.satoshis, t.status as txStatus
120
+ FROM outputs o JOIN transactions t ON o.transactionId = t.transactionId
121
+ WHERE o.userId = ? AND o.basketId = ?`,
122
+ [userId, basketId]
123
+ )
124
+ devLog(`[listOutputsSql] DEBUG basket=${basketId} raw outputs:`, JSON.stringify(raw))
125
+ }
126
+ devLog(`[listOutputsSql] basket="${basket}" specOp=${specOp?.name || 'none'} found ${outputs.length} outputs, satoshis: [${outputs.slice(0, 5).map(o => o.satoshis).join(',')}]`)
127
+
128
+ // Count total
129
+ if (outputs.length === limit) {
130
+ r.totalOutputs = await storage.countOutputs(
131
+ { partial, txStatus: ['completed', 'unproven', 'nosend'], noScript: true } as any,
132
+ tagIds.length > 0 ? tagIds : undefined,
133
+ isQueryModeAll
134
+ )
135
+ } else {
136
+ r.totalOutputs = outputs.length
137
+ }
138
+
139
+ // Apply specOp processing
140
+ if (specOp) {
141
+ if (specOp.filterOutputs) {
142
+ outputs = await specOp.filterOutputs(storage, auth, vargs, specOpTags, outputs)
143
+ }
144
+ if (specOp.resultFromOutputs) {
145
+ return await specOp.resultFromOutputs(storage, auth, vargs, specOpTags, outputs)
146
+ }
147
+ }
148
+
149
+ // Cache labels by transactionId to avoid duplicate queries
150
+ const labelsByTxId = new Map<number, string[]>()
151
+
152
+ // Build output response
153
+ for (const o of outputs) {
154
+ const wo: any = {
155
+ satoshis: Number(o.satoshis),
156
+ spendable: !!o.spendable,
157
+ outpoint: `${(o as any).txid || ''}.${o.vout}`
158
+ }
159
+
160
+ if (includeCustomInstructions && o.customInstructions) {
161
+ wo.customInstructions = o.customInstructions
162
+ }
163
+
164
+ if (includeLabels && (o as any).txid) {
165
+ if (!labelsByTxId.has(o.transactionId)) {
166
+ const txLabels = await storage.getLabelsForTransactionId(o.transactionId)
167
+ labelsByTxId.set(o.transactionId, txLabels.map(l => l.label))
168
+ }
169
+ wo.labels = labelsByTxId.get(o.transactionId)
170
+ }
171
+
172
+ if (includeTags) {
173
+ const outputTags = await storage.getTagsForOutputId(o.outputId)
174
+ wo.tags = outputTags.map(t => t.tag)
175
+ }
176
+
177
+ if (includeLockingScripts) {
178
+ await storage.validateOutputScript(o)
179
+ if (o.lockingScript) {
180
+ wo.lockingScript = typeof o.lockingScript === 'string'
181
+ ? o.lockingScript
182
+ : Array.from(o.lockingScript as any).map((b: any) => b.toString(16).padStart(2, '0')).join('')
183
+ }
184
+ }
185
+
186
+ r.outputs.push(wo)
187
+ }
188
+
189
+ // Build BEEF if includeTransactions requested
190
+ if (vargs.includeTransactions) {
191
+ try {
192
+ const { Beef } = await import('@bsv/sdk')
193
+ const beef = new Beef()
194
+ for (const o of outputs) {
195
+ const txid = (o as any).txid
196
+ if (txid && !beef.findTxid(txid)) {
197
+ try {
198
+ await storage.getValidBeefForKnownTxid(txid, beef, undefined, knownTxids)
199
+ } catch {
200
+ // Skip if we can't build beef for this txid
201
+ }
202
+ }
203
+ }
204
+ r.BEEF = beef.toBinary()
205
+ } catch {
206
+ // BEEF construction is optional
207
+ }
208
+ }
209
+
210
+ return r
211
+ }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Thin SQL mapper for `offline_actions`. Deliberately logic-free: every
3
+ * decision about ordering, cascading, and status lives in
4
+ * `utils/offline/order.ts` and `utils/offline/plan.ts`, which are unit-tested.
5
+ * This file is validated on device.
6
+ */
7
+ /**
8
+ * `parked` is a payment held back deliberately: built and handed over as a code,
9
+ * but NOT released for broadcast, because the payer walked away rather than
10
+ * confirming the hand-over. Every query that drives the drain asks for
11
+ * 'queued'/'posting', so a parked row is inert by construction — it exists to
12
+ * keep the frame (for re-showing the code) and to keep the transaction
13
+ * cancellable.
14
+ */
15
+ export type OfflineActionStatus = 'queued' | 'posting' | 'sent' | 'rejected' | 'acknowledged' | 'parked'
16
+ export type OfflineActionRole = 'received' | 'sent'
17
+
18
+ export interface OfflineActionRow {
19
+ offlineActionId: number
20
+ created_at: string
21
+ updated_at: string
22
+ userId: number
23
+ txid: string
24
+ seq: number
25
+ role: OfflineActionRole
26
+ senderIdentityKey: string | null
27
+ receivedVia: string | null
28
+ status: OfflineActionStatus
29
+ rejectedReason: string | null
30
+ poisonedByTxid: string | null
31
+ framePayload: string | null
32
+ }
33
+
34
+ /** The subset of bind values this mapper ever passes (no blobs). */
35
+ export type BindValue = string | number | null
36
+
37
+ /**
38
+ * Structurally satisfied by expo-sqlite's SQLiteDatabase. `params` is
39
+ * required (not optional) and narrowed to `BindValue[]` rather than
40
+ * `unknown[]`: expo-sqlite's real signatures take `SQLiteBindParams`
41
+ * (`Record<string, SQLiteBindValue> | SQLiteBindValue[]`) as a required
42
+ * argument on the array-form overload, and TypeScript will not treat an
43
+ * optional `unknown[]` parameter as structurally assignable from that —
44
+ * `undefined` isn't a valid SQLiteBindParams, and `unknown` isn't a valid
45
+ * SQLiteBindValue. Every call site below always passes an array, so
46
+ * required is no burden.
47
+ */
48
+ export interface OfflineDb {
49
+ runAsync(sql: string, params: BindValue[]): Promise<unknown>
50
+ getAllAsync(sql: string, params: BindValue[]): Promise<unknown[]>
51
+ getFirstAsync(sql: string, params: BindValue[]): Promise<unknown>
52
+ }
53
+
54
+ export interface NewOfflineAction {
55
+ userId: number
56
+ txid: string
57
+ role: OfflineActionRole
58
+ senderIdentityKey?: string
59
+ receivedVia?: string
60
+ /** The payer's full `bsvpayf1:` QR string, so the code can be re-shown after an app restart. */
61
+ framePayload?: string
62
+ }
63
+
64
+ /**
65
+ * Idempotent: a re-delivered frame must not create a second queue row.
66
+ * `seq` is allocated in the same statement as the insert (a scalar subquery
67
+ * in the VALUES clause) rather than as a separate SELECT-then-INSERT, so
68
+ * SQLite's single-writer lock covers both — two interleaved inserts cannot
69
+ * read the same max and land the same seq.
70
+ */
71
+ export async function insertOfflineAction(
72
+ db: OfflineDb,
73
+ entry: NewOfflineAction,
74
+ status: OfflineActionStatus = 'queued'
75
+ ): Promise<void> {
76
+ const now = new Date().toISOString()
77
+ await db.runAsync(
78
+ `INSERT OR IGNORE INTO offline_actions
79
+ (created_at, updated_at, userId, txid, seq, role, senderIdentityKey, receivedVia, status, framePayload)
80
+ VALUES (?, ?, ?, ?, (SELECT COALESCE(MAX(seq), 0) + 1 FROM offline_actions), ?, ?, ?, ?, ?)`,
81
+ [
82
+ now,
83
+ now,
84
+ entry.userId,
85
+ entry.txid,
86
+ entry.role,
87
+ entry.senderIdentityKey ?? null,
88
+ entry.receivedVia ?? null,
89
+ status,
90
+ entry.framePayload ?? null
91
+ ]
92
+ )
93
+ }
94
+
95
+ export async function findOfflineActions(
96
+ db: OfflineDb,
97
+ filter: { status?: OfflineActionStatus[]; userId?: number } = {}
98
+ ): Promise<OfflineActionRow[]> {
99
+ const where: string[] = []
100
+ const params: BindValue[] = []
101
+ if (filter.status && filter.status.length > 0) {
102
+ where.push(`status IN (${filter.status.map(() => '?').join(',')})`)
103
+ params.push(...filter.status)
104
+ }
105
+ if (filter.userId !== undefined) {
106
+ where.push('userId = ?')
107
+ params.push(filter.userId)
108
+ }
109
+ const sql =
110
+ 'SELECT * FROM offline_actions' + (where.length ? ` WHERE ${where.join(' AND ')}` : '') + ' ORDER BY seq ASC'
111
+ return (await db.getAllAsync(sql, params)) as OfflineActionRow[]
112
+ }
113
+
114
+ export async function updateOfflineAction(
115
+ db: OfflineDb,
116
+ txid: string,
117
+ patch: {
118
+ status?: OfflineActionStatus
119
+ rejectedReason?: string | null
120
+ poisonedByTxid?: string | null
121
+ /**
122
+ * Backfilled after the fact: the row is inserted (with both attribution
123
+ * columns null) from deep inside the storage layer's offline-hold path,
124
+ * which never sees the payment frame. `utils/localpay/pending.ts`'s
125
+ * `processPending` is the one place that has both the txid and the frame,
126
+ * once `internalizeAction` resolves — see its `attribute` callback.
127
+ */
128
+ senderIdentityKey?: string | null
129
+ receivedVia?: string | null
130
+ }
131
+ ): Promise<void> {
132
+ const sets: string[] = ['updated_at = ?']
133
+ const params: BindValue[] = [new Date().toISOString()]
134
+ if (patch.status !== undefined) {
135
+ sets.push('status = ?')
136
+ params.push(patch.status)
137
+ }
138
+ if (patch.rejectedReason !== undefined) {
139
+ sets.push('rejectedReason = ?')
140
+ params.push(patch.rejectedReason)
141
+ }
142
+ if (patch.poisonedByTxid !== undefined) {
143
+ sets.push('poisonedByTxid = ?')
144
+ params.push(patch.poisonedByTxid)
145
+ }
146
+ if (patch.senderIdentityKey !== undefined) {
147
+ sets.push('senderIdentityKey = ?')
148
+ params.push(patch.senderIdentityKey)
149
+ }
150
+ if (patch.receivedVia !== undefined) {
151
+ sets.push('receivedVia = ?')
152
+ params.push(patch.receivedVia)
153
+ }
154
+ params.push(txid)
155
+ await db.runAsync(`UPDATE offline_actions SET ${sets.join(', ')} WHERE txid = ?`, params)
156
+ }