@bsv/expo-wallet-toolbox 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/CHANGELOG.md +292 -0
  2. package/README.md +0 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +9 -1
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +409 -20
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +97 -14
  12. package/core/localpay/build.ts +674 -37
  13. package/core/localpay/codec.ts +68 -5
  14. package/core/localpay/pending.ts +240 -22
  15. package/core/localpay/settlementAck.ts +149 -0
  16. package/core/localpay/types.ts +14 -1
  17. package/core/localpay/verify.ts +118 -69
  18. package/core/mandala/abortGuard.ts +134 -0
  19. package/core/mandala/basketMigration.ts +166 -0
  20. package/core/mandala/bundle.ts +244 -0
  21. package/core/mandala/createRuntime.ts +2437 -0
  22. package/core/mandala/drain.ts +670 -0
  23. package/core/mandala/permissionModule.ts +642 -0
  24. package/core/mandala/resendTransfer.ts +175 -0
  25. package/core/mandala/runtime.ts +357 -0
  26. package/core/mandala/settlementStore.ts +412 -0
  27. package/core/mandala/types.ts +290 -0
  28. package/core/offline/cancelParked.ts +94 -1
  29. package/core/offline/payerHold.ts +152 -12
  30. package/core/offline/tokenFrames.ts +197 -0
  31. package/core/parsePeerPayURI.ts +70 -17
  32. package/core/pay/rails/address.ts +51 -3
  33. package/core/pay/rails/handle.ts +88 -9
  34. package/core/pay/rails/index.ts +16 -6
  35. package/core/pay/rails/nearby.ts +114 -4
  36. package/core/services/capWalletArgs.ts +8 -9
  37. package/core/services/externalOrigin.ts +39 -0
  38. package/core/services/vault/VaultKeyService.ts +912 -251
  39. package/core/services/vault/ceremony.ts +435 -367
  40. package/core/services/vault/ceremonyHost.ts +27 -21
  41. package/core/services/vault/devMock.ts +30 -7
  42. package/core/services/vault/driver.ts +95 -41
  43. package/core/services/vault/guard.ts +514 -56
  44. package/core/services/vault/hardwareLease.ts +22 -0
  45. package/core/services/vault/mockYubiKey.ts +258 -90
  46. package/core/services/vault/pivReset.ts +145 -0
  47. package/core/services/vault/r1comb.ts +976 -0
  48. package/core/services/vault/session.ts +93 -26
  49. package/core/services/vault/transfers.ts +2617 -747
  50. package/core/services/vault/types.ts +100 -43
  51. package/core/services/vault/vaultStore.ts +991 -74
  52. package/core/services/walletConnectionValidation.ts +293 -0
  53. package/core/storage/StorageExpoSQLite.ts +382 -56
  54. package/core/storage/dbImage.ts +48 -0
  55. package/core/storage/methods/findSql.ts +0 -54
  56. package/core/storage/methods/listOutputsSql.ts +7 -3
  57. package/core/storage/methods/offlineActions.ts +15 -0
  58. package/core/storage/methods/processOfflineActions.ts +263 -6
  59. package/core/storage/methods/walletBalanceSql.ts +16 -4
  60. package/core/storage/schema/createTables.ts +123 -0
  61. package/core/storage/sqlUpdateValue.ts +24 -0
  62. package/core/toolboxConfig.ts +112 -1
  63. package/core/walletRepair/runWalletCheck.ts +19 -2
  64. package/package.json +25 -24
  65. package/ui/components/QRScanner.tsx +1 -1
  66. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  67. package/ui/components/pay/AssetPicker.tsx +184 -0
  68. package/ui/components/pay/AvailableBalance.tsx +33 -2
  69. package/ui/components/pay/HandleReceive.tsx +213 -50
  70. package/ui/components/pay/NearbyFlow.tsx +616 -69
  71. package/ui/components/pay/PayForm.tsx +73 -8
  72. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  73. package/ui/components/pay/RecipientField.tsx +49 -4
  74. package/ui/components/pay/RequestHub.tsx +68 -8
  75. package/ui/components/pay/ResultBanner.tsx +41 -4
  76. package/ui/components/pay/UniversalSend.tsx +534 -30
  77. package/ui/components/pay/tokenSendCopy.ts +116 -0
  78. package/ui/components/pay/useRecipientInput.ts +36 -7
  79. package/ui/components/ui/PermissionSheet.tsx +65 -4
  80. package/ui/components/ui/Sheet.tsx +9 -2
  81. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  82. package/ui/components/vault/KeyChooser.tsx +96 -0
  83. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  84. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  85. package/ui/components/wallet/ActivityRow.tsx +101 -17
  86. package/ui/components/wallet/AmountInput.tsx +77 -25
  87. package/ui/components/wallet/AssetAmount.tsx +95 -0
  88. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  89. package/ui/components/wallet/tokenEviction.ts +65 -0
  90. package/ui/hooks/useExportWalletData.ts +39 -0
  91. package/ui/hooks/useMandala.ts +303 -0
  92. package/ui/hooks/useVaultBalance.ts +105 -7
  93. package/ui/hooks/useVaultCoverage.ts +52 -0
  94. package/ui/importDatabases.ts +7 -3
  95. package/ui/index.ts +50 -7
  96. package/ui/screens/ConnectionsScreen.tsx +46 -29
  97. package/ui/screens/PairScreen.tsx +12 -12
  98. package/ui/screens/PayScreen.tsx +130 -10
  99. package/ui/screens/SettingsScreen.tsx +18 -9
  100. package/ui/screens/VaultScreen.tsx +925 -171
  101. package/ui/screens/VaultTransferScreen.tsx +376 -123
  102. package/ui/screens/WalletCheckScreen.tsx +10 -1
  103. package/ui/screens/WalletConfigScreen.tsx +38 -16
  104. package/ui/screens/WalletHomeScreen.tsx +417 -86
  105. package/ui/screens/homeBadges.ts +9 -1
  106. package/ui/screens/tokenRowTitle.ts +68 -0
  107. package/ui/tokenFormat.ts +108 -0
  108. package/ui/tokenSeen.ts +75 -0
  109. package/ui/tokenStatus.ts +79 -0
  110. package/assets/sounds/vault-close.wav +0 -0
  111. package/assets/sounds/vault-open.wav +0 -0
  112. package/core/services/vault/k1.ts +0 -75
  113. package/core/services/vault/sealing.ts +0 -84
  114. package/core/services/vault/vaultDerivation.ts +0 -152
  115. package/core/services/vault/vaultPassphrase.ts +0 -287
  116. package/ui/components/vault/PassphraseField.tsx +0 -306
  117. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  118. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -1,18 +1,36 @@
