@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,1597 @@
1
+ /**
2
+ * The Wallet screen — full screen, not a drawer.
3
+ *
4
+ * Structure, top to bottom:
5
+ * balance → Pay / Get paid / Vault → activity, grouped by day
6
+ *
7
+ * This replaces a bottom-sheet settings menu plus a separate Transactions
8
+ * route. Activity now sits on the screen the user already opens to check their
9
+ * money, so "did that payment go through?" costs one tap instead of two.
10
+ *
11
+ * Colour discipline: `colors.accent` is achromatic (black/white) in this token
12
+ * set, so it only reads as emphasis when used as a FILL. Exactly one element
13
+ * here is accent-filled — Pay — and chroma elsewhere is reserved for
14
+ * transaction status, never for decoration.
15
+ *
16
+ * Surfaces come from the `canvas*`/`surface*` tokens rather than the iOS grays:
17
+ * the screen is a shallow gradient with cards lifted off it, which is what makes
18
+ * the balance read as the focal point in both appearances.
19
+ */
20
+ import React, { useState, useEffect, useCallback, useRef, useMemo, useContext } from 'react'
21
+ import {
22
+ View,
23
+ Text,
24
+ FlatList,
25
+ StyleSheet,
26
+ TouchableOpacity,
27
+ ActivityIndicator,
28
+ Linking,
29
+ type ListRenderItem
30
+ } from 'react-native'
31
+ import { useSafeAreaInsets } from 'react-native-safe-area-context'
32
+ import { useTranslation } from 'react-i18next'
33
+ import AsyncStorage from '@react-native-async-storage/async-storage'
34
+ import { Utils } from '@bsv/sdk'
35
+ import { sdk } from '@bsv/wallet-toolbox-mobile'
36
+ import { PeerPayClient } from '@bsv/message-box-client'
37
+ import {
38
+ useTheme,
39
+ spacing,
40
+ radii,
41
+ typography,
42
+ useWallet,
43
+ ExchangeRateContext,
44
+ formatAmountParts,
45
+ formatAmount,
46
+ formatSatoshisAsBsvDecimal,
47
+ findOfflineActions,
48
+ type OfflineActionRow,
49
+ TaskSendOffline,
50
+ TaskCreditInbox,
51
+ readWalletBalance,
52
+ useLocalStorage,
53
+ handleResendRequests,
54
+ listPendingResendRequests,
55
+ loadUnansweredResends,
56
+ resendPaymentDetails,
57
+ makeListPeerPayAction,
58
+ makeBeefRepair,
59
+ makeResendBeef,
60
+ wocConfigFor,
61
+ getOnline,
62
+ haptics,
63
+ DEFAULT_MESSAGE_BOX_URL,
64
+ MESSAGE_BOX_URL_KEY,
65
+ NO_MESSAGE_BOX,
66
+ LEGACY_MESSAGE_BOX_URL,
67
+ getOutboxEntries,
68
+ unsentEntries,
69
+ retryDelivery,
70
+ makePeerPayClient,
71
+ isMessageBoxNetworkError,
72
+ generateMnemonicWallet,
73
+ backupAttestation,
74
+ type PendingResend
75
+ } from '@bsv/expo-wallet-toolbox'
76
+ import ActivityRow, { type ActivityAction } from '../components/wallet/ActivityRow'
77
+ import { BackupReminderSheet } from '../components/wallet/BackupReminderSheet'
78
+ import { BiometricAdvisoryModal } from '../components/wallet/BiometricAdvisoryModal'
79
+ import { ImportFromBackupPrompt } from '../components/wallet/ImportFromBackupPrompt'
80
+ import { cancelParkedPayment, type CancelParkedWallet } from '../../core/offline/cancelParked'
81
+ import { releaseParkedPayment } from '../../core/offline/payerHold'
82
+ import { partitionQueueByGrace } from '../../core/offline/queueGrace'
83
+ import { storageMatchesNetwork } from '../../core/net/chainMatch'
84
+ import { makeMetadataDecryptor } from '../../core/peerpay/metadataDecryptor'
85
+ import { getPendingCorruptNotice, readUnprocessedPending } from '../../core/localpay/pending'
86
+ import { homeBadges } from './homeBadges'
87
+ import { exportTransactionsAsCsv } from '../exportTransactions'
88
+ import PressableScale from '../components/ui/PressableScale'
89
+ import ScreenGradient from '../components/ui/ScreenGradient'
90
+ import ScrollFade, { sampleScreenGradient } from '../components/ui/ScrollFade'
91
+ import { showToast } from '../components/ui/Toast'
92
+ import { ListRow } from '../components/ui/ListRow'
93
+ import { GroupedSection } from '../components/ui/GroupedList'
94
+ import WalletLockNotice from '../components/security/WalletLockNotice'
95
+ import OfflineNotice from '../components/pay/OfflineNotice'
96
+ import { useOnline } from '../hooks/useOnline'
97
+ import { useOfflineNoticeActions } from '../hooks/useOfflineNoticeActions'
98
+
99
+ async function readMessageBoxUrl(): Promise<string | undefined> {
100
+ const saved = await AsyncStorage.getItem(MESSAGE_BOX_URL_KEY)
101
+ if (saved === NO_MESSAGE_BOX) return undefined
102
+ if (!saved || saved === LEGACY_MESSAGE_BOX_URL) return DEFAULT_MESSAGE_BOX_URL
103
+ return saved
104
+ }
105
+
106
+ /**
107
+ * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
108
+ * etc.), one of which reaches expo-font -> expo-asset -- untransformed ESM
109
+ * that Jest cannot parse when eagerly pulled in via the `ui` package barrel.
110
+ * Both icon sets are loaded lazily, only when actually rendering, same
111
+ * pattern as this package's other native-module-boundary fixes (expo-router,
112
+ * expo-blur).
113
+ */
114
+ type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
115
+ type MaterialCommunityIconsComponent = typeof import('@expo/vector-icons').MaterialCommunityIcons
116
+ let ioniconsComponent: IoniconsComponent | undefined
117
+ let materialCommunityIconsComponent: MaterialCommunityIconsComponent | undefined
118
+ function loadIonicons(): IoniconsComponent {
119
+ if (!ioniconsComponent) {
120
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
121
+ ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
122
+ }
123
+ return ioniconsComponent
124
+ }
125
+ function loadMaterialCommunityIcons(): MaterialCommunityIconsComponent {
126
+ if (!materialCommunityIconsComponent) {
127
+ materialCommunityIconsComponent = // eslint-disable-next-line @typescript-eslint/no-require-imports
128
+ require('@expo/vector-icons').MaterialCommunityIcons as MaterialCommunityIconsComponent
129
+ }
130
+ return materialCommunityIconsComponent
131
+ }
132
+
133
+ /**
134
+ * expo-router is required lazily rather than imported at module scope: this
135
+ * file is barrel-exported from the package's `ui` entry point, and a static
136
+ * top-level `import` of expo-router pulls in its own untransformed JSX
137
+ * source (Navigator.js etc.), which Jest cannot parse for any consumer of the
138
+ * barrel, even one that never navigates. Same pattern as
139
+ * core/context/WalletContext.tsx's and components/security/WalletLockNotice.tsx's
140
+ * lazy expo-router load. `useFocusEffect` is a hook, but calling it via
141
+ * `loadExpoRouter().useFocusEffect(...)` is equivalent to calling it directly
142
+ * — the module is cached after the first call, so it is the exact same
143
+ * function reference on every render, which is what the rules of hooks
144
+ * actually require (a stable, unconditional call per render), not the manner
145
+ * in which the reference to that function was obtained.
146
+ */
147
+ type ExpoRouterModule = typeof import('expo-router')
148
+ let expoRouterMod: ExpoRouterModule | undefined
149
+ function loadExpoRouter(): ExpoRouterModule {
150
+ if (!expoRouterMod) {
151
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
152
+ expoRouterMod = require('expo-router') as ExpoRouterModule
153
+ }
154
+ return expoRouterMod
155
+ }
156
+
157
+ /**
158
+ * @react-native-clipboard/clipboard reaches for its native TurboModule at
159
+ * import time (`TurboModuleRegistry.getEnforcing`), which throws under Jest
160
+ * (no native binary registered there) even though the module itself
161
+ * transforms fine. Required lazily, only when a handler actually copies
162
+ * something, so importing the `ui` barrel never touches the native module.
163
+ */
164
+ type ClipboardModule = typeof import('@react-native-clipboard/clipboard').default
165
+ let clipboardModule: ClipboardModule | undefined
166
+ function loadClipboard(): ClipboardModule {
167
+ if (!clipboardModule) {
168
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
169
+ clipboardModule = require('@react-native-clipboard/clipboard').default as ClipboardModule
170
+ }
171
+ return clipboardModule
172
+ }
173
+
174
+ const PAGE_SIZE = 30
175
+
176
+ /** A day heading injected between rows. Kept in the same list as the rows so
177
+ * the whole thing stays one FlatList — a SectionList would re-measure every
178
+ * section on each status poll. */
179
+ type DayHeader = { kind: 'day'; id: string; label: string }
180
+ type Row = DayHeader | (ActivityAction & { kind?: undefined })
181
+
182
+ const DAY_MS = 86_400_000
183
+ const startOfDay = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()
184
+
185
+ /** Group rows under Today / Yesterday / an absolute date. Rows with no
186
+ * timestamp fall through ungrouped rather than being dated wrongly. */
187
+ function withDayHeaders(actions: ActivityAction[], t: (k: string) => string): Row[] {
188
+ const today = startOfDay(new Date())
189
+ const out: Row[] = []
190
+ let currentDay: number | null = null
191
+ for (const action of actions) {
192
+ const raw = action.created_at
193
+ const ts = raw === undefined || raw === null ? NaN : new Date(raw as string).getTime()
194
+ if (!Number.isNaN(ts)) {
195
+ const day = startOfDay(new Date(ts))
196
+ if (day !== currentDay) {
197
+ currentDay = day
198
+ const label =
199
+ day === today
200
+ ? t('wallet_group_today')
201
+ : day === today - DAY_MS
202
+ ? t('wallet_group_yesterday')
203
+ : new Date(day).toLocaleDateString(undefined, {
204
+ day: 'numeric',
205
+ month: 'short',
206
+ year: day < today - 300 * DAY_MS ? 'numeric' : undefined
207
+ })
208
+ out.push({ kind: 'day', id: `day-${day}`, label })
209
+ }
210
+ }
211
+ out.push(action)
212
+ }
213
+ return out
214
+ }
215
+
216
+ export interface WalletHomeScreenProps {
217
+ /**
218
+ * Rendered in the top-left of the header — e.g. a back button for host apps
219
+ * that present the wallet as a screen within a larger flow (BSV Browser).
220
+ * No default: most hosts (BSV Wallet included) have nothing to return to.
221
+ */
222
+ topLeft?: React.ReactNode
223
+ }
224
+
225
+ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
226
+ const { t } = useTranslation()
227
+ const { colors } = useTheme()
228
+ const insets = useSafeAreaInsets()
229
+ const { router, useFocusEffect } = loadExpoRouter()
230
+ const Ionicons = loadIonicons()
231
+ const MaterialCommunityIcons = loadMaterialCommunityIcons()
232
+ const {
233
+ managers,
234
+ adminOriginator,
235
+ selectedNetwork,
236
+ storage,
237
+ txStatusVersion,
238
+ walletUserId,
239
+ refreshProof,
240
+ settings,
241
+ walletBuilt,
242
+ buildWalletFromMnemonic
243
+ } = useWallet()
244
+ const { setMnemonic: storeMnemonic, hasStoredIdentity } = useLocalStorage()
245
+ const { satoshisPerUSD, usdToFiat = {} } = useContext(ExchangeRateContext)
246
+ const currency = settings?.currency || 'BSV'
247
+ const online = useOnline()
248
+
249
+ // ── lazy wallet creation ────────────────────────────────────────────
250
+ /**
251
+ * Apple HIG: never ask for Face ID/Touch ID before the user has done
252
+ * something that explains why. Creating a wallet needs biometric-gated
253
+ * storage (setMnemonic below), so building one eagerly on first mount —
254
+ * as this screen used to — put a biometric prompt in front of a user who
255
+ * had not yet tapped anything. Instead, wallet creation is deferred until
256
+ * the first Pay or Get Paid tap (see destinationPress below), behind a
257
+ * one-time advisory modal that explains the prompt before it fires.
258
+ *
259
+ * A fresh install has no mnemonic and no recovered key, so until that
260
+ * first tap this screen simply renders with no wallet: zero balance, no
261
+ * activity, Pay/Get Paid still visible. WalletLockNotice covers a
262
+ * RETURNING user whose key the OS destroyed or who cancelled the
263
+ * biometric prompt ('lost' / 'cancelled' / 'unavailable'); a true fresh
264
+ * install never reaches those states, so nothing else needs to render
265
+ * here in the meantime.
266
+ */
267
+ const creatingWalletRef = useRef(false)
268
+ const ensureWalletExists = useCallback(async (): Promise<boolean> => {
269
+ if (managers.permissionsManager) return true
270
+ if (creatingWalletRef.current) return false
271
+ creatingWalletRef.current = true
272
+ try {
273
+ const wallet = generateMnemonicWallet()
274
+ const stored = await storeMnemonic(wallet.mnemonic)
275
+ if (!stored) {
276
+ // Biometric access was needed and unavailable/declined — same dead
277
+ // end onboarding's own generate flow hits. Send the user there to
278
+ // retry explicitly rather than silently failing the tap.
279
+ router.replace('/auth/mnemonic')
280
+ return false
281
+ }
282
+ await buildWalletFromMnemonic(wallet.mnemonic)
283
+ return true
284
+ } finally {
285
+ creatingWalletRef.current = false
286
+ }
287
+ }, [managers.permissionsManager, storeMnemonic, buildWalletFromMnemonic, router])
288
+
289
+ const [pendingDestination, setPendingDestination] = useState<string | null>(null)
290
+ const [showBiometricAdvisory, setShowBiometricAdvisory] = useState(false)
291
+ const [creatingWalletFromAdvisory, setCreatingWalletFromAdvisory] = useState(false)
292
+
293
+ const destinationPress = useCallback(
294
+ (destination: string) => {
295
+ if (managers.permissionsManager) {
296
+ router.push(destination as Parameters<typeof router.push>[0])
297
+ return
298
+ }
299
+ setPendingDestination(destination)
300
+ setShowBiometricAdvisory(true)
301
+ },
302
+ [managers.permissionsManager, router]
303
+ )
304
+
305
+ // ── backup reminder ─────────────────────────────────────────────────
306
+ /**
307
+ * Once a wallet exists, ask whether this identity has ever attested a
308
+ * backup. Re-checked on every focus of this screen (not just mount) so
309
+ * dismissing the card never sticks for the session — it reappears the
310
+ * moment the user lands back on the main page, until they actually back
311
+ * up or import. Same advisory attestation the vault gate reads.
312
+ */
313
+ const [showBackupReminder, setShowBackupReminder] = useState(false)
314
+ useFocusEffect(
315
+ useCallback(() => {
316
+ if (!walletBuilt) return
317
+ const wallet = managers.permissionsManager
318
+ if (!wallet) return
319
+ let cancelled = false
320
+ ;(async () => {
321
+ try {
322
+ const { publicKey } = await wallet.getPublicKey({ identityKey: true }, adminOriginator)
323
+ const attested = await backupAttestation.get(publicKey)
324
+ if (!cancelled) setShowBackupReminder(attested === null)
325
+ } catch {
326
+ // Advisory only — if the check fails, err toward reminding rather
327
+ // than silently skipping it.
328
+ if (!cancelled) setShowBackupReminder(true)
329
+ }
330
+ })()
331
+ return () => {
332
+ cancelled = true
333
+ }
334
+ }, [walletBuilt, managers.permissionsManager, adminOriginator])
335
+ )
336
+
337
+ const balanceCacheKey = `cached_wallet_balance_${selectedNetwork}`
338
+ /**
339
+ * Whether what is mounted is this network's wallet.
340
+ *
341
+ * A switch tears the wallet down and rebuilds it; until that finishes there
342
+ * is either no storage or the old chain's. Reading either one is how a
343
+ * testnet wallet came to show a mainnet balance and a mainnet activity list.
344
+ */
345
+ const onThisNetwork = storageMatchesNetwork(storage, selectedNetwork)
346
+ const [balance, setBalance] = useState<number | null>(null)
347
+ const [actions, setActions] = useState<ActivityAction[]>([])
348
+ const [loading, setLoading] = useState(true)
349
+ const [loadError, setLoadError] = useState(false)
350
+ const [loadingMore, setLoadingMore] = useState(false)
351
+ const [refreshing, setRefreshing] = useState(false)
352
+ const [exporting, setExporting] = useState(false)
353
+ const [offlineByTxid, setOfflineByTxid] = useState<Map<string, OfflineActionRow>>(new Map())
354
+ /** What the row's spinner is currently waiting on. */
355
+ const [busyLabel, setBusyLabel] = useState<string | undefined>(undefined)
356
+ /** Bumped when a queued payment outlives its grace, so the banner can appear. */
357
+ const [graceNonce, setGraceNonce] = useState(0)
358
+ const [attentionCount, setAttentionCount] = useState(0)
359
+ const [unsentCount, setUnsentCount] = useState(0)
360
+ const [stalled, setStalled] = useState<string | undefined>(undefined)
361
+ const [pendingCount, setPendingCount] = useState(0)
362
+ const [pendingStuck, setPendingStuck] = useState(0)
363
+ /** Where the pinned block ends, so the fade below it can be painted in the
364
+ * backdrop's colour at exactly that point rather than a guess. */
365
+ const [pinnedHeight, setPinnedHeight] = useState(0)
366
+ const [pendingCorrupt, setPendingCorrupt] = useState(false)
367
+ // Per-row in-flight action, keyed by txid (or reference for abort) so only
368
+ // the tapped row shows a spinner rather than the whole list.
369
+ const [busyRow, setBusyRow] = useState<string | null>(null)
370
+ /** The one row whose utility chips are open. One at a time: two open rows and
371
+ * the chips stop obviously belonging to a transaction. */
372
+ const [expandedRow, setExpandedRow] = useState<string | null>(null)
373
+ const [pendingResends, setPendingResends] = useState<PendingResend[]>([])
374
+ const [resending, setResending] = useState(false)
375
+ const offsetRef = useRef(0)
376
+ /** Set once the server has no more rows, so onEndReached stops re-querying at
377
+ * the bottom of the list. Cleared whenever the list is refetched from 0. */
378
+ const exhaustedRef = useRef(false)
379
+ /** Synchronous in-flight latch for loadMore (state updates are async). */
380
+ const inFlightRef = useRef(false)
381
+
382
+ /**
383
+ * Whether a wallet is already stored on this device, checked prompt-free
384
+ * (no biometric, no wallet build) so it settles well before the wallet
385
+ * itself finishes building. That build gap is briefly indistinguishable
386
+ * from "no wallet at all" — both show no permissions manager — and two
387
+ * things key off telling them apart: ImportFromBackupPrompt below (must
388
+ * not flash "import" over an existing user's already-populated screen)
389
+ * and refreshBalance (must not blank a freshly-painted cached figure while
390
+ * an existing wallet is still mid-build). Defaults to false (assume a
391
+ * wallet exists) until the check resolves, so it can only suppress an
392
+ * incorrect flash, never cause one.
393
+ */
394
+ const [knownNoStoredIdentity, setKnownNoStoredIdentity] = useState(false)
395
+ useEffect(() => {
396
+ let cancelled = false
397
+ ;(async () => {
398
+ try {
399
+ const exists = await hasStoredIdentity()
400
+ if (!cancelled) setKnownNoStoredIdentity(!exists)
401
+ } catch {
402
+ // Unknown: err toward not showing the import prompt.
403
+ }
404
+ })()
405
+ return () => {
406
+ cancelled = true
407
+ }
408
+ }, [hasStoredIdentity])
409
+
410
+ // ── balance ─────────────────────────────────────────────────────────
411
+ /**
412
+ * One balance read at a time, shared by every caller.
413
+ *
414
+ * Mount, invalidation and pull-to-refresh all funnel through this latch, so a
415
+ * caller arriving mid-read awaits that read instead of starting another.
416
+ */
417
+ const inFlightBalanceRef = useRef<Promise<void> | null>(null)
418
+ const refreshBalance = useCallback(async () => {
419
+ if (inFlightBalanceRef.current) return await inFlightBalanceRef.current
420
+ const read = (async () => {
421
+ try {
422
+ // Straight to our own SQLite, deliberately NOT through the wallet's
423
+ // listOutputs: every call through WalletStorageManager queues on one
424
+ // FIFO reader lock, and the monitor holds that lock across network
425
+ // broadcasts — so this read used to wait on whatever the monitor was
426
+ // doing rather than on the database. See storage/methods/walletBalanceSql.
427
+ // The wallet's own path stays as the fallback for the window before
428
+ // storage and the user id are known.
429
+ // Mid-switch the previous chain's storage is still mounted, and its
430
+ // figure is not this network's money. Only bails when storage is
431
+ // mounted for the WRONG chain — storageMatchesNetwork returns false
432
+ // for a null storage too (no `.chain` to compare), which is also the
433
+ // no-wallet-at-all case, and that one must fall through to the
434
+ // zero-settle below rather than being swallowed here.
435
+ if (storage && !onThisNetwork) return
436
+ let total: number | null = null
437
+ if (storage && walletUserId != null) {
438
+ total = await readWalletBalance(storage, walletUserId)
439
+ }
440
+ if (total == null) {
441
+ const pm = managers.permissionsManager
442
+ if (!pm) {
443
+ // Genuinely no wallet on this device (freshly logged out /
444
+ // deleted) rather than an existing wallet still mid-build: settle
445
+ // on zero so the spinner does not spin forever. Gated on the
446
+ // confirmed, prompt-free identity check rather than merely "no
447
+ // permissions manager yet" — that condition is also true for a
448
+ // split second at every cold start, and would otherwise blank
449
+ // the cached figure this same mount just painted.
450
+ if (knownNoStoredIdentity) setBalance(0)
451
+ return
452
+ }
453
+ const { totalOutputs } = await pm.listOutputs({ basket: sdk.specOpWalletBalance }, adminOriginator)
454
+ total = totalOutputs ?? 0
455
+ }
456
+ setBalance(total)
457
+ await AsyncStorage.setItem(balanceCacheKey, String(total))
458
+ } catch {
459
+ // Keep the last known balance on screen rather than blanking it: a
460
+ // failed read is not "zero satoshis".
461
+ }
462
+ })()
463
+ inFlightBalanceRef.current = read
464
+ // Cleared here rather than in a `finally` inside the body: a synchronous
465
+ // throw from the read would run that finally BEFORE the assignment above,
466
+ // leaving a settled promise latched forever.
467
+ void read.finally(() => {
468
+ if (inFlightBalanceRef.current === read) inFlightBalanceRef.current = null
469
+ })
470
+ return await read
471
+ }, [
472
+ storage,
473
+ walletUserId,
474
+ managers.permissionsManager,
475
+ adminOriginator,
476
+ balanceCacheKey,
477
+ onThisNetwork,
478
+ knownNoStoredIdentity
479
+ ])
480
+
481
+ /**
482
+ * The effects below key off DATA changes, never off `refreshBalance`'s
483
+ * identity.
484
+ *
485
+ * `refreshBalance` is rebuilt whenever the wallet context rebuilds, because
486
+ * `managers.permissionsManager` is one of its deps. With that callback in an
487
+ * effect's dependency list, a mid-session rebuild made every live instance of
488
+ * this screen fire a fresh multi-second balance read — the "mount" effect was
489
+ * never mount-only. What the effects actually need is *whether* a wallet
490
+ * exists, so they depend on that instead.
491
+ */
492
+ const refreshBalanceRef = useRef(refreshBalance)
493
+ useEffect(() => {
494
+ refreshBalanceRef.current = refreshBalance
495
+ }, [refreshBalance])
496
+ // Either route to a figure counts: the direct read needs storage and the user
497
+ // id, the fallback needs the permissions manager.
498
+ const hasWallet = (storage != null && walletUserId != null) || managers.permissionsManager != null
499
+
500
+ // The old chain's figures must not outlive the switch that ended them. The
501
+ // cached read below refills the balance from THIS network's key a moment
502
+ // later; the list refills once its own storage is mounted.
503
+ useEffect(() => {
504
+ setBalance(null)
505
+ setActions([])
506
+ setOfflineByTxid(new Map())
507
+ offsetRef.current = 0
508
+ exhaustedRef.current = false
509
+ }, [selectedNetwork])
510
+
511
+ useEffect(() => {
512
+ let cancelled = false
513
+ ;(async () => {
514
+ // Show the cached figure immediately so the screen never opens empty.
515
+ const cached = await AsyncStorage.getItem(balanceCacheKey)
516
+ if (cancelled) return
517
+ if (cached != null) setBalance(Number(cached))
518
+ await refreshBalanceRef.current()
519
+ })()
520
+ return () => {
521
+ cancelled = true
522
+ }
523
+ // `hasWallet` covers the cold start where this screen mounts before the
524
+ // wallet finishes building; `balanceCacheKey` covers a network switch.
525
+ // `knownNoStoredIdentity` re-fires this once the prompt-free identity
526
+ // check resolves — it starts false, so a genuinely wallet-less mount's
527
+ // first pass through refreshBalance skips the zero-settle (see there) and
528
+ // would otherwise leave the spinner with no wallet build left to finish
529
+ // and no further balance read ever queued.
530
+ }, [balanceCacheKey, hasWallet, knownNoStoredIdentity])
531
+
532
+ /**
533
+ * Returning to this screen refetches the balance and the activity list once.
534
+ *
535
+ * This screen stays mounted while /pay and /vault sit on top of it in the
536
+ * stack, so neither the mount effect above nor the activity effect below runs
537
+ * again on the way back. `txStatusVersion` covers writes that go through the
538
+ * wallet, but relying on it alone leaves the user's own money looking stale
539
+ * for any path that does not — an offline row queued while the network was
540
+ * down, say — and "did that payment go through?" is the exact question this
541
+ * screen exists to answer.
542
+ *
543
+ * A counter rather than a direct call: both effects below already know how to
544
+ * fetch, so this reuses them instead of duplicating the fetch logic. Fires
545
+ * once per return, not on a timer. The first focus is skipped — that is the
546
+ * mount, which the effects already cover.
547
+ */
548
+ const [focusVersion, setFocusVersion] = useState(0)
549
+ const firstFocusRef = useRef(true)
550
+
551
+ const pollResendRequests = useCallback(async () => {
552
+ const pm = managers.permissionsManager
553
+ if (!pm || !storage) return
554
+ try {
555
+ const url = await readMessageBoxUrl()
556
+ if (!url) return
557
+ const client = new PeerPayClient({
558
+ messageBoxHost: url,
559
+ walletClient: pm as never,
560
+ originator: adminOriginator
561
+ })
562
+ const r = await listPendingResendRequests({ client, storage })
563
+ setPendingResends(r.pending)
564
+ } catch {
565
+ // Silent: an unreachable box must not alert on focus. The stored
566
+ // unanswered count (if any) keeps the inline row visible.
567
+ }
568
+ }, [managers.permissionsManager, storage, adminOriginator])
569
+
570
+ useEffect(() => {
571
+ if (!storage) return
572
+ let cancelled = false
573
+ ;(async () => {
574
+ const stored = await loadUnansweredResends(storage)
575
+ if (cancelled) return
576
+ setPendingResends(stored)
577
+ await pollResendRequests()
578
+ })()
579
+ return () => {
580
+ cancelled = true
581
+ }
582
+ }, [storage, pollResendRequests])
583
+
584
+ useFocusEffect(
585
+ useCallback(() => {
586
+ if (firstFocusRef.current) {
587
+ firstFocusRef.current = false
588
+ return
589
+ }
590
+ setFocusVersion(v => v + 1)
591
+ void pollResendRequests()
592
+ }, [pollResendRequests])
593
+ )
594
+
595
+ // Re-read the figure whenever the transaction tables move — a payment sent, a
596
+ // deposit internalized, a status change from the monitor. Skips the first pass,
597
+ // which the mount effect above already covers.
598
+ const balanceMountedRef = useRef(false)
599
+ useEffect(() => {
600
+ if (!balanceMountedRef.current) {
601
+ balanceMountedRef.current = true
602
+ return
603
+ }
604
+ void refreshBalanceRef.current()
605
+ }, [txStatusVersion, focusVersion])
606
+
607
+ // ── activity ────────────────────────────────────────────────────────
608
+ const fetchActions = useCallback(
609
+ async (offset: number) => {
610
+ if (!managers.permissionsManager) return null
611
+ try {
612
+ const result = await managers.permissionsManager.listActions(
613
+ { labels: [], includeLabels: true, limit: PAGE_SIZE, offset },
614
+ adminOriginator
615
+ )
616
+ if (offset === 0) setLoadError(false)
617
+ return result
618
+ } catch (e) {
619
+ if (offset === 0) setLoadError(true)
620
+ throw e
621
+ }
622
+ },
623
+ [managers.permissionsManager, adminOriginator]
624
+ )
625
+
626
+ const fetchOfflineRows = useCallback(async () => {
627
+ try {
628
+ if (storage) {
629
+ try {
630
+ const pending = await readUnprocessedPending(storage)
631
+ setPendingCount(pending.count)
632
+ setPendingStuck(pending.stuck)
633
+ setPendingCorrupt(pending.corrupt)
634
+ } catch {
635
+ setPendingCount(0)
636
+ setPendingStuck(0)
637
+ setPendingCorrupt(getPendingCorruptNotice())
638
+ }
639
+ }
640
+ const db = storage?.sqliteDb
641
+ if (!db) return
642
+ const rows = await findOfflineActions(db, {
643
+ status: ['queued', 'posting', 'rejected', 'parked'],
644
+ ...(walletUserId === null ? {} : { userId: walletUserId })
645
+ })
646
+ setOfflineByTxid(new Map(rows.map(r => [r.txid, r])))
647
+ setStalled(TaskSendOffline.lastStall)
648
+ } catch {
649
+ // Advisory overlay only — a read failure must not break the list.
650
+ }
651
+ }, [storage, walletUserId])
652
+
653
+ useEffect(() => {
654
+ let cancelled = false
655
+ ;(async () => {
656
+ // Same gate as the balance: until the mounted storage belongs to the
657
+ // network on screen, the wallet answering listActions is still the
658
+ // previous chain's, and its payments are not this network's. A null
659
+ // storage (no wallet created yet) also fails this gate, and has
660
+ // nothing to load — settle the spinner instead of leaving it spinning
661
+ // until a wallet exists.
662
+ if (!onThisNetwork) {
663
+ if (!storage) setLoading(false)
664
+ return
665
+ }
666
+ if (actions.length === 0) setLoading(true)
667
+ try {
668
+ const result = await fetchActions(0)
669
+ if (cancelled) return
670
+ if (!result) {
671
+ // No permissionsManager yet (no wallet created — see the lazy
672
+ // creation flow above): there is nothing to load, so settle the
673
+ // spinner instead of leaving it spinning forever.
674
+ setLoading(false)
675
+ return
676
+ }
677
+ setActions(result.actions as ActivityAction[])
678
+ offsetRef.current = result.actions.length
679
+ // A fresh first page may have more behind it again.
680
+ exhaustedRef.current = result.actions.length < PAGE_SIZE || result.actions.length >= (result.totalActions ?? 0)
681
+ setLoading(false)
682
+ } catch {
683
+ if (cancelled) return
684
+ setLoadError(true)
685
+ setLoading(false)
686
+ }
687
+ })()
688
+ void fetchOfflineRows()
689
+ setAttentionCount(TaskCreditInbox.lastAttentionCount)
690
+ if (storage) {
691
+ void getOutboxEntries(storage).then(entries => {
692
+ if (!cancelled) setUnsentCount(unsentEntries(entries).length)
693
+ })
694
+ }
695
+ return () => {
696
+ cancelled = true
697
+ }
698
+ // eslint-disable-next-line react-hooks/exhaustive-deps
699
+ }, [fetchActions, txStatusVersion, focusVersion, fetchOfflineRows, storage, onThisNetwork])
700
+
701
+ const loadMore = useCallback(async () => {
702
+ // Three guards, all load-bearing:
703
+ // - exhaustedRef: without it, reaching the bottom fires onEndReached
704
+ // forever — each pass runs a real listActions query, returns nothing, and
705
+ // the footer swapping between spinner and spacer changes content height,
706
+ // which makes FlatList re-evaluate and fire again. That is a tight loop.
707
+ // - inFlightRef: `loadingMore` is state, so two onEndReached calls in the
708
+ // same tick would both read the stale `false` and double-fetch.
709
+ // - loading: the first page is still landing; its result sets the offset.
710
+ if (exhaustedRef.current || inFlightRef.current || loading) return
711
+ inFlightRef.current = true
712
+ setLoadingMore(true)
713
+ try {
714
+ const result = await fetchActions(offsetRef.current)
715
+ const page = (result?.actions ?? []) as ActivityAction[]
716
+ if (page.length) {
717
+ setActions(prev => [...prev, ...page])
718
+ offsetRef.current += page.length
719
+ }
720
+ // A short page means the end; so does reaching the reported total.
721
+ if (page.length < PAGE_SIZE || offsetRef.current >= (result?.totalActions ?? 0)) {
722
+ exhaustedRef.current = true
723
+ }
724
+ } catch {
725
+ // Keep existing rows; a failed page is not the end of the list.
726
+ } finally {
727
+ inFlightRef.current = false
728
+ setLoadingMore(false)
729
+ }
730
+ }, [fetchActions, loading])
731
+
732
+ const onRefresh = useCallback(async () => {
733
+ setRefreshing(true)
734
+ try {
735
+ const [result, , , entries] = await Promise.all([
736
+ fetchActions(0),
737
+ refreshBalance(),
738
+ fetchOfflineRows(),
739
+ storage ? getOutboxEntries(storage) : Promise.resolve([])
740
+ ])
741
+ if (result) {
742
+ setActions(result.actions as ActivityAction[])
743
+ offsetRef.current = result.actions.length
744
+ exhaustedRef.current = result.actions.length < PAGE_SIZE || result.actions.length >= (result.totalActions ?? 0)
745
+ }
746
+ setAttentionCount(TaskCreditInbox.lastAttentionCount)
747
+ setUnsentCount(unsentEntries(entries).length)
748
+ } catch {
749
+ // loadError is set by fetchActions for a first-page failure.
750
+ } finally {
751
+ setRefreshing(false)
752
+ }
753
+ }, [fetchActions, refreshBalance, fetchOfflineRows, storage])
754
+
755
+ const onExport = useCallback(async () => {
756
+ if (exporting || actions.length === 0 || !managers.permissionsManager) return
757
+ setExporting(true)
758
+ try {
759
+ const count = await exportTransactionsAsCsv(managers.permissionsManager, storage, adminOriginator)
760
+ if (count === 0) showToast(t('no_transactions'), { type: 'info' })
761
+ } catch {
762
+ showToast(t('tx_export_failed'), { type: 'error' })
763
+ } finally {
764
+ setExporting(false)
765
+ }
766
+ }, [exporting, actions.length, managers.permissionsManager, storage, adminOriginator, t])
767
+
768
+ // ── per-row actions ──────────────────────────────────────────────────
769
+
770
+ /** Open the transaction on a block explorer in the system browser. */
771
+ const onExplorer = useCallback(
772
+ (txid: string) => {
773
+ const base =
774
+ selectedNetwork === 'main'
775
+ ? 'https://whatsonchain.com'
776
+ : selectedNetwork === 'teratest'
777
+ ? 'https://woc-ttn.bsvblockchain.tech'
778
+ : 'https://test.whatsonchain.com'
779
+ Linking.openURL(`${base}/tx/${txid}`).catch(() => {
780
+ showToast(t('explorer_open_failed'), { type: 'error' })
781
+ })
782
+ },
783
+ [selectedNetwork, t]
784
+ )
785
+
786
+ /** Copy the transaction's full BEEF (raw tx + the proofs/ancestry that make
787
+ * it independently verifiable) as hex — what you paste into a tool or hand to
788
+ * support, unlike a bare txid. */
789
+ const onRefreshTx = useCallback(
790
+ async (txid: string) => {
791
+ if (busyRow) return
792
+ setBusyRow(txid)
793
+ try {
794
+ const outcome = await refreshProof(txid)
795
+ if (outcome === 'confirmed') showToast(t('tx_proof_refreshed'), { type: 'success' })
796
+ else if (outcome === 'failed') showToast(t('tx_marked_failed'), { type: 'info' })
797
+ else showToast(t('tx_still_pending'), { type: 'info' })
798
+ } catch {
799
+ showToast(t('tx_proof_refresh_failed'), { type: 'error' })
800
+ } finally {
801
+ setBusyRow(null)
802
+ setBusyLabel(undefined)
803
+ }
804
+ },
805
+ [busyRow, refreshProof, t]
806
+ )
807
+
808
+ /** Abort a still-local transaction, releasing the inputs it reserved. */
809
+ const onAbort = useCallback(
810
+ async (reference: string) => {
811
+ if (!managers.permissionsManager || busyRow) return
812
+ setBusyRow(reference)
813
+ try {
814
+ const r = (await managers.permissionsManager.abortAction({ reference }, adminOriginator)) as
815
+ | { aborted?: boolean }
816
+ | undefined
817
+ if (!r || r.aborted === false) {
818
+ showToast(t('tx_abort_failed'), { type: 'error' })
819
+ } else {
820
+ showToast(t('tx_abort_success'), { type: 'success' })
821
+ await onRefresh()
822
+ }
823
+ } catch {
824
+ showToast(t('tx_abort_failed'), { type: 'error' })
825
+ } finally {
826
+ setBusyRow(null)
827
+ setBusyLabel(undefined)
828
+ }
829
+ },
830
+ [managers.permissionsManager, adminOriginator, busyRow, onRefresh, t]
831
+ )
832
+
833
+ const onResendPending = useCallback(async () => {
834
+ if (resending) return
835
+ setResending(true)
836
+ try {
837
+ const pm = managers.permissionsManager
838
+ if (!pm || !storage) throw new Error(t('unknown_error'))
839
+ const url = await readMessageBoxUrl()
840
+ if (!url) {
841
+ showToast(t('message_box_unreachable'), { type: 'error' })
842
+ return
843
+ }
844
+ const client = new PeerPayClient({
845
+ messageBoxHost: url,
846
+ walletClient: pm as never,
847
+ originator: adminOriginator
848
+ })
849
+ const r = await handleResendRequests({
850
+ client,
851
+ storage,
852
+ listPeerPayAction: makeListPeerPayAction(pm, adminOriginator),
853
+ decryptMetadata: makeMetadataDecryptor(pm, adminOriginator),
854
+ refetch: makeBeefRepair({ woc: wocConfigFor(selectedNetwork), online: getOnline })
855
+ })
856
+ setPendingResends(r.pending)
857
+ if (r.pending.length === 0) haptics.success()
858
+ else showToast(t('unknown_error'), { type: 'error' })
859
+ } catch (e: unknown) {
860
+ const message = e instanceof Error ? e.message : t('unknown_error')
861
+ showToast(message, { type: 'error' })
862
+ } finally {
863
+ setResending(false)
864
+ }
865
+ }, [resending, managers.permissionsManager, storage, adminOriginator, selectedNetwork, t])
866
+
867
+ const onSendPaymentDetails = useCallback(
868
+ async (txid: string) => {
869
+ if (busyRow) return
870
+ setBusyRow(txid)
871
+ setBusyLabel(t('resend_sending'))
872
+ try {
873
+ const pm = managers.permissionsManager
874
+ if (!pm || !storage) throw new Error(t('unknown_error'))
875
+ const url = await readMessageBoxUrl()
876
+ if (!url) {
877
+ showToast(t('message_box_unreachable'), { type: 'error' })
878
+ return
879
+ }
880
+ const client = new PeerPayClient({
881
+ messageBoxHost: url,
882
+ walletClient: pm as never,
883
+ originator: adminOriginator
884
+ })
885
+ const outcome = await resendPaymentDetails({
886
+ client,
887
+ storage,
888
+ txid,
889
+ listPeerPayAction: makeListPeerPayAction(pm, adminOriginator),
890
+ // Network first for a fresh proof; this device's own copy when the
891
+ // network has never heard of the transaction — a nearby payment whose
892
+ // code was never scanned is `nosend`, and that is the case a resend
893
+ // most needs to cover.
894
+ decryptMetadata: makeMetadataDecryptor(pm, adminOriginator),
895
+ refetch: makeResendBeef({
896
+ refetch: makeBeefRepair({ woc: wocConfigFor(selectedNetwork), online: getOnline }),
897
+ storage
898
+ })
899
+ })
900
+ if (outcome.ok) {
901
+ // A parked payment has now been handed over for real, over a rail
902
+ // that confirms delivery. Release it so this wallet broadcasts it
903
+ // too, instead of leaving it looking like it never went anywhere.
904
+ if (storage && offlineByTxid.get(txid)?.status === 'parked') {
905
+ try {
906
+ await releaseParkedPayment({ storage, txid })
907
+ } catch (e) {
908
+ console.warn('[localpay] resent but could not release:', e instanceof Error ? e.message : e)
909
+ }
910
+ await onRefresh()
911
+ }
912
+ haptics.success()
913
+ showToast(t('resend_sent'), { type: 'success' })
914
+ } else {
915
+ // Each reason is a different thing for the user to do — or not do.
916
+ // Collapsing them into "Unknown error" told someone whose payment can
917
+ // never be rebuilt to keep tapping a button that cannot work.
918
+ showToast(t(`resend_failed_${outcome.reason}`), { type: 'error' })
919
+ }
920
+ } catch (e: unknown) {
921
+ const message = e instanceof Error ? e.message : t('unknown_error')
922
+ showToast(message, { type: 'error' })
923
+ } finally {
924
+ setBusyRow(null)
925
+ setBusyLabel(undefined)
926
+ }
927
+ },
928
+ [busyRow, managers.permissionsManager, storage, adminOriginator, selectedNetwork, offlineByTxid, onRefresh, t]
929
+ )
930
+
931
+ const onFailedSendAgain = useCallback(
932
+ async (action: ActivityAction) => {
933
+ if (busyRow) return
934
+ if (action.txid && storage && managers.permissionsManager) {
935
+ const entry = unsentEntries(await getOutboxEntries(storage)).find(e => e.txid === action.txid)
936
+ if (entry) {
937
+ setBusyRow(action.txid)
938
+ try {
939
+ // Host order on any re-delivery: the recipient's advertised inbox
940
+ // (the client re-resolves it per send, so a host anointed since the
941
+ // original attempt is picked up), then whatever this wallet is
942
+ // configured for NOW — the setting may have changed since the
943
+ // payment was minted — and only then the host recorded at send
944
+ // time, which is the last thing still worth trying if the user has
945
+ // since opted out of a server.
946
+ const client = makePeerPayClient({
947
+ wallet: managers.permissionsManager as never,
948
+ messageBoxUrl: (await readMessageBoxUrl()) ?? entry.messageBoxUrl,
949
+ originator: adminOriginator
950
+ })
951
+ if (!client) {
952
+ showToast(t('message_box_unreachable'), { type: 'error' })
953
+ return
954
+ }
955
+ await retryDelivery({
956
+ wallet: managers.permissionsManager as never,
957
+ adminOriginator,
958
+ client,
959
+ storage,
960
+ entry
961
+ })
962
+ haptics.success()
963
+ await onRefresh()
964
+ } catch (e: unknown) {
965
+ const message = isMessageBoxNetworkError(e)
966
+ ? t('message_box_unreachable')
967
+ : e instanceof Error
968
+ ? e.message
969
+ : t('unknown_error')
970
+ showToast(message, { type: 'error' })
971
+ } finally {
972
+ setBusyRow(null)
973
+ }
974
+ return
975
+ }
976
+ }
977
+ const sats = Math.abs(action.satoshis)
978
+ router.push(sats > 0 ? `/pay?sats=${sats}` : '/pay')
979
+ },
980
+ [busyRow, storage, managers.permissionsManager, adminOriginator, onRefresh, t]
981
+ )
982
+
983
+ const toggleRow = useCallback((key: string) => {
984
+ setExpandedRow(prev => (prev === key ? null : key))
985
+ }, [])
986
+
987
+ const offlineRows = useMemo(() => [...offlineByTxid.values()], [offlineByTxid])
988
+ const rejected = useMemo(
989
+ () => offlineRows.filter(r => r.status === 'rejected' && r.role === 'received'),
990
+ [offlineRows]
991
+ )
992
+ const sentRejected = useMemo(
993
+ () => offlineRows.filter(r => r.status === 'rejected' && r.role === 'sent'),
994
+ [offlineRows]
995
+ )
996
+ // Parked payments are counted apart from queued ones: nothing is waiting to
997
+ // broadcast them, so folding them into "waiting to be broadcast" would say
998
+ // something untrue about both.
999
+ //
1000
+ // The rest pass through the grace filter: online, a payment the drain is
1001
+ // about to post says nothing worth reading, and the banner appearing for the
1002
+ // half second before it lands reads as a fault that is not there.
1003
+ const queued = useMemo(
1004
+ () => offlineRows.filter(r => r.status !== 'rejected' && r.status !== 'parked'),
1005
+ [offlineRows]
1006
+ )
1007
+ const { shown: queuedShown, nextCheckMs } = useMemo(
1008
+ // graceNonce is a dependency only: it carries no value into the call, it
1009
+ // just re-runs it once a young row has aged past the grace.
1010
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1011
+ () => partitionQueueByGrace(queued, { online, nowMs: Date.now() }),
1012
+ [queued, online, graceNonce]
1013
+ )
1014
+ // A row that is merely young becomes newsworthy by the passage of time alone,
1015
+ // and nothing else would wake this screen to notice.
1016
+ useEffect(() => {
1017
+ if (nextCheckMs === undefined) return
1018
+ const t = setTimeout(() => setGraceNonce(n => n + 1), nextCheckMs + 100)
1019
+ return () => clearTimeout(t)
1020
+ }, [nextCheckMs])
1021
+ const queuedCount = queuedShown.length
1022
+ const queuedSent = useMemo(() => queuedShown.filter(r => r.role === 'sent'), [queuedShown])
1023
+ const stuckBadges = useMemo(
1024
+ () =>
1025
+ homeBadges({
1026
+ attention: attentionCount,
1027
+ unsent: unsentCount,
1028
+ offlineQueued: queuedCount,
1029
+ offlineRejected: rejected.length + sentRejected.length
1030
+ }).filter(b => b.kind !== 'offline'),
1031
+ [attentionCount, unsentCount, queuedCount, rejected.length, sentRejected.length]
1032
+ )
1033
+ const reloadOffline = useCallback(() => {
1034
+ void fetchOfflineRows()
1035
+ }, [fetchOfflineRows])
1036
+ const pushPay = useCallback((sats?: number) => {
1037
+ router.push(sats && sats > 0 ? `/pay?sats=${sats}` : '/pay')
1038
+ }, [])
1039
+ const { onRequestAgain, onCopyDetails, onDismiss, onSendAgain } = useOfflineNoticeActions({
1040
+ storage,
1041
+ permissionsManager: managers.permissionsManager,
1042
+ adminOriginator,
1043
+ online,
1044
+ rejected,
1045
+ t,
1046
+ reload: reloadOffline,
1047
+ pushPay
1048
+ })
1049
+
1050
+ // ── rows ────────────────────────────────────────────────────────────
1051
+ const rows = useMemo(() => withDayHeaders(actions, t), [actions, t])
1052
+
1053
+ /** Cancel a parked payment: abort the action so the inputs come back, and
1054
+ * retire its queue row. Refuses once the counterparty has broadcast. */
1055
+ const onCancelParked = useCallback(
1056
+ async (txid: string) => {
1057
+ const pm = managers.permissionsManager
1058
+ if (!storage || !pm || busyRow) return
1059
+ setBusyRow(txid)
1060
+ setBusyLabel(t('cancelling_payment'))
1061
+ try {
1062
+ const outcome = await cancelParkedPayment({
1063
+ storage,
1064
+ wallet: pm as unknown as CancelParkedWallet,
1065
+ originator: adminOriginator,
1066
+ txid
1067
+ })
1068
+ if (outcome === 'cancelled') showToast(t('tx_abort_success'), { type: 'success' })
1069
+ else if (outcome === 'already-sent') showToast(t('pay_parked_already_sent'), { type: 'info' })
1070
+ else showToast(t('tx_abort_failed'), { type: 'error' })
1071
+ await onRefresh()
1072
+ } catch (e: unknown) {
1073
+ showToast(e instanceof Error ? e.message : t('unknown_error'), { type: 'error' })
1074
+ } finally {
1075
+ setBusyRow(null)
1076
+ setBusyLabel(undefined)
1077
+ }
1078
+ },
1079
+ [storage, managers.permissionsManager, adminOriginator, busyRow, onRefresh, t]
1080
+ )
1081
+
1082
+ const renderItem: ListRenderItem<Row> = useCallback(
1083
+ ({ item, index }) => {
1084
+ if (item.kind === 'day') {
1085
+ return <Text style={[styles.dayHeader, { color: colors.textTertiary }]}>{item.label}</Text>
1086
+ }
1087
+ const key = item.txid || item.reference || `row-${index}`
1088
+ const offline = item.txid ? offlineByTxid.get(item.txid) : undefined
1089
+ const busy = busyRow === item.txid || (!!item.reference && busyRow === item.reference)
1090
+
1091
+ return (
1092
+ <ActivityRow
1093
+ action={item}
1094
+ rowKey={key}
1095
+ offlineStatus={offline?.status}
1096
+ expanded={expandedRow === key}
1097
+ busy={busy}
1098
+ busyLabel={busyLabel}
1099
+ onToggle={toggleRow}
1100
+ onExplorer={onExplorer}
1101
+ onRefreshTx={onRefreshTx}
1102
+ onAbort={onAbort}
1103
+ onSendPaymentDetails={onSendPaymentDetails}
1104
+ onSendAgain={onFailedSendAgain}
1105
+ onCancelParked={txid => void onCancelParked(txid)}
1106
+ />
1107
+ )
1108
+ },
1109
+ [
1110
+ colors,
1111
+ offlineByTxid,
1112
+ busyRow,
1113
+ busyLabel,
1114
+ expandedRow,
1115
+ toggleRow,
1116
+ onExplorer,
1117
+ onRefreshTx,
1118
+ onAbort,
1119
+ onSendPaymentDetails,
1120
+ onFailedSendAgain,
1121
+ onCancelParked
1122
+ ]
1123
+ )
1124
+
1125
+ // ── header (balance + the three destinations + activity heading) ─────
1126
+ const balanceParts = useMemo(
1127
+ () => (balance === null ? null : formatAmountParts(balance, currency, satoshisPerUSD, { abbreviate: true, usdToFiat })),
1128
+ [balance, currency, satoshisPerUSD, usdToFiat]
1129
+ )
1130
+
1131
+ /** The line under the figure: the same money in the denominations the figure
1132
+ * is not using, so the user never has to convert in their head. */
1133
+ const balanceContext = useMemo(() => {
1134
+ if (balance === null) return ''
1135
+ const bsv = `${formatSatoshisAsBsvDecimal(balance)} BSV`
1136
+ const other = formatAmount(balance, currency === 'BSV' ? 'USD' : 'BSV', satoshisPerUSD, {
1137
+ abbreviate: true,
1138
+ usdToFiat
1139
+ })
1140
+ return `${bsv} · ${other}`
1141
+ }, [balance, currency, satoshisPerUSD, usdToFiat])
1142
+
1143
+ /**
1144
+ * Pinned above the list, not part of it.
1145
+ *
1146
+ * The balance and the two destinations are what someone opens this screen
1147
+ * for; scrolling a long history used to carry them off the top, so the
1148
+ * answer to "how much do I have" and the way to pay were both a scroll back
1149
+ * up. Everything below them still scrolls with the activity it describes.
1150
+ */
1151
+ const pinnedHeader = useMemo(
1152
+ () => (
1153
+ <View>
1154
+ <TouchableOpacity
1155
+ onPress={() => void refreshBalance()}
1156
+ activeOpacity={0.7}
1157
+ style={styles.balanceBlock}
1158
+ accessibilityLabel={t('wallet_balance_refresh')}
1159
+ >
1160
+ <Text style={[styles.balanceLabel, { color: colors.textTertiary }]}>{t('wallet_balance_you_have')}</Text>
1161
+ {balanceParts === null ? (
1162
+ <ActivityIndicator color={colors.textSecondary} style={styles.balanceSpinner} />
1163
+ ) : (
1164
+ <>
1165
+ <Text style={[styles.balance, { color: colors.textPrimary }]}>
1166
+ {balanceParts.value}
1167
+ {balanceParts.unit ? (
1168
+ <Text style={[styles.balanceUnit, { color: colors.textSecondary }]}> {balanceParts.unit}</Text>
1169
+ ) : null}
1170
+ </Text>
1171
+ <Text style={[styles.balanceContext, { color: colors.textSecondary }]}>{balanceContext}</Text>
1172
+ </>
1173
+ )}
1174
+ </TouchableOpacity>
1175
+
1176
+ {/* The destinations. Pay is the only accent-filled element on this
1177
+ screen, so the eye lands on it first. */}
1178
+ <View style={styles.destinations}>
1179
+ <PressableScale
1180
+ haptic="confirm"
1181
+ onPress={() => destinationPress('/pay')}
1182
+ style={[styles.dest, styles.destPrimary, { backgroundColor: colors.accent }]}
1183
+ >
1184
+ <MaterialCommunityIcons name="arrow-top-right" size={19} color={colors.textOnAccent} />
1185
+ <Text style={[styles.destLabel, styles.destLabelPrimary, { color: colors.textOnAccent }]}>
1186
+ {t('pay_direction_pay')}
1187
+ </Text>
1188
+ </PressableScale>
1189
+
1190
+ <PressableScale
1191
+ haptic="confirm"
1192
+ onPress={() => destinationPress('/pay?direction=get')}
1193
+ style={[styles.dest, { backgroundColor: colors.surfaceRaised, borderColor: colors.surfaceRaisedBorder }]}
1194
+ >
1195
+ <MaterialCommunityIcons name="arrow-bottom-left" size={19} color={colors.textPrimary} />
1196
+ <Text style={[styles.destLabel, { color: colors.textPrimary }]}>{t('pay_direction_receive')}</Text>
1197
+ </PressableScale>
1198
+
1199
+ {/* Vault — hidden for now; will release once R1-K1 research is complete.
1200
+ <PressableScale
1201
+ onPress={() => router.push('/vault')}
1202
+ style={[
1203
+ styles.dest,
1204
+ { backgroundColor: colors.surfaceRaised, borderColor: colors.surfaceRaisedBorder }
1205
+ ]}
1206
+ >
1207
+ <MaterialCommunityIcons name="safe" size={19} color={colors.textPrimary} />
1208
+ <Text style={[styles.destLabel, { color: colors.textPrimary }]}>
1209
+ {t('wallet_vault')}
1210
+ </Text>
1211
+ </PressableScale>
1212
+ */}
1213
+ </View>
1214
+ </View>
1215
+ ),
1216
+ [balanceParts, balanceContext, colors, t, refreshBalance, router]
1217
+ )
1218
+
1219
+ const listHeader = useMemo(
1220
+ () => (
1221
+ <View>
1222
+ {pendingResends.length > 0 || stuckBadges.length > 0 ? (
1223
+ <View style={styles.resendBanner}>
1224
+ {pendingResends.length > 0 ? (
1225
+ <GroupedSection>
1226
+ <ListRow
1227
+ label={t('resend_requested')}
1228
+ icon="refresh-outline"
1229
+ iconColor={colors.warning}
1230
+ showChevron={false}
1231
+ isLast
1232
+ onPress={resending ? undefined : () => void onResendPending()}
1233
+ trailing={
1234
+ resending ? (
1235
+ <View style={styles.resendTrailing}>
1236
+ <ActivityIndicator size="small" color={colors.accent} />
1237
+ <Text style={[styles.resendAction, { color: colors.accent }]}>{t('resending')}</Text>
1238
+ </View>
1239
+ ) : (
1240
+ <Text style={[styles.resendAction, { color: colors.accent }]}>{t('resend')}</Text>
1241
+ )
1242
+ }
1243
+ />
1244
+ </GroupedSection>
1245
+ ) : null}
1246
+ {stuckBadges.length > 0 ? (
1247
+ <GroupedSection>
1248
+ {stuckBadges.map((badge, i) => (
1249
+ <ListRow
1250
+ key={badge.kind}
1251
+ label={
1252
+ badge.kind === 'attention'
1253
+ ? t('home_payments_need_attention', { count: badge.count })
1254
+ : t('home_payments_unsent', { count: badge.count })
1255
+ }
1256
+ icon={badge.kind === 'attention' ? 'alert-circle-outline' : 'send-outline'}
1257
+ iconColor={colors.warning}
1258
+ isLast={i === stuckBadges.length - 1}
1259
+ onPress={() =>
1260
+ router.push(badge.kind === 'attention' ? '/pay?cell=get-handle' : '/pay?cell=pay-handle')
1261
+ }
1262
+ />
1263
+ ))}
1264
+ </GroupedSection>
1265
+ ) : null}
1266
+ </View>
1267
+ ) : null}
1268
+
1269
+ <OfflineNotice
1270
+ compact
1271
+ online={online}
1272
+ queued={queuedCount}
1273
+ rejected={rejected}
1274
+ sentRejected={sentRejected}
1275
+ onSendNow={() => TaskSendOffline.requestNow()}
1276
+ stalled={stalled}
1277
+ pendingCount={pendingCount}
1278
+ pendingStuck={pendingStuck}
1279
+ pendingCorrupt={pendingCorrupt}
1280
+ queuedSent={queuedSent}
1281
+ onShowCode={() => router.push('/pay')}
1282
+ onRequestAgain={row => void onRequestAgain(row)}
1283
+ onCopyDetails={onCopyDetails}
1284
+ onDismiss={row => void onDismiss(row)}
1285
+ onSendAgain={row => void onSendAgain(row)}
1286
+ />
1287
+
1288
+ <View style={styles.activityHead}>
1289
+ <Text style={[styles.activityTitle, { color: colors.textPrimary }]}>{t('wallet_activity')}</Text>
1290
+ <TouchableOpacity
1291
+ onPress={onExport}
1292
+ disabled={exporting || actions.length === 0}
1293
+ hitSlop={8}
1294
+ style={[styles.exportBtn, { borderColor: colors.surfaceRaisedBorder }]}
1295
+ accessibilityRole="button"
1296
+ accessibilityLabel={t('tx_export_csv')}
1297
+ >
1298
+ {exporting ? (
1299
+ <ActivityIndicator size="small" color={colors.textSecondary} />
1300
+ ) : (
1301
+ <Ionicons
1302
+ name="download-outline"
1303
+ size={12}
1304
+ color={actions.length === 0 ? colors.textTertiary : colors.textSecondary}
1305
+ />
1306
+ )}
1307
+ <Text
1308
+ style={[styles.exportLabel, { color: actions.length === 0 ? colors.textTertiary : colors.textSecondary }]}
1309
+ >
1310
+ {t('tx_export_csv')}
1311
+ </Text>
1312
+ </TouchableOpacity>
1313
+ </View>
1314
+ </View>
1315
+ ),
1316
+ [
1317
+ colors,
1318
+ t,
1319
+ onExport,
1320
+ exporting,
1321
+ actions.length,
1322
+ pendingResends.length,
1323
+ stuckBadges,
1324
+ resending,
1325
+ onResendPending,
1326
+ online,
1327
+ queuedCount,
1328
+ rejected,
1329
+ sentRejected,
1330
+ queuedSent,
1331
+ stalled,
1332
+ pendingCount,
1333
+ pendingStuck,
1334
+ pendingCorrupt,
1335
+ onRequestAgain,
1336
+ onCopyDetails,
1337
+ onDismiss,
1338
+ onSendAgain
1339
+ ]
1340
+ )
1341
+
1342
+ return (
1343
+ <View style={[styles.container, { paddingTop: insets.top }]}>
1344
+ <ScreenGradient from={colors.canvasTop} to={colors.canvasBase} height={360} />
1345
+
1346
+ {/* Settings is the only thing up here: it is navigation chrome, not a
1347
+ money action, so it should not compete with Pay and Vault for the eye.
1348
+ Connections moved into Settings as "Connect to App" — pairing a desktop
1349
+ app is a once-in-a-while errand, not a home-screen affordance. */}
1350
+ <View style={[styles.header, topLeft ? styles.headerSpaced : styles.headerEnd]}>
1351
+ {topLeft}
1352
+ <TouchableOpacity
1353
+ onPress={() => router.push('/wallet-config')}
1354
+ style={[styles.iconBtn, { backgroundColor: colors.surfaceRaised, borderColor: colors.surfaceRaisedBorder }]}
1355
+ accessibilityRole="button"
1356
+ accessibilityLabel={t('wallet_settings')}
1357
+ >
1358
+ <Ionicons name="settings-outline" size={17} color={colors.textSecondary} />
1359
+ </TouchableOpacity>
1360
+ </View>
1361
+
1362
+ {/* Renders only when the keys could not be released — a destroyed key, a
1363
+ dismissed prompt, or biometric lockout. Previously all three looked
1364
+ identical to "you have no wallet". */}
1365
+ <WalletLockNotice />
1366
+
1367
+ <View onLayout={e => setPinnedHeight(e.nativeEvent.layout.height)}>{pinnedHeader}</View>
1368
+
1369
+ {/* The list scrolls under this edge. The fade makes a row dissolve into
1370
+ the backdrop as it goes rather than being cut off mid-glyph. */}
1371
+ <View style={styles.listWrap}>
1372
+ <ScrollFade color={sampleScreenGradient(colors.canvasTop, colors.canvasBase, insets.top + pinnedHeight, 360)} />
1373
+ <FlatList
1374
+ data={rows}
1375
+ keyExtractor={(item, index) => (item.kind === 'day' ? item.id : `${item.txid || index}-${index}`)}
1376
+ renderItem={renderItem}
1377
+ ListHeaderComponent={listHeader}
1378
+ ListEmptyComponent={
1379
+ loading ? (
1380
+ <ActivityIndicator style={styles.pad} color={colors.textSecondary} />
1381
+ ) : loadError ? (
1382
+ <View style={styles.emptyError}>
1383
+ <Text style={[styles.empty, { color: colors.textSecondary, padding: 0 }]}>
1384
+ {t('activity_load_failed')}
1385
+ </Text>
1386
+ <PressableScale
1387
+ onPress={() => {
1388
+ setLoadError(false)
1389
+ setFocusVersion(v => v + 1)
1390
+ }}
1391
+ haptic="tap"
1392
+ style={styles.emptyRetry}
1393
+ accessibilityRole="button"
1394
+ accessibilityLabel={t('activity_load_retry')}
1395
+ >
1396
+ <Text style={[styles.emptyRetryLabel, { color: colors.accent }]}>{t('activity_load_retry')}</Text>
1397
+ </PressableScale>
1398
+ </View>
1399
+ ) : (
1400
+ <Text style={[styles.empty, { color: colors.textSecondary }]}>{t('no_transactions')}</Text>
1401
+ )
1402
+ }
1403
+ onEndReached={loadMore}
1404
+ onEndReachedThreshold={0.3}
1405
+ refreshing={refreshing}
1406
+ onRefresh={onRefresh}
1407
+ ListFooterComponent={
1408
+ // One container of FIXED height in both states. Swapping a short
1409
+ // spinner for a tall spacer changed the content height every time a
1410
+ // page load started/ended, which made FlatList re-evaluate and re-fire
1411
+ // onEndReached — feeding the loop the guards above now break.
1412
+ <View style={[styles.footer, { height: insets.bottom + spacing.xxxl }]}>
1413
+ {loadingMore ? <ActivityIndicator color={colors.textSecondary} /> : null}
1414
+ </View>
1415
+ }
1416
+ />
1417
+ </View>
1418
+
1419
+ <BackupReminderSheet
1420
+ visible={showBackupReminder}
1421
+ onClose={() => setShowBackupReminder(false)}
1422
+ onBackupNow={() => {
1423
+ setShowBackupReminder(false)
1424
+ router.push('/auth/mnemonic?flow=backup')
1425
+ }}
1426
+ />
1427
+
1428
+ <BiometricAdvisoryModal
1429
+ visible={showBiometricAdvisory}
1430
+ loading={creatingWalletFromAdvisory}
1431
+ onCancel={() => {
1432
+ setShowBiometricAdvisory(false)
1433
+ setPendingDestination(null)
1434
+ }}
1435
+ onContinue={() => {
1436
+ // Kept up (with a spinner in place of the label) until wallet
1437
+ // creation actually settles: recoverMnemonicWallet's PBKDF2/BIP32
1438
+ // math is real, blocking JS-thread work, and dismissing the modal
1439
+ // immediately here left the screen looking frozen for that whole
1440
+ // stretch, with nothing on screen explaining why.
1441
+ setCreatingWalletFromAdvisory(true)
1442
+ const destination = pendingDestination
1443
+ ;(async () => {
1444
+ try {
1445
+ // ensureWalletExists' generateMnemonicWallet/recoverMnemonicWallet
1446
+ // math starts running synchronously on this same tick — without
1447
+ // yielding first, that blocking work could start before React
1448
+ // ever got to paint the spinner just requested above, making the
1449
+ // tap look like it did nothing.
1450
+ await new Promise(resolve => setTimeout(resolve, 0))
1451
+ const created = await ensureWalletExists()
1452
+ setShowBiometricAdvisory(false)
1453
+ setPendingDestination(null)
1454
+ if (created && destination) router.push(destination as Parameters<typeof router.push>[0])
1455
+ } finally {
1456
+ setCreatingWalletFromAdvisory(false)
1457
+ }
1458
+ })()
1459
+ }}
1460
+ />
1461
+
1462
+ <ImportFromBackupPrompt
1463
+ visible={!hasWallet && knownNoStoredIdentity}
1464
+ onImport={() => router.push('/auth/mnemonic?flow=import')}
1465
+ />
1466
+ </View>
1467
+ )
1468
+ }
1469
+
1470
+ const styles = StyleSheet.create({
1471
+ container: { flex: 1 },
1472
+ // No bottom rule: the gradient already separates the chrome from the balance,
1473
+ // and a hairline there cut the screen in half above the focal figure.
1474
+ header: {
1475
+ flexDirection: 'row',
1476
+ alignItems: 'center',
1477
+ paddingHorizontal: spacing.lg,
1478
+ paddingTop: spacing.sm,
1479
+ paddingBottom: spacing.xs
1480
+ },
1481
+ headerEnd: { justifyContent: 'flex-end' },
1482
+ headerSpaced: { justifyContent: 'space-between' },
1483
+ iconBtn: {
1484
+ width: 34,
1485
+ height: 34,
1486
+ borderRadius: 17,
1487
+ borderWidth: StyleSheet.hairlineWidth,
1488
+ alignItems: 'center',
1489
+ justifyContent: 'center'
1490
+ },
1491
+ balanceBlock: {
1492
+ alignItems: 'center',
1493
+ paddingTop: spacing.xxl,
1494
+ paddingBottom: spacing.xl,
1495
+ paddingHorizontal: spacing.xl
1496
+ },
1497
+ // Uppercase + wide tracking: this is a column heading over a figure, not a
1498
+ // phrase leading into it. Scripts without case ignore the transform.
1499
+ // Sentence case, not the uppercase eyebrow treatment: "You have" is a phrase
1500
+ // leading into the figure, and caps would read as shouting rather than as a
1501
+ // label.
1502
+ balanceLabel: {
1503
+ fontSize: 13,
1504
+ fontWeight: '600',
1505
+ letterSpacing: 0.2
1506
+ },
1507
+ balanceSpinner: { marginTop: spacing.md },
1508
+ // tabular-nums keeps the figure from jittering as digits change.
1509
+ balance: {
1510
+ ...typography.display,
1511
+ lineHeight: 46,
1512
+ letterSpacing: -1.2,
1513
+ marginTop: 10,
1514
+ fontVariant: ['tabular-nums']
1515
+ },
1516
+ balanceUnit: { fontSize: 19, fontWeight: '600', letterSpacing: 0 },
1517
+ balanceContext: { fontSize: 13, lineHeight: 18, marginTop: 10, fontVariant: ['tabular-nums'] },
1518
+
1519
+ destinations: {
1520
+ flexDirection: 'row',
1521
+ gap: 10,
1522
+ paddingHorizontal: spacing.xl,
1523
+ // Breathing room under the buttons, so the first activity row fades in
1524
+ // below them instead of arriving hard against their edge.
1525
+ paddingBottom: spacing.lg
1526
+ },
1527
+ listWrap: { flex: 1 },
1528
+ dest: {
1529
+ flex: 1,
1530
+ alignItems: 'center',
1531
+ justifyContent: 'center',
1532
+ gap: spacing.sm,
1533
+ borderRadius: 16,
1534
+ paddingTop: 15,
1535
+ paddingBottom: 13,
1536
+ borderWidth: StyleSheet.hairlineWidth,
1537
+ borderColor: 'transparent'
1538
+ },
1539
+ // The one accent-filled control on the screen, so it also gets the only
1540
+ // shadow — the two cues have to agree about what is primary.
1541
+ destPrimary: {
1542
+ borderColor: 'transparent',
1543
+ shadowColor: '#000',
1544
+ shadowOpacity: 0.28,
1545
+ shadowRadius: 14,
1546
+ shadowOffset: { width: 0, height: 8 },
1547
+ elevation: 4
1548
+ },
1549
+ destLabel: { fontSize: 13, fontWeight: '600' },
1550
+ destLabelPrimary: { fontWeight: '700' },
1551
+ resendBanner: { paddingTop: spacing.xl },
1552
+ resendTrailing: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
1553
+ resendAction: { fontSize: 15, fontWeight: '600' },
1554
+
1555
+ activityHead: {
1556
+ flexDirection: 'row',
1557
+ alignItems: 'center',
1558
+ justifyContent: 'space-between',
1559
+ paddingHorizontal: spacing.xl,
1560
+ paddingTop: 28,
1561
+ paddingBottom: 10
1562
+ },
1563
+ activityTitle: { fontSize: 15, fontWeight: '700', letterSpacing: -0.2 },
1564
+ exportBtn: {
1565
+ flexDirection: 'row',
1566
+ alignItems: 'center',
1567
+ gap: 6,
1568
+ paddingHorizontal: 11,
1569
+ paddingVertical: 6,
1570
+ borderRadius: radii.pill,
1571
+ borderWidth: StyleSheet.hairlineWidth
1572
+ },
1573
+ exportLabel: { fontSize: 12, fontWeight: '600' },
1574
+
1575
+ dayHeader: {
1576
+ fontSize: 10.5,
1577
+ fontWeight: '700',
1578
+ letterSpacing: 1.3,
1579
+ textTransform: 'uppercase',
1580
+ paddingHorizontal: spacing.xl,
1581
+ paddingTop: 14,
1582
+ paddingBottom: 4
1583
+ },
1584
+
1585
+ pad: { padding: spacing.xl },
1586
+ footer: { alignItems: 'center', justifyContent: 'center' },
1587
+ empty: { ...typography.subhead, textAlign: 'center', padding: spacing.xxxl },
1588
+ emptyError: { alignItems: 'center', padding: spacing.xxxl, gap: spacing.md },
1589
+ emptyRetry: {
1590
+ minHeight: 44,
1591
+ minWidth: 44,
1592
+ alignItems: 'center',
1593
+ justifyContent: 'center',
1594
+ paddingHorizontal: spacing.lg
1595
+ },
1596
+ emptyRetryLabel: { fontSize: 15, fontWeight: '600' }
1597
+ })