@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,226 @@
1
+ /**
2
+ * Vault recovery — full screen, not a drawer.
3
+ *
4
+ * The escape hatch when the hardware key is lost or its PIV applet is bricked.
5
+ * It sweeps the vault to the everyday balance WITHOUT the key, then clears the
6
+ * vault.
7
+ *
8
+ * Requires the wallet's own recovery phrase (already on this device) plus the
9
+ * vault passphrase chosen at enrollment. BIP39 passphrases have no checksum,
10
+ * so a typo silently derives a different, valid, empty vault node rather than
11
+ * throwing. v4 vault meta stores no key material to catch that here anymore —
12
+ * the sweep itself catches it instead: every vault output mismatches a wrong
13
+ * key (transfers.ts's prepareSpends), and the resulting
14
+ * VaultError('wrong-key') is mapped below to the passphrase copy the user
15
+ * actually needs to see.
16
+ */
17
+ import React, { useCallback, useState } from 'react'
18
+ import { View, Text, StyleSheet, TextInput, ScrollView, ActivityIndicator, TouchableOpacity } from 'react-native'
19
+ import { useSafeAreaInsets } from 'react-native-safe-area-context'
20
+ import PressableScale from '../components/ui/PressableScale'
21
+ import { showToast } from '../components/ui/Toast'
22
+ import {
23
+ useTheme,
24
+ spacing,
25
+ radii,
26
+ typography,
27
+ haptics,
28
+ useWallet,
29
+ useLocalStorage,
30
+ disableVault,
31
+ recoverVaultHD,
32
+ sweepVaultWithHD,
33
+ type VaultWallet,
34
+ VaultError,
35
+ i18n
36
+ } from '@bsv/expo-wallet-toolbox'
37
+
38
+ const t = (k: string, o?: Record<string, unknown>) => i18n.t(k, o) as string
39
+
40
+ /**
41
+ * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
42
+ * etc.), one of which reaches expo-font -> expo-asset -- untransformed ESM
43
+ * that Jest cannot parse when eagerly pulled in via the `ui` package barrel.
44
+ * Ionicons is loaded lazily, only when actually rendering, same pattern as
45
+ * this package's other native-module-boundary fixes (expo-router, expo-blur).
46
+ */
47
+ type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
48
+ let ioniconsComponent: IoniconsComponent | undefined
49
+ function loadIonicons(): IoniconsComponent {
50
+ if (!ioniconsComponent) {
51
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
52
+ ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
53
+ }
54
+ return ioniconsComponent
55
+ }
56
+
57
+ /**
58
+ * expo-router is required lazily rather than imported at module scope: this
59
+ * file is barrel-exported from the package's `ui` entry point, and a static
60
+ * top-level `import` of expo-router pulls in its own untransformed JSX
61
+ * source (Navigator.js etc.), which Jest cannot parse for any consumer of the
62
+ * barrel, even one that never navigates. Same pattern as
63
+ * core/context/WalletContext.tsx's and WalletHomeScreen.tsx's lazy
64
+ * expo-router load.
65
+ */
66
+ type ExpoRouterModule = typeof import('expo-router')
67
+ let expoRouterMod: ExpoRouterModule | undefined
68
+ function loadExpoRouter(): ExpoRouterModule {
69
+ if (!expoRouterMod) {
70
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
71
+ expoRouterMod = require('expo-router') as ExpoRouterModule
72
+ }
73
+ return expoRouterMod
74
+ }
75
+
76
+ export function VaultRecoverScreen() {
77
+ const { colors } = useTheme()
78
+ const insets = useSafeAreaInsets()
79
+ const { router } = loadExpoRouter()
80
+ const Ionicons = loadIonicons()
81
+ const { managers, adminOriginator } = useWallet()
82
+ const { getMnemonic } = useLocalStorage()
83
+
84
+ const [passphrase, setPassphrase] = useState('')
85
+ const [busy, setBusy] = useState(false)
86
+ const [error, setError] = useState<string | null>(null)
87
+
88
+ const run = useCallback(async () => {
89
+ const pm = managers?.permissionsManager
90
+ if (!pm) return
91
+ setBusy(true)
92
+ setError(null)
93
+ try {
94
+ const mnemonic = await getMnemonic()
95
+ if (!mnemonic) throw new VaultError('bad-mnemonic', t('vault_requires_mnemonic'))
96
+ const hd = await recoverVaultHD(mnemonic, passphrase)
97
+
98
+ // sweepVaultWithHD caps at VAULT_MAX_INPUTS per call (see transfers.ts) and
99
+ // reports how many vault outputs it left behind. A vault holding more than
100
+ // that cap needs several sweeps, so repeat until either call reports
101
+ // nothing left to do: `null` means the vault was already empty when that
102
+ // sweep ran, and `remainingInputs === 0` means the sweep that just ran
103
+ // cleared the last of it. Each successful iteration strictly reduces the
104
+ // number of vault outputs still held (it spends min(remaining,
105
+ // VAULT_MAX_INPUTS) > 0 of them), so remainingInputs decreases every pass
106
+ // and the loop is guaranteed to terminate at 0 or null. A thrown error
107
+ // (e.g. 'wrong-key' from a mismatched passphrase) exits the loop and the
108
+ // catch below runs instead — disableVault() is never reached, and the
109
+ // vault is left exactly as it was before the failed iteration.
110
+ let result = await sweepVaultWithHD(pm as unknown as VaultWallet, adminOriginator, hd, t('vault_recover_reason'))
111
+ while (result !== null && result.remainingInputs > 0) {
112
+ result = await sweepVaultWithHD(pm as unknown as VaultWallet, adminOriginator, hd, t('vault_recover_reason'))
113
+ }
114
+
115
+ await disableVault()
116
+ haptics.success()
117
+ showToast(t('vault_recovered_toast'), { type: 'success' })
118
+ setPassphrase('')
119
+ router.back()
120
+ } catch (e) {
121
+ const code = e instanceof VaultError ? e.code : undefined
122
+ // The sweep's prepareSpends throws 'wrong-key' when every vault output
123
+ // mismatches the derived key — on this screen that always means the
124
+ // typed passphrase does not match the one this vault was enrolled
125
+ // with (there is no YubiKey involved here to be the "wrong" one), so
126
+ // show the passphrase-specific copy rather than the sweep's own
127
+ // generic wrong-key message.
128
+ const msg =
129
+ code === 'wrong-key'
130
+ ? t('vault_recover_wrong_passphrase')
131
+ : e instanceof VaultError
132
+ ? e.message || t(`vault_err_${e.code.replace(/-/g, '_')}`)
133
+ : t('vault_recover_failed')
134
+ setError(msg)
135
+ haptics.error()
136
+ } finally {
137
+ setBusy(false)
138
+ }
139
+ }, [passphrase, managers?.permissionsManager, adminOriginator, getMnemonic])
140
+
141
+ const canRun = passphrase.length > 0
142
+
143
+ return (
144
+ <View style={[styles.container, { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }]}>
145
+ <View style={[styles.header, { borderBottomColor: colors.separator }]}>
146
+ <TouchableOpacity onPress={() => router.back()} style={styles.iconBtn}>
147
+ <Ionicons name="chevron-back" size={24} color={colors.textSecondary} />
148
+ </TouchableOpacity>
149
+ <Text style={[styles.headerTitle, { color: colors.textPrimary }]}>{t('vault_recover_title')}</Text>
150
+ <View style={styles.iconBtn} />
151
+ </View>
152
+
153
+ <ScrollView contentContainerStyle={styles.body} keyboardShouldPersistTaps="handled">
154
+ <Text style={[styles.sub, { color: colors.textSecondary }]}>{t('vault_recover_sub')}</Text>
155
+
156
+ <Text style={[styles.label, { color: colors.textPrimary }]}>{t('vault_recover_passphrase_label')}</Text>
157
+ <Text style={[styles.fine, { color: colors.textSecondary }]}>{t('vault_recover_passphrase_help')}</Text>
158
+ <TextInput
159
+ style={[styles.input, { color: colors.textPrimary, backgroundColor: colors.backgroundElevated }]}
160
+ value={passphrase}
161
+ onChangeText={setPassphrase}
162
+ placeholder={t('vault_recover_passphrase_placeholder')}
163
+ placeholderTextColor={colors.textTertiary}
164
+ autoCapitalize="none"
165
+ autoCorrect={false}
166
+ spellCheck={false}
167
+ secureTextEntry
168
+ />
169
+
170
+ {error && <Text style={[styles.err, { color: colors.error }]}>{error}</Text>}
171
+
172
+ <PressableScale
173
+ haptic="confirm"
174
+ onPress={canRun && !busy ? run : undefined}
175
+ style={[
176
+ styles.primary,
177
+ {
178
+ backgroundColor: canRun ? colors.accent : colors.backgroundElevated,
179
+ opacity: busy ? 0.6 : 1
180
+ }
181
+ ]}
182
+ >
183
+ {busy ? (
184
+ <ActivityIndicator color={colors.textOnAccent} />
185
+ ) : (
186
+ <Text style={[styles.primaryLabel, { color: canRun ? colors.textOnAccent : colors.textTertiary }]}>
187
+ {t('vault_recover_cta')}
188
+ </Text>
189
+ )}
190
+ </PressableScale>
191
+ </ScrollView>
192
+ </View>
193
+ )
194
+ }
195
+
196
+ const styles = StyleSheet.create({
197
+ container: { flex: 1 },
198
+ header: {
199
+ flexDirection: 'row',
200
+ alignItems: 'center',
201
+ justifyContent: 'space-between',
202
+ paddingHorizontal: spacing.sm,
203
+ paddingVertical: spacing.md,
204
+ borderBottomWidth: StyleSheet.hairlineWidth
205
+ },
206
+ iconBtn: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center' },
207
+ headerTitle: { ...typography.headline },
208
+ body: { padding: spacing.xl, gap: spacing.md },
209
+ sub: { ...typography.subhead },
210
+ label: { ...typography.footnote, fontWeight: '600', textTransform: 'uppercase' },
211
+ fine: { ...typography.footnote },
212
+ input: {
213
+ borderRadius: radii.md,
214
+ paddingHorizontal: spacing.lg,
215
+ paddingVertical: spacing.md,
216
+ ...typography.body
217
+ },
218
+ err: { ...typography.footnote },
219
+ primary: {
220
+ borderRadius: radii.md,
221
+ paddingVertical: spacing.lg,
222
+ alignItems: 'center',
223
+ marginTop: spacing.sm
224
+ },
225
+ primaryLabel: { ...typography.headline }
226
+ })
@@ -0,0 +1,423 @@
1
+ /**
2
+ * The Vault screen.
3
+ *
4
+ * Not enrolled → a hero explainer and the enrollment wizard.
5
+ * Enrolled → the vault balance, deposit/withdraw actions, the key card, and a
6
+ * recovery/disable overflow.
7
+ *
8
+ * Feature-gated: when no YubiKey-capable driver is present (and not a dev
9
+ * build) the screen explains the requirement rather than offering enrollment.
10
+ */
11
+ import React, { useEffect, useState, useCallback } from 'react'
12
+ import { View, Text, StyleSheet, ScrollView, TouchableOpacity, ActivityIndicator } from 'react-native'
13
+ import { useSafeAreaInsets } from 'react-native-safe-area-context'
14
+ import { GroupedSection } from '../components/ui/GroupedList'
15
+ import { ListRow } from '../components/ui/ListRow'
16
+ import PressableScale from '../components/ui/PressableScale'
17
+ import AmountDisplay from '../components/wallet/AmountDisplay'
18
+ import { showAlert } from '../components/ui/AlertCard'
19
+ import { showToast } from '../components/ui/Toast'
20
+ import { EnrollWizard } from '../components/vault/EnrollWizard'
21
+ import { VaultBackdrop } from '../components/vault/VaultBackdrop'
22
+ import { useVaultBalance } from '../hooks/useVaultBalance'
23
+ import {
24
+ useTheme,
25
+ spacing,
26
+ radii,
27
+ typography,
28
+ useWallet,
29
+ reclaimStagingOutputs,
30
+ type VaultWallet,
31
+ vaultStore,
32
+ type VaultMeta,
33
+ getVaultDriver,
34
+ disableVault,
35
+ haptics,
36
+ i18n
37
+ } from '@bsv/expo-wallet-toolbox'
38
+
39
+ const t = (k: string, o?: Record<string, unknown>) => i18n.t(k, o) as string
40
+
41
+ /**
42
+ * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
43
+ * etc.), one of which reaches expo-font -> expo-asset -- untransformed ESM
44
+ * that Jest cannot parse when eagerly pulled in via the `ui` package barrel.
45
+ * Loaded lazily, only when actually rendering, same pattern as this
46
+ * package's other native-module-boundary fixes (expo-router, expo-blur).
47
+ */
48
+ type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
49
+ let ioniconsComponent: IoniconsComponent | undefined
50
+ function loadIonicons(): IoniconsComponent {
51
+ if (!ioniconsComponent) {
52
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
53
+ ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
54
+ }
55
+ return ioniconsComponent
56
+ }
57
+
58
+ /**
59
+ * expo-router is required lazily rather than imported at module scope: this
60
+ * file is barrel-exported from the package's `ui` entry point, and a static
61
+ * top-level `import` of expo-router pulls in its own untransformed JSX
62
+ * source (Navigator.js etc.), which Jest cannot parse for any consumer of the
63
+ * barrel, even one that never navigates. Same pattern as
64
+ * core/context/WalletContext.tsx's and WalletHomeScreen.tsx's lazy
65
+ * expo-router load.
66
+ */
67
+ type ExpoRouterModule = typeof import('expo-router')
68
+ let expoRouterMod: ExpoRouterModule | undefined
69
+ function loadExpoRouter(): ExpoRouterModule {
70
+ if (!expoRouterMod) {
71
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
72
+ expoRouterMod = require('expo-router') as ExpoRouterModule
73
+ }
74
+ return expoRouterMod
75
+ }
76
+
77
+ export function VaultScreen() {
78
+ const { colors } = useTheme()
79
+ const insets = useSafeAreaInsets()
80
+ const { router } = loadExpoRouter()
81
+ const Ionicons = loadIonicons()
82
+ const { balance, loading, refresh } = useVaultBalance()
83
+ const { managers, adminOriginator, storage } = useWallet()
84
+ const [enrolled, setEnrolled] = useState<boolean | null>(null)
85
+ const [meta, setMeta] = useState<VaultMeta | null>(null)
86
+ const [enrolling, setEnrolling] = useState(false)
87
+
88
+ const supported = getVaultDriver()?.isSupported() ?? false
89
+
90
+ const reload = useCallback(async () => {
91
+ const [e, m] = await Promise.all([vaultStore.isEnrolled(), vaultStore.getMeta()])
92
+ setEnrolled(e)
93
+ setMeta(m)
94
+ }, [])
95
+
96
+ useEffect(() => {
97
+ reload()
98
+ }, [reload])
99
+
100
+ // Recover money the retired two-transaction deposit stranded (tx1 landed,
101
+ // tx2 failed). Stranded coins are invisible to BOTH balances — the main
102
+ // balance counts only the default basket, the vault balance only the vault
103
+ // basket — so this cannot wait for the user to notice anything. One attempt
104
+ // per screen visit; a wallet with nothing stranded returns without touching
105
+ // anything. No ceremony: staging keys are ordinary wallet-derived keys.
106
+ const pm = managers?.permissionsManager
107
+ useEffect(() => {
108
+ if (!enrolled || !pm) return
109
+ let stale = false
110
+ reclaimStagingOutputs(pm as unknown as VaultWallet, adminOriginator, {
111
+ releaseStrandedStaging: storage ? () => storage.releaseVaultStagingStrandedByInvalidTx() : undefined,
112
+ findSpendingReferences: storage ? outpoints => storage.findSpendingReferences(outpoints) : undefined
113
+ })
114
+ .then(r => {
115
+ if (stale || r.reclaimed === 0) return
116
+ console.log(`[vault] reclaimed ${r.reclaimed} staging output(s), ${r.satoshis} sats · txid=${r.txid}`)
117
+ showToast(t('vault_reclaim_done'), { type: 'success' })
118
+ })
119
+ .catch(e => console.log('[vault] staging reclaim failed:', (e as Error)?.message))
120
+ return () => {
121
+ stale = true
122
+ }
123
+ }, [enrolled, pm, adminOriginator, storage])
124
+
125
+ const onEnrolled = useCallback(async () => {
126
+ setEnrolling(false)
127
+ await reload()
128
+ refresh()
129
+ }, [reload, refresh])
130
+
131
+ const confirmDisable = useCallback(async () => {
132
+ // Refuse to disable while funds remain: there IS a seal (disableVault's
133
+ // vaultStore.clear deletes it along with the meta), and disabling before
134
+ // a sweep would leave any vault UTXO reachable only the slow way — the
135
+ // main mnemonic + vault passphrase, via the recovery sweep — with no more
136
+ // in-app YubiKey ceremony to reach it directly. Force a withdrawal (or
137
+ // recovery sweep) first.
138
+ if ((balance ?? 0) > 0) {
139
+ await showAlert({
140
+ title: t('vault_disable_blocked_title'),
141
+ message: t('vault_disable_blocked_message'),
142
+ buttons: [{ text: t('vault_ok'), key: 'ok' }]
143
+ })
144
+ return
145
+ }
146
+ const choice = await showAlert({
147
+ title: t('vault_disable_title'),
148
+ message: t('vault_disable_message'),
149
+ buttons: [
150
+ { text: t('vault_disable_confirm'), key: 'confirm', style: 'destructive' },
151
+ { text: t('vault_cancel'), key: 'cancel', style: 'cancel' }
152
+ ]
153
+ })
154
+ if (choice !== 'confirm') return
155
+ await disableVault()
156
+ haptics.warning()
157
+ showToast(t('vault_disabled_toast'), { type: 'info' })
158
+ await reload()
159
+ }, [balance, reload])
160
+
161
+ const Header = (
162
+ <View style={[styles.header, { borderBottomColor: colors.separator }]}>
163
+ {/* Mid-enrolment, back means "leave setup", not "leave the vault" — the
164
+ wizard's own Cancel button is gone, so this is the only way out and it
165
+ has to land on the screen the user came from inside this flow. */}
166
+ <TouchableOpacity
167
+ onPress={() => (enrolling ? setEnrolling(false) : router.back())}
168
+ style={styles.iconBtn}
169
+ >
170
+ <Ionicons name="chevron-back" size={24} color={colors.textSecondary} />
171
+ </TouchableOpacity>
172
+ <Text style={[styles.headerTitle, { color: colors.textPrimary }]}>{t('vault_title')}</Text>
173
+ <View style={styles.iconBtn} />
174
+ </View>
175
+ )
176
+
177
+ if (enrolled === null) {
178
+ return (
179
+ <View style={[styles.container, { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }]}>
180
+ {Header}
181
+ <View style={styles.centered}>
182
+ <ActivityIndicator color={colors.accent} />
183
+ </View>
184
+ </View>
185
+ )
186
+ }
187
+
188
+ // ── enrollment wizard ────────────────────────────────────────────────
189
+ if (enrolling) {
190
+ return (
191
+ <View style={[styles.container, { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }]}>
192
+ {Header}
193
+ <EnrollWizard onDone={onEnrolled} onCancel={() => setEnrolling(false)} />
194
+ </View>
195
+ )
196
+ }
197
+
198
+ // ── not enrolled ─────────────────────────────────────────────────────
199
+ if (!enrolled) {
200
+ return (
201
+ <View style={[styles.container, { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }]}>
202
+ {Header}
203
+ {/* Backdrop is clipped to the area below the header rather than laid over
204
+ the whole screen, so the line work never crosses the title bar. */}
205
+ <View style={styles.heroArea}>
206
+ {/* Copy on top, drawing beneath it. They do not overlap: when they
207
+ did, the artwork had to be faded almost to nothing to keep the
208
+ body text readable, which wasted it. */}
209
+ <View style={styles.heroArt}>
210
+ <VaultBackdrop color={colors.textPrimary} />
211
+ </View>
212
+ <ScrollView contentContainerStyle={styles.heroScroll}>
213
+ {/* 1:4 spacers sit the copy block high, just under the header,
214
+ clear of the drawing — a ratio rather than a magic padding, so
215
+ it holds on every screen height. */}
216
+ <View style={styles.heroSpacerTop} />
217
+ <View style={styles.heroCopy}>
218
+ <Text style={[styles.h1, { color: colors.textPrimary }]}>{t('vault_hero_title')}</Text>
219
+ <Text style={[styles.p, { color: colors.textSecondary }]}>{t('vault_hero_body')}</Text>
220
+ <PressableScale
221
+ haptic="confirm"
222
+ onPress={supported ? () => setEnrolling(true) : undefined}
223
+ style={[
224
+ styles.primary,
225
+ supported
226
+ ? { backgroundColor: colors.accent }
227
+ : {
228
+ backgroundColor: 'transparent',
229
+ borderWidth: StyleSheet.hairlineWidth,
230
+ borderColor: colors.separator
231
+ }
232
+ ]}
233
+ >
234
+ <Text
235
+ style={[
236
+ styles.primaryLabel,
237
+ { color: supported ? colors.textOnAccent : colors.textTertiary }
238
+ ]}
239
+ >
240
+ {t('vault_enroll_begin')}
241
+ </Text>
242
+ </PressableScale>
243
+ {/* Said here, before the user picks a passphrase — it used to
244
+ surface as a red line under that form at the end of the
245
+ ceremony, which is the app taking someone through setup before
246
+ mentioning their phone cannot do it. Turning on the DEV mock
247
+ YubiKey swaps the driver in, so this clears by itself. */}
248
+ {!supported && (
249
+ <View style={styles.heroNotice}>
250
+ <Text style={[styles.heroNoticeTitle, { color: colors.error }]}>
251
+ {t('vault_unsupported_title')}
252
+ </Text>
253
+ <Text style={[styles.heroNoticeBody, { color: colors.textSecondary }]}>
254
+ {t('vault_unsupported_body')}
255
+ </Text>
256
+ </View>
257
+ )}
258
+ </View>
259
+ <View style={styles.heroSpacerBottom} />
260
+ </ScrollView>
261
+ </View>
262
+ </View>
263
+ )
264
+ }
265
+
266
+ // ── enrolled ─────────────────────────────────────────────────────────
267
+ return (
268
+ <View style={[styles.container, { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }]}>
269
+ {Header}
270
+ <ScrollView contentContainerStyle={styles.content}>
271
+ <View style={styles.balanceBlock}>
272
+ <Text style={[styles.balanceLabel, { color: colors.textSecondary }]}>{t('vault_balance_label')}</Text>
273
+ <TouchableOpacity onPress={refresh} activeOpacity={0.7}>
274
+ {loading && balance === null ? (
275
+ <ActivityIndicator color={colors.accent} />
276
+ ) : (
277
+ <Text style={[styles.balance, { color: colors.textPrimary }]}>
278
+ <AmountDisplay>{balance ?? 0}</AmountDisplay>
279
+ </Text>
280
+ )}
281
+ </TouchableOpacity>
282
+ </View>
283
+
284
+ <View style={styles.actions}>
285
+ <PressableScale
286
+ haptic="confirm"
287
+ onPress={() => router.push('/vault-transfer?direction=deposit')}
288
+ style={[styles.actionBtn, { backgroundColor: colors.accent }]}
289
+ >
290
+ <Ionicons name="arrow-down" size={18} color={colors.textOnAccent} />
291
+ <Text style={[styles.actionLabel, { color: colors.textOnAccent }]}>{t('vault_deposit_cta')}</Text>
292
+ </PressableScale>
293
+ <PressableScale
294
+ haptic="confirm"
295
+ onPress={() => router.push('/vault-transfer?direction=withdraw')}
296
+ style={[
297
+ styles.actionBtn,
298
+ {
299
+ backgroundColor: colors.backgroundElevated,
300
+ borderColor: colors.separator,
301
+ borderWidth: StyleSheet.hairlineWidth
302
+ }
303
+ ]}
304
+ >
305
+ <Ionicons name="arrow-up" size={18} color={colors.accent} />
306
+ <Text style={[styles.actionLabel, { color: colors.accent }]}>{t('vault_withdraw_cta')}</Text>
307
+ </PressableScale>
308
+ </View>
309
+
310
+ <GroupedSection header={t('vault_key_section')}>
311
+ <ListRow
312
+ label={t('vault_key_serial')}
313
+ value={meta?.yubiSerial}
314
+ icon="finger-print"
315
+ iconColor={colors.permissionSpending}
316
+ showChevron={false}
317
+ isLast
318
+ />
319
+ </GroupedSection>
320
+
321
+ <GroupedSection header={t('vault_manage_section')}>
322
+ <ListRow
323
+ label={t('vault_recover_row')}
324
+ icon="medkit-outline"
325
+ iconColor={colors.info ?? colors.accent}
326
+ onPress={() => router.push('/vault-recover')}
327
+ />
328
+ <ListRow
329
+ label={t('vault_disable_row')}
330
+ icon="lock-open"
331
+ iconColor={colors.error}
332
+ destructive
333
+ onPress={confirmDisable}
334
+ isLast
335
+ />
336
+ </GroupedSection>
337
+ </ScrollView>
338
+ </View>
339
+ )
340
+ }
341
+
342
+ const styles = StyleSheet.create({
343
+ container: { flex: 1 },
344
+ header: {
345
+ flexDirection: 'row',
346
+ alignItems: 'center',
347
+ justifyContent: 'space-between',
348
+ paddingHorizontal: spacing.sm,
349
+ paddingVertical: spacing.md,
350
+ borderBottomWidth: StyleSheet.hairlineWidth
351
+ },
352
+ iconBtn: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center' },
353
+ headerTitle: { ...typography.headline },
354
+ centered: { flexGrow: 1, alignItems: 'center', justifyContent: 'center', padding: spacing.xl, gap: spacing.lg },
355
+ // Same centring as `centered`, biased up by half the extra bottom padding
356
+ // (~38pt). Geometric centre reads low here: the header is a solid band at the
357
+ // top, so an empty state centred in the remaining box looks like it sank.
358
+ // Optical centre sits above the true one. The spinner state keeps `centered`.
359
+ heroCentered: {
360
+ flexGrow: 1,
361
+ alignItems: 'center',
362
+ justifyContent: 'center',
363
+ paddingHorizontal: spacing.xl,
364
+ paddingTop: spacing.xl,
365
+ paddingBottom: spacing.xxxl * 3,
366
+ gap: spacing.lg
367
+ },
368
+ // NO horizontal padding here. GroupedSection insets itself (its card carries
369
+ // marginHorizontal: spacing.lg, its header paddingHorizontal: spacing.xl), so
370
+ // padding this container double-inset every grouped card to 32pt while the
371
+ // balance and action row sat at 16pt — three different left edges on one
372
+ // screen. Direct children now carry their own gutter instead, matching the
373
+ // house pattern in app/settings.tsx and app/wallet-config.tsx.
374
+ content: { paddingTop: spacing.lg, paddingBottom: spacing.xxxl },
375
+ gutter: { paddingHorizontal: spacing.lg },
376
+ heroArea: { flex: 1, overflow: 'hidden' },
377
+ heroArt: { position: 'absolute', bottom: '7%', left: 0, right: 0, height: '56%' },
378
+ heroScroll: { flexGrow: 1 },
379
+ heroNotice: { alignItems: 'center', gap: spacing.xs },
380
+ heroNoticeTitle: { ...typography.subhead, fontWeight: '600', textAlign: 'center' },
381
+ heroNoticeBody: { ...typography.footnote, textAlign: 'center' },
382
+ heroSpacerTop: { flex: 1 },
383
+ heroSpacerBottom: { flex: 4 },
384
+ heroCopy: {
385
+ alignSelf: 'stretch',
386
+ alignItems: 'center',
387
+ paddingHorizontal: spacing.xl,
388
+ gap: spacing.lg
389
+ },
390
+ h1: { ...typography.title1, textAlign: 'center' },
391
+ h2: { ...typography.title3, textAlign: 'center' },
392
+ p: { ...typography.subhead, textAlign: 'center' },
393
+ primary: { width: '100%', borderRadius: radii.md, paddingVertical: spacing.lg, alignItems: 'center' },
394
+ primaryLabel: { ...typography.headline },
395
+ balanceBlock: {
396
+ alignItems: 'center',
397
+ gap: spacing.xs,
398
+ paddingVertical: spacing.lg,
399
+ paddingHorizontal: spacing.lg
400
+ },
401
+ // No textTransform, matching the wallet screen: "Vault holds" is a phrase
402
+ // leading into the amount, and casing belongs to the translation.
403
+ balanceLabel: { ...typography.footnote },
404
+ // tabular-nums so the balance does not jitter as digits change — the repo
405
+ // convention (NearbyFlow, AmountInput).
406
+ balance: { ...typography.display, fontVariant: ['tabular-nums'] },
407
+ actions: {
408
+ flexDirection: 'row',
409
+ gap: spacing.md,
410
+ paddingHorizontal: spacing.lg,
411
+ marginBottom: spacing.xxl
412
+ },
413
+ actionBtn: {
414
+ flex: 1,
415
+ flexDirection: 'row',
416
+ alignItems: 'center',
417
+ justifyContent: 'center',
418
+ gap: spacing.sm,
419
+ borderRadius: radii.md,
420
+ paddingVertical: spacing.lg
421
+ },
422
+ actionLabel: { ...typography.headline }
423
+ })