@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 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.
34
+
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.
31
36
 
32
- When A402 is not offered, the 402 response lists it under `notOffered` with the reason.
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.)
33
38
 
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.
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
  });
@@ -70,8 +77,27 @@ export default {
70
77
  ```
71
78
  Rate stores: `memoryRateStore()` (default, tests), `fileRateStore(path)` from `@agent402-dev/pay-server/rates-file` (Node), or your own `RateStore` (for example a Cloudflare Durable Object; see the [Workers example](https://github.com/agent402-dev/agent402-toolkit/tree/main/packages/pay-server/examples/cloudflare-worker)). A Node example is in [`examples/node-server`](https://github.com/agent402-dev/agent402-toolkit/tree/main/packages/pay-server/examples/node-server).
72
79
 
80
+ ## Signed receipts (optional)
81
+ After a settled payment the gate can add an `X-Agent402-Receipt` header: a small JSON record, signed with Ed25519, that binds the request (method, path, body hash), the hash of the response body you delivered, and the payment (network, asset, amount, recipient, transaction). Buyers can keep it as evidence for disputes and settlement reports; `@agent402-dev/pay-mcp` checks it automatically.
82
+
83
+ ```ts
84
+ import { receiptSignerFromBytes } from '@agent402-dev/pay-server';
85
+
86
+ const signer = await receiptSignerFromBytes(receiptKeyBytes); // 64-byte Solana CLI key file, or a 32-byte seed
87
+ const gate = createPaymentGate({ /* ... */ receipts: { signer } });
88
+ ```
89
+ - Use a key made only for receipts (for example `solana-keygen new -o receipt-key.json`), never the key of your receiving wallet. The gate never needs the receiving wallet's key.
90
+ - Publish the receipt key's public key (`signer.publicKey`) so buyers can tell that receipts come from you.
91
+ - If signing fails, the paid resource is still delivered, without a receipt.
92
+
93
+ ## Data
94
+ - No telemetry and no analytics.
95
+ - It contacts only the facilitators you configure (`/supported`, `/verify`, `/settle`) and the RPC you pass to `rpcChain` (settlement checks, receiving token accounts, pool prices for the PREQ rate).
96
+ - Replay protection keeps payment identifiers in the ledger you configure (in memory by default). It stores no other buyer data.
97
+ - It writes nothing to the console except the A402 (v1) deprecation warning when you enable A402.
98
+
73
99
  ## License
74
100
  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
101
 
76
102
  ---
77
- Factual information from public on-chain data. Not investment advice. / 공개 온체인 데이터에 따른 사실 정보이며 투자 권유가 아닙니다.
103
+ 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,32 @@
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
+ import { type ReceiptSigner } from './receipt.js';
5
6
  import { type Asset, type X402Ledger } from './x402.js';
6
- export type AssetSymbol = 'USDC' | 'A402';
7
+ /** A402 is deprecated (v1) */
8
+ export type AssetSymbol = 'USDC' | 'PREQ' | 'A402';
9
+ /** Settings for a token accepted in addition to USDC */
10
+ export interface TokenPayment {
11
+ asset: Asset;
12
+ /** Optional. Default 0: the token is charged the same USD price as USDC */
13
+ discountPercent?: number;
14
+ /** Today's fixed rate. If off or failing, that request does not offer this token */
15
+ rate: () => Promise<DailyRate | null>;
16
+ }
7
17
  export interface FacilitatorSpec {
8
18
  name: string;
9
- /** url 또는 client 중 하나 */
19
+ /** Either url or client */
10
20
  url?: string;
11
21
  client?: FacilitatorClient;
12
- /** 이 facilitator 가 받는 결제 자산. 받지 않는 자산은 402 에 넣지 않음 */
22
+ /** Payment assets this facilitator accepts. Assets it does not accept are not put in the 402 */
13
23
  assets: AssetSymbol[];
14
24
  }
15
25
  /**
16
- * 확인된 facilitator (2026-11-19 메인넷에서 verify·settle 로 확인한 사실 — docs: README "Facilitators").
17
- * 정책·상태는 바뀔 수 있으므로 기본값일 뿐, 설정으로 덮어쓸 수 있음
26
+ * Facilitator defaults. Policies and status can change, so these are only defaults and can be overridden in config.
27
+ * - USDC: confirmed with mainnet verify and settle on 2026-11-19 (PayAI, Dexter)
28
+ * - A402 (v1, deprecated): record of a check on PayAI on 2026-11-19
29
+ * - 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
30
  */
19
31
  export declare const KNOWN_FACILITATORS: {
20
32
  readonly payai: {
@@ -31,31 +43,37 @@ export declare const KNOWN_FACILITATORS: {
31
43
  export declare const SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
32
44
  export declare const SOLANA_DEVNET = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
33
45
  export declare const USDC_MAINNET: Asset;
46
+ /** PREQ (Token-2022, 6 decimals). The mint is PREQ_MAINNET_MINT in preq.ts; if empty, createPaymentGate stops with an error */
47
+ export declare const PREQ_MAINNET: Asset;
48
+ /** @deprecated A402 (v1) is deprecated. Use PREQ_MAINNET. Enabling it explicitly with config.a402 prints a warning */
34
49
  export declare const A402_MAINNET: Asset;
35
50
  export interface GateConfig {
36
51
  network: string;
37
- /** 수령 지갑 공개 주소 */
52
+ /** Public address of the receiving wallet */
38
53
  payTo: string;
39
- /** USDC 가격 (USD) */
54
+ /** USDC price (USD) */
40
55
  priceUsd: number;
41
56
  usdc: Asset;
42
- /** A402 를 받을 때만. rate() 가 off 거나 실패하면 그 요청은 USDC 만 */
43
- a402?: {
44
- asset: Asset;
45
- discountPercent: number;
46
- rate: () => Promise<DailyRate | null>;
47
- };
48
- /** 앞이 기본, 뒤가 예비 */
57
+ /** Only when accepting PREQ. If rate() is off or fails, that request does not offer PREQ. Errors if asset.mint is empty */
58
+ preq?: TokenPayment;
59
+ /**
60
+ * @deprecated A402 (v1) is deprecated; use PREQ. Not in the defaults.
61
+ * Accepted only when set explicitly, and createPaymentGate prints a warning ("A402 (v1) is deprecated and no longer supported; use PREQ.")
62
+ */
63
+ a402?: TokenPayment;
64
+ /** Warning output (default console.warn) */
65
+ warn?: (message: string) => void;
66
+ /** First is primary, the rest are fallbacks */
49
67
  facilitators: FacilitatorSpec[];
50
- /** 체인 읽기 (정산 재확인·결과 모를 때 판정·수령 토큰 계정 확인) */
68
+ /** Chain reader (settlement recheck, deciding unknown results, checking receiving token accounts) */
51
69
  chain: ChainReader;
52
70
  ledger?: X402Ledger;
53
- /** 핸들러 제한 시간 — 넘으면 정산하지 않음 (기본 40초, 결제 트랜잭션 유효시간보다 짧게) */
71
+ /** Handler time limit: if exceeded, no settlement (default 40 s, shorter than the payment transaction's validity) */
54
72
  handlerTimeoutMs?: number;
55
73
  maxTimeoutSeconds?: number;
56
- /** facilitator 쪽 문제(수수료 대납 주소 잔액 부족 등)로 verify 가 실패하면 이 시간 동안 그 facilitator 를 건너뜀 (기본 5분) */
74
+ /** If verify fails because of the facilitator (e.g. fee payer balance too low), skip that facilitator for this long (default 5 min) */
57
75
  facilitatorCooldownMs?: number;
58
- /** 수령 토큰 계정 확인 캐시 (기본 10분) */
76
+ /** Cache for the receiving token account check (default 10 min) */
59
77
  receivingCheckTtlMs?: number;
60
78
  resource?: {
61
79
  description?: string;
@@ -63,8 +81,15 @@ export interface GateConfig {
63
81
  serviceName?: string;
64
82
  };
65
83
  now?: () => number;
66
- /** 체인 재확인 재시도 간격 (기본 1·2·4초) */
84
+ /** Retry intervals for the on-chain recheck (default 1, 2, 4 s) */
67
85
  confirmDelaysMs?: number[];
86
+ /**
87
+ * Signed receipts (optional): after a settled payment, adds the X-Agent402-Receipt header signed with this key.
88
+ * Use a key made only for receipts (receiptSignerFromBytes), never the receiving wallet's key
89
+ */
90
+ receipts?: {
91
+ signer: ReceiptSigner;
92
+ };
68
93
  }
69
94
  export interface ReceivingAccount {
70
95
  asset: AssetSymbol;
@@ -79,9 +104,9 @@ export interface PaymentInfo {
79
104
  network: string;
80
105
  }
81
106
  export interface PaymentGate {
82
- /** 유료 핸들러 감싸기 */
107
+ /** Wraps a paid handler */
83
108
  withPayment(handler: (req: Request, payment: PaymentInfo) => Promise<Response>): (req: Request) => Promise<Response>;
84
- /** 지금 402 에 넣을 결제 조건과 빠진 자산·이유 (확인용) */
109
+ /** Payment requirements that would go in a 402 now, plus missing assets and why (for checking) */
85
110
  quote(resourceUrl: string): Promise<{
86
111
  accepts: PaymentRequirements[];
87
112
  notOffered: {
@@ -90,12 +115,12 @@ export interface PaymentGate {
90
115
  }[];
91
116
  facilitator: string;
92
117
  } | null>;
93
- /** 수령 지갑의 USDC·A402 토큰 계정이 있는지 (없으면 그 자산은 402 에 넣지 않음) */
118
+ /** Whether the receiving wallet has USDC and PREQ (and A402) token accounts (assets without one are not put in the 402) */
94
119
  checkReceivingAccounts(): Promise<ReceivingAccount[]>;
95
120
  }
96
121
  /**
97
- * verify 실패가 구매자 탓이 아니라 facilitator 쪽 문제인지 (수수료 대납 주소 = 트랜잭션 계정 0 의 잔액 부족 등).
98
- * 2026-11-19 실제 사례: `transaction_simulation_failed: Simulation failed: {"InsufficientFundsForRent":{"account_index":0}}`
122
+ * 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).
123
+ * Real case on 2026-11-19: `transaction_simulation_failed: Simulation failed: {"InsufficientFundsForRent":{"account_index":0}}`
99
124
  */
100
125
  export declare function isFacilitatorSideFailure(reason?: string, message?: string): boolean;
101
126
  export declare function createPaymentGate(c: GateConfig): PaymentGate;