@bsv/expo-wallet-toolbox 0.7.0 → 0.10.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 (154) hide show
  1. package/CHANGELOG.md +1790 -0
  2. package/README.md +54 -1
  3. package/core/amountFormatHelpers.ts +20 -2
  4. package/core/backup/RemoteSyncReader.ts +131 -19
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +147 -9
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +70 -4
  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/constants.ts +14 -1
  15. package/core/context/ExchangeRateContext.tsx +34 -27
  16. package/core/context/LocalStorageProvider.tsx +43 -40
  17. package/core/context/UserContext.tsx +18 -7
  18. package/core/context/VaultContext.tsx +49 -2
  19. package/core/context/WalletConnectionContext.tsx +203 -11
  20. package/core/context/WalletContext.tsx +653 -175
  21. package/core/headers/OfflineFirstChaintracks.ts +48 -4
  22. package/core/headers/headerStore.ts +26 -4
  23. package/core/headers/headerSyncTriggers.ts +65 -0
  24. package/core/headers/syncHeaders.ts +12 -1
  25. package/core/i18n/translations.tsx +1001 -25
  26. package/core/identity/handleRegistry/client.ts +31 -2
  27. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  28. package/core/identity/handleRegistry/resolver.ts +71 -3
  29. package/core/index.ts +33 -3
  30. package/core/localpay/build.ts +225 -24
  31. package/core/localpay/pending.ts +110 -7
  32. package/core/localpay/pendingAbortAuthority.ts +95 -0
  33. package/core/localpay/pendingAborts.ts +264 -28
  34. package/core/localpay/session.ts +42 -17
  35. package/core/localpay/settlementAck.ts +10 -1
  36. package/core/localpay/transport/socket.ts +52 -3
  37. package/core/localpay/types.ts +9 -1
  38. package/core/localpay/verify.ts +143 -16
  39. package/core/mandala/abortGuard.ts +96 -20
  40. package/core/mandala/createRuntime.ts +206 -33
  41. package/core/mandala/drain.ts +89 -11
  42. package/core/mandala/inboxPrehold.ts +186 -0
  43. package/core/mandala/permissionModule.ts +202 -20
  44. package/core/mandala/settlementStore.ts +24 -2
  45. package/core/mandala/types.ts +40 -5
  46. package/core/monitor/TaskBackupPush.ts +14 -0
  47. package/core/monitor/TaskDrainOutbox.ts +14 -0
  48. package/core/monitor/TaskSendOffline.ts +14 -0
  49. package/core/net/publicDestination.ts +91 -0
  50. package/core/net/validateArcUrl.ts +22 -0
  51. package/core/offline/cancelParked.ts +134 -13
  52. package/core/offline/payerHold.ts +100 -24
  53. package/core/offline/plan.ts +36 -7
  54. package/core/pay/beefRepair.ts +6 -2
  55. package/core/pay/damagedInbox.ts +24 -0
  56. package/core/pay/rails/address.ts +107 -12
  57. package/core/pay/rails/handle.ts +117 -22
  58. package/core/pay/rails/index.ts +45 -7
  59. package/core/pay/rails/nativeIntent.ts +61 -0
  60. package/core/pay/rails/nearby.ts +1 -0
  61. package/core/pay/receiveHistory.ts +93 -0
  62. package/core/pay/recordProof.ts +19 -1
  63. package/core/pay/refreshProofGuard.ts +42 -1
  64. package/core/pay/watchlist.ts +5 -2
  65. package/core/peerpay/control.ts +17 -18
  66. package/core/peerpay/handleResendRequests.ts +58 -4
  67. package/core/peerpay/outbox.ts +3 -1
  68. package/core/recovery/backupMaterial.ts +61 -0
  69. package/core/recovery/createWallet.ts +95 -0
  70. package/core/recovery/recoverWallet.ts +120 -0
  71. package/core/recovery/restoreWallet.ts +170 -0
  72. package/core/recovery/secret.ts +92 -0
  73. package/core/recovery/shareCollector.ts +71 -0
  74. package/core/recovery/shareParsing.ts +87 -0
  75. package/core/recovery/shares.ts +116 -0
  76. package/core/recovery/useRecoveryDeps.ts +70 -0
  77. package/core/services/arcTokenStorage.ts +52 -0
  78. package/core/services/arcadeBroadcastProvider.ts +232 -48
  79. package/core/services/autoApprovePolicy.ts +105 -0
  80. package/core/services/callbackToken.ts +19 -0
  81. package/core/services/capWalletArgs.ts +14 -2
  82. package/core/services/connectionAuthority.ts +98 -0
  83. package/core/services/exchangeRate.ts +35 -12
  84. package/core/services/externalOrigin.ts +11 -0
  85. package/core/services/secrets/kek.ts +126 -29
  86. package/core/services/secrets/migration.ts +16 -4
  87. package/core/services/secrets/store.ts +42 -14
  88. package/core/services/vault/VaultKeyService.ts +228 -45
  89. package/core/services/vault/chainRecovery.ts +483 -0
  90. package/core/services/vault/driver.ts +9 -1
  91. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  92. package/core/services/vault/guard.ts +218 -32
  93. package/core/services/vault/hardwareLease.ts +19 -0
  94. package/core/services/vault/metaAuthority.ts +210 -0
  95. package/core/services/vault/pivReset.ts +64 -23
  96. package/core/services/vault/r1comb.ts +139 -3
  97. package/core/services/vault/session.ts +25 -4
  98. package/core/services/vault/transfers.ts +866 -170
  99. package/core/services/vault/types.ts +19 -4
  100. package/core/services/vault/vaultStore.ts +256 -29
  101. package/core/services/walletArgLimits.ts +45 -2
  102. package/core/services/walletConnectionValidation.ts +76 -6
  103. package/core/services/walletServiceConfig.ts +10 -8
  104. package/core/storage/StorageExpoSQLite.ts +47 -13
  105. package/core/storage/methods/findSql.ts +21 -2
  106. package/core/storage/methods/offlineActions.ts +10 -1
  107. package/core/storage/methods/processOfflineActions.ts +116 -23
  108. package/core/storage/schema/createTables.ts +126 -2
  109. package/core/stores/ConnectionStore.ts +34 -0
  110. package/core/toolboxConfig.ts +45 -11
  111. package/core/walletDbRegistry.ts +63 -0
  112. package/core/walletMonitor.ts +17 -1
  113. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  114. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  115. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  116. package/package.json +2 -2
  117. package/ui/backupShares.ts +26 -169
  118. package/ui/components/pay/AddressReceive.tsx +13 -6
  119. package/ui/components/pay/AssetPicker.tsx +30 -9
  120. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  121. package/ui/components/pay/NearbyFlow.tsx +511 -251
  122. package/ui/components/pay/PaymentSuccessOverlay.tsx +39 -4
  123. package/ui/components/pay/UniversalSend.tsx +167 -73
  124. package/ui/components/ui/AlertCard.tsx +38 -5
  125. package/ui/components/ui/PermissionSheet.tsx +197 -66
  126. package/ui/components/vault/EnrollWizard.tsx +61 -13
  127. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  128. package/ui/components/wallet/ActivityRow.tsx +5 -3
  129. package/ui/components/wallet/AmountInput.tsx +8 -2
  130. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  131. package/ui/components/wallet/Balance.tsx +42 -23
  132. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  133. package/ui/exportTransactions.ts +36 -4
  134. package/ui/hooks/useExportWalletData.ts +25 -2
  135. package/ui/importDatabases.ts +339 -24
  136. package/ui/index.ts +9 -3
  137. package/ui/isImageUrl.ts +6 -0
  138. package/ui/printRecoveryShares.ts +9 -10
  139. package/ui/recoveryPrompts.ts +91 -0
  140. package/ui/resolveIdentity.ts +31 -9
  141. package/ui/screens/ConnectionsScreen.tsx +86 -19
  142. package/ui/screens/IdentifierScreen.tsx +30 -8
  143. package/ui/screens/PairScreen.tsx +74 -2
  144. package/ui/screens/SettingsScreen.tsx +10 -4
  145. package/ui/screens/TrustScreen.tsx +99 -4
  146. package/ui/screens/VaultScreen.tsx +410 -61
  147. package/ui/screens/VaultTransferScreen.tsx +59 -7
  148. package/ui/screens/WalletCheckScreen.tsx +17 -6
  149. package/ui/screens/WalletConfigScreen.tsx +82 -28
  150. package/ui/screens/WalletHomeScreen.tsx +179 -88
  151. package/ui/screens/detailActionKeys.ts +55 -0
  152. package/ui/tokenFormat.ts +44 -4
  153. package/ui/txStatus.ts +5 -0
  154. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -70,9 +70,12 @@ import {
70
70
  retryDelivery,
71
71
  makePeerPayClient,
72
72
  isMessageBoxNetworkError,
73
+ isAbortSafe,
73
74
  generateMnemonicWallet,
74
75
  backupAttestation,
75
76
  isVaultAvailable,
77
+ useVault,
78
+ resolveProvisioningPolicy,
76
79
  type PendingResend
77
80
  } from '@bsv/expo-wallet-toolbox'
