@agentbadge/database 0.6.0 → 0.6.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,269 @@
1
+ export const TERMINAL_ATTEMPT_STATUSES = [
2
+ "CONFIRMED",
3
+ "FAILED",
4
+ "EXPIRED",
5
+ ];
6
+ const nowIso = () => new Date().toISOString();
7
+ export class InMemoryPaymentStore {
8
+ rows = new Map();
9
+ async create(p) {
10
+ if (this.rows.has(p.id))
11
+ return null;
12
+ if (await this.getByReference(p.reference))
13
+ return null;
14
+ if (p.idempotencyKey != null &&
15
+ (await this.getByIdempotencyKey(p.idempotencyKey))) {
16
+ return null;
17
+ }
18
+ const ts = nowIso();
19
+ const row = {
20
+ ...p,
21
+ idempotencyKey: p.idempotencyKey ?? null,
22
+ customerId: p.customerId ?? null,
23
+ agentId: p.agentId ?? null,
24
+ productId: p.productId ?? null,
25
+ orderId: p.orderId ?? null,
26
+ currency: p.currency ?? "USD",
27
+ expiresAtMs: p.expiresAtMs ?? null,
28
+ createdAt: ts,
29
+ updatedAt: ts,
30
+ };
31
+ this.rows.set(row.id, row);
32
+ return row;
33
+ }
34
+ async getById(id) {
35
+ return this.rows.get(id) ?? null;
36
+ }
37
+ async getByReference(reference) {
38
+ return ([...this.rows.values()].find((r) => r.reference === reference) ?? null);
39
+ }
40
+ async getByIdempotencyKey(key) {
41
+ return ([...this.rows.values()].find((r) => r.idempotencyKey === key) ?? null);
42
+ }
43
+ async listByCustomer(customerId) {
44
+ return [...this.rows.values()]
45
+ .filter((r) => r.customerId === customerId)
46
+ .sort((a, b) => b.createdAtMs - a.createdAtMs);
47
+ }
48
+ async applyStatus(id, expectedFrom, to, updatedAtMs) {
49
+ const row = this.rows.get(id);
50
+ if (!row || row.status !== expectedFrom)
51
+ return null;
52
+ const updated = {
53
+ ...row,
54
+ status: to,
55
+ updatedAtMs,
56
+ updatedAt: nowIso(),
57
+ };
58
+ this.rows.set(id, updated);
59
+ return updated;
60
+ }
61
+ async listExpired(nowMs) {
62
+ return [...this.rows.values()].filter((r) => r.expiresAtMs != null &&
63
+ r.expiresAtMs < nowMs &&
64
+ (r.status === "PENDING" || r.status === "PROCESSING"));
65
+ }
66
+ }
67
+ export class InMemoryPaymentAttemptStore {
68
+ rows = new Map();
69
+ async create(a) {
70
+ if (this.rows.has(a.id))
71
+ return null;
72
+ if (a.providerReference != null &&
73
+ (await this.getByProviderRef(a.provider, a.providerReference))) {
74
+ return null;
75
+ }
76
+ if (a.transactionHash != null) {
77
+ const dup = [...this.rows.values()].find((r) => r.provider === a.provider &&
78
+ r.transactionHash === a.transactionHash);
79
+ if (dup)
80
+ return null;
81
+ }
82
+ const ts = nowIso();
83
+ const row = {
84
+ ...a,
85
+ network: a.network ?? null,
86
+ token: a.token ?? null,
87
+ providerReference: a.providerReference ?? null,
88
+ transactionHash: a.transactionHash ?? null,
89
+ expiresAtMs: a.expiresAtMs ?? null,
90
+ confirmedAtMs: a.confirmedAtMs ?? null,
91
+ createdAt: ts,
92
+ updatedAt: ts,
93
+ };
94
+ this.rows.set(row.id, row);
95
+ return row;
96
+ }
97
+ async getById(id) {
98
+ return this.rows.get(id) ?? null;
99
+ }
100
+ async listByPayment(paymentId) {
101
+ return [...this.rows.values()].filter((r) => r.paymentId === paymentId);
102
+ }
103
+ async getByProviderRef(provider, providerReference) {
104
+ return ([...this.rows.values()].find((r) => r.provider === provider &&
105
+ r.providerReference === providerReference) ?? null);
106
+ }
107
+ async getByTxHash(transactionHash) {
108
+ return ([...this.rows.values()].find((r) => r.transactionHash === transactionHash) ?? null);
109
+ }
110
+ async applyStatus(id, expectedFrom, to, updatedAtMs, patch) {
111
+ const row = this.rows.get(id);
112
+ if (!row || row.status !== expectedFrom)
113
+ return null;
114
+ const updated = {
115
+ ...row,
116
+ status: to,
117
+ ...(patch?.confirmedAtMs !== undefined
118
+ ? { confirmedAtMs: patch.confirmedAtMs }
119
+ : {}),
120
+ ...(patch?.transactionHash !== undefined
121
+ ? { transactionHash: patch.transactionHash }
122
+ : {}),
123
+ ...(patch?.providerReference !== undefined
124
+ ? { providerReference: patch.providerReference }
125
+ : {}),
126
+ updatedAt: nowIso(),
127
+ };
128
+ this.rows.set(id, updated);
129
+ return updated;
130
+ }
131
+ async listExpired(nowMs) {
132
+ return [...this.rows.values()].filter((r) => r.expiresAtMs != null &&
133
+ r.expiresAtMs < nowMs &&
134
+ !TERMINAL_ATTEMPT_STATUSES.includes(r.status));
135
+ }
136
+ }
137
+ export class InMemoryPaymentReceiptStore {
138
+ rows = new Map();
139
+ async append(r) {
140
+ if (this.rows.has(r.id))
141
+ return null;
142
+ if (await this.getByExternalRef(r.provider, r.externalReference)) {
143
+ return null;
144
+ }
145
+ const row = {
146
+ ...r,
147
+ network: r.network ?? null,
148
+ transactionHash: r.transactionHash ?? null,
149
+ payer: r.payer ?? null,
150
+ recipient: r.recipient ?? null,
151
+ createdAt: nowIso(),
152
+ };
153
+ this.rows.set(row.id, row);
154
+ return row;
155
+ }
156
+ async getById(id) {
157
+ return this.rows.get(id) ?? null;
158
+ }
159
+ async listByPayment(paymentId) {
160
+ return [...this.rows.values()].filter((r) => r.paymentId === paymentId);
161
+ }
162
+ async getByExternalRef(provider, externalReference) {
163
+ return ([...this.rows.values()].find((r) => r.provider === provider &&
164
+ r.externalReference === externalReference) ?? null);
165
+ }
166
+ }
167
+ export class InMemoryPaymentEventStore {
168
+ rows = new Map();
169
+ async append(e) {
170
+ if (this.rows.has(e.id))
171
+ return null;
172
+ const row = {
173
+ ...e,
174
+ attemptId: e.attemptId ?? null,
175
+ reason: e.reason ?? null,
176
+ createdAt: nowIso(),
177
+ };
178
+ this.rows.set(row.id, row);
179
+ return row;
180
+ }
181
+ async listByPayment(paymentId) {
182
+ return [...this.rows.values()]
183
+ .filter((r) => r.paymentId === paymentId)
184
+ .sort((a, b) => a.atMs - b.atMs);
185
+ }
186
+ async listByAttempt(attemptId) {
187
+ return [...this.rows.values()]
188
+ .filter((r) => r.attemptId === attemptId)
189
+ .sort((a, b) => a.atMs - b.atMs);
190
+ }
191
+ }
192
+ export class InMemoryPaymentProductStore {
193
+ rows = new Map();
194
+ async upsert(p) {
195
+ const existing = [...this.rows.values()].find((r) => r.code === p.code);
196
+ if (existing) {
197
+ const updated = {
198
+ ...existing,
199
+ name: p.name,
200
+ description: p.description ?? null,
201
+ category: p.category,
202
+ active: p.active ?? true,
203
+ payload: p.payload,
204
+ updatedAt: nowIso(),
205
+ };
206
+ this.rows.set(existing.id, updated);
207
+ return updated;
208
+ }
209
+ const ts = nowIso();
210
+ const row = {
211
+ ...p,
212
+ description: p.description ?? null,
213
+ active: p.active ?? true,
214
+ createdAt: ts,
215
+ updatedAt: ts,
216
+ };
217
+ this.rows.set(row.id, row);
218
+ return row;
219
+ }
220
+ async getById(id) {
221
+ return this.rows.get(id) ?? null;
222
+ }
223
+ async getByCode(code) {
224
+ return [...this.rows.values()].find((r) => r.code === code) ?? null;
225
+ }
226
+ async list(opts) {
227
+ let all = [...this.rows.values()];
228
+ if (opts?.activeOnly)
229
+ all = all.filter((r) => r.active);
230
+ return all;
231
+ }
232
+ }
233
+ export class InMemoryPaymentPriceStore {
234
+ rows = new Map();
235
+ async create(p) {
236
+ if (this.rows.has(p.id))
237
+ return null;
238
+ const ts = nowIso();
239
+ const row = {
240
+ ...p,
241
+ currency: p.currency ?? "USD",
242
+ interval: p.interval ?? null,
243
+ active: p.active ?? true,
244
+ createdAt: ts,
245
+ updatedAt: ts,
246
+ };
247
+ this.rows.set(row.id, row);
248
+ return row;
249
+ }
250
+ async getById(id) {
251
+ return this.rows.get(id) ?? null;
252
+ }
253
+ async listByProduct(productId, opts) {
254
+ let all = [...this.rows.values()].filter((r) => r.productId === productId);
255
+ if (opts?.activeOnly)
256
+ all = all.filter((r) => r.active);
257
+ return all;
258
+ }
259
+ }
260
+ export function createInMemoryPaymentStores() {
261
+ return {
262
+ payments: new InMemoryPaymentStore(),
263
+ attempts: new InMemoryPaymentAttemptStore(),
264
+ receipts: new InMemoryPaymentReceiptStore(),
265
+ events: new InMemoryPaymentEventStore(),
266
+ products: new InMemoryPaymentProductStore(),
267
+ prices: new InMemoryPaymentPriceStore(),
268
+ };
269
+ }
@@ -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
+ }
@@ -0,0 +1,183 @@
1
+ export function edgeKey(e) {
2
+ return `${e.fromAgent}|${e.toAgent}|${e.kind}`;
3
+ }
4
+ export function edgeDeltaOf(event, ledgerSeq) {
5
+ if (!event.counterparty)
6
+ return null;
7
+ return {
8
+ fromAgent: event.actor,
9
+ toAgent: event.counterparty,
10
+ kind: event.kind,
11
+ count: 1,
12
+ usdMicros: toMicros(event.amountUsdc),
13
+ firstEventAt: event.at,
14
+ firstEventSeq: ledgerSeq,
15
+ lastEventAt: event.at,
16
+ lastEventSeq: ledgerSeq,
17
+ };
18
+ }
19
+ export function deltasOfAppended(results) {
20
+ const out = [];
21
+ for (const r of results) {
22
+ if (r.duplicate)
23
+ continue;
24
+ const d = edgeDeltaOf(r.event, r.ledgerSeq);
25
+ if (d)
26
+ out.push(d);
27
+ }
28
+ return mergeDeltas(out);
29
+ }
30
+ export function mergeDeltas(deltas) {
31
+ const byKey = new Map();
32
+ for (const d of deltas) {
33
+ const k = edgeKey(d);
34
+ const prev = byKey.get(k);
35
+ if (!prev) {
36
+ byKey.set(k, { ...d });
37
+ continue;
38
+ }
39
+ prev.count += d.count;
40
+ prev.usdMicros += d.usdMicros;
41
+ if (d.firstEventSeq < prev.firstEventSeq) {
42
+ prev.firstEventSeq = d.firstEventSeq;
43
+ prev.firstEventAt = d.firstEventAt;
44
+ }
45
+ if (d.lastEventSeq > prev.lastEventSeq) {
46
+ prev.lastEventSeq = d.lastEventSeq;
47
+ prev.lastEventAt = d.lastEventAt;
48
+ }
49
+ }
50
+ return [...byKey.values()];
51
+ }
52
+ export function applyDelta(edge, d) {
53
+ const earlier = edge.firstEventSeq === null || d.firstEventSeq < edge.firstEventSeq;
54
+ return {
55
+ fromAgent: edge.fromAgent,
56
+ toAgent: edge.toAgent,
57
+ kind: edge.kind,
58
+ eventCount: edge.eventCount + d.count,
59
+ totalUsd: fromMicros(toMicros(edge.totalUsd) + d.usdMicros),
60
+ firstEventAt: earlier ? d.firstEventAt : edge.firstEventAt,
61
+ firstEventSeq: earlier ? d.firstEventSeq : edge.firstEventSeq,
62
+ lastEventAt: d.lastEventSeq > edge.lastEventSeq ? d.lastEventAt : edge.lastEventAt,
63
+ lastEventSeq: d.lastEventSeq > edge.lastEventSeq ? d.lastEventSeq : edge.lastEventSeq,
64
+ };
65
+ }
66
+ export function foldLog(stored) {
67
+ const byKey = new Map();
68
+ for (const s of stored) {
69
+ const d = edgeDeltaOf(s.event, s.ledgerSeq);
70
+ if (!d)
71
+ continue;
72
+ const k = edgeKey(d);
73
+ const prev = byKey.get(k);
74
+ const merged = applyDelta(prev ?? {
75
+ fromAgent: d.fromAgent,
76
+ toAgent: d.toAgent,
77
+ kind: d.kind,
78
+ eventCount: 0,
79
+ totalUsd: "0",
80
+ firstEventAt: null,
81
+ firstEventSeq: null,
82
+ lastEventAt: "",
83
+ lastEventSeq: 0n,
84
+ }, d);
85
+ byKey.set(k, merged);
86
+ }
87
+ return [...byKey.values()];
88
+ }
89
+ export function rowToEdgeRecord(row) {
90
+ return {
91
+ fromAgent: row.fromAgent,
92
+ toAgent: row.toAgent,
93
+ kind: row.kind,
94
+ eventCount: row.eventCount,
95
+ totalUsd: String(row.totalUsd),
96
+ firstEventAt: row.firstEventAt ?? null,
97
+ firstEventSeq: row.firstEventSeq !== null && row.firstEventSeq !== undefined
98
+ ? BigInt(row.firstEventSeq)
99
+ : null,
100
+ lastEventAt: row.lastEventAt,
101
+ lastEventSeq: BigInt(row.lastEventSeq),
102
+ };
103
+ }
104
+ export function toMicros(usd) {
105
+ if (!usd)
106
+ return 0n;
107
+ const neg = usd.startsWith("-");
108
+ const body = neg ? usd.slice(1) : usd;
109
+ const [i, f = ""] = body.split(".");
110
+ const frac = (f + "000000").slice(0, 6);
111
+ const v = BigInt(i || "0") * 1000000n + BigInt(frac);
112
+ return neg ? -v : v;
113
+ }
114
+ export function fromMicros(micros) {
115
+ const neg = micros < 0n;
116
+ const v = neg ? -micros : micros;
117
+ const i = v / 1000000n;
118
+ const f = (v % 1000000n).toString().padStart(6, "0").replace(/0+$/, "");
119
+ return `${neg ? "-" : ""}${i}${f ? "." + f : ""}`;
120
+ }
121
+ export async function rebuildTrustEdges(ledger, edges, opts) {
122
+ const chunk = opts?.chunk ?? 1_000;
123
+ const all = [];
124
+ for (let cursor = 0n;;) {
125
+ const batch = await ledger.scan(cursor, { limit: chunk });
126
+ all.push(...batch);
127
+ if (batch.length < chunk)
128
+ break;
129
+ cursor = batch[batch.length - 1].ledgerSeq + 1n;
130
+ }
131
+ const folded = foldLog(all);
132
+ await edges.replaceAll(folded);
133
+ return { scanned: all.length, written: folded.length };
134
+ }
135
+ export class InMemoryTrustEdgeStore {
136
+ byKey = new Map();
137
+ static key(e) {
138
+ return edgeKey(e);
139
+ }
140
+ async applyDeltasTx(_tx, deltas) {
141
+ await this.applyDeltas(deltas);
142
+ }
143
+ async applyDeltas(deltas) {
144
+ for (const d of mergeDeltas(deltas)) {
145
+ const k = InMemoryTrustEdgeStore.key(d);
146
+ const prev = this.byKey.get(k);
147
+ this.byKey.set(k, prev
148
+ ? applyDelta(prev, d)
149
+ : {
150
+ fromAgent: d.fromAgent,
151
+ toAgent: d.toAgent,
152
+ kind: d.kind,
153
+ eventCount: d.count,
154
+ totalUsd: fromMicros(d.usdMicros),
155
+ firstEventAt: d.firstEventAt,
156
+ firstEventSeq: d.firstEventSeq,
157
+ lastEventAt: d.lastEventAt,
158
+ lastEventSeq: d.lastEventSeq,
159
+ });
160
+ }
161
+ }
162
+ async listFrom(fromAgent) {
163
+ return this.all().filter((e) => e.fromAgent === fromAgent);
164
+ }
165
+ async listTo(toAgent) {
166
+ return this.all().filter((e) => e.toAgent === toAgent);
167
+ }
168
+ async listPair(a, b) {
169
+ return this.all().filter((e) => (e.fromAgent === a && e.toAgent === b) ||
170
+ (e.fromAgent === b && e.toAgent === a));
171
+ }
172
+ async listAll() {
173
+ return this.all();
174
+ }
175
+ async replaceAll(edges) {
176
+ this.byKey.clear();
177
+ for (const e of edges)
178
+ this.byKey.set(InMemoryTrustEdgeStore.key(e), { ...e });
179
+ }
180
+ all() {
181
+ return [...this.byKey.values()].sort((x, y) => x.lastEventSeq > y.lastEventSeq ? -1 : x.lastEventSeq < y.lastEventSeq ? 1 : 0);
182
+ }
183
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentbadge/database",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "Shared database layer for AgentBadge — Prisma ORM 8 client, repositories, store abstraction",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -50,6 +50,7 @@
50
50
  "vitest": "^2.0.0"
51
51
  },
52
52
  "dependencies": {
53
+ "@agentbadge/econ-events": "^0.1.3",
53
54
  "@prisma/orm-postgres": "8.0.0-rc.11",
54
55
  "dotenv": "^18.0.3"
55
56
  }