@agent402-dev/pay-server 0.0.0-stage → 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/LICENSE +202 -0
- package/NOTICE +6 -0
- package/README.md +83 -2
- package/dist/chain.d.ts +48 -0
- package/dist/chain.js +71 -0
- package/dist/core.d.ts +23 -0
- package/dist/core.js +59 -0
- package/dist/gate.d.ts +118 -0
- package/dist/gate.js +241 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +8 -0
- package/dist/preq.d.ts +10 -0
- package/dist/preq.js +18 -0
- package/dist/pricing.d.ts +117 -0
- package/dist/pricing.js +183 -0
- package/dist/rates-file.d.ts +2 -0
- package/dist/rates-file.js +33 -0
- package/dist/rates.d.ts +23 -0
- package/dist/rates.js +40 -0
- package/dist/x402.d.ts +200 -0
- package/dist/x402.js +270 -0
- package/package.json +51 -4
package/dist/rates.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Payment token (PREQ) rate: sampled hourly, then fixed for the day at the median of the previous day's samples (if a guard trips, token payments are off that day).
|
|
2
|
+
// Pool and mint addresses are read from preq.ts only (PoolTarget default). A402 (v1) is deprecated: only when passed explicitly (with a warning).
|
|
3
|
+
// The store is an interface: memory (default, tests), file (Node: rates-file.ts), Durable Object (Workers example), etc.
|
|
4
|
+
import { DEFAULT_GUARDS, fixRate, PREQ_POOL_TARGET, samplePrice } from './pricing.js';
|
|
5
|
+
export function memoryRateStore() {
|
|
6
|
+
const samples = [];
|
|
7
|
+
const rates = new Map();
|
|
8
|
+
return {
|
|
9
|
+
async addSample(s) { samples.push(s); },
|
|
10
|
+
async samples(day) { return samples.filter((s) => s.at.slice(0, 10) === day); },
|
|
11
|
+
async getRate(date) { return rates.get(date) ?? null; },
|
|
12
|
+
async putRate(r) { rates.set(r.date, r); },
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
const prevDay = (d) => new Date(Date.parse(`${d}T00:00:00Z`) - 86_400_000).toISOString().slice(0, 10);
|
|
16
|
+
export function createRateBook(o) {
|
|
17
|
+
const now = o.now ?? (() => new Date());
|
|
18
|
+
const guards = o.guards ?? DEFAULT_GUARDS;
|
|
19
|
+
const target = o.target ?? PREQ_POOL_TARGET;
|
|
20
|
+
return {
|
|
21
|
+
async record() {
|
|
22
|
+
if (!o.fetcher)
|
|
23
|
+
throw new Error('rate book: no account fetcher configured');
|
|
24
|
+
const s = await samplePrice(o.fetcher, now, guards, target);
|
|
25
|
+
await o.store.addSample(s);
|
|
26
|
+
return s;
|
|
27
|
+
},
|
|
28
|
+
async today() {
|
|
29
|
+
const date = now().toISOString().slice(0, 10);
|
|
30
|
+
const cached = await o.store.getRate(date);
|
|
31
|
+
if (cached)
|
|
32
|
+
return cached;
|
|
33
|
+
// Samples of other tokens (e.g. old A402 samples without symbol) are not mixed in
|
|
34
|
+
const samples = (await o.store.samples(prevDay(date))).filter((s) => (s.symbol ?? 'A402') === target.symbol);
|
|
35
|
+
const r = fixRate(date, samples, guards);
|
|
36
|
+
await o.store.putRate(r);
|
|
37
|
+
return r;
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|
package/dist/x402.d.ts
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import type { FacilitatorClient, x402ResourceServer } from '@x402/core/server';
|
|
2
|
+
import type { PaymentPayload, PaymentRequirements, SettleResponse } from '@x402/core/types';
|
|
3
|
+
import { SPL_TOKEN, TOKEN_2022, type ChainTx } from './chain.js';
|
|
4
|
+
export { SPL_TOKEN, TOKEN_2022 };
|
|
5
|
+
type TxRecordWithInstructions = ChainTx;
|
|
6
|
+
export declare const SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
|
|
7
|
+
export declare const SOLANA_DEVNET = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
|
|
8
|
+
export interface Asset {
|
|
9
|
+
/** A402 is deprecated (v1). Only when enabled explicitly (prints a warning) */
|
|
10
|
+
symbol: 'USDC' | 'PREQ' | 'A402';
|
|
11
|
+
mint: string;
|
|
12
|
+
decimals: number;
|
|
13
|
+
/** SPL Token or Token-2022 program address */
|
|
14
|
+
tokenProgram: string;
|
|
15
|
+
}
|
|
16
|
+
export interface Offer {
|
|
17
|
+
asset: Asset;
|
|
18
|
+
amount: bigint;
|
|
19
|
+
/** For tokens (PREQ, etc.), the rate basis (published as extra.rate). tokenUsd = USD per token */
|
|
20
|
+
rate?: {
|
|
21
|
+
date: string;
|
|
22
|
+
tokenUsd: number;
|
|
23
|
+
method: string;
|
|
24
|
+
discountPercent: number;
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export interface NamedFacilitator {
|
|
28
|
+
name: string;
|
|
29
|
+
client: FacilitatorClient;
|
|
30
|
+
}
|
|
31
|
+
export interface X402Config {
|
|
32
|
+
network: string;
|
|
33
|
+
/** Public address of the receiving wallet */
|
|
34
|
+
payTo: string;
|
|
35
|
+
/** First is primary, the rest are fallbacks */
|
|
36
|
+
facilitators: NamedFacilitator[];
|
|
37
|
+
maxTimeoutSeconds: number;
|
|
38
|
+
}
|
|
39
|
+
interface Chosen {
|
|
40
|
+
facilitator: NamedFacilitator;
|
|
41
|
+
feePayer: string;
|
|
42
|
+
transactionVersions?: unknown;
|
|
43
|
+
server: x402ResourceServer;
|
|
44
|
+
}
|
|
45
|
+
/** First facilitator, primary then fallbacks, that supports exact on this network */
|
|
46
|
+
export declare function chooseFacilitator(cfg: X402Config, nowMs: number): Promise<Chosen | null>;
|
|
47
|
+
/** Facilitator using the feePayer in the payment requirements (settlement must go to that facilitator) */
|
|
48
|
+
export declare function facilitatorForFeePayer(cfg: X402Config, feePayer: unknown, nowMs: number): Promise<Chosen | null>;
|
|
49
|
+
export declare function clearSupportedCache(): void;
|
|
50
|
+
/** Builds payment requirements with the official x402ResourceServer.buildPaymentRequirementsFromOptions (the official SVM server fills feePayer and transactionVersions) */
|
|
51
|
+
export declare function buildRequirements(cfg: X402Config, offers: Offer[], chosen: Chosen): Promise<PaymentRequirements[]>;
|
|
52
|
+
export interface X402Ledger {
|
|
53
|
+
/**
|
|
54
|
+
* Claims the payment (key).
|
|
55
|
+
* new: first time → proceed to settle / settled: settled but the report was not received → skip settlement
|
|
56
|
+
* in_progress, fulfilled: reject
|
|
57
|
+
*/
|
|
58
|
+
claim(key: string, nowMs: number): Promise<{
|
|
59
|
+
ok: true;
|
|
60
|
+
state: 'new';
|
|
61
|
+
}
|
|
62
|
+
/** The result of the previous settle request is unknown; must be decided on-chain */
|
|
63
|
+
| {
|
|
64
|
+
ok: true;
|
|
65
|
+
state: 'settle_unknown';
|
|
66
|
+
since: number;
|
|
67
|
+
} | {
|
|
68
|
+
ok: false;
|
|
69
|
+
state: 'in_progress' | 'fulfilled';
|
|
70
|
+
}>;
|
|
71
|
+
/** The settle request result is unknown (timeout, etc.) */
|
|
72
|
+
markSettleUnknown(key: string, nowMs: number): Promise<void>;
|
|
73
|
+
fulfill(key: string, nowMs: number): Promise<void>;
|
|
74
|
+
/** Failed before settlement → release */
|
|
75
|
+
release(key: string): Promise<void>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* When the settlement result is unknown and the transaction is still not on-chain after this time, it can no longer be processed
|
|
79
|
+
* (blockhash is valid for 150 blocks ≈ 60 to 90 s, with margin)
|
|
80
|
+
*/
|
|
81
|
+
export declare const SETTLE_UNKNOWN_EXPIRY_MS = 150000;
|
|
82
|
+
type LedgerEntry = {
|
|
83
|
+
state: 'in_progress';
|
|
84
|
+
at: number;
|
|
85
|
+
} | {
|
|
86
|
+
state: 'settle_unknown';
|
|
87
|
+
at: number;
|
|
88
|
+
} | {
|
|
89
|
+
state: 'fulfilled';
|
|
90
|
+
at: number;
|
|
91
|
+
};
|
|
92
|
+
/** Ledger state transitions (shared by the Durable Object and memory implementations) */
|
|
93
|
+
export declare function ledgerClaim(e: LedgerEntry | undefined, nowMs: number): {
|
|
94
|
+
next: LedgerEntry;
|
|
95
|
+
result: {
|
|
96
|
+
readonly ok: true;
|
|
97
|
+
readonly state: "new";
|
|
98
|
+
readonly since?: undefined;
|
|
99
|
+
};
|
|
100
|
+
} | {
|
|
101
|
+
next: {
|
|
102
|
+
state: "fulfilled";
|
|
103
|
+
at: number;
|
|
104
|
+
};
|
|
105
|
+
result: {
|
|
106
|
+
readonly ok: false;
|
|
107
|
+
readonly state: "fulfilled";
|
|
108
|
+
readonly since?: undefined;
|
|
109
|
+
};
|
|
110
|
+
} | {
|
|
111
|
+
next: {
|
|
112
|
+
state: "in_progress";
|
|
113
|
+
at: number;
|
|
114
|
+
};
|
|
115
|
+
result: {
|
|
116
|
+
readonly ok: false;
|
|
117
|
+
readonly state: "in_progress";
|
|
118
|
+
readonly since?: undefined;
|
|
119
|
+
};
|
|
120
|
+
} | {
|
|
121
|
+
next: LedgerEntry;
|
|
122
|
+
result: {
|
|
123
|
+
readonly ok: true;
|
|
124
|
+
readonly state: "settle_unknown";
|
|
125
|
+
readonly since: number;
|
|
126
|
+
};
|
|
127
|
+
};
|
|
128
|
+
export type { LedgerEntry };
|
|
129
|
+
export declare function memoryX402Ledger(): X402Ledger;
|
|
130
|
+
export declare function sha256Hex(s: string): Promise<string>;
|
|
131
|
+
export interface ProcessDeps {
|
|
132
|
+
cfg: X402Config;
|
|
133
|
+
ledger: X402Ledger;
|
|
134
|
+
/** Reads transactions on the payment network (on-chain recheck) */
|
|
135
|
+
loadTx: (signature: string) => Promise<TxRecordWithInstructions | null>;
|
|
136
|
+
/** Recent signatures for an address on the payment network (to decide when the settlement result is unknown) */
|
|
137
|
+
recentSignatures: (address: string, limit: number) => Promise<string[]>;
|
|
138
|
+
/** Payment asset mint → token program (to compute the receiving token account address) */
|
|
139
|
+
tokenProgramOf: (mint: string) => string;
|
|
140
|
+
nowMs: number;
|
|
141
|
+
/** Retry intervals for the on-chain recheck */
|
|
142
|
+
confirmDelaysMs?: number[];
|
|
143
|
+
}
|
|
144
|
+
/** A payment that passed verification (no money has moved yet) */
|
|
145
|
+
export interface VerifiedPayment {
|
|
146
|
+
key: string;
|
|
147
|
+
payload: PaymentPayload;
|
|
148
|
+
accepted: PaymentRequirements;
|
|
149
|
+
facilitator: NamedFacilitator;
|
|
150
|
+
/** Official resource server wrapping that facilitator (calls verify and settle) */
|
|
151
|
+
server: x402ResourceServer;
|
|
152
|
+
/** If reprocessing a payment whose previous settlement result is unknown, its time */
|
|
153
|
+
settleUnknownSince: number | null;
|
|
154
|
+
}
|
|
155
|
+
export type VerifyOutcome = {
|
|
156
|
+
kind: 'payment_required';
|
|
157
|
+
reason: string;
|
|
158
|
+
message: string;
|
|
159
|
+
} | {
|
|
160
|
+
kind: 'conflict';
|
|
161
|
+
state: 'in_progress' | 'fulfilled';
|
|
162
|
+
} | {
|
|
163
|
+
kind: 'unavailable';
|
|
164
|
+
message: string;
|
|
165
|
+
} | {
|
|
166
|
+
kind: 'verified';
|
|
167
|
+
payment: VerifiedPayment;
|
|
168
|
+
};
|
|
169
|
+
export type SettleOutcome = {
|
|
170
|
+
kind: 'payment_required';
|
|
171
|
+
reason: string;
|
|
172
|
+
message: string;
|
|
173
|
+
} | {
|
|
174
|
+
kind: 'unavailable';
|
|
175
|
+
message: string;
|
|
176
|
+
}
|
|
177
|
+
/** confirmation: confirmed = confirmed on-chain with our RPC / pending = facilitator reported success, not yet confirmed on-chain */
|
|
178
|
+
| {
|
|
179
|
+
kind: 'paid';
|
|
180
|
+
settlement: SettleResponse;
|
|
181
|
+
confirmation: 'confirmed' | 'pending';
|
|
182
|
+
};
|
|
183
|
+
/** Signatures already filled in a partially signed transaction (base64) (the buyer's signatures). Empty slots (all zeros) are left out */
|
|
184
|
+
export declare function presentSignatures(txBase64: string): string[];
|
|
185
|
+
/**
|
|
186
|
+
* Decides on-chain when the settlement result is unknown: finds a transaction containing the buyer's signature among recent records of the receiving token account.
|
|
187
|
+
* Returns that transaction if found, otherwise null
|
|
188
|
+
*/
|
|
189
|
+
export declare function findSettledOnChain(v: VerifiedPayment, d: ProcessDeps): Promise<TxRecordWithInstructions | null>;
|
|
190
|
+
/**
|
|
191
|
+
* Step 1: check PAYMENT-SIGNATURE → claim in the ledger → facilitator /verify. No money moves yet.
|
|
192
|
+
* The caller then builds the report and calls settleVerified only on success
|
|
193
|
+
*/
|
|
194
|
+
export declare function verifyPaymentHeader(header: string, resourcePath: string, current: PaymentRequirements[], d: ProcessDeps): Promise<VerifyOutcome>;
|
|
195
|
+
/**
|
|
196
|
+
* Step 2 (only after the report is built): facilitator /settle → on-chain recheck with our RPC.
|
|
197
|
+
* If the settlement result is unknown (timeout, etc.), decide on-chain by the buyer's signature; if still unknown, leave it as "result unknown"
|
|
198
|
+
*/
|
|
199
|
+
export declare function settleVerified(v: VerifiedPayment, d: ProcessDeps): Promise<SettleOutcome>;
|
|
200
|
+
export declare function paymentResponseHeader(s: SettleResponse): string;
|
package/dist/x402.js
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
// Standard x402 v2 (exact, Solana): resource-server-side processing steps (internal to @agent402-dev/pay-server, used by gate.ts).
|
|
2
|
+
//
|
|
3
|
+
// Flow: verify → (caller's work) → settle
|
|
4
|
+
// - verifyPaymentHeader: checks the payment's chosen requirement (accepted) equals the current one (official matching), the resource path, claims it in the ledger, facilitator verify
|
|
5
|
+
// - settleVerified: facilitator settle → on-chain recheck. If it fails or the result is unknown, decide on-chain by the buyer's signature;
|
|
6
|
+
// if not found, keep it as "result unknown" and mark "not paid" only when it is still missing after the validity window (150 s)
|
|
7
|
+
//
|
|
8
|
+
// The server holds only the receiving wallet's public address. The fee payer (feePayer) key belongs to the facilitator.
|
|
9
|
+
import { decodePaymentSignatureHeader, encodePaymentResponseHeader } from '@x402/core/http';
|
|
10
|
+
import { buildCoreRequirements, createCoreServer, definiteVerifyRejection, matchRequirement, settleFailureReason } from './core.js';
|
|
11
|
+
import { ataOf, base58Encode, receivedBy, SPL_TOKEN, TOKEN_2022 } from './chain.js';
|
|
12
|
+
export { SPL_TOKEN, TOKEN_2022 };
|
|
13
|
+
export const SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
|
|
14
|
+
export const SOLANA_DEVNET = 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1';
|
|
15
|
+
const supportedCache = new Map();
|
|
16
|
+
const SUPPORTED_TTL_MS = 10 * 60_000;
|
|
17
|
+
/** feePayer for exact (v2) on this network from one facilitator's /supported (cached) */
|
|
18
|
+
async function supportedFor(f, network, nowMs) {
|
|
19
|
+
const key = `${f.name}|${network}`;
|
|
20
|
+
const c = supportedCache.get(key);
|
|
21
|
+
if (c && nowMs - c.at < SUPPORTED_TTL_MS)
|
|
22
|
+
return c.chosen;
|
|
23
|
+
let chosen = null;
|
|
24
|
+
try {
|
|
25
|
+
const server = await createCoreServer(f.client, network);
|
|
26
|
+
const kind = server.getSupportedKind(2, network, 'exact');
|
|
27
|
+
const feePayer = kind?.extra && typeof kind.extra.feePayer === 'string' ? kind.extra.feePayer : null;
|
|
28
|
+
if (feePayer)
|
|
29
|
+
chosen = { facilitator: f, feePayer, transactionVersions: kind?.extra?.transactionVersions, server };
|
|
30
|
+
}
|
|
31
|
+
catch { /* outage → null (cached briefly, move on to the next facilitator) */ }
|
|
32
|
+
supportedCache.set(key, { at: chosen ? nowMs : nowMs - SUPPORTED_TTL_MS + 30_000, chosen });
|
|
33
|
+
return chosen;
|
|
34
|
+
}
|
|
35
|
+
/** First facilitator, primary then fallbacks, that supports exact on this network */
|
|
36
|
+
export async function chooseFacilitator(cfg, nowMs) {
|
|
37
|
+
for (const f of cfg.facilitators) {
|
|
38
|
+
const c = await supportedFor(f, cfg.network, nowMs);
|
|
39
|
+
if (c)
|
|
40
|
+
return c;
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
/** Facilitator using the feePayer in the payment requirements (settlement must go to that facilitator) */
|
|
45
|
+
export async function facilitatorForFeePayer(cfg, feePayer, nowMs) {
|
|
46
|
+
if (typeof feePayer !== 'string')
|
|
47
|
+
return null;
|
|
48
|
+
for (const f of cfg.facilitators) {
|
|
49
|
+
const c = await supportedFor(f, cfg.network, nowMs);
|
|
50
|
+
if (c?.feePayer === feePayer)
|
|
51
|
+
return c;
|
|
52
|
+
}
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
export function clearSupportedCache() { supportedCache.clear(); }
|
|
56
|
+
// ---------- 402 ----------
|
|
57
|
+
/** Builds payment requirements with the official x402ResourceServer.buildPaymentRequirementsFromOptions (the official SVM server fills feePayer and transactionVersions) */
|
|
58
|
+
export function buildRequirements(cfg, offers, chosen) {
|
|
59
|
+
return buildCoreRequirements(chosen.server, cfg.network, cfg.payTo, cfg.maxTimeoutSeconds, offers.map((o) => ({
|
|
60
|
+
asset: o.asset.mint,
|
|
61
|
+
amount: o.amount.toString(),
|
|
62
|
+
extra: { name: o.asset.symbol, decimals: o.asset.decimals, ...(o.rate ? { rate: o.rate } : {}) },
|
|
63
|
+
})));
|
|
64
|
+
}
|
|
65
|
+
const IN_PROGRESS_TTL_MS = 120_000;
|
|
66
|
+
/**
|
|
67
|
+
* When the settlement result is unknown and the transaction is still not on-chain after this time, it can no longer be processed
|
|
68
|
+
* (blockhash is valid for 150 blocks ≈ 60 to 90 s, with margin)
|
|
69
|
+
*/
|
|
70
|
+
export const SETTLE_UNKNOWN_EXPIRY_MS = 150_000;
|
|
71
|
+
/** Ledger state transitions (shared by the Durable Object and memory implementations) */
|
|
72
|
+
export function ledgerClaim(e, nowMs) {
|
|
73
|
+
if (!e)
|
|
74
|
+
return { next: { state: 'in_progress', at: nowMs }, result: { ok: true, state: 'new' } };
|
|
75
|
+
if (e.state === 'fulfilled')
|
|
76
|
+
return { next: e, result: { ok: false, state: 'fulfilled' } };
|
|
77
|
+
if (e.state === 'in_progress' && nowMs - e.at < IN_PROGRESS_TTL_MS)
|
|
78
|
+
return { next: e, result: { ok: false, state: 'in_progress' } };
|
|
79
|
+
if (e.state === 'in_progress')
|
|
80
|
+
return { next: { state: 'in_progress', at: nowMs }, result: { ok: true, state: 'new' } };
|
|
81
|
+
// settle_unknown: claim as in progress, and also return the original time
|
|
82
|
+
return { next: { state: 'in_progress', at: nowMs }, result: { ok: true, state: 'settle_unknown', since: e.at } };
|
|
83
|
+
}
|
|
84
|
+
export function memoryX402Ledger() {
|
|
85
|
+
const m = new Map();
|
|
86
|
+
return {
|
|
87
|
+
async claim(key, now) { const r = ledgerClaim(m.get(key), now); m.set(key, r.next); return r.result; },
|
|
88
|
+
async markSettleUnknown(key, now) { m.set(key, { state: 'settle_unknown', at: now }); },
|
|
89
|
+
async fulfill(key, now) { m.set(key, { state: 'fulfilled', at: now }); },
|
|
90
|
+
async release(key) { if (m.get(key)?.state === 'in_progress')
|
|
91
|
+
m.delete(key); },
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
export async function sha256Hex(s) {
|
|
95
|
+
const d = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s));
|
|
96
|
+
return [...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
97
|
+
}
|
|
98
|
+
/** Signatures already filled in a partially signed transaction (base64) (the buyer's signatures). Empty slots (all zeros) are left out */
|
|
99
|
+
export function presentSignatures(txBase64) {
|
|
100
|
+
const buf = Uint8Array.from(atob(txBase64), (c) => c.charCodeAt(0));
|
|
101
|
+
let n = 0, shift = 0, i = 0;
|
|
102
|
+
for (;;) {
|
|
103
|
+
const b = buf[i++];
|
|
104
|
+
n |= (b & 0x7f) << shift;
|
|
105
|
+
if (!(b & 0x80))
|
|
106
|
+
break;
|
|
107
|
+
shift += 7;
|
|
108
|
+
}
|
|
109
|
+
const out = [];
|
|
110
|
+
for (let k = 0; k < n; k++) {
|
|
111
|
+
const sig = buf.subarray(i + k * 64, i + (k + 1) * 64);
|
|
112
|
+
if (sig.some((x) => x !== 0))
|
|
113
|
+
out.push(base58Encode(sig));
|
|
114
|
+
}
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
/** Whether the on-chain record satisfies this payment requirement */
|
|
118
|
+
function satisfies(tx, accepted) {
|
|
119
|
+
return !tx.err && receivedBy(tx, accepted.payTo, accepted.asset) >= BigInt(accepted.amount);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Decides on-chain when the settlement result is unknown: finds a transaction containing the buyer's signature among recent records of the receiving token account.
|
|
123
|
+
* Returns that transaction if found, otherwise null
|
|
124
|
+
*/
|
|
125
|
+
export async function findSettledOnChain(v, d) {
|
|
126
|
+
const mine = new Set(presentSignatures(v.payload.payload.transaction));
|
|
127
|
+
if (!mine.size)
|
|
128
|
+
return null;
|
|
129
|
+
const ata = await ataOf(v.accepted.payTo, v.accepted.asset, d.tokenProgramOf(v.accepted.asset));
|
|
130
|
+
for (const sig of await d.recentSignatures(ata, 25)) {
|
|
131
|
+
const tx = await d.loadTx(sig);
|
|
132
|
+
if (tx && tx.signatures.some((s) => mine.has(s)))
|
|
133
|
+
return tx;
|
|
134
|
+
}
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Step 1: check PAYMENT-SIGNATURE → claim in the ledger → facilitator /verify. No money moves yet.
|
|
139
|
+
* The caller then builds the report and calls settleVerified only on success
|
|
140
|
+
*/
|
|
141
|
+
export async function verifyPaymentHeader(header, resourcePath, current, d) {
|
|
142
|
+
let payload;
|
|
143
|
+
try {
|
|
144
|
+
payload = decodePaymentSignatureHeader(header);
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
return { kind: 'payment_required', reason: 'invalid_payload', message: 'Could not decode the PAYMENT-SIGNATURE header. No payment was taken.' };
|
|
148
|
+
}
|
|
149
|
+
if (payload.x402Version !== 2)
|
|
150
|
+
return { kind: 'payment_required', reason: 'invalid_x402_version', message: 'Only x402Version 2 is accepted. No payment was taken.' };
|
|
151
|
+
try {
|
|
152
|
+
if (payload.resource?.url && new URL(payload.resource.url).pathname !== resourcePath) {
|
|
153
|
+
return { kind: 'payment_required', reason: 'resource_mismatch', message: 'This payment is for a different resource. No payment was taken.' };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
return { kind: 'payment_required', reason: 'resource_mismatch', message: 'Could not parse resource.url. No payment was taken.' };
|
|
158
|
+
}
|
|
159
|
+
// Official matching rules (exact match of scheme, network, asset, amount, payTo, maxTimeoutSeconds + extra containment)
|
|
160
|
+
const accepted = matchRequirement(current, payload, d.cfg.network);
|
|
161
|
+
if (!accepted) {
|
|
162
|
+
return { kind: 'payment_required', reason: 'requirements_mismatch', message: 'The chosen payment requirements no longer match the current ones (amount, rate, recipient or facilitator may have changed). No payment was taken; pay again with the new requirements.' };
|
|
163
|
+
}
|
|
164
|
+
const tx = payload.payload.transaction;
|
|
165
|
+
if (typeof tx !== 'string' || !tx)
|
|
166
|
+
return { kind: 'payment_required', reason: 'invalid_payload', message: 'payload.transaction is missing. No payment was taken.' };
|
|
167
|
+
const key = await sha256Hex(`${d.cfg.network}|${tx}`);
|
|
168
|
+
const claim = await d.ledger.claim(key, d.nowMs);
|
|
169
|
+
if (!claim.ok)
|
|
170
|
+
return { kind: 'conflict', state: claim.state };
|
|
171
|
+
const target = await facilitatorForFeePayer(d.cfg, accepted.extra.feePayer, d.nowMs);
|
|
172
|
+
if (!target) {
|
|
173
|
+
await d.ledger.release(key);
|
|
174
|
+
return { kind: 'unavailable', message: 'Could not reach the facilitator. No payment was taken.' };
|
|
175
|
+
}
|
|
176
|
+
const payment = { key, payload, accepted, facilitator: target.facilitator, server: target.server, settleUnknownSince: claim.state === 'settle_unknown' ? claim.since : null };
|
|
177
|
+
// Payment whose previous settlement result is unknown: do not verify again; decide on-chain in the settle step
|
|
178
|
+
if (payment.settleUnknownSince !== null)
|
|
179
|
+
return { kind: 'verified', payment };
|
|
180
|
+
try {
|
|
181
|
+
const v = await target.server.verifyPayment(payload, accepted);
|
|
182
|
+
if (!v.isValid) {
|
|
183
|
+
await d.ledger.release(key);
|
|
184
|
+
return { kind: 'payment_required', reason: v.invalidReason ?? 'invalid_payment', message: v.invalidMessage ?? 'Payment verification failed. No payment was taken.' };
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
catch (e) {
|
|
188
|
+
await d.ledger.release(key);
|
|
189
|
+
const rejected = definiteVerifyRejection(e);
|
|
190
|
+
if (rejected)
|
|
191
|
+
return { kind: 'payment_required', reason: rejected.reason, message: rejected.message ?? 'Payment verification failed. No payment was taken.' };
|
|
192
|
+
return { kind: 'unavailable', message: 'The facilitator did not respond. No payment was taken; please try again.' };
|
|
193
|
+
}
|
|
194
|
+
return { kind: 'verified', payment };
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Step 2 (only after the report is built): facilitator /settle → on-chain recheck with our RPC.
|
|
198
|
+
* If the settlement result is unknown (timeout, etc.), decide on-chain by the buyer's signature; if still unknown, leave it as "result unknown"
|
|
199
|
+
*/
|
|
200
|
+
export async function settleVerified(v, d) {
|
|
201
|
+
const { accepted, key } = v;
|
|
202
|
+
/** Not found on-chain → within the validity window, "result unknown" (awaiting recheck); after it, released as "not paid" */
|
|
203
|
+
const unknown = async (facilitatorSaid) => {
|
|
204
|
+
const since = v.settleUnknownSince ?? d.nowMs;
|
|
205
|
+
if (d.nowMs - since > SETTLE_UNKNOWN_EXPIRY_MS) {
|
|
206
|
+
await d.ledger.release(key);
|
|
207
|
+
return { kind: 'payment_required', reason: 'payment_expired', message: 'This payment did not land on chain and has expired. No payment was taken; please pay again.' };
|
|
208
|
+
}
|
|
209
|
+
await d.ledger.markSettleUnknown(key, since);
|
|
210
|
+
return {
|
|
211
|
+
kind: 'unavailable',
|
|
212
|
+
message: `${facilitatorSaid ? `The facilitator reported a settlement failure (${facilitatorSaid}), but the result is not final until the chain is checked. ` : 'The settlement result is not known yet. '}Retry later with the same PAYMENT-SIGNATURE and the result is decided from the chain record (if it settled you get the response; if it is still not on chain after it expires, it is treated as not paid).`,
|
|
213
|
+
};
|
|
214
|
+
};
|
|
215
|
+
/**
|
|
216
|
+
* When settlement failed or its result is unknown (no response, 4xx, 5xx, success:false): don't rely only on the facilitator; look on-chain first
|
|
217
|
+
* (the facilitator may have sent the tx and then returned a failure after timing out on confirmation, so money may have moved)
|
|
218
|
+
*/
|
|
219
|
+
const judgeOnChain = async (facilitatorSaid, reportedTx) => {
|
|
220
|
+
if (reportedTx) {
|
|
221
|
+
const t = await d.loadTx(reportedTx).catch(() => null);
|
|
222
|
+
if (t && satisfies(t, accepted))
|
|
223
|
+
return fromChain(t);
|
|
224
|
+
}
|
|
225
|
+
const tx = await findSettledOnChain(v, d).catch(() => null);
|
|
226
|
+
if (tx && satisfies(tx, accepted))
|
|
227
|
+
return fromChain(tx);
|
|
228
|
+
return unknown(facilitatorSaid);
|
|
229
|
+
};
|
|
230
|
+
const fromChain = (tx) => ({
|
|
231
|
+
kind: 'paid', confirmation: 'confirmed',
|
|
232
|
+
settlement: { success: true, transaction: tx.signature, network: accepted.network, payer: tx.accountKeys[0] },
|
|
233
|
+
});
|
|
234
|
+
// Payment with an unknown previous result → decide on-chain only (do not settle again)
|
|
235
|
+
if (v.settleUnknownSince !== null) {
|
|
236
|
+
const tx = await findSettledOnChain(v, d).catch(() => null);
|
|
237
|
+
if (tx && satisfies(tx, accepted))
|
|
238
|
+
return fromChain(tx);
|
|
239
|
+
return unknown();
|
|
240
|
+
}
|
|
241
|
+
let settlement;
|
|
242
|
+
try {
|
|
243
|
+
settlement = await v.server.settlePayment(v.payload, accepted);
|
|
244
|
+
}
|
|
245
|
+
catch (e) {
|
|
246
|
+
// Whether a 4xx failure response or no response (timeout, 5xx) → decide on-chain first
|
|
247
|
+
return judgeOnChain(settleFailureReason(e) ?? undefined);
|
|
248
|
+
}
|
|
249
|
+
if (!settlement.success) {
|
|
250
|
+
return judgeOnChain(settlement.errorReason ?? 'settle_failed', settlement.transaction || undefined);
|
|
251
|
+
}
|
|
252
|
+
// On-chain recheck (don't trust the facilitator response as is)
|
|
253
|
+
let confirmed = null;
|
|
254
|
+
for (const wait of [0, ...(d.confirmDelaysMs ?? [1000, 2000, 4000])]) {
|
|
255
|
+
if (wait)
|
|
256
|
+
await new Promise((r) => setTimeout(r, wait));
|
|
257
|
+
confirmed = await d.loadTx(settlement.transaction).catch(() => null);
|
|
258
|
+
if (confirmed)
|
|
259
|
+
break;
|
|
260
|
+
}
|
|
261
|
+
if (confirmed && !satisfies(confirmed, accepted)) {
|
|
262
|
+
await d.ledger.release(key);
|
|
263
|
+
return { kind: 'payment_required', reason: 'onchain_mismatch', message: 'On-chain record shows the receiving address did not receive the required amount.' };
|
|
264
|
+
}
|
|
265
|
+
// The facilitator reported success but it is not on-chain yet → the buyer may have paid, so deliver the report and mark it "pending confirmation"
|
|
266
|
+
return { kind: 'paid', settlement, confirmation: confirmed ? 'confirmed' : 'pending' };
|
|
267
|
+
}
|
|
268
|
+
export function paymentResponseHeader(s) {
|
|
269
|
+
return encodePaymentResponseHeader(s);
|
|
270
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agent402-dev/pay-server",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
"description": "Server helpers for x402 on Solana: accept USDC and optionally PREQ (Token-2022) through external facilitators. Verify, run your handler, then settle. Holds no funds and no private keys.",
|
|
4
|
+
"keywords": [
|
|
5
|
+
"x402",
|
|
6
|
+
"solana",
|
|
7
|
+
"usdc",
|
|
8
|
+
"token-2022",
|
|
9
|
+
"payments"
|
|
10
|
+
],
|
|
11
|
+
"main": "./dist/index.js",
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"default": "./dist/index.js"
|
|
17
|
+
},
|
|
18
|
+
"./*": {
|
|
19
|
+
"types": "./dist/*.d.ts",
|
|
20
|
+
"default": "./dist/*.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@solana/web3.js": "^1.98.0",
|
|
25
|
+
"@x402/core": "2.31.0",
|
|
26
|
+
"@x402/svm": "2.31.0"
|
|
27
|
+
},
|
|
28
|
+
"version": "0.2.0",
|
|
29
|
+
"author": "Agent402",
|
|
30
|
+
"license": "Apache-2.0",
|
|
31
|
+
"type": "module",
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=20"
|
|
34
|
+
},
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/agent402-dev/agent402-toolkit.git",
|
|
38
|
+
"directory": "packages/pay-server"
|
|
39
|
+
},
|
|
40
|
+
"homepage": "https://github.com/agent402-dev/agent402-toolkit/tree/main/packages/pay-server#readme",
|
|
41
|
+
"bugs": {
|
|
42
|
+
"url": "https://github.com/agent402-dev/agent402-toolkit/issues"
|
|
43
|
+
},
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
},
|
|
47
|
+
"files": [
|
|
48
|
+
"dist",
|
|
49
|
+
"README.md",
|
|
50
|
+
"LICENSE",
|
|
51
|
+
"NOTICE"
|
|
52
|
+
]
|
|
53
|
+
}
|