@wtflabs/x402-server 0.0.1-beta.2

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 ADDED
@@ -0,0 +1,313 @@
1
+ # @wtflabs/x402-server
2
+
3
+ X402 支付协议的服务端集成包,整合 facilitator、schema 和 viem client。
4
+
5
+ ## 安装
6
+
7
+ ```bash
8
+ npm install @wtflabs/x402-server @wtflabs/x402-facilitator @wtflabs/x402-schema viem
9
+ # 或
10
+ pnpm add @wtflabs/x402-server @wtflabs/x402-facilitator @wtflabs/x402-schema viem
11
+ ```
12
+
13
+ ## 使用
14
+
15
+ ```typescript
16
+ import { X402Server } from "@wtflabs/x402-server";
17
+ import { Facilitator } from "@wtflabs/x402-facilitator";
18
+ import { X402PaymentSchema } from "@wtflabs/x402-schema";
19
+ import { createPublicClient, http } from "viem";
20
+ import { bscTestnet } from "viem/chains";
21
+
22
+ // 创建 facilitator
23
+ const facilitator = new Facilitator({
24
+ recipientAddress: "0x1234...", // 商家地址 (EIP 7702)
25
+ relayer: "0x5678...", // 可选,内置 WTF Facilitator
26
+ waitUntil: "confirmed", // 可选
27
+ });
28
+
29
+ // 创建 schema
30
+ const schema = new X402PaymentSchema({
31
+ scheme: "exact",
32
+ network: "bsc-testnet",
33
+ maxAmountRequired: "100000",
34
+ resource: "http://localhost:3000/protected-resource",
35
+ description: "Access to protected resource with EIP-2612 Permit",
36
+ mimeType: "application/json",
37
+ payTo: "0x1234...", // 商家地址
38
+ maxTimeoutSeconds: 3600,
39
+ asset: "0x5678...", // token address
40
+ paymentType: "permit", // optional
41
+ outputSchema: {
42
+ input: {
43
+ type: "http",
44
+ method: "POST",
45
+ discoverable: true,
46
+ bodyFields: {},
47
+ },
48
+ output: {
49
+ message: "string",
50
+ authorizationType: "string",
51
+ payer: "string",
52
+ },
53
+ },
54
+ });
55
+
56
+ // 创建 viem public client
57
+ const client = createPublicClient({
58
+ chain: bscTestnet,
59
+ transport: http(),
60
+ });
61
+
62
+ // 创建 X402Server
63
+ const server = new X402Server({
64
+ facilitator,
65
+ schema,
66
+ client,
67
+ });
68
+
69
+ // 初始化服务器
70
+ const initResult = await server.initialize();
71
+ if (!initResult.success) {
72
+ console.error("初始化失败:", initResult.error);
73
+ }
74
+
75
+ // 验证配置
76
+ const verifyResult = await server.verify();
77
+ if (!verifyResult.success) {
78
+ console.error("验证失败:", verifyResult.errors);
79
+ }
80
+
81
+ // 验证支付
82
+ const paymentVerifyResult = await server.verifyPayment(
83
+ paymentPayload,
84
+ paymentRequirements
85
+ );
86
+
87
+ if (paymentVerifyResult.success) {
88
+ console.log("支付验证成功!支付者:", paymentVerifyResult.payer);
89
+ }
90
+
91
+ // 结算支付
92
+ const settleResult = await server.settle(paymentPayload, paymentRequirements);
93
+
94
+ if (settleResult.success) {
95
+ console.log("支付结算成功!交易哈希:", settleResult.transactionHash);
96
+ }
97
+ ```
98
+
99
+ ## API
100
+
101
+ ### `X402Server`
102
+
103
+ #### 构造函数
104
+
105
+ ```typescript
106
+ new X402Server(config: X402ServerConfig)
107
+ ```
108
+
109
+ **配置选项 (`X402ServerConfig`):**
110
+
111
+ - `facilitator`: Facilitator 实例
112
+ - `schema`: X402PaymentSchema 实例
113
+ - `client`: Viem PublicClient 实例
114
+
115
+ #### 方法
116
+
117
+ ##### `initialize()`
118
+
119
+ 初始化服务器,验证 schema 并添加 facilitator 数据到 schema 的 extra 字段。
120
+
121
+ - **返回:** `Promise<InitializeResult>`
122
+
123
+ ##### `verify()`
124
+
125
+ 验证配置是否正确:
126
+
127
+ 1. **自动检测 token 支持的支付方式** - 检测 token 是否支持 permit、eip3009 或 permit2
128
+ 2. **验证 facilitator 支持** - 检查 facilitator 的 `/supported` 接口是否包含该代币和链
129
+ 3. **验证链支持** - 检查当前配置的链是否在 facilitator 支持列表中
130
+ 4. 检查 client network 是否和 schema 的 network 匹配
131
+ 5. 检查 facilitator recipientAddress 是否和 schema payTo 一致
132
+
133
+ 该方法会自动检测代币合约的字节码,判断是否支持以下支付方式:
134
+ - **EIP-2612 Permit** - 通过检查 `permit(address,address,uint256,uint256,uint8,bytes32,bytes32)` 方法
135
+ - **EIP-3009** - 通过检查 `transferWithAuthorization` 方法
136
+ - **Permit2** - 通过检查 Permit2 合约是否部署在当前链上
137
+
138
+ - **返回:** `Promise<VerifyResult>`
139
+
140
+ ##### `verifyPayment(paymentPayload, paymentRequirements)`
141
+
142
+ 验证支付负载。
143
+
144
+ - **参数:**
145
+ - `paymentPayload`: 支付负载
146
+ - `paymentRequirements`: 支付要求
147
+ - **返回:** `Promise<{ success: boolean; payer?: string; error?: string }>`
148
+
149
+ ##### `settle(paymentPayload, paymentRequirements)`
150
+
151
+ 结算支付。
152
+
153
+ - **参数:**
154
+ - `paymentPayload`: 支付负载
155
+ - `paymentRequirements`: 支付要求
156
+ - **返回:** `Promise<SettleResult>`
157
+
158
+ ##### `getFacilitator()`
159
+
160
+ 获取 facilitator 实例。
161
+
162
+ - **返回:** `Facilitator`
163
+
164
+ ##### `getSchema()`
165
+
166
+ 获取 schema 实例。
167
+
168
+ - **返回:** `X402PaymentSchema`
169
+
170
+ ##### `getClient()`
171
+
172
+ 获取 viem client 实例。
173
+
174
+ - **返回:** `PublicClient`
175
+
176
+ ##### `isInitialized()`
177
+
178
+ 检查服务器是否已初始化。
179
+
180
+ - **返回:** `boolean`
181
+
182
+ ### Token 检测工具
183
+
184
+ #### `detectTokenPaymentMethods(tokenAddress, client)`
185
+
186
+ 独立的 token 支付方式检测工具函数,可以在不创建完整 server 实例的情况下使用。
187
+
188
+ ```typescript
189
+ import { detectTokenPaymentMethods } from "@wtflabs/x402-server";
190
+ import { createPublicClient, http } from "viem";
191
+ import { bscTestnet } from "viem/chains";
192
+
193
+ const client = createPublicClient({
194
+ chain: bscTestnet,
195
+ transport: http(),
196
+ });
197
+
198
+ const capabilities = await detectTokenPaymentMethods(
199
+ "0x25d066c4C68C8A6332DfDB4230263608305Ca991",
200
+ client
201
+ );
202
+
203
+ console.log("支持的支付方式:", capabilities.supportedMethods);
204
+ // 输出: ['permit'] 或 ['eip3009'] 或 ['permit2', 'permit2-witness']
205
+
206
+ console.log("检测详情:", capabilities.details);
207
+ // {
208
+ // hasEIP3009: false,
209
+ // hasPermit: true,
210
+ // hasPermit2Approval: true
211
+ // }
212
+ ```
213
+
214
+ - **参数:**
215
+ - `tokenAddress`: token 合约地址
216
+ - `client`: Viem PublicClient 实例
217
+ - **返回:** `Promise<TokenPaymentCapabilities>`
218
+
219
+ #### `getRecommendedPaymentMethod(capabilities)`
220
+
221
+ 根据检测结果获取推荐的支付方式(按优先级:permit2 > eip3009 > permit)。
222
+
223
+ ```typescript
224
+ import { getRecommendedPaymentMethod } from "@wtflabs/x402-server";
225
+
226
+ const recommended = getRecommendedPaymentMethod(capabilities);
227
+ console.log("推荐使用:", recommended); // 'permit2' | 'eip3009' | 'permit' | null
228
+ ```
229
+
230
+ - **参数:**
231
+ - `capabilities`: 从 `detectTokenPaymentMethods` 返回的检测结果
232
+ - **返回:** `PaymentMethod | null`
233
+
234
+ #### 类型定义
235
+
236
+ ```typescript
237
+ type PaymentMethod = "eip3009" | "permit" | "permit2" | "permit2-witness";
238
+
239
+ interface TokenPaymentCapabilities {
240
+ address: string;
241
+ supportedMethods: PaymentMethod[];
242
+ details: {
243
+ hasEIP3009: boolean;
244
+ hasPermit: boolean;
245
+ hasPermit2Approval: boolean;
246
+ };
247
+ }
248
+ ```
249
+
250
+ ## 完整示例
251
+
252
+ ```typescript
253
+ import { X402Server } from "@wtflabs/x402-server";
254
+ import { Facilitator } from "@wtflabs/x402-facilitator";
255
+ import { X402PaymentSchema } from "@wtflabs/x402-schema";
256
+ import { createPublicClient, http } from "viem";
257
+ import { bscTestnet } from "viem/chains";
258
+
259
+ async function main() {
260
+ // 1. 创建 facilitator
261
+ const facilitator = new Facilitator({
262
+ recipientAddress: "0x1234567890123456789012345678901234567890",
263
+ waitUntil: "confirmed",
264
+ });
265
+
266
+ // 2. 创建 schema
267
+ const schema = new X402PaymentSchema({
268
+ scheme: "exact",
269
+ network: "bsc-testnet",
270
+ maxAmountRequired: "100000",
271
+ resource: "http://localhost:3000/protected-resource",
272
+ description: "Access to protected resource",
273
+ mimeType: "application/json",
274
+ payTo: "0x1234567890123456789012345678901234567890",
275
+ maxTimeoutSeconds: 3600,
276
+ asset: "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd",
277
+ paymentType: "permit",
278
+ });
279
+
280
+ // 3. 创建 viem client
281
+ const client = createPublicClient({
282
+ chain: bscTestnet,
283
+ transport: http(),
284
+ });
285
+
286
+ // 4. 创建服务器
287
+ const server = new X402Server({
288
+ facilitator,
289
+ schema,
290
+ client,
291
+ });
292
+
293
+ // 5. 初始化
294
+ await server.initialize();
295
+
296
+ // 6. 验证配置
297
+ const verifyResult = await server.verify();
298
+ console.log("验证结果:", verifyResult);
299
+
300
+ // 7. 处理支付
301
+ // const settleResult = await server.settle(
302
+ // paymentPayload,
303
+ // paymentRequirements
304
+ // );
305
+ }
306
+
307
+ main();
308
+ ```
309
+
310
+ ## License
311
+
312
+ Apache-2.0
313
+
@@ -0,0 +1,221 @@
1
+ import { Facilitator } from '@wtflabs/x402-facilitator';
2
+ import { X402PaymentSchema } from '@wtflabs/x402-schema';
3
+ import { PublicClient } from 'viem';
4
+ import { PaymentPayload, PaymentRequirements } from '@wtflabs/x402/types';
5
+
6
+ /**
7
+ * X402Server 配置选项
8
+ */
9
+ interface X402ServerConfig {
10
+ /**
11
+ * Facilitator 实例
12
+ */
13
+ facilitator: Facilitator;
14
+ /**
15
+ * Payment Schema 实例
16
+ */
17
+ schema: X402PaymentSchema;
18
+ /**
19
+ * Viem Public Client 实例
20
+ */
21
+ client: PublicClient;
22
+ }
23
+ /**
24
+ * 初始化结果
25
+ */
26
+ interface InitializeResult {
27
+ success: boolean;
28
+ error?: string;
29
+ }
30
+ /**
31
+ * 验证结果
32
+ */
33
+ interface VerifyResult {
34
+ success: boolean;
35
+ errors?: string[];
36
+ }
37
+ /**
38
+ * 结算结果
39
+ */
40
+ interface SettleResult {
41
+ success: boolean;
42
+ transactionHash?: string;
43
+ error?: string;
44
+ }
45
+
46
+ /**
47
+ * X402Server 类
48
+ * 集成 facilitator, schema 和 client,提供完整的服务端支付处理
49
+ *
50
+ * @example
51
+ * ```typescript
52
+ * import { X402Server } from "@wtflabs/x402-server";
53
+ * import { Facilitator } from "@wtflabs/x402-facilitator";
54
+ * import { X402PaymentSchema } from "@wtflabs/x402-schema";
55
+ * import { createPublicClient, http } from "viem";
56
+ * import { bscTestnet } from "viem/chains";
57
+ *
58
+ * const facilitator = new Facilitator({
59
+ * recipientAddress: "0x1234...",
60
+ * });
61
+ *
62
+ * const schema = new X402PaymentSchema({
63
+ * scheme: "exact",
64
+ * network: "bsc-testnet",
65
+ * maxAmountRequired: "100000",
66
+ * resource: "http://localhost:3000/protected-resource",
67
+ * description: "Access to protected resource",
68
+ * mimeType: "application/json",
69
+ * payTo: "0x1234...",
70
+ * maxTimeoutSeconds: 3600,
71
+ * asset: "0x5678...",
72
+ * });
73
+ *
74
+ * const client = createPublicClient({
75
+ * chain: bscTestnet,
76
+ * transport: http(),
77
+ * });
78
+ *
79
+ * const server = new X402Server({
80
+ * facilitator,
81
+ * schema,
82
+ * client,
83
+ * });
84
+ *
85
+ * // 初始化和校验
86
+ * await server.initialize();
87
+ *
88
+ * // 验证
89
+ * const verifyResult = await server.verify();
90
+ *
91
+ * // 结算
92
+ * const settleResult = await server.settle(paymentPayload, paymentRequirements);
93
+ * ```
94
+ */
95
+ declare class X402Server {
96
+ private facilitator;
97
+ private schema;
98
+ private client;
99
+ private initialized;
100
+ constructor(config: X402ServerConfig);
101
+ /**
102
+ * 初始化服务器
103
+ * 初始化和校验 schema 等数据,对 schema 增加 facilitator 数据 extra: {relayer}
104
+ * 并获取 token 的 name 和 version 信息
105
+ */
106
+ initialize(): Promise<InitializeResult>;
107
+ /**
108
+ * 验证配置
109
+ * 1. 验证 client network 是否和 schema 的 network 匹配
110
+ * 2. 验证 facilitator recipientAddress 和 schema payTo 是否一致
111
+ */
112
+ _verify(): Promise<VerifyResult>;
113
+ /**
114
+ * 结算支付
115
+ * @param paymentPayload 支付负载
116
+ * @param paymentRequirements 支付要求
117
+ */
118
+ settle(paymentPayload: any, paymentRequirements: any): Promise<SettleResult>;
119
+ /**
120
+ * 验证支付负载
121
+ * @param paymentPayload 支付负载
122
+ * @param paymentRequirements 支付要求
123
+ */
124
+ verifyPayment(paymentPayload: any, paymentRequirements: any): Promise<{
125
+ success: boolean;
126
+ data?: string;
127
+ error?: string;
128
+ }>;
129
+ /**
130
+ * 获取 facilitator
131
+ */
132
+ getFacilitator(): Facilitator;
133
+ /**
134
+ * 获取 schema
135
+ */
136
+ getSchema(): X402PaymentSchema;
137
+ /**
138
+ * 获取 client
139
+ */
140
+ getClient(): PublicClient;
141
+ /**
142
+ * 检查是否已初始化
143
+ */
144
+ isInitialized(): boolean;
145
+ /**
146
+ * 验证网络是否匹配
147
+ * @param schemaNetwork schema 中的 network
148
+ * @param clientChainId client 的 chainId
149
+ * @returns 是否匹配
150
+ */
151
+ private validateNetwork;
152
+ /**
153
+ * 解析支付 header
154
+ * @param paymentHeaderBase64 Base64 编码的支付 header
155
+ * @returns 解析结果,成功时返回 paymentPayload 和 paymentRequirements,失败时返回服务端的支付要求
156
+ */
157
+ parsePaymentHeader(paymentHeaderBase64: string): {
158
+ success: true;
159
+ data: {
160
+ paymentPayload: PaymentPayload;
161
+ paymentRequirements: PaymentRequirements;
162
+ };
163
+ } | {
164
+ success: false;
165
+ data: PaymentRequirements;
166
+ error: string;
167
+ };
168
+ /**
169
+ * 验证客户端的支付数据是否与服务端要求一致
170
+ * @param paymentPayload 客户端的支付负载
171
+ * @param paymentRequirements 服务端的支付要求
172
+ * @returns 错误信息,如果验证通过则返回 null
173
+ */
174
+ private validatePaymentPayload;
175
+ }
176
+
177
+ /**
178
+ * Token 信息
179
+ */
180
+ interface TokenInfo {
181
+ name: string;
182
+ version: string;
183
+ }
184
+ /**
185
+ * 支持的支付方式
186
+ */
187
+ type PaymentMethod = "eip3009" | "permit" | "permit2" | "permit2-witness";
188
+ /**
189
+ * 检测结果
190
+ */
191
+ interface TokenPaymentCapabilities {
192
+ address: string;
193
+ supportedMethods: PaymentMethod[];
194
+ details: {
195
+ hasEIP3009: boolean;
196
+ hasPermit: boolean;
197
+ hasPermit2Approval: boolean;
198
+ };
199
+ }
200
+ /**
201
+ * 检测代币支持的支付方式
202
+ * @param tokenAddress 代币地址
203
+ * @param client viem PublicClient
204
+ * @returns 检测结果
205
+ */
206
+ declare function detectTokenPaymentMethods(tokenAddress: string, client: PublicClient): Promise<TokenPaymentCapabilities>;
207
+ /**
208
+ * 获取推荐的支付方式(仅返回 schema 支持的类型)
209
+ * 按优先级排序:eip3009 > permit > permit2
210
+ * 注意:permit2-witness 会被映射为 permit2,因为它们在 schema 中是同一种支付类型
211
+ */
212
+ declare function getRecommendedPaymentMethod(capabilities: TokenPaymentCapabilities): "eip3009" | "permit2" | "permit" | null;
213
+ /**
214
+ * 获取 token 的 name 和 version 信息(用于 EIP-712 签名)
215
+ * @param tokenAddress 代币地址
216
+ * @param client viem PublicClient
217
+ * @returns Token 的 name 和 version
218
+ */
219
+ declare function getTokenInfo(tokenAddress: string, client: PublicClient): Promise<TokenInfo>;
220
+
221
+ export { type InitializeResult, type PaymentMethod, type SettleResult, type TokenInfo, type TokenPaymentCapabilities, type VerifyResult, X402Server, type X402ServerConfig, detectTokenPaymentMethods, getRecommendedPaymentMethod, getTokenInfo };