@bsv/expo-wallet-toolbox 0.5.0 → 0.9.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 (200) hide show
  1. package/CHANGELOG.md +2000 -0
  2. package/README.md +66 -1
  3. package/core/amountFormatHelpers.ts +258 -36
  4. package/core/backup/RemoteSyncReader.ts +133 -24
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +149 -11
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +71 -5
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/config.tsx +12 -5
  15. package/core/constants.ts +14 -1
  16. package/core/contacts/contactActivity.ts +153 -0
  17. package/core/contacts/contactCache.ts +41 -0
  18. package/core/contacts/contactsStore.ts +183 -0
  19. package/core/context/ExchangeRateContext.tsx +34 -27
  20. package/core/context/LocalStorageProvider.tsx +43 -40
  21. package/core/context/UserContext.tsx +18 -7
  22. package/core/context/VaultContext.tsx +49 -2
  23. package/core/context/WalletConnectionContext.tsx +203 -11
  24. package/core/context/WalletContext.tsx +685 -171
  25. package/core/demo/demoAssets.ts +60 -0
  26. package/core/demo/demoLedger.ts +240 -0
  27. package/core/demo/demoMandalaRuntime.ts +96 -0
  28. package/core/demo/demoMode.ts +38 -0
  29. package/core/demo/demoWallet.ts +25 -0
  30. package/core/demo/index.ts +26 -0
  31. package/core/demo/useDemo.ts +59 -0
  32. package/core/headers/OfflineFirstChaintracks.ts +99 -17
  33. package/core/headers/headerStore.ts +33 -14
  34. package/core/headers/syncHeaders.ts +12 -1
  35. package/core/i18n/translations.tsx +2186 -98
  36. package/core/identity/contactLink.ts +36 -0
  37. package/core/identity/handleRegistry/client.ts +314 -0
  38. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  39. package/core/identity/handleRegistry/profileCert.ts +254 -0
  40. package/core/identity/handleRegistry/registration.ts +559 -0
  41. package/core/identity/handleRegistry/resolver.ts +315 -0
  42. package/core/identity/handleRegistry/rules.ts +104 -0
  43. package/core/index.ts +53 -5
  44. package/core/localpay/build.ts +225 -24
  45. package/core/localpay/pending.ts +110 -7
  46. package/core/localpay/pendingAbortAuthority.ts +95 -0
  47. package/core/localpay/pendingAborts.ts +266 -26
  48. package/core/localpay/session.ts +42 -17
  49. package/core/localpay/settlementAck.ts +10 -1
  50. package/core/localpay/transport/socket.ts +52 -3
  51. package/core/localpay/verify.ts +100 -10
  52. package/core/mandala/abortGuard.ts +96 -20
  53. package/core/mandala/createRuntime.ts +206 -33
  54. package/core/mandala/drain.ts +89 -11
  55. package/core/mandala/inboxPrehold.ts +186 -0
  56. package/core/mandala/permissionModule.ts +202 -20
  57. package/core/mandala/settlementStore.ts +24 -2
  58. package/core/mandala/types.ts +40 -5
  59. package/core/monitor/MonitorSupervisor.ts +121 -0
  60. package/core/monitor/TaskBackupPush.ts +15 -1
  61. package/core/monitor/TaskCreditInbox.ts +1 -1
  62. package/core/monitor/TaskDrainOutbox.ts +15 -1
  63. package/core/monitor/TaskSendOffline.ts +15 -1
  64. package/core/net/online.ts +49 -0
  65. package/core/net/publicDestination.ts +91 -0
  66. package/core/net/validateArcUrl.ts +22 -0
  67. package/core/numberFormat.ts +19 -0
  68. package/core/offline/cancelParked.ts +134 -13
  69. package/core/offline/payerHold.ts +100 -24
  70. package/core/offline/plan.ts +37 -8
  71. package/core/pay/beefRepair.ts +6 -2
  72. package/core/pay/damagedInbox.ts +24 -0
  73. package/core/pay/rails/address.ts +107 -12
  74. package/core/pay/rails/handle.ts +117 -22
  75. package/core/pay/rails/index.ts +45 -7
  76. package/core/pay/rails/nativeIntent.ts +61 -0
  77. package/core/pay/receiveHistory.ts +93 -0
  78. package/core/pay/recordProof.ts +21 -7
  79. package/core/pay/refreshProofGuard.ts +42 -1
  80. package/core/pay/watchlist.ts +5 -2
  81. package/core/peerpay/control.ts +17 -18
  82. package/core/peerpay/handleResendRequests.ts +58 -4
  83. package/core/peerpay/outbox.ts +3 -1
  84. package/core/recovery/backupMaterial.ts +61 -0
  85. package/core/recovery/createWallet.ts +95 -0
  86. package/core/recovery/recoverWallet.ts +120 -0
  87. package/core/recovery/restoreWallet.ts +170 -0
  88. package/core/recovery/secret.ts +92 -0
  89. package/core/recovery/shareCollector.ts +71 -0
  90. package/core/recovery/shareParsing.ts +87 -0
  91. package/core/recovery/shares.ts +116 -0
  92. package/core/recovery/useRecoveryDeps.ts +70 -0
  93. package/core/services/arcTokenStorage.ts +52 -0
  94. package/core/services/arcadeBroadcastProvider.ts +233 -52
  95. package/core/services/autoApprovePolicy.ts +105 -0
  96. package/core/services/callbackToken.ts +19 -0
  97. package/core/services/capWalletArgs.ts +14 -2
  98. package/core/services/connectionAuthority.ts +98 -0
  99. package/core/services/exchangeRate.ts +36 -13
  100. package/core/services/externalOrigin.ts +16 -2
  101. package/core/services/secrets/kek.ts +126 -29
  102. package/core/services/secrets/migration.ts +16 -4
  103. package/core/services/secrets/store.ts +42 -14
  104. package/core/services/vault/VaultKeyService.ts +228 -45
  105. package/core/services/vault/chainRecovery.ts +483 -0
  106. package/core/services/vault/driver.ts +9 -1
  107. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  108. package/core/services/vault/guard.ts +218 -32
  109. package/core/services/vault/hardwareLease.ts +19 -0
  110. package/core/services/vault/metaAuthority.ts +210 -0
  111. package/core/services/vault/pivReset.ts +64 -23
  112. package/core/services/vault/r1comb.ts +139 -3
  113. package/core/services/vault/session.ts +25 -4
  114. package/core/services/vault/transfers.ts +868 -172
  115. package/core/services/vault/types.ts +19 -4
  116. package/core/services/vault/vaultStore.ts +256 -29
  117. package/core/services/walletArgLimits.ts +45 -2
  118. package/core/services/walletConnectionValidation.ts +76 -6
  119. package/core/services/walletServiceConfig.ts +40 -27
  120. package/core/storage/StorageExpoSQLite.ts +88 -47
  121. package/core/storage/methods/findSql.ts +24 -2
  122. package/core/storage/methods/listActionsSql.ts +8 -5
  123. package/core/storage/methods/listOutputsSql.ts +2 -2
  124. package/core/storage/methods/offlineActions.ts +10 -1
  125. package/core/storage/methods/processOfflineActions.ts +117 -25
  126. package/core/storage/methods/reviewStatusSql.ts +7 -2
  127. package/core/storage/schema/createTables.ts +155 -2
  128. package/core/stores/ConnectionStore.ts +34 -0
  129. package/core/toolboxConfig.ts +104 -0
  130. package/core/toolboxTypes.ts +40 -0
  131. package/core/userAvatar.ts +79 -0
  132. package/core/walletDbRegistry.ts +63 -0
  133. package/core/walletMonitor.ts +25 -4
  134. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  135. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  136. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  137. package/package.json +7 -7
  138. package/ui/activityFilter.ts +115 -0
  139. package/ui/backupShares.ts +26 -169
  140. package/ui/components/pay/AddressReceive.tsx +13 -6
  141. package/ui/components/pay/AssetPicker.tsx +30 -9
  142. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  143. package/ui/components/pay/NearbyFlow.tsx +480 -243
  144. package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
  145. package/ui/components/pay/RecipientField.tsx +84 -70
  146. package/ui/components/pay/StepBar.tsx +32 -0
  147. package/ui/components/pay/UniversalSend.tsx +827 -205
  148. package/ui/components/ui/AlertCard.tsx +38 -5
  149. package/ui/components/ui/PencilEditField.tsx +109 -0
  150. package/ui/components/ui/PermissionSheet.tsx +197 -66
  151. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  152. package/ui/components/vault/EnrollWizard.tsx +61 -13
  153. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  154. package/ui/components/wallet/ActivityRow.tsx +227 -123
  155. package/ui/components/wallet/AmountInput.tsx +26 -8
  156. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  157. package/ui/components/wallet/Balance.tsx +42 -23
  158. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  159. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  160. package/ui/components/wallet/ContactSigil.tsx +49 -0
  161. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  162. package/ui/components/wallet/FitAmount.tsx +148 -0
  163. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  164. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  165. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  166. package/ui/components/wallet/ProfileButton.tsx +62 -0
  167. package/ui/components/wallet/UserAvatar.tsx +85 -0
  168. package/ui/components/wallet/avatarIcons.ts +122 -0
  169. package/ui/exportTransactions.ts +36 -4
  170. package/ui/hooks/useContactsStore.ts +10 -0
  171. package/ui/hooks/useExportWalletData.ts +25 -2
  172. package/ui/hooks/useMandala.ts +18 -1
  173. package/ui/hooks/useOnline.ts +65 -20
  174. package/ui/importDatabases.ts +339 -24
  175. package/ui/index.ts +33 -2
  176. package/ui/isImageUrl.ts +6 -0
  177. package/ui/printRecoveryShares.ts +9 -10
  178. package/ui/recoveryPrompts.ts +91 -0
  179. package/ui/resolveIdentity.ts +31 -9
  180. package/ui/screens/ConnectionsScreen.tsx +86 -19
  181. package/ui/screens/ContactScreen.tsx +289 -0
  182. package/ui/screens/ContactsScreen.tsx +373 -0
  183. package/ui/screens/IdentifierScreen.tsx +256 -0
  184. package/ui/screens/NewContactScreen.tsx +362 -0
  185. package/ui/screens/PairScreen.tsx +74 -2
  186. package/ui/screens/PayScreen.tsx +20 -7
  187. package/ui/screens/ProfileScreen.tsx +783 -0
  188. package/ui/screens/SettingsScreen.tsx +10 -4
  189. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  190. package/ui/screens/TrustScreen.tsx +100 -5
  191. package/ui/screens/VaultScreen.tsx +410 -61
  192. package/ui/screens/VaultTransferScreen.tsx +59 -7
  193. package/ui/screens/WalletCheckScreen.tsx +17 -6
  194. package/ui/screens/WalletConfigScreen.tsx +124 -28
  195. package/ui/screens/WalletHomeScreen.tsx +640 -104
  196. package/ui/screens/detailActionKeys.ts +55 -0
  197. package/ui/tokenFormat.ts +44 -4
  198. package/ui/tokenStatus.ts +21 -0
  199. package/ui/txStatus.ts +48 -5
  200. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -1,4 +1,5 @@
