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