@bsv/expo-wallet-toolbox 0.1.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 (240) hide show
  1. package/LICENSE.txt +28 -0
  2. package/README.md +512 -0
  3. package/assets/sounds/payment-receive.wav +0 -0
  4. package/assets/sounds/payment-send.wav +0 -0
  5. package/assets/sounds/vault-close.wav +0 -0
  6. package/assets/sounds/vault-open.wav +0 -0
  7. package/core/amountFormatHelpers.ts +330 -0
  8. package/core/backup/RemoteSyncReader.ts +94 -0
  9. package/core/backup/client.ts +111 -0
  10. package/core/backup/codec.ts +218 -0
  11. package/core/backup/constants.ts +88 -0
  12. package/core/backup/cursor.ts +138 -0
  13. package/core/backup/derive.ts +46 -0
  14. package/core/backup/deviceId.ts +33 -0
  15. package/core/backup/erase.ts +67 -0
  16. package/core/backup/preference.ts +33 -0
  17. package/core/backup/push.ts +295 -0
  18. package/core/backup/restore.ts +152 -0
  19. package/core/backup/restoreOnImport.ts +119 -0
  20. package/core/backup/status.ts +46 -0
  21. package/core/config.tsx +47 -0
  22. package/core/constants.ts +35 -0
  23. package/core/context/ExchangeRateContext.tsx +69 -0
  24. package/core/context/LocalStorageProvider.tsx +225 -0
  25. package/core/context/UserContext.tsx +129 -0
  26. package/core/context/VaultContext.tsx +79 -0
  27. package/core/context/WalletConnectionContext.tsx +454 -0
  28. package/core/context/WalletContext.tsx +2938 -0
  29. package/core/context/buildGeneration.ts +37 -0
  30. package/core/deviceTier.ts +89 -0
  31. package/core/diskSpace.ts +62 -0
  32. package/core/displayCurrencies.ts +56 -0
  33. package/core/headers/OfflineFirstChaintracks.ts +176 -0
  34. package/core/headers/checkpoints.ts +39 -0
  35. package/core/headers/fs.ts +119 -0
  36. package/core/headers/headerStore.ts +333 -0
  37. package/core/headers/prewarm.ts +36 -0
  38. package/core/headers/syncHeaders.ts +73 -0
  39. package/core/hooks/useConfirmationSound.ts +135 -0
  40. package/core/hooks/useHaptics.ts +51 -0
  41. package/core/hooks/usePermissionQueue.ts +69 -0
  42. package/core/i18n/translations.tsx +6692 -0
  43. package/core/index.ts +295 -0
  44. package/core/localpay/blePermissions.ts +32 -0
  45. package/core/localpay/build.ts +392 -0
  46. package/core/localpay/codec.ts +338 -0
  47. package/core/localpay/deviceCaps.ts +175 -0
  48. package/core/localpay/nearbyAdvisory.ts +32 -0
  49. package/core/localpay/nearbyPermissions.ts +34 -0
  50. package/core/localpay/pending.ts +385 -0
  51. package/core/localpay/pendingAborts.ts +67 -0
  52. package/core/localpay/qr.ts +16 -0
  53. package/core/localpay/session.ts +277 -0
  54. package/core/localpay/sessionPolicy.ts +5 -0
  55. package/core/localpay/transport/awdl.ts +11 -0
  56. package/core/localpay/transport/ble.ts +159 -0
  57. package/core/localpay/transport/nearby.ts +12 -0
  58. package/core/localpay/transport/race.ts +110 -0
  59. package/core/localpay/transport/select.ts +128 -0
  60. package/core/localpay/transport/socket.ts +244 -0
  61. package/core/localpay/types.ts +82 -0
  62. package/core/localpay/verify.ts +204 -0
  63. package/core/logging.config.ts +10 -0
  64. package/core/logging.ts +77 -0
  65. package/core/mnemonicWallet.ts +180 -0
  66. package/core/monitor/TaskBackupPush.ts +168 -0
  67. package/core/monitor/TaskCreditInbox.ts +116 -0
  68. package/core/monitor/TaskDrainOutbox.ts +122 -0
  69. package/core/monitor/TaskSendOffline.ts +123 -0
  70. package/core/monitor/unfailRetry.ts +116 -0
  71. package/core/net/chainMatch.ts +34 -0
  72. package/core/net/online.ts +34 -0
  73. package/core/offline/cancelParked.ts +56 -0
  74. package/core/offline/hold.ts +127 -0
  75. package/core/offline/order.ts +109 -0
  76. package/core/offline/payerHold.ts +144 -0
  77. package/core/offline/plan.ts +264 -0
  78. package/core/offline/queueGrace.ts +52 -0
  79. package/core/parsePeerPayURI.ts +119 -0
  80. package/core/pay/beefRepair.ts +106 -0
  81. package/core/pay/creditErrors.ts +46 -0
  82. package/core/pay/creditInbox.ts +202 -0
  83. package/core/pay/damagedInbox.ts +64 -0
  84. package/core/pay/proofNudge.ts +23 -0
  85. package/core/pay/provenTxFromBump.ts +31 -0
  86. package/core/pay/rails/address.ts +329 -0
  87. package/core/pay/rails/handle.ts +617 -0
  88. package/core/pay/rails/index.ts +197 -0
  89. package/core/pay/rails/nearby.ts +79 -0
  90. package/core/pay/receiveFocus.ts +13 -0
  91. package/core/pay/recordProof.ts +91 -0
  92. package/core/pay/refreshProofGuard.ts +34 -0
  93. package/core/pay/sweeper.ts +75 -0
  94. package/core/pay/tokenAmount.ts +18 -0
  95. package/core/pay/userError.ts +18 -0
  96. package/core/pay/watchlist.ts +126 -0
  97. package/core/peerpay/control.ts +122 -0
  98. package/core/peerpay/handleResendRequests.ts +475 -0
  99. package/core/peerpay/inboxAttempts.ts +33 -0
  100. package/core/peerpay/metadataDecryptor.ts +42 -0
  101. package/core/peerpay/offlineNacks.ts +96 -0
  102. package/core/peerpay/outbox.ts +209 -0
  103. package/core/peerpay/rebuildToken.ts +76 -0
  104. package/core/peerpay/resendBeef.ts +115 -0
  105. package/core/services/arcadeBroadcastProvider.ts +214 -0
  106. package/core/services/capWalletArgs.ts +99 -0
  107. package/core/services/exchangeRate.ts +63 -0
  108. package/core/services/secrets/envelope.ts +102 -0
  109. package/core/services/secrets/hkdf.ts +37 -0
  110. package/core/services/secrets/index.ts +63 -0
  111. package/core/services/secrets/kek.ts +274 -0
  112. package/core/services/secrets/migration.ts +188 -0
  113. package/core/services/secrets/policy.ts +120 -0
  114. package/core/services/secrets/storage.ts +54 -0
  115. package/core/services/secrets/store.ts +125 -0
  116. package/core/services/secrets/types.ts +85 -0
  117. package/core/services/usdFxRates.ts +101 -0
  118. package/core/services/vault/VaultKeyService.ts +312 -0
  119. package/core/services/vault/backupAttestation.ts +136 -0
  120. package/core/services/vault/ceremony.ts +972 -0
  121. package/core/services/vault/ceremonyHost.ts +46 -0
  122. package/core/services/vault/devMock.ts +22 -0
  123. package/core/services/vault/driver.ts +197 -0
  124. package/core/services/vault/guard.ts +90 -0
  125. package/core/services/vault/k1.ts +75 -0
  126. package/core/services/vault/mockYubiKey.ts +217 -0
  127. package/core/services/vault/random.ts +20 -0
  128. package/core/services/vault/sealing.ts +84 -0
  129. package/core/services/vault/session.ts +59 -0
  130. package/core/services/vault/transfers.ts +1151 -0
  131. package/core/services/vault/types.ts +109 -0
  132. package/core/services/vault/vaultDerivation.ts +152 -0
  133. package/core/services/vault/vaultPassphrase.ts +287 -0
  134. package/core/services/vault/vaultStore.ts +104 -0
  135. package/core/services/walletArgLimits.ts +234 -0
  136. package/core/services/walletServiceConfig.ts +170 -0
  137. package/core/storage/LocalStorageAdapter.ts +58 -0
  138. package/core/storage/README.md +391 -0
  139. package/core/storage/StorageExpoSQLite.ts +2008 -0
  140. package/core/storage/errors.ts +73 -0
  141. package/core/storage/index.ts +3 -0
  142. package/core/storage/methods/findSql.ts +286 -0
  143. package/core/storage/methods/historyNotes.ts +61 -0
  144. package/core/storage/methods/listActionsSql.ts +212 -0
  145. package/core/storage/methods/listOutputsSql.ts +211 -0
  146. package/core/storage/methods/offlineActions.ts +156 -0
  147. package/core/storage/methods/processOfflineActions.ts +503 -0
  148. package/core/storage/methods/reclaim.ts +135 -0
  149. package/core/storage/methods/reviewStatusSql.ts +167 -0
  150. package/core/storage/methods/unprovenWithoutReqSql.ts +26 -0
  151. package/core/storage/methods/walletBalanceSql.ts +55 -0
  152. package/core/storage/schema/createTables.ts +385 -0
  153. package/core/storage/skipQueuedAncestors.ts +29 -0
  154. package/core/storage/sqlUpdateValue.ts +12 -0
  155. package/core/stores/ConnectionStore.ts +71 -0
  156. package/core/theme/ThemeContext.tsx +182 -0
  157. package/core/theme/assertThemeContrast.ts +109 -0
  158. package/core/theme/motion.ts +50 -0
  159. package/core/theme/tokens.ts +232 -0
  160. package/core/theme/useThemeStyles.tsx +156 -0
  161. package/core/walletDbRegistry.ts +110 -0
  162. package/core/walletMonitor.ts +149 -0
  163. package/core/walletRepair/runWalletCheck.ts +195 -0
  164. package/core/walletRepair/shouldReleaseUtxo.ts +18 -0
  165. package/package.json +86 -0
  166. package/ui/backupShares.ts +367 -0
  167. package/ui/components/QRScanner.tsx +353 -0
  168. package/ui/components/pay/AddressReceive.tsx +507 -0
  169. package/ui/components/pay/AvailableBalance.tsx +61 -0
  170. package/ui/components/pay/HandleReceive.tsx +896 -0
  171. package/ui/components/pay/MessageBoxConfig.tsx +256 -0
  172. package/ui/components/pay/NearbyAdvisoryModal.tsx +111 -0
  173. package/ui/components/pay/NearbyFlow.tsx +2542 -0
  174. package/ui/components/pay/OfflineNotice.tsx +337 -0
  175. package/ui/components/pay/PayCellRow.tsx +101 -0
  176. package/ui/components/pay/PayForm.tsx +223 -0
  177. package/ui/components/pay/PaymentQrDisplay.tsx +105 -0
  178. package/ui/components/pay/PaymentSuccessOverlay.tsx +266 -0
  179. package/ui/components/pay/RecipientField.tsx +308 -0
  180. package/ui/components/pay/RequestHub.tsx +75 -0
  181. package/ui/components/pay/ResultBanner.tsx +69 -0
  182. package/ui/components/pay/UniversalSend.tsx +687 -0
  183. package/ui/components/pay/useRecipientInput.ts +270 -0
  184. package/ui/components/security/WalletLockNotice.tsx +138 -0
  185. package/ui/components/ui/AlertCard.tsx +223 -0
  186. package/ui/components/ui/AppLogo.tsx +166 -0
  187. package/ui/components/ui/BlurChrome.tsx +72 -0
  188. package/ui/components/ui/Celebration.tsx +84 -0
  189. package/ui/components/ui/ChoiceSheet.ts +69 -0
  190. package/ui/components/ui/CustomSafeArea.tsx +74 -0
  191. package/ui/components/ui/ErrorBoundary.tsx +154 -0
  192. package/ui/components/ui/GroupedList.tsx +125 -0
  193. package/ui/components/ui/IconButton.tsx +105 -0
  194. package/ui/components/ui/ListRow.tsx +197 -0
  195. package/ui/components/ui/PermissionSheet.tsx +920 -0
  196. package/ui/components/ui/PresenceRow.tsx +215 -0
  197. package/ui/components/ui/PressableScale.tsx +105 -0
  198. package/ui/components/ui/ScreenGradient.tsx +47 -0
  199. package/ui/components/ui/ScrollFade.tsx +76 -0
  200. package/ui/components/ui/Sheet.tsx +342 -0
  201. package/ui/components/ui/Toast.tsx +142 -0
  202. package/ui/components/ui/index.ts +8 -0
  203. package/ui/components/vault/EnrollWizard.tsx +627 -0
  204. package/ui/components/vault/PassphraseField.tsx +306 -0
  205. package/ui/components/vault/PhraseBackupSheet.tsx +227 -0
  206. package/ui/components/vault/VaultBackdrop.tsx +354 -0
  207. package/ui/components/vault/VaultCeremonySheet.tsx +327 -0
  208. package/ui/components/wallet/ActivityRow.tsx +408 -0
  209. package/ui/components/wallet/AmountDisplay.tsx +48 -0
  210. package/ui/components/wallet/AmountInput.tsx +256 -0
  211. package/ui/components/wallet/BackupReminderSheet.tsx +168 -0
  212. package/ui/components/wallet/Balance.tsx +144 -0
  213. package/ui/components/wallet/BiometricAdvisoryModal.tsx +133 -0
  214. package/ui/components/wallet/ImportFromBackupPrompt.tsx +93 -0
  215. package/ui/exportDatabases.ts +122 -0
  216. package/ui/exportTransactions.ts +129 -0
  217. package/ui/hooks/useOfflineNoticeActions.ts +136 -0
  218. package/ui/hooks/useOnline.ts +70 -0
  219. package/ui/hooks/useSpendableBalance.ts +58 -0
  220. package/ui/hooks/useVaultBalance.ts +50 -0
  221. package/ui/importDatabases.ts +170 -0
  222. package/ui/index.ts +136 -0
  223. package/ui/isImageUrl.ts +10 -0
  224. package/ui/printRecoveryShares.ts +93 -0
  225. package/ui/resolveIdentity.ts +125 -0
  226. package/ui/screens/ConnectionsScreen.tsx +438 -0
  227. package/ui/screens/LogsScreen.tsx +432 -0
  228. package/ui/screens/PairScreen.tsx +288 -0
  229. package/ui/screens/PayScreen.tsx +479 -0
  230. package/ui/screens/SettingsScreen.tsx +180 -0
  231. package/ui/screens/TrustScreen.tsx +831 -0
  232. package/ui/screens/VaultRecoverScreen.tsx +226 -0
  233. package/ui/screens/VaultScreen.tsx +423 -0
  234. package/ui/screens/VaultTransferScreen.tsx +293 -0
  235. package/ui/screens/WalletCheckScreen.tsx +539 -0
  236. package/ui/screens/WalletConfigScreen.tsx +1095 -0
  237. package/ui/screens/WalletHomeScreen.tsx +1597 -0
  238. package/ui/screens/homeBadges.ts +18 -0
  239. package/ui/txStatus.ts +79 -0
  240. package/ui/validateTrust.ts +44 -0
