@bsv/expo-wallet-toolbox 0.16.0 → 0.18.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.
@@ -141,6 +141,7 @@ const MANDALA_OUTPOINT_LIST_MAX_PAGES = 1000
141
141
  import type { AppChain } from '../config'
142
142
  import { DEFAULT_STORAGE_URL, DEFAULT_CHAIN, ADMIN_ORIGINATOR, toWalletChain } from '../config'
143
143
  import { getBackupUrl, getHandleRegistryConfig, getMandalaEndpoints, getPushAdapter } from '../toolboxConfig'
144
+ import { inboxSeenStore } from '../directpay/receive'
144
145
  import {
145
146
  DEFAULT_AUTO_APPROVE_THRESHOLD,
146
147
  AUTO_APPROVE_COOLDOWN_MS,
@@ -273,7 +274,7 @@ import { pushOnce } from '../backup/push'
273
274
  import { BACKUP_PUSH_ENABLED_KEY } from '../backup/preference'
274
275
  import { restoreOnImport } from '../backup/restoreOnImport'
275
276
  import { backupPseudonym } from '../backup/derive'
276
- import type { BackupChain } from '../backup/constants'
277
+ import { BACKUP_CHAINS, type BackupChain } from '../backup/constants'
277
278
  import { processOfflineActions } from '../storage/methods/processOfflineActions'
278
279
  import { findOfflineActions } from '../storage/methods/offlineActions'
279
280
  import { boundedHexResponse, isChainAbsenceConfirmed, shouldFailUnprovenTx } from '../pay/refreshProofGuard'
@@ -788,6 +789,9 @@ async function probeForLegacyDb(legacyName: string): Promise<boolean> {
788
789
  }
789
790
  }
790
791
 
792
+ /** The i18n key naming each network to the user. */
793
+ const NETWORK_LABEL_KEYS: Record<AppChain, string> = { main: 'mainnet', test: 'testnet', teratest: 'teratest' }
794
+
791
795
  /**
792
796
  * Minimal shape of the app's toast function. `core` must never import a `ui`
793
797
  * component (see context/VaultContext.tsx's identical `VaultToast` for the
@@ -916,6 +920,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
916
920
  setBackupRestoreState(next)
917
921
  }, [])
918
922
  const getBackupRestore = useCallback((): BackupRestoreState => backupRestoreRef.current, [])
923
+ /**
924
+ * Counts the restore's steps between chunks (restoreOnImport's onActivity). Only
925
+ * waitForRebuild reads it, to tell a slow restore from a stuck one; a ref, so a
926
+ * restore reconciling thousands of proofs does not re-render the app per step.
927
+ */
928
+ const restoreActivityRef = useRef(0)
919
929
  const getWalletBuilt = useCallback((): boolean => walletBuiltRef.current, [])
920
930
  /**
921
931
  * Set once buildWallet resolves this build's backup chain/pseudonym, so a screen (Wallet
@@ -971,18 +981,35 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
971
981
  * rebuildWallet bumped to; a later teardown (another rebuild, a network
972
982
  * switch) bumps past it and this returns immediately rather than waiting on
973
983
  * a build nothing still wants.
984
+ *
985
+ * Resolves true once the build has settled (built or failed), false when it
986
+ * was superseded or is still running at the deadline. Only a settled build
987
+ * may be judged: a false result is never a failure to fall back from.
974
988
  */
