@agentbadge/database 0.6.0 → 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,138 @@
1
+ import { guardEventsForAppend, rowToStored, } from "./econ-ledger-store.js";
2
+ import { deltasOfAppended } from "./trust-edge-store.js";
3
+ function toCreate(e) {
4
+ return {
5
+ id: e.id,
6
+ spec: e.spec,
7
+ source: e.source,
8
+ sourceId: e.sourceId,
9
+ seq: e.seq,
10
+ kind: e.kind,
11
+ actor: e.actor,
12
+ counterparty: e.counterparty ?? null,
13
+ amountUsdc: (e.amountUsdc ?? null),
14
+ at: e.at,
15
+ idempotencyKey: e.idempotencyKey,
16
+ payload: e.payload,
17
+ };
18
+ }
19
+ function isUniqueViolation(err) {
20
+ const m = err instanceof Error ? err.message : String(err);
21
+ return /unique|duplicate/i.test(m);
22
+ }
23
+ export class EconLedgerRepository {
24
+ db;
25
+ edges;
26
+ constructor(db, edges) {
27
+ this.db = db;
28
+ this.edges = edges;
29
+ }
30
+ async append(events) {
31
+ try {
32
+ return await this.appendInTx(events, async () => { });
33
+ }
34
+ catch (err) {
35
+ if (!isUniqueViolation(err))
36
+ throw err;
37
+ return this.appendInTx(events, async () => { });
38
+ }
39
+ }
40
+ async appendInTx(events, extra) {
41
+ guardEventsForAppend(events);
42
+ return this.db.transaction(async (tx) => {
43
+ const out = [];
44
+ for (const e of events) {
45
+ const existing = await tx.orm.public.EconomicEvent.where({
46
+ idempotencyKey: e.idempotencyKey,
47
+ }).first();
48
+ if (existing) {
49
+ out.push({
50
+ event: rowToStored(existing).event,
51
+ ledgerSeq: BigInt(existing.ledgerSeq),
52
+ duplicate: true,
53
+ });
54
+ continue;
55
+ }
56
+ const row = await tx.orm.public.EconomicEvent.create(toCreate(e));
57
+ out.push({ event: e, ledgerSeq: BigInt(row.ledgerSeq), duplicate: false });
58
+ }
59
+ if (this.edges) {
60
+ const deltas = deltasOfAppended(out);
61
+ if (deltas.length > 0)
62
+ await this.edges.applyDeltasTx(tx.orm, deltas);
63
+ }
64
+ await extra(tx.orm);
65
+ return out;
66
+ });
67
+ }
68
+ async getById(id) {
69
+ const row = await this.db.orm.public.EconomicEvent.where({ id }).first();
70
+ return row ? rowToStored(row) : null;
71
+ }
72
+ async getByKey(idempotencyKey) {
73
+ const row = await this.db.orm.public.EconomicEvent.where({
74
+ idempotencyKey,
75
+ }).first();
76
+ return row ? rowToStored(row) : null;
77
+ }
78
+ async listByAgent(agent, opts) {
79
+ const [asActor, asCparty] = await Promise.all([
80
+ this.db.orm.public.EconomicEvent.where({ actor: agent }).all(),
81
+ this.db.orm.public.EconomicEvent.where({ counterparty: agent }).all(),
82
+ ]);
83
+ return this.page(dedupeMerge(asActor, asCparty), opts);
84
+ }
85
+ async listByPair(a, b, opts) {
86
+ const [ab, ba] = await Promise.all([
87
+ this.db.orm.public.EconomicEvent.where({ actor: a, counterparty: b }).all(),
88
+ this.db.orm.public.EconomicEvent.where({ actor: b, counterparty: a }).all(),
89
+ ]);
90
+ return this.page(dedupeMerge(ab, ba), opts);
91
+ }
92
+ async listBySourceId(source, sourceId, opts) {
93
+ const rows = await this.db.orm.public.EconomicEvent.where({
94
+ source,
95
+ sourceId,
96
+ }).all();
97
+ let out = rows
98
+ .map(rowToStored)
99
+ .filter((s) => opts?.beforeLedgerSeq === undefined ||
100
+ s.ledgerSeq < opts.beforeLedgerSeq)
101
+ .sort((x, y) => x.ledgerSeq < y.ledgerSeq ? -1 : x.ledgerSeq > y.ledgerSeq ? 1 : 0);
102
+ if (opts?.limit !== undefined)
103
+ out = out.slice(0, opts.limit);
104
+ return out;
105
+ }
106
+ async scan(fromLedgerSeq, opts) {
107
+ const rows = await this.db.orm.public.EconomicEvent
108
+ .orderBy((e) => e.ledgerSeq.asc())
109
+ .all();
110
+ let out = rows
111
+ .filter((r) => BigInt(r.ledgerSeq) >= fromLedgerSeq)
112
+ .map(rowToStored);
113
+ if (opts?.limit !== undefined)
114
+ out = out.slice(0, opts.limit);
115
+ return out;
116
+ }
117
+ page(rows, opts) {
118
+ let out = rows
119
+ .map(rowToStored)
120
+ .filter((s) => opts?.beforeLedgerSeq === undefined ||
121
+ s.ledgerSeq < opts.beforeLedgerSeq)
122
+ .sort((x, y) => x.ledgerSeq > y.ledgerSeq ? -1 : x.ledgerSeq < y.ledgerSeq ? 1 : 0);
123
+ if (opts?.limit !== undefined)
124
+ out = out.slice(0, opts.limit);
125
+ return out;
126
+ }
127
+ }
128
+ function dedupeMerge(a, b) {
129
+ const seen = new Set();
130
+ const out = [];
131
+ for (const r of [...a, ...b]) {
132
+ if (seen.has(r.idempotencyKey))
133
+ continue;
134
+ seen.add(r.idempotencyKey);
135
+ out.push(r);
136
+ }
137
+ return out;
138
+ }
@@ -0,0 +1,53 @@
1
+ import { type EconomicEvent } from "@agentbadge/econ-events";
2
+ import type { Models } from "../prisma/contract.d.js";
3
+ import { type TrustEdgeDelta } from "./trust-edge-store.js";
4
+ export type EconEventDbRow = Models.public_EconomicEvent;
5
+ export interface EconEventStored {
6
+ ledgerSeq: bigint;
7
+ event: EconomicEvent;
8
+ createdAtMs: bigint;
9
+ }
10
+ export interface AppendResult {
11
+ event: EconomicEvent;
12
+ ledgerSeq: bigint;
13
+ duplicate: boolean;
14
+ }
15
+ export interface ListOpts {
16
+ beforeLedgerSeq?: bigint;
17
+ limit?: number;
18
+ }
19
+ export interface EconLedgerStore<TTx = unknown> {
20
+ append(events: EconomicEvent[]): Promise<AppendResult[]>;
21
+ appendInTx(events: EconomicEvent[], extra: (tx: TTx) => Promise<void>): Promise<AppendResult[]>;
22
+ getById(id: string): Promise<EconEventStored | null>;
23
+ getByKey(idempotencyKey: string): Promise<EconEventStored | null>;
24
+ listByAgent(agent: string, opts?: ListOpts): Promise<EconEventStored[]>;
25
+ listByPair(a: string, b: string, opts?: ListOpts): Promise<EconEventStored[]>;
26
+ listBySourceId(source: string, sourceId: string, opts?: ListOpts): Promise<EconEventStored[]>;
27
+ scan(fromLedgerSeq: bigint, opts?: {
28
+ limit?: number;
29
+ }): Promise<EconEventStored[]>;
30
+ }
31
+ export declare const ECON_LEDGER_MAX_PAYLOAD_BYTES = 65536;
32
+ export declare const ECON_LEDGER_MAX_BATCH = 500;
33
+ export declare function guardEventsForAppend(events: EconomicEvent[]): void;
34
+ export declare function rowToStored(row: EconEventDbRow): EconEventStored;
35
+ export declare class InMemoryEconLedgerStore implements EconLedgerStore<InMemoryEconLedgerStore> {
36
+ private readonly edges?;
37
+ private readonly byKey;
38
+ private seq;
39
+ constructor(edges?: {
40
+ applyDeltas(deltas: TrustEdgeDelta[]): Promise<void>;
41
+ } | undefined);
42
+ append(events: EconomicEvent[]): Promise<AppendResult[]>;
43
+ appendInTx(events: EconomicEvent[], extra: (tx: InMemoryEconLedgerStore) => Promise<void>): Promise<AppendResult[]>;
44
+ getById(id: string): Promise<EconEventStored | null>;
45
+ getByKey(idempotencyKey: string): Promise<EconEventStored | null>;
46
+ listByAgent(agent: string, opts?: ListOpts): Promise<EconEventStored[]>;
47
+ listByPair(a: string, b: string, opts?: ListOpts): Promise<EconEventStored[]>;
48
+ listBySourceId(source: string, sourceId: string, opts?: ListOpts): Promise<EconEventStored[]>;
49
+ scan(fromLedgerSeq: bigint, opts?: {
50
+ limit?: number;
51
+ }): Promise<EconEventStored[]>;
52
+ private page;
53
+ }
@@ -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,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
+ }