@bsv/expo-wallet-toolbox 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/README.md +82 -13
  3. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  4. package/core/bridge/bindings.ts +459 -0
  5. package/core/bridge/conformance.ts +222 -0
  6. package/core/bridge/consent.ts +494 -0
  7. package/core/bridge/consentSheetSource.ts +98 -0
  8. package/core/bridge/dispatcher.ts +621 -0
  9. package/core/bridge/inbox.ts +464 -0
  10. package/core/bridge/index.ts +48 -0
  11. package/core/bridge/loopback/cors.ts +57 -0
  12. package/core/bridge/loopback/endpoints.ts +11 -0
  13. package/core/bridge/loopback/hostCheck.ts +25 -0
  14. package/core/bridge/loopback/index.ts +7 -0
  15. package/core/bridge/loopback/launchProof.ts +166 -0
  16. package/core/bridge/loopback/router.ts +770 -0
  17. package/core/bridge/loopback/routerTypes.ts +115 -0
  18. package/core/bridge/loopback/status.ts +52 -0
  19. package/core/bridge/memoryInboxStore.ts +222 -0
  20. package/core/bridge/permissionPolicy.ts +247 -0
  21. package/core/bridge/policy.ts +72 -0
  22. package/core/bridge/protocol/base64url.ts +64 -0
  23. package/core/bridge/protocol/connectionError.ts +79 -0
  24. package/core/bridge/protocol/constants.ts +21 -0
  25. package/core/bridge/protocol/continuity.ts +21 -0
  26. package/core/bridge/protocol/descriptor.ts +395 -0
  27. package/core/bridge/protocol/envelopes.ts +188 -0
  28. package/core/bridge/protocol/errorCodec.ts +164 -0
  29. package/core/bridge/protocol/json.ts +237 -0
  30. package/core/bridge/protocol/limits.ts +43 -0
  31. package/core/bridge/protocol/methods.ts +55 -0
  32. package/core/bridge/protocol/origin.ts +130 -0
  33. package/core/bridge/runtime.ts +642 -0
  34. package/core/bridge/runtimeFlags.ts +34 -0
  35. package/core/bridge/testing/conformanceCases.ts +149 -0
  36. package/core/bridge/testing/pageClient.ts +44 -0
  37. package/core/bridge/unverifiedManager.ts +97 -0
  38. package/core/bridge/unverifiedOriginator.ts +79 -0
  39. package/core/config.tsx +1 -16
  40. package/core/contacts/contactActivity.ts +48 -28
  41. package/core/contacts/contactsStore.ts +2 -2
  42. package/core/context/WalletConnectionContext.tsx +7 -1
  43. package/core/context/WalletContext.tsx +420 -348
  44. package/core/context/sessionTeardown.ts +46 -0
  45. package/core/demo/demoAssets.ts +8 -10
  46. package/core/demo/demoLedger.ts +32 -38
  47. package/core/demo/demoMandalaRuntime.ts +67 -49
  48. package/core/demo/index.ts +1 -1
  49. package/core/hooks/usePermissionQueue.ts +89 -34
  50. package/core/i18n/translations.tsx +983 -12
  51. package/core/index.ts +70 -37
  52. package/core/localpay/build.ts +110 -569
  53. package/core/localpay/codec.ts +190 -93
  54. package/core/localpay/pending.ts +217 -202
  55. package/core/localpay/session.ts +99 -25
  56. package/core/localpay/types.ts +6 -5
  57. package/core/localpay/verify.ts +118 -173
  58. package/core/mandala/abortGuard.ts +97 -120
  59. package/core/mandala/accessPolicy.ts +133 -0
  60. package/core/mandala/assets.ts +370 -0
  61. package/core/mandala/colorGuard.ts +178 -0
  62. package/core/mandala/colorModule.ts +82 -0
  63. package/core/mandala/createRuntime.ts +483 -2392
  64. package/core/mandala/handle.ts +694 -0
  65. package/core/mandala/kvStore.ts +105 -0
  66. package/core/mandala/nearby.ts +185 -0
  67. package/core/mandala/receipt.ts +121 -0
  68. package/core/mandala/runtime.ts +166 -312
  69. package/core/mandala/settle.ts +540 -0
  70. package/core/mandala/transferJournal.ts +395 -0
  71. package/core/mandala/types.ts +61 -311
  72. package/core/networks.ts +5 -5
  73. package/core/offline/cancelParked.ts +80 -63
  74. package/core/offline/payerHold.ts +52 -118
  75. package/core/parsePeerPayURI.ts +25 -12
  76. package/core/pay/rails/handle.ts +15 -14
  77. package/core/pay/rails/index.ts +5 -3
  78. package/core/pay/rails/nearby.ts +25 -87
  79. package/core/profiles/assertProfileEmpty.ts +19 -10
  80. package/core/services/autoApprovePolicy.ts +7 -1
  81. package/core/services/capWalletArgs.ts +2 -1
  82. package/core/services/permissionPrompts.ts +132 -0
  83. package/core/services/signingPermissionPolicy.ts +230 -2
  84. package/core/services/vault/guard.ts +15 -4
  85. package/core/services/walletArgLimits.ts +17 -2
  86. package/core/storage/StorageExpoSQLite.ts +93 -229
  87. package/core/storage/encryptedDbImage.ts +325 -0
  88. package/core/storage/methods/processOfflineActions.ts +86 -136
  89. package/core/storage/schema/createTables.ts +9 -184
  90. package/core/toolboxConfig.ts +18 -1
  91. package/package.json +9 -8
  92. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  93. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  94. package/ui/components/pay/AssetPicker.tsx +2 -2
  95. package/ui/components/pay/HandleReceive.tsx +4 -4
  96. package/ui/components/pay/NearbyFlow.tsx +324 -239
  97. package/ui/components/pay/RequestHub.tsx +10 -0
  98. package/ui/components/pay/UniversalSend.tsx +31 -28
  99. package/ui/components/pay/useRecipientInput.ts +2 -2
  100. package/ui/components/ui/PermissionSheet.tsx +625 -315
  101. package/ui/components/ui/Sheet.tsx +59 -7
  102. package/ui/components/ui/colorPrompt.ts +236 -0
  103. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  104. package/ui/components/wallet/AmountInput.tsx +9 -6
  105. package/ui/components/wallet/AssetAmount.tsx +6 -6
  106. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  107. package/ui/components/wallet/Balance.tsx +3 -1
  108. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  109. package/ui/components/wallet/tokenEviction.ts +9 -9
  110. package/ui/exportDatabases.ts +94 -5
  111. package/ui/hooks/useExportWalletData.ts +37 -24
  112. package/ui/hooks/useMandala.ts +6 -6
  113. package/ui/hooks/useSpendableBalance.ts +3 -1
  114. package/ui/importDatabases.ts +124 -29
  115. package/ui/index.ts +4 -0
  116. package/ui/screens/PayScreen.tsx +14 -20
  117. package/ui/screens/SettingsScreen.tsx +3 -1
  118. package/ui/screens/WalletCheckScreen.tsx +7 -2
  119. package/ui/screens/WalletConfigScreen.tsx +13 -1
  120. package/ui/screens/WalletHomeScreen.tsx +40 -14
  121. package/ui/screens/tokenRowTitle.ts +28 -15
  122. package/ui/tokenFormat.ts +133 -69
  123. package/ui/tokenStatus.ts +5 -8
  124. package/core/localpay/settlementAck.ts +0 -155
  125. package/core/mandala/basketMigration.ts +0 -166
  126. package/core/mandala/bundle.ts +0 -244
  127. package/core/mandala/drain.ts +0 -754
  128. package/core/mandala/inboxPrehold.ts +0 -193
  129. package/core/mandala/permissionModule.ts +0 -931
  130. package/core/mandala/resendTransfer.ts +0 -178
  131. package/core/mandala/settlementStore.ts +0 -434
  132. package/core/mandala/token.ts +0 -45
  133. package/core/offline/tokenFrames.ts +0 -197