78
81
  import ActivityRow, { type ActivityAction } from '../components/wallet/ActivityRow'
@@ -86,7 +89,8 @@ import { useContactsStore } from '../hooks/useContactsStore'
86
89
  import { BackupReminderSheet } from '../components/wallet/BackupReminderSheet'
87
90
  import { BiometricAdvisoryModal } from '../components/wallet/BiometricAdvisoryModal'
88
91
  import { ImportFromBackupPrompt } from '../components/wallet/ImportFromBackupPrompt'
89
- import { cancelParkedPayment, type CancelParkedWallet } from '../../core/offline/cancelParked'
92
+ import { cancelParkedPayment, runCancelParkedFlow, type CancelParkedWallet } from '../../core/offline/cancelParked'
93
+ import { detailActionKeysFor } from './detailActionKeys'
90
94
  import { releaseParkedPayment } from '../../core/offline/payerHold'
91
95
  import { partitionQueueByGrace } from '../../core/offline/queueGrace'
92
96
  import { storageMatchesNetwork } from '../../core/net/chainMatch'
@@ -115,6 +119,7 @@ import PressableScale from '../components/ui/PressableScale'
115
119
  import ScreenGradient from '../components/ui/ScreenGradient'
116
120
  import ScrollFade, { sampleScreenGradient } from '../components/ui/ScrollFade'
