@bsv/expo-wallet-toolbox 0.5.0 → 0.9.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 (200) hide show
  1. package/CHANGELOG.md +2000 -0
  2. package/README.md +66 -1
  3. package/core/amountFormatHelpers.ts +258 -36
  4. package/core/backup/RemoteSyncReader.ts +133 -24
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +149 -11
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +71 -5
  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/config.tsx +12 -5
  15. package/core/constants.ts +14 -1
  16. package/core/contacts/contactActivity.ts +153 -0
  17. package/core/contacts/contactCache.ts +41 -0
  18. package/core/contacts/contactsStore.ts +183 -0
  19. package/core/context/ExchangeRateContext.tsx +34 -27
  20. package/core/context/LocalStorageProvider.tsx +43 -40
  21. package/core/context/UserContext.tsx +18 -7
  22. package/core/context/VaultContext.tsx +49 -2
  23. package/core/context/WalletConnectionContext.tsx +203 -11
  24. package/core/context/WalletContext.tsx +685 -171
  25. package/core/demo/demoAssets.ts +60 -0
  26. package/core/demo/demoLedger.ts +240 -0
  27. package/core/demo/demoMandalaRuntime.ts +96 -0
  28. package/core/demo/demoMode.ts +38 -0
  29. package/core/demo/demoWallet.ts +25 -0
  30. package/core/demo/index.ts +26 -0
  31. package/core/demo/useDemo.ts +59 -0
  32. package/core/headers/OfflineFirstChaintracks.ts +99 -17
  33. package/core/headers/headerStore.ts +33 -14
  34. package/core/headers/syncHeaders.ts +12 -1
  35. package/core/i18n/translations.tsx +2186 -98
  36. package/core/identity/contactLink.ts +36 -0
  37. package/core/identity/handleRegistry/client.ts +314 -0
  38. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  39. package/core/identity/handleRegistry/profileCert.ts +254 -0
  40. package/core/identity/handleRegistry/registration.ts +559 -0
  41. package/core/identity/handleRegistry/resolver.ts +315 -0
  42. package/core/identity/handleRegistry/rules.ts +104 -0
  43. package/core/index.ts +53 -5
  44. package/core/localpay/build.ts +225 -24
  45. package/core/localpay/pending.ts +110 -7
  46. package/core/localpay/pendingAbortAuthority.ts +95 -0
  47. package/core/localpay/pendingAborts.ts +266 -26
  48. package/core/localpay/session.ts +42 -17
  49. package/core/localpay/settlementAck.ts +10 -1
  50. package/core/localpay/transport/socket.ts +52 -3
  51. package/core/localpay/verify.ts +100 -10
  52. package/core/mandala/abortGuard.ts +96 -20
  53. package/core/mandala/createRuntime.ts +206 -33
  54. package/core/mandala/drain.ts +89 -11
  55. package/core/mandala/inboxPrehold.ts +186 -0
  56. package/core/mandala/permissionModule.ts +202 -20
  57. package/core/mandala/settlementStore.ts +24 -2
  58. package/core/mandala/types.ts +40 -5
  59. package/core/monitor/MonitorSupervisor.ts +121 -0
  60. package/core/monitor/TaskBackupPush.ts +15 -1
  61. package/core/monitor/TaskCreditInbox.ts +1 -1
  62. package/core/monitor/TaskDrainOutbox.ts +15 -1
  63. package/core/monitor/TaskSendOffline.ts +15 -1
  64. package/core/net/online.ts +49 -0
  65. package/core/net/publicDestination.ts +91 -0
  66. package/core/net/validateArcUrl.ts +22 -0
  67. package/core/numberFormat.ts +19 -0
  68. package/core/offline/cancelParked.ts +134 -13
  69. package/core/offline/payerHold.ts +100 -24
  70. package/core/offline/plan.ts +37 -8
  71. package/core/pay/beefRepair.ts +6 -2
  72. package/core/pay/damagedInbox.ts +24 -0
  73. package/core/pay/rails/address.ts +107 -12
  74. package/core/pay/rails/handle.ts +117 -22
  75. package/core/pay/rails/index.ts +45 -7
  76. package/core/pay/rails/nativeIntent.ts +61 -0
  77. package/core/pay/receiveHistory.ts +93 -0
  78. package/core/pay/recordProof.ts +21 -7
  79. package/core/pay/refreshProofGuard.ts +42 -1
  80. package/core/pay/watchlist.ts +5 -2
  81. package/core/peerpay/control.ts +17 -18
  82. package/core/peerpay/handleResendRequests.ts +58 -4
  83. package/core/peerpay/outbox.ts +3 -1
  84. package/core/recovery/backupMaterial.ts +61 -0
  85. package/core/recovery/createWallet.ts +95 -0
  86. package/core/recovery/recoverWallet.ts +120 -0
  87. package/core/recovery/restoreWallet.ts +170 -0
  88. package/core/recovery/secret.ts +92 -0
  89. package/core/recovery/shareCollector.ts +71 -0
  90. package/core/recovery/shareParsing.ts +87 -0
  91. package/core/recovery/shares.ts +116 -0
  92. package/core/recovery/useRecoveryDeps.ts +70 -0
  93. package/core/services/arcTokenStorage.ts +52 -0
  94. package/core/services/arcadeBroadcastProvider.ts +233 -52
  95. package/core/services/autoApprovePolicy.ts +105 -0
  96. package/core/services/callbackToken.ts +19 -0
  97. package/core/services/capWalletArgs.ts +14 -2
  98. package/core/services/connectionAuthority.ts +98 -0
  99. package/core/services/exchangeRate.ts +36 -13
  100. package/core/services/externalOrigin.ts +16 -2
  101. package/core/services/secrets/kek.ts +126 -29
  102. package/core/services/secrets/migration.ts +16 -4
  103. package/core/services/secrets/store.ts +42 -14
  104. package/core/services/vault/VaultKeyService.ts +228 -45
  105. package/core/services/vault/chainRecovery.ts +483 -0
  106. package/core/services/vault/driver.ts +9 -1
  107. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  108. package/core/services/vault/guard.ts +218 -32
  109. package/core/services/vault/hardwareLease.ts +19 -0
  110. package/core/services/vault/metaAuthority.ts +210 -0
  111. package/core/services/vault/pivReset.ts +64 -23
  112. package/core/services/vault/r1comb.ts +139 -3
  113. package/core/services/vault/session.ts +25 -4
  114. package/core/services/vault/transfers.ts +868 -172
  115. package/core/services/vault/types.ts +19 -4
  116. package/core/services/vault/vaultStore.ts +256 -29
  117. package/core/services/walletArgLimits.ts +45 -2
  118. package/core/services/walletConnectionValidation.ts +76 -6
  119. package/core/services/walletServiceConfig.ts +40 -27
  120. package/core/storage/StorageExpoSQLite.ts +88 -47
  121. package/core/storage/methods/findSql.ts +24 -2
  122. package/core/storage/methods/listActionsSql.ts +8 -5
  123. package/core/storage/methods/listOutputsSql.ts +2 -2
  124. package/core/storage/methods/offlineActions.ts +10 -1
  125. package/core/storage/methods/processOfflineActions.ts +117 -25
  126. package/core/storage/methods/reviewStatusSql.ts +7 -2
  127. package/core/storage/schema/createTables.ts +155 -2
  128. package/core/stores/ConnectionStore.ts +34 -0
  129. package/core/toolboxConfig.ts +104 -0
  130. package/core/toolboxTypes.ts +40 -0
  131. package/core/userAvatar.ts +79 -0
  132. package/core/walletDbRegistry.ts +63 -0
  133. package/core/walletMonitor.ts +25 -4
  134. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  135. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  136. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  137. package/package.json +7 -7
  138. package/ui/activityFilter.ts +115 -0
  139. package/ui/backupShares.ts +26 -169
  140. package/ui/components/pay/AddressReceive.tsx +13 -6
  141. package/ui/components/pay/AssetPicker.tsx +30 -9
  142. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  143. package/ui/components/pay/NearbyFlow.tsx +480 -243
  144. package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
  145. package/ui/components/pay/RecipientField.tsx +84 -70
  146. package/ui/components/pay/StepBar.tsx +32 -0
  147. package/ui/components/pay/UniversalSend.tsx +827 -205
  148. package/ui/components/ui/AlertCard.tsx +38 -5
  149. package/ui/components/ui/PencilEditField.tsx +109 -0
  150. package/ui/components/ui/PermissionSheet.tsx +197 -66
  151. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  152. package/ui/components/vault/EnrollWizard.tsx +61 -13
  153. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  154. package/ui/components/wallet/ActivityRow.tsx +227 -123
  155. package/ui/components/wallet/AmountInput.tsx +26 -8
  156. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  157. package/ui/components/wallet/Balance.tsx +42 -23
  158. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  159. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  160. package/ui/components/wallet/ContactSigil.tsx +49 -0
  161. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  162. package/ui/components/wallet/FitAmount.tsx +148 -0
  163. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  164. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  165. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  166. package/ui/components/wallet/ProfileButton.tsx +62 -0
  167. package/ui/components/wallet/UserAvatar.tsx +85 -0
  168. package/ui/components/wallet/avatarIcons.ts +122 -0
  169. package/ui/exportTransactions.ts +36 -4
  170. package/ui/hooks/useContactsStore.ts +10 -0
  171. package/ui/hooks/useExportWalletData.ts +25 -2
  172. package/ui/hooks/useMandala.ts +18 -1
  173. package/ui/hooks/useOnline.ts +65 -20
  174. package/ui/importDatabases.ts +339 -24
  175. package/ui/index.ts +33 -2
  176. package/ui/isImageUrl.ts +6 -0
  177. package/ui/printRecoveryShares.ts +9 -10
  178. package/ui/recoveryPrompts.ts +91 -0
  179. package/ui/resolveIdentity.ts +31 -9
  180. package/ui/screens/ConnectionsScreen.tsx +86 -19
  181. package/ui/screens/ContactScreen.tsx +289 -0
  182. package/ui/screens/ContactsScreen.tsx +373 -0
  183. package/ui/screens/IdentifierScreen.tsx +256 -0
  184. package/ui/screens/NewContactScreen.tsx +362 -0
  185. package/ui/screens/PairScreen.tsx +74 -2
  186. package/ui/screens/PayScreen.tsx +20 -7
  187. package/ui/screens/ProfileScreen.tsx +783 -0
  188. package/ui/screens/SettingsScreen.tsx +10 -4
  189. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  190. package/ui/screens/TrustScreen.tsx +100 -5
  191. package/ui/screens/VaultScreen.tsx +410 -61
  192. package/ui/screens/VaultTransferScreen.tsx +59 -7
  193. package/ui/screens/WalletCheckScreen.tsx +17 -6
  194. package/ui/screens/WalletConfigScreen.tsx +124 -28
  195. package/ui/screens/WalletHomeScreen.tsx +640 -104
  196. package/ui/screens/detailActionKeys.ts +55 -0
  197. package/ui/tokenFormat.ts +44 -4
  198. package/ui/tokenStatus.ts +21 -0
  199. package/ui/txStatus.ts +48 -5
  200. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -14,7 +14,8 @@ import {
14
14
  formatAmount,
15
15
  isFiatCurrency,
16
16
  fiatFractionDigits,
17
- satoshisPerFiatUnit
17
+ satoshisPerFiatUnit,
18
+ decimalSeparator
18
19
  } from '@bsv/expo-wallet-toolbox'
