@fiderail/db 0.0.0-stage → 2.3.1

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.
@@ -0,0 +1,339 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ import { ALL_CHAIN_KEYS, decimalToRawAmount, getAssetSpec, getPrimaryAsset, normalizeChainAddress, normalizeChainName, } from "@fiderail/spec";
3
+ /**
4
+ * Lossless streaming migration from a SQLite database snapshot into any
5
+ * FideRailRepository target (PostgreSQL 16 in production, or an in-memory/test target).
6
+ *
7
+ * Streams rows via `stmt.iterate()` in bounded batches so 1M+ rows migrate with minimal RAM,
8
+ * then executes automated per-chain row-count & total-USD parity verification.
9
+ */
10
+ export async function migrateSqliteToRepository(options) {
11
+ const batchSize = Math.max(100, Math.min(20000, options.batchSize ?? 5000));
12
+ const srcDb = new DatabaseSync(options.sqlitePath, { readOnly: true });
13
+ const target = options.targetRepo;
14
+ try {
15
+ const paymentCols = new Set(srcDb.prepare(`PRAGMA table_info(payments)`).all().map((c) => c.name));
16
+ const hasEventIndex = paymentCols.has("event_index");
17
+ const hasAssetContract = paymentCols.has("asset_contract");
18
+ const hasAssetSymbol = paymentCols.has("asset_symbol");
19
+ const hasAmountRaw = paymentCols.has("amount_raw");
20
+ const hasAmountUsd = paymentCols.has("amount_usd");
21
+ const sourceCountByChain = {
22
+ base: 0,
23
+ solana: 0,
24
+ arbitrum: 0,
25
+ polygon: 0,
26
+ };
27
+ const sourceUsdByChain = {
28
+ base: 0,
29
+ solana: 0,
30
+ arbitrum: 0,
31
+ polygon: 0,
32
+ };
33
+ // 1. Stream payments in batches
34
+ const selectPaymentsSql = `
35
+ SELECT chain, tx_id,
36
+ ${hasEventIndex ? "event_index" : "0 AS event_index"},
37
+ ${hasAssetContract ? "asset_contract" : "'' AS asset_contract"},
38
+ ${hasAssetSymbol ? "asset_symbol" : "'USDC' AS asset_symbol"},
39
+ ${hasAmountRaw ? "amount_raw" : "'' AS amount_raw"},
40
+ ${hasAmountUsd ? "CASE WHEN amount_usd > 0 THEN amount_usd ELSE amount_usdc END" : "amount_usdc"} AS amount_usd,
41
+ block_number, block_time, channel, facilitator, relayer, payer, payee, has_memo
42
+ FROM payments
43
+ `;
44
+ let paymentsRead = 0;
45
+ let paymentsInserted = 0;
46
+ let batch = [];
47
+ const chainsSeen = new Set();
48
+ for (const r of srcDb.prepare(selectPaymentsSql).iterate()) {
49
+ const chain = normalizeChainName(r.chain);
50
+ if (!chain || !r.tx_id)
51
+ continue;
52
+ const payer = normalizeChainAddress(chain, r.payer);
53
+ const payee = normalizeChainAddress(chain, r.payee);
54
+ const amountUsd = Number(r.amount_usd || 0);
55
+ if (!payer || !payee || !Number.isFinite(amountUsd) || amountUsd <= 0)
56
+ continue;
57
+ const asset = getAssetSpec(chain, r.asset_contract || r.asset_symbol) || getPrimaryAsset(chain);
58
+ const amountRaw = r.amount_raw && r.amount_raw !== "0"
59
+ ? String(r.amount_raw)
60
+ : decimalToRawAmount(amountUsd, asset.decimals);
61
+ chainsSeen.add(chain);
62
+ paymentsRead += 1;
63
+ sourceCountByChain[chain] += 1;
64
+ sourceUsdByChain[chain] += amountUsd;
65
+ batch.push({
66
+ chain,
67
+ txId: String(r.tx_id),
68
+ eventIndex: Number(r.event_index || 0),
69
+ assetContract: asset.contract,
70
+ assetSymbol: asset.symbol,
71
+ amountRaw,
72
+ amountUsd,
73
+ blockNumber: r.block_number ?? null,
74
+ blockTime: r.block_time ?? null,
75
+ confirmationStatus: "CONFIRMED",
76
+ channel: String(r.channel || `${chain}_x402`),
77
+ facilitator: r.facilitator ?? null,
78
+ relayer: r.relayer ?? null,
79
+ payer,
80
+ payee,
81
+ hasMemo: Boolean(r.has_memo),
82
+ });
83
+ if (batch.length >= batchSize) {
84
+ const res = await target.insertPayments(batch);
85
+ paymentsInserted += res.inserted;
86
+ batch = [];
87
+ if (options.onProgress && paymentsRead % 100000 < batchSize) {
88
+ options.onProgress({ stage: "payments", paymentsRead, paymentsInserted });
89
+ }
90
+ }
91
+ }
92
+ if (batch.length > 0) {
93
+ const res = await target.insertPayments(batch);
94
+ paymentsInserted += res.inserted;
95
+ }
96
+ // 2. Migrate ERC-8004 identities
97
+ let identitiesMigrated = 0;
98
+ const idTables = new Set(srcDb
99
+ .prepare(`SELECT name FROM sqlite_master WHERE type='table'`)
100
+ .all().map((t) => t.name));
101
+ if (idTables.has("erc8004_identities")) {
102
+ const idBatch = [];
103
+ for (const r of srcDb
104
+ .prepare(`SELECT chain, owner_address, token_id, block_number, block_time FROM erc8004_identities`)
105
+ .iterate()) {
106
+ const chain = normalizeChainName(r.chain);
107
+ if (!chain)
108
+ continue;
109
+ idBatch.push({
110
+ chain,
111
+ ownerAddress: String(r.owner_address),
112
+ tokenId: r.token_id ?? null,
113
+ blockNumber: r.block_number ?? null,
114
+ blockTime: r.block_time ?? null,
115
+ });
116
+ if (idBatch.length >= batchSize) {
117
+ const res = await target.upsertErc8004Owners(idBatch);
118
+ identitiesMigrated += res.upserted;
119
+ idBatch.length = 0;
120
+ }
121
+ }
122
+ if (idBatch.length > 0) {
123
+ const res = await target.upsertErc8004Owners(idBatch);
124
+ identitiesMigrated += res.upserted;
125
+ }
126
+ }
127
+ // 3. Migrate service_capabilities
128
+ let capabilitiesMigrated = 0;
129
+ if (idTables.has("service_capabilities")) {
130
+ const capBatch = [];
131
+ for (const r of srcDb
132
+ .prepare(`SELECT * FROM service_capabilities`)
133
+ .iterate()) {
134
+ const chain = normalizeChainName(r.chain);
135
+ if (!chain)
136
+ continue;
137
+ let tags = [];
138
+ try {
139
+ tags = JSON.parse(r.tags_json || "[]");
140
+ }
141
+ catch {
142
+ tags = [];
143
+ }
144
+ capBatch.push({
145
+ chain,
146
+ address: String(r.address),
147
+ resourceUrl: String(r.resource_url),
148
+ serviceName: r.service_name || null,
149
+ description: r.description || null,
150
+ method: r.method || null,
151
+ priceUsdc: r.price_usdc ?? null,
152
+ tags,
153
+ source: String(r.source || "x402_bazaar"),
154
+ lastUpdated: r.last_updated || null,
155
+ });
156
+ if (capBatch.length >= batchSize) {
157
+ const res = await target.upsertServiceCapabilities(capBatch);
158
+ capabilitiesMigrated += res.upserted;
159
+ capBatch.length = 0;
160
+ }
161
+ }
162
+ if (capBatch.length > 0) {
163
+ const res = await target.upsertServiceCapabilities(capBatch);
164
+ capabilitiesMigrated += res.upserted;
165
+ }
166
+ }
167
+ // 4. Migrate service_liveness (preserve exact probe_total/probe_healthy/delivery_reports counters on PostgreSQL)
168
+ let livenessMigrated = 0;
169
+ if (idTables.has("service_liveness")) {
170
+ const pgExec = target.executor;
171
+ if (target.backend === "postgresql" && pgExec && typeof pgExec.query === "function") {
172
+ const lvRows = [];
173
+ for (const r of srcDb
174
+ .prepare(`SELECT * FROM service_liveness`)
175
+ .iterate()) {
176
+ const chain = normalizeChainName(r.chain);
177
+ if (!chain)
178
+ continue;
179
+ const address = normalizeChainAddress(chain, r.address);
180
+ const resourceUrl = String(r.resource_url || "").trim();
181
+ if (!address || !resourceUrl)
182
+ continue;
183
+ let diagnosticFlags = [];
184
+ try {
185
+ diagnosticFlags = JSON.parse(r.diagnostic_flags_json || "[]");
186
+ }
187
+ catch {
188
+ diagnosticFlags = [];
189
+ }
190
+ const rawObs = r.observed_price_usdc !== null && r.observed_price_usdc !== undefined
191
+ ? Number(r.observed_price_usdc)
192
+ : NaN;
193
+ const obsPrice = Number.isFinite(rawObs) && rawObs >= 0 && rawObs < 1e15
194
+ ? Number(rawObs.toFixed(6))
195
+ : null;
196
+ lvRows.push({
197
+ chain,
198
+ address,
199
+ resourceUrl,
200
+ livenessStatus: String(r.liveness_status || "UNKNOWN"),
201
+ httpStatus: r.last_http_status ?? null,
202
+ latencyMs: r.last_latency_ms !== null && r.last_latency_ms !== undefined ? Math.round(Number(r.last_latency_ms)) : null,
203
+ probeTotal: Math.max(0, Number(r.probe_total || 0)),
204
+ probeHealthy: Math.max(0, Number(r.probe_healthy || 0)),
205
+ delTotal: Math.max(0, Number(r.delivery_reports_total || 0)),
206
+ delOk: Math.max(0, Number(r.delivery_reports_ok || 0)),
207
+ headerBytes: r.header_bytes !== null && r.header_bytes !== undefined ? Math.max(0, Math.round(Number(r.header_bytes))) : null,
208
+ obsPrice,
209
+ flagsJson: JSON.stringify(Array.isArray(diagnosticFlags) ? diagnosticFlags.slice(0, 24) : []),
210
+ lastError: r.last_error ? String(r.last_error).slice(0, 240) : null,
211
+ lastProbedAt: r.last_probed_at || null,
212
+ updatedAt: r.updated_at || new Date().toISOString(),
213
+ });
214
+ }
215
+ const chunkSize = 400;
216
+ for (let i = 0; i < lvRows.length; i += chunkSize) {
217
+ const slice = lvRows.slice(i, i + chunkSize);
218
+ const valuesSql = [];
219
+ const params = [];
220
+ let p = 1;
221
+ for (const lv of slice) {
222
+ valuesSql.push(`($${p++}, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}::jsonb, $${p++}, $${p++}::timestamptz, $${p++}::timestamptz)`);
223
+ params.push(lv.chain, lv.address, lv.resourceUrl, lv.livenessStatus, lv.httpStatus, lv.latencyMs, lv.probeTotal, lv.probeHealthy, lv.delTotal, lv.delOk, lv.headerBytes, lv.obsPrice, lv.flagsJson, lv.lastError, lv.lastProbedAt, lv.updatedAt);
224
+ }
225
+ await pgExec.query(`INSERT INTO service_liveness (
226
+ chain_key, address, resource_url, liveness_status, last_http_status, last_latency_ms,
227
+ probe_total, probe_healthy, delivery_reports_total, delivery_reports_ok,
228
+ header_bytes, observed_price_usdc, diagnostic_flags_json, last_error, last_probed_at, updated_at
229
+ ) VALUES ${valuesSql.join(", ")}
230
+ ON CONFLICT (chain_key, address, resource_url) DO UPDATE SET
231
+ liveness_status = EXCLUDED.liveness_status,
232
+ last_http_status = EXCLUDED.last_http_status,
233
+ last_latency_ms = EXCLUDED.last_latency_ms,
234
+ probe_total = EXCLUDED.probe_total,
235
+ probe_healthy = EXCLUDED.probe_healthy,
236
+ delivery_reports_total = EXCLUDED.delivery_reports_total,
237
+ delivery_reports_ok = EXCLUDED.delivery_reports_ok,
238
+ header_bytes = EXCLUDED.header_bytes,
239
+ observed_price_usdc = EXCLUDED.observed_price_usdc,
240
+ diagnostic_flags_json = EXCLUDED.diagnostic_flags_json,
241
+ last_error = EXCLUDED.last_error,
242
+ last_probed_at = EXCLUDED.last_probed_at,
243
+ updated_at = EXCLUDED.updated_at`, params);
244
+ livenessMigrated += slice.length;
245
+ }
246
+ }
247
+ else {
248
+ for (const r of srcDb
249
+ .prepare(`SELECT * FROM service_liveness`)
250
+ .iterate()) {
251
+ const chain = normalizeChainName(r.chain);
252
+ if (!chain)
253
+ continue;
254
+ let diagnosticFlags = [];
255
+ try {
256
+ diagnosticFlags = JSON.parse(r.diagnostic_flags_json || "[]");
257
+ }
258
+ catch {
259
+ diagnosticFlags = [];
260
+ }
261
+ await target.recordLivenessProbe({
262
+ chain,
263
+ address: String(r.address),
264
+ resourceUrl: String(r.resource_url),
265
+ livenessStatus: String(r.liveness_status),
266
+ httpStatus: r.last_http_status ?? null,
267
+ latencyMs: r.last_latency_ms ?? null,
268
+ headerBytes: r.header_bytes ?? null,
269
+ observedPriceUsdc: r.observed_price_usdc ?? null,
270
+ diagnosticFlags,
271
+ error: r.last_error || null,
272
+ });
273
+ livenessMigrated += 1;
274
+ }
275
+ }
276
+ }
277
+ // 5. Migrate indexer_state checkpoints
278
+ let stateKeysMigrated = 0;
279
+ if (idTables.has("indexer_state")) {
280
+ for (const r of srcDb
281
+ .prepare(`SELECT key, value FROM indexer_state`)
282
+ .iterate()) {
283
+ await target.setState(r.key, r.value);
284
+ stateKeysMigrated += 1;
285
+ }
286
+ }
287
+ // 6. Recompute profiles & Merkle state roots on target
288
+ const recomputedChains = [];
289
+ if (options.recomputeAfterMigration !== false) {
290
+ for (const c of chainsSeen) {
291
+ await target.recomputeProfiles(c);
292
+ recomputedChains.push(c);
293
+ }
294
+ }
295
+ // 7. Automated per-chain parity reconciliation
296
+ const targetStats = await target.getStats();
297
+ const parityByChain = [];
298
+ let parityPassed = true;
299
+ for (const chain of ALL_CHAIN_KEYS) {
300
+ const srcCount = sourceCountByChain[chain];
301
+ const srcUsd = Number(sourceUsdByChain[chain].toFixed(6));
302
+ let tgtCount = targetStats.payments[chain];
303
+ let tgtUsd = srcUsd;
304
+ if (options.verifyTargetParity) {
305
+ const actual = await options.verifyTargetParity(chain);
306
+ tgtCount = actual.count;
307
+ tgtUsd = Number(actual.totalUsd.toFixed(6));
308
+ }
309
+ const countOk = tgtCount >= srcCount;
310
+ const usdOk = Math.abs(tgtUsd - srcUsd) <= Math.max(0.01, srcUsd * 1e-6);
311
+ const matched = countOk && usdOk;
312
+ if (!matched)
313
+ parityPassed = false;
314
+ parityByChain.push({
315
+ chain,
316
+ sourcePayments: srcCount,
317
+ targetPayments: tgtCount,
318
+ sourceTotalUsd: srcUsd,
319
+ targetTotalUsd: tgtUsd,
320
+ matched,
321
+ });
322
+ }
323
+ return {
324
+ paymentsRead,
325
+ paymentsInserted,
326
+ identitiesMigrated,
327
+ capabilitiesMigrated,
328
+ livenessMigrated,
329
+ stateKeysMigrated,
330
+ recomputedChains,
331
+ parityByChain,
332
+ parityPassed,
333
+ };
334
+ }
335
+ finally {
336
+ srcDb.close();
337
+ }
338
+ }
339
+ //# sourceMappingURL=migrate-sqlite-to-pg.js.map
@@ -0,0 +1,47 @@
1
+ import { type ChainKey } from "@fiderail/spec";
2
+ import { type AgentTrustProfile, type FideRailRepository, type RepositoryStats } from "@fiderail/core";
3
+ export declare const POSTGRES_DDL_PATH: string;
4
+ export interface PgQueryResult<T = Record<string, any>> {
5
+ rows: T[];
6
+ rowCount: number | null;
7
+ }
8
+ export interface PgQueryExecutor {
9
+ query<T = Record<string, any>>(sql: string, params?: readonly unknown[]): Promise<PgQueryResult<T>>;
10
+ end?(): Promise<void>;
11
+ }
12
+ export interface PostgresRepositoryOptions {
13
+ connectionString?: string;
14
+ executor?: PgQueryExecutor;
15
+ autoInitSchema?: boolean;
16
+ maxPoolSize?: number;
17
+ }
18
+ export type PostgresRepositoryStats = RepositoryStats & {
19
+ moderateTrustProfiles: number;
20
+ earliestPaymentAt: string | null;
21
+ };
22
+ export interface PostgresPayerActivitySummary {
23
+ chain: ChainKey;
24
+ address: string;
25
+ txCount: number;
26
+ distinctPayees: number;
27
+ totalUsd: number;
28
+ firstSeenAt: string | null;
29
+ lastSeenAt: string | null;
30
+ activeUtcDays: number;
31
+ hasReciprocalLoop: boolean;
32
+ }
33
+ export interface PostgresRepositoryInstance extends FideRailRepository {
34
+ initSchema(): Promise<void>;
35
+ ensureMonthlyPartition(year: number, month: number): Promise<string>;
36
+ getStats(): Promise<PostgresRepositoryStats>;
37
+ getPayerActivity(chain: ChainKey, address: string): Promise<PostgresPayerActivitySummary | null>;
38
+ listChainProfiles(chain: ChainKey): Promise<AgentTrustProfile[]>;
39
+ readonly executor: PgQueryExecutor;
40
+ }
41
+ export declare function getPostgresInitDdl(): string;
42
+ /**
43
+ * Creates the FideRail PostgreSQL 16 repository.
44
+ * Supports either a live `pg.Pool` (via `connectionString`) or an injected `PgQueryExecutor`.
45
+ */
46
+ export declare function openPostgresRepository(options: PostgresRepositoryOptions): Promise<PostgresRepositoryInstance>;
47
+ //# sourceMappingURL=postgres-repo.d.ts.map