@bsv/expo-wallet-toolbox 0.5.0 → 0.9.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 (200) hide show
  1. package/CHANGELOG.md +2000 -0
  2. package/README.md +66 -1
  3. package/core/amountFormatHelpers.ts +258 -36
  4. package/core/backup/RemoteSyncReader.ts +133 -24
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +149 -11
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +71 -5
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/config.tsx +12 -5
  15. package/core/constants.ts +14 -1
  16. package/core/contacts/contactActivity.ts +153 -0
  17. package/core/contacts/contactCache.ts +41 -0
  18. package/core/contacts/contactsStore.ts +183 -0
  19. package/core/context/ExchangeRateContext.tsx +34 -27
  20. package/core/context/LocalStorageProvider.tsx +43 -40
  21. package/core/context/UserContext.tsx +18 -7
  22. package/core/context/VaultContext.tsx +49 -2
  23. package/core/context/WalletConnectionContext.tsx +203 -11
  24. package/core/context/WalletContext.tsx +685 -171
  25. package/core/demo/demoAssets.ts +60 -0
  26. package/core/demo/demoLedger.ts +240 -0
  27. package/core/demo/demoMandalaRuntime.ts +96 -0
  28. package/core/demo/demoMode.ts +38 -0
  29. package/core/demo/demoWallet.ts +25 -0
  30. package/core/demo/index.ts +26 -0
  31. package/core/demo/useDemo.ts +59 -0
  32. package/core/headers/OfflineFirstChaintracks.ts +99 -17
  33. package/core/headers/headerStore.ts +33 -14
  34. package/core/headers/syncHeaders.ts +12 -1
  35. package/core/i18n/translations.tsx +2186 -98
  36. package/core/identity/contactLink.ts +36 -0
  37. package/core/identity/handleRegistry/client.ts +314 -0
  38. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  39. package/core/identity/handleRegistry/profileCert.ts +254 -0
  40. package/core/identity/handleRegistry/registration.ts +559 -0
  41. package/core/identity/handleRegistry/resolver.ts +315 -0
  42. package/core/identity/handleRegistry/rules.ts +104 -0
  43. package/core/index.ts +53 -5
  44. package/core/localpay/build.ts +225 -24
  45. package/core/localpay/pending.ts +110 -7
  46. package/core/localpay/pendingAbortAuthority.ts +95 -0
  47. package/core/localpay/pendingAborts.ts +266 -26
  48. package/core/localpay/session.ts +42 -17
  49. package/core/localpay/settlementAck.ts +10 -1
  50. package/core/localpay/transport/socket.ts +52 -3
  51. package/core/localpay/verify.ts +100 -10
  52. package/core/mandala/abortGuard.ts +96 -20
  53. package/core/mandala/createRuntime.ts +206 -33
  54. package/core/mandala/drain.ts +89 -11
  55. package/core/mandala/inboxPrehold.ts +186 -0
  56. package/core/mandala/permissionModule.ts +202 -20
  57. package/core/mandala/settlementStore.ts +24 -2
  58. package/core/mandala/types.ts +40 -5
  59. package/core/monitor/MonitorSupervisor.ts +121 -0
  60. package/core/monitor/TaskBackupPush.ts +15 -1
  61. package/core/monitor/TaskCreditInbox.ts +1 -1
  62. package/core/monitor/TaskDrainOutbox.ts +15 -1
  63. package/core/monitor/TaskSendOffline.ts +15 -1
  64. package/core/net/online.ts +49 -0
  65. package/core/net/publicDestination.ts +91 -0
  66. package/core/net/validateArcUrl.ts +22 -0
  67. package/core/numberFormat.ts +19 -0
  68. package/core/offline/cancelParked.ts +134 -13
  69. package/core/offline/payerHold.ts +100 -24
  70. package/core/offline/plan.ts +37 -8
  71. package/core/pay/beefRepair.ts +6 -2
  72. package/core/pay/damagedInbox.ts +24 -0
  73. package/core/pay/rails/address.ts +107 -12
  74. package/core/pay/rails/handle.ts +117 -22
  75. package/core/pay/rails/index.ts +45 -7
  76. package/core/pay/rails/nativeIntent.ts +61 -0
  77. package/core/pay/receiveHistory.ts +93 -0
  78. package/core/pay/recordProof.ts +21 -7
  79. package/core/pay/refreshProofGuard.ts +42 -1
  80. package/core/pay/watchlist.ts +5 -2
  81. package/core/peerpay/control.ts +17 -18
  82. package/core/peerpay/handleResendRequests.ts +58 -4
  83. package/core/peerpay/outbox.ts +3 -1
  84. package/core/recovery/backupMaterial.ts +61 -0
  85. package/core/recovery/createWallet.ts +95 -0
  86. package/core/recovery/recoverWallet.ts +120 -0
  87. package/core/recovery/restoreWallet.ts +170 -0
  88. package/core/recovery/secret.ts +92 -0
  89. package/core/recovery/shareCollector.ts +71 -0
  90. package/core/recovery/shareParsing.ts +87 -0
  91. package/core/recovery/shares.ts +116 -0
  92. package/core/recovery/useRecoveryDeps.ts +70 -0
  93. package/core/services/arcTokenStorage.ts +52 -0
  94. package/core/services/arcadeBroadcastProvider.ts +233 -52
  95. package/core/services/autoApprovePolicy.ts +105 -0
  96. package/core/services/callbackToken.ts +19 -0
  97. package/core/services/capWalletArgs.ts +14 -2
  98. package/core/services/connectionAuthority.ts +98 -0
  99. package/core/services/exchangeRate.ts +36 -13
  100. package/core/services/externalOrigin.ts +16 -2
  101. package/core/services/secrets/kek.ts +126 -29
  102. package/core/services/secrets/migration.ts +16 -4
  103. package/core/services/secrets/store.ts +42 -14
  104. package/core/services/vault/VaultKeyService.ts +228 -45
  105. package/core/services/vault/chainRecovery.ts +483 -0
  106. package/core/services/vault/driver.ts +9 -1
  107. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  108. package/core/services/vault/guard.ts +218 -32
  109. package/core/services/vault/hardwareLease.ts +19 -0
  110. package/core/services/vault/metaAuthority.ts +210 -0
  111. package/core/services/vault/pivReset.ts +64 -23
  112. package/core/services/vault/r1comb.ts +139 -3
  113. package/core/services/vault/session.ts +25 -4
  114. package/core/services/vault/transfers.ts +868 -172
  115. package/core/services/vault/types.ts +19 -4
  116. package/core/services/vault/vaultStore.ts +256 -29
  117. package/core/services/walletArgLimits.ts +45 -2
  118. package/core/services/walletConnectionValidation.ts +76 -6
  119. package/core/services/walletServiceConfig.ts +40 -27
  120. package/core/storage/StorageExpoSQLite.ts +88 -47
  121. package/core/storage/methods/findSql.ts +24 -2
  122. package/core/storage/methods/listActionsSql.ts +8 -5
  123. package/core/storage/methods/listOutputsSql.ts +2 -2
  124. package/core/storage/methods/offlineActions.ts +10 -1
  125. package/core/storage/methods/processOfflineActions.ts +117 -25
  126. package/core/storage/methods/reviewStatusSql.ts +7 -2
  127. package/core/storage/schema/createTables.ts +155 -2
  128. package/core/stores/ConnectionStore.ts +34 -0
  129. package/core/toolboxConfig.ts +104 -0
  130. package/core/toolboxTypes.ts +40 -0
  131. package/core/userAvatar.ts +79 -0
  132. package/core/walletDbRegistry.ts +63 -0
  133. package/core/walletMonitor.ts +25 -4
  134. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  135. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  136. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  137. package/package.json +7 -7
  138. package/ui/activityFilter.ts +115 -0
  139. package/ui/backupShares.ts +26 -169
  140. package/ui/components/pay/AddressReceive.tsx +13 -6
  141. package/ui/components/pay/AssetPicker.tsx +30 -9
  142. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  143. package/ui/components/pay/NearbyFlow.tsx +480 -243
  144. package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
  145. package/ui/components/pay/RecipientField.tsx +84 -70
  146. package/ui/components/pay/StepBar.tsx +32 -0
  147. package/ui/components/pay/UniversalSend.tsx +827 -205
  148. package/ui/components/ui/AlertCard.tsx +38 -5
  149. package/ui/components/ui/PencilEditField.tsx +109 -0
  150. package/ui/components/ui/PermissionSheet.tsx +197 -66
  151. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  152. package/ui/components/vault/EnrollWizard.tsx +61 -13
  153. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  154. package/ui/components/wallet/ActivityRow.tsx +227 -123
  155. package/ui/components/wallet/AmountInput.tsx +26 -8
  156. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  157. package/ui/components/wallet/Balance.tsx +42 -23
  158. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  159. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  160. package/ui/components/wallet/ContactSigil.tsx +49 -0
  161. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  162. package/ui/components/wallet/FitAmount.tsx +148 -0
  163. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  164. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  165. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  166. package/ui/components/wallet/ProfileButton.tsx +62 -0
  167. package/ui/components/wallet/UserAvatar.tsx +85 -0
  168. package/ui/components/wallet/avatarIcons.ts +122 -0
  169. package/ui/exportTransactions.ts +36 -4
  170. package/ui/hooks/useContactsStore.ts +10 -0
  171. package/ui/hooks/useExportWalletData.ts +25 -2
  172. package/ui/hooks/useMandala.ts +18 -1
  173. package/ui/hooks/useOnline.ts +65 -20
  174. package/ui/importDatabases.ts +339 -24
  175. package/ui/index.ts +33 -2
  176. package/ui/isImageUrl.ts +6 -0
  177. package/ui/printRecoveryShares.ts +9 -10
  178. package/ui/recoveryPrompts.ts +91 -0
  179. package/ui/resolveIdentity.ts +31 -9
  180. package/ui/screens/ConnectionsScreen.tsx +86 -19
  181. package/ui/screens/ContactScreen.tsx +289 -0
  182. package/ui/screens/ContactsScreen.tsx +373 -0
  183. package/ui/screens/IdentifierScreen.tsx +256 -0
  184. package/ui/screens/NewContactScreen.tsx +362 -0
  185. package/ui/screens/PairScreen.tsx +74 -2
  186. package/ui/screens/PayScreen.tsx +20 -7
  187. package/ui/screens/ProfileScreen.tsx +783 -0
  188. package/ui/screens/SettingsScreen.tsx +10 -4
  189. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  190. package/ui/screens/TrustScreen.tsx +100 -5
  191. package/ui/screens/VaultScreen.tsx +410 -61
  192. package/ui/screens/VaultTransferScreen.tsx +59 -7
  193. package/ui/screens/WalletCheckScreen.tsx +17 -6
  194. package/ui/screens/WalletConfigScreen.tsx +124 -28
  195. package/ui/screens/WalletHomeScreen.tsx +640 -104
  196. package/ui/screens/detailActionKeys.ts +55 -0
  197. package/ui/tokenFormat.ts +44 -4
  198. package/ui/tokenStatus.ts +21 -0
  199. package/ui/txStatus.ts +48 -5
  200. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -53,6 +53,7 @@ import {
53
53
  isVaultAvailable,
54
54
  isBackupPushEnabled,
55
55
  getBackupUrl,
56
+ readBackupAttestation,
56
57
  type VaultWallet,
57
58
  type VaultMeta,
58
59
  type VaultSpendResult,
@@ -176,9 +177,7 @@ export function VaultTransferScreen() {
176
177
  if (!m || m.keys.length === 0) return
177
178
  // Restored records are offered only after this device has proved live
178
179
  // 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
180
+ const eligible = m.recovery?.required ? m.keys.filter(k => m.recovery!.adoptedSerials.includes(k.serial)) : m.keys
182
181
  const lastUsed = eligible.find(k => k.serial === m.lastUsedSerial)
183
182
  setChosenSerial((lastUsed ?? eligible[0])?.serial)
184
183
  })
