@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
@@ -55,86 +55,41 @@
55
55
  import { findOfflineActionByTxid, insertOfflineAction, updateOfflineAction } from '../storage/methods/offlineActions'
56
56
  import { TaskSendOffline } from '../monitor/TaskSendOffline'
57
57
  import { devLog } from '../logging'
58
- import { createSettlementStore, type SettlementDb } from '../mandala/settlementStore'
59
- import type { EvidenceFrame, TokenHandedOverHook } from '../mandala/types'
58
+ import type { NearbyTokenDeps } from '../mandala/runtime'
60
59
  import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
61
60
 
62
61
  /**
63
- * The PLAINTEXT frame and the hook that persists what it carries.
62
+ * The token half of a payer hold (plan 07 Task 15).
64
63
  *
65
- * `framePayload` is the frame SEALED with the nearby session's pre-shared key,
66
- * and `offline/tokenFrames.ts` keeps that key IN MEMORY ONLY, deliberately — a
67
- * durable copy of the key that opens every stored frame is exactly what nobody
68
- * wants on disk. The consequence, until now, was that the payer's own
69
- * `token_settlements` row existed only as a re-derivation from bytes it could
70
- * no longer open after a restart: no row, and `processOfflineActions` reads the
71
- * absence as "this is an ordinary BSV transaction" and broadcasts an unadmitted
72
- * token tip.
73
- *
74
- * So the frame is handed over here, while it is still open, and the row plus
75
- * its evidence are written from it. `tokenFrames.ts` stays exactly as it was —
76
- * a best-effort fallback for the rows this process still holds a key for.
64
+ * A nearby token payment's durable host record is its `color_transfers` row,
65
+ * journaled `built` by the runtime's `nearby.handover` before any frame
66
+ * existed. Park, hold and release only move that row forward, through the
67
+ * runtime's `nearby.onHandedOver`: `parked` when the payer backed out
68
+ * without confirming, `handed_over` once the payee has (or is known to have)
69
+ * the frame. Nothing here needs the sealed `framePayload` or the session key
70
+ * that opens it. Absent on the BSV rail.
77
71
  */
78
72
  export interface TokenHandoverDeps {
79
- /** The open frame this hand-over is for. Absent on the BSV rail. */
80
- frame?: EvidenceFrame
81
- /** Implemented by the Mandala runtime; writes the row and the evidence. */
82
- onTokenHandedOver?: TokenHandedOverHook
83
- /**
84
- * The `createAction` reference of the action that built this tip
85
- * (`BuiltPayment.reference`), recorded on the settlement row so an
86
- * `abortAction` against it can be refused once the payee holds the frame.
87
- * See `core/mandala/abortGuard.ts` — a token action stays `noSend` until the
88
- * drain broadcasts it, so its reference is the one handle anything has on
89
- * money that is already gone.
90
- */
91
- reference?: string
92
- }
93
-
94
- /**
95
- * Advance this txid's settlement row `parked → handed_over` (§4.4, FIX F).
96
- *
97
- * The queue row's own `parked → queued` advance has a settlement twin, and it
98
- * has to be issued explicitly for the same reason the queue one did:
99
- * `upsertSettlement` never writes `state` on conflict (rule 1 in
100
- * `settlementStore.ts`), so a hook re-running over an existing `parked` row
101
- * leaves it `parked` — and `parked` is the one non-terminal state the drain
102
- * refuses to submit, by design (FIX F). Without this the payer's optional
103
- * submit (rule 6) could never start for a payment that was parked first.
104
- *
105
- * Best-effort, and it runs AFTER the queue row: the queue row is the durable
106
- * fact, a settlement row is a re-derivable cache (FIX G), and the drain's own
107
- * `reconcileSettlements` pass re-runs this population every tick. A wallet on a
108
- * schema without these tables simply logs.
109
- */
110
- async function advanceToHandedOver(storage: StorageExpoSQLite, txid: string): Promise<void> {
111
- const db = storage.sqliteDb
112
- if (!db) return
113
- try {
114
- await createSettlementStore(db as unknown as SettlementDb).advanceSettlement(txid, ['parked'], 'handed_over')
115
- } catch (e) {
116
- devLog(`[payerHold] could not advance the settlement row for ${txid} to handed_over:`, e)
117
- }
73
+ onHandedOver?: NearbyTokenDeps['onHandedOver']
118
74
  }
119
75
 
