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