@bsv/expo-wallet-toolbox 0.21.0 → 0.23.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 (133) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/README.md +82 -13
  3. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  4. package/core/bridge/bindings.ts +459 -0
  5. package/core/bridge/conformance.ts +222 -0
  6. package/core/bridge/consent.ts +494 -0
  7. package/core/bridge/consentSheetSource.ts +98 -0
  8. package/core/bridge/dispatcher.ts +621 -0
  9. package/core/bridge/inbox.ts +464 -0
  10. package/core/bridge/index.ts +48 -0
  11. package/core/bridge/loopback/cors.ts +57 -0
  12. package/core/bridge/loopback/endpoints.ts +11 -0
  13. package/core/bridge/loopback/hostCheck.ts +25 -0
  14. package/core/bridge/loopback/index.ts +7 -0
  15. package/core/bridge/loopback/launchProof.ts +166 -0
  16. package/core/bridge/loopback/router.ts +770 -0
  17. package/core/bridge/loopback/routerTypes.ts +115 -0
  18. package/core/bridge/loopback/status.ts +52 -0
  19. package/core/bridge/memoryInboxStore.ts +222 -0
  20. package/core/bridge/permissionPolicy.ts +247 -0
  21. package/core/bridge/policy.ts +72 -0
  22. package/core/bridge/protocol/base64url.ts +64 -0
  23. package/core/bridge/protocol/connectionError.ts +79 -0
  24. package/core/bridge/protocol/constants.ts +21 -0
  25. package/core/bridge/protocol/continuity.ts +21 -0
  26. package/core/bridge/protocol/descriptor.ts +395 -0
  27. package/core/bridge/protocol/envelopes.ts +188 -0
  28. package/core/bridge/protocol/errorCodec.ts +164 -0
  29. package/core/bridge/protocol/json.ts +237 -0
  30. package/core/bridge/protocol/limits.ts +43 -0
  31. package/core/bridge/protocol/methods.ts +55 -0
  32. package/core/bridge/protocol/origin.ts +130 -0
  33. package/core/bridge/runtime.ts +642 -0
  34. package/core/bridge/runtimeFlags.ts +34 -0
  35. package/core/bridge/testing/conformanceCases.ts +149 -0
  36. package/core/bridge/testing/pageClient.ts +44 -0
  37. package/core/bridge/unverifiedManager.ts +97 -0
  38. package/core/bridge/unverifiedOriginator.ts +79 -0
  39. package/core/config.tsx +1 -16
  40. package/core/contacts/contactActivity.ts +48 -28
  41. package/core/contacts/contactsStore.ts +2 -2
  42. package/core/context/WalletConnectionContext.tsx +7 -1
  43. package/core/context/WalletContext.tsx +420 -348
  44. package/core/context/sessionTeardown.ts +46 -0
  45. package/core/demo/demoAssets.ts +8 -10
  46. package/core/demo/demoLedger.ts +32 -38
  47. package/core/demo/demoMandalaRuntime.ts +67 -49
  48. package/core/demo/index.ts +1 -1
  49. package/core/hooks/usePermissionQueue.ts +89 -34
  50. package/core/i18n/translations.tsx +983 -12
  51. package/core/index.ts +70 -37
  52. package/core/localpay/build.ts +110 -569
  53. package/core/localpay/codec.ts +190 -93
  54. package/core/localpay/pending.ts +217 -202
  55. package/core/localpay/session.ts +99 -25
  56. package/core/localpay/types.ts +6 -5
  57. package/core/localpay/verify.ts +118 -173
  58. package/core/mandala/abortGuard.ts +97 -120
  59. package/core/mandala/accessPolicy.ts +133 -0
  60. package/core/mandala/assets.ts +370 -0
  61. package/core/mandala/colorGuard.ts +178 -0
  62. package/core/mandala/colorModule.ts +82 -0
  63. package/core/mandala/createRuntime.ts +483 -2392
  64. package/core/mandala/handle.ts +694 -0
  65. package/core/mandala/kvStore.ts +105 -0
  66. package/core/mandala/nearby.ts +185 -0
  67. package/core/mandala/receipt.ts +121 -0
  68. package/core/mandala/runtime.ts +166 -312
  69. package/core/mandala/settle.ts +540 -0
  70. package/core/mandala/transferJournal.ts +395 -0
  71. package/core/mandala/types.ts +61 -311
  72. package/core/networks.ts +5 -5
  73. package/core/offline/cancelParked.ts +80 -63
  74. package/core/offline/payerHold.ts +52 -118
  75. package/core/parsePeerPayURI.ts +25 -12
  76. package/core/pay/rails/handle.ts +15 -14
  77. package/core/pay/rails/index.ts +5 -3
  78. package/core/pay/rails/nearby.ts +25 -87
  79. package/core/profiles/assertProfileEmpty.ts +19 -10
  80. package/core/services/autoApprovePolicy.ts +7 -1
  81. package/core/services/capWalletArgs.ts +2 -1
  82. package/core/services/permissionPrompts.ts +132 -0
  83. package/core/services/signingPermissionPolicy.ts +230 -2
  84. package/core/services/vault/guard.ts +15 -4
  85. package/core/services/walletArgLimits.ts +17 -2
  86. package/core/storage/StorageExpoSQLite.ts +93 -229
  87. package/core/storage/encryptedDbImage.ts +325 -0
  88. package/core/storage/methods/processOfflineActions.ts +86 -136
  89. package/core/storage/schema/createTables.ts +9 -184
  90. package/core/toolboxConfig.ts +18 -1
  91. package/package.json +9 -8
  92. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  93. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  94. package/ui/components/pay/AssetPicker.tsx +2 -2
  95. package/ui/components/pay/HandleReceive.tsx +4 -4
  96. package/ui/components/pay/NearbyFlow.tsx +324 -239
  97. package/ui/components/pay/RequestHub.tsx +10 -0
  98. package/ui/components/pay/UniversalSend.tsx +31 -28
  99. package/ui/components/pay/useRecipientInput.ts +2 -2
  100. package/ui/components/ui/PermissionSheet.tsx +625 -315
  101. package/ui/components/ui/Sheet.tsx +59 -7
  102. package/ui/components/ui/colorPrompt.ts +236 -0
  103. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  104. package/ui/components/wallet/AmountInput.tsx +9 -6
  105. package/ui/components/wallet/AssetAmount.tsx +6 -6
  106. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  107. package/ui/components/wallet/Balance.tsx +3 -1
  108. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  109. package/ui/components/wallet/tokenEviction.ts +9 -9
  110. package/ui/exportDatabases.ts +94 -5
  111. package/ui/hooks/useExportWalletData.ts +37 -24
  112. package/ui/hooks/useMandala.ts +6 -6
  113. package/ui/hooks/useSpendableBalance.ts +3 -1
  114. package/ui/importDatabases.ts +124 -29
  115. package/ui/index.ts +4 -0
  116. package/ui/screens/PayScreen.tsx +14 -20
  117. package/ui/screens/SettingsScreen.tsx +3 -1
  118. package/ui/screens/WalletCheckScreen.tsx +7 -2
  119. package/ui/screens/WalletConfigScreen.tsx +13 -1
  120. package/ui/screens/WalletHomeScreen.tsx +40 -14
  121. package/ui/screens/tokenRowTitle.ts +28 -15
  122. package/ui/tokenFormat.ts +133 -69
  123. package/ui/tokenStatus.ts +5 -8
  124. package/core/localpay/settlementAck.ts +0 -155
  125. package/core/mandala/basketMigration.ts +0 -166
  126. package/core/mandala/bundle.ts +0 -244
  127. package/core/mandala/drain.ts +0 -754
  128. package/core/mandala/inboxPrehold.ts +0 -193
  129. package/core/mandala/permissionModule.ts +0 -931
  130. package/core/mandala/resendTransfer.ts +0 -178
  131. package/core/mandala/settlementStore.ts +0 -434
  132. package/core/mandala/token.ts +0 -45
  133. package/core/offline/tokenFrames.ts +0 -197
