@bsv/expo-wallet-toolbox 0.20.0 → 0.22.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 (85) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +78 -13
  3. package/core/contacts/contactActivity.ts +48 -28
  4. package/core/contacts/contactsStore.ts +2 -2
  5. package/core/context/WalletContext.tsx +166 -219
  6. package/core/demo/demoAssets.ts +8 -10
  7. package/core/demo/demoLedger.ts +32 -38
  8. package/core/demo/demoMandalaRuntime.ts +67 -49
  9. package/core/demo/index.ts +1 -1
  10. package/core/directpay/DirectPayManager.ts +148 -29
  11. package/core/directpay/DirectPayProvider.tsx +11 -2
  12. package/core/directpay/payFlow.ts +10 -1
  13. package/core/directpay/settings.ts +56 -9
  14. package/core/directpay/types.ts +11 -2
  15. package/core/directpay/webrtpay.ts +4 -0
  16. package/core/i18n/translations.tsx +185 -84
  17. package/core/index.ts +55 -37
  18. package/core/localpay/build.ts +110 -569
  19. package/core/localpay/codec.ts +190 -93
  20. package/core/localpay/pending.ts +217 -202
  21. package/core/localpay/session.ts +99 -25
  22. package/core/localpay/types.ts +6 -5
  23. package/core/localpay/verify.ts +118 -173
  24. package/core/mandala/abortGuard.ts +97 -120
  25. package/core/mandala/accessPolicy.ts +133 -0
  26. package/core/mandala/assets.ts +370 -0
  27. package/core/mandala/colorGuard.ts +178 -0
  28. package/core/mandala/colorModule.ts +82 -0
  29. package/core/mandala/createRuntime.ts +483 -2392
  30. package/core/mandala/handle.ts +694 -0
  31. package/core/mandala/kvStore.ts +105 -0
  32. package/core/mandala/nearby.ts +185 -0
  33. package/core/mandala/receipt.ts +121 -0
  34. package/core/mandala/runtime.ts +166 -312
  35. package/core/mandala/settle.ts +540 -0
  36. package/core/mandala/transferJournal.ts +395 -0
  37. package/core/mandala/types.ts +61 -311
  38. package/core/networks.ts +5 -5
  39. package/core/offline/cancelParked.ts +80 -63
  40. package/core/offline/payerHold.ts +52 -118
  41. package/core/parsePeerPayURI.ts +25 -12
  42. package/core/pay/rails/direct.ts +6 -2
  43. package/core/pay/rails/handle.ts +15 -14
  44. package/core/pay/rails/index.ts +5 -3
  45. package/core/pay/rails/nearby.ts +25 -87
  46. package/core/profiles/assertProfileEmpty.ts +19 -10
  47. package/core/services/vault/guard.ts +5 -4
  48. package/core/storage/StorageExpoSQLite.ts +93 -229
  49. package/core/storage/methods/processOfflineActions.ts +86 -136
  50. package/core/storage/schema/createTables.ts +9 -184
  51. package/package.json +6 -5
  52. package/ui/components/pay/AssetPicker.tsx +2 -2
  53. package/ui/components/pay/HandleReceive.tsx +10 -4
  54. package/ui/components/pay/NearbyFlow.tsx +324 -239
  55. package/ui/components/pay/RequestHub.tsx +10 -0
  56. package/ui/components/pay/UniversalSend.tsx +31 -28
  57. package/ui/components/pay/useRecipientInput.ts +2 -2
  58. package/ui/components/ui/PermissionSheet.tsx +94 -160
  59. package/ui/components/ui/colorPrompt.ts +236 -0
  60. package/ui/components/wallet/AmountInput.tsx +9 -6
  61. package/ui/components/wallet/AssetAmount.tsx +6 -6
  62. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  63. package/ui/components/wallet/Balance.tsx +3 -1
  64. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  65. package/ui/components/wallet/tokenEviction.ts +9 -9
  66. package/ui/hooks/useMandala.ts +6 -6
  67. package/ui/hooks/useSpendableBalance.ts +3 -1
  68. package/ui/importDatabases.ts +1 -1
  69. package/ui/screens/PayScreen.tsx +14 -20
  70. package/ui/screens/SettingsScreen.tsx +3 -1
  71. package/ui/screens/WalletCheckScreen.tsx +7 -2
  72. package/ui/screens/WalletHomeScreen.tsx +40 -14
  73. package/ui/screens/tokenRowTitle.ts +28 -15
  74. package/ui/tokenFormat.ts +133 -69
  75. package/ui/tokenStatus.ts +5 -8
  76. package/core/localpay/settlementAck.ts +0 -155
  77. package/core/mandala/basketMigration.ts +0 -166
  78. package/core/mandala/bundle.ts +0 -244
  79. package/core/mandala/drain.ts +0 -754
  80. package/core/mandala/inboxPrehold.ts +0 -193
  81. package/core/mandala/permissionModule.ts +0 -931
  82. package/core/mandala/resendTransfer.ts +0 -178
  83. package/core/mandala/settlementStore.ts +0 -434
  84. package/core/mandala/token.ts +0 -45
  85. package/core/offline/tokenFrames.ts +0 -197
@@ -1,39 +1,16 @@
1
- import {
2
- Beef,
3
- Hash,
4
- P2PKH,
5
- PublicKey,
6
- Signature,
7
- Transaction,
8
- TransactionSignature,
9
- UnlockingScript,
10
- Utils
11
- } from '@bsv/sdk'
12
- import { MandalaToken } from '../mandala/token'
1
+ import { P2PKH, PublicKey, Transaction } from '@bsv/sdk'
13
2
  import { FRAME_VERSION, type PaymentFrame } from './codec'
