@bsv/expo-wallet-toolbox 0.4.0 → 0.7.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 (182) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/README.md +19 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/amountFormatHelpers.ts +238 -34
  6. package/core/backup/RemoteSyncReader.ts +2 -5
  7. package/core/backup/codec.ts +2 -2
  8. package/core/backup/push.ts +1 -1
  9. package/core/config.tsx +16 -1
  10. package/core/contacts/contactActivity.ts +153 -0
  11. package/core/contacts/contactCache.ts +41 -0
  12. package/core/contacts/contactsStore.ts +183 -0
  13. package/core/context/VaultContext.tsx +8 -11
  14. package/core/context/WalletConnectionContext.tsx +137 -52
  15. package/core/context/WalletContext.tsx +464 -30
  16. package/core/demo/demoAssets.ts +60 -0
  17. package/core/demo/demoLedger.ts +240 -0
  18. package/core/demo/demoMandalaRuntime.ts +96 -0
  19. package/core/demo/demoMode.ts +38 -0
  20. package/core/demo/demoWallet.ts +25 -0
  21. package/core/demo/index.ts +26 -0
  22. package/core/demo/useDemo.ts +59 -0
  23. package/core/headers/OfflineFirstChaintracks.ts +52 -14
  24. package/core/headers/headerStore.ts +7 -10
  25. package/core/hooks/useConfirmationSound.ts +14 -8
  26. package/core/i18n/translations.tsx +4562 -986
  27. package/core/identity/contactLink.ts +36 -0
  28. package/core/identity/handleRegistry/client.ts +285 -0
  29. package/core/identity/handleRegistry/profileCert.ts +254 -0
  30. package/core/identity/handleRegistry/registration.ts +559 -0
  31. package/core/identity/handleRegistry/resolver.ts +247 -0
  32. package/core/identity/handleRegistry/rules.ts +104 -0
  33. package/core/index.ts +116 -15
  34. package/core/localpay/build.ts +674 -37
  35. package/core/localpay/codec.ts +68 -5
  36. package/core/localpay/pending.ts +240 -22
  37. package/core/localpay/pendingAborts.ts +5 -1
  38. package/core/localpay/settlementAck.ts +149 -0
  39. package/core/localpay/types.ts +14 -1
  40. package/core/localpay/verify.ts +118 -69
  41. package/core/mandala/abortGuard.ts +134 -0
  42. package/core/mandala/basketMigration.ts +166 -0
  43. package/core/mandala/bundle.ts +244 -0
  44. package/core/mandala/createRuntime.ts +2437 -0
  45. package/core/mandala/drain.ts +670 -0
  46. package/core/mandala/permissionModule.ts +642 -0
  47. package/core/mandala/resendTransfer.ts +175 -0
  48. package/core/mandala/runtime.ts +357 -0
  49. package/core/mandala/settlementStore.ts +412 -0
  50. package/core/mandala/types.ts +290 -0
  51. package/core/monitor/MonitorSupervisor.ts +121 -0
  52. package/core/monitor/TaskBackupPush.ts +1 -1
  53. package/core/monitor/TaskCreditInbox.ts +1 -1
  54. package/core/monitor/TaskDrainOutbox.ts +1 -1
  55. package/core/monitor/TaskSendOffline.ts +1 -1
  56. package/core/net/online.ts +49 -0
  57. package/core/numberFormat.ts +19 -0
  58. package/core/offline/cancelParked.ts +94 -1
  59. package/core/offline/payerHold.ts +152 -12
  60. package/core/offline/plan.ts +1 -1
  61. package/core/offline/tokenFrames.ts +197 -0
  62. package/core/parsePeerPayURI.ts +70 -17
  63. package/core/pay/rails/address.ts +51 -3
  64. package/core/pay/rails/handle.ts +88 -9
  65. package/core/pay/rails/index.ts +16 -6
  66. package/core/pay/rails/nearby.ts +114 -4
  67. package/core/pay/recordProof.ts +2 -6
  68. package/core/services/arcadeBroadcastProvider.ts +1 -4
  69. package/core/services/capWalletArgs.ts +8 -9
  70. package/core/services/exchangeRate.ts +1 -1
  71. package/core/services/externalOrigin.ts +42 -0
  72. package/core/services/vault/VaultKeyService.ts +912 -251
  73. package/core/services/vault/ceremony.ts +435 -367
  74. package/core/services/vault/ceremonyHost.ts +27 -21
  75. package/core/services/vault/devMock.ts +30 -7
  76. package/core/services/vault/driver.ts +95 -41
  77. package/core/services/vault/guard.ts +514 -56
  78. package/core/services/vault/hardwareLease.ts +22 -0
  79. package/core/services/vault/mockYubiKey.ts +258 -90
  80. package/core/services/vault/pivReset.ts +145 -0
  81. package/core/services/vault/r1comb.ts +976 -0
  82. package/core/services/vault/session.ts +93 -26
  83. package/core/services/vault/transfers.ts +2617 -747
  84. package/core/services/vault/types.ts +100 -43
  85. package/core/services/vault/vaultStore.ts +991 -74
  86. package/core/services/walletConnectionValidation.ts +293 -0
  87. package/core/services/walletServiceConfig.ts +31 -20
  88. package/core/storage/StorageExpoSQLite.ts +420 -87
  89. package/core/storage/dbImage.ts +48 -0
  90. package/core/storage/methods/findSql.ts +3 -54
  91. package/core/storage/methods/listActionsSql.ts +8 -5
  92. package/core/storage/methods/listOutputsSql.ts +9 -5
  93. package/core/storage/methods/offlineActions.ts +15 -0
  94. package/core/storage/methods/processOfflineActions.ts +265 -9
  95. package/core/storage/methods/reviewStatusSql.ts +7 -2
  96. package/core/storage/methods/walletBalanceSql.ts +16 -4
  97. package/core/storage/schema/createTables.ts +152 -0
  98. package/core/storage/sqlUpdateValue.ts +24 -0
  99. package/core/toolboxConfig.ts +182 -1
  100. package/core/toolboxTypes.ts +40 -0
  101. package/core/userAvatar.ts +79 -0
  102. package/core/walletMonitor.ts +8 -3
  103. package/core/walletRepair/runWalletCheck.ts +19 -2
  104. package/package.json +31 -30
  105. package/ui/activityFilter.ts +115 -0
  106. package/ui/components/QRScanner.tsx +1 -1
  107. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  108. package/ui/components/pay/AssetPicker.tsx +184 -0
  109. package/ui/components/pay/AvailableBalance.tsx +33 -2
  110. package/ui/components/pay/HandleReceive.tsx +213 -50
  111. package/ui/components/pay/NearbyFlow.tsx +616 -69
  112. package/ui/components/pay/PayForm.tsx +73 -8
  113. package/ui/components/pay/PaymentSuccessOverlay.tsx +89 -8
  114. package/ui/components/pay/RecipientField.tsx +132 -73
  115. package/ui/components/pay/RequestHub.tsx +68 -8
  116. package/ui/components/pay/ResultBanner.tsx +41 -4
  117. package/ui/components/pay/StepBar.tsx +32 -0
  118. package/ui/components/pay/UniversalSend.tsx +1118 -86
  119. package/ui/components/pay/tokenSendCopy.ts +116 -0
  120. package/ui/components/pay/useRecipientInput.ts +36 -7
  121. package/ui/components/ui/PencilEditField.tsx +109 -0
  122. package/ui/components/ui/PermissionSheet.tsx +65 -4
  123. package/ui/components/ui/Sheet.tsx +9 -2
  124. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  125. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  126. package/ui/components/vault/KeyChooser.tsx +96 -0
  127. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  128. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  129. package/ui/components/wallet/ActivityRow.tsx +283 -97
  130. package/ui/components/wallet/AmountInput.tsx +92 -28
  131. package/ui/components/wallet/AssetAmount.tsx +95 -0
  132. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  133. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  134. package/ui/components/wallet/ContactSigil.tsx +49 -0
  135. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  136. package/ui/components/wallet/FitAmount.tsx +148 -0
  137. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  138. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  139. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  140. package/ui/components/wallet/ProfileButton.tsx +62 -0
  141. package/ui/components/wallet/UserAvatar.tsx +85 -0
  142. package/ui/components/wallet/avatarIcons.ts +122 -0
  143. package/ui/components/wallet/tokenEviction.ts +65 -0
  144. package/ui/hooks/useContactsStore.ts +10 -0
  145. package/ui/hooks/useExportWalletData.ts +39 -0
  146. package/ui/hooks/useMandala.ts +320 -0
  147. package/ui/hooks/useOnline.ts +65 -20
  148. package/ui/hooks/useVaultBalance.ts +105 -7
  149. package/ui/hooks/useVaultCoverage.ts +52 -0
  150. package/ui/importDatabases.ts +7 -3
  151. package/ui/index.ts +75 -7
  152. package/ui/screens/ConnectionsScreen.tsx +46 -29
  153. package/ui/screens/ContactScreen.tsx +289 -0
  154. package/ui/screens/ContactsScreen.tsx +373 -0
  155. package/ui/screens/IdentifierScreen.tsx +234 -0
  156. package/ui/screens/NewContactScreen.tsx +362 -0
  157. package/ui/screens/PairScreen.tsx +12 -12
  158. package/ui/screens/PayScreen.tsx +145 -12
  159. package/ui/screens/ProfileScreen.tsx +783 -0
  160. package/ui/screens/SettingsScreen.tsx +18 -9
  161. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  162. package/ui/screens/TrustScreen.tsx +1 -1
  163. package/ui/screens/VaultScreen.tsx +925 -171
  164. package/ui/screens/VaultTransferScreen.tsx +376 -123
  165. package/ui/screens/WalletCheckScreen.tsx +10 -1
  166. package/ui/screens/WalletConfigScreen.tsx +80 -16
  167. package/ui/screens/WalletHomeScreen.tsx +915 -139
  168. package/ui/screens/homeBadges.ts +9 -1
  169. package/ui/screens/tokenRowTitle.ts +68 -0
  170. package/ui/tokenFormat.ts +108 -0
  171. package/ui/tokenSeen.ts +75 -0
  172. package/ui/tokenStatus.ts +100 -0
  173. package/ui/txStatus.ts +43 -5
  174. package/assets/sounds/vault-close.wav +0 -0
  175. package/assets/sounds/vault-open.wav +0 -0
  176. package/core/services/vault/k1.ts +0 -75
  177. package/core/services/vault/sealing.ts +0 -84
  178. package/core/services/vault/vaultDerivation.ts +0 -152
  179. package/core/services/vault/vaultPassphrase.ts +0 -287
  180. package/ui/components/vault/PassphraseField.tsx +0 -306
  181. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  182. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -0,0 +1,320 @@
