@agent402-dev/pay-server 0.1.0 → 0.3.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/gate.js CHANGED
@@ -1,30 +1,37 @@
1
- // @agent402-dev/pay-server 의 바깥 API: createPaymentGate(config).withPayment(handler)
2
- // 표준 Request → Response. Cloudflare Workers·Node 20+(fetch API)·Hono 등에서 그대로 씀.
1
+ // External API of @agent402-dev/pay-server: createPaymentGate(config).withPayment(handler)
2
+ // Standard Request → Response. Works as is on Cloudflare Workers, Node 20+ (fetch API), Hono, etc.
3
3
  //
4
- // 순서: 402 → (결제 헤더) 공식 서버로 조건 맞추기·verify → 핸들러 (제한 시간) → 성공(<400)일 때만 settle → 체인 재확인
5
- // 정산이 실패·결과 모름이면 체인에서 먼저 판정 (x402.ts settleVerified)
4
+ // Order: 402 → (payment header) match requirements and verify with the official server → handler (time limit) → settle only on success (<400) → recheck on-chain
5
+ // If settlement fails or its result is unknown, decide on-chain first (x402.ts settleVerified)
6
6
  //
7
- // 하지 않는 것: facilitator 운영, 자금 보관, 환전, 결제 대행. 서버는 수령 지갑 공개 주소만 받음 (개인키 받는 API 없음)
7
+ // Does not: operate a facilitator, hold funds, exchange currencies, or process payments for others. The server only takes the receiving wallet's public address (no API takes a private key)
8
8
  import { decodePaymentSignatureHeader, encodePaymentRequiredHeader } from '@x402/core/http';
9
9
  import { HTTPFacilitatorClient } from '@x402/core/server';
10
10
  import { ataOf } from './chain.js';
11
- import { a402AmountFor } from './rates.js';
11
+ import { tokenAmountFor } from './pricing.js';
12
+ import { RECEIPT_HEADER, sha256Hex, signReceipt } from './receipt.js';
13
+ import { A402_DEPRECATION_WARNING, PREQ_DECIMALS, PREQ_MAINNET_MINT, PREQ_TOKEN_PROGRAM } from './preq.js';
12
14
  import { buildRequirements, chooseFacilitator, memoryX402Ledger, paymentResponseHeader, settleVerified, verifyPaymentHeader, } from './x402.js';
13
15
  /**
14
- * 확인된 facilitator (2026-11-19 메인넷에서 verify·settle 로 확인한 사실 — docs: README "Facilitators").
15
- * 정책·상태는 바뀔 수 있으므로 기본값일 뿐, 설정으로 덮어쓸 수 있음
16
+ * Facilitator defaults. Policies and status can change, so these are only defaults and can be overridden in config.
17
+ * - USDC: confirmed with mainnet verify and settle on 2026-11-19 (PayAI, Dexter)
18
+ * - A402 (v1, deprecated): record of a check on PayAI on 2026-11-19
19
+ * - PREQ: listed for PayAI (no asset restriction for Solana exact in /supported). Verified and settled in a local mainnet-fork rehearsal on 2026-11-22; not yet checked on a hosted facilitator
16
20
  */
17
21
  export const KNOWN_FACILITATORS = {
18
- payai: { name: 'payai', url: 'https://facilitator.payai.network', assets: ['USDC', 'A402'] },
22
+ payai: { name: 'payai', url: 'https://facilitator.payai.network', assets: ['USDC', 'PREQ', 'A402'] },
19
23
  dexter: { name: 'dexter', url: 'https://x402.dexter.cash', assets: ['USDC'] },
20
24
  };
21
25
  export const SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
22
26
  export const SOLANA_DEVNET = 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1';
23
27
  export const USDC_MAINNET = { symbol: 'USDC', mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', decimals: 6, tokenProgram: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' };
