@bsv/expo-wallet-toolbox 0.4.0 → 0.5.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 (118) hide show
  1. package/CHANGELOG.md +292 -0
  2. package/README.md +0 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +9 -1
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +409 -20
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +97 -14
  12. package/core/localpay/build.ts +674 -37
  13. package/core/localpay/codec.ts +68 -5
  14. package/core/localpay/pending.ts +240 -22
  15. package/core/localpay/settlementAck.ts +149 -0
  16. package/core/localpay/types.ts +14 -1
  17. package/core/localpay/verify.ts +118 -69
  18. package/core/mandala/abortGuard.ts +134 -0
  19. package/core/mandala/basketMigration.ts +166 -0
  20. package/core/mandala/bundle.ts +244 -0
  21. package/core/mandala/createRuntime.ts +2437 -0
  22. package/core/mandala/drain.ts +670 -0
  23. package/core/mandala/permissionModule.ts +642 -0
  24. package/core/mandala/resendTransfer.ts +175 -0
  25. package/core/mandala/runtime.ts +357 -0
  26. package/core/mandala/settlementStore.ts +412 -0
  27. package/core/mandala/types.ts +290 -0
  28. package/core/offline/cancelParked.ts +94 -1
  29. package/core/offline/payerHold.ts +152 -12
  30. package/core/offline/tokenFrames.ts +197 -0
  31. package/core/parsePeerPayURI.ts +70 -17
  32. package/core/pay/rails/address.ts +51 -3
  33. package/core/pay/rails/handle.ts +88 -9
  34. package/core/pay/rails/index.ts +16 -6
  35. package/core/pay/rails/nearby.ts +114 -4
  36. package/core/services/capWalletArgs.ts +8 -9
  37. package/core/services/externalOrigin.ts +39 -0
  38. package/core/services/vault/VaultKeyService.ts +912 -251
  39. package/core/services/vault/ceremony.ts +435 -367
  40. package/core/services/vault/ceremonyHost.ts +27 -21
  41. package/core/services/vault/devMock.ts +30 -7
  42. package/core/services/vault/driver.ts +95 -41
  43. package/core/services/vault/guard.ts +514 -56
  44. package/core/services/vault/hardwareLease.ts +22 -0
  45. package/core/services/vault/mockYubiKey.ts +258 -90
  46. package/core/services/vault/pivReset.ts +145 -0
  47. package/core/services/vault/r1comb.ts +976 -0
  48. package/core/services/vault/session.ts +93 -26
  49. package/core/services/vault/transfers.ts +2617 -747
  50. package/core/services/vault/types.ts +100 -43
  51. package/core/services/vault/vaultStore.ts +991 -74
  52. package/core/services/walletConnectionValidation.ts +293 -0
  53. package/core/storage/StorageExpoSQLite.ts +382 -56
  54. package/core/storage/dbImage.ts +48 -0
  55. package/core/storage/methods/findSql.ts +0 -54
  56. package/core/storage/methods/listOutputsSql.ts +7 -3
  57. package/core/storage/methods/offlineActions.ts +15 -0
  58. package/core/storage/methods/processOfflineActions.ts +263 -6
  59. package/core/storage/methods/walletBalanceSql.ts +16 -4
  60. package/core/storage/schema/createTables.ts +123 -0
  61. package/core/storage/sqlUpdateValue.ts +24 -0
  62. package/core/toolboxConfig.ts +112 -1
  63. package/core/walletRepair/runWalletCheck.ts +19 -2
  64. package/package.json +25 -24
  65. package/ui/components/QRScanner.tsx +1 -1
  66. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  67. package/ui/components/pay/AssetPicker.tsx +184 -0
  68. package/ui/components/pay/AvailableBalance.tsx +33 -2
  69. package/ui/components/pay/HandleReceive.tsx +213 -50
  70. package/ui/components/pay/NearbyFlow.tsx +616 -69
  71. package/ui/components/pay/PayForm.tsx +73 -8
  72. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  73. package/ui/components/pay/RecipientField.tsx +49 -4
  74. package/ui/components/pay/RequestHub.tsx +68 -8
  75. package/ui/components/pay/ResultBanner.tsx +41 -4
  76. package/ui/components/pay/UniversalSend.tsx +534 -30
  77. package/ui/components/pay/tokenSendCopy.ts +116 -0
  78. package/ui/components/pay/useRecipientInput.ts +36 -7
  79. package/ui/components/ui/PermissionSheet.tsx +65 -4
  80. package/ui/components/ui/Sheet.tsx +9 -2
  81. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  82. package/ui/components/vault/KeyChooser.tsx +96 -0
  83. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  84. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  85. package/ui/components/wallet/ActivityRow.tsx +101 -17
  86. package/ui/components/wallet/AmountInput.tsx +77 -25
  87. package/ui/components/wallet/AssetAmount.tsx +95 -0
  88. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  89. package/ui/components/wallet/tokenEviction.ts +65 -0
  90. package/ui/hooks/useExportWalletData.ts +39 -0
  91. package/ui/hooks/useMandala.ts +303 -0
  92. package/ui/hooks/useVaultBalance.ts +105 -7
  93. package/ui/hooks/useVaultCoverage.ts +52 -0
  94. package/ui/importDatabases.ts +7 -3
  95. package/ui/index.ts +50 -7
  96. package/ui/screens/ConnectionsScreen.tsx +46 -29
  97. package/ui/screens/PairScreen.tsx +12 -12
  98. package/ui/screens/PayScreen.tsx +130 -10
  99. package/ui/screens/SettingsScreen.tsx +18 -9
  100. package/ui/screens/VaultScreen.tsx +925 -171
  101. package/ui/screens/VaultTransferScreen.tsx +376 -123
  102. package/ui/screens/WalletCheckScreen.tsx +10 -1
  103. package/ui/screens/WalletConfigScreen.tsx +38 -16
  104. package/ui/screens/WalletHomeScreen.tsx +417 -86
  105. package/ui/screens/homeBadges.ts +9 -1
  106. package/ui/screens/tokenRowTitle.ts +68 -0
  107. package/ui/tokenFormat.ts +108 -0
  108. package/ui/tokenSeen.ts +75 -0
  109. package/ui/tokenStatus.ts +79 -0
  110. package/assets/sounds/vault-close.wav +0 -0
  111. package/assets/sounds/vault-open.wav +0 -0
  112. package/core/services/vault/k1.ts +0 -75
  113. package/core/services/vault/sealing.ts +0 -84
  114. package/core/services/vault/vaultDerivation.ts +0 -152
  115. package/core/services/vault/vaultPassphrase.ts +0 -287
  116. package/ui/components/vault/PassphraseField.tsx +0 -306
  117. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  118. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -1,37 +1,76 @@
1
1
  /**
2
- * The Vault screen.
2
+ * The Vault screen — spec §3.4 / §5.4.
3
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.
4
+ * Five states:
5
+ * • vaultEnabled off, not enrolled → hero, "Not available yet" notice, inert CTA
6
+ * • off mainnet, not enrolled → hero, "mainnet only" notice, inert CTA
7
+ * • driver unsupported, not enrolled → hero, "Needs a YubiKey" notice, inert CTA
8
+ * • not enrolled → hero; "Set up vault" opens the EnrollWizard
9
+ * • enrolled → balance, deposit / withdraw, the key list with
10
+ * coverage badges, add / rename / remove / re-lock,
11
+ * export wallet data, disable
7
12
  *
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.
13
+ * An enrolled vault remains visible with the release flag off, and likewise on
14
+ * testnet: a tester who enrolled before the mainnet-only rule can still see and
15
+ * withdraw what is there, but nothing may create a new output or enrol a key.
16
+ *
17
+ * Wallet-scoped metadata means setup first creates or unlocks the wallet
18
+ * identity. A fresh device restores records only from authenticated live locks,
19
+ * then requires a physical possession challenge for each YubiKey before that
20
+ * key can sign.
10
21
  */
11
- import React, { useEffect, useState, useCallback } from 'react'
12
- import { View, Text, StyleSheet, ScrollView, TouchableOpacity, ActivityIndicator } from 'react-native'
22
+ import React, { useCallback, useEffect, useRef, useState } from 'react'
23
+ import { View, Text, StyleSheet, ScrollView, TouchableOpacity, ActivityIndicator, TextInput } from 'react-native'
13
24
  import { useSafeAreaInsets } from 'react-native-safe-area-context'
