@bsv/expo-wallet-toolbox 0.7.0 → 0.10.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 (154) hide show
  1. package/CHANGELOG.md +1790 -0
  2. package/README.md +54 -1
  3. package/core/amountFormatHelpers.ts +20 -2
  4. package/core/backup/RemoteSyncReader.ts +131 -19
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +147 -9
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +70 -4
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/constants.ts +14 -1
  15. package/core/context/ExchangeRateContext.tsx +34 -27
  16. package/core/context/LocalStorageProvider.tsx +43 -40
  17. package/core/context/UserContext.tsx +18 -7
  18. package/core/context/VaultContext.tsx +49 -2
  19. package/core/context/WalletConnectionContext.tsx +203 -11
  20. package/core/context/WalletContext.tsx +653 -175
  21. package/core/headers/OfflineFirstChaintracks.ts +48 -4
  22. package/core/headers/headerStore.ts +26 -4
  23. package/core/headers/headerSyncTriggers.ts +65 -0
  24. package/core/headers/syncHeaders.ts +12 -1
  25. package/core/i18n/translations.tsx +1001 -25
  26. package/core/identity/handleRegistry/client.ts +31 -2
  27. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  28. package/core/identity/handleRegistry/resolver.ts +71 -3
  29. package/core/index.ts +33 -3
  30. package/core/localpay/build.ts +225 -24
  31. package/core/localpay/pending.ts +110 -7
  32. package/core/localpay/pendingAbortAuthority.ts +95 -0
  33. package/core/localpay/pendingAborts.ts +264 -28
  34. package/core/localpay/session.ts +42 -17
  35. package/core/localpay/settlementAck.ts +10 -1
  36. package/core/localpay/transport/socket.ts +52 -3
  37. package/core/localpay/types.ts +9 -1
  38. package/core/localpay/verify.ts +143 -16
  39. package/core/mandala/abortGuard.ts +96 -20
  40. package/core/mandala/createRuntime.ts +206 -33
  41. package/core/mandala/drain.ts +89 -11
  42. package/core/mandala/inboxPrehold.ts +186 -0
  43. package/core/mandala/permissionModule.ts +202 -20
  44. package/core/mandala/settlementStore.ts +24 -2
  45. package/core/mandala/types.ts +40 -5
  46. package/core/monitor/TaskBackupPush.ts +14 -0
  47. package/core/monitor/TaskDrainOutbox.ts +14 -0
  48. package/core/monitor/TaskSendOffline.ts +14 -0
  49. package/core/net/publicDestination.ts +91 -0
  50. package/core/net/validateArcUrl.ts +22 -0
  51. package/core/offline/cancelParked.ts +134 -13
  52. package/core/offline/payerHold.ts +100 -24
  53. package/core/offline/plan.ts +36 -7
  54. package/core/pay/beefRepair.ts +6 -2
  55. package/core/pay/damagedInbox.ts +24 -0
  56. package/core/pay/rails/address.ts +107 -12
  57. package/core/pay/rails/handle.ts +117 -22
  58. package/core/pay/rails/index.ts +45 -7
  59. package/core/pay/rails/nativeIntent.ts +61 -0
  60. package/core/pay/rails/nearby.ts +1 -0
  61. package/core/pay/receiveHistory.ts +93 -0
  62. package/core/pay/recordProof.ts +19 -1
  63. package/core/pay/refreshProofGuard.ts +42 -1
  64. package/core/pay/watchlist.ts +5 -2
  65. package/core/peerpay/control.ts +17 -18
  66. package/core/peerpay/handleResendRequests.ts +58 -4
  67. package/core/peerpay/outbox.ts +3 -1
  68. package/core/recovery/backupMaterial.ts +61 -0
  69. package/core/recovery/createWallet.ts +95 -0
  70. package/core/recovery/recoverWallet.ts +120 -0
  71. package/core/recovery/restoreWallet.ts +170 -0
  72. package/core/recovery/secret.ts +92 -0
  73. package/core/recovery/shareCollector.ts +71 -0
  74. package/core/recovery/shareParsing.ts +87 -0
  75. package/core/recovery/shares.ts +116 -0
  76. package/core/recovery/useRecoveryDeps.ts +70 -0
  77. package/core/services/arcTokenStorage.ts +52 -0
  78. package/core/services/arcadeBroadcastProvider.ts +232 -48
  79. package/core/services/autoApprovePolicy.ts +105 -0
  80. package/core/services/callbackToken.ts +19 -0
  81. package/core/services/capWalletArgs.ts +14 -2
  82. package/core/services/connectionAuthority.ts +98 -0
  83. package/core/services/exchangeRate.ts +35 -12
  84. package/core/services/externalOrigin.ts +11 -0
  85. package/core/services/secrets/kek.ts +126 -29
  86. package/core/services/secrets/migration.ts +16 -4
  87. package/core/services/secrets/store.ts +42 -14
  88. package/core/services/vault/VaultKeyService.ts +228 -45
  89. package/core/services/vault/chainRecovery.ts +483 -0
  90. package/core/services/vault/driver.ts +9 -1
  91. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  92. package/core/services/vault/guard.ts +218 -32
  93. package/core/services/vault/hardwareLease.ts +19 -0
  94. package/core/services/vault/metaAuthority.ts +210 -0
  95. package/core/services/vault/pivReset.ts +64 -23
  96. package/core/services/vault/r1comb.ts +139 -3
  97. package/core/services/vault/session.ts +25 -4
  98. package/core/services/vault/transfers.ts +866 -170
  99. package/core/services/vault/types.ts +19 -4
  100. package/core/services/vault/vaultStore.ts +256 -29
  101. package/core/services/walletArgLimits.ts +45 -2
  102. package/core/services/walletConnectionValidation.ts +76 -6
  103. package/core/services/walletServiceConfig.ts +10 -8
  104. package/core/storage/StorageExpoSQLite.ts +47 -13
  105. package/core/storage/methods/findSql.ts +21 -2
  106. package/core/storage/methods/offlineActions.ts +10 -1
  107. package/core/storage/methods/processOfflineActions.ts +116 -23
  108. package/core/storage/schema/createTables.ts +126 -2
  109. package/core/stores/ConnectionStore.ts +34 -0
  110. package/core/toolboxConfig.ts +45 -11
  111. package/core/walletDbRegistry.ts +63 -0
  112. package/core/walletMonitor.ts +17 -1
  113. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  114. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  115. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  116. package/package.json +2 -2
  117. package/ui/backupShares.ts +26 -169
  118. package/ui/components/pay/AddressReceive.tsx +13 -6
  119. package/ui/components/pay/AssetPicker.tsx +30 -9
  120. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  121. package/ui/components/pay/NearbyFlow.tsx +511 -251
  122. package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
  123. package/ui/components/pay/UniversalSend.tsx +167 -73
  124. package/ui/components/ui/AlertCard.tsx +38 -5
  125. package/ui/components/ui/PermissionSheet.tsx +197 -66
  126. package/ui/components/vault/EnrollWizard.tsx +61 -13
  127. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  128. package/ui/components/wallet/ActivityRow.tsx +5 -3
  129. package/ui/components/wallet/AmountInput.tsx +8 -2
  130. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  131. package/ui/components/wallet/Balance.tsx +42 -23
  132. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  133. package/ui/exportTransactions.ts +36 -4
  134. package/ui/hooks/useExportWalletData.ts +25 -2
  135. package/ui/importDatabases.ts +339 -24
  136. package/ui/index.ts +9 -3
  137. package/ui/isImageUrl.ts +6 -0
  138. package/ui/printRecoveryShares.ts +9 -10
  139. package/ui/recoveryPrompts.ts +91 -0
  140. package/ui/resolveIdentity.ts +31 -9
  141. package/ui/screens/ConnectionsScreen.tsx +86 -19
  142. package/ui/screens/IdentifierScreen.tsx +30 -8
  143. package/ui/screens/PairScreen.tsx +74 -2
  144. package/ui/screens/SettingsScreen.tsx +10 -4
  145. package/ui/screens/TrustScreen.tsx +99 -4
  146. package/ui/screens/VaultScreen.tsx +410 -61
  147. package/ui/screens/VaultTransferScreen.tsx +59 -7
  148. package/ui/screens/WalletCheckScreen.tsx +17 -6
  149. package/ui/screens/WalletConfigScreen.tsx +82 -28
  150. package/ui/screens/WalletHomeScreen.tsx +179 -88
  151. package/ui/screens/detailActionKeys.ts +55 -0
  152. package/ui/tokenFormat.ts +44 -4
  153. package/ui/txStatus.ts +5 -0
  154. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -13,21 +13,33 @@
