@bsv/expo-wallet-toolbox 0.4.0 → 0.7.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 (182) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/README.md +19 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/amountFormatHelpers.ts +238 -34
  6. package/core/backup/RemoteSyncReader.ts +2 -5
  7. package/core/backup/codec.ts +2 -2
  8. package/core/backup/push.ts +1 -1
  9. package/core/config.tsx +16 -1
  10. package/core/contacts/contactActivity.ts +153 -0
  11. package/core/contacts/contactCache.ts +41 -0
  12. package/core/contacts/contactsStore.ts +183 -0
  13. package/core/context/VaultContext.tsx +8 -11
  14. package/core/context/WalletConnectionContext.tsx +137 -52
  15. package/core/context/WalletContext.tsx +464 -30
  16. package/core/demo/demoAssets.ts +60 -0
  17. package/core/demo/demoLedger.ts +240 -0
  18. package/core/demo/demoMandalaRuntime.ts +96 -0
  19. package/core/demo/demoMode.ts +38 -0
  20. package/core/demo/demoWallet.ts +25 -0
  21. package/core/demo/index.ts +26 -0
  22. package/core/demo/useDemo.ts +59 -0
  23. package/core/headers/OfflineFirstChaintracks.ts +52 -14
  24. package/core/headers/headerStore.ts +7 -10
  25. package/core/hooks/useConfirmationSound.ts +14 -8
  26. package/core/i18n/translations.tsx +4562 -986
  27. package/core/identity/contactLink.ts +36 -0
  28. package/core/identity/handleRegistry/client.ts +285 -0
  29. package/core/identity/handleRegistry/profileCert.ts +254 -0
  30. package/core/identity/handleRegistry/registration.ts +559 -0
  31. package/core/identity/handleRegistry/resolver.ts +247 -0
  32. package/core/identity/handleRegistry/rules.ts +104 -0
  33. package/core/index.ts +116 -15
  34. package/core/localpay/build.ts +674 -37
  35. package/core/localpay/codec.ts +68 -5
  36. package/core/localpay/pending.ts +240 -22
  37. package/core/localpay/pendingAborts.ts +5 -1
  38. package/core/localpay/settlementAck.ts +149 -0
  39. package/core/localpay/types.ts +14 -1
  40. package/core/localpay/verify.ts +118 -69
  41. package/core/mandala/abortGuard.ts +134 -0
  42. package/core/mandala/basketMigration.ts +166 -0
  43. package/core/mandala/bundle.ts +244 -0
  44. package/core/mandala/createRuntime.ts +2437 -0
  45. package/core/mandala/drain.ts +670 -0
  46. package/core/mandala/permissionModule.ts +642 -0
  47. package/core/mandala/resendTransfer.ts +175 -0
  48. package/core/mandala/runtime.ts +357 -0
  49. package/core/mandala/settlementStore.ts +412 -0
  50. package/core/mandala/types.ts +290 -0
  51. package/core/monitor/MonitorSupervisor.ts +121 -0
  52. package/core/monitor/TaskBackupPush.ts +1 -1
  53. package/core/monitor/TaskCreditInbox.ts +1 -1
  54. package/core/monitor/TaskDrainOutbox.ts +1 -1
  55. package/core/monitor/TaskSendOffline.ts +1 -1
  56. package/core/net/online.ts +49 -0
  57. package/core/numberFormat.ts +19 -0
  58. package/core/offline/cancelParked.ts +94 -1
  59. package/core/offline/payerHold.ts +152 -12
  60. package/core/offline/plan.ts +1 -1
  61. package/core/offline/tokenFrames.ts +197 -0
  62. package/core/parsePeerPayURI.ts +70 -17
  63. package/core/pay/rails/address.ts +51 -3
  64. package/core/pay/rails/handle.ts +88 -9
  65. package/core/pay/rails/index.ts +16 -6
  66. package/core/pay/rails/nearby.ts +114 -4
  67. package/core/pay/recordProof.ts +2 -6
  68. package/core/services/arcadeBroadcastProvider.ts +1 -4
  69. package/core/services/capWalletArgs.ts +8 -9
  70. package/core/services/exchangeRate.ts +1 -1
  71. package/core/services/externalOrigin.ts +42 -0
  72. package/core/services/vault/VaultKeyService.ts +912 -251
  73. package/core/services/vault/ceremony.ts +435 -367
  74. package/core/services/vault/ceremonyHost.ts +27 -21
  75. package/core/services/vault/devMock.ts +30 -7
  76. package/core/services/vault/driver.ts +95 -41
  77. package/core/services/vault/guard.ts +514 -56
  78. package/core/services/vault/hardwareLease.ts +22 -0
  79. package/core/services/vault/mockYubiKey.ts +258 -90
  80. package/core/services/vault/pivReset.ts +145 -0
  81. package/core/services/vault/r1comb.ts +976 -0
  82. package/core/services/vault/session.ts +93 -26
  83. package/core/services/vault/transfers.ts +2617 -747
  84. package/core/services/vault/types.ts +100 -43
  85. package/core/services/vault/vaultStore.ts +991 -74
  86. package/core/services/walletConnectionValidation.ts +293 -0
  87. package/core/services/walletServiceConfig.ts +31 -20
  88. package/core/storage/StorageExpoSQLite.ts +420 -87
  89. package/core/storage/dbImage.ts +48 -0
  90. package/core/storage/methods/findSql.ts +3 -54
  91. package/core/storage/methods/listActionsSql.ts +8 -5
  92. package/core/storage/methods/listOutputsSql.ts +9 -5
  93. package/core/storage/methods/offlineActions.ts +15 -0
  94. package/core/storage/methods/processOfflineActions.ts +265 -9
  95. package/core/storage/methods/reviewStatusSql.ts +7 -2
  96. package/core/storage/methods/walletBalanceSql.ts +16 -4
  97. package/core/storage/schema/createTables.ts +152 -0
  98. package/core/storage/sqlUpdateValue.ts +24 -0
  99. package/core/toolboxConfig.ts +182 -1
  100. package/core/toolboxTypes.ts +40 -0
  101. package/core/userAvatar.ts +79 -0
  102. package/core/walletMonitor.ts +8 -3
  103. package/core/walletRepair/runWalletCheck.ts +19 -2
  104. package/package.json +31 -30
  105. package/ui/activityFilter.ts +115 -0
  106. package/ui/components/QRScanner.tsx +1 -1
  107. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  108. package/ui/components/pay/AssetPicker.tsx +184 -0
  109. package/ui/components/pay/AvailableBalance.tsx +33 -2
  110. package/ui/components/pay/HandleReceive.tsx +213 -50
  111. package/ui/components/pay/NearbyFlow.tsx +616 -69
  112. package/ui/components/pay/PayForm.tsx +73 -8
  113. package/ui/components/pay/PaymentSuccessOverlay.tsx +89 -8
  114. package/ui/components/pay/RecipientField.tsx +132 -73
  115. package/ui/components/pay/RequestHub.tsx +68 -8
  116. package/ui/components/pay/ResultBanner.tsx +41 -4
  117. package/ui/components/pay/StepBar.tsx +32 -0
  118. package/ui/components/pay/UniversalSend.tsx +1118 -86
  119. package/ui/components/pay/tokenSendCopy.ts +116 -0
  120. package/ui/components/pay/useRecipientInput.ts +36 -7
  121. package/ui/components/ui/PencilEditField.tsx +109 -0
  122. package/ui/components/ui/PermissionSheet.tsx +65 -4
  123. package/ui/components/ui/Sheet.tsx +9 -2
  124. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  125. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  126. package/ui/components/vault/KeyChooser.tsx +96 -0
  127. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  128. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  129. package/ui/components/wallet/ActivityRow.tsx +283 -97
  130. package/ui/components/wallet/AmountInput.tsx +92 -28
  131. package/ui/components/wallet/AssetAmount.tsx +95 -0
  132. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  133. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  134. package/ui/components/wallet/ContactSigil.tsx +49 -0
  135. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  136. package/ui/components/wallet/FitAmount.tsx +148 -0
  137. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  138. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  139. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  140. package/ui/components/wallet/ProfileButton.tsx +62 -0
  141. package/ui/components/wallet/UserAvatar.tsx +85 -0
  142. package/ui/components/wallet/avatarIcons.ts +122 -0
  143. package/ui/components/wallet/tokenEviction.ts +65 -0
  144. package/ui/hooks/useContactsStore.ts +10 -0
  145. package/ui/hooks/useExportWalletData.ts +39 -0
  146. package/ui/hooks/useMandala.ts +320 -0
  147. package/ui/hooks/useOnline.ts +65 -20
  148. package/ui/hooks/useVaultBalance.ts +105 -7
  149. package/ui/hooks/useVaultCoverage.ts +52 -0
  150. package/ui/importDatabases.ts +7 -3
  151. package/ui/index.ts +75 -7
  152. package/ui/screens/ConnectionsScreen.tsx +46 -29
  153. package/ui/screens/ContactScreen.tsx +289 -0
  154. package/ui/screens/ContactsScreen.tsx +373 -0
  155. package/ui/screens/IdentifierScreen.tsx +234 -0
  156. package/ui/screens/NewContactScreen.tsx +362 -0
  157. package/ui/screens/PairScreen.tsx +12 -12
  158. package/ui/screens/PayScreen.tsx +145 -12
  159. package/ui/screens/ProfileScreen.tsx +783 -0
  160. package/ui/screens/SettingsScreen.tsx +18 -9
  161. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  162. package/ui/screens/TrustScreen.tsx +1 -1
  163. package/ui/screens/VaultScreen.tsx +925 -171
  164. package/ui/screens/VaultTransferScreen.tsx +376 -123
  165. package/ui/screens/WalletCheckScreen.tsx +10 -1
  166. package/ui/screens/WalletConfigScreen.tsx +80 -16
  167. package/ui/screens/WalletHomeScreen.tsx +915 -139
  168. package/ui/screens/homeBadges.ts +9 -1
  169. package/ui/screens/tokenRowTitle.ts +68 -0
  170. package/ui/tokenFormat.ts +108 -0
  171. package/ui/tokenSeen.ts +75 -0
  172. package/ui/tokenStatus.ts +100 -0
  173. package/ui/txStatus.ts +43 -5
  174. package/assets/sounds/vault-close.wav +0 -0
  175. package/assets/sounds/vault-open.wav +0 -0
  176. package/core/services/vault/k1.ts +0 -75
  177. package/core/services/vault/sealing.ts +0 -84
  178. package/core/services/vault/vaultDerivation.ts +0 -152
  179. package/core/services/vault/vaultPassphrase.ts +0 -287
  180. package/ui/components/vault/PassphraseField.tsx +0 -306
  181. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  182. 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'
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Runs the wallet monitor's pass loop under a watchdog.
3
+ *
4
+ * `Monitor.startTasks()` is `while (running) { await runOnce(); await wait }`.
5
+ * Two things end that loop with no signal to anyone:
6
+ *
7
+ * · a task whose `await` never resolves — runOnce runs tasks sequentially
8
+ * with no per-task timeout, so one hung network or SQLite call parks every
9
+ * other task behind it, TaskSendWaiting included;
10
+ * · `runOnce`'s own catch block calling `logEvent`, which is a SQLite write —
11
+ * if that throws, the error escapes `startTasks` and the loop is gone.
12
+ *
13
+ * Seen 2026-09-18: Clock ticks stopped at 13:29:01 while the app stayed in
14
+ * use; two ordinary BSV sends made minutes later sat at `sending` until the
15
+ * app was force-quit, because nothing but the monitor broadcasts an `unsent`
16
+ * request.
17
+ *
18
+ * So the loop is driven from here instead. Each completed pass stamps
19
+ * `lastPassAt`; the host polls `isStalled` and calls `restart`, which starts a
20
+ * new generation of the loop on the SAME monitor. The old generation, if its
21
+ * hung await ever resolves, sees the generation change and exits rather than
22
+ * running alongside the new one. A pass that throws is logged and does not end
23
+ * the loop.
24
+ *
25
+ * `_tasksRunning` and `_tasksRunningPromise` are kept in step with what
26
+ * `Monitor.startTasks` would have set, because `stopTasks()` clears the first
27
+ * and `stopMonitorAndDrain` awaits the second.
28
+ */
29
+ import type { Monitor } from '@bsv/wallet-toolbox-mobile'
30
+
31
+ /** No completed pass for this long, while the app is active, means the loop is gone. */
32
+ export const MONITOR_STALL_MS = 120_000
33
+
34
+ /** The private loop state the toolbox's own `startTasks` maintains. */
35
+ interface LoopState {
36
+ _tasksRunning: boolean
37
+ _tasksRunningPromise?: Promise<void>
38
+ resolveCompletion?: () => void
39
+ runOnce(): Promise<void>
40
+ options: { taskRunWaitMsecs: number }
41
+ }
42
+
43
+ export class MonitorSupervisor {
44
+ /** When the most recent pass completed (or the loop was started/touched). */
45
+ lastPassAt: number
46
+ /** How many times `restart` has run. Exposed for logging and tests. */
47
+ restarts = 0
48
+ private generation = 0
49
+ private monitor: Monitor | undefined
50
+
51
+ constructor(
52
+ private readonly now: () => number = () => Date.now(),
53
+ private readonly wait: (ms: number) => Promise<void> = ms => new Promise(resolve => setTimeout(resolve, ms)),
54
+ private readonly warn: (message: string, error?: unknown) => void = (m, e) => console.warn(m, e ?? '')
55
+ ) {
56
+ this.lastPassAt = this.now()
57
+ }
58
+
59
+ /** Begin driving `monitor`. Replaces `monitor.startTasks()`; never awaited. */
60
+ start(monitor: Monitor): void {
61
+ this.monitor = monitor
62
+ const state = monitor as unknown as LoopState
63
+ state._tasksRunning = true
64
+ state._tasksRunningPromise = new Promise<void>(resolve => {
65
+ state.resolveCompletion = resolve
66
+ })
67
+ this.lastPassAt = this.now()
68
+ void this.loop(state, ++this.generation)
69
+ }
70
+
71
+ /**
72
+ * Something else proves the loop is not stalled — the app just came back to
73
+ * the foreground and the loop's timers were frozen with it. Resets the clock
74
+ * so the first watchdog check after a resume cannot fire on a gap that was
75
+ * the OS's, not the monitor's.
76
+ */
77
+ touch(): void {
78
+ this.lastPassAt = this.now()
79
+ }
80
+
81
+ isStalled(stallMs: number = MONITOR_STALL_MS): boolean {
82
+ const state = this.monitor as unknown as LoopState | undefined
83
+ if (!state?._tasksRunning) return false
84
+ return this.now() - this.lastPassAt > stallMs
85
+ }
86
+
87
+ /**
88
+ * Start a new generation of the loop on the current monitor. The stalled
89
+ * generation is abandoned: when (if) its await resolves it exits on the
90
+ * generation check. Returns false when there is no running monitor to restart.
91
+ */
92
+ restart(): boolean {
93
+ const state = this.monitor as unknown as LoopState | undefined
94
+ if (!state?._tasksRunning) return false
95
+ this.restarts++
96
+ this.lastPassAt = this.now()
97
+ void this.loop(state, ++this.generation)
98
+ return true
99
+ }
100
+
101
+ private async loop(state: LoopState, generation: number): Promise<void> {
102
+ while (state._tasksRunning && generation === this.generation) {
103
+ try {
104
+ await state.runOnce()
105
+ } catch (e) {
106
+ // The toolbox loop dies here. A failed pass is a failed pass; the next
107
+ // one runs.
108
+ this.warn('[MonitorSupervisor] monitor pass failed', e)
109
+ }
110
+ if (generation !== this.generation) return
111
+ this.lastPassAt = this.now()
112
+ await this.wait(state.options.taskRunWaitMsecs)
113
+ }
114
+ // Only the live generation may report completion: an abandoned one waking
115
+ // up late must not resolve a drain that belongs to its successor.
116
+ if (generation === this.generation && state.resolveCompletion) {
117
+ state.resolveCompletion()
118
+ state.resolveCompletion = undefined
119
+ }
120
+ }
121
+ }
@@ -13,7 +13,7 @@
13
13
  * a pass takes at most one chunk and the interval floor keeps it off the JS thread the rest
