@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
@@ -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
111
  import { Beef, createNonce, 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,
@@ -397,20 +413,35 @@ function satsFrom(text: string): number {
397
413
  * asset this wallet holds (executeSend refuses anything else), and a
398
414
  * `decimals` the registry answered is the figure the overlay stood behind —
399
415
  * 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).
416
+ * would otherwise show 2,500.00 USDX as "0.2500".
417
+ *
418
+ * XR-091: the session's own block — whatever the payee's wallet wrote into
419
+ * the QR — is NEVER trusted as a substitute once a REAL local holding exists
420
+ * for this asset (`held` present) but this device's own metadata lookup for
421
+ * it failed or has not completed (`held.ticker === ''`, the runtime's
422
+ * sentinel for "could not identify"). That holding is genuine spendable
423
+ * value; a malicious or merely out-of-date payee QR is not an authenticated
424
+ * source for the scale it is displayed and typed at, and a payer who is
425
+ * about to move real funds must never have that scale handed to them by the
426
+ * other side of the payment. This fails closed into the same "neither side
427
+ * can name it" path below (`ticker: ''`), which already disables Send and
428
+ * says so — the smallest safe response, since a wrong denomination on a real
429
+ * balance is worse than asking the payer to try again once resolved.
430
+ *
431
+ * The session's own claim is used ONLY as a convenience default when this
432
+ * device holds no local record of the asset AT ALL (`held` absent) — a payer
433
+ * who holds none of an asset cannot spend it regardless of what is shown
434
+ * here (`executeSend`'s own known-holding check refuses the send before any
435
+ * signature is produced), so trusting the QR's naming in that narrower case
436
+ * costs nothing beyond a cosmetic label. The pair is taken from ONE source
437
+ * either way: a resolved decimals beside an unresolved ticker would be a
438
+ * figure with no name. `ticker: ''` on the result means the display refuses
439
+ * to guess, and the screen refuses to send rather than let the payer type
440
+ * into an unlabelled — or falsely labelled — field (design principle 4).
410
441
  */
411
442
  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 }
443
+ if (held && held.ticker !== '') return { ticker: held.ticker, decimals: held.decimals }
444
+ if (held) return { ticker: '', decimals: 0 }
414
445
  // The session block counts only when it names BOTH halves: a ticker with no
415
446
  // decimals would be a named figure at a guessed scale.
416
447
  if (asset.ticker && asset.decimals !== undefined) return { ticker: asset.ticker, decimals: asset.decimals }
@@ -439,13 +470,7 @@ export interface NearbyFlowProps {
439
470
  dismissTo?: DismissTarget
440
471
  }
441
472
 
