@wopr-network/platform-core 1.67.0 → 1.67.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/billing/crypto/btc/checkout.d.ts +4 -0
  2. package/dist/billing/crypto/btc/checkout.js +1 -2
  3. package/dist/billing/crypto/btc/index.d.ts +0 -4
  4. package/dist/billing/crypto/btc/index.js +0 -2
  5. package/dist/billing/crypto/evm/__tests__/checkout.test.js +8 -11
  6. package/dist/billing/crypto/evm/__tests__/eth-checkout.test.js +15 -1
  7. package/dist/billing/crypto/evm/checkout.d.ts +2 -0
  8. package/dist/billing/crypto/evm/checkout.js +1 -2
  9. package/dist/billing/crypto/evm/eth-checkout.d.ts +13 -2
  10. package/dist/billing/crypto/evm/eth-checkout.js +2 -4
  11. package/dist/billing/crypto/evm/eth-settler.d.ts +1 -1
  12. package/dist/billing/crypto/evm/index.d.ts +2 -8
  13. package/dist/billing/crypto/evm/index.js +0 -3
  14. package/dist/billing/crypto/evm/types.d.ts +16 -0
  15. package/dist/billing/crypto/index.d.ts +1 -6
  16. package/dist/billing/crypto/index.js +2 -3
  17. package/dist/billing/crypto/types.d.ts +0 -43
  18. package/dist/billing/crypto/types.js +1 -24
  19. package/package.json +1 -5
  20. package/src/billing/crypto/btc/checkout.ts +3 -2
  21. package/src/billing/crypto/btc/index.ts +0 -4
  22. package/src/billing/crypto/evm/__tests__/checkout.test.ts +10 -12
  23. package/src/billing/crypto/evm/__tests__/eth-checkout.test.ts +17 -1
  24. package/src/billing/crypto/evm/__tests__/eth-settler.test.ts +1 -1
  25. package/src/billing/crypto/evm/checkout.ts +3 -2
  26. package/src/billing/crypto/evm/eth-checkout.ts +15 -6
  27. package/src/billing/crypto/evm/eth-settler.ts +1 -1
  28. package/src/billing/crypto/evm/index.ts +8 -7
  29. package/src/billing/crypto/evm/types.ts +17 -0
  30. package/src/billing/crypto/index.ts +14 -12
  31. package/src/billing/crypto/types.ts +0 -63
  32. package/dist/billing/crypto/__tests__/address-gen.test.d.ts +0 -1
  33. package/dist/billing/crypto/__tests__/address-gen.test.js +0 -219
  34. package/dist/billing/crypto/__tests__/key-server.test.d.ts +0 -1
  35. package/dist/billing/crypto/__tests__/key-server.test.js +0 -742
  36. package/dist/billing/crypto/__tests__/watcher-service.test.d.ts +0 -1
  37. package/dist/billing/crypto/__tests__/watcher-service.test.js +0 -174
  38. package/dist/billing/crypto/address-gen.d.ts +0 -24
  39. package/dist/billing/crypto/address-gen.js +0 -176
  40. package/dist/billing/crypto/btc/__tests__/watcher.test.d.ts +0 -1
  41. package/dist/billing/crypto/btc/__tests__/watcher.test.js +0 -170
  42. package/dist/billing/crypto/btc/watcher.d.ts +0 -44
  43. package/dist/billing/crypto/btc/watcher.js +0 -118
  44. package/dist/billing/crypto/evm/__tests__/eth-watcher.test.d.ts +0 -1
  45. package/dist/billing/crypto/evm/__tests__/eth-watcher.test.js +0 -167
  46. package/dist/billing/crypto/evm/__tests__/watcher-confirmations.test.d.ts +0 -1
  47. package/dist/billing/crypto/evm/__tests__/watcher-confirmations.test.js +0 -159
  48. package/dist/billing/crypto/evm/__tests__/watcher.test.d.ts +0 -1
  49. package/dist/billing/crypto/evm/__tests__/watcher.test.js +0 -145
  50. package/dist/billing/crypto/evm/eth-watcher.d.ts +0 -66
  51. package/dist/billing/crypto/evm/eth-watcher.js +0 -121
  52. package/dist/billing/crypto/evm/watcher.d.ts +0 -51
  53. package/dist/billing/crypto/evm/watcher.js +0 -156
  54. package/dist/billing/crypto/key-server-entry.d.ts +0 -1
  55. package/dist/billing/crypto/key-server-entry.js +0 -122
  56. package/dist/billing/crypto/key-server.d.ts +0 -32
  57. package/dist/billing/crypto/key-server.js +0 -472
  58. package/dist/billing/crypto/oracle/__tests__/chainlink.test.d.ts +0 -1
  59. package/dist/billing/crypto/oracle/__tests__/chainlink.test.js +0 -83
  60. package/dist/billing/crypto/oracle/__tests__/coingecko.test.d.ts +0 -1
  61. package/dist/billing/crypto/oracle/__tests__/coingecko.test.js +0 -65
  62. package/dist/billing/crypto/oracle/__tests__/composite.test.d.ts +0 -1
  63. package/dist/billing/crypto/oracle/__tests__/composite.test.js +0 -48
  64. package/dist/billing/crypto/oracle/__tests__/convert.test.d.ts +0 -1
  65. package/dist/billing/crypto/oracle/__tests__/convert.test.js +0 -61
  66. package/dist/billing/crypto/oracle/__tests__/fixed.test.d.ts +0 -1
  67. package/dist/billing/crypto/oracle/__tests__/fixed.test.js +0 -20
  68. package/dist/billing/crypto/oracle/chainlink.d.ts +0 -26
  69. package/dist/billing/crypto/oracle/chainlink.js +0 -62
  70. package/dist/billing/crypto/oracle/coingecko.d.ts +0 -22
  71. package/dist/billing/crypto/oracle/coingecko.js +0 -71
  72. package/dist/billing/crypto/oracle/composite.d.ts +0 -14
  73. package/dist/billing/crypto/oracle/composite.js +0 -34
  74. package/dist/billing/crypto/oracle/convert.d.ts +0 -30
  75. package/dist/billing/crypto/oracle/convert.js +0 -51
  76. package/dist/billing/crypto/oracle/fixed.d.ts +0 -10
  77. package/dist/billing/crypto/oracle/fixed.js +0 -22
  78. package/dist/billing/crypto/oracle/index.d.ts +0 -9
  79. package/dist/billing/crypto/oracle/index.js +0 -6
  80. package/dist/billing/crypto/oracle/types.d.ts +0 -22
  81. package/dist/billing/crypto/oracle/types.js +0 -7
  82. package/dist/billing/crypto/plugin/__tests__/integration.test.d.ts +0 -1
  83. package/dist/billing/crypto/plugin/__tests__/integration.test.js +0 -58
  84. package/dist/billing/crypto/plugin/__tests__/interfaces.test.d.ts +0 -1
  85. package/dist/billing/crypto/plugin/__tests__/interfaces.test.js +0 -46
  86. package/dist/billing/crypto/plugin/__tests__/registry.test.d.ts +0 -1
  87. package/dist/billing/crypto/plugin/__tests__/registry.test.js +0 -49
  88. package/dist/billing/crypto/plugin/index.d.ts +0 -2
  89. package/dist/billing/crypto/plugin/index.js +0 -1
  90. package/dist/billing/crypto/plugin/interfaces.d.ts +0 -97
  91. package/dist/billing/crypto/plugin/interfaces.js +0 -2
  92. package/dist/billing/crypto/plugin/registry.d.ts +0 -8
  93. package/dist/billing/crypto/plugin/registry.js +0 -21
  94. package/dist/billing/crypto/plugin-watcher-service.d.ts +0 -32
  95. package/dist/billing/crypto/plugin-watcher-service.js +0 -113
  96. package/dist/billing/crypto/tron/__tests__/address-convert.test.d.ts +0 -1
  97. package/dist/billing/crypto/tron/__tests__/address-convert.test.js +0 -55
  98. package/dist/billing/crypto/tron/address-convert.d.ts +0 -14
  99. package/dist/billing/crypto/tron/address-convert.js +0 -93
  100. package/dist/billing/crypto/watcher-service.d.ts +0 -55
  101. package/dist/billing/crypto/watcher-service.js +0 -438
  102. package/src/billing/crypto/__tests__/address-gen.test.ts +0 -264
  103. package/src/billing/crypto/__tests__/key-server.test.ts +0 -823
  104. package/src/billing/crypto/__tests__/watcher-service.test.ts +0 -242
  105. package/src/billing/crypto/address-gen.ts +0 -185
  106. package/src/billing/crypto/btc/__tests__/watcher.test.ts +0 -201
  107. package/src/billing/crypto/btc/watcher.ts +0 -161
  108. package/src/billing/crypto/evm/__tests__/eth-watcher.test.ts +0 -190
  109. package/src/billing/crypto/evm/__tests__/watcher-confirmations.test.ts +0 -191
  110. package/src/billing/crypto/evm/__tests__/watcher.test.ts +0 -167
  111. package/src/billing/crypto/evm/eth-watcher.ts +0 -182
  112. package/src/billing/crypto/evm/watcher.ts +0 -204
  113. package/src/billing/crypto/key-server-entry.ts +0 -144
  114. package/src/billing/crypto/key-server.ts +0 -617
  115. package/src/billing/crypto/oracle/__tests__/chainlink.test.ts +0 -107
  116. package/src/billing/crypto/oracle/__tests__/coingecko.test.ts +0 -75
  117. package/src/billing/crypto/oracle/__tests__/composite.test.ts +0 -61
  118. package/src/billing/crypto/oracle/__tests__/convert.test.ts +0 -74
  119. package/src/billing/crypto/oracle/__tests__/fixed.test.ts +0 -23
  120. package/src/billing/crypto/oracle/chainlink.ts +0 -86
  121. package/src/billing/crypto/oracle/coingecko.ts +0 -96
  122. package/src/billing/crypto/oracle/composite.ts +0 -35
  123. package/src/billing/crypto/oracle/convert.ts +0 -53
  124. package/src/billing/crypto/oracle/fixed.ts +0 -25
  125. package/src/billing/crypto/oracle/index.ts +0 -9
  126. package/src/billing/crypto/oracle/types.ts +0 -28
  127. package/src/billing/crypto/plugin/__tests__/integration.test.ts +0 -64
  128. package/src/billing/crypto/plugin/__tests__/interfaces.test.ts +0 -51
  129. package/src/billing/crypto/plugin/__tests__/registry.test.ts +0 -58
  130. package/src/billing/crypto/plugin/index.ts +0 -17
  131. package/src/billing/crypto/plugin/interfaces.ts +0 -106
  132. package/src/billing/crypto/plugin/registry.ts +0 -26
  133. package/src/billing/crypto/plugin-watcher-service.ts +0 -148
  134. package/src/billing/crypto/tron/__tests__/address-convert.test.ts +0 -67
  135. package/src/billing/crypto/tron/address-convert.ts +0 -89
  136. package/src/billing/crypto/watcher-service.ts +0 -549
