@bsv/expo-wallet-toolbox 0.12.0 → 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 (53) hide show
  1. package/CHANGELOG.md +71 -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/context/WalletContext.tsx +841 -236
  7. package/core/i18n/translations.tsx +376 -0
  8. package/core/identity/handleRegistry/registration.ts +57 -3
  9. package/core/index.ts +24 -1
  10. package/core/mandala/createRuntime.ts +3 -3
  11. package/core/mandala/runtime.ts +7 -2
  12. package/core/mnemonicWallet.ts +46 -40
  13. package/core/monitor/MonitorSupervisor.ts +35 -1
  14. package/core/monitor/TaskCreditInbox.ts +24 -0
  15. package/core/pay/rails/handle.ts +4 -2
  16. package/core/peerpay/outbox.ts +11 -1
  17. package/core/profiles/assertProfileEmpty.ts +287 -0
  18. package/core/profiles/discovery.ts +84 -0
  19. package/core/profiles/profileLabel.ts +13 -0
  20. package/core/profiles/profileStore.ts +265 -0
  21. package/core/profiles/purgeProfile.ts +76 -0
  22. package/core/profiles/removeProfile.ts +257 -0
  23. package/core/push/events.ts +52 -5
  24. package/core/push/identities.ts +55 -0
  25. package/core/push/profilePush.ts +143 -0
  26. package/core/push/registration.ts +362 -24
  27. package/core/push/types.ts +5 -1
  28. package/core/services/arcTokenStorage.ts +17 -2
  29. package/core/services/vault/transfers.ts +6 -1
  30. package/core/services/vault/vaultStore.ts +16 -3
  31. package/core/stores/ConnectionStore.ts +11 -7
  32. package/core/toolboxConfig.ts +7 -3
  33. package/core/userAvatar.ts +12 -5
  34. package/core/walletDbRegistry.ts +73 -0
  35. package/package.json +1 -1
  36. package/ui/backupShares.ts +2 -3
  37. package/ui/components/pay/MessageBoxConfig.tsx +6 -5
  38. package/ui/components/ui/PencilEditField.tsx +5 -2
  39. package/ui/components/wallet/Balance.tsx +3 -1
  40. package/ui/components/wallet/ProfileButton.tsx +92 -18
  41. package/ui/components/wallet/ProfileSwitcherPopover.tsx +247 -0
  42. package/ui/hooks/useOfflineNoticeActions.ts +2 -1
  43. package/ui/hooks/useSpendableBalance.ts +3 -1
  44. package/ui/printRecoveryShares.ts +6 -7
  45. package/ui/screens/PairScreen.tsx +2 -1
  46. package/ui/screens/ProfileScreen.tsx +195 -4
  47. package/ui/screens/SettingsScreen.tsx +8 -4
  48. package/ui/screens/VaultScreen.tsx +31 -2
  49. package/ui/screens/VaultTransferScreen.tsx +25 -2
  50. package/ui/screens/WalletCheckScreen.tsx +2 -1
  51. package/ui/screens/WalletConfigScreen.tsx +51 -21
  52. package/ui/screens/WalletHomeScreen.tsx +6 -3
  53. package/ui/tokenSeen.ts +13 -9
