@agent402-dev/pay-server 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/pricing.js CHANGED
@@ -1,9 +1,11 @@
1
- // A402 결제 환율 (30% 할인). 비공개 영역(API 서버). 방식은 docs/pricing.md 에 공개용으로 정리.
2
- // - 매시간 기록 (RPC 한 번): A402/SOL = 메인넷 Meteora DAMM v2 풀 sqrt_price,
3
- // SOL 쪽 깊이 = 풀 SOL 금고 잔액, SOL/USD = Pyth 푸시 오라클 계정 (Solana 메인넷, USDC ≈ 1 USD 로 봄)
4
- // - 하루 고정: 전날(UTC) 기록의 중앙값. 안전장치(기록 수·유동성·변동폭) 중 하나라도 걸리면 그날 A402 결제 끔 (USDC 만)
1
+ // Payment token (PREQ) rate. The method is documented for the public in docs/pricing.md.
2
+ // - Hourly sample (one RPC call): token/SOL = mainnet Meteora DAMM v2 pool sqrt_price,
3
+ // SOL-side depth = pool SOL vault balance, SOL/USD = Pyth push oracle account (Solana mainnet, USDC treated as ≈ 1 USD)
4
+ // - Fixed per day: median of the previous day's (UTC) samples. If any guard (sample count, liquidity, range) trips, token payments are off that day (USDC only)
5
+ // - Pool and mint addresses are read from preq.ts only. The A402 (v1) pool is deprecated: only when passed explicitly (prints a warning)
5
6
  import { PublicKey } from '@solana/web3.js';
6
- /** Meteora DAMM v2 풀 계정에서 환율에 필요한 부분만 (오프셋: cp-amm IDL, bytemuck — 점검 엔진의 해석과 같은 값) */
7
+ import { A402_DEPRECATION_WARNING, PREQ_DECIMALS, PREQ_MAINNET_MINT, PREQ_MAINNET_POOL, requirePreqValue } from './preq.js';
8
+ /** Only the parts of a Meteora DAMM v2 pool account needed for the rate (offsets: cp-amm IDL, bytemuck; same values as the check engine's decoder) */
7
9
  const DAMM_V2_POOL_SIZE = 1112;
8
10
  const DAMM_V2_POOL_DISC = [241, 154, 109, 4, 17, 177, 109, 188];
9
11
  export function decodeDammV2PoolForRate(data) {
@@ -17,23 +19,34 @@ export function decodeDammV2PoolForRate(data) {
17
19
  sqrtPrice: (b.readBigUInt64LE(464) << 64n) | b.readBigUInt64LE(456),
18
20
  };
19
21
  }
22
+ export const WSOL_MINT = 'So11111111111111111111111111111111111111112';
23
+ /** Meteora DAMM v2 (cp-amm) program */
24
+ export const DAMM_V2_PROGRAM = 'cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG';
25
+ /** Pool vault address = PDA(["token_vault", mint, pool], cp-amm); same rule as Meteora SDK deriveTokenVaultAddress */
26
+ export function dammV2VaultAddress(mint, pool) {
27
+ return PublicKey.findProgramAddressSync([Buffer.from('token_vault'), new PublicKey(mint).toBuffer(), new PublicKey(pool).toBuffer()], new PublicKey(DAMM_V2_PROGRAM))[0].toBase58();
28
+ }
29
+ /** Default target: PREQ (constants in preq.ts). samplePrice errors if they are empty */
30
+ export const PREQ_POOL_TARGET = { symbol: 'PREQ', mint: PREQ_MAINNET_MINT, pool: PREQ_MAINNET_POOL, decimals: PREQ_DECIMALS };
31
+ /** @deprecated A402 (v1) is deprecated. Kept for records only; prints a warning if used */
20
32
  export const A402_MAINNET_MINT = 'GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X';
33
+ /** @deprecated A402 (v1) is deprecated */
21
34
  export const A402_MAINNET_POOL = 'DaHBw8dxnZaCaX5HdsiM1Hs1uQNwsW3QW3wcD6P4Z5oZ';
22
- export const A402_POOL_SOL_VAULT = 'FXf9X8exSSZCSe7h14vK4xpcXsdbdNP7nR8myo1MBaMq';
23
- export const WSOL_MINT = 'So11111111111111111111111111111111111111112';
24
- /** Pyth Crypto.SOL/USD 피드 ID (hermes.pyth.network /v2/price_feeds 목록에서 확인) */
35
+ /** @deprecated A402 (v1) is deprecated. Used only when passed explicitly to samplePrice (prints a warning) */
36
+ export const A402_POOL_TARGET = { symbol: 'A402', mint: A402_MAINNET_MINT, pool: A402_MAINNET_POOL, decimals: 6 };
37
+ /** Pyth Crypto.SOL/USD feed ID (checked against the hermes.pyth.network /v2/price_feeds list) */
25
38
  export const PYTH_SOL_USD_FEED = 'ef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d';
