@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
@@ -9,17 +9,15 @@ import {
9
9
  WalletSigner,
10
10
  PermissionRequest,
11
11
  SimpleWalletManager,
12
- Monitor
12
+ Monitor,
13
+ DEFAULT_SETTINGS as LIB_DEFAULT_SETTINGS,
14
+ WalletSettings,
15
+ WalletSettingsManager
13
16
  } from '@bsv/wallet-toolbox-mobile'
14
17
  import { KeyDeriver, PrivateKey, MerklePath, Transaction, Utils } from '@bsv/sdk'
15
18
  import { VAULT_RETENTION_MS, ceremony as vaultCeremony } from '../services/vault/ceremonyHost'
16
19
  import { getVaultDriver } from '../services/vault/driver'
17
20
  import { backupAttestation } from '../services/vault/backupAttestation'
18
- import {
19
- DEFAULT_SETTINGS as LIB_DEFAULT_SETTINGS,
20
- WalletSettings,
21
- WalletSettingsManager
22
- } from '@bsv/wallet-toolbox-mobile/out/src/WalletSettingsManager'
23
21
 
24
22
  /** App-level defaults: library defaults + additional certifiers */
25
23
  /**
@@ -126,6 +124,15 @@ async function resolveMandalaAssetMetadata(assetId: string): Promise<MandalaAsse
126
124
  }
127
125
  }
128
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
+
129
136
  const DEFAULT_SETTINGS: WalletSettings = {
130
137
  ...LIB_DEFAULT_SETTINGS,
131
138
  trustSettings: {
@@ -157,23 +164,44 @@ const DEFAULT_SETTINGS: WalletSettings = {
157
164
  import type { AppChain } from '../config'
158
165
  import { DEFAULT_STORAGE_URL, DEFAULT_CHAIN, ADMIN_ORIGINATOR, toWalletChain } from '../config'
159
166
  import { getBackupUrl, getMandalaEndpoints } from '../toolboxConfig'
160
- 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'
161
176
  import AsyncStorage from '@react-native-async-storage/async-storage'
162
177
  import { UserContext } from './UserContext'
163
178
  import { useLocalStorage } from './LocalStorageProvider'
164
179
  import { usePermissionQueue } from '../hooks/usePermissionQueue'
165
180
  import { configureMandala, resolveAssetMetadata } from '@bsv/mandala'
166
181
  import { MessageBoxClient } from '@bsv/message-box-client'
167
- 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'
168
189
  import { wrapAbortActionForSettlements } from '../mandala/abortGuard'
169
190
  import { migrateMandalaBasketName } from '../mandala/basketMigration'
170
- import { bindOriginator, createMandalaKvStorage, createMandalaRuntime, type MandalaMessageBox } from '../mandala/createRuntime'
191
+ import {
192
+ bindOriginator,
193
+ createMandalaKvStorage,
194
+ createMandalaRuntime,
195
+ type MandalaMessageBox
196
+ } from '../mandala/createRuntime'
171
197
  import type { MandalaRuntime } from '../mandala/runtime'
172
198
  import { MANDALA_BASKET } from '../mandala/types'
173
199
  import { mandalaSettlementDeps, type CancelParkedSettlementDeps } from '../offline/cancelParked'
174
200
  import { drainMandalaInbox } from '../pay/rails/handle'
175
201
  import { forgetSessionPsks, sealedFramePayloadDecoder } from '../offline/tokenFrames'
202
+ import { disconnectActivePairedSession } from './WalletConnectionContext'
176
203
  import { createServices, chaintracksUrlFor } from '../services/walletServiceConfig'
204
+ import { getArcApiToken } from '../services/arcTokenStorage'
177
205
  import {
178
206
  boundReviewProvenTxs,
179
207
  configureNewHeaderPolling,
@@ -196,20 +224,29 @@ import { StorageProvider, ChaintracksServiceClient } from '@bsv/wallet-toolbox-m
196
224
  import { StorageExpoSQLite } from '../storage'
197
225
  import { makeBuildGeneration } from './buildGeneration'
198
226
  import * as SQLite from 'expo-sqlite'
199
- import { getRegisteredDbs, registerDb, selectLatestDb } from '../walletDbRegistry'
227
+ import {
228
+ getRegisteredDbs,
229
+ purgeRegisteredDbFiles,
230
+ registerDb,
231
+ selectLatestDb,
232
+ unregisterDb
233
+ } from '../walletDbRegistry'
200
234
  import { AppState, AppStateStatus, InteractionManager } from 'react-native'
201
235
  import { getOnline, subscribeOnline } from '../net/online'
202
236
  import { canInternalizePending, processPending } from '../localpay/pending'
203
- import { replayPendingAborts } from '../localpay/pendingAborts'
237
+ import { replayPendingAborts, verifyDeclinedAborts } from '../localpay/pendingAborts'
204
238
  import { TaskSendOffline } from '../monitor/TaskSendOffline'
239
+ import { MONITOR_STALL_MS, MonitorSupervisor } from '../monitor/MonitorSupervisor'
205
240
  import { TaskCreditInbox } from '../monitor/TaskCreditInbox'
206
241
  import { drainUnsentEntries, TaskDrainOutbox } from '../monitor/TaskDrainOutbox'
207
242
  import { TaskBackupPush } from '../monitor/TaskBackupPush'
208
243
  import { pushOnce } from '../backup/push'
209
244
  import { restoreOnImport } from '../backup/restoreOnImport'
245
+ import { backupPseudonym } from '../backup/derive'
246
+ import type { BackupChain } from '../backup/constants'
210
247
  import { processOfflineActions } from '../storage/methods/processOfflineActions'
211
248
  import { findOfflineActions } from '../storage/methods/offlineActions'
212
- import { shouldFailUnprovenTx } from '../pay/refreshProofGuard'
249
+ import { boundedHexResponse, isChainAbsenceConfirmed, shouldFailUnprovenTx } from '../pay/refreshProofGuard'
213
250
  import { inputTxidsFromRawTx, shouldDeferSendWaiting } from '../storage/skipQueuedAncestors'
214
251
  import { provenTxFromBump } from '../pay/provenTxFromBump'
215
252
  import { recordProof } from '../pay/recordProof'
@@ -220,6 +257,9 @@ import { sounds } from '../hooks/useConfirmationSound'
220
257
  import i18n from '../i18n/translations'
221
258
  import { makeBeefRepair } from '../pay/beefRepair'
222
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'
223
263
  import {
224
264
  acceptWithRetry,
225
265
  DEFAULT_MESSAGE_BOX_URL,
@@ -230,7 +270,7 @@ import {
230
270
  retryDelivery
231
271
  } from '../pay/rails/handle'
232
272
  import { getOutboxEntries, pruneExpiredSent, unsentEntries } from '../peerpay/outbox'
233
- import { wocConfigFor } from '../pay/rails/address'
273
+ import { MAX_HEX_RESPONSE_CHARS, wocConfigFor } from '../pay/rails/address'
234
274
  import { PeerPayClient } from '@bsv/message-box-client'
235
275
  import { SWEEP_INTERVAL_MS, runSweep, shouldSweepNow, sweptTotal } from '../pay/sweeper'
236
276
  import { formatAmount } from '../amountFormatHelpers'
@@ -243,9 +283,42 @@ import { prewarmOwnRoots } from '../headers/prewarm'
243
283
  import { syncHeaders } from '../headers/syncHeaders'
244
284
  import type { HeaderSource } from '../headers/syncHeaders'
245
285
 
246
- // Global, origin-agnostic rate limit for auto-approved spending.
247
- // In-memory only — resets on app restart (intentional: more secure).
248
- let lastAutoApproveTime = 0
286
+ // Auto-approve accounting (misc-p2-04). Previously a single global cooldown
287
+ // timer let multiple paired origins accidentally throttle each other while
288
+ // placing no ceiling on a single origin's cumulative total. autoApprovePolicy
289
+ // keys the cooldown PER ORIGINATOR and adds a global rolling-24h cumulative
290
+ // cap across every originator — see services/autoApprovePolicy.ts. Module
291
+ // scope, same lifetime as the value it replaces; `threshold` reads a snapshot
292
+ // updated on every spendingAuthorizationCallback call (see below) since the
293
+ // persisted threshold is itself read fresh per-request.
294
+ let autoApproveThresholdSnapshot = 0
295
+ const autoApprovePolicy = createAutoApprovePolicy({
296
+ now: () => Date.now(),
297
+ threshold: () => autoApproveThresholdSnapshot,
298
+ cooldownMs: AUTO_APPROVE_COOLDOWN_MS,
299
+ dailyCapSats: AUTO_APPROVE_DAILY_CAP_SATS
300
+ })
301
+
302
+ // Best-effort persistence of the rolling ledger so an app restart does not
303
+ // reset the daily cap. Loaded once per process; a read/write failure never
304
+ // blocks a spend decision — the in-memory ledger stays authoritative either way.
305
+ let autoApproveLedgerLoadedOnce = false
306
+ async function loadAutoApproveLedgerOnce(): Promise<void> {
307
+ if (autoApproveLedgerLoadedOnce) return
308
+ autoApproveLedgerLoadedOnce = true
309
+ try {
310
+ const stored = await AsyncStorage.getItem(AUTO_APPROVE_LEDGER_STORAGE_KEY)
311
+ if (stored) {
312
+ const parsed = JSON.parse(stored)
313
+ if (Array.isArray(parsed)) autoApprovePolicy.loadLedger(parsed)
314
+ }
315
+ } catch {
316
+ // No persisted ledger to restore — start with an empty one, same as today.
317
+ }
318
+ }
319
+ function persistAutoApproveLedger(): void {
320
+ AsyncStorage.setItem(AUTO_APPROVE_LEDGER_STORAGE_KEY, JSON.stringify(autoApprovePolicy.getLedger())).catch(() => {})
321
+ }
249
322
 
250
323
  // -----
251
324
  // Context Types
@@ -273,6 +346,12 @@ export interface BackupRestoreState {
273
346
  /** Chunks in the generation being replayed; 0 until the log index is read. */
