@bsv/expo-wallet-toolbox 0.5.0 → 0.9.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 (200) hide show
  1. package/CHANGELOG.md +2000 -0
  2. package/README.md +66 -1
  3. package/core/amountFormatHelpers.ts +258 -36
  4. package/core/backup/RemoteSyncReader.ts +133 -24
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +149 -11
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +71 -5
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/config.tsx +12 -5
  15. package/core/constants.ts +14 -1
  16. package/core/contacts/contactActivity.ts +153 -0
  17. package/core/contacts/contactCache.ts +41 -0
  18. package/core/contacts/contactsStore.ts +183 -0
  19. package/core/context/ExchangeRateContext.tsx +34 -27
  20. package/core/context/LocalStorageProvider.tsx +43 -40
  21. package/core/context/UserContext.tsx +18 -7
  22. package/core/context/VaultContext.tsx +49 -2
  23. package/core/context/WalletConnectionContext.tsx +203 -11
  24. package/core/context/WalletContext.tsx +685 -171
  25. package/core/demo/demoAssets.ts +60 -0
  26. package/core/demo/demoLedger.ts +240 -0
  27. package/core/demo/demoMandalaRuntime.ts +96 -0
  28. package/core/demo/demoMode.ts +38 -0
  29. package/core/demo/demoWallet.ts +25 -0
  30. package/core/demo/index.ts +26 -0
  31. package/core/demo/useDemo.ts +59 -0
  32. package/core/headers/OfflineFirstChaintracks.ts +99 -17
  33. package/core/headers/headerStore.ts +33 -14
  34. package/core/headers/syncHeaders.ts +12 -1
  35. package/core/i18n/translations.tsx +2186 -98
  36. package/core/identity/contactLink.ts +36 -0
  37. package/core/identity/handleRegistry/client.ts +314 -0
  38. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  39. package/core/identity/handleRegistry/profileCert.ts +254 -0
  40. package/core/identity/handleRegistry/registration.ts +559 -0
  41. package/core/identity/handleRegistry/resolver.ts +315 -0
  42. package/core/identity/handleRegistry/rules.ts +104 -0
  43. package/core/index.ts +53 -5
  44. package/core/localpay/build.ts +225 -24
  45. package/core/localpay/pending.ts +110 -7
  46. package/core/localpay/pendingAbortAuthority.ts +95 -0
  47. package/core/localpay/pendingAborts.ts +266 -26
  48. package/core/localpay/session.ts +42 -17
  49. package/core/localpay/settlementAck.ts +10 -1
  50. package/core/localpay/transport/socket.ts +52 -3
  51. package/core/localpay/verify.ts +100 -10
  52. package/core/mandala/abortGuard.ts +96 -20
  53. package/core/mandala/createRuntime.ts +206 -33
  54. package/core/mandala/drain.ts +89 -11
  55. package/core/mandala/inboxPrehold.ts +186 -0
  56. package/core/mandala/permissionModule.ts +202 -20
  57. package/core/mandala/settlementStore.ts +24 -2
  58. package/core/mandala/types.ts +40 -5
  59. package/core/monitor/MonitorSupervisor.ts +121 -0
  60. package/core/monitor/TaskBackupPush.ts +15 -1
  61. package/core/monitor/TaskCreditInbox.ts +1 -1
  62. package/core/monitor/TaskDrainOutbox.ts +15 -1
  63. package/core/monitor/TaskSendOffline.ts +15 -1
  64. package/core/net/online.ts +49 -0
  65. package/core/net/publicDestination.ts +91 -0
  66. package/core/net/validateArcUrl.ts +22 -0
  67. package/core/numberFormat.ts +19 -0
  68. package/core/offline/cancelParked.ts +134 -13
  69. package/core/offline/payerHold.ts +100 -24
  70. package/core/offline/plan.ts +37 -8
  71. package/core/pay/beefRepair.ts +6 -2
  72. package/core/pay/damagedInbox.ts +24 -0
  73. package/core/pay/rails/address.ts +107 -12
  74. package/core/pay/rails/handle.ts +117 -22
  75. package/core/pay/rails/index.ts +45 -7
  76. package/core/pay/rails/nativeIntent.ts +61 -0
  77. package/core/pay/receiveHistory.ts +93 -0
  78. package/core/pay/recordProof.ts +21 -7
  79. package/core/pay/refreshProofGuard.ts +42 -1
  80. package/core/pay/watchlist.ts +5 -2
  81. package/core/peerpay/control.ts +17 -18
  82. package/core/peerpay/handleResendRequests.ts +58 -4
  83. package/core/peerpay/outbox.ts +3 -1
  84. package/core/recovery/backupMaterial.ts +61 -0
  85. package/core/recovery/createWallet.ts +95 -0
  86. package/core/recovery/recoverWallet.ts +120 -0
  87. package/core/recovery/restoreWallet.ts +170 -0
  88. package/core/recovery/secret.ts +92 -0
  89. package/core/recovery/shareCollector.ts +71 -0
  90. package/core/recovery/shareParsing.ts +87 -0
  91. package/core/recovery/shares.ts +116 -0
  92. package/core/recovery/useRecoveryDeps.ts +70 -0
  93. package/core/services/arcTokenStorage.ts +52 -0
  94. package/core/services/arcadeBroadcastProvider.ts +233 -52
  95. package/core/services/autoApprovePolicy.ts +105 -0
  96. package/core/services/callbackToken.ts +19 -0
  97. package/core/services/capWalletArgs.ts +14 -2
  98. package/core/services/connectionAuthority.ts +98 -0
  99. package/core/services/exchangeRate.ts +36 -13
  100. package/core/services/externalOrigin.ts +16 -2
  101. package/core/services/secrets/kek.ts +126 -29
  102. package/core/services/secrets/migration.ts +16 -4
  103. package/core/services/secrets/store.ts +42 -14
  104. package/core/services/vault/VaultKeyService.ts +228 -45
  105. package/core/services/vault/chainRecovery.ts +483 -0
  106. package/core/services/vault/driver.ts +9 -1
  107. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  108. package/core/services/vault/guard.ts +218 -32
  109. package/core/services/vault/hardwareLease.ts +19 -0
  110. package/core/services/vault/metaAuthority.ts +210 -0
  111. package/core/services/vault/pivReset.ts +64 -23
  112. package/core/services/vault/r1comb.ts +139 -3
  113. package/core/services/vault/session.ts +25 -4
  114. package/core/services/vault/transfers.ts +868 -172
  115. package/core/services/vault/types.ts +19 -4
  116. package/core/services/vault/vaultStore.ts +256 -29
  117. package/core/services/walletArgLimits.ts +45 -2
  118. package/core/services/walletConnectionValidation.ts +76 -6
  119. package/core/services/walletServiceConfig.ts +40 -27
  120. package/core/storage/StorageExpoSQLite.ts +88 -47
  121. package/core/storage/methods/findSql.ts +24 -2
  122. package/core/storage/methods/listActionsSql.ts +8 -5
  123. package/core/storage/methods/listOutputsSql.ts +2 -2
  124. package/core/storage/methods/offlineActions.ts +10 -1
  125. package/core/storage/methods/processOfflineActions.ts +117 -25
  126. package/core/storage/methods/reviewStatusSql.ts +7 -2
  127. package/core/storage/schema/createTables.ts +155 -2
  128. package/core/stores/ConnectionStore.ts +34 -0
  129. package/core/toolboxConfig.ts +104 -0
  130. package/core/toolboxTypes.ts +40 -0
  131. package/core/userAvatar.ts +79 -0
  132. package/core/walletDbRegistry.ts +63 -0
  133. package/core/walletMonitor.ts +25 -4
  134. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  135. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  136. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  137. package/package.json +7 -7
  138. package/ui/activityFilter.ts +115 -0
  139. package/ui/backupShares.ts +26 -169
  140. package/ui/components/pay/AddressReceive.tsx +13 -6
  141. package/ui/components/pay/AssetPicker.tsx +30 -9
  142. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  143. package/ui/components/pay/NearbyFlow.tsx +480 -243
  144. package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
  145. package/ui/components/pay/RecipientField.tsx +84 -70
  146. package/ui/components/pay/StepBar.tsx +32 -0
  147. package/ui/components/pay/UniversalSend.tsx +827 -205
  148. package/ui/components/ui/AlertCard.tsx +38 -5
  149. package/ui/components/ui/PencilEditField.tsx +109 -0
  150. package/ui/components/ui/PermissionSheet.tsx +197 -66
  151. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  152. package/ui/components/vault/EnrollWizard.tsx +61 -13
  153. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  154. package/ui/components/wallet/ActivityRow.tsx +227 -123
  155. package/ui/components/wallet/AmountInput.tsx +26 -8
  156. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  157. package/ui/components/wallet/Balance.tsx +42 -23
  158. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  159. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  160. package/ui/components/wallet/ContactSigil.tsx +49 -0
  161. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  162. package/ui/components/wallet/FitAmount.tsx +148 -0
  163. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  164. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  165. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  166. package/ui/components/wallet/ProfileButton.tsx +62 -0
  167. package/ui/components/wallet/UserAvatar.tsx +85 -0
  168. package/ui/components/wallet/avatarIcons.ts +122 -0
  169. package/ui/exportTransactions.ts +36 -4
  170. package/ui/hooks/useContactsStore.ts +10 -0
  171. package/ui/hooks/useExportWalletData.ts +25 -2
  172. package/ui/hooks/useMandala.ts +18 -1
  173. package/ui/hooks/useOnline.ts +65 -20
  174. package/ui/importDatabases.ts +339 -24
  175. package/ui/index.ts +33 -2
  176. package/ui/isImageUrl.ts +6 -0
  177. package/ui/printRecoveryShares.ts +9 -10
  178. package/ui/recoveryPrompts.ts +91 -0
  179. package/ui/resolveIdentity.ts +31 -9
  180. package/ui/screens/ConnectionsScreen.tsx +86 -19
  181. package/ui/screens/ContactScreen.tsx +289 -0
  182. package/ui/screens/ContactsScreen.tsx +373 -0
  183. package/ui/screens/IdentifierScreen.tsx +256 -0
  184. package/ui/screens/NewContactScreen.tsx +362 -0
  185. package/ui/screens/PairScreen.tsx +74 -2
  186. package/ui/screens/PayScreen.tsx +20 -7
  187. package/ui/screens/ProfileScreen.tsx +783 -0
  188. package/ui/screens/SettingsScreen.tsx +10 -4
  189. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  190. package/ui/screens/TrustScreen.tsx +100 -5
  191. package/ui/screens/VaultScreen.tsx +410 -61
  192. package/ui/screens/VaultTransferScreen.tsx +59 -7
  193. package/ui/screens/WalletCheckScreen.tsx +17 -6
  194. package/ui/screens/WalletConfigScreen.tsx +124 -28
  195. package/ui/screens/WalletHomeScreen.tsx +640 -104
  196. package/ui/screens/detailActionKeys.ts +55 -0
  197. package/ui/tokenFormat.ts +44 -4
  198. package/ui/tokenStatus.ts +21 -0
  199. package/ui/txStatus.ts +48 -5
  200. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Flat aliases for @bsv/wallet-toolbox-mobile types that the package exports
