@bsv/expo-wallet-toolbox 0.21.0 → 0.23.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 (133) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/README.md +82 -13
  3. package/core/bridge/BrowserBridgeProvider.tsx +273 -0
  4. package/core/bridge/bindings.ts +459 -0
  5. package/core/bridge/conformance.ts +222 -0
  6. package/core/bridge/consent.ts +494 -0
  7. package/core/bridge/consentSheetSource.ts +98 -0
  8. package/core/bridge/dispatcher.ts +621 -0
  9. package/core/bridge/inbox.ts +464 -0
  10. package/core/bridge/index.ts +48 -0
  11. package/core/bridge/loopback/cors.ts +57 -0
  12. package/core/bridge/loopback/endpoints.ts +11 -0
  13. package/core/bridge/loopback/hostCheck.ts +25 -0
  14. package/core/bridge/loopback/index.ts +7 -0
  15. package/core/bridge/loopback/launchProof.ts +166 -0
  16. package/core/bridge/loopback/router.ts +770 -0
  17. package/core/bridge/loopback/routerTypes.ts +115 -0
  18. package/core/bridge/loopback/status.ts +52 -0
  19. package/core/bridge/memoryInboxStore.ts +222 -0
  20. package/core/bridge/permissionPolicy.ts +247 -0
  21. package/core/bridge/policy.ts +72 -0
  22. package/core/bridge/protocol/base64url.ts +64 -0
  23. package/core/bridge/protocol/connectionError.ts +79 -0
  24. package/core/bridge/protocol/constants.ts +21 -0
  25. package/core/bridge/protocol/continuity.ts +21 -0
  26. package/core/bridge/protocol/descriptor.ts +395 -0
  27. package/core/bridge/protocol/envelopes.ts +188 -0
  28. package/core/bridge/protocol/errorCodec.ts +164 -0
  29. package/core/bridge/protocol/json.ts +237 -0
  30. package/core/bridge/protocol/limits.ts +43 -0
  31. package/core/bridge/protocol/methods.ts +55 -0
  32. package/core/bridge/protocol/origin.ts +130 -0
  33. package/core/bridge/runtime.ts +642 -0
  34. package/core/bridge/runtimeFlags.ts +34 -0
  35. package/core/bridge/testing/conformanceCases.ts +149 -0
  36. package/core/bridge/testing/pageClient.ts +44 -0
  37. package/core/bridge/unverifiedManager.ts +97 -0
  38. package/core/bridge/unverifiedOriginator.ts +79 -0
  39. package/core/config.tsx +1 -16
  40. package/core/contacts/contactActivity.ts +48 -28
  41. package/core/contacts/contactsStore.ts +2 -2
  42. package/core/context/WalletConnectionContext.tsx +7 -1
  43. package/core/context/WalletContext.tsx +420 -348
  44. package/core/context/sessionTeardown.ts +46 -0
  45. package/core/demo/demoAssets.ts +8 -10
  46. package/core/demo/demoLedger.ts +32 -38
  47. package/core/demo/demoMandalaRuntime.ts +67 -49
  48. package/core/demo/index.ts +1 -1
  49. package/core/hooks/usePermissionQueue.ts +89 -34
  50. package/core/i18n/translations.tsx +983 -12
  51. package/core/index.ts +70 -37
  52. package/core/localpay/build.ts +110 -569
  53. package/core/localpay/codec.ts +190 -93
  54. package/core/localpay/pending.ts +217 -202
  55. package/core/localpay/session.ts +99 -25
  56. package/core/localpay/types.ts +6 -5
  57. package/core/localpay/verify.ts +118 -173
  58. package/core/mandala/abortGuard.ts +97 -120
  59. package/core/mandala/accessPolicy.ts +133 -0
  60. package/core/mandala/assets.ts +370 -0
  61. package/core/mandala/colorGuard.ts +178 -0
  62. package/core/mandala/colorModule.ts +82 -0
  63. package/core/mandala/createRuntime.ts +483 -2392
  64. package/core/mandala/handle.ts +694 -0
  65. package/core/mandala/kvStore.ts +105 -0
  66. package/core/mandala/nearby.ts +185 -0
  67. package/core/mandala/receipt.ts +121 -0
  68. package/core/mandala/runtime.ts +166 -312
  69. package/core/mandala/settle.ts +540 -0
  70. package/core/mandala/transferJournal.ts +395 -0
  71. package/core/mandala/types.ts +61 -311
  72. package/core/networks.ts +5 -5
  73. package/core/offline/cancelParked.ts +80 -63
  74. package/core/offline/payerHold.ts +52 -118
  75. package/core/parsePeerPayURI.ts +25 -12
  76. package/core/pay/rails/handle.ts +15 -14
  77. package/core/pay/rails/index.ts +5 -3
  78. package/core/pay/rails/nearby.ts +25 -87
  79. package/core/profiles/assertProfileEmpty.ts +19 -10
  80. package/core/services/autoApprovePolicy.ts +7 -1
  81. package/core/services/capWalletArgs.ts +2 -1
  82. package/core/services/permissionPrompts.ts +132 -0
  83. package/core/services/signingPermissionPolicy.ts +230 -2
  84. package/core/services/vault/guard.ts +15 -4
  85. package/core/services/walletArgLimits.ts +17 -2
  86. package/core/storage/StorageExpoSQLite.ts +93 -229
  87. package/core/storage/encryptedDbImage.ts +325 -0
  88. package/core/storage/methods/processOfflineActions.ts +86 -136
  89. package/core/storage/schema/createTables.ts +9 -184
  90. package/core/toolboxConfig.ts +18 -1
  91. package/package.json +9 -8
  92. package/ui/bridgeSheet/ContextRelay.tsx +86 -0
  93. package/ui/bridgeSheet/relayedContexts.ts +21 -0
  94. package/ui/components/pay/AssetPicker.tsx +2 -2
  95. package/ui/components/pay/HandleReceive.tsx +4 -4
  96. package/ui/components/pay/NearbyFlow.tsx +324 -239
  97. package/ui/components/pay/RequestHub.tsx +10 -0
  98. package/ui/components/pay/UniversalSend.tsx +31 -28
  99. package/ui/components/pay/useRecipientInput.ts +2 -2
  100. package/ui/components/ui/PermissionSheet.tsx +625 -315
  101. package/ui/components/ui/Sheet.tsx +59 -7
  102. package/ui/components/ui/colorPrompt.ts +236 -0
  103. package/ui/components/ui/sheetResumeSignal.ts +19 -0
  104. package/ui/components/wallet/AmountInput.tsx +9 -6
  105. package/ui/components/wallet/AssetAmount.tsx +6 -6
  106. package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
  107. package/ui/components/wallet/Balance.tsx +3 -1
  108. package/ui/components/wallet/ContactActivityList.tsx +10 -13
  109. package/ui/components/wallet/tokenEviction.ts +9 -9
  110. package/ui/exportDatabases.ts +94 -5
  111. package/ui/hooks/useExportWalletData.ts +37 -24
  112. package/ui/hooks/useMandala.ts +6 -6
  113. package/ui/hooks/useSpendableBalance.ts +3 -1
  114. package/ui/importDatabases.ts +124 -29
  115. package/ui/index.ts +4 -0
  116. package/ui/screens/PayScreen.tsx +14 -20
  117. package/ui/screens/SettingsScreen.tsx +3 -1
  118. package/ui/screens/WalletCheckScreen.tsx +7 -2
  119. package/ui/screens/WalletConfigScreen.tsx +13 -1
  120. package/ui/screens/WalletHomeScreen.tsx +40 -14
  121. package/ui/screens/tokenRowTitle.ts +28 -15
  122. package/ui/tokenFormat.ts +133 -69
  123. package/ui/tokenStatus.ts +5 -8
  124. package/core/localpay/settlementAck.ts +0 -155
  125. package/core/mandala/basketMigration.ts +0 -166
  126. package/core/mandala/bundle.ts +0 -244
  127. package/core/mandala/drain.ts +0 -754
  128. package/core/mandala/inboxPrehold.ts +0 -193
  129. package/core/mandala/permissionModule.ts +0 -931
  130. package/core/mandala/resendTransfer.ts +0 -178
  131. package/core/mandala/settlementStore.ts +0 -434
  132. package/core/mandala/token.ts +0 -45
  133. package/core/offline/tokenFrames.ts +0 -197
