@wopr-network/platform-core 1.19.0 → 1.21.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 (74) hide show
  1. package/dist/billing/crypto/btc/__tests__/address-gen.test.d.ts +1 -0
  2. package/dist/billing/crypto/btc/__tests__/address-gen.test.js +44 -0
  3. package/dist/billing/crypto/btc/__tests__/config.test.d.ts +1 -0
  4. package/dist/billing/crypto/btc/__tests__/config.test.js +24 -0
  5. package/dist/billing/crypto/btc/__tests__/settler.test.d.ts +1 -0
  6. package/dist/billing/crypto/btc/__tests__/settler.test.js +92 -0
  7. package/dist/billing/crypto/btc/address-gen.d.ts +8 -0
  8. package/dist/billing/crypto/btc/address-gen.js +34 -0
  9. package/dist/billing/crypto/btc/checkout.d.ts +21 -0
  10. package/dist/billing/crypto/btc/checkout.js +42 -0
  11. package/dist/billing/crypto/btc/config.d.ts +12 -0
  12. package/dist/billing/crypto/btc/config.js +28 -0
  13. package/dist/billing/crypto/btc/index.d.ts +9 -0
  14. package/dist/billing/crypto/btc/index.js +5 -0
  15. package/dist/billing/crypto/btc/settler.d.ts +23 -0
  16. package/dist/billing/crypto/btc/settler.js +55 -0
  17. package/dist/billing/crypto/btc/types.d.ts +23 -0
  18. package/dist/billing/crypto/btc/types.js +1 -0
  19. package/dist/billing/crypto/btc/watcher.d.ts +28 -0
  20. package/dist/billing/crypto/btc/watcher.js +83 -0
  21. package/dist/billing/crypto/charge-store.d.ts +3 -3
  22. package/dist/billing/crypto/evm/__tests__/config.test.js +42 -2
  23. package/dist/billing/crypto/evm/__tests__/watcher.test.js +31 -17
  24. package/dist/billing/crypto/evm/checkout.js +4 -2
  25. package/dist/billing/crypto/evm/config.js +73 -0
  26. package/dist/billing/crypto/evm/types.d.ts +1 -1
  27. package/dist/billing/crypto/evm/watcher.js +2 -0
  28. package/dist/billing/crypto/index.d.ts +3 -1
  29. package/dist/billing/crypto/index.js +2 -0
  30. package/dist/billing/crypto/oracle/__tests__/chainlink.test.d.ts +1 -0
  31. package/dist/billing/crypto/oracle/__tests__/chainlink.test.js +83 -0
  32. package/dist/billing/crypto/oracle/__tests__/convert.test.d.ts +1 -0
  33. package/dist/billing/crypto/oracle/__tests__/convert.test.js +51 -0
  34. package/dist/billing/crypto/oracle/__tests__/fixed.test.d.ts +1 -0
  35. package/dist/billing/crypto/oracle/__tests__/fixed.test.js +20 -0
  36. package/dist/billing/crypto/oracle/chainlink.d.ts +26 -0
  37. package/dist/billing/crypto/oracle/chainlink.js +61 -0
  38. package/dist/billing/crypto/oracle/convert.d.ts +20 -0
  39. package/dist/billing/crypto/oracle/convert.js +38 -0
  40. package/dist/billing/crypto/oracle/fixed.d.ts +10 -0
  41. package/dist/billing/crypto/oracle/fixed.js +20 -0
  42. package/dist/billing/crypto/oracle/index.d.ts +5 -0
  43. package/dist/billing/crypto/oracle/index.js +3 -0
  44. package/dist/billing/crypto/oracle/types.d.ts +13 -0
  45. package/dist/billing/crypto/oracle/types.js +1 -0
  46. package/dist/db/schema/crypto.js +1 -1
  47. package/package.json +3 -1
  48. package/src/billing/crypto/btc/__tests__/address-gen.test.ts +53 -0
  49. package/src/billing/crypto/btc/__tests__/config.test.ts +28 -0
  50. package/src/billing/crypto/btc/__tests__/settler.test.ts +103 -0
  51. package/src/billing/crypto/btc/address-gen.ts +41 -0
  52. package/src/billing/crypto/btc/checkout.ts +61 -0
  53. package/src/billing/crypto/btc/config.ts +33 -0
  54. package/src/billing/crypto/btc/index.ts +9 -0
  55. package/src/billing/crypto/btc/settler.ts +74 -0
  56. package/src/billing/crypto/btc/types.ts +25 -0
  57. package/src/billing/crypto/btc/watcher.ts +115 -0
  58. package/src/billing/crypto/charge-store.ts +3 -3
  59. package/src/billing/crypto/evm/__tests__/config.test.ts +51 -2
  60. package/src/billing/crypto/evm/__tests__/watcher.test.ts +34 -17
  61. package/src/billing/crypto/evm/checkout.ts +4 -2
  62. package/src/billing/crypto/evm/config.ts +73 -0
  63. package/src/billing/crypto/evm/types.ts +1 -1
  64. package/src/billing/crypto/evm/watcher.ts +2 -0
  65. package/src/billing/crypto/index.ts +3 -1
  66. package/src/billing/crypto/oracle/__tests__/chainlink.test.ts +107 -0
  67. package/src/billing/crypto/oracle/__tests__/convert.test.ts +62 -0
  68. package/src/billing/crypto/oracle/__tests__/fixed.test.ts +23 -0
  69. package/src/billing/crypto/oracle/chainlink.ts +85 -0
  70. package/src/billing/crypto/oracle/convert.ts +38 -0
  71. package/src/billing/crypto/oracle/fixed.ts +23 -0
  72. package/src/billing/crypto/oracle/index.ts +5 -0
  73. package/src/billing/crypto/oracle/types.ts +15 -0
  74. package/src/db/schema/crypto.ts +1 -1
