@bsv/expo-wallet-toolbox 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +311 -0
  2. package/README.md +52 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +21 -18
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +413 -23
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +107 -14
  12. package/core/localpay/build.ts +674 -37
  13. package/core/localpay/codec.ts +68 -5
  14. package/core/localpay/pending.ts +240 -22
  15. package/core/localpay/settlementAck.ts +149 -0
  16. package/core/localpay/types.ts +14 -1
  17. package/core/localpay/verify.ts +118 -69
  18. package/core/mandala/abortGuard.ts +134 -0
  19. package/core/mandala/basketMigration.ts +166 -0
  20. package/core/mandala/bundle.ts +244 -0
  21. package/core/mandala/createRuntime.ts +2437 -0
  22. package/core/mandala/drain.ts +670 -0
  23. package/core/mandala/permissionModule.ts +642 -0
  24. package/core/mandala/resendTransfer.ts +175 -0
  25. package/core/mandala/runtime.ts +357 -0
  26. package/core/mandala/settlementStore.ts +412 -0
  27. package/core/mandala/types.ts +290 -0
  28. package/core/offline/cancelParked.ts +94 -1
  29. package/core/offline/payerHold.ts +152 -12
  30. package/core/offline/tokenFrames.ts +197 -0
  31. package/core/parsePeerPayURI.ts +70 -17
  32. package/core/pay/rails/address.ts +51 -3
  33. package/core/pay/rails/handle.ts +88 -9
  34. package/core/pay/rails/index.ts +16 -6
  35. package/core/pay/rails/nearby.ts +114 -4
  36. package/core/services/capWalletArgs.ts +8 -9
  37. package/core/services/externalOrigin.ts +39 -0
  38. package/core/services/vault/VaultKeyService.ts +912 -251
  39. package/core/services/vault/ceremony.ts +435 -367
  40. package/core/services/vault/ceremonyHost.ts +27 -21
  41. package/core/services/vault/devMock.ts +30 -7
  42. package/core/services/vault/driver.ts +95 -41
  43. package/core/services/vault/guard.ts +514 -56
  44. package/core/services/vault/hardwareLease.ts +22 -0
  45. package/core/services/vault/mockYubiKey.ts +258 -90
  46. package/core/services/vault/pivReset.ts +145 -0
  47. package/core/services/vault/r1comb.ts +976 -0
  48. package/core/services/vault/session.ts +93 -26
  49. package/core/services/vault/transfers.ts +2617 -747
  50. package/core/services/vault/types.ts +100 -43
  51. package/core/services/vault/vaultStore.ts +991 -74
  52. package/core/services/walletConnectionValidation.ts +293 -0
  53. package/core/services/walletServiceConfig.ts +19 -24
  54. package/core/storage/StorageExpoSQLite.ts +382 -56
  55. package/core/storage/dbImage.ts +48 -0
  56. package/core/storage/methods/findSql.ts +0 -54
  57. package/core/storage/methods/listOutputsSql.ts +7 -3
  58. package/core/storage/methods/offlineActions.ts +15 -0
  59. package/core/storage/methods/processOfflineActions.ts +263 -6
  60. package/core/storage/methods/walletBalanceSql.ts +16 -4
  61. package/core/storage/schema/createTables.ts +123 -0
  62. package/core/storage/sqlUpdateValue.ts +24 -0
  63. package/core/toolboxConfig.ts +240 -0
  64. package/core/walletRepair/runWalletCheck.ts +19 -2
  65. package/package.json +25 -24
  66. package/ui/components/QRScanner.tsx +1 -1
  67. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  68. package/ui/components/pay/AssetPicker.tsx +184 -0
  69. package/ui/components/pay/AvailableBalance.tsx +33 -2
  70. package/ui/components/pay/HandleReceive.tsx +213 -50
  71. package/ui/components/pay/NearbyFlow.tsx +616 -69
  72. package/ui/components/pay/PayForm.tsx +73 -8
  73. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  74. package/ui/components/pay/RecipientField.tsx +49 -4
  75. package/ui/components/pay/RequestHub.tsx +68 -8
  76. package/ui/components/pay/ResultBanner.tsx +41 -4
  77. package/ui/components/pay/UniversalSend.tsx +534 -30
  78. package/ui/components/pay/tokenSendCopy.ts +116 -0
  79. package/ui/components/pay/useRecipientInput.ts +36 -7
  80. package/ui/components/ui/PermissionSheet.tsx +65 -4
  81. package/ui/components/ui/Sheet.tsx +9 -2
  82. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  83. package/ui/components/vault/KeyChooser.tsx +96 -0
  84. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  85. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  86. package/ui/components/wallet/ActivityRow.tsx +101 -17
  87. package/ui/components/wallet/AmountInput.tsx +77 -25
  88. package/ui/components/wallet/AssetAmount.tsx +95 -0
  89. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  90. package/ui/components/wallet/tokenEviction.ts +65 -0
  91. package/ui/hooks/useExportWalletData.ts +39 -0
  92. package/ui/hooks/useMandala.ts +303 -0
  93. package/ui/hooks/useVaultBalance.ts +105 -7
  94. package/ui/hooks/useVaultCoverage.ts +52 -0
  95. package/ui/importDatabases.ts +7 -3
  96. package/ui/index.ts +50 -7
  97. package/ui/screens/ConnectionsScreen.tsx +46 -29
  98. package/ui/screens/PairScreen.tsx +12 -12
  99. package/ui/screens/PayScreen.tsx +130 -10
  100. package/ui/screens/SettingsScreen.tsx +18 -9
  101. package/ui/screens/VaultScreen.tsx +925 -171
  102. package/ui/screens/VaultTransferScreen.tsx +376 -123
  103. package/ui/screens/WalletCheckScreen.tsx +10 -1
  104. package/ui/screens/WalletConfigScreen.tsx +42 -20
  105. package/ui/screens/WalletHomeScreen.tsx +417 -86
  106. package/ui/screens/homeBadges.ts +9 -1
  107. package/ui/screens/tokenRowTitle.ts +68 -0
  108. package/ui/tokenFormat.ts +108 -0
  109. package/ui/tokenSeen.ts +75 -0
  110. package/ui/tokenStatus.ts +79 -0
  111. package/assets/sounds/vault-close.wav +0 -0
  112. package/assets/sounds/vault-open.wav +0 -0
  113. package/core/services/vault/k1.ts +0 -75
  114. package/core/services/vault/sealing.ts +0 -84
  115. package/core/services/vault/vaultDerivation.ts +0 -152
  116. package/core/services/vault/vaultPassphrase.ts +0 -287
  117. package/ui/components/vault/PassphraseField.tsx +0 -306
  118. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  119. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -0,0 +1,2437 @@
