diff --git a/docs/x402/AGENTS.md b/docs/x402/AGENTS.md index f9876e4..a96707c 100644 --- a/docs/x402/AGENTS.md +++ b/docs/x402/AGENTS.md @@ -68,7 +68,7 @@ Documentation must reflect code changes immediately. Follow these dependency map -- **Network Identifier**: Must follow the `tron:` format (supports `mainnet`, `nile`, `shasta`). +- **Network Identifier**: Must follow the `tron:` CAIP-2 format. Use exported constants from `@bankofai/x402-tron` (`TRON_MAINNET`, `TRON_NILE`, `TRON_SHASTA`) instead of hard-coding names. - **Signature Standard**: TRON signatures must reference the **TIP-712** standard (do not confuse with EIP-712). - **Address Format**: Token addresses must use Base58 encoding (must start with `T`). - **Node Access**: Must connect to TronGrid endpoints. diff --git a/docs/x402/api-catalog/get-started.md b/docs/x402/api-catalog/get-started.md index f5ae92e..76c0ca1 100644 --- a/docs/x402/api-catalog/get-started.md +++ b/docs/x402/api-catalog/get-started.md @@ -62,7 +62,7 @@ For a paid POST endpoint, or to pin the payment chain, token, and scheme, pass t ```bash x402-cli pay 'https://x402-gateway.bankofai.io/providers//' \ --method POST \ - --network tron:mainnet \ + --network tron:0x2b6653dc \ --token USDT \ --scheme exact \ --max-amount 0.000001 \ @@ -73,7 +73,7 @@ x402-cli pay 'https://x402-gateway.bankofai.io/providers//' \ | Flag | Purpose | |---|---| | `--method` | HTTP method (defaults to `GET`) | -| `--network` | CAIP-2 payment chain, e.g. `tron:mainnet`, `eip155:56` | +| `--network` | CAIP-2 payment chain, e.g. `tron:0x2b6653dc`, `eip155:56` | | `--token` | Settlement token, e.g. `USDT` | | `--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 | diff --git a/docs/x402/api-catalog/list-your-service.md b/docs/x402/api-catalog/list-your-service.md index 612e7a1..31f593f 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 \\\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:0x2b6653dc \\\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 \\\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:0x2b6653dc \\\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)" } @@ -90,7 +90,7 @@ An example based on the **SunPump** service (copied verbatim from `providers/sun "logo": "https://sunpump.meme/favicon.ico", "category": "finance", "chains": [ - "tron:mainnet", + "tron:0x2b6653dc", "eip155:56" ], "isFirstParty": true, @@ -110,7 +110,7 @@ An example based on the **SunPump** service (copied verbatim from `providers/sun "url": "https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron/pump-api/ai/agentTokenLaunch", "x402Routes": [ { - "network": "tron:mainnet", + "network": "tron:0x2b6653dc", "provider": "sunpump-token-launch-tron", "scheme": "exact", "url": "https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron/pump-api/ai/agentTokenLaunch" @@ -166,7 +166,7 @@ Use it when an agent, backend workflow, or CLI script has already validated the - FQN: `sunpump-token-launch` - Service URL: `https://sunpump.meme` - Category: `finance` -- Chains: `tron:mainnet`, `eip155:56` +- Chains: `tron:0x2b6653dc`, `eip155:56` - TRON Mainnet gateway base: `https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron` - BSC Mainnet gateway base: `https://x402-gateway.bankofai.io/providers/sunpump-token-launch-bsc` @@ -179,7 +179,7 @@ TRON Mainnet: ```bash x402-cli pay 'https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron/pump-api/ai/agentTokenLaunch' \ --method POST \ - --network tron:mainnet \ + --network tron:0x2b6653dc \ --token USDT \ --scheme exact \ --max-amount 0.000001 \ @@ -233,7 +233,7 @@ CI enforces the following rules — go through them before submitting: - `version` must be `1`. - `fqn` is lowercase letters/digits/hyphens and must match the directory name. - `category` must be one of the allowed values (see [reference](./reference.md#allowed-categories)). -- `chains` needs at least one entry, using CAIP-2 style chain IDs — mainnets or testnets (e.g. `tron:mainnet`, `tron:nile`, `eip155:56`, `eip155:97`). +- `chains` needs at least one entry, using CAIP-2 style chain IDs — mainnets or testnets (e.g. `tron:0x2b6653dc`, `tron:0xcd8690dc`, `eip155:56`, `eip155:97`). - `isFirstParty`, `isFeatured` (booleans) and `featuredTags` (string array, may be empty `[]`) are **required** — missing any of them fails validation. - For every endpoint: `method` must be uppercase, `path` must start with `/`, and `maxPriceUsd` must not be less than `minPriceUsd`. - _(Optional)_ An endpoint that settles across multiple chains can add `x402Routes` — one entry per network (`network`, `provider`, `scheme`, `url`). See the [reference](./reference.md#x402routes--multi-network-routing). diff --git a/docs/x402/api-catalog/reference.md b/docs/x402/api-catalog/reference.md index cfacb7f..08ae5dd 100644 --- a/docs/x402/api-catalog/reference.md +++ b/docs/x402/api-catalog/reference.md @@ -60,7 +60,7 @@ An endpoint may serve the same capability across several chains, each settling t | Field | Type | Description | |---|---|---| -| `network` | string | CAIP-2 chain ID this route settles on (e.g. `tron:mainnet`, `eip155:56`) | +| `network` | string | CAIP-2 chain ID this route settles on (e.g. `tron:0x2b6653dc`, `eip155:56`) | | `provider` | string | The gateway provider `fqn` that handles this network | | `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 | @@ -72,7 +72,7 @@ For example, a token-launch endpoint might expose one route per supported chain ```bash x402-cli pay 'https://x402-gateway.bankofai.io/providers//' \ --method POST \ - --network tron:mainnet \ + --network tron:0x2b6653dc \ --token USDT \ --scheme exact \ --max-amount 0.000001 \ @@ -111,9 +111,9 @@ security shopping storage translation | Chain | ID | |---|---| -| TRON mainnet | `tron:mainnet` | -| TRON Nile testnet | `tron:nile` | -| TRON Shasta testnet | `tron:shasta` | +| TRON mainnet | `tron:0x2b6653dc` | +| TRON Nile testnet | `tron:0xcd8690dc` | +| TRON Shasta testnet | `tron:0x94a9059e` | | BNB Chain (BSC) | `eip155:56` | | BNB Smart Chain testnet | `eip155:97` | diff --git a/docs/x402/core-concepts/http-402.md b/docs/x402/core-concepts/http-402.md index 6db2bdb..cc5c2ea 100644 --- a/docs/x402/core-concepts/http-402.md +++ b/docs/x402/core-concepts/http-402.md @@ -55,7 +55,7 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- "accepts": [ { "scheme": "exact", - "network": "tron:nile", + "network": "tron:0xcd8690dc", "amount": "100", "asset": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", "payTo": "", @@ -128,8 +128,8 @@ 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`, `upto`, `batch-settlement`, `auth-capture`, or `exact_gasfree`) | -| `network` | Network identifier (`tron:nile`, `tron:mainnet`, `eip155:56`, `eip155:97`) | +| `scheme` | Payment scheme (`exact`, `upto`, `batch-settlement`, or `exact_gasfree`) | +| `network` | Network identifier (`tron:0xcd8690dc`, `tron:0x2b6653dc`, `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 | @@ -149,7 +149,7 @@ The client responds via the `PAYMENT-SIGNATURE` header with a signed payload: "x402Version": 2, "accepted": { "scheme": "exact", - "network": "tron:nile", + "network": "tron:0xcd8690dc", "asset": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", "amount": "100", "payTo": "", diff --git a/docs/x402/core-concepts/network-and-token-support.md b/docs/x402/core-concepts/network-and-token-support.md index 320dece..298c1da 100644 --- a/docs/x402/core-concepts/network-and-token-support.md +++ b/docs/x402/core-concepts/network-and-token-support.md @@ -5,16 +5,16 @@ import TabItem from '@theme/TabItem'; ## TRON Network Identifiers -x402 adopts a standardized network identifier format: `tron:`. -The `` can be `mainnet`, `shasta`, or `nile`. +x402 adopts the CAIP-2 network identifier format `tron:`. +Use the exported constants from `@bankofai/x402-tron` (`TRON_MAINNET`, `TRON_NILE`, `TRON_SHASTA`) in application code instead of copying opaque hex strings. ### Identifier Reference -| Network Name | Network | Description | -| :----------- | :------------- | :------------------------------ | -| **TRON Mainnet** | `tron:mainnet` | TRON Mainnet (Production) | -| **TRON Shasta** | `tron:shasta` | TRON Shasta Testnet | -| **TRON Nile** | `tron:nile` | TRON Nile Testnet | +| Network Name | CAIP-2 ID | SDK Constant | Description | +| :----------- | :-------- | :----------- | :---------- | +| **TRON Mainnet** | `tron:0x2b6653dc` | `TRON_MAINNET` | TRON Mainnet (Production) | +| **TRON Shasta** | `tron:0x94a9059e` | `TRON_SHASTA` | TRON Shasta Testnet | +| **TRON Nile** | `tron:0xcd8690dc` | `TRON_NILE` | TRON Nile Testnet | --- @@ -57,10 +57,10 @@ By default, **USDT** and **USDD** are used as primary settlement currencies. | Symbol | Network | Contract Address | | :------ | :------------- | :--------------- | -| **USDT** | `tron:mainnet` | `TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t` | -| **USDT** | `tron:nile` | `TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf` | -| **USDD** | `tron:mainnet` | `TXDk8mbtRbXeYuMNS83CfKPaYYT8XWv9Hz` | -| **USDD** | `tron:nile` | `TGjgvdTWWrybVLaVeFqSyVqJQWjxqRYbaK` | +| **USDT** | `tron:0x2b6653dc` | `TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t` | +| **USDT** | `tron:0xcd8690dc` | `TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf` | +| **USDD** | `tron:0x2b6653dc` | `TXDk8mbtRbXeYuMNS83CfKPaYYT8XWv9Hz` | +| **USDD** | `tron:0xcd8690dc` | `TGjgvdTWWrybVLaVeFqSyVqJQWjxqRYbaK` | | **USDT** | `eip155:56` | `0x55d398326f99059fF775485246999027B3197955` | | **USDC** | `eip155:56` | `0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d` | | **EPS** | `eip155:56` | `0xA7f552078dcC247C2684336020c03648500C6d9F` | @@ -95,7 +95,7 @@ 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`) +1. **Network** – The unique network identifier (e.g., `tron:0xcd8690dc`) 2. **Asset** – The TRC-20/BEP-20 token **contract address** 3. **Amount** – The integer value in the token’s **smallest unit (raw amount)** @@ -108,7 +108,7 @@ When configuring an `HTTP 402` payment request on the server side, you must expl ## Payment Schemes -x402 supports five payment schemes. Each is implemented as a client + server + facilitator trio per chain family. +x402 supports four payment schemes. Each is implemented as a client + server + facilitator trio per chain family. ### `exact` Scheme @@ -127,13 +127,9 @@ Usage-based billing. The client signs a Permit2 authorization for up to a **maxi 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. -### `auth-capture` Scheme - -Escrow-style authorization capture (EVM only). Funds are authorized into an escrow contract and released per business logic. - ### `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`. +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:0x2b6653dc` and `tron:0xcd8690dc`. #### GasFree Account Management (via x402-payment skill) @@ -190,10 +186,10 @@ You may deploy your own Facilitator to gain full control over payment verificati | Core Component | TRON/BSC Implementation | | :------------- | :---------------------- | -| **Networks** | `tron:mainnet`, `tron:shasta`, `tron:nile`, `eip155:56`, `eip155:97` | +| **Networks** | `tron:0x2b6653dc`, `tron:0x94a9059e`, `tron:0xcd8690dc`, `eip155:56`, `eip155:97` | | **Token Standard** | TRC-20 (built-in USDT & USDD support), BEP-20 | | **Signing Mechanism** | TIP-712 / EIP-712 typed data signing | -| **Payment Schemes** | `exact`, `upto`, `batch-settlement`, `auth-capture` (EVM), `exact_gasfree` (TRON) | +| **Payment Schemes** | `exact`, `upto`, `batch-settlement`, `exact_gasfree` (TRON) | --- @@ -202,9 +198,9 @@ You may deploy your own Facilitator to gain full control over payment verificati On the **client / facilitator** side, register a custom TRC-20 token via the TRON token registry (`@bankofai/x402-tron`): ```typescript -import { registerToken } from "@bankofai/x402-tron"; +import { registerToken, TRON_NILE } from "@bankofai/x402-tron"; -registerToken("tron:nile", { +registerToken(TRON_NILE, { address: "", decimals: 6, name: "My Token", diff --git a/docs/x402/faq.md b/docs/x402/faq.md index 69d85fd..bf96a6d 100644 --- a/docs/x402/faq.md +++ b/docs/x402/faq.md @@ -68,12 +68,11 @@ Common pricing models include: #### What payment schemes does x402 support? -x402 supports five payment schemes: +x402 supports four 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**. - **`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? @@ -94,11 +93,11 @@ x402 supports five payment schemes: | Network | Token | Status | | --------------------------- | ------------- | ----------- | -| TRON Mainnet (`tron:mainnet`) | USDT (TRC-20) | **Mainnet** | -| TRON Nile (`tron:nile`) | USDT (TRC-20) | **Testnet** | -| TRON Shasta (`tron:shasta`) | USDT (TRC-20) | **Testnet** | -| TRON Mainnet (`tron:mainnet`) | USDD (TRC-20) | **Mainnet** | -| TRON Nile (`tron:nile`) | USDD (TRC-20) | **Testnet** | +| TRON Mainnet (`tron:0x2b6653dc`) | USDT (TRC-20) | **Mainnet** | +| TRON Nile (`tron:0xcd8690dc`) | USDT (TRC-20) | **Testnet** | +| TRON Shasta (`tron:0x94a9059e`) | USDT (TRC-20) | **Testnet** | +| TRON Mainnet (`tron:0x2b6653dc`) | USDD (TRC-20) | **Mainnet** | +| TRON Nile (`tron:0xcd8690dc`) | USDD (TRC-20) | **Testnet** | | BSC Mainnet (`eip155:56`) | USDT (BEP-20) | **Mainnet** | | BSC Mainnet (`eip155:56`) | USDC (BEP-20) | **Mainnet** | | BSC Testnet (`eip155:97`) | USDT (BEP-20) | **Testnet** | diff --git a/docs/x402/getting-started/quickstart-for-human.md b/docs/x402/getting-started/quickstart-for-human.md index 062fed7..b3b2abe 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 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. +x402 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packages. This guide shows how to integrate the published npm packages directly. ::: --- @@ -34,7 +34,7 @@ x402 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packa - [ ] **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) +- [ ] A target x402-protected API URL, such as the `/credit` endpoint from [Quickstart for Sellers](./quickstart-for-sellers.md) ### Create a Test Wallet and Get Test Tokens @@ -94,7 +94,7 @@ x402 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packa Install the published npm packages in your TypeScript application: ```bash -pnpm add @bankofai/x402-fetch @bankofai/x402-tron @bankofai/x402-evm @bankofai/agent-wallet +pnpm add @bankofai/agent-wallet @bankofai/x402-fetch @bankofai/x402-tron ``` Use `npm install` or `yarn add` with the same package names if your project does not use pnpm. @@ -111,165 +111,55 @@ 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. Copy the env template and fill in your key: +**Never put your private key in code.** Set it as an environment variable so it stays out of your source files: ```bash -cp .env-exact.example .env-exact +export AGENT_WALLET_PRIVATE_KEY=your_private_key_here ``` -Open `.env-exact` and set the payer variables: +> 💡 **Tip:** This quickstart pays on `TRON_NILE` (`tron:0xcd8690dc`). The client chooses the payment option where `network === TRON_NILE` from the server's `accepts` list. -```bash -# ── 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 -``` - -> 💡 **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. - - - - -**Optional:** For production TRON workloads, configure a TronGrid API Key for better RPC reliability: +For production TRON workloads, set a TronGrid API Key for better RPC reliability: ```bash -TRON_GRID_API_KEY="your_trongrid_api_key_here" +export TRON_GRID_API_KEY="your_trongrid_api_key_here" ``` -:::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. -::: - - - - -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.** +> ⚠️ **Security reminder:** Keep your private key only in an environment variable or a secure secret manager. **Never commit files containing private keys to Git or share them with anyone.** --- ## Step Three: Write and Run the Client Code -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: +The client wraps `fetch` so HTTP `402 Payment Required` challenges are paid automatically. Here is a minimal TRON client: ```typescript +import { resolveWallet } from "@bankofai/agent-wallet"; import { x402Client, wrapFetchWithPayment } from "@bankofai/x402-fetch"; +import { createClientTronSigner, TRON_NILE } from "@bankofai/x402-tron"; +import { ExactTronScheme } from "@bankofai/x402-tron/exact/client"; -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; +const wallet = await resolveWallet({ + network: TRON_NILE, }); -// 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)); -} -``` - -### How each chain is registered +const signer = await createClientTronSigner(wallet, { + network: TRON_NILE, +}); -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. +const client = new x402Client((_version, accepts) => + accepts.find((a) => a.network === TRON_NILE)! +); - - +client.register(TRON_NILE, new ExactTronScheme(signer)); -```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; -} -``` +const fetchWithPay = wrapFetchWithPayment(fetch, client); - - +const res = await fetchWithPay("http://localhost:4021/credit"); -```typescript -// 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; -} +console.log(await res.json()); ``` - - - ### Run the client 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: @@ -278,19 +168,15 @@ First, make sure a resource server + facilitator are running (see [Quickstart fo 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:** ``` -→ [tron:nile@USDT] GET http://localhost:4021/weather -← 200 OK -{ "report": { "weather": "sunny", "temperature": 70 } } +{ "status": "success", "credit": 1000000 } ``` > ✅ **Success:** The SDK detected the `402`, signed a payment, settled on-chain, and returned the protected content. -> 💡 To pay a BSC token instead, set `PAY_TARGETS=eip155:97@DHLU` (ERC-3009, gasless) or `eip155:97@USDC` (permit2, one-time `approve`). +> 💡 To pay with another network or token, adjust the `accepts.find(...)` selector and register the matching network scheme. --- @@ -298,19 +184,19 @@ If you are comparing against the reference example, run `pnpm dev:client` from ` | 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 | +| `No wallet configured for TRON` | `AGENT_WALLET_PRIVATE_KEY` is not set or empty | Set the environment variable 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 | -| `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` | +| `server offered no payment option matching "…"` | The client-selected network does not match what the server advertises | Check that the server's `accepts` includes `network: TRON_NILE` | | `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` | +| `Connection timeout` | Network or request timeout | Check the API service, facilitator, and TRON RPC connection | | `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: ```typescript try { - const res = await fetchWithPay(RESOURCE_URL); + const res = await fetchWithPay("http://localhost:4021/credit"); if (res.status === 200) { console.log("Success:", await res.json()); } else { @@ -319,7 +205,7 @@ try { } } catch (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"); + console.error("No matching payment option — check TRON_NILE vs the server's accepts"); } else if (error instanceof Error && error.message.includes("allowance")) { console.error("Insufficient token allowance — check wallet balance"); } else { @@ -352,5 +238,5 @@ Through this guide you: ## References - [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 +- [Fetch client example](https://github.com/BofAI/x402/tree/main/examples/typescript/clients/fetch) — if you want a more complete client example, refer to the examples - [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 3cb0bef..91f2922 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** 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. +x402 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packages. This guide shows how to build with the published npm packages. ::: --- @@ -107,160 +107,98 @@ You need a blockchain wallet address to receive tokens from users. Follow the st **Testnet vs. Mainnet:** -- **Testnet**: Uses free test tokens, no real funds involved, suitable for development and debugging. Network identifiers: `tron:nile` / `eip155:97` -- **Mainnet**: Involves real payments, used when going live. Network identifiers: `tron:mainnet` / `eip155:56` +- **Testnet**: Uses free test tokens, no real funds involved, suitable for development and debugging. Network identifiers: `tron:0xcd8690dc` / `eip155:97` +- **Mainnet**: Involves real payments, used when going live. Network identifiers: `tron:0x2b6653dc` / `eip155:56` --- ## Step 1: Install the SDK Packages -Install the server, chain, and wallet packages in your TypeScript API project: +Install the Express adapter and TRON payment scheme in your TypeScript API project: ```bash -pnpm add @bankofai/x402-core @bankofai/x402-express @bankofai/x402-tron @bankofai/x402-evm @bankofai/agent-wallet +pnpm add express @bankofai/x402-core @bankofai/x402-express @bankofai/x402-tron ``` 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. -The repository examples remain useful as working references, but application development should depend on the published packages instead of linking the monorepo source. +If you want a more complete client → server → facilitator example, refer to the repository [examples](https://github.com/BofAI/x402/tree/main/examples/typescript). Application development should still depend on the published packages instead of linking the monorepo source. --- -## Step 2: Configure Your Environment +## Step 2: Prepare Configuration Values -Create a local `.env-exact` file for your API and fill it in: +The minimal server needs only two values: -```bash -touch .env-exact -``` - -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 - -# TronGrid API key — both client and facilitator touch TRON. Optional on testnet. -TRON_GRID_API_KEY= - -# ── 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) - -# Where the server binds, and where it reaches the facilitator. -SERVER_PORT=4021 -FACILITATOR_URL=http://localhost:4022 - -# ── FACILITATOR · settlement ───────────────────────────────────────────── -FACILITATOR_PORT=4022 -``` +| Configuration | Description | Example | +|------|------|------| +| `HTTPFacilitatorClient.url` | Payment verification and settlement service URL | `https://facilitator.example.com` | +| `payTo` | Your TRON receiving address | `T...` | -> 💡 **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. +> 💡 **Keyless server:** The resource server never signs or holds a private key — it only advertises your public receiving address (`payTo`). Signing and settlement happen on the client and facilitator side. -> ⚠️ **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.** +> ⚠️ **Security reminder:** Keep your private key only in a local env file or as an environment variable. **Never commit a file containing a private key to Git or share it with anyone.** --- ## 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`): +Here is a minimal Express resource server. `GET /credit` requires a `1 USDT` payment before it returns the credit payload. ```typescript import express from "express"; -import { HTTPFacilitatorClient } from "@bankofai/x402-core/server"; import { createResourceServer } from "@bankofai/x402-core"; +import { HTTPFacilitatorClient } from "@bankofai/x402-core/server"; 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}`); -}); +import { TRON_NILE } from "@bankofai/x402-tron"; +import { ExactTronScheme } from "@bankofai/x402-tron/exact/server"; + +const server = createResourceServer( + new HTTPFacilitatorClient({ + url: "https://facilitator.example.com", + }) +); + +server.register(TRON_NILE, new ExactTronScheme()); + +express() + .use( + paymentMiddlewareFromHTTPServer( + new x402HTTPResourceServer(server, { + "GET /credit": { + accepts: [ + { + scheme: "exact", + network: TRON_NILE, + payTo: "T...", + price: "1 USDT", + }, + ], + }, + }) + ) + ) + .get("/credit", (_req, res) => + res.json({ + status: "success", + credit: 1000000, + }) + ) + .listen(4021); ``` -### 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:** | Parameter | Description | Example | |------|------|--------| -| `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` | +| `payTo` | Your receiving wallet address | `T...` | +| `accepts[].price` | Price per request | `"1 USDT"` | +| `accepts[].network` | Network to use | Testnet: `TRON_NILE` (`tron:0xcd8690dc`) | | `accepts[].scheme` | Payment scheme | `"exact"` | -| `routes` | Map of `"METHOD /path"` → `{ accepts, extensions, description, mimeType }` | `"GET /weather"` | +| `routes` | Map of `"METHOD /path"` → `{ accepts }` | `"GET /credit"` | **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. @@ -270,7 +208,7 @@ Each chain module builds the `accepts` entries (price + `payTo` + token). The tw ### What is a Facilitator? -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. +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 through `HTTPFacilitatorClient` — it does not settle on its own. **You must have a Facilitator reachable before starting your API server.** @@ -290,10 +228,14 @@ The officially hosted Facilitator service requires **no infrastructure to mainta #### 4.1 Configure the Service Endpoint -Set `FACILITATOR_URL` in your `.env-exact` to the official endpoint: +Set the `url` in `HTTPFacilitatorClient` to the official endpoint: -``` -FACILITATOR_URL=https://facilitator.bankofai.io +```typescript +const server = createResourceServer( + new HTTPFacilitatorClient({ + 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. @@ -310,10 +252,9 @@ With an API Key, the rate limit increases to **1,000 requests/minute**, sufficie #### 4.3 Wire the API Key into Your Server -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`: +The official key is sent as the `X-API-KEY` header on every facilitator call. Keep it in an environment variable or secret manager, and pass it with facilitator requests in production. ```bash -# Append to .env-exact FACILITATOR_API_KEY=paste_your_api_key_here ``` @@ -371,7 +312,7 @@ pnpm dev:facilitator ``` [evm] facilitator registered eip155:97 (0x…) -[tron] facilitator registered tron:nile (T…) +[tron] facilitator registered tron:0xcd8690dc (T…) 🚀 Facilitator on http://localhost:4022 (evm=true, tron=true) ``` @@ -386,26 +327,20 @@ pnpm dev:facilitator ### 5.1 Start the API Server -Open a **new terminal window** (do not close the facilitator), and from `examples/typescript` run: +Open a **new terminal window** (do not close the facilitator), and run your server entry point from your API project: ```bash -pnpm dev:server +pnpm tsx src/server.ts ``` -**After a successful start, you should see:** - -``` -🌤️ Resource server on http://localhost:4021 (evm=true, tron=true) → facilitator http://localhost:4022 -``` - -> ✅ **Success:** Terminal shows the resource server on `http://localhost:4021` +> ✅ **Success:** The process keeps running and the resource server listens on `http://localhost:4021` ### 5.2 Test Unpaid Access (Should Be Rejected) In any terminal, run: ```bash -curl http://localhost:4021/weather +curl http://localhost:4021/credit ``` **Expected result:** The server returns an HTTP `402` response with the payment requirements (an `accepts` array listing scheme, network, price, and your payout address). @@ -414,43 +349,22 @@ curl http://localhost:4021/weather ### 5.3 Test the Full Payment Flow -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: +To test the complete pay → receive content flow, use the minimal client in [Quickstart for Human Users](./quickstart-for-human.md). Point it at `http://localhost:4021/credit`; the expected response is: -```bash -# 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 +```json +{ "status": "success", "credit": 1000000 } ``` -Then run: - -```bash -pnpm dev:client -``` - -**Expected output:** - -``` -→ [tron:nile@USDT] GET http://localhost:4021/weather -← 200 OK -{ "report": { "weather": "sunny", "temperature": 70 } } -``` - -> ✅ **Success:** The client automatically detected the `402`, signed a payment, settled on-chain via the facilitator, and received the protected content. - -> 💡 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 | 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` | +| `Failed to fetch` / connection refused | Facilitator or server not running | Start the facilitator first, then run your API server entry point | +| Client `server offered no payment option matching "…"` | The client selected a network or token that the server does not advertise | Check the server's `accepts` (network + token), e.g. `TRON_NILE` + `USDT` | | `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 | +| `UnsupportedNetworkError` / `No mechanism registered` | The selected client network has no registered scheme | Ensure the client includes your target network, such as `TRON_NILE` | | `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`) | @@ -462,15 +376,17 @@ After fully validating on the testnet, only a few steps are needed to go live an ### 1. Point the Client and Server at Mainnet -The example registers testnet **and** mainnet in the same tables — no uncommenting needed. Switch by setting mainnet values in `.env-exact`: +Switch the server registration and receiving address to mainnet: -```bash -# Server payout addresses → your mainnet wallets -EVM_ADDRESS=0xYourMainnetBscAddress -TRON_ADDRESS=TYourMainnetTronAddress +```typescript +import { TRON_MAINNET } from "@bankofai/x402-tron"; + +server.register(TRON_MAINNET, new ExactTronScheme()); -# Client pays on mainnet -PAY_TARGETS=tron:mainnet@USDT # or eip155:56@USDT +// In accepts, update: +network: TRON_MAINNET, +payTo: "TYourMainnetTronAddress", +price: "1 USDT", ``` ### 2. Set a Reliable EVM RPC @@ -483,7 +399,7 @@ EVM_RPC_URL=https://bsc-rpc.publicnode.com ### 3. (Self-Hosted) Switch the Facilitator to Mainnet -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: +The facilitator's `TRON_NETWORKS` already includes `TRON_MAINNET` (`tron:0x2b6653dc`), and `EVM_NETWORKS` includes `eip155:56`. Fund the Facilitator wallet with real TRX/BNB to cover settlement gas, then restart: ```bash pnpm dev:facilitator @@ -493,7 +409,7 @@ pnpm dev:facilitator ### 4. (Official Facilitator) No Local Change Needed -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. +If you use the official facilitator, keep `HTTPFacilitatorClient`'s `url` as `https://facilitator.bankofai.io` and continue using your `FACILITATOR_API_KEY`. Only your server's payout addresses move to mainnet. ### 5. Confirm and Do a Small Real Test @@ -509,7 +425,7 @@ If you use the official facilitator, keep `FACILITATOR_URL=https://facilitator.b ## Next Steps -- 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 +- If you want a more complete example, refer to the repository [examples](https://github.com/BofAI/x402/tree/main/examples/typescript), which include the 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 @@ -523,8 +439,8 @@ 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** | Cloned the SDK repo and installed the example workspace | -| **Step 2** | Configured `.env-exact` with your wallet and payout addresses | +| **Step 1** | Installed the x402 SDK packages | +| **Step 2** | Prepared the facilitator URL and receiving address | | **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 | diff --git a/docs/x402/index.md b/docs/x402/index.md index f224eb9..ee1bafb 100644 --- a/docs/x402/index.md +++ b/docs/x402/index.md @@ -75,13 +75,13 @@ Our goal is to build a low-barrier, permissionless, developer-friendly programma x402 currently supports the following networks: -- **TRON Mainnet** (`tron:mainnet`) -- **TRON Shasta Testnet** (`tron:shasta`) -- **TRON Nile Testnet** (`tron:nile`) +- **TRON Mainnet** (`tron:0x2b6653dc`) +- **TRON Shasta Testnet** (`tron:0x94a9059e`) +- **TRON Nile Testnet** (`tron:0xcd8690dc`) - **BSC Mainnet** (`eip155:56`) - **BSC Testnet** (`eip155:97`) -> **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. +> **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`, 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 677130f..ce300cc 100644 --- a/docs/x402/sdk-features.md +++ b/docs/x402/sdk-features.md @@ -16,7 +16,7 @@ This page tracks the feature support of the x402 SDK. | 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-evm` | EVM mechanism: `exact`, `upto`, `batch-settlement` | | `@bankofai/x402-tron` | TRON mechanism: `exact`, `upto`, `batch-settlement`, `exact_gasfree` | | `@bankofai/x402-fetch` | Wrapped-`fetch` client (`wrapFetchWithPayment`) | | `@bankofai/x402-express` | Express server middleware | @@ -48,13 +48,13 @@ This page tracks the feature support of the x402 SDK. ## Networks -| Network | Status | -|-----------|--------| -| `tron:mainnet` | ✅ | -| `tron:nile` | ✅ | -| `tron:shasta` | ✅ | -| `eip155:56` (BSC Mainnet) | ✅ | -| `eip155:97` (BSC Testnet) | ✅ | +| Network | SDK Constant | Status | +|-----------|--------------|--------| +| `tron:0x2b6653dc` | `TRON_MAINNET` | ✅ | +| `tron:0xcd8690dc` | `TRON_NILE` | ✅ | +| `tron:0x94a9059e` | `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. @@ -62,14 +62,13 @@ This page tracks the feature support of the x402 SDK. ## Payment Schemes -x402 supports five payment schemes. Each is implemented as a client + server + facilitator trio per chain family. +x402 supports four payment schemes. Each is implemented as a client + server + facilitator trio per chain family. | 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. | > **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. @@ -137,8 +136,8 @@ Key custody is in [`@bankofai/agent-wallet`](https://github.com/BofAI/agent-wall | Token | Network | Status | |--------|---------|--------| -| USDT (TRC-20) | `tron:mainnet`, `tron:nile` | ✅ | -| USDD (TRC-20) | `tron:mainnet`, `tron:nile` | ✅ | +| USDT (TRC-20) | `tron:0x2b6653dc`, `tron:0xcd8690dc` | ✅ | +| USDD (TRC-20) | `tron:0x2b6653dc`, `tron:0xcd8690dc` | ✅ | | USDT (BEP-20) | `eip155:56`, `eip155:97` | ✅ | | USDC (BEP-20) | `eip155:56`, `eip155:97` | ✅ | | DHLU (BSC testnet, ERC-3009) | `eip155:97` | ✅ | 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 3c4ba61..4c54c81 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 @@ -58,7 +58,7 @@ import TabItem from '@theme/TabItem'; -- **网络标识**:必须遵循 `tron:` 格式(支持 `mainnet`, `nile`, `shasta`)。 +- **网络标识**:必须遵循 `tron:` CAIP-2 格式。优先使用 `@bankofai/x402-tron` 导出的常量(`TRON_MAINNET`、`TRON_NILE`、`TRON_SHASTA`),不要硬编码旧的名称。 - **签名标准**:TRON 签名必须引用 **TIP-712** 标准(请勿混淆为 EIP-712)。 - **地址格式**:Token 地址必须使用 Base58 编码格式(即以 `T` 开头的地址)。 - **节点接入**:节点访问需指向 TronGrid 端点。 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 ce6da40..1ea76cf 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 @@ -62,7 +62,7 @@ x402-cli pay 'https://x402-gateway.bankofai.io/providers//...' ```bash x402-cli pay 'https://x402-gateway.bankofai.io/providers//' \ --method POST \ - --network tron:mainnet \ + --network tron:0x2b6653dc \ --token USDT \ --scheme exact \ --max-amount 0.000001 \ @@ -73,7 +73,7 @@ x402-cli pay 'https://x402-gateway.bankofai.io/providers//' \ | 参数 | 作用 | |---|---| | `--method` | HTTP 方法(默认 `GET`) | -| `--network` | CAIP-2 支付链,如 `tron:mainnet`、`eip155:56` | +| `--network` | CAIP-2 支付链,如 `tron:0x2b6653dc`、`eip155:56` | | `--token` | 结算代币,如 `USDT` | | `--scheme` | 路由声明的 x402 支付方案,如 `exact` | | `--max-amount` | 美元支出上限;报价超出即中止调用 | 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 7a22663..c471e2c 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 \\\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:0x2b6653dc \\\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 \\\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:0x2b6653dc \\\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)" } @@ -90,7 +90,7 @@ x402-cli catalog export-gateway https://gateway.example.com \ "logo": "https://sunpump.meme/favicon.ico", "category": "finance", "chains": [ - "tron:mainnet", + "tron:0x2b6653dc", "eip155:56" ], "isFirstParty": true, @@ -110,7 +110,7 @@ x402-cli catalog export-gateway https://gateway.example.com \ "url": "https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron/pump-api/ai/agentTokenLaunch", "x402Routes": [ { - "network": "tron:mainnet", + "network": "tron:0x2b6653dc", "provider": "sunpump-token-launch-tron", "scheme": "exact", "url": "https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron/pump-api/ai/agentTokenLaunch" @@ -166,7 +166,7 @@ Use it when an agent, backend workflow, or CLI script has already validated the - FQN: `sunpump-token-launch` - Service URL: `https://sunpump.meme` - Category: `finance` -- Chains: `tron:mainnet`, `eip155:56` +- Chains: `tron:0x2b6653dc`, `eip155:56` - TRON Mainnet gateway base: `https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron` - BSC Mainnet gateway base: `https://x402-gateway.bankofai.io/providers/sunpump-token-launch-bsc` @@ -179,7 +179,7 @@ TRON Mainnet: ```bash x402-cli pay 'https://x402-gateway.bankofai.io/providers/sunpump-token-launch-tron/pump-api/ai/agentTokenLaunch' \ --method POST \ - --network tron:mainnet \ + --network tron:0x2b6653dc \ --token USDT \ --scheme exact \ --max-amount 0.000001 \ @@ -233,7 +233,7 @@ CI 会强制以下规则,建议提交前逐条对照: - `version` 必须为 `1`。 - `fqn` 为小写字母/数字/连字符,且与目录名一致。 - `category` 必须是合法类目之一(见[参考](./reference.md#合法类目))。 -- `chains` 至少一条,使用 CAIP-2 风格的链 ID —— 主网或测试网均可(如 `tron:mainnet`、`tron:nile`、`eip155:56`、`eip155:97`)。 +- `chains` 至少一条,使用 CAIP-2 风格的链 ID —— 主网或测试网均可(如 `tron:0x2b6653dc`、`tron:0xcd8690dc`、`eip155:56`、`eip155:97`)。 - `isFirstParty`、`isFeatured`(布尔值)与 `featuredTags`(字符串数组,可为空 `[]`)为**必填**,缺一即校验失败。 - 每个 endpoint 的 `method` 必须大写、`path` 以 `/` 开头、`maxPriceUsd` 不小于 `minPriceUsd`。 - _(选填)_ 跨多条链结算的端点可加 `x402Routes`,每个网络一条(`network`、`provider`、`scheme`、`url`)。详见[参考](./reference.md#x402routes--多网络路由)。 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 d698c9a..799ee44 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 @@ -60,7 +60,7 @@ description: catalog.json / pay.md 的字段定义、合法类目与链 ID,以 | 字段 | 类型 | 说明 | |---|---|---| -| `network` | string | 该路由结算所在的 CAIP-2 链 ID(如 `tron:mainnet`、`eip155:56`) | +| `network` | string | 该路由结算所在的 CAIP-2 链 ID(如 `tron:0x2b6653dc`、`eip155:56`) | | `provider` | string | 处理该网络的 gateway provider `fqn` | | `scheme` | string | 该路由的 x402 支付方案,如 `exact` —— 由每条路由各自声明 | | `url` | string | 该网络路由的完整 gateway URL | @@ -72,7 +72,7 @@ description: catalog.json / pay.md 的字段定义、合法类目与链 ID,以 ```bash x402-cli pay 'https://x402-gateway.bankofai.io/providers//' \ --method POST \ - --network tron:mainnet \ + --network tron:0x2b6653dc \ --token USDT \ --scheme exact \ --max-amount 0.000001 \ @@ -111,9 +111,9 @@ security shopping storage translation | 链 | ID | |---|---| -| TRON 主网 | `tron:mainnet` | -| TRON Nile 测试网 | `tron:nile` | -| TRON Shasta 测试网 | `tron:shasta` | +| TRON 主网 | `tron:0x2b6653dc` | +| TRON Nile 测试网 | `tron:0xcd8690dc` | +| TRON Shasta 测试网 | `tron:0x94a9059e` | | BNB Chain (BSC) | `eip155:56` | | BNB 测试网 | `eip155:97` | 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 60c6eed..2153db6 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 @@ -55,7 +55,7 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: "accepts": [ { "scheme": "exact", - "network": "tron:nile", + "network": "tron:0xcd8690dc", "amount": "100", "asset": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", "payTo": "", @@ -127,8 +127,8 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: | `error` | 人类可读的错误提示 | | `resource` | 关于请求资源的信息 | | `accepts` | 接受的支付选项数组 | -| `scheme` | 支付方案(`exact`、`upto`、`batch-settlement`、`auth-capture`、`exact_gasfree`) | -| `network` | 网络标识符(`tron:nile`, `tron:mainnet`, `eip155:56`, `eip155:97`) | +| `scheme` | 支付方案(`exact`、`upto`、`batch-settlement`、`exact_gasfree`) | +| `network` | 网络标识符(`tron:0xcd8690dc`, `tron:0x2b6653dc`, `eip155:56`, `eip155:97`) | | `amount` | 支付金额,以最小单位计(例如:100 = 0.0001 USDT) | | `asset` | TRC-20/BEP-20 代币合约地址 | | `payTo` | 卖家的钱包地址 | @@ -148,7 +148,7 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: "x402Version": 2, "accepted": { "scheme": "exact", - "network": "tron:nile", + "network": "tron:0xcd8690dc", "asset": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", "amount": "100", "payTo": "", 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 89a7ce7..e3a8d6b 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 @@ -5,16 +5,16 @@ import TabItem from '@theme/TabItem'; ## TRON 网络标识符 -x402 采用标准化的网络标识符格式:`tron:`。 -其中 `` 对应为 `mainnet`、`shasta` 或 `nile`。 +x402 采用 CAIP-2 网络标识符格式:`tron:`。 +应用代码中优先使用 `@bankofai/x402-tron` 导出的常量(`TRON_MAINNET`、`TRON_NILE`、`TRON_SHASTA`),不要手动复制不透明的 hex 字符串。 ### 标识符参考表 -| 网络名称 (Network Name) | 网络 (Network) | 描述 (Description) | -| :---------------------- | :------------- | :------------------- | -| **TRON Mainnet** | `tron:mainnet` | TRON 主网 (生产环境) | -| **TRON Shasta** | `tron:shasta` | TRON Shasta 测试网 | -| **TRON Nile** | `tron:nile` | TRON Nile 测试网 | +| 网络名称 (Network Name) | CAIP-2 ID | SDK 常量 | 描述 (Description) | +| :---------------------- | :-------- | :------- | :----------------- | +| **TRON Mainnet** | `tron:0x2b6653dc` | `TRON_MAINNET` | TRON 主网 (生产环境) | +| **TRON Shasta** | `tron:0x94a9059e` | `TRON_SHASTA` | TRON Shasta 测试网 | +| **TRON Nile** | `tron:0xcd8690dc` | `TRON_NILE` | TRON Nile 测试网 | ## BSC 网络标识符 @@ -51,10 +51,10 @@ x402 协议全面支持 **TRC-20/BEP-20** 标准代币,并默认将 **USDT** | 代币符号 | 网络环境 | 合约地址 (Contract Address) | | :------- | :------------- | :----------------------------------- | -| **USDT** | `tron:mainnet` | `TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t` | -| **USDT** | `tron:nile` | `TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf` | -| **USDD** | `tron:mainnet` | `TXDk8mbtRbXeYuMNS83CfKPaYYT8XWv9Hz` | -| **USDD** | `tron:nile` | `TGjgvdTWWrybVLaVeFqSyVqJQWjxqRYbaK` | +| **USDT** | `tron:0x2b6653dc` | `TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t` | +| **USDT** | `tron:0xcd8690dc` | `TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf` | +| **USDD** | `tron:0x2b6653dc` | `TXDk8mbtRbXeYuMNS83CfKPaYYT8XWv9Hz` | +| **USDD** | `tron:0xcd8690dc` | `TGjgvdTWWrybVLaVeFqSyVqJQWjxqRYbaK` | | **USDT** | `eip155:56` | `0x55d398326f99059fF775485246999027B3197955` | | **USDC** | `eip155:56` | `0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d` | | **EPS** | `eip155:56` | `0xA7f552078dcC247C2684336020c03648500C6d9F` | @@ -80,7 +80,7 @@ x402 采用类型化数据签名来处理所有支付相关的签名授权。 在服务端配置 `HTTP 402` 支付要求时,您需要明确指定以下三个核心参数: -1. **网络 (Network)**:目标网络的唯一标识符(例如 `tron:nile`)。 +1. **网络 (Network)**:目标网络的唯一标识符(例如 `tron:0xcd8690dc`)。 2. **资产 (Asset)**:目标 TRC-20/BEP-20 代币的**合约地址**。 3. **金额 (Amount)**:基于代币**最小单位**(Raw Amount)的整数值。 @@ -90,7 +90,7 @@ x402 采用类型化数据签名来处理所有支付相关的签名授权。 ### 支付方案 -x402 支持五种支付方案。每种方案按链族实现为 client + server + facilitator 三件套。 +x402 支持四种支付方案。每种方案按链族实现为 client + server + facilitator 三件套。 #### `exact` 方案 @@ -109,13 +109,9 @@ x402 支持五种支付方案。每种方案按链族实现为 client + server + 面向高频微支付(如 AI 代理每 token 计费)的支付通道方案。客户端链上**一次性存入**,然后用链下**凭证**支付多次请求;facilitator **批量 claim** 并在一笔交易中结算到 `payTo`——因此 N 次请求约仅花费一次存入的 gas。含**退款**路径,可退回通道中未使用的余额。EVM 和 TRON 均支持。 -#### `auth-capture` 方案 - -托管式授权捕获(仅 EVM)。资金被授权进入托管合约,并按业务逻辑释放。 - #### `exact_gasfree` 方案 -TRON 专属。允许用户使用 USDT/USDD 付款而**无需持有 TRX 来支付 gas 费用**。客户端签署 TIP-712 GasFree 许可,由 relayer 通过官方 GasFree 代理支付链上 energy——付款方无需 TRX,也无需一次性 `approve`。资金来自付款方的 GasFree 托管钱包(非主钱包)。支持 `tron:mainnet` 和 `tron:nile`。 +TRON 专属。允许用户使用 USDT/USDD 付款而**无需持有 TRX 来支付 gas 费用**。客户端签署 TIP-712 GasFree 许可,由 relayer 通过官方 GasFree 代理支付链上 energy——付款方无需 TRX,也无需一次性 `approve`。资金来自付款方的 GasFree 托管钱包(非主钱包)。支持 `tron:0x2b6653dc` 和 `tron:0xcd8690dc`。 ##### GasFree 账户管理(通过 x402-payment skill) @@ -163,19 +159,19 @@ Facilitator 作为协议的中间件,承担以下核心职责: | 核心组件 | TRON/BSC 实现详情 | | :----------- | :----------------------------------------- | -| **网络环境** | `tron:mainnet`, `tron:shasta`, `tron:nile`, `eip155:56`, `eip155:97` | +| **网络环境** | `tron:0x2b6653dc`, `tron:0x94a9059e`, `tron:0xcd8690dc`, `eip155:56`, `eip155:97` | | **代币标准** | TRC-20 代币(默认内置 USDT 和 USDD 支持),BEP-20 代币 | | **签名机制** | TIP-712 / EIP-712 类型化数据签名 | -| **支付方案** | `exact`、`upto`、`batch-settlement`、`auth-capture`(EVM)、`exact_gasfree`(TRON) | +| **支付方案** | `exact`、`upto`、`batch-settlement`、`exact_gasfree`(TRON) | ### 添加自定义代币 在**客户端 / facilitator** 侧,通过 TRON 代币注册表(`@bankofai/x402-tron`)注册自定义 TRC-20 代币: ```typescript -import { registerToken } from "@bankofai/x402-tron"; +import { registerToken, TRON_NILE } from "@bankofai/x402-tron"; -registerToken("tron:nile", { +registerToken(TRON_NILE, { address: "", decimals: 6, name: "My Token", 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 17f0883..a57284b 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 @@ -60,12 +60,11 @@ x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发 #### x402 支持哪些支付方案? -x402 支持五种支付方案: +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 消耗**等场景。 - **`batch-settlement`**:面向高频微支付的支付通道——一次性链上存入,然后用链下凭证支付多次请求,一笔交易批量结算。含退款路径。 -- **`auth-capture`**(仅 EVM):托管式授权捕获。 - **`exact_gasfree`**(仅限 TRON):允许买家使用 USDT/USDD 付款而无需持有 TRX 来支付 gas。由 relayer 通过 GasFree API 支付链上 energy——客户端无需配置 API 密钥。 #### 本 SDK 是否可以与 x402 Foundation(原 Coinbase)的 v2 参考实现互通? @@ -84,11 +83,11 @@ x402 支持五种支付方案: | 网络 | 代币 | 状态 | | ----------------------------- | ------------- | ----------- | -| TRON 主网 (`tron:mainnet`) | USDT (TRC-20) | **Mainnet** | -| TRON Nile (`tron:nile`) | USDT (TRC-20) | **Testnet** | -| TRON Shasta (`tron:shasta`) | USDT (TRC-20) | **Testnet** | -| TRON Mainnet (`tron:mainnet`) | USDD (TRC-20) | **Mainnet** | -| TRON Nile (`tron:nile`) | USDD (TRC-20) | **Testnet** | +| TRON 主网 (`tron:0x2b6653dc`) | USDT (TRC-20) | **Mainnet** | +| TRON Nile (`tron:0xcd8690dc`) | USDT (TRC-20) | **Testnet** | +| TRON Shasta (`tron:0x94a9059e`) | USDT (TRC-20) | **Testnet** | +| TRON Mainnet (`tron:0x2b6653dc`) | USDD (TRC-20) | **Mainnet** | +| TRON Nile (`tron:0xcd8690dc`) | USDD (TRC-20) | **Testnet** | | BSC 主网 (`eip155:56`) | USDT (BEP-20) | **Mainnet** | | BSC 主网 (`eip155:56`) | USDC (BEP-20) | **Mainnet** | | BSC 主网 (`eip155:56`) | EPS (BEP-20) | **Mainnet** | 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 d9ced38..c8ebe57 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-*` 包发布。本指南展示如何直接集成已发布的 npm 包;[`examples/typescript/clients/fetch`](https://github.com/BofAI/x402/tree/main/examples/typescript/clients/fetch) 是可运行参考实现,不是必须采用的开发路径。 +x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发布。本指南展示如何直接集成已发布的 npm 包。 ::: --- @@ -34,7 +34,7 @@ x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发 - [ ] 已安装 **Node.js 22+** 和 **pnpm 11.1+** - [ ] 已创建专用**测试钱包**(见下文) - [ ] 已领取测试代币(免费) -- [ ] 有一个目标 x402 保护的 API URL(或运行示例 server) +- [ ] 有一个目标 x402 保护的 API URL(例如按[卖家快速入门](./quickstart-for-sellers.md)启动的 `/credit` 接口) ### 创建测试钱包并领取测试代币 @@ -94,7 +94,7 @@ x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发 在您的 TypeScript 应用中安装已发布的 npm 包: ```bash -pnpm add @bankofai/x402-fetch @bankofai/x402-tron @bankofai/x402-evm @bankofai/agent-wallet +pnpm add @bankofai/agent-wallet @bankofai/x402-fetch @bankofai/x402-tron ``` 如果您的项目不使用 pnpm,也可以用 `npm install` 或 `yarn add` 安装同名包。 @@ -111,165 +111,55 @@ x402 使用 [Agent Wallet](../../Agent-Wallet/QuickStart.md) 解析和管理钱 ## 第二步:配置私钥 -**切勿将私钥写在代码中。** 将其存为环境变量以使其远离源文件。复制环境模板并填入您的密钥: +**切勿将私钥写在代码中。** 将其设为环境变量以使其远离源文件: ```bash -cp .env-exact.example .env-exact +export AGENT_WALLET_PRIVATE_KEY=your_private_key_here ``` -打开 `.env-exact` 并设置付款方变量: +> 💡 **提示:** 本快速入门使用 `TRON_NILE`(`tron:0xcd8690dc`)付款。client 会从 server 返回的 `accepts` 中选择 `network === TRON_NILE` 的付款选项。 -```bash -# ── 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 -TRON_GRID_API_KEY="your_trongrid_api_key_here" +export TRON_GRID_API_KEY="your_trongrid_api_key_here" ``` -:::note -未设置 `TRON_GRID_API_KEY` 时,高负载下请求可能被速率限制。生产环境请设置自己的 `TRON_GRID_API_KEY` 以确保可靠性。 -::: - - - - -BSC 测试网默认的 viem RPC 端点经常不可达。请设置可靠的 RPC: - -```bash -EVM_RPC_URL=https://bsc-testnet-rpc.publicnode.com -``` - - - - -> ⚠️ **安全提醒:** 私钥仅保存在 `.env-exact`(已被 gitignore)或环境变量中。**切勿将含私钥的文件提交到 Git 或分享给任何人。** +> ⚠️ **安全提醒:** 私钥仅保存在环境变量或安全的密钥管理系统中。**切勿将含私钥的文件提交到 Git 或分享给任何人。** --- ## 第三步:编写并运行客户端代码 -客户端会包装 `fetch`,使 HTTP `402 Payment Required` 挑战自动支付。可运行示例 `examples/typescript/clients/fetch/src/index.ts` 采用相同结构;要点如下: +客户端会包装 `fetch`,使 HTTP `402 Payment Required` 挑战自动支付。下面是一个最小 TRON client: ```typescript +import { resolveWallet } from "@bankofai/agent-wallet"; import { x402Client, wrapFetchWithPayment } from "@bankofai/x402-fetch"; +import { createClientTronSigner, TRON_NILE } from "@bankofai/x402-tron"; +import { ExactTronScheme } from "@bankofai/x402-tron/exact/client"; -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; +const wallet = await resolveWallet({ + network: TRON_NILE, }); -// 仅当钱包解析成功时才注册该链(可仅 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)); -} -``` - -### 各链如何注册 +const signer = await createClientTronSigner(wallet, { + network: TRON_NILE, +}); -每条链位于 `src/chains/` 下各自的模块中。仅当该链的 agent-wallet 解析成功时才注册——因此您可以仅从 EVM、仅从 TRON,或两者支付。 +const client = new x402Client((_version, accepts) => + accepts.find((a) => a.network === TRON_NILE)! +); - - +client.register(TRON_NILE, new ExactTronScheme(signer)); -```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; -} -``` +const fetchWithPay = wrapFetchWithPayment(fetch, client); - - +const res = await fetchWithPay("http://localhost:4021/credit"); -```typescript -// 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; -} +console.log(await res.json()); ``` - - - ### 运行 client 首先确保资源服务器 + facilitator 正在运行(参见[卖家快速入门](./quickstart-for-sellers.md)),然后用同一组环境变量运行您的客户端应用: @@ -278,19 +168,15 @@ export async function registerEvm(client: x402Client): Promise { pnpm tsx src/index.ts # 或您的应用 dev 脚本 ``` -如果您是在对照参考示例,请在 `examples/typescript` 下运行 `pnpm dev:client`。 - **预期输出:** ``` -→ [tron:nile@USDT] GET http://localhost:4021/weather -← 200 OK -{ "report": { "weather": "sunny", "temperature": 70 } } +{ "status": "success", "credit": 1000000 } ``` > ✅ **成功:** SDK 检测到 `402`,签署付款,在链上结算,并返回了受保护的内容。 -> 💡 要改为支付 BSC 代币,设置 `PAY_TARGETS=eip155:97@DHLU`(ERC-3009,无 gas)或 `eip155:97@USDC`(permit2,一次性 `approve`)。 +> 💡 要改为支付其他网络或代币,请调整 selector 中的 `accepts.find(...)` 条件,并注册对应网络的 scheme。 --- @@ -298,19 +184,19 @@ pnpm tsx src/index.ts # 或您的应用 dev 脚本 | 问题 | 原因 | 解决方案 | |---------|-------|----------| -| `No wallet configured for EVM or TRON` | 未设置或为空 `AGENT_WALLET_PRIVATE_KEY` | 在 `.env-exact` 中设置并重新运行;确保在**运行脚本的同一终端窗口**中执行 export | +| `No wallet configured for TRON` | 未设置或为空 `AGENT_WALLET_PRIVATE_KEY` | 设置环境变量并重新运行;确保在**运行脚本的同一终端窗口**中执行 `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` | +| `server offered no payment option matching "…"` | client 选择的网络与 server 公布的不匹配 | 检查 server 的 `accepts` 是否包含 `network: TRON_NILE` | | `InsufficientAllowanceError` / 授权错误 | 代币授权额度过低 | SDK 在首次付款时自动广播一次性 Permit2 `approve`;若仍存在,检查钱包余额 | -| `Connection timeout` | 网络或请求超时 | 检查连接;BSC 请设置可靠的 `EVM_RPC_URL=https://bsc-testnet-rpc.publicnode.com` | +| `Connection timeout` | 网络或请求超时 | 检查 API 服务、facilitator 和 TRON RPC 连接 | | `ERR_PACKAGE_PATH_NOT_EXPORTED` | 项目未声明为 ESM | 在 `package.json` 中添加 `"type": "module"` | 如需更细粒度的错误处理: ```typescript try { - const res = await fetchWithPay(RESOURCE_URL); + const res = await fetchWithPay("http://localhost:4021/credit"); if (res.status === 200) { console.log("Success:", await res.json()); } else { @@ -319,7 +205,7 @@ try { } } catch (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"); + console.error("No matching payment option — check TRON_NILE vs the server's accepts"); } else if (error instanceof Error && error.message.includes("allowance")) { console.error("Insufficient token allowance — check wallet balance"); } else { @@ -352,5 +238,5 @@ try { ## 参考资料 - [x402 npm 包](https://www.npmjs.com/package/@bankofai/x402-tron) —— 应用开发应优先安装的发布包 -- [fetch client 示例](https://github.com/BofAI/x402/tree/main/examples/typescript/clients/fetch) —— client 流程参考实现 +- [fetch client example](https://github.com/BofAI/x402/tree/main/examples/typescript/clients/fetch) —— 如果开发者想要一个更完整的 client 例子,可以参考 examples - [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 418f634..54aa906 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** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发布。本指南展示如何基于已发布的 npm 包开发;[`examples/typescript`](https://github.com/BofAI/x402/tree/main/examples/typescript) 中的可运行项目是参考实现,可用于对照和 smoke test。 +x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发布。本指南展示如何基于已发布的 npm 包开发。 ::: --- @@ -107,160 +107,98 @@ git --version # 版本控制工具 **测试网 vs. 主网:** -- **测试网**:使用免费测试代币,不涉及真实资金,适合开发调试。网络标识:`tron:nile` / `eip155:97` -- **主网**:涉及真实支付,上线时使用。网络标识:`tron:mainnet` / `eip155:56` +- **测试网**:使用免费测试代币,不涉及真实资金,适合开发调试。网络标识:`tron:0xcd8690dc` / `eip155:97` +- **主网**:涉及真实支付,上线时使用。网络标识:`tron:0x2b6653dc` / `eip155:56` --- ## 第一步:安装 SDK 包 -在您的 TypeScript API 项目中安装 server、链和钱包相关包: +在您的 TypeScript API 项目中安装 Express 适配器和 TRON 支付 scheme: ```bash -pnpm add @bankofai/x402-core @bankofai/x402-express @bankofai/x402-tron @bankofai/x402-evm @bankofai/agent-wallet +pnpm add express @bankofai/x402-core @bankofai/x402-express @bankofai/x402-tron ``` 请根据服务框架选择对应包(`@bankofai/x402-express`、`@bankofai/x402-hono`、`@bankofai/x402-fastify` 或 `@bankofai/x402-next`)。如果项目不使用 pnpm,也可以用 `npm install` 或 `yarn add` 安装同名包。 -仓库中的 examples 仍然适合作为可运行参考,但应用开发应依赖已发布的 npm 包,而不是链接 monorepo 源码。 +如果开发者想要一个更完整的 client → server → facilitator 例子,可以参考仓库中的 [examples](https://github.com/BofAI/x402/tree/main/examples/typescript);应用开发仍应依赖已发布的 npm 包,而不是链接 monorepo 源码。 --- -## 第二步:配置环境变量 +## 第二步:准备配置值 -在您的 API 项目中创建本地 `.env-exact` 文件并填写: +最小接入只需要两个值: -```bash -touch .env-exact -``` - -在编辑器中打开 `.env-exact`,设置钱包与收款变量: - -```bash -# ── SHARED · client + facilitator(此处用同一把密钥支付与结算)──────── -AGENT_WALLET_PRIVATE_KEY=0x... # 您的测试钱包私钥 - -# TronGrid API key —— client 和 facilitator 都会访问 TRON。测试网上可选。 -TRON_GRID_API_KEY= - -# ── SERVER · 资源提供方(这是您要配置的)────────────────────────────── -EVM_ADDRESS=0x... # 您的 BSC 收款地址(eip155:97) -TRON_ADDRESS=T... # 您的 TRON 收款地址(tron:nile) - -# server 绑定端口,以及它访问 facilitator 的地址。 -SERVER_PORT=4021 -FACILITATOR_URL=http://localhost:4022 +| 配置 | 说明 | 示例 | +|------|------|------| +| `HTTPFacilitatorClient.url` | 付款验证与结算服务地址 | `https://facilitator.example.com` | +| `payTo` | 您的 TRON 收款地址 | `T...` | -# ── FACILITATOR · 结算 ──────────────────────────────────────────────── -FACILITATOR_PORT=4022 -``` - -> 💡 **无密钥 server:** 资源服务器从不签名、不持有密钥——它只公布您的公开收款地址(`EVM_ADDRESS` / `TRON_ADDRESS`)。签名与结算发生在 client 和 facilitator 侧。`AGENT_WALLET_PRIVATE_KEY` 由 client(用于支付)和 facilitator(用于结算)使用,server 不使用。 +> 💡 **无密钥 server:** 资源服务器从不签名、不持有私钥——它只公布您的公开收款地址(`payTo`)。签名与结算发生在 client 和 facilitator 侧。 -> ⚠️ **安全提醒:** 私钥仅保存在 `.env`(已被 gitignore)或环境变量中。**切勿将含私钥的文件提交到 Git 或分享给任何人。** +> ⚠️ **安全提醒:** 私钥仅保存在本地环境文件或环境变量中。**切勿将含私钥的文件提交到 Git 或分享给任何人。** --- ## 第三步:创建付费 API 服务器 -示例资源服务器是一个 Express 应用,将 `GET /weather` 保护在 x402 付款之后。它是**链无关**的——每条链的代币与 `accepts` 条目位于 `src/chains/{evm,tron}.ts`,仅当设置了 `*_ADDRESS` 时才公布该链。 - -以下是服务器入口(`examples/typescript/servers/express/src/index.ts`): +下面是一个最小 Express 资源服务器:`GET /credit` 需要先支付 `1 USDT`,付款成功后返回信用额度数据。 ```typescript import express from "express"; -import { HTTPFacilitatorClient } from "@bankofai/x402-core/server"; import { createResourceServer } from "@bankofai/x402-core"; +import { HTTPFacilitatorClient } from "@bankofai/x402-core/server"; 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}`); -}); +import { TRON_NILE } from "@bankofai/x402-tron"; +import { ExactTronScheme } from "@bankofai/x402-tron/exact/server"; + +const server = createResourceServer( + new HTTPFacilitatorClient({ + url: "https://facilitator.example.com", + }) +); + +server.register(TRON_NILE, new ExactTronScheme()); + +express() + .use( + paymentMiddlewareFromHTTPServer( + new x402HTTPResourceServer(server, { + "GET /credit": { + accepts: [ + { + scheme: "exact", + network: TRON_NILE, + payTo: "T...", + price: "1 USDT", + }, + ], + }, + }) + ) + ) + .get("/credit", (_req, res) => + res.json({ + status: "success", + credit: 1000000, + }) + ) + .listen(4021); ``` -### 各链定价方式 - -每个链模块构建 `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 - ], - }; - ``` - **关键配置参数:** | 参数 | 说明 | 示例 | |------|------|--------| -| `EVM_ADDRESS` / `TRON_ADDRESS` | 您的收款(payout)钱包地址 | `0xAbc…` / `TXyz…` | -| `accepts[].price` | 每次请求价格(代币金额,或 `"<金额> <符号>"`) | `"0.001 USDT"` | -| `accepts[].network` | 使用的网络 | 测试网:`tron:nile` / `eip155:97` | +| `payTo` | 您的收款钱包地址 | `T...` | +| `accepts[].price` | 每次请求价格 | `"1 USDT"` | +| `accepts[].network` | 使用的网络 | 测试网:`TRON_NILE`(`tron:0xcd8690dc`) | | `accepts[].scheme` | 付款方式 | `"exact"` | -| `routes` | `"METHOD /path"` → `{ accepts, extensions, description, mimeType }` 的映射 | `"GET /weather"` | +| `routes` | `"METHOD /path"` → `{ accepts }` 的映射 | `"GET /credit"` | **工作原理:** 当未付款请求到达您的 API 时,中间件自动返回 HTTP `402 Payment Required` 响应并携带付款要求。client SDK 自动完成付款并重发请求——对终端用户几乎不可见。 @@ -270,7 +208,7 @@ app.listen(PORT, () => { ### 什么是 Facilitator? -Facilitator 是一个**自动结算服务**:当有人为您的 API 付款时,Facilitator 验证付款是否真实并将其结算到链上,确保资金到达您的收款钱包。您在第三步构建的 server 仅通过 `FACILITATOR_URL` 指向 Facilitator——它不自行结算。 +Facilitator 是一个**自动结算服务**:当有人为您的 API 付款时,Facilitator 验证付款是否真实并将其结算到链上,确保资金到达您的收款钱包。您在第三步构建的 server 仅通过 `HTTPFacilitatorClient` 指向 Facilitator——它不自行结算。 **启动 API 服务器之前,必须有一个可达的 Facilitator。** @@ -290,10 +228,14 @@ Facilitator 是一个**自动结算服务**:当有人为您的 API 付款时 #### 4.1 配置服务端点 -在 `.env-exact` 中将 `FACILITATOR_URL` 设为官方端点: +在 `HTTPFacilitatorClient` 中将 `url` 设为官方端点: -``` -FACILITATOR_URL=https://facilitator.bankofai.io +```typescript +const server = createResourceServer( + new HTTPFacilitatorClient({ + url: "https://facilitator.bankofai.io", + }) +); ``` 这是您的 x402 server 用于验证和结算付款的地址——**仅供 API 调用**,无需在浏览器中打开。 @@ -310,10 +252,9 @@ FACILITATOR_URL=https://facilitator.bankofai.io #### 4.3 将 API Key 接入您的 server -官方 key 以 `X-API-KEY` 头的形式随每次 facilitator 调用发送。示例 server 已通过 `FACILITATOR_API_KEY` 支持: +官方 key 以 `X-API-KEY` 头的形式随每次 facilitator 调用发送。生产环境中,请将它保存在环境变量或密钥管理系统中,并随 facilitator 请求发送。 ```bash -# 追加到 .env-exact FACILITATOR_API_KEY=paste_your_api_key_here ``` @@ -371,7 +312,7 @@ pnpm dev:facilitator ``` [evm] facilitator registered eip155:97 (0x…) -[tron] facilitator registered tron:nile (T…) +[tron] facilitator registered tron:0xcd8690dc (T…) 🚀 Facilitator on http://localhost:4022 (evm=true, tron=true) ``` @@ -386,16 +327,16 @@ pnpm dev:facilitator ### 5.1 启动 API 服务器 -打开**新终端窗口**(不要关闭 facilitator),从 `examples/typescript` 运行: +打开**新终端窗口**(不要关闭 facilitator),在您的 API 项目中运行服务器入口文件: ```bash -pnpm dev:server +pnpm tsx src/server.ts ``` **启动成功后,应看到:** ``` -🌤️ Resource server on http://localhost:4021 (evm=true, tron=true) → facilitator http://localhost:4022 +Resource server on http://localhost:4021 ``` > ✅ **成功:** 终端显示资源服务器在 `http://localhost:4021` @@ -405,7 +346,7 @@ pnpm dev:server 在任意终端运行: ```bash -curl http://localhost:4021/weather +curl http://localhost:4021/credit ``` **预期结果:** 服务器返回 HTTP `402` 响应,携带付款要求(一个 `accepts` 数组,列出 scheme、网络、价格和您的收款地址)。 @@ -414,43 +355,22 @@ curl http://localhost:4021/weather ### 5.3 测试完整付款流程 -要测试完整的 付款 → 获取内容 流程,在**第三个终端**启动示例 client。从 `examples/typescript` 开始,先设置要支付的链/代币: - -```bash -# 追加到 .env-exact(或在 client 终端 export) -PAY_TARGETS=tron:nile@USDT # TRON Nile USDT;或 eip155:97@DHLU 用于 BSC -RESOURCE_URL=http://localhost:4021/weather -``` - -然后运行: +要测试完整的 付款 → 获取内容 流程,请使用[用户快速入门](./quickstart-for-human.md)中的最小 client。将 client 请求地址设为 `http://localhost:4021/credit`,预期返回: -```bash -pnpm dev:client +```json +{ "status": "success", "credit": 1000000 } ``` -**预期输出:** - -``` -→ [tron:nile@USDT] GET http://localhost:4021/weather -← 200 OK -{ "report": { "weather": "sunny", "temperature": 70 } } -``` - -> ✅ **成功:** client 自动检测到 `402`,签署付款,通过 facilitator 在链上结算,并获取了受保护的内容。 - -> 💡 client 用 `wrapFetchWithPayment(fetch, client)` 包装 `fetch`,使 402 挑战自动支付——客户端流程详见[用户快速入门](./quickstart-for-human.md)。 - --- ## 故障排查 | 问题 | 原因 | 解决方案 | |---------|-------|----------| -| `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` | +| `Failed to fetch` / connection refused | facilitator 或 server 未运行 | 先启动 facilitator,再运行您的 API server 入口文件 | +| client `server offered no payment option matching "…"` | 客户端选择的网络或代币与 server 公布的选项不匹配 | 检查 server 的 `accepts`(网络 + 代币),例如 `TRON_NILE` + `USDT` | | `npx tsx` 下出现 `ERR_PACKAGE_PATH_NOT_EXPORTED` | 项目未声明为 ESM | 在 `package.json` 中添加 `"type": "module"` | -| `UnsupportedNetworkError` / `No mechanism registered` | `PAY_TARGETS` 中的网络没有注册的 scheme | 确保 client 的 `EVM_NETWORKS`/`TRON_NETWORKS` 包含您的目标,且该链的钱包已解析 | +| `UnsupportedNetworkError` / `No mechanism registered` | 客户端选择的网络没有注册的 scheme | 确保 client 包含目标网络,例如 `TRON_NILE` | | `Insufficient balance` / allowance 错误 | 测试钱包缺少测试代币,或 Permit2 授权额度过低 | 从水龙头领取测试代币;client 在首次付款时会自动批准 Permit2 | | `Connection timeout` | 网络或请求超时 | 检查连接,或设置可靠的 `EVM_RPC_URL`(如 `https://bsc-testnet-rpc.publicnode.com`) | @@ -462,15 +382,17 @@ pnpm dev:client ### 1. 将 client 和 server 指向主网 -示例在相同的表中注册了测试网**和**主网——无需取消注释。在 `.env-exact` 中设置主网值即可切换: +将 server 注册的网络和收款地址切换到主网: -```bash -# server 收款地址 → 您的主网钱包 -EVM_ADDRESS=0xYourMainnetBscAddress -TRON_ADDRESS=TYourMainnetTronAddress +```typescript +import { TRON_MAINNET } from "@bankofai/x402-tron"; + +server.register(TRON_MAINNET, new ExactTronScheme()); -# client 在主网支付 -PAY_TARGETS=tron:mainnet@USDT # 或 eip155:56@USDT +// accepts 中同步改为: +network: TRON_MAINNET, +payTo: "TYourMainnetTronAddress", +price: "1 USDT", ``` ### 2. 设置可靠的 EVM RPC @@ -483,7 +405,7 @@ EVM_RPC_URL=https://bsc-rpc.publicnode.com ### 3.(自托管)将 Facilitator 切换到主网 -facilitator 的 `TRON_NETWORKS` 已包含 `tron:mainnet`,`EVM_NETWORKS` 已包含 `eip155:56`。向 Facilitator 钱包充入足够的真实 TRX/BNB 以支付结算 gas,然后重启: +facilitator 的 `TRON_NETWORKS` 已包含 `TRON_MAINNET`(`tron:0x2b6653dc`),`EVM_NETWORKS` 已包含 `eip155:56`。向 Facilitator 钱包充入足够的真实 TRX/BNB 以支付结算 gas,然后重启: ```bash pnpm dev:facilitator @@ -493,7 +415,7 @@ pnpm dev:facilitator ### 4.(官方 Facilitator)无需本地改动 -若使用官方 facilitator,保持 `FACILITATOR_URL=https://facilitator.bankofai.io` 和您的 `FACILITATOR_API_KEY`。仅 server 的收款地址切换到主网。 +若使用官方 facilitator,保持 `HTTPFacilitatorClient` 的 `url` 为 `https://facilitator.bankofai.io`,并继续使用您的 `FACILITATOR_API_KEY`。仅 server 的收款地址切换到主网。 ### 5. 确认并做小额真实测试 @@ -509,7 +431,7 @@ pnpm dev:facilitator ## 下一步 -- 探索[可运行示例](https://github.com/BofAI/x402/tree/main/examples/typescript),查看完整的 client → server → facilitator 循环,以及 `gasfree`、`upto`、`batch-settlement` 场景 +- 如果开发者想要一个更完整的例子,可以参考仓库中的 [examples](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)自动调用您的服务 @@ -523,8 +445,8 @@ pnpm dev:facilitator | 步骤 | 您做了什么 | |------|----------| | **前置准备** | 创建收款钱包、领取测试代币、了解配置参数 | -| **第一步** | 克隆 SDK 仓库并安装示例工作区 | -| **第二步** | 配置 `.env-exact`(钱包与收款地址) | +| **第一步** | 安装 x402 SDK 包 | +| **第二步** | 准备 facilitator 地址与收款地址 | | **第三步** | 运行无密钥 Express 资源服务器(带付款保护) | | **第四步** | 接入 Facilitator(官方或自托管)进行结算 | | **第五步** | 验证付款保护与完整的 client → server → facilitator 付款流程 | 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 844e029..87b71df 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 @@ -61,13 +61,13 @@ x402 支持广泛的应用场景,包括: x402 目前支持以下网络环境: -- **TRON 主网** (`tron:mainnet`) -- **TRON Shasta 测试网** (`tron:shasta`) -- **TRON Nile 测试网** (`tron:nile`) +- **TRON 主网** (`tron:0x2b6653dc`) +- **TRON Shasta 测试网** (`tron:0x94a9059e`) +- **TRON Nile 测试网** (`tron:0xcd8690dc`) - **BSC 主网** (`eip155:56`) - **BSC 测试网** (`eip155:97`) -> **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)。 +> **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`、`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 52417d0..aae05d4 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 @@ -16,7 +16,7 @@ description: 'x402 TypeScript SDK 的功能支持矩阵,以颗粒化 @bankofai | 包 | 用途 | |---------|---------| | `@bankofai/x402-core` | 协议类型、client/facilitator/server 引擎、`HTTPFacilitatorClient`、可观测性 | -| `@bankofai/x402-evm` | EVM 机制:`exact`、`upto`、`batch-settlement`、`auth-capture` | +| `@bankofai/x402-evm` | EVM 机制:`exact`、`upto`、`batch-settlement` | | `@bankofai/x402-tron` | TRON 机制:`exact`、`upto`、`batch-settlement`、`exact_gasfree` | | `@bankofai/x402-fetch` | 包装 `fetch` 的 client(`wrapFetchWithPayment`) | | `@bankofai/x402-express` | Express server 中间件 | @@ -48,13 +48,13 @@ description: 'x402 TypeScript SDK 的功能支持矩阵,以颗粒化 @bankofai ## 网络 -| 网络 | 状态 | -|-----------|--------| -| `tron:mainnet` | ✅ | -| `tron:nile` | ✅ | -| `tron:shasta` | ✅ | -| `eip155:56`(BSC 主网) | ✅ | -| `eip155:97`(BSC 测试网) | ✅ | +| 网络 | SDK 常量 | 状态 | +|-----------|----------|--------| +| `tron:0x2b6653dc` | `TRON_MAINNET` | ✅ | +| `tron:0xcd8690dc` | `TRON_NILE` | ✅ | +| `tron:0x94a9059e` | `TRON_SHASTA` | ✅ | +| `eip155:56`(BSC 主网) | - | ✅ | +| `eip155:97`(BSC 测试网) | - | ✅ | > 上游 EVM 链(Base、Base Sepolia、MegaETH、Monad、Hyperliquid)也已接入 EVM 默认资产注册表。在示例中添加一条链仅需编辑配置表——无需改动 SDK。 @@ -62,14 +62,13 @@ description: 'x402 TypeScript SDK 的功能支持矩阵,以颗粒化 @bankofai ## 付款方案 -x402 支持五种付款方案。每种方案按链族实现为 client + server + facilitator 三件套。 +x402 支持四种付款方案。每种方案按链族实现为 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)。 @@ -137,8 +136,8 @@ x402 支持五种付款方案。每种方案按链族实现为 client + server + | 代币 | 网络 | 状态 | |--------|---------|--------| -| USDT(TRC-20) | `tron:mainnet`、`tron:nile` | ✅ | -| USDD(TRC-20) | `tron:mainnet`、`tron:nile` | ✅ | +| USDT(TRC-20) | `tron:0x2b6653dc`、`tron:0xcd8690dc` | ✅ | +| USDD(TRC-20) | `tron:0x2b6653dc`、`tron:0xcd8690dc` | ✅ | | USDT(BEP-20) | `eip155:56`、`eip155:97` | ✅ | | USDC(BEP-20) | `eip155:56`、`eip155:97` | ✅ | | EPS(BEP-20) | `eip155:56` | ✅ |