14
- import { isRequestableAmount, type Session } from './session'
3
+ import { isRequestableAmount, isRequestableUnits, type Session } from './session'
15
4
  import { PEERPAY_LABEL, PEERPAY_PROTOCOL_ID } from './pending'
16
- import { FT_PROTOCOL_ID } from './verify'
17
5
  import type { Ack } from './types'
18
- import { MANDALA_ACTION_LABEL, MANDALA_BASKET, assembleBundle, type BundleStore } from '../mandala/bundle'
19
- // XR-037: bundle.ts's MANDALA_ACTION_LABEL ('mandala') is the home-screen
20
- // row-recognition label; permissionModule.ts exports a DIFFERENT constant
21
- // under the SAME name ('p mandala token-spend') — the only label that
22
- // P-routes a listActions query to MandalaTokenModule's consent gate (label
23
- // routing is listActions' only signal; the shared 'p mandala' BASKET does
24
- // not make listActions route here). A real token action must carry both.
25
- import { MANDALA_ACTION_LABEL as MANDALA_TOKEN_SPEND_LABEL } from '../mandala/permissionModule'
6
+ import { handoverMismatch } from '../mandala/nearby'
7
+ import { tokenPaymentOfHandover } from '../mandala/receipt'
8
+ import type { NearbyTokenDeps } from '../mandala/runtime'
26
9
  import { getOnline } from '../net/online'
27
10
 
28
11
  /** The toolbox's per-txid verdict on a `sendWith` release. */
29
12
  type SendWithStatus = 'unproven' | 'sending' | 'failed'
30
13
 
