@bsv/expo-wallet-toolbox 0.1.2 → 0.2.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.
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Route target for the `dismissTo` props on this package's payment screens.
3
+ *
4
+ * expo-router's `router.dismissTo` takes `Href`, which is not a fixed type: a
5
+ * host app with `experiments.typedRoutes` on generates a `declare module
6
+ * 'expo-router'` augmentation narrowing `Href` to that app's literal route
7
+ * union. Because that augmentation is global and this package ships raw `.ts`
8
+ * that the host compiles itself, a `dismissTo?: string` prop stops being
9
+ * assignable to `dismissTo()` inside our own files (TS2345). Typing the prop
10
+ * as `Href` resolves against whatever the host's `Href` is: a typed-routes
11
+ * host gets its routes checked, a host without it sees `Href` ~ `string`.
12
+ *
13
+ * `import type` is fully erased at compile time and emits no `require`, so
14
+ * this does not reintroduce the untransformed-JSX problem that the lazy
15
+ * `loadExpoRouter()` pattern exists to avoid.
16
+ */
17
+ import type { Href } from 'expo-router'
18
+
19
+ export type DismissTarget = Href
@@ -11,48 +11,75 @@ import { useEffect, useRef, useState } from 'react'
11
11
  import AsyncStorage from '@react-native-async-storage/async-storage'
12
12
  import { sdk } from '@bsv/wallet-toolbox-mobile'
13
13
  import { useWallet, readWalletBalance } from '@bsv/expo-wallet-toolbox'
14
+ import { storageMatchesNetwork } from '../../core/net/chainMatch'
14
15
 
15
16
  export function useSpendableBalance(): number | null {
16
17
  const { managers, adminOriginator, selectedNetwork, storage, txStatusVersion, walletUserId } = useWallet()
17
- const [balance, setBalance] = useState<number | null>(null)
18
18
  const cacheKey = `cached_wallet_balance_${selectedNetwork}`
19
- // One read at a time; a bump arriving mid-read is served by that read.
19
+ const [balance, setBalance] = useState<{ key: string; value: number } | null>(null)
20
+ // Serialize reads, retaining the latest invalidation while one is in flight.
21
+ // A plain busy flag loses it: the old effect is cancelled, while the new one
22
+ // sees the flag and returns, so neither can update the displayed figure.
20
23
  const inFlightRef = useRef(false)
24
+ const pendingRef = useRef<(() => Promise<void>) | null>(null)
21
25
 
22
26
  useEffect(() => {
23
27
  let cancelled = false
24
- ;(async () => {
25
- const cached = await AsyncStorage.getItem(cacheKey)
26
- if (!cancelled && cached != null) setBalance(prev => (prev == null ? Number(cached) : prev))
27
-
28
- if (inFlightRef.current) return
29
- inFlightRef.current = true
28
+ const refresh = async () => {
29
+ try {
30
+ const cached = await AsyncStorage.getItem(cacheKey)
31
+ const value = cached == null ? NaN : Number(cached)
32
+ if (!cancelled && Number.isFinite(value)) {
33
+ setBalance(prev => prev?.key === cacheKey ? prev : { key: cacheKey, value })
34
+ }
35
+ } catch {
36
+ // A broken cache must not prevent the live read below.
37
+ }
38
+ if (cancelled) return
39
+ // During a network rebuild the previous chain's storage can still be
40
+ // mounted. Never read it or write its figure into the new chain's cache.
41
+ if (storage && !storageMatchesNetwork(storage, selectedNetwork)) return
30
42
  try {
31
43
  let total: number | null = null
32
44
  if (storage && walletUserId != null) {
33
45
  total = await readWalletBalance(storage, walletUserId)
34
46
  }
47
+ if (cancelled) return
35
48
  if (total == null) {
36
49
  const pm = managers?.permissionsManager
37
50
  if (!pm) return
38
51
  const { totalOutputs } = await pm.listOutputs({ basket: sdk.specOpWalletBalance }, adminOriginator)
39
52
  total = totalOutputs ?? 0
40
53
  }
41
- if (!cancelled) setBalance(total)
54
+ if (cancelled) return
55
+ setBalance(prev => prev?.key === cacheKey && prev.value === total ? prev : { key: cacheKey, value: total })
42
56
  await AsyncStorage.setItem(cacheKey, String(total))
43
57
  } catch {
44
58
  // Keep the last known figure: a failed read is not "zero satoshis".
45
- } finally {
46
- inFlightRef.current = false
47
59
  }
48
- })()
60
+ }
61
+
62
+ pendingRef.current = refresh
63
+ if (!inFlightRef.current) {
64
+ inFlightRef.current = true
65
+ void (async () => {
66
+ try {
67
+ while (pendingRef.current) {
68
+ const next = pendingRef.current
69
+ pendingRef.current = null
70
+ await next()
71
+ }
72
+ } finally {
73
+ inFlightRef.current = false
74
+ }
75
+ })()
76
+ }
49
77
  return () => {
50
78
  cancelled = true
79
+ if (pendingRef.current === refresh) pendingRef.current = null
51
80
  }
52
- // Data deps only — see app/index.tsx on why callback identity must not
53
- // be a dependency here.
54
- // eslint-disable-next-line react-hooks/exhaustive-deps
55
- }, [cacheKey, storage, walletUserId, managers?.permissionsManager, txStatusVersion])
81
+ }, [cacheKey, selectedNetwork, storage, walletUserId, managers?.permissionsManager, adminOriginator, txStatusVersion])
56
82
 
