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