@@ -191,9 +190,8 @@ export function VaultTransferScreen() {
191
190
  // every render would invalidate them all.
192
191
  const allKeys = useMemo(() => meta?.keys ?? [], [meta])
193
192
  const keys = useMemo(
194
- () => meta?.recovery?.required
195
- ? allKeys.filter(key => meta.recovery!.adoptedSerials.includes(key.serial))
196
- : allKeys,
193
+ () =>
194
+ meta?.recovery?.required ? allKeys.filter(key => meta.recovery!.adoptedSerials.includes(key.serial)) : allKeys,
197
195
  [meta, allKeys]
198
196
  )
199
197
  const chosen = keys.find(k => k.serial === chosenSerial)
@@ -208,10 +206,16 @@ export function VaultTransferScreen() {
208
206
  ? Number.isFinite(sats) && sats >= VAULT_DEPOSIT_MIN
209
207
  : isMax || (Number.isFinite(sats) && sats > 0)
210
208
  const transfersBlocked = !!meta?.pendingRemoval
209
+ // Six keys is one more than a lock holds (a replacement waiting for the
210
+ // removal of the key it replaces), so nothing that creates a Vault output
211
+ // runs. A deposit always would; a withdrawal only when its remainder is
212
+ // re-vaulted, which run() learns from the preview.
213
+ const overLockLimit = allKeys.length > VAULT_MAX_KEYS
211
214
  const canRun =
212
215
  validAmount &&
213
216
  !busy &&
214
217
  !transfersBlocked &&
218
+ !(isDeposit && overLockLimit) &&
215
219
  !!pm &&
216
220
  balance !== null &&
217
221
  (isDeposit ? released : chosen !== undefined)
@@ -245,6 +249,29 @@ export function VaultTransferScreen() {
245
249
  if (choice === 'settings') router.push('/wallet-config?section=backup' as never)
246
250
  }, [backupConfigured, router])
247
251
 
252
+ /**
253
+ * XR-003: a distinct, blocking check from `privateBackupEnabled` above —
254
+ * that one gates the encrypted REMOTE backup upload; this one gates the
255
+ * LOCAL mnemonic that alone can recover this vault (I1/I2 — YubiKeys carry
256
+ * no seed) ever having been preserved off-device. VaultScreen's own
257
+ * deposit/enroll entry points already require this before reaching this
258
+ * screen, but a session that reached here some other way (a deep link, or
259
+ * one that skipped the ceremony before this fix shipped) must still be
260
+ * caught at the funding boundary rather than only at first creation.
261
+ */
262
+ const seedNotPreservedAlert = useCallback(async () => {
263
+ haptics.error()
264
+ const choice = await showAlert({
265
+ title: t('vault_seed_not_preserved_title'),
266
+ message: t('vault_seed_not_preserved_body'),
267
+ buttons: [
268
+ { text: t('vault_seed_not_preserved_cta'), key: 'backup' },
269
+ { text: t('vault_cancel'), key: 'cancel', style: 'cancel' }
270
+ ]
271
+ })
272
+ if (choice === 'backup') router.push('/auth/mnemonic?flow=backup' as never)
273
+ }, [router])
274
+
248
275
  /** Everything vaultErrorCopy can name for this screen's errors. */
249
276
  const errorParams = useCallback(
250
277
  (e: unknown): VaultErrorParams => {
@@ -284,6 +311,15 @@ export function VaultTransferScreen() {
284
311
  setError(null)
285
312
  try {
286
313
  if (isDeposit) {
314
+ // XR-003: checked before privateBackupEnabled and before the
315
+ // first-deposit confirmation, for the same reason both of those run
316
+ // early — the user must never be asked to approve a transfer that a
317
+ // missing recovery prerequisite would make catastrophic instead of
318
+ // merely rejected.
319
+ if (!(await readBackupAttestation(pm, adminOriginator))) {
320
+ await seedNotPreservedAlert()
321
+ return
322
+ }
287
323
  // Check before first-deposit confirmation so the user is never asked
288
324
  // to approve a transfer the service must reject. The service receives
289
325
  // the same callback and checks again at the output-creation boundary.
@@ -340,6 +376,14 @@ export function VaultTransferScreen() {
340
376
  if (choice !== 'all') return
341
377
  withdrawAll = true
342
378
  }
379
+ // A remainder that goes back into the vault needs a lock, and six
380
+ // keys is one more than a lock holds. Refuse before any NFC sheet;
381
+ // the service refuses too.
382
+ if (overLockLimit && !withdrawAll && remainder >= VAULT_DEPOSIT_MIN) {
383
+ haptics.error()
384
+ setError(vaultErrorCopy('too-many-active-keys'))
385
+ return
386
+ }
343
387
  setBusy(true)
344
388
  const result: VaultSpendResult = await withdrawFromVault(
345
389
  w,
@@ -413,6 +457,7 @@ export function VaultTransferScreen() {
413
457
  balance,
414
458
  isDeposit,
415
459
  isMax,
460
+ overLockLimit,
416
461
  sats,
417
462
  keys.length,
418
463
  allNames,
@@ -423,6 +468,7 @@ export function VaultTransferScreen() {
423
468
  namesFor,
424
469
  privateBackupEnabled,
425
470
  backupOffAlert,
471
+ seedNotPreservedAlert,
426
472
  errorParams,
427
473
  refresh,
428
474
  router
@@ -489,7 +535,13 @@ export function VaultTransferScreen() {
489
535
  )}
490
536
 
491
537
  {transfersBlocked && (
492
- <Text style={[styles.floor, { color: colors.warning }]}>{t('vault_err_relock_required')}</Text>
538
+ <Text style={[styles.floor, { color: colors.warning }]}>
539
+ {t(meta?.pendingRemoval?.state === 'broadcast' ? 'vault_removal_awaiting_network' : 'vault_err_relock_required')}
540
+ </Text>
541
+ )}
542
+
543
+ {isDeposit && overLockLimit && !transfersBlocked && (
544
+ <Text style={[styles.floor, { color: colors.warning }]}>{t('vault_err_too_many_active_keys')}</Text>
493
545
  )}
494
546
 
495
547
  {!isDeposit && meta?.recovery?.required && keys.length === 0 && (
@@ -29,12 +29,12 @@ import {
29
29
  } from '../../core/pay/rails/handle'
30
30
  import {
31
31
  derivationPrefixFor,
32
- getCurrentDate,
33
32
  getPaymentAddress,
34
- MAX_RECOVERY_DAYS,
33
+ recoveryDatesToScan,
35
34
  sweepAddress,
36
35
  wocConfigFor
37
36
  } from '../../core/pay/rails/address'
37
+ import { getIssuedDates } from '../../core/pay/receiveHistory'
38
38
  import {
39
39
  runWalletCheck,
40
40
  type WalletCheckPorts,
@@ -132,6 +132,7 @@ function useWalletCheckPorts(): WalletCheckPorts {
132
132
  adminOriginator,
133
133
  storage,
134
134
  selectedNetwork,
135
+ getBackupPseudonym,
135
136
  checkUtxoSpendability,
136
137
  releaseStuckReservations,
137
138
  runMonitorTask,
@@ -143,7 +144,10 @@ function useWalletCheckPorts(): WalletCheckPorts {
143
144
  return useMemo<WalletCheckPorts>(
144
145
  () => ({
145
146
  checkOnline: async () => ({ online: await getOnline() }),
146
- checkBackup: async () => await getBackupUploadState(),
147
+ // Scoped to THIS wallet's own identity — see XR-009 / getBackupUploadState. No
148
+ // pseudonym yet (no wallet built for this chain) can never match a real cursor key,
149
+ // so `enabled` still reads the ordinary opt-out preference while `uploaded` is false.
150
+ checkBackup: async () => await getBackupUploadState(selectedNetwork, getBackupPseudonym(selectedNetwork) ?? ''),
147
151
  checkPhraseBackup: async () => {
148
152
  // Advisory: it records that someone pressed "I have written these
149
153
  // down" or completed a print. Nothing verifies the paper exists — but
@@ -210,9 +214,15 @@ function useWalletCheckPorts(): WalletCheckPorts {
210
214
  if (!wallet) return { imported: 0 }
211
215
  const woc = wocConfigFor(selectedNetwork)
212
216
  let imported = 0
213
- for (let day = 0; day < MAX_RECOVERY_DAYS; day++) {
217
+ // XR-055: scan every date this device has actually issued a receive address for
218
+ // (pay/receiveHistory.ts), not a fixed 30-day lookback — a payer who sat on a
219
+ // legitimately-displayed address longer than that had no shipped path back to
220
+ // internalizeAction. Falls back to the old fixed-window loop only when there is no
221
+ // recorded history at all (unchanged behaviour for that case).
222
+ const recorded = storage ? await getIssuedDates(storage as never) : []
223
+ for (const date of recoveryDatesToScan(recorded)) {
214
224
  try {
215
- const prefix = derivationPrefixFor(getCurrentDate(day))
225
+ const prefix = derivationPrefixFor(date)
216
226
  const address = await getPaymentAddress(wallet, adminOriginator, prefix, woc.network)
217
227
  const result = await sweepAddress({
218
228
  wallet: wallet as never,
@@ -223,7 +233,7 @@ function useWalletCheckPorts(): WalletCheckPorts {
223
233
  })
224
234
  if (result.importedSatoshis > 0) imported++
225
235
  } catch {
226
- // One day's miss must not skip the rest of the lookback.
236
+ // One date's miss must not skip the rest of the scan.
227
237
  }
228
238
  }
229
239
  return { imported }
@@ -232,6 +242,7 @@ function useWalletCheckPorts(): WalletCheckPorts {
232
242
  [
233
243
  adminOriginator,
234
244
  checkUtxoSpendability,
245
+ getBackupPseudonym,
235
246
  mandala,
236
247
  releaseStuckReservations,
237
248
  runMonitorTask,
@@ -9,7 +9,9 @@ import {
9
9
  KNOWN_ARC_URLS,
10
10
  DEFAULT_ARC_URLS,
11
11
  arcUrlStorageKey,
12
- arcApiTokenStorageKey,
12
+ getArcApiToken,
13
+ setArcApiToken,
14
+ validateArcUrl,
13
15
  useTheme,
14
16
  spacing,
15
17
  typography,
@@ -107,6 +109,19 @@ function loadExpoRouter(): ExpoRouterModule {
107
109
  return expoRouterMod
108
110
  }
109
111
 
112
+ /**
113
+ * Demo mode, or null in anything but a dev bundle.
114
+ *
115
+ * Required at module scope behind `__DEV__` so a release build inlines the
116
+ * flag as false and folds the require — and the whole demo folder — out.
117
+ * Same pattern as `utils/AgentationGate.tsx`.
118
+ */
119
+ type DemoModule = typeof import('../../core/demo')
120
+ const demoMod: DemoModule | null = __DEV__
121
+ ? // eslint-disable-next-line @typescript-eslint/no-require-imports
122
+ (require('../../core/demo') as DemoModule)
123
+ : null
124
+
110
125
  /** The three serials the DEV mock can present, cycled by the selector row below. */
111
126
  type MockPresentKey = Parameters<typeof setMockPresentKey>[0]
112
127
  const NEXT_MOCK_KEY: Record<MockPresentKey, MockPresentKey> = {
@@ -123,6 +138,7 @@ export function WalletConfigScreen() {
123
138
  const { section } = useLocalSearchParams<{ section?: string }>()
124
139
  const openBackup = section === 'backup'
125
140
  const Ionicons = loadIonicons()
141
+
126
142
  const {
127
143
  managers,
128
144
  adminOriginator,
@@ -143,6 +159,7 @@ export function WalletConfigScreen() {
143
159
  // Not read from getMockPresentKey() at mount: the mock is off by default and
144
160
  // the row is hidden until the toggle turns it on, at which point it syncs.
145
161
  const [mockPresent, setMockPresent] = useState<MockPresentKey>('MOCK-DEV-1')
162
+ const [demoOn, setDemoOn] = useState(() => demoMod?.isDemoModeEnabled() ?? false)
146
163
  const [isImporting, setIsImporting] = useState(false)
147
164
  const [vaultMockOn, setVaultMockOn] = useState(false)
148
165
  const [backupPushOn, setBackupPushOn] = useState(true)
@@ -161,6 +178,7 @@ export function WalletConfigScreen() {
161
178
  const [arcUrlInput, setArcUrlInput] = useState('')
162
179
  const [arcTokenInput, setArcTokenInput] = useState('')
163
180
  const [arcSaving, setArcSaving] = useState(false)
181
+ const [arcUrlError, setArcUrlError] = useState(false)
164
182
  const { satoshisPerUSD, usdToFiat = {} } = useContext(ExchangeRateContext)
165
183
 
166
184
  const currentCurrency = settings?.currency || 'BSV'
@@ -350,15 +368,15 @@ export function WalletConfigScreen() {
350
368
  }
351
369
  }, [storageBusy, storage, managers, adminOriginator, t])
352
370
 
353
- // Load persisted ARC URL + token for current network
371
+ // Load persisted ARC URL + token for current network. The token is read
372
+ // via getArcApiToken (XR-106: SecureStore-backed, not plaintext AsyncStorage).
354
373
  useEffect(() => {
355
- Promise.all([
356
- AsyncStorage.getItem(arcUrlStorageKey(selectedNetwork)),
357
- AsyncStorage.getItem(arcApiTokenStorageKey(selectedNetwork))
358
- ]).then(([url, token]) => {
359
- setArcUrlInput(url ?? DEFAULT_ARC_URLS[selectedNetwork] ?? '')
360
- setArcTokenInput(token ?? '')
361
- })
374
+ Promise.all([AsyncStorage.getItem(arcUrlStorageKey(selectedNetwork)), getArcApiToken(selectedNetwork)]).then(
375
+ ([url, token]) => {
376
+ setArcUrlInput(url ?? DEFAULT_ARC_URLS[selectedNetwork] ?? '')
377
+ setArcTokenInput(token ?? '')
378
+ }
379
+ )
362
380
  }, [selectedNetwork])
363
381
 
364
382
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
@@ -390,7 +408,10 @@ export function WalletConfigScreen() {
390
408
  const result = await importWalletDatabase(storage)
391
409
  if (result.imported) {
392
410
  showToast(t('import_success'), { type: 'success' })
393
- await rebuildWallet()
411
+ // Not restoreFromBackup: a raw db import already carries a complete
412
+ // local database and must not also replay the encrypted remote
413
+ // backup on top of it — only the same reconciliation pass (XR-079).
414
+ await rebuildWallet({ reviewImportedCoins: true })
394
415
  }
395
416
  } catch (e) {
396
417
  console.warn('[WalletConfig] Import failed:', e)
@@ -416,20 +437,39 @@ export function WalletConfigScreen() {
416
437
 
417
438
  const handleApplyArc = async () => {
418
439
  if (arcSaving) return
440
+ const url = arcUrlInput.trim()
441
+ const defaultUrl = DEFAULT_ARC_URLS[selectedNetwork] ?? ''
442
+ // XR-064: a custom endpoint carries the signed transaction (and any
443
+ // configured API token) over the wire — require https, with a narrow
444
+ // loopback exception for local dev.
445
+ if (url && url !== defaultUrl && !validateArcUrl(url)) {
446
+ setArcUrlError(true)
447
+ return
448
+ }
449
+ setArcUrlError(false)
419
450
  setArcSaving(true)
420
451
  try {
421
- const url = arcUrlInput.trim()
422
452
  const token = arcTokenInput.trim()
423
- const defaultUrl = DEFAULT_ARC_URLS[selectedNetwork] ?? ''
453
+ const previousUrl = (await AsyncStorage.getItem(arcUrlStorageKey(selectedNetwork))) ?? defaultUrl
454
+ const previousToken = (await getArcApiToken(selectedNetwork)) ?? ''
455
+ const nextUrl = url || defaultUrl
456
+ const originChanged = previousUrl !== nextUrl
457
+ // XR-064: a token left exactly as loaded from storage must never
458
+ // silently follow onto a different origin the person just switched
459
+ // to — require it to be re-entered for the new host. A token the
460
+ // person actually typed in this same action (different from what was
461
+ // stored) is an intentional, explicit entry and is still honored.
462
+ const stalePriorToken = originChanged && token === previousToken
424
463
  if (url && url !== defaultUrl) {
425
464
  await AsyncStorage.setItem(arcUrlStorageKey(selectedNetwork), url)
426
465
  } else {
427
466
  await AsyncStorage.removeItem(arcUrlStorageKey(selectedNetwork))
428
467
  }
429
- if (token) {
430
- await AsyncStorage.setItem(arcApiTokenStorageKey(selectedNetwork), token)
468
+ if (token && !stalePriorToken) {
469
+ await setArcApiToken(selectedNetwork, token)
431
470
  } else {
432
- await AsyncStorage.removeItem(arcApiTokenStorageKey(selectedNetwork))
471
+ await setArcApiToken(selectedNetwork, null)
472
+ if (stalePriorToken) setArcTokenInput('')
433
473
  }
434
474
  setArcExpanded(false)
435
475
  await rebuildWallet()
@@ -443,10 +483,11 @@ export function WalletConfigScreen() {
443
483
  const handleResetArc = async () => {
444
484
  await Promise.all([
445
485
  AsyncStorage.removeItem(arcUrlStorageKey(selectedNetwork)),
446
- AsyncStorage.removeItem(arcApiTokenStorageKey(selectedNetwork))
486
+ setArcApiToken(selectedNetwork, null)
447
487
  ])
448
488
  setArcUrlInput(DEFAULT_ARC_URLS[selectedNetwork] ?? '')
449
489
  setArcTokenInput('')
490
+ setArcUrlError(false)
450
491
  setArcExpanded(false)
451
492
  await rebuildWallet()
452
493
  }
@@ -645,9 +686,15 @@ export function WalletConfigScreen() {
645
686
  <View style={localStyles.arcInputRow}>
646
687
  <Text style={[localStyles.arcLabel, { color: colors.textSecondary }]}>{t('arc_custom_url')}</Text>
647
688
  <TextInput
648
- style={[localStyles.arcInput, { color: colors.textPrimary, borderColor: colors.separator }]}
689
+ style={[
690
+ localStyles.arcInput,
691
+ { color: colors.textPrimary, borderColor: arcUrlError ? colors.error : colors.separator }
692
+ ]}
649
693
  value={arcUrlInput}
650
- onChangeText={setArcUrlInput}
694
+ onChangeText={text => {
695
+ setArcUrlInput(text)
696
+ if (arcUrlError) setArcUrlError(false)
697
+ }}
651
698
  placeholder="https://..."
652
699
  placeholderTextColor={colors.textSecondary}
653
700
  autoCapitalize="none"
@@ -655,6 +702,9 @@ export function WalletConfigScreen() {
655
702
  keyboardType="url"
656
703
  returnKeyType="next"
657
704
  />
705
+ {arcUrlError && (
706
+ <Text style={{ ...typography.caption1, color: colors.error }}>{t('arc_url_https_required')}</Text>
707
+ )}
658
708
  </View>
659
709
  <View style={localStyles.arcInputRow}>
660
710
  <Text style={[localStyles.arcLabel, { color: colors.textSecondary }]}>{t('arc_api_token')}</Text>
@@ -667,7 +717,9 @@ export function WalletConfigScreen() {
667
717
  autoCapitalize="none"
668
718
  autoCorrect={false}
669
719
  returnKeyType="done"
670
- secureTextEntry={false}
720
+ // XR-106: this is a live Bearer credential, not display
721
+ // text — mask it like any other secret field.
722
+ secureTextEntry
671
723
  />
672
724
  </View>
673
725
  <View style={localStyles.arcButtonRow}>
@@ -785,6 +837,33 @@ export function WalletConfigScreen() {
785
837
  {/* ── Data & Security ── */}
786
838
  <View onLayout={event => setBackupSectionY(event.nativeEvent.layout.y)}>
787
839
  <GroupedSection header={t('data_and_security')}>
840
+ {/* Demo mode: a wallet full of obviously-fake BSV and stablecoins,
841
+ for showing the app without an account or a balance. Literal
842
+ copy rather than i18n — this row renders only under `__DEV__`
843
+ and never reaches a release build, so it is not user copy. */}
844
+ {__DEV__ && demoMod && (
845
+ <ListRow
846
+ label="Demo mode (dev)"
847
+ icon="flask-outline"
848
+ iconColor="#8E8E93"
849
+ showChevron={false}
850
+ value={demoOn ? 'On' : 'Off'}
851
+ onPress={() => {
852
+ const next = !demoOn
853
+ setDemoOn(next)
854
+ demoMod.setDemoModeEnabled(next)
855
+ }}
856
+ />
857
+ )}
858
+ {__DEV__ && demoMod && demoOn && (
859
+ <ListRow
860
+ label="Reset demo data (dev)"
861
+ icon="refresh-outline"
862
+ iconColor="#8E8E93"
863
+ showChevron={false}
864
+ onPress={() => demoMod.resetDemoLedger()}
865
+ />
866
+ )}
788
867
  {/* Vault's primary entry lives on the wallet menu (below Payments).
789
868
  The DEV mock toggle stays here. */}
790
869
  {__DEV__ && (
@@ -913,15 +992,32 @@ export function WalletConfigScreen() {
913
992
  if (choice !== 'delete') return
914
993
  setLoggingOut(true)
915
994
  // No artificial yield before this call, unlike the wallet-creation
916
- // spinner: logout() itself is a fire-and-forget kickoff (its first
917
- // real work is behind an await inside its own async IIFE), so it
918
- // returns to let React paint the spinner on its own. Deliberately
919
- // NOT delayed further — logout's very first synchronous step stops
920
- // the background monitor's task loop, and a gap here let the
921
- // monitor's own pending tick sneak in a fresh task run against
922
- // storage that was about to be torn down (WERR_UNKNOWN "Database
923
- // not initialized" from a task caught mid-flight).
924
- logout()
995
+ // spinner: logout()'s synchronous prefix (which stops the
996
+ // background monitor's task loop) still runs before its first
997
+ // await, exactly as before — a gap here let the monitor's own
998
+ // pending tick sneak in a fresh task run against storage that
999
+ // was about to be torn down (WERR_UNKNOWN "Database not
1000
+ // initialized" from a task caught mid-flight). Awaiting the
1001
+ // result below only affects what happens AFTER that teardown.
1002
+ //
1003
+ // XR-107: logout() now resolves to whether the secrets layer
1004
+ // verified every legacy plaintext item erased. A persistent
1005
+ // SecureStore delete failure must be reported, not silently
1006
+ // treated as a completed "Delete Wallet" — the user needs to
1007
+ // know and be able to retry, rather than being navigated away
1008
+ // as though nothing were left behind.
1009
+ const erased = await logout()
1010
+ if (!erased) {
1011
+ setLoggingOut(false)
1012
+ await showAlert({
1013
+ title: t('delete_wallet_failed_title'),
1014
+ message: t('delete_wallet_failed_body'),
1015
+ buttons: [{ text: t('vault_ok'), key: 'ok' }],
1016
+ })
1017
+ }
1018
+ // On success logout() has already navigated away — the screen
1019
+ // that owns `loggingOut` is gone, so there is nothing left to
1020
+ // reset here.
925
1021
  }}
926
1022
  destructive
927
1023
  showChevron={false}