@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,48 @@
1
+ /**
2
+ * Helpers for raw SQLite database images (the bytes of a `.db` file).
3
+ */
4
+
5
+ /** "SQLite format 3\0" — the 16-byte magic at the start of every database file. */
6
+ const SQLITE_MAGIC = [0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00]
7
+
8
+ const HEADER_WRITE_VERSION = 18
9
+ const HEADER_READ_VERSION = 19
10
+ const FORMAT_LEGACY = 1
11
+ const FORMAT_WAL = 2
12
+
13
+ function hasSqliteMagic(bytes: Uint8Array): boolean {
14
+ if (bytes.length < 100) return false
15
+ for (let i = 0; i < SQLITE_MAGIC.length; i++) {
16
+ if (bytes[i] !== SQLITE_MAGIC[i]) return false
17
+ }
18
+ return true
19
+ }
20
+
21
+ /**
22
+ * Make a database image safe to hand to `deserializeDatabaseAsync`.
23
+ *
24
+ * The wallet database runs in WAL mode, so every export of it (an iOS byte
25
+ * copy or an Android `serializeAsync` image) carries header bytes 18/19 = 2,
26
+ * which tells SQLite the file is in WAL mode. `sqlite3_deserialize` loads the
27
+ * image under the memdb VFS, which implements no shared-memory (`xShmMap`)
28
+ * methods, so the pager's attempt to open the WAL fails with SQLITE_CANTOPEN
29
+ * ("unable to open database file") on the first read — surfacing from
30
+ * `backupDatabaseAsync` during import.
31
+ *
32
+ * The image itself is complete (the export checkpoints before copying, and
33
+ * `serializeAsync` reads through the pager), so flipping the two version
34
+ * bytes to rollback-journal mode (1) loses nothing. The caller's buffer is
35
+ * not modified; a patched copy is returned only when a change is needed.
36
+ * Non-SQLite input is returned as-is so the real validation error still
37
+ * comes from SQLite.
38
+ */
39
+ export function prepareSqliteImageForDeserialize(bytes: Uint8Array): Uint8Array {
40
+ if (!hasSqliteMagic(bytes)) return bytes
41
+ if (bytes[HEADER_WRITE_VERSION] !== FORMAT_WAL && bytes[HEADER_READ_VERSION] !== FORMAT_WAL) {
42
+ return bytes
43
+ }
44
+ const out = new Uint8Array(bytes)
45
+ if (out[HEADER_WRITE_VERSION] === FORMAT_WAL) out[HEADER_WRITE_VERSION] = FORMAT_LEGACY
46
+ if (out[HEADER_READ_VERSION] === FORMAT_WAL) out[HEADER_READ_VERSION] = FORMAT_LEGACY
47
+ return out
48
+ }
@@ -204,6 +204,9 @@ export function rangeReadSql(table: 'proven_txs' | 'proven_tx_reqs'): string {
204
204
  */
205
205
  export const PROVEN_HEIGHTS_SQL = 'SELECT txid, height FROM proven_txs'
206
206
 
207
+ /** One transaction's block height, without reading its rawTx or merklePath. */
208
+ export const PROVEN_HEIGHT_SQL = 'SELECT height FROM proven_txs WHERE txid = ? LIMIT 1'
209
+
207
210
  /**
208
211
  * The transactions that have reserved the given outpoints, by `reference`.
209
212
  *
@@ -224,60 +227,6 @@ export function spendingReferencesSql(pairCount: number): string {
224
227
  )
225
228
  }
226
229
 
227
- /**
228
- * Release every input still held by a definitively-invalid vault deposit tx2.
229
- *
230
- * The predicate is deliberately narrow, every clause load-bearing:
231
- * - `t.status = 'failed'` AND its proven_tx_req is `'invalid'`: the network
232
- * REJECTED the spender outright — it can never be mined, so releasing its
233
- * inputs cannot enable a real double-spend. A 'failed' transaction without
234
- * an 'invalid' req (say, a broadcast that timed out but may still have
235
- * propagated) is NOT touched.
236
- * - the spender carries the 'vault-deposit' label: this heal exists for the
237
- * deposit flow and must not reinterpret failures of anything else.
238
- *
239
- * Why this exists: when tx2 fails, updateTransactionStatus('failed') restores
240
- * its inputs, but markStaleInputsAsSpent then re-strands them — it asks the
241
- * indexers whether tx1's staging output is a UTXO seconds after tx1 broadcast,
242
- * and indexer lag answers "no". abortAction cannot fix it afterwards because
243
- * 'failed' is in its unAbortable list.
244
- */
245
- export const RELEASE_STRANDED_VAULT_STAGING_SQL = `
246
- UPDATE outputs SET spendable = 1, spentBy = NULL
247
- WHERE spendable = 0 AND spentBy IN (
248
- SELECT t.transactionId FROM transactions t
249
- JOIN proven_tx_reqs r ON r.txid = t.txid AND r.status = 'invalid'
250
- JOIN tx_labels_map m ON m.transactionId = t.transactionId AND m.isDeleted = 0
251
- JOIN tx_labels l ON l.txLabelId = m.txLabelId AND l.label = 'vault-deposit'
252
- WHERE t.status = 'failed'
253
- )
254
- `.trim()
255
-
256
- /**
257
- * Companion to RELEASE_STRANDED_VAULT_STAGING_SQL: clear a STALE spentBy on
258
- * coins that are already spendable again.
259
- *
260
- * The other arm of the same failure. When the invalid spender's inputs are
261
- * restored, updateOutput({spendable: true, spentBy: undefined}) re-lists the
262
- * coin — but sqlUpdate drops undefined values, so spentBy keeps pointing at
263
- * the failed transaction (which HAS a txid). createAction's reservation check
264
- * (markKnownInputsSpent) refuses any input whose spentBy names a tx with a
265
- * txid — WITHOUT checking whether that tx is 'failed' — so every later spend
266
- * of the coin throws WERR_REVIEW_ACTIONS forever. Same deliberately narrow
267
- * predicate: only a 'failed' spender whose req the network rejected outright
268
- * ('invalid') and that carries the vault-deposit label.
269
- */
270
- export const RELEASE_STALE_VAULT_STAGING_SPENTBY_SQL = `
271
- UPDATE outputs SET spentBy = NULL
272
- WHERE spendable = 1 AND spentBy IN (
273
- SELECT t.transactionId FROM transactions t
274
- JOIN proven_tx_reqs r ON r.txid = t.txid AND r.status = 'invalid'
275
- JOIN tx_labels_map m ON m.transactionId = t.transactionId AND m.isDeleted = 0
276
- JOIN tx_labels l ON l.txLabelId = m.txLabelId AND l.label = 'vault-deposit'
277
- WHERE t.status = 'failed'
278
- )
279
- `.trim()
280
-
281
230
  /** Split a `txid.vout` or `txid:vout` outpoint into its parts, or null. */
282
231
  export function splitOutpoint(outpoint: string): { txid: string; vout: number } | null {
283
232
  const m = /^([0-9a-fA-F]{64})[.:](\d+)$/.exec(outpoint.trim())
@@ -4,11 +4,14 @@
4
4
  * Handles specOp patterns (noSend actions, failed actions, etc.)
5
5
  */
6
6
  import type { ListActionsResult, Validation } from '@bsv/sdk'
7
- import type { AuthId } from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
8
7
  import type { StorageExpoSQLite } from '../StorageExpoSQLite'
9
- import { getLabelToSpecOp } from '@bsv/wallet-toolbox-mobile/out/src/storage/methods/ListActionsSpecOp'
10
- import { isListActionsSpecOp } from '@bsv/wallet-toolbox-mobile/out/src/sdk/types'
11
- import { parseBrc114ActionTimeLabels, makeBrc114ActionTimeLabel } from '@bsv/wallet-toolbox-mobile/out/src/utility/brc114ActionTimeLabels'
8
+ import {
9
+ getLabelToSpecOp,
10
+ makeBrc114ActionTimeLabel,
11
+ parseBrc114ActionTimeLabels,
12
+ sdk as toolboxSdk
13
+ } from '@bsv/wallet-toolbox-mobile'
14
+ import type { AuthId } from '../../toolboxTypes'
12
15
 
13
16
  export async function listActionsSql(
14
17
  storage: StorageExpoSQLite,
@@ -32,7 +35,7 @@ export async function listActionsSql(
32
35
  let specOpLabels: string[] = []
33
36
  let labels: string[] = []
34
37
  for (const label of ordinaryLabelsPreSpecOp) {
35
- if (isListActionsSpecOp(label)) {
38
+ if (toolboxSdk.isListActionsSpecOp(label)) {
36
39
  specOp = getLabelToSpecOp()[label]
37
40
  } else {
38
41
  labels.push(label)
@@ -4,10 +4,11 @@
4
4
  * Handles specOp patterns (wallet balance, invalid change, etc.)
5
5
  */
6
6
  import type { ListOutputsResult, Validation } from '@bsv/sdk'
7
- import type { AuthId } from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
8
7
  import type { StorageExpoSQLite } from '../StorageExpoSQLite'
9
- import { getListOutputsSpecOp } from '@bsv/wallet-toolbox-mobile/out/src/storage/methods/ListOutputsSpecOp'
8
+ import { getListOutputsSpecOp } from '@bsv/wallet-toolbox-mobile'
10
9
  import { devLog, isLoggingEnabled } from '../../logging'
10
+ import { BALANCE_TX_STATUS } from './walletBalanceSql'
11
+ import type { AuthId } from '../../toolboxTypes'
11
12
 
12
13
  export async function listOutputsSql(
13
14
  storage: StorageExpoSQLite,
@@ -83,7 +84,7 @@ export async function listOutputsSql(
83
84
  // Build find args — specOps with ignoreLimit fetch ALL outputs
84
85
  const findArgs: any = {
85
86
  partial,
86
- txStatus: ['completed', 'unproven', 'nosend'],
87
+ txStatus: BALANCE_TX_STATUS,
87
88
  noScript: true
88
89
  }
89
90
  if (!specOp || !specOp.ignoreLimit) {
@@ -128,12 +129,15 @@ export async function listOutputsSql(
128
129
  // Count total
129
130
  if (outputs.length === limit) {
130
131
  r.totalOutputs = await storage.countOutputs(
131
- { partial, txStatus: ['completed', 'unproven', 'nosend'], noScript: true } as any,
132
+ { partial, txStatus: BALANCE_TX_STATUS, noScript: true } as any,
132
133
  tagIds.length > 0 ? tagIds : undefined,
133
134
  isQueryModeAll
134
135
  )
135
136
  } else {
136
- r.totalOutputs = outputs.length
137
+ // A short page proves this is the end, but its length is only the suffix
138
+ // after `offset`. Return the stable total for the whole result set, as the
139
+ // BRC-100 pagination contract and listActionsSql both require.
140
+ r.totalOutputs = offset + outputs.length
137
141
  }
138
142
 
139
143
  // Apply specOp processing
@@ -92,6 +92,21 @@ export async function insertOfflineAction(
92
92
  )
93
93
  }
94
94
 
95
+ /**
96
+ * The one row for a txid, or undefined.
97
+ *
98
+ * Separate from `findOfflineActions` because its caller
99
+ * (`holdSentPaymentOffline`) needs to tell "no row" from "a row in some state"
100
+ * before it decides between an insert and an advance — `INSERT OR IGNORE`
101
+ * proves re-insert idempotency only, never a state advance, and reading that
102
+ * distinction wrong is how a parked payment stayed parked forever (FIX F).
103
+ */
104
+ export async function findOfflineActionByTxid(db: OfflineDb, txid: string): Promise<OfflineActionRow | undefined> {
105
+ return ((await db.getFirstAsync('SELECT * FROM offline_actions WHERE txid = ?', [txid])) ?? undefined) as
106
+ | OfflineActionRow
107
+ | undefined
108
+ }
109
+
95
110
  export async function findOfflineActions(
96
111
  db: OfflineDb,
97
112
  filter: { status?: OfflineActionStatus[]; userId?: number } = {}
@@ -18,9 +18,8 @@
18
18
  * database reads, writes and logging, which is validated on device.
19
19
  */
20
20
  import { Beef } from '@bsv/sdk'
21
- import { attemptToPostReqsToNetwork } from '@bsv/wallet-toolbox-mobile/out/src/storage/methods/attemptToPostReqsToNetwork'
22
- import { EntityProvenTxReq } from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/entities'
23
- import type { TableProvenTxReq, TableTransaction } from '@bsv/wallet-toolbox-mobile/out/src/storage/schema/tables'
21
+ import { attemptToPostReqsToNetwork, EntityProvenTxReq } from '@bsv/wallet-toolbox-mobile'
22
+ import type { TableProvenTxReq, TableTransaction } from '@bsv/wallet-toolbox-mobile'
24
23
  import type { StorageExpoSQLite } from '../StorageExpoSQLite'
25
24
  import { findOfflineActions, updateOfflineAction, type OfflineActionRow, type OfflineDb } from './offlineActions'
26
25
  import {
@@ -33,6 +32,14 @@ import {
33
32
  type PostOutcome
34
33
  } from '../../offline/plan'
35
34
  import { descendantsOf, type OrderableTx } from '../../offline/order'
35
+ import { postTokenStep, reconcileSettlements, type TokenFrameSource } from '../../mandala/drain'
36
+ import type {
37
+ AdmissionVerifier,
38
+ CoverFn,
39
+ SettlementStore,
40
+ SubmitFn,
41
+ TokenSettlementRow
42
+ } from '../../mandala/types'
36
43
  import { devLog } from '../../logging'
37
44
  import { getOnline } from '../../net/online'
38
45
 
@@ -73,25 +80,112 @@ interface HeldAction {
73
80
  api: TableProvenTxReq
74
81
  }
75
82
 
83
+ /**
84
+ * Everything the Mandala settlement drain needs that this module cannot do
85
+ * itself. Absent for a wallet with no token payments — then not one line of
86
+ * behaviour below changes.
87
+ *
88
+ * `cover` and `submit` are injected rather than imported because one is a pure
89
+ * verifier over local evidence and the other is a network call; keeping both
90
+ * out of here is what leaves this file a database-and-ordering module.
91
+ */
92
+ export interface OfflineTokenDeps {
93
+ store: SettlementStore
94
+ cover: CoverFn
95
+ submit: SubmitFn
96
+ /**
97
+ * FIX H / wire contract §9.10. THIS WALLET's configured overlay identity key
98
+ * and the σ_I verifier that checks against it — the only thing that may let a
99
+ * cached admission skip a `/submit`, and the filter on what the evidence
100
+ * cache is allowed to keep at all. Absent and nothing is trusted: every
101
+ * ancestor is submitted, which is free and always correct.
102
+ */
103
+ overlayIdentityKey?: string
104
+ verifyAdmission?: AdmissionVerifier
105
+ /**
106
+ * Clear `@bsv/mandala`'s tx-journal entry for a tip this pass really
107
+ * broadcast. See `TokenStepDeps.journalRemove`; passed straight through so
108
+ * the drain's own broadcast is the only thing that can clear one.
109
+ */
110
+ journalRemove?: (txid: string) => Promise<void>
111
+ /**
112
+ * FIX G: every durable token frame this device holds, re-read each pass so
113
+ * the evidence tables and the settlement rows are re-derived idempotently
114
+ * before anything is decided. Supplied by the caller because only it can
115
+ * open a payer-side sealed `framePayload`.
116
+ */
117
+ frames?: () => Promise<TokenFrameSource[]>
118
+ }
119
+
76
120
  export async function processOfflineActions(args: {
77
121
  storage: StorageExpoSQLite
78
122
  /** Injected so tests can supply a missing ancestor without hitting the network. */
79
123
  refetchBeef?: (txid: string) => Promise<number[] | undefined>
124
+ /** Mandala settlement. Omit entirely and the drain behaves exactly as before. */
125
+ token?: OfflineTokenDeps
80
126
  }): Promise<ProcessOfflineActionsResult> {
81
- const { storage, refetchBeef } = args
127
+ const { storage, refetchBeef, token } = args
82
128
  const db = storage.sqliteDb
83
129
  if (!db) return { sent: 0, rejected: 0, stopped: true, stalledOn: 'the database is not open' }
84
130
 
131
+ // Before anything is read or decided: re-derive the settlement evidence from
132
+ // the frame bytes that are already durable (FIX G). Purely local, so it runs
133
+ // even on a pass that turns out to be offline, and it is allowed to fail —
134
+ // it is a cache-population step, and the next tick repeats it.
135
+ if (token?.frames) {
136
+ try {
137
+ const r = await reconcileSettlements({
138
+ store: token.store,
139
+ sources: await token.frames(),
140
+ overlayIdentityKey: token.overlayIdentityKey,
141
+ verifyAdmission: token.verifyAdmission
142
+ })
143
+ if (r.errors.length > 0) devLog('[processOfflineActions] evidence reconciliation reported:', r.errors)
144
+ if (r.dropped > 0) {
145
+ // FIX H: counterparty-supplied σ_I that did not verify against this
146
+ // wallet's configured overlay key. Not an error and not a decline —
147
+ // the ancestors are simply submitted rather than skipped.
148
+ devLog(`[processOfflineActions] dropped ${r.dropped} unverifiable admission(s) from frame evidence`)
149
+ }
150
+ } catch (e) {
151
+ devLog('[processOfflineActions] could not reconcile token settlements:', e)
152
+ }
153
+ }
154
+
85
155
  // 'posting' is included so a run interrupted mid-flight resumes rather than
86
156
  // stranding its rows. Re-posting is safe: a transaction the network already has
87
157
  // comes back as accepted (ARC's `SEEN_ON_NETWORK`), and a request storage has
88
158
  // already recorded as delivered is not posted again at all — see `postOwned`.
89
- const rows = await findOfflineActions(db, { status: ['queued', 'posting'] })
90
- if (rows.length === 0) return { sent: 0, rejected: 0, stopped: false }
159
+ const queued = await findOfflineActions(db, { status: ['queued', 'posting'] })
160
+ if (queued.length === 0) return { sent: 0, rejected: 0, stopped: false }
161
+
162
+ // BEFORE the connectivity probe, because it needs none: a row whose request
163
+ // storage already records as delivered ('unmined', 'completed', …) has
164
+ // nothing left to post. Until now that fact was only read inside `postOwned`,
165
+ // i.e. only on a pass that got past the probe and stepped the row — so a
166
+ // token tip that `settleNow` broadcast the moment it was handed over, or that
167
+ // the payee broadcast and this device later saw mined, kept its queue row at
168
+ // 'queued' (blue "settled", the "waiting" banner, no Refresh chip) whenever
169
+ // the drain was offline, stalled on a sibling, or never reached the step
170
+ // (2026-09-16).
171
+ const rows: OfflineActionRow[] = []
172
+ let sent = 0
173
+ for (const row of queued) {
174
+ const api = await findReq(storage, row.txid)
175
+ if (api && outcomeFromReqStatus(api.status) === 'success') {
176
+ devLog(`[processOfflineActions] storage already records '${api.status}' for ${row.txid}; closing its queue row`)
177
+ await updateOfflineAction(db, row.txid, { status: 'sent' })
178
+ if (token) await closeSettlementAsBroadcast(token.store, row.txid)
179
+ sent++
180
+ } else {
181
+ rows.push(row)
182
+ }
183
+ }
184
+ if (rows.length === 0) return { sent, rejected: 0, stopped: false }
91
185
 
92
186
  if (!(await probeOnline())) {
93
187
  devLog(`[processOfflineActions] offline, leaving ${rows.length} action(s) queued`)
94
- return { sent: 0, rejected: 0, stopped: true }
188
+ return { sent, rejected: 0, stopped: true }
95
189
  }
96
190
 
97
191
  // Merge every held request's BEEF into one graph. Anything that cannot be read
@@ -157,7 +251,6 @@ export async function processOfflineActions(args: {
157
251
  const txs: OrderableTx[] = merged.txs
158
252
  const plan = planRelease({ rows, txs })
159
253
 
160
- let sent = 0
161
254
  let rejected = 0
162
255
  const resolved = new Set<string>()
163
256
  const skip = new Set<string>()
@@ -185,7 +278,36 @@ export async function processOfflineActions(args: {
185
278
  }
186
279
  if (action) await updateOfflineAction(db, step.txid, { status: 'posting' })
187
280
 
188
- const outcome = action ? await postOwned(storage, action.api) : await postForeign(storage, merged, step.txid)
281
+ // The ONE token branch. A transaction with a `token_settlements` row may
282
+ // not be broadcast until the issuer's overlay has admitted it and every
283
+ // unadmitted token ancestor it spends — so the ordinary post becomes
284
+ // `postTokenStep`'s injected `broadcast`, reached only after `/submit`
285
+ // says yes. Everything after this line — applyOutcome, the cascade, the
286
+ // requeue — is unchanged, because `postTokenStep` returns the same
287
+ // `PostOutcome` shape a BSV post does.
288
+ const read = token ? await readSettlement(token.store, step.txid) : { ok: true as const, row: undefined }
289
+ const broadcast = async () =>
290
+ action ? await postOwned(storage, action.api) : await postForeign(storage, merged, step.txid)
291
+ const outcome = !read.ok
292
+ ? // The read failed, so this step does not know whether it is a token
293
+ // transaction. Stall it: `serviceError` leaves every row where it was
294
+ // and retries the whole prefix next pass.
295
+ ('serviceError' as PostOutcome)
296
+ : read.row
297
+ ? await postTokenStep(
298
+ {
299
+ store: token!.store,
300
+ cover: token!.cover,
301
+ submit: token!.submit,
302
+ overlayIdentityKey: token!.overlayIdentityKey,
303
+ verifyAdmission: token!.verifyAdmission,
304
+ journalRemove: token!.journalRemove,
305
+ broadcast
306
+ },
307
+ read.row,
308
+ step
309
+ )
310
+ : await broadcast()
189
311
  // A cascade needs to see what spends the refused transaction, and beefs only
190
312
  // reach backwards, so the graph the queue built cannot contain a spender that
191
313
  // is not itself queued. Widened only when a cascade is actually about to run,
@@ -233,6 +355,35 @@ export async function processOfflineActions(args: {
233
355
  }
234
356
  }
235
357
 
358
+ /**
359
+ * Whether this txid has a settlement row — or whether the question could not be
360
+ * answered at all.
361
+ *
362
+ * The three outcomes are deliberately distinct, and the third is the fix. A
363
+ * thrown read (a locked database, a schema without these tables, a corrupt
364
+ * page) USED to fall back to `undefined`, which the caller cannot tell from
365
+ * "this is an ordinary BSV transaction" — so a read fault sent an unadmitted
366
+ * token tip straight to `broadcast()`, defeating the whole §4.3 gate on exactly
367
+ * the kind of transient fault the drain is built to survive. "I could not tell"
368
+ * must never resolve to "go ahead": the caller turns it into `serviceError`,
369
+ * the rows stay where they are, and the next pass asks again.
370
+ *
371
+ * The token guard in `StorageExpoSQLite.attemptToPostReqsToNetwork` reads the
372
+ * same table and would usually catch the same case — but it is reached only
373
+ * from `shareReqsWithWorld`, and `postForeign` does not go through it at all.
374
+ * Two independent barriers are worth having; one of them failing open is not.
375
+ */
376
+ type SettlementRead = { ok: true; row: TokenSettlementRow | undefined } | { ok: false }
377
+
378
+ async function readSettlement(store: SettlementStore, txid: string): Promise<SettlementRead> {
379
+ try {
380
+ return { ok: true, row: await store.getSettlement(txid) }
381
+ } catch (e) {
382
+ devLog(`[processOfflineActions] could not read the settlement row for ${txid}:`, e)
383
+ return { ok: false }
384
+ }
385
+ }
386
+
236
387
  async function tryMergeRefetchedBeef(
237
388
  target: Beef,
238
389
  txid: string,
@@ -367,6 +518,20 @@ async function postOwned(storage: StorageExpoSQLite, api: TableProvenTxReq): Pro
367
518
  return recorded
368
519
  }
369
520
 
521
+ // The second witness: the network itself. A nearby payment is broadcast by
522
+ // whichever side has signal first, and that is routinely the PAYEE — so the
523
+ // payer's own request is still 'nosend' for a transaction that is already in
524
+ // a mempool or a block. Re-posting it is at best a no-op and at worst a
525
+ // broadcaster's "inputs already spent"-shaped error that `outcomeOfOwnedPost`
526
+ // can only read as serviceError: re-held, re-queued, and stuck on every tick
527
+ // while the activity list says settled (2026-09-16). Asking first costs one
528
+ // status lookup and lets storage record what already happened.
529
+ if (await networkAlreadyHas(storage, api.txid)) {
530
+ devLog(`[processOfflineActions] the network already has ${api.txid}; recording delivery without a post`)
531
+ await recordDeliveredElsewhere(storage, api)
532
+ return 'success'
533
+ }
534
+
370
535
  const attemptsBefore = api.attempts
371
536
  const req = new EntityProvenTxReq(api)
372
537
  // What to restore each transaction to, read before the post overwrites it.
@@ -412,6 +577,90 @@ async function postOwned(storage: StorageExpoSQLite, api: TableProvenTxReq): Pro
412
577
  return 'serviceError'
413
578
  }
414
579
 
580
+ /**
581
+ * `postOwned` for ONE txid, for a caller outside the queue loop.
582
+ *
583
+ * The Mandala runtime's `settleNow` needs a broadcast to hand `postTokenStep`
584
+ * the moment a hand-over lands, and it must be the SAME broadcast the drain
585
+ * uses — status transitions, history notes, `markStaleInputsAsSpent`, the
586
+ * re-hold on a service error, and the "storage is the witness, not the reported
587
+ * status" rule all live in `postOwned` and must not be reimplemented beside it.
588
+ * So this is the whole of the new surface: find the request, post it, report
589
+ * the same `PostOutcome`.
590
+ *
591
+ * A txid with no request of this wallet's own comes back `'serviceError'`
592
+ * rather than being posted some other way. That is deliberate: a FOREIGN
593
+ * ancestor is only ever broadcast as part of an ordered release over the merged
594
+ * graph (`postForeign`, from the plan), and guessing at that order from one
595
+ * txid is exactly the out-of-dependency-order broadcast this engine exists to
596
+ * prevent. `'serviceError'` leaves the row untouched for the next drain pass,
597
+ * which has the graph.
598
+ */
599
+ export async function postOwnedByTxid(storage: StorageExpoSQLite, txid: string): Promise<PostOutcome> {
600
+ const api = await findReq(storage, txid)
601
+ if (!api) {
602
+ devLog(`[processOfflineActions] no request of our own for ${txid}; leaving its broadcast to the drain`)
603
+ return 'serviceError'
604
+ }
605
+ return await postOwned(storage, api)
606
+ }
607
+
608
+ /**
609
+ * Whether the network already has `txid`, by the services' own status lookup
610
+ * ('mined' or 'known'). Every failure — no such service, a transport fault, an
611
+ * unexpected shape — is `false`: the answer then falls back to the ordinary
612
+ * post, whose own result decides. Never a reason to stall.
613
+ */
614
+ async function networkAlreadyHas(storage: StorageExpoSQLite, txid: string): Promise<boolean> {
615
+ try {
616
+ const services = storage.getServices() as {
617
+ getStatusForTxids?: (txids: string[]) => Promise<{ results?: { txid: string; status: string }[] }>
618
+ }
619
+ if (typeof services.getStatusForTxids !== 'function') return false
620
+ const r = await services.getStatusForTxids([txid])
621
+ const status = r.results?.find(x => x.txid === txid)?.status
622
+ return status === 'mined' || status === 'known'
623
+ } catch (e) {
624
+ devLog(`[processOfflineActions] could not ask the network whether it has ${txid}:`, e)
625
+ return false
626
+ }
627
+ }
628
+
629
+ /**
630
+ * Record that `txid` reached the network by someone else's hand, exactly as the
631
+ * toolbox records its own successful post (`updateReqsFromAggregateResults`:
632
+ * request 'unmined', transaction 'unproven'). Only a transaction still at a
633
+ * pre-broadcast status is moved; anything past that is left to the monitor,
634
+ * which owns proofs and 'completed'.
635
+ */
636
+ async function recordDeliveredElsewhere(storage: StorageExpoSQLite, api: TableProvenTxReq): Promise<void> {
637
+ await storage.updateProvenTxReq(api.provenTxReqId, { status: 'unmined' })
638
+ const req = new EntityProvenTxReq(api)
639
+ for (const transactionId of req.notify.transactionIds ?? []) {
640
+ try {
641
+ const tx = (await storage.findTransactions({ partial: { transactionId }, noRawTx: true }))[0]
642
+ if (tx && (tx.status === 'nosend' || tx.status === 'sending')) {
643
+ await storage.updateTransactionStatus('unproven', transactionId)
644
+ }
645
+ } catch (e) {
646
+ devLog(`[processOfflineActions] could not promote transaction ${transactionId} of ${api.txid}:`, e)
647
+ }
648
+ }
649
+ }
650
+
651
+ /**
652
+ * The settlement twin of closing a queue row on a recorded delivery: the same
653
+ * advance `broadcastAdmittedTip` makes after a real post. Best-effort — the
654
+ * queue row is the durable fact, and `reconcileSettlements` re-derives rows.
655
+ */
656
+ async function closeSettlementAsBroadcast(store: SettlementStore, txid: string): Promise<void> {
657
+ try {
658
+ await store.advanceSettlement(txid, ['admitted', 'submitting', 'held', 'handed_over'], 'broadcast')
659
+ } catch (e) {
660
+ devLog(`[processOfflineActions] could not close the settlement row of ${txid} as broadcast:`, e)
661
+ }
662
+ }
663
+
415
664
  /**
416
665
  * Post a foreign ancestor that arrived inside someone's BEEF.
417
666
  *
@@ -424,6 +673,13 @@ async function postOwned(storage: StorageExpoSQLite, api: TableProvenTxReq): Pro
424
673
  * one cannot end up posting the same graph to two different sets of providers.
425
674
  */
426
675
  async function postForeign(storage: StorageExpoSQLite, merged: Beef, txid: string): Promise<PostOutcome> {
676
+ // Same witness as `postOwned`: an ancestor that arrived inside a counterparty's
677
+ // BEEF was usually broadcast by that counterparty already, and a failed
678
+ // re-post of it would block every owned transaction behind it.
679
+ if (await networkAlreadyHas(storage, txid)) {
680
+ devLog(`[processOfflineActions] the network already has foreign ancestor ${txid}; not posting`)
681
+ return 'success'
682
+ }
427
683
  try {
428
684
  const atomic = Beef.fromBinary(merged.toBinaryAtomic(txid))
429
685
  const results = await storage.getServices().postBeef(atomic, [txid])
@@ -14,9 +14,14 @@ import { devLog } from '../../logging'
14
14
  const SAFE_REQ_STATUSES = new Set(['invalid', 'doubleSpend'])
15
15
 
16
16
  export type ReviewStatusDb = {
17
+ // Method shorthand (not arrow-style properties) is intentional: it keeps this
18
+ // structurally assignable from node:sqlite's DatabaseSync, whose statement
19
+ // methods take the narrower SQLInputValue type rather than unknown. Arrow-style
20
+ // properties are checked contravariantly under strictFunctionTypes and reject
21
+ // that narrower parameter type; method shorthand is checked bivariantly.
17
22
  prepare(sql: string): {
18
- all: (...params: unknown[]) => unknown[]
19
- run: (...params: unknown[]) => unknown
23
+ all(...params: unknown[]): unknown[]
24
+ run(...params: unknown[]): unknown
20
25
  }
21
26
  }
22
27
 
@@ -17,11 +17,23 @@
17
17
  * the lock the writes need.
18
18
  */
19
19
 
20
- /** The basket the toolbox counts as the wallet balance, and the transaction
21
- * states in which an output's satoshis are really yours. Mirrors what
22
- * `listOutputsSql` builds for every other outputs query. */
20
+ /**
21
+ * The basket the toolbox counts as the wallet balance, and the transaction
22
+ * states in which an output's satoshis are really yours. `listOutputsSql`
23
+ * imports this rather than repeating it, so there is one definition.
24
+ *
25
+ * The rule is "signed and committed": 'nosend' is signed and deliberately
26
+ * held, 'sending' is signed and already handed to the broadcaster, 'unproven'
27
+ * is on-chain awaiting its proof, 'completed' is mined. Omitting 'sending'
28
+ * made a transaction's own outputs vanish for the seconds between the
29
+ * broadcast and the monitor promoting the row to 'unproven' — the wallet's
30
+ * change, and a vault withdrawal's re-lock remainder, both read as gone.
31
+ *
32
+ * 'unprocessed' stays out deliberately (see walletBalanceSql.test.ts), as do
33
+ * 'unsigned', 'nonfinal' and 'failed'.
34
+ */
23
35
  export const BALANCE_BASKET = 'default'
24
- export const BALANCE_TX_STATUS = ['completed', 'unproven', 'nosend']
36
+ export const BALANCE_TX_STATUS = ['completed', 'unproven', 'sending', 'nosend']
25
37
 
26
38
  /** The slice of StorageExpoSQLite this needs. Structural, so a caller can pass
27
39
  * the real provider and a test can pass one backed by any SQLite handle. */