@wopr-network/platform-core 1.20.0 → 1.22.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 (56) hide show
  1. package/dist/billing/crypto/btc/settler.js +1 -1
  2. package/dist/billing/crypto/btc/watcher.d.ts +5 -3
  3. package/dist/billing/crypto/btc/watcher.js +9 -8
  4. package/dist/billing/crypto/evm/__tests__/eth-checkout.test.d.ts +1 -0
  5. package/dist/billing/crypto/evm/__tests__/eth-checkout.test.js +49 -0
  6. package/dist/billing/crypto/evm/__tests__/eth-settler.test.d.ts +1 -0
  7. package/dist/billing/crypto/evm/__tests__/eth-settler.test.js +80 -0
  8. package/dist/billing/crypto/evm/__tests__/eth-watcher.test.d.ts +1 -0
  9. package/dist/billing/crypto/evm/__tests__/eth-watcher.test.js +134 -0
  10. package/dist/billing/crypto/evm/eth-checkout.d.ts +34 -0
  11. package/dist/billing/crypto/evm/eth-checkout.js +53 -0
  12. package/dist/billing/crypto/evm/eth-settler.d.ts +23 -0
  13. package/dist/billing/crypto/evm/eth-settler.js +52 -0
  14. package/dist/billing/crypto/evm/eth-watcher.d.ts +53 -0
  15. package/dist/billing/crypto/evm/eth-watcher.js +83 -0
  16. package/dist/billing/crypto/evm/index.d.ts +6 -0
  17. package/dist/billing/crypto/evm/index.js +3 -0
  18. package/dist/billing/crypto/evm/settler.js +1 -1
  19. package/dist/billing/crypto/index.d.ts +1 -0
  20. package/dist/billing/crypto/index.js +1 -0
  21. package/dist/billing/crypto/oracle/__tests__/chainlink.test.d.ts +1 -0
  22. package/dist/billing/crypto/oracle/__tests__/chainlink.test.js +83 -0
  23. package/dist/billing/crypto/oracle/__tests__/convert.test.d.ts +1 -0
  24. package/dist/billing/crypto/oracle/__tests__/convert.test.js +51 -0
  25. package/dist/billing/crypto/oracle/__tests__/fixed.test.d.ts +1 -0
  26. package/dist/billing/crypto/oracle/__tests__/fixed.test.js +20 -0
  27. package/dist/billing/crypto/oracle/chainlink.d.ts +26 -0
  28. package/dist/billing/crypto/oracle/chainlink.js +61 -0
  29. package/dist/billing/crypto/oracle/convert.d.ts +20 -0
  30. package/dist/billing/crypto/oracle/convert.js +38 -0
  31. package/dist/billing/crypto/oracle/fixed.d.ts +10 -0
  32. package/dist/billing/crypto/oracle/fixed.js +20 -0
  33. package/dist/billing/crypto/oracle/index.d.ts +5 -0
  34. package/dist/billing/crypto/oracle/index.js +3 -0
  35. package/dist/billing/crypto/oracle/types.d.ts +13 -0
  36. package/dist/billing/crypto/oracle/types.js +1 -0
  37. package/package.json +1 -1
  38. package/src/billing/crypto/btc/settler.ts +1 -1
  39. package/src/billing/crypto/btc/watcher.ts +12 -11
  40. package/src/billing/crypto/evm/__tests__/eth-checkout.test.ts +60 -0
  41. package/src/billing/crypto/evm/__tests__/eth-settler.test.ts +98 -0
  42. package/src/billing/crypto/evm/__tests__/eth-watcher.test.ts +157 -0
  43. package/src/billing/crypto/evm/eth-checkout.ts +84 -0
  44. package/src/billing/crypto/evm/eth-settler.ts +71 -0
  45. package/src/billing/crypto/evm/eth-watcher.ts +129 -0
  46. package/src/billing/crypto/evm/index.ts +6 -0
  47. package/src/billing/crypto/evm/settler.ts +1 -1
  48. package/src/billing/crypto/index.ts +1 -0
  49. package/src/billing/crypto/oracle/__tests__/chainlink.test.ts +107 -0
  50. package/src/billing/crypto/oracle/__tests__/convert.test.ts +62 -0
  51. package/src/billing/crypto/oracle/__tests__/fixed.test.ts +23 -0
  52. package/src/billing/crypto/oracle/chainlink.ts +85 -0
  53. package/src/billing/crypto/oracle/convert.ts +38 -0
  54. package/src/billing/crypto/oracle/fixed.ts +23 -0
  55. package/src/billing/crypto/oracle/index.ts +5 -0
  56. package/src/billing/crypto/oracle/types.ts +15 -0
