@bsv/expo-wallet-toolbox 0.11.8 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/core/backup/erase.ts +7 -1
  3. package/core/backup/preference.ts +12 -4
  4. package/core/backup/push.ts +8 -1
  5. package/core/backup/status.ts +6 -2
  6. package/core/config.tsx +1 -1
  7. package/core/context/WalletContext.tsx +904 -184
  8. package/core/i18n/translations.tsx +496 -12
  9. package/core/identity/handleRegistry/registration.ts +57 -3
  10. package/core/index.ts +26 -1
  11. package/core/mandala/createRuntime.ts +3 -3
  12. package/core/mandala/runtime.ts +7 -2
  13. package/core/mnemonicWallet.ts +46 -40
  14. package/core/monitor/MonitorSupervisor.ts +35 -1
  15. package/core/monitor/TaskCreditInbox.ts +24 -0
  16. package/core/pay/beefRepair.ts +8 -3
  17. package/core/pay/rails/address.ts +43 -3
  18. package/core/pay/rails/handle.ts +5 -3
  19. package/core/pay/sweeper.ts +39 -4
  20. package/core/peerpay/outbox.ts +11 -1
  21. package/core/profiles/assertProfileEmpty.ts +287 -0
  22. package/core/profiles/discovery.ts +84 -0
  23. package/core/profiles/profileLabel.ts +13 -0
  24. package/core/profiles/profileStore.ts +265 -0
  25. package/core/profiles/purgeProfile.ts +76 -0
  26. package/core/profiles/removeProfile.ts +257 -0
  27. package/core/push/events.ts +189 -0
  28. package/core/push/identities.ts +55 -0
  29. package/core/push/profilePush.ts +143 -0
  30. package/core/push/pushAdvisory.ts +33 -0
  31. package/core/push/registration.ts +391 -0
  32. package/core/push/types.ts +35 -0
  33. package/core/services/arcTokenStorage.ts +17 -2
  34. package/core/services/vault/transfers.ts +6 -1
  35. package/core/services/vault/vaultStore.ts +16 -3
  36. package/core/stores/ConnectionStore.ts +11 -7
  37. package/core/toolboxConfig.ts +31 -4
  38. package/core/userAvatar.ts +12 -5
  39. package/core/walletDbRegistry.ts +73 -0
  40. package/package.json +1 -1
  41. package/ui/backupShares.ts +2 -3
  42. package/ui/components/pay/HandleReceive.tsx +141 -16
  43. package/ui/components/pay/MessageBoxConfig.tsx +6 -5
  44. package/ui/components/pay/NotificationAdvisoryModal.tsx +124 -0
  45. package/ui/components/ui/PencilEditField.tsx +5 -2
  46. package/ui/components/wallet/Balance.tsx +3 -1
  47. package/ui/components/wallet/ProfileButton.tsx +92 -18
  48. package/ui/components/wallet/ProfileSwitcherPopover.tsx +247 -0
  49. package/ui/hooks/useOfflineNoticeActions.ts +2 -1
  50. package/ui/hooks/useSpendableBalance.ts +3 -1
  51. package/ui/index.ts +1 -0
  52. package/ui/printRecoveryShares.ts +6 -7
  53. package/ui/screens/PairScreen.tsx +2 -1
  54. package/ui/screens/PayScreen.tsx +53 -0
  55. package/ui/screens/ProfileScreen.tsx +195 -4
  56. package/ui/screens/SettingsScreen.tsx +80 -6
  57. package/ui/screens/VaultScreen.tsx +31 -2
  58. package/ui/screens/VaultTransferScreen.tsx +25 -2
  59. package/ui/screens/WalletCheckScreen.tsx +2 -1
  60. package/ui/screens/WalletConfigScreen.tsx +51 -21
  61. package/ui/screens/WalletHomeScreen.tsx +6 -3
  62. package/ui/tokenSeen.ts +13 -9
@@ -46,6 +46,9 @@ import { useAssetStatus, useMandala } from '../hooks/useMandala'
46
46
  import { formatTokenAmountWithUnit } from '../tokenFormat'
47
47
  import { nearbyAdvisory } from '../../core/localpay/nearbyAdvisory'
48
48
  import { NearbyAdvisoryModal } from '../components/pay/NearbyAdvisoryModal'
49
+ import { pushAdvisory } from '../../core/push/pushAdvisory'
50
+ import { getPushAdapter } from '../../core/toolboxConfig'
51
+ import { NotificationAdvisoryModal, shouldShowNotificationAdvisory } from '../components/pay/NotificationAdvisoryModal'
49
52
  import type { DismissTarget } from '../dismissTarget'
50
53
 
