@bsv/expo-wallet-toolbox 0.3.1 → 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 (119) hide show
  1. package/CHANGELOG.md +311 -0
  2. package/README.md +52 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +21 -18
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +413 -23
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +107 -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/services/walletServiceConfig.ts +19 -24
  54. package/core/storage/StorageExpoSQLite.ts +382 -56
  55. package/core/storage/dbImage.ts +48 -0
  56. package/core/storage/methods/findSql.ts +0 -54
  57. package/core/storage/methods/listOutputsSql.ts +7 -3
  58. package/core/storage/methods/offlineActions.ts +15 -0
  59. package/core/storage/methods/processOfflineActions.ts +263 -6
  60. package/core/storage/methods/walletBalanceSql.ts +16 -4
  61. package/core/storage/schema/createTables.ts +123 -0
  62. package/core/storage/sqlUpdateValue.ts +24 -0
  63. package/core/toolboxConfig.ts +240 -0
  64. package/core/walletRepair/runWalletCheck.ts +19 -2
  65. package/package.json +25 -24
  66. package/ui/components/QRScanner.tsx +1 -1
  67. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  68. package/ui/components/pay/AssetPicker.tsx +184 -0
  69. package/ui/components/pay/AvailableBalance.tsx +33 -2
  70. package/ui/components/pay/HandleReceive.tsx +213 -50
  71. package/ui/components/pay/NearbyFlow.tsx +616 -69
  72. package/ui/components/pay/PayForm.tsx +73 -8
  73. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  74. package/ui/components/pay/RecipientField.tsx +49 -4
  75. package/ui/components/pay/RequestHub.tsx +68 -8
  76. package/ui/components/pay/ResultBanner.tsx +41 -4
  77. package/ui/components/pay/UniversalSend.tsx +534 -30
  78. package/ui/components/pay/tokenSendCopy.ts +116 -0
  79. package/ui/components/pay/useRecipientInput.ts +36 -7
  80. package/ui/components/ui/PermissionSheet.tsx +65 -4
  81. package/ui/components/ui/Sheet.tsx +9 -2
  82. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  83. package/ui/components/vault/KeyChooser.tsx +96 -0
  84. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  85. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  86. package/ui/components/wallet/ActivityRow.tsx +101 -17
  87. package/ui/components/wallet/AmountInput.tsx +77 -25
  88. package/ui/components/wallet/AssetAmount.tsx +95 -0
  89. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  90. package/ui/components/wallet/tokenEviction.ts +65 -0
  91. package/ui/hooks/useExportWalletData.ts +39 -0
  92. package/ui/hooks/useMandala.ts +303 -0
  93. package/ui/hooks/useVaultBalance.ts +105 -7
  94. package/ui/hooks/useVaultCoverage.ts +52 -0
  95. package/ui/importDatabases.ts +7 -3
  96. package/ui/index.ts +50 -7
  97. package/ui/screens/ConnectionsScreen.tsx +46 -29
  98. package/ui/screens/PairScreen.tsx +12 -12
  99. package/ui/screens/PayScreen.tsx +130 -10
  100. package/ui/screens/SettingsScreen.tsx +18 -9
  101. package/ui/screens/VaultScreen.tsx +925 -171
  102. package/ui/screens/VaultTransferScreen.tsx +376 -123
  103. package/ui/screens/WalletCheckScreen.tsx +10 -1
  104. package/ui/screens/WalletConfigScreen.tsx +42 -20
  105. package/ui/screens/WalletHomeScreen.tsx +417 -86
  106. package/ui/screens/homeBadges.ts +9 -1
  107. package/ui/screens/tokenRowTitle.ts +68 -0
  108. package/ui/tokenFormat.ts +108 -0
  109. package/ui/tokenSeen.ts +75 -0
  110. package/ui/tokenStatus.ts +79 -0
  111. package/assets/sounds/vault-close.wav +0 -0
  112. package/assets/sounds/vault-open.wav +0 -0
  113. package/core/services/vault/k1.ts +0 -75
  114. package/core/services/vault/sealing.ts +0 -84
  115. package/core/services/vault/vaultDerivation.ts +0 -152
  116. package/core/services/vault/vaultPassphrase.ts +0 -287
  117. package/ui/components/vault/PassphraseField.tsx +0 -306
  118. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  119. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -1,46 +1,67 @@
