@wopr-network/platform-core 1.66.1 → 1.67.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/billing/crypto/btc/checkout.d.ts +4 -0
  2. package/dist/billing/crypto/btc/checkout.js +1 -2
  3. package/dist/billing/crypto/btc/index.d.ts +0 -4
  4. package/dist/billing/crypto/btc/index.js +0 -2
  5. package/dist/billing/crypto/evm/__tests__/checkout.test.js +8 -11
  6. package/dist/billing/crypto/evm/__tests__/eth-checkout.test.js +15 -1
  7. package/dist/billing/crypto/evm/checkout.d.ts +2 -0
  8. package/dist/billing/crypto/evm/checkout.js +1 -2
  9. package/dist/billing/crypto/evm/eth-checkout.d.ts +13 -2
  10. package/dist/billing/crypto/evm/eth-checkout.js +2 -4
  11. package/dist/billing/crypto/evm/eth-settler.d.ts +1 -1
  12. package/dist/billing/crypto/evm/index.d.ts +2 -8
  13. package/dist/billing/crypto/evm/index.js +0 -3
  14. package/dist/billing/crypto/evm/types.d.ts +16 -0
  15. package/dist/billing/crypto/index.d.ts +1 -6
  16. package/dist/billing/crypto/index.js +2 -3
  17. package/dist/billing/crypto/types.d.ts +0 -43
  18. package/dist/billing/crypto/types.js +1 -24
  19. package/package.json +1 -5
  20. package/src/billing/crypto/btc/checkout.ts +3 -2
  21. package/src/billing/crypto/btc/index.ts +0 -4
  22. package/src/billing/crypto/evm/__tests__/checkout.test.ts +10 -12
  23. package/src/billing/crypto/evm/__tests__/eth-checkout.test.ts +17 -1
  24. package/src/billing/crypto/evm/__tests__/eth-settler.test.ts +1 -1
  25. package/src/billing/crypto/evm/checkout.ts +3 -2
  26. package/src/billing/crypto/evm/eth-checkout.ts +15 -6
  27. package/src/billing/crypto/evm/eth-settler.ts +1 -1
  28. package/src/billing/crypto/evm/index.ts +8 -7
  29. package/src/billing/crypto/evm/types.ts +17 -0
  30. package/src/billing/crypto/index.ts +14 -12
  31. package/src/billing/crypto/types.ts +0 -63
  32. package/dist/billing/crypto/__tests__/address-gen.test.d.ts +0 -1
  33. package/dist/billing/crypto/__tests__/address-gen.test.js +0 -219
  34. package/dist/billing/crypto/__tests__/key-server.test.d.ts +0 -1
  35. package/dist/billing/crypto/__tests__/key-server.test.js +0 -363
  36. package/dist/billing/crypto/__tests__/watcher-service.test.d.ts +0 -1
  37. package/dist/billing/crypto/__tests__/watcher-service.test.js +0 -174
  38. package/dist/billing/crypto/address-gen.d.ts +0 -24
  39. package/dist/billing/crypto/address-gen.js +0 -176
  40. package/dist/billing/crypto/btc/__tests__/watcher.test.d.ts +0 -1
  41. package/dist/billing/crypto/btc/__tests__/watcher.test.js +0 -170
  42. package/dist/billing/crypto/btc/watcher.d.ts +0 -44
  43. package/dist/billing/crypto/btc/watcher.js +0 -118
  44. package/dist/billing/crypto/evm/__tests__/eth-watcher.test.d.ts +0 -1
  45. package/dist/billing/crypto/evm/__tests__/eth-watcher.test.js +0 -167
  46. package/dist/billing/crypto/evm/__tests__/watcher-confirmations.test.d.ts +0 -1
  47. package/dist/billing/crypto/evm/__tests__/watcher-confirmations.test.js +0 -159
  48. package/dist/billing/crypto/evm/__tests__/watcher.test.d.ts +0 -1
  49. package/dist/billing/crypto/evm/__tests__/watcher.test.js +0 -145
  50. package/dist/billing/crypto/evm/eth-watcher.d.ts +0 -66
  51. package/dist/billing/crypto/evm/eth-watcher.js +0 -121
  52. package/dist/billing/crypto/evm/watcher.d.ts +0 -51
  53. package/dist/billing/crypto/evm/watcher.js +0 -156
  54. package/dist/billing/crypto/key-server-entry.d.ts +0 -1
  55. package/dist/billing/crypto/key-server-entry.js +0 -122
  56. package/dist/billing/crypto/key-server.d.ts +0 -32
  57. package/dist/billing/crypto/key-server.js +0 -348
  58. package/dist/billing/crypto/oracle/__tests__/chainlink.test.d.ts +0 -1
  59. package/dist/billing/crypto/oracle/__tests__/chainlink.test.js +0 -83
  60. package/dist/billing/crypto/oracle/__tests__/coingecko.test.d.ts +0 -1
  61. package/dist/billing/crypto/oracle/__tests__/coingecko.test.js +0 -65
  62. package/dist/billing/crypto/oracle/__tests__/composite.test.d.ts +0 -1
  63. package/dist/billing/crypto/oracle/__tests__/composite.test.js +0 -48
  64. package/dist/billing/crypto/oracle/__tests__/convert.test.d.ts +0 -1
  65. package/dist/billing/crypto/oracle/__tests__/convert.test.js +0 -61
  66. package/dist/billing/crypto/oracle/__tests__/fixed.test.d.ts +0 -1
  67. package/dist/billing/crypto/oracle/__tests__/fixed.test.js +0 -20
  68. package/dist/billing/crypto/oracle/chainlink.d.ts +0 -26
  69. package/dist/billing/crypto/oracle/chainlink.js +0 -62
  70. package/dist/billing/crypto/oracle/coingecko.d.ts +0 -22
  71. package/dist/billing/crypto/oracle/coingecko.js +0 -71
  72. package/dist/billing/crypto/oracle/composite.d.ts +0 -14
  73. package/dist/billing/crypto/oracle/composite.js +0 -34
  74. package/dist/billing/crypto/oracle/convert.d.ts +0 -30
  75. package/dist/billing/crypto/oracle/convert.js +0 -51
  76. package/dist/billing/crypto/oracle/fixed.d.ts +0 -10
  77. package/dist/billing/crypto/oracle/fixed.js +0 -22
  78. package/dist/billing/crypto/oracle/index.d.ts +0 -9
  79. package/dist/billing/crypto/oracle/index.js +0 -6
  80. package/dist/billing/crypto/oracle/types.d.ts +0 -22
  81. package/dist/billing/crypto/oracle/types.js +0 -7
  82. package/dist/billing/crypto/plugin/__tests__/integration.test.d.ts +0 -1
  83. package/dist/billing/crypto/plugin/__tests__/integration.test.js +0 -58
  84. package/dist/billing/crypto/plugin/__tests__/interfaces.test.d.ts +0 -1
  85. package/dist/billing/crypto/plugin/__tests__/interfaces.test.js +0 -46
  86. package/dist/billing/crypto/plugin/__tests__/registry.test.d.ts +0 -1
  87. package/dist/billing/crypto/plugin/__tests__/registry.test.js +0 -49
  88. package/dist/billing/crypto/plugin/index.d.ts +0 -2
  89. package/dist/billing/crypto/plugin/index.js +0 -1
  90. package/dist/billing/crypto/plugin/interfaces.d.ts +0 -97
  91. package/dist/billing/crypto/plugin/interfaces.js +0 -2
  92. package/dist/billing/crypto/plugin/registry.d.ts +0 -8
  93. package/dist/billing/crypto/plugin/registry.js +0 -21
  94. package/dist/billing/crypto/plugin-watcher-service.d.ts +0 -32
  95. package/dist/billing/crypto/plugin-watcher-service.js +0 -113
  96. package/dist/billing/crypto/tron/__tests__/address-convert.test.d.ts +0 -1
  97. package/dist/billing/crypto/tron/__tests__/address-convert.test.js +0 -55
  98. package/dist/billing/crypto/tron/address-convert.d.ts +0 -14
  99. package/dist/billing/crypto/tron/address-convert.js +0 -93
  100. package/dist/billing/crypto/watcher-service.d.ts +0 -55
  101. package/dist/billing/crypto/watcher-service.js +0 -438
  102. package/src/billing/crypto/__tests__/address-gen.test.ts +0 -264
  103. package/src/billing/crypto/__tests__/key-server.test.ts +0 -395
  104. package/src/billing/crypto/__tests__/watcher-service.test.ts +0 -242
  105. package/src/billing/crypto/address-gen.ts +0 -185
  106. package/src/billing/crypto/btc/__tests__/watcher.test.ts +0 -201
  107. package/src/billing/crypto/btc/watcher.ts +0 -161
  108. package/src/billing/crypto/evm/__tests__/eth-watcher.test.ts +0 -190
  109. package/src/billing/crypto/evm/__tests__/watcher-confirmations.test.ts +0 -191
  110. package/src/billing/crypto/evm/__tests__/watcher.test.ts +0 -167
  111. package/src/billing/crypto/evm/eth-watcher.ts +0 -182
  112. package/src/billing/crypto/evm/watcher.ts +0 -204
  113. package/src/billing/crypto/key-server-entry.ts +0 -144
  114. package/src/billing/crypto/key-server.ts +0 -444
  115. package/src/billing/crypto/oracle/__tests__/chainlink.test.ts +0 -107
  116. package/src/billing/crypto/oracle/__tests__/coingecko.test.ts +0 -75
  117. package/src/billing/crypto/oracle/__tests__/composite.test.ts +0 -61
  118. package/src/billing/crypto/oracle/__tests__/convert.test.ts +0 -74
  119. package/src/billing/crypto/oracle/__tests__/fixed.test.ts +0 -23
  120. package/src/billing/crypto/oracle/chainlink.ts +0 -86
  121. package/src/billing/crypto/oracle/coingecko.ts +0 -96
  122. package/src/billing/crypto/oracle/composite.ts +0 -35
  123. package/src/billing/crypto/oracle/convert.ts +0 -53
  124. package/src/billing/crypto/oracle/fixed.ts +0 -25
  125. package/src/billing/crypto/oracle/index.ts +0 -9
  126. package/src/billing/crypto/oracle/types.ts +0 -28
  127. package/src/billing/crypto/plugin/__tests__/integration.test.ts +0 -64
  128. package/src/billing/crypto/plugin/__tests__/interfaces.test.ts +0 -51
  129. package/src/billing/crypto/plugin/__tests__/registry.test.ts +0 -58
  130. package/src/billing/crypto/plugin/index.ts +0 -17
  131. package/src/billing/crypto/plugin/interfaces.ts +0 -106
  132. package/src/billing/crypto/plugin/registry.ts +0 -26
  133. package/src/billing/crypto/plugin-watcher-service.ts +0 -148
  134. package/src/billing/crypto/tron/__tests__/address-convert.test.ts +0 -67
  135. package/src/billing/crypto/tron/address-convert.ts +0 -89
  136. package/src/billing/crypto/watcher-service.ts +0 -549
