@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,479 @@
1
+ /**
2
+ * Pay — two screens, no chooser.
3
+ *
4
+ * Pay opens on one send form whose recipient field infers the rail from what
5
+ * is typed or scanned (see core/pay/rails: classifyRecipientInput,
6
+ * classifyScan). A scanned nearby-session code swaps the form for NearbyFlow.
7
+ *
8
+ * Get paid opens on the request hub: the amount first, then three method
9
+ * rows, each of which shows that method's code with the amount carried in.
10
+ *
11
+ * `?cell=` values survive as deep-link aliases: any `pay-*` opens the send form
12
+ * (`pay-nearby` with the scanner up), any `get-*` opens that method directly.
13
+ */
14
+ import React, { useCallback, useEffect, useMemo, useState } from 'react'
15
+ import { I18nManager, InteractionManager, Modal, StyleSheet, Text, TouchableOpacity, View } from 'react-native'
16
+ import { useSafeAreaInsets } from 'react-native-safe-area-context'
17
+ import { useTranslation } from 'react-i18next'
18
+
19
+ import PressableScale from '../components/ui/PressableScale'
20
+ import { partitionQueueByGrace } from '../../core/offline/queueGrace'
21
+ import PaymentQrDisplay from '../components/pay/PaymentQrDisplay'
22
+ import UniversalSend from '../components/pay/UniversalSend'
23
+ import RequestHub, { requestSatsFrom, type RequestMethod } from '../components/pay/RequestHub'
24
+ import NearbyFlow from '../components/pay/NearbyFlow'
25
+ import HandleReceive from '../components/pay/HandleReceive'
26
+ import AddressReceive from '../components/pay/AddressReceive'
27
+ import OfflineNotice from '../components/pay/OfflineNotice'
28
+ import { useOnline } from '../hooks/useOnline'
29
+ import { useOfflineNoticeActions } from '../hooks/useOfflineNoticeActions'
30
+ import {
31
+ useTheme,
32
+ spacing,
33
+ typography,
34
+ useWallet,
35
+ validatePeerPayURI,
36
+ type Session,
37
+ takeProofNudge,
38
+ findOfflineActions,
39
+ type OfflineActionRow,
40
+ TaskSendOffline
41
+ } from '@bsv/expo-wallet-toolbox'
42
+ import { getPendingCorruptNotice, readUnprocessedPending } from '../../core/localpay/pending'
43
+ import { nearbyAdvisory } from '../../core/localpay/nearbyAdvisory'
44
+ import { NearbyAdvisoryModal } from '../components/pay/NearbyAdvisoryModal'
45
+
46
+ /**
47
+ * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
48
+ * etc.), one of which reaches expo-font -> expo-asset -- untransformed ESM
49
+ * that Jest cannot parse when eagerly pulled in via the `ui` package barrel.
50
+ * Ionicons is loaded lazily, only when actually rendering, same pattern as
51
+ * this package's other native-module-boundary fixes (expo-router, expo-blur).
52
+ */
53
+ type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
54
+ let ioniconsComponent: IoniconsComponent | undefined
55
+ function loadIonicons(): IoniconsComponent {
56
+ if (!ioniconsComponent) {
57
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
58
+ ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
59
+ }
60
+ return ioniconsComponent
61
+ }
62
+
63
+ /**
64
+ * expo-router is required lazily rather than imported at module scope: this
65
+ * file is barrel-exported from the package's `ui` entry point, and a static
66
+ * top-level `import` of expo-router pulls in its own untransformed JSX
67
+ * source (Navigator.js etc.), which Jest cannot parse for any consumer of the
68
+ * barrel, even one that never navigates. Same pattern as
69
+ * core/context/WalletContext.tsx's and WalletHomeScreen.tsx's lazy
70
+ * expo-router load.
71
+ */
72
+ type ExpoRouterModule = typeof import('expo-router')
73
+ let expoRouterMod: ExpoRouterModule | undefined
74
+ function loadExpoRouter(): ExpoRouterModule {
75
+ if (!expoRouterMod) {
76
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
77
+ expoRouterMod = require('expo-router') as ExpoRouterModule
78
+ }
79
+ return expoRouterMod
80
+ }
81
+
82
+ type Direction = 'pay' | 'get'
83
+
84
+ const firstParam = (v: string | string[] | undefined) => (Array.isArray(v) ? v[0] : v)
85
+
86
+ const METHOD_TITLE_KEYS: Record<RequestMethod, string> = {
87
+ 'get-nearby': 'pay_method_nearby',
88
+ 'get-handle': 'pay_method_remote_link',
89
+ 'get-address': 'pay_method_address'
90
+ }
91
+
92
+ const isRequestMethod = (v: string | undefined): v is RequestMethod =>
93
+ v === 'get-nearby' || v === 'get-handle' || v === 'get-address'
94
+
95
+ export function PayScreen() {
96
+ const { t } = useTranslation()
97
+ const { colors } = useTheme()
98
+ const Ionicons = loadIonicons()
99
+ const { router, useLocalSearchParams } = loadExpoRouter()
100
+ const insets = useSafeAreaInsets()
101
+ const online = useOnline()
102
+ const {
103
+ walletBuilding,
104
+ walletBuilt,
105
+ storage,
106
+ txStatusVersion,
107
+ walletUserId,
108
+ runMonitorTask,
109
+ managers,
110
+ adminOriginator
111
+ } = useWallet()
112
+ const [queued, setQueued] = useState(0)
113
+ const [rejected, setRejected] = useState<OfflineActionRow[]>([])
114
+ const [sentRejected, setSentRejected] = useState<OfflineActionRow[]>([])
115
+ const [queuedSentRows, setQueuedSentRows] = useState<OfflineActionRow[]>([])
116
+ /** When to re-read the queue because a young row will have aged past its grace. */
117
+ const [graceDelay, setGraceDelay] = useState<number | undefined>(undefined)
118
+ const [stalled, setStalled] = useState<string | undefined>(undefined)
119
+ const [pendingCount, setPendingCount] = useState(0)
120
+ const [pendingStuck, setPendingStuck] = useState(0)
121
+ const [pendingCorrupt, setPendingCorrupt] = useState(false)
122
+ const [showCode, setShowCode] = useState<OfflineActionRow | null>(null)
123
+ const [queueNonce, setQueueNonce] = useState(0)
124
+
125
+ const params = useLocalSearchParams<{
126
+ cell?: string | string[]
127
+ direction?: string | string[]
128
+ identityKey?: string | string[]
129
+ sats?: string | string[]
130
+ peerpay?: string | string[]
131
+ }>()
132
+
133
+ const peerpay = firstParam(params.peerpay)
134
+ const peerPayValidation = useMemo(() => (peerpay ? validatePeerPayURI(peerpay) : null), [peerpay])
135
+ const peerPayNotice = useMemo(() => {
136
+ if (!peerPayValidation) return null
137
+ const messages = [peerPayValidation.errors.identityKey, peerPayValidation.errors.sats].filter(Boolean)
138
+ return messages.length ? messages.join('. ') : null
139
+ }, [peerPayValidation])
140
+
141
+ const initialIdentityKey = peerPayValidation?.identityKey ?? firstParam(params.identityKey)
142
+ const satsParam = peerPayValidation?.sats ?? Number(firstParam(params.sats))
143
+ const initialSats = Number.isFinite(satsParam) && satsParam > 0 ? Number(satsParam) : undefined
144
+ // Memoized: useRecipientInput re-adopts initialTarget whenever its identity changes.
145
+ const initialTarget = useMemo(
146
+ () =>
147
+ initialIdentityKey
148
+ ? {
149
+ kind: 'handle' as const,
150
+ identityKey: initialIdentityKey,
151
+ ...(peerPayValidation?.messageBoxUrl ? { messageBoxUrl: peerPayValidation.messageBoxUrl } : {})
152
+ }
153
+ : undefined,
154
+ [initialIdentityKey, peerPayValidation?.messageBoxUrl]
155
+ )
156
+
157
+ const paramCell = firstParam(params.cell)
158
+ // Direction is fixed by how the user got here. A peerpay link is a request
159
+ // to pay; a `get-*` cell or `?direction=get` is the receive side.
160
+ const direction: Direction =
161
+ peerpay || (paramCell ?? '').startsWith('pay')
162
+ ? 'pay'
163
+ : isRequestMethod(paramCell) || firstParam(params.direction) === 'get'
164
+ ? 'get'
165
+ : 'pay'
166
+ /** Pay side: a scanned nearby session takes over the screen. */
167
+ const [nearbySession, setNearbySession] = useState<Session | null>(null)
168
+ /** Get side: the method chosen on the hub, or named by a deep link. */
169
+ const [method, setMethod] = useState<RequestMethod | null>(
170
+ direction === 'get' && isRequestMethod(paramCell) ? paramCell : null
171
+ )
172
+ /** Get side: the hub's raw amount, carried into the method. */
173
+ const [requestSats, setRequestSats] = useState('')
174
+ // One camera raise per deep link; a cancelled advisory must not re-open it.
175
+ const [scanOnMount, setScanOnMount] = useState(paramCell === 'pay-nearby')
176
+
177
+ // ── nearby advisory ─────────────────────────────────────────────────
178
+ /**
179
+ * Nearby pay/get-paid triggers OS-level prompts (iOS Local Network access;
180
+ * Android Bluetooth/nearby-Wi-Fi permissions) as soon as NearbyFlow mounts,
181
+ * with no gesture of its own to explain them. null = not loaded yet (block
182
+ * mounting NearbyFlow, but don't show the modal either — avoids a flash for
183
+ * a returning user whose flag is about to come back true).
184
+ */
185
+ const [nearbyAdvisorySeen, setNearbyAdvisorySeen] = useState<boolean | null>(null)
186
+ useEffect(() => {
187
+ let cancelled = false
188
+ void nearbyAdvisory.get().then(seen => {
189
+ if (!cancelled) setNearbyAdvisorySeen(seen)
190
+ })
191
+ return () => {
192
+ cancelled = true
193
+ }
194
+ }, [])
195
+ const isNearbyCell = (direction === 'pay' && nearbySession !== null) || method === 'get-nearby'
196
+
197
+ // Refreshed whenever the wallet finishes building, connectivity changes, or
198
+ // the user enters/leaves a method or a nearby session: the queue only moves
199
+ // when the network state does or when one of those just queued a row (e.g.
200
+ // an in-session offline QR Done), so there is no need to poll it on every
201
+ // render. It is a cheap local SQLite read, not a network round-trip, so
202
+ // re-running it on every such transition is fine — returning from a method
203
+ // or a nearby session must pick up rows it just queued.
204
+ useEffect(() => {
205
+ if (!walletBuilt) return
206
+ let cancelled = false
207
+ void (async () => {
208
+ try {
209
+ if (storage) {
210
+ try {
211
+ const pending = await readUnprocessedPending(storage)
212
+ setPendingCount(pending.count)
213
+ setPendingStuck(pending.stuck)
214
+ setPendingCorrupt(pending.corrupt)
215
+ } catch {
216
+ setPendingCount(0)
217
+ setPendingStuck(0)
218
+ setPendingCorrupt(getPendingCorruptNotice())
219
+ }
220
+ }
221
+ const db = storage?.sqliteDb
222
+ if (!db) return
223
+ const rows = await findOfflineActions(db, {
224
+ status: ['queued', 'posting', 'rejected'],
225
+ ...(walletUserId === null ? {} : { userId: walletUserId })
226
+ })
227
+ if (cancelled) return
228
+ // Same grace as the wallet screen: online, a payment the drain is about
229
+ // to post is not news, and the banner flashing up for the half second
230
+ // before it lands reads as a fault that is not there.
231
+ const live = partitionQueueByGrace(
232
+ rows.filter(r => r.status !== 'rejected'),
233
+ { online, nowMs: Date.now() }
234
+ )
235
+ setQueued(live.shown.length)
236
+ setGraceDelay(live.nextCheckMs)
237
+ // 'sent'-role rows can be rejected too (a payer's own held payment can be
238
+ // poisoned), but they carry no senderIdentityKey or receivedVia — those
239
+ // are only ever recorded on the receiving side (see
240
+ // storage/StorageExpoSQLite.ts's holdReqsOffline, and
241
+ // utils/localpay/pending.ts's processPending, which backfills them
242
+ // after the fact). Showing one through OfflineNotice's "who handed you
243
+ // this" copy would misreport the user's own failed payment as someone
244
+ // else's fraud against them, so it gets its own unattributed notice.
245
+ setRejected(rows.filter(r => r.status === 'rejected' && r.role === 'received'))
246
+ setSentRejected(rows.filter(r => r.status === 'rejected' && r.role === 'sent'))
247
+ setQueuedSentRows(live.shown.filter(r => r.role === 'sent'))
248
+ setStalled(TaskSendOffline.lastStall)
249
+ } catch {
250
+ // This banner is advisory, never load-bearing. A read failure here must
251
+ // not break the rest of the screen — the send form or hub still has to render.
252
+ }
253
+ })()
254
+ return () => {
255
+ cancelled = true
256
+ }
257
+ }, [walletBuilt, storage, online, txStatusVersion, walletUserId, method, nearbySession, queueNonce])
258
+
259
+ const reloadQueue = useCallback(() => setQueueNonce(n => n + 1), [])
260
+
261
+ // A row that is merely young becomes newsworthy by the passage of time alone.
262
+ useEffect(() => {
263
+ if (graceDelay === undefined) return
264
+ const t = setTimeout(reloadQueue, graceDelay + 100)
265
+ return () => clearTimeout(t)
266
+ }, [graceDelay, reloadQueue])
267
+ const pushPay = useCallback((sats?: number) => {
268
+ const { router: r } = loadExpoRouter()
269
+ if (typeof r.setParams === 'function') {
270
+ r.setParams(sats && sats > 0 ? { sats: String(sats) } : { sats: undefined })
271
+ return
272
+ }
273
+ r.push(sats && sats > 0 ? `/pay?sats=${sats}` : '/pay')
274
+ }, [])
275
+ const { onRequestAgain, onCopyDetails, onDismiss, onSendAgain } = useOfflineNoticeActions({
276
+ storage,
277
+ permissionsManager: managers?.permissionsManager,
278
+ adminOriginator: adminOriginator ?? '',
279
+ online,
280
+ rejected,
281
+ t,
282
+ reload: reloadQueue,
283
+ pushPay
284
+ })
285
+
286
+ // Auth failed while this screen was open (the wallet finished building and
287
+ // there is no wallet) — same guard the old payments screen carried.
288
+ const prevBuilding = React.useRef(walletBuilding)
289
+ useEffect(() => {
290
+ const wasBuilding = prevBuilding.current
291
+ prevBuilding.current = walletBuilding
292
+ if (wasBuilding && !walletBuilding && !walletBuilt) {
293
+ if (router.canGoBack()) router.back()
294
+ else router.replace('/')
295
+ }
296
+ }, [walletBuilding, walletBuilt])
297
+
298
+ // One deferred proof sweep per visit (10-min gated): see utils/pay/proofNudge.ts.
299
+ useEffect(() => {
300
+ if (!online) return
301
+ const task = InteractionManager.runAfterInteractions(() => {
302
+ if (!takeProofNudge(Date.now())) return
303
+ runMonitorTask('CheckForProofs').catch(() => {
304
+ // Best-effort by design: a failed sweep leaves the 2h background
305
+ // trigger as the backstop, and must never surface on this screen.
306
+ })
307
+ })
308
+ return () => task.cancel()
309
+ }, [online, runMonitorTask])
310
+
311
+ /**
312
+ * Back from anywhere on this screen means "back to the wallet" — never to
313
+ * an intermediate screen. The hub or the send form is a decision the user
314
+ * already made on the way in; stepping back through it makes leaving a
315
+ * two- or three-tap affair.
316
+ *
317
+ * `dismissTo` pops to the wallet when it is in the stack (the normal case)
318
+ * and replaces this screen with it when /pay was deep-linked into directly.
319
+ * Not `navigate`: that re-pushes the wallet above the very screens this is
320
+ * trying to leave behind, which puts them one edge-swipe away instead of
321
+ * discarding them.
322
+ */
323
+ const goBack = useCallback(() => {
324
+ router.dismissTo('/')
325
+ }, [])
326
+
327
+ const onNearbySession = useCallback((session: Session) => {
328
+ // One camera raise per deep link; a cancelled advisory must not re-open it.
329
+ setScanOnMount(false)
330
+ setNearbySession(session)
331
+ }, [])
332
+
333
+ const offlineNotice = (
334
+ <View style={styles.noticeWrap}>
335
+ <OfflineNotice
336
+ online={online}
337
+ queued={queued}
338
+ rejected={rejected}
339
+ sentRejected={sentRejected}
340
+ onSendNow={() => TaskSendOffline.requestNow()}
341
+ stalled={stalled}
342
+ pendingCount={pendingCount}
343
+ pendingStuck={pendingStuck}
344
+ pendingCorrupt={pendingCorrupt}
345
+ queuedSent={queuedSentRows}
346
+ onShowCode={setShowCode}
347
+ onRequestAgain={row => void onRequestAgain(row)}
348
+ onCopyDetails={onCopyDetails}
349
+ onDismiss={row => void onDismiss(row)}
350
+ onSendAgain={row => void onSendAgain(row)}
351
+ />
352
+ </View>
353
+ )
354
+
355
+ const body = () => {
356
+ if (direction === 'pay') {
357
+ if (nearbySession) {
358
+ return nearbyAdvisorySeen ? <NearbyFlow role="payer" initialSession={nearbySession} onExit={goBack} /> : null
359
+ }
360
+ return (
361
+ <>
362
+ {offlineNotice}
363
+ <UniversalSend
364
+ initialTarget={initialTarget}
365
+ initialSats={initialSats}
366
+ initialNotice={peerPayNotice}
367
+ openScannerOnMount={scanOnMount}
368
+ onNearbySession={onNearbySession}
369
+ />
370
+ </>
371
+ )
372
+ }
373
+ const sats = requestSatsFrom(requestSats)
374
+ switch (method) {
375
+ case 'get-nearby':
376
+ return nearbyAdvisorySeen ? <NearbyFlow role="payee" initialRequest={{ sats }} onExit={goBack} /> : null
377
+ case 'get-handle':
378
+ return <HandleReceive initialSats={sats} />
379
+ case 'get-address':
380
+ return <AddressReceive initialSats={sats} />
381
+ default:
382
+ return (
383
+ <>
384
+ {offlineNotice}
385
+ <RequestHub
386
+ requestSats={requestSats}
387
+ onChangeRequestSats={setRequestSats}
388
+ onPick={setMethod}
389
+ online={online}
390
+ />
391
+ </>
392
+ )
393
+ }
394
+ }
395
+
396
+ return (
397
+ <View style={[styles.container, { backgroundColor: colors.backgroundSecondary, paddingTop: insets.top }]}>
398
+ <View style={[styles.header, { borderBottomColor: colors.separator }]}>
399
+ <PressableScale
400
+ onPress={goBack}
401
+ haptic="tap"
402
+ style={styles.headerBtn}
403
+ accessibilityRole="button"
404
+ accessibilityLabel={t('go_back')}
405
+ >
406
+ <Ionicons
407
+ name={I18nManager.isRTL ? 'chevron-forward' : 'chevron-back'}
408
+ size={24}
409
+ color={colors.textSecondary}
410
+ />
411
+ </PressableScale>
412
+ <Text style={[styles.headerTitle, { color: colors.textPrimary }]} numberOfLines={1}>
413
+ {/* The screen names what it is doing: the direction, or the rail/method once one is live. */}
414
+ {direction === 'pay'
415
+ ? t(nearbySession ? 'pay_cell_nearby_pay' : 'pay_direction_pay')
416
+ : t(method ? METHOD_TITLE_KEYS[method] : 'local_pay_request')}
417
+ </Text>
418
+ <View style={styles.headerBtn} />
419
+ </View>
420
+ {/* Both entry screens are forms now; the hub's rows carry their own elevation. */}
421
+ <View style={[styles.bodyWrap, { backgroundColor: colors.background }]}>{body()}</View>
422
+ <Modal visible={!!showCode} animationType="slide" transparent onRequestClose={() => setShowCode(null)}>
423
+ <View style={styles.codeOverlay}>
424
+ <View style={[styles.codeCard, { backgroundColor: colors.backgroundElevated }]}>
425
+ {showCode?.framePayload ? (
426
+ <PaymentQrDisplay frameQr={showCode.framePayload} size={288} />
427
+ ) : (
428
+ <Text style={{ color: colors.textSecondary }}>{t('local_pay_too_large')}</Text>
429
+ )}
430
+ <TouchableOpacity onPress={() => setShowCode(null)} style={styles.codeClose}>
431
+ <Text style={{ color: colors.info }}>{t('done')}</Text>
432
+ </TouchableOpacity>
433
+ </View>
434
+ </View>
435
+ </Modal>
436
+ <NearbyAdvisoryModal
437
+ visible={isNearbyCell && nearbyAdvisorySeen === false}
438
+ onCancel={() => {
439
+ // Whichever side raised it, cancelling leaves no nearby state behind.
440
+ setNearbySession(null)
441
+ setMethod(null)
442
+ }}
443
+ onContinue={() => {
444
+ void nearbyAdvisory.set()
445
+ setNearbyAdvisorySeen(true)
446
+ }}
447
+ />
448
+ </View>
449
+ )
450
+ }
451
+
452
+ const styles = StyleSheet.create({
453
+ container: { flex: 1 },
454
+ header: {
455
+ flexDirection: 'row',
456
+ alignItems: 'center',
457
+ justifyContent: 'space-between',
458
+ paddingHorizontal: spacing.sm,
459
+ paddingVertical: spacing.md,
460
+ borderBottomWidth: StyleSheet.hairlineWidth
461
+ },
462
+ headerBtn: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center' },
463
+ headerTitle: { ...typography.headline, fontWeight: '600', flex: 1, textAlign: 'center' },
464
+ bodyWrap: { flex: 1 },
465
+ noticeWrap: { paddingHorizontal: spacing.lg },
466
+ codeOverlay: {
467
+ flex: 1,
468
+ alignItems: 'center',
469
+ justifyContent: 'center',
470
+ backgroundColor: 'rgba(0,0,0,0.5)'
471
+ },
472
+ codeCard: {
473
+ padding: spacing.xl,
474
+ borderRadius: 16,
475
+ alignItems: 'center',
476
+ gap: spacing.lg
477
+ },
478
+ codeClose: { padding: spacing.md }
479
+ })
@@ -0,0 +1,180 @@
1
+ import React, { useState, useEffect, useCallback } from 'react'
2
+ import { View, Text, ScrollView, StyleSheet } from 'react-native'
3
+ import { useTranslation } from 'react-i18next'
4
+ import { useTheme, spacing, typography, useWallet } from '@bsv/expo-wallet-toolbox'
5
+ import { GroupedSection } from '../components/ui/GroupedList'
6
+ import { ListRow } from '../components/ui/ListRow'
7
+ import AmountDisplay from '../components/wallet/AmountDisplay'
8
+ import { sdk } from '@bsv/wallet-toolbox-mobile'
9
+ import AsyncStorage from '@react-native-async-storage/async-storage'
10
+
11
+ /**
12
+ * expo-router is required lazily rather than imported at module scope: this
13
+ * file is barrel-exported from the package's `ui` entry point, and a static
14
+ * top-level `import` of expo-router pulls in its own untransformed JSX
15
+ * source (Navigator.js etc.), which Jest cannot parse for any consumer of the
16
+ * barrel, even one that never navigates. Same pattern as
17
+ * WalletHomeScreen.tsx's/PayScreen.tsx's lazy expo-router load.
18
+ */
19
+ type ExpoRouterModule = typeof import('expo-router')
20
+ let expoRouterMod: ExpoRouterModule | undefined
21
+ function loadExpoRouter(): ExpoRouterModule {
22
+ if (!expoRouterMod) {
23
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
24
+ expoRouterMod = require('expo-router') as ExpoRouterModule
25
+ }
26
+ return expoRouterMod
27
+ }
28
+
29
+ const CACHE_DURATION = 30000
30
+
31
+ export function SettingsScreen() {
32
+ const { t } = useTranslation()
33
+ const { colors } = useTheme()
34
+ const { router } = loadExpoRouter()
35
+ const { managers, adminOriginator, selectedNetwork, txStatusVersion } = useWallet()
36
+
37
+ const balanceCacheKey = `cached_wallet_balance_${selectedNetwork}`
38
+ const balanceCacheTimestampKey = `cached_wallet_balance_ts_${selectedNetwork}`
39
+ const [accountBalance, setAccountBalance] = useState<number | null>(null)
40
+ const [balanceLoading, setBalanceLoading] = useState(false)
41
+
42
+ // Fetch wallet balance — keep last known value visible during network switch
43
+ const refreshBalance = useCallback(async () => {
44
+ if (!managers.permissionsManager) return
45
+ try {
46
+ const { totalOutputs } = await managers.permissionsManager.listOutputs(
47
+ { basket: sdk.specOpWalletBalance },
48
+ adminOriginator
49
+ )
50
+ const total = totalOutputs ?? 0
51
+ setAccountBalance(total)
52
+ setBalanceLoading(false)
53
+ await Promise.all([
54
+ AsyncStorage.setItem(balanceCacheKey, String(total)),
55
+ AsyncStorage.setItem(balanceCacheTimestampKey, String(Date.now()))
56
+ ])
57
+ } catch (e) {
58
+ console.error('Error refreshing balance:', e)
59
+ setBalanceLoading(false)
60
+ }
61
+ }, [managers, adminOriginator, balanceCacheKey, balanceCacheTimestampKey])
62
+
63
+ useEffect(() => {
64
+ if (!managers.permissionsManager) {
65
+ setAccountBalance(null)
66
+ return
67
+ }
68
+
69
+ let cancelled = false
70
+ ;(async () => {
71
+ const [cached, ts] = await Promise.all([
72
+ AsyncStorage.getItem(balanceCacheKey),
73
+ AsyncStorage.getItem(balanceCacheTimestampKey)
74
+ ])
75
+ if (cancelled) return
76
+ if (cached !== null) {
77
+ setAccountBalance(Number(cached))
78
+ if (!ts || Date.now() - Number(ts) > CACHE_DURATION) {
79
+ setBalanceLoading(true)
80
+ refreshBalance()
81
+ }
82
+ } else {
83
+ setBalanceLoading(true)
84
+ refreshBalance()
85
+ }
86
+ })()
87
+ return () => {
88
+ cancelled = true
89
+ }
90
+ }, [managers.permissionsManager, refreshBalance, balanceCacheKey, balanceCacheTimestampKey])
91
+
92
+ // Re-fetch whenever a transaction lands (deposit, withdrawal, anything that
93
+ // bumps txStatusVersion) instead of waiting out the cache TTL — skip the
94
+ // initial mount, which the effect above already covers.
95
+ const mountedRef = React.useRef(false)
96
+ useEffect(() => {
97
+ if (!mountedRef.current) {
98
+ mountedRef.current = true
99
+ return
100
+ }
101
+ refreshBalance()
102
+ }, [txStatusVersion, refreshBalance])
103
+
104
+ return (
105
+ <View style={{ backgroundColor: colors.backgroundSecondary }}>
106
+ <ScrollView contentContainerStyle={{ paddingBottom: spacing.xxxl }}>
107
+ {/* ── Balance ── */}
108
+ <View style={localStyles.balanceContainer}>
109
+ <Text style={[localStyles.balanceLabel, { color: colors.textSecondary }]}>{t('you_have')}</Text>
110
+ <Text
111
+ onPress={refreshBalance}
112
+ style={[localStyles.balanceAmount, { color: colors.textPrimary, opacity: balanceLoading ? 0.4 : 1 }]}
113
+ >
114
+ {accountBalance !== null ? <AmountDisplay abbreviate>{accountBalance}</AmountDisplay> : '...'}
115
+ </Text>
116
+ </View>
117
+
118
+ {/* ── Activity ── */}
119
+ <GroupedSection header={t('activity')}>
120
+ <ListRow
121
+ label={t('transactions')}
122
+ icon="receipt-outline"
123
+ iconColor="#32ADE6"
124
+ onPress={() => router.push('/transactions')}
125
+ />
126
+ {/* One row for every money path. Direction and counterparty are chosen
127
+ inside /pay, where the transport is inferred rather than picked —
128
+ which is why four rows (and the identity-key QR, now Get paid →
129
+ handle) collapse into this one. */}
130
+ <ListRow
131
+ label={t('payments')}
132
+ icon="swap-horizontal-outline"
133
+ iconColor={colors.success}
134
+ onPress={() => router.push('/pay')}
135
+ />
136
+ <ListRow
137
+ label={t('vault_row_title')}
138
+ icon="safe"
139
+ iconFamily="material-community"
140
+ iconColor="#30B0C7"
141
+ onPress={() => router.push('/vault' as any)}
142
+ isLast
143
+ />
144
+ </GroupedSection>
145
+
146
+ {/* ── Settings drill-down ── */}
147
+ <GroupedSection>
148
+ <ListRow
149
+ label={t('settings')}
150
+ icon="settings-outline"
151
+ iconColor="#636366"
152
+ onPress={() => router.push('/wallet-config')}
153
+ isLast
154
+ />
155
+ </GroupedSection>
156
+ </ScrollView>
157
+ </View>
158
+ )
159
+ }
160
+
161
+ const localStyles = StyleSheet.create({
162
+ /* ── Balance ── */
163
+ balanceContainer: {
164
+ alignItems: 'center',
165
+ justifyContent: 'center',
166
+ height: 100,
167
+ paddingHorizontal: spacing.lg
168
+ },
169
+ balanceLabel: {
170
+ ...typography.subhead,
171
+ marginBottom: spacing.xs
172
+ },
173
+ balanceAmount: {
174
+ fontSize: 34,
175
+ fontWeight: '700',
176
+ letterSpacing: 0.4,
177
+ minHeight: 42,
178
+ lineHeight: 42
179
+ }
180
+ })