@wopr-network/platform-core 1.43.0 → 1.44.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 (58) hide show
  1. package/dist/billing/crypto/__tests__/key-server.test.js +16 -1
  2. package/dist/billing/crypto/btc/watcher.d.ts +2 -0
  3. package/dist/billing/crypto/btc/watcher.js +1 -1
  4. package/dist/billing/crypto/charge-store.d.ts +7 -1
  5. package/dist/billing/crypto/charge-store.js +7 -1
  6. package/dist/billing/crypto/client.d.ts +0 -26
  7. package/dist/billing/crypto/client.js +0 -13
  8. package/dist/billing/crypto/client.test.js +1 -11
  9. package/dist/billing/crypto/index.d.ts +5 -7
  10. package/dist/billing/crypto/index.js +3 -5
  11. package/dist/billing/crypto/key-server-entry.js +43 -2
  12. package/dist/billing/crypto/key-server-webhook.d.ts +33 -0
  13. package/dist/billing/crypto/key-server-webhook.js +73 -0
  14. package/dist/billing/crypto/key-server.d.ts +2 -0
  15. package/dist/billing/crypto/key-server.js +25 -1
  16. package/dist/billing/crypto/watcher-service.d.ts +33 -0
  17. package/dist/billing/crypto/watcher-service.js +295 -0
  18. package/dist/billing/index.js +1 -1
  19. package/dist/db/schema/crypto.d.ts +217 -2
  20. package/dist/db/schema/crypto.js +25 -2
  21. package/dist/monetization/crypto/__tests__/webhook.test.js +57 -92
  22. package/dist/monetization/crypto/index.d.ts +4 -4
  23. package/dist/monetization/crypto/index.js +2 -2
  24. package/dist/monetization/crypto/webhook.d.ts +13 -14
  25. package/dist/monetization/crypto/webhook.js +12 -83
  26. package/dist/monetization/index.d.ts +2 -2
  27. package/dist/monetization/index.js +1 -1
  28. package/drizzle/migrations/0015_callback_url.sql +32 -0
  29. package/drizzle/migrations/meta/_journal.json +7 -0
  30. package/package.json +1 -1
  31. package/src/billing/crypto/__tests__/key-server.test.ts +16 -1
  32. package/src/billing/crypto/btc/watcher.ts +3 -1
  33. package/src/billing/crypto/charge-store.ts +13 -1
  34. package/src/billing/crypto/client.test.ts +1 -13
  35. package/src/billing/crypto/client.ts +0 -21
  36. package/src/billing/crypto/index.ts +9 -13
  37. package/src/billing/crypto/key-server-entry.ts +46 -2
  38. package/src/billing/crypto/key-server-webhook.ts +119 -0
  39. package/src/billing/crypto/key-server.ts +29 -1
  40. package/src/billing/crypto/watcher-service.ts +381 -0
  41. package/src/billing/index.ts +1 -1
  42. package/src/db/schema/crypto.ts +30 -2
  43. package/src/monetization/crypto/__tests__/webhook.test.ts +61 -104
  44. package/src/monetization/crypto/index.ts +9 -11
  45. package/src/monetization/crypto/webhook.ts +25 -99
  46. package/src/monetization/index.ts +3 -7
  47. package/dist/billing/crypto/checkout.d.ts +0 -18
  48. package/dist/billing/crypto/checkout.js +0 -35
  49. package/dist/billing/crypto/checkout.test.d.ts +0 -1
  50. package/dist/billing/crypto/checkout.test.js +0 -71
  51. package/dist/billing/crypto/webhook.d.ts +0 -34
  52. package/dist/billing/crypto/webhook.js +0 -107
  53. package/dist/billing/crypto/webhook.test.d.ts +0 -1
  54. package/dist/billing/crypto/webhook.test.js +0 -266
  55. package/src/billing/crypto/checkout.test.ts +0 -93
  56. package/src/billing/crypto/checkout.ts +0 -48
  57. package/src/billing/crypto/webhook.test.ts +0 -340
  58. package/src/billing/crypto/webhook.ts +0 -136