31
- interface ListOutputsOutcome {
32
- totalOutputs?: number
33
- outputs: { outpoint: string; satoshis?: number; spendable?: boolean; customInstructions?: string }[]
34
- BEEF?: number[]
35
- }
36
-
37
14
  interface CreateActionOutcome {
38
15
  tx?: number[]
39
16
  txid?: string
@@ -45,15 +22,6 @@ interface PayingWallet {
45
22
  getPublicKey(args: unknown, originator?: string): Promise<{ publicKey: string }>
46
23
  createAction(args: unknown, originator?: string): Promise<CreateActionOutcome>
47
24
  signAction(args: unknown, originator?: string): Promise<{ tx?: number[]; txid?: string }>
48
- /**
49
- * Token path only. Present on every BRC-100 wallet; optional here so the BSV
50
- * path's callers and its tests are unchanged by the token path's existence.
51
- */
52
- listOutputs?(args: unknown, originator?: string): Promise<ListOutputsOutcome>
53
- /** Token path only: signs each selected token input (BRC-100 `createSignature`). */
54
- createSignature?(args: unknown, originator?: string): Promise<{ signature: number[] }>
55
- /** Token path only: mints the overlay-verifier linkage for inputs and change. */
56
- revealSpecificKeyLinkage?(args: unknown, originator?: string): Promise<unknown>
57
25
  /**
58
26
  * Releases the inputs a `noSend` action is holding. Required, not optional:
59
27
  * without it an abandoned build locks `amount + fee` in the payer's wallet
@@ -101,86 +69,27 @@ export interface BuiltPayment {
101
69
  */
102
70
  satoshis: number
103
71
  /**
104
- * Base units of the asset locked to the payee, on the token path only.
72
+ * Base units of the asset locked to the payee, on the token path only,
73
+ * exact (1..2^64-1).
105
74
  *
106
75
  * A token output carries 1 satoshi and the real figure in its script, so a
107
76
  * caller that rendered `satoshis` as "amount sent" for a token payment would
108
77
  * show "1" for every payment ever made. Undefined on the BSV path, where
109
78
  * `satoshis` IS the payment.
110
79
  */
111
- tokenAmount?: number
112
- }
113
-
114
- /** One token coin in the payer's basket, with what it takes to spend it. */
115
- export interface SelectedTokenCoin {
116
- /** "<txid>.<vout>" */
117
- outpoint: string
118
- /** Base units carried by the script, not satoshis. */
119
- amount: number
120
- /** BRC-42 keyID this coin was locked under, from its customInstructions. */
121
- keyID: string
122
- /** BRC-42 counterparty this coin was locked under. */
123
- counterparty: string
80
+ tokenAmount?: bigint
124
81
  }
125
82
 
126
83
  /**
127
- * The D2 blinding seam.
128
- *
129
- * A′ = A + rG: the payee derives against a BLINDED sender key and so cannot
130
- * join this payer's later payments to each other. That arithmetic needs the
131
- * payer's own scalar, which no BRC-100 method exposes — it lives in
132
- * `@bsv/mandala` beside the rest of the token pipeline. It is injected rather
133
- * than approximated here, and it is REQUIRED rather than defaulted: a
134
- * silent fall-back to an unblinded BRC-29 lock would still produce a working
135
- * payment, which is exactly why it would never be noticed.
84
+ * What the token path needs beyond an ordinary BSV build: the runtime's
85
+ * `nearby.handover`, which builds, funds and signs the hand-over through the
86
+ * color module (lib `sendHandover`) and journals it `built` (plan 07 Task 15).
87
+ * The wallet itself selects no coins, signs no token input and mints no
88
+ * linkage; the module does all of it, which is what the payee's §7.1 receipt
89
+ * then proves.
136
90
  */
137
- export type LockToPayee = (args: {
138
- assetId: string
139
- amount: number
140
- /** The payee's identity key, from the session. */
141
- recipientKey: string
142
- /** The session's own nonces, `"<prefix> <suffix>"` — what binds frame to request. */
143
- keyID: string
144
- }) => Promise<{
145
- lockingScript: string
146
- /** A′ — what goes on the wire as `frame.senderIdentityKey`. */
147
- senderIdentityKey: string
148
- /** The overlay-verifier SpecificLinkage for this output (k for S′, not S). */
149
- linkage: unknown
150
- customInstructions?: string
151
- }>
152
-
153
- /** What the token path needs beyond an ordinary BSV build. */
154
91
  export interface TokenBuildDeps {
155
- /** Read side of this device's settlement tables, for the AdmissionBundle. */
156
- store: BundleStore
157
- lockToPayee: LockToPayee
158
- /**
159
- * Promotes a `lockToPayee` blinding reservation to the frame's tip txid once
160
- * the transaction is signed (nearby blinding, offline-settlement design):
161
- * `lockToPayee` mints r and reserves it under the session's own `keyID`
162
- * before a txid exists; this call moves that reservation to the real txid
163
- * once one does. Optional so the BSV path's callers and tests are
164
- * unaffected — omitting it just leaves the reservation for the drain's own
165
- * `pruneBlindingReservations` sweep instead of promoting it, which costs
166
- * this device's own later recovery of r but never the payment itself.
167
- */
168
- commitBlinding?: (keyID: string, txid: string) => Promise<void>
169
- /** Defaults to `MANDALA_BASKET`. */
170
- basket?: string
171
- /** Opaque serialized VerifiableCertificates to carry, if the asset needs any. */
172
- certificates?: Uint8Array[]
173
- /**
174
- * This device's own configured overlay for the asset (XR-104), never the
175
- * payee's. `buildTokenPaymentFrame` anchors `session.asset`'s
176
- * overlayIdentityKey/overlayUrl — the payee's own claim, decoded off the
177
- * wire — to these before selecting a coin or revealing any linkage, so a
178
- * scanned request cannot direct `revealSpecificKeyLinkage`'s
179
- * SpecificKeyLinkage disclosure to a verifier of its own choosing. Required
180
- * so the check cannot be silently skipped by a caller that forgets to set it.
181
- */
182
- overlayIdentityKey: string
183
- overlayUrl: string
92
+ handover: NearbyTokenDeps['handover']
184
93
  }
185
94
 
186
95
  /**
@@ -194,41 +103,6 @@ export type DeliveryOutcome =
194
103
  | { kind: 'sent'; broadcast: 'ok' | 'pending'; detail?: string }
195
104
  | { kind: 'declined'; reason?: string }
196
105
 
197
- /**
198
- * Picks the coins to spend: largest first, fewest UTXOs.
199
- *
200
- * Fewest inputs is not an aesthetic preference — every token input adds its own
201
- * ancestor to the BEEF the frame carries and its own linkage reveal to the
202
- * payload, and the sealed frame has a hard 64 KiB ceiling on the radios. A
203
- * selection that took ten small coins where one large one would do can push an
204
- * otherwise ordinary payment past the wire limit.
205
- *
206
- * Throws rather than under-funding: a transaction that moves less than the
207
- * payee asked for is not a smaller payment, it is a broken one.
208
- */
209
- export function selectTokenCoins(
210
- coins: SelectedTokenCoin[],
211
- amount: number
212
- ): { selected: SelectedTokenCoin[]; total: number } {
213
- if (!isRequestableAmount(amount)) {
214
- throw new Error('amount must be a positive whole number of base units')
215
- }
216
- const sorted = [...coins].sort((a, b) => b.amount - a.amount)
217
- // An exact or single-coin cover is both the smallest input set and the
218
- // smallest frame, so prefer the smallest coin that covers the whole amount.
219
- const single = [...sorted].reverse().find(c => c.amount >= amount)
220
- if (single) return { selected: [single], total: single.amount }
221
-
222
- const selected: SelectedTokenCoin[] = []
223
- let total = 0
224
- for (const coin of sorted) {
225
- selected.push(coin)
226
- total += coin.amount
227
- if (total >= amount) return { selected, total }
228
- }
229
- throw new Error(`insufficient token balance: have ${total}, need ${amount}`)
230
- }
231
-
232
106
  /**
233
107
  * Builds the frame a payer sends. BRC-29: the output locks to a key derived
234
108
  * for the payee from the session's derivation nonces.
@@ -250,7 +124,12 @@ export async function buildPaymentFrame(
250
124
  wallet: PayingWallet,
251
125
  session: Session,
252
126
  originator: string,
253
- amount: number,
127
+ /**
128
+ * Satoshis (a safe integer) on a BSV session; exact base units (a bigint,
129
+ * 1..2^64-1) on a token session — `session.units` when the payee named a
130
+ * figure. A value of the other kind is refused, never converted.
131
+ */
132
+ amount: number | bigint,
254
133
  /**
255
134
  * Required when — and only when — the session names an asset. A token
256
135
  * request with no deps is refused rather than silently paid in satoshis:
@@ -273,17 +152,29 @@ export async function buildPaymentFrame(
273
152
  */
274
153
  queueFailedAbort?: (reference: string) => Promise<void>
275
154
  ): Promise<BuiltPayment> {
276
- if (!isRequestableAmount(amount)) {
277
- throw new Error('amount must be a positive whole number of satoshis')
278
- }
279
155
  if (session.asset) {
156
+ if (!isRequestableUnits(amount)) {
157
+ throw new Error('a token amount must be a whole number of base units from 1 to 18446744073709551615')
158
+ }
280
159
  if (!token) {
281
- throw new Error('a token session needs token build deps (store + lockToPayee)')
160
+ throw new Error('a token session needs token build deps (the runtime’s nearby.handover)')
282
161
  }
283
- if (session.amount !== undefined && session.amount !== amount) {
162
+ if (session.units !== undefined && session.units !== amount) {
284
163
  throw new Error('amount does not match the payee’s request')
285
164
  }
286
- return buildTokenPaymentFrame(wallet, session, session.asset, originator, amount, token, note, queueFailedAbort)
165
+ return await buildTokenPaymentFrame(
166
+ wallet,
167
+ session,
168
+ session.asset,
169
+ originator,
170
+ amount,
171
+ token,
172
+ note,
173
+ queueFailedAbort
174
+ )
175
+ }
176
+ if (!isRequestableAmount(amount)) {
177
+ throw new Error('amount must be a positive whole number of satoshis')
287
178
  }
288
179
  // A payee that named a figure is stating a binding term of the request, and
289
180
  // its settle path refuses anything else. Catching the disagreement here — on
@@ -438,445 +329,77 @@ async function releasingOnFailure<T>(
438
329
  }
439
330
 
440
331
  /**
441
- * The payer's token build (offline-settlement spec §9, steps 4–5).
442
- *
443
- * Structurally the same shape as the BSV path — select, create `noSend`, sign,
444
- * hand over — with two differences that are the whole point of the revision:
445
- *
446
- * 1. The frame carries an ADMISSION BUNDLE: σ_I for every ancestor this device
447
- * can prove the overlay admitted, and the linkage payload for every one it
448
- * cannot, including the tip's own. That is what lets the payee decide,
449
- * offline, whether the coin it is being handed is real.
450
- * 2. Nothing is submitted. Not to the overlay, not to the network. The payer
451
- * hands over and stops; the recipient submits (rule 3) and this device's own
452
- * drain submits too, optionally, whenever it next reconnects (rule 6).
453
- * Submitting first would put a face-to-face payment behind a network round
454
- * trip, and broadcasting first would put an unadmitted token transaction on
455
- * chain — which the overlay can then only refuse.
456
- *
457
- * `randomizeOutputs` is off, as on the BSV path, so the payee's output is index
458
- * 0 and the frame can name it. The mandala handle rail shuffles instead, to hide
459
- * which output is the recipient's from a chain observer; that buys nothing here,
460
- * where the payee is standing in front of the payer and already knows its own
461
- * script.
462
- */
463
- /**
464
- * How many basket outputs one `listOutputs` page asks for.
465
- *
466
- * BRC-100's default `limit` is TEN. Coin selection was reading that one default
467
- * page and calling it the wallet's balance: a payer holding twelve coins whose
468
- * eleventh and twelfth were the ones that covered the amount got
469
- * `insufficient token balance` for money it plainly had — worse, the figure in
470
- * the message was a partial total, so it read as a wallet bug rather than a
471
- * paging bug. A thousand is high enough that the loop below is one round trip
472
- * for any realistic basket and low enough not to drag a whole basket's BEEF
473
- * through one response.
474
- */
475
- const TOKEN_LIST_PAGE = 1000
476
-
477
- /**
478
- * Hard stop on the paging loop.
332
+ * The payer's token build (plan 07 Task 15): one module hand-over, framed.
479
333
  *
480
- * `totalOutputs` is the wallet's own count, and the loop also stops on a short
481
- * or empty page — but a wallet that reports a total it never serves (or serves
482
- * the same page forever) must not spin a payment screen. A million outputs is
483
- * far past any real basket.
484
- */
485
- const TOKEN_LIST_MAX_PAGES = 1000
486
-
487
- /**
488
- * Every output of the token basket, page by page, merging each page's BEEF into
489
- * `into` as it goes.
334
+ * The runtime's `nearby.handover` builds, funds and signs the hand-over
335
+ * `noSend` through the color module, with the session's own remittance
336
+ * strings, and journals it `built` before returning. This function never
337
+ * creates, signs, broadcasts or submits anything itself: hand-over comes
338
+ * first, unconditionally, so a face-to-face payment never waits on a network,
339
+ * and settlement is `settleNow` after the payee's positive ack (W5).
490
340
  *
491
- * The BEEF accumulates across pages on purpose: an output's value lives in its
492
- * source transaction's script, so a coin from page two is unreadable — silently
493
- * skipped by the caller's `if (!script) continue` — unless page two's
494
- * transactions are merged before it is examined.
341
+ * What it does check is binding. The hand-over must carry the session's
342
+ * asset and remittance strings and pay output 0, because the frame names
343
+ * output 0 and the payee derives its key from those very strings. The
344
+ * runtime checks the same thing before journaling; this is the second,
345
+ * independent check at the one place the frame is assembled. A mismatch
346
+ * releases the signed action (nobody has its bytes) and throws.
495
347
  */
496
- async function* listTokenBasket(
497
- wallet: PayingWallet,
498
- basket: string,
499
- originator: string,
500
- into: Beef
501
- ): AsyncGenerator<ListOutputsOutcome['outputs'][number]> {
502
- let offset = 0
503
- for (let page = 0; page < TOKEN_LIST_MAX_PAGES; page++) {
504
- const listed = await wallet.listOutputs!(
505
- {
506
- basket,
507
- include: 'entire transactions',
508
- includeCustomInstructions: true,
509
- limit: TOKEN_LIST_PAGE,
510
- offset
511
- },
512
- originator
513
- )
514
- if (listed.BEEF) into.mergeBeef(listed.BEEF)
515
- const outputs = listed.outputs ?? []
516
- for (const out of outputs) yield out
517
- // An empty page always ends it — that, plus the page ceiling, is what keeps
518
- // a wallet that ignores `offset` from looping forever.
519
- if (outputs.length === 0) return
520
- offset += outputs.length
521
- if (typeof listed.totalOutputs === 'number') {
522
- // The wallet's own count is the authority when it reports one. A SHORT
523
- // page must not end the loop here: a wallet is free to cap `limit` below
524
- // what was asked for, and treating its cap as "end of basket" would
525
- // re-introduce the very truncation this loop exists to fix.
526
- if (offset >= listed.totalOutputs) return
527
- } else if (outputs.length < TOKEN_LIST_PAGE) {
528
- // No count to go by, so a short page is the only end-of-basket signal
529
- // there is.
530
- return
531
- }
532
- }
533
- }
534
-
535
348
  async function buildTokenPaymentFrame(
536
349
  wallet: PayingWallet,
537
350
  session: Session,
538
351
  asset: NonNullable<Session['asset']>,
539
352
  originator: string,
540
- amount: number,
353
+ units: bigint,
541
354
  deps: TokenBuildDeps,
542
355
  note?: string,
543
356
  /** XR-088: see `buildPaymentFrame`'s own doc for this same parameter. */
544
357
  queueFailedAbort?: (reference: string) => Promise<void>
545
358
  ): Promise<BuiltPayment> {
546
- if (!wallet.listOutputs) throw new Error('this wallet cannot list token outputs')
547
- if (!wallet.createSignature) throw new Error('this wallet cannot sign token inputs')
548
- if (!wallet.revealSpecificKeyLinkage) throw new Error('this wallet cannot reveal token linkage')
549
-
550
- // XR-104: `asset` is `session.asset` — the PAYEE's own claim, decoded off
551
- // the wire with no anchor of its own. Refuse before any coin is selected,
552
- // any output built, or any linkage revealed: NearbyFlow's own comparison
553
- // (its sole production caller) already refuses this case, but this
554
- // exported, documented-single-import-site function must not depend on an
555
- // upstream caller remembering to check first.
556
- if (asset.overlayIdentityKey !== deps.overlayIdentityKey || asset.overlayUrl !== deps.overlayUrl) {
557
- throw new Error('token asset overlay does not match this device’s configured overlay')
558
- }
559
-
560
- const basket = deps.basket ?? MANDALA_BASKET
561
- const keyID = `${session.derivationPrefix} ${session.derivationSuffix}`
562
-
563
- // `include: 'entire transactions'` is not an optimisation: the amount a token
564
- // output carries lives in its SCRIPT, not in `satoshis`, so the coins cannot
565
- // even be valued without their source transactions — and the same BEEF is
566
- // what the payee will walk to prove the chain.
567
- const sourceBeef = new Beef()
568
- const coins: SelectedTokenCoin[] = []
569
- for await (const out of listTokenBasket(wallet, basket, originator, sourceBeef)) {
570
- if (out.spendable === false) continue
571
- const [txid, voutText] = out.outpoint.split('.')
572
- const source = sourceBeef.findTxid(txid)?.tx
573
- const script = source?.outputs[Number(voutText)]?.lockingScript
574
- if (!script) continue
575
- let decoded: { assetId: string; amount: number }
576
- try {
577
- decoded = MandalaToken.decode(script)
578
- } catch {
579
- continue // a stray non-token output in the basket is not this asset's coin
580
- }
581
- if (decoded.assetId !== asset.id) continue
582
- const ci = parseCustomInstructions(out.customInstructions)
583
- coins.push({
584
- outpoint: out.outpoint,
585
- amount: decoded.amount,
586
- keyID: ci.keyID ?? '',
587
- counterparty: ci.counterparty ?? 'self'
588
- })
589
- }
590
-
591
- const { selected, total } = selectTokenCoins(coins, amount)
592
- const change = total - amount
593
-
594
- const payee = await deps.lockToPayee({
359
+ const trimmedNote = note?.trim() || undefined
360
+ // A throw here has nothing to release: either nothing was signed, or the
361
+ // runtime already released what it could not journal.
362
+ const h = await deps.handover({
595
363
  assetId: asset.id,
596
- amount,
364
+ units,
597
365
  recipientKey: session.identityKey,
598
- keyID
366
+ derivationPrefix: session.derivationPrefix,
367
+ derivationSuffix: session.derivationSuffix,
368
+ note: trimmedNote
599
369
  })
600
370
 
601
- const outputs: Record<string, unknown>[] = [
602
- {
603
- satoshis: 1,
604
- lockingScript: payee.lockingScript,
605
- outputDescription: 'Nearby token payment',
606
- ...(payee.customInstructions === undefined ? {} : { customInstructions: payee.customInstructions })
607
- }
608
- ]
609
- // One keyID for the change, derived from the session's own nonces so a
610
- // resend rebuilds the same script rather than minting a second coin.
611
- const changeKeyID = `change ${keyID}`
612
- const { publicKey: identityKey } = await wallet.getPublicKey({ identityKey: true }, originator)
613
- if (change > 0) {
614
- const changeScript = await new MandalaToken(wallet as never, originator).lockBRC29(
615
- asset.id,
616
- change,
617
- FT_PROTOCOL_ID,
618
- changeKeyID,
619
- identityKey
620
- )
621
- outputs.push({
622
- satoshis: 1,
623
- lockingScript: changeScript.toHex(),
624
- outputDescription: 'Token change',
625
- // Change comes back to THIS device, so it goes back in the basket. The
626
- // payee's output deliberately does not: it is not ours to track.
627
- basket,
628
- customInstructions: JSON.stringify({
629
- protocolID: FT_PROTOCOL_ID,
630
- keyID: changeKeyID,
631
- counterparty: identityKey,
632
- direction: 'change'
633
- })
634
- })
635
- }
636
-
637
- const created = await wallet.createAction(
638
- {
639
- // Same title discipline as the BSV path; the activity row overrides it
640
- // with "Sent <ticker>" from the settlement row unless a note was given
641
- // (WalletHomeScreen.tsx). The 'mandala' label is what makes the row
642
- // recognise a token row at all — the home screen keys off that label,
643
- // and without it a nearby token payment rendered as a BSV row — the
644
- // payee's key over "+0 sats" (2026-09-16). The payee key stays on as a
645
- // label for the resend path.
646
- description: (note?.trim() || 'Sent token').padEnd(5),
647
- labels: [PEERPAY_LABEL, session.identityKey, MANDALA_ACTION_LABEL, MANDALA_TOKEN_SPEND_LABEL],
648
- inputBEEF: sourceBeef.toBinary(),
649
- inputs: selected.map(coin => ({
650
- outpoint: coin.outpoint,
651
- unlockingScriptLength: 108,
652
- inputDescription: 'spend token'
653
- })),
654
- outputs,
655
- options: { randomizeOutputs: false, noSend: true, signAndProcess: false }
656
- },
657
- originator
658
- )
659
-
660
- const signable = created.signableTransaction
661
- if (!signable?.tx) throw new Error('createAction returned no signable token transaction')
662
- const signableTx = signable.tx
663
-
664
- return await releasingOnFailure(wallet, signable.reference, originator, queueFailedAbort, async () => {
665
- const unsigned = Transaction.fromBEEF(signableTx)
666
-
667
- // Input order is caller order — `randomizeOutputs` shuffles outputs only, and
668
- // it is off here anyway — so our coins occupy indices 0..n-1 and the wallet's
669
- // own fee inputs follow. Each is signed individually rather than through
670
- // `tx.sign()`, which would also reach inputs that are the wallet's to sign.
671
- const spends: Record<string, { unlockingScript: string }> = {}
672
- for (let i = 0; i < selected.length; i++) {
673
- const script = await signTokenInput(wallet, unsigned, i, selected[i], sourceBeef, originator)
674
- spends[String(i)] = { unlockingScript: script.toHex() }
675
- }
676
-
677
- const signed = await wallet.signAction(
678
- { reference: signable.reference, spends, options: { noSend: true } },
679
- originator
680
- )
681
- if (!signed.tx) throw new Error('signAction returned no transaction')
682
-
683
- const tipTx = Transaction.fromAtomicBEEF(signed.tx)
684
- const tipTxid = signed.txid ?? tipTx.id('hex')
685
-
686
- // Promote the payee's blinding reservation (minted back in `lockToPayee`,
687
- // before this txid existed) now that one does. Best-effort and after the
688
- // fact: the payment is already signed, so a commit failure here must not
689
- // fail it — it only costs this device's own later recovery of r, and the
690
- // reservation is still there for `pruneBlindingReservations` to sweep.
691
- if (deps.commitBlinding) {
692
- try {
693
- await deps.commitBlinding(keyID, tipTxid)
694
- } catch (e) {
695
- console.warn('[localpay] blindingCommit failed:', messageOf(e))
696
- }
697
- }
698
-
699
- // The bundle covers the ANCESTORS; the tip's own payload is minted here,
700
- // because only this function knows which outputs it just created and under
701
- // which keys.
702
- const bundle = await assembleBundle({
703
- tipTx,
371
+ return await releasingOnFailure(wallet, h.reference, originator, queueFailedAbort, async () => {
372
+ const mismatch = handoverMismatch(h, {
704
373
  assetId: asset.id,
705
- // deps.overlayIdentityKey, not asset.overlayIdentityKey (XR-104): the
706
- // two are equal here by construction (checked above), but sourcing
707
- // from deps means a future refactor that drops or reorders that check
708
- // still cannot hand a session-controlled value to the bundle.
709
- overlayIdentityKey: deps.overlayIdentityKey,
710
- store: deps.store
711
- })
712
- const tipLinkage = await mintTipLinkage(wallet, {
713
- inputs: selected,
714
- payeeLinkage: payee.linkage,
715
- changeKeyID: change > 0 ? changeKeyID : undefined,
716
- changeCounterparty: identityKey,
717
- // Same reasoning: this is `revealSpecificKeyLinkage`'s `verifier`, the
718
- // exact disclosure target XR-104 is about — it must come from this
719
- // device's configuration, never from the payee's request.
720
- overlayIdentityKey: deps.overlayIdentityKey,
721
- originator
374
+ derivationPrefix: session.derivationPrefix,
375
+ derivationSuffix: session.derivationSuffix
722
376
  })
377
+ if (mismatch !== null) throw new Error(mismatch)
723
378
 
724
- const paid = tipTx.outputs[0]?.satoshis
379
+ const paid = Transaction.fromAtomicBEEF(h.tx).outputs[h.outputIndex]?.satoshis
725
380
  return {
726
381
  frame: {
727
382
  version: FRAME_VERSION,
728
383
  kind: 'token' as const,
729
- // A′, never A. `lockToPayee` is the only thing that knows it.
730
- senderIdentityKey: payee.senderIdentityKey,
731
- outputIndex: 0,
732
- derivationPrefix: session.derivationPrefix,
733
- derivationSuffix: session.derivationSuffix,
734
- token: {
735
- assetId: asset.id,
736
- // deps, not asset — see the anchor check and comments above.
737
- overlayUrl: deps.overlayUrl,
738
- overlayIdentityKey: deps.overlayIdentityKey,
739
- certificates: deps.certificates ?? [],
740
- // The tip goes first: it is the one entry every recipient of this frame
741
- // needs, whatever else the chain behind it looks like.
742
- linkage: [{ txid: tipTxid, payload: tipLinkage }, ...bundle.linkage],
743
- admissions: bundle.admissions
744
- },
745
- ...(note?.trim() ? { note: note.trim() } : {}),
746
- transaction: new Uint8Array(signed.tx)
384
+ // A′ when blinded, from the receipt: the key the payee derives against.
385
+ senderIdentityKey: h.receipt.senderIdentityKey,
386
+ outputIndex: h.outputIndex,
387
+ derivationPrefix: h.receipt.derivationPrefix,
388
+ derivationSuffix: h.receipt.derivationSuffix,
389
+ // The v4 body's own members (IC §7.3): the payee rebuilds the body
390
+ // and runs the lib's recipient path on it.
391
+ token: tokenPaymentOfHandover(h),
392
+ ...(trimmedNote !== undefined ? { note: trimmedNote } : {}),
393
+ transaction: Uint8Array.from(h.tx)
747
394
  },
748
- reference: signable.reference,
749
- txid: tipTxid,
395
+ reference: h.reference,
396
+ txid: h.txid,
750
397
  satoshis: typeof paid === 'number' ? paid : 1,
751
- tokenAmount: amount
398
+ tokenAmount: units
752
399
  }
753
400
  })
754
401
  }
755
402
 
756
- function parseCustomInstructions(text?: string): { keyID?: string; counterparty?: string } {
757
- if (!text) return {}
758
- try {
759
- const parsed = JSON.parse(text) as Record<string, unknown>
760
- return {
761
- keyID: typeof parsed.keyID === 'string' ? parsed.keyID : undefined,
762
- counterparty: typeof parsed.counterparty === 'string' ? parsed.counterparty : undefined
763
- }
764
- } catch {
765
- // A coin whose instructions are unreadable cannot be unlocked, but that is
766
- // the signer's failure to report, not this parser's — it would be worse to
767
- // drop the coin silently and tell the user they are short of funds.
768
- return {}
769
- }
770
- }
771
-
772
- /**
773
- * Signs one token input through the wallet (BRC-100 `createSignature`).
774
- *
775
- * `MandalaToken.unlock` in `@bsv/templates` signs with a raw `PrivateKey`,
776
- * which a BRC-100 wallet never exports. This is the same construction driven
777
- * through the wallet instead: the sighash preimage is built identically, the
778
- * wallet signs its double-SHA256 under the FT protocol and the coin's own
779
- * keyID, and the public key that goes in the script is the `forSelf: true`
780
- * derivation — the key the LOCKER hashed, by BRC-42 symmetry. For a coin
781
- * another party locked to us, only `forSelf: true` matches the pubKeyHash.
782
- */
783
- async function signTokenInput(
784
- wallet: PayingWallet,
785
- tx: Transaction,
786
- inputIndex: number,
787
- coin: SelectedTokenCoin,
788
- sources: Beef,
789
- originator: string
790
- ): Promise<UnlockingScript> {
791
- const input = tx.inputs[inputIndex]
792
- if (!input) throw new Error(`the signable transaction has no input ${inputIndex}`)
793
- const [coinTxid, coinVout] = coin.outpoint.split('.')
794
- const sourceTx = input.sourceTransaction ?? sources.findTxid(coinTxid)?.tx
795
- const sourceOutput = sourceTx?.outputs[input.sourceOutputIndex ?? Number(coinVout)]
796
- if (!sourceOutput?.lockingScript || sourceOutput.satoshis == null) {
797
- throw new Error(`cannot sign token input ${inputIndex}: its source output is missing`)
798
- }
799
-
800
- const scope = TransactionSignature.SIGHASH_FORKID | TransactionSignature.SIGHASH_ALL
801
- const preimage = TransactionSignature.format({
802
- sourceTXID: input.sourceTXID ?? coinTxid,
803
- sourceOutputIndex: input.sourceOutputIndex ?? Number(coinVout),
804
- sourceSatoshis: sourceOutput.satoshis,
805
- transactionVersion: tx.version,
806
- otherInputs: tx.inputs.filter((_, i) => i !== inputIndex),
807
- inputIndex,
808
- outputs: tx.outputs,
809
- inputSequence: input.sequence ?? 0xffffffff,
810
- subscript: sourceOutput.lockingScript,
811
- lockTime: tx.lockTime,
812
- scope
813
- })
814
-
815
- const { signature: der } = await (wallet.createSignature as NonNullable<PayingWallet['createSignature']>)(
816
- {
817
- hashToDirectlySign: Hash.hash256(preimage),
818
- protocolID: FT_PROTOCOL_ID,
819
- keyID: coin.keyID,
820
- counterparty: coin.counterparty
821
- },
822
- originator
823
- )
824
- const sig = Signature.fromDER([...der])
825
- const sigForScript = new TransactionSignature(sig.r, sig.s, scope).toChecksigFormat()
826
- const { publicKey } = await wallet.getPublicKey(
827
- { protocolID: FT_PROTOCOL_ID, keyID: coin.keyID, counterparty: coin.counterparty, forSelf: true },
828
- originator
829
- )
830
- const pubkey = Utils.toArray(publicKey, 'hex')
831
- return new UnlockingScript([
832
- { op: sigForScript.length, data: sigForScript },
833
- { op: pubkey.length, data: pubkey }
834
- ])
835
- }
836
-
837
- /**
838
- * The tip's own `MandalaLinkagePayload` — the exact off-chain bytes the
839
- * overlay's `/submit` consumes, UTF-8 JSON of
840
- * `{ inputs: [{index, linkage}], outputs: [{index, linkage}] }`.
841
- *
842
- * EVERY token output needs its own entry: an unlinked one is skipped by the
843
- * overlay's topic manager and breaks its conservation check, which refuses the
844
- * whole transaction. Inputs are revealed so the overlay can screen the SENDER
845
- * under an allowlist or denylist asset — omit them and a denylist asset still
846
- * admits, but sender screening silently degrades.
847
- *
848
- * The verifier on every reveal is the OVERLAY's key, never the payee's: these
849
- * are BRC-72 blobs only the prover and the named verifier can decrypt. The
850
- * payee carries them, forwards them verbatim on a re-spend, and can read none
851
- * of them.
852
- */
853
- async function mintTipLinkage(
854
- wallet: PayingWallet,
855
- args: {
856
- inputs: SelectedTokenCoin[]
857
- payeeLinkage: unknown
858
- changeKeyID?: string
859
- changeCounterparty: string
860
- overlayIdentityKey: string
861
- originator: string
862
- }
863
- ): Promise<Uint8Array> {
864
- const reveal = wallet.revealSpecificKeyLinkage as NonNullable<PayingWallet['revealSpecificKeyLinkage']>
865
- const forOverlay = (keyID: string, counterparty: string) =>
866
- reveal({ counterparty, verifier: args.overlayIdentityKey, protocolID: FT_PROTOCOL_ID, keyID }, args.originator)
867
-
868
- const outputs: { index: number; linkage: unknown }[] = [{ index: 0, linkage: args.payeeLinkage }]
869
- if (args.changeKeyID !== undefined) {
870
- outputs.push({ index: 1, linkage: await forOverlay(args.changeKeyID, args.changeCounterparty) })
871
- }
872
- const inputs: { index: number; linkage: unknown }[] = []
873
- for (let i = 0; i < args.inputs.length; i++) {
874
- inputs.push({ index: i, linkage: await forOverlay(args.inputs[i].keyID, args.inputs[i].counterparty) })
875
- }
876
-
877
- return new Uint8Array(Utils.toArray(JSON.stringify({ inputs, outputs }), 'utf8'))
878
- }
879
-
880
403
  /**
881
404
  * Releases the `noSend` payment identified by `txid` so this device broadcasts it.
882
405
  *
@@ -1047,6 +570,16 @@ export async function finalizeDelivery(
1047
570
  * not adopted it.
1048
571
  */
1049
572
  parkUnverifiable?: (txid: string) => Promise<void>
573
+ /**
574
+ * Plan 07 Task 15: a decline whose inputs this call actually released
575
+ * (the abort was attempted, not skipped for a park or a txid the chain
576
+ * already knows). The nearby token rail journals the row `built →
577
+ * cancelled` here: the payee queued nothing and the money never moved.
578
+ * Called after the abort, whatever its result (a failed one is queued
579
+ * for replay above, and the abort guard allows `cancelled`). Best-effort:
580
+ * a throw never turns the decline into a failure.
581
+ */
582
+ onReleased?: (txid: string) => Promise<void>
1050
583
  }
1051
584
  ): Promise<DeliveryOutcome> {
1052
585
  if (!ack.ok) {
@@ -1125,6 +658,13 @@ export async function finalizeDelivery(
1125
658
  if (built.txid && deps.watchDeclinedAbort) {
1126
659
  await deps.watchDeclinedAbort({ txid: built.txid, reference: built.reference }).catch(() => undefined)
1127
660
  }
661
+ if (built.txid && deps.onReleased) {
662
+ try {
663
+ await deps.onReleased(built.txid)
664
+ } catch (e) {
665
+ console.warn('[localpay] could not record the released decline:', messageOf(e))
666
+ }
667
+ }
1128
668
  }
1129
669
  }
1130
670
  return { kind: 'declined', reason: ack.error }
@@ -1180,19 +720,20 @@ export async function finalizeDelivery(
1180
720
  // GUARD #1 (offline-settlement spec §4.3). A token payment is NEVER
1181
721
  // broadcast from here, online or off.
1182
722
  //
1183
- // This is the structural half of "admission gates broadcast": `postTokenStep`
1184
- // in the drain is the only path to a real broadcast for a token transaction,
1185
- // and it gets there only after every ancestor in COVER's `mustSubmit` has
1186
- // been admitted. Without this check the online payer falls straight through
1187
- // to `sendWith` exactly as the BSV path does — with no `kind` check at all —
1188
- // and puts an unadmitted token transaction on chain before any overlay has
1189
- // seen it. The overlay can then only refuse it, and the coin is stranded
1190
- // between "spent on chain" and "never admitted".
723
+ // Admission gates broadcast: the color module settles the hand-over
724
+ // (`settleNow` after this positive ack, W5, or the tick's bare settle) and
725
+ // only a verified admission releases it — the module's own `sendWith`, and
726
+ // the drain once the `color_transfers` row reads `settled` (W1). Without
727
+ // this check the online payer falls straight through to `sendWith` exactly
728
+ // as the BSV path does and puts an unadmitted token transaction on chain
729
+ // before any overlay has seen it; the overlay can then only refuse it, and
730
+ // the coin is stranded between "spent on chain" and "never admitted". The
731
+ // storage broadcast hold would also refuse it, but this path never asks.
1191
732
  //
1192
- // Placed AFTER the hold on purpose: the hold is what creates the queue row
1193
- // the drain owns and promotes `nosend → unproven` so this payment's change
1194
- // can fund the next offline one. Skipping the broadcast is the whole change;
1195
- // skipping the hold would strand the payment instead.
733
+ // Placed AFTER the hold on purpose: the hold journals `handed_over` and
734
+ // creates the queue row the drain owns, and promotes `nosend → unproven` so
735
+ // this payment's change can fund the next offline one. Skipping the
736
+ // broadcast is the whole change; skipping the hold would strand the payment.
1196
737
  if (built.frame?.kind === 'token') {
1197
738
  return { kind: 'sent', broadcast: 'pending', detail: 'awaiting overlay admission' }
1198
739
  }