1
1
  import { Hash, P2PKH, PublicKey, Transaction, Utils } from '@bsv/sdk'
2
+ import type { ChainTracker } from '@bsv/sdk'
2
3
  import { MandalaToken } from '@bsv/templates'
3
4
  import type { PaymentFrame } from './codec'
4
5
  import { coverFromFrame, type CoverVerifier } from '../mandala/bundle'
@@ -61,9 +62,17 @@ export class FrameVerifyError extends Error {
61
62
  }
62
63
  }
63
64
 
64
- /** The one wallet capability this module needs: BRC-42 derivation. */
65
+ /** The wallet capabilities this module needs: BRC-42 derivation, plus (for the
66
+ * BSV branch) the same chain tracker `internalizeAction` itself consults.
67
+ *
68
+ * `getServices` mirrors the toolbox's own `Wallet`/`WalletStorageManager`
69
+ * shape exactly (`wallet.getServices().getChainTracker()`, not a promise of
70
+ * an object) — the real object NearbyFlow passes in already implements this,
71
+ * so widening the interface needs no new wiring.
72
+ */
65
73
  export interface DerivingWallet {
66
74
  getPublicKey(args: unknown, originator?: string): Promise<{ publicKey: string }>
75
+ getServices(): { getChainTracker(): Promise<ChainTracker> | ChainTracker }
67
76
  }
