@bsv/expo-wallet-toolbox 0.5.0 → 0.7.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 (90) hide show
  1. package/CHANGELOG.md +255 -0
  2. package/README.md +19 -0
  3. package/core/amountFormatHelpers.ts +238 -34
  4. package/core/backup/RemoteSyncReader.ts +2 -5
  5. package/core/backup/codec.ts +2 -2
  6. package/core/backup/push.ts +1 -1
  7. package/core/config.tsx +12 -5
  8. package/core/contacts/contactActivity.ts +153 -0
  9. package/core/contacts/contactCache.ts +41 -0
  10. package/core/contacts/contactsStore.ts +183 -0
  11. package/core/context/WalletContext.tsx +55 -10
  12. package/core/demo/demoAssets.ts +60 -0
  13. package/core/demo/demoLedger.ts +240 -0
  14. package/core/demo/demoMandalaRuntime.ts +96 -0
  15. package/core/demo/demoMode.ts +38 -0
  16. package/core/demo/demoWallet.ts +25 -0
  17. package/core/demo/index.ts +26 -0
  18. package/core/demo/useDemo.ts +59 -0
  19. package/core/headers/OfflineFirstChaintracks.ts +52 -14
  20. package/core/headers/headerStore.ts +7 -10
  21. package/core/i18n/translations.tsx +1234 -74
  22. package/core/identity/contactLink.ts +36 -0
  23. package/core/identity/handleRegistry/client.ts +285 -0
  24. package/core/identity/handleRegistry/profileCert.ts +254 -0
  25. package/core/identity/handleRegistry/registration.ts +559 -0
  26. package/core/identity/handleRegistry/resolver.ts +247 -0
  27. package/core/identity/handleRegistry/rules.ts +104 -0
  28. package/core/index.ts +20 -2
  29. package/core/localpay/pendingAborts.ts +5 -1
  30. package/core/monitor/MonitorSupervisor.ts +121 -0
  31. package/core/monitor/TaskBackupPush.ts +1 -1
  32. package/core/monitor/TaskCreditInbox.ts +1 -1
  33. package/core/monitor/TaskDrainOutbox.ts +1 -1
  34. package/core/monitor/TaskSendOffline.ts +1 -1
  35. package/core/net/online.ts +49 -0
  36. package/core/numberFormat.ts +19 -0
  37. package/core/offline/plan.ts +1 -1
  38. package/core/pay/recordProof.ts +2 -6
  39. package/core/services/arcadeBroadcastProvider.ts +1 -4
  40. package/core/services/exchangeRate.ts +1 -1
  41. package/core/services/externalOrigin.ts +5 -2
  42. package/core/services/vault/transfers.ts +2 -2
  43. package/core/services/walletServiceConfig.ts +31 -20
  44. package/core/storage/StorageExpoSQLite.ts +41 -34
  45. package/core/storage/methods/findSql.ts +3 -0
  46. package/core/storage/methods/listActionsSql.ts +8 -5
  47. package/core/storage/methods/listOutputsSql.ts +2 -2
  48. package/core/storage/methods/processOfflineActions.ts +2 -3
  49. package/core/storage/methods/reviewStatusSql.ts +7 -2
  50. package/core/storage/schema/createTables.ts +29 -0
  51. package/core/toolboxConfig.ts +70 -0
  52. package/core/toolboxTypes.ts +40 -0
  53. package/core/userAvatar.ts +79 -0
  54. package/core/walletMonitor.ts +8 -3
  55. package/package.json +7 -7
  56. package/ui/activityFilter.ts +115 -0
  57. package/ui/components/pay/PaymentSuccessOverlay.tsx +46 -6
  58. package/ui/components/pay/RecipientField.tsx +84 -70
  59. package/ui/components/pay/StepBar.tsx +32 -0
  60. package/ui/components/pay/UniversalSend.tsx +677 -149
  61. package/ui/components/ui/PencilEditField.tsx +109 -0
  62. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  63. package/ui/components/wallet/ActivityRow.tsx +222 -120
  64. package/ui/components/wallet/AmountInput.tsx +18 -6
  65. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  66. package/ui/components/wallet/ContactSigil.tsx +49 -0
  67. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  68. package/ui/components/wallet/FitAmount.tsx +148 -0
  69. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  70. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  71. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  72. package/ui/components/wallet/ProfileButton.tsx +62 -0
  73. package/ui/components/wallet/UserAvatar.tsx +85 -0
  74. package/ui/components/wallet/avatarIcons.ts +122 -0
  75. package/ui/hooks/useContactsStore.ts +10 -0
  76. package/ui/hooks/useMandala.ts +18 -1
  77. package/ui/hooks/useOnline.ts +65 -20
  78. package/ui/index.ts +26 -1
  79. package/ui/screens/ContactScreen.tsx +289 -0
  80. package/ui/screens/ContactsScreen.tsx +373 -0
  81. package/ui/screens/IdentifierScreen.tsx +234 -0
  82. package/ui/screens/NewContactScreen.tsx +362 -0
  83. package/ui/screens/PayScreen.tsx +20 -7
  84. package/ui/screens/ProfileScreen.tsx +783 -0
  85. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  86. package/ui/screens/TrustScreen.tsx +1 -1
  87. package/ui/screens/WalletConfigScreen.tsx +42 -0
  88. package/ui/screens/WalletHomeScreen.tsx +528 -83
  89. package/ui/tokenStatus.ts +21 -0
  90. package/ui/txStatus.ts +43 -5
