@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
@@ -71,6 +71,7 @@ import {
71
71
  isMessageBoxNetworkError,
72
72
  generateMnemonicWallet,
73
73
  backupAttestation,
74
+ isVaultAvailable,
74
75
  type PendingResend
75
76
  } from '@bsv/expo-wallet-toolbox'
76
77
  import ActivityRow, { type ActivityAction } from '../components/wallet/ActivityRow'
@@ -84,6 +85,13 @@ import { storageMatchesNetwork } from '../../core/net/chainMatch'
84
85
  import { makeMetadataDecryptor } from '../../core/peerpay/metadataDecryptor'
85
86
  import { getPendingCorruptNotice, readUnprocessedPending } from '../../core/localpay/pending'
86
87
  import { homeBadges } from './homeBadges'
88
+ import { tokenRowTitle } from './tokenRowTitle'
89
+ import { useMandala, useMandalaRuntime, useTokenActivity, tokenActivityByTxid } from '../hooks/useMandala'
90
+ import { announceEviction, evictionsFrom } from '../components/wallet/tokenEviction'
91
+ import { SEEN_EVICTIONS_KEY, useSeenSet } from '../tokenSeen'
92
+ import { tokenStatusKey } from '../tokenStatus'
93
+ import { formatTokenAmount, tokenAmountParts } from '../tokenFormat'
94
+ import AssetSwitcherDropdown, { BSV_LABEL } from '../components/wallet/AssetSwitcherDropdown'
87
95
  import { exportTransactionsAsCsv } from '../exportTransactions'
88
96
  import PressableScale from '../components/ui/PressableScale'
89
97
  import ScreenGradient from '../components/ui/ScreenGradient'
@@ -240,12 +248,17 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
240
248
  settings,
241
249
  walletBuilt,
242
250
  walletBuilding,
243
- buildWalletFromMnemonic
251
+ buildWalletFromMnemonic,
252
+ mandalaSettlement
244
253
  } = useWallet()
245
254
  const { createMnemonic, hasStoredIdentity, secretsReady } = useLocalStorage()
246
255
  const { satoshisPerUSD, usdToFiat = {} } = useContext(ExchangeRateContext)
247
256
  const currency = settings?.currency || 'BSV'
248
257
  const online = useOnline()
258
+ // For the token Resend below. Read here rather than off `useMandala()` (which
259
+ // mounts further down) so the handler can close over it without a
260
+ // use-before-declaration.
261
+ const mandalaRuntime = useMandalaRuntime()
249
262
 
250
263
  // ── lazy wallet creation ────────────────────────────────────────────
251
264
  /**
@@ -296,7 +309,15 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
296
309
  } finally {
297
310
  creatingWalletRef.current = false
298
311
  }
299
- }, [managers.permissionsManager, secretsReady, walletBuilding, hasStoredIdentity, createMnemonic, buildWalletFromMnemonic, router])
312
+ }, [
313
+ managers.permissionsManager,
314
+ secretsReady,
315
+ walletBuilding,
316
+ hasStoredIdentity,
317
+ createMnemonic,
318
+ buildWalletFromMnemonic,
319
+ router
320
+ ])
300
321
 
301
322
  const [pendingDestination, setPendingDestination] = useState<string | null>(null)
302
323
  const [showBiometricAdvisory, setShowBiometricAdvisory] = useState(false)
@@ -381,6 +402,9 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
381
402
  /** Where the pinned block ends, so the fade below it can be painted in the
382
403
  * backdrop's colour at exactly that point rather than a guess. */
383
404
  const [pinnedHeight, setPinnedHeight] = useState(0)
405
+ /** Where the top bar ends, so the switcher dropdown (design 4a) can anchor
406
+ * itself right under it instead of guessing a fixed offset. */
407
+ const [headerHeight, setHeaderHeight] = useState(0)
384
408
  const [pendingCorrupt, setPendingCorrupt] = useState(false)
385
409
  // Per-row in-flight action, keyed by txid (or reference for abort) so only
386
410
  // the tapped row shows a spinner rather than the whole list.