14
25
  import { GroupedSection } from '../components/ui/GroupedList'
15
26
  import { ListRow } from '../components/ui/ListRow'
16
27
  import PressableScale from '../components/ui/PressableScale'
28
+ import Sheet from '../components/ui/Sheet'
17
29
  import AmountDisplay from '../components/wallet/AmountDisplay'
18
- import { showAlert } from '../components/ui/AlertCard'
30
+ import { BiometricAdvisoryModal } from '../components/wallet/BiometricAdvisoryModal'
31
+ import { showAlert, type AlertButton } from '../components/ui/AlertCard'
19
32
  import { showToast } from '../components/ui/Toast'
20
33
  import { EnrollWizard } from '../components/vault/EnrollWizard'
34
+ import { KeyChooser, vaultKeyLabel, formatVaultSerial } from '../components/vault/KeyChooser'
21
35
  import { VaultBackdrop } from '../components/vault/VaultBackdrop'
36
+ import { vaultErrorCopy } from '../components/vault/vaultErrorCopy'
22
37
  import { useVaultBalance } from '../hooks/useVaultBalance'
38
+ import { useVaultCoverage } from '../hooks/useVaultCoverage'
39
+ import { useExportWalletData } from '../hooks/useExportWalletData'
23
40
  import {
24
41
  useTheme,
25
42
  spacing,
26
43
  radii,
27
44
  typography,
28
45
  useWallet,
29
- reclaimStagingOutputs,
46
+ useLocalStorage,
47
+ relockVault,
48
+ recoverVaultMetaFromOutputs,
49
+ adoptVaultKey,
50
+ beginVaultKeyRemoval,
51
+ finalizeVaultKeyRemoval,
52
+ estimateRelockFee,
53
+ R1C_LOCK_LEN,
30
54
  type VaultWallet,
55
+ type VaultSpendResult,
31
56
  vaultStore,
32
57
  type VaultMeta,
58
+ type VaultKeyRecord,
59
+ type VaultScopeToken,
60
+ type AdoptPhase,
61
+ VAULT_MIN_KEYS,
62
+ VAULT_MAX_KEYS,
33
63
  getVaultDriver,
64
+ isVaultEnabled,
65
+ isVaultAvailable,
66
+ isBackupPushEnabled,
67
+ getBackupUrl,
34
68
  disableVault,
69
+ disableVaultWhenSafe,
70
+ getOnline,
71
+ generateMnemonicWallet,
72
+ backupAttestation,
73
+ VaultError,
35
74
  haptics,
36
75
  i18n
37
76
  } from '@bsv/expo-wallet-toolbox'
@@ -74,68 +113,468 @@ function loadExpoRouter(): ExpoRouterModule {
74
113
  return expoRouterMod
75
114
  }
76
115
 
116
+ /** Swallows the sheet's dismiss while a re-lock is in flight. */
117
+ const noop = (): void => {}
118
+
119
+ interface RelockRequest {
120
+ /** The reason line the ceremony sheet shows and relockVault passes to the
121
+ * card scan. Not the action's description — that is fixed. */
122
+ reason: string
123
+ /** A serial to leave out of the chooser — the key just added, which cannot open the old outputs. */
124
+ exclude?: string
125
+ /** Present for two-phase removal. Metadata remains until every real output
126
+ * has been re-locked without this key and reconciled by the service. */
127
+ revoke?: VaultKeyRecord
128
+ }
129
+
77
130
  export function VaultScreen() {
78
131
  const { colors } = useTheme()
79
132
  const insets = useSafeAreaInsets()
80
133
  const { router } = loadExpoRouter()
81
134
  const Ionicons = loadIonicons()
82
135
  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)
136
+ const { coverage, refresh: refreshCoverage } = useVaultCoverage()
137
+ const { exportData, exporting } = useExportWalletData()
138
+ const { managers, adminOriginator, selectedNetwork, storage, walletBuilding, buildWalletFromMnemonic } = useWallet()
139
+ const { createMnemonic, hasStoredIdentity, secretsReady } = useLocalStorage()
140
+
141
+ /** undefined = loading; null = not enrolled. */
142
+ const [meta, setMeta] = useState<VaultMeta | null | undefined>(undefined)
143
+ const metaRef = useRef<VaultMeta | null>(null)
144
+ const [wizard, setWizard] = useState<'enroll' | 'add-key' | null>(null)
145
+ const serialsBeforeAdd = useRef<Set<string>>(new Set())
146
+ const [renaming, setRenaming] = useState<VaultKeyRecord | null>(null)
147
+ const [renameText, setRenameText] = useState('')
148
+ const [relock, setRelock] = useState<RelockRequest | null>(null)
149
+ const [relockSerial, setRelockSerial] = useState<string | undefined>(undefined)
150
+ const [relocking, setRelocking] = useState(false)
151
+ const [relockError, setRelockError] = useState<string | null>(null)
152
+ const [showBiometricAdvisory, setShowBiometricAdvisory] = useState(false)
153
+ const [creatingWallet, setCreatingWallet] = useState(false)
154
+ const [walletCreationIntent, setWalletCreationIntent] = useState<'deposit' | 'enroll'>('deposit')
155
+ const [recoveryError, setRecoveryError] = useState<string | null>(null)
156
+ const [adopting, setAdopting] = useState<{ record: VaultKeyRecord; scopeToken: VaultScopeToken } | null>(null)
157
+ const [adoptionPin, setAdoptionPin] = useState('')
158
+ const [adoptionPhase, setAdoptionPhase] = useState<AdoptPhase | null>(null)
159
+ const [adoptionBusy, setAdoptionBusy] = useState(false)
160
+ const [adoptionError, setAdoptionError] = useState<string | null>(null)
87
161
 
162
+ // Release flag AND mainnet (task 11). Read from the reactive `selectedNetwork`
163
+ // so everything this gates collapses on a network switch without a remount —
164
+ // in particular the two doors into EnrollWizard, whose factory-reset offer is
165
+ // the fund-loss path a testnet vault reopens.
166
+ const enabled = isVaultAvailable(selectedNetwork)
167
+ // Which refusal to print when it is off. A build with the flag off says so
168
+ // first (spec §5.5); a released build that is simply on the wrong network owes
169
+ // the user that reason instead — "not available yet" would describe an
170
+ // unreleased build, not a vault they had working a moment ago.
171
+ const unavailableCopy = isVaultEnabled() ? 'vault_not_on_mainnet_body' : 'vault_not_released_body'
172
+ const backupConfigured = getBackupUrl() !== ''
88
173
  const supported = getVaultDriver()?.isSupported() ?? false
174
+ const pm = managers?.permissionsManager
89
175
 
90
- const reload = useCallback(async () => {
91
- const [e, m] = await Promise.all([vaultStore.isEnrolled(), vaultStore.getMeta()])
92
- setEnrolled(e)
93
- setMeta(m)
94
- }, [])
176
+ const reload = useCallback(async (): Promise<VaultMeta | null> => {
177
+ try {
178
+ if (!pm) {
179
+ metaRef.current = null
180
+ setMeta(null)
181
+ setRecoveryError(null)
182
+ return null
183
+ }
184
+ let m = await vaultStore.getMeta()
185
+ if (!m) m = await recoverVaultMetaFromOutputs(pm as unknown as VaultWallet, adminOriginator)
186
+ metaRef.current = m
187
+ setMeta(m)
188
+ setRecoveryError(null)
189
+ return m
190
+ } catch (error) {
191
+ metaRef.current = null
192
+ setRecoveryError(vaultErrorCopy(error instanceof VaultError ? error.code : undefined))
193
+ throw error
194
+ }
195
+ }, [pm, adminOriginator])
95
196
 
96
197
  useEffect(() => {
97
- reload()
198
+ void reload().catch(error => console.error('[vault] recovery scan failed:', error))
199
+ }, [reload])
200
+
201
+ const retryRecovery = useCallback(() => {
202
+ setRecoveryError(null)
203
+ setMeta(undefined)
204
+ void reload().catch(error => console.error('[vault] recovery scan failed:', error))
98
205
  }, [reload])