1
- import { P2PKH, PublicKey, Transaction } from '@bsv/sdk'
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 '@bsv/templates'
2
13
  import { FRAME_VERSION, type PaymentFrame } from './codec'
3
14
  import { isRequestableAmount, type Session } from './session'
4
15
  import { PEERPAY_LABEL, PEERPAY_PROTOCOL_ID } from './pending'
16
+ import { FT_PROTOCOL_ID } from './verify'
5
17
  import type { Ack } from './types'
18
+ import { MANDALA_ACTION_LABEL, MANDALA_BASKET, assembleBundle, type BundleStore } from '../mandala/bundle'
6
19
  import { getOnline } from '../net/online'
7
- import { abbreviateKey } from '../pay/counterparty'
8
20
 
9
21
  /** The toolbox's per-txid verdict on a `sendWith` release. */
10
22
  type SendWithStatus = 'unproven' | 'sending' | 'failed'
11
23
 
24
+ interface ListOutputsOutcome {
25
+ totalOutputs?: number
26
+ outputs: { outpoint: string; satoshis?: number; spendable?: boolean; customInstructions?: string }[]
27
+ BEEF?: number[]
28
+ }
29
+
12
30
  interface CreateActionOutcome {
13
31
  tx?: number[]
14
32
  txid?: string
15
- signableTransaction?: { reference: string }
33
+ signableTransaction?: { reference: string; tx?: number[] }
16
34
  sendWithResults?: { txid: string; status: string }[]
17
35
  }
18
36
 
@@ -20,6 +38,15 @@ interface PayingWallet {
20
38
  getPublicKey(args: unknown, originator?: string): Promise<{ publicKey: string }>
21
39
  createAction(args: unknown, originator?: string): Promise<CreateActionOutcome>
22
40
  signAction(args: unknown, originator?: string): Promise<{ tx?: number[]; txid?: string }>
41
+ /**
42
+ * Token path only. Present on every BRC-100 wallet; optional here so the BSV
43
+ * path's callers and its tests are unchanged by the token path's existence.
44
+ */
45
+ listOutputs?(args: unknown, originator?: string): Promise<ListOutputsOutcome>
46
+ /** Token path only: signs each selected token input (BRC-100 `createSignature`). */
47
+ createSignature?(args: unknown, originator?: string): Promise<{ signature: number[] }>
48
+ /** Token path only: mints the overlay-verifier linkage for inputs and change. */
49
+ revealSpecificKeyLinkage?(args: unknown, originator?: string): Promise<unknown>
23
50
  /**
24
51
  * Releases the inputs a `noSend` action is holding. Required, not optional:
25
52
  * without it an abandoned build locks `amount + fee` in the payer's wallet
@@ -61,8 +88,81 @@ export interface BuiltPayment {
61
88
  * send-max, where `amount` carries the sentinel and the wallet rewrites the
62
89
  * output to whatever it could fund. Callers displaying "amount sent" must
63
90
  * use this, not the value they asked `buildPaymentFrame` for.
91
+ *
92
+ * On the TOKEN path this is the output's own satoshis — 1, per BRC-92 — and
93
+ * is not the payment. `tokenAmount` is.
64
94
  */
65
95
  satoshis: number
96
+ /**
97
+ * Base units of the asset locked to the payee, on the token path only.
98
+ *
99
+ * A token output carries 1 satoshi and the real figure in its script, so a
100
+ * caller that rendered `satoshis` as "amount sent" for a token payment would
101
+ * show "1" for every payment ever made. Undefined on the BSV path, where
102
+ * `satoshis` IS the payment.
103
+ */
104
+ tokenAmount?: number
105
+ }
106
+
107
+ /** One token coin in the payer's basket, with what it takes to spend it. */
108
+ export interface SelectedTokenCoin {
109
+ /** "<txid>.<vout>" */
110
+ outpoint: string
111
+ /** Base units carried by the script, not satoshis. */
112
+ amount: number
113
+ /** BRC-42 keyID this coin was locked under, from its customInstructions. */
114
+ keyID: string
115
+ /** BRC-42 counterparty this coin was locked under. */
116
+ counterparty: string
117
+ }
118
+
119
+ /**
120
+ * The D2 blinding seam.
121
+ *
122
+ * A′ = A + rG: the payee derives against a BLINDED sender key and so cannot
123
+ * join this payer's later payments to each other. That arithmetic needs the
124
+ * payer's own scalar, which no BRC-100 method exposes — it lives in
125
+ * `@bsv/mandala` beside the rest of the token pipeline. It is injected rather
126
+ * than approximated here, and it is REQUIRED rather than defaulted: a
127
+ * silent fall-back to an unblinded BRC-29 lock would still produce a working
128
+ * payment, which is exactly why it would never be noticed.
129
+ */
130
+ export type LockToPayee = (args: {
131
+ assetId: string
132
+ amount: number
133
+ /** The payee's identity key, from the session. */
134
+ recipientKey: string
135
+ /** The session's own nonces, `"<prefix> <suffix>"` — what binds frame to request. */
136
+ keyID: string
137
+ }) => Promise<{
138
+ lockingScript: string
139
+ /** A′ — what goes on the wire as `frame.senderIdentityKey`. */
140
+ senderIdentityKey: string
141
+ /** The overlay-verifier SpecificLinkage for this output (k for S′, not S). */
142
+ linkage: unknown
143
+ customInstructions?: string
144
+ }>
145
+
146
+ /** What the token path needs beyond an ordinary BSV build. */
147
+ export interface TokenBuildDeps {
148
+ /** Read side of this device's settlement tables, for the AdmissionBundle. */
149
+ store: BundleStore
150
+ lockToPayee: LockToPayee
151
+ /**
152
+ * Promotes a `lockToPayee` blinding reservation to the frame's tip txid once
153
+ * the transaction is signed (nearby blinding, offline-settlement design):
154
+ * `lockToPayee` mints r and reserves it under the session's own `keyID`
155
+ * before a txid exists; this call moves that reservation to the real txid
156
+ * once one does. Optional so the BSV path's callers and tests are
157
+ * unaffected — omitting it just leaves the reservation for the drain's own
158
+ * `pruneBlindingReservations` sweep instead of promoting it, which costs
159
+ * this device's own later recovery of r but never the payment itself.
160
+ */
161
+ commitBlinding?: (keyID: string, txid: string) => Promise<void>
162
+ /** Defaults to `MANDALA_BASKET`. */
163
+ basket?: string
164
+ /** Opaque serialized VerifiableCertificates to carry, if the asset needs any. */
165
+ certificates?: Uint8Array[]
66
166
  }