51
54
  /**
@@ -298,6 +301,35 @@ export function PayScreen({ dismissTo = '/' }: PayScreenProps = {}) {
298
301
  }, [])
299
302
  const isNearbyCell = (direction === 'pay' && nearbySession !== null) || method === 'get-nearby'
300
303
 
304
+ // ── notification advisory ───────────────────────────────────────────
305
+ /**
306
+ * The first time the user picks "Share remote link", the OS will be asked to
307
+ * allow notifications (so a payment can reach them while the app is in the
308
+ * background). The advisory goes first, over the link flow — which keeps
309
+ * mounting underneath and never waits on the answer. null = not loaded yet
310
+ * (show nothing rather than flash it at a returning user); both stay null
311
+ * until the user first lands on the remote-link method.
312
+ */
313
+ const [pushAdvisorySeen, setPushAdvisorySeen] = useState<boolean | null>(null)
314
+ const [pushPermission, setPushPermission] = useState<'granted' | 'denied' | 'undetermined' | null>(null)
315
+ useEffect(() => {
316
+ if (method !== 'get-handle' || pushAdvisorySeen !== null) return
317
+ let cancelled = false
318
+ const adapter = getPushAdapter()
319
+ void Promise.all([pushAdvisory.get(), adapter ? adapter.getPermission() : Promise.resolve(null)])
320
+ .then(([seen, perm]) => {
321
+ if (cancelled) return
322
+ setPushAdvisorySeen(seen)
323
+ setPushPermission(perm)
324
+ })
325
+ .catch(() => {
326
+ // Advisory only: a host adapter that cannot report its permission just means no modal.
327
+ })
328
+ return () => {
329
+ cancelled = true
330
+ }
331
+ }, [method, pushAdvisorySeen])
332
+
301
333
  // Refreshed whenever the wallet finishes building, connectivity changes, or
302
334
  // the user enters/leaves a method or a nearby session: the queue only moves
303
335
  // when the network state does or when one of those just queued a row (e.g.
@@ -595,6 +627,27 @@ export function PayScreen({ dismissTo = '/' }: PayScreenProps = {}) {
595
627
  setNearbyAdvisorySeen(true)
596
628
  }}
597
629
  />
630
+ <NotificationAdvisoryModal
631
+ visible={shouldShowNotificationAdvisory({
632
+ method,
633
+ advisorySeen: pushAdvisorySeen,
634
+ permission: pushPermission
635
+ })}
636
+ onNotNow={() => {
637
+ void pushAdvisory.set()
638
+ setPushAdvisorySeen(true)
639
+ }}
640
+ onContinue={() => {
641
+ void pushAdvisory.set()
642
+ setPushAdvisorySeen(true)
643
+ void getPushAdapter()
644
+ ?.requestPermission()
645
+ .then(setPushPermission)
646
+ .catch(() => {
647
+ // The link flow does not depend on the answer; Task 7's sync reads the permission itself.
648
+ })
649
+ }}
650
+ />
598
651
  </View>
599
652
  )
600
653
  }