@@ -1,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";
@@ -1,6 +0,0 @@
1
- export { ChainlinkOracle } from "./chainlink.js";
2
- export { CoinGeckoOracle } from "./coingecko.js";
3
- export { CompositeOracle } from "./composite.js";
4
- export { centsToNative, nativeToCents } from "./convert.js";
5
- export { FixedPriceOracle } from "./fixed.js";
6
- export { AssetNotSupportedError } from "./types.js";
@@ -1,22 +0,0 @@
1
- /** Assets with Chainlink price feeds. */
2
- export type PriceAsset = string;
3
- /** Thrown when no oracle supports a given asset (not a transient failure). */
4
- export declare class AssetNotSupportedError extends Error {
5
- constructor(asset: string);
6
- }
7
- /** Result from a price oracle query. */
8
- export interface PriceResult {
9
- /** Microdollars per 1 unit of asset (integer, 10^-6 USD). */
10
- priceMicros: number;
11
- /** When the price was last updated on-chain. */
12
- updatedAt: Date;
13
- }
14
- /** Read-only price oracle. */
15
- export interface IPriceOracle {
16
- /**
17
- * Get the current USD price for an asset.
18
- * @param asset — token symbol (e.g. "BTC", "DOGE")
19
- * @param feedAddress — optional Chainlink feed address override (from payment_methods.oracle_address)
20
- */
21
- getPrice(asset: PriceAsset, feedAddress?: `0x${string}`): Promise<PriceResult>;
22
- }
@@ -1,7 +0,0 @@
1
- /** Thrown when no oracle supports a given asset (not a transient failure). */
2
- export class AssetNotSupportedError extends Error {
3
- constructor(asset) {
4
- super(`No price oracle supports asset: ${asset}`);
5
- this.name = "AssetNotSupportedError";
6
- }
7
- }
@@ -1,58 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { PluginRegistry } from "../registry.js";
3
- describe("plugin integration — registry → watcher → events", () => {
4
- it("full lifecycle: register → create watcher → poll → events", async () => {
5
- const mockEvent = {
6
- chain: "test",
7
- token: "TEST",
8
- from: "0xsender",
9
- to: "0xreceiver",
10
- rawAmount: "1000",
11
- amountUsdCents: 100,
12
- txHash: "0xhash",
13
- blockNumber: 42,
14
- confirmations: 6,
15
- confirmationsRequired: 6,
16
- };
17
- const plugin = {
18
- pluginId: "test",
19
- supportedCurve: "secp256k1",
20
- encoders: {},
21
- createWatcher: (_opts) => ({
22
- init: async () => { },
23
- poll: async () => [mockEvent],
24
- setWatchedAddresses: () => { },
25
- getCursor: () => 42,
26
- stop: () => { },
27
- }),
28
- createSweeper: () => ({ scan: async () => [], sweep: async () => [] }),
29
- version: 1,
30
- };
31
- const registry = new PluginRegistry();
32
- registry.register(plugin);
33
- const resolved = registry.getOrThrow("test");
34
- const watcher = resolved.createWatcher({
35
- rpcUrl: "http://localhost:8545",
36
- rpcHeaders: {},
37
- oracle: {
38
- getPrice: async () => ({ priceMicros: 3500_000000 }),
39
- },
40
- cursorStore: {
41
- get: async () => null,
42
- save: async () => { },
43
- getConfirmationCount: async () => null,
44
- saveConfirmationCount: async () => { },
45
- },
46
- token: "TEST",
47
- chain: "test",
48
- decimals: 18,
49
- confirmations: 6,
50
- });
51
- await watcher.init();
52
- const events = await watcher.poll();
53
- expect(events).toHaveLength(1);
54
- expect(events[0].txHash).toBe("0xhash");
55
- expect(watcher.getCursor()).toBe(42);
56
- watcher.stop();
57
- });
58
- });
@@ -1,46 +0,0 @@
1
- // src/billing/crypto/plugin/__tests__/interfaces.test.ts
2
- import { describe, expect, it } from "vitest";
3
- describe("plugin interfaces — type contracts", () => {
4
- it("PaymentEvent has required fields", () => {
5
- const event = {
6
- chain: "ethereum",
7
- token: "ETH",
8
- from: "0xabc",
9
- to: "0xdef",
10
- rawAmount: "1000000000000000000",
11
- amountUsdCents: 350000,
12
- txHash: "0x123",
13
- blockNumber: 100,
14
- confirmations: 6,
15
- confirmationsRequired: 6,
16
- };
17
- expect(event.chain).toBe("ethereum");
18
- expect(event.amountUsdCents).toBe(350000);
19
- });
20
- it("ICurveDeriver contract is satisfiable", () => {
21
- const deriver = {
22
- derivePublicKey: (_chain, _index) => new Uint8Array(33),
23
- getCurve: () => "secp256k1",
24
- };
25
- expect(deriver.getCurve()).toBe("secp256k1");
26
- expect(deriver.derivePublicKey(0, 0)).toBeInstanceOf(Uint8Array);
27
- });
28
- it("IAddressEncoder contract is satisfiable", () => {
29
- const encoder = {
30
- encode: (_pk, _params) => "bc1qtest",
31
- encodingType: () => "bech32",
32
- };
33
- expect(encoder.encodingType()).toBe("bech32");
34
- expect(encoder.encode(new Uint8Array(33), { hrp: "bc" })).toBe("bc1qtest");
35
- });
36
- it("IChainWatcher contract is satisfiable", () => {
37
- const watcher = {
38
- init: async () => { },
39
- poll: async () => [],
40
- setWatchedAddresses: () => { },
41
- getCursor: () => 0,
42
- stop: () => { },
43
- };
44
- expect(watcher.getCursor()).toBe(0);
45
- });
46
- });