@bsv/expo-wallet-toolbox 0.7.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 (151) hide show
  1. package/CHANGELOG.md +1745 -0
  2. package/README.md +47 -1
  3. package/core/amountFormatHelpers.ts +20 -2
  4. package/core/backup/RemoteSyncReader.ts +131 -19
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +147 -9
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +70 -4
  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/constants.ts +14 -1
  15. package/core/context/ExchangeRateContext.tsx +34 -27
  16. package/core/context/LocalStorageProvider.tsx +43 -40
  17. package/core/context/UserContext.tsx +18 -7
  18. package/core/context/VaultContext.tsx +49 -2
  19. package/core/context/WalletConnectionContext.tsx +203 -11
  20. package/core/context/WalletContext.tsx +631 -162
  21. package/core/headers/OfflineFirstChaintracks.ts +48 -4
  22. package/core/headers/headerStore.ts +26 -4
  23. package/core/headers/syncHeaders.ts +12 -1
  24. package/core/i18n/translations.tsx +953 -25
  25. package/core/identity/handleRegistry/client.ts +31 -2
  26. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  27. package/core/identity/handleRegistry/resolver.ts +71 -3
  28. package/core/index.ts +33 -3
  29. package/core/localpay/build.ts +225 -24
  30. package/core/localpay/pending.ts +110 -7
  31. package/core/localpay/pendingAbortAuthority.ts +95 -0
  32. package/core/localpay/pendingAborts.ts +264 -28
  33. package/core/localpay/session.ts +42 -17
  34. package/core/localpay/settlementAck.ts +10 -1
  35. package/core/localpay/transport/socket.ts +52 -3
  36. package/core/localpay/verify.ts +100 -10
  37. package/core/mandala/abortGuard.ts +96 -20
  38. package/core/mandala/createRuntime.ts +206 -33
  39. package/core/mandala/drain.ts +89 -11
  40. package/core/mandala/inboxPrehold.ts +186 -0
  41. package/core/mandala/permissionModule.ts +202 -20
  42. package/core/mandala/settlementStore.ts +24 -2
  43. package/core/mandala/types.ts +40 -5
  44. package/core/monitor/TaskBackupPush.ts +14 -0
  45. package/core/monitor/TaskDrainOutbox.ts +14 -0
  46. package/core/monitor/TaskSendOffline.ts +14 -0
  47. package/core/net/publicDestination.ts +91 -0
  48. package/core/net/validateArcUrl.ts +22 -0
  49. package/core/offline/cancelParked.ts +134 -13
  50. package/core/offline/payerHold.ts +100 -24
  51. package/core/offline/plan.ts +36 -7
  52. package/core/pay/beefRepair.ts +6 -2
  53. package/core/pay/damagedInbox.ts +24 -0
  54. package/core/pay/rails/address.ts +107 -12
  55. package/core/pay/rails/handle.ts +117 -22
  56. package/core/pay/rails/index.ts +45 -7
  57. package/core/pay/rails/nativeIntent.ts +61 -0
  58. package/core/pay/receiveHistory.ts +93 -0
  59. package/core/pay/recordProof.ts +19 -1
  60. package/core/pay/refreshProofGuard.ts +42 -1
  61. package/core/pay/watchlist.ts +5 -2
  62. package/core/peerpay/control.ts +17 -18
  63. package/core/peerpay/handleResendRequests.ts +58 -4
  64. package/core/peerpay/outbox.ts +3 -1
  65. package/core/recovery/backupMaterial.ts +61 -0
  66. package/core/recovery/createWallet.ts +95 -0
  67. package/core/recovery/recoverWallet.ts +120 -0
  68. package/core/recovery/restoreWallet.ts +170 -0
  69. package/core/recovery/secret.ts +92 -0
  70. package/core/recovery/shareCollector.ts +71 -0
  71. package/core/recovery/shareParsing.ts +87 -0
  72. package/core/recovery/shares.ts +116 -0
  73. package/core/recovery/useRecoveryDeps.ts +70 -0
  74. package/core/services/arcTokenStorage.ts +52 -0
  75. package/core/services/arcadeBroadcastProvider.ts +232 -48
  76. package/core/services/autoApprovePolicy.ts +105 -0
  77. package/core/services/callbackToken.ts +19 -0
  78. package/core/services/capWalletArgs.ts +14 -2
  79. package/core/services/connectionAuthority.ts +98 -0
  80. package/core/services/exchangeRate.ts +35 -12
  81. package/core/services/externalOrigin.ts +11 -0
  82. package/core/services/secrets/kek.ts +126 -29
  83. package/core/services/secrets/migration.ts +16 -4
  84. package/core/services/secrets/store.ts +42 -14
  85. package/core/services/vault/VaultKeyService.ts +228 -45
  86. package/core/services/vault/chainRecovery.ts +483 -0
  87. package/core/services/vault/driver.ts +9 -1
  88. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  89. package/core/services/vault/guard.ts +218 -32
  90. package/core/services/vault/hardwareLease.ts +19 -0
  91. package/core/services/vault/metaAuthority.ts +210 -0
  92. package/core/services/vault/pivReset.ts +64 -23
  93. package/core/services/vault/r1comb.ts +139 -3
  94. package/core/services/vault/session.ts +25 -4
  95. package/core/services/vault/transfers.ts +866 -170
  96. package/core/services/vault/types.ts +19 -4
  97. package/core/services/vault/vaultStore.ts +256 -29
  98. package/core/services/walletArgLimits.ts +45 -2
  99. package/core/services/walletConnectionValidation.ts +76 -6
  100. package/core/services/walletServiceConfig.ts +10 -8
  101. package/core/storage/StorageExpoSQLite.ts +47 -13
  102. package/core/storage/methods/findSql.ts +21 -2
  103. package/core/storage/methods/offlineActions.ts +10 -1
  104. package/core/storage/methods/processOfflineActions.ts +116 -23
  105. package/core/storage/schema/createTables.ts +126 -2
  106. package/core/stores/ConnectionStore.ts +34 -0
  107. package/core/toolboxConfig.ts +45 -11
  108. package/core/walletDbRegistry.ts +63 -0
  109. package/core/walletMonitor.ts +17 -1
  110. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  111. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  112. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  113. package/package.json +2 -2
  114. package/ui/backupShares.ts +26 -169
  115. package/ui/components/pay/AddressReceive.tsx +13 -6
  116. package/ui/components/pay/AssetPicker.tsx +30 -9
  117. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  118. package/ui/components/pay/NearbyFlow.tsx +480 -243
  119. package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
  120. package/ui/components/pay/UniversalSend.tsx +167 -73
  121. package/ui/components/ui/AlertCard.tsx +38 -5
  122. package/ui/components/ui/PermissionSheet.tsx +197 -66
  123. package/ui/components/vault/EnrollWizard.tsx +61 -13
  124. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  125. package/ui/components/wallet/ActivityRow.tsx +5 -3
  126. package/ui/components/wallet/AmountInput.tsx +8 -2
  127. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  128. package/ui/components/wallet/Balance.tsx +42 -23
  129. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  130. package/ui/exportTransactions.ts +36 -4
  131. package/ui/hooks/useExportWalletData.ts +25 -2
  132. package/ui/importDatabases.ts +339 -24
  133. package/ui/index.ts +9 -3
  134. package/ui/isImageUrl.ts +6 -0
  135. package/ui/printRecoveryShares.ts +9 -10
  136. package/ui/recoveryPrompts.ts +91 -0
  137. package/ui/resolveIdentity.ts +31 -9
  138. package/ui/screens/ConnectionsScreen.tsx +86 -19
  139. package/ui/screens/IdentifierScreen.tsx +30 -8
  140. package/ui/screens/PairScreen.tsx +74 -2
  141. package/ui/screens/SettingsScreen.tsx +10 -4
  142. package/ui/screens/TrustScreen.tsx +99 -4
  143. package/ui/screens/VaultScreen.tsx +410 -61
  144. package/ui/screens/VaultTransferScreen.tsx +59 -7
  145. package/ui/screens/WalletCheckScreen.tsx +17 -6
  146. package/ui/screens/WalletConfigScreen.tsx +82 -28
  147. package/ui/screens/WalletHomeScreen.tsx +179 -88
  148. package/ui/screens/detailActionKeys.ts +55 -0
  149. package/ui/tokenFormat.ts +44 -4
  150. package/ui/txStatus.ts +5 -0
  151. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -84,6 +84,26 @@ export interface ReceivedOverlayProps {
84
84
  * tell them yet". Never a claim of settlement the wallet does not have.
85
85
  */
86
86
  statusNote?: string
87
+ /**
88
+ * Received only (P1-1). The overlay's TIMING never changes — it is shown
89
+ * as soon as the payment is durably queued, before internalizeAction has
90
+ * necessarily run — but the green success CLAIM is gated on this:
91
+ *
92
+ * 'pending' — internalizeAction has not resolved yet. Neutral copy
93
+ * (t('local_pay_received_confirming')), no green.
94
+ * 'verified' — credited. Today's unchanged green 'local_pay_added'.
95
+ * 'not-credited' — internalizeAction failed or returned no success.
96
+ * The money is still safely queued and will resolve —
97
+ * this is not a decline and not a loss — but claiming
98
+ * it is already "Added to your wallet" would be a
99
+ * claim this device cannot back yet. Neutral copy
100
+ * (t('local_pay_received_not_credited')), no green.
101
+ *
102
+ * Defaults to 'verified' so every existing caller (and the whole 'sent'
103
+ * direction, where the payer's money already left and there is nothing
104
+ * left here to confirm) is unaffected.
105
+ */
106
+ verification?: 'pending' | 'verified' | 'not-credited'
87
107
  /**
88
108
  * First time this wallet has ever held this asset: who issues it and what
89
109
  * they can do. Disclosure at the one moment the user is definitely looking.
@@ -122,7 +142,8 @@ export default function PaymentSuccessOverlay({
122
142
  firstHoldNote,
123
143
  dismissTo = '/',
124
144
  onAddContact,
125
- onDismiss
145
+ onDismiss,
146
+ verification = 'verified'
126
147
  }: ReceivedOverlayProps) {
127
148
  const sent = direction === 'sent'
128
149
  const { t } = useTranslation()
@@ -168,6 +189,17 @@ export default function PaymentSuccessOverlay({
168
189
  router.dismissTo(dismissTo)
169
190
  }, [onDismiss, dismissTo])
170
191
 
192
+ // Received-only (see the `verification` prop doc). Computed once so the
193
+ // same sentence backs both the visible text and its accessibility label.
194
+ const receivedSupportText =
195
+ verification === 'pending'
196
+ ? t('local_pay_received_confirming')
197
+ : verification === 'not-credited'
198
+ ? t('local_pay_received_not_credited')
199
+ : count > 1
200
+ ? t('local_pay_added_multiple', { count })
201
+ : t('local_pay_added')
202
+
171
203
  const settleIn = reducedMotion
172
204
  ? undefined
173
205
  : FadeInDown.springify()
@@ -189,7 +221,7 @@ export default function PaymentSuccessOverlay({
189
221
  style={[styles.container, { backgroundColor: colors.background }]}
190
222
  accessibilityViewIsModal
191
223
  accessibilityRole="alert"
192
- accessibilityLabel={sent ? t('local_pay_sent') : `${t('local_pay_received')}. ${t('local_pay_added')}`}
224
+ accessibilityLabel={sent ? t('local_pay_sent') : `${t('local_pay_received')}. ${receivedSupportText}`}
193
225
  >
194
226
  <View style={styles.stage}>
195
227
  <Celebration onDone={onMarkDone} />
@@ -238,8 +270,11 @@ export default function PaymentSuccessOverlay({
238
270
  )}
239
271
  </>
240
272
  ) : (
241
- <Text style={[styles.support, { color: colors.success }]} textBreakStrategy="balanced">
242
- {count > 1 ? t('local_pay_added_multiple', { count }) : t('local_pay_added')}
273
+ <Text
274
+ style={[styles.support, { color: verification === 'verified' ? colors.success : colors.textSecondary }]}
275
+ textBreakStrategy="balanced"
276
+ >
277
+ {receivedSupportText}
243
278
  </Text>
244
279
  )}
245
280
 
@@ -40,7 +40,7 @@ import { useAssetStatus, useMandala } from '../../hooks/useMandala'
40
40
  import { useSpendableBalance } from '../../hooks/useSpendableBalance'
41
41
  import { useContactsStore } from '../../hooks/useContactsStore'
42
42
  import ContactSigil from '../wallet/ContactSigil'
43
- import { formatTokenAmount, formatTokenAmountWithUnit } from '../../tokenFormat'
43
+ import { formatTokenAmount, formatTokenAmountWithUnit, shortAssetId } from '../../tokenFormat'
44
44
  import { abbreviateKey } from '../../../core/pay/counterparty'
45
45
  import type { ContactRow } from '../../../core/contacts/contactsStore'
46
46
  import { createHandleRegistryClient } from '../../../core/identity/handleRegistry/client'
@@ -57,6 +57,7 @@ import {
57
57
  useWalletStatus,
58
58
  CONSEQUENCE_KEYS,
59
59
  NO_MESSAGE_BOX,
60
+ addressNetwork,
60
61
  cancelOutboxPayment,
61
62
  classifyRecipientInput,
62
63
  getHandleRegistryConfig,
@@ -71,7 +72,8 @@ import {
71
72
  type OutboxEntry,
72
73
  type Session,
73
74
  haptics,
74
- listPendingResendRequests
75
+ listPendingResendRequests,
76
+ makeListPeerPayAction
75
77
  } from '@bsv/expo-wallet-toolbox'
76
78
  import type { DismissTarget } from '../../dismissTarget'
77
79
 
@@ -382,6 +384,12 @@ function UniversalSendInner(
382
384
  initialNotice ? { type: 'error', message: initialNotice } : null
383
385
  )
384
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)
385
393
  const [sendResult, setSendResult] = useState<{ type: 'success' | 'error'; message: string } | null>(null)
386
394
  /**
387
395
  * The failed-token-send note, kept apart from `sendResult` because it carries
@@ -592,6 +600,12 @@ function UniversalSendInner(
592
600
  for (const p of registryMatches) {
593
601
  if (seen.has(p.identityKey)) continue
594
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()
595
609
  registryIdentities.push({
596
610
  identityKey: p.identityKey,
597
611
  // A display name is the owner's own unvalidated plaintext, and this row
@@ -604,7 +618,9 @@ function UniversalSendInner(
604
618
  avatarURL: '',
605
619
  abbreviatedKey: abbreviateKey(p.identityKey),
606
620
  badgeIconURL: '',
607
- badgeLabel: t('pay_trust_handle_attested'),
621
+ badgeLabel: ownDomain
622
+ ? t('pay_trust_handle_attested')
623
+ : t('pay_trust_handle_domain_attested', { domain: p.domain }),
608
624
  badgeClickURL: '',
609
625
  secondaryLine: p.paymail
610
626
  })
@@ -614,7 +630,7 @@ function UniversalSendInner(
614
630
  ...registryIdentities,
615
631
  ...recipient.searchResults.filter(r => !seen.has(r.identityKey))
616
632
  ]
617
- }, [contactMatches, registryMatches, recipient.searchResults, t])
633
+ }, [contactMatches, registryMatches, recipient.searchResults, registryClient, t])
618
634
 
619
635
  /**
620
636
  * The handle of the row the user picked, so the success screen's "Save as
@@ -803,11 +819,14 @@ function UniversalSendInner(
803
819
  const client = peerPayClient
804
820
  if (!client || !storage) return
805
821
  try {
806
- 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) })
807
826
  } catch {
808
827
  // Home owns the unanswered-resend banner; a failed poll here is retryable.
809
828
  }
810
- }, [peerPayClient, storage])
829
+ }, [peerPayClient, storage, wallet, adminOriginator])
811
830
 
812
831
  useEffect(() => {
813
832
  void pollResendRequests()
@@ -949,65 +968,78 @@ function UniversalSendInner(
949
968
  )
950
969
 
951
970
  const handleSend = useCallback(async () => {
952
- if (!target) return
953
- // Guard before any side effect: a wallet that is not ready must leave the
954
- // form exactly as typed, with a banner, not a cleared field and silence.
955
- // On the token path the runtime IS the wallet — it holds its own manager,
956
- // storage and journal — so that is what has to be ready.
957
- if (asset ? !mandala.runtime : !wallet || !storage) {
958
- flashResult({ type: 'error', message: t('wallet_not_ready') })
959
- return
960
- }
961
- // The same integer either way — satoshis on the BSV rail, base units of the
962
- // asset on the token rail. The field emits whole units in both modes.
963
- const amount = Math.round(Number(sendAmount))
964
- if (!Number.isFinite(amount) || amount <= 0) {
965
- flashResult({ type: 'error', message: t('enter_valid_amount') })
966
- return
967
- }
968
- haptics.confirm()
969
- setIsSending(true)
970
- 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
971
980
  try {
972
- if (asset) {
973
- // D4: a token has no address rail, and `canSend` has already refused
974
- // one. This is the second gate, because the first is a render.
975
- if (target.kind !== 'handle') return
976
- const sent = await sendToken(target, amount)
977
- if (!sent) return
978
- } else if (target.kind === 'handle') await sendHandle(target, amount)
979
- else await sendAddress(target, amount)
980
- setFigure(current => ({ ...current, text: '' }))
981
- setNote('')
982
- recipient.clearRecipient()
983
- setStep('who')
984
- } catch (error: any) {
985
- if (await handleWalletCheck(error)) return
986
- if (asset) {
987
- console.warn('[mandala] token send threw:', error)
988
- // A throw out of the token path is NOT a refusal: the overlay may have
989
- // admitted the transaction and lost the response, so the copy claims
990
- // nothing and offers a balance check rather than a retry.
991
- setTokenFailure(
992
- tokenThrowCopy(error, {
993
- ticker: asset.ticker,
994
- issuer: asset.issuerName,
995
- issuerFallback: t('token_issuer_fallback')
996
- })
997
- )
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') })
998
995
  return
999
996
  }
1000
- const message =
1001
- error instanceof RangeError
1002
- ? t('enter_valid_amount')
1003
- : isMessageBoxNetworkError(error)
1004
- ? t('message_box_unreachable')
1005
- : error?.message || t('unknown_error')
1006
- flashResult({ type: 'error', message })
1007
- // A failed handle send leaves its entry 'unsent' and offered for retry below.
1008
- 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
+ }
1009
1041
  } finally {
1010
- setIsSending(false)
1042
+ sendingRef.current = false
1011
1043
  }
1012
1044
  }, [
1013
1045
  target,
@@ -1117,6 +1149,17 @@ function UniversalSendInner(
1117
1149
  const amountOk = Number(sendAmount) > 0
1118
1150
  const isHandle = target?.kind === 'handle'
1119
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')
1120
1163
  // A stuck handle payment blocks new HANDLE sends: every attempt while the box
1121
1164
  // is unreachable would mint another noSend action and another stuck entry.
1122
1165
  // Address sends never touch the box, so they are not held hostage by it.
@@ -1259,6 +1302,11 @@ function UniversalSendInner(
1259
1302
  const reviewAmount = asset
1260
1303
  ? { value: formatTokenAmount(baseUnits, asset.decimals) ?? '', unit: asset.ticker }
1261
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(' · ') : ''
1262
1310
  const reviewPrimary =
1263
1311
  recipient.selectedIdentity?.name ||
1264
1312
  (target?.kind === 'handle' ? abbreviateKey(target.identityKey) : target?.kind === 'address' ? target.address : '')
@@ -1277,6 +1325,15 @@ function UniversalSendInner(
1277
1325
  ? { icon: 'shield-checkmark-outline', color: colors.textSecondary, text: t('pay_trust_handle_attested') }
1278
1326
  : { icon: 'alert-circle-outline', color: colors.warning, text: t('pay_trust_unverified') }
1279
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
1280
1337
 
1281
1338
  return (
1282
1339
  <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
@@ -1439,21 +1496,52 @@ function UniversalSendInner(
1439
1496
  </View>
1440
1497
 
1441
1498
  <View
1442
- style={[styles.reviewRow, !showNoteRow && styles.reviewRowLast, { borderBottomColor: colors.separator }]}
1499
+ style={[
1500
+ styles.reviewRow,
1501
+ !showNoteRow && !showHostRow && styles.reviewRowLast,
1502
+ { borderBottomColor: colors.separator }
1503
+ ]}
1443
1504
  >
1444
1505
  <Text style={[styles.reviewLabel, { color: colors.textTertiary }]}>{t('pay_review_amount')}</Text>
1445
- {/* No adjustsFontSizeToFit / numberOfLines: iOS's shrink floor is a fixed 4pt and in this
1446
- flex row it collapsed the amount to illegible. A long amount wraps instead, so no digit
1447
- is ever hidden on the screen that confirms it. */}
1448
- <Text
1449
- style={[styles.reviewAmount, { color: colors.textPrimary }]}
1450
- accessibilityLabel={`${reviewAmount.value} ${reviewAmount.unit}`}
1451
- >
1452
- {reviewAmount.value}{' '}
1453
- <Text style={[styles.reviewUnit, { color: colors.textSecondary }]}>{reviewAmount.unit}</Text>
1454
- </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>
1455
1525
  </View>
