@bsv/expo-wallet-toolbox 0.7.0 → 0.10.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 (154) hide show
  1. package/CHANGELOG.md +1790 -0
  2. package/README.md +54 -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 +653 -175
  21. package/core/headers/OfflineFirstChaintracks.ts +48 -4
  22. package/core/headers/headerStore.ts +26 -4
  23. package/core/headers/headerSyncTriggers.ts +65 -0
  24. package/core/headers/syncHeaders.ts +12 -1
  25. package/core/i18n/translations.tsx +1001 -25
  26. package/core/identity/handleRegistry/client.ts +31 -2
  27. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  28. package/core/identity/handleRegistry/resolver.ts +71 -3
  29. package/core/index.ts +33 -3
  30. package/core/localpay/build.ts +225 -24
  31. package/core/localpay/pending.ts +110 -7
  32. package/core/localpay/pendingAbortAuthority.ts +95 -0
  33. package/core/localpay/pendingAborts.ts +264 -28
  34. package/core/localpay/session.ts +42 -17
  35. package/core/localpay/settlementAck.ts +10 -1
  36. package/core/localpay/transport/socket.ts +52 -3
  37. package/core/localpay/types.ts +9 -1
  38. package/core/localpay/verify.ts +143 -16
  39. package/core/mandala/abortGuard.ts +96 -20
  40. package/core/mandala/createRuntime.ts +206 -33
  41. package/core/mandala/drain.ts +89 -11
  42. package/core/mandala/inboxPrehold.ts +186 -0
  43. package/core/mandala/permissionModule.ts +202 -20
  44. package/core/mandala/settlementStore.ts +24 -2
  45. package/core/mandala/types.ts +40 -5
  46. package/core/monitor/TaskBackupPush.ts +14 -0
  47. package/core/monitor/TaskDrainOutbox.ts +14 -0
  48. package/core/monitor/TaskSendOffline.ts +14 -0
  49. package/core/net/publicDestination.ts +91 -0
  50. package/core/net/validateArcUrl.ts +22 -0
  51. package/core/offline/cancelParked.ts +134 -13
  52. package/core/offline/payerHold.ts +100 -24
  53. package/core/offline/plan.ts +36 -7
  54. package/core/pay/beefRepair.ts +6 -2
  55. package/core/pay/damagedInbox.ts +24 -0
  56. package/core/pay/rails/address.ts +107 -12
  57. package/core/pay/rails/handle.ts +117 -22
  58. package/core/pay/rails/index.ts +45 -7
  59. package/core/pay/rails/nativeIntent.ts +61 -0
  60. package/core/pay/rails/nearby.ts +1 -0
  61. package/core/pay/receiveHistory.ts +93 -0
  62. package/core/pay/recordProof.ts +19 -1
  63. package/core/pay/refreshProofGuard.ts +42 -1
  64. package/core/pay/watchlist.ts +5 -2
  65. package/core/peerpay/control.ts +17 -18
  66. package/core/peerpay/handleResendRequests.ts +58 -4
  67. package/core/peerpay/outbox.ts +3 -1
  68. package/core/recovery/backupMaterial.ts +61 -0
  69. package/core/recovery/createWallet.ts +95 -0
  70. package/core/recovery/recoverWallet.ts +120 -0
  71. package/core/recovery/restoreWallet.ts +170 -0
  72. package/core/recovery/secret.ts +92 -0
  73. package/core/recovery/shareCollector.ts +71 -0
  74. package/core/recovery/shareParsing.ts +87 -0
  75. package/core/recovery/shares.ts +116 -0
  76. package/core/recovery/useRecoveryDeps.ts +70 -0
  77. package/core/services/arcTokenStorage.ts +52 -0
  78. package/core/services/arcadeBroadcastProvider.ts +232 -48
  79. package/core/services/autoApprovePolicy.ts +105 -0
  80. package/core/services/callbackToken.ts +19 -0
  81. package/core/services/capWalletArgs.ts +14 -2
  82. package/core/services/connectionAuthority.ts +98 -0
  83. package/core/services/exchangeRate.ts +35 -12
  84. package/core/services/externalOrigin.ts +11 -0
  85. package/core/services/secrets/kek.ts +126 -29
  86. package/core/services/secrets/migration.ts +16 -4
  87. package/core/services/secrets/store.ts +42 -14
  88. package/core/services/vault/VaultKeyService.ts +228 -45
  89. package/core/services/vault/chainRecovery.ts +483 -0
  90. package/core/services/vault/driver.ts +9 -1
  91. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  92. package/core/services/vault/guard.ts +218 -32
  93. package/core/services/vault/hardwareLease.ts +19 -0
  94. package/core/services/vault/metaAuthority.ts +210 -0
  95. package/core/services/vault/pivReset.ts +64 -23
  96. package/core/services/vault/r1comb.ts +139 -3
  97. package/core/services/vault/session.ts +25 -4
  98. package/core/services/vault/transfers.ts +866 -170
  99. package/core/services/vault/types.ts +19 -4
  100. package/core/services/vault/vaultStore.ts +256 -29
  101. package/core/services/walletArgLimits.ts +45 -2
  102. package/core/services/walletConnectionValidation.ts +76 -6
  103. package/core/services/walletServiceConfig.ts +10 -8
  104. package/core/storage/StorageExpoSQLite.ts +47 -13
  105. package/core/storage/methods/findSql.ts +21 -2
  106. package/core/storage/methods/offlineActions.ts +10 -1
  107. package/core/storage/methods/processOfflineActions.ts +116 -23
  108. package/core/storage/schema/createTables.ts +126 -2
  109. package/core/stores/ConnectionStore.ts +34 -0
  110. package/core/toolboxConfig.ts +45 -11
  111. package/core/walletDbRegistry.ts +63 -0
  112. package/core/walletMonitor.ts +17 -1
  113. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  114. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  115. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  116. package/package.json +2 -2
  117. package/ui/backupShares.ts +26 -169
  118. package/ui/components/pay/AddressReceive.tsx +13 -6
  119. package/ui/components/pay/AssetPicker.tsx +30 -9
  120. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  121. package/ui/components/pay/NearbyFlow.tsx +511 -251
  122. package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
  123. package/ui/components/pay/UniversalSend.tsx +167 -73
  124. package/ui/components/ui/AlertCard.tsx +38 -5
  125. package/ui/components/ui/PermissionSheet.tsx +197 -66
  126. package/ui/components/vault/EnrollWizard.tsx +61 -13
  127. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  128. package/ui/components/wallet/ActivityRow.tsx +5 -3
  129. package/ui/components/wallet/AmountInput.tsx +8 -2
  130. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  131. package/ui/components/wallet/Balance.tsx +42 -23
  132. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  133. package/ui/exportTransactions.ts +36 -4
  134. package/ui/hooks/useExportWalletData.ts +25 -2
  135. package/ui/importDatabases.ts +339 -24
  136. package/ui/index.ts +9 -3
  137. package/ui/isImageUrl.ts +6 -0
  138. package/ui/printRecoveryShares.ts +9 -10
  139. package/ui/recoveryPrompts.ts +91 -0
  140. package/ui/resolveIdentity.ts +31 -9
  141. package/ui/screens/ConnectionsScreen.tsx +86 -19
  142. package/ui/screens/IdentifierScreen.tsx +30 -8
  143. package/ui/screens/PairScreen.tsx +74 -2
  144. package/ui/screens/SettingsScreen.tsx +10 -4
  145. package/ui/screens/TrustScreen.tsx +99 -4
  146. package/ui/screens/VaultScreen.tsx +410 -61
  147. package/ui/screens/VaultTransferScreen.tsx +59 -7
  148. package/ui/screens/WalletCheckScreen.tsx +17 -6
  149. package/ui/screens/WalletConfigScreen.tsx +82 -28
  150. package/ui/screens/WalletHomeScreen.tsx +179 -88
  151. package/ui/screens/detailActionKeys.ts +55 -0
  152. package/ui/tokenFormat.ts +44 -4
  153. package/ui/txStatus.ts +5 -0
  154. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -48,14 +48,20 @@
