@bsv/expo-wallet-toolbox 0.3.1 → 0.5.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 (119) hide show
  1. package/CHANGELOG.md +311 -0
  2. package/README.md +52 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +21 -18
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +413 -23
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +107 -14
  12. package/core/localpay/build.ts +674 -37
  13. package/core/localpay/codec.ts +68 -5
  14. package/core/localpay/pending.ts +240 -22
  15. package/core/localpay/settlementAck.ts +149 -0
  16. package/core/localpay/types.ts +14 -1
  17. package/core/localpay/verify.ts +118 -69
  18. package/core/mandala/abortGuard.ts +134 -0
  19. package/core/mandala/basketMigration.ts +166 -0
  20. package/core/mandala/bundle.ts +244 -0
  21. package/core/mandala/createRuntime.ts +2437 -0
  22. package/core/mandala/drain.ts +670 -0
  23. package/core/mandala/permissionModule.ts +642 -0
  24. package/core/mandala/resendTransfer.ts +175 -0
  25. package/core/mandala/runtime.ts +357 -0
  26. package/core/mandala/settlementStore.ts +412 -0
  27. package/core/mandala/types.ts +290 -0
  28. package/core/offline/cancelParked.ts +94 -1
  29. package/core/offline/payerHold.ts +152 -12
  30. package/core/offline/tokenFrames.ts +197 -0
  31. package/core/parsePeerPayURI.ts +70 -17
  32. package/core/pay/rails/address.ts +51 -3
  33. package/core/pay/rails/handle.ts +88 -9
  34. package/core/pay/rails/index.ts +16 -6
  35. package/core/pay/rails/nearby.ts +114 -4
  36. package/core/services/capWalletArgs.ts +8 -9
  37. package/core/services/externalOrigin.ts +39 -0
  38. package/core/services/vault/VaultKeyService.ts +912 -251
  39. package/core/services/vault/ceremony.ts +435 -367
  40. package/core/services/vault/ceremonyHost.ts +27 -21
  41. package/core/services/vault/devMock.ts +30 -7
  42. package/core/services/vault/driver.ts +95 -41
  43. package/core/services/vault/guard.ts +514 -56
  44. package/core/services/vault/hardwareLease.ts +22 -0
  45. package/core/services/vault/mockYubiKey.ts +258 -90
  46. package/core/services/vault/pivReset.ts +145 -0
  47. package/core/services/vault/r1comb.ts +976 -0
  48. package/core/services/vault/session.ts +93 -26
  49. package/core/services/vault/transfers.ts +2617 -747
  50. package/core/services/vault/types.ts +100 -43
  51. package/core/services/vault/vaultStore.ts +991 -74
  52. package/core/services/walletConnectionValidation.ts +293 -0
  53. package/core/services/walletServiceConfig.ts +19 -24
  54. package/core/storage/StorageExpoSQLite.ts +382 -56
  55. package/core/storage/dbImage.ts +48 -0
  56. package/core/storage/methods/findSql.ts +0 -54
  57. package/core/storage/methods/listOutputsSql.ts +7 -3
  58. package/core/storage/methods/offlineActions.ts +15 -0
  59. package/core/storage/methods/processOfflineActions.ts +263 -6
  60. package/core/storage/methods/walletBalanceSql.ts +16 -4
  61. package/core/storage/schema/createTables.ts +123 -0
  62. package/core/storage/sqlUpdateValue.ts +24 -0
  63. package/core/toolboxConfig.ts +240 -0
  64. package/core/walletRepair/runWalletCheck.ts +19 -2
  65. package/package.json +25 -24
  66. package/ui/components/QRScanner.tsx +1 -1
  67. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  68. package/ui/components/pay/AssetPicker.tsx +184 -0
  69. package/ui/components/pay/AvailableBalance.tsx +33 -2
  70. package/ui/components/pay/HandleReceive.tsx +213 -50
  71. package/ui/components/pay/NearbyFlow.tsx +616 -69
  72. package/ui/components/pay/PayForm.tsx +73 -8
  73. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  74. package/ui/components/pay/RecipientField.tsx +49 -4
  75. package/ui/components/pay/RequestHub.tsx +68 -8
  76. package/ui/components/pay/ResultBanner.tsx +41 -4
  77. package/ui/components/pay/UniversalSend.tsx +534 -30
  78. package/ui/components/pay/tokenSendCopy.ts +116 -0
  79. package/ui/components/pay/useRecipientInput.ts +36 -7
  80. package/ui/components/ui/PermissionSheet.tsx +65 -4
  81. package/ui/components/ui/Sheet.tsx +9 -2
  82. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  83. package/ui/components/vault/KeyChooser.tsx +96 -0
  84. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  85. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  86. package/ui/components/wallet/ActivityRow.tsx +101 -17
  87. package/ui/components/wallet/AmountInput.tsx +77 -25
  88. package/ui/components/wallet/AssetAmount.tsx +95 -0
  89. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  90. package/ui/components/wallet/tokenEviction.ts +65 -0
  91. package/ui/hooks/useExportWalletData.ts +39 -0
  92. package/ui/hooks/useMandala.ts +303 -0
  93. package/ui/hooks/useVaultBalance.ts +105 -7
  94. package/ui/hooks/useVaultCoverage.ts +52 -0
  95. package/ui/importDatabases.ts +7 -3
  96. package/ui/index.ts +50 -7
  97. package/ui/screens/ConnectionsScreen.tsx +46 -29
  98. package/ui/screens/PairScreen.tsx +12 -12
  99. package/ui/screens/PayScreen.tsx +130 -10
  100. package/ui/screens/SettingsScreen.tsx +18 -9
  101. package/ui/screens/VaultScreen.tsx +925 -171
  102. package/ui/screens/VaultTransferScreen.tsx +376 -123
  103. package/ui/screens/WalletCheckScreen.tsx +10 -1
  104. package/ui/screens/WalletConfigScreen.tsx +42 -20
  105. package/ui/screens/WalletHomeScreen.tsx +417 -86
  106. package/ui/screens/homeBadges.ts +9 -1
  107. package/ui/screens/tokenRowTitle.ts +68 -0
  108. package/ui/tokenFormat.ts +108 -0
  109. package/ui/tokenSeen.ts +75 -0
  110. package/ui/tokenStatus.ts +79 -0
  111. package/assets/sounds/vault-close.wav +0 -0
  112. package/assets/sounds/vault-open.wav +0 -0
  113. package/core/services/vault/k1.ts +0 -75
  114. package/core/services/vault/sealing.ts +0 -84
  115. package/core/services/vault/vaultDerivation.ts +0 -152
  116. package/core/services/vault/vaultPassphrase.ts +0 -287
  117. package/ui/components/vault/PassphraseField.tsx +0 -306
  118. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  119. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -0,0 +1,261 @@