@@ -1,83 +0,0 @@
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.priceMicros).toBe(3_500_000_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.priceMicros).toBe(65_000_000_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.priceMicros).toBe(3_456_780_000); // $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.priceMicros).toBe(3_500_000_000);
82
- });
83
- });
@@ -1,65 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
- import { CoinGeckoOracle } from "../coingecko.js";
3
- describe("CoinGeckoOracle", () => {
4
- const mockFetch = (price) => vi.fn().mockResolvedValue({
5
- ok: true,
6
- json: () => Promise.resolve({ bitcoin: { usd: price } }),
7
- });
8
- it("returns price in microdollars from CoinGecko API", async () => {
9
- const oracle = new CoinGeckoOracle({ fetchFn: mockFetch(84_532.17) });
10
- const result = await oracle.getPrice("BTC");
11
- expect(result.priceMicros).toBe(84_532_170_000);
12
- expect(result.updatedAt).toBeInstanceOf(Date);
13
- });
14
- it("caches prices within TTL", async () => {
15
- const fn = mockFetch(84_532.17);
16
- const oracle = new CoinGeckoOracle({ fetchFn: fn, cacheTtlMs: 60_000 });
17
- await oracle.getPrice("BTC");
18
- await oracle.getPrice("BTC");
19
- expect(fn).toHaveBeenCalledTimes(1);
20
- });
21
- it("re-fetches after cache expires", async () => {
22
- const fn = mockFetch(84_532.17);
23
- const oracle = new CoinGeckoOracle({ fetchFn: fn, cacheTtlMs: 0 });
24
- await oracle.getPrice("BTC");
25
- await oracle.getPrice("BTC");
26
- expect(fn).toHaveBeenCalledTimes(2);
27
- });
28
- it("throws for unknown asset", async () => {
29
- const oracle = new CoinGeckoOracle({ fetchFn: mockFetch(100) });
30
- await expect(oracle.getPrice("UNKNOWN")).rejects.toThrow("No price oracle supports asset: UNKNOWN");
31
- });
32
- it("throws on API error", async () => {
33
- const fn = vi.fn().mockResolvedValue({ ok: false, status: 429, statusText: "Too Many Requests" });
34
- const oracle = new CoinGeckoOracle({ fetchFn: fn });
35
- await expect(oracle.getPrice("BTC")).rejects.toThrow("CoinGecko API error");
36
- });
37
- it("throws on zero price", async () => {
38
- const fn = vi.fn().mockResolvedValue({
39
- ok: true,
40
- json: () => Promise.resolve({ bitcoin: { usd: 0 } }),
41
- });
42
- const oracle = new CoinGeckoOracle({ fetchFn: fn });
43
- await expect(oracle.getPrice("BTC")).rejects.toThrow("Invalid CoinGecko price");
44
- });
45
- it("resolves DOGE via coingecko ID mapping", async () => {
46
- const fn = vi.fn().mockResolvedValue({
47
- ok: true,
48
- json: () => Promise.resolve({ dogecoin: { usd: 0.1742 } }),
49
- });
50
- const oracle = new CoinGeckoOracle({ fetchFn: fn });
51
- const result = await oracle.getPrice("DOGE");
52
- expect(result.priceMicros).toBe(174_200);
53
- expect(fn).toHaveBeenCalledWith(expect.stringContaining("ids=dogecoin"));
54
- });
55
- it("resolves LTC via coingecko ID mapping", async () => {
56
- const fn = vi.fn().mockResolvedValue({
57
- ok: true,
58
- json: () => Promise.resolve({ litecoin: { usd: 92.45 } }),
59
- });
60
- const oracle = new CoinGeckoOracle({ fetchFn: fn });
61
- const result = await oracle.getPrice("LTC");
62
- expect(result.priceMicros).toBe(92_450_000);
63
- expect(fn).toHaveBeenCalledWith(expect.stringContaining("ids=litecoin"));
64
- });
65
- });
@@ -1,48 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
- import { CompositeOracle } from "../composite.js";
3
- function mockOracle(priceMicros) {
4
- return { getPrice: vi.fn().mockResolvedValue({ priceMicros, updatedAt: new Date() }) };
5
- }
6
- function failingOracle(msg = "no feed") {
7
- return { getPrice: vi.fn().mockRejectedValue(new Error(msg)) };
8
- }
9
- describe("CompositeOracle", () => {
10
- it("uses primary when feedAddress is provided and primary succeeds", async () => {
11
- const primary = mockOracle(8_500_000);
12
- const fallback = mockOracle(8_400_000);
13
- const oracle = new CompositeOracle(primary, fallback);
14
- const result = await oracle.getPrice("BTC", "0x64c911996D3c6aC71f9b455B1E8E7266BcbD848F");
15
- expect(result.priceMicros).toBe(8_500_000);
16
- expect(primary.getPrice).toHaveBeenCalledWith("BTC", "0x64c911996D3c6aC71f9b455B1E8E7266BcbD848F");
17
- expect(fallback.getPrice).not.toHaveBeenCalled();
18
- });
19
- it("falls back when primary fails with feedAddress", async () => {
20
- const primary = failingOracle("stale");
21
- const fallback = mockOracle(8_400_000);
22
- const oracle = new CompositeOracle(primary, fallback);
23
- const result = await oracle.getPrice("BTC", "0x64c911996D3c6aC71f9b455B1E8E7266BcbD848F");
24
- expect(result.priceMicros).toBe(8_400_000);
25
- });
26
- it("tries primary without feed, then falls back for unknown assets", async () => {
27
- const primary = failingOracle("No price feed for asset: DOGE");
28
- const fallback = mockOracle(17);
29
- const oracle = new CompositeOracle(primary, fallback);
30
- const result = await oracle.getPrice("DOGE");
31
- expect(result.priceMicros).toBe(17);
32
- });
33
- it("uses primary built-in feeds for BTC/ETH without explicit feedAddress", async () => {
34
- const primary = mockOracle(8_500_000);
35
- const fallback = mockOracle(8_400_000);
36
- const oracle = new CompositeOracle(primary, fallback);
37
- const result = await oracle.getPrice("BTC");
38
- expect(result.priceMicros).toBe(8_500_000);
39
- expect(primary.getPrice).toHaveBeenCalledWith("BTC");
40
- expect(fallback.getPrice).not.toHaveBeenCalled();
41
- });
42
- it("propagates fallback errors when both fail", async () => {
43
- const primary = failingOracle("no chainlink");
44
- const fallback = failingOracle("no coingecko");
45
- const oracle = new CompositeOracle(primary, fallback);
46
- await expect(oracle.getPrice("UNKNOWN")).rejects.toThrow("no coingecko");
47
- });
48
- });
@@ -1,61 +0,0 @@
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 × 10000 × 10^18 / 3_500_000_000 micros = 14285714285714285n wei
6
- const wei = centsToNative(5000, 3_500_000_000, 18);
7
- expect(wei).toBe(14285714285714285n);
8
- });
9
- it("converts $50 to BTC sats at $65,000", () => {
10
- // 5000 cents × 10000 × 10^8 / 65_000_000_000 micros = 76923n sats
11
- const sats = centsToNative(5000, 65_000_000_000, 8);
12
- expect(sats).toBe(76923n);
13
- });
14
- it("converts $50 to DOGE at $0.094147", () => {
15
- // 5000 cents × 10000 × 10^8 / 94_147 micros = 53_107_898_982n base units (531.08 DOGE)
16
- const dogeUnits = centsToNative(5000, 94_147, 8);
17
- expect(Number(dogeUnits) / 1e8).toBeCloseTo(531.08, 0);
18
- });
19
- it("converts $50 to LTC at $55.79", () => {
20
- // 5000 cents × 10000 × 10^8 / 55_790_000 micros = 89_622_512n base units (0.896 LTC)
21
- const ltcUnits = centsToNative(5000, 55_790_000, 8);
22
- expect(Number(ltcUnits) / 1e8).toBeCloseTo(0.896, 2);
23
- });
24
- it("converts $100 to ETH wei at $2,000", () => {
25
- // 10000 cents × 10000 × 10^18 / 2_000_000_000 micros = 50_000_000_000_000_000n (0.05 ETH)
26
- const wei = centsToNative(10_000, 2_000_000_000, 18);
27
- expect(wei).toBe(50000000000000000n);
28
- });
29
- it("rejects non-integer amountCents", () => {
30
- expect(() => centsToNative(50.5, 3_500_000_000, 18)).toThrow("positive integer");
31
- });
32
- it("rejects zero amountCents", () => {
33
- expect(() => centsToNative(0, 3_500_000_000, 18)).toThrow("positive integer");
34
- });
35
- it("rejects zero priceMicros", () => {
36
- expect(() => centsToNative(5000, 0, 18)).toThrow("positive integer");
37
- });
38
- it("rejects negative decimals", () => {
39
- expect(() => centsToNative(5000, 3_500_000_000, -1)).toThrow("non-negative integer");
40
- });
41
- });
42
- describe("nativeToCents", () => {
43
- it("converts ETH wei back to cents at $3,500", () => {
44
- // 14285714285714285n × 3_500_000_000 / (10000 × 10^18) = 4999 cents (truncated)
45
- const cents = nativeToCents(14285714285714285n, 3_500_000_000, 18);
46
- expect(cents).toBe(4999);
47
- });
48
- it("converts BTC sats back to cents at $65,000", () => {
49
- // 76923n × 65_000_000_000 / (10000 × 10^8) = 4999 cents
50
- const cents = nativeToCents(76923n, 65_000_000_000, 8);
51
- expect(cents).toBe(4999);
52
- });
53
- it("exact round-trip for clean division", () => {
54
- // 0.05 ETH at $2,000 = $100
55
- const cents = nativeToCents(50000000000000000n, 2_000_000_000, 18);
56
- expect(cents).toBe(10_000); // $100.00
57
- });
58
- it("rejects negative rawAmount", () => {
59
- expect(() => nativeToCents(-1n, 3_500_000_000, 18)).toThrow("non-negative");
60
- });
61
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,20 +0,0 @@
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.priceMicros).toBe(3_500_000_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.priceMicros).toBe(65_000_000_000); // $65,000
14
- });
15
- it("accepts custom prices", async () => {
16
- const oracle = new FixedPriceOracle({ ETH: 2_000_000_000, BTC: 50_000_000_000 });
17
- expect((await oracle.getPrice("ETH")).priceMicros).toBe(2_000_000_000);
18
- expect((await oracle.getPrice("BTC")).priceMicros).toBe(50_000_000_000);
19
- });
20
- });
@@ -1,26 +0,0 @@
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
- * priceMicros = answer / 100 (i.e. answer / 10^8 * 10^6)
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, feedAddress?: `0x${string}`): Promise<PriceResult>;
25
- }
26
- export {};
@@ -1,62 +0,0 @@
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
- * priceMicros = answer / 100 (i.e. answer / 10^8 * 10^6)
21
- */
22
- export class ChainlinkOracle {
23
- rpc;
24
- feeds;
25
- maxStalenessMs;
26
- constructor(opts) {
27
- this.rpc = opts.rpcCall;
28
- this.feeds = new Map(Object.entries({ ...FEED_ADDRESSES, ...opts.feedAddresses }));
29
- this.maxStalenessMs = opts.maxStalenessMs ?? DEFAULT_MAX_STALENESS_MS;
30
- }
31
- async getPrice(asset, feedAddress) {
32
- const resolvedFeed = feedAddress ?? this.feeds.get(asset);
33
- if (!resolvedFeed)
34
- throw new Error(`No price feed for asset: ${asset}`);
35
- const result = (await this.rpc("eth_call", [{ to: resolvedFeed, 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 / 100 = microdollars (10^-6 USD).
55
- // e.g. BTC at $70,315 → answer = 7_031_500_000_000 → 70_315_000_000 microdollars
56
- const priceMicros = Number(answer / 100n);
57
- if (priceMicros <= 0) {
58
- throw new Error(`Invalid price for ${asset}: ${priceMicros} microdollars`);
59
- }
60
- return { priceMicros, updatedAt };
61
- }
62
- }
@@ -1,22 +0,0 @@
1
- import type { IPriceOracle, PriceAsset, PriceResult } from "./types.js";
2
- export interface CoinGeckoOracleOpts {
3
- /** Override token→id mapping. */
4
- tokenIds?: Record<string, string>;
5
- /** Cache TTL in ms. Default: 60s. */
6
- cacheTtlMs?: number;
7
- /** Custom fetch function (for testing). */
8
- fetchFn?: typeof fetch;
9
- }
10
- /**
11
- * CoinGecko price oracle — free API, no key required.
12
- * Used for assets without Chainlink on-chain feeds (DOGE, LTC).
13
- * Caches prices to stay within rate limits.
14
- */
15
- export declare class CoinGeckoOracle implements IPriceOracle {
16
- private readonly ids;
17
- private readonly cacheTtlMs;
18
- private readonly fetchFn;
19
- private readonly cache;
20
- constructor(opts?: CoinGeckoOracleOpts);
21
- getPrice(asset: PriceAsset, _feedAddress?: `0x${string}`): Promise<PriceResult>;
22
- }
@@ -1,71 +0,0 @@
1
- import { AssetNotSupportedError } from "./types.js";
2
- /**
3
- * Token symbol → CoinGecko API ID mapping.
4
- * CoinGecko uses lowercase slugs, not ticker symbols.
5
- */
6
- const COINGECKO_IDS = {
7
- BTC: "bitcoin",
8
- ETH: "ethereum",
9
- DOGE: "dogecoin",
10
- LTC: "litecoin",
11
- SOL: "solana",
12
- LINK: "chainlink",
13
- UNI: "uniswap",
14
- AERO: "aerodrome-finance",
15
- TRX: "tron",
16
- BNB: "binancecoin",
17
- POL: "matic-network",
18
- AVAX: "avalanche-2",
19
- };
20
- /** Default cache TTL: 60 seconds. CoinGecko free tier allows 10-30 req/min. */
21
- const DEFAULT_CACHE_TTL_MS = 60_000;
22
- /**
23
- * CoinGecko price oracle — free API, no key required.
24
- * Used for assets without Chainlink on-chain feeds (DOGE, LTC).
25
- * Caches prices to stay within rate limits.
26
- */
27
- export class CoinGeckoOracle {
28
- ids;
29
- cacheTtlMs;
30
- fetchFn;
31
- cache = new Map();
32
- constructor(opts = {}) {
33
- this.ids = { ...COINGECKO_IDS, ...opts.tokenIds };
34
- this.cacheTtlMs = opts.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
35
- this.fetchFn = opts.fetchFn ?? fetch;
36
- }
37
- async getPrice(asset, _feedAddress) {
38
- const cached = this.cache.get(asset);
39
- if (cached && Date.now() - cached.fetchedAt < this.cacheTtlMs) {
40
- return { priceMicros: cached.priceMicros, updatedAt: cached.updatedAt };
41
- }
42
- const coinId = this.ids[asset];
43
- if (!coinId)
44
- throw new AssetNotSupportedError(asset);
45
- const url = `https://api.coingecko.com/api/v3/simple/price?ids=${coinId}&vs_currencies=usd`;
46
- try {
47
- const res = await this.fetchFn(url);
48
- if (!res.ok) {
49
- throw new Error(`CoinGecko API error for ${asset}: ${res.status} ${res.statusText}`);
50
- }
51
- const data = (await res.json());
52
- const usdPrice = data[coinId]?.usd;
53
- if (usdPrice === undefined || usdPrice <= 0) {
54
- throw new Error(`Invalid CoinGecko price for ${asset}: ${usdPrice}`);
55
- }
56
- const priceMicros = Math.round(usdPrice * 1_000_000);
57
- const updatedAt = new Date();
58
- this.cache.set(asset, { priceMicros, updatedAt, fetchedAt: Date.now() });
59
- return { priceMicros, updatedAt };
60
- }
61
- catch (err) {
62
- // Serve stale cache on transient failure (rate limit, network error).
63
- // A slightly old price is better than rejecting the charge entirely.
64
- const stale = this.cache.get(asset);
65
- if (stale) {
66
- return { priceMicros: stale.priceMicros, updatedAt: stale.updatedAt };
67
- }
68
- throw err;
69
- }
70
- }
71
- }
@@ -1,14 +0,0 @@
1
- import type { IPriceOracle, PriceAsset, PriceResult } from "./types.js";
2
- /**
3
- * Composite oracle — tries primary (Chainlink on-chain), falls back to secondary (CoinGecko).
4
- *
5
- * When a feedAddress is provided (from payment_methods.oracle_address), the primary
6
- * oracle is used with that address. When no feed exists or the primary fails,
7
- * the fallback oracle is consulted.
8
- */
9
- export declare class CompositeOracle implements IPriceOracle {
10
- private readonly primary;
11
- private readonly fallback;
12
- constructor(primary: IPriceOracle, fallback: IPriceOracle);
13
- getPrice(asset: PriceAsset, feedAddress?: `0x${string}`): Promise<PriceResult>;
14
- }
@@ -1,34 +0,0 @@
1
- /**
2
- * Composite oracle — tries primary (Chainlink on-chain), falls back to secondary (CoinGecko).
3
- *
4
- * When a feedAddress is provided (from payment_methods.oracle_address), the primary
5
- * oracle is used with that address. When no feed exists or the primary fails,
6
- * the fallback oracle is consulted.
7
- */
8
- export class CompositeOracle {
9
- primary;
10
- fallback;
11
- constructor(primary, fallback) {
12
- this.primary = primary;
13
- this.fallback = fallback;
14
- }
15
- async getPrice(asset, feedAddress) {
16
- // If a specific feed address is provided, try the primary (Chainlink) first
17
- if (feedAddress) {
18
- try {
19
- return await this.primary.getPrice(asset, feedAddress);
20
- }
21
- catch {
22
- // Primary failed (stale, network error) — fall through to fallback
23
- }
24
- }
25
- // Try primary without explicit feed (uses built-in feed map for BTC/ETH)
26
- try {
27
- return await this.primary.getPrice(asset);
28
- }
29
- catch {
30
- // No feed configured or call failed — use fallback
31
- }
32
- return this.fallback.getPrice(asset);
33
- }
34
- }
@@ -1,30 +0,0 @@
1
- /**
2
- * Price units: **microdollars** (1 microdollar = $0.000001 = 10^-6 USD).
3
- *
4
- * Why not cents? DOGE at $0.094 rounds to 9 cents — 6% error.
5
- * Microdollars give 6 decimal places: $0.094147 = 94,147 microdollars.
6
- *
7
- * Chainlink feeds: 8 decimals → answer / 100 = microdollars.
8
- * CoinGecko: Math.round(usd * 1_000_000) = microdollars.
9
- * All math is integer bigint — no floating point.
10
- */
11
- /**
12
- * Convert USD cents to native token amount using a price in microdollars.
13
- *
14
- * Formula: rawAmount = (amountCents × 10_000) × 10^decimals / priceMicros
15
- *
16
- * Examples:
17
- * $50 in BTC at $70,315: centsToNative(5000, 70_315_000_000, 8) = 71,119 sats
18
- * $50 in DOGE at $0.094: centsToNative(5000, 94_147, 8) = 53,107,898,982 base units (531.08 DOGE)
19
- *
20
- * Integer math only. No floating point.
21
- */
22
- export declare function centsToNative(amountCents: number, priceMicros: number, decimals: number): bigint;
23
- /**
24
- * Convert native token amount back to USD cents using a price in microdollars.
25
- *
26
- * Inverse of centsToNative. Truncates fractional cents.
27
- *
28
- * Integer math only.
29
- */
30
- export declare function nativeToCents(rawAmount: bigint, priceMicros: number, decimals: number): number;
@@ -1,51 +0,0 @@
1
- /**
2
- * Price units: **microdollars** (1 microdollar = $0.000001 = 10^-6 USD).
3
- *
4
- * Why not cents? DOGE at $0.094 rounds to 9 cents — 6% error.
5
- * Microdollars give 6 decimal places: $0.094147 = 94,147 microdollars.
6
- *
7
- * Chainlink feeds: 8 decimals → answer / 100 = microdollars.
8
- * CoinGecko: Math.round(usd * 1_000_000) = microdollars.
9
- * All math is integer bigint — no floating point.
10
- */
11
- /** Microdollars per cent. Multiply amountCents by this to get microdollars. */
12
- const MICROS_PER_CENT = 10000n;
13
- /**
14
- * Convert USD cents to native token amount using a price in microdollars.
15
- *
16
- * Formula: rawAmount = (amountCents × 10_000) × 10^decimals / priceMicros
17
- *
18
- * Examples:
19
- * $50 in BTC at $70,315: centsToNative(5000, 70_315_000_000, 8) = 71,119 sats
20
- * $50 in DOGE at $0.094: centsToNative(5000, 94_147, 8) = 53,107,898,982 base units (531.08 DOGE)
21
- *
22
- * Integer math only. No floating point.
23
- */
24
- export function centsToNative(amountCents, priceMicros, decimals) {
25
- if (!Number.isInteger(amountCents) || amountCents <= 0) {
26
- throw new Error(`amountCents must be a positive integer, got ${amountCents}`);
27
- }
28
- if (!Number.isInteger(priceMicros) || priceMicros <= 0) {
29
- throw new Error(`priceMicros must be a positive integer, got ${priceMicros}`);
30
- }
31
- if (!Number.isInteger(decimals) || decimals < 0) {
32
- throw new Error(`decimals must be a non-negative integer, got ${decimals}`);
33
- }
34
- // Convert amountCents to microdollars to match priceMicros units
35
- return (BigInt(amountCents) * MICROS_PER_CENT * 10n ** BigInt(decimals)) / BigInt(priceMicros);
36
- }
37
- /**
38
- * Convert native token amount back to USD cents using a price in microdollars.
39
- *
40
- * Inverse of centsToNative. Truncates fractional cents.
41
- *
42
- * Integer math only.
43
- */
44
- export function nativeToCents(rawAmount, priceMicros, decimals) {
45
- if (rawAmount < 0n)
46
- throw new Error("rawAmount must be non-negative");
47
- if (!Number.isInteger(priceMicros) || priceMicros <= 0) {
48
- throw new Error(`priceMicros must be a positive integer, got ${priceMicros}`);
49
- }
50
- return Number((rawAmount * BigInt(priceMicros)) / (MICROS_PER_CENT * 10n ** BigInt(decimals)));
51
- }
@@ -1,10 +0,0 @@
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 in microdollars — 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, _feedAddress?: `0x${string}`): Promise<PriceResult>;
10
- }
@@ -1,22 +0,0 @@
1
- /**
2
- * Fixed-price oracle for testing and local dev (Anvil, regtest).
3
- * Returns hardcoded prices in microdollars — no RPC calls.
4
- */
5
- export class FixedPriceOracle {
6
- prices;
7
- constructor(prices = {}) {
8
- this.prices = {
9
- ETH: 3_500_000_000, // $3,500 in microdollars
10
- BTC: 65_000_000_000, // $65,000 in microdollars
11
- DOGE: 94_000, // $0.094 in microdollars
12
- LTC: 55_000_000, // $55 in microdollars
13
- ...prices,
14
- };
15
- }
16
- async getPrice(asset, _feedAddress) {
17
- const priceMicros = this.prices[asset];
18
- if (priceMicros === undefined)
19
- throw new Error(`No fixed price for ${asset}`);
20
- return { priceMicros, updatedAt: new Date() };
21
- }
22
- }
@@ -1,9 +0,0 @@
1
- export type { ChainlinkOracleOpts } from "./chainlink.js";
2
- export { ChainlinkOracle } from "./chainlink.js";
3
- export type { CoinGeckoOracleOpts } from "./coingecko.js";
4
- export { CoinGeckoOracle } from "./coingecko.js";
5
- export { CompositeOracle } from "./composite.js";
6
- export { centsToNative, nativeToCents } from "./convert.js";
7
- export { FixedPriceOracle } from "./fixed.js";
8
- export type { IPriceOracle, PriceAsset, PriceResult } from "./types.js";
9
- export { AssetNotSupportedError } from "./types.js";