1
1
  /**
2
- * Vault deposit / withdraw — full screen, not a drawer.
2
+ * Vault deposit / withdraw — full screen, not a drawer. Spec §4.1 / §4.2.
3
3
  *
4
4
  * Direction comes from the `direction` search param ('deposit' | 'withdraw').
5
5
  *
6
- * Both directions run the ceremony sheet. A deposit address is a BIP32 child
7
- * of the vault's PRIVATE HD node — there is no stored xpub to derive one
8
- * from without it — so even a deposit needs one YubiKey tap to unwrap that
9
- * node. Withdraw derives every input's key (and any re-vaulted remainder)
10
- * from the same unwrapped node and signs in software. Either way the ceremony
11
- * sheet takes over for insert/PIN/touch — that one stays a sheet
12
- * deliberately, because it fires from any screen as a system prompt.
6
+ * Deposit needs no hardware: the wallet builds an R1C output committed to every
7
+ * enrolled key and broadcasts it (depositToVault). The screen shows the floor
8
+ * and the fee inline, confirms the FIRST deposit into an empty vault, and
9
+ * refuses while encrypted private backup is unavailable. The salt is
10
+ * deterministic and public in the lock; backup preserves the authenticated
11
+ * YubiKey records and wallet history a replacement device needs for recovery.
12
+ *
13
+ * Withdraw asks which key will be tapped BEFORE anything runs (the NFC sheet is
14
+ * modal), previews what the chosen key can select (previewVaultWithdrawal —
15
+ * a database read, nothing reserved or tapped) so the remainder-fold
16
+ * confirmation is computed against THAT total rather than the whole balance,
17
+ * confirms when the remainder would fall under the vault floor, and reports
18
+ * what did NOT move afterwards as alerts rather than toasts: outputs the
19
+ * chosen key cannot open, and outputs left behind by the input cap.
20
+ *
21
+ * Lazy wallet creation is the Vault screen's job (its Deposit button); with no
22
+ * built wallet the CTA here is simply inert.
13
23
  */
14
- import React, { useState, useCallback } from 'react'
15
- import {
16
- View,
17
- Text,
18
- StyleSheet,
19
- ActivityIndicator,
20
- ScrollView,
21
- TouchableOpacity
22
- } from 'react-native'
24
+ import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
25
+ import { View, Text, StyleSheet, ActivityIndicator, ScrollView, TouchableOpacity } from 'react-native'
23
26
  import { useSafeAreaInsets } from 'react-native-safe-area-context'
24
27
  import { AmountInput, SEND_MAX_VALUE } from '../components/wallet/AmountInput'
25
28
  import PressableScale from '../components/ui/PressableScale'
26
29
  import AmountDisplay from '../components/wallet/AmountDisplay'
30
+ import AvailableBalance from '../components/pay/AvailableBalance'
27
31
  import { showToast } from '../components/ui/Toast'
28
32
  import { showAlert } from '../components/ui/AlertCard'
33
+ import { KeyChooser, vaultKeyLabel } from '../components/vault/KeyChooser'
34
+ import { vaultErrorCopy, type VaultErrorParams } from '../components/vault/vaultErrorCopy'
35
+ import { expectVaultBalance, useVaultBalance } from '../hooks/useVaultBalance'
29
36
  import {
30
37
  useTheme,
31
38
  spacing,
32
39
  radii,
33
40
  typography,
34
41
  useWallet,
42
+ ExchangeRateContext,
43
+ formatAmount,
44
+ vaultStore,
35
45
  depositToVault,
46
+ previewVaultWithdrawal,
36
47
  withdrawFromVault,
48
+ VAULT_DEPOSIT_MIN,
49
+ VAULT_MAX_KEYS,
50
+ estimateRelockFee,
51
+ R1C_LOCK_LEN,
52
+ isVaultEnabled,
53
+ isVaultAvailable,
54
+ isBackupPushEnabled,
55
+ getBackupUrl,
37
56
  type VaultWallet,
57
+ type VaultMeta,
58
+ type VaultSpendResult,
38
59
  getOnline,
39
60
  VaultError,
40
61
  haptics,
62
+ sounds,
41
63
  i18n
42
64
  } from '@bsv/expo-wallet-toolbox'
43
- import { useVaultBalance } from '../hooks/useVaultBalance'
44
65
 
45
66
  const t = (k: string, o?: Record<string, unknown>) => i18n.t(k, o) as string
46
67
 
