diff --git a/docs/x402/getting-started/quickstart-for-human.md b/docs/x402/getting-started/quickstart-for-human.md index f2d0f50..5d057c9 100644 --- a/docs/x402/getting-started/quickstart-for-human.md +++ b/docs/x402/getting-started/quickstart-for-human.md @@ -1,270 +1,93 @@ -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - -# Quickstart for Human Users - -## Who Is This Guide For? - -This guide is for developers who want to **call an x402-protected API from code** and have payments handled automatically. When you're done, you'll have a working TypeScript script that detects a 402 response, pays for access, and retrieves the protected content — all without manual steps. - -> **Testnet first:** This guide uses testnet by default. You can safely follow every step without spending real money. - -:::info (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. -::: - ---- - -## Prerequisites - -### First: Private Key Security - -> 🔴 **Private key security warning — please read before you begin:** -> -> - Your **private key** is the sole credential that controls your wallet. Anyone who has it can access your funds completely. -> - This guide requires you to configure a private key. Follow these rules strictly: -> 1. **Never** write your private key directly in code files -> 2. **Never** commit a file containing a private key to Git or push it to GitHub -> 3. **Never** send your private key via messaging apps, email, or chat -> 4. Store it only in a local `.env` file or as a system environment variable -> 5. For testing, create a **dedicated test wallet** holding only a small amount of test tokens — never use a wallet holding real assets - -### Checklist Before You Start - -- [ ] **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, such as the `/credit` endpoint from [Quickstart for Sellers](./quickstart-for-sellers.md) - -### Create a Test Wallet and Get Test Tokens - - - - -**Create a test wallet:** - -1. Install the [TronLink browser extension](https://www.tronlink.org/) or mobile app -2. Click "Create Wallet", set a password, and **write down your seed phrase on paper and store it safely** -3. After creation, copy your wallet address (starts with `T`) - -**Claim free test tokens:** - -1. Go to the [Nile Testnet Faucet](https://nileex.io/join/getJoinPage) -2. Paste your TRON test wallet address and claim test TRX and USDT/USDD -3. In TronLink, switch to the "Nile Testnet" and confirm the balance - -**Export your private key:** - -1. In TronLink, go to Settings → Account Management → Export Private Key -2. Enter your password to confirm -3. Copy the 64-character hex string — you'll need it in the next step - -> ✅ **Success check:** You have a TRON test wallet address, its private key, and test TRX and USDT (or USDD) in the balance - - - - -**Create a test wallet:** - -1. Install the [MetaMask browser extension](https://metamask.io/) -2. Click "Create a new wallet", set a password, and **write down your seed phrase on paper and store it safely** -3. After creation, copy your wallet address (starts with `0x`) - -**Claim free test tokens:** - -1. Go to the [BSC Testnet Faucet](https://www.bnbchain.org/en/testnet-faucet) -2. Paste your BSC test wallet address and claim test BNB and USDT -3. In MetaMask, switch to the BSC Testnet and confirm the balance - -**Export your private key:** - -1. In MetaMask, click Account Details → Export Private Key -2. Enter your MetaMask password to confirm -3. Copy the 64-character hex string — you'll need it in the next step - -> ✅ **Success check:** You have a BSC test wallet address, its private key, and test BNB and USDT in the balance - - - - --- - -## Step One: Install the SDK Packages - -Install the published npm packages in your TypeScript application: - -```bash -pnpm add @bankofai/agent-wallet @bankofai/x402-fetch @bankofai/x402-tron -pnpm add -D tsx # to run the TypeScript entry point below -``` - -Use `npm install` or `yarn add` with the same package names if your project does not use pnpm. - -:::info Wallet Management -x402 uses [Agent Wallet](../../Agent-Wallet/QuickStart.md) to resolve and manage wallet credentials. Agent Wallet is installed with the package set above. Private key resolution priority: -1. Encrypted wallet file (imported via the Agent Wallet CLI) -2. Environment variable `AGENT_WALLET_PRIVATE_KEY` - -This guide uses the environment variable method. -::: - +title: "Quickstart for Buyers" +description: "Configure a wallet and make an x402 payment with wallet-cli 4.14.0." --- -## Step Two: Configure Your Private Key +# Quickstart for Buyers -**Never put your private key in code.** Set it as an environment variable so it stays out of your source files: +Use **wallet-cli 4.14.0** to manage your account, sign payments, and call x402 APIs. This guide uses a local Nile testnet service; public catalog routes may support mainnet only. -```bash -export AGENT_WALLET_PRIVATE_KEY=your_private_key_here -``` - -> 💡 **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. +## Install wallet-cli -For production TRON workloads, use a TronGrid API Key for better RPC reliability. The SDK never reads environment variables, so pass it explicitly to the signer: +Requires Node.js 20 or newer. Install globally and inspect the command interface: ```bash -export TRON_GRID_API_KEY="your_trongrid_api_key_here" -``` - -```typescript -const signer = await createClientTronSigner(wallet, { - network: TRON_NILE, - apiKey: process.env.TRON_GRID_API_KEY, -}); +npm install -g @tron-walletcli/wallet-cli@4.14.0 +wallet-cli --version +wallet-cli x402 pay --help +wallet-cli x402 pay --json-schema -o json ``` -Without `apiKey`, the signer stays on the key-less public endpoint. - -> ⚠️ **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. Here is a minimal TRON client: - -```typescript -import { resolveWallet, type Wallet, type Eip712Capable } 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"; - -// resolveWallet is typed as the base Wallet, which does not declare -// signTypedData — but for tron it returns a TronSigner, which implements both -// Wallet and Eip712Capable. Combine the SDK's own types so the wallet -// satisfies what createClientTronSigner expects. -type SignerWallet = Wallet & Eip712Capable; - -const wallet = (await resolveWallet({ - network: TRON_NILE, -})) as SignerWallet; - -const signer = await createClientTronSigner(wallet, { - network: TRON_NILE, -}); - -const client = new x402Client((_version, accepts) => - accepts.find((a) => a.network === TRON_NILE)! -); - -client.register(TRON_NILE, new ExactTronScheme(signer)); - -const fetchWithPay = wrapFetchWithPayment(fetch, client); - -const res = await fetchWithPay("http://localhost:4021/credit"); - -console.log(await res.json()); -``` +The CLI must report `4.14.0`. Help and schema discovery do not access wallet data. Operational commands may first return `command: "migration"`; inspect that result before invoking the original command again. -### Run the client +## Configure your account locally -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: +In your own terminal, use `wallet-cli create --help` or `wallet-cli import --help` to choose the account setup flow, then follow its instructions. Keep wallet passwords, private keys, and mnemonics out of chat, command arguments, and logs. Do not export a private key to an environment variable for this workflow. ```bash -pnpm tsx src/index.ts # or your app's dev script +wallet-cli list -o json +wallet-cli current -o json ``` -**Expected output:** +Verify the selected account's public address. Use `wallet-cli use --help` to select another account, or pass `--account` with its account ID or label in payment commands. Use a dedicated Nile test account funded with test TRX for fees and test USDT for payment. See the [Nile faucet](https://nileex.io/join/getJoinPage). -``` -{ "status": "success", "credit": 1000000 } -``` - -> ✅ **Success:** The SDK detected the `402` and signed a payment; the resource server then had the facilitator settle it on-chain and returned the protected content. - -> 💡 To pay with another network or token, adjust the `accepts.find(...)` selector and register the matching network scheme. +## Preview the payment -:::caution Default spend controls cap each payment at $1 -Since SDK 1.1.0 the client refuses any payment above `$1` and any asset outside the default-asset registry, before your selector ever runs. This quickstart works because the seller guide prices the route at exactly `1 USDT`. For anything larger, raise the cap: +Start the Nile service described in the [seller quick start](/x402/getting-started/quickstart-for-sellers/). Its local `GET /credit` route charges 1 USDT. A configured account is required even for the preview. -```typescript -client.setSpendControls({ maxAmountPerPayment: "$5" }); +```bash +wallet-cli x402 pay http://localhost:4021/credit \ + --method GET \ + --network tron:3448148188 \ + --token USDT \ + --scheme exact \ + --max-amount 1 \ + --dry-run -o json ``` -See [SDK Feature Matrix](../sdk-features.md) for the full options, including `allowedAssets`. -::: +`--dry-run` inspects the payment challenge without signing or paying. Check the URL, selected account, network, asset, recipient, payment amount, and fees. The decimal network ID above is wallet-cli's canonical Nile identifier. `--max-amount 1` caps the payment at one whole token, not one smallest unit; keep the USDT filter. Chain fees require a separate TRX balance. ---- +For a catalog service, discover its route with `wallet-cli x402 provider-list` and `wallet-cli x402 endpoint-list --help`; use the route's actual URL and supported network. Changing a mainnet route's network flag does not make it a testnet service. See [API discovery](/x402/api-catalog/get-started/). -## Step Four: Error Troubleshooting +## Pay after checking the preview -| Problem | Cause | Solution | -|---------|-------|----------| -| `WalletNotFoundError` / no wallet resolved | agent-wallet has no wallet, or `AGENT_WALLET_PRIVATE_KEY` is not set in this shell | Run `agent-wallet start`, or run the `export` in **the same terminal window** as 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 | -| `No network/scheme registered for x402 version: 2 …` | No scheme is registered for any network the server advertises — this is raised before your selector runs | Check that the server's `accepts` includes `network: TRON_NILE` and that you called `client.register(TRON_NILE, …)` | -| `permit2_allowance_required` | The Permit2 allowance is missing or too low | On TRON the SDK auto-broadcasts the one-time `approve` on first payment; if it persists, check that the wallet holds enough TRX for that approve | -| `approval_reset_required` (TRON) | The token already has a non-zero but insufficient Permit2 allowance, and the default `zero-first` strategy will not overwrite it | Set the token's Permit2 allowance back to `0`, then retry — the SDK never inserts an implicit `approve(0)` | -| `approval_asset_unsupported` (TRON) | The token is not a known Permit2 asset and no approval strategy was configured for it | Configure it with `createTrc20ApprovalPolicy`, or pay with a supported token | -| `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` | +Once you authorize the exact payment, rerun the same command with `--dry-run` removed and `--password-stdin` added. Supply the wallet password directly through stdin from your secure local password source. Never put it in the command, print it with `echo`, or send it to an AI. Keep the account, network, token, scheme, and amount cap unchanged from the reviewed preview. -If you need finer-grained error handling in your code: +The CLI manages the wallet and payment signing. Inspect the JSON result and HTTP response before reporting success. The sample service returns a payload like: -```typescript -try { - const res = await fetchWithPay("http://localhost:4021/credit"); - if (res.status === 200) { - console.log("Success:", await res.json()); - } else { - console.error(`Request failed: ${res.status}`); - console.error(await res.text()); - } -} catch (error) { - if (error instanceof Error && error.message.includes("no payment option")) { - 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 { - console.error("Payment error:", error); - } -} +```json +{ "status": "success", "credit": 1000000 } ``` ---- - -## Summary - -Through this guide you: - -- **Created a test wallet** and claimed test tokens, understanding why private key security matters -- **Installed the SDK** and configured your private key as an environment variable (not in code) -- **Wrote and ran** automated payment client code -- **Understood the full flow**: SDK detects 402 → signs authorization → pays → retrieves content - ---- - -## Next Steps - -- Read [Core Concepts](../core-concepts/http-402.md) to understand the x402 protocol in depth -- See [Network and Token Support](../core-concepts/network-and-token-support.md) for supported tokens and networks -- Want to build your own paid API? See [Quickstart for Sellers](./quickstart-for-sellers.md) - ---- - -## 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) — 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 +This is the service response payload, not the full wallet-cli result envelope. A successful process exit alone does not prove that payment and delivery both completed. + +## Handle errors without paying twice + +| Result | Action | +|---|---| +| Wallet migration result | Complete the local migration and inspect its outcome before rerunning the intended command. | +| No usable account | Check `list` and `current`; select the intended account locally. | +| No matching payment option or payment over the cap | Check the server's network, token, scheme, and price; do not silently change the approved payment limit. | +| Insufficient funds or approval failure | Check token balance, TRX fees, and the returned approval details before retrying. | +| Timeout, `paymentStatus: "unknown"`, or `retryPayment: false` | Reconcile the original payment and service result. Do not automatically submit another payment. | + +Check the process exit code and structured error fields. Keep any returned transaction hash for reconciliation. See the [command and result reference](/wallet-cli/command-reference/) for payment results and retry handling. + +## Next steps + +- [Wallet CLI guide](/wallet-cli/quickstart/) +- [Agent quick start](/x402/getting-started/quickstart-for-agent/) +- [SDK integration reference](/x402/sdk-features/) + + + + + + + + + + + + + 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 12a3bb1..0aa31d7 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/getting-started/quickstart-for-human.md @@ -1,269 +1,93 @@ -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - -# 用户快速入门 - -## 本指南面向谁? - -本指南面向希望**通过代码调用 x402 保护的 API 并自动完成付款**的开发者。完成后,您将拥有一个可工作的 TypeScript 脚本:它能检测 402 响应、为访问付费、并获取受保护的内容——全程无需手动操作。 - -> **测试网优先:** 本指南默认使用测试网,您可以安全地完成每一步而不花费真实资金。 - -:::info SDK(仅 TypeScript) -x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发布。本指南展示如何直接集成已发布的 npm 包。 -::: - --- - -## 前置准备 - -### 首先:私钥安全 - -> 🔴 **私钥安全警告——开始前请阅读:** -> -> - 您的**私钥**是控制钱包的唯一凭据。任何拥有它的人都可以完全访问您的资金。 -> - 本指南要求您配置私钥。请严格遵守以下规则: -> 1. **切勿**将私钥直接写在代码文件中 -> 2. **切勿**将含私钥的文件提交到 Git 或推送到 GitHub -> 3. **切勿**通过消息应用、邮件或聊天发送私钥 -> 4. 仅将其保存在本地 `.env` 文件或系统环境变量中 -> 5. 测试时请创建一个**专用测试钱包**,仅持有少量测试代币——切勿使用持有真实资产的钱包 - -### 开始前清单 - -- [ ] 已安装 **Node.js 22+** 和 **pnpm 11.1+** -- [ ] 已创建专用**测试钱包**(见下文) -- [ ] 已领取测试代币(免费) -- [ ] 有一个目标 x402 保护的 API URL(例如按[卖家快速入门](./quickstart-for-sellers.md)启动的 `/credit` 接口) - -### 创建测试钱包并领取测试代币 - - - - -**创建测试钱包:** - -1. 安装 [TronLink 浏览器扩展](https://www.tronlink.org/) 或手机 App -2. 点击"创建钱包",设置密码,并**将助记词抄写在纸上并妥善保管** -3. 创建后,复制您的钱包地址(以 `T` 开头) - -**领取免费测试代币:** - -1. 前往 [Nile 测试网水龙头](https://nileex.io/join/getJoinPage) -2. 粘贴您的 TRON 测试钱包地址,领取测试 TRX 和 USDT/USDD -3. 在 TronLink 切换到"Nile 测试网"并确认余额 - -**导出私钥:** - -1. 在 TronLink 中,前往 设置 → 账户管理 → 导出私钥 -2. 输入密码确认 -3. 复制 64 位十六进制字符串——下一步将用到 - -> ✅ **成功检查:** 您拥有 TRON 测试钱包地址、其私钥,以及测试 TRX 和 USDT(或 USDD)余额 - - - - -**创建测试钱包:** - -1. 安装 [MetaMask 浏览器扩展](https://metamask.io/) -2. 点击"创建新钱包",设置密码,并**将助记词抄写在纸上并妥善保管** -3. 创建后,复制您的钱包地址(以 `0x` 开头) - -**领取免费测试代币:** - -1. 前往 [BSC 测试网水龙头](https://www.bnbchain.org/en/testnet-faucet) -2. 粘贴您的 BSC 测试钱包地址,领取测试 BNB 和 USDT -3. 在 MetaMask 切换到 BSC 测试网并确认余额 - -**导出私钥:** - -1. 在 MetaMask 中,点击 账户详情 → 导出私钥 -2. 输入 MetaMask 密码确认 -3. 复制 64 位十六进制字符串——下一步将用到 - -> ✅ **成功检查:** 您拥有 BSC 测试钱包地址、其私钥,以及测试 BNB 和 USDT 余额 - - - - +title: "买家快速入门" +description: "使用 wallet-cli 4.14.0 配置钱包并完成 x402 支付。" --- -## 第一步:安装 SDK 包 - -在您的 TypeScript 应用中安装已发布的 npm 包: - -```bash -pnpm add @bankofai/agent-wallet @bankofai/x402-fetch @bankofai/x402-tron -pnpm add -D tsx # 运行下面的 TypeScript 入口文件 -``` +# 买家快速入门 -如果您的项目不使用 pnpm,也可以用 `npm install` 或 `yarn add` 安装同名包。 - -:::info 钱包管理 -x402 使用 [Agent Wallet](../../Agent-Wallet/QuickStart.md) 解析和管理钱包凭据。Agent Wallet 会随上面的包一起安装。私钥解析优先级: -1. 加密钱包文件(通过 Agent Wallet CLI 导入) -2. 环境变量 `AGENT_WALLET_PRIVATE_KEY` - -本指南使用环境变量方式。 -::: - ---- +使用 **wallet-cli 4.14.0** 管理账户、签署支付并调用 x402 API。本指南使用本地 Nile 测试网服务;公开目录中的服务可能只支持主网。 -## 第二步:配置私钥 +## 安装 wallet-cli -**切勿将私钥写在代码中。** 将其设为环境变量以使其远离源文件: +需要 Node.js 20 或更新版本。全局安装并查看命令说明: ```bash -export AGENT_WALLET_PRIVATE_KEY=your_private_key_here +npm install -g @tron-walletcli/wallet-cli@4.14.0 +wallet-cli --version +wallet-cli x402 pay --help +wallet-cli x402 pay --json-schema -o json ``` -> 💡 **提示:** 本快速入门使用 `TRON_NILE`(`tron:0xcd8690dc`)付款。client 会从 server 返回的 `accepts` 中选择 `network === TRON_NILE` 的付款选项。 +CLI 版本应为 `4.14.0`。帮助和 schema 查询不访问钱包数据。其他命令首次运行可能返回 `command: "migration"`;检查迁移结果后,再执行原命令。 -生产 TRON 负载建议使用 TronGrid API Key,以获得更可靠的 RPC。SDK 不会读取任何环境变量,因此必须显式传给 signer: +## 在本地配置账户 -```bash -export TRON_GRID_API_KEY="your_trongrid_api_key_here" -``` - -```typescript -const signer = await createClientTronSigner(wallet, { - network: TRON_NILE, - apiKey: process.env.TRON_GRID_API_KEY, -}); -``` - -不传 `apiKey` 时,signer 会继续使用无密钥的公共节点。 - -> ⚠️ **安全提醒:** 私钥仅保存在环境变量或安全的密钥管理系统中。**切勿将含私钥的文件提交到 Git 或分享给任何人。** - ---- - -## 第三步:编写并运行客户端代码 - -客户端会包装 `fetch`,使 HTTP `402 Payment Required` 挑战自动支付。下面是一个最小 TRON client: - -```typescript -import { resolveWallet, type Wallet, type Eip712Capable } 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"; - -// resolveWallet 的返回类型是基础的 Wallet,不声明 signTypedData; -// 但在 tron 上它返回的是 TronSigner,该类同时实现了 Wallet 与 Eip712Capable。 -// 直接组合 SDK 自身导出的这两个类型,即可满足 createClientTronSigner 的入参要求。 -type SignerWallet = Wallet & Eip712Capable; - -const wallet = (await resolveWallet({ - network: TRON_NILE, -})) as SignerWallet; - -const signer = await createClientTronSigner(wallet, { - network: TRON_NILE, -}); - -const client = new x402Client((_version, accepts) => - accepts.find((a) => a.network === TRON_NILE)! -); - -client.register(TRON_NILE, new ExactTronScheme(signer)); - -const fetchWithPay = wrapFetchWithPayment(fetch, client); - -const res = await fetchWithPay("http://localhost:4021/credit"); - -console.log(await res.json()); -``` - -### 运行 client - -首先确保资源服务器 + facilitator 正在运行(参见[卖家快速入门](./quickstart-for-sellers.md)),然后用同一组环境变量运行您的客户端应用: +在自己的终端中,通过 `wallet-cli create --help` 或 `wallet-cli import --help` 选择账户配置流程,并按说明操作。不要将钱包密码、私钥或助记词放入聊天、命令参数或日志。本流程不需要将私钥导出为环境变量。 ```bash -pnpm tsx src/index.ts # 或您的应用 dev 脚本 +wallet-cli list -o json +wallet-cli current -o json ``` -**预期输出:** +核对选中账户的公开地址。需要切换时查看 `wallet-cli use --help`,也可以在支付命令中用 `--account` 指定账户 ID 或标签。使用专用 Nile 测试账户,准备支付手续费的测试 TRX 和付款所需的测试 USDT。参见 [Nile 水龙头](https://nileex.io/join/getJoinPage)。 -``` -{ "status": "success", "credit": 1000000 } -``` - -> ✅ **成功:** SDK 检测到 `402` 并签署了付款;随后由资源服务端交给 facilitator 在链上结算,并返回受保护的内容。 +## 预览支付 -> 💡 要改为支付其他网络或代币,请调整 selector 中的 `accepts.find(...)` 条件,并注册对应网络的 scheme。 +先启动[卖家快速入门](/zh-Hans/x402/getting-started/quickstart-for-sellers/)中的 Nile 服务。本地 `GET /credit` 接口收取 1 USDT。预览也需要已配置账户。 -:::caution 默认消费管控把每笔支付限制在 $1 -自 SDK 1.1.0 起,客户端会在你的 selector 运行之前就拒绝超过 `$1` 的支付、以及默认资产注册表之外的资产。本快速入门能跑通,是因为卖家指南把价格正好设为 `1 USDT`。金额更大时需要提高上限: - -```typescript -client.setSpendControls({ maxAmountPerPayment: "$5" }); +```bash +wallet-cli x402 pay http://localhost:4021/credit \ + --method GET \ + --network tron:3448148188 \ + --token USDT \ + --scheme exact \ + --max-amount 1 \ + --dry-run -o json ``` -完整选项(含 `allowedAssets`)见 [SDK 功能矩阵](../sdk-features.md)。 -::: +`--dry-run` 只检查支付要求,不签名、不付款。核对 URL、选中账户、网络、资产、收款地址、金额和手续费。上面的十进制网络 ID 是 wallet-cli 的 Nile 规范标识。`--max-amount 1` 表示最多支付一个完整代币,不是一个最小单位;保留 USDT 筛选条件。链上手续费还需要单独准备 TRX。 ---- +调用目录服务时,通过 `wallet-cli x402 provider-list` 和 `wallet-cli x402 endpoint-list --help` 查找服务,使用其实际路由 URL 和支持的网络。只修改网络参数不会将主网服务变成测试网服务。参见 [API 服务发现](/zh-Hans/x402/api-catalog/get-started/)。 -## 第四步:错误排查 +## 核对后付款 -| 问题 | 原因 | 解决方案 | -|---------|-------|----------| -| `WalletNotFoundError` / 解析不到钱包 | agent-wallet 里没有钱包,或当前 shell 未设置 `AGENT_WALLET_PRIVATE_KEY` | 执行 `agent-wallet start`,或确保在**运行脚本的同一终端窗口**中执行 `export` | -| `WalletNotFoundError: No active wallet set` | agent-wallet 未配置钱包 | 运行 `agent-wallet start` 并按提示导入私钥 | -| `Insufficient balance` / 余额错误 | 测试钱包 USDT/USDD 不足 | 返回前置准备,从水龙头领取测试代币 | -| `No network/scheme registered for x402 version: 2 …` | server 公布的网络里没有任何一个注册了 scheme——该错误在 selector 运行之前就会抛出 | 检查 server 的 `accepts` 是否包含 `network: TRON_NILE`,以及是否调用了 `client.register(TRON_NILE, …)` | -| `permit2_allowance_required` | Permit2 授权额度缺失或过低 | 在 TRON 上 SDK 会在首次付款时自动广播一次性 `approve`;若仍存在,检查钱包是否有足够 TRX 支付这笔授权 | -| `approval_reset_required`(TRON) | 该代币的 Permit2 授权额度非零但不足,默认的 `zero-first` 策略不会直接覆写 | 先把该代币的 Permit2 授权额度重置为 `0` 再重试——SDK 不会自动插入 `approve(0)` | -| `approval_asset_unsupported`(TRON) | 该代币不属于已知 Permit2 资产,也没有为它配置授权策略 | 用 `createTrc20ApprovalPolicy` 为其配置策略,或改用受支持的代币付款 | -| `Connection timeout` | 网络或请求超时 | 检查 API 服务、facilitator 和 TRON RPC 连接 | -| `ERR_PACKAGE_PATH_NOT_EXPORTED` | 项目未声明为 ESM | 在 `package.json` 中添加 `"type": "module"` | +确认授权这笔具体付款后,在同一命令中移除 `--dry-run` 并加上 `--password-stdin`。通过安全的本地密码来源将钱包密码直接传入 stdin。不要把密码写在命令里、通过 `echo` 打印,或发送给 AI。保持账户、网络、代币、scheme 和金额上限与已核对的预览一致。 -如需更细粒度的错误处理: +钱包和支付签名均由 CLI 处理。检查 JSON 结果和 HTTP 响应后再判断是否成功。示例服务返回类似以下业务数据: -```typescript -try { - const res = await fetchWithPay("http://localhost:4021/credit"); - if (res.status === 200) { - console.log("Success:", await res.json()); - } else { - console.error(`Request failed: ${res.status}`); - console.error(await res.text()); - } -} catch (error) { - if (error instanceof Error && error.message.includes("no payment option")) { - 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 { - console.error("Payment error:", error); - } -} +```json +{ "status": "success", "credit": 1000000 } ``` ---- +这是服务响应内容,不是完整的 wallet-cli 结果对象。进程退出成功本身不能证明支付和服务交付都已完成。 -## 完成总结 +## 错误处理与避免重复付款 -通过本指南,您: +| 结果 | 处理方式 | +|---|---| +| 返回钱包迁移结果 | 完成本地迁移并检查结果,再执行原命令。 | +| 没有可用账户 | 检查 `list` 和 `current`,在本地选择预期账户。 | +| 没有匹配的支付选项或价格超过上限 | 核对服务端网络、代币、scheme 和价格,不要自动提高已授权金额上限。 | +| 余额不足或授权失败 | 检查代币余额、TRX 手续费及返回的授权详情后再决定是否重试。 | +| 超时、`paymentStatus: "unknown"` 或 `retryPayment: false` | 核实原付款和服务结果,不要自动再次付款。 | -- **创建了测试钱包**并领取了测试代币,理解了私钥安全的重要性 -- **安装了 SDK** 并将私钥配置为环境变量(而非写在代码中) -- **编写并运行了**自动付款客户端代码 -- **理解了完整流程**:SDK 检测 402 → 签署授权 → 付款 → 获取内容 - ---- +检查进程退出码和结构化错误字段,保存返回的交易哈希以核实状态。支付结果和重试规则参见[命令与结果参考](/zh-Hans/wallet-cli/command-reference/)。 ## 下一步 -- 阅读[核心概念](../core-concepts/http-402.md)深入了解 x402 协议 -- 查看[网络与代币支持](../core-concepts/network-and-token-support.md)了解支持的代币与网络 -- 想构建自己的付费 API?参见[卖家快速入门](./quickstart-for-sellers.md) - ---- - -## 参考资料 - -- [x402 npm 包](https://www.npmjs.com/package/@bankofai/x402-tron) —— 应用开发应优先安装的发布包 -- [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 使用的密钥托管 +- [Wallet CLI 指南](/zh-Hans/wallet-cli/quickstart/) +- [Agent 快速入门](/zh-Hans/x402/getting-started/quickstart-for-agent/) +- [SDK 集成参考](/zh-Hans/x402/sdk-features/) + + + + + + + + + + + + +