@agent402-dev/pay-server 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,212 @@
1
+ // @agent402-dev/pay-server 의 바깥 API: createPaymentGate(config).withPayment(handler)
2
+ // 표준 Request → Response. Cloudflare Workers·Node 20+(fetch API)·Hono 등에서 그대로 씀.
3
+ //
4
+ // 순서: 402 → (결제 헤더) 공식 서버로 조건 맞추기·verify → 핸들러 (제한 시간) → 성공(<400)일 때만 settle → 체인 재확인
5
+ // 정산이 실패·결과 모름이면 체인에서 먼저 판정 (x402.ts settleVerified)
6
+ //
7
+ // 하지 않는 것: facilitator 운영, 자금 보관, 환전, 결제 대행. 서버는 수령 지갑 공개 주소만 받음 (개인키 받는 API 없음)
8
+ import { decodePaymentSignatureHeader, encodePaymentRequiredHeader } from '@x402/core/http';
9
+ import { HTTPFacilitatorClient } from '@x402/core/server';
10
+ import { ataOf } from './chain.js';
11
+ import { a402AmountFor } from './rates.js';
12
+ import { buildRequirements, chooseFacilitator, memoryX402Ledger, paymentResponseHeader, settleVerified, verifyPaymentHeader, } from './x402.js';
13
+ /**
14
+ * 확인된 facilitator (2026-11-19 메인넷에서 verify·settle 로 확인한 사실 — docs: README "Facilitators").
15
+ * 정책·상태는 바뀔 수 있으므로 기본값일 뿐, 설정으로 덮어쓸 수 있음
16
+ */
17
+ export const KNOWN_FACILITATORS = {
18
+ payai: { name: 'payai', url: 'https://facilitator.payai.network', assets: ['USDC', 'A402'] },
19
+ dexter: { name: 'dexter', url: 'https://x402.dexter.cash', assets: ['USDC'] },
20
+ };
21
+ export const SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
22
+ export const SOLANA_DEVNET = 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1';
23
+ export const USDC_MAINNET = { symbol: 'USDC', mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', decimals: 6, tokenProgram: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' };
24
+ export const A402_MAINNET = { symbol: 'A402', mint: 'GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X', decimals: 6, tokenProgram: 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' };
25
+ /**
26
+ * verify 실패가 구매자 탓이 아니라 facilitator 쪽 문제인지 (수수료 대납 주소 = 트랜잭션 계정 0 의 잔액 부족 등).
27
+ * 2026-11-19 실제 사례: `transaction_simulation_failed: Simulation failed: {"InsufficientFundsForRent":{"account_index":0}}`
28
+ */
29
+ export function isFacilitatorSideFailure(reason, message) {
30
+ const s = `${reason ?? ''} ${message ?? ''}`;
31
+ if (/InsufficientFundsForRent[^}]*account_index"?\s*:\s*0\b/.test(s))
32
+ return true;
33
+ if (/fee[ _-]?payer/i.test(s) && /(insufficient|balance|funds|rent)/i.test(s))
34
+ return true;
35
+ return false;
36
+ }
37
+ 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
+ const NOT_CHARGED = 'No payment was taken.';
39
+ export function createPaymentGate(c) {
40
+ const now = c.now ?? (() => Date.now());
41
+ const ledger = c.ledger ?? memoryX402Ledger();
42
+ const named = c.facilitators.map((f) => ({
43
+ name: f.name,
44
+ client: f.client ?? new HTTPFacilitatorClient({ url: f.url }),
45
+ assets: f.assets,
46
+ }));
47
+ const cooldown = new Map();
48
+ const cfgFor = (fs) => ({ network: c.network, payTo: c.payTo, facilitators: fs, maxTimeoutSeconds: c.maxTimeoutSeconds ?? 60 });
49
+ const allCfg = cfgFor(named);
50
+ // ---- 수령 토큰 계정 확인 (캐시) ----
51
+ let receiving = null;
52
+ async function checkReceivingAccounts() {
53
+ if (receiving && now() - receiving.at < (c.receivingCheckTtlMs ?? 600_000))
54
+ return receiving.list;
55
+ const assets = [c.usdc, ...(c.a402 ? [c.a402.asset] : [])];
56
+ const atas = await Promise.all(assets.map((a) => ataOf(c.payTo, a.mint, a.tokenProgram)));
57
+ const { accounts } = await c.chain.accounts(atas);
58
+ const list = assets.map((a, i) => ({ asset: a.symbol, mint: a.mint, tokenAccount: atas[i], exists: !!accounts[i] && accounts[i].owner === a.tokenProgram }));
59
+ receiving = { at: now(), list };
60
+ return list;
61
+ }
62
+ async function quote(resourceUrl) {
63
+ const healthy = named.filter((f) => (cooldown.get(f.name) ?? 0) <= now());
64
+ const chosen = await chooseFacilitator(cfgFor(healthy), now());
65
+ if (!chosen)
66
+ return null;
67
+ const fac = named.find((f) => f.name === chosen.facilitator.name);
68
+ const notOffered = [];
69
+ let recv = [];
70
+ try {
71
+ recv = await checkReceivingAccounts();
72
+ }
73
+ catch { /* 확인 실패 → 막지 않고 진행 (체인 재확인이 따로 있음) */ }
74
+ const missing = (sym) => recv.find((r) => r.asset === sym && !r.exists);
75
+ const offers = [];
76
+ // USDC
77
+ if (missing('USDC'))
78
+ notOffered.push({ asset: 'USDC', reason: `receiving token account ${missing('USDC').tokenAccount} does not exist` });
79
+ else
80
+ 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` });
85
+ }
86
+ else if (missing('A402')) {
87
+ notOffered.push({ asset: 'A402', reason: `receiving token account ${missing('A402').tokenAccount} does not exist` });
88
+ }
89
+ else {
90
+ const rate = await c.a402.rate().catch(() => null);
91
+ if (!rate)
92
+ notOffered.push({ asset: 'A402', reason: 'A402 rate unavailable' });
93
+ else if (rate.status === 'off')
94
+ notOffered.push({ asset: 'A402', reason: rate.reason });
95
+ 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
+ });
101
+ }
102
+ }
103
+ }
104
+ if (!fac.assets.includes('USDC')) {
105
+ const i = offers.findIndex((o) => o.asset.symbol === 'USDC');
106
+ if (i >= 0) {
107
+ offers.splice(i, 1);
108
+ notOffered.push({ asset: 'USDC', reason: `facilitator ${fac.name} does not accept USDC` });
109
+ }
110
+ }
111
+ const accepts = offers.length ? await buildRequirements(allCfg, offers, chosen) : [];
112
+ return { accepts, notOffered, facilitator: fac.name };
113
+ }
114
+ function paymentRequired(resourceUrl, q, extra = {}, error) {
115
+ const pr = {
116
+ x402Version: 2,
117
+ ...(error ? { error } : {}),
118
+ resource: { url: resourceUrl, description: c.resource?.description ?? '', mimeType: c.resource?.mimeType ?? 'application/json', ...(c.resource?.serviceName ? { serviceName: c.resource.serviceName } : {}) },
119
+ accepts: q.accepts,
120
+ };
121
+ return json(402, { ...pr, ...(q.notOffered.length ? { notOffered: q.notOffered } : {}), ...extra }, {
122
+ 'payment-required': encodePaymentRequiredHeader(pr),
123
+ 'access-control-expose-headers': 'PAYMENT-REQUIRED, PAYMENT-RESPONSE',
124
+ });
125
+ }
126
+ function withPayment(handler) {
127
+ return async (req) => {
128
+ const url = new URL(req.url);
129
+ const resourceUrl = `${url.origin}${url.pathname}`;
130
+ const q = await quote(resourceUrl);
131
+ if (!q)
132
+ return json(503, { error: 'payment_unavailable', message: `No facilitator is reachable right now. ${NOT_CHARGED}` });
133
+ if (!q.accepts.length)
134
+ return json(503, { error: 'payment_unavailable', message: `No payment option can be offered right now. ${NOT_CHARGED}`, notOffered: q.notOffered });
135
+ const header = req.headers.get('payment-signature');
136
+ if (!header)
137
+ return paymentRequired(resourceUrl, q, {}, 'Payment required');
138
+ const d = {
139
+ cfg: allCfg, ledger,
140
+ loadTx: (s) => c.chain.loadTx(s),
141
+ recentSignatures: (a, n) => c.chain.recentSignatures(a, n),
142
+ tokenProgramOf: (mint) => (mint === c.a402?.asset.mint ? c.a402.asset.tokenProgram : c.usdc.tokenProgram),
143
+ nowMs: now(),
144
+ confirmDelaysMs: c.confirmDelaysMs,
145
+ };
146
+ // 1) 조건 맞추기·verify (돈은 아직 안 나감)
147
+ const v = await verifyPaymentHeader(header, url.pathname, q.accepts, d);
148
+ if (v.kind === 'conflict')
149
+ 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.' });
150
+ if (v.kind === 'unavailable')
151
+ return json(503, { error: 'payment_unavailable', message: `Could not reach the facilitator. ${NOT_CHARGED}` });
152
+ if (v.kind === 'payment_required') {
153
+ if (isFacilitatorSideFailure(v.reason, v.message)) {
154
+ // 구매자 탓이 아님 → 그 facilitator 를 잠시 빼고, 다음 facilitator 의 새 조건으로 다시 결제하도록 안내
155
+ const feePayer = (() => { try {
156
+ return decodePaymentSignatureHeader(header).accepted?.extra?.feePayer;
157
+ }
158
+ catch {
159
+ return undefined;
160
+ } })();
161
+ const failed = (await Promise.all(named.map(async (f) => ((await chooseFacilitator(cfgFor([f]), now()))?.feePayer === feePayer ? f.name : null)))).find(Boolean);
162
+ if (failed)
163
+ cooldown.set(failed, now() + (c.facilitatorCooldownMs ?? 300_000));
164
+ const q2 = await quote(resourceUrl);
165
+ if (!q2 || !q2.accepts.length)
166
+ return json(503, { error: 'payment_unavailable', reason: 'facilitator_unavailable', message: `The facilitator could not process this payment and no other facilitator is available. ${NOT_CHARGED}` });
167
+ return paymentRequired(resourceUrl, q2, { reason: 'facilitator_unavailable', message: `The facilitator could not process this payment (${v.reason}). ${NOT_CHARGED} Please pay again with these new requirements.` }, 'facilitator_unavailable');
168
+ }
169
+ return paymentRequired(resourceUrl, q, { reason: v.reason, message: `Payment was not accepted (${v.reason}). ${NOT_CHARGED}` }, v.reason);
170
+ }
171
+ // 2) 핸들러 (제한 시간). 실패·시간 초과·4xx/5xx 응답이면 정산하지 않음
172
+ const payment = v.payment;
173
+ const info = { asset: payment.accepted.asset, amount: payment.accepted.amount, payTo: payment.accepted.payTo, network: payment.accepted.network };
174
+ let res;
175
+ let timer;
176
+ try {
177
+ res = await Promise.race([
178
+ handler(req, info),
179
+ new Promise((_, rej) => { timer = setTimeout(() => rej(new Error('__handler_timeout__')), c.handlerTimeoutMs ?? 40_000); }),
180
+ ]);
181
+ }
182
+ catch (e) {
183
+ await ledger.release(payment.key);
184
+ const timeout = e.message === '__handler_timeout__';
185
+ return json(timeout ? 504 : 502, { error: timeout ? 'handler_timeout' : 'handler_failed', message: `The resource could not be produced. The payment was not settled. ${NOT_CHARGED}` });
186
+ }
187
+ finally {
188
+ if (timer)
189
+ clearTimeout(timer);
190
+ }
191
+ if (res.status >= 400) {
192
+ await ledger.release(payment.key);
193
+ const h = new Headers(res.headers);
194
+ h.set('x-payment-status', 'not-settled');
195
+ return new Response(res.body, { status: res.status, headers: h });
196
+ }
197
+ // 3) 정산 (+ 실패·결과 모름이면 체인 판정)
198
+ const s = await settleVerified(payment, { ...d, nowMs: now() });
199
+ if (s.kind === 'payment_required')
200
+ return paymentRequired(resourceUrl, q, { reason: s.reason, message: `Payment was not settled (${s.reason}). ${NOT_CHARGED}` }, s.reason);
201
+ if (s.kind === 'unavailable')
202
+ return json(503, { error: 'settlement_pending', message: 'The settlement result is not known yet. Retry with the same PAYMENT-SIGNATURE shortly; it will be judged from the chain (if it settled you get the resource; if it never lands before it expires, no payment is taken).' });
203
+ await ledger.fulfill(payment.key, now());
204
+ const h = new Headers(res.headers);
205
+ h.set('payment-response', paymentResponseHeader(s.settlement));
206
+ h.set('x-payment-confirmation', s.confirmation);
207
+ h.set('access-control-expose-headers', 'PAYMENT-RESPONSE, X-Payment-Confirmation');
208
+ return new Response(res.body, { status: res.status, headers: h });
209
+ };
210
+ }
211
+ return { withPayment, quote, checkReceivingAccounts };
212
+ }
@@ -0,0 +1,5 @@
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';
2
+ 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';
5
+ export { memoryX402Ledger, ledgerClaim, SETTLE_UNKNOWN_EXPIRY_MS, type X402Ledger, type LedgerEntry, type Asset } from './x402.js';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ // @agent402-dev/pay-server — 공개 API
2
+ export { createPaymentGate, isFacilitatorSideFailure, KNOWN_FACILITATORS, SOLANA_MAINNET, SOLANA_DEVNET, USDC_MAINNET, A402_MAINNET, } from './gate.js';
3
+ 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 { memoryX402Ledger, ledgerClaim, SETTLE_UNKNOWN_EXPIRY_MS } from './x402.js';
@@ -0,0 +1,87 @@
1
+ import type { AccountFetcher } from './chain.js';
2
+ export declare function decodeDammV2PoolForRate(data: Uint8Array): {
3
+ tokenAMint: string;
4
+ tokenBMint: string;
5
+ tokenAVault: string;
6
+ tokenBVault: string;
7
+ /** sqrt_price (Q64.64, u128 LE) */
8
+ sqrtPrice: bigint;
9
+ };
10
+ export declare const A402_MAINNET_MINT = "GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X";
11
+ 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 목록에서 확인) */
15
+ export declare const PYTH_SOL_USD_FEED = "ef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d";
16
+ /** Pyth 푸시 오라클 프로그램과 receiver(계정 소유자) */
17
+ export declare const PYTH_PUSH_ORACLE = "pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT";
18
+ export declare const PYTH_RECEIVER = "rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ";
19
+ /** 샤드 0 의 SOL/USD 가격 계정 = PDA([u16 shard=0, feed_id], push oracle) — 아래 함수로 계산해 대조 */
20
+ export declare function pythPriceAccount(feedHex?: string, shard?: number): string;
21
+ export declare const PRICE_USDC_BASE_UNITS = 20000n;
22
+ export declare const A402_DISCOUNT_BPS = 3000;
23
+ /** 안전장치 기준 (제안값, 2026-11-19) */
24
+ export interface RateGuards {
25
+ /** 전날 기록 최소 개수 (24시간 중) */
26
+ minSamples: number;
27
+ /** 전날 모든 기록에서 풀 SOL 쪽 깊이(USD) 최소값 */
28
+ minPoolSolSideUsd: number;
29
+ /** 전날 기록의 최고가 / 최저가 최대 비율 */
30
+ maxDailyRangeRatio: number;
31
+ /** Pyth 신뢰구간 / 가격 최대 비율 (넘으면 그 기록을 버림) */
32
+ maxOracleConfRatio: number;
33
+ /** Pyth 갱신 시각이 기록 시각보다 최대 몇 초 전까지 허용 */
34
+ maxOracleAgeSec: number;
35
+ }
36
+ export declare const DEFAULT_GUARDS: RateGuards;
37
+ export interface PriceSample {
38
+ /** ISO 시각 */
39
+ at: string;
40
+ /** SOL per A402 */
41
+ a402Sol: number;
42
+ /** USD per SOL (Pyth) */
43
+ solUsd: number;
44
+ solUsdConf: number;
45
+ /** USD per A402 */
46
+ a402Usd: number;
47
+ /** 풀 SOL 금고 잔액 × SOL/USD */
48
+ poolSolSideUsd: number;
49
+ slot: number;
50
+ pythPublishTime: number;
51
+ }
52
+ export type DailyRate = {
53
+ status: 'on';
54
+ date: string;
55
+ basedOn: string;
56
+ a402Usd: number;
57
+ samples: number;
58
+ method: string;
59
+ } | {
60
+ status: 'off';
61
+ date: string;
62
+ basedOn: string;
63
+ reason: string;
64
+ samples: number;
65
+ };
66
+ /**
67
+ * DAMM v2 sqrt_price(Q64.64) → B per A 가격.
68
+ * price = (sqrt_price / 2^64)^2 × 10^(decimalsA − decimalsB)
69
+ */
70
+ export declare function dammV2Price(sqrtPrice: bigint, decimalsA: number, decimalsB: number): number;
71
+ /** Pyth PriceUpdateV2 계정 해석 (verification_level 이 Partial 이면 1바이트 더) */
72
+ export declare function decodePythPriceUpdate(data: Buffer): {
73
+ verification: string;
74
+ feedId: string;
75
+ price: number;
76
+ conf: number;
77
+ publishTime: number;
78
+ };
79
+ /** 풀·SOL 금고·Pyth 계정을 RPC 한 번으로 읽어 기록 하나. 오라클 품질이 기준 밖이면 예외 */
80
+ export declare function samplePrice(fetcher: AccountFetcher, now?: () => Date, guards?: RateGuards): Promise<PriceSample>;
81
+ export declare function median(xs: number[]): number;
82
+ /** date 에 쓸 고정 환율. 전날 기록으로 계산하고, 안전장치에 걸리면 off */
83
+ 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, {
86
+ status: 'on';
87
+ }>, decimals?: number): bigint;
@@ -0,0 +1,127 @@
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 만)
5
+ import { PublicKey } from '@solana/web3.js';
6
+ /** Meteora DAMM v2 풀 계정에서 환율에 필요한 부분만 (오프셋: cp-amm IDL, bytemuck — 점검 엔진의 해석과 같은 값) */
7
+ const DAMM_V2_POOL_SIZE = 1112;
8
+ const DAMM_V2_POOL_DISC = [241, 154, 109, 4, 17, 177, 109, 188];
9
+ export function decodeDammV2PoolForRate(data) {
10
+ const b = Buffer.from(data);
11
+ if (b.length !== DAMM_V2_POOL_SIZE || !DAMM_V2_POOL_DISC.every((x, i) => b[i] === x))
12
+ throw new Error('not a DAMM v2 pool account');
13
+ const key = (o) => new PublicKey(b.subarray(o, o + 32)).toBase58();
14
+ return {
15
+ tokenAMint: key(168), tokenBMint: key(200), tokenAVault: key(232), tokenBVault: key(264),
16
+ /** sqrt_price (Q64.64, u128 LE) */
17
+ sqrtPrice: (b.readBigUInt64LE(464) << 64n) | b.readBigUInt64LE(456),
18
+ };
19
+ }
20
+ export const A402_MAINNET_MINT = 'GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X';
21
+ 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 목록에서 확인) */
25
+ export const PYTH_SOL_USD_FEED = 'ef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d';
26
+ /** Pyth 푸시 오라클 프로그램과 receiver(계정 소유자) */
27
+ export const PYTH_PUSH_ORACLE = 'pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT';
28
+ export const PYTH_RECEIVER = 'rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ';
29
+ /** 샤드 0 의 SOL/USD 가격 계정 = PDA([u16 shard=0, feed_id], push oracle) — 아래 함수로 계산해 대조 */
30
+ export function pythPriceAccount(feedHex = PYTH_SOL_USD_FEED, shard = 0) {
31
+ const s = Buffer.alloc(2);
32
+ s.writeUInt16LE(shard);
33
+ return PublicKey.findProgramAddressSync([s, Buffer.from(feedHex, 'hex')], new PublicKey(PYTH_PUSH_ORACLE))[0].toBase58();
34
+ }
35
+ export const PRICE_USDC_BASE_UNITS = 20000n; // 0.02 USDC (소수 6자리)
36
+ export const A402_DISCOUNT_BPS = 3000; // 30%
37
+ export const DEFAULT_GUARDS = {
38
+ minSamples: 12,
39
+ minPoolSolSideUsd: 100,
40
+ maxDailyRangeRatio: 1.5,
41
+ maxOracleConfRatio: 0.01,
42
+ maxOracleAgeSec: 120,
43
+ };
44
+ /**
45
+ * DAMM v2 sqrt_price(Q64.64) → B per A 가격.
46
+ * price = (sqrt_price / 2^64)^2 × 10^(decimalsA − decimalsB)
47
+ */
48
+ export function dammV2Price(sqrtPrice, decimalsA, decimalsB) {
49
+ const s = Number(sqrtPrice) / 2 ** 64;
50
+ return s * s * 10 ** (decimalsA - decimalsB);
51
+ }
52
+ /** Pyth PriceUpdateV2 계정 해석 (verification_level 이 Partial 이면 1바이트 더) */
53
+ export function decodePythPriceUpdate(data) {
54
+ const tag = data[40];
55
+ let o = 41 + (tag === 0 ? 1 : 0);
56
+ const feedId = data.subarray(o, o + 32).toString('hex');
57
+ o += 32;
58
+ const price = data.readBigInt64LE(o);
59
+ const conf = data.readBigUInt64LE(o + 8);
60
+ const expo = data.readInt32LE(o + 16);
61
+ const publishTime = Number(data.readBigInt64LE(o + 20));
62
+ return { verification: tag === 1 ? 'full' : 'partial', feedId, price: Number(price) * 10 ** expo, conf: Number(conf) * 10 ** expo, publishTime };
63
+ }
64
+ /** 풀·SOL 금고·Pyth 계정을 RPC 한 번으로 읽어 기록 하나. 오라클 품질이 기준 밖이면 예외 */
65
+ export async function samplePrice(fetcher, now = () => new Date(), guards = DEFAULT_GUARDS) {
66
+ const pythAcc = pythPriceAccount();
67
+ const { slot, accounts } = await fetcher([A402_MAINNET_POOL, A402_POOL_SOL_VAULT, pythAcc]);
68
+ const [poolAcc, vaultAcc, pyth] = accounts;
69
+ if (!poolAcc || !vaultAcc || !pyth)
70
+ throw new Error('price accounts missing');
71
+ const pool = decodeDammV2PoolForRate(poolAcc.data);
72
+ if (pool.tokenAMint !== A402_MAINNET_MINT || pool.tokenBMint !== WSOL_MINT || pool.tokenBVault !== A402_POOL_SOL_VAULT) {
73
+ 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;
77
+ if (pyth.owner !== PYTH_RECEIVER)
78
+ throw new Error('pyth account owner mismatch');
79
+ const p = decodePythPriceUpdate(Buffer.from(pyth.data));
80
+ if (p.feedId !== PYTH_SOL_USD_FEED)
81
+ throw new Error('pyth feed mismatch');
82
+ if (p.verification !== 'full')
83
+ throw new Error('pyth update not fully verified');
84
+ const nowSec = Math.floor(now().getTime() / 1000);
85
+ if (nowSec - p.publishTime > guards.maxOracleAgeSec)
86
+ throw new Error('pyth price stale');
87
+ if (!(p.price > 0) || p.conf / p.price > guards.maxOracleConfRatio)
88
+ throw new Error('pyth confidence too wide');
89
+ if (!(a402Sol > 0))
90
+ throw new Error('non-positive pool price');
91
+ return {
92
+ at: now().toISOString(), a402Sol, solUsd: p.price, solUsdConf: p.conf, a402Usd: a402Sol * p.price,
93
+ poolSolSideUsd: solInVault * p.price, slot, pythPublishTime: p.publishTime,
94
+ };
95
+ }
96
+ export function median(xs) {
97
+ const s = [...xs].sort((a, b) => a - b);
98
+ const m = s.length >> 1;
99
+ return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
100
+ }
101
+ const prevDay = (d) => new Date(Date.parse(`${d}T00:00:00Z`) - 86_400_000).toISOString().slice(0, 10);
102
+ /** date 에 쓸 고정 환율. 전날 기록으로 계산하고, 안전장치에 걸리면 off */
103
+ export function fixRate(date, samples, guards = DEFAULT_GUARDS) {
104
+ const basedOn = prevDay(date);
105
+ const ys = samples.filter((s) => s.at.slice(0, 10) === basedOn);
106
+ 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));
110
+ if (minDepth < guards.minPoolSolSideUsd) {
111
+ return off(`${basedOn}: lowest pool SOL-side depth ${minDepth.toFixed(0)} USD, below the minimum of ${guards.minPoolSolSideUsd} USD`);
112
+ }
113
+ const prices = ys.map((s) => s.a402Usd);
114
+ const ratio = Math.max(...prices) / Math.min(...prices);
115
+ if (ratio > guards.maxDailyRangeRatio) {
116
+ return off(`${basedOn}: max/min price ratio ${ratio.toFixed(2)}, above the limit of ${guards.maxDailyRangeRatio}`);
117
+ }
118
+ return {
119
+ status: 'on', date, basedOn, a402Usd: median(prices), samples: ys.length,
120
+ method: `median of ${ys.length} hourly samples on ${basedOn} (UTC) (lowest depth ${minDepth.toFixed(0)} USD, max/min ${ratio.toFixed(2)})`,
121
+ };
122
+ }
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));
127
+ }
@@ -0,0 +1,2 @@
1
+ import type { RateStore } from './rates.js';
2
+ export declare function fileRateStore(path: string, keepDays?: number): RateStore;
@@ -0,0 +1,33 @@
1
+ // Node 전용 환율 저장소: JSON 파일 하나 (기록은 최근 3일치만 유지). Workers 에서는 쓰지 말 것 (node:fs)
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { dirname } from 'node:path';
4
+ export function fileRateStore(path, keepDays = 3) {
5
+ const read = () => {
6
+ if (!existsSync(path))
7
+ return { samples: [], rates: {} };
8
+ return JSON.parse(readFileSync(path, 'utf8'));
9
+ };
10
+ const write = (s) => {
11
+ mkdirSync(dirname(path), { recursive: true });
12
+ const tmp = `${path}.tmp`;
13
+ writeFileSync(tmp, JSON.stringify(s));
14
+ renameSync(tmp, path); // 쓰다 끊겨도 원본이 깨지지 않게
15
+ };
16
+ return {
17
+ async addSample(x) {
18
+ const s = read();
19
+ const cutoff = new Date(Date.parse(x.at) - keepDays * 86_400_000).toISOString();
20
+ s.samples = [...s.samples.filter((y) => y.at >= cutoff), x];
21
+ write(s);
22
+ },
23
+ async samples(day) { return read().samples.filter((x) => x.at.slice(0, 10) === day); },
24
+ async getRate(date) { return read().rates[date] ?? null; },
25
+ async putRate(r) {
26
+ const s = read();
27
+ s.rates[r.date] = r;
28
+ for (const d of Object.keys(s.rates).sort().slice(0, -keepDays))
29
+ delete s.rates[d];
30
+ write(s);
31
+ },
32
+ };
33
+ }
@@ -0,0 +1,26 @@
1
+ import { type DailyRate, type PriceSample, type RateGuards } from './pricing.js';
2
+ import type { AccountFetcher } from './chain.js';
3
+ export interface RateStore {
4
+ addSample(s: PriceSample): Promise<void>;
5
+ /** UTC 날짜(YYYY-MM-DD) 하루치 기록 */
6
+ samples(day: string): Promise<PriceSample[]>;
7
+ getRate(date: string): Promise<DailyRate | null>;
8
+ putRate(r: DailyRate): Promise<void>;
9
+ }
10
+ export declare function memoryRateStore(): RateStore;
11
+ export interface RateBook {
12
+ /** 기록 하나 남기기 (매시간 cron 등에서). 오라클 품질 기준 밖이면 예외 — 기록하지 않음 */
13
+ record(): Promise<PriceSample>;
14
+ /** 오늘(UTC) 고정 환율. 처음 물을 때 전날 기록으로 계산해 저장 */
15
+ today(): Promise<DailyRate>;
16
+ }
17
+ export declare function createRateBook(o: {
18
+ store: RateStore;
19
+ fetcher?: AccountFetcher;
20
+ guards?: RateGuards;
21
+ now?: () => Date;
22
+ }): 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 ADDED
@@ -0,0 +1,41 @@
1
+ // A402 환율: 매시간 기록 → 전날 기록의 중앙값으로 하루 고정 (안전장치에 걸리면 그날 A402 끔).
2
+ // 저장소는 인터페이스 — 메모리(기본·테스트), 파일(Node: rates-file.ts), Durable Object(Workers 예제) 등
3
+ import { DEFAULT_GUARDS, fixRate, samplePrice } from './pricing.js';
4
+ export function memoryRateStore() {
5
+ const samples = [];
6
+ const rates = new Map();
7
+ return {
8
+ async addSample(s) { samples.push(s); },
9
+ async samples(day) { return samples.filter((s) => s.at.slice(0, 10) === day); },
10
+ async getRate(date) { return rates.get(date) ?? null; },
11
+ async putRate(r) { rates.set(r.date, r); },
12
+ };
13
+ }
14
+ const prevDay = (d) => new Date(Date.parse(`${d}T00:00:00Z`) - 86_400_000).toISOString().slice(0, 10);
15
+ export function createRateBook(o) {
16
+ const now = o.now ?? (() => new Date());
17
+ const guards = o.guards ?? DEFAULT_GUARDS;
18
+ return {
19
+ async record() {
20
+ if (!o.fetcher)
21
+ throw new Error('rate book: no account fetcher configured');
22
+ const s = await samplePrice(o.fetcher, now, guards);
23
+ await o.store.addSample(s);
24
+ return s;
25
+ },
26
+ async today() {
27
+ const date = now().toISOString().slice(0, 10);
28
+ const cached = await o.store.getRate(date);
29
+ if (cached)
30
+ return cached;
31
+ const r = fixRate(date, await o.store.samples(prevDay(date)), guards);
32
+ await o.store.putRate(r);
33
+ return r;
34
+ },
35
+ };
36
+ }
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
+ }