@bsv/expo-wallet-toolbox 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +292 -0
- package/README.md +0 -1
- package/assets/sounds/vault-deposit.wav +0 -0
- package/assets/sounds/vault-withdraw.wav +0 -0
- package/core/config.tsx +9 -1
- package/core/context/VaultContext.tsx +8 -11
- package/core/context/WalletConnectionContext.tsx +137 -52
- package/core/context/WalletContext.tsx +409 -20
- package/core/hooks/useConfirmationSound.ts +14 -8
- package/core/i18n/translations.tsx +3368 -952
- package/core/index.ts +97 -14
- package/core/localpay/build.ts +674 -37
- package/core/localpay/codec.ts +68 -5
- package/core/localpay/pending.ts +240 -22
- package/core/localpay/settlementAck.ts +149 -0
- package/core/localpay/types.ts +14 -1
- package/core/localpay/verify.ts +118 -69
- package/core/mandala/abortGuard.ts +134 -0
- package/core/mandala/basketMigration.ts +166 -0
- package/core/mandala/bundle.ts +244 -0
- package/core/mandala/createRuntime.ts +2437 -0
- package/core/mandala/drain.ts +670 -0
- package/core/mandala/permissionModule.ts +642 -0
- package/core/mandala/resendTransfer.ts +175 -0
- package/core/mandala/runtime.ts +357 -0
- package/core/mandala/settlementStore.ts +412 -0
- package/core/mandala/types.ts +290 -0
- package/core/offline/cancelParked.ts +94 -1
- package/core/offline/payerHold.ts +152 -12
- package/core/offline/tokenFrames.ts +197 -0
- package/core/parsePeerPayURI.ts +70 -17
- package/core/pay/rails/address.ts +51 -3
- package/core/pay/rails/handle.ts +88 -9
- package/core/pay/rails/index.ts +16 -6
- package/core/pay/rails/nearby.ts +114 -4
- package/core/services/capWalletArgs.ts +8 -9
- package/core/services/externalOrigin.ts +39 -0
- package/core/services/vault/VaultKeyService.ts +912 -251
- package/core/services/vault/ceremony.ts +435 -367
- package/core/services/vault/ceremonyHost.ts +27 -21
- package/core/services/vault/devMock.ts +30 -7
- package/core/services/vault/driver.ts +95 -41
- package/core/services/vault/guard.ts +514 -56
- package/core/services/vault/hardwareLease.ts +22 -0
- package/core/services/vault/mockYubiKey.ts +258 -90
- package/core/services/vault/pivReset.ts +145 -0
- package/core/services/vault/r1comb.ts +976 -0
- package/core/services/vault/session.ts +93 -26
- package/core/services/vault/transfers.ts +2617 -747
- package/core/services/vault/types.ts +100 -43
- package/core/services/vault/vaultStore.ts +991 -74
- package/core/services/walletConnectionValidation.ts +293 -0
- package/core/storage/StorageExpoSQLite.ts +382 -56
- package/core/storage/dbImage.ts +48 -0
- package/core/storage/methods/findSql.ts +0 -54
- package/core/storage/methods/listOutputsSql.ts +7 -3
- package/core/storage/methods/offlineActions.ts +15 -0
- package/core/storage/methods/processOfflineActions.ts +263 -6
- package/core/storage/methods/walletBalanceSql.ts +16 -4
- package/core/storage/schema/createTables.ts +123 -0
- package/core/storage/sqlUpdateValue.ts +24 -0
- package/core/toolboxConfig.ts +112 -1
- package/core/walletRepair/runWalletCheck.ts +19 -2
- package/package.json +25 -24
- package/ui/components/QRScanner.tsx +1 -1
- package/ui/components/pay/AdmissionNotice.tsx +99 -0
- package/ui/components/pay/AssetPicker.tsx +184 -0
- package/ui/components/pay/AvailableBalance.tsx +33 -2
- package/ui/components/pay/HandleReceive.tsx +213 -50
- package/ui/components/pay/NearbyFlow.tsx +616 -69
- package/ui/components/pay/PayForm.tsx +73 -8
- package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
- package/ui/components/pay/RecipientField.tsx +49 -4
- package/ui/components/pay/RequestHub.tsx +68 -8
- package/ui/components/pay/ResultBanner.tsx +41 -4
- package/ui/components/pay/UniversalSend.tsx +534 -30
- package/ui/components/pay/tokenSendCopy.ts +116 -0
- package/ui/components/pay/useRecipientInput.ts +36 -7
- package/ui/components/ui/PermissionSheet.tsx +65 -4
- package/ui/components/ui/Sheet.tsx +9 -2
- package/ui/components/vault/EnrollWizard.tsx +1432 -488
- package/ui/components/vault/KeyChooser.tsx +96 -0
- package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
- package/ui/components/vault/vaultErrorCopy.ts +145 -0
- package/ui/components/wallet/ActivityRow.tsx +101 -17
- package/ui/components/wallet/AmountInput.tsx +77 -25
- package/ui/components/wallet/AssetAmount.tsx +95 -0
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
- package/ui/components/wallet/tokenEviction.ts +65 -0
- package/ui/hooks/useExportWalletData.ts +39 -0
- package/ui/hooks/useMandala.ts +303 -0
- package/ui/hooks/useVaultBalance.ts +105 -7
- package/ui/hooks/useVaultCoverage.ts +52 -0
- package/ui/importDatabases.ts +7 -3
- package/ui/index.ts +50 -7
- package/ui/screens/ConnectionsScreen.tsx +46 -29
- package/ui/screens/PairScreen.tsx +12 -12
- package/ui/screens/PayScreen.tsx +130 -10
- package/ui/screens/SettingsScreen.tsx +18 -9
- package/ui/screens/VaultScreen.tsx +925 -171
- package/ui/screens/VaultTransferScreen.tsx +376 -123
- package/ui/screens/WalletCheckScreen.tsx +10 -1
- package/ui/screens/WalletConfigScreen.tsx +38 -16
- package/ui/screens/WalletHomeScreen.tsx +417 -86
- package/ui/screens/homeBadges.ts +9 -1
- package/ui/screens/tokenRowTitle.ts +68 -0
- package/ui/tokenFormat.ts +108 -0
- package/ui/tokenSeen.ts +75 -0
- package/ui/tokenStatus.ts +79 -0
- package/assets/sounds/vault-close.wav +0 -0
- package/assets/sounds/vault-open.wav +0 -0
- package/core/services/vault/k1.ts +0 -75
- package/core/services/vault/sealing.ts +0 -84
- package/core/services/vault/vaultDerivation.ts +0 -152
- package/core/services/vault/vaultPassphrase.ts +0 -287
- package/ui/components/vault/PassphraseField.tsx +0 -306
- package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
- package/ui/screens/VaultRecoverScreen.tsx +0 -226
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared types for Mandala stablecoin settlement in the wallet.
|
|
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.
|
|
9
|
+
*/
|
|
10
|
+
|
|
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'
|
|
22
|
+
|
|
23
|
+
export type TokenSettlementRole = 'sent' | 'received'
|
|
24
|
+
|
|
25
|
+
export interface TokenSettlementRow {
|
|
26
|
+
txid: string
|
|
27
|
+
role: TokenSettlementRole
|
|
28
|
+
assetId: string
|
|
29
|
+
state: TokenSettlementState
|
|
30
|
+
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
|
+
refusedCode?: string
|
|
39
|
+
/**
|
|
40
|
+
* `payloadHash` of the off-chain linkage bytes this device submitted when
|
|
41
|
+
* the overlay returned `refusedCode` (amendment v2.1 §9.1/§9.3). A refusal
|
|
42
|
+
* is keyed by `(txid, payloadHash)`, not by txid alone, so the UI needs this
|
|
43
|
+
* alongside `refusedCode` to say "refused for THIS payload" rather than
|
|
44
|
+
* implying every payload for this txid is dead. Set only alongside
|
|
45
|
+
* `refusedCode`; absent when this device held no linkage bytes to hash.
|
|
46
|
+
*/
|
|
47
|
+
refusedPayloadHash?: string
|
|
48
|
+
poisonedByTxid?: string
|
|
49
|
+
/**
|
|
50
|
+
* The `createAction`/`signAction` **reference** of the wallet action that
|
|
51
|
+
* built this transaction, when this device is the one that built it.
|
|
52
|
+
*
|
|
53
|
+
* Recorded so an `abortAction` can be recognised for what it is. A token
|
|
54
|
+
* payment is signed `noSend` and handed over BEFORE anything is broadcast,
|
|
55
|
+
* so for a window the only thing holding its inputs is a live noSend action
|
|
56
|
+
* — and `abortAction(reference)` releases those inputs as spendable. Once
|
|
57
|
+
* the overlay has admitted the transaction (it broadcasts on admission) that
|
|
58
|
+
* release is a double spend waiting to happen: the next send reuses a coin
|
|
59
|
+
* that is already spent on chain, and the overlay refuses the child with
|
|
60
|
+
* `ERR_INPUT_SPENT`. That is the 2026-09-15 incident, and the reference is
|
|
61
|
+
* what lets `wrapAbortActionForSettlements` refuse the abort instead.
|
|
62
|
+
*
|
|
63
|
+
* Absent for rows this device did not build (every `received` row) and for
|
|
64
|
+
* rows written before the column existed — an unknown reference is never a
|
|
65
|
+
* reason to refuse an abort.
|
|
66
|
+
*/
|
|
67
|
+
reference?: string
|
|
68
|
+
createdAt: string
|
|
69
|
+
updatedAt: string
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** token_admissions — cache of AdmissionEntry values this device has seen. */
|
|
73
|
+
export interface TokenAdmissionRow {
|
|
74
|
+
txid: string
|
|
75
|
+
outputsToAdmit: number[]
|
|
76
|
+
signatureHex: string
|
|
77
|
+
signerKey: string
|
|
78
|
+
source: 'minted' | 'bundle' | 'submitted' | 'fetched'
|
|
79
|
+
obtainedAt: string
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** token_admission_edges — child spends parent:vout (token inputs only). */
|
|
83
|
+
export interface TokenAdmissionEdge {
|
|
84
|
+
childTxid: string
|
|
85
|
+
parentTxid: string
|
|
86
|
+
parentVout: number
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** token_linkage_payloads — off-chain linkage bytes for UNADMITTED chain txs. */
|
|
90
|
+
export interface TokenLinkageRow {
|
|
91
|
+
txid: string
|
|
92
|
+
payloadBytes: Uint8Array
|
|
93
|
+
overlayUrl: string
|
|
94
|
+
overlayIdentityKey: string
|
|
95
|
+
source: 'minted' | 'forwarded'
|
|
96
|
+
createdAt: string
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Wire-contract v2 §2: what the overlay answered for one /submit. */
|
|
100
|
+
export type OverlayVerdict =
|
|
101
|
+
| { kind: 'admitted'; outputsToAdmit: number[]; signatureHex: string; signerKey: string }
|
|
102
|
+
| { kind: 'refused'; code: string; spendTxid?: string } // final (400) — terminal
|
|
103
|
+
| { kind: 'evicted' } // 410 — terminal, inputs restored
|
|
104
|
+
| { kind: 'unavailable'; code: string; retryable: true } // 409 liftable or 503 — retry
|
|
105
|
+
|
|
106
|
+
/** An AdmissionEntry as carried on the wire (frame v4 `admissions[]`). */
|
|
107
|
+
export interface AdmissionEntryWire {
|
|
108
|
+
txid: string
|
|
109
|
+
outputsToAdmit: number[]
|
|
110
|
+
signature: Uint8Array
|
|
111
|
+
signerKey: string
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Result of the pure COVER walk (spec §1.2). mustSubmit is parents-first, tip last. */
|
|
115
|
+
export type CoverResult =
|
|
116
|
+
| { ok: true; mustSubmit: string[] }
|
|
117
|
+
| { ok: false; reason: 'uncovered_ancestor' | 'unsafe_asset' | 'shape' }
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Storage-facing API for the four settlement tables. Implemented in
|
|
121
|
+
* core/mandala/settlementStore.ts over StorageExpoSQLite's connection.
|
|
122
|
+
* Every write is idempotent (INSERT OR IGNORE / keyed UPDATE) — spec FIX G.
|
|
123
|
+
*/
|
|
124
|
+
export interface SettlementStore {
|
|
125
|
+
// token_settlements
|
|
126
|
+
getSettlement(txid: string): Promise<TokenSettlementRow | undefined>
|
|
127
|
+
/**
|
|
128
|
+
* The row whose `reference` is this wallet action's, or undefined.
|
|
129
|
+
*
|
|
130
|
+
* The abort guard's only question, and it is asked on the hot path of every
|
|
131
|
+
* `abortAction` the wallet makes — including plain BSV ones, which have no
|
|
132
|
+
* row at all — so it is one indexed statement rather than a scan.
|
|
133
|
+
*/
|
|
134
|
+
getSettlementByReference(reference: string): Promise<TokenSettlementRow | undefined>
|
|
135
|
+
listSettlements(filter?: { state?: TokenSettlementState[]; role?: TokenSettlementRole }): Promise<TokenSettlementRow[]>
|
|
136
|
+
upsertSettlement(row: Omit<TokenSettlementRow, 'createdAt' | 'updatedAt'> & { createdAt?: string }): Promise<void>
|
|
137
|
+
/** Single-statement state advance; returns false if the row was not in one of `from`. */
|
|
138
|
+
advanceSettlement(txid: string, from: TokenSettlementState[], to: TokenSettlementState, patch?: Partial<TokenSettlementRow>): Promise<boolean>
|
|
139
|
+
// token_admissions
|
|
140
|
+
getAdmission(txid: string): Promise<TokenAdmissionRow | undefined>
|
|
141
|
+
putAdmission(row: TokenAdmissionRow): Promise<void>
|
|
142
|
+
// token_admission_edges
|
|
143
|
+
putEdges(edges: TokenAdmissionEdge[]): Promise<void>
|
|
144
|
+
parentsOf(childTxid: string): Promise<TokenAdmissionEdge[]>
|
|
145
|
+
// token_linkage_payloads
|
|
146
|
+
getLinkage(txid: string): Promise<TokenLinkageRow | undefined>
|
|
147
|
+
putLinkage(row: TokenLinkageRow): Promise<void>
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ──────────────────── the frame, structurally (FIX G supply) ────────────────────
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The token block of a payment frame, as the settlement machinery reads it.
|
|
154
|
+
*
|
|
155
|
+
* Structural rather than an import of `localpay/codec`'s `TokenPayment` on
|
|
156
|
+
* purpose: this file may not depend on the codec (it is the leaf every other
|
|
157
|
+
* module imports), and describing the shape here means the drain, the payer's
|
|
158
|
+
* hold and the receiver's queue all agree on one type without a cycle.
|
|
159
|
+
* `admissions[]` is optional so a v3 frame — linkage and edges only — still
|
|
160
|
+
* type-checks through the same path.
|
|
161
|
+
*/
|
|
162
|
+
export interface EvidenceTokenBlock {
|
|
163
|
+
assetId: string
|
|
164
|
+
overlayUrl: string
|
|
165
|
+
overlayIdentityKey: string
|
|
166
|
+
linkage: readonly { txid: string; payload: Uint8Array }[]
|
|
167
|
+
admissions?: readonly AdmissionEntryWire[]
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Satisfied by `PaymentFrame` from `localpay/codec`. */
|
|
171
|
+
export interface EvidenceFrame {
|
|
172
|
+
kind?: string
|
|
173
|
+
/**
|
|
174
|
+
* Optional here and required on `PaymentFrame`: a settlement row wants it for
|
|
175
|
+
* `counterpartyKey`, but nothing structural depends on its presence, and the
|
|
176
|
+
* drain re-derives rows from frames it has only the token block of.
|
|
177
|
+
*/
|
|
178
|
+
senderIdentityKey?: string
|
|
179
|
+
/**
|
|
180
|
+
* Which output of the atomic transaction is the payee's. Present on every
|
|
181
|
+
* `PaymentFrame`; optional here because the drain re-derives rows from frames
|
|
182
|
+
* it has only the token block of. Read as 0 when absent — the nearby build
|
|
183
|
+
* never randomises outputs, so the payee's is always the first.
|
|
184
|
+
*/
|
|
185
|
+
outputIndex?: number
|
|
186
|
+
token?: EvidenceTokenBlock
|
|
187
|
+
/** AtomicBEEF. The only place the edge graph can come from, offline. */
|
|
188
|
+
transaction: Uint8Array
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// ─────────────────────── FIX H: the trust anchor, injected ───────────────────
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Verifies one counterparty-supplied `AdmissionEntry`'s σ_I — cryptographically,
|
|
195
|
+
* against the wallet's OWN CONFIGURED overlay identity key, which the
|
|
196
|
+
* implementation closes over.
|
|
197
|
+
*
|
|
198
|
+
* Injected rather than imported because the σ_I digest is the overlay's own and
|
|
199
|
+
* lives in `@bsv/mandala`, so the wallet and the overlay cannot disagree about
|
|
200
|
+
* what is signed. Wire contract §9.10: the expected signer key comes from the
|
|
201
|
+
* verifier's own configuration; an `overlayIdentityKey` that arrived on a frame
|
|
202
|
+
* or sits on a settlement row is DATA and can never be the anchor.
|
|
203
|
+
*
|
|
204
|
+
* Returns a plain boolean for every failure there is — a malformed signature, a
|
|
205
|
+
* foreign key, an empty admitted set — because FIX H treats an unverifiable σ_I
|
|
206
|
+
* as ABSENT, never as a decline.
|
|
207
|
+
*/
|
|
208
|
+
export type AdmissionVerifier = (entry: AdmissionEntryWire) => boolean | Promise<boolean>
|
|
209
|
+
|
|
210
|
+
// ───────────────────────── settlement-durability hooks ─────────────────────────
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* RECEIVER, called BEFORE `wallet.internalizeAction` (§4.2, §4.3 guard #2).
|
|
214
|
+
*
|
|
215
|
+
* Writes the `token_settlements` row (state `'held'`) and the frame's evidence.
|
|
216
|
+
* It has to run first because the guard that stops an unadmitted token
|
|
217
|
+
* broadcast — `attemptToPostReqsToNetwork`'s `token_settlements` lookup — reads
|
|
218
|
+
* that row, and `internalizeAction` triggers a forced broadcast of its own. A
|
|
219
|
+
* row written only AFTER the credit fails open on the very first internalize,
|
|
220
|
+
* which is the one moment it matters.
|
|
221
|
+
*
|
|
222
|
+
* A throw therefore means "do not credit yet": the frame is already durable in
|
|
223
|
+
* `localpay_pending`, so the next tick retries the whole step.
|
|
224
|
+
*/
|
|
225
|
+
export type TokenHeldHook = (frame: EvidenceFrame, txid: string) => Promise<void>
|
|
226
|
+
|
|
227
|
+
/** Which side of the payer's own fork a hand-over landed on. */
|
|
228
|
+
export type TokenHandoverState = 'parked' | 'handed_over'
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* PAYER, called at park/hold time with the PLAINTEXT frame.
|
|
232
|
+
*
|
|
233
|
+
* `offline_actions.framePayload` holds the frame SEALED with the nearby
|
|
234
|
+
* session's pre-shared key, and that key is in-memory only — so a payer that
|
|
235
|
+
* restarts can no longer open its own frame, and a settlement row derived only
|
|
236
|
+
* from it would never exist. This hook is handed the frame while it is still
|
|
237
|
+
* open, so the row and the evidence are durable independently of the PSK.
|
|
238
|
+
*
|
|
239
|
+
* Best-effort at the call site: the queue row is written first and is the
|
|
240
|
+
* durable fact.
|
|
241
|
+
*/
|
|
242
|
+
export type TokenHandedOverHook = (
|
|
243
|
+
frame: EvidenceFrame,
|
|
244
|
+
txid: string,
|
|
245
|
+
state: TokenHandoverState,
|
|
246
|
+
/**
|
|
247
|
+
* The `createAction` reference of the action that built `txid`, when the
|
|
248
|
+
* caller still holds it. Recorded on the row so an abort of that action can
|
|
249
|
+
* be refused once the overlay has the bytes — see `TokenSettlementRow.reference`.
|
|
250
|
+
* Optional: a caller that does not have one simply leaves the column null,
|
|
251
|
+
* which reads as "unknown reference" and blocks nothing.
|
|
252
|
+
*/
|
|
253
|
+
reference?: string
|
|
254
|
+
) => Promise<void>
|
|
255
|
+
|
|
256
|
+
/** Injected by the drain: run COVER for a tip against local evidence. */
|
|
257
|
+
export type CoverFn = (tipTxid: string) => Promise<CoverResult>
|
|
258
|
+
/** Injected by the drain: POST /submit for one txid (beef + linkage resolved from local tables). */
|
|
259
|
+
export type SubmitFn = (txid: string) => Promise<OverlayVerdict>
|
|
260
|
+
/** Injected: GET /admin/admission/:txid (undefined = 404 / unknown). */
|
|
261
|
+
export type FetchAdmissionFn = (overlayUrl: string, txid: string) => Promise<OverlayVerdict | undefined>
|
|
262
|
+
|
|
263
|
+
/** FIX M: a non-terminal row older than this is surfaced as "stuck". */
|
|
264
|
+
export const STUCK_AFTER_MS = 3 * 24 * 60 * 60 * 1000
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* The basket Mandala token outputs (and change) live in. Deliberately
|
|
268
|
+
* `'p '`-prefixed (BRC-99 P-basket) so `WalletPermissionsManager` routes every
|
|
269
|
+
* `listOutputs`/`createAction`(basket output)/`internalizeAction`(basket
|
|
270
|
+
* insertion)/`relinquishOutput` call against it through
|
|
271
|
+
* `MandalaTokenModule` (schemeID 'mandala' = `'p mandala'.split(' ')[1]`),
|
|
272
|
+
* regardless of originator. A flat, single basket for every asset -- unlike
|
|
273
|
+
* BTMS's per-asset `'p btms <assetId>'` baskets, Mandala keeps one cardinality
|
|
274
|
+
* for the whole scheme. Was `'mandala-tokens'` (not P-routed, no gate at all);
|
|
275
|
+
* see core/mandala/basketMigration.ts for the one-time rename and
|
|
276
|
+
* offline-settlement-final.md §8 for the rationale.
|
|
277
|
+
*/
|
|
278
|
+
export const MANDALA_BASKET = 'p mandala'
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* The action label every token transfer carries, on every rail.
|
|
282
|
+
*
|
|
283
|
+
* `@bsv/mandala`'s own `transferTokens` / `receiveTokens` write it, and the
|
|
284
|
+
* home screen recognises a token row by it ALONE — by label, not by holdings,
|
|
285
|
+
* so a user who sends their last coin keeps the denomination across their
|
|
286
|
+
* history. The nearby rail's token actions have to write the same label, or
|
|
287
|
+
* they render as BSV rows: the counterparty's abbreviated key over "+0 sats"
|
|
288
|
+
* (2026-09-16).
|
|
289
|
+
*/
|
|
290
|
+
export const MANDALA_ACTION_LABEL = 'mandala'
|
|
@@ -14,6 +14,10 @@
|
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
16
|
import { updateOfflineAction } from '../storage/methods/offlineActions'
|
|
17
|
+
import { devLog } from '../logging'
|
|
18
|
+
import { getOnline } from '../net/online'
|
|
19
|
+
import type { FetchAdmissionFn, SettlementStore } from '../mandala/types'
|
|
20
|
+
import type { MandalaRuntime } from '../mandala/runtime'
|
|
17
21
|
|
|
18
22
|
const CANCELLABLE = new Set(['nosend', 'unsigned', 'unprocessed'])
|
|
19
23
|
|
|
@@ -31,18 +35,78 @@ export interface CancelParkedWallet {
|
|
|
31
35
|
abortAction(args: { reference: string }, originator?: string): Promise<{ aborted?: boolean } | void>
|
|
32
36
|
}
|
|
33
37
|
|
|
38
|
+
/**
|
|
39
|
+
* FIX J: what makes a cancel overlay-authoritative for a token payment.
|
|
40
|
+
*
|
|
41
|
+
* Omit it entirely — every BSV caller does — and the cancel behaves exactly as
|
|
42
|
+
* it always has. There is deliberately no "cancel by respend" path:
|
|
43
|
+
* `token_settlements` has no `cancelling` state, so the only exits from
|
|
44
|
+
* `handed_over`/`held` are the overlay's own eventual terminal verdict or this
|
|
45
|
+
* check of a payment it never admitted.
|
|
46
|
+
*/
|
|
47
|
+
export interface CancelParkedSettlementDeps {
|
|
48
|
+
settlements: Pick<SettlementStore, 'getSettlement'>
|
|
49
|
+
/**
|
|
50
|
+
* GET /admin/admission/:txid.
|
|
51
|
+
*
|
|
52
|
+
* The URL this is called with is ADVISORY. The row's `overlayUrl` is
|
|
53
|
+
* re-derived from frames a counterparty wrote, so the runtime's
|
|
54
|
+
* implementation pins every request to its own configured overlay and
|
|
55
|
+
* verifies the answer against its own configured key (§9.10) — which is what
|
|
56
|
+
* stops a payer naming a server that would happily "admit" their own
|
|
57
|
+
* payment and talk this cancel out of releasing the coins.
|
|
58
|
+
*/
|
|
59
|
+
fetchAdmission: FetchAdmissionFn
|
|
60
|
+
/** Offline there is nothing to poll, so the local check stands alone. */
|
|
61
|
+
isOnline: () => Promise<boolean>
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Assembles `CancelParkedSettlementDeps` from the Mandala runtime, for a
|
|
66
|
+
* cancel call site: `mandala.store` already satisfies the read-only
|
|
67
|
+
* `settlements` slice, and `mandala.fetchAdmission` is FIX-H-verified and
|
|
68
|
+
* scoped to this session's overlay identity key. Returns `undefined` when
|
|
69
|
+
* Mandala is unavailable — passing that straight through as `settlement`
|
|
70
|
+
* leaves `cancelParkedPayment` exactly as it behaves for a plain BSV payment
|
|
71
|
+
* (the local `nosend` check stands alone).
|
|
72
|
+
*/
|
|
73
|
+
export function mandalaSettlementDeps(
|
|
74
|
+
mandala: Pick<MandalaRuntime, 'available' | 'store' | 'fetchAdmission'> | undefined,
|
|
75
|
+
isOnline: () => Promise<boolean> = getOnline
|
|
76
|
+
): CancelParkedSettlementDeps | undefined {
|
|
77
|
+
if (!mandala?.available) return undefined
|
|
78
|
+
return { settlements: mandala.store, fetchAdmission: mandala.fetchAdmission, isOnline }
|
|
79
|
+
}
|
|
80
|
+
|
|
34
81
|
export async function cancelParkedPayment(args: {
|
|
35
82
|
storage: CancelParkedStorage
|
|
36
83
|
wallet: CancelParkedWallet
|
|
37
84
|
originator?: string
|
|
38
85
|
txid: string
|
|
86
|
+
/** Token settlement. Absent for a plain BSV payment. */
|
|
87
|
+
settlement?: CancelParkedSettlementDeps
|
|
39
88
|
}): Promise<CancelParkedOutcome> {
|
|
40
|
-
const { storage, wallet, originator, txid } = args
|
|
89
|
+
const { storage, wallet, originator, txid, settlement } = args
|
|
41
90
|
const db = storage.sqliteDb
|
|
42
91
|
if (!db) throw new Error('the database is not open, cannot cancel this payment')
|
|
43
92
|
|
|
44
93
|
const tx = (await storage.findTransactions({ partial: { txid }, noRawTx: true }))[0]
|
|
45
94
|
if (!tx) return 'not-found'
|
|
95
|
+
|
|
96
|
+
// FIX J. Locally this transaction still looks cancellable — it is `nosend`
|
|
97
|
+
// and its inputs are still reserved — but for a token payment the overlay,
|
|
98
|
+
// not this device, decides. The counterparty's own submit may already have
|
|
99
|
+
// landed (rule 3: the RECIPIENT settles the hop), in which case aborting
|
|
100
|
+
// would release inputs the overlay has already marked spent and hand the
|
|
101
|
+
// payer a double-spend against the person they just paid.
|
|
102
|
+
if (settlement && (await isOnline(settlement))) {
|
|
103
|
+
const row = await settlement.settlements.getSettlement(txid)
|
|
104
|
+
if (row) {
|
|
105
|
+
const verdict = await fetchAdmissionSafely(settlement, row.overlayUrl, txid)
|
|
106
|
+
if (verdict?.kind === 'admitted') return 'already-sent'
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
46
110
|
if (!tx.status || !CANCELLABLE.has(tx.status)) return 'already-sent'
|
|
47
111
|
if (!tx.reference) return 'not-found'
|
|
48
112
|
|
|
@@ -54,3 +118,32 @@ export async function cancelParkedPayment(args: {
|
|
|
54
118
|
await updateOfflineAction(db as never, txid, { status: 'acknowledged' })
|
|
55
119
|
return 'cancelled'
|
|
56
120
|
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* A probe that throws must not strand the user on a screen they cannot leave.
|
|
124
|
+
* Treating the failure as offline falls back to the local `nosend` check, which
|
|
125
|
+
* is the behaviour every build before this feature had.
|
|
126
|
+
*/
|
|
127
|
+
async function isOnline(deps: CancelParkedSettlementDeps): Promise<boolean> {
|
|
128
|
+
try {
|
|
129
|
+
return await deps.isOnline()
|
|
130
|
+
} catch (e) {
|
|
131
|
+
devLog('[cancelParkedPayment] connectivity probe failed, treating as offline:', e)
|
|
132
|
+
return false
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Only a 200/admitted refuses the cancel. Anything else — a 404 for a txid the
|
|
138
|
+
* overlay has never seen, a persisted refusal, an unreachable overlay — leaves
|
|
139
|
+
* the decision to the local check: the payment was not admitted, so cancelling
|
|
140
|
+
* it cannot double-spend anyone.
|
|
141
|
+
*/
|
|
142
|
+
async function fetchAdmissionSafely(deps: CancelParkedSettlementDeps, overlayUrl: string, txid: string) {
|
|
143
|
+
try {
|
|
144
|
+
return await deps.fetchAdmission(overlayUrl, txid)
|
|
145
|
+
} catch (e) {
|
|
146
|
+
devLog(`[cancelParkedPayment] could not reach ${overlayUrl} for ${txid}, falling back to the local check:`, e)
|
|
147
|
+
return undefined
|
|
148
|
+
}
|
|
149
|
+
}
|
|
@@ -52,16 +52,110 @@
|
|
|
52
52
|
* shares nothing. What genuinely is shared — the `offline_actions` insert — is
|
|
53
53
|
* reused directly via `insertOfflineAction`.
|
|
54
54
|
*/
|
|
55
|
-
import { insertOfflineAction, updateOfflineAction } from '../storage/methods/offlineActions'
|
|
55
|
+
import { findOfflineActionByTxid, insertOfflineAction, updateOfflineAction } from '../storage/methods/offlineActions'
|
|
56
56
|
import { TaskSendOffline } from '../monitor/TaskSendOffline'
|
|
57
|
+
import { devLog } from '../logging'
|
|
58
|
+
import { createSettlementStore, type SettlementDb } from '../mandala/settlementStore'
|
|
59
|
+
import type { EvidenceFrame, TokenHandedOverHook } from '../mandala/types'
|
|
57
60
|
import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
|
|
58
61
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
62
|
+
/**
|
|
63
|
+
* The PLAINTEXT frame and the hook that persists what it carries.
|
|
64
|
+
*
|
|
65
|
+
* `framePayload` is the frame SEALED with the nearby session's pre-shared key,
|
|
66
|
+
* and `offline/tokenFrames.ts` keeps that key IN MEMORY ONLY, deliberately — a
|
|
67
|
+
* durable copy of the key that opens every stored frame is exactly what nobody
|
|
68
|
+
* wants on disk. The consequence, until now, was that the payer's own
|
|
69
|
+
* `token_settlements` row existed only as a re-derivation from bytes it could
|
|
70
|
+
* no longer open after a restart: no row, and `processOfflineActions` reads the
|
|
71
|
+
* absence as "this is an ordinary BSV transaction" and broadcasts an unadmitted
|
|
72
|
+
* token tip.
|
|
73
|
+
*
|
|
74
|
+
* So the frame is handed over here, while it is still open, and the row plus
|
|
75
|
+
* its evidence are written from it. `tokenFrames.ts` stays exactly as it was —
|
|
76
|
+
* a best-effort fallback for the rows this process still holds a key for.
|
|
77
|
+
*/
|
|
78
|
+
export interface TokenHandoverDeps {
|
|
79
|
+
/** The open frame this hand-over is for. Absent on the BSV rail. */
|
|
80
|
+
frame?: EvidenceFrame
|
|
81
|
+
/** Implemented by the Mandala runtime; writes the row and the evidence. */
|
|
82
|
+
onTokenHandedOver?: TokenHandedOverHook
|
|
83
|
+
/**
|
|
84
|
+
* The `createAction` reference of the action that built this tip
|
|
85
|
+
* (`BuiltPayment.reference`), recorded on the settlement row so an
|
|
86
|
+
* `abortAction` against it can be refused once the payee holds the frame.
|
|
87
|
+
* See `core/mandala/abortGuard.ts` — a token action stays `noSend` until the
|
|
88
|
+
* drain broadcasts it, so its reference is the one handle anything has on
|
|
89
|
+
* money that is already gone.
|
|
90
|
+
*/
|
|
91
|
+
reference?: string
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Advance this txid's settlement row `parked → handed_over` (§4.4, FIX F).
|
|
96
|
+
*
|
|
97
|
+
* The queue row's own `parked → queued` advance has a settlement twin, and it
|
|
98
|
+
* has to be issued explicitly for the same reason the queue one did:
|
|
99
|
+
* `upsertSettlement` never writes `state` on conflict (rule 1 in
|
|
100
|
+
* `settlementStore.ts`), so a hook re-running over an existing `parked` row
|
|
101
|
+
* leaves it `parked` — and `parked` is the one non-terminal state the drain
|
|
102
|
+
* refuses to submit, by design (FIX F). Without this the payer's optional
|
|
103
|
+
* submit (rule 6) could never start for a payment that was parked first.
|
|
104
|
+
*
|
|
105
|
+
* Best-effort, and it runs AFTER the queue row: the queue row is the durable
|
|
106
|
+
* fact, a settlement row is a re-derivable cache (FIX G), and the drain's own
|
|
107
|
+
* `reconcileSettlements` pass re-runs this population every tick. A wallet on a
|
|
108
|
+
* schema without these tables simply logs.
|
|
109
|
+
*/
|
|
110
|
+
async function advanceToHandedOver(storage: StorageExpoSQLite, txid: string): Promise<void> {
|
|
111
|
+
const db = storage.sqliteDb
|
|
112
|
+
if (!db) return
|
|
113
|
+
try {
|
|
114
|
+
await createSettlementStore(db as unknown as SettlementDb).advanceSettlement(txid, ['parked'], 'handed_over')
|
|
115
|
+
} catch (e) {
|
|
116
|
+
devLog(`[payerHold] could not advance the settlement row for ${txid} to handed_over:`, e)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Persist what the plaintext frame carries, for the state this call just put
|
|
122
|
+
* the payment in. Never throws: the queue row is already durable by the time
|
|
123
|
+
* this runs, and a payment that IS queued must not be reported as un-queued
|
|
124
|
+
* because a cache write failed.
|
|
125
|
+
*/
|
|
126
|
+
async function journalHandover(
|
|
127
|
+
deps: TokenHandoverDeps,
|
|
128
|
+
txid: string,
|
|
129
|
+
state: 'parked' | 'handed_over'
|
|
130
|
+
): Promise<void> {
|
|
131
|
+
if (!deps.frame?.token || !deps.onTokenHandedOver) return
|
|
132
|
+
try {
|
|
133
|
+
await deps.onTokenHandedOver(deps.frame, txid, state, deps.reference)
|
|
134
|
+
} catch (e) {
|
|
135
|
+
devLog(`[payerHold] could not journal the ${state} settlement for ${txid}:`, e)
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Statuses a second confirm may advance to 'queued'.
|
|
141
|
+
*
|
|
142
|
+
* 'parked' is the case FIX F names: the payer showed the code, walked away,
|
|
143
|
+
* came back and confirmed. 'queued' is included because re-confirming an
|
|
144
|
+
* already-queued payment must be a harmless no-op rather than a refusal.
|
|
145
|
+
* Everything past them — 'sent', 'rejected', 'acknowledged' — is a decided
|
|
146
|
+
* payment, and dragging one back to 'queued' would re-broadcast a transaction
|
|
147
|
+
* the wallet has already failed or cancelled.
|
|
148
|
+
*/
|
|
149
|
+
const ADVANCEABLE_TO_QUEUED = new Set(['parked', 'queued'])
|
|
150
|
+
|
|
151
|
+
export async function holdSentPaymentOffline(
|
|
152
|
+
args: TokenHandoverDeps & {
|
|
153
|
+
storage: StorageExpoSQLite
|
|
154
|
+
txid: string
|
|
155
|
+
/** The full bsvpayf1: QR string, persisted so the code can be re-shown later. */
|
|
156
|
+
framePayload?: string
|
|
157
|
+
}
|
|
158
|
+
): Promise<void> {
|
|
65
159
|
const { storage, txid, framePayload } = args
|
|
66
160
|
const db = storage.sqliteDb
|
|
67
161
|
if (!db) throw new Error('the database is not open, cannot queue this payment for release')
|
|
@@ -80,9 +174,42 @@ export async function holdSentPaymentOffline(args: {
|
|
|
80
174
|
const tx = (await storage.findTransactions({ partial: { txid }, noRawTx: true }))[0]
|
|
81
175
|
if (!tx) throw new Error(`no transaction record for ${txid}, cannot queue it for release`)
|
|
82
176
|
|
|
177
|
+
// FIX F, part 1. `insertOfflineAction` is INSERT OR IGNORE on a UNIQUE txid:
|
|
178
|
+
// with a row already present it proves re-insert idempotency only, never a
|
|
179
|
+
// state advance. So a payer who parked, walked away, came back and confirmed
|
|
180
|
+
// had the insert silently ignored — the row stayed 'parked' forever while
|
|
181
|
+
// the promotion below still moved the transaction past 'nosend', leaving the
|
|
182
|
+
// payment neither drainable ('queued'/'posting' are all the drain reads) nor
|
|
183
|
+
// cancellable (`cancelParkedPayment` refuses anything past 'nosend'). An
|
|
184
|
+
// existing row is therefore ADVANCED rather than re-inserted.
|
|
185
|
+
const existing = await findOfflineActionByTxid(db, txid)
|
|
186
|
+
if (existing) {
|
|
187
|
+
if (!ADVANCEABLE_TO_QUEUED.has(existing.status)) {
|
|
188
|
+
// A decided payment. Neither the queue row nor the transaction may move.
|
|
189
|
+
devLog(`[holdSentPaymentOffline] ${txid} is already '${existing.status}', leaving it alone`)
|
|
190
|
+
return
|
|
191
|
+
}
|
|
192
|
+
// Same two writes and the same order as the insert path: the durable row
|
|
193
|
+
// first, the promotion after.
|
|
194
|
+
await updateOfflineAction(db, txid, { status: 'queued' })
|
|
195
|
+
TaskSendOffline.noteEnqueued()
|
|
196
|
+
await journalHandover(args, txid, 'handed_over')
|
|
197
|
+
await advanceToHandedOver(storage, txid)
|
|
198
|
+
// Only while still withheld: if the payee already broadcast and this device
|
|
199
|
+
// saw it, the transaction has moved on and this write would be a lie.
|
|
200
|
+
if (tx.status === 'nosend') await storage.updateTransactionStatus('unproven', tx.transactionId)
|
|
201
|
+
return
|
|
202
|
+
}
|
|
203
|
+
|
|
83
204
|
// Insert before promote — see the ORDER MATTERS note above.
|
|
84
205
|
await insertOfflineAction(db, { userId: tx.userId, txid, role: 'sent', framePayload })
|
|
85
206
|
TaskSendOffline.noteEnqueued()
|
|
207
|
+
// Queue row first, settlement second, for the reason the ORDER MATTERS note
|
|
208
|
+
// gives: the queue row is what the drain finds, and it is durable. The
|
|
209
|
+
// advance is issued even on this path because a row may already exist at
|
|
210
|
+
// `parked` from a park that never got its queue row written.
|
|
211
|
+
await journalHandover(args, txid, 'handed_over')
|
|
212
|
+
await advanceToHandedOver(storage, txid)
|
|
86
213
|
await storage.updateTransactionStatus('unproven', tx.transactionId)
|
|
87
214
|
}
|
|
88
215
|
|
|
@@ -102,11 +229,13 @@ export async function holdSentPaymentOffline(args: {
|
|
|
102
229
|
* their side and this device sees it confirm. If they did not, the payer can
|
|
103
230
|
* cancel and nothing was ever spent.
|
|
104
231
|
*/
|
|
105
|
-
export async function parkSentPaymentOffline(
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
232
|
+
export async function parkSentPaymentOffline(
|
|
233
|
+
args: TokenHandoverDeps & {
|
|
234
|
+
storage: StorageExpoSQLite
|
|
235
|
+
txid: string
|
|
236
|
+
framePayload?: string
|
|
237
|
+
}
|
|
238
|
+
): Promise<void> {
|
|
110
239
|
const { storage, txid, framePayload } = args
|
|
111
240
|
const db = storage.sqliteDb
|
|
112
241
|
if (!db) throw new Error('the database is not open, cannot park this payment')
|
|
@@ -117,6 +246,12 @@ export async function parkSentPaymentOffline(args: {
|
|
|
117
246
|
// No promote, and no TaskSendOffline.noteEnqueued(): both are what turn a
|
|
118
247
|
// stored frame into a broadcast.
|
|
119
248
|
await insertOfflineAction(db, { userId: tx.userId, txid, role: 'sent', framePayload }, 'parked')
|
|
249
|
+
// The row is written at `parked`, which the drain will never submit (FIX F) —
|
|
250
|
+
// but it EXISTS, which is what `processOfflineActions` and
|
|
251
|
+
// `attemptToPostReqsToNetwork` both key their token branch on. That is the
|
|
252
|
+
// durability this call buys and the sealed `framePayload` cannot: after a
|
|
253
|
+
// restart the session PSK is gone and these bytes can no longer be opened.
|
|
254
|
+
await journalHandover(args, txid, 'parked')
|
|
120
255
|
}
|
|
121
256
|
|
|
122
257
|
|
|
@@ -138,6 +273,11 @@ export async function releaseParkedPayment(args: { storage: StorageExpoSQLite; t
|
|
|
138
273
|
|
|
139
274
|
await updateOfflineAction(db, txid, { status: 'queued' })
|
|
140
275
|
TaskSendOffline.noteEnqueued()
|
|
276
|
+
// The settlement twin of the line above (§4.4). No frame is threaded here —
|
|
277
|
+
// this is the re-show-and-confirm path, and the row was already written from
|
|
278
|
+
// the plaintext frame when the payment was parked — so the state advance is
|
|
279
|
+
// the whole of it.
|
|
280
|
+
await advanceToHandedOver(storage, txid)
|
|
141
281
|
// Already promoted if the payee broadcast and this device saw it; the write
|
|
142
282
|
// is only correct while the transaction is still being withheld.
|
|
143
283
|
if (tx.status === 'nosend') await storage.updateTransactionStatus('unproven', tx.transactionId)
|