@@ -2,6 +2,12 @@ export { deriveDepositAddress, isValidXpub } from "./address-gen.js";
2
2
  export type { StablecoinCheckoutDeps, StablecoinCheckoutResult } from "./checkout.js";
3
3
  export { createStablecoinCheckout, MIN_STABLECOIN_USD } from "./checkout.js";
4
4
  export { centsFromTokenAmount, getChainConfig, getTokenConfig, tokenAmountFromCents } from "./config.js";
5
+ export type { EthCheckoutDeps, EthCheckoutOpts, EthCheckoutResult } from "./eth-checkout.js";
6
+ export { createEthCheckout, MIN_ETH_USD } from "./eth-checkout.js";
7
+ export type { EthSettlerDeps } from "./eth-settler.js";
8
+ export { settleEthPayment } from "./eth-settler.js";
9
+ export type { EthPaymentEvent, EthWatcherOpts } from "./eth-watcher.js";
10
+ export { EthWatcher } from "./eth-watcher.js";
5
11
  export type { EvmSettlerDeps } from "./settler.js";
6
12
  export { settleEvmPayment } from "./settler.js";
7
13
  export type { ChainConfig, EvmChain, EvmPaymentEvent, StablecoinCheckoutOpts, StablecoinToken, TokenConfig, } from "./types.js";
@@ -1,5 +1,8 @@
1
1
  export { deriveDepositAddress, isValidXpub } from "./address-gen.js";
2
2
  export { createStablecoinCheckout, MIN_STABLECOIN_USD } from "./checkout.js";
3
3
  export { centsFromTokenAmount, getChainConfig, getTokenConfig, tokenAmountFromCents } from "./config.js";
4
+ export { createEthCheckout, MIN_ETH_USD } from "./eth-checkout.js";
5
+ export { settleEthPayment } from "./eth-settler.js";
6
+ export { EthWatcher } from "./eth-watcher.js";
4
7
  export { settleEvmPayment } from "./settler.js";
5
8
  export { createRpcCaller, EvmWatcher } from "./watcher.js";