26
- /** Pyth 푸시 오라클 프로그램과 receiver(계정 소유자) */
39
+ /** Pyth push oracle program and receiver (account owner) */
27
40
  export const PYTH_PUSH_ORACLE = 'pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT';
28
41
  export const PYTH_RECEIVER = 'rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ';
29
- /** 샤드 0 의 SOL/USD 가격 계정 = PDA([u16 shard=0, feed_id], push oracle) — 아래 함수로 계산해 대조 */
42
+ /** SOL/USD price account for shard 0 = PDA([u16 shard=0, feed_id], push oracle); computed and checked by the function below */
30
43
  export function pythPriceAccount(feedHex = PYTH_SOL_USD_FEED, shard = 0) {
31
44
  const s = Buffer.alloc(2);
32
45
  s.writeUInt16LE(shard);
33
46
  return PublicKey.findProgramAddressSync([s, Buffer.from(feedHex, 'hex')], new PublicKey(PYTH_PUSH_ORACLE))[0].toBase58();
34
47
  }
35
- export const PRICE_USDC_BASE_UNITS = 20000n; // 0.02 USDC (소수 6자리)
36
- export const A402_DISCOUNT_BPS = 3000; // 30%
48
+ export const PRICE_USDC_BASE_UNITS = 20000n; // 0.02 USDC (6 decimals)
49
+ export const TOKEN_DISCOUNT_BPS = 0; // no discount by default
37
50
  export const DEFAULT_GUARDS = {
38
51
  minSamples: 12,
39
52
  minPoolSolSideUsd: 100,
@@ -42,14 +55,14 @@ export const DEFAULT_GUARDS = {
42
55
  maxOracleAgeSec: 120,
43
56
  };
44
57
  /**
45
- * DAMM v2 sqrt_price(Q64.64) → B per A 가격.
58
+ * DAMM v2 sqrt_price (Q64.64) → price of B per A.
46
59
  * price = (sqrt_price / 2^64)^2 × 10^(decimalsA − decimalsB)
47
60
  */
48
61
  export function dammV2Price(sqrtPrice, decimalsA, decimalsB) {
49
62
  const s = Number(sqrtPrice) / 2 ** 64;
50
63
  return s * s * 10 ** (decimalsA - decimalsB);
51
64
  }
52
- /** Pyth PriceUpdateV2 계정 해석 (verification_level 이 Partial 이면 1바이트 더) */
65
+ /** Decodes a Pyth PriceUpdateV2 account (one more byte if verification_level is Partial) */
53
66
  export function decodePythPriceUpdate(data) {
54
67
  const tag = data[40];
55
68
  let o = 41 + (tag === 0 ? 1 : 0);
@@ -61,19 +74,41 @@ export function decodePythPriceUpdate(data) {
61
74
  const publishTime = Number(data.readBigInt64LE(o + 20));
62
75
  return { verification: tag === 1 ? 'full' : 'partial', feedId, price: Number(price) * 10 ** expo, conf: Number(conf) * 10 ** expo, publishTime };
63
76
  }
64
- /** 풀·SOL 금고·Pyth 계정을 RPC 한 번으로 읽어 기록 하나. 오라클 품질이 기준 밖이면 예외 */
65
- export async function samplePrice(fetcher, now = () => new Date(), guards = DEFAULT_GUARDS) {
77
+ /**
78
+ * "SOL per token" from the pool's sqrt_price. Handles the token on side A or B.
79
+ * Throws on 0, infinity or NaN (including when a single-sided pool's price sits at the range edge right after trading starts)
80
+ */
81
+ export function tokenSolFromPool(sqrtPrice, tokenIsA, tokenDecimals) {
82
+ const v = tokenIsA ? dammV2Price(sqrtPrice, tokenDecimals, 9) : 1 / dammV2Price(sqrtPrice, 9, tokenDecimals);
83
+ if (!Number.isFinite(v) || !(v > 0))
84
+ throw new Error('non-positive or non-finite pool price');
85
+ return v;
86
+ }
87
+ /** Reads the pool, SOL vault and Pyth accounts in one RPC call and records one sample. Default target is PREQ (preq.ts). Throws if oracle quality is out of bounds */
88
+ export async function samplePrice(fetcher, now = () => new Date(), guards = DEFAULT_GUARDS, target = PREQ_POOL_TARGET) {
89
+ if (target.symbol === 'A402')
90
+ console.warn(A402_DEPRECATION_WARNING);
91
+ const mint = target.symbol === 'PREQ' ? requirePreqValue('PREQ_MAINNET_MINT', target.mint) : target.mint;
92
+ const poolAddr = target.symbol === 'PREQ' ? requirePreqValue('PREQ_MAINNET_POOL', target.pool) : target.pool;
93
+ if (!mint || !poolAddr)
94
+ throw new Error(`${target.symbol} mint/pool not set`);
95
+ const solVault = dammV2VaultAddress(WSOL_MINT, poolAddr);
66
96
  const pythAcc = pythPriceAccount();
67
- const { slot, accounts } = await fetcher([A402_MAINNET_POOL, A402_POOL_SOL_VAULT, pythAcc]);
97
+ const { slot, accounts } = await fetcher([poolAddr, solVault, pythAcc]);
68
98
  const [poolAcc, vaultAcc, pyth] = accounts;
69
99
  if (!poolAcc || !vaultAcc || !pyth)
70
100
  throw new Error('price accounts missing');
71
101
  const pool = decodeDammV2PoolForRate(poolAcc.data);
72
- if (pool.tokenAMint !== A402_MAINNET_MINT || pool.tokenBMint !== WSOL_MINT || pool.tokenBVault !== A402_POOL_SOL_VAULT) {
102
+ const tokenIsA = pool.tokenAMint === mint && pool.tokenBMint === WSOL_MINT && pool.tokenBVault === solVault;
103
+ const tokenIsB = pool.tokenBMint === mint && pool.tokenAMint === WSOL_MINT && pool.tokenAVault === solVault;
104
+ if (!tokenIsA && !tokenIsB)
73
105
  throw new Error('unexpected pool layout');
74
- }
75
- const a402Sol = dammV2Price(pool.sqrtPrice, 6, 9);
76
- const solInVault = Number(Buffer.from(vaultAcc.data).readBigUInt64LE(64)) / 1e9;
106
+ const tokenSol = tokenSolFromPool(pool.sqrtPrice, tokenIsA, target.decimals);
107
+ const vaultData = Buffer.from(vaultAcc.data);
108
+ if (vaultData.length < 72)
109
+ throw new Error('unexpected SOL vault account');
110
+ // A single-sided pool may have 0 on the SOL side right after trading starts → record depth 0 (fixRate's depth guard turns off payments that day)
111
+ const solInVault = Number(vaultData.readBigUInt64LE(64)) / 1e9;
77
112
  if (pyth.owner !== PYTH_RECEIVER)
78
113
  throw new Error('pyth account owner mismatch');
79
114
  const p = decodePythPriceUpdate(Buffer.from(pyth.data));
@@ -86,10 +121,11 @@ export async function samplePrice(fetcher, now = () => new Date(), guards = DEFA
86
121
  throw new Error('pyth price stale');
87
122
  if (!(p.price > 0) || p.conf / p.price > guards.maxOracleConfRatio)
88
123
  throw new Error('pyth confidence too wide');
89
- if (!(a402Sol > 0))
90
- throw new Error('non-positive pool price');
124
+ const tokenUsd = tokenSol * p.price;
125
+ if (!Number.isFinite(tokenUsd) || !(tokenUsd > 0))
126
+ throw new Error('non-positive or non-finite token price');
91
127
  return {
92
- at: now().toISOString(), a402Sol, solUsd: p.price, solUsdConf: p.conf, a402Usd: a402Sol * p.price,
128
+ at: now().toISOString(), symbol: target.symbol, tokenSol, solUsd: p.price, solUsdConf: p.conf, tokenUsd,
93
129
  poolSolSideUsd: solInVault * p.price, slot, pythPublishTime: p.publishTime,
94
130
  };
95
131
  }
@@ -99,29 +135,49 @@ export function median(xs) {
99
135
  return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
100
136
  }
101
137
  const prevDay = (d) => new Date(Date.parse(`${d}T00:00:00Z`) - 86_400_000).toISOString().slice(0, 10);
102
- /** date 에 쓸 고정 환율. 전날 기록으로 계산하고, 안전장치에 걸리면 off */
138
+ /** Fixed rate for date. Computed from the previous day's samples; off if a guard trips */
103
139
  export function fixRate(date, samples, guards = DEFAULT_GUARDS) {
104
140
  const basedOn = prevDay(date);
105
141
  const ys = samples.filter((s) => s.at.slice(0, 10) === basedOn);
106
142
  const off = (reason) => ({ status: 'off', date, basedOn, reason, samples: ys.length });
107
- if (ys.length < guards.minSamples)
108
- return off(`${basedOn}: ${ys.length} samples, below the minimum of ${guards.minSamples}`);
109
- const minDepth = Math.min(...ys.map((s) => s.poolSolSideUsd));
143
+ if (ys.length === 0 || ys.length < guards.minSamples)
144
+ return off(`${basedOn}: ${ys.length} samples, below the minimum of ${Math.max(1, guards.minSamples)}`);
145
+ // If any price is 0, negative, infinite or NaN, turn off that day (avoids division by zero and abnormal amounts)
146
+ if (ys.some((s) => !Number.isFinite(s.tokenUsd) || !(s.tokenUsd > 0)))
147
+ return off(`${basedOn}: invalid (zero, negative or non-finite) price sample`);
148
+ const depths = ys.map((s) => (Number.isFinite(s.poolSolSideUsd) ? s.poolSolSideUsd : 0));
149
+ const minDepth = Math.min(...depths);
110
150
  if (minDepth < guards.minPoolSolSideUsd) {
111
151
  return off(`${basedOn}: lowest pool SOL-side depth ${minDepth.toFixed(0)} USD, below the minimum of ${guards.minPoolSolSideUsd} USD`);
112
152
  }
113
- const prices = ys.map((s) => s.a402Usd);
153
+ const prices = ys.map((s) => s.tokenUsd);
114
154
  const ratio = Math.max(...prices) / Math.min(...prices);
115
- if (ratio > guards.maxDailyRangeRatio) {
155
+ if (!Number.isFinite(ratio) || ratio > guards.maxDailyRangeRatio) {
116
156
  return off(`${basedOn}: max/min price ratio ${ratio.toFixed(2)}, above the limit of ${guards.maxDailyRangeRatio}`);
117
157
  }
118
158
  return {
119
- status: 'on', date, basedOn, a402Usd: median(prices), samples: ys.length,
159
+ status: 'on', date, basedOn, tokenUsd: median(prices), samples: ys.length,
120
160
  method: `median of ${ys.length} hourly samples on ${basedOn} (UTC) (lowest depth ${minDepth.toFixed(0)} USD, max/min ${ratio.toFixed(2)})`,
121
161
  };
122
162
  }
123
- /** A402 로 낼 금액 (원 단위). 0.02 USD × (1 − 30%) 를 고정 환율로 나누고 올림 */
124
- export function a402Amount(rate, decimals = 6) {
125
- const usd = (Number(PRICE_USDC_BASE_UNITS) / 1e6) * (1 - A402_DISCOUNT_BPS / 10_000);
126
- return BigInt(Math.ceil((usd / rate.a402Usd) * 10 ** decimals));
163
+ const U64_MAX = (1n << 64n) - 1n;
164
+ /**
165
+ * Token amount to pay (base units): priceUsd × (1 − discount) ÷ fixed rate, rounded up.
166
+ * Throws if the rate is 0, negative, infinite or NaN, or if the result exceeds u64 (so that request does not offer token payment)
167
+ */
168
+ export function tokenAmountFor(priceUsd, discountPercent, rate, decimals = 6) {
169
+ if (!Number.isFinite(rate.tokenUsd) || !(rate.tokenUsd > 0))
170
+ throw new Error('invalid token rate');
171
+ const usd = priceUsd * (1 - discountPercent / 100);
172
+ const units = Math.ceil((usd / rate.tokenUsd) * 10 ** decimals);
173
+ if (!Number.isFinite(units) || units <= 0)
174
+ throw new Error('token amount out of range');
175
+ const amount = BigInt(units);
176
+ if (amount > U64_MAX)
177
+ throw new Error('token amount out of range');
178
+ return amount;
179
+ }
180
+ /** Token amount (base units) at the default price (0.02 USD), no discount */
181
+ export function tokenAmount(rate, decimals = 6) {
182
+ return tokenAmountFor(Number(PRICE_USDC_BASE_UNITS) / 1e6, TOKEN_DISCOUNT_BPS / 100, rate, decimals);
127
183
  }
@@ -1,4 +1,4 @@
1
- // Node 전용 환율 저장소: JSON 파일 하나 (기록은 최근 3일치만 유지). Workers 에서는 쓰지 말 것 (node:fs)
1
+ // Node-only rate store: a single JSON file (keeps only the last 3 days of samples). Do not use on Workers (node:fs)
2
2
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
3
  import { dirname } from 'node:path';
4
4
  export function fileRateStore(path, keepDays = 3) {
@@ -11,7 +11,7 @@ export function fileRateStore(path, keepDays = 3) {
11
11
  mkdirSync(dirname(path), { recursive: true });
12
12
  const tmp = `${path}.tmp`;
13
13
  writeFileSync(tmp, JSON.stringify(s));
14
- renameSync(tmp, path); // 쓰다 끊겨도 원본이 깨지지 않게
14
+ renameSync(tmp, path); // so the original is not corrupted if writing is interrupted
15
15
  };
16
16
  return {
17
17
  async addSample(x) {
package/dist/rates.d.ts CHANGED
@@ -1,17 +1,17 @@
1
- import { type DailyRate, type PriceSample, type RateGuards } from './pricing.js';
1
+ import { type DailyRate, type PoolTarget, type PriceSample, type RateGuards } from './pricing.js';
2
2
  import type { AccountFetcher } from './chain.js';
3
3
  export interface RateStore {
4
4
  addSample(s: PriceSample): Promise<void>;
5
- /** UTC 날짜(YYYY-MM-DD) 하루치 기록 */
5
+ /** Samples for one UTC date (YYYY-MM-DD) */
6
6
  samples(day: string): Promise<PriceSample[]>;
7
7
  getRate(date: string): Promise<DailyRate | null>;
8
8
  putRate(r: DailyRate): Promise<void>;
9
9
  }
10
10
  export declare function memoryRateStore(): RateStore;
11
11
  export interface RateBook {
12
- /** 기록 하나 남기기 (매시간 cron 등에서). 오라클 품질 기준 밖이면 예외 — 기록하지 않음 */
12
+ /** Records one sample (e.g. from an hourly cron). Throws if outside the oracle quality bounds; nothing is recorded */
13
13
  record(): Promise<PriceSample>;
14
- /** 오늘(UTC) 고정 환율. 처음 물을 때 전날 기록으로 계산해 저장 */
14
+ /** Today's (UTC) fixed rate. Computed from the previous day's samples on first request and stored */
15
15
  today(): Promise<DailyRate>;
16
16
  }
17
17
  export declare function createRateBook(o: {
@@ -19,8 +19,5 @@ export declare function createRateBook(o: {
19
19
  fetcher?: AccountFetcher;
20
20
  guards?: RateGuards;
21
21
  now?: () => Date;
22
+ target?: PoolTarget;
22
23
  }): RateBook;
23
- /** A402 로 낼 금액 (원 단위): priceUsd × (1 − 할인) ÷ 고정 환율, 올림 */
24
- export declare function a402AmountFor(priceUsd: number, discountPercent: number, rate: Extract<DailyRate, {
25
- status: 'on';
26
- }>, decimals?: number): bigint;
package/dist/rates.js CHANGED
@@ -1,6 +1,7 @@
1
- // A402 환율: 매시간 기록 → 전날 기록의 중앙값으로 하루 고정 (안전장치에 걸리면 그날 A402 끔).
2
- // 저장소는 인터페이스 — 메모리(기본·테스트), 파일(Node: rates-file.ts), Durable Object(Workers 예제) 등
3
- import { DEFAULT_GUARDS, fixRate, samplePrice } from './pricing.js';
1
+ // Payment token (PREQ) rate: sampled hourly, then fixed for the day at the median of the previous day's samples (if a guard trips, token payments are off that day).
2
+ // Pool and mint addresses are read from preq.ts only (PoolTarget default). A402 (v1) is deprecated: only when passed explicitly (with a warning).
3
+ // The store is an interface: memory (default, tests), file (Node: rates-file.ts), Durable Object (Workers example), etc.
4
+ import { DEFAULT_GUARDS, fixRate, PREQ_POOL_TARGET, samplePrice } from './pricing.js';
4
5
  export function memoryRateStore() {
5
6
  const samples = [];
6
7
  const rates = new Map();
@@ -15,11 +16,12 @@ const prevDay = (d) => new Date(Date.parse(`${d}T00:00:00Z`) - 86_400_000).toISO
15
16
  export function createRateBook(o) {
16
17
  const now = o.now ?? (() => new Date());
17
18
  const guards = o.guards ?? DEFAULT_GUARDS;
19
+ const target = o.target ?? PREQ_POOL_TARGET;
18
20
  return {
19
21
  async record() {
20
22
  if (!o.fetcher)
21
23
  throw new Error('rate book: no account fetcher configured');
22
- const s = await samplePrice(o.fetcher, now, guards);
24
+ const s = await samplePrice(o.fetcher, now, guards, target);
23
25
  await o.store.addSample(s);
24
26
  return s;
25
27
  },
@@ -28,14 +30,11 @@ export function createRateBook(o) {
28
30
  const cached = await o.store.getRate(date);
29
31
  if (cached)
30
32
  return cached;
31
- const r = fixRate(date, await o.store.samples(prevDay(date)), guards);
33
+ // Samples of other tokens (e.g. old A402 samples without symbol) are not mixed in
34
+ const samples = (await o.store.samples(prevDay(date))).filter((s) => (s.symbol ?? 'A402') === target.symbol);
35
+ const r = fixRate(date, samples, guards);
32
36
  await o.store.putRate(r);
33
37
  return r;
34
38
  },
35
39
  };
36
40
  }
37
- /** A402 로 낼 금액 (원 단위): priceUsd × (1 − 할인) ÷ 고정 환율, 올림 */
38
- export function a402AmountFor(priceUsd, discountPercent, rate, decimals = 6) {
39
- const usd = priceUsd * (1 - discountPercent / 100);
40
- return BigInt(Math.ceil((usd / rate.a402Usd) * 10 ** decimals));
41
- }
@@ -0,0 +1,37 @@
1
+ export declare const RECEIPT_HEADER = "x-agent402-receipt";
2
+ export declare const RECEIPT_KIND = "agent402.x402-receipt";
3
+ export interface Receipt {
4
+ v: 1;
5
+ kind: typeof RECEIPT_KIND;
6
+ issuedAt: string;
7
+ /** path is the URL path and query as the server received it */
8
+ request: {
9
+ method: string;
10
+ path: string;
11
+ bodySha256: string | null;
12
+ };
13
+ response: {
14
+ status: number;
15
+ bodySha256: string;
16
+ };
17
+ payment: {
18
+ network: string;
19
+ asset: string;
20
+ amount: string;
21
+ payTo: string;
22
+ transaction: string | null;
23
+ };
24
+ /** Base58 Ed25519 public key of the receipt key */
25
+ signer: string;
26
+ }
27
+ export interface ReceiptSigner {
28
+ publicKey: string;
29
+ sign(data: Uint8Array): Promise<Uint8Array>;
30
+ }
31
+ export declare function b64url(u: Uint8Array): string;
32
+ export declare function b64urlDecode(s: string): Uint8Array;
33
+ export declare function sha256Hex(data: ArrayBuffer | Uint8Array): Promise<string>;
34
+ /** Receipt key from a Solana CLI key file (64 bytes: seed + public key) or a 32-byte seed */
35
+ export declare function receiptSignerFromBytes(bytes: Uint8Array): Promise<ReceiptSigner>;
36
+ /** Signs a receipt → header value "<base64url JSON>.<base64url signature>" (the signature covers the exact JSON bytes) */
37
+ export declare function signReceipt(signer: ReceiptSigner, r: Omit<Receipt, 'v' | 'kind' | 'signer'>): Promise<string>;
@@ -0,0 +1,50 @@
1
+ // Signed receipts (optional): after a settled payment the seller signs a small JSON record that binds
2
+ // the request, the hash of the response body and the payment. Buyers can keep it as evidence for disputes and settlement reports.
3
+ // Ed25519 through WebCrypto (Node 20+, Cloudflare Workers). Use a key made only for receipts, never the receiving wallet's key.
4
+ import { PublicKey } from '@solana/web3.js';
5
+ export const RECEIPT_HEADER = 'x-agent402-receipt';
6
+ export const RECEIPT_KIND = 'agent402.x402-receipt';
7
+ const PKCS8_ED25519_PREFIX = [0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20];
8
+ export function b64url(u) {
9
+ let s = '';
10
+ for (const b of u)
11
+ s += String.fromCharCode(b);
12
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
13
+ }
14
+ export function b64urlDecode(s) {
15
+ const b = atob(s.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (s.length % 4)) % 4));
16
+ return Uint8Array.from(b, (c) => c.charCodeAt(0));
17
+ }
18
+ export async function sha256Hex(data) {
19
+ const d = new Uint8Array(await crypto.subtle.digest('SHA-256', data));
20
+ return Array.from(d, (b) => b.toString(16).padStart(2, '0')).join('');
21
+ }
22
+ /** Receipt key from a Solana CLI key file (64 bytes: seed + public key) or a 32-byte seed */
23
+ export async function receiptSignerFromBytes(bytes) {
24
+ if (bytes.length !== 64 && bytes.length !== 32)
25
+ throw new Error('receipt key must be 64 bytes (Solana CLI key file) or a 32-byte seed');
26
+ const pkcs8 = new Uint8Array(48);
27
+ pkcs8.set(PKCS8_ED25519_PREFIX);
28
+ pkcs8.set(bytes.subarray(0, 32), 16);
29
+ try {
30
+ // Exportable copy only to read the public key; the signing key is not exportable
31
+ const tmp = await crypto.subtle.importKey('pkcs8', pkcs8, { name: 'Ed25519' }, true, ['sign']);
32
+ const pub = b64urlDecode((await crypto.subtle.exportKey('jwk', tmp)).x);
33
+ if (bytes.length === 64 && b64url(pub) !== b64url(bytes.subarray(32)))
34
+ throw new Error('receipt key: the public key does not match the secret');
35
+ const key = await crypto.subtle.importKey('pkcs8', pkcs8, { name: 'Ed25519' }, false, ['sign']);
36
+ return {
37
+ publicKey: new PublicKey(pub).toBase58(),
38
+ async sign(data) { return new Uint8Array(await crypto.subtle.sign('Ed25519', key, data)); },
39
+ };
40
+ }
41
+ finally {
42
+ pkcs8.fill(0);
43
+ }
44
+ }
45
+ /** Signs a receipt → header value "<base64url JSON>.<base64url signature>" (the signature covers the exact JSON bytes) */
46
+ export async function signReceipt(signer, r) {
47
+ const receipt = { v: 1, kind: RECEIPT_KIND, ...r, signer: signer.publicKey };
48
+ const bytes = new TextEncoder().encode(JSON.stringify(receipt));
49
+ return `${b64url(bytes)}.${b64url(await signer.sign(bytes))}`;
50
+ }
package/dist/x402.d.ts CHANGED
@@ -6,19 +6,20 @@ type TxRecordWithInstructions = ChainTx;
6
6
  export declare const SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
7
7
  export declare const SOLANA_DEVNET = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
8
8
  export interface Asset {
9
- symbol: 'USDC' | 'A402';
9
+ /** A402 is deprecated (v1). Only when enabled explicitly (prints a warning) */
10
+ symbol: 'USDC' | 'PREQ' | 'A402';
10
11
  mint: string;
11
12
  decimals: number;
12
- /** SPL Token 또는 Token-2022 프로그램 주소 */
13
+ /** SPL Token or Token-2022 program address */
13
14
  tokenProgram: string;
14
15
  }
15
16
  export interface Offer {
16
17
  asset: Asset;
17
18
  amount: bigint;
18
- /** A402 일 때 환율 근거 (extra.rate 로 공개) */
19
+ /** For tokens (PREQ, etc.), the rate basis (published as extra.rate). tokenUsd = USD per token */
19
20
  rate?: {
20
21
  date: string;
21
- a402Usd: number;
22
+ tokenUsd: number;
22
23
  method: string;
23
24
  discountPercent: number;
24
25
  };
@@ -29,9 +30,9 @@ export interface NamedFacilitator {
29
30
  }
30
31
  export interface X402Config {
31
32
  network: string;
32
- /** 수령 지갑 공개 주소 */
33
+ /** Public address of the receiving wallet */
33
34
  payTo: string;
34
- /** 앞쪽이 기본, 뒤쪽이 예비 */
35
+ /** First is primary, the rest are fallbacks */
35
36
  facilitators: NamedFacilitator[];
36
37
  maxTimeoutSeconds: number;
37
38
  }
@@ -41,24 +42,24 @@ interface Chosen {
41
42
  transactionVersions?: unknown;
42
43
  server: x402ResourceServer;
43
44
  }
44
- /** 기본 → 예비 순서로, 이 네트워크 exact 를 지원하는 첫 facilitator */
45
+ /** First facilitator, primary then fallbacks, that supports exact on this network */
45
46
  export declare function chooseFacilitator(cfg: X402Config, nowMs: number): Promise<Chosen | null>;
46
- /** 결제 조건의 feePayer 를 쓰는 facilitator (정산은 반드시 그 facilitator 로) */
47
+ /** Facilitator using the feePayer in the payment requirements (settlement must go to that facilitator) */
47
48
  export declare function facilitatorForFeePayer(cfg: X402Config, feePayer: unknown, nowMs: number): Promise<Chosen | null>;
48
49
  export declare function clearSupportedCache(): void;
49
- /** 결제 조건 만들기 — 공식 x402ResourceServer.buildPaymentRequirementsFromOptions (feePayer·transactionVersions 는 공식 SVM 서버가 채움) */
50
+ /** Builds payment requirements with the official x402ResourceServer.buildPaymentRequirementsFromOptions (the official SVM server fills feePayer and transactionVersions) */
50
51
  export declare function buildRequirements(cfg: X402Config, offers: Offer[], chosen: Chosen): Promise<PaymentRequirements[]>;
51
52
  export interface X402Ledger {
52
53
  /**
53
- * 결제(키)를 잡음.
54
- * new: 처음 → 정산 진행 / settled: 정산은 끝났고 리포트를 못 받은 결제 → 정산 건너뜀
55
- * in_progress·fulfilled: 거절
54
+ * Claims the payment (key).
55
+ * new: first time → proceed to settle / settled: settled but the report was not received → skip settlement
56
+ * in_progress, fulfilled: reject
56
57
  */
57
58
  claim(key: string, nowMs: number): Promise<{
58
59
  ok: true;
59
60
  state: 'new';
60
61
  }
61
- /** 지난번 정산 요청의 결과를 모름 — 체인에서 판정해야 함 */
62
+ /** The result of the previous settle request is unknown; must be decided on-chain */
62
63
  | {
63
64
  ok: true;
64
65
  state: 'settle_unknown';
@@ -67,15 +68,15 @@ export interface X402Ledger {
67
68
  ok: false;
68
69
  state: 'in_progress' | 'fulfilled';
69
70
  }>;
70
- /** 정산 요청 결과를 모름 (시간 초과 등) */
71
+ /** The settle request result is unknown (timeout, etc.) */
71
72
  markSettleUnknown(key: string, nowMs: number): Promise<void>;
72
73
  fulfill(key: string, nowMs: number): Promise<void>;
73
- /** 정산 전 실패 → 풀어 줌 */
74
+ /** Failed before settlement → release */
74
75
  release(key: string): Promise<void>;
75
76
  }
76
77
  /**
77
- * 정산 결과를 모를 때, 이 시간이 지나도 체인에 없으면 그 트랜잭션은 더는 처리될 수 없음
78
- * (blockhash 유효 150블록 ≈ 60~90초에 여유를 둠)
78
+ * When the settlement result is unknown and the transaction is still not on-chain after this time, it can no longer be processed
79
+ * (blockhash is valid for 150 blocks ≈ 60 to 90 s, with margin)
79
80
  */
80
81
  export declare const SETTLE_UNKNOWN_EXPIRY_MS = 150000;
81
82
  type LedgerEntry = {
@@ -88,7 +89,7 @@ type LedgerEntry = {
88
89
  state: 'fulfilled';
89
90
  at: number;
90
91
  };
91
- /** 장부 상태 전이 (Durable Object 와 메모리 구현이 같이 씀) */
92
+ /** Ledger state transitions (shared by the Durable Object and memory implementations) */
92
93
  export declare function ledgerClaim(e: LedgerEntry | undefined, nowMs: number): {
93
94
  next: LedgerEntry;
94
95
  result: {
@@ -130,25 +131,25 @@ export declare function sha256Hex(s: string): Promise<string>;
130
131
  export interface ProcessDeps {
131
132
  cfg: X402Config;
132
133
  ledger: X402Ledger;
133
- /** 결제 네트워크에서 트랜잭션 읽기 (체인 재확인) */
134
+ /** Reads transactions on the payment network (on-chain recheck) */
134
135
  loadTx: (signature: string) => Promise<TxRecordWithInstructions | null>;
135
- /** 결제 네트워크에서 주소의 최근 서명 (정산 결과를 모를 때 판정용) */
136
+ /** Recent signatures for an address on the payment network (to decide when the settlement result is unknown) */
136
137
  recentSignatures: (address: string, limit: number) => Promise<string[]>;
137
- /** 결제 수단 민트 → 토큰 프로그램 (수령 토큰 계정 주소 계산용) */
138
+ /** Payment asset mint → token program (to compute the receiving token account address) */
138
139
  tokenProgramOf: (mint: string) => string;
139
140
  nowMs: number;
140
- /** 체인 재확인 재시도 간격 */
141
+ /** Retry intervals for the on-chain recheck */
141
142
  confirmDelaysMs?: number[];
142
143
  }
143
- /** 검증까지 끝난 결제 (아직 돈은 나가지 않음) */
144
+ /** A payment that passed verification (no money has moved yet) */
144
145
  export interface VerifiedPayment {
145
146
  key: string;
146
147
  payload: PaymentPayload;
147
148
  accepted: PaymentRequirements;
148
149
  facilitator: NamedFacilitator;
149
- /** 그 facilitator 를 감싼 공식 리소스 서버 (verify·settle 호출) */
150
+ /** Official resource server wrapping that facilitator (calls verify and settle) */
150
151
  server: x402ResourceServer;
151
- /** 지난번 정산 결과를 모르는 결제를 다시 처리하는 중이면 그 시각 */
152
+ /** If reprocessing a payment whose previous settlement result is unknown, its time */
152
153
  settleUnknownSince: number | null;
153
154
  }
154
155
  export type VerifyOutcome = {
@@ -173,27 +174,27 @@ export type SettleOutcome = {
173
174
  kind: 'unavailable';
174
175
  message: string;
175
176
  }
176
- /** confirmation: confirmed = 우리 RPC 로 체인에서 확인 / pending = facilitator 는 성공, 체인 확인은 아직 */
177
+ /** confirmation: confirmed = confirmed on-chain with our RPC / pending = facilitator reported success, not yet confirmed on-chain */
177
178
  | {
178
179
  kind: 'paid';
179
180
  settlement: SettleResponse;
180
181
  confirmation: 'confirmed' | 'pending';
181
182
  };
182
- /** 부분 서명된 트랜잭션(base64)에서 이미 채워진 서명들 (구매자 서명). 비어 있는 자리(전부 0)는 뺌 */
183
+ /** Signatures already filled in a partially signed transaction (base64) (the buyer's signatures). Empty slots (all zeros) are left out */
183
184
  export declare function presentSignatures(txBase64: string): string[];
184
185
  /**
185
- * 정산 결과를 모를 때 체인에서 판정: 수령 토큰 계정의 최근 기록 중 구매자 서명이 들어 있는 트랜잭션을 찾음.
186
- * 찾으면 그 트랜잭션, 없으면 null
186
+ * Decides on-chain when the settlement result is unknown: finds a transaction containing the buyer's signature among recent records of the receiving token account.
187
+ * Returns that transaction if found, otherwise null
187
188
  */
188
189
  export declare function findSettledOnChain(v: VerifiedPayment, d: ProcessDeps): Promise<TxRecordWithInstructions | null>;
189
190
  /**
190
- * 1단계: PAYMENT-SIGNATURE 확인 → 장부에서 잡기 → facilitator /verify. 돈은 아직 나가지 않음.
191
- * 호출자는 이 다음에 리포트를 만들고, 성공했을 때만 settleVerified 를 부름
191
+ * Step 1: check PAYMENT-SIGNATURE → claim in the ledger → facilitator /verify. No money moves yet.
192
+ * The caller then builds the report and calls settleVerified only on success
192
193
  */
193
194
  export declare function verifyPaymentHeader(header: string, resourcePath: string, current: PaymentRequirements[], d: ProcessDeps): Promise<VerifyOutcome>;
194
195
  /**
195
- * 2단계 (리포트를 만든 뒤에만): facilitator /settle → 우리 RPC 로 체인 재확인.
196
- * 정산 결과를 모르면(시간 초과 등) 체인에서 구매자 서명으로 판정하고, 그래도 모르면 "결과 모름"으로 남김
196
+ * Step 2 (only after the report is built): facilitator /settle → on-chain recheck with our RPC.
197
+ * If the settlement result is unknown (timeout, etc.), decide on-chain by the buyer's signature; if still unknown, leave it as "result unknown"
197
198
  */
198
199
  export declare function settleVerified(v: VerifiedPayment, d: ProcessDeps): Promise<SettleOutcome>;
199
200
  export declare function paymentResponseHeader(s: SettleResponse): string;