99
206
 
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
207
  useEffect(() => {
108
- if (!enrolled || !pm) return
208
+ if (!pm || !meta?.pendingRemoval) return
109
209
  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
210
+ void finalizeVaultKeyRemoval(pm as unknown as VaultWallet, adminOriginator)
211
+ .then(async complete => {
212
+ if (!stale && complete) await reload()
213
+ })
214
+ .catch(error => console.error('[vault] pending key-removal reconciliation failed:', error))
215
+ return () => { stale = true }
216
+ }, [pm, meta?.pendingRemoval, adminOriginator, reload])
217
+
218
+ // ── helpers ─────────────────────────────────────────────────────────
219
+ /** `nickname · …tail4` for each referenced key; a key no longer in meta shows its pubkey tail. */
220
+ const namesFor = useCallback(
221
+ (refs: { serial?: string; pubkey: string }[]): string =>
222
+ refs
223
+ .map(r => {
224
+ const current = metaRef.current
225
+ const rec = [...(current?.keys ?? []), ...(current?.pendingRemoval ? [current.pendingRemoval.key] : [])]
226
+ .find(k => (r.serial !== undefined && k.serial === r.serial) || k.pubkey === r.pubkey)
227
+ return rec ? vaultKeyLabel(rec) : `…${r.pubkey.slice(-4)}`
228
+ })
229
+ .join(', '),
230
+ []
231
+ )
232
+
233
+ const privateBackupEnabled = useCallback(async (): Promise<boolean> => {
234
+ if (!backupConfigured) return false
235
+ try {
236
+ return await isBackupPushEnabled()
237
+ } catch {
238
+ return false
239
+ }
240
+ }, [backupConfigured])
241
+
242
+ const backupOffAlert = useCallback(async () => {
243
+ haptics.error()
244
+ const choice = await showAlert({
245
+ title: t('vault_backup_off_title'),
246
+ message: t('vault_backup_off_body'),
247
+ buttons: backupConfigured
248
+ ? [
249
+ { text: t('vault_backup_off_cta'), key: 'settings' },
250
+ { text: t('vault_cancel'), key: 'cancel', style: 'cancel' }
251
+ ]
252
+ : [{ text: t('vault_ok'), key: 'ok' }]
113
253
  })
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' })
254
+ if (choice === 'settings') router.push('/wallet-config?section=backup' as never)
255
+ }, [backupConfigured, router])
256
+
257
+ const closeAdoption = useCallback(() => {
258
+ if (adoptionBusy) return
259
+ setAdopting(null)
260
+ setAdoptionPin('')
261
+ setAdoptionPhase(null)
262
+ setAdoptionError(null)
263
+ }, [adoptionBusy])
264
+
265
+ const openAdoption = useCallback((record: VaultKeyRecord) => {
266
+ try {
267
+ setAdopting({ record, scopeToken: vaultStore.captureScopeToken() })
268
+ setAdoptionPin('')
269
+ setAdoptionPhase(null)
270
+ setAdoptionError(null)
271
+ } catch (error) {
272
+ showToast(vaultErrorCopy(error instanceof VaultError ? error.code : undefined), { type: 'error' })
273
+ }
274
+ }, [])
275
+
276
+ const runAdoption = useCallback(async () => {
277
+ if (!adopting || adoptionBusy || !/^[0-9]{6,8}$/.test(adoptionPin)) return
278
+ setAdoptionBusy(true)
279
+ setAdoptionError(null)
280
+ try {
281
+ await adoptVaultKey({
282
+ record: adopting.record,
283
+ scopeToken: adopting.scopeToken,
284
+ onPhase: setAdoptionPhase,
285
+ getPin: async () => adoptionPin,
286
+ nfcMessage: t('vault_nfc_adopt_message')
118
287
  })
119
- .catch(e => console.log('[vault] staging reclaim failed:', (e as Error)?.message))
120
- return () => {
121
- stale = true
288
+ await reload()
289
+ haptics.success()
290
+ showToast(t('vault_recovery_verified'), { type: 'success' })
291
+ setAdopting(null)
292
+ setAdoptionPin('')
293
+ setAdoptionPhase(null)
294
+ } catch (error) {
295
+ haptics.error()
296
+ const vaultError = error instanceof VaultError ? error : undefined
297
+ if (vaultError?.code === 'scope-changed') {
298
+ setAdopting(null)
299
+ setAdoptionPin('')
300
+ setAdoptionPhase(null)
301
+ showToast(vaultErrorCopy('scope-changed'), { type: 'error' })
302
+ return
303
+ }
304
+ if (vaultError?.code === 'pin-invalid') setAdoptionPin('')
305
+ setAdoptionError(vaultErrorCopy(vaultError?.code, {
306
+ count: vaultError?.retriesLeft,
307
+ names: metaRef.current?.keys.map(vaultKeyLabel).join(', ') || undefined
308
+ }))
309
+ } finally {
310
+ setAdoptionBusy(false)
122
311
  }
123
- }, [enrolled, pm, adminOriginator, storage])
312
+ }, [adopting, adoptionBusy, adoptionPin, reload])
313
+
314
+ const transferOpts = useCallback(
315
+ () => ({
316
+ // Lets the reservation heal find the reserving transaction with one
317
+ // indexed query instead of paging every action in the wallet.
318
+ findSpendingReferences: storage ? (outpoints: string[]) => storage.findSpendingReferences(outpoints) : undefined,
319
+ isOnline: getOnline,
320
+ backupEnabled: privateBackupEnabled
321
+ }),
322
+ [storage, privateBackupEnabled]
323
+ )
324
+
325
+ // ── re-lock ─────────────────────────────────────────────────────────
326
+ const openRelock = useCallback((request: RelockRequest) => {
327
+ const m = metaRef.current
328
+ if (!m) return
329
+ const candidates = request.exclude ? m.keys.filter(k => k.serial !== request.exclude) : m.keys
330
+ const lastUsed = candidates.find(k => k.serial === m.lastUsedSerial)
331
+ setRelockSerial((lastUsed ?? candidates[0])?.serial)
332
+ setRelockError(null)
333
+ setRelock(request)
334
+ }, [])
335
+
336
+ const closeRelock = useCallback(() => {
337
+ setRelock(null)
338
+ setRelockError(null)
339
+ }, [])
340
+
341
+ const runRelock = useCallback(async () => {
342
+ if (!relock || !relockSerial || relocking) return
343
+ if (!pm) {
344
+ // The manage row is reachable with no built wallet (enrolment needs
345
+ // none). Nothing can be listed or signed, so say so in the sheet rather
346
+ // than swallow the tap.
347
+ setRelockError(vaultErrorCopy(undefined))
348
+ return
349
+ }
350
+ setRelocking(true)
351
+ setRelockError(null)
352
+ try {
353
+ const w = pm as unknown as VaultWallet
354
+ let result: VaultSpendResult
355
+ let previousCapped = Number.POSITIVE_INFINITY
356
+ // Keep moving capped outputs until the authenticated scan is exhausted.
357
+ // A strict progress check avoids both a fixed page/output ceiling and an
358
+ // infinite retry if the wallet monitor stops advancing reservations.
359
+ do {
360
+ result = await relockVault(w, adminOriginator, relock.reason, relockSerial, {
361
+ ...transferOpts(),
362
+ revokePubkey: relock.revoke?.pubkey
363
+ })
364
+ if (result.cappedInputs >= previousCapped) {
365
+ throw new VaultError('template-invalid', 'Vault re-lock made no progress')
366
+ }
367
+ previousCapped = result.cappedInputs
368
+ if (result.cappedInputs > 0) showToast(t('vault_relock_capped', { count: result.cappedInputs }), { type: 'info' })
369
+ } while (result.cappedInputs > 0)
370
+ refresh()
371
+ refreshCoverage()
372
+ if (result.unreachable.count > 0) {
373
+ // Outputs this key is NOT committed to: another key has to finish
374
+ // the job (whatever the cap left behind, this key cannot open these).
375
+ await showAlert({
376
+ title: t('vault_relock_row'),
377
+ message: t('vault_relock_unreachable', {
378
+ count: result.unreachable.count,
379
+ names: namesFor(result.unreachable.keys)
380
+ }),
381
+ buttons: [{ text: t('vault_ok'), key: 'ok' }]
382
+ })
383
+ // Keep the revocation sheet open and choose a remaining key that can
384
+ // reach the untouched outputs. The target stays in pendingRemoval.
385
+ if (relock.revoke) {
386
+ const next = metaRef.current?.keys.find(
387
+ k => k.serial !== relock.revoke?.serial && result.unreachable.keys.some(r => r.pubkey === k.pubkey)
388
+ )
389
+ setRelockSerial(next?.serial)
390
+ } else {
391
+ closeRelock()
392
+ }
393
+ } else if (result.cappedInputs === 0) {
394
+ if (relock.revoke) {
395
+ const removed = await finalizeVaultKeyRemoval(w, adminOriginator)
396
+ await reload()
397
+ if (removed) {
398
+ haptics.warning()
399
+ showToast(t('vault_key_removed_toast'), { type: 'info' })
400
+ } else {
401
+ showToast(t('tx_still_pending'), { type: 'info' })
402
+ }
403
+ } else {
404
+ showToast(t('vault_relock_done'), { type: 'success' })
405
+ }
406
+ closeRelock()
407
+ }
408
+ } catch (e) {
409
+ console.error('[vault] re-lock failed:', e instanceof Error ? e.message : e, e)
410
+ const code = e instanceof VaultError ? e.code : undefined
411
+ if (code === 'backup-off') {
412
+ await backupOffAlert()
413
+ return
414
+ }
415
+ haptics.error()
416
+ setRelockError(
417
+ vaultErrorCopy(code, {
418
+ names: metaRef.current?.keys.map(vaultKeyLabel).join(', ') || undefined
419
+ })
420
+ )
421
+ } finally {
422
+ setRelocking(false)
423
+ }
424
+ }, [pm, relock, relockSerial, relocking, adminOriginator, transferOpts, closeRelock, refresh, refreshCoverage, namesFor, reload, backupOffAlert])
425
+
426
+ // ── wizard hand-offs ────────────────────────────────────────────────
427
+ /**
428
+ * Every way out of the wizard — done or cancel — comes through here. The
429
+ * wizard persists keys as it goes, so meta may have changed however it
430
+ * closed; a cancel that skipped the reload would leave a stale
431
+ * not-enrolled hero over a persisted key list, or an add-key list missing
432
+ * the new key. Returns the fresh meta so onKeyAdded can diff it.
433
+ */
434
+ const closeWizard = useCallback(async (): Promise<VaultMeta | null> => {
435
+ setWizard(null)
436
+ const m = await reload()
437
+ refreshCoverage()
438
+ return m
439
+ }, [reload, refreshCoverage])
124
440
 