68
77
 
69
78
  /**
@@ -78,8 +87,8 @@ export interface DerivingWallet {
78
87
  *
79
88
  * Throws on every failure and returns on none, so a caller cannot mistake a
80
89
  * refusal for a zero-value payment. MUST be called before the settle path
81
- * latches or writes anything: every throw here has to remain a provable
82
- * "queued nothing" decline.
90
+ * latches or writes anything: every throw here has to remain an invariant
91
+ * this module enforces on itself — a "queued nothing" decline, by construction.
83
92
  */
84
93
  export async function verifyFramePayment(
85
94
  wallet: DerivingWallet,
@@ -159,6 +168,36 @@ export async function verifyFramePayment(
159
168
  throw new FrameVerifyError('not_mine', `the named output carries no usable satoshi value: ${output.satoshis}`)
160
169
  }
161
170
 
171
+ // The ownership/amount checks above are cheap and certain, but they say
172
+ // nothing about the REST of the transaction: `internalizeAction`'s own
173
+ // gate (toolbox `validateAtomicBeef` -> SDK `Beef.verify`) is a pure
174
+ // AtomicBEEF-structure/SPV check with no script interpreter step, so
175
+ // without this call a payer could spend a real mined UTXO it does not
176
+ // own, with a garbage unlockingScript, into an output that locks to us,
177
+ // for any amount, and have it accepted here.
178
+ //
179
+ // `tx.verify(chainTracker)` does the whole job in one pass: it walks
180
+ // every ancestor's merkle path against this device's own offline-capable
181
+ // chain tracker, runs the per-input script check against each ancestor's
182
+ // real locking script (defeating the garbage-unlockingScript attack), and
183
+ // checks sum(outputs) <= sum(inputs) (defeating an inflated-output
184
+ // attack) — and it FAILS CLOSED: it throws when an input's ancestor is
185
+ // present only as a txid (no raw bytes, e.g. a mined ancestor the payer's
186
+ // BEEF only proved by merkle path) rather than silently skipping that
187
+ // input, which is the desired refusal for an ancestor this device cannot
188
+ // actually verify. No feeModel is passed, so a legitimate low-fee frame
189
+ // is never refused on fee grounds — only on SPV/script/value grounds.
190
+ const chainTracker = await wallet.getServices().getChainTracker()
191
+ let verified: boolean
192
+ try {
193
+ verified = await tx.verify(chainTracker)
194
+ } catch (e) {
195
+ throw new FrameVerifyError('unparseable', `transaction failed SPV/script verification: ${messageOf(e)}`)
196
+ }
197
+ if (!verified) {
198
+ throw new FrameVerifyError('unparseable', 'transaction failed SPV/script verification')
199
+ }
200
+
162
201
  return { kind: 'bsv', satoshis: output.satoshis }
163
202
  }
