@bsv/expo-wallet-toolbox 0.15.2 → 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 +199 -0
- package/core/backup/appData.ts +5 -1
- package/core/backup/codec.ts +9 -3
- package/core/backup/contactsBackup.ts +145 -0
- package/core/backup/push.ts +14 -0
- package/core/backup/restore.ts +26 -4
- package/core/backup/restoreOnImport.ts +28 -4
- package/core/contacts/contactsStore.ts +47 -3
- package/core/context/LocalStorageProvider.tsx +3 -1
- package/core/context/WalletContext.tsx +256 -76
- package/core/context/startupPrewarm.ts +54 -0
- 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/hooks/useConfirmationSound.ts +7 -0
- package/core/i18n/translations.tsx +354 -12
- package/core/identity/handleRegistry/client.ts +2 -1
- package/core/identity/handleRegistry/profileKeys.ts +16 -0
- package/core/identity/handleRegistry/resolver.ts +2 -1
- package/core/identity/handleRegistry/rules.ts +7 -3
- package/core/index.ts +14 -2
- package/core/localpay/build.ts +4 -3
- package/core/localpay/session.ts +6 -0
- package/core/localpay/transport/select.ts +64 -3
- package/core/localpay/verify.ts +2 -1
- package/core/net/trimTrailingSlashes.ts +13 -0
- package/core/parsePeerPayURI.ts +25 -2
- package/core/pay/creditInbox.ts +31 -1
- package/core/pay/rails/address.ts +3 -2
- package/core/pay/rails/handle.ts +8 -2
- package/core/pay/rails/index.ts +6 -4
- package/core/pos/protocol.ts +172 -0
- package/core/profiles/discovery.ts +17 -8
- package/core/profiles/profileStore.ts +34 -7
- package/core/profiles/removalProblems.ts +41 -0
- package/core/push/registration.ts +2 -1
- package/core/services/callbackToken.ts +7 -0
- package/core/services/revokeConnection.ts +98 -0
- package/core/storage/schema/createTables.ts +24 -0
- package/core/toolboxConfig.ts +85 -5
- package/package.json +1 -1
- package/ui/components/pay/MessageBoxConfig.tsx +2 -1
- package/ui/components/pay/NearbyFlow.tsx +410 -7
- package/ui/exportTransactions.ts +26 -13
- package/ui/index.ts +2 -2
- package/ui/screens/ConnectionsScreen.tsx +8 -63
- package/ui/screens/ProfileScreen.tsx +2 -40
- package/ui/screens/WalletConfigScreen.tsx +57 -51
|
@@ -206,6 +206,7 @@ import {
|
|
|
206
206
|
combineEmpty,
|
|
207
207
|
type DatabasesEmptyDeps
|
|
208
208
|
} from '../profiles/assertProfileEmpty'
|
|
209
|
+
import { takeStartupConfig } from './startupPrewarm'
|
|
209
210
|
import { purgeProfile, purgeRemovedProfiles, type PurgeProfileIo } from '../profiles/purgeProfile'
|
|
210
211
|
import {
|
|
211
212
|
checkProfileRemoval as runProfileRemovalCheck,
|
|
@@ -272,7 +273,7 @@ import { pushOnce } from '../backup/push'
|
|
|
272
273
|
import { BACKUP_PUSH_ENABLED_KEY } from '../backup/preference'
|
|
273
274
|
import { restoreOnImport } from '../backup/restoreOnImport'
|
|
274
275
|
import { backupPseudonym } from '../backup/derive'
|
|
275
|
-
import type
|
|
276
|
+
import { BACKUP_CHAINS, type BackupChain } from '../backup/constants'
|
|
276
277
|
import { processOfflineActions } from '../storage/methods/processOfflineActions'
|
|
277
278
|
import { findOfflineActions } from '../storage/methods/offlineActions'
|
|
278
279
|
import { boundedHexResponse, isChainAbsenceConfirmed, shouldFailUnprovenTx } from '../pay/refreshProofGuard'
|
|
@@ -787,6 +788,9 @@ async function probeForLegacyDb(legacyName: string): Promise<boolean> {
|
|
|
787
788
|
}
|
|
788
789
|
}
|
|
789
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
|
+
|
|
790
794
|
/**
|
|
791
795
|
* Minimal shape of the app's toast function. `core` must never import a `ui`
|
|
792
796
|
* component (see context/VaultContext.tsx's identical `VaultToast` for the
|
|
@@ -915,6 +919,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
915
919
|
setBackupRestoreState(next)
|
|
916
920
|
}, [])
|
|
917
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)
|
|
918
928
|
const getWalletBuilt = useCallback((): boolean => walletBuiltRef.current, [])
|
|
919
929
|
/**
|
|
920
930
|
* Set once buildWallet resolves this build's backup chain/pseudonym, so a screen (Wallet
|
|
@@ -970,18 +980,35 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
970
980
|
* rebuildWallet bumped to; a later teardown (another rebuild, a network
|
|
971
981
|
* switch) bumps past it and this returns immediately rather than waiting on
|
|
972
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.
|
|
973
987
|
*/
|
|
974
|
-
const waitForRebuild = useCallback(async (token: number, timeoutMs = 300000): Promise<
|
|
988
|
+
const waitForRebuild = useCallback(async (token: number, timeoutMs = 300000): Promise<boolean> => {
|
|
975
989
|
// A restore replays the encrypted backup log INSIDE the build, before
|
|
976
|
-
// walletBuiltRef flips — a large history can legitimately take
|
|
977
|
-
//
|
|
978
|
-
//
|
|
979
|
-
//
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
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
|
|
983
1009
|
await new Promise(resolve => setTimeout(resolve, 40))
|
|
984
1010
|
}
|
|
1011
|
+
return false
|
|
985
1012
|
}, [])
|
|
986
1013
|
const [localPayNotification, setLocalPayNotification] = useState<{
|
|
987
1014
|
message: string
|
|
@@ -1309,6 +1336,21 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1309
1336
|
const profileTransitionRef = useRef(false)
|
|
1310
1337
|
/** A whole switch or add, from the tap until its build lands (see runProfileTransition). */
|
|
1311
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' })
|
|
1312
1354
|
const [switchingProfile, setSwitchingProfile] = useState(false)
|
|
1313
1355
|
/** The profile a removal is working on, for the cover's label; null the rest of the time. */
|
|
1314
1356
|
const [removingProfile, setRemovingProfile] = useState<number | null>(null)
|
|
@@ -1356,13 +1398,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1356
1398
|
// The active profile picks the network, keys and database, so it must be in
|
|
1357
1399
|
// memory before anything builds. Per-profile caches that were read at import
|
|
1358
1400
|
// or mount time (before this resolved) are re-read for the profile it names.
|
|
1359
|
-
|
|
1401
|
+
// begun at startup if the app prewarmed (core/context/startupPrewarm)
|
|
1402
|
+
const warm = takeStartupConfig()
|
|
1403
|
+
await (warm ? warm.profiles : loadProfiles())
|
|
1360
1404
|
// A removal that stopped between its tombstone and its purge (a crash, a
|
|
1361
1405
|
// locked store) still has its history on disk: purge it again. Idempotent,
|
|
1362
1406
|
// best effort, and never in the way of startup.
|
|
1363
1407
|
void purgeRemovedProfiles(getProfilesState().profiles, profilePurgeIo).catch(() => {})
|
|
1364
1408
|
await reloadProfileCaches()
|
|
1365
|
-
const storedConfig = await getItem('finalConfig')
|
|
1409
|
+
const storedConfig = warm ? await warm.config : await getItem('finalConfig')
|
|
1366
1410
|
if (storedConfig) {
|
|
1367
1411
|
try {
|
|
1368
1412
|
const config = JSON.parse(storedConfig)
|
|
@@ -1621,6 +1665,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1621
1665
|
// discovered on disk). Only true in the "fresh user" branch — see its use at
|
|
1622
1666
|
// the restore-failure cleanup further down (XR-017 review follow-up).
|
|
1623
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
|
|
1624
1671
|
|
|
1625
1672
|
if (knownDbs.length === 0) {
|
|
1626
1673
|
// First launch after update or fresh user.
|
|
@@ -1630,6 +1677,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1630
1677
|
if (hasLegacy) {
|
|
1631
1678
|
await registerDb(keySuffix, chainStr, legacyName)
|
|
1632
1679
|
knownDbs = [legacyName]
|
|
1680
|
+
adoptedLegacyDb = true
|
|
1633
1681
|
console.log(`[WalletContext] Registered legacy DB: ${legacyName}`)
|
|
1634
1682
|
} else {
|
|
1635
1683
|
// Fresh user — create a timestamped database
|
|
@@ -1659,16 +1707,55 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1659
1707
|
|
|
1660
1708
|
console.log('[WalletContext] Local SQLite storage initialized successfully')
|
|
1661
1709
|
|
|
1662
|
-
// ──
|
|
1710
|
+
// ── Restore ─────────────────────────────────────────────────────────
|
|
1663
1711
|
//
|
|
1664
1712
|
// Deliberately HERE: the database is migrated and empty, nothing has been
|
|
1665
1713
|
// published to the app yet, and the monitor (with its backup push task) does
|
|
1666
1714
|
// not exist — so this device cannot have written a log of its own that the
|
|
1667
1715
|
// restore would then pick as the newest. See utils/backup/restoreOnImport.ts.
|
|
1668
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
|
+
//
|
|
1669
1735
|
// A failure throws, which aborts the whole build: the import screen reports it
|
|
1670
|
-
// and lets the user retry or continue without history
|
|
1671
|
-
//
|
|
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
|
+
|
|
1672
1759
|
let localStorageAdded = false
|
|
1673
1760
|
const addLocalStorage = async () => {
|
|
1674
1761
|
if (localStorageAdded) return
|
|
@@ -1676,7 +1763,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1676
1763
|
localStorageAdded = true
|
|
1677
1764
|
}
|
|
1678
1765
|
|
|
1679
|
-
if (
|
|
1766
|
+
if (restoreRequested || restorePending) {
|
|
1680
1767
|
restoreIntentRef.current = false
|
|
1681
1768
|
setBackupRestore({ phase: 'checking', chunks: 0, total: 0 })
|
|
1682
1769
|
try {
|
|
@@ -1687,6 +1774,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1687
1774
|
identityKey,
|
|
1688
1775
|
baseUrl: getBackupUrl(),
|
|
1689
1776
|
onProgress: (chunks, total) => setBackupRestore({ phase: 'restoring', chunks, total }),
|
|
1777
|
+
onActivity: () => {
|
|
1778
|
+
restoreActivityRef.current++
|
|
1779
|
+
},
|
|
1690
1780
|
// reviewSpendableOutputs talks to Services through the Wallet, which
|
|
1691
1781
|
// needs this storage attached first. Attach here (idempotent with the
|
|
1692
1782
|
// call below) so the post-restore pass actually sees the replayed coins.
|
|
@@ -1709,6 +1799,7 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1709
1799
|
`[WalletContext] backup restore · restored=${String(restored.restored)} · ` +
|
|
1710
1800
|
`chunks=${restored.chunks} · reason=${restored.reason ?? 'none'}`
|
|
1711
1801
|
)
|
|
1802
|
+
await settleRestore()
|
|
1712
1803
|
// See P1-backup-incomplete-generation: restoreOnImport.pickTarget falls back to
|
|
1713
1804
|
// an unverified (no seal) target rather than blocking the import, so this is a
|
|
1714
1805
|
// warning rather than a thrown error — but it must not pass silently, since the
|
|
@@ -2654,15 +2745,17 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
2654
2745
|
}
|
|
2655
2746
|
vaultStore.configureScope({ identityKey: keyDeriver.identityKey, chain: backupChain, profileIndex })
|
|
2656
2747
|
// The identity is public; Delete Wallet needs it to find this profile's
|
|
2657
|
-
// databases.
|
|
2658
|
-
|
|
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 })
|
|
2659
2751
|
updateManagers(m => ({ ...m, ...newManagers }))
|
|
2660
2752
|
logWithTimestamp(F, 'Wallet build completed successfully')
|
|
2661
2753
|
|
|
2662
2754
|
return permissionsManager
|
|
2663
2755
|
} catch (error: any) {
|
|
2664
2756
|
console.error('Error building wallet:', error)
|
|
2665
|
-
|
|
2757
|
+
buildThrewRef.current = true
|
|
2758
|
+
if (!buildFailureReportedRef.current) onToast?.('Failed to build wallet: ' + error.message, { type: 'error' })
|
|
2666
2759
|
logWithTimestamp(F, 'Error building wallet', error.message)
|
|
2667
2760
|
// SimpleWalletManager authenticates whenever its builder resolves,
|
|
2668
2761
|
// even to null. Reject so a failed restore cannot mark a wallet built.
|
|
@@ -2699,7 +2792,8 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
2699
2792
|
const buildFromMnemonicRef = useRef<((m?: string, o?: WalletBuildOptions) => Promise<void>) | null>(null)
|
|
2700
2793
|
|
|
2701
2794
|
/** After a seed import, find the other profiles it backed up (see core/profiles/discovery).
|
|
2702
|
-
* 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. */
|
|
2703
2797
|
const discoverProfilesRef = useRef<((mnemonic: string) => void) | null>(null)
|
|
2704
2798
|
discoverProfilesRef.current = (mnemonic: string) => {
|
|
2705
2799
|
const baseUrl = getBackupUrl()
|
|
@@ -2714,9 +2808,9 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
2714
2808
|
probe: async (primaryKey, chain) => stillOwned() && (await backupProbe(baseUrl)(primaryKey, chain)),
|
|
2715
2809
|
// A profile removed on this device stays removed (and does not end the search).
|
|
2716
2810
|
skip: index => !!getProfilesState().profiles[index]?.deleted,
|
|
2717
|
-
register: async (index, network) => {
|
|
2811
|
+
register: async (index, network, chains) => {
|
|
2718
2812
|
// Idempotent: a second import of the same seed must not duplicate profiles.
|
|
2719
|
-
if (stillOwned()) await registerDiscoveredProfile(index, network)
|
|
2813
|
+
if (stillOwned()) await registerDiscoveredProfile(index, network, chains)
|
|
2720
2814
|
}
|
|
2721
2815
|
})
|
|
2722
2816
|
.then(n => {
|
|
@@ -2807,9 +2901,6 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
2807
2901
|
// allows the import screen to continue without restoring on retry.
|
|
2808
2902
|
if (opts !== undefined) restoreIntentRef.current = opts.restoreFromBackup === true
|
|
2809
2903
|
if (opts !== undefined) reviewImportedCoinsRef.current = opts.reviewImportedCoins === true
|
|
2810
|
-
// A profile found by restore discovery, or just added, replays its own
|
|
2811
|
-
// remote backup on its first build — on whichever launch that happens.
|
|
2812
|
-
if (getProfilesState().profiles[profileIndex]?.needsRestore) restoreIntentRef.current = true
|
|
2813
2904
|
// Captured before buildWallet consumes it: an import of profile 0 is what
|
|
2814
2905
|
// triggers discovery of the other profiles this seed has backed up.
|
|
2815
2906
|
const wantedRestore = restoreIntentRef.current
|
|
@@ -2906,9 +2997,18 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
2906
2997
|
try {
|
|
2907
2998
|
const recoveredKey = PrivateKey.fromWif(wif)
|
|
2908
2999
|
const primaryKey = recoveredKey.toArray()
|
|
2909
|
-
// 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.
|
|
2910
3003
|
setProfilesSupported(false)
|
|
2911
|
-
|
|
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
|
+
}
|
|
2912
3012
|
|
|
2913
3013
|
// The recovered key doubles as the privileged key — there is no seed to
|
|
2914
3014
|
// derive a separate one from. guardVaultAccess is what keeps non-admin
|
|
@@ -3053,32 +3153,61 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
3053
3153
|
|
|
3054
3154
|
// Switch network: tear down wallet, update config, and rebuild on new chain.
|
|
3055
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.
|
|
3056
3161
|
const switchNetwork = useCallback(
|
|
3057
|
-
async (network: AppChain) => {
|
|
3058
|
-
|
|
3059
|
-
|
|
3060
|
-
|
|
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()
|
|
3061
3168
|
// Same hold-off as switchProfile: no build may start on the old network
|
|
3062
3169
|
// between teardown's walletBuilt flip and finalizeConfig below.
|
|
3063
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
|
|
3064
3175
|
const newConfig = { wabUrl: 'noWAB', method: 'mnemonic', network, storageUrl: 'local' }
|
|
3065
3176
|
try {
|
|
3066
|
-
|
|
3177
|
+
try {
|
|
3178
|
+
await teardownBuiltWallet()
|
|
3067
3179
|
|
|
3068
|
-
|
|
3069
|
-
|
|
3070
|
-
|
|
3180
|
+
// Persist new config
|
|
3181
|
+
await updateProfile(getActiveProfileIndex(), { network })
|
|
3182
|
+
await setItem('finalConfig', JSON.stringify(newConfig))
|
|
3071
3183
|
|
|
3072
|
-
|
|
3073
|
-
|
|
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)
|
|
3074
3193
|
} finally {
|
|
3075
|
-
|
|
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 })
|
|
3076
3205
|
}
|
|
3077
|
-
setAutoBuildRequest(r => r + 1)
|
|
3078
|
-
logWithTimestamp(F, `Network switched to ${network}`)
|
|
3079
3206
|
},
|
|
3080
|
-
[
|
|
3207
|
+
[setItem, teardownBuiltWallet, finalizeConfig, waitForRebuild]
|
|
3081
3208
|
)
|
|
3209
|
+
const switchNetworkRef = useRef<typeof switchNetwork | null>(null)
|
|
3210
|
+
switchNetworkRef.current = switchNetwork
|
|
3082
3211
|
|
|
3083
3212
|
/**
|
|
3084
3213
|
* Switch to wallet profile `n`: its own keys (m/0'/n', m/1'/n'), database,
|
|
@@ -3108,32 +3237,41 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
3108
3237
|
const token = buildGenRef.current.bump()
|
|
3109
3238
|
restoreIntentRef.current = false
|
|
3110
3239
|
reviewImportedCoinsRef.current = false
|
|
3111
|
-
|
|
3112
|
-
|
|
3113
|
-
|
|
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
|
|
3114
3245
|
try {
|
|
3115
|
-
|
|
3116
|
-
|
|
3117
|
-
|
|
3118
|
-
|
|
3119
|
-
|
|
3120
|
-
|
|
3121
|
-
|
|
3122
|
-
|
|
3123
|
-
|
|
3124
|
-
|
|
3125
|
-
|
|
3126
|
-
`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' })
|
|
3127
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
|
|
3128
3268
|
}
|
|
3129
|
-
|
|
3130
|
-
|
|
3269
|
+
setAutoBuildRequest(r => r + 1)
|
|
3270
|
+
__tBuild = performance.now()
|
|
3271
|
+
settled = await waitForRebuild(token)
|
|
3131
3272
|
} finally {
|
|
3132
|
-
|
|
3273
|
+
if (owner && buildFailureReportedRef.current === owner) buildFailureReportedRef.current = null
|
|
3133
3274
|
}
|
|
3134
|
-
setAutoBuildRequest(r => r + 1)
|
|
3135
|
-
const __tBuild = performance.now()
|
|
3136
|
-
await waitForRebuild(token)
|
|
3137
3275
|
if (__DEV__) {
|
|
3138
3276
|
console.warn(
|
|
3139
3277
|
`[perf] switchProfile build ${(performance.now() - __tBuild).toFixed(0)}ms, ` +
|
|
@@ -3141,8 +3279,10 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
3141
3279
|
)
|
|
3142
3280
|
}
|
|
3143
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
|
|
3144
3284
|
|
|
3145
|
-
if (
|
|
3285
|
+
if (fallback) {
|
|
3146
3286
|
logWithTimestamp(F, `Profile ${n} failed to build; returning to profile ${from}`)
|
|
3147
3287
|
onToast?.(t('profile_switch_failed', { profile: profileLabel(record, t) }), { type: 'error' })
|
|
3148
3288
|
await switchProfileImplRef.current?.(from, { fallback: false })
|
|
@@ -3178,11 +3318,12 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
3178
3318
|
switchProfileRef.current = switchProfile
|
|
3179
3319
|
|
|
3180
3320
|
/** Append the next profile on mainnet and switch to it. If this seed already
|
|
3181
|
-
* 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. */
|
|
3182
3323
|
const addProfile = useCallback(async () => {
|
|
3183
3324
|
if (!profilesSupported) return
|
|
3184
3325
|
await runProfileTransition(async () => {
|
|
3185
|
-
const record = await appendProfile('main', {
|
|
3326
|
+
const record = await appendProfile('main', { restorePending: BACKUP_CHAINS })
|
|
3186
3327
|
await switchProfileImpl(record.index)
|
|
3187
3328
|
})
|
|
3188
3329
|
}, [profilesSupported, runProfileTransition, switchProfileImpl])
|
|
@@ -3338,20 +3479,59 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
3338
3479
|
// walletBuildingRef synchronously, in this same tick) — waitForRebuild can
|
|
3339
3480
|
// stop treating this generation as "not yet started".
|
|
3340
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
|
|
3341
3501
|
;(async () => {
|
|
3342
|
-
|
|
3343
|
-
|
|
3344
|
-
|
|
3345
|
-
|
|
3346
|
-
|
|
3347
|
-
|
|
3348
|
-
|
|
3349
|
-
|
|
3350
|
-
|
|
3351
|
-
|
|
3352
|
-
|
|
3353
|
-
|
|
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
|
+
}
|
|
3354
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 })
|
|
3355
3535
|
}
|
|
3356
3536
|
})()
|
|
3357
3537
|
}, [
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Startup reads that need nothing from React, begun before the app renders.
|
|
3
|
+
*
|
|
4
|
+
* LocalStorageProvider's secrets migration and WalletContext's configuration
|
|
5
|
+
* (the profiles, then the stored config) used to start in effects, after the
|
|
6
|
+
* whole first screen had rendered and committed; the wallet build waits on both.
|
|
7
|
+
* An app calls prewarmStartup() from its entry file, once the crypto seams are
|
|
8
|
+
* installed, and the reads run while the app renders. Each is taken once: the
|
|
9
|
+
* provider that would have started it awaits the one in flight instead. Taken,
|
|
10
|
+
* or never begun (an app that doesn't prewarm), the provider does the work
|
|
11
|
+
* itself, as before; a later run (after logout) always does.
|
|
12
|
+
*/
|
|
13
|
+
import AsyncStorage from '@react-native-async-storage/async-storage'
|
|
14
|
+
import { loadProfiles } from '../profiles/profileStore'
|
|
15
|
+
import { migrateLegacySecrets, type MigrationResult } from '../services/secrets'
|
|
16
|
+
|
|
17
|
+
export interface StartupConfig {
|
|
18
|
+
/** loadProfiles(), done: the active profile is in memory */
|
|
19
|
+
profiles: Promise<unknown>
|
|
20
|
+
/** the stored 'finalConfig', read once the profiles are */
|
|
21
|
+
config: Promise<string | null>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
let secrets: Promise<MigrationResult> | null = null
|
|
25
|
+
let config: StartupConfig | null = null
|
|
26
|
+
|
|
27
|
+
export function prewarmStartup(): void {
|
|
28
|
+
if (!secrets) {
|
|
29
|
+
secrets = migrateLegacySecrets()
|
|
30
|
+
// taken later (or never): an unhandled rejection meanwhile is noise
|
|
31
|
+
secrets.catch(() => {})
|
|
32
|
+
}
|
|
33
|
+
if (!config) {
|
|
34
|
+
const profiles = loadProfiles()
|
|
35
|
+
const stored = profiles.then(() => AsyncStorage.getItem('finalConfig'))
|
|
36
|
+
profiles.catch(() => {})
|
|
37
|
+
stored.catch(() => {})
|
|
38
|
+
config = { profiles, config: stored }
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The secrets migration begun at startup, if there's one not yet taken. */
|
|
43
|
+
export function takeStartupSecrets(): Promise<MigrationResult> | null {
|
|
44
|
+
const taken = secrets
|
|
45
|
+
secrets = null
|
|
46
|
+
return taken
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The configuration reads begun at startup, if not yet taken. */
|
|
50
|
+
export function takeStartupConfig(): StartupConfig | null {
|
|
51
|
+
const taken = config
|
|
52
|
+
config = null
|
|
53
|
+
return taken
|
|
54
|
+
}
|
|
@@ -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
|
+
}
|