@bsv/expo-wallet-toolbox 0.21.0 → 0.22.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 (78) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/README.md +78 -13
  3. package/core/contacts/contactActivity.ts +48 -28
  4. package/core/contacts/contactsStore.ts +2 -2
  5. package/core/context/WalletContext.tsx +166 -219
  6. package/core/demo/demoAssets.ts +8 -10
  7. package/core/demo/demoLedger.ts +32 -38
  8. package/core/demo/demoMandalaRuntime.ts +67 -49
  9. package/core/demo/index.ts +1 -1
  10. package/core/i18n/translations.tsx +72 -0
  11. package/core/index.ts +55 -37
  12. package/core/localpay/build.ts +110 -569
  13. package/core/localpay/codec.ts +190 -93
  14. package/core/localpay/pending.ts +217 -202
  15. package/core/localpay/session.ts +99 -25
  16. package/core/localpay/types.ts +6 -5
  17. package/core/localpay/verify.ts +118 -173
  18. package/core/mandala/abortGuard.ts +97 -120
  19. package/core/mandala/accessPolicy.ts +133 -0
  20. package/core/mandala/assets.ts +370 -0
  21. package/core/mandala/colorGuard.ts +178 -0
  22. package/core/mandala/colorModule.ts +82 -0
  23. package/core/mandala/createRuntime.ts +483 -2392
  24. package/core/mandala/handle.ts +694 -0
  25. package/core/mandala/kvStore.ts +105 -0
  26. package/core/mandala/nearby.ts +185 -0
  27. package/core/mandala/receipt.ts +121 -0
  28. package/core/mandala/runtime.ts +166 -312
  29. package/core/mandala/settle.ts +540 -0
  30. package/core/mandala/transferJournal.ts +395 -0
  31. package/core/mandala/types.ts +61 -311
  32. package/core/networks.ts +5 -5
  33. package/core/offline/cancelParked.ts +80 -63
  34. package/core/offline/payerHold.ts +52 -118
  35. package/core/parsePeerPayURI.ts +25 -12
  36. package/core/pay/rails/handle.ts +15 -14
  37. package/core/pay/rails/index.ts +5 -3
  38. package/core/pay/rails/nearby.ts +25 -87
  39. package/core/profiles/assertProfileEmpty.ts +19 -10
  40. package/core/services/vault/guard.ts +5 -4
  41. package/core/storage/StorageExpoSQLite.ts +93 -229
  42. package/core/storage/methods/processOfflineActions.ts +86 -136
  43. package/core/storage/schema/createTables.ts +9 -184
  44. package/package.json +6 -5
  45. package/ui/components/pay/AssetPicker.tsx +2 -2
  46. package/ui/components/pay/HandleReceive.tsx +4 -4
  47. package/ui/components/pay/NearbyFlow.tsx +324 -239
  48. package/ui/components/pay/RequestHub.tsx +10 -0
  49. package/ui/components/pay/UniversalSend.tsx +31 -28
  50. package/ui/components/pay/useRecipientInput.ts +2 -2
  51. package/ui/components/ui/PermissionSheet.tsx +94 -160
  52. package/ui/components/ui/colorPrompt.ts +236 -0
  53. package/ui/components/wallet/AmountInput.tsx +9 -6
  54. package/ui/components/wallet/AssetAmount.tsx +6 -6
  55. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  56. package/ui/components/wallet/Balance.tsx +3 -1
  57. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  58. package/ui/components/wallet/tokenEviction.ts +9 -9
  59. package/ui/hooks/useMandala.ts +6 -6
  60. package/ui/hooks/useSpendableBalance.ts +3 -1
  61. package/ui/importDatabases.ts +1 -1
  62. package/ui/screens/PayScreen.tsx +14 -20
  63. package/ui/screens/SettingsScreen.tsx +3 -1
  64. package/ui/screens/WalletCheckScreen.tsx +7 -2
  65. package/ui/screens/WalletHomeScreen.tsx +40 -14
  66. package/ui/screens/tokenRowTitle.ts +28 -15
  67. package/ui/tokenFormat.ts +133 -69
  68. package/ui/tokenStatus.ts +5 -8
  69. package/core/localpay/settlementAck.ts +0 -155
  70. package/core/mandala/basketMigration.ts +0 -166
  71. package/core/mandala/bundle.ts +0 -244
  72. package/core/mandala/drain.ts +0 -754
  73. package/core/mandala/inboxPrehold.ts +0 -193
  74. package/core/mandala/permissionModule.ts +0 -931
  75. package/core/mandala/resendTransfer.ts +0 -178
  76. package/core/mandala/settlementStore.ts +0 -434
  77. package/core/mandala/token.ts +0 -45
  78. package/core/offline/tokenFrames.ts +0 -197
