@bsv/expo-wallet-toolbox 0.4.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/CHANGELOG.md +547 -0
  2. package/README.md +19 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/amountFormatHelpers.ts +238 -34
  6. package/core/backup/RemoteSyncReader.ts +2 -5
  7. package/core/backup/codec.ts +2 -2
  8. package/core/backup/push.ts +1 -1
  9. package/core/config.tsx +16 -1
  10. package/core/contacts/contactActivity.ts +153 -0
  11. package/core/contacts/contactCache.ts +41 -0
  12. package/core/contacts/contactsStore.ts +183 -0
  13. package/core/context/VaultContext.tsx +8 -11
  14. package/core/context/WalletConnectionContext.tsx +137 -52
  15. package/core/context/WalletContext.tsx +464 -30
  16. package/core/demo/demoAssets.ts +60 -0
  17. package/core/demo/demoLedger.ts +240 -0
  18. package/core/demo/demoMandalaRuntime.ts +96 -0
  19. package/core/demo/demoMode.ts +38 -0
  20. package/core/demo/demoWallet.ts +25 -0
  21. package/core/demo/index.ts +26 -0
  22. package/core/demo/useDemo.ts +59 -0
  23. package/core/headers/OfflineFirstChaintracks.ts +52 -14
  24. package/core/headers/headerStore.ts +7 -10
  25. package/core/hooks/useConfirmationSound.ts +14 -8
  26. package/core/i18n/translations.tsx +4562 -986
  27. package/core/identity/contactLink.ts +36 -0
  28. package/core/identity/handleRegistry/client.ts +285 -0
  29. package/core/identity/handleRegistry/profileCert.ts +254 -0
  30. package/core/identity/handleRegistry/registration.ts +559 -0
  31. package/core/identity/handleRegistry/resolver.ts +247 -0
  32. package/core/identity/handleRegistry/rules.ts +104 -0
  33. package/core/index.ts +116 -15
  34. package/core/localpay/build.ts +674 -37
  35. package/core/localpay/codec.ts +68 -5
  36. package/core/localpay/pending.ts +240 -22
  37. package/core/localpay/pendingAborts.ts +5 -1
  38. package/core/localpay/settlementAck.ts +149 -0
  39. package/core/localpay/types.ts +14 -1
  40. package/core/localpay/verify.ts +118 -69
  41. package/core/mandala/abortGuard.ts +134 -0
  42. package/core/mandala/basketMigration.ts +166 -0
  43. package/core/mandala/bundle.ts +244 -0
  44. package/core/mandala/createRuntime.ts +2437 -0
  45. package/core/mandala/drain.ts +670 -0
  46. package/core/mandala/permissionModule.ts +642 -0
  47. package/core/mandala/resendTransfer.ts +175 -0
  48. package/core/mandala/runtime.ts +357 -0
  49. package/core/mandala/settlementStore.ts +412 -0
  50. package/core/mandala/types.ts +290 -0
  51. package/core/monitor/MonitorSupervisor.ts +121 -0
  52. package/core/monitor/TaskBackupPush.ts +1 -1
  53. package/core/monitor/TaskCreditInbox.ts +1 -1
  54. package/core/monitor/TaskDrainOutbox.ts +1 -1
  55. package/core/monitor/TaskSendOffline.ts +1 -1
  56. package/core/net/online.ts +49 -0
  57. package/core/numberFormat.ts +19 -0
  58. package/core/offline/cancelParked.ts +94 -1
  59. package/core/offline/payerHold.ts +152 -12
  60. package/core/offline/plan.ts +1 -1
  61. package/core/offline/tokenFrames.ts +197 -0
  62. package/core/parsePeerPayURI.ts +70 -17
  63. package/core/pay/rails/address.ts +51 -3
  64. package/core/pay/rails/handle.ts +88 -9
  65. package/core/pay/rails/index.ts +16 -6
  66. package/core/pay/rails/nearby.ts +114 -4
  67. package/core/pay/recordProof.ts +2 -6
  68. package/core/services/arcadeBroadcastProvider.ts +1 -4
  69. package/core/services/capWalletArgs.ts +8 -9
  70. package/core/services/exchangeRate.ts +1 -1
  71. package/core/services/externalOrigin.ts +42 -0
  72. package/core/services/vault/VaultKeyService.ts +912 -251
  73. package/core/services/vault/ceremony.ts +435 -367
  74. package/core/services/vault/ceremonyHost.ts +27 -21
  75. package/core/services/vault/devMock.ts +30 -7
  76. package/core/services/vault/driver.ts +95 -41
  77. package/core/services/vault/guard.ts +514 -56
  78. package/core/services/vault/hardwareLease.ts +22 -0
  79. package/core/services/vault/mockYubiKey.ts +258 -90
  80. package/core/services/vault/pivReset.ts +145 -0
  81. package/core/services/vault/r1comb.ts +976 -0
  82. package/core/services/vault/session.ts +93 -26
  83. package/core/services/vault/transfers.ts +2617 -747
  84. package/core/services/vault/types.ts +100 -43
  85. package/core/services/vault/vaultStore.ts +991 -74
  86. package/core/services/walletConnectionValidation.ts +293 -0
  87. package/core/services/walletServiceConfig.ts +31 -20
  88. package/core/storage/StorageExpoSQLite.ts +420 -87
  89. package/core/storage/dbImage.ts +48 -0
  90. package/core/storage/methods/findSql.ts +3 -54
  91. package/core/storage/methods/listActionsSql.ts +8 -5
  92. package/core/storage/methods/listOutputsSql.ts +9 -5
  93. package/core/storage/methods/offlineActions.ts +15 -0
  94. package/core/storage/methods/processOfflineActions.ts +265 -9
  95. package/core/storage/methods/reviewStatusSql.ts +7 -2
  96. package/core/storage/methods/walletBalanceSql.ts +16 -4
  97. package/core/storage/schema/createTables.ts +152 -0
  98. package/core/storage/sqlUpdateValue.ts +24 -0
  99. package/core/toolboxConfig.ts +182 -1
  100. package/core/toolboxTypes.ts +40 -0
  101. package/core/userAvatar.ts +79 -0
  102. package/core/walletMonitor.ts +8 -3
  103. package/core/walletRepair/runWalletCheck.ts +19 -2
  104. package/package.json +31 -30
  105. package/ui/activityFilter.ts +115 -0
  106. package/ui/components/QRScanner.tsx +1 -1
  107. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  108. package/ui/components/pay/AssetPicker.tsx +184 -0
  109. package/ui/components/pay/AvailableBalance.tsx +33 -2
  110. package/ui/components/pay/HandleReceive.tsx +213 -50
  111. package/ui/components/pay/NearbyFlow.tsx +616 -69
  112. package/ui/components/pay/PayForm.tsx +73 -8
  113. package/ui/components/pay/PaymentSuccessOverlay.tsx +89 -8
  114. package/ui/components/pay/RecipientField.tsx +132 -73
  115. package/ui/components/pay/RequestHub.tsx +68 -8
  116. package/ui/components/pay/ResultBanner.tsx +41 -4
  117. package/ui/components/pay/StepBar.tsx +32 -0
  118. package/ui/components/pay/UniversalSend.tsx +1118 -86
  119. package/ui/components/pay/tokenSendCopy.ts +116 -0
  120. package/ui/components/pay/useRecipientInput.ts +36 -7
  121. package/ui/components/ui/PencilEditField.tsx +109 -0
  122. package/ui/components/ui/PermissionSheet.tsx +65 -4
  123. package/ui/components/ui/Sheet.tsx +9 -2
  124. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  125. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  126. package/ui/components/vault/KeyChooser.tsx +96 -0
  127. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  128. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  129. package/ui/components/wallet/ActivityRow.tsx +283 -97
  130. package/ui/components/wallet/AmountInput.tsx +92 -28
  131. package/ui/components/wallet/AssetAmount.tsx +95 -0
  132. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  133. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  134. package/ui/components/wallet/ContactSigil.tsx +49 -0
  135. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  136. package/ui/components/wallet/FitAmount.tsx +148 -0
  137. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  138. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  139. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  140. package/ui/components/wallet/ProfileButton.tsx +62 -0
  141. package/ui/components/wallet/UserAvatar.tsx +85 -0
  142. package/ui/components/wallet/avatarIcons.ts +122 -0
  143. package/ui/components/wallet/tokenEviction.ts +65 -0
  144. package/ui/hooks/useContactsStore.ts +10 -0
  145. package/ui/hooks/useExportWalletData.ts +39 -0
  146. package/ui/hooks/useMandala.ts +320 -0
  147. package/ui/hooks/useOnline.ts +65 -20
  148. package/ui/hooks/useVaultBalance.ts +105 -7
  149. package/ui/hooks/useVaultCoverage.ts +52 -0
  150. package/ui/importDatabases.ts +7 -3
  151. package/ui/index.ts +75 -7
  152. package/ui/screens/ConnectionsScreen.tsx +46 -29
  153. package/ui/screens/ContactScreen.tsx +289 -0
  154. package/ui/screens/ContactsScreen.tsx +373 -0
  155. package/ui/screens/IdentifierScreen.tsx +234 -0
  156. package/ui/screens/NewContactScreen.tsx +362 -0
  157. package/ui/screens/PairScreen.tsx +12 -12
  158. package/ui/screens/PayScreen.tsx +145 -12
  159. package/ui/screens/ProfileScreen.tsx +783 -0
  160. package/ui/screens/SettingsScreen.tsx +18 -9
  161. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  162. package/ui/screens/TrustScreen.tsx +1 -1
  163. package/ui/screens/VaultScreen.tsx +925 -171
  164. package/ui/screens/VaultTransferScreen.tsx +376 -123
  165. package/ui/screens/WalletCheckScreen.tsx +10 -1
  166. package/ui/screens/WalletConfigScreen.tsx +80 -16
  167. package/ui/screens/WalletHomeScreen.tsx +915 -139
  168. package/ui/screens/homeBadges.ts +9 -1
  169. package/ui/screens/tokenRowTitle.ts +68 -0
  170. package/ui/tokenFormat.ts +108 -0
  171. package/ui/tokenSeen.ts +75 -0
  172. package/ui/tokenStatus.ts +100 -0
  173. package/ui/txStatus.ts +43 -5
  174. package/assets/sounds/vault-close.wav +0 -0
  175. package/assets/sounds/vault-open.wav +0 -0
  176. package/core/services/vault/k1.ts +0 -75
  177. package/core/services/vault/sealing.ts +0 -84
  178. package/core/services/vault/vaultDerivation.ts +0 -152
  179. package/core/services/vault/vaultPassphrase.ts +0 -287
  180. package/ui/components/vault/PassphraseField.tsx +0 -306
  181. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  182. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -0,0 +1,412 @@