274
347
  total: number
275
348
  error?: string
349
+ /**
350
+ * Set alongside a `'restored'` phase, from `restoreOnImport`'s own `verified` — true
351
+ * unless the replayed generation's newest entry could not be proven complete (see
352
+ * RemoteSyncReader.verifiedComplete). Absent for every other phase.
353
+ */
354
+ verified?: boolean
276
355
  }
277
356
 
278
357
  export interface WalletBuildOptions {
@@ -283,6 +362,16 @@ export interface WalletBuildOptions {
283
362
  * to restore, and an auto-build on relaunch must not re-import over a live database.
284
363
  */
285
364
  restoreFromBackup?: boolean
365
+ /**
366
+ * Run the same spendability-reconciliation pass a backup restore runs, once local
367
+ * storage is attached — WITHOUT pulling or replaying the encrypted remote backup.
368
+ *
369
+ * Set ONLY by the raw-database-import flow (ui/importDatabases.ts): that flow already
370
+ * hands over a complete local database, so it must not also overlay a remote backup on
371
+ * top of it, but it still skipped the reconciliation review until this option existed
372
+ * (XR-079).
373
+ */
374
+ reviewImportedCoins?: boolean
286
375
  }
287
376
 
288
377
  export interface WalletContextValue {
@@ -293,8 +382,13 @@ export interface WalletContextValue {
293
382
  // Settings
294
383
  settings: WalletSettings
295
384
  updateSettings: (newSettings: WalletSettings) => Promise<void>
296
- // Logout
297
- logout: () => void
385
+ /** "Delete Wallet". Resolves to whether the secrets layer verified every
386
+ * legacy plaintext item erased (XR-107) — false means a persistent
387
+ * SecureStore delete failure left something recoverable, and the caller
388
+ * must report that as a failure (offer retry) rather than treat the
389
+ * wallet as gone: this same false also means the attestation was left
390
+ * untouched and no navigation happened. */
391
+ logout: () => Promise<boolean>
298
392
  adminOriginator: string
299
393
  basketRequests: BasketAccessRequest[]
300
394
  certificateRequests: CertificateAccessRequest[]
@@ -325,12 +419,31 @@ export interface WalletContextValue {
325
419
  * captured `backupRestore` is still the pre-build render's value. This reads the ref.
326
420
  */
327
421
  getBackupRestore: () => BackupRestoreState
422
+ /**
423
+ * This wallet's own backup-server pseudonym for `chain`, or undefined when no wallet is
424
+ * built for that chain (or none at all). Not a secret — it is exactly what the backup
425
+ * server sees as this wallet's account — but deriving it needs the primary key, so it is
426
+ * exposed this way rather than the key itself. See XR-009 / getBackupUploadState.
427
+ */
428
+ getBackupPseudonym: (chain: BackupChain) => string | undefined
429
+ /**
430
+ * The same value as `walletBuilt`, read fresh.
431
+ *
432
+ * Mirrors `getBackupRestore`'s rationale: a caller that awaits a build or rebuild
433
+ * (recoverWallet's retry loop is the motivating case) and then checks whether the
434
+ * wallet is already built must not see a React state snapshot frozen at the render
435
+ * before the await — it must see the ref, which is updated synchronously at every
436
+ * build/teardown transition.
437
+ */
438
+ getWalletBuilt: () => boolean
328
439
  switchNetwork: (network: AppChain) => Promise<void>
329
440
  /** Tear down the current wallet and re-trigger auto-build (e.g. after DB import).
330
441
  * `restoreFromBackup` threads through to the auto-build's replay, for replacing
331
442
  * an already-built wallet with an imported one (e.g. onboarding's backup-reminder
332
- * "import from backup" over an auto-created wallet). */
333
- rebuildWallet: (opts?: { restoreFromBackup?: boolean }) => Promise<void>
443
+ * "import from backup" over an auto-created wallet). `reviewImportedCoins` threads
444
+ * through to a post-storage-attach reconciliation pass (no remote replay) for a raw
445
+ * database import that already carries a complete local database (XR-079). */
446
+ rebuildWallet: (opts?: { restoreFromBackup?: boolean; reviewImportedCoins?: boolean }) => Promise<void>
334
447
  storage: StorageExpoSQLite | null
335
448
  /**
336
449
  * Mandala stablecoins, or undefined.
@@ -384,7 +497,7 @@ export const WalletContext = createContext<WalletContextValue>({
384
497
  getManagers: () => ({}),
385
498
  settings: DEFAULT_SETTINGS,
386
499
  updateSettings: async () => {},
387
- logout: () => {},
500
+ logout: async () => false,
388
501
  adminOriginator: ADMIN_ORIGINATOR,
389
502
  basketRequests: [],
390
503
  certificateRequests: [],
@@ -408,6 +521,8 @@ export const WalletContext = createContext<WalletContextValue>({
408
521
  buildWalletFromRecoveredKey: async () => {},
409
522
  backupRestore: { phase: 'idle', chunks: 0, total: 0 },
410
523
  getBackupRestore: () => ({ phase: 'idle', chunks: 0, total: 0 }),
524
+ getBackupPseudonym: () => undefined,
525
+ getWalletBuilt: () => false,
411
526
  switchNetwork: async () => {},
412
527
  rebuildWallet: async () => {},
413
528
  storage: null,
@@ -598,6 +713,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
598
713
  const [mandala, setMandala] = useState<MandalaRuntime | undefined>(undefined)
599
714
  const mandalaRef = useRef<MandalaRuntime | undefined>(undefined)
600
715
  const appStateRef = useRef<AppStateStatus>(AppState.currentState)
716
+ const monitorSupervisorRef = useRef<MonitorSupervisor | null>(null)
601
717
  const monitorRef = useRef<Monitor | null>(null)
602
718
  // The offline-first chain tracker and the header store it wraps. Populated
603
719
  // in buildWallet (tracker synchronously, store once the background open
@@ -661,6 +777,22 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
661
777
  setBackupRestoreState(next)
662
778
  }, [])
663
779
  const getBackupRestore = useCallback((): BackupRestoreState => backupRestoreRef.current, [])
780
+ const getWalletBuilt = useCallback((): boolean => walletBuiltRef.current, [])
781
+ /**
782
+ * Set once buildWallet resolves this build's backup chain/pseudonym, so a screen (Wallet
783
+ * Check) can scope a backup-cursor lookup to the CURRENT identity (see XR-009) without
784
+ * ever seeing the primary key itself — the pseudonym is derived from it but is not a
785
+ * secret; it is exactly what the backup server sees as this wallet's account. Cleared on
786
+ * logout so a departed wallet's pseudonym is never read back before the next build sets
787
+ * its own; `getBackupPseudonym` also refuses to answer for any OTHER chain, so a stale
788
+ * entry from a network switch can never be misread as the current one's.
789
+ */
790
+ const backupIdentityRef = useRef<{ chain: BackupChain, pseudonym: string } | null>(null)
791
+ const getBackupPseudonym = useCallback(
792
+ (chain: BackupChain): string | undefined =>
793
+ backupIdentityRef.current?.chain === chain ? backupIdentityRef.current.pseudonym : undefined,
794
+ []
795
+ )
664
796
  /**
665
797
  * Set by an import flow immediately before it hands the primary key over, and consumed
666
798
  * (and cleared) by the buildWallet pass it triggers. A ref rather than state because
@@ -668,6 +800,17 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
668
800
  * render — a state read there would see whatever was committed, which is a race.
669
801
  */
670
802
  const restoreIntentRef = useRef(false)
803
+ /**
804
+ * Set by a raw-database-import flow (ui/importDatabases.ts, via
805
+ * rebuildWallet's `reviewImportedCoins` option) immediately before it
806
+ * triggers a rebuild, and consumed (and cleared) once local storage is
807
+ * attached in the build this triggers. Deliberately separate from
808
+ * restoreIntentRef: a raw import already carries a complete local
809
+ * database, so it must NOT also pull and replay the encrypted remote
810
+ * backup — it only needs the same spendability reconciliation pass that
811
+ * restoreIntentRef's path runs after its own replay (XR-079).
812
+ */
813
+ const reviewImportedCoinsRef = useRef(false)
671
814
  /**
672
815
  * Set by rebuildWallet right before finalizeConfig, cleared by the auto-build
673
816
  * effect once it actually starts (or determines there is nothing to build).
@@ -763,6 +906,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
763
906
  AsyncStorage.getItem(AUTO_APPROVE_STORAGE_KEY).then(v => {
764
907
  if (v !== null) autoApproveThresholdRef.current = Number(v) || 0
765
908
  })
909
+ // Restores the rolling auto-approve ledger so an app restart does not
910
+ // reset the daily cap (misc-p2-04). Best-effort — see loadAutoApproveLedgerOnce.
911
+ loadAutoApproveLedgerOnce()
766
912
  AsyncStorage.getItem('walletSettings').then(v => {
767
913
  if (v) setSettings(prev => ({ ...prev, ...JSON.parse(v) }))
768
914
  })
@@ -930,36 +1076,39 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
930
1076
  const { requestID, originator, reason, renewal, spending } = args
931
1077
  if (!requestID || !spending) return
932
1078
 
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").
1079
+ // Auto-approve small transactions if within threshold, per-originator
1080
+ // cooldown, and the global rolling 24h cap (misc-p2-04) — accounting
1081
+ // lives in autoApprovePolicy.ts. Read the persisted threshold fresh on
1082
+ // every request so a change made in wallet-config takes effect
1083
+ // immediately (the mount-time ref read alone left the old value live
1084
+ // until app restart — felt like auto-approve was "stuck on").
938
1085
  try {
939
1086
  const stored = await AsyncStorage.getItem(AUTO_APPROVE_STORAGE_KEY)
940
1087
  if (stored !== null) autoApproveThresholdRef.current = Number(stored) || 0
941
1088
  } catch {}
942
1089
  const threshold = autoApproveThresholdRef.current
943
- const now = Date.now()
944
- const sinceLastMs = now - lastAutoApproveTime
1090
+ autoApproveThresholdSnapshot = threshold
945
1091
  // Logging gated behind __DEV__: an unconditional console.log here flushes
946
1092
  // over the JS↔native bridge on every spend request — i.e. on the payment
947
1093
  // 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__) {
1094
+ const autoApproveDecision = autoApprovePolicy.shouldAutoApprove({
1095
+ originator,
1096
+ satoshis: spending.satoshis
1097
+ })
1098
+ if (autoApproveDecision.approve) {
1099
+ autoApprovePolicy.record({ originator, satoshis: spending.satoshis, at: Date.now() })
1100
+ persistAutoApproveLedger()
1101
+ if (__DEV__) console.log(`[spend-auth] AUTO-APPROVING requestID=${requestID} sats=${spending.satoshis}`)
1102
+ managersRef.current.permissionsManager?.grantPermission({
1103
+ requestID,
1104
+ ephemeral: true,
1105
+ amount: spending.satoshis
1106
+ })
1107
+ return
1108
+ }
1109
+ if (__DEV__) {
961
1110
  console.log(
962
- `[spend-auth] not eligible → manual modal requestID=${requestID} sats=${spending.satoshis} threshold=${threshold}`
1111
+ `[spend-auth] not eligible (${autoApproveDecision.reason}) → manual modal requestID=${requestID} sats=${spending.satoshis} threshold=${threshold}`
963
1112
  )
964
1113
  }
965
1114
 
@@ -1080,16 +1229,26 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1080
1229
  // the backup derivation is frozen on the app-level names.
1081
1230
  const backupChain =
1082
1231
  chain === 'main' ? ('main' as const) : chain === 'test' ? ('test' as const) : ('teratest' as const)
1232
+ // See getBackupPseudonym's own docs: this is what lets Wallet Check scope its
1233
+ // cursor lookup to THIS identity without the primary key itself leaving this scope.
1234
+ backupIdentityRef.current = { chain: backupChain, pseudonym: backupPseudonym(primaryKey, backupChain) }
1083
1235
  const keyDeriver = new KeyDeriver(new PrivateKey(primaryKey))
1084
1236
  const storageManager = new WalletStorageManager(keyDeriver.identityKey)
1085
1237
  const signer = new WalletSigner(walletChain, keyDeriver, storageManager)
1086
1238
 
1087
1239
  const bsvExchangeRate = await getExchangeRate()
1088
- const callbackToken = keyDeriver.identityKey.substring(0, 32)
1089
-
1240
+ // Derived from PRIVATE key material (misc-p2-06) — was previously the
1241
+ // first 32 chars of the PUBLIC identityKey, which any past
1242
+ // counterparty can already reconstruct. See callbackToken.ts.
1243
+ const callbackToken = deriveCallbackToken(keyDeriver)
1244
+
1245
+ // XR-106: the token half is SecureStore-backed (getArcApiToken also
1246
+ // migrates away any plaintext value a pre-fix build left in
1247
+ // AsyncStorage under this same key) — only the URL, which is not a
1248
+ // credential, still lives in plain AsyncStorage.
1090
1249
  const [arcUrlOverride, arcApiTokenOverride] = await Promise.all([
1091
1250
  AsyncStorage.getItem(`arc_custom_url_${chain}`),
1092
- AsyncStorage.getItem(`arc_custom_api_token_${chain}`)
1251
+ getArcApiToken(chain)
1093
1252
  ])
1094
1253
 
1095
1254
  // The remote client the wrapper delegates to. Built here rather than
@@ -1098,7 +1257,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1098
1257
  // the single source of truth for these URLs — createServiceOptions
1099
1258
  // calls the same function, so there is exactly one table to edit.
1100
1259
  const remoteChaintracks = new ChaintracksServiceClient(walletChain, chaintracksUrlFor(chain))
1101
- const offlineChaintracks = new OfflineFirstChaintracks(remoteChaintracks, getOnline)
1260
+ const offlineChaintracks = new OfflineFirstChaintracks(remoteChaintracks, getOnline, walletChain)
1102
1261
  offlineChaintracksRef.current = offlineChaintracks
1103
1262
 
1104
1263
  // Passing offlineChaintracks here does two things, and createServices
@@ -1121,19 +1280,22 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1121
1280
 
1122
1281
  // Replace all default broadcast providers with EF/rawtx-only services.
1123
1282
  // Order: Arcade → Taal → GorillaPool → WoC → Bitails. UntilSuccess stops at first success.
1283
+ // Taal runs on main + test only, GorillaPool on main only; teratest has no public ARC.
1284
+ // 'ArcadeBeef' is the toolbox's own Arcade broadcaster, registered
1285
+ // because serviceOptions now carries arcadeUrl (needed for Arcade-first
1286
+ // proofs and SSE). Our createArcadeBroadcastService replaces it here so
1287
+ // the same tx is not posted to Arcade twice with two header sets.
1124
1288
  const bitailsService = (services as any).bitails
1289
+ services.postBeefServices.remove('ArcadeBeef')
1125
1290
  services.postBeefServices.remove('GorillaPoolArcBeef')
1126
1291
  services.postBeefServices.remove('TaalArcBeef')
1127
1292
  services.postBeefServices.remove('Bitails')
1128
1293
  services.postBeefServices.remove('WhatsOnChain')
1129
1294
  services.postBeefServices.add(createArcadeBroadcastService(serviceOptions.arcUrl!, callbackToken))
1130
- const taalArcUrl =
1131
- chain === 'main'
1132
- ? 'https://arc.taal.com'
1133
- : chain === 'test'
1134
- ? 'https://arc-test.taal.com'
1135
- : 'https://arc-teratest.taal.com'
1136
- services.postBeefServices.add(createTaalBroadcastService(taalArcUrl, serviceOptions.taalApiKey))
1295
+ if (chain === 'main' || chain === 'test') {
1296
+ const taalArcUrl = chain === 'main' ? 'https://arc.taal.com' : 'https://arc-test.taal.com'
1297
+ services.postBeefServices.add(createTaalBroadcastService(taalArcUrl, serviceOptions.taalApiKey))
1298
+ }
1137
1299
  if (chain === 'main') {
1138
1300
  services.postBeefServices.add(createGorillaPoolBroadcastService('https://arc.gorillapool.io'))
1139
1301
  }
@@ -1143,7 +1305,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1143
1305
  }
1144
1306
 
1145
1307
  // Replace WoC getMerklePath with BUMP endpoint — no TSC→BUMP conversion needed.
1146
- // Remove all providers then re-add in order: WoC BUMP first, Bitails fallback.
1308
+ // The toolbox's 'Arcade' provider stays where Services put it: first.
1309
+ // Every tx this wallet sends goes through Arcade, so GET /tx/{txid}
1310
+ // there is the one lookup that can answer as soon as it is mined. WoC
1311
+ // BUMP and Bitails are re-added after it as fallbacks, in that order.
1147
1312
  const wocBumpBase =
1148
1313
  chain === 'main'
1149
1314
  ? 'https://api.whatsonchain.com/v1/bsv/main'
@@ -1244,6 +1409,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1244
1409
  // ── Select the best database file from the registry ──
1245
1410
  let knownDbs = await getRegisteredDbs(keySuffix, chainStr)
1246
1411
 
1412
+ // Whether THIS build attempt is the one that created selectedDb below, as
1413
+ // opposed to reselecting a file that already existed before this attempt
1414
+ // started (an already-onboarded identity's real database, or a legacy file
1415
+ // discovered on disk). Only true in the "fresh user" branch — see its use at
1416
+ // the restore-failure cleanup further down (XR-017 review follow-up).
1417
+ let dbWasFreshlyCreatedThisAttempt = false
1418
+
1247
1419
  if (knownDbs.length === 0) {
1248
1420
  // First launch after update or fresh user.
1249
1421
  // Probe for a legacy (no-timestamp) database file.
@@ -1259,6 +1431,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1259
1431
  const newName = `wallet-${keySuffix}-${chainStr}net-${ts}.db`
1260
1432
  await registerDb(keySuffix, chainStr, newName)
1261
1433
  knownDbs = [newName]
1434
+ dbWasFreshlyCreatedThisAttempt = true
1262
1435
  console.log(`[WalletContext] Created new timestamped DB: ${newName}`)
1263
1436
  }
1264
1437
  }
@@ -1317,9 +1490,27 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1317
1490
  `[WalletContext] backup restore · restored=${String(restored.restored)} · ` +
1318
1491
  `chunks=${restored.chunks} · reason=${restored.reason ?? 'none'}`
1319
1492
  )
1493
+ // See P1-backup-incomplete-generation: restoreOnImport.pickTarget falls back to
1494
+ // an unverified (no seal) target rather than blocking the import, so this is a
1495
+ // warning rather than a thrown error — but it must not pass silently, since the
1496
+ // replayed generation could be a partial mid-rotation snapshot. The screens
1497
+ // that drive `recoverWallet` surface this to the user directly (restoreUnverified
1498
+ // in ui/recoveryPrompts.ts); this warn is the equivalent for the import flow,
1499
+ // which has no such prompt.
1500
+ if (restored.restored && restored.verified === false) {
1501
+ console.warn(
1502
+ `[backup] restore completed but could not be verified as a complete ` +
1503
+ `generation · deviceId=${String(restored.deviceId)} · generation=${String(restored.generation)}`
1504
+ )
1505
+ }
1320
1506
  setBackupRestore(
1321
1507
  restored.restored
1322
- ? { phase: 'restored', chunks: restored.chunks, total: restored.chunks }
1508
+ ? {
1509
+ phase: 'restored',
1510
+ chunks: restored.chunks,
1511
+ total: restored.chunks,
1512
+ verified: restored.verified
1513
+ }
1323
1514
  : { phase: 'no-backup', chunks: 0, total: 0 }
1324
1515
  )
1325
1516
  } catch (e: any) {
@@ -1331,6 +1522,32 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1331
1522
  try {
1332
1523
  await phoneStorage.destroy()
1333
1524
  } catch {}
1525
+ // restoreOnImport's precondition is that the database is freshly migrated
1526
+ // and still empty of real data — but that is only actually guaranteed when
1527
+ // THIS attempt is the one that just created selectedDb (dbWasFreshlyCreated
1528
+ // ThisAttempt). rebuildWallet({restoreFromBackup:true}) takes this same path
1529
+ // to "recover over an already-onboarded wallet" (see restoreWallet.ts), and
1530
+ // recoverWallet.ts's confirmReplace does not check whether the newly
1531
+ // supplied secret differs from the one already active — so selectedDb can
1532
+ // instead be a pre-existing, already-registered database (this identity's
1533
+ // real, live wallet, or a legacy file just discovered on disk) that this
1534
+ // attempt only SELECTED, never created. Deleting that on a restore failure
1535
+ // would destroy locally-cached change-output/BRC-29 metadata the seed cannot
1536
+ // reconstruct (see XR-017 review follow-up). Only ever discard a database
1537
+ // this exact attempt created: a later build that skips another replay
1538
+ // (recoverWallet's "skip", or any future restoreFromBackup:false call) would
1539
+ // otherwise reselect this SAME partially replayed file via selectLatestDb and
1540
+ // publish it as a working wallet. Both steps are best-effort cleanup: the
1541
+ // ORIGINAL restore failure above is what must reach the caller, not a failure
1542
+ // to tidy up after it.
1543
+ if (dbWasFreshlyCreatedThisAttempt) {
1544
+ try {
1545
+ await unregisterDb(keySuffix, chainStr, selectedDb)
1546
+ } catch {}
1547
+ try {
1548
+ await SQLite.deleteDatabaseAsync(selectedDb)
1549
+ } catch {}
1550
+ }
1334
1551
  throw e
1335
1552
  }
1336
1553
  }
@@ -1354,6 +1571,20 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1354
1571
  console.error('[WalletContext] Failed to add local storage provider:', error)
1355
1572
  }
1356
1573
 
1574
+ // A raw database import (ui/importDatabases.ts) armed this instead of
1575
+ // restoreIntentRef: the imported database is already a complete local
1576
+ // copy, so there is nothing to replay, but it never ran the same
1577
+ // spendability reconciliation an encrypted restore runs above before
1578
+ // its balance is trusted and displayed (XR-079).
1579
+ if (reviewImportedCoinsRef.current) {
1580
+ reviewImportedCoinsRef.current = false
1581
+ try {
1582
+ await wallet.reviewSpendableOutputs(false, true)
1583
+ } catch (error) {
1584
+ console.error('[WalletContext] Post-import reconciliation failed:', error)
1585
+ }
1586
+ }
1587
+
1357
1588
  let migrationUserId: number | undefined
1358
1589
  try {
1359
1590
  const auth = await storageManager.getAuth()
@@ -1419,20 +1650,53 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1419
1650
  // module's own admin pass-through branch). Shared by the module's
1420
1651
  // deps below AND by wrapCreateActionForTokenInputs's wrapper further
1421
1652
  // down, so both use the exact same listing.
1422
- const listMandalaTokenOutpoints = async (): Promise<Set<string>> => {
1423
- try {
1424
- const { outputs } = await wallet.listOutputs(
1425
- { basket: MANDALA_BASKET, includeCustomInstructions: false, limit: 10000 } as never,
1426
- adminOriginator
1427
- )
1428
- return new Set(outputs.map((o: { outpoint: string }) => o.outpoint))
1429
- } catch {
1430
- // A wallet with no Mandala basket yet, or a storage fault -- treat
1431
- // as "no known token inputs" rather than blocking createAction;
1432
- // see permissionModule.ts's doc on this dep failing open.
1433
- return new Set()
1434
- }
1435
- }
1653
+ //
1654
+ // XR-039: paginated to completion via `listAllOutpoints` (a single
1655
+ // 10,000-row page silently truncated a larger basket, and a spend of
1656
+ // an input past that page read as "not a token input" -- the same
1657
+ // balance-truncation bug `core/localpay/build.ts`'s `listTokenBasket`
1658
+ // and `createRuntime.ts`'s `listTokenOutputs` were already fixed
1659
+ // for), and a genuine listing fault now PROPAGATES instead of being
1660
+ // swallowed into an authoritative-looking empty Set -- an empty Set
1661
+ // here reads as "confirmed no token inputs" to every caller, which a
1662
+ // storage fault or a wallet with no Mandala basket are not
1663
+ // distinguishable from without this throwing. The two callers
1664
+ // (`injectMandalaLabelIfTokenInputsPresent`, `anyInputIsTokenCoin`)
1665
+ // are exactly what now fails closed on that throw.
1666
+ const listMandalaTokenOutpoints = (): Promise<Set<string>> =>
1667
+ listAllOutpoints(
1668
+ async (limit, offset) =>
1669
+ await wallet.listOutputs(
1670
+ { basket: MANDALA_BASKET, includeCustomInstructions: false, limit, offset } as never,
1671
+ adminOriginator
1672
+ ),
1673
+ MANDALA_OUTPOINT_LIST_PAGE,
1674
+ MANDALA_OUTPOINT_LIST_MAX_PAGES
1675
+ )
1676
+
1677
+ // XR-041: resolves ONE outpoint named on a `relinquishOutput` call to
1678
+ // its decoded `{assetId, amount}`, from this device's OWN current
1679
+ // MANDALA_BASKET listing — `include: 'locking scripts'` is the one
1680
+ // difference from `listMandalaTokenOutpoints` above, since naming the
1681
+ // holding needs the script, not just the outpoint. Same admin-
1682
+ // originator, zero-prompt listing; same to-completion paging.
1683
+ const resolveMandalaOutputForRelinquish = (outpoint: string) =>
1684
+ resolveMandalaOutput(
1685
+ async (limit, offset) =>
1686
+ await wallet.listOutputs(
1687
+ {
1688
+ basket: MANDALA_BASKET,
1689
+ include: 'locking scripts',
1690
+ includeCustomInstructions: false,
1691
+ limit,
1692
+ offset
1693
+ } as never,
1694
+ adminOriginator
1695
+ ),
1696
+ outpoint,
1697
+ MANDALA_OUTPOINT_LIST_PAGE,
1698
+ MANDALA_OUTPOINT_LIST_MAX_PAGES
1699
+ )
1436
1700
 
1437
1701
  // Mandala's own P-module (schemeID 'mandala', basket MANDALA_BASKET =
1438
1702
  // 'p mandala') -- same routing mechanism as BTMS above
@@ -1443,7 +1707,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1443
1707
  adminOriginator,
1444
1708
  requestTokenAccess: mandalaPromptHandler,
1445
1709
  resolveAssetMetadata: resolveMandalaAssetMetadata,
1446
- listTokenOutpoints: listMandalaTokenOutpoints
1710
+ listTokenOutpoints: listMandalaTokenOutpoints,
1711
+ resolveMandalaOutput: resolveMandalaOutputForRelinquish
1447
1712
  })
1448
1713
 
1449
1714
  // Setup permissions with provided callbacks and BTMS module.
@@ -1510,10 +1775,17 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1510
1775
  // admitted (and therefore broadcast) releases inputs that are spent on
1511
1776
  // chain. It reads the settlement store LATE, off `mandalaRef`, because
1512
1777
  // the runtime is built below this line and replaced on every rebuild.
1778
+ //
1779
+ // XR-034: `mandalaEndpoints` (above, static for this build) is the
1780
+ // guard's ONLY "token settlement provably not in use" signal — never
1781
+ // `mandalaRef.current`, whose `undefined` also covers a runtime that
1782
+ // threw or is mid-rebuild, both of which can leave real settlement
1783
+ // rows unreadable rather than absent.
1513
1784
  newManagers.permissionsManager = guardVaultAccess(
1514
1785
  wrapAbortActionForSettlements(
1515
1786
  wrapCreateActionForTokenInputs(permissionsManager, listMandalaTokenOutpoints, adminOriginator),
1516
- () => mandalaRef.current?.store
1787
+ () => mandalaRef.current?.store,
1788
+ () => mandalaEndpoints !== undefined
1517
1789
  ),
1518
1790
  adminOriginator
1519
1791
  )
@@ -1811,7 +2083,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1811
2083
  // the drain so the parent goes out first.
1812
2084
  if (phoneStorage) {
1813
2085
  const sendWaiting = monitor._tasks.find(t => t.name === 'SendWaiting') as
1814
- | { processUnsent?: (reqApis: Array<{ txid: string; rawTx?: number[] }>, indent?: number) => Promise<string> }
2086
+ | {
2087
+ processUnsent?: (
2088
+ reqApis: Array<{ txid: string; rawTx?: number[] }>,
2089
+ indent?: number
2090
+ ) => Promise<string>
2091
+ }
1815
2092
  | undefined
1816
2093
  if (sendWaiting?.processUnsent) {
1817
2094
  const orig = sendWaiting.processUnsent.bind(sendWaiting)
@@ -1820,7 +2097,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1820
2097
  // row is the settlement drain's to broadcast, after `/submit`,
1821
2098
  // never the monitor's. Held here and dropped from this pass.
1822
2099
  const heldTokenTxids = await phoneStorage.holdTokenReqsForDrain(allReqApis as never)
1823
- const reqApis = heldTokenTxids.size > 0 ? allReqApis.filter(r => !heldTokenTxids.has(r.txid)) : allReqApis
2100
+ const reqApis =
2101
+ heldTokenTxids.size > 0 ? allReqApis.filter(r => !heldTokenTxids.has(r.txid)) : allReqApis
1824
2102
  if (heldTokenTxids.size > 0) TaskSendOffline.requestNow()
1825
2103
  let queuedTxids = new Set<string>()
1826
2104
  try {
@@ -1841,7 +2119,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1841
2119
  if (deferred > 0) TaskSendOffline.requestNow()
1842
2120
  if (ready.length === 0) {
1843
2121
  const notes: string[] = []
1844
- if (heldTokenTxids.size > 0) notes.push(`held ${heldTokenTxids.size} token req(s) for the settlement drain`)
2122
+ if (heldTokenTxids.size > 0)
2123
+ notes.push(`held ${heldTokenTxids.size} token req(s) for the settlement drain`)
1845
2124
  if (deferred > 0) notes.push(`deferred ${deferred} req(s) behind queued ancestors`)
1846
2125
  return notes.length > 0 ? `${notes.join('; ')}\n` : ''
1847
2126
  }
@@ -1997,8 +2276,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1997
2276
  // otherwise "stop" a not-yet-started monitor and this callback
1998
2277
  // would then start an unstoppable zombie nothing references.
1999
2278
  if (monitorRef.current !== monitor) return
2000
- // startTasks runs in background — don't await (it never resolves until stopTasks)
2001
- monitor.startTasks().catch(e => console.error('[WalletContext] Monitor error:', e))
2279
+ // Not monitor.startTasks(): the supervisor drives the same pass
2280
+ // loop, but survives a throwing pass and can be restarted by the
2281
+ // watchdog below when a pass hangs. See MonitorSupervisor.
2282
+ const supervisor = new MonitorSupervisor()
2283
+ monitorSupervisorRef.current = supervisor
2284
+ supervisor.start(monitor)
2002
2285
  })
2003
2286
  logWithTimestamp(F, 'Monitor scheduled (ARC SSE) after interactions')
2004
2287
  } catch (error: any) {
@@ -2154,6 +2437,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2154
2437
  // rebuildWallet until buildWallet consumes it. Explicit false still
2155
2438
  // allows the import screen to continue without restoring on retry.
2156
2439
  if (opts !== undefined) restoreIntentRef.current = opts.restoreFromBackup === true
2440
+ if (opts !== undefined) reviewImportedCoinsRef.current = opts.reviewImportedCoins === true
2157
2441
 
2158
2442
  // Provide the primary key and privileged key manager to authenticate the wallet
2159
2443
  await swm.providePrimaryKey(primaryKey)
@@ -2188,6 +2472,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2188
2472
  // Never leave the intent armed: the next build on this device would otherwise be
2189
2473
  // an auto-build on relaunch, which must not re-import over a live database.
2190
2474
  restoreIntentRef.current = false
2475
+ reviewImportedCoinsRef.current = false
2191
2476
  walletBuildingRef.current = false
2192
2477
  setWalletBuilding(false)
2193
2478
  console.error('[WalletContext] Error building mnemonic wallet:', error)
@@ -2225,6 +2510,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2225
2510
  // rebuildWallet until buildWallet consumes it. Explicit false still
2226
2511
  // allows the import screen to continue without restoring on retry.
2227
2512
  if (opts !== undefined) restoreIntentRef.current = opts.restoreFromBackup === true
2513
+ if (opts !== undefined) reviewImportedCoinsRef.current = opts.reviewImportedCoins === true
2228
2514
 
2229
2515
  await swm.providePrimaryKey(primaryKey)
2230
2516
 
@@ -2242,6 +2528,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2242
2528
  logWithTimestamp(F, 'Recovered key wallet build completed')
2243
2529
  } catch (error: any) {
2244
2530
  restoreIntentRef.current = false
2531
+ reviewImportedCoinsRef.current = false
2245
2532
  walletBuildingRef.current = false
2246
2533
  setWalletBuilding(false)
2247
2534
  console.error('[WalletContext] Error building wallet from recovered key:', error)
@@ -2253,73 +2540,78 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2253
2540
 
2254
2541
  // Tear down the current wallet and re-trigger auto-build.
2255
2542
  // Used after DB import and internally by switchNetwork.
2256
- const rebuildWallet = useCallback(async (opts?: { restoreFromBackup?: boolean }) => {
2257
- logWithTimestamp(F, 'Rebuilding wallet')
2258
- // Armed before teardown so the auto-build effect this triggers (via
2259
- // finalizeConfig below) replays the backup log the same way an explicit
2260
- // buildWalletFromMnemonic({ restoreFromBackup: true }) would.
2261
- restoreIntentRef.current = opts?.restoreFromBackup === true
2262
- // Any build already in flight belongs to the configuration being replaced.
2263
- const token = buildGenRef.current.bump()
2264
- // Invalidate Vault operations before the first teardown await. Otherwise a
2265
- // signer/listing already in flight can resume against the departing wallet.
2266
- vaultStore.clearScope()
2267
- vaultCeremony.cancel()
2543
+ const rebuildWallet = useCallback(
2544
+ async (opts?: { restoreFromBackup?: boolean; reviewImportedCoins?: boolean }) => {
2545
+ logWithTimestamp(F, 'Rebuilding wallet')
2546
+ // Armed before teardown so the auto-build effect this triggers (via
2547
+ // finalizeConfig below) replays the backup log the same way an explicit
2548
+ // buildWalletFromMnemonic({ restoreFromBackup: true }) would.
2549
+ restoreIntentRef.current = opts?.restoreFromBackup === true
2550
+ // Same arming pattern, for the raw-import reconciliation pass (XR-079).
2551
+ reviewImportedCoinsRef.current = opts?.reviewImportedCoins === true
2552
+ // Any build already in flight belongs to the configuration being replaced.
2553
+ const token = buildGenRef.current.bump()
2554
+ // Invalidate Vault operations before the first teardown await. Otherwise a
2555
+ // signer/listing already in flight can resume against the departing wallet.
2556
+ vaultStore.clearScope()
2557
+ vaultCeremony.cancel()
2558
+
2559
+ // Stop any running monitor and let its current pass drain before the
2560
+ // storage teardown below closes the connection under it.
2561
+ {
2562
+ const monitor = monitorRef.current
2563
+ if (monitor) {
2564
+ monitorRef.current = null
2565
+ await stopMonitorAndDrain(monitor)
2566
+ }
2567
+ }
2568
+ // Same convention as monitorRef above: clear so a stale deferred header
2569
+ // init or reconnect handler from the old build can't pair a leftover
2570
+ // store/tracker across the rebuild.
2571
+ offlineChaintracksRef.current = undefined
2572
+ headerStoreRef.current = undefined
2268
2573
 
2269
- // Stop any running monitor and let its current pass drain before the
2270
- // storage teardown below closes the connection under it.
2271
- {
2272
- const monitor = monitorRef.current
2273
- if (monitor) {
2274
- monitorRef.current = null
2275
- await stopMonitorAndDrain(monitor)
2574
+ // Close the current storage connection so the new build can open
2575
+ // whichever DB file the registry selects.
2576
+ if (storage?.db) {
2577
+ try {
2578
+ await storage.destroy()
2579
+ } catch {}
2276
2580
  }
2277
- }
2278
- // Same convention as monitorRef above: clear so a stale deferred header
2279
- // init or reconnect handler from the old build can't pair a leftover
2280
- // store/tracker across the rebuild.
2281
- offlineChaintracksRef.current = undefined
2282
- headerStoreRef.current = undefined
2283
-
2284
- // Close the current storage connection so the new build can open
2285
- // whichever DB file the registry selects.
2286
- if (storage?.db) {
2287
- try {
2288
- await storage.destroy()
2289
- } catch {}
2290
- }
2291
- // And drop the handle with it. Leaving a destroyed storage in state kept
2292
- // the screens reading the OLD chain's database until the new build
2293
- // replaced it — which is how a testnet wallet displayed mainnet money.
2294
- setStorage(null)
2295
- // The runtime holds this build's settlement store, which is a handle on
2296
- // the database just destroyed. Dropping it here is what stops a monitor
2297
- // task or a screen draining the departed wallet's tables.
2298
- mandalaRef.current = undefined
2299
- setMandala(undefined)
2300
- forgetSessionPsks()
2301
-
2302
- // Tear down current wallet state (but keep mnemonic / config)
2303
- vaultStore.clearScope()
2304
- updateManagers({})
2305
- walletBuiltRef.current = false
2306
- setWalletBuilt(false)
2307
- walletBuildingRef.current = false
2308
- setWalletBuilding(false)
2309
-
2310
- // Re-finalize with current config — triggers auto-build effect
2311
- const config = { wabUrl: 'noWAB', method: 'mnemonic', network: selectedNetwork, storageUrl: 'local' }
2312
- pendingAutoBuildRef.current = true
2313
- finalizeConfig(config)
2314
- logWithTimestamp(F, 'Wallet rebuild triggered')
2315
- // finalizeConfig above only requests the rebuild; without this,
2316
- // rebuildWallet's promise resolved before the auto-build effect had even
2317
- // run, so `await rebuildWallet(...)` callers (e.g. the import screens
2318
- // replacing an auto-created wallet) saw pre-rebuild managers and a
2319
- // pre-rebuild walletBuilt — silently skipping anything gated on the new
2320
- // wallet actually existing, such as recording a backup attestation.
2321
- await waitForRebuild(token)
2322
- }, [selectedNetwork, storage, finalizeConfig, waitForRebuild])
2581
+ // And drop the handle with it. Leaving a destroyed storage in state kept
2582
+ // the screens reading the OLD chain's database until the new build
2583
+ // replaced it — which is how a testnet wallet displayed mainnet money.
2584
+ setStorage(null)
2585
+ // The runtime holds this build's settlement store, which is a handle on
2586
+ // the database just destroyed. Dropping it here is what stops a monitor
2587
+ // task or a screen draining the departed wallet's tables.
2588
+ mandalaRef.current = undefined
2589
+ setMandala(undefined)
2590
+ forgetSessionPsks()
2591
+
2592
+ // Tear down current wallet state (but keep mnemonic / config)
2593
+ vaultStore.clearScope()
2594
+ updateManagers({})
2595
+ walletBuiltRef.current = false
2596
+ setWalletBuilt(false)
2597
+ walletBuildingRef.current = false
2598
+ setWalletBuilding(false)
2599
+
2600
+ // Re-finalize with current config — triggers auto-build effect
2601
+ const config = { wabUrl: 'noWAB', method: 'mnemonic', network: selectedNetwork, storageUrl: 'local' }
2602
+ pendingAutoBuildRef.current = true
2603
+ finalizeConfig(config)
2604
+ logWithTimestamp(F, 'Wallet rebuild triggered')
2605
+ // finalizeConfig above only requests the rebuild; without this,
2606
+ // rebuildWallet's promise resolved before the auto-build effect had even
2607
+ // run, so `await rebuildWallet(...)` callers (e.g. the import screens
2608
+ // replacing an auto-created wallet) saw pre-rebuild managers and a
2609
+ // pre-rebuild walletBuilt — silently skipping anything gated on the new
2610
+ // wallet actually existing, such as recording a backup attestation.
2611
+ await waitForRebuild(token)
2612
+ },
2613
+ [selectedNetwork, storage, finalizeConfig, waitForRebuild]
2614
+ )
2323
2615
 
2324
2616
  // Switch network: tear down wallet, update config, and rebuild on new chain
2325
2617
  const switchNetwork = useCallback(
@@ -2475,8 +2767,47 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2475
2767
  void replayPendingAborts({
2476
2768
  wallet: managers.permissionsManager as {
2477
2769
  abortAction: (args: { reference: string }, originator?: string) => Promise<{ aborted?: boolean } | void>
2770
+ verifyHmac: NonNullable<typeof managers.permissionsManager>['verifyHmac']
2478
2771
  },
2479
2772
  storage
2773
+ }).then(result => {
2774
+ // XR-102: an entry replayPendingAborts dropped as untrusted (missing or
2775
+ // mismatching authority tag) never called abortAction at all, so
2776
+ // whatever it named — if it was even real — is unaffected; the only
2777
+ // thing to tell the user is that a stored release record was ignored,
2778
+ // in case a payment still looks stuck (Activity's manual per-row
2779
+ // Cancel remains available either way, and does not depend on this
2780
+ // queue).
2781
+ if (result.droppedUntrusted > 0) {
2782
+ setLocalPayNotification({
2783
+ message: `${t('local_pay_pending_abort_dropped_title')}. ${t('local_pay_pending_abort_dropped_body')}`,
2784
+ type: 'error'
2785
+ })
2786
+ }
2787
+ })
2788
+ // P1-3: a decline is the payee's own unverifiable claim that nothing was
2789
+ // queued (see build.ts's `watchDeclinedAbort`). Checked at the same
2790
+ // cadence as the pending-abort replay above — wallet build and every
2791
+ // reconnect — so a declined txid that reaches the chain anyway is
2792
+ // surfaced as a background notice rather than silently missed. Never
2793
+ // blocks anything: the inputs were already freed when the decline
2794
+ // was recorded.
2795
+ void verifyDeclinedAborts({
2796
+ storage,
2797
+ getStatusForTxids: async txids => {
2798
+ const services = storage.getServices() as {
2799
+ getStatusForTxids?: (txids: string[]) => Promise<{ results?: { txid: string; status: string }[] }>
2800
+ }
2801
+ if (typeof services.getStatusForTxids !== 'function') return {}
2802
+ return services.getStatusForTxids(txids)
2803
+ }
2804
+ }).then(surfaced => {
2805
+ if (surfaced.length > 0) {
2806
+ setLocalPayNotification({
2807
+ message: `${t('local_pay_decline_broadcast_title')}. ${t('local_pay_decline_broadcast_body')}`,
2808
+ type: 'error'
2809
+ })
2810
+ }
2480
2811
  })
2481
2812
 
2482
2813
  // Also run when connectivity is restored
@@ -2612,6 +2943,35 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2612
2943
  })
2613
2944
  }, [walletBuilt])
2614
2945
 
2946
+ // Monitor watchdog. A pass loop that stops — a task's await that never
2947
+ // resolves, or a throw out of runOnce's own logging — leaves every unsent
2948
+ // request at 'sending' with nothing else in the app able to broadcast it
2949
+ // (2026-09-18: two BSV sends stuck until a force-quit). No completed pass
2950
+ // for MONITOR_STALL_MS while the app is active means the loop is gone;
2951
+ // restart it on the same monitor. 2 min, not 1: a healthy pass is ~5 s
2952
+ // apart but a slow network task can legitimately hold one for a while, and
2953
+ // restarting a healthy loop is the one thing this must never do.
2954
+ useEffect(() => {
2955
+ if (!walletBuilt) return
2956
+ const check = () => {
2957
+ if (AppState.currentState !== 'active') return
2958
+ const supervisor = monitorSupervisorRef.current
2959
+ if (!supervisor || monitorRef.current === null) return
2960
+ if (!supervisor.isStalled(MONITOR_STALL_MS)) return
2961
+ const stalledForMs = Date.now() - supervisor.lastPassAt
2962
+ console.warn(`[WalletContext] monitor loop stalled for ${Math.round(stalledForMs / 1000)}s; restarting it`)
2963
+ if (supervisor.restart()) {
2964
+ // Best-effort: the stalled pass may be holding the very connection this
2965
+ // writes to. Never awaited, never allowed to throw.
2966
+ monitorRef.current
2967
+ ?.logEvent('Watchdog', `restarted monitor loop after ${Math.round(stalledForMs / 1000)}s without a pass`)
2968
+ .catch(() => {})
2969
+ }
2970
+ }
2971
+ const interval = setInterval(check, 30_000)
2972
+ return () => clearInterval(interval)
2973
+ }, [walletBuilt])
2974
+
2615
2975
  // Fetch Arcade status events when app returns to foreground
2616
2976
  useEffect(() => {
2617
2977
  const subscription = AppState.addEventListener('change', (nextAppState: AppStateStatus) => {
@@ -2619,6 +2979,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2619
2979
  const isNowForeground = nextAppState === 'active'
2620
2980
 
2621
2981
  if (wasBackground && isNowForeground) {
2982
+ // The loop's timers were frozen with the app; the gap is the OS's, not
2983
+ // the monitor's. Without this the first watchdog check after a long
2984
+ // background would restart a healthy loop.
2985
+ monitorSupervisorRef.current?.touch()
2622
2986
  const monitor = monitorRef.current
2623
2987
  if (monitor) {
2624
2988
  monitor.fetchSSEEvents().then(count => {
@@ -2687,13 +3051,23 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2687
3051
  }
2688
3052
  }, [])
2689
3053
 
2690
- const logout = useCallback(() => {
3054
+ const logout = useCallback((): Promise<boolean> => {
2691
3055
  logWithTimestamp(F, 'Logout')
2692
3056
  // Synchronous on purpose: invalidate transfer tokens and release any PIN /
2693
3057
  // hardware session before monitor or storage teardown yields.
2694
3058
  vaultStore.clearScope()
2695
3059
  vaultCeremony.cancel()
2696
- ;(async () => {
3060
+ // XR-018: a live paired RPC socket otherwise outlives logout/wallet
3061
+ // deletion — the peer would keep dispatching allowlisted BRC-100 methods
3062
+ // against a wallet the user believes they've logged out of.
3063
+ disconnectActivePairedSession()
3064
+ // The IIFE's promise IS returned (unlike the old fire-and-forget version):
3065
+ // XR-107 needs the caller to await the verified outcome of the secret
3066
+ // erasure below, not just the synchronous kickoff. This does not
3067
+ // reintroduce the yield-before-first-synchronous-step problem the old
3068
+ // comment warned about — everything above this point already ran
3069
+ // synchronously before any promise existed to await.
3070
+ return (async () => {
2697
3071
  // Tear the wallet down the same way rebuildWallet does. Logout used to
2698
3072
  // skip this, which orphaned a running monitor AND left the SQLite
2699
3073
  // connection open: a re-import of the same phrase then opened a second
@@ -2709,10 +3083,26 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2709
3083
  }
2710
3084
  offlineChaintracksRef.current = undefined
2711
3085
  headerStoreRef.current = undefined
2712
- if (storage?.db) {
3086
+ backupIdentityRef.current = null
3087
+ if (storage) {
3088
+ const dbName = storage.dbName
3089
+ if (storage.db) {
3090
+ try {
3091
+ await storage.destroy()
3092
+ } catch {}
3093
+ }
3094
+ // XQ-008: destroy() only closes the connection — it never deleted the
3095
+ // underlying .db file(s) or the walletDbRegistry entry that points at
3096
+ // them, so a "deleted" wallet's complete plaintext history stayed on
3097
+ // disk indefinitely and silently reattached with everything intact if
3098
+ // the same mnemonic was ever built again on this device. dbName is a
3099
+ // plain field that survives destroy(), so it is still readable after
3100
+ // the connection is closed.
2713
3101
  try {
2714
- await storage.destroy()
2715
- } catch {}
3102
+ await purgeRegisteredDbFiles(dbName, SQLite.deleteDatabaseAsync)
3103
+ } catch (err) {
3104
+ console.warn('[logout] failed to purge wallet db file(s)/registry', err)
3105
+ }
2716
3106
  }
2717
3107
  setStorage(null)
2718
3108
  mandalaRef.current = undefined
@@ -2735,15 +3125,46 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2735
3125
  try {
2736
3126
  const keys = await AsyncStorage.getAllKeys()
2737
3127
  const stale = keys.filter(k => k.startsWith('cached_wallet_balance_'))
3128
+ // XR-058: the legacy (pre-network-scoping) `Balance` component wrote
3129
+ // an exact, unscoped `cached_wallet_balance` key with no trailing
3130
+ // underscore, which the prefix filter above never matches. Nothing
3131
+ // reads that key any more, but an install that still carries one
3132
+ // from before the fix should have it swept here too.
3133
+ if (await AsyncStorage.getItem('cached_wallet_balance')) stale.push('cached_wallet_balance')
2738
3134
  if (stale.length > 0) await AsyncStorage.multiRemove(stale)
2739
3135
  } catch (err) {
2740
3136
  console.warn('[logout] failed to clear cached balance', err)
2741
3137
  }
2742
3138
 
3139
+ // A departed wallet's push cursor must not linger to be misread as THIS device
3140
+ // already having backed up the next wallet built here — deviceId never changes
3141
+ // across a logout/re-import on the same install (see deviceId.ts and XR-009), so an
3142
+ // unscoped Wallet Check read would otherwise inherit it. Sweeps every identity's
3143
+ // cursor, not just the one just logged out of, same as the balance-cache sweep above.
3144
+ try {
3145
+ const keys = await AsyncStorage.getAllKeys()
3146
+ const stale = keys.filter(k => k.startsWith('backupCursor-'))
3147
+ if (stale.length > 0) await AsyncStorage.multiRemove(stale)
3148
+ } catch (err) {
3149
+ console.warn('[logout] failed to clear backup cursor', err)
3150
+ }
3151
+
2743
3152
  // Awaited, and it removes the KEK along with the ciphertexts: leaving the
2744
3153
  // key behind would make the next cold start prompt for a wallet that no
2745
3154
  // longer exists. Works while locked, since deleting needs no key.
2746
- await deleteAllWalletKeys()
3155
+ //
3156
+ // XR-107: its result is real, read-back-verified evidence of whether a
3157
+ // legacy plaintext mnemonic/recoveredKey/password actually got erased —
3158
+ // not a guess. A `false` here must fail closed: skip the attestation
3159
+ // clear and the navigation below (both of which tell the rest of the
3160
+ // app "this wallet is gone") and report the failure to the caller
3161
+ // instead, so the UI can show an error and let the user retry rather
3162
+ // than silently behaving as though "Delete Wallet" fully succeeded.
3163
+ const erased = await deleteAllWalletKeys()
3164
+ if (!erased) {
3165
+ console.warn('[logout] legacy secret erasure could not be verified; not reporting Delete Wallet as complete')
3166
+ return false
3167
+ }
2747
3168
 
2748
3169
  // The attestation is per wallet. "Delete Wallet" routes here, so leaving
2749
3170
  // it behind would let the NEXT wallet on this device inherit a backup it
@@ -2759,6 +3180,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2759
3180
  const { router } = loadExpoRouter()
2760
3181
  router.dismissAll()
2761
3182
  router.replace('/')
3183
+ return true
2762
3184
  })()
2763
3185
  }, [deleteAllWalletKeys, storage])
2764
3186
 
@@ -2790,7 +3212,14 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2790
3212
  const res = await fetch(`${wocBase}/v1/bsv/${chain}/tx/${txid}/proof/bump`)
2791
3213
 
2792
3214
  if (res.ok) {
2793
- const bumpHex = (await res.text()).trim()
3215
+ // XR-059 remainder: a compromised/misbehaving configured indexer must
3216
+ // not be able to force an unbounded hex-decode here just by sending
3217
+ // back an oversized (or malformed) proof body — same guard as
3218
+ // address.ts's parseWocBeefBody / beefRepair.ts's refetchAtomicBeef.
3219
+ // An oversized/invalid proof is indistinguishable from "no usable
3220
+ // proof yet", so this fails closed to 'pending', exactly like a 404.
3221
+ const bumpHex = boundedHexResponse(await res.text(), MAX_HEX_RESPONSE_CHARS)
3222
+ if (bumpHex === undefined) return 'pending'
2794
3223
  const merklePath = MerklePath.fromHex(bumpHex)
2795
3224
  const merkleRoot = merklePath.computeRoot(txid)
2796
3225
  const ct = offlineChaintracksRef.current
@@ -2822,7 +3251,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2822
3251
  fetchRawTx: async () => {
2823
3252
  const r = await fetch(`${wocBase}/v1/bsv/${chain}/tx/${txid}/hex`)
2824
3253
  if (!r.ok) throw new Error(`raw tx fetch failed: ${r.status}`)
2825
- return Utils.toArray((await r.text()).trim(), 'hex')
3254
+ // XR-059 remainder: same unbounded-hex-decode gap as the BUMP
3255
+ // fetch above, on the raw-tx body this time. Throwing here (like
3256
+ // the !r.ok case just above) is refreshProof's existing
3257
+ // fail-closed shape for a raw-tx read it cannot trust.
3258
+ const hex = boundedHexResponse(await r.text(), MAX_HEX_RESPONSE_CHARS)
3259
+ if (hex === undefined) throw new Error('raw tx fetch: response too large or not valid hex')
3260
+ return Utils.toArray(hex, 'hex')
2826
3261
  }
2827
3262
  })
2828
3263
  setTxStatusVersion(v => v + 1)
@@ -2836,6 +3271,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2836
3271
  try {
2837
3272
  const head = await fetch(`${wocBase}/v1/bsv/${chain}/tx/hash/${txid}`)
2838
3273
  onChain = head.ok
3274
+ // XR-030: any other non-OK (429/500/401/403/...) is a service
3275
+ // problem, not proof of absence — only a 404 is authoritative.
3276
+ if (!onChain && !isChainAbsenceConfirmed(head.status)) return 'pending'
2839
3277
  } catch {
2840
3278
  // Network unreachable — we cannot prove absence, so never fail the tx.
2841
3279
  return 'pending'
@@ -2852,9 +3290,14 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2852
3290
  if (!tx || tx.status === 'failed' || tx.status === 'completed') return 'pending'
2853
3291
 
2854
3292
  // A queued/posting offline payment is expected not to be on chain yet —
2855
- // failing it would release inputs the payee still holds.
3293
+ // failing it would release inputs the payee still holds. Same for an
3294
+ // 'import_hold' row (XR-085): a raw database import quarantines a
3295
+ // copied-in queued/posting row under that status precisely because it
3296
+ // may already be broadcast/handed off, so this lookup has to see it
3297
+ // too or shouldFailUnprovenTx below never learns the row is held and
3298
+ // can fail it on a stale, in-flight tx status alone.
2856
3299
  const db = storage.sqliteDb
2857
- const rows = db ? await findOfflineActions(db, { status: ['queued', 'posting'] }) : []
3300
+ const rows = db ? await findOfflineActions(db, { status: ['queued', 'posting', 'import_hold'] }) : []
2858
3301
  const offlineStatus = rows.find(r => r.txid === txid)?.status
2859
3302
  if (
2860
3303
  shouldFailUnprovenTx({
@@ -2946,20 +3389,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2946
3389
  const db = (storage as any)?.sqliteDb
2947
3390
  if (!db?.runAsync) return 'DB not available'
2948
3391
  try {
2949
- const rows = (await db.getAllAsync(
2950
- `SELECT o.outputId AS outputId, o.satoshis AS satoshis, t.txid AS txid
2951
- FROM outputs o JOIN transactions t ON t.transactionId = o.spentBy
2952
- WHERE t.status = 'failed'`
2953
- )) as { outputId: number; satoshis: number; txid: string }[]
2954
- if (!rows || rows.length === 0) return 'No stuck reservations found.'
2955
- await db.runAsync(
2956
- `UPDATE outputs SET spentBy = NULL, spendable = 1
2957
- WHERE spentBy IN (SELECT transactionId FROM transactions WHERE status = 'failed')`
2958
- )
2959
- const detail = rows
2960
- .map(r => ` • ${r.satoshis} sat (output ${r.outputId}) ← failed ${String(r.txid).slice(0, 12)}…`)
2961
- .join('\n')
2962
- return `✓ Released ${rows.length} stuck reservation(s):\n${detail}`
3392
+ return await releaseStuckReservationsOnDb(db)
2963
3393
  } catch (e: any) {
2964
3394
  return `⚠ Release failed: ${e.message}`
2965
3395
  }
@@ -3068,21 +3498,101 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3068
3498
  continue
3069
3499
  }
3070
3500
 
3071
- spentCount++
3072
- lines.push(` SPENT: ${o.txid}:${o.vout} (${o.satoshis} sat) → by ${spendingTxid}`)
3073
- await storage.updateOutput(o.outputId, { spendable: false as any })
3501
+ // Second-source corroboration (misc-p2-01): a single WoC 200-with-txid
3502
+ // response is not enough to permanently mark a UTXO unspendable — WoC
3503
+ // can be wrong, stale, or answering for the wrong network, and this
3504
+ // path never writes spentBy, so nothing can ever restore a wrong call
3505
+ // later. Require the toolbox's own configured getUtxoStatus providers
3506
+ // to ALSO report the output as no longer a UTXO before committing.
3507
+ let utxoStatus: { status: 'success' | 'error'; isUtxo?: boolean } = { status: 'error' }
3508
+ try {
3509
+ const scriptedRows = await storage.findOutputs({ partial: { outputId: o.outputId } })
3510
+ const scripted = scriptedRows[0]
3511
+ const utxoServices = storage.getServices() as {
3512
+ hashOutputScript?: (script: string) => string
3513
+ getUtxoStatus?: (
3514
+ output: string,
3515
+ outputFormat?: string,
3516
+ outpoint?: string
3517
+ ) => Promise<{ status: 'success' | 'error'; isUtxo?: boolean }>
3518
+ }
3519
+ if (scripted?.lockingScript && utxoServices.hashOutputScript && utxoServices.getUtxoStatus) {
3520
+ const scriptHash = utxoServices.hashOutputScript(Utils.toHex(scripted.lockingScript))
3521
+ const result = await utxoServices.getUtxoStatus(scriptHash, undefined, `${o.txid}.${o.vout}`)
3522
+ utxoStatus = { status: result.status, isUtxo: result.isUtxo }
3523
+ }
3524
+ } catch {
3525
+ utxoStatus = { status: 'error' }
3526
+ }
3074
3527
 
3075
- if (!spendingTxid) continue
3528
+ const markUnspendable = shouldMarkUnspendable({
3529
+ wocProbe: probe,
3530
+ wocSpendingTxid: spendingTxid,
3531
+ utxoStatus
3532
+ })
3533
+ if (!markUnspendable) {
3534
+ console.warn(
3535
+ `[walletCheck] WoC claims ${o.txid}:${o.vout} spent by ${spendingTxid || '(no txid)'} but the second source did not corroborate — leaving spendable`
3536
+ )
3537
+ lines.push(
3538
+ ` SPENT (unconfirmed by 2nd source): ${o.txid}:${o.vout} (${o.satoshis} sat) — claimed spender ${spendingTxid || '(no txid)'}, left spendable`
3539
+ )
3540
+ continue
3541
+ }
3542
+
3543
+ // XR-031: markUnspendable only means two independent chain-service
3544
+ // oracles AGREE the output is spent — neither of them is the spending
3545
+ // transaction. Fetch and parse the alleged spender's own BEEF and
3546
+ // require it to actually consume this exact outpoint BEFORE
3547
+ // committing spendable:false; a claim that fails to fetch, fails to
3548
+ // parse, hashes to a different tx, or simply doesn't reference this
3549
+ // outpoint is left spendable rather than mutated.
3550
+ if (!spendingTxid) continue // shouldMarkUnspendable already requires this; narrows the type below.
3551
+ let spenderTx: Transaction | undefined
3076
3552
  try {
3077
3553
  const beefResp = await throttledFetch(`${wocBase}/tx/${spendingTxid}/beef`)
3078
3554
  if (!beefResp.ok) {
3079
- lines.push(` ↳ BEEF fetch failed (HTTP ${beefResp.status}), skipping change recovery`)
3555
+ lines.push(
3556
+ ` SPENT (unverified, spender BEEF fetch HTTP ${beefResp.status}): ${o.txid}:${o.vout} — left spendable`
3557
+ )
3080
3558
  continue
3081
3559
  }
3082
3560
  const beefHex = await beefResp.text()
3083
3561
  const beefBytes = Utils.toArray(beefHex, 'hex')
3084
3562
  const tx = Transaction.fromBEEF(beefBytes)
3085
- const atomicBeef = tx.toAtomicBEEF()
3563
+ const confirmed = spenderConsumesOutpoint({
3564
+ parsedTxid: tx.id('hex'),
3565
+ expectedTxid: spendingTxid,
3566
+ inputs: tx.inputs,
3567
+ outpoint: { txid: o.txid, vout: o.vout }
3568
+ })
3569
+ if (!confirmed) {
3570
+ lines.push(
3571
+ ` SPENT (unverified, spender does not reference this outpoint): ${o.txid}:${o.vout} — left spendable`
3572
+ )
3573
+ continue
3574
+ }
3575
+ spenderTx = tx
3576
+ } catch (e: any) {
3577
+ lines.push(
3578
+ ` SPENT (unverified, could not parse spender BEEF: ${e.message}): ${o.txid}:${o.vout} — left spendable`
3579
+ )
3580
+ continue
3581
+ }
3582
+
3583
+ spentCount++
3584
+ lines.push(` SPENT: ${o.txid}:${o.vout} (${o.satoshis} sat) → by ${spendingTxid}`)
3585
+ // Paper trail for a repair pass: `spendingDescription` is a free-text
3586
+ // column nothing else in this app reads or writes (unlike
3587
+ // `customInstructions`, which carries live BRC-42 derivation data
3588
+ // other flows depend on), so it is safe to repurpose as a note here.
3589
+ await storage.updateOutput(o.outputId, {
3590
+ spendable: false as any,
3591
+ spendingDescription: JSON.stringify({ claimedSpender: spendingTxid, checkedAt: new Date().toISOString() })
3592
+ } as any)
3593
+
3594
+ try {
3595
+ const atomicBeef = spenderTx.toAtomicBEEF()
3086
3596
 
3087
3597
  const changeOutputs = await storage.findOutputs({
3088
3598
  partial: { change: true as any, spendable: false as any },
@@ -3177,6 +3687,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3177
3687
  buildWalletFromRecoveredKey,
3178
3688
  backupRestore,
3179
3689
  getBackupRestore,
3690
+ getBackupPseudonym,
3691
+ getWalletBuilt,
3180
3692
  switchNetwork,
3181
3693
  rebuildWallet,
3182
3694
  storage,
@@ -3224,6 +3736,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3224
3736
  buildWalletFromRecoveredKey,
3225
3737
  backupRestore,
3226
3738
  getBackupRestore,
3739
+ getBackupPseudonym,
3740
+ getWalletBuilt,
3227
3741
  switchNetwork,
3228
3742
  rebuildWallet,
3229
3743
  storage,