@@ -158,7 +158,6 @@ import {
158
158
  localSupportsBle,
159
159
  localSupportsNearby,
160
160
  mintSession,
161
- rememberSessionPsk,
162
161
  nearbyTransport,
163
162
  nextPhaseAfterUnsealFailure,
164
163
  prepareBle,
@@ -185,12 +184,10 @@ import {
185
184
  declineReasonFor,
186
185
  verifyFramePayment,
187
186
  type VerifiedPayment,
188
- type CoverVerifier,
187
+ type NearbyTokenDeps,
189
188
  type SessionAsset
190
189
  } from '@bsv/expo-wallet-toolbox'
191
- import { readSettlementAck, tokenSendState } from '../../../core/localpay/settlementAck'
192
190
  import { useMandala } from '../../hooks/useMandala'
193
- import { useOnline } from '../../hooks/useOnline'
194
191
  import { formatTokenAmount, formatTokenAmountWithUnit } from '../../tokenFormat'
195
192
  import type { AmountInputAsset } from '../wallet/AmountInput'
196
193
  import type { DismissTarget } from '../../dismissTarget'
@@ -410,6 +407,27 @@ function satsFrom(text: string): number {
410
407
  return Number.isFinite(n) && n > 0 ? n : 0
411
408
  }
412
409
 
410
+ /**
411
+ * Token base units from the amount field, exact, or 0n when it is not yet a
412
+ * usable figure. The field is in token mode on a token session and emits
413
+ * whole base units as plain digits; anything else (a fraction, a sign, junk)
414
+ * is not a figure, and nothing is ever rounded into one.
415
+ */
416
+ function unitsFrom(text: string): bigint {
417
+ const t = text.trim()
418
+ if (!/^[0-9]+$/.test(t)) return 0n
419
+ const u = BigInt(t)
420
+ return u > 0n ? u : 0n
421
+ }
422
+
423
+ /** A host's request figure: exact `units` on a token request when given, else `sats`. */
424
+ function requestedFigure(r: { sats?: number; units?: bigint; asset?: SessionAsset }): number | bigint | undefined {
425
+ return r.asset && r.units !== undefined ? r.units : r.sats
426
+ }
427
+
428
+ /** How long the payer's receipt waits on its own post-ACK settle before it stays "settling" (W5). */
429
+ const SETTLE_AFTER_HANDOVER_MS = 8_000
430
+
413
431
  /**
414
432
  * The unit a token session's figures are typed and shown in on THIS device.
415
433
  *
@@ -461,16 +479,34 @@ function assetUnits(asset: SessionAsset, held?: { ticker: string; decimals: numb
461
479
  */
462
480
  export interface NearbyConfirm {
463
481
  session: Session
464
- /** The payee's own figure, which the payer cannot change; undefined is an open request. */
482
+ /**
483
+ * BSV session: the payee's own satoshi figure, which the payer cannot
484
+ * change; undefined is an open request. Always undefined on a token
485
+ * session — read `fixedUnits` there.
486
+ */
465
487
  fixedAmount?: number
466
- /** What will be paid: satoshis, or base units of `asset`. 0 until usable. */
488
+ /**
489
+ * BSV session: the satoshis that will be paid, 0 until usable. Always 0 on a
490
+ * token session, whose figure is `units` / `amountText`: token base units
491
+ * run to 2^64-1, and a number is not that figure above 2^53.
492
+ */
467
493
  amount: number
468
- /** Open request only: set the payer's figure (satoshis or base units); undefined clears it. */
469
- setAmount: (units: number | undefined) => void
494
+ /** Token session: the payee's own figure in exact base units; undefined is an open request. */
495
+ fixedUnits?: bigint
496
+ /** Token session: what will be paid, in exact base units of `asset`. 0n until usable. */
497
+ units?: bigint
498
+ /** Token session: `units` formatted in `asset` (e.g. "25.00 USDX"), when the unit can be named. */
499
+ amountText?: string
500
+ /**
501
+ * Open request only: set the payer's figure — satoshis on a BSV session,
502
+ * base units on a token one (pass a bigint there: a number above 2^53 is
503
+ * already a different figure). undefined or a non-positive value clears it.
504
+ */
505
+ setAmount: (amount: number | bigint | undefined) => void
470
506
  /** Token session: the unit every figure is in. Undefined on BSV. */
471
507
  asset?: { ticker: string; decimals: number }
472
- /** Token session: this wallet's holding of it, in base units. */
473
- holding?: number
508
+ /** Token session: this wallet's holding of it, in exact base units. */
509
+ holding?: bigint
474
510
  note: string
475
511
  setNote: (note: string) => void
476
512
  recipient: { name: string; detail?: string }
@@ -489,8 +525,12 @@ export interface NearbyConfirm {
489
525
 
490
526
  /** The payer's "Delivering…" step, while the radio carries the payment. */
491
527
  export interface NearbySending {
492
- /** Satoshis, or base units of `asset`. */
528
+ /** Satoshis on a BSV session; 0 on a token session, whose figure is `units` / `amountText`. */
493
529
  amount: number
530
+ /** Token session: exact base units of `asset`. */
531
+ units?: bigint
532
+ /** Token session: `units` formatted in `asset`. */
533
+ amountText?: string
494
534
  asset?: { ticker: string; decimals: number }
495
535
  recipient: { name: string; detail?: string }
496
536
  presence: { state: PresenceState; label: string } | null
@@ -502,7 +542,12 @@ export interface NearbyShowCode {
502
542
  code: (size: number) => React.ReactNode
503
543
  /** True when the code cycles through frames. */
504
544
  animated: boolean
545
+ /** Satoshis on a BSV session; 0 on a token session, whose figure is `units` / `amountText`. */
505
546
  amount: number
547
+ /** Token session: exact base units of `asset`. */
548
+ units?: bigint
549
+ /** Token session: `units` formatted in `asset`. */
550
+ amountText?: string
506
551
  asset?: { ticker: string; decimals: number }
507
552
  recipient: { name: string; detail?: string }
508
553
  presence: { state: PresenceState; label: string } | null
@@ -516,7 +561,7 @@ export interface NearbyShowCode {
516
561
 
517
562
  /** The payer's finish: the payment went. */
518
563
  export interface NearbyDone {
519
- /** Satoshis; with `amountText` set it's a token payment and that is the figure. */
564
+ /** Satoshis; 0 on a token payment, where `amountText` is the figure. */
520
565
  amount: number
521
566
  amountText?: string
522
567
  statusNote?: string
@@ -556,7 +601,8 @@ export interface NearbyFlowProps {
556
601
  * when one is — the session carries the asset alongside the figure, so the
557
602
  * two can never be read in the wrong unit downstream.
558
603
  */
559
- initialRequest?: { sats?: number; asset?: SessionAsset }
604
+ /** `units` is a token request's exact figure; `sats` a BSV one (or, from an older host, a token's units as a number). */
605
+ initialRequest?: { sats?: number; units?: bigint; asset?: SessionAsset }
560
606
  /** Where the post-payment overlay and an exited QR flow send the user. Defaults to `/`. */
561
607
  dismissTo?: DismissTarget
562
608
  /**
@@ -619,18 +665,6 @@ function NearbyFlow({
619
665
  * plain reason rather than paid in satoshis.
620
666
  */
621
667
  const mandala = useMandala()
622
- /**
623
- * COVER at hand-over (offline-settlement §1.2). The payee credits a token
624
- * frame only once every un-admitted ancestor in it is covered by the
625
- * evidence the frame itself carries; a frame that fails is refused exactly
626
- * like an unreadable one, because crediting money the issuer's overlay has
627
- * never vouched for is the mistake this whole evidence model exists to
628
- * prevent.
629
- *
630
- * The walk is the lib's, beside the overlay's own σ_I digest, and reaches
631
- * this screen through the runtime — `ui/` never imports `@bsv/mandala`.
632
- */
633
- const coverVerifier: CoverVerifier | null = mandala.runtime?.coverVerifier ?? null
634
668
 
635
669
  /**
636
670
  * Who to name in a token sentence. Best-effort and never load-bearing: an
@@ -677,8 +711,8 @@ function NearbyFlow({
677
711
  /**
678
712
  * Token mode: the figure in the asset's own units, and what is and is not
679
713
  * settled yet. Held apart from `settledAmount`, which is satoshis and on the
680
- * token path is always 1 (BRC-92) — rendering it would show "1" for every
681
- * token payment ever made.
714
+ * token path is always 0 — the output's 1 satoshi (BRC-92) rendered as the
715
+ * figure would show "1" for every token payment ever made.
682
716
  */
683
717
  const [settledTokenText, setSettledTokenText] = useState<string | null>(null)
684
718
  const [settledStatusNote, setSettledStatusNote] = useState<string | null>(null)
@@ -697,21 +731,6 @@ function NearbyFlow({
697
731
  /** True once the AWDL link has provably carried this session's frame. */
698
732
  const [linked, setLinked] = useState(false)
699
733
 
700
- /**
701
- * Connectivity, read through a ref.
702
- *
703
- * The only thing this screen asks about signal is whether a hand-over that
704
- * just landed should be followed by this device's own submit. Reading it from
705
- * a ref keeps a connectivity flap — which on a screen two people are pointing
706
- * at each other happens constantly — from re-creating the send callback that
707
- * a payer may be halfway through.
708
- */
709
- const online = useOnline()
710
- const onlineRef = useRef(online)
711
- useEffect(() => {
712
- onlineRef.current = online
713
- }, [online])
714
-
715
734
  /**
716
735
  * Whether this screen is still here.
717
736
  *
@@ -739,33 +758,65 @@ function NearbyFlow({
739
758
  * device holds a durable queue row before the overlay hears about any of it.
740
759
  * What is left is one best-effort call and one sentence.
741
760
  *
742
- * Never awaited by the caller and never able to fail a payment. Offline it is
743
- * not attempted at all — the drain owns every retry, and a face-to-face
744
- * payment is exactly the case where there may be no signal for hours. The
745
- * abort signal gates only the UI write: the settlement itself is a money
746
- * decision and is allowed to finish on a screen the payer has walked away
747
- * from.
761
+ * Never awaited by the caller and never able to fail a payment. It runs
762
+ * OFFLINE too, on purpose: `settleNow` names this hand-over to the module's
763
+ * settle, and the module persists that post-ACK intent before it submits
764
+ * anything (IC §2.3), so a later bare settle (the tick) retries it. Without
765
+ * the naming, the module never submits an own hand-over, and a payee who
766
+ * never submits would leave this payment unsettled for good. Offline the
767
+ * submit fails fast as `retry` and the receipt stays "settling". The abort
768
+ * signal gates only the UI write: the settlement itself is a money decision
769
+ * and is allowed to finish on a screen the payer has walked away from.
748
770
  */
749
771
  const settleAfterHandover = useCallback(
750
772
  async (txid: string, issuer: string, signal: AbortSignal): Promise<void> => {
751
773
  const runtime = mandala.runtime
752
- if (!runtime || !onlineRef.current) return
774
+ if (!runtime) return
775
+ let timer: ReturnType<typeof setTimeout> | undefined
753
776
  try {
754
- const state = await runtime.settleNow(txid)
777
+ // W5: the payee's positive ack is the ACK; this names the hand-over
778
+ // to the module's settle (post-ACK intent, IC §2.3). Raced against a
779
+ // timeout so a slow overlay only delays the sentence, never the
780
+ // payment; the settle itself keeps running, and the tick retries it.
781
+ const state = await Promise.race([
782
+ runtime.settleNow(txid),
783
+ new Promise<undefined>(resolve => {
784
+ timer = setTimeout(() => resolve(undefined), SETTLE_AFTER_HANDOVER_MS)
785
+ })
786
+ ])
755
787
  if (signal.aborted || !mountedRef.current) return
756
- // `admitted` is the issuer's overlay having folded this transaction
757
- // into its own state — the broadcast on top of it is bookkeeping — so
758
- // both read as settled, exactly as the activity list reads them.
759
- if (state === 'admitted' || state === 'broadcast') setSettledStatusNote(t('token_sent_settled', { issuer }))
788
+ // Only the overlay's verified admission reads as settled, exactly as
789
+ // the activity list reads it.
790
+ if (state === 'settled') setSettledStatusNote(t('token_sent_settled', { issuer }))
760
791
  } catch (e) {
761
792
  // The payment is made and the row is durable; this was only ever an
762
793
  // attempt to finish it early.
763
794
  console.warn('[localpay] could not settle the hand-over immediately:', e instanceof Error ? e.message : e)
795
+ } finally {
796
+ if (timer !== undefined) clearTimeout(timer)
764
797
  }
765
798
  },
766
799
  [mandala.runtime, t]
767
800
  )
768
801
 
802
+ /**
803
+ * The token half of every payer hold, park and release: the runtime's
804
+ * journal hook, which moves the payment's `color_transfers` row forward
805
+ * (plan 07 Task 15). With no runtime (torn down mid-payment) the hook
806
+ * fails, so `payerHold` keeps the queue row parked rather than treating a
807
+ * token payment as plain BSV.
808
+ */
809
+ const tokenHoldDeps = useCallback(
810
+ (): { onHandedOver: NearbyTokenDeps['onHandedOver'] } => ({
811
+ onHandedOver:
812
+ mandala.runtime?.nearby.onHandedOver ??
813
+ (async () => {
814
+ throw new Error('the token runtime is not available to journal this payment')
815
+ })
816
+ }),
817
+ [mandala.runtime]
818
+ )
819
+
769
820
  /**
770
821
  * The payee's `broadcast` flag for the shared success overlay (see the
771
822
  * `phase === 'done'` render below): whether storage already records a
@@ -1127,24 +1178,27 @@ function NearbyFlow({
1127
1178
  }
1128
1179
  let verified: VerifiedPayment
1129
1180
  try {
1130
- verified = await verifyFramePayment({ wallet, chainTracker }, frame, adminOriginator, {
1131
- // A token frame with no verifier is REFUSED, not credited: no
1132
- // verifier is no evidence, and verify.ts enforces that. Absent on a
1133
- // BSV request, where it is never read.
1134
- //
1135
- // `asset` is the session's OWN block — this device minted it — and is
1136
- // the trust anchor wire contract §9.10 requires: the frame's
1137
- // `overlayUrl`/`overlayIdentityKey` are data, and must equal it or
1138
- // the frame is refused before COVER ever runs.
1139
- ...(session.asset ? { cover: coverVerifier ?? undefined, asset: session.asset } : {})
1140
- })
1181
+ verified = await verifyFramePayment(
1182
+ { wallet, chainTracker },
1183
+ frame,
1184
+ adminOriginator,
1185
+ // The session's OWN asset — this device minted it — and this
1186
+ // device's own overlay key. A token frame is verified against both
1187
+ // (value output of this asset paying our `p color` key, evidence
1188
+ // that reaches σ by our K); the lib verifies it again online or by
1189
+ // COVER before the receipt is internalized. Absent on a BSV request,
1190
+ // where a token frame is refused for naming no asset.
1191
+ session.asset
1192
+ ? { assetId: session.asset.id, overlayIdentityKey: mandala.runtime?.endpoints.overlayIdentityKey }
1193
+ : undefined
1194
+ )
1141
1195
  } catch (e) {
1142
1196
  // `not_mine` is a frame that was never for this request; `unparseable`
1143
1197
  // is bytes that are not a transaction; `not_covered` is a token frame
1144
- // whose evidence does not cover its own ancestry; `root_unverified` is
1145
- // a block this device could not confirm (offline, headers behind). All
1146
- // four leave the request LIVE and unspent, exactly as a nonce mismatch
1147
- // does, so the genuine payer can still complete.
1198
+ // that does not carry the issuer's attested evidence; `root_unverified`
1199
+ // is a block this device could not confirm (offline, headers behind).
1200
+ // All four leave the request LIVE and unspent, exactly as a nonce
1201
+ // mismatch does, so the genuine payer can still complete.
1148
1202
  const kind = e instanceof FrameVerifyError ? e.kind : 'unparseable'
1149
1203
  void confirm?.(false, declineReasonFor(kind))
1150
1204
  if (kind === 'root_unverified') {
@@ -1181,10 +1235,10 @@ function NearbyFlow({
1181
1235
  setListenerEpoch(n => n + 1)
1182
1236
  return
1183
1237
  }
1184
- // Satoshis on the BSV path, base units of the session's asset on the
1185
- // token path. Every check below binds the figure the payee ASKED for to
1186
- // the figure that was actually locked, in whichever unit that is.
1187
- const satoshis = verified.kind === 'token' ? verified.amount : verified.satoshis
1238
+ // Satoshis on the BSV path, exact base units of the session's asset on
1239
+ // the token path. Every check below binds the figure the payee ASKED for
1240
+ // to the figure that was actually locked, in whichever unit that is —
1241
+ // `session.units` (bigint) for a token request, `session.amount` for BSV.
1188
1242
 
1189
1243
  // (0) Bind the frame to THIS session, before the one-shot latch and before
1190
1244
  // any write. Two distinct holes close here:
@@ -1212,7 +1266,10 @@ function NearbyFlow({
1212
1266
  //
1213
1267
  // Deliberately NOT terminal, and deliberately does NOT mark the session
1214
1268
  // spent: the request stays live so the genuine payer can still complete.
1215
- const amountDisagrees = session.amount !== undefined && satoshis !== session.amount
1269
+ const amountDisagrees =
1270
+ verified.kind === 'token'
1271
+ ? session.units !== undefined && verified.units !== session.units
1272
+ : session.amount !== undefined && verified.satoshis !== session.amount
1216
1273
  if (
1217
1274
  frame.derivationPrefix !== session.derivationPrefix ||
1218
1275
  frame.derivationSuffix !== session.derivationSuffix ||
@@ -1310,12 +1367,15 @@ function NearbyFlow({
1310
1367
  // failure. A payee who is told "failed" taps Retry, mints a fresh session,
1311
1368
  // and the payer builds a second createAction from different UTXOs: both
1312
1369
  // internalize, the payee is credited twice and the payer pays twice.
1313
- setSettledAmount(satoshis)
1370
+ // `settledAmount` is the satoshi-shaped figure the receipt draws only
1371
+ // when there is no `amountText`; on the token path the exact bigint
1372
+ // text below is the figure, and the number is never read for it.
1373
+ setSettledAmount(verified.kind === 'token' ? 0 : verified.satoshis)
1314
1374
  setSettledTokenText(
1315
- session.asset
1375
+ session.asset && verified.kind === 'token'
1316
1376
  ? // Never `null` on the token path: falling through to the satoshi
1317
1377
  // renderer would print base units as satoshis.
1318
- (formatTokenAmountWithUnit(satoshis, {
1378
+ (formatTokenAmountWithUnit(verified.units, {
1319
1379
  decimals: session.asset.decimals ?? 0,
1320
1380
  ticker: session.asset.ticker ?? ''
1321
1381
  }) ?? t('token_row_amount_pending'))
@@ -1323,7 +1383,8 @@ function NearbyFlow({
1323
1383
  )
1324
1384
  // Credited and spendable — and not yet confirmed by the issuer. Both are
1325
1385
  // true at this moment and the receipt says both, because a receipt that
1326
- // said only the first would be claiming a settlement nobody has.
1386
+ // said only the first would be claiming a settlement nobody has. It is
1387
+ // lifted below only when the journal reads `settled`.
1327
1388
  setSettledStatusNote(
1328
1389
  session.asset ? t('local_pay_token_not_cleared', { issuer: issuerNameFor(session.asset.id) }) : null
1329
1390
  )
@@ -1377,16 +1438,15 @@ function NearbyFlow({
1377
1438
  receivedVia: info.receivedVia
1378
1439
  })
1379
1440
  },
1380
- // A credited token frame's settlement row and evidence. Isolated
1381
- // inside processPending from the internalize itself, so a failing
1382
- // journal write can never un-credit a coin that is already ours.
1383
- mandala.runtime?.onTokenCredited,
1384
- // The same write, BEFORE the internalize. This is the path that
1385
- // actually needs it: a payee on Wi-Fi internalizing a frame from an
1386
- // offline payer triggers a forced broadcast inside `internalizeAction`,
1387
- // and the only thing that stops an unadmitted token going out there is
1388
- // the `token_settlements` row this hook writes first (§4.3 guard #2).
1389
- mandala.runtime?.onTokenHeld
1441
+ // How the receipt settled, for the `color_transfers` journal (held /
1442
+ // settled / refused). Isolated inside processPending from the credit
1443
+ // itself: a failing journal write can never un-credit a coin that is
1444
+ // already ours, and until it lands the missing row holds the tx from
1445
+ // broadcast (W1).
1446
+ mandala.runtime?.nearby.onReceived,
1447
+ // The lib's recipient path for a token frame (B7): verify, record
1448
+ // in the host ledger, then internalize the plain receipt.
1449
+ mandala.runtime?.nearby.accept
1390
1450
  )
1391
1451
  const credited = results.some(r => r.success)
1392
1452
  setNotice(
@@ -1397,6 +1457,18 @@ function NearbyFlow({
1397
1457
  // copy instead — the money is safe (still queued, will resolve on
1398
1458
  // the next retry) but not yet in the wallet.
1399
1459
  setReceivedVerification(credited ? 'verified' : 'not-credited')
1460
+ // The "not cleared by the issuer" copy stays unless the journal says
1461
+ // the overlay admitted it (`settled`). An unreadable journal keeps it:
1462
+ // a receipt must never claim a settlement nobody has.
1463
+ if (credited && session.asset && mandala.runtime) {
1464
+ try {
1465
+ const txid = Beef.fromBinary(frame.transaction).atomicTxid
1466
+ const row = txid ? await mandala.runtime.journal.get(txid) : undefined
1467
+ if (row?.role === 'received' && row.state === 'settled') setSettledStatusNote(null)
1468
+ } catch {
1469
+ // Keep the pending copy.
1470
+ }
1471
+ }
1400
1472
  // The success overlay is already up by this point (set unconditionally
1401
1473
  // at the top of this function) — this only refines its `broadcast`
1402
1474
  // flag once storage confirms a network hand-off. Not reachable when
@@ -1421,7 +1493,7 @@ function NearbyFlow({
1421
1493
  setReceivedVerification('not-credited')
1422
1494
  }
1423
1495
  },
1424
- [storage, wallet, adminOriginator, coverVerifier, issuerNameFor, mandala.runtime, fail, t]
1496
+ [storage, wallet, adminOriginator, issuerNameFor, mandala.runtime, fail, t]
1425
1497
  )
1426
1498
 
1427
1499
  // Read through refs so the listener effect below depends only on the session
@@ -1486,13 +1558,22 @@ function NearbyFlow({
1486
1558
  // ── Receive: mint the request ──
1487
1559
 
1488
1560
  const startRequest = useCallback(
1489
- async (requested?: number, asset?: SessionAsset) => {
1561
+ async (requested?: number | bigint, asset?: SessionAsset) => {
1490
1562
  // Zero (or blank) is the user asking the payer to choose, so it becomes an
1491
1563
  // open session rather than a rejected input. Undefined, never 0 — the codec
1492
1564
  // refuses a non-positive amount precisely so a corrupt zero can never be
1493
- // read back as "any amount".
1565
+ // read back as "any amount". A token request arrives as exact `bigint`
1566
+ // units and never passes through a number on its way to the session.
1494
1567
  const sats =
1495
- requested !== undefined && Number.isFinite(requested) && requested > 0 ? Math.round(requested) : undefined
1568
+ typeof requested === 'number' && Number.isFinite(requested) && requested > 0 ? Math.round(requested) : undefined
1569
+ const units =
1570
+ typeof requested === 'bigint'
1571
+ ? requested > 0n
1572
+ ? requested
1573
+ : undefined
1574
+ : sats !== undefined
1575
+ ? BigInt(sats)
1576
+ : undefined
1496
1577
  // Gate on storage too, not just the wallet. Advertising with storage null
1497
1578
  // means a payer can deliver a frame the payee then cannot persist, after the
1498
1579
  // transport has already acked it as accepted.
@@ -1532,10 +1613,11 @@ function NearbyFlow({
1532
1613
  const bleLive = bleNow === 'poweredOn' && blePermitted
1533
1614
  const session = mintSession({
1534
1615
  identityKey,
1535
- // Satoshis, or base units of `asset` — `isRequestableAmount` is
1536
- // unit-agnostic and the asset travels with the figure, so the payer
1537
- // can never read one as the other.
1538
- amount: sats,
1616
+ // Satoshis for BSV; base units of `asset` as exact `units` for a
1617
+ // token request (session v2 refuses a satoshi `amount` beside an
1618
+ // asset). The asset travels with the figure, so the payer can never
1619
+ // read one as the other.
1620
+ ...(asset ? { units } : { amount: sats }),
1539
1621
  asset,
1540
1622
  derivationPrefix,
1541
1623
  derivationSuffix,
@@ -1554,10 +1636,6 @@ function NearbyFlow({
1554
1636
  hints: capsFromProbe({ ...probe, bluetooth: bleHere ? bleNow : probe.bluetooth }),
1555
1637
  os: Platform.OS === 'ios' ? 'ios' : 'android'
1556
1638
  })
1557
- // Same reason as the payer's side: the drain re-derives this device's own
1558
- // settlement rows from sealed frames, and the key that opens them lives
1559
- // only here, for this process.
1560
- if (session.asset) rememberSessionPsk(session.psk)
1561
1639
  setRole('payee')
1562
1640
  setHostedSession(session)
1563
1641
  setPhase('receive_wait')
@@ -1619,11 +1697,6 @@ function NearbyFlow({
1619
1697
 
1620
1698
  /** The state moves that follow a valid session, whether scanned here or handed in. */
1621
1699
  const adoptSession = useCallback((session: Session) => {
1622
- // The payer's own sealed `offline_actions.framePayload` can only be
1623
- // re-opened by the settlement drain while this process still holds the
1624
- // session key — it is deliberately never written to disk. Remembered at
1625
- // the moment the session is adopted, before anything is built with it.
1626
- if (session.asset) rememberSessionPsk(session.psk)
1627
1700
  setScannedSession(session)
1628
1701
  // Prompt-free read of this device's Bluetooth state for describeFloor.
1629
1702
  // Never prepare() here: a payer who lands on QR must never be prompted.
@@ -1677,7 +1750,7 @@ function NearbyFlow({
1677
1750
  if (initialRole === 'payee' && initialRequest) {
1678
1751
  if (!permissionsSettled || mintedRef.current) return
1679
1752
  mintedRef.current = true
1680
- void startRequest(initialRequest.sats, initialRequest.asset)
1753
+ void startRequest(requestedFigure(initialRequest), initialRequest.asset)
1681
1754
  return
1682
1755
  }
1683
1756
  if (enteredRef.current) return
@@ -1700,7 +1773,7 @@ function NearbyFlow({
1700
1773
  abortAll()
1701
1774
  clearFlowState()
1702
1775
  if (initialRole === 'payee') {
1703
- if (initialRequest) void startRequest(initialRequest.sats, initialRequest.asset)
1776
+ if (initialRequest) void startRequest(requestedFigure(initialRequest), initialRequest.asset)
1704
1777
  else setPhase('receive_amount')
1705
1778
  } else if (initialSession) {
1706
1779
  adoptSession(initialSession)
@@ -1784,10 +1857,43 @@ function NearbyFlow({
1784
1857
  * mode there (`scannedAssetUnits`) and never emits anything else. 0 means
1785
1858
  * "not a usable amount yet" and keeps Send disabled.
1786
1859
  */
1860
+ const payUnits = useMemo(() => {
1861
+ if (!scannedSession?.asset) return 0n
1862
+ return scannedSession.units ?? unitsFrom(sendAmount)
1863
+ }, [scannedSession, sendAmount])
1864
+ /**
1865
+ * The satoshi figure: the BSV path's amount, and always 0 on a token
1866
+ * session. Token units are never converted to a number (above 2^53 that is
1867
+ * a different figure): the money path, every token display and the hosted
1868
+ * renderers' `units` / `amountText` read `payUnits`.
1869
+ */
1787
1870
  const payAmount = useMemo(() => {
1788
- if (!scannedSession) return 0
1871
+ if (!scannedSession || scannedSession.asset) return 0
1789
1872
  return scannedSession.amount ?? satsFrom(sendAmount)
1790
1873
  }, [scannedSession, sendAmount])
1874
+ /**
1875
+ * The figure the payee NAMED, or undefined for an open request: `units` on a
1876
+ * token session (session v2 carries no satoshi `amount` beside an asset),
1877
+ * `amount` on a BSV one. `fixedUnits` is the exact token figure every token
1878
+ * display uses; `fixedAmount` is the BSV satoshi figure and is undefined on
1879
+ * a token session (never a `Number()` of units). `hasFixedAmount` is the
1880
+ * one "did the payee name a figure" test for both.
1881
+ */
1882
+ const fixedUnits = scannedSession?.asset ? scannedSession.units : undefined
1883
+ const fixedAmount = scannedSession && !scannedSession.asset ? scannedSession.amount : undefined
1884
+ const hasFixedAmount = fixedUnits !== undefined || fixedAmount !== undefined
1885
+ /**
1886
+ * Token session: the figure being paid, formatted in the asset's unit, for
1887
+ * the hosted renderers. Undefined while the unit cannot be named
1888
+ * (`unitsUnknown`): a bare number at a guessed scale is not printed.
1889
+ */
1890
+ const payAmountText = useMemo(
1891
+ () =>
1892
+ scannedAssetUnits && !unitsUnknown
1893
+ ? (formatTokenAmountWithUnit(payUnits, scannedAssetUnits) ?? undefined)
1894
+ : undefined,
1895
+ [scannedAssetUnits, unitsUnknown, payUnits]
1896
+ )
1791
1897
 
1792
1898
  /**
1793
1899
  * The token receipt, once a hand-over is accepted — one writer for BOTH
@@ -1795,9 +1901,9 @@ function NearbyFlow({
1795
1901
  * carries where the radio shows "25.00 USDX".
1796
1902
  *
1797
1903
  * The figure is in the asset's own units (`built.tokenAmount`, the payment
1798
- * — never `built.satoshis`), and the settlement sentence is "settled" only
1799
- * when the ack already carried a verifying σ_I; otherwise "settling", which
1800
- * this payer's own immediate submit (if online) may still turn into
1904
+ * — never `built.satoshis`), and the settlement sentence opens as
1905
+ * "settling" (`alreadySettled` is false on both rails since W5), which
1906
+ * this payer's own immediate settle may still turn into
1801
1907
  * "settled" before the screen dismisses. That submit is taken now rather
1802
1908
  * than on the next drain tick (ux design §4.3 step 7), strictly AFTER the
1803
1909
  * positive ack and `finalizeDelivery`'s hold — the payee has the frame and
@@ -1808,10 +1914,11 @@ function NearbyFlow({
1808
1914
  * still runs to completion (see settleAfterHandover).
1809
1915
  */
1810
1916
  const writeTokenReceipt = useCallback(
1811
- (asset: SessionAsset, built: { txid?: string; tokenAmount?: number }, alreadySettled: boolean) => {
1917
+ (asset: SessionAsset, built: { txid?: string; tokenAmount?: bigint }, alreadySettled: boolean) => {
1812
1918
  const issuer = issuerNameFor(asset.id)
1813
1919
  setSettledTokenText(
1814
- formatTokenAmountWithUnit(built.tokenAmount ?? payAmount, scannedAssetUnits ?? assetUnits(asset)) ??
1920
+ // Exact: the payment's own bigint units, never through a number.
1921
+ formatTokenAmountWithUnit(built.tokenAmount ?? payUnits, scannedAssetUnits ?? assetUnits(asset)) ??
1815
1922
  t('token_row_amount_pending')
1816
1923
  )
1817
1924
  setSettledStatusNote(
@@ -1828,7 +1935,7 @@ function NearbyFlow({
1828
1935
  abortsRef.current.delete(controller)
1829
1936
  })
1830
1937
  },
1831
- [issuerNameFor, payAmount, scannedAssetUnits, peerName, settleAfterHandover, t]
1938
+ [issuerNameFor, payUnits, scannedAssetUnits, peerName, settleAfterHandover, t]
1832
1939
  )
1833
1940
 
1834
1941
  // ── Send: release an abandoned build ──
@@ -1845,7 +1952,7 @@ function NearbyFlow({
1845
1952
  // must not overwrite the real error already on screen.
1846
1953
 
1847
1954
  const abortBuild = useCallback(
1848
- (reference: string | undefined) => {
1955
+ (reference: string | undefined, tokenTxid?: string) => {
1849
1956
  if (!reference || !wallet) return
1850
1957
  void (async () => {
1851
1958
  try {
@@ -1864,9 +1971,17 @@ function NearbyFlow({
1864
1971
  ).catch(() => undefined)
1865
1972
  }
1866
1973
  }
1974
+ // A token build nobody received never moved money: its journal row
1975
+ // goes built → cancelled (a failed abort above is queued for replay,
1976
+ // and the abort guard allows a cancelled row).
1977
+ if (tokenTxid) {
1978
+ await mandala.runtime?.journal.advance(tokenTxid, ['built'], 'cancelled').catch((e: unknown) => {
1979
+ console.warn('[localpay] could not journal the released build:', messageOf(e))
1980
+ })
1981
+ }
1867
1982
  })()
1868
1983
  },
1869
- [wallet, adminOriginator, storage]
1984
+ [wallet, adminOriginator, storage, mandala.runtime]
1870
1985
  )
1871
1986
 
1872
1987
  /**
@@ -1890,7 +2005,7 @@ function NearbyFlow({
1890
2005
  if (!session || !sendKind) return
1891
2006
  // Guards the open-request path: with no figure there is nothing to build,
1892
2007
  // and buildPaymentFrame would refuse it anyway.
1893
- if (payAmount <= 0) return
2008
+ if (session.asset ? payUnits <= 0n : payAmount <= 0) return
1894
2009
  if (!wallet) {
1895
2010
  fail('generic', t('wallet_not_ready'))
1896
2011
  return
@@ -1932,13 +2047,9 @@ function NearbyFlow({
1932
2047
  storage,
1933
2048
  txid: built.txid,
1934
2049
  framePayload,
1935
- ...(session.asset
1936
- ? {
1937
- frame: built.frame,
1938
- onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
1939
- reference: built.reference
1940
- }
1941
- : {})
2050
+ // Token sessions only: the journal hook moves the payer's
2051
+ // `color_transfers` row built → parked (see `TokenHandoverDeps`).
2052
+ ...(session.asset ? tokenHoldDeps() : {})
1942
2053
  })
1943
2054
  } catch (e) {
1944
2055
  console.warn('[localpay] could not park an uncertain delivery:', e instanceof Error ? e.message : e)
@@ -1946,12 +2057,13 @@ function NearbyFlow({
1946
2057
  }
1947
2058
 
1948
2059
  // A token request this wallet is not set up for is refused before anything
1949
- // is built: v1 resolves one overlay, and paying a token whose issuer this
1950
- // device cannot reach would produce a frame nobody can settle.
2060
+ // is built: the asset must be one this wallet holds. The session names no
2061
+ // overlay (W6): the hand-over settles on THIS device's configured overlay,
2062
+ // so a request cannot steer it anywhere else.
1951
2063
  if (session.asset) {
1952
2064
  const runtime = mandala.runtime
1953
2065
  const known = (mandala.balances ?? []).find(b => b.asset.assetId === session.asset?.id)
1954
- if (!runtime || !known || known.asset.overlayIdentityKey !== session.asset.overlayIdentityKey) {
2066
+ if (!runtime || !known) {
1955
2067
  fail('generic', t('pay_asset_nearby_wrong_overlay'))
1956
2068
  return
1957
2069
  }
@@ -1968,13 +2080,12 @@ function NearbyFlow({
1968
2080
  wallet as unknown as PayingWalletArg,
1969
2081
  session,
1970
2082
  adminOriginator,
1971
- payAmount,
1972
- // The token half of the build: the payee lock (blinded A′, which no
1973
- // BRC-100 method can produce) and this device's evidence tables, for
1974
- // the AdmissionBundle the frame carries. Nothing is submitted here —
1975
- // hand-over comes first, unconditionally, so a face-to-face payment
1976
- // never waits on a network.
1977
- session.asset ? mandala.runtime?.tokenBuildDeps : undefined,
2083
+ session.asset ? payUnits : payAmount,
2084
+ // The token half of the build: the runtime's module hand-over, bound
2085
+ // to this session's remittance and journaled `built`. Nothing is
2086
+ // submitted here — hand-over comes first, unconditionally, so a
2087
+ // face-to-face payment never waits on a network.
2088
+ session.asset && mandala.runtime ? { handover: mandala.runtime.nearby.handover } : undefined,
1978
2089
  note,
1979
2090
  // XR-088: a build failure whose own release also fails used to be
1980
2091
  // logged only — no durable retry record at all — unlike the
@@ -2007,7 +2118,7 @@ function NearbyFlow({
2007
2118
  if (controller.signal.aborted) {
2008
2119
  // The user backed out or the screen blurred while "Delivering…" was up.
2009
2120
  // The frame was never handed to a transport and never rendered.
2010
- abortBuild(built.reference)
2121
+ abortBuild(built.reference, session.asset ? built.txid : undefined)
2011
2122
  return
2012
2123
  }
2013
2124
 
@@ -2019,7 +2130,7 @@ function NearbyFlow({
2019
2130
  // below share these bytes rather than sealing the frame twice.
2020
2131
  const sealed = sealFrame(built.frame, session.psk)
2021
2132
  if (sealed.length > MAX_MESSAGE_BYTES) {
2022
- abortBuild(built.reference)
2133
+ abortBuild(built.reference, session.asset ? built.txid : undefined)
2023
2134
  setPaymentQr(null)
2024
2135
  fail('generic', t('local_pay_too_large'))
2025
2136
  return
@@ -2116,33 +2227,10 @@ function NearbyFlow({
2116
2227
  await holdSentPaymentOffline({
2117
2228
  storage,
2118
2229
  txid,
2119
- // Token sessions only: the still-plaintext frame and the hook that
2120
- // journals it, so the payer's own settlement row survives a
2121
- // restart (see `TokenHandoverDeps`). The BSV rail has neither.
2122
- ...(session.asset
2123
- ? {
2124
- frame: built.frame,
2125
- onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
2126
- // The noSend action's own reference, onto the settlement row:
2127
- // it is what lets the abort guard tell a handed-over token
2128
- // payment from an abandoned one (core/mandala/abortGuard.ts).
2129
- reference: built.reference,
2130
- // XR-036: this rail acked over the radio and never sealed a
2131
- // QR, so unlike the QR/fallback paths it had no framePayload
2132
- // to give FIX G's re-derivation. Sealed here purely for local
2133
- // durability — never rendered — so a restart that loses the
2134
- // in-memory session PSK still has bytes to re-derive this
2135
- // settlement row from if the journal write below did not land.
2136
- ...(() => {
2137
- try {
2138
- return { framePayload: sealedToQr(sealFrame(built.frame, session.psk)) }
2139
- } catch (e) {
2140
- console.warn('[localpay] could not seal a fallback framePayload for the queue row:', e)
2141
- return {}
2142
- }
2143
- })()
2144
- }
2145
- : {})
2230
+ // Token sessions only: the journal hook moves the payer's
2231
+ // `color_transfers` row to handed_over before the queue row wakes
2232
+ // the drain (see `TokenHandoverDeps`). The BSV rail has none.
2233
+ ...(session.asset ? tokenHoldDeps() : {})
2146
2234
  })
2147
2235
  },
2148
2236
  queueFailedAbort: async reference => {
@@ -2199,15 +2287,19 @@ function NearbyFlow({
2199
2287
  storage,
2200
2288
  txid,
2201
2289
  framePayload: sealedToQr(sealFrame(built.frame, session.psk)),
2202
- ...(session.asset
2203
- ? {
2204
- frame: built.frame,
2205
- onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
2206
- reference: built.reference
2207
- }
2208
- : {})
2290
+ ...(session.asset ? tokenHoldDeps() : {})
2209
2291
  })
2210
- }
2292
+ },
2293
+ // Plan 07 Task 15: a decline whose inputs were released never moved
2294
+ // the money, so the token row is journaled cancelled (built →
2295
+ // cancelled; a parked or handed-over row is left alone).
2296
+ ...(session.asset
2297
+ ? {
2298
+ onReleased: async (txid: string) => {
2299
+ await mandala.runtime?.journal.advance(txid, ['built'], 'cancelled')
2300
+ }
2301
+ }
2302
+ : {})
2211
2303
  })
2212
2304
  if (controller.signal.aborted) return
2213
2305
 
@@ -2238,30 +2330,16 @@ function NearbyFlow({
2238
2330
  }
2239
2331
  // `built.satoshis` is the real amount the wallet locked into the output —
2240
2332
  // `payAmount` is only what was requested, and the two diverge under
2241
- // send-max (`payAmount` carries the sentinel). On the token path it is 1
2242
- // satoshi, per BRC-92, and `built.tokenAmount` is the payment.
2243
- setSettledAmount(built.satoshis)
2333
+ // send-max (`payAmount` carries the sentinel). On the token path the
2334
+ // figure is 0: the output's 1 satoshi (BRC-92) is not the payment,
2335
+ // `built.tokenAmount` is, and the receipt writer sets its text.
2336
+ setSettledAmount(session.asset ? 0 : built.satoshis)
2244
2337
  if (session.asset) {
2245
- // σ_I, if the recipient's drain already had it and sent it back — and
2246
- // only if it VERIFIES (FIX H). An unverified payload is treated as
2247
- // absent, never as proof and never as a decline, so the worst a forged
2248
- // ack can cost this payer is one idempotent submit by their own drain.
2249
- let admission
2250
- try {
2251
- const verify = mandala.runtime?.verifyAdmissionEntry
2252
- admission = verify
2253
- ? await readSettlementAck(ack, {
2254
- overlayIdentityKey: session.asset.overlayIdentityKey,
2255
- expectTxid: built.txid,
2256
- expectVout: built.frame.outputIndex,
2257
- verify
2258
- })
2259
- : undefined
2260
- } catch {
2261
- // Absent, like every other unreadable payload.
2262
- admission = undefined
2263
- }
2264
- writeTokenReceipt(session.asset, built, tokenSendState(admission) === 'sent-settled')
2338
+ // W5: the positive ack is the ACK. The receipt opens as "settling",
2339
+ // and `settleAfterHandover` (inside the writer) names this hand-over
2340
+ // to the module's settle; only a verified admission turns it to
2341
+ // "settled".
2342
+ writeTokenReceipt(session.asset, built, false)
2265
2343
  }
2266
2344
  setPhase('done')
2267
2345
  } finally {
@@ -2271,6 +2349,8 @@ function NearbyFlow({
2271
2349
  scannedSession,
2272
2350
  sendKind,
2273
2351
  payAmount,
2352
+ payUnits,
2353
+ tokenHoldDeps,
2274
2354
  note,
2275
2355
  writeTokenReceipt,
2276
2356
  wallet,
@@ -2335,6 +2415,7 @@ function NearbyFlow({
2335
2415
  // No handle (e.g. re-entry after reset, which clears builtRef and
2336
2416
  // scannedSession together): nothing to decide, just close.
2337
2417
  if (celebrate) {
2418
+ // Satoshis only: 0 on a token session (payAmount already is).
2338
2419
  setSettledAmount(payAmount)
2339
2420
  setRole('payer')
2340
2421
  setNotice(null)
@@ -2358,17 +2439,8 @@ function NearbyFlow({
2358
2439
  storage,
2359
2440
  txid: built.txid,
2360
2441
  framePayload,
2361
- // Token sessions only — see the hold callback below for why.
2362
- ...(session.asset
2363
- ? {
2364
- frame: built.frame,
2365
- onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
2366
- // The noSend action's own reference, onto the settlement row:
2367
- // it is what lets the abort guard tell a handed-over token
2368
- // payment from an abandoned one (core/mandala/abortGuard.ts).
2369
- reference: built.reference
2370
- }
2371
- : {})
2442
+ // Token sessions only: the journal row moves built → parked.
2443
+ ...(session.asset ? tokenHoldDeps() : {})
2372
2444
  })
2373
2445
  }
2374
2446
  } catch (e) {
@@ -2390,18 +2462,8 @@ function NearbyFlow({
2390
2462
  txid,
2391
2463
  framePayload,
2392
2464
  // Token sessions only: same reasoning as the executeSend hold call —
2393
- // the plaintext frame and the journal hook, so a restart does not
2394
- // strand this payer's settlement row.
2395
- ...(session.asset
2396
- ? {
2397
- frame: built.frame,
2398
- onTokenHandedOver: mandala.runtime?.onTokenHandedOver,
2399
- // The noSend action's own reference, onto the settlement row:
2400
- // it is what lets the abort guard tell a handed-over token
2401
- // payment from an abandoned one (core/mandala/abortGuard.ts).
2402
- reference: built.reference
2403
- }
2404
- : {})
2465
+ // the journal row moves to handed_over before the queue row wakes.
2466
+ ...(session.asset ? tokenHoldDeps() : {})
2405
2467
  })
2406
2468
  },
2407
2469
  queueFailedAbort: async reference => {
@@ -2422,15 +2484,15 @@ function NearbyFlow({
2422
2484
  if (celebrate) setNotice({ text: t('local_pay_broadcast_pending'), tone: 'warning' })
2423
2485
  }
2424
2486
  if (celebrate) {
2425
- setSettledAmount(built.satoshis)
2426
- // This rail has no ack payload to read σ_I from, so the receipt opens as
2427
- // "settling" and the writer's own submit is what may settle it.
2487
+ setSettledAmount(session.asset ? 0 : built.satoshis)
2488
+ // The receipt opens as "settling"; the writer's own settleNow is what
2489
+ // may settle it (W5: tapping Done is this rail's ACK).
2428
2490
  if (session.asset) writeTokenReceipt(session.asset, built, false)
2429
2491
  setRole('payer')
2430
2492
  setPhase('done')
2431
2493
  }
2432
2494
  },
2433
- [wallet, storage, adminOriginator, payAmount, scannedSession, paymentQr, mandala.runtime, writeTokenReceipt, t]
2495
+ [wallet, storage, adminOriginator, payAmount, scannedSession, paymentQr, tokenHoldDeps, writeTokenReceipt, t]
2434
2496
  )
2435
2497
 
2436
2498
  // ── Send: leave send_qr without Done ──
@@ -2550,8 +2612,8 @@ function NearbyFlow({
2550
2612
  * payment the build would have made; with no holding resolved yet there is
2551
2613
  * nothing to compare against and the build decides, as it always has.
2552
2614
  */
2553
- const overHolding = scannedHolding != null && payAmount > scannedHolding.baseUnits
2554
- const canSend = payAmount > 0 && !overHolding && !unitsUnknown
2615
+ const overHolding = scannedHolding != null && payUnits > scannedHolding.units
2616
+ const canSend = (scannedSession?.asset ? payUnits > 0n : payAmount > 0) && !overHolding && !unitsUnknown
2555
2617
  const scannerOpen = phase === 'send_scan' || phase === 'receive_scan'
2556
2618
 
2557
2619
  /**
@@ -2644,8 +2706,8 @@ function NearbyFlow({
2644
2706
  * units of a 2-decimal asset would render as "2,500 satoshis" and, in a fiat
2645
2707
  * display mode, as a dollar figure this wallet invented.
2646
2708
  */
2647
- const amountBlock = (amount: number, key?: string, units?: AmountInputAsset) => {
2648
- const tokenText = units ? formatTokenAmountWithUnit(amount, units) : null
2709
+ const amountBlock = (amount: number, key?: string, token?: { units: bigint; asset: AmountInputAsset }) => {
2710
+ const tokenText = token ? formatTokenAmountWithUnit(token.units, token.asset) : null
2649
2711
  return (
2650
2712
  <Animated.View key={key} entering={settleIn} style={styles.amountBlock}>
2651
2713
  <Text
@@ -2826,10 +2888,10 @@ function NearbyFlow({
2826
2888
  maxFontSizeMultiplier={1.4}
2827
2889
  numberOfLines={1}
2828
2890
  >
2829
- {hostedSession.amount === undefined ? (
2891
+ {(hostedSession.asset ? hostedSession.units : hostedSession.amount) === undefined ? (
2830
2892
  t('local_pay_any_amount')
2831
- ) : hostedSession.asset ? (
2832
- formatTokenAmountWithUnit(hostedSession.amount, {
2893
+ ) : hostedSession.asset && hostedSession.units !== undefined ? (
2894
+ formatTokenAmountWithUnit(hostedSession.units, {
2833
2895
  decimals: hostedSession.asset.decimals ?? 0,
2834
2896
  ticker: hostedSession.asset.ticker ?? ''
2835
2897
  })
@@ -2873,7 +2935,7 @@ function NearbyFlow({
2873
2935
  {/* A frame arrived that could not be credited. Advisory, not a
2874
2936
  failure: this session was deliberately NOT marked spent, so
2875
2937
  the pairing QR above is still live for the real payer. `notice`
2876
- (set only for a token frame that failed COVER) names the
2938
+ (set only for a token frame refused as not_covered) names the
2877
2939
  ISSUER's records as the reason — a specific true sentence beats
2878
2940
  the generic "wrong session" one, and must never read as a
2879
2941
  scanning mistake this device made (ux design §4.3). */}
@@ -2946,9 +3008,9 @@ function NearbyFlow({
2946
3008
  when the payee fixed it, or the live field when they left it open. */}
2947
3009
  {phase === 'send_confirm' && scannedSession && (
2948
3010
  <Animated.View entering={settleIn}>
2949
- {phaseTitle(scannedSession.amount === undefined ? t('local_pay_choose_amount') : t('local_pay_send'))}
3011
+ {phaseTitle(hasFixedAmount ? t('local_pay_send') : t('local_pay_choose_amount'))}
2950
3012
 
2951
- {scannedSession.amount === undefined ? (
3013
+ {!hasFixedAmount ? (
2952
3014
  <>
2953
3015
  {supportText(t('local_pay_enter_amount_send'))}
2954
3016
  <View style={styles.gapXl} />
@@ -2964,10 +3026,10 @@ function NearbyFlow({
2964
3026
  value={sendAmount}
2965
3027
  onChangeText={setSendAmount}
2966
3028
  asset={scannedAssetUnits}
2967
- maxValue={scannedHolding && !unitsUnknown ? String(scannedHolding.baseUnits) : undefined}
3029
+ maxValue={scannedHolding && !unitsUnknown ? String(scannedHolding.units) : undefined}
2968
3030
  availableText={
2969
3031
  scannedHolding && scannedAssetUnits && !unitsUnknown
2970
- ? (formatTokenAmount(scannedHolding.baseUnits, scannedAssetUnits.decimals) ?? undefined)
3032
+ ? (formatTokenAmount(scannedHolding.units, scannedAssetUnits.decimals) ?? undefined)
2971
3033
  : undefined
2972
3034
  }
2973
3035
  // No money chrome at all while the unit is unknown: an
@@ -2994,7 +3056,13 @@ function NearbyFlow({
2994
3056
  </Text>
2995
3057
  </Animated.View>
2996
3058
  ) : (
2997
- amountBlock(scannedSession.amount, undefined, scannedAssetUnits)
3059
+ amountBlock(
3060
+ fixedAmount ?? 0,
3061
+ undefined,
3062
+ scannedAssetUnits && fixedUnits !== undefined
3063
+ ? { units: fixedUnits, asset: scannedAssetUnits }
3064
+ : undefined
3065
+ )
2998
3066
  )}
2999
3067
  </View>
3000
3068
  <View style={styles.gapXl} />
@@ -3100,7 +3168,7 @@ function NearbyFlow({
3100
3168
  numberOfLines={1}
3101
3169
  >
3102
3170
  {scannedAssetUnits ? (
3103
- formatTokenAmountWithUnit(payAmount, scannedAssetUnits)
3171
+ formatTokenAmountWithUnit(payUnits, scannedAssetUnits)
3104
3172
  ) : (
3105
3173
  <AmountDisplay>{payAmount}</AmountDisplay>
3106
3174
  )}
@@ -3400,11 +3468,21 @@ function NearbyFlow({
3400
3468
  render={renderPayer.confirm}
3401
3469
  value={{
3402
3470
  session: scannedSession,
3403
- fixedAmount: scannedSession.amount,
3471
+ fixedAmount,
3404
3472
  amount: payAmount,
3405
- setAmount: units => setSendAmount(units !== undefined && units > 0 ? String(Math.round(units)) : ''),
3473
+ ...(scannedSession.asset ? { fixedUnits, units: payUnits, amountText: payAmountText } : {}),
3474
+ setAmount: amount =>
3475
+ setSendAmount(
3476
+ typeof amount === 'bigint'
3477
+ ? amount > 0n
3478
+ ? amount.toString()
3479
+ : ''
3480
+ : amount !== undefined && amount > 0
3481
+ ? String(Math.round(amount))
3482
+ : ''
3483
+ ),
3406
3484
  asset: scannedAssetUnits,
3407
- holding: scannedHolding && !unitsUnknown ? scannedHolding.baseUnits : undefined,
3485
+ holding: scannedHolding && !unitsUnknown ? scannedHolding.units : undefined,
3408
3486
  note,
3409
3487
  setNote,
3410
3488
  recipient: payerRecipient,
@@ -3436,7 +3514,13 @@ function NearbyFlow({
3436
3514
  node: (
3437
3515
  <Hosted
3438
3516
  render={renderPayer.sending}
3439
- value={{ amount: payAmount, asset: scannedAssetUnits, recipient: payerRecipient, presence }}
3517
+ value={{
3518
+ amount: payAmount,
3519
+ ...(scannedSession?.asset ? { units: payUnits, amountText: payAmountText } : {}),
3520
+ asset: scannedAssetUnits,
3521
+ recipient: payerRecipient,
3522
+ presence
3523
+ }}
3440
3524
  />
3441
3525
  )
3442
3526
  }
@@ -3449,6 +3533,7 @@ function NearbyFlow({
3449
3533
  code: size => <PaymentQrDisplay frameQr={paymentQr} size={size} onError={onPaymentQrError} />,
3450
3534
  animated: paymentQrBlocks > 1,
3451
3535
  amount: payAmount,
3536
+ ...(scannedSession?.asset ? { units: payUnits, amountText: payAmountText } : {}),
3452
3537
  asset: scannedAssetUnits,
3453
3538
  recipient: payerRecipient,
3454
3539
  presence,