@fiderail/db 0.0.0-stage → 2.3.2

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,1138 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import pg from "pg";
5
+ import { decimalToRawAmount, getAssetSpec, getPrimaryAsset, isVerifiedX402Channels, normalizeChainAddress, normalizeChainName, } from "@fiderail/spec";
6
+ import { DEFAULT_TRUST_SCORER, buildTrustStateRootCommitment, computeCreditProfilesFromPayments, } from "@fiderail/core";
7
+ import { signStateRootEd25519 } from "./state-root-signer.js";
8
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
9
+ export const POSTGRES_DDL_PATH = path.resolve(__dirname, "..", "sql", "001_init_v2.sql");
10
+ const DANGEROUS_QUERY_CHARS_RE = /[\u0000-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g;
11
+ function buildSafeLikePattern(query, maxLength = 128) {
12
+ const cleaned = String(query || "")
13
+ .replace(DANGEROUS_QUERY_CHARS_RE, "")
14
+ .trim()
15
+ .toLowerCase()
16
+ .slice(0, maxLength);
17
+ if (!cleaned)
18
+ return null;
19
+ const escaped = cleaned.replace(/[\\%_]/g, (ch) => `\\${ch}`);
20
+ return `%${escaped}%`;
21
+ }
22
+ function isHealthyLivenessStatus(status) {
23
+ return status === "LIVE_402" || status === "LIVE_200" || status === "LIVE_REACHABLE";
24
+ }
25
+ function emptyChainCounts() {
26
+ return { base: 0, solana: 0, arbitrum: 0, polygon: 0, total: 0 };
27
+ }
28
+ function toIsoOrNull(raw) {
29
+ if (raw === null || raw === undefined)
30
+ return null;
31
+ const d = raw instanceof Date ? raw : new Date(String(raw));
32
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
33
+ }
34
+ function parseJsonField(raw, fallback) {
35
+ if (raw === null || raw === undefined)
36
+ return fallback;
37
+ if (typeof raw === "string") {
38
+ try {
39
+ return JSON.parse(raw);
40
+ }
41
+ catch {
42
+ return fallback;
43
+ }
44
+ }
45
+ return raw;
46
+ }
47
+ function rowToProfile(row) {
48
+ const channels = parseJsonField(row.channels_json, []);
49
+ const riskFlags = parseJsonField(row.risk_flags_json, []);
50
+ const extraMetrics = parseJsonField(row.metrics_json, {});
51
+ const dataCoverage = row.data_coverage_json
52
+ ? parseJsonField(row.data_coverage_json, undefined)
53
+ : undefined;
54
+ return {
55
+ chain: row.chain_key,
56
+ address: String(row.address),
57
+ creditScore: Number(row.credit_score),
58
+ confidence: row.confidence !== null && row.confidence !== undefined
59
+ ? Number(row.confidence)
60
+ : undefined,
61
+ confidenceLevel: row.confidence_level || undefined,
62
+ riskLevel: row.risk_level || undefined,
63
+ tier: row.tier,
64
+ channels,
65
+ metrics: {
66
+ ...extraMetrics,
67
+ txCount: Number(row.tx_count),
68
+ totalUsdc: Number(row.total_usdc),
69
+ totalUsd: Number(row.total_usdc),
70
+ uniquePayers: Number(row.unique_payers),
71
+ medianTicketUsdc: Number(row.median_ticket_usdc),
72
+ hhi: Number(row.hhi),
73
+ top1PayerShare: Number(row.top1_payer_share),
74
+ activeSpanHours: Number(row.active_span_hours || 0),
75
+ activeUtcDays: Number(row.active_utc_days || 1),
76
+ },
77
+ dataCoverage,
78
+ riskFlags,
79
+ erc8004Registered: Boolean(row.erc8004_registered),
80
+ firstSeenAt: row.first_seen_at ? new Date(row.first_seen_at).toISOString() : null,
81
+ lastSeenAt: row.last_seen_at ? new Date(row.last_seen_at).toISOString() : null,
82
+ sourceSnapshot: row.updated_at ? new Date(row.updated_at).toISOString() : null,
83
+ source: row.source || "postgres_live",
84
+ modelVersion: row.model_version || "trust-v2",
85
+ modelHash: row.model_hash || undefined,
86
+ };
87
+ }
88
+ function rowToHistoryEntry(row) {
89
+ return {
90
+ id: row.id !== undefined ? Number(row.id) : undefined,
91
+ chain: row.chain_key,
92
+ address: String(row.address),
93
+ modelVersion: String(row.model_version || "trust-v2"),
94
+ previousScore: row.previous_score !== null && row.previous_score !== undefined
95
+ ? Number(row.previous_score)
96
+ : null,
97
+ currentScore: Number(row.current_score),
98
+ reasonCodes: parseJsonField(row.reason_codes, []),
99
+ recordedAt: row.recorded_at ? new Date(row.recorded_at).toISOString() : new Date().toISOString(),
100
+ };
101
+ }
102
+ function rowToStateRoot(row) {
103
+ return {
104
+ epochId: String(row.epoch_id),
105
+ modelVersion: String(row.model_version),
106
+ modelHash: String(row.model_hash),
107
+ merkleRoot: String(row.merkle_root),
108
+ leafCount: Number(row.leaf_count),
109
+ createdAt: row.created_at ? new Date(row.created_at).toISOString() : new Date().toISOString(),
110
+ proofType: (row.proof_type || "ed25519"),
111
+ signature: row.signature ? String(row.signature) : null,
112
+ };
113
+ }
114
+ function rowToAssociatedCredit(row) {
115
+ return {
116
+ endorsementId: String(row.endorsement_id),
117
+ parentChain: row.parent_chain,
118
+ parentAddress: String(row.parent_address),
119
+ childChain: row.child_chain,
120
+ childAddress: String(row.child_address),
121
+ discountFactor: Number(row.discount_factor),
122
+ maxEndorsedScore: Number(row.max_endorsed_score),
123
+ maxEndorsedSingleTxUsd: Number(row.max_endorsed_single_tx_usd),
124
+ ruleVersion: String(row.rule_version),
125
+ status: row.status,
126
+ issuedAt: row.issued_at ? new Date(row.issued_at).toISOString() : new Date().toISOString(),
127
+ expiresAt: row.expires_at ? new Date(row.expires_at).toISOString() : new Date().toISOString(),
128
+ proofType: (row.proof_type || "ed25519"),
129
+ proofPayload: row.proof_payload
130
+ ? parseJsonField(row.proof_payload, null)
131
+ : null,
132
+ };
133
+ }
134
+ function rowToCapability(row) {
135
+ const tags = Array.isArray(row.tags_json)
136
+ ? row.tags_json
137
+ : typeof row.tags_json === "string"
138
+ ? JSON.parse(row.tags_json || "[]")
139
+ : [];
140
+ return {
141
+ chain: row.chain_key,
142
+ address: String(row.address),
143
+ resourceUrl: String(row.resource_url),
144
+ serviceName: row.service_name || null,
145
+ description: row.description || null,
146
+ method: row.method || null,
147
+ priceUsdc: row.price_usdc !== null && row.price_usdc !== undefined ? Number(row.price_usdc) : null,
148
+ tags,
149
+ source: String(row.source),
150
+ lastUpdated: row.last_updated || null,
151
+ syncedAt: row.synced_at ? new Date(row.synced_at).toISOString() : undefined,
152
+ };
153
+ }
154
+ function rowToLiveness(row) {
155
+ const probeTotal = Number(row.probe_total || 0);
156
+ const probeHealthy = Number(row.probe_healthy || 0);
157
+ const delTotal = Number(row.delivery_reports_total || 0);
158
+ const delOk = Number(row.delivery_reports_ok || 0);
159
+ const headerBytes = row.header_bytes !== null && row.header_bytes !== undefined ? Number(row.header_bytes) : null;
160
+ const diagnosticFlags = Array.isArray(row.diagnostic_flags_json)
161
+ ? row.diagnostic_flags_json
162
+ : typeof row.diagnostic_flags_json === "string"
163
+ ? JSON.parse(row.diagnostic_flags_json || "[]")
164
+ : [];
165
+ return {
166
+ chain: row.chain_key,
167
+ address: String(row.address),
168
+ resourceUrl: String(row.resource_url),
169
+ livenessStatus: String(row.liveness_status),
170
+ lastHttpStatus: row.last_http_status !== null && row.last_http_status !== undefined ? Number(row.last_http_status) : null,
171
+ lastLatencyMs: row.last_latency_ms !== null && row.last_latency_ms !== undefined ? Number(row.last_latency_ms) : null,
172
+ probeTotal,
173
+ probeHealthy,
174
+ livenessRate: probeTotal > 0 ? Number((probeHealthy / probeTotal).toFixed(4)) : null,
175
+ deliveryReportsTotal: delTotal,
176
+ deliveryReportsOk: delOk,
177
+ deliverySuccessRate: delTotal > 0 ? Number((delOk / delTotal).toFixed(4)) : null,
178
+ headerBytes,
179
+ aiohttpSafe: headerBytes === null ? null : headerBytes <= 8192,
180
+ nodeHttpSafe: headerBytes === null ? null : headerBytes <= 16384,
181
+ observedPriceUsdc: row.observed_price_usdc !== null && row.observed_price_usdc !== undefined
182
+ ? Number(row.observed_price_usdc)
183
+ : null,
184
+ diagnosticFlags,
185
+ lastError: row.last_error || null,
186
+ lastProbedAt: row.last_probed_at ? new Date(row.last_probed_at).toISOString() : null,
187
+ updatedAt: row.updated_at ? new Date(row.updated_at).toISOString() : new Date().toISOString(),
188
+ };
189
+ }
190
+ export function getPostgresInitDdl() {
191
+ return fs.readFileSync(POSTGRES_DDL_PATH, "utf8");
192
+ }
193
+ /**
194
+ * Creates the FideRail PostgreSQL 16 repository.
195
+ * Supports either a live `pg.Pool` (via `connectionString`) or an injected `PgQueryExecutor`.
196
+ */
197
+ export async function openPostgresRepository(options) {
198
+ const ownPool = !options.executor;
199
+ const executor = options.executor ||
200
+ new pg.Pool({
201
+ connectionString: options.connectionString,
202
+ max: options.maxPoolSize ?? 20,
203
+ idleTimeoutMillis: 30000,
204
+ connectionTimeoutMillis: 10000,
205
+ });
206
+ async function initSchema() {
207
+ const ddl = getPostgresInitDdl();
208
+ await executor.query(ddl);
209
+ const now = new Date();
210
+ const baseYear = now.getUTCFullYear();
211
+ const baseMonth = now.getUTCMonth() + 1;
212
+ // Pre-create monthly partitions from previous month through +3 months ahead
213
+ for (const offset of [-1, 0, 1, 2, 3]) {
214
+ const d = new Date(Date.UTC(baseYear, baseMonth - 1 + offset, 1));
215
+ try {
216
+ await ensureMonthlyPartition(d.getUTCFullYear(), d.getUTCMonth() + 1);
217
+ }
218
+ catch (err) {
219
+ // Ignore overlap if historical data already landed in payments_default before partition creation
220
+ if (!/overlap|default partition/i.test(String(err?.message || ""))) {
221
+ throw err;
222
+ }
223
+ }
224
+ }
225
+ }
226
+ async function ensureMonthlyPartition(year, month) {
227
+ if (!Number.isInteger(year) || !Number.isInteger(month) || month < 1 || month > 12) {
228
+ throw new Error(`Invalid partition year/month: ${year}/${month}`);
229
+ }
230
+ const mm = String(month).padStart(2, "0");
231
+ const partName = `payments_${year}_${mm}`;
232
+ const startIso = `${year}-${mm}-01T00:00:00Z`;
233
+ const nextY = month === 12 ? year + 1 : year;
234
+ const nextM = String(month === 12 ? 1 : month + 1).padStart(2, "0");
235
+ const endIso = `${nextY}-${nextM}-01T00:00:00Z`;
236
+ await executor.query(`CREATE TABLE IF NOT EXISTS ${partName} PARTITION OF payments FOR VALUES FROM ('${startIso}') TO ('${endIso}')`);
237
+ return partName;
238
+ }
239
+ async function countByChain(table) {
240
+ const res = await executor.query(`SELECT chain_key, COUNT(*)::text AS cnt FROM ${table} GROUP BY chain_key`);
241
+ const map = emptyChainCounts();
242
+ for (const r of res.rows) {
243
+ if (r.chain_key === "base" ||
244
+ r.chain_key === "solana" ||
245
+ r.chain_key === "arbitrum" ||
246
+ r.chain_key === "polygon") {
247
+ map[r.chain_key] = Number(r.cnt);
248
+ }
249
+ }
250
+ map.total = map.base + map.solana + map.arbitrum + map.polygon;
251
+ return map;
252
+ }
253
+ if (options.autoInitSchema !== false) {
254
+ await initSchema();
255
+ }
256
+ const repo = {
257
+ backend: "postgresql",
258
+ executor,
259
+ initSchema,
260
+ ensureMonthlyPartition,
261
+ async insertPayments(rows) {
262
+ if (!rows || rows.length === 0)
263
+ return { inserted: 0 };
264
+ const cleaned = [];
265
+ for (const r of rows) {
266
+ const chain = normalizeChainName(r.chain);
267
+ if (!chain || !r.txId)
268
+ continue;
269
+ const payer = normalizeChainAddress(chain, r.payer);
270
+ const payee = normalizeChainAddress(chain, r.payee);
271
+ const amountUsd = Number(r.amountUsd ?? r.amountUsdc ?? r.amount_usdc ?? 0);
272
+ if (!payer || !payee || !Number.isFinite(amountUsd) || amountUsd <= 0)
273
+ continue;
274
+ const primary = getPrimaryAsset(chain);
275
+ const matched = getAssetSpec(chain, r.assetContract || r.assetSymbol) || primary;
276
+ const amountRaw = r.amountRaw || decimalToRawAmount(amountUsd, matched.decimals);
277
+ const tsSec = r.blockTime ?? r.block_time ?? Math.floor(Date.now() / 1000);
278
+ cleaned.push({
279
+ chain,
280
+ txId: String(r.txId),
281
+ eventIndex: Number.isInteger(r.eventIndex) ? Number(r.eventIndex) : 0,
282
+ assetContract: matched.contract,
283
+ assetSymbol: matched.symbol,
284
+ amountRaw,
285
+ amountUsd: Number(amountUsd.toFixed(6)),
286
+ payer,
287
+ payee,
288
+ channel: String(r.channel || `${chain}_x402`),
289
+ facilitator: r.facilitator ?? null,
290
+ relayer: r.relayer ? normalizeChainAddress(chain, r.relayer) : null,
291
+ blockNumber: r.blockNumber ?? null,
292
+ blockTimeIso: new Date(Number(tsSec) * 1000).toISOString(),
293
+ confirmationStatus: r.confirmationStatus || "CONFIRMED",
294
+ hasMemo: Boolean(r.hasMemo),
295
+ });
296
+ }
297
+ if (cleaned.length === 0)
298
+ return { inserted: 0 };
299
+ let inserted = 0;
300
+ const chunkSize = 1500;
301
+ for (let i = 0; i < cleaned.length; i += chunkSize) {
302
+ const slice = cleaned.slice(i, i + chunkSize);
303
+ const valuesSql = [];
304
+ const params = [];
305
+ let p = 1;
306
+ for (const item of slice) {
307
+ valuesSql.push(`($${p++}, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}::numeric, $${p++}::numeric, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}::timestamptz, $${p++}, $${p++})`);
308
+ params.push(item.chain, item.txId, item.eventIndex, item.assetContract, item.assetSymbol, item.amountRaw, item.amountUsd, item.payer, item.payee, item.channel, item.facilitator, item.relayer, item.blockNumber, item.blockTimeIso, item.confirmationStatus, item.hasMemo);
309
+ }
310
+ const res = await executor.query(`INSERT INTO payments (
311
+ chain_key, tx_id, event_index, asset_contract, asset_symbol, amount_raw, amount_usd,
312
+ payer, payee, channel, facilitator, relayer, block_number, block_time, confirmation_status, has_memo
313
+ ) VALUES ${valuesSql.join(", ")}
314
+ ON CONFLICT (chain_key, tx_id, event_index, block_time) DO NOTHING`, params);
315
+ inserted += Number(res.rowCount || 0);
316
+ }
317
+ return { inserted };
318
+ },
319
+ async upsertErc8004Owners(rows) {
320
+ if (!rows || rows.length === 0)
321
+ return { upserted: 0 };
322
+ const dedup = new Map();
323
+ for (const r of rows) {
324
+ const chain = normalizeChainName(r.chain);
325
+ if (!chain)
326
+ continue;
327
+ const owner = normalizeChainAddress(chain, r.ownerAddress);
328
+ if (!owner)
329
+ continue;
330
+ dedup.set(`${chain}|${owner}`, {
331
+ chain,
332
+ owner,
333
+ tokenId: r.tokenId ?? null,
334
+ blockNumber: r.blockNumber ?? null,
335
+ blockTime: r.blockTime ?? null,
336
+ });
337
+ }
338
+ const list = [...dedup.values()];
339
+ const chunkSize = 500;
340
+ for (let i = 0; i < list.length; i += chunkSize) {
341
+ const slice = list.slice(i, i + chunkSize);
342
+ const valuesSql = [];
343
+ const params = [];
344
+ let p = 1;
345
+ for (const item of slice) {
346
+ valuesSql.push(`($${p++}, $${p++}, $${p++}, $${p++}, $${p++})`);
347
+ params.push(item.chain, item.owner, item.tokenId, item.blockNumber, item.blockTime);
348
+ }
349
+ await executor.query(`INSERT INTO erc8004_identities (chain_key, owner_address, token_id, block_number, block_time)
350
+ VALUES ${valuesSql.join(", ")}
351
+ ON CONFLICT (chain_key, owner_address) DO UPDATE SET
352
+ token_id = EXCLUDED.token_id,
353
+ block_number = EXCLUDED.block_number,
354
+ block_time = EXCLUDED.block_time`, params);
355
+ }
356
+ return { upserted: list.length };
357
+ },
358
+ async upsertServiceCapabilities(rows) {
359
+ if (!rows || rows.length === 0)
360
+ return { upserted: 0 };
361
+ const dedup = new Map();
362
+ for (const r of rows) {
363
+ const chain = normalizeChainName(r.chain);
364
+ if (!chain)
365
+ continue;
366
+ const address = normalizeChainAddress(chain, r.address);
367
+ const resourceUrl = String(r.resourceUrl || "").trim();
368
+ if (!address || !resourceUrl)
369
+ continue;
370
+ const rawPrice = r.priceUsdc !== null && r.priceUsdc !== undefined ? Number(r.priceUsdc) : NaN;
371
+ const priceUsdc = Number.isFinite(rawPrice) && rawPrice >= 0 && rawPrice < 1e15
372
+ ? Number(rawPrice.toFixed(6))
373
+ : null;
374
+ dedup.set(`${chain}|${address}|${resourceUrl}`, {
375
+ chain,
376
+ address,
377
+ resourceUrl,
378
+ serviceName: r.serviceName ? String(r.serviceName).slice(0, 160) : null,
379
+ description: r.description ? String(r.description).slice(0, 600) : null,
380
+ method: r.method ? String(r.method).toUpperCase().slice(0, 16) : null,
381
+ priceUsdc,
382
+ tagsJson: JSON.stringify(Array.isArray(r.tags) ? r.tags.slice(0, 16) : []),
383
+ source: String(r.source || "x402_bazaar"),
384
+ lastUpdated: r.lastUpdated ? String(r.lastUpdated) : null,
385
+ });
386
+ }
387
+ const list = [...dedup.values()];
388
+ const chunkSize = 400;
389
+ for (let i = 0; i < list.length; i += chunkSize) {
390
+ const slice = list.slice(i, i + chunkSize);
391
+ const valuesSql = [];
392
+ const params = [];
393
+ let p = 1;
394
+ for (const item of slice) {
395
+ valuesSql.push(`($${p++}, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}::jsonb, $${p++}, $${p++}, NOW())`);
396
+ params.push(item.chain, item.address, item.resourceUrl, item.serviceName, item.description, item.method, item.priceUsdc, item.tagsJson, item.source, item.lastUpdated);
397
+ }
398
+ await executor.query(`INSERT INTO service_capabilities (
399
+ chain_key, address, resource_url, service_name, description, method,
400
+ price_usdc, tags_json, source, last_updated, synced_at
401
+ ) VALUES ${valuesSql.join(", ")}
402
+ ON CONFLICT (chain_key, address, resource_url) DO UPDATE SET
403
+ service_name = EXCLUDED.service_name,
404
+ description = EXCLUDED.description,
405
+ method = EXCLUDED.method,
406
+ price_usdc = EXCLUDED.price_usdc,
407
+ tags_json = EXCLUDED.tags_json,
408
+ source = EXCLUDED.source,
409
+ last_updated = EXCLUDED.last_updated,
410
+ synced_at = NOW()`, params);
411
+ }
412
+ return { upserted: list.length };
413
+ },
414
+ async registerOpenBazaarService(item) {
415
+ const chain = normalizeChainName(item.chain);
416
+ if (!chain)
417
+ throw new Error(`Unsupported chain "${item.chain}"`);
418
+ const { upserted } = await repo.upsertServiceCapabilities([
419
+ {
420
+ chain,
421
+ address: item.address,
422
+ resourceUrl: item.resourceUrl,
423
+ serviceName: item.serviceName ?? null,
424
+ description: item.description ?? null,
425
+ method: item.method ?? null,
426
+ priceUsdc: item.priceUsdc ?? null,
427
+ tags: item.tags ?? [],
428
+ source: item.source || "open_bazaar_self_submit",
429
+ lastUpdated: item.lastUpdated || new Date().toISOString(),
430
+ },
431
+ ]);
432
+ if (upserted > 0 && item.livenessStatus) {
433
+ await repo.recordLivenessProbe({
434
+ chain,
435
+ address: item.address,
436
+ resourceUrl: item.resourceUrl,
437
+ livenessStatus: item.livenessStatus,
438
+ httpStatus: item.httpStatus ?? null,
439
+ latencyMs: item.latencyMs ?? null,
440
+ headerBytes: item.headerBytes ?? null,
441
+ observedPriceUsdc: item.observedPriceUsdc ?? item.priceUsdc ?? null,
442
+ diagnosticFlags: item.diagnosticFlags ?? [],
443
+ error: item.error ?? null,
444
+ });
445
+ }
446
+ return { upserted };
447
+ },
448
+ async getCapabilitiesForAddress(chainInput, addressInput) {
449
+ const chain = normalizeChainName(chainInput);
450
+ if (!chain)
451
+ return [];
452
+ const address = normalizeChainAddress(chain, addressInput);
453
+ const res = await executor.query(`SELECT * FROM service_capabilities
454
+ WHERE chain_key = $1 AND address = $2
455
+ ORDER BY COALESCE(last_updated, '') DESC, synced_at DESC
456
+ LIMIT 10`, [chain, address]);
457
+ return res.rows.map(rowToCapability);
458
+ },
459
+ async getCapabilitiesSummaryForAddresses(keys) {
460
+ const out = new Map();
461
+ if (!keys || keys.length === 0)
462
+ return out;
463
+ for (const { chain, address } of keys) {
464
+ const caps = await repo.getCapabilitiesForAddress(chain, address);
465
+ if (caps.length === 0)
466
+ continue;
467
+ const normAddr = normalizeChainAddress(chain, address);
468
+ const tags = new Set();
469
+ const sources = new Set();
470
+ let minPriceUsdc = null;
471
+ for (const c of caps) {
472
+ if (c.priceUsdc !== null && (minPriceUsdc === null || c.priceUsdc < minPriceUsdc)) {
473
+ minPriceUsdc = c.priceUsdc;
474
+ }
475
+ for (const t of c.tags)
476
+ tags.add(t);
477
+ if (c.source)
478
+ sources.add(c.source);
479
+ }
480
+ out.set(`${chain}:${normAddr}`, {
481
+ serviceCount: caps.length,
482
+ primaryServiceName: caps.find((c) => c.serviceName)?.serviceName || null,
483
+ primaryDescription: caps.find((c) => c.description)?.description || null,
484
+ primaryResourceUrl: caps[0].resourceUrl,
485
+ minPriceUsdc,
486
+ tags: [...tags].slice(0, 8),
487
+ sources: [...sources],
488
+ });
489
+ }
490
+ return out;
491
+ },
492
+ async searchCapabilities({ query = "", chain = "all", maxPriceUsdc = null, limit = 50 } = {}) {
493
+ const where = ["1 = 1"];
494
+ const params = [];
495
+ let p = 1;
496
+ if (chain !== "all") {
497
+ const norm = normalizeChainName(chain);
498
+ if (!norm)
499
+ throw new Error(`Unsupported chain filter "${chain}".`);
500
+ where.push(`chain_key = $${p++}`);
501
+ params.push(norm);
502
+ }
503
+ if (maxPriceUsdc !== null && maxPriceUsdc !== undefined) {
504
+ const maxP = Number(maxPriceUsdc);
505
+ if (Number.isFinite(maxP) && maxP >= 0) {
506
+ where.push(`(price_usdc IS NULL OR price_usdc <= $${p++})`);
507
+ params.push(maxP);
508
+ }
509
+ }
510
+ const likePattern = buildSafeLikePattern(query);
511
+ if (likePattern) {
512
+ where.push(`LOWER(COALESCE(service_name, '') || ' ' || COALESCE(description, '') || ' ' || resource_url || ' ' || tags_json::text || ' ' || address) LIKE $${p++} ESCAPE '\\'`);
513
+ params.push(likePattern);
514
+ }
515
+ const clampedLimit = Math.max(1, Math.min(500, Number(limit) || 50));
516
+ params.push(clampedLimit);
517
+ const res = await executor.query(`SELECT * FROM service_capabilities WHERE ${where.join(" AND ")} ORDER BY COALESCE(last_updated, '') DESC, synced_at DESC LIMIT $${p}`, params);
518
+ return res.rows.map(rowToCapability);
519
+ },
520
+ async recordLivenessProbe(input) {
521
+ const chain = normalizeChainName(input.chain);
522
+ if (!chain)
523
+ throw new Error(`Unsupported chain "${input.chain}"`);
524
+ const address = normalizeChainAddress(chain, input.address);
525
+ const url = String(input.resourceUrl || "").trim();
526
+ const healthyInc = isHealthyLivenessStatus(input.livenessStatus) ? 1 : 0;
527
+ const normFlags = Array.isArray(input.diagnosticFlags)
528
+ ? input.diagnosticFlags.map((f) => String(f)).slice(0, 24)
529
+ : [];
530
+ await executor.query(`INSERT INTO service_liveness (
531
+ chain_key, address, resource_url, liveness_status, last_http_status, last_latency_ms,
532
+ probe_total, probe_healthy, delivery_reports_total, delivery_reports_ok,
533
+ header_bytes, observed_price_usdc, diagnostic_flags_json, last_error, last_probed_at, updated_at
534
+ ) VALUES ($1, $2, $3, $4, $5, $6, 1, $7, 0, 0, $8, $9, $10::jsonb, $11, NOW(), NOW())
535
+ ON CONFLICT (chain_key, address, resource_url) DO UPDATE SET
536
+ liveness_status = EXCLUDED.liveness_status,
537
+ last_http_status = EXCLUDED.last_http_status,
538
+ last_latency_ms = EXCLUDED.last_latency_ms,
539
+ probe_total = service_liveness.probe_total + 1,
540
+ probe_healthy = service_liveness.probe_healthy + EXCLUDED.probe_healthy,
541
+ header_bytes = COALESCE(EXCLUDED.header_bytes, service_liveness.header_bytes),
542
+ observed_price_usdc = COALESCE(EXCLUDED.observed_price_usdc, service_liveness.observed_price_usdc),
543
+ diagnostic_flags_json = EXCLUDED.diagnostic_flags_json,
544
+ last_error = EXCLUDED.last_error,
545
+ last_probed_at = NOW(),
546
+ updated_at = NOW()`, [
547
+ chain,
548
+ address,
549
+ url,
550
+ String(input.livenessStatus),
551
+ input.httpStatus ?? null,
552
+ input.latencyMs !== null && input.latencyMs !== undefined ? Math.round(Number(input.latencyMs)) : null,
553
+ healthyInc,
554
+ input.headerBytes !== null && input.headerBytes !== undefined
555
+ ? Math.max(0, Math.round(Number(input.headerBytes)))
556
+ : null,
557
+ input.observedPriceUsdc ?? null,
558
+ JSON.stringify(normFlags),
559
+ input.error ? String(input.error).slice(0, 240) : null,
560
+ ]);
561
+ },
562
+ async recordDeliveryTelemetry(input) {
563
+ const chain = normalizeChainName(input.chain);
564
+ if (!chain)
565
+ throw new Error(`Unsupported chain "${input.chain}"`);
566
+ const address = normalizeChainAddress(chain, input.address);
567
+ const url = String(input.resourceUrl || "").trim();
568
+ const okInc = input.delivered ? 1 : 0;
569
+ const initialStatus = input.delivered ? "LIVE_200" : "DEGRADED";
570
+ let duplicate = false;
571
+ if (input.receipt) {
572
+ const recObj = input.receipt;
573
+ const receiptHash = typeof recObj.receiptHash === "string"
574
+ ? recObj.receiptHash
575
+ : typeof recObj.quoteDigest === "string"
576
+ ? recObj.quoteDigest
577
+ : null;
578
+ const attRes = await executor.query(`INSERT INTO delivery_attestations (
579
+ chain_key, address, resource_url, receipt_hash, verification_tier,
580
+ delivered, http_status, latency_ms, receipt_payload
581
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb)
582
+ ON CONFLICT (receipt_hash) DO NOTHING
583
+ RETURNING id`, [
584
+ chain,
585
+ address,
586
+ url,
587
+ receiptHash,
588
+ input.verificationTier || "L2_SIGNED_SAR_TELEMETRY",
589
+ Boolean(input.delivered),
590
+ input.httpStatus ?? null,
591
+ input.latencyMs !== null && input.latencyMs !== undefined
592
+ ? Math.round(Number(input.latencyMs))
593
+ : null,
594
+ JSON.stringify(input.receipt),
595
+ ]);
596
+ if (receiptHash && attRes.rows.length === 0) {
597
+ duplicate = true;
598
+ }
599
+ }
600
+ if (!duplicate) {
601
+ await executor.query(`INSERT INTO service_liveness (
602
+ chain_key, address, resource_url, liveness_status, last_http_status, last_latency_ms,
603
+ probe_total, probe_healthy, delivery_reports_total, delivery_reports_ok, updated_at
604
+ ) VALUES ($1, $2, $3, $4, $5, $6, 0, 0, 1, $7, NOW())
605
+ ON CONFLICT (chain_key, address, resource_url) DO UPDATE SET
606
+ last_http_status = COALESCE(EXCLUDED.last_http_status, service_liveness.last_http_status),
607
+ last_latency_ms = COALESCE(EXCLUDED.last_latency_ms, service_liveness.last_latency_ms),
608
+ delivery_reports_total = service_liveness.delivery_reports_total + 1,
609
+ delivery_reports_ok = service_liveness.delivery_reports_ok + EXCLUDED.delivery_reports_ok,
610
+ updated_at = NOW()`, [
611
+ chain,
612
+ address,
613
+ url,
614
+ initialStatus,
615
+ input.httpStatus ?? null,
616
+ input.latencyMs !== null && input.latencyMs !== undefined
617
+ ? Math.round(Number(input.latencyMs))
618
+ : null,
619
+ okInc,
620
+ ]);
621
+ }
622
+ return { duplicate };
623
+ },
624
+ async getLivenessForAddress(chainInput, addressInput) {
625
+ const map = new Map();
626
+ const chain = normalizeChainName(chainInput);
627
+ if (!chain)
628
+ return map;
629
+ const address = normalizeChainAddress(chain, addressInput);
630
+ const res = await executor.query(`SELECT * FROM service_liveness WHERE chain_key = $1 AND address = $2`, [chain, address]);
631
+ for (const r of res.rows) {
632
+ const item = rowToLiveness(r);
633
+ map.set(item.resourceUrl, item);
634
+ }
635
+ return map;
636
+ },
637
+ async getAddressLivenessSummary(chainInput, addressInput) {
638
+ const chain = normalizeChainName(chainInput);
639
+ if (!chain)
640
+ return null;
641
+ const address = normalizeChainAddress(chain, addressInput);
642
+ const res = await executor.query(`SELECT
643
+ SUM(CASE WHEN probe_total > 0 THEN 1 ELSE 0 END) AS probed_endpoints,
644
+ SUM(CASE WHEN probe_total > 0 AND liveness_status IN ('LIVE_402', 'LIVE_200', 'LIVE_REACHABLE') THEN 1 ELSE 0 END) AS healthy_endpoints,
645
+ SUM(CASE WHEN probe_total > 0 AND liveness_status NOT IN ('LIVE_402', 'LIVE_200', 'LIVE_REACHABLE') THEN 1 ELSE 0 END) AS down_endpoints,
646
+ AVG(CASE WHEN last_latency_ms IS NOT NULL THEN last_latency_ms END) AS avg_latency_ms,
647
+ COALESCE(SUM(delivery_reports_total), 0) AS delivery_reports_total,
648
+ COALESCE(SUM(delivery_reports_ok), 0) AS delivery_reports_ok
649
+ FROM service_liveness
650
+ WHERE chain_key = $1 AND address = $2`, [chain, address]);
651
+ const row = res.rows[0];
652
+ if (!row)
653
+ return null;
654
+ const probed = Number(row.probed_endpoints || 0);
655
+ const delTotal = Number(row.delivery_reports_total || 0);
656
+ if (probed === 0 && delTotal === 0)
657
+ return null;
658
+ const delOk = Number(row.delivery_reports_ok || 0);
659
+ return {
660
+ probedEndpoints: probed,
661
+ healthyEndpoints: Number(row.healthy_endpoints || 0),
662
+ downEndpoints: Number(row.down_endpoints || 0),
663
+ avgLatencyMs: row.avg_latency_ms !== null && row.avg_latency_ms !== undefined
664
+ ? Math.round(Number(row.avg_latency_ms))
665
+ : null,
666
+ deliveryReportsTotal: delTotal,
667
+ deliverySuccessRate: delTotal > 0 ? Number((delOk / delTotal).toFixed(4)) : null,
668
+ };
669
+ },
670
+ async getLivenessForResources(keys) {
671
+ const out = new Map();
672
+ if (!keys || keys.length === 0)
673
+ return out;
674
+ for (const k of keys) {
675
+ const addr = normalizeChainAddress(k.chain, k.address);
676
+ const res = await executor.query(`SELECT * FROM service_liveness WHERE chain_key = $1 AND address = $2 AND resource_url = $3`, [k.chain, addr, k.resourceUrl]);
677
+ if (res.rows[0]) {
678
+ out.set(`${k.chain}:${addr}:${k.resourceUrl}`, rowToLiveness(res.rows[0]));
679
+ }
680
+ }
681
+ return out;
682
+ },
683
+ async getAddressLivenessSummariesForAddresses(keys) {
684
+ const out = new Map();
685
+ if (!keys || keys.length === 0)
686
+ return out;
687
+ for (const { chain, address } of keys) {
688
+ const addr = normalizeChainAddress(chain, address);
689
+ const summary = await repo.getAddressLivenessSummary(chain, addr);
690
+ if (summary)
691
+ out.set(`${chain}:${addr}`, summary);
692
+ }
693
+ return out;
694
+ },
695
+ async listServicesToProbe({ limit = 30 } = {}) {
696
+ const clamped = Math.max(1, Math.min(200, Number(limit) || 30));
697
+ const res = await executor.query(`SELECT sc.chain_key AS chain, sc.address, sc.resource_url AS "resourceUrl", sc.method,
698
+ sc.price_usdc AS "catalogPriceUsdc"
699
+ FROM service_capabilities sc
700
+ LEFT JOIN service_liveness sl
701
+ ON sc.chain_key = sl.chain_key AND sc.address = sl.address AND sc.resource_url = sl.resource_url
702
+ LEFT JOIN agent_profiles ap
703
+ ON sc.chain_key = ap.chain_key AND sc.address = ap.address
704
+ ORDER BY
705
+ CASE WHEN ap.address IS NOT NULL THEN 0 ELSE 1 END ASC,
706
+ COALESCE(sl.last_probed_at, TO_TIMESTAMP(0)) ASC,
707
+ COALESCE(sc.last_updated, '') DESC
708
+ LIMIT $1`, [clamped]);
709
+ return res.rows.map((r) => ({
710
+ chain: r.chain,
711
+ address: String(r.address),
712
+ resourceUrl: String(r.resourceUrl),
713
+ method: r.method || null,
714
+ catalogPriceUsdc: r.catalogPriceUsdc !== null && r.catalogPriceUsdc !== undefined
715
+ ? Number(r.catalogPriceUsdc)
716
+ : null,
717
+ }));
718
+ },
719
+ async recomputeProfiles(chainInput, options = {}) {
720
+ const chain = normalizeChainName(chainInput);
721
+ if (!chain)
722
+ throw new Error(`Unsupported chain "${chainInput}"`);
723
+ const [paymentsRes, ownersRes, prevRes] = await Promise.all([
724
+ executor.query(`SELECT payer, payee, amount_usd::float8 AS amount_usdc,
725
+ EXTRACT(EPOCH FROM block_time)::bigint AS block_time, channel
726
+ FROM payments
727
+ WHERE chain_key = $1 AND confirmation_status != 'REORGED'`, [chain]),
728
+ executor.query(`SELECT owner_address FROM erc8004_identities WHERE chain_key = $1`, [chain]),
729
+ executor.query(`SELECT address, credit_score, risk_flags_json FROM agent_profiles WHERE chain_key = $1`, [chain]),
730
+ ]);
731
+ const owners = new Set(ownersRes.rows.map((r) => r.owner_address));
732
+ // Stream rows via generator to avoid duplicating 1M+ payment objects in RAM
733
+ function* paymentRecordStream(chainKey) {
734
+ for (const r of paymentsRes.rows) {
735
+ yield {
736
+ chain: chainKey,
737
+ txId: "",
738
+ payer: String(r.payer),
739
+ payee: String(r.payee),
740
+ amountUsd: Number(r.amount_usdc),
741
+ blockTime: r.block_time !== null ? Number(r.block_time) : null,
742
+ channel: String(r.channel || ""),
743
+ };
744
+ }
745
+ }
746
+ const activeScorer = options.scorer ?? DEFAULT_TRUST_SCORER;
747
+ const profiles = computeCreditProfilesFromPayments(chain, paymentRecordStream(chain), owners, "postgres_live", {
748
+ scorer: activeScorer,
749
+ referenceTimeSec: options.referenceTimeSec,
750
+ });
751
+ const stateRoot = buildTrustStateRootCommitment(chain, profiles, {
752
+ modelVersion: activeScorer.modelVersion,
753
+ modelHash: activeScorer.modelHash,
754
+ signRoot: options.signRoot ??
755
+ ((merkleRoot, epochId) => signStateRootEd25519(merkleRoot, epochId)),
756
+ });
757
+ const prevScores = new Map();
758
+ for (const r of prevRes.rows) {
759
+ prevScores.set(r.address, {
760
+ score: Number(r.credit_score),
761
+ flags: JSON.stringify(r.risk_flags_json || []),
762
+ });
763
+ }
764
+ const historyBatch = [];
765
+ // Batch upsert profiles in chunks of 400 (25 params/row = 10,000 params)
766
+ const profileChunkSize = 400;
767
+ for (let i = 0; i < profiles.length; i += profileChunkSize) {
768
+ const slice = profiles.slice(i, i + profileChunkSize);
769
+ const valuesSql = [];
770
+ const params = [];
771
+ let idx = 1;
772
+ for (const p of slice) {
773
+ const flagsJson = JSON.stringify(p.riskFlags);
774
+ valuesSql.push(`($${idx++}, $${idx++}, $${idx++}, $${idx++}, $${idx++}, $${idx++}, $${idx++}, $${idx++}, $${idx++}, $${idx++}, $${idx++}, $${idx++}, $${idx++}, $${idx++}, $${idx++}, $${idx++}, $${idx++}, $${idx++}::jsonb, $${idx++}::jsonb, $${idx++}::jsonb, $${idx++}::jsonb, $${idx++}, $${idx++}, $${idx++}::timestamptz, $${idx++}::timestamptz, NOW(), 'postgres_live')`);
775
+ params.push(p.chain, p.address, p.creditScore, p.tier, p.confidence ?? null, p.confidenceLevel ?? null, p.riskLevel ?? null, p.modelVersion || activeScorer.modelVersion, p.modelHash || activeScorer.modelHash, p.metrics.txCount, Number(Number(p.metrics.totalUsdc || 0).toFixed(6)), p.metrics.uniquePayers, Number(Number(p.metrics.medianTicketUsdc || 0).toFixed(6)), Number(Number(p.metrics.hhi || 0).toFixed(4)), Number(Number(p.metrics.top1PayerShare || 0).toFixed(4)), Number(Number(p.metrics.activeSpanHours || 0).toFixed(2)), p.metrics.activeUtcDays, JSON.stringify(p.metrics), p.dataCoverage ? JSON.stringify(p.dataCoverage) : null, JSON.stringify(p.channels), flagsJson, isVerifiedX402Channels(p.channels), p.erc8004Registered, p.firstSeenAt, p.lastSeenAt);
776
+ const prev = prevScores.get(p.address);
777
+ if (!prev || Math.abs(prev.score - p.creditScore) >= 5 || prev.flags !== flagsJson) {
778
+ historyBatch.push({
779
+ chain: p.chain,
780
+ address: p.address,
781
+ modelVersion: p.modelVersion || activeScorer.modelVersion,
782
+ prevScore: prev ? prev.score : null,
783
+ currentScore: p.creditScore,
784
+ flagsJson,
785
+ });
786
+ }
787
+ }
788
+ await executor.query(`INSERT INTO agent_profiles (
789
+ chain_key, address, credit_score, tier, confidence, confidence_level, risk_level,
790
+ model_version, model_hash,
791
+ tx_count, total_usdc, unique_payers, median_ticket_usdc, hhi, top1_payer_share,
792
+ active_span_hours, active_utc_days, metrics_json, data_coverage_json,
793
+ channels_json, risk_flags_json,
794
+ has_verified_x402, erc8004_registered, first_seen_at, last_seen_at, updated_at, source
795
+ ) VALUES ${valuesSql.join(", ")}
796
+ ON CONFLICT (chain_key, address) DO UPDATE SET
797
+ credit_score = EXCLUDED.credit_score,
798
+ tier = EXCLUDED.tier,
799
+ confidence = EXCLUDED.confidence,
800
+ confidence_level = EXCLUDED.confidence_level,
801
+ risk_level = EXCLUDED.risk_level,
802
+ model_version = EXCLUDED.model_version,
803
+ model_hash = EXCLUDED.model_hash,
804
+ tx_count = EXCLUDED.tx_count,
805
+ total_usdc = EXCLUDED.total_usdc,
806
+ unique_payers = EXCLUDED.unique_payers,
807
+ median_ticket_usdc = EXCLUDED.median_ticket_usdc,
808
+ hhi = EXCLUDED.hhi,
809
+ top1_payer_share = EXCLUDED.top1_payer_share,
810
+ active_span_hours = EXCLUDED.active_span_hours,
811
+ active_utc_days = EXCLUDED.active_utc_days,
812
+ metrics_json = EXCLUDED.metrics_json,
813
+ data_coverage_json = EXCLUDED.data_coverage_json,
814
+ channels_json = EXCLUDED.channels_json,
815
+ risk_flags_json = EXCLUDED.risk_flags_json,
816
+ has_verified_x402 = EXCLUDED.has_verified_x402,
817
+ erc8004_registered = EXCLUDED.erc8004_registered,
818
+ first_seen_at = EXCLUDED.first_seen_at,
819
+ last_seen_at = EXCLUDED.last_seen_at,
820
+ updated_at = NOW(),
821
+ source = 'postgres_live'`, params);
822
+ }
823
+ // Batch insert delta history rows in chunks of 500
824
+ const historyChunkSize = 500;
825
+ for (let i = 0; i < historyBatch.length; i += historyChunkSize) {
826
+ const slice = historyBatch.slice(i, i + historyChunkSize);
827
+ const valuesSql = [];
828
+ const params = [];
829
+ let idx = 1;
830
+ for (const h of slice) {
831
+ valuesSql.push(`($${idx++}, $${idx++}, $${idx++}, $${idx++}, $${idx++}, $${idx++}::jsonb)`);
832
+ params.push(h.chain, h.address, h.modelVersion, h.prevScore, h.currentScore, h.flagsJson);
833
+ }
834
+ await executor.query(`INSERT INTO trust_score_history (
835
+ chain_key, address, model_version, previous_score, current_score, reason_codes
836
+ ) VALUES ${valuesSql.join(", ")}`, params);
837
+ }
838
+ await executor.query(`INSERT INTO trust_state_roots (
839
+ epoch_id, chain_key, model_version, model_hash, merkle_root, leaf_count, proof_type, signature
840
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
841
+ ON CONFLICT (epoch_id) DO UPDATE SET
842
+ merkle_root = EXCLUDED.merkle_root,
843
+ leaf_count = EXCLUDED.leaf_count,
844
+ signature = EXCLUDED.signature`, [
845
+ stateRoot.epochId,
846
+ chain,
847
+ stateRoot.modelVersion,
848
+ stateRoot.modelHash,
849
+ stateRoot.merkleRoot,
850
+ stateRoot.leafCount,
851
+ stateRoot.proofType,
852
+ stateRoot.signature,
853
+ ]);
854
+ return { profileCount: profiles.length, stateRoot };
855
+ },
856
+ async getProfile(chainInput, addressInput) {
857
+ const chain = normalizeChainName(chainInput);
858
+ if (!chain)
859
+ return null;
860
+ const address = normalizeChainAddress(chain, addressInput);
861
+ const res = await executor.query(`SELECT * FROM agent_profiles WHERE chain_key = $1 AND address = $2`, [chain, address]);
862
+ return res.rows[0] ? rowToProfile(res.rows[0]) : null;
863
+ },
864
+ async getPayerActivity(chainInput, addressInput) {
865
+ const chain = normalizeChainName(chainInput);
866
+ if (!chain)
867
+ return null;
868
+ const address = normalizeChainAddress(chain, addressInput);
869
+ if (!address)
870
+ return null;
871
+ const res = await executor.query(`SELECT
872
+ COUNT(*)::text AS tx_count,
873
+ COUNT(DISTINCT CASE WHEN payee != payer THEN payee END)::text AS distinct_payees,
874
+ COALESCE(SUM(amount_usd), 0)::float8 AS total_usd,
875
+ MIN(block_time) AS first_seen_at,
876
+ MAX(block_time) AS last_seen_at,
877
+ COUNT(DISTINCT (block_time AT TIME ZONE 'UTC')::date)::text AS active_utc_days,
878
+ COALESCE(BOOL_OR(payee = payer), FALSE) AS has_self_transfer
879
+ FROM payments
880
+ WHERE chain_key = $1 AND payer = $2 AND confirmation_status != 'REORGED'`, [chain, address]);
881
+ const row = res.rows[0];
882
+ const txCount = Number(row?.tx_count || 0);
883
+ if (!row || txCount === 0)
884
+ return null;
885
+ let hasReciprocalLoop = Boolean(row.has_self_transfer);
886
+ if (!hasReciprocalLoop) {
887
+ const loopRes = await executor.query(`SELECT EXISTS (
888
+ SELECT 1
889
+ FROM payments p_in
890
+ WHERE p_in.chain_key = $1
891
+ AND p_in.payee = $2
892
+ AND p_in.payer != $2
893
+ AND p_in.confirmation_status != 'REORGED'
894
+ AND EXISTS (
895
+ SELECT 1
896
+ FROM payments p_out
897
+ WHERE p_out.chain_key = $1
898
+ AND p_out.payer = $2
899
+ AND p_out.payee = p_in.payer
900
+ AND p_out.confirmation_status != 'REORGED'
901
+ )
902
+ ) AS has_reciprocal`, [chain, address]);
903
+ hasReciprocalLoop = Boolean(loopRes.rows[0]?.has_reciprocal);
904
+ }
905
+ return {
906
+ chain,
907
+ address,
908
+ txCount,
909
+ distinctPayees: Number(row.distinct_payees || 0),
910
+ totalUsd: Number(Number(row.total_usd || 0).toFixed(6)),
911
+ firstSeenAt: toIsoOrNull(row.first_seen_at),
912
+ lastSeenAt: toIsoOrNull(row.last_seen_at),
913
+ activeUtcDays: Math.max(1, Number(row.active_utc_days || 0)),
914
+ hasReciprocalLoop,
915
+ };
916
+ },
917
+ async listChainProfiles(chainInput) {
918
+ const chain = normalizeChainName(chainInput);
919
+ if (!chain)
920
+ return [];
921
+ const res = await executor.query(`SELECT * FROM agent_profiles WHERE chain_key = $1 ORDER BY address ASC`, [chain]);
922
+ return res.rows.map(rowToProfile);
923
+ },
924
+ async getScoreHistory(chainInput, addressInput, limit = 50) {
925
+ const chain = normalizeChainName(chainInput);
926
+ if (!chain)
927
+ return [];
928
+ const address = normalizeChainAddress(chain, addressInput);
929
+ if (!address)
930
+ return [];
931
+ const clampedLimit = Math.max(1, Math.min(200, Number(limit) || 50));
932
+ const res = await executor.query(`SELECT * FROM trust_score_history
933
+ WHERE chain_key = $1 AND address = $2
934
+ ORDER BY recorded_at DESC, id DESC
935
+ LIMIT $3`, [chain, address, clampedLimit]);
936
+ return res.rows.map(rowToHistoryEntry);
937
+ },
938
+ async getLatestStateRoot(chainInput) {
939
+ const chain = normalizeChainName(chainInput);
940
+ if (!chain)
941
+ return null;
942
+ const res = await executor.query(`SELECT * FROM trust_state_roots
943
+ WHERE chain_key = $1
944
+ ORDER BY created_at DESC, epoch_id DESC
945
+ LIMIT 1`, [chain]);
946
+ return res.rows[0] ? rowToStateRoot(res.rows[0]) : null;
947
+ },
948
+ async upsertAssociatedCredit(endorsement) {
949
+ const parentChain = normalizeChainName(endorsement.parentChain);
950
+ const childChain = normalizeChainName(endorsement.childChain);
951
+ if (!parentChain || !childChain) {
952
+ throw new Error(`Unsupported associated credit chain pair: ${endorsement.parentChain} -> ${endorsement.childChain}`);
953
+ }
954
+ const parentAddress = normalizeChainAddress(parentChain, endorsement.parentAddress);
955
+ const childAddress = normalizeChainAddress(childChain, endorsement.childAddress);
956
+ const nowIso = new Date().toISOString();
957
+ await executor.query(`INSERT INTO associated_credit_endorsements (
958
+ endorsement_id, parent_chain, parent_address, child_chain, child_address,
959
+ discount_factor, max_endorsed_score, max_endorsed_single_tx_usd,
960
+ rule_version, status, issued_at, expires_at, proof_type, proof_payload, updated_at
961
+ ) VALUES (
962
+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::timestamptz, $12::timestamptz, $13, $14::jsonb, NOW()
963
+ )
964
+ ON CONFLICT (endorsement_id) DO UPDATE SET
965
+ parent_chain = EXCLUDED.parent_chain,
966
+ parent_address = EXCLUDED.parent_address,
967
+ child_chain = EXCLUDED.child_chain,
968
+ child_address = EXCLUDED.child_address,
969
+ discount_factor = EXCLUDED.discount_factor,
970
+ max_endorsed_score = EXCLUDED.max_endorsed_score,
971
+ max_endorsed_single_tx_usd = EXCLUDED.max_endorsed_single_tx_usd,
972
+ rule_version = EXCLUDED.rule_version,
973
+ status = EXCLUDED.status,
974
+ issued_at = EXCLUDED.issued_at,
975
+ expires_at = EXCLUDED.expires_at,
976
+ proof_type = EXCLUDED.proof_type,
977
+ proof_payload = EXCLUDED.proof_payload,
978
+ updated_at = NOW()`, [
979
+ String(endorsement.endorsementId),
980
+ parentChain,
981
+ parentAddress,
982
+ childChain,
983
+ childAddress,
984
+ Number(endorsement.discountFactor),
985
+ Math.round(Number(endorsement.maxEndorsedScore)),
986
+ Number(endorsement.maxEndorsedSingleTxUsd),
987
+ String(endorsement.ruleVersion || "assoc-v1"),
988
+ String(endorsement.status || "ACTIVE"),
989
+ String(endorsement.issuedAt || nowIso),
990
+ String(endorsement.expiresAt),
991
+ String(endorsement.proofType || "ed25519"),
992
+ endorsement.proofPayload ? JSON.stringify(endorsement.proofPayload) : null,
993
+ ]);
994
+ },
995
+ async revokeAssociatedCredit(endorsementId) {
996
+ await executor.query(`UPDATE associated_credit_endorsements
997
+ SET status = 'REVOKED', updated_at = NOW()
998
+ WHERE endorsement_id = $1`, [String(endorsementId)]);
999
+ },
1000
+ async getAssociatedCreditForChild(chainInput, childAddressInput) {
1001
+ const chain = normalizeChainName(chainInput);
1002
+ if (!chain)
1003
+ return null;
1004
+ const childAddress = normalizeChainAddress(chain, childAddressInput);
1005
+ if (!childAddress)
1006
+ return null;
1007
+ const res = await executor.query(`SELECT * FROM associated_credit_endorsements
1008
+ WHERE child_chain = $1 AND child_address = $2
1009
+ ORDER BY CASE WHEN status = 'ACTIVE' THEN 0 ELSE 1 END ASC, updated_at DESC
1010
+ LIMIT 1`, [chain, childAddress]);
1011
+ return res.rows[0] ? rowToAssociatedCredit(res.rows[0]) : null;
1012
+ },
1013
+ async listProfiles({ chain = "all", minScore = 0, excludeFlagged = false, tier = "all", channel = "all", sort = "score", offset = 0, limit = 20, query = "", } = {}) {
1014
+ const where = ["credit_score >= $1"];
1015
+ const params = [Number(minScore) || 0];
1016
+ let p = 2;
1017
+ if (chain !== "all") {
1018
+ const norm = normalizeChainName(chain);
1019
+ if (!norm)
1020
+ throw new Error(`Unsupported chain filter "${chain}".`);
1021
+ where.push(`chain_key = $${p++}`);
1022
+ params.push(norm);
1023
+ }
1024
+ if (excludeFlagged) {
1025
+ where.push("tier NOT IN ('FLAGGED_LOOP', 'FLAGGED_CONCENTRATED', 'FLAGGED_FARM')");
1026
+ }
1027
+ const tierFilter = String(tier || "all").trim().toUpperCase();
1028
+ if (tierFilter === "FLAGGED") {
1029
+ where.push("tier IN ('FLAGGED_LOOP', 'FLAGGED_CONCENTRATED', 'FLAGGED_FARM')");
1030
+ }
1031
+ else if (tierFilter !== "ALL") {
1032
+ where.push(`UPPER(tier) = $${p++}`);
1033
+ params.push(tierFilter);
1034
+ }
1035
+ if (String(channel || "all").trim().toLowerCase() === "x402") {
1036
+ where.push("has_verified_x402 = TRUE");
1037
+ }
1038
+ const pattern = buildSafeLikePattern(query);
1039
+ if (pattern) {
1040
+ where.push(`(LOWER(address) LIKE $${p} ESCAPE '\\' OR EXISTS (
1041
+ SELECT 1 FROM service_capabilities sc
1042
+ WHERE sc.chain_key = agent_profiles.chain_key AND sc.address = agent_profiles.address
1043
+ AND LOWER(COALESCE(sc.service_name, '') || ' ' || COALESCE(sc.description, '')) LIKE $${p} ESCAPE '\\'
1044
+ ))`);
1045
+ params.push(pattern);
1046
+ p += 1;
1047
+ }
1048
+ let orderBy = "credit_score DESC, total_usdc DESC";
1049
+ if (sort === "volume")
1050
+ orderBy = "total_usdc DESC, credit_score DESC";
1051
+ else if (sort === "txs")
1052
+ orderBy = "tx_count DESC, credit_score DESC";
1053
+ else if (sort === "risk") {
1054
+ orderBy =
1055
+ "CASE WHEN tier IN ('FLAGGED_LOOP', 'FLAGGED_CONCENTRATED', 'FLAGGED_FARM') THEN 1 ELSE 0 END DESC, credit_score ASC, total_usdc DESC";
1056
+ }
1057
+ const whereSql = where.join(" AND ");
1058
+ const countRes = await executor.query(`SELECT COUNT(*)::text AS cnt FROM agent_profiles WHERE ${whereSql}`, params);
1059
+ const clampedOffset = Math.max(0, Math.floor(Number(offset) || 0));
1060
+ const clampedLimit = Math.max(1, Math.min(200, Number(limit) || 20));
1061
+ const rowsRes = await executor.query(`SELECT * FROM agent_profiles WHERE ${whereSql} ORDER BY ${orderBy} LIMIT $${p} OFFSET $${p + 1}`, [...params, clampedLimit, clampedOffset]);
1062
+ return {
1063
+ totalMatched: Number(countRes.rows[0]?.cnt || 0),
1064
+ agents: rowsRes.rows.map(rowToProfile),
1065
+ };
1066
+ },
1067
+ async setState(key, value) {
1068
+ await executor.query(`INSERT INTO indexer_state (key, value, updated_at) VALUES ($1, $2, NOW())
1069
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()`, [String(key), String(value)]);
1070
+ },
1071
+ async getState() {
1072
+ const res = await executor.query(`SELECT key, value FROM indexer_state`);
1073
+ const out = {};
1074
+ for (const r of res.rows)
1075
+ out[r.key] = r.value;
1076
+ return out;
1077
+ },
1078
+ async getStats() {
1079
+ const [payments, profiles, erc8004Owners, capabilities, capPayeesRes, lvRes, tierRes, earliestRes, sizeRes,] = await Promise.all([
1080
+ countByChain("payments"),
1081
+ countByChain("agent_profiles"),
1082
+ countByChain("erc8004_identities"),
1083
+ countByChain("service_capabilities"),
1084
+ executor.query(`SELECT COUNT(DISTINCT chain_key || ':' || address)::text AS cnt FROM service_capabilities`),
1085
+ executor.query(`SELECT
1086
+ COALESCE(SUM(CASE WHEN probe_total > 0 AND liveness_status IN ('LIVE_402', 'LIVE_200', 'LIVE_REACHABLE') THEN 1 ELSE 0 END), 0) AS healthy,
1087
+ COALESCE(SUM(CASE WHEN probe_total > 0 AND liveness_status NOT IN ('LIVE_402', 'LIVE_200', 'LIVE_REACHABLE') THEN 1 ELSE 0 END), 0) AS degraded_or_down,
1088
+ COALESCE(SUM(delivery_reports_total), 0) AS delivery_reports_total,
1089
+ COALESCE(SUM(delivery_reports_ok), 0) AS delivery_reports_ok
1090
+ FROM service_liveness`),
1091
+ executor.query(`SELECT
1092
+ COALESCE(SUM(CASE WHEN credit_score >= 70 AND tier = 'HIGH_TRUST' THEN 1 ELSE 0 END), 0) AS high_trust,
1093
+ COALESCE(SUM(CASE WHEN credit_score >= 40 AND credit_score < 70 AND tier = 'MODERATE_TRUST' THEN 1 ELSE 0 END), 0) AS moderate_trust,
1094
+ COALESCE(SUM(CASE WHEN tier IN ('FLAGGED_LOOP', 'FLAGGED_CONCENTRATED', 'FLAGGED_FARM') THEN 1 ELSE 0 END), 0) AS flagged
1095
+ FROM agent_profiles`),
1096
+ executor.query(`SELECT MIN(block_time) AS earliest_payment_at FROM payments`),
1097
+ executor
1098
+ .query(`SELECT pg_database_size(current_database())::text AS bytes`)
1099
+ .catch(() => ({ rows: [{ bytes: "0" }] })),
1100
+ ]);
1101
+ const lv = lvRes.rows[0] || {};
1102
+ const tr = tierRes.rows[0] || {};
1103
+ return {
1104
+ storageBackend: "postgresql",
1105
+ payments,
1106
+ profiles,
1107
+ erc8004Owners,
1108
+ capabilities,
1109
+ capabilitiesDistinctPayees: Number(capPayeesRes.rows[0]?.cnt || 0),
1110
+ liveness: {
1111
+ totalProbed: Number(lv.healthy || 0) + Number(lv.degraded_or_down || 0),
1112
+ healthy: Number(lv.healthy || 0),
1113
+ degradedOrDown: Number(lv.degraded_or_down || 0),
1114
+ deliveryReportsTotal: Number(lv.delivery_reports_total || 0),
1115
+ deliveryReportsOk: Number(lv.delivery_reports_ok || 0),
1116
+ },
1117
+ highTrustProfiles: Number(tr.high_trust || 0),
1118
+ moderateTrustProfiles: Number(tr.moderate_trust || 0),
1119
+ flaggedProfiles: Number(tr.flagged || 0),
1120
+ earliestPaymentAt: toIsoOrNull(earliestRes.rows[0]?.earliest_payment_at),
1121
+ dbSizeBytes: Number(sizeRes.rows[0]?.bytes || 0),
1122
+ };
1123
+ },
1124
+ async pruneOldPayments(retentionDays = 60) {
1125
+ const days = Math.max(1, Number(retentionDays) || 60);
1126
+ const cutoff = Math.floor(Date.now() / 1000) - days * 86400;
1127
+ const res = await executor.query(`DELETE FROM payments WHERE block_time < TO_TIMESTAMP($1)`, [cutoff]);
1128
+ return { deleted: Number(res.rowCount || 0), cutoffTimestamp: cutoff };
1129
+ },
1130
+ async close() {
1131
+ if (ownPool && typeof executor.end === "function") {
1132
+ await executor.end();
1133
+ }
1134
+ },
1135
+ };
1136
+ return repo;
1137
+ }
1138
+ //# sourceMappingURL=postgres-repo.js.map