@bsv/expo-wallet-toolbox 0.12.0 → 0.13.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 (53) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/core/backup/erase.ts +7 -1
  3. package/core/backup/preference.ts +12 -4
  4. package/core/backup/push.ts +8 -1
  5. package/core/backup/status.ts +6 -2
  6. package/core/context/WalletContext.tsx +841 -236
  7. package/core/i18n/translations.tsx +376 -0
  8. package/core/identity/handleRegistry/registration.ts +57 -3
  9. package/core/index.ts +24 -1
  10. package/core/mandala/createRuntime.ts +3 -3
  11. package/core/mandala/runtime.ts +7 -2
  12. package/core/mnemonicWallet.ts +46 -40
  13. package/core/monitor/MonitorSupervisor.ts +35 -1
  14. package/core/monitor/TaskCreditInbox.ts +24 -0
  15. package/core/pay/rails/handle.ts +4 -2
  16. package/core/peerpay/outbox.ts +11 -1
  17. package/core/profiles/assertProfileEmpty.ts +287 -0
  18. package/core/profiles/discovery.ts +84 -0
  19. package/core/profiles/profileLabel.ts +13 -0
  20. package/core/profiles/profileStore.ts +265 -0
  21. package/core/profiles/purgeProfile.ts +76 -0
  22. package/core/profiles/removeProfile.ts +257 -0
  23. package/core/push/events.ts +52 -5
  24. package/core/push/identities.ts +55 -0
  25. package/core/push/profilePush.ts +143 -0
  26. package/core/push/registration.ts +362 -24
  27. package/core/push/types.ts +5 -1
  28. package/core/services/arcTokenStorage.ts +17 -2
  29. package/core/services/vault/transfers.ts +6 -1
  30. package/core/services/vault/vaultStore.ts +16 -3
  31. package/core/stores/ConnectionStore.ts +11 -7
  32. package/core/toolboxConfig.ts +7 -3
  33. package/core/userAvatar.ts +12 -5
  34. package/core/walletDbRegistry.ts +73 -0
  35. package/package.json +1 -1
  36. package/ui/backupShares.ts +2 -3
  37. package/ui/components/pay/MessageBoxConfig.tsx +6 -5
  38. package/ui/components/ui/PencilEditField.tsx +5 -2
  39. package/ui/components/wallet/Balance.tsx +3 -1
  40. package/ui/components/wallet/ProfileButton.tsx +92 -18
  41. package/ui/components/wallet/ProfileSwitcherPopover.tsx +247 -0
  42. package/ui/hooks/useOfflineNoticeActions.ts +2 -1
  43. package/ui/hooks/useSpendableBalance.ts +3 -1
  44. package/ui/printRecoveryShares.ts +6 -7
  45. package/ui/screens/PairScreen.tsx +2 -1
  46. package/ui/screens/ProfileScreen.tsx +195 -4
  47. package/ui/screens/SettingsScreen.tsx +8 -4
  48. package/ui/screens/VaultScreen.tsx +31 -2
  49. package/ui/screens/VaultTransferScreen.tsx +25 -2
  50. package/ui/screens/WalletCheckScreen.tsx +2 -1
  51. package/ui/screens/WalletConfigScreen.tsx +51 -21
  52. package/ui/screens/WalletHomeScreen.tsx +6 -3
  53. package/ui/tokenSeen.ts +13 -9
@@ -29,9 +29,12 @@ import { backupAttestation } from '../services/vault/backupAttestation'
29
29
  * again on the closed handle. Draining first keeps teardown quiet. Bounded:
30
30
  * a hung task must not wedge logout/rebuild forever.
31
31
  */