@@ -0,0 +1,2938 @@
1
+ const F = 'context/WalletContext'
2
+
3
+ import React, { useState, useEffect, createContext, useMemo, useCallback, useContext, useRef } from 'react'
4
+ import {
5
+ Wallet,
6
+ WalletPermissionsManager,
7
+ PrivilegedKeyManager,
8
+ WalletStorageManager,
9
+ WalletSigner,
10
+ PermissionRequest,
11
+ SimpleWalletManager,
12
+ Monitor
13
+ } from '@bsv/wallet-toolbox-mobile'
14
+ import { KeyDeriver, PrivateKey, MerklePath, Transaction, Utils } from '@bsv/sdk'
15
+ import { VAULT_RETENTION_MS, ceremony as vaultCeremony } from '../services/vault/ceremonyHost'
16
+ import { getVaultDriver } from '../services/vault/driver'
17
+ 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
+
24
+ /** App-level defaults: library defaults + additional certifiers */
25
+ /**
26
+ * Stop a monitor and wait (bounded) for its run loop to drain. stopTasks()
27
+ * only clears a flag the loop checks BETWEEN passes, so tearing storage down
28
+ * immediately after can close the SQLite connection under a task still inside
29
+ * runOnce — the pass rejects, and the loop's own logEvent error write rejects
30
+ * again on the closed handle. Draining first keeps teardown quiet. Bounded:
31
+ * a hung task must not wedge logout/rebuild forever.
32
+ */
33
+ async function stopMonitorAndDrain(monitor: Monitor): Promise<void> {
34
+ try {
35
+ monitor.stopTasks()
36
+ const running = (monitor as unknown as { _tasksRunningPromise?: Promise<void> })._tasksRunningPromise
37
+ if (running) {
38
+ await Promise.race([running, new Promise<void>(resolve => setTimeout(resolve, 7_000))])
39
+ }
40
+ } catch (e) {
41
+ console.warn('[WalletContext] monitor stop/drain failed:', e)
42
+ }
43
+ }
44
+
45
+ /**
46
+ * expo-router's `router` singleton is required lazily (on first call from
47
+ * logout()), rather than imported statically, because this file is
48
+ * barrel-exported from the package root — a static top-level `import` of
49
+ * expo-router pulls in its own untransformed JSX source (Navigator.js etc.),
50
+ * which Jest cannot parse for any consumer of the barrel, even one that never
51
+ * navigates. Same class of issue as hooks/useHaptics.ts's lazy expo-haptics
52
+ * require and services/vault/driver.ts's lazy native require.
53
+ */
54
+ type ExpoRouterModule = typeof import('expo-router')
55
+ let expoRouterMod: ExpoRouterModule | undefined
56
+ function loadExpoRouter(): ExpoRouterModule {
57
+ if (!expoRouterMod) {
58
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
59
+ expoRouterMod = require('expo-router') as ExpoRouterModule
60
+ }
61
+ return expoRouterMod
62
+ }
63
+
64
+ /**
65
+ * @bsv/btms-permission-module (and its @bsv/btms dependency) ship ESM-only
66
+ * `exports` maps with no `require` condition, which Jest's default CJS
67
+ * resolver cannot follow — required lazily (on first buildWallet call), same
68
+ * reason and same pattern as loadExpoRouter above, so importing this barrel
69
+ * in a test that never builds a wallet never touches either package.
70
+ */
71
+ type BtmsPermissionModule = typeof import('@bsv/btms-permission-module')
72
+ let btmsPermissionMod: BtmsPermissionModule | undefined
73
+ function loadBtmsPermissionModule(): BtmsPermissionModule {
74
+ if (!btmsPermissionMod) {
75
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
76
+ btmsPermissionMod = require('@bsv/btms-permission-module') as BtmsPermissionModule
77
+ }
78
+ return btmsPermissionMod
79
+ }
80
+
81
+ /**
82
+ * react-native-sse ships an untransformed ESM `export default`, same problem
83
+ * as expo-router/@bsv/btms-permission-module above — required lazily so it is
84
+ * only ever touched from inside buildWallet, never at barrel-import time.
85
+ * QuietEventSource itself must be built lazily too (not just the import):
86
+ * `class X extends Y` evaluates `Y` the moment the class declaration runs, so
87
+ * a top-level class extending RNEventSource would force the eager require
88
+ * right back in even with the import alone made lazy.
89
+ */
90
+ type EventSourceCtor = new (url: any, options?: any) => any
91
+ let quietEventSourceClass: EventSourceCtor | undefined
92
+ function loadQuietEventSourceClass(): EventSourceCtor {
93
+ if (!quietEventSourceClass) {
94
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
95
+ const RNEventSource = require('react-native-sse').default as EventSourceCtor
96
+ // The toolbox's ArcSSEClient constructs the EventSource with `{ debug: true }`,
97
+ // which makes react-native-sse `console.debug()` on EVERY readystate change of a
98
+ // long-lived SSE connection — a continuous flood over the Metro bridge that
99
+ // starves the JS thread and janks every interaction. Force debug off.
100
+ quietEventSourceClass = class QuietEventSource extends (RNEventSource as any) {
101
+ constructor(url: any, options: any = {}) {
102
+ super(url, { ...options, debug: false })
103
+ }
104
+ } as unknown as EventSourceCtor
105
+ }
106
+ return quietEventSourceClass
107
+ }
108
+
109
+ const DEFAULT_SETTINGS: WalletSettings = {
110
+ ...LIB_DEFAULT_SETTINGS,
111
+ trustSettings: {
112
+ ...LIB_DEFAULT_SETTINGS.trustSettings,
113
+ trustedCertifiers: [
114
+ ...LIB_DEFAULT_SETTINGS.trustSettings.trustedCertifiers,
115
+ {
116
+ name: 'Who I Am',
117
+ description: 'Certifies email, phone, and X account ownership',
118
+ iconUrl: 'https://whoiam.bsvblockchain.tech/whoiam.png',
119
+ identityKey: '02e7eeb3986273db6843b790a1595ed0ff1b2ae8f43ae2e7f1a0c9db4dd3fb9441',
120
+ trust: 5
121
+ }
122
+ ]
123
+ }
124
+ }
125
+ import type { AppChain } from '../config'
126
+ import { DEFAULT_STORAGE_URL, DEFAULT_CHAIN, ADMIN_ORIGINATOR, DEFAULT_BACKUP_URL, toWalletChain } from '../config'
127
+ import { DEFAULT_AUTO_APPROVE_THRESHOLD, AUTO_APPROVE_COOLDOWN_MS, AUTO_APPROVE_STORAGE_KEY } from '../constants'
128
+ import AsyncStorage from '@react-native-async-storage/async-storage'
129
+ import { UserContext } from './UserContext'
130
+ import { useLocalStorage } from './LocalStorageProvider'
131
+ import { usePermissionQueue } from '../hooks/usePermissionQueue'
132
+ import { createServices, chaintracksUrlFor } from '../services/walletServiceConfig'
133
+ import {
134
+ boundReviewProvenTxs,
135
+ configureNewHeaderPolling,
136
+ createWalletMonitor,
137
+ createWalletMonitorOptions
138
+ } from '../walletMonitor'
139
+ import { runBoundedUnfail } from '../monitor/unfailRetry'
140
+ import {
141
+ createArcadeBroadcastService,
142
+ createTaalBroadcastService,
143
+ createGorillaPoolBroadcastService,
144
+ createWocBroadcastService
145
+ } from '../services/arcadeBroadcastProvider'
146
+ import { getExchangeRate } from '../services/exchangeRate'
147
+ import { logWithTimestamp } from '../logging'
148
+ import { recoverMnemonicWallet } from '../mnemonicWallet'
149
+ import { StorageProvider, ChaintracksServiceClient } from '@bsv/wallet-toolbox-mobile'
150
+ import { StorageExpoSQLite } from '../storage'
151
+ import { makeBuildGeneration } from './buildGeneration'
152
+ import * as SQLite from 'expo-sqlite'
153
+ import { getRegisteredDbs, registerDb, selectLatestDb } from '../walletDbRegistry'
154
+ import { AppState, AppStateStatus, InteractionManager } from 'react-native'
155
+ import { getOnline, subscribeOnline } from '../net/online'
156
+ import { canInternalizePending, processPending } from '../localpay/pending'
157
+ import { replayPendingAborts } from '../localpay/pendingAborts'
158
+ import { TaskSendOffline } from '../monitor/TaskSendOffline'
159
+ import { TaskCreditInbox } from '../monitor/TaskCreditInbox'
160
+ import { drainUnsentEntries, TaskDrainOutbox } from '../monitor/TaskDrainOutbox'
161
+ import { TaskBackupPush } from '../monitor/TaskBackupPush'
162
+ import { pushOnce } from '../backup/push'
163
+ import { restoreOnImport } from '../backup/restoreOnImport'
164
+ import { processOfflineActions } from '../storage/methods/processOfflineActions'
165
+ import { findOfflineActions } from '../storage/methods/offlineActions'
166
+ import { shouldFailUnprovenTx } from '../pay/refreshProofGuard'
167
+ import { inputTxidsFromRawTx, shouldDeferSendWaiting } from '../storage/skipQueuedAncestors'
168
+ import { provenTxFromBump } from '../pay/provenTxFromBump'
169
+ import { recordProof } from '../pay/recordProof'
170
+ import { makeCreditClassifier } from '../pay/creditErrors'
171
+ import { creditInboxOnce, INBOX_DESCRIPTION } from '../pay/creditInbox'
172
+ import { isReceiveInboxFocused } from '../pay/receiveFocus'
173
+ import { sounds } from '../hooks/useConfirmationSound'
174
+ import i18n from '../i18n/translations'
175
+ import { makeBeefRepair } from '../pay/beefRepair'
176
+ import { shouldReleaseUtxo, type UtxoProbe } from '../walletRepair/shouldReleaseUtxo'
177
+ import {
178
+ acceptWithRetry,
179
+ DEFAULT_MESSAGE_BOX_URL,
180
+ internalizeIncoming,
181
+ LEGACY_MESSAGE_BOX_URL,
182
+ MESSAGE_BOX_URL_KEY,
183
+ NO_MESSAGE_BOX,
184
+ retryDelivery
185
+ } from '../pay/rails/handle'
186
+ import { getOutboxEntries, pruneExpiredSent, unsentEntries } from '../peerpay/outbox'
187
+ import { wocConfigFor } from '../pay/rails/address'
188
+ import { PeerPayClient } from '@bsv/message-box-client'
189
+ import { SWEEP_INTERVAL_MS, runSweep, shouldSweepNow, sweptTotal } from '../pay/sweeper'
190
+ import { formatAmount } from '../amountFormatHelpers'
191
+ import { useTranslation } from 'react-i18next'
192
+ import { HEADER_CHECKPOINTS } from '../headers/checkpoints'
193
+ import { expoHeaderFs } from '../headers/fs'
194
+ import { HeaderStore } from '../headers/headerStore'
195
+ import { OfflineFirstChaintracks } from '../headers/OfflineFirstChaintracks'
196
+ import { prewarmOwnRoots } from '../headers/prewarm'
197
+ import { syncHeaders } from '../headers/syncHeaders'
198
+ import type { HeaderSource } from '../headers/syncHeaders'
199
+
200
+ // Global, origin-agnostic rate limit for auto-approved spending.
201
+ // In-memory only — resets on app restart (intentional: more secure).
202
+ let lastAutoApproveTime = 0
203
+
204
+ // -----
205
+ // Context Types
206
+ // -----
207
+
208
+ interface ManagerState {
209
+ walletManager?: SimpleWalletManager
210
+ permissionsManager?: WalletPermissionsManager
211
+ settingsManager?: WalletSettingsManager
212
+ }
213
+
214
+ type ConfigStatus = 'editing' | 'configured' | 'initial'
215
+
216
+ /**
217
+ * Where the import-time restore has got to.
218
+ *
219
+ * 'no-backup' is a success, not a failure: the server has nothing under this seed, so the
220
+ * import continues with an empty history. 'failed' is the only phase that blocks — see
221
+ * restoreOnImport for why a half-replayed log must never be presented as a wallet.
222
+ */
223
+ export interface BackupRestoreState {
224
+ phase: 'idle' | 'checking' | 'restoring' | 'restored' | 'no-backup' | 'failed'
225
+ /** Chunks replayed so far. */
226
+ chunks: number
227
+ /** Chunks in the generation being replayed; 0 until the log index is read. */
228
+ total: number
229
+ error?: string
230
+ }
231
+
232
+ export interface WalletBuildOptions {
233
+ /**
234
+ * Replay the encrypted backup log into the fresh database before the wallet is usable.
235
+ *
236
+ * Set ONLY by the import-an-existing-wallet flows. A newly generated wallet has nothing
237
+ * to restore, and an auto-build on relaunch must not re-import over a live database.
238
+ */
239
+ restoreFromBackup?: boolean
240
+ }
241
+
242
+ export interface WalletContextValue {
243
+ // Managers:
244
+ managers: ManagerState
245
+ /** Synchronous, always-current read of managers — see getManagers's own comment. */
246
+ getManagers: () => ManagerState
247
+ // Settings
248
+ settings: WalletSettings
249
+ updateSettings: (newSettings: WalletSettings) => Promise<void>
250
+ // Logout
251
+ logout: () => void
252
+ adminOriginator: string
253
+ basketRequests: BasketAccessRequest[]
254
+ certificateRequests: CertificateAccessRequest[]
255
+ protocolRequests: ProtocolAccessRequest[]
256
+ spendingRequests: SpendingRequest[]
257
+ btmsRequests: BtmsRequest[]
258
+ advanceBasketQueue: () => void
259
+ advanceCertificateQueue: () => void
260
+ advanceProtocolQueue: () => void
261
+ advanceSpendingQueue: () => void
262
+ advanceBtmsQueue: (approved: boolean) => void
263
+ finalizeConfig: (wabConfig: WABConfig) => boolean
264
+ setConfigStatus: (status: ConfigStatus) => void
265
+ configStatus: ConfigStatus
266
+ selectedStorageUrl: string
267
+ selectedMethod: string
268
+ selectedNetwork: AppChain
269
+ buildWalletFromMnemonic: (mnemonic?: string, opts?: WalletBuildOptions) => Promise<void>
270
+ buildWalletFromRecoveredKey: (wif: string, opts?: WalletBuildOptions) => Promise<void>
271
+ /** Progress of the encrypted-log restore that runs during a wallet import. */
272
+ backupRestore: BackupRestoreState
273
+ /**
274
+ * The same value, read fresh.
275
+ *
276
+ * An import flow needs the outcome immediately after its `await` returns, where a
277
+ * captured `backupRestore` is still the pre-build render's value. This reads the ref.
278
+ */
279
+ getBackupRestore: () => BackupRestoreState
280
+ switchNetwork: (network: AppChain) => Promise<void>
281
+ /** Tear down the current wallet and re-trigger auto-build (e.g. after DB import).
282
+ * `restoreFromBackup` threads through to the auto-build's replay, for replacing
283
+ * an already-built wallet with an imported one (e.g. onboarding's backup-reminder
284
+ * "import from backup" over an auto-created wallet). */
285
+ rebuildWallet: (opts?: { restoreFromBackup?: boolean }) => Promise<void>
286
+ storage: StorageExpoSQLite | null
287
+ /** Fetch BUMP from WoC and store merkle proof, advancing tx status to completed */
288
+ refreshProof: (txid: string) => Promise<'confirmed' | 'pending' | 'failed'>
289
+ /** Peek OfflineFirstChaintracks.lastMissHeight for credit-error classification. Does not clear. */
290
+ peekLastMissHeight: () => number | undefined
291
+ /** Incremented when a transaction status changes via SSE, triggers UI refresh */
292
+ txStatusVersion: number
293
+ /** The active user's storage id, for scoping `offline_actions` reads. null if unknown. */
294
+ walletUserId: number | null
295
+ /** True while the wallet is being built (biometric auth pending, async build in progress) */
296
+ walletBuilding: boolean
297
+ /** True once the wallet has been successfully built (mnemonic/key provisioned) */
298
+ walletBuilt: boolean
299
+ /**
300
+ * Notification from background local payment processing.
301
+ * Set when pending payments are internalized in the background (e.g. on
302
+ * wallet build or when connectivity is restored). Cleared by the UI after
303
+ * display. null = no pending notification.
304
+ */
305
+ localPayNotification: { message: string; type: 'success' | 'error' | 'info' } | null
306
+ clearLocalPayNotification: () => void
307
+ /** Run a named monitor task and return its log output */
308
+ runMonitorTask: (taskName: string) => Promise<string>
309
+ /** List available monitor task names */
310
+ getMonitorTaskNames: () => string[]
311
+ /** Check spendability of all UTXOs against WoC */
312
+ checkUtxoSpendability: () => Promise<string>
313
+ releaseStuckReservations: () => Promise<string>
314
+ }
315
+
316
+ export const WalletContext = createContext<WalletContextValue>({
317
+ managers: {},
318
+ getManagers: () => ({}),
319
+ settings: DEFAULT_SETTINGS,
320
+ updateSettings: async () => {},
321
+ logout: () => {},
322
+ adminOriginator: ADMIN_ORIGINATOR,
323
+ basketRequests: [],
324
+ certificateRequests: [],
325
+ protocolRequests: [],
326
+ spendingRequests: [],
327
+ btmsRequests: [],
328
+ advanceBasketQueue: () => {},
329
+ advanceCertificateQueue: () => {},
330
+ advanceProtocolQueue: () => {},
331
+ advanceSpendingQueue: () => {},
332
+ advanceBtmsQueue: () => {},
333
+ finalizeConfig: () => false,
334
+ setConfigStatus: () => {},
335
+ configStatus: 'initial',
336
+ selectedStorageUrl: '',
337
+ selectedMethod: '',
338
+ selectedNetwork: 'main',
339
+ buildWalletFromMnemonic: async () => {},
340
+ buildWalletFromRecoveredKey: async () => {},
341
+ backupRestore: { phase: 'idle', chunks: 0, total: 0 },
342
+ getBackupRestore: () => ({ phase: 'idle', chunks: 0, total: 0 }),
343
+ switchNetwork: async () => {},
344
+ rebuildWallet: async () => {},
345
+ storage: null,
346
+ refreshProof: async () => 'pending',
347
+ peekLastMissHeight: () => undefined,
348
+ txStatusVersion: 0,
349
+ walletUserId: null,
350
+ walletBuilding: false,
351
+ walletBuilt: false,
352
+ localPayNotification: null,
353
+ clearLocalPayNotification: () => {},
354
+ runMonitorTask: async () => '',
355
+ getMonitorTaskNames: () => [],
356
+ checkUtxoSpendability: async () => '',
357
+ releaseStuckReservations: async () => ''
358
+ })
359
+
360
+ /**
361
+ * Stable sub-context carrying ONLY the rarely-changing wallet handles
362
+ * (managers, storage, adminOriginator, walletBuilding). Consumers that just
363
+ * need the manager (e.g. the Browser screen) subscribe here instead of the
364
+ * full WalletContext, whose value identity changes on every queue/tx-status/SSE
365
+ * tick — which previously re-rendered the entire Browser tree dozens of times
366
+ * per second during dApp activity.
367
+ */
368
+ export interface WalletManagersSlice {
369
+ managers: ManagerState
370
+ storage: StorageExpoSQLite | null
371
+ adminOriginator: string
372
+ walletBuilding: boolean
373
+ }
374
+ export const WalletManagersContext = createContext<WalletManagersSlice>({
375
+ managers: {},
376
+ storage: null,
377
+ adminOriginator: ADMIN_ORIGINATOR,
378
+ walletBuilding: false
379
+ })
380
+
381
+ type PermissionType = 'identity' | 'protocol' | 'renewal' | 'basket'
382
+
383
+ type BasketAccessRequest = {
384
+ requestID: string
385
+ basket?: string
386
+ originator: string
387
+ reason?: string
388
+ renewal?: boolean
389
+ }
390
+
391
+ type CertificateAccessRequest = {
392
+ requestID: string
393
+ certificate?: {
394
+ certType?: string
395
+ fields?: Record<string, any>
396
+ verifier?: string
397
+ }
398
+ originator: string
399
+ reason?: string
400
+ renewal?: boolean
401
+ }
402
+
403
+ type ProtocolAccessRequest = {
404
+ requestID: string
405
+ protocolSecurityLevel: number
406
+ protocolID: string
407
+ counterparty?: string
408
+ originator?: string
409
+ description?: string
410
+ renewal?: boolean
411
+ type?: PermissionType
412
+ }
413
+
414
+ type SpendingRequest = {
415
+ requestID: string
416
+ originator: string
417
+ description?: string
418
+ transactionAmount: number
419
+ totalPastSpending: number
420
+ amountPreviouslyAuthorized: number
421
+ authorizationAmount: number
422
+ renewal?: boolean
423
+ lineItems: any[]
424
+ }
425
+
426
+ type BtmsRequest = {
427
+ /** The originator (dApp domain) requesting BTMS token access */
428
+ originator: string
429
+ /** The raw message from BasicTokenModule (JSON-encoded promptData) */
430
+ message: string
431
+ /** Resolve the pending Promise from BasicTokenModule — true = approved */
432
+ resolve: (approved: boolean) => void
433
+ }
434
+
435
+ export interface WABConfig {
436
+ wabUrl: string
437
+ wabInfo?: any // Optional for noWAB (self-custodial) mode
438
+ method: string
439
+ network: AppChain
440
+ storageUrl: string
441
+ }
442
+
443
+ /**
444
+ * Open a legacy (no-timestamp) wallet DB and check whether it already contains
445
+ * a settings row. If so, it's a real database from a previous version. If
446
+ * not, the file was freshly created by `openDatabaseAsync` and we clean it up.
447
+ */
448
+ async function probeForLegacyDb(legacyName: string): Promise<boolean> {
449
+ let db: SQLite.SQLiteDatabase | undefined
450
+ try {
451
+ db = await SQLite.openDatabaseAsync(legacyName)
452
+ const row = await db.getFirstAsync('SELECT * FROM settings LIMIT 1')
453
+ if (row) {
454
+ // Real legacy database — close and report success
455
+ await db.closeAsync()
456
+ return true
457
+ }
458
+ // Empty / newly-created database — clean up
459
+ await db.closeAsync()
460
+ db = undefined
461
+ await SQLite.deleteDatabaseAsync(legacyName)
462
+ return false
463
+ } catch {
464
+ // Table doesn't exist → file was just created or is invalid
465
+ try {
466
+ await db?.closeAsync()
467
+ } catch {}
468
+ try {
469
+ await SQLite.deleteDatabaseAsync(legacyName)
470
+ } catch {}
471
+ return false
472
+ }
473
+ }
474
+
475
+ /**
476
+ * Minimal shape of the app's toast function. `core` must never import a `ui`
477
+ * component (see context/VaultContext.tsx's identical `VaultToast` for the
478
+ * same boundary), so WalletContextProvider takes an optional toast callback
479
+ * instead of importing one — the host app wires its own toast implementation
480
+ * (e.g. `components/ui/Toast`'s `showToast`) in via the `onToast` prop.
481
+ */
482
+ export type WalletContextToast = (message: string, opts?: { type?: 'info' | 'success' | 'error' }) => void
483
+
484
+ interface WalletContextProps {
485
+ children: React.ReactNode
486
+ onToast?: WalletContextToast
487
+ }
488
+
489
+ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children = <></>, onToast }) => {
490
+ const { t } = useTranslation()
491
+ const [managers, setManagers] = useState<ManagerState>({})
492
+ const [storage, setStorage] = useState<StorageExpoSQLite | null>(null)
493
+ /**
494
+ * Which build may publish itself. Bumped by every teardown (network switch,
495
+ * rebuild, delete); a build captures it at the start and checks it before
496
+ * handing anything to React. See core/context/buildGeneration.ts.
497
+ */
498
+ const buildGenRef = useRef(makeBuildGeneration())
499
+ const [settings, setSettings] = useState(DEFAULT_SETTINGS)
500
+ const [txStatusVersion, setTxStatusVersion] = useState(0)
501
+ // The active user's storage id, for scoping `offline_actions` reads (see
502
+ // buildWallet's getAuth() call below). null until a wallet is built, or if
503
+ // getAuth() fails — callers treat null as "unscoped" rather than a gate.
504
+ const [walletUserId, setWalletUserId] = useState<number | null>(null)
505
+ const appStateRef = useRef<AppStateStatus>(AppState.currentState)
506
+ const monitorRef = useRef<Monitor | null>(null)
507
+ // The offline-first chain tracker and the header store it wraps. Populated
508
+ // in buildWallet (tracker synchronously, store once the background open
509
+ // finishes); the reconnect top-up effect below reuses both rather than
510
+ // reopening the store from disk on every reconnect. Cleared together in
511
+ // rebuildWallet, switchNetwork, and the unmount cleanup (alongside
512
+ // monitorRef, which already follows this convention) so the two can never
513
+ // independently point at different chains — a stale pairing would let the
514
+ // reconnect effect sync one chain's store against another chain's tracker.
515
+ const offlineChaintracksRef = useRef<OfflineFirstChaintracks | undefined>(undefined)
516
+ const headerStoreRef = useRef<HeaderStore | undefined>(undefined)
517
+ /**
518
+ * "The transaction tables just changed" — one coalescing bump of
519
+ * `txStatusVersion`, which every balance and activity view keys off. A single
520
+ * user action can touch storage more than once (createAction then signAction
521
+ * for a signable transaction), and each of those should not cost its own
522
+ * round of listOutputs/listActions across three screens, so the bump lands on
523
+ * a short trailing timer instead of per call.
524
+ */
525
+ const ledgerBumpTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
526
+ const noteLedgerChanged = useCallback(() => {
527
+ if (ledgerBumpTimerRef.current) return
528
+ ledgerBumpTimerRef.current = setTimeout(() => {
529
+ ledgerBumpTimerRef.current = null
530
+ setTxStatusVersion(v => v + 1)
531
+ }, 120)
532
+ }, [])
533
+ // Serializes syncHeaders calls against a single store. The init sync and
534
+ // the reconnect top-up both target the same instance; HeaderStore.append
535
+ // checks `firstHeight === tipHeight + 1` synchronously but only advances
536
+ // tipHeight after the async fs write, so two overlapping runs can both pass
537
+ // the check and double-append the same range, corrupting the window.
538
+ const headerSyncInFlightRef = useRef(false)
539
+ const adminOriginator = ADMIN_ORIGINATOR
540
+ const [walletBuilt, setWalletBuilt] = useState<boolean>(false)
541
+ /**
542
+ * Ref twin of walletBuilt, kept in sync at every transition. The builders'
543
+ * repeat-build guard MUST read this, not the state: buildWalletFromMnemonic /
544
+ * buildWalletFromRecoveredKey are useCallbacks whose closures freeze
545
+ * walletBuilt at creation time, and stale holders (the auto-build effect,
546
+ * screens memoizing a handler) can call an old identity after a build
547
+ * succeeded — the frozen `walletBuilt=false` waves the duplicate through,
548
+ * which is how a second wallet+monitor stack gets built over a live one.
549
+ * walletBuildingRef doesn't cover this: it only serializes CONCURRENT
550
+ * builds, both builders clear it on completion.
551
+ */
552
+ const walletBuiltRef = useRef<boolean>(false)
553
+ const walletBuildingRef = useRef<boolean>(false)
554
+ const [walletBuilding, setWalletBuilding] = useState<boolean>(false)
555
+ const [backupRestore, setBackupRestoreState] = useState<BackupRestoreState>({
556
+ phase: 'idle',
557
+ chunks: 0,
558
+ total: 0
559
+ })
560
+ const backupRestoreRef = useRef<BackupRestoreState>({ phase: 'idle', chunks: 0, total: 0 })
561
+ /** Writes both the render value and the ref the import flow reads back synchronously. */
562
+ const setBackupRestore = useCallback((next: BackupRestoreState) => {
563
+ backupRestoreRef.current = next
564
+ setBackupRestoreState(next)
565
+ }, [])
566
+ const getBackupRestore = useCallback((): BackupRestoreState => backupRestoreRef.current, [])
567
+ /**
568
+ * Set by an import flow immediately before it hands the primary key over, and consumed
569
+ * (and cleared) by the buildWallet pass it triggers. A ref rather than state because
570
+ * buildWallet is invoked from SimpleWalletManager's authenticate callback, not from a
571
+ * render — a state read there would see whatever was committed, which is a race.
572
+ */
573
+ const restoreIntentRef = useRef(false)
574
+ /**
575
+ * Set by rebuildWallet right before finalizeConfig, cleared by the auto-build
576
+ * effect once it actually starts (or determines there is nothing to build).
577
+ *
578
+ * finalizeConfig only REQUESTS a rebuild — it flips configStatus, and the
579
+ * actual build runs later in the auto-build effect below, once React has
580
+ * committed that state change and run the effect. rebuildWallet's own promise
581
+ * resolves long before any of that happens, so a caller doing
582
+ * `await rebuildWallet(...)` then reading the result (managers, walletBuilt)
583
+ * sees the PRE-rebuild state, not the new wallet. This ref closes that gap:
584
+ * waitForRebuild spins until it (and walletBuildingRef) both go false, i.e.
585
+ * the auto-build effect has run to completion for this generation.
586
+ */
587
+ const pendingAutoBuildRef = useRef(false)
588
+ /**
589
+ * Poll until the auto-build effect triggered by rebuildWallet has actually
590
+ * settled (built, or determined there is nothing to build) for the given
591
+ * generation — see pendingAutoBuildRef's comment. `token` is the generation
592
+ * rebuildWallet bumped to; a later teardown (another rebuild, a network
593
+ * switch) bumps past it and this returns immediately rather than waiting on
594
+ * a build nothing still wants.
595
+ */
596
+ const waitForRebuild = useCallback(async (token: number, timeoutMs = 300000): Promise<void> => {
597
+ // A restore replays the encrypted backup log INSIDE the build, before
598
+ // walletBuiltRef flips — a large history can legitimately take minutes.
599
+ // The timeout is a safety net against a build that never settles, not a
600
+ // normal-path budget; the generation check is what actually bounds this
601
+ // to a superseded rebuild.
602
+ const start = Date.now()
603
+ while (buildGenRef.current.isCurrent(token) && Date.now() - start < timeoutMs) {
604
+ if (!pendingAutoBuildRef.current && !walletBuildingRef.current) return
605
+ await new Promise(resolve => setTimeout(resolve, 40))
606
+ }
607
+ }, [])
608
+ const [localPayNotification, setLocalPayNotification] = useState<{
609
+ message: string
610
+ type: 'success' | 'error' | 'info'
611
+ } | null>(null)
612
+ const clearLocalPayNotification = useCallback(() => setLocalPayNotification(null), [])
613
+ // Guards against overlapping background retry runs (triggered by both wallet
614
+ // build and NetInfo reconnect events)
615
+ const localPayProcessingRef = useRef<boolean>(false)
616
+ // Guards overlapping address-sweep passes. Same reason as the localpay guard
617
+ // above: a pass writes to the wallet, so two at once can race an internalize.
618
+ const addressSweepingRef = useRef<boolean>(false)
619
+ // Auto-approve: cached threshold (satoshis) and managers ref for use in callback
620
+ const autoApproveThresholdRef = useRef<number>(DEFAULT_AUTO_APPROVE_THRESHOLD)
621
+ const managersRef = useRef<ManagerState>({})
622
+ useEffect(() => {
623
+ managersRef.current = managers
624
+ }, [managers])
625
+ /**
626
+ * Synchronous read of the managers a build just produced.
627
+ *
628
+ * `managers` from render scope is stale inside the async build functions below:
629
+ * setManagers schedules a re-render, but a caller doing
630
+ * `await buildWalletFromMnemonic(...)` then reading `managers.permissionsManager`
631
+ * from its own closure sees the pre-build value, not the one the build just set.
632
+ * updateManagers keeps this ref in lockstep with every setManagers call so
633
+ * callers can read the real, current value immediately after an await.
634
+ */
635
+ const getManagers = useCallback((): ManagerState => managersRef.current, [])
636
+ const updateManagers = useCallback((updater: ManagerState | ((m: ManagerState) => ManagerState)): void => {
637
+ setManagers(m => {
638
+ const next = typeof updater === 'function' ? (updater as (m: ManagerState) => ManagerState)(m) : updater
639
+ managersRef.current = next
640
+ return next
641
+ })
642
+ }, [])
643
+
644
+ // [perf] JS-thread-stall watchdog — started at provider MOUNT (not in the
645
+ // monitor setup) so it also covers the cold-start window BEFORE the wallet
646
+ // builds. Logs whenever the JS event loop is blocked >120ms. NOTE: a native/UI
647
+ // thread freeze or an interactive auth wait (Face ID) leaves the JS thread
648
+ // idle, so the watchdog stays silent — that absence is itself a signal.
649
+ useEffect(() => {
650
+ if (!__DEV__) return
651
+ const g = globalThis as any
652
+ if (g.__jsStallWatchdog) return
653
+ g.__jsStallWatchdog = true
654
+ const TICK = 200
655
+ let last = performance.now()
656
+ const tick = () => {
657
+ const now = performance.now()
658
+ const lag = now - last - TICK
659
+ if (lag > 120) console.warn(`[perf] JS thread stalled ${lag.toFixed(0)}ms`)
660
+ last = now
661
+ g.__jsStallWatchdogTimer = setTimeout(tick, TICK)
662
+ }
663
+ g.__jsStallWatchdogTimer = setTimeout(tick, TICK)
664
+ }, [])
665
+ useEffect(() => {
666
+ AsyncStorage.getItem(AUTO_APPROVE_STORAGE_KEY).then(v => {
667
+ if (v !== null) autoApproveThresholdRef.current = Number(v) || 0
668
+ })
669
+ AsyncStorage.getItem('walletSettings').then(v => {
670
+ if (v) setSettings(prev => ({ ...prev, ...JSON.parse(v) }))
671
+ })
672
+ }, [])
673
+
674
+ const { getItem, setItem, getMnemonic, getRecoveredKey, deleteAllWalletKeys, secretsReady } = useLocalStorage()
675
+
676
+ const {
677
+ isFocused,
678
+ onFocusRequested,
679
+ onFocusRelinquished,
680
+ setBasketAccessModalOpen,
681
+ setCertificateAccessModalOpen,
682
+ setProtocolAccessModalOpen,
683
+ setSpendingAuthorizationModalOpen
684
+ } = useContext(UserContext)
685
+
686
+ const focusOpts = { isFocused, onFocusRequested, onFocusRelinquished }
687
+
688
+ const basketQueue = usePermissionQueue<BasketAccessRequest>({
689
+ ...focusOpts,
690
+ openModal: setBasketAccessModalOpen
691
+ })
692
+ const certificateQueue = usePermissionQueue<CertificateAccessRequest>({
693
+ ...focusOpts,
694
+ openModal: setCertificateAccessModalOpen
695
+ })
696
+ const protocolQueue = usePermissionQueue<ProtocolAccessRequest>({
697
+ ...focusOpts,
698
+ openModal: setProtocolAccessModalOpen
699
+ })
700
+ const spendingQueue = usePermissionQueue<SpendingRequest>({
701
+ ...focusOpts,
702
+ openModal: setSpendingAuthorizationModalOpen
703
+ })
704
+ const btmsQueue = usePermissionQueue<BtmsRequest>(focusOpts)
705
+
706
+ const advanceBtmsQueue = useCallback(
707
+ (approved: boolean) => {
708
+ btmsQueue.advance(head => head.resolve(approved))
709
+ },
710
+ [btmsQueue.advance]
711
+ )
712
+
713
+ const btmsPromptHandler = useCallback(
714
+ (originator: string, message: string): Promise<boolean> => {
715
+ return new Promise<boolean>(resolve => {
716
+ btmsQueue.enqueue({ originator, message, resolve })
717
+ })
718
+ },
719
+ [btmsQueue.enqueue]
720
+ )
721
+
722
+ const updateSettings = useCallback(
723
+ async (newSettings: WalletSettings) => {
724
+ setSettings(newSettings)
725
+ AsyncStorage.setItem('walletSettings', JSON.stringify(newSettings))
726
+ },
727
+ [managers.settingsManager]
728
+ )
729
+
730
+ const basketAccessCallback = useCallback(
731
+ (
732
+ incomingRequest: PermissionRequest & {
733
+ requestID: string
734
+ basket?: string
735
+ originator: string
736
+ reason?: string
737
+ renewal?: boolean
738
+ }
739
+ ) => {
740
+ if (incomingRequest?.requestID) {
741
+ basketQueue.enqueue({
742
+ requestID: incomingRequest.requestID,
743
+ basket: incomingRequest.basket,
744
+ originator: incomingRequest.originator,
745
+ reason: incomingRequest.reason,
746
+ renewal: incomingRequest.renewal
747
+ })
748
+ }
749
+ },
750
+ [basketQueue.enqueue]
751
+ )
752
+
753
+ const certificateAccessCallback = useCallback(
754
+ (
755
+ incomingRequest: PermissionRequest & {
756
+ requestID: string
757
+ certificate?: {
758
+ certType?: string
759
+ fields?: string[]
760
+ verifier?: string
761
+ }
762
+ originator: string
763
+ reason?: string
764
+ renewal?: boolean
765
+ }
766
+ ) => {
767
+ if (incomingRequest?.requestID) {
768
+ const certificate = incomingRequest.certificate as any
769
+ certificateQueue.enqueue({
770
+ requestID: incomingRequest.requestID,
771
+ originator: incomingRequest.originator,
772
+ verifierPublicKey: certificate?.verifier || '',
773
+ certificateType: certificate?.certType || '',
774
+ fieldsArray: certificate?.fields || [],
775
+ description: incomingRequest.reason,
776
+ renewal: incomingRequest.renewal
777
+ } as any)
778
+ }
779
+ },
780
+ [certificateQueue.enqueue]
781
+ )
782
+
783
+ const protocolPermissionCallback = useCallback(
784
+ (args: PermissionRequest & { requestID: string }): Promise<void> => {
785
+ const { requestID, counterparty, originator, reason, renewal, protocolID } = args
786
+ if (!requestID || !protocolID) return Promise.resolve()
787
+
788
+ const [protocolSecurityLevel, protocolNameString] = protocolID
789
+
790
+ let permissionType: PermissionType = 'protocol'
791
+ if (protocolNameString === 'identity resolution') permissionType = 'identity'
792
+ else if (renewal) permissionType = 'renewal'
793
+ else if (protocolNameString.includes('basket')) permissionType = 'basket'
794
+
795
+ protocolQueue.enqueue({
796
+ requestID,
797
+ protocolSecurityLevel,
798
+ protocolID: protocolNameString,
799
+ counterparty,
800
+ originator,
801
+ description: reason,
802
+ renewal,
803
+ type: permissionType
804
+ })
805
+ return Promise.resolve()
806
+ },
807
+ [protocolQueue.enqueue]
808
+ )
809
+
810
+ const spendingAuthorizationCallback = useCallback(
811
+ async (args: PermissionRequest & { requestID: string }): Promise<void> => {
812
+ const { requestID, originator, reason, renewal, spending } = args
813
+ if (!requestID || !spending) return
814
+
815
+ // Auto-approve small transactions if within threshold and cooldown.
816
+ // Read the persisted threshold fresh on every request so a change made
817
+ // in wallet-config takes effect immediately (the mount-time ref read
818
+ // alone left the old value live until app restart — felt like
819
+ // auto-approve was "stuck on").
820
+ try {
821
+ const stored = await AsyncStorage.getItem(AUTO_APPROVE_STORAGE_KEY)
822
+ if (stored !== null) autoApproveThresholdRef.current = Number(stored) || 0
823
+ } catch {}
824
+ const threshold = autoApproveThresholdRef.current
825
+ const now = Date.now()
826
+ const sinceLastMs = now - lastAutoApproveTime
827
+ // Logging gated behind __DEV__: an unconditional console.log here flushes
828
+ // over the JS↔native bridge on every spend request — i.e. on the payment
829
+ // hot path — and shows up as jank under any burst of micropayments.
830
+ if (threshold > 0 && spending.satoshis <= threshold) {
831
+ if (sinceLastMs >= AUTO_APPROVE_COOLDOWN_MS) {
832
+ lastAutoApproveTime = now
833
+ if (__DEV__) console.log(`[spend-auth] AUTO-APPROVING requestID=${requestID} sats=${spending.satoshis}`)
834
+ managersRef.current.permissionsManager?.grantPermission({
835
+ requestID,
836
+ ephemeral: true,
837
+ amount: spending.satoshis
838
+ })
839
+ return
840
+ }
841
+ if (__DEV__) console.log(`[spend-auth] cooldown blocked → manual modal requestID=${requestID}`)
842
+ } else if (__DEV__) {
843
+ console.log(
844
+ `[spend-auth] not eligible → manual modal requestID=${requestID} sats=${spending.satoshis} threshold=${threshold}`
845
+ )
846
+ }
847
+
848
+ spendingQueue.enqueue({
849
+ requestID,
850
+ originator,
851
+ description: reason,
852
+ transactionAmount: 0,
853
+ totalPastSpending: 0,
854
+ amountPreviouslyAuthorized: 0,
855
+ authorizationAmount: spending.satoshis,
856
+ renewal,
857
+ lineItems: spending.lineItems || []
858
+ })
859
+ },
860
+ [spendingQueue.enqueue]
861
+ )
862
+
863
+ // ---- WAB + network + storage configuration ----
864
+ const [selectedMethod, setSelectedMethod] = useState<string>('')
865
+ const [selectedNetwork, setSelectedNetwork] = useState<AppChain>(DEFAULT_CHAIN)
866
+ /**
867
+ * The network a build should use, readable without a closure.
868
+ *
869
+ * `buildWallet` runs inside a SimpleWalletManager callback that a render
870
+ * captured, and a build in flight when the user switches keeps the network
871
+ * that render saw: after switching back to mainnet the app rebuilt TESTNET
872
+ * and published it, leaving a mainnet label over a testnet wallet. The state
873
+ * is what the UI renders; this ref is what the build reads.
874
+ */
875
+ const selectedNetworkRef = useRef<AppChain>(DEFAULT_CHAIN)
876
+ selectedNetworkRef.current = selectedNetwork
877
+ const [selectedStorageUrl, setSelectedStorageUrl] = useState<string>(DEFAULT_STORAGE_URL)
878
+
879
+ // Flag that indicates configuration is complete. For returning users,
880
+ // if a snapshot exists we auto-mark configComplete.
881
+ const [configStatus, setConfigStatus] = useState<ConfigStatus>('initial')
882
+
883
+ const finalizeConfig = useCallback((wabConfig: WABConfig): boolean => {
884
+ const { method, network, storageUrl } = wabConfig
885
+ if (!network) {
886
+ console.error('Network selection is required')
887
+ return false
888
+ }
889
+ setSelectedMethod(method || 'mnemonic')
890
+ setSelectedNetwork(network)
891
+ setSelectedStorageUrl(storageUrl || 'local')
892
+ setConfigStatus('configured')
893
+ return true
894
+ }, [])
895
+
896
+ // Auto-configure on first launch: if no stored config, set defaults
897
+ useEffect(() => {
898
+ ;(async () => {
899
+ if (configStatus !== 'initial') return
900
+ const storedConfig = await getItem('finalConfig')
901
+ if (storedConfig) {
902
+ try {
903
+ const config = JSON.parse(storedConfig)
904
+ finalizeConfig(config)
905
+ } catch {
906
+ finalizeConfig({ wabUrl: 'noWAB', method: 'mnemonic', network: DEFAULT_CHAIN, storageUrl: 'local' })
907
+ await setItem(
908
+ 'finalConfig',
909
+ JSON.stringify({ wabUrl: 'noWAB', method: 'mnemonic', network: DEFAULT_CHAIN, storageUrl: 'local' })
910
+ )
911
+ }
912
+ } else {
913
+ // First launch: auto-configure with defaults
914
+ finalizeConfig({ wabUrl: 'noWAB', method: 'mnemonic', network: DEFAULT_CHAIN, storageUrl: 'local' })
915
+ await setItem(
916
+ 'finalConfig',
917
+ JSON.stringify({ wabUrl: 'noWAB', method: 'mnemonic', network: DEFAULT_CHAIN, storageUrl: 'local' })
918
+ )
919
+ }
920
+ })()
921
+ }, [configStatus]) // Re-run whenever configStatus resets to 'initial' (e.g. after logout)
922
+
923
+ // Shared by buildWallet's background init and the reconnect top-up effect,
924
+ // both of which sync the same store — see headerSyncInFlightRef above.
925
+ const runHeaderSync = useCallback(
926
+ async (
927
+ store: HeaderStore,
928
+ client: HeaderSource,
929
+ shouldStop?: () => boolean
930
+ ): Promise<{ added: number; tipHeight: number; presentHeight: number } | undefined> => {
931
+ if (headerSyncInFlightRef.current) return undefined
932
+ headerSyncInFlightRef.current = true
933
+ try {
934
+ return await syncHeaders({ store, client, shouldStop })
935
+ } finally {
936
+ headerSyncInFlightRef.current = false
937
+ }
938
+ },
939
+ []
940
+ )
941
+
942
+ // Build wallet function
943
+ const buildWallet = useCallback(
944
+ async (primaryKey: number[], privilegedKeyManager: PrivilegedKeyManager): Promise<any> => {
945
+ // Captured before anything is opened: everything this build publishes is
946
+ // conditional on the app still wanting THIS build by the time it gets there.
947
+ const buildToken = buildGenRef.current.current()
948
+ const stillWanted = () => buildGenRef.current.isCurrent(buildToken)
949
+ try {
950
+ logWithTimestamp(F, 'Building wallet')
951
+ const newManagers = {} as any
952
+ // Deliberately the ref, not the state: see selectedNetworkRef.
953
+ const chain = selectedNetworkRef.current
954
+ // Toolbox chain id ('teratest' -> 'ttn'). App keeps 'teratest' for AsyncStorage keys / env / UI.
955
+ const walletChain = toWalletChain(chain)
956
+ // The backup log's network name. Distinct from walletChain ('ttn' for teratest):
957
+ // the backup derivation is frozen on the app-level names.
958
+ const backupChain =
959
+ chain === 'main' ? ('main' as const) : chain === 'test' ? ('test' as const) : ('teratest' as const)
960
+ const keyDeriver = new KeyDeriver(new PrivateKey(primaryKey))
961
+ const storageManager = new WalletStorageManager(keyDeriver.identityKey)
962
+ const signer = new WalletSigner(walletChain, keyDeriver, storageManager)
963
+
964
+ const bsvExchangeRate = await getExchangeRate()
965
+ const callbackToken = keyDeriver.identityKey.substring(0, 32)
966
+
967
+ const [arcUrlOverride, arcApiTokenOverride] = await Promise.all([
968
+ AsyncStorage.getItem(`arc_custom_url_${chain}`),
969
+ AsyncStorage.getItem(`arc_custom_api_token_${chain}`)
970
+ ])
971
+
972
+ // The remote client the wrapper delegates to. Built here rather than
973
+ // inside createServiceOptions so the same instance is both the fallback
974
+ // for root misses and the source for header sync. chaintracksUrlFor is
975
+ // the single source of truth for these URLs — createServiceOptions
976
+ // calls the same function, so there is exactly one table to edit.
977
+ const remoteChaintracks = new ChaintracksServiceClient(walletChain, chaintracksUrlFor(chain))
978
+ const offlineChaintracks = new OfflineFirstChaintracks(remoteChaintracks, getOnline)
979
+ offlineChaintracksRef.current = offlineChaintracks
980
+
981
+ // Passing offlineChaintracks here does two things, and createServices
982
+ // does both so they cannot come apart: it becomes options.chaintracks
983
+ // (header sync and root misses read it), and it is installed as the
984
+ // chain tracker. Without the second, Services.getChainTracker() wraps
985
+ // options.chaintracks in ChaintracksChainTracker, whose
986
+ // isValidRootForHeight calls findHeaderForHeight rather than the
987
+ // client's own — bypassing the store-first lookup entirely and leaving
988
+ // offline verification dead with nothing to say so. See
989
+ // installOfflineChainTracker's doc comment for the full story.
990
+ const { services, serviceOptions } = createServices(
991
+ chain,
992
+ callbackToken,
993
+ bsvExchangeRate,
994
+ arcUrlOverride || undefined,
995
+ arcApiTokenOverride || undefined,
996
+ offlineChaintracks
997
+ )
998
+
999
+ // Replace all default broadcast providers with EF/rawtx-only services.
1000
+ // Order: Arcade → Taal → GorillaPool → WoC → Bitails. UntilSuccess stops at first success.
1001
+ const bitailsService = (services as any).bitails
1002
+ services.postBeefServices.remove('GorillaPoolArcBeef')
1003
+ services.postBeefServices.remove('TaalArcBeef')
1004
+ services.postBeefServices.remove('Bitails')
1005
+ services.postBeefServices.remove('WhatsOnChain')
1006
+ services.postBeefServices.add(createArcadeBroadcastService(serviceOptions.arcUrl!, callbackToken))
1007
+ const taalArcUrl =
1008
+ chain === 'main'
1009
+ ? 'https://arc.taal.com'
1010
+ : chain === 'test'
1011
+ ? 'https://arc-test.taal.com'
1012
+ : 'https://arc-teratest.taal.com'
1013
+ services.postBeefServices.add(createTaalBroadcastService(taalArcUrl, serviceOptions.taalApiKey))
1014
+ if (chain === 'main') {
1015
+ services.postBeefServices.add(createGorillaPoolBroadcastService('https://arc.gorillapool.io'))
1016
+ }
1017
+ services.postBeefServices.add(createWocBroadcastService(walletChain, serviceOptions.whatsOnChainApiKey))
1018
+ if (bitailsService) {
1019
+ services.postBeefServices.add({ name: 'Bitails', service: bitailsService.postBeef.bind(bitailsService) })
1020
+ }
1021
+
1022
+ // Replace WoC getMerklePath with BUMP endpoint — no TSC→BUMP conversion needed.
1023
+ // Remove all providers then re-add in order: WoC BUMP first, Bitails fallback.
1024
+ const wocBumpBase =
1025
+ chain === 'main'
1026
+ ? 'https://api.whatsonchain.com/v1/bsv/main'
1027
+ : chain === 'test'
1028
+ ? 'https://api.whatsonchain.com/v1/bsv/test'
1029
+ : 'https://api.woc-ttn.bsvblockchain.tech/v1/bsv/test'
1030
+ const wocApiKey = serviceOptions.whatsOnChainApiKey
1031
+ const chaintracksClient = serviceOptions.chaintracks as any
1032
+ const getMerklePathSvc = (services as any).getMerklePathServices
1033
+ const bitailsGetMerklePath = (services as any).bitails?.getMerklePath?.bind((services as any).bitails)
1034
+ getMerklePathSvc.remove('WhatsOnChain')
1035
+ getMerklePathSvc.remove('Bitails')
1036
+ getMerklePathSvc.add({
1037
+ name: 'WhatsOnChain',
1038
+ service: async (txid: string): Promise<any> => {
1039
+ const r: any = { name: 'WhatsOnChain', notes: [] }
1040
+ try {
1041
+ const headers: Record<string, string> = {}
1042
+ if (wocApiKey) headers['woc-api-key'] = wocApiKey
1043
+ const res = await fetch(`${wocBumpBase}/tx/${txid}/proof/bump`, { headers })
1044
+ if (res.status === 404) {
1045
+ r.notes.push({ what: 'getMerklePathNoData', when: new Date().toISOString() })
1046
+ return r
1047
+ }
1048
+ if (!res.ok) {
1049
+ r.notes.push({ what: 'getMerklePathBadStatus', httpStatus: res.status, when: new Date().toISOString() })
1050
+ return r
1051
+ }
1052
+ const bumpHex = (await res.text()).trim()
1053
+ r.merklePath = MerklePath.fromHex(bumpHex)
1054
+ const height = r.merklePath.blockHeight
1055
+ const header = await chaintracksClient.findHeaderForHeight(height)
1056
+ if (header) r.header = { ...header, height }
1057
+ r.notes.push({ what: 'getMerklePathSuccess', when: new Date().toISOString() })
1058
+ } catch (eu: any) {
1059
+ r.error = eu
1060
+ r.notes.push({ what: 'getMerklePathError', description: eu?.message, when: new Date().toISOString() })
1061
+ }
1062
+ return r
1063
+ }
1064
+ })
1065
+ if (bitailsGetMerklePath) {
1066
+ getMerklePathSvc.add({ name: 'Bitails', service: bitailsGetMerklePath })
1067
+ }
1068
+
1069
+ const wallet = new Wallet(signer, services, undefined, privilegedKeyManager)
1070
+
1071
+ // Every write to the transaction/output tables refreshes the money on
1072
+ // screen immediately. The monitor's onTransactionStatusChanged only
1073
+ // fires for transitions it OBSERVES (SSE events, proof checks), so a
1074
+ // payment we just signed or funds we just internalized would otherwise
1075
+ // sit behind a 30s cache TTL until the network told us about it.
1076
+ //
1077
+ // Wrapped on the Wallet itself — below the permissions manager and
1078
+ // below every originator — so one hook covers in-app payments, vault
1079
+ // transfers, and BRC-100 calls coming out of a page's WebView alike.
1080
+ for (const method of [
1081
+ 'createAction',
1082
+ 'signAction',
1083
+ 'internalizeAction',
1084
+ 'abortAction',
1085
+ 'relinquishOutput'
1086
+ ] as const) {
1087
+ const original = (wallet as any)[method]
1088
+ if (typeof original !== 'function') continue
1089
+ const bound = original.bind(wallet)
1090
+ ;(wallet as any)[method] = async (...callArgs: any[]) => {
1091
+ const result = await bound(...callArgs)
1092
+ noteLedgerChanged()
1093
+ return result
1094
+ }
1095
+ }
1096
+
1097
+ // Set default settings including "Who I Am" certifier before first get().
1098
+ // config is private in the type declarations but settable at runtime.
1099
+ ;(wallet.settingsManager as any).config = { defaultSettings: DEFAULT_SETTINGS }
1100
+ newManagers.settingsManager = wallet.settingsManager
1101
+
1102
+ // Use user-selected storage provider
1103
+ // Check if user selected local storage
1104
+ let phoneStorage: StorageExpoSQLite | undefined
1105
+ if (selectedStorageUrl === 'local') {
1106
+ console.log('[WalletContext] Using local SQLite storage')
1107
+
1108
+ const identityKey = keyDeriver.identityKey
1109
+ const keySuffix = identityKey.slice(-8)
1110
+ const chainStr = backupChain
1111
+
1112
+ // ── Select the best database file from the registry ──
1113
+ let knownDbs = await getRegisteredDbs(keySuffix, chainStr)
1114
+
1115
+ if (knownDbs.length === 0) {
1116
+ // First launch after update or fresh user.
1117
+ // Probe for a legacy (no-timestamp) database file.
1118
+ const legacyName = `wallet-${keySuffix}-${chainStr}net.db`
1119
+ const hasLegacy = await probeForLegacyDb(legacyName)
1120
+ if (hasLegacy) {
1121
+ await registerDb(keySuffix, chainStr, legacyName)
1122
+ knownDbs = [legacyName]
1123
+ console.log(`[WalletContext] Registered legacy DB: ${legacyName}`)
1124
+ } else {
1125
+ // Fresh user — create a timestamped database
1126
+ const ts = Math.floor(Date.now() / 1000)
1127
+ const newName = `wallet-${keySuffix}-${chainStr}net-${ts}.db`
1128
+ await registerDb(keySuffix, chainStr, newName)
1129
+ knownDbs = [newName]
1130
+ console.log(`[WalletContext] Created new timestamped DB: ${newName}`)
1131
+ }
1132
+ }
1133
+
1134
+ const selectedDb = selectLatestDb(knownDbs)
1135
+ console.log(`[WalletContext] Selected DB: ${selectedDb} (from ${knownDbs.length} registered)`)
1136
+
1137
+ phoneStorage = new StorageExpoSQLite({
1138
+ ...StorageProvider.createStorageBaseOptions(walletChain),
1139
+ feeModel: { model: 'sat/kb', value: 100 },
1140
+ identityKey,
1141
+ databaseName: selectedDb
1142
+ })
1143
+ phoneStorage.setServices(services)
1144
+ await phoneStorage.migrate('bsv-wallet', identityKey)
1145
+
1146
+ console.log('[WalletContext] Local SQLite storage initialized successfully')
1147
+
1148
+ // ── Import-time restore ────────────────────────────────────────────
1149
+ //
1150
+ // Deliberately HERE: the database is migrated and empty, nothing has been
1151
+ // published to the app yet, and the monitor (with its backup push task) does
1152
+ // not exist — so this device cannot have written a log of its own that the
1153
+ // restore would then pick as the newest. See utils/backup/restoreOnImport.ts.
1154
+ //
1155
+ // A failure throws, which aborts the whole build: the import screen reports it
1156
+ // and lets the user retry or continue without history. Presenting a
1157
+ // half-replayed database as a working wallet is the one outcome to avoid.
1158
+ let localStorageAdded = false
1159
+ const addLocalStorage = async () => {
1160
+ if (localStorageAdded) return
1161
+ await storageManager.addWalletStorageProvider(phoneStorage as any)
1162
+ localStorageAdded = true
1163
+ }
1164
+
1165
+ if (restoreIntentRef.current) {
1166
+ restoreIntentRef.current = false
1167
+ setBackupRestore({ phase: 'checking', chunks: 0, total: 0 })
1168
+ try {
1169
+ const restored = await restoreOnImport({
1170
+ storage: phoneStorage,
1171
+ primaryKey,
1172
+ chain: chainStr,
1173
+ identityKey,
1174
+ baseUrl: DEFAULT_BACKUP_URL,
1175
+ onProgress: (chunks, total) => setBackupRestore({ phase: 'restoring', chunks, total }),
1176
+ // reviewSpendableOutputs talks to Services through the Wallet, which
1177
+ // needs this storage attached first. Attach here (idempotent with the
1178
+ // call below) so the post-restore pass actually sees the replayed coins.
1179
+ validateRestoredCoins: async () => {
1180
+ await addLocalStorage()
1181
+ await wallet.reviewSpendableOutputs(false, true)
1182
+ }
1183
+ })
1184
+ console.log(
1185
+ `[WalletContext] backup restore · restored=${String(restored.restored)} · ` +
1186
+ `chunks=${restored.chunks} · reason=${restored.reason ?? 'none'}`
1187
+ )
1188
+ setBackupRestore(
1189
+ restored.restored
1190
+ ? { phase: 'restored', chunks: restored.chunks, total: restored.chunks }
1191
+ : { phase: 'no-backup', chunks: 0, total: 0 }
1192
+ )
1193
+ } catch (e: any) {
1194
+ const message = e instanceof Error ? e.message : String(e)
1195
+ console.error('[WalletContext] backup restore failed:', message)
1196
+ setBackupRestore({ phase: 'failed', chunks: 0, total: 0, error: message })
1197
+ throw e
1198
+ }
1199
+ }
1200
+
1201
+ // A switch landed while this build was opening its database. Publishing
1202
+ // now would put the old chain's storage under the new chain's wallet.
1203
+ if (!stillWanted()) {
1204
+ logWithTimestamp(F, 'Discarding a build the network switch overtook')
1205
+ try {
1206
+ await phoneStorage.destroy()
1207
+ } catch {}
1208
+ return null
1209
+ }
1210
+ setStorage(phoneStorage)
1211
+
1212
+ // addWalletStorageProvider calls makeAvailable internally
1213
+ try {
1214
+ await addLocalStorage()
1215
+ console.log('[WalletContext] Local storage provider added to wallet')
1216
+ } catch (error) {
1217
+ console.error('[WalletContext] Failed to add local storage provider:', error)
1218
+ }
1219
+
1220
+ try {
1221
+ const auth = await storageManager.getAuth()
1222
+ setWalletUserId(auth.userId ?? null)
1223
+ } catch {
1224
+ // Scoping is a filter, not a gate: with no id the queue reads fall
1225
+ // back to unscoped, which is today's behaviour.
1226
+ setWalletUserId(null)
1227
+ }
1228
+ }
1229
+ // TODO: Re-add remote storage support in future version
1230
+
1231
+ // Create BTMS permission module, wiring in the prompt handler so that
1232
+ // "p btms" operations surface a UI modal rather than silently denying.
1233
+ const btmsModule = loadBtmsPermissionModule().createBtmsModule({ wallet, promptHandler: btmsPromptHandler })
1234
+
1235
+ // Setup permissions with provided callbacks and BTMS module.
1236
+ const permissionsManager = new WalletPermissionsManager(wallet, adminOriginator, {
1237
+ differentiatePrivilegedOperations: true,
1238
+ seekBasketInsertionPermissions: false,
1239
+ seekBasketListingPermissions: false,
1240
+ seekBasketRemovalPermissions: false,
1241
+ seekCertificateAcquisitionPermissions: false,
1242
+ seekCertificateDisclosurePermissions: false,
1243
+ seekCertificateRelinquishmentPermissions: false,
1244
+ seekCertificateListingPermissions: false,
1245
+ seekGroupedPermission: true,
1246
+ seekPermissionsForIdentityKeyRevelation: false,
1247
+ seekPermissionsForIdentityResolution: false,
1248
+ seekPermissionsForKeyLinkageRevelation: false,
1249
+ seekPermissionsForPublicKeyRevelation: false,
1250
+ seekPermissionWhenApplyingActionLabels: false,
1251
+ seekPermissionWhenListingActionsByLabel: false,
1252
+ seekProtocolPermissionsForEncrypting: false,
1253
+ seekProtocolPermissionsForHMAC: false,
1254
+ seekProtocolPermissionsForSigning: false,
1255
+ seekSpendingPermissions: true,
1256
+ permissionModules: { btms: btmsModule }
1257
+ } as any)
1258
+
1259
+ if (protocolPermissionCallback) {
1260
+ permissionsManager.bindCallback('onProtocolPermissionRequested', protocolPermissionCallback)
1261
+ }
1262
+ if (basketAccessCallback) {
1263
+ permissionsManager.bindCallback('onBasketAccessRequested', basketAccessCallback)
1264
+ }
1265
+ if (spendingAuthorizationCallback) {
1266
+ permissionsManager.bindCallback('onSpendingAuthorizationRequested', spendingAuthorizationCallback)
1267
+ }
1268
+ if (certificateAccessCallback) {
1269
+ permissionsManager.bindCallback('onCertificateAccessRequested', certificateAccessCallback)
1270
+ }
1271
+
1272
+ newManagers.permissionsManager = permissionsManager
1273
+
1274
+ // Start background monitor for transaction status updates (sending → unproven → completed)
1275
+ try {
1276
+ // A previous build's monitor may still be running: logout resets
1277
+ // walletBuilt without tearing the wallet down the way rebuildWallet/
1278
+ // switchNetwork do, so a re-import after "Delete Wallet" reaches here
1279
+ // with monitorRef still live. Overwriting the ref without stopping it
1280
+ // orphans an unstoppable duplicate — two monitors on one SQLite file
1281
+ // was the contention behind the 2026-08-22 deposit crash (duplicate
1282
+ // Clock rows in monitor_events are its fingerprint). Belt to logout's
1283
+ // braces: this also covers any future path that resets walletBuilt.
1284
+ const staleMonitor = monitorRef.current
1285
+ if (staleMonitor) {
1286
+ monitorRef.current = null
1287
+ try {
1288
+ staleMonitor.stopTasks()
1289
+ } catch {}
1290
+ console.warn('[WalletContext] Stopped a leftover monitor from a previous wallet build')
1291
+ }
1292
+ const monitorOptions = createWalletMonitorOptions(walletChain, storageManager, services, offlineChaintracks)
1293
+ monitorOptions.callbackToken = callbackToken
1294
+ monitorOptions.EventSourceClass = loadQuietEventSourceClass()
1295
+ monitorOptions.onTransactionStatusChanged = async (_txid: string, _newStatus: string) => {
1296
+ setTxStatusVersion(v => v + 1)
1297
+ // The database moved, so the backup log has something to catch up on.
1298
+ TaskBackupPush.noteChanged()
1299
+ }
1300
+ if (phoneStorage) {
1301
+ const SSE_KEY = 'sse_last_event_id'
1302
+ monitorOptions.loadLastSSEEventId = () => phoneStorage!.getKeyValue(SSE_KEY)
1303
+ monitorOptions.saveLastSSEEventId = (id: string) => phoneStorage!.setKeyValue(SSE_KEY, id)
1304
+ }
1305
+ const monitor = await createWalletMonitor(monitorOptions)
1306
+
1307
+ // Release held offline transactions when signal returns — registered
1308
+ // BEFORE the defaults, and the order matters. Monitor.runOnce collects
1309
+ // and runs due tasks in registration order (Monitor.js:188-215, a plain
1310
+ // sequential for loop over _tasks, awaiting each), so with this
1311
+ // registered last TaskSendWaiting could post a child of a queued
1312
+ // transaction in the same pass, before the drain had posted its parent.
1313
+ // A child broadcast without its parent is refused as an orphan, which is
1314
+ // exactly what this feature's release ordering exists to prevent.
1315
+ //
1316
+ // (The old comment here claimed the last slot was wanted so the header
1317
+ // window would be topped up first. It is not needed: posting Extended
1318
+ // Format uses no headers at all.)
1319
+ //
1320
+ // Registration order is the cheap half of the ordering fix. After
1321
+ // addDefaultTasks we also patch TaskSendWaiting.processUnsent so a
1322
+ // child whose parent is still queued/posting is deferred.
1323
+ if (phoneStorage) {
1324
+ monitor.addTask(
1325
+ new TaskSendOffline(monitor, async () => {
1326
+ const r = await processOfflineActions({
1327
+ storage: phoneStorage!,
1328
+ refetchBeef: makeBeefRepair({ woc: wocConfigFor(chain), online: getOnline })
1329
+ })
1330
+ // The drain writes transaction statuses directly, below the
1331
+ // monitor's onTransactionStatusChanged callback — bump the
1332
+ // version ourselves so the transactions screen re-fetches.
1333
+ //
1334
+ // Also bump when the stall itself changes. TaskSendOffline.runTask
1335
+ // (utils/monitor/TaskSendOffline.ts) only assigns
1336
+ // `TaskSendOffline.lastStall = r.stalledOn` AFTER this lambda
1337
+ // returns, so right here `TaskSendOffline.lastStall` still holds the
1338
+ // PREVIOUS run's value — comparing against it is what lets this
1339
+ // fire on a stall appearing, changing, or clearing. Without it, a
1340
+ // pure stall (sent: 0, rejected: 0, stalledOn set — a queued row
1341
+ // whose request vanished) never bumps the version, so /pay's queue
1342
+ // effect never re-runs and the stall line never appears, even after
1343
+ // the user taps "Send now" into it.
1344
+ if (r.sent > 0 || r.rejected > 0 || r.stalledOn !== TaskSendOffline.lastStall) {
1345
+ setTxStatusVersion(v => v + 1)
1346
+ }
1347
+ return r
1348
+ })
1349
+ )
1350
+ // Rows may be sitting in offline_actions from a previous session.
1351
+ // Pessimistic: one idle drain clears it the first time we are online.
1352
+ TaskSendOffline.noteEnqueued()
1353
+
1354
+ monitor.addTask(
1355
+ new TaskCreditInbox(
1356
+ monitor,
1357
+ async () => {
1358
+ const saved = await AsyncStorage.getItem(MESSAGE_BOX_URL_KEY)
1359
+ const messageBoxUrl =
1360
+ saved === NO_MESSAGE_BOX
1361
+ ? undefined
1362
+ : !saved || saved === LEGACY_MESSAGE_BOX_URL
1363
+ ? DEFAULT_MESSAGE_BOX_URL
1364
+ : saved
1365
+ if (!messageBoxUrl) return { accepted: 0, attention: 0, pending: false }
1366
+ let client: PeerPayClient
1367
+ try {
1368
+ client = new PeerPayClient({
1369
+ messageBoxHost: messageBoxUrl,
1370
+ walletClient: permissionsManager as never,
1371
+ originator: adminOriginator
1372
+ })
1373
+ } catch {
1374
+ return { accepted: 0, attention: 0, pending: false }
1375
+ }
1376
+ const repairBeef = makeBeefRepair({ woc: wocConfigFor(chain), online: getOnline })
1377
+ const classify = await makeCreditClassifier({
1378
+ getOnline,
1379
+ peekLastMissHeight: () => offlineChaintracks.peekLastMissHeight()
1380
+ })
1381
+ const r = await creditInboxOnce({
1382
+ client,
1383
+ messageBoxUrl,
1384
+ storage: phoneStorage!,
1385
+ classify,
1386
+ accept: payment =>
1387
+ acceptWithRetry(client, messageBoxUrl, payment, INBOX_DESCRIPTION, (p, d) =>
1388
+ internalizeIncoming(permissionsManager as never, client, adminOriginator, p, d, repairBeef)
1389
+ )
1390
+ })
1391
+ return { accepted: r.accepted, attention: r.attentionCount, pending: r.pending }
1392
+ },
1393
+ Date.now,
1394
+ () => {
1395
+ if (isReceiveInboxFocused()) return
1396
+ sounds.paymentReceive()
1397
+ onToast?.(i18n.t('payment_arrived'), { type: 'success' })
1398
+ }
1399
+ )
1400
+ )
1401
+ TaskCreditInbox.noteEnqueued()
1402
+
1403
+ monitor.addTask(
1404
+ new TaskDrainOutbox(
1405
+ monitor,
1406
+ async () => {
1407
+ const entries = unsentEntries(await getOutboxEntries(phoneStorage!))
1408
+ return drainUnsentEntries({
1409
+ entries,
1410
+ retry: async entry => {
1411
+ const client = new PeerPayClient({
1412
+ messageBoxHost: entry.messageBoxUrl,
1413
+ walletClient: permissionsManager as never,
1414
+ originator: adminOriginator
1415
+ })
1416
+ await retryDelivery({
1417
+ wallet: permissionsManager as never,
1418
+ adminOriginator,
1419
+ client,
1420
+ storage: phoneStorage!,
1421
+ entry
1422
+ })
1423
+ }
1424
+ })
1425
+ },
1426
+ Date.now,
1427
+ async () => {
1428
+ await pruneExpiredSent(phoneStorage!)
1429
+ }
1430
+ )
1431
+ )
1432
+ TaskDrainOutbox.noteEnqueued()
1433
+
1434
+ // Encrypted backup log. The database is required to spend — change outputs
1435
+ // carry a random derivation suffix and BRC-29 receipts carry sender-chosen
1436
+ // derivation data, none of it on-chain and none of it recoverable from the
1437
+ // seed — so without this a user with their recovery phrase still cannot
1438
+ // restore their funds.
1439
+ //
1440
+ // Reads chunks straight from phoneStorage rather than through
1441
+ // WalletStorageManager, whose sync lock would block all storage access.
1442
+ if (DEFAULT_BACKUP_URL !== '') {
1443
+ monitor.addTask(
1444
+ new TaskBackupPush(monitor, async () => {
1445
+ return await pushOnce({
1446
+ storage: phoneStorage!,
1447
+ primaryKey,
1448
+ chain: backupChain,
1449
+ identityKey: keyDeriver.identityKey,
1450
+ baseUrl: DEFAULT_BACKUP_URL
1451
+ })
1452
+ })
1453
+ )
1454
+ // Pessimistic: one idle pass clears it if there is nothing to send.
1455
+ TaskBackupPush.noteChanged()
1456
+ }
1457
+ }
1458
+ monitor.addDefaultTasks()
1459
+
1460
+ // TaskSendWaiting calls attemptToPostReqsToNetwork as a module
1461
+ // function, so the storage hold override never sees it. Skip any req
1462
+ // whose inputs still sit in queued/posting offline_actions, and kick
1463
+ // the drain so the parent goes out first.
1464
+ if (phoneStorage) {
1465
+ const sendWaiting = monitor._tasks.find(t => t.name === 'SendWaiting') as
1466
+ | { processUnsent?: (reqApis: Array<{ rawTx?: number[] }>, indent?: number) => Promise<string> }
1467
+ | undefined
1468
+ if (sendWaiting?.processUnsent) {
1469
+ const orig = sendWaiting.processUnsent.bind(sendWaiting)
1470
+ sendWaiting.processUnsent = async (reqApis, indent) => {
1471
+ let queuedTxids = new Set<string>()
1472
+ try {
1473
+ const db = phoneStorage.sqliteDb
1474
+ if (db) {
1475
+ const rows = await findOfflineActions(db, { status: ['queued', 'posting'] })
1476
+ queuedTxids = new Set(rows.map(r => r.txid))
1477
+ }
1478
+ } catch {
1479
+ // A queue read failure must not freeze ordinary broadcasts.
1480
+ }
1481
+ const ready: typeof reqApis = []
1482
+ let deferred = 0
1483
+ for (const req of reqApis) {
1484
+ if (shouldDeferSendWaiting(inputTxidsFromRawTx(req.rawTx), queuedTxids)) deferred++
1485
+ else ready.push(req)
1486
+ }
1487
+ if (deferred > 0) TaskSendOffline.requestNow()
1488
+ if (ready.length === 0) {
1489
+ return deferred > 0 ? `deferred ${deferred} req(s) behind queued ancestors\n` : ''
1490
+ }
1491
+ return orig(ready, indent)
1492
+ }
1493
+ }
1494
+ }
1495
+
1496
+ const newHeaderTask = monitor._tasks.find((t: any) => t.name === 'NewHeader') as any
1497
+ if (newHeaderTask) {
1498
+ configureNewHeaderPolling(newHeaderTask, {
1499
+ onFailure: (error, retryAt) => {
1500
+ const message = error instanceof Error ? error.message : String(error)
1501
+ console.warn(
1502
+ `[TaskNewHeader] Chaintracks request failed; retrying after ${new Date(retryAt).toISOString()}: ${message}`
1503
+ )
1504
+ }
1505
+ })
1506
+ }
1507
+
1508
+ // Patch TaskArcadeSSE: treat REJECTED as retryable, not permanent failure.
1509
+ // Arcade returns REJECTED with 503 "no available server" for transient infra
1510
+ // errors — the default handler marks these as permanently invalid.
1511
+ const sseTask = monitor._tasks.find(t => t.name === 'ArcadeSSE') as any
1512
+ if (sseTask) {
1513
+ const origProcess = sseTask.processStatusEvent.bind(sseTask)
1514
+ sseTask.processStatusEvent = async (event: any) => {
1515
+ if (event.txStatus === 'REJECTED') {
1516
+ console.log(`[TaskArcadeSSE] REJECTED treated as retryable: txid=${event.txid}`)
1517
+ return `SSE: txid=${event.txid} status=REJECTED (ignored — retryable)\n`
1518
+ }
1519
+ // ARC emits SEEN_MULTIPLE_NODES after a tx has propagated to >1 node.
1520
+ // Library switch only knows SEEN_ON_NETWORK — normalize so req → unmined
1521
+ // and tx → unproven instead of falling through as unhandled.
1522
+ if (event.txStatus === 'SEEN_MULTIPLE_NODES') {
1523
+ return origProcess({ ...event, txStatus: 'SEEN_ON_NETWORK' })
1524
+ }
1525
+ return origProcess(event)
1526
+ }
1527
+ }
1528
+
1529
+ // TaskReviewProvenTxs is the backup audit when live reorg SSE is missing.
1530
+ // Bound it to the last 100 eligible heights so it cannot crawl from genesis.
1531
+ // getOnline() is async; trigger is sync — TaskSendOffline.onlineNow is the
1532
+ // app's single online signal (same subscribeOnline feed as the drain).
1533
+ const reviewProvenTxsTask = monitor._tasks.find((t: any) => t.name === 'ReviewProvenTxs') as any
1534
+ if (reviewProvenTxsTask) {
1535
+ boundReviewProvenTxs(reviewProvenTxsTask, { getOnline: () => TaskSendOffline.onlineNow })
1536
+ }
1537
+
1538
+ // TaskCheckForProofs.trigger() only fires when checkNow=true (set by TaskNewHeader).
1539
+ // The periodic triggerMsecs fallback is commented out in the library. Patch it back in
1540
+ // so proofs are still sought every 2h even when block header events are missed.
1541
+ const checkForProofsTask = monitor._tasks.find((t: any) => t.name === 'CheckForProofs') as any
1542
+ if (checkForProofsTask) {
1543
+ // Re-enable periodic trigger (commented out in library — only fires on checkNow otherwise).
1544
+ if (checkForProofsTask.triggerMsecs > 0) {
1545
+ const origTrigger = checkForProofsTask.trigger.bind(checkForProofsTask)
1546
+ checkForProofsTask.trigger = (nowMsecs: number) => {
1547
+ const base = origTrigger(nowMsecs)
1548
+ const elapsed = nowMsecs - checkForProofsTask.lastRunMsecsSinceEpoch
1549
+ return { run: base.run || elapsed > checkForProofsTask.triggerMsecs }
1550
+ }
1551
+ }
1552
+ // runTask exits immediately when monitor.lastNewHeader is undefined (only set by
1553
+ // TaskNewHeader on successful chaintracks response). Fall back to currentHeight().
1554
+ const origRunTask = checkForProofsTask.runTask.bind(checkForProofsTask)
1555
+ checkForProofsTask.runTask = async () => {
1556
+ if (checkForProofsTask.monitor.lastNewHeader === undefined) {
1557
+ try {
1558
+ const ct = checkForProofsTask.monitor.chaintracksWithEvents || checkForProofsTask.monitor.chaintracks
1559
+ const height = await ct.currentHeight()
1560
+ checkForProofsTask.monitor.lastNewHeader = { height }
1561
+ } catch {
1562
+ // chaintracks still down — can't proceed
1563
+ return ''
1564
+ }
1565
+ }
1566
+ return origRunTask()
1567
+ }
1568
+ logWithTimestamp(F, `CheckForProofs patched: periodic fallback + lastNewHeader bootstrap`)
1569
+ }
1570
+
1571
+ // TaskUnFail only processes 'unfail' status — nothing promotes 'invalid' → 'unfail'.
1572
+ // Patch to also process 'invalid' reqs so transactions stuck due to service failures
1573
+ // (e.g. WoC 401, chaintracks down) get retried.
1574
+ //
1575
+ // Bounded, because the first version of this was not: it took every
1576
+ // invalid req on every pass. A transaction that will never be mined —
1577
+ // one reviewStatus has already failed and released the inputs of —
1578
+ // was asked about for the rest of the wallet's life, ten minutes
1579
+ // apart, a network call each. See `selectRetryableInvalidReqs`.
1580
+ const unFailTask = monitor._tasks.find((t: any) => t.name === 'UnFail') as any
1581
+ if (unFailTask) {
1582
+ const origRunTask = unFailTask.runTask.bind(unFailTask)
1583
+ unFailTask.runTask = async () => {
1584
+ const log = await origRunTask()
1585
+ return (
1586
+ log +
1587
+ (await runBoundedUnfail({
1588
+ storage: unFailTask.storage,
1589
+ unfail: (reqs, indent) => unFailTask.unfail(reqs, indent)
1590
+ }))
1591
+ )
1592
+ }
1593
+ }
1594
+
1595
+ // ── Perf instrumentation (dev) — find which Monitor task hangs the UI ──
1596
+ // The Monitor runs all due tasks back-to-back on the JS thread every
1597
+ // ~5s with no yielding between them (Monitor.runOnce), so one task doing
1598
+ // heavy SYNCHRONOUS work freezes the UI. Wrap every task's runTask to
1599
+ // log wall-clock duration, and run a JS-thread-stall watchdog that fires
1600
+ // whenever the event loop is blocked >120ms. Cross-reference: a task
1601
+ // whose duration ~matches a stall is the synchronous-CPU culprit; a long
1602
+ // duration with NO matching stall is just slow network (non-blocking).
1603
+ if (__DEV__) {
1604
+ for (const task of monitor._tasks as any[]) {
1605
+ const taskName = task.name
1606
+ const origRun = task.runTask.bind(task)
1607
+ task.runTask = async () => {
1608
+ const start = performance.now()
1609
+ try {
1610
+ return await origRun()
1611
+ } finally {
1612
+ const ms = performance.now() - start
1613
+ if (ms > 50) console.warn(`[perf] monitor task ${taskName}: ${ms.toFixed(0)}ms (wall-clock)`)
1614
+ }
1615
+ }
1616
+ }
1617
+ // (JS-thread-stall watchdog now started at provider mount above so it
1618
+ // also covers the pre-wallet-build cold-start window.)
1619
+ }
1620
+
1621
+ // Assign the ref synchronously so foreground-resume can reach the monitor
1622
+ // immediately, but DEFER startTasks() until the current interaction/frame
1623
+ // settles. startTasks opens the ARC SSE connection + header polling + proof
1624
+ // crawls — kicking that off in the same frame as the heavy synchronous wallet
1625
+ // build and the first WebView mount piles network + JS work onto the most
1626
+ // fragile moment of cold start. Deferring it costs nothing (background sync is
1627
+ // not needed for first paint or CWI page interaction) and eases launch
1628
+ // contention that contributes to watchdog/OOM kills on real devices.
1629
+ if (!stillWanted()) {
1630
+ try {
1631
+ await stopMonitorAndDrain(monitor)
1632
+ } catch {}
1633
+ return null
1634
+ }
1635
+ monitorRef.current = monitor
1636
+ InteractionManager.runAfterInteractions(() => {
1637
+ // Re-check identity: stopTasks() before startTasks() is a no-op
1638
+ // (it only clears a flag the loop hasn't set yet), so a rebuild/
1639
+ // switchNetwork/unmount landing inside this deferral window would
1640
+ // otherwise "stop" a not-yet-started monitor and this callback
1641
+ // would then start an unstoppable zombie nothing references.
1642
+ if (monitorRef.current !== monitor) return
1643
+ // startTasks runs in background — don't await (it never resolves until stopTasks)
1644
+ monitor.startTasks().catch(e => console.error('[WalletContext] Monitor error:', e))
1645
+ })
1646
+ logWithTimestamp(F, 'Monitor scheduled (ARC SSE) after interactions')
1647
+ } catch (error: any) {
1648
+ console.warn('[WalletContext] Failed to start monitor:', error.message)
1649
+ }
1650
+
1651
+ // Header window: open, seed from our own validated proofs, then extend
1652
+ // to tip. All three steps are off the critical path — the wallet is
1653
+ // usable immediately, it just cannot verify offline until the first
1654
+ // sync finishes.
1655
+ InteractionManager.runAfterInteractions(() => {
1656
+ void (async () => {
1657
+ // InteractionManager can delay this past a subsequent
1658
+ // rebuildWallet/switchNetwork, which replaces offlineChaintracksRef
1659
+ // with a different build's (possibly different chain's) tracker.
1660
+ // Guard every mutation of the shared refs behind identity so a
1661
+ // stale init never attaches this build's store onto a tracker (or
1662
+ // a store) that belongs to a different build.
1663
+ const stillCurrent = () => offlineChaintracksRef.current === offlineChaintracks
1664
+ try {
1665
+ const anchor = HEADER_CHECKPOINTS[walletChain as 'main' | 'test' | 'ttn']
1666
+ if (!anchor) return
1667
+
1668
+ const openStart = Date.now()
1669
+ const store = await HeaderStore.open(expoHeaderFs(), walletChain, anchor)
1670
+ logWithTimestamp(F, `HeaderStore.open took ${Date.now() - openStart}ms (${store.count} headers)`)
1671
+ if (!stillCurrent()) return
1672
+ headerStoreRef.current = store
1673
+ offlineChaintracksRef.current?.setStore(store)
1674
+
1675
+ const db = phoneStorage?.sqliteDb
1676
+ if (db) {
1677
+ const rows = (await db.getAllAsync(
1678
+ 'SELECT DISTINCT height, merkleRoot FROM proven_txs WHERE height > 0'
1679
+ )) as { height: number; merkleRoot: string }[]
1680
+ const prewarmStart = Date.now()
1681
+ const warmed = await prewarmOwnRoots({ rows, store })
1682
+ logWithTimestamp(
1683
+ F,
1684
+ `prewarmOwnRoots took ${Date.now() - prewarmStart}ms, ${warmed} roots from proven_txs`
1685
+ )
1686
+ }
1687
+
1688
+ if (!stillCurrent()) return
1689
+ if (await getOnline()) {
1690
+ const r = await runHeaderSync(store, remoteChaintracks, () => !stillCurrent())
1691
+ if (r) logWithTimestamp(F, `Header sync: +${r.added} to ${r.tipHeight}/${r.presentHeight}`)
1692
+ }
1693
+ } catch (e: any) {
1694
+ console.warn('[WalletContext] header store unavailable:', e?.message)
1695
+ }
1696
+ })()
1697
+ })
1698
+
1699
+ if (!stillWanted()) {
1700
+ logWithTimestamp(F, 'Discarding a build the network switch overtook')
1701
+ return null
1702
+ }
1703
+ updateManagers(m => ({ ...m, ...newManagers }))
1704
+ logWithTimestamp(F, 'Wallet build completed successfully')
1705
+
1706
+ return permissionsManager
1707
+ } catch (error: any) {
1708
+ console.error('Error building wallet:', error)
1709
+ onToast?.('Failed to build wallet: ' + error.message, { type: 'error' })
1710
+ logWithTimestamp(F, 'Error building wallet', error.message)
1711
+ return null
1712
+ }
1713
+ },
1714
+ [
1715
+ setBackupRestore,
1716
+ selectedNetwork,
1717
+ selectedStorageUrl,
1718
+ adminOriginator,
1719
+ protocolPermissionCallback,
1720
+ basketAccessCallback,
1721
+ spendingAuthorizationCallback,
1722
+ certificateAccessCallback,
1723
+ btmsPromptHandler,
1724
+ runHeaderSync,
1725
+ noteLedgerChanged,
1726
+ onToast
1727
+ ]
1728
+ )
1729
+
1730
+ // NOTE: SimpleWalletManager snapshots are deliberately not persisted. Its
1731
+ // snapshot format prepends the encryption key to the ciphertext, so the blob
1732
+ // is plaintext-equivalent for anyone who can read it — storing one would hand
1733
+ // out the primary key and undo the biometric protection on the mnemonic.
1734
+
1735
+ // TODO: Re-add WAB (WalletAuthenticationManager) support in future version
1736
+
1737
+ /** Lets a build that finished on a stale configuration re-enter this same
1738
+ * callback, which cannot name itself inside its own definition. */
1739
+ const buildFromMnemonicRef = useRef<((m?: string, o?: WalletBuildOptions) => Promise<void>) | null>(null)
1740
+
1741
+ const buildWalletFromMnemonic = useCallback(
1742
+ async (providedMnemonic?: string, opts?: WalletBuildOptions) => {
1743
+ // Skip if wallet already built or a build is already in progress
1744
+ if (walletBuiltRef.current || walletBuildingRef.current) {
1745
+ return
1746
+ }
1747
+ const buildToken = buildGenRef.current.current()
1748
+
1749
+ // Only build if wallet is properly configured
1750
+ if (configStatus !== 'configured') {
1751
+ return
1752
+ }
1753
+
1754
+ walletBuildingRef.current = true
1755
+ setWalletBuilding(true)
1756
+
1757
+ try {
1758
+ // Use provided mnemonic directly (e.g. from mnemonic screen) or read from secure storage
1759
+ // [perf breadcrumbs] attribute the cold-start pre-build gap: getMnemonic
1760
+ // can block on Face ID / Keychain (interactive, not a JS hang), while
1761
+ // recoverMnemonicWallet runs pure-JS PBKDF2 + BIP32 EC math (JS-thread).
1762
+ const __tMnemonicStart = performance.now()
1763
+ const mnemonic = providedMnemonic || (await getMnemonic())
1764
+ if (__DEV__)
1765
+ console.warn(`[perf] getMnemonic (auth/keychain): ${(performance.now() - __tMnemonicStart).toFixed(0)}ms`)
1766
+ if (!mnemonic) {
1767
+ walletBuildingRef.current = false
1768
+ setWalletBuilding(false)
1769
+ return
1770
+ }
1771
+
1772
+ const __tRecoverStart = performance.now()
1773
+ const { rootKey, primaryKey } = recoverMnemonicWallet(mnemonic)
1774
+ if (__DEV__)
1775
+ console.warn(
1776
+ `[perf] recoverMnemonicWallet (PBKDF2+BIP32): ${(performance.now() - __tRecoverStart).toFixed(0)}ms`
1777
+ )
1778
+
1779
+ // The vault no longer routes through the PKM — the YubiKey signs vault
1780
+ // inputs directly. The toolbox still requires a privileged key manager,
1781
+ // so this returns the plain root key. guardVaultAccess is what keeps
1782
+ // non-admin originators away from it.
1783
+ const privilegedKeyManager = new PrivilegedKeyManager(async () => rootKey, VAULT_RETENTION_MS)
1784
+
1785
+ // Create SimpleWalletManager and provide keys for authentication
1786
+ const swm = new SimpleWalletManager(ADMIN_ORIGINATOR, buildWallet)
1787
+
1788
+ // Armed before the keys go in, because providing both is what triggers
1789
+ // buildWallet — the only place a fresh, empty database exists to replay into.
1790
+ restoreIntentRef.current = opts?.restoreFromBackup === true
1791
+
1792
+ // Provide the primary key and privileged key manager to authenticate the wallet
1793
+ await swm.providePrimaryKey(primaryKey)
1794
+
1795
+ await swm.providePrivilegedKeyManager(privilegedKeyManager)
1796
+
1797
+ updateManagers(m => ({
1798
+ ...m,
1799
+ walletManager: swm
1800
+ }))
1801
+ walletBuildingRef.current = false
1802
+
1803
+ // The configuration changed while this build ran, so what it produced
1804
+ // (if anything — buildWallet refuses to publish a stale build) is not
1805
+ // the wallet the app is now asking for. The request that carried the
1806
+ // new chain was refused by the in-progress guard at the top of this
1807
+ // function, so nothing else will retry: do it here.
1808
+ if (!buildGenRef.current.isCurrent(buildToken)) {
1809
+ logWithTimestamp(F, 'Configuration changed mid-build, rebuilding')
1810
+ walletBuiltRef.current = false
1811
+ setWalletBuilt(false)
1812
+ await buildFromMnemonicRef.current?.(providedMnemonic, opts)
1813
+ return
1814
+ }
1815
+
1816
+ walletBuiltRef.current = true
1817
+ setWalletBuilt(true)
1818
+ setWalletBuilding(false)
1819
+
1820
+ logWithTimestamp(F, 'Mnemonic wallet build completed')
1821
+ } catch (error: any) {
1822
+ // Never leave the intent armed: the next build on this device would otherwise be
1823
+ // an auto-build on relaunch, which must not re-import over a live database.
1824
+ restoreIntentRef.current = false
1825
+ walletBuildingRef.current = false
1826
+ setWalletBuilding(false)
1827
+ console.error('[WalletContext] Error building mnemonic wallet:', error)
1828
+ }
1829
+ },
1830
+ // walletBuilt deliberately absent: the repeat-build guard reads
1831
+ // walletBuiltRef, so the callback identity no longer needs to churn on it.
1832
+ [configStatus, getMnemonic, buildWallet]
1833
+ )
1834
+
1835
+ buildFromMnemonicRef.current = buildWalletFromMnemonic
1836
+
1837
+ // Build wallet from a recovered PrivateKey (WIF) obtained via backup share scanning
1838
+ const buildWalletFromRecoveredKey = useCallback(
1839
+ async (wif: string, opts?: WalletBuildOptions) => {
1840
+ if (walletBuiltRef.current || walletBuildingRef.current) return
1841
+ if (configStatus !== 'configured') return
1842
+
1843
+ walletBuildingRef.current = true
1844
+ setWalletBuilding(true)
1845
+ logWithTimestamp(F, 'Building wallet from recovered key')
1846
+
1847
+ try {
1848
+ const recoveredKey = PrivateKey.fromWif(wif)
1849
+ const primaryKey = recoveredKey.toArray()
1850
+
1851
+ // Same plain-root-key manager as the mnemonic path — see the comment
1852
+ // there. guardVaultAccess is what keeps non-admin originators away from it.
1853
+ const privilegedKeyManager = new PrivilegedKeyManager(async () => recoveredKey, VAULT_RETENTION_MS)
1854
+
1855
+ const swm = new SimpleWalletManager(ADMIN_ORIGINATOR, buildWallet)
1856
+
1857
+ // Same arming point as the mnemonic path — see the comment there.
1858
+ restoreIntentRef.current = opts?.restoreFromBackup === true
1859
+
1860
+ await swm.providePrimaryKey(primaryKey)
1861
+
1862
+ await swm.providePrivilegedKeyManager(privilegedKeyManager)
1863
+
1864
+ updateManagers(m => ({
1865
+ ...m,
1866
+ walletManager: swm
1867
+ }))
1868
+ walletBuiltRef.current = true
1869
+ setWalletBuilt(true)
1870
+ walletBuildingRef.current = false
1871
+ setWalletBuilding(false)
1872
+
1873
+ logWithTimestamp(F, 'Recovered key wallet build completed')
1874
+ } catch (error: any) {
1875
+ restoreIntentRef.current = false
1876
+ walletBuildingRef.current = false
1877
+ setWalletBuilding(false)
1878
+ console.error('[WalletContext] Error building wallet from recovered key:', error)
1879
+ }
1880
+ },
1881
+ // Same as buildWalletFromMnemonic: the guard reads walletBuiltRef.
1882
+ [configStatus, buildWallet]
1883
+ )
1884
+
1885
+ // Tear down the current wallet and re-trigger auto-build.
1886
+ // Used after DB import and internally by switchNetwork.
1887
+ const rebuildWallet = useCallback(async (opts?: { restoreFromBackup?: boolean }) => {
1888
+ logWithTimestamp(F, 'Rebuilding wallet')
1889
+ // Armed before teardown so the auto-build effect this triggers (via
1890
+ // finalizeConfig below) replays the backup log the same way an explicit
1891
+ // buildWalletFromMnemonic({ restoreFromBackup: true }) would.
1892
+ restoreIntentRef.current = opts?.restoreFromBackup === true
1893
+ // Any build already in flight belongs to the configuration being replaced.
1894
+ const token = buildGenRef.current.bump()
1895
+
1896
+ // Stop any running monitor and let its current pass drain before the
1897
+ // storage teardown below closes the connection under it.
1898
+ {
1899
+ const monitor = monitorRef.current
1900
+ if (monitor) {
1901
+ monitorRef.current = null
1902
+ await stopMonitorAndDrain(monitor)
1903
+ }
1904
+ }
1905
+ // Same convention as monitorRef above: clear so a stale deferred header
1906
+ // init or reconnect handler from the old build can't pair a leftover
1907
+ // store/tracker across the rebuild.
1908
+ offlineChaintracksRef.current = undefined
1909
+ headerStoreRef.current = undefined
1910
+
1911
+ // Close the current storage connection so the new build can open
1912
+ // whichever DB file the registry selects.
1913
+ if (storage?.db) {
1914
+ try {
1915
+ await storage.destroy()
1916
+ } catch {}
1917
+ }
1918
+ // And drop the handle with it. Leaving a destroyed storage in state kept
1919
+ // the screens reading the OLD chain's database until the new build
1920
+ // replaced it — which is how a testnet wallet displayed mainnet money.
1921
+ setStorage(null)
1922
+
1923
+ // Tear down current wallet state (but keep mnemonic / config)
1924
+ updateManagers({})
1925
+ walletBuiltRef.current = false
1926
+ setWalletBuilt(false)
1927
+ walletBuildingRef.current = false
1928
+ setWalletBuilding(false)
1929
+
1930
+ // Re-finalize with current config — triggers auto-build effect
1931
+ const config = { wabUrl: 'noWAB', method: 'mnemonic', network: selectedNetwork, storageUrl: 'local' }
1932
+ pendingAutoBuildRef.current = true
1933
+ finalizeConfig(config)
1934
+ logWithTimestamp(F, 'Wallet rebuild triggered')
1935
+ // finalizeConfig above only requests the rebuild; without this,
1936
+ // rebuildWallet's promise resolved before the auto-build effect had even
1937
+ // run, so `await rebuildWallet(...)` callers (e.g. the import screens
1938
+ // replacing an auto-created wallet) saw pre-rebuild managers and a
1939
+ // pre-rebuild walletBuilt — silently skipping anything gated on the new
1940
+ // wallet actually existing, such as recording a backup attestation.
1941
+ await waitForRebuild(token)
1942
+ }, [selectedNetwork, storage, finalizeConfig, waitForRebuild])
1943
+
1944
+ // Switch network: tear down wallet, update config, and rebuild on new chain
1945
+ const switchNetwork = useCallback(
1946
+ async (network: AppChain) => {
1947
+ if (network === selectedNetwork) return
1948
+ logWithTimestamp(F, `Switching network from ${selectedNetwork} to ${network}`)
1949
+ buildGenRef.current.bump()
1950
+
1951
+ // Stop any running monitor and let its current pass drain before the
1952
+ // storage teardown below closes the connection under it.
1953
+ {
1954
+ const monitor = monitorRef.current
1955
+ if (monitor) {
1956
+ monitorRef.current = null
1957
+ await stopMonitorAndDrain(monitor)
1958
+ }
1959
+ }
1960
+ // Same convention as monitorRef above: clear so the old chain's
1961
+ // tracker/store can't linger and get paired against the new chain.
1962
+ offlineChaintracksRef.current = undefined
1963
+ headerStoreRef.current = undefined
1964
+
1965
+ // Close the current storage connection
1966
+ if (storage?.db) {
1967
+ try {
1968
+ await storage.destroy()
1969
+ } catch {}
1970
+ }
1971
+ setStorage(null)
1972
+
1973
+ // Tear down current wallet state (but keep mnemonic)
1974
+ updateManagers({})
1975
+ walletBuiltRef.current = false
1976
+ setWalletBuilt(false)
1977
+ walletBuildingRef.current = false
1978
+ setWalletBuilding(false)
1979
+
1980
+ // Persist new config
1981
+ const newConfig = { wabUrl: 'noWAB', method: 'mnemonic', network, storageUrl: 'local' }
1982
+ await setItem('finalConfig', JSON.stringify(newConfig))
1983
+
1984
+ // Re-finalize with new network — this triggers the auto-build effect
1985
+ finalizeConfig(newConfig)
1986
+ logWithTimestamp(F, `Network switched to ${network}`)
1987
+ },
1988
+ [selectedNetwork, setItem, storage, finalizeConfig]
1989
+ )
1990
+
1991
+ // Auto-build wallet for returning users (mnemonic first, then recovered key).
1992
+ // Sets walletBuilding=true eagerly so other parts of the app (index.tsx
1993
+ // navigation) know not to react as if no wallet exists.
1994
+ useEffect(() => {
1995
+ if (configStatus !== 'configured' || walletBuilt) return
1996
+ // Signal that a build attempt is starting. buildWalletFromMnemonic /
1997
+ // buildWalletFromRecoveredKey will clear this flag on completion or error.
1998
+ // Set before the secretsReady gate below, so the migration window is not
1999
+ // mistaken by the rest of the app for "this user has no wallet".
2000
+ setWalletBuilding(true)
2001
+ // Wait for the legacy-secret migration to settle. Reading a secret before
2002
+ // it does would report "no wallet" to an existing user on the first launch
2003
+ // after upgrading, and this effect would not re-fire to correct it.
2004
+ if (!secretsReady) return
2005
+ // From here the build actually starts (buildWalletFromMnemonic below sets
2006
+ // walletBuildingRef synchronously, in this same tick) — waitForRebuild can
2007
+ // stop treating this generation as "not yet started".
2008
+ pendingAutoBuildRef.current = false
2009
+ ;(async () => {
2010
+ // Try mnemonic-based build first (calls getMnemonic internally)
2011
+ await buildWalletFromMnemonic()
2012
+ // If still not built (no mnemonic), try recovered key. walletBuiltRef is
2013
+ // the reliable signal here — this closure's walletBuilt is frozen at
2014
+ // false, and the old `!walletBuildingRef.current` check was wrong twice
2015
+ // over: it reads false after a SUCCESSFUL build too (both builders clear
2016
+ // it on completion), so a wallet holding both a mnemonic and a leftover
2017
+ // recoveredKey would build TWICE — two wallet stacks, two monitors.
2018
+ if (!walletBuiltRef.current && !walletBuildingRef.current) {
2019
+ // buildWalletFromMnemonic finished without building (no mnemonic found).
2020
+ // Try recovered key as a fallback.
2021
+ const recoveredWif = await getRecoveredKey()
2022
+ if (recoveredWif) {
2023
+ await buildWalletFromRecoveredKey(recoveredWif)
2024
+ } else {
2025
+ // No mnemonic and no recovered key — genuinely no wallet to build
2026
+ setWalletBuilding(false)
2027
+ }
2028
+ }
2029
+ })()
2030
+ }, [configStatus, walletBuilt, secretsReady, buildWalletFromMnemonic, buildWalletFromRecoveredKey, getRecoveredKey])
2031
+
2032
+ // Settings are AsyncStorage-only — no on-chain sync needed
2033
+
2034
+ // ── Background local payment pending-queue processing ──
2035
+ // After wallet build completes, attempt to internalize any local payments
2036
+ // that were received while offline. A NetInfo listener then re-triggers
2037
+ // whenever the device comes back online so the queue drains automatically.
2038
+ useEffect(() => {
2039
+ if (!walletBuilt || !managers.permissionsManager || !storage) return
2040
+
2041
+ const tryProcess = async () => {
2042
+ // Two triggers (wallet build + reconnect) can fire close together;
2043
+ // processPending mutates a shared queue, so only let one run at a time.
2044
+ if (localPayProcessingRef.current) return
2045
+ localPayProcessingRef.current = true
2046
+ try {
2047
+ let online = false
2048
+ try {
2049
+ online = await getOnline()
2050
+ } catch {
2051
+ online = false
2052
+ }
2053
+ if (!canInternalizePending(online)) return
2054
+ const results = await processPending(managers.permissionsManager as any, storage, adminOriginator)
2055
+ const successes = results.filter(r => r.success)
2056
+ if (successes.length > 0) {
2057
+ // The activity list and balance re-read on this version; without it
2058
+ // a payment credited here stayed invisible until a manual refresh.
2059
+ setTxStatusVersion(v => v + 1)
2060
+ setLocalPayNotification({
2061
+ message:
2062
+ successes.length === 1
2063
+ ? t('local_pay_added')
2064
+ : t('local_pay_added_multiple', { count: successes.length }),
2065
+ type: 'success'
2066
+ })
2067
+ }
2068
+ } catch {
2069
+ // Best-effort — failures are recorded per-entry in the queue
2070
+ } finally {
2071
+ localPayProcessingRef.current = false
2072
+ }
2073
+ }
2074
+
2075
+ // Run immediately after wallet build
2076
+ tryProcess()
2077
+ void replayPendingAborts({
2078
+ wallet: managers.permissionsManager as {
2079
+ abortAction: (args: { reference: string }, originator?: string) => Promise<{ aborted?: boolean } | void>
2080
+ },
2081
+ storage
2082
+ })
2083
+
2084
+ // Also run when connectivity is restored
2085
+ const unsubscribe = subscribeOnline(online => {
2086
+ if (online) tryProcess()
2087
+ })
2088
+
2089
+ return () => unsubscribe()
2090
+ }, [walletBuilt, managers.permissionsManager, storage, adminOriginator, t])
2091
+
2092
+ // ── Background legacy-address sweep ──
2093
+ // "Get paid → a conventional wallet" is: show the address, and money appears.
2094
+ // The user never has to return to a screen, so the poll cannot live in one.
2095
+ // Bounds live in utils/pay/watchlist.ts (which addresses are eligible) and
2096
+ // utils/pay/sweeper.ts (when a pass may run at all).
2097
+ useEffect(() => {
2098
+ const wallet = managers.permissionsManager
2099
+ if (!walletBuilt || !wallet || !storage) return
2100
+
2101
+ let cancelled = false
2102
+ // Assume online until NetInfo says otherwise: a first pass that fails on a
2103
+ // dead network is harmless (every address stays watched), while waiting for
2104
+ // the first NetInfo event would delay the common case.
2105
+ let online = true
2106
+ const woc = wocConfigFor(selectedNetwork)
2107
+
2108
+ const tick = async () => {
2109
+ if (cancelled) return
2110
+ if (
2111
+ !shouldSweepNow({
2112
+ walletBuilt: true,
2113
+ appActive: AppState.currentState === 'active',
2114
+ online,
2115
+ inFlight: addressSweepingRef.current
2116
+ })
2117
+ ) {
2118
+ return
2119
+ }
2120
+ addressSweepingRef.current = true
2121
+ try {
2122
+ const outcomes = await runSweep({
2123
+ wallet: wallet as any,
2124
+ storage: storage as any,
2125
+ adminOriginator,
2126
+ woc
2127
+ })
2128
+ const total = sweptTotal(outcomes)
2129
+ if (total > 0 && !cancelled) {
2130
+ // The internalizeAction inside the sweep IS the inbound history entry
2131
+ // (labels: legacy, inbound, …), so a toast is all that is left to do.
2132
+ // Formatted in BSV deliberately: formatAmount divides by
2133
+ // satoshisPerUSD for a USD display, and this context has no exchange
2134
+ // rate — sats are always correct, a fiat figure computed from a zero
2135
+ // rate is not.
2136
+ setLocalPayNotification({
2137
+ message: t('pay_address_swept', { amount: formatAmount(total, 'BSV') }),
2138
+ type: 'success'
2139
+ })
2140
+ }
2141
+ } catch {
2142
+ // Best-effort. Every address stays watched and the next tick retries.
2143
+ } finally {
2144
+ addressSweepingRef.current = false
2145
+ }
2146
+ }
2147
+
2148
+ const netUnsubscribe = subscribeOnline(next => {
2149
+ online = next
2150
+ // Coming back online is worth a pass now rather than at the next tick.
2151
+ if (online) void tick()
2152
+ })
2153
+ const appSubscription = AppState.addEventListener('change', next => {
2154
+ if (next === 'active') void tick()
2155
+ })
2156
+ const interval = setInterval(() => void tick(), SWEEP_INTERVAL_MS)
2157
+ void tick()
2158
+
2159
+ return () => {
2160
+ cancelled = true
2161
+ clearInterval(interval)
2162
+ netUnsubscribe()
2163
+ appSubscription.remove()
2164
+ }
2165
+ }, [walletBuilt, managers.permissionsManager, storage, adminOriginator, selectedNetwork, t])
2166
+
2167
+ // Top the header window up whenever signal returns, so the next time we go
2168
+ // underground the window already reaches the tip.
2169
+ //
2170
+ // Reuses the HeaderStore instance already opened by buildWallet's background
2171
+ // init (held in headerStoreRef) instead of calling HeaderStore.open again.
2172
+ // Re-opening on every reconnect would re-scan the whole .bin file and rebuild
2173
+ // the in-memory roots array from scratch on the JS thread each time — for a
2174
+ // year of mainnet headers that's the same ~52,000-iteration cost the initial
2175
+ // open pays, and NetInfo can fire "online" repeatedly (wifi↔cellular
2176
+ // handoffs) without ever having gone offline. If the background init hasn't
2177
+ // populated the ref yet, this pass is skipped — the init's own online check
2178
+ // covers that case, and the next reconnect retries.
2179
+ //
2180
+ // The chain check is defense in depth: offlineChaintracksRef/headerStoreRef
2181
+ // are cleared together in rebuildWallet, switchNetwork, and the unmount
2182
+ // cleanup, and the background init only pairs them under an identity guard,
2183
+ // so the two should never point at different chains — but this effect reads
2184
+ // both refs fresh on every reconnect, independent of that init's own
2185
+ // guarding, so it re-validates the pairing itself before syncing rather than
2186
+ // trusting it was never broken.
2187
+ useEffect(() => {
2188
+ if (!walletBuilt) return
2189
+ return subscribeOnline(online => {
2190
+ if (!online) return
2191
+ const ct = offlineChaintracksRef.current
2192
+ const store = headerStoreRef.current
2193
+ if (!ct || !store) return
2194
+ if (store.chain !== toWalletChain(selectedNetwork)) return
2195
+ void (async () => {
2196
+ try {
2197
+ await runHeaderSync(store, ct)
2198
+ } catch {
2199
+ // Best-effort. The next reconnect retries.
2200
+ }
2201
+ })()
2202
+ })
2203
+ }, [walletBuilt, selectedNetwork, runHeaderSync])
2204
+
2205
+ // Feed the drain's and the backup push's online gates, arming an immediate pass on
2206
+ // reconnect. Both are gated on the app's single online signal.
2207
+ useEffect(() => {
2208
+ if (!walletBuilt) return
2209
+ return subscribeOnline(online => {
2210
+ TaskSendOffline.noteConnectivity(online)
2211
+ TaskCreditInbox.noteConnectivity(online)
2212
+ TaskDrainOutbox.noteConnectivity(online)
2213
+ TaskBackupPush.noteConnectivity(online)
2214
+ })
2215
+ }, [walletBuilt])
2216
+
2217
+ // Fetch Arcade status events when app returns to foreground
2218
+ useEffect(() => {
2219
+ const subscription = AppState.addEventListener('change', (nextAppState: AppStateStatus) => {
2220
+ const wasBackground = appStateRef.current.match(/inactive|background/)
2221
+ const isNowForeground = nextAppState === 'active'
2222
+
2223
+ if (wasBackground && isNowForeground) {
2224
+ const monitor = monitorRef.current
2225
+ if (monitor) {
2226
+ monitor.fetchSSEEvents().then(count => {
2227
+ if (count > 0) setTxStatusVersion(v => v + 1)
2228
+ })
2229
+ }
2230
+
2231
+ // Reconnects that happened while backgrounded may not replay as a
2232
+ // NetInfo event on resume; if work is pending, ask for a pass and let
2233
+ // the trigger's online gate decide.
2234
+ if (TaskSendOffline.hasPending) TaskSendOffline.requestNow()
2235
+ TaskCreditInbox.requestNow()
2236
+ if (TaskDrainOutbox.hasPending) TaskDrainOutbox.requestNow()
2237
+ }
2238
+
2239
+ appStateRef.current = nextAppState
2240
+ })
2241
+
2242
+ return () => subscription.remove()
2243
+ }, [])
2244
+
2245
+ // Relock-on-unplug, for PERSISTENT readers only (Android USB). Start discovery
2246
+ // at launch and, when the key is pulled, tell the ceremony (its onRelock
2247
+ // fires the close sound/haptic) so an armed or mid-signature vault session
2248
+ // ends with the hardware rather than lingering.
2249
+ //
2250
+ // Session-based transports (iOS NFC) are skipped here: they have no persistent
2251
+ // presence — the scan session is opened per ceremony and closed on arm — so
2252
+ // starting discovery at launch would pop the NFC sheet, and a session-end
2253
+ // "detach" is normal, not an unplug. The ceremony's own session-scoped
2254
+ // listener (see ceremony.ts) handles relock there instead.
2255
+ useEffect(() => {
2256
+ const driver = getVaultDriver()
2257
+ if (!driver || driver.sessionBased) return
2258
+ driver.start()
2259
+ const off = driver.onKeyEvent(e => {
2260
+ if (e.type === 'detached') {
2261
+ vaultCeremony.notifyKeyDetached()
2262
+ } else if (e.type === 'attached') {
2263
+ vaultCeremony.notifyKeyAttached()
2264
+ } else {
2265
+ // session-failed: the session died before any key connected. Never
2266
+ // emitted by a persistent reader today, but must not read as attach.
2267
+ vaultCeremony.notifySessionFailed(e.code)
2268
+ }
2269
+ })
2270
+ return () => {
2271
+ off()
2272
+ try {
2273
+ driver.stop()
2274
+ } catch {}
2275
+ }
2276
+ }, [])
2277
+
2278
+ // Cleanup monitor on unmount
2279
+ useEffect(() => {
2280
+ return () => {
2281
+ try {
2282
+ monitorRef.current?.stopTasks()
2283
+ } catch {}
2284
+ if (ledgerBumpTimerRef.current) {
2285
+ clearTimeout(ledgerBumpTimerRef.current)
2286
+ ledgerBumpTimerRef.current = null
2287
+ }
2288
+ monitorRef.current = null
2289
+ offlineChaintracksRef.current = undefined
2290
+ headerStoreRef.current = undefined
2291
+ }
2292
+ }, [])
2293
+
2294
+ const logout = useCallback(() => {
2295
+ logWithTimestamp(F, 'Logout')
2296
+ ;(async () => {
2297
+ // Tear the wallet down the same way rebuildWallet does. Logout used to
2298
+ // skip this, which orphaned a running monitor AND left the SQLite
2299
+ // connection open: a re-import of the same phrase then opened a second
2300
+ // connection to the SAME file with a second monitor on top — the
2301
+ // "database is locked" contention that corrupted expo-sqlite state and
2302
+ // crashed the 2026-08-22 vault deposit.
2303
+ {
2304
+ const monitor = monitorRef.current
2305
+ if (monitor) {
2306
+ monitorRef.current = null
2307
+ await stopMonitorAndDrain(monitor)
2308
+ }
2309
+ }
2310
+ offlineChaintracksRef.current = undefined
2311
+ headerStoreRef.current = undefined
2312
+ if (storage?.db) {
2313
+ try {
2314
+ await storage.destroy()
2315
+ } catch {}
2316
+ }
2317
+ setStorage(null)
2318
+
2319
+ updateManagers({})
2320
+ setConfigStatus('initial')
2321
+ walletBuiltRef.current = false
2322
+ setWalletBuilt(false)
2323
+ walletBuildingRef.current = false
2324
+ setWalletBuilding(false)
2325
+ setWalletUserId(null)
2326
+
2327
+ // The home screen shows this cached figure immediately on mount, before
2328
+ // its own balance read resolves — logout must not leave the departed
2329
+ // wallet's number sitting there for the next (walletless) mount to
2330
+ // paint. Sweep every network's cache, not just the current one.
2331
+ try {
2332
+ const keys = await AsyncStorage.getAllKeys()
2333
+ const stale = keys.filter(k => k.startsWith('cached_wallet_balance_'))
2334
+ if (stale.length > 0) await AsyncStorage.multiRemove(stale)
2335
+ } catch (err) {
2336
+ console.warn('[logout] failed to clear cached balance', err)
2337
+ }
2338
+
2339
+ // Awaited, and it removes the KEK along with the ciphertexts: leaving the
2340
+ // key behind would make the next cold start prompt for a wallet that no
2341
+ // longer exists. Works while locked, since deleting needs no key.
2342
+ await deleteAllWalletKeys()
2343
+
2344
+ // The attestation is per wallet. "Delete Wallet" routes here, so leaving
2345
+ // it behind would let the NEXT wallet on this device inherit a backup it
2346
+ // never made. Deliberately not awaited: a storage failure must not strand
2347
+ // the user mid-logout with no navigation.
2348
+ backupAttestation.clearAll().catch(err => {
2349
+ console.warn('[backupAttestation.clearAll]', err)
2350
+ })
2351
+
2352
+ // dismissAll() leaves exactly one screen on the stack, so this has to
2353
+ // REPLACE it: push() would add a second /index on top of the one already
2354
+ // there and leave two Browsers mounted.
2355
+ const { router } = loadExpoRouter()
2356
+ router.dismissAll()
2357
+ router.replace('/')
2358
+ })()
2359
+ }, [deleteAllWalletKeys, storage])
2360
+
2361
+ /**
2362
+ * Reconcile ONE transaction against the network, and repair it if the local
2363
+ * record disagrees with reality.
2364
+ *
2365
+ * Three outcomes:
2366
+ * - 'confirmed': a merkle proof exists; record it, the tx is settled.
2367
+ * - 'pending': the tx is on-chain (or too recent to judge) but unproven —
2368
+ * leave it alone, it is legitimately in flight.
2369
+ * - 'failed': the tx is NOT on-chain, the local record still claims it is
2370
+ * in flight, and it is old enough that propagation cannot
2371
+ * explain it. Mark it failed, which RELEASES the inputs it had
2372
+ * reserved (see storage's updateTransactionStatus).
2373
+ *
2374
+ * The 'failed' branch fills a real gap: the monitor's TaskFailAbandoned only
2375
+ * reaps 'unprocessed'/'unsigned', so a 'sending' transaction whose broadcast
2376
+ * silently failed shows "Broadcasting" forever and holds its inputs hostage.
2377
+ */
2378
+ const refreshProof = useCallback(
2379
+ async (txid: string, opts?: { neverFail?: boolean }): Promise<'confirmed' | 'pending' | 'failed'> => {
2380
+ if (!storage) throw new Error('Storage not available')
2381
+
2382
+ const wocBase =
2383
+ selectedNetwork === 'teratest' ? 'https://api.woc-ttn.bsvblockchain.tech' : 'https://api.whatsonchain.com'
2384
+ const chain = selectedNetwork === 'main' ? 'main' : 'test'
2385
+
2386
+ const res = await fetch(`${wocBase}/v1/bsv/${chain}/tx/${txid}/proof/bump`)
2387
+
2388
+ if (res.ok) {
2389
+ const bumpHex = (await res.text()).trim()
2390
+ const merklePath = MerklePath.fromHex(bumpHex)
2391
+ const merkleRoot = merklePath.computeRoot(txid)
2392
+ const ct = offlineChaintracksRef.current
2393
+ if (!ct || !(await ct.isValidRootForHeight(merkleRoot, merklePath.blockHeight))) {
2394
+ return 'pending'
2395
+ }
2396
+
2397
+ const store = headerStoreRef.current
2398
+ let headerHash = store && store.tipHeight === merklePath.blockHeight ? store.tipHash : ''
2399
+ if (!headerHash) {
2400
+ try {
2401
+ const header = await ct.findHeaderForHeight(merklePath.blockHeight)
2402
+ headerHash = header?.hash ?? ''
2403
+ } catch {
2404
+ return 'pending'
2405
+ }
2406
+ }
2407
+ if (!headerHash) return 'pending'
2408
+
2409
+ // Through the req when there is one; written directly when there is
2410
+ // not (a half-internalized payment has a row and an output but no req —
2411
+ // see pay/recordProof.ts). The direct path needs the raw bytes, which
2412
+ // an internalized row may not hold, so they come from the same source
2413
+ // as the proof.
2414
+ const proof = provenTxFromBump({ merklePath, txid, headerHash })
2415
+ await recordProof(storage, {
2416
+ txid,
2417
+ proof,
2418
+ fetchRawTx: async () => {
2419
+ const r = await fetch(`${wocBase}/v1/bsv/${chain}/tx/${txid}/hex`)
2420
+ if (!r.ok) throw new Error(`raw tx fetch failed: ${r.status}`)
2421
+ return Utils.toArray((await r.text()).trim(), 'hex')
2422
+ }
2423
+ })
2424
+ setTxStatusVersion(v => v + 1)
2425
+ return 'confirmed'
2426
+ }
2427
+
2428
+ // No proof. Before judging, find out whether the network has the tx at all.
2429
+ // A 404 on the proof endpoint alone is NOT evidence of failure — an
2430
+ // unconfirmed but perfectly healthy tx also has no proof.
2431
+ let onChain = false
2432
+ try {
2433
+ const head = await fetch(`${wocBase}/v1/bsv/${chain}/tx/hash/${txid}`)
2434
+ onChain = head.ok
2435
+ } catch {
2436
+ // Network unreachable — we cannot prove absence, so never fail the tx.
2437
+ return 'pending'
2438
+ }
2439
+ if (onChain) return 'pending'
2440
+
2441
+ // Not on chain. Only repair records that still claim to be in flight, and
2442
+ // only once propagation can no longer be the explanation — and only when
2443
+ // a person asked: the background repair sweep records proofs, it does
2444
+ // not decide that money is gone.
2445
+ if (opts?.neverFail) return 'pending'
2446
+ const txs = await storage.findTransactions({ partial: { txid }, noRawTx: true })
2447
+ const tx = txs[0]
2448
+ if (!tx || tx.status === 'failed' || tx.status === 'completed') return 'pending'
2449
+
2450
+ // A queued/posting offline payment is expected not to be on chain yet —
2451
+ // failing it would release inputs the payee still holds.
2452
+ const db = storage.sqliteDb
2453
+ const rows = db ? await findOfflineActions(db, { status: ['queued', 'posting'] }) : []
2454
+ const offlineStatus = rows.find(r => r.txid === txid)?.status
2455
+ if (
2456
+ shouldFailUnprovenTx({
2457
+ offlineStatus,
2458
+ txStatus: tx.status,
2459
+ updatedAtMs: tx.updated_at ? new Date(tx.updated_at).getTime() : 0,
2460
+ nowMs: Date.now()
2461
+ }) === 'pending'
2462
+ ) {
2463
+ if (offlineStatus === 'queued' || offlineStatus === 'posting') TaskSendOffline.requestNow()
2464
+ return 'pending'
2465
+ }
2466
+
2467
+ // Releases the inputs this transaction had reserved and marks its outputs
2468
+ // unspendable — the same repair the monitor performs for abandoned rows.
2469
+ await storage.updateTransactionStatus('failed', tx.transactionId)
2470
+ setTxStatusVersion(v => v + 1)
2471
+ return 'failed'
2472
+ },
2473
+ [storage, selectedNetwork]
2474
+ )
2475
+
2476
+ // ── Proof repair for transactions nothing else will prove ──
2477
+ // An `unproven` row with no proven_tx_req is invisible to TaskCheckForProofs
2478
+ // (see storage/methods/unprovenWithoutReqSql.ts for how one comes to exist).
2479
+ // Refresh each once per wallet build, proof-only: this never marks a
2480
+ // transaction failed.
2481
+ useEffect(() => {
2482
+ if (!walletBuilt || !storage) return
2483
+ let cancelled = false
2484
+ ;(async () => {
2485
+ let txids: string[] = []
2486
+ try {
2487
+ txids = await storage.findUnprovenTxidsWithoutReq()
2488
+ } catch {
2489
+ return
2490
+ }
2491
+ for (const txid of txids) {
2492
+ if (cancelled) return
2493
+ try {
2494
+ await refreshProof(txid, { neverFail: true })
2495
+ } catch {
2496
+ // Offline, or still unmined: the next build tries again.
2497
+ }
2498
+ }
2499
+ })()
2500
+ return () => {
2501
+ cancelled = true
2502
+ }
2503
+ }, [walletBuilt, storage, refreshProof])
2504
+
2505
+ const peekLastMissHeight = useCallback(() => offlineChaintracksRef.current?.peekLastMissHeight(), [])
2506
+
2507
+ const runMonitorTask = useCallback(async (taskName: string): Promise<string> => {
2508
+ const monitor = monitorRef.current
2509
+ if (!monitor) return 'Monitor not running'
2510
+ try {
2511
+ return await monitor.runTask(taskName)
2512
+ } catch (e: any) {
2513
+ return `Error: ${e.message || 'unknown'}`
2514
+ }
2515
+ }, [])
2516
+
2517
+ const DIAGNOSTIC_TASKS = new Set([
2518
+ 'SendWaiting',
2519
+ 'CheckForProofs',
2520
+ 'CheckNoSends',
2521
+ 'ReviewStatus',
2522
+ 'MonitorCallHistory',
2523
+ 'ArcadeSSE',
2524
+ 'UnFail'
2525
+ ])
2526
+
2527
+ const getMonitorTaskNames = useCallback((): string[] => {
2528
+ const monitor = monitorRef.current
2529
+ if (!monitor) return []
2530
+ return [...monitor._tasks, ...monitor._otherTasks].map(t => t.name).filter(n => DIAGNOSTIC_TASKS.has(n))
2531
+ }, [])
2532
+
2533
+ // Fast, targeted repair. A FAILED transaction never confirms, but the toolbox
2534
+ // leaves the inputs it had reserved marked `spentBy` that dead txid — so the
2535
+ // coin reads as an unresolvable double-spend forever (WERR_REVIEW_ACTIONS on
2536
+ // every new spend, even though the output is still `spendable`). Null out
2537
+ // spentBy and restore spendable for every output still reserved by a failed
2538
+ // tx. Pure local SQL scoped to failed-tx reservations — NO per-UTXO network
2539
+ // scan (unlike checkUtxoSpendability), so it is instant and safe to run often.
2540
+ const releaseStuckReservations = useCallback(async (): Promise<string> => {
2541
+ if (!storage) return 'Storage not available'
2542
+ const db = (storage as any)?.sqliteDb
2543
+ if (!db?.runAsync) return 'DB not available'
2544
+ try {
2545
+ const rows = (await db.getAllAsync(
2546
+ `SELECT o.outputId AS outputId, o.satoshis AS satoshis, t.txid AS txid
2547
+ FROM outputs o JOIN transactions t ON t.transactionId = o.spentBy
2548
+ WHERE t.status = 'failed'`
2549
+ )) as { outputId: number; satoshis: number; txid: string }[]
2550
+ if (!rows || rows.length === 0) return 'No stuck reservations found.'
2551
+ await db.runAsync(
2552
+ `UPDATE outputs SET spentBy = NULL, spendable = 1
2553
+ WHERE spentBy IN (SELECT transactionId FROM transactions WHERE status = 'failed')`
2554
+ )
2555
+ const detail = rows
2556
+ .map(r => ` • ${r.satoshis} sat (output ${r.outputId}) ← failed ${String(r.txid).slice(0, 12)}…`)
2557
+ .join('\n')
2558
+ return `✓ Released ${rows.length} stuck reservation(s):\n${detail}`
2559
+ } catch (e: any) {
2560
+ return `⚠ Release failed: ${e.message}`
2561
+ }
2562
+ }, [storage])
2563
+
2564
+ const checkUtxoSpendability = useCallback(async (): Promise<string> => {
2565
+ if (!(await getOnline())) throw new Error('offline')
2566
+ if (!storage) return 'Storage not available'
2567
+ const wallet = managers?.permissionsManager
2568
+ if (!wallet) return 'Wallet not ready'
2569
+
2570
+ // Clear stuck failed-tx reservations first (see releaseStuckReservations).
2571
+ const releaseResult = await releaseStuckReservations()
2572
+ const releasedNote = releaseResult === 'No stuck reservations found.' ? '' : releaseResult + '\n\n'
2573
+
2574
+ const wocBase =
2575
+ selectedNetwork === 'main'
2576
+ ? 'https://api.whatsonchain.com/v1/bsv/main'
2577
+ : selectedNetwork === 'test'
2578
+ ? 'https://api.whatsonchain.com/v1/bsv/test'
2579
+ : 'https://api.woc-ttn.bsvblockchain.tech/v1/bsv/test'
2580
+
2581
+ // Rate limit: max 3 requests/sec (WoC limit ~1 per 0.34s)
2582
+ const WOC_INTERVAL = 340
2583
+ let lastRequest = 0
2584
+ const throttledFetch = async (url: string, init?: RequestInit): Promise<Response> => {
2585
+ const now = Date.now()
2586
+ const wait = WOC_INTERVAL - (now - lastRequest)
2587
+ if (wait > 0) await new Promise(r => setTimeout(r, wait))
2588
+ lastRequest = Date.now()
2589
+ return fetch(url, init)
2590
+ }
2591
+
2592
+ try {
2593
+ const outputs = await storage.findOutputs({
2594
+ partial: { spendable: true as any },
2595
+ noScript: true,
2596
+ txStatus: ['completed'] as any
2597
+ })
2598
+ if (outputs.length === 0) return releasedNote + 'No spendable outputs found.'
2599
+
2600
+ const db = storage.sqliteDb
2601
+ const liveRows = db ? await findOfflineActions(db, { status: ['queued', 'posting'] }) : []
2602
+ const liveOfflineTxids = new Set(liveRows.map(r => r.txid).filter(Boolean))
2603
+
2604
+ const lines: string[] = [`Found ${outputs.length} spendable output(s). Checking WoC...\n`]
2605
+ let spentCount = 0
2606
+ let unspentCount = 0
2607
+ let errorCount = 0
2608
+ let internalizedCount = 0
2609
+
2610
+ for (const o of outputs) {
2611
+ if (!o.txid) {
2612
+ lines.push(` outputId=${o.outputId} — no txid, skipped`)
2613
+ continue
2614
+ }
2615
+ let probe: UtxoProbe = { status: 'error' }
2616
+ let spendingTxid: string | undefined
2617
+ try {
2618
+ const controller = new AbortController()
2619
+ const timeout = setTimeout(() => controller.abort(), 10_000)
2620
+ let resp: Response
2621
+ try {
2622
+ resp = await throttledFetch(`${wocBase}/tx/${o.txid}/${o.vout}/spent`, {
2623
+ signal: controller.signal
2624
+ })
2625
+ } finally {
2626
+ clearTimeout(timeout)
2627
+ }
2628
+ if (resp.status === 404) {
2629
+ probe = { status: 'success', isUtxo: true }
2630
+ } else if (!resp.ok) {
2631
+ errorCount++
2632
+ lines.push(` ERROR: ${o.txid}:${o.vout} — HTTP ${resp.status}`)
2633
+ } else {
2634
+ const spentData = await resp.json()
2635
+ const txid = spentData?.txid
2636
+ if (typeof txid === 'string' && txid) {
2637
+ spendingTxid = txid
2638
+ probe = { status: 'success', isUtxo: false }
2639
+ } else {
2640
+ errorCount++
2641
+ lines.push(` ERROR: ${o.txid}:${o.vout} — HTTP 200 with no spending txid`)
2642
+ }
2643
+ }
2644
+ } catch (e: any) {
2645
+ errorCount++
2646
+ lines.push(` ERROR: ${o.txid}:${o.vout} — ${e.message}`)
2647
+ }
2648
+
2649
+ if (probe.status === 'error') continue
2650
+ if (probe.isUtxo === true) {
2651
+ unspentCount++
2652
+ continue
2653
+ }
2654
+
2655
+ const release = shouldReleaseUtxo({
2656
+ online: true,
2657
+ txStatus: 'completed',
2658
+ txid: o.txid,
2659
+ liveOfflineTxids,
2660
+ probe
2661
+ })
2662
+ if (!release) {
2663
+ lines.push(` SPENT: ${o.txid}:${o.vout} (${o.satoshis} sat) — not released (live offline_action)`)
2664
+ continue
2665
+ }
2666
+
2667
+ spentCount++
2668
+ lines.push(` SPENT: ${o.txid}:${o.vout} (${o.satoshis} sat) → by ${spendingTxid}`)
2669
+ await storage.updateOutput(o.outputId, { spendable: false as any })
2670
+
2671
+ if (!spendingTxid) continue
2672
+ try {
2673
+ const beefResp = await throttledFetch(`${wocBase}/tx/${spendingTxid}/beef`)
2674
+ if (!beefResp.ok) {
2675
+ lines.push(` ↳ BEEF fetch failed (HTTP ${beefResp.status}), skipping change recovery`)
2676
+ continue
2677
+ }
2678
+ const beefHex = await beefResp.text()
2679
+ const beefBytes = Utils.toArray(beefHex, 'hex')
2680
+ const tx = Transaction.fromBEEF(beefBytes)
2681
+ const atomicBeef = tx.toAtomicBEEF()
2682
+
2683
+ const changeOutputs = await storage.findOutputs({
2684
+ partial: { change: true as any, spendable: false as any },
2685
+ noScript: true
2686
+ })
2687
+ // Only transactionId is used below; noRawTx keeps rawTx/inputBEEF
2688
+ // (and their JS-array expansion) out of the read entirely.
2689
+ const txRows = await storage.findTransactions({ partial: { txid: spendingTxid }, noRawTx: true })
2690
+ const matchingTxId = txRows.length > 0 ? txRows[0].transactionId : undefined
2691
+
2692
+ const outputsToInternalize: any[] = []
2693
+ if (matchingTxId) {
2694
+ const txChangeOutputs = changeOutputs.filter(co => co.transactionId === matchingTxId)
2695
+ for (const co of txChangeOutputs) {
2696
+ if (co.derivationPrefix && co.derivationSuffix) {
2697
+ outputsToInternalize.push({
2698
+ outputIndex: co.vout,
2699
+ protocol: 'wallet payment',
2700
+ paymentRemittance: {
2701
+ derivationPrefix: co.derivationPrefix,
2702
+ derivationSuffix: co.derivationSuffix,
2703
+ senderIdentityKey:
2704
+ co.senderIdentityKey ||
2705
+ (await wallet.getPublicKey({ identityKey: true }, adminOriginator)).publicKey
2706
+ }
2707
+ })
2708
+ }
2709
+ }
2710
+ }
2711
+
2712
+ if (outputsToInternalize.length > 0) {
2713
+ await wallet.internalizeAction(
2714
+ {
2715
+ tx: atomicBeef,
2716
+ outputs: outputsToInternalize,
2717
+ description: 'Recovered from stale UTXO check'
2718
+ },
2719
+ adminOriginator
2720
+ )
2721
+ internalizedCount++
2722
+ lines.push(` ↳ INTERNALIZED: ${outputsToInternalize.length} change output(s) recovered`)
2723
+ } else {
2724
+ lines.push(` ↳ No recoverable change outputs`)
2725
+ }
2726
+ } catch (e: any) {
2727
+ lines.push(` ↳ Internalize failed: ${e.message}`)
2728
+ }
2729
+ }
2730
+
2731
+ lines.push(
2732
+ `\nSummary: ${unspentCount} unspent, ${spentCount} spent, ${internalizedCount} internalized, ${errorCount} errors`
2733
+ )
2734
+ if (internalizedCount > 0) {
2735
+ lines.push(`✓ ${internalizedCount} spending tx(s) internalized with change outputs`)
2736
+ }
2737
+ if (spentCount > internalizedCount) {
2738
+ lines.push(`⚠ ${spentCount - internalizedCount} stale output(s) marked unspendable (no change to recover)`)
2739
+ }
2740
+ return releasedNote + lines.join('\n')
2741
+ } catch (e: any) {
2742
+ return releasedNote + `Error querying outputs: ${e.message}`
2743
+ }
2744
+ }, [storage, selectedNetwork, managers, adminOriginator, releaseStuckReservations])
2745
+
2746
+ const contextValue = useMemo<WalletContextValue>(
2747
+ () => ({
2748
+ managers,
2749
+ getManagers,
2750
+ settings,
2751
+ updateSettings,
2752
+ logout,
2753
+ adminOriginator,
2754
+ basketRequests: basketQueue.requests,
2755
+ certificateRequests: certificateQueue.requests,
2756
+ protocolRequests: protocolQueue.requests,
2757
+ spendingRequests: spendingQueue.requests,
2758
+ btmsRequests: btmsQueue.requests,
2759
+ advanceBasketQueue: basketQueue.advance,
2760
+ advanceCertificateQueue: certificateQueue.advance,
2761
+ advanceProtocolQueue: protocolQueue.advance,
2762
+ advanceSpendingQueue: spendingQueue.advance,
2763
+ advanceBtmsQueue,
2764
+ finalizeConfig,
2765
+ setConfigStatus,
2766
+ configStatus,
2767
+ selectedStorageUrl,
2768
+ selectedMethod,
2769
+ selectedNetwork,
2770
+ buildWalletFromMnemonic,
2771
+ buildWalletFromRecoveredKey,
2772
+ backupRestore,
2773
+ getBackupRestore,
2774
+ switchNetwork,
2775
+ rebuildWallet,
2776
+ storage,
2777
+ refreshProof,
2778
+ peekLastMissHeight,
2779
+ txStatusVersion,
2780
+ walletUserId,
2781
+ walletBuilding,
2782
+ walletBuilt,
2783
+ localPayNotification,
2784
+ clearLocalPayNotification,
2785
+ runMonitorTask,
2786
+ getMonitorTaskNames,
2787
+ checkUtxoSpendability,
2788
+ releaseStuckReservations
2789
+ }),
2790
+ [
2791
+ managers,
2792
+ getManagers,
2793
+ settings,
2794
+ updateSettings,
2795
+ logout,
2796
+ adminOriginator,
2797
+ basketQueue.requests,
2798
+ certificateQueue.requests,
2799
+ protocolQueue.requests,
2800
+ spendingQueue.requests,
2801
+ btmsQueue.requests,
2802
+ basketQueue.advance,
2803
+ certificateQueue.advance,
2804
+ protocolQueue.advance,
2805
+ spendingQueue.advance,
2806
+ advanceBtmsQueue,
2807
+ finalizeConfig,
2808
+ setConfigStatus,
2809
+ configStatus,
2810
+ selectedStorageUrl,
2811
+ selectedMethod,
2812
+ selectedNetwork,
2813
+ buildWalletFromMnemonic,
2814
+ buildWalletFromRecoveredKey,
2815
+ backupRestore,
2816
+ getBackupRestore,
2817
+ switchNetwork,
2818
+ rebuildWallet,
2819
+ storage,
2820
+ refreshProof,
2821
+ peekLastMissHeight,
2822
+ txStatusVersion,
2823
+ walletUserId,
2824
+ walletBuilding,
2825
+ walletBuilt,
2826
+ localPayNotification,
2827
+ clearLocalPayNotification,
2828
+ runMonitorTask,
2829
+ getMonitorTaskNames,
2830
+ checkUtxoSpendability,
2831
+ releaseStuckReservations
2832
+ ]
2833
+ )
2834
+
2835
+ // Stable handles only — identity changes solely when the managers are
2836
+ // (re)built or the building flag flips, NOT on queue/tx-status/SSE churn.
2837
+ const managersValue = useMemo<WalletManagersSlice>(
2838
+ () => ({ managers, storage, adminOriginator, walletBuilding }),
2839
+ [managers, storage, adminOriginator, walletBuilding]
2840
+ )
2841
+
2842
+ return (
2843
+ <WalletContext.Provider value={contextValue}>
2844
+ <WalletManagersContext.Provider value={managersValue}>{children}</WalletManagersContext.Provider>
2845
+ </WalletContext.Provider>
2846
+ )
2847
+ }
2848
+
2849
+ export const useWallet = () => useContext(WalletContext)
2850
+
2851
+ /* -------------------------------------------------------------------------- */
2852
+ /* NARROW SELECTOR HOOKS */
2853
+ /* -------------------------------------------------------------------------- */
2854
+ //
2855
+ // `useWallet()` returns the full ~35-field context object — any consumer is
2856
+ // re-rendered every time *any* field changes (queue mutation, txStatusVersion
2857
+ // tick, settings update, SSE event, etc.). For components that only need a
2858
+ // slice (e.g. the chrome shell needs `walletBuilt` but doesn't care about
2859
+ // `txStatusVersion`), use one of the narrow selector hooks below.
2860
+ //
2861
+ // They share the same provider value, so they don't avoid the underlying
2862
+ // React context re-render — but they do clearly mark each consumer's
2863
+ // dependency surface, and provide a single seam for a future
2864
+ // `useSyncExternalStore`-based selector migration when the WalletContext
2865
+ // is finally split into independent providers.
2866
+ //
2867
+ // Returning a stable object via `useMemo` on the slice keys still means a
2868
+ // consumer that does `const { walletBuilt } = useWalletStatus()` re-renders
2869
+ // only when walletBuilt itself toggles — because the slice's identity tracks
2870
+ // just the queried fields. This is the maximum win achievable without
2871
+ // breaking the existing `useWallet()` API.
2872
+
2873
+ export interface WalletStatusSlice {
2874
+ walletBuilt: boolean
2875
+ walletBuilding: boolean
2876
+ configStatus: ConfigStatus
2877
+ selectedNetwork: AppChain
2878
+ }
2879
+ export const useWalletStatus = (): WalletStatusSlice => {
2880
+ const ctx = useContext(WalletContext)
2881
+ return useMemo<WalletStatusSlice>(
2882
+ () => ({
2883
+ walletBuilt: ctx.walletBuilt,
2884
+ walletBuilding: ctx.walletBuilding,
2885
+ configStatus: ctx.configStatus,
2886
+ selectedNetwork: ctx.selectedNetwork
2887
+ }),
2888
+ [ctx.walletBuilt, ctx.walletBuilding, ctx.configStatus, ctx.selectedNetwork]
2889
+ )
2890
+ }
2891
+
2892
+ export interface WalletQueuesSlice {
2893
+ basketRequests: BasketAccessRequest[]
2894
+ certificateRequests: CertificateAccessRequest[]
2895
+ protocolRequests: ProtocolAccessRequest[]
2896
+ spendingRequests: SpendingRequest[]
2897
+ btmsRequests: BtmsRequest[]
2898
+ advanceBasketQueue: () => void
2899
+ advanceCertificateQueue: () => void
2900
+ advanceProtocolQueue: () => void
2901
+ advanceSpendingQueue: () => void
2902
+ advanceBtmsQueue: (approved: boolean) => void
2903
+ }
2904
+ export const useWalletQueues = (): WalletQueuesSlice => {
2905
+ const ctx = useContext(WalletContext)
2906
+ return useMemo<WalletQueuesSlice>(
2907
+ () => ({
2908
+ basketRequests: ctx.basketRequests,
2909
+ certificateRequests: ctx.certificateRequests,
2910
+ protocolRequests: ctx.protocolRequests,
2911
+ spendingRequests: ctx.spendingRequests,
2912
+ btmsRequests: ctx.btmsRequests,
2913
+ advanceBasketQueue: ctx.advanceBasketQueue,
2914
+ advanceCertificateQueue: ctx.advanceCertificateQueue,
2915
+ advanceProtocolQueue: ctx.advanceProtocolQueue,
2916
+ advanceSpendingQueue: ctx.advanceSpendingQueue,
2917
+ advanceBtmsQueue: ctx.advanceBtmsQueue
2918
+ }),
2919
+ [
2920
+ ctx.basketRequests,
2921
+ ctx.certificateRequests,
2922
+ ctx.protocolRequests,
2923
+ ctx.spendingRequests,
2924
+ ctx.btmsRequests,
2925
+ ctx.advanceBasketQueue,
2926
+ ctx.advanceCertificateQueue,
2927
+ ctx.advanceProtocolQueue,
2928
+ ctx.advanceSpendingQueue,
2929
+ ctx.advanceBtmsQueue
2930
+ ]
2931
+ )
2932
+ }
2933
+
2934
+ /** For consumers that only care about the SSE-driven transaction tick. */
2935
+ export const useTxStatusVersion = (): number => {
2936
+ const ctx = useContext(WalletContext)
2937
+ return ctx.txStatusVersion
2938
+ }