@bsv/expo-wallet-toolbox 0.1.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 (240) hide show
  1. package/LICENSE.txt +28 -0
  2. package/README.md +512 -0
  3. package/assets/sounds/payment-receive.wav +0 -0
  4. package/assets/sounds/payment-send.wav +0 -0
  5. package/assets/sounds/vault-close.wav +0 -0
  6. package/assets/sounds/vault-open.wav +0 -0
  7. package/core/amountFormatHelpers.ts +330 -0
  8. package/core/backup/RemoteSyncReader.ts +94 -0
  9. package/core/backup/client.ts +111 -0
  10. package/core/backup/codec.ts +218 -0
  11. package/core/backup/constants.ts +88 -0
  12. package/core/backup/cursor.ts +138 -0
  13. package/core/backup/derive.ts +46 -0
  14. package/core/backup/deviceId.ts +33 -0
  15. package/core/backup/erase.ts +67 -0
  16. package/core/backup/preference.ts +33 -0
  17. package/core/backup/push.ts +295 -0
  18. package/core/backup/restore.ts +152 -0
  19. package/core/backup/restoreOnImport.ts +119 -0
  20. package/core/backup/status.ts +46 -0
  21. package/core/config.tsx +47 -0
  22. package/core/constants.ts +35 -0
  23. package/core/context/ExchangeRateContext.tsx +69 -0
  24. package/core/context/LocalStorageProvider.tsx +225 -0
  25. package/core/context/UserContext.tsx +129 -0
  26. package/core/context/VaultContext.tsx +79 -0
  27. package/core/context/WalletConnectionContext.tsx +454 -0
  28. package/core/context/WalletContext.tsx +2938 -0
  29. package/core/context/buildGeneration.ts +37 -0
  30. package/core/deviceTier.ts +89 -0
  31. package/core/diskSpace.ts +62 -0
  32. package/core/displayCurrencies.ts +56 -0
  33. package/core/headers/OfflineFirstChaintracks.ts +176 -0
  34. package/core/headers/checkpoints.ts +39 -0
  35. package/core/headers/fs.ts +119 -0
  36. package/core/headers/headerStore.ts +333 -0
  37. package/core/headers/prewarm.ts +36 -0
  38. package/core/headers/syncHeaders.ts +73 -0
  39. package/core/hooks/useConfirmationSound.ts +135 -0
  40. package/core/hooks/useHaptics.ts +51 -0
  41. package/core/hooks/usePermissionQueue.ts +69 -0
  42. package/core/i18n/translations.tsx +6692 -0
  43. package/core/index.ts +295 -0
  44. package/core/localpay/blePermissions.ts +32 -0
  45. package/core/localpay/build.ts +392 -0
  46. package/core/localpay/codec.ts +338 -0
  47. package/core/localpay/deviceCaps.ts +175 -0
  48. package/core/localpay/nearbyAdvisory.ts +32 -0
  49. package/core/localpay/nearbyPermissions.ts +34 -0
  50. package/core/localpay/pending.ts +385 -0
  51. package/core/localpay/pendingAborts.ts +67 -0
  52. package/core/localpay/qr.ts +16 -0
  53. package/core/localpay/session.ts +277 -0
  54. package/core/localpay/sessionPolicy.ts +5 -0
  55. package/core/localpay/transport/awdl.ts +11 -0
  56. package/core/localpay/transport/ble.ts +159 -0
  57. package/core/localpay/transport/nearby.ts +12 -0
  58. package/core/localpay/transport/race.ts +110 -0
  59. package/core/localpay/transport/select.ts +128 -0
  60. package/core/localpay/transport/socket.ts +244 -0
  61. package/core/localpay/types.ts +82 -0
  62. package/core/localpay/verify.ts +204 -0
  63. package/core/logging.config.ts +10 -0
  64. package/core/logging.ts +77 -0
  65. package/core/mnemonicWallet.ts +180 -0
  66. package/core/monitor/TaskBackupPush.ts +168 -0
  67. package/core/monitor/TaskCreditInbox.ts +116 -0
  68. package/core/monitor/TaskDrainOutbox.ts +122 -0
  69. package/core/monitor/TaskSendOffline.ts +123 -0
  70. package/core/monitor/unfailRetry.ts +116 -0
  71. package/core/net/chainMatch.ts +34 -0
  72. package/core/net/online.ts +34 -0
  73. package/core/offline/cancelParked.ts +56 -0
  74. package/core/offline/hold.ts +127 -0
  75. package/core/offline/order.ts +109 -0
  76. package/core/offline/payerHold.ts +144 -0
  77. package/core/offline/plan.ts +264 -0
  78. package/core/offline/queueGrace.ts +52 -0
  79. package/core/parsePeerPayURI.ts +119 -0
  80. package/core/pay/beefRepair.ts +106 -0
  81. package/core/pay/creditErrors.ts +46 -0
  82. package/core/pay/creditInbox.ts +202 -0
  83. package/core/pay/damagedInbox.ts +64 -0
  84. package/core/pay/proofNudge.ts +23 -0
  85. package/core/pay/provenTxFromBump.ts +31 -0
  86. package/core/pay/rails/address.ts +329 -0
  87. package/core/pay/rails/handle.ts +617 -0
  88. package/core/pay/rails/index.ts +197 -0
  89. package/core/pay/rails/nearby.ts +79 -0
  90. package/core/pay/receiveFocus.ts +13 -0
  91. package/core/pay/recordProof.ts +91 -0
  92. package/core/pay/refreshProofGuard.ts +34 -0
  93. package/core/pay/sweeper.ts +75 -0
  94. package/core/pay/tokenAmount.ts +18 -0
  95. package/core/pay/userError.ts +18 -0
  96. package/core/pay/watchlist.ts +126 -0
  97. package/core/peerpay/control.ts +122 -0
  98. package/core/peerpay/handleResendRequests.ts +475 -0
  99. package/core/peerpay/inboxAttempts.ts +33 -0
  100. package/core/peerpay/metadataDecryptor.ts +42 -0
  101. package/core/peerpay/offlineNacks.ts +96 -0
  102. package/core/peerpay/outbox.ts +209 -0
  103. package/core/peerpay/rebuildToken.ts +76 -0
  104. package/core/peerpay/resendBeef.ts +115 -0
  105. package/core/services/arcadeBroadcastProvider.ts +214 -0
  106. package/core/services/capWalletArgs.ts +99 -0
  107. package/core/services/exchangeRate.ts +63 -0
  108. package/core/services/secrets/envelope.ts +102 -0
  109. package/core/services/secrets/hkdf.ts +37 -0
  110. package/core/services/secrets/index.ts +63 -0
  111. package/core/services/secrets/kek.ts +274 -0
  112. package/core/services/secrets/migration.ts +188 -0
  113. package/core/services/secrets/policy.ts +120 -0
  114. package/core/services/secrets/storage.ts +54 -0
  115. package/core/services/secrets/store.ts +125 -0
  116. package/core/services/secrets/types.ts +85 -0
  117. package/core/services/usdFxRates.ts +101 -0
  118. package/core/services/vault/VaultKeyService.ts +312 -0
  119. package/core/services/vault/backupAttestation.ts +136 -0
  120. package/core/services/vault/ceremony.ts +972 -0
  121. package/core/services/vault/ceremonyHost.ts +46 -0
  122. package/core/services/vault/devMock.ts +22 -0
  123. package/core/services/vault/driver.ts +197 -0
  124. package/core/services/vault/guard.ts +90 -0
  125. package/core/services/vault/k1.ts +75 -0
  126. package/core/services/vault/mockYubiKey.ts +217 -0
  127. package/core/services/vault/random.ts +20 -0
  128. package/core/services/vault/sealing.ts +84 -0
  129. package/core/services/vault/session.ts +59 -0
  130. package/core/services/vault/transfers.ts +1151 -0
  131. package/core/services/vault/types.ts +109 -0
  132. package/core/services/vault/vaultDerivation.ts +152 -0
  133. package/core/services/vault/vaultPassphrase.ts +287 -0
  134. package/core/services/vault/vaultStore.ts +104 -0
  135. package/core/services/walletArgLimits.ts +234 -0
  136. package/core/services/walletServiceConfig.ts +170 -0
  137. package/core/storage/LocalStorageAdapter.ts +58 -0
  138. package/core/storage/README.md +391 -0
  139. package/core/storage/StorageExpoSQLite.ts +2008 -0
  140. package/core/storage/errors.ts +73 -0
  141. package/core/storage/index.ts +3 -0
  142. package/core/storage/methods/findSql.ts +286 -0
  143. package/core/storage/methods/historyNotes.ts +61 -0
  144. package/core/storage/methods/listActionsSql.ts +212 -0
  145. package/core/storage/methods/listOutputsSql.ts +211 -0
  146. package/core/storage/methods/offlineActions.ts +156 -0
  147. package/core/storage/methods/processOfflineActions.ts +503 -0
  148. package/core/storage/methods/reclaim.ts +135 -0
  149. package/core/storage/methods/reviewStatusSql.ts +167 -0
  150. package/core/storage/methods/unprovenWithoutReqSql.ts +26 -0
  151. package/core/storage/methods/walletBalanceSql.ts +55 -0
  152. package/core/storage/schema/createTables.ts +385 -0
  153. package/core/storage/skipQueuedAncestors.ts +29 -0
  154. package/core/storage/sqlUpdateValue.ts +12 -0
  155. package/core/stores/ConnectionStore.ts +71 -0
  156. package/core/theme/ThemeContext.tsx +182 -0
  157. package/core/theme/assertThemeContrast.ts +109 -0
  158. package/core/theme/motion.ts +50 -0
  159. package/core/theme/tokens.ts +232 -0
  160. package/core/theme/useThemeStyles.tsx +156 -0
  161. package/core/walletDbRegistry.ts +110 -0
  162. package/core/walletMonitor.ts +149 -0
  163. package/core/walletRepair/runWalletCheck.ts +195 -0
  164. package/core/walletRepair/shouldReleaseUtxo.ts +18 -0
  165. package/package.json +86 -0
  166. package/ui/backupShares.ts +367 -0
  167. package/ui/components/QRScanner.tsx +353 -0
  168. package/ui/components/pay/AddressReceive.tsx +507 -0
  169. package/ui/components/pay/AvailableBalance.tsx +61 -0
  170. package/ui/components/pay/HandleReceive.tsx +896 -0
  171. package/ui/components/pay/MessageBoxConfig.tsx +256 -0
  172. package/ui/components/pay/NearbyAdvisoryModal.tsx +111 -0
  173. package/ui/components/pay/NearbyFlow.tsx +2542 -0
  174. package/ui/components/pay/OfflineNotice.tsx +337 -0
  175. package/ui/components/pay/PayCellRow.tsx +101 -0
  176. package/ui/components/pay/PayForm.tsx +223 -0
  177. package/ui/components/pay/PaymentQrDisplay.tsx +105 -0
  178. package/ui/components/pay/PaymentSuccessOverlay.tsx +266 -0
  179. package/ui/components/pay/RecipientField.tsx +308 -0
  180. package/ui/components/pay/RequestHub.tsx +75 -0
  181. package/ui/components/pay/ResultBanner.tsx +69 -0
  182. package/ui/components/pay/UniversalSend.tsx +687 -0
  183. package/ui/components/pay/useRecipientInput.ts +270 -0
  184. package/ui/components/security/WalletLockNotice.tsx +138 -0
  185. package/ui/components/ui/AlertCard.tsx +223 -0
  186. package/ui/components/ui/AppLogo.tsx +166 -0
  187. package/ui/components/ui/BlurChrome.tsx +72 -0
  188. package/ui/components/ui/Celebration.tsx +84 -0
  189. package/ui/components/ui/ChoiceSheet.ts +69 -0
  190. package/ui/components/ui/CustomSafeArea.tsx +74 -0
  191. package/ui/components/ui/ErrorBoundary.tsx +154 -0
  192. package/ui/components/ui/GroupedList.tsx +125 -0
  193. package/ui/components/ui/IconButton.tsx +105 -0
  194. package/ui/components/ui/ListRow.tsx +197 -0
  195. package/ui/components/ui/PermissionSheet.tsx +920 -0
  196. package/ui/components/ui/PresenceRow.tsx +215 -0
  197. package/ui/components/ui/PressableScale.tsx +105 -0
  198. package/ui/components/ui/ScreenGradient.tsx +47 -0
  199. package/ui/components/ui/ScrollFade.tsx +76 -0
  200. package/ui/components/ui/Sheet.tsx +342 -0
  201. package/ui/components/ui/Toast.tsx +142 -0
  202. package/ui/components/ui/index.ts +8 -0
  203. package/ui/components/vault/EnrollWizard.tsx +627 -0
  204. package/ui/components/vault/PassphraseField.tsx +306 -0
  205. package/ui/components/vault/PhraseBackupSheet.tsx +227 -0
  206. package/ui/components/vault/VaultBackdrop.tsx +354 -0
  207. package/ui/components/vault/VaultCeremonySheet.tsx +327 -0
  208. package/ui/components/wallet/ActivityRow.tsx +408 -0
  209. package/ui/components/wallet/AmountDisplay.tsx +48 -0
  210. package/ui/components/wallet/AmountInput.tsx +256 -0
  211. package/ui/components/wallet/BackupReminderSheet.tsx +168 -0
  212. package/ui/components/wallet/Balance.tsx +144 -0
  213. package/ui/components/wallet/BiometricAdvisoryModal.tsx +133 -0
  214. package/ui/components/wallet/ImportFromBackupPrompt.tsx +93 -0
  215. package/ui/exportDatabases.ts +122 -0
  216. package/ui/exportTransactions.ts +129 -0
  217. package/ui/hooks/useOfflineNoticeActions.ts +136 -0
  218. package/ui/hooks/useOnline.ts +70 -0
  219. package/ui/hooks/useSpendableBalance.ts +58 -0
  220. package/ui/hooks/useVaultBalance.ts +50 -0
  221. package/ui/importDatabases.ts +170 -0
  222. package/ui/index.ts +136 -0
  223. package/ui/isImageUrl.ts +10 -0
  224. package/ui/printRecoveryShares.ts +93 -0
  225. package/ui/resolveIdentity.ts +125 -0
  226. package/ui/screens/ConnectionsScreen.tsx +438 -0
  227. package/ui/screens/LogsScreen.tsx +432 -0
  228. package/ui/screens/PairScreen.tsx +288 -0
  229. package/ui/screens/PayScreen.tsx +479 -0
  230. package/ui/screens/SettingsScreen.tsx +180 -0
  231. package/ui/screens/TrustScreen.tsx +831 -0
  232. package/ui/screens/VaultRecoverScreen.tsx +226 -0
  233. package/ui/screens/VaultScreen.tsx +423 -0
  234. package/ui/screens/VaultTransferScreen.tsx +293 -0
  235. package/ui/screens/WalletCheckScreen.tsx +539 -0
  236. package/ui/screens/WalletConfigScreen.tsx +1095 -0
  237. package/ui/screens/WalletHomeScreen.tsx +1597 -0
  238. package/ui/screens/homeBadges.ts +18 -0
  239. package/ui/txStatus.ts +79 -0
  240. package/ui/validateTrust.ts +44 -0
