@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,330 +1,80 @@
1
1
  /**
2
- * Shared types for Mandala stablecoin settlement in the wallet.
2
+ * Shared types for 1Color token transfers in the wallet.
3
3
  *
4
- * Source of truth: the offline-settlement spec (recipient submits; σ_I per
5
- * input txid with recursive walk-back; idempotent /submit) and the
6
- * wire contract v2. Pure types only — no runtime, no imports from storage,
7
- * so every module (stores, drain, codec, verifier, UI) can depend on this
8
- * file without creating cycles.
4
+ * The color permission module holds all token custody and evidence. The
5
+ * wallet keeps exactly one durable host record of its own: the
6
+ * `color_transfers` journal (`transferJournal.ts`), one row per token tx per
7
+ * role. It is the only key the broadcast hold and the abort refusal read
8
+ * (plan 07, W1); neither ever reads the module's internal `color.v1.*` keys.
9
+ *
10
+ * Pure types and constants only — no runtime imports — so every module
11
+ * (journal, guards, runtime, UI) can depend on this file without a cycle.
9
12
  */
10
13
 
11
- /** token_settlements.state — one row per token tx per party (spec §5). */
12
- export type TokenSettlementState =
13
- | 'built'
14
- | 'parked'
15
- | 'handed_over'
16
- | 'held'
17
- | 'submitting'
18
- | 'admitted'
19
- | 'broadcast'
20
- | 'refused'
21
- | 'orphaned'
14
+ export type ColorTransferRole = 'sent' | 'received'
15
+
16
+ export type ColorTransferRail = 'handle' | 'nearby' | 'external'
22
17
 
23
- export type TokenSettlementRole = 'sent' | 'received'
18
+ /**
19
+ * sent: built → (parked ⇄) handed_over → settled | refused; built|parked → cancelled.
20
+ * received: held → settled | refused.
21
+ *
22
+ * Only `settled` releases a tx to the network. Every other state, and a
23
+ * missing row, holds it.
24
+ */
25
+ export type ColorTransferState = 'built' | 'parked' | 'handed_over' | 'held' | 'settled' | 'refused' | 'cancelled'
26
+
27
+ export const COLOR_TRANSFER_ROLES: readonly ColorTransferRole[] = ['sent', 'received']
28
+ export const COLOR_TRANSFER_RAILS: readonly ColorTransferRail[] = ['handle', 'nearby', 'external']
29
+ export const COLOR_TRANSFER_STATES: readonly ColorTransferState[] = [
30
+ 'built',
31
+ 'parked',
32
+ 'handed_over',
33
+ 'held',
34
+ 'settled',
35
+ 'refused',
36
+ 'cancelled'
37
+ ]
38
+
39
+ /** States no transition leaves. */
40
+ export const TERMINAL_TRANSFER_STATES: readonly ColorTransferState[] = ['settled', 'refused', 'cancelled']
41
+
42
+ /** A non-terminal row older than this is surfaced as "stuck". */
43
+ export const STUCK_AFTER_MS = 3 * 24 * 60 * 60 * 1000
24
44
 
