@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,507 @@
1
+ /**
2
+ * Get paid → a conventional wallet.
3
+ *
4
+ * Show the address, and money appears: the sweep runs in WalletContext, not
5
+ * here, so this view registers today's address on the watchlist and then
6
+ * stays out of the way. The day-offset stepper survives as a recovery
7
+ * affordance only — a previously-issued address whose funds cannot be swept is
8
+ * lost money — which is why it is behind a disclosure rather than on the main
9
+ * view.
10
+ */
11
+ import React, { useCallback, useEffect, useRef, useState } from 'react'
12
+ import { ActivityIndicator, AppState, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native'
13
+ import { useTranslation } from 'react-i18next'
14
+ import { formatDistanceToNow } from 'date-fns'
15
+
16
+ import ReceivedOverlay from './PaymentSuccessOverlay'
17
+ import AmountDisplay from '../wallet/AmountDisplay'
18
+ import { showToast } from '../ui/Toast'
19
+ import {
20
+ useTheme,
21
+ radii,
22
+ spacing,
23
+ typography,
24
+ useWallet,
25
+ MAX_RECOVERY_DAYS,
26
+ derivationPrefixFor,
27
+ getCurrentDate,
28
+ getPaymentAddress,
29
+ getProcessedTransactions,
30
+ sweepAddress,
31
+ wocConfigFor,
32
+ type ProcessedTx,
33
+ watchAddress
34
+ } from '@bsv/expo-wallet-toolbox'
35
+
36
+ /**
37
+ * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
38
+ * etc.), one of which reaches expo-font -> expo-asset -- untransformed ESM
39
+ * that Jest cannot parse when eagerly pulled in via the `ui` package barrel.
40
+ * Ionicons is loaded lazily, only when actually rendering, same pattern as
41
+ * this package's other native-module-boundary fixes (expo-router, expo-blur).
42
+ */
43
+ type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
44
+ let ioniconsComponent: IoniconsComponent | undefined
45
+ function loadIonicons(): IoniconsComponent {
46
+ if (!ioniconsComponent) {
47
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
48
+ ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
49
+ }
50
+ return ioniconsComponent
51
+ }
52
+
53
+ /**
54
+ * expo-router is required lazily rather than imported at module scope: this
55
+ * file is barrel-exported from the package's `ui` entry point, and a static
56
+ * top-level `import` of expo-router pulls in its own untransformed JSX
57
+ * source (Navigator.js etc.), which Jest cannot parse for any consumer of the
58
+ * barrel, even one that never navigates. Same pattern as
59
+ * core/context/WalletContext.tsx's and WalletHomeScreen.tsx's lazy
60
+ * expo-router load. `useFocusEffect` is a hook, but calling it via
61
+ * `loadExpoRouter().useFocusEffect(...)` is equivalent to calling it directly
62
+ * — the module is cached after the first call, so it is the exact same
63
+ * function reference on every render, which is what the rules of hooks
64
+ * actually require (a stable, unconditional call per render).
65
+ */
66
+ type ExpoRouterModule = typeof import('expo-router')
67
+ let expoRouterMod: ExpoRouterModule | undefined
68
+ function loadExpoRouter(): ExpoRouterModule {
69
+ if (!expoRouterMod) {
70
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
71
+ expoRouterMod = require('expo-router') as ExpoRouterModule
72
+ }
73
+ return expoRouterMod
74
+ }
75
+
76
+ /**
77
+ * @react-native-clipboard/clipboard reaches for its native TurboModule at
78
+ * import time (`TurboModuleRegistry.getEnforcing`), which throws under Jest
79
+ * (no native binary registered there) even though the module itself
80
+ * transforms fine. Required lazily, only when a handler actually copies
81
+ * something, so importing the `ui` barrel never touches the native module.
82
+ * Same pattern as WalletHomeScreen.tsx's lazy clipboard load.
83
+ */
84
+ type ClipboardModule = typeof import('@react-native-clipboard/clipboard').default
85
+ let clipboardModule: ClipboardModule | undefined
86
+ function loadClipboard(): ClipboardModule {
87
+ if (!clipboardModule) {
88
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
89
+ clipboardModule = require('@react-native-clipboard/clipboard').default as ClipboardModule
90
+ }
91
+ return clipboardModule
92
+ }
93
+
94
+ /**
95
+ * react-native-qrcode-svg ships an untransformed ESM build that Jest cannot
96
+ * parse when eagerly pulled in via the `ui` package barrel, even for a
97
+ * consumer that never renders one. Loaded lazily, only when actually
98
+ * rendering, same pattern as this package's other native/ESM-boundary fixes.
99
+ * `mod?.default ?? mod` mirrors Babel's default-interop rather than a plain
100
+ * `.default` access, since this repo's test mock for the module
101
+ * (`jest.mock('react-native-qrcode-svg', () => 'QRCode')`) has no
102
+ * `__esModule`/`default` shape.
103
+ */
104
+ type QRCodeComponent = typeof import('react-native-qrcode-svg').default
105
+ let qrCodeComponent: QRCodeComponent | undefined
106
+ function loadQRCode(): QRCodeComponent {
107
+ if (!qrCodeComponent) {
108
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
109
+ const mod = require('react-native-qrcode-svg')
110
+ qrCodeComponent = (mod?.default ?? mod) as QRCodeComponent
111
+ }
112
+ return qrCodeComponent
113
+ }
114
+
115
+ /**
116
+ * How often this screen re-reads its own imported history while it is in front.
117
+ *
118
+ * The sweep itself lives in WalletContext and runs on its own 30s cycle whether
119
+ * or not anyone is looking. This is only the screen noticing — it exists so a
120
+ * payee standing in front of the address gets the arrival moment rather than a
121
+ * silently-updated list.
122
+ */
123
+ const HISTORY_POLL_MS = 5000
124
+
125
+ export default function AddressReceive({ initialSats }: { initialSats?: number } = {}) {
126
+ const { t } = useTranslation()
127
+ const { colors } = useTheme()
128
+ const Ionicons = loadIonicons()
129
+ const QRCode = loadQRCode()
130
+ const { useFocusEffect } = loadExpoRouter()
131
+ const { managers, adminOriginator, selectedNetwork, storage } = useWallet()
132
+ const wallet = managers?.permissionsManager || null
133
+ const woc = wocConfigFor(selectedNetwork)
134
+
135
+ const [daysOffset, setDaysOffset] = useState(0)
136
+ const [address, setAddress] = useState<string | null>(null)
137
+ const [loading, setLoading] = useState(false)
138
+ const [copied, setCopied] = useState(false)
139
+ const [processed, setProcessed] = useState<ProcessedTx[]>([])
140
+ const [showRecovery, setShowRecovery] = useState(false)
141
+ const [sweeping, setSweeping] = useState(false)
142
+
143
+ /** The success moment, held until the payee acknowledges it. */
144
+ const [received, setReceived] = useState<{ amount: number; count: number } | null>(null)
145
+
146
+ /**
147
+ * What this screen had already seen imported, so a poll can tell an arrival
148
+ * from the history it loaded with. Null until the first read establishes the
149
+ * baseline — without that, opening the screen on an address with past imports
150
+ * would celebrate them all over again.
151
+ */
152
+ const baselineRef = useRef<{ total: number; count: number } | null>(null)
153
+ const focusedRef = useRef(true)
154
+ const pollingRef = useRef(false)
155
+ useFocusEffect(
156
+ useCallback(() => {
157
+ focusedRef.current = true
158
+ return () => {
159
+ focusedRef.current = false
160
+ }
161
+ }, [])
162
+ )
163
+
164
+ /** Sum and count of everything imported to the address on screen. */
165
+ const tally = (rows: ProcessedTx[]) => ({
166
+ total: rows.reduce((sum, tx) => sum + tx.satoshis, 0),
167
+ count: rows.length
168
+ })
169
+
170
+ const load = useCallback(
171
+ async (offset: number) => {
172
+ if (!wallet) return
173
+ setLoading(true)
174
+ try {
175
+ const date = getCurrentDate(offset)
176
+ const derivationPrefix = derivationPrefixFor(date)
177
+ const next = await getPaymentAddress(wallet as any, adminOriginator, derivationPrefix, woc.network)
178
+ setDaysOffset(offset)
179
+ setAddress(next)
180
+ // Registering is what makes the background sweeper poll it. Every
181
+ // address the user is shown gets watched — including a recovered one.
182
+ if (storage) await watchAddress(storage as any, { address: next, date, derivationPrefix })
183
+ const rows = await getProcessedTransactions(wallet as any, adminOriginator, next)
184
+ setProcessed(rows)
185
+ // A different address means a different history: re-baseline, or stepping
186
+ // to a recovered day would read its existing imports as new arrivals.
187
+ baselineRef.current = tally(rows)
188
+ } catch (e: any) {
189
+ showToast(e?.message || t('unable_to_generate_address'), { type: 'error' })
190
+ } finally {
191
+ setLoading(false)
192
+ }
193
+ },
194
+ [wallet, adminOriginator, woc.network, storage, t]
195
+ )
196
+
197
+ useEffect(() => {
198
+ if (wallet) void load(0)
199
+ }, [wallet]) // eslint-disable-line react-hooks/exhaustive-deps
200
+
201
+ const handleCopy = useCallback(() => {
202
+ if (!address) return
203
+ loadClipboard().setString(address)
204
+ setCopied(true)
205
+ setTimeout(() => setCopied(false), 2000)
206
+ }, [address])
207
+
208
+ // ── Notice what the background sweep credited ──
209
+ //
210
+ // The sweeper in WalletContext does the work and raises a global toast, which
211
+ // is right when the user is elsewhere in the app. But when they are standing on
212
+ // this screen watching the address, the arrival deserves the same full-screen
213
+ // moment every other way of being paid gets. This only reads the wallet's own
214
+ // imported history — it never sweeps, so it cannot race the sweeper.
215
+ useEffect(() => {
216
+ if (!wallet || !address) return
217
+ let cancelled = false
218
+
219
+ const tick = async () => {
220
+ if (cancelled || !focusedRef.current) return
221
+ if (AppState.currentState !== 'active') return
222
+ if (pollingRef.current) return
223
+ pollingRef.current = true
224
+ try {
225
+ const rows = await getProcessedTransactions(wallet as any, adminOriginator, address)
226
+ if (cancelled) return
227
+ setProcessed(rows)
228
+ const now = tally(rows)
229
+ const before = baselineRef.current
230
+ baselineRef.current = now
231
+ // Compare on total AND count: two imports of equal size in one interval
232
+ // move the count when the delta alone would look like one payment.
233
+ if (before && (now.total > before.total || now.count > before.count)) {
234
+ setReceived({
235
+ amount: Math.max(0, now.total - before.total),
236
+ count: Math.max(1, now.count - before.count)
237
+ })
238
+ }
239
+ } catch {
240
+ // A failed history read is not worth reporting: the next tick retries and
241
+ // the money is already credited either way.
242
+ } finally {
243
+ pollingRef.current = false
244
+ }
245
+ }
246
+
247
+ const interval = setInterval(() => void tick(), HISTORY_POLL_MS)
248
+ const appSubscription = AppState.addEventListener('change', next => {
249
+ if (next === 'active') void tick()
250
+ })
251
+
252
+ return () => {
253
+ cancelled = true
254
+ clearInterval(interval)
255
+ appSubscription.remove()
256
+ }
257
+ }, [wallet, address, adminOriginator])
258
+
259
+ /**
260
+ * Sweep this address now. The background pass covers the common case; this
261
+ * exists for a recovered day, where the user is standing in front of the
262
+ * screen precisely because they want an answer immediately.
263
+ */
264
+ const handleSweepNow = useCallback(async () => {
265
+ if (!wallet || !address) return
266
+ setSweeping(true)
267
+ try {
268
+ const { importedSatoshis } = await sweepAddress({
269
+ wallet: wallet as any,
270
+ adminOriginator,
271
+ woc,
272
+ address,
273
+ derivationPrefix: derivationPrefixFor(getCurrentDate(daysOffset))
274
+ })
275
+ const rows = await getProcessedTransactions(wallet as any, adminOriginator, address)
276
+ setProcessed(rows)
277
+ baselineRef.current = tally(rows)
278
+ if (importedSatoshis > 0) {
279
+ // The arrival gets the full-screen moment, same as every other way of
280
+ // being paid. Nothing found is not an event — a toast is right for that.
281
+ setReceived({ amount: importedSatoshis, count: 1 })
282
+ } else {
283
+ showToast(t('no_pending_payments'), { type: 'info' })
284
+ }
285
+ } catch (e: any) {
286
+ showToast(e?.message || t('unknown_error'), { type: 'error' })
287
+ } finally {
288
+ setSweeping(false)
289
+ }
290
+ }, [wallet, address, adminOriginator, woc, daysOffset, t])
291
+
292
+ return (
293
+ <ScrollView contentContainerStyle={styles.content}>
294
+ {loading && !address ? (
295
+ <View style={styles.centered}>
296
+ <ActivityIndicator size="large" color={colors.accent} />
297
+ <Text style={[styles.support, { color: colors.textSecondary }]}>{t('generating_address')}</Text>
298
+ </View>
299
+ ) : !address ? (
300
+ <View style={styles.centered}>
301
+ <Text style={[styles.support, { color: colors.textSecondary }]}>{t('unable_to_generate_address')}</Text>
302
+ </View>
303
+ ) : (
304
+ <>
305
+ {/* The figure the code asks for, as its price. Only when one was named. */}
306
+ {initialSats !== undefined && initialSats > 0 && (
307
+ <Text style={[styles.requestedAmount, { color: colors.textPrimary }]}>
308
+ <AmountDisplay>{initialSats}</AmountDisplay>
309
+ </Text>
310
+ )}
311
+ <View style={styles.qrHero}>
312
+ <View style={styles.qrPlate}>
313
+ <QRCode value={address} size={240} color="#000" backgroundColor="#fff" />
314
+ </View>
315
+ </View>
316
+
317
+ <TouchableOpacity onPress={handleCopy} style={[styles.addressChip, { backgroundColor: colors.fillTertiary }]}>
318
+ <Text
319
+ style={[styles.addressText, { color: colors.textSecondary }]}
320
+ numberOfLines={1}
321
+ ellipsizeMode="middle"
322
+ >
323
+ {address}
324
+ </Text>
325
+ <View style={[styles.copyPill, { backgroundColor: copied ? colors.success + '20' : colors.fill }]}>
326
+ <Ionicons
327
+ name={copied ? 'checkmark' : 'copy-outline'}
328
+ size={16}
329
+ color={copied ? colors.success : colors.textSecondary}
330
+ />
331
+ <Text style={[styles.copyText, { color: copied ? colors.success : colors.textSecondary }]}>
332
+ {copied ? t('copied') : t('pay_copy')}
333
+ </Text>
334
+ </View>
335
+ </TouchableOpacity>
336
+
337
+ {/* No Check balance, no Import funds: the sweep is automatic now. */}
338
+ <Text style={[styles.watching, { color: colors.textTertiary }]}>{t('pay_address_watching')}</Text>
339
+
340
+ {processed.length > 0 && (
341
+ <>
342
+ <View style={[styles.totalRow, { borderTopColor: colors.separator }]}>
343
+ <Text style={[styles.totalLabel, { color: colors.textSecondary }]}>{t('imported')}</Text>
344
+ <Text style={[styles.totalValue, { color: colors.success }]}>
345
+ <AmountDisplay>{processed.reduce((sum, tx) => sum + tx.satoshis, 0)}</AmountDisplay>
346
+ </Text>
347
+ </View>
348
+ <View style={[styles.log, { borderColor: colors.separator }]}>
349
+ {processed.map((tx, i) => (
350
+ <View
351
+ key={tx.txid}
352
+ style={[
353
+ styles.logRow,
354
+ i < processed.length - 1 && {
355
+ borderBottomWidth: StyleSheet.hairlineWidth,
356
+ borderBottomColor: colors.separator
357
+ }
358
+ ]}
359
+ >
360
+ <Ionicons name="checkmark-circle" size={14} color={colors.success} />
361
+ <Text style={[styles.logSats, { color: colors.success }]}>
362
+ +<AmountDisplay>{tx.satoshis}</AmountDisplay>
363
+ </Text>
364
+ {tx.importedAt ? (
365
+ <Text style={[styles.logTime, { color: colors.textTertiary }]}>
366
+ {formatDistanceToNow(tx.importedAt, { addSuffix: true })}
367
+ </Text>
368
+ ) : (
369
+ <Text
370
+ style={[styles.logTxid, { color: colors.textTertiary }]}
371
+ numberOfLines={1}
372
+ ellipsizeMode="middle"
373
+ >
374
+ {tx.txid}
375
+ </Text>
376
+ )}
377
+ </View>
378
+ ))}
379
+ </View>
380
+ </>
381
+ )}
382
+
383
+ {/* ── Recovery. Secondary by design: reaching an earlier day is the
384
+ uncommon case of a payer who sat on an address. It must exist —
385
+ unswept funds on an unreachable address are lost — but it is not
386
+ a primary control. */}
387
+ <TouchableOpacity onPress={() => setShowRecovery(v => !v)} style={styles.disclosure} hitSlop={8}>
388
+ <Ionicons name={showRecovery ? 'chevron-down' : 'chevron-forward'} size={16} color={colors.textTertiary} />
389
+ <Text style={[styles.disclosureText, { color: colors.textTertiary }]}>{t('pay_address_earlier_day')}</Text>
390
+ </TouchableOpacity>
391
+
392
+ {showRecovery && (
393
+ <View style={styles.recovery}>
394
+ <View style={styles.dateRow}>
395
+ <TouchableOpacity
396
+ onPress={() => void load(Math.min(MAX_RECOVERY_DAYS, daysOffset + 1))}
397
+ disabled={daysOffset >= MAX_RECOVERY_DAYS}
398
+ hitSlop={8}
399
+ style={styles.dateArrow}
400
+ >
401
+ <Ionicons
402
+ name="chevron-back"
403
+ size={20}
404
+ color={daysOffset >= MAX_RECOVERY_DAYS ? colors.textQuaternary : colors.accent}
405
+ />
406
+ </TouchableOpacity>
407
+ <Text style={[styles.dateText, { color: colors.textSecondary }]}>{getCurrentDate(daysOffset)}</Text>
408
+ <TouchableOpacity
409
+ onPress={() => void load(Math.max(0, daysOffset - 1))}
410
+ disabled={daysOffset === 0}
411
+ hitSlop={8}
412
+ style={styles.dateArrow}
413
+ >
414
+ <Ionicons
415
+ name="chevron-forward"
416
+ size={20}
417
+ color={daysOffset === 0 ? colors.textQuaternary : colors.accent}
418
+ />
419
+ </TouchableOpacity>
420
+ </View>
421
+ <TouchableOpacity
422
+ onPress={handleSweepNow}
423
+ disabled={sweeping}
424
+ style={[styles.sweepButton, { borderColor: colors.separator }]}
425
+ >
426
+ {sweeping ? (
427
+ <ActivityIndicator size="small" color={colors.accent} />
428
+ ) : (
429
+ <Text style={[styles.sweepText, { color: colors.accent }]}>{t('pay_address_sweep_now')}</Text>
430
+ )}
431
+ </TouchableOpacity>
432
+ </View>
433
+ )}
434
+ </>
435
+ )}
436
+ {/* The moment money arrives. A Modal, so it covers the header too, and it
437
+ stays until acknowledged. */}
438
+ {received && (
439
+ <ReceivedOverlay amount={received.amount} count={received.count} onDismiss={() => setReceived(null)} />
440
+ )}
441
+ </ScrollView>
442
+ )
443
+ }
444
+
445
+ const styles = StyleSheet.create({
446
+ content: { paddingHorizontal: spacing.lg, paddingTop: spacing.lg },
447
+ centered: { alignItems: 'center', justifyContent: 'center', paddingVertical: spacing.xxxl, gap: spacing.md },
448
+ support: { ...typography.subhead, textAlign: 'center' },
449
+ requestedAmount: { ...typography.title2, textAlign: 'center', marginBottom: spacing.lg },
450
+ qrHero: { alignItems: 'center', marginBottom: spacing.lg },
451
+ qrPlate: { padding: spacing.lg, borderRadius: radii.xl, backgroundColor: '#fff' },
452
+ addressChip: { borderRadius: radii.lg, paddingHorizontal: spacing.md, paddingVertical: spacing.sm, gap: spacing.sm },
453
+ addressText: { ...typography.footnote, fontFamily: 'monospace', textAlign: 'center' },
454
+ copyPill: {
455
+ flexDirection: 'row',
456
+ alignItems: 'center',
457
+ justifyContent: 'center',
458
+ gap: spacing.xs,
459
+ borderRadius: radii.pill,
460
+ paddingVertical: spacing.sm,
461
+ paddingHorizontal: spacing.lg
462
+ },
463
+ copyText: { ...typography.subhead, fontWeight: '500' },
464
+ watching: { ...typography.footnote, textAlign: 'center', marginTop: spacing.md },
465
+ totalRow: {
466
+ flexDirection: 'row',
467
+ justifyContent: 'space-between',
468
+ borderTopWidth: StyleSheet.hairlineWidth,
469
+ paddingTop: spacing.lg,
470
+ marginTop: spacing.lg,
471
+ marginBottom: spacing.md
472
+ },
473
+ totalLabel: { ...typography.subhead },
474
+ totalValue: { ...typography.headline, fontWeight: '700' },
475
+ log: { borderWidth: StyleSheet.hairlineWidth, borderRadius: radii.md, overflow: 'hidden' },
476
+ logRow: {
477
+ flexDirection: 'row',
478
+ alignItems: 'center',
479
+ gap: spacing.sm,
480
+ paddingVertical: spacing.sm,
481
+ paddingHorizontal: spacing.md
482
+ },
483
+ logSats: { ...typography.subhead, fontWeight: '600' },
484
+ logTxid: { ...typography.caption1, fontFamily: 'monospace', flex: 1 },
485
+ logTime: { ...typography.caption1, fontFamily: 'monospace' },
486
+ disclosure: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs, marginTop: spacing.xl },
487
+ disclosureText: { ...typography.footnote },
488
+ recovery: { marginTop: spacing.md, gap: spacing.md },
489
+ dateRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: spacing.md },
490
+ dateArrow: { width: 32, height: 32, alignItems: 'center', justifyContent: 'center' },
491
+ dateText: {
492
+ ...typography.footnote,
493
+ fontFamily: 'monospace',
494
+ fontWeight: '500',
495
+ minWidth: 100,
496
+ textAlign: 'center',
497
+ letterSpacing: 0.3
498
+ },
499
+ sweepButton: {
500
+ alignItems: 'center',
501
+ justifyContent: 'center',
502
+ paddingVertical: spacing.sm + 2,
503
+ borderRadius: radii.md,
504
+ borderWidth: StyleSheet.hairlineWidth
505
+ },
506
+ sweepText: { ...typography.subhead, fontWeight: '500' }
507
+ })
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The "what can I actually send?" line under the amount input.
3
+ *
4
+ * One footnote: the spendable figure, then "available". By default, the figure
5
+ * is in the unit the input above it is taking (satoshis or EUR) with no symbol
6
+ * or unit word, because the input's own suffix already names it. Renders nothing
7
+ * until a figure exists rather than flashing "0", and nothing in fiat mode until
8
+ * a rate exists rather than inventing one.
9
+ *
10
+ * When `withUnit` is true, render as a unit-labelled figure via AmountDisplay
11
+ * instead — used standalone under a unit-labelled headline (e.g. a confirm
12
+ * screen showing "$12.34" above) where no input suffix names the unit.
13
+ */
14
+ import React, { useContext } from 'react'
15
+ import { StyleSheet, Text } from 'react-native'
16
+ import { useTranslation } from 'react-i18next'
17
+ import { useSpendableBalance } from '../../hooks/useSpendableBalance'
18
+ import {
19
+ ExchangeRateContext,
20
+ formatAmountInInputUnit,
21
+ spacing,
22
+ typography,
23
+ useTheme,
24
+ useWallet
25
+ } from '@bsv/expo-wallet-toolbox'
26
+ import AmountDisplay from '../wallet/AmountDisplay'
27
+
28
+ export default function AvailableBalance({ withUnit = false }: { withUnit?: boolean }) {
29
+ const { t } = useTranslation()
30
+ const { colors } = useTheme()
31
+ const { settings } = useWallet()
32
+ const { satoshisPerUSD, usdToFiat = {} } = useContext(ExchangeRateContext)
33
+ const balance = useSpendableBalance()
34
+
35
+ if (balance == null) return null
36
+
37
+ if (withUnit) {
38
+ return (
39
+ <Text style={[styles.text, { color: colors.textSecondary }]} accessibilityRole="text">
40
+ <Text style={[styles.figure, { color: colors.textPrimary }]}>
41
+ <AmountDisplay>{balance}</AmountDisplay>
42
+ </Text>{' '}
43
+ {t('available')}
44
+ </Text>
45
+ )
46
+ }
47
+
48
+ const figure = formatAmountInInputUnit(balance, settings?.currency || 'BSV', satoshisPerUSD, usdToFiat)
49
+ if (!figure) return null
50
+
51
+ return (
52
+ <Text style={[styles.text, { color: colors.textSecondary }]} accessibilityRole="text">
53
+ <Text style={[styles.figure, { color: colors.textPrimary }]}>{figure}</Text> {t('available')}
54
+ </Text>
55
+ )
56
+ }
57
+
58
+ const styles = StyleSheet.create({
59
+ text: { ...typography.footnote, marginTop: spacing.sm },
60
+ figure: { ...typography.footnote, fontWeight: '600', fontVariant: ['tabular-nums'] }
61
+ })