@@ -1,7 +1,11 @@
1
1
  /**
2
- * Profile — your display name (pencil → confirm), your handle (registered
3
- * state, or the claim flow), and your Identifier with a way to show it as a
4
- * QR (its own screen) or copy it.
2
+ * Profile — this profile's private name and your display name (pencil →
3
+ * confirm), your handle (registered state, or the claim flow), and your
4
+ * Identifier with a way to show it as a QR (its own screen) or copy it.
5
+ *
6
+ * The profile name is a label for the switcher, kept on this device only (the
7
+ * profile store, not the wallet database): unlike the display name it is never
8
+ * published. A recovered-key wallet has no profiles, so no such field.
5
9
  *
6
10
  * The registry, not this device, is the source of truth for which handle this
7
11
  * key holds: `profile_registered_handle` is only an offline cache, shown at
@@ -10,6 +14,11 @@
10
14
  * anything. A build with no registry configured for the selected chain says so
11
15
  * (`profile_handle_unavailable`) rather than pretending a check can succeed.
12
16
  *
17
+ * A profile other than the first can be removed from here ("Remove profile"):
18
+ * the check runs first and explains a refusal, the confirm says what happens
19
+ * (and, with a handle, the cooldown it starts), and only then does it go. See
20
+ * core/profiles/removeProfile for what removal does and in what order.
21
+ *
13
22
  * The hero disc wears whatever icon the user picked ("Edit picture" →
14
23
  * "Pick icon"), and the same choice is what every other "you" in the app
15
24
  * draws — see `core/userAvatar.ts`. Photo sources are not offered yet: they
@@ -25,6 +34,7 @@ import PressableScale from '../components/ui/PressableScale'
25
34
  import { GroupedSection } from '../components/ui/GroupedList'
26
35
  import { ListRow } from '../components/ui/ListRow'
27
36
  import { PencilEditField } from '../components/ui/PencilEditField'
37
+ import { showAlert } from '../components/ui/AlertCard'
28
38
  import { showToast } from '../components/ui/Toast'
29
39
  import IdentifierRow from '../components/wallet/IdentifierRow'
30
40
  import { AvatarGlyph } from '../components/wallet/UserAvatar'
@@ -33,6 +43,14 @@ import IconPickerSheet from '../components/wallet/IconPickerSheet'
33
43
  import { makeIdentityClient, resolveIdentity } from '../resolveIdentity'
34
44
  import { getHandleRegistryConfig } from '../../core/toolboxConfig'
35
45
  import { bindOriginator } from '../../core/mandala/createRuntime'
46
+ import { profileLabel } from '../../core/profiles/profileLabel'
47
+ import type { RemovalBlocker } from '../../core/profiles/assertProfileEmpty'
48
+ import type { ProfileRemovalCheck, RemoveProfileResult } from '../../core/profiles/removeProfile'
49
+ import {
50
+ MAX_PROFILE_NAME_LENGTH,
51
+ updateProfile as updateProfileRecord,
52
+ useProfiles
53
+ } from '../../core/profiles/profileStore'
36
54
  import { isValidHandleFormat, parsePaymail } from '../../core/identity/handleRegistry/rules'
37
55
  import type { ProfileSigner } from '../../core/identity/handleRegistry/profileCert'
38
56
  import { createHandleRegistryClient, type AvailabilityReason } from '../../core/identity/handleRegistry/client'
@@ -79,14 +97,60 @@ const HANDLE_KV_KEY = 'profile_registered_handle'
79
97
  const DISPLAY_NAME_KV_KEY = 'profile_display_name'
80
98
  const HANDLE_CHECK_DEBOUNCE_MS = 400
81
99
 
100
+ /** What can stand in the way of removing a profile, grouped the way the user is told about it. */
101
+ const FUNDS_BLOCKERS: RemovalBlocker[] = ['spendable-outputs', 'token-balance']
102
+ const PENDING_BLOCKERS: RemovalBlocker[] = [
103
+ 'pending-transactions',
104
+ 'offline-queue',
105
+ 'token-settlements',
106
+ 'localpay-pending',
107
+ 'peerpay-outbox',
108
+ 'inbox-pending'
109
+ ]
110
+
111
+ type RemovalProblem = Exclude<ProfileRemovalCheck, { kind: 'ok' }> | Exclude<RemoveProfileResult, { kind: 'removed' }>
112
+
113
+ /**
114
+ * How long the switch cover takes to leave. A removal runs under it (a Modal on
115
+ * the Home screen underneath this one), and it is dismissed in the same tick the
116
+ * removal's answer arrives. iOS will not present a second Modal while the first
117
+ * is still dismissing, and an alert that is dropped never settles, so an
118
+ * explanation of a failure that followed the cover waits this long: the fade and
119
+ * a margin.
120
+ */
121
+ export const PROFILE_COVER_FADE_MS = 500
122
+ const untilCoverGone = () => new Promise<void>(resolve => setTimeout(resolve, PROFILE_COVER_FADE_MS))
123
+
124
+ /** The i18n keys that explain a refusal or failure, one paragraph per kind of reason. */
125
+ function removalProblemKeys(problem: RemovalProblem): string[] {
126
+ if (problem.kind === 'refused')
127
+ return [problem.reason === 'offline' ? 'profile_remove_offline' : 'profile_remove_failed']
128
+ if (problem.kind === 'handle-failed') return ['profile_remove_failed_handle']
129
+ if (problem.kind === 'blocked') {
130
+ const keys: string[] = []
131
+ const has = (group: RemovalBlocker[]) => problem.reasons.some(r => group.includes(r))
132
+ if (has(FUNDS_BLOCKERS)) keys.push('profile_remove_blocked_funds')
133
+ if (has(PENDING_BLOCKERS)) keys.push('profile_remove_blocked_pending')
134
+ // Funds or pending activity in the databases of its other networks, which the open one never shows.
135
+ if (problem.reasons.includes('other-network')) keys.push('profile_remove_blocked_network')
136
+ // An unfinished handle write is the same thing to the user as a handle that would not release.
137
+ if (problem.reasons.includes('handle-journal')) keys.push('profile_remove_failed_handle')
138
+ if (problem.reasons.includes('check-failed')) keys.push('profile_remove_blocked_check')
139
+ if (keys.length > 0) return keys
140
+ }
141
+ return ['profile_remove_failed']
142
+ }
143
+
82
144
  export function ProfileScreen() {
83
145
  const { t } = useTranslation()
84
146
  const { colors } = useTheme()
85
147
  const insets = useSafeAreaInsets()
86
148
  const Ionicons = loadIonicons()
87
149
  const { router } = loadExpoRouter()
88
- const { managers, adminOriginator, selectedNetwork, storage } = useWallet()
150
+ const { managers, adminOriginator, selectedNetwork, storage, profilesSupported, checkProfileRemoval, removeProfile } =
151
+ useWallet()
89
152
  const wallet = managers?.permissionsManager || null
153
+ const { active: activeProfile, profiles } = useProfiles()
90
154
 
91
155
  const [identityKey, setIdentityKey] = useState('')
92
156
  const avatarIcon = useUserAvatarIcon()
@@ -101,6 +165,14 @@ export function ProfileScreen() {
101
165
  const [registering, setRegistering] = useState(false)
102
166
  /** A journalled write that has not landed yet. Non-blocking, with a retry. */
103
167
  const [finishing, setFinishing] = useState(false)
168
+ /**
169
+ * Remove profile is running. Its own flag rather than a read of the active
170
+ * profile, which flips to 0 partway through — that is the removal working —
171
+ * and the row must not vanish from under its own spinner.
172
+ */
173
+ const [removing, setRemoving] = useState(false)
174
+ /** The same flag, readable before the next render: two taps in one frame must not start two removals. */
175
+ const removingRef = useRef(false)
104
176
 
105
177
  /**
106
178
  * Two strings, not the config object: `getHandleRegistryConfig` builds a
@@ -211,6 +283,19 @@ export function ProfileScreen() {
211
283
  } else if (result.kind === 'pending' || result.kind === 'idle') {
212
284
  // The callout says the first. The second is the ordinary mount, with
213
285
  // nothing journalled and so nothing to report.
286
+ } else if (result.kind === 'released') {
287
+ // Only a resumed journal gets here: this screen never starts a release
288
+ // itself, profile removal does. Finishing one means the handle is gone,
289
+ // and the lookup that follows the resume cannot be left to say so — it
290
+ // may be offline, and then the cache would keep offering a handle the
291
+ // registry no longer holds. Nothing to announce: the user asked for the
292
+ // removal that wrote the journal.
293
+ handleEpoch.current += 1
294
+ setRegisteredPaymail(null)
295
+ void storage?.setKeyValue(HANDLE_KV_KEY, '')
296
+ setChangingHandle(false)
297
+ setHandleInput('')
298
+ setAvailability('idle')
214
299
  } else if (result.kind === 'unavailable') {
215
300
  showToast(t('profile_handle_unavailable'), { type: 'error' })
216
301
  } else if (result.kind === 'rejected') {
@@ -402,6 +487,82 @@ export function ProfileScreen() {
402
487
  [storage, client, signer, registeredPaymail, finishing, applyResult, t]
403
488
  )
404
489
 
490
+ /** Only this device's store: the name is never published, so there is nothing to wait on. */
491
+ const onSaveProfileName = useCallback(
492
+ (next: string) => updateProfileRecord(activeProfile, { name: next }),
493
+ [activeProfile]
494
+ )
495
+
496
+ /**
497
+ * Ask, confirm, remove. The check comes first and changes nothing, so a
498
+ * refusal is explained before anyone is asked to confirm; the removal then
499
+ * checks again for itself, since the dialog may have sat open a while.
500
+ */
501
+ const onRemoveProfile = useCallback(async () => {
502
+ if (removingRef.current) return
503
+ removingRef.current = true
504
+ setRemoving(true)
505
+ // Named now: by the time anything is shown the active profile may be another one.
506
+ const label = profileLabel(profiles[activeProfile] ?? { index: activeProfile }, t)
507
+ let removed = false
508
+ /** The switch cover has been up since the removal started, so what follows it waits for it to go. */
509
+ let covered = false
510
+ const explain = async (problem: RemovalProblem) => {
511
+ if (covered) await untilCoverGone()
512
+ return showAlert({
513
+ title: t('profile_remove_problem_title', { profile: label }),
514
+ message: removalProblemKeys(problem)
515
+ .map(key => t(key))
516
+ .join('\n\n'),
517
+ buttons: [{ text: t('vault_ok'), key: 'ok' }]
518
+ })
519
+ }
520
+ try {
521
+ const check = await checkProfileRemoval()
522
+ if (check.kind !== 'ok') {
523
+ await explain(check)
524
+ return
525
+ }
526
+ const choice = await showAlert({
527
+ title: t('profile_remove_confirm_title', { profile: label }),
528
+ message: [
529
+ t('profile_remove_confirm_body', { profile: label }),
530
+ check.handle ? t('profile_remove_confirm_handle', { handle: check.handle }) : null
531
+ ]
532
+ .filter(Boolean)
533
+ .join('\n\n'),
534
+ buttons: [
535
+ { text: t('cancel'), style: 'cancel', key: 'cancel' },
536
+ { text: t('profile_remove_confirm_action'), style: 'destructive', key: 'remove' }
537
+ ]
538
+ })
539
+ if (choice !== 'remove') return
540
+ covered = true
541
+ const result = await removeProfile()
542
+ if (result.kind !== 'removed') {
543
+ await explain(result)
544
+ return
545
+ }
546
+ removed = true
547
+ showToast(t('profile_removed', { profile: label }), { type: 'success' })
548
+ // Profile 0 is open now and this screen was about this profile: leave it,
549
+ // the same way Delete Wallet does (dismissAll leaves one screen, so replace it).
550
+ router.dismissAll()
551
+ router.replace('/')
552
+ } catch (err) {
553
+ // The flow answers rather than throws, so this is a fault in the plumbing
554
+ // around it: still tell the user, and leave nothing unhandled in a press.
555
+ console.warn('[ProfileScreen] removing the profile failed', err)
556
+ await explain({ kind: 'failed', message: err instanceof Error ? err.message : String(err) })
557
+ } finally {
558
+ removingRef.current = false
559
+ setRemoving(false)
560
+ // An attempt may have released the handle or finished a journalled write
561
+ // without going through: have the screen ask the registry again.
562
+ if (!removed) setResumeNonce(n => n + 1)
563
+ }
564
+ }, [profiles, activeProfile, t, checkProfileRemoval, removeProfile, router])
565
+
405
566
  const handle = handleInput.trim().toLowerCase()
406
567
  const paymailPreview = registryDomain ? `${handle}@${registryDomain}` : handle
407
568
  const editingHandle = !!registryDomain && (!registeredPaymail || changingHandle)
@@ -487,6 +648,20 @@ export function ProfileScreen() {
487
648
  </PressableScale>
488
649
  </View>
489
650
 
651
+ {profilesSupported && (
652
+ <GroupedSection header={t('profile_name')} footer={t('profile_name_hint')}>
653
+ <PencilEditField
654
+ value={profiles[activeProfile]?.name ?? ''}
655
+ placeholder={profileLabel({ index: activeProfile }, t)}
656
+ onSave={onSaveProfileName}
657
+ editAccessibilityLabel={t('profile_name_edit')}
658
+ saveAccessibilityLabel={t('profile_name_save')}
659
+ maxLength={MAX_PROFILE_NAME_LENGTH}
660
+ allowEmpty
661
+ />
662
+ </GroupedSection>
663
+ )}
664
+
490
665
  <GroupedSection header={t('profile_display_name')} footer={t('profile_display_name_hint')}>
491
666
  <PencilEditField
492
667
  value={displayName}
@@ -645,6 +820,22 @@ export function ProfileScreen() {
645
820
  />
646
821
  {!!identityKey && <IdentifierRow identityKey={identityKey} />}
647
822
  </GroupedSection>
823
+
824
+ {profilesSupported && (activeProfile !== 0 || removing) && (
825
+ <GroupedSection>
826
+ <ListRow
827
+ label={t('profile_remove')}
828
+ subtitle={t('profile_remove_hint')}
829
+ icon="trash-outline"
830
+ iconColor={colors.error}
831
+ destructive
832
+ showChevron={false}
833
+ onPress={onRemoveProfile}
834
+ trailing={removing ? <ActivityIndicator size="small" color={colors.error} /> : undefined}
835
+ isLast
836
+ />
837
+ </GroupedSection>
838
+ )}
648
839
  </ScrollView>
649
840
 
650
841
  {/* Where a picture comes from. One source today; Take Photo and Photo
@@ -1,5 +1,5 @@
1
1
  import React, { useState, useEffect, useCallback } from 'react'
2
- import { View, Text, ScrollView, StyleSheet } from 'react-native'
2
+ import { View, Text, ScrollView, StyleSheet, AppState } from 'react-native'
3
3
  import { useTranslation } from 'react-i18next'
4
4
  import { useTheme, spacing, typography, useWallet, isVaultAvailable, useVault } from '@bsv/expo-wallet-toolbox'
5
5
  import { GroupedSection } from '../components/ui/GroupedList'
@@ -7,6 +7,10 @@ import { ListRow } from '../components/ui/ListRow'
7
7
  import AmountDisplay from '../components/wallet/AmountDisplay'
8
8
  import { sdk } from '@bsv/wallet-toolbox-mobile'
9
9
  import AsyncStorage from '@react-native-async-storage/async-storage'
10
+ import { pushAdvisory } from '../../core/push/pushAdvisory'
11
+ import type { PushPermission } from '../../core/push/types'
12
+ import { getPushAdapter } from '../../core/toolboxConfig'
13
+ import { profileScopedKey, useActiveProfileIndex } from '../../core/profiles/profileStore'
10
14
 
11
15
  /**
12
16
  * expo-router is required lazily rather than imported at module scope: this
@@ -31,20 +35,25 @@ const CACHE_DURATION = 30000
31
35
  export function SettingsScreen() {
32
36
  const { t } = useTranslation()
33
37
  const { colors } = useTheme()
34
- const { router } = loadExpoRouter()
38
+ // `useFocusEffect` is a hook, but calling it through the lazy loader is
39
+ // equivalent to a direct import (same as WalletHomeScreen/PayScreen).
40
+ const { router, useFocusEffect } = loadExpoRouter()
35
41
  const { managers, adminOriginator, selectedNetwork, txStatusVersion } = useWallet()
42
+ const activeProfile = useActiveProfileIndex()
36
43
 
37
44
  // Read during render, from the reactive network, so the row disappears on a
38
45
  // switch to testnet without a remount.
39
- const vaultAvailable = isVaultAvailable(selectedNetwork)
46
+ const vaultAvailable = isVaultAvailable(selectedNetwork, activeProfile)
40
47
  // F-07: an existing, already-funded vault stays reachable even when the
41
48
  // flag is off or the network switched — see showVaultRow below. VaultScreen
42
49
  // itself is never gated on that flag for withdraw.
43
50
  const { hasVaultMeta } = useVault()
44
- const showVaultRow = vaultAvailable || hasVaultMeta
51
+ // Only the default profile has a vault — on any other an empty vault would
52
+ // read as the user's vault being gone.
53
+ const showVaultRow = activeProfile === 0 && (vaultAvailable || hasVaultMeta)
45
54
 
46
- const balanceCacheKey = `cached_wallet_balance_${selectedNetwork}`
47
- const balanceCacheTimestampKey = `cached_wallet_balance_ts_${selectedNetwork}`
55
+ const balanceCacheKey = profileScopedKey(`cached_wallet_balance_${selectedNetwork}`, activeProfile)
56
+ const balanceCacheTimestampKey = profileScopedKey(`cached_wallet_balance_ts_${selectedNetwork}`, activeProfile)
48
57
  const [accountBalance, setAccountBalance] = useState<number | null>(null)
49
58
  const [balanceLoading, setBalanceLoading] = useState(false)
50
59
 
@@ -110,6 +119,57 @@ export function SettingsScreen() {
110
119
  refreshBalance()
111
120
  }, [txStatusVersion, refreshBalance])
112
121
 
122
+ // Payment notifications. The row exists only when the host wired a push
123
+ // adapter, and it is the one place besides the "Share remote link" advisory
124
+ // that can trigger the OS permission prompt.
125
+ const pushAdapter = getPushAdapter()
126
+ const [pushPermission, setPushPermission] = useState<PushPermission | null>(null)
127
+ const refreshPushPermission = useCallback(async () => {
128
+ if (!pushAdapter) return
129
+ try {
130
+ const next = await pushAdapter.getPermission()
131
+ // A re-read never walks 'denied' back to 'undetermined'. Android reports
132
+ // every not-granted state as 'undetermined', and the OS dialog's own
133
+ // dismissal brings the app back to 'active' right after a denial, so an
134
+ // unguarded read would erase the denial and leave the next press
135
+ // re-requesting (a silent no-op once the OS stops prompting) instead of
136
+ // opening the OS settings. A later 'granted' still replaces 'denied'.
137
+ setPushPermission(prev => (prev === 'denied' && next === 'undetermined' ? prev : next))
138
+ } catch {
139
+ // Leave the last known state; the row stays usable.
140
+ }
141
+ }, [pushAdapter])
142
+ useFocusEffect(
143
+ useCallback(() => {
144
+ void refreshPushPermission()
145
+ }, [refreshPushPermission])
146
+ )
147
+ // Coming back from the OS notification settings does not refocus this
148
+ // screen, so re-read when the app returns to the foreground.
149
+ useEffect(() => {
150
+ if (!pushAdapter) return
151
+ const subscription = AppState.addEventListener('change', state => {
152
+ if (state === 'active') void refreshPushPermission()
153
+ })
154
+ return () => subscription.remove()
155
+ }, [pushAdapter, refreshPushPermission])
156
+
157
+ const onPushPress = useCallback(async () => {
158
+ if (!pushAdapter) return
159
+ try {
160
+ if (pushPermission === 'undetermined') {
161
+ await pushAdvisory.set()
162
+ // Take the answer as given rather than re-reading it (see the guard
163
+ // in refreshPushPermission for why a denial must stick).
164
+ setPushPermission(await pushAdapter.requestPermission())
165
+ } else {
166
+ await pushAdapter.openSettings()
167
+ }
168
+ } catch {
169
+ // The adapter is host code; a failed call leaves the row as it was.
170
+ }
171
+ }, [pushAdapter, pushPermission])
172
+
113
173
  return (
114
174
  <View style={{ backgroundColor: colors.backgroundSecondary }}>
115
175
  <ScrollView contentContainerStyle={{ paddingBottom: spacing.xxxl }}>
@@ -158,6 +218,20 @@ export function SettingsScreen() {
158
218
  )}
159
219
  </GroupedSection>
160
220
 
221
+ {/* ── Notifications ── */}
222
+ {pushAdapter && (
223
+ <GroupedSection header={t('notifications')}>
224
+ <ListRow
225
+ label={t('push_settings_row')}
226
+ icon="notifications-outline"
227
+ iconColor={colors.accent}
228
+ value={pushPermission === 'granted' ? t('push_settings_on') : t('push_settings_off')}
229
+ onPress={onPushPress}
230
+ isLast
231
+ />
232
+ </GroupedSection>
233
+ )}
234
+
161
235
  {/* ── Settings drill-down ── */}
162
236
  <GroupedSection>
163
237
  <ListRow
@@ -34,6 +34,7 @@ import { EnrollWizard } from '../components/vault/EnrollWizard'
34
34
  import { KeyChooser, vaultKeyLabel, formatVaultSerial } from '../components/vault/KeyChooser'
35
35
  import { VaultBackdrop } from '../components/vault/VaultBackdrop'
36
36
  import { vaultErrorCopy } from '../components/vault/vaultErrorCopy'
37
+ import { profileLabel } from '../../core/profiles/profileLabel'
37
38
  import { useVaultBalance } from '../hooks/useVaultBalance'
38
39
  import { useVaultCoverage } from '../hooks/useVaultCoverage'
39
40
  import { useExportWalletData } from '../hooks/useExportWalletData'
@@ -150,7 +151,16 @@ export function VaultScreen() {
150
151
  const { balance, loading, refresh } = useVaultBalance()
151
152
  const { coverage, refresh: refreshCoverage } = useVaultCoverage()
152
153
  const { exportData, exporting } = useExportWalletData()
153
- const { managers, adminOriginator, selectedNetwork, storage, walletBuilding, buildWalletFromMnemonic } = useWallet()
154
+ const {
155
+ managers,
156
+ adminOriginator,
157
+ selectedNetwork,
158
+ storage,
159
+ walletBuilding,
160
+ buildWalletFromMnemonic,
161
+ activeProfile,
162
+ profiles
163
+ } = useWallet()
154
164
  const { createMnemonic, hasStoredIdentity, secretsReady } = useLocalStorage()
155
165
 
156
166
  /** undefined = loading; null = not enrolled. */
@@ -193,7 +203,7 @@ export function VaultScreen() {
193
203
  // so everything this gates collapses on a network switch without a remount —
194
204
  // in particular the two doors into EnrollWizard, whose factory-reset offer is
195
205
  // the fund-loss path a testnet vault reopens.
196
- const enabled = isVaultAvailable(selectedNetwork)
206
+ const enabled = isVaultAvailable(selectedNetwork, activeProfile)
197
207
  // Which refusal to print when it is off. A build with the flag off says so
198
208
  // first (spec §5.5); a released build that is simply on the wrong network owes
199
209
  // the user that reason instead — "not available yet" would describe an
@@ -1079,6 +1089,25 @@ export function VaultScreen() {
1079
1089
  </View>
1080
1090
  )
1081
1091
 
1092
+ // Only the default profile has a vault. Reachable here only through a deep
1093
+ // link or a back stack that outlived a profile switch: no door, not even
1094
+ // withdraw or chain restore, opens on another profile's identity.
1095
+ if (activeProfile !== 0) {
1096
+ return (
1097
+ <View style={[styles.container, { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }]}>
1098
+ {Header}
1099
+ <View style={styles.centered}>
1100
+ <Ionicons name="lock-closed-outline" size={44} color={colors.textSecondary} />
1101
+ <Text style={[styles.p, { color: colors.textPrimary }]}>
1102
+ {t('vault_profile_only_default', {
1103
+ profile: profileLabel(profiles.find(p => p.index === 0) ?? { index: 0 }, t)
1104
+ })}
1105
+ </Text>
1106
+ </View>
1107
+ </View>
1108
+ )
1109
+ }
1110
+
1082
1111
  if (recoveryError) {
1083
1112
  return (
1084
1113
  <View style={[styles.container, { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }]}>
@@ -33,6 +33,7 @@ import { showAlert } from '../components/ui/AlertCard'
33
33
  import { KeyChooser, vaultKeyLabel } from '../components/vault/KeyChooser'
34
34
  import { vaultErrorCopy, type VaultErrorParams } from '../components/vault/vaultErrorCopy'
35
35
  import { expectVaultBalance, useVaultBalance } from '../hooks/useVaultBalance'
36
+ import { profileLabel } from '../../core/profiles/profileLabel'
36
37
  import {
37
38
  useTheme,
38
39
  spacing,
@@ -129,7 +130,7 @@ export function VaultTransferScreen() {
129
130
  const { router, useLocalSearchParams } = loadExpoRouter()
130
131
  const Ionicons = loadIonicons()
131
132
  const { direction } = useLocalSearchParams<{ direction?: string }>()
132
- const { managers, adminOriginator, selectedNetwork, storage, settings } = useWallet()
133
+ const { managers, adminOriginator, selectedNetwork, storage, settings, activeProfile, profiles } = useWallet()
133
134
  const { satoshisPerUSD, usdToFiat = {} } = useContext(ExchangeRateContext)
134
135
  const { balance, refresh } = useVaultBalance()
135
136
  const [meta, setMeta] = useState<VaultMeta | null>(null)
@@ -147,7 +148,7 @@ export function VaultTransferScreen() {
147
148
  // Release flag AND mainnet (task 11): deposits create a vault output, and one
148
149
  // must never land off mainnet. Withdrawal of pre-existing outputs is never
149
150
  // gated — that is how a testnet tester gets their coins back out.
150
- const released = isVaultAvailable(selectedNetwork)
151
+ const released = isVaultAvailable(selectedNetwork, activeProfile)
151
152
  // See VaultScreen: "not available yet" describes an unreleased build, not a
152
153
  // released build on the wrong network.
153
154
  const unavailableCopy = isVaultEnabled() ? 'vault_not_on_mainnet_body' : 'vault_not_released_body'
@@ -474,6 +475,28 @@ export function VaultTransferScreen() {
474
475
  router
475
476
  ])
476
477
 
478
+ // Only the default profile has a vault — see VaultScreen.
479
+ if (activeProfile !== 0) {
480
+ return (
481
+ <View style={[styles.container, { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }]}>
482
+ <View style={[styles.header, { borderBottomColor: colors.separator }]}>
483
+ <TouchableOpacity onPress={() => router.back()} style={styles.iconBtn}>
484
+ <Ionicons name="chevron-back" size={24} color={colors.textSecondary} />
485
+ </TouchableOpacity>
486
+ <Text style={[styles.headerTitle, { color: colors.textPrimary }]}>{t('vault_title')}</Text>
487
+ <View style={styles.iconBtn} />
488
+ </View>
489
+ <View style={styles.body}>
490
+ <Text style={{ ...typography.body, color: colors.textSecondary, textAlign: 'center' }}>
491
+ {t('vault_profile_only_default', {
492
+ profile: profileLabel(profiles.find(p => p.index === 0) ?? { index: 0 }, t)
493
+ })}
494
+ </Text>
495
+ </View>
496
+ </View>
497
+ )
498
+ }
499
+
477
500
  return (
478
501
  <View style={[styles.container, { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }]}>
479
502
  <View style={[styles.header, { borderBottomColor: colors.separator }]}>
@@ -46,6 +46,7 @@ import { userFacingPayError } from '../../core/pay/userError'
46
46
  import { backupAttestation } from '../../core/services/vault/backupAttestation'
47
47
  import { getBackupUploadState } from '../../core/backup/status'
48
48
  import { getOnline, haptics, spacing, typography, useTheme, useWallet } from '@bsv/expo-wallet-toolbox'
49
+ import { profileScopedKey } from '../../core/profiles/profileStore'
49
50
 
50
51
  /**
51
52
  * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
@@ -188,7 +189,7 @@ function useWalletCheckPorts(): WalletCheckPorts {
188
189
  },
189
190
  creditInbox: async () => {
190
191
  if (!wallet) return { accepted: 0 }
191
- const saved = await AsyncStorage.getItem(MESSAGE_BOX_URL_KEY)
192
+ const saved = await AsyncStorage.getItem(profileScopedKey(MESSAGE_BOX_URL_KEY))
192
193
  const messageBoxUrl = !saved || saved === LEGACY_MESSAGE_BOX_URL ? DEFAULT_MESSAGE_BOX_URL : saved
193
194
  if (!messageBoxUrl || messageBoxUrl === NO_MESSAGE_BOX) return { accepted: 0 }
194
195
  const client = new PeerPayClient({