@bsv/expo-wallet-toolbox 0.11.8 → 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 (62) hide show
  1. package/CHANGELOG.md +159 -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/config.tsx +1 -1
  7. package/core/context/WalletContext.tsx +904 -184
  8. package/core/i18n/translations.tsx +496 -12
  9. package/core/identity/handleRegistry/registration.ts +57 -3
  10. package/core/index.ts +26 -1
  11. package/core/mandala/createRuntime.ts +3 -3
  12. package/core/mandala/runtime.ts +7 -2
  13. package/core/mnemonicWallet.ts +46 -40
  14. package/core/monitor/MonitorSupervisor.ts +35 -1
  15. package/core/monitor/TaskCreditInbox.ts +24 -0
  16. package/core/pay/beefRepair.ts +8 -3
  17. package/core/pay/rails/address.ts +43 -3
  18. package/core/pay/rails/handle.ts +5 -3
  19. package/core/pay/sweeper.ts +39 -4
  20. package/core/peerpay/outbox.ts +11 -1
  21. package/core/profiles/assertProfileEmpty.ts +287 -0
  22. package/core/profiles/discovery.ts +84 -0
  23. package/core/profiles/profileLabel.ts +13 -0
  24. package/core/profiles/profileStore.ts +265 -0
  25. package/core/profiles/purgeProfile.ts +76 -0
  26. package/core/profiles/removeProfile.ts +257 -0
  27. package/core/push/events.ts +189 -0
  28. package/core/push/identities.ts +55 -0
  29. package/core/push/profilePush.ts +143 -0
  30. package/core/push/pushAdvisory.ts +33 -0
  31. package/core/push/registration.ts +391 -0
  32. package/core/push/types.ts +35 -0
  33. package/core/services/arcTokenStorage.ts +17 -2
  34. package/core/services/vault/transfers.ts +6 -1
  35. package/core/services/vault/vaultStore.ts +16 -3
  36. package/core/stores/ConnectionStore.ts +11 -7
  37. package/core/toolboxConfig.ts +31 -4
  38. package/core/userAvatar.ts +12 -5
  39. package/core/walletDbRegistry.ts +73 -0
  40. package/package.json +1 -1
  41. package/ui/backupShares.ts +2 -3
  42. package/ui/components/pay/HandleReceive.tsx +141 -16
  43. package/ui/components/pay/MessageBoxConfig.tsx +6 -5
  44. package/ui/components/pay/NotificationAdvisoryModal.tsx +124 -0
  45. package/ui/components/ui/PencilEditField.tsx +5 -2
  46. package/ui/components/wallet/Balance.tsx +3 -1
  47. package/ui/components/wallet/ProfileButton.tsx +92 -18
  48. package/ui/components/wallet/ProfileSwitcherPopover.tsx +247 -0
  49. package/ui/hooks/useOfflineNoticeActions.ts +2 -1
  50. package/ui/hooks/useSpendableBalance.ts +3 -1
  51. package/ui/index.ts +1 -0
  52. package/ui/printRecoveryShares.ts +6 -7
  53. package/ui/screens/PairScreen.tsx +2 -1
  54. package/ui/screens/PayScreen.tsx +53 -0
  55. package/ui/screens/ProfileScreen.tsx +195 -4
  56. package/ui/screens/SettingsScreen.tsx +80 -6
  57. package/ui/screens/VaultScreen.tsx +31 -2
  58. package/ui/screens/VaultTransferScreen.tsx +25 -2
  59. package/ui/screens/WalletCheckScreen.tsx +2 -1
  60. package/ui/screens/WalletConfigScreen.tsx +51 -21
  61. package/ui/screens/WalletHomeScreen.tsx +6 -3
  62. 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 } 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,22 +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'
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'
214
268
  import { drainUnsentEntries, TaskDrainOutbox } from '../monitor/TaskDrainOutbox'
215
269
  import { TaskBackupPush } from '../monitor/TaskBackupPush'
216
270
  import { pushOnce } from '../backup/push'
271
+ import { BACKUP_PUSH_ENABLED_KEY } from '../backup/preference'
217
272
  import { restoreOnImport } from '../backup/restoreOnImport'
218
273
  import { backupPseudonym } from '../backup/derive'
219
274
  import type { BackupChain } from '../backup/constants'
