@bsv/expo-wallet-toolbox 0.7.0 → 0.10.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 (154) hide show
  1. package/CHANGELOG.md +1790 -0
  2. package/README.md +54 -1
  3. package/core/amountFormatHelpers.ts +20 -2
  4. package/core/backup/RemoteSyncReader.ts +131 -19
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +147 -9
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +70 -4
  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/constants.ts +14 -1
  15. package/core/context/ExchangeRateContext.tsx +34 -27
  16. package/core/context/LocalStorageProvider.tsx +43 -40
  17. package/core/context/UserContext.tsx +18 -7
  18. package/core/context/VaultContext.tsx +49 -2
  19. package/core/context/WalletConnectionContext.tsx +203 -11
  20. package/core/context/WalletContext.tsx +653 -175
  21. package/core/headers/OfflineFirstChaintracks.ts +48 -4
  22. package/core/headers/headerStore.ts +26 -4
  23. package/core/headers/headerSyncTriggers.ts +65 -0
  24. package/core/headers/syncHeaders.ts +12 -1
  25. package/core/i18n/translations.tsx +1001 -25
  26. package/core/identity/handleRegistry/client.ts +31 -2
  27. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  28. package/core/identity/handleRegistry/resolver.ts +71 -3
  29. package/core/index.ts +33 -3
  30. package/core/localpay/build.ts +225 -24
  31. package/core/localpay/pending.ts +110 -7
  32. package/core/localpay/pendingAbortAuthority.ts +95 -0
  33. package/core/localpay/pendingAborts.ts +264 -28
  34. package/core/localpay/session.ts +42 -17
  35. package/core/localpay/settlementAck.ts +10 -1
  36. package/core/localpay/transport/socket.ts +52 -3
  37. package/core/localpay/types.ts +9 -1
  38. package/core/localpay/verify.ts +143 -16
  39. package/core/mandala/abortGuard.ts +96 -20
  40. package/core/mandala/createRuntime.ts +206 -33
  41. package/core/mandala/drain.ts +89 -11
  42. package/core/mandala/inboxPrehold.ts +186 -0
  43. package/core/mandala/permissionModule.ts +202 -20
  44. package/core/mandala/settlementStore.ts +24 -2
  45. package/core/mandala/types.ts +40 -5
  46. package/core/monitor/TaskBackupPush.ts +14 -0
  47. package/core/monitor/TaskDrainOutbox.ts +14 -0
  48. package/core/monitor/TaskSendOffline.ts +14 -0
  49. package/core/net/publicDestination.ts +91 -0
  50. package/core/net/validateArcUrl.ts +22 -0
  51. package/core/offline/cancelParked.ts +134 -13
  52. package/core/offline/payerHold.ts +100 -24
  53. package/core/offline/plan.ts +36 -7
  54. package/core/pay/beefRepair.ts +6 -2
  55. package/core/pay/damagedInbox.ts +24 -0
  56. package/core/pay/rails/address.ts +107 -12
  57. package/core/pay/rails/handle.ts +117 -22
  58. package/core/pay/rails/index.ts +45 -7
  59. package/core/pay/rails/nativeIntent.ts +61 -0
  60. package/core/pay/rails/nearby.ts +1 -0
  61. package/core/pay/receiveHistory.ts +93 -0
  62. package/core/pay/recordProof.ts +19 -1
  63. package/core/pay/refreshProofGuard.ts +42 -1
  64. package/core/pay/watchlist.ts +5 -2
  65. package/core/peerpay/control.ts +17 -18
  66. package/core/peerpay/handleResendRequests.ts +58 -4
  67. package/core/peerpay/outbox.ts +3 -1
  68. package/core/recovery/backupMaterial.ts +61 -0
  69. package/core/recovery/createWallet.ts +95 -0
  70. package/core/recovery/recoverWallet.ts +120 -0
  71. package/core/recovery/restoreWallet.ts +170 -0
  72. package/core/recovery/secret.ts +92 -0
  73. package/core/recovery/shareCollector.ts +71 -0
  74. package/core/recovery/shareParsing.ts +87 -0
  75. package/core/recovery/shares.ts +116 -0
  76. package/core/recovery/useRecoveryDeps.ts +70 -0
  77. package/core/services/arcTokenStorage.ts +52 -0
  78. package/core/services/arcadeBroadcastProvider.ts +232 -48
  79. package/core/services/autoApprovePolicy.ts +105 -0
  80. package/core/services/callbackToken.ts +19 -0
  81. package/core/services/capWalletArgs.ts +14 -2
  82. package/core/services/connectionAuthority.ts +98 -0
  83. package/core/services/exchangeRate.ts +35 -12
  84. package/core/services/externalOrigin.ts +11 -0
  85. package/core/services/secrets/kek.ts +126 -29
  86. package/core/services/secrets/migration.ts +16 -4
  87. package/core/services/secrets/store.ts +42 -14
  88. package/core/services/vault/VaultKeyService.ts +228 -45
  89. package/core/services/vault/chainRecovery.ts +483 -0
  90. package/core/services/vault/driver.ts +9 -1
  91. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  92. package/core/services/vault/guard.ts +218 -32
  93. package/core/services/vault/hardwareLease.ts +19 -0
  94. package/core/services/vault/metaAuthority.ts +210 -0
  95. package/core/services/vault/pivReset.ts +64 -23
  96. package/core/services/vault/r1comb.ts +139 -3
  97. package/core/services/vault/session.ts +25 -4
  98. package/core/services/vault/transfers.ts +866 -170
  99. package/core/services/vault/types.ts +19 -4
  100. package/core/services/vault/vaultStore.ts +256 -29
  101. package/core/services/walletArgLimits.ts +45 -2
  102. package/core/services/walletConnectionValidation.ts +76 -6
  103. package/core/services/walletServiceConfig.ts +10 -8
  104. package/core/storage/StorageExpoSQLite.ts +47 -13
  105. package/core/storage/methods/findSql.ts +21 -2
  106. package/core/storage/methods/offlineActions.ts +10 -1
  107. package/core/storage/methods/processOfflineActions.ts +116 -23
  108. package/core/storage/schema/createTables.ts +126 -2
  109. package/core/stores/ConnectionStore.ts +34 -0
  110. package/core/toolboxConfig.ts +45 -11
  111. package/core/walletDbRegistry.ts +63 -0
  112. package/core/walletMonitor.ts +17 -1
  113. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  114. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  115. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  116. package/package.json +2 -2
  117. package/ui/backupShares.ts +26 -169
  118. package/ui/components/pay/AddressReceive.tsx +13 -6
  119. package/ui/components/pay/AssetPicker.tsx +30 -9
  120. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  121. package/ui/components/pay/NearbyFlow.tsx +511 -251
  122. package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
  123. package/ui/components/pay/UniversalSend.tsx +167 -73
  124. package/ui/components/ui/AlertCard.tsx +38 -5
  125. package/ui/components/ui/PermissionSheet.tsx +197 -66
  126. package/ui/components/vault/EnrollWizard.tsx +61 -13
  127. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  128. package/ui/components/wallet/ActivityRow.tsx +5 -3
  129. package/ui/components/wallet/AmountInput.tsx +8 -2
  130. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  131. package/ui/components/wallet/Balance.tsx +42 -23
  132. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  133. package/ui/exportTransactions.ts +36 -4
  134. package/ui/hooks/useExportWalletData.ts +25 -2
  135. package/ui/importDatabases.ts +339 -24
  136. package/ui/index.ts +9 -3
  137. package/ui/isImageUrl.ts +6 -0
  138. package/ui/printRecoveryShares.ts +9 -10
  139. package/ui/recoveryPrompts.ts +91 -0
  140. package/ui/resolveIdentity.ts +31 -9
  141. package/ui/screens/ConnectionsScreen.tsx +86 -19
  142. package/ui/screens/IdentifierScreen.tsx +30 -8
  143. package/ui/screens/PairScreen.tsx +74 -2
  144. package/ui/screens/SettingsScreen.tsx +10 -4
  145. package/ui/screens/TrustScreen.tsx +99 -4
  146. package/ui/screens/VaultScreen.tsx +410 -61
  147. package/ui/screens/VaultTransferScreen.tsx +59 -7
  148. package/ui/screens/WalletCheckScreen.tsx +17 -6
  149. package/ui/screens/WalletConfigScreen.tsx +82 -28
  150. package/ui/screens/WalletHomeScreen.tsx +179 -88
  151. package/ui/screens/detailActionKeys.ts +55 -0
  152. package/ui/tokenFormat.ts +44 -4
  153. package/ui/txStatus.ts +5 -0
  154. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -124,6 +124,15 @@ async function resolveMandalaAssetMetadata(assetId: string): Promise<MandalaAsse
124
124
  }
125
125
  }
126
126
 
