@wopr-network/platform-core 1.14.8 → 1.15.0

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.
Files changed (116) hide show
  1. package/dist/account/deletion-executor-repository.d.ts +2 -2
  2. package/dist/account/deletion-executor-repository.js +5 -5
  3. package/dist/{monetization/payram → billing/crypto}/cents-credits-boundary.test.js +14 -17
  4. package/dist/billing/{payram → crypto}/charge-store.d.ts +17 -13
  5. package/dist/billing/{payram → crypto}/charge-store.js +21 -18
  6. package/dist/billing/crypto/charge-store.test.js +64 -0
  7. package/dist/billing/crypto/checkout.d.ts +18 -0
  8. package/dist/billing/crypto/checkout.js +35 -0
  9. package/dist/billing/crypto/checkout.test.js +71 -0
  10. package/dist/billing/crypto/client.d.ts +39 -0
  11. package/dist/billing/crypto/client.js +72 -0
  12. package/dist/billing/crypto/client.test.js +100 -0
  13. package/dist/billing/crypto/index.d.ts +9 -0
  14. package/dist/billing/crypto/index.js +5 -0
  15. package/dist/billing/crypto/types.d.ts +61 -0
  16. package/dist/billing/crypto/types.js +24 -0
  17. package/dist/billing/crypto/webhook.d.ts +34 -0
  18. package/dist/billing/crypto/webhook.js +107 -0
  19. package/dist/billing/crypto/webhook.test.js +266 -0
  20. package/dist/billing/index.d.ts +1 -1
  21. package/dist/billing/index.js +2 -2
  22. package/dist/billing/payment-processor.d.ts +3 -3
  23. package/dist/credits/credit-ledger.d.ts +3 -3
  24. package/dist/credits/credit-ledger.js +3 -3
  25. package/dist/db/schema/credits.js +1 -1
  26. package/dist/db/schema/{payram.d.ts → crypto.d.ts} +17 -13
  27. package/dist/db/schema/crypto.js +25 -0
  28. package/dist/db/schema/index.d.ts +1 -1
  29. package/dist/db/schema/index.js +1 -1
  30. package/dist/monetization/crypto/__tests__/webhook.test.js +249 -0
  31. package/dist/monetization/crypto/index.d.ts +4 -0
  32. package/dist/monetization/crypto/index.js +2 -0
  33. package/dist/monetization/crypto/webhook.d.ts +24 -0
  34. package/dist/monetization/crypto/webhook.js +88 -0
  35. package/dist/monetization/index.d.ts +3 -3
  36. package/dist/monetization/index.js +1 -1
  37. package/dist/monetization/repository-types.d.ts +1 -1
  38. package/dist/observability/pagerduty.test.js +1 -0
  39. package/drizzle/migrations/0004_crypto_charges.sql +25 -0
  40. package/drizzle/migrations/meta/_journal.json +7 -0
  41. package/package.json +1 -3
  42. package/src/account/deletion-executor-repository.ts +6 -6
  43. package/src/billing/{payram → crypto}/cents-credits-boundary.test.ts +14 -17
  44. package/src/billing/crypto/charge-store.test.ts +81 -0
  45. package/src/billing/{payram → crypto}/charge-store.ts +28 -25
  46. package/src/billing/crypto/checkout.test.ts +93 -0
  47. package/src/billing/crypto/checkout.ts +48 -0
  48. package/src/billing/crypto/client.test.ts +132 -0
  49. package/src/billing/crypto/client.ts +86 -0
  50. package/src/billing/crypto/index.ts +15 -0
  51. package/src/billing/crypto/types.ts +83 -0
  52. package/src/billing/crypto/webhook.test.ts +340 -0
  53. package/src/billing/crypto/webhook.ts +136 -0
  54. package/src/billing/index.ts +2 -2
  55. package/src/billing/payment-processor.ts +3 -3
  56. package/src/credits/credit-ledger.ts +3 -3
  57. package/src/db/schema/credits.ts +1 -1
  58. package/src/db/schema/crypto.ts +30 -0
  59. package/src/db/schema/index.ts +1 -1
  60. package/src/monetization/crypto/__tests__/webhook.test.ts +327 -0
  61. package/src/monetization/crypto/index.ts +23 -0
  62. package/src/monetization/crypto/webhook.ts +115 -0
  63. package/src/monetization/index.ts +23 -21
  64. package/src/monetization/repository-types.ts +2 -2
  65. package/src/observability/pagerduty.test.ts +1 -0
  66. package/dist/billing/payram/cents-credits-boundary.test.js +0 -75
  67. package/dist/billing/payram/charge-store.test.js +0 -64
  68. package/dist/billing/payram/checkout.d.ts +0 -15
  69. package/dist/billing/payram/checkout.js +0 -24
  70. package/dist/billing/payram/checkout.test.js +0 -74
  71. package/dist/billing/payram/client.d.ts +0 -7
  72. package/dist/billing/payram/client.js +0 -15
  73. package/dist/billing/payram/client.test.js +0 -52
  74. package/dist/billing/payram/index.d.ts +0 -8
  75. package/dist/billing/payram/index.js +0 -4
  76. package/dist/billing/payram/types.d.ts +0 -40
  77. package/dist/billing/payram/webhook.d.ts +0 -19
  78. package/dist/billing/payram/webhook.js +0 -71
  79. package/dist/billing/payram/webhook.test.d.ts +0 -7
  80. package/dist/billing/payram/webhook.test.js +0 -249
  81. package/dist/db/schema/payram.js +0 -21
  82. package/dist/monetization/payram/charge-store.test.d.ts +0 -1
  83. package/dist/monetization/payram/charge-store.test.js +0 -64
  84. package/dist/monetization/payram/checkout.test.d.ts +0 -1
  85. package/dist/monetization/payram/checkout.test.js +0 -73
  86. package/dist/monetization/payram/client.test.d.ts +0 -1
  87. package/dist/monetization/payram/client.test.js +0 -52
  88. package/dist/monetization/payram/index.d.ts +0 -4
  89. package/dist/monetization/payram/index.js +0 -2
  90. package/dist/monetization/payram/webhook.d.ts +0 -17
  91. package/dist/monetization/payram/webhook.js +0 -71
  92. package/dist/monetization/payram/webhook.test.d.ts +0 -7
  93. package/dist/monetization/payram/webhook.test.js +0 -247
  94. package/src/billing/payram/charge-store.test.ts +0 -84
  95. package/src/billing/payram/checkout.test.ts +0 -99
  96. package/src/billing/payram/checkout.ts +0 -40
  97. package/src/billing/payram/client.test.ts +0 -62
  98. package/src/billing/payram/client.ts +0 -21
  99. package/src/billing/payram/index.ts +0 -14
  100. package/src/billing/payram/types.ts +0 -44
  101. package/src/billing/payram/webhook.test.ts +0 -320
  102. package/src/billing/payram/webhook.ts +0 -94
  103. package/src/db/schema/payram.ts +0 -26
  104. package/src/monetization/payram/cents-credits-boundary.test.ts +0 -84
  105. package/src/monetization/payram/charge-store.test.ts +0 -84
  106. package/src/monetization/payram/checkout.test.ts +0 -98
  107. package/src/monetization/payram/client.test.ts +0 -62
  108. package/src/monetization/payram/index.ts +0 -20
  109. package/src/monetization/payram/webhook.test.ts +0 -327
  110. package/src/monetization/payram/webhook.ts +0 -97
  111. /package/dist/billing/{payram → crypto}/cents-credits-boundary.test.d.ts +0 -0
  112. /package/dist/billing/{payram → crypto}/charge-store.test.d.ts +0 -0
  113. /package/dist/billing/{payram → crypto}/checkout.test.d.ts +0 -0
  114. /package/dist/billing/{payram → crypto}/client.test.d.ts +0 -0
  115. /package/dist/billing/{payram/types.js → crypto/webhook.test.d.ts} +0 -0
  116. /package/dist/monetization/{payram/cents-credits-boundary.test.d.ts → crypto/__tests__/webhook.test.d.ts} +0 -0
