@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 +24 -17
- package/dist/chain.d.ts +6 -6
- package/dist/chain.js +7 -7
- package/dist/core.d.ts +6 -6
- package/dist/core.js +11 -11
- package/dist/gate.d.ts +42 -25
- package/dist/gate.js +62 -33
- package/dist/index.d.ts +4 -3
- package/dist/index.js +6 -4
- package/dist/preq.d.ts +10 -0
- package/dist/preq.js +18 -0
- package/dist/pricing.d.ts +57 -27
- package/dist/pricing.js +91 -35
- package/dist/rates-file.js +2 -2
- package/dist/rates.d.ts +5 -8
- package/dist/rates.js +9 -10
- package/dist/x402.d.ts +34 -33
- package/dist/x402.js +32 -32
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
# @agent402-dev/pay-server
|
|
2
2
|
|
|
3
|
-
|
|
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
|
|
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
|
|
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
|
-
##
|
|
27
|
-
|
|
28
|
-
1. The selected facilitator is configured to accept
|
|
29
|
-
2. Your receiving address has
|
|
30
|
-
3. The day's
|
|
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
|
-
|
|
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
|
|
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,
|
|
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
|
-
|
|
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
|
|
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
|
-
/**
|
|
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
|
|
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
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
|
|
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
|
|
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
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
|
|
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
|
|
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
|
|
4
|
+
import { type DailyRate } from './pricing.js';
|
|
5
5
|
import { type Asset, type X402Ledger } from './x402.js';
|
|
6
|
-
|
|
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
|
|
18
|
+
/** Either url or client */
|
|
10
19
|
url?: string;
|
|
11
20
|
client?: FacilitatorClient;
|
|
12
|
-
/**
|
|
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
|
-
|
|
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
|
|
53
|
+
/** USDC price (USD) */
|
|
40
54
|
priceUsd: number;
|
|
41
55
|
usdc: Asset;
|
|
42
|
-
/**
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
|
|
98
|
-
|
|
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
|
|
2
|
-
//
|
|
1
|
+
// External API of @agent402-dev/pay-server: createPaymentGate(config).withPayment(handler)
|
|
2
|
+
// Standard Request → Response. Works as is on Cloudflare Workers, Node 20+ (fetch API), Hono, etc.
|
|
3
3
|
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
4
|
+
// Order: 402 → (payment header) match requirements and verify with the official server → handler (time limit) → settle only on success (<400) → recheck on-chain
|
|
5
|
+
// If settlement fails or its result is unknown, decide on-chain first (x402.ts settleVerified)
|
|
6
6
|
//
|
|
7
|
-
//
|
|
7
|
+
// Does not: operate a facilitator, hold funds, exchange currencies, or process payments for others. The server only takes the receiving wallet's public address (no API takes a private key)
|
|
8
8
|
import { decodePaymentSignatureHeader, encodePaymentRequiredHeader } from '@x402/core/http';
|
|
9
9
|
import { HTTPFacilitatorClient } from '@x402/core/server';
|
|
10
10
|
import { ataOf } from './chain.js';
|
|
11
|
-
import {
|
|
11
|
+
import { tokenAmountFor } from './pricing.js';
|
|
12
|
+
import { 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
|
-
|
|
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
|
-
|
|
27
|
-
|
|
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, ...(
|
|
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
|
-
|
|
83
|
-
|
|
84
|
-
|
|
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(
|
|
87
|
-
notOffered.push({ asset:
|
|
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
|
|
113
|
+
const rate = await t.rate().catch(() => null);
|
|
91
114
|
if (!rate)
|
|
92
|
-
notOffered.push({ asset:
|
|
115
|
+
notOffered.push({ asset: sym, reason: `${sym} rate unavailable` });
|
|
93
116
|
else if (rate.status === 'off')
|
|
94
|
-
notOffered.push({ asset:
|
|
117
|
+
notOffered.push({ asset: sym, reason: rate.reason });
|
|
95
118
|
else {
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
amount
|
|
99
|
-
|
|
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) => (
|
|
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)
|
|
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
|
-
//
|
|
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)
|
|
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,
|
|
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';
|