127
+ // XR-039: same paging discipline as `core/localpay/build.ts`'s
128
+ // `listTokenBasket` and `core/mandala/createRuntime.ts`'s `listTokenOutputs`
129
+ // -- a page size generous enough that any realistic basket is one round
130
+ // trip, and a hard page ceiling so a wallet that reports a `totalOutputs` it
131
+ // never actually serves (or repeats a page forever) cannot spin
132
+ // `listMandalaTokenOutpoints` into an infinite loop.
133
+ const MANDALA_OUTPOINT_LIST_PAGE = 1000
134
+ const MANDALA_OUTPOINT_LIST_MAX_PAGES = 1000
135
+
127
136
  const DEFAULT_SETTINGS: WalletSettings = {
128
137
  ...LIB_DEFAULT_SETTINGS,
129
138
  trustSettings: {
@@ -155,23 +164,44 @@ const DEFAULT_SETTINGS: WalletSettings = {
155
164
  import type { AppChain } from '../config'
156
165
  import { DEFAULT_STORAGE_URL, DEFAULT_CHAIN, ADMIN_ORIGINATOR, toWalletChain } from '../config'
157
166
  import { getBackupUrl, getMandalaEndpoints } from '../toolboxConfig'
158
- import { DEFAULT_AUTO_APPROVE_THRESHOLD, AUTO_APPROVE_COOLDOWN_MS, AUTO_APPROVE_STORAGE_KEY } from '../constants'
167
+ import {
168
+ DEFAULT_AUTO_APPROVE_THRESHOLD,
169
+ AUTO_APPROVE_COOLDOWN_MS,
170
+ AUTO_APPROVE_STORAGE_KEY,
171
+ AUTO_APPROVE_DAILY_CAP_SATS,
172
+ AUTO_APPROVE_LEDGER_STORAGE_KEY
173
+ } from '../constants'
174
+ import { createAutoApprovePolicy } from '../services/autoApprovePolicy'
175
+ import { deriveCallbackToken } from '../services/callbackToken'
159
176
  import AsyncStorage from '@react-native-async-storage/async-storage'
160
177
  import { UserContext } from './UserContext'
161
178
  import { useLocalStorage } from './LocalStorageProvider'
162
179
  import { usePermissionQueue } from '../hooks/usePermissionQueue'
163
180
  import { configureMandala, resolveAssetMetadata } from '@bsv/mandala'
164
181
  import { MessageBoxClient } from '@bsv/message-box-client'
165
- import { MandalaTokenModule, wrapCreateActionForTokenInputs, type MandalaAssetMetadata } from '../mandala/permissionModule'
182
+ import {
183
+ MandalaTokenModule,
184
+ wrapCreateActionForTokenInputs,
185
+ listAllOutpoints,
186
+ resolveMandalaOutput,
187
+ type MandalaAssetMetadata
188
+ } from '../mandala/permissionModule'
166
189
  import { wrapAbortActionForSettlements } from '../mandala/abortGuard'
167
190
  import { migrateMandalaBasketName } from '../mandala/basketMigration'
168
- import { bindOriginator, createMandalaKvStorage, createMandalaRuntime, type MandalaMessageBox } from '../mandala/createRuntime'
191
+ import {
192
+ bindOriginator,
193
+ createMandalaKvStorage,
194
+ createMandalaRuntime,
195
+ type MandalaMessageBox
196
+ } from '../mandala/createRuntime'
169
197
  import type { MandalaRuntime } from '../mandala/runtime'
170
198
  import { MANDALA_BASKET } from '../mandala/types'
171
199
  import { mandalaSettlementDeps, type CancelParkedSettlementDeps } from '../offline/cancelParked'
172
200
  import { drainMandalaInbox } from '../pay/rails/handle'
173
201
  import { forgetSessionPsks, sealedFramePayloadDecoder } from '../offline/tokenFrames'
202
+ import { disconnectActivePairedSession } from './WalletConnectionContext'
174
203
  import { createServices, chaintracksUrlFor } from '../services/walletServiceConfig'
204
+ import { getArcApiToken } from '../services/arcTokenStorage'
175
205
  import {
176
206
  boundReviewProvenTxs,
177
207
  configureNewHeaderPolling,
@@ -194,11 +224,17 @@ import { StorageProvider, ChaintracksServiceClient } from '@bsv/wallet-toolbox-m
194
224
  import { StorageExpoSQLite } from '../storage'
195
225
  import { makeBuildGeneration } from './buildGeneration'
196
226
  import * as SQLite from 'expo-sqlite'
197
- import { getRegisteredDbs, registerDb, selectLatestDb } from '../walletDbRegistry'
227
+ import {
228
+ getRegisteredDbs,
229
+ purgeRegisteredDbFiles,
230
+ registerDb,
231
+ selectLatestDb,
232
+ unregisterDb
233
+ } from '../walletDbRegistry'
198
234
  import { AppState, AppStateStatus, InteractionManager } from 'react-native'
199
235
  import { getOnline, subscribeOnline } from '../net/online'
200
236
  import { canInternalizePending, processPending } from '../localpay/pending'
201
- import { replayPendingAborts } from '../localpay/pendingAborts'
237
+ import { replayPendingAborts, verifyDeclinedAborts } from '../localpay/pendingAborts'
202
238
  import { TaskSendOffline } from '../monitor/TaskSendOffline'
203
239
  import { MONITOR_STALL_MS, MonitorSupervisor } from '../monitor/MonitorSupervisor'
204
240
  import { TaskCreditInbox } from '../monitor/TaskCreditInbox'
@@ -206,9 +242,11 @@ import { drainUnsentEntries, TaskDrainOutbox } from '../monitor/TaskDrainOutbox'
206
242
  import { TaskBackupPush } from '../monitor/TaskBackupPush'
207
243
  import { pushOnce } from '../backup/push'
208
244
  import { restoreOnImport } from '../backup/restoreOnImport'
245
+ import { backupPseudonym } from '../backup/derive'
246
+ import type { BackupChain } from '../backup/constants'
209
247
  import { processOfflineActions } from '../storage/methods/processOfflineActions'
210
248
  import { findOfflineActions } from '../storage/methods/offlineActions'
211
- import { shouldFailUnprovenTx } from '../pay/refreshProofGuard'
249
+ import { boundedHexResponse, isChainAbsenceConfirmed, shouldFailUnprovenTx } from '../pay/refreshProofGuard'
212
250
  import { inputTxidsFromRawTx, shouldDeferSendWaiting } from '../storage/skipQueuedAncestors'
213
251
  import { provenTxFromBump } from '../pay/provenTxFromBump'
214
252
  import { recordProof } from '../pay/recordProof'
@@ -219,6 +257,9 @@ import { sounds } from '../hooks/useConfirmationSound'
219
257
  import i18n from '../i18n/translations'
220
258
  import { makeBeefRepair } from '../pay/beefRepair'
221
259
  import { shouldReleaseUtxo, type UtxoProbe } from '../walletRepair/shouldReleaseUtxo'
260
+ import { shouldMarkUnspendable } from '../walletRepair/shouldMarkUnspendable'
261
+ import { spenderConsumesOutpoint } from '../walletRepair/spenderConsumesOutpoint'
262
+ import { releaseStuckReservationsOnDb } from '../walletRepair/releaseStuckReservations'
222
263
  import {
223
264
  acceptWithRetry,
224
265
  DEFAULT_MESSAGE_BOX_URL,
@@ -229,7 +270,7 @@ import {
229
270
  retryDelivery
230
271
  } from '../pay/rails/handle'
231
272
  import { getOutboxEntries, pruneExpiredSent, unsentEntries } from '../peerpay/outbox'
232
- import { wocConfigFor } from '../pay/rails/address'
273
+ import { MAX_HEX_RESPONSE_CHARS, wocConfigFor } from '../pay/rails/address'
233
274
  import { PeerPayClient } from '@bsv/message-box-client'
234
275
  import { SWEEP_INTERVAL_MS, runSweep, shouldSweepNow, sweptTotal } from '../pay/sweeper'
235
276
  import { formatAmount } from '../amountFormatHelpers'
@@ -241,10 +282,44 @@ import { OfflineFirstChaintracks } from '../headers/OfflineFirstChaintracks'
241
282
  import { prewarmOwnRoots } from '../headers/prewarm'
242
283
  import { syncHeaders } from '../headers/syncHeaders'
243
284
  import type { HeaderSource } from '../headers/syncHeaders'
285
+ import { startHeaderSyncTriggers } from '../headers/headerSyncTriggers'
286
+
287
+ // Auto-approve accounting (misc-p2-04). Previously a single global cooldown
288
+ // timer let multiple paired origins accidentally throttle each other while
289
+ // placing no ceiling on a single origin's cumulative total. autoApprovePolicy
290
+ // keys the cooldown PER ORIGINATOR and adds a global rolling-24h cumulative
291
+ // cap across every originator — see services/autoApprovePolicy.ts. Module
292
+ // scope, same lifetime as the value it replaces; `threshold` reads a snapshot
293
+ // updated on every spendingAuthorizationCallback call (see below) since the
294
+ // persisted threshold is itself read fresh per-request.
295
+ let autoApproveThresholdSnapshot = 0
296
+ const autoApprovePolicy = createAutoApprovePolicy({
297
+ now: () => Date.now(),
298
+ threshold: () => autoApproveThresholdSnapshot,
299
+ cooldownMs: AUTO_APPROVE_COOLDOWN_MS,
300
+ dailyCapSats: AUTO_APPROVE_DAILY_CAP_SATS
301
+ })
244
302
 
245
- // Global, origin-agnostic rate limit for auto-approved spending.
246
- // In-memory only — resets on app restart (intentional: more secure).
247
- let lastAutoApproveTime = 0
303
+ // Best-effort persistence of the rolling ledger so an app restart does not
304
+ // reset the daily cap. Loaded once per process; a read/write failure never
305
+ // blocks a spend decision — the in-memory ledger stays authoritative either way.
306
+ let autoApproveLedgerLoadedOnce = false
307
+ async function loadAutoApproveLedgerOnce(): Promise<void> {
308
+ if (autoApproveLedgerLoadedOnce) return
309
+ autoApproveLedgerLoadedOnce = true
310
+ try {
311
+ const stored = await AsyncStorage.getItem(AUTO_APPROVE_LEDGER_STORAGE_KEY)
312
+ if (stored) {
313
+ const parsed = JSON.parse(stored)
314
+ if (Array.isArray(parsed)) autoApprovePolicy.loadLedger(parsed)
315
+ }
316
+ } catch {
317
+ // No persisted ledger to restore — start with an empty one, same as today.
318
+ }
319
+ }
320
+ function persistAutoApproveLedger(): void {
321
+ AsyncStorage.setItem(AUTO_APPROVE_LEDGER_STORAGE_KEY, JSON.stringify(autoApprovePolicy.getLedger())).catch(() => {})
322
+ }
248
323
 
249
324
  // -----
250
325
  // Context Types
@@ -272,6 +347,12 @@ export interface BackupRestoreState {
272
347
  /** Chunks in the generation being replayed; 0 until the log index is read. */
273
348
  total: number
274
349
  error?: string
350
+ /**
351
+ * Set alongside a `'restored'` phase, from `restoreOnImport`'s own `verified` — true
352
+ * unless the replayed generation's newest entry could not be proven complete (see
353
+ * RemoteSyncReader.verifiedComplete). Absent for every other phase.
354
+ */
355
+ verified?: boolean
275
356
  }
276
357
 
277
358
  export interface WalletBuildOptions {
@@ -282,6 +363,16 @@ export interface WalletBuildOptions {
282
363
  * to restore, and an auto-build on relaunch must not re-import over a live database.
283
364
  */
284
365
  restoreFromBackup?: boolean
366
+ /**
367
+ * Run the same spendability-reconciliation pass a backup restore runs, once local
368
+ * storage is attached — WITHOUT pulling or replaying the encrypted remote backup.
369
+ *
370
+ * Set ONLY by the raw-database-import flow (ui/importDatabases.ts): that flow already
371
+ * hands over a complete local database, so it must not also overlay a remote backup on
372
+ * top of it, but it still skipped the reconciliation review until this option existed
373
+ * (XR-079).
374
+ */
375
+ reviewImportedCoins?: boolean
285
376
  }
286
377
 
287
378
  export interface WalletContextValue {
@@ -292,8 +383,13 @@ export interface WalletContextValue {
292
383
  // Settings
293
384
  settings: WalletSettings
294
385
  updateSettings: (newSettings: WalletSettings) => Promise<void>
295
- // Logout
296
- logout: () => void
386
+ /** "Delete Wallet". Resolves to whether the secrets layer verified every
387
+ * legacy plaintext item erased (XR-107) — false means a persistent
388
+ * SecureStore delete failure left something recoverable, and the caller
389
+ * must report that as a failure (offer retry) rather than treat the
390
+ * wallet as gone: this same false also means the attestation was left
391
+ * untouched and no navigation happened. */
392
+ logout: () => Promise<boolean>
297
393
  adminOriginator: string
298
394
  basketRequests: BasketAccessRequest[]
299
395
  certificateRequests: CertificateAccessRequest[]
@@ -324,12 +420,31 @@ export interface WalletContextValue {
324
420
  * captured `backupRestore` is still the pre-build render's value. This reads the ref.
325
421
  */
326
422
  getBackupRestore: () => BackupRestoreState
423
+ /**
424
+ * This wallet's own backup-server pseudonym for `chain`, or undefined when no wallet is
425
+ * built for that chain (or none at all). Not a secret — it is exactly what the backup
426
+ * server sees as this wallet's account — but deriving it needs the primary key, so it is
427
+ * exposed this way rather than the key itself. See XR-009 / getBackupUploadState.
428
+ */
429
+ getBackupPseudonym: (chain: BackupChain) => string | undefined
430
+ /**
431
+ * The same value as `walletBuilt`, read fresh.
432
+ *
433
+ * Mirrors `getBackupRestore`'s rationale: a caller that awaits a build or rebuild
434
+ * (recoverWallet's retry loop is the motivating case) and then checks whether the
435
+ * wallet is already built must not see a React state snapshot frozen at the render
436
+ * before the await — it must see the ref, which is updated synchronously at every
437
+ * build/teardown transition.
438
+ */
439
+ getWalletBuilt: () => boolean
327
440
  switchNetwork: (network: AppChain) => Promise<void>
328
441
  /** Tear down the current wallet and re-trigger auto-build (e.g. after DB import).
329
442
  * `restoreFromBackup` threads through to the auto-build's replay, for replacing
330
443
  * an already-built wallet with an imported one (e.g. onboarding's backup-reminder
331
- * "import from backup" over an auto-created wallet). */
332
- rebuildWallet: (opts?: { restoreFromBackup?: boolean }) => Promise<void>
444
+ * "import from backup" over an auto-created wallet). `reviewImportedCoins` threads
445
+ * through to a post-storage-attach reconciliation pass (no remote replay) for a raw
446
+ * database import that already carries a complete local database (XR-079). */
447
+ rebuildWallet: (opts?: { restoreFromBackup?: boolean; reviewImportedCoins?: boolean }) => Promise<void>
333
448
  storage: StorageExpoSQLite | null
334
449
  /**
335
450
  * Mandala stablecoins, or undefined.
@@ -383,7 +498,7 @@ export const WalletContext = createContext<WalletContextValue>({
383
498
  getManagers: () => ({}),
384
499
  settings: DEFAULT_SETTINGS,
385
500
  updateSettings: async () => {},
386
- logout: () => {},
501
+ logout: async () => false,
387
502
  adminOriginator: ADMIN_ORIGINATOR,
388
503
  basketRequests: [],
389
504
  certificateRequests: [],
@@ -407,6 +522,8 @@ export const WalletContext = createContext<WalletContextValue>({
407
522
  buildWalletFromRecoveredKey: async () => {},
408
523
  backupRestore: { phase: 'idle', chunks: 0, total: 0 },
409
524
  getBackupRestore: () => ({ phase: 'idle', chunks: 0, total: 0 }),
525
+ getBackupPseudonym: () => undefined,
526
+ getWalletBuilt: () => false,
410
527
  switchNetwork: async () => {},
411
528
  rebuildWallet: async () => {},
412
529
  storage: null,
@@ -661,6 +778,22 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
661
778
  setBackupRestoreState(next)
662
779
  }, [])
663
780
  const getBackupRestore = useCallback((): BackupRestoreState => backupRestoreRef.current, [])
781
+ const getWalletBuilt = useCallback((): boolean => walletBuiltRef.current, [])
782
+ /**
783
+ * Set once buildWallet resolves this build's backup chain/pseudonym, so a screen (Wallet
784
+ * Check) can scope a backup-cursor lookup to the CURRENT identity (see XR-009) without
785
+ * ever seeing the primary key itself — the pseudonym is derived from it but is not a
786
+ * secret; it is exactly what the backup server sees as this wallet's account. Cleared on
787
+ * logout so a departed wallet's pseudonym is never read back before the next build sets
788
+ * its own; `getBackupPseudonym` also refuses to answer for any OTHER chain, so a stale
789
+ * entry from a network switch can never be misread as the current one's.
790
+ */
791
+ const backupIdentityRef = useRef<{ chain: BackupChain, pseudonym: string } | null>(null)
792
+ const getBackupPseudonym = useCallback(
793
+ (chain: BackupChain): string | undefined =>
794
+ backupIdentityRef.current?.chain === chain ? backupIdentityRef.current.pseudonym : undefined,
795
+ []
796
+ )
664
797
  /**
665
798
  * Set by an import flow immediately before it hands the primary key over, and consumed
666
799
  * (and cleared) by the buildWallet pass it triggers. A ref rather than state because
@@ -668,6 +801,17 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
668
801
  * render — a state read there would see whatever was committed, which is a race.
669
802
  */
670
803
  const restoreIntentRef = useRef(false)
804
+ /**
805
+ * Set by a raw-database-import flow (ui/importDatabases.ts, via
806
+ * rebuildWallet's `reviewImportedCoins` option) immediately before it
807
+ * triggers a rebuild, and consumed (and cleared) once local storage is
808
+ * attached in the build this triggers. Deliberately separate from
809
+ * restoreIntentRef: a raw import already carries a complete local
810
+ * database, so it must NOT also pull and replay the encrypted remote
811
+ * backup — it only needs the same spendability reconciliation pass that
812
+ * restoreIntentRef's path runs after its own replay (XR-079).
813
+ */
814
+ const reviewImportedCoinsRef = useRef(false)
671
815
  /**
672
816
  * Set by rebuildWallet right before finalizeConfig, cleared by the auto-build
673
817
  * effect once it actually starts (or determines there is nothing to build).
@@ -763,6 +907,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
763
907
  AsyncStorage.getItem(AUTO_APPROVE_STORAGE_KEY).then(v => {
764
908
  if (v !== null) autoApproveThresholdRef.current = Number(v) || 0
765
909
  })
910
+ // Restores the rolling auto-approve ledger so an app restart does not
911
+ // reset the daily cap (misc-p2-04). Best-effort — see loadAutoApproveLedgerOnce.
912
+ loadAutoApproveLedgerOnce()
766
913
  AsyncStorage.getItem('walletSettings').then(v => {
767
914
  if (v) setSettings(prev => ({ ...prev, ...JSON.parse(v) }))
768
915
  })
@@ -930,36 +1077,39 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
930
1077
  const { requestID, originator, reason, renewal, spending } = args
931
1078
  if (!requestID || !spending) return
932
1079
 
933
- // Auto-approve small transactions if within threshold and cooldown.
934
- // Read the persisted threshold fresh on every request so a change made
935
- // in wallet-config takes effect immediately (the mount-time ref read
936
- // alone left the old value live until app restart — felt like
937
- // auto-approve was "stuck on").
1080
+ // Auto-approve small transactions if within threshold, per-originator
1081
+ // cooldown, and the global rolling 24h cap (misc-p2-04) — accounting
1082
+ // lives in autoApprovePolicy.ts. Read the persisted threshold fresh on
1083
+ // every request so a change made in wallet-config takes effect
1084
+ // immediately (the mount-time ref read alone left the old value live
1085
+ // until app restart — felt like auto-approve was "stuck on").
938
1086
  try {
939
1087
  const stored = await AsyncStorage.getItem(AUTO_APPROVE_STORAGE_KEY)
940
1088
  if (stored !== null) autoApproveThresholdRef.current = Number(stored) || 0
941
1089
  } catch {}
942
1090
  const threshold = autoApproveThresholdRef.current
943
- const now = Date.now()
944
- const sinceLastMs = now - lastAutoApproveTime
1091
+ autoApproveThresholdSnapshot = threshold
945
1092
  // Logging gated behind __DEV__: an unconditional console.log here flushes
946
1093
  // over the JS↔native bridge on every spend request — i.e. on the payment
947
1094
  // hot path — and shows up as jank under any burst of micropayments.
948
- if (threshold > 0 && spending.satoshis <= threshold) {
949
- if (sinceLastMs >= AUTO_APPROVE_COOLDOWN_MS) {
950
- lastAutoApproveTime = now
951
- if (__DEV__) console.log(`[spend-auth] AUTO-APPROVING requestID=${requestID} sats=${spending.satoshis}`)
952
- managersRef.current.permissionsManager?.grantPermission({
953
- requestID,
954
- ephemeral: true,
955
- amount: spending.satoshis
956
- })
957
- return
958
- }
959
- if (__DEV__) console.log(`[spend-auth] cooldown blocked → manual modal requestID=${requestID}`)
960
- } else if (__DEV__) {
1095
+ const autoApproveDecision = autoApprovePolicy.shouldAutoApprove({
1096
+ originator,
1097
+ satoshis: spending.satoshis
1098
+ })
1099
+ if (autoApproveDecision.approve) {
1100
+ autoApprovePolicy.record({ originator, satoshis: spending.satoshis, at: Date.now() })
1101
+ persistAutoApproveLedger()
1102
+ if (__DEV__) console.log(`[spend-auth] AUTO-APPROVING requestID=${requestID} sats=${spending.satoshis}`)
1103
+ managersRef.current.permissionsManager?.grantPermission({
1104
+ requestID,
1105
+ ephemeral: true,
1106
+ amount: spending.satoshis
1107
+ })
1108
+ return
1109
+ }
1110
+ if (__DEV__) {
961
1111
  console.log(
962
- `[spend-auth] not eligible → manual modal requestID=${requestID} sats=${spending.satoshis} threshold=${threshold}`
1112
+ `[spend-auth] not eligible (${autoApproveDecision.reason}) → manual modal requestID=${requestID} sats=${spending.satoshis} threshold=${threshold}`
963
1113
  )
964
1114
  }
965
1115
 
@@ -1080,16 +1230,26 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1080
1230
  // the backup derivation is frozen on the app-level names.
1081
1231
  const backupChain =
1082
1232
  chain === 'main' ? ('main' as const) : chain === 'test' ? ('test' as const) : ('teratest' as const)
1233
+ // See getBackupPseudonym's own docs: this is what lets Wallet Check scope its
1234
+ // cursor lookup to THIS identity without the primary key itself leaving this scope.
1235
+ backupIdentityRef.current = { chain: backupChain, pseudonym: backupPseudonym(primaryKey, backupChain) }
1083
1236
  const keyDeriver = new KeyDeriver(new PrivateKey(primaryKey))
1084
1237
  const storageManager = new WalletStorageManager(keyDeriver.identityKey)
1085
1238
  const signer = new WalletSigner(walletChain, keyDeriver, storageManager)
1086
1239
 
1087
1240
  const bsvExchangeRate = await getExchangeRate()
1088
- const callbackToken = keyDeriver.identityKey.substring(0, 32)
1089
-
1241
+ // Derived from PRIVATE key material (misc-p2-06) — was previously the
1242
+ // first 32 chars of the PUBLIC identityKey, which any past
1243
+ // counterparty can already reconstruct. See callbackToken.ts.
1244
+ const callbackToken = deriveCallbackToken(keyDeriver)
1245
+
1246
+ // XR-106: the token half is SecureStore-backed (getArcApiToken also
1247
+ // migrates away any plaintext value a pre-fix build left in
1248
+ // AsyncStorage under this same key) — only the URL, which is not a
1249
+ // credential, still lives in plain AsyncStorage.
1090
1250
  const [arcUrlOverride, arcApiTokenOverride] = await Promise.all([
1091
1251
  AsyncStorage.getItem(`arc_custom_url_${chain}`),
1092
- AsyncStorage.getItem(`arc_custom_api_token_${chain}`)
1252
+ getArcApiToken(chain)
1093
1253
  ])
1094
1254
 
1095
1255
  // The remote client the wrapper delegates to. Built here rather than
@@ -1121,6 +1281,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1121
1281
 
1122
1282
  // Replace all default broadcast providers with EF/rawtx-only services.
1123
1283
  // Order: Arcade → Taal → GorillaPool → WoC → Bitails. UntilSuccess stops at first success.
1284
+ // Taal runs on main + test only, GorillaPool on main only; teratest has no public ARC.
1124
1285
  // 'ArcadeBeef' is the toolbox's own Arcade broadcaster, registered
1125
1286
  // because serviceOptions now carries arcadeUrl (needed for Arcade-first
1126
1287
  // proofs and SSE). Our createArcadeBroadcastService replaces it here so
@@ -1132,13 +1293,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1132
1293
  services.postBeefServices.remove('Bitails')
1133
1294
  services.postBeefServices.remove('WhatsOnChain')
1134
1295
  services.postBeefServices.add(createArcadeBroadcastService(serviceOptions.arcUrl!, callbackToken))
1135
- const taalArcUrl =
1136
- chain === 'main'
1137
- ? 'https://arc.taal.com'
1138
- : chain === 'test'
1139
- ? 'https://arc-test.taal.com'
1140
- : 'https://arc-teratest.taal.com'
1141
- services.postBeefServices.add(createTaalBroadcastService(taalArcUrl, serviceOptions.taalApiKey))
1296
+ if (chain === 'main' || chain === 'test') {
1297
+ const taalArcUrl = chain === 'main' ? 'https://arc.taal.com' : 'https://arc-test.taal.com'
1298
+ services.postBeefServices.add(createTaalBroadcastService(taalArcUrl, serviceOptions.taalApiKey))
1299
+ }
1142
1300
  if (chain === 'main') {
1143
1301
  services.postBeefServices.add(createGorillaPoolBroadcastService('https://arc.gorillapool.io'))
1144
1302
  }
@@ -1149,7 +1307,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1149
1307
 
1150
1308
  // Replace WoC getMerklePath with BUMP endpoint — no TSC→BUMP conversion needed.
1151
1309
  // The toolbox's 'Arcade' provider stays where Services put it: first.
1152
- // Every tx this wallet sends goes through Arcade, so GET /v1/tx/{txid}
1310
+ // Every tx this wallet sends goes through Arcade, so GET /tx/{txid}
1153
1311
  // there is the one lookup that can answer as soon as it is mined. WoC
1154
1312
  // BUMP and Bitails are re-added after it as fallbacks, in that order.
1155
1313
  const wocBumpBase =
@@ -1252,6 +1410,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1252
1410
  // ── Select the best database file from the registry ──
1253
1411
  let knownDbs = await getRegisteredDbs(keySuffix, chainStr)
1254
1412
 
1413
+ // Whether THIS build attempt is the one that created selectedDb below, as
1414
+ // opposed to reselecting a file that already existed before this attempt
1415
+ // started (an already-onboarded identity's real database, or a legacy file
1416
+ // discovered on disk). Only true in the "fresh user" branch — see its use at
1417
+ // the restore-failure cleanup further down (XR-017 review follow-up).
1418
+ let dbWasFreshlyCreatedThisAttempt = false
1419
+
1255
1420
  if (knownDbs.length === 0) {
1256
1421
  // First launch after update or fresh user.
1257
1422
  // Probe for a legacy (no-timestamp) database file.
@@ -1267,6 +1432,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1267
1432
  const newName = `wallet-${keySuffix}-${chainStr}net-${ts}.db`
1268
1433
  await registerDb(keySuffix, chainStr, newName)
1269
1434
  knownDbs = [newName]
1435
+ dbWasFreshlyCreatedThisAttempt = true
1270
1436
  console.log(`[WalletContext] Created new timestamped DB: ${newName}`)
1271
1437
  }
1272
1438
  }
@@ -1325,9 +1491,27 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1325
1491
  `[WalletContext] backup restore · restored=${String(restored.restored)} · ` +
1326
1492
  `chunks=${restored.chunks} · reason=${restored.reason ?? 'none'}`
1327
1493
  )
1494
+ // See P1-backup-incomplete-generation: restoreOnImport.pickTarget falls back to
1495
+ // an unverified (no seal) target rather than blocking the import, so this is a
1496
+ // warning rather than a thrown error — but it must not pass silently, since the
1497
+ // replayed generation could be a partial mid-rotation snapshot. The screens
1498
+ // that drive `recoverWallet` surface this to the user directly (restoreUnverified
1499
+ // in ui/recoveryPrompts.ts); this warn is the equivalent for the import flow,
1500
+ // which has no such prompt.
1501
+ if (restored.restored && restored.verified === false) {
1502
+ console.warn(
1503
+ `[backup] restore completed but could not be verified as a complete ` +
1504
+ `generation · deviceId=${String(restored.deviceId)} · generation=${String(restored.generation)}`
1505
+ )
1506
+ }
1328
1507
  setBackupRestore(
1329
1508
  restored.restored
1330
- ? { phase: 'restored', chunks: restored.chunks, total: restored.chunks }
1509
+ ? {
1510
+ phase: 'restored',
1511
+ chunks: restored.chunks,
1512
+ total: restored.chunks,
1513
+ verified: restored.verified
1514
+ }
1331
1515
  : { phase: 'no-backup', chunks: 0, total: 0 }
1332
1516
  )
1333
1517
  } catch (e: any) {
@@ -1339,6 +1523,32 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1339
1523
  try {
1340
1524
  await phoneStorage.destroy()
1341
1525
  } catch {}
1526
+ // restoreOnImport's precondition is that the database is freshly migrated
1527
+ // and still empty of real data — but that is only actually guaranteed when
1528
+ // THIS attempt is the one that just created selectedDb (dbWasFreshlyCreated
1529
+ // ThisAttempt). rebuildWallet({restoreFromBackup:true}) takes this same path
1530
+ // to "recover over an already-onboarded wallet" (see restoreWallet.ts), and
1531
+ // recoverWallet.ts's confirmReplace does not check whether the newly
1532
+ // supplied secret differs from the one already active — so selectedDb can
1533
+ // instead be a pre-existing, already-registered database (this identity's
1534
+ // real, live wallet, or a legacy file just discovered on disk) that this
1535
+ // attempt only SELECTED, never created. Deleting that on a restore failure
1536
+ // would destroy locally-cached change-output/BRC-29 metadata the seed cannot
1537
+ // reconstruct (see XR-017 review follow-up). Only ever discard a database
1538
+ // this exact attempt created: a later build that skips another replay
1539
+ // (recoverWallet's "skip", or any future restoreFromBackup:false call) would
1540
+ // otherwise reselect this SAME partially replayed file via selectLatestDb and
1541
+ // publish it as a working wallet. Both steps are best-effort cleanup: the
1542
+ // ORIGINAL restore failure above is what must reach the caller, not a failure
1543
+ // to tidy up after it.
1544
+ if (dbWasFreshlyCreatedThisAttempt) {
1545
+ try {
1546
+ await unregisterDb(keySuffix, chainStr, selectedDb)
1547
+ } catch {}
1548
+ try {
1549
+ await SQLite.deleteDatabaseAsync(selectedDb)
1550
+ } catch {}
1551
+ }
1342
1552
  throw e
1343
1553
  }
1344
1554
  }
@@ -1362,6 +1572,20 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1362
1572
  console.error('[WalletContext] Failed to add local storage provider:', error)
1363
1573
  }
1364
1574
 
1575
+ // A raw database import (ui/importDatabases.ts) armed this instead of
1576
+ // restoreIntentRef: the imported database is already a complete local
1577
+ // copy, so there is nothing to replay, but it never ran the same
1578
+ // spendability reconciliation an encrypted restore runs above before
1579
+ // its balance is trusted and displayed (XR-079).
1580
+ if (reviewImportedCoinsRef.current) {
1581
+ reviewImportedCoinsRef.current = false
1582
+ try {
1583
+ await wallet.reviewSpendableOutputs(false, true)
1584
+ } catch (error) {
1585
+ console.error('[WalletContext] Post-import reconciliation failed:', error)
1586
+ }
1587
+ }
1588
+
1365
1589
  let migrationUserId: number | undefined
1366
1590
  try {
1367
1591
  const auth = await storageManager.getAuth()
@@ -1427,20 +1651,53 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1427
1651
  // module's own admin pass-through branch). Shared by the module's
1428
1652
  // deps below AND by wrapCreateActionForTokenInputs's wrapper further
1429
1653
  // down, so both use the exact same listing.
1430
- const listMandalaTokenOutpoints = async (): Promise<Set<string>> => {
1431
- try {
1432
- const { outputs } = await wallet.listOutputs(
1433
- { basket: MANDALA_BASKET, includeCustomInstructions: false, limit: 10000 } as never,
1434
- adminOriginator
1435
- )
1436
- return new Set(outputs.map((o: { outpoint: string }) => o.outpoint))
1437
- } catch {
1438
- // A wallet with no Mandala basket yet, or a storage fault -- treat
1439
- // as "no known token inputs" rather than blocking createAction;
1440
- // see permissionModule.ts's doc on this dep failing open.
1441
- return new Set()
1442
- }
1443
- }
1654
+ //
1655
+ // XR-039: paginated to completion via `listAllOutpoints` (a single
1656
+ // 10,000-row page silently truncated a larger basket, and a spend of
1657
+ // an input past that page read as "not a token input" -- the same
1658
+ // balance-truncation bug `core/localpay/build.ts`'s `listTokenBasket`
1659
+ // and `createRuntime.ts`'s `listTokenOutputs` were already fixed
1660
+ // for), and a genuine listing fault now PROPAGATES instead of being
1661
+ // swallowed into an authoritative-looking empty Set -- an empty Set
1662
+ // here reads as "confirmed no token inputs" to every caller, which a
1663
+ // storage fault or a wallet with no Mandala basket are not
1664
+ // distinguishable from without this throwing. The two callers
1665
+ // (`injectMandalaLabelIfTokenInputsPresent`, `anyInputIsTokenCoin`)
1666
+ // are exactly what now fails closed on that throw.
1667
+ const listMandalaTokenOutpoints = (): Promise<Set<string>> =>
1668
+ listAllOutpoints(
1669
+ async (limit, offset) =>
1670
+ await wallet.listOutputs(
1671
+ { basket: MANDALA_BASKET, includeCustomInstructions: false, limit, offset } as never,
1672
+ adminOriginator
1673
+ ),
1674
+ MANDALA_OUTPOINT_LIST_PAGE,
1675
+ MANDALA_OUTPOINT_LIST_MAX_PAGES
1676
+ )
1677
+
1678
+ // XR-041: resolves ONE outpoint named on a `relinquishOutput` call to
1679
+ // its decoded `{assetId, amount}`, from this device's OWN current
1680
+ // MANDALA_BASKET listing — `include: 'locking scripts'` is the one
1681
+ // difference from `listMandalaTokenOutpoints` above, since naming the
1682
+ // holding needs the script, not just the outpoint. Same admin-
1683
+ // originator, zero-prompt listing; same to-completion paging.
1684
+ const resolveMandalaOutputForRelinquish = (outpoint: string) =>
1685
+ resolveMandalaOutput(
1686
+ async (limit, offset) =>
1687
+ await wallet.listOutputs(
1688
+ {
1689
+ basket: MANDALA_BASKET,
1690
+ include: 'locking scripts',
1691
+ includeCustomInstructions: false,
1692
+ limit,
1693
+ offset
1694
+ } as never,
1695
+ adminOriginator
1696
+ ),
1697
+ outpoint,
1698
+ MANDALA_OUTPOINT_LIST_PAGE,
1699
+ MANDALA_OUTPOINT_LIST_MAX_PAGES
1700
+ )
1444
1701
 
1445
1702
  // Mandala's own P-module (schemeID 'mandala', basket MANDALA_BASKET =
1446
1703
  // 'p mandala') -- same routing mechanism as BTMS above
@@ -1451,7 +1708,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1451
1708
  adminOriginator,
1452
1709
  requestTokenAccess: mandalaPromptHandler,
1453
1710
  resolveAssetMetadata: resolveMandalaAssetMetadata,
1454
- listTokenOutpoints: listMandalaTokenOutpoints
1711
+ listTokenOutpoints: listMandalaTokenOutpoints,
1712
+ resolveMandalaOutput: resolveMandalaOutputForRelinquish
1455
1713
  })
1456
1714
 
1457
1715
  // Setup permissions with provided callbacks and BTMS module.
@@ -1518,10 +1776,17 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1518
1776
  // admitted (and therefore broadcast) releases inputs that are spent on
1519
1777
  // chain. It reads the settlement store LATE, off `mandalaRef`, because
1520
1778
  // the runtime is built below this line and replaced on every rebuild.
1779
+ //
1780
+ // XR-034: `mandalaEndpoints` (above, static for this build) is the
1781
+ // guard's ONLY "token settlement provably not in use" signal — never
1782
+ // `mandalaRef.current`, whose `undefined` also covers a runtime that
1783
+ // threw or is mid-rebuild, both of which can leave real settlement
1784
+ // rows unreadable rather than absent.
1521
1785
  newManagers.permissionsManager = guardVaultAccess(
1522
1786
  wrapAbortActionForSettlements(
1523
1787
  wrapCreateActionForTokenInputs(permissionsManager, listMandalaTokenOutpoints, adminOriginator),
1524
- () => mandalaRef.current?.store
1788
+ () => mandalaRef.current?.store,
1789
+ () => mandalaEndpoints !== undefined
1525
1790
  ),
1526
1791
  adminOriginator
1527
1792
  )
@@ -1819,7 +2084,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1819
2084
  // the drain so the parent goes out first.
1820
2085
  if (phoneStorage) {
1821
2086
  const sendWaiting = monitor._tasks.find(t => t.name === 'SendWaiting') as
1822
- | { processUnsent?: (reqApis: Array<{ txid: string; rawTx?: number[] }>, indent?: number) => Promise<string> }
2087
+ | {
2088
+ processUnsent?: (
2089
+ reqApis: Array<{ txid: string; rawTx?: number[] }>,
2090
+ indent?: number
2091
+ ) => Promise<string>
2092
+ }
1823
2093
  | undefined
1824
2094
  if (sendWaiting?.processUnsent) {
1825
2095
  const orig = sendWaiting.processUnsent.bind(sendWaiting)
@@ -1828,7 +2098,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1828
2098
  // row is the settlement drain's to broadcast, after `/submit`,
1829
2099
  // never the monitor's. Held here and dropped from this pass.
1830
2100
  const heldTokenTxids = await phoneStorage.holdTokenReqsForDrain(allReqApis as never)
1831
- const reqApis = heldTokenTxids.size > 0 ? allReqApis.filter(r => !heldTokenTxids.has(r.txid)) : allReqApis
2101
+ const reqApis =
2102
+ heldTokenTxids.size > 0 ? allReqApis.filter(r => !heldTokenTxids.has(r.txid)) : allReqApis
1832
2103
  if (heldTokenTxids.size > 0) TaskSendOffline.requestNow()
1833
2104
  let queuedTxids = new Set<string>()
1834
2105
  try {
@@ -1849,7 +2120,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1849
2120
  if (deferred > 0) TaskSendOffline.requestNow()
1850
2121
  if (ready.length === 0) {
1851
2122
  const notes: string[] = []
1852
- if (heldTokenTxids.size > 0) notes.push(`held ${heldTokenTxids.size} token req(s) for the settlement drain`)
2123
+ if (heldTokenTxids.size > 0)
2124
+ notes.push(`held ${heldTokenTxids.size} token req(s) for the settlement drain`)
1853
2125
  if (deferred > 0) notes.push(`deferred ${deferred} req(s) behind queued ancestors`)
1854
2126
  return notes.length > 0 ? `${notes.join('; ')}\n` : ''
1855
2127
  }
@@ -2166,6 +2438,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2166
2438
  // rebuildWallet until buildWallet consumes it. Explicit false still
2167
2439
  // allows the import screen to continue without restoring on retry.
2168
2440
  if (opts !== undefined) restoreIntentRef.current = opts.restoreFromBackup === true
2441
+ if (opts !== undefined) reviewImportedCoinsRef.current = opts.reviewImportedCoins === true
2169
2442
 
2170
2443
  // Provide the primary key and privileged key manager to authenticate the wallet
2171
2444
  await swm.providePrimaryKey(primaryKey)
@@ -2200,6 +2473,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2200
2473
  // Never leave the intent armed: the next build on this device would otherwise be
2201
2474
  // an auto-build on relaunch, which must not re-import over a live database.
2202
2475
  restoreIntentRef.current = false
2476
+ reviewImportedCoinsRef.current = false
2203
2477
  walletBuildingRef.current = false
2204
2478
  setWalletBuilding(false)
2205
2479
  console.error('[WalletContext] Error building mnemonic wallet:', error)
@@ -2237,6 +2511,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2237
2511
  // rebuildWallet until buildWallet consumes it. Explicit false still
2238
2512
  // allows the import screen to continue without restoring on retry.
2239
2513
  if (opts !== undefined) restoreIntentRef.current = opts.restoreFromBackup === true
2514
+ if (opts !== undefined) reviewImportedCoinsRef.current = opts.reviewImportedCoins === true
2240
2515
 
2241
2516
  await swm.providePrimaryKey(primaryKey)
2242
2517
 
@@ -2254,6 +2529,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2254
2529
  logWithTimestamp(F, 'Recovered key wallet build completed')
2255
2530
  } catch (error: any) {
2256
2531
  restoreIntentRef.current = false
2532
+ reviewImportedCoinsRef.current = false
2257
2533
  walletBuildingRef.current = false
2258
2534
  setWalletBuilding(false)
2259
2535
  console.error('[WalletContext] Error building wallet from recovered key:', error)
@@ -2265,73 +2541,78 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2265
2541
 
2266
2542
  // Tear down the current wallet and re-trigger auto-build.
2267
2543
  // Used after DB import and internally by switchNetwork.
2268
- const rebuildWallet = useCallback(async (opts?: { restoreFromBackup?: boolean }) => {
2269
- logWithTimestamp(F, 'Rebuilding wallet')
2270
- // Armed before teardown so the auto-build effect this triggers (via
2271
- // finalizeConfig below) replays the backup log the same way an explicit
2272
- // buildWalletFromMnemonic({ restoreFromBackup: true }) would.
2273
- restoreIntentRef.current = opts?.restoreFromBackup === true
2274
- // Any build already in flight belongs to the configuration being replaced.
2275
- const token = buildGenRef.current.bump()
2276
- // Invalidate Vault operations before the first teardown await. Otherwise a
2277
- // signer/listing already in flight can resume against the departing wallet.
2278
- vaultStore.clearScope()
2279
- vaultCeremony.cancel()
2544
+ const rebuildWallet = useCallback(
2545
+ async (opts?: { restoreFromBackup?: boolean; reviewImportedCoins?: boolean }) => {
2546
+ logWithTimestamp(F, 'Rebuilding wallet')
2547
+ // Armed before teardown so the auto-build effect this triggers (via
2548
+ // finalizeConfig below) replays the backup log the same way an explicit
2549
+ // buildWalletFromMnemonic({ restoreFromBackup: true }) would.
2550
+ restoreIntentRef.current = opts?.restoreFromBackup === true
2551
+ // Same arming pattern, for the raw-import reconciliation pass (XR-079).
2552
+ reviewImportedCoinsRef.current = opts?.reviewImportedCoins === true
2553
+ // Any build already in flight belongs to the configuration being replaced.
2554
+ const token = buildGenRef.current.bump()
2555
+ // Invalidate Vault operations before the first teardown await. Otherwise a
2556
+ // signer/listing already in flight can resume against the departing wallet.
2557
+ vaultStore.clearScope()
2558
+ vaultCeremony.cancel()
2280
2559
 
2281
- // Stop any running monitor and let its current pass drain before the
2282
- // storage teardown below closes the connection under it.
2283
- {
2284
- const monitor = monitorRef.current
2285
- if (monitor) {
2286
- monitorRef.current = null
2287
- await stopMonitorAndDrain(monitor)
2560
+ // Stop any running monitor and let its current pass drain before the
2561
+ // storage teardown below closes the connection under it.
2562
+ {
2563
+ const monitor = monitorRef.current
2564
+ if (monitor) {
2565
+ monitorRef.current = null
2566
+ await stopMonitorAndDrain(monitor)
2567
+ }
2288
2568
  }
2289
- }
2290
- // Same convention as monitorRef above: clear so a stale deferred header
2291
- // init or reconnect handler from the old build can't pair a leftover
2292
- // store/tracker across the rebuild.
2293
- offlineChaintracksRef.current = undefined
2294
- headerStoreRef.current = undefined
2295
-
2296
- // Close the current storage connection so the new build can open
2297
- // whichever DB file the registry selects.
2298
- if (storage?.db) {
2299
- try {
2300
- await storage.destroy()
2301
- } catch {}
2302
- }
2303
- // And drop the handle with it. Leaving a destroyed storage in state kept
2304
- // the screens reading the OLD chain's database until the new build
2305
- // replaced it — which is how a testnet wallet displayed mainnet money.
2306
- setStorage(null)
2307
- // The runtime holds this build's settlement store, which is a handle on
2308
- // the database just destroyed. Dropping it here is what stops a monitor
2309
- // task or a screen draining the departed wallet's tables.
2310
- mandalaRef.current = undefined
2311
- setMandala(undefined)
2312
- forgetSessionPsks()
2313
-
2314
- // Tear down current wallet state (but keep mnemonic / config)
2315
- vaultStore.clearScope()
2316
- updateManagers({})
2317
- walletBuiltRef.current = false
2318
- setWalletBuilt(false)
2319
- walletBuildingRef.current = false
2320
- setWalletBuilding(false)
2321
-
2322
- // Re-finalize with current config — triggers auto-build effect
2323
- const config = { wabUrl: 'noWAB', method: 'mnemonic', network: selectedNetwork, storageUrl: 'local' }
2324
- pendingAutoBuildRef.current = true
2325
- finalizeConfig(config)
2326
- logWithTimestamp(F, 'Wallet rebuild triggered')
2327
- // finalizeConfig above only requests the rebuild; without this,
2328
- // rebuildWallet's promise resolved before the auto-build effect had even
2329
- // run, so `await rebuildWallet(...)` callers (e.g. the import screens
2330
- // replacing an auto-created wallet) saw pre-rebuild managers and a
2331
- // pre-rebuild walletBuilt — silently skipping anything gated on the new
2332
- // wallet actually existing, such as recording a backup attestation.
2333
- await waitForRebuild(token)
2334
- }, [selectedNetwork, storage, finalizeConfig, waitForRebuild])
2569
+ // Same convention as monitorRef above: clear so a stale deferred header
2570
+ // init or reconnect handler from the old build can't pair a leftover
2571
+ // store/tracker across the rebuild.
2572
+ offlineChaintracksRef.current = undefined
2573
+ headerStoreRef.current = undefined
2574
+
2575
+ // Close the current storage connection so the new build can open
2576
+ // whichever DB file the registry selects.
2577
+ if (storage?.db) {
2578
+ try {
2579
+ await storage.destroy()
2580
+ } catch {}
2581
+ }
2582
+ // And drop the handle with it. Leaving a destroyed storage in state kept
2583
+ // the screens reading the OLD chain's database until the new build
2584
+ // replaced it — which is how a testnet wallet displayed mainnet money.
2585
+ setStorage(null)
2586
+ // The runtime holds this build's settlement store, which is a handle on
2587
+ // the database just destroyed. Dropping it here is what stops a monitor
2588
+ // task or a screen draining the departed wallet's tables.
2589
+ mandalaRef.current = undefined
2590
+ setMandala(undefined)
2591
+ forgetSessionPsks()
2592
+
2593
+ // Tear down current wallet state (but keep mnemonic / config)
2594
+ vaultStore.clearScope()
2595
+ updateManagers({})
2596
+ walletBuiltRef.current = false
2597
+ setWalletBuilt(false)
2598
+ walletBuildingRef.current = false
2599
+ setWalletBuilding(false)
2600
+
2601
+ // Re-finalize with current config — triggers auto-build effect
2602
+ const config = { wabUrl: 'noWAB', method: 'mnemonic', network: selectedNetwork, storageUrl: 'local' }
2603
+ pendingAutoBuildRef.current = true
2604
+ finalizeConfig(config)
2605
+ logWithTimestamp(F, 'Wallet rebuild triggered')
2606
+ // finalizeConfig above only requests the rebuild; without this,
2607
+ // rebuildWallet's promise resolved before the auto-build effect had even
2608
+ // run, so `await rebuildWallet(...)` callers (e.g. the import screens
2609
+ // replacing an auto-created wallet) saw pre-rebuild managers and a
2610
+ // pre-rebuild walletBuilt — silently skipping anything gated on the new
2611
+ // wallet actually existing, such as recording a backup attestation.
2612
+ await waitForRebuild(token)
2613
+ },
2614
+ [selectedNetwork, storage, finalizeConfig, waitForRebuild]
2615
+ )
2335
2616
 
2336
2617
  // Switch network: tear down wallet, update config, and rebuild on new chain
2337
2618
  const switchNetwork = useCallback(
@@ -2487,8 +2768,47 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2487
2768
  void replayPendingAborts({
2488
2769
  wallet: managers.permissionsManager as {
2489
2770
  abortAction: (args: { reference: string }, originator?: string) => Promise<{ aborted?: boolean } | void>
2771
+ verifyHmac: NonNullable<typeof managers.permissionsManager>['verifyHmac']
2490
2772
  },
2491
2773
  storage
2774
+ }).then(result => {
2775
+ // XR-102: an entry replayPendingAborts dropped as untrusted (missing or
2776
+ // mismatching authority tag) never called abortAction at all, so
2777
+ // whatever it named — if it was even real — is unaffected; the only
2778
+ // thing to tell the user is that a stored release record was ignored,
2779
+ // in case a payment still looks stuck (Activity's manual per-row
2780
+ // Cancel remains available either way, and does not depend on this
2781
+ // queue).
2782
+ if (result.droppedUntrusted > 0) {
2783
+ setLocalPayNotification({
2784
+ message: `${t('local_pay_pending_abort_dropped_title')}. ${t('local_pay_pending_abort_dropped_body')}`,
2785
+ type: 'error'
2786
+ })
2787
+ }
2788
+ })
2789
+ // P1-3: a decline is the payee's own unverifiable claim that nothing was
2790
+ // queued (see build.ts's `watchDeclinedAbort`). Checked at the same
2791
+ // cadence as the pending-abort replay above — wallet build and every
2792
+ // reconnect — so a declined txid that reaches the chain anyway is
2793
+ // surfaced as a background notice rather than silently missed. Never
2794
+ // blocks anything: the inputs were already freed when the decline
2795
+ // was recorded.
2796
+ void verifyDeclinedAborts({
2797
+ storage,
2798
+ getStatusForTxids: async txids => {
2799
+ const services = storage.getServices() as {
2800
+ getStatusForTxids?: (txids: string[]) => Promise<{ results?: { txid: string; status: string }[] }>
2801
+ }
2802
+ if (typeof services.getStatusForTxids !== 'function') return {}
2803
+ return services.getStatusForTxids(txids)
2804
+ }
2805
+ }).then(surfaced => {
2806
+ if (surfaced.length > 0) {
2807
+ setLocalPayNotification({
2808
+ message: `${t('local_pay_decline_broadcast_title')}. ${t('local_pay_decline_broadcast_body')}`,
2809
+ type: 'error'
2810
+ })
2811
+ }
2492
2812
  })
2493
2813
 
2494
2814
  // Also run when connectivity is restored
@@ -2594,21 +2914,29 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2594
2914
  // both refs fresh on every reconnect, independent of that init's own
2595
2915
  // guarding, so it re-validates the pairing itself before syncing rather than
2596
2916
  // trusting it was never broken.
2917
+ //
2918
+ // Reconnects alone left the window hours behind on a phone that stayed on
2919
+ // one network, which an offline payee then pays for by refusing any coin
2920
+ // mined since. So the same pass also runs on returning to the foreground and
2921
+ // every HEADER_SYNC_INTERVAL_MS while online (see headerSyncTriggers.ts).
2597
2922
  useEffect(() => {
2598
2923
  if (!walletBuilt) return
2599
- return subscribeOnline(online => {
2600
- if (!online) return
2601
- const ct = offlineChaintracksRef.current
2602
- const store = headerStoreRef.current
2603
- if (!ct || !store) return
2604
- if (store.chain !== toWalletChain(selectedNetwork)) return
2605
- void (async () => {
2606
- try {
2607
- await runHeaderSync(store, ct)
2608
- } catch {
2609
- // Best-effort. The next reconnect retries.
2610
- }
2611
- })()
2924
+ return startHeaderSyncTriggers({
2925
+ sync: async () => {
2926
+ const ct = offlineChaintracksRef.current
2927
+ const store = headerStoreRef.current
2928
+ if (!ct || !store) return
2929
+ if (store.chain !== toWalletChain(selectedNetwork)) return
2930
+ await runHeaderSync(store, ct)
2931
+ },
2932
+ isOnline: getOnline,
2933
+ subscribeOnline,
2934
+ subscribeForeground: cb => {
2935
+ const sub = AppState.addEventListener('change', next => {
2936
+ if (next === 'active') cb()
2937
+ })
2938
+ return () => sub.remove()
2939
+ }
2612
2940
  })
2613
2941
  }, [walletBuilt, selectedNetwork, runHeaderSync])
2614
2942
 
@@ -2732,13 +3060,23 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2732
3060
  }
2733
3061
  }, [])
2734
3062
 
2735
- const logout = useCallback(() => {
3063
+ const logout = useCallback((): Promise<boolean> => {
2736
3064
  logWithTimestamp(F, 'Logout')
2737
3065
  // Synchronous on purpose: invalidate transfer tokens and release any PIN /
2738
3066
  // hardware session before monitor or storage teardown yields.
2739
3067
  vaultStore.clearScope()
2740
3068
  vaultCeremony.cancel()
2741
- ;(async () => {
3069
+ // XR-018: a live paired RPC socket otherwise outlives logout/wallet
3070
+ // deletion — the peer would keep dispatching allowlisted BRC-100 methods
3071
+ // against a wallet the user believes they've logged out of.
3072
+ disconnectActivePairedSession()
3073
+ // The IIFE's promise IS returned (unlike the old fire-and-forget version):
3074
+ // XR-107 needs the caller to await the verified outcome of the secret
3075
+ // erasure below, not just the synchronous kickoff. This does not
3076
+ // reintroduce the yield-before-first-synchronous-step problem the old
3077
+ // comment warned about — everything above this point already ran
3078
+ // synchronously before any promise existed to await.
3079
+ return (async () => {
2742
3080
  // Tear the wallet down the same way rebuildWallet does. Logout used to
2743
3081
  // skip this, which orphaned a running monitor AND left the SQLite
2744
3082
  // connection open: a re-import of the same phrase then opened a second
@@ -2754,10 +3092,26 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2754
3092
  }
2755
3093
  offlineChaintracksRef.current = undefined
2756
3094
  headerStoreRef.current = undefined
2757
- if (storage?.db) {
3095
+ backupIdentityRef.current = null
3096
+ if (storage) {
3097
+ const dbName = storage.dbName
3098
+ if (storage.db) {
3099
+ try {
3100
+ await storage.destroy()
3101
+ } catch {}
3102
+ }
3103
+ // XQ-008: destroy() only closes the connection — it never deleted the
3104
+ // underlying .db file(s) or the walletDbRegistry entry that points at
3105
+ // them, so a "deleted" wallet's complete plaintext history stayed on
3106
+ // disk indefinitely and silently reattached with everything intact if
3107
+ // the same mnemonic was ever built again on this device. dbName is a
3108
+ // plain field that survives destroy(), so it is still readable after
3109
+ // the connection is closed.
2758
3110
  try {
2759
- await storage.destroy()
2760
- } catch {}
3111
+ await purgeRegisteredDbFiles(dbName, SQLite.deleteDatabaseAsync)
3112
+ } catch (err) {
3113
+ console.warn('[logout] failed to purge wallet db file(s)/registry', err)
3114
+ }
2761
3115
  }
2762
3116
  setStorage(null)
2763
3117
  mandalaRef.current = undefined
@@ -2780,15 +3134,46 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2780
3134
  try {
2781
3135
  const keys = await AsyncStorage.getAllKeys()
2782
3136
  const stale = keys.filter(k => k.startsWith('cached_wallet_balance_'))
3137
+ // XR-058: the legacy (pre-network-scoping) `Balance` component wrote
3138
+ // an exact, unscoped `cached_wallet_balance` key with no trailing
3139
+ // underscore, which the prefix filter above never matches. Nothing
3140
+ // reads that key any more, but an install that still carries one
3141
+ // from before the fix should have it swept here too.
3142
+ if (await AsyncStorage.getItem('cached_wallet_balance')) stale.push('cached_wallet_balance')
2783
3143
  if (stale.length > 0) await AsyncStorage.multiRemove(stale)
2784
3144
  } catch (err) {
2785
3145
  console.warn('[logout] failed to clear cached balance', err)
2786
3146
  }
2787
3147
 
3148
+ // A departed wallet's push cursor must not linger to be misread as THIS device
3149
+ // already having backed up the next wallet built here — deviceId never changes
3150
+ // across a logout/re-import on the same install (see deviceId.ts and XR-009), so an
3151
+ // unscoped Wallet Check read would otherwise inherit it. Sweeps every identity's
3152
+ // cursor, not just the one just logged out of, same as the balance-cache sweep above.
3153
+ try {
3154
+ const keys = await AsyncStorage.getAllKeys()
3155
+ const stale = keys.filter(k => k.startsWith('backupCursor-'))
3156
+ if (stale.length > 0) await AsyncStorage.multiRemove(stale)
3157
+ } catch (err) {
3158
+ console.warn('[logout] failed to clear backup cursor', err)
3159
+ }
3160
+
2788
3161
  // Awaited, and it removes the KEK along with the ciphertexts: leaving the
2789
3162
  // key behind would make the next cold start prompt for a wallet that no
2790
3163
  // longer exists. Works while locked, since deleting needs no key.
2791
- await deleteAllWalletKeys()
3164
+ //
3165
+ // XR-107: its result is real, read-back-verified evidence of whether a
3166
+ // legacy plaintext mnemonic/recoveredKey/password actually got erased —
3167
+ // not a guess. A `false` here must fail closed: skip the attestation
3168
+ // clear and the navigation below (both of which tell the rest of the
3169
+ // app "this wallet is gone") and report the failure to the caller
3170
+ // instead, so the UI can show an error and let the user retry rather
3171
+ // than silently behaving as though "Delete Wallet" fully succeeded.
3172
+ const erased = await deleteAllWalletKeys()
3173
+ if (!erased) {
3174
+ console.warn('[logout] legacy secret erasure could not be verified; not reporting Delete Wallet as complete')
3175
+ return false
3176
+ }
2792
3177
 
2793
3178
  // The attestation is per wallet. "Delete Wallet" routes here, so leaving
2794
3179
  // it behind would let the NEXT wallet on this device inherit a backup it
@@ -2804,6 +3189,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2804
3189
  const { router } = loadExpoRouter()
2805
3190
  router.dismissAll()
2806
3191
  router.replace('/')
3192
+ return true
2807
3193
  })()
2808
3194
  }, [deleteAllWalletKeys, storage])
2809
3195
 
@@ -2835,7 +3221,14 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2835
3221
  const res = await fetch(`${wocBase}/v1/bsv/${chain}/tx/${txid}/proof/bump`)
2836
3222
 
2837
3223
  if (res.ok) {
2838
- const bumpHex = (await res.text()).trim()
3224
+ // XR-059 remainder: a compromised/misbehaving configured indexer must
3225
+ // not be able to force an unbounded hex-decode here just by sending
3226
+ // back an oversized (or malformed) proof body — same guard as
3227
+ // address.ts's parseWocBeefBody / beefRepair.ts's refetchAtomicBeef.
3228
+ // An oversized/invalid proof is indistinguishable from "no usable
3229
+ // proof yet", so this fails closed to 'pending', exactly like a 404.
3230
+ const bumpHex = boundedHexResponse(await res.text(), MAX_HEX_RESPONSE_CHARS)
3231
+ if (bumpHex === undefined) return 'pending'
2839
3232
  const merklePath = MerklePath.fromHex(bumpHex)
2840
3233
  const merkleRoot = merklePath.computeRoot(txid)
2841
3234
  const ct = offlineChaintracksRef.current
@@ -2867,7 +3260,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2867
3260
  fetchRawTx: async () => {
2868
3261
  const r = await fetch(`${wocBase}/v1/bsv/${chain}/tx/${txid}/hex`)
2869
3262
  if (!r.ok) throw new Error(`raw tx fetch failed: ${r.status}`)
2870
- return Utils.toArray((await r.text()).trim(), 'hex')
3263
+ // XR-059 remainder: same unbounded-hex-decode gap as the BUMP
3264
+ // fetch above, on the raw-tx body this time. Throwing here (like
3265
+ // the !r.ok case just above) is refreshProof's existing
3266
+ // fail-closed shape for a raw-tx read it cannot trust.
3267
+ const hex = boundedHexResponse(await r.text(), MAX_HEX_RESPONSE_CHARS)
3268
+ if (hex === undefined) throw new Error('raw tx fetch: response too large or not valid hex')
3269
+ return Utils.toArray(hex, 'hex')
2871
3270
  }
2872
3271
  })
2873
3272
  setTxStatusVersion(v => v + 1)
@@ -2881,6 +3280,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2881
3280
  try {
2882
3281
  const head = await fetch(`${wocBase}/v1/bsv/${chain}/tx/hash/${txid}`)
2883
3282
  onChain = head.ok
3283
+ // XR-030: any other non-OK (429/500/401/403/...) is a service
3284
+ // problem, not proof of absence — only a 404 is authoritative.
3285
+ if (!onChain && !isChainAbsenceConfirmed(head.status)) return 'pending'
2884
3286
  } catch {
2885
3287
  // Network unreachable — we cannot prove absence, so never fail the tx.
2886
3288
  return 'pending'
@@ -2897,9 +3299,14 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2897
3299
  if (!tx || tx.status === 'failed' || tx.status === 'completed') return 'pending'
2898
3300
 
2899
3301
  // A queued/posting offline payment is expected not to be on chain yet —
2900
- // failing it would release inputs the payee still holds.
3302
+ // failing it would release inputs the payee still holds. Same for an
3303
+ // 'import_hold' row (XR-085): a raw database import quarantines a
3304
+ // copied-in queued/posting row under that status precisely because it
3305
+ // may already be broadcast/handed off, so this lookup has to see it
3306
+ // too or shouldFailUnprovenTx below never learns the row is held and
3307
+ // can fail it on a stale, in-flight tx status alone.
2901
3308
  const db = storage.sqliteDb
2902
- const rows = db ? await findOfflineActions(db, { status: ['queued', 'posting'] }) : []
3309
+ const rows = db ? await findOfflineActions(db, { status: ['queued', 'posting', 'import_hold'] }) : []
2903
3310
  const offlineStatus = rows.find(r => r.txid === txid)?.status
2904
3311
  if (
2905
3312
  shouldFailUnprovenTx({
@@ -2991,20 +3398,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2991
3398
  const db = (storage as any)?.sqliteDb
2992
3399
  if (!db?.runAsync) return 'DB not available'
2993
3400
  try {
2994
- const rows = (await db.getAllAsync(
2995
- `SELECT o.outputId AS outputId, o.satoshis AS satoshis, t.txid AS txid
2996
- FROM outputs o JOIN transactions t ON t.transactionId = o.spentBy
2997
- WHERE t.status = 'failed'`
2998
- )) as { outputId: number; satoshis: number; txid: string }[]
2999
- if (!rows || rows.length === 0) return 'No stuck reservations found.'
3000
- await db.runAsync(
3001
- `UPDATE outputs SET spentBy = NULL, spendable = 1
3002
- WHERE spentBy IN (SELECT transactionId FROM transactions WHERE status = 'failed')`
3003
- )
3004
- const detail = rows
3005
- .map(r => ` • ${r.satoshis} sat (output ${r.outputId}) ← failed ${String(r.txid).slice(0, 12)}…`)
3006
- .join('\n')
3007
- return `✓ Released ${rows.length} stuck reservation(s):\n${detail}`
3401
+ return await releaseStuckReservationsOnDb(db)
3008
3402
  } catch (e: any) {
3009
3403
  return `⚠ Release failed: ${e.message}`
3010
3404
  }
@@ -3113,21 +3507,101 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3113
3507
  continue
3114
3508
  }
3115
3509
 
3116
- spentCount++
3117
- lines.push(` SPENT: ${o.txid}:${o.vout} (${o.satoshis} sat) → by ${spendingTxid}`)
3118
- await storage.updateOutput(o.outputId, { spendable: false as any })
3510
+ // Second-source corroboration (misc-p2-01): a single WoC 200-with-txid
3511
+ // response is not enough to permanently mark a UTXO unspendable — WoC
3512
+ // can be wrong, stale, or answering for the wrong network, and this
3513
+ // path never writes spentBy, so nothing can ever restore a wrong call
3514
+ // later. Require the toolbox's own configured getUtxoStatus providers
3515
+ // to ALSO report the output as no longer a UTXO before committing.
3516
+ let utxoStatus: { status: 'success' | 'error'; isUtxo?: boolean } = { status: 'error' }
3517
+ try {
3518
+ const scriptedRows = await storage.findOutputs({ partial: { outputId: o.outputId } })
3519
+ const scripted = scriptedRows[0]
3520
+ const utxoServices = storage.getServices() as {
3521
+ hashOutputScript?: (script: string) => string
3522
+ getUtxoStatus?: (
3523
+ output: string,
3524
+ outputFormat?: string,
3525
+ outpoint?: string
3526
+ ) => Promise<{ status: 'success' | 'error'; isUtxo?: boolean }>
3527
+ }
3528
+ if (scripted?.lockingScript && utxoServices.hashOutputScript && utxoServices.getUtxoStatus) {
3529
+ const scriptHash = utxoServices.hashOutputScript(Utils.toHex(scripted.lockingScript))
3530
+ const result = await utxoServices.getUtxoStatus(scriptHash, undefined, `${o.txid}.${o.vout}`)
3531
+ utxoStatus = { status: result.status, isUtxo: result.isUtxo }
3532
+ }
3533
+ } catch {
3534
+ utxoStatus = { status: 'error' }
3535
+ }
3536
+
3537
+ const markUnspendable = shouldMarkUnspendable({
3538
+ wocProbe: probe,
3539
+ wocSpendingTxid: spendingTxid,
3540
+ utxoStatus
3541
+ })
3542
+ if (!markUnspendable) {
3543
+ console.warn(
3544
+ `[walletCheck] WoC claims ${o.txid}:${o.vout} spent by ${spendingTxid || '(no txid)'} but the second source did not corroborate — leaving spendable`
3545
+ )
3546
+ lines.push(
3547
+ ` SPENT (unconfirmed by 2nd source): ${o.txid}:${o.vout} (${o.satoshis} sat) — claimed spender ${spendingTxid || '(no txid)'}, left spendable`
3548
+ )
3549
+ continue
3550
+ }
3119
3551
 
3120
- if (!spendingTxid) continue
3552
+ // XR-031: markUnspendable only means two independent chain-service
3553
+ // oracles AGREE the output is spent — neither of them is the spending
3554
+ // transaction. Fetch and parse the alleged spender's own BEEF and
3555
+ // require it to actually consume this exact outpoint BEFORE
3556
+ // committing spendable:false; a claim that fails to fetch, fails to
3557
+ // parse, hashes to a different tx, or simply doesn't reference this
3558
+ // outpoint is left spendable rather than mutated.
3559
+ if (!spendingTxid) continue // shouldMarkUnspendable already requires this; narrows the type below.
3560
+ let spenderTx: Transaction | undefined
3121
3561
  try {
3122
3562
  const beefResp = await throttledFetch(`${wocBase}/tx/${spendingTxid}/beef`)
3123
3563
  if (!beefResp.ok) {
3124
- lines.push(` ↳ BEEF fetch failed (HTTP ${beefResp.status}), skipping change recovery`)
3564
+ lines.push(
3565
+ ` SPENT (unverified, spender BEEF fetch HTTP ${beefResp.status}): ${o.txid}:${o.vout} — left spendable`
3566
+ )
3125
3567
  continue
3126
3568
  }
3127
3569
  const beefHex = await beefResp.text()
3128
3570
  const beefBytes = Utils.toArray(beefHex, 'hex')
3129
3571
  const tx = Transaction.fromBEEF(beefBytes)
3130
- const atomicBeef = tx.toAtomicBEEF()
3572
+ const confirmed = spenderConsumesOutpoint({
3573
+ parsedTxid: tx.id('hex'),
3574
+ expectedTxid: spendingTxid,
3575
+ inputs: tx.inputs,
3576
+ outpoint: { txid: o.txid, vout: o.vout }
3577
+ })
3578
+ if (!confirmed) {
3579
+ lines.push(
3580
+ ` SPENT (unverified, spender does not reference this outpoint): ${o.txid}:${o.vout} — left spendable`
3581
+ )
3582
+ continue
3583
+ }
3584
+ spenderTx = tx
3585
+ } catch (e: any) {
3586
+ lines.push(
3587
+ ` SPENT (unverified, could not parse spender BEEF: ${e.message}): ${o.txid}:${o.vout} — left spendable`
3588
+ )
3589
+ continue
3590
+ }
3591
+
3592
+ spentCount++
3593
+ lines.push(` SPENT: ${o.txid}:${o.vout} (${o.satoshis} sat) → by ${spendingTxid}`)
3594
+ // Paper trail for a repair pass: `spendingDescription` is a free-text
3595
+ // column nothing else in this app reads or writes (unlike
3596
+ // `customInstructions`, which carries live BRC-42 derivation data
3597
+ // other flows depend on), so it is safe to repurpose as a note here.
3598
+ await storage.updateOutput(o.outputId, {
3599
+ spendable: false as any,
3600
+ spendingDescription: JSON.stringify({ claimedSpender: spendingTxid, checkedAt: new Date().toISOString() })
3601
+ } as any)
3602
+
3603
+ try {
3604
+ const atomicBeef = spenderTx.toAtomicBEEF()
3131
3605
 
3132
3606
  const changeOutputs = await storage.findOutputs({
3133
3607
  partial: { change: true as any, spendable: false as any },
@@ -3222,6 +3696,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3222
3696
  buildWalletFromRecoveredKey,
3223
3697
  backupRestore,
3224
3698
  getBackupRestore,
3699
+ getBackupPseudonym,
3700
+ getWalletBuilt,
3225
3701
  switchNetwork,
3226
3702
  rebuildWallet,
3227
3703
  storage,
@@ -3269,6 +3745,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3269
3745
  buildWalletFromRecoveredKey,
3270
3746
  backupRestore,
3271
3747
  getBackupRestore,
3748
+ getBackupPseudonym,
3749
+ getWalletBuilt,
3272
3750
  switchNetwork,
3273
3751
  rebuildWallet,
3274
3752
  storage,