@@ -245,7 +300,14 @@ import {
245
300
  import { getOutboxEntries, pruneExpiredSent, unsentEntries } from '../peerpay/outbox'
246
301
  import { MAX_HEX_RESPONSE_CHARS, wocConfigFor } from '../pay/rails/address'
247
302
  import { PeerPayClient } from '@bsv/message-box-client'
248
- import { SWEEP_INTERVAL_MS, runSweep, shouldSweepNow, sweptTotal } from '../pay/sweeper'
303
+ import {
304
+ SWEEP_INTERVAL_MS,
305
+ backoffAfterSweepError,
306
+ consumeBackoff,
307
+ runSweep,
308
+ shouldSweepNow,
309
+ sweptTotal
310
+ } from '../pay/sweeper'
249
311
  import { formatAmount } from '../amountFormatHelpers'
250
312
  import { useTranslation } from 'react-i18next'
251
313
  import { HEADER_CHECKPOINTS } from '../headers/checkpoints'
@@ -274,24 +336,47 @@ const autoApprovePolicy = createAutoApprovePolicy({
274
336
  })
275
337
 
276
338
  // Best-effort persistence of the rolling ledger so an app restart does not
277
- // reset the daily cap. Loaded once per process; a read/write failure never
278
- // blocks a spend decision — the in-memory ledger stays authoritative either way.
279
- let autoApproveLedgerLoadedOnce = false
280
- async function loadAutoApproveLedgerOnce(): Promise<void> {
281
- if (autoApproveLedgerLoadedOnce) return
282
- 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 = []
283
345
  try {
284
- const stored = await AsyncStorage.getItem(AUTO_APPROVE_LEDGER_STORAGE_KEY)
285
- if (stored) {
286
- const parsed = JSON.parse(stored)
287
- if (Array.isArray(parsed)) autoApprovePolicy.loadLedger(parsed)
288
- }
346
+ const stored = await AsyncStorage.getItem(profileScopedKey(AUTO_APPROVE_LEDGER_STORAGE_KEY))
347
+ if (stored) entries = JSON.parse(stored)
289
348
  } catch {
290
- // No persisted ledger to restore — start with an empty one, same as today.
349
+ // No persisted ledger to restore — start with an empty one.
291
350
  }
351
+ autoApprovePolicy.loadLedger(Array.isArray(entries) ? entries : [])
292
352
  }
293
353
  function persistAutoApproveLedger(): void {
294
- 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)
295
380
  }
296
381
 
297
382
  // -----
