@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,93 @@
1
+ /**
2
+ * Shown only before any wallet exists on this device (a true fresh install,
3
+ * prior to the first Pay/Get Paid tap that lazily creates one — see
4
+ * WalletHomeScreen's destinationPress/ensureWalletExists). Gives a returning
5
+ * user with an existing recovery key a way in without first tripping the
6
+ * biometric-advisory/auto-create path meant for brand-new wallets.
7
+ *
8
+ * Sticky at the bottom of the screen, and non-blocking like
9
+ * BackupReminderSheet: no backdrop, no Modal, the rest of the screen
10
+ * (including Pay/Get Paid) stays interactive underneath it
11
+ * (pointerEvents="box-none" on the wrapper).
12
+ */
13
+ import React from 'react'
14
+ import { StyleSheet, Text, View } from 'react-native'
15
+ import { useSafeAreaInsets } from 'react-native-safe-area-context'
16
+ import { useTheme, spacing, radii, typography, i18n } from '@bsv/expo-wallet-toolbox'
17
+ import PressableScale from '../ui/PressableScale'
18
+
19
+ const t = (k: string, o?: Record<string, unknown>) => i18n.t(k, o) as string
20
+
21
+ type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
22
+ let ioniconsComponent: IoniconsComponent | undefined
23
+ function loadIonicons(): IoniconsComponent {
24
+ if (!ioniconsComponent) {
25
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
26
+ ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
27
+ }
28
+ return ioniconsComponent
29
+ }
30
+
31
+ export const ImportFromBackupPrompt: React.FC<{
32
+ visible: boolean
33
+ onImport: () => void
34
+ }> = ({ visible, onImport }) => {
35
+ const { colors } = useTheme()
36
+ const Ionicons = loadIonicons()
37
+ const insets = useSafeAreaInsets()
38
+
39
+ if (!visible) return null
40
+
41
+ return (
42
+ <View style={[styles.wrapper, { paddingBottom: insets.bottom + spacing.md }]} pointerEvents="box-none">
43
+ <View style={[styles.card, { backgroundColor: colors.sheetBackground, borderColor: colors.separator }]}>
44
+ <Ionicons name="download-outline" size={22} color={colors.accent} style={styles.icon} />
45
+ <View style={styles.textGroup}>
46
+ <Text style={[styles.title, { color: colors.textPrimary }]}>{t('import_prompt_title')}</Text>
47
+ <Text style={[styles.body, { color: colors.textSecondary }]}>{t('import_prompt_body')}</Text>
48
+ </View>
49
+ <PressableScale haptic="tap" onPress={onImport} style={[styles.button, { borderColor: colors.accent }]}>
50
+ <Text style={[styles.buttonLabel, { color: colors.accent }]}>{t('import_prompt_action')}</Text>
51
+ </PressableScale>
52
+ </View>
53
+ </View>
54
+ )
55
+ }
56
+
57
+ const styles = StyleSheet.create({
58
+ wrapper: {
59
+ position: 'absolute',
60
+ left: 0,
61
+ right: 0,
62
+ bottom: 0,
63
+ zIndex: 30,
64
+ alignItems: 'center',
65
+ paddingHorizontal: spacing.lg
66
+ },
67
+ card: {
68
+ width: '100%',
69
+ maxWidth: 380,
70
+ borderRadius: radii.lg,
71
+ borderWidth: StyleSheet.hairlineWidth,
72
+ padding: spacing.lg,
73
+ alignItems: 'center',
74
+ gap: spacing.sm,
75
+ shadowColor: '#000',
76
+ shadowOffset: { width: 0, height: 4 },
77
+ shadowOpacity: 0.15,
78
+ shadowRadius: 12,
79
+ elevation: 6
80
+ },
81
+ icon: { marginBottom: spacing.xs },
82
+ textGroup: { alignItems: 'center', gap: 2 },
83
+ title: { ...typography.subhead, fontWeight: '600', textAlign: 'center' },
84
+ body: { ...typography.footnote, textAlign: 'center' },
85
+ button: {
86
+ marginTop: spacing.xs,
87
+ paddingVertical: spacing.sm,
88
+ paddingHorizontal: spacing.lg,
89
+ borderRadius: radii.pill,
90
+ borderWidth: StyleSheet.hairlineWidth
91
+ },
92
+ buttonLabel: { ...typography.subhead, fontWeight: '600' }
93
+ })
@@ -0,0 +1,122 @@
1
+ import { Platform } from 'react-native'
2
+ import { type StorageExpoSQLite, parseDbFilename } from '@bsv/expo-wallet-toolbox'
3
+
4
+ /**
5
+ * expo-file-system and expo-sharing both ship untransformed ESM/raw-TS
6
+ * entry points that Jest cannot parse when eagerly pulled in via the `ui`
7
+ * package barrel, so both are required lazily here rather than imported at
8
+ * module scope — same pattern as this package's other native-module-boundary
9
+ * fixes (expo-router, expo-blur, ui/exportTransactions.ts's expo-file-system
10
+ * use).
11
+ */
12
+ function loadExpoFileSystem(): typeof import('expo-file-system') {
13
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
14
+ return require('expo-file-system') as typeof import('expo-file-system')
15
+ }
16
+ function loadExpoSharing(): typeof import('expo-sharing') {
17
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
18
+ return require('expo-sharing') as typeof import('expo-sharing')
19
+ }
20
+
21
+ /**
22
+ * Build an export filename with the current timestamp.
23
+ *
24
+ * Strips any existing timestamp from the source DB name and replaces it with
25
+ * the current time (Unix seconds). This ensures each export produces a
26
+ * uniquely identifiable snapshot.
27
+ *
28
+ * Examples:
29
+ * wallet-a1b2c3d4-mainnet.db → wallet-a1b2c3d4-mainnet-1741305600.db
30
+ * wallet-a1b2c3d4-mainnet-1700000.db → wallet-a1b2c3d4-mainnet-1741305600.db
31
+ */
32
+ function exportFilename(dbName: string): string {
33
+ const parsed = parseDbFilename(dbName)
34
+ const ts = Math.floor(Date.now() / 1000)
35
+ if (parsed) {
36
+ return `wallet-${parsed.keySuffix}-${parsed.chain}net-${ts}.db`
37
+ }
38
+ // Fallback: strip .db, append timestamp
39
+ return dbName.replace(/\.db$/, `-${ts}.db`)
40
+ }
41
+
42
+ /**
43
+ * Exports the currently active wallet database as a timestamped `.db` file
44
+ * and presents the OS share dialogue so the user can save or send it.
45
+ *
46
+ * On iOS the file is copied from disk; on Android `serializeAsync` is used
47
+ * to avoid filesystem permission issues with the native database directory.
48
+ *
49
+ * Returns the number of database files exported (0 or 1).
50
+ */
51
+ export async function exportAllWalletDatabases(storage: StorageExpoSQLite | null): Promise<number> {
52
+ if (Platform.OS === 'android') {
53
+ return exportAndroid(storage)
54
+ }
55
+
56
+ return exportIOS(storage)
57
+ }
58
+
59
+ async function exportIOS(storage: StorageExpoSQLite | null): Promise<number> {
60
+ if (!storage?.db?.databasePath) return 0
61
+
62
+ const { File, Directory, Paths } = loadExpoFileSystem()
63
+ const { shareAsync } = loadExpoSharing()
64
+
65
+ const dbPath = storage.db.databasePath
66
+ const sourceFile = new File(dbPath)
67
+ if (!sourceFile.exists) return 0
68
+
69
+ // The database runs in WAL mode: commits sit in the -wal sidecar until a
70
+ // checkpoint, and a byte copy of the .db alone would silently omit them.
71
+ await storage.checkpointWal()
72
+
73
+ const outName = exportFilename(storage.dbName)
74
+ const tempDir = new Directory(Paths.cache, 'bsv-wallet-export')
75
+ if (tempDir.exists) tempDir.delete()
76
+ tempDir.create({ intermediates: true })
77
+
78
+ try {
79
+ sourceFile.copy(new File(tempDir, outName))
80
+ await shareAsync(new File(tempDir, outName).uri, {
81
+ mimeType: 'application/octet-stream',
82
+ dialogTitle: outName
83
+ })
84
+ } finally {
85
+ try {
86
+ tempDir.delete()
87
+ } catch {}
88
+ }
89
+
90
+ return 1
91
+ }
92
+
93
+ async function exportAndroid(storage: StorageExpoSQLite | null): Promise<number> {
94
+ if (!storage?.db) return 0
95
+
96
+ const { File, Directory, Paths } = loadExpoFileSystem()
97
+ const { shareAsync } = loadExpoSharing()
98
+
99
+ const outName = exportFilename(storage.dbName)
100
+ const tempDir = new Directory(Paths.cache, 'bsv-wallet-export')
101
+ if (tempDir.exists) tempDir.delete()
102
+ tempDir.create({ intermediates: true })
103
+
104
+ try {
105
+ // serializeAsync dumps the live database to bytes — no file-system
106
+ // permission issues accessing the native database directory.
107
+ const bytes = await storage.db.serializeAsync()
108
+ const outFile = new File(tempDir, outName)
109
+ outFile.write(bytes)
110
+
111
+ await shareAsync(outFile.uri, {
112
+ mimeType: 'application/octet-stream',
113
+ dialogTitle: outName
114
+ })
115
+ } finally {
116
+ try {
117
+ tempDir.delete()
118
+ } catch {}
119
+ }
120
+
121
+ return 1
122
+ }
@@ -0,0 +1,129 @@
1
+ import type { WalletInterface, WalletAction } from '@bsv/sdk'
2
+ import type { StorageExpoSQLite } from '@bsv/expo-wallet-toolbox'
3
+
4
+ /**
5
+ * expo-file-system and expo-sharing both ship untransformed ESM/raw-TS
6
+ * entry points that Jest cannot parse when eagerly pulled in via the `ui`
7
+ * package barrel, so both are required lazily here rather than imported at
8
+ * module scope — same pattern as this package's other native-module-boundary
9
+ * fixes (expo-router, expo-blur, core/headers/fs.ts's expo-file-system use).
10
+ */
11
+ function loadExpoFileSystem(): typeof import('expo-file-system') {
12
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
13
+ return require('expo-file-system') as typeof import('expo-file-system')
14
+ }
15
+ function loadExpoSharing(): typeof import('expo-sharing') {
16
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
17
+ return require('expo-sharing') as typeof import('expo-sharing')
18
+ }
19
+
20
+ const PAGE = 200
21
+
22
+ function csvEscape(v: unknown): string {
23
+ if (v == null) return ''
24
+ const s = String(v)
25
+ if (/[",\n\r]/.test(s)) return `"${s.replace(/"/g, '""')}"`
26
+ return s
27
+ }
28
+
29
+ /**
30
+ * Exports all wallet transactions as a CSV file via the OS share dialog.
31
+ * Columns: txid, satoshis (signed), description, status, blockHeight,
32
+ * tags (semi-colon), labels (semi-colon), outputDescriptions (semi-colon).
33
+ *
34
+ * Returns the number of rows exported.
35
+ */
36
+ export async function exportTransactionsAsCsv(
37
+ wallet: WalletInterface,
38
+ storage: StorageExpoSQLite | null,
39
+ adminOriginator: string
40
+ ): Promise<number> {
41
+ const actions: WalletAction[] = []
42
+ let offset = 0
43
+ let total = Infinity
44
+ while (offset < total) {
45
+ const r = await wallet.listActions(
46
+ {
47
+ labels: [],
48
+ includeLabels: true,
49
+ includeOutputs: true,
50
+ limit: PAGE,
51
+ offset
52
+ },
53
+ adminOriginator
54
+ )
55
+ total = r.totalActions
56
+ if (r.actions.length === 0) break
57
+ actions.push(...r.actions)
58
+ offset += r.actions.length
59
+ }
60
+
61
+ if (actions.length === 0) return 0
62
+
63
+ // Two columns, read as two columns. findProvenTxs({ partial: {} }) would
64
+ // SELECT * over every proven transaction, expanding each rawTx and merklePath
65
+ // into a JS array on the way to being ignored.
66
+ const heightMap = storage ? await storage.getProvenTxHeights() : new Map<string, number>()
67
+
68
+ const header = [
69
+ 'txid',
70
+ 'satoshis',
71
+ 'description',
72
+ 'status',
73
+ 'blockHeight',
74
+ 'tags',
75
+ 'labels',
76
+ 'outputDescriptions'
77
+ ].join(',')
78
+
79
+ const rows = actions.map(a => {
80
+ const sats = a.isOutgoing ? -Math.abs(a.satoshis) : Math.abs(a.satoshis)
81
+ const outputs = a.outputs || []
82
+ const tagsSet = new Set<string>()
83
+ for (const o of outputs) for (const t of (o as any).tags || []) tagsSet.add(t)
84
+ const tags = Array.from(tagsSet).join(';')
85
+ const labels = (a.labels || []).join(';')
86
+ const outDescs = outputs
87
+ .map((o: any) => o.outputDescription)
88
+ .filter((d: string) => d && d.length > 0)
89
+ .join(';')
90
+ const height = heightMap.get(a.txid) ?? ''
91
+ return [
92
+ csvEscape(a.txid),
93
+ csvEscape(sats),
94
+ csvEscape(a.description),
95
+ csvEscape(a.status),
96
+ csvEscape(height),
97
+ csvEscape(tags),
98
+ csvEscape(labels),
99
+ csvEscape(outDescs)
100
+ ].join(',')
101
+ })
102
+
103
+ const csv = [header, ...rows].join('\n') + '\n'
104
+
105
+ const { Directory, File, Paths } = loadExpoFileSystem()
106
+ const { shareAsync } = loadExpoSharing()
107
+
108
+ const ts = Math.floor(Date.now() / 1000)
109
+ const outName = `bsv-transactions-${ts}.csv`
110
+ const tempDir = new Directory(Paths.cache, 'bsv-tx-export')
111
+ if (tempDir.exists) tempDir.delete()
112
+ tempDir.create({ intermediates: true })
113
+
114
+ try {
115
+ const outFile = new File(tempDir, outName)
116
+ outFile.write(csv)
117
+ await shareAsync(outFile.uri, {
118
+ mimeType: 'text/csv',
119
+ dialogTitle: outName,
120
+ UTI: 'public.comma-separated-values-text'
121
+ })
122
+ } finally {
123
+ try {
124
+ tempDir.delete()
125
+ } catch {}
126
+ }
127
+
128
+ return actions.length
129
+ }
@@ -0,0 +1,136 @@
1
+ import { useCallback, useEffect, useRef } from 'react'
2
+ import AsyncStorage from '@react-native-async-storage/async-storage'
3
+ import { PeerPayClient } from '@bsv/message-box-client'
4
+ import {
5
+ DEFAULT_MESSAGE_BOX_URL,
6
+ LEGACY_MESSAGE_BOX_URL,
7
+ MESSAGE_BOX_URL_KEY,
8
+ NO_MESSAGE_BOX
9
+ } from '@bsv/expo-wallet-toolbox'
10
+ import { nackRejectedReceived, sendBouncedOfflineNack } from '../../core/peerpay/offlineNacks'
11
+ import { updateOfflineAction, type OfflineActionRow } from '../../core/storage/methods/offlineActions'
12
+ import type { StorageExpoSQLite } from '../../core/storage/StorageExpoSQLite'
13
+ import { showToast } from '../components/ui/Toast'
14
+ import { offlineActionDetails } from '../components/pay/OfflineNotice'
15
+
16
+ async function readMessageBoxUrl(): Promise<string | undefined> {
17
+ const saved = await AsyncStorage.getItem(MESSAGE_BOX_URL_KEY)
18
+ if (saved === NO_MESSAGE_BOX) return undefined
19
+ if (!saved || saved === LEGACY_MESSAGE_BOX_URL) return DEFAULT_MESSAGE_BOX_URL
20
+ return saved
21
+ }
22
+
23
+ type ClipboardModule = typeof import('@react-native-clipboard/clipboard').default
24
+ let clipboardModule: ClipboardModule | undefined
25
+ function loadClipboard(): ClipboardModule {
26
+ if (!clipboardModule) {
27
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
28
+ clipboardModule = require('@react-native-clipboard/clipboard').default as ClipboardModule
29
+ }
30
+ return clipboardModule
31
+ }
32
+
33
+ type WalletClient = ConstructorParameters<typeof PeerPayClient>[0]['walletClient']
34
+
35
+ export function useOfflineNoticeActions(args: {
36
+ storage: StorageExpoSQLite | null | undefined
37
+ permissionsManager: unknown
38
+ adminOriginator: string
39
+ online: boolean
40
+ rejected: OfflineActionRow[]
41
+ t: (key: string, options?: Record<string, unknown>) => string
42
+ reload: () => void
43
+ pushPay: (sats?: number) => void
44
+ }) {
45
+ const { storage, permissionsManager, adminOriginator, online, rejected, t, reload, pushPay } = args
46
+ const rejectedRef = useRef(rejected)
47
+ rejectedRef.current = rejected
48
+
49
+ const makeClient = useCallback(async () => {
50
+ const pm = permissionsManager
51
+ if (!pm) return undefined
52
+ const url = await readMessageBoxUrl()
53
+ if (!url) return undefined
54
+ return new PeerPayClient({
55
+ messageBoxHost: url,
56
+ walletClient: pm as WalletClient,
57
+ originator: adminOriginator
58
+ })
59
+ }, [permissionsManager, adminOriginator])
60
+
61
+ useEffect(() => {
62
+ if (!online || !storage || rejected.length === 0) return
63
+ let cancelled = false
64
+ void (async () => {
65
+ const client = await makeClient()
66
+ if (!client || cancelled) return
67
+ await nackRejectedReceived({ client, storage, rows: rejectedRef.current })
68
+ })()
69
+ return () => {
70
+ cancelled = true
71
+ }
72
+ }, [online, storage, makeClient, rejected])
73
+
74
+ const onRequestAgain = useCallback(
75
+ async (row: OfflineActionRow) => {
76
+ if (!row.senderIdentityKey || !storage) return
77
+ try {
78
+ const client = await makeClient()
79
+ if (!client) {
80
+ showToast(t('message_box_unreachable'), { type: 'error' })
81
+ return
82
+ }
83
+ await sendBouncedOfflineNack({
84
+ client,
85
+ storage,
86
+ txid: row.txid,
87
+ recipient: row.senderIdentityKey,
88
+ force: true
89
+ })
90
+ showToast(t('payment_bounced_resend'), { type: 'success' })
91
+ } catch (e: unknown) {
92
+ const message = e instanceof Error ? e.message : t('unknown_error')
93
+ showToast(message, { type: 'error' })
94
+ }
95
+ },
96
+ [makeClient, storage, t]
97
+ )
98
+
99
+ const onCopyDetails = useCallback((row: OfflineActionRow) => {
100
+ loadClipboard().setString(offlineActionDetails(row))
101
+ showToast(t('copied'), { type: 'success' })
102
+ }, [t])
103
+
104
+ const onDismiss = useCallback(
105
+ async (row: OfflineActionRow) => {
106
+ const db = storage?.sqliteDb
107
+ if (!db) return
108
+ try {
109
+ await updateOfflineAction(db, row.txid, { status: 'acknowledged' })
110
+ showToast(t('dismiss_rejected_payment'), { type: 'success' })
111
+ reload()
112
+ } catch (e: unknown) {
113
+ const message = e instanceof Error ? e.message : t('unknown_error')
114
+ showToast(message, { type: 'error' })
115
+ }
116
+ },
117
+ [storage, t, reload]
118
+ )
119
+
120
+ const onSendAgain = useCallback(
121
+ async (row: OfflineActionRow) => {
122
+ let sats: number | undefined
123
+ try {
124
+ const txs = storage ? await storage.findTransactions({ partial: { txid: row.txid }, noRawTx: true }) : []
125
+ const raw = txs[0]?.satoshis
126
+ if (typeof raw === 'number' && Number.isFinite(raw) && raw !== 0) sats = Math.abs(raw)
127
+ } catch {
128
+ // Prefill without an amount rather than blocking Send again.
129
+ }
130
+ pushPay(sats)
131
+ },
132
+ [storage, pushPay]
133
+ )
134
+
135
+ return { onRequestAgain, onCopyDetails, onDismiss, onSendAgain }
136
+ }
@@ -0,0 +1,70 @@
1
+ import { useEffect, useRef, useState } from 'react'
2
+ import { getOnline, subscribeOnline } from '@bsv/expo-wallet-toolbox'
3
+
4
+ /**
5
+ * How long a device must keep reporting offline before the UI says so.
6
+ *
7
+ * Connectivity flaps: NetInfo emits during handovers, on waking, and while a
8
+ * native probe is still settling, and the first of those emissions can arrive
9
+ * before there is anything to report. Announcing each one puts an offline
10
+ * banner in front of someone who has signal — the app claiming a state it has
11
+ * not established. Going back online is not delayed: good news is never in
12
+ * doubt, so it applies on the spot.
13
+ */
14
+ export const OFFLINE_CONFIRM_MS = 2500
15
+
16
+ /**
17
+ * Starts optimistic. A first render that wrongly says "online" costs a failed
18
+ * request; a first render that wrongly says "offline" hides the online payment
19
+ * rails from a user who has signal, which is worse.
20
+ */
21
+ export function useOnline(confirmMs: number = OFFLINE_CONFIRM_MS): boolean {
22
+ const [online, setOnline] = useState(true)
23
+ // Held in a ref so a pending confirmation survives re-renders and is cleared
24
+ // the moment connectivity returns.
25
+ const pendingOffline = useRef<ReturnType<typeof setTimeout> | null>(null)
26
+
27
+ useEffect(() => {
28
+ let cancelled = false
29
+
30
+ const clearPending = () => {
31
+ if (pendingOffline.current !== null) {
32
+ clearTimeout(pendingOffline.current)
33
+ pendingOffline.current = null
34
+ }
35
+ }
36
+
37
+ /** Online applies at once; offline only after it has held for `confirmMs`. */
38
+ const apply = (next: boolean) => {
39
+ if (cancelled) return
40
+ if (next) {
41
+ clearPending()
42
+ setOnline(true)
43
+ return
44
+ }
45
+ if (pendingOffline.current !== null) return
46
+ pendingOffline.current = setTimeout(() => {
47
+ pendingOffline.current = null
48
+ if (!cancelled) setOnline(false)
49
+ }, confirmMs)
50
+ }
51
+
52
+ void getOnline()
53
+ .then(apply)
54
+ // A rejected probe is not worth an unhandled rejection at mount. NetInfo
55
+ // reads native state and this hook is mounted by /pay, so a throw here
56
+ // would take the screen down for a device whose connectivity we simply do
57
+ // not know yet — and the optimistic `true` plus `subscribeOnline`'s updates
58
+ // already answer that question well enough.
59
+ .catch(() => {})
60
+ const unsubscribe = subscribeOnline(apply)
61
+
62
+ return () => {
63
+ cancelled = true
64
+ clearPending()
65
+ unsubscribe()
66
+ }
67
+ }, [confirmMs])
68
+
69
+ return online
70
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Spendable wallet balance for the send surfaces — the same figure the wallet
3
+ * screen shows, read the same two ways: the cached figure immediately (so the
4
+ * line never opens empty), then straight to our own SQLite rather than through
5
+ * WalletStorageManager's FIFO reader lock (see storage/methods/walletBalanceSql
6
+ * and the storage-lock notes in app/index.tsx). The wallet's own listOutputs
7
+ * path stays as the fallback for the window before storage and the user id are
8
+ * known. Refreshes on txStatusVersion bumps so a completed send updates it.
9
+ */
10
+ import { useEffect, useRef, useState } from 'react'
11
+ import AsyncStorage from '@react-native-async-storage/async-storage'
12
+ import { sdk } from '@bsv/wallet-toolbox-mobile'
13
+ import { useWallet, readWalletBalance } from '@bsv/expo-wallet-toolbox'
14
+
15
+ export function useSpendableBalance(): number | null {
16
+ const { managers, adminOriginator, selectedNetwork, storage, txStatusVersion, walletUserId } = useWallet()
17
+ const [balance, setBalance] = useState<number | null>(null)
18
+ const cacheKey = `cached_wallet_balance_${selectedNetwork}`
19
+ // One read at a time; a bump arriving mid-read is served by that read.
20
+ const inFlightRef = useRef(false)
21
+
22
+ useEffect(() => {
23
+ let cancelled = false
24
+ ;(async () => {
25
+ const cached = await AsyncStorage.getItem(cacheKey)
26
+ if (!cancelled && cached != null) setBalance(prev => (prev == null ? Number(cached) : prev))
27
+
28
+ if (inFlightRef.current) return
29
+ inFlightRef.current = true
30
+ try {
31
+ let total: number | null = null
32
+ if (storage && walletUserId != null) {
33
+ total = await readWalletBalance(storage, walletUserId)
34
+ }
35
+ if (total == null) {
36
+ const pm = managers?.permissionsManager
37
+ if (!pm) return
38
+ const { totalOutputs } = await pm.listOutputs({ basket: sdk.specOpWalletBalance }, adminOriginator)
39
+ total = totalOutputs ?? 0
40
+ }
41
+ if (!cancelled) setBalance(total)
42
+ await AsyncStorage.setItem(cacheKey, String(total))
43
+ } catch {
44
+ // Keep the last known figure: a failed read is not "zero satoshis".
45
+ } finally {
46
+ inFlightRef.current = false
47
+ }
48
+ })()
49
+ return () => {
50
+ cancelled = true
51
+ }
52
+ // Data deps only — see app/index.tsx on why callback identity must not
53
+ // be a dependency here.
54
+ // eslint-disable-next-line react-hooks/exhaustive-deps
55
+ }, [cacheKey, storage, walletUserId, managers?.permissionsManager, txStatusVersion])
56
+
57
+ return balance
58
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Vault balance — the sum of outputs in the `admin vault` basket. Separate from
3
+ * the main wallet balance (which is managed-change-only and deliberately
4
+ * excludes vault funds). Refreshes on txStatusVersion bumps and on demand
5
+ * after a transfer.
6
+ *
7
+ * FROZEN while a transfer is mid-flight (ceremony phase 'preparing' /
8
+ * 'broadcasting'): in that window the spent vault UTXO is gone and its change
9
+ * is still unsent, so a fetch reads 0 — a partial withdrawal would flash
10
+ * "balance: 0" mid-operation. The last known figure stays up; the busy→idle
11
+ * transition refetches, covering any txStatusVersion bumps the freeze
12
+ * swallowed.
13
+ */
14
+ import { useCallback, useEffect, useRef, useState } from 'react'
15
+ import { useWallet, useVault, getVaultBalance, type VaultWallet } from '@bsv/expo-wallet-toolbox'
16
+
17
+ export function useVaultBalance(): { balance: number | null; loading: boolean; refresh: () => void } {
18
+ const { managers, adminOriginator, txStatusVersion } = useWallet()
19
+ const { state: vaultState } = useVault()
20
+ // The zero-read window: both transfer paths note 'preparing' BEFORE their
21
+ // createAction and stay busy until the broadcast settles (transfers.ts).
22
+ const transferInFlight = vaultState.phase === 'preparing' || vaultState.phase === 'broadcasting'
23
+ const [balance, setBalance] = useState<number | null>(null)
24
+ const [loading, setLoading] = useState(false)
25
+ // Kept in a ref so `refresh` has a stable identity. With `balance` in its deps
26
+ // every callers' effect that lists `refresh` (app/vault.tsx does) re-ran and
27
+ // refetched each time the figure changed.
28
+ const balanceRef = useRef<number | null>(null)
29
+ balanceRef.current = balance
30
+
31
+ const refresh = useCallback(() => {
32
+ const pm = managers?.permissionsManager
33
+ if (!pm) return
34
+ setLoading(prev => (balanceRef.current === null ? true : prev))
35
+ getVaultBalance(pm as unknown as VaultWallet, adminOriginator)
36
+ .then(setBalance)
37
+ .catch(() => {
38
+ /* leave the last known balance in place on a transient failure */
39
+ })
40
+ .finally(() => setLoading(false))
41
+ }, [managers?.permissionsManager, adminOriginator])
42
+
43
+ useEffect(() => {
44
+ if (transferInFlight) return // freeze: a fetch now would read a false 0
45
+ refresh() // also runs on the busy→idle transition, adopting the real figure
46
+ // eslint-disable-next-line react-hooks/exhaustive-deps
47
+ }, [managers?.permissionsManager, adminOriginator, txStatusVersion, transferInFlight])
48
+
49
+ return { balance, loading, refresh }
50
+ }