117
121
  import { showToast } from '../components/ui/Toast'
122
+ import { showAlert } from '../components/ui/AlertCard'
118
123
  import { ListRow } from '../components/ui/ListRow'
119
124
  import { GroupedSection } from '../components/ui/GroupedList'
120
125
  import WalletLockNotice from '../components/security/WalletLockNotice'
@@ -219,14 +224,6 @@ const PAGE_SIZE = 30
219
224
  * the whole thing stays one FlatList — a SectionList would re-measure every
220
225
  * section on each status poll. */
221
226
  type DayHeader = { kind: 'day'; id: string; label: string }
222
- /**
223
- * Statuses whose transaction is still local and therefore abortable — the same
224
- * set `ActivityRow` gates its own Cancel chip on. Duplicated as a constant
225
- * rather than imported so the row keeps owning its own copy while both
226
- * surfaces exist.
227
- */
228
- const ABORTABLE_DETAIL_STATUSES = new Set(['unsigned', 'nosend', 'nonfinal', 'failed'])
229
-
230
227
  type Row = DayHeader | (ActivityAction & { kind?: undefined })
231
228
 
232
229
  const DAY_MS = 86_400_000
@@ -296,6 +293,10 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
296
293
  buildWalletFromMnemonic,
297
294
  mandalaSettlement
298
295
  } = useWallet()
296
+ // F-07: an existing, already-funded vault stays reachable even when
297
+ // isVaultAvailable is off (flag or off-mainnet) — see the Vault
298
+ // destination's condition below.
299
+ const { hasVaultMeta } = useVault()
299
300
  const { createMnemonic, hasStoredIdentity, secretsReady } = useLocalStorage()
300
301
  const { satoshisPerUSD, usdToFiat = {} } = useContext(ExchangeRateContext)
301
302
  const currency = settings?.currency || 'BSV'
@@ -394,6 +395,10 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
394
395
  const [pendingDestination, setPendingDestination] = useState<string | null>(null)
395
396
  const [showBiometricAdvisory, setShowBiometricAdvisory] = useState(false)
396
397
  const [creatingWalletFromAdvisory, setCreatingWalletFromAdvisory] = useState(false)
398
+ // XR-114: whether provisioning would actually land on a disclosed
399
+ // (non-biometric) policy for this device/build, so the advisory below
400
+ // never promises Face ID/fingerprint protection it will not deliver.
401
+ const [advisoryDegraded, setAdvisoryDegraded] = useState(false)
397
402
 
398
403
  const destinationPress = useCallback(
399
404
  async (destination: string) => {
@@ -407,6 +412,7 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
407
412
  } catch {
408
413
  return
409
414
  }
415
+ setAdvisoryDegraded((await resolveProvisioningPolicy()).disclose)
410
416
  setPendingDestination(destination)
411
417
  setShowBiometricAdvisory(true)
412
418
  },
@@ -736,7 +742,10 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
736
742
  walletClient: pm as never,
737
743
  originator: adminOriginator
738
744
  })
739
- const r = await listPendingResendRequests({ client, storage })
745
+ // XR-051: without this, an unauthenticated resend_request could not be
746
+ // told apart from a legitimate one and would be surfaced (and kept
747
+ // being surfaced) as pending forever.
748
+ const r = await listPendingResendRequests({ client, storage, listPeerPayAction: makeListPeerPayAction(pm, adminOriginator) })
740
749
  setPendingResends(r.pending)
741
750
  } catch {
742
751
  // Silent: an unreachable box must not alert on focus. The stored
@@ -821,7 +830,18 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
821
830
  const db = storage?.sqliteDb
822
831
  if (!db) return
823
832
  const rows = await findOfflineActions(db, {
824
- status: ['queued', 'posting', 'rejected', 'parked'],
833
+ // 'import_hold' included (XR-085 review follow-up) so a raw-import
834
+ // quarantined row reaches offlineByTxid and reads as "Held (imported)"
835
+ // via txStatusView/ActivityRow instead of falling through to its raw,
836
+ // uninformative status. This is safe ONLY because the derived `queued`
837
+ // value below (which feeds OfflineNotice's count/Send-now/Show-code
838
+ // and the queued-count badge) explicitly excludes 'import_hold' too —
839
+ // an earlier version of this comment claimed that filtering was
840
+ // unnecessary ("nothing below acts on the row by this status"), which
841
+ // was false and let a held row render as an ordinary active payment
842
+ // waiting to be broadcast. Do not widen `queued`'s exclusion list
843
+ // without keeping 'import_hold' in it.
844
+ status: ['queued', 'posting', 'rejected', 'parked', 'import_hold'],
825
845
  ...(walletUserId === null ? {} : { userId: walletUserId })
826
846
  })
827
847
  setOfflineByTxid(new Map(rows.map(r => [r.txid, r])))
@@ -996,12 +1016,28 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
996
1016
  [busyRow, refreshProof, t]
997
1017
  )
