@bsv/expo-wallet-toolbox 0.21.0 → 0.22.0

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