@bsv/expo-wallet-toolbox 0.4.0 → 0.7.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 (182) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/README.md +19 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/amountFormatHelpers.ts +238 -34
  6. package/core/backup/RemoteSyncReader.ts +2 -5
  7. package/core/backup/codec.ts +2 -2
  8. package/core/backup/push.ts +1 -1
  9. package/core/config.tsx +16 -1
  10. package/core/contacts/contactActivity.ts +153 -0
  11. package/core/contacts/contactCache.ts +41 -0
  12. package/core/contacts/contactsStore.ts +183 -0
  13. package/core/context/VaultContext.tsx +8 -11
  14. package/core/context/WalletConnectionContext.tsx +137 -52
  15. package/core/context/WalletContext.tsx +464 -30
  16. package/core/demo/demoAssets.ts +60 -0
  17. package/core/demo/demoLedger.ts +240 -0
  18. package/core/demo/demoMandalaRuntime.ts +96 -0
  19. package/core/demo/demoMode.ts +38 -0
  20. package/core/demo/demoWallet.ts +25 -0
  21. package/core/demo/index.ts +26 -0
  22. package/core/demo/useDemo.ts +59 -0
  23. package/core/headers/OfflineFirstChaintracks.ts +52 -14
  24. package/core/headers/headerStore.ts +7 -10
  25. package/core/hooks/useConfirmationSound.ts +14 -8
  26. package/core/i18n/translations.tsx +4562 -986
  27. package/core/identity/contactLink.ts +36 -0
  28. package/core/identity/handleRegistry/client.ts +285 -0
  29. package/core/identity/handleRegistry/profileCert.ts +254 -0
  30. package/core/identity/handleRegistry/registration.ts +559 -0
  31. package/core/identity/handleRegistry/resolver.ts +247 -0
  32. package/core/identity/handleRegistry/rules.ts +104 -0
  33. package/core/index.ts +116 -15
  34. package/core/localpay/build.ts +674 -37
  35. package/core/localpay/codec.ts +68 -5
  36. package/core/localpay/pending.ts +240 -22
  37. package/core/localpay/pendingAborts.ts +5 -1
  38. package/core/localpay/settlementAck.ts +149 -0
  39. package/core/localpay/types.ts +14 -1
  40. package/core/localpay/verify.ts +118 -69
  41. package/core/mandala/abortGuard.ts +134 -0
  42. package/core/mandala/basketMigration.ts +166 -0
  43. package/core/mandala/bundle.ts +244 -0
  44. package/core/mandala/createRuntime.ts +2437 -0
  45. package/core/mandala/drain.ts +670 -0
  46. package/core/mandala/permissionModule.ts +642 -0
  47. package/core/mandala/resendTransfer.ts +175 -0
  48. package/core/mandala/runtime.ts +357 -0
  49. package/core/mandala/settlementStore.ts +412 -0
  50. package/core/mandala/types.ts +290 -0
  51. package/core/monitor/MonitorSupervisor.ts +121 -0
  52. package/core/monitor/TaskBackupPush.ts +1 -1
  53. package/core/monitor/TaskCreditInbox.ts +1 -1
  54. package/core/monitor/TaskDrainOutbox.ts +1 -1
  55. package/core/monitor/TaskSendOffline.ts +1 -1
  56. package/core/net/online.ts +49 -0
  57. package/core/numberFormat.ts +19 -0
  58. package/core/offline/cancelParked.ts +94 -1
  59. package/core/offline/payerHold.ts +152 -12
  60. package/core/offline/plan.ts +1 -1
  61. package/core/offline/tokenFrames.ts +197 -0
  62. package/core/parsePeerPayURI.ts +70 -17
  63. package/core/pay/rails/address.ts +51 -3
  64. package/core/pay/rails/handle.ts +88 -9
  65. package/core/pay/rails/index.ts +16 -6
  66. package/core/pay/rails/nearby.ts +114 -4
  67. package/core/pay/recordProof.ts +2 -6
  68. package/core/services/arcadeBroadcastProvider.ts +1 -4
  69. package/core/services/capWalletArgs.ts +8 -9
  70. package/core/services/exchangeRate.ts +1 -1
  71. package/core/services/externalOrigin.ts +42 -0
  72. package/core/services/vault/VaultKeyService.ts +912 -251
  73. package/core/services/vault/ceremony.ts +435 -367
  74. package/core/services/vault/ceremonyHost.ts +27 -21
  75. package/core/services/vault/devMock.ts +30 -7
  76. package/core/services/vault/driver.ts +95 -41
  77. package/core/services/vault/guard.ts +514 -56
  78. package/core/services/vault/hardwareLease.ts +22 -0
  79. package/core/services/vault/mockYubiKey.ts +258 -90
  80. package/core/services/vault/pivReset.ts +145 -0
  81. package/core/services/vault/r1comb.ts +976 -0
  82. package/core/services/vault/session.ts +93 -26
  83. package/core/services/vault/transfers.ts +2617 -747
  84. package/core/services/vault/types.ts +100 -43
  85. package/core/services/vault/vaultStore.ts +991 -74
  86. package/core/services/walletConnectionValidation.ts +293 -0
  87. package/core/services/walletServiceConfig.ts +31 -20
  88. package/core/storage/StorageExpoSQLite.ts +420 -87
  89. package/core/storage/dbImage.ts +48 -0
  90. package/core/storage/methods/findSql.ts +3 -54
  91. package/core/storage/methods/listActionsSql.ts +8 -5
  92. package/core/storage/methods/listOutputsSql.ts +9 -5
  93. package/core/storage/methods/offlineActions.ts +15 -0
  94. package/core/storage/methods/processOfflineActions.ts +265 -9
  95. package/core/storage/methods/reviewStatusSql.ts +7 -2
  96. package/core/storage/methods/walletBalanceSql.ts +16 -4
  97. package/core/storage/schema/createTables.ts +152 -0
  98. package/core/storage/sqlUpdateValue.ts +24 -0
  99. package/core/toolboxConfig.ts +182 -1
  100. package/core/toolboxTypes.ts +40 -0
  101. package/core/userAvatar.ts +79 -0
  102. package/core/walletMonitor.ts +8 -3
  103. package/core/walletRepair/runWalletCheck.ts +19 -2
  104. package/package.json +31 -30
  105. package/ui/activityFilter.ts +115 -0
  106. package/ui/components/QRScanner.tsx +1 -1
  107. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  108. package/ui/components/pay/AssetPicker.tsx +184 -0
  109. package/ui/components/pay/AvailableBalance.tsx +33 -2
  110. package/ui/components/pay/HandleReceive.tsx +213 -50
  111. package/ui/components/pay/NearbyFlow.tsx +616 -69
  112. package/ui/components/pay/PayForm.tsx +73 -8
  113. package/ui/components/pay/PaymentSuccessOverlay.tsx +89 -8
  114. package/ui/components/pay/RecipientField.tsx +132 -73
  115. package/ui/components/pay/RequestHub.tsx +68 -8
  116. package/ui/components/pay/ResultBanner.tsx +41 -4
  117. package/ui/components/pay/StepBar.tsx +32 -0
  118. package/ui/components/pay/UniversalSend.tsx +1118 -86
  119. package/ui/components/pay/tokenSendCopy.ts +116 -0
  120. package/ui/components/pay/useRecipientInput.ts +36 -7
  121. package/ui/components/ui/PencilEditField.tsx +109 -0
  122. package/ui/components/ui/PermissionSheet.tsx +65 -4
  123. package/ui/components/ui/Sheet.tsx +9 -2
  124. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  125. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  126. package/ui/components/vault/KeyChooser.tsx +96 -0
  127. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  128. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  129. package/ui/components/wallet/ActivityRow.tsx +283 -97
  130. package/ui/components/wallet/AmountInput.tsx +92 -28
  131. package/ui/components/wallet/AssetAmount.tsx +95 -0
  132. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  133. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  134. package/ui/components/wallet/ContactSigil.tsx +49 -0
  135. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  136. package/ui/components/wallet/FitAmount.tsx +148 -0
  137. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  138. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  139. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  140. package/ui/components/wallet/ProfileButton.tsx +62 -0
  141. package/ui/components/wallet/UserAvatar.tsx +85 -0
  142. package/ui/components/wallet/avatarIcons.ts +122 -0
  143. package/ui/components/wallet/tokenEviction.ts +65 -0
  144. package/ui/hooks/useContactsStore.ts +10 -0
  145. package/ui/hooks/useExportWalletData.ts +39 -0
  146. package/ui/hooks/useMandala.ts +320 -0
  147. package/ui/hooks/useOnline.ts +65 -20
  148. package/ui/hooks/useVaultBalance.ts +105 -7
  149. package/ui/hooks/useVaultCoverage.ts +52 -0
  150. package/ui/importDatabases.ts +7 -3
  151. package/ui/index.ts +75 -7
  152. package/ui/screens/ConnectionsScreen.tsx +46 -29
  153. package/ui/screens/ContactScreen.tsx +289 -0
  154. package/ui/screens/ContactsScreen.tsx +373 -0
  155. package/ui/screens/IdentifierScreen.tsx +234 -0
  156. package/ui/screens/NewContactScreen.tsx +362 -0
  157. package/ui/screens/PairScreen.tsx +12 -12
  158. package/ui/screens/PayScreen.tsx +145 -12
  159. package/ui/screens/ProfileScreen.tsx +783 -0
  160. package/ui/screens/SettingsScreen.tsx +18 -9
  161. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  162. package/ui/screens/TrustScreen.tsx +1 -1
  163. package/ui/screens/VaultScreen.tsx +925 -171
  164. package/ui/screens/VaultTransferScreen.tsx +376 -123
  165. package/ui/screens/WalletCheckScreen.tsx +10 -1
  166. package/ui/screens/WalletConfigScreen.tsx +80 -16
  167. package/ui/screens/WalletHomeScreen.tsx +915 -139
  168. package/ui/screens/homeBadges.ts +9 -1
  169. package/ui/screens/tokenRowTitle.ts +68 -0
  170. package/ui/tokenFormat.ts +108 -0
  171. package/ui/tokenSeen.ts +75 -0
  172. package/ui/tokenStatus.ts +100 -0
  173. package/ui/txStatus.ts +43 -5
  174. package/assets/sounds/vault-close.wav +0 -0
  175. package/assets/sounds/vault-open.wav +0 -0
  176. package/core/services/vault/k1.ts +0 -75
  177. package/core/services/vault/sealing.ts +0 -84
  178. package/core/services/vault/vaultDerivation.ts +0 -152
  179. package/core/services/vault/vaultPassphrase.ts +0 -287
  180. package/ui/components/vault/PassphraseField.tsx +0 -306
  181. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  182. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -88,7 +88,7 @@