164
203
 
@@ -183,13 +222,22 @@ export async function verifyFramePayment(
183
222
  originator
184
223
  )
185
224
  const expectedPkh = Hash.hash160(Utils.toArray(publicKey, 'hex'))
186
- const mine = decoded.pubKeyHash.length === expectedPkh.length &&
187
- decoded.pubKeyHash.every((b, i) => b === expectedPkh[i])
225
+ const mine =
226
+ decoded.pubKeyHash.length === expectedPkh.length && decoded.pubKeyHash.every((b, i) => b === expectedPkh[i])
188
227
  if (!mine) throw new FrameVerifyError('not_mine', 'the named token output does not pay this device')
189
228
  if (!Number.isSafeInteger(decoded.amount) || decoded.amount < 1) {
190
229
  throw new FrameVerifyError('not_mine', `the named output carries no usable token amount: ${decoded.amount}`)
191
230
  }
192
231
 
232
+ // XR-099. COVER proves ancestry admission, never value: nothing before this
233
+ // point sums a token input against a token output, so a payer could spend a
234
+ // real, small admitted coin into an output naming any larger amount it
235
+ // likes and have it accepted. Cheap and certain, like the ownership checks
236
+ // above it, so it runs before the COVER walk below.
237
+ if (!tokenConservationHolds(tx, frame.token.assetId)) {
238
+ throw new FrameVerifyError('not_covered', 'the frame’s admission evidence does not cover it: conservation')
239
+ }
240
+
193
241
  // Coverage runs LAST, and only for an output already proven to be ours.
