@bsv/expo-wallet-toolbox 0.3.1 → 0.5.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.
- package/CHANGELOG.md +311 -0
- package/README.md +52 -1
- package/assets/sounds/vault-deposit.wav +0 -0
- package/assets/sounds/vault-withdraw.wav +0 -0
- package/core/config.tsx +21 -18
- package/core/context/VaultContext.tsx +8 -11
- package/core/context/WalletConnectionContext.tsx +137 -52
- package/core/context/WalletContext.tsx +413 -23
- package/core/hooks/useConfirmationSound.ts +14 -8
- package/core/i18n/translations.tsx +3368 -952
- package/core/index.ts +107 -14
- package/core/localpay/build.ts +674 -37
- package/core/localpay/codec.ts +68 -5
- package/core/localpay/pending.ts +240 -22
- package/core/localpay/settlementAck.ts +149 -0
- package/core/localpay/types.ts +14 -1
- package/core/localpay/verify.ts +118 -69
- package/core/mandala/abortGuard.ts +134 -0
- package/core/mandala/basketMigration.ts +166 -0
- package/core/mandala/bundle.ts +244 -0
- package/core/mandala/createRuntime.ts +2437 -0
- package/core/mandala/drain.ts +670 -0
- package/core/mandala/permissionModule.ts +642 -0
- package/core/mandala/resendTransfer.ts +175 -0
- package/core/mandala/runtime.ts +357 -0
- package/core/mandala/settlementStore.ts +412 -0
- package/core/mandala/types.ts +290 -0
- package/core/offline/cancelParked.ts +94 -1
- package/core/offline/payerHold.ts +152 -12
- package/core/offline/tokenFrames.ts +197 -0
- package/core/parsePeerPayURI.ts +70 -17
- package/core/pay/rails/address.ts +51 -3
- package/core/pay/rails/handle.ts +88 -9
- package/core/pay/rails/index.ts +16 -6
- package/core/pay/rails/nearby.ts +114 -4
- package/core/services/capWalletArgs.ts +8 -9
- package/core/services/externalOrigin.ts +39 -0
- package/core/services/vault/VaultKeyService.ts +912 -251
- package/core/services/vault/ceremony.ts +435 -367
- package/core/services/vault/ceremonyHost.ts +27 -21
- package/core/services/vault/devMock.ts +30 -7
- package/core/services/vault/driver.ts +95 -41
- package/core/services/vault/guard.ts +514 -56
- package/core/services/vault/hardwareLease.ts +22 -0
- package/core/services/vault/mockYubiKey.ts +258 -90
- package/core/services/vault/pivReset.ts +145 -0
- package/core/services/vault/r1comb.ts +976 -0
- package/core/services/vault/session.ts +93 -26
- package/core/services/vault/transfers.ts +2617 -747
- package/core/services/vault/types.ts +100 -43
- package/core/services/vault/vaultStore.ts +991 -74
- package/core/services/walletConnectionValidation.ts +293 -0
- package/core/services/walletServiceConfig.ts +19 -24
- package/core/storage/StorageExpoSQLite.ts +382 -56
- package/core/storage/dbImage.ts +48 -0
- package/core/storage/methods/findSql.ts +0 -54
- package/core/storage/methods/listOutputsSql.ts +7 -3
- package/core/storage/methods/offlineActions.ts +15 -0
- package/core/storage/methods/processOfflineActions.ts +263 -6
- package/core/storage/methods/walletBalanceSql.ts +16 -4
- package/core/storage/schema/createTables.ts +123 -0
- package/core/storage/sqlUpdateValue.ts +24 -0
- package/core/toolboxConfig.ts +240 -0
- package/core/walletRepair/runWalletCheck.ts +19 -2
- package/package.json +25 -24
- package/ui/components/QRScanner.tsx +1 -1
- package/ui/components/pay/AdmissionNotice.tsx +99 -0
- package/ui/components/pay/AssetPicker.tsx +184 -0
- package/ui/components/pay/AvailableBalance.tsx +33 -2
- package/ui/components/pay/HandleReceive.tsx +213 -50
- package/ui/components/pay/NearbyFlow.tsx +616 -69
- package/ui/components/pay/PayForm.tsx +73 -8
- package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
- package/ui/components/pay/RecipientField.tsx +49 -4
- package/ui/components/pay/RequestHub.tsx +68 -8
- package/ui/components/pay/ResultBanner.tsx +41 -4
- package/ui/components/pay/UniversalSend.tsx +534 -30
- package/ui/components/pay/tokenSendCopy.ts +116 -0
- package/ui/components/pay/useRecipientInput.ts +36 -7
- package/ui/components/ui/PermissionSheet.tsx +65 -4
- package/ui/components/ui/Sheet.tsx +9 -2
- package/ui/components/vault/EnrollWizard.tsx +1432 -488
- package/ui/components/vault/KeyChooser.tsx +96 -0
- package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
- package/ui/components/vault/vaultErrorCopy.ts +145 -0
- package/ui/components/wallet/ActivityRow.tsx +101 -17
- package/ui/components/wallet/AmountInput.tsx +77 -25
- package/ui/components/wallet/AssetAmount.tsx +95 -0
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
- package/ui/components/wallet/tokenEviction.ts +65 -0
- package/ui/hooks/useExportWalletData.ts +39 -0
- package/ui/hooks/useMandala.ts +303 -0
- package/ui/hooks/useVaultBalance.ts +105 -7
- package/ui/hooks/useVaultCoverage.ts +52 -0
- package/ui/importDatabases.ts +7 -3
- package/ui/index.ts +50 -7
- package/ui/screens/ConnectionsScreen.tsx +46 -29
- package/ui/screens/PairScreen.tsx +12 -12
- package/ui/screens/PayScreen.tsx +130 -10
- package/ui/screens/SettingsScreen.tsx +18 -9
- package/ui/screens/VaultScreen.tsx +925 -171
- package/ui/screens/VaultTransferScreen.tsx +376 -123
- package/ui/screens/WalletCheckScreen.tsx +10 -1
- package/ui/screens/WalletConfigScreen.tsx +42 -20
- package/ui/screens/WalletHomeScreen.tsx +417 -86
- package/ui/screens/homeBadges.ts +9 -1
- package/ui/screens/tokenRowTitle.ts +68 -0
- package/ui/tokenFormat.ts +108 -0
- package/ui/tokenSeen.ts +75 -0
- package/ui/tokenStatus.ts +79 -0
- package/assets/sounds/vault-close.wav +0 -0
- package/assets/sounds/vault-open.wav +0 -0
- package/core/services/vault/k1.ts +0 -75
- package/core/services/vault/sealing.ts +0 -84
- package/core/services/vault/vaultDerivation.ts +0 -152
- package/core/services/vault/vaultPassphrase.ts +0 -287
- package/ui/components/vault/PassphraseField.tsx +0 -306
- package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
- package/ui/screens/VaultRecoverScreen.tsx +0 -226
|
@@ -224,60 +224,6 @@ export function spendingReferencesSql(pairCount: number): string {
|
|
|
224
224
|
)
|
|
225
225
|
}
|
|
226
226
|
|
|
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
227
|
/** Split a `txid.vout` or `txid:vout` outpoint into its parts, or null. */
|
|
282
228
|
export function splitOutpoint(outpoint: string): { txid: string; vout: number } | null {
|
|
283
229
|
const m = /^([0-9a-fA-F]{64})[.:](\d+)$/.exec(outpoint.trim())
|
|
@@ -8,6 +8,7 @@ import type { AuthId } from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorag
|
|
|
8
8
|
import type { StorageExpoSQLite } from '../StorageExpoSQLite'
|
|
9
9
|
import { getListOutputsSpecOp } from '@bsv/wallet-toolbox-mobile/out/src/storage/methods/ListOutputsSpecOp'
|
|
10
10
|
import { devLog, isLoggingEnabled } from '../../logging'
|
|
11
|
+
import { BALANCE_TX_STATUS } from './walletBalanceSql'
|
|
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:
|
|
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:
|
|
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
|
-
|
|
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 } = {}
|
|
@@ -33,6 +33,14 @@ import {
|
|
|
33
33
|
type PostOutcome
|
|
34
34
|
} from '../../offline/plan'
|
|
35
35
|
import { descendantsOf, type OrderableTx } from '../../offline/order'
|
|
36
|
+
import { postTokenStep, reconcileSettlements, type TokenFrameSource } from '../../mandala/drain'
|
|
37
|
+
import type {
|
|
38
|
+
AdmissionVerifier,
|
|
39
|
+
CoverFn,
|
|
40
|
+
SettlementStore,
|
|
41
|
+
SubmitFn,
|
|
42
|
+
TokenSettlementRow
|
|
43
|
+
} from '../../mandala/types'
|
|
36
44
|
import { devLog } from '../../logging'
|
|
37
45
|
import { getOnline } from '../../net/online'
|
|
38
46
|
|
|
@@ -73,25 +81,112 @@ interface HeldAction {
|
|
|
73
81
|
api: TableProvenTxReq
|
|
74
82
|
}
|
|
75
83
|
|
|
84
|
+
/**
|
|
85
|
+
* Everything the Mandala settlement drain needs that this module cannot do
|
|
86
|
+
* itself. Absent for a wallet with no token payments — then not one line of
|
|
87
|
+
* behaviour below changes.
|
|
88
|
+
*
|
|
89
|
+
* `cover` and `submit` are injected rather than imported because one is a pure
|
|
90
|
+
* verifier over local evidence and the other is a network call; keeping both
|
|
91
|
+
* out of here is what leaves this file a database-and-ordering module.
|
|
92
|
+
*/
|
|
93
|
+
export interface OfflineTokenDeps {
|
|
94
|
+
store: SettlementStore
|
|
95
|
+
cover: CoverFn
|
|
96
|
+
submit: SubmitFn
|
|
97
|
+
/**
|
|
98
|
+
* FIX H / wire contract §9.10. THIS WALLET's configured overlay identity key
|
|
99
|
+
* and the σ_I verifier that checks against it — the only thing that may let a
|
|
100
|
+
* cached admission skip a `/submit`, and the filter on what the evidence
|
|
101
|
+
* cache is allowed to keep at all. Absent and nothing is trusted: every
|
|
102
|
+
* ancestor is submitted, which is free and always correct.
|
|
103
|
+
*/
|
|
104
|
+
overlayIdentityKey?: string
|
|
105
|
+
verifyAdmission?: AdmissionVerifier
|
|
106
|
+
/**
|
|
107
|
+
* Clear `@bsv/mandala`'s tx-journal entry for a tip this pass really
|
|
108
|
+
* broadcast. See `TokenStepDeps.journalRemove`; passed straight through so
|
|
109
|
+
* the drain's own broadcast is the only thing that can clear one.
|
|
110
|
+
*/
|
|
111
|
+
journalRemove?: (txid: string) => Promise<void>
|
|
112
|
+
/**
|
|
113
|
+
* FIX G: every durable token frame this device holds, re-read each pass so
|
|
114
|
+
* the evidence tables and the settlement rows are re-derived idempotently
|
|
115
|
+
* before anything is decided. Supplied by the caller because only it can
|
|
116
|
+
* open a payer-side sealed `framePayload`.
|
|
117
|
+
*/
|
|
118
|
+
frames?: () => Promise<TokenFrameSource[]>
|
|
119
|
+
}
|
|
120
|
+
|
|
76
121
|
export async function processOfflineActions(args: {
|
|
77
122
|
storage: StorageExpoSQLite
|
|
78
123
|
/** Injected so tests can supply a missing ancestor without hitting the network. */
|
|
79
124
|
refetchBeef?: (txid: string) => Promise<number[] | undefined>
|
|
125
|
+
/** Mandala settlement. Omit entirely and the drain behaves exactly as before. */
|
|
126
|
+
token?: OfflineTokenDeps
|
|
80
127
|
}): Promise<ProcessOfflineActionsResult> {
|
|
81
|
-
const { storage, refetchBeef } = args
|
|
128
|
+
const { storage, refetchBeef, token } = args
|
|
82
129
|
const db = storage.sqliteDb
|
|
83
130
|
if (!db) return { sent: 0, rejected: 0, stopped: true, stalledOn: 'the database is not open' }
|
|
84
131
|
|
|
132
|
+
// Before anything is read or decided: re-derive the settlement evidence from
|
|
133
|
+
// the frame bytes that are already durable (FIX G). Purely local, so it runs
|
|
134
|
+
// even on a pass that turns out to be offline, and it is allowed to fail —
|
|
135
|
+
// it is a cache-population step, and the next tick repeats it.
|
|
136
|
+
if (token?.frames) {
|
|
137
|
+
try {
|
|
138
|
+
const r = await reconcileSettlements({
|
|
139
|
+
store: token.store,
|
|
140
|
+
sources: await token.frames(),
|
|
141
|
+
overlayIdentityKey: token.overlayIdentityKey,
|
|
142
|
+
verifyAdmission: token.verifyAdmission
|
|
143
|
+
})
|
|
144
|
+
if (r.errors.length > 0) devLog('[processOfflineActions] evidence reconciliation reported:', r.errors)
|
|
145
|
+
if (r.dropped > 0) {
|
|
146
|
+
// FIX H: counterparty-supplied σ_I that did not verify against this
|
|
147
|
+
// wallet's configured overlay key. Not an error and not a decline —
|
|
148
|
+
// the ancestors are simply submitted rather than skipped.
|
|
149
|
+
devLog(`[processOfflineActions] dropped ${r.dropped} unverifiable admission(s) from frame evidence`)
|
|
150
|
+
}
|
|
151
|
+
} catch (e) {
|
|
152
|
+
devLog('[processOfflineActions] could not reconcile token settlements:', e)
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
85
156
|
// 'posting' is included so a run interrupted mid-flight resumes rather than
|
|
86
157
|
// stranding its rows. Re-posting is safe: a transaction the network already has
|
|
87
158
|
// comes back as accepted (ARC's `SEEN_ON_NETWORK`), and a request storage has
|
|
88
159
|
// already recorded as delivered is not posted again at all — see `postOwned`.
|
|
89
|
-
const
|
|
90
|
-
if (
|
|
160
|
+
const queued = await findOfflineActions(db, { status: ['queued', 'posting'] })
|
|
161
|
+
if (queued.length === 0) return { sent: 0, rejected: 0, stopped: false }
|
|
162
|
+
|
|
163
|
+
// BEFORE the connectivity probe, because it needs none: a row whose request
|
|
164
|
+
// storage already records as delivered ('unmined', 'completed', …) has
|
|
165
|
+
// nothing left to post. Until now that fact was only read inside `postOwned`,
|
|
166
|
+
// i.e. only on a pass that got past the probe and stepped the row — so a
|
|
167
|
+
// token tip that `settleNow` broadcast the moment it was handed over, or that
|
|
168
|
+
// the payee broadcast and this device later saw mined, kept its queue row at
|
|
169
|
+
// 'queued' (blue "settled", the "waiting" banner, no Refresh chip) whenever
|
|
170
|
+
// the drain was offline, stalled on a sibling, or never reached the step
|
|
171
|
+
// (2026-09-16).
|
|
172
|
+
const rows: OfflineActionRow[] = []
|
|
173
|
+
let sent = 0
|
|
174
|
+
for (const row of queued) {
|
|
175
|
+
const api = await findReq(storage, row.txid)
|
|
176
|
+
if (api && outcomeFromReqStatus(api.status) === 'success') {
|
|
177
|
+
devLog(`[processOfflineActions] storage already records '${api.status}' for ${row.txid}; closing its queue row`)
|
|
178
|
+
await updateOfflineAction(db, row.txid, { status: 'sent' })
|
|
179
|
+
if (token) await closeSettlementAsBroadcast(token.store, row.txid)
|
|
180
|
+
sent++
|
|
181
|
+
} else {
|
|
182
|
+
rows.push(row)
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (rows.length === 0) return { sent, rejected: 0, stopped: false }
|
|
91
186
|
|
|
92
187
|
if (!(await probeOnline())) {
|
|
93
188
|
devLog(`[processOfflineActions] offline, leaving ${rows.length} action(s) queued`)
|
|
94
|
-
return { sent
|
|
189
|
+
return { sent, rejected: 0, stopped: true }
|
|
95
190
|
}
|
|
96
191
|
|
|
97
192
|
// Merge every held request's BEEF into one graph. Anything that cannot be read
|
|
@@ -157,7 +252,6 @@ export async function processOfflineActions(args: {
|
|
|
157
252
|
const txs: OrderableTx[] = merged.txs
|
|
158
253
|
const plan = planRelease({ rows, txs })
|
|
159
254
|
|
|
160
|
-
let sent = 0
|
|
161
255
|
let rejected = 0
|
|
162
256
|
const resolved = new Set<string>()
|
|
163
257
|
const skip = new Set<string>()
|
|
@@ -185,7 +279,36 @@ export async function processOfflineActions(args: {
|
|
|
185
279
|
}
|
|
186
280
|
if (action) await updateOfflineAction(db, step.txid, { status: 'posting' })
|
|
187
281
|
|
|
188
|
-
|
|
282
|
+
// The ONE token branch. A transaction with a `token_settlements` row may
|
|
283
|
+
// not be broadcast until the issuer's overlay has admitted it and every
|
|
284
|
+
// unadmitted token ancestor it spends — so the ordinary post becomes
|
|
285
|
+
// `postTokenStep`'s injected `broadcast`, reached only after `/submit`
|
|
286
|
+
// says yes. Everything after this line — applyOutcome, the cascade, the
|
|
287
|
+
// requeue — is unchanged, because `postTokenStep` returns the same
|
|
288
|
+
// `PostOutcome` shape a BSV post does.
|
|
289
|
+
const read = token ? await readSettlement(token.store, step.txid) : { ok: true as const, row: undefined }
|
|
290
|
+
const broadcast = async () =>
|
|
291
|
+
action ? await postOwned(storage, action.api) : await postForeign(storage, merged, step.txid)
|
|
292
|
+
const outcome = !read.ok
|
|
293
|
+
? // The read failed, so this step does not know whether it is a token
|
|
294
|
+
// transaction. Stall it: `serviceError` leaves every row where it was
|
|
295
|
+
// and retries the whole prefix next pass.
|
|
296
|
+
('serviceError' as PostOutcome)
|
|
297
|
+
: read.row
|
|
298
|
+
? await postTokenStep(
|
|
299
|
+
{
|
|
300
|
+
store: token!.store,
|
|
301
|
+
cover: token!.cover,
|
|
302
|
+
submit: token!.submit,
|
|
303
|
+
overlayIdentityKey: token!.overlayIdentityKey,
|
|
304
|
+
verifyAdmission: token!.verifyAdmission,
|
|
305
|
+
journalRemove: token!.journalRemove,
|
|
306
|
+
broadcast
|
|
307
|
+
},
|
|
308
|
+
read.row,
|
|
309
|
+
step
|
|
310
|
+
)
|
|
311
|
+
: await broadcast()
|
|
189
312
|
// A cascade needs to see what spends the refused transaction, and beefs only
|
|
190
313
|
// reach backwards, so the graph the queue built cannot contain a spender that
|
|
191
314
|
// is not itself queued. Widened only when a cascade is actually about to run,
|
|
@@ -233,6 +356,35 @@ export async function processOfflineActions(args: {
|
|
|
233
356
|
}
|
|
234
357
|
}
|
|
235
358
|
|
|
359
|
+
/**
|
|
360
|
+
* Whether this txid has a settlement row — or whether the question could not be
|
|
361
|
+
* answered at all.
|
|
362
|
+
*
|
|
363
|
+
* The three outcomes are deliberately distinct, and the third is the fix. A
|
|
364
|
+
* thrown read (a locked database, a schema without these tables, a corrupt
|
|
365
|
+
* page) USED to fall back to `undefined`, which the caller cannot tell from
|
|
366
|
+
* "this is an ordinary BSV transaction" — so a read fault sent an unadmitted
|
|
367
|
+
* token tip straight to `broadcast()`, defeating the whole §4.3 gate on exactly
|
|
368
|
+
* the kind of transient fault the drain is built to survive. "I could not tell"
|
|
369
|
+
* must never resolve to "go ahead": the caller turns it into `serviceError`,
|
|
370
|
+
* the rows stay where they are, and the next pass asks again.
|
|
371
|
+
*
|
|
372
|
+
* The token guard in `StorageExpoSQLite.attemptToPostReqsToNetwork` reads the
|
|
373
|
+
* same table and would usually catch the same case — but it is reached only
|
|
374
|
+
* from `shareReqsWithWorld`, and `postForeign` does not go through it at all.
|
|
375
|
+
* Two independent barriers are worth having; one of them failing open is not.
|
|
376
|
+
*/
|
|
377
|
+
type SettlementRead = { ok: true; row: TokenSettlementRow | undefined } | { ok: false }
|
|
378
|
+
|
|
379
|
+
async function readSettlement(store: SettlementStore, txid: string): Promise<SettlementRead> {
|
|
380
|
+
try {
|
|
381
|
+
return { ok: true, row: await store.getSettlement(txid) }
|
|
382
|
+
} catch (e) {
|
|
383
|
+
devLog(`[processOfflineActions] could not read the settlement row for ${txid}:`, e)
|
|
384
|
+
return { ok: false }
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
236
388
|
async function tryMergeRefetchedBeef(
|
|
237
389
|
target: Beef,
|
|
238
390
|
txid: string,
|
|
@@ -367,6 +519,20 @@ async function postOwned(storage: StorageExpoSQLite, api: TableProvenTxReq): Pro
|
|
|
367
519
|
return recorded
|
|
368
520
|
}
|
|
369
521
|
|
|
522
|
+
// The second witness: the network itself. A nearby payment is broadcast by
|
|
523
|
+
// whichever side has signal first, and that is routinely the PAYEE — so the
|
|
524
|
+
// payer's own request is still 'nosend' for a transaction that is already in
|
|
525
|
+
// a mempool or a block. Re-posting it is at best a no-op and at worst a
|
|
526
|
+
// broadcaster's "inputs already spent"-shaped error that `outcomeOfOwnedPost`
|
|
527
|
+
// can only read as serviceError: re-held, re-queued, and stuck on every tick
|
|
528
|
+
// while the activity list says settled (2026-09-16). Asking first costs one
|
|
529
|
+
// status lookup and lets storage record what already happened.
|
|
530
|
+
if (await networkAlreadyHas(storage, api.txid)) {
|
|
531
|
+
devLog(`[processOfflineActions] the network already has ${api.txid}; recording delivery without a post`)
|
|
532
|
+
await recordDeliveredElsewhere(storage, api)
|
|
533
|
+
return 'success'
|
|
534
|
+
}
|
|
535
|
+
|
|
370
536
|
const attemptsBefore = api.attempts
|
|
371
537
|
const req = new EntityProvenTxReq(api)
|
|
372
538
|
// What to restore each transaction to, read before the post overwrites it.
|
|
@@ -412,6 +578,90 @@ async function postOwned(storage: StorageExpoSQLite, api: TableProvenTxReq): Pro
|
|
|
412
578
|
return 'serviceError'
|
|
413
579
|
}
|
|
414
580
|
|
|
581
|
+
/**
|
|
582
|
+
* `postOwned` for ONE txid, for a caller outside the queue loop.
|
|
583
|
+
*
|
|
584
|
+
* The Mandala runtime's `settleNow` needs a broadcast to hand `postTokenStep`
|
|
585
|
+
* the moment a hand-over lands, and it must be the SAME broadcast the drain
|
|
586
|
+
* uses — status transitions, history notes, `markStaleInputsAsSpent`, the
|
|
587
|
+
* re-hold on a service error, and the "storage is the witness, not the reported
|
|
588
|
+
* status" rule all live in `postOwned` and must not be reimplemented beside it.
|
|
589
|
+
* So this is the whole of the new surface: find the request, post it, report
|
|
590
|
+
* the same `PostOutcome`.
|
|
591
|
+
*
|
|
592
|
+
* A txid with no request of this wallet's own comes back `'serviceError'`
|
|
593
|
+
* rather than being posted some other way. That is deliberate: a FOREIGN
|
|
594
|
+
* ancestor is only ever broadcast as part of an ordered release over the merged
|
|
595
|
+
* graph (`postForeign`, from the plan), and guessing at that order from one
|
|
596
|
+
* txid is exactly the out-of-dependency-order broadcast this engine exists to
|
|
597
|
+
* prevent. `'serviceError'` leaves the row untouched for the next drain pass,
|
|
598
|
+
* which has the graph.
|
|
599
|
+
*/
|
|
600
|
+
export async function postOwnedByTxid(storage: StorageExpoSQLite, txid: string): Promise<PostOutcome> {
|
|
601
|
+
const api = await findReq(storage, txid)
|
|
602
|
+
if (!api) {
|
|
603
|
+
devLog(`[processOfflineActions] no request of our own for ${txid}; leaving its broadcast to the drain`)
|
|
604
|
+
return 'serviceError'
|
|
605
|
+
}
|
|
606
|
+
return await postOwned(storage, api)
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/**
|
|
610
|
+
* Whether the network already has `txid`, by the services' own status lookup
|
|
611
|
+
* ('mined' or 'known'). Every failure — no such service, a transport fault, an
|
|
612
|
+
* unexpected shape — is `false`: the answer then falls back to the ordinary
|
|
613
|
+
* post, whose own result decides. Never a reason to stall.
|
|
614
|
+
*/
|
|
615
|
+
async function networkAlreadyHas(storage: StorageExpoSQLite, txid: string): Promise<boolean> {
|
|
616
|
+
try {
|
|
617
|
+
const services = storage.getServices() as {
|
|
618
|
+
getStatusForTxids?: (txids: string[]) => Promise<{ results?: { txid: string; status: string }[] }>
|
|
619
|
+
}
|
|
620
|
+
if (typeof services.getStatusForTxids !== 'function') return false
|
|
621
|
+
const r = await services.getStatusForTxids([txid])
|
|
622
|
+
const status = r.results?.find(x => x.txid === txid)?.status
|
|
623
|
+
return status === 'mined' || status === 'known'
|
|
624
|
+
} catch (e) {
|
|
625
|
+
devLog(`[processOfflineActions] could not ask the network whether it has ${txid}:`, e)
|
|
626
|
+
return false
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* Record that `txid` reached the network by someone else's hand, exactly as the
|
|
632
|
+
* toolbox records its own successful post (`updateReqsFromAggregateResults`:
|
|
633
|
+
* request 'unmined', transaction 'unproven'). Only a transaction still at a
|
|
634
|
+
* pre-broadcast status is moved; anything past that is left to the monitor,
|
|
635
|
+
* which owns proofs and 'completed'.
|
|
636
|
+
*/
|
|
637
|
+
async function recordDeliveredElsewhere(storage: StorageExpoSQLite, api: TableProvenTxReq): Promise<void> {
|
|
638
|
+
await storage.updateProvenTxReq(api.provenTxReqId, { status: 'unmined' })
|
|
639
|
+
const req = new EntityProvenTxReq(api)
|
|
640
|
+
for (const transactionId of req.notify.transactionIds ?? []) {
|
|
641
|
+
try {
|
|
642
|
+
const tx = (await storage.findTransactions({ partial: { transactionId }, noRawTx: true }))[0]
|
|
643
|
+
if (tx && (tx.status === 'nosend' || tx.status === 'sending')) {
|
|
644
|
+
await storage.updateTransactionStatus('unproven', transactionId)
|
|
645
|
+
}
|
|
646
|
+
} catch (e) {
|
|
647
|
+
devLog(`[processOfflineActions] could not promote transaction ${transactionId} of ${api.txid}:`, e)
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/**
|
|
653
|
+
* The settlement twin of closing a queue row on a recorded delivery: the same
|
|
654
|
+
* advance `broadcastAdmittedTip` makes after a real post. Best-effort — the
|
|
655
|
+
* queue row is the durable fact, and `reconcileSettlements` re-derives rows.
|
|
656
|
+
*/
|
|
657
|
+
async function closeSettlementAsBroadcast(store: SettlementStore, txid: string): Promise<void> {
|
|
658
|
+
try {
|
|
659
|
+
await store.advanceSettlement(txid, ['admitted', 'submitting', 'held', 'handed_over'], 'broadcast')
|
|
660
|
+
} catch (e) {
|
|
661
|
+
devLog(`[processOfflineActions] could not close the settlement row of ${txid} as broadcast:`, e)
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
415
665
|
/**
|
|
416
666
|
* Post a foreign ancestor that arrived inside someone's BEEF.
|
|
417
667
|
*
|
|
@@ -424,6 +674,13 @@ async function postOwned(storage: StorageExpoSQLite, api: TableProvenTxReq): Pro
|
|
|
424
674
|
* one cannot end up posting the same graph to two different sets of providers.
|
|
425
675
|
*/
|
|
426
676
|
async function postForeign(storage: StorageExpoSQLite, merged: Beef, txid: string): Promise<PostOutcome> {
|
|
677
|
+
// Same witness as `postOwned`: an ancestor that arrived inside a counterparty's
|
|
678
|
+
// BEEF was usually broadcast by that counterparty already, and a failed
|
|
679
|
+
// re-post of it would block every owned transaction behind it.
|
|
680
|
+
if (await networkAlreadyHas(storage, txid)) {
|
|
681
|
+
devLog(`[processOfflineActions] the network already has foreign ancestor ${txid}; not posting`)
|
|
682
|
+
return 'success'
|
|
683
|
+
}
|
|
427
684
|
try {
|
|
428
685
|
const atomic = Beef.fromBinary(merged.toBinaryAtomic(txid))
|
|
429
686
|
const results = await storage.getServices().postBeef(atomic, [txid])
|
|
@@ -17,11 +17,23 @@
|
|
|
17
17
|
* the lock the writes need.
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
|
-
/**
|
|
21
|
-
*
|
|
22
|
-
*
|
|
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. */
|
|
@@ -360,6 +360,104 @@ export async function createTables(db: SQLiteDatabase): Promise<void> {
|
|
|
360
360
|
CREATE INDEX IF NOT EXISTS idx_offline_actions_seq ON offline_actions(seq);
|
|
361
361
|
CREATE INDEX IF NOT EXISTS idx_offline_actions_txid ON offline_actions(txid);
|
|
362
362
|
`)
|
|
363
|
+
|
|
364
|
+
await createMandalaSettlementTables(db)
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* The four Mandala settlement tables (offline-settlement spec §4.1).
|
|
369
|
+
*
|
|
370
|
+
* Additive only: nothing in `offline_actions`, `proven_tx_reqs` or the
|
|
371
|
+
* toolbox's own schema changes shape. `CREATE TABLE IF NOT EXISTS` is the whole
|
|
372
|
+
* migration — a device upgrading into this feature gets the tables empty on its
|
|
373
|
+
* next boot, and every row in them is re-derivable from frame bytes that are
|
|
374
|
+
* already durable elsewhere (FIX G), so there is nothing to backfill.
|
|
375
|
+
*
|
|
376
|
+
* Split into its own exported function so the settlement store's tests can
|
|
377
|
+
* stand the schema up without the rest of the wallet, and so a future migration
|
|
378
|
+
* runner has one named unit to call.
|
|
379
|
+
*/
|
|
380
|
+
export async function createMandalaSettlementTables(
|
|
381
|
+
db: Pick<SQLiteDatabase, 'execAsync' | 'getAllAsync'>
|
|
382
|
+
): Promise<void> {
|
|
383
|
+
// One row per token transaction this wallet has ever built, received, or
|
|
384
|
+
// forwarded evidence for — THE single owner of "what state is this token
|
|
385
|
+
// payment in" (spec §5). The `state` CHECK is deliberately the whole state
|
|
386
|
+
// machine: a state this file does not list is a bug that must fail at the
|
|
387
|
+
// write, not survive as an unreachable row nothing drains.
|
|
388
|
+
await db.execAsync(`
|
|
389
|
+
CREATE TABLE IF NOT EXISTS token_settlements (
|
|
390
|
+
txid TEXT PRIMARY KEY,
|
|
391
|
+
role TEXT NOT NULL CHECK (role IN ('sent','received')),
|
|
392
|
+
assetId TEXT NOT NULL,
|
|
393
|
+
state TEXT NOT NULL CHECK (state IN (
|
|
394
|
+
'built','parked','handed_over','held',
|
|
395
|
+
'submitting','admitted','broadcast','refused','orphaned')),
|
|
396
|
+
counterpartyKey TEXT,
|
|
397
|
+
amountBaseUnits INTEGER,
|
|
398
|
+
overlayUrl TEXT NOT NULL,
|
|
399
|
+
overlayIdentityKey TEXT NOT NULL,
|
|
400
|
+
admissionOutputsJson TEXT,
|
|
401
|
+
admissionSignatureHex TEXT,
|
|
402
|
+
refusedCode TEXT,
|
|
403
|
+
refusedPayloadHash TEXT,
|
|
404
|
+
poisonedByTxid TEXT,
|
|
405
|
+
reference TEXT,
|
|
406
|
+
createdAt TEXT NOT NULL,
|
|
407
|
+
updatedAt TEXT NOT NULL
|
|
408
|
+
);
|
|
409
|
+
CREATE INDEX IF NOT EXISTS idx_token_settlements_state ON token_settlements(state);
|
|
410
|
+
CREATE INDEX IF NOT EXISTS idx_token_settlements_role ON token_settlements(role);
|
|
411
|
+
CREATE INDEX IF NOT EXISTS idx_token_settlements_createdAt ON token_settlements(createdAt);
|
|
412
|
+
`)
|
|
413
|
+
|
|
414
|
+
// A device that created these tables before `reference` existed keeps them;
|
|
415
|
+
// CREATE TABLE IF NOT EXISTS cannot add the column, so the guarded ALTER does.
|
|
416
|
+
await ensureTokenSettlementColumns(db)
|
|
417
|
+
await db.execAsync(`CREATE INDEX IF NOT EXISTS idx_token_settlements_reference ON token_settlements(reference);`)
|
|
418
|
+
|
|
419
|
+
// Cached mirror of the AdmissionEntry values this device has SEEN. Purely a
|
|
420
|
+
// derivable cache (FIX G) — never a precondition for anything.
|
|
421
|
+
await db.execAsync(`
|
|
422
|
+
CREATE TABLE IF NOT EXISTS token_admissions (
|
|
423
|
+
txid TEXT PRIMARY KEY,
|
|
424
|
+
outputsToAdmitJson TEXT NOT NULL,
|
|
425
|
+
signatureHex TEXT NOT NULL,
|
|
426
|
+
signerKey TEXT NOT NULL,
|
|
427
|
+
source TEXT NOT NULL CHECK (source IN ('minted','bundle','submitted','fetched')),
|
|
428
|
+
obtainedAt TEXT NOT NULL
|
|
429
|
+
);
|
|
430
|
+
CREATE INDEX IF NOT EXISTS idx_token_admissions_signerKey ON token_admissions(signerKey);
|
|
431
|
+
`)
|
|
432
|
+
|
|
433
|
+
// Edge index for the recursive COVER walk, so coverage is a local SQL query
|
|
434
|
+
// rather than a re-parse of a whole BEEF on every pass. Token inputs only
|
|
435
|
+
// (FIX K): a plain BSV change input funding the fee is not a token ancestor.
|
|
436
|
+
await db.execAsync(`
|
|
437
|
+
CREATE TABLE IF NOT EXISTS token_admission_edges (
|
|
438
|
+
childTxid TEXT NOT NULL,
|
|
439
|
+
parentTxid TEXT NOT NULL,
|
|
440
|
+
parentVout INTEGER NOT NULL,
|
|
441
|
+
PRIMARY KEY (childTxid, parentTxid, parentVout)
|
|
442
|
+
);
|
|
443
|
+
CREATE INDEX IF NOT EXISTS idx_token_admission_edges_child ON token_admission_edges(childTxid);
|
|
444
|
+
CREATE INDEX IF NOT EXISTS idx_token_admission_edges_parent ON token_admission_edges(parentTxid);
|
|
445
|
+
`)
|
|
446
|
+
|
|
447
|
+
// Off-chain linkage payloads for UNADMITTED chain transactions: the exact
|
|
448
|
+
// bytes a downstream submitter needs to build the /submit body for a txid
|
|
449
|
+
// nobody has σ_I for yet. Carried verbatim hop by hop — this device can never
|
|
450
|
+
// decrypt one, only forward it.
|
|
451
|
+
await db.execAsync(`
|
|
452
|
+
CREATE TABLE IF NOT EXISTS token_linkage_payloads (
|
|
453
|
+
txid TEXT PRIMARY KEY,
|
|
454
|
+
payloadBytes BLOB NOT NULL,
|
|
455
|
+
overlayUrl TEXT NOT NULL,
|
|
456
|
+
overlayIdentityKey TEXT NOT NULL,
|
|
457
|
+
source TEXT NOT NULL CHECK (source IN ('minted','forwarded')),
|
|
458
|
+
createdAt TEXT NOT NULL
|
|
459
|
+
);
|
|
460
|
+
`)
|
|
363
461
|
}
|
|
364
462
|
|
|
365
463
|
/**
|
|
@@ -383,3 +481,28 @@ export async function ensureOfflineActionsColumns(db: {
|
|
|
383
481
|
if (!have.has(col.name)) await db.execAsync(col.ddl)
|
|
384
482
|
}
|
|
385
483
|
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* The same doctrine for `token_settlements`, which shipped before it had a
|
|
487
|
+
* `reference` column and cannot be re-created over live rows.
|
|
488
|
+
*
|
|
489
|
+
* A nullable column with no default: every existing row reads back
|
|
490
|
+
* `reference === undefined`, which the abort guard treats as "unknown
|
|
491
|
+
* reference" and therefore never blocks on. The wallet re-derives these rows
|
|
492
|
+
* every drain tick (FIX G) but only from frame bytes, which do not carry a
|
|
493
|
+
* wallet action reference — so the backfill is simply the next hand-over.
|
|
494
|
+
*/
|
|
495
|
+
const TOKEN_SETTLEMENT_COLUMNS: { name: string; ddl: string }[] = [
|
|
496
|
+
{ name: 'reference', ddl: 'ALTER TABLE token_settlements ADD COLUMN reference TEXT' }
|
|
497
|
+
]
|
|
498
|
+
|
|
499
|
+
export async function ensureTokenSettlementColumns(db: {
|
|
500
|
+
getAllAsync(sql: string, params: BindValue[]): Promise<unknown[]>
|
|
501
|
+
execAsync(sql: string): Promise<unknown>
|
|
502
|
+
}): Promise<void> {
|
|
503
|
+
const info = (await db.getAllAsync('PRAGMA table_info(token_settlements)', [])) as { name: string }[]
|
|
504
|
+
const have = new Set(info.map(c => c.name))
|
|
505
|
+
for (const col of TOKEN_SETTLEMENT_COLUMNS) {
|
|
506
|
+
if (!have.has(col.name)) await db.execAsync(col.ddl)
|
|
507
|
+
}
|
|
508
|
+
}
|
|
@@ -1,5 +1,29 @@
|
|
|
1
|
+
import { BLOB_COLUMNS } from './methods/findSql'
|
|
2
|
+
|
|
1
3
|
export type SqlBindResult = { omit: true } | { omit: false; value: unknown }
|
|
2
4
|
|
|
5
|
+
/** Every column the schema declares BLOB, by name; no two tables disagree about one. */
|
|
6
|
+
export const BYTE_COLUMNS: ReadonlySet<string> = new Set(Object.values(BLOB_COLUMNS).flat())
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The bind for a byte column: bytes, or nothing.
|
|
10
|
+
*
|
|
11
|
+
* expo-sqlite binds only a `Uint8Array` as a BLOB. Anything else reaches the
|
|
12
|
+
* native layer as a primitive, which Android stringifies into TEXT and iOS
|
|
13
|
+
* refuses — how a JSON-rehydrated payload (an index-keyed object) became an
|
|
14
|
+
* unreadable `token_linkage_payloads` row on 2026-09-16. Refused here, while
|
|
15
|
+
* the column is still named, rather than stored in the wrong storage class.
|
|
16
|
+
*/
|
|
17
|
+
export function bytesForColumn(column: string, value: unknown): Uint8Array | undefined {
|
|
18
|
+
if (value === undefined || value === null) return undefined
|
|
19
|
+
if (value instanceof Uint8Array) return value
|
|
20
|
+
if (value instanceof ArrayBuffer) return new Uint8Array(value)
|
|
21
|
+
if (Array.isArray(value) && value.every(b => Number.isInteger(b))) return Uint8Array.from(value as number[])
|
|
22
|
+
throw new Error(
|
|
23
|
+
`${column} must be bytes (Uint8Array or number[]), got ${Array.isArray(value) ? 'a non-integer array' : typeof value}`
|
|
24
|
+
)
|
|
25
|
+
}
|
|
26
|
+
|
|
3
27
|
/** Map an update field to a SQL bind, or omit it from the SET clause. */
|
|
4
28
|
export function sqlBindValue(table: string, column: string, value: unknown): SqlBindResult {
|
|
5
29
|
if (value === undefined) {
|