@@ -16,7 +16,7 @@ export async function settleEvmPayment(deps, event) {
16
16
  const { chargeStore, creditLedger } = deps;
17
17
  const charge = await chargeStore.getByDepositAddress(event.to.toLowerCase());
18
18
  if (!charge) {
19
- return { handled: false, status: "Settled" };
19
+ return { handled: false, status: "Invalid" };
20
20
  }
21
21
  // Update charge status to Settled.
22
22
  await chargeStore.updateStatus(charge.referenceId, "Settled");
@@ -5,6 +5,7 @@ export { createCryptoCheckout, MIN_PAYMENT_USD } from "./checkout.js";
5
5
  export type { CryptoConfig } from "./client.js";
6
6
  export { BTCPayClient, loadCryptoConfig } from "./client.js";
7
7
  export * from "./evm/index.js";
8
+ export * from "./oracle/index.js";
8
9
  export type { CryptoBillingConfig, CryptoCheckoutOpts, CryptoPaymentState, CryptoWebhookPayload, CryptoWebhookResult, } from "./types.js";
9
10
  export { mapBtcPayEventToStatus } from "./types.js";
10
11
  export type { CryptoWebhookDeps } from "./webhook.js";
@@ -3,5 +3,6 @@ export { CryptoChargeRepository, DrizzleCryptoChargeRepository } from "./charge-
3
3
  export { createCryptoCheckout, MIN_PAYMENT_USD } from "./checkout.js";
4
4
  export { BTCPayClient, loadCryptoConfig } from "./client.js";
5
5
  export * from "./evm/index.js";
6
+ export * from "./oracle/index.js";
6
7
  export { mapBtcPayEventToStatus } from "./types.js";
7
8
  export { handleCryptoWebhook, verifyCryptoWebhookSignature } from "./webhook.js";
@@ -0,0 +1,83 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { ChainlinkOracle } from "../chainlink.js";
3
+ /**
4
+ * Encode a mock latestRoundData() response.
5
+ * Chainlink returns 5 × 32-byte ABI-encoded words:
6
+ * roundId, answer, startedAt, updatedAt, answeredInRound
7
+ */
8
+ function encodeRoundData(answer, updatedAtSec) {
9
+ const pad = (v) => v.toString(16).padStart(64, "0");
10
+ return ("0x" +
11
+ pad(1n) + // roundId
12
+ pad(answer) + // answer (price × 10^8)
13
+ pad(BigInt(updatedAtSec)) + // startedAt
14
+ pad(BigInt(updatedAtSec)) + // updatedAt
15
+ pad(1n) // answeredInRound
16
+ );
17
+ }
18
+ describe("ChainlinkOracle", () => {
19
+ const nowSec = Math.floor(Date.now() / 1000);
20
+ it("decodes ETH/USD price from latestRoundData", async () => {
21
+ // ETH at $3,500.00 → answer = 3500 × 10^8 = 350_000_000_000
22
+ const rpc = vi.fn().mockResolvedValue(encodeRoundData(350000000000n, nowSec));
23
+ const oracle = new ChainlinkOracle({ rpcCall: rpc });
24
+ const result = await oracle.getPrice("ETH");
25
+ expect(result.priceCents).toBe(350_000); // $3,500.00
26
+ expect(result.updatedAt).toBeInstanceOf(Date);
27
+ expect(rpc).toHaveBeenCalledWith("eth_call", [
28
+ { to: "0x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70", data: "0xfeaf968c" },
29
+ "latest",
30
+ ]);
31
+ });
32
+ it("decodes BTC/USD price from latestRoundData", async () => {
33
+ // BTC at $65,000.00 → answer = 65000 × 10^8 = 6_500_000_000_000
34
+ const rpc = vi.fn().mockResolvedValue(encodeRoundData(6500000000000n, nowSec));
35
+ const oracle = new ChainlinkOracle({ rpcCall: rpc });
36
+ const result = await oracle.getPrice("BTC");
37
+ expect(result.priceCents).toBe(6_500_000); // $65,000.00
38
+ });
39
+ it("handles fractional dollar prices correctly", async () => {
40
+ // ETH at $3,456.78 → answer = 345_678_000_000
41
+ const rpc = vi.fn().mockResolvedValue(encodeRoundData(345678000000n, nowSec));
42
+ const oracle = new ChainlinkOracle({ rpcCall: rpc });
43
+ const result = await oracle.getPrice("ETH");
44
+ expect(result.priceCents).toBe(345_678); // $3,456.78
45
+ });
46
+ it("rejects stale prices", async () => {
47
+ const staleTime = nowSec - 7200; // 2 hours ago
48
+ const rpc = vi.fn().mockResolvedValue(encodeRoundData(350000000000n, staleTime));
49
+ const oracle = new ChainlinkOracle({ rpcCall: rpc, maxStalenessMs: 3600_000 });
50
+ await expect(oracle.getPrice("ETH")).rejects.toThrow("stale");
51
+ });
52
+ it("rejects zero price", async () => {
53
+ const rpc = vi.fn().mockResolvedValue(encodeRoundData(0n, nowSec));
54
+ const oracle = new ChainlinkOracle({ rpcCall: rpc });
55
+ await expect(oracle.getPrice("ETH")).rejects.toThrow("Invalid price");
56
+ });
57
+ it("rejects malformed response", async () => {
58
+ const rpc = vi.fn().mockResolvedValue("0xdead");
59
+ const oracle = new ChainlinkOracle({ rpcCall: rpc });
60
+ await expect(oracle.getPrice("ETH")).rejects.toThrow("Malformed");
61
+ });
62
+ it("accepts custom feed addresses", async () => {
63
+ const customFeed = "0x1234567890abcdef1234567890abcdef12345678";
64
+ const rpc = vi.fn().mockResolvedValue(encodeRoundData(350000000000n, nowSec));
65
+ const oracle = new ChainlinkOracle({
66
+ rpcCall: rpc,
67
+ feedAddresses: { ETH: customFeed },
68
+ });
69
+ await oracle.getPrice("ETH");
70
+ expect(rpc).toHaveBeenCalledWith("eth_call", [{ to: customFeed, data: "0xfeaf968c" }, "latest"]);
71
+ });
72
+ it("respects custom staleness threshold", async () => {
73
+ const thirtyMinAgo = nowSec - 1800;
74
+ const rpc = vi.fn().mockResolvedValue(encodeRoundData(350000000000n, thirtyMinAgo));
75
+ // 20-minute threshold → stale
76
+ const strict = new ChainlinkOracle({ rpcCall: rpc, maxStalenessMs: 20 * 60 * 1000 });
77
+ await expect(strict.getPrice("ETH")).rejects.toThrow("stale");
78
+ // 60-minute threshold → fresh
79
+ const relaxed = new ChainlinkOracle({ rpcCall: rpc, maxStalenessMs: 60 * 60 * 1000 });
80
+ const result = await relaxed.getPrice("ETH");
81
+ expect(result.priceCents).toBe(350_000);
82
+ });
83
+ });
@@ -0,0 +1,51 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { centsToNative, nativeToCents } from "../convert.js";
3
+ describe("centsToNative", () => {
4
+ it("converts $50 to ETH wei at $3,500", () => {
5
+ // 5000 cents × 10^18 / 350000 cents = 14285714285714285n wei
6
+ const wei = centsToNative(5000, 350_000, 18);
7
+ expect(wei).toBe(14285714285714285n);
8
+ });
9
+ it("converts $50 to BTC sats at $65,000", () => {
10
+ // 5000 cents × 10^8 / 6500000 cents = 76923n sats
11
+ const sats = centsToNative(5000, 6_500_000, 8);
12
+ expect(sats).toBe(76923n);
13
+ });
14
+ it("converts $100 to ETH wei at $2,000", () => {
15
+ // 10000 cents × 10^18 / 200000 cents = 50000000000000000n wei (0.05 ETH)
16
+ const wei = centsToNative(10_000, 200_000, 18);
17
+ expect(wei).toBe(50000000000000000n);
18
+ });
19
+ it("rejects non-integer amountCents", () => {
20
+ expect(() => centsToNative(50.5, 350_000, 18)).toThrow("positive integer");
21
+ });
22
+ it("rejects zero amountCents", () => {
23
+ expect(() => centsToNative(0, 350_000, 18)).toThrow("positive integer");
24
+ });
25
+ it("rejects zero priceCents", () => {
26
+ expect(() => centsToNative(5000, 0, 18)).toThrow("positive integer");
27
+ });
28
+ it("rejects negative decimals", () => {
29
+ expect(() => centsToNative(5000, 350_000, -1)).toThrow("non-negative integer");
30
+ });
31
+ });
32
+ describe("nativeToCents", () => {
33
+ it("converts ETH wei back to cents at $3,500", () => {
34
+ // 14285714285714285n wei × 350000 / 10^18 = 4999 cents (truncated)
35
+ const cents = nativeToCents(14285714285714285n, 350_000, 18);
36
+ expect(cents).toBe(4999); // truncation from integer division
37
+ });
38
+ it("converts BTC sats back to cents at $65,000", () => {
39
+ // 76923n sats × 6500000 / 10^8 = 4999 cents (truncated)
40
+ const cents = nativeToCents(76923n, 6_500_000, 8);
41
+ expect(cents).toBe(4999);
42
+ });
43
+ it("exact round-trip for clean division", () => {
44
+ // 0.05 ETH at $2,000 = $100
45
+ const cents = nativeToCents(50000000000000000n, 200_000, 18);
46
+ expect(cents).toBe(10_000); // $100.00
47
+ });
48
+ it("rejects negative rawAmount", () => {
49
+ expect(() => nativeToCents(-1n, 350_000, 18)).toThrow("non-negative");
50
+ });
51
+ });
@@ -0,0 +1,20 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { FixedPriceOracle } from "../fixed.js";
3
+ describe("FixedPriceOracle", () => {
4
+ it("returns default ETH price", async () => {
5
+ const oracle = new FixedPriceOracle();
6
+ const result = await oracle.getPrice("ETH");
7
+ expect(result.priceCents).toBe(350_000); // $3,500
8
+ expect(result.updatedAt).toBeInstanceOf(Date);
9
+ });
10
+ it("returns default BTC price", async () => {
11
+ const oracle = new FixedPriceOracle();
12
+ const result = await oracle.getPrice("BTC");
13
+ expect(result.priceCents).toBe(6_500_000); // $65,000
14
+ });
15
+ it("accepts custom prices", async () => {
16
+ const oracle = new FixedPriceOracle({ ETH: 200_000, BTC: 5_000_000 });
17
+ expect((await oracle.getPrice("ETH")).priceCents).toBe(200_000);
18
+ expect((await oracle.getPrice("BTC")).priceCents).toBe(5_000_000);
19
+ });
20
+ });
@@ -0,0 +1,26 @@
1
+ import type { IPriceOracle, PriceAsset, PriceResult } from "./types.js";
2
+ type RpcCall = (method: string, params: unknown[]) => Promise<unknown>;
3
+ export interface ChainlinkOracleOpts {
4
+ rpcCall: RpcCall;
5
+ /** Override feed addresses (e.g. for testnet or Anvil forks). */
6
+ feedAddresses?: Partial<Record<PriceAsset, `0x${string}`>>;
7
+ /** Maximum age of price data before rejecting (ms). Default: 1 hour. */
8
+ maxStalenessMs?: number;
9
+ }
10
+ /**
11
+ * On-chain Chainlink price oracle.
12
+ *
13
+ * Reads latestRoundData() from Chainlink aggregator contracts via eth_call.
14
+ * No API key, no rate limits — just an RPC call to our own node.
15
+ *
16
+ * Chainlink USD feeds use 8 decimals. We convert to integer USD cents:
17
+ * priceCents = answer / 10^6 (i.e. answer / 10^8 * 100)
18
+ */
19
+ export declare class ChainlinkOracle implements IPriceOracle {
20
+ private readonly rpc;
21
+ private readonly feeds;
22
+ private readonly maxStalenessMs;
23
+ constructor(opts: ChainlinkOracleOpts);
24
+ getPrice(asset: PriceAsset): Promise<PriceResult>;
25
+ }
26
+ export {};
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Chainlink price feed addresses on Base mainnet.
3
+ * These are ERC-1967 proxy contracts — addresses are stable.
4
+ */
5
+ const FEED_ADDRESSES = {
6
+ ETH: "0x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70",
7
+ BTC: "0x64c911996D3c6aC71f9b455B1E8E7266BcbD848F",
8
+ };
9
+ /** Function selector for latestRoundData(). */
10
+ const LATEST_ROUND_DATA = "0xfeaf968c";
11
+ /** Default max staleness: 1 hour. */
12
+ const DEFAULT_MAX_STALENESS_MS = 60 * 60 * 1000;
13
+ /**
14
+ * On-chain Chainlink price oracle.
15
+ *
16
+ * Reads latestRoundData() from Chainlink aggregator contracts via eth_call.
17
+ * No API key, no rate limits — just an RPC call to our own node.
18
+ *
19
+ * Chainlink USD feeds use 8 decimals. We convert to integer USD cents:
20
+ * priceCents = answer / 10^6 (i.e. answer / 10^8 * 100)
21
+ */
22
+ export class ChainlinkOracle {
23
+ rpc;
24
+ feeds;
25
+ maxStalenessMs;
26
+ constructor(opts) {
27
+ this.rpc = opts.rpcCall;
28
+ this.feeds = { ...FEED_ADDRESSES, ...opts.feedAddresses };
29
+ this.maxStalenessMs = opts.maxStalenessMs ?? DEFAULT_MAX_STALENESS_MS;
30
+ }
31
+ async getPrice(asset) {
32
+ const feedAddress = this.feeds[asset];
33
+ if (!feedAddress)
34
+ throw new Error(`No price feed for asset: ${asset}`);
35
+ const result = (await this.rpc("eth_call", [{ to: feedAddress, data: LATEST_ROUND_DATA }, "latest"]));
36
+ // ABI decode latestRoundData() return:
37
+ // [0] roundId (uint80) — skip
38
+ // [1] answer (int256) — price × 10^8
39
+ // [2] startedAt (uint256) — skip
40
+ // [3] updatedAt (uint256) — unix seconds
41
+ // [4] answeredInRound (uint80) — skip
42
+ const hex = result.slice(2);
43
+ if (hex.length < 320) {
44
+ throw new Error(`Malformed Chainlink response for ${asset}: expected 320 hex chars, got ${hex.length}`);
45
+ }
46
+ const answer = BigInt(`0x${hex.slice(64, 128)}`);
47
+ const updatedAtSec = Number(BigInt(`0x${hex.slice(192, 256)}`));
48
+ const updatedAt = new Date(updatedAtSec * 1000);
49
+ // Staleness guard.
50
+ const ageMs = Date.now() - updatedAt.getTime();
51
+ if (ageMs > this.maxStalenessMs) {
52
+ throw new Error(`Price feed for ${asset} is stale (${Math.round(ageMs / 1000)}s old, max ${Math.round(this.maxStalenessMs / 1000)}s)`);
53
+ }
54
+ // Chainlink USD feeds: 8 decimals. answer / 10^6 = cents (integer).
55
+ const priceCents = Number(answer / 1000000n);
56
+ if (priceCents <= 0) {
57
+ throw new Error(`Invalid price for ${asset}: ${priceCents} cents`);
58
+ }
59
+ return { priceCents, updatedAt };
60
+ }
61
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Convert USD cents to native token amount using a price in cents.
3
+ *
4
+ * Formula: rawAmount = amountCents × 10^decimals / priceCents
5
+ *
6
+ * Examples:
7
+ * $50 in ETH at $3,500: centsToNative(5000, 350000, 18) = 14285714285714285n (≈0.01429 ETH)
8
+ * $50 in BTC at $65,000: centsToNative(5000, 6500000, 8) = 76923n (76,923 sats ≈ 0.00077 BTC)
9
+ *
10
+ * Integer math only. No floating point.
11
+ */
12
+ export declare function centsToNative(amountCents: number, priceCents: number, decimals: number): bigint;
13
+ /**
14
+ * Convert native token amount back to USD cents using a price in cents.
15
+ *
16
+ * Inverse of centsToNative. Truncates fractional cents.
17
+ *
18
+ * Integer math only.
19
+ */
20
+ export declare function nativeToCents(rawAmount: bigint, priceCents: number, decimals: number): number;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Convert USD cents to native token amount using a price in cents.
3
+ *
4
+ * Formula: rawAmount = amountCents × 10^decimals / priceCents
5
+ *
6
+ * Examples:
7
+ * $50 in ETH at $3,500: centsToNative(5000, 350000, 18) = 14285714285714285n (≈0.01429 ETH)
8
+ * $50 in BTC at $65,000: centsToNative(5000, 6500000, 8) = 76923n (76,923 sats ≈ 0.00077 BTC)
9
+ *
10
+ * Integer math only. No floating point.
11
+ */
12
+ export function centsToNative(amountCents, priceCents, decimals) {
13
+ if (!Number.isInteger(amountCents) || amountCents <= 0) {
14
+ throw new Error(`amountCents must be a positive integer, got ${amountCents}`);
15
+ }
16
+ if (!Number.isInteger(priceCents) || priceCents <= 0) {
17
+ throw new Error(`priceCents must be a positive integer, got ${priceCents}`);
18
+ }
19
+ if (!Number.isInteger(decimals) || decimals < 0) {
20
+ throw new Error(`decimals must be a non-negative integer, got ${decimals}`);
21
+ }
22
+ return (BigInt(amountCents) * 10n ** BigInt(decimals)) / BigInt(priceCents);
23
+ }
24
+ /**
25
+ * Convert native token amount back to USD cents using a price in cents.
26
+ *
27
+ * Inverse of centsToNative. Truncates fractional cents.
28
+ *
29
+ * Integer math only.
30
+ */
31
+ export function nativeToCents(rawAmount, priceCents, decimals) {
32
+ if (rawAmount < 0n)
33
+ throw new Error("rawAmount must be non-negative");
34
+ if (!Number.isInteger(priceCents) || priceCents <= 0) {
35
+ throw new Error(`priceCents must be a positive integer, got ${priceCents}`);
36
+ }
37
+ return Number((rawAmount * BigInt(priceCents)) / 10n ** BigInt(decimals));
38
+ }
@@ -0,0 +1,10 @@
1
+ import type { IPriceOracle, PriceAsset, PriceResult } from "./types.js";
2
+ /**
3
+ * Fixed-price oracle for testing and local dev (Anvil, regtest).
4
+ * Returns hardcoded prices — no RPC calls.
5
+ */
6
+ export declare class FixedPriceOracle implements IPriceOracle {
7
+ private readonly prices;
8
+ constructor(prices?: Partial<Record<PriceAsset, number>>);
9
+ getPrice(asset: PriceAsset): Promise<PriceResult>;
10
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Fixed-price oracle for testing and local dev (Anvil, regtest).
3
+ * Returns hardcoded prices — no RPC calls.
4
+ */
5
+ export class FixedPriceOracle {
6
+ prices;
7
+ constructor(prices = {}) {
8
+ this.prices = {
9
+ ETH: 350_000, // $3,500
10
+ BTC: 6_500_000, // $65,000
11
+ ...prices,
12
+ };
13
+ }
14
+ async getPrice(asset) {
15
+ const priceCents = this.prices[asset];
16
+ if (priceCents === undefined)
17
+ throw new Error(`No fixed price for ${asset}`);
18
+ return { priceCents, updatedAt: new Date() };
19
+ }
20
+ }
@@ -0,0 +1,5 @@
1
+ export type { ChainlinkOracleOpts } from "./chainlink.js";
2
+ export { ChainlinkOracle } from "./chainlink.js";
3
+ export { centsToNative, nativeToCents } from "./convert.js";
4
+ export { FixedPriceOracle } from "./fixed.js";
5
+ export type { IPriceOracle, PriceAsset, PriceResult } from "./types.js";
@@ -0,0 +1,3 @@
1
+ export { ChainlinkOracle } from "./chainlink.js";
2
+ export { centsToNative, nativeToCents } from "./convert.js";
3
+ export { FixedPriceOracle } from "./fixed.js";
@@ -0,0 +1,13 @@
1
+ /** Assets with Chainlink price feeds. */
2
+ export type PriceAsset = "ETH" | "BTC";
3
+ /** Result from a price oracle query. */
4
+ export interface PriceResult {
5
+ /** USD cents per 1 unit of asset (integer). */
6
+ priceCents: number;
7
+ /** When the price was last updated on-chain. */
8
+ updatedAt: Date;
9
+ }
10
+ /** Read-only price oracle. */
11
+ export interface IPriceOracle {
12
+ getPrice(asset: PriceAsset): Promise<PriceResult>;
13
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wopr-network/platform-core",
3
- "version": "1.20.0",
3
+ "version": "1.22.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -28,7 +28,7 @@ export async function settleBtcPayment(deps: BtcSettlerDeps, event: BtcPaymentEv
28
28
 
29
29
  const charge = await chargeStore.getByDepositAddress(event.address);
30
30
  if (!charge) {
31
- return { handled: false, status: "Settled" };
31
+ return { handled: false, status: "Invalid" };
32
32
  }
33
33
 
34
34
  await chargeStore.updateStatus(charge.referenceId, "Settled");
@@ -1,3 +1,4 @@
1
+ import type { IPriceOracle } from "../oracle/types.js";
1
2
  import type { BitcoindConfig, BtcPaymentEvent } from "./types.js";
2
3
 
3
4
  type RpcCall = (method: string, params: unknown[]) => Promise<unknown>;
@@ -8,8 +9,8 @@ export interface BtcWatcherOpts {
8
9
  /** Addresses to watch (must be imported into bitcoind wallet first). */
9
10
  watchedAddresses: string[];
10
11
  onPayment: (event: BtcPaymentEvent) => void | Promise<void>;
11
- /** Current BTC/USD price for conversion. */
12
- getBtcPrice: () => Promise<number>;
12
+ /** Price oracle for BTC/USD conversion. */
13
+ oracle: IPriceOracle;
13
14
  }
14
15
 
15
16
  interface ReceivedByAddress {
@@ -19,22 +20,20 @@ interface ReceivedByAddress {
19
20
  txids: string[];
20
21
  }
21
22
 
22
- /** Track which txids we've already processed to avoid double-crediting. */
23
- const processedTxids = new Set<string>();
24
-
25
23
  export class BtcWatcher {
26
24
  private readonly rpc: RpcCall;
27
25
  private readonly addresses: Set<string>;
28
26
  private readonly onPayment: BtcWatcherOpts["onPayment"];
29
27
  private readonly minConfirmations: number;
30
- private readonly getBtcPrice: () => Promise<number>;
28
+ private readonly oracle: IPriceOracle;
29
+ private readonly processedTxids = new Set<string>();
31
30
 
32
31
  constructor(opts: BtcWatcherOpts) {
33
32
  this.rpc = opts.rpcCall;
34
33
  this.addresses = new Set(opts.watchedAddresses);
35
34
  this.onPayment = opts.onPayment;
36
35
  this.minConfirmations = opts.config.confirmations;
37
- this.getBtcPrice = opts.getBtcPrice;
36
+ this.oracle = opts.oracle;
38
37
  }
39
38
 
40
39
  /** Update the set of watched addresses. */
@@ -59,14 +58,13 @@ export class BtcWatcher {
59
58
  true, // include_watchonly
60
59
  ])) as ReceivedByAddress[];
61
60
 
62
- const btcPrice = await this.getBtcPrice();
61
+ const { priceCents } = await this.oracle.getPrice("BTC");
63
62
 
64
63
  for (const entry of received) {
65
64
  if (!this.addresses.has(entry.address)) continue;
66
65
 
67
66
  for (const txid of entry.txids) {
68
- if (processedTxids.has(txid)) continue;
69
- processedTxids.add(txid);
67
+ if (this.processedTxids.has(txid)) continue;
70
68
 
71
69
  // Get transaction details for the exact amount sent to this address
72
70
  const tx = (await this.rpc("gettransaction", [txid, true])) as {
@@ -78,7 +76,8 @@ export class BtcWatcher {
78
76
  if (!detail) continue;
79
77
 
80
78
  const amountSats = Math.round(detail.amount * 100_000_000);
81
- const amountUsdCents = Math.round(detail.amount * btcPrice * 100);
79
+ // priceCents is cents per 1 BTC. detail.amount is in BTC.
80
+ const amountUsdCents = Math.round((amountSats * priceCents) / 100_000_000);
82
81
 
83
82
  const event: BtcPaymentEvent = {
84
83
  address: entry.address,
@@ -89,6 +88,8 @@ export class BtcWatcher {
89
88
  };
90
89
 
91
90
  await this.onPayment(event);
91
+ // Add AFTER successful onPayment to avoid skipping on failure
92
+ this.processedTxids.add(txid);
92
93
  }
93
94
  }
94
95
  }
@@ -0,0 +1,60 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { createEthCheckout, MIN_ETH_USD } from "../eth-checkout.js";
3
+
4
+ const mockOracle = { getPrice: vi.fn().mockResolvedValue({ priceCents: 350_000, updatedAt: new Date() }) };
5
+
6
+ function makeDeps(derivationIndex = 0) {
7
+ return {
8
+ chargeStore: {
9
+ getNextDerivationIndex: vi.fn().mockResolvedValue(derivationIndex),
10
+ createStablecoinCharge: vi.fn().mockResolvedValue(undefined),
11
+ },
12
+ oracle: mockOracle,
13
+ xpub: "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8",
14
+ };
15
+ }
16
+
17
+ describe("createEthCheckout", () => {
18
+ it("creates checkout with oracle-derived expected wei", async () => {
19
+ const deps = makeDeps();
20
+ const result = await createEthCheckout(deps, { tenant: "t1", amountUsd: 50, chain: "base" });
21
+
22
+ expect(result.amountUsd).toBe(50);
23
+ expect(result.priceCents).toBe(350_000);
24
+ expect(result.chain).toBe("base");
25
+ // $50 = 5000 cents. 5000 × 10^18 / 350000 = 14285714285714285n
26
+ expect(result.expectedWei).toBe("14285714285714285");
27
+ expect(result.depositAddress).toMatch(/^0x/);
28
+ expect(result.referenceId).toMatch(/^eth:base:0x/);
29
+ });
30
+
31
+ it("rejects amount below minimum", async () => {
32
+ const deps = makeDeps();
33
+ await expect(createEthCheckout(deps, { tenant: "t1", amountUsd: 5, chain: "base" })).rejects.toThrow(
34
+ `Minimum payment amount is $${MIN_ETH_USD}`,
35
+ );
36
+ });
37
+
38
+ it("retries on unique constraint violation", async () => {
39
+ const deps = makeDeps();
40
+ deps.chargeStore.createStablecoinCharge
41
+ .mockRejectedValueOnce(Object.assign(new Error("unique_violation"), { code: "23505" }))
42
+ .mockResolvedValueOnce(undefined);
43
+ deps.chargeStore.getNextDerivationIndex.mockResolvedValueOnce(0).mockResolvedValueOnce(1);
44
+
45
+ const result = await createEthCheckout(deps, { tenant: "t1", amountUsd: 50, chain: "base" });
46
+ expect(result.depositAddress).toMatch(/^0x/);
47
+ expect(deps.chargeStore.createStablecoinCharge).toHaveBeenCalledTimes(2);
48
+ });
49
+
50
+ it("stores amountUsdCents as integer cents", async () => {
51
+ const deps = makeDeps();
52
+ await createEthCheckout(deps, { tenant: "t1", amountUsd: 50, chain: "base" });
53
+
54
+ const call = deps.chargeStore.createStablecoinCharge.mock.calls[0][0];
55
+ expect(call.amountUsdCents).toBe(5000);
56
+ expect(Number.isInteger(call.amountUsdCents)).toBe(true);
57
+ expect(call.token).toBe("ETH");
58
+ expect(call.chain).toBe("base");
59
+ });
60
+ });