@agent402-dev/pay-server 0.1.0 → 0.2.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.
package/dist/index.js CHANGED
@@ -1,6 +1,8 @@
1
- // @agent402-dev/pay-server — 공개 API
2
- export { createPaymentGate, isFacilitatorSideFailure, KNOWN_FACILITATORS, SOLANA_MAINNET, SOLANA_DEVNET, USDC_MAINNET, A402_MAINNET, } from './gate.js';
1
+ // @agent402-dev/pay-server — public API
2
+ // Payment tokens: USDC + PREQ. A402 (v1) is deprecated (A402_MAINNET and config.a402 only when used explicitly, with a warning)
3
+ export { createPaymentGate, isFacilitatorSideFailure, KNOWN_FACILITATORS, SOLANA_MAINNET, SOLANA_DEVNET, USDC_MAINNET, PREQ_MAINNET, A402_MAINNET, } from './gate.js';
4
+ export { PREQ_MAINNET_MINT, PREQ_MAINNET_POOL, A402_DEPRECATION_WARNING } from './preq.js';
3
5
  export { rpcChain, receivedBy } from './chain.js';
4
- export { createRateBook, memoryRateStore, a402AmountFor } from './rates.js';
5
- export { DEFAULT_GUARDS, fixRate, samplePrice } from './pricing.js';
6
+ export { createRateBook, memoryRateStore } from './rates.js';
7
+ export { DEFAULT_GUARDS, fixRate, samplePrice, tokenAmountFor, PREQ_POOL_TARGET, A402_POOL_TARGET, } from './pricing.js';
6
8
  export { memoryX402Ledger, ledgerClaim, SETTLE_UNKNOWN_EXPIRY_MS } from './x402.js';
package/dist/preq.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /** PREQ mint (Token-2022, 6 decimals) */
2
+ export declare const PREQ_MAINNET_MINT = "aTbGw3gU5JyJkAdXLj8rYZ3mCXkPbyHjtTAyCX3jQLX";
3
+ /** Meteora DAMM v2 pool used for pricing (PREQ / WSOL) */
4
+ export declare const PREQ_MAINNET_POOL = "51F34MKDFBLr5GwKiiJMWV9HsHv63dkkP3ZMMxPN71xc";
5
+ export declare const PREQ_DECIMALS = 6;
6
+ export declare const PREQ_TOKEN_PROGRAM = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb";
7
+ /** Warning printed when A402 (v1) is enabled explicitly */
8
+ export declare const A402_DEPRECATION_WARNING = "A402 (v1) is deprecated and no longer supported; use PREQ.";
9
+ /** Error explaining what to fill in when a value is empty */
10
+ export declare function requirePreqValue(name: 'PREQ_MAINNET_MINT' | 'PREQ_MAINNET_POOL', value: string): string;
package/dist/preq.js ADDED
@@ -0,0 +1,18 @@
1
+ // Mainnet values of the payment token PREQ (Prequ), kept in this one file only.
2
+ // Set after the PREQ launch on 2026-11-21 (official addresses: https://claude.ai/artifact/S6UafAfViJk3DJeMsDMAja).
3
+ import { TOKEN_2022 } from './chain.js';
4
+ /** PREQ mint (Token-2022, 6 decimals) */
5
+ export const PREQ_MAINNET_MINT = 'aTbGw3gU5JyJkAdXLj8rYZ3mCXkPbyHjtTAyCX3jQLX';
6
+ /** Meteora DAMM v2 pool used for pricing (PREQ / WSOL) */
7
+ export const PREQ_MAINNET_POOL = '51F34MKDFBLr5GwKiiJMWV9HsHv63dkkP3ZMMxPN71xc';
8
+ export const PREQ_DECIMALS = 6;
9
+ export const PREQ_TOKEN_PROGRAM = TOKEN_2022;
10
+ /** Warning printed when A402 (v1) is enabled explicitly */
11
+ export const A402_DEPRECATION_WARNING = 'A402 (v1) is deprecated and no longer supported; use PREQ.';
12
+ /** Error explaining what to fill in when a value is empty */
13
+ export function requirePreqValue(name, value) {
14
+ if (!value) {
15
+ throw new Error(`${name} is not set: PREQ payments cannot be enabled yet. Fill ${name} in @agent402-dev/pay-server src/preq.ts after the PREQ launch (or pass your own asset/pool).`);
16
+ }
17
+ return value;
18
+ }
package/dist/pricing.d.ts CHANGED
@@ -7,44 +7,62 @@ export declare function decodeDammV2PoolForRate(data: Uint8Array): {
7
7
  /** sqrt_price (Q64.64, u128 LE) */
8
8
  sqrtPrice: bigint;
9
9
  };