975
- const waitForRebuild = useCallback(async (token: number, timeoutMs = 300000): Promise<void> => {
989
+ const waitForRebuild = useCallback(async (token: number, timeoutMs = 300000): Promise<boolean> => {
976
990
  // A restore replays the encrypted backup log INSIDE the build, before
977
- // walletBuiltRef flips — a large history can legitimately take minutes.
978
- // The timeout is a safety net against a build that never settles, not a
979
- // normal-path budget; the generation check is what actually bounds this
980
- // to a superseded rebuild.
981
- const start = Date.now()
982
- while (buildGenRef.current.isCurrent(token) && Date.now() - start < timeoutMs) {
983
- if (!pendingAutoBuildRef.current && !walletBuildingRef.current) return
991
+ // walletBuiltRef flips — a large history can legitimately take far longer
992
+ // than the timeout. So the deadline restarts whenever the restore reports
993
+ // anything: a phase change, a chunk, or a step between chunks (ranking a
994
+ // candidate generation, before and during proof reconciliation, and before
995
+ // the coin review; see restoreActivityRef). The timeout then ends the wait
996
+ // only when no single step reports for that long: a stuck build, or one
997
+ // request or coin review that alone outlasts it. The generation check is
998
+ // what bounds this to a superseded rebuild.
999
+ let deadline = Date.now() + timeoutMs
1000
+ let seen = backupRestoreRef.current
1001
+ let seenActivity = restoreActivityRef.current
1002
+ while (buildGenRef.current.isCurrent(token)) {
1003
+ if (!pendingAutoBuildRef.current && !walletBuildingRef.current) return true
1004
+ if (backupRestoreRef.current !== seen || restoreActivityRef.current !== seenActivity) {
1005
+ seen = backupRestoreRef.current
1006
+ seenActivity = restoreActivityRef.current
1007
+ if (seen.phase === 'checking' || seen.phase === 'restoring') deadline = Date.now() + timeoutMs
1008
+ }
1009
+ if (Date.now() >= deadline) return false
984
1010
  await new Promise(resolve => setTimeout(resolve, 40))
985
1011
  }
1012
+ return false
986
1013
  }, [])
987
1014
  const [localPayNotification, setLocalPayNotification] = useState<{
988
1015
  message: string
@@ -1310,6 +1337,21 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1310
1337
  const profileTransitionRef = useRef(false)
1311
1338
  /** A whole switch or add, from the tap until its build lands (see runProfileTransition). */
1312
1339
  const switchInFlightRef = useRef(false)
1340
+ /**
1341
+ * Set while the code that started a build has its own fallback and reports a
1342
+ * failure itself (a network or profile switch, or a cold start falling back to
1343
+ * another network): the build's generic failure toast would be a second
1344
+ * message for one event, and no other fallback may act on it. Each owner
1345
+ * holds its own token and releases only that, so a later owner keeps its
1346
+ * claim when an earlier one finishes.
1347
+ */
1348
+ const buildFailureReportedRef = useRef<object | null>(null)
1349
+ /** Set by buildWallet when it throws; cleared by whoever starts a build and judges its outcome. */
1350
+ const buildThrewRef = useRef(false)
1351
+ /** Tell the user `network` could not be opened. A ref: the auto-build effect must not re-run on a new toast or t. */
1352
+ const reportNetworkFailedRef = useRef<(network: AppChain) => void>(() => {})
1353
+ reportNetworkFailedRef.current = network =>
1354
+ onToast?.(t('profile_switch_failed', { profile: t(NETWORK_LABEL_KEYS[network]) }), { type: 'error' })
1313
1355
  const [switchingProfile, setSwitchingProfile] = useState(false)
1314
1356
  /** The profile a removal is working on, for the cover's label; null the rest of the time. */
1315
1357
  const [removingProfile, setRemovingProfile] = useState<number | null>(null)
@@ -1624,6 +1666,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1624
1666
  // discovered on disk). Only true in the "fresh user" branch — see its use at
1625
1667
  // the restore-failure cleanup further down (XR-017 review follow-up).
1626
1668
  let dbWasFreshlyCreatedThisAttempt = false
1669
+ // A pre-registry database file was found for this chain: an existing local
1670
+ // wallet, which a pending restore must never replay over.
1671
+ let adoptedLegacyDb = false
1627
1672
 
1628
1673
  if (knownDbs.length === 0) {
1629
1674
  // First launch after update or fresh user.
@@ -1633,6 +1678,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1633
1678
  if (hasLegacy) {
1634
1679
  await registerDb(keySuffix, chainStr, legacyName)
1635
1680
  knownDbs = [legacyName]
1681
+ adoptedLegacyDb = true
1636
1682
  console.log(`[WalletContext] Registered legacy DB: ${legacyName}`)
1637
1683
  } else {
1638
1684
  // Fresh user — create a timestamped database
@@ -1662,16 +1708,55 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1662
1708
 
1663
1709
  console.log('[WalletContext] Local SQLite storage initialized successfully')
1664
1710
 
1665
- // ── Import-time restore ────────────────────────────────────────────
1711
+ // ── Restore ─────────────────────────────────────────────────────────
1666
1712
  //
1667
1713
  // Deliberately HERE: the database is migrated and empty, nothing has been
1668
1714
  // published to the app yet, and the monitor (with its backup push task) does
1669
1715
  // not exist — so this device cannot have written a log of its own that the
1670
1716
  // restore would then pick as the newest. See utils/backup/restoreOnImport.ts.
1671
1717
  //
1718
+ // Two triggers. An import asks for it (restoreIntentRef) on the network it
1719
+ // runs on. And each network a profile still has pending (see
1720
+ // ProfileRecord.restorePending) replays the first time this device builds
1721
+ // the profile there: the networks an import did not run on, those a
1722
+ // discovered profile was found backed up on, and every network of an added
1723
+ // profile. A wallet created on this device has nothing pending, so it never
1724
+ // asks the backup server. An import leaves out every network that already
1725
+ // has a local database, and a pre-registry (legacy) file is settled, not
1726
+ // replayed. A pending network that does have a database is normally the one
1727
+ // its own interrupted replay created. The exception: the profile store can be
1728
+ // reset (a replacing import) while the database registry survives, so after
1729
+ // a re-import of the original seed, discovery or Add profile can mark a
1730
+ // profile's network pending over a database that was in use. That replay
1731
+ // is the same as re-importing a seed over its own wallet: wallet records
1732
+ // and contacts merge by identity (newer wins), while three app-data rows
1733
+ // (pending local payments, outbox, issued receive dates) are written over
1734
+ // with the backup's snapshot.
1735
+ //
1672
1736
  // A failure throws, which aborts the whole build: the import screen reports it
1673
- // and lets the user retry or continue without history. Presenting a
1674
- // half-replayed database as a working wallet is the one outcome to avoid.
1737
+ // and lets the user retry or continue without history, and a network switch
1738
+ // returns to the network it came from. Presenting a half-replayed database as
1739
+ // a working wallet is the one outcome to avoid.
1740
+ const pendingOf = () => getProfilesState().profiles[profileIndex]?.restorePending ?? []
1741
+ /** This network's restore has run, or must not: it is no longer pending. */
1742
+ const settleRestore = async () => {
1743
+ if (pendingOf().includes(chainStr)) {
1744
+ await updateProfile(profileIndex, { restorePending: pendingOf().filter(c => c !== chainStr) })
1745
+ }
1746
+ }
1747
+ const restoreRequested = restoreIntentRef.current
1748
+ const restorePending = pendingOf().includes(chainStr) && !adoptedLegacyDb
1749
+ if (adoptedLegacyDb) await settleRestore()
1750
+ if (restoreRequested) {
1751
+ // An import: the other networks restore when they are first built, except
1752
+ // one that already has a local wallet.
1753
+ const others: BackupChain[] = []
1754
+ for (const c of BACKUP_CHAINS) {
1755
+ if (c !== chainStr && (await getRegisteredDbs(keySuffix, c)).length === 0) others.push(c)
1756
+ }
1757
+ await updateProfile(profileIndex, { restorePending: [...pendingOf(), ...others] })
1758
+ }
1759
+
1675
1760
  let localStorageAdded = false
1676
1761
  const addLocalStorage = async () => {
1677
1762
  if (localStorageAdded) return
@@ -1679,7 +1764,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1679
1764
  localStorageAdded = true
1680
1765
  }
1681
1766
 
1682
- if (restoreIntentRef.current) {
1767
+ if (restoreRequested || restorePending) {
1683
1768
  restoreIntentRef.current = false
1684
1769
  setBackupRestore({ phase: 'checking', chunks: 0, total: 0 })
1685
1770
  try {
@@ -1690,6 +1775,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1690
1775
  identityKey,
1691
1776
  baseUrl: getBackupUrl(),
1692
1777
  onProgress: (chunks, total) => setBackupRestore({ phase: 'restoring', chunks, total }),
1778
+ onActivity: () => {
1779
+ restoreActivityRef.current++
1780
+ },
1693
1781
  // reviewSpendableOutputs talks to Services through the Wallet, which
1694
1782
  // needs this storage attached first. Attach here (idempotent with the
1695
1783
  // call below) so the post-restore pass actually sees the replayed coins.
@@ -1712,6 +1800,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
1712
1800
  `[WalletContext] backup restore · restored=${String(restored.restored)} · ` +
1713
1801
  `chunks=${restored.chunks} · reason=${restored.reason ?? 'none'}`
1714
1802
  )
1803
+ await settleRestore()
1715
1804
  // See P1-backup-incomplete-generation: restoreOnImport.pickTarget falls back to
1716
1805
  // an unverified (no seal) target rather than blocking the import, so this is a
1717
1806
  // warning rather than a thrown error — but it must not pass silently, since the
@@ -2231,6 +2320,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2231
2320
  getOnline,
2232
2321
  peekLastMissHeight: () => offlineChaintracks.peekLastMissHeight()
2233
2322
  })
2323
+ // With direct payments on, a payment that arrived live as well is
2324
+ // credited, and announced, once (see core/directpay/receive.ts).
2325
+ const seen = inboxSeenStore(keyDeriver.identityKey, chain)
2234
2326
  const r = await creditInboxOnce({
2235
2327
  client,
2236
2328
  messageBoxUrl,
@@ -2238,7 +2330,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2238
2330
  classify,
2239
2331
  accept: payment =>
2240
2332
  acceptWithRetry(client, messageBoxUrl, payment, p =>
2241
- internalizeIncoming(permissionsManager as never, client, adminOriginator, p, repairBeef)
2333
+ internalizeIncoming(permissionsManager as never, client, adminOriginator, p, repairBeef, seen)
2242
2334
  )
2243
2335
  })
2244
2336
  // The SAME rail, a second box. A handle-rail token payment
@@ -2657,15 +2749,17 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2657
2749
  }
2658
2750
  vaultStore.configureScope({ identityKey: keyDeriver.identityKey, chain: backupChain, profileIndex })
2659
2751
  // The identity is public; Delete Wallet needs it to find this profile's
2660
- // databases. Any restore this profile was waiting for has now run.
2661
- void updateProfile(profileIndex, { identityKey: keyDeriver.identityKey, needsRestore: false })
2752
+ // databases. The network is where a cold start falls back to (see the
2753
+ // auto-build effect).
2754
+ void updateProfile(profileIndex, { identityKey: keyDeriver.identityKey, lastBuiltNetwork: chain })
2662
2755
  updateManagers(m => ({ ...m, ...newManagers }))
2663
2756
  logWithTimestamp(F, 'Wallet build completed successfully')
2664
2757
 
2665
2758
  return permissionsManager
2666
2759
  } catch (error: any) {
2667
2760
  console.error('Error building wallet:', error)
2668
- onToast?.('Failed to build wallet: ' + error.message, { type: 'error' })
2761
+ buildThrewRef.current = true
2762
+ if (!buildFailureReportedRef.current) onToast?.('Failed to build wallet: ' + error.message, { type: 'error' })
2669
2763
  logWithTimestamp(F, 'Error building wallet', error.message)
2670
2764
  // SimpleWalletManager authenticates whenever its builder resolves,
2671
2765
  // even to null. Reject so a failed restore cannot mark a wallet built.
@@ -2702,7 +2796,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2702
2796
  const buildFromMnemonicRef = useRef<((m?: string, o?: WalletBuildOptions) => Promise<void>) | null>(null)
2703
2797
 
2704
2798
  /** After a seed import, find the other profiles it backed up (see core/profiles/discovery).
2705
- * Fire-and-forget: only the probe runs now; each profile restores on first switch. */
2799
+ * Fire-and-forget: only the probe runs now; each profile restores each of its
2800
+ * networks the first time it is built there. */
2706
2801
  const discoverProfilesRef = useRef<((mnemonic: string) => void) | null>(null)
2707
2802
  discoverProfilesRef.current = (mnemonic: string) => {
2708
2803
  const baseUrl = getBackupUrl()
@@ -2717,9 +2812,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2717
2812
  probe: async (primaryKey, chain) => stillOwned() && (await backupProbe(baseUrl)(primaryKey, chain)),
2718
2813
  // A profile removed on this device stays removed (and does not end the search).
2719
2814
  skip: index => !!getProfilesState().profiles[index]?.deleted,
2720
- register: async (index, network) => {
2815
+ register: async (index, network, chains) => {
2721
2816
  // Idempotent: a second import of the same seed must not duplicate profiles.
2722
- if (stillOwned()) await registerDiscoveredProfile(index, network)
2817
+ if (stillOwned()) await registerDiscoveredProfile(index, network, chains)
2723
2818
  }
2724
2819
  })
2725
2820
  .then(n => {
@@ -2810,9 +2905,6 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2810
2905
  // allows the import screen to continue without restoring on retry.
2811
2906
  if (opts !== undefined) restoreIntentRef.current = opts.restoreFromBackup === true
2812
2907
  if (opts !== undefined) reviewImportedCoinsRef.current = opts.reviewImportedCoins === true
2813
- // A profile found by restore discovery, or just added, replays its own
2814
- // remote backup on its first build — on whichever launch that happens.
2815
- if (getProfilesState().profiles[profileIndex]?.needsRestore) restoreIntentRef.current = true
2816
2908
  // Captured before buildWallet consumes it: an import of profile 0 is what
2817
2909
  // triggers discovery of the other profiles this seed has backed up.
2818
2910
  const wantedRestore = restoreIntentRef.current
@@ -2909,9 +3001,18 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
2909
3001
  try {
2910
3002
  const recoveredKey = PrivateKey.fromWif(wif)
2911
3003
  const primaryKey = recoveredKey.toArray()
2912
- // A recovered key is a single wallet: no seed, so no other profiles.
3004
+ // A recovered key is a single wallet: no seed, so no other profiles. Nor
3005
+ // does it inherit profile 0's record (and its pending restores) from
3006
+ // another wallet.
2913
3007
  setProfilesSupported(false)
2914
- if (getProfilesState().profiles.length > 1 || getActiveProfileIndex() !== 0) await resetProfiles()
3008
+ const recordedIdentity = getProfilesState().profiles[0]?.identityKey
3009
+ if (
3010
+ getProfilesState().profiles.length > 1 ||
3011
+ getActiveProfileIndex() !== 0 ||
3012
+ (recordedIdentity !== undefined && recordedIdentity !== recoveredKey.toPublicKey().toString())
3013
+ ) {
3014
+ await resetProfiles()
3015
+ }
2915
3016
 
2916
3017
  // The recovered key doubles as the privileged key — there is no seed to
2917
3018
  // derive a separate one from. guardVaultAccess is what keeps non-admin
@@ -3056,32 +3157,61 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3056
3157
 
3057
3158
  // Switch network: tear down wallet, update config, and rebuild on new chain.
3058
3159
  // The network belongs to the active profile, so this changes that profile's.
3160
+ //
3161
+ // Resolves once the new network's build has settled. If it fails (typically:
3162
+ // the network's first restore could not reach the backup server), the
3163
+ // previous network is rebuilt and the failure is reported, so a switch never
3164
+ // strands the user on an unusable wallet. Switching again retries.
3059
3165
  const switchNetwork = useCallback(
3060
- async (network: AppChain) => {
3061
- if (network === selectedNetwork || switchInFlightRef.current) return
3062
- logWithTimestamp(F, `Switching network from ${selectedNetwork} to ${network}`)
3063
- buildGenRef.current.bump()
3166
+ async (network: AppChain, opts: { fallback?: boolean } = {}) => {
3167
+ // The ref, not the state: the fallback below runs inside the same call.
3168
+ const from = selectedNetworkRef.current
3169
+ if (network === from || switchInFlightRef.current) return
3170
+ logWithTimestamp(F, `Switching network from ${from} to ${network}`)
3171
+ const token = buildGenRef.current.bump()
3064
3172
  // Same hold-off as switchProfile: no build may start on the old network
3065
3173
  // between teardown's walletBuilt flip and finalizeConfig below.
3066
3174
  profileTransitionRef.current = true
3175
+ // The fallback below reports a failure; a revert (no fallback) leaves it to the build.
3176
+ const owner = opts.fallback !== false ? {} : null
3177
+ if (owner) buildFailureReportedRef.current = owner
3178
+ let settled = false
3067
3179
  const newConfig = { wabUrl: 'noWAB', method: 'mnemonic', network, storageUrl: 'local' }
3068
3180
  try {
3069
- await teardownBuiltWallet()
3181
+ try {
3182
+ await teardownBuiltWallet()
3070
3183
 
3071
- // Persist new config
3072
- await updateProfile(getActiveProfileIndex(), { network })
3073
- await setItem('finalConfig', JSON.stringify(newConfig))
3184
+ // Persist new config
3185
+ await updateProfile(getActiveProfileIndex(), { network })
3186
+ await setItem('finalConfig', JSON.stringify(newConfig))
3074
3187
 
3075
- // Re-finalize with new network — the request below triggers the auto-build effect
3076
- finalizeConfig(newConfig)
3188
+ // Re-finalize with new network — the request below triggers the auto-build effect
3189
+ pendingAutoBuildRef.current = true
3190
+ finalizeConfig(newConfig)
3191
+ } finally {
3192
+ profileTransitionRef.current = false
3193
+ }
3194
+ setAutoBuildRequest(r => r + 1)
3195
+ logWithTimestamp(F, `Network switched to ${network}`)
3196
+ settled = await waitForRebuild(token)
3077
3197
  } finally {
3078
- profileTransitionRef.current = false
3198
+ if (owner && buildFailureReportedRef.current === owner) buildFailureReportedRef.current = null
3199
+ }
3200
+ // Still building (a restore that stopped reporting progress): not a
3201
+ // failure, and nothing may be built over it, so no revert. Its outcome
3202
+ // reports itself: a wallet, or the generic failure toast.
3203
+ if (walletBuiltRef.current || !buildGenRef.current.isCurrent(token) || !settled) return
3204
+
3205
+ if (opts.fallback !== false) {
3206
+ logWithTimestamp(F, `${network} failed to build; returning to ${from}`)
3207
+ reportNetworkFailedRef.current(network)
3208
+ await switchNetworkRef.current?.(from, { fallback: false })
3079
3209
  }
3080
- setAutoBuildRequest(r => r + 1)
3081
- logWithTimestamp(F, `Network switched to ${network}`)
3082
3210
  },
3083
- [selectedNetwork, setItem, teardownBuiltWallet, finalizeConfig]
3211
+ [setItem, teardownBuiltWallet, finalizeConfig, waitForRebuild]
3084
3212
  )
3213
+ const switchNetworkRef = useRef<typeof switchNetwork | null>(null)
3214
+ switchNetworkRef.current = switchNetwork
3085
3215
 
3086
3216
  /**
3087
3217
  * Switch to wallet profile `n`: its own keys (m/0'/n', m/1'/n'), database,
@@ -3111,32 +3241,41 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3111
3241
  const token = buildGenRef.current.bump()
3112
3242
  restoreIntentRef.current = false
3113
3243
  reviewImportedCoinsRef.current = false
3114
- // Pairings belong to the departing identity.
3115
- disconnectActivePairedSession()
3116
- profileTransitionRef.current = true
3244
+ const fallback = opts.fallback !== false && from !== n
3245
+ const owner = fallback ? {} : null
3246
+ if (owner) buildFailureReportedRef.current = owner
3247
+ let settled = false
3248
+ let __tBuild = 0
3117
3249
  try {
3118
- await teardownBuiltWallet()
3119
- const __tTeardown = performance.now()
3120
- await setActiveProfile(n)
3121
- await reloadProfileCaches()
3122
- await setItem(
3123
- 'finalConfig',
3124
- JSON.stringify({ wabUrl: 'noWAB', method: 'mnemonic', network: record.network, storageUrl: 'local' })
3125
- )
3126
- if (__DEV__) {
3127
- console.warn(
3128
- `[perf] switchProfile teardown ${(__tTeardown - __t0).toFixed(0)}ms, ` +
3129
- `store+caches ${(performance.now() - __tTeardown).toFixed(0)}ms`
3250
+ // Pairings belong to the departing identity.
3251
+ disconnectActivePairedSession()
3252
+ profileTransitionRef.current = true
3253
+ try {
3254
+ await teardownBuiltWallet()
3255
+ const __tTeardown = performance.now()
3256
+ await setActiveProfile(n)
3257
+ await reloadProfileCaches()
3258
+ await setItem(
3259
+ 'finalConfig',
3260
+ JSON.stringify({ wabUrl: 'noWAB', method: 'mnemonic', network: record.network, storageUrl: 'local' })
3130
3261
  )
3262
+ if (__DEV__) {
3263
+ console.warn(
3264
+ `[perf] switchProfile teardown ${(__tTeardown - __t0).toFixed(0)}ms, ` +
3265
+ `store+caches ${(performance.now() - __tTeardown).toFixed(0)}ms`
3266
+ )
3267
+ }
3268
+ pendingAutoBuildRef.current = true
3269
+ finalizeConfig({ wabUrl: 'noWAB', method: 'mnemonic', network: record.network, storageUrl: 'local' })
3270
+ } finally {
3271
+ profileTransitionRef.current = false
3131
3272
  }
3132
- pendingAutoBuildRef.current = true
3133
- finalizeConfig({ wabUrl: 'noWAB', method: 'mnemonic', network: record.network, storageUrl: 'local' })
3273
+ setAutoBuildRequest(r => r + 1)
3274
+ __tBuild = performance.now()
3275
+ settled = await waitForRebuild(token)
3134
3276
  } finally {
3135
- profileTransitionRef.current = false
3277
+ if (owner && buildFailureReportedRef.current === owner) buildFailureReportedRef.current = null
3136
3278
  }
3137
- setAutoBuildRequest(r => r + 1)
3138
- const __tBuild = performance.now()
3139
- await waitForRebuild(token)
3140
3279
  if (__DEV__) {
3141
3280
  console.warn(
3142
3281
  `[perf] switchProfile build ${(performance.now() - __tBuild).toFixed(0)}ms, ` +
@@ -3144,8 +3283,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3144
3283
  )
3145
3284
  }
3146
3285
  if (walletBuiltRef.current || !buildGenRef.current.isCurrent(token)) return true
3286
+ // Still building: not a failure to fall back from (see switchNetwork).
3287
+ if (!settled) return false
3147
3288
 
3148
- if (opts.fallback !== false && from !== n) {
3289
+ if (fallback) {
3149
3290
  logWithTimestamp(F, `Profile ${n} failed to build; returning to profile ${from}`)
3150
3291
  onToast?.(t('profile_switch_failed', { profile: profileLabel(record, t) }), { type: 'error' })
3151
3292
  await switchProfileImplRef.current?.(from, { fallback: false })
@@ -3181,11 +3322,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3181
3322
  switchProfileRef.current = switchProfile
3182
3323
 
3183
3324
  /** Append the next profile on mainnet and switch to it. If this seed already
3184
- * backed that profile up (a profile discovery missed), its history comes back. */
3325
+ * backed that profile up (a profile discovery missed), its history comes back,
3326
+ * on each network the first time the profile is built there. */
3185
3327
  const addProfile = useCallback(async () => {
3186
3328
  if (!profilesSupported) return
3187
3329
  await runProfileTransition(async () => {
3188
- const record = await appendProfile('main', { needsRestore: true })
3330
+ const record = await appendProfile('main', { restorePending: BACKUP_CHAINS })
3189
3331
  await switchProfileImpl(record.index)
3190
3332
  })
3191
3333
  }, [profilesSupported, runProfileTransition, switchProfileImpl])
@@ -3341,20 +3483,59 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
3341
3483
  // walletBuildingRef synchronously, in this same tick) — waitForRebuild can
3342
3484
  // stop treating this generation as "not yet started".
3343
3485
  pendingAutoBuildRef.current = false
3486
+ // A build on a network still waiting for its restore fails when the restore
3487
+ // cannot run (offline, the server down) — typically a cold start after the
3488
+ // app was killed during a switch's restore. A switch has its own fallback
3489
+ // (buildFailureReportedRef); anything else opens the network this profile
3490
+ // last built instead, which has its own database and nothing pending, so
3491
+ // nothing replays over it. The network stays pending, so the restore is
3492
+ // retried the next time it is built.
3493
+ const network = selectedNetworkRef.current
3494
+ const profile = getActiveProfile()
3495
+ const fallbackNetwork =
3496
+ !buildFailureReportedRef.current &&
3497
+ profile.restorePending?.includes(network) &&
3498
+ profile.lastBuiltNetwork !== undefined &&
3499
+ profile.lastBuiltNetwork !== network &&
3500
+ !profile.restorePending.includes(profile.lastBuiltNetwork)
3501
+ ? profile.lastBuiltNetwork
3502
+ : undefined
3503
+ const buildToken = buildGenRef.current.current()
3504
+ const owner = fallbackNetwork ? {} : null
3344
3505
  ;(async () => {
3345
- // Try mnemonic-based build first (calls getMnemonic internally)
3346
- await buildWalletFromMnemonic()
3347
- // Only missing mnemonic material allows a recovered-key fallback. A
3348
- // restore failure must remain failed so the import screen can offer a
3349
- // retry; a leftover WIF must not build over that partial replay.
3350
- if (mnemonicMissingRef.current && !walletBuiltRef.current && !walletBuildingRef.current) {
3351
- const recoveredWif = await getRecoveredKey()
3352
- if (recoveredWif) {
3353
- await buildWalletFromRecoveredKey(recoveredWif)
3354
- } else {
3355
- // No mnemonic and no recovered key — genuinely no wallet to build
3356
- setWalletBuilding(false)
3506
+ if (owner) buildFailureReportedRef.current = owner
3507
+ buildThrewRef.current = false
3508
+ try {
3509
+ // Try mnemonic-based build first (calls getMnemonic internally)
3510
+ await buildWalletFromMnemonic()
3511
+ // Only missing mnemonic material allows a recovered-key fallback. A
3512
+ // restore failure must remain failed so the import screen can offer a
3513
+ // retry; a leftover WIF must not build over that partial replay.
3514
+ if (mnemonicMissingRef.current && !walletBuiltRef.current && !walletBuildingRef.current) {
3515
+ const recoveredWif = await getRecoveredKey()
3516
+ if (recoveredWif) {
3517
+ await buildWalletFromRecoveredKey(recoveredWif)
3518
+ } else {
3519
+ // No mnemonic and no recovered key — genuinely no wallet to build
3520
+ setWalletBuilding(false)
3521
+ }
3357
3522
  }
3523
+ } finally {
3524
+ if (owner && buildFailureReportedRef.current === owner) buildFailureReportedRef.current = null
3525
+ }
3526
+ if (
3527
+ fallbackNetwork &&
3528
+ !walletBuiltRef.current &&
3529
+ !walletBuildingRef.current &&
3530
+ // The build ran and threw, whatever the step (its restore, migrate, the
3531
+ // registry): this owner suppressed the generic toast, so it reports
3532
+ // every such failure. Not a missing secret, where no build ran.
3533
+ buildThrewRef.current &&
3534
+ buildGenRef.current.isCurrent(buildToken)
3535
+ ) {
3536
+ logWithTimestamp(F, `${network} failed to build; opening ${fallbackNetwork}`)
3537
+ reportNetworkFailedRef.current(network)
3538
+ await switchNetworkRef.current?.(fallbackNetwork, { fallback: false })
3358
3539
  }
3359
3540
  })()
3360
3541
  }, [