@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,105 @@
1
+ import type { JsonValue } from "@prisma/orm-postgres/target/codec-types";
2
+ import type { Models } from "../prisma/contract.d.js";
3
+ import type { PrismaDb } from "./event-repository.js";
4
+ type CardRow = Models.public_BoardCard;
5
+ type EntryRow = Models.public_BoardEntry;
6
+ type ReputationRow = Models.public_ReputationWrite;
7
+ type OutboxRow = Models.public_ChainTxOutbox;
8
+ export interface BoardCardInsert {
9
+ bountyId: string;
10
+ column: string;
11
+ title: string;
12
+ budgetUsdc?: string | null;
13
+ specHash: string;
14
+ createdBy?: string | null;
15
+ currentPassportId?: string | null;
16
+ fixDeadlineMs?: bigint | null;
17
+ payload: JsonValue;
18
+ }
19
+ export interface BoardCardPatch {
20
+ column?: string;
21
+ currentPassportId?: string | null;
22
+ fixDeadlineMs?: bigint | null;
23
+ payload?: JsonValue;
24
+ }
25
+ export interface BoardEntryInsert {
26
+ cardId: string;
27
+ seq: number;
28
+ attempt?: number;
29
+ kind: string;
30
+ actor: string;
31
+ txHash?: string | null;
32
+ payload: JsonValue;
33
+ atMs: bigint;
34
+ }
35
+ export interface ReputationWriteInsert {
36
+ sourceType: string;
37
+ sourceId: string;
38
+ jobAttempt?: number;
39
+ passportId: string;
40
+ agentId?: string | null;
41
+ score: number;
42
+ status?: string;
43
+ feedbackUri?: string | null;
44
+ feedbackHash?: string | null;
45
+ txHash?: string | null;
46
+ attempts?: number;
47
+ payload: JsonValue;
48
+ }
49
+ export interface ReputationWritePatch {
50
+ status?: string;
51
+ agentId?: string | null;
52
+ txHash?: string | null;
53
+ feedbackUri?: string | null;
54
+ feedbackHash?: string | null;
55
+ attempts?: number;
56
+ payload?: JsonValue;
57
+ }
58
+ export interface ChainTxOutboxInsert {
59
+ kind: string;
60
+ cardId?: string | null;
61
+ jobAttempt?: number | null;
62
+ idempotencyKey: string;
63
+ status?: string;
64
+ txHash?: string | null;
65
+ attempts?: number;
66
+ lastError?: string | null;
67
+ payload: JsonValue;
68
+ }
69
+ export interface ChainTxOutboxPatch {
70
+ status?: string;
71
+ txHash?: string | null;
72
+ attempts?: number;
73
+ lastError?: string | null;
74
+ payload?: JsonValue;
75
+ }
76
+ export declare class BoardRepository {
77
+ private readonly db;
78
+ constructor(db: PrismaDb);
79
+ insertCard(cardId: string, data: BoardCardInsert): Promise<CardRow>;
80
+ getCard(cardId: string): Promise<CardRow | null>;
81
+ getCardByBounty(bountyId: string): Promise<CardRow | null>;
82
+ listCards(opts?: {
83
+ column?: string;
84
+ currentPassportId?: string;
85
+ limit?: number;
86
+ }): Promise<CardRow[]>;
87
+ listAllCards(): Promise<CardRow[]>;
88
+ listExpiredFix(nowMs: bigint): Promise<CardRow[]>;
89
+ patchCard(cardId: string, patch: BoardCardPatch): Promise<CardRow | null>;
90
+ insertEntry(id: string, data: BoardEntryInsert): Promise<EntryRow>;
91
+ listEntries(cardId: string): Promise<EntryRow[]>;
92
+ listAllEntries(): Promise<EntryRow[]>;
93
+ insertReputation(data: ReputationWriteInsert): Promise<ReputationRow>;
94
+ getReputation(sourceType: string, sourceId: string, jobAttempt: number): Promise<ReputationRow | null>;
95
+ listReputation(opts?: {
96
+ status?: string;
97
+ passportId?: string;
98
+ }): Promise<ReputationRow[]>;
99
+ patchReputation(id: string, patch: ReputationWritePatch): Promise<ReputationRow | null>;
100
+ enqueueOutbox(data: ChainTxOutboxInsert): Promise<OutboxRow>;
101
+ getOutboxByKey(idempotencyKey: string): Promise<OutboxRow | null>;
102
+ listOutboxByStatus(status: string): Promise<OutboxRow[]>;
103
+ patchOutbox(id: string, patch: ChainTxOutboxPatch): Promise<OutboxRow | null>;
104
+ }
105
+ export {};
@@ -0,0 +1,142 @@
1
+ export class BoardRepository {
2
+ db;
3
+ constructor(db) {
4
+ this.db = db;
5
+ }
6
+ async insertCard(cardId, data) {
7
+ return this.db.orm.public.BoardCard.create({ cardId, ...data });
8
+ }
9
+ async getCard(cardId) {
10
+ return this.db.orm.public.BoardCard.where({ cardId }).first();
11
+ }
12
+ async getCardByBounty(bountyId) {
13
+ return this.db.orm.public.BoardCard.where({ bountyId }).first();
14
+ }
15
+ async listCards(opts) {
16
+ let q = this.db.orm.public.BoardCard.orderBy((c) => c.createdAt.desc());
17
+ if (opts?.column !== undefined)
18
+ q = q.where({ column: opts.column });
19
+ if (opts?.currentPassportId !== undefined) {
20
+ q = q.where({ currentPassportId: opts.currentPassportId });
21
+ }
22
+ if (opts?.limit !== undefined)
23
+ q = q.limit(opts.limit);
24
+ return q.all();
25
+ }
26
+ async listAllCards() {
27
+ return this.db.orm.public.BoardCard.all();
28
+ }
29
+ async listExpiredFix(nowMs) {
30
+ const buggy = await this.db.orm.public.BoardCard.where({
31
+ column: "bug",
32
+ }).all();
33
+ return buggy.filter((c) => c.fixDeadlineMs !== null && BigInt(c.fixDeadlineMs) < nowMs);
34
+ }
35
+ async patchCard(cardId, patch) {
36
+ const existing = await this.getCard(cardId);
37
+ if (!existing)
38
+ return null;
39
+ return this.db.orm.public.BoardCard.where({ cardId }).update({
40
+ column: patch.column ?? existing.column,
41
+ currentPassportId: patch.currentPassportId !== undefined
42
+ ? patch.currentPassportId
43
+ : existing.currentPassportId,
44
+ fixDeadlineMs: patch.fixDeadlineMs !== undefined
45
+ ? patch.fixDeadlineMs
46
+ : existing.fixDeadlineMs,
47
+ payload: patch.payload ?? existing.payload,
48
+ });
49
+ }
50
+ async insertEntry(id, data) {
51
+ return this.db.orm.public.BoardEntry.create({ id, ...data });
52
+ }
53
+ async listEntries(cardId) {
54
+ return this.db.orm.public.BoardEntry.where({ cardId })
55
+ .orderBy((e) => e.seq.asc())
56
+ .all();
57
+ }
58
+ async listAllEntries() {
59
+ return this.db.orm.public.BoardEntry.all();
60
+ }
61
+ async insertReputation(data) {
62
+ const existing = await this.getReputation(data.sourceType, data.sourceId, data.jobAttempt ?? 1);
63
+ if (existing)
64
+ return existing;
65
+ return this.db.orm.public.ReputationWrite.create({
66
+ status: "pending",
67
+ jobAttempt: 1,
68
+ ...data,
69
+ });
70
+ }
71
+ async getReputation(sourceType, sourceId, jobAttempt) {
72
+ return this.db.orm.public.ReputationWrite.where({
73
+ sourceType,
74
+ sourceId,
75
+ jobAttempt,
76
+ }).first();
77
+ }
78
+ async listReputation(opts) {
79
+ let q = this.db.orm.public.ReputationWrite.orderBy((r) => r.createdAt.desc());
80
+ if (opts?.status !== undefined)
81
+ q = q.where({ status: opts.status });
82
+ if (opts?.passportId !== undefined) {
83
+ q = q.where({ passportId: opts.passportId });
84
+ }
85
+ return q.all();
86
+ }
87
+ async patchReputation(id, patch) {
88
+ const existing = await this.db.orm.public.ReputationWrite.where({
89
+ id,
90
+ }).first();
91
+ if (!existing)
92
+ return null;
93
+ return this.db.orm.public.ReputationWrite.where({ id }).update({
94
+ status: patch.status ?? existing.status,
95
+ agentId: patch.agentId !== undefined ? patch.agentId : existing.agentId,
96
+ txHash: patch.txHash !== undefined ? patch.txHash : existing.txHash,
97
+ feedbackUri: patch.feedbackUri !== undefined
98
+ ? patch.feedbackUri
99
+ : existing.feedbackUri,
100
+ feedbackHash: patch.feedbackHash !== undefined
101
+ ? patch.feedbackHash
102
+ : existing.feedbackHash,
103
+ attempts: patch.attempts ?? existing.attempts,
104
+ payload: patch.payload ?? existing.payload,
105
+ });
106
+ }
107
+ async enqueueOutbox(data) {
108
+ const existing = await this.db.orm.public.ChainTxOutbox.where({
109
+ idempotencyKey: data.idempotencyKey,
110
+ }).first();
111
+ if (existing)
112
+ return existing;
113
+ return this.db.orm.public.ChainTxOutbox.create({
114
+ status: "pending",
115
+ ...data,
116
+ });
117
+ }
118
+ async getOutboxByKey(idempotencyKey) {
119
+ return this.db.orm.public.ChainTxOutbox.where({
120
+ idempotencyKey,
121
+ }).first();
122
+ }
123
+ async listOutboxByStatus(status) {
124
+ return this.db.orm.public.ChainTxOutbox.where({ status })
125
+ .orderBy((o) => o.createdAt.asc())
126
+ .all();
127
+ }
128
+ async patchOutbox(id, patch) {
129
+ const existing = await this.db.orm.public.ChainTxOutbox.where({
130
+ id,
131
+ }).first();
132
+ if (!existing)
133
+ return null;
134
+ return this.db.orm.public.ChainTxOutbox.where({ id }).update({
135
+ status: patch.status ?? existing.status,
136
+ txHash: patch.txHash !== undefined ? patch.txHash : existing.txHash,
137
+ attempts: patch.attempts ?? existing.attempts,
138
+ lastError: patch.lastError !== undefined ? patch.lastError : existing.lastError,
139
+ payload: patch.payload ?? existing.payload,
140
+ });
141
+ }
142
+ }
@@ -0,0 +1,81 @@
1
+ import type { JsonValue } from "@prisma/orm-postgres/target/codec-types";
2
+ import type { Models } from "../prisma/contract.d.js";
3
+ import type { PrismaDb } from "./event-repository.js";
4
+ type BountyRow = Models.public_Bounty;
5
+ type ClaimRow = Models.public_BountyClaim;
6
+ type TransitionRow = Models.public_BountyTransition;
7
+ type OutcomeRow = Models.public_BountyOutcome;
8
+ type PassportOwnerRow = Models.public_PassportOwner;
9
+ export interface BountyUpsert {
10
+ status: string;
11
+ onchainJobId?: string | null;
12
+ jobAttempt?: number;
13
+ budgetUsdc?: string | null;
14
+ createdBy?: string | null;
15
+ payload: JsonValue;
16
+ }
17
+ export interface BountyClaimInsert {
18
+ bountyId: string;
19
+ jobAttempt: number;
20
+ passportId: string;
21
+ payoutWallet: string;
22
+ claimedAtMs: bigint;
23
+ leaseUntilMs: bigint;
24
+ state?: string;
25
+ payload: JsonValue;
26
+ }
27
+ export interface BountyTransitionInsert {
28
+ bountyId: string;
29
+ actor: string;
30
+ from: string;
31
+ to: string;
32
+ reason?: string | null;
33
+ atMs: bigint;
34
+ payload: JsonValue;
35
+ }
36
+ export interface BountyOutcomeInsert {
37
+ bountyId: string;
38
+ jobAttempt: number;
39
+ passportId?: string | null;
40
+ verdict: string;
41
+ reasonCodes?: JsonValue | null;
42
+ verdictMemoTx?: string | null;
43
+ verdictRejectTx?: string | null;
44
+ commitSha?: string | null;
45
+ payload: JsonValue;
46
+ }
47
+ export interface PassportOwnerUpsert {
48
+ owner: string;
49
+ blockNumber: bigint;
50
+ logIndex?: number | null;
51
+ payload: JsonValue;
52
+ }
53
+ export declare class BountyRepository {
54
+ private readonly db;
55
+ constructor(db: PrismaDb);
56
+ upsertBounty(bountyId: string, data: BountyUpsert): Promise<BountyRow>;
57
+ getBounty(bountyId: string): Promise<BountyRow | null>;
58
+ listBounties(opts?: {
59
+ status?: string;
60
+ limit?: number;
61
+ offset?: number;
62
+ }): Promise<BountyRow[]>;
63
+ listAllBounties(): Promise<BountyRow[]>;
64
+ insertClaim(data: BountyClaimInsert): Promise<ClaimRow>;
65
+ getClaim(bountyId: string, jobAttempt: number): Promise<ClaimRow | null>;
66
+ listExpiredClaims(nowMs: bigint): Promise<ClaimRow[]>;
67
+ listClaimsByPassport(passportId: string): Promise<ClaimRow[]>;
68
+ listAllClaims(): Promise<ClaimRow[]>;
69
+ patchClaimState(id: string, state: string): Promise<ClaimRow | null>;
70
+ insertTransition(data: BountyTransitionInsert): Promise<TransitionRow>;
71
+ listTransitions(bountyId: string): Promise<TransitionRow[]>;
72
+ listAllTransitions(): Promise<TransitionRow[]>;
73
+ insertOutcome(data: BountyOutcomeInsert): Promise<OutcomeRow>;
74
+ listOutcomesByPassport(passportId: string): Promise<OutcomeRow[]>;
75
+ listAllOutcomes(): Promise<OutcomeRow[]>;
76
+ upsertPassportOwner(passportId: string, data: PassportOwnerUpsert): Promise<PassportOwnerRow>;
77
+ getPassportOwner(passportId: string): Promise<PassportOwnerRow | null>;
78
+ listPassportsByOwner(owner: string): Promise<PassportOwnerRow[]>;
79
+ listAllPassportOwners(): Promise<PassportOwnerRow[]>;
80
+ }
81
+ export {};
@@ -0,0 +1,111 @@
1
+ export class BountyRepository {
2
+ db;
3
+ constructor(db) {
4
+ this.db = db;
5
+ }
6
+ async upsertBounty(bountyId, data) {
7
+ return this.db.orm.public.Bounty.upsert({
8
+ create: { bountyId, ...data },
9
+ update: { ...data },
10
+ conflictOn: { bountyId },
11
+ });
12
+ }
13
+ async getBounty(bountyId) {
14
+ return this.db.orm.public.Bounty.where({ bountyId }).first();
15
+ }
16
+ async listBounties(opts) {
17
+ let q = this.db.orm.public.Bounty.orderBy((b) => b.createdAt.desc());
18
+ if (opts?.status !== undefined)
19
+ q = q.where({ status: opts.status });
20
+ if (opts?.offset !== undefined)
21
+ q = q.offset(opts.offset);
22
+ if (opts?.limit !== undefined)
23
+ q = q.limit(opts.limit);
24
+ return q.all();
25
+ }
26
+ async listAllBounties() {
27
+ return this.db.orm.public.Bounty.all();
28
+ }
29
+ async insertClaim(data) {
30
+ return this.db.orm.public.BountyClaim.upsert({
31
+ create: { state: "open", ...data },
32
+ update: { state: "open", ...data },
33
+ conflictOn: { bountyId: data.bountyId, jobAttempt: data.jobAttempt },
34
+ });
35
+ }
36
+ async getClaim(bountyId, jobAttempt) {
37
+ return this.db.orm.public.BountyClaim.where({
38
+ bountyId,
39
+ jobAttempt,
40
+ }).first();
41
+ }
42
+ async listExpiredClaims(nowMs) {
43
+ const open = await this.db.orm.public.BountyClaim.where({
44
+ state: "open",
45
+ }).all();
46
+ return open.filter((c) => BigInt(c.leaseUntilMs) < nowMs);
47
+ }
48
+ async listClaimsByPassport(passportId) {
49
+ return this.db.orm.public.BountyClaim.where({ passportId })
50
+ .orderBy((c) => c.createdAt.desc())
51
+ .all();
52
+ }
53
+ async listAllClaims() {
54
+ return this.db.orm.public.BountyClaim.all();
55
+ }
56
+ async patchClaimState(id, state) {
57
+ return this.db.orm.public.BountyClaim.where({ id }).update({
58
+ state,
59
+ });
60
+ }
61
+ async insertTransition(data) {
62
+ return this.db.orm.public.BountyTransition.create(data);
63
+ }
64
+ async listTransitions(bountyId) {
65
+ return this.db.orm.public.BountyTransition.where({ bountyId })
66
+ .orderBy((t) => t.atMs.asc())
67
+ .all();
68
+ }
69
+ async listAllTransitions() {
70
+ return this.db.orm.public.BountyTransition.all();
71
+ }
72
+ async insertOutcome(data) {
73
+ return this.db.orm.public.BountyOutcome.upsert({
74
+ create: { ...data },
75
+ update: { ...data },
76
+ conflictOn: { bountyId: data.bountyId, jobAttempt: data.jobAttempt },
77
+ });
78
+ }
79
+ async listOutcomesByPassport(passportId) {
80
+ return this.db.orm.public.BountyOutcome.where({ passportId })
81
+ .orderBy((o) => o.createdAt.desc())
82
+ .all();
83
+ }
84
+ async listAllOutcomes() {
85
+ return this.db.orm.public.BountyOutcome.all();
86
+ }
87
+ async upsertPassportOwner(passportId, data) {
88
+ const existing = await this.db.orm.public.PassportOwner.where({
89
+ passportId,
90
+ }).first();
91
+ if (existing && BigInt(existing.blockNumber) >= BigInt(data.blockNumber)) {
92
+ return existing;
93
+ }
94
+ return this.db.orm.public.PassportOwner.upsert({
95
+ create: { passportId, ...data },
96
+ update: { ...data },
97
+ conflictOn: { passportId },
98
+ });
99
+ }
100
+ async getPassportOwner(passportId) {
101
+ return this.db.orm.public.PassportOwner.where({
102
+ passportId,
103
+ }).first();
104
+ }
105
+ async listPassportsByOwner(owner) {
106
+ return this.db.orm.public.PassportOwner.where({ owner }).all();
107
+ }
108
+ async listAllPassportOwners() {
109
+ return this.db.orm.public.PassportOwner.all();
110
+ }
111
+ }
@@ -0,0 +1,22 @@
1
+ import type { EconomicEvent } from "@agentbadge/econ-events";
2
+ import type { PrismaDb } from "./event-repository.js";
3
+ import { type AppendResult, type EconEventStored, type EconLedgerStore, type ListOpts } from "./econ-ledger-store.js";
4
+ import { type TrustEdgeStore } from "./trust-edge-store.js";
5
+ type Orm = PrismaDb["orm"];
6
+ export declare class EconLedgerRepository implements EconLedgerStore<Orm> {
7
+ private readonly db;
8
+ private readonly edges?;
9
+ constructor(db: PrismaDb, edges?: TrustEdgeStore<Orm> | undefined);
10
+ append(events: EconomicEvent[]): Promise<AppendResult[]>;
11
+ appendInTx(events: EconomicEvent[], extra: (tx: Orm) => Promise<void>): Promise<AppendResult[]>;
12
+ getById(id: string): Promise<EconEventStored | null>;
13
+ getByKey(idempotencyKey: string): Promise<EconEventStored | null>;
14
+ listByAgent(agent: string, opts?: ListOpts): Promise<EconEventStored[]>;
15
+ listByPair(a: string, b: string, opts?: ListOpts): Promise<EconEventStored[]>;
16
+ listBySourceId(source: string, sourceId: string, opts?: ListOpts): Promise<EconEventStored[]>;
17
+ scan(fromLedgerSeq: bigint, opts?: {
18
+ limit?: number;
19
+ }): Promise<EconEventStored[]>;
20
+ private page;
21
+ }
22
+ export {};
@@ -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
+ }