1456
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
+
1457
1545
  {showNoteRow && (
1458
1546
  <View style={[styles.reviewRow, styles.reviewRowLast]}>
1459
1547
  <Text style={[styles.reviewLabel, { color: colors.textTertiary }]}>{t('pay_review_note')}</Text>
@@ -1474,6 +1562,7 @@ function UniversalSendInner(
1474
1562
  for a handle, and nothing at all in token mode, where an address is
1475
1563
  refused rather than warned about. */}
1476
1564
  {isAddress && !asset && <ConsequenceNote textKey={CONSEQUENCE_KEYS.address} />}
1565
+ {isAddress && !asset && addressNetworkMismatch && <ConsequenceNote textKey="pay_address_network_mismatch" />}
1477
1566
 
1478
1567
  {tokenNote && (
1479
1568
  <ConsequenceNote
@@ -1618,9 +1707,14 @@ const styles = StyleSheet.create({
1618
1707
  reviewNameSub: { ...typography.subhead, flexShrink: 1 },
1619
1708
  reviewTrustRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
1620
1709
  reviewTrust: { ...typography.caption1 },
1621
- reviewAmount: { ...typography.title2, fontWeight: '700', fontVariant: ['tabular-nums'], flex: 1 },
1710
+ reviewAmountBlock: { flex: 1 },
1711
+ reviewAmount: { ...typography.title2, fontWeight: '700', fontVariant: ['tabular-nums'] },
1622
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'] },
1623
1716
  reviewNoteInput: { ...typography.body, flex: 1, minWidth: 0, paddingVertical: 0 },
1717
+ reviewHostText: { ...typography.footnote, flex: 1 },
1624
1718
 
1625
1719
  // Consequence line + call to action
1626
1720
  consequence: {
@@ -57,6 +57,10 @@ export function showAlert(options: AlertOptions): Promise<string> {
57
57
 
58
58
  const DEFAULT_BUTTONS: AlertButton[] = [{ text: 'OK', key: 'ok' }]
59
59
 
60
+ /** Upper bound on waiting for the native modal's dismissal (iOS `onDismiss`),
61
+ * so an alert whose modal never presented cannot hold the queue forever. */
62
+ const DISMISS_FALLBACK_MS = 1_000
63
+
60
64
  export function AlertHost() {
61
65
  const { colors } = useTheme()
62
66
  const reducedMotion = useReducedMotion()
@@ -66,6 +70,13 @@ export function AlertHost() {
66
70
  const progress = useSharedValue(0)
67
71
  const exiting = useRef(false)
68
72
  const lastHapticAlert = useRef<ActiveAlert | null>(null)
73
+ // The pressed key, held until the modal is gone. The caller's promise must
74
+ // not settle while the alert's native modal is still presented: a caller
75
+ // that presents native UI next (the export's share sheet) would present it
76
+ // ON this modal, and dismissing the modal takes it down before it can
77
+ // report back.
78
+ const pending = useRef<{ alert: ActiveAlert; key: string; fallback: ReturnType<typeof setTimeout> } | null>(null)
79
+ const [hiding, setHiding] = useState(false)
69
80
 
70
81
  useEffect(() => {
71
82
  enqueue = (a: ActiveAlert) => setQueue(q => [...q, a])
@@ -97,14 +108,35 @@ export function AlertHost() {
97
108
  }
98
109
  }, [current, progress, reducedMotion])
99
110
 
111
+ /** Resolve the dismissed alert and show the next one. Runs once per alert. */
112
+ const finish = useCallback(() => {
113
+ const done = pending.current
114
+ if (!done) return
115
+ pending.current = null
116
+ clearTimeout(done.fallback)
117
+ exiting.current = false
118
+ setHiding(false)
119
+ setQueue(q => (q[0] === done.alert ? q.slice(1) : q))
120
+ done.alert.resolve(done.key)
121
+ }, [])
122
+
100
123
  const dismiss = useCallback((key: string) => {
101
124
  if (!current || exiting.current) return
102
125
  exiting.current = true
103
- current.resolve(key)
126
+ pending.current = { alert: current, key, fallback: setTimeout(finish, durations.instant + DISMISS_FALLBACK_MS) }
104
127
  progress.value = withTiming(0, { duration: durations.instant })
105
- // Unmount after the exit fade completes.
106
- setTimeout(() => { exiting.current = false; setQueue(q => q.slice(1)) }, durations.instant)
107
- }, [current, progress])
128
+ // After the exit fade, hide the modal. iOS reports the native dismissal
129
+ // through onDismiss; Android has no such event and nothing presented over
130
+ // it to protect, so it finishes here.
131
+ setTimeout(() => {
132
+ if (Platform.OS === 'ios') setHiding(true)
133
+ else finish()
134
+ }, durations.instant)
135
+ }, [current, progress, finish])
136
+
137
+ useEffect(() => () => {
138
+ if (pending.current) clearTimeout(pending.current.fallback)
139
+ }, [])
108
140
 
109
141
  const backdropStyle = useAnimatedStyle(() => ({ opacity: progress.value }))
110
142
  const cardStyle = useAnimatedStyle(() => ({
@@ -124,8 +156,9 @@ export function AlertHost() {
124
156
  return (
125
157
  <Modal
126
158
  transparent
127
- visible
159
+ visible={!hiding}
128
160
  animationType="none"
161
+ onDismiss={finish}
129
162
  onRequestClose={() => dismiss('cancel')}
130
163
  statusBarTranslucent={Platform.OS === 'android'}
131
164
  navigationBarTranslucent={Platform.OS === 'android'}