@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,687 @@
1
+ /**
2
+ * Pay → anyone.
3
+ *
4
+ * One recipient field decides the rail: a base58check address goes out as a
5
+ * plain P2PKH payment; an identity key, peerpay link or search hit goes out as
6
+ * a PeerPay token dropped in the recipient's message box; a nearby-session
7
+ * code is handed up to the Pay screen, which swaps this form for NearbyFlow.
8
+ * Nothing here is chosen by the user except the recipient and the amount.
9
+ *
10
+ * The form recomposes by what the field resolved to: a note field exists
11
+ * only for handles (an address has nowhere to carry one), and the "they are
12
+ * not notified" consequence is shown only for addresses, where it is
13
+ * load-bearing — a user who pastes an address expecting messaging-style
14
+ * delivery has effectively posted cash.
15
+ */
16
+ import React, { useCallback, useEffect, useMemo, useState } from 'react'
17
+ import { ActivityIndicator, Modal, ScrollView, StyleSheet, Text, TextInput, View } from 'react-native'
18
+ import { useTranslation } from 'react-i18next'
19
+
20
+ import QRScanner from '../QRScanner'
21
+ import AmountDisplay from '../wallet/AmountDisplay'
22
+ import { showAlert } from '../ui/AlertCard'
23
+ import { showChoiceSheet } from '../ui/ChoiceSheet'
24
+ import { promptCheckWallet } from '../../screens/WalletCheckScreen'
25
+ import { userFacingPayError } from '../../../core/pay/userError'
26
+ import PressableScale from '../ui/PressableScale'
27
+ import { showToast } from '../ui/Toast'
28
+ import { ConsequenceNote, PayAmountField, PayCta, PayField } from './PayForm'
29
+ import PaymentSuccessOverlay from './PaymentSuccessOverlay'
30
+ import ResultBanner from './ResultBanner'
31
+ import RecipientField from './RecipientField'
32
+ import { useMessageBoxConfig } from './MessageBoxConfig'
33
+ import { useRecipientInput, type RecipientTarget } from './useRecipientInput'
34
+ import {
35
+ useTheme,
36
+ spacing,
37
+ typography,
38
+ radii,
39
+ hitTargets,
40
+ useWallet,
41
+ CONSEQUENCE_KEYS,
42
+ NO_MESSAGE_BOX,
43
+ cancelOutboxPayment,
44
+ isMessageBoxNetworkError,
45
+ makePeerPayClient,
46
+ retryDelivery,
47
+ sendViaHandle,
48
+ sendToAddress,
49
+ getOutboxEntries,
50
+ pruneExpiredSent,
51
+ unsentEntries,
52
+ type OutboxEntry,
53
+ type Session,
54
+ haptics,
55
+ listPendingResendRequests
56
+ } from '@bsv/expo-wallet-toolbox'
57
+
58
+ /**
59
+ * expo-status-bar's package.json `main` points straight at its raw
60
+ * TypeScript source (no compiled build output ships), and the unscoped,
61
+ * hyphenated package name is not in this repo's Jest transformIgnorePatterns
62
+ * allow-list, so a static top-level import fails to parse for any consumer
63
+ * of the `ui` package barrel. Loaded lazily, only when actually rendering,
64
+ * same pattern as this package's other native/ESM-boundary fixes.
65
+ */
66
+ type StatusBarComponent = typeof import('expo-status-bar').StatusBar
67
+ let statusBarComponent: StatusBarComponent | undefined
68
+ function loadStatusBar(): StatusBarComponent {
69
+ if (!statusBarComponent) {
70
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
71
+ statusBarComponent = require('expo-status-bar').StatusBar as StatusBarComponent
72
+ }
73
+ return statusBarComponent
74
+ }
75
+
76
+ /**
77
+ * expo-router is required lazily rather than imported at module scope: this
78
+ * file is barrel-exported from the package's `ui` entry point, and a static
79
+ * top-level `import` of expo-router pulls in its own untransformed JSX
80
+ * source (Navigator.js etc.), which Jest cannot parse for any consumer of the
81
+ * barrel, even one that never navigates.
82
+ */
83
+ type ExpoRouterModule = typeof import('expo-router')
84
+ let expoRouterMod: ExpoRouterModule | undefined
85
+ function loadExpoRouter(): ExpoRouterModule {
86
+ if (!expoRouterMod) {
87
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
88
+ expoRouterMod = require('expo-router') as ExpoRouterModule
89
+ }
90
+ return expoRouterMod
91
+ }
92
+
93
+ // ── Outgoing Section ─────────────────────────────────────────────────────────
94
+
95
+ interface OutgoingSectionProps {
96
+ readonly entries: OutboxEntry[]
97
+ readonly retryingId: string | null
98
+ readonly colors: ReturnType<typeof import('@bsv/expo-wallet-toolbox').useTheme>['colors']
99
+ readonly t: ReturnType<typeof import('react-i18next').useTranslation>['t']
100
+ readonly onRetry: (entry: OutboxEntry) => void
101
+ readonly onCancel: (entry: OutboxEntry) => void
102
+ }
103
+
104
+ function OutgoingSection({ entries, retryingId, colors, t, onRetry, onCancel }: OutgoingSectionProps) {
105
+ if (entries.length === 0) return null
106
+
107
+ return (
108
+ <PayField labelKey="outgoing_payments">
109
+ <View style={[styles.outgoingCard, { backgroundColor: colors.background, borderColor: colors.separator }]}>
110
+ {entries.map((entry, idx) => {
111
+ const isRetrying = retryingId === entry.id
112
+ const isLast = idx === entries.length - 1
113
+ // Unsent rows: delivery and/or broadcast still outstanding.
114
+ const accentColor = colors.warning
115
+ const truncated = `${entry.recipient.slice(0, 8)}…${entry.recipient.slice(-4)}`
116
+ return (
117
+ <View
118
+ key={entry.id}
119
+ style={[
120
+ styles.outgoingRow,
121
+ { borderLeftColor: accentColor },
122
+ !isLast && { borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: colors.separator }
123
+ ]}
124
+ >
125
+ {/* Top row: recipient key + amount */}
126
+ <View style={styles.outgoingInfo}>
127
+ <View style={styles.outgoingTopRow}>
128
+ <Text style={[styles.outgoingRecipient, { color: colors.textPrimary }]} numberOfLines={1}>
129
+ {truncated}
130
+ </Text>
131
+ <Text style={[styles.outgoingAmount, { color: accentColor }]}>
132
+ <AmountDisplay>{entry.token.amount}</AmountDisplay>
133
+ </Text>
134
+ </View>
135
+
136
+ {/* Status / error text */}
137
+ <Text style={[styles.outgoingStatusText, { color: colors.textSecondary }]} numberOfLines={2}>
138
+ {entry.lastError
139
+ ? isMessageBoxNetworkError(entry.lastError)
140
+ ? t('message_box_unreachable')
141
+ : entry.lastError
142
+ : t('payment_not_delivered')}
143
+ </Text>
144
+
145
+ {/* Action buttons — full-width row, easy tap targets */}
146
+ <View style={[styles.outgoingButtons, { borderTopColor: colors.separator }]}>
147
+ <PressableScale
148
+ onPress={() => onCancel(entry)}
149
+ disabled={isRetrying}
150
+ haptic="tap"
151
+ style={[styles.outgoingDismissButton, { borderRightColor: colors.separator }]}
152
+ >
153
+ <Text style={[styles.outgoingDismissText, { color: colors.textSecondary }]}>{t('cancel')}</Text>
154
+ </PressableScale>
155
+ <PressableScale
156
+ onPress={() => onRetry(entry)}
157
+ disabled={isRetrying}
158
+ haptic="tap"
159
+ style={styles.outgoingRetryButton}
160
+ >
161
+ {isRetrying ? (
162
+ <View style={styles.outgoingRetryBusy}>
163
+ <ActivityIndicator size="small" color={colors.accent} />
164
+ <Text style={[styles.outgoingRetryText, { color: colors.accent }]}>{t('resending')}</Text>
165
+ </View>
166
+ ) : (
167
+ <Text style={[styles.outgoingRetryText, { color: colors.accent }]}>{t('retry')}</Text>
168
+ )}
169
+ </PressableScale>
170
+ </View>
171
+ </View>
172
+ </View>
173
+ )
174
+ })}
175
+ </View>
176
+ </PayField>
177
+ )
178
+ }
179
+
180
+ export interface UniversalSendProps {
181
+ /** A recipient known before the form opened: a peerpay deep link or `?identityKey=`. */
182
+ initialTarget?: Extract<RecipientTarget, { kind: 'handle' }>
183
+ /** Prefilled amount in satoshis from a peerpay link or `?sats=`. */
184
+ initialSats?: number
185
+ /** Error text from a malformed peerpay link, shown as a banner. */
186
+ initialNotice?: string | null
187
+ /** Open the scanner as soon as the form mounts (deep link `cell=pay-nearby`). */
188
+ openScannerOnMount?: boolean
189
+ /** A nearby-session code was scanned. The Pay screen swaps this form for NearbyFlow. */
190
+ onNearbySession: (session: Session) => void
191
+ }
192
+
193
+ export default function UniversalSend({
194
+ initialTarget,
195
+ initialSats,
196
+ initialNotice,
197
+ openScannerOnMount = false,
198
+ onNearbySession
199
+ }: UniversalSendProps) {
200
+ const { t } = useTranslation()
201
+ const { colors } = useTheme()
202
+ const StatusBar = loadStatusBar()
203
+ const { managers, adminOriginator, storage } = useWallet()
204
+ const wallet = managers?.permissionsManager || null
205
+
206
+ // Read-only here: the server is configured in Settings › Advanced.
207
+ const { messageBoxUrl } = useMessageBoxConfig(t)
208
+ const isConfigured = !!messageBoxUrl && messageBoxUrl !== NO_MESSAGE_BOX
209
+
210
+ const [sendAmount, setSendAmount] = useState(initialSats && initialSats > 0 ? String(initialSats) : '')
211
+ const [note, setNote] = useState('')
212
+ const [notice, setNotice] = useState<{ type: 'error'; message: string } | null>(
213
+ initialNotice ? { type: 'error', message: initialNotice } : null
214
+ )
215
+ const [isSending, setIsSending] = useState(false)
216
+ const [sendResult, setSendResult] = useState<{ type: 'success' | 'error'; message: string } | null>(null)
217
+ /** The success moment, held until acknowledged — same screen as every rail. */
218
+ const [sent, setSent] = useState<{ amount: number; recipient?: string } | null>(null)
219
+ const [outbox, setOutbox] = useState<OutboxEntry[]>([])
220
+ const [retryingId, setRetryingId] = useState<string | null>(null)
221
+
222
+ const onPeerPayAmount = useCallback((sats: number) => setSendAmount(String(sats)), [])
223
+ const onPeerPayError = useCallback((message: string) => setNotice({ type: 'error', message }), [])
224
+ const recipient = useRecipientInput({
225
+ wallet,
226
+ adminOriginator,
227
+ initialTarget,
228
+ onPeerPayAmount,
229
+ onPeerPayError,
230
+ onNearbySession
231
+ })
232
+ const target = recipient.target
233
+
234
+ // A second deep link while mounted re-adopts the recipient (useRecipientInput);
235
+ // the amount and the notice it carried must follow, or Pay sends the OLD
236
+ // figure to the NEW person.
237
+ useEffect(() => {
238
+ setSendAmount(initialSats && initialSats > 0 ? String(initialSats) : '')
239
+ }, [initialSats])
240
+ useEffect(() => {
241
+ setNotice(initialNotice ? { type: 'error', message: initialNotice } : null)
242
+ }, [initialNotice])
243
+
244
+ useEffect(() => {
245
+ if (openScannerOnMount) recipient.openScanner()
246
+ // Mount-only by design: re-opening on every render would trap the user in the camera.
247
+ // eslint-disable-next-line react-hooks/exhaustive-deps
248
+ }, [])
249
+
250
+ const peerPayClient = useMemo(
251
+ () => makePeerPayClient({ wallet: wallet as never, messageBoxUrl, originator: adminOriginator }),
252
+ [messageBoxUrl, wallet, adminOriginator]
253
+ )
254
+
255
+ const loadOutbox = useCallback(async () => {
256
+ if (!storage) return
257
+ await pruneExpiredSent(storage)
258
+ setOutbox(unsentEntries(await getOutboxEntries(storage)))
259
+ }, [storage])
260
+
261
+ useEffect(() => {
262
+ void loadOutbox()
263
+ }, [loadOutbox])
264
+
265
+ const pollResendRequests = useCallback(async () => {
266
+ const client = peerPayClient
267
+ if (!client || !storage) return
268
+ try {
269
+ await listPendingResendRequests({ client, storage })
270
+ } catch {
271
+ // Home owns the unanswered-resend banner; a failed poll here is retryable.
272
+ }
273
+ }, [peerPayClient, storage])
274
+
275
+ useEffect(() => {
276
+ void pollResendRequests()
277
+ }, [pollResendRequests])
278
+
279
+ const flashResult = useCallback((result: { type: 'success' | 'error'; message: string }) => {
280
+ setSendResult(result)
281
+ setTimeout(() => setSendResult(null), 5000)
282
+ }, [])
283
+
284
+ const handleWalletCheck = useCallback(
285
+ async (error: unknown): Promise<boolean> => {
286
+ if (!userFacingPayError(error).offerWalletCheck) return false
287
+ const choice = await promptCheckWallet(t)
288
+ if (choice === 'check_wallet') loadExpoRouter().router.push('/wallet-check' as any)
289
+ return true
290
+ },
291
+ [t]
292
+ )
293
+
294
+ const sendHandle = useCallback(
295
+ async (to: Extract<RecipientTarget, { kind: 'handle' }>, sats: number) => {
296
+ const client = peerPayClient
297
+ if (!client) throw new Error(t('message_box_off_hint'))
298
+ if (!storage || !wallet) throw new Error(t('wallet_not_ready'))
299
+ const { satoshis: paidSats } = await sendViaHandle({
300
+ wallet: wallet as any,
301
+ adminOriginator,
302
+ client,
303
+ storage,
304
+ recipient: to.identityKey,
305
+ recipientHost: to.messageBoxUrl,
306
+ satoshis: sats,
307
+ messageBoxUrl,
308
+ note,
309
+ recipientName: recipient.selectedIdentity?.name
310
+ })
311
+ await loadOutbox()
312
+ // The overlay stages its own haptic (inside Celebration) and tone; firing
313
+ // haptics.success() here would double the beat. Only a human-readable
314
+ // name goes on the success screen — a raw identity key is noise there.
315
+ setSent({ amount: paidSats, recipient: recipient.selectedIdentity?.name })
316
+ },
317
+ [peerPayClient, storage, wallet, adminOriginator, messageBoxUrl, note, recipient.selectedIdentity, loadOutbox, t]
318
+ )
319
+
320
+ const sendAddress = useCallback(
321
+ async (to: Extract<RecipientTarget, { kind: 'address' }>, sats: number) => {
322
+ if (!wallet) throw new Error(t('wallet_not_ready'))
323
+ const { paidSatoshis } = await sendToAddress({
324
+ wallet: wallet as any,
325
+ adminOriginator,
326
+ address: to.address,
327
+ satoshis: sats
328
+ })
329
+ setSent({ amount: paidSatoshis, recipient: to.address })
330
+ },
331
+ [wallet, adminOriginator, t]
332
+ )
333
+
334
+ const handleSend = useCallback(async () => {
335
+ if (!target) return
336
+ // Guard before any side effect: a wallet that is not ready must leave the
337
+ // form exactly as typed, with a banner, not a cleared field and silence.
338
+ if (!wallet || !storage) {
339
+ flashResult({ type: 'error', message: t('wallet_not_ready') })
340
+ return
341
+ }
342
+ const sats = Math.round(Number(sendAmount))
343
+ if (!Number.isFinite(sats) || sats <= 0) {
344
+ flashResult({ type: 'error', message: t('enter_valid_amount') })
345
+ return
346
+ }
347
+ haptics.confirm()
348
+ setIsSending(true)
349
+ try {
350
+ if (target.kind === 'handle') await sendHandle(target, sats)
351
+ else await sendAddress(target, sats)
352
+ setSendAmount('')
353
+ setNote('')
354
+ recipient.clearRecipient()
355
+ } catch (error: any) {
356
+ if (await handleWalletCheck(error)) return
357
+ const message =
358
+ error instanceof RangeError
359
+ ? t('enter_valid_amount')
360
+ : isMessageBoxNetworkError(error)
361
+ ? t('message_box_unreachable')
362
+ : error?.message || t('unknown_error')
363
+ flashResult({ type: 'error', message })
364
+ // A failed handle send leaves its entry 'unsent' and offered for retry below.
365
+ if (target.kind === 'handle') await loadOutbox()
366
+ } finally {
367
+ setIsSending(false)
368
+ }
369
+ }, [
370
+ target,
371
+ sendAmount,
372
+ sendHandle,
373
+ sendAddress,
374
+ recipient,
375
+ handleWalletCheck,
376
+ flashResult,
377
+ loadOutbox,
378
+ t,
379
+ wallet,
380
+ storage
381
+ ])
382
+
383
+ const handleRetry = useCallback(
384
+ async (entry: OutboxEntry) => {
385
+ // `peerPayClient` is built from the CURRENT setting, so it wins: the
386
+ // configured host may have changed since this entry was minted, and the
387
+ // client re-resolves the recipient's advertised inbox on every send
388
+ // anyway. The entry's own host is the last resort, for when the user has
389
+ // since opted out of a server entirely. When the entry carries a
390
+ // `recipientHost`, `retryDelivery` passes it as the override regardless
391
+ // of which client is used.
392
+ const client =
393
+ peerPayClient ??
394
+ makePeerPayClient({ wallet: wallet as never, messageBoxUrl: entry.messageBoxUrl, originator: adminOriginator })
395
+ if (!client || !storage) {
396
+ showToast(t('message_box_off_hint'), { type: 'error' })
397
+ return
398
+ }
399
+ setRetryingId(entry.id)
400
+ try {
401
+ await retryDelivery({ wallet: wallet as any, adminOriginator, client, storage, entry })
402
+ setSent({ amount: entry.token.amount })
403
+ } catch (e: any) {
404
+ if (await handleWalletCheck(e)) return
405
+ const reason = isMessageBoxNetworkError(e) ? t('message_box_unreachable') : e?.message || t('unknown_error')
406
+ showToast(`${t('retry_failed')}: ${reason}`, { type: 'error' })
407
+ } finally {
408
+ setRetryingId(null)
409
+ await loadOutbox()
410
+ }
411
+ },
412
+ [peerPayClient, storage, loadOutbox, wallet, adminOriginator, t, handleWalletCheck]
413
+ )
414
+
415
+ const handleCancel = useCallback(
416
+ async (entry: OutboxEntry) => {
417
+ if (!storage || !wallet) return
418
+ const deliveredOrUncertain = entry.delivered === true || entry.delivering === true
419
+ if (deliveredOrUncertain) {
420
+ const key = await showChoiceSheet({
421
+ title: t('cancel_this_payment'),
422
+ options: [
423
+ { key: 'abandon', label: t('abandon_payment'), destructive: true },
424
+ { key: 'finish', label: t('finish_payment') }
425
+ ],
426
+ cancelLabel: t('cancel')
427
+ })
428
+ if (key === 'finish') {
429
+ await handleRetry(entry)
430
+ return
431
+ }
432
+ if (key !== 'abandon') return
433
+ const client = peerPayClient
434
+ if (!client) {
435
+ showToast(t('message_box_off_hint'), { type: 'error' })
436
+ return
437
+ }
438
+ setRetryingId(entry.id)
439
+ try {
440
+ await cancelOutboxPayment({ wallet: wallet as any, adminOriginator, storage, entry, client, mode: 'abandon' })
441
+ } catch (e: any) {
442
+ const reason = isMessageBoxNetworkError(e) ? t('message_box_unreachable') : e?.message || t('unknown_error')
443
+ showToast(reason, { type: 'error' })
444
+ } finally {
445
+ setRetryingId(null)
446
+ await loadOutbox()
447
+ }
448
+ return
449
+ }
450
+ const choice = await showAlert({
451
+ title: t('cancel_this_payment'),
452
+ buttons: [
453
+ { text: t('cancel'), style: 'cancel', key: 'cancel' },
454
+ { text: t('cancel_payment'), style: 'destructive', key: 'cancel_payment' }
455
+ ]
456
+ })
457
+ if (choice !== 'cancel_payment') return
458
+ setRetryingId(entry.id)
459
+ try {
460
+ await cancelOutboxPayment({ wallet: wallet as any, adminOriginator, storage, entry, mode: 'undelivered' })
461
+ } catch (e: any) {
462
+ showToast(e?.message || t('unknown_error'), { type: 'error' })
463
+ } finally {
464
+ setRetryingId(null)
465
+ await loadOutbox()
466
+ }
467
+ },
468
+ [storage, wallet, adminOriginator, peerPayClient, handleRetry, loadOutbox, t]
469
+ )
470
+
471
+ const amountOk = Number(sendAmount) > 0
472
+ const isHandle = target?.kind === 'handle'
473
+ const isAddress = target?.kind === 'address'
474
+ // A stuck handle payment blocks new HANDLE sends: every attempt while the box
475
+ // is unreachable would mint another noSend action and another stuck entry.
476
+ // Address sends never touch the box, so they are not held hostage by it.
477
+ const handleBlockedByOutbox = isHandle && outbox.length > 0
478
+ const handleFormValid = isHandle && amountOk && !isSending && isConfigured
479
+ const canSend = isAddress ? amountOk && !isSending : handleFormValid && !handleBlockedByOutbox
480
+
481
+ return (
482
+ <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
483
+ {notice && <ResultBanner result={notice} onDismiss={() => setNotice(null)} colors={colors} />}
484
+ {recipient.searchError && (
485
+ <ResultBanner
486
+ result={{ type: 'error', message: t('identity_search_unavailable') }}
487
+ onDismiss={recipient.clearSearchError}
488
+ colors={colors}
489
+ />
490
+ )}
491
+
492
+ <PayField labelKey="recipient">
493
+ <RecipientField
494
+ selectedIdentity={recipient.selectedIdentity}
495
+ inputText={recipient.inputText}
496
+ target={recipient.target}
497
+ inlineError={recipient.inlineError}
498
+ isSearching={recipient.isSearching}
499
+ searchResults={recipient.searchResults}
500
+ colors={colors}
501
+ t={t}
502
+ onChangeText={recipient.onChangeText}
503
+ onSelectIdentity={recipient.selectIdentity}
504
+ onClear={recipient.clearRecipient}
505
+ onOpenScanner={recipient.openScanner}
506
+ />
507
+ </PayField>
508
+
509
+ <PayAmountField value={sendAmount} onChangeText={setSendAmount} />
510
+
511
+ {isHandle && (
512
+ <PayField labelKey="note">
513
+ <TextInput
514
+ value={note}
515
+ onChangeText={setNote}
516
+ placeholder={t('note_placeholder')}
517
+ placeholderTextColor={colors.textQuaternary}
518
+ maxLength={280}
519
+ style={[
520
+ styles.noteInput,
521
+ { backgroundColor: colors.backgroundSecondary, borderColor: colors.separator, color: colors.textPrimary }
522
+ ]}
523
+ />
524
+ </PayField>
525
+ )}
526
+
527
+ {/* Load-bearing for an address: this rail cannot notify the payee. Nothing for a handle. */}
528
+ {isAddress && <ConsequenceNote textKey={CONSEQUENCE_KEYS.address} />}
529
+
530
+ {isHandle && !isConfigured && (
531
+ <Text style={[styles.consequence, { color: colors.textSecondary }]}>{t('message_box_off_hint')}</Text>
532
+ )}
533
+ {handleFormValid && handleBlockedByOutbox && (
534
+ <Text style={[styles.consequence, { color: colors.textSecondary }]}>{t('finish_or_cancel_outgoing')}</Text>
535
+ )}
536
+
537
+ <PayCta onPress={handleSend} disabled={!canSend} busy={isSending} />
538
+
539
+ {sendResult && <ResultBanner result={sendResult} onDismiss={() => setSendResult(null)} colors={colors} />}
540
+
541
+ {outbox.length > 0 && (
542
+ <OutgoingSection
543
+ entries={outbox}
544
+ retryingId={retryingId}
545
+ colors={colors}
546
+ t={t}
547
+ onRetry={handleRetry}
548
+ onCancel={handleCancel}
549
+ />
550
+ )}
551
+
552
+ <Modal
553
+ visible={recipient.scannerVisible}
554
+ animationType="slide"
555
+ onRequestClose={() => recipient.setScannerVisible(false)}
556
+ statusBarTranslucent
557
+ >
558
+ <StatusBar style="light" />
559
+ <QRScanner
560
+ multiScan
561
+ onScan={recipient.onScan}
562
+ onClose={() => recipient.setScannerVisible(false)}
563
+ hintText={t('scan_recipient_hint')}
564
+ />
565
+ </Modal>
566
+
567
+ {sent && (
568
+ <PaymentSuccessOverlay
569
+ direction="sent"
570
+ amount={sent.amount}
571
+ recipientName={sent.recipient}
572
+ onDismiss={() => setSent(null)}
573
+ />
574
+ )}
575
+ </ScrollView>
576
+ )
577
+ }
578
+
579
+ const styles = StyleSheet.create({
580
+ content: {
581
+ paddingHorizontal: spacing.lg,
582
+ paddingTop: spacing.lg
583
+ },
584
+
585
+ // Field group
586
+ fieldGroup: {
587
+ marginBottom: spacing.lg
588
+ },
589
+
590
+ // Consequence line + call to action
591
+ consequence: {
592
+ ...typography.footnote,
593
+ marginBottom: spacing.md
594
+ },
595
+ cta: {
596
+ flexDirection: 'row',
597
+ alignItems: 'center',
598
+ justifyContent: 'center',
599
+ gap: spacing.sm,
600
+ paddingVertical: spacing.md + 2,
601
+ borderRadius: radii.md
602
+ },
603
+ ctaText: {
604
+ ...typography.subhead,
605
+ fontWeight: '600'
606
+ },
607
+
608
+ // Outgoing section
609
+ outgoingCard: {
610
+ borderRadius: radii.md,
611
+ borderWidth: StyleSheet.hairlineWidth,
612
+ overflow: 'hidden',
613
+ marginBottom: spacing.lg
614
+ },
615
+ outgoingRow: {
616
+ paddingVertical: spacing.md,
617
+ paddingHorizontal: spacing.lg,
618
+ borderLeftWidth: 3
619
+ },
620
+ outgoingInfo: {
621
+ gap: 6
622
+ },
623
+ outgoingTopRow: {
624
+ flexDirection: 'row',
625
+ alignItems: 'baseline',
626
+ justifyContent: 'space-between',
627
+ gap: spacing.md
628
+ },
629
+ outgoingRecipient: {
630
+ ...typography.footnote,
631
+ fontWeight: '500',
632
+ fontFamily: 'monospace',
633
+ flex: 1
634
+ },
635
+ outgoingAmount: {
636
+ ...typography.subhead,
637
+ fontWeight: '700',
638
+ flexShrink: 0
639
+ },
640
+ outgoingStatusText: {
641
+ ...typography.caption1,
642
+ marginBottom: spacing.sm
643
+ },
644
+ outgoingButtons: {
645
+ flexDirection: 'row',
646
+ borderTopWidth: StyleSheet.hairlineWidth,
647
+ marginHorizontal: -spacing.lg,
648
+ marginBottom: -spacing.md
649
+ },
650
+ outgoingDismissButton: {
651
+ flex: 1,
652
+ minHeight: hitTargets.minimum,
653
+ minWidth: hitTargets.minimum,
654
+ paddingVertical: 13,
655
+ alignItems: 'center',
656
+ justifyContent: 'center',
657
+ borderRightWidth: StyleSheet.hairlineWidth
658
+ },
659
+ outgoingRetryButton: {
660
+ flex: 1,
661
+ minHeight: hitTargets.minimum,
662
+ minWidth: hitTargets.minimum,
663
+ paddingVertical: 13,
664
+ alignItems: 'center',
665
+ justifyContent: 'center'
666
+ },
667
+ outgoingRetryBusy: {
668
+ flexDirection: 'row',
669
+ alignItems: 'center',
670
+ gap: spacing.sm
671
+ },
672
+ outgoingRetryText: {
673
+ ...typography.subhead,
674
+ fontWeight: '600'
675
+ },
676
+ outgoingDismissText: {
677
+ ...typography.subhead
678
+ },
679
+
680
+ noteInput: {
681
+ ...typography.body,
682
+ borderRadius: radii.md,
683
+ borderWidth: StyleSheet.hairlineWidth,
684
+ paddingHorizontal: spacing.md,
685
+ paddingVertical: spacing.md
686
+ }
687
+ })