10
+ export declare const WSOL_MINT = "So11111111111111111111111111111111111111112";
11
+ /** Meteora DAMM v2 (cp-amm) program */
12
+ export declare const DAMM_V2_PROGRAM = "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG";
13
+ /** Pool vault address = PDA(["token_vault", mint, pool], cp-amm); same rule as Meteora SDK deriveTokenVaultAddress */
14
+ export declare function dammV2VaultAddress(mint: string, pool: string): string;
15
+ /** Token to price and its token/WSOL pool */
16
+ export interface PoolTarget {
17
+ symbol: 'PREQ' | 'A402';
18
+ mint: string;
19
+ pool: string;
20
+ decimals: number;
21
+ }
22
+ /** Default target: PREQ (constants in preq.ts). samplePrice errors if they are empty */
23
+ export declare const PREQ_POOL_TARGET: PoolTarget;
24
+ /** @deprecated A402 (v1) is deprecated. Kept for records only; prints a warning if used */
10
25
  export declare const A402_MAINNET_MINT = "GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X";
26
+ /** @deprecated A402 (v1) is deprecated */
11
27
  export declare const A402_MAINNET_POOL = "DaHBw8dxnZaCaX5HdsiM1Hs1uQNwsW3QW3wcD6P4Z5oZ";
12
- export declare const A402_POOL_SOL_VAULT = "FXf9X8exSSZCSe7h14vK4xpcXsdbdNP7nR8myo1MBaMq";
13
- export declare const WSOL_MINT = "So11111111111111111111111111111111111111112";
14
- /** Pyth Crypto.SOL/USD 피드 ID (hermes.pyth.network /v2/price_feeds 목록에서 확인) */
28
+ /** @deprecated A402 (v1) is deprecated. Used only when passed explicitly to samplePrice (prints a warning) */
29
+ export declare const A402_POOL_TARGET: PoolTarget;
30
+ /** Pyth Crypto.SOL/USD feed ID (checked against the hermes.pyth.network /v2/price_feeds list) */
15
31
  export declare const PYTH_SOL_USD_FEED = "ef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d";
16
- /** Pyth 푸시 오라클 프로그램과 receiver(계정 소유자) */
32
+ /** Pyth push oracle program and receiver (account owner) */
17
33
  export declare const PYTH_PUSH_ORACLE = "pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT";
18
34
  export declare const PYTH_RECEIVER = "rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ";
19
- /** 샤드 0 의 SOL/USD 가격 계정 = PDA([u16 shard=0, feed_id], push oracle) — 아래 함수로 계산해 대조 */
35
+ /** SOL/USD price account for shard 0 = PDA([u16 shard=0, feed_id], push oracle); computed and checked by the function below */
20
36
  export declare function pythPriceAccount(feedHex?: string, shard?: number): string;
21
37
  export declare const PRICE_USDC_BASE_UNITS = 20000n;
22
- export declare const A402_DISCOUNT_BPS = 3000;
23
- /** 안전장치 기준 (제안값, 2026-11-19) */
38
+ export declare const TOKEN_DISCOUNT_BPS = 0;
39
+ /** Guard thresholds (proposed values, 2026-11-19) */
24
40
  export interface RateGuards {
25
- /** 전날 기록 최소 개수 (24시간 중) */
41
+ /** Minimum samples in the previous day (out of 24 hours) */
26
42
  minSamples: number;
27
- /** 전날 모든 기록에서 풀 SOL 쪽 깊이(USD) 최소값 */
43
+ /** Minimum SOL-side pool depth (USD) across all of the previous day's samples */
28
44
  minPoolSolSideUsd: number;
29
- /** 전날 기록의 최고가 / 최저가 최대 비율 */
45
+ /** Maximum ratio of the previous day's highest to lowest price */
30
46
  maxDailyRangeRatio: number;
31
- /** Pyth 신뢰구간 / 가격 최대 비율 (넘으면 그 기록을 버림) */
47
+ /** Maximum Pyth confidence / price ratio (samples above it are discarded) */
32
48
  maxOracleConfRatio: number;
33
- /** Pyth 갱신 시각이 기록 시각보다 최대 몇 초 전까지 허용 */
49
+ /** How many seconds before the sample time the Pyth update may be */
34
50
  maxOracleAgeSec: number;
35
51
  }
36
52
  export declare const DEFAULT_GUARDS: RateGuards;
