@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,37 @@
1
+ /**
2
+ * Which wallet build is allowed to publish itself.
3
+ *
4
+ * A network switch tears the wallet down and rebuilds it on the new chain. Two
5
+ * things then go wrong on their own:
6
+ *
7
+ * - The build in flight belongs to the OLD chain. Nothing stops it finishing
8
+ * and publishing its managers, storage and monitor over the top of the new
9
+ * ones — leaving a wallet wired half to each, which is how a mainnet balance
10
+ * could sit above an activity list that returned nothing.
11
+ * - The NEW build is refused. `buildWalletFromMnemonic` returns early while a
12
+ * build is in progress, so the request that carried the new chain is dropped
13
+ * and the stale build is the only one that ever completes.
14
+ *
15
+ * A generation counter answers both. Every teardown bumps it; a build captures
16
+ * the value at its start and publishes only while it still holds. A build that
17
+ * finishes stale says so, and the caller runs again for the chain that is
18
+ * actually selected now.
19
+ */
20
+
21
+ export interface BuildGeneration {
22
+ /** Invalidate any build in flight. Returns the new generation. */
23
+ bump(): number
24
+ /** The generation a build starting now belongs to. */
25
+ current(): number
26
+ /** May a build that started at `token` still publish its results? */
27
+ isCurrent(token: number): boolean
28
+ }
29
+
30
+ export function makeBuildGeneration(): BuildGeneration {
31
+ let n = 0
32
+ return {
33
+ bump: () => ++n,
34
+ current: () => n,
35
+ isCurrent: (token: number) => token === n
36
+ }
37
+ }
@@ -0,0 +1,89 @@
1
+ import * as Device from 'expo-device'
2
+ import { Platform } from 'react-native'
3
+
4
+ /**
5
+ * Coarse device performance tier — used to degrade chrome effects + tab caps
6
+ * on low-RAM hardware (iPhone SE 1/2/3, base iPad, older Pixel) where the
7
+ * combination of liquid glass + Reanimated 4 + live WebView contends for the
8
+ * main thread.
9
+ *
10
+ * The mapping is intentionally conservative — we lean toward "low" if the
11
+ * RAM read is uncertain, so SE-class devices stay smooth at the cost of
12
+ * a slightly less fancy chrome on borderline mid-range models.
13
+ */
14
+ export type DeviceTier = 'low' | 'mid' | 'high'
15
+
16
+ let cachedTier: DeviceTier | null = null
17
+
18
+ /** Read once and cache — device tier doesn't change at runtime. */
19
+ export function getDeviceTier(): DeviceTier {
20
+ if (cachedTier) return cachedTier
21
+
22
+ // Device.totalMemory is bytes on iOS+Android. expo-device returns null on
23
+ // simulators/emulators occasionally; treat null as "mid" (warm pool default 2)
24
+ // so dev work isn't degraded.
25
+ const memBytes = Device.totalMemory
26
+ if (typeof memBytes === 'number' && memBytes > 0) {
27
+ const gb = memBytes / 1024 / 1024 / 1024
28
+ if (gb < 3.5) cachedTier = 'low'
29
+ else if (gb < 5.5) cachedTier = 'mid'
30
+ else cachedTier = 'high'
31
+ } else {
32
+ cachedTier = 'mid'
33
+ }
34
+
35
+ // iPad gets a small bump — extra screen real estate but the same SoC as the
36
+ // matching iPhone (e.g. iPad mini 6 vs iPhone 12). Allow chrome glass at mid.
37
+ if (Platform.OS === 'ios' && Device.deviceType === Device.DeviceType.TABLET && cachedTier === 'mid') {
38
+ cachedTier = 'mid'
39
+ }
40
+
41
+ return cachedTier
42
+ }
43
+
44
+ /** Tab cap by tier — keeps SE-class within OOM-safe memory. */
45
+ export function maxTabsForTier(tier: DeviceTier = getDeviceTier()): number {
46
+ switch (tier) {
47
+ case 'low':
48
+ return 4
49
+ case 'mid':
50
+ return 8
51
+ case 'high':
52
+ return 12
53
+ }
54
+ }
55
+
56
+ /**
57
+ * How many WebViews to keep mounted for instant tab switching.
58
+ * iOS keeps one WebContent process per mounted page — four warm tabs on
59
+ * SE-class hardware caused multi-GB footprints and process termination.
60
+ * Flagship devices can afford 2–3 without the same pressure.
61
+ */
62
+ export function warmPoolSizeForTier(tier: DeviceTier = getDeviceTier()): number {
63
+ if (Platform.OS !== 'ios') return Math.min(2, maxTabsForTier(tier))
64
+ switch (tier) {
65
+ case 'low':
66
+ return 1
67
+ case 'mid':
68
+ return 2
69
+ case 'high':
70
+ return 3
71
+ }
72
+ }
73
+
74
+ /** Should we render liquid glass + heavy blur? Disabled on low tier. */
75
+ export function shouldUseLiquidGlass(tier: DeviceTier = getDeviceTier()): boolean {
76
+ return tier !== 'low'
77
+ }
78
+
79
+ /** Thumbnail capture quality — lowered on low tier to skip the rasterization spike. */
80
+ export function thumbnailQualityForTier(tier: DeviceTier = getDeviceTier()): number {
81
+ switch (tier) {
82
+ case 'low':
83
+ return 0.35
84
+ case 'mid':
85
+ return 0.5
86
+ case 'high':
87
+ return 0.7
88
+ }
89
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Free-space probe.
3
+ *
4
+ * THE API NAME MATTERS. In expo-file-system 55.0.22 the reading is
5
+ * `Paths.availableDiskSpace` — a SYNCHRONOUS getter, no await, no parens.
6
+ * `getFreeDiskStorageAsync` is still exported from the bare specifier and still
7
+ * type-checks, but THROWS at runtime; the only valid async form is
8
+ * `expo-file-system/legacy`. Code using the wrong one compiles, passes review,
9
+ * and fails only on device.
10
+ *
11
+ * THRESHOLDS ARE ABSOLUTE, never percentages. `Paths.totalDiskSpace` returns
12
+ * FREE space on iOS in this version (upstream bug), so `available / total` reads
13
+ * ~1.0 regardless of state and any percentage gate silently never fires there.
14
+ *
15
+ * THE READING CAN BE NULL. The native getters are `Int64?` and return nil on
16
+ * failure while TypeScript claims `number`, so an unguarded `free < THRESHOLD`
17
+ * evaluates false and the gate never triggers. Everything here treats an
18
+ * unusable reading as 'unknown' and callers must fail OPEN on it: refusing to
19
+ * write because we could not read the disk is worse than the problem.
20
+ *
21
+ * On iOS this is the raw `.systemFreeSize`, which excludes whatever purgeable
22
+ * cache the OS is holding — so it under-reports what the system could actually
23
+ * free on demand. That direction is the safe one for a warning.
24
+ */
25
+
26
+ /** Warn the user below this. */
27
+ export const DISK_WARN_BYTES = 200 * 1024 * 1024
28
+
29
+ /** Refuse non-essential writes below this. */
30
+ export const DISK_BLOCK_BYTES = 50 * 1024 * 1024
31
+
32
+ export type DiskPressure = 'ok' | 'warn' | 'block' | 'unknown'
33
+
34
+ /**
35
+ * Bytes available on the volume, or null when the platform gave nothing usable.
36
+ *
37
+ * expo-file-system is a native module, so the import is lazy: a pure helper must
38
+ * not require the native side to exist in order to be loaded.
39
+ */
40
+ export function availableDiskBytes(): number | null {
41
+ try {
42
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
43
+ const { Paths } = require('expo-file-system') as typeof import('expo-file-system')
44
+ const free = (Paths as unknown as { availableDiskSpace?: unknown }).availableDiskSpace
45
+ return typeof free === 'number' && Number.isFinite(free) && free >= 0 ? free : null
46
+ } catch {
47
+ return null
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Classify a free-space reading.
53
+ *
54
+ * Pass a value to test it; omit it to read the device.
55
+ */
56
+ export function diskPressure(free?: number | null): DiskPressure {
57
+ const bytes = free === undefined ? availableDiskBytes() : free
58
+ if (typeof bytes !== 'number' || !Number.isFinite(bytes) || bytes < 0) return 'unknown'
59
+ if (bytes < DISK_BLOCK_BYTES) return 'block'
60
+ if (bytes < DISK_WARN_BYTES) return 'warn'
61
+ return 'ok'
62
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Display currencies the wallet offers. BSV is native; USD comes from
3
+ * WhatsOnChain; every other fiat is WhatsOnChain USD × a Frankfurter USD cross.
4
+ *
5
+ * Language coverage (app locales: en, es, zh, hi, fr, ar, pt, bn, ru, id, ja, pl):
6
+ * USD/GBP/AUD/CAD/NZD (en), EUR (es/fr/pt), CNY (zh), INR (hi), CHF (fr),
7
+ * BRL (pt), JPY (ja), PLN (pl), IDR (id), RUB (ru). ar/bn fall back to USD.
8
+ */
9
+ export const FIAT_CURRENCIES = [
10
+ 'USD',
11
+ 'AUD',
12
+ 'BRL',
13
+ 'CAD',
14
+ 'CHF',
15
+ 'CNY',
16
+ 'EUR',
17
+ 'GBP',
18
+ 'IDR',
19
+ 'INR',
20
+ 'JPY',
21
+ 'NZD',
22
+ 'PLN',
23
+ 'RUB'
24
+ ] as const
25
+
26
+ export type FiatCurrency = (typeof FIAT_CURRENCIES)[number]
27
+
28
+ /** Last-resort USD→fiat snapshot for first-launch offline. Not for trading. */
29
+ export const FALLBACK_USD_FX: Record<string, number> = {
30
+ AUD: 1.3976,
31
+ BRL: 5.1214,
32
+ CAD: 1.3869,
33
+ CHF: 0.8121,
34
+ CNY: 6.7175,
35
+ EUR: 0.86238,
36
+ GBP: 0.74107,
37
+ IDR: 17711,
38
+ INR: 94.78,
39
+ JPY: 158.79,
40
+ NZD: 1.7077,
41
+ PLN: 3.7338,
42
+ RUB: 86.92
43
+ }
44
+
45
+ export const DISPLAY_CURRENCIES = ['BSV', ...FIAT_CURRENCIES] as const
46
+
47
+ export const FRANKFURTER_QUOTES = FIAT_CURRENCIES.filter(code => code !== 'USD')
48
+
49
+ export const FRANKFURTER_RATES_URL = `https://api.frankfurter.dev/v2/rates?base=USD&quotes=${FRANKFURTER_QUOTES.join(',')}`
50
+
51
+ export const DISPLAY_CURRENCY_OPTIONS: { id: string; label: string; icon: 'logo-bitcoin' | 'cash-outline' }[] = [
52
+ { id: 'BSV', label: 'BSV', icon: 'logo-bitcoin' },
53
+ ...FIAT_CURRENCIES.map(id => ({ id, label: id, icon: 'cash-outline' as const }))
54
+ ]
55
+
56
+ export const fallbackUsdToFiat = (): Record<string, number> => ({ USD: 1, ...FALLBACK_USD_FX })
@@ -0,0 +1,176 @@
1
+ /**
2
+ * The chain tracker the wallet uses. Answers merkle roots from the local header
3
+ * window first, the network second, and nothing at all when offline and the
4
+ * height is outside the window.
5
+ *
6
+ * This is the single seam that makes offline payments possible: both BEEF
7
+ * verification call sites — `signer/methods/internalizeAction.js:96` and
8
+ * `storage/methods/createAction.js:495` — reach it through
9
+ * `Services.getChainTracker()`, which wraps whatever sits in
10
+ * `options.chaintracks` (`services/Services.js:149-154`).
11
+ *
12
+ * On a miss it calls `findHeaderForHeight` rather than the remote's own
13
+ * `isValidRootForHeight`, because we want the root itself to cache — a coin
14
+ * whose ancestry we resolved once should verify offline forever after.
15
+ */
16
+ import { Utils } from '@bsv/sdk'
17
+ import type { ChaintracksClientApi } from '@bsv/wallet-toolbox-mobile/out/src/services/chaintracker/chaintracks/Api/ChaintracksClientApi'
18
+ import type { HeaderStore } from './headerStore'
19
+
20
+ /** A merkle root as display-order hex, whether the source gave us a hex string
21
+ * or raw bytes. The remote's `findHeaderForHeight` may return either; plain
22
+ * `String(bytes)` yields "1,2,3,…" which never matches a real root — the source
23
+ * of a chain-tracker that rejects valid proofs. Mirrors the toolbox's own
24
+ * `asString(merkleRoot)`. */
25
+ function rootHex(v: unknown): string {
26
+ return typeof v === 'string' ? v : Utils.toHex(Array.from(v as ArrayLike<number>))
27
+ }
28
+
29
+ export class OfflineFirstChaintracks implements ChaintracksClientApi {
30
+ private store: HeaderStore | undefined
31
+ /**
32
+ * Height of the most recent root we could not resolve. The UI reads it to
33
+ * explain a refusal ("this coin's history is older than the headers on this
34
+ * device") instead of showing a bare verification failure.
35
+ */
36
+ lastMissHeight: number | undefined
37
+
38
+ constructor(
39
+ private readonly remote: ChaintracksClientApi,
40
+ private readonly online: () => Promise<boolean>
41
+ ) {}
42
+
43
+ /** Consume the most recent unresolved height, if any. Kept for tests; classifiers must peek. */
44
+ takeLastMissHeight(): number | undefined {
45
+ const height = this.lastMissHeight
46
+ this.lastMissHeight = undefined
47
+ return height
48
+ }
49
+
50
+ /** Read the most recent unresolved height without clearing it. */
51
+ peekLastMissHeight(): number | undefined {
52
+ return this.lastMissHeight
53
+ }
54
+
55
+ setStore(store: HeaderStore): void {
56
+ this.store = store
57
+ }
58
+
59
+ async isValidRootForHeight(root: string, height: number): Promise<boolean> {
60
+ // Fast path: a local root that AGREES is trusted offline forever (validated
61
+ // window headers, or a previously-resolved root). We do NOT trust a local
62
+ // DISAGREEMENT — it can be a stale/poisoned cache entry or an index error —
63
+ // so a miss OR a mismatch both fall through to the authoritative network.
64
+ const local = this.store?.rootForHeight(height)
65
+ if (local === root) return true
66
+
67
+ if (!(await this.online())) {
68
+ // Logged, because this branch is otherwise indistinguishable from a bad
69
+ // proof: it returns false without consulting anything, and the caller
70
+ // (`Beef.verify` -> the toolbox's validateAtomicBeef) reports that as
71
+ // "The tx parameter must be valid AtomicBEEF". A device whose NetInfo
72
+ // says not-connected therefore rejects every incoming payment with an
73
+ // error blaming the sender's transaction, silently and forever.
74
+ console.warn(
75
+ `[OfflineFirstChaintracks] REFUSED height ${height}: offline (getOnline() false), no lookup attempted. ` +
76
+ 'BEEF verification will fail and be reported as an invalid transaction.'
77
+ )
78
+ this.lastMissHeight = height
79
+ return false
80
+ }
81
+
82
+ try {
83
+ const header = await this.remote.findHeaderForHeight(height)
84
+ if (!header) {
85
+ console.warn(
86
+ `[OfflineFirstChaintracks] REFUSED height ${height}: the chaintracks service has no header ` +
87
+ 'for it (behind the chain tip, or pruned).'
88
+ )
89
+ this.lastMissHeight = height
90
+ return false
91
+ }
92
+ const remoteRoot = rootHex(header.merkleRoot)
93
+ // Refresh the cache with the authoritative value (self-heals a poisoned
94
+ // extra entry from an earlier bad conversion).
95
+ await this.store?.putExtraRoot(height, remoteRoot)
96
+ if (local !== undefined && local !== remoteRoot) {
97
+ console.warn(
98
+ `[OfflineFirstChaintracks] local root disagreed with network at height ${height} (local=${local} network=${remoteRoot}); healed`
99
+ )
100
+ }
101
+ const agrees = remoteRoot === root
102
+ if (!agrees) {
103
+ // The comparison is ===, so a root that is "correct" to the eye still
104
+ // fails on hex case or byte order. Print both to make which one it is
105
+ // obvious from a device log.
106
+ console.warn(
107
+ `[OfflineFirstChaintracks] REFUSED height ${height}: root mismatch\n` +
108
+ ` wanted (from the BEEF's merkle path): ${root}\n` +
109
+ ` got (from chaintracks) : ${remoteRoot}`
110
+ )
111
+ }
112
+ return agrees
113
+ } catch (e: any) {
114
+ // A verification path must never throw a network error at the caller:
115
+ // `Beef.verify` treats false as "not proven", which is the truth here.
116
+ console.warn('[OfflineFirstChaintracks] isValidRootForHeight lookup failed:', e?.message)
117
+ this.lastMissHeight = height
118
+ return false
119
+ }
120
+ }
121
+
122
+ async currentHeight(): Promise<number> {
123
+ if (await this.online()) return await this.remote.currentHeight()
124
+ return this.store?.tipHeight ?? 0
125
+ }
126
+
127
+ // ── Everything below is pure delegation ───────────────────────────────────
128
+ getChain() {
129
+ return this.remote.getChain()
130
+ }
131
+ getInfo() {
132
+ return this.remote.getInfo()
133
+ }
134
+ getPresentHeight() {
135
+ return this.remote.getPresentHeight()
136
+ }
137
+ getHeaders(height: number, count: number) {
138
+ return this.remote.getHeaders(height, count)
139
+ }
140
+ findChainTipHeader() {
141
+ return this.remote.findChainTipHeader()
142
+ }
143
+ findChainTipHash() {
144
+ return this.remote.findChainTipHash()
145
+ }
146
+ findHeaderForHeight(height: number) {
147
+ return this.remote.findHeaderForHeight(height)
148
+ }
149
+ findHeaderForBlockHash(hash: string) {
150
+ return this.remote.findHeaderForBlockHash(hash)
151
+ }
152
+ addHeader(header: Parameters<ChaintracksClientApi['addHeader']>[0]) {
153
+ return this.remote.addHeader(header)
154
+ }
155
+ startListening() {
156
+ return this.remote.startListening()
157
+ }
158
+ listening() {
159
+ return this.remote.listening()
160
+ }
161
+ isListening() {
162
+ return this.remote.isListening()
163
+ }
164
+ isSynchronized() {
165
+ return this.remote.isSynchronized()
166
+ }
167
+ subscribeHeaders(listener: Parameters<ChaintracksClientApi['subscribeHeaders']>[0]) {
168
+ return this.remote.subscribeHeaders(listener)
169
+ }
170
+ subscribeReorgs(listener: Parameters<ChaintracksClientApi['subscribeReorgs']>[0]) {
171
+ return this.remote.subscribeReorgs(listener)
172
+ }
173
+ unsubscribe(subscriptionId: string) {
174
+ return this.remote.unsubscribe(subscriptionId)
175
+ }
176
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Trust anchors for the local header window.
3
+ *
4
+ * A checkpoint is the last header we trust WITHOUT having validated it, so the
5
+ * window starts at `height + 1` and its first header must name `hash` as its
6
+ * previous hash. Nothing enters the store unless it chains back to one of these
7
+ * — which is what stops a compromised or wrong chaintracks deployment from
8
+ * feeding us a merkle root we would then accept money against.
9
+ *
10
+ * Values fetched from the arcade chaintracks deployments on 2026-07-28.
11
+ *
12
+ * · main — height 907,324, mined 2025-07-27, about one year and 52,560 blocks
13
+ * behind the 959,884 tip at the time of writing. One year of headers is
14
+ * ~4.2 MB. Bump this in a future release to prune.
15
+ * · test — height 1,697,402, about 52,560 blocks behind its 1,749,962 tip.
16
+ * · ttn — height 0. The whole teratest chain was 27,502 blocks (~2.2 MB), so
17
+ * windowing it buys nothing and starting from genesis costs nothing.
18
+ */
19
+ export interface HeaderCheckpoint {
20
+ /** Height of the last a-priori-trusted header. The window starts above it. */
21
+ height: number
22
+ /** Block hash in display order. */
23
+ hash: string
24
+ }
25
+
26
+ export const HEADER_CHECKPOINTS: Record<'main' | 'test' | 'ttn', HeaderCheckpoint> = {
27
+ main: {
28
+ height: 907324,
29
+ hash: '00000000000000000ccc802efeef429acb6b670a6b2bac373ece30f7d2df3e26'
30
+ },
31
+ test: {
32
+ height: 1697402,
33
+ hash: '0000000000ae922fff32ff94055b7b1c3963c6b5fd04e2b25f3c52d1708498e7'
34
+ },
35
+ ttn: {
36
+ height: 0,
37
+ hash: '000000000499eabba0a88f5b3747231c74b9191c1a4a04b2c2ea817976b7776d'
38
+ }
39
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * The filesystem operations the header store needs, behind an interface.
3
+ *
4
+ * expo-file-system's binary API is native-only, so the store would be
5
+ * untestable in jest without this seam. It is deliberately tiny: no seeking, no
6
+ * directory walking, no partial writes.
7
+ *
8
+ * `expo-file-system` is required lazily inside `expoHeaderFs()` rather than
9
+ * imported at module scope: the package ships untranspiled TS as its main
10
+ * entry and this project's jest transformIgnorePatterns does not cover it, so
11
+ * an eager import would break any test that only needs `memoryHeaderFs`. Same
12
+ * pattern already used for native-only imports in utils/secpNativeProof.ts and
13
+ * utils/engineNativeProof.ts.
14
+ */
15
+ export interface HeaderFs {
16
+ readBytes(path: string): Promise<Uint8Array | undefined>
17
+ appendBytes(path: string, bytes: Uint8Array): Promise<void>
18
+ /**
19
+ * Replaces the file's entire contents. `appendBytes` cannot shrink a file, so
20
+ * a crash-torn `.bin` (bytes past `meta.count`) can only be healed by writing
21
+ * a prefix.
22
+ */
23
+ writeBytes(path: string, bytes: Uint8Array): Promise<void>
24
+ readText(path: string): Promise<string | undefined>
25
+ writeText(path: string, text: string): Promise<void>
26
+ /**
27
+ * Removes a path, if it is there. An absent path is the desired end state,
28
+ * not an error, so it resolves; anything else genuinely failing throws.
29
+ *
30
+ * Exists because `appendBytes` appends and nothing else can undo that. The
31
+ * header window is discarded whenever the shipped checkpoint moves, and
32
+ * without a delete the old anchor's bytes stay on disk in front of everything
33
+ * the next sync writes — see `HeaderStore.reset`.
34
+ */
35
+ deleteFile(path: string): Promise<void>
36
+ }
37
+
38
+ const HEADERS_DIR = 'headers'
39
+
40
+ export function expoHeaderFs(): HeaderFs {
41
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
42
+ const { Directory, File, Paths } = require('expo-file-system') as typeof import('expo-file-system')
43
+ const dir = new Directory(Paths.document, HEADERS_DIR)
44
+ const ensureDir = () => {
45
+ if (!dir.exists) dir.create({ intermediates: true })
46
+ }
47
+ const file = (path: string) => new File(dir, path)
48
+ return {
49
+ async readBytes(path) {
50
+ const f = file(path)
51
+ return f.exists ? await f.bytes() : undefined
52
+ },
53
+ async appendBytes(path, bytes) {
54
+ ensureDir()
55
+ const f = file(path)
56
+ if (!f.exists) f.create()
57
+ f.write(bytes, { append: true })
58
+ },
59
+ async writeBytes(path, bytes) {
60
+ ensureDir()
61
+ const f = file(path)
62
+ if (!f.exists) f.create()
63
+ f.write(bytes)
64
+ },
65
+ async readText(path) {
66
+ const f = file(path)
67
+ return f.exists ? await f.text() : undefined
68
+ },
69
+ async writeText(path, text) {
70
+ ensureDir()
71
+ const f = file(path)
72
+ if (!f.exists) f.create()
73
+ f.write(text)
74
+ },
75
+ async deleteFile(path) {
76
+ const f = file(path)
77
+ // `File.delete()` throws when the file is absent, which is the one outcome
78
+ // this operation is content with.
79
+ if (f.exists) f.delete()
80
+ }
81
+ }
82
+ }
83
+
84
+ /** In-memory HeaderFs for tests. */
85
+ export function memoryHeaderFs(): HeaderFs {
86
+ const files = new Map<string, Uint8Array>()
87
+ const text = new Map<string, string>()
88
+ return {
89
+ async readBytes(path) {
90
+ return files.get(path)
91
+ },
92
+ async appendBytes(path, bytes) {
93
+ const existing = files.get(path)
94
+ if (!existing) {
95
+ files.set(path, bytes.slice())
96
+ return
97
+ }
98
+ const next = new Uint8Array(existing.length + bytes.length)
99
+ next.set(existing, 0)
100
+ next.set(bytes, existing.length)
101
+ files.set(path, next)
102
+ },
103
+ async writeBytes(path, bytes) {
104
+ files.set(path, bytes.slice())
105
+ },
106
+ async readText(path) {
107
+ return text.get(path)
108
+ },
109
+ async writeText(path, value) {
110
+ text.set(path, value)
111
+ },
112
+ async deleteFile(path) {
113
+ // Both maps: this fake splits bytes from text, but a real filesystem has
114
+ // one namespace and callers are entitled to that behaviour.
115
+ files.delete(path)
116
+ text.delete(path)
117
+ }
118
+ }
119
+ }