3
+ * only under its `sdk` namespace. Since 2.13 the toolbox ships as one bundle
4
+ * whose exports map exposes just the package root, so the former
5
+ * `out/src/...` deep imports no longer resolve.
6
+ */
7
+ import type { sdk } from '@bsv/wallet-toolbox-mobile'
8
+
9
+ export type AuthId = sdk.AuthId
10
+ export type BsvExchangeRate = sdk.BsvExchangeRate
11
+ export type FindCertificateFieldsArgs = sdk.FindCertificateFieldsArgs
12
+ export type FindCertificatesArgs = sdk.FindCertificatesArgs
13
+ export type FindCommissionsArgs = sdk.FindCommissionsArgs
14
+ export type FindForUserSincePagedArgs = sdk.FindForUserSincePagedArgs
15
+ export type FindMonitorEventsArgs = sdk.FindMonitorEventsArgs
16
+ export type FindOutputBasketsArgs = sdk.FindOutputBasketsArgs
17
+ export type FindOutputTagMapsArgs = sdk.FindOutputTagMapsArgs
18
+ export type FindOutputTagsArgs = sdk.FindOutputTagsArgs
19
+ export type FindOutputsArgs = sdk.FindOutputsArgs
20
+ export type FindProvenTxReqsArgs = sdk.FindProvenTxReqsArgs
21
+ export type FindProvenTxsArgs = sdk.FindProvenTxsArgs
22
+ export type FindSyncStatesArgs = sdk.FindSyncStatesArgs
23
+ export type FindTransactionsArgs = sdk.FindTransactionsArgs
24
+ export type FindTxLabelMapsArgs = sdk.FindTxLabelMapsArgs
25
+ export type FindTxLabelsArgs = sdk.FindTxLabelsArgs
26
+ export type FindUsersArgs = sdk.FindUsersArgs
27
+ export type PostBeefResult = sdk.PostBeefResult
28
+ export type PostTxResultForTxid = sdk.PostTxResultForTxid
29
+ export type ProcessSyncChunkResult = sdk.ProcessSyncChunkResult
30
+ export type ProvenOrRawTx = sdk.ProvenOrRawTx
31
+ export type ProvenTxReqStatus = sdk.ProvenTxReqStatus
32
+ export type PurgeParams = sdk.PurgeParams
33
+ export type PurgeResults = sdk.PurgeResults
34
+ export type RequestSyncChunkArgs = sdk.RequestSyncChunkArgs
35
+ export type StorageProcessActionArgs = sdk.StorageProcessActionArgs
36
+ export type StorageProcessActionResults = sdk.StorageProcessActionResults
37
+ export type SyncChunk = sdk.SyncChunk
38
+ export type TrxToken = sdk.TrxToken
39
+ export type UpdateProvenTxReqWithNewProvenTxArgs = sdk.UpdateProvenTxReqWithNewProvenTxArgs
40
+ export type WalletServicesOptions = sdk.WalletServicesOptions
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The picture this wallet's own user wears.
3
+ *
4
+ * One stored choice, read by every surface that draws "you" — the home
5
+ * button, the profile hero — so picking an icon once changes all of them.
6
+ *
7
+ * Kept out of `WalletSettings`: that type belongs to
8
+ * `@bsv/wallet-toolbox-mobile` and is not ours to extend. AsyncStorage
9
+ * instead, loaded once at startup, exactly like `core/numberFormat.ts`.
10
+ *
11
+ * Stored as `family/name` rather than a component so nothing here depends on
12
+ * the icon package, and an unknown value from a newer build degrades to the
13
+ * default disc instead of crashing.
14
+ */
15
+ import { useSyncExternalStore } from 'react'
16
+ import AsyncStorage from '@react-native-async-storage/async-storage'
17
+
18
+ export type AvatarIconFamily = 'ionicons' | 'material-community'
19
+
20
+ export interface AvatarIcon {
21
+ family: AvatarIconFamily
22
+ name: string
23
+ }
24
+
25
+ const STORAGE_KEY = 'wallet_user_avatar_icon'
26
+
27
+ const listeners = new Set<() => void>()
28
+ let icon: AvatarIcon | null = null
29
+
30
+ /** The chosen icon, or `null` for the default profile disc. */
31
+ export function getUserAvatarIcon(): AvatarIcon | null {
32
+ return icon
33
+ }
34
+
35
+ export function setUserAvatarIcon(next: AvatarIcon | null): void {
36
+ if (icon?.family === next?.family && icon?.name === next?.name) return
37
+ icon = next
38
+ listeners.forEach(l => l())
39
+ // Fire-and-forget: the choice is already live in memory, and a failed write
40
+ // costs the next launch's avatar, never the one on screen now.
41
+ if (next) void AsyncStorage.setItem(STORAGE_KEY, `${next.family}/${next.name}`).catch(() => {})
42
+ else void AsyncStorage.removeItem(STORAGE_KEY).catch(() => {})
43
+ }
44
+
45
+ export function subscribeUserAvatar(listener: () => void): () => void {
46
+ listeners.add(listener)
47
+ return () => {
48
+ listeners.delete(listener)
49
+ }
50
+ }
51
+
52
+ function parse(stored: string | null): AvatarIcon | null {
53
+ if (!stored) return null
54
+ const at = stored.indexOf('/')
55
+ if (at < 0) return null
56
+ const family = stored.slice(0, at)
57
+ const name = stored.slice(at + 1)
58
+ if (!name) return null
59
+ if (family !== 'ionicons' && family !== 'material-community') return null
60
+ return { family, name }
61
+ }
62
+
63
+ /** Restore the stored choice. Call once at startup; safe to call twice. */
64
+ export async function loadUserAvatarIcon(): Promise<void> {
65
+ try {
66
+ const next = parse(await AsyncStorage.getItem(STORAGE_KEY))
67
+ if (next && (next.family !== icon?.family || next.name !== icon?.name)) {
68
+ icon = next
69
+ listeners.forEach(l => l())
70
+ }
71
+ } catch {
72
+ // Keep the default disc; an unreadable preference is not worth surfacing.
73
+ }
74
+ }
75
+
76
+ /** Re-renders the caller whenever the choice changes. */
77
+ export function useUserAvatarIcon(): AvatarIcon | null {
78
+ return useSyncExternalStore(subscribeUserAvatar, getUserAvatarIcon, () => null)
79
+ }
@@ -122,3 +122,66 @@ export async function registerDb(keySuffix: string, chain: string, filename: str
122
122
  existing.push(filename)
123
123
  await getAsyncStorage().setItem(registryKey(keySuffix, chain), JSON.stringify(existing))
124
124
  }
