@wopr-network/platform-core 1.67.0 → 1.68.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 (140) hide show
  1. package/dist/auth/better-auth.js +7 -0
  2. package/dist/billing/crypto/btc/checkout.d.ts +4 -0
  3. package/dist/billing/crypto/btc/checkout.js +1 -2
  4. package/dist/billing/crypto/btc/index.d.ts +0 -4
  5. package/dist/billing/crypto/btc/index.js +0 -2
  6. package/dist/billing/crypto/evm/__tests__/checkout.test.js +8 -11
  7. package/dist/billing/crypto/evm/__tests__/eth-checkout.test.js +15 -1
  8. package/dist/billing/crypto/evm/checkout.d.ts +2 -0
  9. package/dist/billing/crypto/evm/checkout.js +1 -2
  10. package/dist/billing/crypto/evm/eth-checkout.d.ts +13 -2
  11. package/dist/billing/crypto/evm/eth-checkout.js +2 -4
  12. package/dist/billing/crypto/evm/eth-settler.d.ts +1 -1
  13. package/dist/billing/crypto/evm/index.d.ts +2 -8
  14. package/dist/billing/crypto/evm/index.js +0 -3
  15. package/dist/billing/crypto/evm/types.d.ts +16 -0
  16. package/dist/billing/crypto/index.d.ts +1 -6
  17. package/dist/billing/crypto/index.js +2 -3
  18. package/dist/billing/crypto/types.d.ts +0 -43
  19. package/dist/billing/crypto/types.js +1 -24
  20. package/dist/email/client.js +16 -0
  21. package/package.json +4 -7
  22. package/src/auth/better-auth.ts +8 -0
  23. package/src/billing/crypto/btc/checkout.ts +3 -2
  24. package/src/billing/crypto/btc/index.ts +0 -4
  25. package/src/billing/crypto/evm/__tests__/checkout.test.ts +10 -12
  26. package/src/billing/crypto/evm/__tests__/eth-checkout.test.ts +17 -1
  27. package/src/billing/crypto/evm/__tests__/eth-settler.test.ts +1 -1
  28. package/src/billing/crypto/evm/checkout.ts +3 -2
  29. package/src/billing/crypto/evm/eth-checkout.ts +15 -6
  30. package/src/billing/crypto/evm/eth-settler.ts +1 -1
  31. package/src/billing/crypto/evm/index.ts +8 -7
  32. package/src/billing/crypto/evm/types.ts +17 -0
  33. package/src/billing/crypto/index.ts +14 -12
  34. package/src/billing/crypto/types.ts +0 -63
  35. package/src/email/client.ts +18 -0
  36. package/dist/billing/crypto/__tests__/address-gen.test.d.ts +0 -1
  37. package/dist/billing/crypto/__tests__/address-gen.test.js +0 -219
  38. package/dist/billing/crypto/__tests__/key-server.test.d.ts +0 -1
  39. package/dist/billing/crypto/__tests__/key-server.test.js +0 -742
  40. package/dist/billing/crypto/__tests__/watcher-service.test.d.ts +0 -1
  41. package/dist/billing/crypto/__tests__/watcher-service.test.js +0 -174
  42. package/dist/billing/crypto/address-gen.d.ts +0 -24
  43. package/dist/billing/crypto/address-gen.js +0 -176
  44. package/dist/billing/crypto/btc/__tests__/watcher.test.d.ts +0 -1
  45. package/dist/billing/crypto/btc/__tests__/watcher.test.js +0 -170
  46. package/dist/billing/crypto/btc/watcher.d.ts +0 -44
  47. package/dist/billing/crypto/btc/watcher.js +0 -118
  48. package/dist/billing/crypto/evm/__tests__/eth-watcher.test.d.ts +0 -1
  49. package/dist/billing/crypto/evm/__tests__/eth-watcher.test.js +0 -167
  50. package/dist/billing/crypto/evm/__tests__/watcher-confirmations.test.d.ts +0 -1
  51. package/dist/billing/crypto/evm/__tests__/watcher-confirmations.test.js +0 -159
  52. package/dist/billing/crypto/evm/__tests__/watcher.test.d.ts +0 -1
  53. package/dist/billing/crypto/evm/__tests__/watcher.test.js +0 -145
  54. package/dist/billing/crypto/evm/eth-watcher.d.ts +0 -66
  55. package/dist/billing/crypto/evm/eth-watcher.js +0 -121
  56. package/dist/billing/crypto/evm/watcher.d.ts +0 -51
  57. package/dist/billing/crypto/evm/watcher.js +0 -156
  58. package/dist/billing/crypto/key-server-entry.d.ts +0 -1
  59. package/dist/billing/crypto/key-server-entry.js +0 -122
  60. package/dist/billing/crypto/key-server.d.ts +0 -32
  61. package/dist/billing/crypto/key-server.js +0 -472
  62. package/dist/billing/crypto/oracle/__tests__/chainlink.test.d.ts +0 -1
  63. package/dist/billing/crypto/oracle/__tests__/chainlink.test.js +0 -83
  64. package/dist/billing/crypto/oracle/__tests__/coingecko.test.d.ts +0 -1
  65. package/dist/billing/crypto/oracle/__tests__/coingecko.test.js +0 -65
  66. package/dist/billing/crypto/oracle/__tests__/composite.test.d.ts +0 -1
  67. package/dist/billing/crypto/oracle/__tests__/composite.test.js +0 -48
  68. package/dist/billing/crypto/oracle/__tests__/convert.test.d.ts +0 -1
  69. package/dist/billing/crypto/oracle/__tests__/convert.test.js +0 -61
  70. package/dist/billing/crypto/oracle/__tests__/fixed.test.d.ts +0 -1
  71. package/dist/billing/crypto/oracle/__tests__/fixed.test.js +0 -20
  72. package/dist/billing/crypto/oracle/chainlink.d.ts +0 -26
  73. package/dist/billing/crypto/oracle/chainlink.js +0 -62
  74. package/dist/billing/crypto/oracle/coingecko.d.ts +0 -22
  75. package/dist/billing/crypto/oracle/coingecko.js +0 -71
  76. package/dist/billing/crypto/oracle/composite.d.ts +0 -14
  77. package/dist/billing/crypto/oracle/composite.js +0 -34
  78. package/dist/billing/crypto/oracle/convert.d.ts +0 -30
  79. package/dist/billing/crypto/oracle/convert.js +0 -51
  80. package/dist/billing/crypto/oracle/fixed.d.ts +0 -10
  81. package/dist/billing/crypto/oracle/fixed.js +0 -22
  82. package/dist/billing/crypto/oracle/index.d.ts +0 -9
  83. package/dist/billing/crypto/oracle/index.js +0 -6
  84. package/dist/billing/crypto/oracle/types.d.ts +0 -22
  85. package/dist/billing/crypto/oracle/types.js +0 -7
  86. package/dist/billing/crypto/plugin/__tests__/integration.test.d.ts +0 -1
  87. package/dist/billing/crypto/plugin/__tests__/integration.test.js +0 -58
  88. package/dist/billing/crypto/plugin/__tests__/interfaces.test.d.ts +0 -1
  89. package/dist/billing/crypto/plugin/__tests__/interfaces.test.js +0 -46
  90. package/dist/billing/crypto/plugin/__tests__/registry.test.d.ts +0 -1
  91. package/dist/billing/crypto/plugin/__tests__/registry.test.js +0 -49
  92. package/dist/billing/crypto/plugin/index.d.ts +0 -2
  93. package/dist/billing/crypto/plugin/index.js +0 -1
  94. package/dist/billing/crypto/plugin/interfaces.d.ts +0 -97
  95. package/dist/billing/crypto/plugin/interfaces.js +0 -2
  96. package/dist/billing/crypto/plugin/registry.d.ts +0 -8
  97. package/dist/billing/crypto/plugin/registry.js +0 -21
  98. package/dist/billing/crypto/plugin-watcher-service.d.ts +0 -32
  99. package/dist/billing/crypto/plugin-watcher-service.js +0 -113
  100. package/dist/billing/crypto/tron/__tests__/address-convert.test.d.ts +0 -1
  101. package/dist/billing/crypto/tron/__tests__/address-convert.test.js +0 -55
  102. package/dist/billing/crypto/tron/address-convert.d.ts +0 -14
  103. package/dist/billing/crypto/tron/address-convert.js +0 -93
  104. package/dist/billing/crypto/watcher-service.d.ts +0 -55
  105. package/dist/billing/crypto/watcher-service.js +0 -438
  106. package/src/billing/crypto/__tests__/address-gen.test.ts +0 -264
  107. package/src/billing/crypto/__tests__/key-server.test.ts +0 -823
  108. package/src/billing/crypto/__tests__/watcher-service.test.ts +0 -242
  109. package/src/billing/crypto/address-gen.ts +0 -185
  110. package/src/billing/crypto/btc/__tests__/watcher.test.ts +0 -201
  111. package/src/billing/crypto/btc/watcher.ts +0 -161
  112. package/src/billing/crypto/evm/__tests__/eth-watcher.test.ts +0 -190
  113. package/src/billing/crypto/evm/__tests__/watcher-confirmations.test.ts +0 -191
  114. package/src/billing/crypto/evm/__tests__/watcher.test.ts +0 -167
  115. package/src/billing/crypto/evm/eth-watcher.ts +0 -182
  116. package/src/billing/crypto/evm/watcher.ts +0 -204
  117. package/src/billing/crypto/key-server-entry.ts +0 -144
  118. package/src/billing/crypto/key-server.ts +0 -617
  119. package/src/billing/crypto/oracle/__tests__/chainlink.test.ts +0 -107
  120. package/src/billing/crypto/oracle/__tests__/coingecko.test.ts +0 -75
  121. package/src/billing/crypto/oracle/__tests__/composite.test.ts +0 -61
  122. package/src/billing/crypto/oracle/__tests__/convert.test.ts +0 -74
  123. package/src/billing/crypto/oracle/__tests__/fixed.test.ts +0 -23
  124. package/src/billing/crypto/oracle/chainlink.ts +0 -86
  125. package/src/billing/crypto/oracle/coingecko.ts +0 -96
  126. package/src/billing/crypto/oracle/composite.ts +0 -35
  127. package/src/billing/crypto/oracle/convert.ts +0 -53
  128. package/src/billing/crypto/oracle/fixed.ts +0 -25
  129. package/src/billing/crypto/oracle/index.ts +0 -9
  130. package/src/billing/crypto/oracle/types.ts +0 -28
  131. package/src/billing/crypto/plugin/__tests__/integration.test.ts +0 -64
  132. package/src/billing/crypto/plugin/__tests__/interfaces.test.ts +0 -51
  133. package/src/billing/crypto/plugin/__tests__/registry.test.ts +0 -58
  134. package/src/billing/crypto/plugin/index.ts +0 -17
  135. package/src/billing/crypto/plugin/interfaces.ts +0 -106
  136. package/src/billing/crypto/plugin/registry.ts +0 -26
  137. package/src/billing/crypto/plugin-watcher-service.ts +0 -148
  138. package/src/billing/crypto/tron/__tests__/address-convert.test.ts +0 -67
  139. package/src/billing/crypto/tron/address-convert.ts +0 -89
  140. package/src/billing/crypto/watcher-service.ts +0 -549