57
- return balance
83
+ // Hide the old chain's figure immediately, before the new effect reads cache.
84
+ return balance?.key === cacheKey ? balance.value : null
58
85
  }
@@ -22,29 +22,60 @@ export function useVaultBalance(): { balance: number | null; loading: boolean; r
22
22
  const transferInFlight = vaultState.phase === 'preparing' || vaultState.phase === 'broadcasting'
23
23
  const [balance, setBalance] = useState<number | null>(null)
24
24
  const [loading, setLoading] = useState(false)
25
- // Kept in a ref so `refresh` has a stable identity. With `balance` in its deps
26
- // every callers' effect that lists `refresh` (app/vault.tsx does) re-ran and
27
- // refetched each time the figure changed.
25
+ const [refreshVersion, setRefreshVersion] = useState(0)
26
+ // Read the latest figure without making balance changes trigger another read.
28
27
  const balanceRef = useRef<number | null>(null)
29
28
  balanceRef.current = balance
29
+ const inFlightRef = useRef(false)
30
+ const pendingRef = useRef<(() => Promise<void>) | null>(null)
30
31
 
31
32
  const refresh = useCallback(() => {
32
- const pm = managers?.permissionsManager
33
- if (!pm) return
34
- setLoading(prev => (balanceRef.current === null ? true : prev))
35
- getVaultBalance(pm as unknown as VaultWallet, adminOriginator)
36
- .then(setBalance)
37
- .catch(() => {
38
- /* leave the last known balance in place on a transient failure */
39
- })
40
- .finally(() => setLoading(false))
41
- }, [managers?.permissionsManager, adminOriginator])
33
+ setRefreshVersion(prev => prev + 1)
34
+ }, [])
42
35
 
43
36
  useEffect(() => {
44
- if (transferInFlight) return // freeze: a fetch now would read a false 0
45
- refresh() // also runs on the busy→idle transition, adopting the real figure
46
- // eslint-disable-next-line react-hooks/exhaustive-deps
47
- }, [managers?.permissionsManager, adminOriginator, txStatusVersion, transferInFlight])
37
+ let cancelled = false
38
+ const pm = managers?.permissionsManager
39
+ if (transferInFlight || !pm) {
40
+ setLoading(false)
41
+ return
42
+ }
43
+
44
+ const read = async () => {
45
+ if (balanceRef.current === null) setLoading(true)
46
+ try {
47
+ const next = await getVaultBalance(pm as unknown as VaultWallet, adminOriginator)
48
+ if (!cancelled) setBalance(next)
49
+ } catch {
50
+ // Leave the last known balance in place on a transient failure.
51
+ } finally {
52
+ if (!cancelled) setLoading(false)
53
+ }
54
+ }
55
+
56
+ // Retain only the latest invalidation while a read is in flight. Cleanup
57
+ // also discards results from reads that started before the transfer freeze.
58
+ pendingRef.current = read
59
+ if (!inFlightRef.current) {
60
+ inFlightRef.current = true
61
+ void (async () => {
62
+ try {
63
+ while (pendingRef.current) {
64
+ const next = pendingRef.current
65
+ pendingRef.current = null
66
+ await next()
67
+ }
68
+ } finally {
69
+ inFlightRef.current = false
70
+ }
71
+ })()
72
+ }
73
+
74
+ return () => {
75
+ cancelled = true
76
+ if (pendingRef.current === read) pendingRef.current = null
77
+ }
78
+ }, [managers?.permissionsManager, adminOriginator, txStatusVersion, transferInFlight, refreshVersion])
48
79
 