37
53
  export interface PriceSample {
38
- /** ISO 시각 */
54
+ /** ISO time */
39
55
  at: string;
40
- /** SOL per A402 */
41
- a402Sol: number;
56
+ /** Which token the sample is for (missing for old A402 samples) */
57
+ symbol?: 'PREQ' | 'A402';
58
+ /** SOL per token */
59
+ tokenSol: number;
42
60
  /** USD per SOL (Pyth) */
43
61
  solUsd: number;
44
62
  solUsdConf: number;
45
- /** USD per A402 */
46
- a402Usd: number;
47
- /** 풀 SOL 금고 잔액 × SOL/USD */
63
+ /** USD per token */
64
+ tokenUsd: number;
65
+ /** Pool SOL vault balance × SOL/USD */
48
66
  poolSolSideUsd: number;
49
67
  slot: number;
50
68
  pythPublishTime: number;
@@ -52,8 +70,8 @@ export interface PriceSample {
52
70
  export type DailyRate = {
53
71
  status: 'on';
54
72
  date: string;
55
- basedOn: string;
56
- a402Usd: number;
73
+ basedOn: string; /** USD per token */
74
+ tokenUsd: number;
57
75
  samples: number;
58
76
  method: string;
59
77
  } | {
@@ -64,11 +82,11 @@ export type DailyRate = {
64
82
  samples: number;
65
83
  };
66
84
  /**
67
- * DAMM v2 sqrt_price(Q64.64) → B per A 가격.
85
+ * DAMM v2 sqrt_price (Q64.64) → price of B per A.
68
86
  * price = (sqrt_price / 2^64)^2 × 10^(decimalsA − decimalsB)
69
87
  */
70
88
  export declare function dammV2Price(sqrtPrice: bigint, decimalsA: number, decimalsB: number): number;
71
- /** Pyth PriceUpdateV2 계정 해석 (verification_level 이 Partial 이면 1바이트 더) */
89
+ /** Decodes a Pyth PriceUpdateV2 account (one more byte if verification_level is Partial) */
72
90
  export declare function decodePythPriceUpdate(data: Buffer): {
73
91
  verification: string;
74
92
  feedId: string;
@@ -76,12 +94,24 @@ export declare function decodePythPriceUpdate(data: Buffer): {
76
94
  conf: number;
77
95
  publishTime: number;
78
96
  };
79
- /** 풀·SOL 금고·Pyth 계정을 RPC 한 번으로 읽어 기록 하나. 오라클 품질이 기준 밖이면 예외 */
80
- export declare function samplePrice(fetcher: AccountFetcher, now?: () => Date, guards?: RateGuards): Promise<PriceSample>;
97
+ /**
98
+ * "SOL per token" from the pool's sqrt_price. Handles the token on side A or B.
99
+ * Throws on 0, infinity or NaN (including when a single-sided pool's price sits at the range edge right after trading starts)
100
+ */
101
+ export declare function tokenSolFromPool(sqrtPrice: bigint, tokenIsA: boolean, tokenDecimals: number): number;
102
+ /** Reads the pool, SOL vault and Pyth accounts in one RPC call and records one sample. Default target is PREQ (preq.ts). Throws if oracle quality is out of bounds */
103
+ export declare function samplePrice(fetcher: AccountFetcher, now?: () => Date, guards?: RateGuards, target?: PoolTarget): Promise<PriceSample>;
81
104
  export declare function median(xs: number[]): number;
82
- /** date 에 쓸 고정 환율. 전날 기록으로 계산하고, 안전장치에 걸리면 off */
105
+ /** Fixed rate for date. Computed from the previous day's samples; off if a guard trips */
83
106
  export declare function fixRate(date: string, samples: PriceSample[], guards?: RateGuards): DailyRate;
84
- /** A402 로 낼 금액 (원 단위). 0.02 USD × (1 − 30%) 를 고정 환율로 나누고 올림 */
85
- export declare function a402Amount(rate: Extract<DailyRate, {
107
+ /**
108
+ * Token amount to pay (base units): priceUsd × (1 − discount) ÷ fixed rate, rounded up.
109
+ * Throws if the rate is 0, negative, infinite or NaN, or if the result exceeds u64 (so that request does not offer token payment)
110
+ */
111
+ export declare function tokenAmountFor(priceUsd: number, discountPercent: number, rate: Extract<DailyRate, {
112
+ status: 'on';
113
+ }>, decimals?: number): bigint;
114
+ /** Token amount (base units) at the default price (0.02 USD), no discount */
115
+ export declare function tokenAmount(rate: Extract<DailyRate, {
86
116
  status: 'on';
87
117
  }>, decimals?: number): bigint;
package/dist/pricing.js CHANGED
@@ -1,9 +1,11 @@
1
- // A402 결제 환율 (30% 할인). 비공개 영역(API 서버). 방식은 docs/pricing.md 에 공개용으로 정리.
2
- // - 매시간 기록 (RPC 한 번): A402/SOL = 메인넷 Meteora DAMM v2 풀 sqrt_price,
3
- // SOL 쪽 깊이 = 풀 SOL 금고 잔액, SOL/USD = Pyth 푸시 오라클 계정 (Solana 메인넷, USDC ≈ 1 USD 로 봄)
4
- // - 하루 고정: 전날(UTC) 기록의 중앙값. 안전장치(기록 수·유동성·변동폭) 중 하나라도 걸리면 그날 A402 결제 끔 (USDC 만)
1
+ // Payment token (PREQ) rate. The method is documented for the public in docs/pricing.md.
2
+ // - Hourly sample (one RPC call): token/SOL = mainnet Meteora DAMM v2 pool sqrt_price,
3
+ // SOL-side depth = pool SOL vault balance, SOL/USD = Pyth push oracle account (Solana mainnet, USDC treated as ≈ 1 USD)
4
+ // - Fixed per day: median of the previous day's (UTC) samples. If any guard (sample count, liquidity, range) trips, token payments are off that day (USDC only)
5
+ // - Pool and mint addresses are read from preq.ts only. The A402 (v1) pool is deprecated: only when passed explicitly (prints a warning)
5
6
  import { PublicKey } from '@solana/web3.js';
6
- /** Meteora DAMM v2 풀 계정에서 환율에 필요한 부분만 (오프셋: cp-amm IDL, bytemuck — 점검 엔진의 해석과 같은 값) */
7
+ import { A402_DEPRECATION_WARNING, PREQ_DECIMALS, PREQ_MAINNET_MINT, PREQ_MAINNET_POOL, requirePreqValue } from './preq.js';
8
+ /** Only the parts of a Meteora DAMM v2 pool account needed for the rate (offsets: cp-amm IDL, bytemuck; same values as the check engine's decoder) */
7
9
  const DAMM_V2_POOL_SIZE = 1112;
8
10
  const DAMM_V2_POOL_DISC = [241, 154, 109, 4, 17, 177, 109, 188];
9
11
  export function decodeDammV2PoolForRate(data) {
@@ -17,23 +19,34 @@ export function decodeDammV2PoolForRate(data) {
17
19
  sqrtPrice: (b.readBigUInt64LE(464) << 64n) | b.readBigUInt64LE(456),
18
20
  };
19
21
  }
22
+ export const WSOL_MINT = 'So11111111111111111111111111111111111111112';
23
+ /** Meteora DAMM v2 (cp-amm) program */
24
+ export const DAMM_V2_PROGRAM = 'cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG';
25
+ /** Pool vault address = PDA(["token_vault", mint, pool], cp-amm); same rule as Meteora SDK deriveTokenVaultAddress */
26
+ export function dammV2VaultAddress(mint, pool) {
27
+ return PublicKey.findProgramAddressSync([Buffer.from('token_vault'), new PublicKey(mint).toBuffer(), new PublicKey(pool).toBuffer()], new PublicKey(DAMM_V2_PROGRAM))[0].toBase58();
28
+ }
29
+ /** Default target: PREQ (constants in preq.ts). samplePrice errors if they are empty */
30
+ export const PREQ_POOL_TARGET = { symbol: 'PREQ', mint: PREQ_MAINNET_MINT, pool: PREQ_MAINNET_POOL, decimals: PREQ_DECIMALS };
31
+ /** @deprecated A402 (v1) is deprecated. Kept for records only; prints a warning if used */
20
32
  export const A402_MAINNET_MINT = 'GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X';
33
+ /** @deprecated A402 (v1) is deprecated */
21
34
  export const A402_MAINNET_POOL = 'DaHBw8dxnZaCaX5HdsiM1Hs1uQNwsW3QW3wcD6P4Z5oZ';
22
- export const A402_POOL_SOL_VAULT = 'FXf9X8exSSZCSe7h14vK4xpcXsdbdNP7nR8myo1MBaMq';
23
- export const WSOL_MINT = 'So11111111111111111111111111111111111111112';
24
- /** Pyth Crypto.SOL/USD 피드 ID (hermes.pyth.network /v2/price_feeds 목록에서 확인) */
35
+ /** @deprecated A402 (v1) is deprecated. Used only when passed explicitly to samplePrice (prints a warning) */
36
+ export const A402_POOL_TARGET = { symbol: 'A402', mint: A402_MAINNET_MINT, pool: A402_MAINNET_POOL, decimals: 6 };
37
+ /** Pyth Crypto.SOL/USD feed ID (checked against the hermes.pyth.network /v2/price_feeds list) */
25
38
  export const PYTH_SOL_USD_FEED = 'ef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d';
26
- /** Pyth 푸시 오라클 프로그램과 receiver(계정 소유자) */
39
+ /** Pyth push oracle program and receiver (account owner) */
27
40
  export const PYTH_PUSH_ORACLE = 'pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT';
28
41
  export const PYTH_RECEIVER = 'rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ';
29
- /** 샤드 0 의 SOL/USD 가격 계정 = PDA([u16 shard=0, feed_id], push oracle) — 아래 함수로 계산해 대조 */
42
+ /** SOL/USD price account for shard 0 = PDA([u16 shard=0, feed_id], push oracle); computed and checked by the function below */
30
43
  export function pythPriceAccount(feedHex = PYTH_SOL_USD_FEED, shard = 0) {
31
44
  const s = Buffer.alloc(2);
32
45
  s.writeUInt16LE(shard);
33
46
  return PublicKey.findProgramAddressSync([s, Buffer.from(feedHex, 'hex')], new PublicKey(PYTH_PUSH_ORACLE))[0].toBase58();
34
47
  }
35
- export const PRICE_USDC_BASE_UNITS = 20000n; // 0.02 USDC (소수 6자리)
36
- export const A402_DISCOUNT_BPS = 3000; // 30%
48
+ export const PRICE_USDC_BASE_UNITS = 20000n; // 0.02 USDC (6 decimals)
49
+ export const TOKEN_DISCOUNT_BPS = 0; // no discount by default
37
50
  export const DEFAULT_GUARDS = {
38
51
  minSamples: 12,
39
52
  minPoolSolSideUsd: 100,
@@ -42,14 +55,14 @@ export const DEFAULT_GUARDS = {
42
55
  maxOracleAgeSec: 120,
43
56
  };
44
57
  /**
45
- * DAMM v2 sqrt_price(Q64.64) → B per A 가격.
58
+ * DAMM v2 sqrt_price (Q64.64) → price of B per A.
46
59
  * price = (sqrt_price / 2^64)^2 × 10^(decimalsA − decimalsB)
47
60
  */
48
61
  export function dammV2Price(sqrtPrice, decimalsA, decimalsB) {
49
62
  const s = Number(sqrtPrice) / 2 ** 64;
50
63
  return s * s * 10 ** (decimalsA - decimalsB);
51
64
  }
52
- /** Pyth PriceUpdateV2 계정 해석 (verification_level 이 Partial 이면 1바이트 더) */
65
+ /** Decodes a Pyth PriceUpdateV2 account (one more byte if verification_level is Partial) */
53
66
  export function decodePythPriceUpdate(data) {
54
67
  const tag = data[40];
55
68
  let o = 41 + (tag === 0 ? 1 : 0);
@@ -61,19 +74,41 @@ export function decodePythPriceUpdate(data) {
61
74
  const publishTime = Number(data.readBigInt64LE(o + 20));
62
75
  return { verification: tag === 1 ? 'full' : 'partial', feedId, price: Number(price) * 10 ** expo, conf: Number(conf) * 10 ** expo, publishTime };
63
76
  }
64
- /** 풀·SOL 금고·Pyth 계정을 RPC 한 번으로 읽어 기록 하나. 오라클 품질이 기준 밖이면 예외 */
65
- export async function samplePrice(fetcher, now = () => new Date(), guards = DEFAULT_GUARDS) {
77
+ /**
78
+ * "SOL per token" from the pool's sqrt_price. Handles the token on side A or B.
79
+ * Throws on 0, infinity or NaN (including when a single-sided pool's price sits at the range edge right after trading starts)
80
+ */
81
+ export function tokenSolFromPool(sqrtPrice, tokenIsA, tokenDecimals) {
82
+ const v = tokenIsA ? dammV2Price(sqrtPrice, tokenDecimals, 9) : 1 / dammV2Price(sqrtPrice, 9, tokenDecimals);
83
+ if (!Number.isFinite(v) || !(v > 0))
84
+ throw new Error('non-positive or non-finite pool price');
85
+ return v;
86
+ }
87
+ /** Reads the pool, SOL vault and Pyth accounts in one RPC call and records one sample. Default target is PREQ (preq.ts). Throws if oracle quality is out of bounds */
88
+ export async function samplePrice(fetcher, now = () => new Date(), guards = DEFAULT_GUARDS, target = PREQ_POOL_TARGET) {
89
+ if (target.symbol === 'A402')
90
+ console.warn(A402_DEPRECATION_WARNING);
91
+ const mint = target.symbol === 'PREQ' ? requirePreqValue('PREQ_MAINNET_MINT', target.mint) : target.mint;
92
+ const poolAddr = target.symbol === 'PREQ' ? requirePreqValue('PREQ_MAINNET_POOL', target.pool) : target.pool;
93
+ if (!mint || !poolAddr)
94
+ throw new Error(`${target.symbol} mint/pool not set`);
95
+ const solVault = dammV2VaultAddress(WSOL_MINT, poolAddr);
66
96
  const pythAcc = pythPriceAccount();
67
- const { slot, accounts } = await fetcher([A402_MAINNET_POOL, A402_POOL_SOL_VAULT, pythAcc]);
97
+ const { slot, accounts } = await fetcher([poolAddr, solVault, pythAcc]);
68
98
  const [poolAcc, vaultAcc, pyth] = accounts;
69
99
  if (!poolAcc || !vaultAcc || !pyth)
70
100
  throw new Error('price accounts missing');
71
101
  const pool = decodeDammV2PoolForRate(poolAcc.data);
72
- if (pool.tokenAMint !== A402_MAINNET_MINT || pool.tokenBMint !== WSOL_MINT || pool.tokenBVault !== A402_POOL_SOL_VAULT) {
102
+ const tokenIsA = pool.tokenAMint === mint && pool.tokenBMint === WSOL_MINT && pool.tokenBVault === solVault;
103
+ const tokenIsB = pool.tokenBMint === mint && pool.tokenAMint === WSOL_MINT && pool.tokenAVault === solVault;
104
+ if (!tokenIsA && !tokenIsB)
73
105
  throw new Error('unexpected pool layout');
74
- }
75
- const a402Sol = dammV2Price(pool.sqrtPrice, 6, 9);
76
- const solInVault = Number(Buffer.from(vaultAcc.data).readBigUInt64LE(64)) / 1e9;
106
+ const tokenSol = tokenSolFromPool(pool.sqrtPrice, tokenIsA, target.decimals);
107
+ const vaultData = Buffer.from(vaultAcc.data);
108
+ if (vaultData.length < 72)
109
+ throw new Error('unexpected SOL vault account');
110
+ // A single-sided pool may have 0 on the SOL side right after trading starts → record depth 0 (fixRate's depth guard turns off payments that day)
111
+ const solInVault = Number(vaultData.readBigUInt64LE(64)) / 1e9;
77
112
  if (pyth.owner !== PYTH_RECEIVER)
78
113
  throw new Error('pyth account owner mismatch');
79
114
  const p = decodePythPriceUpdate(Buffer.from(pyth.data));
@@ -86,10 +121,11 @@ export async function samplePrice(fetcher, now = () => new Date(), guards = DEFA
86
121
  throw new Error('pyth price stale');
87
122
  if (!(p.price > 0) || p.conf / p.price > guards.maxOracleConfRatio)
88
123
  throw new Error('pyth confidence too wide');
89
- if (!(a402Sol > 0))
90
- throw new Error('non-positive pool price');
124
+ const tokenUsd = tokenSol * p.price;
125
+ if (!Number.isFinite(tokenUsd) || !(tokenUsd > 0))
126
+ throw new Error('non-positive or non-finite token price');
91
127
  return {
92
- at: now().toISOString(), a402Sol, solUsd: p.price, solUsdConf: p.conf, a402Usd: a402Sol * p.price,
128
+ at: now().toISOString(), symbol: target.symbol, tokenSol, solUsd: p.price, solUsdConf: p.conf, tokenUsd,
93
129
  poolSolSideUsd: solInVault * p.price, slot, pythPublishTime: p.publishTime,
94
130
  };
95
131
  }
@@ -99,29 +135,49 @@ export function median(xs) {
99
135
  return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
100
136
  }
101
137
  const prevDay = (d) => new Date(Date.parse(`${d}T00:00:00Z`) - 86_400_000).toISOString().slice(0, 10);
102
- /** date 에 쓸 고정 환율. 전날 기록으로 계산하고, 안전장치에 걸리면 off */
138
+ /** Fixed rate for date. Computed from the previous day's samples; off if a guard trips */
103
139
  export function fixRate(date, samples, guards = DEFAULT_GUARDS) {
104
140
  const basedOn = prevDay(date);
105
141
  const ys = samples.filter((s) => s.at.slice(0, 10) === basedOn);
106
142
  const off = (reason) => ({ status: 'off', date, basedOn, reason, samples: ys.length });
107
- if (ys.length < guards.minSamples)
108
- return off(`${basedOn}: ${ys.length} samples, below the minimum of ${guards.minSamples}`);
109
- const minDepth = Math.min(...ys.map((s) => s.poolSolSideUsd));
143
+ if (ys.length === 0 || ys.length < guards.minSamples)
144
+ return off(`${basedOn}: ${ys.length} samples, below the minimum of ${Math.max(1, guards.minSamples)}`);
145
+ // If any price is 0, negative, infinite or NaN, turn off that day (avoids division by zero and abnormal amounts)
146
+ if (ys.some((s) => !Number.isFinite(s.tokenUsd) || !(s.tokenUsd > 0)))
147
+ return off(`${basedOn}: invalid (zero, negative or non-finite) price sample`);
148
+ const depths = ys.map((s) => (Number.isFinite(s.poolSolSideUsd) ? s.poolSolSideUsd : 0));
149
+ const minDepth = Math.min(...depths);
110
150
  if (minDepth < guards.minPoolSolSideUsd) {
111
151
  return off(`${basedOn}: lowest pool SOL-side depth ${minDepth.toFixed(0)} USD, below the minimum of ${guards.minPoolSolSideUsd} USD`);
112
152
  }
113
- const prices = ys.map((s) => s.a402Usd);
153
+ const prices = ys.map((s) => s.tokenUsd);
114
154
  const ratio = Math.max(...prices) / Math.min(...prices);
115
- if (ratio > guards.maxDailyRangeRatio) {
155
+ if (!Number.isFinite(ratio) || ratio > guards.maxDailyRangeRatio) {
116
156
  return off(`${basedOn}: max/min price ratio ${ratio.toFixed(2)}, above the limit of ${guards.maxDailyRangeRatio}`);
117
157
  }
118
158
  return {
119
- status: 'on', date, basedOn, a402Usd: median(prices), samples: ys.length,
159
+ status: 'on', date, basedOn, tokenUsd: median(prices), samples: ys.length,
120
160
  method: `median of ${ys.length} hourly samples on ${basedOn} (UTC) (lowest depth ${minDepth.toFixed(0)} USD, max/min ${ratio.toFixed(2)})`,
121
161
  };
122
162
  }
123
- /** A402 로 낼 금액 (원 단위). 0.02 USD × (1 − 30%) 를 고정 환율로 나누고 올림 */
124
- export function a402Amount(rate, decimals = 6) {
125
- const usd = (Number(PRICE_USDC_BASE_UNITS) / 1e6) * (1 - A402_DISCOUNT_BPS / 10_000);
126
- return BigInt(Math.ceil((usd / rate.a402Usd) * 10 ** decimals));
163
+ const U64_MAX = (1n << 64n) - 1n;
164
+ /**
165
+ * Token amount to pay (base units): priceUsd × (1 − discount) ÷ fixed rate, rounded up.
166
+ * Throws if the rate is 0, negative, infinite or NaN, or if the result exceeds u64 (so that request does not offer token payment)
167
+ */
168
+ export function tokenAmountFor(priceUsd, discountPercent, rate, decimals = 6) {
169
+ if (!Number.isFinite(rate.tokenUsd) || !(rate.tokenUsd > 0))
170
+ throw new Error('invalid token rate');
171
+ const usd = priceUsd * (1 - discountPercent / 100);
172
+ const units = Math.ceil((usd / rate.tokenUsd) * 10 ** decimals);
173
+ if (!Number.isFinite(units) || units <= 0)
174
+ throw new Error('token amount out of range');
175
+ const amount = BigInt(units);
176
+ if (amount > U64_MAX)
177
+ throw new Error('token amount out of range');
178
+ return amount;
179
+ }
180
+ /** Token amount (base units) at the default price (0.02 USD), no discount */
181
+ export function tokenAmount(rate, decimals = 6) {
182
+ return tokenAmountFor(Number(PRICE_USDC_BASE_UNITS) / 1e6, TOKEN_DISCOUNT_BPS / 100, rate, decimals);
127
183
  }
@@ -1,4 +1,4 @@
1
- // Node 전용 환율 저장소: JSON 파일 하나 (기록은 최근 3일치만 유지). Workers 에서는 쓰지 말 것 (node:fs)
1
+ // Node-only rate store: a single JSON file (keeps only the last 3 days of samples). Do not use on Workers (node:fs)
2
2
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
3
  import { dirname } from 'node:path';
4
4
  export function fileRateStore(path, keepDays = 3) {
@@ -11,7 +11,7 @@ export function fileRateStore(path, keepDays = 3) {
11
11
  mkdirSync(dirname(path), { recursive: true });
12
12
  const tmp = `${path}.tmp`;
13
13
  writeFileSync(tmp, JSON.stringify(s));
14
- renameSync(tmp, path); // 쓰다 끊겨도 원본이 깨지지 않게
14
+ renameSync(tmp, path); // so the original is not corrupted if writing is interrupted
15
15
  };
16
16
  return {
17
17
  async addSample(x) {
package/dist/rates.d.ts CHANGED
@@ -1,17 +1,17 @@
1
- import { type DailyRate, type PriceSample, type RateGuards } from './pricing.js';
1
+ import { type DailyRate, type PoolTarget, type PriceSample, type RateGuards } from './pricing.js';
2
2
  import type { AccountFetcher } from './chain.js';
3
3
  export interface RateStore {
4
4
  addSample(s: PriceSample): Promise<void>;
5
- /** UTC 날짜(YYYY-MM-DD) 하루치 기록 */
5
+ /** Samples for one UTC date (YYYY-MM-DD) */
6
6
  samples(day: string): Promise<PriceSample[]>;
7
7
  getRate(date: string): Promise<DailyRate | null>;
8
8
  putRate(r: DailyRate): Promise<void>;
9
9
  }
10
10
  export declare function memoryRateStore(): RateStore;
11
11
  export interface RateBook {
12
- /** 기록 하나 남기기 (매시간 cron 등에서). 오라클 품질 기준 밖이면 예외 — 기록하지 않음 */
12
+ /** Records one sample (e.g. from an hourly cron). Throws if outside the oracle quality bounds; nothing is recorded */
13
13
  record(): Promise<PriceSample>;
14
- /** 오늘(UTC) 고정 환율. 처음 물을 때 전날 기록으로 계산해 저장 */
14
+ /** Today's (UTC) fixed rate. Computed from the previous day's samples on first request and stored */
15
15
  today(): Promise<DailyRate>;
16
16
  }
17
17
  export declare function createRateBook(o: {
@@ -19,8 +19,5 @@ export declare function createRateBook(o: {
19
19
  fetcher?: AccountFetcher;
20
20
  guards?: RateGuards;
21
21
  now?: () => Date;
22
+ target?: PoolTarget;
22
23
  }): RateBook;
23
- /** A402 로 낼 금액 (원 단위): priceUsd × (1 − 할인) ÷ 고정 환율, 올림 */
24
- export declare function a402AmountFor(priceUsd: number, discountPercent: number, rate: Extract<DailyRate, {
25
- status: 'on';
26
- }>, decimals?: number): bigint;
package/dist/rates.js CHANGED
@@ -1,6 +1,7 @@
1
- // A402 환율: 매시간 기록 → 전날 기록의 중앙값으로 하루 고정 (안전장치에 걸리면 그날 A402 끔).
2
- // 저장소는 인터페이스 — 메모리(기본·테스트), 파일(Node: rates-file.ts), Durable Object(Workers 예제) 등
3
- import { DEFAULT_GUARDS, fixRate, samplePrice } from './pricing.js';
1
+ // Payment token (PREQ) rate: sampled hourly, then fixed for the day at the median of the previous day's samples (if a guard trips, token payments are off that day).
2
+ // Pool and mint addresses are read from preq.ts only (PoolTarget default). A402 (v1) is deprecated: only when passed explicitly (with a warning).
3
+ // The store is an interface: memory (default, tests), file (Node: rates-file.ts), Durable Object (Workers example), etc.
4
+ import { DEFAULT_GUARDS, fixRate, PREQ_POOL_TARGET, samplePrice } from './pricing.js';
4
5
  export function memoryRateStore() {
5
6
  const samples = [];
6
7
  const rates = new Map();
@@ -15,11 +16,12 @@ const prevDay = (d) => new Date(Date.parse(`${d}T00:00:00Z`) - 86_400_000).toISO
15
16
  export function createRateBook(o) {
16
17
  const now = o.now ?? (() => new Date());
17
18
  const guards = o.guards ?? DEFAULT_GUARDS;
19
+ const target = o.target ?? PREQ_POOL_TARGET;
18
20
  return {
19
21
  async record() {
20
22
  if (!o.fetcher)
21
23
  throw new Error('rate book: no account fetcher configured');
22
- const s = await samplePrice(o.fetcher, now, guards);
24
+ const s = await samplePrice(o.fetcher, now, guards, target);
23
25
  await o.store.addSample(s);
24
26
  return s;
25
27
  },
@@ -28,14 +30,11 @@ export function createRateBook(o) {
28
30
  const cached = await o.store.getRate(date);
29
31
  if (cached)
30
32
  return cached;
31
- const r = fixRate(date, await o.store.samples(prevDay(date)), guards);
33
+ // Samples of other tokens (e.g. old A402 samples without symbol) are not mixed in
34
+ const samples = (await o.store.samples(prevDay(date))).filter((s) => (s.symbol ?? 'A402') === target.symbol);
35
+ const r = fixRate(date, samples, guards);
32
36
  await o.store.putRate(r);
33
37
  return r;
34
38
  },
35
39
  };
36
40
  }
37
- /** A402 로 낼 금액 (원 단위): priceUsd × (1 − 할인) ÷ 고정 환율, 올림 */
38
- export function a402AmountFor(priceUsd, discountPercent, rate, decimals = 6) {
39
- const usd = priceUsd * (1 - discountPercent / 100);
40
- return BigInt(Math.ceil((usd / rate.a402Usd) * 10 ** decimals));
41
- }