@@ -17,35 +17,38 @@ function mockTransferLog(to, amount, blockNumber) {
17
17
  }
18
18
  describe("EvmWatcher", () => {
19
19
  it("parses Transfer log into EvmPaymentEvent", async () => {
20
+ const toAddr = `0x${"cc".repeat(20)}`;
20
21
  const events = [];
21
22
  const mockRpc = vi
22
23
  .fn()
23
- .mockResolvedValueOnce(`0x${(102).toString(16)}`) // eth_blockNumber: block 102
24
- .mockResolvedValueOnce([mockTransferLog(`0x${"cc".repeat(20)}`, 10000000n, 99)]); // eth_getLogs
24
+ .mockResolvedValueOnce(`0x${(102).toString(16)}`)
25
+ .mockResolvedValueOnce([mockTransferLog(toAddr, 10000000n, 99)]);
25
26
  const watcher = new EvmWatcher({
26
27
  chain: "base",
27
28
  token: "USDC",
28
29
  rpcCall: mockRpc,
29
30
  fromBlock: 99,
31
+ watchedAddresses: [toAddr],
30
32
  onPayment: (evt) => {
31
33
  events.push(evt);
32
34
  },
33
35
  });
34
36
  await watcher.poll();
35
37
  expect(events).toHaveLength(1);
36
- expect(events[0].amountUsdCents).toBe(1000); // 10 USDC = $10 = 1000 cents
38
+ expect(events[0].amountUsdCents).toBe(1000);
37
39
  expect(events[0].to).toMatch(/^0x/);
38
40
  });
39
41
  it("advances cursor after processing", async () => {
40
42
  const mockRpc = vi
41
43
  .fn()
42
- .mockResolvedValueOnce(`0x${(200).toString(16)}`) // block 200
43
- .mockResolvedValueOnce([]); // no logs
44
+ .mockResolvedValueOnce(`0x${(200).toString(16)}`)
45
+ .mockResolvedValueOnce([]);
44
46
  const watcher = new EvmWatcher({
45
47
  chain: "base",
46
48
  token: "USDC",
47
49
  rpcCall: mockRpc,
48
50
  fromBlock: 100,
51
+ watchedAddresses: ["0xdeadbeef"],
49
52
  onPayment: vi.fn(),
50
53
  });
51
54
  await watcher.poll();
@@ -53,37 +56,35 @@ describe("EvmWatcher", () => {
53
56
  });
54
57
  it("skips blocks not yet confirmed", async () => {
55
58
  const events = [];
56
- const mockRpc = vi.fn().mockResolvedValueOnce(`0x${(50).toString(16)}`); // current block: 50
57
- // Base needs 1 confirmation, so confirmed = 50 - 1 = 49
58
- // cursor starts at 50, so confirmed (49) < cursor (50) → no poll
59
+ const mockRpc = vi.fn().mockResolvedValueOnce(`0x${(50).toString(16)}`);
59
60
  const watcher = new EvmWatcher({
60
61
  chain: "base",
61
62
  token: "USDC",
62
63
  rpcCall: mockRpc,
63
64
  fromBlock: 50,
65
+ watchedAddresses: ["0xdeadbeef"],
64
66
  onPayment: (evt) => {
65
67
  events.push(evt);
66
68
  },
67
69
  });
68
70
  await watcher.poll();
69
71
  expect(events).toHaveLength(0);
70
- // eth_getLogs should not even be called
71
72
  expect(mockRpc).toHaveBeenCalledTimes(1);
72
73
  });
73
74
  it("processes multiple logs in one poll", async () => {
75
+ const addr1 = `0x${"aa".repeat(20)}`;
76
+ const addr2 = `0x${"bb".repeat(20)}`;
74
77
  const events = [];
75
78
  const mockRpc = vi
76
79
  .fn()
77
- .mockResolvedValueOnce(`0x${(110).toString(16)}`) // block 110
78
- .mockResolvedValueOnce([
79
- mockTransferLog(`0x${"aa".repeat(20)}`, 5000000n, 105), // $5
80
- mockTransferLog(`0x${"bb".repeat(20)}`, 20000000n, 107), // $20
81
- ]);
80
+ .mockResolvedValueOnce(`0x${(110).toString(16)}`)
81
+ .mockResolvedValueOnce([mockTransferLog(addr1, 5000000n, 105), mockTransferLog(addr2, 20000000n, 107)]);
82
82
  const watcher = new EvmWatcher({
83
83
  chain: "base",
84
84
  token: "USDC",
85
85
  rpcCall: mockRpc,
86
86
  fromBlock: 100,
87
+ watchedAddresses: [addr1, addr2],
87
88
  onPayment: (evt) => {
88
89
  events.push(evt);
89
90
  },
@@ -94,16 +95,29 @@ describe("EvmWatcher", () => {
94
95
  expect(events[1].amountUsdCents).toBe(2000);
95
96
  });
96
97
  it("does nothing when no new blocks", async () => {
97
- const mockRpc = vi.fn().mockResolvedValueOnce(`0x${(99).toString(16)}`); // block 99, confirmed = 98
98
+ const mockRpc = vi.fn().mockResolvedValueOnce(`0x${(99).toString(16)}`);
98
99
  const watcher = new EvmWatcher({
99
100
  chain: "base",
100
101
  token: "USDC",
101
102
  rpcCall: mockRpc,
102
103
  fromBlock: 100,
104
+ watchedAddresses: ["0xdeadbeef"],
103
105
  onPayment: vi.fn(),
104
106
  });
105
107
  await watcher.poll();
106
- expect(watcher.cursor).toBe(100); // unchanged
107
- expect(mockRpc).toHaveBeenCalledTimes(1); // only eth_blockNumber
108
+ expect(watcher.cursor).toBe(100);
109
+ expect(mockRpc).toHaveBeenCalledTimes(1);
110
+ });
111
+ it("early-returns when no watched addresses are set", async () => {
112
+ const mockRpc = vi.fn();
113
+ const watcher = new EvmWatcher({
114
+ chain: "base",
115
+ token: "USDC",
116
+ rpcCall: mockRpc,
117
+ fromBlock: 0,
118
+ onPayment: vi.fn(),
119
+ });
120
+ await watcher.poll();
121
+ expect(mockRpc).not.toHaveBeenCalled(); // no RPC calls at all
108
122
  });
109
123
  });
@@ -47,8 +47,10 @@ export async function createStablecoinCheckout(deps, opts) {
47
47
  catch (err) {
48
48
  // Unique constraint violation = another checkout claimed this index concurrently.
49
49
  // Retry with the next available index.
50
- const msg = err instanceof Error ? err.message : "";
51
- const isConflict = msg.includes("unique") || msg.includes("duplicate") || msg.includes("23505");
50
+ // PostgreSQL error code 23505 = unique_violation.
51
+ // Check structured code first, fall back to message for other drivers.
52
+ const code = err.code;
53
+ const isConflict = code === "23505" || (err instanceof Error && err.message.includes("unique_violation"));
52
54
  if (!isConflict || attempt === maxRetries)
53
55
  throw err;
54
56
  }
@@ -6,8 +6,30 @@ const CHAINS = {
6
6
  blockTimeMs: 2000,
7
7
  chainId: 8453,
8
8
  },
9
+ ethereum: {
10
+ chain: "ethereum",
11
+ rpcUrl: process.env.EVM_RPC_ETHEREUM ?? "http://geth:8545",
12
+ confirmations: 12,
13
+ blockTimeMs: 12000,
14
+ chainId: 1,
15
+ },
16
+ arbitrum: {
17
+ chain: "arbitrum",
18
+ rpcUrl: process.env.EVM_RPC_ARBITRUM ?? "http://nitro:8547",
19
+ confirmations: 1,
20
+ blockTimeMs: 250,
21
+ chainId: 42161,
22
+ },
23
+ polygon: {
24
+ chain: "polygon",
25
+ rpcUrl: process.env.EVM_RPC_POLYGON ?? "http://bor:8545",
26
+ confirmations: 32,
27
+ blockTimeMs: 2000,
28
+ chainId: 137,
29
+ },
9
30
  };
10
31
  const TOKENS = {
32
+ // --- Base ---
11
33
  "USDC:base": {
12
34
  token: "USDC",
13
35
  chain: "base",
@@ -26,6 +48,57 @@ const TOKENS = {
26
48
  contractAddress: "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb",
27
49
  decimals: 18,
28
50
  },
51
+ // --- Ethereum ---
52
+ "USDC:ethereum": {
53
+ token: "USDC",
54
+ chain: "ethereum",
55
+ contractAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
56
+ decimals: 6,
57
+ },
58
+ "USDT:ethereum": {
59
+ token: "USDT",
60
+ chain: "ethereum",
61
+ contractAddress: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
62
+ decimals: 6,
63
+ },
64
+ "DAI:ethereum": {
65
+ token: "DAI",
66
+ chain: "ethereum",
67
+ contractAddress: "0x6B175474E89094C44Da98b954EedeAC495271d0F",
68
+ decimals: 18,
69
+ },
70
+ // --- Arbitrum ---
71
+ "USDC:arbitrum": {
72
+ token: "USDC",
73
+ chain: "arbitrum",
74
+ contractAddress: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
75
+ decimals: 6,
76
+ },
77
+ "USDT:arbitrum": {
78
+ token: "USDT",
79
+ chain: "arbitrum",
80
+ contractAddress: "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",
81
+ decimals: 6,
82
+ },
83
+ "DAI:arbitrum": {
84
+ token: "DAI",
85
+ chain: "arbitrum",
86
+ contractAddress: "0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1",
87
+ decimals: 18,
88
+ },
89
+ // --- Polygon ---
90
+ "USDC:polygon": {
91
+ token: "USDC",
92
+ chain: "polygon",
93
+ contractAddress: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",
94
+ decimals: 6,
95
+ },
96
+ "USDT:polygon": {
97
+ token: "USDT",
98
+ chain: "polygon",
99
+ contractAddress: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F",
100
+ decimals: 6,
101
+ },
29
102
  };
30
103
  export function getChainConfig(chain) {
31
104
  const cfg = CHAINS[chain];
@@ -1,5 +1,5 @@
1
1
  /** Supported EVM chains. */
2
- export type EvmChain = "base";
2
+ export type EvmChain = "base" | "ethereum" | "arbitrum" | "polygon";
3
3
  /** Supported stablecoin tokens. */
4
4
  export type StablecoinToken = "USDC" | "USDT" | "DAI";
5
5
  /** Chain configuration. */
@@ -32,6 +32,8 @@ export class EvmWatcher {
32
32
  }
33
33
  /** Poll for new Transfer events. Call on an interval. */
34
34
  async poll() {
35
+ if (this._watchedAddresses.length === 0)
36
+ return; // nothing to watch
35
37
  const latestHex = (await this.rpc("eth_blockNumber", []));
36
38
  const latest = Number.parseInt(latestHex, 16);
37
39
  const confirmed = latest - this.confirmations;
@@ -1,9 +1,11 @@
1
- export type { CryptoChargeRecord, ICryptoChargeRepository, StablecoinChargeInput } from "./charge-store.js";
1
+ export * from "./btc/index.js";
2
+ export type { CryptoChargeRecord, CryptoDepositChargeInput, ICryptoChargeRepository } from "./charge-store.js";
2
3
  export { CryptoChargeRepository, DrizzleCryptoChargeRepository } from "./charge-store.js";
3
4
  export { createCryptoCheckout, MIN_PAYMENT_USD } from "./checkout.js";
4
5
  export type { CryptoConfig } from "./client.js";
5
6
  export { BTCPayClient, loadCryptoConfig } from "./client.js";
6
7
  export * from "./evm/index.js";
8
+ export * from "./oracle/index.js";
7
9
  export type { CryptoBillingConfig, CryptoCheckoutOpts, CryptoPaymentState, CryptoWebhookPayload, CryptoWebhookResult, } from "./types.js";
8
10
  export { mapBtcPayEventToStatus } from "./types.js";
9
11
  export type { CryptoWebhookDeps } from "./webhook.js";
@@ -1,6 +1,8 @@
1
+ export * from "./btc/index.js";
1
2
  export { CryptoChargeRepository, DrizzleCryptoChargeRepository } from "./charge-store.js";
2
3
  export { createCryptoCheckout, MIN_PAYMENT_USD } from "./checkout.js";
3
4
  export { BTCPayClient, loadCryptoConfig } from "./client.js";
4
5
  export * from "./evm/index.js";
6
+ export * from "./oracle/index.js";
5
7
  export { mapBtcPayEventToStatus } from "./types.js";
6
8
  export { handleCryptoWebhook, verifyCryptoWebhookSignature } from "./webhook.js";
@@ -0,0 +1,83 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { ChainlinkOracle } from "../chainlink.js";
3
+ /**
4
+ * Encode a mock latestRoundData() response.
5
+ * Chainlink returns 5 × 32-byte ABI-encoded words:
6
+ * roundId, answer, startedAt, updatedAt, answeredInRound
7
+ */
8
+ function encodeRoundData(answer, updatedAtSec) {
9
+ const pad = (v) => v.toString(16).padStart(64, "0");
10
+ return ("0x" +
11
+ pad(1n) + // roundId
12
+ pad(answer) + // answer (price × 10^8)
13
+ pad(BigInt(updatedAtSec)) + // startedAt
14
+ pad(BigInt(updatedAtSec)) + // updatedAt
15
+ pad(1n) // answeredInRound
16
+ );
17
+ }
18
+ describe("ChainlinkOracle", () => {
19
+ const nowSec = Math.floor(Date.now() / 1000);
20
+ it("decodes ETH/USD price from latestRoundData", async () => {
21
+ // ETH at $3,500.00 → answer = 3500 × 10^8 = 350_000_000_000
22
+ const rpc = vi.fn().mockResolvedValue(encodeRoundData(350000000000n, nowSec));
23
+ const oracle = new ChainlinkOracle({ rpcCall: rpc });
24
+ const result = await oracle.getPrice("ETH");
25
+ expect(result.priceCents).toBe(350_000); // $3,500.00
26
+ expect(result.updatedAt).toBeInstanceOf(Date);
27
+ expect(rpc).toHaveBeenCalledWith("eth_call", [
28
+ { to: "0x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70", data: "0xfeaf968c" },
29
+ "latest",
30
+ ]);
31
+ });
32
+ it("decodes BTC/USD price from latestRoundData", async () => {
33
+ // BTC at $65,000.00 → answer = 65000 × 10^8 = 6_500_000_000_000
34
+ const rpc = vi.fn().mockResolvedValue(encodeRoundData(6500000000000n, nowSec));
35
+ const oracle = new ChainlinkOracle({ rpcCall: rpc });
36
+ const result = await oracle.getPrice("BTC");
37
+ expect(result.priceCents).toBe(6_500_000); // $65,000.00
38
+ });
39
+ it("handles fractional dollar prices correctly", async () => {
40
+ // ETH at $3,456.78 → answer = 345_678_000_000
41
+ const rpc = vi.fn().mockResolvedValue(encodeRoundData(345678000000n, nowSec));
42
+ const oracle = new ChainlinkOracle({ rpcCall: rpc });
43
+ const result = await oracle.getPrice("ETH");
44
+ expect(result.priceCents).toBe(345_678); // $3,456.78
45
+ });
46
+ it("rejects stale prices", async () => {
47
+ const staleTime = nowSec - 7200; // 2 hours ago
48
+ const rpc = vi.fn().mockResolvedValue(encodeRoundData(350000000000n, staleTime));
49
+ const oracle = new ChainlinkOracle({ rpcCall: rpc, maxStalenessMs: 3600_000 });
50
+ await expect(oracle.getPrice("ETH")).rejects.toThrow("stale");
51
+ });
52
+ it("rejects zero price", async () => {
53
+ const rpc = vi.fn().mockResolvedValue(encodeRoundData(0n, nowSec));
54
+ const oracle = new ChainlinkOracle({ rpcCall: rpc });
55
+ await expect(oracle.getPrice("ETH")).rejects.toThrow("Invalid price");
56
+ });
57
+ it("rejects malformed response", async () => {
58
+ const rpc = vi.fn().mockResolvedValue("0xdead");
59
+ const oracle = new ChainlinkOracle({ rpcCall: rpc });
60
+ await expect(oracle.getPrice("ETH")).rejects.toThrow("Malformed");
61
+ });
62
+ it("accepts custom feed addresses", async () => {
63
+ const customFeed = "0x1234567890abcdef1234567890abcdef12345678";
64
+ const rpc = vi.fn().mockResolvedValue(encodeRoundData(350000000000n, nowSec));
65
+ const oracle = new ChainlinkOracle({
66
+ rpcCall: rpc,
67
+ feedAddresses: { ETH: customFeed },
68
+ });
69
+ await oracle.getPrice("ETH");
70
+ expect(rpc).toHaveBeenCalledWith("eth_call", [{ to: customFeed, data: "0xfeaf968c" }, "latest"]);
71
+ });
72
+ it("respects custom staleness threshold", async () => {
73
+ const thirtyMinAgo = nowSec - 1800;
74
+ const rpc = vi.fn().mockResolvedValue(encodeRoundData(350000000000n, thirtyMinAgo));
75
+ // 20-minute threshold → stale
76
+ const strict = new ChainlinkOracle({ rpcCall: rpc, maxStalenessMs: 20 * 60 * 1000 });
77
+ await expect(strict.getPrice("ETH")).rejects.toThrow("stale");
78
+ // 60-minute threshold → fresh
79
+ const relaxed = new ChainlinkOracle({ rpcCall: rpc, maxStalenessMs: 60 * 60 * 1000 });
80
+ const result = await relaxed.getPrice("ETH");
81
+ expect(result.priceCents).toBe(350_000);
82
+ });
83
+ });
@@ -0,0 +1,51 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { centsToNative, nativeToCents } from "../convert.js";
3
+ describe("centsToNative", () => {
4
+ it("converts $50 to ETH wei at $3,500", () => {
5
+ // 5000 cents × 10^18 / 350000 cents = 14285714285714285n wei
6
+ const wei = centsToNative(5000, 350_000, 18);
7
+ expect(wei).toBe(14285714285714285n);
8
+ });
9
+ it("converts $50 to BTC sats at $65,000", () => {
10
+ // 5000 cents × 10^8 / 6500000 cents = 76923n sats
11
+ const sats = centsToNative(5000, 6_500_000, 8);
12
+ expect(sats).toBe(76923n);
13
+ });
14
+ it("converts $100 to ETH wei at $2,000", () => {
15
+ // 10000 cents × 10^18 / 200000 cents = 50000000000000000n wei (0.05 ETH)
16
+ const wei = centsToNative(10_000, 200_000, 18);
17
+ expect(wei).toBe(50000000000000000n);
18
+ });
19
+ it("rejects non-integer amountCents", () => {
20
+ expect(() => centsToNative(50.5, 350_000, 18)).toThrow("positive integer");
21
+ });
22
+ it("rejects zero amountCents", () => {
23
+ expect(() => centsToNative(0, 350_000, 18)).toThrow("positive integer");
24
+ });
25
+ it("rejects zero priceCents", () => {
26
+ expect(() => centsToNative(5000, 0, 18)).toThrow("positive integer");
27
+ });
28
+ it("rejects negative decimals", () => {
29
+ expect(() => centsToNative(5000, 350_000, -1)).toThrow("non-negative integer");
30
+ });
31
+ });
32
+ describe("nativeToCents", () => {
33
+ it("converts ETH wei back to cents at $3,500", () => {
34
+ // 14285714285714285n wei × 350000 / 10^18 = 4999 cents (truncated)
35
+ const cents = nativeToCents(14285714285714285n, 350_000, 18);
36
+ expect(cents).toBe(4999); // truncation from integer division
37
+ });
38
+ it("converts BTC sats back to cents at $65,000", () => {
39
+ // 76923n sats × 6500000 / 10^8 = 4999 cents (truncated)
40
+ const cents = nativeToCents(76923n, 6_500_000, 8);
41
+ expect(cents).toBe(4999);
42
+ });
43
+ it("exact round-trip for clean division", () => {
44
+ // 0.05 ETH at $2,000 = $100
45
+ const cents = nativeToCents(50000000000000000n, 200_000, 18);
46
+ expect(cents).toBe(10_000); // $100.00
47
+ });
48
+ it("rejects negative rawAmount", () => {
49
+ expect(() => nativeToCents(-1n, 350_000, 18)).toThrow("non-negative");
50
+ });
51
+ });
@@ -0,0 +1,20 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { FixedPriceOracle } from "../fixed.js";
3
+ describe("FixedPriceOracle", () => {
4
+ it("returns default ETH price", async () => {
5
+ const oracle = new FixedPriceOracle();
6
+ const result = await oracle.getPrice("ETH");
7
+ expect(result.priceCents).toBe(350_000); // $3,500
8
+ expect(result.updatedAt).toBeInstanceOf(Date);
9
+ });
10
+ it("returns default BTC price", async () => {
11
+ const oracle = new FixedPriceOracle();
12
+ const result = await oracle.getPrice("BTC");
13
+ expect(result.priceCents).toBe(6_500_000); // $65,000
14
+ });
15
+ it("accepts custom prices", async () => {
16
+ const oracle = new FixedPriceOracle({ ETH: 200_000, BTC: 5_000_000 });
17
+ expect((await oracle.getPrice("ETH")).priceCents).toBe(200_000);
18
+ expect((await oracle.getPrice("BTC")).priceCents).toBe(5_000_000);
19
+ });
20
+ });
@@ -0,0 +1,26 @@
1
+ import type { IPriceOracle, PriceAsset, PriceResult } from "./types.js";
2
+ type RpcCall = (method: string, params: unknown[]) => Promise<unknown>;
3
+ export interface ChainlinkOracleOpts {
4
+ rpcCall: RpcCall;
5
+ /** Override feed addresses (e.g. for testnet or Anvil forks). */
6
+ feedAddresses?: Partial<Record<PriceAsset, `0x${string}`>>;
7
+ /** Maximum age of price data before rejecting (ms). Default: 1 hour. */
8
+ maxStalenessMs?: number;
9
+ }
10
+ /**
11
+ * On-chain Chainlink price oracle.
12
+ *
13
+ * Reads latestRoundData() from Chainlink aggregator contracts via eth_call.
14
+ * No API key, no rate limits — just an RPC call to our own node.
15
+ *
16
+ * Chainlink USD feeds use 8 decimals. We convert to integer USD cents:
17
+ * priceCents = answer / 10^6 (i.e. answer / 10^8 * 100)
18
+ */
19
+ export declare class ChainlinkOracle implements IPriceOracle {
20
+ private readonly rpc;
21
+ private readonly feeds;
22
+ private readonly maxStalenessMs;
23
+ constructor(opts: ChainlinkOracleOpts);
24
+ getPrice(asset: PriceAsset): Promise<PriceResult>;
25
+ }
26
+ export {};
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Chainlink price feed addresses on Base mainnet.
3
+ * These are ERC-1967 proxy contracts — addresses are stable.
4
+ */
5
+ const FEED_ADDRESSES = {
6
+ ETH: "0x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70",
7
+ BTC: "0x64c911996D3c6aC71f9b455B1E8E7266BcbD848F",
8
+ };
9
+ /** Function selector for latestRoundData(). */
10
+ const LATEST_ROUND_DATA = "0xfeaf968c";
11
+ /** Default max staleness: 1 hour. */
12
+ const DEFAULT_MAX_STALENESS_MS = 60 * 60 * 1000;
13
+ /**
14
+ * On-chain Chainlink price oracle.
15
+ *
16
+ * Reads latestRoundData() from Chainlink aggregator contracts via eth_call.
17
+ * No API key, no rate limits — just an RPC call to our own node.
18
+ *
19
+ * Chainlink USD feeds use 8 decimals. We convert to integer USD cents:
20
+ * priceCents = answer / 10^6 (i.e. answer / 10^8 * 100)
21
+ */
22
+ export class ChainlinkOracle {
23
+ rpc;
24
+ feeds;
25
+ maxStalenessMs;
26
+ constructor(opts) {
27
+ this.rpc = opts.rpcCall;
28
+ this.feeds = { ...FEED_ADDRESSES, ...opts.feedAddresses };
29
+ this.maxStalenessMs = opts.maxStalenessMs ?? DEFAULT_MAX_STALENESS_MS;
30
+ }
31
+ async getPrice(asset) {
32
+ const feedAddress = this.feeds[asset];
33
+ if (!feedAddress)
34
+ throw new Error(`No price feed for asset: ${asset}`);
35
+ const result = (await this.rpc("eth_call", [{ to: feedAddress, data: LATEST_ROUND_DATA }, "latest"]));
36
+ // ABI decode latestRoundData() return:
37
+ // [0] roundId (uint80) — skip
38
+ // [1] answer (int256) — price × 10^8
39
+ // [2] startedAt (uint256) — skip
40
+ // [3] updatedAt (uint256) — unix seconds
41
+ // [4] answeredInRound (uint80) — skip
42
+ const hex = result.slice(2);
43
+ if (hex.length < 320) {
44
+ throw new Error(`Malformed Chainlink response for ${asset}: expected 320 hex chars, got ${hex.length}`);
45
+ }
46
+ const answer = BigInt(`0x${hex.slice(64, 128)}`);
47
+ const updatedAtSec = Number(BigInt(`0x${hex.slice(192, 256)}`));
48
+ const updatedAt = new Date(updatedAtSec * 1000);
49
+ // Staleness guard.
50
+ const ageMs = Date.now() - updatedAt.getTime();
51
+ if (ageMs > this.maxStalenessMs) {
52
+ throw new Error(`Price feed for ${asset} is stale (${Math.round(ageMs / 1000)}s old, max ${Math.round(this.maxStalenessMs / 1000)}s)`);
53
+ }
54
+ // Chainlink USD feeds: 8 decimals. answer / 10^6 = cents (integer).
55
+ const priceCents = Number(answer / 1000000n);
56
+ if (priceCents <= 0) {
57
+ throw new Error(`Invalid price for ${asset}: ${priceCents} cents`);
58
+ }
59
+ return { priceCents, updatedAt };
60
+ }
61
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Convert USD cents to native token amount using a price in cents.
3
+ *
4
+ * Formula: rawAmount = amountCents × 10^decimals / priceCents
5
+ *
6
+ * Examples:
7
+ * $50 in ETH at $3,500: centsToNative(5000, 350000, 18) = 14285714285714285n (≈0.01429 ETH)
8
+ * $50 in BTC at $65,000: centsToNative(5000, 6500000, 8) = 76923n (76,923 sats ≈ 0.00077 BTC)
9
+ *
10
+ * Integer math only. No floating point.
11
+ */
12
+ export declare function centsToNative(amountCents: number, priceCents: number, decimals: number): bigint;
13
+ /**
14
+ * Convert native token amount back to USD cents using a price in cents.
15
+ *
16
+ * Inverse of centsToNative. Truncates fractional cents.
17
+ *
18
+ * Integer math only.
19
+ */
20
+ export declare function nativeToCents(rawAmount: bigint, priceCents: number, decimals: number): number;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Convert USD cents to native token amount using a price in cents.
3
+ *
4
+ * Formula: rawAmount = amountCents × 10^decimals / priceCents
5
+ *
6
+ * Examples:
7
+ * $50 in ETH at $3,500: centsToNative(5000, 350000, 18) = 14285714285714285n (≈0.01429 ETH)
8
+ * $50 in BTC at $65,000: centsToNative(5000, 6500000, 8) = 76923n (76,923 sats ≈ 0.00077 BTC)
9
+ *
10
+ * Integer math only. No floating point.
11
+ */
12
+ export function centsToNative(amountCents, priceCents, decimals) {
13
+ if (!Number.isInteger(amountCents) || amountCents <= 0) {
14
+ throw new Error(`amountCents must be a positive integer, got ${amountCents}`);
15
+ }
16
+ if (!Number.isInteger(priceCents) || priceCents <= 0) {
17
+ throw new Error(`priceCents must be a positive integer, got ${priceCents}`);
18
+ }
19
+ if (!Number.isInteger(decimals) || decimals < 0) {
20
+ throw new Error(`decimals must be a non-negative integer, got ${decimals}`);
21
+ }
22
+ return (BigInt(amountCents) * 10n ** BigInt(decimals)) / BigInt(priceCents);
23
+ }
24
+ /**
25
+ * Convert native token amount back to USD cents using a price in cents.
26
+ *
27
+ * Inverse of centsToNative. Truncates fractional cents.
28
+ *
29
+ * Integer math only.
30
+ */
31
+ export function nativeToCents(rawAmount, priceCents, decimals) {
32
+ if (rawAmount < 0n)
33
+ throw new Error("rawAmount must be non-negative");
34
+ if (!Number.isInteger(priceCents) || priceCents <= 0) {
35
+ throw new Error(`priceCents must be a positive integer, got ${priceCents}`);
36
+ }
37
+ return Number((rawAmount * BigInt(priceCents)) / 10n ** BigInt(decimals));
38
+ }
@@ -0,0 +1,10 @@
1
+ import type { IPriceOracle, PriceAsset, PriceResult } from "./types.js";
2
+ /**
3
+ * Fixed-price oracle for testing and local dev (Anvil, regtest).
4
+ * Returns hardcoded prices — no RPC calls.
5
+ */
6
+ export declare class FixedPriceOracle implements IPriceOracle {
7
+ private readonly prices;
8
+ constructor(prices?: Partial<Record<PriceAsset, number>>);
9
+ getPrice(asset: PriceAsset): Promise<PriceResult>;
10
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Fixed-price oracle for testing and local dev (Anvil, regtest).
3
+ * Returns hardcoded prices — no RPC calls.
4
+ */
5
+ export class FixedPriceOracle {
6
+ prices;
7
+ constructor(prices = {}) {
8
+ this.prices = {
9
+ ETH: 350_000, // $3,500
10
+ BTC: 6_500_000, // $65,000
11
+ ...prices,
12
+ };
13
+ }
14
+ async getPrice(asset) {
15
+ const priceCents = this.prices[asset];
16
+ if (priceCents === undefined)
17
+ throw new Error(`No fixed price for ${asset}`);
18
+ return { priceCents, updatedAt: new Date() };
19
+ }
20
+ }
@@ -0,0 +1,5 @@
1
+ export type { ChainlinkOracleOpts } from "./chainlink.js";
2
+ export { ChainlinkOracle } from "./chainlink.js";
3
+ export { centsToNative, nativeToCents } from "./convert.js";
4
+ export { FixedPriceOracle } from "./fixed.js";
5
+ export type { IPriceOracle, PriceAsset, PriceResult } from "./types.js";
@@ -0,0 +1,3 @@
1
+ export { ChainlinkOracle } from "./chainlink.js";
2
+ export { centsToNative, nativeToCents } from "./convert.js";
3
+ export { FixedPriceOracle } from "./fixed.js";
@@ -0,0 +1,13 @@
1
+ /** Assets with Chainlink price feeds. */
2
+ export type PriceAsset = "ETH" | "BTC";
3
+ /** Result from a price oracle query. */
4
+ export interface PriceResult {
5
+ /** USD cents per 1 unit of asset (integer). */
6
+ priceCents: number;
7
+ /** When the price was last updated on-chain. */
8
+ updatedAt: Date;
9
+ }
10
+ /** Read-only price oracle. */
11
+ export interface IPriceOracle {
12
+ getPrice(asset: PriceAsset): Promise<PriceResult>;
13
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -27,6 +27,6 @@ export const cryptoCharges = pgTable("crypto_charges", {
27
27
  index("idx_crypto_charges_status").on(table.status),
28
28
  index("idx_crypto_charges_created").on(table.createdAt),
29
29
  index("idx_crypto_charges_deposit_address").on(table.depositAddress),
30
- // uniqueIndex would be ideal but drizzle pgTable helper doesn't support it inline.
30
+ // Unique indexes use WHERE IS NOT NULL partial indexes (declared in migration SQL).
31
31
  // Enforced via migration: CREATE UNIQUE INDEX.
32
32
  ]);