28
+ /** PREQ (Token-2022, 6 decimals). The mint is PREQ_MAINNET_MINT in preq.ts; if empty, createPaymentGate stops with an error */
29
+ export const PREQ_MAINNET = { symbol: 'PREQ', mint: PREQ_MAINNET_MINT, decimals: PREQ_DECIMALS, tokenProgram: PREQ_TOKEN_PROGRAM };
30
+ /** @deprecated A402 (v1) is deprecated. Use PREQ_MAINNET. Enabling it explicitly with config.a402 prints a warning */
24
31
  export const A402_MAINNET = { symbol: 'A402', mint: 'GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X', decimals: 6, tokenProgram: 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' };
25
32
  /**
26
- * verify 실패가 구매자 탓이 아니라 facilitator 쪽 문제인지 (수수료 대납 주소 = 트랜잭션 계정 0 의 잔액 부족 등).
27
- * 2026-11-19 실제 사례: `transaction_simulation_failed: Simulation failed: {"InsufficientFundsForRent":{"account_index":0}}`
33
+ * Whether a verify failure is a facilitator-side problem rather than the buyer's fault (e.g. the fee payer = transaction account 0 has too little balance).
34
+ * Real case on 2026-11-19: `transaction_simulation_failed: Simulation failed: {"InsufficientFundsForRent":{"account_index":0}}`
28
35
  */
29
36
  export function isFacilitatorSideFailure(reason, message) {
30
37
  const s = `${reason ?? ''} ${message ?? ''}`;
@@ -37,6 +44,22 @@ export function isFacilitatorSideFailure(reason, message) {
37
44
  const json = (status, body, headers = {}) => new Response(JSON.stringify(body, null, 2), { status, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...headers } });
38
45
  const NOT_CHARGED = 'No payment was taken.';
39
46
  export function createPaymentGate(c) {
47
+ // Check token payment settings: stop if the PREQ mint is empty; A402 (v1) only when enabled explicitly, with a warning
48
+ if (c.preq) {
49
+ if (c.preq.asset.symbol !== 'PREQ')
50
+ throw new Error(`config.preq.asset.symbol must be PREQ (got ${c.preq.asset.symbol})`);
51
+ if (!c.preq.asset.mint) {
52
+ throw new Error('PREQ mint is not set: PREQ payments cannot be enabled yet. Fill PREQ_MAINNET_MINT in @agent402-dev/pay-server src/preq.ts after the PREQ launch, or pass your own asset (e.g. a devnet mint).');
53
+ }
54
+ }
55
+ if (c.a402) {
56
+ if (c.a402.asset.symbol !== 'A402')
57
+ throw new Error(`config.a402.asset.symbol must be A402 (got ${c.a402.asset.symbol})`);
58
+ (c.warn ?? console.warn)(A402_DEPRECATION_WARNING);
59
+ }
60
+ if (c.preq && c.a402 && c.preq.asset.mint === c.a402.asset.mint)
61
+ throw new Error('config.preq and config.a402 use the same mint');
62
+ const tokens = [c.preq, c.a402].filter((t) => !!t);
40
63
  const now = c.now ?? (() => Date.now());
41
64
  const ledger = c.ledger ?? memoryX402Ledger();
42
65
  const named = c.facilitators.map((f) => ({
@@ -47,12 +70,12 @@ export function createPaymentGate(c) {
47
70
  const cooldown = new Map();
48
71
  const cfgFor = (fs) => ({ network: c.network, payTo: c.payTo, facilitators: fs, maxTimeoutSeconds: c.maxTimeoutSeconds ?? 60 });
49
72
  const allCfg = cfgFor(named);
50
- // ---- 수령 토큰 계정 확인 (캐시) ----
73
+ // ---- Receiving token account check (cached) ----
51
74
  let receiving = null;
52
75
  async function checkReceivingAccounts() {
53
76
  if (receiving && now() - receiving.at < (c.receivingCheckTtlMs ?? 600_000))
54
77
  return receiving.list;
55
- const assets = [c.usdc, ...(c.a402 ? [c.a402.asset] : [])];
78
+ const assets = [c.usdc, ...tokens.map((t) => t.asset)];
56
79
  const atas = await Promise.all(assets.map((a) => ataOf(c.payTo, a.mint, a.tokenProgram)));
57
80
  const { accounts } = await c.chain.accounts(atas);
58
81
  const list = assets.map((a, i) => ({ asset: a.symbol, mint: a.mint, tokenAccount: atas[i], exists: !!accounts[i] && accounts[i].owner === a.tokenProgram }));
@@ -70,7 +93,7 @@ export function createPaymentGate(c) {
70
93
  try {
71
94
  recv = await checkReceivingAccounts();
72
95
  }
73
- catch { /* 확인 실패 → 막지 않고 진행 (체인 재확인이 따로 있음) */ }
96
+ catch { /* check failed → continue without blocking (there is a separate on-chain recheck) */ }
74
97
  const missing = (sym) => recv.find((r) => r.asset === sym && !r.exists);
75
98
  const offers = [];
76
99
  // USDC
@@ -78,26 +101,33 @@ export function createPaymentGate(c) {
78
101
  notOffered.push({ asset: 'USDC', reason: `receiving token account ${missing('USDC').tokenAccount} does not exist` });
79
102
  else
80
103
  offers.push({ asset: c.usdc, amount: BigInt(Math.round(c.priceUsd * 10 ** c.usdc.decimals)) });
81
- // A402
82
- if (c.a402) {
83
- if (!fac.assets.includes('A402')) {
84
- notOffered.push({ asset: 'A402', reason: `facilitator ${fac.name} does not accept A402` });
104
+ // Tokens (PREQ, and A402 (v1) only when enabled explicitly)
105
+ for (const t of tokens) {
106
+ const sym = t.asset.symbol;
107
+ if (!fac.assets.includes(sym)) {
108
+ notOffered.push({ asset: sym, reason: `facilitator ${fac.name} does not accept ${sym}` });
85
109
  }
86
- else if (missing('A402')) {
87
- notOffered.push({ asset: 'A402', reason: `receiving token account ${missing('A402').tokenAccount} does not exist` });
110
+ else if (missing(sym)) {
111
+ notOffered.push({ asset: sym, reason: `receiving token account ${missing(sym).tokenAccount} does not exist` });
88
112
  }
89
113
  else {
90
- const rate = await c.a402.rate().catch(() => null);
114
+ const rate = await t.rate().catch(() => null);
91
115
  if (!rate)
92
- notOffered.push({ asset: 'A402', reason: 'A402 rate unavailable' });
116
+ notOffered.push({ asset: sym, reason: `${sym} rate unavailable` });
93
117
  else if (rate.status === 'off')
94
- notOffered.push({ asset: 'A402', reason: rate.reason });
118
+ notOffered.push({ asset: sym, reason: rate.reason });
95
119
  else {
96
- offers.push({
97
- asset: c.a402.asset,
98
- amount: a402AmountFor(c.priceUsd, c.a402.discountPercent, rate, c.a402.asset.decimals),
99
- rate: { date: rate.date, a402Usd: rate.a402Usd, method: rate.method, discountPercent: c.a402.discountPercent },
100
- });
120
+ let amount = null;
121
+ try {
122
+ amount = tokenAmountFor(c.priceUsd, t.discountPercent ?? 0, rate, t.asset.decimals);
123
+ }
124
+ catch {
125
+ amount = null;
126
+ }
127
+ if (amount === null)
128
+ notOffered.push({ asset: sym, reason: `${sym} rate out of range` });
129
+ else
130
+ offers.push({ asset: t.asset, amount, rate: { date: rate.date, tokenUsd: rate.tokenUsd, method: rate.method, discountPercent: t.discountPercent ?? 0 } });
101
131
  }
102
132
  }
103
133
  }
@@ -139,11 +169,11 @@ export function createPaymentGate(c) {
139
169
  cfg: allCfg, ledger,
140
170
  loadTx: (s) => c.chain.loadTx(s),
141
171
  recentSignatures: (a, n) => c.chain.recentSignatures(a, n),
142
- tokenProgramOf: (mint) => (mint === c.a402?.asset.mint ? c.a402.asset.tokenProgram : c.usdc.tokenProgram),
172
+ tokenProgramOf: (mint) => tokens.find((t) => t.asset.mint === mint)?.asset.tokenProgram ?? c.usdc.tokenProgram,
143
173
  nowMs: now(),
144
174
  confirmDelaysMs: c.confirmDelaysMs,
145
175
  };
146
- // 1) 조건 맞추기·verify (돈은 아직 안 나감)
176
+ // 1) Match requirements and verify (no money moves yet)
147
177
  const v = await verifyPaymentHeader(header, url.pathname, q.accepts, d);
148
178
  if (v.kind === 'conflict')
149
179
  return json(409, { error: 'payment_already_used', state: v.state, message: v.state === 'fulfilled' ? 'This payment has already been used.' : 'This payment is being processed.' });
@@ -151,7 +181,7 @@ export function createPaymentGate(c) {
151
181
  return json(503, { error: 'payment_unavailable', message: `Could not reach the facilitator. ${NOT_CHARGED}` });
152
182
  if (v.kind === 'payment_required') {
153
183
  if (isFacilitatorSideFailure(v.reason, v.message)) {
154
- // 구매자 탓이 아님 → 그 facilitator 를 잠시 빼고, 다음 facilitator 의 새 조건으로 다시 결제하도록 안내
184
+ // Not the buyer's fault → drop that facilitator for a while and ask the buyer to pay again with the next facilitator's new requirements
155
185
  const feePayer = (() => { try {
156
186
  return decodePaymentSignatureHeader(header).accepted?.extra?.feePayer;
157
187
  }
@@ -168,8 +198,10 @@ export function createPaymentGate(c) {
168
198
  }
169
199
  return paymentRequired(resourceUrl, q, { reason: v.reason, message: `Payment was not accepted (${v.reason}). ${NOT_CHARGED}` }, v.reason);
170
200
  }
171
- // 2) 핸들러 (제한 시간). 실패·시간 초과·4xx/5xx 응답이면 정산하지 않음
201
+ // 2) Handler (time limit). No settlement on failure, timeout, or a 4xx/5xx response
172
202
  const payment = v.payment;
203
+ // Copy of the request for the receipt's request body hash (the handler may read the original body)
204
+ const reqCopy = c.receipts && req.body ? req.clone() : null;
173
205
  const info = { asset: payment.accepted.asset, amount: payment.accepted.amount, payTo: payment.accepted.payTo, network: payment.accepted.network };
174
206
  let res;
175
207
  let timer;
@@ -194,7 +226,7 @@ export function createPaymentGate(c) {
194
226
  h.set('x-payment-status', 'not-settled');
195
227
  return new Response(res.body, { status: res.status, headers: h });
196
228
  }
197
- // 3) 정산 (+ 실패·결과 모름이면 체인 판정)
229
+ // 3) Settle (+ decide on-chain if it fails or the result is unknown)
198
230
  const s = await settleVerified(payment, { ...d, nowMs: now() });
199
231
  if (s.kind === 'payment_required')
200
232
  return paymentRequired(resourceUrl, q, { reason: s.reason, message: `Payment was not settled (${s.reason}). ${NOT_CHARGED}` }, s.reason);
@@ -205,7 +237,24 @@ export function createPaymentGate(c) {
205
237
  h.set('payment-response', paymentResponseHeader(s.settlement));
206
238
  h.set('x-payment-confirmation', s.confirmation);
207
239
  h.set('access-control-expose-headers', 'PAYMENT-RESPONSE, X-Payment-Confirmation');
208
- return new Response(res.body, { status: res.status, headers: h });
240
+ if (!c.receipts)
241
+ return new Response(res.body, { status: res.status, headers: h });
242
+ const body = await res.arrayBuffer();
243
+ try {
244
+ const reqBody = reqCopy ? await reqCopy.arrayBuffer() : null;
245
+ const token = await signReceipt(c.receipts.signer, {
246
+ issuedAt: new Date(now()).toISOString(),
247
+ request: { method: req.method, path: `${url.pathname}${url.search}`, bodySha256: reqBody && reqBody.byteLength ? await sha256Hex(reqBody) : null },
248
+ response: { status: res.status, bodySha256: await sha256Hex(body) },
249
+ payment: { network: info.network, asset: info.asset, amount: info.amount, payTo: info.payTo, transaction: s.settlement.transaction || null },
250
+ });
251
+ h.set(RECEIPT_HEADER, token);
252
+ h.set('access-control-expose-headers', 'PAYMENT-RESPONSE, X-Payment-Confirmation, X-Agent402-Receipt');
253
+ }
254
+ catch {
255
+ // Receipts are optional: the paid resource is still delivered without one
256
+ }
257
+ return new Response(body, { status: res.status, headers: h });
209
258
  };
210
259
  }
211
260
  return { withPayment, quote, checkReceivingAccounts };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
- export { createPaymentGate, isFacilitatorSideFailure, KNOWN_FACILITATORS, SOLANA_MAINNET, SOLANA_DEVNET, USDC_MAINNET, A402_MAINNET, type AssetSymbol, type FacilitatorSpec, type GateConfig, type PaymentGate, type PaymentInfo, type ReceivingAccount, } from './gate.js';
1
+ export { createPaymentGate, isFacilitatorSideFailure, KNOWN_FACILITATORS, SOLANA_MAINNET, SOLANA_DEVNET, USDC_MAINNET, PREQ_MAINNET, A402_MAINNET, type AssetSymbol, type FacilitatorSpec, type GateConfig, type PaymentGate, type PaymentInfo, type ReceivingAccount, type TokenPayment, } from './gate.js';
2
+ export { PREQ_MAINNET_MINT, PREQ_MAINNET_POOL, A402_DEPRECATION_WARNING } from './preq.js';
2
3
  export { rpcChain, receivedBy, type ChainReader, type ChainTx, type AccountFetcher } from './chain.js';
3
- export { createRateBook, memoryRateStore, a402AmountFor, type RateBook, type RateStore } from './rates.js';
4
- export { DEFAULT_GUARDS, fixRate, samplePrice, type DailyRate, type PriceSample, type RateGuards } from './pricing.js';
4
+ export { createRateBook, memoryRateStore, type RateBook, type RateStore } from './rates.js';
5
+ export { DEFAULT_GUARDS, fixRate, samplePrice, tokenAmountFor, PREQ_POOL_TARGET, A402_POOL_TARGET, type DailyRate, type PoolTarget, type PriceSample, type RateGuards, } from './pricing.js';
6
+ export { receiptSignerFromBytes, signReceipt, RECEIPT_HEADER, type Receipt, type ReceiptSigner } from './receipt.js';
5
7
  export { memoryX402Ledger, ledgerClaim, SETTLE_UNKNOWN_EXPIRY_MS, type X402Ledger, type LedgerEntry, type Asset } from './x402.js';
package/dist/index.js CHANGED
@@ -1,6 +1,9 @@
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';
8
+ export { receiptSignerFromBytes, signReceipt, RECEIPT_HEADER } from './receipt.js';
6
9
  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;