@@ -420,6 +505,34 @@ export interface WalletContextValue {
420
505
  * through to a post-storage-attach reconciliation pass (no remote replay) for a raw
421
506
  * database import that already carries a complete local database (XR-079). */
422
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>
423
536
  storage: StorageExpoSQLite | null
424
537
  /**
425
538
  * Mandala stablecoins, or undefined.
@@ -503,6 +616,15 @@ export const WalletContext = createContext<WalletContextValue>({
503
616
  getWalletBuilt: () => false,
504
617
  switchNetwork: async () => {},
505
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' }),
506
628
  storage: null,
507
629
  mandala: undefined,
508
630
  mandalaSettlement: undefined,
@@ -706,6 +828,27 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
706
828
  const appStateRef = useRef<AppStateStatus>(AppState.currentState)
707
829
  const monitorSupervisorRef = useRef<MonitorSupervisor | null>(null)
708
830
  const monitorRef = useRef<Monitor | null>(null)
831
+ // Push notifications. `pushDetachRef` removes the adapter listeners the
832
+ // current build attached; `pushSyncRef` is that build's registration sync,
833
+ // which the foreground handler calls so a permission granted from OS Settings
834
+ // registers on return. Both are cleared wherever the monitor is torn down.
835
+ const pushDetachRef = useRef<(() => void) | undefined>(undefined)
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)
709
852
  // The offline-first chain tracker and the header store it wraps. Populated
710
853
  // in buildWallet (tracker synchronously, store once the background open
711
854
  // finishes); the reconnect top-up effect below reuses both rather than
@@ -894,12 +1037,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
894
1037
  g.__jsStallWatchdogTimer = setTimeout(tick, TICK)
895
1038
  }, [])
896
1039
  useEffect(() => {
897
- AsyncStorage.getItem(AUTO_APPROVE_STORAGE_KEY).then(v => {
1040
+ AsyncStorage.getItem(profileScopedKey(AUTO_APPROVE_STORAGE_KEY)).then(v => {
898
1041
  if (v !== null) autoApproveThresholdRef.current = Number(v) || 0
899
1042
  })
900
1043
  // Restores the rolling auto-approve ledger so an app restart does not
901
- // reset the daily cap (misc-p2-04). Best-effort — see loadAutoApproveLedgerOnce.
902
- 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()
903
1047
  AsyncStorage.getItem('walletSettings').then(v => {
904
1048
  if (v) setSettings(prev => ({ ...prev, ...JSON.parse(v) }))
905
1049
  })
@@ -1076,8 +1220,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1076
1220
  // immediately (the mount-time ref read alone left the old value live
1077
1221
  // until app restart — felt like auto-approve was "stuck on").
1078
1222
  try {
1079
- const stored = await AsyncStorage.getItem(AUTO_APPROVE_STORAGE_KEY)
1080
- 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
1081
1226
  } catch {}
1082
1227
  const threshold = autoApproveThresholdRef.current
1083
1228
  autoApproveThresholdSnapshot = threshold
@@ -1144,6 +1289,23 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1144
1289
  const selectedNetworkRef = useRef<AppChain>(DEFAULT_CHAIN)
1145
1290
  selectedNetworkRef.current = selectedNetwork
1146
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)
1147
1309
 
1148
1310
  // Flag that indicates configuration is complete. For returning users,
1149
1311
  // if a snapshot exists we auto-mark configComplete.
@@ -1162,17 +1324,46 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1162
1324
  return true
1163
1325
  }, [])
1164
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
+
1165
1346
  // Auto-configure on first launch: if no stored config, set defaults
1166
1347
  useEffect(() => {
1167
1348
  ;(async () => {
1168
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()
1169
1359
  const storedConfig = await getItem('finalConfig')
1170
1360
  if (storedConfig) {
1171
1361
  try {
1172
1362
  const config = JSON.parse(storedConfig)
1173
- finalizeConfig(config)
1363
+ // The network lives on the active profile, not in finalConfig.
1364
+ finalizeConfig({ ...config, network: getActiveProfile().network })
1174
1365
  } catch {
1175
- finalizeConfig({ wabUrl: 'noWAB', method: 'mnemonic', network: DEFAULT_CHAIN, storageUrl: 'local' })
1366
+ finalizeConfig({ wabUrl: 'noWAB', method: 'mnemonic', network: getActiveProfile().network, storageUrl: 'local' })
1176
1367
  await setItem(
1177
1368
  'finalConfig',
1178
1369
  JSON.stringify({ wabUrl: 'noWAB', method: 'mnemonic', network: DEFAULT_CHAIN, storageUrl: 'local' })
@@ -1180,7 +1371,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1180
1371
  }
1181
1372
  } else {
1182
1373
  // First launch: auto-configure with defaults
1183
- finalizeConfig({ wabUrl: 'noWAB', method: 'mnemonic', network: DEFAULT_CHAIN, storageUrl: 'local' })
1374
+ finalizeConfig({ wabUrl: 'noWAB', method: 'mnemonic', network: getActiveProfile().network, storageUrl: 'local' })
1184
1375
  await setItem(
1185
1376
  'finalConfig',
1186
1377
  JSON.stringify({ wabUrl: 'noWAB', method: 'mnemonic', network: DEFAULT_CHAIN, storageUrl: 'local' })
@@ -1215,6 +1406,13 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1215
1406
  // conditional on the app still wanting THIS build by the time it gets there.
1216
1407
  const buildToken = buildGenRef.current.current()
1217
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 = []
1218
1416
  try {
1219
1417
  logWithTimestamp(F, 'Building wallet')
1220
1418
  const newManagers = {} as any
@@ -1249,7 +1447,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1249
1447
  // AsyncStorage under this same key) — only the URL, which is not a
1250
1448
  // credential, still lives in plain AsyncStorage.
1251
1449
  const [arcUrlOverride, arcApiTokenOverride] = await Promise.all([
1252
- AsyncStorage.getItem(`arc_custom_url_${chain}`),
1450
+ AsyncStorage.getItem(profileScopedKey(arcUrlStorageKey(chain))),
1253
1451
  getArcApiToken(chain)
1254
1452
  ])
1255
1453
 
@@ -1899,6 +2097,20 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1899
2097
  monitorOptions.saveLastSSEEventId = (id: string) => phoneStorage!.setKeyValue(SSE_KEY, id)
1900
2098
  }
1901
2099
  const monitor = await createWalletMonitor(monitorOptions)
2100
+ // The MessageBox host this wallet talks to, or undefined when the
2101
+ // user turned MessageBox off. One definition for the CreditInbox task
2102
+ // and the push registration below, so a device token is always
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))
2108
+ return saved === NO_MESSAGE_BOX
2109
+ ? undefined
2110
+ : !saved || saved === LEGACY_MESSAGE_BOX_URL
2111
+ ? DEFAULT_MESSAGE_BOX_URL
2112
+ : saved
2113
+ }
1902
2114
 
1903
2115
  // Release held offline transactions when signal returns — registered
1904
2116
  // BEFORE the defaults, and the order matters. Monitor.runOnce collects
@@ -1986,64 +2198,56 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1986
2198
  // Pessimistic: one idle drain clears it the first time we are online.
1987
2199
  TaskSendOffline.noteEnqueued()
1988
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
1989
2245
  monitor.addTask(
1990
- new TaskCreditInbox(
1991
- monitor,
1992
- async () => {
1993
- const saved = await AsyncStorage.getItem(MESSAGE_BOX_URL_KEY)
1994
- const messageBoxUrl =
1995
- saved === NO_MESSAGE_BOX
1996
- ? undefined
1997
- : !saved || saved === LEGACY_MESSAGE_BOX_URL
1998
- ? DEFAULT_MESSAGE_BOX_URL
1999
- : saved
2000
- if (!messageBoxUrl) return { accepted: 0, attention: 0, pending: false }
2001
- let client: PeerPayClient
2002
- try {
2003
- client = new PeerPayClient({
2004
- messageBoxHost: messageBoxUrl,
2005
- walletClient: permissionsManager as never,
2006
- originator: adminOriginator
2007
- })
2008
- } catch {
2009
- return { accepted: 0, attention: 0, pending: false }
2010
- }
2011
- const repairBeef = makeBeefRepair({ woc: wocConfigFor(chain), online: getOnline })
2012
- const classify = await makeCreditClassifier({
2013
- getOnline,
2014
- peekLastMissHeight: () => offlineChaintracks.peekLastMissHeight()
2015
- })
2016
- const r = await creditInboxOnce({
2017
- client,
2018
- messageBoxUrl,
2019
- storage: phoneStorage!,
2020
- classify,
2021
- accept: payment =>
2022
- acceptWithRetry(client, messageBoxUrl, payment, p =>
2023
- internalizeIncoming(permissionsManager as never, client, adminOriginator, p, repairBeef)
2024
- )
2025
- })
2026
- // The SAME rail, a second box. A handle-rail token payment
2027
- // is delivered into 'mandala-payments', not 'payment_inbox',
2028
- // so a receive drain that read only the satoshi box would
2029
- // leave real money sitting in the other one. Never throws
2030
- // (see drainMandalaInbox) — a MessageBox fault on the token
2031
- // side must not take the satoshi inbox down with it.
2032
- const tokens = await drainMandalaInbox(mandalaRef.current)
2033
- if (tokens.credited > 0) setTxStatusVersion(v => v + 1)
2034
- return {
2035
- accepted: r.accepted + tokens.credited,
2036
- attention: r.attentionCount,
2037
- pending: r.pending
2038
- }
2039
- },
2040
- Date.now,
2041
- () => {
2042
- if (isReceiveInboxFocused()) return
2043
- sounds.paymentReceive()
2044
- onToast?.(i18n.t('payment_arrived'), { type: 'success' })
2045
- }
2046
- )
2246
+ new TaskCreditInbox(monitor, creditInboxPass, Date.now, () => {
2247
+ if (isReceiveInboxFocused()) return
2248
+ sounds.paymentReceive()
2249
+ onToast?.(i18n.t('payment_arrived'), { type: 'success' })
2250
+ })
2047
2251
  )
2048
2252
  TaskCreditInbox.noteEnqueued()
2049
2253
 
@@ -2094,7 +2298,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2094
2298
  primaryKey,
2095
2299
  chain: backupChain,
2096
2300
  identityKey: keyDeriver.identityKey,
2097
- 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
2098
2305
  })
2099
2306
  })
2100
2307
  )
@@ -2291,11 +2498,77 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2291
2498
  // contention that contributes to watchdog/OOM kills on real devices.
2292
2499
  if (!stillWanted()) {
2293
2500
  try {
2294
- await stopMonitorAndDrain(monitor)
2501
+ await stopMonitorAndDrain(monitor, monitorSupervisorRef.current)
2295
2502
  } catch {}
2296
2503
  return null
2297
2504
  }
2298
2505
  monitorRef.current = monitor
2506
+
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
2510
+ // CreditInbox pass registered above, so nothing is shown or credited
2511
+ // twice.
2512
+ //
2513
+ // Wired HERE, after the supersession check and with no await between
2514
+ // the two, on purpose. A build that was replaced mid-flight never
2515
+ // reaches this line, so it can neither register a token against a
2516
+ // wallet being torn down nor detach the listeners a newer build wired.
2517
+ // Every teardown clears the refs before it yields, so a build that is
2518
+ // superseded after this line is cleaned up by whoever superseded it.
2519
+ //
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
2526
+ // overlapping burst into one rerun. Push is an enhancement: nothing
2527
+ // here may throw into the build.
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
2569
+ }
2570
+ })
2571
+ }
2299
2572
  InteractionManager.runAfterInteractions(() => {
2300
2573
  // Re-check identity: stopTasks() before startTasks() is a no-op
2301
2574
  // (it only clears a flag the loop hasn't set yet), so a rebuild/
@@ -2367,7 +2640,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2367
2640
  logWithTimestamp(F, 'Discarding a build the network switch overtook')
2368
2641
  return null
2369
2642
  }
2370
- 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 })
2371
2647
  updateManagers(m => ({ ...m, ...newManagers }))
2372
2648
  logWithTimestamp(F, 'Wallet build completed successfully')
2373
2649
 
@@ -2410,6 +2686,33 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2410
2686
  * callback, which cannot name itself inside its own definition. */
2411
2687
  const buildFromMnemonicRef = useRef<((m?: string, o?: WalletBuildOptions) => Promise<void>) | null>(null)
2412
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
+
2413
2716
  const buildWalletFromMnemonic = useCallback(
2414
2717
  async (providedMnemonic?: string, opts?: WalletBuildOptions) => {
2415
2718
  // Skip if wallet already built or a build is already in progress
@@ -2443,8 +2746,33 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2443
2746
  return
2444
2747
  }
2445
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()
2446
2754
  const __tRecoverStart = performance.now()
2447
- 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 })
2448
2776
  if (__DEV__)