1
+ /**
2
+ * `useMandala()` — the UI's only door to stablecoins.
3
+ *
4
+ * Everything token-shaped on a screen (a balance row, a picker option, an
5
+ * activity status, a refusal sentence) comes from `MandalaRuntime` and nothing
6
+ * else: the UI never talks to the overlay, the lib or the settlement tables
7
+ * directly, so failure copy, journalling and state stay in one place
8
+ * (core/mandala/runtime.ts's own design rule).
9
+ *
10
+ * The runtime is built by the wallet's own wiring and published on
11
+ * `useWallet().mandala`. It is `undefined` until the wallet is built and on
12
+ * every chain but mainnet — and that is the chain gate, not an error state:
13
+ * when it is undefined every token surface renders `null`, so a wallet that
14
+ * will never hold a token renders today's screens byte for byte (ux §2).
15
+ *
16
+ * `MandalaProvider` exists for tests and for a host that constructs its own
17
+ * runtime; a provider value wins over the context field so a screen test can
18
+ * inject a fake without standing up a wallet.
19
+ *
20
+ * Three rules this hook keeps for its callers:
21
+ *
22
+ * · `null` is UNKNOWN and is never rendered as zero. A cold open, a failed
23
+ * read and a wallet switch all report `null`, because "0 USDX" and "we have
24
+ * not looked yet" are different sentences and only one of them is a balance.
25
+ * · A failed refresh keeps the last figure rather than blanking the screen.
26
+ * · Every async result is dropped if the runtime changed underneath it, so a
27
+ * wallet switch can never paint the previous wallet's money.
28
+ */
29
+ import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
30
+ import { useWallet } from '@bsv/expo-wallet-toolbox'
31
+ import type {
32
+ MandalaRuntime,
33
+ TokenActivityRow,
34
+ TokenAssetInfo,
35
+ TokenAssetStatus,
36
+ TokenBalance
37
+ } from '../../core/mandala/runtime'
38
+ import type { TokenSettlementRow } from '../../core/mandala/types'
39
+
40
+ /**
41
+ * expo-router is required lazily rather than imported at module scope: this
42
+ * file is barrel-exported from the package's `ui` entry point, and a static
43
+ * top-level `import` of expo-router pulls in its own untransformed JSX
44
+ * source, which Jest cannot parse for any consumer of the barrel, even one
45
+ * that never navigates. Same pattern as every other screen/component in this
46
+ * package that needs `useFocusEffect`.
47
+ */
48
+ type ExpoRouterModule = typeof import('expo-router')
49
+ let expoRouterMod: ExpoRouterModule | undefined
50
+ function loadExpoRouter(): ExpoRouterModule {
51
+ if (!expoRouterMod) {
52
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
53
+ expoRouterMod = require('expo-router') as ExpoRouterModule
54
+ }
55
+ return expoRouterMod
56
+ }
57
+
58
+ /**
59
+ * Demo mode's runtime, or a constant `null` in anything but a dev bundle.
60
+ *
61
+ * Resolved once at module scope behind `__DEV__` so the demo folder is
62
+ * required only into a dev bundle: a release build inlines `__DEV__` as false
63
+ * and folds the require — and everything it reaches — out entirely. Same
64
+ * pattern as `utils/AgentationGate.tsx`. Called unconditionally below, because
65
+ * it is a hook and its identity must not change between renders.
66
+ */
67
+ const useDemoRuntime: () => MandalaRuntime | null = __DEV__
68
+ ? // eslint-disable-next-line @typescript-eslint/no-require-imports
69
+ (require('../../core/demo') as typeof import('../../core/demo')).useDemoMandalaRuntime
70
+ : () => null
71
+
72
+ /** Injected runtime. `undefined` means "ask the wallet context"; `null` means "none". */
73
+ const MandalaRuntimeContext = createContext<MandalaRuntime | null | undefined>(undefined)
74
+
75
+ export function MandalaProvider({
76
+ runtime,
77
+ children
78
+ }: {
79
+ runtime: MandalaRuntime | null
80
+ children: React.ReactNode
81
+ }) {
82
+ return React.createElement(MandalaRuntimeContext.Provider, { value: runtime }, children)
83
+ }
84
+
85
+ /**
86
+ * The runtime, or `null` when stablecoins are unavailable on this wallet or
87
+ * this chain. Callers that only fire actions (send, drain) want this; callers
88
+ * that render money want `useMandala()`.
89
+ */
90
+ export function useMandalaRuntime(): MandalaRuntime | null {
91
+ // Before everything else: in demo mode the stablecoin half of the wallet is
92
+ // the demo ledger, whatever the real wallet has built.
93
+ const demo = useDemoRuntime()
94
+ const injected = useContext(MandalaRuntimeContext)
95
+ // `undefined` on the context until the wallet is built, and on every chain
96
+ // but mainnet — which IS the chain gate, not an error state.
97
+ const fromWallet = useWallet()?.mandala ?? null
98
+ const runtime = demo ?? (injected !== undefined ? injected : fromWallet)
99
+ // `available` is the runtime's own chain gate; a runtime that says it is not
100
+ // available is the same as none at all for every surface below.
101
+ return runtime && runtime.available ? runtime : null
102
+ }
103
+
104
+ export interface MandalaState {
105
+ /** Stablecoins exist for this wallet on this chain. Everything is gated on it. */
106
+ available: boolean
107
+ runtime: MandalaRuntime | null
108
+ /** Held assets with their figures. `null` = not known yet, never "zero". */
109
+ balances: TokenBalance[] | null
110
+ /** Just the assets, for a picker. `[]` when nothing is held. */
111
+ assets: TokenAssetInfo[]
112
+ /** Non-terminal settlement rows past the stuck bound (FIX M) — the home badge. */
113
+ stuck: TokenSettlementRow[]
114
+ /** True only while the FIRST read is outstanding; a refresh keeps the figures. */
115
+ loading: boolean
116
+ refresh: () => void
117
+ }
118
+
119
+ const EMPTY_ASSETS: TokenAssetInfo[] = []
120
+ const EMPTY_STUCK: TokenSettlementRow[] = []
121
+
122
+ export function useMandala(): MandalaState {
123
+ const runtime = useMandalaRuntime()
124
+ const [balances, setBalances] = useState<TokenBalance[] | null>(null)
125
+ const [stuck, setStuck] = useState<TokenSettlementRow[]>(EMPTY_STUCK)
126
+ const [loading, setLoading] = useState(false)
127
+ const [nonce, setNonce] = useState(0)
128
+ const runtimeRef = useRef<MandalaRuntime | null>(runtime)
129
+ /** Which runtime we have already read once, so a refresh keeps the figures. */
130
+ const loadedForRef = useRef<MandalaRuntime | null>(null)
131
+
132
+ const refresh = useCallback(() => setNonce(n => n + 1), [])
133
+
134
+ // A wallet switch must read as UNKNOWN immediately, not as the previous
135
+ // wallet's balance held over until the next read lands.
136
+ useEffect(() => {
137
+ if (runtimeRef.current === runtime) return
138
+ runtimeRef.current = runtime
139
+ setBalances(null)
140
+ setStuck(EMPTY_STUCK)
141
+ }, [runtime])
142
+
143
+ useEffect(() => {
144
+ if (!runtime) {
145
+ setBalances(null)
146
+ setStuck(EMPTY_STUCK)
147
+ setLoading(false)
148
+ return
149
+ }
150
+ let live = true
151
+ if (loadedForRef.current !== runtime) setLoading(true)
152
+ void (async () => {
153
+ try {
154
+ const rows = await runtime.balances()
155
+ if (live && runtimeRef.current === runtime) setBalances(rows)
156
+ } catch {
157
+ // A failed read keeps the last figure: a balance that blinks to "—" on
158
+ // every transient overlay hiccup teaches the holder to distrust it.
159
+ }
160
+ try {
161
+ const rows = await runtime.stuck()
162
+ if (live && runtimeRef.current === runtime) setStuck(rows)
163
+ } catch {
164
+ // Same: the badge is advisory, and a missing one is better than a wrong one.
165
+ }
166
+ if (live) {
167
+ loadedForRef.current = runtime
168
+ setLoading(false)
169
+ }
170
+ })()
171
+ return () => {
172
+ live = false
173
+ }
174
+ }, [runtime, nonce])
175
+
176
+ // The runtime tells us when money moved; nothing here polls.
177
+ useEffect(() => {
178
+ if (!runtime) return
179
+ return runtime.subscribe(refresh)
180
+ }, [runtime, refresh])
181
+
182
+ const assets = useMemo(() => (balances ? balances.map(b => b.asset) : EMPTY_ASSETS), [balances])
183
+
184
+ return { available: runtime != null, runtime, balances, assets, stuck, loading, refresh }
185
+ }
186
+
187
+ export interface MandalaActivityState {
188
+ /** `null` until the first read lands — an empty list is a claim, not a wait. */
189
+ rows: TokenActivityRow[] | null
190
+ loading: boolean
191
+ refresh: () => void
192
+ }
193
+
194
+ /**
195
+ * Token rows for the activity list (ux §6.2). Kept out of `useMandala()` so a
196
+ * screen that only needs balances does not pay for an activity query.
197
+ */
198
+ export function useTokenActivity(limit?: number): MandalaActivityState {
199
+ const runtime = useMandalaRuntime()
200
+ const [rows, setRows] = useState<TokenActivityRow[] | null>(null)
201
+ const [loading, setLoading] = useState(false)
202
+ const [nonce, setNonce] = useState(0)
203
+ const refresh = useCallback(() => setNonce(n => n + 1), [])
204
+
205
+ useEffect(() => {
206
+ if (!runtime) {
207
+ setRows(null)
208
+ return
209
+ }
210
+ let live = true
211
+ setLoading(true)
212
+ void (async () => {
213
+ try {
214
+ const next = await runtime.activity(limit)
215
+ if (live) setRows(next)
216
+ } catch {
217
+ // Advisory: the BSV rows still render, and a token row with no status
218
+ // is better than an activity list that failed to draw.
219
+ }
220
+ if (live) setLoading(false)
221
+ })()
222
+ return () => {
223
+ live = false
224
+ }
225
+ }, [runtime, limit, nonce])
226
+
227
+ useEffect(() => {
228
+ if (!runtime) return
229
+ return runtime.subscribe(refresh)
230
+ }, [runtime, refresh])
231
+
232
+ return { rows, loading, refresh }
233
+ }
234
+
235
+ /** Index of token rows by txid, for interleaving into the wallet's own list. */
236
+ export function tokenActivityByTxid(rows: TokenActivityRow[] | null): Map<string, TokenActivityRow> {
237
+ const map = new Map<string, TokenActivityRow>()
238
+ for (const row of rows ?? []) map.set(row.txid.toLowerCase(), row)
239
+ return map
240
+ }
241
+
242
+ export interface AssetStatusState {
243
+ /** `null` until the first read lands, or when there is no runtime/assetId. Never a stand-in for "fine". */
244
+ status: TokenAssetStatus | null
245
+ /** True only while the FIRST read for this (runtime, assetId) pair is outstanding. */
246
+ loading: boolean
247
+ /** Forces a fresh read past the runtime's own ~10s cache. */
248
+ refresh: () => void
249
+ }
250
+
251
+ /**
252
+ * Regulatory/registry facts for one asset (paused, frozen, self/recipient
253
+ * admission, metadata resolution, the MessageBox host) — the one door a pay
254
+ * or receive screen has to the pre-flight copy in ux design §4.2/§5.4.
255
+ *
256
+ * Cached: reads go through `runtime.assetStatus`, which already holds a
257
+ * ~10s cache in the implementation (runtime.ts), so calling this from more
258
+ * than one screen for the same asset costs no extra round trip. Refreshed
259
+ * three ways: the assetId/runtime changing, the runtime announcing a
260
+ * mutation (`subscribe` — a send, a receive, a drain tick), and this screen
261
+ * regaining focus (a paused/frozen fact can go stale while the holder was
262
+ * looking at a different screen). A failed read is silently dropped and
263
+ * keeps the last-known status — this is advisory copy, not a gate anything
264
+ * transacts against (ux §4.2 rule 3: pre-flight may only ever say "no").
265
+ */
266
+ export function useAssetStatus(assetId: string | null | undefined): AssetStatusState {
267
+ const runtime = useMandalaRuntime()
268
+ const [status, setStatus] = useState<TokenAssetStatus | null>(null)
269
+ const [loading, setLoading] = useState(false)
270
+ const [nonce, setNonce] = useState(0)
271
+ const refresh = useCallback(() => setNonce(n => n + 1), [])
272
+ const key = runtime && assetId ? assetId : null
273
+
274
+ useEffect(() => {
275
+ if (!runtime || !key) {
276
+ setStatus(null)
277
+ setLoading(false)
278
+ return
279
+ }
280
+ let live = true
281
+ setLoading(true)
282
+ void (async () => {
283
+ try {
284
+ const next = await runtime.assetStatus(key)
285
+ if (live) setStatus(next)
286
+ } catch {
287
+ // Fails open, like the runtime's own cache: a stale or unreachable
288
+ // overlay must read as "unknown", never as a thrown error, and the
289
+ // last-known status (possibly still null) is kept on screen.
290
+ }
291
+ if (live) setLoading(false)
292
+ })()
293
+ return () => {
294
+ live = false
295
+ }
296
+ }, [runtime, key, nonce])
297
+
298
+ // After mutations: the runtime's own change signal (a send, a receive, a
299
+ // drain tick advancing a settlement) — the same subscription useMandala()
300
+ // uses for balances/activity.
301
+ useEffect(() => {
302
+ if (!runtime) return
303
+ return runtime.subscribe(refresh)
304
+ }, [runtime, refresh])
305
+
306
+ // On focus: a paused/frozen/admission fact can go stale while this screen
307
+ // was backgrounded. `loadExpoRouter().useFocusEffect` is a hook, but the
308
+ // module is cached after the first call, so it is the exact same function
309
+ // reference on every render — a stable, unconditional call per render,
310
+ // which is what the rules of hooks actually require.
311
+ loadExpoRouter().useFocusEffect(
312
+ useCallback(() => {
313
+ refresh()
314
+ // Only re-fetch on (re)focus, not on every render while focused.
315
+ // eslint-disable-next-line react-hooks/exhaustive-deps
316
+ }, [runtime, key])
317
+ )
318
+
319
+ return { status, loading, refresh }
320
+ }
@@ -1,8 +1,9 @@
1
- import { useEffect, useRef, useState } from 'react'
2
- import { getOnline, subscribeOnline } from '@bsv/expo-wallet-toolbox'
1
+ import { useEffect, useState } from 'react'
2
+ import { getOnline, probeOnline, subscribeOnline } from '@bsv/expo-wallet-toolbox'
3
3
 
