@agent402-dev/pay-server 0.0.0-stage → 0.1.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 +76 -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 +101 -0
- package/dist/gate.js +212 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +6 -0
- package/dist/pricing.d.ts +87 -0
- package/dist/pricing.js +127 -0
- package/dist/rates-file.d.ts +2 -0
- package/dist/rates-file.js +33 -0
- package/dist/rates.d.ts +26 -0
- package/dist/rates.js +41 -0
- package/dist/x402.d.ts +199 -0
- package/dist/x402.js +270 -0
- package/package.json +51 -4
package/dist/x402.d.ts
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
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
|
+
symbol: 'USDC' | 'A402';
|
|
10
|
+
mint: string;
|
|
11
|
+
decimals: number;
|
|
12
|
+
/** SPL Token 또는 Token-2022 프로그램 주소 */
|
|
13
|
+
tokenProgram: string;
|
|
14
|
+
}
|
|
15
|
+
export interface Offer {
|
|
16
|
+
asset: Asset;
|
|
17
|
+
amount: bigint;
|
|
18
|
+
/** A402 일 때 환율 근거 (extra.rate 로 공개) */
|
|
19
|
+
rate?: {
|
|
20
|
+
date: string;
|
|
21
|
+
a402Usd: number;
|
|
22
|
+
method: string;
|
|
23
|
+
discountPercent: number;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export interface NamedFacilitator {
|
|
27
|
+
name: string;
|
|
28
|
+
client: FacilitatorClient;
|
|
29
|
+
}
|
|
30
|
+
export interface X402Config {
|
|
31
|
+
network: string;
|
|
32
|
+
/** 수령 지갑 공개 주소 */
|
|
33
|
+
payTo: string;
|
|
34
|
+
/** 앞쪽이 기본, 뒤쪽이 예비 */
|
|
35
|
+
facilitators: NamedFacilitator[];
|
|
36
|
+
maxTimeoutSeconds: number;
|
|
37
|
+
}
|
|
38
|
+
interface Chosen {
|
|
39
|
+
facilitator: NamedFacilitator;
|
|
40
|
+
feePayer: string;
|
|
41
|
+
transactionVersions?: unknown;
|
|
42
|
+
server: x402ResourceServer;
|
|
43
|
+
}
|
|
44
|
+
/** 기본 → 예비 순서로, 이 네트워크 exact 를 지원하는 첫 facilitator */
|
|
45
|
+
export declare function chooseFacilitator(cfg: X402Config, nowMs: number): Promise<Chosen | null>;
|
|
46
|
+
/** 결제 조건의 feePayer 를 쓰는 facilitator (정산은 반드시 그 facilitator 로) */
|
|
47
|
+
export declare function facilitatorForFeePayer(cfg: X402Config, feePayer: unknown, nowMs: number): Promise<Chosen | null>;
|
|
48
|
+
export declare function clearSupportedCache(): void;
|
|
49
|
+
/** 결제 조건 만들기 — 공식 x402ResourceServer.buildPaymentRequirementsFromOptions (feePayer·transactionVersions 는 공식 SVM 서버가 채움) */
|
|
50
|
+
export declare function buildRequirements(cfg: X402Config, offers: Offer[], chosen: Chosen): Promise<PaymentRequirements[]>;
|
|
51
|
+
export interface X402Ledger {
|
|
52
|
+
/**
|
|
53
|
+
* 결제(키)를 잡음.
|
|
54
|
+
* new: 처음 → 정산 진행 / settled: 정산은 끝났고 리포트를 못 받은 결제 → 정산 건너뜀
|
|
55
|
+
* in_progress·fulfilled: 거절
|
|
56
|
+
*/
|
|
57
|
+
claim(key: string, nowMs: number): Promise<{
|
|
58
|
+
ok: true;
|
|
59
|
+
state: 'new';
|
|
60
|
+
}
|
|
61
|
+
/** 지난번 정산 요청의 결과를 모름 — 체인에서 판정해야 함 */
|
|
62
|
+
| {
|
|
63
|
+
ok: true;
|
|
64
|
+
state: 'settle_unknown';
|
|
65
|
+
since: number;
|
|
66
|
+
} | {
|
|
67
|
+
ok: false;
|
|
68
|
+
state: 'in_progress' | 'fulfilled';
|
|
69
|
+
}>;
|
|
70
|
+
/** 정산 요청 결과를 모름 (시간 초과 등) */
|
|
71
|
+
markSettleUnknown(key: string, nowMs: number): Promise<void>;
|
|
72
|
+
fulfill(key: string, nowMs: number): Promise<void>;
|
|
73
|
+
/** 정산 전 실패 → 풀어 줌 */
|
|
74
|
+
release(key: string): Promise<void>;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* 정산 결과를 모를 때, 이 시간이 지나도 체인에 없으면 그 트랜잭션은 더는 처리될 수 없음
|
|
78
|
+
* (blockhash 유효 150블록 ≈ 60~90초에 여유를 둠)
|
|
79
|
+
*/
|
|
80
|
+
export declare const SETTLE_UNKNOWN_EXPIRY_MS = 150000;
|
|
81
|
+
type LedgerEntry = {
|
|
82
|
+
state: 'in_progress';
|
|
83
|
+
at: number;
|
|
84
|
+
} | {
|
|
85
|
+
state: 'settle_unknown';
|
|
86
|
+
at: number;
|
|
87
|
+
} | {
|
|
88
|
+
state: 'fulfilled';
|
|
89
|
+
at: number;
|
|
90
|
+
};
|
|
91
|
+
/** 장부 상태 전이 (Durable Object 와 메모리 구현이 같이 씀) */
|
|
92
|
+
export declare function ledgerClaim(e: LedgerEntry | undefined, nowMs: number): {
|
|
93
|
+
next: LedgerEntry;
|
|
94
|
+
result: {
|
|
95
|
+
readonly ok: true;
|
|
96
|
+
readonly state: "new";
|
|
97
|
+
readonly since?: undefined;
|
|
98
|
+
};
|
|
99
|
+
} | {
|
|
100
|
+
next: {
|
|
101
|
+
state: "fulfilled";
|
|
102
|
+
at: number;
|
|
103
|
+
};
|
|
104
|
+
result: {
|
|
105
|
+
readonly ok: false;
|
|
106
|
+
readonly state: "fulfilled";
|
|
107
|
+
readonly since?: undefined;
|
|
108
|
+
};
|
|
109
|
+
} | {
|
|
110
|
+
next: {
|
|
111
|
+
state: "in_progress";
|
|
112
|
+
at: number;
|
|
113
|
+
};
|
|
114
|
+
result: {
|
|
115
|
+
readonly ok: false;
|
|
116
|
+
readonly state: "in_progress";
|
|
117
|
+
readonly since?: undefined;
|
|
118
|
+
};
|
|
119
|
+
} | {
|
|
120
|
+
next: LedgerEntry;
|
|
121
|
+
result: {
|
|
122
|
+
readonly ok: true;
|
|
123
|
+
readonly state: "settle_unknown";
|
|
124
|
+
readonly since: number;
|
|
125
|
+
};
|
|
126
|
+
};
|
|
127
|
+
export type { LedgerEntry };
|
|
128
|
+
export declare function memoryX402Ledger(): X402Ledger;
|
|
129
|
+
export declare function sha256Hex(s: string): Promise<string>;
|
|
130
|
+
export interface ProcessDeps {
|
|
131
|
+
cfg: X402Config;
|
|
132
|
+
ledger: X402Ledger;
|
|
133
|
+
/** 결제 네트워크에서 트랜잭션 읽기 (체인 재확인) */
|
|
134
|
+
loadTx: (signature: string) => Promise<TxRecordWithInstructions | null>;
|
|
135
|
+
/** 결제 네트워크에서 주소의 최근 서명 (정산 결과를 모를 때 판정용) */
|
|
136
|
+
recentSignatures: (address: string, limit: number) => Promise<string[]>;
|
|
137
|
+
/** 결제 수단 민트 → 토큰 프로그램 (수령 토큰 계정 주소 계산용) */
|
|
138
|
+
tokenProgramOf: (mint: string) => string;
|
|
139
|
+
nowMs: number;
|
|
140
|
+
/** 체인 재확인 재시도 간격 */
|
|
141
|
+
confirmDelaysMs?: number[];
|
|
142
|
+
}
|
|
143
|
+
/** 검증까지 끝난 결제 (아직 돈은 나가지 않음) */
|
|
144
|
+
export interface VerifiedPayment {
|
|
145
|
+
key: string;
|
|
146
|
+
payload: PaymentPayload;
|
|
147
|
+
accepted: PaymentRequirements;
|
|
148
|
+
facilitator: NamedFacilitator;
|
|
149
|
+
/** 그 facilitator 를 감싼 공식 리소스 서버 (verify·settle 호출) */
|
|
150
|
+
server: x402ResourceServer;
|
|
151
|
+
/** 지난번 정산 결과를 모르는 결제를 다시 처리하는 중이면 그 시각 */
|
|
152
|
+
settleUnknownSince: number | null;
|
|
153
|
+
}
|
|
154
|
+
export type VerifyOutcome = {
|
|
155
|
+
kind: 'payment_required';
|
|
156
|
+
reason: string;
|
|
157
|
+
message: string;
|
|
158
|
+
} | {
|
|
159
|
+
kind: 'conflict';
|
|
160
|
+
state: 'in_progress' | 'fulfilled';
|
|
161
|
+
} | {
|
|
162
|
+
kind: 'unavailable';
|
|
163
|
+
message: string;
|
|
164
|
+
} | {
|
|
165
|
+
kind: 'verified';
|
|
166
|
+
payment: VerifiedPayment;
|
|
167
|
+
};
|
|
168
|
+
export type SettleOutcome = {
|
|
169
|
+
kind: 'payment_required';
|
|
170
|
+
reason: string;
|
|
171
|
+
message: string;
|
|
172
|
+
} | {
|
|
173
|
+
kind: 'unavailable';
|
|
174
|
+
message: string;
|
|
175
|
+
}
|
|
176
|
+
/** confirmation: confirmed = 우리 RPC 로 체인에서 확인 / pending = facilitator 는 성공, 체인 확인은 아직 */
|
|
177
|
+
| {
|
|
178
|
+
kind: 'paid';
|
|
179
|
+
settlement: SettleResponse;
|
|
180
|
+
confirmation: 'confirmed' | 'pending';
|
|
181
|
+
};
|
|
182
|
+
/** 부분 서명된 트랜잭션(base64)에서 이미 채워진 서명들 (구매자 서명). 비어 있는 자리(전부 0)는 뺌 */
|
|
183
|
+
export declare function presentSignatures(txBase64: string): string[];
|
|
184
|
+
/**
|
|
185
|
+
* 정산 결과를 모를 때 체인에서 판정: 수령 토큰 계정의 최근 기록 중 구매자 서명이 들어 있는 트랜잭션을 찾음.
|
|
186
|
+
* 찾으면 그 트랜잭션, 없으면 null
|
|
187
|
+
*/
|
|
188
|
+
export declare function findSettledOnChain(v: VerifiedPayment, d: ProcessDeps): Promise<TxRecordWithInstructions | null>;
|
|
189
|
+
/**
|
|
190
|
+
* 1단계: PAYMENT-SIGNATURE 확인 → 장부에서 잡기 → facilitator /verify. 돈은 아직 나가지 않음.
|
|
191
|
+
* 호출자는 이 다음에 리포트를 만들고, 성공했을 때만 settleVerified 를 부름
|
|
192
|
+
*/
|
|
193
|
+
export declare function verifyPaymentHeader(header: string, resourcePath: string, current: PaymentRequirements[], d: ProcessDeps): Promise<VerifyOutcome>;
|
|
194
|
+
/**
|
|
195
|
+
* 2단계 (리포트를 만든 뒤에만): facilitator /settle → 우리 RPC 로 체인 재확인.
|
|
196
|
+
* 정산 결과를 모르면(시간 초과 등) 체인에서 구매자 서명으로 판정하고, 그래도 모르면 "결과 모름"으로 남김
|
|
197
|
+
*/
|
|
198
|
+
export declare function settleVerified(v: VerifiedPayment, d: ProcessDeps): Promise<SettleOutcome>;
|
|
199
|
+
export declare function paymentResponseHeader(s: SettleResponse): string;
|
package/dist/x402.js
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
// 표준 x402 v2 (exact, Solana) — 리소스 서버 쪽 처리 단계 (@agent402-dev/pay-server 내부, gate.ts 가 씀).
|
|
2
|
+
//
|
|
3
|
+
// 흐름: 검증 → (호출자의 작업) → 정산
|
|
4
|
+
// - verifyPaymentHeader: 결제가 고른 조건(accepted)이 지금 조건과 같은지(공식 매칭), resource 경로, 장부에서 잡기, facilitator verify
|
|
5
|
+
// - settleVerified: facilitator settle → 체인 재확인. 실패·결과 모름이면 체인에서 구매자 서명으로 판정,
|
|
6
|
+
// 없으면 "결과 모름"으로 두고 유효시간(150초)이 지나도 없을 때만 "결제 안 됨"
|
|
7
|
+
//
|
|
8
|
+
// 서버에는 수령 지갑 공개 주소만 있음. 수수료 대납(feePayer) 키는 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
|
+
/** facilitator 하나의 /supported 에서 이 네트워크 exact(v2) 의 feePayer (캐시) */
|
|
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 { /* 장애 → null (짧게 캐시해 다음 facilitator 로) */ }
|
|
32
|
+
supportedCache.set(key, { at: chosen ? nowMs : nowMs - SUPPORTED_TTL_MS + 30_000, chosen });
|
|
33
|
+
return chosen;
|
|
34
|
+
}
|
|
35
|
+
/** 기본 → 예비 순서로, 이 네트워크 exact 를 지원하는 첫 facilitator */
|
|
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
|
+
/** 결제 조건의 feePayer 를 쓰는 facilitator (정산은 반드시 그 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
|
+
/** 결제 조건 만들기 — 공식 x402ResourceServer.buildPaymentRequirementsFromOptions (feePayer·transactionVersions 는 공식 SVM 서버가 채움) */
|
|
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
|
+
* 정산 결과를 모를 때, 이 시간이 지나도 체인에 없으면 그 트랜잭션은 더는 처리될 수 없음
|
|
68
|
+
* (blockhash 유효 150블록 ≈ 60~90초에 여유를 둠)
|
|
69
|
+
*/
|
|
70
|
+
export const SETTLE_UNKNOWN_EXPIRY_MS = 150_000;
|
|
71
|
+
/** 장부 상태 전이 (Durable Object 와 메모리 구현이 같이 씀) */
|
|
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: 처리 중으로 잡되 원래 시각을 함께 돌려줌
|
|
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
|
+
/** 부분 서명된 트랜잭션(base64)에서 이미 채워진 서명들 (구매자 서명). 비어 있는 자리(전부 0)는 뺌 */
|
|
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
|
+
/** 체인 기록이 이 결제 조건을 만족하는지 */
|
|
118
|
+
function satisfies(tx, accepted) {
|
|
119
|
+
return !tx.err && receivedBy(tx, accepted.payTo, accepted.asset) >= BigInt(accepted.amount);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* 정산 결과를 모를 때 체인에서 판정: 수령 토큰 계정의 최근 기록 중 구매자 서명이 들어 있는 트랜잭션을 찾음.
|
|
123
|
+
* 찾으면 그 트랜잭션, 없으면 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
|
+
* 1단계: PAYMENT-SIGNATURE 확인 → 장부에서 잡기 → facilitator /verify. 돈은 아직 나가지 않음.
|
|
139
|
+
* 호출자는 이 다음에 리포트를 만들고, 성공했을 때만 settleVerified 를 부름
|
|
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
|
+
// 공식 매칭 규칙 (scheme·network·asset·amount·payTo·maxTimeoutSeconds 완전 일치 + extra 포함 관계)
|
|
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
|
+
// 지난번 정산 결과를 모르는 결제: 다시 verify 하지 않고 정산 단계에서 체인으로 판정
|
|
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
|
+
* 2단계 (리포트를 만든 뒤에만): facilitator /settle → 우리 RPC 로 체인 재확인.
|
|
198
|
+
* 정산 결과를 모르면(시간 초과 등) 체인에서 구매자 서명으로 판정하고, 그래도 모르면 "결과 모름"으로 남김
|
|
199
|
+
*/
|
|
200
|
+
export async function settleVerified(v, d) {
|
|
201
|
+
const { accepted, key } = v;
|
|
202
|
+
/** 체인에서 못 찾음 → 유효시간 안이면 "결과 모름"(재판정 대기), 지났으면 그때 비로소 "결제 안 됨"으로 풀어 줌 */
|
|
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
|
+
* 정산이 실패했거나 결과를 모를 때 (응답 없음·4xx·5xx·success:false 모두): facilitator 말만 믿지 않고 체인에서 먼저 찾음
|
|
217
|
+
* (facilitator 가 tx 를 보낸 뒤 확정 대기 시간 초과로 실패를 돌려주는 경우 — 돈은 나갔을 수 있음)
|
|
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
|
+
// 지난번 결과를 모르는 결제 → 체인으로만 판정 (다시 settle 하지 않음)
|
|
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
|
+
// 4xx 실패 응답이든 응답 없음(시간 초과·5xx)이든 → 체인에서 먼저 판정
|
|
247
|
+
return judgeOnChain(settleFailureReason(e) ?? undefined);
|
|
248
|
+
}
|
|
249
|
+
if (!settlement.success) {
|
|
250
|
+
return judgeOnChain(settlement.errorReason ?? 'settle_failed', settlement.transaction || undefined);
|
|
251
|
+
}
|
|
252
|
+
// 체인 재확인 (facilitator 응답을 그대로 믿지 않음)
|
|
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
|
+
// facilitator 는 성공이라 했는데 아직 체인에서 못 찾음 → 구매자가 돈을 냈을 수 있으므로 리포트는 드리고 "확인 대기"로 표시
|
|
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 A402 (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.1.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
|
+
}
|