2449
2777
  console.warn(
2450
2778
  `[perf] recoverMnemonicWallet (PBKDF2+BIP32): ${(performance.now() - __tRecoverStart).toFixed(0)}ms`
@@ -2452,9 +2780,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2452
2780
 
2453
2781
  // The vault no longer routes through the PKM — the YubiKey signs vault
2454
2782
  // inputs directly. The toolbox still requires a privileged key manager,
2455
- // so this returns the plain root key. guardVaultAccess is what keeps
2456
- // non-admin originators away from it.
2457
- 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)
2458
2787
 
2459
2788
  // Create SimpleWalletManager and provide keys for authentication
2460
2789
  const swm = new SimpleWalletManager(ADMIN_ORIGINATOR, buildWallet)
@@ -2466,6 +2795,43 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2466
2795
  // allows the import screen to continue without restoring on retry.
2467
2796
  if (opts !== undefined) restoreIntentRef.current = opts.restoreFromBackup === true
2468
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
+ }
2469
2835
 
2470
2836
  // Provide the primary key and privileged key manager to authenticate the wallet
2471
2837
  await swm.providePrimaryKey(primaryKey)
@@ -2494,6 +2860,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2494
2860
  walletBuiltRef.current = true
2495
2861
  setWalletBuilt(true)