@@ -26,6 +26,7 @@ import type { BindValue } from '../storage/methods/offlineActions'
26
26
  import { PENDING_JOURNAL_KEY } from '../identity/handleRegistry/registration'
27
27
  import { PENDING_KEY } from '../localpay/pending'
28
28
  import { getOutboxEntriesStrict, unsentEntries } from '../peerpay/outbox'
29
+ import { TERMINAL_TRANSFER_STATES } from '../mandala/types'
29
30
 
30
31
  /** Why a profile cannot be removed. One code per thing found, for the UI to explain. */
31
32
  export type RemovalBlocker =
@@ -87,13 +88,14 @@ export interface AssertProfileEmptyDeps {
87
88
  */
88
89
  creditInbox: () => Promise<{ attention: number; pending: boolean }>
89
90
  /**
90
- * The Mandala runtime's `balances()`, when this wallet has one. Belt and
91
- * braces only: the runtime's own token listing swallows its errors into an
92
- * empty list, so a zero here proves less than it appears to. The SQL checks
93
- * on outputs and settlements are what actually cover tokens, which is why
94
- * this may be left out.
91
+ * The Mandala runtime's `balances()`, when this wallet has one: exact
92
+ * `bigint` units (W10), `units` from the `p color balance` view and
93
+ * `offlineUnits` from the `color_offline` inventory records. Belt and braces
94
+ * only: the SQL checks on outputs and the `color_transfers` journal are what
95
+ * actually cover tokens, which is why this may be left out. Any figure that
96
+ * is not exactly `0n` — including one that is not a bigint at all — blocks.
95
97
  */
96
- mandalaBalances?: () => Promise<ReadonlyArray<{ baseUnits: number; unsettledBaseUnits: number }>>
98
+ mandalaBalances?: () => Promise<ReadonlyArray<{ units: bigint; offlineUnits: bigint }>>
97
99
  }
98
100
 
99
101
  // Terminal lists, not blocking lists — see the header.
@@ -103,9 +105,14 @@ const OPEN_TRANSACTIONS =
103
105
  // Equal to queued/posting/parked/import_hold for every status there is.
104
106
  const OPEN_OFFLINE_ACTIONS =
105
107
  "SELECT 1 AS found FROM offline_actions WHERE userId = ? AND status NOT IN ('sent', 'rejected', 'acknowledged') LIMIT 1"
106
- // No userId column: this table is one database's worth, and a database is one profile's.
107
- const OPEN_SETTLEMENTS =
108
- "SELECT 1 AS found FROM token_settlements WHERE state NOT IN ('broadcast', 'admitted', 'refused', 'orphaned') LIMIT 1"
108
+ // The `color_transfers` journal (plan 07 W1). No userId column: this table is
109
+ // one database's worth, and a database is one profile's. Terminal states come
110
+ // from the journal's own list, so a state added later blocks until somebody
111
+ // decides it should not. A file without the table (never booted since the
112
+ // 1Color migration) throws here and reads as `check-failed`: fail closed.
113
+ const OPEN_SETTLEMENTS = `SELECT 1 AS found FROM color_transfers WHERE state NOT IN (${TERMINAL_TRANSFER_STATES.map(
114
+ s => `'${s}'`
115
+ ).join(', ')}) LIMIT 1`
109
116
  // A corrupt localpay queue is copied here and the live key reset (pending.ts `readAll`).
110
117
  const QUARANTINED_PENDING =
111
118
  "SELECT 1 AS found FROM key_value_store WHERE key LIKE 'localpay\\_pending\\_corrupt\\_%' ESCAPE '\\' LIMIT 1"