1
+ /**
2
+ * The coin switcher dropdown (design 4a, 2026-09-16).
3
+ *
4
+ * Home's coin pill, now in the top bar, IS the switcher; this is what it
5
+ * opens — a small card anchored just under the top bar, with a tail
6
+ * pointing back at the pill, rather than a bottom drawer. One row per kind
7
+ * of money the wallet holds — BSV first, then every stablecoin — each with
8
+ * its figure, and a checkmark on the one the screen is currently showing.
9
+ * Picking a row swaps the whole wallet to that coin: hero figure, activity
10
+ * list, and what Pay / Get paid are armed with. The asset question is asked
11
+ * here, once, so the Pay screen never has to ask it again.
12
+ *
13
+ * Each row is the ticker over the asset's full name — "BSV" / "Bitcoin SV",
14
+ * "CHFB" / "CHF on BSV" — so the figure on the right always reads against a
15
+ * denomination you can pronounce, not just a four-letter code.
16
+ *
17
+ * Rendered only when something is held — a wallet that has never held a token
18
+ * never mounts this, so it keeps today's screen byte for byte.
19
+ */
20
+ import React, { useEffect, useRef, useState } from 'react'
21
+ import { Pressable, StyleSheet, Text, TouchableOpacity, View } from 'react-native'
22
+ import Animated, { runOnJS, useAnimatedStyle, useSharedValue, withTiming } from 'react-native-reanimated'
23
+ import { hitTargets, radii, spacing, typography, useTheme } from '@bsv/expo-wallet-toolbox'
24
+ import type { TokenBalance } from '../../../core/mandala/runtime'
25
+ import { tokenAmountParts } from '../../tokenFormat'
26
+
27
+ /**
28
+ * @expo/vector-icons' index barrel re-exports every icon set, one of which
29
+ * reaches expo-font -> expo-asset -- untransformed ESM Jest cannot parse when
30
+ * eagerly pulled in via the `ui` package barrel. Loaded lazily, same pattern
31
+ * as this package's other native-module-boundary fixes.
32
+ */
33
+ type IoniconsComponent = typeof import('@expo/vector-icons').Ionicons
34
+ let ioniconsComponent: IoniconsComponent | undefined
35
+ function loadIonicons(): IoniconsComponent {
36
+ if (!ioniconsComponent) {
37
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
38
+ ioniconsComponent = require('@expo/vector-icons').Ionicons as IoniconsComponent
39
+ }
40
+ return ioniconsComponent
41
+ }
42
+
43
+ /** The literal, like `mainnet`/`testnet`: a translated "BSV" would be byte-identical in every locale. */
44
+ export const BSV_LABEL = 'BSV'
45
+ /** BSV's own full name, the way a token's `asset.label` names it — a proper noun, not translated. */
46
+ export const BSV_FULL_NAME = 'Bitcoin SV'
47
+
48
+ export interface AssetSwitcherDropdownProps {
49
+ visible: boolean
50
+ onClose: () => void
51
+ /** Where the top bar ends, in the same coordinate space this component is
52
+ * mounted in — the card hangs just under it, tail pointing up at the pill. */
53
+ top: number
54
+ /** Held stablecoins, in the order the runtime reports them. */
55
+ balances: TokenBalance[]
56
+ /** `null` is BSV. */
57
+ selected: string | null
58
+ onSelect: (assetId: string | null) => void
59
+ /** The BSV figure as the hero draws it; `null` is UNKNOWN and prints nothing. */
60
+ bsv: { value: string; unit: string } | null
61
+ }
62
+
63
+ export default function AssetSwitcherDropdown({
64
+ visible,
65
+ onClose,
66
+ top,
67
+ balances,
68
+ selected,
69
+ onSelect,
70
+ bsv
71
+ }: AssetSwitcherDropdownProps) {
72
+ const { colors } = useTheme()
73
+
74
+ // Fade + scale in place, no gesture — this is a dropdown, not a draggable
75
+ // drawer. Mirrors Sheet's rendered/visible split so content unmounts only
76
+ // once the close animation actually finishes, not the instant the prop flips.
77
+ const [rendered, setRendered] = useState(false)
78
+ const wasVisibleRef = useRef(false)
79
+ const progress = useSharedValue(0)
80
+
81
+ useEffect(() => {
82
+ if (visible) {
83
+ setRendered(true)
84
+ if (!wasVisibleRef.current) {
85
+ progress.value = 0
86
+ progress.value = withTiming(1, { duration: 160 })
87
+ }
88
+ } else if (wasVisibleRef.current) {
89
+ progress.value = withTiming(0, { duration: 120 }, finished => {
90
+ if (finished) runOnJS(setRendered)(false)
91
+ })
92
+ }
93
+ wasVisibleRef.current = visible
94
+ }, [visible, progress])
95
+
96
+ const animatedStyle = useAnimatedStyle(() => ({
97
+ opacity: progress.value,
98
+ transform: [{ scale: 0.95 + progress.value * 0.05 }, { translateY: (1 - progress.value) * -4 }]
99
+ }))
100
+
101
+ const isVisible = visible || rendered
102
+ if (!isVisible) return null
103
+
104
+ const choose = (assetId: string | null) => {
105
+ onSelect(assetId)
106
+ onClose()
107
+ }
108
+
109
+ return (
110
+ <View style={[StyleSheet.absoluteFill, { zIndex: 50 }]} pointerEvents="box-none">
111
+ <Pressable
112
+ style={[StyleSheet.absoluteFill, { zIndex: 10 }]}
113
+ onPress={onClose}
114
+ accessible={true}
115
+ accessibilityRole="button"
116
+ accessibilityLabel="Close"
117
+ accessibilityHint="Dismisses the coin switcher"
118
+ />
119
+ <Animated.View
120
+ style={[
121
+ styles.card,
122
+ {
123
+ top: top + spacing.xs,
124
+ backgroundColor: colors.surfaceRaised,
125
+ borderColor: colors.surfaceRaisedBorder,
126
+ shadowColor: colors.textPrimary
127
+ },
128
+ animatedStyle
129
+ ]}
130
+ >
131
+ {/* The tail: a rotated square peeking out the top edge, pointing back
132
+ at the pill that opened this — the pill sits centred in the top
133
+ bar, and so does this card, so the tail needs no measurement. */}
134
+ <View
135
+ style={[styles.tail, { backgroundColor: colors.surfaceRaised, borderColor: colors.surfaceRaisedBorder }]}
136
+ />
137
+ <View style={styles.list}>
138
+ <CoinRow
139
+ ticker={BSV_LABEL}
140
+ fullName={BSV_FULL_NAME}
141
+ figure={bsv}
142
+ selected={selected === null}
143
+ onPress={() => choose(null)}
144
+ />
145
+ {balances.map(b => (
146
+ <CoinRow
147
+ key={b.asset.assetId}
148
+ ticker={b.asset.ticker}
149
+ fullName={b.asset.label}
150
+ figure={tokenAmountParts(b.baseUnits, b.asset)}
151
+ selected={selected === b.asset.assetId}
152
+ onPress={() => choose(b.asset.assetId)}
153
+ />
154
+ ))}
155
+ </View>
156
+ </Animated.View>
157
+ </View>
158
+ )
159
+ }
160
+
161
+ function CoinRow({
162
+ ticker,
163
+ fullName,
164
+ figure,
165
+ selected,
166
+ onPress
167
+ }: {
168
+ ticker: string
169
+ fullName?: string
170
+ figure: { value: string; unit: string } | null
171
+ selected: boolean
172
+ onPress: () => void
173
+ }) {
174
+ const { colors } = useTheme()
175
+ const Ionicons = loadIonicons()
176
+ const figureText = figure ? `${figure.value} ${figure.unit}`.trim() : ''
177
+ return (
178
+ <TouchableOpacity
179
+ style={[styles.row, selected && { backgroundColor: colors.fill }]}
180
+ onPress={onPress}
181
+ activeOpacity={0.6}
182
+ accessibilityRole="button"
183
+ // The checkmark is not the only signal: state travels with the element.
184
+ accessibilityState={{ selected }}
185
+ accessibilityLabel={[ticker, fullName, figureText].filter(Boolean).join(', ')}
186
+ >
187
+ <View style={styles.body}>
188
+ <Text style={[styles.name, { color: colors.textPrimary }]} numberOfLines={1}>
189
+ {ticker}
190
+ </Text>
191
+ {!!fullName && (
192
+ <Text style={[styles.detail, { color: colors.textSecondary }]} numberOfLines={1}>
193
+ {fullName}
194
+ </Text>
195
+ )}
196
+ </View>
197
+ {figure && (
198
+ <Text style={[styles.figure, { color: colors.textPrimary }]} numberOfLines={1} accessibilityLabel={figureText}>
199
+ {figure.value}
200
+ {figure.unit ? <Text style={[styles.unit, { color: colors.textSecondary }]}> {figure.unit}</Text> : null}
201
+ </Text>
202
+ )}
203
+ <View style={styles.check}>{selected && <Ionicons name="checkmark" size={20} color={colors.accent} />}</View>
204
+ </TouchableOpacity>
205
+ )
206
+ }
207
+
208
+ const styles = StyleSheet.create({
209
+ card: {
210
+ position: 'absolute',
211
+ left: spacing.lg,
212
+ right: spacing.lg,
213
+ // 20, not the sheet radius scale's 24 — this is the design file's own
214
+ // number (Multi-currency wallet options.dc.html, option 4a), chosen so
215
+ // it stays concentric with the row radius below: 20 = 14 (row) + 6 (inset).
216
+ borderRadius: 20,
217
+ borderWidth: StyleSheet.hairlineWidth,
218
+ overflow: 'visible',
219
+ zIndex: 20,
220
+ elevation: 12,
221
+ // Deep and soft rather than tight — the card has to sit clearly in front
222
+ // of the dimmed page behind it, and a small shadow reads as a seam.
223
+ shadowOffset: { width: 0, height: 16 },
224
+ shadowOpacity: 0.22,
225
+ shadowRadius: 30
226
+ },
227
+ tail: {
228
+ position: 'absolute',
229
+ top: -6,
230
+ alignSelf: 'center',
231
+ width: 12,
232
+ height: 12,
233
+ borderTopWidth: StyleSheet.hairlineWidth,
234
+ borderLeftWidth: StyleSheet.hairlineWidth,
235
+ borderTopLeftRadius: 3,
236
+ transform: [{ rotate: '45deg' }]
237
+ },
238
+ list: {
239
+ // 6, so the clipped corner here stays concentric with the card's 20 above
240
+ // (20 = 14 + 6) — a smaller inset left the row's own 14px corner cutting
241
+ // across the card's wider sweep instead of following it.
242
+ padding: 6,
243
+ borderRadius: 20,
244
+ overflow: 'hidden'
245
+ },
246
+ row: {
247
+ flexDirection: 'row',
248
+ alignItems: 'center',
249
+ gap: spacing.md,
250
+ minHeight: hitTargets.minimum,
251
+ paddingVertical: 11,
252
+ paddingHorizontal: 10,
253
+ borderRadius: radii.lg
254
+ },
255
+ body: { flex: 1, minWidth: 0 },
256
+ name: { ...typography.body, fontWeight: '600' },
257
+ detail: { ...typography.footnote, marginTop: 2, fontVariant: ['tabular-nums'] },
258
+ figure: { ...typography.body, fontWeight: '600', fontVariant: ['tabular-nums'] },
259
+ unit: { ...typography.footnote },
260
+ check: { width: 20, alignItems: 'center' }
261
+ })
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The one modal this design spends (ux §6.3).
3
+ *
4
+ * When an issuer withdraws coins, the balance simply drops. On a phone, money
5
+ * disappearing without a sentence is the worst failure in the system — worse
6
+ * than a refusal, which at least names itself — so this is the single place the
7
+ * design chooses interruption over quiet: one alert, once per transaction,
8
+ * naming the actor and the figure.
9
+ *
10
+ * `showAlert` rather than a toast: a toast is the FYI channel and can be missed
11
+ * entirely, while an alert must be acknowledged. No Activity row is fabricated
12
+ * to go with it — there is no transaction of the user's to show.
13
+ */
14
+ import type { TokenActivityRow } from '../../../core/mandala/runtime'
15
+ import { showAlert } from '../ui/AlertCard'
16
+ import { formatTokenAmount } from '../../tokenFormat'
17
+
18
+ /** The `t` every component in this package already holds. */
19
+ type Translate = ReturnType<typeof import('react-i18next').useTranslation>['t']
20
+
21
+ export interface EvictionNotice {
22
+ txid: string
23
+ ticker: string
24
+ issuer?: string
25
+ /** Base units the holder lost. */
26
+ baseUnits: number
27
+ decimals: number
28
+ }
29
+
30
+ /**
31
+ * Money that was credited to this wallet and is no longer there.
32
+ *
33
+ * A `reversed` row is exactly that and nothing else: a `refused` SENT payment
34
+ * never left, so the holder's balance is unchanged and there is nothing to
35
+ * announce; a `refused` RECEIVED payment is the settlement spec's row 1
36
+ * (reversed credit) and belongs here too.
37
+ */
38
+ export function evictionsFrom(rows: readonly TokenActivityRow[] | null, alreadySeen: readonly string[]): EvictionNotice[] {
39
+ if (!rows) return []
40
+ return rows
41
+ .filter(r => r.role === 'received' && (r.status === 'reversed' || r.status === 'refused'))
42
+ .filter(r => !alreadySeen.includes(r.txid))
43
+ .map(r => ({
44
+ txid: r.txid,
45
+ ticker: r.asset.ticker,
46
+ issuer: r.asset.issuerName,
47
+ baseUnits: r.baseUnits,
48
+ decimals: r.asset.decimals
49
+ }))
50
+ }
51
+
52
+ /** Raises the alert and resolves once it has been acknowledged. */
53
+ export async function announceEviction(t: Translate, notice: EvictionNotice): Promise<void> {
54
+ const issuer = notice.issuer || t('token_issuer_fallback')
55
+ const amount = formatTokenAmount(notice.baseUnits, notice.decimals)
56
+ await showAlert({
57
+ title: t('token_evicted_title', { ticker: notice.ticker }),
58
+ // Without a figure the sentence would be "some money left" — true, useless,
59
+ // and the reason the alert exists. If the figure cannot be formatted the
60
+ // alert still fires, because the withdrawal happened either way.
61
+ message: amount
62
+ ? t('token_evicted_body', { issuer, amount, ticker: notice.ticker })
63
+ : t('token_recv_reversed', { issuer })
64
+ })
65
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Export the wallet database through the OS share sheet — the action behind
3
+ * Settings › "Export Wallet Data" and the Vault screen's row of the same name
4
+ * (spec §3.4: the vault screen is where the user is thinking about recovery,
5
+ * and encrypted export preserves the recovery metadata/history mirrored by
6
+ * each output. The salt in v6 custom instructions is rederived through the
7
+ * wallet HMAC and used to rebuild the lock's salted commitments).
8
+ *
9
+ * Lifted from WalletConfigScreen.handleExportData so both screens share one
10
+ * implementation: one export at a time, `exporting` for the spinner, failures
11
+ * logged rather than surfaced (a dismissed share sheet is not an error).
12
+ */
13
+ import { useCallback, useRef, useState } from 'react'
14
+ import { useWallet } from '@bsv/expo-wallet-toolbox'
15
+ import { exportAllWalletDatabases } from '../exportDatabases'
16
+
17
+ export function useExportWalletData(): { exportData: () => Promise<void>; exporting: boolean } {
18
+ const { storage } = useWallet()
19
+ const [exporting, setExporting] = useState(false)
20
+ // A ref, not the state: two taps in the same tick both see `exporting ===
21
+ // false` in their closure, and the second must still be refused.
22
+ const inFlightRef = useRef(false)
23
+
24
+ const exportData = useCallback(async () => {
25
+ if (inFlightRef.current) return
26
+ inFlightRef.current = true
27
+ setExporting(true)
28
+ try {
29
+ await exportAllWalletDatabases(storage)
30
+ } catch (e) {
31
+ console.warn('[exportWalletData] Export failed:', e)
32
+ } finally {
33
+ inFlightRef.current = false
34
+ setExporting(false)
35
+ }
36
+ }, [storage])
37
+
38
+ return { exportData, exporting }
39
+ }
@@ -0,0 +1,303 @@
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
+ /** Injected runtime. `undefined` means "ask the wallet context"; `null` means "none". */
59
+ const MandalaRuntimeContext = createContext<MandalaRuntime | null | undefined>(undefined)
60
+
61
+ export function MandalaProvider({
62
+ runtime,
63
+ children
64
+ }: {
65
+ runtime: MandalaRuntime | null
66
+ children: React.ReactNode
67
+ }) {
68
+ return React.createElement(MandalaRuntimeContext.Provider, { value: runtime }, children)
69
+ }
70
+
71
+ /**
72
+ * The runtime, or `null` when stablecoins are unavailable on this wallet or
73
+ * this chain. Callers that only fire actions (send, drain) want this; callers
74
+ * that render money want `useMandala()`.
75
+ */
76
+ export function useMandalaRuntime(): MandalaRuntime | null {
77
+ const injected = useContext(MandalaRuntimeContext)
78
+ // `undefined` on the context until the wallet is built, and on every chain
79
+ // but mainnet — which IS the chain gate, not an error state.
80
+ const fromWallet = useWallet()?.mandala ?? null
81
+ const runtime = injected !== undefined ? injected : fromWallet
82
+ // `available` is the runtime's own chain gate; a runtime that says it is not
83
+ // available is the same as none at all for every surface below.
84
+ return runtime && runtime.available ? runtime : null
85
+ }
86
+
87
+ export interface MandalaState {
88
+ /** Stablecoins exist for this wallet on this chain. Everything is gated on it. */
89
+ available: boolean
90
+ runtime: MandalaRuntime | null
91
+ /** Held assets with their figures. `null` = not known yet, never "zero". */
92
+ balances: TokenBalance[] | null
93
+ /** Just the assets, for a picker. `[]` when nothing is held. */
94
+ assets: TokenAssetInfo[]
95
+ /** Non-terminal settlement rows past the stuck bound (FIX M) — the home badge. */
96
+ stuck: TokenSettlementRow[]
97
+ /** True only while the FIRST read is outstanding; a refresh keeps the figures. */
98
+ loading: boolean
99
+ refresh: () => void
100
+ }
101
+
102
+ const EMPTY_ASSETS: TokenAssetInfo[] = []
103
+ const EMPTY_STUCK: TokenSettlementRow[] = []
104
+
105
+ export function useMandala(): MandalaState {
106
+ const runtime = useMandalaRuntime()
107
+ const [balances, setBalances] = useState<TokenBalance[] | null>(null)
108
+ const [stuck, setStuck] = useState<TokenSettlementRow[]>(EMPTY_STUCK)
109
+ const [loading, setLoading] = useState(false)
110
+ const [nonce, setNonce] = useState(0)
111
+ const runtimeRef = useRef<MandalaRuntime | null>(runtime)
112
+ /** Which runtime we have already read once, so a refresh keeps the figures. */
113
+ const loadedForRef = useRef<MandalaRuntime | null>(null)
114
+
115
+ const refresh = useCallback(() => setNonce(n => n + 1), [])
116
+
117
+ // A wallet switch must read as UNKNOWN immediately, not as the previous
118
+ // wallet's balance held over until the next read lands.
119
+ useEffect(() => {
120
+ if (runtimeRef.current === runtime) return
121
+ runtimeRef.current = runtime
122
+ setBalances(null)
123
+ setStuck(EMPTY_STUCK)
124
+ }, [runtime])
125
+
126
+ useEffect(() => {
127
+ if (!runtime) {
128
+ setBalances(null)
129
+ setStuck(EMPTY_STUCK)
130
+ setLoading(false)
131
+ return
132
+ }
133
+ let live = true
134
+ if (loadedForRef.current !== runtime) setLoading(true)
135
+ void (async () => {
136
+ try {
137
+ const rows = await runtime.balances()
138
+ if (live && runtimeRef.current === runtime) setBalances(rows)
139
+ } catch {
140
+ // A failed read keeps the last figure: a balance that blinks to "—" on
141
+ // every transient overlay hiccup teaches the holder to distrust it.
142
+ }
143
+ try {
144
+ const rows = await runtime.stuck()
145
+ if (live && runtimeRef.current === runtime) setStuck(rows)
146
+ } catch {
147
+ // Same: the badge is advisory, and a missing one is better than a wrong one.
148
+ }
149
+ if (live) {
150
+ loadedForRef.current = runtime
151
+ setLoading(false)
152
+ }
153
+ })()
154
+ return () => {
155
+ live = false
156
+ }
157
+ }, [runtime, nonce])
158
+
159
+ // The runtime tells us when money moved; nothing here polls.
160
+ useEffect(() => {
161
+ if (!runtime) return
162
+ return runtime.subscribe(refresh)
163
+ }, [runtime, refresh])
164
+
165
+ const assets = useMemo(() => (balances ? balances.map(b => b.asset) : EMPTY_ASSETS), [balances])
166
+
167
+ return { available: runtime != null, runtime, balances, assets, stuck, loading, refresh }
168
+ }
169
+
170
+ export interface MandalaActivityState {
171
+ /** `null` until the first read lands — an empty list is a claim, not a wait. */
172
+ rows: TokenActivityRow[] | null
173
+ loading: boolean
174
+ refresh: () => void
175
+ }
176
+
177
+ /**
178
+ * Token rows for the activity list (ux §6.2). Kept out of `useMandala()` so a
179
+ * screen that only needs balances does not pay for an activity query.
180
+ */
181
+ export function useTokenActivity(limit?: number): MandalaActivityState {
182
+ const runtime = useMandalaRuntime()
183
+ const [rows, setRows] = useState<TokenActivityRow[] | null>(null)
184
+ const [loading, setLoading] = useState(false)
185
+ const [nonce, setNonce] = useState(0)
186
+ const refresh = useCallback(() => setNonce(n => n + 1), [])
187
+
188
+ useEffect(() => {
189
+ if (!runtime) {
190
+ setRows(null)
191
+ return
192
+ }
193
+ let live = true
194
+ setLoading(true)
195
+ void (async () => {
196
+ try {
197
+ const next = await runtime.activity(limit)
198
+ if (live) setRows(next)
199
+ } catch {
200
+ // Advisory: the BSV rows still render, and a token row with no status
201
+ // is better than an activity list that failed to draw.
202
+ }
203
+ if (live) setLoading(false)
204
+ })()
205
+ return () => {
206
+ live = false
207
+ }
208
+ }, [runtime, limit, nonce])
209
+
210
+ useEffect(() => {
211
+ if (!runtime) return
212
+ return runtime.subscribe(refresh)
213
+ }, [runtime, refresh])
214
+
215
+ return { rows, loading, refresh }
216
+ }
217
+
218
+ /** Index of token rows by txid, for interleaving into the wallet's own list. */
219
+ export function tokenActivityByTxid(rows: TokenActivityRow[] | null): Map<string, TokenActivityRow> {
220
+ const map = new Map<string, TokenActivityRow>()
221
+ for (const row of rows ?? []) map.set(row.txid.toLowerCase(), row)
222
+ return map
223
+ }
224
+
225
+ export interface AssetStatusState {
226
+ /** `null` until the first read lands, or when there is no runtime/assetId. Never a stand-in for "fine". */
227
+ status: TokenAssetStatus | null
228
+ /** True only while the FIRST read for this (runtime, assetId) pair is outstanding. */
229
+ loading: boolean
230
+ /** Forces a fresh read past the runtime's own ~10s cache. */
231
+ refresh: () => void
232
+ }
233
+
234
+ /**
235
+ * Regulatory/registry facts for one asset (paused, frozen, self/recipient
236
+ * admission, metadata resolution, the MessageBox host) — the one door a pay
237
+ * or receive screen has to the pre-flight copy in ux design §4.2/§5.4.
238
+ *
239
+ * Cached: reads go through `runtime.assetStatus`, which already holds a
240
+ * ~10s cache in the implementation (runtime.ts), so calling this from more
241
+ * than one screen for the same asset costs no extra round trip. Refreshed
242
+ * three ways: the assetId/runtime changing, the runtime announcing a
243
+ * mutation (`subscribe` — a send, a receive, a drain tick), and this screen
244
+ * regaining focus (a paused/frozen fact can go stale while the holder was
245
+ * looking at a different screen). A failed read is silently dropped and
246
+ * keeps the last-known status — this is advisory copy, not a gate anything
247
+ * transacts against (ux §4.2 rule 3: pre-flight may only ever say "no").
248
+ */
249
+ export function useAssetStatus(assetId: string | null | undefined): AssetStatusState {
250
+ const runtime = useMandalaRuntime()
251
+ const [status, setStatus] = useState<TokenAssetStatus | null>(null)
252
+ const [loading, setLoading] = useState(false)
253
+ const [nonce, setNonce] = useState(0)
254
+ const refresh = useCallback(() => setNonce(n => n + 1), [])
255
+ const key = runtime && assetId ? assetId : null
256
+
257
+ useEffect(() => {
258
+ if (!runtime || !key) {
259
+ setStatus(null)
260
+ setLoading(false)
261
+ return
262
+ }
263
+ let live = true
264
+ setLoading(true)
265
+ void (async () => {
266
+ try {
267
+ const next = await runtime.assetStatus(key)
268
+ if (live) setStatus(next)
269
+ } catch {
270
+ // Fails open, like the runtime's own cache: a stale or unreachable
271
+ // overlay must read as "unknown", never as a thrown error, and the
272
+ // last-known status (possibly still null) is kept on screen.
273
+ }
274
+ if (live) setLoading(false)
275
+ })()
276
+ return () => {
277
+ live = false
278
+ }
279
+ }, [runtime, key, nonce])
280
+
281
+ // After mutations: the runtime's own change signal (a send, a receive, a
282
+ // drain tick advancing a settlement) — the same subscription useMandala()
283
+ // uses for balances/activity.
284
+ useEffect(() => {
285
+ if (!runtime) return
286
+ return runtime.subscribe(refresh)
287
+ }, [runtime, refresh])
288
+
289
+ // On focus: a paused/frozen/admission fact can go stale while this screen
290
+ // was backgrounded. `loadExpoRouter().useFocusEffect` is a hook, but the
291
+ // module is cached after the first call, so it is the exact same function
292
+ // reference on every render — a stable, unconditional call per render,
293
+ // which is what the rules of hooks actually require.
294
+ loadExpoRouter().useFocusEffect(
295
+ useCallback(() => {
296
+ refresh()
297
+ // Only re-fetch on (re)focus, not on every render while focused.
298
+ // eslint-disable-next-line react-hooks/exhaustive-deps
299
+ }, [runtime, key])
300
+ )
301
+
302
+ return { status, loading, refresh }
303
+ }