@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,73 @@
1
+ /**
2
+ * Typed storage failures.
3
+ *
4
+ * expo-sqlite gives every failure the same `code`: `ERR_INTERNAL_SQLITE_ERROR`,
5
+ * for a full disk, a locked database, corruption and a syntax error alike. So a
6
+ * handler keyed on `code` cannot tell "free some space" from "another reader
7
+ * holds the lock" — and this project already has a storage-lock stall issue, so
8
+ * that confusion is not hypothetical.
9
+ *
10
+ * Classification therefore reads the message text, and does so carefully:
11
+ *
12
+ * - Match the SQLITE text, never the prefix. Android builds its message with
13
+ * `result += code` on an int, so SQLITE_FULL arrives as
14
+ * `Error code \r: database or disk is full`. Anchoring on `^Error code`
15
+ * would also miss every execAsync failure, which returns the bare errmsg on
16
+ * both platforms — including the BEGIN/COMMIT/ROLLBACK that
17
+ * withExclusiveTransactionAsync issues. Matching the sqlite text survives
18
+ * both forms, and survives the Android prefix being fixed upstream.
19
+ * - Never parse a number out of the message, for the same reason.
20
+ * - `database is locked` is classified as its own code and explicitly NOT as
21
+ * storage pressure.
22
+ *
23
+ * Shaped after services/vault/types.ts, which is the established pattern here
24
+ * for turning a native error string into a branded code.
25
+ */
26
+
27
+ export type StorageErrorCode =
28
+ /** The volume is full: the write did not happen and will not until space is freed. */
29
+ | 'disk-full'
30
+ /** The device reported an I/O failure. Transient or hardware; not a quota. */
31
+ | 'disk-io'
32
+ /** Another reader or writer holds the lock. NOT a storage-pressure problem. */
33
+ | 'locked'
34
+ /** Recognisably a storage failure, but none of the above. */
35
+ | 'unknown'
36
+
37
+ export class StorageError extends Error {
38
+ code: StorageErrorCode
39
+ /** The original failure, kept so a log can carry the untranslated text. */
40
+ cause?: unknown
41
+
42
+ constructor(code: StorageErrorCode, message?: string, cause?: unknown) {
43
+ super(message ?? code)
44
+ this.name = 'StorageError'
45
+ this.code = code
46
+ this.cause = cause
47
+ }
48
+ }
49
+
50
+ /** Unanchored, deliberately — see the module doc. */
51
+ const PATTERNS: { code: StorageErrorCode; re: RegExp }[] = [
52
+ { code: 'disk-full', re: /database or disk is full/i },
53
+ { code: 'disk-full', re: /disk full/i },
54
+ { code: 'disk-io', re: /disk i\/o error/i },
55
+ { code: 'locked', re: /database is locked/i },
56
+ { code: 'locked', re: /database table is locked/i }
57
+ ]
58
+
59
+ /**
60
+ * Classify a failure as a storage problem, or return null.
61
+ *
62
+ * Null means "not recognisably about storage" and the caller must rethrow the
63
+ * original untouched: guessing would turn a schema bug into a misleading
64
+ * "free up space" prompt.
65
+ */
66
+ export function storageErrorFromSqlite(e: unknown): StorageError | null {
67
+ if (!(e instanceof Error)) return null
68
+ const message = e.message ?? ''
69
+ for (const { code, re } of PATTERNS) {
70
+ if (re.test(message)) return new StorageError(code, message, e)
71
+ }
72
+ return null
73
+ }
@@ -0,0 +1,3 @@
1
+ export { StorageExpoSQLite } from './StorageExpoSQLite'
2
+ export type { StorageExpoSQLiteOptions } from './StorageExpoSQLite'
3
+ export { createTables } from './schema/createTables'
@@ -0,0 +1,286 @@
1
+ /**
2
+ * SQL construction for the storage layer's read paths.
3
+ *
4
+ * Extracted from StorageExpoSQLite so the generated SQL is testable without a
5
+ * device: everything here is a pure string function.
6
+ *
7
+ * The reason this exists at all is `SELECT *`. Every finder used to read every
8
+ * column, which meant `validateEntity` ran `Array.from` over each BLOB (an
9
+ * ~8x heap multiplier under Hermes for a byte array) and `findOutputs` /
10
+ * `findTransactions` then threw the value away when the caller had asked for
11
+ * `noScript` / `noRawTx`. Five callers already ask for the cheap path. A vault
12
+ * transaction's rawTx is ~960 KB, so a page of them was tens of megabytes of
13
+ * transient heap to answer a question about integers.
14
+ */
15
+
16
+ /**
17
+ * Columns of every table this module can project, in schema declaration order.
18
+ *
19
+ * SOURCE OF TRUTH: storage/schema/createTables.ts. These lists are duplicated
20
+ * here deliberately — SQLite has no `SELECT * EXCEPT`, so an explicit projection
21
+ * needs the names — and __tests__/storage/findSql.test.ts parses createTables.ts
22
+ * and fails if the two ever diverge. Add a column there and the test tells you
23
+ * to add it here.
24
+ */
25
+ export const TABLE_COLUMNS: Record<string, string[]> = {
26
+ proven_txs: [
27
+ 'provenTxId',
28
+ 'created_at',
29
+ 'updated_at',
30
+ 'txid',
31
+ 'height',
32
+ 'index',
33
+ 'merklePath',
34
+ 'rawTx',
35
+ 'blockHash',
36
+ 'merkleRoot'
37
+ ],
38
+ proven_tx_reqs: [
39
+ 'provenTxReqId',
40
+ 'created_at',
41
+ 'updated_at',
42
+ 'txid',
43
+ 'status',
44
+ 'attempts',
45
+ 'notified',
46
+ 'history',
47
+ 'notify',
48
+ 'rawTx',
49
+ 'inputBEEF',
50
+ 'batch',
51
+ 'provenTxId',
52
+ 'wasBroadcast',
53
+ 'rebroadcastAttempts'
54
+ ],
55
+ transactions: [
56
+ 'transactionId',
57
+ 'created_at',
58
+ 'updated_at',
59
+ 'userId',
60
+ 'status',
61
+ 'reference',
62
+ 'isOutgoing',
63
+ 'satoshis',
64
+ 'description',
65
+ 'version',
66
+ 'lockTime',
67
+ 'txid',
68
+ 'inputBEEF',
69
+ 'rawTx',
70
+ 'provenTxId'
71
+ ],
72
+ outputs: [
73
+ 'outputId',
74
+ 'created_at',
75
+ 'updated_at',
76
+ 'userId',
77
+ 'transactionId',
78
+ 'basketId',
79
+ 'spendable',
80
+ 'change',
81
+ 'outputDescription',
82
+ 'vout',
83
+ 'satoshis',
84
+ 'providedBy',
85
+ 'purpose',
86
+ 'type',
87
+ 'txid',
88
+ 'senderIdentityKey',
89
+ 'derivationPrefix',
90
+ 'derivationSuffix',
91
+ 'customInstructions',
92
+ 'spentBy',
93
+ 'sequenceNumber',
94
+ 'spendingDescription',
95
+ 'scriptLength',
96
+ 'scriptOffset',
97
+ 'lockingScript'
98
+ ],
99
+ commissions: [
100
+ 'commissionId',
101
+ 'created_at',
102
+ 'updated_at',
103
+ 'userId',
104
+ 'transactionId',
105
+ 'satoshis',
106
+ 'keyOffset',
107
+ 'isRedeemed',
108
+ 'lockingScript'
109
+ ]
110
+ }
111
+
112
+ /** The BLOB columns per table — the ones worth not reading. */
113
+ export const BLOB_COLUMNS: Record<string, string[]> = {
114
+ proven_txs: ['merklePath', 'rawTx'],
115
+ proven_tx_reqs: ['rawTx', 'inputBEEF'],
116
+ transactions: ['inputBEEF', 'rawTx'],
117
+ outputs: ['lockingScript'],
118
+ commissions: ['lockingScript']
119
+ }
120
+
121
+ /**
122
+ * Every column of `table` except `exclude`, or undefined when nothing is
123
+ * excluded.
124
+ *
125
+ * Undefined means "emit SELECT *" — the pre-existing behaviour. Returning it
126
+ * rather than the full list keeps the generated SQL identical for every caller
127
+ * that has no reason to project, so this change cannot alter their result rows.
128
+ */
129
+ export function columnsExcluding(table: string, exclude: string[]): string[] | undefined {
130
+ if (exclude.length === 0) return undefined
131
+ const all = TABLE_COLUMNS[table]
132
+ if (!all) return undefined
133
+ const drop = new Set(exclude)
134
+ return all.filter(c => !drop.has(c))
135
+ }
136
+
137
+ export interface FindSqlOptions {
138
+ table: string
139
+ /** Pre-built WHERE clause (possibly empty) from buildWhere. */
140
+ whereSql: string
141
+ hasSince: boolean
142
+ extraConditions?: string[]
143
+ pkCol: string
144
+ orderDescending?: boolean
145
+ limit?: number
146
+ offset?: number
147
+ /** Explicit projection. Undefined emits SELECT *. */
148
+ columns?: string[]
149
+ }
150
+
151
+ /**
152
+ * Build a finder query.
153
+ *
154
+ * Clause order and the WHERE/AND choice are copied from the original inline
155
+ * implementation and must not be reordered: whether `since` and the extra
156
+ * conditions introduce `WHERE` or extend it with `AND` depends on what came
157
+ * before them.
158
+ *
159
+ * Every identifier is quoted, which is not cosmetic — proven_txs has a column
160
+ * literally named `index`.
161
+ */
162
+ export function buildFindSql(opts: FindSqlOptions): string {
163
+ const projection = opts.columns ? opts.columns.map(c => `"${c}"`).join(', ') : '*'
164
+ let query = `SELECT ${projection} FROM "${opts.table}" ${opts.whereSql}`
165
+
166
+ if (opts.hasSince) {
167
+ query += `${opts.whereSql ? ' AND' : ' WHERE'} updated_at >= ?`
168
+ }
169
+ for (const c of opts.extraConditions ?? []) {
170
+ query += `${opts.whereSql || opts.hasSince ? ' AND' : ' WHERE'} ${c}`
171
+ }
172
+ query += ` ORDER BY "${opts.pkCol}" ${opts.orderDescending ? 'DESC' : 'ASC'}`
173
+ if (opts.limit) {
174
+ query += ` LIMIT ${opts.limit}`
175
+ if (opts.offset) query += ` OFFSET ${opts.offset}`
176
+ }
177
+ return query
178
+ }
179
+
180
+ /**
181
+ * Byte-range read of a stored rawTx.
182
+ *
183
+ * `substr` on a BLOB is byte-based and 1-INDEXED, so a JS offset n is passed as
184
+ * n + 1. Doing the range in SQL is what stops a caller that wants one output's
185
+ * locking script from materialising the whole rawTx (and then a JS array over
186
+ * every byte of it) to slice it.
187
+ *
188
+ * The proven_tx_reqs variant carries the same status filter getProvenOrRawTx
189
+ * applies, so the two paths cannot disagree about which rows are usable.
190
+ */
191
+ export function rangeReadSql(table: 'proven_txs' | 'proven_tx_reqs'): string {
192
+ const usable = "AND status IN ('unsent','unmined','unconfirmed','sending','nosend','completed')"
193
+ return `SELECT substr(rawTx, ?, ?) AS chunk FROM "${table}" WHERE txid = ? ${
194
+ table === 'proven_tx_reqs' ? usable : ''
195
+ }`.trimEnd()
196
+ }
197
+
198
+ /**
199
+ * txid → height for every proven transaction.
200
+ *
201
+ * The CSV export used findProvenTxs({ partial: {} }) for this, which is an
202
+ * unbounded SELECT * that reads and Array.from-expands every rawTx and
203
+ * merklePath in the wallet to build a map of two small columns.
204
+ */
205
+ export const PROVEN_HEIGHTS_SQL = 'SELECT txid, height FROM proven_txs'
206
+
207
+ /**
208
+ * The transactions that have reserved the given outpoints, by `reference`.
209
+ *
210
+ * `reference` and not `txid` deliberately: this exists to heal a vault UTXO left
211
+ * reserved by an attempt that died BEFORE signing, so the reserving row has no
212
+ * txid at all — which is exactly why the old heal had to page every action and
213
+ * match on its input list. `abortAction` takes a reference anyway.
214
+ *
215
+ * One OR-group per outpoint rather than a row-value IN, so the query works on
216
+ * any SQLite build.
217
+ */
218
+ export function spendingReferencesSql(pairCount: number): string {
219
+ const groups = Array.from({ length: pairCount }, () => '("o"."txid" = ? AND "o"."vout" = ?)').join(' OR ')
220
+ return (
221
+ 'SELECT DISTINCT "t"."reference" AS reference, "t"."status" AS status ' +
222
+ 'FROM "outputs" "o" JOIN "transactions" "t" ON "t"."transactionId" = "o"."spentBy" ' +
223
+ `WHERE "o"."spentBy" IS NOT NULL AND (${groups})`
224
+ )
225
+ }
226
+
227
+ /**
228
+ * Release every input still held by a definitively-invalid vault deposit tx2.
229
+ *
230
+ * The predicate is deliberately narrow, every clause load-bearing:
231
+ * - `t.status = 'failed'` AND its proven_tx_req is `'invalid'`: the network
232
+ * REJECTED the spender outright — it can never be mined, so releasing its
233
+ * inputs cannot enable a real double-spend. A 'failed' transaction without
234
+ * an 'invalid' req (say, a broadcast that timed out but may still have
235
+ * propagated) is NOT touched.
236
+ * - the spender carries the 'vault-deposit' label: this heal exists for the
237
+ * deposit flow and must not reinterpret failures of anything else.
238
+ *
239
+ * Why this exists: when tx2 fails, updateTransactionStatus('failed') restores
240
+ * its inputs, but markStaleInputsAsSpent then re-strands them — it asks the
241
+ * indexers whether tx1's staging output is a UTXO seconds after tx1 broadcast,
242
+ * and indexer lag answers "no". abortAction cannot fix it afterwards because
243
+ * 'failed' is in its unAbortable list.
244
+ */
245
+ export const RELEASE_STRANDED_VAULT_STAGING_SQL = `
246
+ UPDATE outputs SET spendable = 1, spentBy = NULL
247
+ WHERE spendable = 0 AND spentBy IN (
248
+ SELECT t.transactionId FROM transactions t
249
+ JOIN proven_tx_reqs r ON r.txid = t.txid AND r.status = 'invalid'
250
+ JOIN tx_labels_map m ON m.transactionId = t.transactionId AND m.isDeleted = 0
251
+ JOIN tx_labels l ON l.txLabelId = m.txLabelId AND l.label = 'vault-deposit'
252
+ WHERE t.status = 'failed'
253
+ )
254
+ `.trim()
255
+
256
+ /**
257
+ * Companion to RELEASE_STRANDED_VAULT_STAGING_SQL: clear a STALE spentBy on
258
+ * coins that are already spendable again.
259
+ *
260
+ * The other arm of the same failure. When the invalid spender's inputs are
261
+ * restored, updateOutput({spendable: true, spentBy: undefined}) re-lists the
262
+ * coin — but sqlUpdate drops undefined values, so spentBy keeps pointing at
263
+ * the failed transaction (which HAS a txid). createAction's reservation check
264
+ * (markKnownInputsSpent) refuses any input whose spentBy names a tx with a
265
+ * txid — WITHOUT checking whether that tx is 'failed' — so every later spend
266
+ * of the coin throws WERR_REVIEW_ACTIONS forever. Same deliberately narrow
267
+ * predicate: only a 'failed' spender whose req the network rejected outright
268
+ * ('invalid') and that carries the vault-deposit label.
269
+ */
270
+ export const RELEASE_STALE_VAULT_STAGING_SPENTBY_SQL = `
271
+ UPDATE outputs SET spentBy = NULL
272
+ WHERE spendable = 1 AND spentBy IN (
273
+ SELECT t.transactionId FROM transactions t
274
+ JOIN proven_tx_reqs r ON r.txid = t.txid AND r.status = 'invalid'
275
+ JOIN tx_labels_map m ON m.transactionId = t.transactionId AND m.isDeleted = 0
276
+ JOIN tx_labels l ON l.txLabelId = m.txLabelId AND l.label = 'vault-deposit'
277
+ WHERE t.status = 'failed'
278
+ )
279
+ `.trim()
280
+
281
+ /** Split a `txid.vout` or `txid:vout` outpoint into its parts, or null. */
282
+ export function splitOutpoint(outpoint: string): { txid: string; vout: number } | null {
283
+ const m = /^([0-9a-fA-F]{64})[.:](\d+)$/.exec(outpoint.trim())
284
+ if (!m) return null
285
+ return { txid: m[1].toLowerCase(), vout: Number(m[2]) }
286
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Bounding `proven_tx_reqs.history`.
3
+ *
4
+ * Every broadcast provider in the toolbox captures its full payload in an error
5
+ * note — Arcade keeps the Extended Format hex, WhatsOnChain keeps `beef.toHex()`,
6
+ * Bitails keeps the joined raw hex — and `transferNotesToReqHistories` copies
7
+ * those notes verbatim into this TEXT column with no truncation. Worse,
8
+ * `addHistoryNote`'s dedup does full string equality against every existing
9
+ * note, so the second failure compares megabyte strings against megabyte
10
+ * strings.
11
+ *
12
+ * A single failing vault broadcast therefore writes multi-megabyte hex into the
13
+ * database and makes each subsequent attempt quadratic — precisely when things
14
+ * are already going wrong. No rawTx codec touches this: the bytes arrive as hex
15
+ * text inside a diagnostic string.
16
+ *
17
+ * The cap is deliberately applied to VALUES, not to the note count. History is
18
+ * the only diagnostic trail for a stuck transaction, so losing entries would
19
+ * cost real debuggability; losing the tail of one enormous hex string costs
20
+ * nothing.
21
+ */
22
+
23
+ /** Longest string value kept in a history note, including the ellipsis. */
24
+ export const NOTE_VALUE_MAX = 256
25
+
26
+ const truncate = (s: string): string => (s.length <= NOTE_VALUE_MAX ? s : `${s.slice(0, NOTE_VALUE_MAX - 1)}…`)
27
+
28
+ /**
29
+ * Recursive copy of `value` with every over-long string truncated.
30
+ *
31
+ * Returns a copy rather than mutating: these objects are handed to us by
32
+ * provider code that may still be using them, and a note is also frequently a
33
+ * literal in the caller's own scope.
34
+ */
35
+ export function scrubNoteValues<T>(value: T): T {
36
+ if (typeof value === 'string') return truncate(value) as unknown as T
37
+ if (Array.isArray(value)) return value.map(v => scrubNoteValues(v)) as unknown as T
38
+ if (value != null && typeof value === 'object') {
39
+ const out: Record<string, unknown> = {}
40
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) out[k] = scrubNoteValues(v)
41
+ return out as unknown as T
42
+ }
43
+ return value
44
+ }
45
+
46
+ /**
47
+ * Scrub the JSON text stored in `proven_tx_reqs.history`.
48
+ *
49
+ * Falls back to truncating the raw text when it does not parse: unparseable
50
+ * history is already a bug, and letting a megabyte through because it was
51
+ * malformed would defeat the point.
52
+ */
53
+ export function scrubHistoryJson(history: unknown): unknown {
54
+ if (typeof history !== 'string') return typeof history === 'undefined' ? history : scrubNoteValues(history)
55
+ if (history.length <= NOTE_VALUE_MAX) return history
56
+ try {
57
+ return JSON.stringify(scrubNoteValues(JSON.parse(history)))
58
+ } catch {
59
+ return truncate(history)
60
+ }
61
+ }
@@ -0,0 +1,212 @@
1
+ /**
2
+ * SQL-native listActions implementation.
3
+ * Replaces IDB cursor-based filtering with SQL queries.
4
+ * Handles specOp patterns (noSend actions, failed actions, etc.)
5
+ */
6
+ import type { ListActionsResult, 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 { getLabelToSpecOp } from '@bsv/wallet-toolbox-mobile/out/src/storage/methods/ListActionsSpecOp'
10
+ import { isListActionsSpecOp } from '@bsv/wallet-toolbox-mobile/out/src/sdk/types'
11
+ import { parseBrc114ActionTimeLabels, makeBrc114ActionTimeLabel } from '@bsv/wallet-toolbox-mobile/out/src/utility/brc114ActionTimeLabels'
12
+
13
+ export async function listActionsSql(
14
+ storage: StorageExpoSQLite,
15
+ auth: AuthId,
16
+ vargs: Validation.ValidListActionsArgs
17
+ ): Promise<ListActionsResult> {
18
+ const userId = auth.userId!
19
+ const limit = vargs.limit
20
+ const offset = vargs.offset
21
+
22
+ const r: ListActionsResult = { totalActions: 0, actions: [] }
23
+
24
+ // Parse BRC-114 time labels
25
+ const { from: actionTimeFrom, to: actionTimeTo, timeFilterRequested, remainingLabels: ordinaryLabelsPreSpecOp } =
26
+ parseBrc114ActionTimeLabels(vargs.labels)
27
+ const createdAtFrom = actionTimeFrom !== undefined ? new Date(actionTimeFrom) : undefined
28
+ const createdAtTo = actionTimeTo !== undefined ? new Date(actionTimeTo) : undefined
29
+
30
+ // Separate specOp labels from ordinary labels
31
+ let specOp: any = undefined
32
+ let specOpLabels: string[] = []
33
+ let labels: string[] = []
34
+ for (const label of ordinaryLabelsPreSpecOp) {
35
+ if (isListActionsSpecOp(label)) {
36
+ specOp = getLabelToSpecOp()[label]
37
+ } else {
38
+ labels.push(label)
39
+ }
40
+ }
41
+
42
+ // Handle specOp label interception
43
+ if (specOp?.labelsToIntercept !== undefined) {
44
+ const intercept = specOp.labelsToIntercept as string[]
45
+ const labels2 = labels
46
+ labels = []
47
+ if (intercept.length === 0) {
48
+ specOpLabels = labels2
49
+ }
50
+ for (const label of labels2) {
51
+ if (intercept.indexOf(label) >= 0) {
52
+ specOpLabels.push(label)
53
+ } else {
54
+ labels.push(label)
55
+ }
56
+ }
57
+ }
58
+
59
+ // Resolve labels to labelIds
60
+ let labelIds: number[] = []
61
+ if (labels.length > 0) {
62
+ const foundLabels = await storage.findTxLabels({
63
+ partial: { userId, isDeleted: false } as any
64
+ })
65
+ for (const tl of foundLabels) {
66
+ if (labels.includes((tl as any).label)) {
67
+ labelIds.push((tl as any).txLabelId)
68
+ }
69
+ }
70
+ }
71
+
72
+ const isQueryModeAll = vargs.labelQueryMode === 'all'
73
+ if (isQueryModeAll && labelIds.length < labels.length) return r
74
+ if (!isQueryModeAll && labelIds.length === 0 && labels.length > 0) return r
75
+
76
+ // Determine statuses to query
77
+ const stati: string[] = specOp?.setStatusFilter
78
+ ? specOp.setStatusFilter()
79
+ : ['completed', 'unprocessed', 'sending', 'unproven', 'unsigned', 'nosend', 'nonfinal']
80
+
81
+ // Find transactions ordered by transactionId DESC (newest first)
82
+ const txs = await storage.findTransactions(
83
+ {
84
+ partial: { userId },
85
+ status: stati as any,
86
+ from: createdAtFrom,
87
+ to: createdAtTo,
88
+ paged: { limit, offset },
89
+ noRawTx: true,
90
+ orderDescending: true
91
+ },
92
+ labelIds.length > 0 ? labelIds : undefined,
93
+ isQueryModeAll
94
+ )
95
+
96
+ // Count total
97
+ if (txs.length === limit) {
98
+ r.totalActions = await storage.countTransactions(
99
+ { partial: { userId }, status: stati as any, from: createdAtFrom, to: createdAtTo } as any,
100
+ labelIds.length > 0 ? labelIds : undefined,
101
+ isQueryModeAll
102
+ )
103
+ } else {
104
+ r.totalActions = (offset || 0) + txs.length
105
+ }
106
+
107
+ // Apply specOp post-processing
108
+ if (specOp?.postProcess) {
109
+ await specOp.postProcess(storage, auth, vargs, specOpLabels, txs)
110
+ }
111
+
112
+ // Build action objects
113
+ for (const tx of txs) {
114
+ const wtx: any = {
115
+ txid: tx.txid || '',
116
+ satoshis: tx.satoshis || 0,
117
+ status: tx.status,
118
+ isOutgoing: !!tx.isOutgoing,
119
+ description: tx.description || '',
120
+ version: tx.version || 0,
121
+ lockTime: tx.lockTime || 0,
122
+ reference: tx.reference,
123
+ // Not part of the SDK's WalletAction, but the activity list groups rows by
124
+ // day and prints a time next to the status — neither is derivable from the
125
+ // fields the interface does declare. Carried as an extra property, the way
126
+ // `reference` already is.
127
+ created_at: tx.created_at
128
+ }
129
+ r.actions.push(wtx)
130
+ }
131
+
132
+ // Include labels, inputs, outputs if requested
133
+ if (vargs.includeLabels || vargs.includeInputs || vargs.includeOutputs) {
134
+ await Promise.all(txs.map(async (tx, i) => {
135
+ const action = r.actions[i] as any
136
+
137
+ if (vargs.includeLabels) {
138
+ action.labels = (await storage.getLabelsForTransactionId(tx.transactionId)).map(l => l.label)
139
+ if (timeFilterRequested) {
140
+ const ts = tx.created_at ? new Date(tx.created_at as any).getTime() : NaN
141
+ if (!Number.isNaN(ts)) {
142
+ const timeLabel = makeBrc114ActionTimeLabel(ts)
143
+ if (!action.labels.includes(timeLabel)) action.labels.push(timeLabel)
144
+ }
145
+ }
146
+ }
147
+
148
+ if (vargs.includeOutputs) {
149
+ const outputs = await storage.findOutputs({
150
+ partial: { transactionId: tx.transactionId },
151
+ noScript: !vargs.includeOutputLockingScripts
152
+ })
153
+ action.outputs = []
154
+ for (const o of outputs) {
155
+ const ox = await storage.extendOutput(o, true, true) as any
156
+ const wo: any = {
157
+ satoshis: o.satoshis || 0,
158
+ spendable: !!o.spendable,
159
+ tags: (ox.tags?.map((t: any) => t.tag)) || [],
160
+ outputIndex: Number(o.vout),
161
+ outputDescription: (o as any).outputDescription || '',
162
+ basket: ox.basket?.name || ''
163
+ }
164
+ if (o.customInstructions) wo.customInstructions = o.customInstructions
165
+ if (vargs.includeOutputLockingScripts && o.lockingScript) {
166
+ wo.lockingScript = typeof o.lockingScript === 'string'
167
+ ? o.lockingScript
168
+ : Array.from(o.lockingScript as any).map((b: any) => b.toString(16).padStart(2, '0')).join('')
169
+ }
170
+ action.outputs.push(wo)
171
+ }
172
+ }
173
+
174
+ if (vargs.includeInputs) {
175
+ const inputs = await storage.findOutputs({
176
+ partial: { spentBy: tx.transactionId } as any,
177
+ noScript: !vargs.includeInputSourceLockingScripts
178
+ })
179
+ action.inputs = []
180
+ if (inputs.length > 0) {
181
+ const rawTx = await storage.getRawTxOfKnownValidTransaction(tx.txid)
182
+ let bsvTx: any = undefined
183
+ if (rawTx) {
184
+ const { Transaction } = await import('@bsv/sdk')
185
+ bsvTx = Transaction.fromBinary(rawTx)
186
+ }
187
+ for (const o of inputs) {
188
+ await storage.extendOutput(o, true, true)
189
+ const input = bsvTx?.inputs.find((v: any) => v.sourceTXID === (o as any).txid && v.sourceOutputIndex === o.vout)
190
+ const wo: any = {
191
+ sourceOutpoint: `${(o as any).txid}.${o.vout}`,
192
+ sourceSatoshis: o.satoshis || 0,
193
+ inputDescription: (o as any).outputDescription || '',
194
+ sequenceNumber: input?.sequence || 0
195
+ }
196
+ action.inputs.push(wo)
197
+ if (vargs.includeInputSourceLockingScripts) {
198
+ wo.sourceLockingScript = typeof o.lockingScript === 'string'
199
+ ? o.lockingScript
200
+ : Array.from(o.lockingScript as any || []).map((b: any) => b.toString(16).padStart(2, '0')).join('')
201
+ }
202
+ if (vargs.includeInputUnlockingScripts) {
203
+ wo.unlockingScript = input?.unlockingScript?.toHex()
204
+ }
205
+ }
206
+ }
207
+ }
208
+ }))
209
+ }
210
+
211
+ return r
212
+ }