32
- async function stopMonitorAndDrain(monitor: Monitor): Promise<void> {
32
+ async function stopMonitorAndDrain(monitor: Monitor, supervisor?: MonitorSupervisor | null): Promise<void> {
33
33
  try {
34
34
  monitor.stopTasks()
35
+ // Wake the supervisor's loop if it is sleeping between passes, so the drain
36
+ // below waits only for a pass in flight — not the rest of the interval.
37
+ supervisor?.wake()
35
38
  const running = (monitor as unknown as { _tasksRunningPromise?: Promise<void> })._tasksRunningPromise
36
39
  if (running) {
37
40
  await Promise.race([running, new Promise<void>(resolve => setTimeout(resolve, 7_000))])
@@ -136,13 +139,14 @@ const MANDALA_OUTPOINT_LIST_MAX_PAGES = 1000
136
139
 
137
140
  import type { AppChain } from '../config'
138
141
  import { DEFAULT_STORAGE_URL, DEFAULT_CHAIN, ADMIN_ORIGINATOR, toWalletChain } from '../config'
139
- import { getBackupUrl, getMandalaEndpoints, getPushAdapter } from '../toolboxConfig'
142
+ import { getBackupUrl, getHandleRegistryConfig, getMandalaEndpoints, getPushAdapter } from '../toolboxConfig'
140
143
  import {
141
144
  DEFAULT_AUTO_APPROVE_THRESHOLD,
142
145
  AUTO_APPROVE_COOLDOWN_MS,
143
146
  AUTO_APPROVE_STORAGE_KEY,
144
147
  AUTO_APPROVE_DAILY_CAP_SATS,
145
- AUTO_APPROVE_LEDGER_STORAGE_KEY
148
+ AUTO_APPROVE_LEDGER_STORAGE_KEY,
149
+ arcUrlStorageKey
146
150
  } from '../constants'
147
151
  import { createAutoApprovePolicy } from '../services/autoApprovePolicy'
148
152
  import { deriveCallbackToken } from '../services/callbackToken'
@@ -173,8 +177,10 @@ import { mandalaSettlementDeps, type CancelParkedSettlementDeps } from '../offli
173
177
  import { drainMandalaInbox } from '../pay/rails/handle'
174
178
  import { forgetSessionPsks, sealedFramePayloadDecoder } from '../offline/tokenFrames'
175
179
  import { disconnectActivePairedSession } from './WalletConnectionContext'
180
+ import connectionStore from '../stores/ConnectionStore'
181
+ import { loadUserAvatarIcon } from '../userAvatar'
176
182
  import { createServices, chaintracksUrlFor } from '../services/walletServiceConfig'
177
- import { getArcApiToken } from '../services/arcTokenStorage'
183
+ import { clearArcApiTokensForProfile, getArcApiToken } from '../services/arcTokenStorage'
178
184
  import {
179
185
  boundReviewProvenTxs,
180
186
  configureNewHeaderPolling,
@@ -191,6 +197,42 @@ import {
191
197
  import { getExchangeRate } from '../services/exchangeRate'
192
198
  import { logWithTimestamp } from '../logging'
193
199
  import { recoverMnemonicWallet } from '../mnemonicWallet'
200
+ import { backupProbe, discoverProfiles, registerDiscoveredProfile } from '../profiles/discovery'
201
+ import {
202
+ assertDatabasesEmpty,
203
+ assertOtherNetworksEmpty,
204
+ assertProfileEmpty,
205
+ combineEmpty,
206
+ type DatabasesEmptyDeps
207
+ } from '../profiles/assertProfileEmpty'
208
+ import { purgeProfile, purgeRemovedProfiles, type PurgeProfileIo } from '../profiles/purgeProfile'
209
+ import {
210
+ checkProfileRemoval as runProfileRemovalCheck,
211
+ removalRefusal,
212
+ removeProfileFlow,
213
+ type ProfileRemovalCheck,
214
+ type RemoveProfileDeps,
215
+ type RemoveProfileResult
216
+ } from '../profiles/removeProfile'
217
+ import { profileLabel } from '../profiles/profileLabel'
218
+ import { createHandleRegistryClient } from '../identity/handleRegistry/client'
219
+ import type { ProfileSigner } from '../identity/handleRegistry/profileCert'
220
+ import { releaseHandle, resumePending } from '../identity/handleRegistry/registration'
221
+ import {
222
+ appendProfile,
223
+ getActiveProfile,
224
+ getActiveProfileIndex,
225
+ getProfilesState,
226
+ liveProfiles,
227
+ loadProfiles,
228
+ profileScopedKey,
229
+ PROFILE_KEY_SUFFIX_RE,
230
+ resetProfiles,
231
+ setActiveProfile,
232
+ updateProfile,
233
+ useProfiles,
234
+ type ProfileRecord
235
+ } from '../profiles/profileStore'
194
236
  import { vaultStore } from '../services/vault/vaultStore'
195
237
  import { guardVaultAccess } from '../services/vault/guard'
196
238
  import { StorageProvider, ChaintracksServiceClient } from '@bsv/wallet-toolbox-mobile'
@@ -198,24 +240,35 @@ import { StorageExpoSQLite } from '../storage'
198
240
  import { makeBuildGeneration } from './buildGeneration'
199
241
  import * as SQLite from 'expo-sqlite'
200
242
  import {
243
+ getAllRegisteredDbs,
201
244
  getRegisteredDbs,
202
245
  purgeRegisteredDbFiles,
246
+ purgeIdentityDbFiles,
203
247
  registerDb,
204
248
  selectLatestDb,
205
249
  unregisterDb
206
250
  } from '../walletDbRegistry'
207
251
  import { AppState, AppStateStatus, InteractionManager } from 'react-native'
208
- import { getOnline, subscribeOnline } from '../net/online'
252
+ import { getOnline, probeOnline, subscribeOnline } from '../net/online'
209
253
  import { canInternalizePending, processPending } from '../localpay/pending'
210
254
  import { replayPendingAborts, verifyDeclinedAborts } from '../localpay/pendingAborts'
211
255
  import { TaskSendOffline } from '../monitor/TaskSendOffline'
212
256
  import { MONITOR_STALL_MS, MonitorSupervisor } from '../monitor/MonitorSupervisor'
213
- import { TaskCreditInbox } from '../monitor/TaskCreditInbox'
214
- import { attachPushHandlers, coalesceRuns } from '../push/events'
215
- import { syncPushRegistration } from '../push/registration'
257
+ import { mergeInboxResults, TaskCreditInbox, type CreditInboxTaskResult } from '../monitor/TaskCreditInbox'
258
+ import { attachPushHandlers } from '../push/events'
259
+ import {
260
+ authPostFor,
261
+ derivePushProfileKeys,
262
+ makePushProfile,
263
+ type PushProfile,
264
+ type PushProfileKey
265
+ } from '../push/identities'
266
+ import { createProfilePush, type ProfilePush } from '../push/profilePush'
267
+ import { PUSH_REGISTRATION_KEY, PUSH_REGISTRATION_OWNER_KEY, readPushMarkerIdentities } from '../push/registration'
216
268
  import { drainUnsentEntries, TaskDrainOutbox } from '../monitor/TaskDrainOutbox'
217
269
  import { TaskBackupPush } from '../monitor/TaskBackupPush'
218
270
  import { pushOnce } from '../backup/push'
271
+ import { BACKUP_PUSH_ENABLED_KEY } from '../backup/preference'
219
272
  import { restoreOnImport } from '../backup/restoreOnImport'
220
273
  import { backupPseudonym } from '../backup/derive'
221
274
  import type { BackupChain } from '../backup/constants'
@@ -283,24 +336,47 @@ const autoApprovePolicy = createAutoApprovePolicy({
283
336
  })
284
337
 
285
338
  // Best-effort persistence of the rolling ledger so an app restart does not
286
- // reset the daily cap. Loaded once per process; a read/write failure never
287
- // blocks a spend decision — the in-memory ledger stays authoritative either way.
288
- let autoApproveLedgerLoadedOnce = false
289
- async function loadAutoApproveLedgerOnce(): Promise<void> {
290
- if (autoApproveLedgerLoadedOnce) return
291
- autoApproveLedgerLoadedOnce = true
339
+ // reset the daily cap. The ledger belongs to one wallet profile: it is reloaded
340
+ // at startup and after every profile switch, replacing whatever the previous
341
+ // profile left in memory. A read/write failure never blocks a spend decision —
342
+ // the in-memory ledger stays authoritative either way.
343
+ async function reloadAutoApproveLedger(): Promise<void> {
344
+ let entries: unknown = []
292
345
  try {
293
- const stored = await AsyncStorage.getItem(AUTO_APPROVE_LEDGER_STORAGE_KEY)
294
- if (stored) {
295
- const parsed = JSON.parse(stored)
296
- if (Array.isArray(parsed)) autoApprovePolicy.loadLedger(parsed)
297
- }
346
+ const stored = await AsyncStorage.getItem(profileScopedKey(AUTO_APPROVE_LEDGER_STORAGE_KEY))
347
+ if (stored) entries = JSON.parse(stored)
298
348
  } catch {
299
- // No persisted ledger to restore — start with an empty one, same as today.
349
+ // No persisted ledger to restore — start with an empty one.
300
350
  }
351
+ autoApprovePolicy.loadLedger(Array.isArray(entries) ? entries : [])
301
352
  }
302
353
  function persistAutoApproveLedger(): void {
303
- AsyncStorage.setItem(AUTO_APPROVE_LEDGER_STORAGE_KEY, JSON.stringify(autoApprovePolicy.getLedger())).catch(() => {})
354
+ AsyncStorage.setItem(profileScopedKey(AUTO_APPROVE_LEDGER_STORAGE_KEY), JSON.stringify(autoApprovePolicy.getLedger())).catch(() => {})
355
+ }
356
+
357
+ /**
358
+ * An identity's wallet databases on every network, as the removal checks read
359
+ * them: the registry's list (less `except`, the one already checked through the
360
+ * open wallet) and a connection of their own per file.
361
+ */
362
+ const walletDatabasesOf = (identityKey: string, except?: string): DatabasesEmptyDeps => ({
363
+ list: async () => (await getAllRegisteredDbs(identityKey.slice(-8))).filter(file => file !== except),
364
+ open: filename => SQLite.openDatabaseAsync(filename)
365
+ })
366
+
367
+ /** The real stores behind a profile purge (core/profiles/purgeProfile), for a removal and for the startup retry. */
368
+ const profilePurgeIo: PurgeProfileIo = {
369
+ purgeDbFiles: async keySuffix => {
370
+ // A file that could not be deleted keeps its registry entry, because the
371
+ // startup retry finds the removed profile's files through it (see
372
+ // purgeIdentityDbFiles). `=== false`: only a purge that says so is unclean.
373
+ if ((await purgeIdentityDbFiles(keySuffix, SQLite.deleteDatabaseAsync, { keepFailed: true })) === false) {
374
+ throw new Error('a database file of the removed profile could not be deleted')
375
+ }
376
+ },
377
+ clearArcTokens: clearArcApiTokensForProfile,
378
+ getAllKeys: () => AsyncStorage.getAllKeys(),
379
+ removeKeys: keys => AsyncStorage.multiRemove(keys)
304
380
  }
305
381
 
306
382
  // -----
@@ -429,6 +505,34 @@ export interface WalletContextValue {
429
505
  * through to a post-storage-attach reconciliation pass (no remote replay) for a raw
430
506
  * database import that already carries a complete local database (XR-079). */
431
507
  rebuildWallet: (opts?: { restoreFromBackup?: boolean; reviewImportedCoins?: boolean }) => Promise<void>
508
+ /** Index of the active wallet profile (0 = default). See core/profiles/profileStore. */
509
+ activeProfile: number
510
+ /** Every profile on this device, dense by index. */
511
+ profiles: ProfileRecord[]
512
+ /** True once the active wallet was built from a mnemonic. A recovered-key wallet has no profiles. */
513
+ profilesSupported: boolean
514
+ /** Tear down the current profile's wallet and build profile `n` (its own keys, DB and network). */
515
+ switchProfile: (n: number) => Promise<void>
516
+ /** Append the next profile and switch to it, restoring its remote backup if one exists. */
517
+ addProfile: () => Promise<void>
518
+ /** A profile switch is in flight, from the tap until the new profile's wallet is built. */
519
+ switchingProfile: boolean
520
+ /** The profile being removed while a removal runs (its cover reads "Removing …"), else null. */
521
+ removingProfile: number | null
522
+ /**
523
+ * Whether the active profile could be removed right now: the guards, the proof
524
+ * that it holds nothing, and the handle that removal would release. Changes
525
+ * nothing, so the Profile screen can explain a refusal before it asks anyone
526
+ * to confirm. See core/profiles/removeProfile.
527
+ */
528
+ checkProfileRemoval: () => Promise<ProfileRemovalCheck>
529
+ /**
530
+ * Remove the active profile from this device and release its handle, then open
531
+ * profile 0. Re-runs every check itself: what was true when the user was asked
532
+ * to confirm may not be true now. Runs as a profile transition, so the cover
533
+ * shows. Never profile 0.
534
+ */
535
+ removeProfile: () => Promise<RemoveProfileResult>
432
536
  storage: StorageExpoSQLite | null
433
537
  /**
434
538
  * Mandala stablecoins, or undefined.
@@ -512,6 +616,15 @@ export const WalletContext = createContext<WalletContextValue>({
512
616
  getWalletBuilt: () => false,
513
617
  switchNetwork: async () => {},
514
618
  rebuildWallet: async () => {},
619
+ activeProfile: 0,
620
+ profiles: [{ index: 0, network: 'main' }],
621
+ profilesSupported: false,
622
+ switchProfile: async () => {},
623
+ addProfile: async () => {},
624
+ switchingProfile: false,
625
+ removingProfile: null,
626
+ checkProfileRemoval: async () => ({ kind: 'refused', reason: 'unsupported' }),
627
+ removeProfile: async () => ({ kind: 'refused', reason: 'unsupported' }),
515
628
  storage: null,
516
629
  mandala: undefined,
517
630
  mandalaSettlement: undefined,
@@ -721,6 +834,21 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
721
834
  // registers on return. Both are cleared wherever the monitor is torn down.
722
835
  const pushDetachRef = useRef<(() => void) | undefined>(undefined)
723
836
  const pushSyncRef = useRef<(() => Promise<void>) | undefined>(undefined)
837
+ // Every live profile registers this device for push, so the build keeps all
838
+ // of their signing identities. `profilePushRef` is this build's handle on
839
+ // them (sync, unregister, and which profile a push is for); the keys of the
840
+ // profiles that are NOT open are handed from buildWalletFromMnemonic to the
841
+ // build through `pushOtherProfileKeysRef`, because the wallet manager calls
842
+ // buildWallet with the open profile's keys only. Both are cleared wherever
843
+ // the monitor is torn down, and the keys are consumed by the build that reads them.
844
+ const profilePushRef = useRef<ProfilePush | undefined>(undefined)
845
+ const pushOtherProfileKeysRef = useRef<PushProfileKey[]>([])
846
+ // Reaches the public switch (with its cover) from the build, which is defined first.
847
+ const switchProfileRef = useRef<((n: number) => Promise<void>) | null>(null)
848
+ // This build's MessageBox credit pass: the very function the CreditInbox
849
+ // monitor task runs, held here so removing a profile can run one pass and see
850
+ // what it left. Set by the build, cleared wherever the monitor is torn down.
851
+ const creditInboxPassRef = useRef<(() => Promise<CreditInboxTaskResult>) | undefined>(undefined)
724
852
  // The offline-first chain tracker and the header store it wraps. Populated
725
853
  // in buildWallet (tracker synchronously, store once the background open
726
854
  // finishes); the reconnect top-up effect below reuses both rather than
@@ -909,12 +1037,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
909
1037
  g.__jsStallWatchdogTimer = setTimeout(tick, TICK)
910
1038
  }, [])
911
1039
  useEffect(() => {
912
- AsyncStorage.getItem(AUTO_APPROVE_STORAGE_KEY).then(v => {
1040
+ AsyncStorage.getItem(profileScopedKey(AUTO_APPROVE_STORAGE_KEY)).then(v => {
913
1041
  if (v !== null) autoApproveThresholdRef.current = Number(v) || 0
914
1042
  })
915
1043
  // Restores the rolling auto-approve ledger so an app restart does not
916
- // reset the daily cap (misc-p2-04). Best-effort — see loadAutoApproveLedgerOnce.
917
- loadAutoApproveLedgerOnce()
1044
+ // reset the daily cap (misc-p2-04). Best-effort — see reloadAutoApproveLedger.
1045
+ // Re-run (with the threshold) once the profile store loads; see the config effect.
1046
+ reloadAutoApproveLedger()
918
1047
  AsyncStorage.getItem('walletSettings').then(v => {
919
1048
  if (v) setSettings(prev => ({ ...prev, ...JSON.parse(v) }))
920
1049
  })
@@ -1091,8 +1220,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1091
1220
  // immediately (the mount-time ref read alone left the old value live
1092
1221
  // until app restart — felt like auto-approve was "stuck on").
1093
1222
  try {
1094
- const stored = await AsyncStorage.getItem(AUTO_APPROVE_STORAGE_KEY)
1095
- if (stored !== null) autoApproveThresholdRef.current = Number(stored) || 0
1223
+ const stored = await AsyncStorage.getItem(profileScopedKey(AUTO_APPROVE_STORAGE_KEY))
1224
+ // Unset means this profile never chose one: the default, never another profile's.
1225
+ autoApproveThresholdRef.current = stored !== null ? Number(stored) || 0 : DEFAULT_AUTO_APPROVE_THRESHOLD
1096
1226
  } catch {}
1097
1227
  const threshold = autoApproveThresholdRef.current
1098
1228
  autoApproveThresholdSnapshot = threshold
@@ -1159,6 +1289,23 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1159
1289
  const selectedNetworkRef = useRef<AppChain>(DEFAULT_CHAIN)
1160
1290
  selectedNetworkRef.current = selectedNetwork
1161
1291
  const [selectedStorageUrl, setSelectedStorageUrl] = useState<string>(DEFAULT_STORAGE_URL)
1292
+ // Wallet profiles (one mnemonic, many wallets). The store is module state so
1293
+ // key builders can read it synchronously; this subscribes the provider to it.
1294
+ const profilesState = useProfiles()
1295
+ const [profilesSupported, setProfilesSupported] = useState(false)
1296
+ /** Bumped to make the auto-build effect run again when nothing it otherwise
1297
+ * watches changes — a profile switch away from a failed build on the same
1298
+ * network leaves configStatus, walletBuilt and the network all as they were. */
1299
+ const [autoBuildRequest, setAutoBuildRequest] = useState(0)
1300
+ /** Single flight for profile switches. While set, the auto-build effect holds
1301
+ * off: teardown flips walletBuilt, and a build started before the new profile
1302
+ * and its network are in place would build the wrong wallet. */
1303
+ const profileTransitionRef = useRef(false)
1304
+ /** A whole switch or add, from the tap until its build lands (see runProfileTransition). */
1305
+ const switchInFlightRef = useRef(false)
1306
+ const [switchingProfile, setSwitchingProfile] = useState(false)
1307
+ /** The profile a removal is working on, for the cover's label; null the rest of the time. */
1308
+ const [removingProfile, setRemovingProfile] = useState<number | null>(null)
1162
1309
 
1163
1310
  // Flag that indicates configuration is complete. For returning users,
1164
1311
  // if a snapshot exists we auto-mark configComplete.
@@ -1177,17 +1324,46 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1177
1324
  return true
1178
1325
  }, [])
1179
1326
 
1327
+ /** Re-read the active profile's in-memory device state: the auto-approve
1328
+ * threshold and ledger, the avatar and the paired connections. At startup and
1329
+ * after every switch — each was read at import or mount time for whichever
1330
+ * profile was active then, and none may carry over to another profile. */
1331
+ const reloadProfileCaches = useCallback(
1332
+ () =>
1333
+ Promise.all([
1334
+ reloadAutoApproveLedger(),
1335
+ loadUserAvatarIcon(),
1336
+ connectionStore.reload(),
1337
+ AsyncStorage.getItem(profileScopedKey(AUTO_APPROVE_STORAGE_KEY))
1338
+ .then(v => {
1339
+ autoApproveThresholdRef.current = v !== null ? Number(v) || 0 : DEFAULT_AUTO_APPROVE_THRESHOLD
1340
+ })
1341
+ .catch(() => {})
1342
+ ]).then(() => undefined),
1343
+ []
1344
+ )
1345
+
1180
1346
  // Auto-configure on first launch: if no stored config, set defaults
1181
1347
  useEffect(() => {
1182
1348
  ;(async () => {
1183
1349
  if (configStatus !== 'initial') return
1350
+ // The active profile picks the network, keys and database, so it must be in
1351
+ // memory before anything builds. Per-profile caches that were read at import
1352
+ // or mount time (before this resolved) are re-read for the profile it names.
1353
+ await loadProfiles()
1354
+ // A removal that stopped between its tombstone and its purge (a crash, a
1355
+ // locked store) still has its history on disk: purge it again. Idempotent,
1356
+ // best effort, and never in the way of startup.
1357
+ void purgeRemovedProfiles(getProfilesState().profiles, profilePurgeIo).catch(() => {})
1358
+ await reloadProfileCaches()
1184
1359
  const storedConfig = await getItem('finalConfig')
1185
1360
  if (storedConfig) {
1186
1361
  try {
1187
1362
  const config = JSON.parse(storedConfig)
1188
- finalizeConfig(config)
1363
+ // The network lives on the active profile, not in finalConfig.
1364
+ finalizeConfig({ ...config, network: getActiveProfile().network })
1189
1365
  } catch {
1190
- finalizeConfig({ wabUrl: 'noWAB', method: 'mnemonic', network: DEFAULT_CHAIN, storageUrl: 'local' })
1366
+ finalizeConfig({ wabUrl: 'noWAB', method: 'mnemonic', network: getActiveProfile().network, storageUrl: 'local' })
1191
1367
  await setItem(
1192
1368
  'finalConfig',
1193
1369
  JSON.stringify({ wabUrl: 'noWAB', method: 'mnemonic', network: DEFAULT_CHAIN, storageUrl: 'local' })
@@ -1195,7 +1371,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1195
1371
  }
1196
1372
  } else {
1197
1373
  // First launch: auto-configure with defaults
1198
- finalizeConfig({ wabUrl: 'noWAB', method: 'mnemonic', network: DEFAULT_CHAIN, storageUrl: 'local' })
1374
+ finalizeConfig({ wabUrl: 'noWAB', method: 'mnemonic', network: getActiveProfile().network, storageUrl: 'local' })
1199
1375
  await setItem(
1200
1376
  'finalConfig',
1201
1377
  JSON.stringify({ wabUrl: 'noWAB', method: 'mnemonic', network: DEFAULT_CHAIN, storageUrl: 'local' })
@@ -1230,6 +1406,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1230
1406
  // conditional on the app still wanting THIS build by the time it gets there.
1231
1407
  const buildToken = buildGenRef.current.current()
1232
1408
  const stillWanted = () => buildGenRef.current.isCurrent(buildToken)
1409
+ // The profile this build belongs to. A switch bumps the build generation,
1410
+ // so a build that outlives its profile never reaches the record below.
1411
+ const profileIndex = getActiveProfileIndex()
1412
+ // The other profiles' push keys, taken now: they were set for THIS build
1413
+ // by buildWalletFromMnemonic, and a later build must not inherit them.
1414
+ const pushOtherProfileKeys = pushOtherProfileKeysRef.current
1415
+ pushOtherProfileKeysRef.current = []
1233
1416
  try {
1234
1417
  logWithTimestamp(F, 'Building wallet')
1235
1418
  const newManagers = {} as any
@@ -1264,7 +1447,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1264
1447
  // AsyncStorage under this same key) — only the URL, which is not a
1265
1448
  // credential, still lives in plain AsyncStorage.
1266
1449
  const [arcUrlOverride, arcApiTokenOverride] = await Promise.all([
1267
- AsyncStorage.getItem(`arc_custom_url_${chain}`),
1450
+ AsyncStorage.getItem(profileScopedKey(arcUrlStorageKey(chain))),
1268
1451
  getArcApiToken(chain)
1269
1452
  ])
1270
1453
 
@@ -1917,9 +2100,11 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1917
2100
  // The MessageBox host this wallet talks to, or undefined when the
1918
2101
  // user turned MessageBox off. One definition for the CreditInbox task
1919
2102
  // and the push registration below, so a device token is always
1920
- // registered on exactly the host the inbox reads.
1921
- const readMessageBoxHost = async (): Promise<string | undefined> => {
1922
- const saved = await AsyncStorage.getItem(MESSAGE_BOX_URL_KEY)
2103
+ // registered on exactly the host the inbox reads. The push
2104
+ // registration names the profile it is asking about; the inbox task
2105
+ // reads the open profile's.
2106
+ const readMessageBoxHost = async (index?: number): Promise<string | undefined> => {
2107
+ const saved = await AsyncStorage.getItem(profileScopedKey(MESSAGE_BOX_URL_KEY, index))
1923
2108
  return saved === NO_MESSAGE_BOX
1924
2109
  ? undefined
1925
2110
  : !saved || saved === LEGACY_MESSAGE_BOX_URL
@@ -2013,58 +2198,56 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2013
2198
  // Pessimistic: one idle drain clears it the first time we are online.
2014
2199
  TaskSendOffline.noteEnqueued()
2015
2200
 
2201
+ const creditInboxPass = async (): Promise<CreditInboxTaskResult> => {
2202
+ const messageBoxUrl = await readMessageBoxHost()
2203
+ if (!messageBoxUrl) return { accepted: 0, attention: 0, pending: false }
2204
+ let client: PeerPayClient
2205
+ try {
2206
+ client = new PeerPayClient({
2207
+ messageBoxHost: messageBoxUrl,
2208
+ walletClient: permissionsManager as never,
2209
+ originator: adminOriginator
2210
+ })
2211
+ } catch {
2212
+ return { accepted: 0, attention: 0, pending: false }
2213
+ }
2214
+ const repairBeef = makeBeefRepair({ woc: wocConfigFor(chain), online: getOnline })
2215
+ const classify = await makeCreditClassifier({
2216
+ getOnline,
2217
+ peekLastMissHeight: () => offlineChaintracks.peekLastMissHeight()
2218
+ })
2219
+ const r = await creditInboxOnce({
2220
+ client,
2221
+ messageBoxUrl,
2222
+ storage: phoneStorage!,
2223
+ classify,
2224
+ accept: payment =>
2225
+ acceptWithRetry(client, messageBoxUrl, payment, p =>
2226
+ internalizeIncoming(permissionsManager as never, client, adminOriginator, p, repairBeef)
2227
+ )
2228
+ })
2229
+ // The SAME rail, a second box. A handle-rail token payment
2230
+ // is delivered into 'mandala-payments', not 'payment_inbox',
2231
+ // so a receive drain that read only the satoshi box would
2232
+ // leave real money sitting in the other one. Never throws
2233
+ // (see drainMandalaInbox) — a MessageBox fault on the token
2234
+ // side must not take the satoshi inbox down with it.
2235
+ const drained = await drainMandalaInbox(mandalaRef.current)
2236
+ if (drained.credited > 0) setTxStatusVersion(v => v + 1)
2237
+ // A network with tokens whose runtime could not be built has a token
2238
+ // box nobody can read: that is no more an empty one than a box that
2239
+ // would not answer (see mergeInboxResults).
2240
+ const tokens = mandalaEndpoints && !mandalaRef.current ? { ...drained, incomplete: true } : drained
2241
+ return mergeInboxResults(r, tokens)
2242
+ }
2243
+ // The same function the removal flow runs as its inbox pass.
2244
+ creditInboxPassRef.current = creditInboxPass
2016
2245
  monitor.addTask(
2017
- new TaskCreditInbox(
2018
- monitor,
2019
- async () => {
2020
- const messageBoxUrl = await readMessageBoxHost()
2021
- if (!messageBoxUrl) return { accepted: 0, attention: 0, pending: false }
2022
- let client: PeerPayClient
2023
- try {
2024
- client = new PeerPayClient({
2025
- messageBoxHost: messageBoxUrl,
2026
- walletClient: permissionsManager as never,
2027
- originator: adminOriginator
2028
- })
2029
- } catch {
2030
- return { accepted: 0, attention: 0, pending: false }
2031
- }
2032
- const repairBeef = makeBeefRepair({ woc: wocConfigFor(chain), online: getOnline })
2033
- const classify = await makeCreditClassifier({
2034
- getOnline,
2035
- peekLastMissHeight: () => offlineChaintracks.peekLastMissHeight()
2036
- })
2037
- const r = await creditInboxOnce({
2038
- client,
2039
- messageBoxUrl,
2040
- storage: phoneStorage!,
2041
- classify,
2042
- accept: payment =>
2043
- acceptWithRetry(client, messageBoxUrl, payment, p =>
2044
- internalizeIncoming(permissionsManager as never, client, adminOriginator, p, repairBeef)
2045
- )
2046
- })
2047
- // The SAME rail, a second box. A handle-rail token payment
2048
- // is delivered into 'mandala-payments', not 'payment_inbox',
2049
- // so a receive drain that read only the satoshi box would
2050
- // leave real money sitting in the other one. Never throws
2051
- // (see drainMandalaInbox) — a MessageBox fault on the token
2052
- // side must not take the satoshi inbox down with it.
2053
- const tokens = await drainMandalaInbox(mandalaRef.current)
2054
- if (tokens.credited > 0) setTxStatusVersion(v => v + 1)
2055
- return {
2056
- accepted: r.accepted + tokens.credited,
2057
- attention: r.attentionCount,
2058
- pending: r.pending
2059
- }
2060
- },
2061
- Date.now,
2062
- () => {
2063
- if (isReceiveInboxFocused()) return
2064
- sounds.paymentReceive()
2065
- onToast?.(i18n.t('payment_arrived'), { type: 'success' })
2066
- }
2067
- )
2246
+ new TaskCreditInbox(monitor, creditInboxPass, Date.now, () => {
2247
+ if (isReceiveInboxFocused()) return
2248
+ sounds.paymentReceive()
2249
+ onToast?.(i18n.t('payment_arrived'), { type: 'success' })
2250
+ })
2068
2251
  )
2069
2252
  TaskCreditInbox.noteEnqueued()
2070
2253
 
@@ -2115,7 +2298,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2115
2298
  primaryKey,
2116
2299
  chain: backupChain,
2117
2300
  identityKey: keyDeriver.identityKey,
2118
- baseUrl: getBackupUrl()
2301
+ baseUrl: getBackupUrl(),
2302
+ // This build's profile, not whichever is active when the pass runs: a
2303
+ // drain that outlives a switch must read the departing profile's opt-out.
2304
+ profileIndex
2119
2305
  })
2120
2306
  })
2121
2307
  )
@@ -2312,15 +2498,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2312
2498
  // contention that contributes to watchdog/OOM kills on real devices.
2313
2499
  if (!stillWanted()) {
2314
2500
  try {
2315
- await stopMonitorAndDrain(monitor)
2501
+ await stopMonitorAndDrain(monitor, monitorSupervisorRef.current)
2316
2502
  } catch {}
2317
2503
  return null
2318
2504
  }
2319
2505
  monitorRef.current = monitor
2320
2506
 
2321
- // Push: a payment for this identity wakes the phone (the MessageBox
2322
- // host sends the FCM message), and a push only ever means "look at
2323
- // the inbox now" — the credit, sound and toast come from the
2507
+ // Push: a payment for any profile of this wallet wakes the phone (the
2508
+ // MessageBox host sends the FCM message), and a push only ever means
2509
+ // "look at the inbox now" — the credit, sound and toast come from the
2324
2510
  // CreditInbox pass registered above, so nothing is shown or credited
2325
2511
  // twice.
2326
2512
  //
@@ -2331,52 +2517,57 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2331
2517
  // Every teardown clears the refs before it yields, so a build that is
2332
2518
  // superseded after this line is cleaned up by whoever superseded it.
2333
2519
  //
2334
- // Registration reads the same host as the CreditInbox task and derives
2335
- // the identity key and the client's wallet from the SAME
2336
- // permissionsManager, so the token is bound to the identity the inbox
2337
- // is actually reading. Startup, token refresh and foreground can all
2338
- // fire it at once; coalesceRuns never runs two at a time and folds an
2520
+ // Every live profile registers this install's token as itself: the
2521
+ // open profile from the key this build was given, the others from the
2522
+ // keys buildWalletFromMnemonic derived, each signing in through a
2523
+ // ProtoWallet (see core/push/identities) and each at the MessageBox host
2524
+ // of its own profile. Startup, token refresh and foreground can all
2525
+ // fire the sync at once; it never runs twice at a time and folds an
2339
2526
  // overlapping burst into one rerun. Push is an enhancement: nothing
2340
2527
  // here may throw into the build.
2341
- if (phoneStorage) {
2342
- const syncPush = coalesceRuns(async () => {
2343
- const adapter = getPushAdapter()
2344
- if (!adapter) return
2345
- const host = await readMessageBoxHost()
2346
- let identityKey: string
2347
- try {
2348
- identityKey = (await permissionsManager.getPublicKey({ identityKey: true }, adminOriginator)).publicKey
2349
- } catch (e) {
2350
- console.warn(
2351
- `[push] could not read the identity key; skipping registration: ${e instanceof Error ? e.message : String(e)}`
2352
- )
2353
- return
2528
+ const pushAdapter = getPushAdapter()
2529
+ pushDetachRef.current?.()
2530
+ pushDetachRef.current = undefined
2531
+ if (phoneStorage && pushAdapter) {
2532
+ const isRemoved = (index: number) => !!getProfilesState().profiles[index]?.deleted
2533
+ const others = pushOtherProfileKeys.filter(k => k.index !== profileIndex)
2534
+ const profiles: PushProfile[] = [
2535
+ ...others.filter(k => !isRemoved(k.index)).map(k => makePushProfile(k.index, k.primaryKey)),
2536
+ makePushProfile(profileIndex, primaryKey)
2537
+ ]
2538
+ // Removed earlier, registration still on record: only asked to withdraw it.
2539
+ const retired: PushProfile[] = others
2540
+ .filter(k => isRemoved(k.index))
2541
+ .map(k => makePushProfile(k.index, k.primaryKey))
2542
+ const profilePush = createProfilePush({
2543
+ adapter: pushAdapter,
2544
+ profiles,
2545
+ retired,
2546
+ activeIndex: profileIndex,
2547
+ readHost: readMessageBoxHost,
2548
+ // Still this build's, and not removed: a removal tombstones its profile
2549
+ // right after the switch to profile 0, whose build holds the key.
2550
+ isCurrent: index => stillWanted() && !isRemoved(index),
2551
+ isRemoved,
2552
+ makeClient: (wallet, host) => new MessageBoxClient({ host, walletClient: wallet as never }),
2553
+ makePost: authPostFor
2554
+ })
2555
+ profilePushRef.current = profilePush
2556
+ pushSyncRef.current = profilePush.sync
2557
+ void profilePush.sync()
2558
+ pushDetachRef.current = attachPushHandlers({
2559
+ adapter: pushAdapter,
2560
+ requestInboxPass: () => TaskCreditInbox.requestNow(),
2561
+ openActivity: () => loadExpoRouter().router.push('/transactions'),
2562
+ onTokenRefresh: () => void profilePush.sync(),
2563
+ resolveInactiveProfile: recipient => profilePush.inactiveProfileFor(recipient),
2564
+ // The public switch, so the cover shows. It resolves without saying
2565
+ // whether it landed, so ask the store: the profile is open or it is not.
2566
+ switchProfile: async index => {
2567
+ await switchProfileRef.current?.(index)
2568
+ return getActiveProfileIndex() === index
2354
2569
  }
2355
- const result = await syncPushRegistration({
2356
- adapter,
2357
- host,
2358
- identityKey,
2359
- makeClient: h =>
2360
- new MessageBoxClient({
2361
- host: h,
2362
- walletClient: permissionsManager as never,
2363
- originator: adminOriginator
2364
- })
2365
- })
2366
- if (result === 'failed') console.warn('[push] device registration with the MessageBox host failed')
2367
2570
  })
2368
- pushSyncRef.current = syncPush
2369
- void syncPush()
2370
- const pushAdapter = getPushAdapter()
2371
- pushDetachRef.current?.()
2372
- pushDetachRef.current = pushAdapter
2373
- ? attachPushHandlers({
2374
- adapter: pushAdapter,
2375
- requestInboxPass: () => TaskCreditInbox.requestNow(),
2376
- openActivity: () => loadExpoRouter().router.push('/transactions'),
2377
- onTokenRefresh: () => void syncPush()
2378
- })
2379
- : undefined
2380
2571
  }
2381
2572
  InteractionManager.runAfterInteractions(() => {
2382
2573
  // Re-check identity: stopTasks() before startTasks() is a no-op
@@ -2449,7 +2640,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2449
2640
  logWithTimestamp(F, 'Discarding a build the network switch overtook')
2450
2641
  return null
2451
2642
  }
2452
- vaultStore.configureScope({ identityKey: keyDeriver.identityKey, chain: backupChain })
2643
+ vaultStore.configureScope({ identityKey: keyDeriver.identityKey, chain: backupChain, profileIndex })
2644
+ // The identity is public; Delete Wallet needs it to find this profile's
2645
+ // databases. Any restore this profile was waiting for has now run.
2646
+ void updateProfile(profileIndex, { identityKey: keyDeriver.identityKey, needsRestore: false })
2453
2647
  updateManagers(m => ({ ...m, ...newManagers }))
2454
2648
  logWithTimestamp(F, 'Wallet build completed successfully')
2455
2649
 
@@ -2492,6 +2686,33 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2492
2686
  * callback, which cannot name itself inside its own definition. */
2493
2687
  const buildFromMnemonicRef = useRef<((m?: string, o?: WalletBuildOptions) => Promise<void>) | null>(null)
2494
2688
 
2689
+ /** After a seed import, find the other profiles it backed up (see core/profiles/discovery).
2690
+ * Fire-and-forget: only the probe runs now; each profile restores on first switch. */
2691
+ const discoverProfilesRef = useRef<((mnemonic: string) => void) | null>(null)
2692
+ discoverProfilesRef.current = (mnemonic: string) => {
2693
+ const baseUrl = getBackupUrl()
2694
+ if (!baseUrl) return
2695
+ // Discovery outlives the build that started it; it must stop adding
2696
+ // profiles the moment this seed's store is gone (Delete Wallet, a replacing
2697
+ // import), or it would resurrect them into the next wallet's store.
2698
+ const owner = getProfilesState().profiles[0]?.identityKey
2699
+ const stillOwned = () => getProfilesState().profiles[0]?.identityKey === owner
2700
+ void discoverProfiles({
2701
+ mnemonic,
2702
+ probe: async (primaryKey, chain) => stillOwned() && (await backupProbe(baseUrl)(primaryKey, chain)),
2703
+ // A profile removed on this device stays removed (and does not end the search).
2704
+ skip: index => !!getProfilesState().profiles[index]?.deleted,
2705
+ register: async (index, network) => {
2706
+ // Idempotent: a second import of the same seed must not duplicate profiles.
2707
+ if (stillOwned()) await registerDiscoveredProfile(index, network)
2708
+ }
2709
+ })
2710
+ .then(n => {
2711
+ if (n > 0) logWithTimestamp(F, `Profile discovery registered ${n} profile(s)`)
2712
+ })
2713
+ .catch(err => console.warn('[WalletContext] profile discovery failed:', err))
2714
+ }
2715
+
2495
2716
  const buildWalletFromMnemonic = useCallback(
2496
2717
  async (providedMnemonic?: string, opts?: WalletBuildOptions) => {
2497
2718
  // Skip if wallet already built or a build is already in progress
@@ -2525,8 +2746,33 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2525
2746
  return
2526
2747
  }
2527
2748
 
2749
+ // A seed means profiles, whether or not this build succeeds: the switcher
2750
+ // must stay reachable so a profile that fails to build can be left.
2751
+ setProfilesSupported(true)
2752
+
2753
+ let profileIndex = getActiveProfileIndex()
2528
2754
  const __tRecoverStart = performance.now()
2529
- const { rootKey, primaryKey } = recoverMnemonicWallet(mnemonic)
2755
+ let { privilegedKey, primaryKey, identityKey } = recoverMnemonicWallet(mnemonic, '', profileIndex)
2756
+ // The profile store belongs to one seed. A seed installed without Delete
2757
+ // Wallet (a replacing import, a lost-key reset) must not inherit another
2758
+ // seed's profiles: if profile 0 is recorded under a different identity,
2759
+ // start over from this seed's profile 0.
2760
+ const recordedP0 = getProfilesState().profiles[0]?.identityKey
2761
+ if (recordedP0) {
2762
+ const p0Identity = profileIndex === 0 ? identityKey : recoverMnemonicWallet(mnemonic, '', 0).identityKey
2763
+ if (p0Identity && p0Identity !== recordedP0) {
2764
+ logWithTimestamp(F, 'Profile store belongs to another seed; resetting to profile 0')
2765
+ await resetProfiles()
2766
+ if (profileIndex !== 0) {
2767
+ profileIndex = 0
2768
+ ;({ privilegedKey, primaryKey, identityKey } = recoverMnemonicWallet(mnemonic, '', 0))
2769
+ }
2770
+ }
2771
+ }
2772
+ // Recorded now, not after the build: the database is registered (and a
2773
+ // restore may fill it) before the build finishes, and Delete Wallet finds
2774
+ // a profile's databases through this identity even if the build fails.
2775
+ if (identityKey) void updateProfile(profileIndex, { identityKey })
2530
2776
  if (__DEV__)
2531
2777
  console.warn(
2532
2778
  `[perf] recoverMnemonicWallet (PBKDF2+BIP32): ${(performance.now() - __tRecoverStart).toFixed(0)}ms`
@@ -2534,9 +2780,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2534
2780
 
2535
2781
  // The vault no longer routes through the PKM — the YubiKey signs vault
2536
2782
  // inputs directly. The toolbox still requires a privileged key manager,
2537
- // so this returns the plain root key. guardVaultAccess is what keeps
2538
- // non-admin originators away from it.
2539
- const privilegedKeyManager = new PrivilegedKeyManager(async () => rootKey, VAULT_RETENTION_MS)
2783
+ // so this returns the profile's own m/1'/n' key (never the BIP32 master,
2784
+ // which every profile would otherwise share). guardVaultAccess is what
2785
+ // keeps non-admin originators away from it.
2786
+ const privilegedKeyManager = new PrivilegedKeyManager(async () => privilegedKey, VAULT_RETENTION_MS)
2540
2787
 
2541
2788
  // Create SimpleWalletManager and provide keys for authentication
2542
2789
  const swm = new SimpleWalletManager(ADMIN_ORIGINATOR, buildWallet)
@@ -2548,6 +2795,43 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2548
2795
  // allows the import screen to continue without restoring on retry.
2549
2796
  if (opts !== undefined) restoreIntentRef.current = opts.restoreFromBackup === true
2550
2797
  if (opts !== undefined) reviewImportedCoinsRef.current = opts.reviewImportedCoins === true
2798
+ // A profile found by restore discovery, or just added, replays its own
2799
+ // remote backup on its first build — on whichever launch that happens.
2800
+ if (getProfilesState().profiles[profileIndex]?.needsRestore) restoreIntentRef.current = true
2801
+ // Captured before buildWallet consumes it: an import of profile 0 is what
2802
+ // triggers discovery of the other profiles this seed has backed up.
2803
+ const wantedRestore = restoreIntentRef.current
2804
+
2805
+ // Push registers every live profile, and only this function has the seed to
2806
+ // derive the ones that are not open (from one seed-to-root derivation). Set
2807
+ // before the keys go in, because providing both is what triggers
2808
+ // buildWallet, which takes them. Skipped when there is nothing to register
2809
+ // with or only one profile, and push is an enhancement: a derivation that
2810
+ // fails leaves the open profile as the only one registered.
2811
+ //
2812
+ // A removed profile whose registration could not be withdrawn at the time
2813
+ // (it still has a marker) is derived too, to ask again: only its signature
2814
+ // is needed, never a wallet.
2815
+ pushOtherProfileKeysRef.current = []
2816
+ if (getPushAdapter()) {
2817
+ try {
2818
+ const withMarker = new Set((await readPushMarkerIdentities()).map(k => k.toLowerCase()))
2819
+ const retired = getProfilesState()
2820
+ .profiles.filter(p => p.deleted && p.identityKey && withMarker.has(p.identityKey.toLowerCase()))
2821
+ .map(p => p.index)
2822
+ const others = [
2823
+ ...liveProfiles()
2824
+ .map(p => p.index)
2825
+ .filter(index => index !== profileIndex),
2826
+ ...retired
2827
+ ]
2828
+ pushOtherProfileKeysRef.current = derivePushProfileKeys(mnemonic, others)
2829
+ } catch (e) {
2830
+ console.warn(
2831
+ `[push] could not derive the other profiles' identities; only the open profile registers: ${e instanceof Error ? e.message : String(e)}`
2832
+ )
2833
+ }
2834
+ }
2551
2835
 
2552
2836
  // Provide the primary key and privileged key manager to authenticate the wallet
2553
2837
  await swm.providePrimaryKey(primaryKey)
@@ -2576,6 +2860,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2576
2860
  walletBuiltRef.current = true
2577
2861
  setWalletBuilt(true)
2578
2862
  setWalletBuilding(false)
2863
+ if (wantedRestore && profileIndex === 0) discoverProfilesRef.current?.(mnemonic)
2579
2864
 
2580
2865
  logWithTimestamp(F, 'Mnemonic wallet build completed')
2581
2866
  } catch (error: any) {
@@ -2583,6 +2868,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2583
2868
  // an auto-build on relaunch, which must not re-import over a live database.
2584
2869
  restoreIntentRef.current = false
2585
2870
  reviewImportedCoinsRef.current = false
2871
+ pushOtherProfileKeysRef.current = []
2586
2872
  walletBuildingRef.current = false
2587
2873
  setWalletBuilding(false)
2588
2874
  console.error('[WalletContext] Error building mnemonic wallet:', error)
@@ -2608,13 +2894,20 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2608
2894
  try {
2609
2895
  const recoveredKey = PrivateKey.fromWif(wif)
2610
2896
  const primaryKey = recoveredKey.toArray()
2897
+ // A recovered key is a single wallet: no seed, so no other profiles.
2898
+ setProfilesSupported(false)
2899
+ if (getProfilesState().profiles.length > 1 || getActiveProfileIndex() !== 0) await resetProfiles()
2611
2900
 
2612
- // Same plain-root-key manager as the mnemonic path — see the comment
2613
- // there. guardVaultAccess is what keeps non-admin originators away from it.
2901
+ // The recovered key doubles as the privileged key — there is no seed to
2902
+ // derive a separate one from. guardVaultAccess is what keeps non-admin
2903
+ // originators away from it.
2614
2904
  const privilegedKeyManager = new PrivilegedKeyManager(async () => recoveredKey, VAULT_RETENTION_MS)
2615
2905
 
2616
2906
  const swm = new SimpleWalletManager(ADMIN_ORIGINATOR, buildWallet)
2617
2907
 
2908
+ // A single wallet: the open profile is the only identity to register for push.
2909
+ pushOtherProfileKeysRef.current = []
2910
+
2618
2911
  // Same arming point as the mnemonic path — see the comment there.
2619
2912
  // An automatic build has no options: preserve the request armed by
2620
2913
  // rebuildWallet until buildWallet consumes it. Explicit false still
@@ -2648,6 +2941,70 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2648
2941
  [configStatus, buildWallet]
2649
2942
  )
2650
2943
 
2944
+ /**
2945
+ * Tear the built wallet down but keep the secrets and config: what
2946
+ * rebuildWallet, switchNetwork and switchProfile all share. The caller bumps
2947
+ * the build generation first. Everything up to the first await runs
2948
+ * synchronously, so in-flight Vault operations are invalidated before
2949
+ * anything can resume against the departing wallet.
2950
+ */
2951
+ const teardownBuiltWallet = useCallback(async () => {
2952
+ // Invalidate Vault operations before the first teardown await. Otherwise a
2953
+ // signer/listing already in flight can resume against the departing wallet.
2954
+ vaultStore.clearScope()
2955
+ vaultCeremony.cancel()
2956
+
2957
+ // Push listeners and the registration sync belong to the wallet being
2958
+ // torn down; nothing may fire them against it from here on.
2959
+ pushDetachRef.current?.()
2960
+ pushDetachRef.current = undefined
2961
+ pushSyncRef.current = undefined
2962
+ profilePushRef.current = undefined
2963
+ pushOtherProfileKeysRef.current = []
2964
+ creditInboxPassRef.current = undefined
2965
+
2966
+ // Stop any running monitor and let its current pass drain before the
2967
+ // storage teardown below closes the connection under it.
2968
+ {
2969
+ const monitor = monitorRef.current
2970
+ if (monitor) {
2971
+ monitorRef.current = null
2972
+ await stopMonitorAndDrain(monitor, monitorSupervisorRef.current)
2973
+ }
2974
+ }
2975
+ // Same convention as monitorRef above: clear so a stale deferred header
2976
+ // init or reconnect handler from the old build can't pair a leftover
2977
+ // store/tracker across the rebuild.
2978
+ offlineChaintracksRef.current = undefined
2979
+ headerStoreRef.current = undefined
2980
+
2981
+ // Close the current storage connection so the new build can open
2982
+ // whichever DB file the registry selects.
2983
+ if (storage?.db) {
2984
+ try {
2985
+ await storage.destroy()
2986
+ } catch {}
2987
+ }
2988
+ // And drop the handle with it. Leaving a destroyed storage in state kept
2989
+ // the screens reading the OLD chain's database until the new build
2990
+ // replaced it — which is how a testnet wallet displayed mainnet money.
2991
+ setStorage(null)
2992
+ // The runtime holds this build's settlement store, which is a handle on
2993
+ // the database just destroyed. Dropping it here is what stops a monitor
2994
+ // task or a screen draining the departed wallet's tables.
2995
+ mandalaRef.current = undefined
2996
+ setMandala(undefined)
2997
+ forgetSessionPsks()
2998
+
2999
+ // Tear down current wallet state (but keep mnemonic / config)
3000
+ vaultStore.clearScope()
3001
+ updateManagers({})
3002
+ walletBuiltRef.current = false
3003
+ setWalletBuilt(false)
3004
+ walletBuildingRef.current = false
3005
+ setWalletBuilding(false)
3006
+ }, [storage])
3007
+
2651
3008
  // Tear down the current wallet and re-trigger auto-build.
2652
3009
  // Used after DB import and internally by switchNetwork.
2653
3010
  const rebuildWallet = useCallback(
@@ -2661,62 +3018,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2661
3018
  reviewImportedCoinsRef.current = opts?.reviewImportedCoins === true
2662
3019
  // Any build already in flight belongs to the configuration being replaced.
2663
3020
  const token = buildGenRef.current.bump()
2664
- // Invalidate Vault operations before the first teardown await. Otherwise a
2665
- // signer/listing already in flight can resume against the departing wallet.
2666
- vaultStore.clearScope()
2667
- vaultCeremony.cancel()
2668
-
2669
- // Push listeners and the registration sync belong to the wallet being
2670
- // torn down; nothing may fire them against it from here on.
2671
- pushDetachRef.current?.()
2672
- pushDetachRef.current = undefined
2673
- pushSyncRef.current = undefined
2674
-
2675
- // Stop any running monitor and let its current pass drain before the
2676
- // storage teardown below closes the connection under it.
2677
- {
2678
- const monitor = monitorRef.current
2679
- if (monitor) {
2680
- monitorRef.current = null
2681
- await stopMonitorAndDrain(monitor)
2682
- }
2683
- }
2684
- // Same convention as monitorRef above: clear so a stale deferred header
2685
- // init or reconnect handler from the old build can't pair a leftover
2686
- // store/tracker across the rebuild.
2687
- offlineChaintracksRef.current = undefined
2688
- headerStoreRef.current = undefined
2689
-
2690
- // Close the current storage connection so the new build can open
2691
- // whichever DB file the registry selects.
2692
- if (storage?.db) {
2693
- try {
2694
- await storage.destroy()
2695
- } catch {}
2696
- }
2697
- // And drop the handle with it. Leaving a destroyed storage in state kept
2698
- // the screens reading the OLD chain's database until the new build
2699
- // replaced it — which is how a testnet wallet displayed mainnet money.
2700
- setStorage(null)
2701
- // The runtime holds this build's settlement store, which is a handle on
2702
- // the database just destroyed. Dropping it here is what stops a monitor
2703
- // task or a screen draining the departed wallet's tables.
2704
- mandalaRef.current = undefined
2705
- setMandala(undefined)
2706
- forgetSessionPsks()
2707
-
2708
- // Tear down current wallet state (but keep mnemonic / config)
2709
- vaultStore.clearScope()
2710
- updateManagers({})
2711
- walletBuiltRef.current = false
2712
- setWalletBuilt(false)
2713
- walletBuildingRef.current = false
2714
- setWalletBuilding(false)
3021
+ await teardownBuiltWallet()
2715
3022
 
2716
3023
  // Re-finalize with current config — triggers auto-build effect
2717
3024
  const config = { wabUrl: 'noWAB', method: 'mnemonic', network: selectedNetwork, storageUrl: 'local' }
2718
3025
  pendingAutoBuildRef.current = true
2719
3026
  finalizeConfig(config)
3027
+ // Rebuilding after a failed build changes nothing the auto-build effect
3028
+ // watches; see autoBuildRequest.
3029
+ setAutoBuildRequest(r => r + 1)
2720
3030
  logWithTimestamp(F, 'Wallet rebuild triggered')
2721
3031
  // finalizeConfig above only requests the rebuild; without this,
2722
3032
  // rebuildWallet's promise resolved before the auto-build effect had even
@@ -2726,72 +3036,282 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2726
3036
  // wallet actually existing, such as recording a backup attestation.
2727
3037
  await waitForRebuild(token)
2728
3038
  },
2729
- [selectedNetwork, storage, finalizeConfig, waitForRebuild]
3039
+ [selectedNetwork, teardownBuiltWallet, finalizeConfig, waitForRebuild]
2730
3040
  )
2731
3041
 
2732
- // Switch network: tear down wallet, update config, and rebuild on new chain
3042
+ // Switch network: tear down wallet, update config, and rebuild on new chain.
3043
+ // The network belongs to the active profile, so this changes that profile's.
2733
3044
  const switchNetwork = useCallback(
2734
3045
  async (network: AppChain) => {
2735
- if (network === selectedNetwork) return
3046
+ if (network === selectedNetwork || switchInFlightRef.current) return
2736
3047
  logWithTimestamp(F, `Switching network from ${selectedNetwork} to ${network}`)
2737
3048
  buildGenRef.current.bump()
2738
- vaultStore.clearScope()
2739
- vaultCeremony.cancel()
3049
+ // Same hold-off as switchProfile: no build may start on the old network
3050
+ // between teardown's walletBuilt flip and finalizeConfig below.
3051
+ profileTransitionRef.current = true
3052
+ const newConfig = { wabUrl: 'noWAB', method: 'mnemonic', network, storageUrl: 'local' }
3053
+ try {
3054
+ await teardownBuiltWallet()
2740
3055
 
2741
- // Push listeners and the registration sync belong to the wallet being
2742
- // torn down; nothing may fire them against it from here on.
2743
- pushDetachRef.current?.()
2744
- pushDetachRef.current = undefined
2745
- pushSyncRef.current = undefined
3056
+ // Persist new config
3057
+ await updateProfile(getActiveProfileIndex(), { network })
3058
+ await setItem('finalConfig', JSON.stringify(newConfig))
2746
3059
 
2747
- // Stop any running monitor and let its current pass drain before the
2748
- // storage teardown below closes the connection under it.
2749
- {
2750
- const monitor = monitorRef.current
2751
- if (monitor) {
2752
- monitorRef.current = null
2753
- await stopMonitorAndDrain(monitor)
2754
- }
3060
+ // Re-finalize with new network — the request below triggers the auto-build effect
3061
+ finalizeConfig(newConfig)
3062
+ } finally {
3063
+ profileTransitionRef.current = false
2755
3064
  }
2756
- // Same convention as monitorRef above: clear so the old chain's
2757
- // tracker/store can't linger and get paired against the new chain.
2758
- offlineChaintracksRef.current = undefined
2759
- headerStoreRef.current = undefined
3065
+ setAutoBuildRequest(r => r + 1)
3066
+ logWithTimestamp(F, `Network switched to ${network}`)
3067
+ },
3068
+ [selectedNetwork, setItem, teardownBuiltWallet, finalizeConfig]
3069
+ )
2760
3070
 
2761
- // Close the current storage connection
2762
- if (storage?.db) {
2763
- try {
2764
- await storage.destroy()
2765
- } catch {}
3071
+ /**
3072
+ * Switch to wallet profile `n`: its own keys (m/0'/n', m/1'/n'), database,
3073
+ * network and per-profile settings. A profile awaiting restore replays its
3074
+ * remote backup during this build (see buildWalletFromMnemonic).
3075
+ *
3076
+ * Single flight: a second switch (or add) while one is running is ignored,
3077
+ * and the auto-build effect holds off until the new profile and its network
3078
+ * are fully in place — otherwise teardown's walletBuilt flip could start a
3079
+ * build of the wrong profile or on the wrong network. The generation bump
3080
+ * comes before any await, so a build already running for the old profile
3081
+ * never publishes; the store only flips AFTER teardown, so the departing
3082
+ * wallet never reads the new profile's settings.
3083
+ *
3084
+ * If the new profile fails to build (typically: its first restore could not
3085
+ * reach the backup server), the previous profile is rebuilt and the failure
3086
+ * is reported, so a switch never strands the user on an unusable wallet.
3087
+ */
3088
+ const switchProfileImpl = useCallback(
3089
+ async (n: number, opts: { fallback?: boolean } = {}): Promise<boolean> => {
3090
+ const from = getActiveProfileIndex()
3091
+ const record = getProfilesState().profiles[n]
3092
+ if (!record) throw new Error(`Unknown profile index: ${n}`)
3093
+ if (record.deleted) throw new Error(`Profile ${n} was removed`)
3094
+ logWithTimestamp(F, `Switching profile ${from} → ${n}`)
3095
+ const __t0 = performance.now()
3096
+ const token = buildGenRef.current.bump()
3097
+ restoreIntentRef.current = false
3098
+ reviewImportedCoinsRef.current = false
3099
+ // Pairings belong to the departing identity.
3100
+ disconnectActivePairedSession()
3101
+ profileTransitionRef.current = true
3102
+ try {
3103
+ await teardownBuiltWallet()
3104
+ const __tTeardown = performance.now()
3105
+ await setActiveProfile(n)
3106
+ await reloadProfileCaches()
3107
+ await setItem(
3108
+ 'finalConfig',
3109
+ JSON.stringify({ wabUrl: 'noWAB', method: 'mnemonic', network: record.network, storageUrl: 'local' })
3110
+ )
3111
+ if (__DEV__) {
3112
+ console.warn(
3113
+ `[perf] switchProfile teardown ${(__tTeardown - __t0).toFixed(0)}ms, ` +
3114
+ `store+caches ${(performance.now() - __tTeardown).toFixed(0)}ms`
3115
+ )
3116
+ }
3117
+ pendingAutoBuildRef.current = true
3118
+ finalizeConfig({ wabUrl: 'noWAB', method: 'mnemonic', network: record.network, storageUrl: 'local' })
3119
+ } finally {
3120
+ profileTransitionRef.current = false
2766
3121
  }
2767
- setStorage(null)
2768
- mandalaRef.current = undefined
2769
- setMandala(undefined)
2770
- forgetSessionPsks()
3122
+ setAutoBuildRequest(r => r + 1)
3123
+ const __tBuild = performance.now()
3124
+ await waitForRebuild(token)
3125
+ if (__DEV__) {
3126
+ console.warn(
3127
+ `[perf] switchProfile build ${(performance.now() - __tBuild).toFixed(0)}ms, ` +
3128
+ `total ${(performance.now() - __t0).toFixed(0)}ms`
3129
+ )
3130
+ }
3131
+ if (walletBuiltRef.current || !buildGenRef.current.isCurrent(token)) return true
2771
3132
 
2772
- // Tear down current wallet state (but keep mnemonic)
2773
- vaultStore.clearScope()
2774
- updateManagers({})
2775
- walletBuiltRef.current = false
2776
- setWalletBuilt(false)
2777
- walletBuildingRef.current = false
2778
- setWalletBuilding(false)
3133
+ if (opts.fallback !== false && from !== n) {
3134
+ logWithTimestamp(F, `Profile ${n} failed to build; returning to profile ${from}`)
3135
+ onToast?.(t('profile_switch_failed', { profile: profileLabel(record, t) }), { type: 'error' })
3136
+ await switchProfileImplRef.current?.(from, { fallback: false })
3137
+ }
3138
+ return false
3139
+ },
3140
+ [teardownBuiltWallet, reloadProfileCaches, setItem, finalizeConfig, waitForRebuild, onToast, t]
3141
+ )
3142
+ const switchProfileImplRef = useRef<typeof switchProfileImpl | null>(null)
3143
+ switchProfileImplRef.current = switchProfileImpl
3144
+
3145
+ /** One switch or add at a time, reported through `switchingProfile` from the tap until the build lands. */
3146
+ const runProfileTransition = useCallback(async (work: () => Promise<unknown>) => {
3147
+ if (switchInFlightRef.current) return
3148
+ switchInFlightRef.current = true
3149
+ setSwitchingProfile(true)
3150
+ try {
3151
+ await work()
3152
+ } finally {
3153
+ switchInFlightRef.current = false
3154
+ setSwitchingProfile(false)
3155
+ }
3156
+ }, [])
2779
3157
 
2780
- // Persist new config
2781
- const newConfig = { wabUrl: 'noWAB', method: 'mnemonic', network, storageUrl: 'local' }
2782
- await setItem('finalConfig', JSON.stringify(newConfig))
3158
+ const switchProfile = useCallback(
3159
+ async (n: number) => {
3160
+ const record = getProfilesState().profiles[n]
3161
+ if (n === getActiveProfileIndex() || !record || record.deleted) return
3162
+ await runProfileTransition(() => switchProfileImpl(n))
3163
+ },
3164
+ [runProfileTransition, switchProfileImpl]
3165
+ )
3166
+ switchProfileRef.current = switchProfile
3167
+
3168
+ /** Append the next profile on mainnet and switch to it. If this seed already
3169
+ * backed that profile up (a profile discovery missed), its history comes back. */
3170
+ const addProfile = useCallback(async () => {
3171
+ if (!profilesSupported) return
3172
+ await runProfileTransition(async () => {
3173
+ const record = await appendProfile('main', { needsRestore: true })
3174
+ await switchProfileImpl(record.index)
3175
+ })
3176
+ }, [profilesSupported, runProfileTransition, switchProfileImpl])
2783
3177
 
2784
- // Re-finalize with new network — this triggers the auto-build effect
2785
- finalizeConfig(newConfig)
2786
- logWithTimestamp(F, `Network switched to ${network}`)
3178
+ /**
3179
+ * Withdraw a removed profile's device registration so the phone stops being
3180
+ * woken for an identity it no longer shows. Called once the profile is
3181
+ * tombstoned and purged, best effort: it never rejects and is bounded in time,
3182
+ * so the removal neither fails for it nor waits long on it. It works from what
3183
+ * the device recorded when it registered, so the purge having swept the
3184
+ * profile's own settings does not matter. The registration is withdrawn
3185
+ * through the build that holds the profile's signing identity (the switch to
3186
+ * profile 0 built it while the profile was still live). A withdrawal that does
3187
+ * not get through leaves the profile's marker on record, and the next build
3188
+ * derives the profile's key again to ask once more (see buildWalletFromMnemonic):
3189
+ * with no such build now, the marker simply waits for that.
3190
+ */
3191
+ const unregisterRemovedProfilePush = useCallback(
3192
+ async (target: { index: number; identityKey: string }): Promise<void> => {
3193
+ await profilePushRef.current?.unregister([target.identityKey])
2787
3194
  },
2788
- [selectedNetwork, setItem, storage, finalizeConfig]
3195
+ []
2789
3196
  )
2790
3197
 
3198
+ /**
3199
+ * Everything the removal flow needs, captured NOW. The open storage, the user
3200
+ * id, the signer and the inbox pass all change under a switch, and a flow that
3201
+ * read them late would be asking the next profile's wallet. The flow itself
3202
+ * (core/profiles/removeProfile) decides nothing about this device: it only
3203
+ * calls what is handed to it here.
3204
+ */
3205
+ const makeRemovalDeps = useCallback((): RemoveProfileDeps => {
3206
+ const index = getActiveProfileIndex()
3207
+ const network = getProfilesState().profiles[index]?.network ?? selectedNetwork
3208
+ const openStorage = storage
3209
+ const userId = walletUserId
3210
+ const permissionsManager = getManagers().permissionsManager
3211
+ const creditInbox = creditInboxPassRef.current
3212
+ const runtime = mandalaRef.current
3213
+ const registry = getHandleRegistryConfig(network)
3214
+ const client = registry
3215
+ ? createHandleRegistryClient({ pinned: { domain: registry.domain, url: registry.url } })
3216
+ : null
3217
+ // Bound to the admin originator, like the Profile screen's: signing our own
3218
+ // certificate must never raise a permission prompt.
3219
+ const signer = permissionsManager
3220
+ ? (bindOriginator(permissionsManager, adminOriginator) as unknown as ProfileSigner)
3221
+ : null
3222
+ const registration = client && signer && openStorage ? { client, signer, storage: openStorage } : null
3223
+
3224
+ return {
3225
+ index,
3226
+ supported: profilesSupported,
3227
+ activeIndex: getActiveProfileIndex,
3228
+ record: () => getProfilesState().profiles[index],
3229
+ ready: () => walletBuiltRef.current && !!openStorage && userId !== null && !!creditInbox && !!permissionsManager,
3230
+ // NetInfo's "offline" is a cached snapshot on iOS; believe it only if a live request agrees.
3231
+ online: async () => (await getOnline()) || (await probeOnline()),
3232
+ liveIdentityKey: async () =>
3233
+ (await permissionsManager?.getPublicKey({ identityKey: true }, adminOriginator))?.publicKey,
3234
+ // A release that timed out leaves a journal behind, which the emptiness
3235
+ // check would then refuse: finish it first. Only "no answer" leaves it open.
3236
+ settleHandleJournal: async () => (registration ? (await resumePending(registration)).kind !== 'pending' : true),
3237
+ checkEmpty: async identityKey => {
3238
+ if (!openStorage || userId === null || !creditInbox) return { ok: false, reasons: ['check-failed'] }
3239
+ const open = await assertProfileEmpty(openStorage, userId, {
3240
+ creditInbox: async () => {
3241
+ const pass = await creditInbox()
3242
+ // A token box that could not be read is an inbox nobody has looked
3243
+ // into, which is not an empty one: the check cannot be made.
3244
+ if (pass.incomplete) throw new Error('the token inbox could not be read')
3245
+ // Not told means not known: a missing flag blocks, as a pending one does.
3246
+ return { attention: pass.attention, pending: pass.pending !== false }
3247
+ },
3248
+ mandalaBalances: runtime ? () => runtime.balances() : undefined
3249
+ })
3250
+ // The open storage is one network's database, and the removal deletes the
3251
+ // profile's databases on every network: look into the rest.
3252
+ const rest = await assertOtherNetworksEmpty(identityKey, walletDatabasesOf(identityKey, openStorage.dbName))
3253
+ return combineEmpty(open, rest)
3254
+ },
3255
+ // No registry for this network: no handle can exist, so there is nothing to release.
3256
+ lookupHandle: async identityKey => {
3257
+ if (!client) return { kind: 'none' }
3258
+ const seen = await client.lookupProfile(identityKey)
3259
+ return seen.kind === 'found' ? { kind: 'found', paymail: seen.profile.paymail } : { kind: seen.kind }
3260
+ },
3261
+ releaseHandle: async paymail =>
3262
+ registration ? releaseHandle(registration, { paymail }) : { kind: 'unavailable' as const },
3263
+ // The normal switch: it also disconnects the paired session before anything
3264
+ // is torn down. Built and on profile 0 is what "landed" means.
3265
+ switchToDefault: async () => (await switchProfileImpl(0)) && walletBuiltRef.current,
3266
+ // The profile's wallet is down now: every one of its databases, from the files.
3267
+ checkClosed: identityKey => assertDatabasesEmpty(identityKey, walletDatabasesOf(identityKey)),
3268
+ tombstone: identityKey => updateProfile(index, { deleted: true, identityKey }),
3269
+ purge: async target => {
3270
+ await purgeProfile(target, profilePurgeIo)
3271
+ },
3272
+ unregisterPush: unregisterRemovedProfilePush
3273
+ }
3274
+ }, [
3275
+ selectedNetwork,
3276
+ storage,
3277
+ walletUserId,
3278
+ getManagers,
3279
+ adminOriginator,
3280
+ profilesSupported,
3281
+ switchProfileImpl,
3282
+ unregisterRemovedProfilePush
3283
+ ])
3284
+
3285
+ const checkProfileRemoval = useCallback(async (): Promise<ProfileRemovalCheck> => {
3286
+ if (switchInFlightRef.current) return { kind: 'refused', reason: 'busy' }
3287
+ return runProfileRemovalCheck(makeRemovalDeps())
3288
+ }, [makeRemovalDeps])
3289
+
3290
+ const removeProfile = useCallback(async (): Promise<RemoveProfileResult> => {
3291
+ // Before the transition, which would otherwise answer a second tap with
3292
+ // nothing at all (it ignores a call made while one is running).
3293
+ if (switchInFlightRef.current) return { kind: 'refused', reason: 'busy' }
3294
+ const deps = makeRemovalDeps()
3295
+ const refusal = removalRefusal(deps)
3296
+ if (refusal) return { kind: 'refused', reason: refusal }
3297
+ let result: RemoveProfileResult = { kind: 'refused', reason: 'busy' }
3298
+ await runProfileTransition(async () => {
3299
+ setRemovingProfile(deps.index)
3300
+ try {
3301
+ result = await removeProfileFlow(deps)
3302
+ } finally {
3303
+ setRemovingProfile(null)
3304
+ }
3305
+ })
3306
+ return result
3307
+ }, [makeRemovalDeps, runProfileTransition])
3308
+
2791
3309
  // Auto-build wallet for returning users (mnemonic first, then recovered key).
2792
3310
  // Sets walletBuilding=true eagerly so other parts of the app (index.tsx
2793
3311
  // navigation) know not to react as if no wallet exists.
2794
3312
  useEffect(() => {
3313
+ // A profile switch is mid-way: it requests the build itself once ready.
3314
+ if (profileTransitionRef.current) return
2795
3315
  if (configStatus !== 'configured' || walletBuilt) return
2796
3316
  // Signal that a build attempt is starting. buildWalletFromMnemonic /
2797
3317
  // buildWalletFromRecoveredKey will clear this flag on completion or error.
@@ -2822,7 +3342,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2822
3342
  }
2823
3343
  }
2824
3344
  })()
2825
- }, [configStatus, walletBuilt, secretsReady, buildWalletFromMnemonic, buildWalletFromRecoveredKey, getRecoveredKey])
3345
+ }, [
3346
+ configStatus,
3347
+ walletBuilt,
3348
+ secretsReady,
3349
+ buildWalletFromMnemonic,
3350
+ buildWalletFromRecoveredKey,
3351
+ getRecoveredKey,
3352
+ autoBuildRequest
3353
+ ])
2826
3354
 
2827
3355
  // Settings are AsyncStorage-only — no on-chain sync needed
2828
3356
 
@@ -3184,6 +3712,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3184
3712
  pushDetachRef.current?.()
3185
3713
  pushDetachRef.current = undefined
3186
3714
  pushSyncRef.current = undefined
3715
+ profilePushRef.current = undefined
3716
+ pushOtherProfileKeysRef.current = []
3717
+ creditInboxPassRef.current = undefined
3187
3718
  if (ledgerBumpTimerRef.current) {
3188
3719
  clearTimeout(ledgerBumpTimerRef.current)
3189
3720
  ledgerBumpTimerRef.current = null
@@ -3198,6 +3729,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3198
3729
 
3199
3730
  const logout = useCallback((): Promise<boolean> => {
3200
3731
  logWithTimestamp(F, 'Logout')
3732
+ // A build still running for the departing wallet must never publish (nor
3733
+ // record its identity into the fresh profile store).
3734
+ buildGenRef.current.bump()
3201
3735
  // Synchronous on purpose: invalidate transfer tokens and release any PIN /
3202
3736
  // hardware session before monitor or storage teardown yields.
3203
3737
  vaultStore.clearScope()
@@ -3218,6 +3752,16 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3218
3752
  pushDetachRef.current?.()
3219
3753
  pushDetachRef.current = undefined
3220
3754
  pushSyncRef.current = undefined
3755
+ const profilePush = profilePushRef.current
3756
+ profilePushRef.current = undefined
3757
+ pushOtherProfileKeysRef.current = []
3758
+ creditInboxPassRef.current = undefined
3759
+ // The phone must stop being woken for identities this wallet no longer has:
3760
+ // withdraw every profile's registration, started now while the build's
3761
+ // signing identities are still in hand and awaited before the sweep below
3762
+ // takes the markers it works from. Best effort and bounded in time, so a
3763
+ // server that does not answer cannot hold Delete Wallet. It never rejects.
3764
+ const pushUnregistered = profilePush?.unregister()
3221
3765
 
3222
3766
  // Tear the wallet down the same way rebuildWallet does. Logout used to
3223
3767
  // skip this, which orphaned a running monitor AND left the SQLite
@@ -3229,7 +3773,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3229
3773
  const monitor = monitorRef.current
3230
3774
  if (monitor) {
3231
3775
  monitorRef.current = null
3232
- await stopMonitorAndDrain(monitor)
3776
+ await stopMonitorAndDrain(monitor, monitorSupervisorRef.current)
3233
3777
  }
3234
3778
  }
3235
3779
  offlineChaintracksRef.current = undefined
@@ -3255,6 +3799,26 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3255
3799
  console.warn('[logout] failed to purge wallet db file(s)/registry', err)
3256
3800
  }
3257
3801
  }
3802
+ // Every wallet profile is part of this wallet: purge each one's databases
3803
+ // on every network (and its ARC token), not just the one that was open.
3804
+ // A profile discovered but never built here has no identity recorded and
3805
+ // so no database on this device.
3806
+ for (const profile of getProfilesState().profiles) {
3807
+ if (profile.identityKey) {
3808
+ try {
3809
+ await purgeIdentityDbFiles(profile.identityKey.slice(-8), SQLite.deleteDatabaseAsync)
3810
+ } catch (err) {
3811
+ console.warn(`[logout] failed to purge profile ${profile.index} db file(s)`, err)
3812
+ }
3813
+ }
3814
+ await clearArcApiTokensForProfile(profile.index)
3815
+ }
3816
+ // Back to a single default profile BEFORE configStatus resets below: that
3817
+ // re-runs the startup config effect, which must not reload the departed
3818
+ // wallet's profile (and its network) from storage. Reset even if the
3819
+ // secret erasure further down fails — those databases are already gone.
3820
+ await resetProfiles()
3821
+ setProfilesSupported(false)
3258
3822
  setStorage(null)
3259
3823
  mandalaRef.current = undefined
3260
3824
  setMandala(undefined)
@@ -3292,6 +3856,30 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3292
3856
  // across a logout/re-import on the same install (see deviceId.ts and XR-009), so an
3293
3857
  // unscoped Wallet Check read would otherwise inherit it. Sweeps every identity's
3294
3858
  // cursor, not just the one just logged out of, same as the balance-cache sweep above.
3859
+ // Every non-default profile's device state (avatar, connections, ARC and
3860
+ // MessageBox overrides, auto-approve, caches) lives under a `__p<n>` key.
3861
+ //
3862
+ // The backup opt-out is per profile, so profile 0's bare key goes too: the next
3863
+ // wallet built here starts with backup ON instead of inheriting this one's opt-out.
3864
+ //
3865
+ // The push registration markers (identity keys and the token) are not
3866
+ // profile-scoped and belong to this wallet too. The unregistration started above
3867
+ // works from them, so it is finished before they go.
3868
+ await pushUnregistered
3869
+ try {
3870
+ const keys = await AsyncStorage.getAllKeys()
3871
+ const stale = keys.filter(
3872
+ k =>
3873
+ PROFILE_KEY_SUFFIX_RE.test(k) ||
3874
+ k === BACKUP_PUSH_ENABLED_KEY ||
3875
+ k === PUSH_REGISTRATION_KEY ||
3876
+ k === PUSH_REGISTRATION_OWNER_KEY
3877
+ )
3878
+ if (stale.length > 0) await AsyncStorage.multiRemove(stale)
3879
+ } catch (err) {
3880
+ console.warn('[logout] failed to clear profile state', err)
3881
+ }
3882
+
3295
3883
  try {
3296
3884
  const keys = await AsyncStorage.getAllKeys()
3297
3885
  const stale = keys.filter(k => k.startsWith('backupCursor-'))
@@ -3844,6 +4432,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3844
4432
  getWalletBuilt,
3845
4433
  switchNetwork,
3846
4434
  rebuildWallet,
4435
+ activeProfile: profilesState.active,
4436
+ profiles: profilesState.profiles,
4437
+ profilesSupported,
4438
+ switchProfile,
4439
+ addProfile,
4440
+ switchingProfile,
4441
+ removingProfile,
4442
+ checkProfileRemoval,
4443
+ removeProfile,
3847
4444
  storage,
3848
4445
  mandala,
3849
4446
  mandalaSettlement: mandalaSettlementDeps(mandala),
@@ -3895,6 +4492,14 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3895
4492
  getWalletBuilt,
3896
4493
  switchNetwork,
3897
4494
  rebuildWallet,
4495
+ profilesState,
4496
+ profilesSupported,
4497
+ switchProfile,
4498
+ addProfile,
4499
+ switchingProfile,
4500
+ removingProfile,
4501
+ checkProfileRemoval,
4502
+ removeProfile,
3898
4503
  storage,
3899
4504
  mandala,
3900
4505
  refreshProof,