14
14
  * of the time.
15
15
  */
16
- import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile/out/src/monitor/tasks/WalletMonitorTask'
16
+ import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile'
17
17
  import type { Monitor } from '@bsv/wallet-toolbox-mobile'
18
18
  import { MIN_PUSH_INTERVAL_MS } from '../backup/constants'
19
19
  import type { PushResult } from '../backup/push'
@@ -11,7 +11,7 @@
11
11
  * and rebuilt on network switches and wallet rebuilds, and a pending inbox
12
12
  * must survive that.
13
13
  */
14
- import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile/out/src/monitor/tasks/WalletMonitorTask'
14
+ import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile'
15
15
  import type { Monitor } from '@bsv/wallet-toolbox-mobile'
16
16
 
17
17
  export interface CreditInboxTaskResult {
@@ -11,7 +11,7 @@
11
11
  * and rebuilt on network switches and wallet rebuilds, and a pending outbox
12
12
  * must survive that.
13
13
  */
14
- import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile/out/src/monitor/tasks/WalletMonitorTask'
14
+ import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile'
15
15
  import type { Monitor } from '@bsv/wallet-toolbox-mobile'
16
16
  import type { OutboxEntry } from '../peerpay/outbox'
17
17
 
@@ -19,7 +19,7 @@
19
19
  * reports online seconds before routes actually work — which is exactly the
20
20
  * "payments sit at nosend forever" bug this rewrite removes.
21
21
  */
22
- import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile/out/src/monitor/tasks/WalletMonitorTask'
22
+ import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile'
23
23
  import type { Monitor } from '@bsv/wallet-toolbox-mobile'
24
24
  import type { ProcessOfflineActionsResult } from '../storage/methods/processOfflineActions'
25
25
 
@@ -14,6 +14,8 @@
14
14
  * retry, a wrong "offline" hides the online rails from someone who has signal.
15
15
  */
16
16
  import NetInfo from '@react-native-community/netinfo'
17
+ import { DEFAULT_MESSAGEBOX_URL } from '../config'
18
+ import { DEFAULT_ARC_URLS } from '../constants'
17
19
 
18
20
  export interface OnlineState {
19
21
  isConnected: boolean | null
@@ -32,3 +34,50 @@ export async function getOnline(): Promise<boolean> {
32
34
  export function subscribeOnline(cb: (online: boolean) => void): () => void {
33
35
  return NetInfo.addEventListener(state => cb(isOnlineState(state)))
34
36
  }
37
+
38
+ /** Longest a live request may take before it counts as "nothing got out". */
39
+ export const PROBE_TIMEOUT_MS = 4000
40
+
41
+ /**
42
+ * Hosts the wallet already talks to, so asking them adds no third party and no
43
+ * new traffic pattern. HTTPS, so a captive portal cannot answer for them.
44
+ */
45
+ const PROBE_URLS = [DEFAULT_ARC_URLS.main, DEFAULT_MESSAGEBOX_URL]
46
+
47
+ /**
48
+ * A live request, for when NetInfo's verdict is offline and something needs to
49
+ * know whether to believe it.
50
+ *
51
+ * That verdict is not a measurement of the moment. On iOS it is a cached
52
+ * reachability snapshot — the OS delivers no callbacks while the app is
53
+ * suspended, and NetInfo's cache is never re-read — plus an HTTP probe of a
54
+ * Google host the wallet has no other use for. Either can say offline for a
55
+ * device whose connection works, and NetInfo will not correct itself until the
56
+ * next network change. This asks the wallet's own hosts instead: any HTTP
57
+ * response, a 404 included, proves DNS, a route and TLS all worked, so one
58
+ * answer from any host is enough. It only ever upgrades a verdict to online,
59
+ * never the reverse.
60
+ */
61
+ export function probeOnline(timeoutMs: number = PROBE_TIMEOUT_MS): Promise<boolean> {
62
+ return new Promise(resolve => {
63
+ const controller = new AbortController()
64
+ let failed = 0
65
+ const finish = (online: boolean) => {
66
+ clearTimeout(timer)
67
+ controller.abort()
68
+ resolve(online)
69
+ }
70
+ const timer = setTimeout(() => finish(false), timeoutMs)
71
+ for (const url of PROBE_URLS) {
72
+ Promise.resolve()
73
+ .then(() => fetch(url, { method: 'HEAD', cache: 'no-store', credentials: 'omit', signal: controller.signal }))
74
+ .then(
75
+ () => finish(true),
76
+ () => {
77
+ failed += 1
78
+ if (failed === PROBE_URLS.length) finish(false)
79
+ }
80
+ )
81
+ }
82
+ })
83
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Which separators money is printed with: always the device's own locale.
3
+ */
4
+
5
+ /** The device's own locale, resolved once. */
6
+ function detectDeviceLocale(): string {
7
+ try {
8
+ return Intl.NumberFormat().resolvedOptions().locale?.split('-u-')[0] || 'en-US'
9
+ } catch {
10
+ return 'en-US'
11
+ }
12
+ }
13
+
14
+ const deviceLocale = detectDeviceLocale()
15
+
16
+ /** The locale every formatter in `amountFormatHelpers` prints through. */
17
+ export function getNumberLocale(): string {
18
+ return deviceLocale
19
+ }
@@ -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
+ }