125
441
  const onEnrolled = useCallback(async () => {
126
- setEnrolling(false)
127
- await reload()
442
+ await closeWizard()
128
443
  refresh()
129
- }, [reload, refresh])
444
+ }, [closeWizard, refresh])
130
445
 
446
+ const openAddKey = useCallback(() => {
447
+ serialsBeforeAdd.current = new Set(metaRef.current?.keys.map(k => k.serial) ?? [])
448
+ setWizard('add-key')
449
+ }, [])
450
+
451
+ const onKeyAdded = useCallback(async () => {
452
+ const m = await closeWizard()
453
+ if (!m) return
454
+ const before = serialsBeforeAdd.current
455
+ const added = m.keys.filter(k => !before.has(k.serial))
456
+ const others = m.keys.filter(k => before.has(k.serial))
457
+ // The new key can open deposits made from now on; a re-lock makes it open
458
+ // everything. Pointless on an empty vault, so only offered when it holds
459
+ // something — the wizard's done step already said so either way.
460
+ if (added.length > 0 && (balance ?? 0) > 0) {
461
+ openRelock({
462
+ reason: t('vault_relock_reason', { names: others.map(vaultKeyLabel).join(', ') }),
463
+ exclude: added[0].serial
464
+ })
465
+ }
466
+ }, [closeWizard, balance, openRelock])
467
+
468
+ // ── rename / remove ─────────────────────────────────────────────────
469
+ const saveRename = useCallback(async () => {
470
+ if (!renaming) return
471
+ const next = renameText.trim()
472
+ if (next && next !== renaming.nickname) {
473
+ try {
474
+ await vaultStore.renameKey(renaming.serial, next)
475
+ await reload()
476
+ } catch (e) {
477
+ haptics.error()
478
+ showToast(vaultErrorCopy(e instanceof VaultError ? e.code : undefined), { type: 'error' })
479
+ }
480
+ }
481
+ setRenaming(null)
482
+ }, [renaming, renameText, reload])
483
+
484
+ const removeKey = useCallback(
485
+ async (rec: VaultKeyRecord) => {
486
+ const m = metaRef.current
487
+ if (!m) return
488
+ const title = t('vault_remove_title', { nickname: rec.nickname })
489
+ // Availability first, before any other refusal and long before the
490
+ // service is called. beginVaultKeyRemoval writes a DURABLE pendingRemoval
491
+ // tombstone and only a re-lock clears it — and a re-lock creates a vault
492
+ // output, so it is exactly what this gate refuses. Starting a removal
493
+ // here would wedge the vault with no exit: `transfersBlocked` then kills
494
+ // withdraw, deep-linking the transfer screen refuses with
495
+ // relock-required, cancelUnbroadcastKeyRemoval has no UI caller, and
496
+ // disable is refused while a tombstone is set. The tombstone-before-gate
497
+ // ordering is the underlying defect; refusing up front is the fix that
498
+ // does not reorder the two-phase service.
499
+ if (!enabled) {
500
+ await showAlert({ title, message: t(unavailableCopy), buttons: [{ text: t('vault_ok'), key: 'ok' }] })
501
+ return
502
+ }
503
+ if (m.keys.length <= VAULT_MIN_KEYS) {
504
+ await showAlert({ title, message: vaultErrorCopy('last-keys'), buttons: [{ text: t('vault_ok'), key: 'ok' }] })
505
+ return
506
+ }
507
+ const ok = [{ text: t('vault_ok'), key: 'ok' }]
508
+ if (!pm) {
509
+ await showAlert({ title, message: vaultErrorCopy(undefined), buttons: ok })
510
+ return
511
+ }
512
+ const fee = estimateRelockFee(Math.max(coverage?.outputs ?? 1, 1), R1C_LOCK_LEN(m.keys.length - 1))
513
+ const buttons: AlertButton[] = [
514
+ { text: t('vault_remove_only'), key: 'remove', style: 'destructive' },
515
+ { text: t('vault_cancel'), key: 'cancel', style: 'cancel' }
516
+ ]
517
+ const choice = await showAlert({
518
+ title,
519
+ message: t('vault_remove_body', { nickname: rec.nickname, fee: fee.toLocaleString('en-US') }),
520
+ buttons
521
+ })
522
+ if (choice !== 'remove') return
523
+ try {
524
+ const started = await beginVaultKeyRemoval(pm as unknown as VaultWallet, adminOriginator, rec.serial)
525
+ await reload()
526
+ refreshCoverage()
527
+ if (started.complete) {
528
+ haptics.warning()
529
+ showToast(t('vault_key_removed_toast'), { type: 'info' })
530
+ return
531
+ }
532
+ // The tombstone already dropped this key from the list; the sheet asks
533
+ // for the re-lock that makes the keys still on it open every deposit.
534
+ openRelock({
535
+ reason: t('vault_relock_reason_remaining', {
536
+ names: m.keys.filter(k => k.serial !== rec.serial).map(vaultKeyLabel).join(', ')
537
+ }),
538
+ revoke: rec
539
+ })
540
+ } catch (e) {
541
+ haptics.error()
542
+ await showAlert({
543
+ title,
544
+ message: vaultErrorCopy(e instanceof VaultError ? e.code : undefined),
545
+ buttons: [{ text: t('vault_ok'), key: 'ok' }]
546
+ })
547
+ return
548
+ }
549
+ },
550
+ [coverage, pm, adminOriginator, reload, refreshCoverage, openRelock, enabled, unavailableCopy]
551
+ )
552
+
553
+ const keyActions = useCallback(
554
+ async (rec: VaultKeyRecord) => {
555
+ const choice = await showAlert({
556
+ title: vaultKeyLabel(rec),
557
+ buttons: [
558
+ { text: t('vault_key_action_rename'), key: 'rename' },
559
+ { text: t('vault_key_action_remove'), key: 'remove', style: 'destructive' },
560
+ { text: t('vault_cancel'), key: 'cancel', style: 'cancel' }
561
+ ]
562
+ })
563
+ if (choice === 'rename') {
564
+ setRenameText(rec.nickname)
565
+ setRenaming(rec)
566
+ } else if (choice === 'remove') {
567
+ await removeKey(rec)
568
+ }
569
+ },
570
+ [removeKey]
571
+ )
572
+
573
+ // ── disable ─────────────────────────────────────────────────────────
131
574
  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) {
575
+ // Refuse while funds remain: disabling forgets the key list, and with it
576
+ // the only in-app way to sign for those outputs.
577
+ if (!pm || balance === null || loading || balance > 0) {
139
578
  await showAlert({
140
579
  title: t('vault_disable_blocked_title'),
141
580
  message: t('vault_disable_blocked_message'),
@@ -152,29 +591,160 @@ export function VaultScreen() {
152
591
  ]
153
592
  })
154
593
  if (choice !== 'confirm') return
155
- await disableVault()
594
+ let disabled = false
595
+ try {
596
+ disabled = await disableVaultWhenSafe(pm as unknown as VaultWallet, adminOriginator, disableVault)
597
+ } catch (e) {
598
+ // A failed check is not a funded vault. Saying "withdraw funds first"
599
+ // over a read error sends the user to look for money that is not there.
600
+ console.error('[vault] safe disable check failed:', e instanceof Error ? e.message : e)
601
+ haptics.error()
602
+ await showAlert({
603
+ title: t('vault_disable_title'),
604
+ message: vaultErrorCopy(e instanceof VaultError ? e.code : undefined),
605
+ buttons: [{ text: t('vault_ok'), key: 'ok' }]
606
+ })
607
+ return
608
+ }
609
+ if (!disabled) {
610
+ haptics.error()
611
+ await showAlert({
612
+ title: t('vault_disable_blocked_title'),
613
+ message: t('vault_disable_blocked_message'),
614
+ buttons: [{ text: t('vault_ok'), key: 'ok' }]
615
+ })
616
+ return
617
+ }
156
618
  haptics.warning()
157
619
  showToast(t('vault_disabled_toast'), { type: 'info' })
158
620
  await reload()
159
- }, [balance, reload])
621
+ }, [pm, balance, loading, adminOriginator, reload])
622
+
623
+ // ── wallet-scoped setup / deposit ───────────────────────────────────
624
+ /**
625
+ * Apple HIG: never ask for Face ID/Touch ID before the user has done
626
+ * something that explains why. Vault metadata is scoped to the wallet
627
+ * identity and chain, so both enrollment and deposits create/unlock the
628
+ * wallet first. Same flow as WalletHomeScreen's
629
+ * destinationPress → BiometricAdvisoryModal → ensureWalletExists.
630
+ */
631
+ const creatingWalletRef = useRef(false)
632
+ const ensureWalletExists = useCallback(async (): Promise<boolean> => {
633
+ if (managers.permissionsManager) return true
634
+ if (!secretsReady || walletBuilding || creatingWalletRef.current) return false
635
+ creatingWalletRef.current = true
636
+ try {
637
+ // A missing manager during migration, unlock, or a failed build does
638
+ // not mean the device has no wallet. Never replace that stored identity.
639
+ if (await hasStoredIdentity()) return false
640
+ const wallet = generateMnemonicWallet()
641
+ const stored = await createMnemonic(wallet.mnemonic)
642
+ if (!stored) {
643
+ // Biometric access was needed and unavailable/declined — same dead
644
+ // end onboarding's own generate flow hits. Send the user there to
645
+ // retry explicitly rather than silently failing the tap.
646
+ if (!(await hasStoredIdentity())) router.replace('/auth/mnemonic')
647
+ return false
648
+ }
649
+ try {
650
+ await backupAttestation.markPending(wallet.identityKey)
651
+ } catch (error) {
652
+ console.warn('[vault] Could not record pending backup reminder:', error)
653
+ }
654
+ await buildWalletFromMnemonic(wallet.mnemonic)
655
+ return true
656
+ } catch (error) {
657
+ console.warn('[vault] Wallet creation did not complete:', error)
658
+ return false
659
+ } finally {
660
+ creatingWalletRef.current = false
661
+ }
662
+ }, [managers.permissionsManager, secretsReady, walletBuilding, hasStoredIdentity, createMnemonic, buildWalletFromMnemonic, router])
663
+
664
+ const onDeposit = useCallback(async () => {
665
+ if (managers.permissionsManager) {
666
+ router.push('/vault-transfer?direction=deposit')
667
+ return
668
+ }
669
+ if (!secretsReady || walletBuilding) return
670
+ try {
671
+ if (await hasStoredIdentity()) return
672
+ } catch {
673
+ return
674
+ }
675
+ setWalletCreationIntent('deposit')
676
+ setShowBiometricAdvisory(true)
677
+ }, [managers.permissionsManager, secretsReady, walletBuilding, hasStoredIdentity, router])
678
+
679
+ const onBeginEnrollment = useCallback(async () => {
680
+ if (managers.permissionsManager) {
681
+ setWizard('enroll')
682
+ return
683
+ }
684
+ if (!secretsReady || walletBuilding) return
685
+ try {
686
+ if (await hasStoredIdentity()) return
687
+ } catch {
688
+ return
689
+ }
690
+ setWalletCreationIntent('enroll')
691
+ setShowBiometricAdvisory(true)
692
+ }, [managers.permissionsManager, secretsReady, walletBuilding, hasStoredIdentity])
693
+
694
+ const onAdvisoryContinue = useCallback(() => {
695
+ // Kept up (with a spinner in place of the label) until wallet creation
696
+ // actually settles: the mnemonic math is real, blocking JS-thread work.
697
+ setCreatingWallet(true)
698
+ void (async () => {
699
+ try {
700
+ // Yield once so the spinner paints before the blocking key math starts.
701
+ await new Promise(resolve => setTimeout(resolve, 0))
702
+ const created = await ensureWalletExists()
703
+ setShowBiometricAdvisory(false)
704
+ if (created) {
705
+ if (walletCreationIntent === 'enroll') setWizard('enroll')
706
+ else router.push('/vault-transfer?direction=deposit')
707
+ }
708
+ } finally {
709
+ setCreatingWallet(false)
710
+ }
711
+ })()
712
+ }, [ensureWalletExists, router, walletCreationIntent])
160
713
 
