@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,539 @@
1
+ /**
2
+ * Troubleshooting — a pushed, determinate repair destination.
3
+ *
4
+ * All four steps are on screen from the first frame as a checklist, each
5
+ * ticking as it settles. A single in-progress line could not be trusted: on a
6
+ * healthy wallet the steps resolve in one frame, so the user saw a flicker and
7
+ * had no way to tell what had actually been checked. A list that fills in
8
+ * leaves the evidence standing after the run.
9
+ *
10
+ * Back always works. Done is quiet copy and a haptic, not Celebration.
11
+ */
12
+ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
13
+ import { ActivityIndicator, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native'
14
+ import { useSafeAreaInsets } from 'react-native-safe-area-context'
15
+ import { useTranslation } from 'react-i18next'
16
+ import AsyncStorage from '@react-native-async-storage/async-storage'
17
+ import { PeerPayClient } from '@bsv/message-box-client'
18
+ import { showAlert } from '../components/ui/AlertCard'
19
+ import { makeCreditClassifier } from '../../core/pay/creditErrors'
20
+ import { creditInboxOnce, INBOX_DESCRIPTION } from '../../core/pay/creditInbox'
21
+ import { makeBeefRepair } from '../../core/pay/beefRepair'
22
+ import {
23
+ acceptWithRetry,
24
+ DEFAULT_MESSAGE_BOX_URL,
25
+ internalizeIncoming,
26
+ LEGACY_MESSAGE_BOX_URL,
27
+ MESSAGE_BOX_URL_KEY,
28
+ NO_MESSAGE_BOX
29
+ } from '../../core/pay/rails/handle'
30
+ import {
31
+ derivationPrefixFor,
32
+ getCurrentDate,
33
+ getPaymentAddress,
34
+ MAX_RECOVERY_DAYS,
35
+ sweepAddress,
36
+ wocConfigFor
37
+ } from '../../core/pay/rails/address'
38
+ import {
39
+ runWalletCheck,
40
+ type WalletCheckPorts,
41
+ type WalletCheckSkips,
42
+ type WalletCheckStepId,
43
+ type WalletCheckStepStatus
44
+ } from '../../core/walletRepair/runWalletCheck'
45
+ import { userFacingPayError } from '../../core/pay/userError'
46
+ import { backupAttestation } from '../../core/services/vault/backupAttestation'
47
+ import { getBackupUploadState } from '../../core/backup/status'
48
+ import { getOnline, haptics, spacing, typography, useTheme, useWallet } from '@bsv/expo-wallet-toolbox'
49
+
50
+ /**
51
+ * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
52
+ * etc.), one of which reaches expo-font -> expo-asset -- untransformed ESM
53
+ * that Jest cannot parse when eagerly pulled in via the `ui` package barrel.
54
+ * Ionicons is loaded lazily, only when actually rendering, same pattern as
55
+ * this package's other native-module-boundary fixes (expo-router, expo-blur).
56
+ */
57
+ type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
58
+ let ioniconsComponent: IoniconsComponent | undefined
59
+ function loadIonicons(): IoniconsComponent {
60
+ if (!ioniconsComponent) {
61
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
62
+ ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
63
+ }
64
+ return ioniconsComponent
65
+ }
66
+
67
+ /**
68
+ * expo-router is required lazily rather than imported at module scope: this
69
+ * file is barrel-exported from the package's `ui` entry point, and a static
70
+ * top-level `import` of expo-router pulls in its own untransformed JSX
71
+ * source (Navigator.js etc.), which Jest cannot parse for any consumer of the
72
+ * barrel, even one that never navigates.
73
+ */
74
+ type ExpoRouterModule = typeof import('expo-router')
75
+ let expoRouterMod: ExpoRouterModule | undefined
76
+ function loadExpoRouter(): ExpoRouterModule {
77
+ if (!expoRouterMod) {
78
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
79
+ expoRouterMod = require('expo-router') as ExpoRouterModule
80
+ }
81
+ return expoRouterMod
82
+ }
83
+
84
+ /** Display order, and the order runWalletCheck runs them in. Coins last: it is
85
+ * the only step that can take minutes. */
86
+ const STEPS: { id: WalletCheckStepId; labelKey: string }[] = [
87
+ { id: 'online', labelKey: 'wallet_check_step_online' },
88
+ { id: 'records', labelKey: 'wallet_check_step_records' },
89
+ { id: 'proofs', labelKey: 'wallet_check_step_proofs' },
90
+ { id: 'backup', labelKey: 'wallet_check_step_backup' },
91
+ { id: 'phrase_backup', labelKey: 'wallet_check_step_phrase' },
92
+ { id: 'missed_payments', labelKey: 'wallet_check_step_missed' },
93
+ { id: 'coins', labelKey: 'wallet_check_step_coins' }
94
+ ]
95
+
96
+ export function isReviewActionsError(error: unknown): boolean {
97
+ return userFacingPayError(error).offerWalletCheck
98
+ }
99
+
100
+ export async function promptCheckWallet(t: (key: string) => string): Promise<'check_wallet' | 'cancel'> {
101
+ const choice = await showAlert({
102
+ title: t('wallet_check_stuck_title'),
103
+ message: t('wallet_check_stuck_message'),
104
+ buttons: [
105
+ { text: t('cancel'), key: 'cancel', style: 'cancel' },
106
+ { text: t('check_wallet'), key: 'check_wallet' }
107
+ ]
108
+ })
109
+ return choice === 'check_wallet' ? 'check_wallet' : 'cancel'
110
+ }
111
+
112
+ function parseCount(text: string, re: RegExp): number {
113
+ const match = text.match(re)
114
+ return match ? Number(match[1]) || 0 : 0
115
+ }
116
+
117
+ function countNeedle(text: string, needle: string): number {
118
+ if (!text) return 0
119
+ let n = 0
120
+ let i = 0
121
+ while ((i = text.indexOf(needle, i)) !== -1) {
122
+ n++
123
+ i += needle.length
124
+ }
125
+ return n
126
+ }
127
+
128
+ function useWalletCheckPorts(): WalletCheckPorts {
129
+ const {
130
+ managers,
131
+ adminOriginator,
132
+ storage,
133
+ selectedNetwork,
134
+ checkUtxoSpendability,
135
+ releaseStuckReservations,
136
+ runMonitorTask,
137
+ peekLastMissHeight
138
+ } = useWallet()
139
+ const wallet = managers?.permissionsManager
140
+
141
+ return useMemo<WalletCheckPorts>(
142
+ () => ({
143
+ checkOnline: async () => ({ online: await getOnline() }),
144
+ checkBackup: async () => await getBackupUploadState(),
145
+ checkPhraseBackup: async () => {
146
+ // Advisory: it records that someone pressed "I have written these
147
+ // down" or completed a print. Nothing verifies the paper exists — but
148
+ // the absence of the record does mean nobody ever said they had.
149
+ if (!wallet) return { backedUp: false }
150
+ const { publicKey } = await wallet.getPublicKey({ identityKey: true }, adminOriginator)
151
+ return { backedUp: (await backupAttestation.get(publicKey)) !== null }
152
+ },
153
+ reviewSpendable: async () => {
154
+ const log = await checkUtxoSpendability()
155
+ // Stuck-reservation releases are counted by releaseStuck, not here.
156
+ return {
157
+ released: parseCount(log, /(\d+) stale output\(s\) marked unspendable/),
158
+ recovered: parseCount(log, /(\d+) spending tx\(s\) internalized/)
159
+ }
160
+ },
161
+ checkProofs: async () => {
162
+ await runMonitorTask('CheckForProofs')
163
+ return { repaired: 0 }
164
+ },
165
+ reviewStatus: async () => {
166
+ if (!storage?.reviewStatus) return { failedTxs: 0, restoredInputs: 0 }
167
+ const { log } = await storage.reviewStatus({ agedLimit: new Date() })
168
+ return {
169
+ failedTxs: countNeedle(log, "updated to status of 'failed'"),
170
+ restoredInputs: countNeedle(log, 'updated to spendable because spentBy is failed')
171
+ }
172
+ },
173
+ releaseStuck: async () => {
174
+ const log = await releaseStuckReservations()
175
+ return { released: parseCount(log, /Released (\d+) stuck/) }
176
+ },
177
+ creditInbox: async () => {
178
+ if (!wallet) return { accepted: 0 }
179
+ const saved = await AsyncStorage.getItem(MESSAGE_BOX_URL_KEY)
180
+ const messageBoxUrl = !saved || saved === LEGACY_MESSAGE_BOX_URL ? DEFAULT_MESSAGE_BOX_URL : saved
181
+ if (!messageBoxUrl || messageBoxUrl === NO_MESSAGE_BOX) return { accepted: 0 }
182
+ const client = new PeerPayClient({
183
+ messageBoxHost: messageBoxUrl,
184
+ walletClient: wallet as never,
185
+ originator: adminOriginator
186
+ })
187
+ const repairBeef = makeBeefRepair({ woc: wocConfigFor(selectedNetwork), online: getOnline })
188
+ const classify = await makeCreditClassifier({ getOnline, peekLastMissHeight })
189
+ const outcome = await creditInboxOnce({
190
+ client,
191
+ messageBoxUrl,
192
+ storage: storage ?? undefined,
193
+ classify,
194
+ accept: payment =>
195
+ acceptWithRetry(client, messageBoxUrl, payment, INBOX_DESCRIPTION, (p, d) =>
196
+ internalizeIncoming(wallet as never, client, adminOriginator, p, d, repairBeef)
197
+ )
198
+ })
199
+ return { accepted: outcome.accepted }
200
+ },
201
+ sweepAddresses: async () => {
202
+ if (!wallet) return { imported: 0 }
203
+ const woc = wocConfigFor(selectedNetwork)
204
+ let imported = 0
205
+ for (let day = 0; day < MAX_RECOVERY_DAYS; day++) {
206
+ try {
207
+ const prefix = derivationPrefixFor(getCurrentDate(day))
208
+ const address = await getPaymentAddress(wallet, adminOriginator, prefix, woc.network)
209
+ const result = await sweepAddress({
210
+ wallet: wallet as never,
211
+ adminOriginator,
212
+ woc,
213
+ address,
214
+ derivationPrefix: prefix
215
+ })
216
+ if (result.importedSatoshis > 0) imported++
217
+ } catch {
218
+ // One day's miss must not skip the rest of the lookback.
219
+ }
220
+ }
221
+ return { imported }
222
+ }
223
+ }),
224
+ [
225
+ adminOriginator,
226
+ checkUtxoSpendability,
227
+ releaseStuckReservations,
228
+ runMonitorTask,
229
+ selectedNetwork,
230
+ storage,
231
+ peekLastMissHeight,
232
+ wallet
233
+ ]
234
+ )
235
+ }
236
+
237
+ export function WalletCheckScreen(props?: { ports?: WalletCheckPorts }) {
238
+ const { t } = useTranslation()
239
+ const { colors } = useTheme()
240
+ const insets = useSafeAreaInsets()
241
+ const { router } = loadExpoRouter()
242
+ const Ionicons = loadIonicons()
243
+ const contextPorts = useWalletCheckPorts()
244
+ const ports = props?.ports ?? contextPorts
245
+ const portsRef = useRef(ports)
246
+ portsRef.current = ports
247
+
248
+ const [statuses, setStatuses] = useState<Partial<Record<WalletCheckStepId, WalletCheckStepStatus>>>({})
249
+ /**
250
+ * Skip state lives in refs, not state: the running pass reads it through
251
+ * closures the runner already holds, and a re-render must not hand it a
252
+ * different Set. Each id gets a promise the runner can race, resolved by the
253
+ * Skip button.
254
+ */
255
+ const skippedRef = useRef<Set<WalletCheckStepId>>(new Set())
256
+ const waitersRef = useRef<Map<WalletCheckStepId, { promise: Promise<void>; resolve: () => void }>>(new Map())
257
+ const waiterFor = useCallback((id: WalletCheckStepId) => {
258
+ const existing = waitersRef.current.get(id)
259
+ if (existing) return existing
260
+ let resolve: () => void = () => {}
261
+ const promise = new Promise<void>(r => {
262
+ resolve = r
263
+ })
264
+ const entry = { promise, resolve }
265
+ waitersRef.current.set(id, entry)
266
+ return entry
267
+ }, [])
268
+ const skips = useMemo<WalletCheckSkips>(
269
+ () => ({
270
+ isSkipped: id => skippedRef.current.has(id),
271
+ whenSkipped: id => waiterFor(id).promise
272
+ }),
273
+ [waiterFor]
274
+ )
275
+ const skipCurrent = useCallback(
276
+ (id: WalletCheckStepId) => {
277
+ skippedRef.current.add(id)
278
+ waiterFor(id).resolve()
279
+ },
280
+ [waiterFor]
281
+ )
282
+ const [running, setRunning] = useState(true)
283
+ const [error, setError] = useState<string | null>(null)
284
+ const [summary, setSummary] = useState<{
285
+ freedCoins: number
286
+ recoveredPayments: number
287
+ allOk: boolean
288
+ allClear: boolean
289
+ } | null>(null)
290
+
291
+ const run = useCallback(async () => {
292
+ setError(null)
293
+ setSummary(null)
294
+ setStatuses({})
295
+ skippedRef.current = new Set()
296
+ waitersRef.current = new Map()
297
+ setRunning(true)
298
+ try {
299
+ const result = await runWalletCheck(
300
+ portsRef.current,
301
+ // Start-of-step is not tracked: activeStep is derived from what has
302
+ // settled, which cannot disagree with the ticks beside it.
303
+ () => {},
304
+ (id: WalletCheckStepId, status: WalletCheckStepStatus) =>
305
+ setStatuses(prev => ({ ...prev, [id]: status })),
306
+ skips
307
+ )
308
+ setSummary({
309
+ freedCoins: result.freedCoins,
310
+ recoveredPayments: result.recoveredPayments,
311
+ allOk: result.allOk,
312
+ allClear: result.allClear
313
+ })
314
+ if (result.allClear) haptics.success()
315
+ else haptics.error()
316
+ } catch {
317
+ setError(t('wallet_check_failed'))
318
+ haptics.error()
319
+ } finally {
320
+ setRunning(false)
321
+ }
322
+ }, [t, skips])
323
+
324
+ useEffect(() => {
325
+ void run()
326
+ }, [run])
327
+
328
+ // The first step with no status yet is the one in flight: steps settle in
329
+ // order, so this needs no separate "which step started" state to drift from.
330
+ const activeStep = running ? STEPS.find(x => statuses[x.id] === undefined) : undefined
331
+ const doneCopy =
332
+ summary == null || !summary.allOk
333
+ ? null
334
+ : !summary.allClear
335
+ ? // Ran end to end, but something is worth seeing: offline, no backup,
336
+ // no phrase written down. Saying "everything looks good" over an
337
+ // amber row would be the screen contradicting itself.
338
+ t('wallet_check_attention')
339
+ : summary.freedCoins === 0 && summary.recoveredPayments === 0
340
+ ? t('wallet_check_ok')
341
+ : t('wallet_check_summary', { freed: summary.freedCoins, recovered: summary.recoveredPayments })
342
+ const couldntCheck = Boolean(summary && !summary.allOk)
343
+
344
+ return (
345
+ <View style={{ flex: 1, backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }}>
346
+ <View style={[styles.header, { borderBottomColor: colors.separator }]}>
347
+ <TouchableOpacity onPress={() => router.back()} style={styles.headerBack} accessibilityRole="button">
348
+ <Ionicons name="chevron-back" size={24} color={colors.textSecondary} />
349
+ </TouchableOpacity>
350
+ <View style={styles.headerBack} />
351
+ </View>
352
+ <ScrollView
353
+ style={{ flex: 1 }}
354
+ contentContainerStyle={{ paddingHorizontal: spacing.lg, paddingTop: spacing.md, paddingBottom: spacing.xxxl }}
355
+ >
356
+ <Text style={[styles.title, { color: colors.textPrimary }]}>{t('check_wallet')}</Text>
357
+ <View style={styles.progressBlock}>
358
+ {/* Every step is listed from the first frame, so the list never
359
+ reflows as it fills and a finished check stays on screen as its
360
+ own evidence. */}
361
+ {STEPS.map((s, i) => {
362
+ const status = statuses[s.id]
363
+ const active = activeStep?.id === s.id
364
+ return (
365
+ <View key={s.id} style={styles.checkRow}>
366
+ <View style={styles.checkIcon}>
367
+ {active ? (
368
+ <ActivityIndicator size="small" color={colors.textSecondary} />
369
+ ) : status === 'ok' ? (
370
+ <Ionicons name="checkmark-circle" size={22} color={colors.success} />
371
+ ) : status === 'attention' || status === 'error' ? (
372
+ <Ionicons name="alert-circle" size={22} color={colors.warning} />
373
+ ) : status === 'skipped' ? (
374
+ <Ionicons name="remove-circle-outline" size={22} color={colors.textTertiary} />
375
+ ) : (
376
+ <Ionicons name="ellipse-outline" size={22} color={colors.textQuaternary} />
377
+ )}
378
+ </View>
379
+ <Text
380
+ style={[
381
+ styles.checkLabel,
382
+ {
383
+ color:
384
+ status === 'skipped' || (status === undefined && !active)
385
+ ? colors.textTertiary
386
+ : colors.textPrimary
387
+ }
388
+ ]}
389
+ accessibilityLabel={`${t(s.labelKey)}${status === 'ok' ? ' ✓' : ''}`}
390
+ >
391
+ {t(s.labelKey)}
392
+ </Text>
393
+ {status === 'skipped' && (
394
+ <Text style={[styles.skippedTag, { color: colors.textTertiary }]}>{t('wallet_check_skipped')}</Text>
395
+ )}
396
+ </View>
397
+ )
398
+ })}
399
+ {/* Where the progress bar used to be. A bar only told the user to
400
+ keep waiting; this lets them stop waiting on the step that is
401
+ holding them up — which, once coins runs last, is the only step
402
+ that ever does. */}
403
+ {activeStep && (
404
+ <TouchableOpacity
405
+ onPress={() => skipCurrent(activeStep.id)}
406
+ style={[styles.skip, { borderColor: colors.separator }]}
407
+ accessibilityRole="button"
408
+ accessibilityLabel={t('wallet_check_skip')}
409
+ >
410
+ <Text style={[styles.retryLabel, { color: colors.accent }]}>{t('wallet_check_skip')}</Text>
411
+ </TouchableOpacity>
412
+ )}
413
+ </View>
414
+ {/* The verdict sits under the list it summarises, not above it: the
415
+ checklist is the evidence, and this is what it adds up to. */}
416
+ {!running && (doneCopy || couldntCheck || error) && (
417
+ <View style={styles.resultBlock}>
418
+ <Text style={[styles.done, styles.centered, { color: colors.textPrimary }]}>
419
+ {couldntCheck ? t('wallet_check_couldnt') : error ? error : doneCopy}
420
+ </Text>
421
+ {couldntCheck && (
422
+ <Text style={[styles.body, styles.centered, { color: colors.textSecondary }]}>
423
+ {t('wallet_check_couldnt_body')}
424
+ </Text>
425
+ )}
426
+ {(couldntCheck || error) && (
427
+ // Outlined, because Done below is filled: two accent-filled
428
+ // full-width buttons would read as equally weighted, and Done is
429
+ // the one that ends the task.
430
+ <TouchableOpacity
431
+ onPress={() => void run()}
432
+ style={[styles.retry, { borderColor: colors.separator }]}
433
+ accessibilityRole="button"
434
+ >
435
+ <Text style={[styles.retryLabel, { color: colors.accent }]}>{t('retry')}</Text>
436
+ </TouchableOpacity>
437
+ )}
438
+ {/* The way out, and the only thing on this screen the user still
439
+ has to do — so it carries the accent and the full width rather
440
+ than competing with Retry as an equal. */}
441
+ <TouchableOpacity
442
+ onPress={() => router.replace('/' as any)}
443
+ style={[styles.doneButton, { backgroundColor: colors.accent }]}
444
+ accessibilityRole="button"
445
+ >
446
+ <Text style={[styles.retryLabel, { color: colors.textOnAccent }]}>{t('done')}</Text>
447
+ </TouchableOpacity>
448
+ </View>
449
+ )}
450
+ </ScrollView>
451
+ </View>
452
+ )
453
+ }
454
+
455
+ const styles = StyleSheet.create({
456
+ header: {
457
+ flexDirection: 'row',
458
+ alignItems: 'center',
459
+ justifyContent: 'space-between',
460
+ paddingHorizontal: spacing.sm,
461
+ paddingVertical: spacing.md,
462
+ borderBottomWidth: StyleSheet.hairlineWidth
463
+ },
464
+ headerBack: {
465
+ width: 44,
466
+ height: 44,
467
+ alignItems: 'center',
468
+ justifyContent: 'center'
469
+ },
470
+ title: {
471
+ ...typography.largeTitle,
472
+ marginBottom: spacing.xl
473
+ },
474
+ progressBlock: {
475
+ gap: spacing.sm
476
+ },
477
+ checkRow: {
478
+ flexDirection: 'row',
479
+ alignItems: 'center',
480
+ gap: spacing.sm,
481
+ paddingVertical: spacing.sm
482
+ },
483
+ checkIcon: {
484
+ width: 22,
485
+ height: 22,
486
+ alignItems: 'center',
487
+ justifyContent: 'center'
488
+ },
489
+ checkLabel: {
490
+ ...typography.body,
491
+ flex: 1
492
+ },
493
+ skip: {
494
+ alignSelf: 'stretch',
495
+ marginTop: spacing.md,
496
+ minHeight: 44,
497
+ borderWidth: StyleSheet.hairlineWidth,
498
+ borderRadius: 12,
499
+ alignItems: 'center',
500
+ justifyContent: 'center'
501
+ },
502
+ skippedTag: {
503
+ ...typography.footnote
504
+ },
505
+ done: {
506
+ ...typography.title3
507
+ },
508
+ body: {
509
+ ...typography.body
510
+ },
511
+ resultBlock: {
512
+ gap: spacing.lg,
513
+ alignItems: 'center',
514
+ marginTop: spacing.xxl
515
+ },
516
+ centered: {
517
+ textAlign: 'center'
518
+ },
519
+ doneButton: {
520
+ alignSelf: 'stretch',
521
+ minHeight: 50,
522
+ paddingHorizontal: spacing.lg,
523
+ borderRadius: 12,
524
+ alignItems: 'center',
525
+ justifyContent: 'center'
526
+ },
527
+ retry: {
528
+ alignSelf: 'stretch',
529
+ borderWidth: StyleSheet.hairlineWidth,
530
+ minHeight: 44,
531
+ paddingHorizontal: spacing.lg,
532
+ borderRadius: 12,
533
+ alignItems: 'center',
534
+ justifyContent: 'center'
535
+ },
536
+ retryLabel: {
537
+ ...typography.headline
538
+ }
539
+ })