@agent402-dev/pay-server 0.1.0 → 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/README.md CHANGED
@@ -1,15 +1,16 @@
1
1
  # @agent402-dev/pay-server
2
2
 
3
- Server helpers for [x402](https://github.com/coinbase/x402) payments on Solana that accept **USDC** and, optionally, **A402** (a Token-2022 token) through standard x402 facilitators.
3
+ > **A402 (v1) is deprecated.** The token payment option is now **PREQ** (mint `aTbGw3gU5JyJkAdXLj8rYZ3mCXkPbyHjtTAyCX3jQLX`). Official addresses: https://claude.ai/artifact/S6UafAfViJk3DJeMsDMAja
4
+
5
+ Server helpers for [x402](https://github.com/coinbase/x402) payments on Solana that accept **USDC** and, optionally, **PREQ** (a Token-2022 token) through standard x402 facilitators.
4
6
 
5
7
  Part of the [Agent402 toolkit](https://github.com/agent402-dev/agent402-toolkit) (Solana).
6
8
  Not related to `agent402.tools`, `@agents402` or other similarly named sites, accounts or projects, including projects named "a402" on other chains.
7
9
 
8
10
  > This package moves no funds itself and gives no opinion on any token. Rates and amounts are facts computed from public on-chain data, not investment advice.
9
- > 공개 온체인 데이터에 따른 사실 정보이며 투자 권유가 아닙니다.
10
11
 
11
12
  ## What it does
12
- - Builds x402 v2 `exact` payment requirements per request with the official `@x402/core` `x402ResourceServer` (USDC, plus A402 when it can be offered).
13
+ - Builds x402 v2 `exact` payment requirements per request with the official `@x402/core` `x402ResourceServer` (USDC, plus PREQ when it can be offered).
13
14
  - Order of work: **verify → your handler → settle**. If your handler fails, times out (default 40 s), or returns a status ≥ 400, the payment is **not settled**.
14
15
  - If a settlement fails or its result is unknown, it checks the chain for the buyer's transaction before answering. It treats the payment as not taken only after the transaction can no longer land (about 150 s).
15
16
  - Keeps a ledger so a payment cannot be used twice.
@@ -20,26 +21,32 @@ Not related to `agent402.tools`, `@agents402` or other similarly named sites, ac
20
21
  - It **does not judge, score or rate tokens** and gives no investment advice.
21
22
  - It **does not operate a facilitator.** Verification and settlement are done by the external facilitators you configure.
22
23
  - It **does not hold funds.** Payments go from the buyer's wallet directly to your receiving address.
23
- - It **does not exchange** currencies. The A402 rate is used only to compute the A402 amount; there is no A402 ↔ USDC conversion.
24
+ - It **does not exchange** currencies. The PREQ rate is used only to compute the PREQ amount; there is no PREQ ↔ USDC conversion.
24
25
  - It **does not accept or send payments on anyone's behalf.** Your server receives only your receiving address (public key); there is no API that takes a private key.
25
26
 
26
- ## A402 option
27
- A402 is offered only when all of these hold for the request:
28
- 1. The selected facilitator is configured to accept A402.
29
- 2. Your receiving address has an A402 (Token-2022) token account. `exact` payments do not create the receiving account; create it in advance. The same applies to USDC.
30
- 3. The day's A402 rate is available. The rate is the median of the previous UTC day's hourly samples (Meteora DAMM v2 pool price × Pyth SOL/USD). It is switched off for the day when there are fewer than 12 samples, the pool's SOL-side depth fell below 100 USD, or the max/min ratio exceeded 1.5. These thresholds are configurable.
27
+ ## PREQ option
28
+ PREQ is offered only when all of these hold for the request:
29
+ 1. The selected facilitator is configured to accept PREQ.
30
+ 2. Your receiving address has a PREQ (Token-2022) token account. `exact` payments do not create the receiving account; create it in advance. The same applies to USDC.
31
+ 3. The day's PREQ rate is available. The rate is the median of the previous UTC day's hourly samples (Meteora DAMM v2 PREQ/SOL pool price × Pyth SOL/USD). It is switched off for the day when there are fewer than 12 samples, the pool's SOL-side depth fell below 100 USD, the max/min ratio exceeded 1.5, or any sample has a zero or non-finite price. These thresholds are configurable. Right after trading starts, a single-sided pool holds almost no SOL, so the depth rule keeps PREQ off until the pool has SOL-side depth.
32
+
33
+ When PREQ is not offered, the 402 response lists it under `notOffered` with the reason.
31
34
 
32
- When A402 is not offered, the 402 response lists it under `notOffered` with the reason.
35
+ **PREQ addresses.** `PREQ_MAINNET` (mint) and the pricing pool address are kept in one place, `src/preq.ts`. Until they are filled in, enabling PREQ (`config.preq` with `PREQ_MAINNET`, or `rates.record()`) stops with an error that names the missing value.
33
36
 
34
- **Units.** As in every x402 requirement, `amount` is in the token's smallest unit. USDC and A402 both have 6 decimals: 1 USDC = 1,000,000 smallest units, 1 A402 = 1,000,000 smallest units. For example, an A402 `amount` of `140000000000` is 140,000 A402. The A402 amount is `priceUsd × (1 − discountPercent / 100) ÷ (A402 rate in USD)`, rounded up to the smallest unit.
37
+ **Units.** As in every x402 requirement, `amount` is in the token's smallest unit. USDC and PREQ both have 6 decimals: 1 USDC = 1,000,000 smallest units, 1 PREQ = 1,000,000 smallest units. For example, a PREQ `amount` of `140000000000` is 140,000 PREQ. The PREQ amount is `priceUsd ÷ (PREQ rate in USD)`, rounded up to the smallest unit: the same USD price as USDC. (`discountPercent` exists as an optional setting and defaults to 0.)
38
+
39
+ **A402 (v1).** A402 is deprecated and is not part of any default. `A402_MAINNET` and `config.a402` remain only for existing setups; passing `config.a402` prints the warning "A402 (v1) is deprecated and no longer supported; use PREQ.". Nothing is paid in A402 unless you configure it explicitly.
35
40
 
36
41
  ## Facilitators (facts as checked on Solana mainnet, 2026-11-19)
37
- | Facilitator | USDC `exact` | A402 (Token-2022) `exact` |
42
+ | Facilitator | USDC `exact` | A402 (v1, deprecated; Token-2022) `exact` |
38
43
  |---|---|---|
39
44
  | PayAI `https://facilitator.payai.network` | verify and settle succeeded | verify and settle succeeded (fee paid by the facilitator's fee payer) |
40
45
  | Dexter `https://x402.dexter.cash` | listed in `/supported`; at the time of the check, verify returned `transaction_simulation_failed` because its fee payer account held 0.000656 SOL | verify returned `policy:asset_not_allowed` (A402 is not in its asset allowlist) |
41
46
 
42
- These are observations from one day. Facilitator policies and balances change; `KNOWN_FACILITATORS` only provides defaults that you can override.
47
+ PREQ has not been checked on a hosted facilitator yet. On 2026-11-22 a PREQ payment was verified and settled end to end in a local mainnet-fork rehearsal (Surfpool, with the official x402 facilitator code `@x402/svm` exact scheme and the real PREQ mint). `KNOWN_FACILITATORS.payai` lists PREQ because PayAI's `/supported` shows no asset restriction for the Solana `exact` scheme and it accepted a Token-2022 token in the check above. These are observations from one day. Facilitator policies and balances change; `KNOWN_FACILITATORS` only provides defaults that you can override.
48
+
49
+ **Facilitator fees.** As of 2026-11-22, PayAI's documentation describes a free tier of up to 10,000 settlements per month without an API key, and paid credits with an API key beyond that. Check the facilitator's current terms before production use.
43
50
 
44
51
  ## Install
45
52
  ```bash
@@ -49,16 +56,16 @@ Node 20+ or Cloudflare Workers (`nodejs_compat`). ESM only.
49
56
 
50
57
  ## Usage
51
58
  ```ts
52
- import { createPaymentGate, rpcChain, KNOWN_FACILITATORS, SOLANA_MAINNET, USDC_MAINNET, A402_MAINNET,
59
+ import { createPaymentGate, rpcChain, KNOWN_FACILITATORS, SOLANA_MAINNET, USDC_MAINNET, PREQ_MAINNET,
53
60
  createRateBook, memoryRateStore } from '@agent402-dev/pay-server';
54
61
 
55
- const rates = createRateBook({ store: memoryRateStore(), fetcher: rpcChain(RPC_URL).accounts });
62
+ const rates = createRateBook({ store: memoryRateStore(), fetcher: rpcChain(RPC_URL).accounts }); // PREQ pool from src/preq.ts
56
63
  const gate = createPaymentGate({
57
64
  network: SOLANA_MAINNET,
58
65
  payTo: 'YOUR_RECEIVING_ADDRESS',
59
66
  priceUsd: 0.02, // example setting
60
67
  usdc: USDC_MAINNET,
61
- a402: { asset: A402_MAINNET, discountPercent: 30 /* example setting — choose your own */, rate: () => rates.today() },
68
+ preq: { asset: PREQ_MAINNET, rate: () => rates.today() },
62
69
  facilitators: [KNOWN_FACILITATORS.payai, KNOWN_FACILITATORS.dexter],
63
70
  chain: rpcChain(RPC_URL),
64
71
  });
@@ -74,4 +81,4 @@ Rate stores: `memoryRateStore()` (default, tests), `fileRateStore(path)` from `@
74
81
  Apache-2.0. See [LICENSE](https://github.com/agent402-dev/agent402-toolkit/blob/main/LICENSE) and [NOTICE](https://github.com/agent402-dev/agent402-toolkit/blob/main/NOTICE).
75
82
 
76
83
  ---
77
- Factual information from public on-chain data. Not investment advice. / 공개 온체인 데이터에 따른 사실 정보이며 투자 권유가 아닙니다.
84
+ Factual information from public on-chain data. Not investment advice.
package/dist/chain.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- /** 정산 확인에 필요한 트랜잭션 정보 */
1
+ /** Transaction info needed to confirm settlement */
2
2
  export interface ChainTx {
3
3
  signature: string;
4
4
  err: boolean;
5
- /** 0번 = 수수료 낸 주소 */
5
+ /** Index 0 = fee payer */
6
6
  accountKeys: string[];
7
7
  preTokenBalances: {
8
8
  accountIndex: number;
@@ -16,7 +16,7 @@ export interface ChainTx {
16
16
  owner?: string | null;
17
17
  amount: string;
18
18
  }[];
19
- /** 트랜잭션의 모든 서명 (구매자 서명 찾기용) */
19
+ /** All signatures in the transaction (to find the buyer's signature) */
20
20
  signatures: string[];
21
21
  }
22
22
  export interface ChainAccount {
@@ -33,16 +33,16 @@ export interface ChainReader {
33
33
  recentSignatures(address: string, limit: number): Promise<string[]>;
34
34
  accounts: AccountFetcher;
35
35
  }
36
- /** 이 결제 수단의 수령 주소 증가량 (수령 주소가 소유한 그 민트 토큰 계정 합) */
36
+ /** Increase at the receiving address for this payment asset (sum of that mint's token accounts owned by the receiver) */
37
37
  export declare function receivedBy(tx: ChainTx, owner: string, mint: string): bigint;
38
38
  export interface RpcOptions {
39
39
  fetchImpl?: typeof fetch;
40
40
  commitment?: 'confirmed' | 'finalized';
41
41
  }
42
- /** JSON-RPC 로 ChainReader 만들기. RPC 주소(키 포함일 수 있음)는 오류 메시지에 넣지 않음 */
42
+ /** Builds a ChainReader over JSON-RPC. The RPC address (which may contain a key) is never put in error messages */
43
43
  export declare function rpcChain(rpcUrl: string, o?: RpcOptions): ChainReader;
44
44
  export declare const SPL_TOKEN = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
45
45
  export declare const TOKEN_2022 = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb";
46
- /** 연결 토큰 계정(ATA) 주소 */
46
+ /** Associated token account (ATA) address */
47
47
  export declare function ataOf(owner: string, mint: string, tokenProgram: string): Promise<string>;
48
48
  export declare function base58Encode(bytes: Uint8Array): string;
package/dist/chain.js CHANGED
@@ -1,12 +1,12 @@
1
- // SDK 가 체인에서 읽는 것 (점검 엔진에 기대지 않는 최소 구현). fetch 만 씀 → Cloudflare Workers·Node 모두.
2
- // - 정산 트랜잭션 읽기 (수령 증가액 확인), 수령 토큰 계정의 최근 서명 (정산 결과를 모를 때 판정)
3
- // - 계정 여러 개 읽기 (환율 기록·받는 쪽 토큰 계정 확인)
4
- /** 이 결제 수단의 수령 주소 증가량 (수령 주소가 소유한 그 민트 토큰 계정 합) */
1
+ // What the SDK reads from the chain (minimal implementation, independent of the check engine). Uses only fetch, so it runs on Cloudflare Workers and Node.
2
+ // - Reads settlement transactions (checks the received increase) and recent signatures of receiving token accounts (to decide when the settlement result is unknown)
3
+ // - Reads multiple accounts (rate recording, checking the receiver's token account)
4
+ /** Increase at the receiving address for this payment asset (sum of that mint's token accounts owned by the receiver) */
5
5
  export function receivedBy(tx, owner, mint) {
6
6
  const sum = (xs) => xs.filter((b) => b.owner === owner && b.mint === mint).reduce((s, b) => s + BigInt(b.amount), 0n);
7
7
  return sum(tx.postTokenBalances) - sum(tx.preTokenBalances);
8
8
  }
9
- /** JSON-RPC 로 ChainReader 만들기. RPC 주소(키 포함일 수 있음)는 오류 메시지에 넣지 않음 */
9
+ /** Builds a ChainReader over JSON-RPC. The RPC address (which may contain a key) is never put in error messages */
10
10
  export function rpcChain(rpcUrl, o = {}) {
11
11
  const f = o.fetchImpl ?? fetch;
12
12
  const commitment = o.commitment ?? 'confirmed';
@@ -42,11 +42,11 @@ export function rpcChain(rpcUrl, o = {}) {
42
42
  },
43
43
  };
44
44
  }
45
- // ---------- 주소 ----------
45
+ // ---------- Addresses ----------
46
46
  export const SPL_TOKEN = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
47
47
  export const TOKEN_2022 = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';
48
48
  const ATA_PROGRAM = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';
49
- /** 연결 토큰 계정(ATA) 주소 */
49
+ /** Associated token account (ATA) address */
50
50
  export async function ataOf(owner, mint, tokenProgram) {
51
51
  const { PublicKey } = await import('@solana/web3.js');
52
52
  return PublicKey.findProgramAddressSync([new PublicKey(owner).toBuffer(), new PublicKey(tokenProgram).toBuffer(), new PublicKey(mint).toBuffer()], new PublicKey(ATA_PROGRAM))[0].toBase58();
package/dist/core.d.ts CHANGED
@@ -1,22 +1,22 @@
1
1
  import { x402ResourceServer, type FacilitatorClient } from '@x402/core/server';
2
2
  import type { PaymentPayload, PaymentRequirements } from '@x402/core/types';
3
- /** facilitator 하나를 감싼 공식 리소스 서버 (그 facilitator 의 /supported 로 초기화) */
3
+ /** Official resource server wrapping one facilitator (initialized from that facilitator's /supported) */
4
4
  export declare function createCoreServer(client: FacilitatorClient, network: string): Promise<x402ResourceServer>;
5
- /** 공식 매칭 규칙으로, 결제가 고른 조건(accepted)과 같은 지금 조건 */
5
+ /** The current requirement equal to the one the payment chose (accepted), using the official matching rules */
6
6
  export declare function matchRequirement(current: PaymentRequirements[], payload: PaymentPayload, network: string): PaymentRequirements | undefined;
7
7
  export interface CoreOffer {
8
8
  asset: string;
9
9
  amount: string;
10
10
  extra: Record<string, unknown>;
11
11
  }
12
- /** 공식 서버로 결제 조건 만들기 (요청마다 결제 수단 목록은 호출자가 정함) */
12
+ /** Builds payment requirements with the official server (the caller decides the payment assets per request) */
13
13
  export declare function buildCoreRequirements(server: x402ResourceServer, network: string, payTo: string, maxTimeoutSeconds: number, offers: CoreOffer[]): Promise<PaymentRequirements[]>;
14
14
  /**
15
- * 정산 예외에 facilitator 가 적어 보낸 실패 이유 (있으면). 기록·안내용일 뿐 — 실패 응답이어도 facilitator 가 tx 를 보낸 뒤
16
- * 확정 대기 시간 초과로 실패를 돌려줄 수 있으므로, 결과는 언제나 체인에서 판정함
15
+ * Failure reason the facilitator sent in a settle exception, if any. For logging and messages only: even with a failure response, the facilitator may have sent the tx
16
+ * and then timed out waiting for confirmation, so the result is always decided on-chain
17
17
  */
18
18
  export declare function settleFailureReason(e: unknown): string | null;
19
- /** verify 예외가 "확실한 거절 응답"인지 (4xx + invalidReason) */
19
+ /** Whether a verify exception is a "definite rejection" (4xx + invalidReason) */
20
20
  export declare function definiteVerifyRejection(e: unknown): {
21
21
  reason: string;
22
22
  message?: string;
package/dist/core.js CHANGED
@@ -1,16 +1,16 @@
1
- // 공식 @x402/core x402ResourceServer 위에 얹는 부분 (2주차 시제품).
2
- // 공식 코드가 맡는 것: /supported 읽기, 결제 조건 만들기(parsePrice·feePayer·transactionVersions 채우기),
3
- // 결제와 조건 맞추기(findMatchingRequirements), facilitator verify·settle 호출
4
- // 우리가 맡는 것(x402.ts): facilitator 장애 시 예비로, 요청마다 결제 수단 고르기, 재사용 방지 장부, 체인 판정·재확인
1
+ // Layer on top of the official @x402/core x402ResourceServer.
2
+ // The official code handles: reading /supported, building payment requirements (parsePrice, filling feePayer and transactionVersions),
3
+ // matching payments to requirements (findMatchingRequirements), and calling facilitator verify and settle
4
+ // What we handle (x402.ts): fallback when a facilitator is down, choosing payment assets per request, the replay-protection ledger, on-chain decisions and rechecks
5
5
  import { x402ResourceServer } from '@x402/core/server';
6
6
  import { ExactSvmScheme } from '@x402/svm/exact/server';
7
- /** facilitator 하나를 감싼 공식 리소스 서버 (그 facilitator 의 /supported 로 초기화) */
7
+ /** Official resource server wrapping one facilitator (initialized from that facilitator's /supported) */
8
8
  export async function createCoreServer(client, network) {
9
9
  const server = new x402ResourceServer(client).register(network, new ExactSvmScheme());
10
10
  await server.initialize();
11
11
  return server;
12
12
  }
13
- /** facilitator 없이 조건 맞추기만 하는 서버 (네트워크별 하나) */
13
+ /** Server that only matches requirements, without a facilitator (one per network) */
14
14
  const matchers = new Map();
15
15
  function matcher(network) {
16
16
  let m = matchers.get(network);
@@ -20,7 +20,7 @@ function matcher(network) {
20
20
  }
21
21
  return m;
22
22
  }
23
- /** 공식 매칭 규칙으로, 결제가 고른 조건(accepted)과 같은 지금 조건 */
23
+ /** The current requirement equal to the one the payment chose (accepted), using the official matching rules */
24
24
  export function matchRequirement(current, payload, network) {
25
25
  try {
26
26
  return matcher(network).findMatchingRequirements(current, payload);
@@ -29,7 +29,7 @@ export function matchRequirement(current, payload, network) {
29
29
  return undefined;
30
30
  }
31
31
  }
32
- /** 공식 서버로 결제 조건 만들기 (요청마다 결제 수단 목록은 호출자가 정함) */
32
+ /** Builds payment requirements with the official server (the caller decides the payment assets per request) */
33
33
  export function buildCoreRequirements(server, network, payTo, maxTimeoutSeconds, offers) {
34
34
  return server.buildPaymentRequirementsFromOptions(offers.map((o) => ({
35
35
  scheme: 'exact',
@@ -40,8 +40,8 @@ export function buildCoreRequirements(server, network, payTo, maxTimeoutSeconds,
40
40
  })), {});
41
41
  }
42
42
  /**
43
- * 정산 예외에 facilitator 가 적어 보낸 실패 이유 (있으면). 기록·안내용일 뿐 — 실패 응답이어도 facilitator 가 tx 를 보낸 뒤
44
- * 확정 대기 시간 초과로 실패를 돌려줄 수 있으므로, 결과는 언제나 체인에서 판정함
43
+ * Failure reason the facilitator sent in a settle exception, if any. For logging and messages only: even with a failure response, the facilitator may have sent the tx
44
+ * and then timed out waiting for confirmation, so the result is always decided on-chain
45
45
  */
46
46
  export function settleFailureReason(e) {
47
47
  const err = e;
@@ -49,7 +49,7 @@ export function settleFailureReason(e) {
49
49
  return `${err.errorReason}${typeof err.statusCode === 'number' ? ` (HTTP ${err.statusCode})` : ''}`;
50
50
  return null;
51
51
  }
52
- /** verify 예외가 "확실한 거절 응답"인지 (4xx + invalidReason) */
52
+ /** Whether a verify exception is a "definite rejection" (4xx + invalidReason) */
53
53
  export function definiteVerifyRejection(e) {
54
54
  const err = e;
55
55
  if (err?.name === 'VerifyError' && typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 500 && err.invalidReason) {
package/dist/gate.d.ts CHANGED
@@ -1,20 +1,31 @@
1
1
  import { type FacilitatorClient } from '@x402/core/server';
2
2
  import type { PaymentRequirements } from '@x402/core/types';
3
3
  import { type ChainReader } from './chain.js';
4
- import type { DailyRate } from './pricing.js';
4
+ import { type DailyRate } from './pricing.js';
5
5
  import { type Asset, type X402Ledger } from './x402.js';
6
- export type AssetSymbol = 'USDC' | 'A402';
6
+ /** A402 is deprecated (v1) */
7
+ export type AssetSymbol = 'USDC' | 'PREQ' | 'A402';
8
+ /** Settings for a token accepted in addition to USDC */
9
+ export interface TokenPayment {
10
+ asset: Asset;
11
+ /** Optional. Default 0: the token is charged the same USD price as USDC */
12
+ discountPercent?: number;
13
+ /** Today's fixed rate. If off or failing, that request does not offer this token */
14
+ rate: () => Promise<DailyRate | null>;
15
+ }
7
16
  export interface FacilitatorSpec {
8
17
  name: string;
9
- /** url 또는 client 중 하나 */
18
+ /** Either url or client */
10
19
  url?: string;
11
20
  client?: FacilitatorClient;
12
- /** 이 facilitator 가 받는 결제 자산. 받지 않는 자산은 402 에 넣지 않음 */
21
+ /** Payment assets this facilitator accepts. Assets it does not accept are not put in the 402 */
13
22
  assets: AssetSymbol[];
14
23
  }
15
24
  /**
16
- * 확인된 facilitator (2026-11-19 메인넷에서 verify·settle 로 확인한 사실 — docs: README "Facilitators").
17
- * 정책·상태는 바뀔 수 있으므로 기본값일 뿐, 설정으로 덮어쓸 수 있음
25
+ * Facilitator defaults. Policies and status can change, so these are only defaults and can be overridden in config.
26
+ * - USDC: confirmed with mainnet verify and settle on 2026-11-19 (PayAI, Dexter)
27
+ * - A402 (v1, deprecated): record of a check on PayAI on 2026-11-19
28
+ * - 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
18
29
  */
19
30
  export declare const KNOWN_FACILITATORS: {
20
31
  readonly payai: {
@@ -31,31 +42,37 @@ export declare const KNOWN_FACILITATORS: {
31
42
  export declare const SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
32
43
  export declare const SOLANA_DEVNET = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
33
44
  export declare const USDC_MAINNET: Asset;
45
+ /** PREQ (Token-2022, 6 decimals). The mint is PREQ_MAINNET_MINT in preq.ts; if empty, createPaymentGate stops with an error */
46
+ export declare const PREQ_MAINNET: Asset;
47
+ /** @deprecated A402 (v1) is deprecated. Use PREQ_MAINNET. Enabling it explicitly with config.a402 prints a warning */
34
48
  export declare const A402_MAINNET: Asset;
35
49
  export interface GateConfig {
36
50
  network: string;
37
- /** 수령 지갑 공개 주소 */
51
+ /** Public address of the receiving wallet */
38
52
  payTo: string;
39
- /** USDC 가격 (USD) */
53
+ /** USDC price (USD) */
40
54
  priceUsd: number;
41
55
  usdc: Asset;
42
- /** A402 를 받을 때만. rate() 가 off 거나 실패하면 그 요청은 USDC 만 */
43
- a402?: {
44
- asset: Asset;
45
- discountPercent: number;
46
- rate: () => Promise<DailyRate | null>;
47
- };
48
- /** 앞이 기본, 뒤가 예비 */
56
+ /** Only when accepting PREQ. If rate() is off or fails, that request does not offer PREQ. Errors if asset.mint is empty */
57
+ preq?: TokenPayment;
58
+ /**
59
+ * @deprecated A402 (v1) is deprecated; use PREQ. Not in the defaults.
60
+ * Accepted only when set explicitly, and createPaymentGate prints a warning ("A402 (v1) is deprecated and no longer supported; use PREQ.")
61
+ */
62
+ a402?: TokenPayment;
63
+ /** Warning output (default console.warn) */
64
+ warn?: (message: string) => void;
65
+ /** First is primary, the rest are fallbacks */
49
66
  facilitators: FacilitatorSpec[];
50
- /** 체인 읽기 (정산 재확인·결과 모를 때 판정·수령 토큰 계정 확인) */
67
+ /** Chain reader (settlement recheck, deciding unknown results, checking receiving token accounts) */
51
68
  chain: ChainReader;
52
69
  ledger?: X402Ledger;
53
- /** 핸들러 제한 시간 — 넘으면 정산하지 않음 (기본 40초, 결제 트랜잭션 유효시간보다 짧게) */
70
+ /** Handler time limit: if exceeded, no settlement (default 40 s, shorter than the payment transaction's validity) */
54
71
  handlerTimeoutMs?: number;
55
72
  maxTimeoutSeconds?: number;
56
- /** facilitator 쪽 문제(수수료 대납 주소 잔액 부족 등)로 verify 가 실패하면 이 시간 동안 그 facilitator 를 건너뜀 (기본 5분) */
73
+ /** If verify fails because of the facilitator (e.g. fee payer balance too low), skip that facilitator for this long (default 5 min) */
57
74
  facilitatorCooldownMs?: number;
58
- /** 수령 토큰 계정 확인 캐시 (기본 10분) */
75
+ /** Cache for the receiving token account check (default 10 min) */
59
76
  receivingCheckTtlMs?: number;
60
77
  resource?: {
61
78
  description?: string;
@@ -63,7 +80,7 @@ export interface GateConfig {
63
80
  serviceName?: string;
64
81
  };
65
82
  now?: () => number;
66
- /** 체인 재확인 재시도 간격 (기본 1·2·4초) */
83
+ /** Retry intervals for the on-chain recheck (default 1, 2, 4 s) */
67
84
  confirmDelaysMs?: number[];
68
85
  }
69
86
  export interface ReceivingAccount {
@@ -79,9 +96,9 @@ export interface PaymentInfo {
79
96
  network: string;
80
97
  }
81
98
  export interface PaymentGate {
82
- /** 유료 핸들러 감싸기 */
99
+ /** Wraps a paid handler */
83
100
  withPayment(handler: (req: Request, payment: PaymentInfo) => Promise<Response>): (req: Request) => Promise<Response>;
84
- /** 지금 402 에 넣을 결제 조건과 빠진 자산·이유 (확인용) */
101
+ /** Payment requirements that would go in a 402 now, plus missing assets and why (for checking) */
85
102
  quote(resourceUrl: string): Promise<{
86
103
  accepts: PaymentRequirements[];
87
104
  notOffered: {
@@ -90,12 +107,12 @@ export interface PaymentGate {
90
107
  }[];
91
108
  facilitator: string;
92
109
  } | null>;
93
- /** 수령 지갑의 USDC·A402 토큰 계정이 있는지 (없으면 그 자산은 402 에 넣지 않음) */
110
+ /** Whether the receiving wallet has USDC and PREQ (and A402) token accounts (assets without one are not put in the 402) */
94
111
  checkReceivingAccounts(): Promise<ReceivingAccount[]>;
95
112
  }
96
113
  /**
97
- * verify 실패가 구매자 탓이 아니라 facilitator 쪽 문제인지 (수수료 대납 주소 = 트랜잭션 계정 0 의 잔액 부족 등).
98
- * 2026-11-19 실제 사례: `transaction_simulation_failed: Simulation failed: {"InsufficientFundsForRent":{"account_index":0}}`
114
+ * 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).
115
+ * Real case on 2026-11-19: `transaction_simulation_failed: Simulation failed: {"InsufficientFundsForRent":{"account_index":0}}`
99
116
  */
100
117
  export declare function isFacilitatorSideFailure(reason?: string, message?: string): boolean;
101
118
  export declare function createPaymentGate(c: GateConfig): PaymentGate;
package/dist/gate.js CHANGED
@@ -1,30 +1,36 @@
1
- // @agent402-dev/pay-server 의 바깥 API: createPaymentGate(config).withPayment(handler)
2
- // 표준 Request → Response. Cloudflare Workers·Node 20+(fetch API)·Hono 등에서 그대로 씀.
1
+ // External API of @agent402-dev/pay-server: createPaymentGate(config).withPayment(handler)
2
+ // Standard Request → Response. Works as is on Cloudflare Workers, Node 20+ (fetch API), Hono, etc.
3
3
  //
4
- // 순서: 402 → (결제 헤더) 공식 서버로 조건 맞추기·verify → 핸들러 (제한 시간) → 성공(<400)일 때만 settle → 체인 재확인
5
- // 정산이 실패·결과 모름이면 체인에서 먼저 판정 (x402.ts settleVerified)
4
+ // Order: 402 → (payment header) match requirements and verify with the official server → handler (time limit) → settle only on success (<400) → recheck on-chain
5
+ // If settlement fails or its result is unknown, decide on-chain first (x402.ts settleVerified)
6
6
  //
7
- // 하지 않는 것: facilitator 운영, 자금 보관, 환전, 결제 대행. 서버는 수령 지갑 공개 주소만 받음 (개인키 받는 API 없음)
7
+ // Does not: operate a facilitator, hold funds, exchange currencies, or process payments for others. The server only takes the receiving wallet's public address (no API takes a private key)
8
8
  import { decodePaymentSignatureHeader, encodePaymentRequiredHeader } from '@x402/core/http';
9
9
  import { HTTPFacilitatorClient } from '@x402/core/server';
10
10
  import { ataOf } from './chain.js';
11
- import { a402AmountFor } from './rates.js';
11
+ import { tokenAmountFor } from './pricing.js';
12
+ import { A402_DEPRECATION_WARNING, PREQ_DECIMALS, PREQ_MAINNET_MINT, PREQ_TOKEN_PROGRAM } from './preq.js';
12
13
  import { buildRequirements, chooseFacilitator, memoryX402Ledger, paymentResponseHeader, settleVerified, verifyPaymentHeader, } from './x402.js';
13
14
  /**
14
- * 확인된 facilitator (2026-11-19 메인넷에서 verify·settle 로 확인한 사실 — docs: README "Facilitators").
15
- * 정책·상태는 바뀔 수 있으므로 기본값일 뿐, 설정으로 덮어쓸 수 있음
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
16
19
  */
17
20
  export const KNOWN_FACILITATORS = {
18
- payai: { name: 'payai', url: 'https://facilitator.payai.network', assets: ['USDC', 'A402'] },
21
+ payai: { name: 'payai', url: 'https://facilitator.payai.network', assets: ['USDC', 'PREQ', 'A402'] },
19
22
  dexter: { name: 'dexter', url: 'https://x402.dexter.cash', assets: ['USDC'] },
20
23
  };
21
24
  export const SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
22
25
  export const SOLANA_DEVNET = 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1';
23
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 */
24
30
  export const A402_MAINNET = { symbol: 'A402', mint: 'GC8VRpVFheTb8Ep53MihEDfLmTfFR5TEP4B2eGG6ny5X', decimals: 6, tokenProgram: 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' };
25
31
  /**
26
- * verify 실패가 구매자 탓이 아니라 facilitator 쪽 문제인지 (수수료 대납 주소 = 트랜잭션 계정 0 의 잔액 부족 등).
27
- * 2026-11-19 실제 사례: `transaction_simulation_failed: Simulation failed: {"InsufficientFundsForRent":{"account_index":0}}`
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}}`
28
34
  */
29
35
  export function isFacilitatorSideFailure(reason, message) {
30
36
  const s = `${reason ?? ''} ${message ?? ''}`;
@@ -37,6 +43,22 @@ export function isFacilitatorSideFailure(reason, message) {
37
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 } });
38
44
  const NOT_CHARGED = 'No payment was taken.';
39
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);
40
62
  const now = c.now ?? (() => Date.now());
41
63
  const ledger = c.ledger ?? memoryX402Ledger();
42
64
  const named = c.facilitators.map((f) => ({
@@ -47,12 +69,12 @@ export function createPaymentGate(c) {
47
69
  const cooldown = new Map();
48
70
  const cfgFor = (fs) => ({ network: c.network, payTo: c.payTo, facilitators: fs, maxTimeoutSeconds: c.maxTimeoutSeconds ?? 60 });
49
71
  const allCfg = cfgFor(named);
50
- // ---- 수령 토큰 계정 확인 (캐시) ----
72
+ // ---- Receiving token account check (cached) ----
51
73
  let receiving = null;
52
74
  async function checkReceivingAccounts() {
53
75
  if (receiving && now() - receiving.at < (c.receivingCheckTtlMs ?? 600_000))
54
76
  return receiving.list;
55
- const assets = [c.usdc, ...(c.a402 ? [c.a402.asset] : [])];
77
+ const assets = [c.usdc, ...tokens.map((t) => t.asset)];
56
78
  const atas = await Promise.all(assets.map((a) => ataOf(c.payTo, a.mint, a.tokenProgram)));
57
79
  const { accounts } = await c.chain.accounts(atas);
58
80
  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 +92,7 @@ export function createPaymentGate(c) {
70
92
  try {
71
93
  recv = await checkReceivingAccounts();
72
94
  }
73
- catch { /* 확인 실패 → 막지 않고 진행 (체인 재확인이 따로 있음) */ }
95
+ catch { /* check failed → continue without blocking (there is a separate on-chain recheck) */ }
74
96
  const missing = (sym) => recv.find((r) => r.asset === sym && !r.exists);
75
97
  const offers = [];
76
98
  // USDC
@@ -78,26 +100,33 @@ export function createPaymentGate(c) {
78
100
  notOffered.push({ asset: 'USDC', reason: `receiving token account ${missing('USDC').tokenAccount} does not exist` });
79
101
  else
80
102
  offers.push({ asset: c.usdc, amount: BigInt(Math.round(c.priceUsd * 10 ** c.usdc.decimals)) });
81
- // A402
82
- if (c.a402) {
83
- if (!fac.assets.includes('A402')) {
84
- notOffered.push({ asset: 'A402', reason: `facilitator ${fac.name} does not accept A402` });
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}` });
85
108
  }
86
- else if (missing('A402')) {
87
- notOffered.push({ asset: 'A402', reason: `receiving token account ${missing('A402').tokenAccount} does not exist` });
109
+ else if (missing(sym)) {
110
+ notOffered.push({ asset: sym, reason: `receiving token account ${missing(sym).tokenAccount} does not exist` });
88
111
  }
89
112
  else {
90
- const rate = await c.a402.rate().catch(() => null);
113
+ const rate = await t.rate().catch(() => null);
91
114
  if (!rate)
92
- notOffered.push({ asset: 'A402', reason: 'A402 rate unavailable' });
115
+ notOffered.push({ asset: sym, reason: `${sym} rate unavailable` });
93
116
  else if (rate.status === 'off')
94
- notOffered.push({ asset: 'A402', reason: rate.reason });
117
+ notOffered.push({ asset: sym, reason: rate.reason });
95
118
  else {
96
- offers.push({
97
- asset: c.a402.asset,
98
- amount: a402AmountFor(c.priceUsd, c.a402.discountPercent, rate, c.a402.asset.decimals),
99
- rate: { date: rate.date, a402Usd: rate.a402Usd, method: rate.method, discountPercent: c.a402.discountPercent },
100
- });
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 } });
101
130
  }
102
131
  }
103
132
  }
@@ -139,11 +168,11 @@ export function createPaymentGate(c) {
139
168
  cfg: allCfg, ledger,
140
169
  loadTx: (s) => c.chain.loadTx(s),
141
170
  recentSignatures: (a, n) => c.chain.recentSignatures(a, n),
142
- tokenProgramOf: (mint) => (mint === c.a402?.asset.mint ? c.a402.asset.tokenProgram : c.usdc.tokenProgram),
171
+ tokenProgramOf: (mint) => tokens.find((t) => t.asset.mint === mint)?.asset.tokenProgram ?? c.usdc.tokenProgram,
143
172
  nowMs: now(),
144
173
  confirmDelaysMs: c.confirmDelaysMs,
145
174
  };
146
- // 1) 조건 맞추기·verify (돈은 아직 안 나감)
175
+ // 1) Match requirements and verify (no money moves yet)
147
176
  const v = await verifyPaymentHeader(header, url.pathname, q.accepts, d);
148
177
  if (v.kind === 'conflict')
149
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.' });
@@ -151,7 +180,7 @@ export function createPaymentGate(c) {
151
180
  return json(503, { error: 'payment_unavailable', message: `Could not reach the facilitator. ${NOT_CHARGED}` });
152
181
  if (v.kind === 'payment_required') {
153
182
  if (isFacilitatorSideFailure(v.reason, v.message)) {
154
- // 구매자 탓이 아님 → 그 facilitator 를 잠시 빼고, 다음 facilitator 의 새 조건으로 다시 결제하도록 안내
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
155
184
  const feePayer = (() => { try {
156
185
  return decodePaymentSignatureHeader(header).accepted?.extra?.feePayer;
157
186
  }
@@ -168,7 +197,7 @@ export function createPaymentGate(c) {
168
197
  }
169
198
  return paymentRequired(resourceUrl, q, { reason: v.reason, message: `Payment was not accepted (${v.reason}). ${NOT_CHARGED}` }, v.reason);
170
199
  }
171
- // 2) 핸들러 (제한 시간). 실패·시간 초과·4xx/5xx 응답이면 정산하지 않음
200
+ // 2) Handler (time limit). No settlement on failure, timeout, or a 4xx/5xx response
172
201
  const payment = v.payment;
173
202
  const info = { asset: payment.accepted.asset, amount: payment.accepted.amount, payTo: payment.accepted.payTo, network: payment.accepted.network };
174
203
  let res;
@@ -194,7 +223,7 @@ export function createPaymentGate(c) {
194
223
  h.set('x-payment-status', 'not-settled');
195
224
  return new Response(res.body, { status: res.status, headers: h });
196
225
  }
197
- // 3) 정산 (+ 실패·결과 모름이면 체인 판정)
226
+ // 3) Settle (+ decide on-chain if it fails or the result is unknown)
198
227
  const s = await settleVerified(payment, { ...d, nowMs: now() });
199
228
  if (s.kind === 'payment_required')
200
229
  return paymentRequired(resourceUrl, q, { reason: s.reason, message: `Payment was not settled (${s.reason}). ${NOT_CHARGED}` }, s.reason);
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- export { createPaymentGate, isFacilitatorSideFailure, KNOWN_FACILITATORS, SOLANA_MAINNET, SOLANA_DEVNET, USDC_MAINNET, A402_MAINNET, type AssetSymbol, type FacilitatorSpec, type GateConfig, type PaymentGate, type PaymentInfo, type ReceivingAccount, } from './gate.js';
1
+ export { createPaymentGate, isFacilitatorSideFailure, KNOWN_FACILITATORS, SOLANA_MAINNET, SOLANA_DEVNET, USDC_MAINNET, PREQ_MAINNET, A402_MAINNET, type AssetSymbol, type FacilitatorSpec, type GateConfig, type PaymentGate, type PaymentInfo, type ReceivingAccount, type TokenPayment, } from './gate.js';
2
+ export { PREQ_MAINNET_MINT, PREQ_MAINNET_POOL, A402_DEPRECATION_WARNING } from './preq.js';
2
3
  export { rpcChain, receivedBy, type ChainReader, type ChainTx, type AccountFetcher } from './chain.js';
3
- export { createRateBook, memoryRateStore, a402AmountFor, type RateBook, type RateStore } from './rates.js';
4
- export { DEFAULT_GUARDS, fixRate, samplePrice, type DailyRate, type PriceSample, type RateGuards } from './pricing.js';
4
+ export { createRateBook, memoryRateStore, type RateBook, type RateStore } from './rates.js';
5
+ export { DEFAULT_GUARDS, fixRate, samplePrice, tokenAmountFor, PREQ_POOL_TARGET, A402_POOL_TARGET, type DailyRate, type PoolTarget, type PriceSample, type RateGuards, } from './pricing.js';
5
6
  export { memoryX402Ledger, ledgerClaim, SETTLE_UNKNOWN_EXPIRY_MS, type X402Ledger, type LedgerEntry, type Asset } from './x402.js';