19
20
  import { parseTokenAmount, tokenAmountInputText, tokenAmountMask } from '../../tokenFormat'
20
21
 
@@ -132,9 +133,7 @@ export const AmountInput: React.FC<AmountInputProps> = ({
132
133
  setDisplayText(String(Math.round(amount)))
133
134
  } else {
134
135
  setDisplayText(
135
- amount % 1 === 0
136
- ? amount.toFixed(0)
137
- : amount.toFixed(fractionDigits).replace(/0+$/, '').replace(/\.$/, '')
136
+ amount % 1 === 0 ? amount.toFixed(0) : amount.toFixed(fractionDigits).replace(/0+$/, '').replace(/\.$/, '')
138
137
  )
139
138
  }
140
139
  }
@@ -149,7 +148,17 @@ export const AmountInput: React.FC<AmountInputProps> = ({
149
148
  if (value === lastEmitted.current) return
150
149
  setDisplayText(!value || value === '0' ? '' : tokenAmountInputText(Number(value), asset.decimals))
151
150
  lastEmitted.current = value
152
- }, [value, asset])
151
+ // `asset` is a fresh object literal on every render of most callers
152
+ // (e.g. `asset={{ ticker, decimals }}`), so depending on it directly
153
+ // reruns this effect on EVERY parent render, not just when the figure
154
+ // actually changes. Two such reruns queued back to back can interleave
155
+ // out of order — an older render's effect (with a stale `value`) firing
156
+ // AFTER a newer one clobbers `lastEmitted.current` back down, which then
157
+ // makes the newer render's own effect think it must resync and reformats
158
+ // what the user just typed. Depending on the primitive that the effect
159
+ // body actually reads keeps it from firing on an unrelated re-render.
160
+ // eslint-disable-next-line react-hooks/exhaustive-deps
161
+ }, [value, asset?.decimals, !!asset])
153
162
 