2496
2862
  setWalletBuilding(false)
2863
+ if (wantedRestore && profileIndex === 0) discoverProfilesRef.current?.(mnemonic)
2497
2864
 
2498
2865
  logWithTimestamp(F, 'Mnemonic wallet build completed')
2499
2866
  } catch (error: any) {
@@ -2501,6 +2868,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2501
2868
  // an auto-build on relaunch, which must not re-import over a live database.
2502
2869
  restoreIntentRef.current = false
2503
2870
  reviewImportedCoinsRef.current = false
2871
+ pushOtherProfileKeysRef.current = []
2504
2872
  walletBuildingRef.current = false
2505
2873
  setWalletBuilding(false)
2506
2874
  console.error('[WalletContext] Error building mnemonic wallet:', error)
@@ -2526,13 +2894,20 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2526
2894
  try {
2527
2895
  const recoveredKey = PrivateKey.fromWif(wif)
2528
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()
2529
2900
 
2530
- // Same plain-root-key manager as the mnemonic path — see the comment
2531
- // 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.
2532
2904
  const privilegedKeyManager = new PrivilegedKeyManager(async () => recoveredKey, VAULT_RETENTION_MS)
2533
2905
 
2534
2906
  const swm = new SimpleWalletManager(ADMIN_ORIGINATOR, buildWallet)
2535
2907
 
2908
+ // A single wallet: the open profile is the only identity to register for push.
2909
+ pushOtherProfileKeysRef.current = []
2910
+
2536
2911
  // Same arming point as the mnemonic path — see the comment there.
2537
2912
  // An automatic build has no options: preserve the request armed by
2538
2913
  // rebuildWallet until buildWallet consumes it. Explicit false still
@@ -2566,6 +2941,70 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2566
2941
  [configStatus, buildWallet]
2567
2942
  )
2568
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
+
2569
3008
  // Tear down the current wallet and re-trigger auto-build.
2570
3009
  // Used after DB import and internally by switchNetwork.
2571
3010
  const rebuildWallet = useCallback(
@@ -2579,56 +3018,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2579
3018
  reviewImportedCoinsRef.current = opts?.reviewImportedCoins === true
2580
3019
  // Any build already in flight belongs to the configuration being replaced.
2581
3020
  const token = buildGenRef.current.bump()
2582
- // Invalidate Vault operations before the first teardown await. Otherwise a
2583
- // signer/listing already in flight can resume against the departing wallet.
2584
- vaultStore.clearScope()
2585
- vaultCeremony.cancel()
2586
-
2587
- // Stop any running monitor and let its current pass drain before the
2588
- // storage teardown below closes the connection under it.
2589
- {
2590
- const monitor = monitorRef.current
2591
- if (monitor) {
2592
- monitorRef.current = null
2593
- await stopMonitorAndDrain(monitor)
2594
- }
2595
- }
2596
- // Same convention as monitorRef above: clear so a stale deferred header
2597
- // init or reconnect handler from the old build can't pair a leftover
2598
- // store/tracker across the rebuild.
2599
- offlineChaintracksRef.current = undefined
2600
- headerStoreRef.current = undefined
2601
-
2602
- // Close the current storage connection so the new build can open
2603
- // whichever DB file the registry selects.
2604
- if (storage?.db) {
2605
- try {
2606
- await storage.destroy()
2607
- } catch {}
2608
- }
2609
- // And drop the handle with it. Leaving a destroyed storage in state kept
2610
- // the screens reading the OLD chain's database until the new build
2611
- // replaced it — which is how a testnet wallet displayed mainnet money.
2612
- setStorage(null)
2613
- // The runtime holds this build's settlement store, which is a handle on
2614
- // the database just destroyed. Dropping it here is what stops a monitor
2615
- // task or a screen draining the departed wallet's tables.
2616
- mandalaRef.current = undefined
2617
- setMandala(undefined)
2618
- forgetSessionPsks()
2619
-
2620
- // Tear down current wallet state (but keep mnemonic / config)
2621
- vaultStore.clearScope()
2622
- updateManagers({})
2623
- walletBuiltRef.current = false
2624
- setWalletBuilt(false)
2625
- walletBuildingRef.current = false
2626
- setWalletBuilding(false)
3021
+ await teardownBuiltWallet()
2627
3022
 
2628
3023
  // Re-finalize with current config — triggers auto-build effect
2629
3024
  const config = { wabUrl: 'noWAB', method: 'mnemonic', network: selectedNetwork, storageUrl: 'local' }
2630
3025
  pendingAutoBuildRef.current = true
2631
3026
  finalizeConfig(config)
3027
+ // Rebuilding after a failed build changes nothing the auto-build effect
3028
+ // watches; see autoBuildRequest.
3029
+ setAutoBuildRequest(r => r + 1)
2632
3030
  logWithTimestamp(F, 'Wallet rebuild triggered')
2633
3031
  // finalizeConfig above only requests the rebuild; without this,
2634
3032
  // rebuildWallet's promise resolved before the auto-build effect had even
@@ -2638,66 +3036,282 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2638
3036
  // wallet actually existing, such as recording a backup attestation.
2639
3037
  await waitForRebuild(token)
2640
3038
  },
2641
- [selectedNetwork, storage, finalizeConfig, waitForRebuild]
3039
+ [selectedNetwork, teardownBuiltWallet, finalizeConfig, waitForRebuild]
2642
3040
  )