@@ -66,12 +87,9 @@ function loadIonicons(): IoniconsComponent {
66
87
  * file is barrel-exported from the package's `ui` entry point, and a static
67
88
  * top-level `import` of expo-router pulls in its own untransformed JSX
68
89
  * source (Navigator.js etc.), which Jest cannot parse for any consumer of the
69
- * barrel, even one that never navigates. Same pattern as
70
- * core/context/WalletContext.tsx's and WalletHomeScreen.tsx's lazy
71
- * expo-router load. `useLocalSearchParams` is a hook, but calling it via
72
- * `loadExpoRouter().useLocalSearchParams()` is equivalent to calling it
73
- * directly — the module is cached after the first call, so it is the exact
74
- * same function reference on every render, which is what the rules of hooks
90
+ * barrel, even one that never navigates. `useLocalSearchParams` is a hook, but
91
+ * calling it via `loadExpoRouter().useLocalSearchParams()` is the exact same
92
+ * function reference on every render, which is what the rules of hooks
75
93
  * actually require (a stable, unconditional call per render).
76
94
  */
77
95
  type ExpoRouterModule = typeof import('expo-router')
@@ -85,15 +103,23 @@ function loadExpoRouter(): ExpoRouterModule {
85
103
  }
86
104
 
87
105
  /**
88
- * i18next returns the KEY itself when a string is missing, and a key is
89
- * truthy — so the old `t(...) || t('vault_err_generic')` fallback never fired
90
- * and shipped raw keys like `vault_err_backup_required` to the screen.
106
+ * Optional structured details services attach to a VaultError per the
107
+ * DECISION: `key-cannot-cover` → `{ reachable, total }` (what the chosen key
108
+ * can reach and the vault's total); `serial-mismatch` → `{ tapped, chosen }`
109
+ * (both serials, so the sheet can say "That's X — you chose Y"). Read
110
+ * structurally so this file depends on no service type; when absent the copy
111
+ * degrades per vaultErrorCopy.
91
112
  */
92
- function translateVaultError(code: string | undefined): string {
93
- if (!code) return t('vault_err_generic')
94
- const key = `vault_err_${code.replace(/-/g, '_')}`
95
- const translated = t(key)
96
- return translated === key ? t('vault_err_generic') : translated
113
+ function readErrorDetails(e: unknown): { reachable?: number; total?: number; tapped?: string; chosen?: string } {
114
+ const details = (e as { details?: unknown } | null)?.details
115
+ if (!details || typeof details !== 'object') return {}
116
+ const d = details as Record<string, unknown>
117
+ return {
118
+ reachable: typeof d.reachable === 'number' ? d.reachable : undefined,
119
+ total: typeof d.total === 'number' ? d.total : undefined,
120
+ tapped: typeof d.tapped === 'string' ? d.tapped : undefined,
121
+ chosen: typeof d.chosen === 'string' ? d.chosen : undefined
122
+ }
97
123
  }
98
124
 
99
125
  export function VaultTransferScreen() {
@@ -102,61 +128,268 @@ export function VaultTransferScreen() {
102
128
  const { router, useLocalSearchParams } = loadExpoRouter()
103
129
  const Ionicons = loadIonicons()
104
130
  const { direction } = useLocalSearchParams<{ direction?: string }>()
105
- const { managers, adminOriginator, storage } = useWallet()
131
+ const { managers, adminOriginator, selectedNetwork, storage, settings } = useWallet()
132
+ const { satoshisPerUSD, usdToFiat = {} } = useContext(ExchangeRateContext)
106
133
  const { balance, refresh } = useVaultBalance()
134
+ const [meta, setMeta] = useState<VaultMeta | null>(null)
107
135
  const [amount, setAmount] = useState('')
136
+ const [chosenSerial, setChosenSerial] = useState<string | undefined>(undefined)
108
137
  const [busy, setBusy] = useState(false)
109
138
  const [error, setError] = useState<string | null>(null)
139
+ // Guards run()'s whole lifetime, not just the `busy` render state: without
140
+ // it a second tap that lands before React commits the busy state can re-enter
141
+ // run() while canRun is still true and busy is still false.
142
+ const runningRef = useRef(false)
110
143
 
111
144
  const isDeposit = direction !== 'withdraw'
112
-
113
- // Send max is a sentinel value, not a number: the withdraw path takes 'all'
114
- // and lets the toolbox work out the fee, which is the only way to empty the
115
- // vault exactly. Pre-computing "balance minus fee" here cannot work — a K1
116
- // withdrawal's fee depends on how many vault inputs it takes to cover the
117
- // amount (each input is an ordinary ~107-byte unlock), not on any one
118
- // script's size, and that count is not known until the outputs are selected.
119
145
  const isMax = amount === SEND_MAX_VALUE
146
+ // Release flag AND mainnet (task 11): deposits create a vault output, and one
147
+ // must never land off mainnet. Withdrawal of pre-existing outputs is never
148
+ // gated — that is how a testnet tester gets their coins back out.
149
+ const released = isVaultAvailable(selectedNetwork)
150
+ // See VaultScreen: "not available yet" describes an unreleased build, not a
151
+ // released build on the wrong network.
152
+ const unavailableCopy = isVaultEnabled() ? 'vault_not_on_mainnet_body' : 'vault_not_released_body'
153
+ const backupConfigured = getBackupUrl() !== ''
154
+ const pm = managers?.permissionsManager
155
+ const currency = settings?.currency || 'BSV'
156
+ // The same formatter AmountDisplay wraps; a component cannot be interpolated
157
+ // into i18n.t, so the alerts and the floor line take the string form.
158
+ const fmt = useCallback(
159
+ (sats: number) => formatAmount(sats, currency, satoshisPerUSD, { usdToFiat }),
160
+ [currency, satoshisPerUSD, usdToFiat]
161
+ )
162
+ const privateBackupEnabled = useCallback(async (): Promise<boolean> => {
163
+ if (!backupConfigured) return false
164
+ try {
165
+ return await isBackupPushEnabled()
166
+ } catch {
167
+ return false
168
+ }
169
+ }, [backupConfigured])
170
+
171
+ useEffect(() => {
172
+ let alive = true
173
+ void vaultStore.getMeta().then(m => {
174
+ if (!alive) return
175
+ setMeta(m)
176
+ if (!m || m.keys.length === 0) return
177
+ // Restored records are offered only after this device has proved live
178
+ // possession. Default to the last eligible key, then the first.
179
+ const eligible = m.recovery?.required
180
+ ? m.keys.filter(k => m.recovery!.adoptedSerials.includes(k.serial))
181
+ : m.keys
182
+ const lastUsed = eligible.find(k => k.serial === m.lastUsedSerial)
183
+ setChosenSerial((lastUsed ?? eligible[0])?.serial)
184
+ })
185
+ return () => {
186
+ alive = false
187
+ }
188
+ }, [])
189
+
190
+ // Memoised: several useCallback deps below read it, and a fresh `[]` on
191
+ // every render would invalidate them all.
192
+ const allKeys = useMemo(() => meta?.keys ?? [], [meta])
193
+ const keys = useMemo(
194
+ () => meta?.recovery?.required
195
+ ? allKeys.filter(key => meta.recovery!.adoptedSerials.includes(key.serial))
196
+ : allKeys,
197
+ [meta, allKeys]
198
+ )
199
+ const chosen = keys.find(k => k.serial === chosenSerial)
200
+ const allNames = keys.map(vaultKeyLabel).join(', ')
201
+
202
+ // The lock's own size at the toolbox rate, plus its 10 % margin. The funding
203
+ // input adds ~15 sat on top; "about" is the right word for the copy.
204
+ const depositFee = estimateRelockFee(0, R1C_LOCK_LEN(Math.min(VAULT_MAX_KEYS, Math.max(1, allKeys.length))))
205
+
206
+ const sats = parseInt(amount, 10)
207
+ const validAmount = isDeposit
208
+ ? Number.isFinite(sats) && sats >= VAULT_DEPOSIT_MIN
209
+ : isMax || (Number.isFinite(sats) && sats > 0)
210
+ const transfersBlocked = !!meta?.pendingRemoval
211
+ const canRun =
212
+ validAmount &&
213
+ !busy &&
214
+ !transfersBlocked &&
215
+ !!pm &&
216
+ balance !== null &&
217
+ (isDeposit ? released : chosen !== undefined)
218
+
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 rec = keys.find(k => (r.serial !== undefined && k.serial === r.serial) || k.pubkey === r.pubkey)
225
+ return rec ? vaultKeyLabel(rec) : `…${r.pubkey.slice(-4)}`
226
+ })
227
+ .join(', '),
228
+ [keys]
229
+ )
230
+
231
+ const backupOffAlert = useCallback(async () => {
232
+ haptics.error()
233
+ const choice = await showAlert({
234
+ title: t('vault_backup_off_title'),
235
+ message: t('vault_backup_off_body'),
236
+ buttons: backupConfigured
237
+ ? [
238
+ { text: t('vault_backup_off_cta'), key: 'settings' },
239
+ { text: t('vault_cancel'), key: 'cancel', style: 'cancel' }
240
+ ]
241
+ : [{ text: t('vault_ok'), key: 'ok' }]
242
+ })
243
+ // Keep this screen on the stack so the user can switch backup on, return,
244
+ // and retry the same transfer.
245
+ if (choice === 'settings') router.push('/wallet-config?section=backup' as never)
246
+ }, [backupConfigured, router])
247
+
248
+ /** Everything vaultErrorCopy can name for this screen's errors. */
249
+ const errorParams = useCallback(
250
+ (e: unknown): VaultErrorParams => {
251
+ const details = readErrorDetails(e)
252
+ // The DECISION: serial-mismatch carries { tapped, chosen } in
253
+ // VaultError.details, not in message — details.tapped is only ever an
254
+ // enrolled serial (or absent), so a lookup miss degrades to undefined
255
+ // exactly like every other missing param. The chosen key is read from
256
+ // details first (the serial the service actually ran with) and falls
257
+ // back to the in-app choice when a service attaches none.
258
+ const tapped = details.tapped ? keys.find(k => k.serial === details.tapped) : undefined
259
+ const chosenRec = (details.chosen ? keys.find(k => k.serial === details.chosen) : undefined) ?? chosen
260
+ const others = keys.filter(k => k.serial !== chosenRec?.serial)
261
+ return {
262
+ nickname: chosenRec ? vaultKeyLabel(chosenRec) : undefined,
263
+ chosenName: chosenRec ? vaultKeyLabel(chosenRec) : undefined,
264
+ tappedName: tapped ? vaultKeyLabel(tapped) : undefined,
265
+ otherNames: others.length ? others.map(vaultKeyLabel).join(', ') : undefined,
266
+ names: allNames || undefined,
267
+ reachable: details.reachable !== undefined ? fmt(details.reachable) : undefined,
268
+ total: details.total !== undefined ? fmt(details.total) : undefined,
269
+ count: e instanceof VaultError ? e.retriesLeft : undefined
270
+ }
271
+ },
272
+ [keys, chosen, allNames, fmt]
273
+ )
120
274
 
121
275
  const run = useCallback(async () => {
122
- const pm = managers?.permissionsManager
123
- const sats = parseInt(amount, 10)
124
- if (!pm) return
125
- if (!isMax && (!Number.isFinite(sats) || sats <= 0)) return
126
- setBusy(true)
276
+ if (!pm || !canRun) return
277
+ // Whole-lifetime re-entrancy guard (not just `busy`): a second tap that
278
+ // lands before this function's first `await` still sees canRun true and
279
+ // busy false, so `busy` alone cannot stop it.
280
+ if (runningRef.current) return
281
+ runningRef.current = true
282
+ const w = pm as unknown as VaultWallet
283
+ const total = balance ?? 0
127
284
  setError(null)
128
285
  try {
129
- const w = pm as unknown as VaultWallet
130
286
  if (isDeposit) {
131
- await depositToVault(w, adminOriginator, sats, t('vault_deposit_reason', { amount: sats }), {
132
- isOnline: getOnline
287
+ // Check before first-deposit confirmation so the user is never asked
288
+ // to approve a transfer the service must reject. The service receives
289
+ // the same callback and checks again at the output-creation boundary.
290
+ if (!(await privateBackupEnabled())) {
291
+ await backupOffAlert()
292
+ return
293
+ }
294
+ // The first deposit is the moment the recovery model becomes real
295
+ // money: say it once, with the names of the keys that hold it.
296
+ if (total === 0) {
297
+ const choice = await showAlert({
298
+ title: t('vault_first_deposit_title'),
299
+ message: t('vault_first_deposit_body', { amount: fmt(sats), count: keys.length, names: allNames }),
300
+ buttons: [
301
+ { text: t('vault_deposit_cta'), key: 'deposit' },
302
+ { text: t('vault_cancel'), key: 'cancel', style: 'cancel' }
303
+ ]
304
+ })
305
+ if (choice !== 'deposit') return
306
+ }
307
+ setBusy(true)
308
+ await depositToVault(w, adminOriginator, sats, {
309
+ isOnline: getOnline,
310
+ backupEnabled: privateBackupEnabled
133
311
  })
134
- // vaultOpen/haptic already fired by the ceremony's onArmed
312
+ expectVaultBalance(total + sats)
313
+ // The success toast carries the success haptic (Toast.tsx); the tone
314
+ // is the vault's own (see useConfirmationSound's pairing rules).
315
+ sounds.vaultDeposit()
135
316
  showToast(t('vault_deposit_done'), { type: 'success' })
136
317
  } else {
137
- const result = await withdrawFromVault(
318
+ if (!chosen) return
319
+ let withdrawAll = isMax
320
+ // What THIS key would select — a database read; nothing reserved or
321
+ // tapped. Its total can be less than the balance (outputs only other
322
+ // keys can open, or the input cap), and it is the figure the service
323
+ // folds or re-vaults the remainder against, so the remainder rule
324
+ // below must use it. A refusal here (key-cannot-cover, …) lands in
325
+ // the catch and shows inline, before any NFC sheet.
326
+ const preview = await previewVaultWithdrawal(w, adminOriginator, chosen.serial, withdrawAll ? 'all' : sats)
327
+ const remainder = preview.selectedTotal - (withdrawAll ? preview.selectedTotal : sats)
328
+ // Remainder rule (spec §4.2 step 4): a leftover under the floor cannot
329
+ // be re-vaulted, so everything this key can select would move. Say so
330
+ // before running.
331
+ if (!withdrawAll && remainder > 0 && remainder < VAULT_DEPOSIT_MIN) {
332
+ const choice = await showAlert({
333
+ title: t('vault_remainder_title'),
334
+ message: t('vault_remainder_body', { amount: fmt(sats), remainder: fmt(remainder) }),
335
+ buttons: [
336
+ { text: t('vault_remainder_all'), key: 'all' },
337
+ { text: t('vault_remainder_change'), key: 'change', style: 'cancel' }
338
+ ]
339
+ })
340
+ if (choice !== 'all') return
341
+ withdrawAll = true
342
+ }
343
+ setBusy(true)
344
+ const result: VaultSpendResult = await withdrawFromVault(
138
345
  w,
139
346
  adminOriginator,
140
- isMax ? 'all' : sats,
141
- t('vault_withdraw_reason', { amount: isMax ? (balance ?? 0) : sats }),
347
+ withdrawAll ? 'all' : sats,
348
+ // Becomes the NFC sheet's text for every tap of this withdrawal.
349
+ t('vault_withdraw_reason', { amount: withdrawAll ? total : sats }),
350
+ chosen.serial,
142
351
  {
143
352
  // Lets the reservation heal find the reserving transaction with one
144
353
  // indexed query instead of paging every action in the wallet.
145
354
  findSpendingReferences: storage ? outpoints => storage.findSpendingReferences(outpoints) : undefined,
146
- isOnline: getOnline
355
+ isOnline: getOnline,
356
+ backupEnabled: privateBackupEnabled
147
357
  }
148
358
  )
149
- // vaultOpen/haptic already fired by the ceremony's onArmed
150
- //
151
- // A capped withdrawal is partial by design (see VAULT_MAX_INPUTS), so
152
- // say so rather than letting the balance look wrong: the vault still
153
- // holds the untouched outputs, and repeating the withdrawal moves them.
154
- showToast(
155
- result.remainingInputs > 0
156
- ? t('vault_withdraw_partial', { count: result.remainingInputs })
157
- : t('vault_withdraw_done'),
158
- { type: 'success' }
159
- )
359
+ // The withdrawal itself succeeded whether or not everything moved —
360
+ // play the tone once here rather than only in the plain-success
361
+ // branch below, so a partial (unreachable/capped) withdrawal still
362
+ // gets it.
363
+ sounds.vaultWithdraw()
364
+ // Alerts, not toasts, for what did NOT move (spec §4.2 step 8): the
365
+ // user has to act on both, and a toast can be missed.
366
+ const moved = withdrawAll ? Math.max(0, total - result.unreachable.satoshis) : sats
367
+ // Publish what the vault now holds before the alerts below, so the
368
+ // screen behind them is already right and nothing has to read it back.
369
+ expectVaultBalance(Math.max(0, total - moved))
370
+ let reported = false
371
+ if (result.unreachable.count > 0) {
372
+ reported = true
373
+ await showAlert({
374
+ title: t('vault_unreachable_title'),
375
+ message: t('vault_unreachable_body', {
376
+ moved: fmt(moved),
377
+ count: result.unreachable.count,
378
+ amount: fmt(result.unreachable.satoshis),
379
+ names: namesFor(result.unreachable.keys)
380
+ }),
381
+ buttons: [{ text: t('vault_ok'), key: 'ok' }]
382
+ })
383
+ }
384
+ if (result.cappedInputs > 0) {
385
+ reported = true
386
+ await showAlert({
387
+ title: t('vault_withdraw_done'),
388
+ message: t('vault_withdraw_partial', { count: result.cappedInputs }),
389
+ buttons: [{ text: t('vault_ok'), key: 'ok' }]
390
+ })
391
+ }
392
+ if (!reported) showToast(t('vault_withdraw_done'), { type: 'success' })
160
393
  }
161
394
  setAmount('')
162
395
  refresh()
@@ -164,50 +397,39 @@ export function VaultTransferScreen() {
164
397
  } catch (e) {
165
398
  console.error('[vault] transfer failed:', e instanceof Error ? e.message : e, e)
166
399
  const code = e instanceof VaultError ? e.code : undefined
167
-
168
- if (code === 'backup-required') {
169
- // A blocked deposit needs a route out, not a red footnote. Matches the
170
- // disable-while-funded pattern on the vault screen.
171
- //
172
- // The CTA goes to Settings > Wallet, not back to /vault: this refusal
173
- // only fires once a vault already exists (deposit is only offered
174
- // from the enrolled vault screen), and the enrolled vault screen has
175
- // no backup affordance of its own — EnrollWizard, the only other
176
- // place that records an attestation, isn't reachable from there.
177
- // Printing recovery shares from wallet-config is a real backup and
178
- // now records the same attestation (see handlePrintRecoveryShares),
179
- // so it satisfies the gate. push (not replace) keeps this screen on
180
- // the stack so the user can come back and retry the deposit.
181
- haptics.error()
182
- const choice = await showAlert({
183
- title: t('vault_deposit_blocked_title'),
184
- message: t('vault_deposit_blocked_message'),
185
- buttons: [
186
- { text: t('vault_deposit_blocked_dismiss'), style: 'cancel', key: 'cancel' },
187
- { text: t('vault_deposit_blocked_cta'), key: 'backup' }
188
- ]
189
- })
190
- if (choice === 'backup') router.push('/wallet-config')
400
+ if (code === 'backup-off') {
401
+ await backupOffAlert()
191
402
  return
192
403
  }
193
-
194
- setError(translateVaultError(code))
195
404
  haptics.error()
405
+ setError(vaultErrorCopy(code, errorParams(e)))
196
406
  } finally {
197
407
  setBusy(false)
408
+ runningRef.current = false
198
409
  }
199
- }, [amount, isMax, balance, isDeposit, managers?.permissionsManager, adminOriginator, refresh, storage])
200
-
201
- const sats = parseInt(amount, 10)
202
- const valid = isMax || (Number.isFinite(sats) && sats > 0)
410
+ }, [
411
+ pm,
412
+ canRun,
413
+ balance,
414
+ isDeposit,
415
+ isMax,
416
+ sats,
417
+ keys.length,
418
+ allNames,
419
+ chosen,
420
+ adminOriginator,
421
+ storage,
422
+ fmt,
423
+ namesFor,
424
+ privateBackupEnabled,
425
+ backupOffAlert,
426
+ errorParams,
427
+ refresh,
428
+ router
429
+ ])
203
430
 
204
431
  return (
205
- <View
206
- style={[
207
- styles.container,
208
- { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }
209
- ]}
210
- >
432
+ <View style={[styles.container, { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }]}>
211
433
  <View style={[styles.header, { borderBottomColor: colors.separator }]}>
212
434
  <TouchableOpacity onPress={() => router.back()} style={styles.iconBtn}>
213
435
  <Ionicons name="chevron-back" size={24} color={colors.textSecondary} />
@@ -220,47 +442,75 @@ export function VaultTransferScreen() {
220
442
 
221
443
  <ScrollView contentContainerStyle={styles.body} keyboardShouldPersistTaps="handled">
222
444
  <View style={styles.balanceBlock}>
223
- <Text style={[styles.balanceLabel, { color: colors.textSecondary }]}>
224
- {t('vault_balance_label')}
225
- </Text>
226
- <Text style={[styles.balance, { color: colors.textPrimary }]}>
227
- <AmountDisplay>{balance ?? 0}</AmountDisplay>
228
- </Text>
445
+ <Text style={[styles.balanceLabel, { color: colors.textSecondary }]}>{t('vault_balance_label')}</Text>
446
+ {/* Unknown is not zero — see the same guard on VaultScreen. */}
447
+ {balance === null ? (
448
+ <ActivityIndicator color={colors.accent} />
449
+ ) : (
450
+ <Text style={[styles.balance, { color: colors.textPrimary }]}>
451
+ <AmountDisplay>{balance}</AmountDisplay>
452
+ </Text>
453
+ )}
229
454
  </View>
230
455
 
231
456
  <Text style={[styles.sub, { color: colors.textSecondary }]}>
232
457
  {isDeposit ? t('vault_deposit_sub') : t('vault_withdraw_sub')}
233
458
  </Text>
234
459
 
235
- <AmountInput
236
- value={amount}
237
- onChangeText={setAmount}
238
- showMax={!isDeposit}
239
- maxLabelKey="entire_vault_balance"
240
- />
460
+ {!isDeposit && keys.length > 0 && (
461
+ <View style={styles.chooser}>
462
+ <Text style={[styles.chooserLabel, { color: colors.textPrimary }]}>{t('vault_choose_key')}</Text>
463
+ {/* Frozen while a ceremony runs: the highlighted key must stay the
464
+ one the NFC sheet is asking for. */}
465
+ <KeyChooser keys={keys} selected={chosenSerial} onSelect={busy ? () => {} : setChosenSerial} />
466
+ </View>
467
+ )}
468
+
469
+ <AmountInput value={amount} onChangeText={setAmount} showMax={!isDeposit} maxLabelKey="entire_vault_balance" />
470
+
471
+ {/* What a deposit draws from is the WALLET's spendable balance, not the
472
+ vault's (shown above already) — the same line PayForm shows under
473
+ its amount input, for the same reason: "how much can I actually
474
+ put in this field". */}
475
+ {isDeposit && <AvailableBalance />}
476
+
477
+ {isDeposit && (
478
+ <Text style={[styles.floor, { color: colors.textSecondary }]}>
479
+ {t('vault_floor_line', {
480
+ floorDisplay: fmt(VAULT_DEPOSIT_MIN),
481
+ floorSats: VAULT_DEPOSIT_MIN.toLocaleString('en-US'),
482
+ feeDisplay: fmt(depositFee)
483
+ })}
484
+ </Text>
485
+ )}
486
+
487
+ {isDeposit && !released && (
488
+ <Text style={[styles.floor, { color: colors.textSecondary }]}>{t(unavailableCopy)}</Text>
489
+ )}
490
+
491
+ {transfersBlocked && (
492
+ <Text style={[styles.floor, { color: colors.warning }]}>{t('vault_err_relock_required')}</Text>
493
+ )}
494
+
495
+ {!isDeposit && meta?.recovery?.required && keys.length === 0 && (
496
+ <Text style={[styles.floor, { color: colors.warning }]}>{t('vault_err_key_not_adopted')}</Text>
497
+ )}
241
498
 
242
499
  {error && <Text style={[styles.err, { color: colors.error }]}>{error}</Text>}
243
500
 
244
501
  <PressableScale
245
502
  haptic="confirm"
246
- onPress={valid && !busy ? run : undefined}
503
+ onPress={canRun ? () => void run() : undefined}
504
+ accessibilityState={{ disabled: !canRun }}
247
505
  style={[
248
506
  styles.primary,
249
- {
250
- backgroundColor: valid ? colors.accent : colors.backgroundElevated,
251
- opacity: busy ? 0.6 : 1
252
- }
507
+ { backgroundColor: canRun ? colors.accent : colors.backgroundElevated, opacity: busy ? 0.6 : 1 }
253
508
  ]}
254
509
  >
255
510
  {busy ? (
256
511
  <ActivityIndicator color={colors.textOnAccent} />
257
512
  ) : (
258
- <Text
259
- style={[
260
- styles.primaryLabel,
261
- { color: valid ? colors.textOnAccent : colors.textTertiary }
262
- ]}
263
- >
513
+ <Text style={[styles.primaryLabel, { color: canRun ? colors.textOnAccent : colors.textTertiary }]}>
264
514
  {isDeposit ? t('vault_deposit_cta') : t('vault_withdraw_cta')}
265
515
  </Text>
266
516
  )}
@@ -287,6 +537,9 @@ const styles = StyleSheet.create({
287
537
  balanceLabel: { ...typography.footnote, textTransform: 'uppercase' },
288
538
  balance: { ...typography.title1, fontVariant: ['tabular-nums'] },
289
539
  sub: { ...typography.subhead, textAlign: 'center' },
540
+ chooser: { gap: spacing.sm },
541
+ chooserLabel: { ...typography.headline },
542
+ floor: { ...typography.footnote, textAlign: 'center' },
290
543
  err: { ...typography.footnote, textAlign: 'center' },
291
544
  primary: { borderRadius: radii.md, paddingVertical: spacing.lg, alignItems: 'center' },
292
545
  primaryLabel: { ...typography.headline }
@@ -86,6 +86,7 @@ function loadExpoRouter(): ExpoRouterModule {
86
86
  const STEPS: { id: WalletCheckStepId; labelKey: string }[] = [
87
87
  { id: 'online', labelKey: 'wallet_check_step_online' },
88
88
  { id: 'records', labelKey: 'wallet_check_step_records' },
89
+ { id: 'tokens', labelKey: 'wallet_check_step_tokens' },
89
90
  { id: 'proofs', labelKey: 'wallet_check_step_proofs' },
90
91
  { id: 'backup', labelKey: 'wallet_check_step_backup' },
91
92
  { id: 'phrase_backup', labelKey: 'wallet_check_step_phrase' },
@@ -134,7 +135,8 @@ function useWalletCheckPorts(): WalletCheckPorts {
134
135
  checkUtxoSpendability,
135
136
  releaseStuckReservations,
136
137
  runMonitorTask,
137
- peekLastMissHeight
138
+ peekLastMissHeight,
139
+ mandala
138
140
  } = useWallet()
139
141
  const wallet = managers?.permissionsManager
140
142
 
@@ -158,6 +160,12 @@ function useWalletCheckPorts(): WalletCheckPorts {
158
160
  recovered: parseCount(log, /(\d+) spending tx\(s\) internalized/)
159
161
  }
160
162
  },
163
+ reviewTokens: async () => {
164
+ if (!mandala?.available) return { settled: 0, removed: 0, unattested: 0 }
165
+ const { settled, removed, unattested, unreachable } = await mandala.reviewTokenHoldings()
166
+ if (unreachable) throw new Error('token overlay unreachable')
167
+ return { settled, removed, unattested }
168
+ },
161
169
  checkProofs: async () => {
162
170
  await runMonitorTask('CheckForProofs')
163
171
  return { repaired: 0 }
@@ -224,6 +232,7 @@ function useWalletCheckPorts(): WalletCheckPorts {
224
232
  [
225
233
  adminOriginator,
226
234
  checkUtxoSpendability,
235
+ mandala,
227
236
  releaseStuckReservations,
228
237
  runMonitorTask,
229
238
  selectedNetwork,