@@ -891,31 +915,46 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
891
915
  try {
892
916
  const pm = managers.permissionsManager
893
917
  if (!pm || !storage) throw new Error(t('unknown_error'))
894
- const url = await readMessageBoxUrl()
895
- if (!url) {
896
- showToast(t('message_box_unreachable'), { type: 'error' })
897
- return
898
- }
899
- const client = new PeerPayClient({
900
- messageBoxHost: url,
901
- walletClient: pm as never,
902
- originator: adminOriginator
918
+ // Network first for a fresh proof; this device's own copy when the
919
+ // network has never heard of the transaction — a nearby payment whose
920
+ // code was never scanned is `nosend`, and that is the case a resend
921
+ // most needs to cover.
922
+ const refetch = makeResendBeef({
923
+ refetch: makeBeefRepair({ woc: wocConfigFor(selectedNetwork), online: getOnline }),
924
+ storage
903
925
  })
904
- const outcome = await resendPaymentDetails({
905
- client,
906
- storage,
907
- txid,
908
- listPeerPayAction: makeListPeerPayAction(pm, adminOriginator),
909
- // Network first for a fresh proof; this device's own copy when the
910
- // network has never heard of the transaction — a nearby payment whose
911
- // code was never scanned is `nosend`, and that is the case a resend
912
- // most needs to cover.
913
- decryptMetadata: makeMetadataDecryptor(pm, adminOriginator),
914
- refetch: makeResendBeef({
915
- refetch: makeBeefRepair({ woc: wocConfigFor(selectedNetwork), online: getOnline }),
916
- storage
926
+ const decryptMetadata = makeMetadataDecryptor(pm, adminOriginator)
927
+ // Every resend goes over the message box, whatever rail the payment
928
+ // first took. What differs is the body: a token row re-sends the
929
+ // Mandala transfer notification (the runtime rebuilds it from the
930
+ // blinding journal and the payee output's marker); a BSV row rebuilds
931
+ // its BRC-29 PeerPay token. Identification is by LABEL, like every
932
+ // other token decision on this screen.
933
+ const isToken = actions.find(a => a.txid === txid)?.labels?.includes('mandala') ?? false
934
+ let outcome: Awaited<ReturnType<typeof resendPaymentDetails>>
935
+ if (isToken) {
936
+ if (!mandalaRuntime) throw new Error(t('unknown_error'))
937
+ outcome = await mandalaRuntime.resendTransfer(txid, { refetch, decryptMetadata })
938
+ } else {
939
+ const url = await readMessageBoxUrl()
940
+ if (!url) {
941
+ showToast(t('message_box_unreachable'), { type: 'error' })
942
+ return
943
+ }
944
+ const client = new PeerPayClient({
945
+ messageBoxHost: url,
946
+ walletClient: pm as never,
947
+ originator: adminOriginator
917
948
  })
918
- })
949
+ outcome = await resendPaymentDetails({
950
+ client,
951
+ storage,
952
+ txid,
953
+ listPeerPayAction: makeListPeerPayAction(pm, adminOriginator),
954
+ decryptMetadata,
955
+ refetch
956
+ })
957
+ }
919
958
  if (outcome.ok) {
920
959
  // A parked payment has now been handed over for real, over a rail
921
960
  // that confirms delivery. Release it so this wallet broadcasts it
@@ -944,7 +983,18 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
944
983
  setBusyLabel(undefined)
945
984
  }
946
985
  },
947
- [busyRow, managers.permissionsManager, storage, adminOriginator, selectedNetwork, offlineByTxid, onRefresh, t]
986
+ [
987
+ busyRow,
988
+ managers.permissionsManager,
989
+ storage,
990
+ adminOriginator,
991
+ selectedNetwork,
992
+ offlineByTxid,
993
+ onRefresh,
994
+ t,
995
+ actions,
996
+ mandalaRuntime
997
+ ]
948
998
  )
949
999
 
950
1000
  const onFailedSendAgain = useCallback(
@@ -1019,10 +1069,7 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1019
1069
  // The rest pass through the grace filter: online, a payment the drain is
1020
1070
  // about to post says nothing worth reading, and the banner appearing for the
1021
1071
  // half second before it lands reads as a fault that is not there.
1022
- const queued = useMemo(
1023
- () => offlineRows.filter(r => r.status !== 'rejected' && r.status !== 'parked'),
1024
- [offlineRows]
1025
- )
1072
+ const queued = useMemo(() => offlineRows.filter(r => r.status !== 'rejected' && r.status !== 'parked'), [offlineRows])
1026
1073
  const { shown: queuedShown, nextCheckMs } = useMemo(
1027
1074
  // graceNonce is a dependency only: it carries no value into the call, it
1028
1075
  // just re-runs it once a young row has aged past the grace.
@@ -1039,15 +1086,73 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1039
1086
  }, [nextCheckMs])
1040
1087
  const queuedCount = queuedShown.length
1041
1088
  const queuedSent = useMemo(() => queuedShown.filter(r => r.role === 'sent'), [queuedShown])
1089
+ // ── stablecoins ─────────────────────────────────────────────────────
1090
+ // Every token surface below is conditional on a fact being true, and the
1091
+ // first fact is "you hold one": with no runtime and no balances this screen
1092
+ // renders exactly what it rendered before any of this existed.
1093
+ const mandala = useMandala()
1094
+ const tokenActivity = useTokenActivity()
1095
+ const tokenByTxid = useMemo(() => tokenActivityByTxid(tokenActivity.rows), [tokenActivity.rows])
1096
+ const seenEvictions = useSeenSet(SEEN_EVICTIONS_KEY)
1097
+ /** True the moment any token balance exists — the gate for the coin switcher. */
1098
+ const hasTokens = (mandala.balances?.length ?? 0) > 0
1099
+
1100
+ // ── the coin on screen ──────────────────────────────────────────────
1101
+ /**
1102
+ * Which money the screen is showing (design 1b, 2026-09-15): `null` is BSV,
1103
+ * the default and the only coin a wallet with no token ever shows. Picked in
1104
+ * the switcher the hero label opens; it decides the hero figure, which
1105
+ * activity rows are listed, and what Pay / Get paid are armed with — so the
1106
+ * Pay screen never asks the asset question a second time.
1107
+ */
1108
+ const [selectedAssetId, setSelectedAssetId] = useState<string | null>(null)
1109
+ const [switcherOpen, setSwitcherOpen] = useState(false)
1110
+ const heldAsset = useMemo(
1111
+ () => (selectedAssetId ? (mandala.balances?.find(b => b.asset.assetId === selectedAssetId) ?? null) : null),
1112
+ [selectedAssetId, mandala.balances]
1113
+ )
1114
+ // A coin that is no longer held (spent to zero, or a wallet switch) falls
1115
+ // back to BSV. `balances === null` is UNKNOWN, not "holds nothing", and
1116
+ // decides nothing.
1117
+ useEffect(() => {
1118
+ if (selectedAssetId && mandala.balances && !heldAsset) setSelectedAssetId(null)
1119
+ }, [selectedAssetId, mandala.balances, heldAsset])
1120
+
1121
+ /**
1122
+ * Money that left without a sentence. `showAlert`, once per transaction —
1123
+ * the one modal this feature spends, because a balance that simply drops is
1124
+ * the worst failure in the system on a phone.
1125
+ */
1126
+ useEffect(() => {
1127
+ const pending = evictionsFrom(tokenActivity.rows, seenEvictions.seen)
1128
+ if (pending.length === 0) return
1129
+ let live = true
1130
+ void (async () => {
1131
+ for (const notice of pending) {
1132
+ if (!live) return
1133
+ // Marked before the await resolves: an alert the user dismisses by
1134
+ // backgrounding the app must not re-fire on every foreground after.
1135
+ seenEvictions.see(notice.txid)
1136
+ await announceEviction(t, notice)
1137
+ }
1138
+ })()
1139
+ return () => {
1140
+ live = false
1141
+ }
1142
+ // `seenEvictions.see` is stable; `seen` is the gate and belongs here.
1143
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1144
+ }, [tokenActivity.rows, seenEvictions.seen, t])
1145
+
1042
1146
  const stuckBadges = useMemo(
1043
1147
  () =>
1044
1148
  homeBadges({
1045
1149
  attention: attentionCount,
1046
1150
  unsent: unsentCount,
1047
1151
  offlineQueued: queuedCount,
1048
- offlineRejected: rejected.length + sentRejected.length
1152
+ offlineRejected: rejected.length + sentRejected.length,
1153
+ tokenAttention: mandala.stuck.length
1049
1154
  }).filter(b => b.kind !== 'offline'),
1050
- [attentionCount, unsentCount, queuedCount, rejected.length, sentRejected.length]
1155
+ [attentionCount, unsentCount, queuedCount, rejected.length, sentRejected.length, mandala.stuck.length]
1051
1156
  )
1052
1157
  const reloadOffline = useCallback(() => {
1053
1158
  void fetchOfflineRows()
@@ -1055,6 +1160,15 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1055
1160
  const pushPay = useCallback((sats?: number) => {
1056
1161
  router.push(sats && sats > 0 ? `/pay?sats=${sats}` : '/pay')
1057
1162
  }, [])
1163
+ /** `/pay` for the coin on screen: a token rides along as `?asset=`, BSV needs nothing. */
1164
+ const payDestination = useCallback(
1165
+ (direction: 'pay' | 'get') => {
1166
+ const base = direction === 'get' ? '/pay?direction=get' : '/pay'
1167
+ if (!heldAsset) return base
1168
+ return `${base}${direction === 'get' ? '&' : '?'}asset=${encodeURIComponent(heldAsset.asset.assetId)}`
1169
+ },
1170
+ [heldAsset]
1171
+ )
1058
1172
  const { onRequestAgain, onCopyDetails, onDismiss, onSendAgain } = useOfflineNoticeActions({
1059
1173
  storage,
1060
1174
  permissionsManager: managers.permissionsManager,
@@ -1067,7 +1181,32 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1067
1181
  })
1068
1182
 
1069
1183
  // ── rows ────────────────────────────────────────────────────────────
1070
- const rows = useMemo(() => withDayHeaders(actions, t), [actions, t])
1184
+ /**
1185
+ * The activity list follows the coin on screen. A token shows only its own
1186
+ * transfers; BSV, once a token is held, hides them — a "Sent USDX" row under
1187
+ * a BSV figure would read as BSV leaving. A wallet with no token filters
1188
+ * nothing, and lists exactly what it listed before any of this existed.
1189
+ * Token rows are recognised by LABEL, not by holdings, like `renderItem`.
1190
+ */
1191
+ const visibleActions = useMemo(() => {
1192
+ if (!hasTokens) return actions
1193
+ if (heldAsset) {
1194
+ return actions.filter(
1195
+ a => !!a.txid && tokenByTxid.get(a.txid.toLowerCase())?.asset.assetId === heldAsset.asset.assetId
1196
+ )
1197
+ }
1198
+ return actions.filter(a => !a.labels?.includes('mandala'))
1199
+ }, [actions, hasTokens, heldAsset, tokenByTxid])
1200
+ const rows = useMemo(() => withDayHeaders(visibleActions, t), [visibleActions, t])
1201
+
1202
+ // A filtered page can come up short — or empty — while the server still has
1203
+ // more, and a list too short to scroll never fires onEndReached. Keep
1204
+ // paging until the visible list is a page long or the history is spent.
1205
+ useEffect(() => {
1206
+ if (!hasTokens || loading || loadingMore || actions.length === 0) return
1207
+ if (visibleActions.length >= PAGE_SIZE || exhaustedRef.current) return
1208
+ void loadMore()
1209
+ }, [hasTokens, loading, loadingMore, actions.length, visibleActions.length, loadMore])
1071
1210
 
1072
1211
  /** Cancel a parked payment: abort the action so the inputs come back, and
1073
1212
  * retire its queue row. Refuses once the counterparty has broadcast. */
@@ -1077,16 +1216,25 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1077
1216
  if (!storage || !pm || busyRow) return
1078
1217
  setBusyRow(txid)
1079
1218
  setBusyLabel(t('cancelling_payment'))
1219
+ // FIX J: a token payment's cancel is overlay-authoritative — pass the
1220
+ // settlement deps so `cancelParkedPayment` checks admission before
1221
+ // aborting, refusing with 'already-sent' if the recipient's own submit
1222
+ // already beat the cancel (rule 3: the RECIPIENT settles the hop).
1223
+ // `mandalaSettlement` is `undefined` whenever Mandala is unavailable,
1224
+ // which leaves a plain BSV cancel exactly as it behaves today.
1225
+ const isTokenRow = tokenByTxid.has(txid)
1080
1226
  try {
1081
1227
  const outcome = await cancelParkedPayment({
1082
1228
  storage,
1083
1229
  wallet: pm as unknown as CancelParkedWallet,
1084
1230
  originator: adminOriginator,
1085
- txid
1231
+ txid,
1232
+ settlement: mandalaSettlement
1086
1233
  })
1087
1234
  if (outcome === 'cancelled') showToast(t('tx_abort_success'), { type: 'success' })
1088
- else if (outcome === 'already-sent') showToast(t('pay_parked_already_sent'), { type: 'info' })
1089
- else showToast(t('tx_abort_failed'), { type: 'error' })
1235
+ else if (outcome === 'already-sent') {
1236
+ showToast(t(isTokenRow ? 'token_cancel_already_sent' : 'pay_parked_already_sent'), { type: 'info' })
1237
+ } else showToast(t('tx_abort_failed'), { type: 'error' })
1090
1238
  await onRefresh()
1091
1239
  } catch (e: unknown) {
1092
1240
  showToast(e instanceof Error ? e.message : t('unknown_error'), { type: 'error' })
@@ -1095,9 +1243,50 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1095
1243
  setBusyLabel(undefined)
1096
1244
  }
1097
1245
  },
1098
- [storage, managers.permissionsManager, adminOriginator, busyRow, onRefresh, t]
1246
+ [storage, managers.permissionsManager, adminOriginator, busyRow, onRefresh, t, mandalaSettlement, tokenByTxid]
1099
1247
  )
1100
1248
 
1249
+ /**
1250
+ * The token half of each row, precomputed and keyed by txid.
1251
+ *
1252
+ * Built once per activity change rather than inline per render: `ActivityRow`
1253
+ * is memoised on prop identity, and a fresh object per render would defeat that
1254
+ * for exactly the rows a token holder scrolls past most.
1255
+ */
1256
+ const tokenProps = useMemo(() => {
1257
+ const actionByTxid = new Map(actions.filter(a => a.txid).map(a => [a.txid as string, a]))
1258
+ const map = new Map<string, NonNullable<React.ComponentProps<typeof ActivityRow>['token']>>()
1259
+ for (const [txid, row] of tokenByTxid) {
1260
+ const signedBaseUnits = row.role === 'sent' ? -row.baseUnits : row.baseUnits
1261
+ const figure = formatTokenAmount(signedBaseUnits, row.asset.decimals, {
1262
+ showPlus: row.role === 'received'
1263
+ })
1264
+ const action = actionByTxid.get(txid)
1265
+ map.set(txid, {
1266
+ title: tokenRowTitle({
1267
+ role: row.role,
1268
+ ticker: row.asset.ticker,
1269
+ labels: action?.labels,
1270
+ description: action?.description,
1271
+ assetId: row.asset.assetId,
1272
+ baseUnits: row.baseUnits,
1273
+ t
1274
+ }),
1275
+ amount: figure ? { value: figure, unit: row.asset.ticker } : undefined,
1276
+ incoming: row.role === 'received',
1277
+ // The same generative face a BSV row draws, keyed on the token row's
1278
+ // OWN counterparty key rather than the wallet action's labels/sender
1279
+ // (meaningless for a token transfer) — see TokenActivityRow.counterpartyKey.
1280
+ // A received row is keyed on the sender's blinded per-payment key A′
1281
+ // by design (spec D2): the image differs on every payment from the
1282
+ // same payer, which is the point of the blinding, not a bug in it.
1283
+ counterpartyKey: row.counterpartyKey,
1284
+ statusText: t(tokenStatusKey(row.status))
1285
+ })
1286
+ }
1287
+ return map
1288
+ }, [tokenByTxid, actions, t])
1289
+
1101
1290
  const renderItem: ListRenderItem<Row> = useCallback(
1102
1291
  ({ item, index }) => {
1103
1292
  if (item.kind === 'day') {
@@ -1106,12 +1295,16 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1106
1295
  const key = item.txid || item.reference || `row-${index}`
1107
1296
  const offline = item.txid ? offlineByTxid.get(item.txid) : undefined
1108
1297
  const busy = busyRow === item.txid || (!!item.reference && busyRow === item.reference)
1298
+ // Identification is by LABEL, not by holdings: a user who sends their
1299
+ // last token keeps denomination across their whole history.
1300
+ const token = item.labels?.includes('mandala') ? tokenProps.get(key) : undefined
1109
1301
 
1110
1302
  return (
1111
1303
  <ActivityRow
1112
1304
  currency={currency}
1113
1305
  action={item}
1114
1306
  rowKey={key}
1307
+ token={token}
1115
1308
  offlineStatus={offline?.status}
1116
1309
  expanded={expandedRow === key}
1117
1310
  busy={busy}
@@ -1130,6 +1323,7 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1130
1323
  colors,
1131
1324
  currency,
1132
1325
  offlineByTxid,
1326
+ tokenProps,
1133
1327
  busyRow,
1134
1328
  busyLabel,
1135
1329
  expandedRow,
@@ -1145,7 +1339,8 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1145
1339
 
1146
1340
  // ── header (balance + the three destinations + activity heading) ─────
1147
1341
  const balanceParts = useMemo(
1148
- () => (balance === null ? null : formatAmountParts(balance, currency, satoshisPerUSD, { abbreviate: true, usdToFiat })),
1342
+ () =>
1343
+ balance === null ? null : formatAmountParts(balance, currency, satoshisPerUSD, { abbreviate: true, usdToFiat }),
1149
1344
  [balance, currency, satoshisPerUSD, usdToFiat]
1150
1345
  )
1151
1346
 
@@ -1169,27 +1364,48 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1169
1364
  * answer to "how much do I have" and the way to pay were both a scroll back
1170
1365
  * up. Everything below them still scrolls with the activity it describes.
1171
1366
  */
1367
+ /** The hero figure: the token on screen, or the BSV balance. `null` is UNKNOWN. */
1368
+ const heroParts = heldAsset ? tokenAmountParts(heldAsset.baseUnits, heldAsset.asset) : balanceParts
1369
+ const heroText = heroParts ? `${heroParts.value} ${heroParts.unit}`.trim() : undefined
1370
+
1172
1371
  const pinnedHeader = useMemo(
1173
1372
  () => (
1174
1373
  <View>
1175
1374
  <TouchableOpacity
1176
- onPress={() => void refreshBalance()}
1375
+ onPress={() => {
1376
+ void refreshBalance()
1377
+ if (heldAsset) mandala.refresh()
1378
+ }}
1177
1379
  activeOpacity={0.7}
1178
1380
  style={styles.balanceBlock}
1179
1381
  accessibilityLabel={t('wallet_balance_refresh')}
1382
+ accessibilityValue={heroText ? { text: heroText } : undefined}
1180
1383
  >
1181
- <Text style={[styles.balanceLabel, { color: colors.textTertiary }]}>{t('wallet_balance_you_have')}</Text>
1182
- {balanceParts === null ? (
1384
+ {/* With a token held, the coin switcher pill in the top bar IS the
1385
+ label (design 4a) — this block needs none of its own. Without a
1386
+ token it is the plain "You have" of today's screen — a holder
1387
+ with 1,240.00 USDX and no BSV must not read "You have / 0 sats"
1388
+ at display size with their real money elsewhere. */}
1389
+ {!hasTokens && (
1390
+ <Text style={[styles.balanceLabel, { color: colors.textTertiary }]}>{t('wallet_balance_you_have')}</Text>
1391
+ )}
1392
+ {heroParts === null ? (
1183
1393
  <ActivityIndicator color={colors.textSecondary} style={styles.balanceSpinner} />
1184
1394
  ) : (
1185
1395
  <>
1186
1396
  <Text style={[styles.balance, { color: colors.textPrimary }]}>
1187
- {balanceParts.value}
1188
- {balanceParts.unit ? (
1189
- <Text style={[styles.balanceUnit, { color: colors.textSecondary }]}> {balanceParts.unit}</Text>
1397
+ {heroParts.value}
1398
+ {heroParts.unit ? (
1399
+ <Text style={[styles.balanceUnit, { color: colors.textSecondary }]}> {heroParts.unit}</Text>
1190
1400
  ) : null}
1191
1401
  </Text>
1192
- <Text style={[styles.balanceContext, { color: colors.textSecondary }]}>{balanceContext}</Text>
1402
+ {/* Conversions are BSV's alone: the wallet has no price for a
1403
+ token, and a converted figure would be invented (ux §6.1).
1404
+ A token uses the line for its full name instead, so "1,240.00
1405
+ USDX" is never a ticker the holder has to decode. */}
1406
+ <Text style={[styles.balanceContext, { color: colors.textSecondary }]}>
1407
+ {heldAsset ? heldAsset.asset.label || heldAsset.asset.issuerName || '' : balanceContext}
1408
+ </Text>
1193
1409
  </>
1194
1410
  )}
1195
1411
  </TouchableOpacity>
@@ -1199,7 +1415,7 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1199
1415
  <View style={styles.destinations}>
1200
1416
  <PressableScale
1201
1417
  haptic="confirm"
1202
- onPress={() => destinationPress('/pay')}
1418
+ onPress={() => destinationPress(payDestination('pay'))}
1203
1419
  style={[styles.dest, styles.destPrimary, { backgroundColor: colors.accent }]}
1204
1420
  >
1205
1421
  <MaterialCommunityIcons name="arrow-top-right" size={19} color={colors.textOnAccent} />
@@ -1210,33 +1426,58 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1210
1426
 
1211
1427
  <PressableScale
1212
1428
  haptic="confirm"
1213
- onPress={() => destinationPress('/pay?direction=get')}
1429
+ onPress={() => destinationPress(payDestination('get'))}
1214
1430
  style={[styles.dest, { backgroundColor: colors.surfaceRaised, borderColor: colors.surfaceRaisedBorder }]}
1215
1431
  >
1216
1432
  <MaterialCommunityIcons name="arrow-bottom-left" size={19} color={colors.textPrimary} />
1217
1433
  <Text style={[styles.destLabel, { color: colors.textPrimary }]}>{t('pay_direction_receive')}</Text>
1218
1434
  </PressableScale>
1219
1435
 
1220
- {/* Vault — hidden for now; will release once R1-K1 research is complete.
1221
- <PressableScale
1222
- onPress={() => router.push('/vault')}
1223
- style={[
1224
- styles.dest,
1225
- { backgroundColor: colors.surfaceRaised, borderColor: colors.surfaceRaisedBorder }
1226
- ]}
1227
- >
1228
- <MaterialCommunityIcons name="safe" size={19} color={colors.textPrimary} />
1229
- <Text style={[styles.destLabel, { color: colors.textPrimary }]}>
1230
- {t('wallet_vault')}
1231
- </Text>
1232
- </PressableScale>
1233
- */}
1436
+ {/* Release- and network-gated (spec §5.5, task 11): no Vault
1437
+ destination until the host turns vaultEnabled on, and never off
1438
+ mainnet. `selectedNetwork` is a dependency of this memo, so the
1439
+ destination appears and disappears with a network switch. Plain
1440
+ push, not destinationPress — enrolment needs no wallet, and the
1441
+ Vault screen's own Deposit button runs the lazy wallet-creation
1442
+ path when it comes to that. */}
1443
+ {isVaultAvailable(selectedNetwork) && (
1444
+ <PressableScale
1445
+ haptic="confirm"
1446
+ onPress={() => router.push('/vault')}
1447
+ style={[styles.dest, { backgroundColor: colors.surfaceRaised, borderColor: colors.surfaceRaisedBorder }]}
1448
+ >
1449
+ <MaterialCommunityIcons name="safe" size={19} color={colors.textPrimary} />
1450
+ <Text style={[styles.destLabel, { color: colors.textPrimary }]}>{t('wallet_vault')}</Text>
1451
+ </PressableScale>
1452
+ )}
1234
1453
  </View>
1235
1454
  </View>
1236
1455
  ),
1237
- [balanceParts, balanceContext, colors, t, refreshBalance, router]
1456
+ [
1457
+ heroParts,
1458
+ heroText,
1459
+ balanceContext,
1460
+ colors,
1461
+ t,
1462
+ refreshBalance,
1463
+ router,
1464
+ selectedNetwork,
1465
+ hasTokens,
1466
+ heldAsset,
1467
+ mandala,
1468
+ payDestination,
1469
+ destinationPress,
1470
+ MaterialCommunityIcons
1471
+ ]
1238
1472
  )
1239
1473
 
1474
+ /** The issuer a single stuck row is waiting on, when it can be named. */
1475
+ const stuckIssuerName = useMemo(() => {
1476
+ const first = mandala.stuck[0]
1477
+ const held = first ? (mandala.balances ?? []).find(b => b.asset.assetId === first.assetId) : undefined
1478
+ return held?.asset.issuerName || t('token_issuer_fallback')
1479
+ }, [mandala.stuck, mandala.balances, t])
1480
+
1240
1481
  const listHeader = useMemo(
1241
1482
  () => (
1242
1483
  <View>
@@ -1272,14 +1513,40 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1272
1513
  label={
1273
1514
  badge.kind === 'attention'
1274
1515
  ? t('home_payments_need_attention', { count: badge.count })
1275
- : t('home_payments_unsent', { count: badge.count })
1516
+ : badge.kind === 'token_attention'
1517
+ ? // One stuck payment can name the issuer it is waiting
1518
+ // on; several cannot, so the plural says the true
1519
+ // thing instead of naming one of them.
1520
+ badge.count === 1
1521
+ ? t('token_attention_one', { issuer: stuckIssuerName })
1522
+ : t('token_attention_many', { count: badge.count })
1523
+ : t('home_payments_unsent', { count: badge.count })
1524
+ }
1525
+ icon={
1526
+ badge.kind === 'attention'
1527
+ ? 'alert-circle-outline'
1528
+ : badge.kind === 'token_attention'
1529
+ ? 'time-outline'
1530
+ : 'send-outline'
1276
1531
  }
1277
- icon={badge.kind === 'attention' ? 'alert-circle-outline' : 'send-outline'}
1278
1532
  iconColor={colors.warning}
1279
1533
  isLast={i === stuckBadges.length - 1}
1280
- onPress={() =>
1534
+ onPress={() => {
1535
+ if (badge.kind === 'token_attention') {
1536
+ // No per-asset sheet in v1 (2026-09-15 maintainer
1537
+ // decision): route to Pay with that asset selected, so
1538
+ // the holder lands on the form that can actually move
1539
+ // — or retry — the stuck payment.
1540
+ const assetId = mandala.stuck[0]?.assetId
1541
+ router.push(
1542
+ (assetId ? `/pay?asset=${encodeURIComponent(assetId)}` : '/pay') as Parameters<
1543
+ typeof router.push
1544
+ >[0]
1545
+ )
1546
+ return
1547
+ }
1281
1548
  router.push(badge.kind === 'attention' ? '/pay?cell=get-handle' : '/pay?cell=pay-handle')
1282
- }
1549
+ }}
1283
1550
  />
1284
1551
  ))}
1285
1552
  </GroupedSection>
@@ -1356,7 +1623,9 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1356
1623
  onRequestAgain,
1357
1624
  onCopyDetails,
1358
1625
  onDismiss,
1359
- onSendAgain
1626
+ onSendAgain,
1627
+ mandala.stuck,
1628
+ stuckIssuerName
1360
1629
  ]
1361
1630
  )
1362
1631
 
@@ -1364,20 +1633,46 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1364
1633
  <View style={[styles.container, { paddingTop: insets.top }]}>
1365
1634
  <ScreenGradient from={colors.canvasTop} to={colors.canvasBase} height={360} />
1366
1635
 
1367
- {/* Settings is the only thing up here: it is navigation chrome, not a
1368
- money action, so it should not compete with Pay and Vault for the eye.
1369
- Connections moved into Settings as "Connect to App" — pairing a desktop
1370
- app is a once-in-a-while errand, not a home-screen affordance. */}
1371
- <View style={[styles.header, topLeft ? styles.headerSpaced : styles.headerEnd]}>
1372
- {topLeft}
1373
- <TouchableOpacity
1374
- onPress={() => router.push('/wallet-config')}
1375
- style={[styles.iconBtn, { backgroundColor: colors.surfaceRaised, borderColor: colors.surfaceRaisedBorder }]}
1376
- accessibilityRole="button"
1377
- accessibilityLabel={t('wallet_settings')}
1378
- >
1379
- <Ionicons name="settings-outline" size={17} color={colors.textSecondary} />
1380
- </TouchableOpacity>
1636
+ {/* Settings is the only permanent fixture up here: it is navigation
1637
+ chrome, not a money action, so it should not compete with Pay and
1638
+ Vault for the eye. Connections moved into Settings as "Connect to
1639
+ App" — pairing a desktop app is a once-in-a-while errand, not a
1640
+ home-screen affordance.
1641
+ Once a token is held, the coin switcher (design 4a, 2026-09-16)
1642
+ takes the centre column as a filled pill — the screen's title IS
1643
+ the control that changes what the screen is showing, rather than a
1644
+ plain label buried in the balance block below. Both side columns
1645
+ share `iconBtn`'s width so the pill centres over an empty slot too,
1646
+ not just when a host supplies `topLeft`. */}
1647
+ <View style={styles.header} onLayout={e => setHeaderHeight(e.nativeEvent.layout.height)}>
1648
+ <View style={styles.headerSide}>{topLeft}</View>
1649
+ <View style={styles.headerCenter}>
1650
+ {hasTokens && (
1651
+ <TouchableOpacity
1652
+ onPress={() => setSwitcherOpen(true)}
1653
+ activeOpacity={0.7}
1654
+ hitSlop={8}
1655
+ style={[styles.switcherPill, { backgroundColor: colors.accent }]}
1656
+ accessibilityRole="button"
1657
+ accessibilityLabel={t('wallet_coin_switcher')}
1658
+ >
1659
+ <Text style={[styles.switcherPillLabel, { color: colors.textOnAccent }]} numberOfLines={1}>
1660
+ {heldAsset ? heldAsset.asset.ticker : BSV_LABEL}
1661
+ </Text>
1662
+ <Ionicons name="chevron-down" size={12} color={colors.textOnAccent} />
1663
+ </TouchableOpacity>
1664
+ )}
1665
+ </View>
1666
+ <View style={[styles.headerSide, styles.headerSideEnd]}>
1667
+ <TouchableOpacity
1668
+ onPress={() => router.push('/wallet-config')}
1669
+ style={[styles.iconBtn, { backgroundColor: colors.surfaceRaised, borderColor: colors.surfaceRaisedBorder }]}
1670
+ accessibilityRole="button"
1671
+ accessibilityLabel={t('wallet_settings')}
1672
+ >
1673
+ <Ionicons name="settings-outline" size={17} color={colors.textSecondary} />
1674
+ </TouchableOpacity>
1675
+ </View>
1381
1676
  </View>
1382
1677
 
1383
1678
  {/* Renders only when the keys could not be released — a destroyed key, a
@@ -1418,7 +1713,11 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1418
1713
  </PressableScale>
1419
1714
  </View>
1420
1715
  ) : (
1421
- <Text style={[styles.empty, { color: colors.textSecondary }]}>{t('no_transactions')}</Text>
1716
+ <Text style={[styles.empty, { color: colors.textSecondary }]}>
1717
+ {heldAsset
1718
+ ? t('wallet_activity_empty_asset', { ticker: heldAsset.asset.ticker })
1719
+ : t('no_transactions')}
1720
+ </Text>
1422
1721
  )
1423
1722
  }
1424
1723
  onEndReached={loadMore}
@@ -1484,6 +1783,19 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1484
1783
  visible={!hasWallet && secretsReady && !walletBuilding && knownNoStoredIdentity}
1485
1784
  onImport={() => router.push('/auth/mnemonic?flow=import')}
1486
1785
  />
1786
+
1787
+ {/* Mounted only once a token is held: a wallet without one keeps today's tree. */}
1788
+ {hasTokens && (
1789
+ <AssetSwitcherDropdown
1790
+ visible={switcherOpen}
1791
+ onClose={() => setSwitcherOpen(false)}
1792
+ top={insets.top + headerHeight}
1793
+ balances={mandala.balances ?? []}
1794
+ selected={heldAsset ? heldAsset.asset.assetId : null}
1795
+ onSelect={setSelectedAssetId}
1796
+ bsv={balanceParts}
1797
+ />
1798
+ )}
1487
1799
  </View>
1488
1800
  )
1489
1801
  }
@@ -1499,8 +1811,12 @@ const styles = StyleSheet.create({
1499
1811
  paddingTop: spacing.sm,
1500
1812
  paddingBottom: spacing.xs
1501
1813
  },
1502
- headerEnd: { justifyContent: 'flex-end' },
1503
- headerSpaced: { justifyContent: 'space-between' },
1814
+ // Both sides share the settings icon's width, so the centre column (the
1815
+ // switcher pill, when it's there) stays centred whether or not a host
1816
+ // supplies `topLeft` — an empty slot is still a slot the same size.
1817
+ headerSide: { minWidth: 34, alignItems: 'flex-start', justifyContent: 'center' },
1818
+ headerSideEnd: { alignItems: 'flex-end' },
1819
+ headerCenter: { flex: 1, alignItems: 'center' },
1504
1820
  iconBtn: {
1505
1821
  width: 34,
1506
1822
  height: 34,
@@ -1509,6 +1825,21 @@ const styles = StyleSheet.create({
1509
1825
  alignItems: 'center',
1510
1826
  justifyContent: 'center'
1511
1827
  },
1828
+ // The switcher pill (design 4a): filled with the accent colour so it reads
1829
+ // as the screen's title AND its primary control, not a secondary label.
1830
+ switcherPill: {
1831
+ flexDirection: 'row',
1832
+ alignItems: 'center',
1833
+ gap: 6,
1834
+ paddingVertical: 8,
1835
+ paddingLeft: 14,
1836
+ paddingRight: 10,
1837
+ borderRadius: radii.pill
1838
+ },
1839
+ switcherPillLabel: {
1840
+ ...typography.headline,
1841
+ fontWeight: '700'
1842
+ },
1512
1843
  balanceBlock: {
1513
1844
  alignItems: 'center',
1514
1845
  paddingTop: spacing.xxl,
@@ -1563,8 +1894,8 @@ const styles = StyleSheet.create({
1563
1894
  borderColor: 'transparent',
1564
1895
  shadowColor: '#000',
1565
1896
  shadowOpacity: 0.28,
1566
- shadowRadius: 14,
1567
- shadowOffset: { width: 0, height: 8 },
1897
+ shadowRadius: 6,
1898
+ shadowOffset: { width: 0, height: 2 },
1568
1899
  elevation: 4
1569
1900
  },
1570
1901
  destLabel: { fontSize: 13, fontWeight: '600' },