@@ -0,0 +1,540 @@
1
+ /**
2
+ * Settlement of token hand-overs and receipts on the host (design §9 B7, IC
3
+ * §8.2 Revision 3).
4
+ *
5
+ * The color module no longer settles anything. The host does, with the lib:
6
+ *
7
+ * · a SENT hand-over the recipient acknowledged (journal `handed_over`,
8
+ * `delivered`) is submitted by `settleHandover` with the exact bytes and
9
+ * envelope `sendHandover` recorded in the host ledger. A verified σ
10
+ * settles it; a final verdict refuses it.
11
+ * · a RECEIVED coin credited offline (ledger `pending`) is submitted by
12
+ * `settleReceipts` with its stored chain; a verified σ covering the
13
+ * credited output settles it.
14
+ *
15
+ * Both end in the host-only `color.markSettled(txid)`, which clears
16
+ * `color_offline` on the tx's outputs. The wallet hands the lib a
17
+ * `markSettled` that ALSO moves the `color_transfers` row to `settled`, in
18
+ * that order and before the lib's own post-admission broadcast starts, so the
19
+ * broadcast hold (keyed on the journal, W1) already releases that broadcast.
20
+ *
21
+ * Rules every function here keeps (stability mandate):
22
+ * · Journal moves are compare-and-set only (`journal.advance`), so a drain
23
+ * tick racing a screen, or a verdict replayed after a crash, can never move
24
+ * a row twice or out of a final state.
25
+ * · `built`/`parked` rows are the payer's own and are never submitted (FIX
26
+ * F), and neither is a `handed_over` row whose delivery is not known to
27
+ * have happened (B5: the sender submits only after the recipient's ACK).
28
+ * A final row is never submitted.
29
+ * · A refused own hand-over is journaled `refused` FIRST and only then
30
+ * aborted, so the abort guard (which refuses aborts of `handed_over` and
31
+ * `settled` rows) lets its inputs go. `settleNow` of a `refused` row
32
+ * retries the abort, so a crash between the two steps never strands the
33
+ * inputs. Within one settler the abort is coalesced per reference (a
34
+ * racing `settleAll` and `settleNow` abort once) and not repeated after it
35
+ * succeeded.
36
+ * · Every unknown answer fails closed: an unreadable admission answer is
37
+ * `undefined` (never `false`), and an inventory record that is offline or
38
+ * restricted is never journaled as `settled`.
39
+ */
40
+ import { Transaction, Utils, type LookupAnswer, type WalletInterface } from '@bsv/sdk'
41
+ import type { ColorOverlayProvider } from '@bsv/color-permission-module'
42
+ import { COLOR_OFFLINE_TAG } from '@bsv/color-permission-module'
43
+ import {
44
+ settleHandover as libSettleHandover,
45
+ settleReceipts as libSettleReceipts,
46
+ type HostLedger,
47
+ type LedgerRecord,
48
+ type ReceiptSettleResult,
49
+ type SettleResult
50
+ } from '@bsv/mandala'
51
+ import { devLog } from '../logging'
52
+ import type { InventoryRecord } from './assets'
53
+ import type { TokenSettleState } from './runtime'
54
+ import type { TransferJournal } from './transferJournal'
55
+ import type { ColorTransferRow, ColorTransferState } from './types'
56
+
57
+ export interface SettleDeps {
58
+ /** The bound manager: the lib's post-admission `sendWith` runs through it. */
59
+ wallet: WalletInterface
60
+ journal: TransferJournal
61
+ /** The host ledger shared with the issuer-v1 handler. */
62
+ ledger: HostLedger
63
+ /** The module's host-only `markSettled(txid)` (clears `color_offline`). */
64
+ markSettled: (txid: string) => Promise<void>
65
+ /** This chain's overlay identity key K. */
66
+ overlayIdentityKey: string
67
+ /** The bound manager's `abortAction({ reference })`, behind the abort guard. */
68
+ abort: (reference: string) => Promise<{ aborted: boolean }>
69
+ onChange: () => void
70
+ /** Lib seams (tests replace them). */
71
+ settleHandover?: typeof libSettleHandover
72
+ settleReceipts?: typeof libSettleReceipts
73
+ }
74
+
75
+ /** Every state a verdict may move a row out of. Final states are never left. */
76
+ const OPEN_STATES: readonly ColorTransferState[] = ['built', 'parked', 'handed_over', 'held']
77
+
78
+ /** The transport-failure code (overlay unreachable, no typed verdict). */
79
+ export const ERR_UNAVAILABLE = 'ERR_UNAVAILABLE'
80
+
81
+ /** One settlement outcome, sent or received, as the drain reports it. */
82
+ export interface SettleOutcome {
83
+ txid: string
84
+ assetId: string
85
+ status: 'admitted' | 'retry' | 'refused'
86
+ code?: string
87
+ }
88
+
89
+ export interface SettleReport {
90
+ results: SettleOutcome[]
91
+ }
92
+
93
+ /**
94
+ * Aborts the action behind a REFUSED own hand-over so its reserved inputs come
95
+ * back. Only for a row that reads `refused`, so the abort guard allows it.
96
+ * Never throws: a failed abort is retried by the next `settleNow` of the row.
97
+ */
98
+ async function releaseRefused(row: ColorTransferRow | undefined, abort: SettleDeps['abort']): Promise<void> {
99
+ if (row?.state !== 'refused' || row.role !== 'sent' || !row.reference) return
100
+ try {
101
+ const r = await abort(row.reference)
102
+ if (!r?.aborted) devLog(`[mandala] settle: the refused hand-over ${row.txid} was not aborted`)
103
+ } catch (e) {
104
+ devLog(`[mandala] settle: aborting the refused hand-over ${row.txid} failed:`, e)
105
+ }
106
+ }
107
+
108
+ /** The exact submit bytes of an own hand-over, from its host-ledger record. */
109
+ function ownSubmit(
110
+ rec: LedgerRecord | undefined,
111
+ txid: string
112
+ ): { tx: number[]; offChainValues: number[] } | undefined {
113
+ const tip = rec?.submits?.find(s => s.txid === txid)
114
+ const beefHex = tip?.beefHex ?? rec?.beefHex
115
+ if (tip === undefined || beefHex === undefined || tip.offChainHex === '') return undefined
116
+ return { tx: Utils.toArray(beefHex, 'hex'), offChainValues: Utils.toArray(tip.offChainHex, 'hex') }
117
+ }
118
+
119
+ export interface Settler {
120
+ settleNow(txid: string): Promise<TokenSettleState>
121
+ settleAll(): Promise<number>
122
+ /** `settleAll` with every outcome, sharing its single flight. */
123
+ settleAllReport(): Promise<{ changed: number; report: SettleReport }>
124
+ /** The `markSettled` the lib is handed: module first, then the journal row. */
125
+ markSettled(txid: string): Promise<void>
126
+ }
127
+
128
+ export function createSettler(deps: SettleDeps): Settler {
129
+ const settleHandover = deps.settleHandover ?? libSettleHandover
130
+ const settleReceipts = deps.settleReceipts ?? libSettleReceipts
131
+ const inFlight = new Map<string, Promise<TokenSettleState>>()
132
+ let allInFlight: Promise<{ changed: number; report: SettleReport }> | undefined
133
+
134
+ // The per-txid and settle-all single flights are separate, so a tick's
135
+ // `settleAll()` racing a screen's `settleNow(T)` can both see T refused.
136
+ // The journal CAS moves the row once; the abort is coalesced here:
137
+ // concurrent aborts of one reference share a call, and a reference already
138
+ // aborted by this settler is not asked again. A failed or declined abort is
139
+ // never remembered, so the retry paths still run it.
140
+ const abortInFlight = new Map<string, Promise<{ aborted: boolean }>>()
141
+ const aborted = new Set<string>()
142
+ const abortOnce = (reference: string): Promise<{ aborted: boolean }> => {
143
+ if (aborted.has(reference)) return Promise.resolve({ aborted: true })
144
+ const existing = abortInFlight.get(reference)
145
+ if (existing) return existing
146
+ const running = (async () => {
147
+ const r = await deps.abort(reference)
148
+ if (r?.aborted) aborted.add(reference)
149
+ return r
150
+ })()
151
+ abortInFlight.set(reference, running)
152
+ const clear = (): void => {
153
+ if (abortInFlight.get(reference) === running) abortInFlight.delete(reference)
154
+ }
155
+ running.then(clear, clear)
156
+ return running
157
+ }
158
+
159
+ const notify = (): void => {
160
+ try {
161
+ deps.onChange()
162
+ } catch (e) {
163
+ devLog('[mandala] settle: a change listener threw:', e)
164
+ }
165
+ }
166
+
167
+ /** CAS to `settled`; true when this call moved the row. */
168
+ const journalSettled = async (txid: string): Promise<boolean> => {
169
+ const moved = await deps.journal.advance(txid, OPEN_STATES, 'settled')
170
+ if (moved) notify()
171
+ return moved
172
+ }
173
+
174
+ /**
175
+ * The lib's `markSettled`: the module's flag first (so the coin stops being
176
+ * `color_offline`), then the journal (so the hold releases). A module
177
+ * failure throws before the journal moves, and the lib retries both.
178
+ */
179
+ const markSettled = async (txid: string): Promise<void> => {
180
+ await deps.markSettled(txid)
181
+ await journalSettled(txid)
182
+ }
183
+
184
+ /** Journals a final refusal (CAS) and releases a refused own hand-over. */
185
+ const journalRefused = async (txid: string, code: string | undefined): Promise<boolean> => {
186
+ const moved = await deps.journal.advance(txid, OPEN_STATES, 'refused', code !== undefined ? { code } : {})
187
+ if (moved) notify()
188
+ await releaseRefused(await deps.journal.get(txid), abortOnce)
189
+ return moved
190
+ }
191
+
192
+ const currentState = async (txid: string): Promise<TokenSettleState> => {
193
+ try {
194
+ return (await deps.journal.get(txid))?.state ?? 'unavailable'
195
+ } catch (e) {
196
+ devLog(`[mandala] settle: could not read ${txid} from the journal:`, e)
197
+ return 'unavailable'
198
+ }
199
+ }
200
+
201
+ /** Post-ACK submit of one own hand-over. Never throws for an overlay outcome. */
202
+ const settleSent = async (row: ColorTransferRow): Promise<SettleOutcome | undefined> => {
203
+ const base = { txid: row.txid, assetId: row.assetId }
204
+ const rec = await deps.ledger.get(row.txid)
205
+ if (rec?.state === 'settled') {
206
+ // Admitted before (a crash after the σ, or another settle): finish it.
207
+ if (rec.marked !== true) await markSettled(row.txid)
208
+ else await journalSettled(row.txid)
209
+ return { ...base, status: 'admitted' }
210
+ }
211
+ if (rec?.state === 'refused') {
212
+ await journalRefused(row.txid, rec.code)
213
+ return { ...base, status: 'refused', ...(rec.code !== undefined ? { code: rec.code } : {}) }
214
+ }
215
+ const bytes = ownSubmit(rec, row.txid)
216
+ if (bytes === undefined) {
217
+ devLog(`[mandala] settle: no host-ledger submit bytes for the hand-over ${row.txid}; it stays ${row.state}`)
218
+ return { ...base, status: 'retry', code: 'ERR_NO_CHAIN' }
219
+ }
220
+ let r: SettleResult
221
+ try {
222
+ r = await settleHandover({
223
+ wallet: deps.wallet,
224
+ handover: { txid: row.txid, ...bytes },
225
+ assetId: row.assetId,
226
+ overlayIdentityKey: deps.overlayIdentityKey,
227
+ ledger: deps.ledger,
228
+ markSettled
229
+ })
230
+ } catch (e) {
231
+ devLog(`[mandala] settle: the hand-over ${row.txid} could not be submitted:`, e)
232
+ return { ...base, status: 'retry', code: 'ERR_SETTLE' }
233
+ }
234
+ if (r.status === 'admitted') {
235
+ // The lib ran markSettled already; a failure there is only warned, so
236
+ // the row is moved here too (a CAS: a no-op when it already moved).
237
+ await journalSettled(row.txid)
238
+ return { ...base, status: 'admitted' }
239
+ }
240
+ if (r.status === 'refused') {
241
+ await journalRefused(row.txid, r.code)
242
+ return { ...base, status: 'refused', code: r.code }
243
+ }
244
+ return { ...base, status: 'retry', code: r.code }
245
+ }
246
+
247
+ /** Mirrors `settleReceipts` results onto the journal. */
248
+ const applyReceiptResults = async (results: readonly ReceiptSettleResult[]): Promise<SettleOutcome[]> => {
249
+ const out: SettleOutcome[] = []
250
+ for (const r of results) {
251
+ if (r.status === 'admitted') await journalSettled(r.txid)
252
+ else if (r.status === 'refused') await journalRefused(r.txid, r.code)
253
+ out.push({
254
+ txid: r.txid,
255
+ assetId: r.assetId,
256
+ status: r.status,
257
+ ...(r.code !== undefined ? { code: r.code } : {})
258
+ })
259
+ }
260
+ return out
261
+ }
262
+
263
+ /** A held receipt: submit its pending chain, or catch the row up with a settled ledger record. */
264
+ const settleReceived = async (row: ColorTransferRow): Promise<SettleOutcome[]> => {
265
+ const results = await applyReceiptResults(
266
+ await settleReceipts({
267
+ ledger: deps.ledger,
268
+ markSettled,
269
+ overlayIdentityKey: deps.overlayIdentityKey,
270
+ txids: [row.txid]
271
+ })
272
+ )
273
+ if (results.length > 0) return results
274
+ const rec = await deps.ledger.get(row.txid)
275
+ if (rec?.state === 'settled' && rec.marked !== false) {
276
+ await journalSettled(row.txid)
277
+ return [{ txid: row.txid, assetId: row.assetId, status: 'admitted' }]
278
+ }
279
+ if (rec?.state === 'refused') {
280
+ await journalRefused(row.txid, rec.code)
281
+ return [
282
+ {
283
+ txid: row.txid,
284
+ assetId: row.assetId,
285
+ status: 'refused',
286
+ ...(rec.code !== undefined ? { code: rec.code } : {})
287
+ }
288
+ ]
289
+ }
290
+ return []
291
+ }
292
+
293
+ const runOne = async (txid: string): Promise<TokenSettleState> => {
294
+ const row = await deps.journal.get(txid)
295
+ if (!row) return 'unavailable'
296
+ // A crash between journaling a refusal and aborting its action leaves the
297
+ // inputs reserved: the abort is retried from here.
298
+ if (row.state === 'refused') await releaseRefused(row, abortOnce)
299
+ if (row.role === 'sent') {
300
+ if (row.state !== 'handed_over' || !row.delivered) return row.state
301
+ await settleSent(row)
302
+ } else {
303
+ if (row.state !== 'held') return row.state
304
+ await settleReceived(row)
305
+ }
306
+ return (await deps.journal.get(txid))?.state ?? 'unavailable'
307
+ }
308
+
309
+ const settleNow = (txid: string): Promise<TokenSettleState> => {
310
+ const existing = inFlight.get(txid)
311
+ if (existing) return existing
312
+ const running = (async () => {
313
+ try {
314
+ return await runOne(txid)
315
+ } catch (e) {
316
+ devLog(`[mandala] settle: settling ${txid} failed:`, e)
317
+ return await currentState(txid)
318
+ }
319
+ })()
320
+ inFlight.set(txid, running)
321
+ const clear = (): void => {
322
+ if (inFlight.get(txid) === running) inFlight.delete(txid)
323
+ }
324
+ running.then(clear, clear)
325
+ return running
326
+ }
327
+
328
+ /**
329
+ * Every pending receipt and every delivered own hand-over, once. Faults per
330
+ * item are logged and do not stop the rest; a ledger or journal read fault
331
+ * for the whole pass propagates.
332
+ */
333
+ const runAll = async (): Promise<{ changed: number; report: SettleReport }> => {
334
+ let changed = 0
335
+ const counting = async <T>(fn: () => Promise<T>): Promise<T> => {
336
+ const before = await deps.journal.list({ states: [...OPEN_STATES] })
337
+ const r = await fn()
338
+ const after = await deps.journal.statesOf(before.map(b => b.txid))
339
+ for (const b of before) if (after.get(b.txid) !== b.state) changed++
340
+ return r
341
+ }
342
+ const results = await counting(async () => {
343
+ const out: SettleOutcome[] = []
344
+ try {
345
+ out.push(
346
+ ...(await applyReceiptResults(
347
+ await settleReceipts({ ledger: deps.ledger, markSettled, overlayIdentityKey: deps.overlayIdentityKey })
348
+ ))
349
+ )
350
+ } catch (e) {
351
+ devLog('[mandala] settle: settling pending receipts failed:', e)
352
+ }
353
+ // Held rows whose ledger record is already settled (a crash between the
354
+ // two writes, or a receipt the handler settled with its own submit).
355
+ for (const row of await deps.journal.list({ states: ['held'], role: 'received' })) {
356
+ try {
357
+ const rec = await deps.ledger.get(row.txid)
358
+ if (rec?.state === 'settled' && rec.marked !== false) await journalSettled(row.txid)
359
+ } catch (e) {
360
+ devLog(`[mandala] settle: catching up ${row.txid} failed:`, e)
361
+ }
362
+ }
363
+ for (const row of await deps.journal.list({ states: ['handed_over'], role: 'sent' })) {
364
+ if (!row.delivered) continue
365
+ try {
366
+ const r = await settleSent(row)
367
+ if (r) out.push(r)
368
+ } catch (e) {
369
+ devLog(`[mandala] settle: settling the hand-over ${row.txid} failed:`, e)
370
+ }
371
+ }
372
+ return out
373
+ })
374
+ return { changed, report: { results } }
375
+ }
376
+
377
+ const settleAllReport = (): Promise<{ changed: number; report: SettleReport }> => {
378
+ if (allInFlight) return allInFlight
379
+ const running = runAll()
380
+ allInFlight = running
381
+ const clear = (): void => {
382
+ if (allInFlight === running) allInFlight = undefined
383
+ }
384
+ running.then(clear, clear)
385
+ return running
386
+ }
387
+
388
+ return {
389
+ settleNow,
390
+ settleAll: async () => (await settleAllReport()).changed,
391
+ settleAllReport,
392
+ markSettled
393
+ }
394
+ }
395
+
396
+ /** Whether every result of a non-empty report is a transport `retry`: nothing could be asked. */
397
+ export function reportIsUnreachable(report: SettleReport | undefined): boolean {
398
+ const results = report?.results ?? []
399
+ return results.length > 0 && results.every(r => r.status === 'retry' && r.code === ERR_UNAVAILABLE)
400
+ }
401
+
402
+ /**
403
+ * Reads a `color-admission` answer for ONE queried outpoint.
404
+ *
405
+ * `true`: the answer lists exactly that outpoint (its txid is derived from the
406
+ * BEEF, as the module does; the optional `txid` hint must agree). `false`: an
407
+ * empty output list. Anything else throws — an unrelated, malformed or
408
+ * non-list answer is unreadable, and reading it as `false` would let a cancel
409
+ * release inputs under a payee who already submitted.
410
+ */
411
+ export function readHandoverAdmission(answer: LookupAnswer, outpoint: string): boolean {
412
+ if (answer?.type !== 'output-list' || !Array.isArray(answer.outputs)) {
413
+ throw new Error('color-admission: the overlay answer is not an output list')
414
+ }
415
+ if (answer.outputs.length === 0) return false
416
+ for (const item of answer.outputs) {
417
+ let tx: Transaction
418
+ try {
419
+ tx = Transaction.fromBEEF(item.beef, item.txid)
420
+ } catch {
421
+ throw new Error('color-admission: the overlay answer carries invalid BEEF')
422
+ }
423
+ const txid = tx.id('hex')
424
+ if (item.txid !== undefined && item.txid !== txid) {
425
+ throw new Error('color-admission: the overlay answer names a txid its BEEF does not carry')
426
+ }
427
+ if (!Number.isSafeInteger(item.outputIndex) || tx.outputs[item.outputIndex] === undefined) {
428
+ throw new Error('color-admission: the overlay answer names a missing output')
429
+ }
430
+ if (`${txid}.${item.outputIndex}` !== outpoint) {
431
+ throw new Error(`color-admission: the overlay answered an unrelated output ${txid}.${item.outputIndex}`)
432
+ }
433
+ }
434
+ return true
435
+ }
436
+
437
+ /**
438
+ * Whether the overlay already admitted `txid`'s journaled output. A txid with
439
+ * no row is `false` (this wallet built nothing under it). Every failure to ask
440
+ * or to read the answer — transport, typed refusal, malformed — is `undefined`.
441
+ */
442
+ export async function isHandoverAdmitted(
443
+ d: { journal: Pick<TransferJournal, 'get'>; provider: ColorOverlayProvider | undefined },
444
+ txid: string
445
+ ): Promise<boolean | undefined> {
446
+ if (!d.provider) return undefined
447
+ try {
448
+ const row = await d.journal.get(txid)
449
+ if (!row) return false
450
+ const outpoint = `${txid}.${row.outputIndex}`
451
+ return readHandoverAdmission(await d.provider.admission(row.assetId, [outpoint]), outpoint)
452
+ } catch (e) {
453
+ devLog(`[mandala] could not read the overlay admission of ${txid}:`, e)
454
+ return undefined
455
+ }
456
+ }
457
+
458
+ const RESTRICTED_TAG = 'color_state_restricted'
459
+
460
+ /** Records whose tags say the module has NOT settled their tx (offline credit, or refused). */
461
+ function unsettledRecord(r: InventoryRecord): boolean {
462
+ return r.tags.includes(COLOR_OFFLINE_TAG) || r.tags.includes(RESTRICTED_TAG)
463
+ }
464
+
465
+ const voutOf = (outpoint: string): number => Number(outpoint.slice(outpoint.lastIndexOf('.') + 1))
466
+
467
+ /**
468
+ * Journals held 1Color receipts the journal does not know, from the module's
469
+ * inventory (Review Focus 4: a fresh install, a store loss, an externally
470
+ * internalized receipt).
471
+ *
472
+ * · No row, records present: a `received`/`external` row, `held` when any
473
+ * record is `color_offline` (or restricted), else `settled`. `units` sums
474
+ * the asset's records; `outputIndex` is the lowest vout. No records: skip.
475
+ * · A `held` row whose records are all present and none offline or
476
+ * restricted: `settled` (the module drops `color_offline` only once the tx
477
+ * has a settled record). No records: it stays `held`.
478
+ * · No row, but `ownSends` names the txid (an action this wallet funded,
479
+ * e.g. a third-party originator's token send): skipped. Its records are
480
+ * the sender's own token CHANGE, and a `received` row would show that
481
+ * change as an incoming credit. It stays held here; an admitted one is
482
+ * broadcast by the overlay (design §21), as an exact spend with no change
483
+ * always was. A fault answering `ownSends` propagates (nothing written).
484
+ *
485
+ * Only the named txids are reconciled. Inserts are INSERT OR IGNORE and the
486
+ * advance is a CAS, so a concurrent writer of the same row always wins.
487
+ * Returns how many rows were written or moved.
488
+ */
489
+ export async function reconcileHeldTransfers(
490
+ d: {
491
+ journal: TransferJournal
492
+ inventory: () => Promise<InventoryRecord[]>
493
+ /** Of `txids`, the ones this wallet funded (its own outgoing actions). */
494
+ ownSends?: (txids: readonly string[]) => Promise<ReadonlySet<string>>
495
+ },
496
+ txids: readonly string[]
497
+ ): Promise<number> {
498
+ const wanted = [...new Set(txids)]
499
+ if (wanted.length === 0) return 0
500
+ const states = await d.journal.statesOf(wanted)
501
+ const candidates = wanted.filter(t => !states.has(t) || states.get(t) === 'held')
502
+ if (candidates.length === 0) return 0
503
+
504
+ const byTxid = new Map<string, InventoryRecord[]>()
505
+ for (const r of await d.inventory()) {
506
+ const txid = r.outpoint.slice(0, r.outpoint.lastIndexOf('.'))
507
+ const list = byTxid.get(txid)
508
+ if (list) list.push(r)
509
+ else byTxid.set(txid, [r])
510
+ }
511
+
512
+ const unjournaled = candidates.filter(t => !states.has(t) && byTxid.has(t))
513
+ const own = unjournaled.length > 0 && d.ownSends ? await d.ownSends(unjournaled) : new Set<string>()
514
+
515
+ let changed = 0
516
+ for (const txid of candidates) {
517
+ const records = (byTxid.get(txid) ?? []).slice().sort((a, b) => voutOf(a.outpoint) - voutOf(b.outpoint))
518
+ if (records.length === 0) continue
519
+ const unsettled = records.some(unsettledRecord)
520
+ if (states.get(txid) === 'held') {
521
+ if (!unsettled && (await d.journal.advance(txid, ['held'], 'settled'))) changed++
522
+ continue
523
+ }
524
+ if (own.has(txid)) continue
525
+ const first = records[0]
526
+ const units = records.filter(r => r.assetId === first.assetId).reduce((sum, r) => sum + r.units, 0n)
527
+ const wrote = await d.journal.insert({
528
+ txid,
529
+ role: 'received',
530
+ assetId: first.assetId,
531
+ units,
532
+ outputIndex: voutOf(first.outpoint),
533
+ rail: 'external',
534
+ state: unsettled ? 'held' : 'settled',
535
+ delivered: false
536
+ })
537
+ if (wrote) changed++
538
+ }
539
+ return changed
540
+ }