88
88
  */
89
89
 
90
90
  import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
91
- import { ActivityIndicator, Linking, Modal, Platform, ScrollView, StyleSheet, Text, View } from 'react-native'
91
+ import { ActivityIndicator, Linking, Modal, Platform, ScrollView, StyleSheet, Text, TextInput, View } from 'react-native'
92
92
  import Animated, { FadeIn, FadeInDown, useReducedMotion } from 'react-native-reanimated'
93
93
  import { useSafeAreaInsets } from 'react-native-safe-area-context'
94
94
  import { useTranslation } from 'react-i18next'
@@ -103,7 +103,7 @@ import AmountDisplay from '../wallet/AmountDisplay'
103
103
  import PressableScale from '../ui/PressableScale'
104
104
  import PresenceRow, { type PresenceState } from '../ui/PresenceRow'
105
105
  import AvailableBalance from './AvailableBalance'
106
- import { PayAmountField, RecipientSummary } from './PayForm'
106
+ import { PayAmountField, PayField, RecipientSummary } from './PayForm'
107
107
  import PaymentQrDisplay from './PaymentQrDisplay'
108
108
  import ReceivedOverlay from './PaymentSuccessOverlay'
109
109
  import { identityLabel, makeIdentityClient, resolveIdentity } from '../../resolveIdentity'