@@ -0,0 +1,295 @@
1
+ /**
2
+ * Watcher Service — boots chain watchers and sends webhook callbacks.
3
+ *
4
+ * Payment flow:
5
+ * 1. Watcher detects payment → handlePayment()
6
+ * 2. Accumulate native amount (supports partial payments)
7
+ * 3. When totalReceived >= expectedAmount → settle + credit
8
+ * 4. Every payment (partial or full) enqueues a webhook delivery
9
+ * 5. Outbox processor retries failed deliveries with exponential backoff
10
+ *
11
+ * Amount comparison is ALWAYS in native crypto units (sats, wei, token base units).
12
+ * The exchange rate is locked at charge creation — no live price comparison.
13
+ */
14
+ import { and, eq, isNull, lte, or } from "drizzle-orm";
15
+ import { cryptoCharges, webhookDeliveries } from "../../db/schema/crypto.js";
16
+ import { BtcWatcher, createBitcoindRpc } from "./btc/watcher.js";
17
+ import { createRpcCaller, EvmWatcher } from "./evm/watcher.js";
18
+ const MAX_DELIVERY_ATTEMPTS = 10;
19
+ const BACKOFF_BASE_MS = 5_000;
20
+ // --- SSRF validation ---
21
+ function isValidCallbackUrl(url, allowedPrefixes) {
22
+ try {
23
+ const parsed = new URL(url);
24
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:")
25
+ return false;
26
+ const host = parsed.hostname;
27
+ if (host === "localhost" || host === "127.0.0.1" || host === "0.0.0.0" || host === "::1")
28
+ return false;
29
+ if (host.startsWith("10.") || host.startsWith("192.168.") || host.startsWith("169.254."))
30
+ return false;
31
+ return allowedPrefixes.some((prefix) => url.startsWith(prefix));
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ }
37
+ // --- Webhook outbox ---
38
+ async function enqueueWebhook(db, chargeId, callbackUrl, payload) {
39
+ await db.insert(webhookDeliveries).values({
40
+ chargeId,
41
+ callbackUrl,
42
+ payload: JSON.stringify(payload),
43
+ });
44
+ }
45
+ async function processDeliveries(db, allowedPrefixes, log) {
46
+ const now = new Date().toISOString();
47
+ const pending = await db
48
+ .select()
49
+ .from(webhookDeliveries)
50
+ .where(and(eq(webhookDeliveries.status, "pending"), or(isNull(webhookDeliveries.nextRetryAt), lte(webhookDeliveries.nextRetryAt, now))))
51
+ .limit(50);
52
+ let delivered = 0;
53
+ for (const row of pending) {
54
+ if (!isValidCallbackUrl(row.callbackUrl, allowedPrefixes)) {
55
+ await db
56
+ .update(webhookDeliveries)
57
+ .set({ status: "failed", lastError: "Invalid callbackUrl (SSRF blocked)" })
58
+ .where(eq(webhookDeliveries.id, row.id));
59
+ continue;
60
+ }
61
+ try {
62
+ const res = await fetch(row.callbackUrl, {
63
+ method: "POST",
64
+ headers: { "Content-Type": "application/json" },
65
+ body: row.payload,
66
+ });
67
+ if (!res.ok)
68
+ throw new Error(`HTTP ${res.status}`);
69
+ await db.update(webhookDeliveries).set({ status: "delivered" }).where(eq(webhookDeliveries.id, row.id));
70
+ delivered++;
71
+ }
72
+ catch (err) {
73
+ const attempts = row.attempts + 1;
74
+ if (attempts >= MAX_DELIVERY_ATTEMPTS) {
75
+ await db
76
+ .update(webhookDeliveries)
77
+ .set({ status: "failed", attempts, lastError: String(err) })
78
+ .where(eq(webhookDeliveries.id, row.id));
79
+ log("Webhook permanently failed", { chargeId: row.chargeId, attempts });
80
+ }
81
+ else {
82
+ const backoffMs = BACKOFF_BASE_MS * 2 ** (attempts - 1);
83
+ const nextRetry = new Date(Date.now() + backoffMs).toISOString();
84
+ await db
85
+ .update(webhookDeliveries)
86
+ .set({ attempts, nextRetryAt: nextRetry, lastError: String(err) })
87
+ .where(eq(webhookDeliveries.id, row.id));
88
+ }
89
+ }
90
+ }
91
+ return delivered;
92
+ }
93
+ // --- Payment handling (partial + full) ---
94
+ /**
95
+ * Handle a payment event. Accumulates partial payments in native units.
96
+ * Settles when totalReceived >= expectedAmount. Fires webhook on every payment.
97
+ *
98
+ * @param nativeAmount — received amount in native base units (sats for BTC/DOGE, raw token units for ERC20)
99
+ */
100
+ async function handlePayment(db, chargeStore, address, nativeAmount, payload, log) {
101
+ const charge = await chargeStore.getByDepositAddress(address);
102
+ if (!charge) {
103
+ log("Payment to unknown address", { address });
104
+ return;
105
+ }
106
+ if (charge.creditedAt) {
107
+ return; // Already fully paid and credited
108
+ }
109
+ // Accumulate: add this payment to the running total
110
+ const prevReceived = BigInt(charge.receivedAmount ?? "0");
111
+ const thisPayment = BigInt(nativeAmount);
112
+ const totalReceived = (prevReceived + thisPayment).toString();
113
+ const expected = BigInt(charge.expectedAmount ?? "0");
114
+ const isFull = expected > 0n && BigInt(totalReceived) >= expected;
115
+ // Update received_amount in DB
116
+ await db
117
+ .update(cryptoCharges)
118
+ .set({ receivedAmount: totalReceived, filledAmount: totalReceived })
119
+ .where(eq(cryptoCharges.referenceId, charge.referenceId));
120
+ if (isFull) {
121
+ const settled = "Settled";
122
+ await chargeStore.updateStatus(charge.referenceId, settled, charge.token ?? undefined, totalReceived);
123
+ await chargeStore.markCredited(charge.referenceId);
124
+ log("Charge settled", { chargeId: charge.referenceId, expected: expected.toString(), received: totalReceived });
125
+ }
126
+ else {
127
+ const processing = "Processing";
128
+ await chargeStore.updateStatus(charge.referenceId, processing, charge.token ?? undefined, totalReceived);
129
+ log("Partial payment", { chargeId: charge.referenceId, expected: expected.toString(), received: totalReceived });
130
+ }
131
+ // Webhook on every payment — product shows progress to user
132
+ if (charge.callbackUrl) {
133
+ await enqueueWebhook(db, charge.referenceId, charge.callbackUrl, {
134
+ chargeId: charge.referenceId,
135
+ chain: charge.chain,
136
+ address: charge.depositAddress,
137
+ expectedAmount: expected.toString(),
138
+ receivedAmount: totalReceived,
139
+ amountUsdCents: charge.amountUsdCents,
140
+ status: isFull ? "confirmed" : "partial",
141
+ ...payload,
142
+ });
143
+ }
144
+ }
145
+ // --- Watcher boot ---
146
+ export async function startWatchers(opts) {
147
+ const { db, chargeStore, methodStore, cursorStore, oracle } = opts;
148
+ const pollMs = opts.pollIntervalMs ?? 15_000;
149
+ const deliveryMs = opts.deliveryIntervalMs ?? 10_000;
150
+ const log = opts.log ?? (() => { });
151
+ const allowedPrefixes = opts.allowedCallbackPrefixes ?? ["https://"];
152
+ const timers = [];
153
+ const methods = await methodStore.listEnabled();
154
+ const utxoMethods = methods.filter((m) => m.type === "native" && (m.chain === "bitcoin" || m.chain === "litecoin" || m.chain === "dogecoin"));
155
+ const evmMethods = methods.filter((m) => m.type === "erc20" ||
156
+ (m.type === "native" && m.chain !== "bitcoin" && m.chain !== "litecoin" && m.chain !== "dogecoin"));
157
+ // --- UTXO Watchers (BTC, LTC, DOGE) ---
158
+ for (const method of utxoMethods) {
159
+ if (!method.rpcUrl)
160
+ continue;
161
+ const rpcCall = createBitcoindRpc({
162
+ rpcUrl: method.rpcUrl,
163
+ rpcUser: opts.bitcoindUser ?? "btcpay",
164
+ rpcPassword: opts.bitcoindPassword ?? "",
165
+ network: "mainnet",
166
+ confirmations: method.confirmations,
167
+ });
168
+ const activeAddresses = await chargeStore.listActiveDepositAddresses();
169
+ const chainAddresses = activeAddresses.filter((a) => a.chain === method.chain).map((a) => a.address);
170
+ const watcher = new BtcWatcher({
171
+ config: {
172
+ rpcUrl: method.rpcUrl,
173
+ rpcUser: opts.bitcoindUser ?? "btcpay",
174
+ rpcPassword: opts.bitcoindPassword ?? "",
175
+ network: "mainnet",
176
+ confirmations: method.confirmations,
177
+ },
178
+ chainId: method.chain,
179
+ rpcCall,
180
+ watchedAddresses: chainAddresses,
181
+ oracle,
182
+ cursorStore,
183
+ onPayment: async (event) => {
184
+ log("UTXO payment", { chain: method.chain, address: event.address, txid: event.txid, sats: event.amountSats });
185
+ // Pass native amount (sats) — NOT USD cents
186
+ await handlePayment(db, chargeStore, event.address, String(event.amountSats), {
187
+ txHash: event.txid,
188
+ confirmations: event.confirmations,
189
+ }, log);
190
+ },
191
+ });
192
+ const importedAddresses = new Set();
193
+ for (const addr of chainAddresses) {
194
+ try {
195
+ await watcher.importAddress(addr);
196
+ importedAddresses.add(addr);
197
+ }
198
+ catch {
199
+ log("Failed to import address", { chain: method.chain, address: addr });
200
+ }
201
+ }
202
+ log(`UTXO watcher started (${method.chain})`, { addresses: importedAddresses.size });
203
+ let utxoPolling = false;
204
+ timers.push(setInterval(async () => {
205
+ if (utxoPolling)
206
+ return; // Prevent overlapping polls
207
+ utxoPolling = true;
208
+ try {
209
+ const fresh = await chargeStore.listActiveDepositAddresses();
210
+ const freshChain = fresh.filter((a) => a.chain === method.chain).map((a) => a.address);
211
+ for (const addr of freshChain) {
212
+ if (!importedAddresses.has(addr)) {
213
+ try {
214
+ await watcher.importAddress(addr);
215
+ importedAddresses.add(addr);
216
+ }
217
+ catch {
218
+ log("Failed to import new address (will retry)", { chain: method.chain, address: addr });
219
+ }
220
+ }
221
+ }
222
+ watcher.setWatchedAddresses(freshChain);
223
+ await watcher.poll();
224
+ }
225
+ catch (err) {
226
+ log("UTXO poll error", { chain: method.chain, error: String(err) });
227
+ }
228
+ finally {
229
+ utxoPolling = false;
230
+ }
231
+ }, pollMs));
232
+ }
233
+ // --- EVM Watchers ---
234
+ for (const method of evmMethods) {
235
+ if (!method.rpcUrl || !method.contractAddress)
236
+ continue;
237
+ const rpcCall = createRpcCaller(method.rpcUrl);
238
+ const latestHex = (await rpcCall("eth_blockNumber", []));
239
+ const latestBlock = Number.parseInt(latestHex, 16);
240
+ const activeAddresses = await chargeStore.listActiveDepositAddresses();
241
+ const chainAddresses = activeAddresses.filter((a) => a.chain === method.chain).map((a) => a.address);
242
+ const watcher = new EvmWatcher({
243
+ chain: method.chain,
244
+ token: method.token,
245
+ rpcCall,
246
+ fromBlock: latestBlock,
247
+ watchedAddresses: chainAddresses,
248
+ cursorStore,
249
+ onPayment: async (event) => {
250
+ log("EVM payment", { chain: event.chain, token: event.token, to: event.to, txHash: event.txHash });
251
+ // Pass native amount (raw token units) — NOT USD cents
252
+ await handlePayment(db, chargeStore, event.to, event.rawAmount, {
253
+ txHash: event.txHash,
254
+ confirmations: method.confirmations,
255
+ }, log);
256
+ },
257
+ });
258
+ await watcher.init();
259
+ log(`EVM watcher started (${method.chain}:${method.token})`, { addresses: chainAddresses.length });
260
+ let evmPolling = false;
261
+ timers.push(setInterval(async () => {
262
+ if (evmPolling)
263
+ return; // Prevent overlapping polls
264
+ evmPolling = true;
265
+ try {
266
+ const fresh = await chargeStore.listActiveDepositAddresses();
267
+ const freshChain = fresh.filter((a) => a.chain === method.chain).map((a) => a.address);
268
+ watcher.setWatchedAddresses(freshChain);
269
+ await watcher.poll();
270
+ }
271
+ catch (err) {
272
+ log("EVM poll error", { chain: method.chain, token: method.token, error: String(err) });
273
+ }
274
+ finally {
275
+ evmPolling = false;
276
+ }
277
+ }, pollMs));
278
+ }
279
+ // --- Webhook delivery outbox processor ---
280
+ timers.push(setInterval(async () => {
281
+ try {
282
+ const count = await processDeliveries(db, allowedPrefixes, log);
283
+ if (count > 0)
284
+ log("Webhooks delivered", { count });
285
+ }
286
+ catch (err) {
287
+ log("Delivery loop error", { error: String(err) });
288
+ }
289
+ }, deliveryMs));
290
+ log("All watchers started", { utxo: utxoMethods.length, evm: evmMethods.length, pollMs, deliveryMs });
291
+ return () => {
292
+ for (const t of timers)
293
+ clearInterval(t);
294
+ };
295
+ }
@@ -1,4 +1,4 @@
1
- // Crypto (BTCPay Server)
1
+ // Crypto (key server — native BTC/EVM watchers)
2
2
  export * from "./crypto/index.js";
3
3
  export { DrizzleWebhookSeenRepository } from "./drizzle-webhook-seen-repository.js";
4
4
  export { PaymentMethodOwnershipError } from "./payment-processor.js";
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Crypto payment charges — tracks the lifecycle of each BTCPay invoice.
3
- * reference_id is the BTCPay invoice ID.
2
+ * Crypto payment charges — tracks the lifecycle of each payment.
3
+ * reference_id is the charge ID (e.g. "btc:bc1q...").
4
4
  *
5
5
  * amountUsdCents stores the requested amount in USD cents (integer).
6
6
  * This is NOT nanodollars — Credit.fromCents() handles the conversion
@@ -231,6 +231,57 @@ export declare const cryptoCharges: import("drizzle-orm/pg-core").PgTableWithCol
231
231
  identity: undefined;
232
232
  generated: undefined;
233
233
  }, {}, {}>;