2643
3041
 
2644
- // 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.
2645
3044
  const switchNetwork = useCallback(
2646
3045
  async (network: AppChain) => {
2647
- if (network === selectedNetwork) return
3046
+ if (network === selectedNetwork || switchInFlightRef.current) return
2648
3047
  logWithTimestamp(F, `Switching network from ${selectedNetwork} to ${network}`)
2649
3048
  buildGenRef.current.bump()
2650
- vaultStore.clearScope()
2651
- 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()
2652
3055
 
2653
- // Stop any running monitor and let its current pass drain before the
2654
- // storage teardown below closes the connection under it.
2655
- {
2656
- const monitor = monitorRef.current
2657
- if (monitor) {
2658
- monitorRef.current = null
2659
- await stopMonitorAndDrain(monitor)
2660
- }
3056
+ // Persist new config
3057
+ await updateProfile(getActiveProfileIndex(), { network })
3058
+ await setItem('finalConfig', JSON.stringify(newConfig))
3059
+
3060
+ // Re-finalize with new network — the request below triggers the auto-build effect
3061
+ finalizeConfig(newConfig)
3062
+ } finally {
3063
+ profileTransitionRef.current = false
2661
3064
  }
2662
- // Same convention as monitorRef above: clear so the old chain's
2663
- // tracker/store can't linger and get paired against the new chain.
2664
- offlineChaintracksRef.current = undefined
2665
- headerStoreRef.current = undefined
3065
+ setAutoBuildRequest(r => r + 1)
3066
+ logWithTimestamp(F, `Network switched to ${network}`)
3067
+ },
3068
+ [selectedNetwork, setItem, teardownBuiltWallet, finalizeConfig]
3069
+ )
2666
3070
 