1
+ /**
2
+ * `createMandalaRuntime` — the one construction site for `MandalaRuntime`.
3
+ *
4
+ * This file is the seam between the wallet and `@bsv/mandala`. Everything
5
+ * above it (the UI, `useMandala()`) sees only `runtime.ts`'s pure interface;
6
+ * everything below it (the lib's transfer/receive pipelines, the overlay
7
+ * facilitator, the pure COVER walk) is reached from here and nowhere else. Two
8
+ * consequences are deliberate:
9
+ *
10
+ * · **One place knows the endpoints.** `configureMandala` is called by the
11
+ * wallet build (see `WalletContext`), and every lib entry point in this file
12
+ * reads those live bindings. A screen cannot address a different overlay,
13
+ * and a second Mandala deployment cannot appear behind the first.
14
+ * · **One place turns a lib failure into a wallet verdict.** `OverlayRefusedError`
15
+ * is mapped exactly once — to `TokenSendResult` for the handle rail, and to
16
+ * `OverlayVerdict` for the drain — so "the overlay said no permanently" and
17
+ * "the overlay could not be reached" can never be confused by a caller that
18
+ * forgot to check `retryable`. That distinction is the whole of FIX D.
19
+ *
20
+ * Nothing here decides money on its own. The settlement state machine lives in
21
+ * `drain.ts`, the coverage walk in the lib, and this module only supplies both
22
+ * with the bytes and the evidence the local tables hold.
23
+ */
24
+ import { Beef, Transaction, Utils, type WalletInterface } from '@bsv/sdk'
25
+ import { MandalaToken } from '@bsv/templates'
26
+ import {
27
+ blindingCommit,
28
+ blindingGet,
29
+ blindingPruneReserved,
30
+ blindingReserve,
31
+ cover as coverWalk,
32
+ createOverlayFacilitator,
33
+ fetchAdmission as libFetchAdmission,
34
+ fetchRegistry,
35
+ guardTokenRecipient,
36
+ journalRemove,
37
+ notifyPut,
38
+ notifyRemove,
39
+ payloadHash,
40
+ prepareBlindedPayment,
41
+ receiveTokens,
42
+ recipientCustomInstructions,
43
+ reconcileNotifications,
44
+ reconcileWallet,
45
+ registryIsLive,
46
+ resolveAssetMetadata,
47
+ submitToOverlay,
48
+ transferTokens,
49
+ verifyAdmission as libVerifyAdmission,
50
+ verifyFetchedAdmission,
51
+ type AdmissionEntry as LibAdmissionEntry,
52
+ type DerSignature,
53
+ type EvidenceSource,
54
+ type FetchedAdmission,
55
+ type MandalaStorage,
56
+ type MessageBoxLike,
57
+ type MessageBoxSender,
58
+ type OverlayFetch,
59
+ type OverlayRegistryRow,
60
+ type ReceivedTransfer,
61
+ type SettleFn
62
+ } from '@bsv/mandala'
63
+ import { resolveAssetState, type AssetAdminStateView } from '@bsv/mandala/adminState'
64
+ import type { AppChain } from '../config'
65
+ import type { MandalaEndpointConfig } from '../toolboxConfig'
66
+ import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
67
+ import { postOwnedByTxid, processOfflineActions, type OfflineTokenDeps } from '../storage/methods/processOfflineActions'
68
+ import type { PostOutcome } from '../offline/plan'
69
+ import { findOfflineActions } from '../storage/methods/offlineActions'
70
+ import { getPending, type KVStorage, type TokenCreditedHook } from '../localpay/pending'
71
+ import type { PaymentFrame } from '../localpay/codec'
72
+ import type { VerifyAdmissionFn } from '../localpay/settlementAck'
73
+ import type { LockToPayee, TokenBuildDeps } from '../localpay/build'
74
+ import { frameTokenAmount, tokenFrameSourcesFromOfflineActions, tokenFrameSourcesFromPending } from '../offline/tokenFrames'
75
+ import { resendTokenTransfer, type TokenResendAction, type TokenResendOutcome } from './resendTransfer'
76
+ import type { CoverBundle, CoverVerifier } from './bundle'
77
+ import { assembleBundle } from './bundle'
78
+ import {
79
+ TERMINAL_SETTLEMENT_STATES,
80
+ deriveTokenEdges,
81
+ listStuckSettlements,
82
+ NON_TERMINAL_SETTLEMENT_STATES,
83
+ populateEvidenceFromFrame,
84
+ postTokenStep,
85
+ type EvidenceFrame,
86
+ type TokenFrameSource
87
+ } from './drain'
88
+ import { createSettlementStore, type SettlementDb } from './settlementStore'
89
+ import {
90
+ MANDALA_BASKET,
91
+ STUCK_AFTER_MS,
92
+ type AdmissionEntryWire,
93
+ type AdmissionVerifier,
94
+ type CoverResult,
95
+ type FetchAdmissionFn,
96
+ type OverlayVerdict,
97
+ type SettlementStore,
98
+ type TokenAdmissionEdge,
99
+ type TokenAdmissionRow,
100
+ type TokenHandedOverHook,
101
+ type TokenHeldHook,
102
+ type TokenLinkageRow,
103
+ type TokenSettlementRow,
104
+ type TokenSettlementState
105
+ } from './types'
106
+ import type {
107
+ MandalaRuntime,
108
+ TokenActivityRow,
109
+ TokenHoldingsReview,
110
+ TokenActivityStatus,
111
+ TokenAssetInfo,
112
+ TokenAssetStatus,
113
+ TokenBalance,
114
+ TokenSendResult,
115
+ TokenSettleState
116
+ } from './runtime'
117
+ import { devLog } from '../logging'
118
+
119
+ // ───────────────────────── the duplicated-@bsv/sdk seam ─────────────────────────
120
+
121
+ /**
122
+ * `@bsv/mandala`'s `cover()` (bundle.ts's `TransactionLike` / `BundleBeef`) is
123
+ * typed STRUCTURALLY on purpose, precisely so a consuming app's own
124
+ * `Transaction`/`Beef` objects satisfy it with no cast at the call site —
125
+ * provided the app and the lib resolve to the SAME `@bsv/sdk` install. They do
126
+ * not here: this wallet pins `^2.4.1`, the linked `@bsv/mandala` pins
127
+ * `^2.1.6`, and `LockingScript` — which the walk never does anything with
128
+ * beyond handing it to `MandalaToken.decode`, but which the type still names —
129
+ * is consequently two classes with separately-declared private `_chunks`
130
+ * fields, so TypeScript refuses the assignment even though the runtime values
131
+ * are byte-identical. The crossing is therefore still a type-only cast, kept
132
+ * in this one named place — never an anonymous `as any` at a call site — and
133
+ * it disappears entirely the day the two packages dedupe onto one `@bsv/sdk`
134
+ * version (nothing else about this function would need to change).
135
+ *
136
+ * `expectedSignerKey` is always THIS runtime's own configured
137
+ * `overlayIdentityKey` — never `bundle.overlayIdentityKey`, which is
138
+ * payer-supplied data on the incoming-frame path (`coverVerifier`, built from
139
+ * `coverFromFrame`'s bundle). The lib's own `cover()` refuses with
140
+ * `unsafe_asset` unless the bundle's claimed key equals this expectation
141
+ * (spec amendment §9.10); passing anything else here would let a payer mint
142
+ * their own admissions under a key of their choosing and have COVER rubber-
143
+ * stamp them.
144
+ */
145
+ function libCoverArgs(
146
+ tip: Transaction,
147
+ bundle: {
148
+ assetId: string
149
+ overlayIdentityKey: string
150
+ tip: Transaction
151
+ beef: Map<string, Transaction> | { findTxid: (txid: string) => { tx?: Transaction } | undefined }
152
+ linkage: Map<string, number[]>
153
+ admissions: Map<string, LibAdmissionEntry>
154
+ },
155
+ expectedSignerKey: string
156
+ ): [Parameters<typeof coverWalk>[0], Parameters<typeof coverWalk>[1], Parameters<typeof coverWalk>[2]] {
157
+ return [
158
+ tip as unknown as Parameters<typeof coverWalk>[0],
159
+ bundle as unknown as Parameters<typeof coverWalk>[1],
160
+ { expectedSignerKey } as unknown as Parameters<typeof coverWalk>[2]
161
+ ]
162
+ }
163
+
164
+ // ─────────────────────────── the wallet's storage ───────────────────────────
165
+
166
+ /** What the KV adapter needs: the toolbox's own key/value table, plus raw SQL for the two verbs it lacks. */
167
+ export interface MandalaKvStorage extends KVStorage {
168
+ readonly sqliteDb?: {
169
+ runAsync(sql: string, params: (string | number | null)[]): Promise<{ changes: number }>
170
+ getAllAsync(sql: string, params: (string | number | null)[]): Promise<unknown[]>
171
+ }
172
+ }
173
+
174
+ /** LIKE treats these as wildcards; a journal prefix containing one must still match literally. */
175
+ function escapeLike(prefix: string): string {
176
+ return prefix.replace(/[\\%_]/g, c => `\\${c}`)
177
+ }
178
+
179
+ /**
180
+ * `MandalaStorage` over `StorageExpoSQLite`'s `key_value_store` (D3c).
181
+ *
182
+ * The lib's journals are the recovery contract: an overlay-accepted but
183
+ * not-yet-broadcast transaction is recoverable only because its `'accepted'`
184
+ * entry outlives the process that wrote it. React Native has no
185
+ * `localStorage`, so without this adapter the lib silently falls back to a
186
+ * process-lifetime Map and an interrupted broadcast becomes unrecoverable.
187
+ *
188
+ * `removeItem`/`keys` go straight to SQL because `StorageExpoSQLite` exposes
189
+ * neither — and both are deliberately hard failures when the database is
190
+ * closed rather than silent no-ops: a `removeItem` that quietly did nothing
191
+ * would leave a completed broadcast's journal entry behind forever, which the
192
+ * lib's reconcile pass reads as work still outstanding.
193
+ */
194
+ export function createMandalaKvStorage(storage: MandalaKvStorage): MandalaStorage {
195
+ const db = (): NonNullable<MandalaKvStorage['sqliteDb']> => {
196
+ const handle = storage.sqliteDb
197
+ if (!handle) throw new Error('Mandala journal storage: the wallet database is not open')
198
+ return handle
199
+ }
200
+ return {
201
+ getItem: async key => (await storage.getKeyValue(key)) ?? null,
202
+ setItem: async (key, value) => {
203
+ await storage.setKeyValue(key, value)
204
+ },
205
+ removeItem: async key => {
206
+ await db().runAsync('DELETE FROM key_value_store WHERE key = ?', [key])
207
+ },
208
+ keys: async prefix => {
209
+ const rows = (await db().getAllAsync(`SELECT key FROM key_value_store WHERE key LIKE ? ESCAPE '\\'`, [
210
+ `${escapeLike(prefix)}%`
211
+ ])) as { key: string }[]
212
+ return rows.map(r => r.key)
213
+ }
214
+ }
215
+ }
216
+
217
+ // ─────────────────────────────── construction ───────────────────────────────
218
+
219
+ /** The MessageBox surface both lib pipelines need, as one structural type. */
220
+ export type MandalaMessageBox = MessageBoxSender & MessageBoxLike
221
+
222
+ export interface CreateMandalaRuntimeArgs {
223
+ /** The guarded permissions manager. Every lib call is bound to `adminOriginator` (see `bindOriginator`). */
224
+ wallet: WalletInterface
225
+ adminOriginator: string
226
+ /** Supplies the settlement tables, the release drain and the pending queue. */
227
+ storage: StorageExpoSQLite
228
+ chain: AppChain
229
+ endpoints: MandalaEndpointConfig | undefined
230
+ /** Built lazily on first use so constructing a runtime does no I/O and needs no network. */
231
+ messageBox?: () => Promise<MandalaMessageBox>
232
+ /** Test seam for the overlay facilitator's transport. */
233
+ fetchImpl?: OverlayFetch
234
+ /** Opens a payer-side sealed `offline_actions.framePayload`; see `offline/tokenFrames.ts`. */
235
+ decodeSealedFrame?: (framePayload: string) => EvidenceFrame | undefined
236
+ /** Injected so the drain can rebuild a graph a missing ancestor broke. */
237
+ refetchBeef?: (txid: string) => Promise<number[] | undefined>
238
+ /** Test seam: the asset registry lookup (network + SPV in production). */
239
+ resolveMetadata?: (assetId: string) => Promise<{ label?: string; ticker?: string; decimals?: number } | null>
240
+ /**
241
+ * Whether this device has signal, for the ONE decision that turns on it: does
242
+ * a send take its own submit now (`settleNow`), or leave it to the drain?
243
+ * Never a gate on the hand-over itself — that happens either way.
244
+ *
245
+ * Supplied by the wallet build (`WalletContext` passes the app-wide
246
+ * `getOnline`) rather than imported here, so this module keeps having no
247
+ * NetInfo dependency of its own. Absent, it defaults OPTIMISTIC for the same
248
+ * reason every other connectivity guard in this codebase does: a wrong
249
+ * "online" costs one failed request that leaves the row exactly where it was,
250
+ * while a wrong "offline" makes a payer wait a drain interval for money that
251
+ * could have settled on the spot.
252
+ */
253
+ isOnline?: () => Promise<boolean>
254
+ /**
255
+ * How an admitted token tip reaches the network, for `settleNow`'s own step.
256
+ * Defaults to the release engine's own owned post, which is the same one the
257
+ * queue drain uses — injected only so a test can watch it without a wallet
258
+ * database underneath.
259
+ */
260
+ broadcast?: (txid: string) => Promise<PostOutcome>
261
+ now?: () => Date
262
+ }
263
+
264
+ /**
265
+ * One `listOutputs` page of the token basket, and the hard stop on paging —
266
+ * the same two figures the payment build uses (core/localpay/build.ts), so the
267
+ * balance a screen shows and the coins a build can spend come from one read
268
+ * discipline. A thousand is one round trip for any realistic basket; a
269
+ * million outputs is far past any real one, and the ceiling is what stops a
270
+ * wallet that reports a total it never serves from spinning a balance read.
271
+ */
272
+ const TOKEN_LIST_PAGE = 1000
273
+ const TOKEN_LIST_MAX_PAGES = 1000
274
+
275
+ /**
276
+ * Every lib call runs as the admin originator.
277
+ *
278
+ * `@bsv/mandala` takes a `WalletInterface` and passes no originator, which
279
+ * against `WalletPermissionsManager` means "an anonymous caller" — and the
280
+ * `'p mandala'` basket is P-routed, so an anonymous `listOutputs` would raise a
281
+ * permission prompt for the wallet's own balance screen. Binding here rather
282
+ * than teaching the lib about originators keeps the lib host-agnostic and keeps
283
+ * exactly one place in the wallet that can claim admin authority.
284
+ */
285
+ export function bindOriginator<T extends object>(wallet: T, originator: string): T {
286
+ return new Proxy(wallet, {
287
+ get(target, prop, receiver) {
288
+ const value = Reflect.get(target, prop, receiver) as unknown
289
+ if (typeof value !== 'function') return value
290
+ return (args: unknown, callerOriginator?: string) =>
291
+ (value as (a: unknown, o?: string) => unknown).call(target, args, callerOriginator ?? originator)
292
+ }
293
+ })
294
+ }
295
+
296
+ function messageOf(e: unknown): string {
297
+ return e instanceof Error ? e.message : String(e)
298
+ }
299
+
300
+ /** The lib's structured refusal, recognised by shape as well as by identity. */
301
+ interface RefusalLike {
302
+ code: string
303
+ retryable: boolean
304
+ spendTxid?: string
305
+ httpStatus: number
306
+ message: string
307
+ }
308
+
309
+ function asOverlayRefusal(e: unknown): RefusalLike | undefined {
310
+ const candidate = e as Partial<RefusalLike> & { name?: string }
311
+ if (candidate?.name !== 'OverlayRefusedError') return undefined
312
+ if (typeof candidate.code !== 'string') return undefined
313
+ return {
314
+ code: candidate.code,
315
+ retryable: candidate.retryable === true,
316
+ spendTxid: candidate.spendTxid,
317
+ httpStatus: typeof candidate.httpStatus === 'number' ? candidate.httpStatus : 0,
318
+ message: typeof candidate.message === 'string' ? candidate.message : candidate.code
319
+ }
320
+ }
321
+
322
+ /**
323
+ * The wire contract's verdict for one `/submit`, from whatever the lib threw.
324
+ *
325
+ * Direction matters more than precision here: anything that is not provably a
326
+ * FINAL manager verdict becomes `unavailable`, because a retryable fault
327
+ * mistaken for a refusal burns a payment that would have settled, while a
328
+ * refusal mistaken for a fault costs one idempotent re-submit.
329
+ */
330
+ export function verdictFromError(e: unknown): OverlayVerdict {
331
+ const refusal = asOverlayRefusal(e)
332
+ if (!refusal) return { kind: 'unavailable', code: 'ERR_UNAVAILABLE', retryable: true }
333
+ if (refusal.code === 'ERR_EVICTED' || refusal.httpStatus === 410) return { kind: 'evicted' }
334
+ if (refusal.retryable) return { kind: 'unavailable', code: refusal.code, retryable: true }
335
+ return { kind: 'refused', code: refusal.code, spendTxid: refusal.spendTxid }
336
+ }
337
+
338
+ /**
339
+ * `reconcileWallet`, with the one option this wallet is never allowed to omit.
340
+ *
341
+ * Declared here rather than inline for the same reason `tokenDeps` is assembled
342
+ * as a value: `@bsv/mandala` is a linked working copy, the sweep opt-out lands
343
+ * in it concurrently with this change, and a call written against the
344
+ * not-yet-published signature would fail to compile for a parameter the lib
345
+ * treats as optional anyway. An older lib IGNORES the second argument (it is a
346
+ * plain extra JS argument), which means it still sweeps — so this cast is a
347
+ * compile-time accommodation only; `abortGuard.ts` is what makes the sweep
348
+ * harmless either way, and it is not optional.
349
+ */
350
+ type ReconcileOptions = { sweep?: boolean; broadcast?: boolean }
351
+ type ReconcileWithOptions = (wallet: WalletInterface, options: ReconcileOptions) => ReturnType<typeof reconcileWallet>
352
+ const reconcileWalletWithOptions: ReconcileWithOptions = (wallet, options) =>
353
+ (reconcileWallet as unknown as ReconcileWithOptions)(wallet, options)
354
+
355
+ /**
356
+ * `{ reference }` from a lib result that carries one, or `{}`.
357
+ *
358
+ * A spread rather than a possibly-`undefined` field so `upsertSettlement`'s
359
+ * COALESCE keeps whatever the row already has: a re-derivation that could not
360
+ * find a reference must not erase one an earlier pass recorded.
361
+ */
362
+ function hexToBytes(hex: string): Uint8Array {
363
+ const clean = hex.length % 2 === 0 ? hex : ''
364
+ const out = new Uint8Array(clean.length / 2)
365
+ for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16) || 0
366
+ return out
367
+ }
368
+
369
+ function referenceOf(result: unknown): { reference?: string } {
370
+ const reference = (result as { reference?: unknown } | null)?.reference
371
+ return typeof reference === 'string' && reference.length > 0 ? { reference } : {}
372
+ }
373
+
374
+ /** A store for a runtime with no database: every read is empty, every write a no-op. */
375
+ function nullStore(): SettlementStore {
376
+ return {
377
+ getSettlement: async () => undefined,
378
+ getSettlementByReference: async () => undefined,
379
+ listSettlements: async () => [],
380
+ upsertSettlement: async () => undefined,
381
+ advanceSettlement: async () => false,
382
+ getAdmission: async () => undefined,
383
+ putAdmission: async () => undefined,
384
+ putEdges: async () => undefined,
385
+ parentsOf: async () => [],
386
+ getLinkage: async () => undefined,
387
+ putLinkage: async () => undefined
388
+ }
389
+ }
390
+
391
+ /** States a row reached by an overlay verdict; their money is not "unsettled", it is gone. */
392
+ const TERMINAL_BY_VERDICT = new Set<TokenSettlementState>(['refused', 'orphaned'])
393
+
394
+ /**
395
+ * States whose money is settled, and therefore NOT part of "settling…".
396
+ *
397
+ * `admitted` belongs here for the same reason it reads as `settled` on the
398
+ * activity list (see `activityStatusOf`): σ_I is the issuer's overlay having
399
+ * folded the transaction into its own state, which is the entire meaning of
400
+ * settlement. The broadcast that follows is this device's bookkeeping. Leaving
401
+ * `admitted` in the unsettled figure told a holder their money was still in
402
+ * flight for as long as they happened to be offline after it had, in fact,
403
+ * settled — and did it in the one number they check to decide whether to spend.
404
+ */
405
+ const SETTLED_STATES = new Set<TokenSettlementState>(['broadcast', 'admitted'])
406
+
407
+ interface ListedTokenOutput {
408
+ outpoint: string
409
+ txid: string
410
+ vout: number
411
+ assetId: string
412
+ amount: number
413
+ spendable: boolean
414
+ }
415
+
416
+ /**
417
+ * How a settlement row reads on the activity list.
418
+ *
419
+ * `admitted` is `settled`, not "nearly settled": σ_I is the issuer's overlay
420
+ * having folded the transaction into its own state, which is exactly what the
421
+ * ux copy means by "settled with {{issuer}}". The broadcast that follows is
422
+ * this device's bookkeeping, not the payment's fate.
423
+ */
424
+ export function activityStatusOf(row: TokenSettlementRow, nowMs: number, olderThanMs = STUCK_AFTER_MS): TokenActivityStatus {
425
+ switch (row.state) {
426
+ case 'broadcast':
427
+ case 'admitted':
428
+ return 'settled'
429
+ case 'refused':
430
+ return 'refused'
431
+ case 'orphaned':
432
+ return 'reversed'
433
+ default: {
434
+ const at = Date.parse(row.createdAt)
435
+ return Number.isFinite(at) && nowMs - at >= olderThanMs ? 'stuck' : 'settling'
436
+ }
437
+ }
438
+ }
439
+
440
+ export function createMandalaRuntime(args: CreateMandalaRuntimeArgs): MandalaRuntime {
441
+ const { wallet, adminOriginator, storage, chain, endpoints } = args
442
+ const now = args.now ?? (() => new Date())
443
+ const db = storage.sqliteDb
444
+ // Any chain the host stated complete endpoints for; no chain is hardcoded.
445
+ const available = endpoints !== undefined && db !== undefined
446
+ const overlayUrl = endpoints?.overlayUrl ?? ''
447
+ const overlayIdentityKey = endpoints?.overlayIdentityKey ?? ''
448
+ const messageBoxUrl = endpoints?.messageBoxUrl ?? ''
449
+ const store: SettlementStore = db ? createSettlementStore(db as unknown as SettlementDb) : nullStore()
450
+ const bound = bindOriginator(wallet, adminOriginator)
451
+
452
+ const listeners = new Set<() => void>()
453
+ const emit = (): void => {
454
+ for (const listener of [...listeners]) {
455
+ try {
456
+ listener()
457
+ } catch (e) {
458
+ devLog('[mandala] a runtime subscriber threw:', e)
459
+ }
460
+ }
461
+ }
462
+
463
+ // Cross-call dedup for the MessageBox inbox: a slow drain and a manual
464
+ // refresh must not both internalize the same message.
465
+ const processedMessages = new Set<string>()
466
+ let messageBoxPromise: Promise<MandalaMessageBox> | undefined
467
+ const messageBox = async (): Promise<MandalaMessageBox> => {
468
+ if (!args.messageBox) throw new Error('Mandala: no MessageBox client is configured')
469
+ messageBoxPromise ??= args.messageBox().catch((e: unknown) => {
470
+ // A FAILURE is never memoized. Construction can fail for entirely
471
+ // transient reasons (no network at launch, a host that is briefly down),
472
+ // and a cached rejection would poison every later inbox drain and every
473
+ // pending-notification retry for the life of the process — which is
474
+ // exactly the window `reconcileNotifications` exists to close.
475
+ messageBoxPromise = undefined
476
+ throw e
477
+ })
478
+ return await messageBoxPromise
479
+ }
480
+
481
+ let identityKeyPromise: Promise<string> | undefined
482
+ const identityKey = async (): Promise<string> => {
483
+ identityKeyPromise ??= bound.getPublicKey({ identityKey: true }).then(r => r.publicKey)
484
+ return await identityKeyPromise
485
+ }
486
+
487
+ const metadataCache = new Map<string, { label?: string; ticker?: string; decimals?: number } | null>()
488
+ const resolveMetadata = args.resolveMetadata ?? (async (assetId: string) => await resolveAssetMetadata(assetId))
489
+ const metadataOf = async (assetId: string): Promise<{ label?: string; ticker?: string; decimals?: number } | null> => {
490
+ const cached = metadataCache.get(assetId)
491
+ if (cached !== undefined) return cached
492
+ let resolved: { label?: string; ticker?: string; decimals?: number } | null = null
493
+ try {
494
+ resolved = await resolveMetadata(assetId)
495
+ } catch (e) {
496
+ // A registry lookup is a display concern. It must never be the reason a
497
+ // balance fails to render — the assetId itself is always a usable name.
498
+ devLog(`[mandala] could not resolve metadata for ${assetId}:`, e)
499
+ }
500
+ metadataCache.set(assetId, resolved)
501
+ return resolved
502
+ }
503
+
504
+ const assetInfo = async (assetId: string): Promise<TokenAssetInfo> => {
505
+ const meta = await metadataOf(assetId)
506
+ const issuerName = (meta as Record<string, unknown> | null)?.issuerName
507
+ return {
508
+ assetId,
509
+ label: meta?.label && meta.label !== '' ? meta.label : `${assetId.slice(0, 20)}…`,
510
+ ticker: meta?.ticker ?? '',
511
+ decimals: Number(meta?.decimals) || 0,
512
+ ...(typeof issuerName === 'string' && issuerName !== '' ? { issuerName } : {}),
513
+ overlayUrl,
514
+ overlayIdentityKey
515
+ }
516
+ }
517
+
518
+ // ── Asset status facts (paused / frozen / access mode / admission) ──
519
+ //
520
+ // Regulatory copy the UI wants to show — a paused banner, a frozen-balance
521
+ // notice, an access-mode refusal, "not yet admitted to send/receive" — all
522
+ // read from the overlay's own admin state and the issuer's identity
523
+ // registry. Never a gate anything transacts against: every read here is
524
+ // best-effort and a stale or unreachable overlay reads as the least
525
+ // alarming answer, never a thrown error.
526
+
527
+ const ASSET_STATUS_TTL_MS = 10_000
528
+
529
+ interface AssetStatusSnapshot {
530
+ state: AssetAdminStateView | null
531
+ registryRows: OverlayRegistryRow[]
532
+ registryActive: boolean
533
+ metadataResolved: boolean
534
+ }
535
+
536
+ const assetStatusCache = new Map<string, { at: number; snapshot: AssetStatusSnapshot }>()
537
+
538
+ const isAdmittedIn = (rows: OverlayRegistryRow[], key: string): boolean =>
539
+ rows.some(r => r.identityKey.toLowerCase() === key.toLowerCase() && r.status === 'admitted')
540
+
541
+ const loadAssetStatusSnapshot = async (assetId: string, opts: { force?: boolean } = {}): Promise<AssetStatusSnapshot> => {
542
+ const [state, registryRows, meta] = await Promise.all([
543
+ (async () => {
544
+ try {
545
+ return await resolveAssetState(assetId, opts)
546
+ } catch (e) {
547
+ devLog(`[mandala] could not resolve admin state for ${assetId}:`, e)
548
+ return null
549
+ }
550
+ })(),
551
+ (async () => {
552
+ try {
553
+ return await fetchRegistry()
554
+ } catch (e) {
555
+ devLog('[mandala] could not fetch the identity registry:', e)
556
+ return [] as OverlayRegistryRow[]
557
+ }
558
+ })(),
559
+ metadataOf(assetId)
560
+ ])
561
+ return { state, registryRows, registryActive: registryIsLive(registryRows), metadataResolved: meta !== null }
562
+ }
563
+
564
+ const buildAssetStatus = async (snapshot: AssetStatusSnapshot): Promise<TokenAssetStatus> => {
565
+ const { state, registryRows, registryActive, metadataResolved } = snapshot
566
+ const mine = await identityKey()
567
+ const frozenBaseUnits = (state?.frozenOutpoints ?? []).reduce((sum, o) => sum + (Number(o.amount) || 0), 0)
568
+ return {
569
+ paused: state?.isPaused ?? false,
570
+ frozenBaseUnits,
571
+ accessMode: state?.accessMode,
572
+ selfAdmitted: registryActive ? isAdmittedIn(registryRows, mine) : undefined,
573
+ recipientAdmitted: async (recipientIdentityKey: string) =>
574
+ registryActive ? isAdmittedIn(registryRows, recipientIdentityKey) : undefined,
575
+ metadataResolved,
576
+ messageBoxUrl
577
+ }
578
+ }
579
+
580
+ /**
581
+ * A cache entry is stamped with the time of the LOAD that produced it, never
582
+ * with the time it was last read.
583
+ *
584
+ * Re-stamping on a hit is a self-renewing cache: every read inside the TTL
585
+ * pushes the expiry out, so a screen that polls faster than 10s (the balance
586
+ * header, the send sheet's recipient check) would keep one snapshot alive
587
+ * forever and never see the asset get paused, frozen or un-admitted. The
588
+ * whole point of the TTL is that it expires while somebody is watching.
589
+ */
590
+ const assetStatus = async (assetId: string): Promise<TokenAssetStatus> => {
591
+ const cached = assetStatusCache.get(assetId)
592
+ if (cached && now().getTime() - cached.at < ASSET_STATUS_TTL_MS) return await buildAssetStatus(cached.snapshot)
593
+ const snapshot = await loadAssetStatusSnapshot(assetId)
594
+ assetStatusCache.set(assetId, { at: now().getTime(), snapshot })
595
+ return await buildAssetStatus(snapshot)
596
+ }
597
+
598
+ const refreshAssetStatus = async (assetId: string): Promise<TokenAssetStatus> => {
599
+ const snapshot = await loadAssetStatusSnapshot(assetId, { force: true })
600
+ assetStatusCache.set(assetId, { at: now().getTime(), snapshot })
601
+ return await buildAssetStatus(snapshot)
602
+ }
603
+
604
+ /**
605
+ * Every Mandala output this wallet holds, valued from its SCRIPT.
606
+ *
607
+ * `include: 'entire transactions'` is not an optimisation: a token output
608
+ * carries one satoshi and its real figure in the locking script, so the coins
609
+ * cannot be valued at all without their source transactions.
610
+ */
611
+ const listTokenOutputs = async (): Promise<ListedTokenOutput[]> => {
612
+ // The WHOLE basket, page by page, with the same loop discipline as the
613
+ // payment build's `listTokenBasket` (core/localpay/build.ts): one unpaged
614
+ // read capped at 1000 was the balance this screen showed — and the figure
615
+ // the send surfaces gate on ("more than your USDX balance") — while the
616
+ // build spends from every page. Past 1000 outputs that under-count turned
617
+ // into a refusal of money the wallet plainly had. The BEEF accumulates
618
+ // across pages because a coin's value lives in its source transaction's
619
+ // script, so page two's coins are unreadable without page two's BEEF.
620
+ const listed: Awaited<ReturnType<WalletInterface['listOutputs']>>['outputs'] = []
621
+ const beef = new Beef()
622
+ try {
623
+ let offset = 0
624
+ for (let page = 0; page < TOKEN_LIST_MAX_PAGES; page++) {
625
+ const chunk = await bound.listOutputs({
626
+ basket: MANDALA_BASKET,
627
+ include: 'entire transactions',
628
+ includeCustomInstructions: true,
629
+ limit: TOKEN_LIST_PAGE,
630
+ offset
631
+ })
632
+ if (chunk.BEEF) beef.mergeBeef(chunk.BEEF)
633
+ const outputs = chunk.outputs ?? []
634
+ listed.push(...outputs)
635
+ // An empty page always ends it — that, plus the page ceiling, is what
636
+ // keeps a wallet that ignores `offset` from looping forever.
637
+ if (outputs.length === 0) break
638
+ offset += outputs.length
639
+ if (typeof chunk.totalOutputs === 'number') {
640
+ // The wallet's own count is the authority when it reports one. A
641
+ // SHORT page must not end the loop here: a wallet is free to cap
642
+ // `limit` below what was asked for, and treating its cap as "end of
643
+ // basket" would re-introduce the very truncation this loop removes.
644
+ if (offset >= chunk.totalOutputs) break
645
+ } else if (outputs.length < TOKEN_LIST_PAGE) {
646
+ break
647
+ }
648
+ }
649
+ } catch (e) {
650
+ // A wallet with no Mandala basket yet, a storage fault, or a page whose
651
+ // BEEF would not merge. Either way a balance screen shows nothing rather
652
+ // than a partial figure it would then gate money on, or an error it
653
+ // cannot act on.
654
+ devLog('[mandala] could not list the token basket:', e)
655
+ return []
656
+ }
657
+ const out: ListedTokenOutput[] = []
658
+ for (const output of listed) {
659
+ const [txid, voutText] = output.outpoint.split('.')
660
+ const vout = Number(voutText)
661
+ const script = beef.findTxid(txid)?.tx?.outputs[vout]?.lockingScript
662
+ if (!script) continue
663
+ try {
664
+ const decoded = MandalaToken.decode(script)
665
+ out.push({
666
+ outpoint: output.outpoint,
667
+ txid,
668
+ vout,
669
+ assetId: decoded.assetId,
670
+ amount: decoded.amount,
671
+ spendable: output.spendable !== false
672
+ })
673
+ } catch {
674
+ // A stray non-token output in the basket is not this asset's coin.
675
+ }
676
+ }
677
+ return out
678
+ }
679
+
680
+ /** The tip's own bytes plus its whole ancestry, from the wallet's request rows. */
681
+ const loadBeef = async (txid: string): Promise<Beef | undefined> => {
682
+ try {
683
+ const api = (await storage.findProvenTxReqs({ partial: { txid } }))[0]
684
+ if (!api?.rawTx) return undefined
685
+ const beef = new Beef()
686
+ beef.mergeRawTx(api.rawTx)
687
+ if (api.inputBEEF) beef.mergeBeef(api.inputBEEF)
688
+ return beef
689
+ } catch (e) {
690
+ devLog(`[mandala] could not read the stored bytes of ${txid}:`, e)
691
+ return undefined
692
+ }
693
+ }
694
+
695
+ /** A Beef that actually carries this transaction's bytes (not merely its txid). */
696
+ const carries = (beef: Beef | undefined, txid: string): beef is Beef => beef?.findTxid(txid)?.tx !== undefined
697
+
698
+ /**
699
+ * The bytes of `txid`, from anywhere on this device that holds them.
700
+ *
701
+ * `loadBeef` can only ever find a transaction THIS wallet built or
702
+ * internalized — `findProvenTxReqs` is keyed by the wallet's own request
703
+ * rows. A multi-hop offline chain (spec §1.6) routinely puts a FOREIGN
704
+ * transaction in the middle of a submit set: Alice → Bob → us, where Bob's
705
+ * hop has no request row here at all. `cover()` covers it happily (its bytes
706
+ * are right there in the frame's ancestry), `mustSubmit` names it, and the
707
+ * submit that follows used to come back `ERR_LOCAL_BYTES` forever — a whole
708
+ * chain stalled on a transaction this device was holding the entire time.
709
+ *
710
+ * So the fallback asks every local BEEF that could contain it: the
711
+ * settlement rows' own tips first (their request rows carry the ancestry as
712
+ * `inputBEEF`), then the durable frames the drain already reads for
713
+ * evidence. The ancestor is then served with `toBinaryAtomic` out of
714
+ * whichever one had it, exactly as if it had been ours.
715
+ */
716
+ const loadBeefContaining = async (txid: string): Promise<Beef | undefined> => {
717
+ const own = await loadBeef(txid)
718
+ if (carries(own, txid)) return own
719
+
720
+ let rows: TokenSettlementRow[] = []
721
+ try {
722
+ rows = await store.listSettlements()
723
+ } catch (e) {
724
+ devLog(`[mandala] could not list settlements while looking for the bytes of ${txid}:`, e)
725
+ }
726
+ for (const row of rows) {
727
+ if (row.txid === txid) continue
728
+ const beef = await loadBeef(row.txid)
729
+ if (carries(beef, txid)) return beef
730
+ }
731
+
732
+ for (const source of await frames()) {
733
+ let beef: Beef | undefined
734
+ try {
735
+ beef = Beef.fromBinary(source.frame.transaction)
736
+ } catch {
737
+ continue // a frame this device cannot parse simply holds no bytes for us
738
+ }
739
+ if (carries(beef, txid)) return beef
740
+ }
741
+ return undefined
742
+ }
743
+
744
+ const libAdmissions = (entries: readonly AdmissionEntryWire[]): Map<string, LibAdmissionEntry> =>
745
+ new Map(
746
+ entries.map(entry => [
747
+ entry.txid,
748
+ {
749
+ outputsToAdmit: [...entry.outputsToAdmit],
750
+ signature: Array.from(entry.signature),
751
+ signerKey: entry.signerKey
752
+ }
753
+ ])
754
+ )
755
+
756
+ /**
757
+ * The pure COVER walk, over the evidence the payee's frame carried.
758
+ *
759
+ * This is the injection `bundle.ts` was written around: the walk and the
760
+ * overlay's σ_I digest live together in `@bsv/mandala`, so wallet and overlay
761
+ * cannot disagree about what a signature covers.
762
+ *
763
+ * `expectedSignerKey` is THIS session's own configured `overlayIdentityKey`
764
+ * — never `bundle.overlayIdentityKey`, which is the frame's own (untrusted)
765
+ * claim. See `libCoverArgs`.
766
+ */
767
+ const coverVerifier: CoverVerifier = (tip, bundle: CoverBundle) =>
768
+ coverWalk(
769
+ ...libCoverArgs(
770
+ tip.tx,
771
+ {
772
+ assetId: bundle.assetId,
773
+ overlayIdentityKey: bundle.overlayIdentityKey,
774
+ tip: tip.tx,
775
+ beef: bundle.beef,
776
+ linkage: new Map([...bundle.linkage].map(([txid, payload]) => [txid, Array.from(payload)])),
777
+ admissions: new Map(
778
+ [...bundle.admissions].map(([txid, entry]) => [
779
+ txid,
780
+ {
781
+ outputsToAdmit: [...entry.outputsToAdmit],
782
+ signature: Array.from(entry.signature),
783
+ signerKey: entry.signerKey
784
+ }
785
+ ])
786
+ )
787
+ },
788
+ overlayIdentityKey
789
+ )
790
+ )
791
+
792
+ /** FIX H, in one function: an entry proves nothing unless THIS overlay signed it. */
793
+ const verifyAdmissionEntry: VerifyAdmissionFn = (entry, key) => {
794
+ if (entry.signerKey.toLowerCase() !== key.toLowerCase()) return false
795
+ try {
796
+ return libVerifyAdmission({
797
+ txid: entry.txid,
798
+ outputsToAdmit: entry.outputsToAdmit,
799
+ signature: Array.from(entry.signature),
800
+ signerKey: entry.signerKey
801
+ })
802
+ } catch {
803
+ return false
804
+ }
805
+ }
806
+
807
+ /**
808
+ * The same check with the expected signer already fixed — the only shape the
809
+ * drain, the frame verifier and the evidence cache are allowed to take.
810
+ *
811
+ * Wire contract §9.10: the key a σ_I is checked against is THIS session's
812
+ * configuration. A caller that could name the key would be able to hand in
813
+ * `frame.token.overlayIdentityKey` or `row.overlayIdentityKey`, both of which
814
+ * are counterparty-supplied data, and a self-signed admission would then
815
+ * verify perfectly against the attacker's own key.
816
+ */
817
+ const verifyAdmission: AdmissionVerifier = entry => verifyAdmissionEntry(entry, overlayIdentityKey)
818
+
819
+ /** What every `populateEvidenceFromFrame` call in this file anchors trust on. */
820
+ const evidenceAnchor = { overlayIdentityKey, verifyAdmission }
821
+
822
+ /**
823
+ * The hand-over rail's evidence, read out of this device's OWN settlement
824
+ * tables (spec §4.5, wire contract §9.13).
825
+ *
826
+ * The lib's default source is its own transaction journal, which drops an
827
+ * `'accepted'` entry as soon as the broadcast lands — so a wallet that has
828
+ * been running for a week would hand its payee almost no admissions and
829
+ * force it to walk (and submit) a chain that is long since settled. The
830
+ * durable tables here are exactly the store the lib's `EvidenceSource` hook
831
+ * was added for.
832
+ *
833
+ * FIX H / §9.10 applies in the outgoing direction too: a cached admission is
834
+ * forwarded as this device's own claim about the chain, so only one signed
835
+ * by the CONFIGURED overlay key is offered. Anything else (a foreign key, or
836
+ * the empty `signerKey` an unsigned `/submit` answer is deliberately
837
+ * recorded with) is ABSENT — the ancestor is walked and its linkage
838
+ * forwarded instead, which is always correct and merely costs a submit.
839
+ *
840
+ * Neither lookup throws: the lib treats `undefined` as "nothing held", and a
841
+ * storage fault at send time must cost evidence, never the payment.
842
+ */
843
+ const storeEvidenceSource: EvidenceSource = {
844
+ admissionFor: async txid => {
845
+ let row: TokenAdmissionRow | undefined
846
+ try {
847
+ row = await store.getAdmission(txid)
848
+ } catch (e) {
849
+ devLog(`[mandala] hand-over evidence could not read the admission of ${txid}:`, e)
850
+ return undefined
851
+ }
852
+ if (!row) return undefined
853
+ if (row.signerKey === '' || row.signerKey !== overlayIdentityKey) return undefined
854
+ if (row.signatureHex === '' || row.outputsToAdmit.length === 0) return undefined
855
+ return { outputsToAdmit: [...row.outputsToAdmit], signature: row.signatureHex, signerKey: row.signerKey }
856
+ },
857
+ linkageFor: async txid => {
858
+ let row: TokenLinkageRow | undefined
859
+ try {
860
+ row = await store.getLinkage(txid)
861
+ } catch (e) {
862
+ devLog(`[mandala] hand-over evidence could not read the linkage payload of ${txid}:`, e)
863
+ return undefined
864
+ }
865
+ if (!row || row.payloadBytes.length === 0) return undefined
866
+ return Array.from(row.payloadBytes)
867
+ }
868
+ }
869
+
870
+ /**
871
+ * Pull into `beef` every parent of `tip` it does not already carry, from the
872
+ * wallet's own ancestry lookup.
873
+ *
874
+ * 2026-09-15 incident: a noSend action's stored `inputBEEF` is only what the
875
+ * lib passed to `createAction` — the token parents. The fee input the wallet
876
+ * itself allocated (change from an earlier, still-unmined BSV send) was not
877
+ * in it, and to the COVER walk a parent it cannot see is a hole (FIX B: it
878
+ * could be a token). The immediate submit therefore never went out, and it
879
+ * did so silently. The walk must see the same ancestry the wallet does.
880
+ *
881
+ * Best-effort per parent: a lookup that fails leaves that parent missing,
882
+ * and the walk reports the hole exactly as before.
883
+ */
884
+ const completeAncestry = async (beef: Beef, tip: Transaction): Promise<void> => {
885
+ const lookup = (
886
+ storage as unknown as {
887
+ getValidBeefForTxid?: (txid: string, mergeToBeef?: Beef) => Promise<Beef | undefined>
888
+ }
889
+ ).getValidBeefForTxid
890
+ if (typeof lookup !== 'function') return
891
+ for (const input of tip.inputs) {
892
+ const parentTxid = input.sourceTXID ?? input.sourceTransaction?.id('hex')
893
+ if (!parentTxid || beef.findTxid(parentTxid)?.tx !== undefined) continue
894
+ try {
895
+ await lookup.call(storage, parentTxid, beef)
896
+ } catch (e) {
897
+ devLog(`[mandala] could not load the ancestry of ${parentTxid} for the cover walk:`, e)
898
+ }
899
+ }
900
+ }
901
+
902
+ const cover = async (tipTxid: string): Promise<CoverResult> => {
903
+ if (overlayIdentityKey === '') return { ok: false, reason: 'unsafe_asset' }
904
+ const beef = await loadBeef(tipTxid)
905
+ if (!beef) return { ok: false, reason: 'shape' }
906
+ let tip: Transaction | undefined
907
+ try {
908
+ tip = beef.findAtomicTransaction(tipTxid) ?? beef.findTxid(tipTxid)?.tx
909
+ } catch {
910
+ return { ok: false, reason: 'shape' }
911
+ }
912
+ if (!tip) return { ok: false, reason: 'shape' }
913
+ await completeAncestry(beef, tip)
914
+
915
+ const row = await store.getSettlement(tipTxid)
916
+ const assetId = row?.assetId ?? assetIdOfTx(tip)
917
+ if (!assetId) return { ok: false, reason: 'unsafe_asset' }
918
+
919
+ const bundle = await assembleBundle({ tipTx: tip, assetId, overlayIdentityKey, store })
920
+ const txs = new Map<string, Transaction>()
921
+ for (const entry of beef.txs) if (entry.tx) txs.set(entry.txid, entry.tx)
922
+ return coverWalk(
923
+ ...libCoverArgs(
924
+ tip,
925
+ {
926
+ assetId,
927
+ overlayIdentityKey,
928
+ tip,
929
+ beef: txs,
930
+ linkage: new Map(bundle.linkage.map(l => [l.txid, Array.from(l.payload)])),
931
+ admissions: libAdmissions(bundle.admissions)
932
+ },
933
+ overlayIdentityKey
934
+ )
935
+ )
936
+ }
937
+
938
+ /**
939
+ * `POST /submit` for one txid, with the beef and linkage the local tables hold.
940
+ *
941
+ * An admitted response with no σ_I is still an admission — the overlay has
942
+ * folded the transaction into its state — so the row advances. But it is
943
+ * recorded with an EMPTY `signerKey` so neither `assembleBundle` nor the
944
+ * drain's own `admissionStandsIn` can ever mistake it for evidence: a
945
+ * counterparty handed an unsigned "admission" would otherwise see its
946
+ * ancestor treated as a bottom, with the linkage that could have settled it
947
+ * left behind.
948
+ */
949
+ const submit = async (txid: string): Promise<OverlayVerdict> => {
950
+ // Not `loadBeef`: a submit set is parents-first and its middle hops are
951
+ // routinely somebody else's transactions (spec §1.6). See
952
+ // `loadBeefContaining`.
953
+ const beef = await loadBeefContaining(txid)
954
+ if (!beef) return { kind: 'unavailable', code: 'ERR_LOCAL_BYTES', retryable: true }
955
+ // Same hole as `cover`'s: a stored `inputBEEF` carries the token parents
956
+ // the lib supplied, not the fee parent the wallet allocated. The overlay's
957
+ // SPV check needs every input's source transaction, so complete the
958
+ // ancestry here too (2026-09-15: a4a6b346 came back 503 "missing an
959
+ // associated source transaction" on every pass).
960
+ const own = beef.findTxid(txid)?.tx
961
+ if (own) await completeAncestry(beef, own)
962
+ let bytes: number[]
963
+ try {
964
+ bytes = beef.toBinaryAtomic(txid)
965
+ } catch (e) {
966
+ devLog(`[mandala] could not serialize ${txid} for submission:`, e)
967
+ return { kind: 'unavailable', code: 'ERR_LOCAL_BYTES', retryable: true }
968
+ }
969
+ let linkage: TokenLinkageRow | undefined
970
+ try {
971
+ linkage = await store.getLinkage(txid)
972
+ } catch (e) {
973
+ devLog(`[mandala] could not read the linkage payload of ${txid}:`, e)
974
+ }
975
+ try {
976
+ const admitted = await submitToOverlay(
977
+ bytes,
978
+ linkage && linkage.payloadBytes.length > 0 ? Array.from(linkage.payloadBytes) : undefined,
979
+ facilitator()
980
+ )
981
+ // The lib already refuses an unsigned or unverifiable answer
982
+ // (ERR_NO_ADMISSION / ERR_BAD_ADMISSION); this is the wallet's own
983
+ // check on top, against ITS configured key and verifier, so no
984
+ // answer can reach the settlement tables as an admission without a
985
+ // σ_I that verifies here. An admitted set alone proves nothing about
986
+ // whether the operator accepted the transaction (2026-09-15 review).
987
+ const signatureHex = admitted.admissionSignature ?? ''
988
+ const signerKey = admitted.admissionIdentityKey ?? ''
989
+ if (signatureHex === '' || signerKey === '') {
990
+ devLog(`[mandala] /submit of ${txid} admitted outputs but carried no admission signature; not an admission`)
991
+ return { kind: 'unavailable', code: 'ERR_NO_ADMISSION', retryable: true }
992
+ }
993
+ const trusted = await verifyAdmission({
994
+ txid,
995
+ outputsToAdmit: admitted.outputsToAdmit,
996
+ signature: hexToBytes(signatureHex),
997
+ signerKey
998
+ })
999
+ if (!trusted) {
1000
+ devLog(`[mandala] /submit of ${txid}: admission signature does not verify under the configured key; not an admission`)
1001
+ return { kind: 'unavailable', code: 'ERR_BAD_ADMISSION', retryable: true }
1002
+ }
1003
+ return { kind: 'admitted', outputsToAdmit: admitted.outputsToAdmit, signatureHex, signerKey }
1004
+ } catch (e) {
1005
+ if (isEmptyAdmittedSet(e)) return await resolveEmptyAdmittedSet(txid)
1006
+ return verdictFromError(e)
1007
+ }
1008
+ }
1009
+
1010
+ /**
1011
+ * The overlay engine's answer for a transaction it has ALREADY applied.
1012
+ *
1013
+ * `Engine.submit` short-circuits a txid its storage already holds for the
1014
+ * topic (`doesAppliedTransactionExist` → `isDupe`) and puts an EMPTY
1015
+ * `outputsToAdmit` in the STEAK; the lib has no verdict shape for that and
1016
+ * throws a bare `Error('overlay rejected the transaction')`. On a phone that
1017
+ * is the ordinary shop case, not an edge: the payee had signal, its drain
1018
+ * submitted and broadcast the tip first, and the payer's own optional
1019
+ * submit (rule 6) arrives second. Read as a plain fault — which is what
1020
+ * `verdictFromError` makes of every unstructured throw — it stalled the
1021
+ * payer's queue row at 'queued' on every single tick, while the transaction
1022
+ * was already on chain (2026-09-16).
1023
+ *
1024
+ * Matched by message because the lib gives nothing else to match; a
1025
+ * structured `OverlayRefusedError` never takes this path.
1026
+ */
1027
+ const isEmptyAdmittedSet = (e: unknown): boolean =>
1028
+ asOverlayRefusal(e) === undefined && /overlay rejected the transaction/i.test(messageOf(e))
1029
+
1030
+ /**
1031
+ * An empty admitted set is not a verdict, so the verdict is fetched instead:
1032
+ * `GET /admin/admission/:txid`, FIX-H-verified against the configured key.
1033
+ * An admission on record settles the row exactly as a fresh σ_I would; a
1034
+ * refusal or eviction on record is the final verdict it always was; and
1035
+ * nothing on record (or an unreachable lookup) stays retryable, under a code
1036
+ * of its own so the stall is recognisable in a log.
1037
+ */
1038
+ const resolveEmptyAdmittedSet = async (txid: string): Promise<OverlayVerdict> => {
1039
+ const onRecord = await fetchAdmission(overlayUrl, txid)
1040
+ if (onRecord === undefined || onRecord.kind === 'unavailable') {
1041
+ devLog(`[mandala] /submit of ${txid} admitted nothing and no admission is on record; the step is retried next pass`)
1042
+ return { kind: 'unavailable', code: 'ERR_EMPTY_ADMISSION', retryable: true }
1043
+ }
1044
+ devLog(`[mandala] /submit of ${txid} admitted nothing; the overlay's record says '${onRecord.kind}'`)
1045
+ return onRecord
1046
+ }
1047
+
1048
+ /**
1049
+ * Every spendable token coin's txid has a verified σ_I cached — fetched from
1050
+ * the overlay when it is missing.
1051
+ *
1052
+ * A coin can be in the basket with no admission on record: credited through
1053
+ * the plain inbox path, restored from a backup, or admitted by a counterparty
1054
+ * on this device's behalf. Such a coin spends fine online, but an OFFLINE
1055
+ * hand-over of it would carry no σ_I for its ancestor, and the payee's COVER
1056
+ * walk would have to submit the ancestor itself — impossible offline. So
1057
+ * this pass asks `GET /admin/admission/:txid` for each coin's txid that has
1058
+ * no trustworthy cached entry (FIX-H verified on the way in) and records it.
1059
+ * Best-effort, at most one ask per txid per pass, never throws.
1060
+ */
1061
+ const ensureAdmissionsForHoldings = async (): Promise<number> => {
1062
+ if (!available) return 0
1063
+ let outputs: ListedTokenOutput[]
1064
+ try {
1065
+ outputs = await listTokenOutputs()
1066
+ } catch (e) {
1067
+ devLog('[mandala] could not list token holdings to complete their admissions:', e)
1068
+ return 0
1069
+ }
1070
+ const byTxid = new Map<string, number[]>()
1071
+ for (const o of outputs) {
1072
+ if (!o.spendable) continue
1073
+ byTxid.set(o.txid, [...(byTxid.get(o.txid) ?? []), o.vout])
1074
+ }
1075
+ let fetched = 0
1076
+ for (const [txid, vouts] of byTxid) {
1077
+ let cached: TokenAdmissionRow | undefined
1078
+ try {
1079
+ cached = await store.getAdmission(txid)
1080
+ } catch (e) {
1081
+ devLog(`[mandala] could not read the cached admission of ${txid}:`, e)
1082
+ continue
1083
+ }
1084
+ if (cached && cached.signatureHex !== '' && cached.signerKey === overlayIdentityKey) continue
1085
+ const verdict = await fetchAdmission(overlayUrl, txid)
1086
+ if (verdict?.kind !== 'admitted') continue
1087
+ try {
1088
+ await store.putAdmission({
1089
+ txid,
1090
+ outputsToAdmit: verdict.outputsToAdmit,
1091
+ signatureHex: verdict.signatureHex,
1092
+ signerKey: verdict.signerKey,
1093
+ source: 'fetched',
1094
+ obtainedAt: now().toISOString()
1095
+ })
1096
+ fetched++
1097
+ } catch (e) {
1098
+ devLog(`[mandala] could not cache the fetched admission of ${txid}:`, e)
1099
+ continue
1100
+ }
1101
+ const unadmitted = vouts.filter(v => !verdict.outputsToAdmit.includes(v))
1102
+ if (unadmitted.length > 0) {
1103
+ console.warn(`[mandala] ${txid} is admitted but not for held output(s) ${unadmitted.join(',')}; those coins will not cover offline`)
1104
+ }
1105
+ }
1106
+ return fetched
1107
+ }
1108
+
1109
+ /** DerSignature (string | number[] | Uint8Array), as the hex string OverlayVerdict wants. */
1110
+ const derSignatureHex = (sig: DerSignature): string =>
1111
+ typeof sig === 'string' ? sig : Utils.toHex(Array.from(sig))
1112
+
1113
+ /**
1114
+ * GET /admin/admission/:txid (wire contract v2 §3), mapped onto
1115
+ * `OverlayVerdict` and FIX-H-verified against this SESSION's overlay
1116
+ * identity key — `FetchAdmissionFn` carries no key of its own, and this
1117
+ * runtime speaks for exactly one Mandala deployment, so `overlayIdentityKey`
1118
+ * is the only key an answer could ever be checked against.
1119
+ *
1120
+ * An 'admitted' answer that does not verify (wrong/missing signer, bad
1121
+ * signature) is FIX H's "unverifiable ⇒ absent": it comes back `undefined`,
1122
+ * never as a decline — the caller's own local check (a cancel refusing to
1123
+ * fire, a recovery pass leaving the row alone) is what happens next either
1124
+ * way. Never throws: a network fault from the lib is itself `unavailable`,
1125
+ * and the verifier call is wrapped defensively on top of that.
1126
+ *
1127
+ * Amendment §9.1/§9.3: a persisted FINAL refusal is keyed by `(txid,
1128
+ * payloadHash)`, not by txid alone, so this passes `payloadHash(payload)`
1129
+ * whenever this device still holds the linkage bytes for `txid` — a refusal
1130
+ * recorded against a *different* off-chain payload for the same txid must
1131
+ * never be read as a verdict on the one this device holds. Every caller of
1132
+ * this closure (`recoverStaleAdmissions`, and `cancelParkedPayment` via FIX
1133
+ * J's `mandalaSettlementDeps`) gets this for free, since neither passes a
1134
+ * hash of its own. Absent a stored linkage row — this device never held the
1135
+ * payload, or already advanced past needing it — the lookup is simply
1136
+ * omitted and the fetch proceeds unqualified, exactly as before.
1137
+ *
1138
+ * **The URL argument is advisory and is deliberately ignored** (§9.10). Every
1139
+ * caller sources it from a settlement row, and a settlement row's
1140
+ * `overlayUrl` began life on a counterparty's frame — so honouring it would
1141
+ * let a payer name their own server, answer their own admission query with a
1142
+ * self-signed σ_I, and have the wallet's own recovery pass advance a row to
1143
+ * `admitted` on it. (The σ_I check would not catch it either: it is verified
1144
+ * against the configured key, but a hostile overlay can simply serve a
1145
+ * GENUINE admission for a different transaction — see the txid binding
1146
+ * below.) This runtime speaks for exactly one deployment, whose origin is
1147
+ * `overlayUrl`; anything else is data, and data does not choose endpoints.
1148
+ * A caller that names a different one is logged and answered from the
1149
+ * configured overlay anyway.
1150
+ *
1151
+ * The answer is likewise bound to the txid that was ASKED for. The wire
1152
+ * body carries its own `txid`, and `verifyFetchedAdmission` verifies σ_I over
1153
+ * *that* one — so an overlay (hostile, or merely buggy behind a cache or a
1154
+ * redirect) that answers with a real admission for some other transaction
1155
+ * would produce a perfectly-verifying entry that says nothing whatsoever
1156
+ * about the payment in hand. That is FIX H's "unverifiable ⇒ absent" again:
1157
+ * the mismatch comes back `undefined`, never a decline.
1158
+ */
1159
+ const fetchAdmission: FetchAdmissionFn = async (fetchOverlayUrl, txid) => {
1160
+ if (fetchOverlayUrl !== '' && fetchOverlayUrl !== overlayUrl) {
1161
+ devLog(
1162
+ `[mandala] fetchAdmission was asked to address ${fetchOverlayUrl} for ${txid}; ` +
1163
+ `asking this session's configured overlay instead`
1164
+ )
1165
+ }
1166
+ let hash: string | undefined
1167
+ try {
1168
+ const linkage = await store.getLinkage(txid)
1169
+ if (linkage) hash = payloadHash(linkage.payloadBytes)
1170
+ } catch (e) {
1171
+ devLog(`[mandala] fetchAdmission could not read the stored linkage payload of ${txid}:`, e)
1172
+ }
1173
+ let entry: FetchedAdmission | undefined
1174
+ try {
1175
+ entry = await libFetchAdmission(overlayUrl, txid, hash !== undefined ? { payloadHash: hash } : {})
1176
+ } catch (e) {
1177
+ devLog(`[mandala] fetchAdmission could not reach ${overlayUrl} for ${txid}:`, e)
1178
+ return { kind: 'unavailable', code: 'ERR_UNAVAILABLE', retryable: true }
1179
+ }
1180
+ if (entry === undefined) return undefined
1181
+ if (entry.kind === 'evicted') return { kind: 'evicted' }
1182
+ if (entry.kind === 'refused') {
1183
+ return { kind: 'refused', code: entry.code, ...(entry.spendTxid != null ? { spendTxid: entry.spendTxid } : {}) }
1184
+ }
1185
+ if (entry.kind === 'unavailable') return { kind: 'unavailable', code: entry.code, retryable: true }
1186
+ // The σ_I covers `entry.txid`, which is whatever the body claimed. An
1187
+ // admission for another transaction is somebody else's, however genuine.
1188
+ if (entry.txid.toLowerCase() !== txid.toLowerCase()) {
1189
+ devLog(`[mandala] fetchAdmission asked about ${txid} and was answered about ${entry.txid}; treating as absent`)
1190
+ return undefined
1191
+ }
1192
+ let verified = false
1193
+ try {
1194
+ verified = verifyFetchedAdmission(entry, overlayIdentityKey)
1195
+ } catch (e) {
1196
+ devLog(`[mandala] fetchAdmission could not verify the admission of ${txid}:`, e)
1197
+ }
1198
+ if (!verified) return undefined
1199
+ return {
1200
+ kind: 'admitted',
1201
+ outputsToAdmit: entry.outputsToAdmit,
1202
+ signatureHex: derSignatureHex(entry.signature),
1203
+ signerKey: entry.signerKey
1204
+ }
1205
+ }
1206
+
1207
+ /**
1208
+ * THE 2026-09-15 REPAIR PASS.
1209
+ *
1210
+ * A settlement row that says `admitted`/`broadcast` and a wallet that says
1211
+ * the same transaction `failed` cannot both be right, and on that day they
1212
+ * were not: the overlay admitted a transfer (and broadcasts on admission),
1213
+ * and 0.7 s later the lib's bulk sweep aborted the still-`noSend` action that
1214
+ * built it. `proven_tx_reqs` went `nosend → abortAction → invalid`,
1215
+ * `transactions.status` went `failed`, and — the part that costs money —
1216
+ * `updateTransactionStatus('failed')` restored the input coin to spendable
1217
+ * although it was spent on chain. The next send picked it up and the overlay
1218
+ * refused the child with `ERR_INPUT_SPENT`.
1219
+ *
1220
+ * Three changes make that unreachable going forward (the sweep opt-out in
1221
+ * `reconcileJournals`, the abort guard in `abortGuard.ts`, and the lib no
1222
+ * longer clearing a journal entry for a broadcast that did not happen). This
1223
+ * pass is for the wallets it already happened to, and for any future way the
1224
+ * two records can diverge: it re-establishes the wallet's own view of a
1225
+ * transaction the chain has.
1226
+ *
1227
+ * **It never trusts the settlement row on its own.** The row is this device's
1228
+ * bookkeeping; the question "is this transaction real" is answered outside
1229
+ * it, by `refetchBeef` (the configured WhatsOnChain path the drain already
1230
+ * uses) or by the issuer's overlay confirming it holds an admission. Only
1231
+ * then is a `failed` transaction put back to `unproven`, its inputs re-marked
1232
+ * spent, its own outputs made spendable again, and its request restored to a
1233
+ * status the monitor proves from.
1234
+ *
1235
+ * Best-effort and non-throwing, like every other pass on the drain tick.
1236
+ * Returns the number of transactions repaired.
1237
+ */
1238
+ const repairAdmittedAborted = async (): Promise<number> => {
1239
+ if (!available || !db) return 0
1240
+ let rows: TokenSettlementRow[]
1241
+ try {
1242
+ rows = await store.listSettlements({ state: ['admitted', 'broadcast'] })
1243
+ } catch (e) {
1244
+ devLog('[mandala] settlement repair could not list settlement rows:', e)
1245
+ return 0
1246
+ }
1247
+
1248
+ let repaired = 0
1249
+ for (const row of rows) {
1250
+ let damaged: { txStatuses: string[]; reqStatus?: string }
1251
+ try {
1252
+ damaged = await readWalletVerdict(row.txid)
1253
+ } catch (e) {
1254
+ devLog(`[mandala] settlement repair could not read the wallet's view of ${row.txid}:`, e)
1255
+ continue
1256
+ }
1257
+ // The wallet agrees with the row, or has no record at all. Nothing to do.
1258
+ if (!damaged.txStatuses.includes('failed') && damaged.reqStatus !== 'invalid') continue
1259
+
1260
+ if (!(await transactionIsReal(row))) {
1261
+ devLog(
1262
+ `[mandala] ${row.txid} reads '${row.state}' locally but the wallet failed it, and neither the chain ` +
1263
+ 'nor the overlay confirms it — left alone, because releasing or re-spending on a guess is the harm'
1264
+ )
1265
+ continue
1266
+ }
1267
+
1268
+ try {
1269
+ const result = await storage.repairSettledTokenTransaction(row.txid)
1270
+ if (!result) continue
1271
+ repaired++
1272
+ console.warn(
1273
+ `[mandala] repaired ${row.txid}: settlement '${row.state}' but transaction ` +
1274
+ `${result.wasTxStatuses.join('/')}` +
1275
+ `${result.wasReqStatus ? ` and request '${result.wasReqStatus}'` : ''}. ` +
1276
+ `${result.inputsMarkedSpent} input(s) re-marked spent, ` +
1277
+ `${result.outputsMadeSpendable} output(s) restored to spendable` +
1278
+ `${result.reqCreated ? ', request recreated' : ''}`
1279
+ )
1280
+ } catch (e) {
1281
+ devLog(`[mandala] settlement repair could not restore ${row.txid}:`, e)
1282
+ }
1283
+ }
1284
+ if (repaired > 0) emit()
1285
+ return repaired
1286
+ }
1287
+
1288
+ /** What this wallet's own tables say about a txid: every transaction status, and the request's. */
1289
+ const readWalletVerdict = async (txid: string): Promise<{ txStatuses: string[]; reqStatus?: string }> => {
1290
+ const txs = await storage.findTransactions({ partial: { txid }, noRawTx: true })
1291
+ const req = (await storage.findProvenTxReqs({ partial: { txid } }))[0]
1292
+ return { txStatuses: txs.map(t => t.status), reqStatus: req?.status }
1293
+ }
1294
+
1295
+ /**
1296
+ * Is this transaction genuinely out there? Two independent witnesses, either
1297
+ * of which is enough, and neither of which is the settlement row itself.
1298
+ *
1299
+ * The chain is asked first because it is the stronger answer, but it is also
1300
+ * the one that lags: `refetchBeef` wants a verifiable BEEF, which a
1301
+ * transaction broadcast seconds ago does not have. The overlay is the witness
1302
+ * that matters in exactly that window — it admitted these bytes and it
1303
+ * broadcasts on admission, so an admission it still holds IS the statement
1304
+ * that the transaction went out. Neither answering is "no", never "unknown
1305
+ * so assume yes": the repair makes coins unspendable and must not run on a
1306
+ * guess.
1307
+ */
1308
+ const transactionIsReal = async (row: TokenSettlementRow): Promise<boolean> => {
1309
+ try {
1310
+ const beef = await args.refetchBeef?.(row.txid)
1311
+ if (beef && beef.length > 0) return true
1312
+ } catch (e) {
1313
+ devLog(`[mandala] settlement repair could not fetch ${row.txid} from the chain:`, e)
1314
+ }
1315
+ try {
1316
+ // The CONFIGURED overlay, never `row.overlayUrl` — the row's copy is
1317
+ // re-derived from counterparty frame bytes (§9.10), and the verdict this
1318
+ // returns is σ_I-verified against the configured key either way.
1319
+ return (await fetchAdmission(overlayUrl, row.txid))?.kind === 'admitted'
1320
+ } catch (e) {
1321
+ devLog(`[mandala] settlement repair could not ask the overlay about ${row.txid}:`, e)
1322
+ return false
1323
+ }
1324
+ }
1325
+
1326
+ /**
1327
+ * Fail a token transaction the overlay has finally refused, so its inputs go
1328
+ * back to spendable and its outputs stop being offered. Best-effort; returns
1329
+ * whether anything was failed.
1330
+ */
1331
+ const failRefusedTransaction = async (txid: string): Promise<boolean> => {
1332
+ let failed = false
1333
+ const txs = await storage.findTransactions({ partial: { txid }, noRawTx: true })
1334
+ for (const tx of txs) {
1335
+ if (tx.status === 'failed') continue
1336
+ await storage.updateTransactionStatus('failed', tx.transactionId)
1337
+ failed = true
1338
+ }
1339
+ return failed
1340
+ }
1341
+
1342
+ const reviewTokenHoldings = async (): Promise<TokenHoldingsReview> => {
1343
+ const review: TokenHoldingsReview = { settled: 0, removed: 0, unattested: 0, unreachable: false }
1344
+ if (!available) return review
1345
+
1346
+ let rows: TokenSettlementRow[] = []
1347
+ try {
1348
+ rows = await store.listSettlements({ state: ['handed_over', 'held', 'submitting', 'admitted'] })
1349
+ } catch (e) {
1350
+ devLog('[mandala] token review could not list settlement rows:', e)
1351
+ }
1352
+ const reviewedTxids = new Set<string>()
1353
+ for (const row of rows) {
1354
+ reviewedTxids.add(row.txid)
1355
+ try {
1356
+ const after = await settleNow(row.txid)
1357
+ if (after === 'broadcast') {
1358
+ review.settled++
1359
+ continue
1360
+ }
1361
+ if (after === 'refused' || after === 'orphaned') {
1362
+ if (await failRefusedTransaction(row.txid)) review.removed++
1363
+ continue
1364
+ }
1365
+ const verdict = await fetchAdmission(overlayUrl, row.txid)
1366
+ if (verdict === undefined) {
1367
+ review.unattested++
1368
+ continue
1369
+ }
1370
+ if (verdict.kind === 'unavailable') {
1371
+ review.unreachable = true
1372
+ continue
1373
+ }
1374
+ if (verdict.kind === 'admitted') {
1375
+ await store.putAdmission({
1376
+ txid: row.txid,
1377
+ outputsToAdmit: verdict.outputsToAdmit,
1378
+ signatureHex: verdict.signatureHex,
1379
+ signerKey: verdict.signerKey,
1380
+ source: 'fetched',
1381
+ obtainedAt: now().toISOString()
1382
+ })
1383
+ await store.advanceSettlement(row.txid, ['handed_over', 'held', 'submitting'], 'admitted', {
1384
+ admissionOutputs: verdict.outputsToAdmit,
1385
+ admissionSignatureHex: verdict.signatureHex
1386
+ })
1387
+ continue
1388
+ }
1389
+ const to: TokenSettlementState = verdict.kind === 'evicted' ? 'orphaned' : 'refused'
1390
+ await store.advanceSettlement(row.txid, [...NON_TERMINAL_SETTLEMENT_STATES], to, {
1391
+ refusedCode: verdict.kind === 'refused' ? verdict.code : undefined,
1392
+ poisonedByTxid: verdict.kind === 'evicted' ? row.txid : undefined
1393
+ })
1394
+ await failRefusedTransaction(row.txid)
1395
+ review.removed++
1396
+ } catch (e) {
1397
+ devLog(`[mandala] token review could not settle ${row.txid}:`, e)
1398
+ }
1399
+ }
1400
+
1401
+ let outputs: ListedTokenOutput[] = []
1402
+ try {
1403
+ outputs = await listTokenOutputs()
1404
+ } catch (e) {
1405
+ devLog('[mandala] token review could not list token holdings:', e)
1406
+ }
1407
+ const byTxid = new Map<string, number[]>()
1408
+ for (const o of outputs) {
1409
+ if (!o.spendable || reviewedTxids.has(o.txid)) continue
1410
+ byTxid.set(o.txid, [...(byTxid.get(o.txid) ?? []), o.vout])
1411
+ }
1412
+ for (const [txid, vouts] of byTxid) {
1413
+ try {
1414
+ const cached = await store.getAdmission(txid)
1415
+ if (
1416
+ cached &&
1417
+ cached.signatureHex !== '' &&
1418
+ cached.signerKey === overlayIdentityKey &&
1419
+ vouts.every(v => cached.outputsToAdmit.includes(v))
1420
+ ) {
1421
+ continue
1422
+ }
1423
+ const verdict = await fetchAdmission(overlayUrl, txid)
1424
+ if (verdict === undefined) {
1425
+ review.unattested++
1426
+ continue
1427
+ }
1428
+ if (verdict.kind === 'unavailable') {
1429
+ review.unreachable = true
1430
+ continue
1431
+ }
1432
+ if (verdict.kind !== 'admitted') {
1433
+ if (await failRefusedTransaction(txid)) review.removed++
1434
+ continue
1435
+ }
1436
+ await store.putAdmission({
1437
+ txid,
1438
+ outputsToAdmit: verdict.outputsToAdmit,
1439
+ signatureHex: verdict.signatureHex,
1440
+ signerKey: verdict.signerKey,
1441
+ source: 'fetched',
1442
+ obtainedAt: now().toISOString()
1443
+ })
1444
+ for (const vout of vouts) {
1445
+ if (verdict.outputsToAdmit.includes(vout)) continue
1446
+ const found = await storage.findOutputs({ partial: { txid, vout } })
1447
+ for (const output of found) {
1448
+ await storage.updateOutput(output.outputId, { spendable: false })
1449
+ review.removed++
1450
+ }
1451
+ }
1452
+ } catch (e) {
1453
+ devLog(`[mandala] token review could not check the coin(s) of ${txid}:`, e)
1454
+ }
1455
+ }
1456
+ if (review.removed > 0 || review.settled > 0) emit()
1457
+ return review
1458
+ }
1459
+
1460
+ const HANDED_OVER_RECOVERY_AFTER_MS = 5 * 60 * 1000 // one drain interval (TaskSendOffline's backoff ceiling)
1461
+
1462
+ /**
1463
+ * FIX C recovery: a `handed_over`/`held` row can be stuck with neither
1464
+ * ancestor bytes nor a cached σ_I — a crash between `/submit` and the
1465
+ * admission-cache write, or a counterparty that settled the hop on this
1466
+ * device's behalf without ever telling it. `postTokenStep`'s own idempotent
1467
+ * re-submit already covers a device that still holds the bytes; this covers
1468
+ * the device that has NEITHER, by simply asking the overlay whether it
1469
+ * already knows better. Read-only, best-effort, and at most one overlay ask
1470
+ * per qualifying row per call — never throws.
1471
+ */
1472
+ const recoverStaleAdmissions = async (): Promise<number> => {
1473
+ let rows: TokenSettlementRow[]
1474
+ try {
1475
+ rows = await store.listSettlements({ state: ['handed_over', 'held'] })
1476
+ } catch (e) {
1477
+ devLog('[mandala] admission recovery could not list settlement rows:', e)
1478
+ return 0
1479
+ }
1480
+ const cutoff = now().getTime() - HANDED_OVER_RECOVERY_AFTER_MS
1481
+ let advanced = 0
1482
+ for (const row of rows) {
1483
+ if (Date.parse(row.createdAt) > cutoff) continue
1484
+ try {
1485
+ if ((await store.getAdmission(row.txid)) !== undefined) continue // the ordinary drain owns this one
1486
+ } catch (e) {
1487
+ devLog(`[mandala] admission recovery could not read the admission cache for ${row.txid}:`, e)
1488
+ continue
1489
+ }
1490
+ // The configured origin, never `row.overlayUrl`: the row's copy is
1491
+ // re-derived from frames a counterparty wrote (`reconcileSettlements`),
1492
+ // so it names an endpoint this wallet has no reason to trust. Passing it
1493
+ // would be ignored by `fetchAdmission` anyway — passing the real one
1494
+ // keeps that from looking like a caller bug in the log.
1495
+ const verdict = await fetchAdmission(overlayUrl, row.txid)
1496
+ if (verdict?.kind !== 'admitted') continue
1497
+ try {
1498
+ await store.putAdmission({
1499
+ txid: row.txid,
1500
+ outputsToAdmit: verdict.outputsToAdmit,
1501
+ signatureHex: verdict.signatureHex,
1502
+ signerKey: verdict.signerKey,
1503
+ source: 'fetched',
1504
+ obtainedAt: now().toISOString()
1505
+ })
1506
+ const ok = await store.advanceSettlement(row.txid, ['handed_over', 'held', 'submitting'], 'admitted', {
1507
+ admissionOutputs: verdict.outputsToAdmit,
1508
+ admissionSignatureHex: verdict.signatureHex
1509
+ })
1510
+ if (ok) advanced++
1511
+ } catch (e) {
1512
+ devLog(`[mandala] admission recovery could not journal ${row.txid}:`, e)
1513
+ }
1514
+ }
1515
+ return advanced
1516
+ }
1517
+
1518
+ const BLINDING_RESERVATION_HORIZON_MS = 24 * 60 * 60 * 1000
1519
+
1520
+ /** Sweeps abandoned `lockToPayee` blinding reservations older than 24h. Never throws. */
1521
+ const pruneBlindingReservations = async (): Promise<number> => {
1522
+ try {
1523
+ return await blindingPruneReserved(BLINDING_RESERVATION_HORIZON_MS)
1524
+ } catch (e) {
1525
+ devLog('[mandala] blinding reservation prune failed:', e)
1526
+ return 0
1527
+ }
1528
+ }
1529
+
1530
+ // Built lazily and once: the lib's facilitator is the one that READS the
1531
+ // structured error body (`@bsv/sdk`'s discards it), which is exactly the
1532
+ // verdict FIX D turns on.
1533
+ let facilitatorInstance: ReturnType<typeof createOverlayFacilitator> | undefined
1534
+ const facilitator = (): ReturnType<typeof createOverlayFacilitator> => {
1535
+ facilitatorInstance ??= createOverlayFacilitator(args.fetchImpl)
1536
+ return facilitatorInstance
1537
+ }
1538
+
1539
+ /**
1540
+ * FIX G's supply side: every durable token frame this device holds.
1541
+ *
1542
+ * Read fresh on every pass and never filtered by the pending queue's own
1543
+ * retry ceiling — a token payment's state of record is `token_settlements`,
1544
+ * not `localpay_pending` (FIX I).
1545
+ */
1546
+ const frames = async (): Promise<TokenFrameSource[]> => {
1547
+ const sources: TokenFrameSource[] = []
1548
+ try {
1549
+ sources.push(...tokenFrameSourcesFromPending(await getPending(storage)))
1550
+ } catch (e) {
1551
+ devLog('[mandala] could not read the pending queue for drain sources:', e)
1552
+ }
1553
+ if (db && args.decodeSealedFrame) {
1554
+ try {
1555
+ const rows = await findOfflineActions(db, { status: ['queued', 'posting', 'parked'] })
1556
+ sources.push(...tokenFrameSourcesFromOfflineActions(rows, args.decodeSealedFrame))
1557
+ } catch (e) {
1558
+ devLog('[mandala] could not read the payer queue for drain sources:', e)
1559
+ }
1560
+ }
1561
+ return sources
1562
+ }
1563
+
1564
+ // Assembled as a value, then narrowed: `verifyAdmission` is the drain's FIX H
1565
+ // trust anchor (`TokenStepDeps`), and passing it through an object literal
1566
+ // would make this file fail to compile against a drain that has not grown the
1567
+ // field yet — for a dependency the drain treats as optional evidence.
1568
+ const tokenDepsValue = { store, cover, submit, frames, overlayIdentityKey, verifyAdmission, journalRemove }
1569
+ const tokenDeps: OfflineTokenDeps = tokenDepsValue
1570
+
1571
+ const isOnline = args.isOnline ?? (async () => true)
1572
+
1573
+ /**
1574
+ * Every drainable row the PAYER's handle rail owns, stepped once.
1575
+ *
1576
+ * `sendToHandle` writes a `token_settlements` row and no queue row, and the
1577
+ * release drain only steps queue rows — so a hand-over whose immediate
1578
+ * `settleNow` did not settle (offline, a cover hole, a 503) had NOTHING
1579
+ * retrying it: `recoverStaleAdmissions` can fetch a σ_I the overlay already
1580
+ * holds but never broadcasts, and the lib's own reconcile cannot broadcast
1581
+ * through this wallet's hold at all (2026-09-15 incident). This is the
1582
+ * missing retry: on every tick, each `sent` row still in a drain-owned state
1583
+ * takes the same `settleNow` step it would have taken at send time. Rows the
1584
+ * user owns (`built`/`parked`) are never touched (FIX F); received rows have
1585
+ * their own queue entries. Never throws; returns how many rows moved.
1586
+ */
1587
+ const PAYER_DRAIN_STATES: TokenSettlementState[] = ['handed_over', 'submitting', 'admitted']
1588
+ const settlePendingSends = async (): Promise<number> => {
1589
+ if (!available) return 0
1590
+ let rows: TokenSettlementRow[]
1591
+ try {
1592
+ rows = await store.listSettlements({ state: PAYER_DRAIN_STATES })
1593
+ } catch (e) {
1594
+ devLog('[mandala] could not list the payer rows to settle:', e)
1595
+ return 0
1596
+ }
1597
+ let advanced = 0
1598
+ for (const row of rows) {
1599
+ if (row.role !== 'sent') continue
1600
+ try {
1601
+ const after = await settleNow(row.txid)
1602
+ if (after !== row.state) advanced++
1603
+ } catch (e) {
1604
+ devLog(`[mandala] settling ${row.txid} on the tick failed; next tick retries:`, e)
1605
+ }
1606
+ }
1607
+ return advanced
1608
+ }
1609
+
1610
+ /**
1611
+ * The step's broadcast: the release engine's own owned post, by default.
1612
+ *
1613
+ * `postTokenStep` reaches this only once every ancestor in COVER's
1614
+ * `mustSubmit` is admitted, so nothing about the §4.3 gate changes — this is
1615
+ * simply the same `postOwned` the queue drain would have used a tick later,
1616
+ * called for one txid instead of a planned graph.
1617
+ */
1618
+ const broadcastTip =
1619
+ args.broadcast ?? (async (txid: string): Promise<PostOutcome> => await postOwnedByTxid(storage, txid))
1620
+
1621
+ /**
1622
+ * One `settleNow` per txid at a time.
1623
+ *
1624
+ * Not a lock on the money — `advanceSettlement` is a CAS and `/submit` is
1625
+ * idempotent, so correctness never depended on this — but a send and a
1626
+ * re-tap, or a nearby hold and a drain tick that lands on the same
1627
+ * millisecond, would otherwise each open their own `/submit` for identical
1628
+ * bytes. Coalescing costs nothing and makes the second caller wait for the
1629
+ * first caller's answer, which is also the more useful answer.
1630
+ */
1631
+ const settlesInFlight = new Map<string, Promise<TokenSettleState>>()
1632
+
1633
+ /**
1634
+ * §4.3's drain step for exactly one row, run now.
1635
+ *
1636
+ * Everything this does, the ordinary drain does too. What it never does is
1637
+ * decide anything the drain would not: a row the USER owns is left alone
1638
+ * (FIX F), a terminal row is reported as it stands, and any failure — a
1639
+ * missing row, an unreachable overlay, a throw from deep inside the walk —
1640
+ * leaves the row exactly where it was for the next tick. It cannot reject.
1641
+ */
1642
+ const runSettleStep = async (txid: string): Promise<TokenSettleState> => {
1643
+ if (!available) return 'unavailable'
1644
+ let row: TokenSettlementRow | undefined
1645
+ try {
1646
+ row = await store.getSettlement(txid)
1647
+ } catch (e) {
1648
+ devLog(`[mandala] settleNow could not read the settlement row for ${txid}:`, e)
1649
+ return 'unavailable'
1650
+ }
1651
+ if (!row) return 'unavailable'
1652
+ // Nothing left to do, and nothing that may be undone (spec §5).
1653
+ if (TERMINAL_SETTLEMENT_STATES.includes(row.state)) return row.state
1654
+ // FIX F: `built`/`parked` are the payer's own states. A payment deliberately
1655
+ // withheld is not settled by a convenience path.
1656
+ if (row.state === 'built' || row.state === 'parked') return row.state
1657
+
1658
+ try {
1659
+ await postTokenStep(
1660
+ { store, cover, submit, broadcast: broadcastTip, overlayIdentityKey, verifyAdmission, journalRemove, now },
1661
+ row,
1662
+ { txid, owned: true }
1663
+ )
1664
+ } catch (e) {
1665
+ // `postTokenStep` is written not to throw, but it is reached here from a
1666
+ // money path that has already succeeded: a surprise must cost a drain
1667
+ // interval, never the send.
1668
+ devLog(`[mandala] settleNow could not complete the settlement step for ${txid}:`, e)
1669
+ }
1670
+
1671
+ let after: TokenSettlementRow | undefined
1672
+ try {
1673
+ after = await store.getSettlement(txid)
1674
+ } catch (e) {
1675
+ devLog(`[mandala] settleNow could not re-read the settlement row for ${txid}:`, e)
1676
+ return 'unavailable'
1677
+ }
1678
+ if (after && after.state !== row.state) emit()
1679
+ else devLog(`[mandala] settlement step for ${txid} left the row at '${row.state}'; the drain retries next tick`)
1680
+ return after?.state ?? 'unavailable'
1681
+ }
1682
+
1683
+ const settleNow = async (txid: string): Promise<TokenSettleState> => {
1684
+ const existing = settlesInFlight.get(txid)
1685
+ if (existing) return await existing
1686
+ const run = runSettleStep(txid).finally(() => {
1687
+ settlesInFlight.delete(txid)
1688
+ })
1689
+ settlesInFlight.set(txid, run)
1690
+ return await run
1691
+ }
1692
+
1693
+ /**
1694
+ * How long a send waits for its own submit before handing it back to the drain.
1695
+ *
1696
+ * The hand-over is already done when this starts, so the only thing at stake
1697
+ * is whether the receipt gets to say "settled" — and a receipt that arrives
1698
+ * eight seconds late is worse than one that says "settling" and is corrected
1699
+ * by the activity list a minute later. The submit itself is NOT cancelled on
1700
+ * timeout: it is still in flight, still idempotent, and its verdict still
1701
+ * lands in the row.
1702
+ */
1703
+ const SETTLE_ON_SEND_TIMEOUT_MS = 8_000
1704
+
1705
+ const settleWithinSendTimeout = async (txid: string): Promise<TokenSettleState | 'timeout'> => {
1706
+ let timer: ReturnType<typeof setTimeout> | undefined
1707
+ try {
1708
+ return await Promise.race([
1709
+ settleNow(txid),
1710
+ new Promise<'timeout'>(resolve => {
1711
+ timer = setTimeout(() => resolve('timeout'), SETTLE_ON_SEND_TIMEOUT_MS)
1712
+ })
1713
+ ])
1714
+ } finally {
1715
+ if (timer !== undefined) clearTimeout(timer)
1716
+ }
1717
+ }
1718
+
1719
+ const lockToPayee: LockToPayee = async ({ assetId, amount, recipientKey, keyID }) => {
1720
+ const mine = await identityKey()
1721
+ const blinded = await prepareBlindedPayment(bound, {
1722
+ identityKey: mine,
1723
+ recipientKey,
1724
+ keyID
1725
+ })
1726
+ // Nearby blinding (offline-settlement design): r is minted here, before the
1727
+ // nearby build even has a txid to key it under. Reserve it under `keyID`
1728
+ // now — the build path promotes it via `blindingCommit` once the tx is
1729
+ // signed, and an abandoned reservation (the payee never accepted, the tab
1730
+ // closed) is later swept by `pruneBlindingReservations`. Best-effort: the
1731
+ // lib's own write never throws, and a failed reserve costs only the
1732
+ // sender's later ability to re-derive r from the journal — the payment
1733
+ // itself is unaffected.
1734
+ await blindingReserve(keyID, {
1735
+ r: blinded.r,
1736
+ senderBlinded: blinded.senderBlinded,
1737
+ recipient: recipientKey,
1738
+ keyID,
1739
+ at: now().getTime()
1740
+ })
1741
+ return {
1742
+ lockingScript: new MandalaToken().lock(assetId, amount, blinded.pubKeyHash).toHex(),
1743
+ senderIdentityKey: blinded.senderBlinded,
1744
+ linkage: blinded.linkage,
1745
+ customInstructions: recipientCustomInstructions({
1746
+ keyID,
1747
+ recipientKey,
1748
+ senderBlinded: blinded.senderBlinded
1749
+ })
1750
+ }
1751
+ }
1752
+
1753
+ /**
1754
+ * One frame's evidence, cached under this session's own trust anchor.
1755
+ *
1756
+ * Every caller here hands `populateEvidenceFromFrame` the SAME anchor —
1757
+ * `overlayIdentityKey` + `verifyAdmission`, both closed over the
1758
+ * configuration — so a σ_I that arrived on a frame is cached only if this
1759
+ * wallet's own overlay signed it (FIX H). Errors are logged, never thrown:
1760
+ * each of these hooks runs beside money that is already committed.
1761
+ */
1762
+ const cacheFrameEvidence = async (
1763
+ frame: EvidenceFrame,
1764
+ label: string,
1765
+ opts: { admissionSource?: TokenAdmissionRow['source']; linkageSource?: 'minted' | 'forwarded' } = {}
1766
+ ): Promise<void> => {
1767
+ const evidence = await populateEvidenceFromFrame(store, frame, { now, ...evidenceAnchor, ...opts })
1768
+ if (evidence.errors.length > 0) devLog(`[mandala] evidence from ${label} reported:`, evidence.errors)
1769
+ if (evidence.admissionsDropped > 0) {
1770
+ // Not an error: an unverifiable σ_I is ABSENT, and the ancestor it named
1771
+ // is simply walked and submitted like any other. Worth saying out loud,
1772
+ // because it is also what a forged bundle looks like.
1773
+ devLog(`[mandala] ${label} carried ${evidence.admissionsDropped} admission(s) this overlay did not sign`)
1774
+ }
1775
+ }
1776
+
1777
+ /**
1778
+ * RECEIVER, BEFORE `internalizeAction`: this device is now the one that has
1779
+ * to settle this hop (spec rule 3), and it says so durably first.
1780
+ *
1781
+ * Ordering is the whole contract. `internalizeAction` forces a broadcast
1782
+ * attempt of its own, and the only thing standing between that and an
1783
+ * unadmitted token going out is `attemptToPostReqsToNetwork`'s lookup of
1784
+ * exactly this row — a row written after the credit fails open on the first
1785
+ * internalize, which is the one that matters. So this throws rather than
1786
+ * swallowing: the frame is already durable in `localpay_pending`, and a
1787
+ * failure here means "do not credit yet", not "credit anyway".
1788
+ *
1789
+ * The row carries the CONFIGURED overlay, never `frame.token.overlayUrl` /
1790
+ * `overlayIdentityKey`: those are the payer's claim about which deployment
1791
+ * this asset belongs to, and a row is what later tells recovery where to ask
1792
+ * and whose signature to believe (§9.10).
1793
+ */
1794
+ const onTokenHeld: TokenHeldHook = async (frame, txid) => {
1795
+ const token = frame.token
1796
+ if (!token) return
1797
+ await cacheFrameEvidence(frame, 'a held frame')
1798
+ const existing = await store.getSettlement(txid)
1799
+ await store.upsertSettlement({
1800
+ txid,
1801
+ role: 'received',
1802
+ assetId: token.assetId,
1803
+ state: existing?.state ?? 'held',
1804
+ counterpartyKey: frame.senderIdentityKey,
1805
+ // The figure the activity row prints, off the payee output's own script.
1806
+ // Without it a nearby row rendered as "+0 sats" (2026-09-16).
1807
+ amountBaseUnits: frameTokenAmount(frame),
1808
+ overlayUrl,
1809
+ overlayIdentityKey,
1810
+ createdAt: existing?.createdAt
1811
+ })
1812
+ emit()
1813
+ }
1814
+
1815
+ /**
1816
+ * PAYER, at park/hold: the frame is still plaintext here, and this is the
1817
+ * only moment it is.
1818
+ *
1819
+ * `offline_actions.framePayload` is sealed with the nearby session's
1820
+ * pre-shared key, which lives in memory and dies with the process — so a
1821
+ * payer that restarts can no longer open its own frame, and a settlement row
1822
+ * derived only from it would never exist at all (that is what
1823
+ * `decodeSealedFrame` can only ever partially fix). Writing the row and the
1824
+ * evidence here makes the payer's half of the chain durable independently of
1825
+ * the PSK.
1826
+ *
1827
+ * `state` is the payer's own fork: `'parked'` (the code screen was left
1828
+ * without a hand-over) or `'handed_over'` (the payee took the frame). Both
1829
+ * are the USER's states, which the drain may never claim (FIX F) — so a
1830
+ * `'parked'` row is created but never dragged forward here, while a
1831
+ * hand-over is allowed to advance a row that was parked a moment ago.
1832
+ * `counterpartyKey` is deliberately left unset: on the payer's own frame
1833
+ * `senderIdentityKey` is the PAYER (blinded), not the payee.
1834
+ */
1835
+ const onTokenHandedOver: TokenHandedOverHook = async (frame, txid, state, reference) => {
1836
+ const token = frame.token
1837
+ if (!token) return
1838
+ // `minted`: the payload that matters on the payer's own frame is the tip's,
1839
+ // and the payer is the one who minted it. (Provenance only — nothing
1840
+ // branches on it, and `putLinkage` never overwrites a row already here.)
1841
+ await cacheFrameEvidence(frame, `a ${state} frame`, { linkageSource: 'minted' })
1842
+ const existing = await store.getSettlement(txid)
1843
+ await store.upsertSettlement({
1844
+ txid,
1845
+ role: 'sent',
1846
+ assetId: token.assetId,
1847
+ state: existing?.state ?? state,
1848
+ // Output 0 of the payer's own frame is the PAYEE's, never the change —
1849
+ // `frameTokenAmount` reads `outputIndex`, and the nearby build does not
1850
+ // randomise outputs. This is what the activity row prints as "Sent <ticker>".
1851
+ amountBaseUnits: frameTokenAmount(frame),
1852
+ overlayUrl,
1853
+ overlayIdentityKey,
1854
+ // The nearby rail's half of the abort guard: the action that built this
1855
+ // tip is `noSend` and stays that way until the drain broadcasts it, so
1856
+ // the reference is recorded the same moment the row is. Absent for a
1857
+ // caller that does not have one — see `TokenHandedOverHook`.
1858
+ ...(reference ? { reference } : {}),
1859
+ createdAt: existing?.createdAt
1860
+ })
1861
+ // `upsertSettlement` never rewrites `state` on conflict (a re-derivation
1862
+ // must not drag an `admitted` row back), so the one legitimate advance the
1863
+ // payer makes by hand is made explicitly — and only out of the two states
1864
+ // the payer owns.
1865
+ if (state === 'handed_over') await store.advanceSettlement(txid, ['built', 'parked'], 'handed_over')
1866
+ emit()
1867
+ }
1868
+
1869
+ /**
1870
+ * The settlement row and evidence a credited token frame makes this device
1871
+ * responsible for.
1872
+ *
1873
+ * Kept beside `onTokenHeld` rather than replaced by it: the held hook runs
1874
+ * before the credit, this one after, and a frame that was credited by a
1875
+ * build that had no held hook (or whose held write lost a race with a crash)
1876
+ * still has to end up with a row. Both are idempotent re-derivations of the
1877
+ * same facts, which is exactly FIX G's point.
1878
+ */
1879
+ const onTokenCredited: TokenCreditedHook = async (frame: PaymentFrame, txid: string) => {
1880
+ if (!frame.token) return
1881
+ await onTokenHeld(frame as EvidenceFrame, txid)
1882
+ }
1883
+
1884
+ /**
1885
+ * How a credited hand-over is settled: by the DRAIN, on its next tick — not
1886
+ * inline, and never from inside the receive loop.
1887
+ *
1888
+ * The lib's own `defaultSettle` POSTs each `mustSubmit` txid to `/submit`
1889
+ * right there in `acceptOne`. That is right for the online web console and
1890
+ * wrong for a phone: a wallet that credits a payment while offline (or on a
1891
+ * flaky connection) would throw out of the receive loop, leave the message
1892
+ * un-acknowledged, and re-run the whole credit next pass — and, worse, would
1893
+ * be doing overlay I/O on the path that has just internalized money.
1894
+ *
1895
+ * So this writes DURABLE OBLIGATIONS instead: one `held` settlement row per
1896
+ * transaction the COVER walk says still needs submitting (the tip included),
1897
+ * plus the linkage payload the payer forwarded for it, through exactly the
1898
+ * same `onTokenHeld` the nearby rail uses. `postTokenStep` then owns the
1899
+ * rest — it re-runs COVER over these very tables and submits parents-first,
1900
+ * tip last, on every online tick, idempotently (§0.1 rules 3/6).
1901
+ *
1902
+ * A throw here means "do not acknowledge the message yet", which is correct:
1903
+ * the credit is idempotent (`internalizeAction` already tolerates a repeat)
1904
+ * and a row that was never written is an obligation nothing would own.
1905
+ */
1906
+ const settleThroughDrain: SettleFn = async ({ txid, mustSubmit, bytesFor }) => {
1907
+ // The tip is normally the last entry of `mustSubmit`; appending it when it
1908
+ // is absent costs nothing and makes the tip's own row unconditional.
1909
+ const ids = mustSubmit.includes(txid) ? [...mustSubmit] : [...mustSubmit, txid]
1910
+ // One asset for the whole chain — read from the tip's own bytes, never
1911
+ // from the message body, which is the payer's claim (§9.10).
1912
+ const tipBytes = bytesFor(txid)
1913
+ let assetId: string | undefined
1914
+ if (tipBytes) {
1915
+ try {
1916
+ assetId = assetIdOfTx(Transaction.fromAtomicBEEF(tipBytes.beef))
1917
+ } catch (e) {
1918
+ devLog(`[mandala] could not read the asset of hand-over tip ${txid}:`, e)
1919
+ }
1920
+ }
1921
+ if (assetId === undefined) {
1922
+ // Nothing coherent to own the obligation under. Left to the next inbox
1923
+ // pass rather than silently credited with no row.
1924
+ throw new Error(`could not write the settlement row before crediting ${txid}: unknown asset`)
1925
+ }
1926
+ for (const id of ids) {
1927
+ const bytes = bytesFor(id)
1928
+ if (!bytes) {
1929
+ // COVER only ever names transactions the bundle carries, so this is a
1930
+ // lib-side contradiction rather than a normal state.
1931
+ devLog(`[mandala] the hand-over bundle for ${txid} carries no bytes for ${id}`)
1932
+ continue
1933
+ }
1934
+ await onTokenHeld(
1935
+ {
1936
+ kind: 'token',
1937
+ token: {
1938
+ assetId,
1939
+ // The CONFIGURED deployment, never one named on the wire (§9.10).
1940
+ overlayUrl,
1941
+ overlayIdentityKey,
1942
+ linkage:
1943
+ bytes.offChainValues.length > 0
1944
+ ? [{ txid: id, payload: Uint8Array.from(bytes.offChainValues) }]
1945
+ : []
1946
+ },
1947
+ transaction: Uint8Array.from(bytes.beef)
1948
+ },
1949
+ id
1950
+ )
1951
+ }
1952
+ }
1953
+
1954
+ /** One credited MessageBox transfer, turned into a settlement row and cached evidence. */
1955
+ const journalReceived = async (transfer: ReceivedTransfer): Promise<void> => {
1956
+ const bytes = Uint8Array.from(transfer.transaction as unknown as number[])
1957
+ let txid: string | undefined
1958
+ try {
1959
+ txid = Transaction.fromAtomicBEEF(Array.from(bytes)).id('hex')
1960
+ } catch (e) {
1961
+ devLog(`[mandala] a credited transfer's transaction would not parse:`, e)
1962
+ return
1963
+ }
1964
+
1965
+ const edges: TokenAdmissionEdge[] = deriveTokenEdges(bytes, transfer.assetId)
1966
+ if (edges.length > 0) await store.putEdges(edges)
1967
+
1968
+ const admission = transfer.admission
1969
+ const verified = transfer.admissionVerified && admission != null && admission.txid === txid
1970
+ if (verified && admission) {
1971
+ const row: TokenAdmissionRow = {
1972
+ txid,
1973
+ outputsToAdmit: [...admission.outputsToAdmit],
1974
+ signatureHex: admission.signature,
1975
+ signerKey: admission.signerKey,
1976
+ source: 'bundle',
1977
+ obtainedAt: now().toISOString()
1978
+ }
1979
+ await store.putAdmission(row)
1980
+ }
1981
+
1982
+ const existing = await store.getSettlement(txid)
1983
+ // FIX H: a σ_I that verified against THIS overlay is the only thing that
1984
+ // may open a row already admitted. Anything else is `held` — never a
1985
+ // decline, just a row the drain will settle itself.
1986
+ const state: TokenSettlementState = existing?.state ?? (verified ? 'admitted' : 'held')
1987
+ await store.upsertSettlement({
1988
+ txid,
1989
+ role: 'received',
1990
+ assetId: transfer.assetId,
1991
+ state,
1992
+ counterpartyKey: transfer.sender,
1993
+ amountBaseUnits: Number(transfer.amount) || undefined,
1994
+ overlayUrl,
1995
+ overlayIdentityKey,
1996
+ ...(verified && admission
1997
+ ? { admissionOutputs: [...admission.outputsToAdmit], admissionSignatureHex: admission.signature }
1998
+ : {}),
1999
+ createdAt: existing?.createdAt
2000
+ })
2001
+ }
2002
+
2003
+ /**
2004
+ * The payer-side build's deps, carrying the same FIX H anchor.
2005
+ *
2006
+ * `assembleBundle` forwards this device's cached admissions onward as its own
2007
+ * claim about the chain, and `buildTokenPaymentFrame` reads the asset's
2008
+ * `overlayIdentityKey` off the SESSION — i.e. off the payee's request. Handing
2009
+ * the build the configured key and verifier here is what lets it anchor on
2010
+ * configuration instead (§9.10). Narrowed from a value for the same reason
2011
+ * `tokenDeps` is.
2012
+ */
2013
+ const tokenBuildDepsValue = {
2014
+ store,
2015
+ lockToPayee,
2016
+ commitBlinding: blindingCommit,
2017
+ overlayIdentityKey,
2018
+ verifyAdmission
2019
+ }
2020
+ const tokenBuildDeps: TokenBuildDeps = tokenBuildDepsValue
2021
+
2022
+ /**
2023
+ * FIX C's handle-rail sibling: drive the LIB's own durable journals once.
2024
+ *
2025
+ * `reconcileWallet` is what turns a half-finished `transferTokens` into
2026
+ * either a settled payment or released inputs — an overlay-accepted tx whose
2027
+ * broadcast never went out, a liftable refusal whose noSend action is still
2028
+ * holding its coins, a pending abort, and the stuck-`nosend` sweep behind
2029
+ * them. `reconcileNotifications` re-sends the MessageBox message a committed
2030
+ * transfer owes its recipient. Both are journaled by the lib and are
2031
+ * otherwise driven by NOBODY in this wallet: the settlement drain only knows
2032
+ * about `token_settlements` rows, and the handle rail writes none of the
2033
+ * entries these read.
2034
+ *
2035
+ * Best-effort in every direction — an unreachable overlay, a MessageBox
2036
+ * that will not open, a journal read that throws — because this rides a
2037
+ * monitor tick beside the release drain and must never be the reason the
2038
+ * rest of that pass does not happen. The entries stay journaled; the next
2039
+ * tick tries again.
2040
+ *
2041
+ * **`sweep: false`, always.** `reconcileWallet`'s last step is a BULK SWEEP:
2042
+ * it lists every stuck `noSend` mandala action the wallet holds and aborts
2043
+ * the ones no journal entry claims. That is right for a host whose wallet
2044
+ * broadcasts as soon as the overlay accepts — and exactly wrong for this one,
2045
+ * where `attemptToPostReqsToNetwork` HOLDS every token request for the
2046
+ * settlement drain, so a live, healthy, already-admitted payment looks
2047
+ * abandoned. On 2026-09-15 that sweep aborted a transfer the overlay had
2048
+ * broadcast 0.7 s earlier and released its input coin as spendable (see
2049
+ * `abortGuard.ts`). Settlement in this wallet is owned by `token_settlements`
2050
+ * and the drain over it; the lib's sweep must never run here, on any tick,
2051
+ * for any reason.
2052
+ */
2053
+ const reconcileJournals = async (): Promise<void> => {
2054
+ if (!available) return
2055
+ try {
2056
+ // `broadcast: false`: the lib may re-submit its journaled bytes (the
2057
+ // overlay is idempotent) but must NOT broadcast through
2058
+ // `createAction({ sendWith })` — this wallet's storage holds every token
2059
+ // request for the settlement drain, so that broadcast can never succeed
2060
+ // here and only burned the lib's retry cap into a 'stranded' entry
2061
+ // (2026-09-15). The drain's `postTokenStep` clears the entry when the
2062
+ // transaction really goes out (`journalRemove`).
2063
+ const r = await reconcileWalletWithOptions(bound, { sweep: false, broadcast: false })
2064
+ if (!r.skipped && (r.rebroadcast.length > 0 || r.aborted.length > 0 || r.resubmitted.length > 0 || r.swept > 0)) {
2065
+ devLog('[mandala] reconcileWallet recovered:', r)
2066
+ emit()
2067
+ }
2068
+ if (r.stranded.length > 0) devLog('[mandala] reconcileWallet parked stranded broadcasts:', r.stranded)
2069
+ } catch (e) {
2070
+ devLog('[mandala] reconcileWallet failed; its journal entries stay for the next pass:', e)
2071
+ }
2072
+ try {
2073
+ const delivered = await reconcileNotifications(await messageBox())
2074
+ if (delivered.length > 0) devLog('[mandala] delivered pending recipient notifications:', delivered)
2075
+ } catch (e) {
2076
+ devLog('[mandala] could not retry pending recipient notifications:', e)
2077
+ }
2078
+ }
2079
+
2080
+ const runtime: MandalaRuntime = {
2081
+ available,
2082
+ // The configuration itself, not the endpoints any frame claims — see
2083
+ // `MandalaRuntime.endpoints`. Empty strings on a chain with no deployment.
2084
+ endpoints: { overlayUrl, overlayIdentityKey, messageBoxUrl },
2085
+ store,
2086
+ tokenDeps,
2087
+ tokenBuildDeps,
2088
+ coverVerifier,
2089
+ verifyAdmissionEntry,
2090
+ verifyAdmission,
2091
+ onTokenCredited,
2092
+ onTokenHeld,
2093
+ onTokenHandedOver,
2094
+ lockToPayee,
2095
+ cover,
2096
+ fetchAdmission,
2097
+ settleNow,
2098
+
2099
+ async resendTransfer(txid, deps): Promise<TokenResendOutcome> {
2100
+ if (!available) return { ok: false, reason: 'no_record' }
2101
+ const box = await messageBox()
2102
+ return await resendTokenTransfer(txid, {
2103
+ blindingRecord: async id => {
2104
+ const record = await blindingGet(id)
2105
+ return record ? { recipient: record.recipient, senderBlinded: record.senderBlinded, keyID: record.keyID } : undefined
2106
+ },
2107
+ // The `mandala`-labelled action with its outputs: both rails write the
2108
+ // label (the nearby rail since 2026-09-16) and the payee output's marker.
2109
+ listAction: async id => {
2110
+ const lister = bound as unknown as {
2111
+ listActions(
2112
+ args: unknown,
2113
+ originator?: string
2114
+ ): Promise<{ actions?: (TokenResendAction & { txid?: string })[] }>
2115
+ }
2116
+ const listed = await lister.listActions({
2117
+ labels: ['mandala'],
2118
+ includeOutputs: true,
2119
+ includeLabels: true,
2120
+ limit: 1000
2121
+ })
2122
+ return listed.actions?.find(a => a.txid === id)
2123
+ },
2124
+ refetch: deps.refetch,
2125
+ admission: async id => {
2126
+ const cached = await store.getAdmission(id)
2127
+ // An unsigned entry (see `submit`) is bookkeeping, not evidence to forward.
2128
+ if (!cached || cached.signatureHex === '' || cached.signerKey === '') return undefined
2129
+ return { outputsToAdmit: cached.outputsToAdmit, signatureHex: cached.signatureHex, signerKey: cached.signerKey }
2130
+ },
2131
+ journal: { put: notifyPut, remove: notifyRemove },
2132
+ sendMessage: args => box.sendMessage(args as never),
2133
+ decryptMetadata: deps.decryptMetadata
2134
+ })
2135
+ },
2136
+ settlePendingSends,
2137
+ ensureAdmissionsForHoldings,
2138
+ recoverStaleAdmissions,
2139
+ repairAdmittedAborted,
2140
+ reviewTokenHoldings,
2141
+ pruneBlindingReservations,
2142
+ assetStatus,
2143
+ refreshAssetStatus,
2144
+
2145
+ async listAssets(): Promise<TokenAssetInfo[]> {
2146
+ const ids = new Set<string>()
2147
+ for (const output of await listTokenOutputs()) ids.add(output.assetId)
2148
+ // Assets this wallet has ever received, not only ones it still holds: a
2149
+ // spent-down asset must keep its name on the activity list.
2150
+ for (const row of await store.listSettlements()) ids.add(row.assetId)
2151
+ const assets = await Promise.all([...ids].sort().map(assetInfo))
2152
+ return assets
2153
+ },
2154
+
2155
+ async balances(): Promise<TokenBalance[]> {
2156
+ const outputs = await listTokenOutputs()
2157
+ const rows = await store.listSettlements({ role: 'received' })
2158
+ const ids = new Set<string>()
2159
+ for (const output of outputs) ids.add(output.assetId)
2160
+ for (const row of rows) ids.add(row.assetId)
2161
+
2162
+ const balances: TokenBalance[] = []
2163
+ for (const assetId of [...ids].sort()) {
2164
+ const baseUnits = outputs
2165
+ .filter(o => o.assetId === assetId && o.spendable)
2166
+ .reduce((sum, o) => sum + o.amount, 0)
2167
+ const unsettledBaseUnits = rows
2168
+ .filter(r => r.assetId === assetId && !SETTLED_STATES.has(r.state) && !TERMINAL_BY_VERDICT.has(r.state))
2169
+ .reduce((sum, r) => sum + (r.amountBaseUnits ?? 0), 0)
2170
+ balances.push({ asset: await assetInfo(assetId), baseUnits, unsettledBaseUnits })
2171
+ }
2172
+ return balances
2173
+ },
2174
+
2175
+ async activity(limit = 50): Promise<TokenActivityRow[]> {
2176
+ const rows = await store.listSettlements()
2177
+ const outputs = await listTokenOutputs()
2178
+ const nowMs = now().getTime()
2179
+ const byTxid = new Map<string, number>()
2180
+ for (const output of outputs) byTxid.set(output.txid, (byTxid.get(output.txid) ?? 0) + output.amount)
2181
+
2182
+ const ordered = [...rows].sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0))
2183
+ const out: TokenActivityRow[] = []
2184
+ for (const row of ordered.slice(0, Math.max(0, limit))) {
2185
+ out.push({
2186
+ txid: row.txid,
2187
+ role: row.role,
2188
+ asset: await assetInfo(row.assetId),
2189
+ baseUnits: row.amountBaseUnits ?? byTxid.get(row.txid) ?? 0,
2190
+ ...(row.counterpartyKey ? { counterpartyKey: row.counterpartyKey } : {}),
2191
+ status: activityStatusOf(row, nowMs),
2192
+ at: row.updatedAt || row.createdAt,
2193
+ ...(row.refusedCode ? { refusedCode: row.refusedCode } : {}),
2194
+ ...(row.refusedPayloadHash ? { refusedPayloadHash: row.refusedPayloadHash } : {})
2195
+ })
2196
+ }
2197
+ return out
2198
+ },
2199
+
2200
+ async stuck(): Promise<TokenSettlementRow[]> {
2201
+ return await listStuckSettlements(store, now().getTime())
2202
+ },
2203
+
2204
+ async sendToHandle({ assetId, recipientIdentityKey, baseUnits, note }): Promise<TokenSendResult> {
2205
+ if (!available) {
2206
+ return { kind: 'unavailable', message: 'Stablecoins are not available on this network' }
2207
+ }
2208
+ const refusal = guardTokenRecipient(recipientIdentityKey)
2209
+ if (refusal) return { kind: 'refused', code: 'ERR_RECIPIENT', message: refusal }
2210
+
2211
+ let box: MandalaMessageBox
2212
+ try {
2213
+ box = await messageBox()
2214
+ } catch (e) {
2215
+ return { kind: 'unavailable', message: messageOf(e) }
2216
+ }
2217
+
2218
+ try {
2219
+ const result = await transferTokens({
2220
+ wallet: bound,
2221
+ messageBoxClient: box,
2222
+ identityKey: await identityKey(),
2223
+ assetId,
2224
+ amount: baseUnits,
2225
+ recipientKey: recipientIdentityKey,
2226
+ // 2026-09-15 maintainer decision (§4.5, §12.9, wire contract §9.13):
2227
+ // EVERY rail is hand-over-first. The SEND contacts no overlay at all —
2228
+ // the bytes are built and signed `noSend`, the payee is handed the
2229
+ // evidence, and whoever reconnects first submits. The payer's own
2230
+ // submit follows the hand-over rather than racing it: `settleNow`
2231
+ // below when this device has signal, the ordinary drain otherwise,
2232
+ // both over the `handed_over` row written below.
2233
+ mode: 'handover',
2234
+ evidence: storeEvidenceSource,
2235
+ note
2236
+ })
2237
+ // The handle rail's own evidence (spec §4.5): the exact bytes and
2238
+ // off-chain payload just handed over, cached the same way a nearby
2239
+ // hand-over's frame would be. On this rail it is no longer merely an
2240
+ // optimisation — the drain's own `submit()` reads the tip's linkage
2241
+ // row to build the `/submit` body, so without this write the payment
2242
+ // could only ever be settled by the payee. Its own try/catch: the
2243
+ // payee already holds the bytes, so a bad or missing value must cost a
2244
+ // later reconciliation pass, never the settlement journal below (still
2245
+ // less the payment itself, which is already made).
2246
+ try {
2247
+ if (Array.isArray(result.atomicBeef) && result.atomicBeef.length > 0) {
2248
+ const edges = deriveTokenEdges(Uint8Array.from(result.atomicBeef), assetId)
2249
+ if (edges.length > 0) await store.putEdges(edges)
2250
+ }
2251
+ if (Array.isArray(result.offChainValues) && result.offChainValues.length > 0) {
2252
+ const linkageRow: TokenLinkageRow = {
2253
+ txid: result.txid,
2254
+ payloadBytes: Uint8Array.from(result.offChainValues),
2255
+ overlayUrl,
2256
+ overlayIdentityKey,
2257
+ source: 'minted',
2258
+ createdAt: now().toISOString()
2259
+ }
2260
+ await store.putLinkage(linkageRow)
2261
+ }
2262
+ } catch (e) {
2263
+ devLog(`[mandala] sent ${result.txid} but could not cache its evidence:`, e)
2264
+ }
2265
+ try {
2266
+ await store.upsertSettlement({
2267
+ txid: result.txid,
2268
+ role: 'sent',
2269
+ assetId,
2270
+ // Always `handed_over`, never `admitted`: at THIS point the device
2271
+ // has no proof of admission and has asked for none. The row is what
2272
+ // `settleNow` claims a moment later (and failing that, what the
2273
+ // drain picks up on its next online tick — `postTokenStep` over
2274
+ // `handed_over`), and what `activityStatusOf` reads as "settling".
2275
+ state: 'handed_over',
2276
+ counterpartyKey: recipientIdentityKey,
2277
+ amountBaseUnits: baseUnits,
2278
+ overlayUrl,
2279
+ overlayIdentityKey,
2280
+ // The `createAction`/`signAction` reference of the noSend action
2281
+ // that built these bytes, when the lib reports one. It is what
2282
+ // `wrapAbortActionForSettlements` matches an `abortAction` against,
2283
+ // and it must be on the row BEFORE the submit below — the incident
2284
+ // window opens the instant the overlay admits (and broadcasts), and
2285
+ // a reference written afterwards would leave exactly that window
2286
+ // unguarded. Read structurally because `TransferResult.reference` is
2287
+ // landing in the linked lib concurrently; absent, the row simply has
2288
+ // no reference and the guard blocks nothing for it.
2289
+ ...referenceOf(result)
2290
+ })
2291
+ } catch (e) {
2292
+ // The transfer is committed; a journal failure costs a later
2293
+ // reconciliation pass, never the payment.
2294
+ devLog(`[mandala] sent ${result.txid} but could not journal it:`, e)
2295
+ }
2296
+ emit()
2297
+ // `notified === false` is "committed, but the payee has not been told
2298
+ // yet" — the lib journaled the notification and `reconcileJournals`
2299
+ // retries it every tick. It is reported, never retried here: a retry of
2300
+ // the SEND would be a second payment.
2301
+ const notified = result.notified !== false
2302
+
2303
+ // ── THEN, and only then, this device's own submit (§4.3, 2026-09-15) ──
2304
+ //
2305
+ // Hand-over first is not softened by this, it is *completed* by it: the
2306
+ // v2 body is posted and the `handed_over` row is durable before a
2307
+ // single byte goes to the overlay, and both of those are above this
2308
+ // line. What changes is that a payer who has signal no longer waits a
2309
+ // drain interval to finish what they started.
2310
+ //
2311
+ // Two conditions, and both are about the hand-over rather than about
2312
+ // the overlay:
2313
+ //
2314
+ // · `notified` — a notification that did not go out means the payee
2315
+ // has NOT been handed anything yet, so the order is not satisfied
2316
+ // and the submit waits for `reconcileNotifications` to deliver it.
2317
+ // · `isOnline()` — offline there is nothing to try, and the probe is
2318
+ // made here rather than inside `settleNow` so a send on a dead
2319
+ // connection costs no request at all.
2320
+ //
2321
+ // Everything after this point is best-effort by construction: the
2322
+ // result is already `sent`, `settleNow` cannot throw, and a timeout
2323
+ // leaves the same in-flight submit running for the drain to observe.
2324
+ let settled = false
2325
+ if (notified) {
2326
+ try {
2327
+ if (await isOnline()) {
2328
+ const state = await settleWithinSendTimeout(result.txid)
2329
+ settled = state === 'admitted' || state === 'broadcast'
2330
+ if (state === 'timeout') {
2331
+ devLog(`[mandala] ${result.txid} was handed over; its submit runs on, and the drain will finish it`)
2332
+ }
2333
+ }
2334
+ } catch (e) {
2335
+ // Logged, never surfaced. The payment is made either way.
2336
+ devLog(`[mandala] handed ${result.txid} over but could not settle it now:`, e)
2337
+ }
2338
+ }
2339
+ return { kind: 'sent', txid: result.txid, settled, notified }
2340
+ } catch (e) {
2341
+ const overlay = asOverlayRefusal(e)
2342
+ // Always leave the real cause in the console. Nothing here contacts an
2343
+ // overlay any more, so an 'unavailable' is a LOCAL fault (MessageBox,
2344
+ // wallet, coin selection) and its full text is the only diagnosis
2345
+ // there is — the banner keeps one sentence of it.
2346
+ console.warn('[mandala] sendToHandle failed:', overlay ? `${overlay.code} ${overlay.message}` : e)
2347
+ if (overlay) {
2348
+ return overlay.retryable
2349
+ ? { kind: 'unavailable', message: overlay.message }
2350
+ : { kind: 'refused', code: overlay.code, message: overlay.message }
2351
+ }
2352
+ return { kind: 'unavailable', message: messageOf(e) }
2353
+ }
2354
+ },
2355
+
2356
+ async receiveFromInbox(): Promise<{ credited: number; failed: number }> {
2357
+ if (!available) return { credited: 0, failed: 0 }
2358
+ let box: MandalaMessageBox
2359
+ try {
2360
+ box = await messageBox()
2361
+ } catch (e) {
2362
+ devLog('[mandala] no MessageBox client for the inbox drain:', e)
2363
+ return { credited: 0, failed: 0 }
2364
+ }
2365
+ const result = await receiveTokens({
2366
+ wallet: bound,
2367
+ messageBoxClient: box,
2368
+ processed: processedMessages,
2369
+ settle: settleThroughDrain
2370
+ })
2371
+ for (const transfer of result.accepted) {
2372
+ try {
2373
+ await journalReceived(transfer)
2374
+ } catch (e) {
2375
+ // Already credited by the lib: a journal failure must not undo it.
2376
+ devLog('[mandala] credited a transfer but could not journal it:', e)
2377
+ }
2378
+ }
2379
+ if (result.accepted.length > 0) emit()
2380
+ return { credited: result.accepted.length, failed: result.failed.length }
2381
+ },
2382
+
2383
+ reconcileJournals,
2384
+
2385
+ async drainNow(): Promise<void> {
2386
+ if (!db) return
2387
+ // FIX C recovery, the lib's own journals and the nearby-blinding
2388
+ // reservation sweep ride the same tick as the ordinary
2389
+ // submit-then-broadcast pass (see also the `TaskSendOffline` wiring,
2390
+ // which calls these directly alongside its own `processOfflineActions`
2391
+ // for the production drain).
2392
+ await recoverStaleAdmissions()
2393
+ // Before the release pass, not after: a transaction this restores to
2394
+ // 'unproven' has its inputs re-marked spent, and the whole point is that
2395
+ // the release pass below must never plan a send from a coin that is
2396
+ // already gone.
2397
+ await repairAdmittedAborted()
2398
+ await reconcileJournals()
2399
+ await settlePendingSends()
2400
+ await ensureAdmissionsForHoldings()
2401
+ await pruneBlindingReservations()
2402
+ await processOfflineActions({
2403
+ storage,
2404
+ ...(args.refetchBeef ? { refetchBeef: args.refetchBeef } : {}),
2405
+ token: tokenDeps
2406
+ })
2407
+ emit()
2408
+ },
2409
+
2410
+ recipientRefusal(recipient: string): string | null {
2411
+ return guardTokenRecipient(recipient)
2412
+ },
2413
+
2414
+ subscribe(listener: () => void): () => void {
2415
+ listeners.add(listener)
2416
+ return () => {
2417
+ listeners.delete(listener)
2418
+ }
2419
+ }
2420
+ }
2421
+
2422
+ return runtime
2423
+ }
2424
+
2425
+ /** The first Mandala asset this transaction's own outputs name, for a tip with no settlement row. */
2426
+ function assetIdOfTx(tx: Transaction): string | undefined {
2427
+ for (const output of tx.outputs) {
2428
+ if (!output.lockingScript) continue
2429
+ try {
2430
+ return MandalaToken.decode(output.lockingScript).assetId
2431
+ } catch {
2432
+ // Not a token output.
2433
+ }
2434
+ }
2435
+ return undefined
2436
+ }
2437
+