234
+ callbackUrl: import("drizzle-orm/pg-core").PgColumn<{
235
+ name: "callback_url";
236
+ tableName: "crypto_charges";
237
+ dataType: "string";
238
+ columnType: "PgText";
239
+ data: string;
240
+ driverParam: string;
241
+ notNull: false;
242
+ hasDefault: false;
243
+ isPrimaryKey: false;
244
+ isAutoincrement: false;
245
+ hasRuntimeDefault: false;
246
+ enumValues: [string, ...string[]];
247
+ baseColumn: never;
248
+ identity: undefined;
249
+ generated: undefined;
250
+ }, {}, {}>;
251
+ expectedAmount: import("drizzle-orm/pg-core").PgColumn<{
252
+ name: "expected_amount";
253
+ tableName: "crypto_charges";
254
+ dataType: "string";
255
+ columnType: "PgText";
256
+ data: string;
257
+ driverParam: string;
258
+ notNull: false;
259
+ hasDefault: false;
260
+ isPrimaryKey: false;
261
+ isAutoincrement: false;
262
+ hasRuntimeDefault: false;
263
+ enumValues: [string, ...string[]];
264
+ baseColumn: never;
265
+ identity: undefined;
266
+ generated: undefined;
267
+ }, {}, {}>;
268
+ receivedAmount: import("drizzle-orm/pg-core").PgColumn<{
269
+ name: "received_amount";
270
+ tableName: "crypto_charges";
271
+ dataType: "string";
272
+ columnType: "PgText";
273
+ data: string;
274
+ driverParam: string;
275
+ notNull: false;
276
+ hasDefault: false;
277
+ isPrimaryKey: false;
278
+ isAutoincrement: false;
279
+ hasRuntimeDefault: false;
280
+ enumValues: [string, ...string[]];
281
+ baseColumn: never;
282
+ identity: undefined;
283
+ generated: undefined;
284
+ }, {}, {}>;
234
285
  };