2667
- // Close the current storage connection
2668
- if (storage?.db) {
2669
- try {
2670
- await storage.destroy()
2671
- } 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
2672
3121
  }
2673
- setStorage(null)
2674
- mandalaRef.current = undefined
2675
- setMandala(undefined)
2676
- 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
2677
3132
 
2678
- // Tear down current wallet state (but keep mnemonic)
2679
- vaultStore.clearScope()
2680
- updateManagers({})
2681
- walletBuiltRef.current = false
2682
- setWalletBuilt(false)
2683
- walletBuildingRef.current = false
2684
- 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
+ }, [])
2685
3157
 
2686
- // Persist new config
2687
- const newConfig = { wabUrl: 'noWAB', method: 'mnemonic', network, storageUrl: 'local' }
2688
- 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])
2689
3177
 
2690
- // Re-finalize with new network — this triggers the auto-build effect
2691
- finalizeConfig(newConfig)
2692
- 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])
2693
3194
  },
2694
- [selectedNetwork, setItem, storage, finalizeConfig]
3195
+ []
2695
3196
  )
2696
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
+
2697
3309
  // Auto-build wallet for returning users (mnemonic first, then recovered key).
2698
3310
  // Sets walletBuilding=true eagerly so other parts of the app (index.tsx
2699
3311
  // navigation) know not to react as if no wallet exists.
2700
3312
  useEffect(() => {
3313
+ // A profile switch is mid-way: it requests the build itself once ready.
3314
+ if (profileTransitionRef.current) return
2701
3315
  if (configStatus !== 'configured' || walletBuilt) return
2702
3316
  // Signal that a build attempt is starting. buildWalletFromMnemonic /
2703
3317
  // buildWalletFromRecoveredKey will clear this flag on completion or error.
@@ -2728,7 +3342,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2728
3342
  }
2729
3343
  }
2730
3344
  })()
2731
- }, [configStatus, walletBuilt, secretsReady, buildWalletFromMnemonic, buildWalletFromRecoveredKey, getRecoveredKey])
3345
+ }, [
3346
+ configStatus,
3347
+ walletBuilt,
3348
+ secretsReady,
3349
+ buildWalletFromMnemonic,
3350
+ buildWalletFromRecoveredKey,
3351
+ getRecoveredKey,
3352
+ autoBuildRequest
3353
+ ])
2732
3354
 
2733
3355
  // Settings are AsyncStorage-only — no on-chain sync needed
2734
3356
 
@@ -2861,9 +3483,16 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2861
3483
  // the first NetInfo event would delay the common case.
2862
3484
  let online = true
2863
3485
  const woc = wocConfigFor(selectedNetwork)
3486
+ // Ticks still to sit out after a WhatsOnChain 429. Every tick spends one,
3487
+ // including the app-active and back-online ones, so none of them can reach
3488
+ // WhatsOnChain while the backoff is pending.
3489
+ let backoffTicks = 0
2864
3490
 
2865
3491
  const tick = async () => {
2866
3492
  if (cancelled) return
3493
+ const backoff = consumeBackoff(backoffTicks)
3494
+ backoffTicks = backoff.remaining
3495
+ if (backoff.skip) return
2867
3496
  if (
2868
3497
  !shouldSweepNow({
2869
3498
  walletBuilt: true,
@@ -2895,8 +3524,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2895
3524
  type: 'success'
2896
3525
  })
2897
3526
  }
2898
- } catch {
2899
- // Best-effort. Every address stays watched and the next tick retries.
3527
+ } catch (error) {
3528
+ // Best-effort. Every address stays watched and the next tick retries —
3529
+ // except after a rate limit, which sits out SWEEP_BACKOFF_TICKS first.
3530
+ backoffTicks = backoffAfterSweepError(error, backoffTicks)
2900
3531
  } finally {
2901
3532
  addressSweepingRef.current = false
2902
3533
  }
