@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
@@ -3,16 +3,15 @@ import type { SQLiteDatabase } from 'expo-sqlite'
3
3
  import { createTables, ensureOfflineActionsColumns } from './schema/createTables'
4
4
  import {
5
5
  PROVEN_HEIGHTS_SQL,
6
+ PROVEN_HEIGHT_SQL,
6
7
  buildFindSql,
7
8
  columnsExcluding,
8
9
  rangeReadSql,
9
- RELEASE_STALE_VAULT_STAGING_SPENTBY_SQL,
10
- RELEASE_STRANDED_VAULT_STAGING_SQL,
11
10
  spendingReferencesSql,
12
11
  splitOutpoint
13
12
  } from './methods/findSql'
14
13
  import { scrubHistoryJson } from './methods/historyNotes'
15
- import { sqlBindValue } from './sqlUpdateValue'
14
+ import { BYTE_COLUMNS, bytesForColumn, sqlBindValue } from './sqlUpdateValue'
16
15
  import { StorageError, storageErrorFromSqlite } from './errors'
17
16
  import {
18
17
  RECLAIM_CANDIDATES_SQL,
@@ -23,36 +22,11 @@ import {
23
22
  } from './methods/reclaim'
24
23
  import { availableDiskBytes, diskPressure } from '../diskSpace'
25
24
  import { devLog } from '../logging'
26
- import { StorageProvider } from '@bsv/wallet-toolbox-mobile'
27
- import type { StorageProviderOptions } from '@bsv/wallet-toolbox-mobile'
28
- import type {
29
- AuthId,
30
- FindCertificateFieldsArgs,
31
- FindCertificatesArgs,
32
- FindCommissionsArgs,
33
- FindMonitorEventsArgs,
34
- FindOutputBasketsArgs,
35
- FindOutputsArgs,
36
- FindOutputTagsArgs,
37
- FindOutputTagMapsArgs,
38
- FindProvenTxReqsArgs,
39
- FindProvenTxsArgs,
40
- FindSyncStatesArgs,
41
- FindTransactionsArgs,
42
- FindTxLabelsArgs,
43
- FindTxLabelMapsArgs,
44
- FindUsersArgs,
45
- FindForUserSincePagedArgs,
46
- ProcessSyncChunkResult,
47
- ProvenOrRawTx,
48
- PurgeParams,
49
- PurgeResults,
50
- RequestSyncChunkArgs,
51
- SyncChunk,
52
- TrxToken
53
- } from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
54
- import type { AdminStatsResult } from '@bsv/wallet-toolbox-mobile/out/src/storage/StorageProvider'
25
+ import { EntityProvenTxReq, StorageProvider } from '@bsv/wallet-toolbox-mobile'
55
26
  import type {
27
+ AdminStatsResult,
28
+ PostReqsToNetworkResult,
29
+ StorageProviderOptions,
56
30
  TableCertificate,
57
31
  TableCertificateField,
58
32
  TableCertificateX,
@@ -70,11 +44,9 @@ import type {
70
44
  TableTxLabel,
71
45
  TableTxLabelMap,
72
46
  TableUser
73
- } from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/tables'
47
+ } from '@bsv/wallet-toolbox-mobile'
74
48
  import type { ListActionsResult, ListOutputsResult, Validation, WalletLoggerInterface } from '@bsv/sdk'
75
- import { Beef } from '@bsv/sdk'
76
- import type { EntityProvenTxReq } from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/entities'
77
- import type { PostReqsToNetworkResult } from '@bsv/wallet-toolbox-mobile/out/src/storage/methods/attemptToPostReqsToNetwork'
49
+ import { Beef, Transaction } from '@bsv/sdk'
78
50
  import { listActionsSql } from './methods/listActionsSql'
79
51
  import { listOutputsSql } from './methods/listOutputsSql'
80
52
  import { findUnprovenTxidsWithoutReq } from './methods/unprovenWithoutReqSql'
@@ -94,12 +66,58 @@ import {
94
66
  import { buildOfflineHoldResult, groupOfflineHolds } from '../offline/hold'
95
67
  import { getOnline } from '../net/online'
96
68
  import { TaskSendOffline } from '../monitor/TaskSendOffline'
69
+ import { isR1CLockingScript } from '../services/vault/guard'
70
+ import type {
71
+ AuthId,
72
+ FindCertificateFieldsArgs,
73
+ FindCertificatesArgs,
74
+ FindCommissionsArgs,
75
+ FindMonitorEventsArgs,
76
+ FindOutputBasketsArgs,
77
+ FindOutputsArgs,
78
+ FindOutputTagsArgs,
79
+ FindOutputTagMapsArgs,
80
+ FindProvenTxReqsArgs,
81
+ FindProvenTxsArgs,
82
+ FindSyncStatesArgs,
83
+ FindTransactionsArgs,
84
+ FindTxLabelsArgs,
85
+ FindTxLabelMapsArgs,
86
+ FindUsersArgs,
87
+ FindForUserSincePagedArgs,
88
+ ProcessSyncChunkResult,
89
+ ProvenOrRawTx,
90
+ PurgeParams,
91
+ PurgeResults,
92
+ RequestSyncChunkArgs,
93
+ StorageProcessActionArgs,
94
+ StorageProcessActionResults,
95
+ SyncChunk,
96
+ TrxToken
97
+ } from '../toolboxTypes'
97
98
 
98
99
  export interface StorageExpoSQLiteOptions extends StorageProviderOptions {
99
100
  databaseName?: string
100
101
  identityKey?: string
101
102
  }
102
103
 
104
+ /** What `repairSettledTokenTransaction` actually changed, for the caller's log. */
105
+ export interface TokenTransactionRepair {
106
+ txid: string
107
+ /** Transaction rows moved back to 'unproven'. */
108
+ transactionIds: number[]
109
+ /** Their statuses before the repair — 'failed', in the case this exists for. */
110
+ wasTxStatuses: string[]
111
+ /** The request's status before the repair, or undefined when there was none. */
112
+ wasReqStatus?: string
113
+ /** Coins this transaction spends that were wrongly spendable and are now spent. */
114
+ inputsMarkedSpent: number
115
+ /** This transaction's own outputs (change included) restored to spendable. */
116
+ outputsMadeSpendable: number
117
+ /** True when the request had gone and was rebuilt from the raw transaction. */
118
+ reqCreated: boolean
119
+ }
120
+
103
121
  /** Per-connection wait before a lock contention becomes "database is locked". */
104
122
  export const BUSY_TIMEOUT_MS = 5000
105
123
 
@@ -135,6 +153,25 @@ export class StorageExpoSQLite extends StorageProvider {
135
153
  this.dbName = options.databaseName || `wallet-${keySuffix}-${this.chain}net.db`
136
154
  }
137
155
 
156
+ /**
157
+ * Final Vault authorization check for explicit transaction inputs.
158
+ *
159
+ * The toolbox invokes this only after it has resolved the immutable source
160
+ * locking script from authenticated local storage or verified BEEF. This is
161
+ * the database-side backstop for history-scan races: even if an R1C output
162
+ * appears between an external guard scan and createAction, the reservation
163
+ * cannot proceed without the host-derived internal-admin marker.
164
+ */
165
+ async validateResolvedActionInput(
166
+ vargs: { __bsvVaultAdminAuthorized?: boolean },
167
+ input: { lockingScript?: { toHex(): string } }
168
+ ): Promise<void> {
169
+ const lockingScript = input.lockingScript?.toHex()
170
+ if (lockingScript && isR1CLockingScript(lockingScript) && vargs.__bsvVaultAdminAuthorized !== true) {
171
+ throw new Error('Vault R1C inputs require internal wallet authorization')
172
+ }
173
+ }
174
+
138
175
  // ============================================================================
139
176
  // Infrastructure methods
140
177
  // ============================================================================
@@ -398,7 +435,9 @@ export class StorageExpoSQLite extends StorageProvider {
398
435
  }
399
436
  for (const key of Object.keys(v)) {
400
437
  const val = v[key]
401
- if (Array.isArray(val) && (val.length === 0 || Number.isInteger(val[0]))) {
438
+ if (BYTE_COLUMNS.has(key)) {
439
+ v[key] = bytesForColumn(key, val)
440
+ } else if (Array.isArray(val) && (val.length === 0 || Number.isInteger(val[0]))) {
402
441
  v[key] = Uint8Array.from(val)
403
442
  } else if (val === null) {
404
443
  v[key] = undefined
@@ -435,7 +474,9 @@ export class StorageExpoSQLite extends StorageProvider {
435
474
  }
436
475
  for (const key of Object.keys(v)) {
437
476
  const val = v[key]
438
- if (Array.isArray(val) && (val.length === 0 || Number.isInteger(val[0]))) {
477
+ if (BYTE_COLUMNS.has(key)) {
478
+ v[key] = bytesForColumn(key, val)
479
+ } else if (Array.isArray(val) && (val.length === 0 || Number.isInteger(val[0]))) {
439
480
  v[key] = Uint8Array.from(val)
440
481
  } else if (val === null) {
441
482
  v[key] = undefined
@@ -1363,7 +1404,7 @@ export class StorageExpoSQLite extends StorageProvider {
1363
1404
  * getSyncChunk reads to build a backup chunk.
1364
1405
  */
1365
1406
  async getProvenTxsForUser(args: FindForUserSincePagedArgs): Promise<TableProvenTx[]> {
1366
- const db = this.getDB()
1407
+ const db = this.getDB(args.trx)
1367
1408
  let query = `SELECT pt.* FROM proven_txs pt
1368
1409
  WHERE EXISTS (SELECT 1 FROM transactions t WHERE t.provenTxId = pt.provenTxId AND t.userId = ?)`
1369
1410
  const params: any[] = [args.userId]
@@ -1381,7 +1422,7 @@ export class StorageExpoSQLite extends StorageProvider {
1381
1422
  }
1382
1423
 
1383
1424
  async getProvenTxReqsForUser(args: FindForUserSincePagedArgs): Promise<TableProvenTxReq[]> {
1384
- const db = this.getDB()
1425
+ const db = this.getDB(args.trx)
1385
1426
  let query = `SELECT ptr.* FROM proven_tx_reqs ptr
1386
1427
  WHERE EXISTS (SELECT 1 FROM transactions t WHERE t.txid = ptr.txid AND t.userId = ?)`
1387
1428
  const params: any[] = [args.userId]
@@ -1399,7 +1440,7 @@ export class StorageExpoSQLite extends StorageProvider {
1399
1440
  }
1400
1441
 
1401
1442
  async getTxLabelMapsForUser(args: FindForUserSincePagedArgs): Promise<TableTxLabelMap[]> {
1402
- const db = this.getDB()
1443
+ const db = this.getDB(args.trx)
1403
1444
  let query = `SELECT tlm.* FROM tx_labels_map tlm
1404
1445
  WHERE EXISTS (SELECT 1 FROM tx_labels tl WHERE tl.txLabelId = tlm.txLabelId AND tl.userId = ?)`
1405
1446
  const params: any[] = [args.userId]
@@ -1417,7 +1458,7 @@ export class StorageExpoSQLite extends StorageProvider {
1417
1458
  }
1418
1459
 
1419
1460
  async getOutputTagMapsForUser(args: FindForUserSincePagedArgs): Promise<TableOutputTagMap[]> {
1420
- const db = this.getDB()
1461
+ const db = this.getDB(args.trx)
1421
1462
  let query = `SELECT otm.* FROM output_tags_map otm
1422
1463
  WHERE EXISTS (SELECT 1 FROM output_tags ot WHERE ot.outputTagId = otm.outputTagId AND ot.userId = ?)`
1423
1464
  const params: any[] = [args.userId]
@@ -1520,41 +1561,6 @@ export class StorageExpoSQLite extends StorageProvider {
1520
1561
  .map(r => ({ reference: r.reference as string, status: r.status as string }))
1521
1562
  }
1522
1563
 
1523
- /**
1524
- * Release every input a definitively-invalid vault deposit tx2 still holds.
1525
- * Returns how many outputs were made spendable again.
1526
- *
1527
- * The shape being healed (production, 2026-08-21): tx2 was rejected by every
1528
- * broadcaster (proven_tx_reqs.status = 'invalid', transactions.status =
1529
- * 'failed'), the toolbox's own release of its inputs was then OVERRIDDEN by
1530
- * markStaleInputsAsSpent — which asked the indexers about tx1's staging
1531
- * output seconds after tx1 broadcast, and indexer lag said "not a UTXO" —
1532
- * and abortAction cannot help because 'failed' is in its unAbortable list.
1533
- * The staging coin (and any change the toolbox pulled in as extra funding)
1534
- * sits spendable=0 forever while it is live on chain.
1535
- *
1536
- * The predicate is deliberately narrow, every clause load-bearing:
1537
- * - spentBy transaction has status 'failed' AND its proven_tx_req is
1538
- * 'invalid' — the network REJECTED the spender outright; it can never be
1539
- * mined, so releasing its inputs cannot enable a real double-spend. A
1540
- * 'failed' tx without an 'invalid' req (e.g. a broadcast that timed out
1541
- * but may have propagated) is NOT touched.
1542
- * - the spender carries the 'vault-deposit' label — this heal exists for
1543
- * the deposit flow and must not reinterpret failures of anything else.
1544
- */
1545
- async releaseVaultStagingStrandedByInvalidTx(): Promise<number> {
1546
- if (!this.isAvailable()) await this.makeAvailable()
1547
- const r = await this.getDB().runAsync(RELEASE_STRANDED_VAULT_STAGING_SQL, [])
1548
- // The other arm: coins already spendable=1 but with a stale spentBy still
1549
- // naming the failed spender (updateOutput's spentBy: undefined is dropped
1550
- // by sqlUpdate). createAction refuses those with WERR_REVIEW_ACTIONS, so
1551
- // they are just as stuck as the spendable=0 arm until cleared.
1552
- const r2 = await this.getDB().runAsync(RELEASE_STALE_VAULT_STAGING_SPENTBY_SQL, [])
1553
- const released = (r?.changes ?? 0) + (r2?.changes ?? 0)
1554
- if (released > 0) console.log('[vault] released %d output(s) stranded by invalid deposit tx', released)
1555
- return released
1556
- }
1557
-
1558
1564
  /** Size of the database file on disk, or null when it cannot be read. */
1559
1565
  async databaseFileBytes(): Promise<number | null> {
1560
1566
  try {
@@ -1647,6 +1653,13 @@ export class StorageExpoSQLite extends StorageProvider {
1647
1653
  return map
1648
1654
  }
1649
1655
 
1656
+ /** The block height of a proven transaction, or null while it is unproven. */
1657
+ async getProvenTxHeight(txid: string): Promise<number | null> {
1658
+ if (!this.isAvailable()) await this.makeAvailable()
1659
+ const row = (await this.getDB().getFirstAsync(PROVEN_HEIGHT_SQL, [txid])) as { height?: number } | null
1660
+ return typeof row?.height === 'number' ? row.height : null
1661
+ }
1662
+
1650
1663
  async getRawTxOfKnownValidTransaction(
1651
1664
  txid?: string,
1652
1665
  offset?: number,
@@ -1850,6 +1863,141 @@ export class StorageExpoSQLite extends StorageProvider {
1850
1863
  }, args.trx)
1851
1864
  }
1852
1865
 
1866
+ /**
1867
+ * Put a token transaction the wallet wrongly failed back into a live state,
1868
+ * for a caller that has independently established the transaction IS on chain.
1869
+ *
1870
+ * WHY THIS EXISTS RATHER THAN A CALL INTO THE TOOLBOX. Every sanctioned
1871
+ * un-fail path in `@bsv/wallet-toolbox-mobile` is gated on something this case
1872
+ * cannot supply:
1873
+ *
1874
+ * · `updateTransactionStatus` refuses outright — "A 'failed' transaction may
1875
+ * not be un-failed by this method" (`StorageProvider.js`), and `reviewStatus`
1876
+ * only ever moves rows TOWARDS failed.
1877
+ * · `TaskUnFail` is the real recovery path, but its entry point demands
1878
+ * `services.getMerklePath(txid)` first and returns the req to `'invalid'`
1879
+ * when there is none. A transaction the overlay broadcast seconds ago has
1880
+ * no merkle path and will not have one for ten minutes, which is precisely
1881
+ * the window in which the wallet's own bookkeeping is wrong and its coins
1882
+ * are wrongly spendable.
1883
+ * · `unfailTransactionsForProof` — the body TaskUnFail delegates to — is the
1884
+ * right SHAPE (tx to 'unproven', inputs to spent, req to 'unmined'), and
1885
+ * the steps below are deliberately identical to it, EXCEPT that it decides
1886
+ * each of this transaction's own outputs by `services.isUtxo(output)`. For
1887
+ * a tx broadcast moments ago that probe answers "not a utxo" from services
1888
+ * that have not seen it yet, which would leave the change permanently
1889
+ * unspendable — the opposite of the repair.
1890
+ *
1891
+ * So the steps are written out here, through the provider's own CRUD methods
1892
+ * (`updateTransaction`/`updateOutput`/`updateProvenTxReq`), and never as raw
1893
+ * SQL over the tables. What it does, in one write transaction:
1894
+ *
1895
+ * 1. every transaction row for `txid` that is not already `'completed'`
1896
+ * goes to `'unproven'` — broadcast, awaiting proof;
1897
+ * 2. every input the raw transaction spends that is one of THIS user's
1898
+ * outputs goes back to `spendable: false, spentBy: <this transaction>`.
1899
+ * This is the money-safety step: `updateTransactionStatus('failed')`
1900
+ * released those coins, and they are spent on chain;
1901
+ * 3. this transaction's own outputs go back to `spendable: true`, except any
1902
+ * a different transaction has since spent (`spentBy` set), which are left
1903
+ * exactly as they are;
1904
+ * 4. the request goes to `'unmined'` with `attempts: 0`, which is one of the
1905
+ * statuses `TaskCheckForProofs` polls, so the monitor proves it from here
1906
+ * exactly as it would any other broadcast transaction. A request that has
1907
+ * gone missing entirely is recreated from the transaction's own raw bytes.
1908
+ *
1909
+ * Returns `undefined` when there was nothing to repair (no transaction row, no
1910
+ * raw bytes to read the inputs from, or a transaction that is already live) —
1911
+ * the caller logs, and nothing is written.
1912
+ */
1913
+ async repairSettledTokenTransaction(txid: string): Promise<TokenTransactionRepair | undefined> {
1914
+ const transactions = await this.findTransactions({ partial: { txid } })
1915
+ if (transactions.length === 0) return undefined
1916
+ const req = (await this.findProvenTxReqs({ partial: { txid } }))[0]
1917
+
1918
+ // Nothing to do unless the wallet actually believes this transaction died.
1919
+ const damaged = transactions.some(t => t.status === 'failed') || req?.status === 'invalid'
1920
+ if (!damaged) return undefined
1921
+
1922
+ const rawTx = req?.rawTx ?? transactions.find(t => t.rawTx && t.rawTx.length > 0)?.rawTx
1923
+ if (!rawTx || rawTx.length === 0) {
1924
+ devLog(`[StorageExpoSQLite] cannot repair ${txid}: no raw transaction to read its inputs from`)
1925
+ return undefined
1926
+ }
1927
+ let parsed: Transaction
1928
+ try {
1929
+ parsed = Transaction.fromBinary([...rawTx])
1930
+ } catch (e) {
1931
+ devLog(`[StorageExpoSQLite] cannot repair ${txid}: its raw transaction will not parse:`, e)
1932
+ return undefined
1933
+ }
1934
+
1935
+ const repair: TokenTransactionRepair = {
1936
+ txid,
1937
+ transactionIds: [],
1938
+ wasTxStatuses: transactions.map(t => t.status),
1939
+ wasReqStatus: req?.status,
1940
+ inputsMarkedSpent: 0,
1941
+ outputsMadeSpendable: 0,
1942
+ reqCreated: false
1943
+ }
1944
+
1945
+ await this.transaction(async trx => {
1946
+ for (const tx of transactions) {
1947
+ if (tx.status === 'completed') continue
1948
+ repair.transactionIds.push(tx.transactionId)
1949
+ await this.updateTransaction(tx.transactionId, { status: 'unproven' }, trx)
1950
+
1951
+ for (const input of parsed.inputs) {
1952
+ const sourceTXID = input.sourceTXID ?? input.sourceTransaction?.id('hex')
1953
+ if (!sourceTXID || typeof input.sourceOutputIndex !== 'number') continue
1954
+ const matches = await this.findOutputs({
1955
+ partial: { userId: tx.userId, txid: sourceTXID, vout: input.sourceOutputIndex },
1956
+ trx
1957
+ })
1958
+ for (const output of matches) {
1959
+ if (output.outputId == null) continue
1960
+ await this.updateOutput(output.outputId, { spendable: false, spentBy: tx.transactionId }, trx)
1961
+ repair.inputsMarkedSpent++
1962
+ }
1963
+ }
1964
+
1965
+ const own = await this.findOutputs({ partial: { userId: tx.userId, transactionId: tx.transactionId }, trx })
1966
+ for (const output of own) {
1967
+ // Spent by something else since the failure: that spend is the newer
1968
+ // fact about this coin and must not be undone by a repair.
1969
+ if (output.outputId == null || output.spentBy != null || output.spendable) continue
1970
+ await this.updateOutput(output.outputId, { spendable: true }, trx)
1971
+ repair.outputsMadeSpendable++
1972
+ }
1973
+ }
1974
+
1975
+ if (req) {
1976
+ await this.updateProvenTxReq(req.provenTxReqId, { status: 'unmined', attempts: 0 }, trx)
1977
+ } else {
1978
+ const now = new Date()
1979
+ await this.insertProvenTxReq(
1980
+ {
1981
+ created_at: now,
1982
+ updated_at: now,
1983
+ provenTxReqId: 0,
1984
+ txid,
1985
+ status: 'unmined',
1986
+ attempts: 0,
1987
+ notified: false,
1988
+ history: '{}',
1989
+ notify: JSON.stringify({ transactionIds: repair.transactionIds }),
1990
+ rawTx: [...rawTx]
1991
+ } as TableProvenTxReq,
1992
+ trx
1993
+ )
1994
+ repair.reqCreated = true
1995
+ }
1996
+ })
1997
+
1998
+ return repair
1999
+ }
2000
+
1853
2001
  async purgeData(_params: PurgeParams, _trx?: TrxToken): Promise<PurgeResults> {
1854
2002
  return { count: 0, log: '' }
1855
2003
  }
@@ -1929,7 +2077,81 @@ export class StorageExpoSQLite extends StorageProvider {
1929
2077
  }
1930
2078
 
1931
2079
  /**
1932
- * Offline, hold the requests. Online, behave exactly as before.
2080
+ * Guard #2 for the monitor's own retry path.
2081
+ *
2082
+ * `TaskSendWaiting` posts 'unsent' requests through the module function, not
2083
+ * through `attemptToPostReqsToNetwork` on this instance, so the hold below
2084
+ * never saw them — and an internalized token payment lands exactly there:
2085
+ * `internalizeAction` with delayed broadcast leaves its request 'unsent'. On
2086
+ * 2026-09-15 a recipient wallet raw-broadcast four just-credited token
2087
+ * transactions (one of them a known double-spend) before any `/submit`.
2088
+ * `WalletContext` calls this from its `processUnsent` patch: every request
2089
+ * with a `token_settlements` row is held for the drain and the caller is
2090
+ * told which ones, so it posts only the rest. Never throws.
2091
+ */
2092
+ async holdTokenReqsForDrain(reqApis: TableProvenTxReq[]): Promise<Set<string>> {
2093
+ try {
2094
+ const tokenTxids = await this.tokenSettlementTxids(reqApis.map(r => r.txid))
2095
+ if (tokenTxids.size === 0) return tokenTxids
2096
+ const reqs = reqApis.filter(r => tokenTxids.has(r.txid)).map(r => new EntityProvenTxReq(r))
2097
+ devLog(`[StorageExpoSQLite] holding ${reqs.length} token req(s) from the monitor's retry for the settlement drain`)
2098
+ await this.holdTokenReqs(reqs)
2099
+ return tokenTxids
2100
+ } catch (e) {
2101
+ devLog('[StorageExpoSQLite] could not hold token reqs from the monitor retry; withholding them anyway:', e)
2102
+ return new Set(reqApis.map(r => r.txid))
2103
+ }
2104
+ }
2105
+
2106
+ /**
2107
+ * Which of these txids the Mandala settlement drain owns.
2108
+ *
2109
+ * A missing table (a device that has not yet run the additive migration) or
2110
+ * any other read failure yields the empty set, which is exactly the
2111
+ * pre-feature behaviour — logged, never thrown, because a broken read here
2112
+ * must not take down every broadcast in the wallet.
2113
+ */
2114
+ private async tokenSettlementTxids(txids: string[]): Promise<Set<string>> {
2115
+ if (txids.length === 0 || !this.db) return new Set()
2116
+ try {
2117
+ const rows = (await this.db.getAllAsync(
2118
+ `SELECT txid FROM token_settlements WHERE txid IN (${txids.map(() => '?').join(',')})`,
2119
+ txids
2120
+ )) as { txid: string }[]
2121
+ return new Set(rows.map(r => r.txid))
2122
+ } catch (e) {
2123
+ devLog('[StorageExpoSQLite] could not read token_settlements, treating every req as plain BSV:', e)
2124
+ return new Set()
2125
+ }
2126
+ }
2127
+
2128
+ /**
2129
+ * Hold token requests whatever `groupOfflineHolds` says.
2130
+ *
2131
+ * The all-or-nothing refusal `groupOfflineHolds` offers is right for the BSV
2132
+ * path — refusing there falls back to the ordinary broadcast. For a token req
2133
+ * that fallback is precisely the harm this guard exists to prevent, so an
2134
+ * ungroupable token req is simply not broadcast: it keeps its
2135
+ * `token_settlements` row, which the drain owns independently of any queue
2136
+ * bookkeeping (FIX I) and which `listStuckSettlements` surfaces if it never
2137
+ * moves. The failure is loud in the log and recoverable; a premature
2138
+ * broadcast is neither.
2139
+ */
2140
+ private async holdTokenReqs(reqs: EntityProvenTxReq[]): Promise<void> {
2141
+ const holds = groupOfflineHolds(await this.resolveHoldPairs(reqs))
2142
+ if (!holds) {
2143
+ devLog(
2144
+ '[StorageExpoSQLite] token req(s) could not be attributed for a queue row; withholding anyway:',
2145
+ reqs.map(r => r.txid).join(', ')
2146
+ )
2147
+ return
2148
+ }
2149
+ for (const hold of holds.values()) await this.holdReqsOffline(hold.reqs, hold.userId, hold.role)
2150
+ }
2151
+
2152
+ /**
2153
+ * Offline, hold the requests. Online, behave exactly as before — EXCEPT for a
2154
+ * token request, which is held either way.
1933
2155
  *
1934
2156
  * This override is reached only from `shareReqsWithWorld`
1935
2157
  * (`storage/methods/processAction.js:146`, a method call on storage), which
@@ -1938,15 +2160,105 @@ export class StorageExpoSQLite extends StorageProvider {
1938
2160
  * directly (`monitor/tasks/TaskSendWaiting.js:180`), so the monitor's
1939
2161
  * ordinary broadcast retries are deliberately NOT intercepted.
1940
2162
  *
1941
- * Narrower than "offline means hold": only requests whose transaction is
1942
- * already in a hold-safe status are parked, so in practice this holds the
1943
- * internalize path the feature needs and leaves the non-delayed `createAction`
1944
- * path with the `serviceError` and automatic `TaskSendWaiting` retry it has
1945
- * today. `groupOfflineHolds` makes that call; see `utils/offline/hold.ts`.
2163
+ * **Token guard (offline-settlement spec §4.3, guard #2).** A transaction
2164
+ * with a `token_settlements` row may only be broadcast by `postTokenStep`,
2165
+ * after the issuer's overlay has admitted it and every unadmitted token
2166
+ * ancestor it spends. Holding "only when offline" left the common shop case
2167
+ * wide open — payee has Wi-Fi, payer none — because the payee's own
2168
+ * `internalizeAction` then reached a real, unmediated broadcast. So token
2169
+ * reqs are split off and held unconditionally, and the online branch is taken
2170
+ * only for what is left. The result still covers every txid the caller handed
2171
+ * in: reporting on a subset would make `internalizeAction` roll back a
2172
+ * payment that was in fact accepted for delivery.
2173
+ *
2174
+ * Guard #3 follows from this one: because a token req is never handed to
2175
+ * `sendWith` outside `postTokenStep`, it never reaches `unsent`/`sending`,
2176
+ * which is all that keeps `TaskSendWaiting` — which bypasses this override
2177
+ * entirely — from broadcasting it out from under the drain.
2178
+ *
2179
+ * Narrower than "offline means hold" on the BSV side: only requests whose
2180
+ * transaction is already in a hold-safe status are parked, so in practice
2181
+ * this holds the internalize path the feature needs and leaves the
2182
+ * non-delayed `createAction` path with the `serviceError` and automatic
2183
+ * `TaskSendWaiting` retry it has today. `groupOfflineHolds` makes that call;
2184
+ * see `utils/offline/hold.ts`.
1946
2185
  *
1947
2186
  * The returned 'success' means "accepted for delivery", not "the network has
1948
2187
  * it"; see `utils/offline/hold.ts` for why nothing persisted claims otherwise.
1949
2188
  */
2189
+ /**
2190
+ * Guard #2's RESULT half: a held token request must not read as a posted one.
2191
+ *
2192
+ * `attemptToPostReqsToNetwork` answers `status: 'success'` for a token
2193
+ * request it HELD, and it has to — `'success'` there means "accepted for
2194
+ * delivery", which is what stops `internalizeAction` rolling back a payment
2195
+ * it has already verified (see `offline/hold.ts`). But `aggregateActionResults`
2196
+ * turns that same `'success'` into `SendWithResult.status = 'unproven'`,
2197
+ * i.e. "the processing network has accepted this transaction" — and on
2198
+ * 2026-09-15 `@bsv/mandala`'s `broadcastAcceptedTx` believed it, cleared its
2199
+ * `'accepted'` journal entry for a transaction nothing had broadcast, and so
2200
+ * left the live noSend action looking abandoned to the next reconcile sweep.
2201
+ * One aborted action and one released-but-spent coin later, that is the
2202
+ * incident.
2203
+ *
2204
+ * So a `sendWith` release of a token transaction that is still HELD reports
2205
+ * nothing at all for that txid. Omission rather than a made-up status,
2206
+ * deliberately: `SendWithResult.status` is a three-value SDK union, and
2207
+ * `Wallet.createAction` throws `WERR_REVIEW_ACTIONS` unless EVERY entry reads
2208
+ * `'unproven'` — so inventing a fourth value would turn a correct hold into a
2209
+ * thrown error for every caller, while an absent entry is simply "this wallet
2210
+ * is not telling you it went out", which is the truth and which no caller can
2211
+ * mistake for delivery.
2212
+ *
2213
+ * Scoped as narrowly as it can be: only txids that have a `token_settlements`
2214
+ * row AND whose request is still parked at `'nosend'`. Once `postTokenStep`
2215
+ * has really broadcast the tip its request is past `'nosend'` and its results
2216
+ * pass through exactly as before, and a plain BSV action is never looked at.
2217
+ *
2218
+ * `internalizeAction` is unaffected — it calls `shareReqsWithWorld` directly
2219
+ * rather than through `processAction` — which is what keeps the receiver's
2220
+ * credit from rolling back.
2221
+ */
2222
+ async processAction(auth: AuthId, args: StorageProcessActionArgs): Promise<StorageProcessActionResults> {
2223
+ const r = await super.processAction(auth, args)
2224
+ const swr = r.sendWithResults
2225
+ if (!swr || swr.length === 0) return r
2226
+
2227
+ let heldTokenTxids: Set<string>
2228
+ try {
2229
+ heldTokenTxids = await this.heldTokenTxidsIn(swr.map(s => s.txid))
2230
+ } catch (e) {
2231
+ // A read fault here must not change what the wallet reports; the guard in
2232
+ // front of the broadcast has already done the load-bearing work.
2233
+ devLog('[StorageExpoSQLite] could not check held token reqs for sendWithResults:', e)
2234
+ return r
2235
+ }
2236
+ if (heldTokenTxids.size === 0) return r
2237
+
2238
+ devLog(
2239
+ `[StorageExpoSQLite] omitting ${heldTokenTxids.size} held token req(s) from sendWithResults; ` +
2240
+ 'the settlement drain owns their broadcast'
2241
+ )
2242
+ return { ...r, sendWithResults: swr.filter(s => !heldTokenTxids.has(s.txid)) }
2243
+ }
2244
+
2245
+ /**
2246
+ * Of these txids, the ones that both have a `token_settlements` row and are
2247
+ * still parked at request status `'nosend'` — i.e. held by guard #2 and not
2248
+ * yet broadcast by the drain. Read failures propagate; the one caller decides
2249
+ * what a failure means.
2250
+ */
2251
+ private async heldTokenTxidsIn(txids: string[]): Promise<Set<string>> {
2252
+ const tokenTxids = await this.tokenSettlementTxids(txids)
2253
+ if (tokenTxids.size === 0) return new Set()
2254
+ const held = new Set<string>()
2255
+ for (const txid of tokenTxids) {
2256
+ const req = (await this.findProvenTxReqs({ partial: { txid } }))[0]
2257
+ if (req?.status === 'nosend') held.add(txid)
2258
+ }
2259
+ return held
2260
+ }
2261
+
1950
2262
  async attemptToPostReqsToNetwork(
1951
2263
  reqs: EntityProvenTxReq[],
1952
2264
  trx?: TrxToken,
@@ -1954,6 +2266,21 @@ export class StorageExpoSQLite extends StorageProvider {
1954
2266
  ): Promise<PostReqsToNetworkResult> {
1955
2267
  if (reqs.length === 0) return await super.attemptToPostReqsToNetwork(reqs, trx, logger)
1956
2268
 
2269
+ const tokenTxids = await this.tokenSettlementTxids(reqs.map(r => r.txid))
2270
+ const tokenReqs = tokenTxids.size > 0 ? reqs.filter(r => tokenTxids.has(r.txid)) : []
2271
+ const rest = tokenTxids.size > 0 ? reqs.filter(r => !tokenTxids.has(r.txid)) : reqs
2272
+
2273
+ if (tokenReqs.length > 0) {
2274
+ devLog(
2275
+ `[StorageExpoSQLite] holding ${tokenReqs.length} token req(s) for the settlement drain, regardless of connectivity`
2276
+ )
2277
+ await this.holdTokenReqs(tokenReqs)
2278
+ // Nothing else in the call: answer for the whole call without ever
2279
+ // asking whether we are online, because the answer could not change it.
2280
+ if (rest.length === 0) return { ...buildOfflineHoldResult(reqs), beef: new Beef(), log: '' }
2281
+ }
2282
+ const held = tokenReqs.length > 0 ? buildOfflineHoldResult(tokenReqs).details : []
2283
+
1957
2284
  let online = true
1958
2285
  try {
1959
2286
  online = await getOnline()
@@ -1962,9 +2289,12 @@ export class StorageExpoSQLite extends StorageProvider {
1962
2289
  // online so the real post runs exactly as it did before this override.
1963
2290
  devLog('[StorageExpoSQLite] connectivity probe failed, assuming online:', e)
1964
2291
  }
1965
- if (online) return await super.attemptToPostReqsToNetwork(reqs, trx, logger)
2292
+ if (online) {
2293
+ const posted = await super.attemptToPostReqsToNetwork(rest, trx, logger)
2294
+ return held.length > 0 ? { ...posted, details: [...posted.details, ...held] } : posted
2295
+ }
1966
2296
 
1967
- const pairs = await this.resolveHoldPairs(reqs)
2297
+ const pairs = await this.resolveHoldPairs(rest)
1968
2298
  const holds = groupOfflineHolds(pairs)
1969
2299
  if (!holds) {
1970
2300
  // Either a request could not be attributed to a user, so we could not
@@ -1977,10 +2307,13 @@ export class StorageExpoSQLite extends StorageProvider {
1977
2307
  '[StorageExpoSQLite] offline: not holding, delegating to the real post:',
1978
2308
  pairs.map(p => `${p.req.txid} ${p.tx ? `tx ${p.tx.status}` : 'unattributed'}`).join(', ')
1979
2309
  )
1980
- return await super.attemptToPostReqsToNetwork(reqs, trx, logger)
2310
+ // `rest` only: the token reqs are already held above and must never be
2311
+ // handed to a real post, whatever the rest of the batch turned out to be.
2312
+ const posted = await super.attemptToPostReqsToNetwork(rest, trx, logger)
2313
+ return held.length > 0 ? { ...posted, details: [...posted.details, ...held] } : posted
1981
2314
  }
1982
2315
 
1983
- devLog(`[StorageExpoSQLite] offline: holding ${reqs.length} req(s) for later delivery`)
2316
+ devLog(`[StorageExpoSQLite] offline: holding ${rest.length} req(s) for later delivery`)
1984
2317
  for (const hold of holds.values()) {
1985
2318
  await this.holdReqsOffline(hold.reqs, hold.userId, hold.role)
1986
2319
  }