@bsv/expo-wallet-toolbox 0.4.0 → 0.7.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 (182) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/README.md +19 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/amountFormatHelpers.ts +238 -34
  6. package/core/backup/RemoteSyncReader.ts +2 -5
  7. package/core/backup/codec.ts +2 -2
  8. package/core/backup/push.ts +1 -1
  9. package/core/config.tsx +16 -1
  10. package/core/contacts/contactActivity.ts +153 -0
  11. package/core/contacts/contactCache.ts +41 -0
  12. package/core/contacts/contactsStore.ts +183 -0
  13. package/core/context/VaultContext.tsx +8 -11
  14. package/core/context/WalletConnectionContext.tsx +137 -52
  15. package/core/context/WalletContext.tsx +464 -30
  16. package/core/demo/demoAssets.ts +60 -0
  17. package/core/demo/demoLedger.ts +240 -0
  18. package/core/demo/demoMandalaRuntime.ts +96 -0
  19. package/core/demo/demoMode.ts +38 -0
  20. package/core/demo/demoWallet.ts +25 -0
  21. package/core/demo/index.ts +26 -0
  22. package/core/demo/useDemo.ts +59 -0
  23. package/core/headers/OfflineFirstChaintracks.ts +52 -14
  24. package/core/headers/headerStore.ts +7 -10
  25. package/core/hooks/useConfirmationSound.ts +14 -8
  26. package/core/i18n/translations.tsx +4562 -986
  27. package/core/identity/contactLink.ts +36 -0
  28. package/core/identity/handleRegistry/client.ts +285 -0
  29. package/core/identity/handleRegistry/profileCert.ts +254 -0
  30. package/core/identity/handleRegistry/registration.ts +559 -0
  31. package/core/identity/handleRegistry/resolver.ts +247 -0
  32. package/core/identity/handleRegistry/rules.ts +104 -0
  33. package/core/index.ts +116 -15
  34. package/core/localpay/build.ts +674 -37
  35. package/core/localpay/codec.ts +68 -5
  36. package/core/localpay/pending.ts +240 -22
  37. package/core/localpay/pendingAborts.ts +5 -1
  38. package/core/localpay/settlementAck.ts +149 -0
  39. package/core/localpay/types.ts +14 -1
  40. package/core/localpay/verify.ts +118 -69
  41. package/core/mandala/abortGuard.ts +134 -0
  42. package/core/mandala/basketMigration.ts +166 -0
  43. package/core/mandala/bundle.ts +244 -0
  44. package/core/mandala/createRuntime.ts +2437 -0
  45. package/core/mandala/drain.ts +670 -0
  46. package/core/mandala/permissionModule.ts +642 -0
  47. package/core/mandala/resendTransfer.ts +175 -0
  48. package/core/mandala/runtime.ts +357 -0
  49. package/core/mandala/settlementStore.ts +412 -0
  50. package/core/mandala/types.ts +290 -0
  51. package/core/monitor/MonitorSupervisor.ts +121 -0
  52. package/core/monitor/TaskBackupPush.ts +1 -1
  53. package/core/monitor/TaskCreditInbox.ts +1 -1
  54. package/core/monitor/TaskDrainOutbox.ts +1 -1
  55. package/core/monitor/TaskSendOffline.ts +1 -1
  56. package/core/net/online.ts +49 -0
  57. package/core/numberFormat.ts +19 -0
  58. package/core/offline/cancelParked.ts +94 -1
  59. package/core/offline/payerHold.ts +152 -12
  60. package/core/offline/plan.ts +1 -1
  61. package/core/offline/tokenFrames.ts +197 -0
  62. package/core/parsePeerPayURI.ts +70 -17
  63. package/core/pay/rails/address.ts +51 -3
  64. package/core/pay/rails/handle.ts +88 -9
  65. package/core/pay/rails/index.ts +16 -6
  66. package/core/pay/rails/nearby.ts +114 -4
  67. package/core/pay/recordProof.ts +2 -6
  68. package/core/services/arcadeBroadcastProvider.ts +1 -4
  69. package/core/services/capWalletArgs.ts +8 -9
  70. package/core/services/exchangeRate.ts +1 -1
  71. package/core/services/externalOrigin.ts +42 -0
  72. package/core/services/vault/VaultKeyService.ts +912 -251
  73. package/core/services/vault/ceremony.ts +435 -367
  74. package/core/services/vault/ceremonyHost.ts +27 -21
  75. package/core/services/vault/devMock.ts +30 -7
  76. package/core/services/vault/driver.ts +95 -41
  77. package/core/services/vault/guard.ts +514 -56
  78. package/core/services/vault/hardwareLease.ts +22 -0
  79. package/core/services/vault/mockYubiKey.ts +258 -90
  80. package/core/services/vault/pivReset.ts +145 -0
  81. package/core/services/vault/r1comb.ts +976 -0
  82. package/core/services/vault/session.ts +93 -26
  83. package/core/services/vault/transfers.ts +2617 -747
  84. package/core/services/vault/types.ts +100 -43
  85. package/core/services/vault/vaultStore.ts +991 -74
  86. package/core/services/walletConnectionValidation.ts +293 -0
  87. package/core/services/walletServiceConfig.ts +31 -20
  88. package/core/storage/StorageExpoSQLite.ts +420 -87
  89. package/core/storage/dbImage.ts +48 -0
  90. package/core/storage/methods/findSql.ts +3 -54
  91. package/core/storage/methods/listActionsSql.ts +8 -5
  92. package/core/storage/methods/listOutputsSql.ts +9 -5
  93. package/core/storage/methods/offlineActions.ts +15 -0
  94. package/core/storage/methods/processOfflineActions.ts +265 -9
  95. package/core/storage/methods/reviewStatusSql.ts +7 -2
  96. package/core/storage/methods/walletBalanceSql.ts +16 -4
  97. package/core/storage/schema/createTables.ts +152 -0
  98. package/core/storage/sqlUpdateValue.ts +24 -0
  99. package/core/toolboxConfig.ts +182 -1
  100. package/core/toolboxTypes.ts +40 -0
  101. package/core/userAvatar.ts +79 -0
  102. package/core/walletMonitor.ts +8 -3
  103. package/core/walletRepair/runWalletCheck.ts +19 -2
  104. package/package.json +31 -30
  105. package/ui/activityFilter.ts +115 -0
  106. package/ui/components/QRScanner.tsx +1 -1
  107. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  108. package/ui/components/pay/AssetPicker.tsx +184 -0
  109. package/ui/components/pay/AvailableBalance.tsx +33 -2
  110. package/ui/components/pay/HandleReceive.tsx +213 -50
  111. package/ui/components/pay/NearbyFlow.tsx +616 -69
  112. package/ui/components/pay/PayForm.tsx +73 -8
  113. package/ui/components/pay/PaymentSuccessOverlay.tsx +89 -8
  114. package/ui/components/pay/RecipientField.tsx +132 -73
  115. package/ui/components/pay/RequestHub.tsx +68 -8
  116. package/ui/components/pay/ResultBanner.tsx +41 -4
  117. package/ui/components/pay/StepBar.tsx +32 -0
  118. package/ui/components/pay/UniversalSend.tsx +1118 -86
  119. package/ui/components/pay/tokenSendCopy.ts +116 -0
  120. package/ui/components/pay/useRecipientInput.ts +36 -7
  121. package/ui/components/ui/PencilEditField.tsx +109 -0
  122. package/ui/components/ui/PermissionSheet.tsx +65 -4
  123. package/ui/components/ui/Sheet.tsx +9 -2
  124. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  125. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  126. package/ui/components/vault/KeyChooser.tsx +96 -0
  127. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  128. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  129. package/ui/components/wallet/ActivityRow.tsx +283 -97
  130. package/ui/components/wallet/AmountInput.tsx +92 -28
  131. package/ui/components/wallet/AssetAmount.tsx +95 -0
  132. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  133. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  134. package/ui/components/wallet/ContactSigil.tsx +49 -0
  135. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  136. package/ui/components/wallet/FitAmount.tsx +148 -0
  137. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  138. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  139. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  140. package/ui/components/wallet/ProfileButton.tsx +62 -0
  141. package/ui/components/wallet/UserAvatar.tsx +85 -0
  142. package/ui/components/wallet/avatarIcons.ts +122 -0
  143. package/ui/components/wallet/tokenEviction.ts +65 -0
  144. package/ui/hooks/useContactsStore.ts +10 -0
  145. package/ui/hooks/useExportWalletData.ts +39 -0
  146. package/ui/hooks/useMandala.ts +320 -0
  147. package/ui/hooks/useOnline.ts +65 -20
  148. package/ui/hooks/useVaultBalance.ts +105 -7
  149. package/ui/hooks/useVaultCoverage.ts +52 -0
  150. package/ui/importDatabases.ts +7 -3
  151. package/ui/index.ts +75 -7
  152. package/ui/screens/ConnectionsScreen.tsx +46 -29
  153. package/ui/screens/ContactScreen.tsx +289 -0
  154. package/ui/screens/ContactsScreen.tsx +373 -0
  155. package/ui/screens/IdentifierScreen.tsx +234 -0
  156. package/ui/screens/NewContactScreen.tsx +362 -0
  157. package/ui/screens/PairScreen.tsx +12 -12
  158. package/ui/screens/PayScreen.tsx +145 -12
  159. package/ui/screens/ProfileScreen.tsx +783 -0
  160. package/ui/screens/SettingsScreen.tsx +18 -9
  161. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  162. package/ui/screens/TrustScreen.tsx +1 -1
  163. package/ui/screens/VaultScreen.tsx +925 -171
  164. package/ui/screens/VaultTransferScreen.tsx +376 -123
  165. package/ui/screens/WalletCheckScreen.tsx +10 -1
  166. package/ui/screens/WalletConfigScreen.tsx +80 -16
  167. package/ui/screens/WalletHomeScreen.tsx +915 -139
  168. package/ui/screens/homeBadges.ts +9 -1
  169. package/ui/screens/tokenRowTitle.ts +68 -0
  170. package/ui/tokenFormat.ts +108 -0
  171. package/ui/tokenSeen.ts +75 -0
  172. package/ui/tokenStatus.ts +100 -0
  173. package/ui/txStatus.ts +43 -5
  174. package/assets/sounds/vault-close.wav +0 -0
  175. package/assets/sounds/vault-open.wav +0 -0
  176. package/core/services/vault/k1.ts +0 -75
  177. package/core/services/vault/sealing.ts +0 -84
  178. package/core/services/vault/vaultDerivation.ts +0 -152
  179. package/core/services/vault/vaultPassphrase.ts +0 -287
  180. package/ui/components/vault/PassphraseField.tsx +0 -306
  181. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  182. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -9,17 +9,15 @@ import {
9
9
  WalletSigner,
10
10
  PermissionRequest,
11
11
  SimpleWalletManager,
12
- Monitor
12
+ Monitor,
13
+ DEFAULT_SETTINGS as LIB_DEFAULT_SETTINGS,
14
+ WalletSettings,
15
+ WalletSettingsManager
13
16
  } from '@bsv/wallet-toolbox-mobile'
