跳转到主要内容

概述

x402x 是 x402x 协议的核心包,基于x402 核心包进行的拓展,提供EIP3009,EIP2616,Permit2协议的基础类型、Zod Schemas、EVM 工具与验证逻辑。通常由上层包(x402x-fetch / x402x-server / x402x-facilitator / x402x-detector)间接使用,也可在需要自定义编排时直接引入。

提供能力

  • 🧾 类型与 Zod Schemas:PaymentRequirementsPaymentPayloadResponse402
  • 🔐 EVM 工具:EIP-2612 Permit、EIP-3009、Permit2 签名与验证
  • ✅ 验证逻辑:金额/网络/签名/nonce 等校验
  • 🧩 模块化:shared、schemes、client、verify、facilitator、types

安装

npm i x402x@beta

模块与导出

import type { PaymentRequirements, PaymentPayload, Response402 } from "x402x/types";
其他常用入口:
// 共享 EVM 工具
import { getChainId, getNetworkName } from "x402x/shared/evm";

// 支付方案工具(exact)
import { createExactPaymentRequirements, validateExactPayment } from "x402x/schemes";

// 验证工具
import { verifyPermitSignature, verifyEIP3009Signature, verifyPermit2Signature } from "x402x/verify";

何时直接使用

  • 需要自定义验证或编排时直接引入底层类型与工具
  • 构建 facilitator 时

类型与 Schemas(示例)

// PaymentRequirements
interface PaymentRequirements {
  scheme: string;              // "exact"
  network: string;             // "bsc-testnet"
  maxAmountRequired: string;   // 金额(wei)
  asset: string;               // Token 地址
  paymentType?: string;        // permit/eip3009/permit2
  resource?: string;
  description?: string;
  mimeType?: string;
  maxTimeoutSeconds?: number;
  outputSchema?: Record<string, unknown>;
  extra?: Record<string, unknown>;
}
// Response402
interface Response402 {
  x402Version: number;           // 1
  accepts: PaymentRequirements[]; // 可接受的支付要求列表
  error?: string;
}
Zod 校验:
import { PaymentRequirementsSchema, Response402Schema } from "x402x/types";

const validated = PaymentRequirementsSchema.parse(unknownData);
const safe = Response402Schema.safeParse(unknownResp);

使用示例

创建 402 响应

import type { Response402, PaymentRequirements } from "x402x/types";

function create402Response(accepts: PaymentRequirements[], error?: string): Response402 {
  return { x402Version: 1, accepts, error };
}

EVM 工具

import { getChainId, getNetworkName } from "x402x/shared/evm";
const id = getChainId("bsc-testnet"); // 97
const name = getNetworkName(97);      // "bsc-testnet"

最佳实践

  • 使用 Zod Schema 对外部输入做运行时校验
  • 通过类型推导减少手写类型维护成本
  • 按需导入模块,避免全量打包

与其他包的关系

  • fetch:生成支付头与重试逻辑,依赖核心类型
  • server:创建要求/验证/结算编排,依赖验证和类型
  • facilitator:支付处理接口定义与返回类型
  • detector:仅依赖少量 EVM/类型工具

相关资源

  • 源代码:https://github.com/WTFLabs-WTF/x402x/tree/main/typescript/packages/x402x
  • 协议标准:EIP-2612、EIP-3009、Permit2