@@ -169,7 +176,9 @@ export async function assertProfileEmpty(
169
176
  await check('token-balance', async () => {
170
177
  if (!deps.mandalaBalances) return false
171
178
  const balances = await deps.mandalaBalances()
172
- return balances.some(b => !(b.baseUnits === 0 && b.unsettledBaseUnits === 0))
179
+ // `units` already includes the offline part, but the two views are
180
+ // separate snapshots (0207:657-660), so each is checked on its own.
181
+ return balances.some(b => !(b.units === 0n && b.offlineUnits === 0n))
173
182
  })
174
183
  await check('localpay-pending', () => receivedPaymentsWaiting(storage))
175
184
  await check('peerpay-outbox', async () => unsentEntries(await getOutboxEntriesStrict(storage)).length > 0)
@@ -120,10 +120,11 @@ const PRIVILEGED_CAPABLE = new Set<keyof WalletInterface>([
120
120
  * own vault code ever reaches it. */
121
121
  const VAULT_PROTOCOL_NAMES = new Set(['vault', 'vault salt', 'vault marker', 'vault descriptor', 'vault meta'])
122
122
 
123
- /** Mandala's token protocol (`[2, 'p mandala token']`) is not reserved here:
124
- * its `'p '` prefix routes every call under it to MandalaTokenModule
125
- * (core/mandala/permissionModule.ts), which binds connected-app signatures to
126
- * transactions the user approved.
123
+ /** The 1Color token protocols (`[2, 'p color <assetTag> <prefix> <suffix>']`)
124
+ * are not reserved here: their `'p '` prefix routes every call under them to
125
+ * the BRC-207 color module (`permissionModules.color`, core/mandala/colorModule.ts),
126
+ * which signs only through a signature envelope binding the signature to a
127
+ * transaction the user approved, and refuses a bare digest (A.13).
127
128
  *
128
129
  * BRC-29 (`[2, '3241645161d8']`) was reserved here too (XR-020) and is not any
129
130
  * more: it is the standard BRC-100 payment protocol, and refusing it broke
@@ -46,7 +46,7 @@ import type {
46
46
  TableUser
47
47
  } from '@bsv/wallet-toolbox-mobile'
48
48
  import type { ListActionsResult, ListOutputsResult, Validation, WalletLoggerInterface } from '@bsv/sdk'
49
- import { Beef, Transaction } from '@bsv/sdk'
49
+ import { Beef } from '@bsv/sdk'
50
50
  import { listActionsSql } from './methods/listActionsSql'
51
51
  import { listOutputsSql } from './methods/listOutputsSql'
52
52
  import { findUnprovenTxidsWithoutReq } from './methods/unprovenWithoutReqSql'
@@ -66,6 +66,8 @@ import {
66
66
  import { buildOfflineHoldResult, groupOfflineHolds } from '../offline/hold'
67
67
  import { getOnline } from '../net/online'
68
68
  import { TaskSendOffline } from '../monitor/TaskSendOffline'
69
+ import { colorHeldTxids, HOST_LEDGER_RECORD_PREFIX, txidsSpendingColorOutputs } from '../mandala/colorGuard'
70
+ import { createTransferJournal } from '../mandala/transferJournal'
69
71
  import {
70
72
  anyAdminOutpoint,
71
73
  anyAdminTransaction,
@@ -107,23 +109,6 @@ export interface StorageExpoSQLiteOptions extends StorageProviderOptions {
107
109
  identityKey?: string
108
110
  }
109
111
 
110
- /** What `repairSettledTokenTransaction` actually changed, for the caller's log. */
111
- export interface TokenTransactionRepair {
112
- txid: string
113
- /** Transaction rows moved back to 'unproven'. */
114
- transactionIds: number[]
115
- /** Their statuses before the repair — 'failed', in the case this exists for. */
116
- wasTxStatuses: string[]
117
- /** The request's status before the repair, or undefined when there was none. */
118
- wasReqStatus?: string
119
- /** Coins this transaction spends that were wrongly spendable and are now spent. */
120
- inputsMarkedSpent: number
121
- /** This transaction's own outputs (change included) restored to spendable. */
122
- outputsMadeSpendable: number
123
- /** True when the request had gone and was rebuilt from the raw transaction. */
124
- reqCreated: boolean
125
- }
126
-
127
112
  /** Per-connection wait before a lock contention becomes "database is locked". */
128
113
  export const BUSY_TIMEOUT_MS = 5000
129
114
 
@@ -1908,141 +1893,6 @@ export class StorageExpoSQLite extends StorageProvider {
1908
1893
  }, args.trx)
1909
1894
  }
1910
1895
 
1911
- /**
1912
- * Put a token transaction the wallet wrongly failed back into a live state,
1913
- * for a caller that has independently established the transaction IS on chain.
1914
- *
1915
- * WHY THIS EXISTS RATHER THAN A CALL INTO THE TOOLBOX. Every sanctioned
1916
- * un-fail path in `@bsv/wallet-toolbox-mobile` is gated on something this case
1917
- * cannot supply:
1918
- *
1919
- * · `updateTransactionStatus` refuses outright — "A 'failed' transaction may
1920
- * not be un-failed by this method" (`StorageProvider.js`), and `reviewStatus`
1921
- * only ever moves rows TOWARDS failed.
1922
- * · `TaskUnFail` is the real recovery path, but its entry point demands
1923
- * `services.getMerklePath(txid)` first and returns the req to `'invalid'`
1924
- * when there is none. A transaction the overlay broadcast seconds ago has
1925
- * no merkle path and will not have one for ten minutes, which is precisely
1926
- * the window in which the wallet's own bookkeeping is wrong and its coins
1927
- * are wrongly spendable.
1928
- * · `unfailTransactionsForProof` — the body TaskUnFail delegates to — is the
1929
- * right SHAPE (tx to 'unproven', inputs to spent, req to 'unmined'), and
1930
- * the steps below are deliberately identical to it, EXCEPT that it decides
1931
- * each of this transaction's own outputs by `services.isUtxo(output)`. For
1932
- * a tx broadcast moments ago that probe answers "not a utxo" from services
1933
- * that have not seen it yet, which would leave the change permanently
1934
- * unspendable — the opposite of the repair.
1935
- *
1936
- * So the steps are written out here, through the provider's own CRUD methods
1937
- * (`updateTransaction`/`updateOutput`/`updateProvenTxReq`), and never as raw
1938
- * SQL over the tables. What it does, in one write transaction:
1939
- *
1940
- * 1. every transaction row for `txid` that is not already `'completed'`
1941
- * goes to `'unproven'` — broadcast, awaiting proof;
1942
- * 2. every input the raw transaction spends that is one of THIS user's
1943
- * outputs goes back to `spendable: false, spentBy: <this transaction>`.
1944
- * This is the money-safety step: `updateTransactionStatus('failed')`
1945
- * released those coins, and they are spent on chain;
1946
- * 3. this transaction's own outputs go back to `spendable: true`, except any
1947
- * a different transaction has since spent (`spentBy` set), which are left
1948
- * exactly as they are;
1949
- * 4. the request goes to `'unmined'` with `attempts: 0`, which is one of the
1950
- * statuses `TaskCheckForProofs` polls, so the monitor proves it from here
1951
- * exactly as it would any other broadcast transaction. A request that has
1952
- * gone missing entirely is recreated from the transaction's own raw bytes.
1953
- *
1954
- * Returns `undefined` when there was nothing to repair (no transaction row, no
1955
- * raw bytes to read the inputs from, or a transaction that is already live) —
1956
- * the caller logs, and nothing is written.
1957
- */
1958
- async repairSettledTokenTransaction(txid: string): Promise<TokenTransactionRepair | undefined> {
1959
- const transactions = await this.findTransactions({ partial: { txid } })
1960
- if (transactions.length === 0) return undefined
1961
- const req = (await this.findProvenTxReqs({ partial: { txid } }))[0]
1962
-
1963
- // Nothing to do unless the wallet actually believes this transaction died.
1964
- const damaged = transactions.some(t => t.status === 'failed') || req?.status === 'invalid'
1965
- if (!damaged) return undefined
1966
-
1967
- const rawTx = req?.rawTx ?? transactions.find(t => t.rawTx && t.rawTx.length > 0)?.rawTx
1968
- if (!rawTx || rawTx.length === 0) {
1969
- devLog(`[StorageExpoSQLite] cannot repair ${txid}: no raw transaction to read its inputs from`)
1970
- return undefined
1971
- }
1972
- let parsed: Transaction
1973
- try {
1974
- parsed = Transaction.fromBinary([...rawTx])
1975
- } catch (e) {
1976
- devLog(`[StorageExpoSQLite] cannot repair ${txid}: its raw transaction will not parse:`, e)
1977
- return undefined
1978
- }
1979
-
1980
- const repair: TokenTransactionRepair = {
1981
- txid,
1982
- transactionIds: [],
1983
- wasTxStatuses: transactions.map(t => t.status),
1984
- wasReqStatus: req?.status,
1985
- inputsMarkedSpent: 0,
1986
- outputsMadeSpendable: 0,
1987
- reqCreated: false
1988
- }
1989
-
1990
- await this.transaction(async trx => {
1991
- for (const tx of transactions) {
1992
- if (tx.status === 'completed') continue
1993
- repair.transactionIds.push(tx.transactionId)
1994
- await this.updateTransaction(tx.transactionId, { status: 'unproven' }, trx)
1995
-
1996
- for (const input of parsed.inputs) {
1997
- const sourceTXID = input.sourceTXID ?? input.sourceTransaction?.id('hex')
1998
- if (!sourceTXID || typeof input.sourceOutputIndex !== 'number') continue
1999
- const matches = await this.findOutputs({
2000
- partial: { userId: tx.userId, txid: sourceTXID, vout: input.sourceOutputIndex },
2001
- trx
2002
- })
2003
- for (const output of matches) {
2004
- if (output.outputId == null) continue
2005
- await this.updateOutput(output.outputId, { spendable: false, spentBy: tx.transactionId }, trx)
2006
- repair.inputsMarkedSpent++
2007
- }
2008
- }
2009
-
2010
- const own = await this.findOutputs({ partial: { userId: tx.userId, transactionId: tx.transactionId }, trx })
2011
- for (const output of own) {
2012
- // Spent by something else since the failure: that spend is the newer
2013
- // fact about this coin and must not be undone by a repair.
2014
- if (output.outputId == null || output.spentBy != null || output.spendable) continue
2015
- await this.updateOutput(output.outputId, { spendable: true }, trx)
2016
- repair.outputsMadeSpendable++
2017
- }
2018
- }
2019
-
2020
- if (req) {
2021
- await this.updateProvenTxReq(req.provenTxReqId, { status: 'unmined', attempts: 0 }, trx)
2022
- } else {
2023
- const now = new Date()
2024
- await this.insertProvenTxReq(
2025
- {
2026
- created_at: now,
2027
- updated_at: now,
2028
- provenTxReqId: 0,
2029
- txid,
2030
- status: 'unmined',
2031
- attempts: 0,
2032
- notified: false,
2033
- history: '{}',
2034
- notify: JSON.stringify({ transactionIds: repair.transactionIds }),
2035
- rawTx: [...rawTx]
2036
- } as TableProvenTxReq,
2037
- trx
2038
- )
2039
- repair.reqCreated = true
2040
- }
2041
- })
2042
-
2043
- return repair
2044
- }
2045
-
2046
1896
  async purgeData(_params: PurgeParams, _trx?: TrxToken): Promise<PurgeResults> {
2047
1897
  return { count: 0, log: '' }
2048
1898
  }
@@ -2131,19 +1981,18 @@ export class StorageExpoSQLite extends StorageProvider {
2131
1981
  * 2026-09-15 a recipient wallet raw-broadcast four just-credited token
2132
1982
  * transactions (one of them a known double-spend) before any `/submit`.
2133
1983
  * `WalletContext` calls this from its `processUnsent` patch: every request
2134
- * with a `token_settlements` row is held for the drain and the caller is
2135
- * told which ones, so it posts only the rest. Never throws.
1984
+ * `colorHeldTxids` names (a 1Color tx whose `color_transfers` row is not
1985
+ * `settled`) is held for the drain and the caller is told which ones, so it
1986
+ * posts only the rest. Never throws: any fault withholds the whole batch.
2136
1987
  */
2137
1988
  async holdTokenReqsForDrain(reqApis: TableProvenTxReq[]): Promise<Set<string>> {
2138
1989
  try {
2139
- const tokenTxids = await this.tokenSettlementTxids(reqApis.map(r => r.txid))
2140
- if (tokenTxids.size === 0) return tokenTxids
2141
- const reqs = reqApis.filter(r => tokenTxids.has(r.txid)).map(r => new EntityProvenTxReq(r))
2142
- devLog(
2143
- `[StorageExpoSQLite] holding ${reqs.length} token req(s) from the monitor's retry for the settlement drain`
2144
- )
1990
+ const heldTxids = await this.colorHeldTxids(reqApis.map(r => ({ txid: r.txid, rawTx: r.rawTx })))
1991
+ if (heldTxids.size === 0) return heldTxids
1992
+ const reqs = reqApis.filter(r => heldTxids.has(r.txid)).map(r => new EntityProvenTxReq(r))
1993
+ devLog(`[StorageExpoSQLite] holding ${reqs.length} unsettled 1Color req(s) from the monitor's retry`)
2145
1994
  await this.holdTokenReqs(reqs)
2146
- return tokenTxids
1995
+ return heldTxids
2147
1996
  } catch (e) {
2148
1997
  devLog('[StorageExpoSQLite] could not hold token reqs from the monitor retry; withholding them anyway:', e)
2149
1998
  return new Set(reqApis.map(r => r.txid))
@@ -2151,32 +2000,44 @@ export class StorageExpoSQLite extends StorageProvider {
2151
2000
  }
2152
2001
 
2153
2002
  /**
2154
- * Which of these txids the Mandala settlement drain owns — THROWS if the
2155
- * read itself could not be answered.
2003
+ * Which of these requests must not be broadcast now — THROWS if the journal,
2004
+ * ledger or input read could not be answered.
2156
2005
  *
2157
- * XR-045: this used to collapse "the read failed" into the same empty set as
2158
- * "no token requests here", which is exactly what "treat it as plain BSV"
2159
- * means to every caller — so a transient SQLite fault (busy/locked, a
2160
- * corrupt page) on a table that had just been written to successfully
2161
- * looked identical to "this feature does not apply", and an unadmitted token
2162
- * request went straight to broadcast. Never swallowed here any more: each
2163
- * caller already decides what a failure costs it — `holdTokenReqsForDrain`
2164
- * withholds its whole batch on any exception, and `attemptToPostReqsToNetwork`
2165
- * (guard #2, the one that can actually broadcast) does the same rather than
2166
- * deciding off an incomplete answer. `heldTokenTxidsIn` (guard #2's result
2167
- * half, reporting only) already documented "read failures propagate; the one
2168
- * caller decides" — this is what makes that true.
2006
+ * A request is held when its raw tx will not parse or is missing, or when it
2007
+ * carries a BRC-162 1Color output AND this wallet's token custody is in it
2008
+ * (a `color_transfers` row, a Mandala host-ledger record, or an input spent
2009
+ * from one of its `p color` baskets) AND its row does not read `settled`
2010
+ * (plan 07 W1, IC §8.2, the decoy-output fix). See `mandala/colorGuard.ts`
2011
+ * for the predicate.
2012
+ *
2013
+ * XR-045: a read fault is never collapsed into "no token requests here",
2014
+ * which is exactly what "treat it as plain BSV" means to every caller. Each
2015
+ * caller decides what a failure costs it — `holdTokenReqsForDrain` withholds
2016
+ * its whole batch, `attemptToPostReqsToNetwork` (the one that can actually
2017
+ * broadcast) does the same, `processAction` omits every result, and
2018
+ * `processOfflineActions` stalls the step. An unopened database is a fault
2019
+ * too: it throws rather than answering "nothing held".
2169
2020
  */
2170
- private async tokenSettlementTxids(txids: string[]): Promise<Set<string>> {
2171
- if (txids.length === 0 || !this.db) return new Set()
2021
+ async colorHeldTxids(reqs: readonly { txid: string; rawTx?: readonly number[] }[]): Promise<Set<string>> {
2022
+ if (reqs.length === 0) return new Set()
2172
2023
  try {
2173
- const rows = (await this.db.getAllAsync(
2174
- `SELECT txid FROM token_settlements WHERE txid IN (${txids.map(() => '?').join(',')})`,
2175
- txids
2176
- )) as { txid: string }[]
2177
- return new Set(rows.map(r => r.txid))
2024
+ return await colorHeldTxids(reqs, {
2025
+ statesOf: async txids => {
2026
+ if (!this.db) throw new Error('the database is not open; cannot read color_transfers')
2027
+ return await createTransferJournal(this.db).statesOf(txids)
2028
+ },
2029
+ custodyOf: async txids => {
2030
+ if (!this.db) throw new Error('the database is not open; cannot read token custody')
2031
+ const custodial = await txidsSpendingColorOutputs(this.db, txids)
2032
+ for (const txid of txids) {
2033
+ if (custodial.has(txid)) continue
2034
+ if ((await this.getKeyValue(HOST_LEDGER_RECORD_PREFIX + txid)) !== undefined) custodial.add(txid)
2035
+ }
2036
+ return custodial
2037
+ }
2038
+ })
2178
2039
  } catch (e) {
2179
- devLog('[StorageExpoSQLite] could not read token_settlements:', e)
2040
+ devLog('[StorageExpoSQLite] could not read color_transfers:', e)
2180
2041
  throw e
2181
2042
  }
2182
2043
  }
@@ -2187,11 +2048,11 @@ export class StorageExpoSQLite extends StorageProvider {
2187
2048
  * The all-or-nothing refusal `groupOfflineHolds` offers is right for the BSV
2188
2049
  * path — refusing there falls back to the ordinary broadcast. For a token req
2189
2050
  * that fallback is precisely the harm this guard exists to prevent, so an
2190
- * ungroupable token req is simply not broadcast: it keeps its
2191
- * `token_settlements` row, which the drain owns independently of any queue
2192
- * bookkeeping (FIX I) and which `listStuckSettlements` surfaces if it never
2193
- * moves. The failure is loud in the log and recoverable; a premature
2194
- * broadcast is neither.
2051
+ * ungroupable token req is simply not broadcast: it stays unsent, its
2052
+ * `color_transfers` row (or the module's `color_offline` record, which the
2053
+ * runtime's held reconcile journals) keeps it visible as pending, and every
2054
+ * later post attempt meets this same guard. The failure is loud in the log
2055
+ * and recoverable; a premature broadcast is neither.
2195
2056
  */
2196
2057
  private async holdTokenReqs(reqs: EntityProvenTxReq[]): Promise<void> {
2197
2058
  const holds = groupOfflineHolds(await this.resolveHoldPairs(reqs))
@@ -2216,21 +2077,26 @@ export class StorageExpoSQLite extends StorageProvider {
2216
2077
  * directly (`monitor/tasks/TaskSendWaiting.js:180`), so the monitor's
2217
2078
  * ordinary broadcast retries are deliberately NOT intercepted.
2218
2079
  *
2219
- * **Token guard (offline-settlement spec §4.3, guard #2).** A transaction
2220
- * with a `token_settlements` row may only be broadcast by `postTokenStep`,
2221
- * after the issuer's overlay has admitted it and every unadmitted token
2222
- * ancestor it spends. Holding "only when offline" left the common shop case
2223
- * wide open — payee has Wi-Fi, payer none — because the payee's own
2224
- * `internalizeAction` then reached a real, unmediated broadcast. So token
2225
- * reqs are split off and held unconditionally, and the online branch is taken
2226
- * only for what is left. The result still covers every txid the caller handed
2227
- * in: reporting on a subset would make `internalizeAction` roll back a
2228
- * payment that was in fact accepted for delivery.
2080
+ * **Token guard (guard #2; plan 07 W1, IC §8.2).** A transaction with a
2081
+ * BRC-162 1Color output may be broadcast only once its `color_transfers` row
2082
+ * reads `settled`, i.e. after the color module's `settle` got a verified
2083
+ * admission from the Mandala overlay (which itself broadcasts what it
2084
+ * admits). A missing row holds. Holding "only when offline" left the common
2085
+ * shop case wide open — payee has Wi-Fi, payer none, or ARC reachable while
2086
+ * the overlay is not — because the payee's own `internalizeAction` then
2087
+ * reached a real, unmediated broadcast. So unsettled 1Color reqs are split
2088
+ * off and held unconditionally, and the online branch is taken only for what
2089
+ * is left. The result still covers every txid the caller handed in:
2090
+ * reporting on a subset would make `internalizeAction` roll back a payment
2091
+ * that was in fact accepted for delivery. The module's own post-admission
2092
+ * `sendWith:[txid]` (IC D24) lands here too; when the journal has not caught
2093
+ * up yet it is held, and `processOfflineActions` releases it on the next
2094
+ * pass after the row reads `settled`.
2229
2095
  *
2230
- * Guard #3 follows from this one: because a token req is never handed to
2231
- * `sendWith` outside `postTokenStep`, it never reaches `unsent`/`sending`,
2232
- * which is all that keeps `TaskSendWaiting` — which bypasses this override
2233
- * entirely — from broadcasting it out from under the drain.
2096
+ * Guard #3 follows from this one: because an unsettled 1Color req only ever
2097
+ * reaches this override, which parks it at `nosend`, it never reaches
2098
+ * `unsent`/`sending`, which is all that keeps `TaskSendWaiting` — which
2099
+ * bypasses this override entirely — from broadcasting it before settlement.
2234
2100
  *
2235
2101
  * Narrower than "offline means hold" on the BSV side: only requests whose
2236
2102
  * transaction is already in a hold-safe status are parked, so in practice
@@ -2266,10 +2132,11 @@ export class StorageExpoSQLite extends StorageProvider {
2266
2132
  * is not telling you it went out", which is the truth and which no caller can
2267
2133
  * mistake for delivery.
2268
2134
  *
2269
- * Scoped as narrowly as it can be: only txids that have a `token_settlements`
2270
- * row AND whose request is still parked at `'nosend'`. Once `postTokenStep`
2271
- * has really broadcast the tip its request is past `'nosend'` and its results
2272
- * pass through exactly as before, and a plain BSV action is never looked at.
2135
+ * Scoped as narrowly as it can be: only txids whose request is still parked
2136
+ * at `'nosend'` AND that `colorHeldTxids` names (an unsettled 1Color tx).
2137
+ * Once a settled tx has really been broadcast its request is past `'nosend'`
2138
+ * and its results pass through exactly as before, and a plain BSV action is
2139
+ * never held.
2273
2140
  *
2274
2141
  * `internalizeAction` is unaffected — it calls `shareReqsWithWorld` directly
2275
2142
  * rather than through `processAction` — which is what keeps the receiver's
@@ -2303,26 +2170,26 @@ export class StorageExpoSQLite extends StorageProvider {
2303
2170
 
2304
2171
  devLog(
2305
2172
  `[StorageExpoSQLite] omitting ${heldTokenTxids.size} held token req(s) from sendWithResults; ` +
2306
- 'the settlement drain owns their broadcast'
2173
+ 'they are released once settled'
2307
2174
  )
2308
2175
  return { ...r, sendWithResults: swr.filter(s => !heldTokenTxids.has(s.txid)) }
2309
2176
  }
2310
2177
 
2311
2178
  /**
2312
- * Of these txids, the ones that both have a `token_settlements` row and are
2313
- * still parked at request status `'nosend'` — i.e. held by guard #2 and not
2314
- * yet broadcast by the drain. Read failures propagate; the one caller decides
2315
- * what a failure means.
2179
+ * Of these txids, the ones whose request is still parked at `'nosend'` and
2180
+ * that `colorHeldTxids` names — i.e. held by guard #2 and not yet released.
2181
+ * The request is read first because the classification needs its raw tx. A
2182
+ * `'nosend'` request without bytes is held by `colorHeldTxids` (fail
2183
+ * closed), so it is omitted from the results. Read failures propagate; the
2184
+ * one caller decides what a failure means.
2316
2185
  */
2317
2186
  private async heldTokenTxidsIn(txids: string[]): Promise<Set<string>> {
2318
- const tokenTxids = await this.tokenSettlementTxids(txids)
2319
- if (tokenTxids.size === 0) return new Set()
2320
- const held = new Set<string>()
2321
- for (const txid of tokenTxids) {
2187
+ const parked: { txid: string; rawTx?: number[] }[] = []
2188
+ for (const txid of new Set(txids)) {
2322
2189
  const req = (await this.findProvenTxReqs({ partial: { txid } }))[0]
2323
- if (req?.status === 'nosend') held.add(txid)
2190
+ if (req?.status === 'nosend') parked.push({ txid, rawTx: req.rawTx })
2324
2191
  }
2325
- return held
2192
+ return await this.colorHeldTxids(parked)
2326
2193
  }
2327
2194
 
2328
2195
  async attemptToPostReqsToNetwork(
@@ -2334,25 +2201,22 @@ export class StorageExpoSQLite extends StorageProvider {
2334
2201
 
2335
2202
  let tokenTxids: Set<string>
2336
2203
  try {
2337
- tokenTxids = await this.tokenSettlementTxids(reqs.map(r => r.txid))
2204
+ tokenTxids = await this.colorHeldTxids(reqs.map(r => ({ txid: r.txid, rawTx: r.rawTx })))
2338
2205
  } catch (e) {
2339
2206
  // XR-045: the read could not be answered, so this call does not know
2340
- // which of `reqs` are token requests — and "I could not tell" must never
2341
- // resolve to "post them", the exact fail-open this guard exists to
2342
- // prevent. Hold the WHOLE batch, as if every txid in it needed the
2343
- // drain: a plain BSV req held this way is not lost, only delayed until
2344
- // `processOfflineActions` (or a later, healthy read) finds no settlement
2345
- // row for it and posts it normally.
2346
- devLog('[StorageExpoSQLite] could not read token_settlements; holding the whole batch rather than guessing:', e)
2207
+ // which of `reqs` are unsettled token requests — and "I could not tell"
2208
+ // must never resolve to "post them", the exact fail-open this guard
2209
+ // exists to prevent. Hold the WHOLE batch: a plain BSV req held this way
2210
+ // is not lost, only delayed until `processOfflineActions` (or a later,
2211
+ // healthy read) finds no 1Color output in it and posts it normally.
2212
+ devLog('[StorageExpoSQLite] could not read color_transfers; holding the whole batch rather than guessing:', e)
2347
2213
  tokenTxids = new Set(reqs.map(r => r.txid))
2348
2214
  }
2349
2215
  const tokenReqs = tokenTxids.size > 0 ? reqs.filter(r => tokenTxids.has(r.txid)) : []
2350
2216
  const rest = tokenTxids.size > 0 ? reqs.filter(r => !tokenTxids.has(r.txid)) : reqs
2351
2217
 
2352
2218
  if (tokenReqs.length > 0) {
2353
- devLog(
2354
- `[StorageExpoSQLite] holding ${tokenReqs.length} token req(s) for the settlement drain, regardless of connectivity`
2355
- )
2219
+ devLog(`[StorageExpoSQLite] holding ${tokenReqs.length} unsettled 1Color req(s), regardless of connectivity`)
2356
2220
  await this.holdTokenReqs(tokenReqs)
2357
2221
  // Nothing else in the call: answer for the whole call without ever
2358
2222
  // asking whether we are online, because the answer could not change it.