@@ -0,0 +1,395 @@
1
+ /**
2
+ * `color_transfers`: the wallet's one durable host record of a 1Color
3
+ * transfer, and the one-time migration that replaced the four Mandala σI
4
+ * settlement tables with it.
5
+ *
6
+ * The journal is the only key for the two incident guards (plan 07, W1): the
7
+ * broadcast hold in `StorageExpoSQLite` (a tx with a 1Color output is held
8
+ * unless its row reads `settled`; a missing row holds) and the abort refusal
9
+ * (`abortGuard.ts`, by `reference`). Token custody and evidence live in the
10
+ * color permission module, never here.
11
+ *
12
+ * Rules every method keeps:
13
+ * - `units` is a canonical decimal TEXT on disk and a `bigint` in memory. A
14
+ * value that does not read back exactly is a thrown error, never a
15
+ * coerced number (IC §0).
16
+ * - `insert` is `INSERT OR IGNORE` and reports whether it wrote, so a
17
+ * double-tapped send or a crash-and-retry never forks a row.
18
+ * - `advance` is one compare-and-set statement, so two concurrent callers
19
+ * (the drain tick racing a screen) can never both win a transition.
20
+ * - Read faults propagate. The guards above turn them into "hold" or
21
+ * "refuse"; swallowing one here would read as "no row" and fail open.
22
+ *
23
+ * This file imports types only: `createTables.ts` imports the migration from
24
+ * here, and nothing here may import the schema file back.
25
+ */
26
+ import type { SQLiteDatabase } from 'expo-sqlite'
27
+ import {
28
+ COLOR_TRANSFER_RAILS,
29
+ COLOR_TRANSFER_ROLES,
30
+ COLOR_TRANSFER_STATES,
31
+ type ColorTransferRail,
32
+ type ColorTransferRole,
33
+ type ColorTransferRow,
34
+ type ColorTransferState
35
+ } from './types'
36
+
37
+ type Param = string | number | null
38
+
39
+ /** The two expo-sqlite methods the journal uses. `StorageExpoSQLite`'s connection satisfies it. */
40
+ export interface JournalDb {
41
+ runAsync(sql: string, p: Param[]): Promise<{ changes: number }>
42
+ getAllAsync(sql: string, p: Param[]): Promise<unknown[]>
43
+ }
44
+
45
+ export interface TransferJournal {
46
+ get(txid: string): Promise<ColorTransferRow | undefined>
47
+ /** The newest row built by the wallet action with this `createAction` reference. */
48
+ getByReference(reference: string): Promise<ColorTransferRow | undefined>
49
+ /** Newest `createdAt` first. An empty `states` list matches nothing. */
50
+ list(filter?: { states?: ColorTransferState[]; role?: ColorTransferRole; limit?: number }): Promise<ColorTransferRow[]>
51
+ /** `INSERT OR IGNORE`: true when this call wrote the row, false when it already existed (left untouched). */
52
+ insert(row: Omit<ColorTransferRow, 'createdAt' | 'updatedAt'>): Promise<boolean>
53
+ /** Single-statement CAS: moves the row to `to` only if it is in one of `from`. The patch lands in the same statement. */
54
+ advance(
55
+ txid: string,
56
+ from: readonly ColorTransferState[],
57
+ to: ColorTransferState,
58
+ patch?: { code?: string; delivered?: boolean }
59
+ ): Promise<boolean>
60
+ setDelivered(txid: string, delivered: boolean): Promise<void>
61
+ /** The state of each txid that has a row. A txid with no row is absent from the map. Read faults propagate. */
62
+ statesOf(txids: readonly string[]): Promise<Map<string, ColorTransferState>>
63
+ }
64
+
65
+ // ───────────────────────────────── schema ─────────────────────────────────
66
+
67
+ /** Written last by the migration; its presence means the one-time wipe has run. */
68
+ export const COLOR_MIGRATION_MARKER = 'bsvwallet.migration.color.v1'
69
+
70
+ /** The pre-1color settlement tables. Their indexes drop with them. */
71
+ export const LEGACY_MANDALA_TABLES = [
72
+ 'token_settlements',
73
+ 'token_admissions',
74
+ 'token_admission_edges',
75
+ 'token_linkage_payloads'
76
+ ] as const
77
+
78
+ /**
79
+ * The journal's DDL. Idempotent, and the single definition both the
80
+ * migration and `createTables` run, so the two can never drift (the backup
81
+ * import's schema allow-list is built from `createTables`).
82
+ *
83
+ * No CHECK constraints: the journal validates on every write and every read
84
+ * instead, and a later state can be added without a table rebuild.
85
+ */
86
+ export const COLOR_TRANSFERS_DDL = `
87
+ CREATE TABLE IF NOT EXISTS color_transfers (
88
+ txid TEXT PRIMARY KEY,
89
+ role TEXT NOT NULL,
90
+ assetId TEXT NOT NULL,
91
+ units TEXT NOT NULL,
92
+ outputIndex INTEGER NOT NULL,
93
+ counterpartyKey TEXT,
94
+ reference TEXT,
95
+ rail TEXT NOT NULL,
96
+ state TEXT NOT NULL,
97
+ delivered INTEGER NOT NULL DEFAULT 0,
98
+ code TEXT,
99
+ note TEXT,
100
+ derivationPrefix TEXT,
101
+ derivationSuffix TEXT,
102
+ senderIdentityKey TEXT,
103
+ createdAt TEXT NOT NULL,
104
+ updatedAt TEXT NOT NULL
105
+ );
106
+ CREATE INDEX IF NOT EXISTS idx_color_transfers_state ON color_transfers(state);
107
+ CREATE INDEX IF NOT EXISTS idx_color_transfers_reference ON color_transfers(reference);
108
+ CREATE INDEX IF NOT EXISTS idx_color_transfers_createdAt ON color_transfers(createdAt);
109
+ `
110
+
111
+ type MigrationDb = Pick<SQLiteDatabase, 'execAsync' | 'getAllAsync'> &
112
+ Partial<Pick<SQLiteDatabase, 'withTransactionAsync'>>
113
+
114
+ /**
115
+ * One-time move off the Mandala σI settlement machinery. Runs from
116
+ * `createTables`, which runs on every boot before the runtime, the module or
117
+ * `@bsv/mandala` exist, so no 0.5.0 lib journal can be written before the
118
+ * wipe and none is ever wiped after it: the marker guards every later boot.
119
+ *
120
+ * Steps, in one transaction: marker present ⇒ 'already'; otherwise drop the
121
+ * four tables, delete the old lib's `mandala.` KV journals (exact,
122
+ * case-sensitive prefix), create `color_transfers`, write the marker. Every
123
+ * step is idempotent and the marker is written last, so a crash at any point
124
+ * converges on the next boot even without the transaction.
125
+ *
126
+ * `withTransactionAsync` is used when the connection has it (expo-sqlite
127
+ * always does); otherwise the same steps run between an explicit
128
+ * `BEGIN`/`COMMIT`, with `ROLLBACK` on a throw.
129
+ */
130
+ export async function migrateMandalaToColor(db: MigrationDb): Promise<'migrated' | 'already'> {
131
+ let outcome: 'migrated' | 'already' = 'already'
132
+ const steps = async (): Promise<void> => {
133
+ const marker = await db.getAllAsync('SELECT 1 AS found FROM key_value_store WHERE key = ?', [
134
+ COLOR_MIGRATION_MARKER
135
+ ])
136
+ if (marker.length > 0) {
137
+ outcome = 'already'
138
+ return
139
+ }
140
+ for (const table of LEGACY_MANDALA_TABLES) await db.execAsync(`DROP TABLE IF EXISTS ${table}`)
141
+ // GLOB, not LIKE: LIKE is case-insensitive and treats '_' as a wildcard.
142
+ await db.execAsync(`DELETE FROM key_value_store WHERE key GLOB 'mandala.*'`)
143
+ await db.execAsync(COLOR_TRANSFERS_DDL)
144
+ // execAsync with literals (a constant key, a generated ISO timestamp):
145
+ // createTables' callers include minimal connections with no runAsync.
146
+ const at = new Date().toISOString()
147
+ await db.execAsync(
148
+ `INSERT OR IGNORE INTO key_value_store (key, value, updated_at) VALUES ('${COLOR_MIGRATION_MARKER}', '${at}', '${at}')`
149
+ )
150
+ outcome = 'migrated'
151
+ }
152
+
153
+ if (typeof db.withTransactionAsync === 'function') {
154
+ await db.withTransactionAsync(steps)
155
+ } else {
156
+ await db.execAsync('BEGIN')
157
+ try {
158
+ await steps()
159
+ } catch (e) {
160
+ try {
161
+ await db.execAsync('ROLLBACK')
162
+ } catch {
163
+ // The original fault is the one worth reporting.
164
+ }
165
+ throw e
166
+ }
167
+ await db.execAsync('COMMIT')
168
+ }
169
+ return outcome
170
+ }
171
+
172
+ // ──────────────────────────────── validation ────────────────────────────────
173
+
174
+ const TXID_RE = /^[0-9a-f]{64}$/
175
+ const ASSET_ID_RE = /^[0-9a-f]{64}_(0|[1-9][0-9]{0,9})$/
176
+ const UNITS_RE = /^(0|[1-9][0-9]*)$/
177
+ /** Stay well under SQLite's bound-parameter ceiling on every build. */
178
+ const STATES_OF_CHUNK = 500
179
+
180
+ function fail(what: string, value: unknown): never {
181
+ throw new Error(`color_transfers: invalid ${what} ${JSON.stringify(typeof value === 'bigint' ? `${value}n` : value)}`)
182
+ }
183
+
184
+ function checkState(state: unknown): ColorTransferState {
185
+ if (!COLOR_TRANSFER_STATES.includes(state as ColorTransferState)) fail('state', state)
186
+ return state as ColorTransferState
187
+ }
188
+
189
+ function checkTxid(txid: unknown): string {
190
+ if (typeof txid !== 'string' || !TXID_RE.test(txid)) fail('txid', txid)
191
+ return txid
192
+ }
193
+
194
+ function unitsToText(units: unknown): string {
195
+ if (typeof units !== 'bigint' || units < 0n) fail('units', units)
196
+ return units.toString()
197
+ }
198
+
199
+ function unitsFromText(text: unknown): bigint {
200
+ if (typeof text !== 'string' || !UNITS_RE.test(text)) fail('units', text)
201
+ return BigInt(text)
202
+ }
203
+
204
+ function checkIndex(n: unknown): number {
205
+ if (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0) fail('outputIndex', n)
206
+ return n
207
+ }
208
+
209
+ function optText(v: unknown, what: string): string | undefined {
210
+ if (v === null || v === undefined) return undefined
211
+ if (typeof v !== 'string') fail(what, v)
212
+ return v
213
+ }
214
+
215
+ interface DbRow {
216
+ txid: unknown
217
+ role: unknown
218
+ assetId: unknown
219
+ units: unknown
220
+ outputIndex: unknown
221
+ counterpartyKey: unknown
222
+ reference: unknown
223
+ rail: unknown
224
+ state: unknown
225
+ delivered: unknown
226
+ code: unknown
227
+ note: unknown
228
+ derivationPrefix: unknown
229
+ derivationSuffix: unknown
230
+ senderIdentityKey: unknown
231
+ createdAt: unknown
232
+ updatedAt: unknown
233
+ }
234
+
235
+ /** A row exactly as written, or a throw. Never a best-effort guess. */
236
+ function fromDb(r: DbRow): ColorTransferRow {
237
+ if (!COLOR_TRANSFER_ROLES.includes(r.role as ColorTransferRole)) fail('role', r.role)
238
+ if (!COLOR_TRANSFER_RAILS.includes(r.rail as ColorTransferRail)) fail('rail', r.rail)
239
+ if (typeof r.assetId !== 'string') fail('assetId', r.assetId)
240
+ if (r.delivered !== 0 && r.delivered !== 1) fail('delivered', r.delivered)
241
+ if (typeof r.createdAt !== 'string') fail('createdAt', r.createdAt)
242
+ if (typeof r.updatedAt !== 'string') fail('updatedAt', r.updatedAt)
243
+ const row: ColorTransferRow = {
244
+ txid: checkTxid(r.txid),
245
+ role: r.role as ColorTransferRole,
246
+ assetId: r.assetId,
247
+ units: unitsFromText(r.units),
248
+ outputIndex: checkIndex(r.outputIndex),
249
+ rail: r.rail as ColorTransferRail,
250
+ state: checkState(r.state),
251
+ delivered: r.delivered === 1,
252
+ createdAt: r.createdAt,
253
+ updatedAt: r.updatedAt
254
+ }
255
+ const optional = {
256
+ counterpartyKey: optText(r.counterpartyKey, 'counterpartyKey'),
257
+ reference: optText(r.reference, 'reference'),
258
+ code: optText(r.code, 'code'),
259
+ note: optText(r.note, 'note'),
260
+ derivationPrefix: optText(r.derivationPrefix, 'derivationPrefix'),
261
+ derivationSuffix: optText(r.derivationSuffix, 'derivationSuffix'),
262
+ senderIdentityKey: optText(r.senderIdentityKey, 'senderIdentityKey')
263
+ }
264
+ for (const [k, v] of Object.entries(optional)) if (v !== undefined) (row as unknown as Record<string, unknown>)[k] = v
265
+ return row
266
+ }
267
+
268
+ const COLUMNS =
269
+ 'txid, role, assetId, units, outputIndex, counterpartyKey, reference, rail, state, delivered, code, note, derivationPrefix, derivationSuffix, senderIdentityKey, createdAt, updatedAt'
270
+
271
+ // ───────────────────────────────── journal ─────────────────────────────────
272
+
273
+ export function createTransferJournal(db: JournalDb, now: () => Date = () => new Date()): TransferJournal {
274
+ const select = async (where: string, params: Param[], tail = ''): Promise<ColorTransferRow[]> => {
275
+ const rows = (await db.getAllAsync(`SELECT ${COLUMNS} FROM color_transfers ${where} ${tail}`, params)) as DbRow[]
276
+ return rows.map(fromDb)
277
+ }
278
+
279
+ return {
280
+ async get(txid) {
281
+ const [row] = await select('WHERE txid = ?', [txid], 'LIMIT 1')
282
+ return row
283
+ },
284
+
285
+ async getByReference(reference) {
286
+ const [row] = await select('WHERE reference = ?', [reference], 'ORDER BY createdAt DESC, rowid DESC LIMIT 1')
287
+ return row
288
+ },
289
+
290
+ async list(filter = {}) {
291
+ const clauses: string[] = []
292
+ const params: Param[] = []
293
+ if (filter.states !== undefined) {
294
+ if (filter.states.length === 0) return []
295
+ filter.states.forEach(checkState)
296
+ clauses.push(`state IN (${filter.states.map(() => '?').join(',')})`)
297
+ params.push(...filter.states)
298
+ }
299
+ if (filter.role !== undefined) {
300
+ if (!COLOR_TRANSFER_ROLES.includes(filter.role)) fail('role', filter.role)
301
+ clauses.push('role = ?')
302
+ params.push(filter.role)
303
+ }
304
+ let tail = 'ORDER BY createdAt DESC, rowid DESC'
305
+ if (filter.limit !== undefined) {
306
+ if (!Number.isSafeInteger(filter.limit) || filter.limit < 0) fail('limit', filter.limit)
307
+ if (filter.limit === 0) return []
308
+ tail += ' LIMIT ?'
309
+ params.push(filter.limit)
310
+ }
311
+ return await select(clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '', params, tail)
312
+ },
313
+
314
+ async insert(row) {
315
+ checkTxid(row.txid)
316
+ if (!COLOR_TRANSFER_ROLES.includes(row.role)) fail('role', row.role)
317
+ if (!COLOR_TRANSFER_RAILS.includes(row.rail)) fail('rail', row.rail)
318
+ if (typeof row.assetId !== 'string' || !ASSET_ID_RE.test(row.assetId)) fail('assetId', row.assetId)
319
+ checkState(row.state)
320
+ const units = unitsToText(row.units)
321
+ const outputIndex = checkIndex(row.outputIndex)
322
+ if (typeof row.delivered !== 'boolean') fail('delivered', row.delivered)
323
+ const at = now().toISOString()
324
+ const r = await db.runAsync(
325
+ `INSERT OR IGNORE INTO color_transfers (${COLUMNS}) VALUES (${COLUMNS.split(',')
326
+ .map(() => '?')
327
+ .join(', ')})`,
328
+ [
329
+ row.txid,
330
+ row.role,
331
+ row.assetId,
332
+ units,
333
+ outputIndex,
334
+ row.counterpartyKey ?? null,
335
+ row.reference ?? null,
336
+ row.rail,
337
+ row.state,
338
+ row.delivered ? 1 : 0,
339
+ row.code ?? null,
340
+ row.note ?? null,
341
+ row.derivationPrefix ?? null,
342
+ row.derivationSuffix ?? null,
343
+ row.senderIdentityKey ?? null,
344
+ at,
345
+ at
346
+ ]
347
+ )
348
+ return r.changes === 1
349
+ },
350
+
351
+ async advance(txid, from, to, patch = {}) {
352
+ checkState(to)
353
+ from.forEach(checkState)
354
+ if (from.length === 0) return false
355
+ const sets = ['state = ?', 'updatedAt = ?']
356
+ const params: Param[] = [to, now().toISOString()]
357
+ if (patch.code !== undefined) {
358
+ sets.push('code = ?')
359
+ params.push(patch.code)
360
+ }
361
+ if (patch.delivered !== undefined) {
362
+ sets.push('delivered = ?')
363
+ params.push(patch.delivered ? 1 : 0)
364
+ }
365
+ params.push(txid, ...from)
366
+ const r = await db.runAsync(
367
+ `UPDATE color_transfers SET ${sets.join(', ')} WHERE txid = ? AND state IN (${from.map(() => '?').join(',')})`,
368
+ params
369
+ )
370
+ return r.changes === 1
371
+ },
372
+
373
+ async setDelivered(txid, delivered) {
374
+ await db.runAsync('UPDATE color_transfers SET delivered = ?, updatedAt = ? WHERE txid = ?', [
375
+ delivered ? 1 : 0,
376
+ now().toISOString(),
377
+ txid
378
+ ])
379
+ },
380
+
381
+ async statesOf(txids) {
382
+ const out = new Map<string, ColorTransferState>()
383
+ const unique = [...new Set(txids)]
384
+ for (let i = 0; i < unique.length; i += STATES_OF_CHUNK) {
385
+ const chunk = unique.slice(i, i + STATES_OF_CHUNK)
386
+ const rows = (await db.getAllAsync(
387
+ `SELECT txid, state FROM color_transfers WHERE txid IN (${chunk.map(() => '?').join(',')})`,
388
+ chunk
389
+ )) as { txid: string; state: unknown }[]
390
+ for (const r of rows) out.set(r.txid, checkState(r.state))
391
+ }
392
+ return out
393
+ }
394
+ }
395
+ }