@@ -1,118 +0,0 @@
1
- import { nativeToCents } from "../oracle/convert.js";
2
- export class BtcWatcher {
3
- rpc;
4
- addresses;
5
- onPayment;
6
- minConfirmations;
7
- oracle;
8
- cursorStore;
9
- watcherId;
10
- constructor(opts) {
11
- this.rpc = opts.rpcCall;
12
- this.addresses = new Set(opts.watchedAddresses);
13
- this.onPayment = opts.onPayment;
14
- this.minConfirmations = opts.config.confirmations;
15
- this.oracle = opts.oracle;
16
- this.cursorStore = opts.cursorStore;
17
- this.watcherId = `btc:${opts.chainId ?? opts.config.network}`;
18
- }
19
- /** Update the set of watched addresses. */
20
- setWatchedAddresses(addresses) {
21
- this.addresses.clear();
22
- for (const a of addresses)
23
- this.addresses.add(a);
24
- }
25
- /**
26
- * Import an address into bitcoind's wallet (watch-only).
27
- * Uses `importdescriptors` (modern bitcoind v24+) with fallback to legacy `importaddress`.
28
- */
29
- async importAddress(address) {
30
- try {
31
- // Modern bitcoind: get descriptor checksum, then import
32
- const info = (await this.rpc("getdescriptorinfo", [`addr(${address})`]));
33
- const result = (await this.rpc("importdescriptors", [[{ desc: info.descriptor, timestamp: 0 }]]));
34
- if (result[0] && !result[0].success) {
35
- throw new Error(result[0].error?.message ?? "importdescriptors failed");
36
- }
37
- }
38
- catch {
39
- // Fallback: legacy importaddress (bitcoind <v24)
40
- await this.rpc("importaddress", [address, "", false]);
41
- }
42
- this.addresses.add(address);
43
- }
44
- /**
45
- * Poll for payments to watched addresses, including unconfirmed txs.
46
- *
47
- * Fires onPayment on every confirmation increment (0, 1, 2, ... threshold).
48
- * Only marks a tx as fully processed once it reaches the confirmation threshold.
49
- */
50
- async poll() {
51
- if (this.addresses.size === 0)
52
- return;
53
- // Poll with minconf=0 to see unconfirmed txs
54
- const received = (await this.rpc("listreceivedbyaddress", [
55
- 0, // minconf=0: see ALL txs including unconfirmed
56
- false, // include_empty
57
- true, // include_watchonly
58
- ]));
59
- const { priceMicros } = await this.oracle.getPrice("BTC");
60
- for (const entry of received) {
61
- if (!this.addresses.has(entry.address))
62
- continue;
63
- for (const txid of entry.txids) {
64
- // Skip fully-processed txids (already reached threshold, persisted to DB)
65
- if (await this.cursorStore.hasProcessedTx(this.watcherId, txid))
66
- continue;
67
- // Get transaction details for the exact amount sent to this address
68
- const tx = (await this.rpc("gettransaction", [txid, true]));
69
- const detail = tx.details.find((d) => d.address === entry.address && d.category === "receive");
70
- if (!detail)
71
- continue;
72
- // Check if confirmations have increased since last seen
73
- const lastSeen = await this.cursorStore.getConfirmationCount(this.watcherId, txid);
74
- if (lastSeen !== null && tx.confirmations <= lastSeen)
75
- continue; // No change
76
- const amountSats = Math.round(detail.amount * 100_000_000);
77
- // priceMicros is microdollars per 1 BTC. Convert sats→USD cents via nativeToCents.
78
- const amountUsdCents = nativeToCents(BigInt(amountSats), priceMicros, 8);
79
- const event = {
80
- address: entry.address,
81
- txid,
82
- amountSats,
83
- amountUsdCents,
84
- confirmations: tx.confirmations,
85
- confirmationsRequired: this.minConfirmations,
86
- };
87
- await this.onPayment(event);
88
- // Persist confirmation count
89
- await this.cursorStore.saveConfirmationCount(this.watcherId, txid, tx.confirmations);
90
- // Mark as fully processed once we reach the threshold
91
- if (tx.confirmations >= this.minConfirmations) {
92
- await this.cursorStore.markProcessedTx(this.watcherId, txid);
93
- }
94
- }
95
- }
96
- }
97
- }
98
- /** Create a bitcoind JSON-RPC caller with basic auth. */
99
- export function createBitcoindRpc(config) {
100
- let id = 0;
101
- const auth = btoa(`${config.rpcUser}:${config.rpcPassword}`);
102
- return async (method, params) => {
103
- const res = await fetch(config.rpcUrl, {
104
- method: "POST",
105
- headers: {
106
- "Content-Type": "application/json",
107
- Authorization: `Basic ${auth}`,
108
- },
109
- body: JSON.stringify({ jsonrpc: "1.0", id: ++id, method, params }),
110
- });
111
- if (!res.ok)
112
- throw new Error(`bitcoind ${method} failed: ${res.status}`);
113
- const data = (await res.json());
114
- if (data.error)
115
- throw new Error(`bitcoind ${method}: ${data.error.message}`);
116
- return data.result;
117
- };
118
- }
@@ -1,167 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
- import { EthWatcher } from "../eth-watcher.js";
3
- function makeRpc(responses) {
4
- return vi.fn(async (method) => responses[method]);
5
- }
6
- const mockOracle = { getPrice: vi.fn().mockResolvedValue({ priceMicros: 3_500_000_000, updatedAt: new Date() }) };
7
- describe("EthWatcher", () => {
8
- it("detects native ETH transfer to watched address", async () => {
9
- const onPayment = vi.fn();
10
- // latest = 0xa (10), fromBlock = 10 → scans exactly block 10
11
- const rpc = makeRpc({
12
- eth_blockNumber: "0xa",
13
- eth_getBlockByNumber: {
14
- transactions: [
15
- {
16
- hash: "0xabc",
17
- from: "0xsender",
18
- to: "0xdeposit",
19
- value: "0xDE0B6B3A7640000", // 1 ETH = 10^18 wei
20
- blockNumber: "0xa",
21
- },
22
- ],
23
- },
24
- });
25
- const watcher = new EthWatcher({
26
- chain: "base",
27
- rpcCall: rpc,
28
- oracle: mockOracle,
29
- fromBlock: 10,
30
- confirmations: 1,
31
- onPayment,
32
- watchedAddresses: ["0xDeposit"],
33
- });
34
- await watcher.poll();
35
- expect(onPayment).toHaveBeenCalledOnce();
36
- const event = onPayment.mock.calls[0][0];
37
- expect(event.to).toBe("0xdeposit");
38
- expect(event.valueWei).toBe("1000000000000000000");
39
- expect(event.amountUsdCents).toBe(350_000); // 1 ETH × $3,500 = $3,500 = 350,000 cents
40
- expect(event.txHash).toBe("0xabc");
41
- expect(event.confirmations).toBe(0);
42
- expect(event.confirmationsRequired).toBe(1);
43
- });
44
- it("skips transactions not to watched addresses", async () => {
45
- const onPayment = vi.fn();
46
- const rpc = makeRpc({
47
- eth_blockNumber: "0xb",
48
- eth_getBlockByNumber: {
49
- transactions: [{ hash: "0xabc", from: "0xa", to: "0xother", value: "0xDE0B6B3A7640000", blockNumber: "0xa" }],
50
- },
51
- });
52
- const watcher = new EthWatcher({
53
- chain: "base",
54
- rpcCall: rpc,
55
- oracle: mockOracle,
56
- fromBlock: 10,
57
- confirmations: 1,
58
- onPayment,
59
- watchedAddresses: ["0xDeposit"],
60
- });
61
- await watcher.poll();
62
- expect(onPayment).not.toHaveBeenCalled();
63
- });
64
- it("skips zero-value transactions", async () => {
65
- const onPayment = vi.fn();
66
- const rpc = makeRpc({
67
- eth_blockNumber: "0xb",
68
- eth_getBlockByNumber: {
69
- transactions: [{ hash: "0xabc", from: "0xa", to: "0xdeposit", value: "0x0", blockNumber: "0xa" }],
70
- },
71
- });
72
- const watcher = new EthWatcher({
73
- chain: "base",
74
- rpcCall: rpc,
75
- oracle: mockOracle,
76
- fromBlock: 10,
77
- confirmations: 1,
78
- onPayment,
79
- watchedAddresses: ["0xDeposit"],
80
- });
81
- await watcher.poll();
82
- expect(onPayment).not.toHaveBeenCalled();
83
- });
84
- it("does not double-process same txid", async () => {
85
- const onPayment = vi.fn();
86
- const confirmations = new Map();
87
- const cursorStore = {
88
- get: vi.fn().mockResolvedValue(null),
89
- save: vi.fn().mockResolvedValue(undefined),
90
- hasProcessedTx: vi.fn().mockResolvedValue(false),
91
- markProcessedTx: vi.fn().mockResolvedValue(undefined),
92
- getConfirmationCount: vi
93
- .fn()
94
- .mockImplementation(async (_, txId) => confirmations.get(txId) ?? null),
95
- saveConfirmationCount: vi.fn().mockImplementation(async (_, txId, count) => {
96
- confirmations.set(txId, count);
97
- }),
98
- };
99
- const rpc = makeRpc({
100
- eth_blockNumber: "0xb",
101
- eth_getBlockByNumber: {
102
- transactions: [{ hash: "0xabc", from: "0xa", to: "0xdeposit", value: "0xDE0B6B3A7640000", blockNumber: "0xa" }],
103
- },
104
- });
105
- const watcher = new EthWatcher({
106
- chain: "base",
107
- rpcCall: rpc,
108
- oracle: mockOracle,
109
- fromBlock: 10,
110
- confirmations: 1,
111
- onPayment,
112
- watchedAddresses: ["0xDeposit"],
113
- cursorStore,
114
- });
115
- await watcher.poll();
116
- // Second poll — same block, same confirmations → no duplicate emission
117
- await watcher.poll();
118
- expect(onPayment).toHaveBeenCalledOnce();
119
- });
120
- it("skips poll when no watched addresses", async () => {
121
- const onPayment = vi.fn();
122
- const rpc = vi.fn();
123
- const watcher = new EthWatcher({
124
- chain: "base",
125
- rpcCall: rpc,
126
- oracle: mockOracle,
127
- fromBlock: 10,
128
- confirmations: 1,
129
- onPayment,
130
- watchedAddresses: [],
131
- });
132
- await watcher.poll();
133
- expect(rpc).not.toHaveBeenCalled();
134
- });
135
- it("does not mark txid as processed if onPayment throws", async () => {
136
- const onPayment = vi.fn().mockRejectedValueOnce(new Error("db fail")).mockResolvedValueOnce(undefined);
137
- const cursorStore = {
138
- get: vi.fn().mockResolvedValue(null),
139
- save: vi.fn().mockResolvedValue(undefined),
140
- hasProcessedTx: vi.fn().mockResolvedValue(false),
141
- markProcessedTx: vi.fn().mockResolvedValue(undefined),
142
- getConfirmationCount: vi.fn().mockResolvedValue(null),
143
- saveConfirmationCount: vi.fn().mockResolvedValue(undefined),
144
- };
145
- // latest = 0xa (10) = fromBlock → exactly one block to scan
146
- const rpc = makeRpc({
147
- eth_blockNumber: "0xa",
148
- eth_getBlockByNumber: {
149
- transactions: [{ hash: "0xabc", from: "0xa", to: "0xdeposit", value: "0xDE0B6B3A7640000", blockNumber: "0xa" }],
150
- },
151
- });
152
- const watcher = new EthWatcher({
153
- chain: "base",
154
- rpcCall: rpc,
155
- oracle: mockOracle,
156
- fromBlock: 10,
157
- confirmations: 1,
158
- onPayment,
159
- watchedAddresses: ["0xDeposit"],
160
- cursorStore,
161
- });
162
- await expect(watcher.poll()).rejects.toThrow("db fail");
163
- // Retry — should process the same tx again since confirmationCount wasn't saved (error before save)
164
- await watcher.poll();
165
- expect(onPayment).toHaveBeenCalledTimes(2);
166
- });
167
- });
@@ -1,159 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
- import { EvmWatcher } from "../watcher.js";
3
- const TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
4
- function mockTransferLog(to, amount, blockNumber) {
5
- return {
6
- address: "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
7
- topics: [
8
- TRANSFER_TOPIC,
9
- `0x${"00".repeat(12)}${"ab".repeat(20)}`,
10
- `0x${"00".repeat(12)}${to.slice(2).toLowerCase()}`,
11
- ],
12
- data: `0x${amount.toString(16).padStart(64, "0")}`,
13
- blockNumber: `0x${blockNumber.toString(16)}`,
14
- transactionHash: `0x${"ff".repeat(32)}`,
15
- logIndex: "0x0",
16
- };
17
- }
18
- function makeCursorStore() {
19
- const cursors = new Map();
20
- return {
21
- get: vi.fn().mockImplementation(async (id) => cursors.get(id) ?? null),
22
- save: vi.fn().mockImplementation(async (id, val) => {
23
- cursors.set(id, val);
24
- }),
25
- hasProcessedTx: vi.fn().mockResolvedValue(false),
26
- markProcessedTx: vi.fn().mockResolvedValue(undefined),
27
- getConfirmationCount: vi.fn().mockResolvedValue(null),
28
- saveConfirmationCount: vi.fn().mockResolvedValue(undefined),
29
- };
30
- }
31
- describe("EvmWatcher — intermediate confirmations", () => {
32
- it("emits events with confirmation count", async () => {
33
- const toAddr = `0x${"cc".repeat(20)}`;
34
- const events = [];
35
- // Base has confirmations: 1. Latest block is 105. Log at block 103 -> 2 confirmations.
36
- const mockRpc = vi
37
- .fn()
38
- .mockResolvedValueOnce(`0x${(105).toString(16)}`) // eth_blockNumber
39
- .mockResolvedValueOnce([mockTransferLog(toAddr, 10000000n, 103)]); // eth_getLogs
40
- const watcher = new EvmWatcher({
41
- chain: "base",
42
- token: "USDC",
43
- contractAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
44
- decimals: 6,
45
- confirmations: 1,
46
- rpcCall: mockRpc,
47
- fromBlock: 100,
48
- watchedAddresses: [toAddr],
49
- cursorStore: makeCursorStore(),
50
- onPayment: (evt) => {
51
- events.push(evt);
52
- },
53
- });
54
- await watcher.poll();
55
- expect(events).toHaveLength(1);
56
- expect(events[0].confirmations).toBe(2); // 105 - 103
57
- expect(events[0].confirmationsRequired).toBe(1); // Base chain config
58
- });
59
- it("skips event when confirmation count unchanged", async () => {
60
- const toAddr = `0x${"cc".repeat(20)}`;
61
- const events = [];
62
- const cursorStore = makeCursorStore();
63
- cursorStore.getConfirmationCount.mockResolvedValue(2);
64
- const mockRpc = vi
65
- .fn()
66
- .mockResolvedValueOnce(`0x${(105).toString(16)}`)
67
- .mockResolvedValueOnce([mockTransferLog(toAddr, 10000000n, 103)]);
68
- const watcher = new EvmWatcher({
69
- chain: "base",
70
- token: "USDC",
71
- contractAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
72
- decimals: 6,
73
- confirmations: 1,
74
- rpcCall: mockRpc,
75
- fromBlock: 100,
76
- watchedAddresses: [toAddr],
77
- cursorStore,
78
- onPayment: (evt) => {
79
- events.push(evt);
80
- },
81
- });
82
- await watcher.poll();
83
- expect(events).toHaveLength(0);
84
- });
85
- it("re-emits when confirmations increase", async () => {
86
- const toAddr = `0x${"cc".repeat(20)}`;
87
- const events = [];
88
- const cursorStore = makeCursorStore();
89
- cursorStore.getConfirmationCount.mockResolvedValue(1);
90
- const mockRpc = vi
91
- .fn()
92
- .mockResolvedValueOnce(`0x${(105).toString(16)}`)
93
- .mockResolvedValueOnce([mockTransferLog(toAddr, 10000000n, 103)]);
94
- const watcher = new EvmWatcher({
95
- chain: "base",
96
- token: "USDC",
97
- contractAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
98
- decimals: 6,
99
- confirmations: 1,
100
- rpcCall: mockRpc,
101
- fromBlock: 100,
102
- watchedAddresses: [toAddr],
103
- cursorStore,
104
- onPayment: (evt) => {
105
- events.push(evt);
106
- },
107
- });
108
- await watcher.poll();
109
- expect(events).toHaveLength(1);
110
- expect(events[0].confirmations).toBe(2);
111
- });
112
- it("includes confirmationsRequired from chain config", async () => {
113
- const toAddr = `0x${"cc".repeat(20)}`;
114
- const events = [];
115
- const mockRpc = vi
116
- .fn()
117
- .mockResolvedValueOnce(`0x${(110).toString(16)}`)
118
- .mockResolvedValueOnce([mockTransferLog(toAddr, 10000000n, 105)]);
119
- const watcher = new EvmWatcher({
120
- chain: "base",
121
- token: "USDC",
122
- contractAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
123
- decimals: 6,
124
- confirmations: 1,
125
- rpcCall: mockRpc,
126
- fromBlock: 100,
127
- watchedAddresses: [toAddr],
128
- cursorStore: makeCursorStore(),
129
- onPayment: (evt) => {
130
- events.push(evt);
131
- },
132
- });
133
- await watcher.poll();
134
- expect(events).toHaveLength(1);
135
- expect(events[0].confirmationsRequired).toBe(1); // Base chain config
136
- });
137
- it("saves confirmation count after emitting", async () => {
138
- const toAddr = `0x${"cc".repeat(20)}`;
139
- const cursorStore = makeCursorStore();
140
- const mockRpc = vi
141
- .fn()
142
- .mockResolvedValueOnce(`0x${(105).toString(16)}`)
143
- .mockResolvedValueOnce([mockTransferLog(toAddr, 10000000n, 103)]);
144
- const watcher = new EvmWatcher({
145
- chain: "base",
146
- token: "USDC",
147
- contractAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
148
- decimals: 6,
149
- confirmations: 1,
150
- rpcCall: mockRpc,
151
- fromBlock: 100,
152
- watchedAddresses: [toAddr],
153
- cursorStore,
154
- onPayment: () => { },
155
- });
156
- await watcher.poll();
157
- expect(cursorStore.saveConfirmationCount).toHaveBeenCalledWith(expect.any(String), expect.stringContaining("0x"), 2);
158
- });
159
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,145 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
- import { EvmWatcher } from "../watcher.js";
3
- const TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
4
- function mockTransferLog(to, amount, blockNumber) {
5
- return {
6
- address: "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
7
- topics: [
8
- TRANSFER_TOPIC,
9
- `0x${"00".repeat(12)}${"ab".repeat(20)}`, // from (padded)
10
- `0x${"00".repeat(12)}${to.slice(2).toLowerCase()}`, // to (padded)
11
- ],
12
- data: `0x${amount.toString(16).padStart(64, "0")}`,
13
- blockNumber: `0x${blockNumber.toString(16)}`,
14
- transactionHash: `0x${"ff".repeat(32)}`,
15
- logIndex: "0x0",
16
- };
17
- }
18
- describe("EvmWatcher", () => {
19
- it("parses Transfer log into EvmPaymentEvent", async () => {
20
- const toAddr = `0x${"cc".repeat(20)}`;
21
- const events = [];
22
- const mockRpc = vi
23
- .fn()
24
- .mockResolvedValueOnce(`0x${(102).toString(16)}`)
25
- .mockResolvedValueOnce([mockTransferLog(toAddr, 10000000n, 99)]);
26
- const watcher = new EvmWatcher({
27
- chain: "base",
28
- token: "USDC",
29
- contractAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
30
- decimals: 6,
31
- confirmations: 1,
32
- rpcCall: mockRpc,
33
- fromBlock: 99,
34
- watchedAddresses: [toAddr],
35
- onPayment: (evt) => {
36
- events.push(evt);
37
- },
38
- });
39
- await watcher.poll();
40
- expect(events).toHaveLength(1);
41
- expect(events[0].amountUsdCents).toBe(1000);
42
- expect(events[0].to).toMatch(/^0x/);
43
- });
44
- it("advances cursor after processing", async () => {
45
- const mockRpc = vi
46
- .fn()
47
- .mockResolvedValueOnce(`0x${(200).toString(16)}`)
48
- .mockResolvedValueOnce([]);
49
- const watcher = new EvmWatcher({
50
- chain: "base",
51
- token: "USDC",
52
- contractAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
53
- decimals: 6,
54
- confirmations: 1,
55
- rpcCall: mockRpc,
56
- fromBlock: 100,
57
- watchedAddresses: ["0xdeadbeef"],
58
- onPayment: vi.fn(),
59
- });
60
- await watcher.poll();
61
- expect(watcher.cursor).toBeGreaterThan(100);
62
- });
63
- it("skips blocks not yet confirmed", async () => {
64
- const events = [];
65
- // latest = 50, cursor = 50 → latest < cursor is false, but range is empty (50..50)
66
- // With intermediate confirmations, we still scan the range but find no logs
67
- const mockRpc = vi
68
- .fn()
69
- .mockResolvedValueOnce(`0x${(50).toString(16)}`) // eth_blockNumber
70
- .mockResolvedValueOnce([]); // eth_getLogs (empty)
71
- const watcher = new EvmWatcher({
72
- chain: "base",
73
- token: "USDC",
74
- contractAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
75
- decimals: 6,
76
- confirmations: 1,
77
- rpcCall: mockRpc,
78
- fromBlock: 50,
79
- watchedAddresses: ["0xdeadbeef"],
80
- onPayment: (evt) => {
81
- events.push(evt);
82
- },
83
- });
84
- await watcher.poll();
85
- expect(events).toHaveLength(0);
86
- });
87
- it("processes multiple logs in one poll", async () => {
88
- const addr1 = `0x${"aa".repeat(20)}`;
89
- const addr2 = `0x${"bb".repeat(20)}`;
90
- const events = [];
91
- const mockRpc = vi
92
- .fn()
93
- .mockResolvedValueOnce(`0x${(110).toString(16)}`)
94
- .mockResolvedValueOnce([mockTransferLog(addr1, 5000000n, 105), mockTransferLog(addr2, 20000000n, 107)]);
95
- const watcher = new EvmWatcher({
96
- chain: "base",
97
- token: "USDC",
98
- contractAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
99
- decimals: 6,
100
- confirmations: 1,
101
- rpcCall: mockRpc,
102
- fromBlock: 100,
103
- watchedAddresses: [addr1, addr2],
104
- onPayment: (evt) => {
105
- events.push(evt);
106
- },
107
- });
108
- await watcher.poll();
109
- expect(events).toHaveLength(2);
110
- expect(events[0].amountUsdCents).toBe(500);
111
- expect(events[1].amountUsdCents).toBe(2000);
112
- });
113
- it("does nothing when no new blocks", async () => {
114
- const mockRpc = vi.fn().mockResolvedValueOnce(`0x${(99).toString(16)}`);
115
- const watcher = new EvmWatcher({
116
- chain: "base",
117
- token: "USDC",
118
- contractAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
119
- decimals: 6,
120
- confirmations: 1,
121
- rpcCall: mockRpc,
122
- fromBlock: 100,
123
- watchedAddresses: ["0xdeadbeef"],
124
- onPayment: vi.fn(),
125
- });
126
- await watcher.poll();
127
- expect(watcher.cursor).toBe(100);
128
- expect(mockRpc).toHaveBeenCalledTimes(1);
129
- });
130
- it("early-returns when no watched addresses are set", async () => {
131
- const mockRpc = vi.fn();
132
- const watcher = new EvmWatcher({
133
- chain: "base",
134
- token: "USDC",
135
- contractAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
136
- decimals: 6,
137
- confirmations: 1,
138
- rpcCall: mockRpc,
139
- fromBlock: 0,
140
- onPayment: vi.fn(),
141
- });
142
- await watcher.poll();
143
- expect(mockRpc).not.toHaveBeenCalled(); // no RPC calls at all
144
- });
145
- });
@@ -1,66 +0,0 @@
1
- import type { IWatcherCursorStore } from "../cursor-store.js";
2
- import type { IPriceOracle } from "../oracle/types.js";
3
- import type { EvmChain } from "./types.js";
4
- type RpcCall = (method: string, params: unknown[]) => Promise<unknown>;
5
- /** Event emitted on each confirmation increment for a native ETH deposit. */
6
- export interface EthPaymentEvent {
7
- readonly chain: EvmChain;
8
- readonly from: string;
9
- readonly to: string;
10
- /** Raw value in wei (BigInt as string for serialization). */
11
- readonly valueWei: string;
12
- /** USD cents equivalent at detection time (integer). */
13
- readonly amountUsdCents: number;
14
- readonly txHash: string;
15
- readonly blockNumber: number;
16
- /** Current confirmation count (latest block - tx block). */
17
- readonly confirmations: number;
18
- /** Required confirmations for this chain. */
19
- readonly confirmationsRequired: number;
20
- }
21
- export interface EthWatcherOpts {
22
- chain: EvmChain;
23
- rpcCall: RpcCall;
24
- oracle: IPriceOracle;
25
- fromBlock: number;
26
- onPayment: (event: EthPaymentEvent) => void | Promise<void>;
27
- watchedAddresses?: string[];
28
- cursorStore?: IWatcherCursorStore;
29
- /** Required confirmations (from DB). */
30
- confirmations: number;
31
- }
32
- /**
33
- * Native ETH transfer watcher.
34
- *
35
- * Unlike the ERC-20 EvmWatcher which uses eth_getLogs for Transfer events,
36
- * this scans blocks for transactions where `to` matches a watched deposit
37
- * address and `value > 0`.
38
- *
39
- * Scans up to latest block (not just confirmed) to detect pending txs.
40
- * Emits events on each confirmation increment. Only advances cursor
41
- * past fully-confirmed blocks.
42
- */
43
- export declare class EthWatcher {
44
- private _cursor;
45
- private readonly chain;
46
- private readonly rpc;
47
- private readonly oracle;
48
- private readonly onPayment;
49
- private readonly confirmations;
50
- private readonly cursorStore?;
51
- private readonly watcherId;
52
- private _watchedAddresses;
53
- constructor(opts: EthWatcherOpts);
54
- /** Load cursor from DB. Call once at startup before first poll. */
55
- init(): Promise<void>;
56
- setWatchedAddresses(addresses: string[]): void;
57
- get cursor(): number;
58
- /**
59
- * Poll for native ETH transfers to watched addresses, including unconfirmed blocks.
60
- *
61
- * Scans from cursor to latest block. Emits events with current confirmation count.
62
- * Re-emits on each confirmation increment. Only advances cursor past fully-confirmed blocks.
63
- */
64
- poll(): Promise<void>;
65
- }
66
- export {};