194
242
  // Ownership is the cheaper, more certain check, and running a third party's
195
243
  // injected verifier over a stranger's frame would hand it bytes that were
@@ -200,7 +248,7 @@ export async function verifyFramePayment(
200
248
  // every token ancestor bottoms out at a σ_I this device can verify against
201
249
  // THIS session's overlay key, or at bytes it can walk further. Anything else
202
250
  // is refused here, before the settle path latches or writes anything, so the
203
- // refusal stays a provable "queued nothing".
251
+ // refusal stays an unlatched "queued nothing" by construction.
204
252
  if (!opts?.cover) {
205
253
  throw new FrameVerifyError('not_covered', 'no coverage verifier was supplied for a token frame')
206
254
  }
@@ -214,10 +262,7 @@ export async function verifyFramePayment(
214
262
  // "admitted" as the issuer's.
215
263
  const asset = opts.asset
216
264
  if (!asset || !sameOverlay(frame.token, asset)) {
217
- throw new FrameVerifyError(
218
- 'not_covered',
219
- `the frame’s admission evidence does not cover it: unsafe_asset`
220
- )
265
+ throw new FrameVerifyError('not_covered', `the frame’s admission evidence does not cover it: unsafe_asset`)
221
266
  }
222
267
 
223
268
  const covered = await coverFromFrame(frame, opts.cover)
@@ -251,3 +296,48 @@ function sameOverlay(
251
296
  function messageOf(e: unknown): string {
252
297
  return e instanceof Error ? e.message : String(e)
253
298
  }
299
+
300
+ /**
301
+ * XR-099. Sums `tip`'s own decodable token inputs and outputs for `assetId`
302
+ * and reports whether the outputs are actually covered by the inputs.
303
+ *
304
+ * Deliberately scoped to the tip's OWN direct inputs, not the whole ancestor
305
+ * tree COVER walks: a direct input's previous output is always present in the
306
+ * frame's AtomicBEEF regardless (the payer needs its locking script to build
307
+ * and sign against it), so this is real evidence, not an assumption. An input
308
+ * whose `sourceTransaction` is absent, or whose source output is not a
309
+ * MandalaToken of this asset at all (an ordinary BSV fee input, most
310
+ * commonly), contributes nothing to `inputSum` — which only ever makes this
311
+ * check MORE likely to refuse, never less: there is no way to under-count an
312
+ * output or over-count an input by omission, so this cannot be defeated by a
313
+ * payer hiding a real input behind a hole.
314
+ */
315
+ function tokenConservationHolds(tip: Transaction, assetId: string): boolean {
316
+ let inputSum = 0
317
+ for (const input of tip.inputs) {
318
+ const source = input.sourceTransaction
319
+ const output = source?.outputs[input.sourceOutputIndex]
320
+ if (!output?.lockingScript) continue
321
+ try {
322
+ const decoded = MandalaToken.decode(output.lockingScript)
323
+ if (decoded.assetId === assetId && Number.isSafeInteger(decoded.amount) && decoded.amount > 0) {
324
+ inputSum += decoded.amount
325
+ }
326
+ } catch {
327
+ // Not a token script — an ordinary fee input, per FIX K (see
328
+ // core/mandala/bundle.ts's `tokenParentsOf`).
329
+ }
330
+ }
331
+ let outputSum = 0
332
+ for (const output of tip.outputs) {
333
+ try {
334
+ const decoded = MandalaToken.decode(output.lockingScript)
335
+ if (decoded.assetId === assetId && Number.isSafeInteger(decoded.amount) && decoded.amount > 0) {
336
+ outputSum += decoded.amount
337
+ }
338
+ } catch {
339
+ // Not a token output of this asset.
340
+ }
341
+ }
342
+ return outputSum <= inputSum
343
+ }
@@ -78,7 +78,36 @@ export interface AbortableManager {
78
78
  * `undefined` (no runtime, no database, not a Mandala chain) means "no token
79
79
  * payment can be at stake", which is the correct answer, not a failure.
80
80
  */
81
- export type SettlementStoreLookup = () => Pick<SettlementStore, 'getSettlementByReference'> | undefined
81
+ export type SettlementStoreLookup = () =>
82
+ | Pick<SettlementStore, 'getSettlementByReference' | 'hasUnresolvedLegacyBlockedRows'>
83
+ | undefined
84
+
85
+ /**
86
+ * Whether a token payment could exist on THIS wallet build at all — read LATE,
87
+ * for the same reason `settlements` is, and answering ONLY the question of
88
+ * whether the current chain's configuration could ever have written a
89
+ * `token_settlements` row.
90
+ *
91
+ * XR-034 (SEC1-024 / SEC2-038). `settlements()` answering `undefined` is not
92
+ * one fact. WalletContext.tsx wires it to `() => mandalaRef.current?.store`,
93
+ * and `mandalaRef.current` reads `undefined` in situations that mean opposite
94
+ * things for safety:
95
+ * 1. This chain has no Mandala endpoints at all — `createRuntime.ts`'s
96
+ * `available` (`endpoints !== undefined && db !== undefined`) is false by
97
+ * construction, so no token action has ever existed here, or ever can.
98
+ * 2. `createMandalaRuntime` THREW while endpoints exist (WalletContext.tsx's
99
+ * catch around the construction), or a network switch/rebuild has
100
+ * cleared the ref ahead of the new build's runtime replacing it. Either
101
+ * way the chain's own storage may still carry a `handed_over`/`held`/
102
+ * `submitting`/`admitted`/`broadcast` row from a previous build; this
103
+ * call simply cannot see it right now.
104
+ *
105
+ * Only case 1 licenses treating `undefined` as "no row, safe". WalletContext.tsx
106
+ * wires this to `() => mandalaEndpoints !== undefined` — a static fact of the
107
+ * chain's own configuration that does not fluctuate with runtime construction,
108
+ * build failures, or rebuild timing the way `mandalaRef.current` does.
109
+ */
110
+ export type TokenSettlementPossible = () => boolean
82
111
 
83
112
  /**
84
113
  * Wrap `abortAction` so an action that built a token transaction the overlay
@@ -89,26 +118,72 @@ export type SettlementStoreLookup = () => Pick<SettlementStore, 'getSettlementBy
89
118
  * so the published object is still the one the guard's own re-wrap dedup
90
119
  * recognises. Every other method and property passes through untouched.
91
120
  *
92
- * **Fails OPEN on a lookup fault.** A database that will not answer is not
93
- * evidence that a payment is in flight, and refusing every abort in the wallet
94
- * because one read threw would strand inputs across the whole app — including
95
- * for plain BSV payments this guard has no business touching. The read is
96
- * cheap, indexed, and asked only of `abortAction`.
121
+ * **XR-034: fails CLOSED on anything but a definitive "no".** A database that
122
+ * will not answer, a settlement runtime that has not been built yet, and one
123
+ * mid-rebuild are all indistinguishable from "a payment is in flight" — they
124
+ * are exactly the moments this device can least tell, which is the opposite of
125
+ * evidence that releasing inputs is safe. Refusing the abort in that window
126
+ * costs a retry (every caller already treats `{ aborted: false }` as "did not
127
+ * release, try again" — see `queueFailedAbort`); wrongly granting it costs a
128
+ * double spend. The one shape that still passes through when `settlements()`
129
+ * answers `undefined` is `tokenSettlementPossible()` reporting false: a chain
130
+ * with no Mandala configuration at all, where a blocking row could never have
131
+ * been written and refusing every plain BSV abort forever would be its own
132
+ * outage.
133
+ *
134
+ * **XR-033, a second and coarser check.** A row that predates the `reference`
135
+ * column (or whose backfill at migration time could not resolve one — see
136
+ * `createTables.ts`'s `ensureTokenSettlementColumns`) reads back with
137
+ * `reference === undefined` forever, which the lookup above can never match
138
+ * against ANY reference — so a legacy row stuck in a blocked state is
139
+ * invisible to it no matter which action is being aborted. `hasUnresolvedLegacyBlockedRows`
140
+ * asks the coarser question instead: does ANY such row exist at all. It only
141
+ * ever narrows an abort from allowed to refused, never the reverse, and (like
142
+ * the lookup above) now fails CLOSED on its own read fault, for the same
143
+ * reason.
97
144
  */
98
145
  export function wrapAbortActionForSettlements<T extends AbortableManager>(
99
146
  manager: T,
100
- settlements: SettlementStoreLookup
147
+ settlements: SettlementStoreLookup,
148
+ tokenSettlementPossible: TokenSettlementPossible
101
149
  ): T {
102
150
  return new Proxy(manager, {
103
151
  get(target, prop, receiver) {
104
152
  if (prop === 'abortAction') {
105
153
  return async (args: { reference: string }, originator?: string) => {
106
- const row = await lookupSettlement(settlements, args?.reference)
107
- if (abortIsBlockedBy(row)) {
108
- console.warn(
109
- `[mandala] refusing to abort ${row!.txid}: its settlement is '${row!.state}', ` +
110
- 'so releasing these inputs would double spend a transaction the overlay may already have'
111
- )
154
+ const store = settlements()
155
+ if (!store) {
156
+ if (tokenSettlementPossible()) {
157
+ console.warn(
158
+ '[mandala] refusing to abort: token settlement state is unavailable right now ' +
159
+ '(the runtime is not built, is rebuilding, or its store could not be reached) and this ' +
160
+ 'chain can carry token payments — releasing inputs could double spend one the overlay already has'
161
+ )
162
+ return { aborted: false }
163
+ }
164
+ // No Mandala endpoints on this chain: a blocking row could never
165
+ // have been written, so this is a plain BSV abort like any other.
166
+ return await target.abortAction(args, originator)
167
+ }
168
+ try {
169
+ const row = await lookupSettlement(store, args?.reference)
170
+ if (abortIsBlockedBy(row)) {
171
+ console.warn(
172
+ `[mandala] refusing to abort ${row!.txid}: its settlement is '${row!.state}', ` +
173
+ 'so releasing these inputs would double spend a transaction the overlay may already have'
174
+ )
175
+ return { aborted: false }
176
+ }
177
+ if (await hasUnresolvedLegacyBlockedRow(store)) {
178
+ console.warn(
179
+ '[mandala] refusing to abort: an unresolved legacy settlement row exists with no reference to ' +
180
+ 'match against — releasing any inputs while it is unresolved risks double spending a token ' +
181
+ 'payment that row already has a claim on'
182
+ )
183
+ return { aborted: false }
184
+ }
185
+ } catch (e) {
186
+ console.warn('[mandala] refusing to abort: could not read this action\'s settlement state:', e)
112
187
  return { aborted: false }
113
188
  }
114
189
  return await target.abortAction(args, originator)
@@ -121,14 +196,15 @@ export function wrapAbortActionForSettlements<T extends AbortableManager>(
121
196
  }
122
197
 
123
198
  async function lookupSettlement(
124
- settlements: SettlementStoreLookup,
199
+ store: Pick<SettlementStore, 'getSettlementByReference'>,
125
200
  reference: string | undefined
126
201
  ): Promise<TokenSettlementRow | undefined> {
127
202
  if (!reference) return undefined
128
- try {
129
- return await settlements()?.getSettlementByReference(reference)
130
- } catch (e) {
131
- console.warn('[mandala] could not check the settlement of an aborted action; allowing the abort:', e)
132
- return undefined
133
- }
203
+ return await store.getSettlementByReference(reference)
204
+ }
205
+
206
+ async function hasUnresolvedLegacyBlockedRow(
207
+ store: Pick<SettlementStore, 'hasUnresolvedLegacyBlockedRows'>
208
+ ): Promise<boolean> {
209
+ return await store.hasUnresolvedLegacyBlockedRows()
134
210
  }