48
48
  * derivation nonces do not match the live request — or whose amount
49
49
  * contradicts an amount the payee actually asked for — is refused without
50
50
  * burning the session, so the real payer can still pay.
51
- * 1. isSessionSpent() is consulted before anything is written.
52
- * 2. savePending() completes before markSessionSpent(). Never the reverse:
53
- * a crash between the two would burn a one-shot session whose payment was
54
- * never persisted, and that money is unrecoverable.
55
- * 3. processPending() runs only after savePending() has resolved, outside the
51
+ * 1. claimAndSavePending() checks the session, persists the frame, and burns
52
+ * the session as ONE atomic operation (XR-098) — never three separate
53
+ * ones. Three separate operations, even correctly ordered, are not
54
+ * atomic: two concurrent deliveries for the same session (radio racing a
55
+ * QR scan, or any other overlap) could each pass the check before either
56
+ * had written anything, and both would durably queue a payment for a
57
+ * session meant to be spent exactly once.
58
+ * 2. Persist-then-burn, never the reverse, is still the ordering INSIDE that
59
+ * one operation: a crash between the two would burn a one-shot session
60
+ * whose payment was never persisted, and that money is unrecoverable.
61
+ * 3. processPending() runs only after the claim has resolved, outside the
56
62
  * try that can flip the screen to a failure. Once the frame is queued the
57
63
  * payment cannot be lost, so reporting failure past that line would invite
58
- * a duplicate payment — the same misreport refused for markSessionSpent.
64
+ * a duplicate payment.
59
65
  * 4. The live Session is threaded in as an argument — neither PaymentFrame
60
66
  * nor PendingPayment carries a sessionId, so it cannot be recovered later.
61
67
  * 5. Every decode sits in a bare `catch`, which catches non-Error throws from
@@ -88,13 +94,24 @@
88
94
  */
89
95
 
90
96
  import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
91
- import { ActivityIndicator, Linking, Modal, Platform, ScrollView, StyleSheet, Text, TextInput, View } from 'react-native'
97
+ import {
98
+ ActivityIndicator,
99
+ Linking,
100
+ Modal,
101
+ Platform,
102
+ ScrollView,
103
+ StyleSheet,
104
+ Text,
105
+ TextInput,
106
+ View
107
+ } from 'react-native'
92
108
  import Animated, { FadeIn, FadeInDown, useReducedMotion } from 'react-native-reanimated'
93
109
  import { useSafeAreaInsets } from 'react-native-safe-area-context'
94
110
  import { useTranslation } from 'react-i18next'
95
- import { Beef, createNonce, type WalletInterface } from '@bsv/sdk'
111
+ import { Beef, createNonce, type ChainTracker, type WalletInterface } from '@bsv/sdk'
96
112
  import { finalizeDelivery } from '../../../core/localpay/build'
97
- import { queuePendingAbort } from '../../../core/localpay/pendingAborts'
113
+ import { queuePendingAbort, queueDeclinedAbortWatch } from '../../../core/localpay/pendingAborts'
114
+ import type { PendingAbortTagWallet } from '../../../core/localpay/pendingAbortAuthority'
98
115
  import { receiptBroadcastFromReqStatus } from '../../../core/offline/plan'
99
116
  import { userFacingPayError } from '../../../core/pay/userError'
100
117
 
