@agentbadge/database 0.6.1 → 0.6.3

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,624 @@
1
+ import { TERMINAL_ATTEMPT_STATUSES } from "./payment-store.js";
2
+ const num = (v) => Number(v);
3
+ const numOrNull = (v) => v === null || v === undefined ? null : Number(v);
4
+ const dec = (v) => String(v);
5
+ const toPaymentRow = (r) => ({
6
+ id: r.id,
7
+ reference: r.reference,
8
+ idempotencyKey: r.idempotencyKey,
9
+ customerId: r.customerId,
10
+ agentId: r.agentId,
11
+ productId: r.productId,
12
+ orderId: r.orderId,
13
+ amount: dec(r.amount),
14
+ currency: r.currency,
15
+ status: r.status,
16
+ purpose: r.purpose,
17
+ expiresAtMs: numOrNull(r.expiresAtMs),
18
+ createdAtMs: num(r.createdAtMs),
19
+ updatedAtMs: num(r.updatedAtMs),
20
+ payload: r.payload,
21
+ createdAt: r.createdAt,
22
+ updatedAt: r.updatedAt,
23
+ });
24
+ const toAttemptRow = (r) => ({
25
+ id: r.id,
26
+ paymentId: r.paymentId,
27
+ provider: r.provider,
28
+ network: r.network,
29
+ token: r.token,
30
+ amount: dec(r.amount),
31
+ currency: r.currency,
32
+ status: r.status,
33
+ providerReference: r.providerReference,
34
+ transactionHash: r.transactionHash,
35
+ expiresAtMs: numOrNull(r.expiresAtMs),
36
+ confirmedAtMs: numOrNull(r.confirmedAtMs),
37
+ payload: r.payload,
38
+ createdAt: r.createdAt,
39
+ updatedAt: r.updatedAt,
40
+ });
41
+ const toReceiptRow = (r) => ({
42
+ id: r.id,
43
+ paymentId: r.paymentId,
44
+ attemptId: r.attemptId,
45
+ provider: r.provider,
46
+ externalReference: r.externalReference,
47
+ network: r.network,
48
+ transactionHash: r.transactionHash,
49
+ payer: r.payer,
50
+ recipient: r.recipient,
51
+ amount: dec(r.amount),
52
+ asset: r.asset,
53
+ verifiedAtMs: num(r.verifiedAtMs),
54
+ payload: r.payload,
55
+ createdAt: r.createdAt,
56
+ });
57
+ const toEventRow = (r) => ({
58
+ id: r.id,
59
+ entity: r.entity,
60
+ paymentId: r.paymentId,
61
+ attemptId: r.attemptId,
62
+ from: r.from,
63
+ to: r.to,
64
+ actor: r.actor,
65
+ reason: r.reason,
66
+ atMs: num(r.atMs),
67
+ payload: r.payload,
68
+ createdAt: r.createdAt,
69
+ });
70
+ const toProductRow = (r) => ({
71
+ id: r.id,
72
+ code: r.code,
73
+ name: r.name,
74
+ description: r.description,
75
+ category: r.category,
76
+ active: r.active,
77
+ payload: r.payload,
78
+ createdAt: r.createdAt,
79
+ updatedAt: r.updatedAt,
80
+ });
81
+ const toPriceRow = (r) => ({
82
+ id: r.id,
83
+ productId: r.productId,
84
+ amount: dec(r.amount),
85
+ currency: r.currency,
86
+ billingType: r.billingType,
87
+ interval: r.interval,
88
+ active: r.active,
89
+ payload: r.payload,
90
+ createdAt: r.createdAt,
91
+ updatedAt: r.updatedAt,
92
+ });
93
+ const toUsageRecordRow = (r) => ({
94
+ id: r.id,
95
+ paymentId: r.paymentId,
96
+ agentId: r.agentId,
97
+ resource: r.resource,
98
+ requestId: r.requestId,
99
+ amount: dec(r.amount),
100
+ currency: r.currency,
101
+ network: r.network,
102
+ payerAddress: r.payerAddress,
103
+ txHash: r.txHash,
104
+ createdAtMs: num(r.createdAtMs),
105
+ payload: r.payload,
106
+ createdAt: r.createdAt,
107
+ });
108
+ export class PaymentRepository {
109
+ db;
110
+ constructor(db) {
111
+ this.db = db;
112
+ }
113
+ get orm() {
114
+ return this.db.orm.public.Payment;
115
+ }
116
+ async create(p) {
117
+ if (await this.getById(p.id))
118
+ return null;
119
+ if (await this.getByReference(p.reference))
120
+ return null;
121
+ if (p.idempotencyKey != null &&
122
+ (await this.getByIdempotencyKey(p.idempotencyKey))) {
123
+ return null;
124
+ }
125
+ const row = await this.orm.create({
126
+ id: p.id,
127
+ reference: p.reference,
128
+ idempotencyKey: p.idempotencyKey ?? null,
129
+ customerId: p.customerId ?? null,
130
+ agentId: p.agentId ?? null,
131
+ productId: p.productId ?? null,
132
+ orderId: p.orderId ?? null,
133
+ amount: p.amount,
134
+ currency: p.currency ?? "USD",
135
+ status: p.status,
136
+ purpose: p.purpose,
137
+ expiresAtMs: p.expiresAtMs != null
138
+ ? BigInt(p.expiresAtMs)
139
+ : null,
140
+ createdAtMs: BigInt(p.createdAtMs),
141
+ updatedAtMs: BigInt(p.updatedAtMs),
142
+ payload: p.payload,
143
+ });
144
+ return toPaymentRow(row);
145
+ }
146
+ async getById(id) {
147
+ const r = await this.orm.where({ id }).first();
148
+ return r ? toPaymentRow(r) : null;
149
+ }
150
+ async getByReference(reference) {
151
+ const r = await this.orm.where({ reference }).first();
152
+ return r ? toPaymentRow(r) : null;
153
+ }
154
+ async getByIdempotencyKey(key) {
155
+ const r = await this.orm.where({ idempotencyKey: key }).first();
156
+ return r ? toPaymentRow(r) : null;
157
+ }
158
+ async listByCustomer(customerId) {
159
+ const rows = await this.orm
160
+ .orderBy((e) => e.createdAtMs.desc())
161
+ .where({ customerId })
162
+ .all();
163
+ return rows.map(toPaymentRow);
164
+ }
165
+ async applyStatus(id, expectedFrom, to, updatedAtMs) {
166
+ const row = await this.orm.where({ id, status: expectedFrom }).update({
167
+ status: to,
168
+ updatedAtMs: BigInt(updatedAtMs),
169
+ });
170
+ return row ? toPaymentRow(row) : null;
171
+ }
172
+ async listExpired(nowMs) {
173
+ const out = [];
174
+ for (const status of ["PENDING", "PROCESSING"]) {
175
+ const rows = await this.orm.where({ status }).all();
176
+ for (const r of rows) {
177
+ const exp = numOrNull(r.expiresAtMs);
178
+ if (exp !== null && exp < nowMs)
179
+ out.push(toPaymentRow(r));
180
+ }
181
+ }
182
+ return out;
183
+ }
184
+ }
185
+ export class PaymentAttemptRepository {
186
+ db;
187
+ constructor(db) {
188
+ this.db = db;
189
+ }
190
+ get orm() {
191
+ return this.db.orm.public.PaymentAttempt;
192
+ }
193
+ async create(a) {
194
+ if (await this.getById(a.id))
195
+ return null;
196
+ if (a.providerReference != null &&
197
+ (await this.getByProviderRef(a.provider, a.providerReference))) {
198
+ return null;
199
+ }
200
+ if (a.transactionHash != null &&
201
+ (await this.getByProviderTx(a.provider, a.transactionHash))) {
202
+ return null;
203
+ }
204
+ const row = await this.orm.create({
205
+ id: a.id,
206
+ paymentId: a.paymentId,
207
+ provider: a.provider,
208
+ network: a.network ?? null,
209
+ token: a.token ?? null,
210
+ amount: a.amount,
211
+ currency: a.currency,
212
+ status: a.status,
213
+ providerReference: a.providerReference ?? null,
214
+ transactionHash: a.transactionHash ?? null,
215
+ expiresAtMs: a.expiresAtMs != null
216
+ ? BigInt(a.expiresAtMs)
217
+ : null,
218
+ confirmedAtMs: a.confirmedAtMs != null
219
+ ? BigInt(a.confirmedAtMs)
220
+ : null,
221
+ payload: a.payload,
222
+ });
223
+ return toAttemptRow(row);
224
+ }
225
+ async getById(id) {
226
+ const r = await this.orm.where({ id }).first();
227
+ return r ? toAttemptRow(r) : null;
228
+ }
229
+ async listByPayment(paymentId) {
230
+ const rows = await this.orm.where({ paymentId }).all();
231
+ return rows.map(toAttemptRow);
232
+ }
233
+ async getByProviderRef(provider, providerReference) {
234
+ const r = await this.orm
235
+ .where({ provider, providerReference })
236
+ .first();
237
+ return r ? toAttemptRow(r) : null;
238
+ }
239
+ async getByProviderTx(provider, transactionHash) {
240
+ const r = await this.orm
241
+ .where({ provider, transactionHash })
242
+ .first();
243
+ return r ? toAttemptRow(r) : null;
244
+ }
245
+ async getByTxHash(transactionHash) {
246
+ const r = await this.orm.where({ transactionHash }).first();
247
+ return r ? toAttemptRow(r) : null;
248
+ }
249
+ async applyStatus(id, expectedFrom, to, _updatedAtMs, patch) {
250
+ const row = await this.orm.where({ id, status: expectedFrom }).update({
251
+ status: to,
252
+ ...(patch?.confirmedAtMs !== undefined
253
+ ? {
254
+ confirmedAtMs: BigInt(patch.confirmedAtMs),
255
+ }
256
+ : {}),
257
+ ...(patch?.transactionHash !== undefined
258
+ ? { transactionHash: patch.transactionHash }
259
+ : {}),
260
+ ...(patch?.providerReference !== undefined
261
+ ? { providerReference: patch.providerReference }
262
+ : {}),
263
+ });
264
+ return row ? toAttemptRow(row) : null;
265
+ }
266
+ async listExpired(nowMs) {
267
+ const out = [];
268
+ const openStatuses = [
269
+ "CREATED",
270
+ "PENDING",
271
+ "PROCESSING",
272
+ ].filter((s) => !TERMINAL_ATTEMPT_STATUSES.includes(s));
273
+ for (const status of openStatuses) {
274
+ const rows = await this.orm.where({ status }).all();
275
+ for (const r of rows) {
276
+ const exp = numOrNull(r.expiresAtMs);
277
+ if (exp !== null && exp < nowMs)
278
+ out.push(toAttemptRow(r));
279
+ }
280
+ }
281
+ return out;
282
+ }
283
+ async listPayable(nowMs) {
284
+ const out = [];
285
+ const openStatuses = ["CREATED", "PENDING", "PROCESSING"].filter((s) => !TERMINAL_ATTEMPT_STATUSES.includes(s));
286
+ for (const status of openStatuses) {
287
+ const rows = await this.orm.where({ status }).all();
288
+ for (const r of rows) {
289
+ const exp = numOrNull(r.expiresAtMs);
290
+ if (exp === null || exp > nowMs)
291
+ out.push(toAttemptRow(r));
292
+ }
293
+ }
294
+ return out;
295
+ }
296
+ async listRecentTerminal(sinceMs) {
297
+ const out = [];
298
+ for (const status of TERMINAL_ATTEMPT_STATUSES) {
299
+ const rows = await this.orm
300
+ .where({ status })
301
+ .all();
302
+ for (const r of rows) {
303
+ const stamp = r.updatedAt
304
+ ? new Date(r.updatedAt).getTime()
305
+ : (numOrNull(r.confirmedAtMs) ?? 0);
306
+ if (stamp >= sinceMs)
307
+ out.push(toAttemptRow(r));
308
+ }
309
+ }
310
+ return out;
311
+ }
312
+ }
313
+ export class PaymentReceiptRepository {
314
+ db;
315
+ constructor(db) {
316
+ this.db = db;
317
+ }
318
+ get orm() {
319
+ return this.db.orm.public.PaymentReceipt;
320
+ }
321
+ async append(r) {
322
+ if (await this.getById(r.id))
323
+ return null;
324
+ if (await this.getByExternalRef(r.provider, r.externalReference)) {
325
+ return null;
326
+ }
327
+ const row = await this.orm.create({
328
+ id: r.id,
329
+ paymentId: r.paymentId,
330
+ attemptId: r.attemptId,
331
+ provider: r.provider,
332
+ externalReference: r.externalReference,
333
+ network: r.network ?? null,
334
+ transactionHash: r.transactionHash ?? null,
335
+ payer: r.payer ?? null,
336
+ recipient: r.recipient ?? null,
337
+ amount: r.amount,
338
+ asset: r.asset,
339
+ verifiedAtMs: BigInt(r.verifiedAtMs),
340
+ payload: r.payload,
341
+ });
342
+ return toReceiptRow(row);
343
+ }
344
+ async getById(id) {
345
+ const r = await this.orm.where({ id }).first();
346
+ return r ? toReceiptRow(r) : null;
347
+ }
348
+ async listByPayment(paymentId) {
349
+ const rows = await this.orm.where({ paymentId }).all();
350
+ return rows.map(toReceiptRow);
351
+ }
352
+ async getByExternalRef(provider, externalReference) {
353
+ const r = await this.orm
354
+ .where({ provider, externalReference })
355
+ .first();
356
+ return r ? toReceiptRow(r) : null;
357
+ }
358
+ }
359
+ export class PaymentEventRepository {
360
+ db;
361
+ constructor(db) {
362
+ this.db = db;
363
+ }
364
+ get orm() {
365
+ return this.db.orm.public.PaymentEvent;
366
+ }
367
+ async append(e) {
368
+ const existing = await this.orm.where({ id: e.id }).first();
369
+ if (existing)
370
+ return null;
371
+ const row = await this.orm.create({
372
+ id: e.id,
373
+ entity: e.entity,
374
+ paymentId: e.paymentId,
375
+ attemptId: e.attemptId ?? null,
376
+ from: e.from,
377
+ to: e.to,
378
+ actor: e.actor,
379
+ reason: e.reason ?? null,
380
+ atMs: BigInt(e.atMs),
381
+ payload: e.payload,
382
+ });
383
+ return toEventRow(row);
384
+ }
385
+ async listByPayment(paymentId) {
386
+ const rows = await this.orm
387
+ .orderBy((e) => e.atMs.asc())
388
+ .where({ paymentId })
389
+ .all();
390
+ return rows.map(toEventRow);
391
+ }
392
+ async listByAttempt(attemptId) {
393
+ const rows = await this.orm
394
+ .orderBy((e) => e.atMs.asc())
395
+ .where({ attemptId })
396
+ .all();
397
+ return rows.map(toEventRow);
398
+ }
399
+ }
400
+ export class PaymentProductRepository {
401
+ db;
402
+ constructor(db) {
403
+ this.db = db;
404
+ }
405
+ get orm() {
406
+ return this.db.orm.public.PaymentProduct;
407
+ }
408
+ async upsert(p) {
409
+ const existing = await this.orm.where({ code: p.code }).first();
410
+ if (existing) {
411
+ const updated = await this.orm.where({ id: existing.id }).update({
412
+ name: p.name,
413
+ description: p.description ?? null,
414
+ category: p.category,
415
+ active: p.active ?? true,
416
+ payload: p.payload,
417
+ });
418
+ return toProductRow(updated);
419
+ }
420
+ const row = await this.orm.create({
421
+ id: p.id,
422
+ code: p.code,
423
+ name: p.name,
424
+ description: p.description ?? null,
425
+ category: p.category,
426
+ active: p.active ?? true,
427
+ payload: p.payload,
428
+ });
429
+ return toProductRow(row);
430
+ }
431
+ async getById(id) {
432
+ const r = await this.orm.where({ id }).first();
433
+ return r ? toProductRow(r) : null;
434
+ }
435
+ async getByCode(code) {
436
+ const r = await this.orm.where({ code }).first();
437
+ return r ? toProductRow(r) : null;
438
+ }
439
+ async list(opts) {
440
+ const rows = opts?.activeOnly
441
+ ? await this.orm.where({ active: true }).all()
442
+ : await this.orm.all();
443
+ return rows.map(toProductRow);
444
+ }
445
+ }
446
+ export class PaymentPriceRepository {
447
+ db;
448
+ constructor(db) {
449
+ this.db = db;
450
+ }
451
+ get orm() {
452
+ return this.db.orm.public.PaymentPrice;
453
+ }
454
+ async create(p) {
455
+ if (await this.getById(p.id))
456
+ return null;
457
+ const row = await this.orm.create({
458
+ id: p.id,
459
+ productId: p.productId,
460
+ amount: p.amount,
461
+ currency: p.currency ?? "USD",
462
+ billingType: p.billingType,
463
+ interval: p.interval ?? null,
464
+ active: p.active ?? true,
465
+ payload: p.payload,
466
+ });
467
+ return toPriceRow(row);
468
+ }
469
+ async getById(id) {
470
+ const r = await this.orm.where({ id }).first();
471
+ return r ? toPriceRow(r) : null;
472
+ }
473
+ async listByProduct(productId, opts) {
474
+ const rows = opts?.activeOnly
475
+ ? await this.orm.where({ productId, active: true }).all()
476
+ : await this.orm.where({ productId }).all();
477
+ return rows.map(toPriceRow);
478
+ }
479
+ }
480
+ const toExceptionRow = (r) => ({
481
+ id: r.id,
482
+ paymentId: r.paymentId ?? undefined,
483
+ attemptId: r.attemptId ?? undefined,
484
+ kind: r.kind,
485
+ severity: r.severity,
486
+ details: r.details && typeof r.details === "object"
487
+ ? r.details
488
+ : undefined,
489
+ status: r.status,
490
+ createdAtMs: numOrNull(r.createdAtMs) ?? 0,
491
+ resolvedAtMs: numOrNull(r.resolvedAtMs),
492
+ resolutionNote: r.resolutionNote ?? null,
493
+ createdAt: r.createdAt,
494
+ });
495
+ export class PaymentExceptionRepository {
496
+ db;
497
+ constructor(db) {
498
+ this.db = db;
499
+ }
500
+ get orm() {
501
+ return this.db.orm.public.PaymentException;
502
+ }
503
+ async append(e) {
504
+ if (await this.getById(e.id))
505
+ return null;
506
+ const row = await this.orm.create({
507
+ id: e.id,
508
+ paymentId: e.paymentId ?? null,
509
+ attemptId: e.attemptId ?? null,
510
+ kind: e.kind,
511
+ severity: e.severity,
512
+ details: (e.details ?? null),
513
+ status: e.status,
514
+ createdAtMs: e.createdAtMs,
515
+ });
516
+ return toExceptionRow(row);
517
+ }
518
+ async getById(id) {
519
+ const r = await this.orm.where({ id }).first();
520
+ return r ? toExceptionRow(r) : null;
521
+ }
522
+ async listByPayment(paymentId) {
523
+ const rows = await this.orm.where({ paymentId }).all();
524
+ return rows.map(toExceptionRow);
525
+ }
526
+ async list(opts = {}) {
527
+ const rows = await this.orm.all();
528
+ let out = rows
529
+ .map(toExceptionRow)
530
+ .filter((r) => (opts.status === undefined || r.status === opts.status) &&
531
+ (opts.kind === undefined || r.kind === opts.kind) &&
532
+ (opts.sinceMs === undefined || r.createdAtMs >= opts.sinceMs));
533
+ out.sort((a, b) => b.createdAtMs - a.createdAtMs);
534
+ if (opts.limit !== undefined)
535
+ out = out.slice(0, opts.limit);
536
+ return out;
537
+ }
538
+ async resolve(id, status, note) {
539
+ const cur = await this.getById(id);
540
+ if (!cur || cur.status !== "OPEN")
541
+ return null;
542
+ const row = await this.orm.where({ id, status: "OPEN" }).update({
543
+ status,
544
+ resolvedAtMs: Date.now(),
545
+ resolutionNote: note ?? null,
546
+ });
547
+ return row ? toExceptionRow(row) : null;
548
+ }
549
+ }
550
+ export class UsageRecordRepository {
551
+ db;
552
+ constructor(db) {
553
+ this.db = db;
554
+ }
555
+ get orm() {
556
+ return this.db.orm.public.UsageRecord;
557
+ }
558
+ async append(r) {
559
+ if (await this.getById(r.id))
560
+ return null;
561
+ if (await this.getByRequestId(r.requestId))
562
+ return null;
563
+ const row = await this.orm.create({
564
+ id: r.id,
565
+ paymentId: r.paymentId,
566
+ agentId: r.agentId ?? null,
567
+ resource: r.resource,
568
+ requestId: r.requestId,
569
+ amount: r.amount,
570
+ currency: r.currency ?? "USDC",
571
+ network: r.network,
572
+ payerAddress: r.payerAddress,
573
+ txHash: r.txHash ?? null,
574
+ createdAtMs: BigInt(r.createdAtMs),
575
+ payload: r.payload,
576
+ });
577
+ return toUsageRecordRow(row);
578
+ }
579
+ async getById(id) {
580
+ const r = await this.orm.where({ id }).first();
581
+ return r ? toUsageRecordRow(r) : null;
582
+ }
583
+ async getByRequestId(requestId) {
584
+ const r = await this.orm.where({ requestId }).first();
585
+ return r ? toUsageRecordRow(r) : null;
586
+ }
587
+ async listByPayment(paymentId) {
588
+ const rows = await this.orm
589
+ .orderBy((e) => e.createdAtMs.desc())
590
+ .where({ paymentId })
591
+ .all();
592
+ return rows.map(toUsageRecordRow);
593
+ }
594
+ async listByAgent(agentId, limit) {
595
+ let q = this.orm
596
+ .orderBy((e) => e.createdAtMs.desc())
597
+ .where({ agentId });
598
+ if (limit !== undefined)
599
+ q = q.limit(limit);
600
+ const rows = await q.all();
601
+ return rows.map(toUsageRecordRow);
602
+ }
603
+ async listByResource(resource, limit) {
604
+ let q = this.orm
605
+ .orderBy((e) => e.createdAtMs.desc())
606
+ .where({ resource });
607
+ if (limit !== undefined)
608
+ q = q.limit(limit);
609
+ const rows = await q.all();
610
+ return rows.map(toUsageRecordRow);
611
+ }
612
+ }
613
+ export function createPrismaPaymentStores(db) {
614
+ return {
615
+ payments: new PaymentRepository(db),
616
+ attempts: new PaymentAttemptRepository(db),
617
+ receipts: new PaymentReceiptRepository(db),
618
+ events: new PaymentEventRepository(db),
619
+ exceptions: new PaymentExceptionRepository(db),
620
+ products: new PaymentProductRepository(db),
621
+ prices: new PaymentPriceRepository(db),
622
+ usageRecords: new UsageRecordRepository(db),
623
+ };
624
+ }