25
- export interface TokenSettlementRow {
45
+ export interface ColorTransferRow {
26
46
  txid: string
27
- role: TokenSettlementRole
47
+ role: ColorTransferRole
48
+ /** `<64 lowercase hex>_<vout>` (IC §0). */
28
49
  assetId: string
29
- state: TokenSettlementState
50
+ /** Exact token units of `outputIndex`. Stored as a canonical decimal TEXT, never a number. */
51
+ units: bigint
52
+ /** The output of `txid` this row is about: the payee's output on both sides. */
53
+ outputIndex: number
30
54
  counterpartyKey?: string
31
- amountBaseUnits?: number
32
- overlayUrl: string
33
- overlayIdentityKey: string
34
- /** outputsToAdmit once known (from our own submit, a bundle, or a fetch). */
35
- admissionOutputs?: number[]
36
- /** σ_I over THIS txid once known (DER hex). */
37
- admissionSignatureHex?: string
38
- /**
39
- * Which output of THIS txid the wallet's own stake in the payment is — the
40
- * payee's output, for both a `received` row and a `sent` row (frame
41
- * convention: output 0 is always the payee's, never the payer's own change
42
- * — see `onTokenHandedOver`). Read as 0 when absent, mirroring
43
- * `EvidenceFrame.outputIndex`'s own "absent reads as 0" convention.
44
- *
45
- * The one thing `admissionStandsIn` (drain.ts) requires present in a cached
46
- * admission's `outputsToAdmit` before that admission may stand in for a real
47
- * `/submit` of THIS txid (XR-038): a genuine σ_I for some OTHER output of
48
- * the same txid — the payer's own change, say — must never be read as
49
- * covering this one.
50
- */
51
- relevantVout?: number
52
- refusedCode?: string
53
- /**
54
- * `payloadHash` of the off-chain linkage bytes this device submitted when
55
- * the overlay returned `refusedCode` (amendment v2.1 §9.1/§9.3). A refusal
56
- * is keyed by `(txid, payloadHash)`, not by txid alone, so the UI needs this
57
- * alongside `refusedCode` to say "refused for THIS payload" rather than
58
- * implying every payload for this txid is dead. Set only alongside
59
- * `refusedCode`; absent when this device held no linkage bytes to hash.
60
- */
61
- refusedPayloadHash?: string
62
- poisonedByTxid?: string
63
55
  /**
64
- * The `createAction`/`signAction` **reference** of the wallet action that
65
- * built this transaction, when this device is the one that built it.
66
- *
67
- * Recorded so an `abortAction` can be recognised for what it is. A token
68
- * payment is signed `noSend` and handed over BEFORE anything is broadcast,
69
- * so for a window the only thing holding its inputs is a live noSend action
70
- * — and `abortAction(reference)` releases those inputs as spendable. Once
71
- * the overlay has admitted the transaction (it broadcasts on admission) that
72
- * release is a double spend waiting to happen: the next send reuses a coin
73
- * that is already spent on chain, and the overlay refuses the child with
74
- * `ERR_INPUT_SPENT`. That is the 2026-09-15 incident, and the reference is
75
- * what lets `wrapAbortActionForSettlements` refuse the abort instead.
76
- *
77
- * Absent for rows this device did not build (every `received` row) and for
78
- * rows written before the column existed — an unknown reference is never a
79
- * reason to refuse an abort.
56
+ * The `createAction` reference of the action that built `txid`, when this
57
+ * device built it. The abort refusal's lookup key; absent on received rows.
80
58
  */
81
59
  reference?: string
60
+ rail: ColorTransferRail
61
+ state: ColorTransferState
62
+ /** Handle rail: whether the hand-over is known to have reached the recipient's box. */
63
+ delivered: boolean
64
+ /** The refusal code, on a `refused` row. */
65
+ code?: string
66
+ note?: string
67
+ /** Sent rows: the receipt custody needed to resend (A′ when blinded). */
68
+ derivationPrefix?: string
69
+ derivationSuffix?: string
70
+ senderIdentityKey?: string
82
71
  createdAt: string
83
72
  updatedAt: string
84
73
  }
85
74
 
86
- /** token_admissions — cache of AdmissionEntry values this device has seen. */
87
- export interface TokenAdmissionRow {
88
- txid: string
89
- outputsToAdmit: number[]
90
- signatureHex: string
91
- signerKey: string
92
- source: 'minted' | 'bundle' | 'submitted' | 'fetched'
93
- obtainedAt: string
94
- }
95
-
96
- /** token_admission_edges — child spends parent:vout (token inputs only). */
97
- export interface TokenAdmissionEdge {
98
- childTxid: string
99
- parentTxid: string
100
- parentVout: number
101
- }
102
-
103
- /** token_linkage_payloads — off-chain linkage bytes for UNADMITTED chain txs. */
104
- export interface TokenLinkageRow {
105
- txid: string
106
- payloadBytes: Uint8Array
107
- overlayUrl: string
108
- overlayIdentityKey: string
109
- source: 'minted' | 'forwarded'
110
- createdAt: string
111
- }
112
-
113
- /** Wire-contract v2 §2: what the overlay answered for one /submit. */
114
- export type OverlayVerdict =
115
- | { kind: 'admitted'; outputsToAdmit: number[]; signatureHex: string; signerKey: string }
116
- | { kind: 'refused'; code: string; spendTxid?: string } // final (400) — terminal
117
- | { kind: 'evicted' } // 410 — terminal, inputs restored
118
- | { kind: 'unavailable'; code: string; retryable: true } // 409 liftable or 503 — retry
119
-
120
- /** An AdmissionEntry as carried on the wire (frame v4 `admissions[]`). */
121
- export interface AdmissionEntryWire {
122
- txid: string
123
- /**
124
- * BRC-162 σI v3 topic (`tokenTopic(assetId)`). Optional: when absent the
125
- * verifier derives it from the transaction's own token outputs.
126
- */
127
- topic?: string
128
- outputsToAdmit: number[]
129
- signature: Uint8Array
130
- signerKey: string
131
- }
132
-
133
- /** Result of the pure COVER walk (spec §1.2). mustSubmit is parents-first, tip last. */
134
- export type CoverResult =
135
- | { ok: true; mustSubmit: string[] }
136
- | { ok: false; reason: 'uncovered_ancestor' | 'unsafe_asset' | 'shape' }
137
-
138
75
  /**
139
- * Storage-facing API for the four settlement tables. Implemented in
140
- * core/mandala/settlementStore.ts over StorageExpoSQLite's connection.
141
- * Every write is idempotent (INSERT OR IGNORE / keyed UPDATE) — spec FIX G.
142
- */
143
- export interface SettlementStore {
144
- // token_settlements
145
- getSettlement(txid: string): Promise<TokenSettlementRow | undefined>
146
- /**
147
- * The row whose `reference` is this wallet action's, or undefined.
148
- *
149
- * The abort guard's only question, and it is asked on the hot path of every
150
- * `abortAction` the wallet makes — including plain BSV ones, which have no
151
- * row at all — so it is one indexed statement rather than a scan.
152
- */
153
- getSettlementByReference(reference: string): Promise<TokenSettlementRow | undefined>
154
- /**
155
- * XR-033: whether any row is stuck in a blocked state (see
156
- * `abortGuard.ts`'s `ABORT_BLOCKED_SETTLEMENT_STATES`) with no `reference`
157
- * to match an `abortAction` against — a pre-migration row the one-time
158
- * backfill (`createTables.ts`'s `ensureTokenSettlementColumns`) could not
159
- * resolve, most likely because its transaction row is gone. Such a row is
160
- * invisible to `getSettlementByReference` no matter what reference is
161
- * asked for, so the abort guard's second, coarser layer asks this instead:
162
- * true refuses EVERY abort until the row is reconciled, which trades an
163
- * occasional over-refusal of an unrelated action for never silently
164
- * releasing inputs a legacy row still has a claim on.
165
- */
166
- hasUnresolvedLegacyBlockedRows(): Promise<boolean>
167
- listSettlements(filter?: {
168
- state?: TokenSettlementState[]
169
- role?: TokenSettlementRole
170
- }): Promise<TokenSettlementRow[]>
171
- upsertSettlement(row: Omit<TokenSettlementRow, 'createdAt' | 'updatedAt'> & { createdAt?: string }): Promise<void>
172
- /** Single-statement state advance; returns false if the row was not in one of `from`. */
173
- advanceSettlement(
174
- txid: string,
175
- from: TokenSettlementState[],
176
- to: TokenSettlementState,
177
- patch?: Partial<TokenSettlementRow>
178
- ): Promise<boolean>
179
- // token_admissions
180
- getAdmission(txid: string): Promise<TokenAdmissionRow | undefined>
181
- putAdmission(row: TokenAdmissionRow): Promise<void>
182
- // token_admission_edges
183
- putEdges(edges: TokenAdmissionEdge[]): Promise<void>
184
- parentsOf(childTxid: string): Promise<TokenAdmissionEdge[]>
185
- // token_linkage_payloads
186
- getLinkage(txid: string): Promise<TokenLinkageRow | undefined>
187
- putLinkage(row: TokenLinkageRow): Promise<void>
188
- }
189
-
190
- // ──────────────────── the frame, structurally (FIX G supply) ────────────────────
191
-
192
- /**
193
- * The token block of a payment frame, as the settlement machinery reads it.
194
- *
195
- * Structural rather than an import of `localpay/codec`'s `TokenPayment` on
196
- * purpose: this file may not depend on the codec (it is the leaf every other
197
- * module imports), and describing the shape here means the drain, the payer's
198
- * hold and the receiver's queue all agree on one type without a cycle.
199
- * `admissions[]` is optional so a v3 frame — linkage and edges only — still
200
- * type-checks through the same path.
201
- */
202
- export interface EvidenceTokenBlock {
203
- assetId: string
204
- overlayUrl: string
205
- overlayIdentityKey: string
206
- linkage: readonly { txid: string; payload: Uint8Array }[]
207
- admissions?: readonly AdmissionEntryWire[]
208
- }
209
-
210
- /** Satisfied by `PaymentFrame` from `localpay/codec`. */
211
- export interface EvidenceFrame {
212
- kind?: string
213
- /**
214
- * Optional here and required on `PaymentFrame`: a settlement row wants it for
215
- * `counterpartyKey`, but nothing structural depends on its presence, and the
216
- * drain re-derives rows from frames it has only the token block of.
217
- */
218
- senderIdentityKey?: string
219
- /**
220
- * Which output of the atomic transaction is the payee's. Present on every
221
- * `PaymentFrame`; optional here because the drain re-derives rows from frames
222
- * it has only the token block of. Read as 0 when absent — the nearby build
223
- * never randomises outputs, so the payee's is always the first.
224
- */
225
- outputIndex?: number
226
- token?: EvidenceTokenBlock
227
- /** AtomicBEEF. The only place the edge graph can come from, offline. */
228
- transaction: Uint8Array
229
- }
230
-
231
- // ─────────────────────── FIX H: the trust anchor, injected ───────────────────
232
-
233
- /**
234
- * Verifies one counterparty-supplied `AdmissionEntry`'s σ_I — cryptographically,
235
- * against the wallet's OWN CONFIGURED overlay identity key, which the
236
- * implementation closes over.
237
- *
238
- * Injected rather than imported because the σ_I digest is the overlay's own and
239
- * lives in `@bsv/mandala`, so the wallet and the overlay cannot disagree about
240
- * what is signed. Wire contract §9.10: the expected signer key comes from the
241
- * verifier's own configuration; an `overlayIdentityKey` that arrived on a frame
242
- * or sits on a settlement row is DATA and can never be the anchor.
243
- *
244
- * Returns a plain boolean for every failure there is — a malformed signature, a
245
- * foreign key, an empty admitted set — because FIX H treats an unverifiable σ_I
246
- * as ABSENT, never as a decline.
247
- */
248
- export type AdmissionVerifier = (entry: AdmissionEntryWire) => boolean | Promise<boolean>
249
-
250
- // ───────────────────────── settlement-durability hooks ─────────────────────────
251
-
252
- /**
253
- * RECEIVER, called BEFORE `wallet.internalizeAction` (§4.2, §4.3 guard #2).
254
- *
255
- * Writes the `token_settlements` row (state `'held'`) and the frame's evidence.
256
- * It has to run first because the guard that stops an unadmitted token
257
- * broadcast — `attemptToPostReqsToNetwork`'s `token_settlements` lookup — reads
258
- * that row, and `internalizeAction` triggers a forced broadcast of its own. A
259
- * row written only AFTER the credit fails open on the very first internalize,
260
- * which is the one moment it matters.
261
- *
262
- * A throw therefore means "do not credit yet": the frame is already durable in
263
- * `localpay_pending`, so the next tick retries the whole step.
264
- */
265
- export type TokenHeldHook = (frame: EvidenceFrame, txid: string) => Promise<void>
266
-
267
- /** Which side of the payer's own fork a hand-over landed on. */
268
- export type TokenHandoverState = 'parked' | 'handed_over'
269
-
270
- /**
271
- * PAYER, called at park/hold time with the PLAINTEXT frame.
272
- *
273
- * `offline_actions.framePayload` holds the frame SEALED with the nearby
274
- * session's pre-shared key, and that key is in-memory only — so a payer that
275
- * restarts can no longer open its own frame, and a settlement row derived only
276
- * from it would never exist. This hook is handed the frame while it is still
277
- * open, so the row and the evidence are durable independently of the PSK.
278
- *
279
- * Best-effort at the call site: the queue row is written first and is the
280
- * durable fact.
281
- */
282
- export type TokenHandedOverHook = (
283
- frame: EvidenceFrame,
284
- txid: string,
285
- state: TokenHandoverState,
286
- /**
287
- * The `createAction` reference of the action that built `txid`, when the
288
- * caller still holds it. Recorded on the row so an abort of that action can
289
- * be refused once the overlay has the bytes — see `TokenSettlementRow.reference`.
290
- * Optional: a caller that does not have one simply leaves the column null,
291
- * which reads as "unknown reference" and blocks nothing.
292
- */
293
- reference?: string
294
- ) => Promise<void>
295
-
296
- /** Injected by the drain: run COVER for a tip against local evidence. */
297
- export type CoverFn = (tipTxid: string) => Promise<CoverResult>
298
- /** Injected by the drain: POST /submit for one txid (beef + linkage resolved from local tables). */
299
- export type SubmitFn = (txid: string) => Promise<OverlayVerdict>
300
- /** Injected: GET /admin/admission/:txid (undefined = 404 / unknown). */
301
- export type FetchAdmissionFn = (overlayUrl: string, txid: string) => Promise<OverlayVerdict | undefined>
302
-
303
- /** FIX M: a non-terminal row older than this is surfaced as "stuck". */
304
- export const STUCK_AFTER_MS = 3 * 24 * 60 * 60 * 1000
305
-
306
- /**
307
- * The basket Mandala token outputs (and change) live in. Deliberately
308
- * `'p '`-prefixed (BRC-99 P-basket) so `WalletPermissionsManager` routes every
309
- * `listOutputs`/`createAction`(basket output)/`internalizeAction`(basket
310
- * insertion)/`relinquishOutput` call against it through
311
- * `MandalaTokenModule` (schemeID 'mandala' = `'p mandala'.split(' ')[1]`),
312
- * regardless of originator. A flat, single basket for every asset -- unlike
313
- * BTMS's per-asset `'p btms <assetId>'` baskets, Mandala keeps one cardinality
314
- * for the whole scheme. Was `'mandala-tokens'` (not P-routed, no gate at all);
315
- * see core/mandala/basketMigration.ts for the one-time rename and
316
- * offline-settlement-final.md §8 for the rationale.
317
- */
318
- export const MANDALA_BASKET = 'p mandala'
319
-
320
- /**
321
- * The action label every token transfer carries, on every rail.
322
- *
323
- * `@bsv/mandala`'s own `transferTokens` / `receiveTokens` write it, and the
324
- * home screen recognises a token row by it ALONE — by label, not by holdings,
325
- * so a user who sends their last coin keeps the denomination across their
326
- * history. The nearby rail's token actions have to write the same label, or
327
- * they render as BSV rows: the counterparty's abbreviated key over "+0 sats"
328
- * (2026-09-16).
76
+ * The action label every token transfer carries, on every rail. A plain
77
+ * (non-P) label: the home screen recognises a token row by it, so a user who
78
+ * sends their last coin keeps the denomination across their history.
329
79
  */
330
80
  export const MANDALA_ACTION_LABEL = 'mandala'
package/core/networks.ts CHANGED
@@ -119,11 +119,11 @@ export const NETWORKS: Record<AppChain, NetworkProfile> = {
119
119
  //
120
120
  // Not available yet. The deployed chain runs Teranode regtest parameters
121
121
  // (regtest genesis 0f9188f1…, bits 0x207fffff; its chaintracks reports
122
- // 'regtest'), so the toolbox chain is 'regtest', not 'tstn'. The installed
123
- // @bsv/wallet-toolbox-mobile 2.14.x has no 'regtest' chain and rejects every
124
- // header above the mainnet proof-of-work limit, so nothing on it can be
125
- // verified. Switch it on once the dependency is 2.15.0 or later
126
- // (bsv-blockchain/ts-stack#819).
122
+ // 'regtest'), so the toolbox chain is 'regtest', not 'tstn'. Toolbox 2.14.x
123
+ // had no 'regtest' chain and rejected every header above the mainnet
124
+ // proof-of-work limit. The installed @bsv/wallet-toolbox-mobile 2.15.0 has
125
+ // it (bsv-blockchain/ts-stack#819), so the services build; switching the
126
+ // network on is a separate, deliberate change.
127
127
  scaletest: {
128
128
  walletChain: 'regtest',
129
129
  available: false,
@@ -16,8 +16,9 @@
16
16
  import { updateOfflineAction } from '../storage/methods/offlineActions'
17
17
  import { devLog } from '../logging'
18
18
  import { getOnline } from '../net/online'
19
- import type { FetchAdmissionFn, SettlementStore } from '../mandala/types'
20
19
  import type { MandalaRuntime } from '../mandala/runtime'
20
+ import type { TransferJournal } from '../mandala/transferJournal'
21
+ import type { ColorTransferState } from '../mandala/types'
21
22
 
22
23
  const CANCELLABLE = new Set(['nosend', 'unsigned', 'unprocessed'])
23
24
 
@@ -49,43 +50,47 @@ export interface CancelParkedWallet {
49
50
  * FIX J: what makes a cancel overlay-authoritative for a token payment.
50
51
  *
51
52
  * Omit it entirely — every BSV caller does — and the cancel behaves exactly as
52
- * it always has. There is deliberately no "cancel by respend" path:
53
- * `token_settlements` has no `cancelling` state, so the only exits from
54
- * `handed_over`/`held` are the overlay's own eventual terminal verdict or this
55
- * check of a payment it never admitted.
53
+ * it always has. For a txid with a `color_transfers` row (plan 07 Task 15) the
54
+ * overlay, not this device, decides whether the payee's own submit already
55
+ * landed: a parked payment the payee scanned may have been admitted, and
56
+ * aborting it then releases inputs the overlay considers spent.
56
57
  */
57
58
  export interface CancelParkedSettlementDeps {
58
- settlements: Pick<SettlementStore, 'getSettlement'>
59
59
  /**
60
- * GET /admin/admission/:txid.
61
- *
62
- * The URL this is called with is ADVISORY. The row's `overlayUrl` is
63
- * re-derived from frames a counterparty wrote, so the runtime's
64
- * implementation pins every request to its own configured overlay and
65
- * verifies the answer against its own configured key (§9.10) — which is what
66
- * stops a payer naming a server that would happily "admit" their own
67
- * payment and talk this cancel out of releasing the coins.
60
+ * The runtime's `isHandoverAdmitted`: `true` admitted, `false` asked and
61
+ * not admitted, `undefined` could not be asked. It reads this device's own
62
+ * configured overlay through the module's provider, never a URL from a
63
+ * frame or a row.
68
64
  */
69
- fetchAdmission: FetchAdmissionFn
70
- /** Offline there is nothing to poll, so the local check stands alone. */
65
+ isHandoverAdmitted: (txid: string) => Promise<boolean | undefined>
66
+ /** The `color_transfers` journal: the row to protect, and where the outcome is recorded. */
67
+ journal: Pick<TransferJournal, 'get' | 'advance'>
68
+ /** Offline there is nothing to ask, so the local check stands alone. */
71
69
  isOnline: () => Promise<boolean>
72
70
  }
73
71
 
72
+ /** Journal states a cancel may still release: the payer's own, plus a final word the money never moved. */
73
+ const CANCELLABLE_TRANSFER_STATES: readonly ColorTransferState[] = ['built', 'parked', 'refused', 'cancelled']
74
+ /** The states a cancel moves to `cancelled`. */
75
+ const PAYER_STATES: readonly ColorTransferState[] = ['built', 'parked']
76
+
74
77
  /**
75
78
  * Assembles `CancelParkedSettlementDeps` from the Mandala runtime, for a
76
- * cancel call site: `mandala.store` already satisfies the read-only
77
- * `settlements` slice, and `mandala.fetchAdmission` is FIX-H-verified and
78
- * scoped to this session's overlay identity key. Returns `undefined` when
79
- * Mandala is unavailable — passing that straight through as `settlement`
80
- * leaves `cancelParkedPayment` exactly as it behaves for a plain BSV payment
81
- * (the local `nosend` check stands alone).
79
+ * cancel call site. Returns `undefined` when Mandala is unavailable — passing
80
+ * that straight through as `settlement` leaves `cancelParkedPayment` exactly
81
+ * as it behaves for a plain BSV payment (the local `nosend` check stands
82
+ * alone).
82
83
  */
83
84
  export function mandalaSettlementDeps(
84
- mandala: Pick<MandalaRuntime, 'available' | 'store' | 'fetchAdmission'> | undefined,
85
+ mandala: Pick<MandalaRuntime, 'available' | 'isHandoverAdmitted' | 'journal'> | undefined,
85
86
  isOnline: () => Promise<boolean> = getOnline
86
87
  ): CancelParkedSettlementDeps | undefined {
87
88
  if (!mandala?.available) return undefined
88
- return { settlements: mandala.store, fetchAdmission: mandala.fetchAdmission, isOnline }
89
+ return {
90
+ isHandoverAdmitted: async txid => await mandala.isHandoverAdmitted(txid),
91
+ journal: mandala.journal,
92
+ isOnline
93
+ }
89
94
  }
90
95
 
91
96
  export async function cancelParkedPayment(args: {
@@ -124,29 +129,39 @@ export async function cancelParkedPayment(args: {
124
129
 
125
130
  // FIX J. Locally this transaction still looks cancellable — it is `nosend`
126
131
  // and its inputs are still reserved — but for a token payment the overlay,
127
- // not this device, decides. The counterparty's own submit may already have
128
- // landed (rule 3: the RECIPIENT settles the hop), in which case aborting
129
- // would release inputs the overlay has already marked spent and hand the
130
- // payer a double-spend against the person they just paid.
132
+ // not this device, decides. The payee's own submit may already have landed
133
+ // (the RECIPIENT settles the hop), in which case aborting would release
134
+ // inputs the overlay has already marked spent and hand the payer a
135
+ // double-spend against the person they just paid.
131
136
  //
132
- // XR-100: a settlement ROW is the signal that this txid was genuinely
133
- // handed over — once one exists, "cannot ask the overlay" (offline, or a
134
- // `fetchAdmission` that comes back `unavailable`) must not be read as "the
135
- // overlay says no". Only a txid with NO row at all (never locally tracked
136
- // as a token hand-over) is safe to fall through with no admission check.
137
- if (settlement) {
138
- const row = await settlement.settlements.getSettlement(txid)
139
- if (row) {
140
- if (await isOnline(settlement)) {
141
- const verdict = await fetchAdmissionSafely(settlement, row.overlayUrl, txid)
142
- if (verdict?.kind === 'admitted') return 'already-sent'
143
- if (verdict?.kind === 'unavailable' && !acknowledgedUnverifiable) return 'unverifiable-offline'
144
- } else if (!acknowledgedUnverifiable) {
145
- // Cannot ask the overlay at all while offline. Same refusal as the
146
- // BSV-rail check below, and the same escape hatch: the caller shows
147
- // the destructive confirm and retries with `acknowledgedUnverifiable`.
148
- return 'unverifiable-offline'
137
+ // XR-100: a journal row is the signal that this txid was genuinely built
138
+ // as a token hand-over — once one exists, "cannot ask the overlay"
139
+ // (offline, or an `undefined` answer) must not be read as "the overlay says
140
+ // no". Only a txid with NO row at all is safe to fall through with no
141
+ // admission check. A journal read fault propagates: it is not "no row".
142
+ const row = settlement ? await settlement.journal.get(txid) : undefined
143
+ if (settlement && row) {
144
+ // The journal already says the payee has it (or the overlay admitted it):
145
+ // the abort guard would refuse, and the honest answer is "already sent".
146
+ if (!CANCELLABLE_TRANSFER_STATES.includes(row.state)) return 'already-sent'
147
+ if (await isOnline(settlement)) {
148
+ const admitted = await isHandoverAdmittedSafely(settlement, txid)
149
+ if (admitted === true) {
150
+ // Record what the overlay just said, so every later reader (the abort
151
+ // guard, the activity list) agrees with it.
152
+ try {
153
+ await settlement.journal.advance(txid, PAYER_STATES, 'handed_over', { delivered: true })
154
+ } catch (e) {
155
+ devLog(`[cancelParkedPayment] could not journal ${txid} as handed over:`, e)
156
+ }
157
+ return 'already-sent'
149
158
  }
159
+ if (admitted === undefined && !acknowledgedUnverifiable) return 'unverifiable-offline'
160
+ } else if (!acknowledgedUnverifiable) {
161
+ // Cannot ask the overlay at all while offline. Same refusal as the
162
+ // BSV-rail check below, and the same escape hatch: the caller shows
163
+ // the destructive confirm and retries with `acknowledgedUnverifiable`.
164
+ return 'unverifiable-offline'
150
165
  }
151
166
  }
152
167
 
@@ -173,6 +188,18 @@ export async function cancelParkedPayment(args: {
173
188
  const r = await wallet.abortAction({ reference: tx.reference }, originator)
174
189
  if (r && r.aborted === false) throw new Error('the wallet refused to cancel this payment')
175
190
 
191
+ // The money never moved: say so in the journal, after the abort landed (a
192
+ // row journaled cancelled over a live reservation would hide a payment the
193
+ // payer still has to cancel). A journal fault here does not undo the abort,
194
+ // so it is logged, not thrown.
195
+ if (settlement && row) {
196
+ try {
197
+ await settlement.journal.advance(txid, PAYER_STATES, 'cancelled')
198
+ } catch (e) {
199
+ devLog(`[cancelParkedPayment] could not journal ${txid} as cancelled:`, e)
200
+ }
201
+ }
202
+
176
203
  // Only after the abort landed: a retained parked row is recoverable, a
177
204
  // retired row over a live reservation is not.
178
205
  await updateOfflineAction(db as never, txid, { status: 'acknowledged' })
@@ -244,27 +271,17 @@ async function isOnline(deps: CancelParkedSettlementDeps): Promise<boolean> {
244
271
  }
245
272
 
246
273
  /**
247
- * Only a 200/admitted refuses the cancel outright, and only a definite
248
- * non-admission — `undefined` (a 404 for a txid the overlay has never seen,
249
- * or a mismatched/unverifiable answer, per FIX H) or a terminal `refused`/
250
- * `evicted` — leaves the decision to the local check safely: the overlay
251
- * affirmatively said this payment was never admitted, so cancelling it cannot
252
- * double-spend anyone.
253
- *
254
274
  * XR-100: "the overlay could not be asked" is a THIRD answer, not a synonym
255
- * for either of those. The real runtime's `fetchAdmission` already returns a
256
- * distinct `{ kind: 'unavailable' }` verdict for an unreachable overlay
257
- * rather than throwing (`createRuntime.ts`) — the try/catch here exists only
258
- * for a caller/dependency that fails outright, and folds that failure into
259
- * the SAME `unavailable` verdict rather than swallowing it into `undefined`,
260
- * so `cancelParkedPayment` cannot mistake "could not ask" for "asked, and the
261
- * answer was no".
275
+ * for "not admitted". The runtime's `isHandoverAdmitted` already answers
276
+ * `undefined` for an unreachable overlay; a probe that throws outright is
277
+ * folded into the same `undefined`, so `cancelParkedPayment` cannot mistake
278
+ * "could not ask" for "asked, and the answer was no".
262
279
  */
263
- async function fetchAdmissionSafely(deps: CancelParkedSettlementDeps, overlayUrl: string, txid: string) {
280
+ async function isHandoverAdmittedSafely(deps: CancelParkedSettlementDeps, txid: string): Promise<boolean | undefined> {
264
281
  try {
265
- return await deps.fetchAdmission(overlayUrl, txid)
282
+ return await deps.isHandoverAdmitted(txid)
266
283
  } catch (e) {
267
- devLog(`[cancelParkedPayment] could not reach ${overlayUrl} for ${txid}:`, e)
268
- return { kind: 'unavailable', code: 'ERR_LOCAL_FETCH_FAILED', retryable: true } as const
284
+ devLog(`[cancelParkedPayment] could not ask the overlay about ${txid}:`, e)
285
+ return undefined
269
286
  }
270
287
  }