125
+
126
+ /**
127
+ * Remove a filename from the registry (no-op if not present).
128
+ *
129
+ * Used when a database this registry pointed at turns out to be unsafe to reuse — e.g. a
130
+ * failed import-time restore left it only partially replayed (see XR-017) — so a later
131
+ * `selectLatestDb` can never select it again. Removing the registry entry alone is enough
132
+ * for that; deleting the underlying file is the caller's separate decision.
133
+ */
134
+ export async function unregisterDb(keySuffix: string, chain: string, filename: string): Promise<void> {
135
+ const existing = await getRegisteredDbs(keySuffix, chain)
136
+ const next = existing.filter(f => f !== filename)
137
+ if (next.length === existing.length) return
138
+ await getAsyncStorage().setItem(registryKey(keySuffix, chain), JSON.stringify(next))
139
+ }
140
+
141
+ /**
142
+ * XQ-008: "Delete Wallet" only ever closed the SQLite connection
143
+ * (`storage.destroy()`) — it never deleted the underlying `.db` file(s) or
144
+ * cleared this registry's entry for them, so a "deleted" wallet's complete
145
+ * plaintext transaction/output/contact/note history stayed on disk
146
+ * indefinitely and silently reattached with everything intact the next time
147
+ * the same mnemonic was built on the same device.
148
+ *
149
+ * Deletes every filename this identity+chain's registry knows about (not
150
+ * just `dbName`, in case an earlier build left a stale entry pointing at a
151
+ * different file) via the host-supplied `deleteFile` — kept as a parameter
152
+ * rather than a static `expo-sqlite` import so this stays a plain leaf module
153
+ * a non-native host (e.g. Jest) can load without pulling in a native module,
154
+ * same reasoning as `getAsyncStorage` above — and clears each one's registry
155
+ * entry. `dbName` itself is always included even if the registry never
156
+ * recorded it, so the file actually open at logout time can never be the one
157
+ * left behind.
158
+ *
159
+ * Best-effort per file: one file's delete or unregister failing must not stop
160
+ * the rest from being attempted, and a `dbName` that does not parse as a
161
+ * wallet DB filename is treated as nothing to do rather than an error — this
162
+ * runs during logout, after the decision to erase the wallet has already
163
+ * been made elsewhere, and a cleanup failure here must never surface as (or
164
+ * be mistaken for) that erasure failing.
165
+ */
166
+ export async function purgeRegisteredDbFiles(
167
+ dbName: string,
168
+ deleteFile: (filename: string) => Promise<void>
169
+ ): Promise<void> {
170
+ const parsed = parseDbFilename(dbName)
171
+ if (!parsed) return
172
+ const { keySuffix, chain } = parsed
173
+ const registered = await getRegisteredDbs(keySuffix, chain)
174
+ const filenames = registered.includes(dbName) ? registered : [...registered, dbName]
175
+ for (const filename of filenames) {
176
+ try {
177
+ await deleteFile(filename)
178
+ } catch {
179
+ // Best-effort — see doc comment above.
180
+ }
181
+ try {
182
+ await unregisterDb(keySuffix, chain, filename)
183
+ } catch {
184
+ // Best-effort — see doc comment above.
185
+ }
186
+ }
187
+ }
@@ -59,9 +59,14 @@ export function createWalletMonitorOptions(
59
59
  /**
60
60
  * Construct a Monitor and await `ready` so `_init` registers
61
61
  * `subscribeReorgs` / `subscribeHeaders` on `chaintracksWithEvents`.
62
- * Subscribe failures must not kill the rest of the task loop: the HTTP
63
- * ChaintracksServiceClient still throws "Method not implemented" for those
64
- * methods, and TaskReviewProvenTxs is the backup audit in that case.
62
+ * Subscribe failures must not kill the rest of the task loop. `Monitor.runOnce`
63
+ * retries `ready` on every pass (best effort since toolbox 2.14; 2.13 let a
64
+ * rejection stop every task), so OfflineFirstChaintracks answers `getChain`
65
+ * locally and degrades an unsupported subscription (the HTTP
66
+ * ChaintracksServiceClient throws "Method not implemented") to an inert one,
67
+ * and `ready` settles once instead of failing and retrying each tick.
68
+ * TaskReviewProvenTxs is the backup audit in that case. The warning below is
69
+ * left for a chaintracks that rejects anyway.
65
70
  */
66
71
  export async function createWalletMonitor(
67
72
  options: ReturnType<typeof Monitor.createDefaultWalletMonitorOptions>
@@ -91,6 +96,17 @@ export function reviewProvenTxsStartHeight(
91
96
  return Math.max(0, unbounded, floor)
92
97
  }
93
98
 
99
+ /** A `{fromHeight, toHeight}` window `boundReviewProvenTxs` had to skip because
100
+ * last-reviewed was more than `maxSpan` behind the tip. Kept so diagnostics
101
+ * can surface ranges that will never be audited by TaskReviewProvenTxs
102
+ * (reviews/misc-p2.md misc-p2-09) — process-local and cleared only by
103
+ * `resetSkippedReviewRanges` (used by tests). */
104
+ export const skippedReviewRanges: { fromHeight: number; toHeight: number }[] = []
105
+
106
+ export function resetSkippedReviewRanges(): void {
107
+ skippedReviewRanges.length = 0
108
+ }
109
+
94
110
  interface ReviewProvenTxsLike {
95
111
  trigger: (nowMsecsSinceEpoch: number) => { run: boolean }
96
112
  remainingHeightSpan?: number
@@ -143,7 +159,12 @@ export function boundReviewProvenTxs(task: ReviewProvenTxsLike, opts?: BoundRevi
143
159
  const start = reviewProvenTxsStartHeight(last, maxEligible, maxSpan)
144
160
  const unbounded = last === undefined ? 0 : last + 1
145
161
  task.remainingHeightSpan = Math.max(0, maxEligible - start + 1)
146
- if (start > unbounded) return start - 1
162
+ if (start > unbounded) {
163
+ const skipped = { fromHeight: unbounded, toHeight: start - 1 }
164
+ skippedReviewRanges.push(skipped)
165
+ console.warn('[walletMonitor] skipped proven-tx review heights', skipped)
166
+ return start - 1
167
+ }
147
168
  return last
148
169
  }
149
170
  }
@@ -0,0 +1,72 @@
1
+ import {
2
+ REVIEW_REQ_STATUSES_SQL,
3
+ collectFailedTransactionIds,
4
+ type ReviewFailedTx
5
+ } from '../storage/methods/reviewStatusSql'
6
+
7
+ export type ReleaseStuckDb = {
8
+ getAllAsync(sql: string, params?: unknown[]): Promise<unknown[]>
9
+ runAsync(sql: string, params?: unknown[]): Promise<unknown>
10
+ }
11
+
12
+ type StuckRow = { outputId: number; satoshis: number; txid: string; failedTransactionId: number }
13
+
14
+ const STUCK_RESERVATIONS_SQL = `
15
+ SELECT o.outputId AS outputId, o.satoshis AS satoshis, t.txid AS txid, t.transactionId AS failedTransactionId
16
+ FROM outputs o JOIN transactions t ON t.transactionId = o.spentBy
17
+ WHERE t.status = 'failed'
18
+ `.trim()
19
+
20
+ /**
21
+ * A FAILED transaction never confirms, but the toolbox leaves the inputs it
22
+ * had reserved marked `spentBy` that dead txid — so the coin reads as an
23
+ * unresolvable double-spend forever (WERR_REVIEW_ACTIONS on every new spend,
24
+ * even though the output is still `spendable`). Null out spentBy and restore
25
+ * spendable for every output still reserved by a failed tx.
26
+ *
27
+ * XR-032: the local `status = 'failed'` alone is not proof the reservation is
28
+ * safe to release — the same status is left behind by a transaction that was
29
+ * actually broadcast/delivered (a stale/imported row, or an interrupted
30
+ * send), and resurrecting its inputs lets the wallet build a conflicting
31
+ * second payment from already-spent coins. Reuse the exact proven_tx_reqs
32
+ * gate `StorageExpoSQLite.reviewStatus`/`reviewStatusOnDb` already apply
33
+ * before restoring an input: only release a reservation when every
34
+ * proven_tx_req row for the spender's txid (if any) is itself a terminal,
35
+ * safe-to-discard status (invalid/doubleSpend). Pure local SQL — no network.
36
+ */
37
+ export async function releaseStuckReservationsOnDb(db: ReleaseStuckDb): Promise<string> {
38
+ const rows = (await db.getAllAsync(STUCK_RESERVATIONS_SQL)) as StuckRow[]
39
+ if (!rows || rows.length === 0) return 'No stuck reservations found.'
40
+
41
+ const failedTxs: ReviewFailedTx[] = []
42
+ const seen = new Set<number>()
43
+ for (const row of rows) {
44
+ if (seen.has(row.failedTransactionId)) continue
45
+ seen.add(row.failedTransactionId)
46
+ failedTxs.push({ transactionId: row.failedTransactionId, txid: row.txid })
47
+ }
48
+
49
+ const reqStatusesByTxid = new Map<string, string[]>()
50
+ for (const tx of failedTxs) {
51
+ if (!tx.txid || reqStatusesByTxid.has(tx.txid)) continue
52
+ const reqs = (await db.getAllAsync(REVIEW_REQ_STATUSES_SQL, [tx.txid])) as { status: string }[]
53
+ reqStatusesByTxid.set(
54
+ tx.txid,
55
+ reqs.map(r => r.status)
56
+ )
57
+ }
58
+
59
+ const { safeFailedTransactionIds } = collectFailedTransactionIds(failedTxs, reqStatusesByTxid, new Set())
60
+ const safeRows = rows.filter(row => safeFailedTransactionIds.has(row.failedTransactionId))
61
+ if (safeRows.length === 0) return 'No stuck reservations found.'
62
+
63
+ const placeholders = safeRows.map(() => '?').join(',')
64
+ await db.runAsync(
65
+ `UPDATE outputs SET spentBy = NULL, spendable = 1 WHERE outputId IN (${placeholders})`,
66
+ safeRows.map(r => r.outputId)
67
+ )
68
+ const detail = safeRows
69
+ .map(r => ` • ${r.satoshis} sat (output ${r.outputId}) ← failed ${String(r.txid).slice(0, 12)}…`)
70
+ .join('\n')
71
+ return `✓ Released ${safeRows.length} stuck reservation(s):\n${detail}`
72
+ }
@@ -0,0 +1,20 @@
1
+ export type SecondSourceProbe = { status: 'success' | 'error'; isUtxo?: boolean }
2
+
3
+ /**
4
+ * A single WoC "spent" endpoint 200-with-txid response is not enough to
5
+ * permanently mark a UTXO unspendable (misc-p2-01) — WoC can be wrong,
6
+ * stale, or answering for the wrong network, and checkUtxoSpendability never
7
+ * writes `spentBy`, so nothing can ever restore a wrong call. Require a
8
+ * second, independent source (the toolbox's own configured getUtxoStatus
9
+ * providers) to also report the output as no longer a UTXO before committing
10
+ * to spendable:false.
11
+ */
12
+ export function shouldMarkUnspendable(args: {
13
+ wocProbe: SecondSourceProbe
14
+ wocSpendingTxid: string | undefined
15
+ utxoStatus: SecondSourceProbe
16
+ }): boolean {
17
+ if (args.wocProbe.status !== 'success' || args.wocProbe.isUtxo !== false) return false
18
+ if (!args.wocSpendingTxid) return false
19
+ return args.utxoStatus.status === 'success' && args.utxoStatus.isUtxo === false
20
+ }
@@ -0,0 +1,29 @@
1
+ export type ParsedSpenderInput = {
2
+ sourceTXID?: string
3
+ sourceOutputIndex?: number
4
+ sourceTransaction?: { id(enc: 'hex'): string }
5
+ }
6
+
7
+ /**
8
+ * XR-031: neither the WhatsOnChain "spent" probe nor the toolbox's
9
+ * second-source `getUtxoStatus` corroboration ever look at the alleged
10
+ * spending transaction itself — they are both bare claims. Before Wallet
11
+ * Check commits `spendable:false` against a UTXO, require the claimed
12
+ * spender's own parsed BEEF to (a) actually hash to the txid the chain
13
+ * services named, and (b) contain an input that references the exact
14
+ * outpoint being marked spent. A BEEF that fails to fetch/parse, hashes to a
15
+ * different tx, or doesn't reference this outpoint is not proof of spend —
16
+ * the caller must leave the output spendable rather than mutate it.
17
+ */
18
+ export function spenderConsumesOutpoint(args: {
19
+ parsedTxid: string
20
+ expectedTxid: string
21
+ inputs: ParsedSpenderInput[]
22
+ outpoint: { txid: string; vout: number }
23
+ }): boolean {
24
+ if (args.parsedTxid !== args.expectedTxid) return false
25
+ return args.inputs.some(input => {
26
+ const inTxid = input.sourceTXID ?? input.sourceTransaction?.id('hex')
27
+ return inTxid === args.outpoint.txid && input.sourceOutputIndex === args.outpoint.vout
28
+ })
29
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/expo-wallet-toolbox",
3
- "version": "0.5.0",
3
+ "version": "0.9.0",
4
4
  "private": false,
5
5
  "description": "Wallet screens and P2P local-payment backend for Expo/React Native apps, extracted from BSV Wallet.",
6
6
  "license": "SEE LICENSE IN LICENSE.txt",
@@ -29,15 +29,15 @@
29
29
  "CHANGELOG.md"
30
30
  ],
31
31
  "peerDependencies": {
32
- "@bsv/air-gap": "^0.1.1",
32
+ "@bsv/air-gap": "^0.1.3",
33
33
  "@bsv/backup-cache-client": "^0.1.0",
34
- "@bsv/btms-permission-module": "^1.1.0",
34
+ "@bsv/btms-permission-module": "^1.2.1",
35
35
  "@bsv/mandala": "^0.2.0",
36
- "@bsv/message-box-client": "^2.2.1",
36
+ "@bsv/message-box-client": "^2.5.3",
37
37
  "@bsv/react-native-localpay-transport": "*",
38
- "@bsv/sdk": "^2.4.1",
39
- "@bsv/templates": "^1.10.0",
40
- "@bsv/wallet-toolbox-mobile": "^2.4.3",
38
+ "@bsv/sdk": "^2.8.2",
39
+ "@bsv/templates": "^1.10.3",
40
+ "@bsv/wallet-toolbox-mobile": "^2.14.3",
41
41
  "@expo/vector-icons": "^15.0.3",
42
42
  "@noble/curves": "^2.3.0",
43
43
  "@react-native-async-storage/async-storage": "^2.2.0",
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Narrowing the activity list: by the word a row says (Sent, Received, Spent,
3
+ * Transferred) and by a search over what the row shows plus who it was with.
4
+ *
5
+ * The search only ever reads what this device already holds: the row's own
6
+ * title (the sender's note, or the name recorded when the payment was made)
7
+ * and, when the counterparty is a saved contact, that contact's name and
8
+ * handle. It never asks the network who a key belongs to.
9
+ *
10
+ * Every typed word has to appear somewhere, in any order, ignoring case and
11
+ * accents. That is "fuzzy" in the forgiving sense, not a ranked or
12
+ * typo-tolerant one: a row either says what was typed or it does not.
13
+ */
14
+ import { counterpartyOf } from '../core/pay/counterparty'
15
+ import type { ContactRow } from '../core/contacts/contactsStore'
16
+ import type { ActivityAction } from './components/wallet/ActivityRow'
17
+ import { activityKind, type ActivityKind } from './txStatus'
18
+
19
+ export type ActivityKindFilter = 'all' | ActivityKind
20
+
21
+ /** The chips, in the order they are drawn. */
22
+ export const ACTIVITY_KIND_FILTERS: readonly ActivityKindFilter[] = ['all', 'sent', 'received', 'spent', 'transferred']
23
+
24
+ /** A chip names its kind with the row's own status key, so the two always read the same word. */
25
+ export function kindFilterLabelKey(kind: ActivityKindFilter): string {
26
+ return kind === 'all' ? 'activity_filter_all' : `tx_status_${kind}`
27
+ }
28
+
29
+ export interface ActivityFilter {
30
+ kind: ActivityKindFilter
31
+ /** Already normalised by `searchTerms`. */
32
+ terms: readonly string[]
33
+ }
34
+
35
+ export function isActivityFilterActive(filter: ActivityFilter): boolean {
36
+ return filter.kind !== 'all' || filter.terms.length > 0
37
+ }
38
+
39
+ /** Only the Latin combining marks: Indic vowel signs are letters, not accents. */
40
+ const COMBINING_DIACRITICS = /[̀-ͯ]/g
41
+
42
+ function normalise(text: string): string {
43
+ let folded = text
44
+ try {
45
+ folded = text.normalize('NFKD').replace(COMBINING_DIACRITICS, '')
46
+ } catch {
47
+ // An engine without normalisation still gets a case-insensitive search.
48
+ }
49
+ return folded.toLowerCase()
50
+ }
51
+
52
+ /**
53
+ * The words to look for. A leading `@` is dropped because handles are stored
54
+ * without one; an `@` further in (a paymail) is part of what was typed.
55
+ */
56
+ export function searchTerms(query: string): string[] {
57
+ return normalise(query)
58
+ .split(/\s+/)
59
+ .map(word => word.replace(/^@+/, ''))
60
+ .filter(word => word.length > 0)
61
+ }
62
+
63
+ export interface ContactNames {
64
+ name: string
65
+ cachedHandle?: string
66
+ }
67
+
68
+ /** Contacts keyed by lower-cased identity key: the wallet lower-cases every label it stores. */
69
+ export function contactNamesByKey(
70
+ contacts: readonly Pick<ContactRow, 'identityKey' | 'name' | 'cachedHandle'>[]
71
+ ): Map<string, ContactNames> {
72
+ return new Map(contacts.map(c => [c.identityKey.toLowerCase(), { name: c.name, cachedHandle: c.cachedHandle }]))
73
+ }
74
+
75
+ /** The part of a token row this cares about: see `ActivityRow`'s `token` prop. */
76
+ export interface ActivityRowToken {
77
+ title: string
78
+ incoming: boolean
79
+ counterpartyKey?: string
80
+ }
81
+
82
+ /**
83
+ * Whether a row survives the filter.
84
+ *
85
+ * `token` is the row's token half when it has one, exactly as the list draws
86
+ * it: a token row is read by its own title and direction, never by the wallet
87
+ * action underneath (whose description is a library string carrying a raw
88
+ * token id, and whose satoshis are the BSV the transfer cost).
89
+ */
90
+ export function matchesActivity(
91
+ action: ActivityAction,
92
+ token: ActivityRowToken | undefined,
93
+ filter: ActivityFilter,
94
+ contacts: ReadonlyMap<string, ContactNames>
95
+ ): boolean {
96
+ if (filter.kind !== 'all') {
97
+ // Same direction rule the row itself uses to pick its word.
98
+ const incoming = token ? token.incoming : action.satoshis >= 0
99
+ if (activityKind(incoming, action.labels) !== filter.kind) return false
100
+ }
101
+ if (filter.terms.length === 0) return true
102
+
103
+ const counterpartyKey = token
104
+ ? token.counterpartyKey
105
+ : (() => {
106
+ const cp = counterpartyOf(action)
107
+ return cp?.kind === 'identityKey' ? cp.value : undefined
108
+ })()
109
+ const contact = counterpartyKey ? contacts.get(counterpartyKey.toLowerCase()) : undefined
110
+ // One field per line, so no word can match across the seam of two fields.
111
+ const haystack = normalise(
112
+ [token ? token.title : action.description, contact?.name, contact?.cachedHandle].filter(Boolean).join('\n')
113
+ )
114
+ return filter.terms.every(term => haystack.includes(term))
115
+ }