@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/README.md +43 -17
- package/dist/chain.d.ts +6 -6
- package/dist/chain.js +7 -7
- package/dist/core.d.ts +6 -6
- package/dist/core.js +11 -11
- package/dist/gate.d.ts +50 -25
- package/dist/gate.js +83 -34
- package/dist/index.d.ts +5 -3
- package/dist/index.js +7 -4
- package/dist/preq.d.ts +10 -0
- package/dist/preq.js +18 -0
- package/dist/pricing.d.ts +57 -27
- package/dist/pricing.js +91 -35
- package/dist/rates-file.js +2 -2
- package/dist/rates.d.ts +5 -8
- package/dist/rates.js +9 -10
- package/dist/receipt.d.ts +37 -0
- package/dist/receipt.js +50 -0
- package/dist/x402.d.ts +34 -33
- package/dist/x402.js +32 -32
- package/package.json +2 -2
package/dist/gate.js
CHANGED
|
@@ -1,30 +1,37 @@
|
|
|
1
|
-
// @agent402-dev/pay-server
|
|
2
|
-
//
|
|
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
|
-
//
|
|
5
|
-
//
|
|
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
|
-
//
|
|
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 {
|
|
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
|
-
|
|
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
|
-
|
|
27
|
-
|
|
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, ...(
|
|
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
|
-
|
|
83
|
-
|
|
84
|
-
|
|
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(
|
|
87
|
-
notOffered.push({ asset:
|
|
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
|
|
114
|
+
const rate = await t.rate().catch(() => null);
|
|
91
115
|
if (!rate)
|
|
92
|
-
notOffered.push({ asset:
|
|
116
|
+
notOffered.push({ asset: sym, reason: `${sym} rate unavailable` });
|
|
93
117
|
else if (rate.status === 'off')
|
|
94
|
-
notOffered.push({ asset:
|
|
118
|
+
notOffered.push({ asset: sym, reason: rate.reason });
|
|
95
119
|
else {
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
amount
|
|
99
|
-
|
|
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) => (
|
|
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)
|
|
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
|
-
//
|
|
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)
|
|
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
|
-
|
|
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,
|
|
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 —
|
|
2
|
-
|
|
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
|
|
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
|
-
|
|
13
|
-
export declare const
|
|
14
|
-
/** Pyth Crypto.SOL/USD
|
|
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
|
|
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
|
-
/**
|
|
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
|
|
23
|
-
/**
|
|
38
|
+
export declare const TOKEN_DISCOUNT_BPS = 0;
|
|
39
|
+
/** Guard thresholds (proposed values, 2026-11-19) */
|
|
24
40
|
export interface RateGuards {
|
|
25
|
-
/**
|
|
41
|
+
/** Minimum samples in the previous day (out of 24 hours) */
|
|
26
42
|
minSamples: number;
|
|
27
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
41
|
-
|
|
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
|
|
46
|
-
|
|
47
|
-
/**
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
/**
|
|
80
|
-
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
85
|
-
|
|
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;
|