1
+ /**
2
+ * `SettlementStore` over the toolbox's own SQLite connection.
3
+ *
4
+ * Deliberately logic-free, in the same spirit as `storage/methods/offlineActions.ts`:
5
+ * every decision about WHEN a row may move lives in `mandala/drain.ts`, which is
6
+ * unit-tested against a real in-memory SQLite. What is here is statements.
7
+ *
8
+ * Two rules the SQL itself enforces, because a convention would not survive a
9
+ * crash or a second drain tick:
10
+ *
11
+ * 1. **`state` belongs to `advanceSettlement` alone.** `upsertSettlement` is
12
+ * the re-derivation path (FIX G — the drain re-runs it on every pass from
13
+ * the durable frame bytes), so if it wrote `state` it would drag an
14
+ * `admitted` row back to `held` every tick and re-submit forever. It
15
+ * therefore sets `state` only on the INSERT, and on conflict updates the
16
+ * descriptive columns alone.
17
+ * 2. **`advanceSettlement` is one guarded UPDATE.** `... WHERE txid = ? AND
18
+ * state IN (...)` plus a changes-count check is a compare-and-swap: two
19
+ * interleaved drains cannot both believe they claimed the same row, and a
20
+ * row someone else already moved to a terminal state is never resurrected.
21
+ * There is no read-then-write anywhere in this file for that reason.
22
+ *
23
+ * Access pattern matches `StorageExpoSQLite`'s own use of `offline_actions`:
24
+ * the caller hands in `storage.sqliteDb` and this module only ever issues
25
+ * parameterised statements against it.
26
+ */
27
+ import type {
28
+ SettlementStore,
29
+ TokenAdmissionEdge,
30
+ TokenAdmissionRow,
31
+ TokenLinkageRow,
32
+ TokenSettlementRole,
33
+ TokenSettlementRow,
34
+ TokenSettlementState
35
+ } from './types'
36
+
37
+ /** Everything these statements bind. BLOB columns are why `Uint8Array` is here. */
38
+ export type SettlementBindValue = string | number | null | Uint8Array
39
+
40
+ /**
41
+ * Structurally satisfied by expo-sqlite's `SQLiteDatabase` and by the
42
+ * `node:sqlite` adapter the tests use. `runAsync` is narrowed to its result's
43
+ * `changes` because `advanceSettlement`'s whole contract depends on it.
44
+ */
45
+ export interface SettlementDb {
46
+ runAsync(sql: string, params: SettlementBindValue[]): Promise<{ changes: number }>
47
+ getAllAsync(sql: string, params: SettlementBindValue[]): Promise<unknown[]>
48
+ getFirstAsync(sql: string, params: SettlementBindValue[]): Promise<unknown>
49
+ }
50
+
51
+ /** The store, plus the one batch question the storage guard needs to ask. */
52
+ export interface SqlSettlementStore extends SettlementStore {
53
+ /**
54
+ * Which of `txids` have a `token_settlements` row. One statement, because the
55
+ * caller (`attemptToPostReqsToNetwork`'s token guard) asks this on the hot
56
+ * path of every broadcast.
57
+ */
58
+ settlementTxidsIn(txids: string[]): Promise<Set<string>>
59
+ }
60
+
61
+ interface SettlementDbRow {
62
+ txid: string
63
+ role: string
64
+ assetId: string
65
+ state: string
66
+ counterpartyKey: string | null
67
+ amountBaseUnits: number | null
68
+ overlayUrl: string
69
+ overlayIdentityKey: string
70
+ admissionOutputsJson: string | null
71
+ admissionSignatureHex: string | null
72
+ refusedCode: string | null
73
+ refusedPayloadHash: string | null
74
+ poisonedByTxid: string | null
75
+ reference: string | null
76
+ createdAt: string
77
+ updatedAt: string
78
+ }
79
+
80
+ /** A JSON array column that will not throw the caller's drain pass for one bad row. */
81
+ function readNumberArray(json: string | null): number[] | undefined {
82
+ if (!json) return undefined
83
+ try {
84
+ const parsed = JSON.parse(json) as unknown
85
+ if (!Array.isArray(parsed)) return undefined
86
+ return parsed.filter((n): n is number => typeof n === 'number')
87
+ } catch {
88
+ return undefined
89
+ }
90
+ }
91
+
92
+ function toSettlement(row: SettlementDbRow): TokenSettlementRow {
93
+ return {
94
+ txid: row.txid,
95
+ role: row.role as TokenSettlementRole,
96
+ assetId: row.assetId,
97
+ state: row.state as TokenSettlementState,
98
+ counterpartyKey: row.counterpartyKey ?? undefined,
99
+ amountBaseUnits: row.amountBaseUnits ?? undefined,
100
+ overlayUrl: row.overlayUrl,
101
+ overlayIdentityKey: row.overlayIdentityKey,
102
+ admissionOutputs: readNumberArray(row.admissionOutputsJson),
103
+ admissionSignatureHex: row.admissionSignatureHex ?? undefined,
104
+ refusedCode: row.refusedCode ?? undefined,
105
+ refusedPayloadHash: row.refusedPayloadHash ?? undefined,
106
+ poisonedByTxid: row.poisonedByTxid ?? undefined,
107
+ reference: row.reference ?? undefined,
108
+ createdAt: row.createdAt,
109
+ updatedAt: row.updatedAt
110
+ }
111
+ }
112
+
113
+ /**
114
+ * `payloadBytes` comes back from expo-sqlite as a `Uint8Array` and from
115
+ * `node:sqlite` the same way, but a driver that hands back an ArrayBuffer or a
116
+ * number[] must not silently become an empty payload — these bytes are the only
117
+ * thing that lets a downstream device submit this txid at all.
118
+ *
119
+ * A TEXT value is the 2026-09-16 incident's residue: `putLinkage` was handed a
120
+ * JSON-rehydrated payload (an index-keyed object, not a `Uint8Array`), and
121
+ * expo-sqlite's Android binding stringified it as a java `Map` — `{0=1.0,
122
+ * 2=250.0, 1=2.0}`, hash-ordered, Double-valued. Rows like that are on devices
123
+ * and `INSERT OR IGNORE` would have kept them forever, so they are read back
124
+ * into the bytes they always meant. Anything else that is not bytes still
125
+ * throws, never becomes an empty payload.
126
+ */
127
+ function toBytes(value: unknown): Uint8Array {
128
+ if (value instanceof Uint8Array) return value
129
+ if (value instanceof ArrayBuffer) return new Uint8Array(value)
130
+ if (Array.isArray(value)) return new Uint8Array(value as number[])
131
+ if (typeof value === 'string') {
132
+ const recovered = bytesFromJavaMapString(value)
133
+ if (recovered) return recovered
134
+ }
135
+ throw new Error('token_linkage_payloads.payloadBytes is not readable as bytes')
136
+ }
137
+
138
+ function bytesFromJavaMapString(text: string): Uint8Array | undefined {
139
+ const braced = /^\{(.*)\}$/s.exec(text.trim())
140
+ if (!braced) return undefined
141
+ const body = braced[1].trim()
142
+ if (body === '') return new Uint8Array(0)
143
+ const pairs = body.split(',')
144
+ const out = new Uint8Array(pairs.length)
145
+ const seen = new Set<number>()
146
+ for (const pair of pairs) {
147
+ const kv = /^\s*(\d+)=(\d+)(?:\.0+)?\s*$/.exec(pair)
148
+ if (!kv) return undefined
149
+ const index = Number(kv[1])
150
+ const byte = Number(kv[2])
151
+ if (index >= out.length || seen.has(index) || byte > 255) return undefined
152
+ seen.add(index)
153
+ out[index] = byte
154
+ }
155
+ return out
156
+ }
157
+
158
+ /** Columns `advanceSettlement` and `upsertSettlement` may write, and their SQL names. */
159
+ const PATCHABLE: { key: keyof TokenSettlementRow; column: string }[] = [
160
+ { key: 'counterpartyKey', column: 'counterpartyKey' },
161
+ { key: 'amountBaseUnits', column: 'amountBaseUnits' },
162
+ { key: 'admissionOutputs', column: 'admissionOutputsJson' },
163
+ { key: 'admissionSignatureHex', column: 'admissionSignatureHex' },
164
+ { key: 'refusedCode', column: 'refusedCode' },
165
+ { key: 'refusedPayloadHash', column: 'refusedPayloadHash' },
166
+ { key: 'poisonedByTxid', column: 'poisonedByTxid' },
167
+ { key: 'reference', column: 'reference' }
168
+ ]
169
+
170
+ function patchValue(key: keyof TokenSettlementRow, value: unknown): SettlementBindValue {
171
+ if (value === undefined || value === null) return null
172
+ if (key === 'admissionOutputs') return JSON.stringify(value)
173
+ return value as SettlementBindValue
174
+ }
175
+
176
+ export function createSettlementStore(db: SettlementDb): SqlSettlementStore {
177
+ return {
178
+ async getSettlement(txid: string): Promise<TokenSettlementRow | undefined> {
179
+ const row = (await db.getFirstAsync('SELECT * FROM token_settlements WHERE txid = ?', [
180
+ txid
181
+ ])) as SettlementDbRow | null
182
+ return row ? toSettlement(row) : undefined
183
+ },
184
+
185
+ /**
186
+ * One indexed lookup (`idx_token_settlements_reference`), because this is
187
+ * asked before EVERY `abortAction` the wallet makes — the overwhelming
188
+ * majority of which are plain BSV actions with no row here at all. An empty
189
+ * or absent reference can never match a row and is refused a query.
190
+ */
191
+ async getSettlementByReference(reference: string): Promise<TokenSettlementRow | undefined> {
192
+ if (!reference) return undefined
193
+ const row = (await db.getFirstAsync('SELECT * FROM token_settlements WHERE reference = ?', [
194
+ reference
195
+ ])) as SettlementDbRow | null
196
+ return row ? toSettlement(row) : undefined
197
+ },
198
+
199
+ async listSettlements(filter = {}): Promise<TokenSettlementRow[]> {
200
+ const where: string[] = []
201
+ const params: SettlementBindValue[] = []
202
+ if (filter.state && filter.state.length > 0) {
203
+ where.push(`state IN (${filter.state.map(() => '?').join(',')})`)
204
+ params.push(...filter.state)
205
+ }
206
+ if (filter.role !== undefined) {
207
+ where.push('role = ?')
208
+ params.push(filter.role)
209
+ }
210
+ const sql =
211
+ 'SELECT * FROM token_settlements' +
212
+ (where.length ? ` WHERE ${where.join(' AND ')}` : '') +
213
+ ' ORDER BY createdAt ASC, txid ASC'
214
+ return ((await db.getAllAsync(sql, params)) as SettlementDbRow[]).map(toSettlement)
215
+ },
216
+
217
+ /**
218
+ * Insert the row, or refresh only what a re-derivation can legitimately
219
+ * know. `state`, `role` and the two terminal-verdict columns are never
220
+ * touched on conflict — see rule 1 at the top of this file.
221
+ */
222
+ async upsertSettlement(row): Promise<void> {
223
+ const now = new Date().toISOString()
224
+ const createdAt = row.createdAt ?? now
225
+ await db.runAsync(
226
+ `INSERT INTO token_settlements
227
+ (txid, role, assetId, state, counterpartyKey, amountBaseUnits, overlayUrl, overlayIdentityKey,
228
+ admissionOutputsJson, admissionSignatureHex, refusedCode, refusedPayloadHash, poisonedByTxid,
229
+ reference, createdAt, updatedAt)
230
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
231
+ ON CONFLICT(txid) DO UPDATE SET
232
+ assetId = excluded.assetId,
233
+ counterpartyKey = COALESCE(excluded.counterpartyKey, token_settlements.counterpartyKey),
234
+ amountBaseUnits = COALESCE(excluded.amountBaseUnits, token_settlements.amountBaseUnits),
235
+ overlayUrl = excluded.overlayUrl,
236
+ overlayIdentityKey = excluded.overlayIdentityKey,
237
+ admissionOutputsJson = COALESCE(excluded.admissionOutputsJson, token_settlements.admissionOutputsJson),
238
+ admissionSignatureHex = COALESCE(excluded.admissionSignatureHex, token_settlements.admissionSignatureHex),
239
+ reference = COALESCE(excluded.reference, token_settlements.reference),
240
+ updatedAt = excluded.updatedAt`,
241
+ [
242
+ row.txid,
243
+ row.role,
244
+ row.assetId,
245
+ row.state,
246
+ row.counterpartyKey ?? null,
247
+ row.amountBaseUnits ?? null,
248
+ row.overlayUrl,
249
+ row.overlayIdentityKey,
250
+ row.admissionOutputs ? JSON.stringify(row.admissionOutputs) : null,
251
+ row.admissionSignatureHex ?? null,
252
+ row.refusedCode ?? null,
253
+ row.refusedPayloadHash ?? null,
254
+ row.poisonedByTxid ?? null,
255
+ row.reference ?? null,
256
+ createdAt,
257
+ now
258
+ ]
259
+ )
260
+ },
261
+
262
+ /**
263
+ * One statement, compare-and-swap on `state`. False means the row was not
264
+ * in one of `from` — either someone else moved it, or it does not exist —
265
+ * and NOTHING was written, so a caller may treat false as "not mine to
266
+ * advance" without a compensating read.
267
+ */
268
+ async advanceSettlement(
269
+ txid: string,
270
+ from: TokenSettlementState[],
271
+ to: TokenSettlementState,
272
+ patch: Partial<TokenSettlementRow> = {}
273
+ ): Promise<boolean> {
274
+ const sets = ['state = ?', 'updatedAt = ?']
275
+ const params: SettlementBindValue[] = [to, new Date().toISOString()]
276
+ for (const { key, column } of PATCHABLE) {
277
+ if (patch[key] === undefined) continue
278
+ sets.push(`${column} = ?`)
279
+ params.push(patchValue(key, patch[key]))
280
+ }
281
+ params.push(txid, ...from)
282
+ const placeholders = from.length > 0 ? from.map(() => '?').join(',') : `''`
283
+ const result = await db.runAsync(
284
+ `UPDATE token_settlements SET ${sets.join(', ')} WHERE txid = ? AND state IN (${placeholders})`,
285
+ params
286
+ )
287
+ return (result?.changes ?? 0) > 0
288
+ },
289
+
290
+ async settlementTxidsIn(txids: string[]): Promise<Set<string>> {
291
+ if (txids.length === 0) return new Set()
292
+ const rows = (await db.getAllAsync(
293
+ `SELECT txid FROM token_settlements WHERE txid IN (${txids.map(() => '?').join(',')})`,
294
+ txids
295
+ )) as { txid: string }[]
296
+ return new Set(rows.map(r => r.txid))
297
+ },
298
+
299
+ async getAdmission(txid: string): Promise<TokenAdmissionRow | undefined> {
300
+ const row = (await db.getFirstAsync('SELECT * FROM token_admissions WHERE txid = ?', [txid])) as {
301
+ txid: string
302
+ outputsToAdmitJson: string
303
+ signatureHex: string
304
+ signerKey: string
305
+ source: TokenAdmissionRow['source']
306
+ obtainedAt: string
307
+ } | null
308
+ if (!row) return undefined
309
+ return {
310
+ txid: row.txid,
311
+ outputsToAdmit: readNumberArray(row.outputsToAdmitJson) ?? [],
312
+ signatureHex: row.signatureHex,
313
+ signerKey: row.signerKey,
314
+ source: row.source,
315
+ obtainedAt: row.obtainedAt
316
+ }
317
+ },
318
+
319
+ /**
320
+ * Idempotent, and asymmetric on purpose: first-hand evidence (this device
321
+ * submitted, or fetched `GET /admin/admission/:txid` itself) replaces a
322
+ * cached bundle entry, but a counterparty-supplied bundle NEVER overwrites
323
+ * anything already on record. For a `bundle`/`minted` source against an
324
+ * existing row the `WHERE` makes this exactly an `INSERT OR IGNORE`, which
325
+ * is what the FIX G re-derivation pass needs.
326
+ */
327
+ async putAdmission(row: TokenAdmissionRow): Promise<void> {
328
+ await db.runAsync(
329
+ `INSERT INTO token_admissions (txid, outputsToAdmitJson, signatureHex, signerKey, source, obtainedAt)
330
+ VALUES (?,?,?,?,?,?)
331
+ ON CONFLICT(txid) DO UPDATE SET
332
+ outputsToAdmitJson = excluded.outputsToAdmitJson,
333
+ signatureHex = excluded.signatureHex,
334
+ signerKey = excluded.signerKey,
335
+ source = excluded.source,
336
+ obtainedAt = excluded.obtainedAt
337
+ WHERE excluded.source IN ('submitted','fetched')`,
338
+ [row.txid, JSON.stringify(row.outputsToAdmit), row.signatureHex, row.signerKey, row.source, row.obtainedAt]
339
+ )
340
+ },
341
+
342
+ async putEdges(edges: TokenAdmissionEdge[]): Promise<void> {
343
+ for (const e of edges) {
344
+ await db.runAsync(
345
+ 'INSERT OR IGNORE INTO token_admission_edges (childTxid, parentTxid, parentVout) VALUES (?,?,?)',
346
+ [e.childTxid, e.parentTxid, e.parentVout]
347
+ )
348
+ }
349
+ },
350
+
351
+ async parentsOf(childTxid: string): Promise<TokenAdmissionEdge[]> {
352
+ const rows = (await db.getAllAsync(
353
+ `SELECT childTxid, parentTxid, parentVout FROM token_admission_edges
354
+ WHERE childTxid = ? ORDER BY parentTxid ASC, parentVout ASC`,
355
+ [childTxid]
356
+ )) as TokenAdmissionEdge[]
357
+ return rows.map(r => ({ childTxid: r.childTxid, parentTxid: r.parentTxid, parentVout: r.parentVout }))
358
+ },
359
+
360
+ async getLinkage(txid: string): Promise<TokenLinkageRow | undefined> {
361
+ const row = (await db.getFirstAsync('SELECT * FROM token_linkage_payloads WHERE txid = ?', [txid])) as {
362
+ txid: string
363
+ payloadBytes: unknown
364
+ overlayUrl: string
365
+ overlayIdentityKey: string
366
+ source: TokenLinkageRow['source']
367
+ createdAt: string
368
+ } | null
369
+ if (!row) return undefined
370
+ return {
371
+ txid: row.txid,
372
+ payloadBytes: toBytes(row.payloadBytes),
373
+ overlayUrl: row.overlayUrl,
374
+ overlayIdentityKey: row.overlayIdentityKey,
375
+ source: row.source,
376
+ createdAt: row.createdAt
377
+ }
378
+ },
379
+
380
+ /**
381
+ * Insert-or-ignore in effect: the payload for a txid is whatever its issuer
382
+ * minted, forwarded verbatim. A second copy arriving on a later hop is by
383
+ * construction the same bytes, and a *different* copy is a counterparty
384
+ * trying to rewrite evidence this device already holds — so an existing
385
+ * BLOB is never touched. The one row a new copy may replace is one that
386
+ * holds no evidence at all — not a blob (see `toBytes`), or an empty one:
387
+ * a driver stringifying a value this store should have refused, which it
388
+ * now does, and an empty payload is likewise refused here because an
389
+ * overlay cannot verify nothing and every reader already treats it as
390
+ * "nothing held".
391
+ */
392
+ async putLinkage(row: TokenLinkageRow): Promise<void> {
393
+ if (!(row.payloadBytes instanceof Uint8Array) || row.payloadBytes.length === 0) {
394
+ throw new Error('token_linkage_payloads.payloadBytes must be a non-empty Uint8Array')
395
+ }
396
+ await db.runAsync(
397
+ `INSERT INTO token_linkage_payloads
398
+ (txid, payloadBytes, overlayUrl, overlayIdentityKey, source, createdAt)
399
+ VALUES (?,?,?,?,?,?)
400
+ ON CONFLICT(txid) DO UPDATE SET
401
+ payloadBytes = excluded.payloadBytes,
402
+ overlayUrl = excluded.overlayUrl,
403
+ overlayIdentityKey = excluded.overlayIdentityKey,
404
+ source = excluded.source,
405
+ createdAt = excluded.createdAt
406
+ WHERE typeof(token_linkage_payloads.payloadBytes) <> 'blob'
407
+ OR length(token_linkage_payloads.payloadBytes) = 0`,
408
+ [row.txid, row.payloadBytes, row.overlayUrl, row.overlayIdentityKey, row.source, row.createdAt]
409
+ )
410
+ }
411
+ }
412
+ }