@@ -138,6 +138,7 @@ import {
138
138
  localSupportsNearby,
139
139
  markSessionSpent,
140
140
  mintSession,
141
+ rememberSessionPsk,
141
142
  nearbyTransport,
142
143
  nextPhaseAfterUnsealFailure,
143
144
  prepareBle,
@@ -164,8 +165,15 @@ import {
164
165
  FrameVerifyError,
165
166
  verifyFramePayment,
166
167
  type DerivingWallet,
167
- type VerifiedPayment
168
+ type VerifiedPayment,
169
+ type CoverVerifier,
170
+ type SessionAsset
168
171
  } from '@bsv/expo-wallet-toolbox'
172
+ import { readSettlementAck, tokenSendState } from '../../../core/localpay/settlementAck'
173
+ import { useMandala } from '../../hooks/useMandala'
174
+ import { useOnline } from '../../hooks/useOnline'
175
+ import { formatTokenAmount, formatTokenAmountWithUnit } from '../../tokenFormat'
176
+ import type { AmountInputAsset } from '../wallet/AmountInput'
169
177
  import type { DismissTarget } from '../../dismissTarget'
170
178
 
171
179
  /**
@@ -318,7 +326,8 @@ const DECLINE_KEYS: Record<DeclineReason, string> = {
318
326
  session_mismatch: 'local_pay_declined_mismatch',
319
327
  already_paid: 'local_pay_declined_already_paid',
320
328
  save_failed: 'local_pay_declined_save',
321
- decode_failed: 'local_pay_declined_decode'
329
+ decode_failed: 'local_pay_declined_decode',
330
+ not_covered: 'local_pay_declined_not_covered'
322
331
  }
323
332
 
324
333
  /**
@@ -371,12 +380,43 @@ function abbreviateKey(key: string): string {
371
380
  return key.length > 16 ? `${key.slice(0, 10)}…${key.slice(-6)}` : key
372
381
  }
373
382
 
374
- /** Satoshis from a free-text field, or 0 when it is not yet a usable figure. */
383
+ /**
384
+ * Whole units from a free-text field, or 0 when it is not yet a usable figure.
385
+ * Satoshis on a BSV session; on a token session the amount field is in token
386
+ * mode and already emits whole base units, so the same read is right for both.
387
+ */
375
388
  function satsFrom(text: string): number {
376
389
  const n = Math.round(Number(text))
377
390
  return Number.isFinite(n) && n > 0 ? n : 0
378
391
  }
379
392
 
393
+ /**
394
+ * The unit a token session's figures are typed and shown in on THIS device.
395
+ *
396
+ * The wallet's own RESOLVED metadata comes first: a payer only ever pays an
397
+ * asset this wallet holds (executeSend refuses anything else), and a
398
+ * `decimals` the registry answered is the figure the overlay stood behind —
399
+ * a request claiming 4 decimals against an asset this wallet knows has 2
400
+ * would otherwise show 2,500.00 USDX as "0.2500". The session's own block —
401
+ * whatever the payee's wallet wrote into the QR — is the fallback when this
402
+ * wallet's lookup has NOT resolved: the runtime fabricates `''`/`0` for a
403
+ * holding it could not identify (an offline cold start, the normal case on
404
+ * this rail), and a zero it cannot stand behind must never beat a figure the
405
+ * payee's wallet did resolve. The pair is taken from ONE source: a resolved
406
+ * decimals beside an unresolved ticker would be a figure with no name.
407
+ * `ticker: ''` on the result means neither side knows the unit, and the
408
+ * screen refuses to send rather than let the payer type into an unlabelled
409
+ * field (design principle 4).
410
+ */
411
+ function assetUnits(asset: SessionAsset, held?: { ticker: string; decimals: number } | null): AmountInputAsset {
412
+ const resolved = held && held.ticker !== '' ? held : undefined
413
+ if (resolved) return { ticker: resolved.ticker, decimals: resolved.decimals }
414
+ // The session block counts only when it names BOTH halves: a ticker with no
415
+ // decimals would be a named figure at a guessed scale.
416
+ if (asset.ticker && asset.decimals !== undefined) return { ticker: asset.ticker, decimals: asset.decimals }
417
+ return { ticker: '', decimals: 0 }
418
+ }
419
+
380
420
  // ── Screen ──
381
421
 
382
422
  export interface NearbyFlowProps {
@@ -386,8 +426,15 @@ export interface NearbyFlowProps {
386
426
  onExit: () => void
387
427
  /** Payer only: a session the Pay screen already scanned. Skips the scanner, lands on confirm. */
388
428
  initialSession?: Session
389
- /** Payee only: mint immediately for this amount (undefined = open request). Skips receive_amount. */
390
- initialRequest?: { sats?: number }
429
+ /**
430
+ * Payee only: mint immediately for this amount (undefined = open request).
431
+ * Skips receive_amount.
432
+ *
433
+ * `amount` is satoshis when no asset is named and BASE UNITS of that asset
434
+ * when one is — the session carries the asset alongside the figure, so the
435
+ * two can never be read in the wrong unit downstream.
436
+ */
437
+ initialRequest?: { sats?: number; asset?: SessionAsset }
391
438
  /** Where the post-payment overlay and an exited QR flow send the user. Defaults to `/`. */
392
439
  dismissTo?: DismissTarget
393
440
  }
@@ -410,6 +457,38 @@ function NearbyFlow({
410
457
  const reducedMotion = useReducedMotion()
411
458
  const { managers, adminOriginator, storage } = useWalletManagers()
412
459
  const wallet = managers?.permissionsManager ?? null
460
+ /**
461
+ * The only door to stablecoins this screen has. Everything token-shaped
462
+ * below is gated on it: with no runtime there is no token session to mint,
463
+ * no token frame to build, and a scanned token request is refused with a
464
+ * plain reason rather than paid in satoshis.
465
+ */
466
+ const mandala = useMandala()
467
+ /**
468
+ * COVER at hand-over (offline-settlement §1.2). The payee credits a token
469
+ * frame only once every un-admitted ancestor in it is covered by the
470
+ * evidence the frame itself carries; a frame that fails is refused exactly
471
+ * like an unreadable one, because crediting money the issuer's overlay has
472
+ * never vouched for is the mistake this whole evidence model exists to
473
+ * prevent.
474
+ *
475
+ * The walk is the lib's, beside the overlay's own σ_I digest, and reaches
476
+ * this screen through the runtime — `ui/` never imports `@bsv/mandala`.
477
+ */
478
+ const coverVerifier: CoverVerifier | null = mandala.runtime?.coverVerifier ?? null
479
+
480
+ /**
481
+ * Who to name in a token sentence. Best-effort and never load-bearing: an
482
+ * asset this wallet does not hold has no resolved issuer, and "the issuer" is
483
+ * the honest noun for it — never a hex key, and never a party we cannot name.
484
+ */
485
+ const issuerNameFor = useCallback(
486
+ (assetId?: string) => {
487
+ const held = assetId ? (mandala.balances ?? []).find(b => b.asset.assetId === assetId) : undefined
488
+ return held?.asset.issuerName || t('token_issuer_fallback')
489
+ },
490
+ [mandala.balances, t]
491
+ )
413
492
 
414
493
  const [phase, setPhase] = useState<Phase>('entry')
415
494
  const [role, setRole] = useState<'payee' | 'payer' | null>(initialRole)
@@ -430,9 +509,24 @@ function NearbyFlow({
430
509
  */
431
510
  /** The payer's own entry, used only when the scanned session left the amount open. */
432
511
  const [sendAmount, setSendAmount] = useState('')
512
+ /**
513
+ * The payer's note, same PayForm field as the handle rail's. Rides on the
514
+ * frame (codec.ts's `PaymentFrame.note`) and becomes the payee's action
515
+ * description in place of the fixed "Received BSV/token" wording — the
516
+ * counterpart of what the message-box rail already does.
517
+ */
518
+ const [note, setNote] = useState('')
433
519
 
434
520
  const [paymentQr, setPaymentQr] = useState<string | null>(null)
435
521
  const [settledAmount, setSettledAmount] = useState(0)
522
+ /**
523
+ * Token mode: the figure in the asset's own units, and what is and is not
524
+ * settled yet. Held apart from `settledAmount`, which is satoshis and on the
525
+ * token path is always 1 (BRC-92) — rendering it would show "1" for every
526
+ * token payment ever made.
527
+ */
528
+ const [settledTokenText, setSettledTokenText] = useState<string | null>(null)
529
+ const [settledStatusNote, setSettledStatusNote] = useState<string | null>(null)
436
530
  const [failure, setFailure] = useState<Failure | null>(null)
437
531
  const [notice, setNotice] = useState<Notice | null>(null)
438
532
 
@@ -448,6 +542,75 @@ function NearbyFlow({
448
542
  /** True once the AWDL link has provably carried this session's frame. */
449
543
  const [linked, setLinked] = useState(false)
450
544
 
545
+ /**
546
+ * Connectivity, read through a ref.
547
+ *
548
+ * The only thing this screen asks about signal is whether a hand-over that
549
+ * just landed should be followed by this device's own submit. Reading it from
550
+ * a ref keeps a connectivity flap — which on a screen two people are pointing
551
+ * at each other happens constantly — from re-creating the send callback that
552
+ * a payer may be halfway through.
553
+ */
554
+ const online = useOnline()
555
+ const onlineRef = useRef(online)
556
+ useEffect(() => {
557
+ onlineRef.current = online
558
+ }, [online])
559
+
560
+ /**
561
+ * Whether this screen is still here.
562
+ *
563
+ * `settleAfterHandover` outlives the send callback that started it — that is
564
+ * the point of not awaiting it — and by the time it resolves the send's own
565
+ * AbortController has already been retired from the registry that `abortAll`
566
+ * sweeps on unmount. So its signal alone cannot answer "is anyone still
567
+ * looking at this?", and this ref does.
568
+ */
569
+ const mountedRef = useRef(true)
570
+ useEffect(
571
+ () => () => {
572
+ mountedRef.current = false
573
+ },
574
+ []
575
+ )
576
+
577
+ /**
578
+ * The payer's own submit, taken the moment a hand-over has landed (§4.3,
579
+ * 2026-09-15 refinement).
580
+ *
581
+ * Every ordering rule this feature has is enforced by WHERE this is called
582
+ * from, not by anything in here: it runs only after a positive ack and only
583
+ * after `finalizeDelivery`'s hold, so the payee holds the frame and this
584
+ * device holds a durable queue row before the overlay hears about any of it.
585
+ * What is left is one best-effort call and one sentence.
586
+ *
587
+ * Never awaited by the caller and never able to fail a payment. Offline it is
588
+ * not attempted at all — the drain owns every retry, and a face-to-face
589
+ * payment is exactly the case where there may be no signal for hours. The
590
+ * abort signal gates only the UI write: the settlement itself is a money
591
+ * decision and is allowed to finish on a screen the payer has walked away
592
+ * from.
593
+ */
594
+ const settleAfterHandover = useCallback(
595
+ async (txid: string, issuer: string, signal: AbortSignal): Promise<void> => {
596
+ const runtime = mandala.runtime
597
+ if (!runtime || !onlineRef.current) return
598
+ try {
599
+ const state = await runtime.settleNow(txid)
600
+ if (signal.aborted || !mountedRef.current) return
601
+ // `admitted` is the issuer's overlay having folded this transaction
602
+ // into its own state — the broadcast on top of it is bookkeeping — so
603
+ // both read as settled, exactly as the activity list reads them.
604
+ if (state === 'admitted' || state === 'broadcast') setSettledStatusNote(t('token_sent_settled', { issuer }))
605
+ } catch (e) {
606
+ // The payment is made and the row is durable; this was only ever an
607
+ // attempt to finish it early.
608
+ console.warn('[localpay] could not settle the hand-over immediately:', e instanceof Error ? e.message : e)
609
+ }
610
+ },
611
+ [mandala.runtime, t]
612
+ )
613
+
451
614
  /**
452
615
  * The payee's `broadcast` flag for the shared success overlay (see the
453
616
  * `phase === 'done'` render below): whether storage already records a
@@ -676,8 +839,11 @@ function NearbyFlow({
676
839
  setScannedSession(null)
677
840
  setRequestAmount('')
678
841
  setSendAmount('')
842
+ setNote('')
679
843
  setPaymentQr(null)
680
844
  setSettledAmount(0)
845
+ setSettledTokenText(null)
846
+ setSettledStatusNote(null)
681
847
  setFailure(null)
682
848
  setNotice(null)
683
849
  setUnsettled(null)
@@ -758,27 +924,46 @@ function NearbyFlow({
758
924
  // written, so every failure here is a provable "queued nothing".
759
925
  let verified: VerifiedPayment
760
926
  try {
761
- verified = await verifyFramePayment(wallet as unknown as DerivingWallet, frame, adminOriginator)
927
+ verified = await verifyFramePayment(wallet as unknown as DerivingWallet, frame, adminOriginator, {
928
+ // A token frame with no verifier is REFUSED, not credited: no
929
+ // verifier is no evidence, and verify.ts enforces that. Absent on a
930
+ // BSV request, where it is never read.
931
+ //
932
+ // `asset` is the session's OWN block — this device minted it — and is
933
+ // the trust anchor wire contract §9.10 requires: the frame's
934
+ // `overlayUrl`/`overlayIdentityKey` are data, and must equal it or
935
+ // the frame is refused before COVER ever runs.
936
+ ...(session.asset ? { cover: coverVerifier ?? undefined, asset: session.asset } : {})
937
+ })
762
938
  } catch (e) {
763
939
  // `not_mine` is a frame that was never for this request; `unparseable`
764
- // is bytes that are not a transaction. Both leave the request LIVE and
765
- // unspent, exactly as a nonce mismatch does, so the genuine payer can
766
- // still complete.
940
+ // is bytes that are not a transaction; `not_covered` is a token frame
941
+ // whose evidence does not cover its own ancestry. All three leave the
942
+ // request LIVE and unspent, exactly as a nonce mismatch does, so the
943
+ // genuine payer can still complete.
767
944
  const kind = e instanceof FrameVerifyError ? e.kind : 'unparseable'
768
945
  void confirm?.(false, kind === 'not_mine' ? 'session_mismatch' : 'decode_failed')
946
+ if (kind === 'not_covered') {
947
+ // The one refusal that is about the ISSUER's records rather than
948
+ // about this pair of devices, so it says so instead of reading as a
949
+ // scanning mistake.
950
+ setNotice({ text: t('token_cover_failed', { issuer: issuerNameFor(session.asset?.id) }), tone: 'warning' })
951
+ }
769
952
  scanLatchRef.current = false
770
953
  setSessionMismatch(true)
771
954
  setPhase('receive_wait')
772
955
  setListenerEpoch(n => n + 1)
773
956
  return
774
957
  }
775
- if (verified.kind !== 'bsv') {
776
- // This app's settle path only credits BSV payments today; a token frame
777
- // is refused before anything latches, exactly like a session mismatch —
778
- // and, like that path, the request stays LIVE: re-arm the scan latch,
779
- // surface the mismatch, return to the waiting screen, and restart the
780
- // listener the rejected frame consumed, so a genuine (BSV) payer can
781
- // still complete.
958
+ // Denomination is a binding term of the request, both ways: a token frame
959
+ // against a BSV request pays in the wrong money, and a BSV frame against a
960
+ // token request pays in the wrong money the other way round. Neither is a
961
+ // failure of this device, so both leave the request live.
962
+ const assetMismatch =
963
+ verified.kind === 'token'
964
+ ? !session.asset || session.asset.id !== verified.assetId
965
+ : session.asset !== undefined
966
+ if (assetMismatch) {
782
967
  void confirm?.(false, 'session_mismatch')
783
968
  scanLatchRef.current = false
784
969
  setSessionMismatch(true)
@@ -786,7 +971,10 @@ function NearbyFlow({
786
971
  setListenerEpoch(n => n + 1)
787
972
  return
788
973
  }
789
- const satoshis = verified.satoshis
974
+ // Satoshis on the BSV path, base units of the session's asset on the
975
+ // token path. Every check below binds the figure the payee ASKED for to
976
+ // the figure that was actually locked, in whichever unit that is.
977
+ const satoshis = verified.kind === 'token' ? verified.amount : verified.satoshis
790
978
 
791
979
  // (0) Bind the frame to THIS session, before the one-shot latch and before
792
980
  // any write. Two distinct holes close here:
@@ -921,6 +1109,22 @@ function NearbyFlow({
921
1109
  // and the payer builds a second createAction from different UTXOs: both
922
1110
  // internalize, the payee is credited twice and the payer pays twice.
923
1111
  setSettledAmount(satoshis)
1112
+ setSettledTokenText(
1113
+ session.asset
1114
+ ? // Never `null` on the token path: falling through to the satoshi
1115
+ // renderer would print base units as satoshis.
1116
+ formatTokenAmountWithUnit(satoshis, {
1117
+ decimals: session.asset.decimals ?? 0,
1118
+ ticker: session.asset.ticker ?? ''
1119
+ }) ?? t('token_row_amount_pending')
1120
+ : null
1121
+ )
1122
+ // Credited and spendable — and not yet confirmed by the issuer. Both are
1123
+ // true at this moment and the receipt says both, because a receipt that
1124
+ // said only the first would be claiming a settlement nobody has.
1125
+ setSettledStatusNote(
1126
+ session.asset ? t('local_pay_token_not_cleared', { issuer: issuerNameFor(session.asset.id) }) : null
1127
+ )
924
1128
  setRole('payee')
925
1129
  setPhase('done')
926
1130
  // The overlay below renders as soon as phase flips; start it optimistic
@@ -955,13 +1159,28 @@ function NearbyFlow({
955
1159
  // `storage?.sqliteDb`, because `settleReceived` re-checks `storage`
956
1160
  // is non-null on every call and this closure must not re-derive that.
957
1161
  const db = storage.sqliteDb
958
- const results = await processPending(wallet, storage, adminOriginator, async (txid, info) => {
959
- if (!db) return
960
- await updateOfflineAction(db, txid, {
961
- senderIdentityKey: info.senderIdentityKey,
962
- receivedVia: info.receivedVia
963
- })
964
- })
1162
+ const results = await processPending(
1163
+ wallet,
1164
+ storage,
1165
+ adminOriginator,
1166
+ async (txid, info) => {
1167
+ if (!db) return
1168
+ await updateOfflineAction(db, txid, {
1169
+ senderIdentityKey: info.senderIdentityKey,
1170
+ receivedVia: info.receivedVia
1171
+ })
1172
+ },
1173
+ // A credited token frame's settlement row and evidence. Isolated
1174
+ // inside processPending from the internalize itself, so a failing
1175
+ // journal write can never un-credit a coin that is already ours.
1176
+ mandala.runtime?.onTokenCredited,
1177
+ // The same write, BEFORE the internalize. This is the path that
1178
+ // actually needs it: a payee on Wi-Fi internalizing a frame from an
1179
+ // offline payer triggers a forced broadcast inside `internalizeAction`,
1180
+ // and the only thing that stops an unadmitted token going out there is
1181
+ // the `token_settlements` row this hook writes first (§4.3 guard #2).
1182
+ mandala.runtime?.onTokenHeld
1183
+ )
965
1184
  const credited = results.some(r => r.success)
966
1185
  setNotice(
967
1186
  credited ? { text: t('local_pay_added'), tone: 'success' } : { text: t('local_pay_queued'), tone: 'info' }
@@ -989,7 +1208,7 @@ function NearbyFlow({
989
1208
  setNotice({ text: t('local_pay_queued'), tone: 'info' })
990
1209
  }
991
1210
  },
992
- [storage, wallet, adminOriginator, fail, t]
1211
+ [storage, wallet, adminOriginator, coverVerifier, issuerNameFor, mandala.runtime, fail, t]
993
1212
  )
994
1213
 
995
1214
  // Read through refs so the listener effect below depends only on the session
@@ -1053,7 +1272,7 @@ function NearbyFlow({
1053
1272
 
1054
1273
  // ── Receive: mint the request ──
1055
1274
 
1056
- const startRequest = useCallback(async (requested?: number) => {
1275
+ const startRequest = useCallback(async (requested?: number, asset?: SessionAsset) => {
1057
1276
  // Zero (or blank) is the user asking the payer to choose, so it becomes an
1058
1277
  // open session rather than a rejected input. Undefined, never 0 — the codec
1059
1278
  // refuses a non-positive amount precisely so a corrupt zero can never be
@@ -1098,7 +1317,11 @@ function NearbyFlow({
1098
1317
  const bleLive = bleNow === 'poweredOn' && blePermitted
1099
1318
  const session = mintSession({
1100
1319
  identityKey,
1320
+ // Satoshis, or base units of `asset` — `isRequestableAmount` is
1321
+ // unit-agnostic and the asset travels with the figure, so the payer
1322
+ // can never read one as the other.
1101
1323
  amount: sats,
1324
+ asset,
1102
1325
  derivationPrefix,
1103
1326
  derivationSuffix,
1104
1327
  // Caps advertise what this payee can DO; the payer's ladder picks the
@@ -1116,6 +1339,10 @@ function NearbyFlow({
1116
1339
  hints: capsFromProbe({ ...probe, bluetooth: bleHere ? bleNow : probe.bluetooth }),
1117
1340
  os: Platform.OS === 'ios' ? 'ios' : 'android'
1118
1341
  })
1342
+ // Same reason as the payer's side: the drain re-derives this device's own
1343
+ // settlement rows from sealed frames, and the key that opens them lives
1344
+ // only here, for this process.
1345
+ if (session.asset) rememberSessionPsk(session.psk)
1119
1346
  setRole('payee')
1120
1347
  setHostedSession(session)
1121
1348
  setPhase('receive_wait')
@@ -1175,6 +1402,11 @@ function NearbyFlow({
1175
1402
 
1176
1403
  /** The state moves that follow a valid session, whether scanned here or handed in. */
1177
1404
  const adoptSession = useCallback((session: Session) => {
1405
+ // The payer's own sealed `offline_actions.framePayload` can only be
1406
+ // re-opened by the settlement drain while this process still holds the
1407
+ // session key — it is deliberately never written to disk. Remembered at
1408
+ // the moment the session is adopted, before anything is built with it.
1409
+ if (session.asset) rememberSessionPsk(session.psk)
1178
1410
  setScannedSession(session)
1179
1411
  // Prompt-free read of this device's Bluetooth state for describeFloor.
1180
1412
  // Never prepare() here: a payer who lands on QR must never be prompted.
@@ -1183,6 +1415,7 @@ function NearbyFlow({
1183
1415
  // recipient card; nothing waits on it.
1184
1416
  setPeerKey(session.identityKey)
1185
1417
  setSendAmount('')
1418
+ setNote('')
1186
1419
  setRole('payer')
1187
1420
  setPhase('send_confirm')
1188
1421
  }, [])
@@ -1221,7 +1454,7 @@ function NearbyFlow({
1221
1454
  if (initialRole === 'payee' && initialRequest) {
1222
1455
  if (!permissionsSettled || mintedRef.current) return
1223
1456
  mintedRef.current = true
1224
- void startRequest(initialRequest.sats)
1457
+ void startRequest(initialRequest.sats, initialRequest.asset)
1225
1458
  return
1226
1459
  }
1227
1460
  if (enteredRef.current) return
@@ -1244,7 +1477,7 @@ function NearbyFlow({
1244
1477
  abortAll()
1245
1478
  clearFlowState()
1246
1479
  if (initialRole === 'payee') {
1247
- if (initialRequest) void startRequest(initialRequest.sats)
1480
+ if (initialRequest) void startRequest(initialRequest.sats, initialRequest.asset)
1248
1481
  else setPhase('receive_amount')
1249
1482
  } else if (initialSession) {
1250
1483
  adoptSession(initialSession)
@@ -1276,19 +1509,104 @@ function NearbyFlow({
1276
1509
  [sendKind, scannedSession, bleState]
1277
1510
  )
1278
1511
 
1512
+ /**
1513
+ * This payer's own holding of the scanned session's asset, if any. It is
1514
+ * what Max writes and what the available line shows on an open token
1515
+ * request, and its resolved metadata is the unit every figure on this side
1516
+ * is read in (`assetUnits`). `null` on a BSV session, and on a token this
1517
+ * wallet does not hold — which executeSend then refuses.
1518
+ */
1519
+ const scannedHolding = useMemo(
1520
+ () =>
1521
+ scannedSession?.asset
1522
+ ? ((mandala.balances ?? []).find(b => b.asset.assetId === scannedSession.asset?.id) ?? null)
1523
+ : null,
1524
+ [scannedSession, mandala.balances]
1525
+ )
1526
+ /**
1527
+ * Token mode for everything the payer sees on a token session: the amount
1528
+ * field, the confirm figure, the code caption and the receipt. `undefined`
1529
+ * on a BSV session, where the field takes satoshis as it always has.
1530
+ */
1531
+ const scannedAssetUnits = useMemo(
1532
+ () => (scannedSession?.asset ? assetUnits(scannedSession.asset, scannedHolding?.asset) : undefined),
1533
+ [scannedSession, scannedHolding]
1534
+ )
1535
+ /**
1536
+ * The unit can move underneath a figure already typed: the session's block
1537
+ * answers first, and the wallet's own resolved holding may arrive a moment
1538
+ * later with different decimals. The field would keep the old text while
1539
+ * emitting the old unit's base units, so the figure is cleared instead —
1540
+ * it means something different in the new unit (the same rule the Pay
1541
+ * form's asset picker follows).
1542
+ */
1543
+ const unitDecimals = scannedAssetUnits?.decimals
1544
+ const unitDecimalsRef = useRef(unitDecimals)
1545
+ useEffect(() => {
1546
+ if (unitDecimalsRef.current === unitDecimals) return
1547
+ unitDecimalsRef.current = unitDecimals
1548
+ setSendAmount('')
1549
+ }, [unitDecimals])
1550
+ /** Neither the session nor this wallet could name the unit: nothing here may be typed or sent. */
1551
+ const unitsUnknown = scannedAssetUnits !== undefined && scannedAssetUnits.ticker === ''
1552
+
1279
1553
  /**
1280
1554
  * The figure this payment will actually carry.
1281
1555
  *
1282
1556
  * The payee's request wins outright when they named one — the payer must not
1283
1557
  * be able to talk it down, and the payee's settle check would refuse anything
1284
- * else anyway. Otherwise it is the payer's own entry. 0 means "not a usable
1285
- * amount yet" and keeps Send disabled.
1558
+ * else anyway. Otherwise it is the payer's own entry — satoshis on a BSV
1559
+ * session, whole base units on a token one, because the field is in token
1560
+ * mode there (`scannedAssetUnits`) and never emits anything else. 0 means
1561
+ * "not a usable amount yet" and keeps Send disabled.
1286
1562
  */
1287
1563
  const payAmount = useMemo(() => {
1288
1564
  if (!scannedSession) return 0
1289
1565
  return scannedSession.amount ?? satsFrom(sendAmount)
1290
1566
  }, [scannedSession, sendAmount])
1291
1567
 
1568
+ /**
1569
+ * The token receipt, once a hand-over is accepted — one writer for BOTH
1570
+ * rails, so the fountain can never again show the 1 satoshi a token output
1571
+ * carries where the radio shows "25.00 USDX".
1572
+ *
1573
+ * The figure is in the asset's own units (`built.tokenAmount`, the payment
1574
+ * — never `built.satoshis`), and the settlement sentence is "settled" only
1575
+ * when the ack already carried a verifying σ_I; otherwise "settling", which
1576
+ * this payer's own immediate submit (if online) may still turn into
1577
+ * "settled" before the screen dismisses. That submit is taken now rather
1578
+ * than on the next drain tick (ux design §4.3 step 7), strictly AFTER the
1579
+ * positive ack and `finalizeDelivery`'s hold — the payee has the frame and
1580
+ * this device has a durable queue row before the overlay is asked anything —
1581
+ * and deliberately NOT awaited: the receipt is already true and must not
1582
+ * wait on a network round trip. Registered for as long as it is in flight so
1583
+ * a blur or unmount gates the resulting UI write — the settle call itself
1584
+ * still runs to completion (see settleAfterHandover).
1585
+ */
1586
+ const writeTokenReceipt = useCallback(
1587
+ (asset: SessionAsset, built: { txid?: string; tokenAmount?: number }, alreadySettled: boolean) => {
1588
+ const issuer = issuerNameFor(asset.id)
1589
+ setSettledTokenText(
1590
+ formatTokenAmountWithUnit(built.tokenAmount ?? payAmount, scannedAssetUnits ?? assetUnits(asset)) ??
1591
+ t('token_row_amount_pending')
1592
+ )
1593
+ setSettledStatusNote(
1594
+ alreadySettled
1595
+ ? t('token_sent_settled', { issuer })
1596
+ : peerName
1597
+ ? t('token_sent_settling', { issuer, payee: peerName })
1598
+ : t('token_sent_settling_unnamed', { issuer })
1599
+ )
1600
+ if (alreadySettled || !built.txid) return
1601
+ const controller = new AbortController()
1602
+ abortsRef.current.add(controller)
1603
+ void settleAfterHandover(built.txid, issuer, controller.signal).finally(() => {
1604
+ abortsRef.current.delete(controller)
1605
+ })
1606
+ },
1607
+ [issuerNameFor, payAmount, scannedAssetUnits, peerName, settleAfterHandover, t]
1608
+ )
1609
+
1292
1610
  // ── Send: release an abandoned build ──
1293
1611
  //
1294
1612
  // buildPaymentFrame creates the action with `noSend: true`, which flips its
@@ -1352,6 +1670,18 @@ function NearbyFlow({
1352
1670
  const controller = new AbortController()
1353
1671
  registry.add(controller)
1354
1672
 
1673
+ // A token request this wallet is not set up for is refused before anything
1674
+ // is built: v1 resolves one overlay, and paying a token whose issuer this
1675
+ // device cannot reach would produce a frame nobody can settle.
1676
+ if (session.asset) {
1677
+ const runtime = mandala.runtime
1678
+ const known = (mandala.balances ?? []).find(b => b.asset.assetId === session.asset?.id)
1679
+ if (!runtime || !known || known.asset.overlayIdentityKey !== session.asset.overlayIdentityKey) {
1680
+ fail('generic', t('pay_asset_nearby_wrong_overlay'))
1681
+ return
1682
+ }
1683
+ }
1684
+
1355
1685
  try {
1356
1686
  let built: Awaited<ReturnType<typeof buildPaymentFrame>>
1357
1687
  try {
@@ -1359,7 +1689,19 @@ function NearbyFlow({
1359
1689
  // `number[]`, while the SDK's `AtomicBEEF` is `Byte[] | Uint8Array`. The
1360
1690
  // manager satisfies the contract at runtime — build.ts wraps the result in
1361
1691
  // `new Uint8Array(...)`, which accepts either — so this is nominal only.
1362
- built = await buildPaymentFrame(wallet as unknown as PayingWalletArg, session, adminOriginator, payAmount)
1692
+ built = await buildPaymentFrame(
1693
+ wallet as unknown as PayingWalletArg,
1694
+ session,
1695
+ adminOriginator,
1696
+ payAmount,
1697
+ // The token half of the build: the payee lock (blinded A′, which no
1698
+ // BRC-100 method can produce) and this device's evidence tables, for
1699
+ // the AdmissionBundle the frame carries. Nothing is submitted here —
1700
+ // hand-over comes first, unconditionally, so a face-to-face payment
1701
+ // never waits on a network.
1702
+ session.asset ? mandala.runtime?.tokenBuildDeps : undefined,
1703
+ note
1704
+ )
1363
1705
  } catch (e) {
1364
1706
  // Build errors are wallet errors and must keep their own message. A
1365
1707
  // declined spending prompt reads "Permission denied", which the Local
@@ -1454,7 +1796,23 @@ function NearbyFlow({
1454
1796
  // better than the null-dereference `storage as never` would throw
1455
1797
  // instead — same outward outcome, an honest cause.
1456
1798
  if (!storage) throw new Error('no local storage to queue this payment in')
1457
- await holdSentPaymentOffline({ storage, txid })
1799
+ await holdSentPaymentOffline({
1800
+ storage,
1801
+ txid,
1802
+ // Token sessions only: the still-plaintext frame and the hook that
1803
+ // journals it, so the payer's own settlement row survives a
1804
+ // restart (see `TokenHandoverDeps`). The BSV rail has neither.
1805
+ ...(session.asset
1806
+ ? {
1807
+ frame: built.frame,
1808
+ onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
1809
+ // The noSend action's own reference, onto the settlement row:
1810
+ // it is what lets the abort guard tell a handed-over token
1811
+ // payment from an abandoned one (core/mandala/abortGuard.ts).
1812
+ reference: built.reference
1813
+ }
1814
+ : {})
1815
+ })
1458
1816
  },
1459
1817
  queueFailedAbort: async reference => {
1460
1818
  if (!storage) return
@@ -1490,13 +1848,50 @@ function NearbyFlow({
1490
1848
  }
1491
1849
  // `built.satoshis` is the real amount the wallet locked into the output —
1492
1850
  // `payAmount` is only what was requested, and the two diverge under
1493
- // send-max (`payAmount` carries the sentinel).
1851
+ // send-max (`payAmount` carries the sentinel). On the token path it is 1
1852
+ // satoshi, per BRC-92, and `built.tokenAmount` is the payment.
1494
1853
  setSettledAmount(built.satoshis)
1854
+ if (session.asset) {
1855
+ // σ_I, if the recipient's drain already had it and sent it back — and
1856
+ // only if it VERIFIES (FIX H). An unverified payload is treated as
1857
+ // absent, never as proof and never as a decline, so the worst a forged
1858
+ // ack can cost this payer is one idempotent submit by their own drain.
1859
+ let admission
1860
+ try {
1861
+ const verify = mandala.runtime?.verifyAdmissionEntry
1862
+ admission = verify
1863
+ ? await readSettlementAck(ack, {
1864
+ overlayIdentityKey: session.asset.overlayIdentityKey,
1865
+ expectTxid: built.txid,
1866
+ verify
1867
+ })
1868
+ : undefined
1869
+ } catch {
1870
+ // Absent, like every other unreadable payload.
1871
+ admission = undefined
1872
+ }
1873
+ writeTokenReceipt(session.asset, built, tokenSendState(admission) === 'sent-settled')
1874
+ }
1495
1875
  setPhase('done')
1496
1876
  } finally {
1497
1877
  registry.delete(controller)
1498
1878
  }
1499
- }, [scannedSession, sendKind, payAmount, wallet, adminOriginator, storage, abortBuild, declineMessage, fail, t])
1879
+ }, [
1880
+ scannedSession,
1881
+ sendKind,
1882
+ payAmount,
1883
+ note,
1884
+ writeTokenReceipt,
1885
+ wallet,
1886
+ adminOriginator,
1887
+ storage,
1888
+ mandala.runtime,
1889
+ mandala.balances,
1890
+ abortBuild,
1891
+ declineMessage,
1892
+ fail,
1893
+ t
1894
+ ])
1500
1895
 
1501
1896
  // ── Send: the payer asserts QR delivery ──
1502
1897
  //
@@ -1548,7 +1943,22 @@ function NearbyFlow({
1548
1943
  if (!release) {
1549
1944
  try {
1550
1945
  if (storage && built.txid) {
1551
- await parkSentPaymentOffline({ storage, txid: built.txid, framePayload })
1946
+ await parkSentPaymentOffline({
1947
+ storage,
1948
+ txid: built.txid,
1949
+ framePayload,
1950
+ // Token sessions only — see the hold callback below for why.
1951
+ ...(session.asset
1952
+ ? {
1953
+ frame: built.frame,
1954
+ onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
1955
+ // The noSend action's own reference, onto the settlement row:
1956
+ // it is what lets the abort guard tell a handed-over token
1957
+ // payment from an abandoned one (core/mandala/abortGuard.ts).
1958
+ reference: built.reference
1959
+ }
1960
+ : {})
1961
+ })
1552
1962
  }
1553
1963
  } catch (e) {
1554
1964
  console.warn('[localpay] could not park the payment:', e instanceof Error ? e.message : e)
@@ -1559,7 +1969,24 @@ function NearbyFlow({
1559
1969
  const outcome = await finalizeDelivery(wallet as unknown as PayingWalletArg, built, { ok: true }, adminOriginator, {
1560
1970
  hold: async txid => {
1561
1971
  if (!storage) throw new Error('no local storage to queue this payment in')
1562
- await holdSentPaymentOffline({ storage, txid, framePayload })
1972
+ await holdSentPaymentOffline({
1973
+ storage,
1974
+ txid,
1975
+ framePayload,
1976
+ // Token sessions only: same reasoning as the executeSend hold call —
1977
+ // the plaintext frame and the journal hook, so a restart does not
1978
+ // strand this payer's settlement row.
1979
+ ...(session.asset
1980
+ ? {
1981
+ frame: built.frame,
1982
+ onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
1983
+ // The noSend action's own reference, onto the settlement row:
1984
+ // it is what lets the abort guard tell a handed-over token
1985
+ // payment from an abandoned one (core/mandala/abortGuard.ts).
1986
+ reference: built.reference
1987
+ }
1988
+ : {})
1989
+ })
1563
1990
  },
1564
1991
  queueFailedAbort: async reference => {
1565
1992
  if (!storage) return
@@ -1572,10 +1999,13 @@ function NearbyFlow({
1572
1999
  }
1573
2000
  if (celebrate) {
1574
2001
  setSettledAmount(built.satoshis)
2002
+ // This rail has no ack payload to read σ_I from, so the receipt opens as
2003
+ // "settling" and the writer's own submit is what may settle it.
2004
+ if (session.asset) writeTokenReceipt(session.asset, built, false)
1575
2005
  setRole('payer')
1576
2006
  setPhase('done')
1577
2007
  }
1578
- }, [wallet, storage, adminOriginator, payAmount, scannedSession, paymentQr, t])
2008
+ }, [wallet, storage, adminOriginator, payAmount, scannedSession, paymentQr, mandala.runtime, writeTokenReceipt, t])
1579
2009
 
1580
2010
  // ── Send: leave send_qr without Done ──
1581
2011
  //
@@ -1687,7 +2117,15 @@ function NearbyFlow({
1687
2117
  )
1688
2118
  /** Listening over at least one radio link right now. Goes false once every fast path gives up. */
1689
2119
  const radioActive = hostedSession !== null && radioTransports.some(tr => !radioErrors[tr.kind as RadioKind])
1690
- const canSend = payAmount > 0
2120
+ /**
2121
+ * More than this payer holds of the session's asset: refused here, in the
2122
+ * asset's own words, rather than by the build's error a screen later. The
2123
+ * holding is the same basket the build selects from, so this never blocks a
2124
+ * payment the build would have made; with no holding resolved yet there is
2125
+ * nothing to compare against and the build decides, as it always has.
2126
+ */
2127
+ const overHolding = scannedHolding != null && payAmount > scannedHolding.baseUnits
2128
+ const canSend = payAmount > 0 && !overHolding && !unitsUnknown
1691
2129
  const scannerOpen = phase === 'send_scan' || phase === 'receive_scan'
1692
2130
 
1693
2131
  /**
@@ -1772,19 +2210,30 @@ function NearbyFlow({
1772
2210
 
1773
2211
  // ── Render ──
1774
2212
 
1775
- const amountBlock = (sats: number, key?: string) => (
1776
- <Animated.View key={key} entering={settleIn} style={styles.amountBlock}>
1777
- <Text
1778
- style={[styles.amountDisplay, { color: colors.textPrimary }]}
1779
- maxFontSizeMultiplier={1.3}
1780
- numberOfLines={1}
1781
- adjustsFontSizeToFit
1782
- accessibilityRole="text"
1783
- >
1784
- <AmountDisplay>{sats}</AmountDisplay>
1785
- </Text>
1786
- </Animated.View>
1787
- )
2213
+ /**
2214
+ * The figure, in whatever money this session is denominated in.
2215
+ *
2216
+ * `AmountDisplay` is a satoshi component — it reads `settings.currency` and
2217
+ * can cross into fiat — so a token amount must never reach it: 2,500 base
2218
+ * units of a 2-decimal asset would render as "2,500 satoshis" and, in a fiat
2219
+ * display mode, as a dollar figure this wallet invented.
2220
+ */
2221
+ const amountBlock = (amount: number, key?: string, units?: AmountInputAsset) => {
2222
+ const tokenText = units ? formatTokenAmountWithUnit(amount, units) : null
2223
+ return (
2224
+ <Animated.View key={key} entering={settleIn} style={styles.amountBlock}>
2225
+ <Text
2226
+ style={[styles.amountDisplay, { color: colors.textPrimary }]}
2227
+ maxFontSizeMultiplier={1.3}
2228
+ numberOfLines={1}
2229
+ adjustsFontSizeToFit
2230
+ accessibilityRole="text"
2231
+ >
2232
+ {tokenText ?? <AmountDisplay>{amount}</AmountDisplay>}
2233
+ </Text>
2234
+ </Animated.View>
2235
+ )
2236
+ }
1788
2237
 
1789
2238
  const presenceBlock = presence ? (
1790
2239
  <View style={styles.presenceSlot}>
@@ -1954,6 +2403,11 @@ function NearbyFlow({
1954
2403
  >
1955
2404
  {hostedSession.amount === undefined ? (
1956
2405
  t('local_pay_any_amount')
2406
+ ) : hostedSession.asset ? (
2407
+ formatTokenAmountWithUnit(hostedSession.amount, {
2408
+ decimals: hostedSession.asset.decimals ?? 0,
2409
+ ticker: hostedSession.asset.ticker ?? ''
2410
+ })
1957
2411
  ) : (
1958
2412
  <AmountDisplay>{hostedSession.amount}</AmountDisplay>
1959
2413
  )}
@@ -1991,20 +2445,28 @@ function NearbyFlow({
1991
2445
  <View style={styles.gapLg} />
1992
2446
  {presenceBlock}
1993
2447
 
1994
- {/* A frame arrived that belongs to a different request. Advisory,
1995
- not a failure: this session was deliberately NOT marked spent,
1996
- so the pairing QR above is still live for the real payer. */}
2448
+ {/* A frame arrived that could not be credited. Advisory, not a
2449
+ failure: this session was deliberately NOT marked spent, so
2450
+ the pairing QR above is still live for the real payer. `notice`
2451
+ (set only for a token frame that failed COVER) names the
2452
+ ISSUER's records as the reason — a specific true sentence beats
2453
+ the generic "wrong session" one, and must never read as a
2454
+ scanning mistake this device made (ux design §4.3). */}
1997
2455
  {sessionMismatch && (
1998
2456
  <>
1999
2457
  <View style={styles.gapLg} />
2000
- <Animated.View
2001
- entering={fadeIn}
2002
- style={[styles.notice, { backgroundColor: colors.error + '15', borderColor: colors.error + '40' }]}
2003
- accessibilityRole="alert"
2004
- >
2005
- <Ionicons name="alert-circle-outline" size={16} color={colors.error} />
2006
- <Text style={[styles.noticeText, { color: colors.error }]}>{t('local_pay_wrong_session')}</Text>
2007
- </Animated.View>
2458
+ {notice ? (
2459
+ noticeBlock(notice)
2460
+ ) : (
2461
+ <Animated.View
2462
+ entering={fadeIn}
2463
+ style={[styles.notice, { backgroundColor: colors.error + '15', borderColor: colors.error + '40' }]}
2464
+ accessibilityRole="alert"
2465
+ >
2466
+ <Ionicons name="alert-circle-outline" size={16} color={colors.error} />
2467
+ <Text style={[styles.noticeText, { color: colors.error }]}>{t('local_pay_wrong_session')}</Text>
2468
+ </Animated.View>
2469
+ )}
2008
2470
  </>
2009
2471
  )}
2010
2472
 
@@ -2065,16 +2527,73 @@ function NearbyFlow({
2065
2527
  <>
2066
2528
  {supportText(t('local_pay_enter_amount_send'))}
2067
2529
  <View style={styles.gapXl} />
2068
- <PayAmountField value={sendAmount} onChangeText={setSendAmount} />
2530
+ {/* Token mode on a token session: the field takes and emits base
2531
+ units of the payee's asset and labels itself with its ticker,
2532
+ Max writes this payer's real holding, and the line under it is
2533
+ that holding — never the BSV spendable figure, which is the
2534
+ fee balance and says nothing about the asset. Without `asset`
2535
+ the payer would be typing satoshis against a USDX request,
2536
+ and Max would write the satoshi send-max sentinel straight
2537
+ into a token build. */}
2538
+ <PayAmountField
2539
+ value={sendAmount}
2540
+ onChangeText={setSendAmount}
2541
+ asset={scannedAssetUnits}
2542
+ maxValue={scannedHolding && !unitsUnknown ? String(scannedHolding.baseUnits) : undefined}
2543
+ availableText={
2544
+ scannedHolding && scannedAssetUnits && !unitsUnknown
2545
+ ? (formatTokenAmount(scannedHolding.baseUnits, scannedAssetUnits.decimals) ?? undefined)
2546
+ : undefined
2547
+ }
2548
+ // No money chrome at all while the unit is unknown: an
2549
+ // unlabelled balance is exactly the figure principle 4 forbids.
2550
+ showBalance={!scannedAssetUnits || (scannedHolding != null && !unitsUnknown)}
2551
+ />
2069
2552
  </>
2070
2553
  ) : (
2071
2554
  <>
2072
- <View style={styles.stageTight}>{amountBlock(scannedSession.amount)}</View>
2555
+ <View style={styles.stageTight}>
2556
+ {unitsUnknown ? (
2557
+ // The payee named a figure this device cannot denominate:
2558
+ // a bare number at a guessed scale is exactly what must not
2559
+ // be printed (principle 4), so the slot says so instead.
2560
+ <Animated.View entering={settleIn} style={styles.amountBlock}>
2561
+ <Text
2562
+ style={[styles.amountDisplay, { color: colors.textSecondary }]}
2563
+ maxFontSizeMultiplier={1.3}
2564
+ numberOfLines={1}
2565
+ adjustsFontSizeToFit
2566
+ accessibilityRole="text"
2567
+ >
2568
+ {t('token_row_amount_pending')}
2569
+ </Text>
2570
+ </Animated.View>
2571
+ ) : (
2572
+ amountBlock(scannedSession.amount, undefined, scannedAssetUnits)
2573
+ )}
2574
+ </View>
2073
2575
  <View style={styles.gapXl} />
2074
- <AvailableBalance withUnit />
2576
+ {/* The payer's own BSV balance is the fee balance and says
2577
+ nothing about what they hold of the asset; on a token
2578
+ request it would be a figure beside an unrelated one. */}
2579
+ {!scannedSession.asset && <AvailableBalance withUnit />}
2075
2580
  </>
2076
2581
  )}
2077
2582
 
2583
+ <PayField labelKey="note">
2584
+ <TextInput
2585
+ value={note}
2586
+ onChangeText={setNote}
2587
+ placeholder={t('note_placeholder')}
2588
+ placeholderTextColor={colors.textQuaternary}
2589
+ maxLength={280}
2590
+ style={[
2591
+ styles.noteInput,
2592
+ { backgroundColor: colors.backgroundSecondary, borderColor: colors.separator, color: colors.textPrimary }
2593
+ ]}
2594
+ />
2595
+ </PayField>
2596
+
2078
2597
  <RecipientSummary
2079
2598
  name={peerName ?? abbreviateKey(scannedSession.identityKey)}
2080
2599
  detail={peerName ? abbreviateKey(scannedSession.identityKey) : undefined}
@@ -2101,6 +2620,18 @@ function NearbyFlow({
2101
2620
  </>
2102
2621
  )}
2103
2622
 
2623
+ {overHolding && scannedAssetUnits && !unitsUnknown && (
2624
+ <>
2625
+ <View style={styles.gapLg} />
2626
+ {supportText(t('pay_asset_over_balance', { ticker: scannedAssetUnits.ticker }))}
2627
+ </>
2628
+ )}
2629
+ {unitsUnknown && (
2630
+ <>
2631
+ <View style={styles.gapLg} />
2632
+ {supportText(t('pay_asset_unidentified'))}
2633
+ </>
2634
+ )}
2104
2635
  <View style={styles.gapXl} />
2105
2636
  <PrimaryButton
2106
2637
  styles={styles}
@@ -2125,7 +2656,11 @@ function NearbyFlow({
2125
2656
  maxFontSizeMultiplier={1.4}
2126
2657
  numberOfLines={1}
2127
2658
  >
2128
- <AmountDisplay>{payAmount}</AmountDisplay>
2659
+ {scannedAssetUnits ? (
2660
+ formatTokenAmountWithUnit(payAmount, scannedAssetUnits)
2661
+ ) : (
2662
+ <AmountDisplay>{payAmount}</AmountDisplay>
2663
+ )}
2129
2664
  </Text>
2130
2665
  {paymentQrBlocks > 1 && (
2131
2666
  <Text style={[styles.support, { color: colors.textSecondary }]}>{t('local_pay_animated_hint')}</Text>
@@ -2302,8 +2837,12 @@ function NearbyFlow({
2302
2837
  {phase === 'done' && (
2303
2838
  <ReceivedOverlay
2304
2839
  amount={settledAmount}
2840
+ amountText={settledTokenText ?? undefined}
2841
+ statusNote={settledStatusNote ?? undefined}
2305
2842
  direction={role === 'payer' ? 'sent' : 'received'}
2306
- broadcast={role === 'payer' ? undefined : receivedBroadcast}
2843
+ // A token receipt carries its own settlement sentence; the satoshi
2844
+ // broadcast flag would add a second, contradictory one.
2845
+ broadcast={role === 'payer' || settledTokenText ? undefined : receivedBroadcast}
2307
2846
  recipientName={
2308
2847
  role === 'payer' ? (peerName ?? (scannedSession ? abbreviateKey(scannedSession.identityKey) : undefined)) : undefined
2309
2848
  }
@@ -2537,6 +3076,14 @@ function makeStyles() {
2537
3076
  // The resolved-counterparty card and field labels moved to the shared
2538
3077
  // PayForm vocabulary (RecipientSummary / PayField).
2539
3078
 
3079
+ noteInput: {
3080
+ ...typography.body,
3081
+ borderRadius: radii.md,
3082
+ borderWidth: StyleSheet.hairlineWidth,
3083
+ paddingHorizontal: spacing.md,
3084
+ paddingVertical: spacing.md
3085
+ },
3086
+
2540
3087
  notice: {
2541
3088
  flexDirection: 'row',
2542
3089
  alignItems: 'center',