@wopr-network/platform-core 1.67.0 → 1.67.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.
Files changed (136) hide show
  1. package/dist/billing/crypto/btc/checkout.d.ts +4 -0
  2. package/dist/billing/crypto/btc/checkout.js +1 -2
  3. package/dist/billing/crypto/btc/index.d.ts +0 -4
  4. package/dist/billing/crypto/btc/index.js +0 -2
  5. package/dist/billing/crypto/evm/__tests__/checkout.test.js +8 -11
  6. package/dist/billing/crypto/evm/__tests__/eth-checkout.test.js +15 -1
  7. package/dist/billing/crypto/evm/checkout.d.ts +2 -0
  8. package/dist/billing/crypto/evm/checkout.js +1 -2
  9. package/dist/billing/crypto/evm/eth-checkout.d.ts +13 -2
  10. package/dist/billing/crypto/evm/eth-checkout.js +2 -4
  11. package/dist/billing/crypto/evm/eth-settler.d.ts +1 -1
  12. package/dist/billing/crypto/evm/index.d.ts +2 -8
  13. package/dist/billing/crypto/evm/index.js +0 -3
  14. package/dist/billing/crypto/evm/types.d.ts +16 -0
  15. package/dist/billing/crypto/index.d.ts +1 -6
  16. package/dist/billing/crypto/index.js +2 -3
  17. package/dist/billing/crypto/types.d.ts +0 -43
  18. package/dist/billing/crypto/types.js +1 -24
  19. package/package.json +1 -5
  20. package/src/billing/crypto/btc/checkout.ts +3 -2
  21. package/src/billing/crypto/btc/index.ts +0 -4
  22. package/src/billing/crypto/evm/__tests__/checkout.test.ts +10 -12
  23. package/src/billing/crypto/evm/__tests__/eth-checkout.test.ts +17 -1
  24. package/src/billing/crypto/evm/__tests__/eth-settler.test.ts +1 -1
  25. package/src/billing/crypto/evm/checkout.ts +3 -2
  26. package/src/billing/crypto/evm/eth-checkout.ts +15 -6
  27. package/src/billing/crypto/evm/eth-settler.ts +1 -1
  28. package/src/billing/crypto/evm/index.ts +8 -7
  29. package/src/billing/crypto/evm/types.ts +17 -0
  30. package/src/billing/crypto/index.ts +14 -12
  31. package/src/billing/crypto/types.ts +0 -63
  32. package/dist/billing/crypto/__tests__/address-gen.test.d.ts +0 -1
  33. package/dist/billing/crypto/__tests__/address-gen.test.js +0 -219
  34. package/dist/billing/crypto/__tests__/key-server.test.d.ts +0 -1
  35. package/dist/billing/crypto/__tests__/key-server.test.js +0 -742
  36. package/dist/billing/crypto/__tests__/watcher-service.test.d.ts +0 -1
  37. package/dist/billing/crypto/__tests__/watcher-service.test.js +0 -174
  38. package/dist/billing/crypto/address-gen.d.ts +0 -24
  39. package/dist/billing/crypto/address-gen.js +0 -176
  40. package/dist/billing/crypto/btc/__tests__/watcher.test.d.ts +0 -1
  41. package/dist/billing/crypto/btc/__tests__/watcher.test.js +0 -170
  42. package/dist/billing/crypto/btc/watcher.d.ts +0 -44
  43. package/dist/billing/crypto/btc/watcher.js +0 -118
  44. package/dist/billing/crypto/evm/__tests__/eth-watcher.test.d.ts +0 -1
  45. package/dist/billing/crypto/evm/__tests__/eth-watcher.test.js +0 -167
  46. package/dist/billing/crypto/evm/__tests__/watcher-confirmations.test.d.ts +0 -1
  47. package/dist/billing/crypto/evm/__tests__/watcher-confirmations.test.js +0 -159
  48. package/dist/billing/crypto/evm/__tests__/watcher.test.d.ts +0 -1
  49. package/dist/billing/crypto/evm/__tests__/watcher.test.js +0 -145
  50. package/dist/billing/crypto/evm/eth-watcher.d.ts +0 -66
  51. package/dist/billing/crypto/evm/eth-watcher.js +0 -121
  52. package/dist/billing/crypto/evm/watcher.d.ts +0 -51
  53. package/dist/billing/crypto/evm/watcher.js +0 -156
  54. package/dist/billing/crypto/key-server-entry.d.ts +0 -1
  55. package/dist/billing/crypto/key-server-entry.js +0 -122
  56. package/dist/billing/crypto/key-server.d.ts +0 -32
  57. package/dist/billing/crypto/key-server.js +0 -472
  58. package/dist/billing/crypto/oracle/__tests__/chainlink.test.d.ts +0 -1
  59. package/dist/billing/crypto/oracle/__tests__/chainlink.test.js +0 -83
  60. package/dist/billing/crypto/oracle/__tests__/coingecko.test.d.ts +0 -1
  61. package/dist/billing/crypto/oracle/__tests__/coingecko.test.js +0 -65
  62. package/dist/billing/crypto/oracle/__tests__/composite.test.d.ts +0 -1
  63. package/dist/billing/crypto/oracle/__tests__/composite.test.js +0 -48
  64. package/dist/billing/crypto/oracle/__tests__/convert.test.d.ts +0 -1
  65. package/dist/billing/crypto/oracle/__tests__/convert.test.js +0 -61
  66. package/dist/billing/crypto/oracle/__tests__/fixed.test.d.ts +0 -1
  67. package/dist/billing/crypto/oracle/__tests__/fixed.test.js +0 -20
  68. package/dist/billing/crypto/oracle/chainlink.d.ts +0 -26
  69. package/dist/billing/crypto/oracle/chainlink.js +0 -62
  70. package/dist/billing/crypto/oracle/coingecko.d.ts +0 -22
  71. package/dist/billing/crypto/oracle/coingecko.js +0 -71
  72. package/dist/billing/crypto/oracle/composite.d.ts +0 -14
  73. package/dist/billing/crypto/oracle/composite.js +0 -34
  74. package/dist/billing/crypto/oracle/convert.d.ts +0 -30
  75. package/dist/billing/crypto/oracle/convert.js +0 -51
  76. package/dist/billing/crypto/oracle/fixed.d.ts +0 -10
  77. package/dist/billing/crypto/oracle/fixed.js +0 -22
  78. package/dist/billing/crypto/oracle/index.d.ts +0 -9
  79. package/dist/billing/crypto/oracle/index.js +0 -6
  80. package/dist/billing/crypto/oracle/types.d.ts +0 -22
  81. package/dist/billing/crypto/oracle/types.js +0 -7
  82. package/dist/billing/crypto/plugin/__tests__/integration.test.d.ts +0 -1
  83. package/dist/billing/crypto/plugin/__tests__/integration.test.js +0 -58
  84. package/dist/billing/crypto/plugin/__tests__/interfaces.test.d.ts +0 -1
  85. package/dist/billing/crypto/plugin/__tests__/interfaces.test.js +0 -46
  86. package/dist/billing/crypto/plugin/__tests__/registry.test.d.ts +0 -1
  87. package/dist/billing/crypto/plugin/__tests__/registry.test.js +0 -49
  88. package/dist/billing/crypto/plugin/index.d.ts +0 -2
  89. package/dist/billing/crypto/plugin/index.js +0 -1
  90. package/dist/billing/crypto/plugin/interfaces.d.ts +0 -97
  91. package/dist/billing/crypto/plugin/interfaces.js +0 -2
  92. package/dist/billing/crypto/plugin/registry.d.ts +0 -8
  93. package/dist/billing/crypto/plugin/registry.js +0 -21
  94. package/dist/billing/crypto/plugin-watcher-service.d.ts +0 -32
  95. package/dist/billing/crypto/plugin-watcher-service.js +0 -113
  96. package/dist/billing/crypto/tron/__tests__/address-convert.test.d.ts +0 -1
  97. package/dist/billing/crypto/tron/__tests__/address-convert.test.js +0 -55
  98. package/dist/billing/crypto/tron/address-convert.d.ts +0 -14
  99. package/dist/billing/crypto/tron/address-convert.js +0 -93
  100. package/dist/billing/crypto/watcher-service.d.ts +0 -55
  101. package/dist/billing/crypto/watcher-service.js +0 -438
  102. package/src/billing/crypto/__tests__/address-gen.test.ts +0 -264
  103. package/src/billing/crypto/__tests__/key-server.test.ts +0 -823
  104. package/src/billing/crypto/__tests__/watcher-service.test.ts +0 -242
  105. package/src/billing/crypto/address-gen.ts +0 -185
  106. package/src/billing/crypto/btc/__tests__/watcher.test.ts +0 -201
  107. package/src/billing/crypto/btc/watcher.ts +0 -161
  108. package/src/billing/crypto/evm/__tests__/eth-watcher.test.ts +0 -190
  109. package/src/billing/crypto/evm/__tests__/watcher-confirmations.test.ts +0 -191
  110. package/src/billing/crypto/evm/__tests__/watcher.test.ts +0 -167
  111. package/src/billing/crypto/evm/eth-watcher.ts +0 -182
  112. package/src/billing/crypto/evm/watcher.ts +0 -204
  113. package/src/billing/crypto/key-server-entry.ts +0 -144
  114. package/src/billing/crypto/key-server.ts +0 -617
  115. package/src/billing/crypto/oracle/__tests__/chainlink.test.ts +0 -107
  116. package/src/billing/crypto/oracle/__tests__/coingecko.test.ts +0 -75
  117. package/src/billing/crypto/oracle/__tests__/composite.test.ts +0 -61
  118. package/src/billing/crypto/oracle/__tests__/convert.test.ts +0 -74
  119. package/src/billing/crypto/oracle/__tests__/fixed.test.ts +0 -23
  120. package/src/billing/crypto/oracle/chainlink.ts +0 -86
  121. package/src/billing/crypto/oracle/coingecko.ts +0 -96
  122. package/src/billing/crypto/oracle/composite.ts +0 -35
  123. package/src/billing/crypto/oracle/convert.ts +0 -53
  124. package/src/billing/crypto/oracle/fixed.ts +0 -25
  125. package/src/billing/crypto/oracle/index.ts +0 -9
  126. package/src/billing/crypto/oracle/types.ts +0 -28
  127. package/src/billing/crypto/plugin/__tests__/integration.test.ts +0 -64
  128. package/src/billing/crypto/plugin/__tests__/interfaces.test.ts +0 -51
  129. package/src/billing/crypto/plugin/__tests__/registry.test.ts +0 -58
  130. package/src/billing/crypto/plugin/index.ts +0 -17
  131. package/src/billing/crypto/plugin/interfaces.ts +0 -106
  132. package/src/billing/crypto/plugin/registry.ts +0 -26
  133. package/src/billing/crypto/plugin-watcher-service.ts +0 -148
  134. package/src/billing/crypto/tron/__tests__/address-convert.test.ts +0 -67
  135. package/src/billing/crypto/tron/address-convert.ts +0 -89
  136. package/src/billing/crypto/watcher-service.ts +0 -549