49
80
  return { balance, loading, refresh }
50
81
  }
package/ui/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export const CANARY_UI = 'ui'
2
2
 
3
3
  // Shared UI primitives (components/ui)
4
+ export type { DismissTarget } from './dismissTarget'
4
5
  export { showAlert, AlertHost } from './components/ui/AlertCard'
5
6
  export type { AlertButton, AlertOptions } from './components/ui/AlertCard'
6
7
  export { showChoiceSheet, choiceSheetOrder } from './components/ui/ChoiceSheet'
@@ -122,7 +122,7 @@ function parsePairingUri(raw: string): ParseResult {
122
122
  }
123
123
 
124
124
  if (!/^0[23][0-9a-fA-F]{64}$/.test(backendIdentityKey)) {
125
- return { params: null, error: 'Backend identity key is not a valid public key' }
125
+ return { params: null, error: 'Backend identifier is not valid' }
126
126
  }
127
127
 
128
128
  let proto: unknown
@@ -42,6 +42,7 @@ import {
42
42
  import { getPendingCorruptNotice, readUnprocessedPending } from '../../core/localpay/pending'
43
43
  import { nearbyAdvisory } from '../../core/localpay/nearbyAdvisory'
44
44
  import { NearbyAdvisoryModal } from '../components/pay/NearbyAdvisoryModal'
45
+ import type { DismissTarget } from '../dismissTarget'
45
46
 
46
47
  /**
47
48
  * @expo/vector-icons' index barrel re-exports every icon set (AntDesign,
@@ -99,7 +100,7 @@ export interface PayScreenProps {
99
100
  * screen somewhere other than the app root — e.g. a browser app that puts
100
101
  * the wallet at `/wallet` — should pass that route here instead.
101
102
  */
102
- dismissTo?: string
103
+ dismissTo?: DismissTarget
103
104
  }
104
105
 
105
106
  export function PayScreen({ dismissTo = '/' }: PayScreenProps = {}) {
@@ -181,6 +182,7 @@ export function PayScreen({ dismissTo = '/' }: PayScreenProps = {}) {
181
182
  )
182
183
  /** Get side: the hub's raw amount, carried into the method. */
183
184
  const [requestSats, setRequestSats] = useState('')
185
+ const initialNearbyRequest = useMemo(() => ({ sats: requestSatsFrom(requestSats) }), [requestSats])
184
186
  // One camera raise per deep link; a cancelled advisory must not re-open it.
185
187
  const [scanOnMount, setScanOnMount] = useState(paramCell === 'pay-nearby')
186
188
 
@@ -387,7 +389,7 @@ export function PayScreen({ dismissTo = '/' }: PayScreenProps = {}) {
387
389
  switch (method) {
388
390
  case 'get-nearby':
389
391
  return nearbyAdvisorySeen ? (
390
- <NearbyFlow role="payee" initialRequest={{ sats }} onExit={goBack} dismissTo={dismissTo} />
392
+ <NearbyFlow role="payee" initialRequest={initialNearbyRequest} onExit={goBack} dismissTo={dismissTo} />
391
393
  ) : null
392
394
  case 'get-handle':
393
395
  return <HandleReceive initialSats={sats} dismissTo={dismissTo} />
@@ -1090,6 +1090,7 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1090
1090
 
1091
1091
  return (
1092
1092
  <ActivityRow
1093
+ currency={currency}
1093
1094
  action={item}
1094
1095
  rowKey={key}
1095
1096
  offlineStatus={offline?.status}
@@ -1102,12 +1103,13 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1102
1103
  onAbort={onAbort}
1103
1104
  onSendPaymentDetails={onSendPaymentDetails}
1104
1105
  onSendAgain={onFailedSendAgain}
1105
- onCancelParked={txid => void onCancelParked(txid)}
1106
+ onCancelParked={onCancelParked}
1106
1107
  />
1107
1108
  )
1108
1109
  },
1109
1110
  [
1110
1111
  colors,
1112
+ currency,
1111
1113
  offlineByTxid,
1112
1114
  busyRow,
1113
1115
  busyLabel,