@agent402-dev/pay-server 0.0.0-stage → 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/gate.js ADDED
@@ -0,0 +1,241 @@
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
+ //
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
+ //
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
+ import { decodePaymentSignatureHeader, encodePaymentRequiredHeader } from '@x402/core/http';
9
+ import { HTTPFacilitatorClient } from '@x402/core/server';
10
+ import { ataOf } from './chain.js';
11
+ import { tokenAmountFor } from './pricing.js';
12
+ import { A402_DEPRECATION_WARNING, PREQ_DECIMALS, PREQ_MAINNET_MINT, PREQ_TOKEN_PROGRAM } from './preq.js';
13
+ import { buildRequirements, chooseFacilitator, memoryX402Ledger, paymentResponseHeader, settleVerified, verifyPaymentHeader, } from './x402.js';
14
+ /**
15
+ * Facilitator defaults. Policies and status can change, so these are only defaults and can be overridden in config.
16
+ * - USDC: confirmed with mainnet verify and settle on 2026-11-19 (PayAI, Dexter)
17
+ * - A402 (v1, deprecated): record of a check on PayAI on 2026-11-19
18
+ * - 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
19
+ */
20
+ export const KNOWN_FACILITATORS = {
21
+ payai: { name: 'payai', url: 'https://facilitator.payai.network', assets: ['USDC', 'PREQ', 'A402'] },
22
+ dexter: { name: 'dexter', url: 'https://x402.dexter.cash', assets: ['USDC'] },
23
+ };
24
+ export const SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
25
+ export const SOLANA_DEVNET = 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1';
26
+ export const USDC_MAINNET = { symbol: 'USDC', mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', decimals: 6, tokenProgram: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' };
27
+ /** PREQ (Token-2022, 6 decimals). The mint is PREQ_MAINNET_MINT in preq.ts; if empty, createPaymentGate stops with an error */
28
+ export const PREQ_MAINNET = { symbol: 'PREQ', mint: PREQ_MAINNET_MINT, decimals: PREQ_DECIMALS, tokenProgram: PREQ_TOKEN_PROGRAM };
29
+ /** @deprecated A402 (v1) is deprecated. Use PREQ_MAINNET. Enabling it explicitly with config.a402 prints a warning */
30
+ export const A402_MAINNET = { symbol: 'A402', mint: 'GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X', decimals: 6, tokenProgram: 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' };
31
+ /**
32
+ * 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).
33
+ * Real case on 2026-11-19: `transaction_simulation_failed: Simulation failed: {"InsufficientFundsForRent":{"account_index":0}}`
34
+ */
35
+ export function isFacilitatorSideFailure(reason, message) {
36
+ const s = `${reason ?? ''} ${message ?? ''}`;
37
+ if (/InsufficientFundsForRent[^}]*account_index"?\s*:\s*0\b/.test(s))
38
+ return true;
39
+ if (/fee[ _-]?payer/i.test(s) && /(insufficient|balance|funds|rent)/i.test(s))
40
+ return true;
41
+ return false;
42
+ }
43
+ 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 } });
44
+ const NOT_CHARGED = 'No payment was taken.';
45
+ export function createPaymentGate(c) {
46
+ // Check token payment settings: stop if the PREQ mint is empty; A402 (v1) only when enabled explicitly, with a warning
47
+ if (c.preq) {
48
+ if (c.preq.asset.symbol !== 'PREQ')
49
+ throw new Error(`config.preq.asset.symbol must be PREQ (got ${c.preq.asset.symbol})`);
50
+ if (!c.preq.asset.mint) {
51
+ 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).');
52
+ }
53
+ }
54
+ if (c.a402) {
55
+ if (c.a402.asset.symbol !== 'A402')
56
+ throw new Error(`config.a402.asset.symbol must be A402 (got ${c.a402.asset.symbol})`);
57
+ (c.warn ?? console.warn)(A402_DEPRECATION_WARNING);
58
+ }
59
+ if (c.preq && c.a402 && c.preq.asset.mint === c.a402.asset.mint)
60
+ throw new Error('config.preq and config.a402 use the same mint');
61
+ const tokens = [c.preq, c.a402].filter((t) => !!t);
62
+ const now = c.now ?? (() => Date.now());
63
+ const ledger = c.ledger ?? memoryX402Ledger();
64
+ const named = c.facilitators.map((f) => ({
65
+ name: f.name,
66
+ client: f.client ?? new HTTPFacilitatorClient({ url: f.url }),
67
+ assets: f.assets,
68
+ }));
69
+ const cooldown = new Map();
70
+ const cfgFor = (fs) => ({ network: c.network, payTo: c.payTo, facilitators: fs, maxTimeoutSeconds: c.maxTimeoutSeconds ?? 60 });
71
+ const allCfg = cfgFor(named);
72
+ // ---- Receiving token account check (cached) ----
73
+ let receiving = null;
74
+ async function checkReceivingAccounts() {
75
+ if (receiving && now() - receiving.at < (c.receivingCheckTtlMs ?? 600_000))
76
+ return receiving.list;
77
+ const assets = [c.usdc, ...tokens.map((t) => t.asset)];
78
+ const atas = await Promise.all(assets.map((a) => ataOf(c.payTo, a.mint, a.tokenProgram)));
79
+ const { accounts } = await c.chain.accounts(atas);
80
+ const list = assets.map((a, i) => ({ asset: a.symbol, mint: a.mint, tokenAccount: atas[i], exists: !!accounts[i] && accounts[i].owner === a.tokenProgram }));
81
+ receiving = { at: now(), list };
82
+ return list;
83
+ }
84
+ async function quote(resourceUrl) {
85
+ const healthy = named.filter((f) => (cooldown.get(f.name) ?? 0) <= now());
86
+ const chosen = await chooseFacilitator(cfgFor(healthy), now());
87
+ if (!chosen)
88
+ return null;
89
+ const fac = named.find((f) => f.name === chosen.facilitator.name);
90
+ const notOffered = [];
91
+ let recv = [];
92
+ try {
93
+ recv = await checkReceivingAccounts();
94
+ }
95
+ catch { /* check failed → continue without blocking (there is a separate on-chain recheck) */ }
96
+ const missing = (sym) => recv.find((r) => r.asset === sym && !r.exists);
97
+ const offers = [];
98
+ // USDC
99
+ if (missing('USDC'))
100
+ notOffered.push({ asset: 'USDC', reason: `receiving token account ${missing('USDC').tokenAccount} does not exist` });
101
+ else
102
+ offers.push({ asset: c.usdc, amount: BigInt(Math.round(c.priceUsd * 10 ** c.usdc.decimals)) });
103
+ // Tokens (PREQ, and A402 (v1) only when enabled explicitly)
104
+ for (const t of tokens) {
105
+ const sym = t.asset.symbol;
106
+ if (!fac.assets.includes(sym)) {
107
+ notOffered.push({ asset: sym, reason: `facilitator ${fac.name} does not accept ${sym}` });
108
+ }
109
+ else if (missing(sym)) {
110
+ notOffered.push({ asset: sym, reason: `receiving token account ${missing(sym).tokenAccount} does not exist` });
111
+ }
112
+ else {
113
+ const rate = await t.rate().catch(() => null);
114
+ if (!rate)
115
+ notOffered.push({ asset: sym, reason: `${sym} rate unavailable` });
116
+ else if (rate.status === 'off')
117
+ notOffered.push({ asset: sym, reason: rate.reason });
118
+ else {
119
+ let amount = null;
120
+ try {
121
+ amount = tokenAmountFor(c.priceUsd, t.discountPercent ?? 0, rate, t.asset.decimals);
122
+ }
123
+ catch {
124
+ amount = null;
125
+ }
126
+ if (amount === null)
127
+ notOffered.push({ asset: sym, reason: `${sym} rate out of range` });
128
+ else
129
+ offers.push({ asset: t.asset, amount, rate: { date: rate.date, tokenUsd: rate.tokenUsd, method: rate.method, discountPercent: t.discountPercent ?? 0 } });
130
+ }
131
+ }
132
+ }
133
+ if (!fac.assets.includes('USDC')) {
134
+ const i = offers.findIndex((o) => o.asset.symbol === 'USDC');
135
+ if (i >= 0) {
136
+ offers.splice(i, 1);
137
+ notOffered.push({ asset: 'USDC', reason: `facilitator ${fac.name} does not accept USDC` });
138
+ }
139
+ }
140
+ const accepts = offers.length ? await buildRequirements(allCfg, offers, chosen) : [];
141
+ return { accepts, notOffered, facilitator: fac.name };
142
+ }
143
+ function paymentRequired(resourceUrl, q, extra = {}, error) {
144
+ const pr = {
145
+ x402Version: 2,
146
+ ...(error ? { error } : {}),
147
+ resource: { url: resourceUrl, description: c.resource?.description ?? '', mimeType: c.resource?.mimeType ?? 'application/json', ...(c.resource?.serviceName ? { serviceName: c.resource.serviceName } : {}) },
148
+ accepts: q.accepts,
149
+ };
150
+ return json(402, { ...pr, ...(q.notOffered.length ? { notOffered: q.notOffered } : {}), ...extra }, {
151
+ 'payment-required': encodePaymentRequiredHeader(pr),
152
+ 'access-control-expose-headers': 'PAYMENT-REQUIRED, PAYMENT-RESPONSE',
153
+ });
154
+ }
155
+ function withPayment(handler) {
156
+ return async (req) => {
157
+ const url = new URL(req.url);
158
+ const resourceUrl = `${url.origin}${url.pathname}`;
159
+ const q = await quote(resourceUrl);
160
+ if (!q)
161
+ return json(503, { error: 'payment_unavailable', message: `No facilitator is reachable right now. ${NOT_CHARGED}` });
162
+ if (!q.accepts.length)
163
+ return json(503, { error: 'payment_unavailable', message: `No payment option can be offered right now. ${NOT_CHARGED}`, notOffered: q.notOffered });
164
+ const header = req.headers.get('payment-signature');
165
+ if (!header)
166
+ return paymentRequired(resourceUrl, q, {}, 'Payment required');
167
+ const d = {
168
+ cfg: allCfg, ledger,
169
+ loadTx: (s) => c.chain.loadTx(s),
170
+ recentSignatures: (a, n) => c.chain.recentSignatures(a, n),
171
+ tokenProgramOf: (mint) => tokens.find((t) => t.asset.mint === mint)?.asset.tokenProgram ?? c.usdc.tokenProgram,
172
+ nowMs: now(),
173
+ confirmDelaysMs: c.confirmDelaysMs,
174
+ };
175
+ // 1) Match requirements and verify (no money moves yet)
176
+ const v = await verifyPaymentHeader(header, url.pathname, q.accepts, d);
177
+ if (v.kind === 'conflict')
178
+ 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.' });
179
+ if (v.kind === 'unavailable')
180
+ return json(503, { error: 'payment_unavailable', message: `Could not reach the facilitator. ${NOT_CHARGED}` });
181
+ if (v.kind === 'payment_required') {
182
+ if (isFacilitatorSideFailure(v.reason, v.message)) {
183
+ // 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
184
+ const feePayer = (() => { try {
185
+ return decodePaymentSignatureHeader(header).accepted?.extra?.feePayer;
186
+ }
187
+ catch {
188
+ return undefined;
189
+ } })();
190
+ const failed = (await Promise.all(named.map(async (f) => ((await chooseFacilitator(cfgFor([f]), now()))?.feePayer === feePayer ? f.name : null)))).find(Boolean);
191
+ if (failed)
192
+ cooldown.set(failed, now() + (c.facilitatorCooldownMs ?? 300_000));
193
+ const q2 = await quote(resourceUrl);
194
+ if (!q2 || !q2.accepts.length)
195
+ 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}` });
196
+ 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');
197
+ }
198
+ return paymentRequired(resourceUrl, q, { reason: v.reason, message: `Payment was not accepted (${v.reason}). ${NOT_CHARGED}` }, v.reason);
199
+ }
200
+ // 2) Handler (time limit). No settlement on failure, timeout, or a 4xx/5xx response
201
+ const payment = v.payment;
202
+ const info = { asset: payment.accepted.asset, amount: payment.accepted.amount, payTo: payment.accepted.payTo, network: payment.accepted.network };
203
+ let res;
204
+ let timer;
205
+ try {
206
+ res = await Promise.race([
207
+ handler(req, info),
208
+ new Promise((_, rej) => { timer = setTimeout(() => rej(new Error('__handler_timeout__')), c.handlerTimeoutMs ?? 40_000); }),
209
+ ]);
210
+ }
211
+ catch (e) {
212
+ await ledger.release(payment.key);
213
+ const timeout = e.message === '__handler_timeout__';
214
+ 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}` });
215
+ }
216
+ finally {
217
+ if (timer)
218
+ clearTimeout(timer);
219
+ }
220
+ if (res.status >= 400) {
221
+ await ledger.release(payment.key);
222
+ const h = new Headers(res.headers);
223
+ h.set('x-payment-status', 'not-settled');
224
+ return new Response(res.body, { status: res.status, headers: h });
225
+ }
226
+ // 3) Settle (+ decide on-chain if it fails or the result is unknown)
227
+ const s = await settleVerified(payment, { ...d, nowMs: now() });
228
+ if (s.kind === 'payment_required')
229
+ return paymentRequired(resourceUrl, q, { reason: s.reason, message: `Payment was not settled (${s.reason}). ${NOT_CHARGED}` }, s.reason);
230
+ if (s.kind === 'unavailable')
231
+ 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).' });
232
+ await ledger.fulfill(payment.key, now());
233
+ const h = new Headers(res.headers);
234
+ h.set('payment-response', paymentResponseHeader(s.settlement));
235
+ h.set('x-payment-confirmation', s.confirmation);
236
+ h.set('access-control-expose-headers', 'PAYMENT-RESPONSE, X-Payment-Confirmation');
237
+ return new Response(res.body, { status: res.status, headers: h });
238
+ };
239
+ }
240
+ return { withPayment, quote, checkReceivingAccounts };
241
+ }
@@ -0,0 +1,6 @@
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';
3
+ export { rpcChain, receivedBy, type ChainReader, type ChainTx, type AccountFetcher } from './chain.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 { memoryX402Ledger, ledgerClaim, SETTLE_UNKNOWN_EXPIRY_MS, type X402Ledger, type LedgerEntry, type Asset } from './x402.js';
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
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';
5
+ export { rpcChain, receivedBy } from './chain.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 { 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
+ }
@@ -0,0 +1,117 @@
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 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 */
25
+ export declare const A402_MAINNET_MINT = "GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X";
26
+ /** @deprecated A402 (v1) is deprecated */
27
+ export declare const A402_MAINNET_POOL = "DaHBw8dxnZaCaX5HdsiM1Hs1uQNwsW3QW3wcD6P4Z5oZ";
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) */
31
+ export declare const PYTH_SOL_USD_FEED = "ef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d";
32
+ /** Pyth push oracle program and receiver (account owner) */
33
+ export declare const PYTH_PUSH_ORACLE = "pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT";
34
+ export declare const PYTH_RECEIVER = "rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ";
35
+ /** SOL/USD price account for shard 0 = PDA([u16 shard=0, feed_id], push oracle); computed and checked by the function below */
36
+ export declare function pythPriceAccount(feedHex?: string, shard?: number): string;
37
+ export declare const PRICE_USDC_BASE_UNITS = 20000n;
38
+ export declare const TOKEN_DISCOUNT_BPS = 0;
39
+ /** Guard thresholds (proposed values, 2026-11-19) */
40
+ export interface RateGuards {
41
+ /** Minimum samples in the previous day (out of 24 hours) */
42
+ minSamples: number;
43
+ /** Minimum SOL-side pool depth (USD) across all of the previous day's samples */
44
+ minPoolSolSideUsd: number;
45
+ /** Maximum ratio of the previous day's highest to lowest price */
46
+ maxDailyRangeRatio: number;
47
+ /** Maximum Pyth confidence / price ratio (samples above it are discarded) */
48
+ maxOracleConfRatio: number;
49
+ /** How many seconds before the sample time the Pyth update may be */
50
+ maxOracleAgeSec: number;
51
+ }
52
+ export declare const DEFAULT_GUARDS: RateGuards;
53
+ export interface PriceSample {
54
+ /** ISO time */
55
+ at: string;
56
+ /** Which token the sample is for (missing for old A402 samples) */
57
+ symbol?: 'PREQ' | 'A402';
58
+ /** SOL per token */
59
+ tokenSol: number;
60
+ /** USD per SOL (Pyth) */
61
+ solUsd: number;
62
+ solUsdConf: number;
63
+ /** USD per token */
64
+ tokenUsd: number;
65
+ /** Pool SOL vault balance × SOL/USD */
66
+ poolSolSideUsd: number;
67
+ slot: number;
68
+ pythPublishTime: number;
69
+ }
70
+ export type DailyRate = {
71
+ status: 'on';
72
+ date: string;
73
+ basedOn: string; /** USD per token */
74
+ tokenUsd: number;
75
+ samples: number;
76
+ method: string;
77
+ } | {
78
+ status: 'off';
79
+ date: string;
80
+ basedOn: string;
81
+ reason: string;
82
+ samples: number;
83
+ };
84
+ /**
85
+ * DAMM v2 sqrt_price (Q64.64) → price of B per A.
86
+ * price = (sqrt_price / 2^64)^2 × 10^(decimalsA − decimalsB)
87
+ */
88
+ export declare function dammV2Price(sqrtPrice: bigint, decimalsA: number, decimalsB: number): number;
89
+ /** Decodes a Pyth PriceUpdateV2 account (one more byte if verification_level is Partial) */
90
+ export declare function decodePythPriceUpdate(data: Buffer): {
91
+ verification: string;
92
+ feedId: string;
93
+ price: number;
94
+ conf: number;
95
+ publishTime: number;
96
+ };
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>;
104
+ export declare function median(xs: number[]): number;
105
+ /** Fixed rate for date. Computed from the previous day's samples; off if a guard trips */
106
+ export declare function fixRate(date: string, samples: PriceSample[], guards?: RateGuards): 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, {
116
+ status: 'on';
117
+ }>, decimals?: number): bigint;
@@ -0,0 +1,183 @@
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)
6
+ import { PublicKey } from '@solana/web3.js';
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) */
9
+ const DAMM_V2_POOL_SIZE = 1112;
10
+ const DAMM_V2_POOL_DISC = [241, 154, 109, 4, 17, 177, 109, 188];
11
+ export function decodeDammV2PoolForRate(data) {
12
+ const b = Buffer.from(data);
13
+ if (b.length !== DAMM_V2_POOL_SIZE || !DAMM_V2_POOL_DISC.every((x, i) => b[i] === x))
14
+ throw new Error('not a DAMM v2 pool account');
15
+ const key = (o) => new PublicKey(b.subarray(o, o + 32)).toBase58();
16
+ return {
17
+ tokenAMint: key(168), tokenBMint: key(200), tokenAVault: key(232), tokenBVault: key(264),
18
+ /** sqrt_price (Q64.64, u128 LE) */
19
+ sqrtPrice: (b.readBigUInt64LE(464) << 64n) | b.readBigUInt64LE(456),
20
+ };
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 */
32
+ export const A402_MAINNET_MINT = 'GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X';
33
+ /** @deprecated A402 (v1) is deprecated */
34
+ export const A402_MAINNET_POOL = 'DaHBw8dxnZaCaX5HdsiM1Hs1uQNwsW3QW3wcD6P4Z5oZ';
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) */
38
+ export const PYTH_SOL_USD_FEED = 'ef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d';
39
+ /** Pyth push oracle program and receiver (account owner) */
40
+ export const PYTH_PUSH_ORACLE = 'pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT';
41
+ export const PYTH_RECEIVER = 'rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ';
42
+ /** SOL/USD price account for shard 0 = PDA([u16 shard=0, feed_id], push oracle); computed and checked by the function below */
43
+ export function pythPriceAccount(feedHex = PYTH_SOL_USD_FEED, shard = 0) {
44
+ const s = Buffer.alloc(2);
45
+ s.writeUInt16LE(shard);
46
+ return PublicKey.findProgramAddressSync([s, Buffer.from(feedHex, 'hex')], new PublicKey(PYTH_PUSH_ORACLE))[0].toBase58();
47
+ }
48
+ export const PRICE_USDC_BASE_UNITS = 20000n; // 0.02 USDC (6 decimals)
49
+ export const TOKEN_DISCOUNT_BPS = 0; // no discount by default
50
+ export const DEFAULT_GUARDS = {
51
+ minSamples: 12,
52
+ minPoolSolSideUsd: 100,
53
+ maxDailyRangeRatio: 1.5,
54
+ maxOracleConfRatio: 0.01,
55
+ maxOracleAgeSec: 120,
56
+ };
57
+ /**
58
+ * DAMM v2 sqrt_price (Q64.64) → price of B per A.
59
+ * price = (sqrt_price / 2^64)^2 × 10^(decimalsA − decimalsB)
60
+ */
61
+ export function dammV2Price(sqrtPrice, decimalsA, decimalsB) {
62
+ const s = Number(sqrtPrice) / 2 ** 64;
63
+ return s * s * 10 ** (decimalsA - decimalsB);
64
+ }
65
+ /** Decodes a Pyth PriceUpdateV2 account (one more byte if verification_level is Partial) */
66
+ export function decodePythPriceUpdate(data) {
67
+ const tag = data[40];
68
+ let o = 41 + (tag === 0 ? 1 : 0);
69
+ const feedId = data.subarray(o, o + 32).toString('hex');
70
+ o += 32;
71
+ const price = data.readBigInt64LE(o);
72
+ const conf = data.readBigUInt64LE(o + 8);
73
+ const expo = data.readInt32LE(o + 16);
74
+ const publishTime = Number(data.readBigInt64LE(o + 20));
75
+ return { verification: tag === 1 ? 'full' : 'partial', feedId, price: Number(price) * 10 ** expo, conf: Number(conf) * 10 ** expo, publishTime };
76
+ }
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);
96
+ const pythAcc = pythPriceAccount();
97
+ const { slot, accounts } = await fetcher([poolAddr, solVault, pythAcc]);
98
+ const [poolAcc, vaultAcc, pyth] = accounts;
99
+ if (!poolAcc || !vaultAcc || !pyth)
100
+ throw new Error('price accounts missing');
101
+ const pool = decodeDammV2PoolForRate(poolAcc.data);
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)
105
+ throw new Error('unexpected pool layout');
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;
112
+ if (pyth.owner !== PYTH_RECEIVER)
113
+ throw new Error('pyth account owner mismatch');
114
+ const p = decodePythPriceUpdate(Buffer.from(pyth.data));
115
+ if (p.feedId !== PYTH_SOL_USD_FEED)
116
+ throw new Error('pyth feed mismatch');
117
+ if (p.verification !== 'full')
118
+ throw new Error('pyth update not fully verified');
119
+ const nowSec = Math.floor(now().getTime() / 1000);
120
+ if (nowSec - p.publishTime > guards.maxOracleAgeSec)
121
+ throw new Error('pyth price stale');
122
+ if (!(p.price > 0) || p.conf / p.price > guards.maxOracleConfRatio)
123
+ throw new Error('pyth confidence too wide');
124
+ const tokenUsd = tokenSol * p.price;
125
+ if (!Number.isFinite(tokenUsd) || !(tokenUsd > 0))
126
+ throw new Error('non-positive or non-finite token price');
127
+ return {
128
+ at: now().toISOString(), symbol: target.symbol, tokenSol, solUsd: p.price, solUsdConf: p.conf, tokenUsd,
129
+ poolSolSideUsd: solInVault * p.price, slot, pythPublishTime: p.publishTime,
130
+ };
131
+ }
132
+ export function median(xs) {
133
+ const s = [...xs].sort((a, b) => a - b);
134
+ const m = s.length >> 1;
135
+ return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
136
+ }
137
+ const prevDay = (d) => new Date(Date.parse(`${d}T00:00:00Z`) - 86_400_000).toISOString().slice(0, 10);
138
+ /** Fixed rate for date. Computed from the previous day's samples; off if a guard trips */
139
+ export function fixRate(date, samples, guards = DEFAULT_GUARDS) {
140
+ const basedOn = prevDay(date);
141
+ const ys = samples.filter((s) => s.at.slice(0, 10) === basedOn);
142
+ const off = (reason) => ({ status: 'off', date, basedOn, reason, samples: ys.length });
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);
150
+ if (minDepth < guards.minPoolSolSideUsd) {
151
+ return off(`${basedOn}: lowest pool SOL-side depth ${minDepth.toFixed(0)} USD, below the minimum of ${guards.minPoolSolSideUsd} USD`);
152
+ }
153
+ const prices = ys.map((s) => s.tokenUsd);
154
+ const ratio = Math.max(...prices) / Math.min(...prices);
155
+ if (!Number.isFinite(ratio) || ratio > guards.maxDailyRangeRatio) {
156
+ return off(`${basedOn}: max/min price ratio ${ratio.toFixed(2)}, above the limit of ${guards.maxDailyRangeRatio}`);
157
+ }
158
+ return {
159
+ status: 'on', date, basedOn, tokenUsd: median(prices), samples: ys.length,
160
+ method: `median of ${ys.length} hourly samples on ${basedOn} (UTC) (lowest depth ${minDepth.toFixed(0)} USD, max/min ${ratio.toFixed(2)})`,
161
+ };
162
+ }
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);
183
+ }
@@ -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-only rate store: a single JSON file (keeps only the last 3 days of samples). Do not use on 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); // so the original is not corrupted if writing is interrupted
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,23 @@
1
+ import { type DailyRate, type PoolTarget, 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
+ /** Samples for one UTC date (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
+ /** Records one sample (e.g. from an hourly cron). Throws if outside the oracle quality bounds; nothing is recorded */
13
+ record(): Promise<PriceSample>;
14
+ /** Today's (UTC) fixed rate. Computed from the previous day's samples on first request and stored */
15
+ today(): Promise<DailyRate>;
16
+ }
17
+ export declare function createRateBook(o: {
18
+ store: RateStore;
19
+ fetcher?: AccountFetcher;
20
+ guards?: RateGuards;
21
+ now?: () => Date;
22
+ target?: PoolTarget;
23
+ }): RateBook;