@@ -0,0 +1,2542 @@
1
+ /**
2
+ * Local Payments — pay a nearby device.
3
+ *
4
+ * Three transports behind one user-facing flow, all bootstrapped by the same
5
+ * pairing QR minted by the payee. selectTransport() picks the highest rung
6
+ * both sides share:
7
+ *
8
+ * AWDL iOS↔iOS peer-to-peer Wi-Fi, TLS-PSK. Fast path.
9
+ * Nearby Android↔Android over Google Nearby Connections, same Nitro surface.
10
+ * BLE any platform pair, over a second Nitro object (bsvpay-ble/1). The only
11
+ * radio that crosses iOS↔Android; the session QR is its pairing step.
12
+ * QR any platform pair. The payer renders the signed frame; the payee scans it.
13
+ *
14
+ * Phase machine
15
+ *
16
+ * entry
17
+ * ├─ receive_amount → receive_minting → receive_wait
18
+ * │ receive_wait always renders the pairing QR, and additionally runs one
19
+ * │ listener per radio this device can offer (AWDL or Nearby, plus BLE);
20
+ * │ the first frame to arrive wins and the other listeners are aborted
21
+ * │ (raceReceivers). Either arrival lands in:
22
+ * │ · radio listener resolves ─┐
23
+ * │ · receive_scan (payer QR) ─┴→ receive_settling → done | already_paid
24
+ * └─ send_scan → send_confirm → send_working
25
+ * ├─ selectTransport() === 'awdl' | 'nearby' | 'ble' → radio.send → done
26
+ * └─ selectTransport() === 'qr' → send_qr → done
27
+ *
28
+ * already_paid is a SUCCESS terminal, not an error: the session was settled by
29
+ * an earlier delivery, so that money is already queued. It is the expected end
30
+ * of both legitimate rescan paths and must never offer a retry, because a retry
31
+ * mints a fresh session and invites a second payment.
32
+ *
33
+ * failed is terminal for either role. It offers a retry, a route to Settings
34
+ * when Local Network access is the cause, a re-settle when a delivered frame
35
+ * could not be persisted, and — on a failed AWDL send — the already-built frame
36
+ * as a QR so the payment can still complete.
37
+ *
38
+ * An AWDL listener error does NOT terminate the screen: the fast path is
39
+ * optional, so it degrades to a QR-only request with the pairing QR still up.
40
+ *
41
+ * The amount may come from EITHER side. A payee can name a figure or leave the
42
+ * request open, in which case the payer enters it on the confirm screen. See
43
+ * `Session.amount` and the settle-binding note below — the two cases differ in
44
+ * exactly one check, and the difference is load-bearing.
45
+ *
46
+ * Money safety (see settleReceived below, which is the only write path):
47
+ * 0. The frame is bound to the session before anything else: a frame whose
48
+ * derivation nonces do not match the live request — or whose amount
49
+ * contradicts an amount the payee actually asked for — is refused without
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
56
+ * try that can flip the screen to a failure. Once the frame is queued the
57
+ * payment cannot be lost, so reporting failure past that line would invite
58
+ * a duplicate payment — the same misreport refused for markSessionSpent.
59
+ * 4. The live Session is threaded in as an argument — neither PaymentFrame
60
+ * nor PendingPayment carries a sessionId, so it cannot be recovered later.
61
+ * 5. Every decode sits in a bare `catch`, which catches non-Error throws from
62
+ * atob and destructuring too, not just CodecError.
63
+ * 6. Nothing decorative — identity lookup, the confirmation tone, presence —
64
+ * is ever awaited on a money path. They are all fire-and-forget.
65
+ *
66
+ * Money safety, payer side (see abortBuild below):
67
+ * The frame is built `noSend`, which holds `amount + fee` in inputs marked
68
+ * unspendable. Nothing in storage ever reaps a 'nosend' action, so an
69
+ * abandoned build locks those funds permanently. abortBuild() releases them —
70
+ * but ONLY on paths where the frame provably never left the device. Once
71
+ * delivery is even possible the action must stay intact, because the payee may
72
+ * still broadcast it and a freed input can be respent into a conflict.
73
+ *
74
+ * ── Design notes (see .superpowers/sdd/2026-07-27-local-payments-awdl/phase-b-report.md) ──
75
+ *
76
+ * Density 8pt vertical rhythm throughout. 16pt gutter, 24pt between
77
+ * sections, 8pt within a group. Every vertical value on this screen
78
+ * is a multiple of 8 except hairlines and optical nudges.
79
+ * Type Four levels, doing the hierarchy work together with weight and
80
+ * colour: display(44/700) · title2(22/700) · subhead(15/400) ·
81
+ * footnote(13/400). Never size alone.
82
+ * Colour Green means confirmed money and nothing else. It appears on the
83
+ * celebration mark, the `paid` presence state, and the "added to
84
+ * your wallet" notice — nowhere decorative. Everything else is
85
+ * neutral structure.
86
+ * Motion Transforms and opacity only, under 300ms, springs.snappy or
87
+ * easings.out. Nothing eases in; nothing starts from scale(0).
88
+ */
89
+
90
+ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
91
+ import { ActivityIndicator, Linking, Modal, Platform, ScrollView, StyleSheet, Text, View } from 'react-native'
92
+ import Animated, { FadeIn, FadeInDown, useReducedMotion } from 'react-native-reanimated'
93
+ import { useSafeAreaInsets } from 'react-native-safe-area-context'
94
+ import { useTranslation } from 'react-i18next'
95
+ import { Beef, createNonce, type WalletInterface } from '@bsv/sdk'
96
+ import { finalizeDelivery } from '../../../core/localpay/build'
97
+ import { queuePendingAbort } from '../../../core/localpay/pendingAborts'
98
+ import { receiptBroadcastFromReqStatus } from '../../../core/offline/plan'
99
+ import { userFacingPayError } from '../../../core/pay/userError'
100
+
101
+ import QRScanner from '../QRScanner'
102
+ import AmountDisplay from '../wallet/AmountDisplay'
103
+ import PressableScale from '../ui/PressableScale'
104
+ import PresenceRow, { type PresenceState } from '../ui/PresenceRow'
105
+ import AvailableBalance from './AvailableBalance'
106
+ import { PayAmountField, RecipientSummary } from './PayForm'
107
+ import PaymentQrDisplay from './PaymentQrDisplay'
108
+ import ReceivedOverlay from './PaymentSuccessOverlay'
109
+ import { identityLabel, makeIdentityClient, resolveIdentity } from '../../resolveIdentity'
110
+ import {
111
+ useTheme,
112
+ radii,
113
+ spacing,
114
+ typography,
115
+ durations,
116
+ springs,
117
+ useWallet,
118
+ sounds,
119
+ updateOfflineAction,
120
+ AirGapDecoder,
121
+ FRAME_BLOCK_BYTES,
122
+ MAX_MESSAGE_BYTES,
123
+ awdlTransport,
124
+ bleTransport,
125
+ buildPaymentFrame,
126
+ capsFromProbe,
127
+ decodeSession,
128
+ describeFloor,
129
+ encodeSession,
130
+ frameBytesFromQr,
131
+ holdSentPaymentOffline,
132
+ parkSentPaymentOffline,
133
+ isAirGapPart,
134
+ isDeclineReason,
135
+ isSessionSpent,
136
+ localSupportsAwdl,
137
+ localSupportsBle,
138
+ localSupportsNearby,
139
+ markSessionSpent,
140
+ mintSession,
141
+ nearbyTransport,
142
+ nextPhaseAfterUnsealFailure,
143
+ prepareBle,
144
+ probeDeviceCaps,
145
+ processPending,
146
+ raceReceivers,
147
+ readBluetoothState,
148
+ requestBlePermissions,
149
+ requestNearbyPermissions,
150
+ savePending,
151
+ sealedToQr,
152
+ sealFrame,
153
+ selectTransport,
154
+ unsealFrame,
155
+ type Ack,
156
+ type BluetoothState,
157
+ type ConfirmDelivery,
158
+ type DeclineReason,
159
+ type FloorReason,
160
+ type LocalPaymentTransport,
161
+ type PaymentFrame,
162
+ type RadioKind,
163
+ type Session,
164
+ FrameVerifyError,
165
+ verifyFramePayment,
166
+ type DerivingWallet,
167
+ type VerifiedPayment
168
+ } from '@bsv/expo-wallet-toolbox'
169
+
170
+ /**
171
+ * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
172
+ * etc.), one of which reaches expo-font -> expo-asset -- untransformed ESM
173
+ * that Jest cannot parse when eagerly pulled in via the `ui` package barrel.
174
+ * Ionicons is loaded lazily, only when actually rendering, same pattern as
175
+ * this package's other native-module-boundary fixes (expo-router, expo-blur).
176
+ */
177
+ type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
178
+ let ioniconsComponent: IoniconsComponent | undefined
179
+ function loadIonicons(): IoniconsComponent {
180
+ if (!ioniconsComponent) {
181
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
182
+ ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
183
+ }
184
+ return ioniconsComponent
185
+ }
186
+
187
+ /**
188
+ * expo-router is required lazily rather than imported at module scope: this
189
+ * file is barrel-exported from the package's `ui` entry point, and a static
190
+ * top-level `import` of expo-router pulls in its own untransformed JSX
191
+ * source (Navigator.js etc.), which Jest cannot parse for any consumer of the
192
+ * barrel, even one that never navigates. Same pattern as
193
+ * core/context/WalletContext.tsx's and WalletHomeScreen.tsx's lazy
194
+ * expo-router load. `useFocusEffect` is a hook, but calling it via
195
+ * `loadExpoRouter().useFocusEffect(...)` is equivalent to calling it directly
196
+ * — the module is cached after the first call, so it is the exact same
197
+ * function reference on every render, which is what the rules of hooks
198
+ * actually require (a stable, unconditional call per render).
199
+ */
200
+ type ExpoRouterModule = typeof import('expo-router')
201
+ let expoRouterMod: ExpoRouterModule | undefined
202
+ function loadExpoRouter(): ExpoRouterModule {
203
+ if (!expoRouterMod) {
204
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
205
+ expoRouterMod = require('expo-router') as ExpoRouterModule
206
+ }
207
+ return expoRouterMod
208
+ }
209
+
210
+ /**
211
+ * react-native-qrcode-svg ships an untransformed ESM build that Jest cannot
212
+ * parse when eagerly pulled in via the `ui` package barrel, even for a
213
+ * consumer that never renders one. Loaded lazily, only when actually
214
+ * rendering, same pattern as this package's other native/ESM-boundary fixes.
215
+ * `mod?.default ?? mod` mirrors Babel's default-interop rather than a plain
216
+ * `.default` access, since this repo's test mock for the module
217
+ * (`jest.mock('react-native-qrcode-svg', () => 'QRCode')`) has no
218
+ * `__esModule`/`default` shape.
219
+ */
220
+ type QRCodeComponent = typeof import('react-native-qrcode-svg').default
221
+ let qrCodeComponent: QRCodeComponent | undefined
222
+ function loadQRCode(): QRCodeComponent {
223
+ if (!qrCodeComponent) {
224
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
225
+ const mod = require('react-native-qrcode-svg')
226
+ qrCodeComponent = (mod?.default ?? mod) as QRCodeComponent
227
+ }
228
+ return qrCodeComponent
229
+ }
230
+
231
+ /**
232
+ * expo-status-bar's package.json `main` points straight at its raw
233
+ * TypeScript source (no compiled build output ships), and the unscoped,
234
+ * hyphenated package name is not in this repo's Jest transformIgnorePatterns
235
+ * allow-list, so a static top-level import fails to parse for any consumer
236
+ * of the `ui` package barrel. Loaded lazily, only when actually rendering,
237
+ * same pattern as this package's other native/ESM-boundary fixes.
238
+ */
239
+ type StatusBarComponent = typeof import('expo-status-bar').StatusBar
240
+ let statusBarComponent: StatusBarComponent | undefined
241
+ function loadStatusBar(): StatusBarComponent {
242
+ if (!statusBarComponent) {
243
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
244
+ statusBarComponent = require('expo-status-bar').StatusBar as StatusBarComponent
245
+ }
246
+ return statusBarComponent
247
+ }
248
+
249
+ // ── Types ──
250
+
251
+ type PayingWalletArg = Parameters<typeof buildPaymentFrame>[0]
252
+
253
+ type Phase =
254
+ | 'entry'
255
+ | 'receive_amount'
256
+ | 'receive_minting'
257
+ | 'receive_wait'
258
+ | 'receive_scan'
259
+ | 'receive_settling'
260
+ | 'send_scan'
261
+ | 'send_confirm'
262
+ | 'send_working'
263
+ | 'send_qr'
264
+ | 'done'
265
+ | 'already_paid'
266
+ | 'failed'
267
+
268
+ interface Failure {
269
+ /** Human-readable cause, shown under the generic failure title. */
270
+ detail: string
271
+ /** Local Network access is off — offer a route to Settings. */
272
+ settings: boolean
273
+ /** Offer Check Wallet for WERR_REVIEW_ACTIONS. */
274
+ offerWalletCheck?: boolean
275
+ }
276
+
277
+ /**
278
+ * The tone of the notice on a terminal screen.
279
+ *
280
+ * Separate from the text because tone is a claim about money, not a style
281
+ * choice. `success` is green and states that funds are in the wallet;
282
+ * `broadcast pending` is emphatically NOT that, and wearing success styling was
283
+ * the one piece of UX debt Phase A left behind (a warning dressed as a receipt).
284
+ */
285
+ type NoticeTone = 'success' | 'info' | 'warning'
286
+
287
+ interface Notice {
288
+ text: string
289
+ tone: NoticeTone
290
+ }
291
+
292
+ /**
293
+ * A frame that reached this device but could not be persisted, held for a retry.
294
+ *
295
+ * Only ever set for a delivery that was NOT declined — in practice, the QR
296
+ * path, which has no ack channel. Once the payer has been told nothing was
297
+ * queued it releases the inputs its `noSend` action holds, and re-settling the
298
+ * same frame afterwards would queue a payment against a transaction the payer
299
+ * now considers abandoned and free to respend. An AWDL payer recovers by
300
+ * building afresh, which is clean; this one cannot.
301
+ */
302
+ interface Unsettled {
303
+ frame: PaymentFrame
304
+ session: Session
305
+ }
306
+
307
+ /** Rendered edge length in points. The brief floors payment QRs at 280. */
308
+ const PAYMENT_QR_SIZE = 288
309
+
310
+ /**
311
+ * Decline codes as the PAYER renders them. The payee sends a stable machine
312
+ * code precisely so the sentence can be produced here, in this device's locale.
313
+ * Anything unrecognised falls through to the raw text, preserving the old
314
+ * behaviour for a peer running a different build.
315
+ */
316
+ const DECLINE_KEYS: Record<DeclineReason, string> = {
317
+ session_mismatch: 'local_pay_declined_mismatch',
318
+ already_paid: 'local_pay_declined_already_paid',
319
+ save_failed: 'local_pay_declined_save',
320
+ decode_failed: 'local_pay_declined_decode'
321
+ }
322
+
323
+ /**
324
+ * Why the payer is on the fountain, as one sentence they can act on. Only ever
325
+ * rendered when selectTransport() chose QR (spec §5) — this is what the hint
326
+ * bits in the payee's code buy: the person paying is told what to switch on
327
+ * instead of watching a slow fountain in silence.
328
+ */
329
+ const FLOOR_KEYS: Record<Exclude<FloorReason, 'none'>, string> = {
330
+ peer_no_radio: 'local_pay_floor_peer_no_radio',
331
+ peer_bt_off: 'local_pay_floor_peer_bt_off',
332
+ local_ble_denied: 'local_pay_floor_local_ble_denied',
333
+ local_bt_off: 'local_pay_floor_local_bt_off',
334
+ cross_os_no_ble: 'local_pay_floor_cross_os'
335
+ }
336
+
337
+ const NOTICE_ICONS: Record<NoticeTone, keyof IoniconsComponent['glyphMap']> = {
338
+ success: 'wallet',
339
+ info: 'time-outline',
340
+ warning: 'cloud-offline-outline'
341
+ }
342
+
343
+ // ── Helpers ──
344
+
345
+ function messageOf(e: unknown): string {
346
+ if (e instanceof Error && e.message) return e.message
347
+ const text = String(e)
348
+ return text === '[object Object]' ? '' : text
349
+ }
350
+
351
+ /**
352
+ * iOS surfaces a Local Network denial through Network.framework as a policy or
353
+ * routing error rather than a typed permission result, so this is a match on the
354
+ * localized NWError description. Treated as advisory: a false positive only means
355
+ * the user is additionally offered a Settings shortcut.
356
+ */
357
+ function looksLikeLocalNetworkDenial(message: string): boolean {
358
+ const m = message.toLowerCase()
359
+ return (
360
+ m.includes('policy') ||
361
+ m.includes('denied') ||
362
+ m.includes('not permitted') ||
363
+ m.includes('no route to host') ||
364
+ m.includes('network is down') ||
365
+ m.includes('-65570')
366
+ )
367
+ }
368
+
369
+ function abbreviateKey(key: string): string {
370
+ return key.length > 16 ? `${key.slice(0, 10)}…${key.slice(-6)}` : key
371
+ }
372
+
373
+ /** Satoshis from a free-text field, or 0 when it is not yet a usable figure. */
374
+ function satsFrom(text: string): number {
375
+ const n = Math.round(Number(text))
376
+ return Number.isFinite(n) && n > 0 ? n : 0
377
+ }
378
+
379
+ // ── Screen ──
380
+
381
+ export interface NearbyFlowProps {
382
+ /** Which side of the exchange this device is on. Set by the cell that mounted it. */
383
+ role: 'payer' | 'payee'
384
+ /** Leave the flow. The Pay screen decides what that means (back to the grid). */
385
+ onExit: () => void
386
+ /** Payer only: a session the Pay screen already scanned. Skips the scanner, lands on confirm. */
387
+ initialSession?: Session
388
+ /** Payee only: mint immediately for this amount (undefined = open request). Skips receive_amount. */
389
+ initialRequest?: { sats?: number }
390
+ }
391
+
392
+ export default function NearbyFlow({ role: initialRole, onExit, initialSession, initialRequest }: NearbyFlowProps) {
393
+ const { t } = useTranslation()
394
+ const { colors } = useTheme()
395
+ const Ionicons = loadIonicons()
396
+ const QRCode = loadQRCode()
397
+ const StatusBar = loadStatusBar()
398
+ const { router, useFocusEffect, useNavigation } = loadExpoRouter()
399
+ const navigation = useNavigation()
400
+ const insets = useSafeAreaInsets()
401
+ const reducedMotion = useReducedMotion()
402
+ const { managers, adminOriginator, storage } = useWallet()
403
+ const wallet = managers?.permissionsManager ?? null
404
+
405
+ const [phase, setPhase] = useState<Phase>('entry')
406
+ const [role, setRole] = useState<'payee' | 'payer' | null>(initialRole)
407
+
408
+ /** The payee's own minted session — drives the pairing QR and the AWDL listener. */
409
+ const [hostedSession, setHostedSession] = useState<Session | null>(null)
410
+ /** The session the payer scanned off the payee's screen. */
411
+ const [scannedSession, setScannedSession] = useState<Session | null>(null)
412
+
413
+ const [requestAmount, setRequestAmount] = useState('')
414
+ /**
415
+ * The payee is raising an OPEN request — no figure, the payer decides.
416
+ *
417
+ * Kept separate from an empty `requestAmount` because they are different
418
+ * intents: an empty field is an unfinished specific request and must keep
419
+ * Continue disabled, while this is a complete request that happens to name no
420
+ * amount.
421
+ */
422
+ /** The payer's own entry, used only when the scanned session left the amount open. */
423
+ const [sendAmount, setSendAmount] = useState('')
424
+
425
+ const [paymentQr, setPaymentQr] = useState<string | null>(null)
426
+ const [settledAmount, setSettledAmount] = useState(0)
427
+ const [failure, setFailure] = useState<Failure | null>(null)
428
+ const [notice, setNotice] = useState<Notice | null>(null)
429
+
430
+ /**
431
+ * The other device's identity key, once one is known, and the display name it
432
+ * resolves to. Presentation only: the lookup is a network call that may never
433
+ * complete on a screen two people are using precisely because the network is
434
+ * poor, so nothing waits on it and a null name is a normal outcome.
435
+ */
436
+ const [peerKey, setPeerKey] = useState<string | null>(null)
437
+ const [peerName, setPeerName] = useState<string | null>(null)
438
+
439
+ /** True once the AWDL link has provably carried this session's frame. */
440
+ const [linked, setLinked] = useState(false)
441
+
442
+ /**
443
+ * The payee's `broadcast` flag for the shared success overlay (see the
444
+ * `phase === 'done'` render below): whether storage already records a
445
+ * network hand-off for this tx (`alreadySentStatuses`) — NOT whether this
446
+ * device was online at settle time. An offline hold parks the req at
447
+ * `nosend`, so the receipt must not claim broadcast just because NetInfo
448
+ * was up. Defaults optimistic (no pending line) since the overlay is shown
449
+ * immediately on settle, before this is known; updated once internalizing
450
+ * resolves it (only reachable when the funds actually credited).
451
+ */
452
+ const [receivedBroadcast, setReceivedBroadcast] = useState(true)
453
+
454
+ /**
455
+ * A frame that was delivered but could not be persisted. Held so the payee can
456
+ * retry against the SAME session: dropping it would lose a payment the payer
457
+ * already considers sent, and reset() would mint a session that can never
458
+ * receive it.
459
+ */
460
+ const [unsettled, setUnsettled] = useState<Unsettled | null>(null)
461
+
462
+ /**
463
+ * A radio listener gave up, per radio. Non-fatal by design — the pairing QR
464
+ * is still on screen and a QR-path payer can still complete, and any OTHER
465
+ * radio still listening keeps the request live on that rung. Keyed by kind so
466
+ * the presence row can say "waiting" while one radio is alive and the notice
467
+ * can name the one that is not.
468
+ */
469
+ const [radioErrors, setRadioErrors] = useState<Partial<Record<RadioKind, { networkDenied: boolean }>>>({})
470
+
471
+ /**
472
+ * What this device's Bluetooth radio reported. The payee learns it from
473
+ * prepareBle() at minting (the one call that may show the iOS prompt); the
474
+ * payer reads it prompt-free on scanning a session, so describeFloor can say
475
+ * "your Bluetooth is off" without ever prompting someone about to pay by code.
476
+ */
477
+ const [bleState, setBleState] = useState<BluetoothState>('unknown')
478
+ /**
479
+ * Android's runtime grants for BLE landed (or are not needed: iOS gates BLE
480
+ * through prepare() instead). Nearby's grant set is a superset of BLE's on
481
+ * every API level, so on a GMS device the one Nearby prompt answers both.
482
+ */
483
+ const [blePermitted, setBlePermitted] = useState(Platform.OS !== 'android')
484
+ /**
485
+ * The Android permission probe below has finished, either way. A mint reads
486
+ * the radio flags through startRequest's closure, so a mint fired in the
487
+ * mount commit would advertise their initial `false`; the hub-started
488
+ * request waits on this. True from the start off Android, where there is no
489
+ * probe to wait for.
490
+ */
491
+ const [permissionsSettled, setPermissionsSettled] = useState(Platform.OS !== 'android')
492
+
493
+ /** The encoder rejected the pairing payload. Should be unreachable at ~170 chars. */
494
+ const [sessionQrBroken, setSessionQrBroken] = useState(false)
495
+
496
+ /**
497
+ * A frame arrived that does not belong to this request. Advisory, not fatal:
498
+ * the session is deliberately left live so the real payer can still pay.
499
+ */
500
+ const [sessionMismatch, setSessionMismatch] = useState(false)
501
+
502
+ /**
503
+ * Bumped to restart the AWDL listener. A rejected frame resolves the listener
504
+ * promise, so without this the fast path would stay dead for the rest of a
505
+ * session that is still accepting payment.
506
+ */
507
+ const [listenerEpoch, setListenerEpoch] = useState(0)
508
+
509
+ /** Blur must abort the AWDL listener; refocus must bring it back. */
510
+ const [focused, setFocused] = useState(true)
511
+
512
+ // Every in-flight transport call registers its controller here so unmount,
513
+ // back-navigation and reset can all tear the listener down. A leaked listener
514
+ // leaves the device advertising on the local network.
515
+ const abortsRef = useRef<Set<AbortController>>(new Set())
516
+ /** One-shot latch: two concurrent settles would both clear the spent check. */
517
+ const settlingRef = useRef(false)
518
+ /** Ignores the repeat reads multiScan produces while a scan is being handled. */
519
+ const scanLatchRef = useRef(false)
520
+ /** Assembles animated fountain parts across the continuous scanner's reads. */
521
+ const airGapDecoderRef = useRef<AirGapDecoder | null>(null)
522
+ /** Live part-count for the fountain progress line under the camera. */
523
+ const [scanProgress, setScanProgress] = useState<{ have: number; total: number } | null>(null)
524
+
525
+ /**
526
+ * The built payment behind the QR currently on screen. Done routes it
527
+ * through finalizeDelivery; without it Done can only guess. Cleared by
528
+ * reset() and consumed (nulled) by completeQrDelivery.
529
+ */
530
+ const builtRef = useRef<Awaited<ReturnType<typeof buildPaymentFrame>> | null>(null)
531
+ /** Lets the next `beforeRemove` through after the send_qr exit sheet chooses abort. */
532
+ const sendQrAllowLeaveRef = useRef(false)
533
+
534
+ /**
535
+ * Whether this device can be an AWDL peer. Resolved ONCE per mount.
536
+ *
537
+ * `localSupportsAwdl()` is not a cheap predicate: each call constructs a
538
+ * throwaway NWListener in Swift on the JS thread, and can trigger the Local
539
+ * Network permission alert. It was previously called from render and twice
540
+ * more per render of the confirm screen. The answer cannot change while the
541
+ * screen is mounted, so every read goes through this.
542
+ */
543
+ const supportsAwdl = useMemo(() => localSupportsAwdl(), [])
544
+
545
+ /**
546
+ * Nearby is usable only once BOTH hold: GMS is present (localSupportsNearby)
547
+ * and the runtime grants landed. Resolved async on mount, Android only; a
548
+ * denial leaves this false and the flow QR-only, silently — same posture as
549
+ * a GMS-less device.
550
+ *
551
+ * Spec §7: at flow entry the payee asks for Nearby's grants where GMS is
552
+ * present (that set covers BLE too), and otherwise for BLE's alone. The payer
553
+ * is never prompted for BLE here — executeSend asks lazily, only once BLE has
554
+ * actually been selected, so a payer landing on QR sees no prompt.
555
+ */
556
+ const [nearbyReady, setNearbyReady] = useState(false)
557
+ useEffect(() => {
558
+ if (Platform.OS !== 'android') return
559
+ let live = true
560
+ // Settled either way, and settled even when neither probe runs: a mint held
561
+ // for a probe that will never resolve would never advertise at all.
562
+ const settle = () => {
563
+ if (live) setPermissionsSettled(true)
564
+ }
565
+ if (localSupportsNearby()) {
566
+ void requestNearbyPermissions()
567
+ .then(granted => {
568
+ if (!live) return
569
+ setNearbyReady(granted)
570
+ setBlePermitted(granted)
571
+ })
572
+ .finally(settle)
573
+ } else if (initialRole === 'payee' && localSupportsBle()) {
574
+ // localSupportsBle() is false while the radio is off (Task 9's isSupported
575
+ // reads BluetoothAdapter.isEnabled), so a GMS-less payee who enters with
576
+ // Bluetooth off stays QR-only until the screen is re-entered — the same
577
+ // posture as a Nearby denial.
578
+ void requestBlePermissions()
579
+ .then(granted => {
580
+ if (live) setBlePermitted(granted)
581
+ })
582
+ .finally(settle)
583
+ } else {
584
+ settle()
585
+ }
586
+ return () => {
587
+ live = false
588
+ }
589
+ }, [initialRole])
590
+
591
+ /** BLE can be listened on: radio powered on and (on Android) the grants landed. */
592
+ const bleReady = bleState === 'poweredOn' && blePermitted
593
+
594
+ /**
595
+ * Every radio this device listens on as payee. The platform socket radio
596
+ * (AWDL on iOS, Nearby on Android — they share one native object, so never
597
+ * both) plus BLE when it is ready. Empty means QR-only. Order is irrelevant:
598
+ * raceReceivers starts all of them and the first frame wins (spec §6).
599
+ */
600
+ const radioTransports = useMemo<LocalPaymentTransport[]>(() => {
601
+ const list: LocalPaymentTransport[] = []
602
+ if (supportsAwdl) list.push(awdlTransport)
603
+ else if (nearbyReady) list.push(nearbyTransport)
604
+ if (bleReady) list.push(bleTransport)
605
+ return list
606
+ }, [supportsAwdl, nearbyReady, bleReady])
607
+
608
+ const abortAll = useCallback(() => {
609
+ for (const controller of abortsRef.current) {
610
+ try {
611
+ controller.abort()
612
+ } catch {
613
+ /* already aborted */
614
+ }
615
+ }
616
+ abortsRef.current.clear()
617
+ }, [])
618
+
619
+ useEffect(() => () => abortAll(), [abortAll])
620
+
621
+ // Hand the shared audio player back when the screen goes away. Not required
622
+ // for correctness — a failed release is swallowed — but this screen may sit
623
+ // open on a counter all day and there is no reason to hold a native object.
624
+ useEffect(() => () => sounds.release(), [])
625
+
626
+ useFocusEffect(
627
+ useCallback(() => {
628
+ setFocused(true)
629
+ return () => {
630
+ setFocused(false)
631
+ abortAll()
632
+ }
633
+ }, [abortAll])
634
+ )
635
+
636
+ const openScanner = useCallback((next: 'send_scan' | 'receive_scan') => {
637
+ scanLatchRef.current = false
638
+ airGapDecoderRef.current = null
639
+ setScanProgress(null)
640
+ setPhase(next)
641
+ }, [])
642
+
643
+ const fail = useCallback(
644
+ (kind: 'network' | 'generic', detail?: string, offerWalletCheck = false) => {
645
+ setFailure(
646
+ kind === 'network'
647
+ ? { detail: t('local_pay_network_denied'), settings: true }
648
+ : {
649
+ detail: detail && detail.length > 0 ? detail : t('local_pay_failed'),
650
+ settings: false,
651
+ offerWalletCheck
652
+ }
653
+ )
654
+ setPhase('failed')
655
+ },
656
+ [t]
657
+ )
658
+
659
+ const clearFlowState = useCallback(() => {
660
+ settlingRef.current = false
661
+ scanLatchRef.current = false
662
+ airGapDecoderRef.current = null
663
+ setScanProgress(null)
664
+ builtRef.current = null
665
+ setRole(initialRole)
666
+ setHostedSession(null)
667
+ setScannedSession(null)
668
+ setRequestAmount('')
669
+ setSendAmount('')
670
+ setPaymentQr(null)
671
+ setSettledAmount(0)
672
+ setFailure(null)
673
+ setNotice(null)
674
+ setUnsettled(null)
675
+ setRadioErrors({})
676
+ setSessionQrBroken(false)
677
+ setSessionMismatch(false)
678
+ setPeerKey(null)
679
+ setPeerName(null)
680
+ setLinked(false)
681
+ setReceivedBroadcast(true)
682
+ }, [initialRole])
683
+
684
+ const reset = useCallback(() => {
685
+ // Cancel from a mount whose amount or session came from outside: there is
686
+ // no phase to go back to — the hub or the send form owns that state.
687
+ if (initialRequest || initialSession) {
688
+ abortAll()
689
+ onExit()
690
+ return
691
+ }
692
+ abortAll()
693
+ clearFlowState()
694
+ setPhase(initialRole === 'payee' ? 'receive_amount' : 'entry')
695
+ }, [abortAll, clearFlowState, initialRole, initialRequest, initialSession, onExit])
696
+
697
+ const goBack = useCallback(() => {
698
+ abortAll()
699
+ onExit()
700
+ }, [abortAll, onExit])
701
+
702
+ // ── Peer identity ──
703
+ //
704
+ // Best-effort and strictly presentational. Never awaited by a money path, and
705
+ // a failure is indistinguishable from "nobody has vouched for this key" by
706
+ // design — both mean the presence row simply shows no name.
707
+
708
+ useEffect(() => {
709
+ if (!peerKey || !wallet) return
710
+ const client = makeIdentityClient(wallet as unknown as WalletInterface, adminOriginator)
711
+ if (!client) return
712
+ let live = true
713
+ void resolveIdentity(client, peerKey).then(([, identity]) => {
714
+ if (live) setPeerName(identityLabel(identity))
715
+ })
716
+ return () => {
717
+ live = false
718
+ }
719
+ }, [peerKey, wallet, adminOriginator])
720
+
721
+ // ── Receive: settle ──
722
+ //
723
+ // The single write path. Called by the AWDL listener and by the QR scanner
724
+ // with whichever Session is live at that moment.
725
+
726
+ const settleReceived = useCallback(
727
+ async (frame: PaymentFrame, session: Session, confirm?: ConfirmDelivery, via?: RadioKind) => {
728
+ // `confirm` is how the payer learns what happened. It is undefined on the
729
+ // QR path, which has no socket to ack over. On the AWDL path it MUST be
730
+ // called on every exit below: with `true` only once savePending has
731
+ // resolved (a positive ack is what releases the payer's transaction for
732
+ // broadcast), and with `false` on every path that queued nothing, so the
733
+ // payer aborts its build instead of resting on a green "Sent".
734
+ //
735
+ // Fire-and-forget throughout: ConfirmDelivery never rejects, and the
736
+ // payee's own outcome must not depend on the ack reaching the payer.
737
+ if (settlingRef.current) {
738
+ // Another delivery is mid-settle (an AWDL arrival racing a QR scan).
739
+ // Nothing was written for THIS frame, so it is a provable decline.
740
+ void confirm?.(false, 'save_failed')
741
+ return
742
+ }
743
+
744
+ // (0a) What this frame actually pays this device. The figure below is the
745
+ // satoshis of the AtomicBEEF output at `frame.outputIndex`, and it is
746
+ // only produced once that output is shown to lock to a key this
747
+ // device derives — so it is both the real number and a proof the
748
+ // payment is ours to spend. Nothing has latched and nothing has been
749
+ // written, so every failure here is a provable "queued nothing".
750
+ let verified: VerifiedPayment
751
+ try {
752
+ verified = await verifyFramePayment(wallet as unknown as DerivingWallet, frame, adminOriginator)
753
+ } catch (e) {
754
+ // `not_mine` is a frame that was never for this request; `unparseable`
755
+ // is bytes that are not a transaction. Both leave the request LIVE and
756
+ // unspent, exactly as a nonce mismatch does, so the genuine payer can
757
+ // still complete.
758
+ const kind = e instanceof FrameVerifyError ? e.kind : 'unparseable'
759
+ void confirm?.(false, kind === 'not_mine' ? 'session_mismatch' : 'decode_failed')
760
+ scanLatchRef.current = false
761
+ setSessionMismatch(true)
762
+ setPhase('receive_wait')
763
+ setListenerEpoch(n => n + 1)
764
+ return
765
+ }
766
+ if (verified.kind !== 'bsv') {
767
+ // This app's settle path only credits BSV payments today; a token frame
768
+ // is refused before anything latches, exactly like a session mismatch —
769
+ // and, like that path, the request stays LIVE: re-arm the scan latch,
770
+ // surface the mismatch, return to the waiting screen, and restart the
771
+ // listener the rejected frame consumed, so a genuine (BSV) payer can
772
+ // still complete.
773
+ void confirm?.(false, 'session_mismatch')
774
+ scanLatchRef.current = false
775
+ setSessionMismatch(true)
776
+ setPhase('receive_wait')
777
+ setListenerEpoch(n => n + 1)
778
+ return
779
+ }
780
+ const satoshis = verified.satoshis
781
+
782
+ // (0) Bind the frame to THIS session, before the one-shot latch and before
783
+ // any write. Two distinct holes close here:
784
+ //
785
+ // · the amount check compares the payee's requested figure against the
786
+ // satoshis verified above, not against anything the frame asserts.
787
+ // · onFrameScanned hands ANY decoded frame to the live hostedSession, so
788
+ // scanning a stray payment QR would queue a stranger's payment AND burn
789
+ // this session. The real payer would then be told already_paid, acked
790
+ // ok, and silently discarded.
791
+ //
792
+ // THE NONCE CHECKS ALWAYS APPLY. derivationPrefix/Suffix are the
793
+ // per-session values the payee minted and the payer echoed back, so
794
+ // matching them is what makes the frame provably intended for this
795
+ // request. They are the whole binding, and nothing below weakens them.
796
+ //
797
+ // The amount check applies ONLY where the payee actually named a
798
+ // figure. On an open request there is no requested amount to
799
+ // contradict — the payer chose it — so there is nothing to compare
800
+ // against, and inventing a comparison (against 0, or against whatever
801
+ // the frame itself claims) would either reject every legitimate open
802
+ // payment or be a check that always passes and merely looks like one.
803
+ // What the check does when it does run is unchanged: it pins the
804
+ // figure the payee is about to see to the figure they asked for.
805
+ //
806
+ // Deliberately NOT terminal, and deliberately does NOT mark the session
807
+ // spent: the request stays live so the genuine payer can still complete.
808
+ const amountDisagrees = session.amount !== undefined && satoshis !== session.amount
809
+ if (
810
+ frame.derivationPrefix !== session.derivationPrefix ||
811
+ frame.derivationSuffix !== session.derivationSuffix ||
812
+ amountDisagrees
813
+ ) {
814
+ void confirm?.(false, 'session_mismatch')
815
+ scanLatchRef.current = false
816
+ setSessionMismatch(true)
817
+ // Back to the waiting screen with the pairing QR still up, and restart
818
+ // the AWDL listener the rejected frame consumed.
819
+ setPhase('receive_wait')
820
+ setListenerEpoch(n => n + 1)
821
+ return
822
+ }
823
+
824
+ settlingRef.current = true
825
+ setSessionMismatch(false)
826
+ // The frame crossed the encrypted link and decoded against this session:
827
+ // the peer is provably present. Presentation only — this drives nothing
828
+ // but the presence row.
829
+ if (confirm) setLinked(true)
830
+ setPhase('receive_settling')
831
+
832
+ if (!storage) {
833
+ // The frame already reached this device, but with nowhere to write it
834
+ // there is provably nothing queued — decline, so the payer releases its
835
+ // inputs rather than believing the payment landed.
836
+ void confirm?.(false, 'save_failed')
837
+ settlingRef.current = false
838
+ setUnsettled(confirm ? null : { frame, session })
839
+ fail('generic', t('wallet_not_ready'))
840
+ return
841
+ }
842
+
843
+ // ── Durable-write section ──
844
+ // Everything that can legitimately be reported as a payment failure lives
845
+ // in here, and only in here. Past the closing brace the money is safe.
846
+ try {
847
+ // (1) One-shot session guard, before anything is written. A re-scanned
848
+ // or replayed session must never credit twice.
849
+ if (await isSessionSpent(storage, session.sessionId)) {
850
+ // Not a failure for the PAYEE: that session's payment is already
851
+ // queued. It is a decline for the PAYER, though, and must be — this
852
+ // delivery queued nothing, and each executeSend builds a fresh
853
+ // action from fresh UTXOs, so acking it would broadcast a second
854
+ // transaction for a request already paid.
855
+ void confirm?.(false, 'already_paid')
856
+ setHostedSession(null)
857
+ setUnsettled(null)
858
+ setPhase('already_paid')
859
+ return
860
+ }
861
+
862
+ // (2) Persist before anything else. Once this resolves the money cannot
863
+ // be lost to a crash, a dead network or a closed app.
864
+ //
865
+ // `confirm` is only ever supplied by a radio receive path (the
866
+ // listener effect above; the QR/retry callers below omit it) — the
867
+ // same signal `Unsettled` already keys off of, reused here to
868
+ // attribute the queue row to a transport. `via` is the radio
869
+ // raceReceivers reported as the winner; the 'awdl' fallback covers
870
+ // only the (unreachable in practice) case of a confirm handle with
871
+ // no winner attached.
872
+ await savePending(storage, frame, confirm ? (via ?? 'awdl') : 'qr')
873
+
874
+ // (3) Only now is it safe to burn the session. Doing this first would
875
+ // mean a crash in between marks the session handled while nothing
876
+ // was persisted — unrecoverable, because sessions are one-shot.
877
+ try {
878
+ await markSessionSpent(storage, session.sessionId)
879
+ } catch (e) {
880
+ // The frame is already queued, so this is not a payment failure and
881
+ // must not be reported as one. internalizeAction is idempotent on a
882
+ // repeat of the same output — the toolbox merges "wallet payment"
883
+ // internalizations by txid and skips the second credit — so a replay
884
+ // from here cannot double-credit.
885
+ console.warn('[localpay] markSessionSpent failed:', messageOf(e))
886
+ }
887
+ } catch (e) {
888
+ // Reached only while the frame is still un-persisted, so this is a real
889
+ // failure. Keep the frame and the session so the payee can retry the
890
+ // same settle instead of losing a payment to a transient SQLite error —
891
+ // but only where no decline went out (see Unsettled). A declined AWDL
892
+ // payer has already released its inputs; retrying against that frame
893
+ // would queue a payment its transaction no longer backs.
894
+ void confirm?.(false, 'save_failed')
895
+ settlingRef.current = false
896
+ setUnsettled(confirm ? null : { frame, session })
897
+ fail('generic', messageOf(e))
898
+ return
899
+ }
900
+
901
+ // (3a) ACK. The one place a positive ack may be sent: savePending has
902
+ // resolved, so the claim it makes to the payer — "this payee has
903
+ // durably queued your payment" — is now true. It is also the payer's
904
+ // cue to broadcast, which is why it must not be sent one line
905
+ // earlier. Sent before the UI updates below so the payer's screen
906
+ // moves as soon as possible.
907
+ void confirm?.(true)
908
+
909
+ // ── Past here the frame is durably queued ──
910
+ // The payment cannot be lost, so nothing below may flip the screen to a
911
+ // failure. A payee who is told "failed" taps Retry, mints a fresh session,
912
+ // and the payer builds a second createAction from different UTXOs: both
913
+ // internalize, the payee is credited twice and the payer pays twice.
914
+ setSettledAmount(satoshis)
915
+ setRole('payee')
916
+ setPhase('done')
917
+ // The overlay below renders as soon as phase flips; start it optimistic
918
+ // (no pending-broadcast line) regardless of what a previous settle in
919
+ // this same mount left behind — internalizing corrects it below if the
920
+ // payment credits without a broadcast yet.
921
+ setReceivedBroadcast(true)
922
+ setUnsettled(null)
923
+ // Who paid. Starts a best-effort identity lookup for the presence row;
924
+ // deliberately after the durable write, and never awaited.
925
+ setPeerKey(frame.senderIdentityKey)
926
+ // Clearing the hosted session stops the AWDL listener: this request is settled.
927
+ setHostedSession(null)
928
+
929
+ // (4) Internalization is attempted only after the durable write, and its
930
+ // failure only downgrades the notice. processPending awaits storage
931
+ // outside its own per-entry try, so it can reject as a whole; the entry
932
+ // stays queued either way for the background retry.
933
+ //
934
+ // Tone is a claim about money: `success` (green) is reserved for funds
935
+ // actually in the wallet. "Queued" is safe but not yet spendable, so it
936
+ // is neutral.
937
+ if (!wallet) {
938
+ setNotice({ text: t('local_pay_queued'), tone: 'info' })
939
+ return
940
+ }
941
+ try {
942
+ // Backfills who handed over a payment (and how) onto the offline_actions
943
+ // row internalizeAction may just have created while this device was
944
+ // offline — that row is written deep in the storage layer's hold path,
945
+ // which never sees the frame. Captured once here rather than inside
946
+ // `storage?.sqliteDb`, because `settleReceived` re-checks `storage`
947
+ // is non-null on every call and this closure must not re-derive that.
948
+ const db = storage.sqliteDb
949
+ const results = await processPending(wallet, storage, adminOriginator, async (txid, info) => {
950
+ if (!db) return
951
+ await updateOfflineAction(db, txid, {
952
+ senderIdentityKey: info.senderIdentityKey,
953
+ receivedVia: info.receivedVia
954
+ })
955
+ })
956
+ const credited = results.some(r => r.success)
957
+ setNotice(
958
+ credited ? { text: t('local_pay_added'), tone: 'success' } : { text: t('local_pay_queued'), tone: 'info' }
959
+ )
960
+ // The success overlay is already up by this point (set unconditionally
961
+ // at the top of this function) — this only refines its `broadcast`
962
+ // flag once storage confirms a network hand-off. Not reachable when
963
+ // the payment merely queued (no txid to check yet), so the overlay
964
+ // keeps its optimistic default there.
965
+ if (credited) {
966
+ let broadcast = false
967
+ try {
968
+ const txid = Beef.fromBinary(frame.transaction).atomicTxid
969
+ if (txid) {
970
+ const reqs = await storage.findProvenTxReqs({ partial: { txid } })
971
+ broadcast = receiptBroadcastFromReqStatus(reqs[0]?.status)
972
+ }
973
+ } catch {
974
+ broadcast = false
975
+ }
976
+ setReceivedBroadcast(broadcast)
977
+ }
978
+ } catch (e) {
979
+ console.warn('[localpay] processPending failed:', messageOf(e))
980
+ setNotice({ text: t('local_pay_queued'), tone: 'info' })
981
+ }
982
+ },
983
+ [storage, wallet, adminOriginator, fail, t]
984
+ )
985
+
986
+ // Read through refs so the listener effect below depends only on the session
987
+ // and focus, and is never restarted by an unrelated re-render.
988
+ const settleRef = useRef(settleReceived)
989
+ useEffect(() => {
990
+ settleRef.current = settleReceived
991
+ }, [settleReceived])
992
+
993
+ // ── Receive: radio listeners ──
994
+ //
995
+ // One listener per radio this device offers, all started together; the first
996
+ // frame wins and the rest are aborted before settle (raceReceivers, spec §6).
997
+ // The pairing QR is rendered regardless, so a QR-path payer can always
998
+ // complete against the same session.
999
+
1000
+ useEffect(() => {
1001
+ if (!hostedSession || !focused) return
1002
+ if (radioTransports.length === 0) return
1003
+
1004
+ // The Set identity is stable for the component's lifetime, but capture it so
1005
+ // the cleanup never reaches through a ref that may have been reassigned.
1006
+ const registry = abortsRef.current
1007
+ const controller = new AbortController()
1008
+ registry.add(controller)
1009
+ setRadioErrors({})
1010
+
1011
+ raceReceivers(radioTransports, hostedSession, controller.signal, (kind, e) => {
1012
+ if (controller.signal.aborted) return
1013
+ // Never terminal. Every radio is an optional fast path; one failing must
1014
+ // not unmount the pairing QR a QR-path payer is relying on, nor stop the
1015
+ // other radios. One native error site also fires on a failed ack AFTER
1016
+ // the frame reached JS, so flipping to a failure screen here could
1017
+ // contradict a settle already in flight. The Local Network heuristic is
1018
+ // about Wi-Fi radios only — a BLE failure never offers that Settings route.
1019
+ setRadioErrors(prev => ({
1020
+ ...prev,
1021
+ [kind]: { networkDenied: kind !== 'ble' && looksLikeLocalNetworkDenial(messageOf(e)) }
1022
+ }))
1023
+ })
1024
+ .then(({ kind, frame, confirm }) => {
1025
+ if (controller.signal.aborted) {
1026
+ // The screen went away between delivery and here. The payer is
1027
+ // holding an un-acked connection and nothing was written, so tell it
1028
+ // rather than leaving it to time out on a green "Sent".
1029
+ void confirm(false, 'save_failed')
1030
+ return
1031
+ }
1032
+ void settleRef.current(frame, hostedSession, confirm, kind)
1033
+ })
1034
+ .catch(() => {
1035
+ // Every radio has already been reported through onError above (or the
1036
+ // effect was torn down). Nothing further to show.
1037
+ })
1038
+
1039
+ return () => {
1040
+ controller.abort()
1041
+ registry.delete(controller)
1042
+ }
1043
+ }, [hostedSession, focused, radioTransports, listenerEpoch])
1044
+
1045
+ // ── Receive: mint the request ──
1046
+
1047
+ const startRequest = useCallback(async (requested?: number) => {
1048
+ // Zero (or blank) is the user asking the payer to choose, so it becomes an
1049
+ // open session rather than a rejected input. Undefined, never 0 — the codec
1050
+ // refuses a non-positive amount precisely so a corrupt zero can never be
1051
+ // read back as "any amount".
1052
+ const sats = requested !== undefined && Number.isFinite(requested) && requested > 0 ? Math.round(requested) : undefined
1053
+ // Gate on storage too, not just the wallet. Advertising with storage null
1054
+ // means a payer can deliver a frame the payee then cannot persist, after the
1055
+ // transport has already acked it as accepted.
1056
+ if (!wallet || !storage) {
1057
+ fail('generic', t('wallet_not_ready'))
1058
+ return
1059
+ }
1060
+ setPhase('receive_minting')
1061
+ setRadioErrors({})
1062
+ setSessionQrBroken(false)
1063
+ setSessionMismatch(false)
1064
+ try {
1065
+ // Prompt-free and re-read on every mint, unlike supportsAwdl (whose probe
1066
+ // can raise the Local Network prompt): a radio switched on since the last
1067
+ // request must be picked up without leaving the screen. `notDetermined`
1068
+ // on iOS counts as supported so the prompt can follow inside prepareBle.
1069
+ const bleHere = localSupportsBle()
1070
+ // Everything the request needs, in parallel (spec §4): the identity key,
1071
+ // the two wallet nonces, the prompt-free device probe and — only where
1072
+ // this device has a BLE radio — the one call that may show the iOS
1073
+ // Bluetooth prompt. It appears here, at the moment the user has asked to
1074
+ // receive a nearby payment, the same moment the Local Network prompt
1075
+ // already can. Minting is never slower than the slowest of these, and
1076
+ // both probes are bounded (BLE_PREPARE_TIMEOUT_MS, DEFAULT_NET_BUDGET_MS).
1077
+ const [{ publicKey: identityKey }, derivationPrefix, derivationSuffix, probe, bleNow] = await Promise.all([
1078
+ wallet.getPublicKey({ identityKey: true }, adminOriginator),
1079
+ createNonce(wallet, 'self', adminOriginator),
1080
+ createNonce(wallet, 'self', adminOriginator),
1081
+ probeDeviceCaps(),
1082
+ bleHere ? prepareBle() : Promise.resolve<BluetoothState>('unsupported')
1083
+ ])
1084
+ setBleState(bleNow)
1085
+ // Advertise BLE only where this device will actually listen on it: radio
1086
+ // powered on AND (Android) the runtime grants landed. A CAP_BLE bit with
1087
+ // no advertiser behind it would walk every cross-OS payer into a 6 s
1088
+ // connect timeout before the fountain.
1089
+ const bleLive = bleNow === 'poweredOn' && blePermitted
1090
+ const session = mintSession({
1091
+ identityKey,
1092
+ amount: sats,
1093
+ derivationPrefix,
1094
+ derivationSuffix,
1095
+ // Caps advertise what this payee can DO; the payer's ladder picks the
1096
+ // highest rung both sides share, QR being the floor.
1097
+ supportsAwdl,
1098
+ supportsNearby: nearbyReady,
1099
+ supportsBle: bleLive,
1100
+ // Reversed role (spec 2026-09-03): an iOS payee also scans for a payer
1101
+ // that advertises, so an Android payer never has to be the central.
1102
+ // ble.ts starts that scan alongside the advertised listener.
1103
+ supportsBleScan: bleLive && Platform.OS === 'ios',
1104
+ // prepare() settles the Bluetooth answer the prompt-free probe may have
1105
+ // read as 'unknown' a moment earlier, so where it ran it overrides the
1106
+ // probe's field. The hint bits are copy for the payer, not dispatch.
1107
+ hints: capsFromProbe({ ...probe, bluetooth: bleHere ? bleNow : probe.bluetooth }),
1108
+ os: Platform.OS === 'ios' ? 'ios' : 'android'
1109
+ })
1110
+ setRole('payee')
1111
+ setHostedSession(session)
1112
+ setPhase('receive_wait')
1113
+ } catch (e) {
1114
+ fail('generic', messageOf(e))
1115
+ }
1116
+ }, [wallet, storage, adminOriginator, supportsAwdl, nearbyReady, blePermitted, fail, t])
1117
+
1118
+ // ── Receive: scan the payer's frame ──
1119
+
1120
+ const onFrameScanned = useCallback(
1121
+ (data: string) => {
1122
+ // A payer's code is always an air-gap fountain, so parts are the only
1123
+ // thing this scanner accepts — a bare bsvpayf1: envelope is a stored
1124
+ // value, not something any build renders at a camera. Parts arrive
1125
+ // continuously and are handled statefully; anything else is a QR that
1126
+ // happens to be in frame and changes nothing.
1127
+ if (!isAirGapPart(data)) return
1128
+ // A settling payment must ignore late parts — the frame it already
1129
+ // solved is already on its way through settleReceived.
1130
+ if (scanLatchRef.current || settlingRef.current) return
1131
+ const session = hostedSession
1132
+ if (!session) return
1133
+ if (!airGapDecoderRef.current) airGapDecoderRef.current = new AirGapDecoder()
1134
+ const s = airGapDecoderRef.current.accept(data)
1135
+ if (!s.ok) return
1136
+ setScanProgress({ have: s.have, total: s.total })
1137
+ if (!s.done) return
1138
+ const message = airGapDecoderRef.current.message()
1139
+ if (!message) return // crc mismatch: decoder reset itself, keep scanning
1140
+ airGapDecoderRef.current = null
1141
+ setScanProgress(null)
1142
+ scanLatchRef.current = true
1143
+ let frame: PaymentFrame
1144
+ try {
1145
+ // Bare catch on purpose: version skew, truncation or trailing bytes
1146
+ // throw a CodecError, but a body that destructures from null throws
1147
+ // something else — and must still land here, not crash the screen.
1148
+ frame = unsealFrame(message, session.psk)
1149
+ } catch {
1150
+ // Same posture as settleReceived's mismatch path: keep hostedSession,
1151
+ // re-arm the scanner, return to receive_wait. A new session would
1152
+ // orphan the live request the real payer is still holding.
1153
+ scanLatchRef.current = false
1154
+ airGapDecoderRef.current = null
1155
+ setScanProgress(null)
1156
+ setPhase(nextPhaseAfterUnsealFailure())
1157
+ setListenerEpoch(n => n + 1)
1158
+ return
1159
+ }
1160
+ void settleRef.current(frame, session)
1161
+ },
1162
+ [hostedSession]
1163
+ )
1164
+
1165
+ // ── Send: scan the payee's session ──
1166
+
1167
+ /** The state moves that follow a valid session, whether scanned here or handed in. */
1168
+ const adoptSession = useCallback((session: Session) => {
1169
+ setScannedSession(session)
1170
+ // Prompt-free read of this device's Bluetooth state for describeFloor.
1171
+ // Never prepare() here: a payer who lands on QR must never be prompted.
1172
+ setBleState(readBluetoothState())
1173
+ // Who is being paid. Best-effort lookup for the presence row and the
1174
+ // recipient card; nothing waits on it.
1175
+ setPeerKey(session.identityKey)
1176
+ setSendAmount('')
1177
+ setRole('payer')
1178
+ setPhase('send_confirm')
1179
+ }, [])
1180
+
1181
+ const onSessionScanned = useCallback(
1182
+ (data: string) => {
1183
+ if (scanLatchRef.current) return
1184
+ scanLatchRef.current = true
1185
+ let session: Session
1186
+ try {
1187
+ session = decodeSession(data)
1188
+ } catch {
1189
+ fail('generic', t('invalid_qr_code'))
1190
+ return
1191
+ }
1192
+ adoptSession(session)
1193
+ },
1194
+ [adoptSession, fail, t]
1195
+ )
1196
+
1197
+ // One entry per mount. A payee with a pre-set request mints as soon as the
1198
+ // radio permissions have settled — startRequest reads nearbyReady/blePermitted
1199
+ // through its closure, so minting in the mount commit advertised their initial
1200
+ // `false` and floored every payer to QR. A payer with a pre-scanned session
1201
+ // lands on confirm. Without either, the old behaviour: payee names an amount,
1202
+ // payer raises the camera.
1203
+ //
1204
+ // The effect may therefore run twice on Android — before and after the probe
1205
+ // settles — so each branch is guarded by its own ref: `mintedRef` for the mint
1206
+ // (which waits), `enteredRef` for the three that do not. Declared here, below
1207
+ // startRequest and adoptSession, because a dependency array is read at render
1208
+ // time and both are `const`s — referencing them from above would TDZ.
1209
+ const enteredRef = useRef(false)
1210
+ const mintedRef = useRef(false)
1211
+ useEffect(() => {
1212
+ if (initialRole === 'payee' && initialRequest) {
1213
+ if (!permissionsSettled || mintedRef.current) return
1214
+ mintedRef.current = true
1215
+ void startRequest(initialRequest.sats)
1216
+ return
1217
+ }
1218
+ if (enteredRef.current) return
1219
+ enteredRef.current = true
1220
+ if (initialRole === 'payee') {
1221
+ setPhase('receive_amount')
1222
+ } else if (initialSession) {
1223
+ adoptSession(initialSession)
1224
+ } else {
1225
+ openScanner('send_scan')
1226
+ }
1227
+ }, [initialRole, initialRequest, initialSession, openScanner, startRequest, adoptSession, permissionsSettled])
1228
+
1229
+ /**
1230
+ * The failed screen's Retry. Unlike reset(), it never leaves: a mount that
1231
+ * was handed its request or session re-enters from that same input, so a
1232
+ * failed mint mints again and a failed send lands back on confirm.
1233
+ */
1234
+ const retry = useCallback(() => {
1235
+ abortAll()
1236
+ clearFlowState()
1237
+ if (initialRole === 'payee') {
1238
+ if (initialRequest) void startRequest(initialRequest.sats)
1239
+ else setPhase('receive_amount')
1240
+ } else if (initialSession) {
1241
+ adoptSession(initialSession)
1242
+ } else {
1243
+ setPhase('entry')
1244
+ }
1245
+ }, [abortAll, clearFlowState, initialRole, initialRequest, initialSession, startRequest, adoptSession])
1246
+
1247
+ /**
1248
+ * The transport this payment will take. Memoized per scanned session:
1249
+ * selectTransport() reaches through to localSupportsAwdl(), which is a native
1250
+ * call, and the confirm screen reads it twice on every render.
1251
+ *
1252
+ * Declared above executeSend on purpose — a useCallback dependency array is
1253
+ * evaluated at render time, so referencing it from below would hit the TDZ.
1254
+ */
1255
+ const sendKind = useMemo(() => (scannedSession ? selectTransport(scannedSession) : null), [scannedSession])
1256
+
1257
+ /**
1258
+ * Why this payer is on the fountain, if it is. Evaluated only once
1259
+ * selectTransport() chose QR (spec §5); 'none' otherwise, and 'none' when the
1260
+ * hint bits explain nothing — the confirm screen then says nothing extra.
1261
+ */
1262
+ const floorReason = useMemo<FloorReason>(
1263
+ () =>
1264
+ sendKind === 'qr' && scannedSession
1265
+ ? describeFloor(scannedSession, { os: Platform.OS === 'ios' ? 'ios' : 'android', bluetooth: bleState })
1266
+ : 'none',
1267
+ [sendKind, scannedSession, bleState]
1268
+ )
1269
+
1270
+ /**
1271
+ * The figure this payment will actually carry.
1272
+ *
1273
+ * The payee's request wins outright when they named one — the payer must not
1274
+ * be able to talk it down, and the payee's settle check would refuse anything
1275
+ * else anyway. Otherwise it is the payer's own entry. 0 means "not a usable
1276
+ * amount yet" and keeps Send disabled.
1277
+ */
1278
+ const payAmount = useMemo(() => {
1279
+ if (!scannedSession) return 0
1280
+ return scannedSession.amount ?? satsFrom(sendAmount)
1281
+ }, [scannedSession, sendAmount])
1282
+
1283
+ // ── Send: release an abandoned build ──
1284
+ //
1285
+ // buildPaymentFrame creates the action with `noSend: true`, which flips its
1286
+ // inputs to `spendable: false`. The storage sweeper (TaskFailAbandoned) reaps
1287
+ // only 'unprocessed' and 'unsigned' actions — never 'nosend' — so a build that
1288
+ // is abandoned locks `amount + fee` in this wallet permanently and silently.
1289
+ //
1290
+ // Only ever call this where the frame PROVABLY never left the device. Never
1291
+ // after a possible delivery: the payee may still broadcast, and freeing the
1292
+ // inputs here would let this wallet respend them into a conflicting tx.
1293
+ // Fire-and-forget — an abort failure is a stuck UTXO, not a lost payment, and
1294
+ // must not overwrite the real error already on screen.
1295
+
1296
+ const abortBuild = useCallback(
1297
+ (reference: string | undefined) => {
1298
+ if (!reference || !wallet) return
1299
+ void (async () => {
1300
+ try {
1301
+ const result = await (wallet as unknown as PayingWalletArg).abortAction({ reference }, adminOriginator)
1302
+ if (result?.aborted === false) throw new Error('abortAction returned aborted:false')
1303
+ } catch (e) {
1304
+ console.warn('[localpay] abortAction failed:', messageOf(e))
1305
+ if (storage) {
1306
+ await queuePendingAbort(storage, { reference, originator: adminOriginator }).catch(() => undefined)
1307
+ }
1308
+ }
1309
+ })()
1310
+ },
1311
+ [wallet, adminOriginator, storage]
1312
+ )
1313
+
1314
+ /**
1315
+ * Renders a peer's decline in THIS device's locale. The payee sends a stable
1316
+ * machine code rather than a sentence, so a Japanese payer never sees Polish.
1317
+ * Anything unrecognised is echoed verbatim, which keeps a peer on a different
1318
+ * build readable rather than silent.
1319
+ */
1320
+ const declineMessage = useCallback(
1321
+ (reason: string | undefined) => {
1322
+ if (reason && isDeclineReason(reason)) return t(DECLINE_KEYS[reason])
1323
+ return reason && reason.length > 0 ? reason : t('local_pay_failed')
1324
+ },
1325
+ [t]
1326
+ )
1327
+
1328
+ // ── Send: build and deliver ──
1329
+
1330
+ const executeSend = useCallback(async () => {
1331
+ const session = scannedSession
1332
+ if (!session || !sendKind) return
1333
+ // Guards the open-request path: with no figure there is nothing to build,
1334
+ // and buildPaymentFrame would refuse it anyway.
1335
+ if (payAmount <= 0) return
1336
+ if (!wallet) {
1337
+ fail('generic', t('wallet_not_ready'))
1338
+ return
1339
+ }
1340
+ setPhase('send_working')
1341
+
1342
+ const registry = abortsRef.current
1343
+ const controller = new AbortController()
1344
+ registry.add(controller)
1345
+
1346
+ try {
1347
+ let built: Awaited<ReturnType<typeof buildPaymentFrame>>
1348
+ try {
1349
+ // The structural `PayingWallet` in build.ts pins `createAction().tx` to
1350
+ // `number[]`, while the SDK's `AtomicBEEF` is `Byte[] | Uint8Array`. The
1351
+ // manager satisfies the contract at runtime — build.ts wraps the result in
1352
+ // `new Uint8Array(...)`, which accepts either — so this is nominal only.
1353
+ built = await buildPaymentFrame(wallet as unknown as PayingWalletArg, session, adminOriginator, payAmount)
1354
+ } catch (e) {
1355
+ // Build errors are wallet errors and must keep their own message. A
1356
+ // declined spending prompt reads "Permission denied", which the Local
1357
+ // Network heuristic would otherwise misread into an Open Settings button
1358
+ // for the wrong permission, discarding the real reason. Nothing was
1359
+ // built, so there is nothing to abort.
1360
+ if (!controller.signal.aborted) {
1361
+ const facing = userFacingPayError(e)
1362
+ fail('generic', facing.offerWalletCheck ? t(facing.key) : messageOf(e), facing.offerWalletCheck)
1363
+ }
1364
+ return
1365
+ }
1366
+ if (controller.signal.aborted) {
1367
+ // The user backed out or the screen blurred while "Delivering…" was up.
1368
+ // The frame was never handed to a transport and never rendered.
1369
+ abortBuild(built.reference)
1370
+ return
1371
+ }
1372
+
1373
+ if (sendKind === 'qr') {
1374
+ // The fountain removes the symbol-size ceiling; the only refusal left
1375
+ // is the 64 KB sanity cap, past which QR handover is unreasonable and
1376
+ // something upstream is wrong. Measured on the SEALED length — that is
1377
+ // what actually renders. Sealed once: the size check and the QR string
1378
+ // below share these bytes rather than sealing the frame twice.
1379
+ const sealed = sealFrame(built.frame, session.psk)
1380
+ if (sealed.length > MAX_MESSAGE_BYTES) {
1381
+ abortBuild(built.reference)
1382
+ setPaymentQr(null)
1383
+ fail('generic', t('local_pay_too_large'))
1384
+ return
1385
+ }
1386
+ builtRef.current = built
1387
+ setPaymentQr(sealedToQr(sealed))
1388
+ setPhase('send_qr')
1389
+ return
1390
+ }
1391
+
1392
+ // sendKind is neither 'qr' (returned above) nor null (guarded at the top
1393
+ // of this callback), so it names one of the three radios here.
1394
+ const radio = sendKind === 'awdl' ? awdlTransport : sendKind === 'nearby' ? nearbyTransport : bleTransport
1395
+
1396
+ let ack: Ack
1397
+ try {
1398
+ // Android asks for the BLE runtime grants lazily, here, so a payer who
1399
+ // lands on QR is never prompted (spec §7). A refusal is treated exactly
1400
+ // like a radio failure — the catch below falls to the fountain with
1401
+ // local_pay_radio_fallback — so its wording deliberately avoids every
1402
+ // word looksLikeLocalNetworkDenial matches (no "denied").
1403
+ if (sendKind === 'ble' && Platform.OS === 'android' && !(await requestBlePermissions())) {
1404
+ throw new Error('bluetooth permission not granted')
1405
+ }
1406
+ ack = await radio.send(session, built.frame, controller.signal)
1407
+ } catch (e) {
1408
+ if (controller.signal.aborted) return
1409
+ // The radio path failed: connect timeout (radios off, peer gone),
1410
+ // Local Network denial, or a lost ack. The frame is signed and noSend,
1411
+ // so the QR still completes this payment — fall straight through to
1412
+ // the code instead of a failure screen. Deliberately NOT aborted: a
1413
+ // lost ack does not prove non-delivery, and Done's semantics
1414
+ // (broadcast-or-queue, re-showable) keep the already-delivered case
1415
+ // consistent — the payee's copy merges once this transaction is out.
1416
+ const message = messageOf(e)
1417
+ console.warn('[localpay] radio send failed, falling back to QR:', message)
1418
+ // Sealed once, same as the direct QR path above: the size check and
1419
+ // the QR string below share these bytes.
1420
+ const sealed = sealFrame(built.frame, session.psk)
1421
+ if (sealed.length > MAX_MESSAGE_BYTES) {
1422
+ // No radio and no representable code: the one genuinely dead end.
1423
+ fail(looksLikeLocalNetworkDenial(message) ? 'network' : 'generic', t('local_pay_too_large'))
1424
+ return
1425
+ }
1426
+ builtRef.current = built
1427
+ setPaymentQr(sealedToQr(sealed))
1428
+ setNotice({ text: t('local_pay_radio_fallback'), tone: 'info' })
1429
+ setPhase('send_qr')
1430
+ return
1431
+ }
1432
+
1433
+ // An ack of any kind proves the encrypted link carried this frame to the
1434
+ // peer. Presentation only.
1435
+ if (!controller.signal.aborted) setLinked(true)
1436
+
1437
+ // The ack is a money decision, so it is acted on even if the screen has
1438
+ // since been abandoned — releasing or reclaiming the transaction must not
1439
+ // depend on this component still being mounted. Only the UI writes below
1440
+ // are gated on the abort.
1441
+ const outcome = await finalizeDelivery(wallet as unknown as PayingWalletArg, built, ack, adminOriginator, {
1442
+ hold: async txid => {
1443
+ // `finalizeDelivery` already treats a thrown hold as non-fatal
1444
+ // (`broadcast: 'pending'`), so a clear error here is strictly
1445
+ // better than the null-dereference `storage as never` would throw
1446
+ // instead — same outward outcome, an honest cause.
1447
+ if (!storage) throw new Error('no local storage to queue this payment in')
1448
+ await holdSentPaymentOffline({ storage, txid })
1449
+ },
1450
+ queueFailedAbort: async reference => {
1451
+ if (!storage) return
1452
+ await queuePendingAbort(storage, { reference, originator: adminOriginator })
1453
+ }
1454
+ })
1455
+ if (controller.signal.aborted) return
1456
+
1457
+ if (outcome.kind === 'declined') {
1458
+ // An explicit decline: the peer processed the frame and refused it, so
1459
+ // nothing was queued there and finalizeDelivery has released the inputs.
1460
+ // Because they are released, the frame must NOT then be offered as a QR
1461
+ // fallback — handing over a transaction whose inputs this wallet now
1462
+ // considers free invites a double-spend. Clearing paymentQr also drops
1463
+ // any stale QR left by an earlier attempt.
1464
+ setPaymentQr(null)
1465
+ fail('generic', declineMessage(outcome.reason))
1466
+ return
1467
+ }
1468
+
1469
+ // Positive ack: the payee has durably queued this payment, so it is sent
1470
+ // whatever happened to the broadcast. `broadcast: 'pending'` means only
1471
+ // that this device could not get the transaction out itself — the payee
1472
+ // holds a copy and will internalize it — so it is a retryable notice, not
1473
+ // a failure. Reporting it as a failure would invite a second payment.
1474
+ //
1475
+ // It is a WARNING, not a success: this device's copy of the transaction is
1476
+ // inert and its inputs stay locked. Green on this screen means confirmed
1477
+ // money, and a stuck broadcast is not that.
1478
+ if (outcome.broadcast === 'pending') {
1479
+ console.warn('[localpay] broadcast after a positive ack failed:', outcome.detail ?? '')
1480
+ setNotice({ text: t('local_pay_broadcast_pending'), tone: 'warning' })
1481
+ }
1482
+ // `built.satoshis` is the real amount the wallet locked into the output —
1483
+ // `payAmount` is only what was requested, and the two diverge under
1484
+ // send-max (`payAmount` carries the sentinel).
1485
+ setSettledAmount(built.satoshis)
1486
+ setPhase('done')
1487
+ } finally {
1488
+ registry.delete(controller)
1489
+ }
1490
+ }, [scannedSession, sendKind, payAmount, wallet, adminOriginator, storage, abortBuild, declineMessage, fail, t])
1491
+
1492
+ // ── Send: the payer asserts QR delivery ──
1493
+ //
1494
+ // The QR path has no ack channel, so "the payee has it" is the user's claim,
1495
+ // made by tapping Done. Acting on that claim mirrors a positive AWDL ack:
1496
+ // persist the frame (same hold as offline), then broadcast when online.
1497
+ // This replaces the old do-nothing Done, which stranded the transaction at
1498
+ // nosend with no queue row. The risk of a wrong claim is bounded twice over:
1499
+ // the frame is persisted on the queue row, so the code can be re-shown from
1500
+ // /pay while the payee's session PSK is still live (a payee scanning after
1501
+ // the broadcast internalizes the already-mempooled transaction as a merge);
1502
+ // and once that session is gone, the action's payee label and derivation
1503
+ // customInstructions still let the payment be re-sent through the message box
1504
+ // from its own row in the activity list.
1505
+ const completeQrDelivery = useCallback(async (opts?: { celebrate?: boolean; release?: boolean }) => {
1506
+ const celebrate = opts?.celebrate !== false
1507
+ // Done means "they have it" — the payment is released and the drain posts
1508
+ // it. Backing out means nothing of the kind, so the frame is kept and the
1509
+ // transaction stays cancellable instead. Releasing on the way out is what
1510
+ // made Back send the payment outright.
1511
+ const release = opts?.release !== false
1512
+ const built = builtRef.current
1513
+ const session = scannedSession
1514
+ // `paymentQr` is this exact frame already sealed for display — the Done
1515
+ // button that calls this only renders while it is set (see the send_qr
1516
+ // stage below) — so it is reused as the queue row's framePayload rather
1517
+ // than sealing the frame a third time.
1518
+ const framePayload = paymentQr
1519
+ if (!built || !wallet || !session || !framePayload) {
1520
+ // No handle (e.g. re-entry after reset, which clears builtRef and
1521
+ // scannedSession together): nothing to decide, just close.
1522
+ if (celebrate) {
1523
+ setSettledAmount(payAmount)
1524
+ setRole('payer')
1525
+ setNotice(null)
1526
+ setPhase('done')
1527
+ }
1528
+ return
1529
+ }
1530
+ builtRef.current = null
1531
+ if (celebrate) {
1532
+ setPhase('send_working')
1533
+ setNotice(null)
1534
+ }
1535
+
1536
+ // Backing out never goes through finalizeDelivery: that path broadcasts
1537
+ // after the hold whenever the device is online, so parking inside it would
1538
+ // still have sent the payment. Park and stop.
1539
+ if (!release) {
1540
+ try {
1541
+ if (storage && built.txid) {
1542
+ await parkSentPaymentOffline({ storage, txid: built.txid, framePayload })
1543
+ }
1544
+ } catch (e) {
1545
+ console.warn('[localpay] could not park the payment:', e instanceof Error ? e.message : e)
1546
+ }
1547
+ return
1548
+ }
1549
+
1550
+ const outcome = await finalizeDelivery(wallet as unknown as PayingWalletArg, built, { ok: true }, adminOriginator, {
1551
+ hold: async txid => {
1552
+ if (!storage) throw new Error('no local storage to queue this payment in')
1553
+ await holdSentPaymentOffline({ storage, txid, framePayload })
1554
+ },
1555
+ queueFailedAbort: async reference => {
1556
+ if (!storage) return
1557
+ await queuePendingAbort(storage, { reference, originator: adminOriginator })
1558
+ }
1559
+ })
1560
+ if (outcome.kind === 'sent' && outcome.broadcast === 'pending') {
1561
+ console.warn('[localpay] QR delivery queued or broadcast pending:', outcome.detail ?? '')
1562
+ if (celebrate) setNotice({ text: t('local_pay_broadcast_pending'), tone: 'warning' })
1563
+ }
1564
+ if (celebrate) {
1565
+ setSettledAmount(built.satoshis)
1566
+ setRole('payer')
1567
+ setPhase('done')
1568
+ }
1569
+ }, [wallet, storage, adminOriginator, payAmount, scannedSession, paymentQr, t])
1570
+
1571
+ // ── Send: leave send_qr without Done ──
1572
+ //
1573
+ // The QR path has no ack, so the payer cannot know whether the code was
1574
+ // scanned — and asking them was worse than useless: a wrong "no" aborts a
1575
+ // payment the payee is holding, and nobody can answer honestly for a code
1576
+ // that may have been read in a glance. So backing out is never destructive.
1577
+ // It keeps the payment exactly as Done does: the frame is persisted with the
1578
+ // queue row, so the transaction survives for the payee to broadcast, and the
1579
+ // payer can re-send the details later from the transaction's own row.
1580
+ // Leaving is silent — no celebration for a payment the payer walked away
1581
+ // from — but the money is treated identically.
1582
+ const handleSendQrExit = useCallback(
1583
+ async (leavingScreen: boolean): Promise<boolean> => {
1584
+ // Never celebrates, and never releases: the payer walked away rather than
1585
+ // confirming the hand-over. A success screen would claim something they
1586
+ // did not say, and broadcasting would do something they did not ask for.
1587
+ await completeQrDelivery({ celebrate: false, release: false })
1588
+ // Back means "out of this payment", not "one step up it". Landing on the
1589
+ // Pay chooser leaves the payer inside a flow they just left, one tap from
1590
+ // rebuilding the payment they parked; the wallet is where the parked row
1591
+ // — and its Resend and Cancel — actually is.
1592
+ reset()
1593
+ onExit()
1594
+ router.dismissTo('/')
1595
+ return leavingScreen
1596
+ },
1597
+ [completeQrDelivery, reset, onExit, router]
1598
+ )
1599
+
1600
+ useEffect(() => {
1601
+ if (phase !== 'send_qr') {
1602
+ sendQrAllowLeaveRef.current = false
1603
+ return
1604
+ }
1605
+ const unsub = navigation.addListener(
1606
+ 'beforeRemove',
1607
+ (e: { preventDefault: () => void; data: { action: object } }) => {
1608
+ if (sendQrAllowLeaveRef.current) return
1609
+ e.preventDefault()
1610
+ sendQrAllowLeaveRef.current = true
1611
+ void handleSendQrExit(true)
1612
+ }
1613
+ )
1614
+ return unsub
1615
+ }, [phase, navigation, handleSendQrExit])
1616
+
1617
+ // ── Receive: retry a settle that never reached storage ──
1618
+
1619
+ const retrySettle = useCallback(() => {
1620
+ if (!unsettled) return
1621
+ setFailure(null)
1622
+ // No confirm handle by construction: Unsettled is only ever populated for
1623
+ // a delivery that was not declined, which today means the QR path.
1624
+ void settleRef.current(unsettled.frame, unsettled.session)
1625
+ }, [unsettled])
1626
+
1627
+ // ── QR encoder failures ──
1628
+ //
1629
+ // react-native-qrcode-svg calls onError from inside its own render and returns
1630
+ // null; without a handler it rethrows and the app-level ErrorBoundary replaces
1631
+ // the whole app. Flipping parent state synchronously from a child's render
1632
+ // triggers React's cross-component update warning, so both handlers defer by a
1633
+ // microtask. PaymentQrDisplay reports an unrenderable payload on this same
1634
+ // channel, since its encoder now throws before there is anything to render.
1635
+ // These are backstops — every setPaymentQr(sealedToQr(...)) call site
1636
+ // already gates the sealed frame on MAX_MESSAGE_BYTES before calling it.
1637
+
1638
+ const onSessionQrError = useCallback(() => {
1639
+ void Promise.resolve().then(() => setSessionQrBroken(true))
1640
+ }, [])
1641
+
1642
+ const onPaymentQrError = useCallback(() => {
1643
+ void Promise.resolve().then(() => {
1644
+ setPaymentQr(null)
1645
+ fail('generic', t('local_pay_too_large'))
1646
+ })
1647
+ }, [fail, t])
1648
+
1649
+ // ── Derived ──
1650
+
1651
+ // Source blocks in the payment code. One block renders as a still QR, so the
1652
+ // "hold steady while it animates" hint would be wrong copy for it.
1653
+ const paymentQrBlocks = useMemo(() => {
1654
+ if (!paymentQr) return 0
1655
+ try {
1656
+ return Math.ceil(frameBytesFromQr(paymentQr).length / FRAME_BLOCK_BYTES)
1657
+ } catch {
1658
+ return 0
1659
+ }
1660
+ }, [paymentQr])
1661
+
1662
+ const sessionQr = useMemo(() => {
1663
+ if (!hostedSession) return null
1664
+ try {
1665
+ return encodeSession(hostedSession)
1666
+ } catch {
1667
+ return null
1668
+ }
1669
+ }, [hostedSession])
1670
+
1671
+ /** Radios that have given up, in a render-friendly shape. */
1672
+ const radioFailures = useMemo(
1673
+ () =>
1674
+ (Object.entries(radioErrors) as [RadioKind, { networkDenied: boolean } | undefined][]).filter(
1675
+ (entry): entry is [RadioKind, { networkDenied: boolean }] => entry[1] !== undefined
1676
+ ),
1677
+ [radioErrors]
1678
+ )
1679
+ /** Listening over at least one radio link right now. Goes false once every fast path gives up. */
1680
+ const radioActive = hostedSession !== null && radioTransports.some(tr => !radioErrors[tr.kind as RadioKind])
1681
+ const canSend = payAmount > 0
1682
+ const scannerOpen = phase === 'send_scan' || phase === 'receive_scan'
1683
+
1684
+ /**
1685
+ * What the presence row is entitled to claim, per phase.
1686
+ *
1687
+ * Every branch is driven by something observed. There is no branch for "the
1688
+ * peer is probably nearby": `ready` says a route exists, `waiting` says this
1689
+ * device is genuinely listening or searching, `linked` is only ever set after
1690
+ * bytes crossed the encrypted channel, and `qr` admits there is no link at all.
1691
+ */
1692
+ const presence = useMemo<{ state: PresenceState; label: string } | null>(() => {
1693
+ const at = (state: PresenceState, key: string) => ({ state, label: t(key) })
1694
+ const qr = () => at('qr', 'local_pay_presence_qr')
1695
+
1696
+ // Terminal first: `paid` is the only state that may be green, and nothing
1697
+ // below can override it.
1698
+ if (phase === 'done') return at('paid', 'local_pay_presence_paid')
1699
+
1700
+ // `linked` is a proven fact — bytes crossed the encrypted channel — so it
1701
+ // outranks anything the phase alone would guess about the peer.
1702
+ if (linked) return at('linked', 'local_pay_presence_linked')
1703
+
1704
+ if (role === 'payee') {
1705
+ if (phase === 'receive_settling') return at('linked', 'local_pay_presence_linked')
1706
+ if (phase === 'receive_wait') {
1707
+ // No radio listener means no live link at all, whatever the reason —
1708
+ // an unsupported device, a denied permission, or a fast path that gave up.
1709
+ return radioActive ? at('waiting', 'local_pay_presence_waiting_payee') : qr()
1710
+ }
1711
+ return null
1712
+ }
1713
+
1714
+ if (role === 'payer') {
1715
+ // Every payer branch degrades to `qr` when the QR transport was selected,
1716
+ // because on that path the two devices genuinely never speak. `awdl`,
1717
+ // `nearby` and `ble` are all live radio links, so any of them counts here.
1718
+ const onRadio = sendKind === 'awdl' || sendKind === 'nearby' || sendKind === 'ble'
1719
+ if (phase === 'send_working') {
1720
+ return onRadio ? at('waiting', 'local_pay_presence_waiting_payer') : qr()
1721
+ }
1722
+ if (phase === 'send_qr') return qr()
1723
+ if (phase === 'send_confirm') {
1724
+ return onRadio ? at('ready', 'local_pay_presence_ready') : qr()
1725
+ }
1726
+ return null
1727
+ }
1728
+
1729
+ return null
1730
+ }, [phase, role, linked, radioActive, sendKind, t])
1731
+
1732
+ /**
1733
+ * Which radio the presence row's glyph names. The payee shows Bluetooth only
1734
+ * when BLE is the ONLY radio still listening — while Wi-Fi is alive it is the
1735
+ * faster rung and the one a same-OS payer will land on. The payer shows the
1736
+ * rung the ladder actually picked (spec §6).
1737
+ */
1738
+ const presenceMedium = useMemo<'wifi' | 'bluetooth'>(() => {
1739
+ if (role === 'payer') return sendKind === 'ble' ? 'bluetooth' : 'wifi'
1740
+ const live = radioTransports.filter(tr => !radioErrors[tr.kind as RadioKind])
1741
+ return live.length > 0 && live.every(tr => tr.kind === 'ble') ? 'bluetooth' : 'wifi'
1742
+ }, [role, sendKind, radioTransports, radioErrors])
1743
+
1744
+ // Dismissing the camera returns to whatever raised it. A payee's request must
1745
+ // survive this: closing the scanner is not cancelling the payment.
1746
+ const closeScanner = useCallback(() => {
1747
+ scanLatchRef.current = false
1748
+ setPhase(current => (current === 'receive_scan' ? 'receive_wait' : 'entry'))
1749
+ }, [])
1750
+
1751
+ const styles = useMemo(() => makeStyles(), [])
1752
+
1753
+ // Entrances: opacity + translate only, springs.snappy. Suppressed entirely
1754
+ // under reduced motion rather than shortened, and never applied to an
1755
+ // ancestor of a blur surface.
1756
+ const settleIn = reducedMotion
1757
+ ? undefined
1758
+ : FadeInDown.springify()
1759
+ .mass(springs.snappy.mass)
1760
+ .damping(springs.snappy.damping)
1761
+ .stiffness(springs.snappy.stiffness)
1762
+ const fadeIn = reducedMotion ? undefined : FadeIn.duration(durations.instant)
1763
+
1764
+ // ── Render ──
1765
+
1766
+ const amountBlock = (sats: number, key?: string) => (
1767
+ <Animated.View key={key} entering={settleIn} style={styles.amountBlock}>
1768
+ <Text
1769
+ style={[styles.amountDisplay, { color: colors.textPrimary }]}
1770
+ maxFontSizeMultiplier={1.3}
1771
+ numberOfLines={1}
1772
+ adjustsFontSizeToFit
1773
+ accessibilityRole="text"
1774
+ >
1775
+ <AmountDisplay>{sats}</AmountDisplay>
1776
+ </Text>
1777
+ </Animated.View>
1778
+ )
1779
+
1780
+ const presenceBlock = presence ? (
1781
+ <View style={styles.presenceSlot}>
1782
+ <PresenceRow state={presence.state} label={presence.label} peer={peerName} medium={presenceMedium} />
1783
+ </View>
1784
+ ) : null
1785
+
1786
+ const phaseTitle = (label: string) => (
1787
+ <Text
1788
+ style={[styles.title, { color: colors.textPrimary }]}
1789
+ // The nearest RN has to `text-wrap: balance`. Android honours it; iOS has
1790
+ // no equivalent, so headings are also kept short enough to fit two lines
1791
+ // at the default size in every locale.
1792
+ textBreakStrategy="balanced"
1793
+ maxFontSizeMultiplier={1.4}
1794
+ >
1795
+ {label}
1796
+ </Text>
1797
+ )
1798
+
1799
+ const supportText = (label: string) => (
1800
+ <Text style={[styles.support, { color: colors.textSecondary }]} textBreakStrategy="balanced">
1801
+ {label}
1802
+ </Text>
1803
+ )
1804
+
1805
+ const spinnerBlock = (label: string) => (
1806
+ <View style={styles.stage} accessibilityRole="progressbar" accessibilityLabel={label}>
1807
+ <ActivityIndicator size="large" color={colors.textSecondary} />
1808
+ <View style={styles.gapLg} />
1809
+ {supportText(label)}
1810
+ {presenceBlock}
1811
+ </View>
1812
+ )
1813
+
1814
+ const noticeBlock = (n: Notice) => {
1815
+ const tint = n.tone === 'success' ? colors.success : n.tone === 'warning' ? colors.warning : colors.textSecondary
1816
+ return (
1817
+ <Animated.View
1818
+ entering={fadeIn}
1819
+ style={[
1820
+ styles.notice,
1821
+ {
1822
+ backgroundColor: n.tone === 'info' ? colors.fillTertiary : tint + '15',
1823
+ borderColor: n.tone === 'info' ? colors.separator : tint + '40'
1824
+ }
1825
+ ]}
1826
+ accessibilityRole="text"
1827
+ >
1828
+ <Ionicons name={NOTICE_ICONS[n.tone]} size={16} color={tint} />
1829
+ <Text style={[styles.noticeText, { color: n.tone === 'info' ? colors.textSecondary : tint }]}>{n.text}</Text>
1830
+ </Animated.View>
1831
+ )
1832
+ }
1833
+
1834
+ return (
1835
+ <View style={[styles.container, { backgroundColor: colors.backgroundSecondary }]}>
1836
+ <ScrollView
1837
+ style={{ flex: 1, backgroundColor: colors.background }}
1838
+ contentContainerStyle={[styles.scroll, { paddingBottom: insets.bottom + spacing.xxxl }]}
1839
+ keyboardShouldPersistTaps="handled"
1840
+ >
1841
+ {/* ══ Payer entry ══
1842
+ The Pay screen's grid already asked which side of the exchange this
1843
+ device is on, so there is no role choice left to make here and only
1844
+ one action: raise the camera again. Reached only by dismissing the
1845
+ scanner that opens on mount — a payee never sees this view, they go
1846
+ straight to naming an amount. */}
1847
+ {phase === 'entry' && initialRole === 'payer' && (
1848
+ <Animated.View entering={settleIn} style={styles.stage}>
1849
+ <View style={[styles.heroCircle, { backgroundColor: colors.fillTertiary }]}>
1850
+ <Ionicons name="qr-code-outline" size={44} color={colors.textSecondary} />
1851
+ </View>
1852
+ <View style={styles.gapLg} />
1853
+ {phaseTitle(t('local_pay_scan_qr'))}
1854
+ {supportText(t('pay_pre_nearby'))}
1855
+ <View style={styles.gapXl} />
1856
+ <PrimaryButton
1857
+ styles={styles}
1858
+ colors={colors}
1859
+ icon="scan-outline"
1860
+ label={t('local_pay_scan_qr')}
1861
+ onPress={() => openScanner('send_scan')}
1862
+ />
1863
+
1864
+ {/* TEMPORARY simulator affordance — __DEV__ only, never ships.
1865
+ The simulator has no camera, so the payer flow is unreachable
1866
+ there. This mints an OPEN session (no amount) and feeds it
1867
+ through the real `onSessionScanned`, so decodeSession and every
1868
+ downstream branch run exactly as they would from a real scan —
1869
+ what you see is the genuine payer UI, not a mock.
1870
+ supportsAwdl is false so selectTransport picks the QR path,
1871
+ which is the one a simulator can actually complete. */}
1872
+ {__DEV__ && (
1873
+ <>
1874
+ <View style={styles.gapMd} />
1875
+ <SecondaryButton
1876
+ styles={styles}
1877
+ colors={colors}
1878
+ icon="construct"
1879
+ label="DEV: pay an open request"
1880
+ onPress={() => {
1881
+ scanLatchRef.current = false
1882
+ onSessionScanned(
1883
+ encodeSession(
1884
+ mintSession({
1885
+ // secp256k1 generator point: a genuinely valid
1886
+ // compressed pubkey, so key derivation won't throw.
1887
+ identityKey: '0279BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798',
1888
+ derivationPrefix: 'ZGV2LXByZWZpeA==',
1889
+ derivationSuffix: 'ZGV2LXN1ZmZpeA==',
1890
+ supportsAwdl: false
1891
+ })
1892
+ )
1893
+ )
1894
+ }}
1895
+ />
1896
+ </>
1897
+ )}
1898
+ </Animated.View>
1899
+ )}
1900
+
1901
+ {/* ══ Receive: amount ══
1902
+ Focal: the amount field. Everything else on the view is a label. */}
1903
+ {phase === 'receive_amount' && (
1904
+ <Animated.View entering={settleIn}>
1905
+ {phaseTitle(t('local_pay_request'))}
1906
+ <View style={styles.gapXl} />
1907
+
1908
+ {/* No max button and no balance line: this asks the PAYER for money,
1909
+ so the requester's own balance is meaningless here. Zero or blank
1910
+ is a real choice — payer decides — and the design says so by not
1911
+ gating on it. */}
1912
+ <PayAmountField value={requestAmount} onChangeText={setRequestAmount} showMax={false} showBalance={false} />
1913
+ {/* Never disabled. Leaving the amount at zero is a real choice — it
1914
+ means "payer decides" — so gating Continue on a non-zero amount
1915
+ would make that choice unreachable. startRequest maps 0 to an
1916
+ open session. */}
1917
+ <PrimaryButton
1918
+ styles={styles}
1919
+ colors={colors}
1920
+ label={t('continue_action')}
1921
+ onPress={() => void startRequest(satsFrom(requestAmount) || undefined)}
1922
+ />
1923
+ <CancelButton styles={styles} colors={colors} label={t('cancel')} onPress={reset} />
1924
+ </Animated.View>
1925
+ )}
1926
+
1927
+ {/* Focal on each of these: the single status line. */}
1928
+ {phase === 'receive_minting' && spinnerBlock(t('local_pay_preparing'))}
1929
+ {phase === 'receive_settling' && spinnerBlock(t('local_pay_saving'))}
1930
+ {phase === 'send_working' && spinnerBlock(t('local_pay_delivering'))}
1931
+
1932
+ {/* ══ Receive: pairing QR (always) + AWDL listener (when supported) ══
1933
+ Focal: the pairing code. This is the one view whose focal element is
1934
+ not the amount, and deliberately: the code is the object being
1935
+ physically held up to another person, and shrinking a working
1936
+ scanner target to win a typographic argument would be the wrong
1937
+ trade. The amount sits above it at title scale, as the code's price. */}
1938
+ {phase === 'receive_wait' && hostedSession && (
1939
+ <Animated.View entering={settleIn} style={styles.stage}>
1940
+ {phaseTitle(t('local_pay_show_qr'))}
1941
+ <Text
1942
+ style={[styles.amountTitle, { color: colors.textSecondary }]}
1943
+ maxFontSizeMultiplier={1.4}
1944
+ numberOfLines={1}
1945
+ >
1946
+ {hostedSession.amount === undefined ? (
1947
+ t('local_pay_any_amount')
1948
+ ) : (
1949
+ <AmountDisplay>{hostedSession.amount}</AmountDisplay>
1950
+ )}
1951
+ </Text>
1952
+ <View style={styles.gapLg} />
1953
+
1954
+ {sessionQr && !sessionQrBroken ? (
1955
+ <View style={[styles.qrCard, { shadowColor: colors.textPrimary }]}>
1956
+ <View style={styles.qrPlate}>
1957
+ {/* onError is mandatory: without it the encoder rethrows from
1958
+ render and the app-level ErrorBoundary swallows the app. */}
1959
+ <QRCode
1960
+ value={sessionQr}
1961
+ size={PAYMENT_QR_SIZE}
1962
+ ecl="M"
1963
+ color="#000"
1964
+ backgroundColor="#fff"
1965
+ onError={onSessionQrError}
1966
+ />
1967
+ </View>
1968
+ </View>
1969
+ ) : (
1970
+ // Error state for this data area. The session cannot be handed
1971
+ // over at all, so the only way forward is a fresh one.
1972
+ <View
1973
+ style={[styles.qrError, { backgroundColor: colors.fillTertiary, borderColor: colors.separator }]}
1974
+ accessibilityRole="alert"
1975
+ >
1976
+ <Ionicons name="alert-circle-outline" size={28} color={colors.error} />
1977
+ <View style={styles.gapSm} />
1978
+ <Text style={[styles.support, { color: colors.textSecondary }]}>{t('local_pay_qr_unavailable')}</Text>
1979
+ </View>
1980
+ )}
1981
+
1982
+ <View style={styles.gapLg} />
1983
+ {presenceBlock}
1984
+
1985
+ {/* A frame arrived that belongs to a different request. Advisory,
1986
+ not a failure: this session was deliberately NOT marked spent,
1987
+ so the pairing QR above is still live for the real payer. */}
1988
+ {sessionMismatch && (
1989
+ <>
1990
+ <View style={styles.gapLg} />
1991
+ <Animated.View
1992
+ entering={fadeIn}
1993
+ style={[styles.notice, { backgroundColor: colors.error + '15', borderColor: colors.error + '40' }]}
1994
+ accessibilityRole="alert"
1995
+ >
1996
+ <Ionicons name="alert-circle-outline" size={16} color={colors.error} />
1997
+ <Text style={[styles.noticeText, { color: colors.error }]}>{t('local_pay_wrong_session')}</Text>
1998
+ </Animated.View>
1999
+ </>
2000
+ )}
2001
+
2002
+ {/* A radio gave up. The request is still live over QR — and over
2003
+ any other radio still listening — so each of these is an
2004
+ advisory, not a failure: the pairing QR above still works. */}
2005
+ {radioFailures.map(([kind, err]) => (
2006
+ <React.Fragment key={kind}>
2007
+ <View style={styles.gapLg} />
2008
+ <Animated.View
2009
+ entering={fadeIn}
2010
+ style={[styles.notice, { backgroundColor: colors.fillTertiary, borderColor: colors.separator }]}
2011
+ >
2012
+ <Ionicons name="information-circle-outline" size={16} color={colors.textSecondary} />
2013
+ <Text style={[styles.noticeText, { color: colors.textSecondary }]}>
2014
+ {err.networkDenied
2015
+ ? t('local_pay_network_denied')
2016
+ : kind === 'ble'
2017
+ ? t('local_pay_ble_unavailable')
2018
+ : t('local_pay_nearby_unavailable')}
2019
+ </Text>
2020
+ </Animated.View>
2021
+ </React.Fragment>
2022
+ ))}
2023
+
2024
+ <View style={styles.gapXl} />
2025
+ {radioFailures.some(([, err]) => err.networkDenied) && (
2026
+ <>
2027
+ <SecondaryButton
2028
+ styles={styles}
2029
+ colors={colors}
2030
+ icon="settings-outline"
2031
+ label={t('open_settings')}
2032
+ onPress={() => void Linking.openSettings()}
2033
+ />
2034
+ <View style={styles.gapMd} />
2035
+ </>
2036
+ )}
2037
+ <SecondaryButton
2038
+ styles={styles}
2039
+ colors={colors}
2040
+ icon="scan-outline"
2041
+ label={t('local_pay_scan_payer_qr')}
2042
+ onPress={() => openScanner('receive_scan')}
2043
+ />
2044
+ <CancelButton styles={styles} colors={colors} label={t('cancel')} onPress={reset} />
2045
+ </Animated.View>
2046
+ )}
2047
+
2048
+ {/* ══ Send: confirm ══
2049
+ Focal: the amount — the figure being handed over, at display scale
2050
+ when the payee fixed it, or the live field when they left it open. */}
2051
+ {phase === 'send_confirm' && scannedSession && (
2052
+ <Animated.View entering={settleIn}>
2053
+ {phaseTitle(scannedSession.amount === undefined ? t('local_pay_choose_amount') : t('local_pay_send'))}
2054
+
2055
+ {scannedSession.amount === undefined ? (
2056
+ <>
2057
+ {supportText(t('local_pay_enter_amount_send'))}
2058
+ <View style={styles.gapXl} />
2059
+ <PayAmountField value={sendAmount} onChangeText={setSendAmount} />
2060
+ </>
2061
+ ) : (
2062
+ <>
2063
+ <View style={styles.stageTight}>{amountBlock(scannedSession.amount)}</View>
2064
+ <View style={styles.gapXl} />
2065
+ <AvailableBalance withUnit />
2066
+ </>
2067
+ )}
2068
+
2069
+ <RecipientSummary
2070
+ name={peerName ?? abbreviateKey(scannedSession.identityKey)}
2071
+ detail={peerName ? abbreviateKey(scannedSession.identityKey) : undefined}
2072
+ />
2073
+
2074
+ <View style={styles.gapLg} />
2075
+ {presenceBlock}
2076
+ {floorReason !== 'none' && (
2077
+ <>
2078
+ <View style={styles.gapLg} />
2079
+ {supportText(t(FLOOR_KEYS[floorReason]))}
2080
+ {floorReason === 'local_ble_denied' && (
2081
+ <>
2082
+ <View style={styles.gapMd} />
2083
+ <SecondaryButton
2084
+ styles={styles}
2085
+ colors={colors}
2086
+ icon="settings-outline"
2087
+ label={t('open_settings')}
2088
+ onPress={() => void Linking.openSettings()}
2089
+ />
2090
+ </>
2091
+ )}
2092
+ </>
2093
+ )}
2094
+
2095
+ <View style={styles.gapXl} />
2096
+ <PrimaryButton
2097
+ styles={styles}
2098
+ colors={colors}
2099
+ icon="arrow-up"
2100
+ label={t('local_pay_send')}
2101
+ disabled={!canSend}
2102
+ onPress={() => void executeSend()}
2103
+ />
2104
+ <CancelButton styles={styles} colors={colors} label={t('cancel')} onPress={reset} />
2105
+ </Animated.View>
2106
+ )}
2107
+
2108
+ {/* ══ Send: hand the frame over as a QR ══
2109
+ Focal: the payment code. The amount is settled by this point and
2110
+ demotes to a caption. */}
2111
+ {phase === 'send_qr' && paymentQr && (
2112
+ <Animated.View entering={settleIn} style={styles.stage}>
2113
+ {phaseTitle(t('local_pay_show_payment_qr'))}
2114
+ <Text
2115
+ style={[styles.amountTitle, { color: colors.textSecondary }]}
2116
+ maxFontSizeMultiplier={1.4}
2117
+ numberOfLines={1}
2118
+ >
2119
+ <AmountDisplay>{payAmount}</AmountDisplay>
2120
+ </Text>
2121
+ {paymentQrBlocks > 1 && (
2122
+ <Text style={[styles.support, { color: colors.textSecondary }]}>{t('local_pay_animated_hint')}</Text>
2123
+ )}
2124
+ <View style={styles.gapLg} />
2125
+ <View style={[styles.qrCard, { shadowColor: colors.textPrimary }]}>
2126
+ <View style={styles.qrPlate}>
2127
+ {/* onError is mandatory: without it an oversize payload rethrows
2128
+ from render and the app-level ErrorBoundary swallows the app. */}
2129
+ <PaymentQrDisplay frameQr={paymentQr} size={PAYMENT_QR_SIZE} onError={onPaymentQrError} />
2130
+ </View>
2131
+ </View>
2132
+ <View style={styles.gapLg} />
2133
+ {presenceBlock}
2134
+ {!!notice && (
2135
+ <>
2136
+ <View style={styles.gapLg} />
2137
+ {noticeBlock(notice)}
2138
+ </>
2139
+ )}
2140
+ <View style={styles.gapXl} />
2141
+ {/* Done asserts delivery: persist the frame, then broadcast when
2142
+ online (see completeQrDelivery / finalizeDelivery). Never an
2143
+ abort — the payee may be about to broadcast this frame, and
2144
+ freeing its inputs would let this wallet respend them. */}
2145
+ <PrimaryButton
2146
+ styles={styles}
2147
+ colors={colors}
2148
+ label={t('done')}
2149
+ onPress={() => void completeQrDelivery()}
2150
+ />
2151
+ {/* Not "Cancel": leaving keeps the payment exactly as Done does,
2152
+ so the old label promised an abort that no longer happens. */}
2153
+ <CancelButton
2154
+ styles={styles}
2155
+ colors={colors}
2156
+ label={t('back')}
2157
+ onPress={() => void handleSendQrExit(false)}
2158
+ />
2159
+ </Animated.View>
2160
+ )}
2161
+
2162
+ {/* ══ Done ══
2163
+ Focal: the amount. The celebration mark is a transient overlay that
2164
+ owns attention for ~700ms and then hands it back, so the two never
2165
+ compete for the same beat. */}
2166
+ {/* ══ Already paid — a success terminal, not an error ══
2167
+ Focal: the headline. There is no figure to show — this device never
2168
+ saw a second payment — so nothing here is at display scale. */}
2169
+ {phase === 'already_paid' && (
2170
+ <Animated.View entering={settleIn} style={styles.stage}>
2171
+ <Ionicons name="checkmark-done-circle-outline" size={56} color={colors.textSecondary} />
2172
+ <View style={styles.gapLg} />
2173
+ {phaseTitle(t('local_pay_already_paid'))}
2174
+ {supportText(t('local_pay_queued'))}
2175
+ <View style={styles.gapXl} />
2176
+ {/* Deliberately no retry: reset() would mint a fresh session and ask
2177
+ the payer to pay a second time for money already queued here. */}
2178
+ <PrimaryButton styles={styles} colors={colors} label={t('done')} onPress={goBack} />
2179
+ </Animated.View>
2180
+ )}
2181
+
2182
+ {/* ══ Failed ══
2183
+ Focal: the reason. The title is generic by design, so the sentence
2184
+ under it carries the information and gets the weight. */}
2185
+ {phase === 'failed' && (
2186
+ <Animated.View entering={settleIn} style={styles.stage} accessibilityRole="alert">
2187
+ <View style={[styles.heroCircle, { backgroundColor: colors.error + '15' }]}>
2188
+ <Ionicons name="alert-circle-outline" size={40} color={colors.error} />
2189
+ </View>
2190
+ <View style={styles.gapLg} />
2191
+ {phaseTitle(t('local_pay_failed'))}
2192
+ <Text style={[styles.reason, { color: colors.textPrimary }]} textBreakStrategy="balanced">
2193
+ {failure?.detail}
2194
+ </Text>
2195
+ <View style={styles.gapXl} />
2196
+
2197
+ {/* A frame reached this device but never reached storage. Retry the
2198
+ SAME session — reset() would mint one that can never receive it. */}
2199
+ {unsettled && (
2200
+ <>
2201
+ <PrimaryButton
2202
+ styles={styles}
2203
+ colors={colors}
2204
+ icon="refresh"
2205
+ label={t('local_pay_retry_save')}
2206
+ onPress={retrySettle}
2207
+ />
2208
+ <View style={styles.gapMd} />
2209
+ </>
2210
+ )}
2211
+
2212
+ {failure?.settings && (
2213
+ <>
2214
+ <SecondaryButton
2215
+ styles={styles}
2216
+ colors={colors}
2217
+ icon="settings-outline"
2218
+ label={t('open_settings')}
2219
+ onPress={() => void Linking.openSettings()}
2220
+ />
2221
+ <View style={styles.gapMd} />
2222
+ </>
2223
+ )}
2224
+
2225
+ {failure?.offerWalletCheck && (
2226
+ <>
2227
+ <SecondaryButton
2228
+ styles={styles}
2229
+ colors={colors}
2230
+ label={t('check_wallet')}
2231
+ onPress={() => router.push('/wallet-check' as never)}
2232
+ />
2233
+ <View style={styles.gapMd} />
2234
+ </>
2235
+ )}
2236
+
2237
+ {paymentQr && (
2238
+ <>
2239
+ <SecondaryButton
2240
+ styles={styles}
2241
+ colors={colors}
2242
+ icon="qr-code-outline"
2243
+ label={t('local_pay_show_qr_instead')}
2244
+ onPress={() => {
2245
+ setFailure(null)
2246
+ setPhase('send_qr')
2247
+ }}
2248
+ />
2249
+ <View style={styles.gapMd} />
2250
+ </>
2251
+ )}
2252
+
2253
+ {/* With a frame in hand, reset() means abandoning it — the frame lives
2254
+ only in memory — so it is demoted to the secondary action. */}
2255
+ {unsettled ? (
2256
+ <CancelButton styles={styles} colors={colors} label={t('cancel')} onPress={reset} />
2257
+ ) : (
2258
+ <PrimaryButton styles={styles} colors={colors} label={t('retry')} onPress={retry} />
2259
+ )}
2260
+ </Animated.View>
2261
+ )}
2262
+ </ScrollView>
2263
+
2264
+ {/* ══ Scanner ══ */}
2265
+ <Modal visible={scannerOpen} animationType="slide" onRequestClose={closeScanner} statusBarTranslucent>
2266
+ <StatusBar style="light" />
2267
+ <QRScanner
2268
+ multiScan
2269
+ continuous={phase === 'receive_scan'}
2270
+ onScan={phase === 'send_scan' ? onSessionScanned : onFrameScanned}
2271
+ onClose={closeScanner}
2272
+ hintText={phase === 'send_scan' ? t('local_pay_scan_qr') : t('local_pay_scan_payer_qr')}
2273
+ renderBottom={
2274
+ phase === 'receive_scan' && scanProgress
2275
+ ? () => (
2276
+ <Text style={{ color: 'rgba(255,255,255,0.8)', marginTop: 8 }}>
2277
+ {t('local_pay_scan_progress', { have: scanProgress.have, total: scanProgress.total })}
2278
+ </Text>
2279
+ )
2280
+ : undefined
2281
+ }
2282
+ />
2283
+ </Modal>
2284
+
2285
+ {/* ══ The moment ══
2286
+ One shared overlay for every rail and either direction: full screen,
2287
+ and it stays until acknowledged — being paid in person is the one
2288
+ moment both people are watching for. Shown as soon as the payment is
2289
+ durably queued, even before the payee's wallet has internalized it —
2290
+ the write cannot be lost at that point, and background internalizing
2291
+ catches up on its own; surfacing that separately (if it ever fails)
2292
+ is a job for the activity list, not for withholding this screen. */}
2293
+ {phase === 'done' && (
2294
+ <ReceivedOverlay
2295
+ amount={settledAmount}
2296
+ direction={role === 'payer' ? 'sent' : 'received'}
2297
+ broadcast={role === 'payer' ? undefined : receivedBroadcast}
2298
+ recipientName={
2299
+ role === 'payer' ? (peerName ?? (scannedSession ? abbreviateKey(scannedSession.identityKey) : undefined)) : undefined
2300
+ }
2301
+ // The overlay navigates to the wallet after this; goBack ends the
2302
+ // session and resets the cell so /pay is not left mid-flow beneath.
2303
+ onDismiss={goBack}
2304
+ />
2305
+ )}
2306
+ </View>
2307
+ )
2308
+ }
2309
+
2310
+ // ── Small components ──
2311
+ //
2312
+ // Every control below covers the full interaction set RN can express: default,
2313
+ // pressed (PressableScale's 0.97 spring, plus a fill change where the shape is
2314
+ // not already filled), disabled (dimmed AND announced through
2315
+ // accessibilityState, not colour alone), and focus, which on this platform is
2316
+ // VoiceOver's focus and is served by the role/label/state triple. There is no
2317
+ // hover on a touch device; a pointer-capable iPad hover falls back to the
2318
+ // pressed treatment.
2319
+
2320
+ type Colors = ReturnType<typeof useTheme>['colors']
2321
+ type Styles = ReturnType<typeof makeStyles>
2322
+
2323
+ function PrimaryButton({
2324
+ styles,
2325
+ colors,
2326
+ label,
2327
+ icon,
2328
+ onPress,
2329
+ disabled
2330
+ }: {
2331
+ styles: Styles
2332
+ colors: Colors
2333
+ label: string
2334
+ icon?: keyof IoniconsComponent['glyphMap']
2335
+ onPress: () => void
2336
+ disabled?: boolean
2337
+ }) {
2338
+ const Ionicons = loadIonicons()
2339
+ return (
2340
+ <PressableScale
2341
+ onPress={onPress}
2342
+ disabled={disabled}
2343
+ haptic="confirm"
2344
+ style={[styles.button, { backgroundColor: disabled ? colors.fill : colors.accent }]}
2345
+ accessibilityRole="button"
2346
+ accessibilityLabel={label}
2347
+ accessibilityState={{ disabled: !!disabled }}
2348
+ >
2349
+ {!!icon && <Ionicons name={icon} size={20} color={disabled ? colors.textTertiary : colors.textOnAccent} />}
2350
+ <Text style={[styles.buttonText, { color: disabled ? colors.textTertiary : colors.textOnAccent }]}>{label}</Text>
2351
+ </PressableScale>
2352
+ )
2353
+ }
2354
+
2355
+ function SecondaryButton({
2356
+ styles,
2357
+ colors,
2358
+ label,
2359
+ icon,
2360
+ onPress,
2361
+ disabled
2362
+ }: {
2363
+ styles: Styles
2364
+ colors: Colors
2365
+ label: string
2366
+ icon?: keyof IoniconsComponent['glyphMap']
2367
+ onPress: () => void
2368
+ disabled?: boolean
2369
+ }) {
2370
+ const Ionicons = loadIonicons()
2371
+ return (
2372
+ <PressableScale
2373
+ onPress={onPress}
2374
+ disabled={disabled}
2375
+ haptic="tap"
2376
+ style={[styles.button, styles.buttonOutline, { borderColor: colors.separator }]}
2377
+ accessibilityRole="button"
2378
+ accessibilityLabel={label}
2379
+ accessibilityState={{ disabled: !!disabled }}
2380
+ >
2381
+ {!!icon && <Ionicons name={icon} size={18} color={disabled ? colors.textTertiary : colors.accent} />}
2382
+ <Text style={[styles.buttonText, { color: disabled ? colors.textTertiary : colors.accent }]}>{label}</Text>
2383
+ </PressableScale>
2384
+ )
2385
+ }
2386
+
2387
+ function CancelButton({
2388
+ styles,
2389
+ colors,
2390
+ label,
2391
+ onPress
2392
+ }: {
2393
+ styles: Styles
2394
+ colors: Colors
2395
+ label: string
2396
+ onPress: () => void
2397
+ }) {
2398
+ return (
2399
+ <PressableScale
2400
+ onPress={onPress}
2401
+ haptic="tap"
2402
+ style={styles.cancel}
2403
+ accessibilityRole="button"
2404
+ accessibilityLabel={label}
2405
+ >
2406
+ <Text style={[styles.cancelText, { color: colors.textSecondary }]}>{label}</Text>
2407
+ </PressableScale>
2408
+ )
2409
+ }
2410
+
2411
+ /**
2412
+ * Specific amount vs any amount.
2413
+ *
2414
+ * Concentric by construction: the track's 10pt radius is the segment's 8pt plus
2415
+ * the 2pt inset between them, so the selected pill sits parallel to the outer
2416
+ * edge instead of drifting away from it at the corners.
2417
+ */
2418
+ // ── Styles ──
2419
+ //
2420
+ // Density: 8pt vertical rhythm, 16pt gutter (spacing.lg), 24pt between sections
2421
+ // (spacing.xxl), 8pt within a group (spacing.sm). Horizontal insets use
2422
+ // Start/End rather than Left/Right so Arabic mirrors correctly; `row` is flipped
2423
+ // by Yoga itself.
2424
+
2425
+ function makeStyles() {
2426
+ return StyleSheet.create({
2427
+ container: { flex: 1 },
2428
+ header: {
2429
+ flexDirection: 'row',
2430
+ alignItems: 'center',
2431
+ justifyContent: 'space-between',
2432
+ paddingHorizontal: spacing.sm,
2433
+ paddingVertical: spacing.sm,
2434
+ borderBottomWidth: StyleSheet.hairlineWidth
2435
+ },
2436
+ // 44×44 — the HIG minimum, and the reason the header is 8pt-padded rather
2437
+ // than sized to the glyph.
2438
+ headerBtn: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center' },
2439
+ headerTitle: { ...typography.headline, flexShrink: 1, textAlign: 'center' },
2440
+ scroll: { padding: spacing.lg },
2441
+
2442
+ stage: { alignItems: 'center', paddingVertical: spacing.xxl },
2443
+ stageTight: { alignItems: 'center' },
2444
+
2445
+ // Rhythm spacers. Named for the token so the 8pt grid stays visible in the
2446
+ // markup rather than hiding inside a dozen one-off margins.
2447
+ gapSm: { height: spacing.sm },
2448
+ gapMd: { height: spacing.md },
2449
+ gapLg: { height: spacing.lg },
2450
+ gapXl: { height: spacing.xxl },
2451
+
2452
+ heroCircle: {
2453
+ width: 88,
2454
+ height: 88,
2455
+ borderRadius: 44,
2456
+ alignItems: 'center',
2457
+ justifyContent: 'center'
2458
+ },
2459
+
2460
+ // ── Type: four levels, hierarchy from size + weight + colour together ──
2461
+ // L1 display 44/700 the amount, and only the amount
2462
+ // L2 title2 22/700 the phase heading
2463
+ // L3 subhead 15/400 supporting sentence, textSecondary
2464
+ // L4 footnote 13/400 status and metadata, textTertiary
2465
+ amountBlock: { alignItems: 'center' },
2466
+ amountDisplay: { ...typography.display, fontVariant: ['tabular-nums'], textAlign: 'center' },
2467
+ amountTitle: { ...typography.title2, fontVariant: ['tabular-nums'], textAlign: 'center' },
2468
+ title: { ...typography.title2, textAlign: 'center' },
2469
+ support: { ...typography.subhead, textAlign: 'center', marginTop: spacing.sm },
2470
+ reason: { ...typography.subhead, fontWeight: '500', textAlign: 'center', marginTop: spacing.sm },
2471
+ presenceSlot: { alignSelf: 'stretch', alignItems: 'center' },
2472
+
2473
+ // Concentric: outer 20 = inner plate 4 + padding 16.
2474
+ qrCard: {
2475
+ backgroundColor: '#fff',
2476
+ padding: spacing.lg,
2477
+ borderRadius: radii.xl,
2478
+ shadowOffset: { width: 0, height: 4 },
2479
+ shadowOpacity: 0.1,
2480
+ shadowRadius: 16,
2481
+ elevation: 6
2482
+ },
2483
+ qrPlate: { borderRadius: 4, overflow: 'hidden', backgroundColor: '#fff' },
2484
+ qrError: {
2485
+ alignSelf: 'stretch',
2486
+ alignItems: 'center',
2487
+ paddingVertical: spacing.xxxl,
2488
+ paddingHorizontal: spacing.lg,
2489
+ borderRadius: radii.xl,
2490
+ borderWidth: StyleSheet.hairlineWidth
2491
+ },
2492
+
2493
+ button: {
2494
+ flexDirection: 'row',
2495
+ alignItems: 'center',
2496
+ justifyContent: 'center',
2497
+ alignSelf: 'stretch',
2498
+ gap: spacing.sm,
2499
+ minHeight: 48,
2500
+ paddingVertical: spacing.md,
2501
+ paddingHorizontal: spacing.lg,
2502
+ borderRadius: radii.md
2503
+ },
2504
+ buttonOutline: { borderWidth: StyleSheet.hairlineWidth },
2505
+ buttonText: { ...typography.body, fontWeight: '600' },
2506
+
2507
+ cancel: {
2508
+ alignItems: 'center',
2509
+ justifyContent: 'center',
2510
+ alignSelf: 'stretch',
2511
+ minHeight: 44,
2512
+ paddingVertical: spacing.md,
2513
+ borderRadius: radii.md,
2514
+ marginTop: spacing.lg
2515
+ },
2516
+ cancelText: { ...typography.body, fontWeight: '500' },
2517
+
2518
+ // Concentric: track 10 = segment 8 + 2pt inset.
2519
+ segmentTrack: {
2520
+ flexDirection: 'row',
2521
+ alignSelf: 'stretch',
2522
+ padding: 2,
2523
+ borderRadius: radii.md
2524
+ },
2525
+ segmentTextSelected: { fontWeight: '600' },
2526
+
2527
+ // The resolved-counterparty card and field labels moved to the shared
2528
+ // PayForm vocabulary (RecipientSummary / PayField).
2529
+
2530
+ notice: {
2531
+ flexDirection: 'row',
2532
+ alignItems: 'center',
2533
+ gap: spacing.sm,
2534
+ alignSelf: 'stretch',
2535
+ paddingVertical: spacing.md,
2536
+ paddingHorizontal: spacing.md,
2537
+ borderRadius: radii.md,
2538
+ borderWidth: StyleSheet.hairlineWidth
2539
+ },
2540
+ noticeText: { ...typography.footnote, flex: 1 }
2541
+ })
2542
+ }