235
286
  dialect: "pg";
236
287
  }>;
@@ -680,6 +731,170 @@ export declare const pathAllocations: import("drizzle-orm/pg-core").PgTableWithC
680
731
  };
681
732
  dialect: "pg";
682
733
  }>;
734
+ /**
735
+ * Webhook delivery outbox — durable retry for payment callbacks.
736
+ * Inserted when a payment is confirmed. Retried until the receiver ACKs.
737
+ */
738
+ export declare const webhookDeliveries: import("drizzle-orm/pg-core").PgTableWithColumns<{
739
+ name: "webhook_deliveries";
740
+ schema: undefined;
741
+ columns: {
742
+ id: import("drizzle-orm/pg-core").PgColumn<{
743
+ name: "id";
744
+ tableName: "webhook_deliveries";
745
+ dataType: "number";
746
+ columnType: "PgInteger";
747
+ data: number;
748
+ driverParam: string | number;
749
+ notNull: true;
750
+ hasDefault: true;
751
+ isPrimaryKey: true;
752
+ isAutoincrement: false;
753
+ hasRuntimeDefault: false;
754
+ enumValues: undefined;
755
+ baseColumn: never;
756
+ identity: "always";
757
+ generated: undefined;
758
+ }, {}, {}>;
759
+ chargeId: import("drizzle-orm/pg-core").PgColumn<{
760
+ name: "charge_id";
761
+ tableName: "webhook_deliveries";
762
+ dataType: "string";
763
+ columnType: "PgText";
764
+ data: string;
765
+ driverParam: string;
766
+ notNull: true;
767
+ hasDefault: false;
768
+ isPrimaryKey: false;
769
+ isAutoincrement: false;
770
+ hasRuntimeDefault: false;
771
+ enumValues: [string, ...string[]];
772
+ baseColumn: never;
773
+ identity: undefined;
774
+ generated: undefined;
775
+ }, {}, {}>;
776
+ callbackUrl: import("drizzle-orm/pg-core").PgColumn<{
777
+ name: "callback_url";
778
+ tableName: "webhook_deliveries";
779
+ dataType: "string";
780
+ columnType: "PgText";
781
+ data: string;
782
+ driverParam: string;
783
+ notNull: true;
784
+ hasDefault: false;
785
+ isPrimaryKey: false;
786
+ isAutoincrement: false;
787
+ hasRuntimeDefault: false;
788
+ enumValues: [string, ...string[]];
789
+ baseColumn: never;
790
+ identity: undefined;
791
+ generated: undefined;
792
+ }, {}, {}>;
793
+ payload: import("drizzle-orm/pg-core").PgColumn<{
794
+ name: "payload";
795
+ tableName: "webhook_deliveries";
796
+ dataType: "string";
797
+ columnType: "PgText";
798
+ data: string;
799
+ driverParam: string;
800
+ notNull: true;
801
+ hasDefault: false;
802
+ isPrimaryKey: false;
803
+ isAutoincrement: false;
804
+ hasRuntimeDefault: false;
805
+ enumValues: [string, ...string[]];
806
+ baseColumn: never;
807
+ identity: undefined;
808
+ generated: undefined;
809
+ }, {}, {}>;
810
+ status: import("drizzle-orm/pg-core").PgColumn<{
811
+ name: "status";
812
+ tableName: "webhook_deliveries";
813
+ dataType: "string";
814
+ columnType: "PgText";
815
+ data: string;
816
+ driverParam: string;
817
+ notNull: true;
818
+ hasDefault: true;
819
+ isPrimaryKey: false;
820
+ isAutoincrement: false;
821
+ hasRuntimeDefault: false;
822
+ enumValues: [string, ...string[]];
823
+ baseColumn: never;
824
+ identity: undefined;
825
+ generated: undefined;
826
+ }, {}, {}>;
827
+ attempts: import("drizzle-orm/pg-core").PgColumn<{
828
+ name: "attempts";
829
+ tableName: "webhook_deliveries";
830
+ dataType: "number";
831
+ columnType: "PgInteger";
832
+ data: number;
833
+ driverParam: string | number;
834
+ notNull: true;
835
+ hasDefault: true;
836
+ isPrimaryKey: false;
837
+ isAutoincrement: false;
838
+ hasRuntimeDefault: false;
839
+ enumValues: undefined;
840
+ baseColumn: never;
841
+ identity: undefined;
842
+ generated: undefined;
843
+ }, {}, {}>;
844
+ nextRetryAt: import("drizzle-orm/pg-core").PgColumn<{
845
+ name: "next_retry_at";
846
+ tableName: "webhook_deliveries";
847
+ dataType: "string";
848
+ columnType: "PgText";
849
+ data: string;
850
+ driverParam: string;
851
+ notNull: false;
852
+ hasDefault: false;
853
+ isPrimaryKey: false;
854
+ isAutoincrement: false;
855
+ hasRuntimeDefault: false;
856
+ enumValues: [string, ...string[]];
857
+ baseColumn: never;
858
+ identity: undefined;
859
+ generated: undefined;
860
+ }, {}, {}>;
861
+ lastError: import("drizzle-orm/pg-core").PgColumn<{
862
+ name: "last_error";
863
+ tableName: "webhook_deliveries";
864
+ dataType: "string";
865
+ columnType: "PgText";
866
+ data: string;
867
+ driverParam: string;
868
+ notNull: false;
869
+ hasDefault: false;
870
+ isPrimaryKey: false;
871
+ isAutoincrement: false;
872
+ hasRuntimeDefault: false;
873
+ enumValues: [string, ...string[]];
874
+ baseColumn: never;
875
+ identity: undefined;
876
+ generated: undefined;
877
+ }, {}, {}>;
878
+ createdAt: import("drizzle-orm/pg-core").PgColumn<{
879
+ name: "created_at";
880
+ tableName: "webhook_deliveries";
881
+ dataType: "string";
882
+ columnType: "PgText";
883
+ data: string;
884
+ driverParam: string;
885
+ notNull: true;
886
+ hasDefault: true;
887
+ isPrimaryKey: false;
888
+ isAutoincrement: false;
889
+ hasRuntimeDefault: false;
890
+ enumValues: [string, ...string[]];
891
+ baseColumn: never;
892
+ identity: undefined;
893
+ generated: undefined;
894
+ }, {}, {}>;
895
+ };
896
+ dialect: "pg";
897
+ }>;
683
898
  /**
684
899
  * Every address ever derived — immutable append-only log.
685
900
  * Used for auditing and ensuring no address is ever reused.
@@ -1,8 +1,8 @@
1
1
  import { sql } from "drizzle-orm";
2
2
  import { boolean, index, integer, pgTable, primaryKey, text } from "drizzle-orm/pg-core";
3
3
  /**
4
- * Crypto payment charges — tracks the lifecycle of each BTCPay invoice.
5
- * reference_id is the BTCPay invoice ID.
4
+ * Crypto payment charges — tracks the lifecycle of each payment.
5
+ * reference_id is the charge ID (e.g. "btc:bc1q...").
6
6
  *
7
7
  * amountUsdCents stores the requested amount in USD cents (integer).
8
8
  * This is NOT nanodollars — Credit.fromCents() handles the conversion
@@ -22,6 +22,11 @@ export const cryptoCharges = pgTable("crypto_charges", {
22
22
  token: text("token"),
23
23
  depositAddress: text("deposit_address"),
24
24
  derivationIndex: integer("derivation_index"),
25
+ callbackUrl: text("callback_url"),
26
+ /** Expected crypto amount in native units (e.g. "76923" sats, "50000000" USDC base units). Locked at creation. */
27
+ expectedAmount: text("expected_amount"),
28
+ /** Running total of received crypto in native units. Accumulates across partial payments. */
29
+ receivedAmount: text("received_amount"),
25
30
  }, (table) => [
26
31
  index("idx_crypto_charges_tenant").on(table.tenantId),
27
32
  index("idx_crypto_charges_status").on(table.status),
@@ -77,6 +82,24 @@ export const pathAllocations = pgTable("path_allocations", {
77
82
  xpub: text("xpub").notNull(),
78
83
  allocatedAt: text("allocated_at").notNull().default(sql `(now())`),
79
84
  }, (table) => [primaryKey({ columns: [table.coinType, table.accountIndex] })]);
85
+ /**
86
+ * Webhook delivery outbox — durable retry for payment callbacks.
87
+ * Inserted when a payment is confirmed. Retried until the receiver ACKs.
88
+ */
89
+ export const webhookDeliveries = pgTable("webhook_deliveries", {
90
+ id: integer("id").primaryKey().generatedAlwaysAsIdentity(),
91
+ chargeId: text("charge_id").notNull(),
92
+ callbackUrl: text("callback_url").notNull(),
93
+ payload: text("payload").notNull(), // JSON stringified
94
+ status: text("status").notNull().default("pending"), // pending, delivered, failed
95
+ attempts: integer("attempts").notNull().default(0),
96
+ nextRetryAt: text("next_retry_at"),
97
+ lastError: text("last_error"),
98
+ createdAt: text("created_at").notNull().default(sql `(now())`),
99
+ }, (table) => [
100
+ index("idx_webhook_deliveries_status").on(table.status),
101
+ index("idx_webhook_deliveries_charge").on(table.chargeId),
102
+ ]);
80
103
  /**
81
104
  * Every address ever derived — immutable append-only log.
82
105
  * Used for auditing and ensuring no address is ever reused.