13
13
  * device id, and `restoreFromBackup`'s default target is the most recently updated
14
14
  * device in the manifest. Let the monitor push once and the newest entry becomes this
15
15
  * device's own near-empty log — restore would then replay nothing and report success.
16
- * Belt and braces: this module resolves the target itself and passes it explicitly, so
17
- * the default is never consulted even if the ordering slips.
16
+ * Belt and braces: this module resolves every target itself and passes each one
17
+ * through explicitly, so the default is never consulted even if the ordering slips.
18
18
  * 2. **Into a fresh database.** `restoreFromBackup` documents its storage argument as a
19
19
  * fresh, migrated provider. Replay merges by record identity, so re-running it after a
20
20
  * failed attempt converges rather than duplicating — but it is not a repair tool for a
21
21
  * wallet that has already been transacting.
22
22
  *
23
+ * Every DEVICE in the manifest is replayed into the same storage, not only the single
24
+ * highest-ranked one (see XR-015): each device's own log is an independent, non-overlapping
25
+ * history — a change/receipt record unique to one device is never duplicated into another's
26
+ * — so restoring only the "best" candidate would silently drop the rest. This is safe
27
+ * because it merges by record identity exactly as ordinary live multi-device sync already
28
+ * does; the highest-ranked device (by `restore.ts`'s own verified-first-then-newest rule)
29
+ * still decides the `deviceId`/`generation`/`verified` this module reports, so a
30
+ * single-device manifest — the overwhelming common case — behaves exactly as before.
31
+ *
23
32
  * Errors propagate. A partial or forked log must stop the import: a wallet that looks
24
33
  * healthy while missing the outputs it needs to spend is worse than one that plainly
25
34
  * failed to restore.
26
35
  */
27
36
  import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
28
- import { BackupClient, type DeviceSummary } from './client'
37
+ import { applyAppData, mergeAppData } from './appData'
38
+ import { BackupClient } from './client'
39
+ import type { AppDataSnapshot } from './codec'
29
40
  import type { BackupChain } from './constants'
30
- import { listBackups, restoreFromBackup } from './restore'
41
+ import { deriveBackupWallet } from './derive'
42
+ import { listBackups, pickTarget, restoreFromBackup } from './restore'
31
43
 
32
44
  export interface RestoreOnImportDeps {
33
45
  /** A fresh, migrated storage provider to replay into. */
@@ -42,7 +54,11 @@ export interface RestoreOnImportDeps {
42
54
  baseUrl?: string
43
55
  /** Injected transport, for tests. Takes precedence over `baseUrl`. */
44
56
  client?: BackupClient
45
- /** Chunks replayed so far, and how many this generation holds. */
57
+ /**
58
+ * Chunks replayed so far, and how many this generation holds. Scoped to whichever
59
+ * device is currently replaying — with more than one device in the manifest this fires
60
+ * once per device, each restarting from its own generation's own total.
61
+ */
46
62
  onProgress?: (chunks: number, total: number) => void
47
63
  /**
48
64
  * After a successful replay, check that restored coins are still spendable.
@@ -54,11 +70,20 @@ export interface RestoreOnImportDeps {
54
70
 
55
71
  export interface RestoreOnImportResult {
56
72
  restored: boolean
73
+ /** Total chunks replayed across every device in the manifest, not only the primary one. */
57
74
  chunks: number
75
+ /** The highest-ranked (primary) device replayed — see this module's own docstring. */
58
76
  deviceId?: string
77
+ /** The primary device's own replayed generation. */
59
78
  generation?: number
60
79
  /** Why nothing was replayed. Absent when `restored` is true. */
61
80
  reason?: 'not-configured' | 'no-backup'
81
+ /**
82
+ * True only when EVERY device replayed had a newest entry carrying a seal proving it
83
+ * complete — see restore.ts's RestoreResult and P1-backup-incomplete-generation. False if
84
+ * any one of them could not be verified. Absent when nothing was replayed.
85
+ */
86
+ verified?: boolean
62
87
  }
63
88
 
64
89
  export async function restoreOnImport (deps: RestoreOnImportDeps): Promise<RestoreOnImportResult> {
@@ -68,53 +93,92 @@ export async function restoreOnImport (deps: RestoreOnImportDeps): Promise<Resto
68
93
  }
69
94
 
70
95
  const devices = await listBackups({ primaryKey: deps.primaryKey, chain: deps.chain, client })
71
- const target = newestTarget(devices)
72
- if (target == null) {
96
+ if (devices.length === 0) {
73
97
  // Nothing was ever pushed under this seed. An ordinary outcome — a phrase from a
74
98
  // wallet that predates backups, or one that never went online — so the import
75
99
  // continues with an empty history rather than failing.
76
100
  return { restored: false, chunks: 0, reason: 'no-backup' }
77
101
  }
78
102
 
79
- const result = await restoreFromBackup({
103
+ // Resolved HERE, via the same verified-first ranking restore.ts's pickTarget applies, and
104
+ // passed through explicitly below — never left to restoreFromBackup's own default, which
105
+ // this device's own first push would win as soon as the monitor starts (see this
106
+ // module's docstring). Mirrors restore.ts's pickTarget deliberately: an older but sealed
107
+ // generation is preferred over a newer one still mid-rotation. This PRIMARY target is
108
+ // still what deviceId/generation on the result below describe, so a single-device
109
+ // manifest — the overwhelming common case — restores exactly as before.
110
+ const wallet = deriveBackupWallet(deps.primaryKey, deps.chain)
111
+ const settings = await deps.storage.makeAvailable()
112
+ const primary = await pickTarget(devices, client, wallet, deps.chain, settings)
113
+
114
+ const primaryResult = await restoreFromBackup({
80
115
  storage: deps.storage,
81
116
  primaryKey: deps.primaryKey,
82
117
  chain: deps.chain,
83
118
  identityKey: deps.identityKey,
84
119
  client,
85
120
  manifest: devices,
86
- deviceId: target.deviceId,
87
- generation: target.generation,
121
+ deviceId: primary.deviceId,
122
+ generation: primary.generation,
88
123
  onProgress: deps.onProgress
89
124
  })
90
125
 
126
+ let chunks = primaryResult.chunks
127
+ let verified = primaryResult.verified
128
+ // Folded together across every device before the single write below (XR-011) — never
129
+ // applied per-device: each restoreFromBackup call only RETURNS its own appData rather than
130
+ // writing it, precisely so one device's snapshot can never clobber another's (see
131
+ // mergeAppData's own docs on why this is a union, not last-write-wins).
132
+ let appData: AppDataSnapshot | undefined = primaryResult.appData
133
+
134
+ // Every OTHER device in the manifest is an independent, non-overlapping backup history
135
+ // (see XR-015) — a device's own change/receipt records exist ONLY in its own log, never
136
+ // duplicated into another device's. Restoring only the single highest-ranked device would
137
+ // silently drop anything unique to the rest. Replay each remaining device's own best
138
+ // generation into the SAME storage: safe because it merges by record identity exactly as
139
+ // ordinary live multi-device sync already does (see restoreFromBackup/processSyncChunk),
140
+ // and each device gets its own pickTarget ranking (verified-first, same rule as above)
141
+ // rather than blindly taking its newest generation.
142
+ const otherDeviceIds = [...new Set(devices.map(d => d.deviceId))].filter(id => id !== primary.deviceId)
143
+ for (const deviceId of otherDeviceIds) {
144
+ const target = await pickTarget(devices, client, wallet, deps.chain, settings, deviceId)
145
+ const result = await restoreFromBackup({
146
+ storage: deps.storage,
147
+ primaryKey: deps.primaryKey,
148
+ chain: deps.chain,
149
+ identityKey: deps.identityKey,
150
+ client,
151
+ manifest: devices,
152
+ deviceId: target.deviceId,
153
+ generation: target.generation,
154
+ onProgress: deps.onProgress
155
+ })
156
+ chunks += result.chunks
157
+ verified = verified && result.verified
158
+ appData = mergeAppData(appData, result.appData)
159
+ }
160
+
161
+ // Written once, here, BEFORE validateRestoredCoins/reviewSpendableOutputs and well before
162
+ // the caller marks the wallet built (WalletContext.tsx) — the existing background
163
+ // pending-queue effect and the outbox's own consumers pick these rows up on their own next
164
+ // tick, through their own existing guards, exactly as if this device had written them
165
+ // itself. No new hook, and nothing here ever internalizes, broadcasts or releases anything
166
+ // (see appData.ts's applyAppData docs).
167
+ if (appData !== undefined) {
168
+ await applyAppData(deps.storage, appData)
169
+ }
170
+
91
171
  if (deps.validateRestoredCoins) {
92
172
  await deps.validateRestoredCoins()
93
173
  }
94
174
 
95
175
  return {
96
176
  restored: true,
97
- chunks: result.chunks,
98
- deviceId: result.deviceId,
99
- generation: result.generation
177
+ chunks,
178
+ deviceId: primary.deviceId,
179
+ generation: primary.generation,
180
+ verified
100
181
  }
101
182
  }
102
183
 
103
184
  const hasUrl = (u?: string): boolean => u != null && u !== ''
104
-
105
- /**
106
- * The most recently written device, then that device's highest generation.
107
- *
108
- * A generation is a full snapshot, so the newest one alone is sufficient and is also the
109
- * shortest replay. Mirrors `restoreFromBackup`'s own default deliberately: this exists to
110
- * make the choice explicit at a point where only the other device's logs can be in the
111
- * manifest, not to choose differently.
112
- */
113
- function newestTarget (devices: DeviceSummary[]): { deviceId: string, generation: number } | null {
114
- if (devices.length === 0) return null
115
- const newest = devices.reduce((best, d) => (d.updatedAt > best.updatedAt ? d : best))
116
- const generation = devices
117
- .filter(d => d.deviceId === newest.deviceId)
118
- .reduce((best, d) => (d.generation > best.generation ? d : best)).generation
119
- return { deviceId: newest.deviceId, generation }
120
- }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Has this device actually put a backup on the server?
2
+ * Has THIS wallet actually put a backup on the server?
3
3
  *
4
4
  * Read from the push cursor rather than by asking the server: the cursor is
5
5
  * written only after chunks are appended, so a non-zero `seq` is this device's
@@ -7,26 +7,31 @@
7
7
  * "we could not reach the server" is not the same as "you have no backup", and
8
8
  * the troubleshooting list must not conflate them.
9
9
  *
10
- * Scanning the key prefix avoids needing the primary key (the pseudonym is
11
- * derived from it) up in the UI, where it has no business being.
10
+ * Scoped to `chain`+`pseudonym` (the caller's own identity), not merely the bare
11
+ * `backupCursor-` prefix: `cursorKey`'s deviceId component never changes across a
12
+ * logout/re-import on the same install (see deviceId.ts), so an unscoped scan can read a
13
+ * DIFFERENT, departed wallet's leftover cursor and report a brand-new wallet as backed up
14
+ * before it has ever pushed anything (XR-009). The pseudonym is derived from the primary
15
+ * key but is not itself secret — it is exactly what the backup server sees as this
16
+ * wallet's account — so passing it here still keeps the primary key itself out of the UI.
12
17
  */
13
18
  import AsyncStorage from '@react-native-async-storage/async-storage'
19
+ import { cursorKeyPrefix, type BackupChain } from './constants'
14
20
  import { isBackupPushEnabled } from './preference'
15
21
 
16
- const CURSOR_PREFIX = 'backupCursor-'
17
-
18
22
  export type BackupUploadState = {
19
23
  /** The user has not opted out. */
20
24
  enabled: boolean
21
- /** At least one chunk has been appended for some generation on this device. */
25
+ /** At least one chunk has been appended for some generation, under this identity. */
22
26
  uploaded: boolean
23
27
  }
24
28
 
25
- export async function getBackupUploadState(): Promise<BackupUploadState> {
29
+ export async function getBackupUploadState(chain: BackupChain, pseudonym: string): Promise<BackupUploadState> {
26
30
  const enabled = await isBackupPushEnabled()
27
31
  let uploaded = false
28
32
  try {
29
- const keys = (await AsyncStorage.getAllKeys()).filter(k => k.startsWith(CURSOR_PREFIX))
33
+ const prefix = cursorKeyPrefix(chain, pseudonym)
34
+ const keys = (await AsyncStorage.getAllKeys()).filter(k => k.startsWith(prefix))
30
35
  if (keys.length > 0) {
31
36
  const entries = await AsyncStorage.multiGet(keys)
32
37
  uploaded = entries.some(([, raw]) => {
package/core/constants.ts CHANGED
@@ -1,9 +1,22 @@
1
1
  /** Auto-approve transactions below this satoshi amount without showing the spend modal */
2
2
  export const DEFAULT_AUTO_APPROVE_THRESHOLD = 100_000
3
- /** Minimum milliseconds between auto-approved transactions (global, origin-agnostic) */
3
+ /** Minimum milliseconds between two auto-approved transactions from the SAME originator */
4
4
  export const AUTO_APPROVE_COOLDOWN_MS = 10_000
5
5
  /** AsyncStorage key for persisted auto-approve threshold */
6
6
  export const AUTO_APPROVE_STORAGE_KEY = 'autoApproveThreshold'
7
+ /**
8
+ * Global rolling 24h cumulative cap (satoshis) on auto-approved spending,
9
+ * across every originator combined — closes the gap where a single origin
10
+ * (or several) could otherwise auto-approve an unbounded total by staying
11
+ * under the per-request threshold and cooldown forever (misc-p2-04).
12
+ *
13
+ * PROVISIONAL: 10x the default per-request threshold, chosen only so the cap
14
+ * cannot bind in ordinary single-payment use. Pending product sign-off on
15
+ * the real number.
16
+ */
17
+ export const AUTO_APPROVE_DAILY_CAP_SATS = 10 * DEFAULT_AUTO_APPROVE_THRESHOLD
18
+ /** AsyncStorage key for the persisted rolling auto-approve ledger (best-effort; survives app restart) */
19
+ export const AUTO_APPROVE_LEDGER_STORAGE_KEY = 'auto_approve_ledger'
7
20
 
8
21
  /**
9
22
  * AsyncStorage key for whether Settings' Advanced group is expanded.
@@ -1,10 +1,8 @@
1
1
  import { ReactNode, createContext, useEffect, useState } from 'react'
2
- import AsyncStorage from '@react-native-async-storage/async-storage'
3
2
  import { fallbackUsdToFiat } from '../displayCurrencies'
4
3
  import { loadUsdFxRates } from '../services/usdFxRates'
4
+ import { FALLBACK_RATE, getExchangeRate } from '../services/exchangeRate'
5
5
 
6
- const CACHE_KEY = 'cached_exchange_rate'
7
- const HARDCODED_USD_PER_BSV = 16
8
6
  const SATS_PER_BSV = 100_000_000
9
7
 
10
8
  interface ExchangeRateState {
@@ -12,8 +10,11 @@ interface ExchangeRateState {
12
10
  usdToFiat: Record<string, number>
13
11
  }
14
12
 
13
+ // Was its own hardcoded 16, disagreeing with exchangeRate.ts's 16.75 fallback
14
+ // (misc-p2-05) — both now read the ONE fallback constant, so the fiat-display
15
+ // UI and the wallet-build seed can never quote a different "no data yet" rate.
15
16
  const defaultState: ExchangeRateState = {
16
- satoshisPerUSD: SATS_PER_BSV / HARDCODED_USD_PER_BSV,
17
+ satoshisPerUSD: SATS_PER_BSV / FALLBACK_RATE,
17
18
  usdToFiat: fallbackUsdToFiat()
18
19
  }
19
20
 
@@ -27,39 +28,45 @@ export const ExchangeRateContextProvider: React.FC<{
27
28
 
28
29
  useEffect(() => {
29
30
  const init = async () => {
30
- // Tier 2: Try loading cached rate from AsyncStorage
31
+ // exchangeRate.ts owns the single timeout-guarded fetch, the single
32
+ // fallback constant, and the shared AsyncStorage cache key — this used
33
+ // to be a second, independent fetch/cache/fallback implementation that
34
+ // could (and did) disagree with it. getExchangeRate() reads the cache
35
+ // (or falls back) and kicks off its own background refresh for next
36
+ // time; it never hangs, so no separate timeout is needed here.
37
+ let refreshed: Promise<number | undefined> | undefined
31
38
  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
- }
39
+ const seed = await getExchangeRate()
40
+ refreshed = seed.refreshed
41
+ if (typeof seed.rate === 'number' && seed.rate > 0) {
42
+ setState(prev => ({ ...prev, satoshisPerUSD: SATS_PER_BSV / seed.rate }))
38
43
  }
39
44
  } catch (error) {
40
- console.error('Error loading cached exchange rate:', error)
45
+ console.error('Error loading exchange rate:', error)
41
46
  }
42
47
 
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
+ // The cached/fallback rate above is shown immediately; this is the SAME
49
+ // background refresh, not a second fetch. It used to be fire-and-forget
50
+ // from this screen's point of view — its result only ever reached the
51
+ // UI on the NEXT cold start, so a session that opened stale stayed
52
+ // stale until it was closed and reopened. `refreshed` never rejects
53
+ // (exchangeRate.ts's own contract), so this only ever raises the rate
54
+ // to a freshly fetched one, never drops it back to the fallback.
48
55
  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
+ const live = await refreshed
57
+ if (typeof live === 'number' && live > 0) {
58
+ setState(prev => ({ ...prev, satoshisPerUSD: SATS_PER_BSV / live }))
56
59
  }
57
60
  } 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
61
+ console.error('Error applying the refreshed exchange rate:', error)
60
62
  }
61
63
 
62
- await fxPromise
64
+ try {
65
+ const usdToFiat = await loadUsdFxRates()
66
+ setState(prev => ({ ...prev, usdToFiat }))
67
+ } catch (error) {
68
+ console.error('Error loading USD FX rates:', error)
69
+ }
63
70
  }
64
71
 
65
72
  init()
@@ -1,12 +1,4 @@
1
- import React, {
2
- createContext,
3
- useCallback,
4
- useContext,
5
- useEffect,
6
- useMemo,
7
- useRef,
8
- useState
9
- } from 'react'
1
+ import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
10
2
  import AsyncStorage from '@react-native-async-storage/async-storage'
11
3
  import i18n from '../i18n/translations'
12
4
  import {
@@ -52,7 +44,11 @@ export interface LocalStorageContextType {
52
44
  setRecoveredKey: (wif: string) => Promise<boolean>
53
45
  getRecoveredKey: () => Promise<string | null>
54
46
  deleteRecoveredKey: () => Promise<void>
55
- deleteAllWalletKeys: () => Promise<void>
47
+ /** Returns whether every legacy plaintext item was verified erased (XR-107).
48
+ * The caller MUST NOT treat "Delete Wallet" as complete when this is
49
+ * false — a persistent SecureStore delete failure means a legacy
50
+ * mnemonic/recoveredKey/password may still be readable on this device. */
51
+ deleteAllWalletKeys: () => Promise<boolean>
56
52
  /** Prompt-free existence check (mnemonic or recovered key) — no biometric,
57
53
  * no wallet build. For UI gating that must never wait on the wallet build,
58
54
  * e.g. "is there already a wallet on this device" before offering import. */
@@ -82,7 +78,8 @@ export const LocalStorageContext = createContext<LocalStorageContextType>({
82
78
  setRecoveredKey: async () => false,
83
79
  getRecoveredKey: async () => null,
84
80
  deleteRecoveredKey: async () => {},
85
- deleteAllWalletKeys: async () => {},
81
+ // Fail-closed default: outside a real provider, nothing was verified erased.
82
+ deleteAllWalletKeys: async () => false,
86
83
  hasStoredIdentity: async () => false,
87
84
 
88
85
  /* unlock */
@@ -134,10 +131,7 @@ export default function LocalStorageProvider({ children }: { children: React.Rea
134
131
 
135
132
  /* --------------------------------- unlock -------------------------------- */
136
133
 
137
- const unlock = useCallback(
138
- () => unlockKek(i18n.t('biometric_unlock_wallet')),
139
- []
140
- )
134
+ const unlock = useCallback(() => unlockKek(i18n.t('biometric_unlock_wallet')), [])
141
135
 
142
136
  /**
143
137
  * The single implicit ceremony. Called on the read path so the returning
@@ -153,13 +147,16 @@ export default function LocalStorageProvider({ children }: { children: React.Rea
153
147
 
154
148
  /* -------------------------------- secure --------------------------------- */
155
149
 
156
- const setMnemonic = useCallback(
157
- (mnemonic: string) => putSecret('mnemonic', mnemonic),
158
- []
159
- )
150
+ const setMnemonic = useCallback((mnemonic: string) => putSecret('mnemonic', mnemonic), [])
160
151
 
152
+ // XR-112: a failed migration must never hand back the legacy plaintext —
153
+ // that would let anyone who just declines/fails the biometric ceremony read
154
+ // a fully signing-capable secret with no authentication at all. A failed
155
+ // migration also never committed an envelope, so hasSecret() below already
156
+ // reports false for this state; retry happens on the next launch, when
157
+ // migration runs again.
161
158
  const getMnemonic = useCallback(async (): Promise<string | null> => {
162
- if (legacyFallback.current) return readLegacySecret('mnemonic')
159
+ if (legacyFallback.current) return null
163
160
  if (!(await hasSecret('mnemonic'))) return null
164
161
  if (!(await ensureUnlocked())) return null
165
162
  return getSecret('mnemonic')
@@ -167,13 +164,10 @@ export default function LocalStorageProvider({ children }: { children: React.Rea
167
164
 
168
165
  const deleteMnemonic = useCallback(() => deleteSecret('mnemonic'), [])
169
166
 
170
- const setRecoveredKey = useCallback(
171
- (wif: string) => putSecret('recoveredKey', wif),
172
- []
173
- )
167
+ const setRecoveredKey = useCallback((wif: string) => putSecret('recoveredKey', wif), [])
174
168
 
175
169
  const getRecoveredKey = useCallback(async (): Promise<string | null> => {
176
- if (legacyFallback.current) return readLegacySecret('recoveredKey')
170
+ if (legacyFallback.current) return null
177
171
  if (!(await hasSecret('recoveredKey'))) return null
178
172
  if (!(await ensureUnlocked())) return null
179
173
  return getSecret('recoveredKey')
@@ -183,28 +177,37 @@ export default function LocalStorageProvider({ children }: { children: React.Rea
183
177
 
184
178
  /** Wipes the secrets and the key protecting them, so the next launch reads as
185
179
  * a clean install instead of prompting for a wallet that no longer exists.
186
- * Works while locked or lost — deleting ciphertext needs no key. */
180
+ * Works while locked or lost — deleting ciphertext needs no key.
181
+ *
182
+ * Returns whether the legacy plaintext namespace was verified erased —
183
+ * see deleteAllSecrets (XR-107). The caller must check this before treating
184
+ * "Delete Wallet" as complete. */
187
185
  const deleteAllWalletKeys = useCallback(() => deleteAllSecrets(), [])
188
186
 
189
187
  const hasStoredIdentity = useCallback(async (): Promise<boolean> => {
190
- return (await hasAnySecret({ strict: true })) ||
188
+ return (
189
+ (await hasAnySecret({ strict: true })) ||
191
190
  (await readLegacySecret('mnemonic', { strict: true })) != null ||
192
191
  (await readLegacySecret('recoveredKey', { strict: true })) != null
192
+ )
193
193
  }, [])
194
194
 
195
- const createMnemonic = useCallback(async (mnemonic: string): Promise<boolean> => {
196
- // A failed migration cannot establish that storage is safely empty.
197
- if (!secretsReadyRef.current || legacyFallback.current || creatingMnemonic) return false
198
- creatingMnemonic = true
199
- try {
200
- if (await hasStoredIdentity()) return false
201
- // The provider may have unmounted while checking storage.
202
- if (!secretsReadyRef.current) return false
203
- return await putSecret('mnemonic', mnemonic)
204
- } finally {
205
- creatingMnemonic = false
206
- }
207
- }, [hasStoredIdentity])
195
+ const createMnemonic = useCallback(
196
+ async (mnemonic: string): Promise<boolean> => {
197
+ // A failed migration cannot establish that storage is safely empty.
198
+ if (!secretsReadyRef.current || legacyFallback.current || creatingMnemonic) return false
199
+ creatingMnemonic = true
200
+ try {
201
+ if (await hasStoredIdentity()) return false
202
+ // The provider may have unmounted while checking storage.
203
+ if (!secretsReadyRef.current) return false
204
+ return await putSecret('mnemonic', mnemonic)
205
+ } finally {
206
+ creatingMnemonic = false
207
+ }
208
+ },
209
+ [hasStoredIdentity]
210
+ )
208
211
 
209
212
  /* -------------------------------- output --------------------------------- */
210
213
 
@@ -5,11 +5,11 @@ export interface NativeHandlers {
5
5
  isFocused: () => Promise<boolean>
6
6
  onFocusRequested: () => Promise<void>
7
7
  onFocusRelinquished: () => Promise<void>
8
- onDownloadFile: (fileData: Blob, fileName: string) => Promise<boolean>
8
+ onDownloadFile?: (fileData: Blob, fileName: string) => Promise<boolean>
9
9
  }
10
10
 
11
11
  // Default no-op implementations for Tauri functions
12
- const defaultNativeHandlers: NativeHandlers = {
12
+ const defaultNativeHandlers: Required<NativeHandlers> = {
13
13
  isFocused: async () => false,
14
14
  onFocusRequested: async () => {},
15
15
  onFocusRelinquished: async () => {},
@@ -40,6 +40,14 @@ const defaultNativeHandlers: NativeHandlers = {
40
40
  }
41
41
  }
42
42
 
43
+ // Merges a host-supplied (possibly partial) NativeHandlers object over the
44
+ // defaults, per field, so omitting any single handler (e.g. onDownloadFile)
45
+ // falls back to its no-op/default implementation instead of leaving it
46
+ // undefined.
47
+ export function mergeNativeHandlers(partial?: Partial<NativeHandlers>): Required<NativeHandlers> {
48
+ return { ...defaultNativeHandlers, ...partial }
49
+ }
50
+
43
51
  // -----
44
52
  // UserContextProps Component Props
45
53
  // -----
@@ -83,7 +91,7 @@ export const UserContextProvider: React.FC<UserContextProps> = ({
83
91
  appVersion = 'unknown',
84
92
  appName = 'App',
85
93
  children,
86
- nativeHandlers = defaultNativeHandlers
94
+ nativeHandlers
87
95
  }) => {
88
96
  const [basketAccessModalOpen, setBasketAccessModalOpen] = useState(false)
89
97
  const [certificateAccessModalOpen, setCertificateAccessModalOpen] = useState(false)
@@ -92,12 +100,14 @@ export const UserContextProvider: React.FC<UserContextProps> = ({
92
100
  const [btmsAccessModalOpen, setBtmsAccessModalOpen] = useState(false)
93
101
  const [pageLoaded, setPageLoaded] = useState(false)
94
102
 
103
+ const handlers = useMemo(() => mergeNativeHandlers(nativeHandlers), [nativeHandlers])
104
+
95
105
  const userContext = useMemo(
96
106
  () => ({
97
- isFocused: nativeHandlers.isFocused,
98
- onFocusRequested: nativeHandlers.onFocusRequested,
99
- onFocusRelinquished: nativeHandlers.onFocusRelinquished,
100
- onDownloadFile: nativeHandlers.onDownloadFile,
107
+ isFocused: handlers.isFocused,
108
+ onFocusRequested: handlers.onFocusRequested,
109
+ onFocusRelinquished: handlers.onFocusRelinquished,
110
+ onDownloadFile: handlers.onDownloadFile,
101
111
  appVersion,
102
112
  appName,
103
113
  basketAccessModalOpen,
@@ -114,6 +124,7 @@ export const UserContextProvider: React.FC<UserContextProps> = ({
114
124
  setPageLoaded
115
125
  }),
116
126
  [
127
+ handlers,
117
128
  appVersion,
118
129
  appName,
119
130
  basketAccessModalOpen,
@@ -17,6 +17,7 @@ import { ceremony } from '../services/vault/ceremonyHost'
17
17
  import { CeremonyState } from '../services/vault/ceremony'
18
18
  import { haptics } from '../hooks/useHaptics'
19
19
  import i18n from '../i18n/translations'
20
+ import { vaultStore } from '../services/vault/vaultStore'
20
21
 
21
22
  /**
22
23
  * Minimal shape of the app's toast function. `core` must never import a `ui`
@@ -33,20 +34,63 @@ interface VaultContextValue {
33
34
  submitPin: (pin: string) => void
34
35
  cancel: () => void
35
36
  retry: () => void
37
+ /**
38
+ * F-07: whether this device holds ANY local Vault enrollment record, on any
39
+ * scope — regardless of isVaultAvailable's release/network gate. An
40
+ * existing, already-funded vault must stay reachable from Home/Settings
41
+ * even when the flag is off or the network switched; only entry-point
42
+ * VISIBILITY needs this — VaultScreen's own canDeposit/canEnroll stay gated
43
+ * on the flag exactly as before. Backed by the same device-local
44
+ * vaultStore.isEnrolled() read the screen's own reload() already performs
45
+ * (no network call), refreshed once here rather than by every consumer.
46
+ */
47
+ hasVaultMeta: boolean
36
48
  }
37
49
 
38
50
  const VaultContext = createContext<VaultContextValue>({
39
51
  state: { phase: 'idle' },
40
52
  submitPin: () => {},
41
53
  cancel: () => {},
42
- retry: () => {}
54
+ retry: () => {},
55
+ hasVaultMeta: false
43
56
  })
44
57
 
45
58
  export const VaultProvider: React.FC<{ children: React.ReactNode; onToast?: VaultToast }> = ({ children, onToast }) => {
46
59
  const [state, setState] = useState<CeremonyState>(ceremony.state)
60
+ const [hasVaultMeta, setHasVaultMeta] = useState(false)
47
61
 
48
62
  useEffect(() => ceremony.subscribe(setState), [])
49
63
 
64
+ // Re-check on every ceremony-phase transition — enrollment, key removal and
65
+ // re-lock all happen around a ceremony — AND on every vaultStore scope
66
+ // change. The phase dependency alone loses a structural race on a cold
67
+ // start: this effect's own vaultStore.isEnrolled() read needs no native
68
+ // I/O and resolves before WalletContext's async wallet-build chain ever
69
+ // reaches vaultStore.configureScope(), so it always latches `false` first
70
+ // and, with nothing else to re-trigger it, would stay wrong for the rest
71
+ // of the session (INT-08). onScopeChange fires exactly when that build
72
+ // chain actually configures the scope, so the check re-runs the moment
73
+ // there is anything new to find.
74
+ useEffect(() => {
75
+ let cancelled = false
76
+ const recheck = (): void => {
77
+ vaultStore
78
+ .isEnrolled()
79
+ .then(enrolled => {
80
+ if (!cancelled) setHasVaultMeta(enrolled)
81
+ })
82
+ .catch(() => {
83
+ if (!cancelled) setHasVaultMeta(false)
84
+ })
85
+ }
86
+ recheck()
87
+ const unsubscribe = vaultStore.onScopeChange(recheck)
88
+ return () => {
89
+ cancelled = true
90
+ unsubscribe()
91
+ }
92
+ }, [state.phase])
93
+
50
94
  // Effects of a completed ceremony: the haptic, and nothing else. `onArmed`
51
95
  // deliberately ignores its VaultSigner argument — the signer is owned by the
52
96
  // transfer that requested it (transfers.ts obtains it from ceremonyHost) and
@@ -69,7 +113,10 @@ export const VaultProvider: React.FC<{ children: React.ReactNode; onToast?: Vaul
69
113
  const cancel = useCallback(() => ceremony.cancel(), [])
70
114
  const retry = useCallback(() => ceremony.retry(), [])
71
115
 
72
- const value = useMemo(() => ({ state, submitPin, cancel, retry }), [state, submitPin, cancel, retry])
116
+ const value = useMemo(
117
+ () => ({ state, submitPin, cancel, retry, hasVaultMeta }),
118
+ [state, submitPin, cancel, retry, hasVaultMeta]
119
+ )
73
120
  return <VaultContext.Provider value={value}>{children}</VaultContext.Provider>
74
121
  }
75
122