442
- function NearbyFlow({
443
- role: initialRole,
444
- onExit,
445
- initialSession,
446
- initialRequest,
447
- dismissTo = '/'
448
- }: NearbyFlowProps) {
473
+ function NearbyFlow({ role: initialRole, onExit, initialSession, initialRequest, dismissTo = '/' }: NearbyFlowProps) {
449
474
  const { t } = useTranslation()
450
475
  const { colors } = useTheme()
451
476
  const Ionicons = loadIonicons()
@@ -623,6 +648,17 @@ function NearbyFlow({
623
648
  */
624
649
  const [receivedBroadcast, setReceivedBroadcast] = useState(true)
625
650
 
651
+ /**
652
+ * P1-1: the payee's `verification` for the shared success overlay. The
653
+ * overlay's TIMING is unchanged — still shown as soon as savePending
654
+ * resolves, before internalizeAction has necessarily run — but this gates
655
+ * whether it may claim the money is actually in the wallet yet. Starts
656
+ * 'pending' the instant the overlay appears (settleReceived, below) and is
657
+ * resolved once processPending settles: 'verified' on a credit, or
658
+ * 'not-credited' otherwise. See PaymentSuccessOverlay's `verification` doc.
659
+ */
660
+ const [receivedVerification, setReceivedVerification] = useState<'pending' | 'verified' | 'not-credited'>('verified')
661
+
626
662
  /**
627
663
  * A frame that was delivered but could not be persisted. Held so the payee can
628
664
  * retry against the SAME session: dropping it would lose a payment the payer
@@ -687,6 +723,16 @@ function NearbyFlow({
687
723
  const abortsRef = useRef<Set<AbortController>>(new Set())
688
724
  /** One-shot latch: two concurrent settles would both clear the spent check. */
689
725
  const settlingRef = useRef(false)
726
+ /**
727
+ * XR-097: whole-lifetime re-entrancy guard for executeSend, mirroring
728
+ * VaultTransferScreen's own `runningRef`. `canSend`/`phase` alone cannot
729
+ * stop a double-tap: both onPress events dispatch, and read the same
730
+ * pre-render `phase`, before React ever re-renders with the disabled
731
+ * button — so a second call that lands before the first one's first
732
+ * `await` still passes every check and builds a second, independently
733
+ * reserved payment.
734
+ */
735
+ const sendInFlightRef = useRef(false)
690
736
  /** Ignores the repeat reads multiScan produces while a scan is being handled. */
691
737
  const scanLatchRef = useRef(false)
692
738
  /** Assembles animated fountain parts across the continuous scanner's reads. */
@@ -915,6 +961,16 @@ function NearbyFlow({
915
961
  void confirm?.(false, 'save_failed')
916
962
  return
917
963
  }
964
+ // XR-098: latched HERE, synchronously, before the first await below —
965
+ // not after verification succeeds. Two calls that both start while this
966
+ // is still false (radio racing a QR scan) must not both pass the check
967
+ // above; setting it after `await verifyFramePayment(...)` left exactly
968
+ // that window open. Reset on every early-return branch below that
969
+ // intentionally leaves the request live for a genuine retry (a
970
+ // mismatch is not this device's fault) — `claimAndSavePending`'s own
971
+ // atomic claim (below) is still the backstop even if a caller reset
972
+ // this incorrectly.
973
+ settlingRef.current = true
918
974
 
919
975
  // (0a) What this frame actually pays this device. The figure below is the
920
976
  // satoshis of the AtomicBEEF output at `frame.outputIndex`, and it is
@@ -949,6 +1005,7 @@ function NearbyFlow({
949
1005
  // scanning mistake.
950
1006
  setNotice({ text: t('token_cover_failed', { issuer: issuerNameFor(session.asset?.id) }), tone: 'warning' })
951
1007
  }
1008
+ settlingRef.current = false
952
1009
  scanLatchRef.current = false
953
1010
  setSessionMismatch(true)
954
1011
  setPhase('receive_wait')
@@ -965,6 +1022,7 @@ function NearbyFlow({
965
1022
  : session.asset !== undefined
966
1023
  if (assetMismatch) {
967
1024
  void confirm?.(false, 'session_mismatch')
1025
+ settlingRef.current = false
968
1026
  scanLatchRef.current = false
969
1027
  setSessionMismatch(true)
970
1028
  setPhase('receive_wait')
@@ -1009,6 +1067,7 @@ function NearbyFlow({
1009
1067
  amountDisagrees
1010
1068
  ) {
1011
1069
  void confirm?.(false, 'session_mismatch')
1070
+ settlingRef.current = false
1012
1071
  scanLatchRef.current = false
1013
1072
  setSessionMismatch(true)
1014
1073
  // Back to the waiting screen with the pairing QR still up, and restart
@@ -1018,7 +1077,8 @@ function NearbyFlow({
1018
1077
  return
1019
1078
  }
1020
1079
 
1021
- settlingRef.current = true
1080
+ // settlingRef was already latched at the top of this function (XR-098) —
1081
+ // nothing more to set here.
1022
1082
  setSessionMismatch(false)
1023
1083
  // The frame crossed the encrypted link and decoded against this session:
1024
1084
  // the peer is provably present. Presentation only — this drives nothing
@@ -1041,9 +1101,25 @@ function NearbyFlow({
1041
1101
  // Everything that can legitimately be reported as a payment failure lives
1042
1102
  // in here, and only in here. Past the closing brace the money is safe.
1043
1103
  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)) {
1104
+ // (1)+(2)+(3), atomically (XR-098). The one-shot session guard, the
1105
+ // durable persist, and burning the session used to be three
1106
+ // separate operations — the guard under no lock at all, the other
1107
+ // two each under their own — so a concurrent delivery for the same
1108
+ // session (radio racing a QR scan, or any other overlap) could
1109
+ // pass the guard before either had written anything, and both
1110
+ // would durably queue a payment for a session meant to be spent
1111
+ // exactly once. `claimAndSavePending` runs all three inside one
1112
+ // lock, so the check-then-act sequence cannot interleave.
1113
+ //
1114
+ // `confirm` is only ever supplied by a radio receive path (the
1115
+ // listener effect above; the QR/retry callers below omit it) — the
1116
+ // same signal `Unsettled` already keys off of, reused here to
1117
+ // attribute the queue row to a transport. `via` is the radio
1118
+ // raceReceivers reported as the winner; the 'awdl' fallback covers
1119
+ // only the (unreachable in practice) case of a confirm handle with
1120
+ // no winner attached.
1121
+ const claim = await claimAndSavePending(storage, session.sessionId, frame, confirm ? (via ?? 'awdl') : 'qr')
1122
+ if (!claim.claimed) {
1047
1123
  // Not a failure for the PAYEE: that session's payment is already
1048
1124
  // queued. It is a decline for the PAYER, though, and must be — this
1049
1125
  // delivery queued nothing, and each executeSend builds a fresh
@@ -1055,32 +1131,6 @@ function NearbyFlow({
1055
1131
  setPhase('already_paid')
1056
1132
  return
1057
1133
  }
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
1134
  } catch (e) {
1085
1135
  // Reached only while the frame is still un-persisted, so this is a real
1086
1136
  // failure. Keep the frame and the session so the payee can retry the
@@ -1113,10 +1163,10 @@ function NearbyFlow({
1113
1163
  session.asset
1114
1164
  ? // Never `null` on the token path: falling through to the satoshi
1115
1165
  // renderer would print base units as satoshis.
1116
- formatTokenAmountWithUnit(satoshis, {
1166
+ (formatTokenAmountWithUnit(satoshis, {
1117
1167
  decimals: session.asset.decimals ?? 0,
1118
1168
  ticker: session.asset.ticker ?? ''
1119
- }) ?? t('token_row_amount_pending')
1169
+ }) ?? t('token_row_amount_pending'))
1120
1170
  : null
1121
1171
  )
1122
1172
  // Credited and spendable — and not yet confirmed by the issuer. Both are
@@ -1132,6 +1182,10 @@ function NearbyFlow({
1132
1182
  // this same mount left behind — internalizing corrects it below if the
1133
1183
  // payment credits without a broadcast yet.
1134
1184
  setReceivedBroadcast(true)
1185
+ // P1-1: the overlay is up now, but internalizeAction has not run yet —
1186
+ // 'pending' shows the neutral confirming copy until the block below
1187
+ // resolves it one way or the other.
1188
+ setReceivedVerification('pending')
1135
1189
  setUnsettled(null)
1136
1190
  // Who paid. Starts a best-effort identity lookup for the presence row;
1137
1191
  // deliberately after the durable write, and never awaited.
@@ -1149,6 +1203,7 @@ function NearbyFlow({
1149
1203
  // is neutral.
1150
1204
  if (!wallet) {
1151
1205
  setNotice({ text: t('local_pay_queued'), tone: 'info' })
1206
+ setReceivedVerification('not-credited')
1152
1207
  return
1153
1208
  }
1154
1209
  try {
@@ -1185,6 +1240,11 @@ function NearbyFlow({
1185
1240
  setNotice(
1186
1241
  credited ? { text: t('local_pay_added'), tone: 'success' } : { text: t('local_pay_queued'), tone: 'info' }
1187
1242
  )
1243
+ // P1-1: only a genuine credit earns the overlay's green claim; a
1244
+ // queued-but-not-yet-credited result gets the neutral not-credited
1245
+ // copy instead — the money is safe (still queued, will resolve on
1246
+ // the next retry) but not yet in the wallet.
1247
+ setReceivedVerification(credited ? 'verified' : 'not-credited')
1188
1248
  // The success overlay is already up by this point (set unconditionally
1189
1249
  // at the top of this function) — this only refines its `broadcast`
1190
1250
  // flag once storage confirms a network hand-off. Not reachable when
@@ -1206,6 +1266,7 @@ function NearbyFlow({
1206
1266
  } catch (e) {
1207
1267
  console.warn('[localpay] processPending failed:', messageOf(e))
1208
1268
  setNotice({ text: t('local_pay_queued'), tone: 'info' })
1269
+ setReceivedVerification('not-credited')
1209
1270
  }
1210
1271
  },
1211
1272
  [storage, wallet, adminOriginator, coverVerifier, issuerNameFor, mandala.runtime, fail, t]
@@ -1272,84 +1333,88 @@ function NearbyFlow({
1272
1333
 
1273
1334
  // ── Receive: mint the request ──
1274
1335
 
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])
1336
+ const startRequest = useCallback(
1337
+ async (requested?: number, asset?: SessionAsset) => {
1338
+ // Zero (or blank) is the user asking the payer to choose, so it becomes an
1339
+ // open session rather than a rejected input. Undefined, never 0 — the codec
1340
+ // refuses a non-positive amount precisely so a corrupt zero can never be
1341
+ // read back as "any amount".
1342
+ const sats =
1343
+ requested !== undefined && Number.isFinite(requested) && requested > 0 ? Math.round(requested) : undefined
1344
+ // Gate on storage too, not just the wallet. Advertising with storage null
1345
+ // means a payer can deliver a frame the payee then cannot persist, after the
1346
+ // transport has already acked it as accepted.
1347
+ if (!wallet || !storage) {
1348
+ fail('generic', t('wallet_not_ready'))
1349
+ return
1350
+ }
1351
+ setPhase('receive_minting')
1352
+ setRadioErrors({})
1353
+ setSessionQrBroken(false)
1354
+ setSessionMismatch(false)
1355
+ try {
1356
+ // Prompt-free and re-read on every mint, unlike supportsAwdl (whose probe
1357
+ // can raise the Local Network prompt): a radio switched on since the last
1358
+ // request must be picked up without leaving the screen. `notDetermined`
1359
+ // on iOS counts as supported so the prompt can follow inside prepareBle.
1360
+ const bleHere = localSupportsBle()
1361
+ // Everything the request needs, in parallel (spec §4): the identity key,
1362
+ // the two wallet nonces, the prompt-free device probe and — only where
1363
+ // this device has a BLE radio — the one call that may show the iOS
1364
+ // Bluetooth prompt. It appears here, at the moment the user has asked to
1365
+ // receive a nearby payment, the same moment the Local Network prompt
1366
+ // already can. Minting is never slower than the slowest of these, and
1367
+ // both probes are bounded (BLE_PREPARE_TIMEOUT_MS, DEFAULT_NET_BUDGET_MS).
1368
+ const [{ publicKey: identityKey }, derivationPrefix, derivationSuffix, probe, bleNow] = await Promise.all([
1369
+ wallet.getPublicKey({ identityKey: true }, adminOriginator),
1370
+ createNonce(wallet, 'self', adminOriginator),
1371
+ createNonce(wallet, 'self', adminOriginator),
1372
+ probeDeviceCaps(),
1373
+ bleHere ? prepareBle() : Promise.resolve<BluetoothState>('unsupported')
1374
+ ])
1375
+ setBleState(bleNow)
1376
+ // Advertise BLE only where this device will actually listen on it: radio
1377
+ // powered on AND (Android) the runtime grants landed. A CAP_BLE bit with
1378
+ // no advertiser behind it would walk every cross-OS payer into a 6 s
1379
+ // connect timeout before the fountain.
1380
+ const bleLive = bleNow === 'poweredOn' && blePermitted
1381
+ const session = mintSession({
1382
+ identityKey,
1383
+ // Satoshis, or base units of `asset` — `isRequestableAmount` is
1384
+ // unit-agnostic and the asset travels with the figure, so the payer
1385
+ // can never read one as the other.
1386
+ amount: sats,
1387
+ asset,
1388
+ derivationPrefix,
1389
+ derivationSuffix,
1390
+ // Caps advertise what this payee can DO; the payer's ladder picks the
1391
+ // highest rung both sides share, QR being the floor.
1392
+ supportsAwdl,
1393
+ supportsNearby: nearbyReady,
1394
+ supportsBle: bleLive,
1395
+ // Reversed role (spec 2026-09-03): an iOS payee also scans for a payer
1396
+ // that advertises, so an Android payer never has to be the central.
1397
+ // ble.ts starts that scan alongside the advertised listener.
1398
+ supportsBleScan: bleLive && Platform.OS === 'ios',
1399
+ // prepare() settles the Bluetooth answer the prompt-free probe may have
1400
+ // read as 'unknown' a moment earlier, so where it ran it overrides the
1401
+ // probe's field. The hint bits are copy for the payer, not dispatch.
1402
+ hints: capsFromProbe({ ...probe, bluetooth: bleHere ? bleNow : probe.bluetooth }),
1403
+ os: Platform.OS === 'ios' ? 'ios' : 'android'
1404
+ })
1405
+ // Same reason as the payer's side: the drain re-derives this device's own
1406
+ // settlement rows from sealed frames, and the key that opens them lives
1407
+ // only here, for this process.
1408
+ if (session.asset) rememberSessionPsk(session.psk)
1409
+ setRole('payee')
1410
+ setHostedSession(session)
1411
+ setPhase('receive_wait')
1412
+ } catch (e) {
1413
+ fail('generic', messageOf(e))
1414
+ }
1415
+ },
1416
+ [wallet, storage, adminOriginator, supportsAwdl, nearbyReady, blePermitted, fail, t]
1417
+ )
1353
1418
 
1354
1419
  // ── Receive: scan the payer's frame ──
1355
1420
 
@@ -1491,8 +1556,9 @@ function NearbyFlow({
1491
1556
  * selectTransport() reaches through to localSupportsAwdl(), which is a native
1492
1557
  * call, and the confirm screen reads it twice on every render.
1493
1558
  *
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.
1559
+ * Declared above executeSendLocked on purpose — a useCallback dependency
1560
+ * array is evaluated at render time, so referencing it from below would
1561
+ * hit the TDZ.
1496
1562
  */
1497
1563
  const sendKind = useMemo(() => (scannedSession ? selectTransport(scannedSession) : null), [scannedSession])
1498
1564
 
@@ -1630,7 +1696,10 @@ function NearbyFlow({
1630
1696
  } catch (e) {
1631
1697
  console.warn('[localpay] abortAction failed:', messageOf(e))
1632
1698
  if (storage) {
1633
- await queuePendingAbort(storage, { reference, originator: adminOriginator }).catch(() => undefined)
1699
+ await queuePendingAbort(storage, { reference, originator: adminOriginator }, {
1700
+ wallet: wallet as unknown as PendingAbortTagWallet,
1701
+ originator: adminOriginator
1702
+ }).catch(() => undefined)
1634
1703
  }
1635
1704
  }
1636
1705
  })()
@@ -1654,7 +1723,7 @@ function NearbyFlow({
1654
1723
 
1655
1724
  // ── Send: build and deliver ──
1656
1725
 
1657
- const executeSend = useCallback(async () => {
1726
+ const executeSendLocked = useCallback(async () => {
1658
1727
  const session = scannedSession
1659
1728
  if (!session || !sendKind) return
1660
1729
  // Guards the open-request path: with no figure there is nothing to build,
@@ -1670,6 +1739,37 @@ function NearbyFlow({
1670
1739
  const controller = new AbortController()
1671
1740
  registry.add(controller)
1672
1741
 
1742
+ // XR-096: keeps a built payment reserved instead of an untracked orphan
1743
+ // for the two genuinely ambiguous radio outcomes below — a screen
1744
+ // blur/unmount mid-send, and a radio failure with no representable QR
1745
+ // fallback. Mirrors the QR screen's own "back out" park exactly (see
1746
+ // completeQrDelivery's `!release` branch). Best-effort and never throws:
1747
+ // a park failure must not turn an already uncertain delivery into a
1748
+ // crash, and the built noSend action — not this bookkeeping row — is
1749
+ // what actually matters.
1750
+ const parkUncertainDelivery = async (
1751
+ built: Awaited<ReturnType<typeof buildPaymentFrame>>,
1752
+ framePayload: string
1753
+ ) => {
1754
+ if (!storage || !built.txid) return
1755
+ try {
1756
+ await parkSentPaymentOffline({
1757
+ storage,
1758
+ txid: built.txid,
1759
+ framePayload,
1760
+ ...(session.asset
1761
+ ? {
1762
+ frame: built.frame,
1763
+ onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
1764
+ reference: built.reference
1765
+ }
1766
+ : {})
1767
+ })
1768
+ } catch (e) {
1769
+ console.warn('[localpay] could not park an uncertain delivery:', e instanceof Error ? e.message : e)
1770
+ }
1771
+ }
1772
+
1673
1773
  // A token request this wallet is not set up for is refused before anything
1674
1774
  // is built: v1 resolves one overlay, and paying a token whose issuer this
1675
1775
  // device cannot reach would produce a frame nobody can settle.
@@ -1700,7 +1800,18 @@ function NearbyFlow({
1700
1800
  // hand-over comes first, unconditionally, so a face-to-face payment
1701
1801
  // never waits on a network.
1702
1802
  session.asset ? mandala.runtime?.tokenBuildDeps : undefined,
1703
- note
1803
+ note,
1804
+ // XR-088: a build failure whose own release also fails used to be
1805
+ // logged only — no durable retry record at all — unlike the
1806
+ // decline path's `queueFailedAbort` a few lines below. Same queue,
1807
+ // same replay on the next wallet build.
1808
+ async reference => {
1809
+ if (!storage) return
1810
+ await queuePendingAbort(storage, { reference, originator: adminOriginator }, {
1811
+ wallet: wallet as unknown as PendingAbortTagWallet,
1812
+ originator: adminOriginator
1813
+ })
1814
+ }
1704
1815
  )
1705
1816
  } catch (e) {
1706
1817
  // Build errors are wallet errors and must keep their own message. A
@@ -1756,7 +1867,17 @@ function NearbyFlow({
1756
1867
  }
1757
1868
  ack = await radio.send(session, built.frame, controller.signal)
1758
1869
  } catch (e) {
1759
- if (controller.signal.aborted) return
1870
+ if (controller.signal.aborted) {
1871
+ // XR-096: the screen blurred or unmounted while this native send
1872
+ // was in flight. The OS may already have finished handing the
1873
+ // bytes to the peer even though the AbortController fired — a lost
1874
+ // ack does not prove non-delivery on the happy path just above, and
1875
+ // an abort proves even less — so this must not be treated as "never
1876
+ // delivered". Park instead of leaving the signed noSend action with
1877
+ // no durable trace beyond the raw wallet transaction row.
1878
+ await parkUncertainDelivery(built, sealedToQr(sealFrame(built.frame, session.psk)))
1879
+ return
1880
+ }
1760
1881
  // The radio path failed: connect timeout (radios off, peer gone),
1761
1882
  // Local Network denial, or a lost ack. The frame is signed and noSend,
1762
1883
  // so the QR still completes this payment — fall straight through to
@@ -1770,7 +1891,12 @@ function NearbyFlow({
1770
1891
  // the QR string below share these bytes.
1771
1892
  const sealed = sealFrame(built.frame, session.psk)
1772
1893
  if (sealed.length > MAX_MESSAGE_BYTES) {
1773
- // No radio and no representable code: the one genuinely dead end.
1894
+ // No radio and no representable code: the frame cannot be shown,
1895
+ // but it can still be parked (XR-096) — that row also unlocks a
1896
+ // message-box resend later, which has no QR size limit — rather
1897
+ // than left as an untracked orphan reachable only by the
1898
+ // unrestricted generic Abort action.
1899
+ await parkUncertainDelivery(built, sealedToQr(sealed))
1774
1900
  fail(looksLikeLocalNetworkDenial(message) ? 'network' : 'generic', t('local_pay_too_large'))
1775
1901
  return
1776
1902
  }
@@ -1809,14 +1935,83 @@ function NearbyFlow({
1809
1935
  // The noSend action's own reference, onto the settlement row:
1810
1936
  // it is what lets the abort guard tell a handed-over token
1811
1937
  // payment from an abandoned one (core/mandala/abortGuard.ts).
1812
- reference: built.reference
1938
+ reference: built.reference,
1939
+ // XR-036: this rail acked over the radio and never sealed a
1940
+ // QR, so unlike the QR/fallback paths it had no framePayload
1941
+ // to give FIX G's re-derivation. Sealed here purely for local
1942
+ // durability — never rendered — so a restart that loses the
1943
+ // in-memory session PSK still has bytes to re-derive this
1944
+ // settlement row from if the journal write below did not land.
1945
+ ...(() => {
1946
+ try {
1947
+ return { framePayload: sealedToQr(sealFrame(built.frame, session.psk)) }
1948
+ } catch (e) {
1949
+ console.warn('[localpay] could not seal a fallback framePayload for the queue row:', e)
1950
+ return {}
1951
+ }
1952
+ })()
1813
1953
  }
1814
1954
  : {})
1815
1955
  })
1816
1956
  },
1817
1957
  queueFailedAbort: async reference => {
1818
1958
  if (!storage) return
1819
- await queuePendingAbort(storage, { reference, originator: adminOriginator })
1959
+ await queuePendingAbort(storage, { reference, originator: adminOriginator }, {
1960
+ wallet: wallet as unknown as PendingAbortTagWallet,
1961
+ originator: adminOriginator
1962
+ })
1963
+ },
1964
+ // P1-3: the payee's decline is unverifiable from here — watch the
1965
+ // txid so a later reappearance on chain (the payee's claim was wrong,
1966
+ // or dishonest) is surfaced instead of missed. See build.ts's
1967
+ // `watchDeclinedAbort` doc and WalletContext's reconnect-time
1968
+ // `verifyDeclinedAborts` pass.
1969
+ watchDeclinedAbort: async entry => {
1970
+ if (!storage) return
1971
+ await queueDeclinedAbortWatch(storage, {
1972
+ ...entry,
1973
+ peerIdentityKey: session.identityKey,
1974
+ at: Date.now()
1975
+ })
1976
+ },
1977
+ // XR-103: the same call WalletContext already makes for the identical
1978
+ // question (`verifyDeclinedAborts`) — asked here too so a decline
1979
+ // that lies about a transaction already on the network is caught
1980
+ // before the abort runs, not just surfaced afterwards.
1981
+ checkChainStatus: async txids => {
1982
+ if (!storage) return {}
1983
+ const services = storage.getServices() as {
1984
+ getStatusForTxids?: (txids: string[]) => Promise<{ results?: { txid: string; status: string }[] }>
1985
+ }
1986
+ if (typeof services.getStatusForTxids !== 'function') return {}
1987
+ return services.getStatusForTxids(txids)
1988
+ },
1989
+ // XR-095: ask the chain before releasing a decline's inputs — the
1990
+ // same BSV-rail check `cancelParkedPayment` runs — so a payee that
1991
+ // already broadcast their copy (whatever the ack claimed) is never
1992
+ // raced against a release. Runs after `checkChainStatus` above; that
1993
+ // probe already handles the same "already known" question up front,
1994
+ // so this is the second, independent layer this rail wires in
1995
+ // addition.
1996
+ chainAlreadyKnows: storage ? (txid: string) => chainAlreadyKnows(storage, txid) : undefined,
1997
+ // Genuinely offline, so the chain cannot be asked either way: keep the
1998
+ // inputs reserved instead of guessing, the same way backing out of the
1999
+ // QR screen already does. The frame is re-sealed so the payer can
2000
+ // still show it as a code later, from this parked row.
2001
+ parkUnverifiable: async (txid: string) => {
2002
+ if (!storage) return
2003
+ await parkSentPaymentOffline({
2004
+ storage,
2005
+ txid,
2006
+ framePayload: sealedToQr(sealFrame(built.frame, session.psk)),
2007
+ ...(session.asset
2008
+ ? {
2009
+ frame: built.frame,
2010
+ onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
2011
+ reference: built.reference
2012
+ }
2013
+ : {})
2014
+ })
1820
2015
  }
1821
2016
  })
1822
2017
  if (controller.signal.aborted) return
@@ -1863,6 +2058,7 @@ function NearbyFlow({
1863
2058
  ? await readSettlementAck(ack, {
1864
2059
  overlayIdentityKey: session.asset.overlayIdentityKey,
1865
2060
  expectTxid: built.txid,
2061
+ expectVout: built.frame.outputIndex,
1866
2062
  verify
1867
2063
  })
1868
2064
  : undefined
@@ -1893,6 +2089,25 @@ function NearbyFlow({
1893
2089
  t
1894
2090
  ])
1895
2091
 
2092
+ // XR-097: the actual onPress target. A synchronous, whole-lifetime
2093
+ // re-entrancy guard around executeSendLocked's entire body — set as the
2094
+ // very first statement, before any `await` — so a second call dispatched
2095
+ // before the first one's first `await` (a double-tap, or any two
2096
+ // overlapping invocations) sees the latch already held instead of passing
2097
+ // every check `executeSendLocked` itself makes and building a second,
2098
+ // independently reserved payment. Every early `return` inside
2099
+ // `executeSendLocked` still releases it via this `finally`, since none of
2100
+ // those paths build anything.
2101
+ const executeSend = useCallback(async () => {
2102
+ if (sendInFlightRef.current) return
2103
+ sendInFlightRef.current = true
2104
+ try {
2105
+ await executeSendLocked()
2106
+ } finally {
2107
+ sendInFlightRef.current = false
2108
+ }
2109
+ }, [executeSendLocked])
2110
+
1896
2111
  // ── Send: the payer asserts QR delivery ──
1897
2112
  //
1898
2113
  // The QR path has no ack channel, so "the payee has it" is the user's claim,
@@ -1906,106 +2121,118 @@ function NearbyFlow({
1906
2121
  // and once that session is gone, the action's payee label and derivation
1907
2122
  // customInstructions still let the payment be re-sent through the message box
1908
2123
  // 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.
2124
+ const completeQrDelivery = useCallback(
2125
+ async (opts?: { celebrate?: boolean; release?: boolean }) => {
2126
+ const celebrate = opts?.celebrate !== false
2127
+ // Done means "they have it" — the payment is released and the drain posts
2128
+ // it. Backing out means nothing of the kind, so the frame is kept and the
2129
+ // transaction stays cancellable instead. Releasing on the way out is what
2130
+ // made Back send the payment outright.
2131
+ const release = opts?.release !== false
2132
+ const built = builtRef.current
2133
+ const session = scannedSession
2134
+ // `paymentQr` is this exact frame already sealed for display — the Done
2135
+ // button that calls this only renders while it is set (see the send_qr
2136
+ // stage below) — so it is reused as the queue row's framePayload rather
2137
+ // than sealing the frame a third time.
2138
+ const framePayload = paymentQr
2139
+ if (!built || !wallet || !session || !framePayload) {
2140
+ // No handle (e.g. re-entry after reset, which clears builtRef and
2141
+ // scannedSession together): nothing to decide, just close.
2142
+ if (celebrate) {
2143
+ setSettledAmount(payAmount)
2144
+ setRole('payer')
2145
+ setNotice(null)
2146
+ setPhase('done')
2147
+ }
2148
+ return
2149
+ }
2150
+ builtRef.current = null
1926
2151
  if (celebrate) {
1927
- setSettledAmount(payAmount)
1928
- setRole('payer')
2152
+ setPhase('send_working')
1929
2153
  setNotice(null)
1930
- setPhase('done')
1931
2154
  }
1932
- return
1933
- }
1934
- builtRef.current = null
1935
- if (celebrate) {
1936
- setPhase('send_working')
1937
- setNotice(null)
1938
- }
1939
2155
 
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
- })
2156
+ // Backing out never goes through finalizeDelivery: that path broadcasts
2157
+ // after the hold whenever the device is online, so parking inside it would
2158
+ // still have sent the payment. Park and stop.
2159
+ if (!release) {
2160
+ try {
2161
+ if (storage && built.txid) {
2162
+ await parkSentPaymentOffline({
2163
+ storage,
2164
+ txid: built.txid,
2165
+ framePayload,
2166
+ // Token sessions only — see the hold callback below for why.
2167
+ ...(session.asset
2168
+ ? {
2169
+ frame: built.frame,
2170
+ onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
2171
+ // The noSend action's own reference, onto the settlement row:
2172
+ // it is what lets the abort guard tell a handed-over token
2173
+ // payment from an abandoned one (core/mandala/abortGuard.ts).
2174
+ reference: built.reference
2175
+ }
2176
+ : {})
2177
+ })
2178
+ }
2179
+ } catch (e) {
2180
+ console.warn('[localpay] could not park the payment:', e instanceof Error ? e.message : e)
1962
2181
  }
1963
- } catch (e) {
1964
- console.warn('[localpay] could not park the payment:', e instanceof Error ? e.message : e)
2182
+ return
1965
2183
  }
1966
- return
1967
- }
1968
2184
 
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 })
2185
+ const outcome = await finalizeDelivery(
2186
+ wallet as unknown as PayingWalletArg,
2187
+ built,
2188
+ { ok: true },
2189
+ adminOriginator,
2190
+ {
2191
+ hold: async txid => {
2192
+ if (!storage) throw new Error('no local storage to queue this payment in')
2193
+ await holdSentPaymentOffline({
2194
+ storage,
2195
+ txid,
2196
+ framePayload,
2197
+ // Token sessions only: same reasoning as the executeSend hold call —
2198
+ // the plaintext frame and the journal hook, so a restart does not
2199
+ // strand this payer's settlement row.
2200
+ ...(session.asset
2201
+ ? {
2202
+ frame: built.frame,
2203
+ onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
2204
+ // The noSend action's own reference, onto the settlement row:
2205
+ // it is what lets the abort guard tell a handed-over token
2206
+ // payment from an abandoned one (core/mandala/abortGuard.ts).
2207
+ reference: built.reference
2208
+ }
2209
+ : {})
2210
+ })
2211
+ },
2212
+ queueFailedAbort: async reference => {
2213
+ if (!storage) return
2214
+ await queuePendingAbort(storage, { reference, originator: adminOriginator }, {
2215
+ wallet: wallet as unknown as PendingAbortTagWallet,
2216
+ originator: adminOriginator
2217
+ })
2218
+ }
2219
+ }
2220
+ )
2221
+ if (outcome.kind === 'sent' && outcome.broadcast === 'pending') {
2222
+ console.warn('[localpay] QR delivery queued or broadcast pending:', outcome.detail ?? '')
2223
+ if (celebrate) setNotice({ text: t('local_pay_broadcast_pending'), tone: 'warning' })
1994
2224
  }
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])
2225
+ if (celebrate) {
2226
+ setSettledAmount(built.satoshis)
2227
+ // This rail has no ack payload to read σ_I from, so the receipt opens as
2228
+ // "settling" and the writer's own submit is what may settle it.
2229
+ if (session.asset) writeTokenReceipt(session.asset, built, false)
2230
+ setRole('payer')
2231
+ setPhase('done')
2232
+ }
2233
+ },
2234
+ [wallet, storage, adminOriginator, payAmount, scannedSession, paymentQr, mandala.runtime, writeTokenReceipt, t]
2235
+ )
2009
2236
 
2010
2237
  // ── Send: leave send_qr without Done ──
2011
2238
  //
@@ -2589,7 +2816,11 @@ function NearbyFlow({
2589
2816
  maxLength={280}
2590
2817
  style={[
2591
2818
  styles.noteInput,
2592
- { backgroundColor: colors.backgroundSecondary, borderColor: colors.separator, color: colors.textPrimary }
2819
+ {
2820
+ backgroundColor: colors.backgroundSecondary,
2821
+ borderColor: colors.separator,
2822
+ color: colors.textPrimary
2823
+ }
2593
2824
  ]}
2594
2825
  />
2595
2826
  </PayField>
@@ -2843,8 +3074,14 @@ function NearbyFlow({
2843
3074
  // A token receipt carries its own settlement sentence; the satoshi
2844
3075
  // broadcast flag would add a second, contradictory one.
2845
3076
  broadcast={role === 'payer' || settledTokenText ? undefined : receivedBroadcast}
3077
+ // P1-1: irrelevant on the payer side (their money already left,
3078
+ // nothing left to confirm here) — 'verified' there keeps the
3079
+ // overlay's ordinary green claim exactly as before this existed.
3080
+ verification={role === 'payer' ? 'verified' : receivedVerification}
2846
3081
  recipientName={
2847
- role === 'payer' ? (peerName ?? (scannedSession ? abbreviateKey(scannedSession.identityKey) : undefined)) : undefined
3082
+ role === 'payer'
3083
+ ? (peerName ?? (scannedSession ? abbreviateKey(scannedSession.identityKey) : undefined))
3084
+ : undefined
2848
3085
  }
2849
3086
  // The overlay navigates to the wallet after this; goBack ends the
2850
3087
  // session and resets the cell so /pay is not left mid-flow beneath.