@@ -1,549 +0,0 @@
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 AND confirmations >= required → confirmed + credit
8
- * 4. Every payment/confirmation change 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
-
15
- import { and, eq, isNull, lte, or } from "drizzle-orm";
16
- import type { DrizzleDb } from "../../db/index.js";
17
- import { cryptoCharges, webhookDeliveries } from "../../db/schema/crypto.js";
18
- import type { BtcPaymentEvent } from "./btc/types.js";
19
- import { BtcWatcher, createBitcoindRpc } from "./btc/watcher.js";
20
- import type { ICryptoChargeRepository } from "./charge-store.js";
21
- import type { IWatcherCursorStore } from "./cursor-store.js";
22
- import type { EthPaymentEvent } from "./evm/eth-watcher.js";
23
- import { EthWatcher } from "./evm/eth-watcher.js";
24
- import type { EvmChain, EvmPaymentEvent, StablecoinToken } from "./evm/types.js";
25
- import { createRpcCaller, EvmWatcher } from "./evm/watcher.js";
26
- import type { IPriceOracle } from "./oracle/types.js";
27
- import type { IPaymentMethodStore } from "./payment-method-store.js";
28
- import { hexToTron, isTronAddress, tronToHex } from "./tron/address-convert.js";
29
- import type { CryptoChargeStatus } from "./types.js";
30
-
31
- const MAX_DELIVERY_ATTEMPTS = 10;
32
- const BACKOFF_BASE_MS = 5_000;
33
-
34
- export interface WatcherServiceOpts {
35
- db: DrizzleDb;
36
- chargeStore: ICryptoChargeRepository;
37
- methodStore: IPaymentMethodStore;
38
- cursorStore: IWatcherCursorStore;
39
- oracle: IPriceOracle;
40
- bitcoindUser?: string;
41
- bitcoindPassword?: string;
42
- pollIntervalMs?: number;
43
- deliveryIntervalMs?: number;
44
- log?: (msg: string, meta?: Record<string, unknown>) => void;
45
- /** Allowed callback URL prefixes. Default: ["https://"] — enforces HTTPS. */
46
- allowedCallbackPrefixes?: string[];
47
- /** Service key sent as Bearer token in webhook deliveries. */
48
- serviceKey?: string;
49
- }
50
-
51
- // --- SSRF validation ---
52
-
53
- function isValidCallbackUrl(url: string, allowedPrefixes: string[]): boolean {
54
- try {
55
- const parsed = new URL(url);
56
- if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return false;
57
- const host = parsed.hostname;
58
- if (host === "localhost" || host === "127.0.0.1" || host === "0.0.0.0" || host === "::1") return false;
59
- if (host.startsWith("10.") || host.startsWith("192.168.") || host.startsWith("169.254.")) return false;
60
- return allowedPrefixes.some((prefix) => url.startsWith(prefix));
61
- } catch {
62
- return false;
63
- }
64
- }
65
-
66
- // --- Webhook outbox ---
67
-
68
- async function enqueueWebhook(
69
- db: DrizzleDb,
70
- chargeId: string,
71
- callbackUrl: string,
72
- payload: Record<string, unknown>,
73
- ): Promise<void> {
74
- await db.insert(webhookDeliveries).values({
75
- chargeId,
76
- callbackUrl,
77
- payload: JSON.stringify(payload),
78
- });
79
- }
80
-
81
- async function processDeliveries(
82
- db: DrizzleDb,
83
- allowedPrefixes: string[],
84
- log: (msg: string, meta?: Record<string, unknown>) => void,
85
- serviceKey?: string,
86
- ): Promise<number> {
87
- const now = new Date().toISOString();
88
- const pending = await db
89
- .select()
90
- .from(webhookDeliveries)
91
- .where(
92
- and(
93
- eq(webhookDeliveries.status, "pending"),
94
- or(isNull(webhookDeliveries.nextRetryAt), lte(webhookDeliveries.nextRetryAt, now)),
95
- ),
96
- )
97
- .limit(50);
98
-
99
- let delivered = 0;
100
- for (const row of pending) {
101
- if (!isValidCallbackUrl(row.callbackUrl, allowedPrefixes)) {
102
- await db
103
- .update(webhookDeliveries)
104
- .set({ status: "failed", lastError: "Invalid callbackUrl (SSRF blocked)" })
105
- .where(eq(webhookDeliveries.id, row.id));
106
- continue;
107
- }
108
-
109
- try {
110
- const headers: Record<string, string> = { "Content-Type": "application/json" };
111
- if (serviceKey) headers.Authorization = `Bearer ${serviceKey}`;
112
- const res = await fetch(row.callbackUrl, {
113
- method: "POST",
114
- headers,
115
- body: row.payload,
116
- });
117
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
118
-
119
- await db.update(webhookDeliveries).set({ status: "delivered" }).where(eq(webhookDeliveries.id, row.id));
120
- delivered++;
121
- } catch (err) {
122
- const attempts = row.attempts + 1;
123
- if (attempts >= MAX_DELIVERY_ATTEMPTS) {
124
- await db
125
- .update(webhookDeliveries)
126
- .set({ status: "failed", attempts, lastError: String(err) })
127
- .where(eq(webhookDeliveries.id, row.id));
128
- log("Webhook permanently failed", { chargeId: row.chargeId, attempts });
129
- } else {
130
- const backoffMs = BACKOFF_BASE_MS * 2 ** (attempts - 1);
131
- const nextRetry = new Date(Date.now() + backoffMs).toISOString();
132
- await db
133
- .update(webhookDeliveries)
134
- .set({ attempts, nextRetryAt: nextRetry, lastError: String(err) })
135
- .where(eq(webhookDeliveries.id, row.id));
136
- }
137
- }
138
- }
139
- return delivered;
140
- }
141
-
142
- // --- Payment handling (partial + full + confirmation tracking) ---
143
-
144
- export interface PaymentPayload {
145
- txHash: string;
146
- confirmations: number;
147
- confirmationsRequired: number;
148
- amountReceivedCents: number;
149
- [key: string]: unknown;
150
- }
151
-
152
- /**
153
- * Handle a payment event. Accumulates partial payments in native units.
154
- * Fires webhook on every payment/confirmation change with canonical statuses.
155
- *
156
- * 3-phase webhook lifecycle:
157
- * 1. Tx first seen -> status: "partial", confirmations: 0
158
- * 2. Each new block -> status: "partial", confirmations: current
159
- * 3. Threshold reached + full payment -> status: "confirmed"
160
- *
161
- * @param nativeAmount — received amount in native base units (sats for BTC/DOGE, raw token units for ERC20).
162
- * Pass "0" for confirmation-only updates (no new payment, just more confirmations).
163
- */
164
- export async function handlePayment(
165
- db: DrizzleDb,
166
- chargeStore: ICryptoChargeRepository,
167
- address: string,
168
- nativeAmount: string,
169
- payload: PaymentPayload,
170
- log: (msg: string, meta?: Record<string, unknown>) => void,
171
- ): Promise<void> {
172
- const charge = await chargeStore.getByDepositAddress(address);
173
- if (!charge) {
174
- log("Payment to unknown address", { address });
175
- return;
176
- }
177
- if (charge.creditedAt) {
178
- return; // Already fully paid and credited
179
- }
180
-
181
- const { confirmations, confirmationsRequired, amountReceivedCents, txHash } = payload;
182
-
183
- // Accumulate: add this payment to the running total (if nativeAmount > 0)
184
- const prevReceived = BigInt(charge.receivedAmount ?? "0");
185
- const thisPayment = BigInt(nativeAmount);
186
- const totalReceived = (prevReceived + thisPayment).toString();
187
- const expected = BigInt(charge.expectedAmount ?? "0");
188
- const isFull = expected > 0n && BigInt(totalReceived) >= expected;
189
- const isConfirmed = isFull && confirmations >= confirmationsRequired;
190
-
191
- // Update received_amount in DB (only when there's a new payment)
192
- if (thisPayment > 0n) {
193
- await db
194
- .update(cryptoCharges)
195
- .set({ receivedAmount: totalReceived, filledAmount: totalReceived })
196
- .where(eq(cryptoCharges.referenceId, charge.referenceId));
197
- }
198
-
199
- // Determine canonical status
200
- const status: CryptoChargeStatus = isConfirmed ? "confirmed" : "partial";
201
-
202
- // Update progress via new API
203
- await chargeStore.updateProgress(charge.referenceId, {
204
- status,
205
- amountReceivedCents,
206
- confirmations,
207
- confirmationsRequired,
208
- txHash,
209
- });
210
-
211
- if (isConfirmed) {
212
- await chargeStore.markCredited(charge.referenceId);
213
- log("Charge confirmed", {
214
- chargeId: charge.referenceId,
215
- confirmations,
216
- confirmationsRequired,
217
- });
218
- } else {
219
- log("Payment progress", {
220
- chargeId: charge.referenceId,
221
- confirmations,
222
- confirmationsRequired,
223
- received: totalReceived,
224
- });
225
- }
226
-
227
- // Webhook on every event — product shows confirmation progress to user
228
- if (charge.callbackUrl) {
229
- await enqueueWebhook(db, charge.referenceId, charge.callbackUrl, {
230
- chargeId: charge.referenceId,
231
- chain: charge.chain,
232
- address: charge.depositAddress,
233
- amountExpectedCents: charge.amountUsdCents,
234
- amountReceivedCents,
235
- confirmations,
236
- confirmationsRequired,
237
- txHash,
238
- status,
239
- });
240
- }
241
- }
242
-
243
- // --- Watcher boot ---
244
-
245
- export async function startWatchers(opts: WatcherServiceOpts): Promise<() => void> {
246
- const { db, chargeStore, methodStore, cursorStore, oracle } = opts;
247
- const pollMs = opts.pollIntervalMs ?? 15_000;
248
- const deliveryMs = opts.deliveryIntervalMs ?? 10_000;
249
- const log = opts.log ?? (() => {});
250
- const allowedPrefixes = opts.allowedCallbackPrefixes ?? ["https://"];
251
- const serviceKey = opts.serviceKey;
252
- const timers: ReturnType<typeof setInterval>[] = [];
253
-
254
- const methods = await methodStore.listEnabled();
255
-
256
- // Route watchers by DB-driven watcherType — no hardcoded chain names.
257
- // Adding a new chain is a DB INSERT with watcher_type = "utxo" or "evm".
258
- const utxoMethods = methods.filter((m) => m.watcherType === "utxo");
259
- const evmMethods = methods.filter((m) => m.watcherType === "evm");
260
-
261
- // --- UTXO Watchers (BTC, LTC, DOGE) ---
262
- for (const method of utxoMethods) {
263
- if (!method.rpcUrl) continue;
264
-
265
- const rpcCall = createBitcoindRpc({
266
- rpcUrl: method.rpcUrl,
267
- rpcUser: opts.bitcoindUser ?? "btcpay",
268
- rpcPassword: opts.bitcoindPassword ?? "",
269
- network: "mainnet",
270
- confirmations: method.confirmations,
271
- });
272
-
273
- const activeAddresses = await chargeStore.listActiveDepositAddresses();
274
- const chainAddresses = activeAddresses.filter((a) => a.chain === method.chain).map((a) => a.address);
275
-
276
- const watcher = new BtcWatcher({
277
- config: {
278
- rpcUrl: method.rpcUrl,
279
- rpcUser: opts.bitcoindUser ?? "btcpay",
280
- rpcPassword: opts.bitcoindPassword ?? "",
281
- network: "mainnet",
282
- confirmations: method.confirmations,
283
- },
284
- chainId: method.chain,
285
- rpcCall,
286
- watchedAddresses: chainAddresses,
287
- oracle,
288
- cursorStore,
289
- onPayment: async (event: BtcPaymentEvent) => {
290
- log("UTXO payment", {
291
- chain: method.chain,
292
- address: event.address,
293
- txid: event.txid,
294
- sats: event.amountSats,
295
- confirmations: event.confirmations,
296
- confirmationsRequired: event.confirmationsRequired,
297
- });
298
- await handlePayment(
299
- db,
300
- chargeStore,
301
- event.address,
302
- String(event.amountSats),
303
- {
304
- txHash: event.txid,
305
- confirmations: event.confirmations,
306
- confirmationsRequired: event.confirmationsRequired,
307
- amountReceivedCents: event.amountUsdCents,
308
- },
309
- log,
310
- );
311
- },
312
- });
313
-
314
- const importedAddresses = new Set<string>();
315
- for (const addr of chainAddresses) {
316
- try {
317
- await watcher.importAddress(addr);
318
- importedAddresses.add(addr);
319
- } catch {
320
- log("Failed to import address", { chain: method.chain, address: addr });
321
- }
322
- }
323
-
324
- log(`UTXO watcher started (${method.chain})`, { addresses: importedAddresses.size });
325
-
326
- let utxoPolling = false;
327
- timers.push(
328
- setInterval(async () => {
329
- if (utxoPolling) return; // Prevent overlapping polls
330
- utxoPolling = true;
331
- try {
332
- const fresh = await chargeStore.listActiveDepositAddresses();
333
- const freshChain = fresh.filter((a) => a.chain === method.chain).map((a) => a.address);
334
-
335
- for (const addr of freshChain) {
336
- if (!importedAddresses.has(addr)) {
337
- try {
338
- await watcher.importAddress(addr);
339
- importedAddresses.add(addr);
340
- } catch {
341
- log("Failed to import new address (will retry)", { chain: method.chain, address: addr });
342
- }
343
- }
344
- }
345
-
346
- watcher.setWatchedAddresses(freshChain);
347
- await watcher.poll();
348
- } catch (err) {
349
- log("UTXO poll error", { chain: method.chain, error: String(err) });
350
- } finally {
351
- utxoPolling = false;
352
- }
353
- }, pollMs),
354
- );
355
- }
356
-
357
- // --- Native ETH Watchers (block-scanning for value transfers) ---
358
- const nativeEvmMethods = evmMethods.filter((m) => m.type === "native");
359
- const erc20Methods = evmMethods.filter((m) => m.type === "erc20" && m.contractAddress);
360
-
361
- const BACKFILL_BLOCKS = 1000; // Scan ~30min of blocks on first deploy to catch missed deposits
362
-
363
- // Address conversion for EVM-watched chains with non-0x address formats (Tron T...).
364
- // Only applies to chains routed through the EVM watcher but storing non-hex addresses.
365
- // UTXO chains (DOGE p2pkh) never enter this path — they use the UTXO watcher.
366
- const isTronMethod = (method: { addressType: string; chain: string }): boolean =>
367
- (method.addressType === "p2pkh" || method.addressType === "keccak-b58check") && method.chain === "tron";
368
- const toWatcherAddr = (addr: string, method: { addressType: string; chain: string }): string =>
369
- isTronMethod(method) && isTronAddress(addr) ? tronToHex(addr) : addr;
370
- const fromWatcherAddr = (addr: string, method: { addressType: string; chain: string }): string =>
371
- isTronMethod(method) ? hexToTron(addr) : addr;
372
-
373
- for (const method of nativeEvmMethods) {
374
- if (!method.rpcUrl) continue;
375
-
376
- const rpcCall = createRpcCaller(method.rpcUrl, JSON.parse(method.rpcHeaders ?? "{}"));
377
- let latestBlock: number;
378
- try {
379
- const latestHex = (await rpcCall("eth_blockNumber", [])) as string;
380
- latestBlock = Number.parseInt(latestHex, 16);
381
- } catch (err) {
382
- log("Skipping ETH watcher — RPC unreachable", { chain: method.chain, token: method.token, error: String(err) });
383
- continue;
384
- }
385
- const backfillStart = Math.max(0, latestBlock - BACKFILL_BLOCKS);
386
-
387
- const activeAddresses = await chargeStore.listActiveDepositAddresses();
388
- // Only watch addresses for native charges on this chain (not ERC20 charges)
389
- const chainAddresses = activeAddresses
390
- .filter((a) => a.chain === method.chain && a.token === method.token)
391
- .map((a) => a.address);
392
-
393
- const watcher = new EthWatcher({
394
- chain: method.chain as EvmChain,
395
- rpcCall,
396
- oracle,
397
- fromBlock: backfillStart,
398
- watchedAddresses: chainAddresses.map((a) => toWatcherAddr(a, method)),
399
- cursorStore,
400
- confirmations: method.confirmations,
401
- onPayment: async (event: EthPaymentEvent) => {
402
- const dbAddr = fromWatcherAddr(event.to, method);
403
- log("ETH payment", {
404
- chain: event.chain,
405
- to: dbAddr,
406
- txHash: event.txHash,
407
- valueWei: event.valueWei,
408
- confirmations: event.confirmations,
409
- confirmationsRequired: event.confirmationsRequired,
410
- });
411
- await handlePayment(
412
- db,
413
- chargeStore,
414
- dbAddr,
415
- event.valueWei,
416
- {
417
- txHash: event.txHash,
418
- confirmations: event.confirmations,
419
- confirmationsRequired: event.confirmationsRequired,
420
- amountReceivedCents: event.amountUsdCents,
421
- },
422
- log,
423
- );
424
- },
425
- });
426
-
427
- await watcher.init();
428
- log(`ETH watcher started (${method.chain}:${method.token})`, { addresses: chainAddresses.length });
429
-
430
- let ethPolling = false;
431
- timers.push(
432
- setInterval(async () => {
433
- if (ethPolling) return;
434
- ethPolling = true;
435
- try {
436
- const fresh = await chargeStore.listActiveDepositAddresses();
437
- const freshNative = fresh
438
- .filter((a) => a.chain === method.chain && a.token === method.token)
439
- .map((a) => a.address);
440
- watcher.setWatchedAddresses(freshNative.map((a) => toWatcherAddr(a, method)));
441
- await watcher.poll();
442
- } catch (err) {
443
- log("ETH poll error", { chain: method.chain, error: String(err) });
444
- } finally {
445
- ethPolling = false;
446
- }
447
- }, pollMs),
448
- );
449
- }
450
-
451
- // --- ERC20 Watchers (log-based Transfer event scanning) ---
452
- for (const method of erc20Methods) {
453
- if (!method.rpcUrl || !method.contractAddress) continue;
454
-
455
- const rpcCall = createRpcCaller(method.rpcUrl, JSON.parse(method.rpcHeaders ?? "{}"));
456
- let latestBlock: number;
457
- try {
458
- const latestHex = (await rpcCall("eth_blockNumber", [])) as string;
459
- latestBlock = Number.parseInt(latestHex, 16);
460
- } catch (err) {
461
- log("Skipping EVM watcher — RPC unreachable", { chain: method.chain, token: method.token, error: String(err) });
462
- continue;
463
- }
464
-
465
- const activeAddresses = await chargeStore.listActiveDepositAddresses();
466
- const chainAddresses = activeAddresses.filter((a) => a.chain === method.chain).map((a) => a.address);
467
-
468
- const watcher = new EvmWatcher({
469
- chain: method.chain as EvmChain,
470
- token: method.token as StablecoinToken,
471
- rpcCall,
472
- fromBlock: latestBlock,
473
- watchedAddresses: chainAddresses.map((a) => toWatcherAddr(a, method)),
474
- contractAddress: toWatcherAddr(method.contractAddress, method),
475
- decimals: method.decimals,
476
- confirmations: method.confirmations,
477
- cursorStore,
478
- onPayment: async (event: EvmPaymentEvent) => {
479
- const dbAddr = fromWatcherAddr(event.to, method);
480
- log("EVM payment", {
481
- chain: event.chain,
482
- token: event.token,
483
- to: dbAddr,
484
- txHash: event.txHash,
485
- confirmations: event.confirmations,
486
- confirmationsRequired: event.confirmationsRequired,
487
- });
488
- await handlePayment(
489
- db,
490
- chargeStore,
491
- dbAddr,
492
- event.rawAmount,
493
- {
494
- txHash: event.txHash,
495
- confirmations: event.confirmations,
496
- confirmationsRequired: event.confirmationsRequired,
497
- amountReceivedCents: event.amountUsdCents,
498
- },
499
- log,
500
- );
501
- },
502
- });
503
-
504
- await watcher.init();
505
- log(`EVM watcher started (${method.chain}:${method.token})`, { addresses: chainAddresses.length });
506
-
507
- let evmPolling = false;
508
- timers.push(
509
- setInterval(async () => {
510
- if (evmPolling) return;
511
- evmPolling = true;
512
- try {
513
- const fresh = await chargeStore.listActiveDepositAddresses();
514
- const freshChain = fresh.filter((a) => a.chain === method.chain).map((a) => a.address);
515
- watcher.setWatchedAddresses(freshChain.map((a) => toWatcherAddr(a, method)));
516
- await watcher.poll();
517
- } catch (err) {
518
- log("EVM poll error", { chain: method.chain, token: method.token, error: String(err) });
519
- } finally {
520
- evmPolling = false;
521
- }
522
- }, pollMs),
523
- );
524
- }
525
-
526
- // --- Webhook delivery outbox processor ---
527
- timers.push(
528
- setInterval(async () => {
529
- try {
530
- const count = await processDeliveries(db, allowedPrefixes, log, serviceKey);
531
- if (count > 0) log("Webhooks delivered", { count });
532
- } catch (err) {
533
- log("Delivery loop error", { error: String(err) });
534
- }
535
- }, deliveryMs),
536
- );
537
-
538
- log("All watchers started", {
539
- utxo: utxoMethods.length,
540
- evm: erc20Methods.length,
541
- eth: nativeEvmMethods.length,
542
- pollMs,
543
- deliveryMs,
544
- });
545
-
546
- return () => {
547
- for (const t of timers) clearInterval(t);
548
- };
549
- }