@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,35 @@
1
+ /** Auto-approve transactions below this satoshi amount without showing the spend modal */
2
+ export const DEFAULT_AUTO_APPROVE_THRESHOLD = 100_000
3
+ /** Minimum milliseconds between auto-approved transactions (global, origin-agnostic) */
4
+ export const AUTO_APPROVE_COOLDOWN_MS = 10_000
5
+ /** AsyncStorage key for persisted auto-approve threshold */
6
+ export const AUTO_APPROVE_STORAGE_KEY = 'autoApproveThreshold'
7
+
8
+ /**
9
+ * AsyncStorage key for whether Settings' Advanced group is expanded.
10
+ *
11
+ * Persisted so the split is a default, not a wall: a holder who never opens it
12
+ * gets a four-row screen forever, and an operator who lives in Network/ARC
13
+ * finds it open on every visit rather than re-tapping it each time.
14
+ */
15
+ export const ADVANCED_SETTINGS_EXPANDED_KEY = 'settingsAdvancedExpanded'
16
+
17
+ /** AsyncStorage key for custom ARC URL override (per network) */
18
+ export const arcUrlStorageKey = (network: string) => `arc_custom_url_${network}`
19
+ /** AsyncStorage key for custom ARC API token override (per network) */
20
+ export const arcApiTokenStorageKey = (network: string) => `arc_custom_api_token_${network}`
21
+
22
+ /** Default ARC URLs per network */
23
+ export const DEFAULT_ARC_URLS: Record<string, string> = {
24
+ main: 'https://arcade-v2-us-1.bsvblockchain.tech',
25
+ test: 'https://arcade-v2-testnet-us-1.bsvblockchain.tech',
26
+ teratest: 'https://arcade-v2-ttn-us-1.bsvblockchain.tech'
27
+ }
28
+
29
+ /** Known ARC endpoint presets (mainnet-focused, user edits for other regions) */
30
+ export const KNOWN_ARC_URLS = [
31
+ { label: 'Arcade v2 (default)', url: 'https://arcade-v2-us-1.bsvblockchain.tech', requiresToken: false },
32
+ { label: 'Arcade', url: 'https://arcade-us-1.bsvb.tech', requiresToken: false },
33
+ { label: 'TAAL', url: 'https://arc.taal.com', requiresToken: true },
34
+ { label: 'GorillaPool', url: 'https://arc.gorillapool.io', requiresToken: false }
35
+ ]
@@ -0,0 +1,69 @@
1
+ import { ReactNode, createContext, useEffect, useState } from 'react'
2
+ import AsyncStorage from '@react-native-async-storage/async-storage'
3
+ import { fallbackUsdToFiat } from '../displayCurrencies'
4
+ import { loadUsdFxRates } from '../services/usdFxRates'
5
+
6
+ const CACHE_KEY = 'cached_exchange_rate'
7
+ const HARDCODED_USD_PER_BSV = 16
8
+ const SATS_PER_BSV = 100_000_000
9
+
10
+ interface ExchangeRateState {
11
+ satoshisPerUSD: number
12
+ usdToFiat: Record<string, number>
13
+ }
14
+
15
+ const defaultState: ExchangeRateState = {
16
+ satoshisPerUSD: SATS_PER_BSV / HARDCODED_USD_PER_BSV,
17
+ usdToFiat: fallbackUsdToFiat()
18
+ }
19
+
20
+ // Create the exchange rate context and provider to use in the amount component
21
+ export const ExchangeRateContext = createContext<ExchangeRateState>(defaultState)
22
+
23
+ export const ExchangeRateContextProvider: React.FC<{
24
+ children: ReactNode
25
+ }> = ({ children }) => {
26
+ const [state, setState] = useState<ExchangeRateState>(defaultState)
27
+
28
+ useEffect(() => {
29
+ const init = async () => {
30
+ // Tier 2: Try loading cached rate from AsyncStorage
31
+ try {
32
+ const cached = await AsyncStorage.getItem(CACHE_KEY)
33
+ if (cached) {
34
+ const { usdPerBsv } = JSON.parse(cached)
35
+ if (typeof usdPerBsv === 'number' && usdPerBsv > 0) {
36
+ setState(prev => ({ ...prev, satoshisPerUSD: SATS_PER_BSV / usdPerBsv }))
37
+ }
38
+ }
39
+ } catch (error) {
40
+ console.error('Error loading cached exchange rate:', error)
41
+ }
42
+
43
+ const fxPromise = loadUsdFxRates()
44
+ .then(usdToFiat => setState(prev => ({ ...prev, usdToFiat })))
45
+ .catch(error => console.error('Error loading USD FX rates:', error))
46
+
47
+ // Tier 1: Attempt live fetch from WhatsonChain
48
+ try {
49
+ const response = await fetch('https://api.whatsonchain.com/v1/bsv/main/exchangerate')
50
+ const data = await response.json()
51
+ const usdPerBsv = data?.rate
52
+ if (typeof usdPerBsv === 'number' && usdPerBsv > 0) {
53
+ setState(prev => ({ ...prev, satoshisPerUSD: SATS_PER_BSV / usdPerBsv }))
54
+ // Cache the successful result
55
+ await AsyncStorage.setItem(CACHE_KEY, JSON.stringify({ usdPerBsv, timestamp: new Date().toISOString() }))
56
+ }
57
+ } catch (error) {
58
+ console.error('Error fetching exchange rate from WhatsonChain:', error)
59
+ // Tier 2/3 already loaded above -- state remains as cached or hardcoded default
60
+ }
61
+
62
+ await fxPromise
63
+ }
64
+
65
+ init()
66
+ }, [])
67
+
68
+ return <ExchangeRateContext.Provider value={state}>{children}</ExchangeRateContext.Provider>
69
+ }
@@ -0,0 +1,225 @@
1
+ import React, {
2
+ createContext,
3
+ useCallback,
4
+ useContext,
5
+ useEffect,
6
+ useMemo,
7
+ useRef,
8
+ useState
9
+ } from 'react'
10
+ import AsyncStorage from '@react-native-async-storage/async-storage'
11
+ import i18n from '../i18n/translations'
12
+ import {
13
+ autoUnlockKek,
14
+ deleteAllSecrets,
15
+ deleteSecret,
16
+ getSecret,
17
+ getUnlockState,
18
+ hasAnySecret,
19
+ hasSecret,
20
+ isUnlocked,
21
+ migrateLegacySecrets,
22
+ putSecret,
23
+ readLegacySecret,
24
+ subscribeUnlockState,
25
+ unlockKek,
26
+ type MigrationResult,
27
+ type UnlockState
28
+ } from '../services/secrets'
29
+
30
+ /**
31
+ * Wallet secrets are held by services/secrets, which wraps them in AES-256-GCM
32
+ * under a key the OS will only release after a biometric match. This provider
33
+ * is the React surface over that: it runs the one-time migration off the old
34
+ * plaintext scheme, exposes the unlock state to the UI, and keeps the
35
+ * historical get/set/delete shape so callers did not have to change.
36
+ *
37
+ * The biometric prompt happens at most once per process, when the wallet is
38
+ * first instantiated — but unlike the previous design, skipping it does not
39
+ * yield the mnemonic, because there is nothing to read without the key.
40
+ */
41
+ export interface LocalStorageContextType {
42
+ /* secure */
43
+ setMnemonic: (mnemonic: string) => Promise<boolean>
44
+ getMnemonic: () => Promise<string | null>
45
+ deleteMnemonic: () => Promise<void>
46
+ setRecoveredKey: (wif: string) => Promise<boolean>
47
+ getRecoveredKey: () => Promise<string | null>
48
+ deleteRecoveredKey: () => Promise<void>
49
+ deleteAllWalletKeys: () => Promise<void>
50
+ /** Prompt-free existence check (mnemonic or recovered key) — no biometric,
51
+ * no wallet build. For UI gating that must never wait on the wallet build,
52
+ * e.g. "is there already a wallet on this device" before offering import. */
53
+ hasStoredIdentity: () => Promise<boolean>
54
+
55
+ /* unlock */
56
+ /** False until the legacy migration has settled. Reading a secret before
57
+ * this flips would report "no wallet" for an existing user. */
58
+ secretsReady: boolean
59
+ unlockState: UnlockState
60
+ /** Explicit user-initiated unlock, for the lock screen's retry button. */
61
+ unlock: () => Promise<UnlockState>
62
+ migration: MigrationResult | null
63
+
64
+ /* general */
65
+ setItem: (item: string, value: string) => Promise<void>
66
+ getItem: (item: string) => Promise<string | null>
67
+ deleteItem: (item: string) => Promise<void>
68
+ }
69
+
70
+ export const LocalStorageContext = createContext<LocalStorageContextType>({
71
+ /* secure */
72
+ setMnemonic: async () => false,
73
+ getMnemonic: async () => null,
74
+ deleteMnemonic: async () => {},
75
+ setRecoveredKey: async () => false,
76
+ getRecoveredKey: async () => null,
77
+ deleteRecoveredKey: async () => {},
78
+ deleteAllWalletKeys: async () => {},
79
+ hasStoredIdentity: async () => false,
80
+
81
+ /* unlock */
82
+ secretsReady: false,
83
+ unlockState: { status: 'locked' },
84
+ unlock: async () => ({ status: 'locked' }),
85
+ migration: null,
86
+
87
+ /* general */
88
+ getItem: AsyncStorage.getItem,
89
+ setItem: AsyncStorage.setItem,
90
+ deleteItem: AsyncStorage.removeItem
91
+ })
92
+
93
+ export const useLocalStorage = () => useContext(LocalStorageContext)
94
+
95
+ export default function LocalStorageProvider({ children }: { children: React.ReactNode }) {
96
+ const [secretsReady, setSecretsReady] = useState(false)
97
+ const [migration, setMigration] = useState<MigrationResult | null>(null)
98
+ const [unlockState, setUnlockState] = useState<UnlockState>(getUnlockState)
99
+ /** Set when migration failed: this session keeps serving the legacy plaintext
100
+ * so the user still has a working wallet, and we retry on the next launch. */
101
+ const legacyFallback = useRef(false)
102
+
103
+ useEffect(() => subscribeUnlockState(setUnlockState), [])
104
+
105
+ useEffect(() => {
106
+ let cancelled = false
107
+ ;(async () => {
108
+ let result: MigrationResult
109
+ try {
110
+ result = await migrateLegacySecrets()
111
+ } catch (err) {
112
+ console.warn('[LocalStorageProvider] migration threw', (err as Error)?.message)
113
+ result = { outcome: 'failed', stage: 'unknown', retryable: true }
114
+ }
115
+ if (cancelled) return
116
+ legacyFallback.current = result.outcome === 'failed'
117
+ setMigration(result)
118
+ setSecretsReady(true)
119
+ })()
120
+ return () => {
121
+ cancelled = true
122
+ }
123
+ }, [])
124
+
125
+ /* --------------------------------- unlock -------------------------------- */
126
+
127
+ const unlock = useCallback(
128
+ () => unlockKek(i18n.t('biometric_unlock_wallet')),
129
+ []
130
+ )
131
+
132
+ /**
133
+ * The single implicit ceremony. Called on the read path so the returning
134
+ * user sees exactly what they see today — one sheet at wallet build, no
135
+ * extra tap — while `autoUnlockKek` guarantees we never initiate a second
136
+ * one after a cancellation.
137
+ */
138
+ const ensureUnlocked = useCallback(async (): Promise<boolean> => {
139
+ if (isUnlocked()) return true
140
+ const state = await autoUnlockKek(i18n.t('biometric_unlock_wallet'))
141
+ return state.status === 'unlocked'
142
+ }, [])
143
+
144
+ /* -------------------------------- secure --------------------------------- */
145
+
146
+ const setMnemonic = useCallback(
147
+ (mnemonic: string) => putSecret('mnemonic', mnemonic),
148
+ []
149
+ )
150
+
151
+ const getMnemonic = useCallback(async (): Promise<string | null> => {
152
+ if (legacyFallback.current) return readLegacySecret('mnemonic')
153
+ if (!(await hasSecret('mnemonic'))) return null
154
+ if (!(await ensureUnlocked())) return null
155
+ return getSecret('mnemonic')
156
+ }, [ensureUnlocked])
157
+
158
+ const deleteMnemonic = useCallback(() => deleteSecret('mnemonic'), [])
159
+
160
+ const setRecoveredKey = useCallback(
161
+ (wif: string) => putSecret('recoveredKey', wif),
162
+ []
163
+ )
164
+
165
+ const getRecoveredKey = useCallback(async (): Promise<string | null> => {
166
+ if (legacyFallback.current) return readLegacySecret('recoveredKey')
167
+ if (!(await hasSecret('recoveredKey'))) return null
168
+ if (!(await ensureUnlocked())) return null
169
+ return getSecret('recoveredKey')
170
+ }, [ensureUnlocked])
171
+
172
+ const deleteRecoveredKey = useCallback(() => deleteSecret('recoveredKey'), [])
173
+
174
+ /** Wipes the secrets and the key protecting them, so the next launch reads as
175
+ * a clean install instead of prompting for a wallet that no longer exists.
176
+ * Works while locked or lost — deleting ciphertext needs no key. */
177
+ const deleteAllWalletKeys = useCallback(() => deleteAllSecrets(), [])
178
+
179
+ const hasStoredIdentity = useCallback(async (): Promise<boolean> => {
180
+ if (legacyFallback.current) {
181
+ return (await readLegacySecret('mnemonic')) != null || (await readLegacySecret('recoveredKey')) != null
182
+ }
183
+ return hasAnySecret()
184
+ }, [])
185
+
186
+ /* -------------------------------- output --------------------------------- */
187
+
188
+ const value: LocalStorageContextType = useMemo(
189
+ () => ({
190
+ setMnemonic,
191
+ getMnemonic,
192
+ deleteMnemonic,
193
+ setRecoveredKey,
194
+ getRecoveredKey,
195
+ deleteRecoveredKey,
196
+ deleteAllWalletKeys,
197
+ hasStoredIdentity,
198
+
199
+ secretsReady,
200
+ unlockState,
201
+ unlock,
202
+ migration,
203
+
204
+ getItem: AsyncStorage.getItem,
205
+ setItem: AsyncStorage.setItem,
206
+ deleteItem: AsyncStorage.removeItem
207
+ }),
208
+ [
209
+ setMnemonic,
210
+ getMnemonic,
211
+ deleteMnemonic,
212
+ setRecoveredKey,
213
+ getRecoveredKey,
214
+ deleteRecoveredKey,
215
+ deleteAllWalletKeys,
216
+ hasStoredIdentity,
217
+ secretsReady,
218
+ unlockState,
219
+ unlock,
220
+ migration
221
+ ]
222
+ )
223
+
224
+ return <LocalStorageContext.Provider value={value}>{children}</LocalStorageContext.Provider>
225
+ }
@@ -0,0 +1,129 @@
1
+ import React, { createContext, Dispatch, SetStateAction, useMemo, useState } from 'react'
2
+
3
+ // Define the NativeHandlers interface here to avoid circular dependency
4
+ export interface NativeHandlers {
5
+ isFocused: () => Promise<boolean>
6
+ onFocusRequested: () => Promise<void>
7
+ onFocusRelinquished: () => Promise<void>
8
+ onDownloadFile: (fileData: Blob, fileName: string) => Promise<boolean>
9
+ }
10
+
11
+ // Default no-op implementations for Tauri functions
12
+ const defaultNativeHandlers: NativeHandlers = {
13
+ isFocused: async () => false,
14
+ onFocusRequested: async () => {},
15
+ onFocusRelinquished: async () => {},
16
+ // Default implementation uses browser's download API
17
+ onDownloadFile: async (fileData: Blob, fileName: string) => {
18
+ try {
19
+ // Create a URL for the blob
20
+ const url = window.URL.createObjectURL(fileData)
21
+
22
+ // Create a temporary link element
23
+ const link = document.createElement('a')
24
+ link.href = url
25
+ link.download = fileName
26
+
27
+ // Append to body, click, and clean up
28
+ document.body.appendChild(link)
29
+ link.click()
30
+ document.body.removeChild(link)
31
+
32
+ // Release the blob URL
33
+ window.URL.revokeObjectURL(url)
34
+
35
+ return true
36
+ } catch (error) {
37
+ console.error('Download failed:', error)
38
+ return false
39
+ }
40
+ }
41
+ }
42
+
43
+ // -----
44
+ // UserContextProps Component Props
45
+ // -----
46
+ interface UserContextProps {
47
+ appVersion?: string
48
+ appName?: string
49
+ children?: React.ReactNode
50
+ nativeHandlers?: NativeHandlers
51
+ }
52
+
53
+ export interface UserContextValue {
54
+ isFocused: () => Promise<boolean>
55
+ onFocusRequested: () => Promise<void>
56
+ onFocusRelinquished: () => Promise<void>
57
+ onDownloadFile: (fileData: Blob, fileName: string) => Promise<boolean>
58
+ appVersion: string
59
+ appName: string
60
+ basketAccessModalOpen: boolean
61
+ setBasketAccessModalOpen: Dispatch<SetStateAction<boolean>>
62
+ certificateAccessModalOpen: boolean
63
+ setCertificateAccessModalOpen: Dispatch<SetStateAction<boolean>>
64
+ protocolAccessModalOpen: boolean
65
+ setProtocolAccessModalOpen: Dispatch<SetStateAction<boolean>>
66
+ spendingAuthorizationModalOpen: boolean
67
+ setSpendingAuthorizationModalOpen: Dispatch<SetStateAction<boolean>>
68
+ btmsAccessModalOpen: boolean
69
+ setBtmsAccessModalOpen: Dispatch<SetStateAction<boolean>>
70
+ pageLoaded: boolean
71
+ setPageLoaded: Dispatch<SetStateAction<boolean>>
72
+ }
73
+
74
+ export const UserContext = createContext<UserContextValue>({} as UserContextValue)
75
+
76
+ /**
77
+ * The UserInterface component supports both new and returning users.
78
+ * For returning users, if a snapshot exists it is loaded and once authenticated
79
+ * the AuthRedirector (inside Router) sends them to the dashboard.
80
+ * New users see the WalletConfig UI.
81
+ */
82
+ export const UserContextProvider: React.FC<UserContextProps> = ({
83
+ appVersion = 'unknown',
84
+ appName = 'App',
85
+ children,
86
+ nativeHandlers = defaultNativeHandlers
87
+ }) => {
88
+ const [basketAccessModalOpen, setBasketAccessModalOpen] = useState(false)
89
+ const [certificateAccessModalOpen, setCertificateAccessModalOpen] = useState(false)
90
+ const [protocolAccessModalOpen, setProtocolAccessModalOpen] = useState(false)
91
+ const [spendingAuthorizationModalOpen, setSpendingAuthorizationModalOpen] = useState(false)
92
+ const [btmsAccessModalOpen, setBtmsAccessModalOpen] = useState(false)
93
+ const [pageLoaded, setPageLoaded] = useState(false)
94
+
95
+ const userContext = useMemo(
96
+ () => ({
97
+ isFocused: nativeHandlers.isFocused,
98
+ onFocusRequested: nativeHandlers.onFocusRequested,
99
+ onFocusRelinquished: nativeHandlers.onFocusRelinquished,
100
+ onDownloadFile: nativeHandlers.onDownloadFile,
101
+ appVersion,
102
+ appName,
103
+ basketAccessModalOpen,
104
+ setBasketAccessModalOpen,
105
+ certificateAccessModalOpen,
106
+ setCertificateAccessModalOpen,
107
+ protocolAccessModalOpen,
108
+ setProtocolAccessModalOpen,
109
+ spendingAuthorizationModalOpen,
110
+ setSpendingAuthorizationModalOpen,
111
+ btmsAccessModalOpen,
112
+ setBtmsAccessModalOpen,
113
+ pageLoaded,
114
+ setPageLoaded
115
+ }),
116
+ [
117
+ appVersion,
118
+ appName,
119
+ basketAccessModalOpen,
120
+ certificateAccessModalOpen,
121
+ protocolAccessModalOpen,
122
+ spendingAuthorizationModalOpen,
123
+ btmsAccessModalOpen,
124
+ pageLoaded
125
+ ]
126
+ )
127
+
128
+ return <UserContext.Provider value={userContext}>{children}</UserContext.Provider>
129
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * VaultContext — the React face of the ceremony singleton.
3
+ *
4
+ * Subscribes to the shared CeremonyController (services/vault/ceremonyHost) and
5
+ * republishes its state to the ceremony sheet, and owns the *effects* of a
6
+ * ceremony: on arm, play the open sound + success haptic; on relock, play the
7
+ * close sound + confirm haptic and toast.
8
+ *
9
+ * WalletContext owns the unplug→relock wiring; this owns the user-facing
10
+ * feedback. They never fire the same haptic twice — the pairing rules live in
11
+ * hooks/useConfirmationSound.
12
+ */
13
+ import React, { createContext, useContext, useEffect, useMemo, useState, useCallback } from 'react'
14
+ import { ceremony } from '../services/vault/ceremonyHost'
15
+ import { CeremonyState } from '../services/vault/ceremony'
16
+ import { sounds } from '../hooks/useConfirmationSound'
17
+ import { haptics } from '../hooks/useHaptics'
18
+ import i18n from '../i18n/translations'
19
+
20
+ /**
21
+ * Minimal shape of the app's toast function. `core` must never import a `ui`
22
+ * component (see the module doc above and hooks/useHaptics.ts /
23
+ * hooks/useConfirmationSound.ts for the same boundary), so VaultProvider
24
+ * takes an optional toast callback instead of importing one — the host app
25
+ * wires its own toast implementation (e.g. `components/ui/Toast`'s
26
+ * `showToast`) in via the `onToast` prop.
27
+ */
28
+ export type VaultToast = (message: string, opts?: { type?: 'info' | 'success' | 'error' }) => void
29
+
30
+ interface VaultContextValue {
31
+ state: CeremonyState
32
+ submitPin: (pin: string) => void
33
+ cancel: () => void
34
+ retry: () => void
35
+ }
36
+
37
+ const VaultContext = createContext<VaultContextValue>({
38
+ state: { phase: 'idle' },
39
+ submitPin: () => {},
40
+ cancel: () => {},
41
+ retry: () => {}
42
+ })
43
+
44
+ export const VaultProvider: React.FC<{ children: React.ReactNode; onToast?: VaultToast }> = ({ children, onToast }) => {
45
+ const [state, setState] = useState<CeremonyState>(ceremony.state)
46
+
47
+ useEffect(() => ceremony.subscribe(setState), [])
48
+
49
+ // Effects of a completed ceremony: the open cue, and nothing else. `onArmed`
50
+ // deliberately ignores its VaultKeyHandle argument — the unwrapped node must
51
+ // never reach React state or a closure that outlives the operation (see
52
+ // VaultKeyHandle in services/vault/ceremony.ts). There is no key queue to
53
+ // replenish here either: deposit addresses derive from the private node on
54
+ // demand, and no xpub is stored anywhere.
55
+ useEffect(() => {
56
+ ceremony.onArmed = () => {
57
+ haptics.success()
58
+ sounds.vaultOpen()
59
+ }
60
+ ceremony.onRelock = () => {
61
+ haptics.confirm()
62
+ sounds.vaultClose()
63
+ onToast?.(i18n.t('vault_locked'), { type: 'info' })
64
+ }
65
+ return () => {
66
+ ceremony.onArmed = undefined
67
+ ceremony.onRelock = undefined
68
+ }
69
+ }, [onToast])
70
+
71
+ const submitPin = useCallback((pin: string) => ceremony.submitPin(pin), [])
72
+ const cancel = useCallback(() => ceremony.cancel(), [])
73
+ const retry = useCallback(() => ceremony.retry(), [])
74
+
75
+ const value = useMemo(() => ({ state, submitPin, cancel, retry }), [state, submitPin, cancel, retry])
76
+ return <VaultContext.Provider value={value}>{children}</VaultContext.Provider>
77
+ }
78
+
79
+ export const useVault = (): VaultContextValue => useContext(VaultContext)