@agentbadge/database 0.5.4 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,130 @@
1
+ import { ECON_EVENT_KIND_SET, verifyEconomicEvent, EconEventError, } from "@agentbadge/econ-events";
2
+ import { deltasOfAppended } from "./trust-edge-store.js";
3
+ export const ECON_LEDGER_MAX_PAYLOAD_BYTES = 65_536;
4
+ export const ECON_LEDGER_MAX_BATCH = 500;
5
+ export function guardEventsForAppend(events) {
6
+ if (events.length === 0) {
7
+ throw new EconEventError("invalid_event", "append requires a non-empty batch");
8
+ }
9
+ if (events.length > ECON_LEDGER_MAX_BATCH) {
10
+ throw new EconEventError("invalid_event", `batch size ${events.length} exceeds cap ${ECON_LEDGER_MAX_BATCH}`);
11
+ }
12
+ for (const e of events) {
13
+ const res = verifyEconomicEvent(e);
14
+ if (!res.ok)
15
+ throw res.error;
16
+ if (!ECON_EVENT_KIND_SET.has(e.kind)) {
17
+ throw new EconEventError("invalid_event", `unknown kind "${e.kind}"`);
18
+ }
19
+ if (JSON.stringify(e.payload).length > ECON_LEDGER_MAX_PAYLOAD_BYTES) {
20
+ throw new EconEventError("invalid_event", `payload exceeds ${ECON_LEDGER_MAX_PAYLOAD_BYTES} bytes`);
21
+ }
22
+ }
23
+ }
24
+ export function rowToStored(row) {
25
+ const event = {
26
+ spec: row.spec,
27
+ id: row.id,
28
+ source: row.source,
29
+ sourceId: row.sourceId,
30
+ seq: row.seq,
31
+ kind: row.kind,
32
+ actor: row.actor,
33
+ ...(row.counterparty !== null ? { counterparty: row.counterparty } : {}),
34
+ ...(row.amountUsdc !== null
35
+ ? { amountUsdc: String(row.amountUsdc) }
36
+ : {}),
37
+ at: row.at,
38
+ payload: row.payload,
39
+ idempotencyKey: row.idempotencyKey,
40
+ };
41
+ return {
42
+ ledgerSeq: BigInt(row.ledgerSeq),
43
+ event,
44
+ createdAtMs: BigInt(new Date(row.createdAt).getTime()),
45
+ };
46
+ }
47
+ export class InMemoryEconLedgerStore {
48
+ edges;
49
+ byKey = new Map();
50
+ seq = 0n;
51
+ constructor(edges) {
52
+ this.edges = edges;
53
+ }
54
+ async append(events) {
55
+ guardEventsForAppend(events);
56
+ const out = [];
57
+ for (const e of events) {
58
+ const existing = this.byKey.get(e.idempotencyKey);
59
+ if (existing) {
60
+ out.push({ event: existing.event, ledgerSeq: existing.ledgerSeq, duplicate: true });
61
+ continue;
62
+ }
63
+ const stored = {
64
+ ledgerSeq: ++this.seq,
65
+ event: e,
66
+ createdAtMs: BigInt(Date.now()),
67
+ };
68
+ this.byKey.set(e.idempotencyKey, stored);
69
+ out.push({ event: e, ledgerSeq: stored.ledgerSeq, duplicate: false });
70
+ }
71
+ if (this.edges) {
72
+ const deltas = deltasOfAppended(out);
73
+ if (deltas.length > 0)
74
+ await this.edges.applyDeltas(deltas);
75
+ }
76
+ return out;
77
+ }
78
+ async appendInTx(events, extra) {
79
+ const rs = await this.append(events);
80
+ await extra(this);
81
+ return rs;
82
+ }
83
+ async getById(id) {
84
+ for (const s of this.byKey.values()) {
85
+ if (s.event.id === id)
86
+ return s;
87
+ }
88
+ return null;
89
+ }
90
+ async getByKey(idempotencyKey) {
91
+ return this.byKey.get(idempotencyKey) ?? null;
92
+ }
93
+ async listByAgent(agent, opts) {
94
+ return this.page([...this.byKey.values()].filter((s) => s.event.actor === agent || s.event.counterparty === agent), opts);
95
+ }
96
+ async listByPair(a, b, opts) {
97
+ return this.page([...this.byKey.values()].filter((s) => {
98
+ const { actor, counterparty } = s.event;
99
+ return ((actor === a && counterparty === b) ||
100
+ (actor === b && counterparty === a));
101
+ }), opts);
102
+ }
103
+ async listBySourceId(source, sourceId, opts) {
104
+ let rows = [...this.byKey.values()]
105
+ .filter((s) => s.event.source === source && s.event.sourceId === sourceId)
106
+ .sort((x, y) => x.ledgerSeq < y.ledgerSeq ? -1 : x.ledgerSeq > y.ledgerSeq ? 1 : 0);
107
+ if (opts?.beforeLedgerSeq !== undefined) {
108
+ rows = rows.filter((s) => s.ledgerSeq < opts.beforeLedgerSeq);
109
+ }
110
+ if (opts?.limit !== undefined)
111
+ rows = rows.slice(0, opts.limit);
112
+ return rows;
113
+ }
114
+ async scan(fromLedgerSeq, opts) {
115
+ let rows = [...this.byKey.values()]
116
+ .filter((s) => s.ledgerSeq >= fromLedgerSeq)
117
+ .sort((x, y) => (x.ledgerSeq < y.ledgerSeq ? -1 : x.ledgerSeq > y.ledgerSeq ? 1 : 0));
118
+ if (opts?.limit !== undefined)
119
+ rows = rows.slice(0, opts.limit);
120
+ return rows;
121
+ }
122
+ page(rows, opts) {
123
+ let out = rows
124
+ .filter((s) => opts?.beforeLedgerSeq === undefined || s.ledgerSeq < opts.beforeLedgerSeq)
125
+ .sort((x, y) => (x.ledgerSeq > y.ledgerSeq ? -1 : x.ledgerSeq < y.ledgerSeq ? 1 : 0));
126
+ if (opts?.limit !== undefined)
127
+ out = out.slice(0, opts.limit);
128
+ return out;
129
+ }
130
+ }
@@ -0,0 +1,8 @@
1
+ import type { PrismaDb } from "./event-repository.js";
2
+ import type { ForensicsCursorStore } from "./forensics-store.js";
3
+ export declare class ForensicsCursorRepository implements ForensicsCursorStore {
4
+ private readonly db;
5
+ constructor(db: PrismaDb);
6
+ get(chain: string): Promise<bigint | null>;
7
+ set(chain: string, lastBlock: bigint): Promise<void>;
8
+ }
@@ -0,0 +1,25 @@
1
+ export class ForensicsCursorRepository {
2
+ db;
3
+ constructor(db) {
4
+ this.db = db;
5
+ }
6
+ async get(chain) {
7
+ const r = await this.db.orm.public.ForensicsCursor.where({ chain }).first();
8
+ return r ? BigInt(r.lastBlock) : null;
9
+ }
10
+ async set(chain, lastBlock) {
11
+ const existing = await this.db.orm.public.ForensicsCursor.where({
12
+ chain,
13
+ }).first();
14
+ if (existing) {
15
+ await this.db.orm.public.ForensicsCursor.where({ chain }).update({
16
+ lastBlock: lastBlock,
17
+ });
18
+ return;
19
+ }
20
+ await this.db.orm.public.ForensicsCursor.create({
21
+ chain,
22
+ lastBlock: lastBlock,
23
+ });
24
+ }
25
+ }
@@ -0,0 +1,15 @@
1
+ import type { PrismaDb } from "./event-repository.js";
2
+ import type { ForensicsEdgeInsert, ForensicsEdgeRow, ForensicsEdgeStore } from "./forensics-store.js";
3
+ export declare class ForensicsEdgeRepository implements ForensicsEdgeStore {
4
+ private readonly db;
5
+ constructor(db: PrismaDb);
6
+ append(e: ForensicsEdgeInsert): Promise<ForensicsEdgeRow | null>;
7
+ appendBatch(es: ForensicsEdgeInsert[]): Promise<number>;
8
+ listBySeller(chain: string, seller: string, opts?: {
9
+ limit?: number;
10
+ fromBlock?: bigint;
11
+ }): Promise<ForensicsEdgeRow[]>;
12
+ listByPayer(chain: string, payer: string): Promise<ForensicsEdgeRow[]>;
13
+ countByChain(chain: string): Promise<number>;
14
+ private toRow;
15
+ }
@@ -0,0 +1,68 @@
1
+ export class ForensicsEdgeRepository {
2
+ db;
3
+ constructor(db) {
4
+ this.db = db;
5
+ }
6
+ async append(e) {
7
+ const existing = await this.db.orm.public.ForensicsEdge.where({
8
+ chain: e.chain,
9
+ txHash: e.txHash,
10
+ payer: e.payer.toLowerCase(),
11
+ seller: e.seller.toLowerCase(),
12
+ }).first();
13
+ if (existing)
14
+ return null;
15
+ return this.toRow(await this.db.orm.public.ForensicsEdge.create({
16
+ chain: e.chain,
17
+ payer: e.payer.toLowerCase(),
18
+ seller: e.seller.toLowerCase(),
19
+ amountAtomic: e.amountAtomic,
20
+ txHash: e.txHash,
21
+ blockNumber: e.blockNumber,
22
+ source: e.source,
23
+ ts: e.ts,
24
+ }));
25
+ }
26
+ async appendBatch(es) {
27
+ let n = 0;
28
+ for (const e of es)
29
+ if ((await this.append(e)) !== null)
30
+ n++;
31
+ return n;
32
+ }
33
+ async listBySeller(chain, seller, opts) {
34
+ let q = this.db.orm.public.ForensicsEdge.orderBy((r) => r.blockNumber.asc()).where({ chain, seller: seller.toLowerCase() });
35
+ if (opts?.limit !== undefined)
36
+ q = q.limit(opts.limit);
37
+ const rows = await q.all();
38
+ const mapped = rows.map((r) => this.toRow(r));
39
+ return opts?.fromBlock !== undefined
40
+ ? mapped.filter((r) => r.blockNumber >= opts.fromBlock)
41
+ : mapped;
42
+ }
43
+ async listByPayer(chain, payer) {
44
+ const rows = await this.db.orm.public.ForensicsEdge.where({
45
+ chain,
46
+ payer: payer.toLowerCase(),
47
+ }).all();
48
+ return rows.map((r) => this.toRow(r));
49
+ }
50
+ async countByChain(chain) {
51
+ const rows = await this.db.orm.public.ForensicsEdge.where({ chain }).all();
52
+ return rows.length;
53
+ }
54
+ toRow(r) {
55
+ return {
56
+ id: r.id,
57
+ chain: r.chain,
58
+ payer: r.payer,
59
+ seller: r.seller,
60
+ amountAtomic: BigInt(r.amountAtomic),
61
+ txHash: r.txHash,
62
+ blockNumber: BigInt(r.blockNumber),
63
+ source: r.source,
64
+ ts: BigInt(r.ts),
65
+ createdAt: String(r.createdAt),
66
+ };
67
+ }
68
+ }
@@ -0,0 +1,11 @@
1
+ import type { PrismaDb } from "./event-repository.js";
2
+ import type { ForensicsFundingInsert, ForensicsFundingRow, ForensicsFundingStore } from "./forensics-store.js";
3
+ export declare class ForensicsFundingRepository implements ForensicsFundingStore {
4
+ private readonly db;
5
+ constructor(db: PrismaDb);
6
+ insertFirst(f: ForensicsFundingInsert): Promise<ForensicsFundingRow | null>;
7
+ getFirst(chain: string, funded: string): Promise<ForensicsFundingRow | null>;
8
+ listFundedBy(chain: string, funder: string): Promise<ForensicsFundingRow[]>;
9
+ countByChain(chain: string): Promise<number>;
10
+ private toRow;
11
+ }
@@ -0,0 +1,54 @@
1
+ export class ForensicsFundingRepository {
2
+ db;
3
+ constructor(db) {
4
+ this.db = db;
5
+ }
6
+ async insertFirst(f) {
7
+ const existing = await this.db.orm.public.ForensicsFunding.where({
8
+ chain: f.chain,
9
+ funded: f.funded.toLowerCase(),
10
+ }).first();
11
+ if (existing)
12
+ return null;
13
+ return this.toRow(await this.db.orm.public.ForensicsFunding.create({
14
+ chain: f.chain,
15
+ funded: f.funded.toLowerCase(),
16
+ funder: f.funder.toLowerCase(),
17
+ txHash: f.txHash,
18
+ blockNumber: f.blockNumber,
19
+ isPublicSource: f.isPublicSource ?? false,
20
+ sourceKind: f.sourceKind ?? null,
21
+ }));
22
+ }
23
+ async getFirst(chain, funded) {
24
+ const r = await this.db.orm.public.ForensicsFunding.where({
25
+ chain,
26
+ funded: funded.toLowerCase(),
27
+ }).first();
28
+ return r ? this.toRow(r) : null;
29
+ }
30
+ async listFundedBy(chain, funder) {
31
+ const rows = await this.db.orm.public.ForensicsFunding.where({
32
+ chain,
33
+ funder: funder.toLowerCase(),
34
+ }).all();
35
+ return rows.map((r) => this.toRow(r));
36
+ }
37
+ async countByChain(chain) {
38
+ const rows = await this.db.orm.public.ForensicsFunding.where({ chain }).all();
39
+ return rows.length;
40
+ }
41
+ toRow(r) {
42
+ return {
43
+ id: r.id,
44
+ chain: r.chain,
45
+ funded: r.funded,
46
+ funder: r.funder,
47
+ txHash: r.txHash,
48
+ blockNumber: BigInt(r.blockNumber),
49
+ isPublicSource: r.isPublicSource,
50
+ sourceKind: r.sourceKind,
51
+ createdAt: String(r.createdAt),
52
+ };
53
+ }
54
+ }
@@ -0,0 +1,72 @@
1
+ export interface ForensicsEdgeInsert {
2
+ chain: string;
3
+ payer: string;
4
+ seller: string;
5
+ amountAtomic: bigint;
6
+ txHash: string;
7
+ blockNumber: bigint;
8
+ source: string;
9
+ ts: bigint;
10
+ }
11
+ export interface ForensicsEdgeRow extends ForensicsEdgeInsert {
12
+ id: string;
13
+ createdAt: string;
14
+ }
15
+ export interface ForensicsEdgeStore {
16
+ append(e: ForensicsEdgeInsert): Promise<ForensicsEdgeRow | null>;
17
+ appendBatch(es: ForensicsEdgeInsert[]): Promise<number>;
18
+ listBySeller(chain: string, seller: string, opts?: {
19
+ limit?: number;
20
+ fromBlock?: bigint;
21
+ }): Promise<ForensicsEdgeRow[]>;
22
+ listByPayer(chain: string, payer: string): Promise<ForensicsEdgeRow[]>;
23
+ countByChain(chain: string): Promise<number>;
24
+ }
25
+ export interface ForensicsFundingInsert {
26
+ chain: string;
27
+ funded: string;
28
+ funder: string;
29
+ txHash: string;
30
+ blockNumber: bigint;
31
+ isPublicSource?: boolean;
32
+ sourceKind?: string | null;
33
+ }
34
+ export interface ForensicsFundingRow extends ForensicsFundingInsert {
35
+ id: string;
36
+ createdAt: string;
37
+ }
38
+ export interface ForensicsFundingStore {
39
+ insertFirst(f: ForensicsFundingInsert): Promise<ForensicsFundingRow | null>;
40
+ getFirst(chain: string, funded: string): Promise<ForensicsFundingRow | null>;
41
+ listFundedBy(chain: string, funder: string): Promise<ForensicsFundingRow[]>;
42
+ countByChain(chain: string): Promise<number>;
43
+ }
44
+ export interface ForensicsCursorStore {
45
+ get(chain: string): Promise<bigint | null>;
46
+ set(chain: string, lastBlock: bigint): Promise<void>;
47
+ }
48
+ export declare class InMemoryForensicsEdgeStore implements ForensicsEdgeStore {
49
+ private rows;
50
+ private seq;
51
+ append(e: ForensicsEdgeInsert): Promise<ForensicsEdgeRow | null>;
52
+ appendBatch(es: ForensicsEdgeInsert[]): Promise<number>;
53
+ listBySeller(chain: string, seller: string, opts?: {
54
+ limit?: number;
55
+ fromBlock?: bigint;
56
+ }): Promise<ForensicsEdgeRow[]>;
57
+ listByPayer(chain: string, payer: string): Promise<ForensicsEdgeRow[]>;
58
+ countByChain(chain: string): Promise<number>;
59
+ }
60
+ export declare class InMemoryForensicsFundingStore implements ForensicsFundingStore {
61
+ private rows;
62
+ private seq;
63
+ insertFirst(f: ForensicsFundingInsert): Promise<ForensicsFundingRow | null>;
64
+ getFirst(chain: string, funded: string): Promise<ForensicsFundingRow | null>;
65
+ listFundedBy(chain: string, funder: string): Promise<ForensicsFundingRow[]>;
66
+ countByChain(chain: string): Promise<number>;
67
+ }
68
+ export declare class InMemoryForensicsCursorStore implements ForensicsCursorStore {
69
+ private rows;
70
+ get(chain: string): Promise<bigint | null>;
71
+ set(chain: string, lastBlock: bigint): Promise<void>;
72
+ }
@@ -0,0 +1,81 @@
1
+ const edgeKey = (e) => `${e.chain}|${e.txHash}|${e.payer}|${e.seller}`;
2
+ export class InMemoryForensicsEdgeStore {
3
+ rows = new Map();
4
+ seq = 0;
5
+ async append(e) {
6
+ const k = edgeKey(e);
7
+ if (this.rows.has(k))
8
+ return null;
9
+ const row = {
10
+ ...e,
11
+ payer: e.payer.toLowerCase(),
12
+ seller: e.seller.toLowerCase(),
13
+ id: `mem_edge_${++this.seq}`,
14
+ createdAt: new Date().toISOString(),
15
+ };
16
+ this.rows.set(k, row);
17
+ return row;
18
+ }
19
+ async appendBatch(es) {
20
+ let n = 0;
21
+ for (const e of es)
22
+ if ((await this.append(e)) !== null)
23
+ n++;
24
+ return n;
25
+ }
26
+ async listBySeller(chain, seller, opts) {
27
+ const s = seller.toLowerCase();
28
+ let out = [...this.rows.values()].filter((r) => r.chain === chain && r.seller === s);
29
+ if (opts?.fromBlock !== undefined) {
30
+ out = out.filter((r) => r.blockNumber >= opts.fromBlock);
31
+ }
32
+ out.sort((a, b) => Number(a.blockNumber - b.blockNumber));
33
+ return opts?.limit !== undefined ? out.slice(0, opts.limit) : out;
34
+ }
35
+ async listByPayer(chain, payer) {
36
+ const p = payer.toLowerCase();
37
+ return [...this.rows.values()].filter((r) => r.chain === chain && r.payer === p);
38
+ }
39
+ async countByChain(chain) {
40
+ return [...this.rows.values()].filter((r) => r.chain === chain).length;
41
+ }
42
+ }
43
+ export class InMemoryForensicsFundingStore {
44
+ rows = new Map();
45
+ seq = 0;
46
+ async insertFirst(f) {
47
+ const k = `${f.chain}|${f.funded.toLowerCase()}`;
48
+ if (this.rows.has(k))
49
+ return null;
50
+ const row = {
51
+ ...f,
52
+ funded: f.funded.toLowerCase(),
53
+ funder: f.funder.toLowerCase(),
54
+ isPublicSource: f.isPublicSource ?? false,
55
+ sourceKind: f.sourceKind ?? null,
56
+ id: `mem_fund_${++this.seq}`,
57
+ createdAt: new Date().toISOString(),
58
+ };
59
+ this.rows.set(k, row);
60
+ return row;
61
+ }
62
+ async getFirst(chain, funded) {
63
+ return this.rows.get(`${chain}|${funded.toLowerCase()}`) ?? null;
64
+ }
65
+ async listFundedBy(chain, funder) {
66
+ const f = funder.toLowerCase();
67
+ return [...this.rows.values()].filter((r) => r.chain === chain && r.funder === f);
68
+ }
69
+ async countByChain(chain) {
70
+ return [...this.rows.values()].filter((r) => r.chain === chain).length;
71
+ }
72
+ }
73
+ export class InMemoryForensicsCursorStore {
74
+ rows = new Map();
75
+ async get(chain) {
76
+ return this.rows.get(chain) ?? null;
77
+ }
78
+ async set(chain, lastBlock) {
79
+ this.rows.set(chain, lastBlock);
80
+ }
81
+ }
@@ -0,0 +1,16 @@
1
+ import type { PrismaDb } from "./event-repository.js";
2
+ import { type AgentTrustEdgeRecord, type TrustEdgeDelta, type TrustEdgeStore } from "./trust-edge-store.js";
3
+ type Orm = PrismaDb["orm"];
4
+ export declare class AgentTrustEdgeRepository implements TrustEdgeStore<Orm> {
5
+ private readonly db;
6
+ constructor(db: PrismaDb);
7
+ applyDeltasTx(orm: Orm, deltas: TrustEdgeDelta[]): Promise<void>;
8
+ applyDeltas(deltas: TrustEdgeDelta[]): Promise<void>;
9
+ listFrom(fromAgent: string): Promise<AgentTrustEdgeRecord[]>;
10
+ listTo(toAgent: string): Promise<AgentTrustEdgeRecord[]>;
11
+ listPair(a: string, b: string): Promise<AgentTrustEdgeRecord[]>;
12
+ listAll(): Promise<AgentTrustEdgeRecord[]>;
13
+ replaceAll(edges: AgentTrustEdgeRecord[]): Promise<void>;
14
+ private page;
15
+ }
16
+ export {};
@@ -0,0 +1,93 @@
1
+ import { applyDelta, edgeKey, mergeDeltas, rowToEdgeRecord, toMicros, } from "./trust-edge-store.js";
2
+ export class AgentTrustEdgeRepository {
3
+ db;
4
+ constructor(db) {
5
+ this.db = db;
6
+ }
7
+ async applyDeltasTx(orm, deltas) {
8
+ for (const d of mergeDeltas(deltas)) {
9
+ const existing = await orm.public.AgentTrustEdge
10
+ .where({ fromAgent: d.fromAgent, toAgent: d.toAgent, kind: d.kind })
11
+ .first();
12
+ if (!existing) {
13
+ await orm.public.AgentTrustEdge.create({
14
+ fromAgent: d.fromAgent,
15
+ toAgent: d.toAgent,
16
+ kind: d.kind,
17
+ eventCount: d.count,
18
+ totalUsd: (Number(d.usdMicros) / 1e6),
19
+ firstEventAt: d.firstEventAt,
20
+ firstEventSeq: d.firstEventSeq,
21
+ lastEventAt: d.lastEventAt,
22
+ lastEventSeq: d.lastEventSeq,
23
+ });
24
+ continue;
25
+ }
26
+ const next = applyDelta(rowToEdgeRecord(existing), d);
27
+ await orm.public.AgentTrustEdge.where({ id: existing.id }).update({
28
+ eventCount: next.eventCount,
29
+ totalUsd: Number(toMicros(next.totalUsd)) / 1e6,
30
+ firstEventAt: next.firstEventAt,
31
+ firstEventSeq: next.firstEventSeq,
32
+ lastEventAt: next.lastEventAt,
33
+ lastEventSeq: next.lastEventSeq,
34
+ });
35
+ }
36
+ }
37
+ async applyDeltas(deltas) {
38
+ await this.applyDeltasTx(this.db.orm, deltas);
39
+ }
40
+ async listFrom(fromAgent) {
41
+ const rows = await this.db.orm.public.AgentTrustEdge.where({ fromAgent }).all();
42
+ return this.page(rows);
43
+ }
44
+ async listTo(toAgent) {
45
+ const rows = await this.db.orm.public.AgentTrustEdge.where({ toAgent }).all();
46
+ return this.page(rows);
47
+ }
48
+ async listPair(a, b) {
49
+ const [ab, ba] = await Promise.all([
50
+ this.db.orm.public.AgentTrustEdge.where({ fromAgent: a, toAgent: b }).all(),
51
+ this.db.orm.public.AgentTrustEdge.where({ fromAgent: b, toAgent: a }).all(),
52
+ ]);
53
+ const seen = new Set();
54
+ const rows = [...ab, ...ba].filter((r) => {
55
+ const k = edgeKey(r);
56
+ if (seen.has(k))
57
+ return false;
58
+ seen.add(k);
59
+ return true;
60
+ });
61
+ return this.page(rows);
62
+ }
63
+ async listAll() {
64
+ const rows = await this.db.orm.public.AgentTrustEdge.where({}).all();
65
+ return this.page(rows);
66
+ }
67
+ async replaceAll(edges) {
68
+ await this.db.transaction(async (tx) => {
69
+ const existing = await tx.orm.public.AgentTrustEdge.where({}).all();
70
+ for (const row of existing) {
71
+ await tx.orm.public.AgentTrustEdge.where({ id: row.id }).delete();
72
+ }
73
+ for (const e of edges) {
74
+ await tx.orm.public.AgentTrustEdge.create({
75
+ fromAgent: e.fromAgent,
76
+ toAgent: e.toAgent,
77
+ kind: e.kind,
78
+ eventCount: e.eventCount,
79
+ totalUsd: Number(toMicros(e.totalUsd)) / 1e6,
80
+ firstEventAt: e.firstEventAt,
81
+ firstEventSeq: e.firstEventSeq,
82
+ lastEventAt: e.lastEventAt,
83
+ lastEventSeq: e.lastEventSeq,
84
+ });
85
+ }
86
+ });
87
+ }
88
+ page(rows) {
89
+ return rows
90
+ .map((r) => rowToEdgeRecord(r))
91
+ .sort((x, y) => x.lastEventSeq > y.lastEventSeq ? -1 : x.lastEventSeq < y.lastEventSeq ? 1 : 0);
92
+ }
93
+ }
@@ -0,0 +1,70 @@
1
+ import type { EconomicEvent } from "@agentbadge/econ-events";
2
+ import type { Models } from "../prisma/contract.d.js";
3
+ import type { EconEventStored, EconLedgerStore } from "./econ-ledger-store.js";
4
+ export type AgentTrustEdgeRow = Models.public_AgentTrustEdge;
5
+ export declare function edgeKey(e: {
6
+ fromAgent: string;
7
+ toAgent: string;
8
+ kind: string;
9
+ }): string;
10
+ export interface AgentTrustEdgeRecord {
11
+ fromAgent: string;
12
+ toAgent: string;
13
+ kind: string;
14
+ eventCount: number;
15
+ totalUsd: string;
16
+ firstEventAt: string | null;
17
+ firstEventSeq: bigint | null;
18
+ lastEventAt: string;
19
+ lastEventSeq: bigint;
20
+ }
21
+ export interface TrustEdgeDelta {
22
+ fromAgent: string;
23
+ toAgent: string;
24
+ kind: string;
25
+ count: number;
26
+ usdMicros: bigint;
27
+ firstEventAt: string;
28
+ firstEventSeq: bigint;
29
+ lastEventAt: string;
30
+ lastEventSeq: bigint;
31
+ }
32
+ export declare function edgeDeltaOf(event: EconomicEvent, ledgerSeq: bigint): TrustEdgeDelta | null;
33
+ export declare function deltasOfAppended(results: {
34
+ event: EconomicEvent;
35
+ ledgerSeq: bigint;
36
+ duplicate: boolean;
37
+ }[]): TrustEdgeDelta[];
38
+ export declare function mergeDeltas(deltas: TrustEdgeDelta[]): TrustEdgeDelta[];
39
+ export declare function applyDelta(edge: AgentTrustEdgeRecord, d: TrustEdgeDelta): AgentTrustEdgeRecord;
40
+ export declare function foldLog(stored: EconEventStored[]): AgentTrustEdgeRecord[];
41
+ export declare function rowToEdgeRecord(row: AgentTrustEdgeRow): AgentTrustEdgeRecord;
42
+ export declare function toMicros(usd: string | undefined | null): bigint;
43
+ export declare function fromMicros(micros: bigint): string;
44
+ export interface TrustEdgeStore<TTx = unknown> {
45
+ applyDeltasTx(tx: TTx, deltas: TrustEdgeDelta[]): Promise<void>;
46
+ applyDeltas(deltas: TrustEdgeDelta[]): Promise<void>;
47
+ listFrom(fromAgent: string): Promise<AgentTrustEdgeRecord[]>;
48
+ listTo(toAgent: string): Promise<AgentTrustEdgeRecord[]>;
49
+ listPair(a: string, b: string): Promise<AgentTrustEdgeRecord[]>;
50
+ listAll(): Promise<AgentTrustEdgeRecord[]>;
51
+ replaceAll(edges: AgentTrustEdgeRecord[]): Promise<void>;
52
+ }
53
+ export declare function rebuildTrustEdges(ledger: EconLedgerStore, edges: TrustEdgeStore, opts?: {
54
+ chunk?: number;
55
+ }): Promise<{
56
+ scanned: number;
57
+ written: number;
58
+ }>;
59
+ export declare class InMemoryTrustEdgeStore implements TrustEdgeStore<InMemoryTrustEdgeStore> {
60
+ private readonly byKey;
61
+ private static key;
62
+ applyDeltasTx(_tx: InMemoryTrustEdgeStore, deltas: TrustEdgeDelta[]): Promise<void>;
63
+ applyDeltas(deltas: TrustEdgeDelta[]): Promise<void>;
64
+ listFrom(fromAgent: string): Promise<AgentTrustEdgeRecord[]>;
65
+ listTo(toAgent: string): Promise<AgentTrustEdgeRecord[]>;
66
+ listPair(a: string, b: string): Promise<AgentTrustEdgeRecord[]>;
67
+ listAll(): Promise<AgentTrustEdgeRecord[]>;
68
+ replaceAll(edges: AgentTrustEdgeRecord[]): Promise<void>;
69
+ private all;
70
+ }