@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
@@ -0,0 +1,694 @@
1
+ /**
2
+ * The handle rail's token half (plan 07 Task 13): hand-over send, MessageBox
3
+ * redelivery and inbox receive over the `mandala-color` box (IC §7.2).
4
+ *
5
+ * `@bsv/mandala` builds, parses, verifies and settles (design §9 B7); the
6
+ * color module holds custody; the host ledger records what this host
7
+ * verified; this file only orders the steps and keeps the wallet's
8
+ * `color_transfers` journal true to them.
9
+ *
10
+ * Send, in this order (stability mandate):
11
+ * 1. Refuse what the request alone decides (amount domain, recipient) and a
12
+ * second send of the same asset while one is in flight. The latch is taken
13
+ * with no await before it, so a double tap sees it.
14
+ * 2. `sendHandover` builds and signs `noSend`, builds the envelope from the
15
+ * host wallet's own custody and records the hand-over `pending` in the
16
+ * host ledger. Nobody has the bytes yet.
17
+ * 3. Keep the v4 body (for redelivery), then journal the row `handed_over`
18
+ * (W4) BEFORE delivering: a lost MessageBox
19
+ * response may still have delivered, so from here the abort guard refuses
20
+ * and the broadcast hold holds. A crash before this insert leaves a signed
21
+ * action no recipient has seen; with no row the guard lets it be released.
22
+ * A journal FAULT here is answered by releasing the action, never by
23
+ * delivering bytes the journal does not know.
24
+ * 4. `deliverHandover`. Success is the ACK (IC §7.2) and is journaled.
25
+ * Failure is still `sent`: a second send would be a second payment. The
26
+ * tick redelivers it (`redeliverPending`).
27
+ * 5. Only a delivered hand-over is named to `settleNow` (post-ACK submit,
28
+ * B5), and only when online, raced against a timeout so a slow overlay
29
+ * never holds the payer's screen. The settle keeps running.
30
+ *
31
+ * Redelivery and resend send the v4 body kept at send time (`bodies`): the
32
+ * exact bytes, receipt fields and evidence the first delivery carried. They
33
+ * never contact the overlay. A resend reads the body, and opens the box,
34
+ * BEFORE it hands a parked payment over: a resend that cannot deliver leaves
35
+ * the row exactly as it found it.
36
+ *
37
+ * Receive runs the lib's recipient path with the host ledger (online submit,
38
+ * or offline COVER with the S1 hop checks), which records what it verified
39
+ * before the plain receipt is internalized. A credit is journaled `settled`
40
+ * when the ledger says σ was verified and `held` when it was credited on
41
+ * COVER evidence (`offline`); `settleNow`/the drain settles a held one.
42
+ */
43
+ import { Transaction, Utils, type WalletInterface } from '@bsv/sdk'
44
+ import {
45
+ MAX_UINT64,
46
+ deliverHandover,
47
+ receiveHandovers,
48
+ sendHandover,
49
+ type HandoverBodyV4,
50
+ type HandoverResult,
51
+ type HostLedger,
52
+ type MessageBoxLike,
53
+ type MessageBoxSender
54
+ } from '@bsv/mandala'
55
+ import { devLog } from '../logging'
56
+ import type { TokenSendResult, TokenSettleState } from './runtime'
57
+ import type { TransferJournal } from './transferJournal'
58
+ import type { ColorTransferRow, ColorTransferState } from './types'
59
+
60
+ /** The MessageBox surface the hand-over send and receive need, as one structural type. */
61
+ export type MandalaMessageBox = MessageBoxSender & MessageBoxLike
62
+
63
+ export interface HandleDeps {
64
+ /** The PUBLISHED manager, bound to the admin originator. */
65
+ wallet: WalletInterface
66
+ identityKey: () => Promise<string>
67
+ journal: TransferJournal
68
+ /** The host's UNDERLYING wallet: the hand-over envelope is built from its custody. */
69
+ hostWallet: WalletInterface
70
+ /** The host ledger shared with the issuer-v1 handler. */
71
+ ledger: HostLedger
72
+ /** The settler's `markSettled` (module flag, then journal row). */
73
+ markSettled: (txid: string) => Promise<void>
74
+ /** The v4 bodies of this device's own hand-overs, kept for redelivery. */
75
+ bodies: HandoverBodies
76
+ messageBox: () => Promise<MandalaMessageBox>
77
+ settleNow: (txid: string) => Promise<TokenSettleState>
78
+ isOnline: () => Promise<boolean>
79
+ /** Message ids this session already handled (the lib's dedupe set). */
80
+ processed: Set<string>
81
+ now: () => Date
82
+ /** Plain reason a recipient cannot receive tokens, or null. */
83
+ recipientRefusal: (recipient: string) => string | null
84
+ /**
85
+ * Moves `held` receipts to `settled` when the module inventory shows no
86
+ * unsettled record for them (the runtime's `reconcileHeld`). A view fault
87
+ * leaves them held.
88
+ */
89
+ reconcileHeld: (txids: readonly string[]) => Promise<void>
90
+ /** Journal or delivery state changed. */
91
+ onChange?: () => void
92
+ /** How long a send waits for its own settle before returning. Default 8 000 ms. */
93
+ settleTimeoutMs?: number
94
+ }
95
+
96
+ const DEFAULT_SETTLE_TIMEOUT_MS = 8_000
97
+
98
+ /**
99
+ * Where the v4 body of each own hand-over is kept for redelivery: the lib is
100
+ * run with `journal: false`, and the host ledger keeps the bytes but not the
101
+ * receipt fields or the σ / envelope evidence the body carries.
102
+ */
103
+ export interface HandoverBodies {
104
+ /** Durable before it resolves; a failure throws. */
105
+ put(txid: string, body: HandoverBodyV4): Promise<void>
106
+ /** The stored body, or undefined when there is none (or it is unreadable). */
107
+ get(txid: string): Promise<HandoverBodyV4 | undefined>
108
+ }
109
+
110
+ /** KV key of an own hand-over's v4 body. */
111
+ export function handoverBodyKey(txid: string): string {
112
+ return `bsvwallet.color.handover.${txid}`
113
+ }
114
+
115
+ /** `HandoverBodies` over the wallet's key-value table. */
116
+ export function createHandoverBodies(kv: {
117
+ getKeyValue(key: string): Promise<string | undefined>
118
+ setKeyValue(key: string, value: string): Promise<void>
119
+ }): HandoverBodies {
120
+ return {
121
+ put: async (txid, body) => {
122
+ await kv.setKeyValue(handoverBodyKey(txid), JSON.stringify(body))
123
+ },
124
+ get: async txid => {
125
+ const text = await kv.getKeyValue(handoverBodyKey(txid))
126
+ if (text === undefined) return undefined
127
+ try {
128
+ const body = JSON.parse(text) as HandoverBodyV4
129
+ return body?.v === 4 && body.kind === 'handover' ? body : undefined
130
+ } catch {
131
+ return undefined
132
+ }
133
+ }
134
+ }
135
+ }
136
+
137
+ /** The subject txid of a v4 body's AtomicBEEF, or undefined when unreadable. */
138
+ function bodyTxid(body: HandoverBodyV4): string | undefined {
139
+ try {
140
+ return Transaction.fromAtomicBEEF(Utils.toArray(body.transaction, 'hex')).id('hex')
141
+ } catch {
142
+ return undefined
143
+ }
144
+ }
145
+
146
+ /** Errors the module/lib throw for a profile or argument fault: a refusal, nothing was sent. */
147
+ const REFUSAL_ERROR_NAMES = new Set([
148
+ 'UnsupportedProfileError',
149
+ 'ProfileParamsError',
150
+ 'ProfileDataError',
151
+ // The user's own "no" at the spend prompt.
152
+ 'ColorConsentDeclinedError'
153
+ ])
154
+
155
+ // Per-deps state. One `HandleDeps` is built per runtime, so these are per
156
+ // runtime; a WeakMap lets a discarded runtime take its state with it.
157
+ const sendLatches = new WeakMap<HandleDeps, Set<string>>()
158
+ const deliveringTxids = new WeakMap<HandleDeps, Set<string>>()
159
+ const redeliverFlights = new WeakMap<HandleDeps, Promise<number>>()
160
+ const receiveFlights = new WeakMap<HandleDeps, Promise<{ credited: number; failed: number; incomplete?: true }>>()
161
+
162
+ function setOf(map: WeakMap<HandleDeps, Set<string>>, d: HandleDeps): Set<string> {
163
+ let s = map.get(d)
164
+ if (!s) {
165
+ s = new Set()
166
+ map.set(d, s)
167
+ }
168
+ return s
169
+ }
170
+
171
+ function notify(d: HandleDeps): void {
172
+ try {
173
+ d.onChange?.()
174
+ } catch (e) {
175
+ devLog('[mandala] handle: a change listener threw:', e)
176
+ }
177
+ }
178
+
179
+ const messageOf = (e: unknown): string => (e instanceof Error ? e.message : String(e))
180
+
181
+ /** `e.name`, or the `[ClassName] ` message marker a bridged error keeps (IC D22). */
182
+ function errorName(e: unknown): string | undefined {
183
+ const name = (e as { name?: unknown } | null)?.name
184
+ if (typeof name === 'string' && name !== 'Error') return name
185
+ return /^\[([A-Za-z]+Error)\]/.exec(messageOf(e))?.[1]
186
+ }
187
+
188
+ /** Maps a `sendHandover` throw on `.name` (IC §2.4, D22). */
189
+ export function sendErrorResult(e: unknown): TokenSendResult {
190
+ const name = errorName(e)
191
+ const message = messageOf(e)
192
+ if (name !== undefined && REFUSAL_ERROR_NAMES.has(name)) return { kind: 'refused', code: name, message }
193
+ if (name === 'ColorProviderError') {
194
+ const { code, transport } = e as { code?: unknown; transport?: unknown }
195
+ if (transport !== true) return { kind: 'refused', code: typeof code === 'string' ? code : name, message }
196
+ }
197
+ return { kind: 'unavailable', message }
198
+ }
199
+
200
+ /** `settleNow(txid)` when online, raced against the timeout. `undefined` when not asked or not answered. */
201
+ async function settleSoon(d: HandleDeps, txid: string): Promise<TokenSettleState | undefined> {
202
+ let online = false
203
+ try {
204
+ online = await d.isOnline()
205
+ } catch (e) {
206
+ devLog('[mandala] handle: the connectivity probe failed; not settling now:', e)
207
+ }
208
+ if (!online) return undefined
209
+ let timer: ReturnType<typeof setTimeout> | undefined
210
+ const timeout = new Promise<undefined>(resolve => {
211
+ timer = setTimeout(() => resolve(undefined), d.settleTimeoutMs ?? DEFAULT_SETTLE_TIMEOUT_MS)
212
+ })
213
+ try {
214
+ return await Promise.race([
215
+ d.settleNow(txid).catch((e: unknown) => {
216
+ devLog(`[mandala] handle: settling ${txid} failed:`, e)
217
+ return undefined
218
+ }),
219
+ timeout
220
+ ])
221
+ } finally {
222
+ if (timer !== undefined) clearTimeout(timer)
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Best-effort release of a signed action nobody has seen. The abort guard
228
+ * decides. Once released, the host ledger stops vouching for its change
229
+ * (`sendHandover` recorded it `pending`), as the lib does for its own release.
230
+ */
231
+ export async function releaseUnseenHandover(
232
+ d: { wallet: WalletInterface; ledger: HostLedger },
233
+ h: Pick<HandoverResult, 'txid' | 'reference' | 'receipt'>
234
+ ): Promise<void> {
235
+ let released = false
236
+ try {
237
+ const r = await d.wallet.abortAction({ reference: h.reference })
238
+ released = r?.aborted === true
239
+ if (!released) devLog(`[mandala] the unjournaled hand-over ${h.txid} was not released`)
240
+ } catch (e) {
241
+ devLog(`[mandala] releasing the unjournaled hand-over ${h.txid} failed:`, e)
242
+ }
243
+ if (!released) return
244
+ try {
245
+ await d.ledger.put({
246
+ v: 1,
247
+ txid: h.txid,
248
+ assetId: h.receipt.assetId,
249
+ state: 'refused',
250
+ own: true,
251
+ outputs: [],
252
+ code: 'ERR_RELEASED',
253
+ at: Date.now()
254
+ })
255
+ } catch (e) {
256
+ devLog(`[mandala] the released hand-over ${h.txid} is still recorded pending in the host ledger:`, e)
257
+ }
258
+ }
259
+
260
+ export async function sendToHandle(
261
+ d: HandleDeps,
262
+ a: { assetId: string; recipientIdentityKey: string; units: bigint; note?: string }
263
+ ): Promise<TokenSendResult> {
264
+ // Everything up to the latch is synchronous: a double tap must see it.
265
+ const units = a.units
266
+ if (typeof units !== 'bigint' || units < 1n || units > MAX_UINT64) {
267
+ return {
268
+ kind: 'refused',
269
+ code: 'ERR_INVALID_AMOUNT',
270
+ message: 'A token amount must be a whole number from 1 to 18446744073709551615 base units'
271
+ }
272
+ }
273
+ const refusal = d.recipientRefusal(a.recipientIdentityKey)
274
+ if (refusal !== null) return { kind: 'refused', code: 'ERR_RECIPIENT', message: refusal }
275
+ const latch = setOf(sendLatches, d)
276
+ if (latch.has(a.assetId)) {
277
+ return {
278
+ kind: 'refused',
279
+ code: 'ERR_SEND_IN_FLIGHT',
280
+ message: 'A payment of this token is already being sent; wait for it to finish'
281
+ }
282
+ }
283
+ latch.add(a.assetId)
284
+ try {
285
+ return await runSend(d, { ...a, units, recipientKey: a.recipientIdentityKey.trim().toLowerCase() })
286
+ } finally {
287
+ latch.delete(a.assetId)
288
+ }
289
+ }
290
+
291
+ async function runSend(
292
+ d: HandleDeps,
293
+ a: { assetId: string; recipientKey: string; units: bigint; note?: string }
294
+ ): Promise<TokenSendResult> {
295
+ let identityKey: string
296
+ try {
297
+ identityKey = await d.identityKey()
298
+ } catch (e) {
299
+ return { kind: 'unavailable', message: messageOf(e) }
300
+ }
301
+ const note = a.note !== undefined && a.note.trim() !== '' ? a.note : undefined
302
+
303
+ let h: HandoverResult
304
+ try {
305
+ h = await sendHandover({
306
+ wallet: d.wallet,
307
+ identityKey,
308
+ assetId: a.assetId,
309
+ amount: a.units,
310
+ recipientKey: a.recipientKey,
311
+ ...(note !== undefined ? { note } : {}),
312
+ hostWallet: d.hostWallet,
313
+ ledger: d.ledger,
314
+ // The wallet owns this send's durability: the `color_transfers` row
315
+ // (written next), the kept body and the host ledger. The lib's txJournal would
316
+ // keep a 'signed'/'delivered' entry holding the tx hex that only
317
+ // `settleHandover`/`reconcileWallet` clear, and this wallet runs
318
+ // neither, so with the default it grew by one tx per send. The lib's
319
+ // precondition for `false` (run `reconcileWallet` with `sweep: false`)
320
+ // holds vacuously: no sweep runs here at all.
321
+ journal: false
322
+ })
323
+ } catch (e) {
324
+ return sendErrorResult(e)
325
+ }
326
+
327
+ // Signed. From here nothing may throw out, and nothing is delivered that
328
+ // the journal does not hold.
329
+ const self = a.recipientKey === identityKey.toLowerCase()
330
+ const delivering = setOf(deliveringTxids, d)
331
+ delivering.add(h.txid)
332
+ try {
333
+ try {
334
+ // The body first: a row that can be redelivered must have one.
335
+ await d.bodies.put(h.txid, h.body)
336
+ const wrote = await d.journal.insert({
337
+ txid: h.txid,
338
+ role: 'sent',
339
+ state: 'handed_over',
340
+ // A send to self owes no delivery: nothing for the tick to redeliver.
341
+ delivered: self,
342
+ reference: h.reference,
343
+ rail: 'handle',
344
+ units: a.units,
345
+ counterpartyKey: a.recipientKey,
346
+ outputIndex: h.outputIndex,
347
+ assetId: a.assetId,
348
+ ...(note !== undefined ? { note } : {}),
349
+ derivationPrefix: h.receipt.derivationPrefix,
350
+ derivationSuffix: h.receipt.derivationSuffix,
351
+ senderIdentityKey: h.receipt.senderIdentityKey
352
+ })
353
+ if (!wrote) {
354
+ // A fresh txid cannot already have a row unless this very send was
355
+ // journaled before; anything else is not ours to deliver.
356
+ const existing = await d.journal.get(h.txid)
357
+ if (existing?.role !== 'sent' || existing.reference !== h.reference) {
358
+ await releaseUnseenHandover(d, h)
359
+ return { kind: 'unavailable', message: `color_transfers already holds ${h.txid} for another transfer` }
360
+ }
361
+ }
362
+ } catch (e) {
363
+ devLog(`[mandala] handle: journaling the hand-over ${h.txid} failed; releasing it undelivered:`, e)
364
+ await releaseUnseenHandover(d, h)
365
+ return { kind: 'unavailable', message: messageOf(e) }
366
+ }
367
+ notify(d)
368
+
369
+ let delivered = self
370
+ if (!self) {
371
+ try {
372
+ await deliverHandover({
373
+ messageBoxClient: await d.messageBox(),
374
+ recipientKey: a.recipientKey,
375
+ handover: h
376
+ })
377
+ delivered = true
378
+ } catch (e) {
379
+ devLog(`[mandala] handle: delivering ${h.txid} failed; the tick redelivers it:`, e)
380
+ }
381
+ if (delivered) await markDelivered(d, h.txid)
382
+ }
383
+
384
+ let settled = false
385
+ if (delivered) settled = (await settleSoon(d, h.txid)) === 'settled'
386
+ return { kind: 'sent', txid: h.txid, settled, notified: delivered }
387
+ } finally {
388
+ delivering.delete(h.txid)
389
+ }
390
+ }
391
+
392
+ /** Journals a delivery. A failed write only means a harmless duplicate redelivery later. */
393
+ async function markDelivered(d: HandleDeps, txid: string): Promise<void> {
394
+ try {
395
+ await d.journal.setDelivered(txid, true)
396
+ notify(d)
397
+ } catch (e) {
398
+ devLog(`[mandala] handle: recording the delivery of ${txid} failed:`, e)
399
+ }
400
+ }
401
+
402
+ /** States a sent row may be (re)delivered from without a transition. */
403
+ const DELIVERABLE_STATES: readonly ColorTransferState[] = ['handed_over', 'settled']
404
+ /** The payer's own states: delivering hands it over, so the row moves first (W4). */
405
+ const UNHANDED_STATES: readonly ColorTransferState[] = ['built', 'parked']
406
+
407
+ type DeliverOutcome = 'resent' | 'not-found' | 'unavailable'
408
+
409
+ /** Everything a (re)delivery needs, gathered before anything is changed. */
410
+ interface PreparedDelivery {
411
+ recipientKey: string
412
+ handover: Pick<HandoverResult, 'txid' | 'body'>
413
+ box: MandalaMessageBox
414
+ }
415
+
416
+ /**
417
+ * Reads the kept v4 body of a sent row and opens the box. Reads only: the
418
+ * body must be present and carry the row's own tx and asset, and the box must
419
+ * open, or nothing is to be delivered.
420
+ */
421
+ async function prepareRow(
422
+ d: HandleDeps,
423
+ row: ColorTransferRow
424
+ ): Promise<PreparedDelivery | 'not-found' | 'unavailable'> {
425
+ const { txid } = row
426
+ if (
427
+ row.role !== 'sent' ||
428
+ !row.counterpartyKey ||
429
+ !row.derivationPrefix ||
430
+ !row.derivationSuffix ||
431
+ !row.senderIdentityKey
432
+ ) {
433
+ return 'not-found'
434
+ }
435
+ let body: HandoverBodyV4 | undefined
436
+ try {
437
+ body = await d.bodies.get(txid)
438
+ } catch (e) {
439
+ devLog(`[mandala] handle: reading the kept body of ${txid} failed:`, e)
440
+ return 'unavailable'
441
+ }
442
+ if (!body || body.assetId !== row.assetId || bodyTxid(body) !== txid) return 'not-found'
443
+ let box: MandalaMessageBox
444
+ try {
445
+ box = await d.messageBox()
446
+ } catch (e) {
447
+ devLog(`[mandala] handle: the MessageBox for ${txid} could not be opened:`, e)
448
+ return 'unavailable'
449
+ }
450
+ return { recipientKey: row.counterpartyKey, box, handover: { txid, body } }
451
+ }
452
+
453
+ /** Delivers a prepared hand-over and journals the ACK. */
454
+ async function deliverPrepared(d: HandleDeps, row: ColorTransferRow, p: PreparedDelivery): Promise<DeliverOutcome> {
455
+ try {
456
+ await deliverHandover({
457
+ messageBoxClient: p.box,
458
+ recipientKey: p.recipientKey,
459
+ handover: p.handover
460
+ })
461
+ } catch (e) {
462
+ devLog(`[mandala] handle: redelivering ${row.txid} failed:`, e)
463
+ return 'unavailable'
464
+ }
465
+ await markDelivered(d, row.txid)
466
+ return 'resent'
467
+ }
468
+
469
+ async function deliverRow(d: HandleDeps, row: ColorTransferRow): Promise<DeliverOutcome> {
470
+ const prepared = await prepareRow(d, row)
471
+ return typeof prepared === 'string' ? prepared : await deliverPrepared(d, row, prepared)
472
+ }
473
+
474
+ /**
475
+ * Redelivers every sent hand-over whose delivery is not known to have
476
+ * happened, whatever rail it first took: a parked nearby payment a resend
477
+ * handed over, then failed to deliver, is owed a delivery too. (The nearby
478
+ * rail journals a hand-over it confirmed over BLE `delivered: true`, so this
479
+ * never re-sends one the recipient acknowledged.) Single-flight per runtime;
480
+ * never throws. Returns how many were delivered. Each one delivered is then
481
+ * named to `settleNow` (post-ACK).
482
+ */
483
+ export function redeliverPending(d: HandleDeps): Promise<number> {
484
+ const existing = redeliverFlights.get(d)
485
+ if (existing) return existing
486
+ const running = (async () => {
487
+ let rows: ColorTransferRow[]
488
+ try {
489
+ rows = await d.journal.list({ states: ['handed_over'], role: 'sent' })
490
+ } catch (e) {
491
+ devLog('[mandala] handle: listing undelivered hand-overs failed:', e)
492
+ return 0
493
+ }
494
+ const delivering = setOf(deliveringTxids, d)
495
+ let count = 0
496
+ for (const row of rows) {
497
+ if (row.delivered || delivering.has(row.txid)) continue
498
+ delivering.add(row.txid)
499
+ try {
500
+ if ((await deliverRow(d, row)) === 'resent') {
501
+ count++
502
+ await settleSoon(d, row.txid)
503
+ }
504
+ } catch (e) {
505
+ devLog(`[mandala] handle: redelivering ${row.txid} failed:`, e)
506
+ } finally {
507
+ delivering.delete(row.txid)
508
+ }
509
+ }
510
+ return count
511
+ })()
512
+ redeliverFlights.set(d, running)
513
+ const clear = (): void => {
514
+ if (redeliverFlights.get(d) === running) redeliverFlights.delete(d)
515
+ }
516
+ running.then(clear, clear)
517
+ return running
518
+ }
519
+
520
+ /**
521
+ * Re-delivers one sent hand-over over MessageBox, whatever rail it first took.
522
+ *
523
+ * Everything the delivery needs (custody fields, evidence, bytes, an open
524
+ * box) is gathered first; a resend that cannot have them returns without
525
+ * touching the row, so a parked payment stays parked and cancellable. Only
526
+ * then is a payment not yet handed over (`built`/`parked`) journaled
527
+ * `handed_over` (a compare-and-set: a concurrent cancel wins and nothing is
528
+ * delivered), so the abort guard refuses from the moment the bytes may leave.
529
+ * A delivery that fails after that stays `handed_over`, undelivered, for
530
+ * `redeliverPending`: its bytes may have landed, so it is never parked again.
531
+ *
532
+ * Received rows and final refusals are `'not-found'`: there is nothing to
533
+ * deliver. Never contacts the overlay.
534
+ */
535
+ export async function resendTransfer(d: HandleDeps, txid: string): Promise<'resent' | 'not-found' | 'unavailable'> {
536
+ let row: ColorTransferRow | undefined
537
+ try {
538
+ row = await d.journal.get(txid)
539
+ } catch (e) {
540
+ devLog(`[mandala] handle: reading ${txid} for a resend failed:`, e)
541
+ return 'unavailable'
542
+ }
543
+ if (!row || row.role !== 'sent') return 'not-found'
544
+ const unhanded = UNHANDED_STATES.includes(row.state)
545
+ if (!unhanded && !DELIVERABLE_STATES.includes(row.state)) return 'not-found'
546
+ const delivering = setOf(deliveringTxids, d)
547
+ delivering.add(txid)
548
+ try {
549
+ const prepared = await prepareRow(d, row)
550
+ if (typeof prepared === 'string') return prepared
551
+ if (unhanded) {
552
+ let moved: boolean
553
+ try {
554
+ moved = await d.journal.advance(txid, UNHANDED_STATES, 'handed_over')
555
+ } catch (e) {
556
+ devLog(`[mandala] handle: handing over ${txid} for a resend failed:`, e)
557
+ return 'unavailable'
558
+ }
559
+ if (!moved) {
560
+ // Moved under us (a cancel, a release, a refusal): re-read and decide again.
561
+ let now: ColorTransferRow | undefined
562
+ try {
563
+ now = await d.journal.get(txid)
564
+ } catch (e) {
565
+ devLog(`[mandala] handle: re-reading ${txid} for a resend failed:`, e)
566
+ return 'unavailable'
567
+ }
568
+ if (!now || !DELIVERABLE_STATES.includes(now.state)) return 'not-found'
569
+ row = now
570
+ } else {
571
+ notify(d)
572
+ }
573
+ }
574
+ return await deliverPrepared(d, row, prepared)
575
+ } finally {
576
+ delivering.delete(txid)
577
+ }
578
+ }
579
+
580
+ const IDENTITY_KEY = /^(02|03)[0-9a-f]{64}$/
581
+
582
+ /** What this session learned of each listed message: who sent it. */
583
+ interface ListedMessage {
584
+ sender?: string
585
+ }
586
+
587
+ /**
588
+ * Reads the sender of a listed hand-over, leniently: display data (the
589
+ * counterparty) for credits the lib already verified, never a decision input.
590
+ */
591
+ function readListed(message: unknown): [string, ListedMessage] | undefined {
592
+ if (message === null || typeof message !== 'object') return undefined
593
+ const m = message as { messageId?: unknown; sender?: unknown }
594
+ const id = typeof m.messageId === 'string' || typeof m.messageId === 'number' ? String(m.messageId) : undefined
595
+ if (id === undefined) return undefined
596
+ const out: ListedMessage = {}
597
+ if (typeof m.sender === 'string' && IDENTITY_KEY.test(m.sender)) out.sender = m.sender
598
+ return [id, out]
599
+ }
600
+
601
+ /**
602
+ * Drains the `mandala-color` box through lib `receiveHandovers` (with the
603
+ * host ledger: online submit or offline COVER, recorded before the plain
604
+ * receipt is internalized) and journals each credit, `held` when it was
605
+ * credited offline and `settled` when the ledger holds a verified σ. Held
606
+ * ones are then offered to `reconcileHeld`. Single-flight per runtime.
607
+ *
608
+ * `incomplete: true` means the box could not be read at all, which is never
609
+ * the same answer as an empty box. A journal fault after a credit is logged:
610
+ * the broadcast hold treats a missing row as held, and `reconcileHeld`
611
+ * journals the receipt from the module's inventory on the next tick.
612
+ */
613
+ export function receiveFromInbox(d: HandleDeps): Promise<{ credited: number; failed: number; incomplete?: true }> {
614
+ const existing = receiveFlights.get(d)
615
+ if (existing) return existing
616
+ const running = runReceive(d)
617
+ receiveFlights.set(d, running)
618
+ const clear = (): void => {
619
+ if (receiveFlights.get(d) === running) receiveFlights.delete(d)
620
+ }
621
+ running.then(clear, clear)
622
+ return running
623
+ }
624
+
625
+ async function runReceive(d: HandleDeps): Promise<{ credited: number; failed: number; incomplete?: true }> {
626
+ const listed = new Map<string, ListedMessage>()
627
+ let result: Awaited<ReturnType<typeof receiveHandovers>>
628
+ try {
629
+ const box = await d.messageBox()
630
+ // Observe the listing the lib makes (no second request, no extra ack).
631
+ const observed: MessageBoxLike = {
632
+ listMessages: async args => {
633
+ const messages = await box.listMessages(args)
634
+ if (Array.isArray(messages)) {
635
+ for (const m of messages) {
636
+ const entry = readListed(m)
637
+ if (entry) listed.set(entry[0], entry[1])
638
+ }
639
+ }
640
+ return messages
641
+ },
642
+ acknowledgeMessage: async args => await box.acknowledgeMessage(args)
643
+ }
644
+ result = await receiveHandovers({
645
+ wallet: d.wallet,
646
+ messageBoxClient: observed,
647
+ processed: d.processed,
648
+ ledger: d.ledger,
649
+ markSettled: d.markSettled
650
+ })
651
+ } catch (e) {
652
+ devLog('[mandala] handle: the token inbox could not be read:', e)
653
+ return { credited: 0, failed: 0, incomplete: true }
654
+ }
655
+
656
+ let changed = false
657
+ for (const credit of result.accepted) {
658
+ const seen = listed.get(String(credit.messageId))
659
+ try {
660
+ // `offline` is the host ledger's own state for this tx (B7): `pending`
661
+ // (COVER evidence, not yet admitted) or `settled` (σ verified by this
662
+ // host). A row already `held` is moved by markSettled, never here.
663
+ if (
664
+ await d.journal.insert({
665
+ txid: credit.txid,
666
+ role: 'received',
667
+ assetId: credit.assetId,
668
+ units: credit.amount,
669
+ outputIndex: credit.outputIndex,
670
+ rail: 'handle',
671
+ state: credit.offline ? 'held' : 'settled',
672
+ delivered: false,
673
+ ...(seen?.sender !== undefined ? { counterpartyKey: seen.sender } : {})
674
+ })
675
+ ) {
676
+ changed = true
677
+ }
678
+ } catch (e) {
679
+ devLog(`[mandala] handle: journaling the inbox credit ${credit.txid} failed:`, e)
680
+ }
681
+ }
682
+ if (changed) notify(d)
683
+ if (result.accepted.length > 0) {
684
+ // A replay of a credit journaled `held` earlier that is now settled is
685
+ // moved by markSettled; this also catches one whose markSettled write
686
+ // failed. A view fault leaves it held for the next tick.
687
+ try {
688
+ await d.reconcileHeld(result.accepted.map(c => c.txid))
689
+ } catch (e) {
690
+ devLog('[mandala] handle: reconciling inbox credits failed; they stay held:', e)
691
+ }
692
+ }
693
+ return { credited: result.accepted.length, failed: result.failed.length }
694
+ }