14
17
  import { KeyDeriver, PrivateKey, MerklePath, Transaction, Utils } from '@bsv/sdk'
15
18
  import { VAULT_RETENTION_MS, ceremony as vaultCeremony } from '../services/vault/ceremonyHost'
16
19
  import { getVaultDriver } from '../services/vault/driver'
17
20
  import { backupAttestation } from '../services/vault/backupAttestation'
18
- import {
19
- DEFAULT_SETTINGS as LIB_DEFAULT_SETTINGS,
20
- WalletSettings,
21
- WalletSettingsManager
22
- } from '@bsv/wallet-toolbox-mobile/out/src/WalletSettingsManager'
23
21
 
24
22
  /** App-level defaults: library defaults + additional certifiers */
25
23
  /**
@@ -106,6 +104,26 @@ function loadQuietEventSourceClass(): EventSourceCtor {
106
104
  return quietEventSourceClass
107
105
  }
108
106
 
107
+ /**
108
+ * `MandalaTokenModuleDeps.resolveAssetMetadata`, over the lib's own registry
109
+ * lookup (`@bsv/mandala`'s `resolveAssetMetadata` — overlay lookup,
110
+ * SPV-verified genesis, memoized). Only ever affects the display (name AND,
111
+ * per adversarial-review finding 4, decimal formatting) in a permission
112
+ * prompt, never a decision to prompt or to grant, so a failure is null and
113
+ * the prompt falls back to the raw assetId in base units — including on a
114
+ * build where `configureMandala` has not run, where the lib throws rather
115
+ * than pretending the asset has no name.
116
+ */
117
+ async function resolveMandalaAssetMetadata(assetId: string): Promise<MandalaAssetMetadata | null> {
118
+ try {
119
+ const meta = await resolveAssetMetadata(assetId)
120
+ if (!meta) return null
121
+ return { label: meta.label, ticker: meta.ticker, decimals: meta.decimals }
122
+ } catch {
123
+ return null
124
+ }
125
+ }
126
+
109
127
  const DEFAULT_SETTINGS: WalletSettings = {
110
128
  ...LIB_DEFAULT_SETTINGS,
111
129
  trustSettings: {
@@ -136,12 +154,23 @@ const DEFAULT_SETTINGS: WalletSettings = {
136
154
  }
137
155
  import type { AppChain } from '../config'
138
156
  import { DEFAULT_STORAGE_URL, DEFAULT_CHAIN, ADMIN_ORIGINATOR, toWalletChain } from '../config'
139
- import { getBackupUrl } from '../toolboxConfig'
157
+ import { getBackupUrl, getMandalaEndpoints } from '../toolboxConfig'
140
158
  import { DEFAULT_AUTO_APPROVE_THRESHOLD, AUTO_APPROVE_COOLDOWN_MS, AUTO_APPROVE_STORAGE_KEY } from '../constants'
141
159
  import AsyncStorage from '@react-native-async-storage/async-storage'
142
160
  import { UserContext } from './UserContext'
143
161
  import { useLocalStorage } from './LocalStorageProvider'
144
162
  import { usePermissionQueue } from '../hooks/usePermissionQueue'
163
+ import { configureMandala, resolveAssetMetadata } from '@bsv/mandala'
164
+ import { MessageBoxClient } from '@bsv/message-box-client'
165
+ import { MandalaTokenModule, wrapCreateActionForTokenInputs, type MandalaAssetMetadata } from '../mandala/permissionModule'
166
+ import { wrapAbortActionForSettlements } from '../mandala/abortGuard'
167
+ import { migrateMandalaBasketName } from '../mandala/basketMigration'
168
+ import { bindOriginator, createMandalaKvStorage, createMandalaRuntime, type MandalaMessageBox } from '../mandala/createRuntime'
169
+ import type { MandalaRuntime } from '../mandala/runtime'
170
+ import { MANDALA_BASKET } from '../mandala/types'
171
+ import { mandalaSettlementDeps, type CancelParkedSettlementDeps } from '../offline/cancelParked'
172
+ import { drainMandalaInbox } from '../pay/rails/handle'
173
+ import { forgetSessionPsks, sealedFramePayloadDecoder } from '../offline/tokenFrames'
145
174
  import { createServices, chaintracksUrlFor } from '../services/walletServiceConfig'
146
175
  import {
147
176
  boundReviewProvenTxs,
@@ -159,6 +188,8 @@ import {
159
188
  import { getExchangeRate } from '../services/exchangeRate'
160
189
  import { logWithTimestamp } from '../logging'
161
190
  import { recoverMnemonicWallet } from '../mnemonicWallet'
191
+ import { vaultStore } from '../services/vault/vaultStore'
192
+ import { guardVaultAccess } from '../services/vault/guard'
162
193
  import { StorageProvider, ChaintracksServiceClient } from '@bsv/wallet-toolbox-mobile'
163
194
  import { StorageExpoSQLite } from '../storage'
164
195
  import { makeBuildGeneration } from './buildGeneration'
@@ -169,6 +200,7 @@ import { getOnline, subscribeOnline } from '../net/online'
169
200
  import { canInternalizePending, processPending } from '../localpay/pending'
170
201
  import { replayPendingAborts } from '../localpay/pendingAborts'
171
202
  import { TaskSendOffline } from '../monitor/TaskSendOffline'
203
+ import { MONITOR_STALL_MS, MonitorSupervisor } from '../monitor/MonitorSupervisor'
172
204
  import { TaskCreditInbox } from '../monitor/TaskCreditInbox'
173
205
  import { drainUnsentEntries, TaskDrainOutbox } from '../monitor/TaskDrainOutbox'
174
206
  import { TaskBackupPush } from '../monitor/TaskBackupPush'
@@ -268,11 +300,13 @@ export interface WalletContextValue {
268
300
  protocolRequests: ProtocolAccessRequest[]
269
301
  spendingRequests: SpendingRequest[]
270
302
  btmsRequests: BtmsRequest[]
303
+ mandalaRequests: MandalaRequest[]
271
304
  advanceBasketQueue: () => void
272
305
  advanceCertificateQueue: () => void
273
306
  advanceProtocolQueue: () => void
274
307
  advanceSpendingQueue: () => void
275
308
  advanceBtmsQueue: (approved: boolean) => void
309
+ advanceMandalaQueue: (approved: boolean) => void
276
310
  finalizeConfig: (wabConfig: WABConfig) => boolean
277
311
  setConfigStatus: (status: ConfigStatus) => void
278
312
  configStatus: ConfigStatus
@@ -297,6 +331,24 @@ export interface WalletContextValue {
297
331
  * "import from backup" over an auto-created wallet). */
298
332
  rebuildWallet: (opts?: { restoreFromBackup?: boolean }) => Promise<void>
299
333
  storage: StorageExpoSQLite | null
334
+ /**
335
+ * Mandala stablecoins, or undefined.
336
+ *
337
+ * Undefined until the wallet is built, and on every chain the host has not
338
+ * stated endpoints for (mainnet only in v1) — so `mandala === undefined` is
339
+ * exactly "this wallet cannot do stablecoins right now", which is what the UI
340
+ * renders. Consumed through `useMandala()`; nothing above this context may
341
+ * reach `@bsv/mandala` directly.
342
+ */
343
+ mandala: MandalaRuntime | undefined
344
+ /**
345
+ * `cancelParkedPayment`'s `settlement` argument, pre-assembled from
346
+ * `mandala` (FIX J — an online cancel of an already-admitted token payment
347
+ * refuses with `'already-sent'` rather than aborting inputs the overlay
348
+ * considers spent). `undefined` exactly when `mandala` is, which is also
349
+ * the argument a plain BSV cancel needs — nothing else has to branch on it.
350
+ */
351
+ mandalaSettlement: CancelParkedSettlementDeps | undefined
300
352
  /** Fetch BUMP from WoC and store merkle proof, advancing tx status to completed */
301
353
  refreshProof: (txid: string) => Promise<'confirmed' | 'pending' | 'failed'>
302
354
  /** Peek OfflineFirstChaintracks.lastMissHeight for credit-error classification. Does not clear. */
@@ -338,11 +390,13 @@ export const WalletContext = createContext<WalletContextValue>({
338
390
  protocolRequests: [],
339
391
  spendingRequests: [],
340
392
  btmsRequests: [],
393
+ mandalaRequests: [],
341
394
  advanceBasketQueue: () => {},
342
395
  advanceCertificateQueue: () => {},
343
396
  advanceProtocolQueue: () => {},
344
397
  advanceSpendingQueue: () => {},
345
398
  advanceBtmsQueue: () => {},
399
+ advanceMandalaQueue: () => {},
346
400
  finalizeConfig: () => false,
347
401
  setConfigStatus: () => {},
348
402
  configStatus: 'initial',
@@ -356,6 +410,8 @@ export const WalletContext = createContext<WalletContextValue>({
356
410
  switchNetwork: async () => {},
357
411
  rebuildWallet: async () => {},
358
412
  storage: null,
413
+ mandala: undefined,
414
+ mandalaSettlement: undefined,
359
415
  refreshProof: async () => 'pending',
360
416
  peekLastMissHeight: () => undefined,
361
417
  txStatusVersion: 0,
@@ -448,6 +504,16 @@ type BtmsRequest = {
448
504
  resolve: (approved: boolean) => void
449
505
  }
450
506
 
507
+ /** Same shape as BtmsRequest — MandalaTokenModule's requestTokenAccess queue item. */
508
+ type MandalaRequest = {
509
+ /** The originator (dApp domain) requesting Mandala token access */
510
+ originator: string
511
+ /** The raw message from MandalaTokenModule (JSON-encoded promptData) */
512
+ message: string
513
+ /** Resolve the pending Promise from MandalaTokenModule — true = approved */
514
+ resolve: (approved: boolean) => void
515
+ }
516
+
451
517
  export interface WABConfig {
452
518
  wabUrl: string
453
519
  wabInfo?: any // Optional for noWAB (self-custodial) mode
@@ -518,7 +584,20 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
518
584
  // buildWallet's getAuth() call below). null until a wallet is built, or if
519
585
  // getAuth() fails — callers treat null as "unscoped" rather than a gate.
520
586
  const [walletUserId, setWalletUserId] = useState<number | null>(null)
587
+ /**
588
+ * The Mandala stablecoin runtime, or undefined — before the wallet is built,
589
+ * and on every chain but the one the host stated endpoints for (mainnet in
590
+ * v1). `useMandala()` reads this; nothing else in the app may reach the lib.
591
+ *
592
+ * The ref beside it is what the monitor tasks read. They are registered once,
593
+ * inside the build, and close over whatever the ref holds at the moment they
594
+ * run — so a rebuild or a network switch cannot leave a task draining the
595
+ * previous wallet's settlement tables.
596
+ */
597
+ const [mandala, setMandala] = useState<MandalaRuntime | undefined>(undefined)
598
+ const mandalaRef = useRef<MandalaRuntime | undefined>(undefined)
521
599
  const appStateRef = useRef<AppStateStatus>(AppState.currentState)
600
+ const monitorSupervisorRef = useRef<MonitorSupervisor | null>(null)
522
601
  const monitorRef = useRef<Monitor | null>(null)
523
602
  // The offline-first chain tracker and the header store it wraps. Populated
524
603
  // in buildWallet (tracker synchronously, store once the background open
@@ -737,6 +816,27 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
737
816
  [btmsQueue.enqueue]
738
817
  )
739
818
 
819
+ // Same usePermissionQueue pattern as BTMS above — a separate queue so a
820
+ // pending BTMS prompt and a pending Mandala prompt never resolve each
821
+ // other's promise.
822
+ const mandalaQueue = usePermissionQueue<MandalaRequest>(focusOpts)
823
+
824
+ const advanceMandalaQueue = useCallback(
825
+ (approved: boolean) => {
826
+ mandalaQueue.advance(head => head.resolve(approved))
827
+ },
828
+ [mandalaQueue.advance]
829
+ )
830
+
831
+ const mandalaPromptHandler = useCallback(
832
+ (originator: string, message: string): Promise<boolean> => {
833
+ return new Promise<boolean>(resolve => {
834
+ mandalaQueue.enqueue({ originator, message, resolve })
835
+ })
836
+ },
837
+ [mandalaQueue.enqueue]
838
+ )
839
+
740
840
  const updateSettings = useCallback(
741
841
  async (newSettings: WalletSettings) => {
742
842
  setSettings(newSettings)
@@ -969,6 +1069,11 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
969
1069
  const newManagers = {} as any
970
1070
  // Deliberately the ref, not the state: see selectedNetworkRef.
971
1071
  const chain = selectedNetworkRef.current
1072
+ // Mandala runs on exactly the chains the host stated endpoints for
1073
+ // (currently testnet only, see app/_layout.tsx): an overlay URL with no
1074
+ // verifiable identity key is an overlay whose admissions nothing can
1075
+ // check, so a partial entry reads as no entry at all (see toolboxConfig).
1076
+ const mandalaEndpoints = getMandalaEndpoints(chain)
972
1077
  // Toolbox chain id ('teratest' -> 'ttn'). App keeps 'teratest' for AsyncStorage keys / env / UI.
973
1078
  const walletChain = toWalletChain(chain)
974
1079
  // The backup log's network name. Distinct from walletChain ('ttn' for teratest):
@@ -993,7 +1098,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
993
1098
  // the single source of truth for these URLs — createServiceOptions
994
1099
  // calls the same function, so there is exactly one table to edit.
995
1100
  const remoteChaintracks = new ChaintracksServiceClient(walletChain, chaintracksUrlFor(chain))
996
- const offlineChaintracks = new OfflineFirstChaintracks(remoteChaintracks, getOnline)
1101
+ const offlineChaintracks = new OfflineFirstChaintracks(remoteChaintracks, getOnline, walletChain)
997
1102
  offlineChaintracksRef.current = offlineChaintracks
998
1103
 
999
1104
  // Passing offlineChaintracks here does two things, and createServices
@@ -1016,7 +1121,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1016
1121
 
1017
1122
  // Replace all default broadcast providers with EF/rawtx-only services.
1018
1123
  // Order: Arcade → Taal → GorillaPool → WoC → Bitails. UntilSuccess stops at first success.
1124
+ // 'ArcadeBeef' is the toolbox's own Arcade broadcaster, registered
1125
+ // because serviceOptions now carries arcadeUrl (needed for Arcade-first
1126
+ // proofs and SSE). Our createArcadeBroadcastService replaces it here so
1127
+ // the same tx is not posted to Arcade twice with two header sets.
1019
1128
  const bitailsService = (services as any).bitails
1129
+ services.postBeefServices.remove('ArcadeBeef')
1020
1130
  services.postBeefServices.remove('GorillaPoolArcBeef')
1021
1131
  services.postBeefServices.remove('TaalArcBeef')
1022
1132
  services.postBeefServices.remove('Bitails')
@@ -1038,7 +1148,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1038
1148
  }
1039
1149
 
1040
1150
  // Replace WoC getMerklePath with BUMP endpoint — no TSC→BUMP conversion needed.
1041
- // Remove all providers then re-add in order: WoC BUMP first, Bitails fallback.
1151
+ // The toolbox's 'Arcade' provider stays where Services put it: first.
1152
+ // Every tx this wallet sends goes through Arcade, so GET /v1/tx/{txid}
1153
+ // there is the one lookup that can answer as soon as it is mined. WoC
1154
+ // BUMP and Bitails are re-added after it as fallbacks, in that order.
1042
1155
  const wocBumpBase =
1043
1156
  chain === 'main'
1044
1157
  ? 'https://api.whatsonchain.com/v1/bsv/main'
@@ -1085,6 +1198,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1085
1198
  }
1086
1199
 
1087
1200
  const wallet = new Wallet(signer, services, undefined, privilegedKeyManager)
1201
+ // Consumed only by the toolbox storage-boundary hook. The value is set
1202
+ // by trusted host code and compared with WalletClient's originator;
1203
+ // external action fields cannot manufacture this authorization bit.
1204
+ Object.defineProperty(wallet, '__bsvVaultAdminOriginator', {
1205
+ value: adminOriginator,
1206
+ enumerable: false,
1207
+ configurable: false,
1208
+ writable: false
1209
+ })
1088
1210
 
1089
1211
  // Every write to the transaction/output tables refreshes the money on
1090
1212
  // screen immediately. The monitor's onTransactionStatusChanged only
@@ -1240,14 +1362,58 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1240
1362
  console.error('[WalletContext] Failed to add local storage provider:', error)
1241
1363
  }
1242
1364
 
1365
+ let migrationUserId: number | undefined
1243
1366
  try {
1244
1367
  const auth = await storageManager.getAuth()
1245
1368
  setWalletUserId(auth.userId ?? null)
1369
+ migrationUserId = auth.userId ?? undefined
1246
1370
  } catch {
1247
1371
  // Scoping is a filter, not a gate: with no id the queue reads fall
1248
1372
  // back to unscoped, which is today's behaviour.
1249
1373
  setWalletUserId(null)
1250
1374
  }
1375
+
1376
+ // One-time basket rename ('mandala-tokens' -> MANDALA_BASKET), run
1377
+ // after storage is attached (and any backup restore above has had
1378
+ // its chance to write old-named rows) so a restored device's rows
1379
+ // are migrated too, not just a freshly-created wallet's. Guarded
1380
+ // internally by its own key_value_store marker; the per-user pass
1381
+ // still runs on every build so a restored backup's old-named rows
1382
+ // are caught even after the marker is set. See offline-settlement-final.md §8.3.
1383
+ try {
1384
+ await migrateMandalaBasketName(phoneStorage, migrationUserId)
1385
+ } catch (error) {
1386
+ console.error('[WalletContext] Mandala basket migration failed:', error)
1387
+ }
1388
+
1389
+ // Hand `@bsv/mandala` this deployment's endpoints, this wallet's
1390
+ // basket, and a DURABLE journal store — before any lib call can run.
1391
+ //
1392
+ // The storage adapter is the load-bearing half. The lib's journals
1393
+ // are its recovery contract: an overlay-accepted, not-yet-broadcast
1394
+ // transaction is recoverable only because the 'accepted' entry
1395
+ // outlives the process that wrote it. React Native has no
1396
+ // localStorage, so a host that injects nothing here gets a
1397
+ // process-lifetime Map — i.e. no crash recovery at all — and the
1398
+ // failure is silent. See lib/src/storage.ts.
1399
+ //
1400
+ // `basket` is the wallet's own deviation from the lib default
1401
+ // ('mandala-tokens'): 'p mandala' is BRC-99 P-routed, which is what
1402
+ // puts every listOutputs/createAction/internalizeAction against it
1403
+ // through MandalaTokenModule regardless of originator (spec §8.3).
1404
+ if (mandalaEndpoints) {
1405
+ try {
1406
+ configureMandala({
1407
+ overlayUrl: mandalaEndpoints.overlayUrl,
1408
+ overlayIdentityKey: mandalaEndpoints.overlayIdentityKey,
1409
+ messageBoxUrl: mandalaEndpoints.messageBoxUrl,
1410
+ basket: MANDALA_BASKET,
1411
+ storage: createMandalaKvStorage(phoneStorage)
1412
+ })
1413
+ } catch (error) {
1414
+ console.error('[WalletContext] configureMandala failed:', error)
1415
+ }
1416
+ }
1251
1417
  }
1252
1418
  // TODO: Re-add remote storage support in future version
1253
1419
 
@@ -1255,6 +1421,39 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1255
1421
  // "p btms" operations surface a UI modal rather than silently denying.
1256
1422
  const btmsModule = loadBtmsPermissionModule().createBtmsModule({ wallet, promptHandler: btmsPromptHandler })
1257
1423
 
1424
+ // Adversarial-review finding (2): every outpoint this wallet holds in
1425
+ // MANDALA_BASKET, via the ADMIN-originator wallet -- i.e. this call
1426
+ // itself passes through MandalaTokenModule with zero prompts (the
1427
+ // module's own admin pass-through branch). Shared by the module's
1428
+ // deps below AND by wrapCreateActionForTokenInputs's wrapper further
1429
+ // down, so both use the exact same listing.
1430
+ const listMandalaTokenOutpoints = async (): Promise<Set<string>> => {
1431
+ try {
1432
+ const { outputs } = await wallet.listOutputs(
1433
+ { basket: MANDALA_BASKET, includeCustomInstructions: false, limit: 10000 } as never,
1434
+ adminOriginator
1435
+ )
1436
+ return new Set(outputs.map((o: { outpoint: string }) => o.outpoint))
1437
+ } catch {
1438
+ // A wallet with no Mandala basket yet, or a storage fault -- treat
1439
+ // as "no known token inputs" rather than blocking createAction;
1440
+ // see permissionModule.ts's doc on this dep failing open.
1441
+ return new Set()
1442
+ }
1443
+ }
1444
+
1445
+ // Mandala's own P-module (schemeID 'mandala', basket MANDALA_BASKET =
1446
+ // 'p mandala') -- same routing mechanism as BTMS above
1447
+ // (WalletPermissionsManager delegates by basket prefix regardless of
1448
+ // originator), but decodes Mandala's own script layout rather than
1449
+ // BTMS's PushDrop. See offline-settlement-final.md §8.
1450
+ const mandalaModule = new MandalaTokenModule({
1451
+ adminOriginator,
1452
+ requestTokenAccess: mandalaPromptHandler,
1453
+ resolveAssetMetadata: resolveMandalaAssetMetadata,
1454
+ listTokenOutpoints: listMandalaTokenOutpoints
1455
+ })
1456
+
1258
1457
  // Setup permissions with provided callbacks and BTMS module.
1259
1458
  const permissionsManager = new WalletPermissionsManager(wallet, adminOriginator, {
1260
1459
  differentiatePrivilegedOperations: true,
@@ -1276,7 +1475,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1276
1475
  seekProtocolPermissionsForHMAC: false,
1277
1476
  seekProtocolPermissionsForSigning: false,
1278
1477
  seekSpendingPermissions: true,
1279
- permissionModules: { btms: btmsModule }
1478
+ permissionModules: { btms: btmsModule, mandala: mandalaModule }
1280
1479
  } as any)
1281
1480
 
1282
1481
  if (protocolPermissionCallback) {
@@ -1292,7 +1491,90 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1292
1491
  permissionsManager.bindCallback('onCertificateAccessRequested', certificateAccessCallback)
1293
1492
  }
1294
1493
 
1295
- newManagers.permissionsManager = permissionsManager
1494
+ // Publish one idempotently guarded manager for both trusted in-app
1495
+ // Vault calls and external WalletClient calls. Admin output mutations
1496
+ // therefore share the guard's FIFO with external inventory scan+use;
1497
+ // external call sites may safely apply guardVaultAccess again.
1498
+ //
1499
+ // wrapCreateActionForTokenInputs wraps the RAW permissionsManager
1500
+ // FIRST, and guardVaultAccess is applied to ITS result (never the
1501
+ // other way around) -- adversarial-review finding (2):
1502
+ // WalletPermissionsManager only P-routes a createAction call whose
1503
+ // OUTPUTS or LABELS name a 'p ' scheme, never its inputs, so a
1504
+ // createAction that spends 'p mandala' inputs with no basketed/
1505
+ // decodable change output would otherwise reach
1506
+ // MandalaTokenModule.onRequest for exactly zero callers of this
1507
+ // manager. Wrapping outside-in (guard around this wrapper) would
1508
+ // instead break guardVaultAccess's own re-wrap dedup, which several
1509
+ // screens rely on (`guardVaultAccess(managers.permissionsManager,
1510
+ // ADMIN_ORIGINATOR)` again) -- see permissionModule.ts's wrapper doc
1511
+ // for the full mechanism.
1512
+ //
1513
+ // `wrapAbortActionForSettlements` goes on the same stack, for the same
1514
+ // reason and in the same place: inside `guardVaultAccess`, so the
1515
+ // published object stays the one the guard's dedup recognises. It is
1516
+ // the last line of defence for the 2026-09-15 incident — an
1517
+ // `abortAction` against a token payment the overlay has already
1518
+ // admitted (and therefore broadcast) releases inputs that are spent on
1519
+ // chain. It reads the settlement store LATE, off `mandalaRef`, because
1520
+ // the runtime is built below this line and replaced on every rebuild.
1521
+ newManagers.permissionsManager = guardVaultAccess(
1522
+ wrapAbortActionForSettlements(
1523
+ wrapCreateActionForTokenInputs(permissionsManager, listMandalaTokenOutpoints, adminOriginator),
1524
+ () => mandalaRef.current?.store
1525
+ ),
1526
+ adminOriginator
1527
+ )
1528
+
1529
+ // THE MANDALA RUNTIME'S ONE CONSTRUCTION SITE.
1530
+ //
1531
+ // Built here, after the permissions manager, because every lib call it
1532
+ // makes must go through the P-module gate — a runtime holding the raw
1533
+ // wallet would bypass exactly the routing §8.3 exists to establish. It
1534
+ // is published only when `available`: a runtime on a chain with no
1535
+ // endpoints could submit nowhere and verify nothing, and `undefined` is
1536
+ // what the UI already renders as "not on this network".
1537
+ if (phoneStorage) {
1538
+ try {
1539
+ const runtime = createMandalaRuntime({
1540
+ wallet: newManagers.permissionsManager as never,
1541
+ adminOriginator,
1542
+ storage: phoneStorage,
1543
+ chain,
1544
+ endpoints: mandalaEndpoints,
1545
+ // Lazy: constructing a runtime must do no I/O, and a wallet that
1546
+ // never touches stablecoins never opens a MessageBox connection.
1547
+ messageBox: mandalaEndpoints
1548
+ ? async () =>
1549
+ new MessageBoxClient({
1550
+ host: mandalaEndpoints.messageBoxUrl,
1551
+ // The client calls getPublicKey / createSignature itself;
1552
+ // those must carry the admin originator or the vault guard
1553
+ // refuses them ("Originator is required for permission checks").
1554
+ walletClient: bindOriginator(newManagers.permissionsManager as object, adminOriginator) as never,
1555
+ enableLogging: false
1556
+ }) as unknown as MandalaMessageBox
1557
+ : undefined,
1558
+ // The payer's own frames are sealed with a nearby session PSK the
1559
+ // drain never persists; this opens the ones whose session this
1560
+ // process still holds. See offline/tokenFrames.ts.
1561
+ decodeSealedFrame: sealedFramePayloadDecoder(),
1562
+ // The one thing `settleNow` asks about connectivity: whether a
1563
+ // hand-over that just landed should be followed by this device's
1564
+ // own submit now, or left to the drain. The runtime deliberately
1565
+ // has no NetInfo dependency of its own, so the app-wide probe is
1566
+ // handed to it here.
1567
+ isOnline: getOnline,
1568
+ refetchBeef: makeBeefRepair({ woc: wocConfigFor(chain), online: getOnline })
1569
+ })
1570
+ mandalaRef.current = runtime.available ? runtime : undefined
1571
+ setMandala(runtime.available ? runtime : undefined)
1572
+ } catch (error) {
1573
+ console.error('[WalletContext] could not build the Mandala runtime:', error)
1574
+ mandalaRef.current = undefined
1575
+ setMandala(undefined)
1576
+ }
1577
+ }
1296
1578
 
1297
1579
  // Start background monitor for transaction status updates (sending → unproven → completed)
1298
1580
  try {
@@ -1346,9 +1628,48 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1346
1628
  if (phoneStorage) {
1347
1629
  monitor.addTask(
1348
1630
  new TaskSendOffline(monitor, async () => {
1631
+ // FIX C recovery and the nearby-blinding reservation sweep ride
1632
+ // this same tick, ahead of the submit-then-broadcast pass below
1633
+ // so a row this recovers to `admitted` can broadcast in the
1634
+ // SAME pass rather than waiting for the next one. Read from the
1635
+ // ref for the same reason `token: mandalaRef.current?.tokenDeps`
1636
+ // is below — a rebuild replaces the runtime under a task
1637
+ // registered once. Both are best-effort and never throw.
1638
+ await mandalaRef.current?.recoverStaleAdmissions()
1639
+ // The 2026-09-15 repair: a settlement row that says the overlay
1640
+ // has the transaction, beside a wallet that failed it and
1641
+ // released its input coin as spendable although it is spent on
1642
+ // chain. Ahead of the release pass on purpose — a coin this
1643
+ // re-marks spent must not be planned into a send below.
1644
+ await mandalaRef.current?.repairAdmittedAborted()
1645
+ // The LIB's own journals, on the same tick and with the same
1646
+ // ref discipline: an overlay-accepted transfer whose broadcast
1647
+ // never went out, a liftable refusal still holding its inputs,
1648
+ // and the recipient notification a committed transfer owes its
1649
+ // payee. Nothing else in this wallet drives them — the
1650
+ // settlement drain below only knows `token_settlements` rows,
1651
+ // and the handle rail writes none of these entries. Never
1652
+ // throws (see `reconcileJournals`).
1653
+ await mandalaRef.current?.reconcileJournals()
1654
+ // The payer's handle-rail rows: no queue row exists for them,
1655
+ // so the release pass below would never step them. Each one
1656
+ // takes its `settleNow` step here instead (2026-09-15).
1657
+ await mandalaRef.current?.settlePendingSends()
1658
+ // Every held coin's σ_I on device, for the next offline hand-over.
1659
+ await mandalaRef.current?.ensureAdmissionsForHoldings()
1660
+ await mandalaRef.current?.pruneBlindingReservations()
1349
1661
  const r = await processOfflineActions({
1350
1662
  storage: phoneStorage!,
1351
- refetchBeef: makeBeefRepair({ woc: wocConfigFor(chain), online: getOnline })
1663
+ refetchBeef: makeBeefRepair({ woc: wocConfigFor(chain), online: getOnline }),
1664
+ // The settlement drain, on the same cadence and in the same
1665
+ // pass as the BSV release. That is the whole of §4.3: a token
1666
+ // transaction takes the ordinary plan's place in dependency
1667
+ // order and simply has `/submit` in front of its broadcast,
1668
+ // so the recipient's `held` rows and the payer's
1669
+ // `handed_over` rows both settle on every online tick.
1670
+ // Read from the ref, not captured: a rebuild replaces the
1671
+ // runtime under a task that was registered once.
1672
+ token: mandalaRef.current?.tokenDeps
1352
1673
  })
1353
1674
  // The drain writes transaction statuses directly, below the
1354
1675
  // monitor's onTransactionStatusChanged callback — bump the
@@ -1411,7 +1732,19 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1411
1732
  internalizeIncoming(permissionsManager as never, client, adminOriginator, p, repairBeef)
1412
1733
  )
1413
1734
  })
1414
- return { accepted: r.accepted, attention: r.attentionCount, pending: r.pending }
1735
+ // The SAME rail, a second box. A handle-rail token payment
1736
+ // is delivered into 'mandala-payments', not 'payment_inbox',
1737
+ // so a receive drain that read only the satoshi box would
1738
+ // leave real money sitting in the other one. Never throws
1739
+ // (see drainMandalaInbox) — a MessageBox fault on the token
1740
+ // side must not take the satoshi inbox down with it.
1741
+ const tokens = await drainMandalaInbox(mandalaRef.current)
1742
+ if (tokens.credited > 0) setTxStatusVersion(v => v + 1)
1743
+ return {
1744
+ accepted: r.accepted + tokens.credited,
1745
+ attention: r.attentionCount,
1746
+ pending: r.pending
1747
+ }
1415
1748
  },
1416
1749
  Date.now,
1417
1750
  () => {
@@ -1486,11 +1819,17 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1486
1819
  // the drain so the parent goes out first.
1487
1820
  if (phoneStorage) {
1488
1821
  const sendWaiting = monitor._tasks.find(t => t.name === 'SendWaiting') as
1489
- | { processUnsent?: (reqApis: Array<{ rawTx?: number[] }>, indent?: number) => Promise<string> }
1822
+ | { processUnsent?: (reqApis: Array<{ txid: string; rawTx?: number[] }>, indent?: number) => Promise<string> }
1490
1823
  | undefined
1491
1824
  if (sendWaiting?.processUnsent) {
1492
1825
  const orig = sendWaiting.processUnsent.bind(sendWaiting)
1493
- sendWaiting.processUnsent = async (reqApis, indent) => {
1826
+ sendWaiting.processUnsent = async (allReqApis, indent) => {
1827
+ // Guard #2 for this path: a request with a `token_settlements`
1828
+ // row is the settlement drain's to broadcast, after `/submit`,
1829
+ // never the monitor's. Held here and dropped from this pass.
1830
+ const heldTokenTxids = await phoneStorage.holdTokenReqsForDrain(allReqApis as never)
1831
+ const reqApis = heldTokenTxids.size > 0 ? allReqApis.filter(r => !heldTokenTxids.has(r.txid)) : allReqApis
1832
+ if (heldTokenTxids.size > 0) TaskSendOffline.requestNow()
1494
1833
  let queuedTxids = new Set<string>()
1495
1834
  try {
1496
1835
  const db = phoneStorage.sqliteDb
@@ -1509,7 +1848,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1509
1848
  }
1510
1849
  if (deferred > 0) TaskSendOffline.requestNow()
1511
1850
  if (ready.length === 0) {
1512
- return deferred > 0 ? `deferred ${deferred} req(s) behind queued ancestors\n` : ''
1851
+ const notes: string[] = []
1852
+ if (heldTokenTxids.size > 0) notes.push(`held ${heldTokenTxids.size} token req(s) for the settlement drain`)
1853
+ if (deferred > 0) notes.push(`deferred ${deferred} req(s) behind queued ancestors`)
1854
+ return notes.length > 0 ? `${notes.join('; ')}\n` : ''
1513
1855
  }
1514
1856
  return orig(ready, indent)
1515
1857
  }
@@ -1663,8 +2005,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1663
2005
  // otherwise "stop" a not-yet-started monitor and this callback
1664
2006
  // would then start an unstoppable zombie nothing references.
1665
2007
  if (monitorRef.current !== monitor) return
1666
- // startTasks runs in background — don't await (it never resolves until stopTasks)
1667
- monitor.startTasks().catch(e => console.error('[WalletContext] Monitor error:', e))
2008
+ // Not monitor.startTasks(): the supervisor drives the same pass
2009
+ // loop, but survives a throwing pass and can be restarted by the
2010
+ // watchdog below when a pass hangs. See MonitorSupervisor.
2011
+ const supervisor = new MonitorSupervisor()
2012
+ monitorSupervisorRef.current = supervisor
2013
+ supervisor.start(monitor)
1668
2014
  })
1669
2015
  logWithTimestamp(F, 'Monitor scheduled (ARC SSE) after interactions')
1670
2016
  } catch (error: any) {
@@ -1723,6 +2069,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1723
2069
  logWithTimestamp(F, 'Discarding a build the network switch overtook')
1724
2070
  return null
1725
2071
  }
2072
+ vaultStore.configureScope({ identityKey: keyDeriver.identityKey, chain: backupChain })
1726
2073
  updateManagers(m => ({ ...m, ...newManagers }))
1727
2074
  logWithTimestamp(F, 'Wallet build completed successfully')
1728
2075
 
@@ -1746,6 +2093,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1746
2093
  spendingAuthorizationCallback,
1747
2094
  certificateAccessCallback,
1748
2095
  btmsPromptHandler,
2096
+ mandalaPromptHandler,
1749
2097
  runHeaderSync,
1750
2098
  noteLedgerChanged,
1751
2099
  onToast
@@ -1925,6 +2273,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1925
2273
  restoreIntentRef.current = opts?.restoreFromBackup === true
1926
2274
  // Any build already in flight belongs to the configuration being replaced.
1927
2275
  const token = buildGenRef.current.bump()
2276
+ // Invalidate Vault operations before the first teardown await. Otherwise a
2277
+ // signer/listing already in flight can resume against the departing wallet.
2278
+ vaultStore.clearScope()
2279
+ vaultCeremony.cancel()
1928
2280
 
1929
2281
  // Stop any running monitor and let its current pass drain before the
1930
2282
  // storage teardown below closes the connection under it.
@@ -1952,8 +2304,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1952
2304
  // the screens reading the OLD chain's database until the new build
1953
2305
  // replaced it — which is how a testnet wallet displayed mainnet money.
1954
2306
  setStorage(null)
2307
+ // The runtime holds this build's settlement store, which is a handle on
2308
+ // the database just destroyed. Dropping it here is what stops a monitor
2309
+ // task or a screen draining the departed wallet's tables.
2310
+ mandalaRef.current = undefined
2311
+ setMandala(undefined)
2312
+ forgetSessionPsks()
1955
2313
 
1956
2314
  // Tear down current wallet state (but keep mnemonic / config)
2315
+ vaultStore.clearScope()
1957
2316
  updateManagers({})
1958
2317
  walletBuiltRef.current = false
1959
2318
  setWalletBuilt(false)
@@ -1980,6 +2339,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1980
2339
  if (network === selectedNetwork) return
1981
2340
  logWithTimestamp(F, `Switching network from ${selectedNetwork} to ${network}`)
1982
2341
  buildGenRef.current.bump()
2342
+ vaultStore.clearScope()
2343
+ vaultCeremony.cancel()
1983
2344
 
1984
2345
  // Stop any running monitor and let its current pass drain before the
1985
2346
  // storage teardown below closes the connection under it.
@@ -2002,8 +2363,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2002
2363
  } catch {}
2003
2364
  }
2004
2365
  setStorage(null)
2366
+ mandalaRef.current = undefined
2367
+ setMandala(undefined)
2368
+ forgetSessionPsks()
2005
2369
 
2006
2370
  // Tear down current wallet state (but keep mnemonic)
2371
+ vaultStore.clearScope()
2007
2372
  updateManagers({})
2008
2373
  walletBuiltRef.current = false
2009
2374
  setWalletBuilt(false)
@@ -2079,7 +2444,24 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2079
2444
  online = false
2080
2445
  }
2081
2446
  if (!canInternalizePending(online)) return
2082
- const results = await processPending(managers.permissionsManager as any, storage, adminOriginator)
2447
+ const results = await processPending(
2448
+ managers.permissionsManager as any,
2449
+ storage,
2450
+ adminOriginator,
2451
+ undefined,
2452
+ // A credited TOKEN frame is the moment this device becomes
2453
+ // responsible for submitting its chain (settlement rule 3), so the
2454
+ // row and the evidence the frame carried are written here — not
2455
+ // inside the queue, which knows nothing about settlement. Its own
2456
+ // failure is never the payment's: the coin is already credited, and
2457
+ // the drain re-derives what this missed on the next online tick.
2458
+ mandalaRef.current?.onTokenCredited,
2459
+ // The same facts, written BEFORE the internalize — which is the only
2460
+ // ordering the unadmitted-broadcast guard can actually read
2461
+ // (§4.3 guard #2). This one IS allowed to refuse the credit: the
2462
+ // frame stays durable in the queue and the next tick retries it.
2463
+ mandalaRef.current?.onTokenHeld
2464
+ )
2083
2465
  const successes = results.filter(r => r.success)
2084
2466
  if (successes.length > 0) {
2085
2467
  // The activity list and balance re-read on this version; without it
@@ -2242,6 +2624,35 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2242
2624
  })
2243
2625
  }, [walletBuilt])
2244
2626
 
2627
+ // Monitor watchdog. A pass loop that stops — a task's await that never
2628
+ // resolves, or a throw out of runOnce's own logging — leaves every unsent
2629
+ // request at 'sending' with nothing else in the app able to broadcast it
2630
+ // (2026-09-18: two BSV sends stuck until a force-quit). No completed pass
2631
+ // for MONITOR_STALL_MS while the app is active means the loop is gone;
2632
+ // restart it on the same monitor. 2 min, not 1: a healthy pass is ~5 s
2633
+ // apart but a slow network task can legitimately hold one for a while, and
2634
+ // restarting a healthy loop is the one thing this must never do.
2635
+ useEffect(() => {
2636
+ if (!walletBuilt) return
2637
+ const check = () => {
2638
+ if (AppState.currentState !== 'active') return
2639
+ const supervisor = monitorSupervisorRef.current
2640
+ if (!supervisor || monitorRef.current === null) return
2641
+ if (!supervisor.isStalled(MONITOR_STALL_MS)) return
2642
+ const stalledForMs = Date.now() - supervisor.lastPassAt
2643
+ console.warn(`[WalletContext] monitor loop stalled for ${Math.round(stalledForMs / 1000)}s; restarting it`)
2644
+ if (supervisor.restart()) {
2645
+ // Best-effort: the stalled pass may be holding the very connection this
2646
+ // writes to. Never awaited, never allowed to throw.
2647
+ monitorRef.current
2648
+ ?.logEvent('Watchdog', `restarted monitor loop after ${Math.round(stalledForMs / 1000)}s without a pass`)
2649
+ .catch(() => {})
2650
+ }
2651
+ }
2652
+ const interval = setInterval(check, 30_000)
2653
+ return () => clearInterval(interval)
2654
+ }, [walletBuilt])
2655
+
2245
2656
  // Fetch Arcade status events when app returns to foreground
2246
2657
  useEffect(() => {
2247
2658
  const subscription = AppState.addEventListener('change', (nextAppState: AppStateStatus) => {
@@ -2249,6 +2660,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2249
2660
  const isNowForeground = nextAppState === 'active'
2250
2661
 
2251
2662
  if (wasBackground && isNowForeground) {
2663
+ // The loop's timers were frozen with the app; the gap is the OS's, not
2664
+ // the monitor's. Without this the first watchdog check after a long
2665
+ // background would restart a healthy loop.
2666
+ monitorSupervisorRef.current?.touch()
2252
2667
  const monitor = monitorRef.current
2253
2668
  if (monitor) {
2254
2669
  monitor.fetchSSEEvents().then(count => {
@@ -2270,16 +2685,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2270
2685
  return () => subscription.remove()
2271
2686
  }, [])
2272
2687
 
2273
- // Relock-on-unplug, for PERSISTENT readers only (Android USB). Start discovery
2274
- // at launch and, when the key is pulled, tell the ceremony (its onRelock
2275
- // fires the close sound/haptic) so an armed or mid-signature vault session
2276
- // ends with the hardware rather than lingering.
2688
+ // Relock-on-unplug for injected persistent readers. Native iOS and Android
2689
+ // drivers are ceremony-scoped: the ceremony owns discovery and its listener
2690
+ // through signer release, including Android USB unplug events.
2277
2691
  //
2278
- // Session-based transports (iOS NFC) are skipped here: they have no persistent
2279
- // presence — the scan session is opened per ceremony and closed on arm — so
2280
- // starting discovery at launch would pop the NFC sheet, and a session-end
2281
- // "detach" is normal, not an unplug. The ceremony's own session-scoped
2282
- // listener (see ceremony.ts) handles relock there instead.
2692
+ // Session-based drivers are skipped here so no hardware reader or NFC sheet
2693
+ // is opened at launch. See ceremony.ts for their scoped listener lifecycle.
2283
2694
  useEffect(() => {
2284
2695
  const driver = getVaultDriver()
2285
2696
  if (!driver || driver.sessionBased) return
@@ -2316,11 +2727,17 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2316
2727
  monitorRef.current = null
2317
2728
  offlineChaintracksRef.current = undefined
2318
2729
  headerStoreRef.current = undefined
2730
+ vaultStore.clearScope()
2731
+ vaultCeremony.cancel()
2319
2732
  }
2320
2733
  }, [])
2321
2734
 
2322
2735
  const logout = useCallback(() => {
2323
2736
  logWithTimestamp(F, 'Logout')
2737
+ // Synchronous on purpose: invalidate transfer tokens and release any PIN /
2738
+ // hardware session before monitor or storage teardown yields.
2739
+ vaultStore.clearScope()
2740
+ vaultCeremony.cancel()
2324
2741
  ;(async () => {
2325
2742
  // Tear the wallet down the same way rebuildWallet does. Logout used to
2326
2743
  // skip this, which orphaned a running monitor AND left the SQLite
@@ -2343,7 +2760,11 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2343
2760
  } catch {}
2344
2761
  }
2345
2762
  setStorage(null)
2763
+ mandalaRef.current = undefined
2764
+ setMandala(undefined)
2765
+ forgetSessionPsks()
2346
2766
 
2767
+ vaultStore.clearScope()
2347
2768
  updateManagers({})
2348
2769
  setConfigStatus('initial')
2349
2770
  walletBuiltRef.current = false
@@ -2784,11 +3205,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2784
3205
  protocolRequests: protocolQueue.requests,
2785
3206
  spendingRequests: spendingQueue.requests,
2786
3207
  btmsRequests: btmsQueue.requests,
3208
+ mandalaRequests: mandalaQueue.requests,
2787
3209
  advanceBasketQueue: basketQueue.advance,
2788
3210
  advanceCertificateQueue: certificateQueue.advance,
2789
3211
  advanceProtocolQueue: protocolQueue.advance,
2790
3212
  advanceSpendingQueue: spendingQueue.advance,
2791
3213
  advanceBtmsQueue,
3214
+ advanceMandalaQueue,
2792
3215
  finalizeConfig,
2793
3216
  setConfigStatus,
2794
3217
  configStatus,
@@ -2802,6 +3225,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2802
3225
  switchNetwork,
2803
3226
  rebuildWallet,
2804
3227
  storage,
3228
+ mandala,
3229
+ mandalaSettlement: mandalaSettlementDeps(mandala),
2805
3230
  refreshProof,
2806
3231
  peekLastMissHeight,
2807
3232
  txStatusVersion,
@@ -2827,11 +3252,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2827
3252
  protocolQueue.requests,
2828
3253
  spendingQueue.requests,
2829
3254
  btmsQueue.requests,
3255
+ mandalaQueue.requests,
2830
3256
  basketQueue.advance,
2831
3257
  certificateQueue.advance,
2832
3258
  protocolQueue.advance,
2833
3259
  spendingQueue.advance,
2834
3260
  advanceBtmsQueue,
3261
+ advanceMandalaQueue,
2835
3262
  finalizeConfig,
2836
3263
  setConfigStatus,
2837
3264
  configStatus,
@@ -2845,6 +3272,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2845
3272
  switchNetwork,
2846
3273
  rebuildWallet,
2847
3274
  storage,
3275
+ mandala,
2848
3276
  refreshProof,
2849
3277
  peekLastMissHeight,
2850
3278
  txStatusVersion,
@@ -2923,11 +3351,13 @@ export interface WalletQueuesSlice {
2923
3351
  protocolRequests: ProtocolAccessRequest[]
2924
3352
  spendingRequests: SpendingRequest[]
2925
3353
  btmsRequests: BtmsRequest[]
3354
+ mandalaRequests: MandalaRequest[]
2926
3355
  advanceBasketQueue: () => void
2927
3356
  advanceCertificateQueue: () => void
2928
3357
  advanceProtocolQueue: () => void
2929
3358
  advanceSpendingQueue: () => void
2930
3359
  advanceBtmsQueue: (approved: boolean) => void
3360
+ advanceMandalaQueue: (approved: boolean) => void
2931
3361
  }
2932
3362
  export const useWalletQueues = (): WalletQueuesSlice => {
2933
3363
  const ctx = useContext(WalletContext)
@@ -2938,11 +3368,13 @@ export const useWalletQueues = (): WalletQueuesSlice => {
2938
3368
  protocolRequests: ctx.protocolRequests,
2939
3369
  spendingRequests: ctx.spendingRequests,
2940
3370
  btmsRequests: ctx.btmsRequests,
3371
+ mandalaRequests: ctx.mandalaRequests,
2941
3372
  advanceBasketQueue: ctx.advanceBasketQueue,
2942
3373
  advanceCertificateQueue: ctx.advanceCertificateQueue,
2943
3374
  advanceProtocolQueue: ctx.advanceProtocolQueue,
2944
3375
  advanceSpendingQueue: ctx.advanceSpendingQueue,
2945
- advanceBtmsQueue: ctx.advanceBtmsQueue
3376
+ advanceBtmsQueue: ctx.advanceBtmsQueue,
3377
+ advanceMandalaQueue: ctx.advanceMandalaQueue
2946
3378
  }),
2947
3379
  [
2948
3380
  ctx.basketRequests,
@@ -2950,11 +3382,13 @@ export const useWalletQueues = (): WalletQueuesSlice => {
2950
3382
  ctx.protocolRequests,
2951
3383
  ctx.spendingRequests,
2952
3384
  ctx.btmsRequests,
3385
+ ctx.mandalaRequests,
2953
3386
  ctx.advanceBasketQueue,
2954
3387
  ctx.advanceCertificateQueue,
2955
3388
  ctx.advanceProtocolQueue,
2956
3389
  ctx.advanceSpendingQueue,
2957
- ctx.advanceBtmsQueue
3390
+ ctx.advanceBtmsQueue,
3391
+ ctx.advanceMandalaQueue
2958
3392
  ]
2959
3393
  )
2960
3394
  }