998
1018
 
999
- /** Abort a still-local transaction, releasing the inputs it reserved. */
1019
+ /**
1020
+ * Abort a still-local transaction, releasing the inputs it reserved.
1021
+ *
1022
+ * `action` is passed by every caller that has it (the row and the detail sheet both
1023
+ * render from a loaded ActivityAction). For a `peerpay` action it is checked against the
1024
+ * live outbox before this ever reaches `abortAction`: that outbox row is the only record
1025
+ * of whether the recipient may already hold this payment's token, and it does not survive
1026
+ * a backup/restore (key_value_store is not currently part of the encrypted backup) — so a
1027
+ * restored wallet must refuse rather than guess "never delivered" from a missing row.
1028
+ */
1000
1029
  const onAbort = useCallback(
1001
- async (reference: string) => {
1030
+ async (reference: string, action?: ActivityAction) => {
1002
1031
  if (!managers.permissionsManager || busyRow) return
1003
1032
  setBusyRow(reference)
1004
1033
  try {
1034
+ if (action?.labels?.includes('peerpay')) {
1035
+ const entries = storage ? await getOutboxEntries(storage) : []
1036
+ if (!isAbortSafe(action, entries).aborted) {
1037
+ showToast(t('tx_abort_maybe_delivered'), { type: 'error' })
1038
+ return
1039
+ }
1040
+ }
1005
1041
  const r = (await managers.permissionsManager.abortAction({ reference }, adminOriginator)) as
1006
1042
  | { aborted?: boolean }
1007
1043
  | undefined
@@ -1018,7 +1054,7 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1018
1054
  setBusyLabel(undefined)
1019
1055
  }
1020
1056
  },
1021
- [managers.permissionsManager, adminOriginator, busyRow, onRefresh, t]
1057
+ [managers.permissionsManager, adminOriginator, busyRow, onRefresh, storage, t]
1022
1058
  )
1023
1059
 
1024
1060
  const onResendPending = useCallback(async () => {
@@ -1109,7 +1145,11 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1109
1145
  // too, instead of leaving it looking like it never went anywhere.
1110
1146
  if (storage && offlineByTxid.get(txid)?.status === 'parked') {
1111
1147
  try {
1112
- await releaseParkedPayment({ storage, txid })
1148
+ // XR-036 review follow-up: `isToken` (derived above from the
1149
+ // action's own 'mandala' label) is the only signal
1150
+ // `releaseParkedPayment` has for whether this txid needs a
1151
+ // durable token_settlements row before it may be promoted.
1152
+ await releaseParkedPayment({ storage, txid, isTokenHold: isToken })
1113
1153
  } catch (e) {
1114
1154
  console.warn('[localpay] resent but could not release:', e instanceof Error ? e.message : e)
1115
1155
  }
@@ -1214,10 +1254,20 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1214
1254
  // broadcast them, so folding them into "waiting to be broadcast" would say
1215
1255
  // something untrue about both.
1216
1256
  //
1257
+ // An import_hold row is excluded for the same reason, more strongly: it is
1258
+ // not merely not-waiting, it is quarantined (XR-085) precisely so nothing
1259
+ // treats it as live. offlineByTxid (above) still carries it for ActivityRow,
1260
+ // so it still reads "Held (imported)" there — but it must never inflate this
1261
+ // screen's queued count, feed OfflineNotice's "Send now" banner, or make a
1262
+ // surviving framePayload reachable via queuedSent's "Show code" affordance.
1263
+ //
1217
1264
  // The rest pass through the grace filter: online, a payment the drain is
1218
1265
  // about to post says nothing worth reading, and the banner appearing for the
1219
1266
  // half second before it lands reads as a fault that is not there.
1220
- const queued = useMemo(() => offlineRows.filter(r => r.status !== 'rejected' && r.status !== 'parked'), [offlineRows])
1267
+ const queued = useMemo(
1268
+ () => offlineRows.filter(r => r.status !== 'rejected' && r.status !== 'parked' && r.status !== 'import_hold'),
1269
+ [offlineRows]
1270
+ )
1221
1271
  const { shown: queuedShown, nextCheckMs } = useMemo(
1222
1272
  // graceNonce is a dependency only: it carries no value into the call, it
1223
1273
  // just re-runs it once a young row has aged past the grace.
@@ -1367,17 +1417,36 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1367
1417
  // which leaves a plain BSV cancel exactly as it behaves today.
1368
1418
  const isTokenRow = tokenByTxid.has(txid)
1369
1419
  try {
1370
- const outcome = await cancelParkedPayment({
1371
- storage,
1372
- wallet: pm as unknown as CancelParkedWallet,
1373
- originator: adminOriginator,
1374
- txid,
1375
- settlement: mandalaSettlement
1420
+ // P1-3-localpay-cancelparked-bsv: `cancelParkedPayment` refuses to
1421
+ // cancel silently while the chain status cannot be verified offline.
1422
+ // `runCancelParkedFlow` shows the destructive confirm exactly once and
1423
+ // retries with the acknowledgement only if the user accepts the risk.
1424
+ const outcome = await runCancelParkedFlow({
1425
+ cancel: acknowledgedUnverifiable =>
1426
+ cancelParkedPayment({
1427
+ storage,
1428
+ wallet: pm as unknown as CancelParkedWallet,
1429
+ originator: adminOriginator,
1430
+ txid,
1431
+ settlement: mandalaSettlement,
1432
+ acknowledgedUnverifiable
1433
+ }),
1434
+ confirmUnverifiable: async () => {
1435
+ const choice = await showAlert({
1436
+ title: t('local_pay_cancel_unverifiable_title'),
1437
+ message: t('local_pay_cancel_unverifiable_body'),
1438
+ buttons: [
1439
+ { text: t('cancel'), style: 'cancel', key: 'cancel' },
1440
+ { text: t('local_pay_cancel_unverifiable_confirm'), style: 'destructive', key: 'confirm' }
1441
+ ]
1442
+ })
1443
+ return choice === 'confirm'
1444
+ }
1376
1445
  })
1377
1446
  if (outcome === 'cancelled') showToast(t('tx_abort_success'), { type: 'success' })
1378
1447
  else if (outcome === 'already-sent') {
1379
1448
  showToast(t(isTokenRow ? 'token_cancel_already_sent' : 'pay_parked_already_sent'), { type: 'info' })
1380
- } else showToast(t('tx_abort_failed'), { type: 'error' })
1449
+ } else if (outcome !== 'unverifiable-offline') showToast(t('tx_abort_failed'), { type: 'error' })
1381
1450
  await onRefresh()
1382
1451
  } catch (e: unknown) {
1383
1452
  showToast(e instanceof Error ? e.message : t('unknown_error'), { type: 'error' })
@@ -1468,27 +1537,27 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1468
1537
  // when a row is open) and memoizing them buys nothing, while calling a
1469
1538
  // memoized callback during render trips the compiler's purity rule.
1470
1539
  const detailParams = (action: ActivityAction): TransactionDetailParams => {
1471
- const key = action.txid || action.reference || ''
1472
- const token = action.labels?.includes('mandala') ? tokenProps.get(key) : undefined
1473
- return {
1474
- txid: action.txid,
1475
- satoshis: action.satoshis,
1476
- status: action.status,
1477
- description: action.description,
1478
- isOutgoing: action.isOutgoing,
1479
- createdAt: action.created_at ? new Date(action.created_at).toISOString() : undefined,
1480
- counterpartyKey: token?.counterpartyKey ?? action.senderIdentityKey,
1481
- ...(token
1482
- ? {
1483
- token: {
1484
- title: token.title,
1485
- amount: token.amount,
1486
- incoming: token.incoming,
1487
- statusText: token.statusText
1488
- }
1540
+ const key = action.txid || action.reference || ''
1541
+ const token = action.labels?.includes('mandala') ? tokenProps.get(key) : undefined
1542
+ return {
1543
+ txid: action.txid,
1544
+ satoshis: action.satoshis,
1545
+ status: action.status,
1546
+ description: action.description,
1547
+ isOutgoing: action.isOutgoing,
1548
+ createdAt: action.created_at ? new Date(action.created_at).toISOString() : undefined,
1549
+ counterpartyKey: token?.counterpartyKey ?? action.senderIdentityKey,
1550
+ ...(token
1551
+ ? {
1552
+ token: {
1553
+ title: token.title,
1554
+ amount: token.amount,
1555
+ incoming: token.incoming,
1556
+ statusText: token.statusText
1489
1557
  }
1490
- : {})
1491
- }
1558
+ }
1559
+ : {})
1560
+ }
1492
1561
  }
1493
1562
 
1494
1563
  /**
@@ -1496,48 +1565,64 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1496
1565
  * view's overflow menu. Same handlers, same guards — only the surface moved.
1497
1566
  */
1498
1567
  const detailActions = (action: ActivityAction): TransactionAction[] => {
1499
- const out: TransactionAction[] = []
1500
- const offline = action.txid ? offlineByTxid.get(action.txid) : undefined
1501
- const parked = offline?.status === 'parked'
1502
- if (action.txid && !parked && offline?.status !== 'queued' && offline?.status !== 'posting') {
1503
- out.push({
1504
- key: 'refresh',
1505
- label: t('tx_action_refresh'),
1506
- icon: 'refresh-outline',
1507
- onPress: () => void onRefreshTx(action.txid)
1508
- })
1509
- }
1510
- if (action.txid && !parked) {
1511
- out.push({
1512
- key: 'explorer',
1513
- label: t('tx_action_explorer'),
1514
- icon: 'link-outline',
1515
- onPress: () => onExplorer(action.txid)
1516
- })
1517
- }
1518
- if (action.reference && ABORTABLE_DETAIL_STATUSES.has(action.status)) {
1519
- out.push({
1520
- key: 'abort',
1521
- label: t('tx_action_abort'),
1522
- icon: 'close-circle-outline',
1523
- danger: true,
1524
- onPress: () => void onAbort(action.reference!)
1525
- })
1526
- }
1527
- if (parked && action.txid) {
1528
- out.push({
1529
- key: 'cancel-parked',
1530
- label: t('pay_parked_cancel'),
1531
- icon: 'close-circle-outline',
1532
- danger: true,
1533
- onPress: () => void onCancelParked(action.txid)
1534
- })
1535
- }
1568
+ const out: TransactionAction[] = []
1569
+ const offline = action.txid ? offlineByTxid.get(action.txid) : undefined
1570
+ const keys = detailActionKeysFor({
1571
+ txid: action.txid,
1572
+ reference: action.reference,
1573
+ status: action.status,
1574
+ offlineStatus: offline?.status,
1575
+ isOutgoing: action.isOutgoing ?? action.satoshis < 0,
1576
+ labels: action.labels
1577
+ })
1578
+ if (keys.includes('refresh')) {
1579
+ out.push({
1580
+ key: 'refresh',
1581
+ label: t('tx_action_refresh'),
1582
+ icon: 'refresh-outline',
1583
+ onPress: () => void onRefreshTx(action.txid)
1584
+ })
1585
+ }
1586
+ if (keys.includes('explorer')) {
1587
+ out.push({
1588
+ key: 'explorer',
1589
+ label: t('tx_action_explorer'),
1590
+ icon: 'link-outline',
1591
+ onPress: () => onExplorer(action.txid)
1592
+ })
1593
+ }
1594
+ if (keys.includes('abort')) {
1595
+ out.push({
1596
+ key: 'abort',
1597
+ label: t('tx_action_abort'),
1598
+ icon: 'close-circle-outline',
1599
+ danger: true,
1600
+ // `action` is passed so a peerpay abort gets the same outbox
1601
+ // delivered-check `onAbort` already runs for `ActivityRow`'s own
1602
+ // Cancel chip — this detail-sheet surface must not be a way around it.
1603
+ onPress: () => void onAbort(action.reference!, action)
1604
+ })
1605
+ }
1606
+ if (keys.includes('cancel-parked')) {
1607
+ out.push({
1608
+ key: 'cancel-parked',
1609
+ label: t('pay_parked_cancel'),
1610
+ icon: 'close-circle-outline',
1611
+ danger: true,
1612
+ onPress: () => void onCancelParked(action.txid)
1613
+ })
1614
+ }
1615
+ if (keys.includes('request-confirmation')) {
1616
+ out.push({
1617
+ key: 'request-confirmation',
1618
+ label: t('tx_action_request_confirmation'),
1619
+ icon: 'send-outline',
1620
+ onPress: () => void onSendPaymentDetails(action.txid)
1621
+ })
1622
+ }
1536
1623
  return out
1537
1624
  }
1538
1625
 
1539
-
1540
-
1541
1626
  const renderItem: ListRenderItem<Row> = useCallback(
1542
1627
  ({ item, index }) => {
1543
1628
  if (item.kind === 'day') {
@@ -1700,12 +1785,16 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1700
1785
 
1701
1786
  {/* Release- and network-gated (spec §5.5, task 11): no Vault
1702
1787
  destination until the host turns vaultEnabled on, and never off
1703
- mainnet. `selectedNetwork` is a dependency of this memo, so the
1704
- destination appears and disappears with a network switch. Plain
1705
- push, not destinationPress — enrolment needs no wallet, and the
1706
- Vault screen's own Deposit button runs the lazy wallet-creation
1707
- path when it comes to that. */}
1708
- {isVaultAvailable(selectedNetwork) && (
1788
+ mainnet — UNLESS this device already holds an existing Vault
1789
+ enrollment (F-07): a funded vault must stay reachable even if
1790
+ the flag is later turned off or the wallet switches network,
1791
+ since VaultScreen's withdraw path itself is never gated on this
1792
+ flag. `selectedNetwork`/`hasVaultMeta` are dependencies of this
1793
+ memo, so the destination tracks both live. Plain push, not
1794
+ destinationPress — enrolment needs no wallet, and the Vault
1795
+ screen's own Deposit button runs the lazy wallet-creation path
1796
+ when it comes to that. */}
1797
+ {(isVaultAvailable(selectedNetwork) || hasVaultMeta) && (
1709
1798
  <PressableScale
1710
1799
  haptic="confirm"
1711
1800
  onPress={() => router.push('/vault')}
@@ -1725,6 +1814,7 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
1725
1814
  t,
1726
1815
  router,
1727
1816
  selectedNetwork,
1817
+ hasVaultMeta,
1728
1818
  hasTokens,
1729
1819
  heldAsset,
1730
1820
  payDestination,
@@ -2129,6 +2219,7 @@ export function WalletHomeScreen({ topLeft }: WalletHomeScreenProps = {}) {
2129
2219
  <BiometricAdvisoryModal
2130
2220
  visible={showBiometricAdvisory}
2131
2221
  loading={creatingWalletFromAdvisory}
2222
+ degraded={advisoryDegraded}
2132
2223
  onCancel={() => {
2133
2224
  setShowBiometricAdvisory(false)
2134
2225
  setPendingDestination(null)
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Which detail-sheet action chips apply to an activity row.
3
+ *
4
+ * Extracted out of WalletHomeScreen's `detailActions()` (a pure decision, no
5
+ * JSX or translated labels) so the parked/abort guard is unit-testable
6
+ * without mounting the whole screen. See ActivityRow's `canAbort`, which
7
+ * already carries this same `!parked` guard for the expanded-row surface —
8
+ * this is the detail-sheet surface's copy of that decision.
9
+ */
10
+
11
+ /**
12
+ * Statuses whose transaction is still local and therefore abortable — the same
13
+ * set `ActivityRow` gates its own Cancel chip on. Duplicated as a constant
14
+ * rather than imported so the row keeps owning its own copy while both
15
+ * surfaces exist.
16
+ */
17
+ export const ABORTABLE_DETAIL_STATUSES = new Set(['unsigned', 'nosend', 'nonfinal', 'failed'])
18
+
19
+ export type DetailActionKey = 'refresh' | 'explorer' | 'abort' | 'cancel-parked' | 'request-confirmation'
20
+
21
+ /** Labels of the outgoing rails whose payment can be re-delivered over the
22
+ * message box (the same set ActivityRow's `resendableOutbound` uses). */
23
+ const REDELIVERABLE_LABELS = new Set(['peerpay', 'localpay', 'mandala'])
24
+
25
+ export function detailActionKeysFor(args: {
26
+ txid?: string
27
+ reference?: string
28
+ status: string
29
+ offlineStatus?: string
30
+ isOutgoing?: boolean
31
+ labels?: string[]
32
+ }): DetailActionKey[] {
33
+ const { txid, reference, status, offlineStatus, isOutgoing, labels } = args
34
+ const parked = offlineStatus === 'parked'
35
+ const out: DetailActionKey[] = []
36
+ if (txid && !parked && offlineStatus !== 'queued' && offlineStatus !== 'posting') out.push('refresh')
37
+ if (txid && !parked) out.push('explorer')
38
+ // XR-095: a parked nearby payment's inputs may already be a payee's to
39
+ // broadcast (FIX F) — cancelling it must always go through
40
+ // `cancelParkedPayment`'s chain-status gate, never this unconditional
41
+ // abort. Mirrors the `!parked` guard already used above for
42
+ // 'refresh'/'explorer', and the one `ActivityRow`'s `canAbort` already has.
43
+ //
44
+ // 2026-09-25: and never on a payment this device recorded handing over
45
+ // (queued, posting, sent, acknowledged, rejected, import_hold): the payee may
46
+ // hold it, and an abort would free inputs their copy spends. Plain abort is
47
+ // for a payment with no offline record at all — one that provably never
48
+ // left the device.
49
+ if (reference && offlineStatus === undefined && ABORTABLE_DETAIL_STATUSES.has(status)) out.push('abort')
50
+ if (parked && txid) out.push('cancel-parked')
51
+ // Re-deliver the same payment over the message box, whatever rail it first
52
+ // took (the owner's "request confirmation from recipient").
53
+ if (txid && isOutgoing === true && !!labels?.some(l => REDELIVERABLE_LABELS.has(l))) out.push('request-confirmation')
54
+ return out
55
+ }
package/ui/tokenFormat.ts CHANGED
@@ -18,6 +18,19 @@
18
18
  * vouching for someone else's peg (ux §6.1).
19
19
  */
20
20
 
21
+ /**
22
+ * XR-043: mirrored at every other boundary that ever reads a token's
23
+ * decimals — `core/localpay/session.ts`'s session codec and
24
+ * `core/mandala/createRuntime.ts`'s asset-metadata resolution enforce the
25
+ * same bound at THEIR boundaries; this is the last line of defense inside
26
+ * the formatters themselves, since a decimals value can reach here from a
27
+ * path neither of those touches (a stale cached asset, a test double, a
28
+ * future caller). Nothing token-shaped this wallet knows of uses more than a
29
+ * handful; an unbounded decimals value is how `String(...).padStart` (and
30
+ * an unbounded regex quantifier below) blows up the confirmation UI.
31
+ */
32
+ const MAX_TOKEN_DECIMALS = 18
33
+
21
34
  /** Grouping separators for the integer part, in the device's own locale. */
22
35
  function groupInteger(digits: string): string {
23
36
  const n = Number(digits)
@@ -37,7 +50,8 @@ export function formatTokenAmount(
37
50
  decimals: number,
38
51
  opts: { showPlus?: boolean } = {}
39
52
  ): string | null {
40
- if (!Number.isFinite(baseUnits) || !Number.isFinite(decimals) || decimals < 0) return null
53
+ if (!Number.isFinite(baseUnits) || !Number.isInteger(decimals) || decimals < 0 || decimals > MAX_TOKEN_DECIMALS)
54
+ return null
41
55
  const d = Math.floor(decimals)
42
56
  const rounded = Math.round(Math.abs(baseUnits))
43
57
  const digits = String(rounded).padStart(d + 1, '0')
@@ -78,7 +92,7 @@ export function formatTokenAmountWithUnit(
78
92
  * different amount than the one on screen.
79
93
  */
80
94
  export function parseTokenAmount(text: string, decimals: number): number | null {
81
- if (!Number.isFinite(decimals) || decimals < 0) return null
95
+ if (!Number.isInteger(decimals) || decimals < 0 || decimals > MAX_TOKEN_DECIMALS) return null
82
96
  const trimmed = text.trim()
83
97
  if (!trimmed) return null
84
98
  const d = Math.floor(decimals)
@@ -92,9 +106,17 @@ export function parseTokenAmount(text: string, decimals: number): number | null
92
106
  return Number.isSafeInteger(value) ? value : null
93
107
  }
94
108
 
95
- /** The input mask for an asset's decimals: digits, one point, at most N places. */
109
+ /**
110
+ * The input mask for an asset's decimals: digits, one point, at most N places.
111
+ *
112
+ * XR-043: clamped rather than refused (unlike the formatters above) — this
113
+ * always has to return SOME usable mask for the field to render with, so an
114
+ * out-of-range `decimals` is treated as `MAX_TOKEN_DECIMALS` instead of
115
+ * reaching an unbounded regex quantifier.
116
+ */
96
117
  export function tokenAmountMask(decimals: number): RegExp {
97
- const d = Math.max(0, Math.floor(decimals))
118
+ const bounded = Number.isFinite(decimals) ? decimals : 0
119
+ const d = Math.min(MAX_TOKEN_DECIMALS, Math.max(0, Math.floor(bounded)))
98
120
  return d === 0 ? /^\d*$/ : new RegExp(`^\\d*\\.?\\d{0,${d}}$`)
99
121
  }
100
122
 
@@ -106,3 +128,21 @@ export function tokenAmountInputText(baseUnits: number, decimals: number): strin
106
128
  // cannot produce and `parseTokenAmount` would refuse on the next keystroke.
107
129
  return formatted.replace(/[^\d.]/g, '')
108
130
  }
131
+
132
+ /**
133
+ * A short, human-scannable form of a long `'<64-hex>.<vout>'` assetId —
134
+ * `"a1b2c3d4…ef01.0"`. Same truncation `core/mandala/permissionModule.ts`'s
135
+ * own (unexported) `shortAssetId` uses for prompt copy, kept as a small
136
+ * separate copy here rather than an import so the UI layer does not reach
137
+ * into `core/mandala` for a pure string helper.
138
+ *
139
+ * XR-044: an issuer-chosen ticker/label is not unique — a look-alike asset
140
+ * from a different issuer can share both. `assetId` is the one thing that
141
+ * cannot collide, so every asset-selection row and the final send
142
+ * confirmation show this fingerprint alongside the ticker/label, not instead
143
+ * of it.
144
+ */
145
+ export function shortAssetId(assetId: string): string {
146
+ if (!assetId || assetId.length <= 16) return assetId
147
+ return `${assetId.slice(0, 8)}…${assetId.slice(-6)}`
148
+ }
package/ui/txStatus.ts CHANGED
@@ -72,6 +72,11 @@ export function txStatusView(
72
72
  // says the payment is waiting on a hand-over that may not have happened.
73
73
  case 'parked':
74
74
  return { key: 'tx_status_parked', tone: 'attention' }
75
+ // Written only by a raw database import (XR-085): a copied-in 'queued'/
76
+ // 'posting' row held back from the automatic drain pending the user's
77
+ // renewed review, not silently resumed or dropped.
78
+ case 'import_hold':
79
+ return { key: 'tx_status_import_hold', tone: 'attention' }
75
80
  }
76
81
 
77
82
  switch (status) {
@@ -1,58 +0,0 @@
1
- /**
2
- * Adapter to make StorageExpoSQLite work with the wallet-toolbox ecosystem
3
- *
4
- * This is a temporary adapter that allows using local SQLite storage
5
- * until StorageExpoSQLite fully implements the WalletStorageProvider interface
6
- */
7
-
8
- import { StorageProvider } from '@bsv/wallet-toolbox-mobile'
9
- import { StorageExpoSQLite } from './StorageExpoSQLite'
10
- import type { AppChain } from '../config'
11
- import { toWalletChain } from '../config'
12
-
13
- export interface LocalStorageConfig {
14
- network: AppChain
15
- identityKey: string
16
- storageName?: string
17
- }
18
-
19
- /**
20
- * Initialize local storage for the wallet
21
- */
22
- export async function initializeLocalStorage(config: LocalStorageConfig): Promise<StorageExpoSQLite> {
23
- const { network, identityKey, storageName = 'bsv-wallet' } = config
24
-
25
- // Create storage instance
26
- const storage = new StorageExpoSQLite({
27
- ...StorageProvider.createStorageBaseOptions(toWalletChain(network))
28
- })
29
-
30
- // Initialize database
31
- await storage.migrate(storageName, identityKey)
32
-
33
- // Verify it's ready
34
- await storage.makeAvailable()
35
-
36
- return storage
37
- }
38
-
39
- /**
40
- * Check if a storage URL indicates local storage
41
- */
42
- export function isLocalStorage(storageUrl: string): boolean {
43
- return storageUrl === 'local'
44
- }
45
-
46
- /**
47
- * Get storage display name
48
- */
49
- export function getStorageDisplayName(storageUrl: string): string {
50
- if (isLocalStorage(storageUrl)) {
51
- return 'Local Storage (On Device)'
52
- }
53
- try {
54
- return new URL(storageUrl).hostname
55
- } catch {
56
- return storageUrl
57
- }
58
- }