@@ -1,249 +0,0 @@
1
- /**
2
- * Unit tests for PayRam webhook handler (WOP-407).
3
- *
4
- * Covers FILLED/OVER_FILLED crediting the ledger, PARTIALLY_FILLED/CANCELLED
5
- * no-op status, idempotency, replay guard, and bot reactivation.
6
- */
7
- import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
8
- import { DrizzleLedger } from "../../credits/ledger.js";
9
- import { createTestDb, truncateAllTables } from "../../test/db.js";
10
- import { DrizzleWebhookSeenRepository } from "../drizzle-webhook-seen-repository.js";
11
- import { noOpReplayGuard } from "../webhook-seen-repository.js";
12
- import { PayRamChargeRepository } from "./charge-store.js";
13
- import { handlePayRamWebhook } from "./webhook.js";
14
- function makePayload(overrides = {}) {
15
- return {
16
- reference_id: "ref-test-001",
17
- status: "FILLED",
18
- amount: "25.00",
19
- currency: "USDC",
20
- filled_amount: "25.00",
21
- ...overrides,
22
- };
23
- }
24
- // TOP OF FILE - shared across ALL describes
25
- let pool;
26
- let db;
27
- beforeAll(async () => {
28
- ({ db, pool } = await createTestDb());
29
- });
30
- afterAll(async () => {
31
- await pool.close();
32
- });
33
- describe("handlePayRamWebhook", () => {
34
- let chargeStore;
35
- let creditLedger;
36
- let deps;
37
- beforeEach(async () => {
38
- await truncateAllTables(pool);
39
- chargeStore = new PayRamChargeRepository(db);
40
- creditLedger = new DrizzleLedger(db);
41
- await creditLedger.seedSystemAccounts();
42
- deps = { chargeStore, creditLedger, replayGuard: noOpReplayGuard };
43
- // Create a default test charge
44
- await chargeStore.create("ref-test-001", "tenant-a", 2500);
45
- });
46
- // ---------------------------------------------------------------------------
47
- // FILLED / OVER_FILLED — should credit ledger
48
- // ---------------------------------------------------------------------------
49
- describe("FILLED status", () => {
50
- it("credits the ledger with the requested USD amount", async () => {
51
- const result = await handlePayRamWebhook(deps, makePayload({ status: "FILLED" }));
52
- expect(result.handled).toBe(true);
53
- expect(result.status).toBe("FILLED");
54
- expect(result.tenant).toBe("tenant-a");
55
- expect(result.creditedCents).toBe(2500);
56
- const balance = await creditLedger.balance("tenant-a");
57
- expect(balance.toCents()).toBe(2500);
58
- });
59
- it("uses payram: prefix on reference ID in credit transaction", async () => {
60
- await handlePayRamWebhook(deps, makePayload({ status: "FILLED" }));
61
- const history = await creditLedger.history("tenant-a");
62
- expect(history).toHaveLength(1);
63
- expect(history[0].referenceId).toBe("payram:ref-test-001");
64
- expect(history[0].entryType).toBe("purchase");
65
- });
66
- it("records fundingSource as payram", async () => {
67
- await handlePayRamWebhook(deps, makePayload({ status: "FILLED" }));
68
- const history = await creditLedger.history("tenant-a");
69
- expect(history[0].metadata?.fundingSource).toBe("payram");
70
- });
71
- it("marks the charge as credited after FILLED", async () => {
72
- await handlePayRamWebhook(deps, makePayload({ status: "FILLED" }));
73
- expect(await chargeStore.isCredited("ref-test-001")).toBe(true);
74
- });
75
- it("is idempotent — duplicate FILLED webhook does not double-credit", async () => {
76
- await handlePayRamWebhook(deps, makePayload({ status: "FILLED" }));
77
- const result2 = await handlePayRamWebhook(deps, makePayload({ status: "FILLED" }));
78
- expect(result2.handled).toBe(true);
79
- expect(result2.creditedCents).toBe(0);
80
- const balance = await creditLedger.balance("tenant-a");
81
- expect(balance.toCents()).toBe(2500); // Only credited once
82
- });
83
- });
84
- describe("OVER_FILLED status", () => {
85
- it("credits the requested USD amount (not the overpayment)", async () => {
86
- await chargeStore.create("ref-over-001", "tenant-b", 1000);
87
- const result = await handlePayRamWebhook(deps, makePayload({
88
- reference_id: "ref-over-001",
89
- status: "OVER_FILLED",
90
- filled_amount: "12.50", // Overpaid by $2.50
91
- currency: "ETH",
92
- }));
93
- expect(result.handled).toBe(true);
94
- expect(result.creditedCents).toBe(1000); // Only the requested amount
95
- expect((await creditLedger.balance("tenant-b")).toCents()).toBe(1000);
96
- });
97
- });
98
- // ---------------------------------------------------------------------------
99
- // Statuses that should NOT credit the ledger
100
- // ---------------------------------------------------------------------------
101
- describe("PARTIALLY_FILLED status", () => {
102
- it("does NOT credit the ledger", async () => {
103
- const result = await handlePayRamWebhook(deps, makePayload({ status: "PARTIALLY_FILLED" }));
104
- expect(result.handled).toBe(true);
105
- expect(result.tenant).toBe("tenant-a");
106
- expect(result.creditedCents).toBeUndefined();
107
- expect((await creditLedger.balance("tenant-a")).toCents()).toBe(0);
108
- });
109
- });
110
- describe("VERIFYING status", () => {
111
- it("does NOT credit the ledger", async () => {
112
- const result = await handlePayRamWebhook(deps, makePayload({ status: "VERIFYING" }));
113
- expect(result.handled).toBe(true);
114
- expect(result.creditedCents).toBeUndefined();
115
- expect((await creditLedger.balance("tenant-a")).toCents()).toBe(0);
116
- });
117
- });
118
- describe("OPEN status", () => {
119
- it("does NOT credit the ledger", async () => {
120
- const result = await handlePayRamWebhook(deps, makePayload({ status: "OPEN" }));
121
- expect(result.handled).toBe(true);
122
- expect(result.creditedCents).toBeUndefined();
123
- expect((await creditLedger.balance("tenant-a")).toCents()).toBe(0);
124
- });
125
- });
126
- describe("CANCELLED status", () => {
127
- it("does NOT credit the ledger", async () => {
128
- const result = await handlePayRamWebhook(deps, makePayload({ status: "CANCELLED" }));
129
- expect(result.handled).toBe(true);
130
- expect(result.creditedCents).toBeUndefined();
131
- expect((await creditLedger.balance("tenant-a")).toCents()).toBe(0);
132
- });
133
- });
134
- // ---------------------------------------------------------------------------
135
- // Unknown reference ID
136
- // ---------------------------------------------------------------------------
137
- describe("unknown reference_id", () => {
138
- it("returns handled:false when charge not found", async () => {
139
- const result = await handlePayRamWebhook(deps, makePayload({ reference_id: "ref-unknown-999" }));
140
- expect(result.handled).toBe(false);
141
- expect(result.tenant).toBeUndefined();
142
- });
143
- });
144
- // ---------------------------------------------------------------------------
145
- // Charge store updates
146
- // ---------------------------------------------------------------------------
147
- describe("charge store updates", () => {
148
- it("updates charge status on every webhook call", async () => {
149
- await handlePayRamWebhook(deps, makePayload({ status: "VERIFYING" }));
150
- const charge = await chargeStore.getByReferenceId("ref-test-001");
151
- expect(charge?.status).toBe("VERIFYING");
152
- });
153
- it("updates currency and filled_amount on FILLED", async () => {
154
- await handlePayRamWebhook(deps, makePayload({ status: "FILLED", currency: "USDT", filled_amount: "25.00" }));
155
- const charge = await chargeStore.getByReferenceId("ref-test-001");
156
- expect(charge?.currency).toBe("USDT");
157
- expect(charge?.filledAmount).toBe("25.00");
158
- });
159
- });
160
- // ---------------------------------------------------------------------------
161
- // Multiple tenants / reference IDs
162
- // ---------------------------------------------------------------------------
163
- describe("different reference IDs", () => {
164
- it("processes multiple reference IDs independently", async () => {
165
- await chargeStore.create("ref-b-001", "tenant-b", 5000);
166
- await chargeStore.create("ref-c-001", "tenant-c", 1500);
167
- await handlePayRamWebhook(deps, makePayload({ reference_id: "ref-b-001", status: "FILLED" }));
168
- await handlePayRamWebhook(deps, makePayload({ reference_id: "ref-c-001", status: "FILLED" }));
169
- expect((await creditLedger.balance("tenant-b")).toCents()).toBe(5000);
170
- expect((await creditLedger.balance("tenant-c")).toCents()).toBe(1500);
171
- });
172
- });
173
- // ---------------------------------------------------------------------------
174
- // Replay guard
175
- // ---------------------------------------------------------------------------
176
- describe("replay guard", () => {
177
- it("blocks duplicate reference_id + status combos", async () => {
178
- const replayGuard = new DrizzleWebhookSeenRepository(db);
179
- const depsWithGuard = { ...deps, replayGuard };
180
- const first = await handlePayRamWebhook(depsWithGuard, makePayload({ status: "FILLED" }));
181
- expect(first.handled).toBe(true);
182
- expect(first.creditedCents).toBe(2500);
183
- expect(first.duplicate).toBeUndefined();
184
- const second = await handlePayRamWebhook(depsWithGuard, makePayload({ status: "FILLED" }));
185
- expect(second.handled).toBe(true);
186
- expect(second.duplicate).toBe(true);
187
- expect(second.creditedCents).toBeUndefined();
188
- // Only credited once
189
- expect((await creditLedger.balance("tenant-a")).toCents()).toBe(2500);
190
- });
191
- it("same reference_id with different status is not blocked by replay guard", async () => {
192
- const replayGuard = new DrizzleWebhookSeenRepository(db);
193
- const depsWithGuard = { ...deps, replayGuard };
194
- await handlePayRamWebhook(depsWithGuard, makePayload({ status: "VERIFYING" }));
195
- const result = await handlePayRamWebhook(depsWithGuard, makePayload({ status: "FILLED" }));
196
- expect(result.duplicate).toBeUndefined();
197
- expect(result.creditedCents).toBe(2500);
198
- });
199
- });
200
- // ---------------------------------------------------------------------------
201
- // Bot reactivation
202
- // ---------------------------------------------------------------------------
203
- describe("resource reactivation via onCreditsPurchased", () => {
204
- it("calls onCreditsPurchased on FILLED and includes reactivatedBots in result", async () => {
205
- const mockOnCreditsPurchased = vi.fn().mockResolvedValue(["bot-1", "bot-2"]);
206
- const depsWithCallback = {
207
- ...deps,
208
- onCreditsPurchased: mockOnCreditsPurchased,
209
- };
210
- const result = await handlePayRamWebhook(depsWithCallback, makePayload({ status: "FILLED" }));
211
- expect(mockOnCreditsPurchased).toHaveBeenCalledWith("tenant-a", creditLedger);
212
- expect(result.reactivatedBots).toEqual(["bot-1", "bot-2"]);
213
- });
214
- it("does not include reactivatedBots when no resources reactivated", async () => {
215
- const mockOnCreditsPurchased = vi.fn().mockResolvedValue([]);
216
- const depsWithCallback = {
217
- ...deps,
218
- onCreditsPurchased: mockOnCreditsPurchased,
219
- };
220
- const result = await handlePayRamWebhook(depsWithCallback, makePayload({ status: "FILLED" }));
221
- expect(result.reactivatedBots).toBeUndefined();
222
- });
223
- });
224
- });
225
- // ---------------------------------------------------------------------------
226
- // DrizzleWebhookSeenRepository unit tests (replaces PayRamReplayGuard)
227
- // ---------------------------------------------------------------------------
228
- describe("DrizzleWebhookSeenRepository (payram replay guard)", () => {
229
- beforeEach(async () => {
230
- await truncateAllTables(pool);
231
- });
232
- it("reports unseen keys as not duplicate", async () => {
233
- const guard = new DrizzleWebhookSeenRepository(db);
234
- expect(await guard.isDuplicate("ref-001:FILLED", "payram")).toBe(false);
235
- });
236
- it("reports seen keys as duplicate", async () => {
237
- const guard = new DrizzleWebhookSeenRepository(db);
238
- await guard.markSeen("ref-001:FILLED", "payram");
239
- expect(await guard.isDuplicate("ref-001:FILLED", "payram")).toBe(true);
240
- });
241
- it("purges expired entries via purgeExpired", async () => {
242
- const guard = new DrizzleWebhookSeenRepository(db);
243
- await guard.markSeen("ref-expire:FILLED", "payram");
244
- expect(await guard.isDuplicate("ref-expire:FILLED", "payram")).toBe(true);
245
- // Negative TTL pushes cutoff into the future — entry is expired
246
- await guard.purgeExpired(-24 * 60 * 60 * 1000);
247
- expect(await guard.isDuplicate("ref-expire:FILLED", "payram")).toBe(false);
248
- });
249
- });
@@ -1,21 +0,0 @@
1
- import { sql } from "drizzle-orm";
2
- import { index, integer, pgTable, text } from "drizzle-orm/pg-core";
3
- /**
4
- * PayRam payment sessions — tracks the lifecycle of each crypto payment.
5
- * reference_id is the PayRam-assigned unique identifier.
6
- */
7
- export const payramCharges = pgTable("payram_charges", {
8
- referenceId: text("reference_id").primaryKey(),
9
- tenantId: text("tenant_id").notNull(),
10
- amountUsdCents: integer("amount_usd_cents").notNull(),
11
- status: text("status").notNull().default("OPEN"),
12
- currency: text("currency"),
13
- filledAmount: text("filled_amount"),
14
- createdAt: text("created_at").notNull().default(sql `(now())`),
15
- updatedAt: text("updated_at").notNull().default(sql `(now())`),
16
- creditedAt: text("credited_at"),
17
- }, (table) => [
18
- index("idx_payram_charges_tenant").on(table.tenantId),
19
- index("idx_payram_charges_status").on(table.status),
20
- index("idx_payram_charges_created").on(table.createdAt),
21
- ]);
@@ -1 +0,0 @@
1
- export {};
@@ -1,64 +0,0 @@
1
- import { PayRamChargeRepository } from "@wopr-network/platform-core/billing";
2
- import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
3
- import { beginTestTransaction, createTestDb, endTestTransaction, rollbackTestTransaction } from "../../test/db.js";
4
- describe("PayRamChargeRepository", () => {
5
- let pool;
6
- let db;
7
- let store;
8
- beforeAll(async () => {
9
- ({ db, pool } = await createTestDb());
10
- await beginTestTransaction(pool);
11
- });
12
- afterAll(async () => {
13
- await endTestTransaction(pool);
14
- await pool.close();
15
- });
16
- beforeEach(async () => {
17
- await rollbackTestTransaction(pool);
18
- store = new PayRamChargeRepository(db);
19
- });
20
- it("create() stores a charge", async () => {
21
- await store.create("ref-001", "tenant-1", 2500);
22
- const charge = await store.getByReferenceId("ref-001");
23
- expect(charge).not.toBeNull();
24
- expect(charge?.referenceId).toBe("ref-001");
25
- expect(charge?.tenantId).toBe("tenant-1");
26
- expect(charge?.amountUsdCents).toBe(2500);
27
- expect(charge?.status).toBe("OPEN");
28
- expect(charge?.creditedAt).toBeNull();
29
- });
30
- it("getByReferenceId() returns null when not found", async () => {
31
- const charge = await store.getByReferenceId("ref-nonexistent");
32
- expect(charge).toBeNull();
33
- });
34
- it("updateStatus() updates status, currency and filled_amount", async () => {
35
- await store.create("ref-002", "tenant-2", 5000);
36
- await store.updateStatus("ref-002", "FILLED", "USDC", "50.00");
37
- const charge = await store.getByReferenceId("ref-002");
38
- expect(charge?.status).toBe("FILLED");
39
- expect(charge?.currency).toBe("USDC");
40
- expect(charge?.filledAmount).toBe("50.00");
41
- });
42
- it("updateStatus() handles partial updates (no currency)", async () => {
43
- await store.create("ref-003", "tenant-3", 1000);
44
- await store.updateStatus("ref-003", "VERIFYING");
45
- const charge = await store.getByReferenceId("ref-003");
46
- expect(charge?.status).toBe("VERIFYING");
47
- expect(charge?.currency).toBeNull();
48
- });
49
- it("isCredited() returns false before markCredited", async () => {
50
- await store.create("ref-004", "tenant-4", 1500);
51
- expect(await store.isCredited("ref-004")).toBe(false);
52
- });
53
- it("markCredited() sets creditedAt", async () => {
54
- await store.create("ref-005", "tenant-5", 3000);
55
- await store.markCredited("ref-005");
56
- const charge = await store.getByReferenceId("ref-005");
57
- expect(charge?.creditedAt).not.toBeNull();
58
- });
59
- it("isCredited() returns true after markCredited", async () => {
60
- await store.create("ref-006", "tenant-6", 2000);
61
- await store.markCredited("ref-006");
62
- expect(await store.isCredited("ref-006")).toBe(true);
63
- });
64
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,73 +0,0 @@
1
- import { createPayRamCheckout, MIN_PAYMENT_USD, PayRamChargeRepository } from "@wopr-network/platform-core/billing";
2
- import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
3
- import { beginTestTransaction, createTestDb, endTestTransaction, rollbackTestTransaction } from "../../test/db.js";
4
- function createMockPayram(overrides = {}) {
5
- return {
6
- payments: {
7
- initiatePayment: overrides.initiatePayment ??
8
- vi.fn().mockResolvedValue({
9
- reference_id: "ref-mock-001",
10
- url: "https://payram.example.com/pay/ref-mock-001",
11
- }),
12
- },
13
- };
14
- }
15
- describe("createPayRamCheckout", () => {
16
- let pool;
17
- let db;
18
- let chargeStore;
19
- let payram;
20
- beforeAll(async () => {
21
- ({ db, pool } = await createTestDb());
22
- await beginTestTransaction(pool);
23
- });
24
- afterAll(async () => {
25
- await endTestTransaction(pool);
26
- await pool.close();
27
- });
28
- beforeEach(async () => {
29
- await rollbackTestTransaction(pool);
30
- chargeStore = new PayRamChargeRepository(db);
31
- payram = createMockPayram();
32
- });
33
- it("rejects amounts below $10 minimum", async () => {
34
- await expect(createPayRamCheckout(payram, chargeStore, { tenant: "t-1", amountUsd: 5 })).rejects.toThrow(`Minimum payment amount is $${MIN_PAYMENT_USD}`);
35
- });
36
- it("rejects amounts of exactly $0", async () => {
37
- await expect(createPayRamCheckout(payram, chargeStore, { tenant: "t-1", amountUsd: 0 })).rejects.toThrow();
38
- });
39
- it("calls payram.payments.initiatePayment with correct params", async () => {
40
- const initiatePayment = vi.fn().mockResolvedValue({
41
- reference_id: "ref-abc",
42
- url: "https://payram.example.com/pay/ref-abc",
43
- });
44
- const mockPayram = createMockPayram({ initiatePayment });
45
- await createPayRamCheckout(mockPayram, chargeStore, { tenant: "t-test", amountUsd: 25 });
46
- expect(initiatePayment).toHaveBeenCalledWith({
47
- customerEmail: "t-test@wopr.bot",
48
- customerId: "t-test",
49
- amountInUSD: 25,
50
- });
51
- });
52
- it("stores the charge with correct amountUsdCents (converts from USD)", async () => {
53
- const initiatePayment = vi.fn().mockResolvedValue({
54
- reference_id: "ref-store-test",
55
- url: "https://payram.example.com/pay/ref-store-test",
56
- });
57
- const mockPayram = createMockPayram({ initiatePayment });
58
- await createPayRamCheckout(mockPayram, chargeStore, { tenant: "t-2", amountUsd: 25 });
59
- const charge = await chargeStore.getByReferenceId("ref-store-test");
60
- expect(charge).not.toBeNull();
61
- expect(charge?.tenantId).toBe("t-2");
62
- expect(charge?.amountUsdCents).toBe(2500); // $25.00 = 2500 cents
63
- expect(charge?.status).toBe("OPEN");
64
- });
65
- it("returns referenceId and url from PayRam response", async () => {
66
- const result = await createPayRamCheckout(payram, chargeStore, { tenant: "t-3", amountUsd: 10 });
67
- expect(result.referenceId).toBe("ref-mock-001");
68
- expect(result.url).toBe("https://payram.example.com/pay/ref-mock-001");
69
- });
70
- it("accepts exactly $10 (minimum boundary)", async () => {
71
- await expect(createPayRamCheckout(payram, chargeStore, { tenant: "t-4", amountUsd: 10 })).resolves.not.toBeNull();
72
- });
73
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,52 +0,0 @@
1
- import { createPayRamClient, loadPayRamConfig } from "@wopr-network/platform-core/billing";
2
- import { Payram } from "payram";
3
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
- describe("createPayRamClient", () => {
5
- it("returns a Payram instance", () => {
6
- const client = createPayRamClient({ apiKey: "test-key", baseUrl: "https://api.payram.test" });
7
- expect(client).toBeInstanceOf(Payram);
8
- });
9
- it("passes config through to the Payram constructor", () => {
10
- const client = createPayRamClient({ apiKey: "pk_live_123", baseUrl: "https://api.payram.io" });
11
- expect(client).toBeInstanceOf(Payram);
12
- });
13
- });
14
- describe("loadPayRamConfig", () => {
15
- beforeEach(() => {
16
- delete process.env.PAYRAM_API_KEY;
17
- delete process.env.PAYRAM_BASE_URL;
18
- });
19
- afterEach(() => {
20
- vi.unstubAllEnvs();
21
- });
22
- it("returns null when PAYRAM_API_KEY is missing", () => {
23
- vi.stubEnv("PAYRAM_BASE_URL", "https://api.payram.test");
24
- expect(loadPayRamConfig()).toBeNull();
25
- });
26
- it("returns null when PAYRAM_BASE_URL is missing", () => {
27
- vi.stubEnv("PAYRAM_API_KEY", "pk_test_123");
28
- expect(loadPayRamConfig()).toBeNull();
29
- });
30
- it("returns null when PAYRAM_API_KEY is an empty string", () => {
31
- vi.stubEnv("PAYRAM_API_KEY", "");
32
- vi.stubEnv("PAYRAM_BASE_URL", "https://api.payram.test");
33
- expect(loadPayRamConfig()).toBeNull();
34
- });
35
- it("returns null when PAYRAM_BASE_URL is an empty string", () => {
36
- vi.stubEnv("PAYRAM_API_KEY", "pk_test_123");
37
- vi.stubEnv("PAYRAM_BASE_URL", "");
38
- expect(loadPayRamConfig()).toBeNull();
39
- });
40
- it("returns config when both env vars are set", () => {
41
- vi.stubEnv("PAYRAM_API_KEY", "pk_test_123");
42
- vi.stubEnv("PAYRAM_BASE_URL", "https://api.payram.test");
43
- const config = loadPayRamConfig();
44
- expect(config).toEqual({
45
- apiKey: "pk_test_123",
46
- baseUrl: "https://api.payram.test",
47
- });
48
- });
49
- it("returns null when both env vars are missing", () => {
50
- expect(loadPayRamConfig()).toBeNull();
51
- });
52
- });
@@ -1,4 +0,0 @@
1
- export type { IPayRamChargeRepository, PayRamBillingConfig, PayRamChargeRecord, PayRamCheckoutOpts, PayRamConfig, PayRamPaymentState, PayRamWebhookPayload, PayRamWebhookResult, } from "@wopr-network/platform-core/billing";
2
- export { createPayRamCheckout, createPayRamClient, DrizzlePayRamChargeRepository, loadPayRamConfig, MIN_PAYMENT_USD, PayRamChargeRepository, } from "@wopr-network/platform-core/billing";
3
- export type { PayRamWebhookDeps } from "./webhook.js";
4
- export { handlePayRamWebhook } from "./webhook.js";
@@ -1,2 +0,0 @@
1
- export { createPayRamCheckout, createPayRamClient, DrizzlePayRamChargeRepository, loadPayRamConfig, MIN_PAYMENT_USD, PayRamChargeRepository, } from "@wopr-network/platform-core/billing";
2
- export { handlePayRamWebhook } from "./webhook.js";
@@ -1,17 +0,0 @@
1
- import type { IWebhookSeenRepository, PayRamChargeRepository, PayRamWebhookPayload, PayRamWebhookResult } from "@wopr-network/platform-core/billing";
2
- import type { ILedger } from "@wopr-network/platform-core/credits";
3
- import type { BotBilling } from "../credits/bot-billing.js";
4
- export interface PayRamWebhookDeps {
5
- chargeStore: PayRamChargeRepository;
6
- creditLedger: ILedger;
7
- botBilling?: BotBilling;
8
- replayGuard: IWebhookSeenRepository;
9
- }
10
- /**
11
- * Process a PayRam webhook event.
12
- *
13
- * Only credits the ledger on FILLED or OVER_FILLED status.
14
- * Uses the PayRam reference_id mapped to the stored charge record
15
- * for tenant resolution and idempotency.
16
- */
17
- export declare function handlePayRamWebhook(deps: PayRamWebhookDeps, payload: PayRamWebhookPayload): Promise<PayRamWebhookResult>;
@@ -1,71 +0,0 @@
1
- import { Credit } from "@wopr-network/platform-core/credits";
2
- /**
3
- * Process a PayRam webhook event.
4
- *
5
- * Only credits the ledger on FILLED or OVER_FILLED status.
6
- * Uses the PayRam reference_id mapped to the stored charge record
7
- * for tenant resolution and idempotency.
8
- */
9
- export async function handlePayRamWebhook(deps, payload) {
10
- const { chargeStore, creditLedger } = deps;
11
- // Replay guard: deduplicate by reference_id + status combination.
12
- const dedupeKey = `${payload.reference_id}:${payload.status}`;
13
- if (await deps.replayGuard.isDuplicate(dedupeKey, "payram")) {
14
- return { handled: true, status: payload.status, duplicate: true };
15
- }
16
- // Look up the charge record to find the tenant.
17
- const charge = await chargeStore.getByReferenceId(payload.reference_id);
18
- if (!charge) {
19
- return { handled: false, status: payload.status };
20
- }
21
- // Update charge status regardless of payment state.
22
- await chargeStore.updateStatus(payload.reference_id, payload.status, payload.currency, payload.filled_amount);
23
- let result;
24
- if (payload.status === "FILLED" || payload.status === "OVER_FILLED") {
25
- // Idempotency: skip if already credited.
26
- if (await chargeStore.isCredited(payload.reference_id)) {
27
- result = {
28
- handled: true,
29
- status: payload.status,
30
- tenant: charge.tenantId,
31
- creditedCents: 0,
32
- };
33
- }
34
- else {
35
- // Credit the original USD amount requested (not the crypto amount).
36
- // For OVER_FILLED, we still credit the requested amount — the
37
- // overpayment stays in the PayRam wallet as a buffer.
38
- const creditCents = charge.amountUsdCents;
39
- await creditLedger.credit(charge.tenantId, Credit.fromCents(creditCents), "purchase", {
40
- description: `Crypto credit purchase via PayRam (ref: ${payload.reference_id}, ${payload.currency ?? "crypto"})`,
41
- referenceId: `payram:${payload.reference_id}`,
42
- fundingSource: "payram",
43
- });
44
- await chargeStore.markCredited(payload.reference_id);
45
- // Reactivate suspended bots (same as Stripe webhook, WOP-447).
46
- let reactivatedBots;
47
- if (deps.botBilling) {
48
- reactivatedBots = await deps.botBilling.checkReactivation(charge.tenantId, creditLedger);
49
- if (reactivatedBots.length === 0)
50
- reactivatedBots = undefined;
51
- }
52
- result = {
53
- handled: true,
54
- status: payload.status,
55
- tenant: charge.tenantId,
56
- creditedCents: creditCents,
57
- reactivatedBots,
58
- };
59
- }
60
- }
61
- else {
62
- // OPEN, VERIFYING, PARTIALLY_FILLED, CANCELLED — just track status.
63
- result = {
64
- handled: true,
65
- status: payload.status,
66
- tenant: charge.tenantId,
67
- };
68
- }
69
- await deps.replayGuard.markSeen(dedupeKey, "payram");
70
- return result;
71
- }
@@ -1,7 +0,0 @@
1
- /**
2
- * Unit tests for PayRam webhook handler (WOP-407).
3
- *
4
- * Covers FILLED/OVER_FILLED crediting the ledger, PARTIALLY_FILLED/CANCELLED
5
- * no-op status, idempotency, replay guard, and bot reactivation.
6
- */
7
- export {};