@@ -0,0 +1,783 @@
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.
5
+ *
6
+ * The registry, not this device, is the source of truth for which handle this
7
+ * key holds: `profile_registered_handle` is only an offline cache, shown at
8
+ * once and corrected the moment the reverse lookup answers, so a restored
9
+ * wallet on a new device shows the right handle without having claimed
10
+ * anything. A build with no registry configured for the selected chain says so
11
+ * (`profile_handle_unavailable`) rather than pretending a check can succeed.
12
+ *
13
+ * The hero disc wears whatever icon the user picked ("Edit picture" →
14
+ * "Pick icon"), and the same choice is what every other "you" in the app
15
+ * draws — see `core/userAvatar.ts`. Photo sources are not offered yet: they
16
+ * need `expo-image-picker`, which this build does not carry, and the sheet
17
+ * lists only what actually works rather than a dead control.
18
+ */
19
+ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
20
+ import { ActivityIndicator, I18nManager, ScrollView, StyleSheet, Text, TextInput, View } from 'react-native'
21
+ import { useSafeAreaInsets } from 'react-native-safe-area-context'
22
+ import { useTranslation } from 'react-i18next'
23
+ import { useTheme, spacing, radii, typography, useWallet, useUserAvatarIcon } from '@bsv/expo-wallet-toolbox'
24
+ import PressableScale from '../components/ui/PressableScale'
25
+ import { GroupedSection } from '../components/ui/GroupedList'
26
+ import { ListRow } from '../components/ui/ListRow'
27
+ import { PencilEditField } from '../components/ui/PencilEditField'
28
+ import { showToast } from '../components/ui/Toast'
29
+ import IdentifierRow from '../components/wallet/IdentifierRow'
30
+ import { AvatarGlyph } from '../components/wallet/UserAvatar'
31
+ import EditPictureSheet from '../components/wallet/EditPictureSheet'
32
+ import IconPickerSheet from '../components/wallet/IconPickerSheet'
33
+ import { makeIdentityClient, resolveIdentity } from '../resolveIdentity'
34
+ import { getHandleRegistryConfig } from '../../core/toolboxConfig'
35
+ import { bindOriginator } from '../../core/mandala/createRuntime'
36
+ import { isValidHandleFormat, parsePaymail } from '../../core/identity/handleRegistry/rules'
37
+ import type { ProfileSigner } from '../../core/identity/handleRegistry/profileCert'
38
+ import { createHandleRegistryClient, type AvailabilityReason } from '../../core/identity/handleRegistry/client'
39
+ import {
40
+ changeHandle,
41
+ registerHandle,
42
+ resumePending,
43
+ updateProfile,
44
+ type RegistrationResult
45
+ } from '../../core/identity/handleRegistry/registration'
46
+
47
+ /** What the claim field can be saying. `checking` and `failed` are this
48
+ * screen's own; the rest are the registry's own reasons. */
49
+ type HandleAvailability = 'checking' | 'available' | 'failed' | AvailabilityReason
50
+
51
+ type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
52
+ let ioniconsComponent: IoniconsComponent | undefined
53
+ function loadIonicons(): IoniconsComponent {
54
+ if (!ioniconsComponent) {
55
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
56
+ ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
57
+ }
58
+ return ioniconsComponent
59
+ }
60
+
61
+ type ExpoRouterModule = typeof import('expo-router')
62
+ let expoRouterMod: ExpoRouterModule | undefined
63
+ function loadExpoRouter(): ExpoRouterModule {
64
+ if (!expoRouterMod) {
65
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
66
+ expoRouterMod = require('expo-router') as ExpoRouterModule
67
+ }
68
+ return expoRouterMod
69
+ }
70
+
71
+ /** The full `handle@domain`, cached for a cold start. The registry decides. */
72
+ const HANDLE_KV_KEY = 'profile_registered_handle'
73
+ /**
74
+ * The display name lives here on this device, and — once a handle is
75
+ * registered — as a PUBLIC plaintext field of the profile certificate
76
+ * (2026-09-18 ruling). The identity overlay's `name` is only a fallback for a
77
+ * wallet that has never set one.
78
+ */
79
+ const DISPLAY_NAME_KV_KEY = 'profile_display_name'
80
+ const HANDLE_CHECK_DEBOUNCE_MS = 400
81
+
82
+ export function ProfileScreen() {
83
+ const { t } = useTranslation()
84
+ const { colors } = useTheme()
85
+ const insets = useSafeAreaInsets()
86
+ const Ionicons = loadIonicons()
87
+ const { router } = loadExpoRouter()
88
+ const { managers, adminOriginator, selectedNetwork, storage } = useWallet()
89
+ const wallet = managers?.permissionsManager || null
90
+
91
+ const [identityKey, setIdentityKey] = useState('')
92
+ const avatarIcon = useUserAvatarIcon()
93
+ const [editPictureOpen, setEditPictureOpen] = useState(false)
94
+ const [iconPickerOpen, setIconPickerOpen] = useState(false)
95
+ const [displayName, setDisplayName] = useState('')
96
+ const [displayNameLoaded, setDisplayNameLoaded] = useState(false)
97
+ const [registeredPaymail, setRegisteredPaymail] = useState<string | null>(null)
98
+ const [changingHandle, setChangingHandle] = useState(false)
99
+ const [handleInput, setHandleInput] = useState('')
100
+ const [availability, setAvailability] = useState<HandleAvailability | 'idle'>('idle')
101
+ const [registering, setRegistering] = useState(false)
102
+ /** A journalled write that has not landed yet. Non-blocking, with a retry. */
103
+ const [finishing, setFinishing] = useState(false)
104
+
105
+ /**
106
+ * Two strings, not the config object: `getHandleRegistryConfig` builds a
107
+ * fresh `{ domain, url }` on every call, so memoising on the object would
108
+ * hand `useMemo` a new identity every render — a new client every render, and
109
+ * the mount effect below (which resumes a journal and asks the registry who
110
+ * we are) re-running on every keystroke in either field.
111
+ */
112
+ const registry = getHandleRegistryConfig(selectedNetwork)
113
+ const registryDomain = registry?.domain
114
+ const registryUrl = registry?.url
115
+ const client = useMemo(
116
+ () =>
117
+ registryDomain && registryUrl
118
+ ? createHandleRegistryClient({ pinned: { domain: registryDomain, url: registryUrl } })
119
+ : null,
120
+ [registryDomain, registryUrl]
121
+ )
122
+ /** Bound to the admin originator so signing our own profile never raises a
123
+ * permission prompt (core/mandala/createRuntime.ts). */
124
+ const signer = useMemo(
125
+ () => (wallet ? (bindOriginator(wallet, adminOriginator) as unknown as ProfileSigner) : null),
126
+ [wallet, adminOriginator]
127
+ )
128
+
129
+ useEffect(() => {
130
+ if (!wallet) return
131
+ void wallet.getPublicKey({ identityKey: true }, adminOriginator).then(r => {
132
+ if (r?.publicKey) setIdentityKey(r.publicKey)
133
+ })
134
+ // A cached value from before handles carried a domain names a handle on a
135
+ // registry we cannot identify, so it is worth nothing.
136
+ void storage?.getKeyValue(HANDLE_KV_KEY).then(v => {
137
+ if (v && parsePaymail(v)) setRegisteredPaymail(v)
138
+ })
139
+ void storage?.getKeyValue(DISPLAY_NAME_KV_KEY).then(v => {
140
+ if (v) {
141
+ setDisplayName(v)
142
+ setDisplayNameLoaded(true)
143
+ } else {
144
+ setDisplayNameLoaded(true)
145
+ }
146
+ })
147
+ }, [wallet, adminOriginator, storage])
148
+
149
+ // Fallback only: a name the overlay already has for this key, used when no
150
+ // local display name was ever saved. Never overwrites a saved one.
151
+ useEffect(() => {
152
+ if (!wallet || !identityKey || !displayNameLoaded || displayName !== '') return
153
+ const idClient = makeIdentityClient(wallet as never, adminOriginator)
154
+ if (!idClient) return
155
+ let cancelled = false
156
+ void resolveIdentity(idClient, identityKey).then(([, identity]) => {
157
+ if (!cancelled && identity?.name) setDisplayName(identity.name)
158
+ })
159
+ return () => {
160
+ cancelled = true
161
+ }
162
+ // displayName deliberately omitted: this runs once the local read settles,
163
+ // not on every edit.
164
+ // eslint-disable-next-line react-hooks/exhaustive-deps
165
+ }, [wallet, identityKey, adminOriginator, displayNameLoaded])
166
+
167
+ const [resumeNonce, setResumeNonce] = useState(0)
168
+ /**
169
+ * Bumped by every registration run that WRITES the registered handle, so the
170
+ * reverse lookup this screen started with — whose answer the registry
171
+ * computed before that write — cannot put the old handle back on screen and,
172
+ * worse, back into the offline cache.
173
+ */
174
+ const handleEpoch = useRef(0)
175
+
176
+ /**
177
+ * What a registration run did, and what the user is told about it. One
178
+ * function for the Claim button and for the journal this screen resumes on
179
+ * mount, because a resumed journal reaches exactly the same outcomes: a
180
+ * `rolled_back` nobody is shown is a handle silently swapped back, and a
181
+ * `rejected` nobody is shown is a registration that simply never happened.
182
+ *
183
+ * `attempted` is the handle the user was reaching for, for the one message
184
+ * that has to name a handle the result does not carry.
185
+ */
186
+ const applyResult = useCallback(
187
+ (result: RegistrationResult, attempted?: string) => {
188
+ // `pending` is the only kind that leaves a journal for the callout's
189
+ // Retry to finish. Any other kind leaving `finishing` standing would
190
+ // disable Claim for the rest of the visit.
191
+ setFinishing(result.kind === 'pending')
192
+ if (result.kind === 'registered' || result.kind === 'changed' || result.kind === 'rolled_back') {
193
+ handleEpoch.current += 1
194
+ setRegisteredPaymail(result.paymail)
195
+ void storage?.setKeyValue(HANDLE_KV_KEY, result.paymail)
196
+ setChangingHandle(false)
197
+ setHandleInput('')
198
+ setAvailability('idle')
199
+ }
200
+ if (result.kind === 'registered' || result.kind === 'changed') {
201
+ showToast(t(result.kind === 'changed' ? 'profile_handle_changed' : 'profile_handle_registered'), {
202
+ type: 'success'
203
+ })
204
+ } else if (result.kind === 'rolled_back') {
205
+ // The new handle went to somebody else between the release and the
206
+ // claim; the old one was taken back, so say which one is still yours.
207
+ showToast(
208
+ t('profile_handle_rolled_back', { handle: result.attempted ?? attempted ?? '', previous: result.paymail }),
209
+ { type: 'error' }
210
+ )
211
+ } else if (result.kind === 'pending' || result.kind === 'idle') {
212
+ // The callout says the first. The second is the ordinary mount, with
213
+ // nothing journalled and so nothing to report.
214
+ } else if (result.kind === 'unavailable') {
215
+ showToast(t('profile_handle_unavailable'), { type: 'error' })
216
+ } else if (result.kind === 'rejected') {
217
+ showToast(t('profile_handle_rejected'), { type: 'error' })
218
+ } else if (result.kind === 'failed') {
219
+ // A refusal the module reached on its own carries a code; only an
220
+ // exception's message is English this screen cannot translate.
221
+ if (result.code === 'clock_ahead') showToast(t('profile_handle_clock_ahead'), { type: 'error' })
222
+ else if (result.code === 'wrong_domain') showToast(t('profile_handle_wrong_registry'), { type: 'error' })
223
+ else showToast(result.message, { type: 'error' })
224
+ } else {
225
+ // `updated` cannot reach here from either caller today, but a result
226
+ // kind with no branch is a button that spins and then silently does
227
+ // nothing — the one outcome this screen must never have.
228
+ showToast(t('profile_handle_rejected'), { type: 'error' })
229
+ }
230
+ },
231
+ [storage, t]
232
+ )
233
+ /**
234
+ * Read by the mount effect instead of being a dependency of it: `t` is a
235
+ * fresh function on every render, so depending on `applyResult` would resume
236
+ * the journal and re-ask the registry once per keystroke.
237
+ */
238
+ const applyResultRef = useRef(applyResult)
239
+ useEffect(() => {
240
+ applyResultRef.current = applyResult
241
+ }, [applyResult])
242
+
243
+ /**
244
+ * Finish anything a previous run left journalled, then ask the registry what
245
+ * it actually holds for this key. In that order: a resumed claim is the very
246
+ * thing the lookup would otherwise report as absent.
247
+ *
248
+ * `lookupProfile` rather than `lookupIdentityKey` because this screen WRITES
249
+ * the answer into the offline cache, and only the registry saying this key
250
+ * holds nothing may clear it (spec: "a 404 clears it"). A registry that did
251
+ * not answer at all — no network, a timeout — leaves the cached handle
252
+ * exactly as it was; blanking it for want of a network is the opposite of a
253
+ * cache, and it is the one value this screen cannot mint again offline.
254
+ */
255
+ useEffect(() => {
256
+ if (!client || !signer || !storage || !identityKey) return
257
+ let cancelled = false
258
+ void (async () => {
259
+ const resumed = await resumePending({ client, signer, storage })
260
+ if (cancelled) return
261
+ applyResultRef.current(resumed)
262
+ // Read after the resume, because the resume may itself have written the
263
+ // handle: what this lookup is about to compute is only stale against
264
+ // writes that land after it was asked.
265
+ const epoch = handleEpoch.current
266
+ const seen = await client.lookupProfile(identityKey)
267
+ // A claim that landed while this request was in flight has already put
268
+ // the new handle on screen and in the cache. An answer the registry
269
+ // computed before it would put the old one back — and the cache is the
270
+ // one value this screen cannot mint again offline.
271
+ if (cancelled || seen.kind === 'failed' || epoch !== handleEpoch.current) return
272
+ const paymail = seen.kind === 'found' ? seen.profile.paymail : ''
273
+ setRegisteredPaymail(paymail === '' ? null : paymail)
274
+ // Written only when it says something the cache does not already say: a
275
+ // wallet that has never claimed a handle should not gain a row saying so
276
+ // on every visit to this screen. Best effort, like the display-name write
277
+ // below: the registry's answer is already on screen, and a store that
278
+ // would not take the row must not become an unhandled rejection.
279
+ try {
280
+ const cached = (await storage.getKeyValue(HANDLE_KV_KEY)) ?? ''
281
+ if (cached !== paymail) await storage.setKeyValue(HANDLE_KV_KEY, paymail)
282
+ } catch {
283
+ // Nothing to say and nothing to undo: the next mount asks again.
284
+ }
285
+ })()
286
+ return () => {
287
+ cancelled = true
288
+ }
289
+ }, [client, signer, storage, identityKey, resumeNonce])
290
+
291
+ const checkTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
292
+ /** Bumped per request; a reply for a superseded input is dropped. */
293
+ const checkNonce = useRef(0)
294
+ // A debounce outlives the screen: leaving Profile mid-word would otherwise
295
+ // still ask the registry, and then answer into a tree that is gone. The nonce
296
+ // only drops superseded replies, not post-unmount ones.
297
+ useEffect(
298
+ () => () => {
299
+ if (checkTimer.current) clearTimeout(checkTimer.current)
300
+ },
301
+ []
302
+ )
303
+ const runCheck = useCallback(
304
+ (text: string) => {
305
+ if (checkTimer.current) clearTimeout(checkTimer.current)
306
+ checkNonce.current += 1
307
+ const handle = text.trim().toLowerCase()
308
+ if (!client || handle === '') {
309
+ setAvailability('idle')
310
+ return
311
+ }
312
+ setAvailability('checking')
313
+ const nonce = checkNonce.current
314
+ checkTimer.current = setTimeout(async () => {
315
+ const result = await client.checkAvailability(handle)
316
+ if (nonce !== checkNonce.current) return
317
+ setAvailability(result.kind === 'unavailable' ? result.reason : result.kind)
318
+ }, HANDLE_CHECK_DEBOUNCE_MS)
319
+ },
320
+ [client]
321
+ )
322
+ const onChangeHandle = useCallback(
323
+ (text: string) => {
324
+ setHandleInput(text)
325
+ runCheck(text)
326
+ },
327
+ [runCheck]
328
+ )
329
+
330
+ const onRegister = useCallback(async () => {
331
+ if (!client || !signer || !storage || availability !== 'available' || finishing) return
332
+ const handle = handleInput.trim().toLowerCase()
333
+ if (!isValidHandleFormat(handle)) return
334
+ setRegistering(true)
335
+ try {
336
+ const deps = { client, signer, storage }
337
+ const result: RegistrationResult = registeredPaymail
338
+ ? await changeHandle(deps, { previousPaymail: registeredPaymail, handle, displayName })
339
+ : await registerHandle(deps, { handle, displayName })
340
+ applyResult(result, registryDomain ? `${handle}@${registryDomain}` : handle)
341
+ // A refusal may well be about a handle this key no longer holds — it was
342
+ // released or changed on another device — so ask the registry again
343
+ // rather than let the next press repeat the same refusal off a stale
344
+ // cache. Only from a press: doing it from the mount's own resume would
345
+ // be an effect that re-triggers itself.
346
+ if (result.kind === 'rejected' || (result.kind === 'failed' && result.code === 'wrong_domain')) {
347
+ setResumeNonce(n => n + 1)
348
+ }
349
+ } finally {
350
+ setRegistering(false)
351
+ }
352
+ }, [
353
+ client,
354
+ signer,
355
+ storage,
356
+ availability,
357
+ finishing,
358
+ handleInput,
359
+ displayName,
360
+ registeredPaymail,
361
+ registryDomain,
362
+ applyResult
363
+ ])
364
+
365
+ /**
366
+ * Local first, always: the name is this device's to show even with no
367
+ * network. When a handle is registered it is also a public field of the
368
+ * profile certificate, so the registry gets a fresh one — best effort, and
369
+ * never something the user has to wait on.
370
+ */
371
+ const onSaveDisplayName = useCallback(
372
+ async (next: string) => {
373
+ const trimmed = next.trim()
374
+ setDisplayName(trimmed)
375
+ try {
376
+ await storage?.setKeyValue(DISPLAY_NAME_KV_KEY, trimmed)
377
+ } catch (e) {
378
+ showToast(e instanceof Error ? e.message : String(e), { type: 'error' })
379
+ }
380
+ if (!client || !signer || !storage || !registeredPaymail) return
381
+ // A journalled write is still outstanding: asking the registry for a
382
+ // second intent now would be answered by finishing the first, which is
383
+ // not what a rename asked for. The name is already saved on this device,
384
+ // and the next save publishes it.
385
+ if (finishing) return
386
+ const result = await updateProfile(
387
+ { client, signer, storage },
388
+ { paymail: registeredPaymail, displayName: trimmed }
389
+ )
390
+ // `updated` is the ordinary success: the name is already on screen and a
391
+ // toast for it would be noise. A refusal is the opposite — the registry
392
+ // goes on serving the previous name under a hint that says this one is
393
+ // public — so it is named for what it is rather than as a handle the
394
+ // registry turned down.
395
+ if (result.kind === 'updated') return
396
+ if (result.kind === 'rejected' || result.kind === 'failed') {
397
+ showToast(t('profile_display_name_publish_failed'), { type: 'error' })
398
+ return
399
+ }
400
+ applyResult(result)
401
+ },
402
+ [storage, client, signer, registeredPaymail, finishing, applyResult, t]
403
+ )
404
+
405
+ const handle = handleInput.trim().toLowerCase()
406
+ const paymailPreview = registryDomain ? `${handle}@${registryDomain}` : handle
407
+ const editingHandle = !!registryDomain && (!registeredPaymail || changingHandle)
408
+ const statusLine: Partial<Record<HandleAvailability, { text: string; color: string; icon: string }>> = {
409
+ checking: { text: t('profile_handle_checking'), color: colors.textSecondary, icon: 'time-outline' },
410
+ available: {
411
+ text: t('profile_handle_available', { handle: paymailPreview }),
412
+ color: colors.success,
413
+ icon: 'checkmark-circle'
414
+ },
415
+ taken: { text: t('profile_handle_taken', { handle: paymailPreview }), color: colors.error, icon: 'close-circle' },
416
+ too_similar: {
417
+ text: t('profile_handle_too_similar', { handle: paymailPreview }),
418
+ color: colors.error,
419
+ icon: 'close-circle'
420
+ },
421
+ reserved: {
422
+ text: t('profile_handle_reserved', { handle: paymailPreview }),
423
+ color: colors.error,
424
+ icon: 'close-circle'
425
+ },
426
+ cooldown: {
427
+ text: t('profile_handle_cooldown', { handle: paymailPreview }),
428
+ color: colors.warning,
429
+ icon: 'time-outline'
430
+ },
431
+ invalid: { text: t('profile_handle_invalid'), color: colors.warning, icon: 'alert-circle' }
432
+ }
433
+ const status = availability === 'idle' ? undefined : statusLine[availability]
434
+ // `finishing` disables it too: a journalled write is the only copy of a
435
+ // signed, replayable certificate, and a press that started a second intent
436
+ // over it would be a release the registry has nothing left to apply. The
437
+ // callout's own Retry is the way out of that state.
438
+ const canClaim = availability === 'available' && !registering && !finishing
439
+
440
+ return (
441
+ <View style={[styles.container, { backgroundColor: colors.background, paddingTop: insets.top }]}>
442
+ <View style={[styles.header, { borderBottomColor: colors.separator }]}>
443
+ <PressableScale
444
+ onPress={() => router.back()}
445
+ haptic="tap"
446
+ style={styles.headerBtn}
447
+ accessibilityRole="button"
448
+ accessibilityLabel={t('go_back')}
449
+ >
450
+ <Ionicons
451
+ name={I18nManager.isRTL ? 'chevron-forward' : 'chevron-back'}
452
+ size={24}
453
+ color={colors.textSecondary}
454
+ />
455
+ </PressableScale>
456
+ <Text style={[styles.headerTitle, { color: colors.textPrimary }]} numberOfLines={1}>
457
+ {t('profile')}
458
+ </Text>
459
+ <View style={styles.headerBtn} />
460
+ </View>
461
+
462
+ <ScrollView
463
+ contentContainerStyle={[styles.content, { paddingBottom: Math.max(insets.bottom, spacing.lg) }]}
464
+ keyboardShouldPersistTaps="handled"
465
+ >
466
+ <View style={styles.hero}>
467
+ <View style={[styles.heroDisc, { backgroundColor: colors.accent }]}>
468
+ <AvatarGlyph
469
+ family={avatarIcon?.family ?? 'ionicons'}
470
+ name={avatarIcon?.name ?? 'person'}
471
+ size={44}
472
+ color={colors.textOnAccent}
473
+ />
474
+ </View>
475
+ {/* Centred pill under the disc — the only control that changes the
476
+ picture, so it says what it does rather than relying on the disc
477
+ being discoverably tappable. */}
478
+ <PressableScale
479
+ haptic="tap"
480
+ onPress={() => setEditPictureOpen(true)}
481
+ accessibilityRole="button"
482
+ style={[styles.editPicture, { borderColor: colors.separator, backgroundColor: colors.fillTertiary }]}
483
+ >
484
+ <Text style={[styles.editPictureLabel, { color: colors.textPrimary }]}>
485
+ {t('avatar_edit_picture', { defaultValue: 'Edit picture' })}
486
+ </Text>
487
+ </PressableScale>
488
+ </View>
489
+
490
+ <GroupedSection header={t('profile_display_name')} footer={t('profile_display_name_hint')}>
491
+ <PencilEditField
492
+ value={displayName}
493
+ placeholder={t('profile_display_name')}
494
+ onSave={onSaveDisplayName}
495
+ editAccessibilityLabel={t('contact_edit_name')}
496
+ saveAccessibilityLabel={t('contact_save_name')}
497
+ />
498
+ </GroupedSection>
499
+
500
+ <GroupedSection
501
+ header={t('profile_handle')}
502
+ footer={registeredPaymail && !changingHandle ? t('profile_handle_registered_hint') : undefined}
503
+ >
504
+ {!registryDomain && !registeredPaymail ? (
505
+ <Text style={[styles.unavailable, { color: colors.textSecondary }]}>{t('profile_handle_unavailable')}</Text>
506
+ ) : !editingHandle ? (
507
+ <View style={styles.registeredRow}>
508
+ {/* The caption sits UNDER the handle rather than beside it. In
509
+ one row the handle is the only element that can shrink, so it
510
+ absorbs every overflow: "Registered" and "Change" are longer
511
+ than the English this row was sized against in most locales,
512
+ and a paymail is fourteen characters where the old `@dee` was
513
+ four — which ellipsised the one string on this screen that
514
+ has to render in full. */}
515
+ <View style={styles.registeredText}>
516
+ <Text style={[styles.registeredHandle, { color: colors.textPrimary }]} numberOfLines={1}>
517
+ {registeredPaymail}
518
+ </Text>
519
+ <View style={styles.registeredCaptionRow}>
520
+ <Ionicons name="checkmark-circle" size={14} color={colors.success} />
521
+ <Text style={[styles.registeredCaption, { color: colors.textSecondary }]} numberOfLines={1}>
522
+ {t('pay_trust_handle_attested')}
523
+ </Text>
524
+ </View>
525
+ </View>
526
+ {!!registryDomain && (
527
+ <PressableScale
528
+ onPress={() => setChangingHandle(true)}
529
+ haptic="tap"
530
+ style={styles.textBtn}
531
+ accessibilityRole="button"
532
+ >
533
+ <Text style={[styles.textBtnLabel, { color: colors.accent }]}>{t('profile_handle_change')}</Text>
534
+ </PressableScale>
535
+ )}
536
+ </View>
537
+ ) : (
538
+ <>
539
+ <View style={styles.handleRow}>
540
+ <TextInput
541
+ value={handleInput}
542
+ onChangeText={onChangeHandle}
543
+ placeholder={t('profile_handle_placeholder')}
544
+ placeholderTextColor={colors.textTertiary}
545
+ autoCapitalize="none"
546
+ autoCorrect={false}
547
+ autoFocus={changingHandle}
548
+ style={[styles.handleInput, { color: colors.textPrimary }]}
549
+ />
550
+ {/* Fixed, not typed: a handle is only ever claimed on the
551
+ domain this build is configured for. */}
552
+ <Text style={[styles.atSign, { color: colors.textTertiary }]} numberOfLines={1}>
553
+ @{registryDomain}
554
+ </Text>
555
+ {availability === 'checking' ? (
556
+ <ActivityIndicator size="small" color={colors.textSecondary} />
557
+ ) : status ? (
558
+ <Ionicons name={status.icon as never} size={18} color={status.color} />
559
+ ) : null}
560
+ {registeredPaymail && (
561
+ <PressableScale
562
+ // Through `runCheck` rather than straight to `idle`: it also
563
+ // clears the debounce and bumps the nonce, so a check for
564
+ // the abandoned text cannot land on the emptied field and
565
+ // leave Claim enabled with nothing in it.
566
+ onPress={() => {
567
+ setChangingHandle(false)
568
+ setHandleInput('')
569
+ runCheck('')
570
+ }}
571
+ haptic="tap"
572
+ style={styles.textBtn}
573
+ accessibilityRole="button"
574
+ >
575
+ <Text style={[styles.textBtnLabel, { color: colors.textSecondary }]}>{t('cancel')}</Text>
576
+ </PressableScale>
577
+ )}
578
+ </View>
579
+ {availability === 'failed' ? (
580
+ <View style={[styles.failedWrap]}>
581
+ <View
582
+ style={[styles.failedCard, { borderColor: colors.error, backgroundColor: colors.error + '15' }]}
583
+ >
584
+ <Ionicons name="alert-circle-outline" size={18} color={colors.error} />
585
+ <View style={styles.failedText}>
586
+ <Text style={[styles.failedTitle, { color: colors.textPrimary }]}>
587
+ {t('profile_handle_failed')}
588
+ </Text>
589
+ <PressableScale
590
+ onPress={() => runCheck(handleInput)}
591
+ haptic="tap"
592
+ style={styles.retryBtn}
593
+ accessibilityRole="button"
594
+ >
595
+ <Text style={[styles.retryLabel, { color: colors.accent }]}>{t('retry')}</Text>
596
+ </PressableScale>
597
+ </View>
598
+ </View>
599
+ </View>
600
+ ) : status ? (
601
+ <View style={styles.statusRow}>
602
+ <Ionicons name={status.icon as never} size={12} color={status.color} />
603
+ <Text style={[styles.statusText, { color: status.color }]}>{status.text}</Text>
604
+ </View>
605
+ ) : null}
606
+ </>
607
+ )}
608
+ </GroupedSection>
609
+
610
+ {finishing && (
611
+ <View style={[styles.callout, { backgroundColor: colors.fillTertiary, borderColor: colors.separator }]}>
612
+ <Ionicons name="time-outline" size={16} color={colors.textSecondary} />
613
+ <Text style={[styles.calloutText, { color: colors.textSecondary }]}>{t('profile_handle_pending')}</Text>
614
+ <PressableScale
615
+ onPress={() => setResumeNonce(n => n + 1)}
616
+ haptic="tap"
617
+ style={styles.retryBtn}
618
+ accessibilityRole="button"
619
+ >
620
+ <Text style={[styles.retryLabel, { color: colors.accent }]}>{t('retry')}</Text>
621
+ </PressableScale>
622
+ </View>
623
+ )}
624
+
625
+ {editingHandle && registeredPaymail && (
626
+ <View style={[styles.callout, { backgroundColor: colors.fillTertiary, borderColor: colors.separator }]}>
627
+ <Ionicons name="information-circle-outline" size={16} color={colors.textSecondary} />
628
+ <Text style={[styles.calloutText, { color: colors.textSecondary }]}>
629
+ {t('profile_handle_replace_warning', { handle: registeredPaymail })}
630
+ </Text>
631
+ </View>
632
+ )}
633
+
634
+ <GroupedSection header={t('profile_identifier_section')}>
635
+ <ListRow
636
+ label={t('profile_show_qr')}
637
+ subtitle={t('profile_show_qr_hint')}
638
+ icon="qr-code-outline"
639
+ onPress={() =>
640
+ router.push({
641
+ pathname: '/identifier',
642
+ params: { identityKey, name: displayName, handle: registeredPaymail ?? '' }
643
+ } as never)
644
+ }
645
+ />
646
+ {!!identityKey && <IdentifierRow identityKey={identityKey} />}
647
+ </GroupedSection>
648
+ </ScrollView>
649
+
650
+ {/* Where a picture comes from. One source today; Take Photo and Photo
651
+ Library join this list when `expo-image-picker` does. */}
652
+ <EditPictureSheet
653
+ visible={editPictureOpen}
654
+ onClose={() => setEditPictureOpen(false)}
655
+ options={[
656
+ {
657
+ key: 'pick-icon',
658
+ label: t('avatar_pick_icon', { defaultValue: 'Pick icon' }),
659
+ onPress: () => setIconPickerOpen(true)
660
+ }
661
+ ]}
662
+ />
663
+ <IconPickerSheet visible={iconPickerOpen} onClose={() => setIconPickerOpen(false)} />
664
+
665
+ {editingHandle && (
666
+ <View style={[styles.footer, { paddingBottom: Math.max(insets.bottom, spacing.lg) }]}>
667
+ <PressableScale
668
+ onPress={onRegister}
669
+ disabled={!canClaim}
670
+ haptic="confirm"
671
+ style={[styles.cta, { backgroundColor: canClaim ? colors.accent : colors.fill }]}
672
+ accessibilityRole="button"
673
+ accessibilityState={{ disabled: !canClaim }}
674
+ >
675
+ {registering ? (
676
+ <ActivityIndicator size="small" color={colors.textTertiary} />
677
+ ) : (
678
+ <Text style={[styles.ctaText, { color: canClaim ? colors.textOnAccent : colors.textTertiary }]}>
679
+ {handle ? t('profile_handle_claim', { handle: paymailPreview }) : t('profile_handle_register_action')}
680
+ </Text>
681
+ )}
682
+ </PressableScale>
683
+ </View>
684
+ )}
685
+ </View>
686
+ )
687
+ }
688
+
689
+ export default ProfileScreen
690
+
691
+ const styles = StyleSheet.create({
692
+ container: { flex: 1 },
693
+ header: {
694
+ flexDirection: 'row',
695
+ alignItems: 'center',
696
+ justifyContent: 'space-between',
697
+ paddingHorizontal: spacing.sm,
698
+ paddingVertical: spacing.md,
699
+ borderBottomWidth: StyleSheet.hairlineWidth
700
+ },
701
+ headerBtn: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center' },
702
+ headerTitle: { ...typography.headline, fontWeight: '600', flex: 1, textAlign: 'center' },
703
+ content: { paddingTop: spacing.lg },
704
+ hero: { alignItems: 'center', paddingTop: spacing.sm, paddingBottom: spacing.xl },
705
+ heroDisc: { width: 96, height: 96, borderRadius: 48, alignItems: 'center', justifyContent: 'center' },
706
+ editPicture: {
707
+ marginTop: spacing.md,
708
+ paddingHorizontal: spacing.lg,
709
+ paddingVertical: spacing.sm,
710
+ borderRadius: radii.pill,
711
+ borderWidth: StyleSheet.hairlineWidth
712
+ },
713
+ editPictureLabel: { ...typography.subhead, fontWeight: '600' },
714
+ unavailable: { ...typography.footnote, paddingHorizontal: spacing.lg, paddingVertical: spacing.md },
715
+ registeredRow: {
716
+ flexDirection: 'row',
717
+ alignItems: 'center',
718
+ gap: spacing.sm,
719
+ minHeight: 48,
720
+ paddingLeft: spacing.lg,
721
+ paddingRight: spacing.xs,
722
+ paddingVertical: spacing.sm
723
+ },
724
+ registeredText: { flex: 1, minWidth: 0, gap: 2 },
725
+ registeredHandle: { ...typography.body, fontWeight: '600' },
726
+ registeredCaptionRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
727
+ registeredCaption: { ...typography.footnote, flexShrink: 1 },
728
+ textBtn: { minHeight: 44, paddingHorizontal: spacing.md, justifyContent: 'center' },
729
+ textBtnLabel: { ...typography.footnote, fontWeight: '600' },
730
+ handleRow: {
731
+ flexDirection: 'row',
732
+ alignItems: 'center',
733
+ gap: spacing.sm,
734
+ minHeight: 52,
735
+ paddingLeft: spacing.lg,
736
+ paddingRight: spacing.xs
737
+ },
738
+ atSign: { ...typography.body },
739
+ handleInput: { ...typography.body, flex: 1, minWidth: 0, paddingVertical: spacing.md, paddingHorizontal: 0 },
740
+ statusRow: {
741
+ flexDirection: 'row',
742
+ alignItems: 'center',
743
+ gap: spacing.xs,
744
+ paddingHorizontal: spacing.lg,
745
+ paddingBottom: spacing.md
746
+ },
747
+ statusText: { ...typography.caption1, fontWeight: '500' },
748
+ failedWrap: { paddingHorizontal: spacing.lg, paddingBottom: spacing.md },
749
+ failedCard: {
750
+ flexDirection: 'row',
751
+ alignItems: 'flex-start',
752
+ gap: spacing.sm,
753
+ padding: spacing.md,
754
+ borderRadius: radii.md,
755
+ borderWidth: 1
756
+ },
757
+ failedText: { flex: 1, gap: spacing.xs },
758
+ failedTitle: { ...typography.subhead },
759
+ retryBtn: { alignSelf: 'flex-start', minHeight: 32, justifyContent: 'center' },
760
+ retryLabel: { ...typography.subhead, fontWeight: '700' },
761
+ callout: {
762
+ flexDirection: 'row',
763
+ alignItems: 'center',
764
+ gap: spacing.sm,
765
+ marginHorizontal: spacing.lg,
766
+ marginTop: -spacing.md,
767
+ marginBottom: spacing.xxl,
768
+ borderWidth: StyleSheet.hairlineWidth,
769
+ borderRadius: radii.md,
770
+ paddingVertical: spacing.sm + 2,
771
+ paddingHorizontal: spacing.md
772
+ },
773
+ calloutText: { ...typography.footnote, flex: 1 },
774
+ footer: { paddingHorizontal: spacing.lg, paddingTop: spacing.sm },
775
+ cta: {
776
+ alignItems: 'center',
777
+ justifyContent: 'center',
778
+ minHeight: 48,
779
+ paddingVertical: spacing.md + 2,
780
+ borderRadius: radii.md
781
+ },
782
+ ctaText: { ...typography.subhead, fontWeight: '600' }
783
+ })