154
163
  const handleChangeText = (text: string) => {
155
164
  if (asset) {
@@ -164,7 +173,12 @@ export const AmountInput: React.FC<AmountInputProps> = ({
164
173
  return
165
174
  }
166
175
  if (isFiat) {
167
- const allowed = fractionDigits === 0 ? /^\d*$/ : new RegExp(`^\\d*\\.?\\d{0,${fractionDigits}}$`)
176
+ // The mask accepts the ACTIVE LOCALE's own decimal separator (e.g. ','
177
+ // for de-DE), not a hardcoded '.' — otherwise every comma keystroke a
178
+ // comma-decimal locale types is silently dropped here before
179
+ // `parseDisplayToSatoshis` (which normalizes it) ever sees it.
180
+ const sep = decimalSeparator().replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
181
+ const allowed = fractionDigits === 0 ? /^\d*$/ : new RegExp(`^\\d*${sep}?\\d{0,${fractionDigits}}$`)
168
182
  if (text && !allowed.test(text)) return
169
183
  setDisplayText(text)
170
184
  const sats = parseDisplayToSatoshis(text, currency, satoshisPerUSD, usdToFiat)
@@ -208,8 +222,12 @@ export const AmountInput: React.FC<AmountInputProps> = ({
208
222
  const secondaryText = asset
209
223
  ? null
210
224
  : isFiat
211
- ? (satsForConversion > 0 ? formatAmount(satsForConversion, 'BSV', satoshisPerUSD) : null)
212
- : (satsForConversion > 0 && satoshisPerUSD > 0 ? formatAmount(satsForConversion, 'USD', satoshisPerUSD) : null)
225
+ ? satsForConversion > 0
226
+ ? formatAmount(satsForConversion, 'BSV', satoshisPerUSD)
227
+ : null
228
+ : satsForConversion > 0 && satoshisPerUSD > 0
229
+ ? formatAmount(satsForConversion, 'USD', satoshisPerUSD)
230
+ : null
213
231
 
214
232
  const entering = reducedMotion ? undefined : FadeInUp.duration(durations.instant)
215
233
  const exiting = reducedMotion ? undefined : FadeOutDown.duration(durations.instant)
@@ -22,7 +22,7 @@ import { Pressable, StyleSheet, Text, TouchableOpacity, View } from 'react-nativ
22
22
  import Animated, { runOnJS, useAnimatedStyle, useSharedValue, withTiming } from 'react-native-reanimated'
23
23
  import { hitTargets, radii, spacing, typography, useTheme } from '@bsv/expo-wallet-toolbox'
24
24
  import type { TokenBalance } from '../../../core/mandala/runtime'
25
- import { tokenAmountParts } from '../../tokenFormat'
25
+ import { shortAssetId, tokenAmountParts } from '../../tokenFormat'
26
26
 
27
27
  /**
28
28
  * @expo/vector-icons' index barrel re-exports every icon set, one of which
@@ -147,6 +147,8 @@ export default function AssetSwitcherDropdown({
147
147
  key={b.asset.assetId}
148
148
  ticker={b.asset.ticker}
149
149
  fullName={b.asset.label}
150
+ issuerName={b.asset.issuerName}
151
+ fingerprint={shortAssetId(b.asset.assetId)}
150
152
  figure={tokenAmountParts(b.baseUnits, b.asset)}
151
153
  selected={selected === b.asset.assetId}
152
154
  onPress={() => choose(b.asset.assetId)}
@@ -161,12 +163,18 @@ export default function AssetSwitcherDropdown({
161
163
  function CoinRow({
162
164
  ticker,
163
165
  fullName,
166
+ issuerName,
167
+ fingerprint,
164
168
  figure,
165
169
  selected,
166
170
  onPress
167
171
  }: {
168
172
  ticker: string
169
173
  fullName?: string
174
+ /** XR-044: unverified, issuer-supplied — shown alongside the fingerprint, never in place of it. */
175
+ issuerName?: string
176
+ /** XR-044: `shortAssetId(assetId)` — the one thing a look-alike asset cannot share. Absent for BSV. */
177
+ fingerprint?: string
170
178
  figure: { value: string; unit: string } | null
171
179
  selected: boolean
172
180
  onPress: () => void
@@ -174,6 +182,10 @@ function CoinRow({
174
182
  const { colors } = useTheme()
175
183
  const Ionicons = loadIonicons()
176
184
  const figureText = figure ? `${figure.value} ${figure.unit}`.trim() : ''
185
+ // "Acme Bank · a1b2c3d4…ef01.0", or just the fingerprint when the issuer
186
+ // name could not be resolved — never the fingerprint alone dropped in favor
187
+ // of an unverified name.
188
+ const identityLine = [issuerName, fingerprint].filter(Boolean).join(' · ')
177
189
  return (
178
190
  <TouchableOpacity
179
191
  style={[styles.row, selected && { backgroundColor: colors.fill }]}
@@ -182,7 +194,7 @@ function CoinRow({
182
194
  accessibilityRole="button"
183
195
  // The checkmark is not the only signal: state travels with the element.
184
196
  accessibilityState={{ selected }}
185
- accessibilityLabel={[ticker, fullName, figureText].filter(Boolean).join(', ')}
197
+ accessibilityLabel={[ticker, fullName, identityLine, figureText].filter(Boolean).join(', ')}
186
198
  >
187
199
  <View style={styles.body}>
188
200
  <Text style={[styles.name, { color: colors.textPrimary }]} numberOfLines={1}>
@@ -193,6 +205,11 @@ function CoinRow({
193
205
  {fullName}
194
206
  </Text>
195
207
  )}
208
+ {!!identityLine && (
209
+ <Text style={[styles.identity, { color: colors.textTertiary }]} numberOfLines={1}>
210
+ {identityLine}
211
+ </Text>
212
+ )}
196
213
  </View>
197
214
  {figure && (
198
215
  <Text style={[styles.figure, { color: colors.textPrimary }]} numberOfLines={1} accessibilityLabel={figureText}>
@@ -255,6 +272,9 @@ const styles = StyleSheet.create({
255
272
  body: { flex: 1, minWidth: 0 },
256
273
  name: { ...typography.body, fontWeight: '600' },
257
274
  detail: { ...typography.footnote, marginTop: 2, fontVariant: ['tabular-nums'] },
275
+ // XR-044: smaller and dimmer than `detail` — an issuer/fingerprint line is
276
+ // provenance for the rare collision, not something every glance needs.
277
+ identity: { ...typography.caption2, marginTop: 1, fontVariant: ['tabular-nums'] },
258
278
  figure: { ...typography.body, fontWeight: '600', fontVariant: ['tabular-nums'] },
259
279
  unit: { ...typography.footnote },
260
280
  check: { width: 20, alignItems: 'center' }
@@ -6,30 +6,41 @@ import AppLogo from '../ui/AppLogo'
6
6
  import { sdk } from '@bsv/wallet-toolbox-mobile'
7
7
  import AsyncStorage from '@react-native-async-storage/async-storage'
8
8
 
9
- const BALANCE_CACHE_KEY = 'cached_wallet_balance'
10
- const BALANCE_CACHE_TIMESTAMP_KEY = 'cached_wallet_balance_timestamp'
9
+ // XR-058: scoped by network (matching useSpendableBalance's pattern) rather
10
+ // than a single global key, so one wallet/network context can never read
11
+ // back a figure cached by another. See WalletContext.tsx's logout sweep for
12
+ // the migration cleanup of the legacy unscoped key this replaces.
13
+ const BALANCE_CACHE_PREFIX = 'cached_wallet_balance_'
11
14
  const CACHE_DURATION = 30000 // 30 seconds
12
15
 
13
16
  export default function Balance() {
14
17
  const { colors } = useTheme()
15
- const { managers, adminOriginator, txStatusVersion } = useWallet()
16
- const [accountBalance, setAccountBalance] = React.useState<number | null>(null)
18
+ const { managers, adminOriginator, txStatusVersion, selectedNetwork } = useWallet()
19
+ const cacheKey = `${BALANCE_CACHE_PREFIX}${selectedNetwork}`
20
+ const timestampKey = `${cacheKey}_timestamp`
21
+ // { key, value } rather than a bare number: `key` is compared against the
22
+ // live `cacheKey` everywhere below, so a figure read for a since-departed
23
+ // wallet or network context can never be painted, even if this component
24
+ // stays mounted across a logout or network switch (XR-058).
25
+ const [accountBalance, setAccountBalance] = React.useState<{ key: string; value: number } | null>(null)
17
26
  const [balanceLoading, setBalanceLoading] = React.useState(false)
18
27
  // Read through a ref, not the state value: `accountBalance` in this callback's
19
28
  // deps would give it a new identity on every fetch, re-running both effects
20
29
  // below and firing a second, pointless fetch each time the figure changes.
21
- const accountBalanceRef = React.useRef<number | null>(null)
30
+ const accountBalanceRef = React.useRef<{ key: string; value: number } | null>(null)
22
31
  accountBalanceRef.current = accountBalance
23
32
 
24
33
  const refreshBalance = useCallback(async () => {
25
34
  try {
26
-
27
35
  if (!managers.permissionsManager) {
36
+ // No active wallet context for this network: never leave a previous
37
+ // context's figure on screen (XR-058).
38
+ setAccountBalance(null)
28
39
  return
29
40
  }
30
41
 
31
- // Only show loading if we don't have cached data
32
- if (accountBalanceRef.current === null) {
42
+ // Only show loading if we don't have cached data for this context
43
+ if (accountBalanceRef.current?.key !== cacheKey) {
33
44
  setBalanceLoading(true)
34
45
  }
35
46
 
@@ -40,44 +51,50 @@ export default function Balance() {
40
51
  )
41
52
 
42
53
  const total = totalOutputs ?? 0
43
- setAccountBalance(total)
54
+ setAccountBalance({ key: cacheKey, value: total })
44
55
 
45
56
  // Cache the new balance
46
- await Promise.all([
47
- AsyncStorage.setItem(BALANCE_CACHE_KEY, String(total)),
48
- AsyncStorage.setItem(BALANCE_CACHE_TIMESTAMP_KEY, String(Date.now()))
49
- ])
57
+ await Promise.all([AsyncStorage.setItem(cacheKey, String(total)), AsyncStorage.setItem(timestampKey, String(Date.now()))])
50
58
 
51
59
  setBalanceLoading(false)
52
60
  } catch (e) {
53
61
  console.error('Error refreshing balance:', e)
54
62
  setBalanceLoading(false)
55
63
  }
56
- }, [managers, adminOriginator])
64
+ }, [managers, adminOriginator, cacheKey, timestampKey])
57
65
 
58
- // Load cached balance immediately on mount
66
+ // Load cached balance immediately on mount — but only once a wallet
67
+ // context for this exact network is active. Reading (and painting) the
68
+ // cache before that is exactly how a departed wallet's figure used to leak
69
+ // into a fresh or different-context mount (XR-058).
59
70
  useEffect(() => {
60
71
  let mounted = true
61
72
 
62
73
  const loadCachedBalance = async () => {
74
+ if (!managers.permissionsManager) {
75
+ if (mounted) setAccountBalance(null)
76
+ return
77
+ }
63
78
  try {
64
79
  const [cachedBalance, cachedTimestamp] = await Promise.all([
65
- AsyncStorage.getItem(BALANCE_CACHE_KEY),
66
- AsyncStorage.getItem(BALANCE_CACHE_TIMESTAMP_KEY)
80
+ AsyncStorage.getItem(cacheKey),
81
+ AsyncStorage.getItem(timestampKey)
67
82
  ])
68
83
 
69
- if (mounted && cachedBalance !== null) {
84
+ if (!mounted || !managers.permissionsManager) return
85
+
86
+ if (cachedBalance !== null) {
70
87
  const balance = Number(cachedBalance)
71
88
  const timestamp = Number(cachedTimestamp)
72
89
  const isRecent = timestamp && Date.now() - timestamp < CACHE_DURATION
73
90
 
74
- setAccountBalance(balance)
91
+ setAccountBalance({ key: cacheKey, value: balance })
75
92
 
76
93
  // If cache is old, fetch fresh data
77
94
  if (!isRecent) {
78
95
  refreshBalance()
79
96
  }
80
- } else if (mounted) {
97
+ } else {
81
98
  // No cache, fetch fresh data
82
99
  refreshBalance()
83
100
  }
@@ -91,7 +108,7 @@ export default function Balance() {
91
108
  return () => {
92
109
  mounted = false
93
110
  }
94
- }, [refreshBalance])
111
+ }, [refreshBalance, cacheKey, managers.permissionsManager])
95
112
 
96
113
  // Refresh balance when SSE reports a transaction status change
97
114
  useEffect(() => {
@@ -100,16 +117,18 @@ export default function Balance() {
100
117
  }
101
118
  }, [txStatusVersion, refreshBalance])
102
119
 
120
+ const balance = accountBalance?.key === cacheKey ? accountBalance.value : null
121
+
103
122
  return (
104
123
  <View style={[componentStyles.container, { backgroundColor: colors.paperBackground }]}>
105
124
  <Text style={[componentStyles.sectionTitle, { color: colors.textPrimary }]}>you have</Text>
106
- {accountBalance === null && balanceLoading ? (
125
+ {balance === null && balanceLoading ? (
107
126
  <View style={componentStyles.loadingContainer}>
108
127
  <AppLogo size={50} rotate />
109
128
  </View>
110
129
  ) : (
111
130
  <Text onPress={refreshBalance} style={[componentStyles.balance, { color: colors.textPrimary }]}>
112
- <AmountDisplay abbreviate>{accountBalance ?? 0}</AmountDisplay>
131
+ <AmountDisplay abbreviate>{balance ?? 0}</AmountDisplay>
113
132
  <Text style={[componentStyles.cacheIndicator, { color: colors.textSecondary }]}></Text>
114
133
  </Text>
115
134
  )}
@@ -43,9 +43,15 @@ export const BiometricAdvisoryModal: React.FC<{
43
43
  * looking frozen for that whole stretch, with nothing on screen explaining
44
44
  * why. Keeping the modal up with a spinner in place of the label instead. */
45
45
  loading?: boolean
46
+ /** XR-114: true when this device/build will NOT actually get biometric
47
+ * protection (resolveProvisioningPolicy().disclose) — no strong biometrics
48
+ * enrolled, or a dev build without them. The unconditional "protected by
49
+ * Face ID/fingerprint" promise is false in that case; swap in an honest
50
+ * disclosure instead of silently degrading with no visible change. */
51
+ degraded?: boolean
46
52
  onCancel: () => void
47
53
  onContinue: () => void
48
- }> = ({ visible, loading = false, onCancel, onContinue }) => {
54
+ }> = ({ visible, loading = false, degraded = false, onCancel, onContinue }) => {
49
55
  const { colors } = useTheme()
50
56
  const Ionicons = loadIonicons()
51
57
 
@@ -74,7 +80,9 @@ export const BiometricAdvisoryModal: React.FC<{
74
80
  <Ionicons name="finger-print" size={28} color={colors.accent} />
75
81
  </View>
76
82
  <Text style={[styles.title, { color: colors.textPrimary }]}>{t('biometric_advisory_title')}</Text>
77
- <Text style={[styles.body, { color: colors.textSecondary }]}>{t('biometric_advisory_body')}</Text>
83
+ <Text style={[styles.body, { color: colors.textSecondary }]}>
84
+ {t(degraded ? 'biometric_advisory_body_degraded' : 'biometric_advisory_body')}
85
+ </Text>
78
86
 
79
87
  <PressableScale
80
88
  haptic="confirm"
@@ -89,7 +97,12 @@ export const BiometricAdvisoryModal: React.FC<{
89
97
  )}
90
98
  </PressableScale>
91
99
 
92
- <PressableScale haptic="tap" onPress={loading ? undefined : onCancel} disabled={loading} style={styles.secondary}>
100
+ <PressableScale
101
+ haptic="tap"
102
+ onPress={loading ? undefined : onCancel}
103
+ disabled={loading}
104
+ style={styles.secondary}
105
+ >
93
106
  <Text style={[styles.secondaryLabel, { color: loading ? colors.textTertiary : colors.textSecondary }]}>
94
107
  {t('cancel')}
95
108
  </Text>
@@ -0,0 +1,149 @@
1
+ /**
2
+ * The "ACTIVITY" block of a contact: every interaction with them, drawn with
3
+ * the SAME row Home uses (sigil tile, description, status dot + time, the
4
+ * figure in the display currency with the other denomination beneath), so a
5
+ * payment looks identical whether you find it on Home or on the person.
6
+ *
7
+ * A token settlement has no wallet action of its own here — `getContactActivity`
8
+ * reads it straight off `token_settlements` — so this builds the minimal
9
+ * action `ActivityRow` needs around it and hands the token facts through the
10
+ * row's own `token` prop, exactly as Home does for a `'mandala'`-labelled row.
11
+ */
12
+ import React, { useCallback, useMemo, useState } from 'react'
13
+ import { Linking, StyleSheet, Text, View } from 'react-native'
14
+ import { useTranslation } from 'react-i18next'
15
+ import { useTheme, spacing, typography, useWallet } from '@bsv/expo-wallet-toolbox'
16
+ import ActivityRow, { type ActivityAction } from './ActivityRow'
17
+ import { showToast } from '../ui/Toast'
18
+ import { useMandala } from '../../hooks/useMandala'
19
+ import { formatTokenAmount } from '../../tokenFormat'
20
+ import { tokenRowStatusView } from '../../tokenStatus'
21
+ import type { TokenActivityStatus } from '../../../core/mandala/runtime'
22
+ import type { ContactActivityItem, ContactSettlementRow } from '../../../core/contacts/contactActivity'
23
+
24
+ /** Same reading of a settlement's `state` as the runtime's `activityStatusOf`,
25
+ * minus the "stuck after N hours" clock — a contact page is a record, not a
26
+ * queue, so an old unsettled row reads as "settling" rather than as a fault
27
+ * to act on (the acting happens on Home). */
28
+ function statusOf(row: ContactSettlementRow): TokenActivityStatus {
29
+ switch (row.state) {
30
+ case 'broadcast':
31
+ case 'admitted':
32
+ return 'settled'
33
+ case 'refused':
34
+ return 'refused'
35
+ case 'orphaned':
36
+ return 'reversed'
37
+ default:
38
+ return 'settling'
39
+ }
40
+ }
41
+
42
+ const noop = () => {}
43
+
44
+ export default function ContactActivityList({
45
+ items,
46
+ identityKey
47
+ }: {
48
+ items: ContactActivityItem[]
49
+ identityKey: string
50
+ }) {
51
+ const { t } = useTranslation()
52
+ const { colors } = useTheme()
53
+ const { settings, selectedNetwork } = useWallet()
54
+ const mandala = useMandala()
55
+ const currency = settings?.currency || 'BSV'
56
+ const [expanded, setExpanded] = useState<string | null>(null)
57
+ const onToggle = useCallback((key: string) => setExpanded(prev => (prev === key ? null : key)), [])
58
+
59
+ const onExplorer = useCallback(
60
+ (txid: string) => {
61
+ const base =
62
+ selectedNetwork === 'main'
63
+ ? 'https://whatsonchain.com'
64
+ : selectedNetwork === 'teratest'
65
+ ? 'https://woc-ttn.bsvblockchain.tech'
66
+ : 'https://test.whatsonchain.com'
67
+ Linking.openURL(`${base}/tx/${txid}`).catch(() => showToast(t('explorer_open_failed'), { type: 'error' }))
68
+ },
69
+ [selectedNetwork, t]
70
+ )
71
+
72
+ const rows = useMemo(
73
+ () =>
74
+ items.map(item => {
75
+ const key = `${item.kind}:${item.txid}`
76
+ if (item.kind === 'bsv') {
77
+ return { key, action: item as unknown as ActivityAction, token: undefined }
78
+ }
79
+ const holding = (mandala.balances ?? []).find(b => b.asset.assetId === item.assetId)
80
+ const ticker = holding?.asset.ticker ?? item.assetId.slice(0, 8)
81
+ const incoming = item.role === 'received'
82
+ const figure =
83
+ holding && item.amountBaseUnits !== undefined
84
+ ? formatTokenAmount(incoming ? item.amountBaseUnits : -item.amountBaseUnits, holding.asset.decimals, {
85
+ showPlus: incoming
86
+ })
87
+ : undefined
88
+ const action: ActivityAction = {
89
+ txid: item.txid,
90
+ satoshis: 0,
91
+ status: 'completed',
92
+ isOutgoing: !incoming,
93
+ description: '',
94
+ labels: ['mandala'],
95
+ created_at: item.createdAt
96
+ } as unknown as ActivityAction
97
+ return {
98
+ key,
99
+ action,
100
+ token: {
101
+ title: t(incoming ? 'token_row_received' : 'token_row_sent', { ticker }),
102
+ amount: figure ? { value: figure, unit: ticker } : undefined,
103
+ incoming,
104
+ counterpartyKey: identityKey,
105
+ status: tokenRowStatusView(statusOf(item), incoming),
106
+ statusText: t(tokenRowStatusView(statusOf(item), incoming).key)
107
+ }
108
+ }
109
+ }),
110
+ [items, mandala.balances, identityKey, t]
111
+ )
112
+
113
+ if (rows.length === 0) {
114
+ return <Text style={[styles.empty, { color: colors.textSecondary }]}>{t('contact_activity_empty')}</Text>
115
+ }
116
+
117
+ return (
118
+ <View>
119
+ {rows.map(({ key, action, token }, idx) => (
120
+ <View
121
+ key={key}
122
+ style={
123
+ idx < rows.length - 1 && {
124
+ borderBottomWidth: StyleSheet.hairlineWidth,
125
+ borderBottomColor: colors.separator
126
+ }
127
+ }
128
+ >
129
+ <ActivityRow
130
+ currency={currency}
131
+ action={action}
132
+ rowKey={key}
133
+ token={token}
134
+ expanded={expanded === key}
135
+ busy={false}
136
+ onToggle={onToggle}
137
+ onExplorer={onExplorer}
138
+ onRefreshTx={noop}
139
+ onAbort={noop}
140
+ />
141
+ </View>
142
+ ))}
143
+ </View>
144
+ )
145
+ }
146
+
147
+ const styles = StyleSheet.create({
148
+ empty: { ...typography.footnote, paddingHorizontal: spacing.xl, paddingVertical: spacing.sm }
149
+ })
@@ -0,0 +1,49 @@
1
+ /**
2
+ * A counterparty's face: their avatar when one is known, otherwise always
3
+ * their generative sigil — never an initials placeholder (2026-09-18 design
4
+ * ruling). Shared by Contacts, Contact, New Contact and Pay's recipient card,
5
+ * so all four draw the same face for the same identity key.
6
+ */
7
+ import React from 'react'
8
+ import { Image, StyleSheet, View } from 'react-native'
9
+ import { useTheme, counterpartyHue, sigilPointOf, sigilPalette, type Counterparty } from '@bsv/expo-wallet-toolbox'
10
+ import Sigil from '../ui/Sigil'
11
+
12
+ export default function ContactSigil({
13
+ identityKey,
14
+ avatarUrl,
15
+ size = 38,
16
+ radius = 12
17
+ }: {
18
+ identityKey: string
19
+ avatarUrl?: string
20
+ size?: number
21
+ radius?: number
22
+ }) {
23
+ const { isDark } = useTheme()
24
+ if (avatarUrl) {
25
+ return (
26
+ <Image source={{ uri: avatarUrl }} style={[styles.tile, { width: size, height: size, borderRadius: radius }]} />
27
+ )
28
+ }
29
+ const cp: Counterparty = { kind: 'identityKey', value: identityKey }
30
+ const point = sigilPointOf(cp)
31
+ const palette = sigilPalette(counterpartyHue(cp), isDark)
32
+ return (
33
+ <View
34
+ style={[styles.tile, { width: size, height: size, borderRadius: radius, backgroundColor: palette.background }]}
35
+ >
36
+ <Sigil
37
+ point={point}
38
+ size={size}
39
+ foreground={palette.foreground}
40
+ background={palette.background}
41
+ detail="default"
42
+ />
43
+ </View>
44
+ )
45
+ }
46
+
47
+ const styles = StyleSheet.create({
48
+ tile: { alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }
49
+ })
@@ -0,0 +1,99 @@
1
+ /**
2
+ * "Edit picture" — the stacked pill buttons that choose where an avatar comes
3
+ * from.
4
+ *
5
+ * Today that is one source: a picked icon. Take Photo and Photo Library are
6
+ * deliberately ABSENT rather than present-and-inert — they need
7
+ * `expo-image-picker`, a native dependency this build does not carry, and a
8
+ * button that does nothing when tapped is worse than a button that is not
9
+ * there (the same reasoning that kept a dead "Add photo" control off this
10
+ * screen originally). Add the two entries here once the dependency lands.
11
+ */
12
+ import React from 'react'
13
+ import { Modal, Pressable, StyleSheet, Text, View } from 'react-native'
14
+ import { useTranslation } from 'react-i18next'
15
+ import Animated, { useAnimatedStyle, useReducedMotion, useSharedValue, withTiming } from 'react-native-reanimated'
16
+ import { durations, easings, radii, spacing, typography, useTheme } from '@bsv/expo-wallet-toolbox'
17
+ import PressableScale from '../ui/PressableScale'
18
+
19
+ export interface EditPictureOption {
20
+ key: string
21
+ label: string
22
+ onPress: () => void
23
+ }
24
+
25
+ export default function EditPictureSheet({
26
+ visible,
27
+ options,
28
+ onClose
29
+ }: {
30
+ visible: boolean
31
+ options: EditPictureOption[]
32
+ onClose: () => void
33
+ }) {
34
+ const { colors } = useTheme()
35
+ const { t } = useTranslation()
36
+ const reduced = useReducedMotion()
37
+ const progress = useSharedValue(0)
38
+
39
+ React.useEffect(() => {
40
+ progress.value = withTiming(visible ? 1 : 0, {
41
+ duration: visible ? durations.quick : durations.instant,
42
+ easing: easings.out
43
+ })
44
+ }, [visible, progress])
45
+
46
+ const cardStyle = useAnimatedStyle(() =>
47
+ reduced
48
+ ? { opacity: progress.value, transform: [{ translateY: 0 }] }
49
+ : { opacity: progress.value, transform: [{ translateY: (1 - progress.value) * 24 }] }
50
+ )
51
+ const scrimStyle = useAnimatedStyle(() => ({ opacity: progress.value }))
52
+
53
+ return (
54
+ <Modal visible={visible} transparent animationType="none" onRequestClose={onClose}>
55
+ <View style={StyleSheet.absoluteFill}>
56
+ <Animated.View style={[StyleSheet.absoluteFill, scrimStyle]}>
57
+ <Pressable style={[StyleSheet.absoluteFill, { backgroundColor: colors.scrim }]} onPress={onClose} />
58
+ </Animated.View>
59
+ <Animated.View style={[styles.wrap, cardStyle]} pointerEvents="box-none">
60
+ <View style={[styles.card, { backgroundColor: colors.sheetBackground }]}>
61
+ {options.map(opt => (
62
+ <PressableScale
63
+ key={opt.key}
64
+ haptic="tap"
65
+ onPress={() => {
66
+ onClose()
67
+ opt.onPress()
68
+ }}
69
+ accessibilityRole="button"
70
+ style={[styles.pill, { backgroundColor: colors.fillTertiary }]}
71
+ >
72
+ <Text style={[styles.pillLabel, { color: colors.textPrimary }]}>{opt.label}</Text>
73
+ </PressableScale>
74
+ ))}
75
+ </View>
76
+ <PressableScale
77
+ haptic="tap"
78
+ onPress={onClose}
79
+ accessibilityRole="button"
80
+ style={[styles.cancel, { backgroundColor: colors.sheetBackground }]}
81
+ >
82
+ <Text style={[styles.pillLabel, styles.cancelLabel, { color: colors.accent }]}>
83
+ {t('cancel', { defaultValue: 'Cancel' })}
84
+ </Text>
85
+ </PressableScale>
86
+ </Animated.View>
87
+ </View>
88
+ </Modal>
89
+ )
90
+ }
91
+
92
+ const styles = StyleSheet.create({
93
+ wrap: { position: 'absolute', left: 0, right: 0, bottom: 0, padding: spacing.md, paddingBottom: spacing.xxxl },
94
+ card: { borderRadius: radii.xl, padding: spacing.sm, gap: spacing.sm },
95
+ pill: { borderRadius: radii.lg, paddingVertical: spacing.lg, alignItems: 'center' },
96
+ pillLabel: { ...typography.title3, fontWeight: '600' },
97
+ cancel: { borderRadius: radii.xl, paddingVertical: spacing.lg, alignItems: 'center', marginTop: spacing.sm },
98
+ cancelLabel: { fontWeight: '700' }
99
+ })