From 2641eafd30054f3dd9d0b3bfdfa75696a20e2d97 Mon Sep 17 00:00:00 2001 From: "roger.gan" Date: Sun, 5 Jul 2026 07:59:12 +0800 Subject: [PATCH 01/12] docs(x402): align with SDK 1.0.0 (TypeScript-only) Update all x402 documentation (EN + zh-Hans) from the legacy Python/TS dual-SDK model (v0.6.0) to the TypeScript-only 1.0.0 SDK. Quickstarts (sellers, human, agent): rewritten from Python/FastAPI/ PostgreSQL to TypeScript (Express + agent-wallet), mirroring the runnable examples in examples/typescript/. Removed all x402-demo repository and hosted-endpoint references. Core concepts: payment schemes updated from exact_permit/exact/ exact_gasfree to the five 1.0.0 schemes (exact, upto, batch-settlement, auth-capture, exact_gasfree). http-402 payloads updated to the v2 payload.authorization structure. Facilitator/wallet/client-server token-approval references updated to Permit2/ERC-3009. sdk-features: rebuilt as a TypeScript-only feature matrix (11 packages, 5 schemes, signer factories, observability). index/faq/AGENTS updated to the TS-only SDK. api-catalog scheme names (exact_permit -> exact) synced. --- docs/x402/AGENTS.md | 12 +- docs/x402/api-catalog/get-started.md | 4 +- docs/x402/api-catalog/list-your-service.md | 12 +- docs/x402/api-catalog/reference.md | 4 +- docs/x402/core-concepts/client-server.md | 2 +- docs/x402/core-concepts/facilitator.md | 2 +- docs/x402/core-concepts/http-402.md | 90 +- .../network-and-token-support.md | 96 +- docs/x402/core-concepts/wallet.md | 6 +- docs/x402/faq.md | 43 +- .../getting-started/quickstart-for-agent.md | 30 +- .../getting-started/quickstart-for-human.md | 579 ++++-------- .../getting-started/quickstart-for-sellers.md | 756 ++++++--------- docs/x402/index.md | 6 +- docs/x402/sdk-features.md | 173 ++-- .../current/x402/AGENTS.md | 10 +- .../current/x402/api-catalog/get-started.md | 4 +- .../x402/api-catalog/list-your-service.md | 12 +- .../current/x402/api-catalog/reference.md | 4 +- .../x402/core-concepts/client-server.md | 2 +- .../current/x402/core-concepts/facilitator.md | 2 +- .../current/x402/core-concepts/http-402.md | 90 +- .../network-and-token-support.md | 94 +- .../current/x402/core-concepts/wallet.md | 2 +- .../current/x402/faq.md | 42 +- .../getting-started/quickstart-for-agent.md | 20 +- .../getting-started/quickstart-for-human.md | 682 +++++--------- .../getting-started/quickstart-for-sellers.md | 870 +++++++----------- .../current/x402/index.md | 6 +- .../current/x402/sdk-features.md | 243 +++-- 30 files changed, 1462 insertions(+), 2436 deletions(-) diff --git a/docs/x402/AGENTS.md b/docs/x402/AGENTS.md index 9a29d9ee..f18a8fb6 100644 --- a/docs/x402/AGENTS.md +++ b/docs/x402/AGENTS.md @@ -18,7 +18,7 @@ import TabItem from '@theme/TabItem'; - `docs/faq.md` — Frequently Asked Questions. - `sidebars.js` — Docusaurus sidebar configuration. - `docusaurus.config.js` — Main Docusaurus configuration file. -- `docs/sdk-features.md` — Feature comparison matrix for Python and TypeScript SDKs. +- `docs/sdk-features.md` — Feature matrix for the TypeScript-only x402 SDK (`@bankofai/x402-*` packages). --- @@ -27,16 +27,16 @@ import TabItem from '@theme/TabItem'; Documentation must reflect code changes immediately. Follow these dependency mappings: - Changes in `typescript/packages/` → Update TypeScript documentation. -- Changes in `python/x402/` → Update Python documentation. -- Endpoint logic changes → Update “Getting Started” guides. +- Changes in `examples/typescript/` → Update "Getting Started" guides and code samples (quickstarts mirror the examples). +- Endpoint logic changes → Update "Getting Started" guides. - Core mechanism changes → Update `core-concepts` documentation. --- ## 4. Style & Writing Standards -- Use **Python** as the primary example language (most feature-complete SDK). -- Provide **TypeScript** examples whenever supported. +- Use **TypeScript** as the primary example language (the SDK is TypeScript-only; the previous Python SDK lives under `legacy/`). +- Source code samples from the runnable `examples/typescript/` directory whenever possible. - All API examples **must include complete error handling**. - Target audience: developers with **2–5 years of experience**. - Use Docusaurus MDX components (``, ``) for multi-language examples. @@ -135,7 +135,7 @@ When SDK code changes in any of the following areas, you **must** update `docs/s - New signers added under the `*/signers/` directory. - New features introduced in the Client or Server components. -> **Note**: Always cross-check implementation progress between the **Python** and **TypeScript** SDKs when updating documentation. +> **Note**: The SDK is TypeScript-only. Cross-check documentation against `typescript/packages/` exports and `examples/typescript/` source. --- diff --git a/docs/x402/api-catalog/get-started.md b/docs/x402/api-catalog/get-started.md index 77680816..293cb271 100644 --- a/docs/x402/api-catalog/get-started.md +++ b/docs/x402/api-catalog/get-started.md @@ -58,7 +58,7 @@ x402-cli pay 'https://x402-gateway.bankofai.io/providers//' \ --method POST \ --network tron:mainnet \ --token USDT \ - --scheme exact_permit \ + --scheme exact \ --max-amount 0.000001 \ --header 'Content-Type: application/json' \ --body '{ ... }' @@ -69,7 +69,7 @@ x402-cli pay 'https://x402-gateway.bankofai.io/providers//' \ | `--method` | HTTP method (defaults to `GET`) | | `--network` | CAIP-2 payment chain, e.g. `tron:mainnet`, `eip155:56` | | `--token` | Settlement token, e.g. `USDT` | -| `--scheme` | x402 payment scheme declared by the route, e.g. `exact_permit` or `exact_gasfree` | +| `--scheme` | x402 payment scheme declared by the route, e.g. `exact` or `exact_gasfree` | | `--max-amount` | Spend ceiling in USD; the call aborts if the quote exceeds it | | `--header` / `--body` | Request headers and body for the upstream call | diff --git a/docs/x402/api-catalog/list-your-service.md b/docs/x402/api-catalog/list-your-service.md index aa9796de..4e9e8b32 100644 --- a/docs/x402/api-catalog/list-your-service.md +++ b/docs/x402/api-catalog/list-your-service.md @@ -76,13 +76,13 @@ An example based on the **SunPump** service (copied verbatim from `providers/sun "title": "SunPump", "mainTitle": "One-call agent token launch, paid via x402", "subtitle": "Create a meme or agent token from structured metadata.", - "description": "## What it does\n\nSunPump Agent Token Launch API lets agents, scripts, and applications pay with x402 and submit token launch metadata to SunPump. The gateway forwards the caller's JSON payload to the SunPump launch endpoint after payment settlement.\n\n## Best for\n\n- Agent workflows that need to create a meme or agent token from structured metadata.\n- Operator tools that want one paid API call for token creation.\n- Mainnet payment flows across TRON and BSC while using the same SunPump launch request shape.\n\n## Request shape\n\nPOST a JSON body with `name`, `symbol`, `description`, `imageBase64`, `twitterUrl`, `telegramUrl`, `websiteUrl`, and `tweetUsername`. Keep `name` within 1-20 characters and use a unique symbol. `imageBase64` may include a base64-encoded token image; if it is empty or omitted, SunPump generates an image automatically.\n\n## Code usage\n\nUse `x402-cli pay` against the route for the mainnet payment chain you want. TRON Mainnet example:\n\n```bash\nx402-cli pay 'https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron/pump-api/ai/agentTokenLaunch' \\\n --method POST \\\n --network tron:mainnet \\\n --token USDT \\\n --scheme exact_permit \\\n --max-amount 0.000001 \\\n --header 'Content-Type: application/json' \\\n --body '{\"name\":\"X402MainA\",\"symbol\":\"X4M17\",\"description\":\"x402 launch\",\"imageBase64\":\"\",\"twitterUrl\":\"\",\"telegramUrl\":\"\",\"websiteUrl\":\"\",\"tweetUsername\":\"\"}'\n```\n\nBSC Mainnet uses `sunpump-token-launch-bsc` with `eip155:56` and the same JSON body.", + "description": "## What it does\n\nSunPump Agent Token Launch API lets agents, scripts, and applications pay with x402 and submit token launch metadata to SunPump. The gateway forwards the caller's JSON payload to the SunPump launch endpoint after payment settlement.\n\n## Best for\n\n- Agent workflows that need to create a meme or agent token from structured metadata.\n- Operator tools that want one paid API call for token creation.\n- Mainnet payment flows across TRON and BSC while using the same SunPump launch request shape.\n\n## Request shape\n\nPOST a JSON body with `name`, `symbol`, `description`, `imageBase64`, `twitterUrl`, `telegramUrl`, `websiteUrl`, and `tweetUsername`. Keep `name` within 1-20 characters and use a unique symbol. `imageBase64` may include a base64-encoded token image; if it is empty or omitted, SunPump generates an image automatically.\n\n## Code usage\n\nUse `x402-cli pay` against the route for the mainnet payment chain you want. TRON Mainnet example:\n\n```bash\nx402-cli pay 'https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron/pump-api/ai/agentTokenLaunch' \\\n --method POST \\\n --network tron:mainnet \\\n --token USDT \\\n --scheme exact \\\n --max-amount 0.000001 \\\n --header 'Content-Type: application/json' \\\n --body '{\"name\":\"X402MainA\",\"symbol\":\"X4M17\",\"description\":\"x402 launch\",\"imageBase64\":\"\",\"twitterUrl\":\"\",\"telegramUrl\":\"\",\"websiteUrl\":\"\",\"tweetUsername\":\"\"}'\n```\n\nBSC Mainnet uses `sunpump-token-launch-bsc` with `eip155:56` and the same JSON body.", "useCase": "Use this provider when an app, agent, or CLI workflow needs to launch a SunPump token after a successful x402 payment. Choose the route matching the intended mainnet payment chain: TRON Mainnet or BSC Mainnet.", "i18n": { "zh-CN": { "title": "SunPump", "subtitle": "用结构化元数据一次付费发币(meme/Agent 代币)。", - "description": "## 能做什么\n\nSunPump Agent 发币 API 允许 Agent、脚本和应用先完成 x402 支付,再把发币元数据提交给 SunPump。Gateway 在支付结算后把调用方的 JSON 请求体转发到 SunPump 发币接口。\n\n## 适合场景\n\n- 需要基于结构化元数据创建 meme token 或 agent token 的 Agent 工作流。\n- 希望用一次付费 API 调用完成发币的运营工具。\n- 在 TRON 和 BSC 主网上使用同一套 SunPump 发币请求格式验证支付流程。\n\n## 请求格式\n\nPOST JSON 请求体包含 `name`、`symbol`、`description`、`imageBase64`、`twitterUrl`、`telegramUrl`、`websiteUrl` 和 `tweetUsername`。`name` 需要保持在 1-20 个字符内,并使用唯一 symbol。`imageBase64` 可以传入 base64 编码的 token 图片;如果为空或不传,SunPump 会自动生成图片。\n\n## 代码用法\n\n使用 `x402-cli pay` 调用目标主网支付链对应的路由。TRON 主网示例:\n\n```bash\nx402-cli pay 'https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron/pump-api/ai/agentTokenLaunch' \\\n --method POST \\\n --network tron:mainnet \\\n --token USDT \\\n --scheme exact_permit \\\n --max-amount 0.000001 \\\n --header 'Content-Type: application/json' \\\n --body '{\"name\":\"X402MainA\",\"symbol\":\"X4M17\",\"description\":\"x402 launch\",\"imageBase64\":\"\",\"twitterUrl\":\"\",\"telegramUrl\":\"\",\"websiteUrl\":\"\",\"tweetUsername\":\"\"}'\n```\n\nBSC 主网使用 `sunpump-token-launch-bsc` 和 `eip155:56`,请求体相同。", + "description": "## 能做什么\n\nSunPump Agent 发币 API 允许 Agent、脚本和应用先完成 x402 支付,再把发币元数据提交给 SunPump。Gateway 在支付结算后把调用方的 JSON 请求体转发到 SunPump 发币接口。\n\n## 适合场景\n\n- 需要基于结构化元数据创建 meme token 或 agent token 的 Agent 工作流。\n- 希望用一次付费 API 调用完成发币的运营工具。\n- 在 TRON 和 BSC 主网上使用同一套 SunPump 发币请求格式验证支付流程。\n\n## 请求格式\n\nPOST JSON 请求体包含 `name`、`symbol`、`description`、`imageBase64`、`twitterUrl`、`telegramUrl`、`websiteUrl` 和 `tweetUsername`。`name` 需要保持在 1-20 个字符内,并使用唯一 symbol。`imageBase64` 可以传入 base64 编码的 token 图片;如果为空或不传,SunPump 会自动生成图片。\n\n## 代码用法\n\n使用 `x402-cli pay` 调用目标主网支付链对应的路由。TRON 主网示例:\n\n```bash\nx402-cli pay 'https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron/pump-api/ai/agentTokenLaunch' \\\n --method POST \\\n --network tron:mainnet \\\n --token USDT \\\n --scheme exact \\\n --max-amount 0.000001 \\\n --header 'Content-Type: application/json' \\\n --body '{\"name\":\"X402MainA\",\"symbol\":\"X4M17\",\"description\":\"x402 launch\",\"imageBase64\":\"\",\"twitterUrl\":\"\",\"telegramUrl\":\"\",\"websiteUrl\":\"\",\"tweetUsername\":\"\"}'\n```\n\nBSC 主网使用 `sunpump-token-launch-bsc` 和 `eip155:56`,请求体相同。", "useCase": "适合应用、Agent 或 CLI 流程在 x402 支付成功后调用 SunPump 发币接口。根据主网支付链选择 TRON 主网或 BSC 主网路由。", "mainTitle": "一次付费完成 Agent 代币发行(x402)" } @@ -112,13 +112,13 @@ An example based on the **SunPump** service (copied verbatim from `providers/sun { "network": "tron:mainnet", "provider": "sunpump-token-launch-tron", - "scheme": "exact_permit", + "scheme": "exact", "url": "https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron/pump-api/ai/agentTokenLaunch" }, { "network": "eip155:56", "provider": "sunpump-token-launch-bsc", - "scheme": "exact_permit", + "scheme": "exact", "url": "https://x402-gateway.bankofai.io/providers/sunpump-token-launch-bsc/pump-api/ai/agentTokenLaunch" } ], @@ -181,7 +181,7 @@ x402-cli pay 'https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tr --method POST \ --network tron:mainnet \ --token USDT \ - --scheme exact_permit \ + --scheme exact \ --max-amount 0.000001 \ --header 'Content-Type: application/json' \ --body '{"name":"X402MainA","symbol":"X4M17","description":"x402 launch","imageBase64":"","twitterUrl":"","telegramUrl":"","websiteUrl":"","tweetUsername":""}' @@ -194,7 +194,7 @@ x402-cli pay 'https://x402-gateway.bankofai.io/providers/sunpump-token-launch-bs --method POST \ --network eip155:56 \ --token USDT \ - --scheme exact_permit \ + --scheme exact \ --max-amount 0.000001 \ --header 'Content-Type: application/json' \ --body '{"name":"X402BscA","symbol":"X4B17","description":"x402 launch","imageBase64":"","twitterUrl":"","telegramUrl":"","websiteUrl":"","tweetUsername":""}' diff --git a/docs/x402/api-catalog/reference.md b/docs/x402/api-catalog/reference.md index d6be91aa..35760085 100644 --- a/docs/x402/api-catalog/reference.md +++ b/docs/x402/api-catalog/reference.md @@ -62,7 +62,7 @@ An endpoint may serve the same capability across several chains, each settling t |---|---|---| | `network` | string | CAIP-2 chain ID this route settles on (e.g. `tron:mainnet`, `eip155:56`) | | `provider` | string | The gateway provider `fqn` that handles this network | -| `scheme` | string | x402 payment scheme for this route, e.g. `exact_permit` or `exact_gasfree` — each route declares its own | +| `scheme` | string | x402 payment scheme for this route, e.g. `exact` or `exact_gasfree` — each route declares its own | | `url` | string | Full gateway URL for this network's route | The build passes this through to outputs as `x402_routes`. When present, callers/agents pick the route matching their intended payment chain; the top-level `url` remains the default route. @@ -74,7 +74,7 @@ x402-cli pay 'https://x402-gateway.bankofai.io/providers//' \ --method POST \ --network tron:mainnet \ --token USDT \ - --scheme exact_permit \ + --scheme exact \ --max-amount 0.000001 \ --header 'Content-Type: application/json' \ --body '{ ... }' diff --git a/docs/x402/core-concepts/client-server.md b/docs/x402/core-concepts/client-server.md index ab60aa69..a968f5d8 100644 --- a/docs/x402/core-concepts/client-server.md +++ b/docs/x402/core-concepts/client-server.md @@ -23,7 +23,7 @@ Clients can take many forms, including: - **Initiate Requests**: Send the initial HTTP request to the resource server. - **Handle Payment Requirements**: Parse the `402 Payment Required` response and extract payment details. -- **Manage Token Approvals**: Approve the `PaymentPermit` contract to transfer tokens from the client’s wallet for settlement. +- **Manage Token Approvals**: Authorize Permit2 (one-time `approve(Permit2)`) for plain ERC-20/TRC-20 tokens; ERC-3009 tokens need no approve. The SDK auto-broadcasts this on first payment. - **Prepare Payment Payload**: Construct and sign a payment payload according to server requirements. - **Retry with Payment**: Attach the `PAYMENT-SIGNATURE` header and resend the request. diff --git a/docs/x402/core-concepts/facilitator.md b/docs/x402/core-concepts/facilitator.md index a53b4efb..5228e2f0 100644 --- a/docs/x402/core-concepts/facilitator.md +++ b/docs/x402/core-concepts/facilitator.md @@ -11,7 +11,7 @@ A Facilitator is a middleware service primarily responsible for: - **Payload Verification**: Validating the payment payload submitted by the client. - **Settlement Execution**: Submitting transactions to the blockchain on behalf of the server to complete settlement. -- **Token Transfer**: Executing token transfers by calling the `permitTransferFrom` method of the `PaymentPermit` contract. +- **Token Transfer**: Executing the on-chain transfer — ERC-3009 `transferWithAuthorization`, Permit2 `permitTransferFrom` via the `x402ExactPermit2Proxy`, a batch-settlement claim, or a GasFree relay, depending on the scheme. By introducing a Facilitator, servers no longer need to maintain direct connections to blockchain nodes or implement complex signature verification logic themselves. This reduces operational complexity while ensuring accurate and real-time transaction validation. diff --git a/docs/x402/core-concepts/http-402.md b/docs/x402/core-concepts/http-402.md index 5e4d0550..07a636f9 100644 --- a/docs/x402/core-concepts/http-402.md +++ b/docs/x402/core-concepts/http-402.md @@ -52,7 +52,7 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- }, "accepts": [ { - "scheme": "exact_permit", + "scheme": "exact", "network": "tron:nile", "amount": "100", "asset": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", @@ -71,15 +71,9 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- } ], "extensions": { - "paymentPermitContext": { - "meta": { - "kind": "PAYMENT_ONLY", - "paymentId": "0xb08d71cabc27d5552e36a7f60084e130", - "nonce": "11984290373079535093514815017206530944", - "validAfter": 1770816589, - "validBefore": 1770820189 - } - } + // Present only when the token needs a gas-sponsored Permit2 approve + // (plain ERC-20 like BSC USDC). ERC-3009 tokens omit this. + "erc20ApprovalGasSponsoring": {} } } ``` @@ -98,7 +92,7 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- }, "accepts": [ { - "scheme": "exact_permit", + "scheme": "exact", "network": "eip155:97", "amount": "100000000000000", "asset": "0x337610d27c682E347C9cD60BD4b3b107C9d34dDd", @@ -117,15 +111,9 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- } ], "extensions": { - "paymentPermitContext": { - "meta": { - "kind": "PAYMENT_ONLY", - "paymentId": "0xc00fc79b9a26084ad078b71ffcaa07fd", - "nonce": "94261896388554187915350651456800860604", - "validAfter": 1770817158, - "validBefore": 1770820758 - } - } + // BSC USDT is a plain ERC-20 → the Permit2 path needs this gas-sponsoring + // extension so the client can sign the one-time approve offline. + "erc20ApprovalGasSponsoring": {} } } ``` @@ -141,14 +129,14 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- | `error` | Human-readable error message | | `resource` | Information about the requested resource | | `accepts` | Array of accepted payment options | -| `scheme` | Payment scheme (`exact_permit` or `exact`) | +| `scheme` | Payment scheme (`exact`, `upto`, `batch-settlement`, `auth-capture`, or `exact_gasfree`) | | `network` | Network identifier (`tron:nile`, `tron:mainnet`, `eip155:56`, `eip155:97`) | | `amount` | Payment amount in the smallest unit (e.g., 100 = 0.0001 USDT) | | `asset` | TRC-20/BEP-20 token contract address | | `payTo` | Seller's wallet address | | `maxTimeoutSeconds` | Maximum validity duration of the payment | | `extra.fee` | Facilitator fee information (includes `facilitatorId`, `feeTo`, `feeAmount`, `caller`) | -| `extensions` | Additional context for the payment scheme (e.g., `paymentPermitContext` with nonce, validity window) | +| `extensions` | Additional context for the payment scheme (e.g., gas-sponsoring, payment-identifier) | ## Payment Signature Structure @@ -160,29 +148,18 @@ The client responds via the `PAYMENT-SIGNATURE` header with a signed payload: ```json { "x402Version": 2, - "scheme": "exact_permit", + "scheme": "exact", "network": "tron:nile", "payload": { "signature": "0x...", - "permit": { - "meta": { - "kind": 0, - "paymentId": "0x65f9d4ca3fb5f6dd14930055aa5ccbc4", - "nonce": "241054476753796864345738420545497456919", - "validAfter": 1770817311, - "validBefore": 1770820911 - }, - "buyer": "", - "caller": "", - "payment": { - "payToken": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", - "payAmount": 100, - "payTo": "" - }, - "fee": { - "feeTo": "", - "feeAmount": 100 - } + "authorization": { + // Permit2 witness (USDT/USDD on TRON are plain TRC-20) + "from": "", + "to": "", + "value": 100, + "validAfter": 1770817311, + "validBefore": 1770820911, + "nonce": "0x65f9d4ca3fb5f6dd14930055aa5ccbc4" } } } @@ -194,29 +171,18 @@ The client responds via the `PAYMENT-SIGNATURE` header with a signed payload: ```json { "x402Version": 2, - "scheme": "exact_permit", + "scheme": "exact", "network": "eip155:97", "payload": { "signature": "0x...", - "permit": { - "meta": { - "kind": 0, - "paymentId": "0xc00fc79b9a26084ad078b71ffcaa07fd", - "nonce": "94261896388554187915350651456800860604", - "validAfter": 1770817158, - "validBefore": 1770820758 - }, - "buyer": "", - "caller": "", - "payment": { - "payToken": "0x337610d27c682E347C9cD60BD4b3b107C9d34dDd", - "payAmount": 100000000000000, - "payTo": "" - }, - "fee": { - "feeTo": "", - "feeAmount": 100000000000000 - } + "authorization": { + // Permit2 witness (BSC USDT is a plain ERC-20) + "from": "", + "to": "", + "value": 100000000000000, + "validAfter": 1770817158, + "validBefore": 1770820758, + "nonce": "0xc00fc79b9a26084ad078b71ffcaa07fd" } } } diff --git a/docs/x402/core-concepts/network-and-token-support.md b/docs/x402/core-concepts/network-and-token-support.md index 9d2ece04..42b03c4d 100644 --- a/docs/x402/core-concepts/network-and-token-support.md +++ b/docs/x402/core-concepts/network-and-token-support.md @@ -63,14 +63,13 @@ By default, **USDT** and **USDD** are used as primary settlement currencies. | **USDD** | `tron:nile` | `TGjgvdTWWrybVLaVeFqSyVqJQWjxqRYbaK` | | **USDT** | `eip155:56` | `0x55d398326f99059fF775485246999027B3197955` | | **USDC** | `eip155:56` | `0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d` | -| **EPS** | `eip155:56` | `0xA7f552078dcC247C2684336020c03648500C6d9F` | | **USDT** | `eip155:97` | `0x337610d27c682E347C9cD60BD4b3b107C9d34dDd` | | **USDC** | `eip155:97` | `0x64544969ed7EBf5f083679233325356EbE738930` | | **DHLU** | `eip155:97` | `0x375cADdd2cB68cE82e3D9B075D551067a7b4B816` | > **Extensibility**: The protocol is highly extensible. By registering tokens in the `TokenRegistry`, you can easily support any custom TRC-20 or BEP-20 token. -> **Token selection for the `exact` scheme**: The `exact` scheme requires a token that natively implements ERC-3009 `transferWithAuthorization`. For BSC testnet `exact` interoperability testing, the recommended asset is **DHLU** (Da Hulu). `USDT (BEP-20)` does not natively support ERC-3009 — do NOT advertise `exact` payment requirements with the BSC USDT contract. If you need USDT on BSC, use the `exact_permit` scheme instead. +> **Token selection for the `exact` scheme**: ERC-3009 tokens (e.g. BSC testnet **DHLU**) settle gaslessly via `transferWithAuthorization`. Plain ERC-20 tokens (e.g. BSC USDC/USDT, TRON USDT/USDD) settle via the Permit2 path — the client auto-broadcasts a one-time `approve(Permit2)` on first payment. The per-token method is data in the server's `accepts[].price.extra`: ERC-3009 → `{ name, version }`; plain ERC-20 → `{ assetTransferMethod: "permit2" }`. --- @@ -106,38 +105,34 @@ When configuring an `HTTP 402` payment request on the server side, you must expl --- -## Payment Scheme +## Payment Schemes -x402 supports three payment schemes: `exact_permit`, `exact`, and `exact_gasfree`. +x402 1.0.0 supports five payment schemes. Each is implemented as a client + server + facilitator trio per chain family. -### `exact_permit` Scheme +### `exact` Scheme -The `exact_permit` scheme transfers tokens via the `PaymentPermit` contract, suitable for: +The `exact` scheme pays the exact amount advertised. It covers two token transfer paths: -- **Pay-per-use APIs** (e.g., LLM token generation, image generation services) -- **Metered resources** (cloud compute time, storage usage, bandwidth consumption) -- **Dynamic pricing services** based on actual usage +- **ERC-3009 `transferWithAuthorization`** — for tokens that natively support it (e.g. BSC testnet DHLU). Gasless: no `approve` needed; the client signs a typed-data authorization and the facilitator calls `transferWithAuthorization` on-chain. +- **Permit2** — for plain ERC-20 / TRC-20 tokens that do not implement ERC-3009 (e.g. BSC USDC/USDT, TRON USDT/USDD). The client signs a Permit2 witness and the facilitator settles via the `x402ExactPermit2Proxy` contract. A one-time `approve(Permit2)` is required; the client auto-broadcasts it on first payment. -### `exact` Scheme +The `exact` scheme conforms to the **v2 wire format** published by the **x402 Foundation**: a stock v2 client can pay a protected endpoint on this SDK's server directly, and this SDK's client can pay any v2-compliant server — no project-specific translation required. Transfer authorization data is carried in `payload.authorization`. -The `exact` scheme is for tokens that natively support ERC-3009 `transferWithAuthorization`. It does not require the `PaymentPermit` contract. +### `upto` Scheme -Since **v0.5.9**, the `exact` scheme on both EVM and TRON conforms to the v2 specification published by the **x402 Foundation (formerly Coinbase)**: +Usage-based billing. The client signs a Permit2 authorization for up to a **maximum** amount; the server decides the **real usage** per request and settles only that (≤ max). One signature shape, a different charge each request — ideal for **metered billing** (LLM token usage, compute time, bandwidth). Available on EVM and TRON (both Permit2). -- **V2 wire format**: The `payload` of `exact` conforms to the v2 spec field layout and semantics. A stock v2 client can pay a protected endpoint on this SDK's server directly, and this SDK's client can pay any v2-compliant server — no project-specific translation required. -- **Structured authorization**: The `nativeExact` / `nativeExactEvm` / `nativeExactTron` mechanisms have been updated to emit a V2-compatible `payload` — using a typed-field authorization structure instead of the previous flat hex blob. Transfer authorization data is carried in `payload.authorization`. -- **Migration fallback**: To reduce disruption during rollout, the client dual-writes both `payload.authorization` (V2) and `extensions.transferAuthorization` (V1); the server prefers `payload.authorization` and keeps a temporary fallback for the legacy field. -- **BSC interop smoke tests**: The `examples/bsc-testnet-smoke/` directory provides BSC testnet interoperability smoke tests (TypeScript and Python), validating both the "Coinbase official client → BANK OF AI server" and "BANK OF AI client → Coinbase official server" directions. +### `batch-settlement` Scheme -### `exact_gasfree` Scheme +A payment-channel scheme for high-frequency micro-payments (e.g. AI agent per-token billing). The payer **deposits once** on-chain, then pays many requests with off-chain **vouchers**; the facilitator **claims** a batch and **settles** to `payTo` in a single tx — so N requests cost ~one deposit's worth of gas. Includes a **refund** path for the unused balance. Available on EVM and TRON. -The `exact_gasfree` scheme is a TRON-specific payment mechanism that allows users to pay with USDT/USDD **without holding TRX for gas fees**. Settlement is handled via the official GasFree Proxy through the BANK OF AI facilitator endpoint. +### `auth-capture` Scheme -Key characteristics: +Escrow-style authorization capture (EVM only). Funds are authorized into an escrow contract and released per business logic. -- **Zero gas cost for buyers**: Buyers do not need to hold TRX — gas is covered by the GasFree infrastructure -- **No API keys required**: All GasFree API calls route through the BANK OF AI proxy at `https://facilitator.bankofai.io/{mainnet,nile}`, so clients do not need to configure `GASFREE_API_KEY` or `GASFREE_API_SECRET` -- **TRON only**: Available on `tron:mainnet` and `tron:nile` +### `exact_gasfree` Scheme + +TRON-specific. Allows buyers to pay with USDT/USDD **without holding TRX for gas fees**. The payer signs a TIP-712 GasFree permit and a relayer pays the on-chain energy via the official GasFree Proxy — no TRX for the payer, no one-time `approve`. Funds come from the payer's GasFree custodial wallet (not the main wallet). Available on `tron:mainnet` and `tron:nile`. #### GasFree Account Management (via x402-payment skill) @@ -160,33 +155,33 @@ npx tsx x402-payment/src/x402_invoke.ts --gasfree-activate --network nile --toke ### How Payment Schemes Work 1. **Authorize** - The client signs a message authorizing a **maximum amount**. + The client signs a typed-data message authorizing the payment (exact amount, or a maximum for `upto`/`batch-settlement`). 2. **Execute** - The server performs the requested task and calculates the **actual cost**. + The server performs the requested task and (for usage-based schemes) calculates the **actual cost**. 3. **Settle** - The Facilitator submits the on-chain transaction based on the actual cost. + The Facilitator submits the on-chain transaction — `transferWithAuthorization`, Permit2 `permitTransferFrom`, a batch claim, or a GasFree relay — based on the scheme. --- ## Deploying a Private Facilitator -You may deploy your own Facilitator node to gain full control over payment verification and settlement. +You may deploy your own Facilitator to gain full control over payment verification and settlement. The self-hosted example (`examples/typescript/facilitator/basic`) is an Express service exposing `/verify`, `/settle`, `/supported` — no database required. ### Core Responsibilities -1. **Verify** – Validate signatures and payload integrity -2. **Submit** – Construct and broadcast the `transferFrom` transaction -3. **Monitor** – Track on-chain confirmations to ensure final settlement +1. **Verify** – Validate typed-data signatures and payload integrity +2. **Submit** – Construct and broadcast the on-chain settlement transaction +3. **Monitor** – Track on-chain confirmations to ensure final settlement ### Deployment Requirements -- **Node Access** – Reliable full-node RPC access (e.g., TronGrid or self-hosted node) -- **Gas Funding** – A wallet with sufficient **TRX/BNB** to cover transaction gas fees -- **Service Deployment** – Clone and configure the x402 Facilitator service +- **Node Access** – Reliable RPC access (e.g. TronGrid or a public BSC endpoint) +- **Gas Funding** – A wallet with sufficient **TRX/BNB** to cover settlement gas fees +- **Service Deployment** – Run the example facilitator from `examples/typescript/facilitator/basic` -> For detailed configuration and API references, see the [Facilitator](./facilitator.md) documentation. +> For detailed configuration and API references, see the [Facilitator](./facilitator.md) documentation and the [Quickstart for Sellers](../getting-started/quickstart-for-sellers.md). --- @@ -196,30 +191,29 @@ You may deploy your own Facilitator node to gain full control over payment verif | :------------- | :---------------------- | | **Networks** | `tron:mainnet`, `tron:shasta`, `tron:nile`, `eip155:56`, `eip155:97` | | **Token Standard** | TRC-20 (built-in USDT & USDD support), BEP-20 | -| **Signing Mechanism** | Typed data signing | -| **Payment Scheme** | `exact_permit`, `exact`, `exact_gasfree` (TRON only) | +| **Signing Mechanism** | TIP-712 / EIP-712 typed data signing | +| **Payment Schemes** | `exact`, `upto`, `batch-settlement`, `auth-capture` (EVM), `exact_gasfree` (TRON) | --- ## Adding Custom Tokens -You can support custom TRC-20/BEP-20 tokens by registering them in the `TokenRegistry`: +On the **client / facilitator** side, register a custom TRC-20 token via the TRON token registry (`@bankofai/x402-tron`): -```python -from bankofai.x402.tokens import TokenRegistry, TokenInfo +```typescript +import { registerToken } from "@bankofai/x402-tron"; -TokenRegistry.register_token( - "tron:nile", - TokenInfo( - address="", - decimals=6, - name="My Token", - symbol="MYT", - ), -) +registerToken("tron:nile", { + address: "", + decimals: 6, + name: "My Token", + symbol: "MYT", +}); ``` -Once registered, you can use the custom token symbol in `prices` (e.g., `"0.01 MYT"`). +On the **resource server** side, custom EVM tokens are advertised by adding an entry to the server's `EVM_TOKENS` table in `src/chains/evm.ts` — an explicit `{ asset, amount, extra }` object. Adding a chain is one table entry; no SDK changes are needed. + +Once registered, you can use the custom token symbol in TRON prices (e.g., `"0.001 MYT"`). --- @@ -230,6 +224,6 @@ x402 is deeply tailored for blockchain-native architectures, providing seamless ### Key Takeaways - **Development Environment**: Use testnets for development and debugging. -- **Default Settlement Asset**: **USDT** is the primary default token with preconfigured SDK support. -- **Security Model**: Typed data signing ensures secure, trust-minimized payment authorization. -- **Extensibility**: Expand support for any custom TRC-20/BEP-20 token via the `TokenRegistry`. +- **Default Settlement Asset**: **USDT** is the primary default token with preconfigured SDK support. +- **Security Model**: TIP-712 / EIP-712 typed data signing ensures secure, trust-minimized payment authorization. +- **Extensibility**: Expand support for any custom TRC-20/BEP-20 token via the TRON token registry (`registerToken`) or the server's `EVM_TOKENS` config table. diff --git a/docs/x402/core-concepts/wallet.md b/docs/x402/core-concepts/wallet.md index b7025a07..0a653850 100644 --- a/docs/x402/core-concepts/wallet.md +++ b/docs/x402/core-concepts/wallet.md @@ -76,11 +76,7 @@ x402 uses typed data signing for secure payment authorization. ## Token Approval -For the `exact_permit` payment scheme, the client must authorize the `PaymentPermit` contract to transfer tokens from their wallet for settlement. - -This is completed via the standard TRC-20/BEP-20 `approve` function. - -The x402 client SDK automatically handles this process. +For the `exact` payment scheme, plain ERC-20/TRC-20 tokens (e.g. BSC USDC/USDT, TRON USDT/USDD) settle via the Permit2 path. The client must authorize the Permit2 contract to transfer tokens — a one-time `approve(Permit2, max)`. The x402 client SDK auto-broadcasts this approve on the first payment. ERC-3009 tokens (e.g. BSC testnet DHLU) need no approve — they settle gaslessly via `transferWithAuthorization`. --- diff --git a/docs/x402/faq.md b/docs/x402/faq.md index ec5bf581..c051570c 100644 --- a/docs/x402/faq.md +++ b/docs/x402/faq.md @@ -27,12 +27,13 @@ Not at all. Any Web API or content provider—whether Web3-native or traditional #### What languages and frameworks are supported? -x402 currently provides the following SDKs: +x402 1.0.0 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packages: -- **Python**: Server integration with FastAPI and Flask; `httpx`-based client -- **TypeScript**: Server middleware for Hono and Express; standard `fetch` client +- **Server middleware**: Express, Fastify, Hono, Next.js +- **Client**: wrapped `fetch` (`@bankofai/x402-fetch`), Axios, MCP transport +- **Facilitator**: chain-agnostic engine with per-scheme verify + settle -Both SDKs fully implement Client, Server, and Facilitator functionality. As of **v0.6.0**, the TypeScript SDK reaches feature parity with Python across the Server and Facilitator roles (facilitator client/engine, server middleware, and `exact` / `exact_permit` / `exact_gasfree` verify + settle). +The previous Python SDK lives under `legacy/` for reference. --- @@ -63,23 +64,26 @@ Common pricing models include: - **Flat rate per call**: e.g., `1 USDT` per request - **Tiered pricing**: Different prices for endpoints like `/basic` and `/pro` -- **`exact_permit` / `exact` scheme**: Pay the exact amount determined by the service +- **`exact` scheme**: Pay the exact amount advertised per call #### What payment schemes does x402 support? -x402 supports three payment schemes: +x402 1.0.0 supports five payment schemes: -- **`exact_permit`** and **`exact`**: Both allow the client to authorize a **maximum payment amount**, and the server to settle the **actual cost incurred** (up to the authorized limit). This is ideal for **metered billing**, **LLM token usage**, and similar use cases. Since v0.5.9, the wire `payload` of the `exact` scheme conforms to the v2 specification published by the **x402 Foundation (formerly Coinbase)**. -- **`exact_gasfree`** (TRON only): Allows buyers to pay with USDT/USDD without holding TRX for gas. All GasFree API calls are routed through the BANK OF AI proxy — no API keys required on the client side. +- **`exact`**: Pay the exact advertised amount. ERC-3009 tokens (e.g. BSC testnet DHLU) settle gaslessly via `transferWithAuthorization`; plain ERC-20/TRC-20 tokens (e.g. BSC USDC/USDT, TRON USDT/USDD) settle via the Permit2 path with a one-time `approve(Permit2)`. The `exact` wire payload conforms to the **x402 Foundation** v2 spec. +- **`upto`**: Usage-based billing — the client signs a Permit2 authorization for up to a **maximum**; the server settles only the **real usage** (≤ max). Ideal for **metered billing**, **LLM token usage**. +- **`batch-settlement`**: Payment-channel for high-frequency micro-payments — deposit once, pay many requests with off-chain vouchers, settle in one batch tx. Includes a refund path. +- **`auth-capture`** (EVM only): Escrow-style authorization capture. +- **`exact_gasfree`** (TRON only): Allows buyers to pay with USDT/USDD without holding TRX for gas. A relayer pays the on-chain energy via the GasFree API — no API keys required on the client side. #### Can this SDK interoperate with the x402 Foundation (formerly Coinbase) v2 reference implementation? -**Yes.** Since v0.5.9, the `exact` payment scheme (EVM and TRON) conforms to the v2 specification published by the **x402 Foundation (formerly Coinbase)**: +**Yes.** The `exact` payment scheme (EVM and TRON) conforms to the v2 specification published by the **x402 Foundation**: - A stock v2 client can directly access this SDK's `exact` protected endpoints with no project-specific adapter layer. - This SDK's client can pay v2-compatible servers directly. - In the V2 structure, transfer authorization data is carried in the `payload.authorization` field (a structured object). As a migration fallback, the client also populates `extensions.transferAuthorization` so that servers still running older versions can parse the payload. -- When using the `exact` scheme on BSC, the advertised asset **must** natively implement ERC-3009 `transferWithAuthorization` — for example, **DHLU** on BSC testnet. BSC USDT is a plain ERC-20 and natively supports neither ERC-3009 nor EIP-2612 permit — if you need to accept USDT, use the `exact_permit` scheme instead (which is backed by this project's `PaymentPermit` proxy contract and works with any ERC-20). +- BSC USDT/USDC are plain ERC-20s (no ERC-3009). They settle via the Permit2 path under the `exact` scheme — the client auto-broadcasts a one-time `approve(Permit2)` on first payment. ERC-3009 tokens like BSC testnet **DHLU** settle gaslessly with no approve. - The `examples/bsc-testnet-smoke/` directory contains smoke tests for bidirectional interoperability (Coinbase official client → BANK OF AI server, BANK OF AI client → Coinbase official server) that you can use as a debugging and integration reference. --- @@ -97,12 +101,11 @@ x402 supports three payment schemes: | TRON Nile (`tron:nile`) | USDD (TRC-20) | **Testnet** | | BSC Mainnet (`eip155:56`) | USDT (BEP-20) | **Mainnet** | | BSC Mainnet (`eip155:56`) | USDC (BEP-20) | **Mainnet** | -| BSC Mainnet (`eip155:56`) | EPS (BEP-20) | **Mainnet** | | BSC Testnet (`eip155:97`) | USDT (BEP-20) | **Testnet** | | BSC Testnet (`eip155:97`) | USDC (BEP-20) | **Testnet** | | BSC Testnet (`eip155:97`) | DHLU (BEP-20, for `exact` interop tests) | **Testnet** | -Custom TRC-20 and BEP-20 tokens can also be added via the TokenRegistry. +Custom TRC-20 tokens can be added via the TRON token registry (`registerToken` from `@bankofai/x402-tron`); custom BEP-20 tokens are advertised by adding an entry to the server's `EVM_TOKENS` config table. #### What fees are involved? @@ -125,7 +128,7 @@ Custom TRC-20 and BEP-20 tokens can also be added via the TokenRegistry. #### How does refunds work? -The `exact_permit` / `exact` scheme uses a **push payment** model—once executed on-chain, it is irreversible. +The `exact` scheme uses a **push payment** model — once settled on-chain, it is irreversible. The `batch-settlement` scheme, by contrast, supports an on-chain **refund** path for the unused channel balance. Refund options: @@ -155,12 +158,12 @@ The flow mirrors a human user: #### How do I run x402 locally? -1. **Clone the repository:** Download the [x402-demo repository](https://github.com/BofAI/x402-demo). -2. **Install dependencies:** Run `pip install -r requirements.txt`. -3. **Configure environment:** Copy `.env.example` to `.env` and configure your private keys. -4. **Start Facilitator:** `python facilitator/main.py` -5. **Start Server:** `python server/main.py` -6. **Run Client:** `python client/main.py` +1. **Clone the repository:** `git clone https://github.com/BofAI/x402.git` +2. **Install + build:** `cd x402/typescript && pnpm install && pnpm build` +3. **Configure environment:** `cd examples/typescript && cp .env-exact.example .env-exact` and fill in `AGENT_WALLET_PRIVATE_KEY` + payout addresses +4. **Start Facilitator:** `pnpm dev:facilitator` (terminal 1, `:4022`) +5. **Start Server:** `pnpm dev:server` (terminal 2, `:4021`) +6. **Run Client:** `pnpm dev:client` (terminal 3) #### Which testnet is recommended? @@ -199,4 +202,4 @@ Check the `error` field in the server’s JSON response for detailed diagnostics ### Still Have Questions? • Submit a GitHub Issue in the [x402 repository](https://github.com/BofAI/x402) -• Refer to [x402-demo](https://github.com/BofAI/x402-demo) for a complete, runnable example +• Refer to the [runnable examples](https://github.com/BofAI/x402/tree/main/examples/typescript) in the x402 repository for a complete client → server → facilitator loop diff --git a/docs/x402/getting-started/quickstart-for-agent.md b/docs/x402/getting-started/quickstart-for-agent.md index 482aa8fc..e266fbf5 100644 --- a/docs/x402/getting-started/quickstart-for-agent.md +++ b/docs/x402/getting-started/quickstart-for-agent.md @@ -9,6 +9,10 @@ This guide walks you through: setting up a dedicated agent wallet, configuring c --- +:::info SDK 1.0.0 (TypeScript-only) +x402 `1.0.0` is a **TypeScript-only** SDK. The `x402-payment` skill wraps the new `@bankofai/x402-*` packages and uses [Agent Wallet](../../Agent-Wallet/QuickStart.md) for key custody — the wallet/private-key setup in this guide is unchanged. You can also drive payments directly from the runnable [MCP examples](https://github.com/BofAI/x402/tree/main/examples/typescript) (`servers/mcp` + `clients/mcp`). +::: + ## Prerequisites ### 1. Create a Dedicated Agent Wallet @@ -89,7 +93,11 @@ When `TRON_GRID_API_KEY` is not set, requests may be rate-limited under heavy wo -No additional configuration needed for BSC. +For BSC testnet, the default viem RPC endpoint is frequently unreachable. Set a reliable RPC: + +```bash +export EVM_RPC_URL="https://bsc-testnet-rpc.publicnode.com" +``` @@ -128,17 +136,22 @@ For a detailed walkthrough of the interactive installation process, see the [Ski After completing the setup, follow these steps to verify your agent can complete payments autonomously: -### 3.1 Test with the Demo Endpoint +### 3.1 Test with a Local Paid Endpoint -Instruct your AI agent to access the following demo URL (this is a test endpoint that requires payment): +Start the example trio from `examples/typescript`, then point your agent at the local server: +```bash +cd x402/examples/typescript +cp .env-exact.example .env-exact # fill AGENT_WALLET_PRIVATE_KEY + payout addresses +pnpm dev:facilitator # terminal 1 (:4022) +pnpm dev:server # terminal 2 (:4021) ``` -https://x402-demo.bankofai.io/protected-nile -``` + +Then instruct your agent to access `http://localhost:4021/weather`. **The agent should automatically complete the following flow (no human intervention required):** -1. Send a GET request to the demo URL +1. Send a GET request to the endpoint 2. Receive an HTTP 402 (Payment Required) response from the server 3. Read the payment requirements from the response headers (amount, network, recipient address) 4. Sign a payment authorization using the configured private key @@ -186,7 +199,7 @@ Before deploying your agent to production, make sure to review the following: | `Private key not found` or signing fails | Environment variable not set or misconfigured | Re-run Step 1, and make sure you run the agent **in the same terminal session** | | Insufficient balance error | No test tokens in the agent wallet | Go back to Prerequisites and claim test tokens from the faucet | | Request times out | Network issue or RPC rate limiting | Configure `TRON_GRID_API_KEY` for better performance | -| Agent accesses successfully but balance doesn't change | May have accessed a free endpoint | Confirm the URL path is `/protected-nile`, not another path | +| Agent accesses successfully but balance doesn't change | May have accessed a free endpoint | Confirm the URL path is `/weather` (the paid route), not another path | --- @@ -200,6 +213,7 @@ Before deploying your agent to production, make sure to review the following: ## References +- [x402 repository](https://github.com/BofAI/x402) — SDK source and runnable examples (`examples/typescript/`) +- [MCP examples](https://github.com/BofAI/x402/tree/main/examples/typescript/clients/mcp) — agent payments over MCP transport - [OpenClaw Extension Repository](https://github.com/BofAI/openclaw-extension) - [x402-payment on ClawHub](https://github.com/BofAI/skills/tree/main/x402-payment) -- [x402 Demo Project](https://github.com/BofAI/x402-demo) diff --git a/docs/x402/getting-started/quickstart-for-human.md b/docs/x402/getting-started/quickstart-for-human.md index f8d074a8..59b8c027 100644 --- a/docs/x402/getting-started/quickstart-for-human.md +++ b/docs/x402/getting-started/quickstart-for-human.md @@ -5,10 +5,14 @@ import TabItem from '@theme/TabItem'; ## Who Is This Guide For? -This guide is for developers who want to **call an x402-protected API from code** and have payments handled automatically. When you're done, you'll have a working Python or TypeScript script that detects a 402 response, pays for access, and retrieves the protected content — all without manual steps. +This guide is for developers who want to **call an x402-protected API from code** and have payments handled automatically. When you're done, you'll have a working TypeScript script that detects a 402 response, pays for access, and retrieves the protected content — all without manual steps. > **Testnet first:** This guide uses testnet by default. You can safely follow every step without spending real money. +:::info SDK 1.0.0 (TypeScript-only) +x402 `1.0.0` is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packages. This guide uses the runnable fetch client in the [`x402` repository](https://github.com/BofAI/x402) (`examples/typescript/clients/fetch`), which links the in-repo SDK packages and runs from source. +::: + --- ## Prerequisites @@ -19,7 +23,7 @@ This guide is for developers who want to **call an x402-protected API from code* > > - Your **private key** is the sole credential that controls your wallet. Anyone who has it can access your funds completely. > - This guide requires you to configure a private key. Follow these rules strictly: -> 1. **Never** write your private key directly in code files (e.g. `client.py`) +> 1. **Never** write your private key directly in code files > 2. **Never** commit a file containing a private key to Git or push it to GitHub > 3. **Never** send your private key via messaging apps, email, or chat > 4. Store it only in a local `.env` file or as a system environment variable @@ -27,10 +31,10 @@ This guide is for developers who want to **call an x402-protected API from code* ### Checklist Before You Start -- [ ] **Python 3.11+** or **Node.js 20+** installed (depending on your chosen language) +- [ ] **Node.js 20+** and **pnpm 11+** installed - [ ] A dedicated **test wallet** created (see below) - [ ] Test tokens claimed (free) -- [ ] A target x402-protected API URL (or use our demo endpoint) +- [ ] A target x402-protected API URL (or run the example server) ### Create a Test Wallet and Get Test Tokens @@ -85,95 +89,61 @@ This guide is for developers who want to **call an x402-protected API from code* --- -## Step One: Install the SDK - - - - -Run the following in your terminal: - -```bash -pip install "bankofai-x402[tron] @ git+https://github.com/BofAI/x402.git#subdirectory=python/x402" -``` - -Also install EVM (BSC) dependencies: - -```bash -pip install eth_account web3 -``` - -Verify the installation: - -```bash -python -c "import bankofai.x402; print('Installation successful!')" -``` - -> ✅ **Success check:** Terminal prints `Installation successful!` +## Step One: Get the SDK and Examples -Or install from source: +The examples workspace links the in-repo `@bankofai/x402-*` packages and runs from source: ```bash git clone https://github.com/BofAI/x402.git -cd x402/python/x402 -pip install -e . -``` +cd x402/typescript # the pnpm/turbo monorepo root - - +# Install + link all workspace packages (SDK + examples) +pnpm install -In your project directory, run: +# Build the @bankofai/x402-* dist the examples import from +pnpm build -```bash -npm install @bankofai/x402 tronweb dotenv +cd examples/typescript ``` -Since `@bankofai/x402` is an ESM module, add the following to your `package.json` if not already present: - -```json -{ - "type": "module" -} -``` - -> 💡 If you see `ERR_PACKAGE_PATH_NOT_EXPORTED` when running with `npx tsx`, this `"type": "module"` entry is usually the fix. - -> ✅ **Success check:** `npm install` completes and `node_modules/@bankofai` folder exists - - - - ---- +The fetch client depends on `@bankofai/x402-fetch`, `@bankofai/x402-evm`, `@bankofai/x402-tron`, and `@bankofai/agent-wallet` — all linked automatically by `pnpm install`. :::info Wallet Management -x402 SDK uses [Agent Wallet](../../Agent-Wallet/QuickStart.md) to resolve and manage wallet credentials. Agent Wallet is automatically installed as a dependency of x402. Private key resolution priority: +x402 uses [Agent Wallet](../../Agent-Wallet/QuickStart.md) to resolve and manage wallet credentials. Agent Wallet is installed as a dependency of the examples. Private key resolution priority: 1. Encrypted wallet file (imported via the Agent Wallet CLI) 2. Environment variable `AGENT_WALLET_PRIVATE_KEY` This guide uses the environment variable method. ::: +--- + ## Step Two: Configure Your Private Key -**Never put your private key in code.** Store it as an environment variable so it stays out of your source files. Replace `your_private_key_here` with the private key you exported in the Prerequisites step. +**Never put your private key in code.** Store it as an environment variable so it stays out of your source files. Copy the env template and fill in your key: ```bash -export AGENT_WALLET_PRIVATE_KEY=your_private_key_here +cp .env-exact.example .env-exact ``` -> 💡 **Tip:** To make this permanent across terminal sessions, add the line to your shell profile: -> ```bash -> echo 'export AGENT_WALLET_PRIVATE_KEY=your_key' >> ~/.zshrc # for zsh (macOS default) -> echo 'export AGENT_WALLET_PRIVATE_KEY=your_key' >> ~/.bashrc # for bash (Linux default) -> source ~/.zshrc # or source ~/.bashrc — apply immediately without restarting the terminal -> ``` - -Verify the variable was set: +Open `.env-exact` and set the payer variables: ```bash -echo $AGENT_WALLET_PRIVATE_KEY +# ── SHARED · client (you are the payer) ────────────────────────────────── +AGENT_WALLET_PRIVATE_KEY=your_private_key_here + +# TronGrid API key — optional on testnet, recommended for production TRON. +TRON_GRID_API_KEY= + +# ── CLIENT · which chains/tokens to pay ────────────────────────────────── +# [@] e.g. tron:nile@USDT or eip155:97@DHLU +PAY_TARGETS=tron:nile@USDT + +# The x402-protected API you want to call. +RESOURCE_URL=http://localhost:4021/weather ``` -> ✅ **Success check:** Terminal prints your private key string (not blank) +> 💡 **Tip:** `PAY_TARGETS` controls which chain/token the client pays with, one payment per entry, in order. Omit the token to use that network's first advertised token. Use `@` (not `#`) — dotenv treats `#` as a comment. @@ -181,11 +151,9 @@ echo $AGENT_WALLET_PRIVATE_KEY **Optional:** For production TRON workloads, configure a TronGrid API Key for better RPC reliability: ```bash -export TRON_GRID_API_KEY="your_trongrid_api_key_here" +TRON_GRID_API_KEY="your_trongrid_api_key_here" ``` -> 💡 **How to get a TronGrid API Key:** Register for free at [TronGrid](https://www.trongrid.io/), create an API Key, and paste it above. - :::note When `TRON_GRID_API_KEY` is not set, requests may be rate-limited under heavy workloads. For production, set your own `TRON_GRID_API_KEY` to ensure reliability. ::: @@ -193,415 +161,180 @@ When `TRON_GRID_API_KEY` is not set, requests may be rate-limited under heavy wo -No additional configuration needed for BSC. +For BSC testnet, the default viem RPC endpoint is frequently unreachable. Set a reliable RPC: + +```bash +EVM_RPC_URL=https://bsc-testnet-rpc.publicnode.com +``` +> ⚠️ **Security reminder:** Keep your private key only in `.env-exact` (gitignored) or as an environment variable. **Never commit files containing private keys to Git or share them with anyone.** + --- ## Step Three: Write and Run the Client Code -Create a new file (e.g. `client.py` or `client.ts`) and paste the code for your chosen chain and language: - - - - - - -```python -import asyncio -import httpx +The example fetch client wraps `fetch` so HTTP `402 Payment Required` challenges are paid automatically. Here is the entry point (`examples/typescript/clients/fetch/src/index.ts`), abridged to the essentials: -from bankofai.x402.clients import X402Client, X402HttpClient, SufficientBalancePolicy -from bankofai.x402.mechanisms.tron.exact_permit import ExactPermitTronClientMechanism -from bankofai.x402.mechanisms.tron.exact_gasfree.client import ExactGasFreeClientMechanism -from bankofai.x402.signers.client import TronClientSigner -from bankofai.x402.utils.gasfree import GasFreeAPIClient -from bankofai.x402.config import NetworkConfig - - -# ========== Configuration ========== -# The x402-protected API you want to call. -# The URL below is our demo endpoint — use it to verify your setup works end-to-end. -SERVER_URL = "https://x402-demo.bankofai.io/protected-nile" -# ==================================== - -# GasFree API clients (routed through BANK OF AI proxy — no API keys needed) -gasfree_clients = { - "tron:nile": GasFreeAPIClient(NetworkConfig.get_gasfree_api_base_url("tron:nile")), - "tron:mainnet": GasFreeAPIClient(NetworkConfig.get_gasfree_api_base_url("tron:mainnet")), +```typescript +import { x402Client, wrapFetchWithPayment } from "@bankofai/x402-fetch"; + +import { registerEvm } from "./chains/evm.js"; +import { registerTron } from "./chains/tron.js"; + +const RESOURCE_URL = process.env.RESOURCE_URL || "http://localhost:4021/weather"; + +// The selector is the payment-selection policy: pick which advertised option to pay. +// PAY_TARGETS drives this in the full example; here we accept the first option. +let target: { prefix: string; asset?: string } | null = null; +const client = new x402Client((_x402Version, accepts) => { + const t = target; + if (!t) return accepts[0]!; + const match = accepts.find( + (a) => + a.network.startsWith(t.prefix) && + (!t.asset || a.asset.toLowerCase() === t.asset.toLowerCase()), + ); + if (!match) throw new Error(`server offered no payment option matching "${t.prefix}"`); + return match; +}); + +// Register each chain only if its wallet resolves (EVM-only, TRON-only, or both). +const evm = await registerEvm(client); +const tron = await registerTron(client); + +const fetchWithPay = wrapFetchWithPayment(fetch, client); + +// Pay the resource once per target, in order. +const targets = [{ prefix: "tron:", asset: undefined }]; // simplified +for (const t of targets) { + target = t; + console.log(`\n→ GET ${RESOURCE_URL}`); + const res = await fetchWithPay(RESOURCE_URL); + console.log(`← ${res.status} ${res.statusText}`); + console.log(JSON.stringify(await res.json(), null, 2)); } - - -async def main(): - # Initialize signer via agent-wallet (resolves wallet from environment automatically) - signer = await TronClientSigner.create() - - # Create x402 client and register payment mechanisms and balance policy - x402_client = X402Client() - x402_client.register("tron:*", ExactPermitTronClientMechanism(signer)) - x402_client.register("tron:*", ExactGasFreeClientMechanism(signer, clients=gasfree_clients)) - x402_client.register_policy(SufficientBalancePolicy) - - async with httpx.AsyncClient(timeout=120) as http_client: - client = X402HttpClient(http_client, x402_client) - - # Make the request — the SDK handles payment automatically - response = await client.get(SERVER_URL) - - print(f"Status: {response.status_code}") - print("Response:", response.text) - - -asyncio.run(main()) ``` -**Run the script:** +### How each chain is registered -```bash -python client.py -``` +Each chain lives in its own module under `src/chains/`. A chain registers only if its agent-wallet resolves — so you can pay from EVM-only, TRON-only, or both. -**Expected output:** + + -``` -Status: 200 -Response: {"data": "This is premium content!"} +```typescript +// src/chains/tron.ts +import { createClientTronSigner } from "@bankofai/x402-tron"; +import { ExactTronScheme } from "@bankofai/x402-tron/exact/client"; +import type { x402Client } from "@bankofai/x402-fetch"; +import { tryResolveWallet } from "../env.js"; + +export async function registerTron(client: x402Client): Promise { + const wallet = await tryResolveWallet("tron"); + if (!wallet) return false; + + for (const network of ["tron:nile", "tron:mainnet"] as const) { + // The factory builds TronWeb internally and auto-broadcasts the one-time + // Permit2 approve that USDT/USDD need before their first payment. + const signer = await createClientTronSigner(wallet, { + network, + apiKey: process.env.TRON_GRID_API_KEY, + }); + client.register(network, new ExactTronScheme(signer)); + } + return true; +} ``` - + ```typescript -import 'dotenv/config' -import { - X402Client, X402FetchClient, - ExactPermitTronClientMechanism, ExactGasFreeClientMechanism, - TronClientSigner, SufficientBalancePolicy, - GasFreeAPIClient, getGasFreeApiBaseUrl, -} from '@bankofai/x402' - -// ========== Configuration ========== -// The x402-protected API you want to call. -// The URL below is our demo endpoint — use it to verify your setup works end-to-end. -const SERVER_URL = 'https://x402-demo.bankofai.io/protected-nile' -// ==================================== - -async function main(): Promise { - // Initialize signer via agent-wallet (resolves wallet from environment automatically) - const signer = await TronClientSigner.create() - - // Create x402 client and register payment mechanisms and balance policy - const x402 = new X402Client() - x402.register('tron:*', new ExactPermitTronClientMechanism(signer)) - x402.register('tron:*', new ExactGasFreeClientMechanism(signer, { - 'tron:nile': new GasFreeAPIClient(getGasFreeApiBaseUrl('tron:nile')), - 'tron:mainnet': new GasFreeAPIClient(getGasFreeApiBaseUrl('tron:mainnet')), - })) - x402.registerPolicy(SufficientBalancePolicy) - - const client = new X402FetchClient(x402) - - // Make the request — the SDK handles payment automatically - const response = await client.get(SERVER_URL) - - console.log(`Status: ${response.status}`) - - // Parse the payment receipt (optional) - const paymentResponse = response.headers.get('payment-response') - if (paymentResponse) { - const jsonString = Buffer.from(paymentResponse, 'base64').toString('utf8') - const settleResponse = JSON.parse(jsonString) - console.log(`Transaction hash: ${settleResponse.transaction}`) - } - - // Print the response body - const contentType = response.headers.get('content-type') ?? '' - if (contentType.includes('application/json')) { - const body = await response.json() - console.log('Response:', body) +// src/chains/evm.ts +import { createClientEvmSigner } from "@bankofai/x402-evm/adapters/agent-wallet"; +import { ExactEvmScheme } from "@bankofai/x402-evm/exact/client"; +import type { x402Client } from "@bankofai/x402-fetch"; +import { tryResolveWallet } from "../env.js"; + +export async function registerEvm(client: x402Client): Promise { + const wallet = await tryResolveWallet("evm"); + if (!wallet) return false; + + for (const network of ["eip155:97", "eip155:56"] as const) { + // The factory builds the viem client internally; ERC-3009 tokens (e.g. DHLU) + // sign offline and need no RPC, while permit2 tokens read the chain. + const signer = await createClientEvmSigner(wallet, { + network, + rpcUrl: process.env.EVM_RPC_URL?.trim() || undefined, + }); + client.register(network, new ExactEvmScheme(signer)); } + return true; } - -main().catch(console.error) -``` - -**Run the script:** - -```bash -npx tsx client.ts -``` - -**Expected output:** - -``` -Status: 200 -Transaction hash: abc123... -Response: { data: 'This is premium content!' } ``` - - - - - -```python -import asyncio -import httpx - -from bankofai.x402.clients import X402Client, X402HttpClient, SufficientBalancePolicy -from bankofai.x402.mechanisms.evm.exact_permit import ExactPermitEvmClientMechanism -from bankofai.x402.mechanisms.evm.exact import ExactEvmClientMechanism -from bankofai.x402.signers.client import EvmClientSigner - - -# ========== Configuration ========== -SERVER_URL = "https://x402-demo.bankofai.io/protected-bsc-testnet" -# ==================================== - - -async def main(): - # Initialize signer via agent-wallet (resolves wallet from environment automatically) - signer = await EvmClientSigner.create() - - # Create x402 client and register BSC mechanisms and balance policy - x402_client = X402Client() - x402_client.register("eip155:*", ExactPermitEvmClientMechanism(signer)) - x402_client.register("eip155:*", ExactEvmClientMechanism(signer)) - x402_client.register_policy(SufficientBalancePolicy) - - async with httpx.AsyncClient(timeout=120) as http_client: - client = X402HttpClient(http_client, x402_client) - # Make the request — the SDK handles payment automatically - response = await client.get(SERVER_URL) +### Run the client - print(f"Status: {response.status_code}") - print("Response:", response.text) - - -asyncio.run(main()) -``` - -**Run the script:** +First, make sure a resource server + facilitator are running (see [Quickstart for Sellers](./quickstart-for-sellers.md)), then from `examples/typescript`: ```bash -python client.py +pnpm dev:client ``` **Expected output:** ``` -Status: 200 -Response: {"data": "This is premium content!"} +→ [tron:nile@USDT] GET http://localhost:4021/weather +← 200 OK +{ "report": { "weather": "sunny", "temperature": 70 } } ``` - - - -```typescript -import 'dotenv/config' -import { - X402Client, X402FetchClient, - ExactPermitEvmClientMechanism, ExactEvmClientMechanism, - EvmClientSigner, SufficientBalancePolicy, -} from '@bankofai/x402' - -// ========== Configuration ========== -const SERVER_URL = 'https://x402-demo.bankofai.io/protected-bsc-testnet' -// ==================================== - -async function main(): Promise { - // Initialize signer via agent-wallet (resolves wallet from environment automatically) - const signer = await EvmClientSigner.create() - - // Create x402 client and register BSC mechanisms and balance policy - const x402 = new X402Client() - x402.register('eip155:*', new ExactPermitEvmClientMechanism(signer)) - x402.register('eip155:*', new ExactEvmClientMechanism(signer)) - x402.registerPolicy(SufficientBalancePolicy) - - const client = new X402FetchClient(x402) - - // Make the request — the SDK handles payment automatically - const response = await client.get(SERVER_URL) - - console.log(`Status: ${response.status}`) - - // Parse the payment receipt (optional) - const paymentResponse = response.headers.get('payment-response') - if (paymentResponse) { - const jsonString = Buffer.from(paymentResponse, 'base64').toString('utf8') - const settleResponse = JSON.parse(jsonString) - console.log(`Transaction hash: ${settleResponse.transaction}`) - } +> ✅ **Success:** The SDK detected the `402`, signed a payment, settled on-chain, and returned the protected content. - // Print the response body - const contentType = response.headers.get('content-type') ?? '' - if (contentType.includes('application/json')) { - const body = await response.json() - console.log('Response:', body) - } -} - -main().catch(console.error) -``` - -**Run the script:** - -```bash -npx tsx client.ts -``` - -**Expected output:** - -``` -Status: 200 -Transaction hash: abc123... -Response: { data: 'This is premium content!' } -``` - - - - - +> 💡 To pay a BSC token instead, set `PAY_TARGETS=eip155:97@DHLU` (ERC-3009, gasless) or `eip155:97@USDC` (permit2, one-time `approve`). --- ## Step Four: Error Troubleshooting -If your script throws an error, refer to the table below: - -| Error | Cause | Fix | -|-------|-------|-----| -| Environment variable is `None` or not set | Private key env var not configured | Re-run the `export` command in **the same terminal window** where you run the script | +| Problem | Cause | Solution | +|---------|-------|----------| +| `No wallet configured for EVM or TRON` | `AGENT_WALLET_PRIVATE_KEY` is not set or empty | Set it in `.env-exact` and re-run; run the `export` command in **the same terminal window** where you run the script | | `WalletNotFoundError: No active wallet set` | agent-wallet has no wallet configured | Run `agent-wallet start` and follow the prompts to import your private key | | `Insufficient balance` / balance error | Test wallet doesn't have enough USDT/USDD | Go back to Prerequisites and claim test tokens from the faucet | -| `UnsupportedNetworkError` | Registered network doesn't match the server | Confirm `SERVER_URL` network matches your registered mechanism (`tron:*` for TRON, `eip155:*` for BSC) | -| `InsufficientAllowanceError` | Token allowance too low | The SDK usually handles this automatically; if it persists, check your wallet balance | -| `Connection timeout` | Network or request timeout | Check your connection, or increase `timeout=60.0` to a larger value | -| `ModuleNotFoundError` | SDK not installed | Re-run the Step One install command | +| `server offered no payment option matching "…"` | `PAY_TARGETS` doesn't match what the server advertises | Check the server's `accepts` (network + token) and align `PAY_TARGETS`, e.g. `tron:nile@USDT` or `eip155:97@DHLU` | +| `InsufficientAllowanceError` / allowance error | Token allowance too low | The SDK auto-broadcasts the one-time Permit2 `approve` on first payment; if it persists, check your wallet balance | +| `Connection timeout` | Network or request timeout | Check your connection; for BSC set a reliable `EVM_RPC_URL=https://bsc-testnet-rpc.publicnode.com` | +| `ERR_PACKAGE_PATH_NOT_EXPORTED` | Project is not declared as ESM | Add `"type": "module"` to your `package.json` | If you need finer-grained error handling in your code: - - - - - -```python -from bankofai.x402.exceptions import ( - X402Error, - InsufficientAllowanceError, - SignatureCreationError, - UnsupportedNetworkError, -) - -try: - response = await client.get(SERVER_URL) - print(f"Status: {response.status_code}") - print("Response:", response.text) - -except UnsupportedNetworkError as e: - print(f"Network not supported (check your registered mechanism): {e}") - -except InsufficientAllowanceError as e: - print(f"Insufficient token allowance (check wallet balance): {e}") - -except SignatureCreationError as e: - print(f"Signature failed (check your private key): {e}") - -except X402Error as e: - print(f"Payment error: {e}") -``` - - - - -```typescript -try { - const response = await client.get(SERVER_URL) - if (response.status === 200) { - console.log('Success:', await response.json()) - } else { - console.error(`Request failed: ${response.status}`) - console.error(await response.text()) - } -} catch (error) { - if (error.message.includes('No mechanism registered')) { - console.error('Network not supported — check your registered mechanism') - } else if (error.message.includes('allowance')) { - console.error('Insufficient token allowance — check wallet balance') - } else { - console.error('Payment error:', error.message) - } -} -``` - - - - - - - - -```python -from bankofai.x402.exceptions import ( - X402Error, - InsufficientAllowanceError, - SignatureCreationError, - UnsupportedNetworkError, -) - -try: - response = await client.get(SERVER_URL) - print(f"Status: {response.status_code}") - print("Response:", response.text) - -except UnsupportedNetworkError as e: - print(f"Network not supported (check your registered mechanism): {e}") - -except InsufficientAllowanceError as e: - print(f"Insufficient token allowance (check wallet balance): {e}") - -except SignatureCreationError as e: - print(f"Signature failed (check your private key): {e}") - -except X402Error as e: - print(f"Payment error: {e}") -``` - - - - ```typescript try { - const response = await client.get(SERVER_URL) - if (response.status === 200) { - console.log('Success:', await response.json()) + const res = await fetchWithPay(RESOURCE_URL); + if (res.status === 200) { + console.log("Success:", await res.json()); } else { - console.error(`Request failed: ${response.status}`) - console.error(await response.text()) + console.error(`Request failed: ${res.status}`); + console.error(await res.text()); } } catch (error) { - if (error.message.includes('No mechanism registered')) { - console.error('Network not supported — check your registered mechanism') - } else if (error.message.includes('allowance')) { - console.error('Insufficient token allowance — check wallet balance') + if (error instanceof Error && error.message.includes("no payment option")) { + console.error("No matching payment option — check PAY_TARGETS vs the server's accepts"); + } else if (error instanceof Error && error.message.includes("allowance")) { + console.error("Insufficient token allowance — check wallet balance"); } else { - console.error('Payment error:', error.message) + console.error("Payment error:", error); } } ``` - - - - - --- ## Summary @@ -625,6 +358,6 @@ Through this guide you: ## References -- [npm package](https://www.npmjs.com/package/@bankofai/x402) — x402 TypeScript SDK -- [Python SDK source](https://github.com/BofAI/x402/tree/main/python/x402) — x402 Python SDK (installed from GitHub) -- [Demo repository](https://github.com/BofAI/x402-demo) — Full integration examples +- [x402 repository](https://github.com/BofAI/x402) — SDK source and runnable examples (`examples/typescript/`) +- [Fetch client example](https://github.com/BofAI/x402/tree/main/examples/typescript/clients/fetch) — the client this guide is based on +- [Agent Wallet](https://github.com/BofAI/agent-wallet) — key custody used by the SDK diff --git a/docs/x402/getting-started/quickstart-for-sellers.md b/docs/x402/getting-started/quickstart-for-sellers.md index 4d77ff4a..cc093644 100644 --- a/docs/x402/getting-started/quickstart-for-sellers.md +++ b/docs/x402/getting-started/quickstart-for-sellers.md @@ -15,6 +15,10 @@ After completing this guide, you'll have a **service that charges for API calls* The entire flow takes **4 steps**, estimated time: **15–20 minutes**. +:::info SDK 1.0.0 (TypeScript-only) +x402 `1.0.0` is a **TypeScript-only** pnpm/turbo monorepo published as granular `@bankofai/x402-*` packages. The previous Python SDK lives under `legacy/` for reference. This guide uses the runnable examples in the [`x402` repository](https://github.com/BofAI/x402) (`examples/typescript/`), which link the in-repo SDK packages and run from source. +::: + --- ## Prerequisites @@ -24,13 +28,14 @@ The entire flow takes **4 steps**, estimated time: **15–20 minutes**. In your terminal (Terminal on macOS/Linux, or PowerShell/Command Prompt on Windows), run the following commands to confirm the required tools are installed: ```bash -python --version # Requires 3.11 or higher -pip --version # Installed alongside Python -git --version # Version control tool +node --version # Requires Node.js 20 or higher +pnpm --version # Requires pnpm 11 or higher +git --version # Version control tool ``` If any command says "command not found", install it first: -- Python: go to [python.org](https://www.python.org/downloads/) to download the installer +- Node.js: go to [nodejs.org](https://nodejs.org/en/download) to download the installer (includes `npm`) +- pnpm: after installing Node.js, run `npm install -g pnpm` - Git: go to [git-scm.com](https://git-scm.com/) to download --- @@ -93,8 +98,8 @@ You need a blockchain wallet address to receive tokens from users. Follow the st | Configuration | Description | How to Obtain | |--------|------|----------| -| **TRON Wallet Address** | Wallet address starting with `T` | Copy from TronLink | -| **BSC Wallet Address** | Wallet address starting with `0x` | Copy from MetaMask | +| **TRON Wallet Address** | Wallet address starting with `T` (your payout address) | Copy from TronLink | +| **BSC Wallet Address** | Wallet address starting with `0x` (your payout address) | Copy from MetaMask | | **Test TRX** | TRON testnet fee token | [Nile Faucet](https://nileex.io/join/getJoinPage) | | **Test USDT/USDD (TRON)** | TRON test payment token (both USDT and USDD supported) | [Nile Faucet](https://nileex.io/join/getJoinPage) | | **Test BNB** | BSC testnet fee token | [BSC Testnet Faucet](https://www.bnbchain.org/en/testnet-faucet) | @@ -107,534 +112,360 @@ You need a blockchain wallet address to receive tokens from users. Follow the st --- -## Step 1: Install the x402 SDK - -Open your terminal and run the following install command: +## Step 1: Get the SDK and Examples -**Recommended (install directly from GitHub, ideal for getting started quickly):** +The examples workspace links the in-repo `@bankofai/x402-*` packages and builds from source, so you get the latest SDK without publishing to a registry. ```bash -pip install "bankofai-x402[tron,fastapi] @ git+https://github.com/BofAI/x402.git#subdirectory=python/x402" +git clone https://github.com/BofAI/x402.git +cd x402/typescript # the pnpm/turbo monorepo root + +# Install + link all workspace packages (SDK + examples) +pnpm install + +# Build the @bankofai/x402-* dist the examples import from +pnpm build + +cd examples/typescript ``` -After installation, run the following command to verify it succeeded: +Verify the install by starting the example resource server (it will print a port and the chains it accepts): ```bash -python -c "import bankofai.x402; print('SDK installed successfully!')" +pnpm dev:server ``` -> ✅ **Success:** Terminal outputs `SDK installed successfully!` +> ✅ **Success:** The server boots and prints a startup line. With no payout address set yet it exits with `❌ No payout address configured (set EVM_ADDRESS and/or TRON_ADDRESS)` — that's expected and confirms the toolchain works. You'll set those in Step 2. -**Alternative (install from source, for developers who need to modify the source code):** +--- -```bash -# Clone the repository -git clone https://github.com/BofAI/x402.git -cd x402/python/x402 +## Step 2: Configure Your Environment + +All three processes in the main line (facilitator, server, client) share one file: `.env-exact`. Copy the template and fill it in: -# Install (with FastAPI support) -pip install -e ".[fastapi]" +```bash +cp .env-exact.example .env-exact ``` -> 💡 **Permission error?** Prefix the command with `sudo` (macOS/Linux), or run PowerShell as Administrator (Windows). +Open `.env-exact` in your editor and set the wallet + payout variables: ---- +```bash +# ── SHARED · client + facilitator (the same key pays and settles here) ──── +AGENT_WALLET_PRIVATE_KEY=0x... # your test wallet private key -## Step 2: Create a Payment-Protected API Server +# TronGrid API key — both client and facilitator touch TRON. Optional on testnet. +TRON_GRID_API_KEY= -Now let's create an API server with payment protection. The x402 SDK provides an `@x402_protected` decorator — simply add it to any endpoint you want to charge for, and the SDK will automatically handle all payment verification logic. +# ── SERVER · the resource provider (this is what YOU configure) ─────────── +EVM_ADDRESS=0x... # your BSC payout address (eip155:97) +TRON_ADDRESS=T... # your TRON payout address (tron:nile) -In your project directory, create a new file named `server.py` and paste in the following code: +# Where the server binds, and where it reaches the facilitator. +SERVER_PORT=4021 +FACILITATOR_URL=http://localhost:4022 - - - -```python -from fastapi import FastAPI, Request -from bankofai.x402.server import X402Server -from bankofai.x402.fastapi import x402_protected -from bankofai.x402.facilitator import FacilitatorClient -from bankofai.x402.config import NetworkConfig - -app = FastAPI() - -# ========== Modify the following two settings ========== -# Replace the address below with your TRON wallet address from Prerequisites (used to receive payments) -PAY_TO_ADDRESS = "YourTronWalletAddressHere" - -# Facilitator service URL (will be started in Step 3, default address does not need to change) -FACILITATOR_URL = "http://localhost:8001" -# ======================================================== - -# Initialize x402 server -server = X402Server() -server.set_facilitator(FacilitatorClient(FACILITATOR_URL)) - -# Add payment protection to this API endpoint -@app.get("/protected") -@x402_protected( - server=server, - prices=["0.0001 USDT"], # Charge per request (adjust as needed) - schemes=["exact_permit"], # Payment scheme - network=NetworkConfig.TRON_NILE, # Using testnet now (change to TRON_MAINNET when going live) - pay_to=PAY_TO_ADDRESS, # Your receiving wallet address -) -async def protected_endpoint(request: Request): - return {"data": "This is premium content!"} - - -if __name__ == "__main__": - import uvicorn - uvicorn.run(app, host="0.0.0.0", port=8000) +# ── FACILITATOR · settlement ───────────────────────────────────────────── +FACILITATOR_PORT=4022 ``` - - +> 💡 **Keyless server:** The resource server never signs or holds a key — it only advertises your public payout address (`EVM_ADDRESS` / `TRON_ADDRESS`). Signing and settlement happen at the client and facilitator. `AGENT_WALLET_PRIVATE_KEY` is used by the client (to pay) and the facilitator (to settle), not by the server. + +> ⚠️ **Security reminder:** Keep your private key only in `.env` (which is gitignored) or as an environment variable. **Never commit a file containing a private key to Git or share it with anyone.** -```python -from fastapi import FastAPI, Request -from bankofai.x402.server import X402Server -from bankofai.x402.fastapi import x402_protected -from bankofai.x402.facilitator import FacilitatorClient -from bankofai.x402.config import NetworkConfig -from bankofai.x402.mechanisms.evm.exact_permit import ExactPermitEvmServerMechanism -from bankofai.x402.mechanisms.evm.exact import ExactEvmServerMechanism - -app = FastAPI() - -# ========== Modify the following two settings ========== -# Replace the address below with your BSC wallet address from Prerequisites (used to receive payments) -PAY_TO_ADDRESS = "0xYourBscWalletAddressHere" - -# Facilitator service URL (will be started in Step 3, default address does not need to change) -FACILITATOR_URL = "http://localhost:8001" -# ======================================================== - -# Initialize x402 server and register BSC payment mechanisms -server = X402Server() -server.register(NetworkConfig.BSC_TESTNET, ExactPermitEvmServerMechanism()) -server.register(NetworkConfig.BSC_TESTNET, ExactEvmServerMechanism()) -server.set_facilitator(FacilitatorClient(FACILITATOR_URL)) - -# Add payment protection to this API endpoint -@app.get("/protected") -@x402_protected( - server=server, - prices=["0.0001 USDT"], # Charge per request - network=NetworkConfig.BSC_TESTNET, # Using testnet now (change to BSC_MAINNET when going live) - pay_to=PAY_TO_ADDRESS, # Your receiving wallet address - schemes=["exact_permit"], -) -async def protected_endpoint(request: Request): - return {"data": "This is premium content!"} - - -if __name__ == "__main__": - import uvicorn - uvicorn.run(app, host="0.0.0.0", port=8000) +--- + +## Step 3: Create a Payment-Protected API Server + +The example resource server is an Express app that protects `GET /weather` behind x402 payment. It is **chain-agnostic** — each chain's tokens and `accepts` entries live in `src/chains/{evm,tron}.ts`, and a chain is advertised only when its `*_ADDRESS` is set. + +Here is the server entry point (`examples/typescript/servers/express/src/index.ts`): + +```typescript +import express from "express"; +import { HTTPFacilitatorClient } from "@bankofai/x402-core/server"; +import { createResourceServer } from "@bankofai/x402-core"; +import { + x402HTTPResourceServer, + paymentMiddlewareFromHTTPServer, +} from "@bankofai/x402-express"; + +import { hasEvm, registerEvm, evmAccepts, evmExtensions } from "./chains/evm.js"; +import { hasTron, registerTron, tronAccepts } from "./chains/tron.js"; + +const PORT = parseInt(process.env.SERVER_PORT || "4021", 10); +const FACILITATOR_URL = process.env.FACILITATOR_URL || "http://localhost:4022"; + +// The server delegates verify/settle to a facilitator over HTTP. +const facilitatorClient = new HTTPFacilitatorClient({ url: FACILITATOR_URL }); +// Logging pre-attached: verify/settle results print via the SDK logger. +const resourceServer = createResourceServer(facilitatorClient); + +// Register each chain (and advertise its tokens) only when its payout is set. +type Accept = ReturnType[number] | ReturnType[number]; +const accepts: Accept[] = []; +let extensions: Record = {}; +if (hasEvm()) { + registerEvm(resourceServer); + accepts.push(...evmAccepts()); + extensions = { ...extensions, ...evmExtensions() }; +} +if (hasTron()) { + registerTron(resourceServer); + accepts.push(...tronAccepts()); +} + +// The route you protect — `accepts` is the price list, `extensions` carries +// the gas-sponsoring hint for plain-ERC20 (permit2) tokens like BSC USDC. +const routes = { + "GET /weather": { + accepts, + extensions, + description: "Current weather (paid)", + mimeType: "application/json", + }, +}; + +const httpServer = new x402HTTPResourceServer(resourceServer, routes); + +const app = express(); +app.use(paymentMiddlewareFromHTTPServer(httpServer)); + +app.get("/weather", (_req, res) => { + res.json({ report: { weather: "sunny", temperature: 70 } }); +}); + +app.listen(PORT, () => { + console.log(`🌤️ Resource server on http://localhost:${PORT}`); +}); ``` - - +### How pricing works per chain + +Each chain module builds the `accepts` entries (price + `payTo` + token). The two chain families price differently: + +- **TRON** uses a `" "` string, so the scheme resolves each token from its registry: + ```typescript + // src/chains/tron.ts — USDT and USDD on tron:nile + export function tronAccepts() { + const payTo = process.env.TRON_ADDRESS as string; + return ["tron:nile", "tron:mainnet"].flatMap((network) => + ["0.001 USDT", "0.001 USDD"].map((price) => ({ scheme: "exact", network, payTo, price })), + ); + } + ``` +- **EVM** advertises explicit `{ amount, asset, extra }` objects, because BSC has no default-token registry entry. ERC-3009 tokens (e.g. DHLU) carry their domain `name`/`version`; plain ERC-20 tokens (e.g. USDC/USDT) set `extra.assetTransferMethod: "permit2"` and need a one-time Permit2 `approve`: + ```typescript + // src/chains/evm.ts + const EVM_TOKENS = { + "eip155:97": [ + { asset: "0x375cADdd…B816", amount: "1000", extra: { name: "DA HULU", version: "1" } }, // DHLU, ERC-3009 + { asset: "0x64544969…8930", amount: "1000000000000000", extra: { assetTransferMethod: "permit2" } }, // USDC + { asset: "0x337610d2…4dDd", amount: "1000000000000000", extra: { assetTransferMethod: "permit2" } }, // USDT + ], + }; + ``` -**Key Configuration Parameters:** +**Key configuration parameters:** -| Parameter | Description | Example Value | +| Parameter | Description | Example | |------|------|--------| -| `PAY_TO_ADDRESS` | Your receiving wallet address | `TXyz...` (TRON) or `0xAbc...` (BSC) | -| `prices` | Price per request | `["0.0001 USDT"]` | -| `network` | Network to use | Testnet: `TRON_NILE` / `BSC_TESTNET` | -| `schemes` | Payment scheme | `["exact_permit"]` | +| `EVM_ADDRESS` / `TRON_ADDRESS` | Your receiving (payout) wallet address | `0xAbc…` / `TXyz…` | +| `accepts[].price` | Price per request (token amount, or `" "`) | `"0.001 USDT"` | +| `accepts[].network` | Network to use | Testnet: `tron:nile` / `eip155:97` | +| `accepts[].scheme` | Payment scheme | `"exact"` | +| `routes` | Map of `"METHOD /path"` → `{ accepts, extensions, description, mimeType }` | `"GET /weather"` | -**How it works:** When an unpaid request reaches your API, the server automatically returns an HTTP 402 (Payment Required) response with payment instructions in the response headers. The client SDK automatically completes the payment and re-sends the request — the process is nearly invisible to the end user. +**How it works:** When an unpaid request reaches your API, the middleware automatically returns an HTTP `402 Payment Required` response with payment instructions. The client SDK pays automatically and re-sends the request — the process is nearly invisible to the end user. --- -## Step 3: Connect to a Facilitator +## Step 4: Connect to a Facilitator ### What is a Facilitator? -Simply put, a Facilitator is an **automated settlement service**: when someone pays your API, the Facilitator verifies that the payment is genuine and settles it on the blockchain, ensuring funds are recorded on-chain. +A Facilitator is an **automated settlement service**: when someone pays your API, the Facilitator verifies the payment is genuine and settles it on-chain, ensuring funds reach your payout wallet. The server you built in Step 3 only points at a Facilitator via `FACILITATOR_URL` — it does not settle on its own. -**You must complete the Facilitator configuration before starting your API server.** +**You must have a Facilitator reachable before starting your API server.** ### Two Options — Which Should You Choose? | | Official Facilitator (Recommended) | Self-Hosted Facilitator | |---|---|---| | **Maintenance required** | No — officially hosted | Yes — you run it yourself | -| **Wallet private key required** | No | Yes (to pay transaction fees) | -| **Difficulty** | Low (just apply for an API Key) | Medium (requires deployment and configuration) | +| **Wallet private key required** | No | Yes (to settle on-chain) | +| **Difficulty** | Low (just apply for an API Key) | Medium (run the example facilitator) | | **Best for** | Fast deployment, most users | Full control over fee strategy | -The officially hosted Facilitator service requires **no infrastructure to maintain**. You can also refer to [Official Facilitator](../core-concepts/OfficialFacilitator.md) for details. +The officially hosted Facilitator service requires **no infrastructure to maintain**. See [Official Facilitator](../core-concepts/OfficialFacilitator.md) for the full step-by-step guide. -#### 3.1 Configure the Service Endpoint +#### 4.1 Configure the Service Endpoint -Set your `FACILITATOR_URL` to the official Facilitator service address: +Set `FACILITATOR_URL` in your `.env-exact` to the official endpoint: ``` -https://facilitator.bankofai.io +FACILITATOR_URL=https://facilitator.bankofai.io ``` This is the address your x402 server uses to verify and settle payments — **for API calls only**, no need to open it in a browser. -> ⚠️ **Without an API Key, this endpoint is rate-limited to 1 request per minute per IP address.** This is sufficient for testing, but in production it will throttle your API. Continue to step 3.2 to apply for an API Key. - -#### 3.2 Apply for an API Key - -Apply for a free API Key in the admin dashboard: +> ⚠️ **Without an API Key, this endpoint is rate-limited** (one `/settle` call per IP per minute). Suitable for testing only. -[https://admin-facilitator.bankofai.io](https://admin-facilitator.bankofai.io) +#### 4.2 Apply for an API Key -1. Open the link above in your browser -2. Click **TronLink** to log in with your wallet (for identity verification only — **no charges will be made**) -3. After logging in, go to the Dashboard and click **"Create API Key"** -4. Confirm, then click **View** in the Dashboard to see and copy your API Key +1. Open the [Admin Portal](https://admin-facilitator.bankofai.io) in your browser and sign in with your wallet +2. On the Dashboard, click **"Create API Key"** +3. Confirm, then click **View** in the Dashboard to see and copy your API Key With an API Key, the rate limit increases to **1,000 requests/minute**, sufficient for production use. -> 📖 **Detailed step-by-step guide** available at: [Official Facilitator](../core-concepts/OfficialFacilitator.md) - -> ⚠️ **Security reminder:** Your API Key is a service credential — **treat it like a password and never commit it to Git** - -#### 3.3 Configure the `.env` File +#### 4.3 Wire the API Key into Your Server -In your project directory (where `server.py` is located), create or edit the `.env` file and add the following: +The official key is sent as the `X-API-KEY` header on every facilitator call. The example server already supports it via `FACILITATOR_API_KEY`: ```bash -# Official Facilitator service URL -FACILITATOR_URL=https://facilitator.bankofai.io - -# API Key (apply at admin-facilitator.bankofai.io) — SDK passes it automatically via the X-API-KEY header +# Append to .env-exact FACILITATOR_API_KEY=paste_your_api_key_here ``` -#### 3.4 Update server.py to Connect to the Official Facilitator - -Update the Facilitator initialization section in `server.py` to read configuration from environment variables (add `import os` at the top of the file): - - - - -```python -import os -# ... other imports unchanged ... - -# Official Facilitator service URL (read from environment variable) -# SDK automatically reads FACILITATOR_API_KEY from the environment — no need to pass it explicitly -FACILITATOR_URL = os.getenv("FACILITATOR_URL", "https://facilitator.bankofai.io") +> ⚠️ **Security reminder:** Your API Key is a service credential — **treat it like a password and never commit it to Git**. -# Initialize x402 server and connect to Official Facilitator -server = X402Server() -server.set_facilitator(FacilitatorClient(FACILITATOR_URL)) -``` - - - - -```python -import os -# ... other imports unchanged ... - -# Official Facilitator service URL (read from environment variable) -# SDK automatically reads FACILITATOR_API_KEY from the environment — no need to pass it explicitly -FACILITATOR_URL = os.getenv("FACILITATOR_URL", "https://facilitator.bankofai.io") - -# Initialize x402 server, register BSC mechanisms, connect to Official Facilitator -server = X402Server() -server.register(NetworkConfig.BSC_TESTNET, ExactPermitEvmServerMechanism()) -server.register(NetworkConfig.BSC_TESTNET, ExactEvmServerMechanism()) -server.set_facilitator(FacilitatorClient(FACILITATOR_URL)) -``` - - - - -> ✅ **Done!** The Official Facilitator is configured — **no local service to start**. Proceed directly to Step 4 to test. +> ✅ **Done!** The Official Facilitator is configured — **no local service to start**. Proceed directly to Step 5 to test. -The self-hosted option gives you full control over fee strategy and network configuration. It is intended for advanced users with specific customization requirements. +The self-hosted option gives you full control over fee strategy. It runs the example facilitator (`examples/typescript/facilitator/basic`), which exposes `/verify`, `/settle`, `/supported` over HTTP and dispatches by the payment's `network` field. > ⚠️ **Security reminder — please read first:** -> - You need the private key of a **dedicated wallet** to pay blockchain transaction fees — **this wallet should be separate from your receiving wallet** -> - The Facilitator wallet only needs a small amount of tokens (for fees) — do not deposit large amounts -> - The private key is set via environment variable — **never commit it to Git or share it with anyone** - -#### 3.1 Prepare Prerequisites +> - A self-hosted Facilitator uses your wallet to submit on-chain settlement transactions — **this wallet should be separate from your receiving wallet** +> - Only deposit a small amount of tokens into the Facilitator wallet (enough for fees); do not store large amounts +> - Keep the private key only in `.env-exact` — **never commit it to Git or share it with anyone** -Before starting, make sure you have: +#### 4.1 How the Self-Hosted Facilitator Works -- **Python 3.11+** and **Git** (confirmed in the Prerequisites section above) -- **PostgreSQL** — the Facilitator stores payment records in a database. - - - - - ```bash - brew install postgresql@16 - brew services start postgresql@16 - createdb x402 - ``` - - - - - **Ubuntu / Debian:** - ```bash - sudo apt install -y postgresql - sudo systemctl start postgresql - sudo -u postgres createdb x402 - ``` - - **Amazon Linux / CentOS / RHEL / Fedora:** - ```bash - sudo dnf install -y postgresql15 postgresql15-server # Amazon Linux 2023; other distros: postgresql-server - sudo postgresql-setup --initdb - sudo systemctl start postgresql - sudo systemctl enable postgresql - sudo -u postgres createdb x402 - ``` - - **Arch Linux:** - ```bash - sudo pacman -S postgresql - sudo -u postgres initdb -D /var/lib/postgres/data - sudo systemctl start postgresql - sudo -u postgres createdb x402 - ``` +The facilitator verifies signatures and settles on-chain. It registers the `exact` scheme per chain with a signer: - - +```typescript +// examples/typescript/facilitator/basic/src/index.ts (abridged) +import { x402Facilitator } from "@bankofai/x402-core/facilitator"; - Download and run the installer from [postgresql.org/download/windows](https://www.postgresql.org/download/windows/), then create a database named `x402` via pgAdmin or psql. +const facilitator = new x402Facilitator() + .onBeforeSettle(async ctx => console.log("[settle] before", ctx.requirements.network)) + .onAfterSettle(async ctx => console.log("[settle] after", ctx.requirements.network)) + .onSettleFailure(async ctx => console.log("[settle] failure", ctx)); - - +// Register each chain only if its wallet resolves (EVM-only, TRON-only, or both). +const evm = await registerEvm(facilitator); +const tron = await registerTron(facilitator); - **Set a password for the `postgres` user** (required for the connection string): - - ```bash - sudo -u postgres psql -c "ALTER USER postgres WITH PASSWORD 'yourpassword';" - ``` - - > Replace `yourpassword` with a password of your choice. You will use it in the connection string below. - - **Enable password authentication** (Linux only — required on most distributions): - - By default, PostgreSQL uses `ident` authentication on Linux, which only allows connections when the OS username matches the database username. You need to change it to `md5` (password-based) for the Facilitator to connect: - - ```bash - # Find the pg_hba.conf file - sudo find / -name pg_hba.conf 2>/dev/null - # Typical location: /var/lib/pgsql/data/pg_hba.conf (Amazon Linux / CentOS) - # /etc/postgresql/*/main/pg_hba.conf (Ubuntu / Debian) - ``` - - Open the file and change `ident` to `md5` for IPv4 and IPv6 local connections: - - ``` - # IPv4 local connections: - host all all 127.0.0.1/32 md5 - # IPv6 local connections: - host all all ::1/128 md5 - ``` +// Exposes POST /verify, POST /settle, GET /supported on FACILITATOR_PORT. +app.listen(PORT, () => console.log(`🚀 Facilitator on http://localhost:${PORT}`)); +``` - Then restart PostgreSQL to apply: +Each chain module adapts the agent-wallet to a facilitator signer: - ```bash - sudo systemctl restart postgresql - ``` +- **EVM** — `createFacilitatorEvmSigner(wallet, { network, rpcUrl })`, then `facilitator.register(network, new ExactEvmScheme(signer))` +- **TRON** — `createFacilitatorTronSigner(wallet, { network, apiKey })`, then `facilitator.register(network, new ExactTronScheme(signer))` - Connection string: `postgresql+asyncpg://postgres:yourpassword@localhost:5432/x402` +The signer factories build the viem client / TronWeb internally; the example **never reads a raw private key** — `AGENT_WALLET_PRIVATE_KEY` is consumed by `@bankofai/agent-wallet`. -- **A dedicated Facilitator wallet** — create a new wallet (separate from your receiving wallet, following the same steps in Prerequisites), and claim testnet tokens from the faucet to cover transaction fees. +#### 4.2 Start the Facilitator -#### 3.2 Clone and Install - -Open a **new terminal window** and run: +`FACILITATOR_URL` in your `.env-exact` already defaults to `http://localhost:4022`, which matches the example facilitator. From `examples/typescript`, run: ```bash -# Clone the Facilitator service -git clone https://github.com/BofAI/x402-facilitator.git -cd x402-facilitator - -# Install dependencies -pip install -r requirements.txt +pnpm dev:facilitator ``` -#### 3.3 Configure the Service - -Copy the example config and open it in a text editor: +**After a successful start, you should see output like:** -```bash -cp config/facilitator.config.example.yaml config/facilitator.config.yaml ``` - -Fill in the required fields: - - - - -```yaml -database: - url: "postgresql+asyncpg://postgres:yourpassword@localhost:5432/x402" - -facilitator: - networks: - tron:nile: # Use tron:mainnet when going live - base_fee: - USDT: 100 # 0.0001 USDT per settlement (adjust as needed) - USDD: 100000000000000 # 0.0001 USDD (18 decimals; adjust as needed) +[evm] facilitator registered eip155:97 (0x…) +[tron] facilitator registered tron:nile (T…) +🚀 Facilitator on http://localhost:4022 (evm=true, tron=true) ``` - - - -```yaml -database: - url: "postgresql+asyncpg://postgres:yourpassword@localhost:5432/x402" - -facilitator: - networks: - bsc:testnet: # Use bsc:mainnet when going live - base_fee: - USDT: 100 # 0.0001 USDT per settlement (adjust as needed) -``` +> ✅ **Success:** Facilitator is running on port 4022 — **keep this terminal window open, do not close it** -Then set the private key of your dedicated Facilitator wallet as an environment variable: - - - +--- -```bash -# How to get it: TronLink → Settings → Account Management → Export Private Key -export AGENT_WALLET_PRIVATE_KEY=paste_your_facilitator_private_key_here +## Step 5: Start and Test Your API -# TronGrid API Key (recommended for stable RPC access) -# Apply at: https://www.trongrid.io/ -export TRON_GRID_API_KEY=paste_your_trongrid_api_key_here -``` +### 5.1 Start the API Server - - +Open a **new terminal window** (do not close the facilitator), and from `examples/typescript` run: ```bash -# How to get it: MetaMask → Account Details → Export Private Key -export AGENT_WALLET_PRIVATE_KEY=paste_your_facilitator_private_key_here +pnpm dev:server ``` - - - -#### 3.4 Start the Facilitator Service - -```bash -python src/main.py -``` - -**After a successful start, you should see output like:** +**After a successful start, you should see:** ``` -INFO: Started server process -INFO: Waiting for application startup. -INFO: Application startup complete. -INFO: Uvicorn running on http://0.0.0.0:8001 (Press CTRL+C to quit) +🌤️ Resource server on http://localhost:4021 (evm=true, tron=true) → facilitator http://localhost:4022 ``` -> ✅ **Success:** Uvicorn is running on port 8001 — **keep this terminal window open, do not close it** +> ✅ **Success:** Terminal shows the resource server on `http://localhost:4021` -#### 3.5 Register an API Key (Optional) +### 5.2 Test Unpaid Access (Should Be Rejected) -If you want to track payment records per seller, register an API key using the built-in script: - -```bash -python scripts/register_seller.py -# A random API key will be generated and printed — save it -``` +In any terminal, run: -Set this key on your server side: ```bash -export FACILITATOR_API_KEY=your_generated_key +curl http://localhost:4021/weather ``` -The `FACILITATOR_URL = "http://localhost:8001"` in `server.py` is already configured for self-hosting — **no other changes needed**. Proceed to Step 4. - - - +**Expected result:** The server returns an HTTP `402` response with the payment requirements (an `accepts` array listing scheme, network, price, and your payout address). ---- - -## Step 4: Start and Test Your API +> ✅ **This is exactly what we want!** It confirms that payment protection is working — unpaid requests are successfully blocked. -### 4.1 Start the API Server +### 5.3 Test the Full Payment Flow -Open a **third terminal window** (do not close the previous ones), navigate to the directory containing `server.py`, and run: +To test the complete pay → receive content flow, start the example client in a **third terminal**. From `examples/typescript`, first set which chain/token to pay: ```bash -python server.py +# Append to .env-exact (or export in the client terminal) +PAY_TARGETS=tron:nile@USDT # TRON Nile USDT; or eip155:97@DHLU for BSC +RESOURCE_URL=http://localhost:4021/weather ``` -**After a successful start, you should see:** - -``` -INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) -INFO: Application startup complete. -``` - -> ✅ **Success:** Terminal shows `Uvicorn running on http://0.0.0.0:8000` - -### 4.2 Test Unpaid Access (Should Be Rejected) - -In any terminal, run: +Then run: ```bash -curl http://localhost:8000/protected +pnpm dev:client ``` -**Expected result:** The server returns an HTTP 402 response with content similar to: +**Expected output:** -```json -{"error": "Payment required", "x402Version": 1} +``` +→ [tron:nile@USDT] GET http://localhost:4021/weather +← 200 OK +{ "report": { "weather": "sunny", "temperature": 70 } } ``` -> ✅ **This is exactly what we want!** It confirms that payment protection is working — unpaid requests are successfully blocked. - -### 4.3 Test the Full Payment Flow - -To test the complete pay → receive content flow, you need a client that can sign payments: +> ✅ **Success:** The client automatically detected the `402`, signed a payment, settled on-chain via the facilitator, and received the protected content. -- [Human User Quickstart](./quickstart-for-human.md) — Call your paid API using code -- [AI Agent Quickstart](./quickstart-for-agent.md) — Configure an AI agent to call your API automatically +> 💡 The client wraps `fetch` with `wrapFetchWithPayment(fetch, client)` so 402 challenges are paid automatically — see [Quickstart for Human Users](./quickstart-for-human.md) for the client-side walkthrough. --- ## Troubleshooting -| Issue | Solution | -|------|----------| -| `Connection refused` when connecting to Facilitator | If using **self-hosted**: confirm the Facilitator terminal from Step 3 is still running on port 8001 (`python src/main.py`). If using **official**: check that `FACILITATOR_URL` is correctly set to `https://facilitator.bankofai.io` | -| `ModuleNotFoundError: bankofai` | Re-run the install command from Step 1 | -| Wallet address format error | TRON addresses start with `T`; BSC addresses start with `0x` — check that the address was copied in full | -| Facilitator fails to start — database error | Confirm `database.url` in `config/facilitator.config.yaml` is correct and the PostgreSQL instance is running | -| Facilitator fails to start — wallet error | Confirm `AGENT_WALLET_PRIVATE_KEY` is exported in your terminal session with no extra spaces or line breaks | -| API Key invalid or rate limited (official) | Confirm `FACILITATOR_API_KEY` is correctly set; go to [admin-facilitator.bankofai.io](https://admin-facilitator.bankofai.io) to check the key status | -| `server.py` fails to start | Confirm `PAY_TO_ADDRESS` has been replaced with a real wallet address (do not leave the placeholder text) | - -**Need more examples and references?** - -- [Complete server example code](https://github.com/BofAI/x402-demo/tree/main/server) -- [Facilitator example code](https://github.com/BofAI/x402-demo/tree/main/facilitator) -- [Facilitator reference](../core-concepts/facilitator.md) — Full setup comparison for both options -- [Official Facilitator](../core-concepts/OfficialFacilitator.md) — Step-by-step guide with screenshots for the API Key +| Problem | Cause | Solution | +|---------|-------|----------| +| `No payout address configured` | Neither `EVM_ADDRESS` nor `TRON_ADDRESS` is set | Set at least one in `.env-exact` and restart the server | +| `Failed to fetch` / connection refused | Facilitator or server not running | Start the facilitator first (`pnpm dev:facilitator`), then the server (`pnpm dev:server`) | +| Client `server offered no payment option matching "…"` | `PAY_TARGETS` doesn't match an advertised option | Check the server's `accepts` (network + token) and align `PAY_TARGETS`, e.g. `tron:nile@USDT` or `eip155:97@DHLU` | +| `ERR_PACKAGE_PATH_NOT_EXPORTED` under `npx tsx` | Project is not declared as ESM | Add `"type": "module"` to your `package.json` | +| `UnsupportedNetworkError` / `No mechanism registered` | The network in `PAY_TARGETS` has no registered scheme | Ensure the client's `EVM_NETWORKS`/`TRON_NETWORKS` includes your target, and the wallet for that chain resolved | +| `Insufficient balance` / allowance error | Test wallet lacks test tokens, or Permit2 allowance too low | Claim test tokens from the faucet; the client auto-approves Permit2 on first payment | +| `Connection timeout` | Network or request timeout | Check your connection, or set a reliable `EVM_RPC_URL` (e.g. `https://bsc-testnet-rpc.publicnode.com`) | --- @@ -642,111 +473,47 @@ To test the complete pay → receive content flow, you need a client that can si After fully validating on the testnet, only a few steps are needed to go live and accept real payments: -### 1. Update Server Configuration - -Modify the `network` parameter in the `@x402_protected` decorator in `server.py`: +### 1. Point the Client and Server at Mainnet - - - -```python -@x402_protected( - server=server, - prices=["0.0001 USDT"], - schemes=["exact_permit"], - network=NetworkConfig.TRON_MAINNET, # Changed from TRON_NILE to TRON_MAINNET - pay_to=PAY_TO_ADDRESS, -) -``` +The example registers testnet **and** mainnet in the same tables — no uncommenting needed. Switch by setting mainnet values in `.env-exact`: - - +```bash +# Server payout addresses → your mainnet wallets +EVM_ADDRESS=0xYourMainnetBscAddress +TRON_ADDRESS=TYourMainnetTronAddress -```python -@x402_protected( - server=server, - prices=["0.0001 USDT"], - schemes=["exact_permit"], - network=NetworkConfig.BSC_MAINNET, # Changed from BSC_TESTNET to BSC_MAINNET - pay_to=PAY_TO_ADDRESS, -) +# Client pays on mainnet +PAY_TARGETS=tron:mainnet@USDT # or eip155:56@USDT ``` - - - -### 2. Update Facilitator Configuration - - - +### 2. Set a Reliable EVM RPC -1. **Apply for a TronGrid API Key**: go to [TronGrid](https://www.trongrid.io/) to register and create an API Key, then set it as an environment variable: +BSC mainnet needs a stable endpoint. Set this for both the client and facilitator: - ```bash - export TRON_GRID_API_KEY=your_trongrid_api_key - ``` - - :::note - When `TRON_GRID_API_KEY` is not set, requests may be rate-limited under heavy workloads. For production, set your own `TRON_GRID_API_KEY` to ensure reliability. - ::: - -2. **Replace the private key**: update `AGENT_WALLET_PRIVATE_KEY` to the mainnet Facilitator wallet's private key: - - ```bash - export AGENT_WALLET_PRIVATE_KEY=your_mainnet_facilitator_private_key - ``` - -3. **Fund the fee wallet**: transfer sufficient real TRX to the Facilitator mainnet wallet (to pay Energy and Bandwidth fees). - -4. **Update the network config**: open `config/facilitator.config.yaml` and change the network key from `tron:nile` to `tron:mainnet`: - - ```yaml - facilitator: - networks: - tron:mainnet: # Changed from tron:nile - base_fee: - USDT: 100 - USDD: 100000000000000 # 0.0001 USDD (18 decimals; adjust as needed) - ``` - -5. **Restart the service**: `python src/main.py` - - - - -1. **Fund the fee wallet**: transfer sufficient real BNB to the Facilitator mainnet wallet (to pay Gas fees). - -2. **Replace the private key**: update `AGENT_WALLET_PRIVATE_KEY` to the mainnet Facilitator wallet's private key: - - ```bash - export AGENT_WALLET_PRIVATE_KEY=your_mainnet_facilitator_private_key - ``` +```bash +EVM_RPC_URL=https://bsc-rpc.publicnode.com +``` -3. **Update the network config**: open `config/facilitator.config.yaml` and change the network key from `bsc:testnet` to `bsc:mainnet`: +### 3. (Self-Hosted) Switch the Facilitator to Mainnet - ```yaml - facilitator: - networks: - bsc:mainnet: # Changed from bsc:testnet - base_fee: - USDT: 100 - ``` +The facilitator's `TRON_NETWORKS` already includes `tron:mainnet`, and `EVM_NETWORKS` includes `eip155:56`. Fund the Facilitator wallet with real TRX/BNB to cover settlement gas, then restart: -4. **Restart the service**: `python src/main.py` +```bash +pnpm dev:facilitator +``` - - +> For production TRON workloads, set your own `TRON_GRID_API_KEY` to avoid rate limiting. -### 3. Confirm Your Receiving Wallet Address +### 4. (Official Facilitator) No Local Change Needed -Ensure that `PAY_TO_ADDRESS` is set to a **real mainnet wallet address** you control, and confirm you have a backup of the seed phrase or private key for that wallet. +If you use the official facilitator, keep `FACILITATOR_URL=https://facilitator.bankofai.io` and your `FACILITATOR_API_KEY`. Only your server's payout addresses move to mainnet. -### 4. Perform a Small Real-Money Test Before Going Live +### 5. Confirm and Do a Small Real Test > ⚠️ **Mainnet warning — real funds are involved. Please follow these steps carefully:** > > 1. Ensure all functionality (payment, receipt, error handling) has been fully validated on the testnet -> 2. After going live on mainnet, **start with one minimum-amount real test (e.g. 0.0001 USDT)** +> 2. After going live on mainnet, **start with one minimum-amount real test (e.g. `0.001 USDT`)** > 3. Confirm the transaction succeeded on the blockchain explorer ([TronScan](https://tronscan.org) or [BscScan](https://bscscan.com)) > 4. Open your receiving wallet and confirm the funds have arrived > 5. Only open your API to the public after confirming everything is correct @@ -755,7 +522,7 @@ Ensure that `PAY_TO_ADDRESS` is set to a **real mainnet wallet address** you con ## Next Steps -- View [demo examples](https://github.com/BofAI/x402-demo/tree/main/server) for more complex payment flows +- Explore the [runnable examples](https://github.com/BofAI/x402/tree/main/examples/typescript) for the full client → server → facilitator loop, plus the `gasfree`, `upto`, and `batch-settlement` scenarios - Read the [core concepts](../core-concepts/http-402.md) to understand how the x402 protocol works - Want detailed configuration for both Facilitator options? See the [Facilitator documentation](../core-concepts/facilitator.md) - Experience calling a paid API from the [user perspective](./quickstart-for-human.md), or configure an [AI agent](./quickstart-for-agent.md) to call your service automatically @@ -769,9 +536,10 @@ Congratulations 🎉! You've completed the Seller Quickstart. Here's everything | Step | What You Did | |------|----------| | **Prerequisites** | Created a receiving wallet, obtained test tokens, reviewed configuration parameters | -| **Step 1** | Installed the x402 SDK | -| **Step 2** | Created an API server with payment protection | -| **Step 3** | Configured and connected the Facilitator settlement service | -| **Step 4** | Verified payment protection and the full payment flow | +| **Step 1** | Cloned the SDK repo and installed the example workspace | +| **Step 2** | Configured `.env-exact` with your wallet and payout addresses | +| **Step 3** | Ran a keyless Express resource server with payment protection | +| **Step 4** | Connected to a Facilitator (official or self-hosted) for settlement | +| **Step 5** | Verified payment protection and the full client → server → facilitator payment flow | Your API is now ready to accept blockchain payments via the x402 protocol! diff --git a/docs/x402/index.md b/docs/x402/index.md index b086724f..07de30f6 100644 --- a/docs/x402/index.md +++ b/docs/x402/index.md @@ -15,7 +15,7 @@ x402 currently supports the **TRON** and **BSC** networks, with plans to expand Feel free to submit a PR to the [GitHub repository](https://github.com/BofAI/docs). Our only principle is to maintain neutrality — aside from essential resource links, please avoid promotional or branded content. **Looking for runnable examples?** -Visit the [x402-demo repository](https://github.com/BofAI/x402-demo) for a complete, production-ready sample project. +The [`x402` repository](https://github.com/BofAI/x402) ships runnable client → server → facilitator trios under `examples/typescript/` for every scheme — `exact`, `gasfree`, `upto`, and `batch-settlement`. --- @@ -81,9 +81,7 @@ x402 currently supports the following networks: - **BSC Mainnet** (`eip155:56`) - **BSC Testnet** (`eip155:97`) -> **Protocol interoperability**: Since v0.5.9, the `exact` payment scheme (EVM and TRON) conforms to the v2 specification published by the **x402 Foundation (formerly Coinbase)**, enabling bidirectional interoperability with the x402 Foundation's v2 reference clients and servers. See [SDK Feature Matrix](./sdk-features) and [Network & Token Support](./core-concepts/network-and-token-support#exact-scheme) for details. - -> **TypeScript / Python parity (v0.6.0)**: As of v0.6.0, the TypeScript SDK reaches feature parity with Python for the Server and Facilitator roles — facilitator client and engine, server middleware (Hono + Express), the `fetch` wrapper, facilitator signers, and `exact` / `exact_permit` / `exact_gasfree` verify + settle. See the [SDK Feature Matrix](./sdk-features) for the full breakdown. +> **SDK 1.0.0 (TypeScript-only)**: x402 `1.0.0` is a TypeScript-only pnpm/turbo monorepo published as granular `@bankofai/x402-*` packages (`core`, `evm`, `tron`, `fetch`, `express`, `hono`, `fastify`, `next`, `axios`, `mcp`, `extensions`). The `core` and EVM mechanism fork the [`x402-foundation/x402`](https://github.com/x402-foundation/x402) upstream; the TRON mechanism is in-house. Supported schemes: `exact` (ERC-3009 / Permit2), `upto`, `batch-settlement`, `auth-capture` (EVM), and `exact_gasfree` (TRON). The previous-generation Python + TypeScript SDK lives under `legacy/` for reference. See the [SDK Feature Matrix](./sdk-features) for the full breakdown. --- diff --git a/docs/x402/sdk-features.md b/docs/x402/sdk-features.md index 897a9e4f..73c75dac 100644 --- a/docs/x402/sdk-features.md +++ b/docs/x402/sdk-features.md @@ -1,124 +1,159 @@ --- title: 'SDK Feature Matrix' -description: 'Implementation status and feature support comparison between the Python and TypeScript SDKs for x402.' +description: 'Feature support matrix for the x402 TypeScript SDK (1.0.0), published as granular @bankofai/x402-* packages.' --- # SDK Feature Matrix -This page tracks the implementation progress and feature support status of the x402 SDKs across supported languages (Python and TypeScript). +This page tracks the feature support of the x402 SDK. -> **TypeScript / Python parity (since v0.6.0)**: As of **v0.6.0**, the TypeScript SDK reaches feature parity with Python for the Server and Facilitator roles. TypeScript now ships the facilitator client and engine (`X402Facilitator`), server middleware (`x402Hono` / `x402Express`), the `fetch` wrapper, facilitator signers, and `exact` / `exact_permit` / `exact_gasfree` verify + settle paths. +> **SDK 1.0.0 (TypeScript-only)**: x402 is a **TypeScript-only** pnpm/turbo monorepo published as granular `@bankofai/x402-*` packages. The `core` and EVM mechanism fork the [`x402-foundation/x402`](https://github.com/x402-foundation/x402) upstream; the TRON mechanism is in-house. The previous-generation Python + TypeScript SDK lives under `legacy/` for reference. + +--- + +## Packages + +| Package | Purpose | +|---------|---------| +| `@bankofai/x402-core` | Protocol types, client/facilitator/server engines, `HTTPFacilitatorClient`, observability | +| `@bankofai/x402-evm` | EVM mechanism: `exact`, `upto`, `batch-settlement`, `auth-capture` | +| `@bankofai/x402-tron` | TRON mechanism: `exact`, `upto`, `batch-settlement`, `exact_gasfree` | +| `@bankofai/x402-fetch` | Wrapped-`fetch` client (`wrapFetchWithPayment`) | +| `@bankofai/x402-express` | Express server middleware | +| `@bankofai/x402-hono` | Hono server middleware | +| `@bankofai/x402-fastify` | Fastify server middleware | +| `@bankofai/x402-next` | Next.js server middleware | +| `@bankofai/x402-axios` | Axios client wrapper | +| `@bankofai/x402-mcp` | MCP transport (client + server) for AI agents | +| `@bankofai/x402-extensions` | Extensions: gas-sponsoring, payment-identifier, bazaar, sign-in-with-x, offer-receipt, builder-code | --- ## Core Components -| Component | Python | TypeScript | -|------------|--------|------------| -| Server | ✅ | ✅ | -| Client | ✅ | ✅ | -| Facilitator | ✅ | ✅ | +| Component | Status | +|------------|--------| +| Resource Server | ✅ | +| Client | ✅ | +| Facilitator | ✅ | ### HTTP Framework Integration -| Role | Python | TypeScript | -|------|--------|------------| -| Server | FastAPI, Flask | Hono, Express | -| Client | httpx | fetch | +| Role | Frameworks | +|------|------------| +| Server | Express, Fastify, Hono, Next.js | +| Client | `fetch` (wrapped), Axios, MCP | --- ## Networks -| Network | Python | TypeScript | -|-----------|--------|------------| -| tron:mainnet | ✅ | ✅ | -| tron:nile | ✅ | ✅ | -| tron:shasta | ✅ | ✅ | -| eip155:56 (BSC Mainnet) | ✅ | ✅ | -| eip155:97 (BSC Testnet) | ✅ | ✅ | +| Network | Status | +|-----------|--------| +| `tron:mainnet` | ✅ | +| `tron:nile` | ✅ | +| `tron:shasta` | ✅ | +| `eip155:56` (BSC Mainnet) | ✅ | +| `eip155:97` (BSC Testnet) | ✅ | + +> Upstream EVM chains (Base, Base Sepolia, MegaETH, Monad, Hyperliquid) are also wired in the EVM default-asset registry. Adding a chain is a config-table edit in the examples — no SDK changes. --- -## Payment Mechanisms +## Payment Schemes + +x402 1.0.0 supports five payment schemes. Each is implemented as a client + server + facilitator trio per chain family. -| Mechanism | Python | TypeScript | -|-------------|--------|------------| -| exact_permit/tron | ✅ | ✅ | -| exact_permit/bsc | ✅ | ✅ | -| exact/tron | ✅ | ✅ | -| exact/bsc | ✅ | ✅ | -| exact_gasfree/tron | ✅ | ✅ | +| Scheme | EVM | TRON | Description | +|--------|-----|------|-------------| +| `exact` | ✅ | ✅ | Pay the exact amount. ERC-3009 `transferWithAuthorization` (gasless) or Permit2 (one-time `approve(Permit2)`) for plain ERC-20s. | +| `upto` | ✅ | ✅ | Usage-based billing — the client signs a Permit2 authorization for up to a maximum; the server settles only the real usage (≤ max). | +| `batch-settlement` | ✅ | ✅ | Payment-channel: deposit once on-chain, then pay many requests with off-chain vouchers; the facilitator claims a batch and settles in one tx. Includes a refund path. | +| `auth-capture` | ✅ | ❌ | Escrow-style authorization capture (EVM only). | +| `exact_gasfree` | ❌ | ✅ | TRON-only. Pay with USDT/USDD **without holding TRX for gas** — a relayer pays the on-chain energy via the GasFree API. | -> **Coinbase x402 v2 compatibility**: Since v0.5.9, the `payload` emitted by the `exact` mechanism (EVM and TRON) aligns with the x402 Foundation (formerly Coinbase) v2 wire format. Stock v2 clients can interoperate with this SDK's server and vice versa. See [Network & Token Support → `exact` Scheme](./core-concepts/network-and-token-support.md#exact-scheme) for details. +> **x402 Foundation v2 compatibility**: The `exact` scheme (EVM and TRON) conforms to the v2 wire format published by the **x402 Foundation**. Stock v2 clients interoperate with this SDK's server and vice versa. See [Network & Token Support → `exact` Scheme](./core-concepts/network-and-token-support.md#exact-scheme) for details. --- ## Signers -| Signer | Python | TypeScript | -|----------|--------|------------| -| TronClientSigner | ✅ | ✅ | -| EvmClientSigner | ✅ | ✅ | -| TronFacilitatorSigner | ✅ | ✅ | -| EvmFacilitatorSigner | ✅ | ✅ | +Key custody is in [`@bankofai/agent-wallet`](https://github.com/BofAI/agent-wallet); the SDK never sees a raw private key. The signer factories build the chain client (viem / TronWeb) internally. + +| Signer factory | Role | +|----------|------| +| `createClientTronSigner` | Client (TRON) | +| `createClientEvmSigner` | Client (EVM) | +| `createFacilitatorTronSigner` | Facilitator (TRON) | +| `createFacilitatorEvmSigner` | Facilitator (EVM) | +| `createAuthorizerTronSigner` | Authorizer (TRON, batch-settlement) | --- ## Client Features -| Feature | Python | TypeScript | -|------------|--------|------------| -| Automatic 402 handling | ✅ | ✅ | -| Automatic token approval | ✅ | ✅ | -| Allowance check | ✅ | ✅ | -| Signing (TRON) | ✅ | ✅ | -| Signing (EVM) | ✅ | ✅ | -| SufficientBalancePolicy | ✅ | ✅ | -| GasFree (zero-gas TRON payments) | ✅ | ✅ | +| Feature | Status | +|------------|--------| +| Automatic 402 handling (`wrapFetchWithPayment`) | ✅ | +| Automatic Permit2 / token approval | ✅ | +| Allowance check | ✅ | +| Signing (TRON, TIP-712) | ✅ | +| Signing (EVM, EIP-712) | ✅ | +| Balance-aware payment selection (`filterAffordableRequirements`) | ✅ | +| Cheapest-token selection strategy | ✅ | +| GasFree (zero-gas TRON payments) | ✅ | --- ## Server Features -| Feature | Python | TypeScript | -|------------|--------|------------| -| Protected-route integration | ✅ (`@x402_protected` decorator) | ✅ (`x402Hono` / `x402Express` middleware) | -| Payment verification | ✅ | ✅ | -| Payment settlement | ✅ | ✅ | -| Fee support | ✅ | ✅ | +| Feature | Status | +|------------|--------| +| Protected-route integration | ✅ (`paymentMiddlewareFromHTTPServer`, `x402HTTPResourceServer`) | +| Multi-chain `accepts` advertisement | ✅ | +| Gas-sponsoring extension (Permit2 approve) | ✅ | +| Payment verification (via facilitator) | ✅ | +| Payment settlement (via facilitator) | ✅ | +| Fee support | ✅ | --- ## Facilitator Features -| Feature | Python | TypeScript | -|------------|--------|------------| -| `/verify` endpoint | ✅ | ✅ | -| `/settle` endpoint | ✅ | ✅ | -| `/fee/quote` endpoint | ✅ | ✅ | -| `/supported` endpoint | ✅ | ✅ | -| Submit transaction | ✅ | ✅ | -| Confirm transaction | ✅ | ✅ | +| Feature | Status | +|------------|--------| +| `POST /verify` endpoint | ✅ | +| `POST /settle` endpoint | ✅ | +| `GET /supported` endpoint | ✅ | +| Submit on-chain transaction | ✅ | +| Confirm transaction (receipt polling) | ✅ | +| Extension hooks (`onBeforeSettle` / `onAfterSettle` / `onSettleFailure`) | ✅ | + +> The self-hosted example facilitator (`facilitator/basic`) exposes `/verify`, `/settle`, `/supported`. The official hosted facilitator additionally offers `/fee/quote` and `/payments/{id}` query endpoints — see [Official Facilitator](./core-concepts/OfficialFacilitator.md). --- ## Supported Tokens -| Token | Python | TypeScript | -|--------|--------|------------| -| USDT (TRC-20) | ✅ | ✅ | -| USDD (TRC-20) | ✅ | ✅ | -| Custom TRC-20 | ✅ | ✅ | -| USDT (BEP-20) | ✅ | ✅ | -| USDC (BEP-20, mainnet & testnet) | ✅ | ✅ | -| DHLU (BSC testnet, for `exact` interop tests) | ✅ | ✅ | -| Custom BEP-20 | ✅ | ✅ | +| Token | Network | Status | +|--------|---------|--------| +| USDT (TRC-20) | `tron:mainnet`, `tron:nile` | ✅ | +| USDD (TRC-20) | `tron:mainnet`, `tron:nile` | ✅ | +| USDT (BEP-20) | `eip155:56`, `eip155:97` | ✅ | +| USDC (BEP-20) | `eip155:56`, `eip155:97` | ✅ | +| DHLU (BSC testnet, ERC-3009) | `eip155:97` | ✅ | +| Custom TRC-20 / BEP-20 | any | ✅ (via token registry / `EVM_TOKENS` config) | + +--- + +## Observability + +All `@bankofai/x402-*` packages write through one process-global logger from `@bankofai/x402-core`. Call `setLogger(...)` once at startup to redirect logs to a file, `pino`/`winston`, or `noopLogger` to silence. --- ## Legend -- ✅ = Implemented -- ⏳ = Planned / In Progress -- ❌ = Not Planned +- ✅ = Implemented +- ⏳ = Planned / In Progress +- ❌ = Not Planned diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/AGENTS.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/AGENTS.md index 6d43a48a..3574f32c 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/AGENTS.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/AGENTS.md @@ -16,20 +16,20 @@ import TabItem from '@theme/TabItem'; - `docs/faq.md` — 常见问题解答。 - `sidebars.js` — Docusaurus 侧边栏配置文件。 - `docusaurus.config.js` — Docusaurus 主配置文件。 -- `docs/sdk-features.md` — Python 与 TypeScript SDK 的功能特性对比表。 +- `docs/sdk-features.md` — 仅 TypeScript 的 x402 SDK(`@bankofai/x402-*` 包)功能矩阵。 ## 3. 代码与文档的同步机制 文档维护需遵循以下依赖关系,确保代码变更即时反映在文档中: - `typescript/packages/` 目录下的变更 $\rightarrow$ 需同步更新 TypeScript 相关文档。 -- `python/x402/` 目录下的变更 $\rightarrow$ 需同步更新 Python 相关文档。 +- `examples/typescript/` 目录下的变更 $\rightarrow$ 需更新「快速入门」指南与代码示例(快速入门以示例为蓝本)。 - 端点逻辑的变更 $\rightarrow$ 需更新“快速入门”指南。 - 底层机制的变更 $\rightarrow$ 需更新 `core-concepts` 文档。 ## 4. 风格与规范 -- 以 **Python** 作为主要代码示例(鉴于其 SDK 功能最为完备)。 -- 在功能支持的情况下,务必补充 **TypeScript** 示例。 +- 以 **TypeScript** 作为主要代码示例(SDK 仅 TypeScript;此前的 Python SDK 已移至 `legacy/`)。 +- 尽可能引用 `examples/typescript/` 目录中的可运行示例源码。 - 所有 API 调用示例必须包含完整的错误处理逻辑。 - 内容撰写面向具有 **2–5 年经验** 的开发者。 - 必须使用 Docusaurus MDX 组件(``、``)来展示多语言代码。 @@ -117,7 +117,7 @@ import TabItem from '@theme/TabItem'; - `*/signers/` 目录中新增了签名器。 - 客户端 (Client) 或服务端 (Server) 新增了功能特性。 -**注意**:更新文档时,需同时交叉检查 **Python** 与 **TypeScript** 两个 SDK 的实现进度。 +**注意**:SDK 仅 TypeScript。更新文档时需对照 `typescript/packages/` 的导出与 `examples/typescript/` 的源码交叉检查。 ## 12.开发常用命令 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/get-started.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/get-started.md index 200579fa..8fe0e560 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/get-started.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/get-started.md @@ -58,7 +58,7 @@ x402-cli pay 'https://x402-gateway.bankofai.io/providers//' \ --method POST \ --network tron:mainnet \ --token USDT \ - --scheme exact_permit \ + --scheme exact \ --max-amount 0.000001 \ --header 'Content-Type: application/json' \ --body '{ ... }' @@ -69,7 +69,7 @@ x402-cli pay 'https://x402-gateway.bankofai.io/providers//' \ | `--method` | HTTP 方法(默认 `GET`) | | `--network` | CAIP-2 支付链,如 `tron:mainnet`、`eip155:56` | | `--token` | 结算代币,如 `USDT` | -| `--scheme` | 路由声明的 x402 支付方案,如 `exact_permit` 或 `exact_gasfree` | +| `--scheme` | 路由声明的 x402 支付方案,如 `exact` 或 `exact_gasfree` | | `--max-amount` | 美元支出上限;报价超出即中止调用 | | `--header` / `--body` | 转发到上游的请求头与请求体 | diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/list-your-service.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/list-your-service.md index a8756910..88c3b524 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/list-your-service.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/list-your-service.md @@ -76,13 +76,13 @@ x402-cli catalog export-gateway https://gateway.example.com \ "title": "SunPump", "mainTitle": "One-call agent token launch, paid via x402", "subtitle": "Create a meme or agent token from structured metadata.", - "description": "## What it does\n\nSunPump Agent Token Launch API lets agents, scripts, and applications pay with x402 and submit token launch metadata to SunPump. The gateway forwards the caller's JSON payload to the SunPump launch endpoint after payment settlement.\n\n## Best for\n\n- Agent workflows that need to create a meme or agent token from structured metadata.\n- Operator tools that want one paid API call for token creation.\n- Mainnet payment flows across TRON and BSC while using the same SunPump launch request shape.\n\n## Request shape\n\nPOST a JSON body with `name`, `symbol`, `description`, `imageBase64`, `twitterUrl`, `telegramUrl`, `websiteUrl`, and `tweetUsername`. Keep `name` within 1-20 characters and use a unique symbol. `imageBase64` may include a base64-encoded token image; if it is empty or omitted, SunPump generates an image automatically.\n\n## Code usage\n\nUse `x402-cli pay` against the route for the mainnet payment chain you want. TRON Mainnet example:\n\n```bash\nx402-cli pay 'https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron/pump-api/ai/agentTokenLaunch' \\\n --method POST \\\n --network tron:mainnet \\\n --token USDT \\\n --scheme exact_permit \\\n --max-amount 0.000001 \\\n --header 'Content-Type: application/json' \\\n --body '{\"name\":\"X402MainA\",\"symbol\":\"X4M17\",\"description\":\"x402 launch\",\"imageBase64\":\"\",\"twitterUrl\":\"\",\"telegramUrl\":\"\",\"websiteUrl\":\"\",\"tweetUsername\":\"\"}'\n```\n\nBSC Mainnet uses `sunpump-token-launch-bsc` with `eip155:56` and the same JSON body.", + "description": "## What it does\n\nSunPump Agent Token Launch API lets agents, scripts, and applications pay with x402 and submit token launch metadata to SunPump. The gateway forwards the caller's JSON payload to the SunPump launch endpoint after payment settlement.\n\n## Best for\n\n- Agent workflows that need to create a meme or agent token from structured metadata.\n- Operator tools that want one paid API call for token creation.\n- Mainnet payment flows across TRON and BSC while using the same SunPump launch request shape.\n\n## Request shape\n\nPOST a JSON body with `name`, `symbol`, `description`, `imageBase64`, `twitterUrl`, `telegramUrl`, `websiteUrl`, and `tweetUsername`. Keep `name` within 1-20 characters and use a unique symbol. `imageBase64` may include a base64-encoded token image; if it is empty or omitted, SunPump generates an image automatically.\n\n## Code usage\n\nUse `x402-cli pay` against the route for the mainnet payment chain you want. TRON Mainnet example:\n\n```bash\nx402-cli pay 'https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron/pump-api/ai/agentTokenLaunch' \\\n --method POST \\\n --network tron:mainnet \\\n --token USDT \\\n --scheme exact \\\n --max-amount 0.000001 \\\n --header 'Content-Type: application/json' \\\n --body '{\"name\":\"X402MainA\",\"symbol\":\"X4M17\",\"description\":\"x402 launch\",\"imageBase64\":\"\",\"twitterUrl\":\"\",\"telegramUrl\":\"\",\"websiteUrl\":\"\",\"tweetUsername\":\"\"}'\n```\n\nBSC Mainnet uses `sunpump-token-launch-bsc` with `eip155:56` and the same JSON body.", "useCase": "Use this provider when an app, agent, or CLI workflow needs to launch a SunPump token after a successful x402 payment. Choose the route matching the intended mainnet payment chain: TRON Mainnet or BSC Mainnet.", "i18n": { "zh-CN": { "title": "SunPump", "subtitle": "用结构化元数据一次付费发币(meme/Agent 代币)。", - "description": "## 能做什么\n\nSunPump Agent 发币 API 允许 Agent、脚本和应用先完成 x402 支付,再把发币元数据提交给 SunPump。Gateway 在支付结算后把调用方的 JSON 请求体转发到 SunPump 发币接口。\n\n## 适合场景\n\n- 需要基于结构化元数据创建 meme token 或 agent token 的 Agent 工作流。\n- 希望用一次付费 API 调用完成发币的运营工具。\n- 在 TRON 和 BSC 主网上使用同一套 SunPump 发币请求格式验证支付流程。\n\n## 请求格式\n\nPOST JSON 请求体包含 `name`、`symbol`、`description`、`imageBase64`、`twitterUrl`、`telegramUrl`、`websiteUrl` 和 `tweetUsername`。`name` 需要保持在 1-20 个字符内,并使用唯一 symbol。`imageBase64` 可以传入 base64 编码的 token 图片;如果为空或不传,SunPump 会自动生成图片。\n\n## 代码用法\n\n使用 `x402-cli pay` 调用目标主网支付链对应的路由。TRON 主网示例:\n\n```bash\nx402-cli pay 'https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron/pump-api/ai/agentTokenLaunch' \\\n --method POST \\\n --network tron:mainnet \\\n --token USDT \\\n --scheme exact_permit \\\n --max-amount 0.000001 \\\n --header 'Content-Type: application/json' \\\n --body '{\"name\":\"X402MainA\",\"symbol\":\"X4M17\",\"description\":\"x402 launch\",\"imageBase64\":\"\",\"twitterUrl\":\"\",\"telegramUrl\":\"\",\"websiteUrl\":\"\",\"tweetUsername\":\"\"}'\n```\n\nBSC 主网使用 `sunpump-token-launch-bsc` 和 `eip155:56`,请求体相同。", + "description": "## 能做什么\n\nSunPump Agent 发币 API 允许 Agent、脚本和应用先完成 x402 支付,再把发币元数据提交给 SunPump。Gateway 在支付结算后把调用方的 JSON 请求体转发到 SunPump 发币接口。\n\n## 适合场景\n\n- 需要基于结构化元数据创建 meme token 或 agent token 的 Agent 工作流。\n- 希望用一次付费 API 调用完成发币的运营工具。\n- 在 TRON 和 BSC 主网上使用同一套 SunPump 发币请求格式验证支付流程。\n\n## 请求格式\n\nPOST JSON 请求体包含 `name`、`symbol`、`description`、`imageBase64`、`twitterUrl`、`telegramUrl`、`websiteUrl` 和 `tweetUsername`。`name` 需要保持在 1-20 个字符内,并使用唯一 symbol。`imageBase64` 可以传入 base64 编码的 token 图片;如果为空或不传,SunPump 会自动生成图片。\n\n## 代码用法\n\n使用 `x402-cli pay` 调用目标主网支付链对应的路由。TRON 主网示例:\n\n```bash\nx402-cli pay 'https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron/pump-api/ai/agentTokenLaunch' \\\n --method POST \\\n --network tron:mainnet \\\n --token USDT \\\n --scheme exact \\\n --max-amount 0.000001 \\\n --header 'Content-Type: application/json' \\\n --body '{\"name\":\"X402MainA\",\"symbol\":\"X4M17\",\"description\":\"x402 launch\",\"imageBase64\":\"\",\"twitterUrl\":\"\",\"telegramUrl\":\"\",\"websiteUrl\":\"\",\"tweetUsername\":\"\"}'\n```\n\nBSC 主网使用 `sunpump-token-launch-bsc` 和 `eip155:56`,请求体相同。", "useCase": "适合应用、Agent 或 CLI 流程在 x402 支付成功后调用 SunPump 发币接口。根据主网支付链选择 TRON 主网或 BSC 主网路由。", "mainTitle": "一次付费完成 Agent 代币发行(x402)" } @@ -112,13 +112,13 @@ x402-cli catalog export-gateway https://gateway.example.com \ { "network": "tron:mainnet", "provider": "sunpump-token-launch-tron", - "scheme": "exact_permit", + "scheme": "exact", "url": "https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron/pump-api/ai/agentTokenLaunch" }, { "network": "eip155:56", "provider": "sunpump-token-launch-bsc", - "scheme": "exact_permit", + "scheme": "exact", "url": "https://x402-gateway.bankofai.io/providers/sunpump-token-launch-bsc/pump-api/ai/agentTokenLaunch" } ], @@ -181,7 +181,7 @@ x402-cli pay 'https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tr --method POST \ --network tron:mainnet \ --token USDT \ - --scheme exact_permit \ + --scheme exact \ --max-amount 0.000001 \ --header 'Content-Type: application/json' \ --body '{"name":"X402MainA","symbol":"X4M17","description":"x402 launch","imageBase64":"","twitterUrl":"","telegramUrl":"","websiteUrl":"","tweetUsername":""}' @@ -194,7 +194,7 @@ x402-cli pay 'https://x402-gateway.bankofai.io/providers/sunpump-token-launch-bs --method POST \ --network eip155:56 \ --token USDT \ - --scheme exact_permit \ + --scheme exact \ --max-amount 0.000001 \ --header 'Content-Type: application/json' \ --body '{"name":"X402BscA","symbol":"X4B17","description":"x402 launch","imageBase64":"","twitterUrl":"","telegramUrl":"","websiteUrl":"","tweetUsername":""}' diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/reference.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/reference.md index 4c501087..ea2e127a 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/reference.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/reference.md @@ -62,7 +62,7 @@ description: catalog.json / pay.md 的字段定义、合法类目与链 ID,以 |---|---|---| | `network` | string | 该路由结算所在的 CAIP-2 链 ID(如 `tron:mainnet`、`eip155:56`) | | `provider` | string | 处理该网络的 gateway provider `fqn` | -| `scheme` | string | 该路由的 x402 支付方案,如 `exact_permit` 或 `exact_gasfree` —— 由每条路由各自声明 | +| `scheme` | string | 该路由的 x402 支付方案,如 `exact` 或 `exact_gasfree` —— 由每条路由各自声明 | | `url` | string | 该网络路由的完整 gateway URL | 构建时该字段以 `x402_routes` 透传到产物。存在时,调用方/Agent 按目标支付链选择对应路由;顶层 `url` 仍是默认路由。 @@ -74,7 +74,7 @@ x402-cli pay 'https://x402-gateway.bankofai.io/providers//' \ --method POST \ --network tron:mainnet \ --token USDT \ - --scheme exact_permit \ + --scheme exact \ --max-amount 0.000001 \ --header 'Content-Type: application/json' \ --body '{ ... }' diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/client-server.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/client-server.md index 26253fc9..72cc3ddf 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/client-server.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/client-server.md @@ -21,7 +21,7 @@ - **发起请求**:向资源服务器发送初始 HTTP 请求。 - **处理支付要求**:解析 `402 Payment Required` 响应,并提取支付详情。 -- **管理代币授权**:授权 `PaymentPermit` 合约,使其能从客户端钱包划转代币用于结算。 +- **管理代币授权**:为普通 ERC-20/TRC-20 代币授权 Permit2(一次性 `approve(Permit2)`);ERC-3009 代币无需授权。SDK 在首次付款时自动广播。 - **准备支付载荷**:根据服务端的要求,构建并签署支付载荷。 - **携带支付凭证重发请求**:在请求头中附加 `PAYMENT-SIGNATURE` 并重新发送请求。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/facilitator.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/facilitator.md index 3ecc69a8..46e25c43 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/facilitator.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/facilitator.md @@ -11,7 +11,7 @@ Facilitator 是一种中间件服务,主要负责: - **验证载荷**:校验客户端提交的支付载荷的有效性。 - **执行结算**:代表服务端将交易提交至区块链进行结算。 -- **代币转移**:通过调用 `PaymentPermit` 合约的 `permitTransferFrom` 方法来执行代币转移。 +- **代币转移**:执行链上转账——根据方案,调用 ERC-3009 `transferWithAuthorization`、通过 `x402ExactPermit2Proxy` 的 Permit2 `permitTransferFrom`、批量 settlement claim 或 GasFree relay。 通过引入 Facilitator,服务端无需维护与区块链节点的直连,也无需自行实现复杂的签名验证逻辑。这不仅降低了运维复杂度,还能确保交易验证的准确性与实时性。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/http-402.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/http-402.md index 625b2e53..8822941a 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/http-402.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/http-402.md @@ -52,7 +52,7 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: }, "accepts": [ { - "scheme": "exact_permit", + "scheme": "exact", "network": "tron:nile", "amount": "100", "asset": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", @@ -71,15 +71,9 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: } ], "extensions": { - "paymentPermitContext": { - "meta": { - "kind": "PAYMENT_ONLY", - "paymentId": "0xb08d71cabc27d5552e36a7f60084e130", - "nonce": "11984290373079535093514815017206530944", - "validAfter": 1770816589, - "validBefore": 1770820189 - } - } + // 仅当代币需要 gas 赞助的 Permit2 approve 时才出现 + // (如 BSC USDC 等普通 ERC-20)。ERC-3009 代币省略此项。 + "erc20ApprovalGasSponsoring": {} } } ``` @@ -98,7 +92,7 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: }, "accepts": [ { - "scheme": "exact_permit", + "scheme": "exact", "network": "eip155:97", "amount": "100000000000000", "asset": "0x337610d27c682E347C9cD60BD4b3b107C9d34dDd", @@ -117,15 +111,9 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: } ], "extensions": { - "paymentPermitContext": { - "meta": { - "kind": "PAYMENT_ONLY", - "paymentId": "0xc00fc79b9a26084ad078b71ffcaa07fd", - "nonce": "94261896388554187915350651456800860604", - "validAfter": 1770817158, - "validBefore": 1770820758 - } - } + // BSC USDT 是普通 ERC-20 → Permit2 路径需要此 gas 赞助 + // 扩展,以便客户端离线签署一次性 approve。 + "erc20ApprovalGasSponsoring": {} } } ``` @@ -140,14 +128,14 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: | `error` | 人类可读的错误提示 | | `resource` | 关于请求资源的信息 | | `accepts` | 接受的支付选项数组 | -| `scheme` | 支付方案(`exact_permit` 或 `exact`) | +| `scheme` | 支付方案(`exact`、`upto`、`batch-settlement`、`auth-capture`、`exact_gasfree`) | | `network` | 网络标识符(`tron:nile`, `tron:mainnet`, `eip155:56`, `eip155:97`) | | `amount` | 支付金额,以最小单位计(例如:100 = 0.0001 USDT) | | `asset` | TRC-20/BEP-20 代币合约地址 | | `payTo` | 卖家的钱包地址 | | `maxTimeoutSeconds` | 支付有效期的最大时长 | | `extra.fee` | Facilitator 费用信息(包含 `facilitatorId`、`feeTo`、`feeAmount`、`caller`) | -| `extensions` | 支付方案的附加上下文(如 `paymentPermitContext`,包含 nonce、有效期窗口等) | +| `extensions` | 支付方案的附加上下文(如 gas 赞助、payment-identifier) | ## 支付签名结构 @@ -159,29 +147,18 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: ```json { "x402Version": 2, - "scheme": "exact_permit", + "scheme": "exact", "network": "tron:nile", "payload": { "signature": "0x...", - "permit": { - "meta": { - "kind": 0, - "paymentId": "0x65f9d4ca3fb5f6dd14930055aa5ccbc4", - "nonce": "241054476753796864345738420545497456919", - "validAfter": 1770817311, - "validBefore": 1770820911 - }, - "buyer": "", - "caller": "", - "payment": { - "payToken": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", - "payAmount": 100, - "payTo": "" - }, - "fee": { - "feeTo": "", - "feeAmount": 100 - } + "authorization": { + // Permit2 witness(TRON 上的 USDT/USDD 为普通 TRC-20) + "from": "", + "to": "", + "value": 100, + "validAfter": 1770817311, + "validBefore": 1770820911, + "nonce": "0x65f9d4ca3fb5f6dd14930055aa5ccbc4" } } } @@ -193,29 +170,18 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: ```json { "x402Version": 2, - "scheme": "exact_permit", + "scheme": "exact", "network": "eip155:97", "payload": { "signature": "0x...", - "permit": { - "meta": { - "kind": 0, - "paymentId": "0xc00fc79b9a26084ad078b71ffcaa07fd", - "nonce": "94261896388554187915350651456800860604", - "validAfter": 1770817158, - "validBefore": 1770820758 - }, - "buyer": "", - "caller": "", - "payment": { - "payToken": "0x337610d27c682E347C9cD60BD4b3b107C9d34dDd", - "payAmount": 100000000000000, - "payTo": "" - }, - "fee": { - "feeTo": "", - "feeAmount": 100000000000000 - } + "authorization": { + // Permit2 witness(BSC USDT 为普通 ERC-20) + "from": "", + "to": "", + "value": 100000000000000, + "validAfter": 1770817158, + "validBefore": 1770820758, + "nonce": "0xc00fc79b9a26084ad078b71ffcaa07fd" } } } diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/network-and-token-support.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/network-and-token-support.md index 4184bb20..3ac5a924 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/network-and-token-support.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/network-and-token-support.md @@ -57,14 +57,13 @@ x402 协议全面支持 **TRC-20/BEP-20** 标准代币,并默认将 **USDT** | **USDD** | `tron:nile` | `TGjgvdTWWrybVLaVeFqSyVqJQWjxqRYbaK` | | **USDT** | `eip155:56` | `0x55d398326f99059fF775485246999027B3197955` | | **USDC** | `eip155:56` | `0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d` | -| **EPS** | `eip155:56` | `0xA7f552078dcC247C2684336020c03648500C6d9F` | | **USDT** | `eip155:97` | `0x337610d27c682E347C9cD60BD4b3b107C9d34dDd` | | **USDC** | `eip155:97` | `0x64544969ed7EBf5f083679233325356EbE738930` | | **DHLU** | `eip155:97` | `0x375cADdd2cB68cE82e3D9B075D551067a7b4B816` | -> **扩展支持**:协议具有高度的可扩展性。通过在 `TokenRegistry` 中进行注册,您可以轻松配置并支持任意自定义的 TRC-20/BEP-20 代币。 +> **扩展支持**:协议具有高度的可扩展性。通过 TRON 代币注册表(`@bankofai/x402-tron` 的 `registerToken`)或 server 的 `EVM_TOKENS` 配置表,您可以轻松配置并支持任意自定义的 TRC-20/BEP-20 代币。 -> **关于 `exact` 方案的代币选择**:`exact` 方案要求代币原生实现 ERC-3009 `transferWithAuthorization`。在 BSC 测试网进行 `exact` 路径互通测试时推荐使用 **DHLU**(Da Hulu)测试代币;`USDT (BEP-20)` 并不原生支持 ERC-3009,请勿在 `exact` 方案中发布 USDT (BSC) 作为代币要求——若需要使用 USDT,请改走 `exact_permit` 方案。 +> **关于 `exact` 方案的代币选择**:ERC-3009 代币(如 BSC 测试网 **DHLU**)通过 `transferWithAuthorization` 无 gas 结算。普通 ERC-20 代币(如 BSC USDC/USDT、TRON USDT/USDD)通过 Permit2 路径结算——客户端首次付款时自动广播一次性 `approve(Permit2)`。每代币的结算方式由 server `accepts[].price.extra` 中的数据决定:ERC-3009 → `{ name, version }`;普通 ERC-20 → `{ assetTransferMethod: "permit2" }`。 #### 安全签名 @@ -90,38 +89,34 @@ x402 采用类型化数据签名来处理所有支付相关的签名授权。 ### 支付方案 -x402 支持三种支付方案:`exact_permit`、`exact` 和 `exact_gasfree`。 +x402 1.0.0 支持五种支付方案。每种方案按链族实现为 client + server + facilitator 三件套。 -#### `exact_permit` 方案 +#### `exact` 方案 -`exact_permit` 方案通过 `PaymentPermit` 合约进行代币转账,适用于: +`exact` 方案支付公布的准确金额,覆盖两种代币转账路径: -- **按次/按量付费 API**:例如 LLM 的 Token 生成费、图像生成服务。 -- **计量资源**:云计算实例的运行时间、数据存储量、网络带宽消耗。 -- **动态定价服务**:基于实际使用量的后付费模式。 +- **ERC-3009 `transferWithAuthorization`**:适用于原生支持该标准的代币(如 BSC 测试网 DHLU)。无 gas:无需 `approve`;客户端签署类型化数据授权,facilitator 在链上调用 `transferWithAuthorization`。 +- **Permit2**:适用于不实现 ERC-3009 的普通 ERC-20/TRC-20 代币(如 BSC USDC/USDT、TRON USDT/USDD)。客户端签署 Permit2 witness,facilitator 通过 `x402ExactPermit2Proxy` 合约结算。需要一次性 `approve(Permit2)`;客户端首次付款时自动广播。 -#### `exact` 方案 +`exact` 方案遵循 **x402 Foundation** 发布的 **v2 链路格式**:标准 v2 客户端可直接向本 SDK 的服务端发起付款请求,本 SDK 客户端也可直接访问任何 v2 兼容的服务端——无需项目特定的转换。转账授权数据位于 `payload.authorization` 中。 -`exact` 方案适用于原生支持 ERC-3009 `transferWithAuthorization` 的代币,无需 `PaymentPermit` 合约。 +#### `upto` 方案 -自 **v0.5.9** 起,EVM 和 TRON 上的 `exact` 方案已遵循 **x402 Foundation(原 Coinbase)** 公布的 v2 协议规范: +按量计费。客户端签署最高至最大金额的 Permit2 授权;服务端按每次请求决定**实际用量**并仅结算该部分(≤ max)。一次签名形状,每次请求不同收费——非常适合**按量计费**(LLM Token 消耗、计算时长、带宽)。EVM 和 TRON 均支持(均走 Permit2)。 -- **V2 链路传输格式 (Wire Format)**:`exact` 的 `payload` 遵循 v2 规范的字段布局和语义,标准 v2 客户端可直接向本 SDK 的服务端发起付款请求,本 SDK 客户端也可直接访问任何 v2 兼容的服务端,无需进行项目特定的转换。 -- **结构化 Authorization**:`nativeExact` / `nativeExactEvm` / `nativeExactTron` 机制已更新,现可生成 V2 兼容的 `payload`(采用包含类型化字段的授权结构,而非此前扁平的十六进制数据块)。转账授权数据位于 `payload.authorization` 中。 -- **迁移过渡兼容**:为降低升级期间的破坏性影响,客户端会同时写入 `payload.authorization`(V2)与 `extensions.transferAuthorization`(V1)两份;服务端则优先读取 `payload.authorization`,并对旧字段保留临时兼容。 -- **BSC 互通测试**:`examples/bsc-testnet-smoke/` 目录提供了 BSC 测试网互通烟雾测试示例(TypeScript 与 Python),已验证 "Coinbase 官方客户端 → BANK OF AI 服务端" 与 "BANK OF AI 客户端 → Coinbase 官方服务端" 双向路径。 +#### `batch-settlement` 方案 -#### `exact_gasfree` 方案 +面向高频微支付(如 AI 代理每 token 计费)的支付通道方案。客户端链上**一次性存入**,然后用链下**凭证**支付多次请求;facilitator **批量 claim** 并在一笔交易中结算到 `payTo`——因此 N 次请求约仅花费一次存入的 gas。含**退款**路径,可退回通道中未使用的余额。EVM 和 TRON 均支持。 -`exact_gasfree` 是 TRON 专属的支付机制,允许用户使用 USDT/USDD 付款而**无需持有 TRX 来支付 gas 费用**。结算通过 BANK OF AI Facilitator 端点的官方 GasFree 代理完成。 +#### `auth-capture` 方案 -核心特性: +托管式授权捕获(仅 EVM)。资金被授权进入托管合约,并按业务逻辑释放。 -- **买家零 gas 成本**:买家无需持有 TRX,gas 费用由 GasFree 基础设施承担 -- **无需 API 密钥**:所有 GasFree API 调用通过 BANK OF AI 代理路由至 `https://facilitator.bankofai.io/{mainnet,nile}`,客户端无需配置 `GASFREE_API_KEY` 或 `GASFREE_API_SECRET` -- **仅限 TRON**:支持 `tron:mainnet` 和 `tron:nile` +#### `exact_gasfree` 方案 + +TRON 专属。允许用户使用 USDT/USDD 付款而**无需持有 TRX 来支付 gas 费用**。客户端签署 TIP-712 GasFree 许可,由 relayer 通过官方 GasFree 代理支付链上 energy——付款方无需 TRX,也无需一次性 `approve`。资金来自付款方的 GasFree 托管钱包(非主钱包)。支持 `tron:mainnet` 和 `tron:nile`。 -#### GasFree 账户管理(通过 x402-payment skill) +##### GasFree 账户管理(通过 x402-payment skill) 使用 `x402-payment` skill 时,可直接通过 CLI 管理 GasFree 账户: @@ -141,27 +136,27 @@ npx tsx x402-payment/src/x402_invoke.ts --gasfree-activate --network nile --toke #### 工作原理 -1. **预授权 (Authorize)**:客户端签署消息,授权支付**最大金额** (Max Amount)。 -2. **执行服务 (Execute)**:服务端执行请求任务,并计算**实际成本** (Actual Cost)。 -3. **最终结算 (Settle)**:Facilitator 根据实际成本发起链上扣款。 +1. **预授权 (Authorize)**:客户端签署类型化数据消息,授权付款(精确金额,或 `upto`/`batch-settlement` 的最大金额)。 +2. **执行服务 (Execute)**:服务端执行请求任务,并(对于按量计费方案)计算**实际成本**。 +3. **最终结算 (Settle)**:Facilitator 根据方案发起链上交易——`transferWithAuthorization`、Permit2 `permitTransferFrom`、批量 claim 或 GasFree relay。 ### 部署私有 Facilitator -您可以选择部署私有的 Facilitator 节点,以完全掌控区块链网络上的支付验证与结算流程。 +您可以选择部署私有的 Facilitator,以完全掌控区块链网络上的支付验证与结算流程。自托管示例(`examples/typescript/facilitator/basic`)是一个暴露 `/verify`、`/settle`、`/supported` 的 Express 服务——无需数据库。 Facilitator 作为协议的中间件,承担以下核心职责: -1. **验证载荷 (Verify)**:校验签名的加密有效性及参数完整性。 -2. **提交交易 (Submit)**:构建并向区块链广播 `transferFrom` 交易。 +1. **验证载荷 (Verify)**:校验类型化数据签名的加密有效性及参数完整性。 +2. **提交交易 (Submit)**:构建并向区块链广播链上结算交易。 3. **监控确认 (Monitor)**:追踪交易在链上的确认状态,确保资金最终到账。 **部署先决条件** -- **节点访问权限**:稳定的全节点 RPC 访问(例如 TronGrid 或自建节点)。 -- **Gas 资源储备**:一个持有充足 **TRX/BNB** 的钱包,用于支付链上交易产生的 gas 费用。 -- **代码部署**:拉取并配置 x402 Facilitator 服务代码。 +- **节点访问权限**:稳定的 RPC 访问(例如 TronGrid 或公共 BSC 端点)。 +- **Gas 资源储备**:一个持有充足 **TRX/BNB** 的钱包,用于支付结算 gas 费用。 +- **代码部署**:运行 `examples/typescript/facilitator/basic` 示例 facilitator。 -> **深入了解**:请查阅 [Facilitator](./facilitator.md) 文档以获取详细的配置指南与 API 参考。 +> **深入了解**:请查阅 [Facilitator](./facilitator.md) 文档以获取详细的配置指南与 API 参考,以及[卖家快速入门](../getting-started/quickstart-for-sellers.md)。 ### 快速参考 @@ -169,28 +164,27 @@ Facilitator 作为协议的中间件,承担以下核心职责: | :----------- | :----------------------------------------- | | **网络环境** | `tron:mainnet`, `tron:shasta`, `tron:nile`, `eip155:56`, `eip155:97` | | **代币标准** | TRC-20 代币(默认内置 USDT 和 USDD 支持),BEP-20 代币 | -| **签名机制** | 类型化数据签名 | -| **支付方案** | `exact_permit`, `exact`, `exact_gasfree`(仅限 TRON) | +| **签名机制** | TIP-712 / EIP-712 类型化数据签名 | +| **支付方案** | `exact`、`upto`、`batch-settlement`、`auth-capture`(EVM)、`exact_gasfree`(TRON) | ### 添加自定义代币 -可通过在 `TokenRegistry`(代币注册表)中注册来支持自定义 TRC-20/BEP-20 代币: +在**客户端 / facilitator** 侧,通过 TRON 代币注册表(`@bankofai/x402-tron`)注册自定义 TRC-20 代币: -```python -from bankofai.x402.tokens import TokenRegistry, TokenInfo +```typescript +import { registerToken } from "@bankofai/x402-tron"; -TokenRegistry.register_token( - "tron:nile", - TokenInfo( - address="", - decimals=6, - name="My Token", - symbol="MYT", - ), -) +registerToken("tron:nile", { + address: "", + decimals: 6, + name: "My Token", + symbol: "MYT", +}); ``` -注册完成后,即可在 `prices` 中使用自定义代币符号(例如 `"0.01 MYT"`)。 +在**资源服务器**侧,自定义 EVM 代币通过在 server 的 `src/chains/evm.ts` 中的 `EVM_TOKENS` 表添加一条目来公布——一个显式的 `{ asset, amount, extra }` 对象。添加一条链仅需一条表项;无需改动 SDK。 + +注册完成后,即可在 TRON 价格中使用自定义代币符号(例如 `"0.001 MYT"`)。 ### 总结 @@ -200,5 +194,5 @@ x402 专为区块链架构深度定制,提供了原生的 TRC-20/BEP-20 代币 - **开发环境**:推荐优先使用 **测试网** 进行开发与调试。 - **原生资产**:**USDT** 为默认的首选结算代币,且 SDK 已预置相关合约地址配置。 -- **安全机制**:类型化数据签名机制确保了安全且最小化信任 (Trust-minimized) 的支付授权流程。 -- **扩展能力**:可通过 `TokenRegistry` 接口灵活扩展支持任意自定义的 **TRC-20/BEP-20 代币**。 +- **安全机制**:TIP-712 / EIP-712 类型化数据签名机制确保了安全且最小化信任 (Trust-minimized) 的支付授权流程。 +- **扩展能力**:可通过 TRON 代币注册表(`registerToken`)或 server 的 `EVM_TOKENS` 配置表灵活扩展支持任意自定义的 **TRC-20/BEP-20 代币**。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/wallet.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/wallet.md index 07ce09d5..71aa6711 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/wallet.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/wallet.md @@ -56,7 +56,7 @@ x402 协议采用类型化数据签名来执行安全的支付授权。 ## 代币授权 -对于 `exact_permit` 支付方案,客户端必须授权 `PaymentPermit` 合约从其钱包中划转代币以进行支付结算。这是通过标准的 TRC-20/BEP-20 `approve` 函数完成的。 +对于 `exact` 支付方案,普通 ERC-20/TRC-20 代币(如 BSC USDC/USDT、TRON USDT/USDD)通过 Permit2 路径结算。客户端需授权 Permit2 合约划转代币——一次性 `approve(Permit2, max)`。x402 客户端 SDK 会在首次付款时自动广播此授权。ERC-3009 代币(如 BSC 测试网 DHLU)无需授权——通过 `transferWithAuthorization` 无 gas 结算。 x402 客户端 SDK 会自动处理此操作。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/faq.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/faq.md index b295fcfb..64683edb 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/faq.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/faq.md @@ -25,12 +25,13 @@ x402 唤醒了长期闲置的 HTTP `402 Payment Required` 状态码,将其转 #### 支持哪些语言和框架? -x402 目前提供以下 SDK: +x402 1.0.0 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发布: -- **Python**: 服务端集成 FastAPI 与 Flask;基于 `httpx` 的客户端 -- **TypeScript**: 服务端中间件支持 Hono 与 Express;标准 `fetch` 客户端 +- **服务端中间件**:Express、Fastify、Hono、Next.js +- **客户端**:包装 `fetch`(`@bankofai/x402-fetch`)、Axios、MCP 传输 +- **Facilitator**:链无关引擎,按方案 verify + settle -这两种语言的 SDK 均完整实现了客户端 (Client)、服务端 (Server) 和 Facilitator 的功能。自 **v0.6.0** 起,TypeScript SDK 在服务端与 Facilitator 角色上已与 Python 功能对齐(Facilitator 客户端/引擎、服务端中间件,以及 `exact` / `exact_permit` / `exact_gasfree` 的 verify + settle)。 +此前的 Python SDK 已移至 `legacy/` 仅供参考。 ### Facilitator @@ -55,23 +56,26 @@ x402 目前提供以下 SDK: - **单次调用固定费率**:例如,每次请求收取 `1 USDT`。 - **分层定价**:为不同级别的端点(如 `/basic` 与 `/pro`)设定差异化价格。 -- **`exact_permit` / `exact` 方案**:支付服务指定的准确金额 +- **`exact` 方案**:按公布的准确金额每次调用支付 #### x402 支持哪些支付方案? -x402 支持三种支付方案: +x402 1.0.0 支持五种支付方案: -- **`exact_permit`** 和 **`exact`**:两种方案均允许客户端授权一个**最高支付金额**,服务端结算**实际产生的费用**(不超过授权上限)。此方案非常适用于**按量计费 (Metered Billing)**、**LLM Token 消耗**等场景。自 v0.5.9 起,`exact` 方案的协议 `payload` 已遵循 **x402 Foundation(原 Coinbase)** 公布的 v2 规范。 -- **`exact_gasfree`**(仅限 TRON):允许买家使用 USDT/USDD 付款而无需持有 TRX 来支付 gas。所有 GasFree API 调用通过 BANK OF AI 代理路由,客户端无需配置 API 密钥。 +- **`exact`**:支付公布的准确金额。ERC-3009 代币(如 BSC 测试网 DHLU)通过 `transferWithAuthorization` 无 gas 结算;普通 ERC-20/TRC-20 代币(如 BSC USDC/USDT、TRON USDT/USDD)通过 Permit2 路径结算,首次付款需一次性 `approve(Permit2)`。`exact` 的协议 payload 遵循 **x402 Foundation** 的 v2 规范。 +- **`upto`**:按量计费——客户端签署最高至最大金额的 Permit2 授权,服务端仅结算**实际用量**(≤ max)。非常适合**按量计费**、**LLM Token 消耗**等场景。 +- **`batch-settlement`**:面向高频微支付的支付通道——一次性链上存入,然后用链下凭证支付多次请求,一笔交易批量结算。含退款路径。 +- **`auth-capture`**(仅 EVM):托管式授权捕获。 +- **`exact_gasfree`**(仅限 TRON):允许买家使用 USDT/USDD 付款而无需持有 TRX 来支付 gas。由 relayer 通过 GasFree API 支付链上 energy——客户端无需配置 API 密钥。 #### 本 SDK 是否可以与 x402 Foundation(原 Coinbase)的 v2 参考实现互通? -**可以。** 自 v0.5.9 起,`exact` 支付方案(EVM 与 TRON)已与 **x402 Foundation(原 Coinbase)** 公布的 v2 协议规范保持一致: +**可以。** `exact` 支付方案(EVM 与 TRON)已遵循 **x402 Foundation** 公布的 v2 协议规范: - 标准的 v2 客户端可以直接访问本 SDK 的 `exact` 受保护端点,无需任何项目特定的适配层。 - 本 SDK 的客户端可以直接向 v2 兼容的服务端付款。 - V2 结构中转账授权数据位于 `payload.authorization` 字段(结构化对象);作为迁移过渡,客户端还会同时填充 `extensions.transferAuthorization`,以便仍在运行旧版本的服务端也能解析。 -- 在 BSC 上使用 `exact` 方案时,**必须**选择代币自身原生实现 ERC-3009 `transferWithAuthorization` 的资产,例如 BSC 测试网上的 **DHLU**。BSC USDT 是普通 ERC-20,既不原生支持 ERC-3009 也不原生支持 EIP-2612 permit——如果需要用 USDT 收款,请改用 `exact_permit` 方案(由自研 `PaymentPermit` 代理合约封装,兼容任意 ERC-20)。 +- BSC USDT/USDC 是普通 ERC-20(无 ERC-3009),在 `exact` 方案下通过 Permit2 路径结算——客户端首次付款时自动广播一次性 `approve(Permit2)`。ERC-3009 代币(如 BSC 测试网 DHLU)则无 gas 结算,无需 approve。 - 仓库中的 `examples/bsc-testnet-smoke/` 目录提供了双向互通的烟雾测试示例(Coinbase 官方客户端 → BANK OF AI 服务端、BANK OF AI 客户端 → Coinbase 官方服务端),可作为调试与集成参考。 ### 资产、网络及费用 @@ -92,7 +96,7 @@ x402 支持三种支付方案: | BSC testnet (`eip155:97`) | USDC (BEP-20) | **Testnet** | | BSC testnet (`eip155:97`) | DHLU (BEP-20, 用于 `exact` 互通测试) | **Testnet** | -此外,支持通过 TokenRegistry 添加自定义的 TRC-20/BEP-20 代币。 +此外,可通过 TRON 代币注册表(`@bankofai/x402-tron` 的 `registerToken`)添加自定义 TRC-20 代币;自定义 BEP-20 代币则通过在 server 的 `EVM_TOKENS` 配置表中添加条目来公布。 #### 涉及哪些费用? @@ -113,7 +117,7 @@ x402 支持三种支付方案: #### 退款机制如何运作? -`exact_permit` / `exact` 方案属于**推送支付 (Push Payment)**——交易一旦上链执行即不可逆转。处理退款通常有以下两种方式: +`exact` 方案属于**推送支付 (Push Payment)**——一旦在链上结算即不可逆转。而 `batch-settlement` 方案则支持链上**退款**路径,可退回通道中未使用的余额。处理退款通常有以下两种方式: 1. **业务层退款:** 由卖家主动发起一笔新的 USDT 转账,将资金返还给买家。 2. **按实结算(预防性):** 利用支付方案特性,服务端仅结算实际产生的费用,而非全额扣款(从而避免需要退款的情况)。 @@ -137,12 +141,12 @@ x402 支持三种支付方案: #### 如何在本地运行 x402? -1. **克隆仓库:** 下载 [x402-demo 仓库](https://github.com/BofAI/x402-demo) 到本地。 -2. **安装依赖:** 安装项目依赖项(Python 环境请执行 `pip install -r requirements.txt`)。 -3. **配置环境:** 参考 `.env.example` 示例,在 `.env` 文件中配置您的私钥。 -4. **启动 Facilitator:** 运行 `python facilitator/main.py`。 -5. **启动服务端:** 运行 `python server/main.py`。 -6. **运行客户端:** 执行 `python client/main.py` 发起测试请求。 +1. **克隆仓库:** `git clone https://github.com/BofAI/x402.git` +2. **安装并构建:** `cd x402/typescript && pnpm install && pnpm build` +3. **配置环境:** `cd examples/typescript && cp .env-exact.example .env-exact`,填入 `AGENT_WALLET_PRIVATE_KEY` 与收款地址 +4. **启动 Facilitator:** `pnpm dev:facilitator`(终端 1,`:4022`) +5. **启动服务端:** `pnpm dev:server`(终端 2,`:4021`) +6. **运行客户端:** `pnpm dev:client`(终端 3) #### 推荐使用哪个测试网? @@ -179,4 +183,4 @@ BSC 上推荐使用 **BSC Testnet** 进行测试。该网络是 BSC 主网的镜 ### 仍有疑问? • 在 [x402 仓库](https://github.com/BofAI/x402) 中提交 GitHub Issue 反馈问题 -• 参考 [x402-demo](https://github.com/BofAI/x402-demo) 获取完整可运行的示例代码 +• 参考 x402 仓库中的[可运行示例](https://github.com/BofAI/x402/tree/main/examples/typescript)获取完整的 client → server → facilitator 循环 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-agent.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-agent.md index c01f6c3f..5f6fcaa1 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-agent.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-agent.md @@ -128,17 +128,22 @@ npx skills add https://github.com/BofAI/skills 完成配置后,按以下步骤验证代理能够正常自主付款: -### 3.1 使用演示地址测试 +### 3.1 使用本地付费接口测试 -指示您的 AI 代理访问以下演示地址(这是一个需要付款才能访问的测试接口): +从 `examples/typescript` 启动示例三件套,然后将代理指向本地服务器: +```bash +cd x402/examples/typescript +cp .env-exact.example .env-exact # 填入 AGENT_WALLET_PRIVATE_KEY + 收款地址 +pnpm dev:facilitator # 终端 1(:4022) +pnpm dev:server # 终端 2(:4021) ``` -https://x402-demo.bankofai.io/protected-nile -``` + +然后指示您的代理访问 `http://localhost:4021/weather`。 **代理应自动完成以下流程(无需人工干预):** -1. 向演示地址发起 GET 请求 +1. 向该接口发起 GET 请求 2. 收到服务器返回的 HTTP 402(需要付款)响应 3. 读取响应头中的付款要求(金额、网络、收款地址) 4. 使用配置的私钥签名付款授权 @@ -186,7 +191,7 @@ https://x402-demo.bankofai.io/protected-nile | `私钥未找到` 或签名失败 | 环境变量未配置或配置错误 | 重新执行第一步,在**同一终端**中运行代理 | | 余额不足错误 | 测试钱包中没有测试代币 | 回到前置准备,从水龙头领取测试代币 | | 请求超时 | 网络问题或 RPC 限速 | 配置 `TRON_GRID_API_KEY` 以获得更好的性能 | -| 代理访问成功但余额没有变化 | 可能访问的是免费接口 | 确认 URL 是 `/protected-nile` 而非其他路径 | +| 代理访问成功但余额没有变化 | 可能访问的是免费接口 | 确认 URL 是 `/weather`(付费路由)而非其他路径 | --- @@ -200,6 +205,7 @@ https://x402-demo.bankofai.io/protected-nile ## 参考资料 +- [x402 仓库](https://github.com/BofAI/x402) —— SDK 源码与可运行示例(`examples/typescript/`) +- [MCP 示例](https://github.com/BofAI/x402/tree/main/examples/typescript/clients/mcp) —— 通过 MCP 传输的代理付款 - [OpenClaw 扩展库](https://github.com/BofAI/openclaw-extension) - [ClawHub 上的 x402-payment 技能](https://github.com/BofAI/skills/tree/main/x402-payment) -- [x402 演示项目](https://github.com/BofAI/x402-demo) diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md index db877d19..fb98fbbe 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md @@ -1,635 +1,363 @@ -# 人类用户快速入门 - import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; -## 本指南适合谁? +# 用户快速入门 + +## 本指南面向谁? -本指南适合想要通过代码**调用 x402 付费 API** 的开发者。完成后,您将能够用 Python 或 TypeScript 编写脚本,自动完成"付款 → 获取 API 内容"的完整流程,无需手动操作。 +本指南面向希望**通过代码调用 x402 保护的 API 并自动完成付款**的开发者。完成后,您将拥有一个可工作的 TypeScript 脚本:它能检测 402 响应、为访问付费、并获取受保护的内容——全程无需手动操作。 -> **测试优先:** 本指南默认使用测试网,不涉及真实资金。您可以安全地跟着步骤操作,熟悉整个流程后再连接真实钱包。 +> **测试网优先:** 本指南默认使用测试网,您可以安全地完成每一步而不花费真实资金。 + +:::info SDK 1.0.0(仅 TypeScript) +x402 `1.0.0` 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发布。本指南使用 [`x402` 仓库](https://github.com/BofAI/x402) 中的可运行 fetch client(`examples/typescript/clients/fetch`),它链接了仓库内的 SDK 包并从源码运行。 +::: --- ## 前置准备 -### 第一件事:私钥安全 +### 首先:私钥安全 -> 🔴 **私钥安全警告——请务必先读这一节:** +> 🔴 **私钥安全警告——开始前请阅读:** > -> - **私钥** 是控制您钱包的唯一凭证,相当于银行卡的密码+卡号合一,**获取私钥的人即可完全控制您的资产** -> - 本指南需要您配置私钥,请务必遵守以下规则: -> 1. **永远不要**将私钥直接写进代码文件(如 `client.py`) -> 2. **永远不要**将含有私钥的文件提交到 Git 或上传到 GitHub -> 3. **永远不要**通过微信、邮件、聊天记录发送私钥 -> 4. 私钥应只存放在本地的 `.env` 文件或系统环境变量中 -> 5. 测试时,请专门创建一个只含少量测试代币的**测试钱包**,不要使用存有真实资产的钱包 - -### 准备工作清单 +> - 您的**私钥**是控制钱包的唯一凭据。任何拥有它的人都可以完全访问您的资金。 +> - 本指南要求您配置私钥。请严格遵守以下规则: +> 1. **切勿**将私钥直接写在代码文件中 +> 2. **切勿**将含私钥的文件提交到 Git 或推送到 GitHub +> 3. **切勿**通过消息应用、邮件或聊天发送私钥 +> 4. 仅将其保存在本地 `.env` 文件或系统环境变量中 +> 5. 测试时请创建一个**专用测试钱包**,仅持有少量测试代币——切勿使用持有真实资产的钱包 -在开始之前,请确认以下条件: +### 开始前清单 -- [ ] 已安装 **Python 3.11+** 或 **Node.js 20+**(根据您选择的语言) -- [ ] 已创建一个专用**测试钱包**(见下方说明) -- [ ] 已获取测试代币(免费) -- [ ] 知道要访问的 x402 付费 API 地址(或使用我们提供的演示地址) +- [ ] 已安装 **Node.js 20+** 和 **pnpm 11+** +- [ ] 已创建专用**测试钱包**(见下文) +- [ ] 已领取测试代币(免费) +- [ ] 有一个目标 x402 保护的 API URL(或运行示例 server) -### 创建测试钱包并获取测试代币 +### 创建测试钱包并领取测试代币 **创建测试钱包:** -1. 安装 [TronLink 浏览器插件](https://www.tronlink.org/) 或手机 App -2. 点击"创建钱包",设置密码,**将助记词抄写在纸上保管好** -3. 钱包创建后,复制您的地址(以 `T` 开头) +1. 安装 [TronLink 浏览器扩展](https://www.tronlink.org/) 或手机 App +2. 点击"创建钱包",设置密码,并**将助记词抄写在纸上并妥善保管** +3. 创建后,复制您的钱包地址(以 `T` 开头) -**获取测试代币(免费):** +**领取免费测试代币:** 1. 前往 [Nile 测试网水龙头](https://nileex.io/join/getJoinPage) -2. 粘贴您的 TRON 测试钱包地址,领取测试 TRX 和测试 USDT/USDD -3. 在 TronLink 中切换到"Nile 测试网",确认余额到账 +2. 粘贴您的 TRON 测试钱包地址,领取测试 TRX 和 USDT/USDD +3. 在 TronLink 切换到"Nile 测试网"并确认余额 **导出私钥:** -1. 在 TronLink 中进入"设置 → 账户管理 → 导出私钥" +1. 在 TronLink 中,前往 设置 → 账户管理 → 导出私钥 2. 输入密码确认 -3. 复制这串私钥(64位十六进制字符),下一步会用到 +3. 复制 64 位十六进制字符串——下一步将用到 -> ✅ **成功标志:** 拥有 TRON 测试钱包地址和对应私钥,钱包中有测试 TRX 和 USDT(或 USDD) +> ✅ **成功检查:** 您拥有 TRON 测试钱包地址、其私钥,以及测试 TRX 和 USDT(或 USDD)余额 **创建测试钱包:** -1. 安装 [MetaMask 浏览器插件](https://metamask.io/) -2. 点击"创建新钱包",设置密码,**将助记词抄写在纸上保管好** -3. 复制您的钱包地址(以 `0x` 开头) +1. 安装 [MetaMask 浏览器扩展](https://metamask.io/) +2. 点击"创建新钱包",设置密码,并**将助记词抄写在纸上并妥善保管** +3. 创建后,复制您的钱包地址(以 `0x` 开头) -**获取测试代币(免费):** +**领取免费测试代币:** 1. 前往 [BSC 测试网水龙头](https://www.bnbchain.org/en/testnet-faucet) -2. 粘贴 BSC 测试钱包地址,领取测试 BNB 和测试 USDT -3. 在 MetaMask 中切换到 BSC 测试网,确认余额到账 +2. 粘贴您的 BSC 测试钱包地址,领取测试 BNB 和 USDT +3. 在 MetaMask 切换到 BSC 测试网并确认余额 **导出私钥:** -1. 在 MetaMask 中点击账户图标 → "账户详情" → "导出私钥" +1. 在 MetaMask 中,点击 账户详情 → 导出私钥 2. 输入 MetaMask 密码确认 -3. 复制这串私钥(64位十六进制字符),下一步会用到 +3. 复制 64 位十六进制字符串——下一步将用到 -> ✅ **成功标志:** 拥有 BSC 测试钱包地址和对应私钥,钱包中有测试 BNB 和 USDT +> ✅ **成功检查:** 您拥有 BSC 测试钱包地址、其私钥,以及测试 BNB 和 USDT 余额 --- -## 第一步:安装 SDK - -根据您使用的编程语言,选择对应的安装方式: - - - - -打开终端,执行以下命令安装 x402 Python SDK: - -```bash -pip install "bankofai-x402[tron] @ git+https://github.com/BofAI/x402.git#subdirectory=python/x402" -``` - -再安装 EVM(BSC)所需的额外依赖: - -```bash -pip install eth_account web3 -``` - -验证安装: - -```bash -python -c "import bankofai.x402; print('安装成功!')" -``` - -> ✅ **成功标志:** 终端输出 `安装成功!` +## 第一步:获取 SDK 与示例 -如遇安装问题,也可从源码安装: +示例工作区链接了仓库内的 `@bankofai/x402-*` 包并从源码运行: ```bash git clone https://github.com/BofAI/x402.git -cd x402/python/x402 -pip install -e . -``` - - - +cd x402/typescript # pnpm/turbo monorepo 根目录 -打开终端,在您的项目目录下执行: - -```bash -npm install @bankofai/x402 tronweb dotenv -``` +# 安装并链接所有工作区包(SDK + 示例) +pnpm install -由于 `@bankofai/x402` 是 ESM 模块,请在您的 `package.json` 中添加以下字段(如果没有则添加): +# 构建示例所依赖的 @bankofai/x402-* dist +pnpm build -```json -{ - "type": "module" -} +cd examples/typescript ``` -> 💡 如果在使用 `npx tsx` 运行时遇到 `ERR_PACKAGE_PATH_NOT_EXPORTED` 错误,通常是因为缺少这个 `"type": "module"` 配置。 - -> ✅ **成功标志:** `npm install` 执行完毕,`node_modules` 目录中出现 `@bankofai` 文件夹 - - - - ---- +fetch client 依赖 `@bankofai/x402-fetch`、`@bankofai/x402-evm`、`@bankofai/x402-tron` 和 `@bankofai/agent-wallet`——全部由 `pnpm install` 自动链接。 :::info 钱包管理 -x402 SDK 通过 [Agent Wallet](../../Agent-Wallet/QuickStart.md) 来解析和管理钱包凭证,安装 x402 时会自动安装 agent-wallet 作为依赖。私钥解析优先级为: +x402 使用 [Agent Wallet](../../Agent-Wallet/QuickStart.md) 解析和管理钱包凭据。Agent Wallet 作为示例的依赖自动安装。私钥解析优先级: 1. 加密钱包文件(通过 Agent Wallet CLI 导入) 2. 环境变量 `AGENT_WALLET_PRIVATE_KEY` -本文使用环境变量方式。 +本指南使用环境变量方式。 ::: +--- + ## 第二步:配置私钥 -**不要将私钥写进代码!** 请将私钥存储为环境变量,这样代码从环境中读取,私钥不会出现在代码文件里。将 `your_private_key_here` 替换为前置准备中导出的私钥。 +**切勿将私钥写在代码中。** 将其存为环境变量以使其远离源文件。复制环境模板并填入您的密钥: ```bash -export AGENT_WALLET_PRIVATE_KEY=your_private_key_here +cp .env-exact.example .env-exact ``` -> 💡 **提示:** 如需在每次打开终端时自动生效,可将其写入 shell 配置文件: -> ```bash -> echo 'export AGENT_WALLET_PRIVATE_KEY=你的私钥' >> ~/.zshrc # zsh(macOS 默认) -> echo 'export AGENT_WALLET_PRIVATE_KEY=你的私钥' >> ~/.bashrc # bash(Linux 默认) -> source ~/.zshrc # 或 source ~/.bashrc — 无需重启终端即可立即生效 -> ``` - -验证环境变量已生效: +打开 `.env-exact` 并设置付款方变量: ```bash -echo $AGENT_WALLET_PRIVATE_KEY +# ── SHARED · client(您是付款方)───────────────────────────────────────── +AGENT_WALLET_PRIVATE_KEY=your_private_key_here + +# TronGrid API key —— 测试网上可选,生产 TRON 建议。 +TRON_GRID_API_KEY= + +# ── CLIENT · 支付哪些链/代币 ───────────────────────────────────────────── +# [@] 例如 tron:nile@USDT 或 eip155:97@DHLU +PAY_TARGETS=tron:nile@USDT + +# 您要调用的 x402 保护 API。 +RESOURCE_URL=http://localhost:4021/weather ``` -> ✅ **成功标志:** 终端输出您的私钥字符串(不是空白) +> 💡 **提示:** `PAY_TARGETS` 控制 client 用哪个链/代币支付,每条目支付一次,按顺序执行。省略代币则使用该网络的第一个公布代币。请使用 `@`(而非 `#`)——dotenv 会把 `#` 当作注释。 -**可选:** 生产环境的 TRON 项目建议配置 TronGrid API Key 以获得更稳定的 RPC 服务: +**可选:** 生产 TRON 负载请配置 TronGrid API Key 以获得更可靠的 RPC: ```bash -export TRON_GRID_API_KEY="your_trongrid_api_key_here" +TRON_GRID_API_KEY="your_trongrid_api_key_here" ``` -> 💡 **如何获取 TronGrid API Key:** 前往 [TronGrid 官网](https://www.trongrid.io/) 免费注册,创建 API Key 后粘贴到上方。 - :::note -未配置 `TRON_GRID_API_KEY` 时,在高负载下可能会被限速。生产环境请配置 `TRON_GRID_API_KEY`,以确保可靠性。 +未设置 `TRON_GRID_API_KEY` 时,高负载下请求可能被速率限制。生产环境请设置自己的 `TRON_GRID_API_KEY` 以确保可靠性。 ::: -BSC 无需额外配置。 +BSC 测试网默认的 viem RPC 端点经常不可达。请设置可靠的 RPC: + +```bash +EVM_RPC_URL=https://bsc-testnet-rpc.publicnode.com +``` +> ⚠️ **安全提醒:** 私钥仅保存在 `.env-exact`(已被 gitignore)或环境变量中。**切勿将含私钥的文件提交到 Git 或分享给任何人。** + --- -## 第三步:编写并运行调用代码 +## 第三步:编写并运行客户端代码 -新建一个文件(如 `client.py` 或 `client.ts`),复制对应的代码: +示例 fetch client 包装 `fetch`,使 HTTP `402 Payment Required` 挑战自动支付。以下是入口(`examples/typescript/clients/fetch/src/index.ts`),节选至要点: - - - - - -```python -import asyncio -import httpx - -from bankofai.x402.clients import X402Client, X402HttpClient, SufficientBalancePolicy -from bankofai.x402.mechanisms.tron.exact_permit import ExactPermitTronClientMechanism -from bankofai.x402.mechanisms.tron.exact_gasfree.client import ExactGasFreeClientMechanism -from bankofai.x402.signers.client import TronClientSigner -from bankofai.x402.utils.gasfree import GasFreeAPIClient -from bankofai.x402.config import NetworkConfig - - -# ========== 配置项 ========== -# 您要访问的 x402 付费 API 地址 -# 下方是我们提供的测试地址,您可以先用它验证流程是否通畅 -SERVER_URL = "https://x402-demo.bankofai.io/protected-nile" -# =========================== - -# GasFree API 客户端(通过 BANK OF AI 代理路由,无需 API 密钥) -gasfree_clients = { - "tron:nile": GasFreeAPIClient(NetworkConfig.get_gasfree_api_base_url("tron:nile")), - "tron:mainnet": GasFreeAPIClient(NetworkConfig.get_gasfree_api_base_url("tron:mainnet")), +```typescript +import { x402Client, wrapFetchWithPayment } from "@bankofai/x402-fetch"; + +import { registerEvm } from "./chains/evm.js"; +import { registerTron } from "./chains/tron.js"; + +const RESOURCE_URL = process.env.RESOURCE_URL || "http://localhost:4021/weather"; + +// selector 是付款选择策略:选择要支付哪个公布的选项。 +// 完整示例中由 PAY_TARGETS 驱动;此处我们接受第一个选项。 +let target: { prefix: string; asset?: string } | null = null; +const client = new x402Client((_x402Version, accepts) => { + const t = target; + if (!t) return accepts[0]!; + const match = accepts.find( + (a) => + a.network.startsWith(t.prefix) && + (!t.asset || a.asset.toLowerCase() === t.asset.toLowerCase()), + ); + if (!match) throw new Error(`server offered no payment option matching "${t.prefix}"`); + return match; +}); + +// 仅当钱包解析成功时才注册该链(可仅 EVM、仅 TRON,或两者)。 +const evm = await registerEvm(client); +const tron = await registerTron(client); + +const fetchWithPay = wrapFetchWithPayment(fetch, client); + +// 每个目标支付一次,按顺序。 +const targets = [{ prefix: "tron:", asset: undefined }]; // 简化版 +for (const t of targets) { + target = t; + console.log(`\n→ GET ${RESOURCE_URL}`); + const res = await fetchWithPay(RESOURCE_URL); + console.log(`← ${res.status} ${res.statusText}`); + console.log(JSON.stringify(await res.json(), null, 2)); } - - -async def main(): - # 通过 agent-wallet 初始化签名器(自动从环境变量解析钱包) - signer = await TronClientSigner.create() - - # 创建 x402 客户端,注册付款机制和余额检查策略 - x402_client = X402Client() - x402_client.register("tron:*", ExactPermitTronClientMechanism(signer)) - x402_client.register("tron:*", ExactGasFreeClientMechanism(signer, clients=gasfree_clients)) - x402_client.register_policy(SufficientBalancePolicy) - - async with httpx.AsyncClient(timeout=120) as http_client: - client = X402HttpClient(http_client, x402_client) - - # 发起请求——SDK 会自动处理付款,您无需手动操作 - response = await client.get(SERVER_URL) - - print(f"状态码: {response.status_code}") - print("响应内容:", response.text) - - -asyncio.run(main()) ``` -**运行代码:** +### 各链如何注册 -```bash -python client.py -``` +每条链位于 `src/chains/` 下各自的模块中。仅当该链的 agent-wallet 解析成功时才注册——因此您可以仅从 EVM、仅从 TRON,或两者支付。 -**预期输出:** + + -``` -状态码: 200 -响应内容: {"data": "这是需要付款才能获取的内容!"} +```typescript +// src/chains/tron.ts +import { createClientTronSigner } from "@bankofai/x402-tron"; +import { ExactTronScheme } from "@bankofai/x402-tron/exact/client"; +import type { x402Client } from "@bankofai/x402-fetch"; +import { tryResolveWallet } from "../env.js"; + +export async function registerTron(client: x402Client): Promise { + const wallet = await tryResolveWallet("tron"); + if (!wallet) return false; + + for (const network of ["tron:nile", "tron:mainnet"] as const) { + // 工厂内部构建 TronWeb,并自动广播 USDT/USDD 首次付款前 + // 需要的一次性 Permit2 approve。 + const signer = await createClientTronSigner(wallet, { + network, + apiKey: process.env.TRON_GRID_API_KEY, + }); + client.register(network, new ExactTronScheme(signer)); + } + return true; +} ``` - + ```typescript -import 'dotenv/config' -import { - X402Client, X402FetchClient, - ExactPermitTronClientMechanism, ExactGasFreeClientMechanism, - TronClientSigner, SufficientBalancePolicy, - GasFreeAPIClient, getGasFreeApiBaseUrl, -} from '@bankofai/x402' - -// ========== 配置项 ========== -// 您要访问的 x402 付费 API 地址 -// 下方是我们提供的测试地址,您可以先用它验证流程是否通畅 -const SERVER_URL = 'https://x402-demo.bankofai.io/protected-nile' -// =========================== - -async function main(): Promise { - // 通过 agent-wallet 初始化签名器(自动从环境变量解析钱包) - const signer = await TronClientSigner.create() - - // 创建 x402 客户端,注册付款机制和余额检查策略 - const x402 = new X402Client() - x402.register('tron:*', new ExactPermitTronClientMechanism(signer)) - x402.register('tron:*', new ExactGasFreeClientMechanism(signer, { - 'tron:nile': new GasFreeAPIClient(getGasFreeApiBaseUrl('tron:nile')), - 'tron:mainnet': new GasFreeAPIClient(getGasFreeApiBaseUrl('tron:mainnet')), - })) - x402.registerPolicy(SufficientBalancePolicy) - - const client = new X402FetchClient(x402) - - // 发起请求——SDK 会自动处理付款,您无需手动操作 - const response = await client.get(SERVER_URL) - - console.log(`状态码: ${response.status}`) - - // 解析付款回执(可选) - const paymentResponse = response.headers.get('payment-response') - if (paymentResponse) { - const jsonString = Buffer.from(paymentResponse, 'base64').toString('utf8') - const settleResponse = JSON.parse(jsonString) - console.log(`交易哈希: ${settleResponse.transaction}`) - } - - // 打印响应内容 - const contentType = response.headers.get('content-type') ?? '' - if (contentType.includes('application/json')) { - const body = await response.json() - console.log('响应内容:', body) +// src/chains/evm.ts +import { createClientEvmSigner } from "@bankofai/x402-evm/adapters/agent-wallet"; +import { ExactEvmScheme } from "@bankofai/x402-evm/exact/client"; +import type { x402Client } from "@bankofai/x402-fetch"; +import { tryResolveWallet } from "../env.js"; + +export async function registerEvm(client: x402Client): Promise { + const wallet = await tryResolveWallet("evm"); + if (!wallet) return false; + + for (const network of ["eip155:97", "eip155:56"] as const) { + // 工厂内部构建 viem client;ERC-3009 代币(如 DHLU) + // 离线签名,无需 RPC;permit2 代币则读取链。 + const signer = await createClientEvmSigner(wallet, { + network, + rpcUrl: process.env.EVM_RPC_URL?.trim() || undefined, + }); + client.register(network, new ExactEvmScheme(signer)); } + return true; } - -main().catch(console.error) -``` - -**运行代码:** - -```bash -npx tsx client.ts -``` - -**预期输出:** - -``` -状态码: 200 -交易哈希: abc123... -响应内容: { data: '这是需要付款才能获取的内容!' } ``` - - - - - -```python -import asyncio -import httpx - -from bankofai.x402.clients import X402Client, X402HttpClient, SufficientBalancePolicy -from bankofai.x402.mechanisms.evm.exact_permit import ExactPermitEvmClientMechanism -from bankofai.x402.mechanisms.evm.exact import ExactEvmClientMechanism -from bankofai.x402.signers.client import EvmClientSigner - - -# ========== 配置项 ========== -# 您要访问的 x402 付费 API 地址 -SERVER_URL = "https://x402-demo.bankofai.io/protected-bsc-testnet" -# =========================== - - -async def main(): - # 通过 agent-wallet 初始化签名器(自动从环境变量解析钱包) - signer = await EvmClientSigner.create() - - # 创建 x402 客户端,注册付款机制和余额检查策略 - x402_client = X402Client() - x402_client.register("eip155:*", ExactPermitEvmClientMechanism(signer)) - x402_client.register("eip155:*", ExactEvmClientMechanism(signer)) - x402_client.register_policy(SufficientBalancePolicy) - - async with httpx.AsyncClient(timeout=120) as http_client: - client = X402HttpClient(http_client, x402_client) - - # 发起请求——SDK 会自动处理付款,您无需手动操作 - response = await client.get(SERVER_URL) - print(f"状态码: {response.status_code}") - print("响应内容:", response.text) +### 运行 client - -asyncio.run(main()) -``` - -**运行代码:** +首先确保资源服务器 + facilitator 正在运行(参见[卖家快速入门](./quickstart-for-sellers.md)),然后从 `examples/typescript` 运行: ```bash -python client.py +pnpm dev:client ``` **预期输出:** ``` -状态码: 200 -响应内容: {"data": "这是需要付款才能获取的内容!"} -``` - - - - -```typescript -import 'dotenv/config' -import { - X402Client, X402FetchClient, - ExactPermitEvmClientMechanism, ExactEvmClientMechanism, - EvmClientSigner, SufficientBalancePolicy, -} from '@bankofai/x402' - -// ========== 配置项 ========== -// 您要访问的 x402 付费 API 地址 -const SERVER_URL = 'https://x402-demo.bankofai.io/protected-bsc-testnet' -// =========================== - -async function main(): Promise { - // 通过 agent-wallet 初始化签名器(自动从环境变量解析钱包) - const signer = await EvmClientSigner.create() - - // 创建 x402 客户端,注册付款机制和余额检查策略 - const x402 = new X402Client() - x402.register('eip155:*', new ExactPermitEvmClientMechanism(signer)) - x402.register('eip155:*', new ExactEvmClientMechanism(signer)) - x402.registerPolicy(SufficientBalancePolicy) - - const client = new X402FetchClient(x402) - - // 发起请求——SDK 会自动处理付款,您无需手动操作 - const response = await client.get(SERVER_URL) - - console.log(`状态码: ${response.status}`) - - // 解析付款回执(可选) - const paymentResponse = response.headers.get('payment-response') - if (paymentResponse) { - const jsonString = Buffer.from(paymentResponse, 'base64').toString('utf8') - const settleResponse = JSON.parse(jsonString) - console.log(`交易哈希: ${settleResponse.transaction}`) - } - - // 打印响应内容 - const contentType = response.headers.get('content-type') ?? '' - if (contentType.includes('application/json')) { - const body = await response.json() - console.log('响应内容:', body) - } -} - -main().catch(console.error) -``` - -**运行代码:** - -```bash -npx tsx client.ts +→ [tron:nile@USDT] GET http://localhost:4021/weather +← 200 OK +{ "report": { "weather": "sunny", "temperature": 70 } } ``` -**预期输出:** +> ✅ **成功:** SDK 检测到 `402`,签署付款,在链上结算,并返回了受保护的内容。 -``` -状态码: 200 -交易哈希: abc123... -响应内容: { data: '这是需要付款才能获取的内容!' } -``` - - - - - +> 💡 要改为支付 BSC 代币,设置 `PAY_TARGETS=eip155:97@DHLU`(ERC-3009,无 gas)或 `eip155:97@USDC`(permit2,一次性 `approve`)。 --- ## 第四步:错误排查 -运行代码时如果出现报错,参考以下常见原因和解决方法: - -| 错误信息 | 原因 | 解决方法 | -|----------|------|----------| -| `环境变量未设置` 或 `None` | 私钥环境变量没有正确设置 | 重新执行第二步的 `export` 命令,注意是在**同一个终端窗口**中运行 | -| `WalletNotFoundError: No active wallet set` | agent-wallet 未配置钱包 | 运行 `agent-wallet start`,按提示导入您的私钥 | -| `Insufficient balance` / 余额不足 | 测试钱包里没有足够的测试 USDT/USDD | 回到前置准备,从水龙头重新领取测试代币 | -| `UnsupportedNetworkError` | 代码中注册的网络与服务器不匹配 | 确认 `SERVER_URL` 对应的网络与您注册的 mechanism 一致(TRON 对应 `tron:*`,BSC 对应 `eip155:*`) | -| `InsufficientAllowanceError` | 代币授权额度不足 | SDK 通常会自动处理授权,如持续出现请检查钱包余额 | -| `Connection timeout` | 网络请求超时 | 检查网络连接,或将代码中的 `timeout=60.0` 改为更大的值 | -| `ModuleNotFoundError` | SDK 未正确安装 | 重新执行第一步的安装命令 | - - - - - - - -```python -from bankofai.x402.exceptions import ( - X402Error, - InsufficientAllowanceError, - SignatureCreationError, - UnsupportedNetworkError, -) - -try: - response = await client.get(SERVER_URL) - print(f"状态码: {response.status_code}") - print("响应内容:", response.text) - -except UnsupportedNetworkError as e: - print(f"网络不支持(请检查是否注册了正确的 mechanism): {e}") - -except InsufficientAllowanceError as e: - print(f"代币授权额度不足(请检查钱包余额): {e}") - -except SignatureCreationError as e: - print(f"签名失败(请检查私钥是否正确): {e}") - -except X402Error as e: - print(f"付款出错: {e}") -``` - - - - -```typescript -try { - const response = await client.get(SERVER_URL) - if (response.status === 200) { - console.log('成功:', await response.json()) - } else { - console.error(`请求失败,状态码: ${response.status}`) - console.error(await response.text()) - } -} catch (error) { - if (error.message.includes('No mechanism registered')) { - console.error('网络不支持——请检查是否注册了正确的 mechanism') - } else if (error.message.includes('allowance')) { - console.error('代币授权额度不足——请检查钱包余额') - } else { - console.error('付款出错:', error.message) - } -} -``` - - - - - - - - -```python -from bankofai.x402.exceptions import ( - X402Error, - InsufficientAllowanceError, - SignatureCreationError, - UnsupportedNetworkError, -) - -try: - response = await client.get(SERVER_URL) - print(f"状态码: {response.status_code}") - print("响应内容:", response.text) - -except UnsupportedNetworkError as e: - print(f"网络不支持(请检查是否注册了正确的 mechanism): {e}") - -except InsufficientAllowanceError as e: - print(f"代币授权额度不足(请检查钱包余额): {e}") +| 问题 | 原因 | 解决方案 | +|---------|-------|----------| +| `No wallet configured for EVM or TRON` | 未设置或为空 `AGENT_WALLET_PRIVATE_KEY` | 在 `.env-exact` 中设置并重新运行;确保在**运行脚本的同一终端窗口**中执行 export | +| `WalletNotFoundError: No active wallet set` | agent-wallet 未配置钱包 | 运行 `agent-wallet start` 并按提示导入私钥 | +| `Insufficient balance` / 余额错误 | 测试钱包 USDT/USDD 不足 | 返回前置准备,从水龙头领取测试代币 | +| `server offered no payment option matching "…"` | `PAY_TARGETS` 与 server 公布的不匹配 | 检查 server 的 `accepts`(网络 + 代币)并对齐 `PAY_TARGETS`,如 `tron:nile@USDT` 或 `eip155:97@DHLU` | +| `InsufficientAllowanceError` / 授权错误 | 代币授权额度过低 | SDK 在首次付款时自动广播一次性 Permit2 `approve`;若仍存在,检查钱包余额 | +| `Connection timeout` | 网络或请求超时 | 检查连接;BSC 请设置可靠的 `EVM_RPC_URL=https://bsc-testnet-rpc.publicnode.com` | +| `ERR_PACKAGE_PATH_NOT_EXPORTED` | 项目未声明为 ESM | 在 `package.json` 中添加 `"type": "module"` | -except SignatureCreationError as e: - print(f"签名失败(请检查私钥是否正确): {e}") - -except X402Error as e: - print(f"付款出错: {e}") -``` - - - +如需更细粒度的错误处理: ```typescript try { - const response = await client.get(SERVER_URL) - if (response.status === 200) { - console.log('成功:', await response.json()) + const res = await fetchWithPay(RESOURCE_URL); + if (res.status === 200) { + console.log("Success:", await res.json()); } else { - console.error(`请求失败,状态码: ${response.status}`) - console.error(await response.text()) + console.error(`Request failed: ${res.status}`); + console.error(await res.text()); } } catch (error) { - if (error.message.includes('No mechanism registered')) { - console.error('网络不支持——请检查是否注册了正确的 mechanism') - } else if (error.message.includes('allowance')) { - console.error('代币授权额度不足——请检查钱包余额') + if (error instanceof Error && error.message.includes("no payment option")) { + console.error("No matching payment option — check PAY_TARGETS vs the server's accepts"); + } else if (error instanceof Error && error.message.includes("allowance")) { + console.error("Insufficient token allowance — check wallet balance"); } else { - console.error('付款出错:', error.message) + console.error("Payment error:", error); } } ``` - - - - - --- -## 总结 +## 完成总结 -通过本指南,您完成了以下步骤: +通过本指南,您: -- **创建测试钱包** 并领取了测试代币,理解了私钥安全的重要性 -- **安装 SDK** 并配置了私钥环境变量(而非写入代码) -- **编写并运行**了自动付款的客户端代码 -- **理解了整个付款流程**:SDK 自动检测 402 响应 → 自动签名 → 自动付款 → 获取内容 +- **创建了测试钱包**并领取了测试代币,理解了私钥安全的重要性 +- **安装了 SDK** 并将私钥配置为环境变量(而非写在代码中) +- **编写并运行了**自动付款客户端代码 +- **理解了完整流程**:SDK 检测 402 → 签署授权 → 付款 → 获取内容 --- ## 下一步 - 阅读[核心概念](../core-concepts/http-402.md)深入了解 x402 协议 -- 查看[网络支持](../core-concepts/network-and-token-support.md)了解支持的代币和网络 -- 想搭建自己的付费 API?参见[卖家快速入门](./quickstart-for-sellers.md) +- 查看[网络与代币支持](../core-concepts/network-and-token-support.md)了解支持的代币与网络 +- 想构建自己的付费 API?参见[卖家快速入门](./quickstart-for-sellers.md) --- ## 参考资料 -- [npm 包](https://www.npmjs.com/package/@bankofai/x402) — x402 TypeScript SDK -- [Python SDK 源码](https://github.com/BofAI/x402/tree/main/python/x402) — x402 Python SDK(从 GitHub 安装) -- [示例代码仓库](https://github.com/BofAI/x402-demo) — 完整集成演示 +- [x402 仓库](https://github.com/BofAI/x402) —— SDK 源码与可运行示例(`examples/typescript/`) +- [fetch client 示例](https://github.com/BofAI/x402/tree/main/examples/typescript/clients/fetch) —— 本指南所基于的 client +- [Agent Wallet](https://github.com/BofAI/agent-wallet) —— SDK 使用的密钥托管 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-sellers.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-sellers.md index d7b9c122..392d7ffc 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-sellers.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-sellers.md @@ -3,17 +3,21 @@ import TabItem from '@theme/TabItem'; # 卖家快速入门 -> **测试网优先:** 本指南默认使用测试网,所有操作均使用免费测试代币,**不会涉及任何真实资金**。待测试通过后,再参考文末的[切换到主网](#在主网运行)章节进行上线。 +> **测试网优先:** 本指南默认使用测试网,所有操作均使用免费的测试代币——**不涉及真实资金**。测试完成后,请参考本指南末尾的[切换到主网](#在主网运行)部分。 ## 您将实现什么 -完成本指南后,您将拥有一个**可对 API 调用收费的服务**: +完成本指南后,您将拥有一个**对 API 调用收费的服务**: -- 当用户或 AI 代理调用您的 API 时,系统自动要求对方支付指定代币 -- 支持按请求收费、计量使用、动态定价等多种收费模式 -- 付款验证和区块链结算全程自动完成,收款直接到您的钱包 +- 当用户或 AI 代理调用您的 API 时,系统自动要求支付指定代币 +- 支持按次计费、按量计费、动态定价等 +- 付款验证与链上结算全自动完成——资金直接进入您的钱包 -整个流程分为 **4 步**,预计耗时 **15–20 分钟**。 +整个流程共 **4 步**,预计耗时 **15–20 分钟**。 + +:::info SDK 1.0.0(仅 TypeScript) +x402 `1.0.0` 是一个**仅 TypeScript** 的 pnpm/turbo monorepo,以颗粒化的 `@bankofai/x402-*` 包发布。此前的 Python SDK 已移至 `legacy/` 仅供参考。本指南使用 [`x402` 仓库](https://github.com/BofAI/x402) 中的可运行示例(`examples/typescript/`),这些示例链接了仓库内的 SDK 包并从源码运行。 +::: --- @@ -21,72 +25,72 @@ import TabItem from '@theme/TabItem'; ### 确认运行环境 -请在终端(macOS/Linux 的 Terminal,或 Windows 的 PowerShell/命令提示符)中依次运行以下命令,确认相关工具已安装: +在终端(macOS/Linux 的 Terminal,或 Windows 的 PowerShell/命令提示符)中运行以下命令,确认所需工具已安装: ```bash -python --version # 需要 3.11 或以上版本 -pip --version # 随 Python 一起安装 -git --version # 版本控制工具 +node --version # 需要 Node.js 20 或更高版本 +pnpm --version # 需要 pnpm 11 或更高版本 +git --version # 版本控制工具 ``` -如果任何一个命令提示"找不到命令",请先安装: -- Python:前往 [python.org](https://www.python.org/downloads/) 下载安装包 +如果提示"command not found",请先安装: +- Node.js:前往 [nodejs.org](https://nodejs.org/zh-cn/download) 下载安装程序(包含 `npm`) +- pnpm:安装 Node.js 后运行 `npm install -g pnpm` - Git:前往 [git-scm.com](https://git-scm.com/) 下载 --- ### 创建收款钱包 -您需要一个区块链钱包地址,用于接收用户支付的代币。请根据您选择的网络按照以下步骤操作: - +您需要一个区块链钱包地址来接收用户的代币。根据所选网络,按以下步骤操作: **创建 TronLink 钱包(约 3 分钟):** -1. 在浏览器中安装 [TronLink 插件](https://www.tronlink.org/)(支持 Chrome/Firefox),或在手机上下载 TronLink App -2. 打开插件,点击"创建钱包" -3. 设置登录密码(用于解锁钱包,只存在本地) -4. **重要:** 系统会显示一串助记词(12个英文单词)——将它们**抄写在纸上**并妥善保管,这是找回钱包的唯一方式 -5. 按提示验证助记词后,钱包创建完成 -6. 在首页复制您的钱包地址(以字母 **`T`** 开头,如 `TXyz1234...`) +1. 在浏览器中安装 [TronLink 扩展](https://www.tronlink.org/)(支持 Chrome/Firefox),或在手机上下载 TronLink App +2. 打开扩展,点击"创建钱包" +3. 设置登录密码(用于解锁钱包,仅本地存储) +4. **重要:** 系统会显示一组助记词(12 个英文单词)——**请抄写在纸上并妥善保管**;这是恢复钱包的唯一方式 +5. 按提示验证助记词,完成钱包创建 +6. 在主界面复制您的钱包地址(以字母 **`T`** 开头,例如 `TXyz1234...`) **领取免费测试代币(约 2 分钟):** 1. 前往 [Nile 测试网水龙头](https://nileex.io/join/getJoinPage) -2. 将您的 TRON 钱包地址粘贴到输入框 +2. 在输入框粘贴您的 TRON 钱包地址 3. 点击领取,等待约 1–2 分钟 -4. 在 TronLink 中切换到"Nile 测试网",刷新后确认 TRX 和 USDT/USDD 余额已到账 +4. 在 TronLink 切换到"Nile 测试网",刷新并确认 TRX 和 USDT/USDD 余额已到账 -> ✅ **成功标志:** 钱包显示测试 TRX 和测试 USDT(或 USDD)余额大于 0 +> ✅ **成功:** 钱包显示测试 TRX 和测试 USDT(或 USDD)余额大于 0 **创建 MetaMask 钱包(约 3 分钟):** -1. 在浏览器中安装 [MetaMask 插件](https://metamask.io/)(支持 Chrome/Firefox/Edge) -2. 打开插件,点击"创建新钱包" -3. 设置密码,然后**将助记词(12个英文单词)抄写到纸上保管好** +1. 在浏览器中安装 [MetaMask 扩展](https://metamask.io/)(支持 Chrome/Firefox/Edge) +2. 打开扩展,点击"创建新钱包" +3. 设置密码,然后**将助记词(12 个英文单词)抄写在纸上并妥善保管** 4. 按提示验证助记词,完成创建 -5. 在首页复制您的钱包地址(以 **`0x`** 开头,如 `0xAbc123...`) +5. 在主界面复制您的钱包地址(以 **`0x`** 开头,例如 `0xAbc123...`) **领取免费测试代币(约 2 分钟):** 1. 前往 [BSC 测试网水龙头](https://www.bnbchain.org/en/testnet-faucet) 2. 粘贴您的钱包地址,领取测试 BNB 和测试 USDT -3. 在 MetaMask 中切换到 BSC 测试网,确认余额到账 +3. 在 MetaMask 切换到 BSC 测试网并确认余额已到账 -> ✅ **成功标志:** 钱包显示测试 BNB 和测试 USDT 余额大于 0 +> ✅ **成功:** 钱包显示测试 BNB 和测试 USDT 余额大于 0 -> ⚠️ **钱包安全提示:** -> - 助记词和私钥是您钱包的"万能钥匙",**任何人(包括平台客服)都不应该要求您提供** -> - 请将助记词抄在纸上,存放在安全的物理位置,不要存在手机相册或云盘 -> - 本教程使用测试钱包,建议专门创建一个新钱包用于测试,不要使用存有真实资产的钱包 +> ⚠️ **钱包安全提醒:** +> - 助记词和私钥是您钱包的"总钥匙"——**任何人(包括平台客服)都不应向您索要** +> - 将助记词抄写在纸上,存放在安全的物理位置——不要保存在手机相册或云存储中 +> - 本教程使用测试钱包;建议创建一个专用的新钱包用于测试,不要使用持有真实资产的钱包 --- @@ -94,686 +98,448 @@ git --version # 版本控制工具 | 配置项 | 说明 | 获取方式 | |--------|------|----------| -| **TRON 收款地址** | 以 `T` 开头的钱包地址 | 从 TronLink 复制 | -| **BSC 收款地址** | 以 `0x` 开头的钱包地址 | 从 MetaMask 复制 | -| **测试 TRX** | TRON 测试网手续费代币 | [Nile 水龙头](https://nileex.io/join/getJoinPage) | -| **测试 USDT/USDD(TRON)** | TRON 测试付款代币(USDT 和 USDD 均支持) | [Nile 水龙头](https://nileex.io/join/getJoinPage) | -| **测试 BNB** | BSC 测试网手续费代币 | [BSC Testnet 水龙头](https://www.bnbchain.org/en/testnet-faucet) | -| **测试 USDT(BSC)** | BSC 测试付款代币 | [BSC Testnet 水龙头](https://www.bnbchain.org/en/testnet-faucet) | +| **TRON 钱包地址** | 以 `T` 开头的钱包地址(您的收款地址) | 从 TronLink 复制 | +| **BSC 钱包地址** | 以 `0x` 开头的钱包地址(您的收款地址) | 从 MetaMask 复制 | +| **测试 TRX** | TRON 测试网费率代币 | [Nile 水龙头](https://nileex.io/join/getJoinPage) | +| **测试 USDT/USDD(TRON)** | TRON 测试支付代币(USDT 和 USDD 均支持) | [Nile 水龙头](https://nileex.io/join/getJoinPage) | +| **测试 BNB** | BSC 测试网费率代币 | [BSC 测试网水龙头](https://www.bnbchain.org/en/testnet-faucet) | +| **测试 USDT(BSC)** | BSC 测试支付代币 | [BSC 测试网水龙头](https://www.bnbchain.org/en/testnet-faucet) | -**测试网 vs. 主网的区别:** +**测试网 vs. 主网:** -- **测试网**:使用免费的测试代币,不涉及真实资金,适合开发和调试。网络标识符:`tron:nile` / `eip155:97` -- **主网**:涉及真实支付,正式上线时使用。网络标识符:`tron:mainnet` / `eip155:56` +- **测试网**:使用免费测试代币,不涉及真实资金,适合开发调试。网络标识:`tron:nile` / `eip155:97` +- **主网**:涉及真实支付,上线时使用。网络标识:`tron:mainnet` / `eip155:56` --- -## 第一步:安装 x402 SDK - -打开终端,执行以下安装命令: +## 第一步:获取 SDK 与示例 -**推荐方式(直接从 GitHub 安装,适合快速上手):** +示例工作区链接了仓库内的 `@bankofai/x402-*` 包并从源码构建,无需发布到 npm 仓库即可获得最新 SDK: ```bash -pip install "bankofai-x402[tron,fastapi] @ git+https://github.com/BofAI/x402.git#subdirectory=python/x402" +git clone https://github.com/BofAI/x402.git +cd x402/typescript # pnpm/turbo monorepo 根目录 + +# 安装并链接所有工作区包(SDK + 示例) +pnpm install + +# 构建示例所依赖的 @bankofai/x402-* dist +pnpm build + +cd examples/typescript ``` -安装完成后,运行以下命令验证是否成功: +通过启动示例资源服务器来验证安装(它会打印端口和所接受的链): ```bash -python -c "import bankofai.x402; print('SDK 安装成功!')" +pnpm dev:server ``` -> ✅ **成功标志:** 终端输出 `SDK 安装成功!` +> ✅ **成功:** 服务器启动并打印启动日志。在未设置收款地址时它会以 `❌ No payout address configured (set EVM_ADDRESS and/or TRON_ADDRESS)` 退出——这是预期行为,说明工具链可用。您将在第二步设置这些地址。 -**另一种方式(从源码安装,适合需要修改源码的开发者):** +--- -```bash -# 克隆代码仓库 -git clone https://github.com/BofAI/x402.git -cd x402/python/x402 +## 第二步:配置环境变量 -# 安装(含 FastAPI 支持) -pip install -e ".[fastapi]" +主线(facilitator、server、client)三个进程共用一个文件:`.env-exact`。复制模板并填写: + +```bash +cp .env-exact.example .env-exact ``` -> 💡 **遇到权限错误?** 在命令前加 `sudo`(macOS/Linux),或以管理员身份运行 PowerShell(Windows)。 +在编辑器中打开 `.env-exact`,设置钱包与收款变量: ---- +```bash +# ── SHARED · client + facilitator(此处用同一把密钥支付与结算)──────── +AGENT_WALLET_PRIVATE_KEY=0x... # 您的测试钱包私钥 -## 第二步:创建付费 API 服务器 +# TronGrid API key —— client 和 facilitator 都会访问 TRON。测试网上可选。 +TRON_GRID_API_KEY= -现在,我们来创建一个带有付款保护的 API 服务器。x402 SDK 提供了 `@x402_protected` 装饰器,只需加在您想要收费的接口上,SDK 就会自动处理所有付款验证逻辑。 +# ── SERVER · 资源提供方(这是您要配置的)────────────────────────────── +EVM_ADDRESS=0x... # 您的 BSC 收款地址(eip155:97) +TRON_ADDRESS=T... # 您的 TRON 收款地址(tron:nile) -在您的项目目录下,新建一个名为 `server.py` 的文件,将以下代码复制进去: +# server 绑定端口,以及它访问 facilitator 的地址。 +SERVER_PORT=4021 +FACILITATOR_URL=http://localhost:4022 - - - -```python -from fastapi import FastAPI, Request -from bankofai.x402.server import X402Server -from bankofai.x402.fastapi import x402_protected -from bankofai.x402.facilitator import FacilitatorClient -from bankofai.x402.config import NetworkConfig - -app = FastAPI() - -# ========== 请修改以下两项配置 ========== -# 将下方地址替换为您在"前置准备"中创建的 TRON 钱包地址(用于接收付款) -PAY_TO_ADDRESS = "在此填入您的TRON钱包地址" - -# 结算服务地址(第三步中会启动,地址默认不用改) -FACILITATOR_URL = "http://localhost:8001" -# ======================================== - -# 初始化 x402 服务器 -server = X402Server() -server.set_facilitator(FacilitatorClient(FACILITATOR_URL)) - -# 为这个 API 接口添加付款保护 -@app.get("/protected") -@x402_protected( - server=server, - prices=["0.0001 USDT"], # 每次请求收费金额(可根据需要调整) - schemes=["exact_permit"], # 付款方式 - network=NetworkConfig.TRON_NILE, # 当前使用测试网(上线时改为 TRON_MAINNET) - pay_to=PAY_TO_ADDRESS, # 您的收款钱包地址 -) -async def protected_endpoint(request: Request): - return {"data": "这是需要付款才能获取的内容!"} - - -if __name__ == "__main__": - import uvicorn - uvicorn.run(app, host="0.0.0.0", port=8000) +# ── FACILITATOR · 结算 ──────────────────────────────────────────────── +FACILITATOR_PORT=4022 ``` - - +> 💡 **无密钥 server:** 资源服务器从不签名、不持有密钥——它只公布您的公开收款地址(`EVM_ADDRESS` / `TRON_ADDRESS`)。签名与结算发生在 client 和 facilitator 侧。`AGENT_WALLET_PRIVATE_KEY` 由 client(用于支付)和 facilitator(用于结算)使用,server 不使用。 + +> ⚠️ **安全提醒:** 私钥仅保存在 `.env`(已被 gitignore)或环境变量中。**切勿将含私钥的文件提交到 Git 或分享给任何人。** + +--- -```python -from fastapi import FastAPI, Request -from bankofai.x402.server import X402Server -from bankofai.x402.fastapi import x402_protected -from bankofai.x402.facilitator import FacilitatorClient -from bankofai.x402.config import NetworkConfig -from bankofai.x402.mechanisms.evm.exact_permit import ExactPermitEvmServerMechanism -from bankofai.x402.mechanisms.evm.exact import ExactEvmServerMechanism - -app = FastAPI() - -# ========== 请修改以下两项配置 ========== -# 将下方地址替换为您在"前置准备"中创建的 BSC 钱包地址(用于接收付款) -PAY_TO_ADDRESS = "在此填入您的BSC钱包地址(0x开头)" - -# 结算服务地址(第三步中会启动,地址默认不用改) -FACILITATOR_URL = "http://localhost:8001" -# ======================================== - -# 初始化 x402 服务器,并注册 BSC 付款机制 -server = X402Server() -server.register(NetworkConfig.BSC_TESTNET, ExactPermitEvmServerMechanism()) -server.register(NetworkConfig.BSC_TESTNET, ExactEvmServerMechanism()) -server.set_facilitator(FacilitatorClient(FACILITATOR_URL)) - -# 为这个 API 接口添加付款保护 -@app.get("/protected") -@x402_protected( - server=server, - prices=["0.0001 USDT"], # 每次请求收费金额 - network=NetworkConfig.BSC_TESTNET, # 当前使用测试网(上线时改为 BSC_MAINNET) - pay_to=PAY_TO_ADDRESS, # 您的收款钱包地址 - schemes=["exact_permit"], -) -async def protected_endpoint(request: Request): - return {"data": "这是需要付款才能获取的内容!"} - - -if __name__ == "__main__": - import uvicorn - uvicorn.run(app, host="0.0.0.0", port=8000) +## 第三步:创建付费 API 服务器 + +示例资源服务器是一个 Express 应用,将 `GET /weather` 保护在 x402 付款之后。它是**链无关**的——每条链的代币与 `accepts` 条目位于 `src/chains/{evm,tron}.ts`,仅当设置了 `*_ADDRESS` 时才公布该链。 + +以下是服务器入口(`examples/typescript/servers/express/src/index.ts`): + +```typescript +import express from "express"; +import { HTTPFacilitatorClient } from "@bankofai/x402-core/server"; +import { createResourceServer } from "@bankofai/x402-core"; +import { + x402HTTPResourceServer, + paymentMiddlewareFromHTTPServer, +} from "@bankofai/x402-express"; + +import { hasEvm, registerEvm, evmAccepts, evmExtensions } from "./chains/evm.js"; +import { hasTron, registerTron, tronAccepts } from "./chains/tron.js"; + +const PORT = parseInt(process.env.SERVER_PORT || "4021", 10); +const FACILITATOR_URL = process.env.FACILITATOR_URL || "http://localhost:4022"; + +// server 通过 HTTP 将 verify/settle 委托给 facilitator。 +const facilitatorClient = new HTTPFacilitatorClient({ url: FACILITATOR_URL }); +// 预挂日志:verify/settle 结果通过 SDK logger 打印。 +const resourceServer = createResourceServer(facilitatorClient); + +// 仅当设置了收款地址时才注册该链(并公布其代币)。 +type Accept = ReturnType[number] | ReturnType[number]; +const accepts: Accept[] = []; +let extensions: Record = {}; +if (hasEvm()) { + registerEvm(resourceServer); + accepts.push(...evmAccepts()); + extensions = { ...extensions, ...evmExtensions() }; +} +if (hasTron()) { + registerTron(resourceServer); + accepts.push(...tronAccepts()); +} + +// 您要保护的路由——`accepts` 是价格列表,`extensions` 携带 +// 普通 ERC-20(permit2)代币(如 BSC USDC)的 gas 赞助提示。 +const routes = { + "GET /weather": { + accepts, + extensions, + description: "Current weather (paid)", + mimeType: "application/json", + }, +}; + +const httpServer = new x402HTTPResourceServer(resourceServer, routes); + +const app = express(); +app.use(paymentMiddlewareFromHTTPServer(httpServer)); + +app.get("/weather", (_req, res) => { + res.json({ report: { weather: "sunny", temperature: 70 } }); +}); + +app.listen(PORT, () => { + console.log(`🌤️ Resource server on http://localhost:${PORT}`); +}); ``` - - +### 各链定价方式 + +每个链模块构建 `accepts` 条目(价格 + `payTo` + 代币)。两种链族定价方式不同: + +- **TRON** 使用 `"<金额> <符号>"` 字符串,由 scheme 从注册表中解析每个代币: + ```typescript + // src/chains/tron.ts —— tron:nile 上的 USDT 与 USDD + export function tronAccepts() { + const payTo = process.env.TRON_ADDRESS as string; + return ["tron:nile", "tron:mainnet"].flatMap((network) => + ["0.001 USDT", "0.001 USDD"].map((price) => ({ scheme: "exact", network, payTo, price })), + ); + } + ``` +- **EVM** 公布显式的 `{ amount, asset, extra }` 对象,因为 BSC 没有默认代币注册表项。ERC-3009 代币(如 DHLU)携带其域 `name`/`version`;普通 ERC-20 代币(如 USDC/USDT)设置 `extra.assetTransferMethod: "permit2"` 并需要一次性 Permit2 `approve`: + ```typescript + // src/chains/evm.ts + const EVM_TOKENS = { + "eip155:97": [ + { asset: "0x375cADdd…B816", amount: "1000", extra: { name: "DA HULU", version: "1" } }, // DHLU, ERC-3009 + { asset: "0x64544969…8930", amount: "1000000000000000", extra: { assetTransferMethod: "permit2" } }, // USDC + { asset: "0x337610d2…4dDd", amount: "1000000000000000", extra: { assetTransferMethod: "permit2" } }, // USDT + ], + }; + ``` -**主要配置说明:** +**关键配置参数:** -| 参数 | 说明 | 示例值 | +| 参数 | 说明 | 示例 | |------|------|--------| -| `PAY_TO_ADDRESS` | 您的收款钱包地址 | `TXyz...`(TRON)或 `0xAbc...`(BSC) | -| `prices` | 每次请求的价格 | `["0.0001 USDT"]` | -| `network` | 使用的网络 | 测试:`TRON_NILE` / `BSC_TESTNET` | -| `schemes` | 付款方式 | `["exact_permit"]` | +| `EVM_ADDRESS` / `TRON_ADDRESS` | 您的收款(payout)钱包地址 | `0xAbc…` / `TXyz…` | +| `accepts[].price` | 每次请求价格(代币金额,或 `"<金额> <符号>"`) | `"0.001 USDT"` | +| `accepts[].network` | 使用的网络 | 测试网:`tron:nile` / `eip155:97` | +| `accepts[].scheme` | 付款方式 | `"exact"` | +| `routes` | `"METHOD /path"` → `{ accepts, extensions, description, mimeType }` 的映射 | `"GET /weather"` | -**工作原理:** 当未付款的请求到达您的 API 时,服务器自动返回 HTTP 402(需要付款)响应,并在响应头中附上付款指引。客户端 SDK 会自动完成付款并重新发起请求,整个过程用户几乎无感知。 +**工作原理:** 当未付款请求到达您的 API 时,中间件自动返回 HTTP `402 Payment Required` 响应并携带付款要求。client SDK 自动完成付款并重发请求——对终端用户几乎不可见。 --- -## 第三步:接入结算服务(Facilitator) +## 第四步:接入结算服务(Facilitator) ### 什么是 Facilitator? -简单来说,Facilitator 是一个**自动公证服务**:当有人向您的 API 付款时,Facilitator 负责核实这笔付款是否真实,并在区块链上完成结算,确保资金记录到链上。 +Facilitator 是一个**自动结算服务**:当有人为您的 API 付款时,Facilitator 验证付款是否真实并将其结算到链上,确保资金到达您的收款钱包。您在第三步构建的 server 仅通过 `FACILITATOR_URL` 指向 Facilitator——它不自行结算。 -**您需要先完成 Facilitator 配置,再启动您的 API 服务器。** +**启动 API 服务器之前,必须有一个可达的 Facilitator。** ### 两种接入方式,如何选择? -| | 官方 Facilitator(推荐)| 自托管 Facilitator | +| | 官方 Facilitator(推荐) | 自托管 Facilitator | |---|---|---| -| **是否需要维护服务** | 不需要,官方托管 | 需要自行运行 | -| **是否需要钱包私钥** | 不需要 | 需要(用于支付手续费)| -| **上手难度** | 低(申请 API Key 即可)| 中(需部署配置)| -| **适合场景** | 快速上线、大多数用户 | 需要完全自定义费率策略 | +| **是否需要维护** | 否——官方托管 | 是——您自行运行 | +| **是否需要钱包私钥** | 否 | 是(用于链上结算) | +| **难度** | 低(仅需申请 API Key) | 中(运行示例 facilitator) | +| **适合** | 快速部署、大多数用户 | 需要完全控制费率策略 | -官方托管的 Facilitator 服务,**无需维护任何基础设施**。 详细信息也可参考 [官方 Facilitator](../core-concepts/OfficialFacilitator.md) +官方托管的 Facilitator 服务**无需维护基础设施**。完整步骤请参见 [官方 Facilitator](../core-concepts/OfficialFacilitator.md)。 -#### 3.1 配置服务端点 +#### 4.1 配置服务端点 -将您的 `FACILITATOR_URL` 设置为官方 Facilitator 服务地址: +在 `.env-exact` 中将 `FACILITATOR_URL` 设为官方端点: ``` -https://facilitator.bankofai.io -``` - -这是您的 x402 服务端用来验证和结算支付的地址,**仅供 API 调用**,无需用浏览器访问。 - -> ⚠️ **未配置 API Key 时,此端点按 IP 地址限速为每分钟 1 次请求。** 测试够用,但生产环境中会直接卡住您的 API。请继续第 3.2 步申请 API Key。 - -#### 3.2 申请 API Key - -在管理后台免费申请 API Key: - -[https://admin-facilitator.bankofai.io](https://admin-facilitator.bankofai.io) - -1. 在浏览器中打开上方链接 -2. 点击 **TronLink**,使用钱包登录(仅用于身份验证,**不会扣款**) -3. 登录后进入 Dashboard,点击**"创建 API Key"** -4. 点击确认,然后在 Dashboard 中点击 **View** 查看并复制您的 API Key - -配置 API Key 后,限速提升至 **1000 次/分钟**,足以支撑生产环境。 - -> 📖 **详细图文步骤**请参见:[官方 Facilitator](../core-concepts/OfficialFacilitator.md) - -> ⚠️ **安全提示:** API Key 是您的服务凭证,**请像对待密码一样保护它,绝不提交到 Git** - -#### 3.3 配置 `.env` 文件 - -在您的项目目录(存放 `server.py` 的目录)中,创建或编辑 `.env` 文件,添加以下内容: - -```bash -# 官方 Facilitator 服务地址 FACILITATOR_URL=https://facilitator.bankofai.io - -# API Key(在 admin-facilitator.bankofai.io 申请)— SDK 自动通过 X-API-KEY 请求头传递 -FACILITATOR_API_KEY=在此填入您的API Key ``` -#### 3.4 更新 server.py 连接官方 Facilitator - -将 `server.py` 中的 Facilitator 初始化部分修改为从环境变量读取配置(在文件顶部添加 `import os`): - - - +这是您的 x402 server 用于验证和结算付款的地址——**仅供 API 调用**,无需在浏览器中打开。 -```python -import os -# ... 其他 import 保持不变 ... +> ⚠️ **未配置 API Key 时,该端点受速率限制**(每个 IP 每分钟一次 `/settle`)。仅适合测试。 -# 官方 Facilitator 服务地址(从环境变量读取) -# SDK 会自动从环境变量读取 FACILITATOR_API_KEY,无需显式传参 -FACILITATOR_URL = os.getenv("FACILITATOR_URL", "https://facilitator.bankofai.io") +#### 4.2 申请 API Key -# 初始化 x402 服务器,连接官方 Facilitator -server = X402Server() -server.set_facilitator(FacilitatorClient(FACILITATOR_URL)) -``` +1. 在浏览器中打开[管理后台](https://admin-facilitator.bankofai.io),使用钱包登录 +2. 在 Dashboard 上点击 **"Create API Key"** +3. 确认后,在 Dashboard 点击 **View** 查看并复制您的 API Key - - +配置 API Key 后,速率限制提升到 **每分钟 1,000 次**,足以满足生产需求。 -```python -import os -# ... 其他 import 保持不变 ... +#### 4.3 将 API Key 接入您的 server -# 官方 Facilitator 服务地址(从环境变量读取) -# SDK 会自动从环境变量读取 FACILITATOR_API_KEY,无需显式传参 -FACILITATOR_URL = os.getenv("FACILITATOR_URL", "https://facilitator.bankofai.io") +官方 key 以 `X-API-KEY` 头的形式随每次 facilitator 调用发送。示例 server 已通过 `FACILITATOR_API_KEY` 支持: -# 初始化 x402 服务器,注册 BSC 机制,连接官方 Facilitator -server = X402Server() -server.register(NetworkConfig.BSC_TESTNET, ExactPermitEvmServerMechanism()) -server.register(NetworkConfig.BSC_TESTNET, ExactEvmServerMechanism()) -server.set_facilitator(FacilitatorClient(FACILITATOR_URL)) +```bash +# 追加到 .env-exact +FACILITATOR_API_KEY=paste_your_api_key_here ``` - - +> ⚠️ **安全提醒:** API Key 是服务凭据——**像密码一样保管,切勿提交到 Git**。 -> ✅ **完成!** 官方 Facilitator 已配置好,**不需要启动任何本地服务**,直接进入第四步测试即可。 +> ✅ **完成!** 官方 Facilitator 已配置——**无需启动本地服务**。直接进入第五步测试。 -自托管方式让您完全掌控费用策略和网络配置,适合有特定定制需求的高级用户。 - -> ⚠️ **安全提示——请先阅读:** -> - 需要一个**专用钱包**的私钥用于支付区块链手续费,**该钱包应与收款钱包分开** -> - Facilitator 钱包只需少量代币(用于手续费),不要存入大量资金 -> - 私钥通过环境变量设置,**绝不要提交到 Git 或分享给他人** - -#### 3.1 准备前置依赖 - -启动前,请确认以下条件已就绪: - -- **Python 3.11+** 和 **Git**(前置准备中已确认) -- **PostgreSQL** — Facilitator 使用数据库持久化支付记录。 - - - - - ```bash - brew install postgresql@16 - brew services start postgresql@16 - createdb x402 - ``` - - - - - **Ubuntu / Debian:** - ```bash - sudo apt install -y postgresql - sudo systemctl start postgresql - sudo -u postgres createdb x402 - ``` - - **Amazon Linux / CentOS / RHEL / Fedora:** - ```bash - sudo dnf install -y postgresql15 postgresql15-server # Amazon Linux 2023;其他发行版使用 postgresql-server - sudo postgresql-setup --initdb - sudo systemctl start postgresql - sudo systemctl enable postgresql - sudo -u postgres createdb x402 - ``` - - **Arch Linux:** - ```bash - sudo pacman -S postgresql - sudo -u postgres initdb -D /var/lib/postgres/data - sudo systemctl start postgresql - sudo -u postgres createdb x402 - ``` - - - +自托管方式让您完全控制费率策略。它运行示例 facilitator(`examples/typescript/facilitator/basic`),通过 HTTP 暴露 `/verify`、`/settle`、`/supported`,并按付款的 `network` 字段分发。 - 从 [postgresql.org/download/windows](https://www.postgresql.org/download/windows/) 下载并运行安装程序,然后通过 pgAdmin 或 psql 创建名为 `x402` 的数据库。 +> ⚠️ **安全提醒——请先阅读:** +> - 自托管 Facilitator 使用您的钱包提交链上结算交易——**此钱包应与您的收款钱包分开** +> - 仅向 Facilitator 钱包充入少量代币(足够支付手续费)——不要存放大量资金 +> - 私钥仅保存在 `.env-exact` 中——**切勿提交到 Git 或分享给任何人** - - +#### 4.1 自托管 Facilitator 的工作原理 - **为 `postgres` 用户设置密码**(连接字符串中需要用到): - - ```bash - sudo -u postgres psql -c "ALTER USER postgres WITH PASSWORD 'yourpassword';" - ``` +facilitator 验证签名并在链上结算。它按链注册 `exact` scheme 并附带 signer: - > 将 `yourpassword` 替换为您自定义的密码,后续配置文件中会用到。 +```typescript +// examples/typescript/facilitator/basic/src/index.ts(节选) +import { x402Facilitator } from "@bankofai/x402-core/facilitator"; - **开启密码认证**(仅 Linux — 大多数发行版需要此步骤): +const facilitator = new x402Facilitator() + .onBeforeSettle(async ctx => console.log("[settle] before", ctx.requirements.network)) + .onAfterSettle(async ctx => console.log("[settle] after", ctx.requirements.network)) + .onSettleFailure(async ctx => console.log("[settle] failure", ctx)); - Linux 上 PostgreSQL 默认使用 `ident` 认证,要求操作系统用户名与数据库用户名一致,否则连接会被拒绝。需要将认证方式改为 `md5`(密码认证),Facilitator 才能正常连接: +// 仅当钱包解析成功时才注册该链(可仅 EVM、仅 TRON,或两者)。 +const evm = await registerEvm(facilitator); +const tron = await registerTron(facilitator); - ```bash - # 查找 pg_hba.conf 文件位置 - sudo find / -name pg_hba.conf 2>/dev/null - # 常见路径:/var/lib/pgsql/data/pg_hba.conf(Amazon Linux / CentOS) - # /etc/postgresql/*/main/pg_hba.conf(Ubuntu / Debian) - ``` - - 打开文件,将 IPv4 和 IPv6 本地连接的 `ident` 改为 `md5`: - - ``` - # IPv4 local connections: - host all all 127.0.0.1/32 md5 - # IPv6 local connections: - host all all ::1/128 md5 - ``` - - 修改后重启 PostgreSQL 使配置生效: - - ```bash - sudo systemctl restart postgresql - ``` +// 在 FACILITATOR_PORT 上暴露 POST /verify、POST /settle、GET /supported。 +app.listen(PORT, () => console.log(`🚀 Facilitator on http://localhost:${PORT}`)); +``` - 连接字符串:`postgresql+asyncpg://postgres:yourpassword@localhost:5432/x402` +每个链模块将 agent-wallet 适配为 facilitator signer: +- **EVM** —— `createFacilitatorEvmSigner(wallet, { network, rpcUrl })`,然后 `facilitator.register(network, new ExactEvmScheme(signer))` +- **TRON** —— `createFacilitatorTronSigner(wallet, { network, apiKey })`,然后 `facilitator.register(network, new ExactTronScheme(signer))` -- **Facilitator 专用钱包** — 单独创建一个新钱包(与收款钱包隔离,步骤与前置准备相同),并从水龙头领取测试代币用于支付手续费。 +signer 工厂内部构建 viem client / TronWeb;示例**从不读取原始私钥**——`AGENT_WALLET_PRIVATE_KEY` 由 `@bankofai/agent-wallet` 消费。 -#### 3.2 克隆并安装 +#### 4.2 启动 Facilitator -打开一个**新的终端窗口**,执行: +您的 `.env-exact` 中的 `FACILITATOR_URL` 已默认为 `http://localhost:4022`,与示例 facilitator 一致。从 `examples/typescript` 运行: ```bash -# 克隆 Facilitator 服务仓库 -git clone https://github.com/BofAI/x402-facilitator.git -cd x402-facilitator - -# 安装依赖 -pip install -r requirements.txt +pnpm dev:facilitator ``` -#### 3.3 配置服务 - -复制示例配置文件并用文本编辑器打开: +**启动成功后,应看到类似输出:** -```bash -cp config/facilitator.config.example.yaml config/facilitator.config.yaml ``` - -填写必填字段: - - - - -```yaml -database: - url: "postgresql+asyncpg://postgres:yourpassword@localhost:5432/x402" - -facilitator: - networks: - tron:nile: # 上线时改为 tron:mainnet - base_fee: - USDT: 100 # 每笔结算收 0.0001 USDT(可按需调整) - USDD: 100000000000000 # 0.0001 USDD(18位精度;按需调整) +[evm] facilitator registered eip155:97 (0x…) +[tron] facilitator registered tron:nile (T…) +🚀 Facilitator on http://localhost:4022 (evm=true, tron=true) ``` - - - -```yaml -database: - url: "postgresql+asyncpg://postgres:yourpassword@localhost:5432/x402" - -facilitator: - networks: - bsc:testnet: # 上线时改为 bsc:mainnet - base_fee: - USDT: 100 # 每笔结算收 0.0001 USDT(可按需调整) -``` +> ✅ **成功:** Facilitator 在 4022 端口运行——**保持此终端窗口打开,不要关闭** -然后通过环境变量设置 Facilitator 专用钱包的私钥: - - - - -```bash -# 获取方式:TronLink → 设置 → 账户管理 → 导出私钥 -export AGENT_WALLET_PRIVATE_KEY=在此填入Facilitator专用钱包的私钥 - -# TronGrid API Key(推荐配置,确保 RPC 稳定访问) -# 申请地址:https://www.trongrid.io/ -export TRON_GRID_API_KEY=在此填入TronGrid API Key -``` - - - +--- -```bash -# 获取方式:MetaMask → 账户详情 → 导出私钥 -export AGENT_WALLET_PRIVATE_KEY=在此填入Facilitator专用钱包的私钥 -``` +## 第五步:启动并测试您的 API - - +### 5.1 启动 API 服务器 -#### 3.4 启动 Facilitator 服务 +打开**新终端窗口**(不要关闭 facilitator),从 `examples/typescript` 运行: ```bash -python src/main.py +pnpm dev:server ``` -**成功启动后,您应该看到类似以下输出:** +**启动成功后,应看到:** ``` -INFO: Started server process -INFO: Waiting for application startup. -INFO: Application startup complete. -INFO: Uvicorn running on http://0.0.0.0:8001 (Press CTRL+C to quit) +🌤️ Resource server on http://localhost:4021 (evm=true, tron=true) → facilitator http://localhost:4022 ``` -> ✅ **成功标志:** Uvicorn 已在 8001 端口运行,**保持此终端窗口开启,不要关闭** +> ✅ **成功:** 终端显示资源服务器在 `http://localhost:4021` -#### 3.5 注册 API Key(可选) +### 5.2 测试未付款访问(应被拒绝) -如需按卖家维度追踪支付记录,可用内置脚本生成 API Key: +在任意终端运行: ```bash -python scripts/register_seller.py -# 会自动生成并打印一个随机 API Key,请妥善保存 +curl http://localhost:4021/weather ``` -将此 Key 配置到您的服务端: -```bash -export FACILITATOR_API_KEY=生成的API Key -``` +**预期结果:** 服务器返回 HTTP `402` 响应,携带付款要求(一个 `accepts` 数组,列出 scheme、网络、价格和您的收款地址)。 -`server.py` 中的 `FACILITATOR_URL = "http://localhost:8001"` 已是自托管配置,**无需修改**,直接进入第四步。 +> ✅ **这正是我们想要的!** 确认付款保护已生效——未付款请求被成功拦截。 - - +### 5.3 测试完整付款流程 ---- - -## 第四步:启动并测试您的 API - -### 4.1 启动 API 服务器 - -打开**第三个终端窗口**(前两个不要关),进入存放 `server.py` 的目录,执行: +要测试完整的 付款 → 获取内容 流程,在**第三个终端**启动示例 client。从 `examples/typescript` 开始,先设置要支付的链/代币: ```bash -python server.py +# 追加到 .env-exact(或在 client 终端 export) +PAY_TARGETS=tron:nile@USDT # TRON Nile USDT;或 eip155:97@DHLU 用于 BSC +RESOURCE_URL=http://localhost:4021/weather ``` -**成功启动后,您应该看到:** - -``` -INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) -INFO: Application startup complete. -``` - -> ✅ **成功标志:** 终端显示 `Uvicorn running on http://0.0.0.0:8000` - -### 4.2 测试未付款访问(应被拒绝) - -打开任意终端,执行: +然后运行: ```bash -curl http://localhost:8000/protected +pnpm dev:client ``` -**预期结果:** 服务器返回 HTTP 402 响应,内容类似: +**预期输出:** -```json -{"error": "Payment required", "x402Version": 1} +``` +→ [tron:nile@USDT] GET http://localhost:4021/weather +← 200 OK +{ "report": { "weather": "sunny", "temperature": 70 } } ``` -> ✅ **这正是我们想要的!** 说明付款保护正常工作——未付款的请求被成功拦截了。 - -### 4.3 测试完整付款流程 - -要测试完整的付款→获取内容流程,您需要一个能够签名付款的客户端: +> ✅ **成功:** client 自动检测到 `402`,签署付款,通过 facilitator 在链上结算,并获取了受保护的内容。 -- [人类用户快速入门](./quickstart-for-human.md) — 使用代码方式调用您的付费 API -- [AI 代理快速入门](./quickstart-for-agent.md) — 配置 AI 代理自动付款调用 +> 💡 client 用 `wrapFetchWithPayment(fetch, client)` 包装 `fetch`,使 402 挑战自动支付——客户端流程详见[用户快速入门](./quickstart-for-human.md)。 --- ## 故障排查 -| 问题 | 解决方案 | -|------|----------| -| `Connection refused` 连接 Facilitator 失败 | 使用**自托管**方式时,确认第三步的 Facilitator 终端仍在运行(`python src/main.py`),监听 8001 端口;使用**官方**方式时,检查 `FACILITATOR_URL` 是否正确配置为 `https://facilitator.bankofai.io` | -| `ModuleNotFoundError: bankofai` | 重新执行第一步的安装命令 | -| 钱包地址格式错误 | TRON 地址以 `T` 开头;BSC 地址以 `0x` 开头,检查是否完整复制 | -| Facilitator 启动失败——数据库报错(自托管)| 确认 `config/facilitator.config.yaml` 中 `database.url` 填写正确,且 PostgreSQL 实例正在运行 | -| Facilitator 启动失败——钱包报错(自托管)| 确认 `AGENT_WALLET_PRIVATE_KEY` 已在当前终端 `export`,且无多余空格或换行 | -| API Key 无效或频率受限(官方)| 确认 `FACILITATOR_API_KEY` 已正确设置,前往 [admin-facilitator.bankofai.io](https://admin-facilitator.bankofai.io) 检查 Key 状态 | -| `server.py` 启动报错 | 确认 `PAY_TO_ADDRESS` 已替换为真实钱包地址(不要保留占位文字) | - -**需要更多示例和参考?** - -- [完整服务器示例代码](https://github.com/BofAI/x402-demo/tree/main/server) -- [Facilitator 示例代码](https://github.com/BofAI/x402-demo/tree/main/facilitator) -- [Facilitator 详细说明](../core-concepts/facilitator.md) — 两种方式的完整安装步骤对比 -- [官方 Facilitator](../core-concepts/OfficialFacilitator.md) — 官方服务 API Key 图文教程 +| 问题 | 原因 | 解决方案 | +|---------|-------|----------| +| `No payout address configured` | 未设置 `EVM_ADDRESS` 和 `TRON_ADDRESS` | 在 `.env-exact` 中至少设置一个并重启 server | +| `Failed to fetch` / connection refused | facilitator 或 server 未运行 | 先启动 facilitator(`pnpm dev:facilitator`),再启动 server(`pnpm dev:server`) | +| client `server offered no payment option matching "…"` | `PAY_TARGETS` 与公布的选项不匹配 | 检查 server 的 `accepts`(网络 + 代币)并对齐 `PAY_TARGETS`,如 `tron:nile@USDT` 或 `eip155:97@DHLU` | +| `npx tsx` 下出现 `ERR_PACKAGE_PATH_NOT_EXPORTED` | 项目未声明为 ESM | 在 `package.json` 中添加 `"type": "module"` | +| `UnsupportedNetworkError` / `No mechanism registered` | `PAY_TARGETS` 中的网络没有注册的 scheme | 确保 client 的 `EVM_NETWORKS`/`TRON_NETWORKS` 包含您的目标,且该链的钱包已解析 | +| `Insufficient balance` / allowance 错误 | 测试钱包缺少测试代币,或 Permit2 授权额度过低 | 从水龙头领取测试代币;client 在首次付款时会自动批准 Permit2 | +| `Connection timeout` | 网络或请求超时 | 检查连接,或设置可靠的 `EVM_RPC_URL`(如 `https://bsc-testnet-rpc.publicnode.com`) | --- ## 在主网运行 -在测试网完整验证后,只需以下几步即可上线接收真实付款: - -### 1. 更新服务器配置 +在测试网充分验证后,只需几步即可上线并接受真实付款: -修改 `server.py` 中 `@x402_protected` 装饰器的 `network` 参数: +### 1. 将 client 和 server 指向主网 - - - -```python -@x402_protected( - server=server, - prices=["0.0001 USDT"], - schemes=["exact_permit"], - network=NetworkConfig.TRON_MAINNET, # 从 TRON_NILE 改为 TRON_MAINNET - pay_to=PAY_TO_ADDRESS, -) -``` +示例在相同的表中注册了测试网**和**主网——无需取消注释。在 `.env-exact` 中设置主网值即可切换: - - +```bash +# server 收款地址 → 您的主网钱包 +EVM_ADDRESS=0xYourMainnetBscAddress +TRON_ADDRESS=TYourMainnetTronAddress -```python -@x402_protected( - server=server, - prices=["0.0001 USDT"], - schemes=["exact_permit"], - network=NetworkConfig.BSC_MAINNET, # 从 BSC_TESTNET 改为 BSC_MAINNET - pay_to=PAY_TO_ADDRESS, -) +# client 在主网支付 +PAY_TARGETS=tron:mainnet@USDT # 或 eip155:56@USDT ``` - - - -### 2. 更新 Facilitator 配置 - - - - -1. **申请 TronGrid API Key**:前往 [TronGrid](https://www.trongrid.io/) 注册并创建 API Key,然后通过环境变量设置: +### 2. 设置可靠的 EVM RPC - ```bash - export TRON_GRID_API_KEY=your_trongrid_api_key - ``` +BSC 主网需要稳定端点。为 client 和 facilitator 都设置: - :::note - 未配置 `TRON_GRID_API_KEY` 时,在高负载下可能会被限速。生产环境请配置 `TRON_GRID_API_KEY`,以确保可靠性。 - ::: - -2. **替换私钥**:将环境变量更新为主网 Facilitator 钱包的私钥: - - ```bash - export AGENT_WALLET_PRIVATE_KEY=your_mainnet_facilitator_private_key - ``` - -3. **充值手续费**:向 Facilitator 主网钱包转入足够的真实 TRX(用于支付 Energy 和 Bandwidth 费用)。 - -4. **更新网络配置**:打开 `config/facilitator.config.yaml`,将网络键从 `tron:nile` 改为 `tron:mainnet`: - - ```yaml - facilitator: - networks: - tron:mainnet: # 从 tron:nile 改为 tron:mainnet - base_fee: - USDT: 100 - USDD: 100000000000000 # 0.0001 USDD(18位精度;按需调整) - ``` - -5. **重启服务**:`python src/main.py` - - - - -1. **充值手续费**:向 Facilitator 主网钱包转入足够的真实 BNB(用于支付 Gas 费用)。 - -2. **替换私钥**:将环境变量更新为主网 Facilitator 钱包的私钥: - - ```bash - export AGENT_WALLET_PRIVATE_KEY=your_mainnet_facilitator_private_key - ``` +```bash +EVM_RPC_URL=https://bsc-rpc.publicnode.com +``` -3. **更新网络配置**:打开 `config/facilitator.config.yaml`,将网络键从 `bsc:testnet` 改为 `bsc:mainnet`: +### 3.(自托管)将 Facilitator 切换到主网 - ```yaml - facilitator: - networks: - bsc:mainnet: # 从 bsc:testnet 改为 bsc:mainnet - base_fee: - USDT: 100 - ``` +facilitator 的 `TRON_NETWORKS` 已包含 `tron:mainnet`,`EVM_NETWORKS` 已包含 `eip155:56`。向 Facilitator 钱包充入足够的真实 TRX/BNB 以支付结算 gas,然后重启: -4. **重启服务**:`python src/main.py` +```bash +pnpm dev:facilitator +``` - - +> 生产 TRON 负载请设置自己的 `TRON_GRID_API_KEY` 以避免速率限制。 -### 3. 确认您的收款钱包地址 +### 4.(官方 Facilitator)无需本地改动 -确保 `PAY_TO_ADDRESS` 填写的是您控制的**真实主网钱包地址**,并确认您持有该钱包的助记词或私钥备份。 +若使用官方 facilitator,保持 `FACILITATOR_URL=https://facilitator.bankofai.io` 和您的 `FACILITATOR_API_KEY`。仅 server 的收款地址切换到主网。 -### 4. 上线前进行小额真实测试 +### 5. 确认并做小额真实测试 -> ⚠️ **主网上线警告——涉及真实资金,请严格执行以下步骤:** +> ⚠️ **主网警告——涉及真实资金。请仔细遵循以下步骤:** > -> 1. 确保已在测试网完整验证所有功能(付款、收款、错误处理) -> 2. 主网上线后,**先发起一笔最小金额(如 0.0001 USDT)的真实测试** -> 3. 在区块链浏览器([TronScan](https://tronscan.org) 或 [BscScan](https://bscscan.com))上确认交易成功 -> 4. 打开您的收款钱包,确认资金已到账 -> 5. 确认无误后,再正式对外开放 API +> 1. 确保所有功能(付款、收款、错误处理)已在测试网充分验证 +> 2. 上线主网后,**先用一个最小金额的真实测试(如 `0.001 USDT`)** +> 3. 在区块链浏览器([TronScan](https://tronscan.org) 或 [BscScan](https://bscscan.com))确认交易成功 +> 4. 打开收款钱包,确认资金已到账 +> 5. 确认一切正常后,再将 API 对外公开 --- ## 下一步 -- 查看[演示示例](https://github.com/BofAI/x402-demo/tree/main/server)了解更多复杂的付款流程 -- 深入阅读[核心概念](../core-concepts/http-402.md),理解 x402 协议的工作原理 -- 想深入了解 Facilitator 两种接入方式的详细配置?参见 [Facilitator 说明文档](../core-concepts/facilitator.md) -- 以[用户视角](./quickstart-for-human.md)体验调用付费 API,或配置 [AI 代理](./quickstart-for-agent.md)自动调用您的服务 +- 探索[可运行示例](https://github.com/BofAI/x402/tree/main/examples/typescript),查看完整的 client → server → facilitator 循环,以及 `gasfree`、`upto`、`batch-settlement` 场景 +- 阅读[核心概念](../core-concepts/http-402.md)了解 x402 协议的工作原理 +- 想了解两种 Facilitator 选项的详细配置?参见 [Facilitator 文档](../core-concepts/facilitator.md) +- 从[用户视角](./quickstart-for-human.md)体验调用付费 API,或配置 [AI 代理](./quickstart-for-agent.md)自动调用您的服务 --- ## 完成总结 -恭喜 🎉!您已完成卖家快速入门。以下是您完成的所有步骤: +恭喜 🎉!您已完成卖家快速入门。以下是您完成的所有内容: -| 步骤 | 完成内容 | +| 步骤 | 您做了什么 | |------|----------| -| **前置准备** | 创建收款钱包,获取测试代币,熟悉配置参数 | -| **第一步** | 安装 x402 SDK | -| **第二步** | 创建带付款保护的 API 服务器 | -| **第三步** | 配置并启动 Facilitator 结算服务 | -| **第四步** | 验证付款保护和完整付款流程 | - -您的 API 现在已经可以通过 x402 协议接收区块链支付了! +| **前置准备** | 创建收款钱包、领取测试代币、了解配置参数 | +| **第一步** | 克隆 SDK 仓库并安装示例工作区 | +| **第二步** | 配置 `.env-exact`(钱包与收款地址) | +| **第三步** | 运行无密钥 Express 资源服务器(带付款保护) | +| **第四步** | 接入 Facilitator(官方或自托管)进行结算 | +| **第五步** | 验证付款保护与完整的 client → server → facilitator 付款流程 | + +您的 API 现在已准备好通过 x402 协议接受区块链付款! diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/index.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/index.md index 12955dd2..bfcbf54a 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/index.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/index.md @@ -11,7 +11,7 @@ x402 是一种基于 HTTP `402 Payment Required` 状态码的区块链开放支 **有意参与文档共建?** 欢迎在 [GitHub 仓库](https://github.com/BofAI/docs)提交 PR!我们唯一的原则是保持文档的中立性:除必要的资源链接外,请避免包含任何品牌推广内容。 -**寻找实战代码?** 请访问 [x402-demo 仓库](https://github.com/BofAI/x402-demo) 获取完整且可直接运行的示例项目。 +**寻找可运行示例?** [`x402` 仓库](https://github.com/BofAI/x402) 在 `examples/typescript/` 下提供了每种方案的完整 client → server → facilitator 可运行三件套——`exact`、`gasfree`、`upto`、`batch-settlement`。 ## 为什么要使用 x402? @@ -67,9 +67,7 @@ x402 目前支持以下网络环境: - **BSC 主网** (`eip155:56`) - **BSC 测试网** (`eip155:97`) -> **协议互通**:自 v0.5.9 起,`exact` 支付方案(EVM 与 TRON)已与 **x402 Foundation(原 Coinbase)** 公布的 v2 规范保持一致,支持与 x402 Foundation 的 v2 参考客户端/服务端双向互通。详见 [SDK 功能特性](./sdk-features.md) 与 [网络与代币支持](./core-concepts/network-and-token-support.md#exact-方案)。 - -> **TypeScript / Python 对齐(v0.6.0)**:自 v0.6.0 起,TypeScript SDK 在服务端与 Facilitator 角色上已与 Python 功能对齐——包括 Facilitator 客户端与引擎、服务端中间件(Hono 与 Express)、`fetch` 封装、Facilitator 签名器,以及 `exact` / `exact_permit` / `exact_gasfree` 的 verify + settle。完整对比详见 [SDK 功能特性](./sdk-features.md)。 +> **SDK 1.0.0(仅 TypeScript)**:x402 `1.0.0` 是仅 TypeScript 的 pnpm/turbo monorepo,以颗粒化 `@bankofai/x402-*` 包发布(`core`、`evm`、`tron`、`fetch`、`express`、`hono`、`fastify`、`next`、`axios`、`mcp`、`extensions`)。`core` 与 EVM 机制 fork 自 [`x402-foundation/x402`](https://github.com/x402-foundation/x402) 上游;TRON 机制为自研。支持的方案:`exact`(ERC-3009 / Permit2)、`upto`、`batch-settlement`、`auth-capture`(EVM)、`exact_gasfree`(TRON)。此前的 Python + TypeScript SDK 已移至 `legacy/` 仅供参考。完整对比详见 [SDK 功能特性](./sdk-features.md)。 ## 快速开始 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/sdk-features.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/sdk-features.md index a4a8cde7..df2f98d8 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/sdk-features.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/sdk-features.md @@ -1,102 +1,159 @@ -# SDK 功能特性 +--- +title: 'SDK 功能矩阵' +description: 'x402 TypeScript SDK(1.0.0)的功能支持矩阵,以颗粒化 @bankofai/x402-* 包发布。' +--- -本页面记录了 x402 各语言 SDK(Python, TypeScript)的功能实现进度与支持状态。 +# SDK 功能矩阵 -> **TypeScript / Python 对齐(自 v0.6.0 起)**:自 **v0.6.0** 起,TypeScript SDK 在服务端(Server)与 Facilitator 角色上已与 Python 实现功能对齐。TypeScript 现已提供 Facilitator 客户端与引擎(`X402Facilitator`)、服务端中间件(`x402Hono` / `x402Express`)、`fetch` 封装、Facilitator 签名器,以及 `exact` / `exact_permit` / `exact_gasfree` 的 verify + settle 流程。 +本页跟踪 x402 SDK 的功能支持情况。 -## 核心 +> **SDK 1.0.0(仅 TypeScript)**:x402 是一个**仅 TypeScript** 的 pnpm/turbo monorepo,以颗粒化的 `@bankofai/x402-*` 包发布。`core` 与 EVM 机制 fork 自 [`x402-foundation/x402`](https://github.com/x402-foundation/x402) 上游;TRON 机制为自研。此前的 Python + TypeScript SDK 已移至 `legacy/` 仅供参考。 -| 组件 | Python | TypeScript | -|-----------|--------|------------| -| 服务端 (Server) | ✅ | ✅ | -| 客户端 (Client) | ✅ | ✅ | -| Facilitator | ✅ | ✅ | +--- + +## 包 + +| 包 | 用途 | +|---------|---------| +| `@bankofai/x402-core` | 协议类型、client/facilitator/server 引擎、`HTTPFacilitatorClient`、可观测性 | +| `@bankofai/x402-evm` | EVM 机制:`exact`、`upto`、`batch-settlement`、`auth-capture` | +| `@bankofai/x402-tron` | TRON 机制:`exact`、`upto`、`batch-settlement`、`exact_gasfree` | +| `@bankofai/x402-fetch` | 包装 `fetch` 的 client(`wrapFetchWithPayment`) | +| `@bankofai/x402-express` | Express server 中间件 | +| `@bankofai/x402-hono` | Hono server 中间件 | +| `@bankofai/x402-fastify` | Fastify server 中间件 | +| `@bankofai/x402-next` | Next.js server 中间件 | +| `@bankofai/x402-axios` | Axios client 包装 | +| `@bankofai/x402-mcp` | 面向 AI 代理的 MCP 传输(client + server) | +| `@bankofai/x402-extensions` | 扩展:gas 赞助、payment-identifier、bazaar、sign-in-with-x、offer-receipt、builder-code | + +--- + +## 核心组件 + +| 组件 | 状态 | +|------------|--------| +| 资源服务器(Resource Server) | ✅ | +| 客户端(Client) | ✅ | +| Facilitator | ✅ | ### HTTP 框架集成 -| 角色 | Python | TypeScript | -|------|--------|------------| -| 服务端 | FastAPI, Flask | Hono, Express | -| 客户端 | httpx | fetch | - -## 网络 - -| 网络 | Python | TypeScript | -|---------|--------|------------| -| tron:mainnet | ✅ | ✅ | -| tron:nile | ✅ | ✅ | -| tron:shasta | ✅ | ✅ | -| eip155:56 (BSC Mainnet) | ✅ | ✅ | -| eip155:97 (BSC Testnet) | ✅ | ✅ | - - -## 机制 - -| 机制 | Python | TypeScript | -|-----------|--------|------------| -| exact_permit/tron | ✅ | ✅ | -| exact_permit/bsc | ✅ | ✅ | -| exact/tron | ✅ | ✅ | -| exact/bsc | ✅ | ✅ | -| exact_gasfree/tron | ✅ | ✅ | - -> **Coinbase x402 v2 兼容**:自 v0.5.9 起,`exact` 机制(EVM 与 TRON)的 `payload` 已对齐 x402 Foundation(原 Coinbase)v2 链路传输格式。标准 v2 客户端可直接与本 SDK 服务端互通,反之亦然。详见 [网络与代币支持 → `exact` 方案](./core-concepts/network-and-token-support.md#exact-方案)。 - -## 签名器 - -| 签名器 | Python | TypeScript | -|--------|--------|------------| -| TronClientSigner | ✅ | ✅ | -| EvmClientSigner | ✅ | ✅ | -| TronFacilitatorSigner | ✅ | ✅ | -| EvmFacilitatorSigner | ✅ | ✅ | - -## 客户端功能 - -| 功能 | Python | TypeScript | -|---------|--------|------------| -| 自动处理 402 | ✅ | ✅ | -| 自动代币批准 | ✅ | ✅ | -| 额度检查 | ✅ | ✅ | -| 签名 (TRON) | ✅ | ✅ | -| 签名 (EVM) | ✅ | ✅ | -| SufficientBalancePolicy(余额检查策略) | ✅ | ✅ | -| GasFree(TRON 零 gas 支付) | ✅ | ✅ | - -## 服务端功能 - -| 功能 | Python | TypeScript | -|---------|--------|------------| -| 受保护路由集成 | ✅(`@x402_protected` 装饰器) | ✅(`x402Hono` / `x402Express` 中间件) | -| 支付验证 | ✅ | ✅ | -| 支付结算 | ✅ | ✅ | -| 费用支持 | ✅ | ✅ | - -## Facilitator 功能 - -| 功能 | Python | TypeScript | -|---------|--------|------------| -| /verify 端点 | ✅ | ✅ | -| /settle 端点 | ✅ | ✅ | -| /fee/quote 端点 | ✅ | ✅ | -| /supported 端点 | ✅ | ✅ | -| 提交交易 | ✅ | ✅ | -| 确认交易 | ✅ | ✅ | - -## 支持代币 - -| 代币 | Python | TypeScript | -|-------|--------|------------| -| USDT (TRC-20) | ✅ | ✅ | -| USDD (TRC-20) | ✅ | ✅ | -| 自定义 TRC-20 | ✅ | ✅ | -| USDT (BEP-20) | ✅ | ✅ | -| USDC (BEP-20,主网/测试网) | ✅ | ✅ | -| DHLU (BSC 测试网,用于 `exact` 互通测试) | ✅ | ✅ | -| 自定义 BEP-20 | ✅ | ✅ | - -## 图例 +| 角色 | 框架 | +|------|------------| +| Server | Express、Fastify、Hono、Next.js | +| Client | `fetch`(包装)、Axios、MCP | + +--- + +## 网络 + +| 网络 | 状态 | +|-----------|--------| +| `tron:mainnet` | ✅ | +| `tron:nile` | ✅ | +| `tron:shasta` | ✅ | +| `eip155:56`(BSC 主网) | ✅ | +| `eip155:97`(BSC 测试网) | ✅ | + +> 上游 EVM 链(Base、Base Sepolia、MegaETH、Monad、Hyperliquid)也已接入 EVM 默认资产注册表。在示例中添加一条链仅需编辑配置表——无需改动 SDK。 + +--- + +## 付款方案 + +x402 1.0.0 支持五种付款方案。每种方案按链族实现为 client + server + facilitator 三件套。 + +| 方案 | EVM | TRON | 说明 | +|--------|-----|------|-------------| +| `exact` | ✅ | ✅ | 支付精确金额。ERC-3009 `transferWithAuthorization`(无 gas)或 Permit2(一次性 `approve(Permit2)`)用于普通 ERC-20。 | +| `upto` | ✅ | ✅ | 按量计费——client 签署最高至最大金额的 Permit2 授权;server 仅结算实际用量(≤ max)。 | +| `batch-settlement` | ✅ | ✅ | 支付通道:链上一次性存入,然后用链下凭证支付多次请求;facilitator 批量 claim 并在一笔交易中结算。含退款路径。 | +| `auth-capture` | ✅ | ❌ | 托管式授权捕获(仅 EVM)。 | +| `exact_gasfree` | ❌ | ✅ | 仅 TRON。用 USDT/USDD 付款**无需持有 TRX 支付 gas**——由 relayer 通过 GasFree API 支付链上 energy。 | + +> **x402 Foundation v2 兼容性**:`exact` 方案(EVM 和 TRON)符合 **x402 Foundation** 发布的 v2 线格式。标准 v2 client 可与本 SDK 的 server 互通,反之亦然。详见[网络与代币支持 → `exact` 方案](./core-concepts/network-and-token-support.md#exact-scheme)。 + +--- + +## Signer + +密钥托管在 [`@bankofai/agent-wallet`](https://github.com/BofAI/agent-wallet) 中;SDK 从不接触原始私钥。signer 工厂内部构建链 client(viem / TronWeb)。 + +| signer 工厂 | 角色 | +|----------|------| +| `createClientTronSigner` | Client(TRON) | +| `createClientEvmSigner` | Client(EVM) | +| `createFacilitatorTronSigner` | Facilitator(TRON) | +| `createFacilitatorEvmSigner` | Facilitator(EVM) | +| `createAuthorizerTronSigner` | Authorizer(TRON,batch-settlement) | + +--- + +## Client 功能 + +| 功能 | 状态 | +|------------|--------| +| 自动处理 402(`wrapFetchWithPayment`) | ✅ | +| 自动 Permit2 / 代币授权 | ✅ | +| 授权额度检查 | ✅ | +| 签名(TRON,TIP-712) | ✅ | +| 签名(EVM,EIP-712) | ✅ | +| 余额感知的付款选择(`filterAffordableRequirements`) | ✅ | +| 最低价代币选择策略 | ✅ | +| GasFree(零 gas TRON 付款) | ✅ | + +--- + +## Server 功能 + +| 功能 | 状态 | +|------------|--------| +| 受保护路由集成 | ✅(`paymentMiddlewareFromHTTPServer`、`x402HTTPResourceServer`) | +| 多链 `accepts` 公布 | ✅ | +| gas 赞助扩展(Permit2 approve) | ✅ | +| 付款验证(通过 facilitator) | ✅ | +| 付款结算(通过 facilitator) | ✅ | +| 费率支持 | ✅ | + +--- + +## Facilitator 功能 + +| 功能 | 状态 | +|------------|--------| +| `POST /verify` 端点 | ✅ | +| `POST /settle` 端点 | ✅ | +| `GET /supported` 端点 | ✅ | +| 提交链上交易 | ✅ | +| 确认交易(回执轮询) | ✅ | +| 扩展钩子(`onBeforeSettle` / `onAfterSettle` / `onSettleFailure`) | ✅ | + +> 自托管示例 facilitator(`facilitator/basic`)暴露 `/verify`、`/settle`、`/supported`。官方托管 facilitator 额外提供 `/fee/quote` 和 `/payments/{id}` 查询端点——详见[官方 Facilitator](./core-concepts/OfficialFacilitator.md)。 + +--- + +## 支持的代币 + +| 代币 | 网络 | 状态 | +|--------|---------|--------| +| USDT(TRC-20) | `tron:mainnet`、`tron:nile` | ✅ | +| USDD(TRC-20) | `tron:mainnet`、`tron:nile` | ✅ | +| USDT(BEP-20) | `eip155:56`、`eip155:97` | ✅ | +| USDC(BEP-20) | `eip155:56`、`eip155:97` | ✅ | +| DHLU(BSC 测试网,ERC-3009) | `eip155:97` | ✅ | +| 自定义 TRC-20 / BEP-20 | 任意 | ✅(通过代币注册表 / `EVM_TOKENS` 配置) | + +--- + +## 可观测性 + +所有 `@bankofai/x402-*` 包通过 `@bankofai/x402-core` 的一个进程级 logger 输出日志。启动时调用一次 `setLogger(...)` 即可将日志重定向到文件、`pino`/`winston`,或用 `noopLogger` 静默。 + +--- + +## 图例 - ✅ = 已实现 -- ⏳ = 计划中 / 开发中 -- ❌ = 无计划 \ No newline at end of file +- ⏳ = 计划中 / 进行中 +- ❌ = 不计划 From 532a72063d5b74177e20cf57ccd717893aab9603 Mon Sep 17 00:00:00 2001 From: "roger.gan" Date: Sun, 5 Jul 2026 08:01:13 +0800 Subject: [PATCH 02/12] docs(x402): replace x402-demo reference in README with examples link The x402-demo repository is deprecated; point readers to the runnable examples in the x402 repository (examples/typescript/) instead. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cb9f1a15..1c868857 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ OpenClaw is a financial extension plugin developed by BANK OF AI for AI agents, ## 🏗️ Developer Resources - **Documentation Center**: [docs.bankofai.io](https://docs.bankofai.io) -- **Live Demo**: [x402-demo Repository](https://github.com/BofAI/x402-demo) +- **Runnable Examples**: [x402 repository — `examples/typescript/`](https://github.com/BofAI/x402/tree/main/examples/typescript) - **Technical Support**: Submit issues or join discussions on GitHub. --- From c95962633d7f79aa3293daaca0f1b2d9b5d2f17d Mon Sep 17 00:00:00 2001 From: "roger.gan" Date: Sun, 5 Jul 2026 08:04:39 +0800 Subject: [PATCH 03/12] docs(x402): rename README examples link to Reference Examples --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1c868857..de66b252 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ OpenClaw is a financial extension plugin developed by BANK OF AI for AI agents, ## 🏗️ Developer Resources - **Documentation Center**: [docs.bankofai.io](https://docs.bankofai.io) -- **Runnable Examples**: [x402 repository — `examples/typescript/`](https://github.com/BofAI/x402/tree/main/examples/typescript) +- **Reference Examples**: [x402-examples](https://github.com/BofAI/x402/tree/main/examples/typescript) - **Technical Support**: Submit issues or join discussions on GitHub. --- From fbdcc200722aa1e17b6c8a7e56811c616ed89659 Mon Sep 17 00:00:00 2001 From: "roger.gan" Date: Sun, 5 Jul 2026 08:20:41 +0800 Subject: [PATCH 04/12] docs(x402): fix review findings P1/P2 (install path, v2 payload, Node 22) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address code-review findings across EN + zh-Hans quickstarts and http-402: P1: Fix install path — examples live at x402/examples/typescript (a separate workspace), not under x402/typescript. Use cd ../examples/typescript and run a second pnpm install there (4 quickstarts). P1: Fix PAYMENT-SIGNATURE examples to match v2 PaymentPayload — top-level {x402Version, accepted, payload} (no top-level scheme/network), Permit2 data under payload.permit2Authorization with permitted/spender/nonce/ deadline/witness/from, all numeric fields as strings. P1: Remove erc20ApprovalGasSponsoring from the TRON payment-required example (EVM-only extension; TRON server does not declare it). P2: Complete the agent quickstart local-test flow — add clone, install, build, and split-terminal facilitator/server steps. P2: Bump Node.js requirement 20 -> 22 and pnpm 11 -> 11.1 (matches the SDK engines field). P2: Sync zh-Hans agent quickstart — add SDK 1.0.0 note, MCP examples entry, BSC EVM_RPC_URL config. Remove // comments from JSON code blocks (now valid JSON) and strip trailing whitespace. --- docs/x402/core-concepts/http-402.md | 65 ++++++++++--------- .../getting-started/quickstart-for-agent.md | 27 ++++++-- .../getting-started/quickstart-for-human.md | 12 ++-- .../getting-started/quickstart-for-sellers.md | 14 ++-- .../current/x402/core-concepts/http-402.md | 61 +++++++++-------- .../getting-started/quickstart-for-agent.md | 37 +++++++++-- .../getting-started/quickstart-for-human.md | 12 ++-- .../getting-started/quickstart-for-sellers.md | 14 ++-- 8 files changed, 147 insertions(+), 95 deletions(-) diff --git a/docs/x402/core-concepts/http-402.md b/docs/x402/core-concepts/http-402.md index 07a636f9..79774bd9 100644 --- a/docs/x402/core-concepts/http-402.md +++ b/docs/x402/core-concepts/http-402.md @@ -69,12 +69,7 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- } } } - ], - "extensions": { - // Present only when the token needs a gas-sponsored Permit2 approve - // (plain ERC-20 like BSC USDC). ERC-3009 tokens omit this. - "erc20ApprovalGasSponsoring": {} - } + ] } ``` @@ -111,8 +106,6 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- } ], "extensions": { - // BSC USDT is a plain ERC-20 → the Permit2 path needs this gas-sponsoring - // extension so the client can sign the one-time approve offline. "erc20ApprovalGasSponsoring": {} } } @@ -148,18 +141,24 @@ The client responds via the `PAYMENT-SIGNATURE` header with a signed payload: ```json { "x402Version": 2, - "scheme": "exact", - "network": "tron:nile", + "accepted": { + "scheme": "exact", + "network": "tron:nile", + "asset": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", + "amount": "100", + "payTo": "", + "maxTimeoutSeconds": 3600, + "extra": { "assetTransferMethod": "permit2" } + }, "payload": { "signature": "0x...", - "authorization": { - // Permit2 witness (USDT/USDD on TRON are plain TRC-20) - "from": "", - "to": "", - "value": 100, - "validAfter": 1770817311, - "validBefore": 1770820911, - "nonce": "0x65f9d4ca3fb5f6dd14930055aa5ccbc4" + "permit2Authorization": { + "permitted": { "token": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", "amount": "100" }, + "spender": "", + "nonce": "0", + "deadline": "1770820911", + "witness": { "to": "", "validAfter": "1770817311" }, + "from": "" } } } @@ -171,18 +170,24 @@ The client responds via the `PAYMENT-SIGNATURE` header with a signed payload: ```json { "x402Version": 2, - "scheme": "exact", - "network": "eip155:97", + "accepted": { + "scheme": "exact", + "network": "eip155:97", + "asset": "0x337610d27c682E347C9cD60BD4b3b107C9d34dDd", + "amount": "100000000000000", + "payTo": "", + "maxTimeoutSeconds": 3600, + "extra": { "assetTransferMethod": "permit2" } + }, "payload": { "signature": "0x...", - "authorization": { - // Permit2 witness (BSC USDT is a plain ERC-20) - "from": "", - "to": "", - "value": 100000000000000, - "validAfter": 1770817158, - "validBefore": 1770820758, - "nonce": "0xc00fc79b9a26084ad078b71ffcaa07fd" + "permit2Authorization": { + "permitted": { "token": "0x337610d27c682E347C9cD60BD4b3b107C9d34dDd", "amount": "100000000000000" }, + "spender": "", + "nonce": "0", + "deadline": "1770820758", + "witness": { "to": "", "validAfter": "1770817158" }, + "from": "" } } } @@ -203,5 +208,5 @@ HTTP 402 is the foundation of the x402 protocol. It enables servers to integrate Next, explore: -- [Client / Server](./client-server.md) — Understand the roles and responsibilities of clients and servers -- [Facilitator](./facilitator.md) — Learn how servers verify and settle payments +- [Client / Server](./client-server.md) — Understand the roles and responsibilities of clients and servers +- [Facilitator](./facilitator.md) — Learn how servers verify and settle payments diff --git a/docs/x402/getting-started/quickstart-for-agent.md b/docs/x402/getting-started/quickstart-for-agent.md index e266fbf5..7135ab06 100644 --- a/docs/x402/getting-started/quickstart-for-agent.md +++ b/docs/x402/getting-started/quickstart-for-agent.md @@ -138,16 +138,33 @@ After completing the setup, follow these steps to verify your agent can complete ### 3.1 Test with a Local Paid Endpoint -Start the example trio from `examples/typescript`, then point your agent at the local server: +First, get the SDK and examples (requires **Node.js 22+** and **pnpm 11.1+**): ```bash -cd x402/examples/typescript +git clone https://github.com/BofAI/x402.git +cd x402/typescript # the pnpm/turbo monorepo root (SDK packages) + +# Install + link the SDK packages, then build their dist +pnpm install +pnpm build + +# Examples live in a separate workspace at the repo root +cd ../examples/typescript +pnpm install # links the in-repo SDK packages + example deps cp .env-exact.example .env-exact # fill AGENT_WALLET_PRIVATE_KEY + payout addresses -pnpm dev:facilitator # terminal 1 (:4022) -pnpm dev:server # terminal 2 (:4021) ``` -Then instruct your agent to access `http://localhost:4021/weather`. +Then start the facilitator and the resource server **in two separate terminals** (both from `examples/typescript`): + +```bash +# Terminal 1 — facilitator (verifies + settles on-chain) +pnpm dev:facilitator # http://localhost:4022 + +# Terminal 2 — resource server (sells GET /weather behind 402) +pnpm dev:server # http://localhost:4021 +``` + +Once both are running, instruct your agent to access `http://localhost:4021/weather`. **The agent should automatically complete the following flow (no human intervention required):** diff --git a/docs/x402/getting-started/quickstart-for-human.md b/docs/x402/getting-started/quickstart-for-human.md index 59b8c027..da721b41 100644 --- a/docs/x402/getting-started/quickstart-for-human.md +++ b/docs/x402/getting-started/quickstart-for-human.md @@ -31,7 +31,7 @@ x402 `1.0.0` is a **TypeScript-only** SDK published as granular `@bankofai/x402- ### Checklist Before You Start -- [ ] **Node.js 20+** and **pnpm 11+** installed +- [ ] **Node.js 22+** and **pnpm 11.1+** installed - [ ] A dedicated **test wallet** created (see below) - [ ] Test tokens claimed (free) - [ ] A target x402-protected API URL (or run the example server) @@ -95,15 +95,15 @@ The examples workspace links the in-repo `@bankofai/x402-*` packages and runs fr ```bash git clone https://github.com/BofAI/x402.git -cd x402/typescript # the pnpm/turbo monorepo root +cd x402/typescript # the pnpm/turbo monorepo root (SDK packages) -# Install + link all workspace packages (SDK + examples) +# Install + link the SDK packages, then build their dist pnpm install - -# Build the @bankofai/x402-* dist the examples import from pnpm build -cd examples/typescript +# Examples live in a separate workspace at the repo root +cd ../examples/typescript +pnpm install # links the in-repo SDK packages + example deps ``` The fetch client depends on `@bankofai/x402-fetch`, `@bankofai/x402-evm`, `@bankofai/x402-tron`, and `@bankofai/agent-wallet` — all linked automatically by `pnpm install`. diff --git a/docs/x402/getting-started/quickstart-for-sellers.md b/docs/x402/getting-started/quickstart-for-sellers.md index cc093644..33d32bf5 100644 --- a/docs/x402/getting-started/quickstart-for-sellers.md +++ b/docs/x402/getting-started/quickstart-for-sellers.md @@ -28,8 +28,8 @@ x402 `1.0.0` is a **TypeScript-only** pnpm/turbo monorepo published as granular In your terminal (Terminal on macOS/Linux, or PowerShell/Command Prompt on Windows), run the following commands to confirm the required tools are installed: ```bash -node --version # Requires Node.js 20 or higher -pnpm --version # Requires pnpm 11 or higher +node --version # Requires Node.js 22 or higher +pnpm --version # Requires pnpm 11.1 or higher git --version # Version control tool ``` @@ -118,15 +118,15 @@ The examples workspace links the in-repo `@bankofai/x402-*` packages and builds ```bash git clone https://github.com/BofAI/x402.git -cd x402/typescript # the pnpm/turbo monorepo root +cd x402/typescript # the pnpm/turbo monorepo root (SDK packages) -# Install + link all workspace packages (SDK + examples) +# Install + link the SDK packages, then build their dist pnpm install - -# Build the @bankofai/x402-* dist the examples import from pnpm build -cd examples/typescript +# Examples live in a separate workspace at the repo root +cd ../examples/typescript +pnpm install # links the in-repo SDK packages + example deps ``` Verify the install by starting the example resource server (it will print a port and the chains it accepts): diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/http-402.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/http-402.md index 8822941a..093b20f7 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/http-402.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/http-402.md @@ -69,12 +69,7 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: } } } - ], - "extensions": { - // 仅当代币需要 gas 赞助的 Permit2 approve 时才出现 - // (如 BSC USDC 等普通 ERC-20)。ERC-3009 代币省略此项。 - "erc20ApprovalGasSponsoring": {} - } + ] } ``` @@ -111,8 +106,6 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: } ], "extensions": { - // BSC USDT 是普通 ERC-20 → Permit2 路径需要此 gas 赞助 - // 扩展,以便客户端离线签署一次性 approve。 "erc20ApprovalGasSponsoring": {} } } @@ -147,18 +140,24 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: ```json { "x402Version": 2, - "scheme": "exact", - "network": "tron:nile", + "accepted": { + "scheme": "exact", + "network": "tron:nile", + "asset": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", + "amount": "100", + "payTo": "", + "maxTimeoutSeconds": 3600, + "extra": { "assetTransferMethod": "permit2" } + }, "payload": { "signature": "0x...", - "authorization": { - // Permit2 witness(TRON 上的 USDT/USDD 为普通 TRC-20) - "from": "", - "to": "", - "value": 100, - "validAfter": 1770817311, - "validBefore": 1770820911, - "nonce": "0x65f9d4ca3fb5f6dd14930055aa5ccbc4" + "permit2Authorization": { + "permitted": { "token": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", "amount": "100" }, + "spender": "", + "nonce": "0", + "deadline": "1770820911", + "witness": { "to": "", "validAfter": "1770817311" }, + "from": "" } } } @@ -170,18 +169,24 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: ```json { "x402Version": 2, - "scheme": "exact", - "network": "eip155:97", + "accepted": { + "scheme": "exact", + "network": "eip155:97", + "asset": "0x337610d27c682E347C9cD60BD4b3b107C9d34dDd", + "amount": "100000000000000", + "payTo": "", + "maxTimeoutSeconds": 3600, + "extra": { "assetTransferMethod": "permit2" } + }, "payload": { "signature": "0x...", - "authorization": { - // Permit2 witness(BSC USDT 为普通 ERC-20) - "from": "", - "to": "", - "value": 100000000000000, - "validAfter": 1770817158, - "validBefore": 1770820758, - "nonce": "0xc00fc79b9a26084ad078b71ffcaa07fd" + "permit2Authorization": { + "permitted": { "token": "0x337610d27c682E347C9cD60BD4b3b107C9d34dDd", "amount": "100000000000000" }, + "spender": "", + "nonce": "0", + "deadline": "1770820758", + "witness": { "to": "", "validAfter": "1770817158" }, + "from": "" } } } diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-agent.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-agent.md index 5f6fcaa1..8376931a 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-agent.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-agent.md @@ -9,6 +9,10 @@ x402 专为 Agentic Web 设计。通过安装 `x402-payment` 技能,AI 代理 --- +:::info SDK 1.0.0(仅 TypeScript) +x402 `1.0.0` 是**仅 TypeScript** 的 SDK。`x402-payment` 技能封装了新的 `@bankofai/x402-*` 包,并使用 [Agent Wallet](../../Agent-Wallet/QuickStart.md) 托管密钥——本指南中的钱包/私钥配置方式不变。您也可以直接使用仓库中的可运行 [MCP 示例](https://github.com/BofAI/x402/tree/main/examples/typescript)(`servers/mcp` + `clients/mcp`)驱动付款。 +::: + ## 前置准备 ### 1. 创建代理专用钱包 @@ -89,7 +93,11 @@ export TRON_GRID_API_KEY="在此填入TronGrid API Key" -BSC 无需额外配置。 +BSC 测试网默认的 viem RPC 端点经常不可达。请设置可靠的 RPC: + +```bash +export EVM_RPC_URL="https://bsc-testnet-rpc.publicnode.com" +``` @@ -130,16 +138,33 @@ npx skills add https://github.com/BofAI/skills ### 3.1 使用本地付费接口测试 -从 `examples/typescript` 启动示例三件套,然后将代理指向本地服务器: +首先,获取 SDK 与示例(需要 **Node.js 22+** 和 **pnpm 11.1+**): ```bash -cd x402/examples/typescript +git clone https://github.com/BofAI/x402.git +cd x402/typescript # pnpm/turbo monorepo 根目录(SDK 包) + +# 安装并链接 SDK 包,然后构建其 dist +pnpm install +pnpm build + +# 示例位于仓库根目录下的独立工作区 +cd ../examples/typescript +pnpm install # 链接仓库内 SDK 包 + 示例依赖 cp .env-exact.example .env-exact # 填入 AGENT_WALLET_PRIVATE_KEY + 收款地址 -pnpm dev:facilitator # 终端 1(:4022) -pnpm dev:server # 终端 2(:4021) ``` -然后指示您的代理访问 `http://localhost:4021/weather`。 +然后在**两个独立终端**启动 facilitator 和资源服务器(均在 `examples/typescript` 下): + +```bash +# 终端 1 —— facilitator(验证并链上结算) +pnpm dev:facilitator # http://localhost:4022 + +# 终端 2 —— 资源服务器(将 GET /weather 保护在 402 之后) +pnpm dev:server # http://localhost:4021 +``` + +两者都运行后,指示您的代理访问 `http://localhost:4021/weather`。 **代理应自动完成以下流程(无需人工干预):** diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md index fb98fbbe..01ae79a4 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md @@ -31,7 +31,7 @@ x402 `1.0.0` 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` ### 开始前清单 -- [ ] 已安装 **Node.js 20+** 和 **pnpm 11+** +- [ ] 已安装 **Node.js 22+** 和 **pnpm 11.1+** - [ ] 已创建专用**测试钱包**(见下文) - [ ] 已领取测试代币(免费) - [ ] 有一个目标 x402 保护的 API URL(或运行示例 server) @@ -95,15 +95,15 @@ x402 `1.0.0` 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` ```bash git clone https://github.com/BofAI/x402.git -cd x402/typescript # pnpm/turbo monorepo 根目录 +cd x402/typescript # pnpm/turbo monorepo 根目录(SDK 包) -# 安装并链接所有工作区包(SDK + 示例) +# 安装并链接 SDK 包,然后构建其 dist pnpm install - -# 构建示例所依赖的 @bankofai/x402-* dist pnpm build -cd examples/typescript +# 示例位于仓库根目录下的独立工作区 +cd ../examples/typescript +pnpm install # 链接仓库内 SDK 包 + 示例依赖 ``` fetch client 依赖 `@bankofai/x402-fetch`、`@bankofai/x402-evm`、`@bankofai/x402-tron` 和 `@bankofai/agent-wallet`——全部由 `pnpm install` 自动链接。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-sellers.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-sellers.md index 392d7ffc..4e42a246 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-sellers.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-sellers.md @@ -28,8 +28,8 @@ x402 `1.0.0` 是一个**仅 TypeScript** 的 pnpm/turbo monorepo,以颗粒化 在终端(macOS/Linux 的 Terminal,或 Windows 的 PowerShell/命令提示符)中运行以下命令,确认所需工具已安装: ```bash -node --version # 需要 Node.js 20 或更高版本 -pnpm --version # 需要 pnpm 11 或更高版本 +node --version # 需要 Node.js 22 或更高版本 +pnpm --version # 需要 pnpm 11.1 或更高版本 git --version # 版本控制工具 ``` @@ -118,15 +118,15 @@ git --version # 版本控制工具 ```bash git clone https://github.com/BofAI/x402.git -cd x402/typescript # pnpm/turbo monorepo 根目录 +cd x402/typescript # pnpm/turbo monorepo 根目录(SDK 包) -# 安装并链接所有工作区包(SDK + 示例) +# 安装并链接 SDK 包,然后构建其 dist pnpm install - -# 构建示例所依赖的 @bankofai/x402-* dist pnpm build -cd examples/typescript +# 示例位于仓库根目录下的独立工作区 +cd ../examples/typescript +pnpm install # 链接仓库内 SDK 包 + 示例依赖 ``` 通过启动示例资源服务器来验证安装(它会打印端口和所接受的链): From 573d008b3eeeefea3edc5d1e3845a221bac56b70 Mon Sep 17 00:00:00 2001 From: "roger.gan" Date: Sun, 5 Jul 2026 08:33:00 +0800 Subject: [PATCH 05/12] docs(x402): strip trailing whitespace, fix TRON permit2 hex & assetTransferMethod - Remove 5 trailing-whitespace lines flagged by git diff --check (README, client-server, network-and-token-support, faq) - faq.md: 'runnable examples' -> 'reference examples' (per earlier review: Runnable Examples -> Reference Examples) - http-402.md (EN+ZH): convert permit2Authorization addresses (permitted.token, spender, witness.to, from) to 0x hex for EIP-712/TIP-712 signing; accepted.asset/payTo stay Base58 (TRON) - http-402.md (EN+ZH): replace extra name/version with assetTransferMethod: "permit2" for TRON + BSC so clients pick Permit2 over ERC-3009 --- README.md | 32 +++++------ docs/x402/core-concepts/client-server.md | 50 ++++++++--------- docs/x402/core-concepts/http-402.md | 16 +++--- .../network-and-token-support.md | 28 +++++----- docs/x402/faq.md | 56 +++++++++---------- .../current/x402/core-concepts/http-402.md | 16 +++--- 6 files changed, 99 insertions(+), 99 deletions(-) diff --git a/README.md b/README.md index de66b252..30c3fd1f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 🚀 BANK OF AI +# 🚀 BANK OF AI **Building a Decentralized Financial Sovereignty and Commercial Interconnection Layer for AI Agents** @@ -16,9 +16,9 @@ Currently supports **TRON** and **BSC**, with more blockchain networks coming in x402 is an open blockchain payment protocol based on the HTTP `402 Payment Required` status code. It removes payment friction in M2M (machine-to-machine) interactions for AI agents. -- **Payment-as-Response**: Enables a “pay-before-response” mechanism without complex account registration or session management. -- **Multi-Chain Support**: Currently supports **TRON** (Mainnet/Shasta/Nile) and **BSC** (Mainnet/Testnet); More blockchain networks will be supported in the future. -- **AI-Friendly**: Supports signed payloads, allowing agents to complete settlements automatically. +- **Payment-as-Response**: Enables a “pay-before-response” mechanism without complex account registration or session management. +- **Multi-Chain Support**: Currently supports **TRON** (Mainnet/Shasta/Nile) and **BSC** (Mainnet/Testnet); More blockchain networks will be supported in the future. +- **AI-Friendly**: Supports signed payloads, allowing agents to complete settlements automatically. - **Use Cases**: Pay-per-request APIs, paywalls, and automated settlement between agents. --- @@ -27,9 +27,9 @@ x402 is an open blockchain payment protocol based on the HTTP `402 Payment Requi Built on the Model Context Protocol (MCP) architecture, providing full on-chain execution capabilities for agents. -- **Infrastructure Layer (MCP Server)**: The agent’s **“hands and eyes.”** Provides a unified interface to read blocks, manage wallets, execute transfers, and interact with any contract. -- **Application Logic Layer (Skills)**: The agent’s **“brain.”** Uses structured instructions (`SKILL.md`) to guide AI in orchestrating underlying tools. - - **sunswap**: Enables automated DEX swaps. +- **Infrastructure Layer (MCP Server)**: The agent’s **“hands and eyes.”** Provides a unified interface to read blocks, manage wallets, execute transfers, and interact with any contract. +- **Application Logic Layer (Skills)**: The agent’s **“brain.”** Uses structured instructions (`SKILL.md`) to guide AI in orchestrating underlying tools. + - **sunswap**: Enables automated DEX swaps. - **x402-payment**: Allows agents to detect payment requirements and execute payments automatically. --- @@ -38,8 +38,8 @@ Built on the Model Context Protocol (MCP) architecture, providing full on-chain OpenClaw is a financial extension plugin developed by BANK OF AI for AI agents, aiming to become the “central bank” of the agent economy. -- **Wallet Ownership**: Enables agents to truly control and manage on-chain assets. -- **Autonomous Spending**: Agents can independently pay for computation, storage, and data resources. +- **Wallet Ownership**: Enables agents to truly control and manage on-chain assets. +- **Autonomous Spending**: Agents can independently pay for computation, storage, and data resources. - **Seamless Integration**: Built-in MCP server and automatic skill installer for plug-and-play setup. --- @@ -57,27 +57,27 @@ OpenClaw is a financial extension plugin developed by BANK OF AI for AI agents, ## 🚦 Quick Start -### 🚀 For Sellers +### 🚀 For Sellers *Want to monetize your API, content, or services?* -1. **Integrate x402**: Deploy server-side logic to detect payment requirements and return a `402` status code with payment instructions. +1. **Integrate x402**: Deploy server-side logic to detect payment requirements and return a `402` status code with payment instructions. 2. **Publish Skills**: Write a `SKILL.md` for your service so other AI agents can understand how to interact with it. --- -### 🤖 For Agents/Buyers +### 🤖 For Agents/Buyers *Want your agent to have autonomous payment and on-chain interaction capabilities?* -1. **Install OpenClaw**: Configure your environment and connect to the [mcp-server-tron](https://github.com/BofAI/mcp-server-tron). -2. **Sync Skills**: Load `sunswap` or `x402-payment` from the [skills](https://github.com/BofAI/skills) repository. +1. **Install OpenClaw**: Configure your environment and connect to the [mcp-server-tron](https://github.com/BofAI/mcp-server-tron). +2. **Sync Skills**: Load `sunswap` or `x402-payment` from the [skills](https://github.com/BofAI/skills) repository. 3. **Start Transacting**: Your agent can now automatically process payment requests from sellers and execute settlements. --- ## 🏗️ Developer Resources -- **Documentation Center**: [docs.bankofai.io](https://docs.bankofai.io) -- **Reference Examples**: [x402-examples](https://github.com/BofAI/x402/tree/main/examples/typescript) +- **Documentation Center**: [docs.bankofai.io](https://docs.bankofai.io) +- **Reference Examples**: [x402-examples](https://github.com/BofAI/x402/tree/main/examples/typescript) - **Technical Support**: Submit issues or join discussions on GitHub. --- diff --git a/docs/x402/core-concepts/client-server.md b/docs/x402/core-concepts/client-server.md index a968f5d8..78947356 100644 --- a/docs/x402/core-concepts/client-server.md +++ b/docs/x402/core-concepts/client-server.md @@ -15,17 +15,17 @@ The client is the entity that initiates requests to access paid resources. Clients can take many forms, including: -- User-facing applications -- Autonomous agents -- Backend services acting on behalf of users or systems +- User-facing applications +- Autonomous agents +- Backend services acting on behalf of users or systems ### Core Responsibilities -- **Initiate Requests**: Send the initial HTTP request to the resource server. -- **Handle Payment Requirements**: Parse the `402 Payment Required` response and extract payment details. -- **Manage Token Approvals**: Authorize Permit2 (one-time `approve(Permit2)`) for plain ERC-20/TRC-20 tokens; ERC-3009 tokens need no approve. The SDK auto-broadcasts this on first payment. -- **Prepare Payment Payload**: Construct and sign a payment payload according to server requirements. -- **Retry with Payment**: Attach the `PAYMENT-SIGNATURE` header and resend the request. +- **Initiate Requests**: Send the initial HTTP request to the resource server. +- **Handle Payment Requirements**: Parse the `402 Payment Required` response and extract payment details. +- **Manage Token Approvals**: Authorize Permit2 (one-time `approve(Permit2)`) for plain ERC-20/TRC-20 tokens; ERC-3009 tokens need no approve. The SDK auto-broadcasts this on first payment. +- **Prepare Payment Payload**: Construct and sign a payment payload according to server requirements. +- **Retry with Payment**: Attach the `PAYMENT-SIGNATURE` header and resend the request. The client **does not** need to maintain any account system, login credentials, or session tokens beyond its wallet. All interactions are **stateless** and fully based on standard HTTP protocols. @@ -37,16 +37,16 @@ The server is the provider that requires payment before granting access to its r Servers may include: -- API services -- Digital content providers -- Any HTTP-accessible resource seeking monetization +- API services +- Digital content providers +- Any HTTP-accessible resource seeking monetization ### Core Responsibilities -- **Define Payment Requirements**: Respond with HTTP `402 Payment Required` when a request lacks valid payment credentials, detailing payment requirements in the response body. -- **Validate Payment Payload**: Call the Facilitator service to verify the incoming signed payload. -- **Settle Transactions**: Upon successful validation, submit the transaction via the Facilitator to complete on-chain settlement. -- **Deliver Resources**: After confirming payment, return the requested resource to the client. +- **Define Payment Requirements**: Respond with HTTP `402 Payment Required` when a request lacks valid payment credentials, detailing payment requirements in the response body. +- **Validate Payment Payload**: Call the Facilitator service to verify the incoming signed payload. +- **Settle Transactions**: Upon successful validation, submit the transaction via the Facilitator to complete on-chain settlement. +- **Deliver Resources**: After confirming payment, return the requested resource to the client. The server **does not** need to manage client identity or maintain session state. Validation and settlement are handled independently for each request through the Facilitator. @@ -56,12 +56,12 @@ The server **does not** need to manage client identity or maintain session state In the x402 protocol, a typical interaction between client and server proceeds as follows: -1. **Client Initiates Request**: Sends a request for a paid resource to the server. -2. **Server Requires Payment**: Responds with `402 Payment Required`, including payment details in the `PAYMENT-REQUIRED` header (Base64-encoded). -3. **Client Submits Payment**: Generates a signature and resends the request with the signed payload in the `PAYMENT-SIGNATURE` header (Base64-encoded). -4. **Server Validates Payment**: Calls the Facilitator service to verify the received payment payload. -5. **Server Executes Settlement**: Submits the transaction to the blockchain via the Facilitator. -6. **Server Delivers Resource**: Returns the requested resource and includes settlement confirmation (with transaction hash) in the `PAYMENT-RESPONSE` header. +1. **Client Initiates Request**: Sends a request for a paid resource to the server. +2. **Server Requires Payment**: Responds with `402 Payment Required`, including payment details in the `PAYMENT-REQUIRED` header (Base64-encoded). +3. **Client Submits Payment**: Generates a signature and resends the request with the signed payload in the `PAYMENT-SIGNATURE` header (Base64-encoded). +4. **Server Validates Payment**: Calls the Facilitator service to verify the received payment payload. +5. **Server Executes Settlement**: Submits the transaction to the blockchain via the Facilitator. +6. **Server Delivers Resource**: Returns the requested resource and includes settlement confirmation (with transaction hash) in the `PAYMENT-RESPONSE` header. --- @@ -69,8 +69,8 @@ In the x402 protocol, a typical interaction between client and server proceeds a Within the x402 protocol architecture: -- **Client**: Initiates resource requests and provides a signed payment payload. -- **Server**: Enforces payment policy, verifies transaction validity, and delivers resources upon successful payment confirmation. +- **Client**: Initiates resource requests and provides a signed payment payload. +- **Server**: Enforces payment policy, verifies transaction validity, and delivers resources upon successful payment confirmation. This interaction model is fully based on native HTTP, maintains a **stateless** architecture, and is compatible with both user-facing applications and autonomous agents. @@ -80,5 +80,5 @@ This interaction model is fully based on native HTTP, maintains a **stateless** Continue exploring: -- [Facilitator](./facilitator.md) — Learn how servers validate and settle payments -- [Wallet](./wallet.md) — Learn how to manage wallets used for payments +- [Facilitator](./facilitator.md) — Learn how servers validate and settle payments +- [Wallet](./wallet.md) — Learn how to manage wallets used for payments diff --git a/docs/x402/core-concepts/http-402.md b/docs/x402/core-concepts/http-402.md index 79774bd9..b3bba79f 100644 --- a/docs/x402/core-concepts/http-402.md +++ b/docs/x402/core-concepts/http-402.md @@ -41,6 +41,8 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- +> **Note:** On TRON, `accepted.asset` and `accepted.payTo` use Base58 addresses, but the addresses inside `permit2Authorization` (`permitted.token`, `spender`, `witness.to`, `from`) are converted to `0x` hex form for EIP-712/TIP-712 signing. + ```json { "x402Version": 2, @@ -59,8 +61,7 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- "payTo": "", "maxTimeoutSeconds": 3600, "extra": { - "name": "Tether USD", - "version": "1", + "assetTransferMethod": "permit2", "fee": { "facilitatorId": "", "feeTo": "", @@ -94,8 +95,7 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- "payTo": "", "maxTimeoutSeconds": 3600, "extra": { - "name": "Tether USD", - "version": "1", + "assetTransferMethod": "permit2", "fee": { "facilitatorId": "", "feeTo": "", @@ -153,12 +153,12 @@ The client responds via the `PAYMENT-SIGNATURE` header with a signed payload: "payload": { "signature": "0x...", "permit2Authorization": { - "permitted": { "token": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", "amount": "100" }, - "spender": "", + "permitted": { "token": "0x...", "amount": "100" }, + "spender": "0x...", "nonce": "0", "deadline": "1770820911", - "witness": { "to": "", "validAfter": "1770817311" }, - "from": "" + "witness": { "to": "0x...", "validAfter": "1770817311" }, + "from": "0x..." } } } diff --git a/docs/x402/core-concepts/network-and-token-support.md b/docs/x402/core-concepts/network-and-token-support.md index 42b03c4d..78afa64c 100644 --- a/docs/x402/core-concepts/network-and-token-support.md +++ b/docs/x402/core-concepts/network-and-token-support.md @@ -5,7 +5,7 @@ import TabItem from '@theme/TabItem'; ## TRON Network Identifiers -x402 adopts a standardized network identifier format: `tron:`. +x402 adopts a standardized network identifier format: `tron:`. The `` can be `mainnet`, `shasta`, or `nile`. ### Identifier Reference @@ -33,7 +33,7 @@ In the x402 protocol (on-the-wire), BSC uses the EIP-155 chain ID format: ## Overview -x402 is purpose-built for blockchain ecosystems, enabling native on-chain payment verification and settlement. +x402 is purpose-built for blockchain ecosystems, enabling native on-chain payment verification and settlement. The protocol uses secure signing mechanisms to ensure tamper-resistant message authorization. ### Supported Networks @@ -50,7 +50,7 @@ The protocol uses secure signing mechanisms to ensure tamper-resistant message a ## Supported Tokens -x402 fully supports **TRC-20 and BEP-20** standard tokens. +x402 fully supports **TRC-20 and BEP-20** standard tokens. By default, **USDT** and **USDD** are used as primary settlement currencies. ### Supported Token List @@ -79,13 +79,13 @@ x402 uses typed data signing for all payment-related signatures. ### Key Benefits -- **Off-chain Authorization** +- **Off-chain Authorization** Buyers sign transfer intent locally (off-chain) without locking funds in advance. -- **Trust-Minimized** +- **Trust-Minimized** Signatures include strict constraints (amount, recipient, expiration), preventing the Facilitator from moving funds beyond the explicitly authorized scope. -- **On-chain Verifiability** +- **On-chain Verifiability** All signatures can be cryptographically verified at the smart contract level, ensuring immutability and integrity. --- @@ -94,13 +94,13 @@ x402 uses typed data signing for all payment-related signatures. When configuring an `HTTP 402` payment request on the server side, you must explicitly define: -1. **Network** – The unique network identifier (e.g., `tron:nile`) -2. **Asset** – The TRC-20/BEP-20 token **contract address** -3. **Amount** – The integer value in the token’s **smallest unit (raw amount)** +1. **Network** – The unique network identifier (e.g., `tron:nile`) +2. **Asset** – The TRC-20/BEP-20 token **contract address** +3. **Amount** – The integer value in the token’s **smallest unit (raw amount)** -> **Precision Example** -> USDT on TRON uses **6 decimals**. -> To charge **1.0 USDT**, you must configure the amount as: +> **Precision Example** +> USDT on TRON uses **6 decimals**. +> To charge **1.0 USDT**, you must configure the amount as: > `1000000` --- @@ -223,7 +223,7 @@ x402 is deeply tailored for blockchain-native architectures, providing seamless ### Key Takeaways -- **Development Environment**: Use testnets for development and debugging. +- **Development Environment**: Use testnets for development and debugging. - **Default Settlement Asset**: **USDT** is the primary default token with preconfigured SDK support. - **Security Model**: TIP-712 / EIP-712 typed data signing ensures secure, trust-minimized payment authorization. -- **Extensibility**: Expand support for any custom TRC-20/BEP-20 token via the TRON token registry (`registerToken`) or the server's `EVM_TOKENS` config table. +- **Extensibility**: Expand support for any custom TRC-20/BEP-20 token via the TRON token registry (`registerToken`) or the server's `EVM_TOKENS` config table. diff --git a/docs/x402/faq.md b/docs/x402/faq.md index c051570c..483c3a2d 100644 --- a/docs/x402/faq.md +++ b/docs/x402/faq.md @@ -51,8 +51,8 @@ All payment payloads are **signed by the buyer**, and settlement is executed **d A Facilitator can only: -- Transfer the exact amount authorized by the buyer -- Send funds to the specific recipient address defined in the signed payload +- Transfer the exact amount authorized by the buyer +- Send funds to the specific recipient address defined in the signed payload --- @@ -62,9 +62,9 @@ A Facilitator can only: Common pricing models include: -- **Flat rate per call**: e.g., `1 USDT` per request -- **Tiered pricing**: Different prices for endpoints like `/basic` and `/pro` -- **`exact` scheme**: Pay the exact amount advertised per call +- **Flat rate per call**: e.g., `1 USDT` per request +- **Tiered pricing**: Different prices for endpoints like `/basic` and `/pro` +- **`exact` scheme**: Pay the exact amount advertised per call #### What payment schemes does x402 support? @@ -122,9 +122,9 @@ Custom TRC-20 tokens can be added via the TRON token registry (`registerToken` f **No.** Recommended security model: -1. **Buyer (client/agent)** signs locally (browser, serverless function, or agent VM). -2. **Seller** verifies signatures without accessing private keys. -3. **Facilitator** uses its own key to submit transactions on-chain. +1. **Buyer (client/agent)** signs locally (browser, serverless function, or agent VM). +2. **Seller** verifies signatures without accessing private keys. +3. **Facilitator** uses its own key to submit transactions on-chain. #### How does refunds work? @@ -132,8 +132,8 @@ The `exact` scheme uses a **push payment** model — once settled on-chain, it i Refund options: -1. **Business-layer refund**: Seller manually sends a new USDT transfer back to the buyer. -2. **Preventative settlement**: Server settles only the actual usage amount under the payment scheme. +1. **Business-layer refund**: Seller manually sends a new USDT transfer back to the buyer. +2. **Preventative settlement**: Server settles only the actual usage amount under the payment scheme. --- @@ -143,10 +143,10 @@ Refund options: The flow mirrors a human user: -1. Send initial request. -2. Parse `PAYMENT-REQUIRED` header in the response. -3. Sign the payment payload using the x402 client SDK. -4. Retry request with `PAYMENT-SIGNATURE` header attached. +1. Send initial request. +2. Parse `PAYMENT-REQUIRED` header in the response. +3. Sign the payment payload using the x402 client SDK. +4. Retry request with `PAYMENT-SIGNATURE` header attached. #### Does an agent need a wallet? @@ -169,13 +169,13 @@ The flow mirrors a human user: **TRON Nile** is recommended for TRON testing: -- Faucet: https://nileex.io/join/getJoinPage -- Explorer: https://nile.tronscan.org +- Faucet: https://nileex.io/join/getJoinPage +- Explorer: https://nile.tronscan.org **BSC Testnet** is recommended for BSC testing: -- Faucet: https://www.bnbchain.org/en/testnet-faucet -- Explorer: https://testnet.bscscan.com +- Faucet: https://www.bnbchain.org/en/testnet-faucet +- Explorer: https://testnet.bscscan.com --- @@ -185,21 +185,21 @@ The flow mirrors a human user: Common causes: -1. Invalid signature (incorrect domain or payload). -2. Insufficient payment amount. -3. Insufficient token allowance granted to Facilitator. -4. Insufficient wallet balance. +1. Invalid signature (incorrect domain or payload). +2. Insufficient payment amount. +3. Insufficient token allowance granted to Facilitator. +4. Insufficient wallet balance. Check the `error` field in the server’s JSON response for detailed diagnostics. #### It works on Nile but fails on Mainnet — why? -- Network configuration not updated -- Using testnet tokens instead of real mainnet tokens -- Facilitator lacks sufficient gas tokens -- Token contract address differs between networks +- Network configuration not updated +- Using testnet tokens instead of real mainnet tokens +- Facilitator lacks sufficient gas tokens +- Token contract address differs between networks ### Still Have Questions? -• Submit a GitHub Issue in the [x402 repository](https://github.com/BofAI/x402) -• Refer to the [runnable examples](https://github.com/BofAI/x402/tree/main/examples/typescript) in the x402 repository for a complete client → server → facilitator loop +• Submit a GitHub Issue in the [x402 repository](https://github.com/BofAI/x402) +• Refer to the [reference examples](https://github.com/BofAI/x402/tree/main/examples/typescript) in the x402 repository for a complete client → server → facilitator loop diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/http-402.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/http-402.md index 093b20f7..40a84e3a 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/http-402.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/http-402.md @@ -41,6 +41,8 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: +> **注意:** 在 TRON 上,`accepted.asset` 和 `accepted.payTo` 使用 Base58 地址,但 `permit2Authorization` 内部的地址(`permitted.token`、`spender`、`witness.to`、`from`)会转换为 `0x` hex 格式以进行 EIP-712/TIP-712 签名。 + ```json { "x402Version": 2, @@ -59,8 +61,7 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: "payTo": "", "maxTimeoutSeconds": 3600, "extra": { - "name": "Tether USD", - "version": "1", + "assetTransferMethod": "permit2", "fee": { "facilitatorId": "", "feeTo": "", @@ -94,8 +95,7 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: "payTo": "", "maxTimeoutSeconds": 3600, "extra": { - "name": "Tether USD", - "version": "1", + "assetTransferMethod": "permit2", "fee": { "facilitatorId": "", "feeTo": "", @@ -152,12 +152,12 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: "payload": { "signature": "0x...", "permit2Authorization": { - "permitted": { "token": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", "amount": "100" }, - "spender": "", + "permitted": { "token": "0x...", "amount": "100" }, + "spender": "0x...", "nonce": "0", "deadline": "1770820911", - "witness": { "to": "", "validAfter": "1770817311" }, - "from": "" + "witness": { "to": "0x...", "validAfter": "1770817311" }, + "from": "0x..." } } } From 6f22c6ee6a4fd3a1da37b041b785872d29be9b8e Mon Sep 17 00:00:00 2001 From: "roger.gan" Date: Sun, 5 Jul 2026 08:40:37 +0800 Subject: [PATCH 06/12] docs(x402): remove fee.facilitatorId, fix BSC extension object MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - fee model (mechanisms/tron/src/shared/fee.ts) only has feeTo, feeAmount, caller? — facilitatorId does not exist; drop it from TRON fee blocks and the field table (EN+ZH) - BSC exact has no TRON fee model, so remove the fee object from the BSC PAYMENT-REQUIRED example (extra keeps assetTransferMethod) - BSC extensions.erc20ApprovalGasSponsoring was shown as {} but the server declares info (description+version) and a JSON schema; show the real info plus an abbreviated schema (real required array) with a note marking the omitted properties (EN+ZH) --- docs/x402/core-concepts/http-402.md | 26 ++++++++++++------- .../current/x402/core-concepts/http-402.md | 26 ++++++++++++------- 2 files changed, 32 insertions(+), 20 deletions(-) diff --git a/docs/x402/core-concepts/http-402.md b/docs/x402/core-concepts/http-402.md index b3bba79f..6db2bdb5 100644 --- a/docs/x402/core-concepts/http-402.md +++ b/docs/x402/core-concepts/http-402.md @@ -63,7 +63,6 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- "extra": { "assetTransferMethod": "permit2", "fee": { - "facilitatorId": "", "feeTo": "", "feeAmount": "100", "caller": "" @@ -77,6 +76,8 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- +> **Note:** `extensions.erc20ApprovalGasSponsoring` carries `info` (description + version) and a `schema` (JSON Schema for the clients pre-signed `approve(Permit2)` payload). The `schema.properties` declarations are abbreviated below for brevity. + ```json { "x402Version": 2, @@ -95,18 +96,23 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- "payTo": "", "maxTimeoutSeconds": 3600, "extra": { - "assetTransferMethod": "permit2", - "fee": { - "facilitatorId": "", - "feeTo": "", - "feeAmount": "100000000000000", - "caller": "" - } + "assetTransferMethod": "permit2" } } ], "extensions": { - "erc20ApprovalGasSponsoring": {} + "erc20ApprovalGasSponsoring": { + "info": { + "description": "The facilitator broadcasts a pre-signed ERC-20 approve() transaction to grant Permit2 allowance.", + "version": "1" + }, + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": "...", + "required": ["from", "asset", "spender", "amount", "signedTransaction", "version"] + } + } } } ``` @@ -128,7 +134,7 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- | `asset` | TRC-20/BEP-20 token contract address | | `payTo` | Seller's wallet address | | `maxTimeoutSeconds` | Maximum validity duration of the payment | -| `extra.fee` | Facilitator fee information (includes `facilitatorId`, `feeTo`, `feeAmount`, `caller`) | +| `extra.fee` | Facilitator fee information (includes `feeTo`, `feeAmount`, `caller`) | | `extensions` | Additional context for the payment scheme (e.g., gas-sponsoring, payment-identifier) | ## Payment Signature Structure diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/http-402.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/http-402.md index 40a84e3a..60c6eede 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/http-402.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/http-402.md @@ -63,7 +63,6 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: "extra": { "assetTransferMethod": "permit2", "fee": { - "facilitatorId": "", "feeTo": "", "feeAmount": "100", "caller": "" @@ -77,6 +76,8 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: +> **注意:** `extensions.erc20ApprovalGasSponsoring` 包含 `info`(description + version)和 `schema`(客户端预签名 `approve(Permit2)` 载荷的 JSON Schema)。为简洁起见,下方 `schema.properties` 的具体声明已省略。 + ```json { "x402Version": 2, @@ -95,18 +96,23 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: "payTo": "", "maxTimeoutSeconds": 3600, "extra": { - "assetTransferMethod": "permit2", - "fee": { - "facilitatorId": "", - "feeTo": "", - "feeAmount": "100000000000000", - "caller": "" - } + "assetTransferMethod": "permit2" } } ], "extensions": { - "erc20ApprovalGasSponsoring": {} + "erc20ApprovalGasSponsoring": { + "info": { + "description": "The facilitator broadcasts a pre-signed ERC-20 approve() transaction to grant Permit2 allowance.", + "version": "1" + }, + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": "...", + "required": ["from", "asset", "spender", "amount", "signedTransaction", "version"] + } + } } } ``` @@ -127,7 +133,7 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: | `asset` | TRC-20/BEP-20 代币合约地址 | | `payTo` | 卖家的钱包地址 | | `maxTimeoutSeconds` | 支付有效期的最大时长 | -| `extra.fee` | Facilitator 费用信息(包含 `facilitatorId`、`feeTo`、`feeAmount`、`caller`) | +| `extra.fee` | Facilitator 费用信息(包含 `feeTo`、`feeAmount`、`caller`) | | `extensions` | 支付方案的附加上下文(如 gas 赞助、payment-identifier) | ## 支付签名结构 From fca7f4df489a6b8a96528e8134b16464f310fde1 Mon Sep 17 00:00:00 2001 From: roger-gan Date: Fri, 10 Jul 2026 09:59:44 +0800 Subject: [PATCH 07/12] docs: update x402 gasfree guidance --- docs/McpServer-Skills/SKILLS/BANKOFAISkill.md | 2 +- .../current/McpServer-Skills/SKILLS/BANKOFAISkill.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/McpServer-Skills/SKILLS/BANKOFAISkill.md b/docs/McpServer-Skills/SKILLS/BANKOFAISkill.md index 7c6715eb..f92a4759 100644 --- a/docs/McpServer-Skills/SKILLS/BANKOFAISkill.md +++ b/docs/McpServer-Skills/SKILLS/BANKOFAISkill.md @@ -439,7 +439,7 @@ Some APIs and AI agents require on-chain payment before use. This skill uses the > Activate my GasFree account on nile with USDT. :::tip GasFree support (TRON) -The skill prefers the `exact_gasfree` scheme over `exact_permit` when paying on TRON. GasFree requires an activated account with enough token balance in the GasFree wallet — use `--gasfree-info` to check, and `--gasfree-activate` if it's not active yet. +When paying on TRON, the skill prefers `exact_gasfree` and automatically falls back to `exact` if GasFree payment creation fails. GasFree requires sufficient token balance in the GasFree wallet; inactive accounts can be activated on first payment when the advertised fees permit it. Use `--gasfree-info` to check wallet address, activation status, balance, and nonce; use `--gasfree-activate` to activate manually. ::: :::caution Wallet credentials come from agent-wallet diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/BANKOFAISkill.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/BANKOFAISkill.md index 020fe1d6..c3ecc5e5 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/BANKOFAISkill.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/BANKOFAISkill.md @@ -437,7 +437,7 @@ PSM 支持 **USDT ↔ USDD 即时 1:1 兑换**——是获取 USDD 最简单的 > 在 nile 上用 USDT 激活我的 GasFree 账户。 :::tip GasFree 支持(TRON) -在 TRON 上付款时,技能会优先选择 `exact_gasfree` 方案(比 `exact_permit` 更便宜)。GasFree 需要账户已激活且 GasFree 钱包里有足够余额——用 `--gasfree-info` 检查,没激活就用 `--gasfree-activate` 激活。 +在 TRON 上付款时,技能会优先选择 `exact_gasfree` 方案;如果 GasFree 创建支付载荷失败,会自动回退到 `exact`。GasFree 钱包需要有足够代币余额;未激活账户在服务端声明的费用允许时可在首次付款时激活。可用 `--gasfree-info` 查看 GasFree 地址、激活状态、余额和 nonce;需要手动激活时用 `--gasfree-activate`。 ::: :::caution 钱包凭证来自 agent-wallet From c552bbedbe01a6e7f47edfef5209215fd3fd1fee Mon Sep 17 00:00:00 2001 From: jerryji-prog Date: Fri, 10 Jul 2026 14:19:53 +0800 Subject: [PATCH 08/12] =?UTF-8?q?update=20facilitator=20and=20skills=20?= =?UTF-8?q?=EF=BC=8Cchang=20catalog=20url?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/docker.yml | 2 ++ docs/McpServer-Skills/SKILLS/BANKOFAISkill.md | 34 +++++++++++++++++++ docs/McpServer-Skills/SKILLS/Faq.md | 2 +- docs/McpServer-Skills/SKILLS/Intro.md | 10 +++++- docs/McpServer-Skills/SKILLS/QuickStart.md | 15 +++++--- docs/Openclaw-extension/QuickStart.md | 22 ++++++++---- docs/x402/api-catalog/get-started.md | 16 ++++++--- docs/x402/api-catalog/list-your-service.md | 4 +-- docs/x402/api-catalog/reference.md | 2 +- .../x402/core-concepts/OfficialFacilitator.md | 32 ++++++++++------- docs/x402/core-concepts/facilitator.md | 27 ++++++++------- .../McpServer-Skills/SKILLS/BANKOFAISkill.md | 34 +++++++++++++++++++ .../current/McpServer-Skills/SKILLS/Faq.md | 2 +- .../current/McpServer-Skills/SKILLS/Intro.md | 10 +++++- .../McpServer-Skills/SKILLS/QuickStart.md | 15 +++++--- .../current/Openclaw-extension/QuickStart.md | 22 ++++++++---- .../current/x402/api-catalog/get-started.md | 16 ++++++--- .../x402/api-catalog/list-your-service.md | 4 +-- .../current/x402/api-catalog/reference.md | 2 +- .../x402/core-concepts/OfficialFacilitator.md | 26 ++++++++------ .../current/x402/core-concepts/facilitator.md | 27 ++++++++------- package.json | 2 +- 22 files changed, 238 insertions(+), 88 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 09ac7358..443a6f15 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -7,6 +7,7 @@ on: - master - update-mcp-server - ai-bankofai-patch-1 + - x402-sdk-1.0.0-update tags: - 'test' pull_request: @@ -15,6 +16,7 @@ on: - master - update-mcp-server - ai-bankofai-patch-1 + - x402-sdk-1.0.0-update workflow_dispatch: # Intentionally unrestricted — allows manual builds from any branch for flexibility env: diff --git a/docs/McpServer-Skills/SKILLS/BANKOFAISkill.md b/docs/McpServer-Skills/SKILLS/BANKOFAISkill.md index f92a4759..e939d15d 100644 --- a/docs/McpServer-Skills/SKILLS/BANKOFAISkill.md +++ b/docs/McpServer-Skills/SKILLS/BANKOFAISkill.md @@ -27,6 +27,8 @@ BANK OF AI SKILLS can operate on **real on-chain assets**. Blockchain transactio | **multisig-permissions** | Multi-sig permission setup, key management, co-signed proposals | Wallet credentials (owner key for permission changes) | | **x402-payment** | On-chain "pay-first" auto-settlement on TRON (TRC20) & BSC (ERC20), with GasFree support | Wallet credentials (via agent-wallet) | | **recharge-skill** | Balance, order history, account top-up | BANK OF AI API key | +| **twitter-digest** | Generate a daily digest from your own X/Twitter account — mentions, home timeline, and reply opportunities (API-only) | X/Twitter API credentials | +| **twitter-mcp** | Install/authorize the `xurl` CLI for X/Twitter and generate digests from it; optional hosted X MCP bridge | X/Twitter OAuth (via `xurl`) | | **bankofai-guide** | Onboarding helper — post-install setup, first AgentWallet creation, wallet guard for other skills | None (runs automatically when needed) | ### 🔑 Where Do I Get These Keys? How Do I Set Them Up? @@ -464,6 +466,38 @@ Check your balance, view order history, or top up your account. --- +## twitter-digest {#twitter-digest} + +Generate a concise daily digest from your own X/Twitter account. This skill is **API-only** — it reads your mentions, home timeline, and reply opportunities to produce a daily social-media summary. Trigger it with phrases like "生成X日报", "X日报", "推特日报", or "Twitter digest". + +**What it does:** + +> Generate today's X/Twitter digest for my account. + +> Summarize my mentions and reply opportunities from the last day. + +:::caution Requires X/Twitter API access +This skill pulls data through the X/Twitter API, so it needs valid API credentials configured for your account. +::: + +--- + +## twitter-mcp {#twitter-mcp} + +Install and authorize `@xdevplatform/xurl`, then generate X/Twitter daily digests directly from the local `xurl` CLI (commands like `whoami`, `timeline`, `mentions`, `posts`, `search`). Unlike `twitter-digest`, the data source here is the local `xurl` CLI rather than an API collector. The hosted X MCP bridge can optionally be registered as `xapi` on request. + +**What it does:** + +> Install and authorize xurl for my X/Twitter account. + +> Generate my X/Twitter daily digest from the xurl CLI. + +:::tip xurl vs. twitter-digest +Use `twitter-mcp` when you want digests driven by the local `xurl` CLI; use `twitter-digest` for the API-only digest flow. +::: + +--- + ## bankofai-guide {#bankofai-guide} The onboarding companion that ties the rest of the skill set together. You don't typically invoke this skill directly — it kicks in automatically in three situations: diff --git a/docs/McpServer-Skills/SKILLS/Faq.md b/docs/McpServer-Skills/SKILLS/Faq.md index 7f8b12fc..cd64e037 100644 --- a/docs/McpServer-Skills/SKILLS/Faq.md +++ b/docs/McpServer-Skills/SKILLS/Faq.md @@ -40,7 +40,7 @@ Run this in your terminal: ls ~/.agents/skills ``` -You should see 12 directory names: `agent-wallet`, `sunswap-dex-trading`, `sunpump-meme-token-toolkit`, `sunperp-perpetual-futures-trading`, `tronscan-data-lookup`, `trc20-token-toolkit`, `usdd-just-protocol`, `trx-staking-sr-voting`, `multi-sig-account-permissions`, `x402-payment`, `recharge-skill`, and `bankofai-guide`. +You should see 14 directory names: `agent-wallet`, `sunswap-dex-trading`, `sunpump-meme-token-toolkit`, `sunperp-perpetual-futures-trading`, `tronscan-data-lookup`, `trc20-token-toolkit`, `usdd-just-protocol`, `trx-staking-sr-voting`, `multi-sig-account-permissions`, `x402-payment`, `recharge-skill`, `twitter-digest`, `twitter-mcp`, and `bankofai-guide`. Then verify in your AI chat: diff --git a/docs/McpServer-Skills/SKILLS/Intro.md b/docs/McpServer-Skills/SKILLS/Intro.md index 548dfc7c..5eefda6f 100644 --- a/docs/McpServer-Skills/SKILLS/Intro.md +++ b/docs/McpServer-Skills/SKILLS/Intro.md @@ -57,7 +57,7 @@ No. Skills use an **on-demand, lightweight architecture** — the AI only loads ## What Can Skills Do for You? -Twelve skills in total — covering the most common scenarios in the TRON ecosystem, plus a dedicated onboarding helper. Each one comes with a ready-to-use sample prompt — copy it into your AI chat and hit enter to try it out. +Fourteen skills in total — covering the most common scenarios in the TRON ecosystem plus X/Twitter tooling, and a dedicated onboarding helper. Each one comes with a ready-to-use sample prompt — copy it into your AI chat and hit enter to try it out. ### 🔑 Secure Wallet Management @@ -147,6 +147,14 @@ Check your BANK OF AI balance and top up with a single sentence. 💡 For top-up and withdrawal rules, see: [**recharge-skill**](./BANKOFAISkill.md#recharge-skill) +### 🐦 X/Twitter Daily Digest + +Turn your own X/Twitter account into a daily briefing — mentions, home timeline, and reply opportunities, summarized for you. + +> 🗣️ "Generate today's X/Twitter digest for my account." + +💡 Two ways to run it: API-only via [**twitter-digest**](./BANKOFAISkill.md#twitter-digest), or from the local `xurl` CLI via [**twitter-mcp**](./BANKOFAISkill.md#twitter-mcp). + ### 🧭 Onboarding Guide (bankofai-guide) A lightweight companion skill that runs the post-install setup flow, helps you create your first AgentWallet, and acts as a "wallet guard" before any on-chain operation — reminding you to set up a wallet if none exists. You don't usually call it directly; it gets invoked automatically by the installer and by other skills when needed. diff --git a/docs/McpServer-Skills/SKILLS/QuickStart.md b/docs/McpServer-Skills/SKILLS/QuickStart.md index 747ea1ca..1ad1dcc1 100644 --- a/docs/McpServer-Skills/SKILLS/QuickStart.md +++ b/docs/McpServer-Skills/SKILLS/QuickStart.md @@ -29,7 +29,7 @@ If you're already using a Skills-compatible AI Agent (OpenClaw, a Telegram bot, 3. The AI handles the entire flow automatically: - Pulls the `BofAI/skills` repository - Detects your current Agent's skills directory (e.g. `~/.agents/skills/`) - - Installs all 12 BANK OF AI skills: the 11 core skills (`agent-wallet`, `sunswap-dex-trading`, `sunpump-meme-token-toolkit`, `sunperp-perpetual-futures-trading`, `tronscan-data-lookup`, `trc20-token-toolkit`, `usdd-just-protocol`, `trx-staking-sr-voting`, `multi-sig-account-permissions`, `x402-payment`, `recharge-skill`) plus `bankofai-guide` (the onboarding helper) + - Installs all 14 BANK OF AI skills: the 13 core skills (`agent-wallet`, `sunswap-dex-trading`, `sunpump-meme-token-toolkit`, `sunperp-perpetual-futures-trading`, `tronscan-data-lookup`, `trc20-token-toolkit`, `usdd-just-protocol`, `trx-staking-sr-voting`, `multi-sig-account-permissions`, `x402-payment`, `recharge-skill`, `twitter-digest`, `twitter-mcp`) plus `bankofai-guide` (the onboarding helper) :::tip Why this is the recommended path for beginners You don't need to know what `npx`, `npm`, or "global install" mean. The AI handles every step including selecting the right skills directory for your platform, installing the wallet CLI, and onboarding you to your first wallet. @@ -70,13 +70,14 @@ The installer will guide you through a few steps — just follow along: The installer automatically fetches all available Skills from the repo and lists them for selection. Press **Space** to toggle each one — we recommend selecting all: ``` -◇ Found 12 skills +◇ Found 14 skills │ ◇ Select skills to install (space to toggle) │ agent-wallet, bankofai-guide, Multi-Sig & Account Permissions, │ recharge-skill, SunPerp Perpetual Futures Trading, SunPump Meme Token Toolkit, │ SunSwap DEX Trading, TRC20 Token Toolkit, TronScan Data Lookup, -│ TRX Staking & SR Voting, USDD / JUST Protocol, x402-payment +│ TRX Staking & SR Voting, USDD / JUST Protocol, twitter-digest, twitter-mcp, +│ x402-payment ``` :::tip Select all @@ -223,7 +224,7 @@ When you see output like this, all Skills have been successfully installed to yo ``` ◇ Installation complete -◇ Installed 12 skills ──────────────────────────────────────────────────╮ +◇ Installed 14 skills ──────────────────────────────────────────────────╮ │ │ │ ✓ ~/.agents/skills/bankofai-guide │ │ universal: Amp, Antigravity, Antigravity CLI, Cline, Codex +8 more │ @@ -255,6 +256,12 @@ When you see output like this, all Skills have been successfully installed to yo │ ✓ ~/.agents/skills/usdd-just-protocol │ │ universal: Amp, Antigravity, Antigravity CLI, Cline, Codex +8 more │ │ symlinked: Claude Code, OpenClaw │ +│ ✓ ~/.agents/skills/twitter-digest │ +│ universal: Amp, Antigravity, Antigravity CLI, Cline, Codex +8 more │ +│ symlinked: Claude Code, OpenClaw │ +│ ✓ ~/.agents/skills/twitter-mcp │ +│ universal: Amp, Antigravity, Antigravity CLI, Cline, Codex +8 more │ +│ symlinked: Claude Code, OpenClaw │ │ ✓ ~/.agents/skills/x402-payment │ │ universal: Amp, Antigravity, Antigravity CLI, Cline, Codex +8 more │ │ symlinked: Claude Code, OpenClaw │ diff --git a/docs/Openclaw-extension/QuickStart.md b/docs/Openclaw-extension/QuickStart.md index 73dd12bf..a4eaa27f 100644 --- a/docs/Openclaw-extension/QuickStart.md +++ b/docs/Openclaw-extension/QuickStart.md @@ -115,9 +115,9 @@ After confirming, the installer automatically removes old skills: ``` Running cleanup... -◇ Found 11 unique installed skill(s) +◇ Found 14 unique installed skill(s) ◇ Removal process complete -◆ Successfully removed 11 skill(s) +◆ Successfully removed 14 skill(s) ✓ Clean install cleanup completed. @@ -295,12 +295,13 @@ Press Enter (or type `1`) to install globally — this way all your OpenClaw wor Then the skill picker launches: ``` -◇ Found 11 skills +◇ Found 14 skills │ ◇ Select skills to install (space to toggle) │ agent-wallet, bankofai-guide, Multi-Sig & Account Permissions, recharge-skill, -│ SunPerp Perpetual Futures Trading, SunSwap DEX Trading, TRC20 Token Toolkit, -│ TronScan Data Lookup, TRX Staking & SR Voting, USDD / JUST Protocol, x402-payment +│ SunPerp Perpetual Futures Trading, SunPump Meme Token Toolkit, SunSwap DEX Trading, +│ TRC20 Token Toolkit, TronScan Data Lookup, TRX Staking & SR Voting, USDD / JUST Protocol, +│ twitter-digest, twitter-mcp, x402-payment ``` Here's what each skill does: @@ -311,11 +312,14 @@ Here's what each skill does: | **bankofai-guide** | Onboarding helper that walks the AI through next steps after installation | | **SunSwap DEX Trading** | Swap tokens on SunSwap (TRON's biggest DEX) | | **SunPerp Perpetual Futures** | Trade perpetual futures on SunPerp | +| **SunPump Meme Token Toolkit** | Create and trade meme tokens on SunPump; query token info, rankings, holders, and trade history | | **TronScan Data Lookup** | Query blockchain data via TronScan | | **TRC20 Token Toolkit** | Common TRC20 token operations like sending tokens | | **TRX Staking & SR Voting** | Stake TRX, get energy/bandwidth, and vote for Super Representatives | | **USDD / JUST Protocol** | Manage USDD stablecoin and JUST Protocol positions | | **Multi-Sig & Account Permissions** | Multi-signature wallet and account permission management | +| **twitter-digest** | Generate X/Twitter daily digests (mentions, home timeline, reply opportunities) | +| **twitter-mcp** | Install/authorize xurl for X/Twitter and generate digests from the local xurl CLI | | **x402-payment** | x402 protocol payments (agent-to-agent) | | **recharge-skill** | Check and top up your BANK OF AI balance | @@ -328,11 +332,14 @@ After selecting, the installer shows a security risk assessment: │ Multi-Sig & Account Permissions -- -- -- │ recharge-skill Safe 1 alert Med Risk │ SunPerp Perpetual Futures Trading -- -- -- +│ SunPump Meme Token Toolkit -- -- -- │ SunSwap DEX Trading -- -- -- │ TRC20 Token Toolkit -- -- -- │ TronScan Data Lookup -- -- -- │ TRX Staking & SR Voting -- -- -- │ USDD / JUST Protocol -- -- -- +│ twitter-digest -- -- -- +│ twitter-mcp -- -- -- │ x402-payment Safe 1 alert Med Risk │ agent-wallet Safe 1 alert High Risk ``` @@ -340,18 +347,21 @@ After selecting, the installer shows a security risk assessment: Review the report, then confirm to proceed. When installation completes: ``` -◇ Installed 11 skills +◇ Installed 14 skills │ │ ✓ agent-wallet → ~/.openclaw/skills/agent-wallet │ ✓ bankofai-guide → ~/.openclaw/skills/bankofai-guide │ ✓ Multi-Sig & Account Permissions → ~/.openclaw/skills/multi-sig-account-permissions │ ✓ recharge-skill → ~/.openclaw/skills/recharge-skill │ ✓ SunPerp Perpetual Futures Trading → ~/.openclaw/skills/sunperp-perpetual-futures-trading +│ ✓ SunPump Meme Token Toolkit → ~/.openclaw/skills/sunpump-meme-token-toolkit │ ✓ SunSwap DEX Trading → ~/.openclaw/skills/sunswap-dex-trading │ ✓ TRC20 Token Toolkit → ~/.openclaw/skills/trc20-token-toolkit │ ✓ TronScan Data Lookup → ~/.openclaw/skills/tronscan-data-lookup │ ✓ TRX Staking & SR Voting → ~/.openclaw/skills/trx-staking-sr-voting │ ✓ USDD / JUST Protocol → ~/.openclaw/skills/usdd-just-protocol +│ ✓ twitter-digest → ~/.openclaw/skills/twitter-digest +│ ✓ twitter-mcp → ~/.openclaw/skills/twitter-mcp │ ✓ x402-payment → ~/.openclaw/skills/x402-payment ``` diff --git a/docs/x402/api-catalog/get-started.md b/docs/x402/api-catalog/get-started.md index 293cb271..9b8cc647 100644 --- a/docs/x402/api-catalog/get-started.md +++ b/docs/x402/api-catalog/get-started.md @@ -35,23 +35,29 @@ When the version prints, you're done — that's both steps. Your Agent is now pl Once installed, your Agent can discover and call services through the CLI. Search by name or keyword to see what's in the catalog: ```bash -x402-cli catalog search --catalog https://x402-catelog.bankofai.io/api/catalog.json --json +x402-cli catalog search --catalog https://x402-catalog.bankofai.io/api/catalog.json --json ``` Inspect a service's details and available endpoints: ```bash -x402-cli catalog show --catalog https://x402-catelog.bankofai.io/api/catalog.json --json -x402-cli catalog endpoints --catalog https://x402-catelog.bankofai.io/api/catalog.json --json +x402-cli catalog show --catalog https://x402-catalog.bankofai.io/api/catalog.json --json +x402-cli catalog endpoints --catalog https://x402-catalog.bankofai.io/api/catalog.json --json ``` -Then make a paid call against the target endpoint — quote, payment, and result retrieval in one step. A simple GET endpoint needs nothing more than the URL: +**Free endpoints** (those the provider leaves unpriced) return their result to a plain `curl` — no CLI and no payment needed: + +```bash +curl -sS 'https://x402-gateway.bankofai.io/providers//...' +``` + +For a **paid** endpoint, use `x402-cli pay` — it handles the quote, payment, and result retrieval in one step. A simple GET needs nothing more than the URL: ```bash x402-cli pay 'https://x402-gateway.bankofai.io/providers//...' ``` -For a POST endpoint, or to pin the payment chain, token, and scheme, pass them explicitly: +For a paid POST endpoint, or to pin the payment chain, token, and scheme, pass them explicitly: ```bash x402-cli pay 'https://x402-gateway.bankofai.io/providers//' \ diff --git a/docs/x402/api-catalog/list-your-service.md b/docs/x402/api-catalog/list-your-service.md index 4e9e8b32..612e7a1c 100644 --- a/docs/x402/api-catalog/list-your-service.md +++ b/docs/x402/api-catalog/list-your-service.md @@ -12,7 +12,7 @@ Put your API behind the Gateway and it appears in the catalog: any Agent can dis ## The big picture: what listing actually means -Listing comes down to one action: opening a PR against the [catalog repository](https://github.com/BofAI/x402-catelog) with just two **public** files: +Listing comes down to one action: opening a PR against the [catalog repository](https://github.com/BofAI/x402-catalog) with just two **public** files: | File | Purpose | |---|---| @@ -259,7 +259,7 @@ built 1 provider(s) into dist ## Step 3: Open the Pull Request -Add the two files to the [catalog repository](https://github.com/BofAI/x402-catelog) under the matching directory: +Add the two files to the [catalog repository](https://github.com/BofAI/x402-catalog) under the matching directory: ```text providers//catalog.json diff --git a/docs/x402/api-catalog/reference.md b/docs/x402/api-catalog/reference.md index 35760085..6d4cdb56 100644 --- a/docs/x402/api-catalog/reference.md +++ b/docs/x402/api-catalog/reference.md @@ -6,7 +6,7 @@ description: Field definitions for catalog.json / pay.md, allowed categories and # Data Format & API Reference -This page is the API Catalog's data contract: the `catalog.json` fields providers submit to the [catalog repository](https://github.com/BofAI/x402-catelog), the allowed values, and the structures of the `/api/*` endpoints the catalog exposes after build. +This page is the API Catalog's data contract: the `catalog.json` fields providers submit to the [catalog repository](https://github.com/BofAI/x402-catalog), the allowed values, and the structures of the `/api/*` endpoints the catalog exposes after build. ## provider catalog.json fields diff --git a/docs/x402/core-concepts/OfficialFacilitator.md b/docs/x402/core-concepts/OfficialFacilitator.md index 7f843727..bb034357 100644 --- a/docs/x402/core-concepts/OfficialFacilitator.md +++ b/docs/x402/core-concepts/OfficialFacilitator.md @@ -56,7 +56,7 @@ Official Facilitator supports **two calling modes**. | Mode | Rate Limit | Description | |-----|-----|-----| -| **Anonymous Mode** | 1 time / minute | No API Key required, suitable for local development and functional testing | +| **Anonymous Mode** | 10 times / minute (default, configurable) | No API Key required, suitable for local development and functional testing | | **API Key Mode** | 1000 times / minute | API Key required, suitable for production environments and high-frequency payment requests | The calling methods for both modes are exactly the same, but they differ in **identity recognition and interface rate limiting strategies**. @@ -69,8 +69,8 @@ If the request **does not carry an API Key**, the Facilitator will treat the req In anonymous mode: -- The `/settle` interface will enable **strict rate limiting** -- **Maximum 1 call per minute** +- The `/settle` interface is **rate-limited** +- **Maximum 10 calls per minute** (default, configurable) This mode is mainly used for: @@ -84,7 +84,7 @@ Anonymous call example: ```bash curl -X POST https://facilitator.bankofai.io/settle \ -H "Content-Type: application/json" \ - -d \'{ ... }\' + -d '{ ... }' ``` Although anonymous mode can call all core interfaces normally, due to the very low call frequency of `/settle`, it is **not suitable for production environments**. @@ -107,7 +107,7 @@ Call example: curl -X POST https://facilitator.bankofai.io/settle \ -H "X-API-KEY: your_api_key_here" \ -H "Content-Type: application/json" \ - -d \'{ ... }\' + -d '{ ... }' ``` When the Facilitator recognizes the API Key: @@ -246,24 +246,30 @@ After clicking **"Confirm"**, you will return to the Dashboard page, and the API |------|------|------| | GET | `/health` | Service health check | | GET | `/supported` | Query supported payment capabilities and configurations | -| POST | `/fee/quote` | Get estimated fees for payment requirements | | POST | `/verify` | Verify payment payload validity | | POST | `/settle` | Perform on-chain settlement (**rate-limited**)| -| GET | `/payments/{payment_id}` | Query payment records by payment ID | -| GET | `/payments/tx/{tx_hash}` | Query payment records by transaction hash | +| GET | `/payments/tx/{tx_hash}` | Query payment records by settlement transaction hash | +| GET | `/payments?network=&nonce=[&asset=&payer=]` | Query payment records by the on-chain authorization identity | +| GET | `/payments` | Authenticated seller's settlement feed (`?limit=&offset=`) | -> Rate limiting only applies to the `/settle` interface; other interfaces are not affected by rate limiting. +> There is **no** `/fee/quote` endpoint — fee terms travel inside the payment requirements' `extra` field. Rate limiting only applies to the `/settle` interface; other interfaces are not affected by rate limiting. ### Payment Record Query -Both `/payments/{payment_id}` and `/payments/tx/{tx_hash}` interfaces return a JSON array sorted in reverse chronological order. Each record contains: +The `/payments/tx/{tx_hash}` and `/payments?network=&nonce=[&asset=&payer=]` interfaces return a JSON array sorted in reverse chronological order. Records are keyed on the on-chain authorization identity rather than a client-supplied payment ID. Each record contains: -- `paymentId` — Unique payment identifier (may be empty) +- `network` — CAIP-2 network identifier +- `scheme` — Payment scheme (e.g. `exact`) +- `asset` — Token contract address +- `payer` — Payer address +- `nonce` — Authorization nonce +- `amount` — Settled amount (atomic units) - `txHash` — On-chain transaction hash - `status` — `"success"` or `"failed"` +- `errorReason` — Failure reason (when applicable) - `createdAt` — Timestamp -> When an API Key is provided, these two interfaces only return payment records associated with your account; you will not see data from other sellers. +> When an API Key is provided, these interfaces only return payment records associated with your account; you will not see data from other sellers. --- @@ -271,7 +277,7 @@ Both `/payments/{payment_id}` and `/payments/tx/{tx_hash}` interfaces return a J **Q: Can it run normally without configuring an API Key?** -Yes, it can run, but the `/settle` interface can only be called once per IP per minute. This is only suitable for testing; any real traffic must be configured with an API Key. +Yes, it can run, but the `/settle` interface is limited to 10 calls per IP per minute by default. This is only suitable for testing; any real traffic must be configured with an API Key. **Q: Does the API Key expire?** diff --git a/docs/x402/core-concepts/facilitator.md b/docs/x402/core-concepts/facilitator.md index 5228e2f0..79133be2 100644 --- a/docs/x402/core-concepts/facilitator.md +++ b/docs/x402/core-concepts/facilitator.md @@ -11,7 +11,7 @@ A Facilitator is a middleware service primarily responsible for: - **Payload Verification**: Validating the payment payload submitted by the client. - **Settlement Execution**: Submitting transactions to the blockchain on behalf of the server to complete settlement. -- **Token Transfer**: Executing the on-chain transfer — ERC-3009 `transferWithAuthorization`, Permit2 `permitTransferFrom` via the `x402ExactPermit2Proxy`, a batch-settlement claim, or a GasFree relay, depending on the scheme. +- **Token Transfer**: Executing the on-chain settlement for the scheme — ERC-3009 `transferWithAuthorization`, a Permit2 transfer via the `x402ExactPermit2Proxy` (`exact`) or `x402UptoPermit2Proxy` (`upto`), a batch-settlement claim, or a GasFree relay. By introducing a Facilitator, servers no longer need to maintain direct connections to blockchain nodes or implement complex signature verification logic themselves. This reduces operational complexity while ensuring accurate and real-time transaction validation. @@ -91,11 +91,15 @@ Whether using the official service or a self-hosted instance, the Facilitator pr |--------|------|-------------| | GET | `/health` | Liveness check | | GET | `/supported` | Supported payment capabilities and configuration | -| POST | `/fee/quote` | Get fee quote for payment requirements | | POST | `/verify` | Verify payment payload validity | -| POST | `/settle` | Execute on-chain settlement (**rate-limited**, see below) | -| GET | `/payments/{payment_id}` | Query payment records by payment ID (seller-scoped when authenticated) | -| GET | `/payments/tx/{tx_hash}` | Query payment records by transaction hash (seller-scoped when authenticated) | +| POST | `/settle` | Execute on-chain settlement (**rate-limited**, see below); persists a settlement record | +| GET | `/payments/tx/{tx_hash}` | Query payment records by settlement transaction hash (seller-scoped when authenticated) | +| GET | `/payments?network=&nonce=[&asset=&payer=]` | Query payment records by the on-chain authorization identity (seller-scoped when authenticated) | +| GET | `/payments` | Authenticated seller's settlement feed (`?limit=&offset=`) | +| GET | `/metrics` | Prometheus metrics (operational; exposed on the main port only when monitoring shares it) | +| ALL | `/mainnet/*` · `/nile/*` | GasFree Open API transparent proxy (HMAC-signed) — used internally by the TRON `exact_gasfree` scheme | + +> There is **no** `/fee/quote` endpoint. Fee terms travel inside the payment requirements' `extra` field, and payment records are keyed on the on-chain authorization identity (`network` + `scheme` + `asset` + `payer` + `nonce`), not a client-supplied payment ID. --- @@ -106,9 +110,9 @@ The `/settle` endpoint enforces dynamic rate limits based on the caller's authen | Mode | Rate Limit | How to Authenticate | |------|------------|---------------------| | **Authenticated** | 1000 requests / minute | Include `X-API-KEY: ` header | -| **Anonymous** | 1 request / minute | No API Key provided | +| **Anonymous** | 10 requests / minute (default, configurable) | No API Key provided | -Other endpoints (`/verify`, `/fee/quote`, `/supported`, `/payments/*`) are not individually rate-limited. +Other endpoints (`/verify`, `/supported`, `/payments/*`) are not individually rate-limited. > **Tip**: For any production workload, apply for an API Key via the [Admin Portal](https://admin-facilitator.bankofai.io) to unlock the higher rate limit. @@ -116,7 +120,7 @@ Other endpoints (`/verify`, `/fee/quote`, `/supported`, `/payments/*`) are not i ## Payment Record Queries -The `/payments/{payment_id}` and `/payments/tx/{tx_hash}` endpoints support querying historical payment records. +The `/payments/tx/{tx_hash}` and `/payments?network=&nonce=[&asset=&payer=]` endpoints support querying historical payment records; `/payments` alone returns the authenticated seller's settlement feed. Records are keyed on the on-chain authorization identity (`network` + `scheme` + `asset` + `payer` + `nonce`) rather than a client-supplied payment ID. When the request includes a valid `X-API-KEY` header, the results are **automatically scoped to the seller** associated with that API Key — you will only see your own payment records. Anonymous requests (without an API Key) can only access records that are not bound to any specific seller. @@ -126,11 +130,10 @@ When the request includes a valid `X-API-KEY` header, the results are **automati The Facilitator supports flexible service fee configurations: -- **Base Fee**: A fixed service fee per transaction (e.g., `1 USDT`). -- **Percentage Fee**: A percentage-based fee calculated from the transaction amount. -- **No Fee Mode**: Supports zero-fee operation. +- **Base Fee**: A fixed service fee per transaction, configured per network and asset (e.g., `1 USDT`). +- **No Fee Mode**: Supports zero-fee operation (e.g. EVM `exact` takes no facilitator fee). -Detailed fee information is returned via the `/fee/quote` endpoint and included in the Payment Requirements sent from the server to the client. +Fee terms are included in the Payment Requirements' `extra` field sent from the server to the client; there is no separate `/fee/quote` endpoint. --- diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/BANKOFAISkill.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/BANKOFAISkill.md index c3ecc5e5..a25572bf 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/BANKOFAISkill.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/BANKOFAISkill.md @@ -27,6 +27,8 @@ BANK OF AI SKILLS 可以操作**真实的链上资产**。区块链交易一旦 | **multisig-permissions** | 多签权限配置、密钥管理、多方共签提案 | 需要钱包凭证(权限变更需要 Owner 密钥) | | **x402-payment** | 链上"先付后用"自动结算,支持 TRON(TRC20)与 BSC(ERC20),含 GasFree | 通过 agent-wallet 提供钱包凭证 | | **recharge-skill** | 查余额、看订单、充值 | 需要 BANK OF AI 密钥 | +| **twitter-digest** | 从你自己的 X/Twitter 账号生成每日日报——提及、主页时间线与可回复机会(仅 API) | X/Twitter API 凭据 | +| **twitter-mcp** | 安装/授权 `xurl` CLI 并用它生成 X/Twitter 日报;可选注册托管的 X MCP 桥接 | X/Twitter OAuth(通过 `xurl`) | | **bankofai-guide** | 引导辅助技能——安装后首次配置、首个 AgentWallet 创建、其它技能的钱包守门员 | 无需配置(需要时自动触发) | ### 🔑 这些"钥匙"去哪领?怎么配? @@ -462,6 +464,38 @@ PSM 支持 **USDT ↔ USDD 即时 1:1 兑换**——是获取 USDD 最简单的 --- +## twitter-digest {#twitter-digest} + +从你自己的 X/Twitter 账号生成简洁的每日日报。该技能**仅使用 API**——读取你的提及、主页时间线和可回复机会,生成每日社媒摘要。可用「生成X日报」「X日报」「推特日报」或「Twitter digest」等说法触发。 + +**它能做什么:** + +> 生成我账号今天的 X/Twitter 日报。 + +> 汇总我过去一天的提及和可回复机会。 + +:::caution 需要 X/Twitter API 访问 +该技能通过 X/Twitter API 拉取数据,因此需要为你的账号配置有效的 API 凭据。 +::: + +--- + +## twitter-mcp {#twitter-mcp} + +安装并授权 `@xdevplatform/xurl`,然后直接用本地 `xurl` CLI(`whoami`、`timeline`、`mentions`、`posts`、`search` 等命令)生成 X/Twitter 每日日报。与 `twitter-digest` 不同,这里的数据源是本地 `xurl` CLI 而非 API 采集器。可按需将托管的 X MCP 桥接注册为 `xapi`。 + +**它能做什么:** + +> 为我的 X/Twitter 账号安装并授权 xurl。 + +> 用 xurl CLI 生成我的 X/Twitter 每日日报。 + +:::tip xurl 与 twitter-digest 的区别 +需要由本地 `xurl` CLI 驱动的日报时使用 `twitter-mcp`;需要纯 API 的日报流程时使用 `twitter-digest`。 +::: + +--- + ## bankofai-guide {#bankofai-guide} 把整套技能串起来的引导助手。你通常不需要主动调用它——它会在下面三种场景里自动登场: diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/Faq.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/Faq.md index d86df13d..b3c5c7f3 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/Faq.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/Faq.md @@ -40,7 +40,7 @@ ls ~/.agents/skills ``` -能看到 12 个目录:`agent-wallet`、`sunswap-dex-trading`、`sunpump-meme-token-toolkit`、`sunperp-perpetual-futures-trading`、`tronscan-data-lookup`、`trc20-token-toolkit`、`usdd-just-protocol`、`trx-staking-sr-voting`、`multi-sig-account-permissions`、`x402-payment`、`recharge-skill`,以及 `bankofai-guide`,就说明装好了。 +能看到 14 个目录:`agent-wallet`、`sunswap-dex-trading`、`sunpump-meme-token-toolkit`、`sunperp-perpetual-futures-trading`、`tronscan-data-lookup`、`trc20-token-toolkit`、`usdd-just-protocol`、`trx-staking-sr-voting`、`multi-sig-account-permissions`、`x402-payment`、`recharge-skill`、`twitter-digest`、`twitter-mcp`,以及 `bankofai-guide`,就说明装好了。 然后在 AI 对话中验证: diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/Intro.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/Intro.md index 51b123a9..19e06ff5 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/Intro.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/Intro.md @@ -57,7 +57,7 @@ ## 目前 Skills 能帮你干什么? -一共 12 个技能——覆盖 TRON 生态最常用的场景,外加一个专属的引导辅助技能。每个技能都配了一句"参考话术"——复制到 AI 对话框里回车就能体验。 +一共 14 个技能——覆盖 TRON 生态最常用的场景以及 X/Twitter 工具,外加一个专属的引导辅助技能。每个技能都配了一句"参考话术"——复制到 AI 对话框里回车就能体验。 ### 🔑 安全钱包管理 @@ -147,6 +147,14 @@ 💡 如需了解充值与提现规则,请查看:[**recharge-skill**](./BANKOFAISkill.md#recharge-skill) +### 🐦 X/Twitter 每日日报 + +把你自己的 X/Twitter 账号变成每日简报——提及、主页时间线与可回复机会,一并帮你汇总。 + +> 🗣️ "生成我账号今天的 X/Twitter 日报。" + +💡 两种运行方式:纯 API 的 [**twitter-digest**](./BANKOFAISkill.md#twitter-digest),或基于本地 `xurl` CLI 的 [**twitter-mcp**](./BANKOFAISkill.md#twitter-mcp)。 + ### 🧭 引导辅助(bankofai-guide) 一个轻量的辅助技能,负责跑完安装后的首次上手流程、帮你创建第一个 AgentWallet,并在任何链上操作之前充当"钱包守门员"——如果还没配钱包会提醒你先配一个。你通常不需要主动调用它,安装器和其他技能会在需要时自动把它唤醒。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/QuickStart.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/QuickStart.md index a9fc62c3..5fbdc91e 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/QuickStart.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/SKILLS/QuickStart.md @@ -29,7 +29,7 @@ 3. AI 会自动完成以下流程(无需人工干预): - 拉取 `BofAI/skills` 仓库 - 自动检测当前 Agent 对应的 skills 目录(如 `~/.agents/skills/`) - - 安装全部 12 个 BANK OF AI 技能:11 个核心技能(`agent-wallet`、`sunswap-dex-trading`、`sunpump-meme-token-toolkit`、`sunperp-perpetual-futures-trading`、`tronscan-data-lookup`、`trc20-token-toolkit`、`usdd-just-protocol`、`trx-staking-sr-voting`、`multi-sig-account-permissions`、`x402-payment`、`recharge-skill`),以及 `bankofai-guide`(引导辅助技能) + - 安装全部 14 个 BANK OF AI 技能:13 个核心技能(`agent-wallet`、`sunswap-dex-trading`、`sunpump-meme-token-toolkit`、`sunperp-perpetual-futures-trading`、`tronscan-data-lookup`、`trc20-token-toolkit`、`usdd-just-protocol`、`trx-staking-sr-voting`、`multi-sig-account-permissions`、`x402-payment`、`recharge-skill`、`twitter-digest`、`twitter-mcp`),以及 `bankofai-guide`(引导辅助技能) :::tip 这是新手最推荐的路径 你不需要懂 `npx`、`npm` 是什么,也不用关心"全局安装"是什么意思。AI 会处理每一步,包括为你的平台选对 skills 目录、安装钱包 CLI、引导你完成首个钱包配置。 @@ -70,13 +70,14 @@ npx skills add https://github.com/BofAI/skills 安装器会自动从仓库拉取所有可用的 Skills,然后列出清单让你勾选。按**空格键**切换选中/取消,默认全选即可: ``` -◇ Found 12 skills +◇ Found 14 skills │ ◇ Select skills to install (space to toggle) │ agent-wallet, bankofai-guide, Multi-Sig & Account Permissions, │ recharge-skill, SunPerp Perpetual Futures Trading, SunPump Meme Token Toolkit, │ SunSwap DEX Trading, TRC20 Token Toolkit, TronScan Data Lookup, -│ TRX Staking & SR Voting, USDD / JUST Protocol, x402-payment +│ TRX Staking & SR Voting, USDD / JUST Protocol, twitter-digest, twitter-mcp, +│ x402-payment ``` :::tip 建议全选 @@ -223,7 +224,7 @@ npx skills add https://github.com/BofAI/skills ``` ◇ Installation complete -◇ Installed 12 skills ──────────────────────────────────────────────────╮ +◇ Installed 14 skills ──────────────────────────────────────────────────╮ │ │ │ ✓ ~/.agents/skills/bankofai-guide │ │ universal: Amp, Antigravity, Antigravity CLI, Cline, Codex +8 more │ @@ -255,6 +256,12 @@ npx skills add https://github.com/BofAI/skills │ ✓ ~/.agents/skills/usdd-just-protocol │ │ universal: Amp, Antigravity, Antigravity CLI, Cline, Codex +8 more │ │ symlinked: Claude Code, OpenClaw │ +│ ✓ ~/.agents/skills/twitter-digest │ +│ universal: Amp, Antigravity, Antigravity CLI, Cline, Codex +8 more │ +│ symlinked: Claude Code, OpenClaw │ +│ ✓ ~/.agents/skills/twitter-mcp │ +│ universal: Amp, Antigravity, Antigravity CLI, Cline, Codex +8 more │ +│ symlinked: Claude Code, OpenClaw │ │ ✓ ~/.agents/skills/x402-payment │ │ universal: Amp, Antigravity, Antigravity CLI, Cline, Codex +8 more │ │ symlinked: Claude Code, OpenClaw │ diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/Openclaw-extension/QuickStart.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/Openclaw-extension/QuickStart.md index 22c093ba..5e8856e0 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/Openclaw-extension/QuickStart.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/Openclaw-extension/QuickStart.md @@ -115,9 +115,9 @@ The following data will be permanently deleted: ``` Running cleanup... -◇ Found 11 unique installed skill(s) +◇ Found 14 unique installed skill(s) ◇ Removal process complete -◆ Successfully removed 11 skill(s) +◆ Successfully removed 14 skill(s) ✓ Clean install cleanup completed. @@ -295,12 +295,13 @@ Select skills installation scope: 然后技能选择器启动: ``` -◇ Found 11 skills +◇ Found 14 skills │ ◇ Select skills to install (space to toggle) │ agent-wallet, bankofai-guide, Multi-Sig & Account Permissions, recharge-skill, -│ SunPerp Perpetual Futures Trading, SunSwap DEX Trading, TRC20 Token Toolkit, -│ TronScan Data Lookup, TRX Staking & SR Voting, USDD / JUST Protocol, x402-payment +│ SunPerp Perpetual Futures Trading, SunPump Meme Token Toolkit, SunSwap DEX Trading, +│ TRC20 Token Toolkit, TronScan Data Lookup, TRX Staking & SR Voting, USDD / JUST Protocol, +│ twitter-digest, twitter-mcp, x402-payment ``` 每个技能是干啥的: @@ -311,11 +312,14 @@ Select skills installation scope: | **bankofai-guide** | 安装完成后引导 AI 帮你完成后续操作的入门助手 | | **SunSwap DEX Trading** | 在 SunSwap(波场最大的去中心化交易所)上换币 | | **SunPerp Perpetual Futures** | 在 SunPerp 上做永续合约交易 | +| **SunPump Meme Token Toolkit** | 在 SunPump 上创建与交易 meme 代币,查询代币信息、排行、持有者与交易历史 | | **TronScan Data Lookup** | 通过 TronScan 查链上数据 | | **TRC20 Token Toolkit** | TRC20 代币发送等常用操作 | | **TRX Staking & SR Voting** | 质押 TRX 获取能量/带宽,并为超级代表(SR)投票 | | **USDD / JUST Protocol** | 管理 USDD 稳定币与 JUST 协议仓位 | | **Multi-Sig & Account Permissions** | 多签钱包与账户权限管理 | +| **twitter-digest** | 生成 X/Twitter 每日日报(提及、主页时间线、可回复机会) | +| **twitter-mcp** | 为 X/Twitter 安装/授权 xurl,并用本地 xurl CLI 生成日报 | | **x402-payment** | x402 协议支付(Agent 间付款) | | **recharge-skill** | 查询和充值 BANK OF AI 余额 | @@ -328,11 +332,14 @@ Select skills installation scope: │ Multi-Sig & Account Permissions -- -- -- │ recharge-skill Safe 1 alert Med Risk │ SunPerp Perpetual Futures Trading -- -- -- +│ SunPump Meme Token Toolkit -- -- -- │ SunSwap DEX Trading -- -- -- │ TRC20 Token Toolkit -- -- -- │ TronScan Data Lookup -- -- -- │ TRX Staking & SR Voting -- -- -- │ USDD / JUST Protocol -- -- -- +│ twitter-digest -- -- -- +│ twitter-mcp -- -- -- │ x402-payment Safe 1 alert Med Risk │ agent-wallet Safe 1 alert High Risk ``` @@ -340,18 +347,21 @@ Select skills installation scope: 查看报告后确认继续。安装完成时: ``` -◇ Installed 11 skills +◇ Installed 14 skills │ │ ✓ agent-wallet → ~/.openclaw/skills/agent-wallet │ ✓ bankofai-guide → ~/.openclaw/skills/bankofai-guide │ ✓ Multi-Sig & Account Permissions → ~/.openclaw/skills/multi-sig-account-permissions │ ✓ recharge-skill → ~/.openclaw/skills/recharge-skill │ ✓ SunPerp Perpetual Futures Trading → ~/.openclaw/skills/sunperp-perpetual-futures-trading +│ ✓ SunPump Meme Token Toolkit → ~/.openclaw/skills/sunpump-meme-token-toolkit │ ✓ SunSwap DEX Trading → ~/.openclaw/skills/sunswap-dex-trading │ ✓ TRC20 Token Toolkit → ~/.openclaw/skills/trc20-token-toolkit │ ✓ TronScan Data Lookup → ~/.openclaw/skills/tronscan-data-lookup │ ✓ TRX Staking & SR Voting → ~/.openclaw/skills/trx-staking-sr-voting │ ✓ USDD / JUST Protocol → ~/.openclaw/skills/usdd-just-protocol +│ ✓ twitter-digest → ~/.openclaw/skills/twitter-digest +│ ✓ twitter-mcp → ~/.openclaw/skills/twitter-mcp │ ✓ x402-payment → ~/.openclaw/skills/x402-payment ``` diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/get-started.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/get-started.md index 8fe0e560..b093ce40 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/get-started.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/get-started.md @@ -35,23 +35,29 @@ x402-cli --version 装好后,Agent 就能通过 CLI 发现并调用服务。先按服务名或关键字搜索,看看目录里有什么: ```bash -x402-cli catalog search --catalog https://x402-catelog.bankofai.io/api/catalog.json --json +x402-cli catalog search --catalog https://x402-catalog.bankofai.io/api/catalog.json --json ``` 查看某个服务的详情与可用端点: ```bash -x402-cli catalog show --catalog https://x402-catelog.bankofai.io/api/catalog.json --json -x402-cli catalog endpoints --catalog https://x402-catelog.bankofai.io/api/catalog.json --json +x402-cli catalog show --catalog https://x402-catalog.bankofai.io/api/catalog.json --json +x402-cli catalog endpoints --catalog https://x402-catalog.bankofai.io/api/catalog.json --json ``` -确认后,直接对目标端点发起一次付费调用——报价、付款、取回结果一步完成。简单的 GET 端点只需给出 URL: +**免费端点**(服务方未定价的端点)用普通 `curl` 即可拿到结果——无需 CLI、也无需付费: + +```bash +curl -sS 'https://x402-gateway.bankofai.io/providers//...' +``` + +对于**付费端点**,使用 `x402-cli pay`——它一步完成报价、付款和取回结果。简单的 GET 只需给出 URL: ```bash x402-cli pay 'https://x402-gateway.bankofai.io/providers//...' ``` -如果是 POST 端点,或想指定支付链、代币与方案,显式传入对应参数: +如果是付费 POST 端点,或想指定支付链、代币与方案,显式传入对应参数: ```bash x402-cli pay 'https://x402-gateway.bankofai.io/providers//' \ diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/list-your-service.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/list-your-service.md index 88c3b524..7a226630 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/list-your-service.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/list-your-service.md @@ -12,7 +12,7 @@ description: 把你的 API 上架到 API 目录 —— 填表申请或直接提 ## 先看懂全景:上架到底是在做什么 -上架的全部动作,就是向[目录仓库](https://github.com/BofAI/x402-catelog)提交一个 PR,里面只有两份**公开**文件: +上架的全部动作,就是向[目录仓库](https://github.com/BofAI/x402-catalog)提交一个 PR,里面只有两份**公开**文件: | 文件 | 作用 | |---|---| @@ -259,7 +259,7 @@ built 1 provider(s) into dist ## 第 3 步:提交 Pull Request -把这两份文件加入[目录仓库](https://github.com/BofAI/x402-catelog)对应目录: +把这两份文件加入[目录仓库](https://github.com/BofAI/x402-catalog)对应目录: ```text providers//catalog.json diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/reference.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/reference.md index ea2e127a..1b87ee36 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/reference.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/reference.md @@ -6,7 +6,7 @@ description: catalog.json / pay.md 的字段定义、合法类目与链 ID,以 # 数据格式与 API 参考 -本页是 API 目录 的数据契约:服务方向[目录仓库](https://github.com/BofAI/x402-catelog)提交的 `catalog.json` 字段、合法取值,以及目录构建后对外暴露的 `/api/*` 接口结构。 +本页是 API 目录 的数据契约:服务方向[目录仓库](https://github.com/BofAI/x402-catalog)提交的 `catalog.json` 字段、合法取值,以及目录构建后对外暴露的 `/api/*` 接口结构。 ## provider catalog.json 字段 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/OfficialFacilitator.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/OfficialFacilitator.md index 55c282e7..1598aac5 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/OfficialFacilitator.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/OfficialFacilitator.md @@ -62,7 +62,7 @@ Facilitator 由官方持续维护和升级,包括: | 模式 |限速 |说明 | |-----|-----|-----| -| **匿名调用(Anonymous Mode)** | 1 次 / 分钟 | 不需要 API Key,适用于本地开发和功能测试 | +| **匿名调用(Anonymous Mode)** | 10 次 / 分钟(默认值,可配置) | 不需要 API Key,适用于本地开发和功能测试 | | **API Key 调用(API Key Mode)** | 1000 次 / 分钟 | 需要 API Key,适用于生产环境和高频支付请求 | 两种模式的调用方式完全相同,但在 **身份识别与接口限速策略** 上有所不同。 @@ -78,8 +78,8 @@ Facilitator 由官方持续维护和升级,包括: 在匿名模式下: -- `/settle` 接口会启用 **严格限速** -- **每分钟最多 1 次调用** +- `/settle` 接口会启用 **限速** +- **每分钟最多 10 次调用(默认值,可配置)** 该模式主要用于: @@ -256,21 +256,27 @@ curl -X POST https://facilitator.bankofai.io/settle \ |------|------|------| | GET | `/health` | 服务健康检查 | | GET | `/supported` | 查询支持的支付能力和配置 | -| POST | `/fee/quote` | 获取支付要求的费用预估 | | POST | `/verify` | 验证支付载荷有效性 | | POST | `/settle` | 执行链上结算(**受限速保护**) | -| GET | `/payments/{payment_id}` | 按支付 ID 查询支付记录 | -| GET | `/payments/tx/{tx_hash}` | 按交易哈希查询支付记录 | +| GET | `/payments/tx/{tx_hash}` | 按结算交易哈希查询支付记录 | +| GET | `/payments?network=&nonce=[&asset=&payer=]` | 按链上授权身份查询支付记录 | +| GET | `/payments` | 已认证卖家的结算记录流(`?limit=&offset=`) | -> 限速仅作用于 `/settle` 接口,其他接口不受限速影响。 +> **不存在** `/fee/quote` 端点——费用条款随支付要求的 `extra` 字段一起下发。限速仅作用于 `/settle` 接口,其他接口不受限速影响。 ### 支付记录查询 -`/payments/{payment_id}` 和 `/payments/tx/{tx_hash}` 两个接口均返回按时间倒序排列的 JSON 数组。每条记录包含: +`/payments/tx/{tx_hash}` 和 `/payments?network=&nonce=[&asset=&payer=]` 接口均返回按时间倒序排列的 JSON 数组。记录以链上授权身份为键,而非客户端提供的 payment ID。每条记录包含: -- `paymentId` — 支付唯一标识符(可能为空) +- `network` — CAIP-2 网络标识符 +- `scheme` — 支付方案(例如 `exact`) +- `asset` — 代币合约地址 +- `payer` — 付款方地址 +- `nonce` — 授权 nonce +- `amount` — 结算金额(最小单位) - `txHash` — 链上交易哈希 - `status` — `"success"` 或 `"failed"` +- `errorReason` — 失败原因(如有) - `createdAt` — 时间戳 > 提供 API Key 时,这两个接口只返回与你的账户关联的支付记录,不会看到其他卖家的数据。 @@ -281,7 +287,7 @@ curl -X POST https://facilitator.bankofai.io/settle \ **Q:不配置 API Key 能正常运行吗?** -可以运行,但 `/settle` 接口每 IP 每分钟只能调用 1 次。这只适合测试,任何真实流量都必须配置 API Key。 +可以运行,但 `/settle` 接口默认每 IP 每分钟最多调用 10 次。这只适合测试,任何真实流量都必须配置 API Key。 **Q:API Key 会过期吗?** diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/facilitator.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/facilitator.md index 46e25c43..15aa8980 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/facilitator.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/facilitator.md @@ -11,7 +11,7 @@ Facilitator 是一种中间件服务,主要负责: - **验证载荷**:校验客户端提交的支付载荷的有效性。 - **执行结算**:代表服务端将交易提交至区块链进行结算。 -- **代币转移**:执行链上转账——根据方案,调用 ERC-3009 `transferWithAuthorization`、通过 `x402ExactPermit2Proxy` 的 Permit2 `permitTransferFrom`、批量 settlement claim 或 GasFree relay。 +- **代币转移**:执行对应方案的链上结算——ERC-3009 `transferWithAuthorization`、通过 `x402ExactPermit2Proxy`(`exact`)或 `x402UptoPermit2Proxy`(`upto`)的 Permit2 转账、批量 settlement claim,或 GasFree relay。 通过引入 Facilitator,服务端无需维护与区块链节点的直连,也无需自行实现复杂的签名验证逻辑。这不仅降低了运维复杂度,还能确保交易验证的准确性与实时性。 @@ -91,11 +91,15 @@ Facilitator 是一种中间件服务,主要负责: |------|------|------| | GET | `/health` | 服务健康检查 | | GET | `/supported` | 查询支持的支付能力和配置 | -| POST | `/fee/quote` | 获取支付要求的费用预估 | | POST | `/verify` | 验证支付载荷有效性 | -| POST | `/settle` | 执行链上结算(官方 Facilitator 下**受限速保护**) | -| GET | `/payments/{payment_id}` | 按支付 ID 查询支付记录(认证后仅返回当前卖家的记录) | -| GET | `/payments/tx/{tx_hash}` | 按交易哈希查询支付记录(认证后仅返回当前卖家的记录) | +| POST | `/settle` | 执行链上结算(官方 Facilitator 下**受限速保护**);并持久化一条结算记录 | +| GET | `/payments/tx/{tx_hash}` | 按结算交易哈希查询支付记录(认证后仅返回当前卖家的记录) | +| GET | `/payments?network=&nonce=[&asset=&payer=]` | 按链上授权身份查询支付记录(认证后仅返回当前卖家的记录) | +| GET | `/payments` | 已认证卖家的结算记录流(`?limit=&offset=`) | +| GET | `/metrics` | Prometheus 指标(运维用途;仅当监控与主端口共用时才在主端口暴露) | +| ALL | `/mainnet/*` · `/nile/*` | GasFree Open API 透明代理(HMAC 签名)——由 TRON `exact_gasfree` 方案内部使用 | + +> **不存在** `/fee/quote` 端点。费用条款随支付要求的 `extra` 字段一起下发;支付记录以链上授权身份(`network` + `scheme` + `asset` + `payer` + `nonce`)为键,而非客户端提供的 payment ID。 --- @@ -106,9 +110,9 @@ Facilitator 是一种中间件服务,主要负责: | 模式 | 限速 | 认证方式 | |------|------|----------| | **已认证** | 1000 次 / 分钟 | 请求头携带 `X-API-KEY: ` | -| **匿名** | 1 次 / 分钟 | 不携带 API Key | +| **匿名** | 10 次 / 分钟(默认值,可配置) | 不携带 API Key | -其他端点(`/verify`、`/fee/quote`、`/supported`、`/payments/*`)不单独限速。 +其他端点(`/verify`、`/supported`、`/payments/*`)不单独限速。 > **提示**:任何生产级别的工作负载都建议通过[管理后台](https://admin-facilitator.bankofai.io)申请 API Key,以解锁更高的限速配额。 @@ -116,7 +120,7 @@ Facilitator 是一种中间件服务,主要负责: ## 支付记录查询 -`/payments/{payment_id}` 和 `/payments/tx/{tx_hash}` 端点支持查询历史支付记录。 +`/payments/tx/{tx_hash}` 和 `/payments?network=&nonce=[&asset=&payer=]` 端点支持查询历史支付记录;`/payments` 单独返回已认证卖家的结算记录流。记录以链上授权身份(`network` + `scheme` + `asset` + `payer` + `nonce`)为键,而非客户端提供的 payment ID。 当请求携带有效的 `X-API-KEY` 时,返回结果会**自动按该 API Key 关联的卖家进行过滤**——您只能看到自己名下的支付记录。匿名请求(不带 API Key)只能访问未绑定任何卖家的记录。 @@ -126,11 +130,10 @@ Facilitator 是一种中间件服务,主要负责: Facilitator 支持灵活配置服务费用: -- **固定费用 (Base Fee)**:每笔交易收取固定的服务费(例如 `1 USDT`)。 -- **按比例收费 (Percentage Fee)**:按交易金额的一定百分比收取费用。 -- **免费模式 (No Fee)**:支持零费率运营模式。 +- **固定费用 (Base Fee)**:每笔交易按网络和资产收取固定的服务费(例如 `1 USDT`)。 +- **免费模式 (No Fee)**:支持零费率运营模式(例如 EVM `exact` 不收取 Facilitator 费用)。 -具体的费用明细将通过 `/fee/quote` 端点返回,并包含在服务端下发给客户端的支付要求(Payment Requirements)中。 +费用条款包含在服务端下发给客户端的支付要求(Payment Requirements)的 `extra` 字段中;不存在单独的 `/fee/quote` 端点。 --- diff --git a/package.json b/package.json index 64f56fc1..a13d51d4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@x402-tron/docs", - "version": "1.3.2", + "version": "1.3.4", "description": "x402-tron documentation", "license": "MIT", "scripts": { From ebe6d17a71864b6ad89dc80b39f31aeee81d451b Mon Sep 17 00:00:00 2001 From: roger-gan Date: Fri, 10 Jul 2026 15:07:01 +0800 Subject: [PATCH 09/12] docs: update x402 SDK docs --- docs/x402/core-concepts/network-and-token-support.md | 3 ++- docs/x402/faq.md | 4 ++-- docs/x402/getting-started/quickstart-for-agent.md | 4 ++-- docs/x402/getting-started/quickstart-for-human.md | 4 ++-- docs/x402/getting-started/quickstart-for-sellers.md | 4 ++-- docs/x402/index.md | 2 +- docs/x402/sdk-features.md | 6 +++--- .../x402/core-concepts/network-and-token-support.md | 3 ++- .../docusaurus-plugin-content-docs/current/x402/faq.md | 4 ++-- .../current/x402/getting-started/quickstart-for-agent.md | 4 ++-- .../current/x402/getting-started/quickstart-for-human.md | 4 ++-- .../current/x402/getting-started/quickstart-for-sellers.md | 4 ++-- .../docusaurus-plugin-content-docs/current/x402/index.md | 2 +- .../current/x402/sdk-features.md | 7 ++++--- 14 files changed, 29 insertions(+), 26 deletions(-) diff --git a/docs/x402/core-concepts/network-and-token-support.md b/docs/x402/core-concepts/network-and-token-support.md index 78afa64c..320dece4 100644 --- a/docs/x402/core-concepts/network-and-token-support.md +++ b/docs/x402/core-concepts/network-and-token-support.md @@ -63,6 +63,7 @@ By default, **USDT** and **USDD** are used as primary settlement currencies. | **USDD** | `tron:nile` | `TGjgvdTWWrybVLaVeFqSyVqJQWjxqRYbaK` | | **USDT** | `eip155:56` | `0x55d398326f99059fF775485246999027B3197955` | | **USDC** | `eip155:56` | `0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d` | +| **EPS** | `eip155:56` | `0xA7f552078dcC247C2684336020c03648500C6d9F` | | **USDT** | `eip155:97` | `0x337610d27c682E347C9cD60BD4b3b107C9d34dDd` | | **USDC** | `eip155:97` | `0x64544969ed7EBf5f083679233325356EbE738930` | | **DHLU** | `eip155:97` | `0x375cADdd2cB68cE82e3D9B075D551067a7b4B816` | @@ -107,7 +108,7 @@ When configuring an `HTTP 402` payment request on the server side, you must expl ## Payment Schemes -x402 1.0.0 supports five payment schemes. Each is implemented as a client + server + facilitator trio per chain family. +x402 supports five payment schemes. Each is implemented as a client + server + facilitator trio per chain family. ### `exact` Scheme diff --git a/docs/x402/faq.md b/docs/x402/faq.md index 483c3a2d..34ae1c3c 100644 --- a/docs/x402/faq.md +++ b/docs/x402/faq.md @@ -27,7 +27,7 @@ Not at all. Any Web API or content provider—whether Web3-native or traditional #### What languages and frameworks are supported? -x402 1.0.0 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packages: +x402 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packages: - **Server middleware**: Express, Fastify, Hono, Next.js - **Client**: wrapped `fetch` (`@bankofai/x402-fetch`), Axios, MCP transport @@ -68,7 +68,7 @@ Common pricing models include: #### What payment schemes does x402 support? -x402 1.0.0 supports five payment schemes: +x402 supports five payment schemes: - **`exact`**: Pay the exact advertised amount. ERC-3009 tokens (e.g. BSC testnet DHLU) settle gaslessly via `transferWithAuthorization`; plain ERC-20/TRC-20 tokens (e.g. BSC USDC/USDT, TRON USDT/USDD) settle via the Permit2 path with a one-time `approve(Permit2)`. The `exact` wire payload conforms to the **x402 Foundation** v2 spec. - **`upto`**: Usage-based billing — the client signs a Permit2 authorization for up to a **maximum**; the server settles only the **real usage** (≤ max). Ideal for **metered billing**, **LLM token usage**. diff --git a/docs/x402/getting-started/quickstart-for-agent.md b/docs/x402/getting-started/quickstart-for-agent.md index 7135ab06..e6e68620 100644 --- a/docs/x402/getting-started/quickstart-for-agent.md +++ b/docs/x402/getting-started/quickstart-for-agent.md @@ -9,8 +9,8 @@ This guide walks you through: setting up a dedicated agent wallet, configuring c --- -:::info SDK 1.0.0 (TypeScript-only) -x402 `1.0.0` is a **TypeScript-only** SDK. The `x402-payment` skill wraps the new `@bankofai/x402-*` packages and uses [Agent Wallet](../../Agent-Wallet/QuickStart.md) for key custody — the wallet/private-key setup in this guide is unchanged. You can also drive payments directly from the runnable [MCP examples](https://github.com/BofAI/x402/tree/main/examples/typescript) (`servers/mcp` + `clients/mcp`). +:::info SDK (TypeScript-only) +x402 is a **TypeScript-only** SDK. The `x402-payment` skill wraps the new `@bankofai/x402-*` packages and uses [Agent Wallet](../../Agent-Wallet/QuickStart.md) for key custody — the wallet/private-key setup in this guide is unchanged. You can also drive payments directly from the runnable [MCP examples](https://github.com/BofAI/x402/tree/main/examples/typescript) (`servers/mcp` + `clients/mcp`). ::: ## Prerequisites diff --git a/docs/x402/getting-started/quickstart-for-human.md b/docs/x402/getting-started/quickstart-for-human.md index da721b41..a984f8c2 100644 --- a/docs/x402/getting-started/quickstart-for-human.md +++ b/docs/x402/getting-started/quickstart-for-human.md @@ -9,8 +9,8 @@ This guide is for developers who want to **call an x402-protected API from code* > **Testnet first:** This guide uses testnet by default. You can safely follow every step without spending real money. -:::info SDK 1.0.0 (TypeScript-only) -x402 `1.0.0` is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packages. This guide uses the runnable fetch client in the [`x402` repository](https://github.com/BofAI/x402) (`examples/typescript/clients/fetch`), which links the in-repo SDK packages and runs from source. +:::info (TypeScript-only) +x402 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packages. This guide uses the runnable fetch client in the [`x402` repository](https://github.com/BofAI/x402) (`examples/typescript/clients/fetch`), which links the in-repo SDK packages and runs from source. ::: --- diff --git a/docs/x402/getting-started/quickstart-for-sellers.md b/docs/x402/getting-started/quickstart-for-sellers.md index 33d32bf5..ddcfc74c 100644 --- a/docs/x402/getting-started/quickstart-for-sellers.md +++ b/docs/x402/getting-started/quickstart-for-sellers.md @@ -15,8 +15,8 @@ After completing this guide, you'll have a **service that charges for API calls* The entire flow takes **4 steps**, estimated time: **15–20 minutes**. -:::info SDK 1.0.0 (TypeScript-only) -x402 `1.0.0` is a **TypeScript-only** pnpm/turbo monorepo published as granular `@bankofai/x402-*` packages. The previous Python SDK lives under `legacy/` for reference. This guide uses the runnable examples in the [`x402` repository](https://github.com/BofAI/x402) (`examples/typescript/`), which link the in-repo SDK packages and run from source. +:::info (TypeScript-only) +x402 is a **TypeScript-only** pnpm/turbo monorepo published as granular `@bankofai/x402-*` packages. The previous Python SDK lives under `legacy/` for reference. This guide uses the runnable examples in the [`x402` repository](https://github.com/BofAI/x402) (`examples/typescript/`), which link the in-repo SDK packages and run from source. ::: --- diff --git a/docs/x402/index.md b/docs/x402/index.md index 07de30f6..e3dc7239 100644 --- a/docs/x402/index.md +++ b/docs/x402/index.md @@ -81,7 +81,7 @@ x402 currently supports the following networks: - **BSC Mainnet** (`eip155:56`) - **BSC Testnet** (`eip155:97`) -> **SDK 1.0.0 (TypeScript-only)**: x402 `1.0.0` is a TypeScript-only pnpm/turbo monorepo published as granular `@bankofai/x402-*` packages (`core`, `evm`, `tron`, `fetch`, `express`, `hono`, `fastify`, `next`, `axios`, `mcp`, `extensions`). The `core` and EVM mechanism fork the [`x402-foundation/x402`](https://github.com/x402-foundation/x402) upstream; the TRON mechanism is in-house. Supported schemes: `exact` (ERC-3009 / Permit2), `upto`, `batch-settlement`, `auth-capture` (EVM), and `exact_gasfree` (TRON). The previous-generation Python + TypeScript SDK lives under `legacy/` for reference. See the [SDK Feature Matrix](./sdk-features) for the full breakdown. +> **SDK (TypeScript-only)**: x402 is a TypeScript-only pnpm/turbo monorepo published as granular `@bankofai/x402-*` packages (`core`, `evm`, `tron`, `fetch`, `express`, `hono`, `fastify`, `next`, `axios`, `mcp`, `extensions`). The `core` and EVM mechanism fork the [`x402-foundation/x402`](https://github.com/x402-foundation/x402) upstream; the TRON mechanism is in-house. Supported schemes: `exact` (ERC-3009 / Permit2), `upto`, `batch-settlement`, `auth-capture` (EVM), and `exact_gasfree` (TRON). The previous-generation Python + TypeScript SDK lives under `legacy/` for reference. See the [SDK Feature Matrix](./sdk-features) for the full breakdown. --- diff --git a/docs/x402/sdk-features.md b/docs/x402/sdk-features.md index 73c75dac..1a32607a 100644 --- a/docs/x402/sdk-features.md +++ b/docs/x402/sdk-features.md @@ -1,13 +1,13 @@ --- title: 'SDK Feature Matrix' -description: 'Feature support matrix for the x402 TypeScript SDK (1.0.0), published as granular @bankofai/x402-* packages.' +description: 'Feature support matrix for the x402 TypeScript SDK, published as granular @bankofai/x402-* packages.' --- # SDK Feature Matrix This page tracks the feature support of the x402 SDK. -> **SDK 1.0.0 (TypeScript-only)**: x402 is a **TypeScript-only** pnpm/turbo monorepo published as granular `@bankofai/x402-*` packages. The `core` and EVM mechanism fork the [`x402-foundation/x402`](https://github.com/x402-foundation/x402) upstream; the TRON mechanism is in-house. The previous-generation Python + TypeScript SDK lives under `legacy/` for reference. +> **SDK (TypeScript-only)**: x402 is a **TypeScript-only** pnpm/turbo monorepo published as granular `@bankofai/x402-*` packages. The `core` and EVM mechanism fork the [`x402-foundation/x402`](https://github.com/x402-foundation/x402) upstream; the TRON mechanism is in-house. The previous-generation Python + TypeScript SDK lives under `legacy/` for reference. --- @@ -62,7 +62,7 @@ This page tracks the feature support of the x402 SDK. ## Payment Schemes -x402 1.0.0 supports five payment schemes. Each is implemented as a client + server + facilitator trio per chain family. +x402 supports five payment schemes. Each is implemented as a client + server + facilitator trio per chain family. | Scheme | EVM | TRON | Description | |--------|-----|------|-------------| diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/network-and-token-support.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/network-and-token-support.md index 3ac5a924..89a7ce7e 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/network-and-token-support.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/network-and-token-support.md @@ -57,6 +57,7 @@ x402 协议全面支持 **TRC-20/BEP-20** 标准代币,并默认将 **USDT** | **USDD** | `tron:nile` | `TGjgvdTWWrybVLaVeFqSyVqJQWjxqRYbaK` | | **USDT** | `eip155:56` | `0x55d398326f99059fF775485246999027B3197955` | | **USDC** | `eip155:56` | `0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d` | +| **EPS** | `eip155:56` | `0xA7f552078dcC247C2684336020c03648500C6d9F` | | **USDT** | `eip155:97` | `0x337610d27c682E347C9cD60BD4b3b107C9d34dDd` | | **USDC** | `eip155:97` | `0x64544969ed7EBf5f083679233325356EbE738930` | | **DHLU** | `eip155:97` | `0x375cADdd2cB68cE82e3D9B075D551067a7b4B816` | @@ -89,7 +90,7 @@ x402 采用类型化数据签名来处理所有支付相关的签名授权。 ### 支付方案 -x402 1.0.0 支持五种支付方案。每种方案按链族实现为 client + server + facilitator 三件套。 +x402 支持五种支付方案。每种方案按链族实现为 client + server + facilitator 三件套。 #### `exact` 方案 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/faq.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/faq.md index 64683edb..103b80a9 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/faq.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/faq.md @@ -25,7 +25,7 @@ x402 唤醒了长期闲置的 HTTP `402 Payment Required` 状态码,将其转 #### 支持哪些语言和框架? -x402 1.0.0 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发布: +x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发布: - **服务端中间件**:Express、Fastify、Hono、Next.js - **客户端**:包装 `fetch`(`@bankofai/x402-fetch`)、Axios、MCP 传输 @@ -60,7 +60,7 @@ x402 1.0.0 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` #### x402 支持哪些支付方案? -x402 1.0.0 支持五种支付方案: +x402 支持五种支付方案: - **`exact`**:支付公布的准确金额。ERC-3009 代币(如 BSC 测试网 DHLU)通过 `transferWithAuthorization` 无 gas 结算;普通 ERC-20/TRC-20 代币(如 BSC USDC/USDT、TRON USDT/USDD)通过 Permit2 路径结算,首次付款需一次性 `approve(Permit2)`。`exact` 的协议 payload 遵循 **x402 Foundation** 的 v2 规范。 - **`upto`**:按量计费——客户端签署最高至最大金额的 Permit2 授权,服务端仅结算**实际用量**(≤ max)。非常适合**按量计费**、**LLM Token 消耗**等场景。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-agent.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-agent.md index 8376931a..5014f048 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-agent.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-agent.md @@ -9,8 +9,8 @@ x402 专为 Agentic Web 设计。通过安装 `x402-payment` 技能,AI 代理 --- -:::info SDK 1.0.0(仅 TypeScript) -x402 `1.0.0` 是**仅 TypeScript** 的 SDK。`x402-payment` 技能封装了新的 `@bankofai/x402-*` 包,并使用 [Agent Wallet](../../Agent-Wallet/QuickStart.md) 托管密钥——本指南中的钱包/私钥配置方式不变。您也可以直接使用仓库中的可运行 [MCP 示例](https://github.com/BofAI/x402/tree/main/examples/typescript)(`servers/mcp` + `clients/mcp`)驱动付款。 +:::info SDK(仅 TypeScript) +x402 是**仅 TypeScript** 的 SDK。`x402-payment` 技能封装了新的 `@bankofai/x402-*` 包,并使用 [Agent Wallet](../../Agent-Wallet/QuickStart.md) 托管密钥——本指南中的钱包/私钥配置方式不变。您也可以直接使用仓库中的可运行 [MCP 示例](https://github.com/BofAI/x402/tree/main/examples/typescript)(`servers/mcp` + `clients/mcp`)驱动付款。 ::: ## 前置准备 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md index 01ae79a4..b348d8cd 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md @@ -9,8 +9,8 @@ import TabItem from '@theme/TabItem'; > **测试网优先:** 本指南默认使用测试网,您可以安全地完成每一步而不花费真实资金。 -:::info SDK 1.0.0(仅 TypeScript) -x402 `1.0.0` 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发布。本指南使用 [`x402` 仓库](https://github.com/BofAI/x402) 中的可运行 fetch client(`examples/typescript/clients/fetch`),它链接了仓库内的 SDK 包并从源码运行。 +:::info SDK(仅 TypeScript) +x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发布。本指南使用 [`x402` 仓库](https://github.com/BofAI/x402) 中的可运行 fetch client(`examples/typescript/clients/fetch`),它链接了仓库内的 SDK 包并从源码运行。 ::: --- diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-sellers.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-sellers.md index 4e42a246..4c058121 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-sellers.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-sellers.md @@ -15,8 +15,8 @@ import TabItem from '@theme/TabItem'; 整个流程共 **4 步**,预计耗时 **15–20 分钟**。 -:::info SDK 1.0.0(仅 TypeScript) -x402 `1.0.0` 是一个**仅 TypeScript** 的 pnpm/turbo monorepo,以颗粒化的 `@bankofai/x402-*` 包发布。此前的 Python SDK 已移至 `legacy/` 仅供参考。本指南使用 [`x402` 仓库](https://github.com/BofAI/x402) 中的可运行示例(`examples/typescript/`),这些示例链接了仓库内的 SDK 包并从源码运行。 +:::info SDK(仅 TypeScript) +x402 是一个**仅 TypeScript** 的 pnpm/turbo monorepo,以颗粒化的 `@bankofai/x402-*` 包发布。此前的 Python SDK 已移至 `legacy/` 仅供参考。本指南使用 [`x402` 仓库](https://github.com/BofAI/x402) 中的可运行示例(`examples/typescript/`),这些示例链接了仓库内的 SDK 包并从源码运行。 ::: --- diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/index.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/index.md index bfcbf54a..17f86e3b 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/index.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/index.md @@ -67,7 +67,7 @@ x402 目前支持以下网络环境: - **BSC 主网** (`eip155:56`) - **BSC 测试网** (`eip155:97`) -> **SDK 1.0.0(仅 TypeScript)**:x402 `1.0.0` 是仅 TypeScript 的 pnpm/turbo monorepo,以颗粒化 `@bankofai/x402-*` 包发布(`core`、`evm`、`tron`、`fetch`、`express`、`hono`、`fastify`、`next`、`axios`、`mcp`、`extensions`)。`core` 与 EVM 机制 fork 自 [`x402-foundation/x402`](https://github.com/x402-foundation/x402) 上游;TRON 机制为自研。支持的方案:`exact`(ERC-3009 / Permit2)、`upto`、`batch-settlement`、`auth-capture`(EVM)、`exact_gasfree`(TRON)。此前的 Python + TypeScript SDK 已移至 `legacy/` 仅供参考。完整对比详见 [SDK 功能特性](./sdk-features.md)。 +> **SDK(仅 TypeScript)**:x402 是仅 TypeScript 的 pnpm/turbo monorepo,以颗粒化 `@bankofai/x402-*` 包发布(`core`、`evm`、`tron`、`fetch`、`express`、`hono`、`fastify`、`next`、`axios`、`mcp`、`extensions`)。`core` 与 EVM 机制 fork 自 [`x402-foundation/x402`](https://github.com/x402-foundation/x402) 上游;TRON 机制为自研。支持的方案:`exact`(ERC-3009 / Permit2)、`upto`、`batch-settlement`、`auth-capture`(EVM)、`exact_gasfree`(TRON)。此前的 Python + TypeScript SDK 已移至 `legacy/` 仅供参考。完整对比详见 [SDK 功能特性](./sdk-features.md)。 ## 快速开始 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/sdk-features.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/sdk-features.md index df2f98d8..e14e27e4 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/sdk-features.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/sdk-features.md @@ -1,13 +1,13 @@ --- title: 'SDK 功能矩阵' -description: 'x402 TypeScript SDK(1.0.0)的功能支持矩阵,以颗粒化 @bankofai/x402-* 包发布。' +description: 'x402 TypeScript SDK 的功能支持矩阵,以颗粒化 @bankofai/x402-* 包发布。' --- # SDK 功能矩阵 本页跟踪 x402 SDK 的功能支持情况。 -> **SDK 1.0.0(仅 TypeScript)**:x402 是一个**仅 TypeScript** 的 pnpm/turbo monorepo,以颗粒化的 `@bankofai/x402-*` 包发布。`core` 与 EVM 机制 fork 自 [`x402-foundation/x402`](https://github.com/x402-foundation/x402) 上游;TRON 机制为自研。此前的 Python + TypeScript SDK 已移至 `legacy/` 仅供参考。 +> **SDK(仅 TypeScript)**:x402 是一个**仅 TypeScript** 的 pnpm/turbo monorepo,以颗粒化的 `@bankofai/x402-*` 包发布。`core` 与 EVM 机制 fork 自 [`x402-foundation/x402`](https://github.com/x402-foundation/x402) 上游;TRON 机制为自研。此前的 Python + TypeScript SDK 已移至 `legacy/` 仅供参考。 --- @@ -62,7 +62,7 @@ description: 'x402 TypeScript SDK(1.0.0)的功能支持矩阵,以颗粒化 ## 付款方案 -x402 1.0.0 支持五种付款方案。每种方案按链族实现为 client + server + facilitator 三件套。 +x402 支持五种付款方案。每种方案按链族实现为 client + server + facilitator 三件套。 | 方案 | EVM | TRON | 说明 | |--------|-----|------|-------------| @@ -141,6 +141,7 @@ x402 1.0.0 支持五种付款方案。每种方案按链族实现为 client + se | USDD(TRC-20) | `tron:mainnet`、`tron:nile` | ✅ | | USDT(BEP-20) | `eip155:56`、`eip155:97` | ✅ | | USDC(BEP-20) | `eip155:56`、`eip155:97` | ✅ | +| EPS(BEP-20) | `eip155:56` | ✅ | | DHLU(BSC 测试网,ERC-3009) | `eip155:97` | ✅ | | 自定义 TRC-20 / BEP-20 | 任意 | ✅(通过代币注册表 / `EVM_TOKENS` 配置) | From 0a618c1dfe72c21950c3cd8286ae913904ee7624 Mon Sep 17 00:00:00 2001 From: roger-gan Date: Fri, 10 Jul 2026 15:26:42 +0800 Subject: [PATCH 10/12] docs: guide x402 users to npm packages --- docs/x402/AGENTS.md | 8 ++--- docs/x402/faq.md | 18 +++++----- .../getting-started/quickstart-for-agent.md | 12 ++++--- .../getting-started/quickstart-for-human.md | 33 ++++++++----------- .../getting-started/quickstart-for-sellers.md | 29 +++++----------- docs/x402/index.md | 6 ++-- docs/x402/sdk-features.md | 2 +- .../current/x402/AGENTS.md | 7 ++-- .../current/x402/faq.md | 18 +++++----- .../getting-started/quickstart-for-agent.md | 12 ++++--- .../getting-started/quickstart-for-human.md | 33 ++++++++----------- .../getting-started/quickstart-for-sellers.md | 29 +++++----------- .../current/x402/index.md | 4 +-- .../current/x402/sdk-features.md | 2 +- 14 files changed, 90 insertions(+), 123 deletions(-) diff --git a/docs/x402/AGENTS.md b/docs/x402/AGENTS.md index f18a8fb6..f9876e46 100644 --- a/docs/x402/AGENTS.md +++ b/docs/x402/AGENTS.md @@ -27,7 +27,7 @@ import TabItem from '@theme/TabItem'; Documentation must reflect code changes immediately. Follow these dependency mappings: - Changes in `typescript/packages/` → Update TypeScript documentation. -- Changes in `examples/typescript/` → Update "Getting Started" guides and code samples (quickstarts mirror the examples). +- Changes in `examples/typescript/` → Check whether "Getting Started" reference snippets need updates. Quickstarts should present published npm packages as the primary development path; examples are reference implementations. - Endpoint logic changes → Update "Getting Started" guides. - Core mechanism changes → Update `core-concepts` documentation. @@ -36,7 +36,7 @@ Documentation must reflect code changes immediately. Follow these dependency map ## 4. Style & Writing Standards - Use **TypeScript** as the primary example language (the SDK is TypeScript-only; the previous Python SDK lives under `legacy/`). -- Source code samples from the runnable `examples/typescript/` directory whenever possible. +- Prefer code samples that work with the published `@bankofai/x402-*` npm packages. Runnable `examples/typescript/` code may be used as a reference implementation when it matches the package API. - All API examples **must include complete error handling**. - Target audience: developers with **2–5 years of experience**. - Use Docusaurus MDX components (``, ``) for multi-language examples. @@ -135,7 +135,7 @@ When SDK code changes in any of the following areas, you **must** update `docs/s - New signers added under the `*/signers/` directory. - New features introduced in the Client or Server components. -> **Note**: The SDK is TypeScript-only. Cross-check documentation against `typescript/packages/` exports and `examples/typescript/` source. +> **Note**: The SDK is TypeScript-only. Cross-check documentation against the published `@bankofai/x402-*` package API, `typescript/packages/` exports, and `examples/typescript/` reference source. --- @@ -153,4 +153,4 @@ yarn build # Serve production build locally yarn serve -``` \ No newline at end of file +``` diff --git a/docs/x402/faq.md b/docs/x402/faq.md index 34ae1c3c..69d85fd3 100644 --- a/docs/x402/faq.md +++ b/docs/x402/faq.md @@ -156,14 +156,16 @@ The flow mirrors a human user: ### Development Guide -#### How do I run x402 locally? - -1. **Clone the repository:** `git clone https://github.com/BofAI/x402.git` -2. **Install + build:** `cd x402/typescript && pnpm install && pnpm build` -3. **Configure environment:** `cd examples/typescript && cp .env-exact.example .env-exact` and fill in `AGENT_WALLET_PRIVATE_KEY` + payout addresses -4. **Start Facilitator:** `pnpm dev:facilitator` (terminal 1, `:4022`) -5. **Start Server:** `pnpm dev:server` (terminal 2, `:4021`) -6. **Run Client:** `pnpm dev:client` (terminal 3) +#### How do I develop with x402 locally? + +Install the published packages in your TypeScript app and build against npm, for example: + +```bash +pnpm add @bankofai/x402-fetch @bankofai/x402-tron @bankofai/x402-evm @bankofai/agent-wallet +pnpm add @bankofai/x402-core @bankofai/x402-express +``` + +Use the framework package that matches your server (`express`, `hono`, `fastify`, or `next`). The [`examples/typescript`](https://github.com/BofAI/x402/tree/main/examples/typescript) workspace is a runnable reference for client → server → facilitator flows, not a prerequisite for application development. #### Which testnet is recommended? diff --git a/docs/x402/getting-started/quickstart-for-agent.md b/docs/x402/getting-started/quickstart-for-agent.md index e6e68620..f1930984 100644 --- a/docs/x402/getting-started/quickstart-for-agent.md +++ b/docs/x402/getting-started/quickstart-for-agent.md @@ -10,7 +10,7 @@ This guide walks you through: setting up a dedicated agent wallet, configuring c --- :::info SDK (TypeScript-only) -x402 is a **TypeScript-only** SDK. The `x402-payment` skill wraps the new `@bankofai/x402-*` packages and uses [Agent Wallet](../../Agent-Wallet/QuickStart.md) for key custody — the wallet/private-key setup in this guide is unchanged. You can also drive payments directly from the runnable [MCP examples](https://github.com/BofAI/x402/tree/main/examples/typescript) (`servers/mcp` + `clients/mcp`). +x402 is a **TypeScript-only** SDK published as `@bankofai/x402-*` npm packages. The `x402-payment` skill wraps those packages and uses [Agent Wallet](../../Agent-Wallet/QuickStart.md) for key custody — the wallet/private-key setup in this guide is unchanged. The runnable [MCP examples](https://github.com/BofAI/x402/tree/main/examples/typescript) (`servers/mcp` + `clients/mcp`) are reference implementations. ::: ## Prerequisites @@ -136,9 +136,11 @@ For a detailed walkthrough of the interactive installation process, see the [Ski After completing the setup, follow these steps to verify your agent can complete payments autonomously: -### 3.1 Test with a Local Paid Endpoint +### 3.1 Test with a Paid Endpoint -First, get the SDK and examples (requires **Node.js 22+** and **pnpm 11.1+**): +Point your agent at an x402-protected endpoint built with the published npm packages, for example a service created from [Quickstart for Sellers](./quickstart-for-sellers.md). + +If you do not have a paid endpoint yet, you can run the repository examples as a local reference environment (requires **Node.js 22+** and **pnpm 11.1+**): ```bash git clone https://github.com/BofAI/x402.git @@ -150,11 +152,11 @@ pnpm build # Examples live in a separate workspace at the repo root cd ../examples/typescript -pnpm install # links the in-repo SDK packages + example deps +pnpm install # installs the reference example dependencies cp .env-exact.example .env-exact # fill AGENT_WALLET_PRIVATE_KEY + payout addresses ``` -Then start the facilitator and the resource server **in two separate terminals** (both from `examples/typescript`): +Then start the reference facilitator and resource server **in two separate terminals** (both from `examples/typescript`): ```bash # Terminal 1 — facilitator (verifies + settles on-chain) diff --git a/docs/x402/getting-started/quickstart-for-human.md b/docs/x402/getting-started/quickstart-for-human.md index a984f8c2..062fed7a 100644 --- a/docs/x402/getting-started/quickstart-for-human.md +++ b/docs/x402/getting-started/quickstart-for-human.md @@ -10,7 +10,7 @@ This guide is for developers who want to **call an x402-protected API from code* > **Testnet first:** This guide uses testnet by default. You can safely follow every step without spending real money. :::info (TypeScript-only) -x402 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packages. This guide uses the runnable fetch client in the [`x402` repository](https://github.com/BofAI/x402) (`examples/typescript/clients/fetch`), which links the in-repo SDK packages and runs from source. +x402 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packages. This guide shows how to integrate the published npm packages directly; the runnable [`examples/typescript/clients/fetch`](https://github.com/BofAI/x402/tree/main/examples/typescript/clients/fetch) project is a reference implementation, not the required development path. ::: --- @@ -89,27 +89,18 @@ x402 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packa --- -## Step One: Get the SDK and Examples +## Step One: Install the SDK Packages -The examples workspace links the in-repo `@bankofai/x402-*` packages and runs from source: +Install the published npm packages in your TypeScript application: ```bash -git clone https://github.com/BofAI/x402.git -cd x402/typescript # the pnpm/turbo monorepo root (SDK packages) - -# Install + link the SDK packages, then build their dist -pnpm install -pnpm build - -# Examples live in a separate workspace at the repo root -cd ../examples/typescript -pnpm install # links the in-repo SDK packages + example deps +pnpm add @bankofai/x402-fetch @bankofai/x402-tron @bankofai/x402-evm @bankofai/agent-wallet ``` -The fetch client depends on `@bankofai/x402-fetch`, `@bankofai/x402-evm`, `@bankofai/x402-tron`, and `@bankofai/agent-wallet` — all linked automatically by `pnpm install`. +Use `npm install` or `yarn add` with the same package names if your project does not use pnpm. :::info Wallet Management -x402 uses [Agent Wallet](../../Agent-Wallet/QuickStart.md) to resolve and manage wallet credentials. Agent Wallet is installed as a dependency of the examples. Private key resolution priority: +x402 uses [Agent Wallet](../../Agent-Wallet/QuickStart.md) to resolve and manage wallet credentials. Agent Wallet is installed with the package set above. Private key resolution priority: 1. Encrypted wallet file (imported via the Agent Wallet CLI) 2. Environment variable `AGENT_WALLET_PRIVATE_KEY` @@ -176,7 +167,7 @@ EVM_RPC_URL=https://bsc-testnet-rpc.publicnode.com ## Step Three: Write and Run the Client Code -The example fetch client wraps `fetch` so HTTP `402 Payment Required` challenges are paid automatically. Here is the entry point (`examples/typescript/clients/fetch/src/index.ts`), abridged to the essentials: +The client wraps `fetch` so HTTP `402 Payment Required` challenges are paid automatically. The runnable example at `examples/typescript/clients/fetch/src/index.ts` follows the same structure; the essentials are: ```typescript import { x402Client, wrapFetchWithPayment } from "@bankofai/x402-fetch"; @@ -281,12 +272,14 @@ export async function registerEvm(client: x402Client): Promise { ### Run the client -First, make sure a resource server + facilitator are running (see [Quickstart for Sellers](./quickstart-for-sellers.md)), then from `examples/typescript`: +First, make sure a resource server + facilitator are running (see [Quickstart for Sellers](./quickstart-for-sellers.md)), then run your client app with the same environment variables: ```bash -pnpm dev:client +pnpm tsx src/index.ts # or your app's dev script ``` +If you are comparing against the reference example, run `pnpm dev:client` from `examples/typescript`. + **Expected output:** ``` @@ -358,6 +351,6 @@ Through this guide you: ## References -- [x402 repository](https://github.com/BofAI/x402) — SDK source and runnable examples (`examples/typescript/`) -- [Fetch client example](https://github.com/BofAI/x402/tree/main/examples/typescript/clients/fetch) — the client this guide is based on +- [x402 npm packages](https://www.npmjs.com/package/@bankofai/x402-tron) — published packages for application development +- [Fetch client example](https://github.com/BofAI/x402/tree/main/examples/typescript/clients/fetch) — reference implementation for the client flow - [Agent Wallet](https://github.com/BofAI/agent-wallet) — key custody used by the SDK diff --git a/docs/x402/getting-started/quickstart-for-sellers.md b/docs/x402/getting-started/quickstart-for-sellers.md index ddcfc74c..3cb0befa 100644 --- a/docs/x402/getting-started/quickstart-for-sellers.md +++ b/docs/x402/getting-started/quickstart-for-sellers.md @@ -16,7 +16,7 @@ After completing this guide, you'll have a **service that charges for API calls* The entire flow takes **4 steps**, estimated time: **15–20 minutes**. :::info (TypeScript-only) -x402 is a **TypeScript-only** pnpm/turbo monorepo published as granular `@bankofai/x402-*` packages. The previous Python SDK lives under `legacy/` for reference. This guide uses the runnable examples in the [`x402` repository](https://github.com/BofAI/x402) (`examples/typescript/`), which link the in-repo SDK packages and run from source. +x402 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packages. This guide shows how to build with the published npm packages; the runnable [`examples/typescript`](https://github.com/BofAI/x402/tree/main/examples/typescript) projects are reference implementations for comparison and smoke testing. ::: --- @@ -112,39 +112,26 @@ You need a blockchain wallet address to receive tokens from users. Follow the st --- -## Step 1: Get the SDK and Examples +## Step 1: Install the SDK Packages -The examples workspace links the in-repo `@bankofai/x402-*` packages and builds from source, so you get the latest SDK without publishing to a registry. +Install the server, chain, and wallet packages in your TypeScript API project: ```bash -git clone https://github.com/BofAI/x402.git -cd x402/typescript # the pnpm/turbo monorepo root (SDK packages) - -# Install + link the SDK packages, then build their dist -pnpm install -pnpm build - -# Examples live in a separate workspace at the repo root -cd ../examples/typescript -pnpm install # links the in-repo SDK packages + example deps +pnpm add @bankofai/x402-core @bankofai/x402-express @bankofai/x402-tron @bankofai/x402-evm @bankofai/agent-wallet ``` -Verify the install by starting the example resource server (it will print a port and the chains it accepts): - -```bash -pnpm dev:server -``` +Use the framework package that matches your server (`@bankofai/x402-express`, `@bankofai/x402-hono`, `@bankofai/x402-fastify`, or `@bankofai/x402-next`). Use `npm install` or `yarn add` with the same package names if your project does not use pnpm. -> ✅ **Success:** The server boots and prints a startup line. With no payout address set yet it exits with `❌ No payout address configured (set EVM_ADDRESS and/or TRON_ADDRESS)` — that's expected and confirms the toolchain works. You'll set those in Step 2. +The repository examples remain useful as working references, but application development should depend on the published packages instead of linking the monorepo source. --- ## Step 2: Configure Your Environment -All three processes in the main line (facilitator, server, client) share one file: `.env-exact`. Copy the template and fill it in: +Create a local `.env-exact` file for your API and fill it in: ```bash -cp .env-exact.example .env-exact +touch .env-exact ``` Open `.env-exact` in your editor and set the wallet + payout variables: diff --git a/docs/x402/index.md b/docs/x402/index.md index e3dc7239..f224eb90 100644 --- a/docs/x402/index.md +++ b/docs/x402/index.md @@ -14,8 +14,8 @@ x402 currently supports the **TRON** and **BSC** networks, with plans to expand **Interested in contributing to the documentation?** Feel free to submit a PR to the [GitHub repository](https://github.com/BofAI/docs). Our only principle is to maintain neutrality — aside from essential resource links, please avoid promotional or branded content. -**Looking for runnable examples?** -The [`x402` repository](https://github.com/BofAI/x402) ships runnable client → server → facilitator trios under `examples/typescript/` for every scheme — `exact`, `gasfree`, `upto`, and `batch-settlement`. +**Building with x402?** +Install the published [`@bankofai/x402-*`](https://www.npmjs.com/package/@bankofai/x402-tron) packages in your TypeScript app. The [`x402` repository](https://github.com/BofAI/x402) ships runnable client → server → facilitator examples under `examples/typescript/` for reference — `exact`, `gasfree`, `upto`, and `batch-settlement`. --- @@ -81,7 +81,7 @@ x402 currently supports the following networks: - **BSC Mainnet** (`eip155:56`) - **BSC Testnet** (`eip155:97`) -> **SDK (TypeScript-only)**: x402 is a TypeScript-only pnpm/turbo monorepo published as granular `@bankofai/x402-*` packages (`core`, `evm`, `tron`, `fetch`, `express`, `hono`, `fastify`, `next`, `axios`, `mcp`, `extensions`). The `core` and EVM mechanism fork the [`x402-foundation/x402`](https://github.com/x402-foundation/x402) upstream; the TRON mechanism is in-house. Supported schemes: `exact` (ERC-3009 / Permit2), `upto`, `batch-settlement`, `auth-capture` (EVM), and `exact_gasfree` (TRON). The previous-generation Python + TypeScript SDK lives under `legacy/` for reference. See the [SDK Feature Matrix](./sdk-features) for the full breakdown. +> **SDK (TypeScript-only)**: x402 is a TypeScript-only SDK published as granular `@bankofai/x402-*` npm packages (`core`, `evm`, `tron`, `fetch`, `express`, `hono`, `fastify`, `next`, `axios`, `mcp`, `extensions`). The source is maintained in a pnpm/turbo monorepo, but application development should install the published packages. Supported schemes: `exact` (ERC-3009 / Permit2), `upto`, `batch-settlement`, `auth-capture` (EVM), and `exact_gasfree` (TRON). The previous-generation Python + TypeScript SDK lives under `legacy/` for reference. See the [SDK Feature Matrix](./sdk-features) for the full breakdown. --- diff --git a/docs/x402/sdk-features.md b/docs/x402/sdk-features.md index 1a32607a..677130f9 100644 --- a/docs/x402/sdk-features.md +++ b/docs/x402/sdk-features.md @@ -7,7 +7,7 @@ description: 'Feature support matrix for the x402 TypeScript SDK, published as g This page tracks the feature support of the x402 SDK. -> **SDK (TypeScript-only)**: x402 is a **TypeScript-only** pnpm/turbo monorepo published as granular `@bankofai/x402-*` packages. The `core` and EVM mechanism fork the [`x402-foundation/x402`](https://github.com/x402-foundation/x402) upstream; the TRON mechanism is in-house. The previous-generation Python + TypeScript SDK lives under `legacy/` for reference. +> **SDK (TypeScript-only)**: x402 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` npm packages. The source is maintained in a pnpm/turbo monorepo, but applications should depend on the published packages. The previous-generation Python + TypeScript SDK lives under `legacy/` for reference. --- diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/AGENTS.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/AGENTS.md index 3574f32c..3c4ba61d 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/AGENTS.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/AGENTS.md @@ -23,13 +23,13 @@ import TabItem from '@theme/TabItem'; 文档维护需遵循以下依赖关系,确保代码变更即时反映在文档中: - `typescript/packages/` 目录下的变更 $\rightarrow$ 需同步更新 TypeScript 相关文档。 -- `examples/typescript/` 目录下的变更 $\rightarrow$ 需更新「快速入门」指南与代码示例(快速入门以示例为蓝本)。 +- `examples/typescript/` 目录下的变更 $\rightarrow$ 检查「快速入门」中的参考代码是否需要更新。快速入门应以已发布 npm 包作为主要开发路径,examples 作为参考实现。 - 端点逻辑的变更 $\rightarrow$ 需更新“快速入门”指南。 - 底层机制的变更 $\rightarrow$ 需更新 `core-concepts` 文档。 ## 4. 风格与规范 - 以 **TypeScript** 作为主要代码示例(SDK 仅 TypeScript;此前的 Python SDK 已移至 `legacy/`)。 -- 尽可能引用 `examples/typescript/` 目录中的可运行示例源码。 +- 优先提供可直接基于已发布 `@bankofai/x402-*` npm 包运行的代码示例。`examples/typescript/` 中的可运行代码可作为与包 API 一致时的参考实现。 - 所有 API 调用示例必须包含完整的错误处理逻辑。 - 内容撰写面向具有 **2–5 年经验** 的开发者。 - 必须使用 Docusaurus MDX 组件(``、``)来展示多语言代码。 @@ -117,7 +117,7 @@ import TabItem from '@theme/TabItem'; - `*/signers/` 目录中新增了签名器。 - 客户端 (Client) 或服务端 (Server) 新增了功能特性。 -**注意**:SDK 仅 TypeScript。更新文档时需对照 `typescript/packages/` 的导出与 `examples/typescript/` 的源码交叉检查。 +**注意**:SDK 仅 TypeScript。更新文档时需对照已发布的 `@bankofai/x402-*` 包 API、`typescript/packages/` 的导出与 `examples/typescript/` 的参考源码交叉检查。 ## 12.开发常用命令 @@ -135,4 +135,3 @@ yarn build # 本地服务生产构建 yarn serve ``` - diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/faq.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/faq.md index 103b80a9..17f08830 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/faq.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/faq.md @@ -139,14 +139,16 @@ x402 支持五种支付方案: ### 开发指南 -#### 如何在本地运行 x402? - -1. **克隆仓库:** `git clone https://github.com/BofAI/x402.git` -2. **安装并构建:** `cd x402/typescript && pnpm install && pnpm build` -3. **配置环境:** `cd examples/typescript && cp .env-exact.example .env-exact`,填入 `AGENT_WALLET_PRIVATE_KEY` 与收款地址 -4. **启动 Facilitator:** `pnpm dev:facilitator`(终端 1,`:4022`) -5. **启动服务端:** `pnpm dev:server`(终端 2,`:4021`) -6. **运行客户端:** `pnpm dev:client`(终端 3) +#### 如何在本地开发 x402? + +在您的 TypeScript 应用中安装已发布的 npm 包并基于这些包开发,例如: + +```bash +pnpm add @bankofai/x402-fetch @bankofai/x402-tron @bankofai/x402-evm @bankofai/agent-wallet +pnpm add @bankofai/x402-core @bankofai/x402-express +``` + +请根据服务框架选择对应包(`express`、`hono`、`fastify` 或 `next`)。[`examples/typescript`](https://github.com/BofAI/x402/tree/main/examples/typescript) 工作区是 client → server → facilitator 流程的可运行参考,不是应用开发的前置条件。 #### 推荐使用哪个测试网? diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-agent.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-agent.md index 5014f048..dd183d18 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-agent.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-agent.md @@ -10,7 +10,7 @@ x402 专为 Agentic Web 设计。通过安装 `x402-payment` 技能,AI 代理 --- :::info SDK(仅 TypeScript) -x402 是**仅 TypeScript** 的 SDK。`x402-payment` 技能封装了新的 `@bankofai/x402-*` 包,并使用 [Agent Wallet](../../Agent-Wallet/QuickStart.md) 托管密钥——本指南中的钱包/私钥配置方式不变。您也可以直接使用仓库中的可运行 [MCP 示例](https://github.com/BofAI/x402/tree/main/examples/typescript)(`servers/mcp` + `clients/mcp`)驱动付款。 +x402 是以 `@bankofai/x402-*` npm 包发布的**仅 TypeScript** SDK。`x402-payment` 技能封装这些包,并使用 [Agent Wallet](../../Agent-Wallet/QuickStart.md) 托管密钥——本指南中的钱包/私钥配置方式不变。可运行的 [MCP 示例](https://github.com/BofAI/x402/tree/main/examples/typescript)(`servers/mcp` + `clients/mcp`)是参考实现。 ::: ## 前置准备 @@ -136,9 +136,11 @@ npx skills add https://github.com/BofAI/skills 完成配置后,按以下步骤验证代理能够正常自主付款: -### 3.1 使用本地付费接口测试 +### 3.1 使用付费接口测试 -首先,获取 SDK 与示例(需要 **Node.js 22+** 和 **pnpm 11.1+**): +将代理指向一个基于已发布 npm 包构建的 x402 付费接口,例如按照[卖家快速入门](./quickstart-for-sellers.md)创建的服务。 + +如果您还没有付费接口,可以运行仓库 examples 作为本地参考环境(需要 **Node.js 22+** 和 **pnpm 11.1+**): ```bash git clone https://github.com/BofAI/x402.git @@ -150,11 +152,11 @@ pnpm build # 示例位于仓库根目录下的独立工作区 cd ../examples/typescript -pnpm install # 链接仓库内 SDK 包 + 示例依赖 +pnpm install # 安装参考示例依赖 cp .env-exact.example .env-exact # 填入 AGENT_WALLET_PRIVATE_KEY + 收款地址 ``` -然后在**两个独立终端**启动 facilitator 和资源服务器(均在 `examples/typescript` 下): +然后在**两个独立终端**启动参考 facilitator 和资源服务器(均在 `examples/typescript` 下): ```bash # 终端 1 —— facilitator(验证并链上结算) diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md index b348d8cd..d9ced38b 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md @@ -10,7 +10,7 @@ import TabItem from '@theme/TabItem'; > **测试网优先:** 本指南默认使用测试网,您可以安全地完成每一步而不花费真实资金。 :::info SDK(仅 TypeScript) -x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发布。本指南使用 [`x402` 仓库](https://github.com/BofAI/x402) 中的可运行 fetch client(`examples/typescript/clients/fetch`),它链接了仓库内的 SDK 包并从源码运行。 +x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发布。本指南展示如何直接集成已发布的 npm 包;[`examples/typescript/clients/fetch`](https://github.com/BofAI/x402/tree/main/examples/typescript/clients/fetch) 是可运行参考实现,不是必须采用的开发路径。 ::: --- @@ -89,27 +89,18 @@ x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发 --- -## 第一步:获取 SDK 与示例 +## 第一步:安装 SDK 包 -示例工作区链接了仓库内的 `@bankofai/x402-*` 包并从源码运行: +在您的 TypeScript 应用中安装已发布的 npm 包: ```bash -git clone https://github.com/BofAI/x402.git -cd x402/typescript # pnpm/turbo monorepo 根目录(SDK 包) - -# 安装并链接 SDK 包,然后构建其 dist -pnpm install -pnpm build - -# 示例位于仓库根目录下的独立工作区 -cd ../examples/typescript -pnpm install # 链接仓库内 SDK 包 + 示例依赖 +pnpm add @bankofai/x402-fetch @bankofai/x402-tron @bankofai/x402-evm @bankofai/agent-wallet ``` -fetch client 依赖 `@bankofai/x402-fetch`、`@bankofai/x402-evm`、`@bankofai/x402-tron` 和 `@bankofai/agent-wallet`——全部由 `pnpm install` 自动链接。 +如果您的项目不使用 pnpm,也可以用 `npm install` 或 `yarn add` 安装同名包。 :::info 钱包管理 -x402 使用 [Agent Wallet](../../Agent-Wallet/QuickStart.md) 解析和管理钱包凭据。Agent Wallet 作为示例的依赖自动安装。私钥解析优先级: +x402 使用 [Agent Wallet](../../Agent-Wallet/QuickStart.md) 解析和管理钱包凭据。Agent Wallet 会随上面的包一起安装。私钥解析优先级: 1. 加密钱包文件(通过 Agent Wallet CLI 导入) 2. 环境变量 `AGENT_WALLET_PRIVATE_KEY` @@ -176,7 +167,7 @@ EVM_RPC_URL=https://bsc-testnet-rpc.publicnode.com ## 第三步:编写并运行客户端代码 -示例 fetch client 包装 `fetch`,使 HTTP `402 Payment Required` 挑战自动支付。以下是入口(`examples/typescript/clients/fetch/src/index.ts`),节选至要点: +客户端会包装 `fetch`,使 HTTP `402 Payment Required` 挑战自动支付。可运行示例 `examples/typescript/clients/fetch/src/index.ts` 采用相同结构;要点如下: ```typescript import { x402Client, wrapFetchWithPayment } from "@bankofai/x402-fetch"; @@ -281,12 +272,14 @@ export async function registerEvm(client: x402Client): Promise { ### 运行 client -首先确保资源服务器 + facilitator 正在运行(参见[卖家快速入门](./quickstart-for-sellers.md)),然后从 `examples/typescript` 运行: +首先确保资源服务器 + facilitator 正在运行(参见[卖家快速入门](./quickstart-for-sellers.md)),然后用同一组环境变量运行您的客户端应用: ```bash -pnpm dev:client +pnpm tsx src/index.ts # 或您的应用 dev 脚本 ``` +如果您是在对照参考示例,请在 `examples/typescript` 下运行 `pnpm dev:client`。 + **预期输出:** ``` @@ -358,6 +351,6 @@ try { ## 参考资料 -- [x402 仓库](https://github.com/BofAI/x402) —— SDK 源码与可运行示例(`examples/typescript/`) -- [fetch client 示例](https://github.com/BofAI/x402/tree/main/examples/typescript/clients/fetch) —— 本指南所基于的 client +- [x402 npm 包](https://www.npmjs.com/package/@bankofai/x402-tron) —— 应用开发应优先安装的发布包 +- [fetch client 示例](https://github.com/BofAI/x402/tree/main/examples/typescript/clients/fetch) —— client 流程参考实现 - [Agent Wallet](https://github.com/BofAI/agent-wallet) —— SDK 使用的密钥托管 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-sellers.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-sellers.md index 4c058121..418f6344 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-sellers.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-sellers.md @@ -16,7 +16,7 @@ import TabItem from '@theme/TabItem'; 整个流程共 **4 步**,预计耗时 **15–20 分钟**。 :::info SDK(仅 TypeScript) -x402 是一个**仅 TypeScript** 的 pnpm/turbo monorepo,以颗粒化的 `@bankofai/x402-*` 包发布。此前的 Python SDK 已移至 `legacy/` 仅供参考。本指南使用 [`x402` 仓库](https://github.com/BofAI/x402) 中的可运行示例(`examples/typescript/`),这些示例链接了仓库内的 SDK 包并从源码运行。 +x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发布。本指南展示如何基于已发布的 npm 包开发;[`examples/typescript`](https://github.com/BofAI/x402/tree/main/examples/typescript) 中的可运行项目是参考实现,可用于对照和 smoke test。 ::: --- @@ -112,39 +112,26 @@ git --version # 版本控制工具 --- -## 第一步:获取 SDK 与示例 +## 第一步:安装 SDK 包 -示例工作区链接了仓库内的 `@bankofai/x402-*` 包并从源码构建,无需发布到 npm 仓库即可获得最新 SDK: +在您的 TypeScript API 项目中安装 server、链和钱包相关包: ```bash -git clone https://github.com/BofAI/x402.git -cd x402/typescript # pnpm/turbo monorepo 根目录(SDK 包) - -# 安装并链接 SDK 包,然后构建其 dist -pnpm install -pnpm build - -# 示例位于仓库根目录下的独立工作区 -cd ../examples/typescript -pnpm install # 链接仓库内 SDK 包 + 示例依赖 +pnpm add @bankofai/x402-core @bankofai/x402-express @bankofai/x402-tron @bankofai/x402-evm @bankofai/agent-wallet ``` -通过启动示例资源服务器来验证安装(它会打印端口和所接受的链): - -```bash -pnpm dev:server -``` +请根据服务框架选择对应包(`@bankofai/x402-express`、`@bankofai/x402-hono`、`@bankofai/x402-fastify` 或 `@bankofai/x402-next`)。如果项目不使用 pnpm,也可以用 `npm install` 或 `yarn add` 安装同名包。 -> ✅ **成功:** 服务器启动并打印启动日志。在未设置收款地址时它会以 `❌ No payout address configured (set EVM_ADDRESS and/or TRON_ADDRESS)` 退出——这是预期行为,说明工具链可用。您将在第二步设置这些地址。 +仓库中的 examples 仍然适合作为可运行参考,但应用开发应依赖已发布的 npm 包,而不是链接 monorepo 源码。 --- ## 第二步:配置环境变量 -主线(facilitator、server、client)三个进程共用一个文件:`.env-exact`。复制模板并填写: +在您的 API 项目中创建本地 `.env-exact` 文件并填写: ```bash -cp .env-exact.example .env-exact +touch .env-exact ``` 在编辑器中打开 `.env-exact`,设置钱包与收款变量: diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/index.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/index.md index 17f86e3b..844e029e 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/index.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/index.md @@ -11,7 +11,7 @@ x402 是一种基于 HTTP `402 Payment Required` 状态码的区块链开放支 **有意参与文档共建?** 欢迎在 [GitHub 仓库](https://github.com/BofAI/docs)提交 PR!我们唯一的原则是保持文档的中立性:除必要的资源链接外,请避免包含任何品牌推广内容。 -**寻找可运行示例?** [`x402` 仓库](https://github.com/BofAI/x402) 在 `examples/typescript/` 下提供了每种方案的完整 client → server → facilitator 可运行三件套——`exact`、`gasfree`、`upto`、`batch-settlement`。 +**使用 x402 开发?** 请在您的 TypeScript 应用中安装已发布的 [`@bankofai/x402-*`](https://www.npmjs.com/package/@bankofai/x402-tron) 包。[`x402` 仓库](https://github.com/BofAI/x402) 在 `examples/typescript/` 下提供完整 client → server → facilitator 可运行示例,用于参考——`exact`、`gasfree`、`upto`、`batch-settlement`。 ## 为什么要使用 x402? @@ -67,7 +67,7 @@ x402 目前支持以下网络环境: - **BSC 主网** (`eip155:56`) - **BSC 测试网** (`eip155:97`) -> **SDK(仅 TypeScript)**:x402 是仅 TypeScript 的 pnpm/turbo monorepo,以颗粒化 `@bankofai/x402-*` 包发布(`core`、`evm`、`tron`、`fetch`、`express`、`hono`、`fastify`、`next`、`axios`、`mcp`、`extensions`)。`core` 与 EVM 机制 fork 自 [`x402-foundation/x402`](https://github.com/x402-foundation/x402) 上游;TRON 机制为自研。支持的方案:`exact`(ERC-3009 / Permit2)、`upto`、`batch-settlement`、`auth-capture`(EVM)、`exact_gasfree`(TRON)。此前的 Python + TypeScript SDK 已移至 `legacy/` 仅供参考。完整对比详见 [SDK 功能特性](./sdk-features.md)。 +> **SDK(仅 TypeScript)**:x402 是仅 TypeScript 的 SDK,以颗粒化 `@bankofai/x402-*` npm 包发布(`core`、`evm`、`tron`、`fetch`、`express`、`hono`、`fastify`、`next`、`axios`、`mcp`、`extensions`)。源码由 pnpm/turbo monorepo 维护,但应用开发应安装已发布的包。支持的方案:`exact`(ERC-3009 / Permit2)、`upto`、`batch-settlement`、`auth-capture`(EVM)、`exact_gasfree`(TRON)。此前的 Python + TypeScript SDK 已移至 `legacy/` 仅供参考。完整对比详见 [SDK 功能特性](./sdk-features.md)。 ## 快速开始 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/sdk-features.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/sdk-features.md index e14e27e4..52417d05 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/sdk-features.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/sdk-features.md @@ -7,7 +7,7 @@ description: 'x402 TypeScript SDK 的功能支持矩阵,以颗粒化 @bankofai 本页跟踪 x402 SDK 的功能支持情况。 -> **SDK(仅 TypeScript)**:x402 是一个**仅 TypeScript** 的 pnpm/turbo monorepo,以颗粒化的 `@bankofai/x402-*` 包发布。`core` 与 EVM 机制 fork 自 [`x402-foundation/x402`](https://github.com/x402-foundation/x402) 上游;TRON 机制为自研。此前的 Python + TypeScript SDK 已移至 `legacy/` 仅供参考。 +> **SDK(仅 TypeScript)**:x402 是一个**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` npm 包发布。源码由 pnpm/turbo monorepo 维护,但应用应依赖已发布的包。此前的 Python + TypeScript SDK 已移至 `legacy/` 仅供参考。 --- From 2982e70d4386801f516866d6c25e32d0c070d44f Mon Sep 17 00:00:00 2001 From: roger-gan Date: Fri, 10 Jul 2026 17:19:49 +0800 Subject: [PATCH 11/12] replace pip to npm --- docs/x402/api-catalog/get-started.md | 8 ++++---- docs/x402/api-catalog/reference.md | 2 +- .../current/x402/api-catalog/get-started.md | 8 ++++---- .../current/x402/api-catalog/reference.md | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/x402/api-catalog/get-started.md b/docs/x402/api-catalog/get-started.md index 9b8cc647..f5ae92e8 100644 --- a/docs/x402/api-catalog/get-started.md +++ b/docs/x402/api-catalog/get-started.md @@ -8,14 +8,14 @@ description: Plug your Agent into the API Catalog in 3 minutes — install the A Two steps and under 3 minutes to plug your Agent into the whole catalog: install the wallet, then install the x402 CLI. After that, your Agent can discover and call any service in the catalog, paying per call on-chain. -**Prerequisite**: Node.js (for the wallet) and Python with `pip` (for the CLI). +**Prerequisite**: Node.js and npm. ## Step 1: Install the Agent Wallet Run the command below to install a local wallet that manages stablecoins on TRON & BNB Chain. Every paid call your Agent makes from now on is signed locally by this wallet. ```bash -npm i @bankofai/agent-wallet +npm i -g @bankofai/agent-wallet agent-wallet --help ``` @@ -24,7 +24,7 @@ agent-wallet --help One install connects your Agent to the catalog — it discovers and calls every service over x402, paying per call. No accounts, no API keys to manage. ```bash -pip install bankofai-x402-cli +npm install -g @bankofai/x402-cli x402-cli --version ``` @@ -75,7 +75,7 @@ x402-cli pay 'https://x402-gateway.bankofai.io/providers//' \ | `--method` | HTTP method (defaults to `GET`) | | `--network` | CAIP-2 payment chain, e.g. `tron:mainnet`, `eip155:56` | | `--token` | Settlement token, e.g. `USDT` | -| `--scheme` | x402 payment scheme declared by the route, e.g. `exact` or `exact_gasfree` | +| `--scheme` | x402 payment scheme declared by the route, e.g. `exact` | | `--max-amount` | Spend ceiling in USD; the call aborts if the quote exceeds it | | `--header` / `--body` | Request headers and body for the upstream call | diff --git a/docs/x402/api-catalog/reference.md b/docs/x402/api-catalog/reference.md index 6d4cdb56..cfacb7ff 100644 --- a/docs/x402/api-catalog/reference.md +++ b/docs/x402/api-catalog/reference.md @@ -62,7 +62,7 @@ An endpoint may serve the same capability across several chains, each settling t |---|---|---| | `network` | string | CAIP-2 chain ID this route settles on (e.g. `tron:mainnet`, `eip155:56`) | | `provider` | string | The gateway provider `fqn` that handles this network | -| `scheme` | string | x402 payment scheme for this route, e.g. `exact` or `exact_gasfree` — each route declares its own | +| `scheme` | string | x402 payment scheme for this route, e.g. `exact` — each route declares its own | | `url` | string | Full gateway URL for this network's route | The build passes this through to outputs as `x402_routes`. When present, callers/agents pick the route matching their intended payment chain; the top-level `url` remains the default route. diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/get-started.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/get-started.md index b093ce40..ce6da401 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/get-started.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/get-started.md @@ -8,14 +8,14 @@ description: 3 分钟把你的 Agent 接入 API 目录 —— 安装 Agent Walle 只需两步、不到 3 分钟,你的 Agent 就能接入整个目录:装好钱包,再装上 x402 CLI。完成后,Agent 就能发现并调用目录里的任意服务,按次在链上付费。 -**前提**:Node.js(用于钱包)和带 `pip` 的 Python(用于 CLI)。 +**前提**:Node.js 和 npm。 ## 第 1 步:安装 Agent Wallet 运行下面这行命令,你会装上一个在 TRON 与 BNB Chain 上管理稳定币的本地钱包。之后 Agent 发起的每一次付费调用,都由它在本地签名。 ```bash -npm i @bankofai/agent-wallet +npm i -g @bankofai/agent-wallet agent-wallet --help ``` @@ -24,7 +24,7 @@ agent-wallet --help 一次安装,就把 Agent 接入了目录 —— 它通过 x402 发现并调用全部服务、按次付费。无需账号,也无需管理任何 API Key。 ```bash -pip install bankofai-x402-cli +npm install -g @bankofai/x402-cli x402-cli --version ``` @@ -75,7 +75,7 @@ x402-cli pay 'https://x402-gateway.bankofai.io/providers//' \ | `--method` | HTTP 方法(默认 `GET`) | | `--network` | CAIP-2 支付链,如 `tron:mainnet`、`eip155:56` | | `--token` | 结算代币,如 `USDT` | -| `--scheme` | 路由声明的 x402 支付方案,如 `exact` 或 `exact_gasfree` | +| `--scheme` | 路由声明的 x402 支付方案,如 `exact` | | `--max-amount` | 美元支出上限;报价超出即中止调用 | | `--header` / `--body` | 转发到上游的请求头与请求体 | diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/reference.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/reference.md index 1b87ee36..d698c9a6 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/reference.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/reference.md @@ -62,7 +62,7 @@ description: catalog.json / pay.md 的字段定义、合法类目与链 ID,以 |---|---|---| | `network` | string | 该路由结算所在的 CAIP-2 链 ID(如 `tron:mainnet`、`eip155:56`) | | `provider` | string | 处理该网络的 gateway provider `fqn` | -| `scheme` | string | 该路由的 x402 支付方案,如 `exact` 或 `exact_gasfree` —— 由每条路由各自声明 | +| `scheme` | string | 该路由的 x402 支付方案,如 `exact` —— 由每条路由各自声明 | | `url` | string | 该网络路由的完整 gateway URL | 构建时该字段以 `x402_routes` 透传到产物。存在时,调用方/Agent 按目标支付链选择对应路由;顶层 `url` 仍是默认路由。 From a07894f4cd2566f8460385faa604c9cd561780ec Mon Sep 17 00:00:00 2001 From: jizhen181-dot Date: Fri, 10 Jul 2026 18:15:52 +0800 Subject: [PATCH 12/12] add version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index a13d51d4..1a01ae21 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@x402-tron/docs", - "version": "1.3.4", + "version": "1.3.5", "description": "x402-tron documentation", "license": "MIT", "scripts": {