@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.
- package/LICENSE +21 -0
- package/README.md +50 -2
- package/dist/baseline.d.ts +4 -0
- package/dist/baseline.js +152 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +28 -0
- package/dist/migrate-cli.d.ts +3 -0
- package/dist/migrate-cli.js +45 -0
- package/dist/migrate-sqlite-to-pg.d.ts +44 -0
- package/dist/migrate-sqlite-to-pg.js +339 -0
- package/dist/postgres-repo.d.ts +47 -0
- package/dist/postgres-repo.js +1138 -0
- package/dist/sqlite-repo.d.ts +32 -0
- package/dist/sqlite-repo.js +1241 -0
- package/dist/state-root-signer.d.ts +33 -0
- package/dist/state-root-signer.js +81 -0
- package/package.json +56 -4
- package/sql/001_init_v2.sql +231 -0
|
@@ -0,0 +1,1241 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { DatabaseSync } from "node:sqlite";
|
|
4
|
+
import { decimalToRawAmount, getAssetSpec, getPrimaryAsset, isVerifiedX402Channels, normalizeChainAddress, normalizeChainName, } from "@fiderail/spec";
|
|
5
|
+
import { DEFAULT_TRUST_SCORER, buildTrustStateRootCommitment, computeCreditProfilesFromPayments, } from "@fiderail/core";
|
|
6
|
+
import { signStateRootEd25519 } from "./state-root-signer.js";
|
|
7
|
+
const DANGEROUS_QUERY_CHARS_RE = /[\u0000-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g;
|
|
8
|
+
function buildSafeLikePattern(query, maxLength = 128) {
|
|
9
|
+
const cleaned = String(query || "")
|
|
10
|
+
.replace(DANGEROUS_QUERY_CHARS_RE, "")
|
|
11
|
+
.trim()
|
|
12
|
+
.toLowerCase()
|
|
13
|
+
.slice(0, maxLength);
|
|
14
|
+
if (!cleaned)
|
|
15
|
+
return null;
|
|
16
|
+
const escaped = cleaned.replace(/[\\%_]/g, (ch) => `\\${ch}`);
|
|
17
|
+
return `%${escaped}%`;
|
|
18
|
+
}
|
|
19
|
+
function isHealthyLivenessStatus(status) {
|
|
20
|
+
return status === "LIVE_402" || status === "LIVE_200" || status === "LIVE_REACHABLE";
|
|
21
|
+
}
|
|
22
|
+
function emptyChainCounts() {
|
|
23
|
+
return { base: 0, solana: 0, arbitrum: 0, polygon: 0, total: 0 };
|
|
24
|
+
}
|
|
25
|
+
function unixSecToIsoOrNull(raw) {
|
|
26
|
+
if (raw === null || raw === undefined)
|
|
27
|
+
return null;
|
|
28
|
+
const sec = Number(raw);
|
|
29
|
+
if (!Number.isFinite(sec))
|
|
30
|
+
return null;
|
|
31
|
+
return new Date(sec * 1000).toISOString();
|
|
32
|
+
}
|
|
33
|
+
function safeJsonParse(raw, fallback) {
|
|
34
|
+
if (raw === null || raw === undefined)
|
|
35
|
+
return fallback;
|
|
36
|
+
if (typeof raw !== "string")
|
|
37
|
+
return raw;
|
|
38
|
+
try {
|
|
39
|
+
return JSON.parse(raw);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return fallback;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function rowToProfile(row) {
|
|
46
|
+
const channels = safeJsonParse(row.channels_json, []);
|
|
47
|
+
const riskFlags = safeJsonParse(row.risk_flags_json, []);
|
|
48
|
+
const extraMetrics = safeJsonParse(row.metrics_json, {});
|
|
49
|
+
const dataCoverage = row.data_coverage_json
|
|
50
|
+
? safeJsonParse(row.data_coverage_json, undefined)
|
|
51
|
+
: undefined;
|
|
52
|
+
return {
|
|
53
|
+
chain: row.chain,
|
|
54
|
+
address: String(row.address),
|
|
55
|
+
creditScore: Number(row.credit_score),
|
|
56
|
+
confidence: row.confidence !== null && row.confidence !== undefined
|
|
57
|
+
? Number(row.confidence)
|
|
58
|
+
: undefined,
|
|
59
|
+
confidenceLevel: row.confidence_level || undefined,
|
|
60
|
+
riskLevel: row.risk_level || undefined,
|
|
61
|
+
tier: row.tier,
|
|
62
|
+
channels,
|
|
63
|
+
metrics: {
|
|
64
|
+
...extraMetrics,
|
|
65
|
+
txCount: Number(row.tx_count),
|
|
66
|
+
totalUsdc: Number(row.total_usdc),
|
|
67
|
+
totalUsd: Number(row.total_usdc),
|
|
68
|
+
uniquePayers: Number(row.unique_payers),
|
|
69
|
+
medianTicketUsdc: Number(row.median_ticket_usdc),
|
|
70
|
+
hhi: Number(row.hhi),
|
|
71
|
+
top1PayerShare: Number(row.top1_payer_share),
|
|
72
|
+
activeSpanHours: Number(row.active_span_hours || 0),
|
|
73
|
+
activeUtcDays: Number(row.active_utc_days || 1),
|
|
74
|
+
},
|
|
75
|
+
dataCoverage,
|
|
76
|
+
riskFlags,
|
|
77
|
+
erc8004Registered: Boolean(row.erc8004_registered),
|
|
78
|
+
firstSeenAt: row.first_seen_at || null,
|
|
79
|
+
lastSeenAt: row.last_seen_at || null,
|
|
80
|
+
sourceSnapshot: row.updated_at || null,
|
|
81
|
+
source: row.source || "sqlite_live",
|
|
82
|
+
modelVersion: row.model_version || "trust-v2",
|
|
83
|
+
modelHash: row.model_hash || undefined,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
function rowToHistoryEntry(row) {
|
|
87
|
+
return {
|
|
88
|
+
id: row.id !== undefined ? Number(row.id) : undefined,
|
|
89
|
+
chain: row.chain,
|
|
90
|
+
address: String(row.address),
|
|
91
|
+
modelVersion: String(row.model_version || "trust-v2"),
|
|
92
|
+
previousScore: row.previous_score !== null && row.previous_score !== undefined
|
|
93
|
+
? Number(row.previous_score)
|
|
94
|
+
: null,
|
|
95
|
+
currentScore: Number(row.current_score),
|
|
96
|
+
reasonCodes: safeJsonParse(row.reason_codes_json, []),
|
|
97
|
+
recordedAt: String(row.recorded_at),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function rowToStateRoot(row) {
|
|
101
|
+
return {
|
|
102
|
+
epochId: String(row.epoch_id),
|
|
103
|
+
modelVersion: String(row.model_version),
|
|
104
|
+
modelHash: String(row.model_hash),
|
|
105
|
+
merkleRoot: String(row.merkle_root),
|
|
106
|
+
leafCount: Number(row.leaf_count),
|
|
107
|
+
createdAt: String(row.created_at),
|
|
108
|
+
proofType: (row.proof_type || "ed25519"),
|
|
109
|
+
signature: row.signature ? String(row.signature) : null,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
function rowToAssociatedCredit(row) {
|
|
113
|
+
return {
|
|
114
|
+
endorsementId: String(row.endorsement_id),
|
|
115
|
+
parentChain: row.parent_chain,
|
|
116
|
+
parentAddress: String(row.parent_address),
|
|
117
|
+
childChain: row.child_chain,
|
|
118
|
+
childAddress: String(row.child_address),
|
|
119
|
+
discountFactor: Number(row.discount_factor),
|
|
120
|
+
maxEndorsedScore: Number(row.max_endorsed_score),
|
|
121
|
+
maxEndorsedSingleTxUsd: Number(row.max_endorsed_single_tx_usd),
|
|
122
|
+
ruleVersion: String(row.rule_version),
|
|
123
|
+
status: row.status,
|
|
124
|
+
issuedAt: String(row.issued_at),
|
|
125
|
+
expiresAt: String(row.expires_at),
|
|
126
|
+
proofType: (row.proof_type || "ed25519"),
|
|
127
|
+
proofPayload: row.proof_payload_json
|
|
128
|
+
? safeJsonParse(row.proof_payload_json, null)
|
|
129
|
+
: null,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
function rowToCapability(row) {
|
|
133
|
+
let tags = [];
|
|
134
|
+
try {
|
|
135
|
+
tags = JSON.parse(row.tags_json || "[]");
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
tags = [];
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
chain: row.chain,
|
|
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,
|
|
148
|
+
tags,
|
|
149
|
+
source: String(row.source),
|
|
150
|
+
lastUpdated: row.last_updated || null,
|
|
151
|
+
syncedAt: row.synced_at,
|
|
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;
|
|
160
|
+
let diagnosticFlags = [];
|
|
161
|
+
try {
|
|
162
|
+
diagnosticFlags = JSON.parse(row.diagnostic_flags_json || "[]");
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
diagnosticFlags = [];
|
|
166
|
+
}
|
|
167
|
+
return {
|
|
168
|
+
chain: row.chain,
|
|
169
|
+
address: String(row.address),
|
|
170
|
+
resourceUrl: String(row.resource_url),
|
|
171
|
+
livenessStatus: String(row.liveness_status),
|
|
172
|
+
lastHttpStatus: row.last_http_status ?? null,
|
|
173
|
+
lastLatencyMs: row.last_latency_ms ?? null,
|
|
174
|
+
probeTotal,
|
|
175
|
+
probeHealthy,
|
|
176
|
+
livenessRate: probeTotal > 0 ? Number((probeHealthy / probeTotal).toFixed(4)) : null,
|
|
177
|
+
deliveryReportsTotal: delTotal,
|
|
178
|
+
deliveryReportsOk: delOk,
|
|
179
|
+
deliverySuccessRate: delTotal > 0 ? Number((delOk / delTotal).toFixed(4)) : null,
|
|
180
|
+
headerBytes,
|
|
181
|
+
aiohttpSafe: headerBytes === null ? null : headerBytes <= 8192,
|
|
182
|
+
nodeHttpSafe: headerBytes === null ? null : headerBytes <= 16384,
|
|
183
|
+
observedPriceUsdc: row.observed_price_usdc ?? null,
|
|
184
|
+
diagnosticFlags,
|
|
185
|
+
lastError: row.last_error || null,
|
|
186
|
+
lastProbedAt: row.last_probed_at || null,
|
|
187
|
+
updatedAt: String(row.updated_at),
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Opens or initializes a SQLite WAL repository using Node's built-in `node:sqlite`.
|
|
192
|
+
* Preserves online schema upgrade compatibility with existing SQLite databases, eliminates
|
|
193
|
+
* full-table-scan single-address lookups, and streams recomputation via `stmt.iterate()`.
|
|
194
|
+
*/
|
|
195
|
+
export function openSqliteRepository(dbPath) {
|
|
196
|
+
if (!dbPath || typeof dbPath !== "string") {
|
|
197
|
+
throw new Error("A valid dbPath (or ':memory:') is required.");
|
|
198
|
+
}
|
|
199
|
+
const isMemory = dbPath === ":memory:";
|
|
200
|
+
if (!isMemory) {
|
|
201
|
+
fs.mkdirSync(path.dirname(path.resolve(dbPath)), { recursive: true });
|
|
202
|
+
}
|
|
203
|
+
const db = new DatabaseSync(dbPath);
|
|
204
|
+
db.exec(`
|
|
205
|
+
PRAGMA journal_mode = WAL;
|
|
206
|
+
PRAGMA synchronous = NORMAL;
|
|
207
|
+
PRAGMA busy_timeout = 5000;
|
|
208
|
+
PRAGMA cache_size = -64000;
|
|
209
|
+
PRAGMA temp_store = MEMORY;
|
|
210
|
+
|
|
211
|
+
CREATE TABLE IF NOT EXISTS payments (
|
|
212
|
+
chain TEXT NOT NULL,
|
|
213
|
+
tx_id TEXT NOT NULL,
|
|
214
|
+
event_index INTEGER NOT NULL DEFAULT 0,
|
|
215
|
+
asset_contract TEXT NOT NULL DEFAULT '',
|
|
216
|
+
asset_symbol TEXT NOT NULL DEFAULT 'USDC',
|
|
217
|
+
amount_raw TEXT NOT NULL DEFAULT '0',
|
|
218
|
+
amount_usd REAL NOT NULL DEFAULT 0,
|
|
219
|
+
block_number INTEGER,
|
|
220
|
+
block_time INTEGER,
|
|
221
|
+
confirmation_status TEXT NOT NULL DEFAULT 'CONFIRMED',
|
|
222
|
+
channel TEXT NOT NULL,
|
|
223
|
+
facilitator TEXT,
|
|
224
|
+
relayer TEXT,
|
|
225
|
+
payer TEXT NOT NULL,
|
|
226
|
+
payee TEXT NOT NULL,
|
|
227
|
+
amount_usdc REAL NOT NULL,
|
|
228
|
+
has_memo INTEGER NOT NULL DEFAULT 0,
|
|
229
|
+
inserted_at TEXT NOT NULL,
|
|
230
|
+
PRIMARY KEY (chain, tx_id, event_index)
|
|
231
|
+
);
|
|
232
|
+
|
|
233
|
+
CREATE INDEX IF NOT EXISTS idx_payments_chain_payee ON payments(chain, payee);
|
|
234
|
+
CREATE INDEX IF NOT EXISTS idx_payments_chain_payer ON payments(chain, payer);
|
|
235
|
+
CREATE INDEX IF NOT EXISTS idx_payments_chain_time ON payments(chain, block_time);
|
|
236
|
+
|
|
237
|
+
CREATE TABLE IF NOT EXISTS agent_profiles (
|
|
238
|
+
chain TEXT NOT NULL,
|
|
239
|
+
address TEXT NOT NULL,
|
|
240
|
+
credit_score INTEGER NOT NULL,
|
|
241
|
+
tier TEXT NOT NULL,
|
|
242
|
+
confidence REAL,
|
|
243
|
+
confidence_level TEXT,
|
|
244
|
+
risk_level TEXT,
|
|
245
|
+
model_version TEXT NOT NULL DEFAULT 'trust-v2',
|
|
246
|
+
model_hash TEXT,
|
|
247
|
+
tx_count INTEGER NOT NULL,
|
|
248
|
+
total_usdc REAL NOT NULL,
|
|
249
|
+
unique_payers INTEGER NOT NULL,
|
|
250
|
+
median_ticket_usdc REAL NOT NULL,
|
|
251
|
+
hhi REAL NOT NULL,
|
|
252
|
+
top1_payer_share REAL NOT NULL,
|
|
253
|
+
active_span_hours REAL NOT NULL DEFAULT 0,
|
|
254
|
+
active_utc_days INTEGER NOT NULL DEFAULT 1,
|
|
255
|
+
metrics_json TEXT,
|
|
256
|
+
data_coverage_json TEXT,
|
|
257
|
+
channels_json TEXT NOT NULL,
|
|
258
|
+
risk_flags_json TEXT NOT NULL,
|
|
259
|
+
has_verified_x402 INTEGER NOT NULL DEFAULT 0,
|
|
260
|
+
erc8004_registered INTEGER NOT NULL DEFAULT 0,
|
|
261
|
+
first_seen_at TEXT,
|
|
262
|
+
last_seen_at TEXT,
|
|
263
|
+
updated_at TEXT NOT NULL,
|
|
264
|
+
source TEXT NOT NULL DEFAULT 'sqlite_live',
|
|
265
|
+
PRIMARY KEY (chain, address)
|
|
266
|
+
);
|
|
267
|
+
|
|
268
|
+
CREATE INDEX IF NOT EXISTS idx_profiles_rank
|
|
269
|
+
ON agent_profiles(chain, credit_score DESC, total_usdc DESC);
|
|
270
|
+
CREATE INDEX IF NOT EXISTS idx_profiles_tier
|
|
271
|
+
ON agent_profiles(tier, credit_score DESC);
|
|
272
|
+
|
|
273
|
+
CREATE TABLE IF NOT EXISTS trust_score_history (
|
|
274
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
275
|
+
chain TEXT NOT NULL,
|
|
276
|
+
address TEXT NOT NULL,
|
|
277
|
+
model_version TEXT NOT NULL,
|
|
278
|
+
previous_score INTEGER,
|
|
279
|
+
current_score INTEGER NOT NULL,
|
|
280
|
+
reason_codes_json TEXT NOT NULL DEFAULT '[]',
|
|
281
|
+
recorded_at TEXT NOT NULL
|
|
282
|
+
);
|
|
283
|
+
|
|
284
|
+
CREATE INDEX IF NOT EXISTS idx_trust_history_addr
|
|
285
|
+
ON trust_score_history(chain, address, recorded_at DESC);
|
|
286
|
+
|
|
287
|
+
CREATE TABLE IF NOT EXISTS trust_state_roots (
|
|
288
|
+
epoch_id TEXT PRIMARY KEY,
|
|
289
|
+
chain TEXT NOT NULL,
|
|
290
|
+
model_version TEXT NOT NULL,
|
|
291
|
+
model_hash TEXT NOT NULL,
|
|
292
|
+
merkle_root TEXT NOT NULL,
|
|
293
|
+
leaf_count INTEGER NOT NULL,
|
|
294
|
+
proof_type TEXT NOT NULL DEFAULT 'ed25519',
|
|
295
|
+
signature TEXT,
|
|
296
|
+
created_at TEXT NOT NULL
|
|
297
|
+
);
|
|
298
|
+
|
|
299
|
+
CREATE INDEX IF NOT EXISTS idx_state_roots_chain_time
|
|
300
|
+
ON trust_state_roots(chain, created_at DESC);
|
|
301
|
+
|
|
302
|
+
CREATE TABLE IF NOT EXISTS associated_credit_endorsements (
|
|
303
|
+
endorsement_id TEXT PRIMARY KEY,
|
|
304
|
+
parent_chain TEXT NOT NULL,
|
|
305
|
+
parent_address TEXT NOT NULL,
|
|
306
|
+
child_chain TEXT NOT NULL,
|
|
307
|
+
child_address TEXT NOT NULL,
|
|
308
|
+
discount_factor REAL NOT NULL DEFAULT 0.7,
|
|
309
|
+
max_endorsed_score INTEGER NOT NULL DEFAULT 65,
|
|
310
|
+
max_endorsed_single_tx_usd REAL NOT NULL DEFAULT 5.0,
|
|
311
|
+
rule_version TEXT NOT NULL DEFAULT 'assoc-v1',
|
|
312
|
+
status TEXT NOT NULL DEFAULT 'ACTIVE',
|
|
313
|
+
issued_at TEXT NOT NULL,
|
|
314
|
+
expires_at TEXT NOT NULL,
|
|
315
|
+
proof_type TEXT NOT NULL DEFAULT 'ed25519',
|
|
316
|
+
proof_payload_json TEXT,
|
|
317
|
+
updated_at TEXT NOT NULL
|
|
318
|
+
);
|
|
319
|
+
|
|
320
|
+
CREATE INDEX IF NOT EXISTS idx_assoc_credit_child
|
|
321
|
+
ON associated_credit_endorsements(child_chain, child_address, status);
|
|
322
|
+
|
|
323
|
+
CREATE TABLE IF NOT EXISTS erc8004_identities (
|
|
324
|
+
chain TEXT NOT NULL,
|
|
325
|
+
owner_address TEXT NOT NULL,
|
|
326
|
+
token_id INTEGER,
|
|
327
|
+
block_number INTEGER,
|
|
328
|
+
block_time INTEGER,
|
|
329
|
+
PRIMARY KEY (chain, owner_address)
|
|
330
|
+
);
|
|
331
|
+
|
|
332
|
+
CREATE TABLE IF NOT EXISTS indexer_state (
|
|
333
|
+
key TEXT PRIMARY KEY,
|
|
334
|
+
value TEXT NOT NULL,
|
|
335
|
+
updated_at TEXT NOT NULL
|
|
336
|
+
);
|
|
337
|
+
|
|
338
|
+
CREATE TABLE IF NOT EXISTS service_capabilities (
|
|
339
|
+
chain TEXT NOT NULL,
|
|
340
|
+
address TEXT NOT NULL,
|
|
341
|
+
resource_url TEXT NOT NULL,
|
|
342
|
+
service_name TEXT,
|
|
343
|
+
description TEXT,
|
|
344
|
+
method TEXT,
|
|
345
|
+
price_usdc REAL,
|
|
346
|
+
tags_json TEXT NOT NULL DEFAULT '[]',
|
|
347
|
+
source TEXT NOT NULL,
|
|
348
|
+
last_updated TEXT,
|
|
349
|
+
synced_at TEXT NOT NULL,
|
|
350
|
+
PRIMARY KEY (chain, address, resource_url)
|
|
351
|
+
);
|
|
352
|
+
|
|
353
|
+
CREATE INDEX IF NOT EXISTS idx_caps_chain_addr
|
|
354
|
+
ON service_capabilities(chain, address);
|
|
355
|
+
|
|
356
|
+
CREATE TABLE IF NOT EXISTS service_liveness (
|
|
357
|
+
chain TEXT NOT NULL,
|
|
358
|
+
address TEXT NOT NULL,
|
|
359
|
+
resource_url TEXT NOT NULL,
|
|
360
|
+
liveness_status TEXT NOT NULL,
|
|
361
|
+
last_http_status INTEGER,
|
|
362
|
+
last_latency_ms INTEGER,
|
|
363
|
+
probe_total INTEGER NOT NULL DEFAULT 0,
|
|
364
|
+
probe_healthy INTEGER NOT NULL DEFAULT 0,
|
|
365
|
+
delivery_reports_total INTEGER NOT NULL DEFAULT 0,
|
|
366
|
+
delivery_reports_ok INTEGER NOT NULL DEFAULT 0,
|
|
367
|
+
header_bytes INTEGER,
|
|
368
|
+
observed_price_usdc REAL,
|
|
369
|
+
diagnostic_flags_json TEXT NOT NULL DEFAULT '[]',
|
|
370
|
+
last_error TEXT,
|
|
371
|
+
last_probed_at TEXT,
|
|
372
|
+
updated_at TEXT NOT NULL,
|
|
373
|
+
PRIMARY KEY (chain, address, resource_url)
|
|
374
|
+
);
|
|
375
|
+
|
|
376
|
+
CREATE INDEX IF NOT EXISTS idx_liveness_chain_addr
|
|
377
|
+
ON service_liveness(chain, address);
|
|
378
|
+
|
|
379
|
+
CREATE TABLE IF NOT EXISTS delivery_attestations (
|
|
380
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
381
|
+
chain TEXT NOT NULL,
|
|
382
|
+
address TEXT NOT NULL,
|
|
383
|
+
resource_url TEXT NOT NULL,
|
|
384
|
+
receipt_hash TEXT UNIQUE,
|
|
385
|
+
verification_tier TEXT NOT NULL DEFAULT 'L2_SIGNED_SAR_TELEMETRY',
|
|
386
|
+
delivered INTEGER NOT NULL,
|
|
387
|
+
http_status INTEGER,
|
|
388
|
+
latency_ms INTEGER,
|
|
389
|
+
receipt_json TEXT,
|
|
390
|
+
recorded_at TEXT NOT NULL
|
|
391
|
+
);
|
|
392
|
+
`);
|
|
393
|
+
// Idempotent online schema upgrade for existing SQLite databases
|
|
394
|
+
const ensureColumn = (table, colName, alterSql) => {
|
|
395
|
+
const cols = new Set(db.prepare(`PRAGMA table_info(${table})`).all().map((c) => c.name));
|
|
396
|
+
if (!cols.has(colName)) {
|
|
397
|
+
db.exec(alterSql);
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
ensureColumn("payments", "event_index", `ALTER TABLE payments ADD COLUMN event_index INTEGER NOT NULL DEFAULT 0`);
|
|
401
|
+
ensureColumn("payments", "asset_contract", `ALTER TABLE payments ADD COLUMN asset_contract TEXT NOT NULL DEFAULT ''`);
|
|
402
|
+
ensureColumn("payments", "asset_symbol", `ALTER TABLE payments ADD COLUMN asset_symbol TEXT NOT NULL DEFAULT 'USDC'`);
|
|
403
|
+
ensureColumn("payments", "amount_raw", `ALTER TABLE payments ADD COLUMN amount_raw TEXT NOT NULL DEFAULT '0'`);
|
|
404
|
+
ensureColumn("payments", "amount_usd", `ALTER TABLE payments ADD COLUMN amount_usd REAL NOT NULL DEFAULT 0`);
|
|
405
|
+
ensureColumn("payments", "confirmation_status", `ALTER TABLE payments ADD COLUMN confirmation_status TEXT NOT NULL DEFAULT 'CONFIRMED'`);
|
|
406
|
+
ensureColumn("agent_profiles", "model_version", `ALTER TABLE agent_profiles ADD COLUMN model_version TEXT NOT NULL DEFAULT 'trust-v2'`);
|
|
407
|
+
ensureColumn("agent_profiles", "model_hash", `ALTER TABLE agent_profiles ADD COLUMN model_hash TEXT`);
|
|
408
|
+
ensureColumn("agent_profiles", "confidence", `ALTER TABLE agent_profiles ADD COLUMN confidence REAL`);
|
|
409
|
+
ensureColumn("agent_profiles", "confidence_level", `ALTER TABLE agent_profiles ADD COLUMN confidence_level TEXT`);
|
|
410
|
+
ensureColumn("agent_profiles", "risk_level", `ALTER TABLE agent_profiles ADD COLUMN risk_level TEXT`);
|
|
411
|
+
ensureColumn("agent_profiles", "metrics_json", `ALTER TABLE agent_profiles ADD COLUMN metrics_json TEXT`);
|
|
412
|
+
ensureColumn("agent_profiles", "data_coverage_json", `ALTER TABLE agent_profiles ADD COLUMN data_coverage_json TEXT`);
|
|
413
|
+
ensureColumn("agent_profiles", "has_verified_x402", `ALTER TABLE agent_profiles ADD COLUMN has_verified_x402 INTEGER NOT NULL DEFAULT 0`);
|
|
414
|
+
ensureColumn("service_liveness", "header_bytes", `ALTER TABLE service_liveness ADD COLUMN header_bytes INTEGER`);
|
|
415
|
+
ensureColumn("service_liveness", "observed_price_usdc", `ALTER TABLE service_liveness ADD COLUMN observed_price_usdc REAL`);
|
|
416
|
+
ensureColumn("service_liveness", "diagnostic_flags_json", `ALTER TABLE service_liveness ADD COLUMN diagnostic_flags_json TEXT NOT NULL DEFAULT '[]'`);
|
|
417
|
+
function runInTransaction(fn) {
|
|
418
|
+
db.exec("BEGIN IMMEDIATE");
|
|
419
|
+
try {
|
|
420
|
+
const result = fn();
|
|
421
|
+
db.exec("COMMIT");
|
|
422
|
+
return result;
|
|
423
|
+
}
|
|
424
|
+
catch (err) {
|
|
425
|
+
try {
|
|
426
|
+
db.exec("ROLLBACK");
|
|
427
|
+
}
|
|
428
|
+
catch {
|
|
429
|
+
// ignore rollback error
|
|
430
|
+
}
|
|
431
|
+
throw err;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
const stmtInsertPayment = db.prepare(`
|
|
435
|
+
INSERT OR IGNORE INTO payments (
|
|
436
|
+
chain, tx_id, event_index, asset_contract, asset_symbol, amount_raw, amount_usd,
|
|
437
|
+
block_number, block_time, confirmation_status, channel,
|
|
438
|
+
facilitator, relayer, payer, payee, amount_usdc, has_memo, inserted_at
|
|
439
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
440
|
+
`);
|
|
441
|
+
const stmtUpsertIdentity = db.prepare(`
|
|
442
|
+
INSERT OR REPLACE INTO erc8004_identities (
|
|
443
|
+
chain, owner_address, token_id, block_number, block_time
|
|
444
|
+
) VALUES (?, ?, ?, ?, ?)
|
|
445
|
+
`);
|
|
446
|
+
const stmtSelectPaymentsByChain = db.prepare(`
|
|
447
|
+
SELECT payer, payee,
|
|
448
|
+
CASE WHEN amount_usd > 0 THEN amount_usd ELSE amount_usdc END AS amount_usdc,
|
|
449
|
+
block_time, channel
|
|
450
|
+
FROM payments
|
|
451
|
+
WHERE chain = ? AND COALESCE(confirmation_status, 'CONFIRMED') != 'REORGED'
|
|
452
|
+
`);
|
|
453
|
+
const stmtSelectIdentitiesByChain = db.prepare(`
|
|
454
|
+
SELECT owner_address FROM erc8004_identities WHERE chain = ?
|
|
455
|
+
`);
|
|
456
|
+
const stmtSelectOldScores = db.prepare(`
|
|
457
|
+
SELECT address, credit_score, risk_flags_json FROM agent_profiles WHERE chain = ?
|
|
458
|
+
`);
|
|
459
|
+
const stmtUpsertProfile = db.prepare(`
|
|
460
|
+
INSERT INTO agent_profiles (
|
|
461
|
+
chain, address, credit_score, tier, confidence, confidence_level, risk_level,
|
|
462
|
+
model_version, model_hash,
|
|
463
|
+
tx_count, total_usdc, unique_payers, median_ticket_usdc, hhi, top1_payer_share,
|
|
464
|
+
active_span_hours, active_utc_days, metrics_json, data_coverage_json,
|
|
465
|
+
channels_json, risk_flags_json,
|
|
466
|
+
has_verified_x402, erc8004_registered, first_seen_at, last_seen_at, updated_at, source
|
|
467
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
468
|
+
ON CONFLICT (chain, address) DO UPDATE SET
|
|
469
|
+
credit_score = excluded.credit_score,
|
|
470
|
+
tier = excluded.tier,
|
|
471
|
+
confidence = excluded.confidence,
|
|
472
|
+
confidence_level = excluded.confidence_level,
|
|
473
|
+
risk_level = excluded.risk_level,
|
|
474
|
+
model_version = excluded.model_version,
|
|
475
|
+
model_hash = excluded.model_hash,
|
|
476
|
+
tx_count = excluded.tx_count,
|
|
477
|
+
total_usdc = excluded.total_usdc,
|
|
478
|
+
unique_payers = excluded.unique_payers,
|
|
479
|
+
median_ticket_usdc = excluded.median_ticket_usdc,
|
|
480
|
+
hhi = excluded.hhi,
|
|
481
|
+
top1_payer_share = excluded.top1_payer_share,
|
|
482
|
+
active_span_hours = excluded.active_span_hours,
|
|
483
|
+
active_utc_days = excluded.active_utc_days,
|
|
484
|
+
metrics_json = excluded.metrics_json,
|
|
485
|
+
data_coverage_json = excluded.data_coverage_json,
|
|
486
|
+
channels_json = excluded.channels_json,
|
|
487
|
+
risk_flags_json = excluded.risk_flags_json,
|
|
488
|
+
has_verified_x402 = excluded.has_verified_x402,
|
|
489
|
+
erc8004_registered = excluded.erc8004_registered,
|
|
490
|
+
first_seen_at = excluded.first_seen_at,
|
|
491
|
+
last_seen_at = excluded.last_seen_at,
|
|
492
|
+
updated_at = excluded.updated_at,
|
|
493
|
+
source = excluded.source
|
|
494
|
+
`);
|
|
495
|
+
const stmtInsertScoreHistory = db.prepare(`
|
|
496
|
+
INSERT INTO trust_score_history (
|
|
497
|
+
chain, address, model_version, previous_score, current_score, reason_codes_json, recorded_at
|
|
498
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
499
|
+
`);
|
|
500
|
+
const stmtGetScoreHistory = db.prepare(`
|
|
501
|
+
SELECT * FROM trust_score_history
|
|
502
|
+
WHERE chain = ? AND address = ?
|
|
503
|
+
ORDER BY recorded_at DESC, id DESC
|
|
504
|
+
LIMIT ?
|
|
505
|
+
`);
|
|
506
|
+
const stmtInsertStateRoot = db.prepare(`
|
|
507
|
+
INSERT OR REPLACE INTO trust_state_roots (
|
|
508
|
+
epoch_id, chain, model_version, model_hash, merkle_root, leaf_count, proof_type, signature, created_at
|
|
509
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
510
|
+
`);
|
|
511
|
+
const stmtGetLatestStateRoot = db.prepare(`
|
|
512
|
+
SELECT * FROM trust_state_roots
|
|
513
|
+
WHERE chain = ?
|
|
514
|
+
ORDER BY created_at DESC, epoch_id DESC
|
|
515
|
+
LIMIT 1
|
|
516
|
+
`);
|
|
517
|
+
const stmtUpsertAssociatedCredit = db.prepare(`
|
|
518
|
+
INSERT INTO associated_credit_endorsements (
|
|
519
|
+
endorsement_id, parent_chain, parent_address, child_chain, child_address,
|
|
520
|
+
discount_factor, max_endorsed_score, max_endorsed_single_tx_usd,
|
|
521
|
+
rule_version, status, issued_at, expires_at, proof_type, proof_payload_json, updated_at
|
|
522
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
523
|
+
ON CONFLICT (endorsement_id) DO UPDATE SET
|
|
524
|
+
parent_chain = excluded.parent_chain,
|
|
525
|
+
parent_address = excluded.parent_address,
|
|
526
|
+
child_chain = excluded.child_chain,
|
|
527
|
+
child_address = excluded.child_address,
|
|
528
|
+
discount_factor = excluded.discount_factor,
|
|
529
|
+
max_endorsed_score = excluded.max_endorsed_score,
|
|
530
|
+
max_endorsed_single_tx_usd = excluded.max_endorsed_single_tx_usd,
|
|
531
|
+
rule_version = excluded.rule_version,
|
|
532
|
+
status = excluded.status,
|
|
533
|
+
issued_at = excluded.issued_at,
|
|
534
|
+
expires_at = excluded.expires_at,
|
|
535
|
+
proof_type = excluded.proof_type,
|
|
536
|
+
proof_payload_json = excluded.proof_payload_json,
|
|
537
|
+
updated_at = excluded.updated_at
|
|
538
|
+
`);
|
|
539
|
+
const stmtRevokeAssociatedCredit = db.prepare(`
|
|
540
|
+
UPDATE associated_credit_endorsements
|
|
541
|
+
SET status = 'REVOKED', updated_at = ?
|
|
542
|
+
WHERE endorsement_id = ?
|
|
543
|
+
`);
|
|
544
|
+
const stmtGetAssociatedCreditForChild = db.prepare(`
|
|
545
|
+
SELECT * FROM associated_credit_endorsements
|
|
546
|
+
WHERE child_chain = ? AND child_address = ?
|
|
547
|
+
ORDER BY CASE WHEN status = 'ACTIVE' THEN 0 ELSE 1 END ASC, updated_at DESC
|
|
548
|
+
LIMIT 1
|
|
549
|
+
`);
|
|
550
|
+
const stmtGetProfile = db.prepare(`SELECT * FROM agent_profiles WHERE chain = ? AND address = ?`);
|
|
551
|
+
const stmtListChainProfiles = db.prepare(`
|
|
552
|
+
SELECT * FROM agent_profiles
|
|
553
|
+
WHERE chain = ?
|
|
554
|
+
ORDER BY address ASC
|
|
555
|
+
`);
|
|
556
|
+
const stmtGetPayerActivity = db.prepare(`
|
|
557
|
+
SELECT
|
|
558
|
+
COUNT(*) AS tx_count,
|
|
559
|
+
COUNT(DISTINCT CASE WHEN payee != payer THEN payee END) AS distinct_payees,
|
|
560
|
+
COALESCE(SUM(CASE WHEN amount_usd > 0 THEN amount_usd ELSE amount_usdc END), 0) AS total_usd,
|
|
561
|
+
MIN(block_time) AS first_block_time,
|
|
562
|
+
MAX(block_time) AS last_block_time,
|
|
563
|
+
COUNT(DISTINCT CASE WHEN block_time IS NOT NULL THEN date(block_time, 'unixepoch') END) AS active_utc_days,
|
|
564
|
+
MAX(CASE WHEN payee = payer THEN 1 ELSE 0 END) AS has_self_transfer
|
|
565
|
+
FROM payments
|
|
566
|
+
WHERE chain = ? AND payer = ? AND COALESCE(confirmation_status, 'CONFIRMED') != 'REORGED'
|
|
567
|
+
`);
|
|
568
|
+
const stmtHasReciprocalPayment = db.prepare(`
|
|
569
|
+
SELECT 1 AS hit
|
|
570
|
+
FROM payments p_in
|
|
571
|
+
WHERE p_in.chain = ?
|
|
572
|
+
AND p_in.payee = ?
|
|
573
|
+
AND p_in.payer != ?
|
|
574
|
+
AND COALESCE(p_in.confirmation_status, 'CONFIRMED') != 'REORGED'
|
|
575
|
+
AND EXISTS (
|
|
576
|
+
SELECT 1
|
|
577
|
+
FROM payments p_out
|
|
578
|
+
WHERE p_out.chain = p_in.chain
|
|
579
|
+
AND p_out.payer = ?
|
|
580
|
+
AND p_out.payee = p_in.payer
|
|
581
|
+
AND COALESCE(p_out.confirmation_status, 'CONFIRMED') != 'REORGED'
|
|
582
|
+
)
|
|
583
|
+
LIMIT 1
|
|
584
|
+
`);
|
|
585
|
+
const stmtSetState = db.prepare(`INSERT OR REPLACE INTO indexer_state (key, value, updated_at) VALUES (?, ?, ?)`);
|
|
586
|
+
const stmtGetAllState = db.prepare(`SELECT key, value, updated_at FROM indexer_state`);
|
|
587
|
+
const stmtPrunePayments = db.prepare(`DELETE FROM payments WHERE block_time IS NOT NULL AND block_time < ?`);
|
|
588
|
+
const stmtUpsertCapability = db.prepare(`
|
|
589
|
+
INSERT OR REPLACE INTO service_capabilities (
|
|
590
|
+
chain, address, resource_url, service_name, description, method,
|
|
591
|
+
price_usdc, tags_json, source, last_updated, synced_at
|
|
592
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
593
|
+
`);
|
|
594
|
+
const stmtGetCapabilitiesForAddress = db.prepare(`
|
|
595
|
+
SELECT * FROM service_capabilities
|
|
596
|
+
WHERE chain = ? AND address = ?
|
|
597
|
+
ORDER BY COALESCE(last_updated, '') DESC, synced_at DESC
|
|
598
|
+
LIMIT 10
|
|
599
|
+
`);
|
|
600
|
+
const stmtGetLivenessForAddress = db.prepare(`
|
|
601
|
+
SELECT * FROM service_liveness WHERE chain = ? AND address = ?
|
|
602
|
+
`);
|
|
603
|
+
const stmtGetAddressLivenessSummary = db.prepare(`
|
|
604
|
+
SELECT
|
|
605
|
+
SUM(CASE WHEN probe_total > 0 THEN 1 ELSE 0 END) AS probed_endpoints,
|
|
606
|
+
SUM(CASE WHEN probe_total > 0 AND liveness_status IN ('LIVE_402', 'LIVE_200', 'LIVE_REACHABLE') THEN 1 ELSE 0 END) AS healthy_endpoints,
|
|
607
|
+
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,
|
|
608
|
+
AVG(CASE WHEN last_latency_ms IS NOT NULL THEN last_latency_ms END) AS avg_latency_ms,
|
|
609
|
+
COALESCE(SUM(delivery_reports_total), 0) AS delivery_reports_total,
|
|
610
|
+
COALESCE(SUM(delivery_reports_ok), 0) AS delivery_reports_ok
|
|
611
|
+
FROM service_liveness
|
|
612
|
+
WHERE chain = ? AND address = ?
|
|
613
|
+
`);
|
|
614
|
+
const stmtUpsertLivenessProbe = db.prepare(`
|
|
615
|
+
INSERT INTO service_liveness (
|
|
616
|
+
chain, address, resource_url, liveness_status, last_http_status, last_latency_ms,
|
|
617
|
+
probe_total, probe_healthy, delivery_reports_total, delivery_reports_ok,
|
|
618
|
+
header_bytes, observed_price_usdc, diagnostic_flags_json,
|
|
619
|
+
last_error, last_probed_at, updated_at
|
|
620
|
+
) VALUES (?, ?, ?, ?, ?, ?, 1, ?, 0, 0, ?, ?, ?, ?, ?, ?)
|
|
621
|
+
ON CONFLICT (chain, address, resource_url) DO UPDATE SET
|
|
622
|
+
liveness_status = excluded.liveness_status,
|
|
623
|
+
last_http_status = excluded.last_http_status,
|
|
624
|
+
last_latency_ms = excluded.last_latency_ms,
|
|
625
|
+
probe_total = service_liveness.probe_total + 1,
|
|
626
|
+
probe_healthy = service_liveness.probe_healthy + excluded.probe_healthy,
|
|
627
|
+
header_bytes = COALESCE(excluded.header_bytes, service_liveness.header_bytes),
|
|
628
|
+
observed_price_usdc = COALESCE(excluded.observed_price_usdc, service_liveness.observed_price_usdc),
|
|
629
|
+
diagnostic_flags_json = excluded.diagnostic_flags_json,
|
|
630
|
+
last_error = excluded.last_error,
|
|
631
|
+
last_probed_at = excluded.last_probed_at,
|
|
632
|
+
updated_at = excluded.updated_at
|
|
633
|
+
`);
|
|
634
|
+
const stmtUpsertDeliveryTelemetry = db.prepare(`
|
|
635
|
+
INSERT INTO service_liveness (
|
|
636
|
+
chain, address, resource_url, liveness_status, last_http_status, last_latency_ms,
|
|
637
|
+
probe_total, probe_healthy, delivery_reports_total, delivery_reports_ok,
|
|
638
|
+
header_bytes, observed_price_usdc, diagnostic_flags_json,
|
|
639
|
+
last_error, last_probed_at, updated_at
|
|
640
|
+
) VALUES (?, ?, ?, ?, ?, ?, 0, 0, 1, ?, NULL, NULL, '[]', NULL, NULL, ?)
|
|
641
|
+
ON CONFLICT (chain, address, resource_url) DO UPDATE SET
|
|
642
|
+
last_http_status = COALESCE(excluded.last_http_status, service_liveness.last_http_status),
|
|
643
|
+
last_latency_ms = COALESCE(excluded.last_latency_ms, service_liveness.last_latency_ms),
|
|
644
|
+
delivery_reports_total = service_liveness.delivery_reports_total + 1,
|
|
645
|
+
delivery_reports_ok = service_liveness.delivery_reports_ok + excluded.delivery_reports_ok,
|
|
646
|
+
updated_at = excluded.updated_at
|
|
647
|
+
`);
|
|
648
|
+
const stmtInsertAttestation = db.prepare(`
|
|
649
|
+
INSERT OR IGNORE INTO delivery_attestations (
|
|
650
|
+
chain, address, resource_url, receipt_hash, verification_tier,
|
|
651
|
+
delivered, http_status, latency_ms, receipt_json, recorded_at
|
|
652
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
653
|
+
`);
|
|
654
|
+
function countByChain(table) {
|
|
655
|
+
const rows = db.prepare(`SELECT chain, COUNT(*) AS cnt FROM ${table} GROUP BY chain`).all();
|
|
656
|
+
const map = emptyChainCounts();
|
|
657
|
+
for (const r of rows) {
|
|
658
|
+
if (r.chain === "base" || r.chain === "solana" || r.chain === "arbitrum" || r.chain === "polygon") {
|
|
659
|
+
map[r.chain] = Number(r.cnt);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
map.total = map.base + map.solana + map.arbitrum + map.polygon;
|
|
663
|
+
return map;
|
|
664
|
+
}
|
|
665
|
+
return {
|
|
666
|
+
backend: "sqlite",
|
|
667
|
+
dbPath,
|
|
668
|
+
rawDb: db,
|
|
669
|
+
async insertPayments(rows) {
|
|
670
|
+
if (!rows || rows.length === 0)
|
|
671
|
+
return { inserted: 0 };
|
|
672
|
+
const nowIso = new Date().toISOString();
|
|
673
|
+
return runInTransaction(() => {
|
|
674
|
+
let inserted = 0;
|
|
675
|
+
for (const r of rows) {
|
|
676
|
+
const chain = normalizeChainName(r.chain);
|
|
677
|
+
if (!chain || !r.txId)
|
|
678
|
+
continue;
|
|
679
|
+
const payer = normalizeChainAddress(chain, r.payer);
|
|
680
|
+
const payee = normalizeChainAddress(chain, r.payee);
|
|
681
|
+
const amountUsd = Number(r.amountUsd ?? r.amountUsdc ?? r.amount_usdc ?? 0);
|
|
682
|
+
if (!payer || !payee || !Number.isFinite(amountUsd) || amountUsd <= 0)
|
|
683
|
+
continue;
|
|
684
|
+
const primary = getPrimaryAsset(chain);
|
|
685
|
+
const matchedAsset = getAssetSpec(chain, r.assetContract || r.assetSymbol) || primary;
|
|
686
|
+
const amountRaw = r.amountRaw || decimalToRawAmount(amountUsd, matchedAsset.decimals);
|
|
687
|
+
const eventIndex = Number.isInteger(r.eventIndex) ? Number(r.eventIndex) : 0;
|
|
688
|
+
const info = stmtInsertPayment.run(chain, String(r.txId), eventIndex, matchedAsset.contract, matchedAsset.symbol, amountRaw, amountUsd, r.blockNumber ?? null, r.blockTime ?? r.block_time ?? null, r.confirmationStatus || "CONFIRMED", String(r.channel || `${chain}_x402`), r.facilitator ?? null, r.relayer ? normalizeChainAddress(chain, r.relayer) : null, payer, payee, amountUsd, r.hasMemo ? 1 : 0, nowIso);
|
|
689
|
+
inserted += Number(info.changes || 0);
|
|
690
|
+
}
|
|
691
|
+
return { inserted };
|
|
692
|
+
});
|
|
693
|
+
},
|
|
694
|
+
async upsertErc8004Owners(rows) {
|
|
695
|
+
if (!rows || rows.length === 0)
|
|
696
|
+
return { upserted: 0 };
|
|
697
|
+
return runInTransaction(() => {
|
|
698
|
+
let upserted = 0;
|
|
699
|
+
for (const r of rows) {
|
|
700
|
+
const chain = normalizeChainName(r.chain);
|
|
701
|
+
if (!chain)
|
|
702
|
+
continue;
|
|
703
|
+
const owner = normalizeChainAddress(chain, r.ownerAddress);
|
|
704
|
+
if (!owner)
|
|
705
|
+
continue;
|
|
706
|
+
stmtUpsertIdentity.run(chain, owner, r.tokenId ?? null, r.blockNumber ?? null, r.blockTime ?? null);
|
|
707
|
+
upserted += 1;
|
|
708
|
+
}
|
|
709
|
+
return { upserted };
|
|
710
|
+
});
|
|
711
|
+
},
|
|
712
|
+
async upsertServiceCapabilities(rows) {
|
|
713
|
+
if (!rows || rows.length === 0)
|
|
714
|
+
return { upserted: 0 };
|
|
715
|
+
const nowIso = new Date().toISOString();
|
|
716
|
+
return runInTransaction(() => {
|
|
717
|
+
let upserted = 0;
|
|
718
|
+
for (const r of rows) {
|
|
719
|
+
const chain = normalizeChainName(r.chain);
|
|
720
|
+
if (!chain)
|
|
721
|
+
continue;
|
|
722
|
+
const address = normalizeChainAddress(chain, r.address);
|
|
723
|
+
const resourceUrl = String(r.resourceUrl || "").trim();
|
|
724
|
+
if (!address || !resourceUrl)
|
|
725
|
+
continue;
|
|
726
|
+
const priceUsdc = r.priceUsdc !== null &&
|
|
727
|
+
r.priceUsdc !== undefined &&
|
|
728
|
+
Number.isFinite(Number(r.priceUsdc))
|
|
729
|
+
? Number(r.priceUsdc)
|
|
730
|
+
: null;
|
|
731
|
+
stmtUpsertCapability.run(chain, address, resourceUrl, r.serviceName ? String(r.serviceName).slice(0, 160) : null, r.description ? String(r.description).slice(0, 600) : null, r.method ? String(r.method).toUpperCase().slice(0, 16) : null, priceUsdc, JSON.stringify(Array.isArray(r.tags) ? r.tags.slice(0, 16) : []), String(r.source || "x402_bazaar"), r.lastUpdated ? String(r.lastUpdated) : null, nowIso);
|
|
732
|
+
upserted += 1;
|
|
733
|
+
}
|
|
734
|
+
return { upserted };
|
|
735
|
+
});
|
|
736
|
+
},
|
|
737
|
+
async registerOpenBazaarService(item) {
|
|
738
|
+
if (!item || typeof item !== "object") {
|
|
739
|
+
throw new Error("A service registration payload is required.");
|
|
740
|
+
}
|
|
741
|
+
const chain = normalizeChainName(item.chain);
|
|
742
|
+
if (!chain)
|
|
743
|
+
throw new Error(`Unsupported chain "${item.chain}"`);
|
|
744
|
+
const { upserted } = await this.upsertServiceCapabilities([
|
|
745
|
+
{
|
|
746
|
+
chain,
|
|
747
|
+
address: item.address,
|
|
748
|
+
resourceUrl: item.resourceUrl,
|
|
749
|
+
serviceName: item.serviceName ?? null,
|
|
750
|
+
description: item.description ?? null,
|
|
751
|
+
method: item.method ?? null,
|
|
752
|
+
priceUsdc: item.priceUsdc ?? null,
|
|
753
|
+
tags: item.tags ?? [],
|
|
754
|
+
source: item.source || "open_bazaar_self_submit",
|
|
755
|
+
lastUpdated: item.lastUpdated || new Date().toISOString(),
|
|
756
|
+
},
|
|
757
|
+
]);
|
|
758
|
+
if (upserted > 0 && item.livenessStatus) {
|
|
759
|
+
await this.recordLivenessProbe({
|
|
760
|
+
chain,
|
|
761
|
+
address: item.address,
|
|
762
|
+
resourceUrl: item.resourceUrl,
|
|
763
|
+
livenessStatus: item.livenessStatus,
|
|
764
|
+
httpStatus: item.httpStatus ?? null,
|
|
765
|
+
latencyMs: item.latencyMs ?? null,
|
|
766
|
+
headerBytes: item.headerBytes ?? null,
|
|
767
|
+
observedPriceUsdc: item.observedPriceUsdc ?? item.priceUsdc ?? null,
|
|
768
|
+
diagnosticFlags: item.diagnosticFlags ?? [],
|
|
769
|
+
error: item.error ?? null,
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
return { upserted };
|
|
773
|
+
},
|
|
774
|
+
async getCapabilitiesForAddress(chainInput, addressInput) {
|
|
775
|
+
const chain = normalizeChainName(chainInput);
|
|
776
|
+
if (!chain)
|
|
777
|
+
return [];
|
|
778
|
+
const address = normalizeChainAddress(chain, addressInput);
|
|
779
|
+
if (!address)
|
|
780
|
+
return [];
|
|
781
|
+
return stmtGetCapabilitiesForAddress.all(chain, address).map(rowToCapability);
|
|
782
|
+
},
|
|
783
|
+
async getCapabilitiesSummaryForAddresses(keys) {
|
|
784
|
+
const out = new Map();
|
|
785
|
+
if (!keys || keys.length === 0)
|
|
786
|
+
return out;
|
|
787
|
+
for (const { chain, address } of keys) {
|
|
788
|
+
const normAddr = normalizeChainAddress(chain, address);
|
|
789
|
+
const rows = stmtGetCapabilitiesForAddress.all(chain, normAddr);
|
|
790
|
+
if (rows.length === 0)
|
|
791
|
+
continue;
|
|
792
|
+
const caps = rows.map(rowToCapability);
|
|
793
|
+
const tags = new Set();
|
|
794
|
+
const sources = new Set();
|
|
795
|
+
let minPriceUsdc = null;
|
|
796
|
+
for (const c of caps) {
|
|
797
|
+
if (c.priceUsdc !== null && (minPriceUsdc === null || c.priceUsdc < minPriceUsdc)) {
|
|
798
|
+
minPriceUsdc = c.priceUsdc;
|
|
799
|
+
}
|
|
800
|
+
for (const t of c.tags)
|
|
801
|
+
tags.add(t);
|
|
802
|
+
if (c.source)
|
|
803
|
+
sources.add(c.source);
|
|
804
|
+
}
|
|
805
|
+
out.set(`${chain}:${normAddr}`, {
|
|
806
|
+
serviceCount: caps.length,
|
|
807
|
+
primaryServiceName: caps.find((c) => c.serviceName)?.serviceName || null,
|
|
808
|
+
primaryDescription: caps.find((c) => c.description)?.description || null,
|
|
809
|
+
primaryResourceUrl: caps[0].resourceUrl,
|
|
810
|
+
minPriceUsdc,
|
|
811
|
+
tags: [...tags].slice(0, 8),
|
|
812
|
+
sources: [...sources],
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
return out;
|
|
816
|
+
},
|
|
817
|
+
async searchCapabilities({ query = "", chain = "all", maxPriceUsdc = null, limit = 50 } = {}) {
|
|
818
|
+
const where = ["1 = 1"];
|
|
819
|
+
const params = [];
|
|
820
|
+
if (chain !== "all") {
|
|
821
|
+
const norm = normalizeChainName(chain);
|
|
822
|
+
if (!norm) {
|
|
823
|
+
throw new Error(`Unsupported chain filter "${chain}".`);
|
|
824
|
+
}
|
|
825
|
+
where.push("chain = ?");
|
|
826
|
+
params.push(norm);
|
|
827
|
+
}
|
|
828
|
+
if (maxPriceUsdc !== null && maxPriceUsdc !== undefined) {
|
|
829
|
+
const maxP = Number(maxPriceUsdc);
|
|
830
|
+
if (Number.isFinite(maxP) && maxP >= 0) {
|
|
831
|
+
where.push("(price_usdc IS NULL OR price_usdc <= ?)");
|
|
832
|
+
params.push(maxP);
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
const likePattern = buildSafeLikePattern(query);
|
|
836
|
+
if (likePattern) {
|
|
837
|
+
where.push("LOWER(COALESCE(service_name, '') || ' ' || COALESCE(description, '') || ' ' || resource_url || ' ' || tags_json || ' ' || address) LIKE ? ESCAPE '\\'");
|
|
838
|
+
params.push(likePattern);
|
|
839
|
+
}
|
|
840
|
+
const clampedLimit = Math.max(1, Math.min(500, Number(limit) || 50));
|
|
841
|
+
const rows = db
|
|
842
|
+
.prepare(`SELECT * FROM service_capabilities WHERE ${where.join(" AND ")} ORDER BY COALESCE(last_updated, '') DESC, synced_at DESC LIMIT ?`)
|
|
843
|
+
.all(...params, clampedLimit);
|
|
844
|
+
return rows.map(rowToCapability);
|
|
845
|
+
},
|
|
846
|
+
async recordLivenessProbe(input) {
|
|
847
|
+
const chain = normalizeChainName(input.chain);
|
|
848
|
+
if (!chain)
|
|
849
|
+
throw new Error(`Unsupported chain "${input.chain}"`);
|
|
850
|
+
const address = normalizeChainAddress(chain, input.address);
|
|
851
|
+
const url = String(input.resourceUrl || "").trim();
|
|
852
|
+
if (!address || !url)
|
|
853
|
+
throw new Error("address and resourceUrl are required.");
|
|
854
|
+
const nowIso = new Date().toISOString();
|
|
855
|
+
const healthyInc = isHealthyLivenessStatus(input.livenessStatus) ? 1 : 0;
|
|
856
|
+
const normFlags = Array.isArray(input.diagnosticFlags)
|
|
857
|
+
? input.diagnosticFlags.map((f) => String(f)).slice(0, 24)
|
|
858
|
+
: [];
|
|
859
|
+
stmtUpsertLivenessProbe.run(chain, address, url, String(input.livenessStatus), input.httpStatus !== null && input.httpStatus !== undefined ? Number(input.httpStatus) : null, input.latencyMs !== null && input.latencyMs !== undefined ? Math.round(Number(input.latencyMs)) : null, healthyInc, input.headerBytes !== null && input.headerBytes !== undefined
|
|
860
|
+
? Math.max(0, Math.round(Number(input.headerBytes)))
|
|
861
|
+
: null, input.observedPriceUsdc !== null &&
|
|
862
|
+
input.observedPriceUsdc !== undefined &&
|
|
863
|
+
Number.isFinite(Number(input.observedPriceUsdc))
|
|
864
|
+
? Number(input.observedPriceUsdc)
|
|
865
|
+
: null, JSON.stringify(normFlags), input.error ? String(input.error).slice(0, 240) : null, nowIso, nowIso);
|
|
866
|
+
},
|
|
867
|
+
async recordDeliveryTelemetry(input) {
|
|
868
|
+
const chain = normalizeChainName(input.chain);
|
|
869
|
+
if (!chain)
|
|
870
|
+
throw new Error(`Unsupported chain "${input.chain}"`);
|
|
871
|
+
const address = normalizeChainAddress(chain, input.address);
|
|
872
|
+
const url = String(input.resourceUrl || "").trim();
|
|
873
|
+
if (!address || !url)
|
|
874
|
+
throw new Error("address and resourceUrl are required.");
|
|
875
|
+
const okInc = input.delivered ? 1 : 0;
|
|
876
|
+
const nowIso = new Date().toISOString();
|
|
877
|
+
const initialStatus = input.delivered ? "LIVE_200" : "DEGRADED";
|
|
878
|
+
return runInTransaction(() => {
|
|
879
|
+
let duplicate = false;
|
|
880
|
+
if (input.receipt) {
|
|
881
|
+
const recObj = input.receipt;
|
|
882
|
+
const receiptHash = typeof recObj.receiptHash === "string"
|
|
883
|
+
? recObj.receiptHash
|
|
884
|
+
: typeof recObj.quoteDigest === "string"
|
|
885
|
+
? recObj.quoteDigest
|
|
886
|
+
: null;
|
|
887
|
+
const attInfo = stmtInsertAttestation.run(chain, address, url, receiptHash, input.verificationTier || "L2_SIGNED_SAR_TELEMETRY", okInc, input.httpStatus ?? null, input.latencyMs !== null && input.latencyMs !== undefined
|
|
888
|
+
? Math.round(Number(input.latencyMs))
|
|
889
|
+
: null, JSON.stringify(input.receipt), nowIso);
|
|
890
|
+
if (receiptHash && Number(attInfo.changes || 0) === 0) {
|
|
891
|
+
duplicate = true;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
if (!duplicate) {
|
|
895
|
+
stmtUpsertDeliveryTelemetry.run(chain, address, url, initialStatus, input.httpStatus !== null && input.httpStatus !== undefined
|
|
896
|
+
? Number(input.httpStatus)
|
|
897
|
+
: null, input.latencyMs !== null && input.latencyMs !== undefined
|
|
898
|
+
? Math.round(Number(input.latencyMs))
|
|
899
|
+
: null, okInc, nowIso);
|
|
900
|
+
}
|
|
901
|
+
return { duplicate };
|
|
902
|
+
});
|
|
903
|
+
},
|
|
904
|
+
async getLivenessForAddress(chainInput, addressInput) {
|
|
905
|
+
const map = new Map();
|
|
906
|
+
const chain = normalizeChainName(chainInput);
|
|
907
|
+
if (!chain)
|
|
908
|
+
return map;
|
|
909
|
+
const address = normalizeChainAddress(chain, addressInput);
|
|
910
|
+
const rows = stmtGetLivenessForAddress.all(chain, address);
|
|
911
|
+
for (const r of rows) {
|
|
912
|
+
const item = rowToLiveness(r);
|
|
913
|
+
map.set(item.resourceUrl, item);
|
|
914
|
+
}
|
|
915
|
+
return map;
|
|
916
|
+
},
|
|
917
|
+
async getAddressLivenessSummary(chainInput, addressInput) {
|
|
918
|
+
const chain = normalizeChainName(chainInput);
|
|
919
|
+
if (!chain)
|
|
920
|
+
return null;
|
|
921
|
+
const address = normalizeChainAddress(chain, addressInput);
|
|
922
|
+
const row = stmtGetAddressLivenessSummary.get(chain, address);
|
|
923
|
+
if (!row)
|
|
924
|
+
return null;
|
|
925
|
+
const probed = Number(row.probed_endpoints || 0);
|
|
926
|
+
const delTotal = Number(row.delivery_reports_total || 0);
|
|
927
|
+
if (probed === 0 && delTotal === 0)
|
|
928
|
+
return null;
|
|
929
|
+
const delOk = Number(row.delivery_reports_ok || 0);
|
|
930
|
+
return {
|
|
931
|
+
probedEndpoints: probed,
|
|
932
|
+
healthyEndpoints: Number(row.healthy_endpoints || 0),
|
|
933
|
+
downEndpoints: Number(row.down_endpoints || 0),
|
|
934
|
+
avgLatencyMs: row.avg_latency_ms !== null && row.avg_latency_ms !== undefined ? Math.round(Number(row.avg_latency_ms)) : null,
|
|
935
|
+
deliveryReportsTotal: delTotal,
|
|
936
|
+
deliverySuccessRate: delTotal > 0 ? Number((delOk / delTotal).toFixed(4)) : null,
|
|
937
|
+
};
|
|
938
|
+
},
|
|
939
|
+
async getLivenessForResources(keys) {
|
|
940
|
+
const out = new Map();
|
|
941
|
+
if (!keys || keys.length === 0)
|
|
942
|
+
return out;
|
|
943
|
+
const stmt = db.prepare(`SELECT * FROM service_liveness WHERE chain = ? AND address = ? AND resource_url = ?`);
|
|
944
|
+
for (const k of keys) {
|
|
945
|
+
const addr = normalizeChainAddress(k.chain, k.address);
|
|
946
|
+
const row = stmt.get(k.chain, addr, k.resourceUrl);
|
|
947
|
+
if (row) {
|
|
948
|
+
out.set(`${k.chain}:${addr}:${k.resourceUrl}`, rowToLiveness(row));
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
return out;
|
|
952
|
+
},
|
|
953
|
+
async getAddressLivenessSummariesForAddresses(keys) {
|
|
954
|
+
const out = new Map();
|
|
955
|
+
if (!keys || keys.length === 0)
|
|
956
|
+
return out;
|
|
957
|
+
for (const { chain, address } of keys) {
|
|
958
|
+
const addr = normalizeChainAddress(chain, address);
|
|
959
|
+
const summary = await this.getAddressLivenessSummary(chain, addr);
|
|
960
|
+
if (summary)
|
|
961
|
+
out.set(`${chain}:${addr}`, summary);
|
|
962
|
+
}
|
|
963
|
+
return out;
|
|
964
|
+
},
|
|
965
|
+
async listServicesToProbe({ limit = 30 } = {}) {
|
|
966
|
+
const clamped = Math.max(1, Math.min(200, Number(limit) || 30));
|
|
967
|
+
return db
|
|
968
|
+
.prepare(`SELECT sc.chain, sc.address, sc.resource_url AS resourceUrl, sc.method,
|
|
969
|
+
sc.price_usdc AS catalogPriceUsdc
|
|
970
|
+
FROM service_capabilities sc
|
|
971
|
+
LEFT JOIN service_liveness sl
|
|
972
|
+
ON sc.chain = sl.chain AND sc.address = sl.address AND sc.resource_url = sl.resource_url
|
|
973
|
+
LEFT JOIN agent_profiles ap
|
|
974
|
+
ON sc.chain = ap.chain AND sc.address = ap.address
|
|
975
|
+
ORDER BY
|
|
976
|
+
CASE WHEN ap.address IS NOT NULL THEN 0 ELSE 1 END ASC,
|
|
977
|
+
COALESCE(sl.last_probed_at, '') ASC,
|
|
978
|
+
COALESCE(sc.last_updated, '') DESC
|
|
979
|
+
LIMIT ?`)
|
|
980
|
+
.all(clamped);
|
|
981
|
+
},
|
|
982
|
+
async recomputeProfiles(chainInput, options = {}) {
|
|
983
|
+
const chain = normalizeChainName(chainInput);
|
|
984
|
+
if (!chain) {
|
|
985
|
+
throw new Error(`Unsupported chain "${chainInput}" for profile recomputation.`);
|
|
986
|
+
}
|
|
987
|
+
const owners = new Set(stmtSelectIdentitiesByChain.all(chain).map((r) => r.owner_address));
|
|
988
|
+
const activeScorer = options.scorer ?? DEFAULT_TRUST_SCORER;
|
|
989
|
+
// Stream payments row-by-row via iterate() instead of copying 1M rows into an array
|
|
990
|
+
const paymentStream = stmtSelectPaymentsByChain.iterate(chain);
|
|
991
|
+
const profiles = computeCreditProfilesFromPayments(chain, paymentStream, owners, "sqlite_live", {
|
|
992
|
+
scorer: activeScorer,
|
|
993
|
+
referenceTimeSec: options.referenceTimeSec,
|
|
994
|
+
});
|
|
995
|
+
const nowIso = new Date().toISOString();
|
|
996
|
+
const stateRoot = buildTrustStateRootCommitment(chain, profiles, {
|
|
997
|
+
modelVersion: activeScorer.modelVersion,
|
|
998
|
+
modelHash: activeScorer.modelHash,
|
|
999
|
+
signRoot: options.signRoot ??
|
|
1000
|
+
((merkleRoot, epochId) => signStateRootEd25519(merkleRoot, epochId)),
|
|
1001
|
+
});
|
|
1002
|
+
const prevScores = new Map();
|
|
1003
|
+
for (const r of stmtSelectOldScores.all(chain)) {
|
|
1004
|
+
prevScores.set(r.address, { score: Number(r.credit_score), flags: r.risk_flags_json });
|
|
1005
|
+
}
|
|
1006
|
+
runInTransaction(() => {
|
|
1007
|
+
for (const p of profiles) {
|
|
1008
|
+
const flagsJson = JSON.stringify(p.riskFlags);
|
|
1009
|
+
stmtUpsertProfile.run(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, p.metrics.totalUsdc, p.metrics.uniquePayers, p.metrics.medianTicketUsdc, p.metrics.hhi, p.metrics.top1PayerShare, p.metrics.activeSpanHours, p.metrics.activeUtcDays, JSON.stringify(p.metrics), p.dataCoverage ? JSON.stringify(p.dataCoverage) : null, JSON.stringify(p.channels), flagsJson, isVerifiedX402Channels(p.channels) ? 1 : 0, p.erc8004Registered ? 1 : 0, p.firstSeenAt, p.lastSeenAt, nowIso, "sqlite_live");
|
|
1010
|
+
const prev = prevScores.get(p.address);
|
|
1011
|
+
if (!prev ||
|
|
1012
|
+
Math.abs(prev.score - p.creditScore) >= 5 ||
|
|
1013
|
+
prev.flags !== flagsJson) {
|
|
1014
|
+
stmtInsertScoreHistory.run(p.chain, p.address, p.modelVersion || activeScorer.modelVersion, prev ? prev.score : null, p.creditScore, flagsJson, nowIso);
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
stmtInsertStateRoot.run(stateRoot.epochId, chain, stateRoot.modelVersion, stateRoot.modelHash, stateRoot.merkleRoot, stateRoot.leafCount, stateRoot.proofType, stateRoot.signature, stateRoot.createdAt);
|
|
1018
|
+
});
|
|
1019
|
+
return { profileCount: profiles.length, stateRoot };
|
|
1020
|
+
},
|
|
1021
|
+
async getProfile(chainInput, addressInput) {
|
|
1022
|
+
const chain = normalizeChainName(chainInput);
|
|
1023
|
+
if (!chain)
|
|
1024
|
+
return null;
|
|
1025
|
+
const address = normalizeChainAddress(chain, addressInput);
|
|
1026
|
+
if (!address)
|
|
1027
|
+
return null;
|
|
1028
|
+
const row = stmtGetProfile.get(chain, address);
|
|
1029
|
+
return row ? rowToProfile(row) : null;
|
|
1030
|
+
},
|
|
1031
|
+
async getPayerActivity(chainInput, addressInput) {
|
|
1032
|
+
const chain = normalizeChainName(chainInput);
|
|
1033
|
+
if (!chain)
|
|
1034
|
+
return null;
|
|
1035
|
+
const address = normalizeChainAddress(chain, addressInput);
|
|
1036
|
+
if (!address)
|
|
1037
|
+
return null;
|
|
1038
|
+
const row = stmtGetPayerActivity.get(chain, address);
|
|
1039
|
+
const txCount = Number(row?.tx_count || 0);
|
|
1040
|
+
if (!row || txCount === 0)
|
|
1041
|
+
return null;
|
|
1042
|
+
let hasReciprocalLoop = Number(row.has_self_transfer || 0) > 0;
|
|
1043
|
+
if (!hasReciprocalLoop) {
|
|
1044
|
+
const loopRow = stmtHasReciprocalPayment.get(chain, address, address, address);
|
|
1045
|
+
hasReciprocalLoop = Boolean(loopRow);
|
|
1046
|
+
}
|
|
1047
|
+
return {
|
|
1048
|
+
chain,
|
|
1049
|
+
address,
|
|
1050
|
+
txCount,
|
|
1051
|
+
distinctPayees: Number(row.distinct_payees || 0),
|
|
1052
|
+
totalUsd: Number(Number(row.total_usd || 0).toFixed(6)),
|
|
1053
|
+
firstSeenAt: unixSecToIsoOrNull(row.first_block_time),
|
|
1054
|
+
lastSeenAt: unixSecToIsoOrNull(row.last_block_time),
|
|
1055
|
+
activeUtcDays: Math.max(1, Number(row.active_utc_days || 0)),
|
|
1056
|
+
hasReciprocalLoop,
|
|
1057
|
+
};
|
|
1058
|
+
},
|
|
1059
|
+
async listChainProfiles(chainInput) {
|
|
1060
|
+
const chain = normalizeChainName(chainInput);
|
|
1061
|
+
if (!chain)
|
|
1062
|
+
return [];
|
|
1063
|
+
const rows = stmtListChainProfiles.all(chain);
|
|
1064
|
+
return rows.map(rowToProfile);
|
|
1065
|
+
},
|
|
1066
|
+
async getScoreHistory(chainInput, addressInput, limit = 50) {
|
|
1067
|
+
const chain = normalizeChainName(chainInput);
|
|
1068
|
+
if (!chain)
|
|
1069
|
+
return [];
|
|
1070
|
+
const address = normalizeChainAddress(chain, addressInput);
|
|
1071
|
+
if (!address)
|
|
1072
|
+
return [];
|
|
1073
|
+
const clampedLimit = Math.max(1, Math.min(200, Number(limit) || 50));
|
|
1074
|
+
const rows = stmtGetScoreHistory.all(chain, address, clampedLimit);
|
|
1075
|
+
return rows.map(rowToHistoryEntry);
|
|
1076
|
+
},
|
|
1077
|
+
async getLatestStateRoot(chainInput) {
|
|
1078
|
+
const chain = normalizeChainName(chainInput);
|
|
1079
|
+
if (!chain)
|
|
1080
|
+
return null;
|
|
1081
|
+
const row = stmtGetLatestStateRoot.get(chain);
|
|
1082
|
+
return row ? rowToStateRoot(row) : null;
|
|
1083
|
+
},
|
|
1084
|
+
async upsertAssociatedCredit(endorsement) {
|
|
1085
|
+
const parentChain = normalizeChainName(endorsement.parentChain);
|
|
1086
|
+
const childChain = normalizeChainName(endorsement.childChain);
|
|
1087
|
+
if (!parentChain || !childChain) {
|
|
1088
|
+
throw new Error(`Unsupported associated credit chain pair: ${endorsement.parentChain} -> ${endorsement.childChain}`);
|
|
1089
|
+
}
|
|
1090
|
+
const parentAddress = normalizeChainAddress(parentChain, endorsement.parentAddress);
|
|
1091
|
+
const childAddress = normalizeChainAddress(childChain, endorsement.childAddress);
|
|
1092
|
+
const nowIso = new Date().toISOString();
|
|
1093
|
+
stmtUpsertAssociatedCredit.run(String(endorsement.endorsementId), parentChain, parentAddress, childChain, childAddress, Number(endorsement.discountFactor), Math.round(Number(endorsement.maxEndorsedScore)), Number(endorsement.maxEndorsedSingleTxUsd), String(endorsement.ruleVersion || "assoc-v1"), String(endorsement.status || "ACTIVE"), String(endorsement.issuedAt || nowIso), String(endorsement.expiresAt), String(endorsement.proofType || "ed25519"), endorsement.proofPayload ? JSON.stringify(endorsement.proofPayload) : null, nowIso);
|
|
1094
|
+
},
|
|
1095
|
+
async revokeAssociatedCredit(endorsementId) {
|
|
1096
|
+
stmtRevokeAssociatedCredit.run(new Date().toISOString(), String(endorsementId));
|
|
1097
|
+
},
|
|
1098
|
+
async getAssociatedCreditForChild(chainInput, childAddressInput) {
|
|
1099
|
+
const chain = normalizeChainName(chainInput);
|
|
1100
|
+
if (!chain)
|
|
1101
|
+
return null;
|
|
1102
|
+
const childAddress = normalizeChainAddress(chain, childAddressInput);
|
|
1103
|
+
if (!childAddress)
|
|
1104
|
+
return null;
|
|
1105
|
+
const row = stmtGetAssociatedCreditForChild.get(chain, childAddress);
|
|
1106
|
+
return row ? rowToAssociatedCredit(row) : null;
|
|
1107
|
+
},
|
|
1108
|
+
async listProfiles({ chain = "all", minScore = 0, excludeFlagged = false, tier = "all", channel = "all", sort = "score", offset = 0, limit = 20, query = "", } = {}) {
|
|
1109
|
+
const where = ["credit_score >= ?"];
|
|
1110
|
+
const params = [Number(minScore) || 0];
|
|
1111
|
+
if (chain !== "all") {
|
|
1112
|
+
const norm = normalizeChainName(chain);
|
|
1113
|
+
if (!norm)
|
|
1114
|
+
throw new Error(`Unsupported chain filter "${chain}".`);
|
|
1115
|
+
where.push("chain = ?");
|
|
1116
|
+
params.push(norm);
|
|
1117
|
+
}
|
|
1118
|
+
if (excludeFlagged) {
|
|
1119
|
+
where.push("tier NOT IN ('FLAGGED_LOOP', 'FLAGGED_CONCENTRATED', 'FLAGGED_FARM')");
|
|
1120
|
+
}
|
|
1121
|
+
const tierFilter = String(tier || "all").trim().toUpperCase();
|
|
1122
|
+
if (tierFilter === "FLAGGED") {
|
|
1123
|
+
where.push("tier IN ('FLAGGED_LOOP', 'FLAGGED_CONCENTRATED', 'FLAGGED_FARM')");
|
|
1124
|
+
}
|
|
1125
|
+
else if (tierFilter !== "ALL") {
|
|
1126
|
+
where.push("UPPER(tier) = ?");
|
|
1127
|
+
params.push(tierFilter);
|
|
1128
|
+
}
|
|
1129
|
+
if (String(channel || "all").trim().toLowerCase() === "x402") {
|
|
1130
|
+
where.push("has_verified_x402 = 1");
|
|
1131
|
+
}
|
|
1132
|
+
const likePattern = buildSafeLikePattern(query);
|
|
1133
|
+
if (likePattern) {
|
|
1134
|
+
where.push(`(LOWER(address) LIKE ? ESCAPE '\\' OR EXISTS (
|
|
1135
|
+
SELECT 1 FROM service_capabilities sc
|
|
1136
|
+
WHERE sc.chain = agent_profiles.chain AND sc.address = agent_profiles.address
|
|
1137
|
+
AND LOWER(COALESCE(sc.service_name, '') || ' ' || COALESCE(sc.description, '')) LIKE ? ESCAPE '\\'
|
|
1138
|
+
))`);
|
|
1139
|
+
params.push(likePattern, likePattern);
|
|
1140
|
+
}
|
|
1141
|
+
let orderBy = "credit_score DESC, total_usdc DESC";
|
|
1142
|
+
if (sort === "volume")
|
|
1143
|
+
orderBy = "total_usdc DESC, credit_score DESC";
|
|
1144
|
+
else if (sort === "txs")
|
|
1145
|
+
orderBy = "tx_count DESC, credit_score DESC";
|
|
1146
|
+
else if (sort === "risk") {
|
|
1147
|
+
orderBy =
|
|
1148
|
+
"CASE WHEN tier IN ('FLAGGED_LOOP', 'FLAGGED_CONCENTRATED', 'FLAGGED_FARM') THEN 1 ELSE 0 END DESC, credit_score ASC, total_usdc DESC";
|
|
1149
|
+
}
|
|
1150
|
+
const whereSql = where.join(" AND ");
|
|
1151
|
+
const countRow = db
|
|
1152
|
+
.prepare(`SELECT COUNT(*) AS cnt FROM agent_profiles WHERE ${whereSql}`)
|
|
1153
|
+
.get(...params);
|
|
1154
|
+
const clampedOffset = Math.max(0, Math.floor(Number(offset) || 0));
|
|
1155
|
+
const clampedLimit = Math.max(1, Math.min(200, Number(limit) || 20));
|
|
1156
|
+
const rows = db
|
|
1157
|
+
.prepare(`SELECT * FROM agent_profiles WHERE ${whereSql} ORDER BY ${orderBy} LIMIT ? OFFSET ?`)
|
|
1158
|
+
.all(...params, clampedLimit, clampedOffset);
|
|
1159
|
+
return {
|
|
1160
|
+
totalMatched: Number(countRow?.cnt || 0),
|
|
1161
|
+
agents: rows.map(rowToProfile),
|
|
1162
|
+
};
|
|
1163
|
+
},
|
|
1164
|
+
async setState(key, value) {
|
|
1165
|
+
stmtSetState.run(String(key), String(value), new Date().toISOString());
|
|
1166
|
+
},
|
|
1167
|
+
async getState() {
|
|
1168
|
+
const out = {};
|
|
1169
|
+
for (const row of stmtGetAllState.all()) {
|
|
1170
|
+
out[row.key] = row.value;
|
|
1171
|
+
}
|
|
1172
|
+
return out;
|
|
1173
|
+
},
|
|
1174
|
+
async getStats() {
|
|
1175
|
+
const payments = countByChain("payments");
|
|
1176
|
+
const profiles = countByChain("agent_profiles");
|
|
1177
|
+
const erc8004Owners = countByChain("erc8004_identities");
|
|
1178
|
+
const capabilities = countByChain("service_capabilities");
|
|
1179
|
+
const capPayeesRow = db
|
|
1180
|
+
.prepare(`SELECT COUNT(DISTINCT chain || ':' || address) AS cnt FROM service_capabilities`)
|
|
1181
|
+
.get();
|
|
1182
|
+
const livenessRow = db
|
|
1183
|
+
.prepare(`SELECT
|
|
1184
|
+
SUM(CASE WHEN probe_total > 0 AND liveness_status IN ('LIVE_402', 'LIVE_200', 'LIVE_REACHABLE') THEN 1 ELSE 0 END) AS healthy,
|
|
1185
|
+
SUM(CASE WHEN probe_total > 0 AND liveness_status NOT IN ('LIVE_402', 'LIVE_200', 'LIVE_REACHABLE') THEN 1 ELSE 0 END) AS degraded_or_down,
|
|
1186
|
+
COALESCE(SUM(delivery_reports_total), 0) AS delivery_reports_total,
|
|
1187
|
+
COALESCE(SUM(delivery_reports_ok), 0) AS delivery_reports_ok
|
|
1188
|
+
FROM service_liveness`)
|
|
1189
|
+
.get();
|
|
1190
|
+
const tierRow = db
|
|
1191
|
+
.prepare(`SELECT
|
|
1192
|
+
SUM(CASE WHEN credit_score >= 70 AND tier = 'HIGH_TRUST' THEN 1 ELSE 0 END) AS high_trust,
|
|
1193
|
+
SUM(CASE WHEN credit_score >= 40 AND credit_score < 70 AND tier = 'MODERATE_TRUST' THEN 1 ELSE 0 END) AS moderate_trust,
|
|
1194
|
+
SUM(CASE WHEN tier IN ('FLAGGED_LOOP', 'FLAGGED_CONCENTRATED', 'FLAGGED_FARM') THEN 1 ELSE 0 END) AS flagged
|
|
1195
|
+
FROM agent_profiles`)
|
|
1196
|
+
.get();
|
|
1197
|
+
const earliestRow = db
|
|
1198
|
+
.prepare(`SELECT MIN(block_time) AS earliest_block_time FROM payments WHERE block_time IS NOT NULL`)
|
|
1199
|
+
.get();
|
|
1200
|
+
let dbSizeBytes = 0;
|
|
1201
|
+
if (!isMemory) {
|
|
1202
|
+
try {
|
|
1203
|
+
dbSizeBytes = fs.statSync(dbPath).size;
|
|
1204
|
+
}
|
|
1205
|
+
catch {
|
|
1206
|
+
dbSizeBytes = 0;
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
return {
|
|
1210
|
+
storageBackend: "sqlite",
|
|
1211
|
+
payments,
|
|
1212
|
+
profiles,
|
|
1213
|
+
erc8004Owners,
|
|
1214
|
+
capabilities,
|
|
1215
|
+
capabilitiesDistinctPayees: Number(capPayeesRow?.cnt || 0),
|
|
1216
|
+
liveness: {
|
|
1217
|
+
totalProbed: Number(livenessRow?.healthy || 0) + Number(livenessRow?.degraded_or_down || 0),
|
|
1218
|
+
healthy: Number(livenessRow?.healthy || 0),
|
|
1219
|
+
degradedOrDown: Number(livenessRow?.degraded_or_down || 0),
|
|
1220
|
+
deliveryReportsTotal: Number(livenessRow?.delivery_reports_total || 0),
|
|
1221
|
+
deliveryReportsOk: Number(livenessRow?.delivery_reports_ok || 0),
|
|
1222
|
+
},
|
|
1223
|
+
highTrustProfiles: Number(tierRow?.high_trust || 0),
|
|
1224
|
+
moderateTrustProfiles: Number(tierRow?.moderate_trust || 0),
|
|
1225
|
+
flaggedProfiles: Number(tierRow?.flagged || 0),
|
|
1226
|
+
earliestPaymentAt: unixSecToIsoOrNull(earliestRow?.earliest_block_time),
|
|
1227
|
+
dbSizeBytes,
|
|
1228
|
+
};
|
|
1229
|
+
},
|
|
1230
|
+
async pruneOldPayments(retentionDays = 60) {
|
|
1231
|
+
const days = Math.max(1, Number(retentionDays) || 60);
|
|
1232
|
+
const cutoff = Math.floor(Date.now() / 1000) - days * 86400;
|
|
1233
|
+
const info = stmtPrunePayments.run(cutoff);
|
|
1234
|
+
return { deleted: Number(info.changes || 0), cutoffTimestamp: cutoff };
|
|
1235
|
+
},
|
|
1236
|
+
async close() {
|
|
1237
|
+
db.close();
|
|
1238
|
+
},
|
|
1239
|
+
};
|
|
1240
|
+
}
|
|
1241
|
+
//# sourceMappingURL=sqlite-repo.js.map
|