@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,156 @@
1
+ import { StyleSheet } from 'react-native'
2
+ import { useTheme } from './ThemeContext'
3
+ import { spacing, radii, typography } from './tokens'
4
+
5
+ // This hook creates commonly used styles based on the current theme
6
+ export const useThemeStyles = () => {
7
+ const { colors } = useTheme()
8
+
9
+ return StyleSheet.create({
10
+ // Container styles
11
+ container: {
12
+ flex: 1,
13
+ backgroundColor: colors.background
14
+ },
15
+ contentContainer: {
16
+ flex: 1,
17
+ padding: spacing.xl,
18
+ justifyContent: 'center',
19
+ alignItems: 'center'
20
+ },
21
+ card: {
22
+ backgroundColor: colors.backgroundElevated,
23
+ borderRadius: radii.lg,
24
+ borderWidth: StyleSheet.hairlineWidth,
25
+ borderColor: colors.separator,
26
+ padding: spacing.lg,
27
+ marginVertical: spacing.sm
28
+ },
29
+
30
+ // Text styles
31
+ title: {
32
+ ...typography.title1,
33
+ color: colors.textPrimary,
34
+ marginBottom: spacing.md,
35
+ textAlign: 'center'
36
+ },
37
+ subtitle: {
38
+ ...typography.callout,
39
+ color: colors.textSecondary,
40
+ marginBottom: spacing.xxxl,
41
+ textAlign: 'center'
42
+ },
43
+ text: {
44
+ ...typography.body,
45
+ color: colors.textPrimary
46
+ },
47
+ textSecondary: {
48
+ ...typography.subhead,
49
+ color: colors.textSecondary
50
+ },
51
+
52
+ // Button styles
53
+ button: {
54
+ backgroundColor: colors.accent,
55
+ paddingVertical: spacing.lg,
56
+ paddingHorizontal: spacing.xxxl,
57
+ borderRadius: radii.md,
58
+ width: '100%',
59
+ alignItems: 'center',
60
+ marginBottom: spacing.xl
61
+ },
62
+ buttonText: {
63
+ ...typography.headline,
64
+ color: colors.textOnAccent
65
+ },
66
+ buttonDisabled: {
67
+ backgroundColor: colors.buttonBackgroundDisabled
68
+ },
69
+ buttonTextDisabled: {
70
+ color: colors.buttonTextDisabled
71
+ },
72
+ // Secondary button styles (transparent with border)
73
+ buttonSecondary: {
74
+ backgroundColor: 'transparent',
75
+ paddingVertical: 13,
76
+ paddingHorizontal: 38,
77
+ borderRadius: radii.md,
78
+ width: '100%',
79
+ alignItems: 'center',
80
+ marginBottom: spacing.xl,
81
+ borderWidth: 2,
82
+ borderColor: colors.accent
83
+ },
84
+ buttonSecondaryText: {
85
+ ...typography.headline,
86
+ color: colors.textPrimary
87
+ },
88
+ buttonSecondaryDisabled: {
89
+ borderColor: colors.buttonBackgroundDisabled
90
+ },
91
+
92
+ // Input styles
93
+ inputContainer: {
94
+ width: '100%',
95
+ marginBottom: spacing.xxxl
96
+ },
97
+ input: {
98
+ flexDirection: 'row',
99
+ width: '100%',
100
+ height: 50,
101
+ borderWidth: StyleSheet.hairlineWidth,
102
+ borderColor: colors.separator,
103
+ borderRadius: radii.md,
104
+ backgroundColor: colors.fillTertiary,
105
+ marginBottom: spacing.lg,
106
+ alignItems: 'center'
107
+ },
108
+ inputText: {
109
+ flex: 1,
110
+ ...typography.body,
111
+ paddingHorizontal: spacing.lg,
112
+ color: colors.textPrimary
113
+ },
114
+ inputLabel: {
115
+ ...typography.subhead,
116
+ color: colors.textSecondary,
117
+ marginBottom: spacing.xs
118
+ },
119
+
120
+ // Icon styles
121
+ icon: {
122
+ padding: spacing.md,
123
+ color: colors.textSecondary
124
+ },
125
+
126
+ // Validation styles
127
+ validationError: {
128
+ ...typography.caption1,
129
+ color: colors.error,
130
+ marginBottom: spacing.lg,
131
+ marginTop: -spacing.md
132
+ },
133
+
134
+ // Link styles
135
+ link: {
136
+ color: colors.accent,
137
+ fontWeight: '500'
138
+ },
139
+
140
+ // Other common styles
141
+ row: {
142
+ flexDirection: 'row',
143
+ alignItems: 'center'
144
+ },
145
+ center: {
146
+ justifyContent: 'center',
147
+ alignItems: 'center'
148
+ },
149
+ divider: {
150
+ height: StyleSheet.hairlineWidth,
151
+ backgroundColor: colors.separator,
152
+ width: '100%',
153
+ marginVertical: spacing.lg
154
+ }
155
+ })
156
+ }
@@ -0,0 +1,110 @@
1
+ import AsyncStorage from '@react-native-async-storage/async-storage'
2
+
3
+ /**
4
+ * Wallet database filename registry.
5
+ *
6
+ * Tracks all known wallet `.db` filenames per identityKey-suffix + chain in
7
+ * AsyncStorage so the wallet init code can pick the one with the highest
8
+ * timestamp without needing to scan the filesystem (which is unreliable on
9
+ * Android).
10
+ *
11
+ * Filename formats:
12
+ * Legacy : wallet-<keySuffix>-<chain>net.db → timestamp = 0
13
+ * Current : wallet-<keySuffix>-<chain>net-<unix_s>.db → timestamp = <unix_s>
14
+ */
15
+
16
+ // ── Filename parsing ────────────────────────────────────────────────────────
17
+
18
+ /**
19
+ * Regex that matches both legacy and timestamped wallet DB filenames.
20
+ *
21
+ * Groups:
22
+ * 1 – keySuffix (8 hex chars from the end of the identityKey)
23
+ * 2 – chain (main | test | teratest)
24
+ * 3 – timestamp (digits, optional)
25
+ */
26
+ const DB_FILENAME_RE = /^wallet-([a-fA-F0-9]{8})-(main|test|teratest)net(?:-(\d+))?\.db$/
27
+
28
+ export interface ParsedDbFilename {
29
+ keySuffix: string
30
+ chain: string // 'main' | 'test' | 'teratest'
31
+ timestamp: number // 0 for legacy files without a timestamp segment
32
+ }
33
+
34
+ /**
35
+ * Parse a wallet database filename into its constituent parts.
36
+ * Returns `null` if the filename does not match the expected pattern.
37
+ */
38
+ export function parseDbFilename(name: string): ParsedDbFilename | null {
39
+ const m = DB_FILENAME_RE.exec(name)
40
+ if (!m) return null
41
+ return {
42
+ keySuffix: m[1],
43
+ chain: m[2],
44
+ timestamp: m[3] ? Number(m[3]) : 0
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Extract just the timestamp from a wallet DB filename.
50
+ * Returns `0` for legacy (no-timestamp) filenames, or `-1` if the name is
51
+ * not a valid wallet DB filename at all.
52
+ */
53
+ export function parseTimestampFromFilename(name: string): number {
54
+ const parsed = parseDbFilename(name)
55
+ return parsed ? parsed.timestamp : -1
56
+ }
57
+
58
+ // ── Selection ───────────────────────────────────────────────────────────────
59
+
60
+ /**
61
+ * Given an array of wallet DB filenames, return the one whose embedded
62
+ * timestamp is the highest (i.e. the most recent database).
63
+ *
64
+ * If the array is empty an error is thrown.
65
+ */
66
+ export function selectLatestDb(filenames: string[]): string {
67
+ if (filenames.length === 0) {
68
+ throw new Error('[walletDbRegistry] selectLatestDb called with empty list')
69
+ }
70
+ let best = filenames[0]
71
+ let bestTs = parseTimestampFromFilename(best)
72
+ for (let i = 1; i < filenames.length; i++) {
73
+ const ts = parseTimestampFromFilename(filenames[i])
74
+ if (ts > bestTs) {
75
+ best = filenames[i]
76
+ bestTs = ts
77
+ }
78
+ }
79
+ return best
80
+ }
81
+
82
+ // ── AsyncStorage-backed registry ────────────────────────────────────────────
83
+
84
+ function registryKey(keySuffix: string, chain: string): string {
85
+ return `walletDbs-${keySuffix}-${chain}net`
86
+ }
87
+
88
+ /**
89
+ * Return all registered wallet DB filenames for the given identity + chain.
90
+ */
91
+ export async function getRegisteredDbs(keySuffix: string, chain: string): Promise<string[]> {
92
+ const raw = await AsyncStorage.getItem(registryKey(keySuffix, chain))
93
+ if (!raw) return []
94
+ try {
95
+ const arr = JSON.parse(raw)
96
+ return Array.isArray(arr) ? arr : []
97
+ } catch {
98
+ return []
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Append a filename to the registry (no-op if already present).
104
+ */
105
+ export async function registerDb(keySuffix: string, chain: string, filename: string): Promise<void> {
106
+ const existing = await getRegisteredDbs(keySuffix, chain)
107
+ if (existing.includes(filename)) return
108
+ existing.push(filename)
109
+ await AsyncStorage.setItem(registryKey(keySuffix, chain), JSON.stringify(existing))
110
+ }
@@ -0,0 +1,149 @@
1
+ import { Monitor } from '@bsv/wallet-toolbox-mobile'
2
+
3
+ export const NEW_HEADER_POLL_INTERVAL_MS = 60_000
4
+ export const NEW_HEADER_FAILURE_BACKOFF_MS = 5 * 60_000
5
+ export const REVIEW_PROVEN_TXS_MAX_SPAN = 100
6
+ export const REVIEW_PROVEN_TXS_MIN_INTERVAL_MS = 600_000
7
+
8
+ interface NewHeaderTask {
9
+ lastRunMsecsSinceEpoch: number
10
+ triggerMsecs?: number
11
+ trigger: (nowMsecsSinceEpoch: number) => { run: boolean }
12
+ runTask: () => Promise<string>
13
+ }
14
+
15
+ interface NewHeaderPollingOptions {
16
+ now?: () => number
17
+ pollIntervalMs?: number
18
+ failureBackoffMs?: number
19
+ onFailure?: (error: unknown, retryAt: number) => void
20
+ }
21
+
22
+ /**
23
+ * The wallet SDK's TaskNewHeader declares a one-minute interval but its
24
+ * trigger currently returns true on every five-second monitor cycle. Enforce
25
+ * the intended cadence and back off transient Chaintracks gateway failures.
26
+ */
27
+ export function configureNewHeaderPolling(task: NewHeaderTask, options: NewHeaderPollingOptions = {}) {
28
+ const now = options.now ?? Date.now
29
+ const pollIntervalMs = options.pollIntervalMs ?? Math.max(task.triggerMsecs ?? 0, NEW_HEADER_POLL_INTERVAL_MS)
30
+ const failureBackoffMs = options.failureBackoffMs ?? NEW_HEADER_FAILURE_BACKOFF_MS
31
+ const originalRunTask = task.runTask.bind(task)
32
+ let retryAt = 0
33
+
34
+ task.trigger = (nowMsecsSinceEpoch: number) => ({
35
+ run:
36
+ nowMsecsSinceEpoch >= retryAt &&
37
+ (task.lastRunMsecsSinceEpoch === 0 || nowMsecsSinceEpoch - task.lastRunMsecsSinceEpoch >= pollIntervalMs)
38
+ })
39
+
40
+ task.runTask = async () => {
41
+ try {
42
+ const log = await originalRunTask()
43
+ retryAt = 0
44
+ return log
45
+ } catch (error) {
46
+ retryAt = now() + failureBackoffMs
47
+ options.onFailure?.(error, retryAt)
48
+ return ''
49
+ }
50
+ }
51
+ }
52
+
53
+ export function createWalletMonitorOptions(
54
+ ...args: Parameters<typeof Monitor.createDefaultWalletMonitorOptions>
55
+ ): ReturnType<typeof Monitor.createDefaultWalletMonitorOptions> {
56
+ return Monitor.createDefaultWalletMonitorOptions(...args)
57
+ }
58
+
59
+ /**
60
+ * Construct a Monitor and await `ready` so `_init` registers
61
+ * `subscribeReorgs` / `subscribeHeaders` on `chaintracksWithEvents`.
62
+ * Subscribe failures must not kill the rest of the task loop: the HTTP
63
+ * ChaintracksServiceClient still throws "Method not implemented" for those
64
+ * methods, and TaskReviewProvenTxs is the backup audit in that case.
65
+ */
66
+ export async function createWalletMonitor(
67
+ options: ReturnType<typeof Monitor.createDefaultWalletMonitorOptions>
68
+ ): Promise<Monitor> {
69
+ const monitor = new Monitor(options)
70
+ try {
71
+ await monitor.ready
72
+ } catch (error) {
73
+ const message = error instanceof Error ? error.message : String(error)
74
+ console.warn(`[walletMonitor] chaintracks subscribe failed; TaskReorg will not receive live events: ${message}`)
75
+ }
76
+ return monitor
77
+ }
78
+
79
+ /**
80
+ * Last-reviewed is stored as the height already done; runTask starts at last+1.
81
+ * When that would crawl more than `maxSpan` heights, jump to the last window
82
+ * instead of walking from genesis.
83
+ */
84
+ export function reviewProvenTxsStartHeight(
85
+ lastReviewedHeight: number | undefined,
86
+ maxEligibleHeight: number,
87
+ maxSpan = REVIEW_PROVEN_TXS_MAX_SPAN
88
+ ): number {
89
+ const unbounded = lastReviewedHeight === undefined ? 0 : lastReviewedHeight + 1
90
+ const floor = maxEligibleHeight - maxSpan + 1
91
+ return Math.max(0, unbounded, floor)
92
+ }
93
+
94
+ interface ReviewProvenTxsLike {
95
+ trigger: (nowMsecsSinceEpoch: number) => { run: boolean }
96
+ remainingHeightSpan?: number
97
+ maxHeightsPerRun?: number
98
+ minBlockAge?: number
99
+ getLastReviewedHeight?: () => Promise<number | undefined>
100
+ monitor?: {
101
+ chaintracksWithEvents?: { currentHeight: () => Promise<number> }
102
+ chaintracks: { currentHeight: () => Promise<number> }
103
+ }
104
+ }
105
+
106
+ export interface BoundReviewProvenTxsOptions {
107
+ getOnline?: () => boolean
108
+ now?: () => number
109
+ }
110
+
111
+ /**
112
+ * Keep TaskReviewProvenTxs, but do not let it crawl the whole chain: skip a
113
+ * trigger whose remaining span is over 100, and if last-reviewed is far
114
+ * behind the tip, start at the last 100 eligible heights. Do not run offline,
115
+ * and run at most every REVIEW_PROVEN_TXS_MIN_INTERVAL_MS.
116
+ */
117
+ export function boundReviewProvenTxs(task: ReviewProvenTxsLike, opts?: BoundReviewProvenTxsOptions): void {
118
+ if (typeof task.maxHeightsPerRun === 'number') {
119
+ task.maxHeightsPerRun = Math.min(task.maxHeightsPerRun, REVIEW_PROVEN_TXS_MAX_SPAN)
120
+ }
121
+ const originalTrigger = task.trigger.bind(task)
122
+ let lastRunAt: number | undefined
123
+ task.trigger = (nowMsecsSinceEpoch: number) => {
124
+ if (opts?.getOnline && !opts.getOnline()) return { run: false }
125
+ const base = originalTrigger(nowMsecsSinceEpoch)
126
+ if (!base.run) return base
127
+ if ((task.remainingHeightSpan ?? 0) > REVIEW_PROVEN_TXS_MAX_SPAN) return { run: false }
128
+ const t = opts?.now?.() ?? nowMsecsSinceEpoch
129
+ if (lastRunAt != null && t - lastRunAt < REVIEW_PROVEN_TXS_MIN_INTERVAL_MS) return { run: false }
130
+ lastRunAt = t
131
+ return base
132
+ }
133
+
134
+ const monitor = task.monitor
135
+ if (!task.getLastReviewedHeight || !monitor) return
136
+ const originalGetLast = task.getLastReviewedHeight.bind(task)
137
+ task.getLastReviewedHeight = async () => {
138
+ const last = await originalGetLast()
139
+ const ct = monitor.chaintracksWithEvents || monitor.chaintracks
140
+ const tip = await ct.currentHeight()
141
+ const maxEligible = tip - (task.minBlockAge ?? 0)
142
+ const maxSpan = task.maxHeightsPerRun ?? REVIEW_PROVEN_TXS_MAX_SPAN
143
+ const start = reviewProvenTxsStartHeight(last, maxEligible, maxSpan)
144
+ const unbounded = last === undefined ? 0 : last + 1
145
+ task.remainingHeightSpan = Math.max(0, maxEligible - start + 1)
146
+ if (start > unbounded) return start - 1
147
+ return last
148
+ }
149
+ }
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Ordered Check-my-wallet repair steps.
3
+ *
4
+ * Records first so phantom spendable outputs do not poison later sends.
5
+ * freedCoins = reviewSpendable.released + releaseStuck.released + reviewStatus.restoredInputs
6
+ *
7
+ * A port throw marks that step error; later steps still run.
8
+ */
9
+
10
+ export type WalletCheckStepId =
11
+ | 'online'
12
+ | 'records'
13
+ | 'coins'
14
+ | 'proofs'
15
+ | 'missed_payments'
16
+ | 'backup'
17
+ | 'phrase_backup'
18
+
19
+ /**
20
+ * `error` means the step could not run — the thing to do about it is try again.
21
+ * `attention` means it ran and the answer is one the user should see: offline,
22
+ * no backup on the server, no recovery phrase written down. Conflating the two
23
+ * would offer Retry for a state that retrying cannot change, and would let a
24
+ * wallet with no backup report that everything looks good.
25
+ * `skipped` means the user tapped past it. Not an error, and not clear either:
26
+ * a skipped check is one whose answer nobody knows.
27
+ */
28
+ export type WalletCheckStepStatus = 'ok' | 'error' | 'attention' | 'skipped'
29
+ export type WalletCheckStepResult = { id: WalletCheckStepId; status: WalletCheckStepStatus }
30
+
31
+ /**
32
+ * Lets the user tap past a step. `isSkipped` is read before a step starts;
33
+ * `whenSkipped` races a step already in flight, so the long coins scan can be
34
+ * abandoned rather than watched. The underlying request is not cancellable —
35
+ * it finishes in the background and its result is discarded — but the user is
36
+ * no longer held by it, which is the point.
37
+ */
38
+ export interface WalletCheckSkips {
39
+ isSkipped: (id: WalletCheckStepId) => boolean
40
+ whenSkipped: (id: WalletCheckStepId) => Promise<void>
41
+ }
42
+
43
+ export interface WalletCheckPorts {
44
+ /** Connectivity. Everything below it depends on this being true. */
45
+ checkOnline: () => Promise<{ online: boolean }>
46
+ /** Whether this device has a backup on the private server. */
47
+ checkBackup: () => Promise<{ enabled: boolean; uploaded: boolean }>
48
+ /** Whether the recovery phrase was written down or the shares printed. */
49
+ checkPhraseBackup: () => Promise<{ backedUp: boolean }>
50
+ reviewSpendable: () => Promise<{ released: number; recovered: number }>
51
+ checkProofs: () => Promise<{ repaired: number }>
52
+ reviewStatus: () => Promise<{ failedTxs: number; restoredInputs: number }>
53
+ releaseStuck: () => Promise<{ released: number }>
54
+ creditInbox: () => Promise<{ accepted: number }>
55
+ sweepAddresses: () => Promise<{ imported: number }>
56
+ }
57
+
58
+ async function settle<T>(fn: () => Promise<T>, fallback: T): Promise<{ ok: boolean; value: T }> {
59
+ try {
60
+ return { ok: true, value: await fn() }
61
+ } catch {
62
+ return { ok: false, value: fallback }
63
+ }
64
+ }
65
+
66
+ type StepOutcome<T> = { skipped: true; value: T } | { skipped: false; ok: boolean; value: T }
67
+
68
+ /** Run a step's work unless the user has skipped it, or skips it mid-flight. */
69
+ async function guard<T>(
70
+ skips: WalletCheckSkips | undefined,
71
+ id: WalletCheckStepId,
72
+ fallback: T,
73
+ work: () => Promise<{ ok: boolean; value: T }>
74
+ ): Promise<StepOutcome<T>> {
75
+ if (skips?.isSkipped(id) === true) return { skipped: true, value: fallback }
76
+ if (!skips) return { skipped: false, ...(await work()) }
77
+ const skipSignal = skips.whenSkipped(id).then(() => 'skipped' as const)
78
+ const result = await Promise.race([work(), skipSignal])
79
+ if (result === 'skipped') return { skipped: true, value: fallback }
80
+ return { skipped: false, ...result }
81
+ }
82
+
83
+ function pushStatus(
84
+ steps: WalletCheckStepResult[],
85
+ onStepDone: ((id: WalletCheckStepId, status: WalletCheckStepStatus) => void) | undefined,
86
+ id: WalletCheckStepId,
87
+ status: WalletCheckStepStatus
88
+ ): void {
89
+ steps.push({ id, status })
90
+ onStepDone?.(id, status)
91
+ }
92
+
93
+
94
+ export async function runWalletCheck(
95
+ ports: WalletCheckPorts,
96
+ onStep: (id: WalletCheckStepId) => void,
97
+ /**
98
+ * Fired as each step settles, so a checklist can tick an item the moment it
99
+ * finishes. Without it the per-step outcome is only knowable from the return
100
+ * value — by which point every step has already run, and a user watching a
101
+ * fast wallet would see four steps resolve in one frame with no record of
102
+ * which ones actually happened.
103
+ */
104
+ onStepDone?: (id: WalletCheckStepId, status: WalletCheckStepStatus) => void,
105
+ skips?: WalletCheckSkips
106
+ ): Promise<{
107
+ freedCoins: number
108
+ recoveredPayments: number
109
+ repairedProofs: number
110
+ steps: WalletCheckStepResult[]
111
+ /** Every step ran. Governs whether Retry is worth offering. */
112
+ allOk: boolean
113
+ /**
114
+ * Nothing was flagged, and something was actually checked. Governs the
115
+ * reassuring copy.
116
+ *
117
+ * A skipped step does not count against it: the user chose to move past that
118
+ * one, and answering their choice with "some checks need your attention"
119
+ * treats their own decision as a problem to be fixed. It does not count
120
+ * FOR it either — a run where everything was skipped verified nothing, and
121
+ * has no business claiming the wallet looks fine.
122
+ */
123
+ allClear: boolean
124
+ }> {
125
+ const steps: WalletCheckStepResult[] = []
126
+
127
+ const record = (id: WalletCheckStepId, outcome: { skipped: boolean }, status: () => WalletCheckStepStatus) => {
128
+ pushStatus(steps, onStepDone, id, outcome.skipped ? 'skipped' : status())
129
+ }
130
+
131
+ onStep('online')
132
+ const online = await guard(skips, 'online', { online: false }, () =>
133
+ settle(() => ports.checkOnline(), { online: false })
134
+ )
135
+ record('online', online, () =>
136
+ !(online as { ok?: boolean }).ok ? 'error' : online.value.online ? 'ok' : 'attention'
137
+ )
138
+
139
+ onStep('records')
140
+ const records = await guard(skips, 'records', { failedTxs: 0, restoredInputs: 0, stuckReleased: 0 }, async () => {
141
+ const status = await settle(() => ports.reviewStatus(), { failedTxs: 0, restoredInputs: 0 })
142
+ const stuck = await settle(() => ports.releaseStuck(), { released: 0 })
143
+ return { ok: status.ok && stuck.ok, value: { ...status.value, stuckReleased: stuck.value.released } }
144
+ })
145
+ record('records', records, () => ((records as { ok?: boolean }).ok === true ? 'ok' : 'error'))
146
+
147
+ onStep('proofs')
148
+ const proofs = await guard(skips, 'proofs', { repaired: 0 }, () =>
149
+ settle(() => ports.checkProofs(), { repaired: 0 })
150
+ )
151
+ record('proofs', proofs, () => ((proofs as { ok?: boolean }).ok === true ? 'ok' : 'error'))
152
+
153
+ onStep('backup')
154
+ const backup = await guard(skips, 'backup', { enabled: false, uploaded: false }, () =>
155
+ settle(() => ports.checkBackup(), { enabled: false, uploaded: false })
156
+ )
157
+ record('backup', backup, () =>
158
+ !(backup as { ok?: boolean }).ok ? 'error' : backup.value.enabled && backup.value.uploaded ? 'ok' : 'attention'
159
+ )
160
+
161
+ onStep('phrase_backup')
162
+ const phrase = await guard(skips, 'phrase_backup', { backedUp: false }, () =>
163
+ settle(() => ports.checkPhraseBackup(), { backedUp: false })
164
+ )
165
+ record('phrase_backup', phrase, () =>
166
+ !(phrase as { ok?: boolean }).ok ? 'error' : phrase.value.backedUp ? 'ok' : 'attention'
167
+ )
168
+
169
+ onStep('missed_payments')
170
+ const missed = await guard(skips, 'missed_payments', { accepted: 0, imported: 0 }, async () => {
171
+ const inbox = await settle(() => ports.creditInbox(), { accepted: 0 })
172
+ const sweep = await settle(() => ports.sweepAddresses(), { imported: 0 })
173
+ return { ok: inbox.ok && sweep.ok, value: { accepted: inbox.value.accepted, imported: sweep.value.imported } }
174
+ })
175
+ record('missed_payments', missed, () => ((missed as { ok?: boolean }).ok === true ? 'ok' : 'error'))
176
+
177
+ // Last on purpose: it is the only step that can take minutes (one network
178
+ // call per output), so everything quick has already reported by the time the
179
+ // user is waiting on anything. Still after records, which is what clears the
180
+ // phantom outputs this step would otherwise scan.
181
+ onStep('coins')
182
+ const spendable = await guard(skips, 'coins', { released: 0, recovered: 0 }, () =>
183
+ settle(() => ports.reviewSpendable(), { released: 0, recovered: 0 })
184
+ )
185
+ record('coins', spendable, () => ((spendable as { ok?: boolean }).ok === true ? 'ok' : 'error'))
186
+
187
+ return {
188
+ freedCoins: spendable.value.released + records.value.stuckReleased + records.value.restoredInputs,
189
+ recoveredPayments: missed.value.accepted + missed.value.imported,
190
+ repairedProofs: proofs.value.repaired,
191
+ steps,
192
+ allOk: steps.every(s => s.status !== 'error'),
193
+ allClear: steps.some(s => s.status === 'ok') && steps.every(s => s.status === 'ok' || s.status === 'skipped')
194
+ }
195
+ }
@@ -0,0 +1,18 @@
1
+ export type UtxoProbe = { status: 'success' | 'error'; isUtxo?: boolean }
2
+
3
+ export function shouldReleaseUtxo(args: {
4
+ online: boolean
5
+ txStatus: string
6
+ txid: string
7
+ liveOfflineTxids: Set<string>
8
+ probe: UtxoProbe
9
+ }): boolean {
10
+ return (
11
+ args.online &&
12
+ args.txStatus !== 'nosend' &&
13
+ args.txStatus !== 'unproven' &&
14
+ !args.liveOfflineTxids.has(args.txid) &&
15
+ args.probe.status === 'success' &&
16
+ args.probe.isUtxo === false
17
+ )
18
+ }