4
4
  /**
5
- * How long a device must keep reporting offline before the UI says so.
5
+ * How long a device must keep reporting offline before the UI even asks whether
6
+ * it is.
6
7
  *
7
8
  * Connectivity flaps: NetInfo emits during handovers, on waking, and while a
8
9
  * native probe is still settling, and the first of those emissions can arrive
@@ -13,40 +14,84 @@ import { getOnline, subscribeOnline } from '@bsv/expo-wallet-toolbox'
13
14
  */
14
15
  export const OFFLINE_CONFIRM_MS = 2500
15
16
 
17
+ /**
18
+ * How often an offline claim is put to the network again while it stands.
19
+ *
20
+ * NetInfo will not emit again for a snapshot that is merely out of date, so
21
+ * left to NetInfo alone a wrong banner would stay until the next network
22
+ * change. This is what lets it clear itself.
23
+ */
24
+ export const OFFLINE_RECHECK_MS = 15_000
25
+
16
26
  /**
17
27
  * Starts optimistic. A first render that wrongly says "online" costs a failed
18
28
  * request; a first render that wrongly says "offline" hides the online payment
19
29
  * rails from a user who has signal, which is worse.
30
+ *
31
+ * NetInfo's offline verdict is a claim, not a fact. On iOS it is a cached
32
+ * reachability snapshot (the OS sends no callbacks while the app is suspended)
33
+ * plus an HTTP probe of a Google host, and either can read offline for a phone
34
+ * whose connection works. So once a report has held for `confirmMs`, a real
35
+ * request to the wallet's own hosts decides: only if that also fails does the
36
+ * UI say offline, and while it does the request is repeated every `recheckMs`.
20
37
  */