@@ -3032,6 +3663,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3032
3663
  if (TaskSendOffline.hasPending) TaskSendOffline.requestNow()
3033
3664
  TaskCreditInbox.requestNow()
3034
3665
  if (TaskDrainOutbox.hasPending) TaskDrainOutbox.requestNow()
3666
+ // A notification permission granted from OS Settings, or a token the OS
3667
+ // rotated while away, registers on return. No-ops when already current.
3668
+ void pushSyncRef.current?.()
3035
3669
  }
3036
3670
 
3037
3671
  appStateRef.current = nextAppState
@@ -3075,6 +3709,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3075
3709
  try {
3076
3710
  monitorRef.current?.stopTasks()
3077
3711
  } catch {}
3712
+ pushDetachRef.current?.()
3713
+ pushDetachRef.current = undefined
3714
+ pushSyncRef.current = undefined
3715
+ profilePushRef.current = undefined
3716
+ pushOtherProfileKeysRef.current = []
3717
+ creditInboxPassRef.current = undefined
3078
3718
  if (ledgerBumpTimerRef.current) {
3079
3719
  clearTimeout(ledgerBumpTimerRef.current)
3080
3720
  ledgerBumpTimerRef.current = null
@@ -3089,6 +3729,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3089
3729
 
3090
3730
  const logout = useCallback((): Promise<boolean> => {
3091
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()
3092
3735
  // Synchronous on purpose: invalidate transfer tokens and release any PIN /
3093
3736
  // hardware session before monitor or storage teardown yields.
3094
3737
  vaultStore.clearScope()
@@ -3104,6 +3747,22 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3104
3747
  // comment warned about — everything above this point already ran
3105
3748
  // synchronously before any promise existed to await.
3106
3749
  return (async () => {
3750
+ // Push listeners and the registration sync belong to the wallet being
3751
+ // torn down; nothing may fire them against it from here on.
3752
+ pushDetachRef.current?.()
3753
+ pushDetachRef.current = undefined
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()
3765
+
3107
3766
  // Tear the wallet down the same way rebuildWallet does. Logout used to
3108
3767
  // skip this, which orphaned a running monitor AND left the SQLite
3109
3768
  // connection open: a re-import of the same phrase then opened a second
@@ -3114,7 +3773,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3114
3773
  const monitor = monitorRef.current
3115
3774
  if (monitor) {
3116
3775
  monitorRef.current = null
3117
- await stopMonitorAndDrain(monitor)
3776
+ await stopMonitorAndDrain(monitor, monitorSupervisorRef.current)
3118
3777
  }
3119
3778
  }
3120
3779
  offlineChaintracksRef.current = undefined
@@ -3140,6 +3799,26 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3140
3799
  console.warn('[logout] failed to purge wallet db file(s)/registry', err)
3141
3800
  }
3142
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)
3143
3822
  setStorage(null)
3144
3823
  mandalaRef.current = undefined
3145
3824
  setMandala(undefined)
@@ -3177,6 +3856,30 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3177
3856
  // across a logout/re-import on the same install (see deviceId.ts and XR-009), so an
3178
3857
  // unscoped Wallet Check read would otherwise inherit it. Sweeps every identity's
3179
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
+
3180
3883
  try {
3181
3884
  const keys = await AsyncStorage.getAllKeys()
3182
3885
  const stale = keys.filter(k => k.startsWith('backupCursor-'))
@@ -3729,6 +4432,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3729
4432
  getWalletBuilt,
3730
4433
  switchNetwork,
3731
4434
  rebuildWallet,
4435
+ activeProfile: profilesState.active,
4436
+ profiles: profilesState.profiles,
4437
+ profilesSupported,
4438
+ switchProfile,
4439
+ addProfile,
4440
+ switchingProfile,
4441
+ removingProfile,
4442
+ checkProfileRemoval,
4443
+ removeProfile,
3732
4444
  storage,
3733
4445
  mandala,
3734
4446
  mandalaSettlement: mandalaSettlementDeps(mandala),
@@ -3780,6 +4492,14 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3780
4492
  getWalletBuilt,
3781
4493
  switchNetwork,
3782
4494
  rebuildWallet,
4495
+ profilesState,
4496
+ profilesSupported,
4497
+ switchProfile,
4498
+ addProfile,
4499
+ switchingProfile,
4500
+ removingProfile,
4501
+ checkProfileRemoval,
4502
+ removeProfile,
3783
4503
  storage,
3784
4504
  mandala,
3785
4505
  refreshProof,