@bsv/expo-wallet-toolbox 0.5.0 → 0.9.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 (200) hide show
  1. package/CHANGELOG.md +2000 -0
  2. package/README.md +66 -1
  3. package/core/amountFormatHelpers.ts +258 -36
  4. package/core/backup/RemoteSyncReader.ts +133 -24
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +149 -11
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +71 -5
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/config.tsx +12 -5
  15. package/core/constants.ts +14 -1
  16. package/core/contacts/contactActivity.ts +153 -0
  17. package/core/contacts/contactCache.ts +41 -0
  18. package/core/contacts/contactsStore.ts +183 -0
  19. package/core/context/ExchangeRateContext.tsx +34 -27
  20. package/core/context/LocalStorageProvider.tsx +43 -40
  21. package/core/context/UserContext.tsx +18 -7
  22. package/core/context/VaultContext.tsx +49 -2
  23. package/core/context/WalletConnectionContext.tsx +203 -11
  24. package/core/context/WalletContext.tsx +685 -171
  25. package/core/demo/demoAssets.ts +60 -0
  26. package/core/demo/demoLedger.ts +240 -0
  27. package/core/demo/demoMandalaRuntime.ts +96 -0
  28. package/core/demo/demoMode.ts +38 -0
  29. package/core/demo/demoWallet.ts +25 -0
  30. package/core/demo/index.ts +26 -0
  31. package/core/demo/useDemo.ts +59 -0
  32. package/core/headers/OfflineFirstChaintracks.ts +99 -17
  33. package/core/headers/headerStore.ts +33 -14
  34. package/core/headers/syncHeaders.ts +12 -1
  35. package/core/i18n/translations.tsx +2186 -98
  36. package/core/identity/contactLink.ts +36 -0
  37. package/core/identity/handleRegistry/client.ts +314 -0
  38. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  39. package/core/identity/handleRegistry/profileCert.ts +254 -0
  40. package/core/identity/handleRegistry/registration.ts +559 -0
  41. package/core/identity/handleRegistry/resolver.ts +315 -0
  42. package/core/identity/handleRegistry/rules.ts +104 -0
  43. package/core/index.ts +53 -5
  44. package/core/localpay/build.ts +225 -24
  45. package/core/localpay/pending.ts +110 -7
  46. package/core/localpay/pendingAbortAuthority.ts +95 -0
  47. package/core/localpay/pendingAborts.ts +266 -26
  48. package/core/localpay/session.ts +42 -17
  49. package/core/localpay/settlementAck.ts +10 -1
  50. package/core/localpay/transport/socket.ts +52 -3
  51. package/core/localpay/verify.ts +100 -10
  52. package/core/mandala/abortGuard.ts +96 -20
  53. package/core/mandala/createRuntime.ts +206 -33
  54. package/core/mandala/drain.ts +89 -11
  55. package/core/mandala/inboxPrehold.ts +186 -0
  56. package/core/mandala/permissionModule.ts +202 -20
  57. package/core/mandala/settlementStore.ts +24 -2
  58. package/core/mandala/types.ts +40 -5
  59. package/core/monitor/MonitorSupervisor.ts +121 -0
  60. package/core/monitor/TaskBackupPush.ts +15 -1
  61. package/core/monitor/TaskCreditInbox.ts +1 -1
  62. package/core/monitor/TaskDrainOutbox.ts +15 -1
  63. package/core/monitor/TaskSendOffline.ts +15 -1
  64. package/core/net/online.ts +49 -0
  65. package/core/net/publicDestination.ts +91 -0
  66. package/core/net/validateArcUrl.ts +22 -0
  67. package/core/numberFormat.ts +19 -0
  68. package/core/offline/cancelParked.ts +134 -13
  69. package/core/offline/payerHold.ts +100 -24
  70. package/core/offline/plan.ts +37 -8
  71. package/core/pay/beefRepair.ts +6 -2
  72. package/core/pay/damagedInbox.ts +24 -0
  73. package/core/pay/rails/address.ts +107 -12
  74. package/core/pay/rails/handle.ts +117 -22
  75. package/core/pay/rails/index.ts +45 -7
  76. package/core/pay/rails/nativeIntent.ts +61 -0
  77. package/core/pay/receiveHistory.ts +93 -0
  78. package/core/pay/recordProof.ts +21 -7
  79. package/core/pay/refreshProofGuard.ts +42 -1
  80. package/core/pay/watchlist.ts +5 -2
  81. package/core/peerpay/control.ts +17 -18
  82. package/core/peerpay/handleResendRequests.ts +58 -4
  83. package/core/peerpay/outbox.ts +3 -1
  84. package/core/recovery/backupMaterial.ts +61 -0
  85. package/core/recovery/createWallet.ts +95 -0
  86. package/core/recovery/recoverWallet.ts +120 -0
  87. package/core/recovery/restoreWallet.ts +170 -0
  88. package/core/recovery/secret.ts +92 -0
  89. package/core/recovery/shareCollector.ts +71 -0
  90. package/core/recovery/shareParsing.ts +87 -0
  91. package/core/recovery/shares.ts +116 -0
  92. package/core/recovery/useRecoveryDeps.ts +70 -0
  93. package/core/services/arcTokenStorage.ts +52 -0
  94. package/core/services/arcadeBroadcastProvider.ts +233 -52
  95. package/core/services/autoApprovePolicy.ts +105 -0
  96. package/core/services/callbackToken.ts +19 -0
  97. package/core/services/capWalletArgs.ts +14 -2
  98. package/core/services/connectionAuthority.ts +98 -0
  99. package/core/services/exchangeRate.ts +36 -13
  100. package/core/services/externalOrigin.ts +16 -2
  101. package/core/services/secrets/kek.ts +126 -29
  102. package/core/services/secrets/migration.ts +16 -4
  103. package/core/services/secrets/store.ts +42 -14
  104. package/core/services/vault/VaultKeyService.ts +228 -45
  105. package/core/services/vault/chainRecovery.ts +483 -0
  106. package/core/services/vault/driver.ts +9 -1
  107. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  108. package/core/services/vault/guard.ts +218 -32
  109. package/core/services/vault/hardwareLease.ts +19 -0
  110. package/core/services/vault/metaAuthority.ts +210 -0
  111. package/core/services/vault/pivReset.ts +64 -23
  112. package/core/services/vault/r1comb.ts +139 -3
  113. package/core/services/vault/session.ts +25 -4
  114. package/core/services/vault/transfers.ts +868 -172
  115. package/core/services/vault/types.ts +19 -4
  116. package/core/services/vault/vaultStore.ts +256 -29
  117. package/core/services/walletArgLimits.ts +45 -2
  118. package/core/services/walletConnectionValidation.ts +76 -6
  119. package/core/services/walletServiceConfig.ts +40 -27
  120. package/core/storage/StorageExpoSQLite.ts +88 -47
  121. package/core/storage/methods/findSql.ts +24 -2
  122. package/core/storage/methods/listActionsSql.ts +8 -5
  123. package/core/storage/methods/listOutputsSql.ts +2 -2
  124. package/core/storage/methods/offlineActions.ts +10 -1
  125. package/core/storage/methods/processOfflineActions.ts +117 -25
  126. package/core/storage/methods/reviewStatusSql.ts +7 -2
  127. package/core/storage/schema/createTables.ts +155 -2
  128. package/core/stores/ConnectionStore.ts +34 -0
  129. package/core/toolboxConfig.ts +104 -0
  130. package/core/toolboxTypes.ts +40 -0
  131. package/core/userAvatar.ts +79 -0
  132. package/core/walletDbRegistry.ts +63 -0
  133. package/core/walletMonitor.ts +25 -4
  134. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  135. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  136. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  137. package/package.json +7 -7
  138. package/ui/activityFilter.ts +115 -0
  139. package/ui/backupShares.ts +26 -169
  140. package/ui/components/pay/AddressReceive.tsx +13 -6
  141. package/ui/components/pay/AssetPicker.tsx +30 -9
  142. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  143. package/ui/components/pay/NearbyFlow.tsx +480 -243
  144. package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
  145. package/ui/components/pay/RecipientField.tsx +84 -70
  146. package/ui/components/pay/StepBar.tsx +32 -0
  147. package/ui/components/pay/UniversalSend.tsx +827 -205
  148. package/ui/components/ui/AlertCard.tsx +38 -5
  149. package/ui/components/ui/PencilEditField.tsx +109 -0
  150. package/ui/components/ui/PermissionSheet.tsx +197 -66
  151. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  152. package/ui/components/vault/EnrollWizard.tsx +61 -13
  153. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  154. package/ui/components/wallet/ActivityRow.tsx +227 -123
  155. package/ui/components/wallet/AmountInput.tsx +26 -8
  156. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  157. package/ui/components/wallet/Balance.tsx +42 -23
  158. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  159. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  160. package/ui/components/wallet/ContactSigil.tsx +49 -0
  161. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  162. package/ui/components/wallet/FitAmount.tsx +148 -0
  163. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  164. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  165. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  166. package/ui/components/wallet/ProfileButton.tsx +62 -0
  167. package/ui/components/wallet/UserAvatar.tsx +85 -0
  168. package/ui/components/wallet/avatarIcons.ts +122 -0
  169. package/ui/exportTransactions.ts +36 -4
  170. package/ui/hooks/useContactsStore.ts +10 -0
  171. package/ui/hooks/useExportWalletData.ts +25 -2
  172. package/ui/hooks/useMandala.ts +18 -1
  173. package/ui/hooks/useOnline.ts +65 -20
  174. package/ui/importDatabases.ts +339 -24
  175. package/ui/index.ts +33 -2
  176. package/ui/isImageUrl.ts +6 -0
  177. package/ui/printRecoveryShares.ts +9 -10
  178. package/ui/recoveryPrompts.ts +91 -0
  179. package/ui/resolveIdentity.ts +31 -9
  180. package/ui/screens/ConnectionsScreen.tsx +86 -19
  181. package/ui/screens/ContactScreen.tsx +289 -0
  182. package/ui/screens/ContactsScreen.tsx +373 -0
  183. package/ui/screens/IdentifierScreen.tsx +256 -0
  184. package/ui/screens/NewContactScreen.tsx +362 -0
  185. package/ui/screens/PairScreen.tsx +74 -2
  186. package/ui/screens/PayScreen.tsx +20 -7
  187. package/ui/screens/ProfileScreen.tsx +783 -0
  188. package/ui/screens/SettingsScreen.tsx +10 -4
  189. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  190. package/ui/screens/TrustScreen.tsx +100 -5
  191. package/ui/screens/VaultScreen.tsx +410 -61
  192. package/ui/screens/VaultTransferScreen.tsx +59 -7
  193. package/ui/screens/WalletCheckScreen.tsx +17 -6
  194. package/ui/screens/WalletConfigScreen.tsx +124 -28
  195. package/ui/screens/WalletHomeScreen.tsx +640 -104
  196. package/ui/screens/detailActionKeys.ts +55 -0
  197. package/ui/tokenFormat.ts +44 -4
  198. package/ui/tokenStatus.ts +21 -0
  199. package/ui/txStatus.ts +48 -5
  200. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -16,7 +16,7 @@