21
- export function useOnline(confirmMs: number = OFFLINE_CONFIRM_MS): boolean {
38
+ export function useOnline(confirmMs: number = OFFLINE_CONFIRM_MS, recheckMs: number = OFFLINE_RECHECK_MS): boolean {
22
39
  const [online, setOnline] = useState(true)
23
- // Held in a ref so a pending confirmation survives re-renders and is cleared
24
- // the moment connectivity returns.
25
- const pendingOffline = useRef<ReturnType<typeof setTimeout> | null>(null)
26
40
 
27
41
  useEffect(() => {
28
42
  let cancelled = false
43
+ /** NetInfo's latest verdict is offline: the claim being put to the network. */
44
+ let claimedOffline = false
45
+ let warned = false
46
+ let checking = false
47
+ let timer: ReturnType<typeof setTimeout> | null = null
29
48
 
30
- const clearPending = () => {
31
- if (pendingOffline.current !== null) {
32
- clearTimeout(pendingOffline.current)
33
- pendingOffline.current = null
49
+ const clearTimer = () => {
50
+ if (timer !== null) {
51
+ clearTimeout(timer)
52
+ timer = null
53
+ }
54
+ }
55
+
56
+ const schedule = (ms: number) => {
57
+ timer = setTimeout(() => {
58
+ timer = null
59
+ void verify()
60
+ }, ms)
61
+ }
62
+
63
+ /** Asks the network. Repeats for as long as NetInfo keeps insisting on offline. */
64
+ const verify = async () => {
65
+ checking = true
66
+ let reached = false
67
+ try {
68
+ reached = (await probeOnline()) === true
69
+ } catch {
70
+ // A probe that cannot even run is an offline answer, not a crash.
71
+ }
72
+ checking = false
73
+ // Superseded while the request was out: connectivity came back, or unmounted.
74
+ if (cancelled || !claimedOffline) return
75
+ if (reached && !warned) {
76
+ warned = true
77
+ console.warn('[net] NetInfo reports offline but a live request got through; treating as online')
34
78
  }
79
+ setOnline(reached)
80
+ schedule(recheckMs)
35
81
  }
36
82
 
37
- /** Online applies at once; offline only after it has held for `confirmMs`. */
38
83
  const apply = (next: boolean) => {
39
84
  if (cancelled) return
85
+ claimedOffline = !next
40
86
  if (next) {
41
- clearPending()
87
+ clearTimer()
88
+ warned = false
42
89
  setOnline(true)
43
90
  return
44
91
  }
45
- if (pendingOffline.current !== null) return
46
- pendingOffline.current = setTimeout(() => {
47
- pendingOffline.current = null
48
- if (!cancelled) setOnline(false)
49
- }, confirmMs)
92
+ // Already waiting out the window, or mid-request: that pass covers this report.
93
+ if (timer !== null || checking) return
94
+ schedule(confirmMs)
50
95
  }
51
96
 
52
97
  void getOnline()
@@ -61,10 +106,10 @@ export function useOnline(confirmMs: number = OFFLINE_CONFIRM_MS): boolean {
61
106
 
62
107
  return () => {
63
108
  cancelled = true
64
- clearPending()
109
+ clearTimer()
65
110
  unsubscribe()
66
111
  }
67
- }, [confirmMs])
112
+ }, [confirmMs, recheckMs])
68
113
 
69
114
  return online
70
115
  }
@@ -4,6 +4,13 @@
4
4
  * excludes vault funds). Refreshes on txStatusVersion bumps and on demand
5
5
  * after a transfer.
6
6
  *
7
+ * The figure lives in a module-level store rather than in each caller's state,
8
+ * so every mounted reader shows the same number and a screen that mounts after
9
+ * a read starts from it instead of from "unknown" — which both screens render
10
+ * as `balance ?? 0`, making a funded vault look emptied. The store is keyed to
11
+ * the permissions manager it was read through, so a wallet switch reads as
12
+ * unknown rather than showing the previous wallet's vault.
13
+ *
7
14
  * FROZEN while a transfer is mid-flight (ceremony phase 'preparing' /
8
15
  * 'broadcasting'): in that window the spent vault UTXO is gone and its change
9
16
  * is still unsent, so a fetch reads 0 — a partial withdrawal would flash
@@ -11,18 +18,110 @@
11
18
  * transition refetches, covering any txStatusVersion bumps the freeze
12
19
  * swallowed.
13
20
  */
14
- import { useCallback, useEffect, useRef, useState } from 'react'
21
+ import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'
15
22
  import { useWallet, useVault, getVaultBalance, type VaultWallet } from '@bsv/expo-wallet-toolbox'
16
23
 
24
+ /**
25
+ * How long the store keeps showing a transfer's expected figure while reads
26
+ * still disagree with it. The freeze above covers the ceremony itself; this
27
+ * covers the tail AFTER it, where a read is successful and wrong.
28
+ *
29
+ * Measured in TIME, not in reads. Every mounted screen answers every
30
+ * invalidation and the monitor bumps txStatusVersion besides, so a budget
31
+ * counted in reads is spent in a second or two by sheer traffic — nothing to
32
+ * do with how long the wallet actually takes to agree. Retries back off so a
33
+ * long window costs a handful of reads rather than a hundred; each one is a
34
+ * full authenticated vault scan over 45 KB scripts.
35
+ */
36
+ const SETTLE_WINDOW_MS = 30_000
37
+ const SETTLE_FIRST_DELAY_MS = 300
38
+ const SETTLE_MAX_DELAY_MS = 5_000
39
+
40
+ /** The manager `cached` was read through; a different one reads as unknown. */
41
+ let cacheKey: unknown = null
42
+ let cached: number | null = null
43
+ /** The figure a transfer says is coming, and the moment the store stops
44
+ * discarding reads that disagree with it. */
45
+ let expected: number | null = null
46
+ let expectedUntil = 0
47
+ let settleDelay = SETTLE_FIRST_DELAY_MS
48
+ let settleTimer: ReturnType<typeof setTimeout> | undefined
49
+ /** Bumped to ask every mounted reader to fetch again. */
50
+ let version = 0
51
+
52
+ const readers = new Set<() => void>()
53
+ const notify = (): void => {
54
+ for (const onStoreChange of [...readers]) onStoreChange()
55
+ }
56
+ const subscribe = (onStoreChange: () => void): (() => void) => {
57
+ readers.add(onStoreChange)
58
+ return () => {
59
+ readers.delete(onStoreChange)
60
+ }
61
+ }
62
+
63
+ const bumpVersion = (): void => {
64
+ version++
65
+ notify()
66
+ }
67
+
68
+ const clearSettle = (): void => {
69
+ expected = null
70
+ expectedUntil = 0
71
+ settleDelay = SETTLE_FIRST_DELAY_MS
72
+ if (settleTimer !== undefined) {
73
+ clearTimeout(settleTimer)
74
+ settleTimer = undefined
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Publish the figure a just-completed transfer produces, before any read can
80
+ * confirm it. Callers own the arithmetic: they know what they moved.
81
+ *
82
+ * It publishes under whichever manager last read a balance, which is always
83
+ * the current one by the time a transfer can run — `canRun` requires a
84
+ * non-null balance, so a successful read has already happened.
85
+ */
86
+ export function expectVaultBalance(satoshis: number): void {
87
+ clearSettle()
88
+ cached = satoshis
89
+ expected = satoshis
90
+ expectedUntil = Date.now() + SETTLE_WINDOW_MS
91
+ notify()
92
+ }
93
+
94
+ /** Commit a successful read, unless it still disagrees with what a transfer
95
+ * said was coming and the budget for waiting it out is not yet spent. */
96
+ function commitRead(key: unknown, satoshis: number): void {
97
+ if (key !== cacheKey) clearSettle()
98
+ if (expected !== null && satoshis !== expected && Date.now() < expectedUntil) {
99
+ if (settleTimer === undefined) {
100
+ const delay = settleDelay
101
+ settleDelay = Math.min(settleDelay * 2, SETTLE_MAX_DELAY_MS)
102
+ settleTimer = setTimeout(() => {
103
+ settleTimer = undefined
104
+ bumpVersion()
105
+ }, delay)
106
+ }
107
+ return
108
+ }
109
+ clearSettle()
110
+ cacheKey = key
111
+ cached = satoshis
112
+ notify()
113
+ }
114
+
17
115
  export function useVaultBalance(): { balance: number | null; loading: boolean; refresh: () => void } {
18
116
  const { managers, adminOriginator, txStatusVersion } = useWallet()
19
117
  const { state: vaultState } = useVault()
118
+ const pm = managers?.permissionsManager
20
119
  // The zero-read window: both transfer paths note 'preparing' BEFORE their
21
120
  // createAction and stay busy until the broadcast settles (transfers.ts).
22
121
  const transferInFlight = vaultState.phase === 'preparing' || vaultState.phase === 'broadcasting'
23
- const [balance, setBalance] = useState<number | null>(null)
122
+ const balance = useSyncExternalStore(subscribe, () => (cacheKey === pm ? cached : null))
123
+ const refreshVersion = useSyncExternalStore(subscribe, () => version)
24
124
  const [loading, setLoading] = useState(false)
25
- const [refreshVersion, setRefreshVersion] = useState(0)
26
125
  // Read the latest figure without making balance changes trigger another read.
27
126
  const balanceRef = useRef<number | null>(null)
28
127
  balanceRef.current = balance
@@ -30,12 +129,11 @@ export function useVaultBalance(): { balance: number | null; loading: boolean; r
30
129
  const pendingRef = useRef<(() => Promise<void>) | null>(null)
31
130
 
32
131
  const refresh = useCallback(() => {
33
- setRefreshVersion(prev => prev + 1)
132
+ bumpVersion()
34
133
  }, [])
35
134
 
36
135
  useEffect(() => {
37
136
  let cancelled = false
38
- const pm = managers?.permissionsManager
39
137
  if (transferInFlight || !pm) {
40
138
  setLoading(false)
41
139
  return
@@ -45,7 +143,7 @@ export function useVaultBalance(): { balance: number | null; loading: boolean; r
45
143
  if (balanceRef.current === null) setLoading(true)
46
144
  try {
47
145
  const next = await getVaultBalance(pm as unknown as VaultWallet, adminOriginator)
48
- if (!cancelled) setBalance(next)
146
+ if (!cancelled) commitRead(pm, next)
49
147
  } catch {
50
148
  // Leave the last known balance in place on a transient failure.
51
149
  } finally {
@@ -75,7 +173,7 @@ export function useVaultBalance(): { balance: number | null; loading: boolean; r
75
173
  cancelled = true
76
174
  if (pendingRef.current === read) pendingRef.current = null
77
175
  }
78
- }, [managers?.permissionsManager, adminOriginator, txStatusVersion, transferInFlight, refreshVersion])
176
+ }, [pm, adminOriginator, txStatusVersion, transferInFlight, refreshVersion])
79
177
 
80
178
  return { balance, loading, refresh }
81
179
  }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Which vault outputs are committed to the current key set — the source of the
3
+ * vault screen's badges ("{{count}} deposits not yet open to {{nickname}}",
4
+ * "{{count}} deposits still open to a removed key") and of the Remove-key
5
+ * safety check (spec §3.4).
6
+ *
7
+ * Same invalidation contract as useVaultBalance: read on mount, on every
8
+ * txStatusVersion bump and on refresh(); frozen while a transfer is in flight
9
+ * (the spent outputs are gone and the re-vaulted remainder not yet visible, so
10
+ * a read in that window is wrong), with one read when the window closes.
11
+ *
12
+ * `null` means "nothing readable yet": before the first read lands, and
13
+ * whenever there is no built wallet. It is deliberately not an empty coverage
14
+ * record — a caller deciding whether a key removal would orphan an output
15
+ * must not mistake "could not look" for "looked and saw nothing".
16
+ */
17
+ import { useCallback, useEffect, useState } from 'react'
18
+ import { useWallet, useVault, getVaultKeyCoverage, type VaultKeyCoverage, type VaultWallet } from '@bsv/expo-wallet-toolbox'
19
+
20
+ export function useVaultCoverage(): { coverage: VaultKeyCoverage | null; refresh: () => void } {
21
+ const { managers, adminOriginator, txStatusVersion } = useWallet()
22
+ const { state: vaultState } = useVault()
23
+ const transferInFlight = vaultState.phase === 'preparing' || vaultState.phase === 'broadcasting'
24
+ const [coverage, setCoverage] = useState<VaultKeyCoverage | null>(null)
25
+ const [refreshVersion, setRefreshVersion] = useState(0)
26
+
27
+ const refresh = useCallback(() => {
28
+ setRefreshVersion(prev => prev + 1)
29
+ }, [])
30
+
31
+ useEffect(() => {
32
+ const pm = managers?.permissionsManager
33
+ if (!pm) {
34
+ setCoverage(null)
35
+ return
36
+ }
37
+ if (transferInFlight) return
38
+ let cancelled = false
39
+ getVaultKeyCoverage(pm as unknown as VaultWallet, adminOriginator)
40
+ .then(next => {
41
+ if (!cancelled) setCoverage(next)
42
+ })
43
+ .catch(() => {
44
+ // Leave the last known coverage in place on a transient failure.
45
+ })
46
+ return () => {
47
+ cancelled = true
48
+ }
49
+ }, [managers?.permissionsManager, adminOriginator, txStatusVersion, transferInFlight, refreshVersion])
50
+
51
+ return { coverage, refresh }
52
+ }
@@ -7,7 +7,8 @@ import {
7
7
  getRegisteredDbs,
8
8
  registerDb,
9
9
  selectLatestDb,
10
- parseTimestampFromFilename
10
+ parseTimestampFromFilename,
11
+ prepareSqliteImageForDeserialize
11
12
  } from '@bsv/expo-wallet-toolbox'
12
13
  import { showAlert } from './components/ui/AlertCard'
13
14
  import { showToast } from './components/ui/Toast'
@@ -138,8 +139,11 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
138
139
  let sourceDb: SQLite.SQLiteDatabase | undefined
139
140
  let destDb: SQLite.SQLiteDatabase | undefined
140
141
  try {
141
- // Deserialize the imported bytes into an in-memory database
142
- sourceDb = await SQLite.deserializeDatabaseAsync(bytes)
142
+ // Deserialize the imported bytes into an in-memory database. Exports of
143
+ // the WAL-mode wallet DB carry a WAL header, which the in-memory VFS
144
+ // cannot open (SQLITE_CANTOPEN), so the header is rewritten to
145
+ // rollback-journal mode first.
146
+ sourceDb = await SQLite.deserializeDatabaseAsync(prepareSqliteImageForDeserialize(bytes))
143
147
 
144
148
  // Open (or create) a file-backed database with the target filename.
145
149
  // This places the file in the default expo-sqlite database directory.