@@ -2085,9 +2085,14 @@ async function newVaultOutput(
2085
2085
  function requireReleased(opts: VaultTransferOptions | undefined, scopeToken: VaultScopeToken, what: string): void {
2086
2086
  const enabled = opts?.vaultEnabled ?? isVaultEnabled
2087
2087
  if (!enabled()) throw new VaultError('not-released', `${what} is switched off in this build`)
2088
- if (!isVaultAvailable(scopeToken.chain)) {
2088
+ if (!isVaultAvailable(scopeToken.chain, 0)) {
2089
2089
  throw new VaultError('not-on-mainnet', `${what} is only available on mainnet`)
2090
2090
  }
2091
+ // Captured with the scope, like the chain: a profile switch mid-flight clears
2092
+ // the scope and aborts at assertVaultScope rather than carrying on here.
2093
+ if ((scopeToken.profileIndex ?? 0) !== 0) {
2094
+ throw new VaultError('not-released', `${what} is only available on the default profile`)
2095
+ }
2091
2096
  }
2092
2097
 
2093
2098
  /** A real private-backup configuration needs both a host endpoint and the
@@ -45,6 +45,9 @@ export interface VaultStoreScope {
45
45
  /** Compressed secp256k1 wallet identity key, lowercase hex. */
46
46
  identityKey: string
47
47
  chain: VaultScopeChain
48
+ /** The wallet profile this identity belongs to (default 0). The vault is only
49
+ * ever available on profile 0; transfers check the captured value. */
50
+ profileIndex?: number
48
51
  }
49
52
 
50
53
  /** Opaque capability binding an async operation to one configured scope. */
@@ -52,6 +55,7 @@ export interface VaultScopeToken {
52
55
  readonly generation: number
53
56
  readonly storageKey: string
54
57
  readonly chain: VaultScopeChain
58
+ readonly profileIndex?: number
55
59
  }
56
60
 
57
61
  export interface VaultKeyRecord {
@@ -173,7 +177,11 @@ function normalizeScope(scope: VaultStoreScope): VaultStoreScope {
173
177
  if (scope.chain !== 'main' && scope.chain !== 'test' && scope.chain !== 'teratest') {
174
178
  throw new VaultError('template-invalid', 'Vault scope requires a supported chain')
175
179
  }
176
- return { identityKey: scope.identityKey, chain: scope.chain }
180
+ const profileIndex = scope.profileIndex ?? 0
181
+ if (!Number.isInteger(profileIndex) || profileIndex < 0) {
182
+ throw new VaultError('template-invalid', 'Vault scope requires a valid profile index')
183
+ }
184
+ return { identityKey: scope.identityKey, chain: scope.chain, profileIndex }
177
185
  }
178
186
 
179
187
  function scopedKey(scope = activeScope): string | null {
@@ -297,11 +305,16 @@ function captureScope(required: boolean): VaultScopeToken | null {
297
305
  if (required) throw new VaultError('not-enrolled', 'Wallet vault scope is not configured')
298
306
  return null
299
307
  }
300
- return { generation: scopeGeneration, storageKey, chain: activeScope!.chain }
308
+ return { generation: scopeGeneration, storageKey, chain: activeScope!.chain, profileIndex: activeScope!.profileIndex ?? 0 }
301
309
  }
302
310
 
303
311
  function assertScope(token: VaultScopeToken): void {
304
- if (token.generation !== scopeGeneration || token.storageKey !== scopedKey() || token.chain !== activeScope?.chain) {
312
+ if (
313
+ token.generation !== scopeGeneration ||
314
+ token.storageKey !== scopedKey() ||
315
+ token.chain !== activeScope?.chain ||
316
+ (token.profileIndex ?? 0) !== (activeScope?.profileIndex ?? 0)
317
+ ) {
305
318
  throw new VaultError('scope-changed', 'Wallet or network changed during the vault operation')
306
319
  }
307
320
  }
@@ -1,5 +1,6 @@
1
1
  import { makeAutoObservable, runInAction } from 'mobx'
2
2
  import AsyncStorage from '@react-native-async-storage/async-storage'
3
+ import { profileScopedKey } from '../profiles/profileStore'
3
4
 
4
5
  export interface Connection {
5
6
  sessionId: string
@@ -81,20 +82,23 @@ class ConnectionStore {
81
82
 
82
83
  private async save() {
83
84
  try {
84
- await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(this.connections))
85
+ await AsyncStorage.setItem(profileScopedKey(STORAGE_KEY), JSON.stringify(this.connections))
85
86
  } catch (e) {
86
87
  console.warn('[ConnectionStore] save failed', e)
87
88
  }
88
89
  }
89
90
 
91
+ /** Pairings belong to one wallet profile: re-read after every profile switch. */
92
+ async reload() {
93
+ await this.load()
94
+ }
95
+
90
96
  private async load() {
91
97
  try {
92
- const raw = await AsyncStorage.getItem(STORAGE_KEY)
93
- if (raw) {
94
- runInAction(() => {
95
- this.connections = JSON.parse(raw) as Connection[]
96
- })
97
- }
98
+ const raw = await AsyncStorage.getItem(profileScopedKey(STORAGE_KEY))
99
+ runInAction(() => {
100
+ this.connections = raw ? (JSON.parse(raw) as Connection[]) : []
101
+ })
98
102
  } catch (e) {
99
103
  console.warn('[ConnectionStore] load failed', e)
100
104
  }
@@ -352,13 +352,17 @@ export function getPushAdapter(): PushAdapter | undefined {
352
352
  * across all of them, so a testnet wizard could offer to factory-reset a live
353
353
  * mainnet signer.
354
354
  *
355
- * Chain is a parameter, not a module read: screens must re-render when the user
355
+ * Only the default wallet profile (index 0) has a vault: a YubiKey is enrolled
356
+ * against one identity, and showing an empty vault on another profile would read
357
+ * as the user's vault being gone.
358
+ *
359
+ * Chain and profile are parameters, not module reads: screens must re-render when the user
356
360
  * switches network, and `selectedNetwork` from the wallet context is what makes
357
361
  * that reactive. Keeping it a parameter also keeps this module a leaf — it must
358
362
  * never import `vaultStore`.
359
363
  */
360
- export function isVaultAvailable(chain: AppChain): boolean {
361
- return isVaultEnabled() && chain === 'main'
364
+ export function isVaultAvailable(chain: AppChain, profileIndex: number): boolean {
365
+ return isVaultEnabled() && chain === 'main' && profileIndex === 0
362
366
  }
363
367
 
364
368
  /** Test-only: drop the installed configuration. */
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { useSyncExternalStore } from 'react'
16
16
  import AsyncStorage from '@react-native-async-storage/async-storage'
17
+ import { profileScopedKey } from './profiles/profileStore'
17
18
 
18
19
  export type AvatarIconFamily = 'ionicons' | 'material-community'
19
20
 
@@ -38,8 +39,10 @@ export function setUserAvatarIcon(next: AvatarIcon | null): void {
38
39
  listeners.forEach(l => l())
39
40
  // Fire-and-forget: the choice is already live in memory, and a failed write
40
41
  // costs the next launch's avatar, never the one on screen now.
41
- if (next) void AsyncStorage.setItem(STORAGE_KEY, `${next.family}/${next.name}`).catch(() => {})
42
- else void AsyncStorage.removeItem(STORAGE_KEY).catch(() => {})
42
+ // Per wallet profile: the avatar is how the user tells profiles apart.
43
+ const key = profileScopedKey(STORAGE_KEY)
44
+ if (next) void AsyncStorage.setItem(key, `${next.family}/${next.name}`).catch(() => {})
45
+ else void AsyncStorage.removeItem(key).catch(() => {})
43
46
  }
44
47
 
45
48
  export function subscribeUserAvatar(listener: () => void): () => void {
@@ -60,11 +63,15 @@ function parse(stored: string | null): AvatarIcon | null {
60
63
  return { family, name }
61
64
  }
62
65
 
63
- /** Restore the stored choice. Call once at startup; safe to call twice. */
66
+ /**
67
+ * Restore the active profile's stored choice. Call at startup and after every
68
+ * profile switch; safe to call twice. A profile with no choice gets the default
69
+ * disc, never the previous profile's icon.
70
+ */
64
71
  export async function loadUserAvatarIcon(): Promise<void> {
65
72
  try {
66
- const next = parse(await AsyncStorage.getItem(STORAGE_KEY))
67
- if (next && (next.family !== icon?.family || next.name !== icon?.name)) {
73
+ const next = parse(await AsyncStorage.getItem(profileScopedKey(STORAGE_KEY)))
74
+ if (next?.family !== icon?.family || next?.name !== icon?.name) {
68
75
  icon = next
69
76
  listeners.forEach(l => l())
70
77
  }
@@ -113,6 +113,19 @@ export async function getRegisteredDbs(keySuffix: string, chain: string): Promis
113
113
  }
114
114
  }
115
115
 
116
+ /** The networks a wallet database can belong to. */
117
+ const WALLET_DB_CHAINS = ['main', 'test', 'teratest'] as const
118
+
119
+ /**
120
+ * Every registered wallet DB filename for an identity, on every network. Unlike
121
+ * the purge below, a registry that cannot be read rejects: this answers "what
122
+ * exists", and a guess of "nothing" would be wrong in the dangerous direction.
123
+ */
124
+ export async function getAllRegisteredDbs(keySuffix: string): Promise<string[]> {
125
+ const perChain = await Promise.all(WALLET_DB_CHAINS.map(chain => getRegisteredDbs(keySuffix, chain)))
126
+ return [...new Set(perChain.flat())]
127
+ }
128
+
116
129
  /**
117
130
  * Append a filename to the registry (no-op if already present).
118
131
  */
@@ -185,3 +198,63 @@ export async function purgeRegisteredDbFiles(
185
198
  }
186
199
  }
187
200
  }
201
+
202
+ /**
203
+ * What a failed delete means: the file is already gone (expo-sqlite throws
204
+ * "Database ... not found" for it, on Android and iOS alike) or it is still there.
205
+ */
206
+ function alreadyGone(error: unknown): boolean {
207
+ return /not found/i.test(error instanceof Error ? error.message : String(error))
208
+ }
209
+
210
+ /**
211
+ * Delete Wallet with profiles: every wallet profile has its own identity and so
212
+ * its own registry, one per network. Purges every file this identity's registry
213
+ * knows on every network — the other profiles are not open at logout, so there
214
+ * is no current `dbName` to anchor on as `purgeRegisteredDbFiles` does.
215
+ * Best-effort per file, for the same reasons as that function.
216
+ *
217
+ * Resolves true when every file is gone. By default a file that could not be
218
+ * deleted is unregistered anyway: after Delete Wallet the registry must not point
219
+ * a rebuilt wallet back at it (XQ-008).
220
+ *
221
+ * `keepFailed` is for removing one profile, which has a retry at every startup
222
+ * (core/profiles/purgeProfile) and that retry finds the files only through this
223
+ * registry: an entry dropped with its file still on disk would leave the removed
224
+ * profile's plaintext history there for good. So an entry stays when its file
225
+ * could not be deleted, and goes when the file is gone, whether this call or an
226
+ * earlier one deleted it.
227
+ */
228
+ export async function purgeIdentityDbFiles(
229
+ keySuffix: string,
230
+ deleteFile: (filename: string) => Promise<void>,
231
+ options: { keepFailed?: boolean } = {}
232
+ ): Promise<boolean> {
233
+ let clean = true
234
+ for (const chain of WALLET_DB_CHAINS) {
235
+ let filenames: string[] = []
236
+ try {
237
+ filenames = await getRegisteredDbs(keySuffix, chain)
238
+ } catch {
239
+ clean = false
240
+ continue
241
+ }
242
+ for (const filename of filenames) {
243
+ let deleted = true
244
+ try {
245
+ await deleteFile(filename)
246
+ } catch (error) {
247
+ // Best-effort — see purgeRegisteredDbFiles.
248
+ deleted = alreadyGone(error)
249
+ if (!deleted) clean = false
250
+ }
251
+ if (options.keepFailed && !deleted) continue
252
+ try {
253
+ await unregisterDb(keySuffix, chain, filename)
254
+ } catch {
255
+ // Best-effort — see purgeRegisteredDbFiles.
256
+ }
257
+ }
258
+ }
259
+ return clean
260
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bsv/expo-wallet-toolbox",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "private": false,
5
5
  "description": "Wallet screens and P2P local-payment backend for Expo/React Native apps, extracted from BSV Wallet.",
6
6
  "license": "SEE LICENSE IN LICENSE.txt",
@@ -40,9 +40,8 @@ async function generateQRCodeSVG(data: string, size: number = 180): Promise<stri
40
40
  *
41
41
  * `only`, when given, renders a single page (share index `only` of `shares`,
42
42
  * still labelled "Share <only+1> of <shares.length>") as a standalone
43
- * one-page document instead of every share in one multi-page document. See
44
- * printRecoveryShares.ts (XR-110): the default flow calls this once per
45
- * share so no single print job carries more than one of the threshold.
43
+ * one-page document instead of every share in one multi-page document.
44
+ * printRecoveryShares.ts no longer uses it (XR-110 reverted, see there).
46
45
  */
47
46
  export async function generatePrintHTML(
48
47
  shares: string[],
@@ -21,6 +21,7 @@ import {
21
21
  MESSAGE_BOX_URL_KEY,
22
22
  NO_MESSAGE_BOX
23
23
  } from '@bsv/expo-wallet-toolbox'
24
+ import { profileScopedKey } from '../../../core/profiles/profileStore'
24
25
 
25
26
  /**
26
27
  * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
@@ -46,11 +47,11 @@ export function useMessageBoxConfig(t: ReturnType<typeof import('react-i18next')
46
47
  const [showConfig, setShowConfig] = useState(false)
47
48
 
48
49
  useEffect(() => {
49
- AsyncStorage.getItem(MESSAGE_BOX_URL_KEY).then(saved => {
50
+ AsyncStorage.getItem(profileScopedKey(MESSAGE_BOX_URL_KEY)).then(saved => {
50
51
  // A preference equal to the retired default means "default", not a
51
52
  // deliberate choice of that server — follow the new default instead.
52
53
  if (saved === LEGACY_MESSAGE_BOX_URL) {
53
- void AsyncStorage.removeItem(MESSAGE_BOX_URL_KEY)
54
+ void AsyncStorage.removeItem(profileScopedKey(MESSAGE_BOX_URL_KEY))
54
55
  return
55
56
  }
56
57
  if (saved) {
@@ -85,7 +86,7 @@ export function useMessageBoxConfig(t: ReturnType<typeof import('react-i18next')
85
86
  }
86
87
  setIsSaving(true)
87
88
  try {
88
- await AsyncStorage.setItem(MESSAGE_BOX_URL_KEY, trimmed)
89
+ await AsyncStorage.setItem(profileScopedKey(MESSAGE_BOX_URL_KEY), trimmed)
89
90
  setMessageBoxUrl(trimmed)
90
91
  setShowConfig(false)
91
92
  showToast(t('message_box_saved'), { type: 'success' })
@@ -99,7 +100,7 @@ export function useMessageBoxConfig(t: ReturnType<typeof import('react-i18next')
99
100
  )
100
101
 
101
102
  const handleReset = useCallback(async () => {
102
- await AsyncStorage.removeItem(MESSAGE_BOX_URL_KEY)
103
+ await AsyncStorage.removeItem(profileScopedKey(MESSAGE_BOX_URL_KEY))
103
104
  setMessageBoxUrl(DEFAULT_MESSAGE_BOX_URL)
104
105
  setUrlInput(DEFAULT_MESSAGE_BOX_URL)
105
106
  setShowConfig(false)
@@ -110,7 +111,7 @@ export function useMessageBoxConfig(t: ReturnType<typeof import('react-i18next')
110
111
  const noneValue = NO_MESSAGE_BOX
111
112
  setIsSaving(true)
112
113
  try {
113
- await AsyncStorage.setItem(MESSAGE_BOX_URL_KEY, noneValue)
114
+ await AsyncStorage.setItem(profileScopedKey(MESSAGE_BOX_URL_KEY), noneValue)
114
115
  setMessageBoxUrl(noneValue)
115
116
  setUrlInput(noneValue)
116
117
  setShowConfig(true)
@@ -30,6 +30,8 @@ export interface PencilEditFieldProps {
30
30
  saveAccessibilityLabel: string
31
31
  autoCapitalize?: 'none' | 'sentences' | 'words' | 'characters'
32
32
  maxLength?: number
33
+ /** Let the text be emptied and saved as '' (a name that can go back to its default). */
34
+ allowEmpty?: boolean
33
35
  }
34
36
 
35
37
  export function PencilEditField({
@@ -40,7 +42,8 @@ export function PencilEditField({
40
42
  editAccessibilityLabel,
41
43
  saveAccessibilityLabel,
42
44
  autoCapitalize = 'words',
43
- maxLength
45
+ maxLength,
46
+ allowEmpty = false
44
47
  }: PencilEditFieldProps) {
45
48
  const { colors } = useTheme()
46
49
  const Ionicons = loadIonicons()
@@ -50,7 +53,7 @@ export function PencilEditField({
50
53
  // re-seeds the field; an in-progress edit is never clobbered, because the
51
54
  // parent's value only changes once our own save has gone through.
52
55
  useEffect(() => setText(value), [value])
53
- const changed = text.trim() !== '' && text.trim() !== value.trim()
56
+ const changed = (allowEmpty || text.trim() !== '') && text.trim() !== value.trim()
54
57
 
55
58
  const save = async () => {
56
59
  if (!changed) return
@@ -5,6 +5,7 @@ import AmountDisplay from './AmountDisplay'
5
5
  import AppLogo from '../ui/AppLogo'
6
6
  import { sdk } from '@bsv/wallet-toolbox-mobile'
7
7
  import AsyncStorage from '@react-native-async-storage/async-storage'
8
+ import { profileScopedKey, useActiveProfileIndex } from '../../../core/profiles/profileStore'
8
9
 
9
10
  // XR-058: scoped by network (matching useSpendableBalance's pattern) rather
10
11
  // than a single global key, so one wallet/network context can never read
@@ -16,7 +17,8 @@ const CACHE_DURATION = 30000 // 30 seconds
16
17
  export default function Balance() {
17
18
  const { colors } = useTheme()
18
19
  const { managers, adminOriginator, txStatusVersion, selectedNetwork } = useWallet()
19
- const cacheKey = `${BALANCE_CACHE_PREFIX}${selectedNetwork}`
20
+ const activeProfile = useActiveProfileIndex()
21
+ const cacheKey = profileScopedKey(`${BALANCE_CACHE_PREFIX}${selectedNetwork}`, activeProfile)
20
22
  const timestampKey = `${cacheKey}_timestamp`
21
23
  // { key, value } rather than a bare number: `key` is compared against the
22
24
  // live `cacheKey` everywhere below, so a figure read for a since-departed
@@ -8,13 +8,18 @@
8
8
  * host app's `app/index.tsx`, so this needed no package API change. Same disc
9
9
  * as the settings button on the right (surfaceRaised + hairline), so the two
10
10
  * bookend the header as a matched pair.
11
+ *
12
+ * With wallet profiles (a mnemonic wallet), pressing opens the profile
13
+ * switcher; the active profile's row is the way into Profile. A recovered-key
14
+ * wallet has no profiles, so it keeps going straight to Profile.
11
15
  */
12
- import React from 'react'
13
- import { StyleSheet } from 'react-native'
14
- import { useTheme, useUserAvatarIcon } from '@bsv/expo-wallet-toolbox'
16
+ import React, { useRef, useState } from 'react'
17
+ import { StyleSheet, View } from 'react-native'
18
+ import { useTheme, useUserAvatarIcon, useWallet } from '@bsv/expo-wallet-toolbox'
15
19
  import { useTranslation } from 'react-i18next'
16
20
  import PressableScale from '../ui/PressableScale'
17
21
  import { AvatarGlyph } from './UserAvatar'
22
+ import ProfileSwitcherPopover from './ProfileSwitcherPopover'
18
23
 
19
24
  type ExpoRouterModule = typeof import('expo-router')
20
25
  let expoRouterMod: ExpoRouterModule | undefined
@@ -31,22 +36,91 @@ export default function ProfileButton() {
31
36
  const { t } = useTranslation()
32
37
  const { router } = loadExpoRouter()
33
38
  const avatar = useUserAvatarIcon()
39
+ const {
40
+ profilesSupported,
41
+ profiles,
42
+ activeProfile,
43
+ switchProfile,
44
+ addProfile,
45
+ walletBuilding,
46
+ switchingProfile,
47
+ removingProfile
48
+ } = useWallet()
49
+ const discRef = useRef<View>(null)
50
+ const [open, setOpen] = useState(false)
51
+ /** Which profile the running switch is headed to, for the cover's label. */
52
+ const [target, setTarget] = useState<number | null>(null)
53
+ // Until the first layout measure lands: roughly where Home's top bar puts the disc.
54
+ const [anchor, setAnchor] = useState({ x: 16, y: 54, height: 34 })
55
+
56
+ const openProfile = () => router.push('/profile' as never)
57
+
58
+ // Where the card hangs from, kept current from layout so a press opens at once.
59
+ const measure = () => {
60
+ discRef.current?.measureInWindow?.((x, y, _w, height) => {
61
+ if (Number.isFinite(x) && Number.isFinite(y)) setAnchor({ x, y, height: height || 34 })
62
+ })
63
+ }
64
+
65
+ const onPress = () => {
66
+ if (!profilesSupported) {
67
+ openProfile()
68
+ return
69
+ }
70
+ measure()
71
+ setOpen(true)
72
+ }
73
+
74
+ const run = (to: number, action: () => Promise<void>) => {
75
+ setTarget(to)
76
+ setOpen(false)
77
+ action()
78
+ .catch(err => console.warn('[ProfileButton] profile action failed:', err))
79
+ .finally(() => setTarget(null))
80
+ }
81
+
34
82
  return (
35
- <PressableScale
36
- onPress={() => router.push('/profile' as never)}
37
- haptic="tap"
38
- hitSlop={5}
39
- style={[styles.disc, { backgroundColor: colors.surfaceRaised, borderColor: colors.surfaceRaisedBorder }]}
40
- accessibilityRole="button"
41
- accessibilityLabel={t('profile')}
42
- >
43
- <AvatarGlyph
44
- family={avatar?.family ?? 'ionicons'}
45
- name={avatar?.name ?? 'person-outline'}
46
- size={17}
47
- color={colors.textSecondary}
48
- />
49
- </PressableScale>
83
+ <>
84
+ <View ref={discRef} collapsable={false} onLayout={measure}>
85
+ <PressableScale
86
+ onPress={onPress}
87
+ haptic="tap"
88
+ hitSlop={5}
89
+ style={[styles.disc, { backgroundColor: colors.surfaceRaised, borderColor: colors.surfaceRaisedBorder }]}
90
+ accessibilityRole="button"
91
+ accessibilityLabel={profilesSupported ? t('profile_switcher_a11y') : t('profile')}
92
+ >
93
+ <AvatarGlyph
94
+ family={avatar?.family ?? 'ionicons'}
95
+ name={avatar?.name ?? 'person-outline'}
96
+ size={17}
97
+ color={colors.textSecondary}
98
+ />
99
+ </PressableScale>
100
+ </View>
101
+ {profilesSupported && (
102
+ <ProfileSwitcherPopover
103
+ visible={open || switchingProfile}
104
+ onClose={() => setOpen(false)}
105
+ anchor={anchor}
106
+ profiles={profiles}
107
+ active={activeProfile}
108
+ avatar={avatar}
109
+ busy={walletBuilding || switchingProfile}
110
+ // A removal is started from the Profile screen, not from here, so `target` is
111
+ // empty for it: the cover names the profile being removed instead.
112
+ switchingTo={switchingProfile ? (target ?? removingProfile ?? activeProfile) : null}
113
+ removing={typeof removingProfile === 'number'}
114
+ onSelect={n => run(n, () => switchProfile(n))}
115
+ onOpenProfile={() => {
116
+ setOpen(false)
117
+ openProfile()
118
+ }}
119
+ // The full list, removed profiles included: that count is the index the new profile gets.
120
+ onAdd={() => run(profiles.length, addProfile)}
121
+ />
122
+ )}
123
+ </>
50
124
  )
51
125
  }
52
126