16
16
  * shown only for addresses, where it is load-bearing — a user who pastes an
17
17
  * address expecting messaging-style delivery has effectively posted cash.
18
18
  */
19
- import React, { memo, useCallback, useEffect, useMemo, useState, useRef } from 'react'
19
+ import React, { forwardRef, memo, useCallback, useEffect, useImperativeHandle, useMemo, useState, useRef } from 'react'
20
20
  import { ActivityIndicator, Modal, ScrollView, StyleSheet, Text, TextInput, View } from 'react-native'
21
21
  import { useTranslation } from 'react-i18next'
22
22
 
@@ -31,24 +31,36 @@ import { showToast } from '../ui/Toast'
31
31
  import { ConsequenceNote, PayAmountField, PayCta, PayField } from './PayForm'
32
32
  import PaymentSuccessOverlay from './PaymentSuccessOverlay'
33
33
  import ResultBanner from './ResultBanner'
34
- import RecipientField from './RecipientField'
34
+ import RecipientField, { type RecipientRow } from './RecipientField'
35
+ import StepBar, { type PayStep } from './StepBar'
35
36
  import { useMessageBoxConfig } from './MessageBoxConfig'
36
37
  import { useRecipientInput, type RecipientTarget, type PeerPayRequest } from './useRecipientInput'
37
38
  import { tokenSendCopy, tokenThrowCopy, type TokenSendCopy } from './tokenSendCopy'
38
39
  import { useAssetStatus, useMandala } from '../../hooks/useMandala'
39
40
  import { useSpendableBalance } from '../../hooks/useSpendableBalance'