67
167
 
68
168
  /**
@@ -76,6 +176,41 @@ export type DeliveryOutcome =
76
176
  | { kind: 'sent'; broadcast: 'ok' | 'pending'; detail?: string }
77
177
  | { kind: 'declined'; reason?: string }
78
178
 
179
+ /**
180
+ * Picks the coins to spend: largest first, fewest UTXOs.
181
+ *
182
+ * Fewest inputs is not an aesthetic preference — every token input adds its own
183
+ * ancestor to the BEEF the frame carries and its own linkage reveal to the
184
+ * payload, and the sealed frame has a hard 64 KiB ceiling on the radios. A
185
+ * selection that took ten small coins where one large one would do can push an
186
+ * otherwise ordinary payment past the wire limit.
187
+ *
188
+ * Throws rather than under-funding: a transaction that moves less than the
189
+ * payee asked for is not a smaller payment, it is a broken one.
190
+ */
191
+ export function selectTokenCoins(
192
+ coins: SelectedTokenCoin[],
193
+ amount: number
194
+ ): { selected: SelectedTokenCoin[]; total: number } {
195
+ if (!isRequestableAmount(amount)) {
196
+ throw new Error('amount must be a positive whole number of base units')
197
+ }
198
+ const sorted = [...coins].sort((a, b) => b.amount - a.amount)
199
+ // An exact or single-coin cover is both the smallest input set and the
200
+ // smallest frame, so prefer the smallest coin that covers the whole amount.
201
+ const single = [...sorted].reverse().find(c => c.amount >= amount)
202
+ if (single) return { selected: [single], total: single.amount }
203
+
204
+ const selected: SelectedTokenCoin[] = []
205
+ let total = 0
206
+ for (const coin of sorted) {
207
+ selected.push(coin)
208
+ total += coin.amount
209
+ if (total >= amount) return { selected, total }
210
+ }
211
+ throw new Error(`insufficient token balance: have ${total}, need ${amount}`)
212
+ }
213
+
79
214
  /**
80
215
  * Builds the frame a payer sends. BRC-29: the output locks to a key derived
81
216
  * for the payee from the session's derivation nonces.
@@ -97,11 +232,31 @@ export async function buildPaymentFrame(
97
232
  wallet: PayingWallet,
98
233
  session: Session,
99
234
  originator: string,
100
- amount: number
235
+ amount: number,
236
+ /**
237
+ * Required when — and only when — the session names an asset. A token
238
+ * request with no deps is refused rather than silently paid in satoshis:
239
+ * the two are not interchangeable, and `amount` means base units on one
240
+ * path and satoshis on the other.
241
+ */
242
+ token?: TokenBuildDeps,
243
+ /** The payer's note. Becomes the action's description in place of the fixed
244
+ * fallback, and rides on the frame so the payee's own activity row can show
245
+ * it too. */
246
+ note?: string
101
247
  ): Promise<BuiltPayment> {
102
248
  if (!isRequestableAmount(amount)) {
103
249
  throw new Error('amount must be a positive whole number of satoshis')
104
250
  }
251
+ if (session.asset) {
252
+ if (!token) {
253
+ throw new Error('a token session needs token build deps (store + lockToPayee)')
254
+ }
255
+ if (session.amount !== undefined && session.amount !== amount) {
256
+ throw new Error('amount does not match the payee’s request')
257
+ }
258
+ return buildTokenPaymentFrame(wallet, session, session.asset, originator, amount, token, note)
259
+ }
105
260
  // A payee that named a figure is stating a binding term of the request, and
106
261
  // its settle path refuses anything else. Catching the disagreement here — on
107
262
  // the payer, before an action exists — turns a burnt build and a remote
@@ -126,9 +281,12 @@ export async function buildPaymentFrame(
126
281
 
127
282
  let result = await wallet.createAction(
128
283
  {
129
- // The activity list uses the description as the row title, so it names
130
- // the payee rather than the rail: the rail is already in the label.
131
- description: abbreviateKey(session.identityKey),
284
+ // The activity list uses the description as the row title, so it says
285
+ // what happened. Not the payee's key: the row draws the counterparty as
286
+ // a sigil from the label below, and an abbreviated key as a title told
287
+ // the user nothing about a blinded transfer (2026-09-16). A payer's note
288
+ // overrides this fixed wording, same as the message-box rail.
289
+ description: note?.trim() || 'Sent BSV',
132
290
  // The payee's identity key rides as a label, and the derivation data as
133
291
  // the output's customInstructions — exactly what the handle rail writes.
134
292
  // Both rails derive to BRC-29 (`counterparty: identityKey`, keyID
@@ -166,46 +324,505 @@ export async function buildPaymentFrame(
166
324
 
167
325
  const reference = result.signableTransaction?.reference
168
326
 
169
- // With signAndProcess disabled, createAction returns an unsigned
170
- // `signableTransaction` rather than a final `tx`. We have no caller-supplied
171
- // inputs — all inputs are wallet-funded — so finalize by signing with empty
172
- // `spends`. noSend stays true: the payee internalizes and broadcasts, not
173
- // the payer.
174
- if (!result.tx && result.signableTransaction) {
175
- const signed = await wallet.signAction(
327
+ return await releasingOnFailure(wallet, reference, originator, async () => {
328
+ // With signAndProcess disabled, createAction returns an unsigned
329
+ // `signableTransaction` rather than a final `tx`. We have no caller-supplied
330
+ // inputs — all inputs are wallet-funded — so finalize by signing with empty
331
+ // `spends`. noSend stays true: the payee internalizes and broadcasts, not
332
+ // the payer.
333
+ if (!result.tx && result.signableTransaction) {
334
+ const signed = await wallet.signAction(
335
+ {
336
+ reference: result.signableTransaction.reference,
337
+ spends: {},
338
+ options: { noSend: true }
339
+ },
340
+ originator
341
+ )
342
+ result = { ...result, ...signed }
343
+ }
344
+
345
+ if (!result.tx) throw new Error('createAction returned no transaction')
346
+
347
+ // Authoritative amount off the transaction itself — covers send-max, where
348
+ // `amount` was the sentinel and the wallet wrote the real figure to output 0.
349
+ const paid = Transaction.fromAtomicBEEF(result.tx).outputs[0]?.satoshis
350
+ if (typeof paid !== 'number' || paid <= 0) throw new Error('Could not determine paid amount')
351
+
352
+ return {
353
+ frame: {
354
+ version: FRAME_VERSION,
355
+ kind: 'bsv' as const,
356
+ senderIdentityKey,
357
+ outputIndex: 0,
358
+ derivationPrefix: session.derivationPrefix,
359
+ derivationSuffix: session.derivationSuffix,
360
+ ...(note?.trim() ? { note: note.trim() } : {}),
361
+ transaction: new Uint8Array(result.tx)
362
+ },
363
+ reference,
364
+ txid: result.txid,
365
+ satoshis: paid
366
+ }
367
+ })
368
+ }
369
+
370
+ /**
371
+ * Runs the rest of a build once `createAction` has handed back a reference,
372
+ * and releases that action if any step throws.
373
+ *
374
+ * From `createAction` on, the action holds its inputs `spendable: false`. An
375
+ * `unsigned` action is eventually reaped by the storage sweeper; a signed
376
+ * `nosend` one never is — the 2026-09-16 incident left a just-received coin
377
+ * locked for good when `assembleBundle` threw after `signAction`, and the
378
+ * caller's catch had no way to know an action existed. The build does know,
379
+ * and nothing inside it has left the device, so aborting here is always safe.
380
+ * Best-effort: the error the caller sees is the one that stopped the build.
381
+ */
382
+ async function releasingOnFailure<T>(
383
+ wallet: PayingWallet,
384
+ reference: string | undefined,
385
+ originator: string,
386
+ steps: () => Promise<T>
387
+ ): Promise<T> {
388
+ try {
389
+ return await steps()
390
+ } catch (e) {
391
+ if (reference) {
392
+ try {
393
+ const result = await wallet.abortAction({ reference }, originator)
394
+ if (result?.aborted === false) throw new Error('abortAction returned aborted:false')
395
+ } catch (abortError) {
396
+ console.warn('[localpay] could not release the failed build:', messageOf(abortError))
397
+ }
398
+ }
399
+ throw e
400
+ }
401
+ }
402
+
403
+ /**
404
+ * The payer's token build (offline-settlement spec §9, steps 4–5).
405
+ *
406
+ * Structurally the same shape as the BSV path — select, create `noSend`, sign,
407
+ * hand over — with two differences that are the whole point of the revision:
408
+ *
409
+ * 1. The frame carries an ADMISSION BUNDLE: σ_I for every ancestor this device
410
+ * can prove the overlay admitted, and the linkage payload for every one it
411
+ * cannot, including the tip's own. That is what lets the payee decide,
412
+ * offline, whether the coin it is being handed is real.
413
+ * 2. Nothing is submitted. Not to the overlay, not to the network. The payer
414
+ * hands over and stops; the recipient submits (rule 3) and this device's own
415
+ * drain submits too, optionally, whenever it next reconnects (rule 6).
416
+ * Submitting first would put a face-to-face payment behind a network round
417
+ * trip, and broadcasting first would put an unadmitted token transaction on
418
+ * chain — which the overlay can then only refuse.
419
+ *
420
+ * `randomizeOutputs` is off, as on the BSV path, so the payee's output is index
421
+ * 0 and the frame can name it. The mandala handle rail shuffles instead, to hide
422
+ * which output is the recipient's from a chain observer; that buys nothing here,
423
+ * where the payee is standing in front of the payer and already knows its own
424
+ * script.
425
+ */
426
+ /**
427
+ * How many basket outputs one `listOutputs` page asks for.
428
+ *
429
+ * BRC-100's default `limit` is TEN. Coin selection was reading that one default
430
+ * page and calling it the wallet's balance: a payer holding twelve coins whose
431
+ * eleventh and twelfth were the ones that covered the amount got
432
+ * `insufficient token balance` for money it plainly had — worse, the figure in
433
+ * the message was a partial total, so it read as a wallet bug rather than a
434
+ * paging bug. A thousand is high enough that the loop below is one round trip
435
+ * for any realistic basket and low enough not to drag a whole basket's BEEF
436
+ * through one response.
437
+ */
438
+ const TOKEN_LIST_PAGE = 1000
439
+
440
+ /**
441
+ * Hard stop on the paging loop.
442
+ *
443
+ * `totalOutputs` is the wallet's own count, and the loop also stops on a short
444
+ * or empty page — but a wallet that reports a total it never serves (or serves
445
+ * the same page forever) must not spin a payment screen. A million outputs is
446
+ * far past any real basket.
447
+ */
448
+ const TOKEN_LIST_MAX_PAGES = 1000
449
+
450
+ /**
451
+ * Every output of the token basket, page by page, merging each page's BEEF into
452
+ * `into` as it goes.
453
+ *
454
+ * The BEEF accumulates across pages on purpose: an output's value lives in its
455
+ * source transaction's script, so a coin from page two is unreadable — silently
456
+ * skipped by the caller's `if (!script) continue` — unless page two's
457
+ * transactions are merged before it is examined.
458
+ */
459
+ async function* listTokenBasket(
460
+ wallet: PayingWallet,
461
+ basket: string,
462
+ originator: string,
463
+ into: Beef
464
+ ): AsyncGenerator<ListOutputsOutcome['outputs'][number]> {
465
+ let offset = 0
466
+ for (let page = 0; page < TOKEN_LIST_MAX_PAGES; page++) {
467
+ const listed = await wallet.listOutputs!(
176
468
  {
177
- reference: result.signableTransaction.reference,
178
- spends: {},
179
- options: { noSend: true }
469
+ basket,
470
+ include: 'entire transactions',
471
+ includeCustomInstructions: true,
472
+ limit: TOKEN_LIST_PAGE,
473
+ offset
180
474
  },
181
475
  originator
182
476
  )
183
- result = { ...result, ...signed }
477
+ if (listed.BEEF) into.mergeBeef(listed.BEEF)
478
+ const outputs = listed.outputs ?? []
479
+ for (const out of outputs) yield out
480
+ // An empty page always ends it — that, plus the page ceiling, is what keeps
481
+ // a wallet that ignores `offset` from looping forever.
482
+ if (outputs.length === 0) return
483
+ offset += outputs.length
484
+ if (typeof listed.totalOutputs === 'number') {
485
+ // The wallet's own count is the authority when it reports one. A SHORT
486
+ // page must not end the loop here: a wallet is free to cap `limit` below
487
+ // what was asked for, and treating its cap as "end of basket" would
488
+ // re-introduce the very truncation this loop exists to fix.
489
+ if (offset >= listed.totalOutputs) return
490
+ } else if (outputs.length < TOKEN_LIST_PAGE) {
491
+ // No count to go by, so a short page is the only end-of-basket signal
492
+ // there is.
493
+ return
494
+ }
495
+ }
496
+ }
497
+
498
+ async function buildTokenPaymentFrame(
499
+ wallet: PayingWallet,
500
+ session: Session,
501
+ asset: NonNullable<Session['asset']>,
502
+ originator: string,
503
+ amount: number,
504
+ deps: TokenBuildDeps,
505
+ note?: string
506
+ ): Promise<BuiltPayment> {
507
+ if (!wallet.listOutputs) throw new Error('this wallet cannot list token outputs')
508
+ if (!wallet.createSignature) throw new Error('this wallet cannot sign token inputs')
509
+ if (!wallet.revealSpecificKeyLinkage) throw new Error('this wallet cannot reveal token linkage')
510
+
511
+ const basket = deps.basket ?? MANDALA_BASKET
512
+ const keyID = `${session.derivationPrefix} ${session.derivationSuffix}`
513
+
514
+ // `include: 'entire transactions'` is not an optimisation: the amount a token
515
+ // output carries lives in its SCRIPT, not in `satoshis`, so the coins cannot
516
+ // even be valued without their source transactions — and the same BEEF is
517
+ // what the payee will walk to prove the chain.
518
+ const sourceBeef = new Beef()
519
+ const coins: SelectedTokenCoin[] = []
520
+ for await (const out of listTokenBasket(wallet, basket, originator, sourceBeef)) {
521
+ if (out.spendable === false) continue
522
+ const [txid, voutText] = out.outpoint.split('.')
523
+ const source = sourceBeef.findTxid(txid)?.tx
524
+ const script = source?.outputs[Number(voutText)]?.lockingScript
525
+ if (!script) continue
526
+ let decoded: { assetId: string; amount: number }
527
+ try {
528
+ decoded = MandalaToken.decode(script)
529
+ } catch {
530
+ continue // a stray non-token output in the basket is not this asset's coin
531
+ }
532
+ if (decoded.assetId !== asset.id) continue
533
+ const ci = parseCustomInstructions(out.customInstructions)
534
+ coins.push({
535
+ outpoint: out.outpoint,
536
+ amount: decoded.amount,
537
+ keyID: ci.keyID ?? '',
538
+ counterparty: ci.counterparty ?? 'self'
539
+ })
540
+ }
541
+
542
+ const { selected, total } = selectTokenCoins(coins, amount)
543
+ const change = total - amount
544
+
545
+ const payee = await deps.lockToPayee({
546
+ assetId: asset.id,
547
+ amount,
548
+ recipientKey: session.identityKey,
549
+ keyID
550
+ })
551
+
552
+ const outputs: Record<string, unknown>[] = [
553
+ {
554
+ satoshis: 1,
555
+ lockingScript: payee.lockingScript,
556
+ outputDescription: 'Nearby token payment',
557
+ ...(payee.customInstructions === undefined ? {} : { customInstructions: payee.customInstructions })
558
+ }
559
+ ]
560
+ // One keyID for the change, derived from the session's own nonces so a
561
+ // resend rebuilds the same script rather than minting a second coin.
562
+ const changeKeyID = `change ${keyID}`
563
+ const { publicKey: identityKey } = await wallet.getPublicKey({ identityKey: true }, originator)
564
+ if (change > 0) {
565
+ const changeScript = await new MandalaToken(wallet as never, originator).lockBRC29(
566
+ asset.id,
567
+ change,
568
+ FT_PROTOCOL_ID,
569
+ changeKeyID,
570
+ identityKey
571
+ )
572
+ outputs.push({
573
+ satoshis: 1,
574
+ lockingScript: changeScript.toHex(),
575
+ outputDescription: 'Token change',
576
+ // Change comes back to THIS device, so it goes back in the basket. The
577
+ // payee's output deliberately does not: it is not ours to track.
578
+ basket,
579
+ customInstructions: JSON.stringify({
580
+ protocolID: FT_PROTOCOL_ID,
581
+ keyID: changeKeyID,
582
+ counterparty: identityKey,
583
+ direction: 'change'
584
+ })
585
+ })
184
586
  }
185
587
 
186
- if (!result.tx) throw new Error('createAction returned no transaction')
187
-
188
- // Authoritative amount off the transaction itself — covers send-max, where
189
- // `amount` was the sentinel and the wallet wrote the real figure to output 0.
190
- const paid = Transaction.fromAtomicBEEF(result.tx).outputs[0]?.satoshis
191
- if (typeof paid !== 'number' || paid <= 0) throw new Error('Could not determine paid amount')
192
-
193
- return {
194
- frame: {
195
- version: FRAME_VERSION,
196
- kind: 'bsv' as const,
197
- senderIdentityKey,
198
- outputIndex: 0,
199
- derivationPrefix: session.derivationPrefix,
200
- derivationSuffix: session.derivationSuffix,
201
- transaction: new Uint8Array(result.tx)
588
+ const created = await wallet.createAction(
589
+ {
590
+ // Same title discipline as the BSV path; the activity row overrides it
591
+ // with "Sent <ticker>" from the settlement row unless a note was given
592
+ // (WalletHomeScreen.tsx). The 'mandala' label is what makes the row
593
+ // recognise a token row at all — the home screen keys off that label,
594
+ // and without it a nearby token payment rendered as a BSV row — the
595
+ // payee's key over "+0 sats" (2026-09-16). The payee key stays on as a
596
+ // label for the resend path.
597
+ description: note?.trim() || 'Sent token',
598
+ labels: [PEERPAY_LABEL, session.identityKey, MANDALA_ACTION_LABEL],
599
+ inputBEEF: sourceBeef.toBinary(),
600
+ inputs: selected.map(coin => ({
601
+ outpoint: coin.outpoint,
602
+ unlockingScriptLength: 108,
603
+ inputDescription: 'spend token'
604
+ })),
605
+ outputs,
606
+ options: { randomizeOutputs: false, noSend: true, signAndProcess: false }
202
607
  },
203
- reference,
204
- txid: result.txid,
205
- satoshis: paid
608
+ originator
609
+ )
610
+
611
+ const signable = created.signableTransaction
612
+ if (!signable?.tx) throw new Error('createAction returned no signable token transaction')
613
+ const signableTx = signable.tx
614
+
615
+ return await releasingOnFailure(wallet, signable.reference, originator, async () => {
616
+ const unsigned = Transaction.fromBEEF(signableTx)
617
+
618
+ // Input order is caller order — `randomizeOutputs` shuffles outputs only, and
619
+ // it is off here anyway — so our coins occupy indices 0..n-1 and the wallet's
620
+ // own fee inputs follow. Each is signed individually rather than through
621
+ // `tx.sign()`, which would also reach inputs that are the wallet's to sign.
622
+ const spends: Record<string, { unlockingScript: string }> = {}
623
+ for (let i = 0; i < selected.length; i++) {
624
+ const script = await signTokenInput(wallet, unsigned, i, selected[i], sourceBeef, originator)
625
+ spends[String(i)] = { unlockingScript: script.toHex() }
626
+ }
627
+
628
+ const signed = await wallet.signAction(
629
+ { reference: signable.reference, spends, options: { noSend: true } },
630
+ originator
631
+ )
632
+ if (!signed.tx) throw new Error('signAction returned no transaction')
633
+
634
+ const tipTx = Transaction.fromAtomicBEEF(signed.tx)
635
+ const tipTxid = signed.txid ?? tipTx.id('hex')
636
+
637
+ // Promote the payee's blinding reservation (minted back in `lockToPayee`,
638
+ // before this txid existed) now that one does. Best-effort and after the
639
+ // fact: the payment is already signed, so a commit failure here must not
640
+ // fail it — it only costs this device's own later recovery of r, and the
641
+ // reservation is still there for `pruneBlindingReservations` to sweep.
642
+ if (deps.commitBlinding) {
643
+ try {
644
+ await deps.commitBlinding(keyID, tipTxid)
645
+ } catch (e) {
646
+ console.warn('[localpay] blindingCommit failed:', messageOf(e))
647
+ }
648
+ }
649
+
650
+ // The bundle covers the ANCESTORS; the tip's own payload is minted here,
651
+ // because only this function knows which outputs it just created and under
652
+ // which keys.
653
+ const bundle = await assembleBundle({
654
+ tipTx,
655
+ assetId: asset.id,
656
+ overlayIdentityKey: asset.overlayIdentityKey,
657
+ store: deps.store
658
+ })
659
+ const tipLinkage = await mintTipLinkage(wallet, {
660
+ inputs: selected,
661
+ payeeLinkage: payee.linkage,
662
+ changeKeyID: change > 0 ? changeKeyID : undefined,
663
+ changeCounterparty: identityKey,
664
+ overlayIdentityKey: asset.overlayIdentityKey,
665
+ originator
666
+ })
667
+
668
+ const paid = tipTx.outputs[0]?.satoshis
669
+ return {
670
+ frame: {
671
+ version: FRAME_VERSION,
672
+ kind: 'token' as const,
673
+ // A′, never A. `lockToPayee` is the only thing that knows it.
674
+ senderIdentityKey: payee.senderIdentityKey,
675
+ outputIndex: 0,
676
+ derivationPrefix: session.derivationPrefix,
677
+ derivationSuffix: session.derivationSuffix,
678
+ token: {
679
+ assetId: asset.id,
680
+ overlayUrl: asset.overlayUrl,
681
+ overlayIdentityKey: asset.overlayIdentityKey,
682
+ certificates: deps.certificates ?? [],
683
+ // The tip goes first: it is the one entry every recipient of this frame
684
+ // needs, whatever else the chain behind it looks like.
685
+ linkage: [{ txid: tipTxid, payload: tipLinkage }, ...bundle.linkage],
686
+ admissions: bundle.admissions
687
+ },
688
+ ...(note?.trim() ? { note: note.trim() } : {}),
689
+ transaction: new Uint8Array(signed.tx)
690
+ },
691
+ reference: signable.reference,
692
+ txid: tipTxid,
693
+ satoshis: typeof paid === 'number' ? paid : 1,
694
+ tokenAmount: amount
695
+ }
696
+ })
697
+ }
698
+
699
+ function parseCustomInstructions(text?: string): { keyID?: string; counterparty?: string } {
700
+ if (!text) return {}
701
+ try {
702
+ const parsed = JSON.parse(text) as Record<string, unknown>
703
+ return {
704
+ keyID: typeof parsed.keyID === 'string' ? parsed.keyID : undefined,
705
+ counterparty: typeof parsed.counterparty === 'string' ? parsed.counterparty : undefined
706
+ }
707
+ } catch {
708
+ // A coin whose instructions are unreadable cannot be unlocked, but that is
709
+ // the signer's failure to report, not this parser's — it would be worse to
710
+ // drop the coin silently and tell the user they are short of funds.
711
+ return {}
206
712
  }
207
713
  }
208
714
 
715
+ /**
716
+ * Signs one token input through the wallet (BRC-100 `createSignature`).
717
+ *
718
+ * `MandalaToken.unlock` in `@bsv/templates` signs with a raw `PrivateKey`,
719
+ * which a BRC-100 wallet never exports. This is the same construction driven
720
+ * through the wallet instead: the sighash preimage is built identically, the
721
+ * wallet signs its double-SHA256 under the FT protocol and the coin's own
722
+ * keyID, and the public key that goes in the script is the `forSelf: true`
723
+ * derivation — the key the LOCKER hashed, by BRC-42 symmetry. For a coin
724
+ * another party locked to us, only `forSelf: true` matches the pubKeyHash.
725
+ */
726
+ async function signTokenInput(
727
+ wallet: PayingWallet,
728
+ tx: Transaction,
729
+ inputIndex: number,
730
+ coin: SelectedTokenCoin,
731
+ sources: Beef,
732
+ originator: string
733
+ ): Promise<UnlockingScript> {
734
+ const input = tx.inputs[inputIndex]
735
+ if (!input) throw new Error(`the signable transaction has no input ${inputIndex}`)
736
+ const [coinTxid, coinVout] = coin.outpoint.split('.')
737
+ const sourceTx = input.sourceTransaction ?? sources.findTxid(coinTxid)?.tx
738
+ const sourceOutput = sourceTx?.outputs[input.sourceOutputIndex ?? Number(coinVout)]
739
+ if (!sourceOutput?.lockingScript || sourceOutput.satoshis == null) {
740
+ throw new Error(`cannot sign token input ${inputIndex}: its source output is missing`)
741
+ }
742
+
743
+ const scope = TransactionSignature.SIGHASH_FORKID | TransactionSignature.SIGHASH_ALL
744
+ const preimage = TransactionSignature.format({
745
+ sourceTXID: input.sourceTXID ?? coinTxid,
746
+ sourceOutputIndex: input.sourceOutputIndex ?? Number(coinVout),
747
+ sourceSatoshis: sourceOutput.satoshis,
748
+ transactionVersion: tx.version,
749
+ otherInputs: tx.inputs.filter((_, i) => i !== inputIndex),
750
+ inputIndex,
751
+ outputs: tx.outputs,
752
+ inputSequence: input.sequence ?? 0xffffffff,
753
+ subscript: sourceOutput.lockingScript,
754
+ lockTime: tx.lockTime,
755
+ scope
756
+ })
757
+
758
+ const { signature: der } = await (wallet.createSignature as NonNullable<PayingWallet['createSignature']>)(
759
+ {
760
+ hashToDirectlySign: Hash.hash256(preimage),
761
+ protocolID: FT_PROTOCOL_ID,
762
+ keyID: coin.keyID,
763
+ counterparty: coin.counterparty
764
+ },
765
+ originator
766
+ )
767
+ const sig = Signature.fromDER([...der])
768
+ const sigForScript = new TransactionSignature(sig.r, sig.s, scope).toChecksigFormat()
769
+ const { publicKey } = await wallet.getPublicKey(
770
+ { protocolID: FT_PROTOCOL_ID, keyID: coin.keyID, counterparty: coin.counterparty, forSelf: true },
771
+ originator
772
+ )
773
+ const pubkey = Utils.toArray(publicKey, 'hex')
774
+ return new UnlockingScript([
775
+ { op: sigForScript.length, data: sigForScript },
776
+ { op: pubkey.length, data: pubkey }
777
+ ])
778
+ }
779
+
780
+ /**
781
+ * The tip's own `MandalaLinkagePayload` — the exact off-chain bytes the
782
+ * overlay's `/submit` consumes, UTF-8 JSON of
783
+ * `{ inputs: [{index, linkage}], outputs: [{index, linkage}] }`.
784
+ *
785
+ * EVERY token output needs its own entry: an unlinked one is skipped by the
786
+ * overlay's topic manager and breaks its conservation check, which refuses the
787
+ * whole transaction. Inputs are revealed so the overlay can screen the SENDER
788
+ * under an allowlist or denylist asset — omit them and a denylist asset still
789
+ * admits, but sender screening silently degrades.
790
+ *
791
+ * The verifier on every reveal is the OVERLAY's key, never the payee's: these
792
+ * are BRC-72 blobs only the prover and the named verifier can decrypt. The
793
+ * payee carries them, forwards them verbatim on a re-spend, and can read none
794
+ * of them.
795
+ */
796
+ async function mintTipLinkage(
797
+ wallet: PayingWallet,
798
+ args: {
799
+ inputs: SelectedTokenCoin[]
800
+ payeeLinkage: unknown
801
+ changeKeyID?: string
802
+ changeCounterparty: string
803
+ overlayIdentityKey: string
804
+ originator: string
805
+ }
806
+ ): Promise<Uint8Array> {
807
+ const reveal = wallet.revealSpecificKeyLinkage as NonNullable<PayingWallet['revealSpecificKeyLinkage']>
808
+ const forOverlay = (keyID: string, counterparty: string) =>
809
+ reveal(
810
+ { counterparty, verifier: args.overlayIdentityKey, protocolID: FT_PROTOCOL_ID, keyID },
811
+ args.originator
812
+ )
813
+
814
+ const outputs: { index: number; linkage: unknown }[] = [{ index: 0, linkage: args.payeeLinkage }]
815
+ if (args.changeKeyID !== undefined) {
816
+ outputs.push({ index: 1, linkage: await forOverlay(args.changeKeyID, args.changeCounterparty) })
817
+ }
818
+ const inputs: { index: number; linkage: unknown }[] = []
819
+ for (let i = 0; i < args.inputs.length; i++) {
820
+ inputs.push({ index: i, linkage: await forOverlay(args.inputs[i].keyID, args.inputs[i].counterparty) })
821
+ }
822
+
823
+ return new Uint8Array(Utils.toArray(JSON.stringify({ inputs, outputs }), 'utf8'))
824
+ }
825
+
209
826
  /**
210
827
  * Releases the `noSend` payment identified by `txid` so this device broadcasts it.
211
828
  *
@@ -378,6 +995,26 @@ export async function finalizeDelivery(
378
995
  }
379
996
  }
380
997
 
998
+ // GUARD #1 (offline-settlement spec §4.3). A token payment is NEVER
999
+ // broadcast from here, online or off.
1000
+ //
1001
+ // This is the structural half of "admission gates broadcast": `postTokenStep`
1002
+ // in the drain is the only path to a real broadcast for a token transaction,
1003
+ // and it gets there only after every ancestor in COVER's `mustSubmit` has
1004
+ // been admitted. Without this check the online payer falls straight through
1005
+ // to `sendWith` exactly as the BSV path does — with no `kind` check at all —
1006
+ // and puts an unadmitted token transaction on chain before any overlay has
1007
+ // seen it. The overlay can then only refuse it, and the coin is stranded
1008
+ // between "spent on chain" and "never admitted".
1009
+ //
1010
+ // Placed AFTER the hold on purpose: the hold is what creates the queue row
1011
+ // the drain owns and promotes `nosend → unproven` so this payment's change
1012
+ // can fund the next offline one. Skipping the broadcast is the whole change;
1013
+ // skipping the hold would strand the payment instead.
1014
+ if (built.frame?.kind === 'token') {
1015
+ return { kind: 'sent', broadcast: 'pending', detail: 'awaiting overlay admission' }
1016
+ }
1017
+
381
1018
  if (!isOnline) {
382
1019
  return { kind: 'sent', broadcast: 'pending', detail: 'offline — queued until this device reconnects' }
383
1020
  }