714
+ // ── header ──────────────────────────────────────────────────────────
715
+ // While the wizard is up, back means "leave set-up" and goes through the
716
+ // wizard's own leave-confirm (it owns the pending keys), so the chevron is
717
+ // replaced by a spacer and the wizard's Leave link is the only way out.
161
718
  const Header = (
162
719
  <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>
720
+ {wizard ? (
721
+ <View style={styles.iconBtn} />
722
+ ) : (
723
+ <TouchableOpacity onPress={() => router.back()} style={styles.iconBtn}>
724
+ <Ionicons name="chevron-back" size={24} color={colors.textSecondary} />
725
+ </TouchableOpacity>
726
+ )}
172
727
  <Text style={[styles.headerTitle, { color: colors.textPrimary }]}>{t('vault_title')}</Text>
173
728
  <View style={styles.iconBtn} />
174
729
  </View>
175
730
  )
176
731
 
177
- if (enrolled === null) {
732
+ if (recoveryError) {
733
+ return (
734
+ <View style={[styles.container, { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }]}>
735
+ {Header}
736
+ <View style={styles.centered}>
737
+ <Ionicons name="alert-circle-outline" size={44} color={colors.error} />
738
+ <Text style={[styles.p, { color: colors.textPrimary }]}>{recoveryError}</Text>
739
+ <PressableScale haptic="tap" onPress={retryRecovery} style={[styles.primary, { backgroundColor: colors.accent }]}>
740
+ <Text style={[styles.primaryLabel, { color: colors.textOnAccent }]}>{t('vault_retry')}</Text>
741
+ </PressableScale>
742
+ </View>
743
+ </View>
744
+ )
745
+ }
746
+
747
+ if (meta === undefined) {
178
748
  return (
179
749
  <View style={[styles.container, { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }]}>
180
750
  {Header}
@@ -185,85 +755,99 @@ export function VaultScreen() {
185
755
  )
186
756
  }
187
757
 
188
- // ── enrollment wizard ────────────────────────────────────────────────
189
- if (enrolling) {
758
+ // ── enrollment / add-key wizard ─────────────────────────────────────
759
+ if (wizard) {
190
760
  return (
191
761
  <View style={[styles.container, { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }]}>
192
762
  {Header}
193
- <EnrollWizard onDone={onEnrolled} onCancel={() => setEnrolling(false)} />
763
+ <EnrollWizard mode={wizard} onDone={wizard === 'enroll' ? onEnrolled : onKeyAdded} onCancel={() => void closeWizard()} />
194
764
  </View>
195
765
  )
196
766
  }
197
767
 
198
768
  // ── not enrolled ─────────────────────────────────────────────────────
199
- if (!enrolled) {
769
+ if (meta === null) {
770
+ const canEnroll = enabled && supported
200
771
  return (
201
772
  <View style={[styles.container, { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }]}>
202
773
  {Header}
203
774
  {/* Backdrop is clipped to the area below the header rather than laid over
204
775
  the whole screen, so the line work never crosses the title bar. */}
205
776
  <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
777
  <View style={styles.heroArt}>
210
778
  <VaultBackdrop color={colors.textPrimary} />
211
779
  </View>
212
780
  <ScrollView contentContainerStyle={styles.heroScroll}>
213
781
  {/* 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. */}
782
+ clear of the drawing — a ratio rather than a magic padding. */}
216
783
  <View style={styles.heroSpacerTop} />
217
784
  <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
785
+ <Text style={[styles.h1, { color: colors.textPrimary }]}>{t('vault_hero_title')}</Text>
786
+ <Text style={[styles.p, { color: colors.textSecondary }]}>{t('vault_hero_body')}</Text>
787
+ <PressableScale
788
+ haptic="confirm"
789
+ onPress={canEnroll ? () => void onBeginEnrollment() : undefined}
790
+ accessibilityState={{ disabled: !canEnroll }}
235
791
  style={[
236
- styles.primaryLabel,
237
- { color: supported ? colors.textOnAccent : colors.textTertiary }
792
+ styles.primary,
793
+ canEnroll
794
+ ? { backgroundColor: colors.accent }
795
+ : { backgroundColor: 'transparent', borderWidth: StyleSheet.hairlineWidth, borderColor: colors.separator }
238
796
  ]}
239
797
  >
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')}
798
+ <Text style={[styles.primaryLabel, { color: canEnroll ? colors.textOnAccent : colors.textTertiary }]}>
799
+ {t('vault_enroll_begin')}
255
800
  </Text>
256
- </View>
257
- )}
801
+ </PressableScale>
802
+ {/* Availability gate first (spec §5.5): a build with the flag off,
803
+ or a wallet on testnet, says so before it says anything about
804
+ hardware. */}
805
+ {!enabled && (
806
+ <View style={styles.heroNotice}>
807
+ <Text style={[styles.heroNoticeBody, { color: colors.textSecondary }]}>{t(unavailableCopy)}</Text>
808
+ </View>
809
+ )}
810
+ {enabled && !supported && (
811
+ <View style={styles.heroNotice}>
812
+ <Text style={[styles.heroNoticeTitle, { color: colors.error }]}>{t('vault_unsupported_title')}</Text>
813
+ <Text style={[styles.heroNoticeBody, { color: colors.textSecondary }]}>{t('vault_unsupported_body')}</Text>
814
+ </View>
815
+ )}
258
816
  </View>
259
817
  <View style={styles.heroSpacerBottom} />
260
818
  </ScrollView>
261
819
  </View>
820
+ <BiometricAdvisoryModal
821
+ visible={showBiometricAdvisory}
822
+ loading={creatingWallet}
823
+ onCancel={() => setShowBiometricAdvisory(false)}
824
+ onContinue={onAdvisoryContinue}
825
+ />
262
826
  </View>
263
827
  )
264
828
  }
265
829
 
266
830
  // ── enrolled ─────────────────────────────────────────────────────────
831
+ const canAdd = enabled && !meta.pendingRemoval && meta.keys.length < VAULT_MAX_KEYS
832
+ const adoptedSerials = new Set(meta.recovery?.adoptedSerials ?? [])
833
+ const recoveryRequired = meta.recovery?.required === true
834
+ const adoptedKeyCount = meta.keys.filter(key => adoptedSerials.has(key.serial)).length
835
+ const hasAdoptedKey = !recoveryRequired || adoptedKeyCount > 0
836
+ const hasRecoveryRedundancy = !recoveryRequired || adoptedKeyCount >= VAULT_MIN_KEYS
837
+ const transfersBlocked = !!meta.pendingRemoval
838
+ const canDeposit = enabled && !transfersBlocked && hasRecoveryRedundancy
839
+ const canWithdraw = !transfersBlocked && hasAdoptedKey
840
+ const missingNames = coverage
841
+ ? meta.keys
842
+ .filter(k => coverage.missingKeys.includes(k.pubkey))
843
+ .map(k => k.nickname)
844
+ .join(', ')
845
+ : ''
846
+ const relockCandidates = relock?.exclude ? meta.keys.filter(k => k.serial !== relock.exclude) : meta.keys
847
+ const openGenericRelock = enabled
848
+ ? () => openRelock({ reason: t('vault_relock_reason_generic'), revoke: meta.pendingRemoval?.key })
849
+ : undefined
850
+
267
851
  return (
268
852
  <View style={[styles.container, { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }]}>
269
853
  {Header}
@@ -271,11 +855,16 @@ export function VaultScreen() {
271
855
  <View style={styles.balanceBlock}>
272
856
  <Text style={[styles.balanceLabel, { color: colors.textSecondary }]}>{t('vault_balance_label')}</Text>
273
857
  <TouchableOpacity onPress={refresh} activeOpacity={0.7}>
274
- {loading && balance === null ? (
858
+ {/* Unknown is not zero. `balance ?? 0` rendered both the same, so a
859
+ vault whose balance had not been read yet — or whose read
860
+ failed — looked emptied. Spin until there is a real figure;
861
+ `loading` no longer gates it, because a failed read leaves the
862
+ balance unknown with nothing in flight. */}
863
+ {balance === null ? (
275
864
  <ActivityIndicator color={colors.accent} />
276
865
  ) : (
277
866
  <Text style={[styles.balance, { color: colors.textPrimary }]}>
278
- <AmountDisplay>{balance ?? 0}</AmountDisplay>
867
+ <AmountDisplay>{balance}</AmountDisplay>
279
868
  </Text>
280
869
  )}
281
870
  </TouchableOpacity>
@@ -284,57 +873,241 @@ export function VaultScreen() {
284
873
  <View style={styles.actions}>
285
874
  <PressableScale
286
875
  haptic="confirm"
287
- onPress={() => router.push('/vault-transfer?direction=deposit')}
288
- style={[styles.actionBtn, { backgroundColor: colors.accent }]}
876
+ onPress={canDeposit ? () => void onDeposit() : undefined}
877
+ accessibilityState={{ disabled: !canDeposit }}
878
+ style={[styles.actionBtn, { backgroundColor: canDeposit ? colors.accent : colors.backgroundElevated }]}
289
879
  >
290
- <Ionicons name="arrow-down" size={18} color={colors.textOnAccent} />
291
- <Text style={[styles.actionLabel, { color: colors.textOnAccent }]}>{t('vault_deposit_cta')}</Text>
880
+ <Ionicons name="arrow-down" size={18} color={canDeposit ? colors.textOnAccent : colors.textTertiary} />
881
+ <Text style={[styles.actionLabel, { color: canDeposit ? colors.textOnAccent : colors.textTertiary }]}>
882
+ {t('vault_deposit_cta')}
883
+ </Text>
292
884
  </PressableScale>
885
+ {/* Existing funds remain withdrawable with private backup off. A
886
+ full withdrawal creates no new Vault output; partial withdrawal
887
+ may ask the user to enable backup before preserving a remainder. */}
293
888
  <PressableScale
294
889
  haptic="confirm"
295
- onPress={() => router.push('/vault-transfer?direction=withdraw')}
890
+ onPress={canWithdraw ? () => router.push('/vault-transfer?direction=withdraw') : undefined}
891
+ accessibilityState={{ disabled: !canWithdraw }}
296
892
  style={[
297
893
  styles.actionBtn,
298
- {
299
- backgroundColor: colors.backgroundElevated,
300
- borderColor: colors.separator,
301
- borderWidth: StyleSheet.hairlineWidth
302
- }
894
+ { backgroundColor: colors.backgroundElevated, borderColor: colors.separator, borderWidth: StyleSheet.hairlineWidth }
303
895
  ]}
304
896
  >
305
897
  <Ionicons name="arrow-up" size={18} color={colors.accent} />
306
898
  <Text style={[styles.actionLabel, { color: colors.accent }]}>{t('vault_withdraw_cta')}</Text>
307
899
  </PressableScale>
308
900
  </View>
901
+ {!enabled && <Text style={[styles.notice, { color: colors.textSecondary }]}>{t(unavailableCopy)}</Text>}
902
+ {transfersBlocked && <Text style={[styles.notice, { color: colors.warning }]}>{t('vault_err_relock_required')}</Text>}
903
+ {recoveryRequired && !hasRecoveryRedundancy && (
904
+ <Text style={[styles.notice, { color: colors.warning }]}>{t('vault_err_key_not_adopted')}</Text>
905
+ )}
309
906
 
310
- <GroupedSection header={t('vault_key_section')}>
907
+ <GroupedSection
908
+ header={t('vault_key_section', { count: meta.keys.length + (meta.pendingRemoval ? 1 : 0) })}
909
+ footer={t('vault_footnote')}
910
+ >
911
+ {coverage && coverage.missingKeys.length > 0 && (
912
+ <ListRow
913
+ label={t('vault_badge_missing', { count: coverage.stale, nickname: missingNames })}
914
+ icon="alert-circle-outline"
915
+ iconColor={colors.warning}
916
+ showChevron={false}
917
+ onPress={openGenericRelock}
918
+ />
919
+ )}
920
+ {coverage && coverage.removedKeyOutputs > 0 && (
921
+ <ListRow
922
+ label={t('vault_badge_removed', { count: coverage.removedKeyOutputs })}
923
+ icon="alert-circle-outline"
924
+ iconColor={colors.warning}
925
+ showChevron={false}
926
+ onPress={openGenericRelock}
927
+ />
928
+ )}
929
+ {meta.keys.map((rec, i) => {
930
+ const adopted = !recoveryRequired || adoptedSerials.has(rec.serial)
931
+ return (
932
+ <ListRow
933
+ key={rec.serial}
934
+ label={`${rec.nickname} · ${formatVaultSerial(rec.serial)}`}
935
+ subtitle={adopted ? new Date(rec.enrolledAt).toLocaleDateString() : t('vault_err_key_not_adopted')}
936
+ icon={adopted ? 'key-outline' : 'shield-checkmark-outline'}
937
+ iconColor={adopted ? colors.permissionSpending : colors.warning}
938
+ showChevron={false}
939
+ onPress={adopted ? () => void keyActions(rec) : () => openAdoption(rec)}
940
+ isLast={i === meta.keys.length - 1 && !canAdd}
941
+ />
942
+ )
943
+ })}
944
+ {meta.pendingRemoval && (
945
+ <ListRow
946
+ key={`pending-${meta.pendingRemoval.key.serial}`}
947
+ label={`${meta.pendingRemoval.key.nickname} · ${formatVaultSerial(meta.pendingRemoval.key.serial)}`}
948
+ subtitle={t('vault_key_pending_removal')}
949
+ icon="time-outline"
950
+ iconColor={colors.warning}
951
+ showChevron={false}
952
+ onPress={openGenericRelock}
953
+ isLast={!canAdd}
954
+ />
955
+ )}
956
+ {canAdd && (
957
+ <ListRow label={t('vault_add_key_row')} icon="add-circle-outline" iconColor={colors.info} onPress={openAddKey} isLast />
958
+ )}
959
+ </GroupedSection>
960
+
961
+ <GroupedSection header={t('vault_manage_section')} footer={t('vault_export_explainer')}>
962
+ {/* No standalone "re-lock now" row here (spec revision): re-locking
963
+ is a consequence, not a user action in its own right. It runs
964
+ automatically after adding a key to a funded vault (onKeyAdded
965
+ below) and is offered contextually from the coverage badges
966
+ above (a missing or removed key really does need one) — a
967
+ generic button with no problem to point at just confused
968
+ people into tapping it unprompted. */}
969
+ {/* Same action, label and styling as the Settings row (spec §3.4). */}
311
970
  <ListRow
312
- label={t('vault_key_serial')}
313
- value={meta?.yubiSerial}
314
- icon="finger-print"
315
- iconColor={colors.permissionSpending}
971
+ label={t('export_wallet_data')}
972
+ icon="share-outline"
973
+ iconColor="#32ADE6"
316
974
  showChevron={false}
975
+ onPress={exporting ? undefined : () => void exportData()}
976
+ trailing={exporting ? <ActivityIndicator size="small" /> : undefined}
317
977
  isLast
318
978
  />
319
979
  </GroupedSection>
320
980
 
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
- />
981
+ <GroupedSection>
328
982
  <ListRow
329
983
  label={t('vault_disable_row')}
330
984
  icon="lock-open"
331
985
  iconColor={colors.error}
332
986
  destructive
333
- onPress={confirmDisable}
987
+ onPress={() => void confirmDisable()}
334
988
  isLast
335
989
  />
336
990
  </GroupedSection>
337
991
  </ScrollView>
992
+
993
+ {/* Rename — nickname only. */}
994
+ <Sheet
995
+ visible={renaming !== null}
996
+ onClose={() => setRenaming(null)}
997
+ title={renaming ? t('vault_rename_title', { nickname: renaming.nickname }) : ''}
998
+ fitContent
999
+ >
1000
+ <View style={styles.sheetBody}>
1001
+ <TextInput
1002
+ accessibilityLabel={renaming ? t('vault_rename_title', { nickname: renaming.nickname }) : ''}
1003
+ style={[styles.input, { color: colors.textPrimary, backgroundColor: colors.backgroundSecondary }]}
1004
+ value={renameText}
1005
+ onChangeText={setRenameText}
1006
+ placeholder={renaming?.nickname}
1007
+ placeholderTextColor={colors.textTertiary}
1008
+ maxLength={32}
1009
+ autoCapitalize="words"
1010
+ returnKeyType="done"
1011
+ onSubmitEditing={() => void saveRename()}
1012
+ autoFocus
1013
+ />
1014
+ <PressableScale haptic="confirm" onPress={() => void saveRename()} style={[styles.primary, { backgroundColor: colors.accent }]}>
1015
+ <Text style={[styles.primaryLabel, { color: colors.textOnAccent }]}>{t('vault_rename_save')}</Text>
1016
+ </PressableScale>
1017
+ <PressableScale onPress={() => setRenaming(null)} style={styles.secondary}>
1018
+ <Text style={[styles.secondaryLabel, { color: colors.textSecondary }]}>{t('vault_cancel')}</Text>
1019
+ </PressableScale>
1020
+ </View>
1021
+ </Sheet>
1022
+
1023
+ {/* Fresh-device recovery: prove this exact recovered key with a random
1024
+ challenge before the transfer chooser is allowed to offer it. */}
1025
+ <Sheet
1026
+ visible={adopting !== null}
1027
+ onClose={adoptionBusy ? noop : closeAdoption}
1028
+ title={adopting ? vaultKeyLabel(adopting.record) : ''}
1029
+ fitContent
1030
+ >
1031
+ <View style={styles.sheetBody}>
1032
+ <Text style={[styles.p, { color: colors.textSecondary }]}>{t('vault_err_key_not_adopted')}</Text>
1033
+ <Text style={[styles.sheetLabel, { color: colors.textPrimary }]}>{t('vault_enter_pin')}</Text>
1034
+ <TextInput
1035
+ accessibilityLabel={t('vault_enter_pin')}
1036
+ style={[styles.input, { color: colors.textPrimary, backgroundColor: colors.backgroundSecondary }]}
1037
+ value={adoptionPin}
1038
+ onChangeText={text => {
1039
+ setAdoptionError(null)
1040
+ setAdoptionPin(text)
1041
+ }}
1042
+ placeholder="••••••"
1043
+ placeholderTextColor={colors.textTertiary}
1044
+ keyboardType="number-pad"
1045
+ secureTextEntry={adoptionPin.length > 0}
1046
+ maxLength={8}
1047
+ editable={!adoptionBusy}
1048
+ autoFocus
1049
+ />
1050
+ {adoptionBusy && (
1051
+ <View style={styles.adoptionProgress}>
1052
+ <ActivityIndicator color={colors.accent} />
1053
+ <Text style={[styles.p, { color: colors.textSecondary }]}>
1054
+ {adoptionPhase === 'challenging' ? t('vault_touch_when_blinks') : t('vault_reading_key')}
1055
+ </Text>
1056
+ </View>
1057
+ )}
1058
+ {adoptionError && <Text style={[styles.err, { color: colors.error }]}>{adoptionError}</Text>}
1059
+ <PressableScale
1060
+ haptic="confirm"
1061
+ onPress={!adoptionBusy && /^[0-9]{6,8}$/.test(adoptionPin) ? () => void runAdoption() : undefined}
1062
+ accessibilityState={{ disabled: adoptionBusy || !/^[0-9]{6,8}$/.test(adoptionPin) }}
1063
+ style={[
1064
+ styles.primary,
1065
+ { backgroundColor: colors.accent, opacity: !adoptionBusy && /^[0-9]{6,8}$/.test(adoptionPin) ? 1 : 0.5 }
1066
+ ]}
1067
+ >
1068
+ {adoptionBusy ? (
1069
+ <ActivityIndicator color={colors.textOnAccent} />
1070
+ ) : (
1071
+ <Text style={[styles.primaryLabel, { color: colors.textOnAccent }]}>{t('vault_continue')}</Text>
1072
+ )}
1073
+ </PressableScale>
1074
+ <PressableScale onPress={adoptionBusy ? undefined : closeAdoption} style={styles.secondary}>
1075
+ <Text style={[styles.secondaryLabel, { color: colors.textSecondary }]}>{t('vault_cancel')}</Text>
1076
+ </PressableScale>
1077
+ </View>
1078
+ </Sheet>
1079
+
1080
+ {/* Re-lock — choose the key, then one ceremony tap per pass. */}
1081
+ <Sheet visible={relock !== null} onClose={relocking ? noop : closeRelock} title={t('vault_relock_row')} fitContent>
1082
+ <View style={styles.sheetBody}>
1083
+ {relock?.reason ? <Text style={[styles.p, { color: colors.textSecondary }]}>{relock.reason}</Text> : null}
1084
+ <Text style={[styles.sheetLabel, { color: colors.textPrimary }]}>{t('vault_relock_choose')}</Text>
1085
+ <KeyChooser keys={relockCandidates} selected={relockSerial} onSelect={setRelockSerial} />
1086
+ {relockError && <Text style={[styles.err, { color: colors.error }]}>{relockError}</Text>}
1087
+ <PressableScale
1088
+ haptic="confirm"
1089
+ onPress={relockSerial && !relocking ? () => void runRelock() : undefined}
1090
+ accessibilityState={{ disabled: !relockSerial || relocking }}
1091
+ style={[styles.primary, { backgroundColor: colors.accent, opacity: relockSerial && !relocking ? 1 : 0.5 }]}
1092
+ >
1093
+ {relocking ? (
1094
+ <ActivityIndicator color={colors.textOnAccent} />
1095
+ ) : (
1096
+ <Text style={[styles.primaryLabel, { color: colors.textOnAccent }]}>{t('vault_relock_now')}</Text>
1097
+ )}
1098
+ </PressableScale>
1099
+ <PressableScale onPress={relocking ? undefined : closeRelock} style={styles.secondary}>
1100
+ <Text style={[styles.secondaryLabel, { color: colors.textSecondary }]}>{t('vault_cancel')}</Text>
1101
+ </PressableScale>
1102
+ </View>
1103
+ </Sheet>
1104
+
1105
+ <BiometricAdvisoryModal
1106
+ visible={showBiometricAdvisory}
1107
+ loading={creatingWallet}
1108
+ onCancel={() => setShowBiometricAdvisory(false)}
1109
+ onContinue={onAdvisoryContinue}
1110
+ />
338
1111
  </View>
339
1112
  )
340
1113
  }
@@ -352,27 +1125,11 @@ const styles = StyleSheet.create({
352
1125
  iconBtn: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center' },
353
1126
  headerTitle: { ...typography.headline },
354
1127
  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
1128
  // NO horizontal padding here. GroupedSection insets itself (its card carries
369
1129
  // 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.
1130
+ // padding this container would double-inset every grouped card. Direct
1131
+ // children carry their own gutter instead.
374
1132
  content: { paddingTop: spacing.lg, paddingBottom: spacing.xxxl },
375
- gutter: { paddingHorizontal: spacing.lg },
376
1133
  heroArea: { flex: 1, overflow: 'hidden' },
377
1134
  heroArt: { position: 'absolute', bottom: '7%', left: 0, right: 0, height: '56%' },
378
1135
  heroScroll: { flexGrow: 1 },
@@ -381,35 +1138,22 @@ const styles = StyleSheet.create({
381
1138
  heroNoticeBody: { ...typography.footnote, textAlign: 'center' },
382
1139
  heroSpacerTop: { flex: 1 },
383
1140
  heroSpacerBottom: { flex: 4 },
384
- heroCopy: {
385
- alignSelf: 'stretch',
386
- alignItems: 'center',
387
- paddingHorizontal: spacing.xl,
388
- gap: spacing.lg
389
- },
1141
+ heroCopy: { alignSelf: 'stretch', alignItems: 'center', paddingHorizontal: spacing.xl, gap: spacing.lg },
390
1142
  h1: { ...typography.title1, textAlign: 'center' },
391
- h2: { ...typography.title3, textAlign: 'center' },
392
1143
  p: { ...typography.subhead, textAlign: 'center' },
1144
+ notice: { ...typography.footnote, textAlign: 'center', paddingHorizontal: spacing.xl, marginBottom: spacing.xxl },
393
1145
  primary: { width: '100%', borderRadius: radii.md, paddingVertical: spacing.lg, alignItems: 'center' },
394
1146
  primaryLabel: { ...typography.headline },
395
- balanceBlock: {
396
- alignItems: 'center',
397
- gap: spacing.xs,
398
- paddingVertical: spacing.lg,
399
- paddingHorizontal: spacing.lg
400
- },
1147
+ secondary: { paddingVertical: spacing.md, alignItems: 'center' },
1148
+ secondaryLabel: { ...typography.body },
1149
+ err: { ...typography.footnote, textAlign: 'center' },
1150
+ balanceBlock: { alignItems: 'center', gap: spacing.xs, paddingVertical: spacing.lg, paddingHorizontal: spacing.lg },
401
1151
  // No textTransform, matching the wallet screen: "Vault holds" is a phrase
402
1152
  // leading into the amount, and casing belongs to the translation.
403
1153
  balanceLabel: { ...typography.footnote },
404
- // tabular-nums so the balance does not jitter as digits change — the repo
405
- // convention (NearbyFlow, AmountInput).
1154
+ // tabular-nums so the balance does not jitter as digits change.
406
1155
  balance: { ...typography.display, fontVariant: ['tabular-nums'] },
407
- actions: {
408
- flexDirection: 'row',
409
- gap: spacing.md,
410
- paddingHorizontal: spacing.lg,
411
- marginBottom: spacing.xxl
412
- },
1156
+ actions: { flexDirection: 'row', gap: spacing.md, paddingHorizontal: spacing.lg, marginBottom: spacing.xxl },
413
1157
  actionBtn: {
414
1158
  flex: 1,
415
1159
  flexDirection: 'row',
@@ -419,5 +1163,15 @@ const styles = StyleSheet.create({
419
1163
  borderRadius: radii.md,
420
1164
  paddingVertical: spacing.lg
421
1165
  },
422
- actionLabel: { ...typography.headline }
1166
+ actionLabel: { ...typography.headline },
1167
+ sheetBody: { paddingHorizontal: spacing.xl, paddingBottom: spacing.xxl, gap: spacing.lg },
1168
+ sheetLabel: { ...typography.headline },
1169
+ adoptionProgress: { alignItems: 'center', gap: spacing.sm },
1170
+ input: {
1171
+ width: '100%',
1172
+ borderRadius: radii.md,
1173
+ paddingVertical: spacing.md,
1174
+ paddingHorizontal: spacing.lg,
1175
+ ...typography.body
1176
+ }
423
1177
  })