@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,627 @@
1
+ /**
2
+ * Vault enrollment wizard — backup gate → passphrase → PIN → tap → done.
3
+ *
4
+ * The vault key is derived from the wallet's EXISTING mnemonic plus a vault
5
+ * passphrase, so there is no second phrase to write down and no confirmation
6
+ * quiz. What replaces them is the passphrase step: a strength meter, because
7
+ * the KDF is only 2048 rounds, and a confirm field, because BIP39 passphrases
8
+ * have no checksum and a typo silently opens a different, empty vault.
9
+ *
10
+ * enrollVault() drives the YubiKey (getKeyInfo → PIN → generate). Every prompt
11
+ * is gathered BEFORE the tap, since the NFC sheet covers the app.
12
+ *
13
+ * The adopt step exists because slot occupancy is only knowable ON the card:
14
+ * enrollVault refuses an occupied slot with 'slot-occupied', this wizard turns
15
+ * that refusal into an explicit choice, and a second run with adoptExisting
16
+ * enrolls against the key already there. That costs a second tap only in the
17
+ * occupied case, which is what keeps the one-tap rule intact for the normal
18
+ * one.
19
+ */
20
+ import React, { useCallback, useContext, useEffect, useRef, useState } from 'react'
21
+ import { View, Text, StyleSheet, TextInput, ScrollView, ActivityIndicator } from 'react-native'
22
+ import { PassphraseField } from './PassphraseField'
23
+ import PressableScale from '../ui/PressableScale'
24
+ import { showToast } from '../ui/Toast'
25
+ import { printRecoveryShares } from '../../printRecoveryShares'
26
+ import { PhraseBackupSheet } from './PhraseBackupSheet'
27
+ import {
28
+ useTheme,
29
+ spacing,
30
+ radii,
31
+ typography,
32
+ enrollVault,
33
+ finalizeEnrollment,
34
+ VaultError,
35
+ useLocalStorage,
36
+ sounds,
37
+ haptics,
38
+ i18n,
39
+ readBackupAttestation,
40
+ recordBackupAttestation,
41
+ type BackupMedium,
42
+ useWallet,
43
+ UserContext
44
+ } from '@bsv/expo-wallet-toolbox'
45
+
46
+ const t = (k: string, o?: Record<string, unknown>) => i18n.t(k, o) as string
47
+
48
+ /**
49
+ * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
50
+ * etc.), one of which reaches expo-font -> expo-asset -- untransformed ESM
51
+ * that Jest cannot parse when eagerly pulled in via the `ui` package barrel.
52
+ * Both icon sets are loaded lazily, only when actually rendering, same
53
+ * pattern as this package's other native-module-boundary fixes (expo-router,
54
+ * expo-blur).
55
+ */
56
+ type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
57
+ type MaterialCommunityIconsComponent = typeof import('@expo/vector-icons').MaterialCommunityIcons
58
+ let ioniconsComponent: IoniconsComponent | undefined
59
+ let materialCommunityIconsComponent: MaterialCommunityIconsComponent | undefined
60
+ function loadIonicons(): IoniconsComponent {
61
+ if (!ioniconsComponent) {
62
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
63
+ ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
64
+ }
65
+ return ioniconsComponent
66
+ }
67
+ function loadMaterialCommunityIcons(): MaterialCommunityIconsComponent {
68
+ if (!materialCommunityIconsComponent) {
69
+ materialCommunityIconsComponent = require('@expo/vector-icons')
70
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
71
+ .MaterialCommunityIcons as MaterialCommunityIconsComponent
72
+ }
73
+ return materialCommunityIconsComponent
74
+ }
75
+
76
+ type Step = 'backup' | 'phrase' | 'passphrase' | 'adopt' | 'running' | 'done'
77
+
78
+ interface PinRequest {
79
+ kind: 'pin' | 'change'
80
+ retries?: number
81
+ resolve: (v: any) => void
82
+ reject: (e: unknown) => void
83
+ }
84
+
85
+ export const EnrollWizard: React.FC<{ onDone: () => void; onCancel: () => void }> = ({
86
+ onDone,
87
+ onCancel
88
+ }) => {
89
+ const { colors } = useTheme()
90
+ const Ionicons = loadIonicons()
91
+ const MaterialCommunityIcons = loadMaterialCommunityIcons()
92
+ const { getMnemonic, getRecoveredKey } = useLocalStorage()
93
+ const { appName } = useContext(UserContext)
94
+ const [step, setStep] = useState<Step>('backup')
95
+ const [medium, setMedium] = useState<BackupMedium | null>(null)
96
+ const [wordCount, setWordCount] = useState<number | null>(null)
97
+ const [revealed, setRevealed] = useState<string | null>(null)
98
+ const [passphrase, setPassphrase] = useState('')
99
+ const [confirm, setConfirm] = useState('')
100
+ const [passphraseOk, setPassphraseOk] = useState(false)
101
+ const [phaseLabel, setPhaseLabel] = useState('')
102
+ const [pinReq, setPinReq] = useState<PinRequest | null>(null)
103
+ const [pinError, setPinError] = useState<string | null>(null)
104
+ const [pinInput, setPinInput] = useState('')
105
+ const [newPinInput, setNewPinInput] = useState('')
106
+ const [printing, setPrinting] = useState(false)
107
+ const [error, setError] = useState<string | null>(null)
108
+
109
+ const { managers, adminOriginator } = useWallet()
110
+
111
+ const wallet = managers?.permissionsManager
112
+
113
+ // A user who already backed up should not be asked twice — including the
114
+ // user who wrote their phrase down during wallet creation minutes ago, which
115
+ // now records an attestation of its own. Skipping the step outright rather
116
+ // than showing it pre-ticked: a screen full of green ticks is still a
117
+ // checkpoint to read and clear.
118
+ useEffect(() => {
119
+ let alive = true
120
+ void (async () => {
121
+ const existing = await readBackupAttestation(wallet, adminOriginator)
122
+ if (!alive || !existing) return
123
+ setMedium(existing.medium)
124
+ // Straight to the passphrase. The mnemonic guard that toPassphrase runs
125
+ // is skipped on this path on purpose — it calls getMnemonic(), which is
126
+ // biometric-gated, and prompting for Face ID on mount would be worse than
127
+ // surfacing 'requires mnemonic' when enrolment actually starts.
128
+ setStep(current => (current === 'backup' ? 'passphrase' : current))
129
+ })()
130
+ return () => {
131
+ alive = false
132
+ }
133
+ }, [wallet, adminOriginator])
134
+
135
+ /**
136
+ * Only a persisted attestation may unlock Continue. A wallet that ticks the
137
+ * row without a written flag would enrol into a vault the deposit gate then
138
+ * refuses forever, since the gate would find nothing recorded.
139
+ */
140
+ const attest = useCallback(
141
+ async (m: BackupMedium): Promise<boolean> => {
142
+ if (!(await recordBackupAttestation(wallet, adminOriginator, m))) {
143
+ setError(t('vault_backup_attest_failed'))
144
+ return false
145
+ }
146
+ setError(null)
147
+ setMedium(m)
148
+ return true
149
+ },
150
+ [wallet, adminOriginator]
151
+ )
152
+
153
+ const requestPin = useCallback(
154
+ () => new Promise<string>((resolve, reject) => setPinReq({ kind: 'pin', resolve, reject })),
155
+ []
156
+ )
157
+ const requestPinChange = useCallback(
158
+ (retries: number) =>
159
+ new Promise<{ oldPin: string; newPin: string }>((resolve, reject) =>
160
+ setPinReq({ kind: 'change', retries, resolve, reject })
161
+ ),
162
+ []
163
+ )
164
+
165
+ const onPrintShares = useCallback(async () => {
166
+ if (printing) return
167
+ setPrinting(true)
168
+ try {
169
+ const result = await printRecoveryShares({
170
+ mnemonic: await getMnemonic(),
171
+ recoveredKeyWif: await getRecoveredKey?.(),
172
+ appName
173
+ })
174
+ if (result.ok) {
175
+ // Only a resolved print sheet counts. A cancelled one produced no paper.
176
+ await attest('shares')
177
+ } else if (result.reason === 'unsupported-word-count') {
178
+ showToast(t('vault_shares_word_count'), { type: 'error' })
179
+ } else {
180
+ showToast(t('vault_shares_unavailable'), { type: 'error' })
181
+ }
182
+ } catch {
183
+ // Print sheet dismissed or unavailable — not an error worth blocking on.
184
+ } finally {
185
+ setPrinting(false)
186
+ }
187
+ }, [printing, getMnemonic, getRecoveredKey, attest])
188
+
189
+ const onRevealPhrase = useCallback(async () => {
190
+ setError(null)
191
+ // getMnemonic() is behind the biometric latch, so the reveal is
192
+ // re-authenticated without a second prompt of our own.
193
+ const mnemonic = await getMnemonic()
194
+ if (!mnemonic) {
195
+ setError(t('vault_requires_mnemonic'))
196
+ haptics.error()
197
+ return
198
+ }
199
+ setWordCount(mnemonic.trim().split(/\s+/).length)
200
+ setRevealed(mnemonic)
201
+ setStep('phrase')
202
+ }, [getMnemonic])
203
+
204
+ // Gate: a wallet restored from backup shares has no mnemonic, so it can
205
+ // neither enroll nor ever recover a vault. Refuse rather than create a vault
206
+ // with only one recovery path.
207
+ const toPassphrase = useCallback(async () => {
208
+ setError(null)
209
+ const mnemonic = await getMnemonic()
210
+ if (!mnemonic) {
211
+ setError(t('vault_requires_mnemonic'))
212
+ haptics.error()
213
+ return
214
+ }
215
+ setStep('passphrase')
216
+ }, [getMnemonic])
217
+
218
+ /** Set to `start` below; the wrong-PIN path re-enters the ceremony. */
219
+ const startRef = useRef<((adoptExisting?: boolean) => Promise<void>) | null>(null)
220
+
221
+ const start = useCallback(async (adoptExisting = false) => {
222
+ setStep('running')
223
+ setError(null)
224
+ try {
225
+ const mnemonic = await getMnemonic()
226
+ if (!mnemonic) throw new VaultError('bad-mnemonic', t('vault_requires_mnemonic'))
227
+ const { pending } = await enrollVault({
228
+ // Empty by design: the vault screen identifies the key by its serial,
229
+ // which the key itself reports. A nickname field was one more thing to
230
+ // fill in during setup and named nothing the user could not already see.
231
+ nickname: '',
232
+ mnemonic,
233
+ passphrase,
234
+ adoptExisting,
235
+ onPhase: p => setPhaseLabel(t(`vault_enroll_phase_${p}`)),
236
+ getPin: requestPin,
237
+ requestPinChange
238
+ })
239
+ await finalizeEnrollment(pending)
240
+ setPassphrase('')
241
+ setConfirm('')
242
+ sounds.vaultOpen()
243
+ haptics.success()
244
+ showToast(t('vault_enrolled_toast'), { type: 'success' })
245
+ setStep('done')
246
+ onDone()
247
+ } catch (e) {
248
+ // An occupied slot is a fork in the road, not a failure: the key already
249
+ // there is exactly what a second device needs. Offer it instead of
250
+ // dropping the user back to the passphrase step with a dead-end error.
251
+ if (e instanceof VaultError && e.code === 'slot-occupied' && !adoptExisting) {
252
+ setStep('adopt')
253
+ return
254
+ }
255
+ haptics.error()
256
+
257
+ // A wrong PIN is feedback on the PIN, so it belongs on the PIN prompt.
258
+ // Dropping back to the passphrase screen with "Wrong PIN." underneath it
259
+ // asked the user to re-confirm a passphrase that was never the problem.
260
+ // Nothing has been written to the key at this point — verifyPin runs
261
+ // before generateVaultKey — so re-entering the ceremony is safe, and it
262
+ // is what puts the PIN sheet back on screen.
263
+ if (e instanceof VaultError && e.code === 'pin-invalid') {
264
+ setPinError(
265
+ e.retriesLeft !== undefined
266
+ ? `${t('vault_err_pin_invalid')} ${t('vault_pin_retries', { count: e.retriesLeft })}`
267
+ : t('vault_err_pin_invalid')
268
+ )
269
+ void startRef.current?.(adoptExisting)
270
+ return
271
+ }
272
+
273
+ const msg =
274
+ e instanceof VaultError ? t(`vault_err_${e.code.replace(/-/g, '_')}`, {}) : String(e)
275
+ setError(msg || t('vault_err_generic'))
276
+ setStep('passphrase')
277
+ }
278
+ }, [passphrase, getMnemonic, requestPin, requestPinChange, onDone])
279
+
280
+ startRef.current = start
281
+
282
+ const submitPin = useCallback(() => {
283
+ if (!pinReq) return
284
+ if (pinReq.kind === 'change') {
285
+ if (newPinInput.length < 6) return
286
+ pinReq.resolve({ oldPin: '123456', newPin: newPinInput })
287
+ } else {
288
+ if (pinInput.length < 4) return
289
+ pinReq.resolve(pinInput)
290
+ }
291
+ setPinReq(null)
292
+ setPinInput('')
293
+ setNewPinInput('')
294
+ }, [pinReq, pinInput, newPinInput])
295
+
296
+ // ── backup (prerequisite) ───────────────────────────────────────────
297
+ if (step === 'backup') {
298
+ return (
299
+ <ScrollView contentContainerStyle={styles.gateBody}>
300
+ {/* No hero glyph here. A shield-with-a-tick says "you are protected",
301
+ which is the opposite of this screen's message — it is asking for
302
+ work, not confirming it is done. The two rows below are the
303
+ instruction, so nothing should out-shout them. */}
304
+ <Text style={[styles.h1, { color: colors.textPrimary }]}>{t('vault_backup_title')}</Text>
305
+ <Text style={[styles.p, { color: colors.textSecondary }]}>{t('vault_backup_intro')}</Text>
306
+
307
+ <BackupRow
308
+ icon="document-text-outline"
309
+ title={t('vault_backup_phrase_title')}
310
+ // The actual count is only known once the phrase has been
311
+ // revealed (getMnemonic() is biometric-gated, so it isn't read
312
+ // just to label this row). 12 is the count for every wallet this
313
+ // app generates; imported 24-word wallets get the correct number
314
+ // here as soon as they reveal once.
315
+ subtitle={t('vault_backup_phrase_sub', { count: wordCount ?? 12 })}
316
+ done={medium === 'phrase'}
317
+ busy={false}
318
+ onPress={onRevealPhrase}
319
+ />
320
+ <BackupRow
321
+ icon="print-outline"
322
+ title={t('vault_backup_shares_title')}
323
+ subtitle={t('vault_backup_shares_sub')}
324
+ done={medium === 'shares'}
325
+ busy={printing}
326
+ onPress={onPrintShares}
327
+ />
328
+
329
+
330
+ {error && <Text style={[styles.err, { color: colors.error }]}>{error}</Text>}
331
+ <PressableScale
332
+ haptic="confirm"
333
+ onPress={medium ? toPassphrase : undefined}
334
+ style={[
335
+ styles.primary,
336
+ // Outlined while it is not yet armed. Filled with the secondary
337
+ // background it was indistinguishable from the page in dark mode,
338
+ // so the disabled CTA read as a stray line of grey text rather
339
+ // than as a button waiting on the rows above it.
340
+ {
341
+ backgroundColor: medium ? colors.accent : 'transparent',
342
+ borderWidth: medium ? 0 : StyleSheet.hairlineWidth,
343
+ borderColor: colors.separator
344
+ }
345
+ ]}
346
+ >
347
+ <Text
348
+ style={[
349
+ styles.primaryLabel,
350
+ { color: medium ? colors.textOnAccent : colors.textTertiary }
351
+ ]}
352
+ >
353
+ {t('vault_continue')}
354
+ </Text>
355
+ </PressableScale>
356
+ </ScrollView>
357
+ )
358
+ }
359
+
360
+ // ── phrase reveal ───────────────────────────────────────────────────
361
+ if (step === 'phrase' && revealed) {
362
+ return (
363
+ <PhraseBackupSheet
364
+ mnemonic={revealed}
365
+ onAttest={async () => {
366
+ // Whatever attest() decides, the phrase should not linger on
367
+ // screen: on success the row ticks; on failure the backup step's
368
+ // inline error tells the user to retry rather than stranding them
369
+ // here with no feedback.
370
+ await attest('phrase')
371
+ setRevealed(null)
372
+ setStep('backup')
373
+ }}
374
+ onCancel={() => {
375
+ setRevealed(null)
376
+ setStep('backup')
377
+ }}
378
+ />
379
+ )
380
+ }
381
+
382
+ // ── passphrase ──────────────────────────────────────────────────────
383
+ if (step === 'passphrase') {
384
+ return (
385
+ <ScrollView contentContainerStyle={styles.body} keyboardShouldPersistTaps="handled">
386
+ <Text style={[styles.h1, { color: colors.textPrimary }]}>{t('vault_enroll_title')}</Text>
387
+ <Text style={[styles.p, { color: colors.textSecondary }]}>{t('vault_enroll_intro')}</Text>
388
+
389
+ <PassphraseField
390
+ value={passphrase}
391
+ onChangeText={setPassphrase}
392
+ confirm={confirm}
393
+ onChangeConfirm={setConfirm}
394
+ onValidityChange={setPassphraseOk}
395
+ />
396
+
397
+ <View style={[styles.warnBox, { backgroundColor: colors.warning + '14' }]}>
398
+ <Ionicons name="warning-outline" size={16} color={colors.warning} />
399
+ <Text style={[styles.warnText, { color: colors.textSecondary }]}>
400
+ {t('vault_passphrase_no_reset')}
401
+ </Text>
402
+ </View>
403
+
404
+ {error && <Text style={[styles.err, { color: colors.error }]}>{error}</Text>}
405
+ <PressableScale
406
+ haptic="confirm"
407
+ onPress={passphraseOk ? () => start() : undefined}
408
+ style={[
409
+ styles.primary,
410
+ {
411
+ backgroundColor: passphraseOk ? colors.accent : 'transparent',
412
+ borderWidth: passphraseOk ? 0 : StyleSheet.hairlineWidth,
413
+ borderColor: colors.separator
414
+ }
415
+ ]}
416
+ >
417
+ <Text
418
+ style={[
419
+ styles.primaryLabel,
420
+ { color: passphraseOk ? colors.textOnAccent : colors.textTertiary }
421
+ ]}
422
+ >
423
+ {t('vault_enroll_begin')}
424
+ </Text>
425
+ </PressableScale>
426
+ </ScrollView>
427
+ )
428
+ }
429
+
430
+ // ── adopt (slot already holds a key) ────────────────────────────────
431
+ if (step === 'adopt') {
432
+ return (
433
+ <ScrollView contentContainerStyle={styles.body}>
434
+ <Ionicons
435
+ name="hardware-chip-outline"
436
+ size={48}
437
+ color={colors.textPrimary}
438
+ style={styles.hero}
439
+ />
440
+ <Text style={[styles.h1, { color: colors.textPrimary }]}>{t('vault_slot_in_use_title')}</Text>
441
+ <Text style={[styles.p, { color: colors.textSecondary }]}>{t('vault_slot_in_use_body')}</Text>
442
+
443
+ <PressableScale
444
+ haptic="confirm"
445
+ onPress={() => start(true)}
446
+ style={[styles.primary, { backgroundColor: colors.accent }]}
447
+ >
448
+ <Text style={[styles.primaryLabel, { color: colors.textOnAccent }]}>
449
+ {t('vault_use_existing_key')}
450
+ </Text>
451
+ </PressableScale>
452
+ <PressableScale onPress={onCancel} style={styles.secondary}>
453
+ <Text style={[styles.secondaryLabel, { color: colors.textSecondary }]}>
454
+ {t('vault_cancel')}
455
+ </Text>
456
+ </PressableScale>
457
+ </ScrollView>
458
+ )
459
+ }
460
+
461
+ // ── running (PIN prompts + tap) ─────────────────────────────────────
462
+ if (step === 'running') {
463
+ return (
464
+ <View style={styles.body}>
465
+ {pinReq ? (
466
+ <>
467
+ <Ionicons name="keypad-outline" size={40} color={colors.textPrimary} style={styles.hero} />
468
+ <Text style={[styles.h1, { color: colors.textPrimary }]}>
469
+ {pinReq.kind === 'change' ? t('vault_set_new_pin') : t('vault_enter_pin')}
470
+ </Text>
471
+ {/* Which PIN, and what it is if they have never set one. Without
472
+ this the prompt is ambiguous with the phone's own passcode, and
473
+ a factory key's PIN is not something users know they have. */}
474
+ <Text style={[styles.p, { color: colors.textSecondary }]}>
475
+ {pinReq.kind === 'change' ? t('vault_default_pin_warning') : t('vault_enter_pin_sub')}
476
+ </Text>
477
+ {pinError && <Text style={[styles.err, { color: colors.error }]}>{pinError}</Text>}
478
+ <TextInput
479
+ style={[
480
+ styles.pin,
481
+ { color: colors.textPrimary, backgroundColor: colors.backgroundSecondary }
482
+ ]}
483
+ value={pinReq.kind === 'change' ? newPinInput : pinInput}
484
+ onChangeText={text => {
485
+ setPinError(null)
486
+ ;(pinReq.kind === 'change' ? setNewPinInput : setPinInput)(text)
487
+ }}
488
+ placeholder="••••••"
489
+ placeholderTextColor={colors.textTertiary}
490
+ keyboardType="number-pad"
491
+ // Masking only once there is something to mask: iOS renders a
492
+ // secure field's PLACEHOLDER with masked-glyph metrics, which is
493
+ // what stretches the bullets apart before any digit is typed.
494
+ secureTextEntry={(pinReq.kind === 'change' ? newPinInput : pinInput).length > 0}
495
+ maxLength={8}
496
+ autoFocus
497
+ />
498
+ <PressableScale
499
+ haptic="confirm"
500
+ onPress={submitPin}
501
+ style={[styles.primary, { backgroundColor: colors.accent }]}
502
+ >
503
+ <Text style={[styles.primaryLabel, { color: colors.textOnAccent }]}>
504
+ {t('vault_continue')}
505
+ </Text>
506
+ </PressableScale>
507
+ </>
508
+ ) : (
509
+ <>
510
+ <ActivityIndicator color={colors.textPrimary} size="large" style={styles.hero} />
511
+ <Text style={[styles.h1, { color: colors.textPrimary }]}>
512
+ {phaseLabel || t('vault_reading_key')}
513
+ </Text>
514
+ <Text style={[styles.p, { color: colors.textSecondary }]}>
515
+ {t('vault_touch_when_blinks')}
516
+ </Text>
517
+ </>
518
+ )}
519
+ </View>
520
+ )
521
+ }
522
+
523
+ return null
524
+ }
525
+
526
+ /** One backup route: tappable, ticks when satisfied, stays tappable after. */
527
+ const BackupRow: React.FC<{
528
+ icon: React.ComponentProps<IoniconsComponent>['name']
529
+ title: string
530
+ subtitle: string
531
+ done: boolean
532
+ busy: boolean
533
+ onPress: () => void
534
+ }> = ({ icon, title, subtitle, done, busy, onPress }) => {
535
+ const { colors } = useTheme()
536
+ const Ionicons = loadIonicons()
537
+ return (
538
+ <PressableScale
539
+ onPress={busy ? undefined : onPress}
540
+ style={[styles.backupRow, { borderColor: done ? colors.success : colors.separator }]}
541
+ >
542
+ {busy ? (
543
+ <ActivityIndicator color={colors.info} size="small" />
544
+ ) : (
545
+ <Ionicons name={icon} size={22} color={done ? colors.success : colors.info} />
546
+ )}
547
+ <View style={styles.backupRowText}>
548
+ <Text style={[styles.backupRowTitle, { color: colors.textPrimary }]}>{title}</Text>
549
+ <Text style={[styles.backupRowSub, { color: colors.textSecondary }]}>{subtitle}</Text>
550
+ </View>
551
+ {done && <Ionicons name="checkmark-circle" size={20} color={colors.success} />}
552
+ </PressableScale>
553
+ )
554
+ }
555
+
556
+ const styles = StyleSheet.create({
557
+ body: { padding: spacing.xl, gap: spacing.lg },
558
+ // The gate is three short blocks; top-aligned they sat in the upper third
559
+ // with half a screen of nothing under them.
560
+ gateBody: { padding: spacing.xl, gap: spacing.lg, flexGrow: 1, justifyContent: 'center' },
561
+ hero: { marginTop: spacing.lg, alignSelf: 'center' },
562
+ h1: { ...typography.title2, textAlign: 'center' },
563
+ p: { ...typography.subhead, textAlign: 'center' },
564
+ input: {
565
+ width: '100%',
566
+ borderRadius: radii.md,
567
+ paddingVertical: spacing.md,
568
+ paddingHorizontal: spacing.lg,
569
+ ...typography.body
570
+ },
571
+ pin: {
572
+ width: '70%',
573
+ alignSelf: 'center',
574
+ textAlign: 'center',
575
+ ...typography.title2,
576
+ letterSpacing: 8,
577
+ borderRadius: radii.md,
578
+ paddingVertical: spacing.md
579
+ },
580
+ primary: { width: '100%', borderRadius: radii.md, paddingVertical: spacing.lg, alignItems: 'center' },
581
+ primaryLabel: { ...typography.headline },
582
+ secondary: { paddingVertical: spacing.md, alignItems: 'center' },
583
+ secondaryLabel: { ...typography.body },
584
+ err: { ...typography.footnote, textAlign: 'center' },
585
+ fine: { ...typography.caption2, textAlign: 'center' },
586
+ ghost: {
587
+ flexDirection: 'row',
588
+ alignItems: 'center',
589
+ justifyContent: 'center',
590
+ gap: spacing.xs,
591
+ borderRadius: radii.md,
592
+ borderWidth: StyleSheet.hairlineWidth,
593
+ paddingVertical: spacing.md
594
+ },
595
+ ghostLabel: { ...typography.footnote, fontWeight: '600' },
596
+ backupRow: {
597
+ flexDirection: 'row',
598
+ alignItems: 'center',
599
+ gap: spacing.md,
600
+ borderRadius: radii.md,
601
+ borderWidth: StyleSheet.hairlineWidth,
602
+ padding: spacing.lg
603
+ },
604
+ backupRowText: { flex: 1, gap: spacing.xs },
605
+ backupRowTitle: { ...typography.headline },
606
+ backupRowSub: { ...typography.footnote },
607
+ paths: {
608
+ width: '100%',
609
+ gap: spacing.sm,
610
+ borderRadius: radii.md,
611
+ borderWidth: StyleSheet.hairlineWidth,
612
+ padding: spacing.lg
613
+ },
614
+ pathsTitle: { ...typography.footnote, fontWeight: '600' },
615
+ pathRow: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing.sm },
616
+ pathText: { ...typography.footnote, flex: 1 },
617
+ pathsFine: { ...typography.caption2 },
618
+ warnBox: {
619
+ flexDirection: 'row',
620
+ gap: spacing.sm,
621
+ alignItems: 'flex-start',
622
+ borderRadius: radii.md,
623
+ borderWidth: StyleSheet.hairlineWidth,
624
+ padding: spacing.md
625
+ },
626
+ warnText: { ...typography.footnote, flex: 1 }
627
+ })