@@ -124,6 +141,8 @@ import {
124
141
  bleTransport,
125
142
  buildPaymentFrame,
126
143
  capsFromProbe,
144
+ chainAlreadyKnows,
145
+ claimAndSavePending,
127
146
  decodeSession,
128
147
  describeFloor,
129
148
  encodeSession,
@@ -132,11 +151,9 @@ import {
132
151
  parkSentPaymentOffline,
133
152
  isAirGapPart,
134
153
  isDeclineReason,
135
- isSessionSpent,
136
154
  localSupportsAwdl,
137
155
  localSupportsBle,
138
156
  localSupportsNearby,
139
- markSessionSpent,
140
157
  mintSession,
141
158
  rememberSessionPsk,
142
159
  nearbyTransport,
@@ -148,7 +165,6 @@ import {
148
165
  readBluetoothState,
149
166
  requestBlePermissions,
150
167
  requestNearbyPermissions,
151
- savePending,
152
168
  sealedToQr,
153
169
  sealFrame,
154
170
  selectTransport,
@@ -163,8 +179,8 @@ import {
163
179
  type RadioKind,
164
180
  type Session,
165
181
  FrameVerifyError,
182
+ declineReasonFor,
166
183
  verifyFramePayment,
167
- type DerivingWallet,
168
184
  type VerifiedPayment,
169
185
  type CoverVerifier,
170
186
  type SessionAsset
@@ -327,7 +343,8 @@ const DECLINE_KEYS: Record<DeclineReason, string> = {
327
343
  already_paid: 'local_pay_declined_already_paid',
328
344
  save_failed: 'local_pay_declined_save',
329
345
  decode_failed: 'local_pay_declined_decode',
330
- not_covered: 'local_pay_declined_not_covered'
346
+ not_covered: 'local_pay_declined_not_covered',
347
+ root_unverified: 'local_pay_declined_root_unverified'
331
348
  }
332
349
 
333
350
  /**
@@ -397,20 +414,35 @@ function satsFrom(text: string): number {
397
414
  * asset this wallet holds (executeSend refuses anything else), and a
398
415
  * `decimals` the registry answered is the figure the overlay stood behind —
399
416
  * a request claiming 4 decimals against an asset this wallet knows has 2
400
- * would otherwise show 2,500.00 USDX as "0.2500". The session's own block —
401
- * whatever the payee's wallet wrote into the QR — is the fallback when this
402
- * wallet's lookup has NOT resolved: the runtime fabricates `''`/`0` for a
403
- * holding it could not identify (an offline cold start, the normal case on
404
- * this rail), and a zero it cannot stand behind must never beat a figure the
405
- * payee's wallet did resolve. The pair is taken from ONE source: a resolved
406
- * decimals beside an unresolved ticker would be a figure with no name.
407
- * `ticker: ''` on the result means neither side knows the unit, and the
408
- * screen refuses to send rather than let the payer type into an unlabelled
409
- * field (design principle 4).
417
+ * would otherwise show 2,500.00 USDX as "0.2500".
418
+ *
419
+ * XR-091: the session's own block — whatever the payee's wallet wrote into
420
+ * the QR — is NEVER trusted as a substitute once a REAL local holding exists
421
+ * for this asset (`held` present) but this device's own metadata lookup for
422
+ * it failed or has not completed (`held.ticker === ''`, the runtime's
423
+ * sentinel for "could not identify"). That holding is genuine spendable
424
+ * value; a malicious or merely out-of-date payee QR is not an authenticated
425
+ * source for the scale it is displayed and typed at, and a payer who is
426
+ * about to move real funds must never have that scale handed to them by the
427
+ * other side of the payment. This fails closed into the same "neither side
428
+ * can name it" path below (`ticker: ''`), which already disables Send and
429
+ * says so — the smallest safe response, since a wrong denomination on a real
430
+ * balance is worse than asking the payer to try again once resolved.
431
+ *
432
+ * The session's own claim is used ONLY as a convenience default when this
433
+ * device holds no local record of the asset AT ALL (`held` absent) — a payer
434
+ * who holds none of an asset cannot spend it regardless of what is shown
435
+ * here (`executeSend`'s own known-holding check refuses the send before any
436
+ * signature is produced), so trusting the QR's naming in that narrower case
437
+ * costs nothing beyond a cosmetic label. The pair is taken from ONE source
438
+ * either way: a resolved decimals beside an unresolved ticker would be a
439
+ * figure with no name. `ticker: ''` on the result means the display refuses
440
+ * to guess, and the screen refuses to send rather than let the payer type
441
+ * into an unlabelled — or falsely labelled — field (design principle 4).
410
442
  */
411
443
  function assetUnits(asset: SessionAsset, held?: { ticker: string; decimals: number } | null): AmountInputAsset {
412
- const resolved = held && held.ticker !== '' ? held : undefined
413
- if (resolved) return { ticker: resolved.ticker, decimals: resolved.decimals }
444
+ if (held && held.ticker !== '') return { ticker: held.ticker, decimals: held.decimals }
445
+ if (held) return { ticker: '', decimals: 0 }
414
446
  // The session block counts only when it names BOTH halves: a ticker with no
415
447
  // decimals would be a named figure at a guessed scale.
416
448
  if (asset.ticker && asset.decimals !== undefined) return { ticker: asset.ticker, decimals: asset.decimals }
@@ -439,13 +471,7 @@ export interface NearbyFlowProps {
439
471
  dismissTo?: DismissTarget
440
472
  }
441
473
 
442
- function NearbyFlow({
443
- role: initialRole,
444
- onExit,
445
- initialSession,
446
- initialRequest,
447
- dismissTo = '/'
448
- }: NearbyFlowProps) {
474
+ function NearbyFlow({ role: initialRole, onExit, initialSession, initialRequest, dismissTo = '/' }: NearbyFlowProps) {
449
475
  const { t } = useTranslation()
450
476
  const { colors } = useTheme()
451
477
  const Ionicons = loadIonicons()
@@ -623,6 +649,17 @@ function NearbyFlow({
623
649
  */
624
650
  const [receivedBroadcast, setReceivedBroadcast] = useState(true)
625
651
 
652
+ /**
653
+ * P1-1: the payee's `verification` for the shared success overlay. The
654
+ * overlay's TIMING is unchanged — still shown as soon as savePending
655
+ * resolves, before internalizeAction has necessarily run — but this gates
656
+ * whether it may claim the money is actually in the wallet yet. Starts
657
+ * 'pending' the instant the overlay appears (settleReceived, below) and is
658
+ * resolved once processPending settles: 'verified' on a credit, or
659
+ * 'not-credited' otherwise. See PaymentSuccessOverlay's `verification` doc.
660
+ */
661
+ const [receivedVerification, setReceivedVerification] = useState<'pending' | 'verified' | 'not-credited'>('verified')
662
+
626
663
  /**
627
664
  * A frame that was delivered but could not be persisted. Held so the payee can
628
665
  * retry against the SAME session: dropping it would lose a payment the payer
@@ -687,6 +724,16 @@ function NearbyFlow({
687
724
  const abortsRef = useRef<Set<AbortController>>(new Set())
688
725
  /** One-shot latch: two concurrent settles would both clear the spent check. */
689
726
  const settlingRef = useRef(false)
727
+ /**
728
+ * XR-097: whole-lifetime re-entrancy guard for executeSend, mirroring
729
+ * VaultTransferScreen's own `runningRef`. `canSend`/`phase` alone cannot
730
+ * stop a double-tap: both onPress events dispatch, and read the same
731
+ * pre-render `phase`, before React ever re-renders with the disabled
732
+ * button — so a second call that lands before the first one's first
733
+ * `await` still passes every check and builds a second, independently
734
+ * reserved payment.
735
+ */
736
+ const sendInFlightRef = useRef(false)
690
737
  /** Ignores the repeat reads multiScan produces while a scan is being handled. */
691
738
  const scanLatchRef = useRef(false)
692
739
  /** Assembles animated fountain parts across the continuous scanner's reads. */
@@ -915,6 +962,16 @@ function NearbyFlow({
915
962
  void confirm?.(false, 'save_failed')
916
963
  return
917
964
  }
965
+ // XR-098: latched HERE, synchronously, before the first await below —
966
+ // not after verification succeeds. Two calls that both start while this
967
+ // is still false (radio racing a QR scan) must not both pass the check
968
+ // above; setting it after `await verifyFramePayment(...)` left exactly
969
+ // that window open. Reset on every early-return branch below that
970
+ // intentionally leaves the request live for a genuine retry (a
971
+ // mismatch is not this device's fault) — `claimAndSavePending`'s own
972
+ // atomic claim (below) is still the backstop even if a caller reset
973
+ // this incorrectly.
974
+ settlingRef.current = true
918
975
 
919
976
  // (0a) What this frame actually pays this device. The figure below is the
920
977
  // satoshis of the AtomicBEEF output at `frame.outputIndex`, and it is
@@ -922,9 +979,26 @@ function NearbyFlow({
922
979
  // device derives — so it is both the real number and a proof the
923
980
  // payment is ours to spend. Nothing has latched and nothing has been
924
981
  // written, so every failure here is a provable "queued nothing".
982
+ //
983
+ // Keys come from the permissions manager; the BSV branch's SPV check
984
+ // takes its chain tracker from `storage`, the same services every
985
+ // other chain query here uses. Without either nothing can be shown
986
+ // to be ours, so the frame is declined having queued nothing.
987
+ let chainTracker: ChainTracker | null = null
988
+ try {
989
+ chainTracker = storage ? await storage.getServices().getChainTracker() : null
990
+ } catch {
991
+ chainTracker = null
992
+ }
993
+ if (!wallet || !chainTracker) {
994
+ void confirm?.(false, 'save_failed')
995
+ settlingRef.current = false
996
+ scanLatchRef.current = false
997
+ return
998
+ }
925
999
  let verified: VerifiedPayment
926
1000
  try {
927
- verified = await verifyFramePayment(wallet as unknown as DerivingWallet, frame, adminOriginator, {
1001
+ verified = await verifyFramePayment({ wallet, chainTracker }, frame, adminOriginator, {
928
1002
  // A token frame with no verifier is REFUSED, not credited: no
929
1003
  // verifier is no evidence, and verify.ts enforces that. Absent on a
930
1004
  // BSV request, where it is never read.
@@ -938,17 +1012,23 @@ function NearbyFlow({
938
1012
  } catch (e) {
939
1013
  // `not_mine` is a frame that was never for this request; `unparseable`
940
1014
  // is bytes that are not a transaction; `not_covered` is a token frame
941
- // whose evidence does not cover its own ancestry. All three leave the
942
- // request LIVE and unspent, exactly as a nonce mismatch does, so the
943
- // genuine payer can still complete.
1015
+ // whose evidence does not cover its own ancestry; `root_unverified` is
1016
+ // a block this device could not confirm (offline, headers behind). All
1017
+ // four leave the request LIVE and unspent, exactly as a nonce mismatch
1018
+ // does, so the genuine payer can still complete.
944
1019
  const kind = e instanceof FrameVerifyError ? e.kind : 'unparseable'
945
- void confirm?.(false, kind === 'not_mine' ? 'session_mismatch' : 'decode_failed')
1020
+ void confirm?.(false, declineReasonFor(kind))
1021
+ if (kind === 'root_unverified') {
1022
+ // Not a scanning mistake either: the remedy is on THIS device.
1023
+ setNotice({ text: t('local_pay_root_unverified'), tone: 'warning' })
1024
+ }
946
1025
  if (kind === 'not_covered') {
947
1026
  // The one refusal that is about the ISSUER's records rather than
948
1027
  // about this pair of devices, so it says so instead of reading as a
949
1028
  // scanning mistake.
950
1029
  setNotice({ text: t('token_cover_failed', { issuer: issuerNameFor(session.asset?.id) }), tone: 'warning' })
951
1030
  }
1031
+ settlingRef.current = false
952
1032
  scanLatchRef.current = false
953
1033
  setSessionMismatch(true)
954
1034
  setPhase('receive_wait')
@@ -965,6 +1045,7 @@ function NearbyFlow({
965
1045
  : session.asset !== undefined
966
1046
  if (assetMismatch) {
967
1047
  void confirm?.(false, 'session_mismatch')
1048
+ settlingRef.current = false
968
1049
  scanLatchRef.current = false
969
1050
  setSessionMismatch(true)
970
1051
  setPhase('receive_wait')
@@ -1009,6 +1090,7 @@ function NearbyFlow({
1009
1090
  amountDisagrees
1010
1091
  ) {
1011
1092
  void confirm?.(false, 'session_mismatch')
1093
+ settlingRef.current = false
1012
1094
  scanLatchRef.current = false
1013
1095
  setSessionMismatch(true)
1014
1096
  // Back to the waiting screen with the pairing QR still up, and restart
@@ -1018,7 +1100,8 @@ function NearbyFlow({
1018
1100
  return
1019
1101
  }
1020
1102
 
1021
- settlingRef.current = true
1103
+ // settlingRef was already latched at the top of this function (XR-098) —
1104
+ // nothing more to set here.
1022
1105
  setSessionMismatch(false)
1023
1106
  // The frame crossed the encrypted link and decoded against this session:
1024
1107
  // the peer is provably present. Presentation only — this drives nothing
@@ -1041,9 +1124,25 @@ function NearbyFlow({
1041
1124
  // Everything that can legitimately be reported as a payment failure lives
1042
1125
  // in here, and only in here. Past the closing brace the money is safe.
1043
1126
  try {
1044
- // (1) One-shot session guard, before anything is written. A re-scanned
1045
- // or replayed session must never credit twice.
1046
- if (await isSessionSpent(storage, session.sessionId)) {
1127
+ // (1)+(2)+(3), atomically (XR-098). The one-shot session guard, the
1128
+ // durable persist, and burning the session used to be three
1129
+ // separate operations — the guard under no lock at all, the other
1130
+ // two each under their own — so a concurrent delivery for the same
1131
+ // session (radio racing a QR scan, or any other overlap) could
1132
+ // pass the guard before either had written anything, and both
1133
+ // would durably queue a payment for a session meant to be spent
1134
+ // exactly once. `claimAndSavePending` runs all three inside one
1135
+ // lock, so the check-then-act sequence cannot interleave.
1136
+ //
1137
+ // `confirm` is only ever supplied by a radio receive path (the
1138
+ // listener effect above; the QR/retry callers below omit it) — the
1139
+ // same signal `Unsettled` already keys off of, reused here to
1140
+ // attribute the queue row to a transport. `via` is the radio
1141
+ // raceReceivers reported as the winner; the 'awdl' fallback covers
1142
+ // only the (unreachable in practice) case of a confirm handle with
1143
+ // no winner attached.
1144
+ const claim = await claimAndSavePending(storage, session.sessionId, frame, confirm ? (via ?? 'awdl') : 'qr')
1145
+ if (!claim.claimed) {
1047
1146
  // Not a failure for the PAYEE: that session's payment is already
1048
1147
  // queued. It is a decline for the PAYER, though, and must be — this
1049
1148
  // delivery queued nothing, and each executeSend builds a fresh
@@ -1055,32 +1154,6 @@ function NearbyFlow({
1055
1154
  setPhase('already_paid')
1056
1155
  return
1057
1156
  }
1058
-
1059
- // (2) Persist before anything else. Once this resolves the money cannot
1060
- // be lost to a crash, a dead network or a closed app.
1061
- //
1062
- // `confirm` is only ever supplied by a radio receive path (the
1063
- // listener effect above; the QR/retry callers below omit it) — the
1064
- // same signal `Unsettled` already keys off of, reused here to
1065
- // attribute the queue row to a transport. `via` is the radio
1066
- // raceReceivers reported as the winner; the 'awdl' fallback covers
1067
- // only the (unreachable in practice) case of a confirm handle with
1068
- // no winner attached.
1069
- await savePending(storage, frame, confirm ? (via ?? 'awdl') : 'qr')
1070
-
1071
- // (3) Only now is it safe to burn the session. Doing this first would
1072
- // mean a crash in between marks the session handled while nothing
1073
- // was persisted — unrecoverable, because sessions are one-shot.
1074
- try {
1075
- await markSessionSpent(storage, session.sessionId)
1076
- } catch (e) {
1077
- // The frame is already queued, so this is not a payment failure and
1078
- // must not be reported as one. internalizeAction is idempotent on a
1079
- // repeat of the same output — the toolbox merges "wallet payment"
1080
- // internalizations by txid and skips the second credit — so a replay
1081
- // from here cannot double-credit.
1082
- console.warn('[localpay] markSessionSpent failed:', messageOf(e))
1083
- }
1084
1157
  } catch (e) {
1085
1158
  // Reached only while the frame is still un-persisted, so this is a real
1086
1159
  // failure. Keep the frame and the session so the payee can retry the
@@ -1113,10 +1186,10 @@ function NearbyFlow({
1113
1186
  session.asset
1114
1187
  ? // Never `null` on the token path: falling through to the satoshi
1115
1188
  // renderer would print base units as satoshis.
1116
- formatTokenAmountWithUnit(satoshis, {
1189
+ (formatTokenAmountWithUnit(satoshis, {
1117
1190
  decimals: session.asset.decimals ?? 0,
1118
1191
  ticker: session.asset.ticker ?? ''
1119
- }) ?? t('token_row_amount_pending')
1192
+ }) ?? t('token_row_amount_pending'))
1120
1193
  : null
1121
1194
  )
1122
1195
  // Credited and spendable — and not yet confirmed by the issuer. Both are
@@ -1132,6 +1205,10 @@ function NearbyFlow({
1132
1205
  // this same mount left behind — internalizing corrects it below if the
1133
1206
  // payment credits without a broadcast yet.
1134
1207
  setReceivedBroadcast(true)
1208
+ // P1-1: the overlay is up now, but internalizeAction has not run yet —
1209
+ // 'pending' shows the neutral confirming copy until the block below
1210
+ // resolves it one way or the other.
1211
+ setReceivedVerification('pending')
1135
1212
  setUnsettled(null)
1136
1213
  // Who paid. Starts a best-effort identity lookup for the presence row;
1137
1214
  // deliberately after the durable write, and never awaited.
@@ -1149,6 +1226,7 @@ function NearbyFlow({
1149
1226
  // is neutral.
1150
1227
  if (!wallet) {
1151
1228
  setNotice({ text: t('local_pay_queued'), tone: 'info' })
1229
+ setReceivedVerification('not-credited')
1152
1230
  return
1153
1231
  }
1154
1232
  try {
@@ -1185,6 +1263,11 @@ function NearbyFlow({
1185
1263
  setNotice(
1186
1264
  credited ? { text: t('local_pay_added'), tone: 'success' } : { text: t('local_pay_queued'), tone: 'info' }
1187
1265
  )
1266
+ // P1-1: only a genuine credit earns the overlay's green claim; a
1267
+ // queued-but-not-yet-credited result gets the neutral not-credited
1268
+ // copy instead — the money is safe (still queued, will resolve on
1269
+ // the next retry) but not yet in the wallet.
1270
+ setReceivedVerification(credited ? 'verified' : 'not-credited')
1188
1271
  // The success overlay is already up by this point (set unconditionally
1189
1272
  // at the top of this function) — this only refines its `broadcast`
1190
1273
  // flag once storage confirms a network hand-off. Not reachable when
@@ -1206,6 +1289,7 @@ function NearbyFlow({
1206
1289
  } catch (e) {
1207
1290
  console.warn('[localpay] processPending failed:', messageOf(e))
1208
1291
  setNotice({ text: t('local_pay_queued'), tone: 'info' })
1292
+ setReceivedVerification('not-credited')
1209
1293
  }
1210
1294
  },
1211
1295
  [storage, wallet, adminOriginator, coverVerifier, issuerNameFor, mandala.runtime, fail, t]
@@ -1272,84 +1356,88 @@ function NearbyFlow({
1272
1356
 
1273
1357
  // ── Receive: mint the request ──
1274
1358
 
1275
- const startRequest = useCallback(async (requested?: number, asset?: SessionAsset) => {
1276
- // Zero (or blank) is the user asking the payer to choose, so it becomes an
1277
- // open session rather than a rejected input. Undefined, never 0 — the codec
1278
- // refuses a non-positive amount precisely so a corrupt zero can never be
1279
- // read back as "any amount".
1280
- const sats = requested !== undefined && Number.isFinite(requested) && requested > 0 ? Math.round(requested) : undefined
1281
- // Gate on storage too, not just the wallet. Advertising with storage null
1282
- // means a payer can deliver a frame the payee then cannot persist, after the
1283
- // transport has already acked it as accepted.
1284
- if (!wallet || !storage) {
1285
- fail('generic', t('wallet_not_ready'))
1286
- return
1287
- }
1288
- setPhase('receive_minting')
1289
- setRadioErrors({})
1290
- setSessionQrBroken(false)
1291
- setSessionMismatch(false)
1292
- try {
1293
- // Prompt-free and re-read on every mint, unlike supportsAwdl (whose probe
1294
- // can raise the Local Network prompt): a radio switched on since the last
1295
- // request must be picked up without leaving the screen. `notDetermined`
1296
- // on iOS counts as supported so the prompt can follow inside prepareBle.
1297
- const bleHere = localSupportsBle()
1298
- // Everything the request needs, in parallel (spec §4): the identity key,
1299
- // the two wallet nonces, the prompt-free device probe and — only where
1300
- // this device has a BLE radio — the one call that may show the iOS
1301
- // Bluetooth prompt. It appears here, at the moment the user has asked to
1302
- // receive a nearby payment, the same moment the Local Network prompt
1303
- // already can. Minting is never slower than the slowest of these, and
1304
- // both probes are bounded (BLE_PREPARE_TIMEOUT_MS, DEFAULT_NET_BUDGET_MS).
1305
- const [{ publicKey: identityKey }, derivationPrefix, derivationSuffix, probe, bleNow] = await Promise.all([
1306
- wallet.getPublicKey({ identityKey: true }, adminOriginator),
1307
- createNonce(wallet, 'self', adminOriginator),
1308
- createNonce(wallet, 'self', adminOriginator),
1309
- probeDeviceCaps(),
1310
- bleHere ? prepareBle() : Promise.resolve<BluetoothState>('unsupported')
1311
- ])
1312
- setBleState(bleNow)
1313
- // Advertise BLE only where this device will actually listen on it: radio
1314
- // powered on AND (Android) the runtime grants landed. A CAP_BLE bit with
1315
- // no advertiser behind it would walk every cross-OS payer into a 6 s
1316
- // connect timeout before the fountain.
1317
- const bleLive = bleNow === 'poweredOn' && blePermitted
1318
- const session = mintSession({
1319
- identityKey,
1320
- // Satoshis, or base units of `asset` — `isRequestableAmount` is
1321
- // unit-agnostic and the asset travels with the figure, so the payer
1322
- // can never read one as the other.
1323
- amount: sats,
1324
- asset,
1325
- derivationPrefix,
1326
- derivationSuffix,
1327
- // Caps advertise what this payee can DO; the payer's ladder picks the
1328
- // highest rung both sides share, QR being the floor.
1329
- supportsAwdl,
1330
- supportsNearby: nearbyReady,
1331
- supportsBle: bleLive,
1332
- // Reversed role (spec 2026-09-03): an iOS payee also scans for a payer
1333
- // that advertises, so an Android payer never has to be the central.
1334
- // ble.ts starts that scan alongside the advertised listener.
1335
- supportsBleScan: bleLive && Platform.OS === 'ios',
1336
- // prepare() settles the Bluetooth answer the prompt-free probe may have
1337
- // read as 'unknown' a moment earlier, so where it ran it overrides the
1338
- // probe's field. The hint bits are copy for the payer, not dispatch.
1339
- hints: capsFromProbe({ ...probe, bluetooth: bleHere ? bleNow : probe.bluetooth }),
1340
- os: Platform.OS === 'ios' ? 'ios' : 'android'
1341
- })
1342
- // Same reason as the payer's side: the drain re-derives this device's own
1343
- // settlement rows from sealed frames, and the key that opens them lives
1344
- // only here, for this process.
1345
- if (session.asset) rememberSessionPsk(session.psk)
1346
- setRole('payee')
1347
- setHostedSession(session)
1348
- setPhase('receive_wait')
1349
- } catch (e) {
1350
- fail('generic', messageOf(e))
1351
- }
1352
- }, [wallet, storage, adminOriginator, supportsAwdl, nearbyReady, blePermitted, fail, t])
1359
+ const startRequest = useCallback(
1360
+ async (requested?: number, asset?: SessionAsset) => {
1361
+ // Zero (or blank) is the user asking the payer to choose, so it becomes an
1362
+ // open session rather than a rejected input. Undefined, never 0 — the codec
1363
+ // refuses a non-positive amount precisely so a corrupt zero can never be
1364
+ // read back as "any amount".
1365
+ const sats =
1366
+ requested !== undefined && Number.isFinite(requested) && requested > 0 ? Math.round(requested) : undefined
1367
+ // Gate on storage too, not just the wallet. Advertising with storage null
1368
+ // means a payer can deliver a frame the payee then cannot persist, after the
1369
+ // transport has already acked it as accepted.
1370
+ if (!wallet || !storage) {
1371
+ fail('generic', t('wallet_not_ready'))
1372
+ return
1373
+ }
1374
+ setPhase('receive_minting')
1375
+ setRadioErrors({})
1376
+ setSessionQrBroken(false)
1377
+ setSessionMismatch(false)
1378
+ try {
1379
+ // Prompt-free and re-read on every mint, unlike supportsAwdl (whose probe
1380
+ // can raise the Local Network prompt): a radio switched on since the last
1381
+ // request must be picked up without leaving the screen. `notDetermined`
1382
+ // on iOS counts as supported so the prompt can follow inside prepareBle.
1383
+ const bleHere = localSupportsBle()
1384
+ // Everything the request needs, in parallel (spec §4): the identity key,
1385
+ // the two wallet nonces, the prompt-free device probe and — only where
1386
+ // this device has a BLE radio — the one call that may show the iOS
1387
+ // Bluetooth prompt. It appears here, at the moment the user has asked to
1388
+ // receive a nearby payment, the same moment the Local Network prompt
1389
+ // already can. Minting is never slower than the slowest of these, and
1390
+ // both probes are bounded (BLE_PREPARE_TIMEOUT_MS, DEFAULT_NET_BUDGET_MS).
1391
+ const [{ publicKey: identityKey }, derivationPrefix, derivationSuffix, probe, bleNow] = await Promise.all([
1392
+ wallet.getPublicKey({ identityKey: true }, adminOriginator),
1393
+ createNonce(wallet, 'self', adminOriginator),
1394
+ createNonce(wallet, 'self', adminOriginator),
1395
+ probeDeviceCaps(),
1396
+ bleHere ? prepareBle() : Promise.resolve<BluetoothState>('unsupported')
1397
+ ])
1398
+ setBleState(bleNow)
1399
+ // Advertise BLE only where this device will actually listen on it: radio
1400
+ // powered on AND (Android) the runtime grants landed. A CAP_BLE bit with
1401
+ // no advertiser behind it would walk every cross-OS payer into a 6 s
1402
+ // connect timeout before the fountain.
1403
+ const bleLive = bleNow === 'poweredOn' && blePermitted
1404
+ const session = mintSession({
1405
+ identityKey,
1406
+ // Satoshis, or base units of `asset` — `isRequestableAmount` is
1407
+ // unit-agnostic and the asset travels with the figure, so the payer
1408
+ // can never read one as the other.
1409
+ amount: sats,
1410
+ asset,
1411
+ derivationPrefix,
1412
+ derivationSuffix,
1413
+ // Caps advertise what this payee can DO; the payer's ladder picks the
1414
+ // highest rung both sides share, QR being the floor.
1415
+ supportsAwdl,
1416
+ supportsNearby: nearbyReady,
1417
+ supportsBle: bleLive,
1418
+ // Reversed role (spec 2026-09-03): an iOS payee also scans for a payer
1419
+ // that advertises, so an Android payer never has to be the central.
1420
+ // ble.ts starts that scan alongside the advertised listener.
1421
+ supportsBleScan: bleLive && Platform.OS === 'ios',
1422
+ // prepare() settles the Bluetooth answer the prompt-free probe may have
1423
+ // read as 'unknown' a moment earlier, so where it ran it overrides the
1424
+ // probe's field. The hint bits are copy for the payer, not dispatch.
1425
+ hints: capsFromProbe({ ...probe, bluetooth: bleHere ? bleNow : probe.bluetooth }),
1426
+ os: Platform.OS === 'ios' ? 'ios' : 'android'
1427
+ })
1428
+ // Same reason as the payer's side: the drain re-derives this device's own
1429
+ // settlement rows from sealed frames, and the key that opens them lives
1430
+ // only here, for this process.
1431
+ if (session.asset) rememberSessionPsk(session.psk)
1432
+ setRole('payee')
1433
+ setHostedSession(session)
1434
+ setPhase('receive_wait')
1435
+ } catch (e) {
1436
+ fail('generic', messageOf(e))
1437
+ }
1438
+ },
1439
+ [wallet, storage, adminOriginator, supportsAwdl, nearbyReady, blePermitted, fail, t]
1440
+ )
1353
1441
 
1354
1442
  // ── Receive: scan the payer's frame ──
1355
1443
 
@@ -1491,8 +1579,9 @@ function NearbyFlow({
1491
1579
  * selectTransport() reaches through to localSupportsAwdl(), which is a native
1492
1580
  * call, and the confirm screen reads it twice on every render.
1493
1581
  *
1494
- * Declared above executeSend on purpose — a useCallback dependency array is
1495
- * evaluated at render time, so referencing it from below would hit the TDZ.
1582
+ * Declared above executeSendLocked on purpose — a useCallback dependency
1583
+ * array is evaluated at render time, so referencing it from below would
1584
+ * hit the TDZ.
1496
1585
  */
1497
1586
  const sendKind = useMemo(() => (scannedSession ? selectTransport(scannedSession) : null), [scannedSession])
1498
1587
 
@@ -1630,7 +1719,10 @@ function NearbyFlow({
1630
1719
  } catch (e) {
1631
1720
  console.warn('[localpay] abortAction failed:', messageOf(e))
1632
1721
  if (storage) {
1633
- await queuePendingAbort(storage, { reference, originator: adminOriginator }).catch(() => undefined)
1722
+ await queuePendingAbort(storage, { reference, originator: adminOriginator }, {
1723
+ wallet: wallet as unknown as PendingAbortTagWallet,
1724
+ originator: adminOriginator
1725
+ }).catch(() => undefined)
1634
1726
  }
1635
1727
  }
1636
1728
  })()
@@ -1654,7 +1746,7 @@ function NearbyFlow({
1654
1746
 
1655
1747
  // ── Send: build and deliver ──
1656
1748
 
1657
- const executeSend = useCallback(async () => {
1749
+ const executeSendLocked = useCallback(async () => {
1658
1750
  const session = scannedSession
1659
1751
  if (!session || !sendKind) return
1660
1752
  // Guards the open-request path: with no figure there is nothing to build,
@@ -1670,6 +1762,37 @@ function NearbyFlow({
1670
1762
  const controller = new AbortController()
1671
1763
  registry.add(controller)
1672
1764
 
1765
+ // XR-096: keeps a built payment reserved instead of an untracked orphan
1766
+ // for the two genuinely ambiguous radio outcomes below — a screen
1767
+ // blur/unmount mid-send, and a radio failure with no representable QR
1768
+ // fallback. Mirrors the QR screen's own "back out" park exactly (see
1769
+ // completeQrDelivery's `!release` branch). Best-effort and never throws:
1770
+ // a park failure must not turn an already uncertain delivery into a
1771
+ // crash, and the built noSend action — not this bookkeeping row — is
1772
+ // what actually matters.
1773
+ const parkUncertainDelivery = async (
1774
+ built: Awaited<ReturnType<typeof buildPaymentFrame>>,
1775
+ framePayload: string
1776
+ ) => {
1777
+ if (!storage || !built.txid) return
1778
+ try {
1779
+ await parkSentPaymentOffline({
1780
+ storage,
1781
+ txid: built.txid,
1782
+ framePayload,
1783
+ ...(session.asset
1784
+ ? {
1785
+ frame: built.frame,
1786
+ onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
1787
+ reference: built.reference
1788
+ }
1789
+ : {})
1790
+ })
1791
+ } catch (e) {
1792
+ console.warn('[localpay] could not park an uncertain delivery:', e instanceof Error ? e.message : e)
1793
+ }
1794
+ }
1795
+
1673
1796
  // A token request this wallet is not set up for is refused before anything
1674
1797
  // is built: v1 resolves one overlay, and paying a token whose issuer this
1675
1798
  // device cannot reach would produce a frame nobody can settle.
@@ -1700,7 +1823,18 @@ function NearbyFlow({
1700
1823
  // hand-over comes first, unconditionally, so a face-to-face payment
1701
1824
  // never waits on a network.
1702
1825
  session.asset ? mandala.runtime?.tokenBuildDeps : undefined,
1703
- note
1826
+ note,
1827
+ // XR-088: a build failure whose own release also fails used to be
1828
+ // logged only — no durable retry record at all — unlike the
1829
+ // decline path's `queueFailedAbort` a few lines below. Same queue,
1830
+ // same replay on the next wallet build.
1831
+ async reference => {
1832
+ if (!storage) return
1833
+ await queuePendingAbort(storage, { reference, originator: adminOriginator }, {
1834
+ wallet: wallet as unknown as PendingAbortTagWallet,
1835
+ originator: adminOriginator
1836
+ })
1837
+ }
1704
1838
  )
1705
1839
  } catch (e) {
1706
1840
  // Build errors are wallet errors and must keep their own message. A
@@ -1756,7 +1890,17 @@ function NearbyFlow({
1756
1890
  }
1757
1891
  ack = await radio.send(session, built.frame, controller.signal)
1758
1892
  } catch (e) {
1759
- if (controller.signal.aborted) return
1893
+ if (controller.signal.aborted) {
1894
+ // XR-096: the screen blurred or unmounted while this native send
1895
+ // was in flight. The OS may already have finished handing the
1896
+ // bytes to the peer even though the AbortController fired — a lost
1897
+ // ack does not prove non-delivery on the happy path just above, and
1898
+ // an abort proves even less — so this must not be treated as "never
1899
+ // delivered". Park instead of leaving the signed noSend action with
1900
+ // no durable trace beyond the raw wallet transaction row.
1901
+ await parkUncertainDelivery(built, sealedToQr(sealFrame(built.frame, session.psk)))
1902
+ return
1903
+ }
1760
1904
  // The radio path failed: connect timeout (radios off, peer gone),
1761
1905
  // Local Network denial, or a lost ack. The frame is signed and noSend,
1762
1906
  // so the QR still completes this payment — fall straight through to
@@ -1770,7 +1914,12 @@ function NearbyFlow({
1770
1914
  // the QR string below share these bytes.
1771
1915
  const sealed = sealFrame(built.frame, session.psk)
1772
1916
  if (sealed.length > MAX_MESSAGE_BYTES) {
1773
- // No radio and no representable code: the one genuinely dead end.
1917
+ // No radio and no representable code: the frame cannot be shown,
1918
+ // but it can still be parked (XR-096) — that row also unlocks a
1919
+ // message-box resend later, which has no QR size limit — rather
1920
+ // than left as an untracked orphan reachable only by the
1921
+ // unrestricted generic Abort action.
1922
+ await parkUncertainDelivery(built, sealedToQr(sealed))
1774
1923
  fail(looksLikeLocalNetworkDenial(message) ? 'network' : 'generic', t('local_pay_too_large'))
1775
1924
  return
1776
1925
  }
@@ -1809,14 +1958,83 @@ function NearbyFlow({
1809
1958
  // The noSend action's own reference, onto the settlement row:
1810
1959
  // it is what lets the abort guard tell a handed-over token
1811
1960
  // payment from an abandoned one (core/mandala/abortGuard.ts).
1812
- reference: built.reference
1961
+ reference: built.reference,
1962
+ // XR-036: this rail acked over the radio and never sealed a
1963
+ // QR, so unlike the QR/fallback paths it had no framePayload
1964
+ // to give FIX G's re-derivation. Sealed here purely for local
1965
+ // durability — never rendered — so a restart that loses the
1966
+ // in-memory session PSK still has bytes to re-derive this
1967
+ // settlement row from if the journal write below did not land.
1968
+ ...(() => {
1969
+ try {
1970
+ return { framePayload: sealedToQr(sealFrame(built.frame, session.psk)) }
1971
+ } catch (e) {
1972
+ console.warn('[localpay] could not seal a fallback framePayload for the queue row:', e)
1973
+ return {}
1974
+ }
1975
+ })()
1813
1976
  }
1814
1977
  : {})
1815
1978
  })
1816
1979
  },
1817
1980
  queueFailedAbort: async reference => {
1818
1981
  if (!storage) return
1819
- await queuePendingAbort(storage, { reference, originator: adminOriginator })
1982
+ await queuePendingAbort(storage, { reference, originator: adminOriginator }, {
1983
+ wallet: wallet as unknown as PendingAbortTagWallet,
1984
+ originator: adminOriginator
1985
+ })
1986
+ },
1987
+ // P1-3: the payee's decline is unverifiable from here — watch the
1988
+ // txid so a later reappearance on chain (the payee's claim was wrong,
1989
+ // or dishonest) is surfaced instead of missed. See build.ts's
1990
+ // `watchDeclinedAbort` doc and WalletContext's reconnect-time
1991
+ // `verifyDeclinedAborts` pass.
1992
+ watchDeclinedAbort: async entry => {
1993
+ if (!storage) return
1994
+ await queueDeclinedAbortWatch(storage, {
1995
+ ...entry,
1996
+ peerIdentityKey: session.identityKey,
1997
+ at: Date.now()
1998
+ })
1999
+ },
2000
+ // XR-103: the same call WalletContext already makes for the identical
2001
+ // question (`verifyDeclinedAborts`) — asked here too so a decline
2002
+ // that lies about a transaction already on the network is caught
2003
+ // before the abort runs, not just surfaced afterwards.
2004
+ checkChainStatus: async txids => {
2005
+ if (!storage) return {}
2006
+ const services = storage.getServices() as {
2007
+ getStatusForTxids?: (txids: string[]) => Promise<{ results?: { txid: string; status: string }[] }>
2008
+ }
2009
+ if (typeof services.getStatusForTxids !== 'function') return {}
2010
+ return services.getStatusForTxids(txids)
2011
+ },
2012
+ // XR-095: ask the chain before releasing a decline's inputs — the
2013
+ // same BSV-rail check `cancelParkedPayment` runs — so a payee that
2014
+ // already broadcast their copy (whatever the ack claimed) is never
2015
+ // raced against a release. Runs after `checkChainStatus` above; that
2016
+ // probe already handles the same "already known" question up front,
2017
+ // so this is the second, independent layer this rail wires in
2018
+ // addition.
2019
+ chainAlreadyKnows: storage ? (txid: string) => chainAlreadyKnows(storage, txid) : undefined,
2020
+ // Genuinely offline, so the chain cannot be asked either way: keep the
2021
+ // inputs reserved instead of guessing, the same way backing out of the
2022
+ // QR screen already does. The frame is re-sealed so the payer can
2023
+ // still show it as a code later, from this parked row.
2024
+ parkUnverifiable: async (txid: string) => {
2025
+ if (!storage) return
2026
+ await parkSentPaymentOffline({
2027
+ storage,
2028
+ txid,
2029
+ framePayload: sealedToQr(sealFrame(built.frame, session.psk)),
2030
+ ...(session.asset
2031
+ ? {
2032
+ frame: built.frame,
2033
+ onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
2034
+ reference: built.reference
2035
+ }
2036
+ : {})
2037
+ })
1820
2038
  }
1821
2039
  })
1822
2040
  if (controller.signal.aborted) return
@@ -1863,6 +2081,7 @@ function NearbyFlow({
1863
2081
  ? await readSettlementAck(ack, {
1864
2082
  overlayIdentityKey: session.asset.overlayIdentityKey,
1865
2083
  expectTxid: built.txid,
2084
+ expectVout: built.frame.outputIndex,
1866
2085
  verify
1867
2086
  })
1868
2087
  : undefined
@@ -1893,6 +2112,25 @@ function NearbyFlow({
1893
2112
  t
1894
2113
  ])
1895
2114
 
2115
+ // XR-097: the actual onPress target. A synchronous, whole-lifetime
2116
+ // re-entrancy guard around executeSendLocked's entire body — set as the
2117
+ // very first statement, before any `await` — so a second call dispatched
2118
+ // before the first one's first `await` (a double-tap, or any two
2119
+ // overlapping invocations) sees the latch already held instead of passing
2120
+ // every check `executeSendLocked` itself makes and building a second,
2121
+ // independently reserved payment. Every early `return` inside
2122
+ // `executeSendLocked` still releases it via this `finally`, since none of
2123
+ // those paths build anything.
2124
+ const executeSend = useCallback(async () => {
2125
+ if (sendInFlightRef.current) return
2126
+ sendInFlightRef.current = true
2127
+ try {
2128
+ await executeSendLocked()
2129
+ } finally {
2130
+ sendInFlightRef.current = false
2131
+ }
2132
+ }, [executeSendLocked])
2133
+
1896
2134
  // ── Send: the payer asserts QR delivery ──
1897
2135
  //
1898
2136
  // The QR path has no ack channel, so "the payee has it" is the user's claim,
@@ -1906,106 +2144,118 @@ function NearbyFlow({
1906
2144
  // and once that session is gone, the action's payee label and derivation
1907
2145
  // customInstructions still let the payment be re-sent through the message box
1908
2146
  // from its own row in the activity list.
1909
- const completeQrDelivery = useCallback(async (opts?: { celebrate?: boolean; release?: boolean }) => {
1910
- const celebrate = opts?.celebrate !== false
1911
- // Done means "they have it" — the payment is released and the drain posts
1912
- // it. Backing out means nothing of the kind, so the frame is kept and the
1913
- // transaction stays cancellable instead. Releasing on the way out is what
1914
- // made Back send the payment outright.
1915
- const release = opts?.release !== false
1916
- const built = builtRef.current
1917
- const session = scannedSession
1918
- // `paymentQr` is this exact frame already sealed for display — the Done
1919
- // button that calls this only renders while it is set (see the send_qr
1920
- // stage below) — so it is reused as the queue row's framePayload rather
1921
- // than sealing the frame a third time.
1922
- const framePayload = paymentQr
1923
- if (!built || !wallet || !session || !framePayload) {
1924
- // No handle (e.g. re-entry after reset, which clears builtRef and
1925
- // scannedSession together): nothing to decide, just close.
2147
+ const completeQrDelivery = useCallback(
2148
+ async (opts?: { celebrate?: boolean; release?: boolean }) => {
2149
+ const celebrate = opts?.celebrate !== false
2150
+ // Done means "they have it" — the payment is released and the drain posts
2151
+ // it. Backing out means nothing of the kind, so the frame is kept and the
2152
+ // transaction stays cancellable instead. Releasing on the way out is what
2153
+ // made Back send the payment outright.
2154
+ const release = opts?.release !== false
2155
+ const built = builtRef.current
2156
+ const session = scannedSession
2157
+ // `paymentQr` is this exact frame already sealed for display — the Done
2158
+ // button that calls this only renders while it is set (see the send_qr
2159
+ // stage below) — so it is reused as the queue row's framePayload rather
2160
+ // than sealing the frame a third time.
2161
+ const framePayload = paymentQr
2162
+ if (!built || !wallet || !session || !framePayload) {
2163
+ // No handle (e.g. re-entry after reset, which clears builtRef and
2164
+ // scannedSession together): nothing to decide, just close.
2165
+ if (celebrate) {
2166
+ setSettledAmount(payAmount)
2167
+ setRole('payer')
2168
+ setNotice(null)
2169
+ setPhase('done')
2170
+ }
2171
+ return
2172
+ }
2173
+ builtRef.current = null
1926
2174
  if (celebrate) {
1927
- setSettledAmount(payAmount)
1928
- setRole('payer')
2175
+ setPhase('send_working')
1929
2176
  setNotice(null)
1930
- setPhase('done')
1931
2177
  }
1932
- return
1933
- }
1934
- builtRef.current = null
1935
- if (celebrate) {
1936
- setPhase('send_working')
1937
- setNotice(null)
1938
- }
1939
2178
 
1940
- // Backing out never goes through finalizeDelivery: that path broadcasts
1941
- // after the hold whenever the device is online, so parking inside it would
1942
- // still have sent the payment. Park and stop.
1943
- if (!release) {
1944
- try {
1945
- if (storage && built.txid) {
1946
- await parkSentPaymentOffline({
1947
- storage,
1948
- txid: built.txid,
1949
- framePayload,
1950
- // Token sessions only — see the hold callback below for why.
1951
- ...(session.asset
1952
- ? {
1953
- frame: built.frame,
1954
- onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
1955
- // The noSend action's own reference, onto the settlement row:
1956
- // it is what lets the abort guard tell a handed-over token
1957
- // payment from an abandoned one (core/mandala/abortGuard.ts).
1958
- reference: built.reference
1959
- }
1960
- : {})
1961
- })
2179
+ // Backing out never goes through finalizeDelivery: that path broadcasts
2180
+ // after the hold whenever the device is online, so parking inside it would
2181
+ // still have sent the payment. Park and stop.
2182
+ if (!release) {
2183
+ try {
2184
+ if (storage && built.txid) {
2185
+ await parkSentPaymentOffline({
2186
+ storage,
2187
+ txid: built.txid,
2188
+ framePayload,
2189
+ // Token sessions only — see the hold callback below for why.
2190
+ ...(session.asset
2191
+ ? {
2192
+ frame: built.frame,
2193
+ onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
2194
+ // The noSend action's own reference, onto the settlement row:
2195
+ // it is what lets the abort guard tell a handed-over token
2196
+ // payment from an abandoned one (core/mandala/abortGuard.ts).
2197
+ reference: built.reference
2198
+ }
2199
+ : {})
2200
+ })
2201
+ }
2202
+ } catch (e) {
2203
+ console.warn('[localpay] could not park the payment:', e instanceof Error ? e.message : e)
1962
2204
  }
1963
- } catch (e) {
1964
- console.warn('[localpay] could not park the payment:', e instanceof Error ? e.message : e)
2205
+ return
1965
2206
  }
1966
- return
1967
- }
1968
2207
 
1969
- const outcome = await finalizeDelivery(wallet as unknown as PayingWalletArg, built, { ok: true }, adminOriginator, {
1970
- hold: async txid => {
1971
- if (!storage) throw new Error('no local storage to queue this payment in')
1972
- await holdSentPaymentOffline({
1973
- storage,
1974
- txid,
1975
- framePayload,
1976
- // Token sessions only: same reasoning as the executeSend hold call —
1977
- // the plaintext frame and the journal hook, so a restart does not
1978
- // strand this payer's settlement row.
1979
- ...(session.asset
1980
- ? {
1981
- frame: built.frame,
1982
- onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
1983
- // The noSend action's own reference, onto the settlement row:
1984
- // it is what lets the abort guard tell a handed-over token
1985
- // payment from an abandoned one (core/mandala/abortGuard.ts).
1986
- reference: built.reference
1987
- }
1988
- : {})
1989
- })
1990
- },
1991
- queueFailedAbort: async reference => {
1992
- if (!storage) return
1993
- await queuePendingAbort(storage, { reference, originator: adminOriginator })
2208
+ const outcome = await finalizeDelivery(
2209
+ wallet as unknown as PayingWalletArg,
2210
+ built,
2211
+ { ok: true },
2212
+ adminOriginator,
2213
+ {
2214
+ hold: async txid => {
2215
+ if (!storage) throw new Error('no local storage to queue this payment in')
2216
+ await holdSentPaymentOffline({
2217
+ storage,
2218
+ txid,
2219
+ framePayload,
2220
+ // Token sessions only: same reasoning as the executeSend hold call —
2221
+ // the plaintext frame and the journal hook, so a restart does not
2222
+ // strand this payer's settlement row.
2223
+ ...(session.asset
2224
+ ? {
2225
+ frame: built.frame,
2226
+ onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
2227
+ // The noSend action's own reference, onto the settlement row:
2228
+ // it is what lets the abort guard tell a handed-over token
2229
+ // payment from an abandoned one (core/mandala/abortGuard.ts).
2230
+ reference: built.reference
2231
+ }
2232
+ : {})
2233
+ })
2234
+ },
2235
+ queueFailedAbort: async reference => {
2236
+ if (!storage) return
2237
+ await queuePendingAbort(storage, { reference, originator: adminOriginator }, {
2238
+ wallet: wallet as unknown as PendingAbortTagWallet,
2239
+ originator: adminOriginator
2240
+ })
2241
+ }
2242
+ }
2243
+ )
2244
+ if (outcome.kind === 'sent' && outcome.broadcast === 'pending') {
2245
+ console.warn('[localpay] QR delivery queued or broadcast pending:', outcome.detail ?? '')
2246
+ if (celebrate) setNotice({ text: t('local_pay_broadcast_pending'), tone: 'warning' })
1994
2247
  }
1995
- })
1996
- if (outcome.kind === 'sent' && outcome.broadcast === 'pending') {
1997
- console.warn('[localpay] QR delivery queued or broadcast pending:', outcome.detail ?? '')
1998
- if (celebrate) setNotice({ text: t('local_pay_broadcast_pending'), tone: 'warning' })
1999
- }
2000
- if (celebrate) {
2001
- setSettledAmount(built.satoshis)
2002
- // This rail has no ack payload to read σ_I from, so the receipt opens as
2003
- // "settling" and the writer's own submit is what may settle it.
2004
- if (session.asset) writeTokenReceipt(session.asset, built, false)
2005
- setRole('payer')
2006
- setPhase('done')
2007
- }
2008
- }, [wallet, storage, adminOriginator, payAmount, scannedSession, paymentQr, mandala.runtime, writeTokenReceipt, t])
2248
+ if (celebrate) {
2249
+ setSettledAmount(built.satoshis)
2250
+ // This rail has no ack payload to read σ_I from, so the receipt opens as
2251
+ // "settling" and the writer's own submit is what may settle it.
2252
+ if (session.asset) writeTokenReceipt(session.asset, built, false)
2253
+ setRole('payer')
2254
+ setPhase('done')
2255
+ }
2256
+ },
2257
+ [wallet, storage, adminOriginator, payAmount, scannedSession, paymentQr, mandala.runtime, writeTokenReceipt, t]
2258
+ )
2009
2259
 
2010
2260
  // ── Send: leave send_qr without Done ──
2011
2261
  //
@@ -2589,7 +2839,11 @@ function NearbyFlow({
2589
2839
  maxLength={280}
2590
2840
  style={[
2591
2841
  styles.noteInput,
2592
- { backgroundColor: colors.backgroundSecondary, borderColor: colors.separator, color: colors.textPrimary }
2842
+ {
2843
+ backgroundColor: colors.backgroundSecondary,
2844
+ borderColor: colors.separator,
2845
+ color: colors.textPrimary
2846
+ }
2593
2847
  ]}
2594
2848
  />
2595
2849
  </PayField>
@@ -2843,8 +3097,14 @@ function NearbyFlow({
2843
3097
  // A token receipt carries its own settlement sentence; the satoshi
2844
3098
  // broadcast flag would add a second, contradictory one.
2845
3099
  broadcast={role === 'payer' || settledTokenText ? undefined : receivedBroadcast}
3100
+ // P1-1: irrelevant on the payer side (their money already left,
3101
+ // nothing left to confirm here) — 'verified' there keeps the
3102
+ // overlay's ordinary green claim exactly as before this existed.
3103
+ verification={role === 'payer' ? 'verified' : receivedVerification}
2846
3104
  recipientName={
2847
- role === 'payer' ? (peerName ?? (scannedSession ? abbreviateKey(scannedSession.identityKey) : undefined)) : undefined
3105
+ role === 'payer'
3106
+ ? (peerName ?? (scannedSession ? abbreviateKey(scannedSession.identityKey) : undefined))
3107
+ : undefined
2848
3108
  }
2849
3109
  // The overlay navigates to the wallet after this; goBack ends the
2850
3110
  // session and resets the cell so /pay is not left mid-flow beneath.