120
76
  /**
121
- * Persist what the plaintext frame carries, for the state this call just put
122
- * the payment in. Never throws — the caller decides what a failed journal
123
- * costs, from the boolean this returns, rather than finding out from a thrown
124
- * exception. `true` for a plain BSV hold (nothing to journal) and for a token
125
- * hold whose write landed; `false` only when a token hold's write did not.
77
+ * Move the journal row for the state this call just put the payment in. Never
78
+ * throws — the caller decides what a failed journal costs, from the boolean
79
+ * this returns. `true` for a plain BSV hold (nothing to journal) and for a
80
+ * token hold whose write landed; `false` only when a token hold's did not.
126
81
  */
127
82
  async function journalHandover(
128
83
  deps: TokenHandoverDeps,
129
84
  txid: string,
130
85
  state: 'parked' | 'handed_over'
131
86
  ): Promise<boolean> {
132
- if (!deps.frame?.token || !deps.onTokenHandedOver) return true
87
+ if (!deps.onHandedOver) return true
133
88
  try {
134
- await deps.onTokenHandedOver(deps.frame, txid, state, deps.reference)
89
+ await deps.onHandedOver(txid, state)
135
90
  return true
136
91
  } catch (e) {
137
- devLog(`[payerHold] could not journal the ${state} settlement for ${txid}:`, e)
92
+ devLog(`[payerHold] could not journal ${txid} as ${state}:`, e)
138
93
  return false
139
94
  }
140
95
  }