40
- import { formatTokenAmount, formatTokenAmountWithUnit } from '../../tokenFormat'
41
+ import { useContactsStore } from '../../hooks/useContactsStore'
42
+ import ContactSigil from '../wallet/ContactSigil'
43
+ import { formatTokenAmount, formatTokenAmountWithUnit, shortAssetId } from '../../tokenFormat'
44
+ import { abbreviateKey } from '../../../core/pay/counterparty'
45
+ import type { ContactRow } from '../../../core/contacts/contactsStore'
46
+ import { createHandleRegistryClient } from '../../../core/identity/handleRegistry/client'
47
+ import type { RegistryProfile } from '../../../core/identity/handleRegistry/profileCert'
41
48
  import {
42
49
  useTheme,
43
50
  spacing,
44
51
  typography,
45
52
  radii,
46
53
  hitTargets,
54
+ formatSatoshisAsBsvDecimal,
55
+ useWallet,
47
56
  useWalletManagers,
48
57
  useWalletStatus,
49
58
  CONSEQUENCE_KEYS,
50
59
  NO_MESSAGE_BOX,
60
+ addressNetwork,
51
61
  cancelOutboxPayment,
62
+ classifyRecipientInput,
63
+ getHandleRegistryConfig,
52
64
  isMessageBoxNetworkError,
53
65
  makePeerPayClient,
54
66
  retryDelivery,
@@ -60,10 +72,28 @@ import {
60
72
  type OutboxEntry,
61
73
  type Session,
62
74
  haptics,
63
- listPendingResendRequests
75
+ listPendingResendRequests,
76
+ makeListPeerPayAction
64
77
  } from '@bsv/expo-wallet-toolbox'
65
78
  import type { DismissTarget } from '../../dismissTarget'
66
79
 
80
+ /**
81
+ * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
82
+ * etc.), one of which reaches expo-font -> expo-asset -- untransformed ESM
83
+ * that Jest cannot parse when eagerly pulled in via the `ui` package barrel.
84
+ * Ionicons is loaded lazily, only when actually rendering, same pattern as
85
+ * this package's other native-module-boundary fixes.
86
+ */
87
+ type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
88
+ let ioniconsComponent: IoniconsComponent | undefined
89
+ function loadIonicons(): IoniconsComponent {
90
+ if (!ioniconsComponent) {
91
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
92
+ ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
93
+ }
94
+ return ioniconsComponent
95
+ }
96
+
67
97
  /**
68
98
  * expo-status-bar's package.json `main` points straight at its raw
69
99
  * TypeScript source (no compiled build output ships), and the unscoped,
@@ -99,6 +129,11 @@ function loadExpoRouter(): ExpoRouterModule {
99
129
  return expoRouterMod
100
130
  }
101
131
 
132
+ /** The registry's own debounce. Deliberately a third constant rather than a
133
+ * shared one: `useRecipientInput`'s overlay timer and `ProfileScreen`'s
134
+ * availability timer are separate decisions that happen to agree today. */
135
+ const REGISTRY_SEARCH_DEBOUNCE_MS = 400
136
+
102
137
  // ── Outgoing Section ─────────────────────────────────────────────────────────
103
138
 
104
139
  interface OutgoingSectionProps {
@@ -186,6 +221,16 @@ function OutgoingSection({ entries, retryingId, colors, t, onRetry, onCancel }:
186
221
  )
187
222
  }
188
223
 
224
+ /**
225
+ * What the host screen can ask of the form: walk back one step. Returns false
226
+ * when already on the first step, so the host knows to leave the screen
227
+ * instead — the header's one back chevron serves both (2026-09-18 design: no
228
+ * second back control inside the form).
229
+ */
230
+ export interface UniversalSendHandle {
231
+ back(): boolean
232
+ }
233
+
189
234
  export interface UniversalSendProps {
190
235
  /** A recipient known before the form opened: a peerpay deep link or `?identityKey=`. */
191
236
  initialTarget?: Extract<RecipientTarget, { kind: 'handle' }>
@@ -214,6 +259,8 @@ export interface UniversalSendProps {
214
259
  onNearbySession: (session: Session) => void
215
260
  /** Where the post-payment overlay sends the user. Defaults to `/`. */
216
261
  dismissTo?: DismissTarget
262
+ /** Which of the three steps is on screen — the host names its header by it. */
263
+ onStepChange?: (step: PayStep) => void
217
264
  }
218
265
 
219
266
  /**
@@ -233,24 +280,67 @@ function seedFigure(sats?: number, token?: { assetId: string; baseUnits: number
233
280
  return { text: '', unit: null }
234
281
  }
235
282
 
236
- function UniversalSend({
237
- initialTarget,
238
- initialSats,
239
- initialTokenAmount,
240
- initialNotice,
241
- openScannerOnMount = false,
242
- onNearbySession,
243
- selectedAssetId,
244
- onSelectAsset,
245
- dismissTo = '/'
246
- }: UniversalSendProps) {
283
+ function UniversalSendInner(
284
+ {
285
+ initialTarget,
286
+ initialSats,
287
+ initialTokenAmount,
288
+ initialNotice,
289
+ openScannerOnMount = false,
290
+ onNearbySession,
291
+ selectedAssetId,
292
+ onSelectAsset,
293
+ dismissTo = '/',
294
+ onStepChange
295
+ }: UniversalSendProps,
296
+ ref: React.ForwardedRef<UniversalSendHandle>
297
+ ) {
247
298
  const { t } = useTranslation()
248
299
  const { colors } = useTheme()
249
300
  const StatusBar = loadStatusBar()
301
+ const Ionicons = loadIonicons()
250
302
  const { managers, adminOriginator, storage } = useWalletManagers()
251
303
  const { walletBuilt } = useWalletStatus()
304
+ const { walletUserId, selectedNetwork } = useWallet()
252
305
  const wallet = managers?.permissionsManager || null
253
306
 
307
+ // ── the three-step flow (who / amount / review, 2026-09-18 design) ──────
308
+ // A recipient known before the form opened (a deep link, a scan on the way
309
+ // in) starts on 'amount' — the identity is already decided. Everything
310
+ // else about this form is unchanged; `step` only decides which of the
311
+ // sections below is on screen.
312
+ const [step, setStep] = useState<PayStep>(initialTarget ? 'amount' : 'who')
313
+ // A second deep link while this form is mounted re-adopts the recipient
314
+ // (see useRecipientInput's own initialTarget effect) and must jump the
315
+ // step forward the same way the initial mount does — a link naming a
316
+ // payee is a stronger signal than whatever step the user was on.
317
+ useEffect(() => {
318
+ if (initialTarget) setStep('amount')
319
+ }, [initialTarget?.identityKey])
320
+ const contactsStore = useContactsStore()
321
+ const [contactMatches, setContactMatches] = useState<ContactRow[]>([])
322
+ const [registryMatches, setRegistryMatches] = useState<RegistryProfile[]>([])
323
+ const [registrySearching, setRegistrySearching] = useState(false)
324
+ const [registryError, setRegistryError] = useState(false)
325
+ /**
326
+ * Two strings, not the config object. `getHandleRegistryConfig` builds a
327
+ * fresh `{ domain, url }` on every call, so memoising on the object gives the
328
+ * client a new identity every render, which gives the registry effect below a
329
+ * changed dependency every render — and its own `setState` then schedules the
330
+ * next render. That is an unbreakable loop ("Maximum update depth exceeded")
331
+ * in which the 400 ms debounce is also cleared before it can ever fire.
332
+ */
333
+ const registry = getHandleRegistryConfig(selectedNetwork)
334
+ const registryDomain = registry?.domain
335
+ const registryUrl = registry?.url
336
+ const registryClient = useMemo(
337
+ () =>
338
+ registryDomain && registryUrl
339
+ ? createHandleRegistryClient({ pinned: { domain: registryDomain, url: registryUrl } })
340
+ : null,
341
+ [registryDomain, registryUrl]
342
+ )
343
+
254
344
  // ── the asset axis ──────────────────────────────────────────────────
255
345
  // Every line below is gated on `asset`: with no token held, `balances` is
256
346
  // empty, `asset` is null, the picker renders nothing and this form is
@@ -294,6 +384,12 @@ function UniversalSend({
294
384
  initialNotice ? { type: 'error', message: initialNotice } : null
295
385
  )
296
386
  const [isSending, setIsSending] = useState(false)
387
+ // XR-061: synchronous in-flight latch for handleSend. `isSending` is React
388
+ // state and only takes effect on the next render, so two activations in the
389
+ // same JS turn (double-tap, or two gesture callbacks before the disabled
390
+ // prop reaches the native view) would both pass its checks; this ref is
391
+ // read-and-set before any await.
392
+ const sendingRef = useRef(false)
297
393
  const [sendResult, setSendResult] = useState<{ type: 'success' | 'error'; message: string } | null>(null)
298
394
  /**
299
395
  * The failed-token-send note, kept apart from `sendResult` because it carries
@@ -304,11 +400,20 @@ function UniversalSend({
304
400
  const [sent, setSent] = useState<{
305
401
  amount: number
306
402
  recipient?: string
403
+ /** Set only for a handle/token send — offers "Add to contacts" on the success screen. */
404
+ recipientIdentityKey?: string
307
405
  /** Token mode: the figure in the asset's own units. */
308
406
  amountText?: string
309
407
  /** Whether the issuer has confirmed it yet — never claimed, only reported. */
310
408
  statusNote?: string
311
409
  } | null>(null)
410
+ /** Set once `sent` names a handle recipient who is not already a saved
411
+ * contact — null while that check is pending or once it comes back "already saved". */
412
+ const [offerAddContact, setOfferAddContact] = useState<{
413
+ identityKey: string
414
+ name?: string
415
+ handle?: string
416
+ } | null>(null)
312
417
  const [outbox, setOutbox] = useState<OutboxEntry[]>([])
313
418
  const [retryingId, setRetryingId] = useState<string | null>(null)
314
419
 
@@ -365,6 +470,13 @@ function UniversalSend({
365
470
  * held), otherwise parked until they are — see the effect below `recipient`.
366
471
  */
367
472
  const onPeerPayRequest = (request: PeerPayRequest) => {
473
+ // A request that names money (a link's `sats=`/`amount=`, typed, pasted or
474
+ // scanned) is "amount pre-populated by QR/deep link" whichever way it
475
+ // arrived — so it jumps the same way a deep-linked `initialTarget` does.
476
+ // A bare handle/key with no figure never reaches this function at all
477
+ // (see useRecipientInput's `requestOf`), so Continue still decides step
478
+ // for every ordinary "who" entry.
479
+ setStep('amount')
368
480
  if (request.asset !== undefined) {
369
481
  if (tokensNever) {
370
482
  applyTokenRequest(request, [], { deferred: false })
@@ -393,6 +505,224 @@ function UniversalSend({
393
505
  onNearbySession
394
506
  })
395
507
  const target = recipient.target
508
+
509
+ // Local contacts, searched ahead of the 400ms overlay debounce (instant —
510
+ // this is a local SQLite read) and merged into the same dropdown. Contacts
511
+ // come first; an overlay hit for an identity key already in the merged list
512
+ // is dropped rather than shown twice. An empty query shows every contact as
513
+ // "Recent" (RecipientField's `recentLabel`) rather than nothing.
514
+ useEffect(() => {
515
+ if (!contactsStore || walletUserId === null || recipient.selectedIdentity || target) {
516
+ setContactMatches([])
517
+ return
518
+ }
519
+ let cancelled = false
520
+ void contactsStore.searchContacts(walletUserId, recipient.inputText).then(rows => {
521
+ if (!cancelled) setContactMatches(rows)
522
+ })
523
+ return () => {
524
+ cancelled = true
525
+ }
526
+ }, [contactsStore, walletUserId, recipient.inputText, recipient.selectedIdentity, target])
527
+
528
+ /**
529
+ * The registry tier: people who can be paid by name. Its own timer — the
530
+ * contacts effect above has none, which is right for a local SQLite read and
531
+ * would be one request per keystroke here — and its own notice, so a
532
+ * registry outage never takes the contacts already on screen with it.
533
+ *
534
+ * It never fires for text that already resolved to a key or an address
535
+ * (`classifyRecipientInput`), for fewer than two characters (shorter than
536
+ * the registry's own minimum), with no registry configured, or before the
537
+ * wallet user is known.
538
+ */
539
+ useEffect(() => {
540
+ const query = recipient.inputText.trim()
541
+ const routable =
542
+ !!registryClient &&
543
+ typeof walletUserId === 'number' &&
544
+ !recipient.selectedIdentity &&
545
+ !target &&
546
+ classifyRecipientInput(query).kind === 'search' &&
547
+ query.length >= 2
548
+ if (!routable) {
549
+ // Only here, and only when there is something to clear: an unconditional
550
+ // `setRegistryMatches([])` hands React a new array reference on every
551
+ // run, which it can never bail out of.
552
+ setRegistryMatches(rows => (rows.length === 0 ? rows : []))
553
+ setRegistrySearching(false)
554
+ return
555
+ }
556
+ let cancelled = false
557
+ setRegistrySearching(true)
558
+ const timer = setTimeout(async () => {
559
+ try {
560
+ const rows = await registryClient.search(query)
561
+ if (cancelled) return
562
+ setRegistryMatches(rows)
563
+ setRegistryError(false)
564
+ } catch (error) {
565
+ console.error('Handle registry search error:', error)
566
+ if (cancelled) return
567
+ setRegistryMatches([])
568
+ setRegistryError(true)
569
+ } finally {
570
+ if (!cancelled) setRegistrySearching(false)
571
+ }
572
+ }, REGISTRY_SEARCH_DEBOUNCE_MS)
573
+ return () => {
574
+ cancelled = true
575
+ clearTimeout(timer)
576
+ }
577
+ }, [registryClient, walletUserId, recipient.inputText, recipient.selectedIdentity, target])
578
+
579
+ const mergedSearchResults = useMemo((): RecipientRow[] => {
580
+ const contactIdentities: RecipientRow[] = contactMatches.map(c => ({
581
+ identityKey: c.identityKey,
582
+ name: c.name,
583
+ avatarURL: c.cachedAvatarUrl ?? '',
584
+ abbreviatedKey: abbreviateKey(c.identityKey),
585
+ badgeIconURL: '',
586
+ badgeLabel: '',
587
+ badgeClickURL: '',
588
+ ...(c.cachedHandle ? { secondaryLine: c.cachedHandle } : {})
589
+ }))
590
+ const seen = new Set(contactIdentities.map(c => c.identityKey))
591
+ // Contacts, then the registry, then the overlay. A person the user has
592
+ // already labelled is shown with that label; a registry row states the
593
+ // name the owner published and the handle it belongs to.
594
+ //
595
+ // One key, one row, across the WHOLE list — so `seen` is consulted and
596
+ // added to in the same pass. Filtering first would let two certificates
597
+ // for one subject through together, which the pinned registry cannot
598
+ // produce but a foreign host answering `search` can.
599
+ const registryIdentities: RecipientRow[] = []
600
+ for (const p of registryMatches) {
601
+ if (seen.has(p.identityKey)) continue
602
+ seen.add(p.identityKey)
603
+ // The pinned registry's own certificate is the app's actual vetting —
604
+ // writes only ever go there (handleRegistry/client.ts). A foreign
605
+ // domain's `search` hit is only as trustworthy as that domain's own
606
+ // DNS + TLS (the same level paymail already offers), so it earns a
607
+ // different badge rather than being dressed as "Registered" (misc-p2-14).
608
+ const ownDomain = !!registryClient && p.domain.toLowerCase() === registryClient.domain.toLowerCase()
609
+ registryIdentities.push({
610
+ identityKey: p.identityKey,
611
+ // A display name is the owner's own unvalidated plaintext, and this row
612
+ // is the one place it is drawn ABOVE the handle it belongs to. A name
613
+ // shaped like an address therefore reads as somebody else's
614
+ // `handle@domain` — and it is the name, not the handle, that the field
615
+ // and the review card carry from here on. A name that can be mistaken
616
+ // for an address is no name.
617
+ name: (p.displayName?.includes('@') ? '' : p.displayName) || p.handle,
618
+ avatarURL: '',
619
+ abbreviatedKey: abbreviateKey(p.identityKey),
620
+ badgeIconURL: '',
621
+ badgeLabel: ownDomain
622
+ ? t('pay_trust_handle_attested')
623
+ : t('pay_trust_handle_domain_attested', { domain: p.domain }),
624
+ badgeClickURL: '',
625
+ secondaryLine: p.paymail
626
+ })
627
+ }
628
+ return [
629
+ ...contactIdentities,
630
+ ...registryIdentities,
631
+ ...recipient.searchResults.filter(r => !seen.has(r.identityKey))
632
+ ]
633
+ }, [contactMatches, registryMatches, recipient.searchResults, registryClient, t])
634
+
635
+ /**
636
+ * The handle of the row the user picked, so the success screen's "Save as
637
+ * contact" can carry it into the new contact — held against the KEY it
638
+ * belongs to, not as a bare string.
639
+ *
640
+ * `handleSend` clears the field through the hook's own `clearRecipient`
641
+ * rather than the wrapper below, deliberately, so this survives the send and
642
+ * the overlay can still read it. A bare string would therefore also outlive
643
+ * its owner: pay someone with a handle, then pay a pasted key from the same
644
+ * mounted form, and the second person would be offered for saving with the
645
+ * first person's `handle@domain`.
646
+ */
647
+ const selectedHandleRef = useRef<{ identityKey: string; handle: string } | undefined>(undefined)
648
+ /**
649
+ * The same fact, as state, for the review card — which is the one screen
650
+ * whose whole job is the last check before money moves, and which otherwise
651
+ * draws a name over an abbreviated key and never shows the `handle@domain`
652
+ * being paid at all. State rather than the ref above because the card is
653
+ * rendered, and a ref does not re-render; both rather than one because the
654
+ * ref must outlive the send and this must not survive a new recipient.
655
+ */
656
+ const [pickedHandle, setPickedHandle] = useState<{ identityKey: string; handle: string } | null>(null)
657
+ const onSelectIdentity = (identity: RecipientRow) => {
658
+ const picked = identity.secondaryLine?.includes('@')
659
+ ? { identityKey: identity.identityKey, handle: identity.secondaryLine }
660
+ : undefined
661
+ selectedHandleRef.current = picked
662
+ setPickedHandle(picked ?? null)
663
+ recipient.selectIdentity(identity)
664
+ }
665
+ const onClearRecipient = () => {
666
+ selectedHandleRef.current = undefined
667
+ setPickedHandle(null)
668
+ recipient.clearRecipient()
669
+ }
670
+ // Whether the resolved recipient is already a saved contact — the review
671
+ // step's trust tag names this before "registered"/"unverified".
672
+ const [targetIsContact, setTargetIsContact] = useState(false)
673
+ useEffect(() => {
674
+ if (!contactsStore || walletUserId === null || target?.kind !== 'handle') {
675
+ setTargetIsContact(false)
676
+ return
677
+ }
678
+ let cancelled = false
679
+ void contactsStore.getContact(walletUserId, target.identityKey).then(c => {
680
+ if (!cancelled) setTargetIsContact(!!c)
681
+ })
682
+ return () => {
683
+ cancelled = true
684
+ }
685
+ }, [contactsStore, walletUserId, target])
686
+
687
+ // The success screen's "Add to contacts" offer: only for a handle send, and
688
+ // only once confirmed absent from contacts (checked fresh here rather than
689
+ // reusing `targetIsContact` — `target` may already be cleared by the time
690
+ // this runs, and a check against the stale ONE this send actually used is
691
+ // what the button must reflect).
692
+ useEffect(() => {
693
+ setOfferAddContact(null)
694
+ if (!sent?.recipientIdentityKey || !contactsStore || walletUserId === null) return
695
+ let cancelled = false
696
+ const identityKey = sent.recipientIdentityKey
697
+ void contactsStore.getContact(walletUserId, identityKey).then(c => {
698
+ if (cancelled || c) return
699
+ // Only the handle of the person actually paid: see selectedHandleRef.
700
+ const picked = selectedHandleRef.current
701
+ setOfferAddContact({
702
+ identityKey,
703
+ name: sent.recipient,
704
+ ...(picked?.identityKey === identityKey ? { handle: picked.handle } : {})
705
+ })
706
+ })
707
+ return () => {
708
+ cancelled = true
709
+ }
710
+ }, [sent, contactsStore, walletUserId])
711
+
712
+ const onAddContact = useCallback(() => {
713
+ if (!offerAddContact) return
714
+ setSent(null)
715
+ loadExpoRouter().router.push({
716
+ pathname: '/contact/add',
717
+ params: {
718
+ identityKey: offerAddContact.identityKey,
719
+ name: offerAddContact.name ?? '',
720
+ handle: offerAddContact.handle ?? '',
721
+ source: 'pay'
722
+ }
723
+ } as never)
724
+ }, [offerAddContact])
725
+
396
726
  /**
397
727
  * A token link that arrived before the holdings were known. `null` balances
398
728
  * mean UNKNOWN, never "holds nothing" (useMandala's contract), and a
@@ -489,11 +819,14 @@ function UniversalSend({
489
819
  const client = peerPayClient
490
820
  if (!client || !storage) return
491
821
  try {
492
- await listPendingResendRequests({ client, storage })
822
+ // XR-051: without this, an unauthenticated resend_request could not be
823
+ // told apart from a legitimate one and would be surfaced (and kept
824
+ // being surfaced) as pending forever.
825
+ await listPendingResendRequests({ client, storage, listPeerPayAction: makeListPeerPayAction(wallet, adminOriginator) })
493
826
  } catch {
494
827
  // Home owns the unanswered-resend banner; a failed poll here is retryable.
495
828
  }
496
- }, [peerPayClient, storage])
829
+ }, [peerPayClient, storage, wallet, adminOriginator])
497
830
 
498
831
  useEffect(() => {
499
832
  void pollResendRequests()
@@ -538,6 +871,7 @@ function UniversalSend({
538
871
  setSent({
539
872
  amount: paidSats,
540
873
  recipient: recipient.selectedIdentity?.name,
874
+ recipientIdentityKey: to.identityKey,
541
875
  // The handle rail always drops the payment in the recipient's message
542
876
  // box rather than handing it over in person — worth saying explicitly
543
877
  // here, since it is the one thing an in-person (Nearby) payer never
@@ -571,7 +905,7 @@ function UniversalSend({
571
905
  * allowed to promise "nothing was sent".
572
906
  */
573
907
  const sendToken = useCallback(
574
- async (to: Extract<RecipientTarget, { kind: 'handle' }>, baseUnits: number) => {
908
+ async (to: Extract<RecipientTarget, { kind: 'handle' }>, baseUnits: number): Promise<boolean> => {
575
909
  const runtime = mandala.runtime
576
910
  if (!runtime || !asset) throw new Error(t('wallet_not_ready'))
577
911
  const ctx = {
@@ -593,11 +927,15 @@ function UniversalSend({
593
927
  // that could not sign) and is the only place it survives.
594
928
  console.warn('[pay] token send failed:', result.kind, result.message ?? (result as { code?: string }).code)
595
929
  setTokenFailure(tokenSendCopy(result, ctx))
596
- return
930
+ // A refusal must leave the review step exactly as it is — the banner
931
+ // that explains it lives there, and stepping back to "who" (as a
932
+ // successful send does) would carry the user straight past it.
933
+ return false
597
934
  }
598
935
  setSent({
599
936
  amount: 0,
600
937
  recipient: recipient.selectedIdentity?.name,
938
+ recipientIdentityKey: to.identityKey,
601
939
  // Never falls back to the satoshi renderer: a token figure it could not
602
940
  // format would print as satoshis, which is a wrong number rather than a
603
941
  // missing one.
@@ -624,68 +962,84 @@ function UniversalSend({
624
962
  : t('token_sent_settling_unnamed', { issuer })
625
963
  })
626
964
  mandala.refresh()
965
+ return true
627
966
  },
628
967
  [mandala, asset, issuer, recipient.selectedIdentity, note, t]
629
968
  )
630
969
 
631
970
  const handleSend = useCallback(async () => {
632
- if (!target) return
633
- // Guard before any side effect: a wallet that is not ready must leave the
634
- // form exactly as typed, with a banner, not a cleared field and silence.
635
- // On the token path the runtime IS the wallet — it holds its own manager,
636
- // storage and journal — so that is what has to be ready.
637
- if (asset ? !mandala.runtime : !wallet || !storage) {
638
- flashResult({ type: 'error', message: t('wallet_not_ready') })
639
- return
640
- }
641
- // The same integer either way — satoshis on the BSV rail, base units of the
642
- // asset on the token rail. The field emits whole units in both modes.
643
- const amount = Math.round(Number(sendAmount))
644
- if (!Number.isFinite(amount) || amount <= 0) {
645
- flashResult({ type: 'error', message: t('enter_valid_amount') })
646
- return
647
- }
648
- haptics.confirm()
649
- setIsSending(true)
650
- setTokenFailure(null)
971
+ // XR-061: isSending is React state and does not commit synchronously, so
972
+ // two activations landing in the same JS turn (a double-tap, or two
973
+ // gesture callbacks firing before the disabled prop reaches the native
974
+ // view) would both pass every guard below and independently reach a
975
+ // value-moving rail call. This ref is checked and set synchronously,
976
+ // before any await, so the second activation returns immediately; it is
977
+ // released in the same `finally` that clears `isSending`.
978
+ if (sendingRef.current) return
979
+ sendingRef.current = true
651
980
  try {
652
- if (asset) {
653
- // D4: a token has no address rail, and `canSend` has already refused
654
- // one. This is the second gate, because the first is a render.
655
- if (target.kind !== 'handle') return
656
- await sendToken(target, amount)
657
- } else if (target.kind === 'handle') await sendHandle(target, amount)
658
- else await sendAddress(target, amount)
659
- setFigure(current => ({ ...current, text: '' }))
660
- setNote('')
661
- recipient.clearRecipient()
662
- } catch (error: any) {
663
- if (await handleWalletCheck(error)) return
664
- if (asset) {
665
- console.warn('[mandala] token send threw:', error)
666
- // A throw out of the token path is NOT a refusal: the overlay may have
667
- // admitted the transaction and lost the response, so the copy claims
668
- // nothing and offers a balance check rather than a retry.
669
- setTokenFailure(
670
- tokenThrowCopy(error, {
671
- ticker: asset.ticker,
672
- issuer: asset.issuerName,
673
- issuerFallback: t('token_issuer_fallback')
674
- })
675
- )
981
+ if (!target) return
982
+ // Guard before any side effect: a wallet that is not ready must leave the
983
+ // form exactly as typed, with a banner, not a cleared field and silence.
984
+ // On the token path the runtime IS the wallet — it holds its own manager,
985
+ // storage and journal — so that is what has to be ready.
986
+ if (asset ? !mandala.runtime : !wallet || !storage) {
987
+ flashResult({ type: 'error', message: t('wallet_not_ready') })
988
+ return
989
+ }
990
+ // The same integer either way — satoshis on the BSV rail, base units of the
991
+ // asset on the token rail. The field emits whole units in both modes.
992
+ const amount = Math.round(Number(sendAmount))
993
+ if (!Number.isFinite(amount) || amount <= 0) {
994
+ flashResult({ type: 'error', message: t('enter_valid_amount') })
676
995
  return
677
996
  }
678
- const message =
679
- error instanceof RangeError
680
- ? t('enter_valid_amount')
681
- : isMessageBoxNetworkError(error)
682
- ? t('message_box_unreachable')
683
- : error?.message || t('unknown_error')
684
- flashResult({ type: 'error', message })
685
- // A failed handle send leaves its entry 'unsent' and offered for retry below.
686
- if (target.kind === 'handle') await loadOutbox()
997
+ haptics.confirm()
998
+ setIsSending(true)
999
+ setTokenFailure(null)
1000
+ try {
1001
+ if (asset) {
1002
+ // D4: a token has no address rail, and `canSend` has already refused
1003
+ // one. This is the second gate, because the first is a render.
1004
+ if (target.kind !== 'handle') return
1005
+ const sent = await sendToken(target, amount)
1006
+ if (!sent) return
1007
+ } else if (target.kind === 'handle') await sendHandle(target, amount)
1008
+ else await sendAddress(target, amount)
1009
+ setFigure(current => ({ ...current, text: '' }))
1010
+ setNote('')
1011
+ recipient.clearRecipient()
1012
+ setStep('who')
1013
+ } catch (error: any) {
1014
+ if (await handleWalletCheck(error)) return
1015
+ if (asset) {
1016
+ console.warn('[mandala] token send threw:', error)
1017
+ // A throw out of the token path is NOT a refusal: the overlay may have
1018
+ // admitted the transaction and lost the response, so the copy claims
1019
+ // nothing and offers a balance check rather than a retry.
1020
+ setTokenFailure(
1021
+ tokenThrowCopy(error, {
1022
+ ticker: asset.ticker,
1023
+ issuer: asset.issuerName,
1024
+ issuerFallback: t('token_issuer_fallback')
1025
+ })
1026
+ )
1027
+ return
1028
+ }
1029
+ const message =
1030
+ error instanceof RangeError
1031
+ ? t('enter_valid_amount')
1032
+ : isMessageBoxNetworkError(error)
1033
+ ? t('message_box_unreachable')
1034
+ : error?.message || t('unknown_error')
1035
+ flashResult({ type: 'error', message })
1036
+ // A failed handle send leaves its entry 'unsent' and offered for retry below.
1037
+ if (target.kind === 'handle') await loadOutbox()
1038
+ } finally {
1039
+ setIsSending(false)
1040
+ }
687
1041
  } finally {
688
- setIsSending(false)
1042
+ sendingRef.current = false
689
1043
  }
690
1044
  }, [
691
1045
  target,
@@ -723,7 +1077,7 @@ function UniversalSend({
723
1077
  setRetryingId(entry.id)
724
1078
  try {
725
1079
  await retryDelivery({ wallet: wallet as any, adminOriginator, client, storage, entry })
726
- setSent({ amount: entry.token.amount })
1080
+ setSent({ amount: entry.token.amount, recipientIdentityKey: entry.recipient })
727
1081
  } catch (e: any) {
728
1082
  if (await handleWalletCheck(e)) return
729
1083
  const reason = isMessageBoxNetworkError(e) ? t('message_box_unreachable') : e?.message || t('unknown_error')
@@ -795,6 +1149,17 @@ function UniversalSend({
795
1149
  const amountOk = Number(sendAmount) > 0
796
1150
  const isHandle = target?.kind === 'handle'
797
1151
  const isAddress = target?.kind === 'address'
1152
+ /**
1153
+ * misc-p2-03: the address rail pays with a P2PKH lock regardless of which
1154
+ * network's version byte the pasted/scanned address carries — the same key
1155
+ * redeems on either chain, so this is a warning, not a refusal. Recomputed
1156
+ * from the address itself rather than threaded through `target`, so the
1157
+ * check stays independent of how the recipient was resolved (typed, scanned
1158
+ * or picked from a search result).
1159
+ */
1160
+ const detectedAddressNetwork = target?.kind === 'address' ? addressNetwork(target.address) : undefined
1161
+ const addressNetworkMismatch =
1162
+ !!detectedAddressNetwork && detectedAddressNetwork !== (selectedNetwork === 'main' ? 'main' : 'test')
798
1163
  // A stuck handle payment blocks new HANDLE sends: every attempt while the box
799
1164
  // is unreachable would mint another noSend action and another stuck entry.
800
1165
  // Address sends never touch the box, so they are not held hostage by it.
@@ -902,159 +1267,360 @@ function UniversalSend({
902
1267
  : null
903
1268
  : null
904
1269
 
905
- const ctaLabel =
906
- asset && amountOk
907
- ? t('pay_asset_cta', {
908
- amount: formatTokenAmount(baseUnits, asset.decimals) ?? '',
909
- ticker: asset.ticker
910
- })
1270
+ const backStep = useCallback(() => {
1271
+ setStep(prev => (prev === 'review' ? 'amount' : 'who'))
1272
+ }, [])
1273
+ useImperativeHandle(
1274
+ ref,
1275
+ () => ({
1276
+ back: () => {
1277
+ if (step === 'who') return false
1278
+ backStep()
1279
+ return true
1280
+ }
1281
+ }),
1282
+ [step, backStep]
1283
+ )
1284
+ // Taken off `recipient` here rather than called through it below: calling it
1285
+ // as a method would make the whole (rebuilt every render) `recipient` object
1286
+ // a dependency of the effect, and an effect that reran every render would
1287
+ // clear the overlay's own search notice the instant it was raised.
1288
+ const clearSearchError = recipient.clearSearchError
1289
+ useEffect(() => {
1290
+ onStepChange?.(step)
1291
+ // Neither search notice belongs on the amount or review screen: both are
1292
+ // about a recipient field that is no longer on screen.
1293
+ setRegistryError(false)
1294
+ clearSearchError()
1295
+ }, [step, onStepChange, clearSearchError])
1296
+
1297
+ // ── the review card's facts ──────────────────────────────────────────
1298
+ // Once money is moving, the figure is ALWAYS the asset that actually moves
1299
+ // (BSV or the token), never the display currency (2026-09-17 ruling):
1300
+ // "12.00 USD" on a BSV send reads as a stablecoin.
1301
+ const sendSats = Math.round(Number(sendAmount)) || 0
1302
+ const reviewAmount = asset
1303
+ ? { value: formatTokenAmount(baseUnits, asset.decimals) ?? '', unit: asset.ticker }
1304
+ : { value: formatSatoshisAsBsvDecimal(sendSats), unit: 'BSV' }
1305
+ // XR-044: the last on-screen chance to catch a look-alike asset before Send
1306
+ // — issuerName is unverified, but assetId cannot collide, so the review
1307
+ // step shows both, not only the ticker/label the amount is already keyed
1308
+ // to. Absent for a BSV send: there is no issuer/assetId to show.
1309
+ const reviewAssetIdentity = asset ? [asset.issuerName, shortAssetId(asset.assetId)].filter(Boolean).join(' · ') : ''
1310
+ const reviewPrimary =
1311
+ recipient.selectedIdentity?.name ||
1312
+ (target?.kind === 'handle' ? abbreviateKey(target.identityKey) : target?.kind === 'address' ? target.address : '')
1313
+ // The handle the picked row carried, when it is still the row being paid —
1314
+ // the name above it may be anything its owner published, this is the address
1315
+ // the money is going to. An abbreviated key only when there is no handle.
1316
+ const reviewSecondary =
1317
+ recipient.selectedIdentity?.name && target?.kind === 'handle'
1318
+ ? pickedHandle?.identityKey === target.identityKey
1319
+ ? pickedHandle.handle
1320
+ : abbreviateKey(target.identityKey)
911
1321
  : undefined
1322
+ const reviewTrust = targetIsContact
1323
+ ? { icon: 'person-circle-outline', color: colors.textSecondary, text: t('pay_trust_contact') }
1324
+ : recipient.selectedIdentity
1325
+ ? { icon: 'shield-checkmark-outline', color: colors.textSecondary, text: t('pay_trust_handle_attested') }
1326
+ : { icon: 'alert-circle-outline', color: colors.warning, text: t('pay_trust_unverified') }
1327
+ const showNoteRow = isHandle || (isAddress && !asset)
1328
+ // XR-053: a `peerpay:` link's `url` extension silently overrides normal
1329
+ // recipient-host resolution (the overlay/advertisement lookup) with no
1330
+ // binding to the recipient's identity. Surfacing the resolved host on the
1331
+ // last screen before Send is the local, backwards-compatible hardening —
1332
+ // the payer can catch a substituted/unexpected host before committing;
1333
+ // full closure (a recipient-signed delivery receipt) is a wire-protocol
1334
+ // change out of scope here.
1335
+ const linkHost = target?.kind === 'handle' ? target.messageBoxUrl : undefined
1336
+ const showHostRow = !!linkHost
912
1337
 
913
1338
  return (
914
1339
  <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
1340
+ <StepBar step={step} />
915
1341
  {notice && <ResultBanner result={notice} onDismiss={() => setNotice(null)} colors={colors} />}
916
- {recipient.searchError && (
1342
+ {/* One notice for both remote tiers. Offline they fail on the same
1343
+ keystroke, and two banners carrying the identical sentence read as the
1344
+ error re-appearing when the first is dismissed. */}
1345
+ {(recipient.searchError || registryError) && (
917
1346
  <ResultBanner
918
1347
  result={{ type: 'error', message: t('identity_search_unavailable') }}
919
- onDismiss={recipient.clearSearchError}
1348
+ onDismiss={() => {
1349
+ recipient.clearSearchError()
1350
+ setRegistryError(false)
1351
+ }}
920
1352
  colors={colors}
921
1353
  />
922
1354
  )}
923
1355
 
924
- <PayField labelKey="recipient">
925
- <RecipientField
926
- selectedIdentity={recipient.selectedIdentity}
927
- inputText={recipient.inputText}
928
- target={recipient.target}
929
- inlineError={recipient.inlineError}
930
- isSearching={recipient.isSearching}
931
- searchResults={recipient.searchResults}
932
- colors={colors}
933
- t={t}
934
- onChangeText={recipient.onChangeText}
935
- onSelectIdentity={recipient.selectIdentity}
936
- onClear={recipient.clearRecipient}
937
- onOpenScanner={recipient.openScanner}
938
- assetTicker={asset?.ticker}
939
- statusOverride={
940
- recipientRefusal && !tokenAddressRefused
941
- ? { text: recipientRefusal, tone: 'warning' }
942
- : recipientRegistryRefused
943
- ? {
944
- text: t(
945
- assetStatus?.accessMode === 'denylist' ? 'pay_asset_recipient_blocked' : 'pay_asset_recipient_unregistered',
946
- { issuer, ticker: asset?.ticker }
947
- ),
948
- tone: 'warning'
949
- }
950
- : undefined
951
- }
952
- />
953
- </PayField>
954
-
955
- {/* No "Paying with" picker here (design 1b, 2026-09-15): the coin is
956
- chosen once, on Home's switcher, and arrives as `selectedAssetId`.
957
- It still decides the unit of the figure, the available balance under
958
- it, and which recipient shapes are legal for a token (D4, above) —
959
- and a peerpay link naming an asset still moves it. */}
960
-
961
- <PayAmountField
962
- value={sendAmount}
963
- onChangeText={setSendAmount}
964
- asset={asset ? { ticker: asset.ticker, decimals: asset.decimals } : undefined}
965
- maxValue={holding ? String(holding.baseUnits) : undefined}
966
- availableText={
967
- holding ? (formatTokenAmount(holding.baseUnits, holding.asset.decimals) ?? undefined) : undefined
968
- }
969
- />
970
-
971
- {(isHandle || (isAddress && !asset)) && (
972
- <PayField labelKey="note">
973
- <TextInput
974
- value={note}
975
- onChangeText={setNote}
976
- placeholder={t('note_placeholder')}
977
- placeholderTextColor={colors.textQuaternary}
978
- maxLength={280}
979
- style={[
980
- styles.noteInput,
981
- { backgroundColor: colors.backgroundSecondary, borderColor: colors.separator, color: colors.textPrimary }
982
- ]}
983
- />
984
- </PayField>
985
- )}
1356
+ {step === 'who' && (
1357
+ <>
1358
+ <PayField labelKey="pay_review_to">
1359
+ <RecipientField
1360
+ selectedIdentity={recipient.selectedIdentity}
1361
+ inputText={recipient.inputText}
1362
+ target={recipient.target}
1363
+ inlineError={recipient.inlineError}
1364
+ isSearching={recipient.isSearching || registrySearching}
1365
+ searchResults={mergedSearchResults}
1366
+ colors={colors}
1367
+ t={t}
1368
+ onChangeText={recipient.onChangeText}
1369
+ onSelectIdentity={onSelectIdentity}
1370
+ onClear={onClearRecipient}
1371
+ onOpenScanner={recipient.openScanner}
1372
+ assetTicker={asset?.ticker}
1373
+ recentLabel={t('contacts_recent')}
1374
+ statusOverride={
1375
+ recipientRefusal && !tokenAddressRefused
1376
+ ? { text: recipientRefusal, tone: 'warning' }
1377
+ : recipientRegistryRefused
1378
+ ? {
1379
+ text: t(
1380
+ assetStatus?.accessMode === 'denylist'
1381
+ ? 'pay_asset_recipient_blocked'
1382
+ : 'pay_asset_recipient_unregistered',
1383
+ { issuer, ticker: asset?.ticker }
1384
+ ),
1385
+ tone: 'warning'
1386
+ }
1387
+ : undefined
1388
+ }
1389
+ />
1390
+ </PayField>
986
1391
 
987
- {/* Load-bearing for an address: this rail cannot notify the payee. Nothing
988
- for a handle, and nothing at all in token mode, where an address is
989
- refused rather than warned about. */}
990
- {isAddress && !asset && <ConsequenceNote textKey={CONSEQUENCE_KEYS.address} />}
991
-
992
- {tokenNote && (
993
- <ConsequenceNote
994
- textKey={tokenNote.key}
995
- values={tokenNote.values}
996
- text={tokenNote.text}
997
- action={
998
- tokenNote.action === 'get-bsv'
999
- ? {
1000
- label: t('pay_asset_get_bsv'),
1001
- onPress: () => loadExpoRouter().router.push('/pay?direction=get' as never)
1002
- }
1003
- : undefined
1004
- }
1005
- />
1006
- )}
1392
+ {/* No "Paying with" picker here (design 1b, 2026-09-15): the coin is
1393
+ chosen once, on Home's switcher, and arrives as `selectedAssetId`. */}
1007
1394
 
1008
- {isHandle && !isConfigured && !asset && (
1009
- <Text style={[styles.consequence, { color: colors.textSecondary }]}>{t('message_box_off_hint')}</Text>
1010
- )}
1011
- {handleFormValid && handleBlockedByOutbox && !asset && (
1012
- <Text style={[styles.consequence, { color: colors.textSecondary }]}>{t('finish_or_cancel_outgoing')}</Text>
1395
+ {target ? (
1396
+ <PayCta
1397
+ onPress={() => setStep('amount')}
1398
+ disabled={false}
1399
+ busy={false}
1400
+ label={t('pay_step_continue')}
1401
+ icon="arrow-forward"
1402
+ />
1403
+ ) : (
1404
+ <PressableScale
1405
+ onPress={() => loadExpoRouter().router.push('/contacts' as never)}
1406
+ haptic="tap"
1407
+ style={[
1408
+ styles.outlineBtn,
1409
+ { backgroundColor: colors.surfaceRaised, borderColor: colors.surfaceRaisedBorder }
1410
+ ]}
1411
+ accessibilityRole="button"
1412
+ >
1413
+ <Ionicons name="people-outline" size={18} color={colors.textPrimary} />
1414
+ <Text style={[styles.outlineBtnText, { color: colors.textPrimary }]}>{t('pay_step_contacts')}</Text>
1415
+ </PressableScale>
1416
+ )}
1417
+
1418
+ {outbox.length > 0 && (
1419
+ <OutgoingSection
1420
+ entries={outbox}
1421
+ retryingId={retryingId}
1422
+ colors={colors}
1423
+ t={t}
1424
+ onRetry={handleRetry}
1425
+ onCancel={handleCancel}
1426
+ />
1427
+ )}
1428
+ </>
1013
1429
  )}
1014
1430
 
1015
- <PayCta onPress={handleSend} disabled={!canSend} busy={isSending} label={ctaLabel} />
1431
+ {step === 'amount' && (
1432
+ <>
1433
+ <PayAmountField
1434
+ value={sendAmount}
1435
+ onChangeText={setSendAmount}
1436
+ asset={asset ? { ticker: asset.ticker, decimals: asset.decimals } : undefined}
1437
+ maxValue={holding ? String(holding.baseUnits) : undefined}
1438
+ availableText={
1439
+ holding ? (formatTokenAmount(holding.baseUnits, holding.asset.decimals) ?? undefined) : undefined
1440
+ }
1441
+ />
1016
1442
 
1017
- {/* A failed token send, in the app's own failure channel: error tone,
1018
- dismissible, and carrying at most one affordance. "Check again"
1019
- refreshes the balance rather than re-sending, because a retry after a
1020
- lost response builds a second spend of the same coins. */}
1021
- {tokenFailure && (
1022
- <ResultBanner
1023
- result={{ type: 'error', message: t(tokenFailure.key, tokenFailure.values) }}
1024
- onDismiss={() => setTokenFailure(null)}
1025
- colors={colors}
1026
- action={
1027
- tokenFailure.action === 'check-again'
1028
- ? {
1029
- label: t('token_err_check_again'),
1030
- onPress: () => {
1031
- mandala.refresh()
1032
- setTokenFailure(null)
1033
- }
1034
- }
1035
- : tokenFailure.action === 'get-bsv'
1036
- ? {
1037
- label: t('pay_asset_get_bsv'),
1038
- onPress: () => loadExpoRouter().router.push('/pay?direction=get' as never)
1039
- }
1040
- : undefined
1041
- }
1042
- />
1443
+ <PayCta
1444
+ onPress={() => setStep('review')}
1445
+ disabled={!amountOk}
1446
+ busy={false}
1447
+ label={t('pay_step_continue')}
1448
+ icon="arrow-forward"
1449
+ />
1450
+ </>
1043
1451
  )}
1044
1452
 
1045
- {sendResult && <ResultBanner result={sendResult} onDismiss={() => setSendResult(null)} colors={colors} />}
1453
+ {step === 'review' && target && (
1454
+ <>
1455
+ <View
1456
+ style={[styles.reviewCard, { backgroundColor: colors.backgroundElevated, borderColor: colors.separator }]}
1457
+ >
1458
+ <View style={[styles.reviewRow, { borderBottomColor: colors.separator }]}>
1459
+ <Text style={[styles.reviewLabel, { color: colors.textTertiary }]}>{t('pay_review_to')}</Text>
1460
+ {target.kind === 'handle' ? (
1461
+ <ContactSigil
1462
+ identityKey={target.identityKey}
1463
+ avatarUrl={recipient.selectedIdentity?.avatarURL || undefined}
1464
+ size={32}
1465
+ radius={16}
1466
+ />
1467
+ ) : (
1468
+ <View style={[styles.reviewAddressIcon, { backgroundColor: colors.fillTertiary }]}>
1469
+ <Ionicons name="wallet-outline" size={16} color={colors.textSecondary} />
1470
+ </View>
1471
+ )}
1472
+ <View style={styles.reviewToText}>
1473
+ <View style={styles.reviewNameRow}>
1474
+ <Text style={[styles.reviewName, { color: colors.textPrimary }]} numberOfLines={1}>
1475
+ {reviewPrimary}
1476
+ </Text>
1477
+ {!!reviewSecondary && (
1478
+ <Text
1479
+ style={[styles.reviewNameSub, { color: colors.textSecondary }]}
1480
+ numberOfLines={1}
1481
+ ellipsizeMode="middle"
1482
+ >
1483
+ {reviewSecondary}
1484
+ </Text>
1485
+ )}
1486
+ </View>
1487
+ {target.kind === 'handle' && (
1488
+ <View style={styles.reviewTrustRow}>
1489
+ <Ionicons name={reviewTrust.icon as never} size={12} color={reviewTrust.color} />
1490
+ <Text style={[styles.reviewTrust, { color: reviewTrust.color }]} numberOfLines={1}>
1491
+ {reviewTrust.text}
1492
+ </Text>
1493
+ </View>
1494
+ )}
1495
+ </View>
1496
+ </View>
1046
1497
 
1047
- {outbox.length > 0 && (
1048
- <OutgoingSection
1049
- entries={outbox}
1050
- retryingId={retryingId}
1051
- colors={colors}
1052
- t={t}
1053
- onRetry={handleRetry}
1054
- onCancel={handleCancel}
1055
- />
1498
+ <View
1499
+ style={[
1500
+ styles.reviewRow,
1501
+ !showNoteRow && !showHostRow && styles.reviewRowLast,
1502
+ { borderBottomColor: colors.separator }
1503
+ ]}
1504
+ >
1505
+ <Text style={[styles.reviewLabel, { color: colors.textTertiary }]}>{t('pay_review_amount')}</Text>
1506
+ <View style={styles.reviewAmountBlock}>
1507
+ {/* No adjustsFontSizeToFit / numberOfLines: iOS's shrink floor is a fixed 4pt and in this
1508
+ flex row it collapsed the amount to illegible. A long amount wraps instead, so no digit
1509
+ is ever hidden on the screen that confirms it. */}
1510
+ <Text
1511
+ style={[styles.reviewAmount, { color: colors.textPrimary }]}
1512
+ accessibilityLabel={[reviewAmount.value, reviewAmount.unit, reviewAssetIdentity]
1513
+ .filter(Boolean)
1514
+ .join(' ')}
1515
+ >
1516
+ {reviewAmount.value}{' '}
1517
+ <Text style={[styles.reviewUnit, { color: colors.textSecondary }]}>{reviewAmount.unit}</Text>
1518
+ </Text>
1519
+ {!!reviewAssetIdentity && (
1520
+ <Text style={[styles.reviewAssetIdentity, { color: colors.textTertiary }]} numberOfLines={1}>
1521
+ {reviewAssetIdentity}
1522
+ </Text>
1523
+ )}
1524
+ </View>
1525
+ </View>
1526
+
1527
+ {/* A link-named host is never silent (XR-053): the review screen is the
1528
+ last stop before Send, and Send is the only confirmation this
1529
+ narrow fix adds — no separate dialog to build or maintain. */}
1530
+ {showHostRow && (
1531
+ <View
1532
+ style={[
1533
+ styles.reviewRow,
1534
+ !showNoteRow && styles.reviewRowLast,
1535
+ { borderBottomColor: colors.separator }
1536
+ ]}
1537
+ >
1538
+ <Ionicons name="alert-circle-outline" size={16} color={colors.warning} />
1539
+ <Text style={[styles.reviewHostText, { color: colors.warning }]} numberOfLines={2}>
1540
+ {t('pay_review_delivery_host')} <Text style={{ fontWeight: '600' }}>{linkHost}</Text>
1541
+ </Text>
1542
+ </View>
1543
+ )}
1544
+
1545
+ {showNoteRow && (
1546
+ <View style={[styles.reviewRow, styles.reviewRowLast]}>
1547
+ <Text style={[styles.reviewLabel, { color: colors.textTertiary }]}>{t('pay_review_note')}</Text>
1548
+ <TextInput
1549
+ value={note}
1550
+ onChangeText={setNote}
1551
+ placeholder={t('pay_review_note_edit')}
1552
+ placeholderTextColor={colors.textQuaternary}
1553
+ maxLength={280}
1554
+ style={[styles.reviewNoteInput, { color: colors.textPrimary }]}
1555
+ />
1556
+ <Ionicons name="pencil-outline" size={16} color={colors.textTertiary} />
1557
+ </View>
1558
+ )}
1559
+ </View>
1560
+
1561
+ {/* Load-bearing for an address: this rail cannot notify the payee. Nothing
1562
+ for a handle, and nothing at all in token mode, where an address is
1563
+ refused rather than warned about. */}
1564
+ {isAddress && !asset && <ConsequenceNote textKey={CONSEQUENCE_KEYS.address} />}
1565
+ {isAddress && !asset && addressNetworkMismatch && <ConsequenceNote textKey="pay_address_network_mismatch" />}
1566
+
1567
+ {tokenNote && (
1568
+ <ConsequenceNote
1569
+ textKey={tokenNote.key}
1570
+ values={tokenNote.values}
1571
+ text={tokenNote.text}
1572
+ action={
1573
+ tokenNote.action === 'get-bsv'
1574
+ ? {
1575
+ label: t('pay_asset_get_bsv'),
1576
+ onPress: () => loadExpoRouter().router.push('/pay?direction=get' as never)
1577
+ }
1578
+ : undefined
1579
+ }
1580
+ />
1581
+ )}
1582
+
1583
+ {isHandle && !isConfigured && !asset && (
1584
+ <Text style={[styles.consequence, { color: colors.textSecondary }]}>{t('message_box_off_hint')}</Text>
1585
+ )}
1586
+ {handleFormValid && handleBlockedByOutbox && !asset && (
1587
+ <Text style={[styles.consequence, { color: colors.textSecondary }]}>{t('finish_or_cancel_outgoing')}</Text>
1588
+ )}
1589
+
1590
+ <PayCta onPress={handleSend} disabled={!canSend} busy={isSending} labelKey="send" />
1591
+
1592
+ {/* A failed token send, in the app's own failure channel: error tone,
1593
+ dismissible, and carrying at most one affordance. "Check again"
1594
+ refreshes the balance rather than re-sending, because a retry after a
1595
+ lost response builds a second spend of the same coins. */}
1596
+ {tokenFailure && (
1597
+ <ResultBanner
1598
+ result={{ type: 'error', message: t(tokenFailure.key, tokenFailure.values) }}
1599
+ onDismiss={() => setTokenFailure(null)}
1600
+ colors={colors}
1601
+ action={
1602
+ tokenFailure.action === 'check-again'
1603
+ ? {
1604
+ label: t('token_err_check_again'),
1605
+ onPress: () => {
1606
+ mandala.refresh()
1607
+ setTokenFailure(null)
1608
+ }
1609
+ }
1610
+ : tokenFailure.action === 'get-bsv'
1611
+ ? {
1612
+ label: t('pay_asset_get_bsv'),
1613
+ onPress: () => loadExpoRouter().router.push('/pay?direction=get' as never)
1614
+ }
1615
+ : undefined
1616
+ }
1617
+ />
1618
+ )}
1619
+ </>
1056
1620
  )}
1057
1621
 
1622
+ {sendResult && <ResultBanner result={sendResult} onDismiss={() => setSendResult(null)} colors={colors} />}
1623
+
1058
1624
  <Modal
1059
1625
  visible={recipient.scannerVisible}
1060
1626
  animationType="slide"
@@ -1077,6 +1643,7 @@ function UniversalSend({
1077
1643
  amountText={sent.amountText}
1078
1644
  statusNote={sent.statusNote}
1079
1645
  recipientName={sent.recipient}
1646
+ onAddContact={offerAddContact ? onAddContact : undefined}
1080
1647
  onDismiss={() => setSent(null)}
1081
1648
  dismissTo={dismissTo}
1082
1649
  />
@@ -1096,6 +1663,59 @@ const styles = StyleSheet.create({
1096
1663
  marginBottom: spacing.lg
1097
1664
  },
1098
1665
 
1666
+ // Step 1's quiet second door: Contacts, on the chrome surface.
1667
+ outlineBtn: {
1668
+ flexDirection: 'row',
1669
+ alignItems: 'center',
1670
+ justifyContent: 'center',
1671
+ gap: spacing.sm,
1672
+ minHeight: 48,
1673
+ borderWidth: StyleSheet.hairlineWidth,
1674
+ borderRadius: radii.md,
1675
+ paddingVertical: spacing.md
1676
+ },
1677
+ outlineBtnText: { ...typography.subhead, fontWeight: '600' },
1678
+
1679
+ // Review card (step "review"): label-left rows, hairlines between them.
1680
+ reviewCard: {
1681
+ borderRadius: radii.lg,
1682
+ borderWidth: StyleSheet.hairlineWidth,
1683
+ marginBottom: spacing.lg,
1684
+ overflow: 'hidden'
1685
+ },
1686
+ reviewRow: {
1687
+ flexDirection: 'row',
1688
+ alignItems: 'center',
1689
+ gap: spacing.md,
1690
+ minHeight: 56,
1691
+ paddingVertical: spacing.md,
1692
+ paddingHorizontal: spacing.lg,
1693
+ borderBottomWidth: StyleSheet.hairlineWidth
1694
+ },
1695
+ reviewRowLast: { borderBottomWidth: 0 },
1696
+ reviewLabel: {
1697
+ width: 64,
1698
+ ...typography.caption2,
1699
+ fontWeight: '600',
1700
+ letterSpacing: 0.8,
1701
+ textTransform: 'uppercase'
1702
+ },
1703
+ reviewAddressIcon: { width: 32, height: 32, borderRadius: 16, alignItems: 'center', justifyContent: 'center' },
1704
+ reviewToText: { flex: 1, minWidth: 0, gap: 2 },
1705
+ reviewNameRow: { flexDirection: 'row', alignItems: 'baseline', gap: spacing.sm, minWidth: 0 },
1706
+ reviewName: { ...typography.body, fontWeight: '600', flexShrink: 1 },
1707
+ reviewNameSub: { ...typography.subhead, flexShrink: 1 },
1708
+ reviewTrustRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
1709
+ reviewTrust: { ...typography.caption1 },
1710
+ reviewAmountBlock: { flex: 1 },
1711
+ reviewAmount: { ...typography.title2, fontWeight: '700', fontVariant: ['tabular-nums'] },
1712
+ reviewUnit: { ...typography.headline, fontWeight: '600' },
1713
+ // XR-044: smaller and dimmer than the amount — the last-chance identity
1714
+ // check, not something every glance needs.
1715
+ reviewAssetIdentity: { ...typography.caption2, marginTop: 2, fontVariant: ['tabular-nums'] },
1716
+ reviewNoteInput: { ...typography.body, flex: 1, minWidth: 0, paddingVertical: 0 },
1717
+ reviewHostText: { ...typography.footnote, flex: 1 },
1718
+
1099
1719
  // Consequence line + call to action
1100
1720
  consequence: {
1101
1721
  ...typography.footnote,
@@ -1195,5 +1815,7 @@ const styles = StyleSheet.create({
1195
1815
  }
1196
1816
  })
1197
1817
 
1818
+ const UniversalSend = forwardRef<UniversalSendHandle, UniversalSendProps>(UniversalSendInner)
1819
+
1198
1820
  // Wallet status updates in the parent do not change this form's inputs.
1199
1821
  export default memo(UniversalSend)