@@ -152,17 +107,16 @@ async function journalHandover(
152
107
  const ADVANCEABLE_TO_QUEUED = new Set(['parked', 'queued'])
153
108
 
154
109
  /**
155
- * XR-036: whether this hold has a settlement row to wait for at all.
156
- *
157
- * `processOfflineActions.ts`'s `readSettlement` tells "ordinary BSV" from
158
- * "token, needs overlay admission first" by whether ANY `token_settlements`
159
- * row exists for the txid — so a token hold's queue row may not be promoted
160
- * to 'queued' (which wakes the drain) until `journalHandover` has actually
161
- * written that row. A plain BSV hold has no such row to wait for and keeps
162
- * its old, immediate promotion.
110
+ * XR-036, re-keyed onto the journal: whether this hold has a journal row to
111
+ * move before its queue row may wake the drain. The broadcast hold already
112
+ * holds any 1Color tx whose row is not `settled` (W1), so this is no longer
113
+ * what keeps a token tx off the network; it is what keeps a queue row from
114
+ * reading "queued" for a payment whose journal never said it was handed over,
115
+ * which nothing would then settle. A plain BSV hold keeps its immediate
116
+ * promotion.
163
117
  */
164
118
  function isTokenHold(deps: TokenHandoverDeps): boolean {
165
- return !!(deps.frame?.token && deps.onTokenHandedOver)
119
+ return deps.onHandedOver !== undefined
166
120
  }
167
121
 
168
122
  export async function holdSentPaymentOffline(
@@ -207,25 +161,23 @@ export async function holdSentPaymentOffline(
207
161
  return
208
162
  }
209
163
  if (isTokenHold(args)) {
210
- // XR-036: do NOT wake the drain until the settlement row is durable —
164
+ // XR-036: do NOT wake the drain until the journal reads handed_over —
211
165
  // leave the row exactly where a park would (non-drainable) if the write
212
- // fails, rather than handing the drain a 'queued' row with nothing in
213
- // `token_settlements` to stop it reading this as plain BSV.
166
+ // fails.
214
167
  const journaled = await journalHandover(args, txid, 'handed_over')
215
168
  if (journaled) {
216
169
  await updateOfflineAction(db, txid, { status: 'queued' })
217
170
  TaskSendOffline.noteEnqueued()
218
171
  } else {
219
- devLog(`[holdSentPaymentOffline] ${txid} left '${existing.status}': its settlement could not be journaled`)
172
+ devLog(`[holdSentPaymentOffline] ${txid} left '${existing.status}': its hand-over could not be journaled`)
220
173
  }
221
174
  } else {
222
175
  // Same two writes and the same order as before: the durable row first,
223
176
  // the promotion after — unchanged for the plain BSV rail, which has no
224
- // settlement row to wait for.
177
+ // journal row to wait for.
225
178
  await updateOfflineAction(db, txid, { status: 'queued' })
226
179
  TaskSendOffline.noteEnqueued()
227
180
  }
228
- await advanceToHandedOver(storage, txid)
229
181
  // Only while still withheld: if the payee already broadcast and this device
230
182
  // saw it, the transaction has moved on and this write would be a lie.
231
183
  if (tx.status === 'nosend') await storage.updateTransactionStatus('unproven', tx.transactionId)
@@ -235,19 +187,17 @@ export async function holdSentPaymentOffline(
235
187
  if (isTokenHold(args)) {
236
188
  // XR-036: insert at 'parked' — durable (`findOfflineActions` never reads
237
189
  // it, so the drain leaves it alone), and NOT promoted to 'queued' until
238
- // `journalHandover`'s write to `token_settlements` has actually landed.
239
- // Without this, a process kill or a transient write fault right here left
240
- // a 'queued' row with no settlement to match it, and
241
- // `processOfflineActions`'s `readSettlement` reads that absence as "this
242
- // is an ordinary BSV transaction" and posts it straight past overlay
243
- // admission (§4.3).
190
+ // the journal reads handed_over. A process kill or a transient write
191
+ // fault right here leaves a parked row the payer can still release or
192
+ // cancel, never a queued one for a payment the journal does not know was
193
+ // handed over.
244
194
  await insertOfflineAction(db, { userId: tx.userId, txid, role: 'sent', framePayload }, 'parked')
245
195
  const journaled = await journalHandover(args, txid, 'handed_over')
246
196
  if (journaled) {
247
197
  await updateOfflineAction(db, txid, { status: 'queued' })
248
198
  TaskSendOffline.noteEnqueued()
249
199
  } else {
250
- devLog(`[holdSentPaymentOffline] ${txid} left 'parked': its settlement could not be journaled`)
200
+ devLog(`[holdSentPaymentOffline] ${txid} left 'parked': its hand-over could not be journaled`)
251
201
  }
252
202
  } else {
253
203
  // Insert before promote — see the ORDER MATTERS note above. Unchanged for
@@ -255,7 +205,6 @@ export async function holdSentPaymentOffline(
255
205
  await insertOfflineAction(db, { userId: tx.userId, txid, role: 'sent', framePayload })
256
206
  TaskSendOffline.noteEnqueued()
257
207
  }
258
- await advanceToHandedOver(storage, txid)
259
208
  await storage.updateTransactionStatus('unproven', tx.transactionId)
260
209
  }
261
210
 
@@ -291,46 +240,33 @@ export async function parkSentPaymentOffline(
291
240
  // No promote, and no TaskSendOffline.noteEnqueued(): both are what turn a
292
241
  // stored frame into a broadcast.
293
242
  await insertOfflineAction(db, { userId: tx.userId, txid, role: 'sent', framePayload }, 'parked')
294
- // The row is written at `parked`, which the drain will never submit (FIX F) —
295
- // but it EXISTS, which is what `processOfflineActions` and
296
- // `attemptToPostReqsToNetwork` both key their token branch on. That is the
297
- // durability this call buys and the sealed `framePayload` cannot: after a
298
- // restart the session PSK is gone and these bytes can no longer be opened.
299
- //
300
- // XR-036 review follow-up: this used to discard journalHandover's result,
301
- // so nothing downstream could tell a landed token journal from a silently
302
- // failed one. Returned now so a caller (and `releaseParkedPayment`'s own
303
- // settlement check) has something to act on. A plain BSV park still
304
- // resolves `true` (there is nothing to journal).
243
+ // The queue row is written at `parked`, which the drain never posts, and
244
+ // the journal row moves to `parked`, which nobody settles (FIX F): the
245
+ // payer withheld this payment, and only the payer releases it. The result
246
+ // is returned so a caller can tell a landed journal from a failed one; a
247
+ // plain BSV park resolves `true` (there is nothing to journal).
305
248
  return journalHandover(args, txid, 'parked')
306
249
  }
307
250
 
308
251
  /**
309
252
  * Release a parked payment: the payer showed the code again and this time
310
- * confirmed the hand-over.
253
+ * confirmed the hand-over, or re-delivered it over the message box.
311
254
  *
312
255
  * The same two writes `holdSentPaymentOffline` makes, minus the insert — the
313
256
  * row already exists from parking, so it is flipped to 'queued' instead. Same
314
257
  * order for the same reason: the durable row moves first, the promotion after.
315
258
  *
316
- * XR-036 review follow-up: no frame is threaded here (the row already exists
317
- * from the park), so this cannot re-attempt `journalHandover` the way a second
318
- * `holdSentPaymentOffline` confirm can. What it CAN and must do is refuse to
319
- * repeat XR-036's own defect through this second entry point: a token-bearing
320
- * park whose `journalHandover(..., 'parked')` write silently failed (see
321
- * `parkSentPaymentOffline`) has no `token_settlements` row, and
322
- * `processOfflineActions`'s `readSettlement` reads that absence as "ordinary
323
- * BSV" and posts it straight past overlay admission. `isTokenHold` is the
324
- * caller's own knowledge of which rail this txid took (WalletHomeScreen.tsx's
325
- * resend flow already derives it from the action's 'mandala' label); when set,
326
- * the row is only promoted once a settlement row proves the park-time journal
327
- * actually landed, otherwise it is left at 'parked' exactly like a fresh
328
- * journal failure in `holdSentPaymentOffline`.
259
+ * A token park (`isTokenHold`, which the caller knows from the action's
260
+ * 'mandala' label) is released only through the journal: `onHandedOver`
261
+ * moves its row to `handed_over` first, and when that hook is missing or
262
+ * fails the queue row is left parked. A queued row whose journal never says
263
+ * handed_over is a payment nothing would settle.
329
264
  */
330
265
  export async function releaseParkedPayment(args: {
331
266
  storage: StorageExpoSQLite
332
267
  txid: string
333
268
  isTokenHold?: boolean
269
+ onHandedOver?: NearbyTokenDeps['onHandedOver']
334
270
  }): Promise<void> {
335
271
  const { storage, txid, isTokenHold } = args
336
272
  const db = storage.sqliteDb
@@ -340,20 +276,18 @@ export async function releaseParkedPayment(args: {
340
276
  if (!tx) throw new Error(`no transaction record for ${txid}, cannot release it`)
341
277
 
342
278
  if (isTokenHold) {
343
- const settlement = await createSettlementStore(db as unknown as SettlementDb).getSettlement(txid)
344
- if (!settlement) {
345
- devLog(`[releaseParkedPayment] ${txid} left 'parked': no settlement row to release a token hold from`)
279
+ if (!args.onHandedOver) {
280
+ devLog(`[releaseParkedPayment] ${txid} left 'parked': no journal hook to release a token hold through`)
281
+ return
282
+ }
283
+ if (!(await journalHandover({ onHandedOver: args.onHandedOver }, txid, 'handed_over'))) {
284
+ devLog(`[releaseParkedPayment] ${txid} left 'parked': its hand-over could not be journaled`)
346
285
  return
347
286
  }
348
287
  }
349
288
 
350
289
  await updateOfflineAction(db, txid, { status: 'queued' })
351
290
  TaskSendOffline.noteEnqueued()
352
- // The settlement twin of the line above (§4.4). No frame is threaded here —
353
- // this is the re-show-and-confirm path, and the row was already written from
354
- // the plaintext frame when the payment was parked — so the state advance is
355
- // the whole of it.
356
- await advanceToHandedOver(storage, txid)
357
291
  // Already promoted if the payee broadcast and this device saw it; the write
358
292
  // is only correct while the transaction is still being withheld.
359
293
  if (tx.status === 'nosend') await storage.updateTransactionStatus('unproven', tx.transactionId)
@@ -6,12 +6,12 @@ import { trimTrailingSlashes } from './net/trimTrailingSlashes'
6
6
  *
7
7
  * peerpay-URI = "peerpay:" identity-key [ "?" query ]
8
8
  * sats-param = "sats=" 1*DIGIT
9
- * asset-param = "asset=" 64HEXDIG "." 1*DIGIT ; the asset's genesis outpoint
10
- * amount-param = "amount=" 1*DIGIT ; BASE UNITS of that asset
9
+ * asset-param = "asset=" 64HEXDIG "_0" ; the BRC-162 token id
10
+ * amount-param = "amount=" ("0" / %x31-39 *DIGIT) ; BASE UNITS of that asset, ≤ 2^64-1
11
11
  *
12
- * `sats` is the BSV selector. `asset` names a token by its genesis outpoint —
13
- * the one identifier every issuer's asset already has — and `amount` is a
14
- * figure in that token's own base units, so it only means anything beside an
12
+ * `sats` is the BSV selector. `asset` names a token by its BRC-162 id — the
13
+ * one identifier every issuer's asset already has — and `amount` is an exact
14
+ * figure (a `bigint`) in that token's own base units, so it only means anything beside an
15
15
  * `asset`. Both are optional: `asset` alone is an open token request, where
16
16
  * the payer chooses the figure. A link mixing `sats` with either is refused
17
17
  * rather than read in one money or the other (maintainer decision, 2026-09-15).
@@ -42,10 +42,10 @@ export function cleanPeerPayNote(raw: string | null | undefined): string | undef
42
42
  export interface PeerPayParams {
43
43
  identityKey: string
44
44
  sats?: number
45
- /** The token's genesis outpoint, `txid.vout`, lowercased. */
45
+ /** The token id, `<64 hex>_0`, lowercased. */
46
46
  asset?: string
47
- /** Base units of `asset`. Never present without it. */
48
- amount?: number
47
+ /** Exact base units of `asset` (1..2^64-1). Never present without it. */
48
+ amount?: bigint
49
49
  messageBoxUrl?: string
50
50
  /** What it's for, as the payee wrote it (the `note` extension). */
51
51
  note?: string
@@ -56,7 +56,7 @@ export interface PeerPayValidationResult {
56
56
  identityKey?: string
57
57
  sats?: number
58
58
  asset?: string
59
- amount?: number
59
+ amount?: bigint
60
60
  /** Present only when the link carried a usable https `url` extension. */
61
61
  messageBoxUrl?: string
62
62
  /** Present only when the link carried a non-empty `note` extension. */
@@ -122,7 +122,7 @@ export function validatePeerPayURI(uri: string): PeerPayValidationResult {
122
122
 
123
123
  let sats: number | undefined
124
124
  let asset: string | undefined
125
- let amount: number | undefined
125
+ let amount: bigint | undefined
126
126
  let messageBoxUrl: string | undefined
127
127
  let note: string | undefined
128
128
  if (queryPart) {
@@ -138,10 +138,10 @@ export function validatePeerPayURI(uri: string): PeerPayValidationResult {
138
138
  else errors.asset = 'PeerPay link names an invalid asset'
139
139
  }
140
140
  if (params.has('amount')) {
141
- const figure = wholeFigure(params.get('amount') ?? '')
141
+ const figure = tokenFigure(params.get('amount') ?? '')
142
142
  if (figure === null) errors.amount = 'PeerPay link contains an invalid amount'
143
143
  else if (!params.has('asset')) errors.amount = 'PeerPay link names an amount without an asset'
144
- else if (figure > 0) amount = figure
144
+ else if (figure > 0n) amount = figure
145
145
  }
146
146
  // Two selectors for two different monies: refused, never read as either.
147
147
  if (params.has('sats') && (params.has('asset') || params.has('amount'))) {
@@ -172,6 +172,19 @@ export function peerPayValidationMessage(result: PeerPayValidationResult | null)
172
172
  return messages.length ? messages.join('. ') : null
173
173
  }
174
174
 
175
+ /** 2^64-1: the largest amount one token output can carry (BRC-162). */
176
+ const MAX_TOKEN_FIGURE = 18446744073709551615n
177
+
178
+ /**
179
+ * An exact token figure from a query value: a canonical decimal string (IC §0)
180
+ * no larger than 2^64-1, or null for anything else. Never through a float.
181
+ */
182
+ function tokenFigure(text: string): bigint | null {
183
+ if (!WHOLE_FIGURE_REGEX.test(text)) return null
184
+ const figure = BigInt(text)
185
+ return figure <= MAX_TOKEN_FIGURE ? figure : null
186
+ }
187
+
175
188
  /** A whole safe integer from a query value, or null for anything else. */
176
189
  function wholeFigure(text: string): number | null {
177
190
  if (!WHOLE_FIGURE_REGEX.test(text)) return null
@@ -57,6 +57,7 @@ import { markOutboxSent, saveOutboxEntry, updateOutboxEntry } from '../../peerpa
57
57
  import { TaskDrainOutbox } from '../../monitor/TaskDrainOutbox'
58
58
  import { NotSentError } from '../../directpay/payFlow'
59
59
  import { dialFailure } from '../../directpay/dialFailure'
60
+ import { MAX_LIVE_TRANSACTION_BYTES } from '../../directpay/settings'
60
61
  import type { DirectPayClientLike, DirectPaymentAck, DirectPeer, WebRTPayModule } from '../../directpay/webrtpay'
61
62
 
62
63
  interface StorageLike {
@@ -246,10 +247,13 @@ function whyNotDeliverable(
246
247
  ): NotSentError | undefined {
247
248
  if (signal?.aborted) return new NotSentError('Cancelled', '', 'aborted')
248
249
  const bytes = token.transaction.length
249
- if (bytes > webrtpay.MAX_DIRECT_TRANSACTION_BYTES) {
250
+ // Live payments carry at most 1 MB (MAX_LIVE_TRANSACTION_BYTES), below the package's own cap.
251
+ const limit = Math.min(MAX_LIVE_TRANSACTION_BYTES, webrtpay.MAX_DIRECT_TRANSACTION_BYTES)
252
+ if (bytes > limit) {
250
253
  return new NotSentError(
251
254
  'This payment is too large to deliver directly',
252
- `${bytes} bytes; at most ${webrtpay.MAX_DIRECT_TRANSACTION_BYTES} can go over the link`
255
+ `${bytes} bytes; at most ${limit} can go over the link`,
256
+ 'too_large'
253
257
  )
254
258
  }
255
259
  try {
@@ -144,7 +144,7 @@ interface InternalizingWallet {
144
144
  * A shareable BRC-125 payment link for a handle.
145
145
  *
146
146
  * `peerpay:<key>[?sats=<n>][&url=<host>]` for BSV, or
147
- * `peerpay:<key>?asset=<txid.vout>[&amount=<base units>][&url=<host>]` for a
147
+ * `peerpay:<key>?asset=<txid>_0[&amount=<base units, exact decimal>][&url=<host>]` for a
148
148
  * token — the same forms the app parses (parsePeerPayURI.ts) and routes
149
149
  * (+native-intent.ts in the host app). A non-positive figure emits no
150
150
  * `sats`/`amount` — a zero would be an invalid link, and an open request is
@@ -157,15 +157,16 @@ export function peerPayLinkFor(
157
157
  identityKey: string,
158
158
  sats?: number,
159
159
  messageBoxUrl?: string,
160
- token?: { assetId: string; baseUnits?: number },
160
+ token?: { assetId: string; units?: bigint },
161
161
  /** what it's for: the link's `note` extension (see parsePeerPayURI.ts) */
162
162
  note?: string
163
163
  ): string {
164
164
  const params: string[] = []
165
165
  if (token) {
166
166
  params.push(`asset=${token.assetId.toLowerCase()}`)
167
- const units = token.baseUnits !== undefined ? Math.round(Number(token.baseUnits)) : NaN
168
- if (Number.isFinite(units) && units > 0) params.push(`amount=${units}`)
167
+ // Exact: a bigint's decimal string, never through a float (IC §0).
168
+ const units = token.units
169
+ if (typeof units === 'bigint' && units > 0n) params.push(`amount=${units.toString()}`)
169
170
  } else {
170
171
  const amount = sats !== undefined ? Math.round(Number(sats)) : NaN
171
172
  if (Number.isFinite(amount) && amount > 0) params.push(`sats=${amount}`)
@@ -832,13 +833,12 @@ export function isAbortSafe(
832
833
  // ── The token half of the handle rail (offline-settlement spec §4.5) ──
833
834
  //
834
835
  // Same rail, different pipeline. A satoshi payment is minted here and delivered
835
- // through the `payment_inbox` PeerPay box; a Mandala token payment is minted by
836
- // `@bsv/mandala`'s own overlay-first transfer and delivered through the
837
- // `'mandala-payments'` box — and unlike the nearby rail, the handle rail's
838
- // SENDER is online by construction, so it submits before it notifies and can
839
- // forward the tip's own σ_I in the body. That is why `TokenSendResult` carries
840
- // `settled`: it is the difference between "sent · settling" and "sent · settled
841
- // with {{issuer}}" on the payer's screen, decided by evidence rather than hope.
836
+ // through the `payment_inbox` PeerPay box; a token payment is a BRC-207
837
+ // hand-over the color module signs `noSend`, delivered on the `mandala-color`
838
+ // box (IC §7.2) and only then settled with the issuer's overlay (the delivery
839
+ // is the ACK). That is why `TokenSendResult` carries `settled` (admitted before
840
+ // the call returned) and `notified` (the delivery went through; when it did
841
+ // not, the runtime's tick redelivers it, and sending again would pay twice).
842
842
  //
843
843
  // Neither function reaches into the runtime's internals: both take the
844
844
  // narrowest slice of `MandalaRuntime` they need, so this module keeps knowing
@@ -862,15 +862,16 @@ export async function sendTokenViaHandle(args: {
862
862
  runtime: HandleTokenRuntime | undefined
863
863
  recipient: string
864
864
  assetId: string
865
- baseUnits: number
865
+ units: bigint
866
+ note?: string
866
867
  }): Promise<TokenSendResult> {
867
- const { runtime, recipient, assetId, baseUnits } = args
868
+ const { runtime, recipient, assetId, units, note } = args
868
869
  if (!runtime?.available) {
869
870
  return { kind: 'unavailable', message: 'Stablecoins are not available on this network' }
870
871
  }
871
872
  const refusal = runtime.recipientRefusal(recipient)
872
873
  if (refusal) return { kind: 'refused', code: 'ERR_RECIPIENT', message: refusal }
873
- return await runtime.sendToHandle({ assetId, recipientIdentityKey: recipient, baseUnits })
874
+ return await runtime.sendToHandle({ assetId, recipientIdentityKey: recipient, units, ...(note ? { note } : {}) })
874
875
  }
875
876
 
876
877
  /**
@@ -25,7 +25,7 @@ export type RailId = 'nearby' | 'handle' | 'address'
25
25
  /**
26
26
  * How a counterparty was identified. Each variant carries only what its rail
27
27
  * needs. A handle may carry a figure in exactly one money: `sats` (BSV), or
28
- * `asset` (a token's genesis outpoint) with `amount` in its base units —
28
+ * `asset` (a token id, `<64 hex>_0`) with `amount` in its exact base units —
29
29
  * `asset` alone is an open token request.
30
30
  */
31
31
  export type PayTarget =
@@ -35,7 +35,8 @@ export type PayTarget =
35
35
  identityKey: string
36
36
  sats?: number
37
37
  asset?: string
38
- amount?: number
38
+ /** Exact token base units (1..2^64-1). */
39
+ amount?: bigint
39
40
  messageBoxUrl?: string
40
41
  note?: string
41
42
  }
@@ -144,7 +145,8 @@ export type RecipientInput =
144
145
  identityKey: string
145
146
  sats?: number
146
147
  asset?: string
147
- amount?: number
148
+ /** Exact token base units (1..2^64-1). */
149
+ amount?: bigint
148
150
  messageBoxUrl?: string
149
151
  note?: string
150
152
  }
@@ -43,35 +43,36 @@ export {
43
43
  processPending,
44
44
  savePending,
45
45
  type PendingPayment,
46
- type TokenCreditedHook
46
+ type TokenReceiveHook
47
47
  } from '../../localpay/pending'
48
48
  /**
49
- * The two settlement-durability hooks the rail's callers wire (§4.2, §4.3).
49
+ * The token half of the rail (plan 07 Tasks 15–16).
50
50
  *
51
- * `TokenHeldHook` runs BEFORE the receiver's `internalizeAction`, so the
52
- * `token_settlements` row exists when guard #2 looks for it;
53
- * `TokenHandedOverHook` runs at the payer's park/hold with the frame still in
54
- * plaintext, so the payer's own row does not depend on a session key this
55
- * process only holds in memory. Re-exported here because the rail is the single
56
- * import site for nearby, and both are implemented by the Mandala runtime and
57
- * consumed by `processPending` / `holdSentPaymentOffline` respectively.
51
+ * Same three moves the BSV path makes — build, hand over, hold — with the
52
+ * color module doing the token work:
53
+ *
54
+ * · PAYER: `buildPaymentFrame` with `TokenBuildDeps` frames the runtime's
55
+ * `nearby.handover` (lib `sendHandover`, bound to the session's own
56
+ * remittance strings) as a v7 frame carrying the v4 hand-over body's
57
+ * members (IC §7.3). It submits NOTHING — hand-over comes first,
58
+ * unconditionally.
59
+ * `finalizeDelivery` then holds and returns `broadcast: 'pending'` for
60
+ * every token payment, online or off (guard #1); the screen calls
61
+ * `settleNow` after the payee's positive ack (W5), and only a verified
62
+ * admission ever releases the tx.
63
+ * · PAYEE: `verifyFramePayment` checks the frame (a value output of the
64
+ * session's asset, paying this device's `p color` key, with evidence that
65
+ * reaches σ by this device's K under offline COVER), and `processPending`
66
+ * hands it to the runtime's `nearby.accept` (lib `acceptHandover`: online
67
+ * submit or COVER, host-ledger record, then the plain BRC-207 receipt into
68
+ * `p color <assetTag>`); `nearby.onReceived` journals it held, settled or
69
+ * refused (Task 16, B7).
58
70
  */
59
- export type {
60
- AdmissionVerifier,
61
- EvidenceFrame,
62
- EvidenceTokenBlock,
63
- TokenHandedOverHook,
64
- TokenHandoverState,
65
- TokenHeldHook
66
- } from '../../mandala/types'
67
71
  export {
68
72
  buildPaymentFrame,
69
73
  finalizeDelivery,
70
- selectTokenCoins,
71
74
  type BuiltPayment,
72
75
  type DeliveryOutcome,
73
- type LockToPayee,
74
- type SelectedTokenCoin,
75
76
  type TokenBuildDeps
76
77
  } from '../../localpay/build'
77
78
  export {
@@ -83,79 +84,16 @@ export {
83
84
  type FrameVerifyKind,
84
85
  type VerifiedPayment
85
86
  } from '../../localpay/verify'
86
- /**
87
- * The token half of the rail (offline-settlement spec §9).
88
- *
89
- * Same three moves the BSV path makes — build, hand over, hold — with the
90
- * evidence that makes them safe offline attached to each:
91
- *
92
- * · PAYER: `buildPaymentFrame` with `TokenBuildDeps` selects from
93
- * `MANDALA_BASKET`, builds `noSend`, and attaches the AdmissionBundle
94
- * `assembleBundle` collected. It submits NOTHING — hand-over comes first,
95
- * unconditionally, so a face-to-face payment never waits on a network.
96
- * `finalizeDelivery` then holds and returns `broadcast: 'pending'` for
97
- * every token payment, online or off (guard #1): the drain is the only
98
- * path to a real broadcast, and only after admission.
99
- * · PAYEE: `verifyFramePayment` proves the output is ours and then runs
100
- * `coverFromFrame` against the injected verifier; a frame that fails COVER
101
- * is refused at hand-over with `'not_covered'`, exactly like a
102
- * `not_mine`/`unparseable` decode failure. A frame that passes is credited
103
- * by `processPending` as a basket insertion, and `onTokenCredited` is where
104
- * the settlement row and the frame's evidence are persisted.
105
- * · BOTH: `readSettlementAck` reads σ_I off the confirm channel — verified
106
- * before it is believed, absent if it does not (FIX H) — and
107
- * `tokenSendState` turns that into the payer's 'sent-settling' /
108
- * 'sent-settled' copy.
109
- */
110
- export {
111
- SETTLEMENT_ACK_PREFIX,
112
- decodeSettlementAck,
113
- encodeSettlementAck,
114
- readSettlementAck,
115
- tokenSendState,
116
- type SettlementAck,
117
- type TokenSendState,
118
- type VerifyAdmissionFn
119
- } from '../../localpay/settlementAck'
120
- export {
121
- MANDALA_BASKET,
122
- assembleBundle,
123
- coverFromFrame,
124
- tokenParentsOf,
125
- type AdmissionBundle,
126
- type BundleStore,
127
- type CoverBundle,
128
- type CoverTip,
129
- type CoverVerifier
130
- } from '../../mandala/bundle'
131
- /**
132
- * The session key the drain cannot hold for itself.
133
- *
134
- * A payer's `offline_actions.framePayload` is SEALED with the nearby session's
135
- * PSK, and the drain deliberately never persists that key — so the flow that
136
- * mints or scans a session hands it to `rememberSessionPsk` for this process's
137
- * lifetime, and the drain's decoder tries the keys it was given. See
138
- * `offline/tokenFrames.ts` for exactly what an unopened row costs (a race the
139
- * payer is always safe to lose: the RECIPIENT submits).
140
- */
141
- export {
142
- MAX_REMEMBERED_SESSION_KEYS,
143
- forgetSessionPsks,
144
- rememberSessionPsk,
145
- sealedFramePayloadDecoder
146
- } from '../../offline/tokenFrames'
147
87
  /**
148
88
  * The payer's three durability moves, all from one place.
149
89
  *
150
90
  * `holdSentPaymentOffline` was the only one re-exported here while
151
91
  * `parkSentPaymentOffline` and `releaseParkedPayment` were reached through the
152
92
  * package root — which is the second implementation path this module exists to
153
- * prevent. `holdSentPaymentOffline` and `parkSentPaymentOffline` take the same
154
- * `{ frame, onTokenHandedOver }` deps (they create the settlement row from the
155
- * plaintext frame); `releaseParkedPayment` takes none — the row already exists
156
- * from the park, so it only advances it parked → handed_over. All three are the
157
- * same fork of one decision (confirm now, keep for later, confirm later), so
158
- * they belong on one import site.
93
+ * prevent. All three take the runtime's `nearby.onHandedOver` on the token
94
+ * rail, which moves the payment's `color_transfers` row forward (parked, then
95
+ * handed_over). All three are the same fork of one decision (confirm now, keep
96
+ * for later, confirm later), so they belong on one import site.
159
97
  */
160
98
  export {
161
99
  holdSentPaymentOffline,