From 2887942d13c15bff6cfa95899fa2940e5f2adb59 Mon Sep 17 00:00:00 2001 From: jizhen181-dot Date: Wed, 28 Oct 2026 17:02:01 +0800 Subject: [PATCH 01/13] docs(x402): align with SDK 2.1.0 and facilitator v2.2.2 - Packages, imports and samples follow @bankofai/x402-tron 2.1.0 on official @x402/* 2.28.0; Node.js 24.22.1+. - Facilitator error codes, rate limits, /sponsoring/ready, sponsoring scope (Nile, API key) and GasFree proxy behaviour match v2.2.2. - TRON resource sponsoring now notes the 2.1.0 client extension requirement. - Decimal TRON CAIP-2 IDs; the API Catalog keeps hex IDs; catalog CI rules. - Diagrams: catalog consumer is wallet-cli, MCP catalog lookup not shipped, zh permitTransferFrom. Co-Authored-By: Claude Opus 5.5 (1M context) --- changelog/x402.md | 40 +++++++ docs/x402/AGENTS.md | 10 +- docs/x402/api-catalog/get-started.md | 6 +- docs/x402/api-catalog/index.md | 2 +- docs/x402/api-catalog/list-your-service.md | 13 ++- docs/x402/api-catalog/reference.md | 14 ++- .../x402/core-concepts/OfficialFacilitator.md | 36 +++--- docs/x402/core-concepts/client-server.md | 6 +- docs/x402/core-concepts/facilitator.md | 23 ++-- docs/x402/core-concepts/gateway.md | 2 +- docs/x402/core-concepts/http-402.md | 16 +-- .../network-and-token-support.md | 29 +++-- docs/x402/core-concepts/wallet.md | 4 +- docs/x402/faq.md | 50 ++++---- .../getting-started/quickstart-for-human.md | 24 ++-- .../getting-started/quickstart-for-sellers.md | 75 +++++------- docs/x402/index.md | 12 +- docs/x402/sdk-features.md | 109 ++++++++++-------- .../current/x402.md | 40 +++++++ .../current/x402/AGENTS.md | 10 +- .../current/x402/api-catalog/get-started.md | 6 +- .../current/x402/api-catalog/index.md | 2 +- .../x402/api-catalog/list-your-service.md | 13 ++- .../current/x402/api-catalog/reference.md | 14 ++- .../x402/core-concepts/OfficialFacilitator.md | 36 +++--- .../x402/core-concepts/client-server.md | 6 +- .../current/x402/core-concepts/facilitator.md | 25 ++-- .../current/x402/core-concepts/gateway.md | 2 +- .../current/x402/core-concepts/http-402.md | 16 +-- .../network-and-token-support.md | 29 +++-- .../current/x402/core-concepts/wallet.md | 6 +- .../current/x402/faq.md | 50 ++++---- .../getting-started/quickstart-for-human.md | 24 ++-- .../getting-started/quickstart-for-sellers.md | 75 +++++------- .../current/x402/index.md | 12 +- .../current/x402/sdk-features.md | 109 ++++++++++-------- .../x402-api-catalog-pipeline.light.svg | 4 +- .../diagrams/x402-api-catalog-pipeline.svg | 4 +- .../x402-api-catalog-pipeline.zh.light.svg | 4 +- .../diagrams/x402-api-catalog-pipeline.zh.svg | 4 +- .../x402-payment-scheme-flow.zh.light.svg | 2 +- .../diagrams/x402-payment-scheme-flow.zh.svg | 2 +- 42 files changed, 555 insertions(+), 411 deletions(-) diff --git a/changelog/x402.md b/changelog/x402.md index 1fc8792f..de867bdc 100644 --- a/changelog/x402.md +++ b/changelog/x402.md @@ -7,6 +7,46 @@ description: 'Release notes for the x402 payment protocol, SDK, and CLI.' Release notes for the x402 protocol, SDK, and [Wallet CLI guide](/wallet-cli/). +
+
Oct 27, 2026
+
+ +### Facilitator error codes completed + +
DocsFix
+ +- The facilitator error list now includes the protocol-level sponsoring reasons (`approval_transaction_reused`, `sponsor_approval_lifetime_exceeded`, `sponsor_existing_delegation`), `400 permit2_invalid_authorization` on `/settle`, `500 internal_error`, and the GasFree proxy's `502 bad_gateway`. +- **Wallet CLI reference** — a table of the error codes a reader will hit (`missing_wallet_address`, `auth_required`, `invalid_option`, `no_matching_requirement`, `permit2_allowance_required`, …) with exit codes, and the `bai recharge` rules: `--to`, the token default (USDC on Base, USDT elsewhere) and the minimum amounts behind `invalid_amount`. + +👉 [Facilitator](/x402/core-concepts/facilitator/) · [Wallet CLI reference](/wallet-cli/command-reference/) + +
+
+ +
+
Oct 25, 2026
+
+ +### Docs aligned with SDK 2.1.0 and facilitator v2.2.2 + +
DocsFix
+ +- **SDK 2.1.0** — the SDK pages follow the 2.1.0 package set: `@bankofai/x402-tron` 2.1.0 and the new `@bankofai/x402-tron-extensions` 2.1.0 (upgrade the two together) on official `@x402/core` 2.28.0, with the official `@x402/*` HTTP/MCP integrations, `@x402/evm` and `@x402/extensions` 2.28.0. The quickstarts import from `@x402/core`, `@x402/fetch` and `@x402/express`, and construct `new x402ResourceServer(...)` in place of `createResourceServer` from `@bankofai/x402-core`, which is not used with the 2.1 mechanism. The local EVM package, `@bankofai/x402-extensions` and the `typescript/packages/legacy/` compatibility packages were removed in 2.1.0 (the root `legacy/` archive, including the retired Python SDK, already in 2.0.0). TRON resource sponsoring now needs an explicitly registered client extension, and the SDK requires Node.js 24.22.1+. The official `@x402/evm` ships no BSC default assets, so BSC routes must be priced with an explicit `{ asset, amount, extra }` object and BSC assets must be allowlisted on the client; among the networks these docs cover, the default assets are now USDT on TRON and USDC on Base / Base Sepolia. +- **Pending settlement** — `settlement_pending` is documented as a non-terminal result to reconcile rather than resubmit. 2.1.0 adds the injectable `pendingSettlementStore` (the default `InMemoryTronPendingSettlementStore` covers one process only) and the `settlement_store_unavailable` and `settlement_execution_failed` codes, and extends `chain_read_failed` (already used by `exact` Permit2 reads) to `upto` preflight reads. `HTTPFacilitatorClient` now comes from official Core with a 90 s default timeout; the examples set 120 s. +- **TRON-only examples** — the repository examples now cover TRON only, so the seller quickstart points BSC and Base sellers to the official facilitator or the upstream `@x402/evm` examples. The official facilitator v2.2.1 and v2.2.2 are security releases (Node.js and dependency updates; v2.2.2 also installs the patched system Brotli for CVE-2026-111497); its documented behavior is unchanged. +- **Decimal TRON IDs** — examples and tables use `tron:728126428` (mainnet), `tron:3448148188` (Nile) and `tron:2494104990` (Shasta). The x402 SDK still accepts the hex forms as input; wallet-cli's `--network` does not. The API Catalog is the exception: its schema still accepts only the hex form. +- **Official facilitator limits** — anonymous callers get 10 requests per IP per minute and API Keys 1,000 per minute, counted separately for `/verify` and `/settle` (both are limited). Over the limit returns `429` with `Retry-After`. The docs previously said one `/settle` per minute. +- **Resource sponsoring on Nile** — the official facilitator lists `trc20ApprovalResourceSponsoring` in `/supported` but enables it on Nile only, for Nile USDT, and requires an API Key (`sponsor_auth_required` / `sponsor_network_disabled` otherwise). `GET /sponsoring/ready` and the `/verify` / `/settle` error codes are now documented. +- **Settlement records** — successful settlements are unique per (network, asset, payer, nonce) through a partial unique index. This corrects the Sep 9 note that the table had no unique constraint. +- **API Catalog** — local checks need Python 3.11+; the checklist adds the remaining CI rules (required `pay.md` strings, a TRON `exact` + `permit2` first route, no `--scheme exact_gasfree`, all four `status` keys) and notes that fixed-count tests must be updated in the same PR. The list commands read the local cache and download only when it is missing or lacks what was asked for, so run `update-catalog` to refresh a cache that may be stale. +- **Wallet CLI reference** — now targets `@tron-walletcli/wallet-cli@4.15.1` and documents the default $1 per-payment cap for known stablecoins (`amount_exceeds_limit`), `--out` (required for binary responses), `--max-gasfree-fee-raw`, and that `--max-raw-amount` requires `--token` or `--asset`. The quick start warns that a first TRON `exact` payment in a token may broadcast a one-time `approve(Permit2, MaxUint256)`, and the result reference covers a response format error after settlement (`retryPayment: false`). It also notes that the wallet-cli Skill pins 4.14.0, so Skill users install that version instead. +- **Protocol details** — a `402` carries its requirements in the Base64 `PAYMENT-REQUIRED` header with a `{}` body, and verification failures put the reason in that header's `error`; an insufficient Permit2 allowance on `exact` / `upto` returns `412 permit2_allowance_required`. EVM `exact` also supports the `upfront` payment flow. Permit2 payloads use `payload.permit2Authorization`. DHLU was removed from the token tables (no current code references it), BSC mainnet USDC is marked as explicit-asset only, the official facilitator's rate-limit counters are per instance, and the npm packages are Apache-2.0 (the repository LICENSE is MIT). + +👉 [SDK Features](/x402/sdk-features/) · [Official Facilitator](/x402/core-concepts/OfficialFacilitator/) · [List Your Service](/x402/api-catalog/list-your-service/) + +
+
+
Sep 28, 2026
diff --git a/docs/x402/AGENTS.md b/docs/x402/AGENTS.md index 30419d17..afacdca3 100644 --- a/docs/x402/AGENTS.md +++ b/docs/x402/AGENTS.md @@ -18,7 +18,7 @@ import TabItem from '@theme/TabItem'; - `docs/faq.md` — Frequently Asked Questions. - `sidebars.js` — Docusaurus sidebar configuration. - `docusaurus.config.js` — Main Docusaurus configuration file. -- `docs/sdk-features.md` — Feature matrix for the TypeScript-only x402 SDK (`@bankofai/x402-*` packages). +- `docs/sdk-features.md` — Feature matrix for the TypeScript-only x402 SDK (`@bankofai/x402-tron` and `@bankofai/x402-tron-extensions` on the official `@x402/*` packages). --- @@ -35,8 +35,8 @@ Documentation must reflect code changes immediately. Follow these dependency map ## 4. Style & Writing Standards -- Use **TypeScript** as the primary example language (the SDK is TypeScript-only; the previous Python SDK lives under `legacy/`). -- Prefer code samples that work with the published `@bankofai/x402-*` npm packages. Runnable `examples/typescript/` code may be used as a reference implementation when it matches the package API. +- Use **TypeScript** as the primary example language (the SDK is TypeScript-only; the previous Python SDK was removed in x402 v2.0.0). +- Prefer code samples that work with the published npm packages (`@bankofai/x402-tron`, `@bankofai/x402-tron-extensions` and the official `@x402/*` packages). Runnable `examples/typescript/` code may be used as a reference implementation when it matches the package API. - All API examples **must include complete error handling**. - Target audience: developers with **2–5 years of experience**. - Use Docusaurus MDX components (``, ``) for multi-language examples. @@ -66,7 +66,7 @@ Documentation must reflect code changes immediately. Follow these dependency map -- **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. +- **Network Identifier**: Must follow the `tron:` CAIP-2 format (e.g. `tron:3448148188` for Nile); hex forms such as `tron:0xcd8690dc` are deprecated input aliases. 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. @@ -142,7 +142,7 @@ When SDK code changes in any of the following areas, you **must** update `docs/s - New signers added under the `*/signers/` directory. - New features introduced in the Client or Server components. -> **Note**: The SDK is TypeScript-only. Cross-check documentation against the published `@bankofai/x402-*` package API, `typescript/packages/` exports, and `examples/typescript/` reference source. +> **Note**: The SDK is TypeScript-only. Cross-check documentation against the published package APIs (`@bankofai/x402-tron`, `@bankofai/x402-tron-extensions`, official `@x402/*`), `typescript/packages/` exports, and `examples/typescript/` reference source. --- diff --git a/docs/x402/api-catalog/get-started.md b/docs/x402/api-catalog/get-started.md index b810dfeb..f5796d7b 100644 --- a/docs/x402/api-catalog/get-started.md +++ b/docs/x402/api-catalog/get-started.md @@ -5,18 +5,18 @@ description: "Discover catalog services and preview payments with wallet-cli." # Catalog Quick Start -Install `@tron-walletcli/wallet-cli@4.14.0` using the [Wallet CLI quick start](/wallet-cli/quickstart/). Catalog reads need no wallet or password; payment previews and payments require a configured account. +Install Wallet CLI using the [Wallet CLI quick start](/wallet-cli/quickstart/). Catalog reads need no wallet or password; payment previews and payments require a configured account. ## Browse providers ```bash +wallet-cli x402 update-catalog -o json wallet-cli x402 provider-list -o json wallet-cli x402 provider-show dia -o json wallet-cli x402 endpoint-list dia -o json -wallet-cli x402 update-catalog -o json ``` -`provider-list` supports network, category, and capability filters. `update-catalog` refreshes the local cache. +`update-catalog` downloads the catalog to the local cache. `provider-list`, `provider-show`, and `endpoint-list` read that cache and download from the catalog only when the cache is missing or lacks what was asked for; they never refresh it, so run `update-catalog` again when you want the latest providers and prices. `provider-list` supports `--network`, `--category`, and `--capability` filters. ## Choose an endpoint and network diff --git a/docs/x402/api-catalog/index.md b/docs/x402/api-catalog/index.md index 9a86d241..9cf05710 100644 --- a/docs/x402/api-catalog/index.md +++ b/docs/x402/api-catalog/index.md @@ -35,7 +35,7 @@ Three consumers share the same data: - **[Catalog website](https://bankofai.io/catalog)**: for humans to browse and compare services. - **wallet-cli**: search, inspect, and make paid calls from the command line. -- **MCP**: `@bankofai/x402-mcp` lets an Agent pay for an x402 endpoint over MCP. Catalog-aware MCP discovery — browsing the catalog by name from inside an MCP client — is not shipped yet; use `wallet-cli x402 provider-list` for discovery today. +- **MCP**: `@x402/mcp` (the official MCP integration used since SDK 2.1.0) lets an Agent pay for an x402 endpoint over MCP. Catalog-aware MCP discovery — browsing the catalog by name from inside an MCP client — is not shipped yet; use `wallet-cli x402 provider-list` for discovery today. ## What's in the catalog diff --git a/docs/x402/api-catalog/list-your-service.md b/docs/x402/api-catalog/list-your-service.md index 9a7efbca..1c84c718 100644 --- a/docs/x402/api-catalog/list-your-service.md +++ b/docs/x402/api-catalog/list-your-service.md @@ -163,7 +163,7 @@ Full field definitions: [Data Format & API Reference](./reference.md). ### How to write pay.md -`pay.md` is read by humans and Agents alike. Three parts are recommended: basic service info, endpoint addresses and prices, and copy-paste call examples. The catalog's CI tests require every `pay.md` to contain a `wallet-cli x402 pay` example with `--network tron:728126428` and `--scheme exact`, to mention `exact_gasfree`, and to cover Base Mainnet (`eip155:8453`). The real SunPump file, `providers/sunpump-token-launch/pay.md`: +`pay.md` is read by humans and Agents alike. Three parts are recommended: basic service info, endpoint addresses and prices, and copy-paste call examples. The catalog's CI tests require every `pay.md` to contain a `wallet-cli x402 pay` example with `--network tron:728126428` and `--scheme exact`, to mention `exact_gasfree`, and to cover Base Mainnet: the text must contain `Base Mainnet`, `eip155:8453`, a `-base` gateway provider, `USDC`, and `EIP-3009`, and must not mention `Sepolia` or `eip155:84532`. The real SunPump file, `providers/sunpump-token-launch/pay.md`: ````markdown # SunPump Agent Token Launch API @@ -286,20 +286,21 @@ 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. TRON IDs must be `tron:0x2b6653dc`, `tron:0xcd8690dc`, or `tron:0x94a9059e`. CI tests require every provider to list Base Mainnet `eip155:8453` and reject Base Sepolia `eip155:84532`. +- `chains` needs at least one entry, using CAIP-2 style chain IDs. TRON IDs must be `tron:0x2b6653dc`, `tron:0xcd8690dc`, or `tron:0x94a9059e` — the decimal form (`tron:728126428`) is rejected; see [Chain IDs](./reference.md#chain-ids). CI tests require every provider to list Base Mainnet `eip155:8453` and reject Base Sepolia `eip155:84532`. - `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`. - `serviceUrl`, every endpoint `url`, and every route `url` must start with `https://`. - Unknown fields are rejected — at the top level and in endpoints, routes, `i18n.`, and `status`. - `x402Routes` is optional in the schema, but CI tests require every endpoint to publish exactly one Base Mainnet route: `scheme` `exact`, `assetTransferMethod` `eip3009`, and a `provider` ending in `-base`. Every route's `network` must also appear in `chains`, and `exact_gasfree` is allowed only on TRON networks. Every route needs `network`, `provider`, `scheme`, and `url`; an `exact` route must also carry `assetTransferMethod` (`permit2` or `eip3009`), and an `exact_gasfree` route must **omit** it. A network may appear more than once — TRON typically publishes both an `exact` and an `exact_gasfree` route — as long as each `(provider, network, scheme, url)` combination is unique. Legacy `fee` / `feeConfig` fields are rejected. See the [reference](./reference.md#x402routes--multi-network-routing). +- On every endpoint with TRON routes, the first TRON route must be `exact` + `permit2` (the default), and the service-level `description` — including its `i18n` translations — must not contain `--scheme exact_gasfree`. - The service and every endpoint must provide `i18n.zh-CN` translations for `title`, `subtitle`, `description`, and `useCase`. -- `status`, if present, only accepts: `catalog` `listed`/`unlisted`; `gateway` `configured`/`unknown`/`unavailable`; `payment` `paid-route`/`mainnet`/`testnet`/`unknown`; `upstream` `public`/`authenticated`/`unknown`/`unavailable`. +- `status` is optional, but if present it must include all four keys, and only accepts: `catalog` `listed`/`unlisted`; `gateway` `configured`/`unknown`/`unavailable`; `payment` `paid-route`/`mainnet`/`testnet`/`unknown`; `upstream` `public`/`authenticated`/`unknown`/`unavailable`. - `pay.md` must be submitted together with `catalog.json`; both files are scanned for sensitive data. - No keys, private keys, or private network addresses anywhere. ## Step 2: Validate locally -Before submitting, install the validation dependency, then run validation, build, and the unit tests locally — the same steps CI runs: +Before submitting, install the validation dependency, then run validation, build, and the unit tests locally — the same steps CI runs. The scripts need Python 3.11 or newer (CI uses 3.12); on 3.10 they fail with `ImportError: cannot import name 'UTC' from 'datetime'`. ```bash pip install -r requirements.txt @@ -310,6 +311,10 @@ python3 -m unittest discover -s tests The first two print `validated N provider(s)` and `built N provider(s) into dist`, where N counts every provider in the repository, yours included. +:::note Pinned counts in the tests +`tests/test_build.py` pins current catalog totals, such as the number of Base Mainnet routes across all providers. A new provider that passes `validate.py` can still fail those assertions (for example `AssertionError: 20 != 18`); update the expected counts in the same PR. +::: + ## Step 3: Open the Pull Request Add the two files to the [catalog repository](https://github.com/BofAI/x402-catalog) under the matching directory, together with the regenerated `dist/` files: diff --git a/docs/x402/api-catalog/reference.md b/docs/x402/api-catalog/reference.md index 3eb42820..a7e99d02 100644 --- a/docs/x402/api-catalog/reference.md +++ b/docs/x402/api-catalog/reference.md @@ -59,7 +59,7 @@ An endpoint may serve the same capability across several chains, each settling t | Field | Type | Description | |---|---|---| -| `network` | string | Canonical CAIP-2 chain ID this route settles on (e.g. `tron:0x2b6653dc`, `eip155:56`, `eip155:8453`). Legacy TRON aliases such as `tron:nile` are rejected by schema validation. | +| `network` | string | CAIP-2 chain ID this route settles on (e.g. `tron:0x2b6653dc`, `eip155:56`, `eip155:8453`). For TRON the catalog accepts only the hexadecimal IDs listed under [Chain IDs](#chain-ids); aliases such as `tron:nile` and the decimal form `tron:728126428` are both rejected by the catalog's validation. | | `provider` | string | The gateway provider `fqn` that handles this network | | `scheme` | string | x402 payment scheme for this route: `exact` or, on TRON, `exact_gasfree` — each route declares its own | | `assetTransferMethod` | string | **Required** for every `exact` route: use `permit2` for TRON/BSC routes and `eip3009` for Base USDC routes. **Omit** it only on `exact_gasfree` routes. | @@ -68,7 +68,7 @@ An endpoint may serve the same capability across several chains, each settling t The build passes this through to outputs as `x402_routes`. When present, callers/agents pick the route matching their intended payment chain; the top-level `url` remains the default route. :::note GasFree routes -On TRON you can add an `exact_gasfree` route alongside the `exact` one for the same endpoint: a relayer pays the network energy and deducts its fee from the payment token, so the payer needs no TRX. GasFree routes are TRON-only and must not carry `assetTransferMethod`. Since x402 SDK 1.0.1 (current release 1.2.0) the relayer cost is estimated client-side, so catalog routes must **not** publish the legacy `fee` or `feeConfig` fields. +On TRON you can add an `exact_gasfree` route alongside the `exact` one for the same endpoint: a relayer pays the network energy and deducts its fee from the payment token, so the payer needs no TRX. GasFree routes are TRON-only and must not carry `assetTransferMethod`. Since x402 SDK 1.0.1 the relayer cost is estimated client-side, so catalog routes must **not** publish the legacy `fee` or `feeConfig` fields. ::: For example, an endpoint may expose one route per supported chain — TRON Mainnet, BSC Mainnet, and Base Mainnet — each with its own `provider` and `scheme`. To call one, point `wallet-cli x402 pay` at the chosen route's `url` and pass the matching `--network` / `--scheme`: @@ -88,7 +88,7 @@ The other routes reuse the same request body, swapping only the route `url`, `-- ### status block -`status` is optional and describes the state of each stage of the service, with four keys: `catalog` / `gateway` / `payment` / `upstream`. When omitted, the build output (service detail) fills in defaults automatically: +`status` is optional and describes the state of each stage of the service, with four keys: `catalog` / `gateway` / `payment` / `upstream`. When present, all four keys are required. When omitted, the build output (service detail) fills in defaults automatically: ```json { "catalog": "listed", "gateway": "unknown", "payment": "unknown", "upstream": "unknown" } @@ -105,7 +105,7 @@ Allowed values: ## pay.md -Submitted alongside `catalog.json` in the same directory — a human- and Agent-readable call guide, and a **required** file. Recommended contents: basic service info (FQN, entry address, category, settlement chains), each endpoint's address and price, plus copy-paste call examples. The catalog's CI tests currently require a `wallet-cli x402 pay` example with `--network tron:728126428` and `--scheme exact`, a mention of `exact_gasfree`, and Base Mainnet (`eip155:8453`) coverage. Like `catalog.json`, this file goes through the sensitive-data scan (see below). +Submitted alongside `catalog.json` in the same directory — a human- and Agent-readable call guide, and a **required** file. Recommended contents: basic service info (FQN, entry address, category, settlement chains), each endpoint's address and price, plus copy-paste call examples. The catalog's CI tests currently require a `wallet-cli x402 pay` example with `--network tron:728126428` and `--scheme exact`, a mention of `exact_gasfree`, and Base Mainnet coverage (the strings `Base Mainnet`, `eip155:8453`, `-base`, `USDC`, and `EIP-3009`, with no `Sepolia` or `eip155:84532`). Like `catalog.json`, this file goes through the sensitive-data scan (see below). ## Allowed categories @@ -122,6 +122,10 @@ security shopping storage translation `chains` uses CAIP-2 style chain identifiers. Mainnets and testnets are both recognized: +:::note TRON ID format +The catalog schema accepts TRON chains only in the hexadecimal form below. The x402 SDK (since 2.0.0) and Wallet CLI use the decimal CAIP-2 IDs — `tron:728126428` (mainnet), `tron:3448148188` (Nile), `tron:2494104990` (Shasta). The SDK still accepts the hexadecimal values as deprecated aliases of the same chains; Wallet CLI's global `--network` (used by `x402 pay` and account commands) does not — use the decimal ID or an alias such as `tron`, `nile` or `shasta`; only the catalog filter `x402 provider-list --network` also accepts the hex form. That is why the CLI examples pass `--network tron:728126428` while `catalog.json` lists `tron:0x2b6653dc`. +::: + | Chain | ID | |---|---| | TRON mainnet | `tron:0x2b6653dc` | @@ -214,6 +218,8 @@ These are additive — the raw `title`, `subtitle`, `category`, `chains`, and `i ## Local build and run +Requires Python 3.11 or newer. + ```bash # install the validation dependency (jsonschema) pip install -r requirements.txt diff --git a/docs/x402/core-concepts/OfficialFacilitator.md b/docs/x402/core-concepts/OfficialFacilitator.md index 76058d44..c6f736ac 100644 --- a/docs/x402/core-concepts/OfficialFacilitator.md +++ b/docs/x402/core-concepts/OfficialFacilitator.md @@ -56,11 +56,13 @@ Official Facilitator supports **two calling modes**. | Mode | Rate Limit | Description | |-----|-----|-----| -| **Anonymous Mode** | Official service: 1 request per IP per minute. Self-hosted deployments default to 10 requests per IP per minute when `rate_limit.anonymous` is omitted (configurable). | No API Key required, suitable for local development and functional testing | -| **API Key Mode** | Official service: 1000 requests per API Key per minute. Self-hosted deployments use the same default when `rate_limit.authenticated` is omitted (configurable). | API Key required, suitable for production environments and high-frequency payment requests | +| **Anonymous Mode** | Official service: 10 requests per IP per minute, counted separately for `/verify` and `/settle`. This is also the self-hosted default when `rate_limit.anonymous` is omitted (configurable). | No API Key required, suitable for local development and functional testing | +| **API Key Mode** | Official service: 1000 requests per API Key per minute, counted separately for `/verify` and `/settle`. Self-hosted deployments use the same default when `rate_limit.authenticated` is omitted (configurable). | API Key required, suitable for production environments and high-frequency payment requests | The calling methods for both modes are exactly the same, but they differ in **identity recognition and interface rate limiting strategies**. +> **Counters are per instance.** The official production config uses `rate_limit.store: memory`, so each facilitator instance keeps its own counters; requests that land on different instances are not counted against one shared total. Self-hosted deployments default to the same in-memory store — set `rate_limit.store: redis` (with `redis_url`) to share counters across replicas. + --- ### Anonymous Calling Mode @@ -69,8 +71,8 @@ If the request **does not carry an API Key**, the Facilitator will treat the req In anonymous mode: -- The `/settle` interface is **rate-limited** -- The **official service allows 1 request per IP per minute**. Self-hosted deployments default to **10 requests per IP per minute** when `rate_limit.anonymous` is omitted; this limit is configurable. +- The `/verify` and `/settle` interfaces are **rate-limited**, each with its own counter +- The **official service allows 10 requests per IP per minute** on each of them — the same as the self-hosted default when `rate_limit.anonymous` is omitted; this limit is configurable. This mode is mainly used for: @@ -87,7 +89,7 @@ curl -X POST https://facilitator.bankofai.io/settle \ -d '{ ... }' ``` -Although anonymous mode can call all core interfaces normally, due to the very low call frequency of `/settle`, it is **not suitable for production environments**. +Although anonymous mode can call all core interfaces normally, due to the low per-IP limit on `/verify` and `/settle`, it is **not suitable for production environments**. If your application needs to handle real user payments or higher frequency requests, it is recommended to use **API Key calling mode**. @@ -112,7 +114,7 @@ curl -X POST https://facilitator.bankofai.io/settle \ When the Facilitator recognizes the API Key: -- On the official service, the `/settle` limit increases to **1000 requests per API Key per minute** +- On the official service, the `/verify` and `/settle` limits each increase to **1000 requests per API Key per minute** This means your service can support **production-level payment throughput**. @@ -246,23 +248,31 @@ After clicking **"Confirm"**, you will return to the Dashboard page, and the API |------|------|------| | GET | `/health` | Service health check | | GET | `/supported` | Query supported payment capabilities and configurations | -| POST | `/verify` | Verify payment payload validity | +| POST | `/verify` | Verify payment payload validity (**rate-limited**) | | POST | `/settle` | Perform on-chain settlement (**rate-limited**)| | GET | `/payments/tx/{tx_hash}` | Query payment records by settlement transaction hash | | GET | `/payments?network=&nonce=[&asset=&payer=]` | Query payment records by the on-chain authorization identity | | GET | `/payments` | Authenticated seller's settlement feed (`?limit=&offset=`; `limit` defaults to `50` and is capped at `200` — a larger value is silently reduced to `200`, not rejected; `offset` defaults to `0`) | +| GET | `/sponsoring/ready` | TRON approval resource sponsoring readiness (`?network=` checks one network); HTTP `200` when ready, `503` otherwise (booting, recovering, degraded, or sponsoring disabled) | -> There is **no** `/fee/quote` endpoint, and the schemes carry no facilitator fee. Rate limiting only applies to the `/settle` interface; other interfaces are not affected by rate limiting. +> There is **no** `/fee/quote` endpoint, and the schemes carry no facilitator fee. Rate limiting applies to `/verify` and `/settle` (separate counters); other interfaces are not rate-limited. A request over the limit receives HTTP `429` with `{"error":"rate_limit_exceeded"}` and a `Retry-After` header. ### Networks and schemes the official service settles | Network | Environment | |---|---| -| `tron:0x2b6653dc` (TRON Mainnet) · `tron:0xcd8690dc` (Nile) | mainnet · testnet | +| `tron:728126428` (TRON Mainnet) · `tron:3448148188` (Nile) | mainnet · testnet | | `eip155:56` (BSC) · `eip155:97` (BSC testnet) | mainnet · testnet | | `eip155:8453` (Base) · `eip155:84532` (Base Sepolia) | mainnet · testnet | -Each of these networks registers `exact`, `upto`, and `batch-settlement`; TRON additionally registers `exact_gasfree` where the service holds GasFree relayer credentials (TRON Mainnet and Nile). Query `/supported` for the authoritative list of the deployment you are pointing at. The official facilitator does not currently enable the `trc20ApprovalResourceSponsoring` extension — TRON approval resource sponsoring requires a self-hosted facilitator. On its EVM networks (BSC and Base) it does register the ERC-20 approval gas-sponsoring extension for every EVM network it serves — but sponsoring only kicks in when the resource server declares that extension on the route. +Each of these networks registers `exact`, `upto`, and `batch-settlement`; TRON additionally registers `exact_gasfree` where the service holds GasFree relayer credentials (TRON Mainnet and Nile). Query `/supported` for the authoritative list of the deployment you are pointing at. TRON networks are reported with decimal CAIP-2 identifiers; the older hex forms (`tron:0x2b6653dc`, `tron:0xcd8690dc`) are still accepted as input aliases. + +`/supported` lists two extensions: + +- `erc20ApprovalGasSponsoring` — registered for every EVM network the service serves (BSC and Base). +- `trc20ApprovalResourceSponsoring` — TRON approval resource sponsoring is enabled **on Nile only**, for the configured asset (Nile USDT), and **requires an API Key**. An anonymous request that carries the extension is rejected with `sponsor_auth_required`; an authenticated request for TRON Mainnet is rejected with `sponsor_network_disabled`. `GET /sponsoring/ready` reports whether the sponsoring runtime is ready. + +Either sponsorship only kicks in when the resource server declares the extension on the route. ### Payment Record Query @@ -282,7 +292,7 @@ The `/payments/tx/{tx_hash}` and `/payments?network=&nonce=[&asset=&payer=]` int > When an API Key is provided, these interfaces only return payment records associated with your account; you will not see data from other sellers. :::danger Without an API Key -The `tx_hash` and `network` + `nonce` lookups add **no seller filter** when the request is anonymous, so the response may include records bound to a seller — anyone holding an exact identifier can resolve the corresponding record. The `/payments` list endpoint still requires authentication, so there is no unauthenticated listing endpoint; but these lookups are not rate-limited either (the official service's 1-request-per-IP-per-minute anonymous limit covers `/settle` only), and settlement tx hashes are public on-chain data. Treat settlement metadata as effectively public rather than seller-private. +The `tx_hash` and `network` + `nonce` lookups add **no seller filter** when the request is anonymous, so the response may include records bound to a seller — anyone holding an exact identifier can resolve the corresponding record. The `/payments` list endpoint still requires authentication, so there is no unauthenticated listing endpoint; but these lookups are not rate-limited either (the official service's 10-requests-per-IP-per-minute anonymous limit covers `/verify` and `/settle` only), and settlement tx hashes are public on-chain data. Treat settlement metadata as effectively public rather than seller-private. **This describes the current implementation, not a recommended access-control policy.** Send your API Key to keep queries scoped to your own account, and never treat a settlement tx hash or its nonce as a secret. ::: @@ -293,7 +303,7 @@ The `tx_hash` and `network` + `nonce` lookups add **no seller filter** when the **Q: Can it run normally without configuring an API Key?** -Yes, it can run, but the official service limits `/settle` to 1 request per IP per minute. A self-hosted deployment defaults to 10 requests per IP per minute when `rate_limit.anonymous` is omitted, and that limit is configurable. Anonymous access is only suitable for testing; any real traffic must be configured with an API Key. +Yes, it can run, but the official service limits `/verify` and `/settle` to 10 requests per IP per minute each — the same as the self-hosted default when `rate_limit.anonymous` is omitted, which is configurable. Anonymous access is only suitable for testing; any real traffic must be configured with an API Key. **Q: Does the API Key expire?** @@ -301,7 +311,7 @@ Currently, API Keys do not actively expire, but if you actively delete and recre **Q: Can I use the same API Key for multiple projects?** -Yes, the same API Key can be reused across multiple service instances. On the official service, those instances share that Key's limit of 1000 `/settle` requests per minute; the quota does not reset for each server using the Key. +Yes, the same API Key can be reused across multiple service instances. On the official service the limit is keyed by API Key, not by calling server: your instances draw on the same 1000 `/settle` requests per minute (and a separate 1000 for `/verify`) rather than each getting its own quota. Those counters are kept per facilitator instance (`rate_limit.store: memory`), so the limit applies within each facilitator instance, not as one global total. **Q: I want to change my API Key, how do I do it?** diff --git a/docs/x402/core-concepts/client-server.md b/docs/x402/core-concepts/client-server.md index 6f8dab46..7b561731 100644 --- a/docs/x402/core-concepts/client-server.md +++ b/docs/x402/core-concepts/client-server.md @@ -25,7 +25,7 @@ Clients can take many forms, including: - **Initiate Requests**: Send the initial HTTP request to the resource server. - **Handle Payment Requirements**: Parse the `402 Payment Required` response and extract payment details. -- **Manage Token Approvals**: Authorize Permit2 (one-time `approve(Permit2)`) for plain ERC-20/TRC-20 tokens; ERC-3009 tokens need no approve. Who broadcasts it differs by chain. **On TRON** the client auto-broadcasts the approve on first payment, paying the Energy itself — unless the server advertises the `trc20ApprovalResourceSponsoring` extension (SDK 1.2.0+), in which case the client signs it **without broadcasting** and the facilitator sponsors the Energy/Bandwidth and broadcasts it. **On EVM the client never broadcasts anything**: it either attaches a signed, unbroadcast approve for the facilitator to relay (when the server advertises `eip2612GasSponsoring` or `erc20ApprovalGasSponsoring`), or, with no such extension declared, verification fails with `permit2_allowance_required` and the allowance must be granted once out of band before the first payment. See [SDK Feature Matrix](../sdk-features.md#extensions). +- **Manage Token Approvals**: Authorize Permit2 (one-time `approve(Permit2)`) for plain ERC-20/TRC-20 tokens; ERC-3009 tokens need no approve. Who broadcasts it differs by chain. **On TRON** the client auto-broadcasts the approve on first payment, paying the Energy itself (with the default `allowanceMode: "auto"`; `"skip"` leaves the approval to your app) — unless the server advertises the `trc20ApprovalResourceSponsoring` extension, in which case the client signs it **without broadcasting** and the facilitator sponsors the Energy/Bandwidth and broadcasts it. Since 2.1.0 this needs the client extension from `@bankofai/x402-tron-extensions` registered with `client.registerExtension(createTrc20ApprovalResourceSponsoringClientExtension(signer))`; without it, a sponsored payment fails with `trc20_approval_client_extension_not_registered` instead of falling back to a client broadcast. **On EVM the client never broadcasts anything**: it either attaches an off-chain EIP-2612 permit signature (when the server advertises `eip2612GasSponsoring`) or a signed, unbroadcast approve transaction for the facilitator to relay (`erc20ApprovalGasSponsoring`), or, with no such extension declared, verification fails with `permit2_allowance_required` and the allowance must be granted once out of band before the first payment. See [SDK Feature Matrix](../sdk-features.md#extensions). - **Prepare Payment Payload**: Construct and sign a payment payload according to server requirements. - **Retry with Payment**: Attach the `PAYMENT-SIGNATURE` header and resend the request. @@ -45,7 +45,7 @@ Servers may include: ### Core Responsibilities -- **Define Payment Requirements**: Respond with HTTP `402 Payment Required` when a request lacks valid payment credentials, detailing payment requirements in the response body. +- **Define Payment Requirements**: Respond with HTTP `402 Payment Required` when a request lacks valid payment credentials, detailing payment requirements in the Base64-encoded `PAYMENT-REQUIRED` response header (the body is `{}` by default). - **Validate Payment Payload**: Call the Facilitator service to verify the incoming signed payload. - **Settle Transactions**: Upon successful validation, submit the transaction via the Facilitator to complete on-chain settlement. - **Deliver Resources**: After confirming payment, return the requested resource to the client. @@ -72,6 +72,8 @@ In the x402 protocol, a typical interaction between client and server proceeds a }} /> +The diagram shows the order the client observes: the resource arrives after settlement. Under the default `authorization` flow the server runs its handler before settling and releases the response only once settlement succeeds (step 5 above). + --- ## Summary diff --git a/docs/x402/core-concepts/facilitator.md b/docs/x402/core-concepts/facilitator.md index 66e7d7b3..7730e534 100644 --- a/docs/x402/core-concepts/facilitator.md +++ b/docs/x402/core-concepts/facilitator.md @@ -19,7 +19,7 @@ By introducing a Facilitator, servers no longer need to maintain direct connecti - **Payment Verification**: Ensures that the signed payload strictly complies with the server's declared payment requirements. - **Payment Settlement**: Submits validated transactions to the blockchain and monitors their confirmation status. -- **Settlement Records**: Persists one row per settle attempt — the store applies no de-duplication and holds no unique constraint, so failures and retries accumulate. At most one *successful* row exists per authorization identity in practice, because on-chain replay protection lets a given authorization settle only once. It also answers record queries, seller-scoped when the caller authenticates. A save failure is logged but never changes the `/settle` response. +- **Settlement Records**: Persists one row for each settle attempt that reaches a result from the settle mechanism — success or failure — so failed attempts and retries accumulate. Requests rejected before or around settlement get no row: malformed bodies (400), sponsoring-access rejections (403/503), Permit2 replay-guard errors, and internal errors (500). A partial unique index on (`network`, `asset`, `payer`, `nonce`) where `status = 'success'` allows at most one *successful* row per authorization, complementing on-chain replay protection, which lets a given authorization settle only once. It also answers record queries, seller-scoped when the caller authenticates. A save failure is logged but never changes the `/settle` response. - **Result Feedback**: Returns verification and settlement results to the server, enabling it to decide whether to deliver the requested resource. > **Note**: The Facilitator **does not custody funds** and does not act as an escrow. It only executes verification and on-chain operations according to the client's signed authorization. @@ -31,7 +31,7 @@ Integrating a Facilitator provides significant advantages: - **Reduced Operational Overhead**: Servers do not need to directly manage blockchain nodes or RPC infrastructure. - **Protocol Standardization**: Ensures consistent payment verification and settlement processes across services. - **Fast Integration**: Servers can begin accepting payments with minimal blockchain development effort. -- **Resource Fee Management**: The Facilitator covers transaction execution costs such as TRX (Energy and Bandwidth) / BNB, reducing the operational burden on the server. Since SDK 1.2.0 a TRON Facilitator may additionally opt into the `trc20ApprovalResourceSponsoring` extension, temporarily delegating its own Stake 2.0 Energy — and, when needed, Bandwidth — to the payer so the payer's first `approve(Permit2)` costs them no TRX. This is opt-in: the Facilitator must register the sponsoring runtime together with a bounded sponsorship policy and a durable operation coordinator. Either way the resource server must also declare the extension on the route — that declaration is what makes an SDK client attach the sponsoring payload (the Facilitator itself does not check it, so a non-SDK client could skip that step). EVM networks have an equivalent capability — sponsoring the payer's ERC-20 `approve` gas — but the SDK does not wire it up for you: a self-hosted Facilitator must register the extension itself. The official Facilitator registers it for the EVM networks it serves; see [Official Facilitator](./OfficialFacilitator.md). +- **Resource Fee Management**: The Facilitator covers transaction execution costs such as TRX (Energy and Bandwidth) / BNB, reducing the operational burden on the server. Since SDK 1.2.0 a TRON Facilitator may additionally opt into the `trc20ApprovalResourceSponsoring` extension, temporarily delegating its own Stake 2.0 Energy — and, when needed, Bandwidth — to the payer so the payer's first `approve(Permit2)` costs them no TRX. This is opt-in: the Facilitator must register the sponsoring runtime together with a bounded sponsorship policy and a durable operation coordinator. Either way the resource server must also declare the extension on the route — that declaration is what makes an SDK client attach the sponsoring payload (the Facilitator itself does not check it, so a non-SDK client could skip that step). EVM networks have an equivalent capability — sponsoring the payer's ERC-20 `approve` gas — but the SDK does not wire it up for you: a self-hosted Facilitator must register the extension itself. The official Facilitator registers it for the EVM networks it serves, and enables TRON approval resource sponsoring on Nile for API Key holders; see [Official Facilitator](./OfficialFacilitator.md). Although developers may implement verification and settlement logic locally, using a Facilitator significantly accelerates development and ensures protocol-compliant implementation. @@ -74,7 +74,7 @@ Quick usage examples can be found in [OfficialFacilitator](./OfficialFacilitator If you need full control over the settlement wallet, RPC endpoints, energy management, or which networks and schemes are registered — or you have specific privacy or compliance requirements — you can deploy your own Facilitator service. > ⚠️ **Self-hosting security notes:** -> - A self-hosted Facilitator needs a **dedicated funded wallet** to pay blockchain transaction fees. It is resolved through `@bankofai/agent-wallet` and unlocked out-of-band (for example `AGENT_WALLET_PASSWORD`) — the raw private key never enters the service process +> - A self-hosted Facilitator needs a **dedicated funded wallet** to pay blockchain transaction fees. It is resolved through `@bankofai/agent-wallet` v3: with the `privy` or `wallet_cli` provider the key stays outside the service process; the `raw_secret` provider keeps a plaintext key in its config and is for development only > - **This Facilitator wallet should be separate from your payment recipient wallet** — create a new wallet specifically for this purpose > - Only deposit a small amount of tokens into the Facilitator wallet (enough for fees); do not store large amounts > - Never place a raw private key in `.env`, a config file, or a shell command — **and never upload wallet material to GitHub or share it with anyone** @@ -91,30 +91,35 @@ Whether using the official service or a self-hosted instance, the Facilitator pr |--------|------|-------------| | GET | `/health` | Liveness check | | GET | `/supported` | Supported payment capabilities and configuration | -| POST | `/verify` | Verify payment payload validity | +| POST | `/verify` | Verify payment payload validity (**rate-limited**, see below) | | POST | `/settle` | Execute on-chain settlement (**rate-limited**, see below); persists a settlement record | | GET | `/payments/tx/{tx_hash}` | Query payment records by settlement transaction hash (seller-scoped when authenticated) | | GET | `/payments?network=&nonce=[&asset=&payer=]` | Query payment records by the on-chain authorization identity (seller-scoped when authenticated) | | GET | `/payments` | Authenticated seller's settlement feed (`?limit=&offset=`; `limit` defaults to `50` and is capped at `200` — a larger value is silently reduced to `200`, not rejected; `offset` defaults to `0`) | +| GET | `/sponsoring/ready` | TRON approval resource sponsoring readiness (`?network=` checks one network); HTTP `200` when ready, `503` otherwise (booting, recovering, degraded, or sponsoring disabled) | | GET | `/metrics` | Prometheus metrics (operational; exposed on the main port only when monitoring shares it) | | ALL | `/mainnet/*` · `/nile/*` | GasFree Open API transparent proxy (HMAC-signed) — used internally by the TRON `exact_gasfree` scheme | Record-query failures use these codes: `404 not_found` when no record matches, `400 invalid_identity_query` for a partial identity query (any of `network`/`nonce`/`asset`/`payer` without the required `network`+`nonce` pair), and `400 missing_identity_or_auth` when `/payments` is called with neither identity parameters nor an API Key. +`/verify` and `/settle` keep the x402 response shape (`invalidReason` / `errorReason`). Besides the SDK's own reasons, the service returns: `400 invalid_json` or `missing_parameters` for a malformed body; `413` `{"code":"body_too_large","message":…}` (default limit 1 MiB); `429` `{"error":"rate_limit_exceeded"}`; `403 sponsor_auth_required`, `sponsor_network_disabled` or `sponsor_pay_to_invalid` when a request carries `trc20ApprovalResourceSponsoring` that the deployment will not sponsor; and `503` with `Retry-After` for transient conditions (`sponsor_owner_busy`, `sponsor_recovery_in_progress`, `sponsor_storage_unavailable`, and on `/settle` only `permit2_authorization_busy`, `permit2_storage_unavailable`, `permit2_nonce_check_unavailable`). On `/settle`, a Permit2 authorization whose nonce is already consumed fails with `permit2_nonce_consumed` (HTTP 200) without broadcasting a new transaction; a malformed one fails `/settle` with `400 permit2_invalid_authorization`. Sponsored approvals can also fail at the protocol level (HTTP 200, in `invalidReason` / `errorReason`): `approval_transaction_reused` (the signed approve was already used for a different payment request), `sponsor_approval_lifetime_exceeded` (the signed approve is valid for longer than 630 seconds) and, on `/settle` only, `sponsor_existing_delegation`. An unexpected failure returns `500 internal_error`. The GasFree proxy is served only under `/mainnet` and `/nile` (any other path gets a plain `404`), and answers `502 bad_gateway` when the upstream fails or its response is too large. + > There is **no** `/fee/quote` endpoint, and the schemes carry no facilitator fee at all. Payment records are keyed on the on-chain authorization identity (`network` + `scheme` + `asset` + `payer` + `nonce`), not a client-supplied payment ID. --- ## Rate Limiting -The `/settle` endpoint enforces dynamic rate limits based on the caller's authentication status: +The `/verify` and `/settle` endpoints enforce dynamic rate limits based on the caller's authentication status, with a separate counter for each endpoint: | Mode | Rate Limit | How to Authenticate | |------|------------|---------------------| -| **Authenticated** | Official service: 1000 requests per API Key per minute. Self-hosted deployments use the same default when `rate_limit.authenticated` is omitted (configurable). | Include `X-API-KEY: ` header | -| **Anonymous** | Official service: 1 request per IP per minute. Self-hosted deployments default to 10 requests per IP per minute when `rate_limit.anonymous` is omitted (configurable). | No API Key provided | +| **Authenticated** | Official service: 1000 requests per API Key per minute, counted separately for `/verify` and `/settle`. Self-hosted deployments use the same default when `rate_limit.authenticated` is omitted (configurable). | Include `X-API-KEY: ` header | +| **Anonymous** | Official service: 10 requests per IP per minute, counted separately for `/verify` and `/settle`. This is also the self-hosted default when `rate_limit.anonymous` is omitted (configurable). | No API Key provided | + +Other endpoints (`/supported`, `/payments/*`, `/sponsoring/ready`, `/health`) are not rate-limited. Over the limit, the response is HTTP `429` `{"error":"rate_limit_exceeded"}` with a `Retry-After` header. -Other endpoints (`/verify`, `/supported`, `/payments/*`) are not individually rate-limited. +> **Counters are per instance.** The official production config uses `rate_limit.store: memory`, so each facilitator instance keeps its own counters; requests that land on different instances are not counted against one shared total. Self-hosted deployments default to the same in-memory store — set `rate_limit.store: redis` (with `redis_url`) to share counters across replicas. > **Tip**: For any production workload, apply for an API Key via the [Admin Portal](https://admin-facilitator.bankofai.io) to unlock the higher rate limit. @@ -132,7 +137,7 @@ How access currently behaves: - **With a valid `X-API-KEY`** — results are filtered to the seller that key belongs to. - **Anonymous `tx_hash` or `network` + `nonce` lookup** — the current implementation adds **no seller filter**, so the response may include records that are bound to a seller. - **The `/payments` list endpoint** — still requires authentication: with no identity parameters and no API Key it returns `400`, and a partial identity query returns `400` rather than degrading into a feed. -- **No rate limit on these lookups** — the official service's 1-request-per-IP-per-minute anonymous limit applies to `/settle` only; the record-query endpoints are not individually rate-limited. +- **No rate limit on these lookups** — the official service's anonymous limit applies to `/verify` and `/settle` only; the record-query endpoints are not individually rate-limited. Settlement tx hashes are public on-chain data, and the `network` + `nonce` lookup additionally resolves **failed** settlements — including pre-broadcast failures, which carry no tx hash at all and so cannot be reached any other way. The practical consequence is that **settlement metadata should be treated as effectively public**, even though no unauthenticated listing endpoint exists. The response body never includes the seller id, so what a lookup exposes is the payment metadata of a seller-bound record, not seller attribution. diff --git a/docs/x402/core-concepts/gateway.md b/docs/x402/core-concepts/gateway.md index 6e5fdc83..58105b61 100644 --- a/docs/x402/core-concepts/gateway.md +++ b/docs/x402/core-concepts/gateway.md @@ -74,7 +74,7 @@ Providers turn calls into cash flow. Agents turn calls into capabilities. The ga ### For AI Agents: one catalog, many APIs, pay as you go -- **CLI discovery today** — `wallet-cli x402 provider-list` / `provider-show` / `endpoint-list` find the right API and its routes. Paying over MCP is supported via `@bankofai/x402-mcp`; catalog-aware MCP discovery is not shipped yet. +- **CLI discovery today** — `wallet-cli x402 provider-list` / `provider-show` / `endpoint-list` find the right API and its routes. Paying over MCP is supported via `@x402/mcp`; catalog-aware MCP discovery is not shipped yet. - **Per-call pricing** — no subscriptions, no minimums. - **Live price transparency** — the gateway returns the computed price in its `402` response, and the client's authorization binds the selected payment requirement. The quote itself is not a gateway cryptographic signature. - **No accounts, no keys** — your wallet is your identity; nothing to register or manage. diff --git a/docs/x402/core-concepts/http-402.md b/docs/x402/core-concepts/http-402.md index 8666d91f..83bbb491 100644 --- a/docs/x402/core-concepts/http-402.md +++ b/docs/x402/core-concepts/http-402.md @@ -49,13 +49,13 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- "error": "Payment required", "resource": { "url": "http://example.com/protected", - "description": null, - "mimeType": null + "description": "", + "mimeType": "" }, "accepts": [ { "scheme": "exact", - "network": "tron:0xcd8690dc", + "network": "tron:3448148188", "amount": "100", "asset": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", "payTo": "", @@ -79,8 +79,8 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- "error": "Payment required", "resource": { "url": "http://example.com/protected", - "description": null, - "mimeType": null + "description": "", + "mimeType": "" }, "accepts": [ { @@ -124,12 +124,12 @@ When the server returns a `402 Payment Required` response, the decoded `PAYMENT- | `resource` | Information about the requested resource | | `accepts` | Array of accepted payment options | | `scheme` | Payment scheme (`exact`, `upto`, `batch-settlement`, or `exact_gasfree`) | -| `network` | Network identifier — the three TRON IDs (`tron:0x2b6653dc`, `tron:0xcd8690dc`, `tron:0x94a9059e`) or any `eip155:`: a resource server registers `eip155:*` by default, so this field is not limited to `eip155:56` / `97` / `8453` / `84532`. Settlement is bounded separately by the networks the facilitator has configured | +| `network` | Network identifier — the three TRON IDs (`tron:728126428`, `tron:3448148188`, `tron:2494104990`) or any `eip155:`: a resource server registers `eip155:*` by default, so this field is not limited to `eip155:56` / `97` / `8453` / `84532`. Settlement is bounded separately by the networks the facilitator has configured | | `amount` | Payment amount in the smallest unit (e.g., 100 = 0.0001 USDT) | | `asset` | TRC-20/BEP-20 token contract address | | `payTo` | Seller's wallet address | | `maxTimeoutSeconds` | Maximum validity duration of the payment | -| `extra` | Scheme-specific data — `assetTransferMethod` (`eip3009` / `permit2`), the token `name`/`version` for EIP-3009 assets and for permit2 assets that also support EIP-2612, and, for a scheme that declares a non-default payment flow, `paymentFlow` (`upfront` or `escrow`) — every built-in scheme uses the default `authorization` flow, which is omitted from `extra`. It carries no fee object: the schemes take no facilitator fee. | +| `extra` | Scheme-specific data — `assetTransferMethod` (`eip3009` / `permit2`), the token `name`/`version` for EIP-3009 assets and for permit2 assets that also support EIP-2612, and, when a route selects a non-default payment flow, `paymentFlow` (`upfront` or `escrow`) — the default `authorization` flow is omitted from `extra`. TRON schemes and EVM `upto` / `batch-settlement` support only `authorization`; EVM `exact` also supports `upfront`. It carries no fee object: the schemes take no facilitator fee. | | `extensions` | Additional context for the payment scheme (e.g., EVM gas-sponsoring, TRON `trc20ApprovalResourceSponsoring`, payment-identifier) | ## Payment Signature Structure @@ -144,7 +144,7 @@ The client responds via the `PAYMENT-SIGNATURE` header with a signed payload: "x402Version": 2, "accepted": { "scheme": "exact", - "network": "tron:0xcd8690dc", + "network": "tron:3448148188", "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 ee2fa15b..e965658d 100644 --- a/docs/x402/core-concepts/network-and-token-support.md +++ b/docs/x402/core-concepts/network-and-token-support.md @@ -7,8 +7,8 @@ import TabItem from '@theme/TabItem'; ## TRON Network Identifiers -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. +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 identifier strings. ### Identifier Reference @@ -18,7 +18,7 @@ Use the exported constants from `@bankofai/x402-tron` (`TRON_MAINNET`, `TRON_NIL | **TRON Shasta** | `tron:2494104990` | `TRON_SHASTA` | TRON Shasta Testnet | | **TRON Nile** | `tron:3448148188` | `TRON_NILE` | TRON Nile Testnet | -> **TRON ID format**: since `@bankofai/x402-tron` 2.0.0 the SDK constants use decimal CAIP-2 references. The older hexadecimal forms (`tron:0x2b6653dc`, `tron:0xcd8690dc`, `tron:0x94a9059e`) are still accepted as input aliases, and are what the official facilitator and the API catalog currently report. +> **TRON ID format**: since `@bankofai/x402-tron` 2.0.0 the SDK constants use decimal CAIP-2 references. The older hexadecimal forms (`tron:0x2b6653dc`, `tron:0xcd8690dc`, `tron:0x94a9059e`) are still accepted as input aliases and are normalized to the decimal form. The official facilitator reports the decimal identifiers in `/supported`; the API Catalog still lists the hexadecimal forms. --- @@ -31,7 +31,7 @@ In the x402 protocol (on-the-wire), BSC uses the EIP-155 chain ID format: | **BSC Mainnet** | `eip155:56` | BSC Mainnet (Production) | | **BSC Testnet** | `eip155:97` | BSC Testnet (Chapel) | -> **Note**: A self-hosted Facilitator's YAML config takes **canonical CAIP-2 identifiers only** — `eip155:56`, `eip155:97`, `eip155:8453`, `eip155:84532`, `tron:0x2b6653dc`, `tron:0xcd8690dc`, `tron:0x94a9059e`. Friendly aliases such as `bsc:mainnet` or `tron:nile` are not resolved and are rejected at startup. +> **Note**: A self-hosted Facilitator's YAML config takes **canonical CAIP-2 identifiers only** — `eip155:56`, `eip155:97`, `eip155:8453`, `eip155:84532`, `tron:728126428`, `tron:3448148188`, `tron:2494104990`. Deprecated hexadecimal TRON IDs (`tron:0x…`) are still accepted and normalized to decimal. Friendly aliases such as `bsc:mainnet` or `tron:nile` are not resolved and are rejected at startup. --- @@ -81,18 +81,17 @@ x402 supports **TRC-20, BEP-20, and ERC-20** tokens. TRON/BSC routes use their c | **USDD** | `tron:728126428` | `TXDk8mbtRbXeYuMNS83CfKPaYYT8XWv9Hz` | | **USDD** | `tron:3448148188` | `TGjgvdTWWrybVLaVeFqSyVqJQWjxqRYbaK` | | **USDT** | `eip155:56` | `0x55d398326f99059fF775485246999027B3197955` | -| **USDC** | `eip155:56` | `0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d` | +| **USDC** | `eip155:56` | `0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d` (not in any shipped token registry — explicit asset only) | | **USDT** | `eip155:97` | `0x337610d27c682E347C9cD60BD4b3b107C9d34dDd` | | **USDC** | `eip155:97` | `0x64544969ed7EBf5f083679233325356EbE738930` | -| **DHLU** | `eip155:97` | `0x375cADdd2cB68cE82e3D9B075D551067a7b4B816` | | **USDC** | `eip155:8453` | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` | | **USDC** | `eip155:84532` | `0x036CbD53842c5426634e7929541eC2318f3dCF7e` | -> **Default assets vs. opt-in assets (SDK 1.1.0+)**: the default-asset registry resolves **USDT** on TRON (`tron:728126428`, `tron:3448148188`, `tron:2494104990`) and BSC Mainnet (`eip155:56`), and **USDC** on BSC Testnet (`eip155:97`) and Base (`eip155:8453`, `eip155:84532`). The registry also ships defaults for twenty further EVM networks (MegaETH, Monad, Polygon, Arbitrum, Mezo, Radius, XDC, Celo, Flare and others) that this page does not table. Everything else in the table above — TRON USDD, BSC Mainnet USDC, BSC Testnet USDT, DHLU, and any custom token — is server-advertised only: with the 1.1.0 client spend controls on by default, a client refuses to pay it unless you allowlist it via `spendControls.allowedAssets`. For CLI asset selection, follow the [wallet-cli command reference](/wallet-cli/command-reference/). +> **Default assets vs. opt-in assets (SDK 1.1.0+)**: the default-asset registries resolve **USDT** on TRON (`tron:728126428`, `tron:3448148188`, `tron:2494104990`, from `@bankofai/x402-tron`) and **USDC** on Base (`eip155:8453`, `eip155:84532`, from the official `@x402/evm` 2.28.0). `@x402/evm` also ships defaults for further EVM networks (Ethereum, Polygon, Arbitrum, Avalanche, Celo, Sei, MegaETH, Monad, XDC, Flare and others) that this page does not table, but **none for BSC**: a BSC route must be priced with an explicit `{ asset, amount, extra }` object. Everything else in the table above — TRON USDD, every BSC asset, and any custom token — is server-advertised only: with the 1.1.0 client spend controls on by default, a client refuses to pay it unless you allowlist it via `spendControls.allowedAssets`. For CLI asset selection, follow the [wallet-cli command reference](/wallet-cli/command-reference/). -> **Extensibility**: The protocol is highly extensible. By registering tokens through the TRON token registry (`registerToken` from `@bankofai/x402-tron`) or the server's `EVM_TOKENS` config table, you can support any custom TRC-20 or BEP-20 token. +> **Extensibility**: The protocol is highly extensible. By registering tokens through the TRON token registry (`registerToken` from `@bankofai/x402-tron`) or an explicit `{ asset, amount, extra }` price on the server route, you can support any custom TRC-20 or BEP-20 token. -> **Token selection for the `exact` scheme**: EIP-3009 tokens (for example official Base USDC and BSC testnet DHLU) settle gaslessly via `transferWithAuthorization`. Plain ERC-20 tokens (for example BSC USDC/USDT and TRON USDT/USDD) settle via the Permit2 path — the client auto-broadcasts a one-time `approve(Permit2)` on first payment, or, on TRON when the server advertises `trc20ApprovalResourceSponsoring` (SDK 1.2.0+), signs it and lets the facilitator sponsor and broadcast it. You set the per-token method on the server under `accepts[].price.extra`; the SDK surfaces it on the wire as `accepts[].extra`: EIP-3009 → `{ name, version }`; plain ERC-20 → `{ assetTransferMethod: "permit2" }`. A permit2 asset that also implements EIP-2612 carries `{ name, version }` alongside `assetTransferMethod`; omitting that pair is precisely how a server tells clients to skip EIP-2612. Both sponsoring paths live inside the permit2 branch, so neither applies to an EIP-3009 asset. On a permit2 asset the client signs a gasless EIP-2612 permit when a `readContract` capability is available (from the signer or a configured RPC), the server advertises the `eip2612GasSponsoring` extension, `extra` carries both `name` and `version`, and the current Permit2 allowance does not already cover the payment. Note the asymmetry: a *missing* read capability skips the permit entirely, whereas a read that *throws* is caught and signing proceeds. Otherwise the client *tries* ERC-20 approval gas sponsoring, which needs `readContract`, the separate `erc20ApprovalGasSponsoring` extension from the server, a signer that can both sign raw transactions and report a transaction count, and again an allowance that does not already cover the payment; there the client signs an `approve` for `MaxUint256` — always the max, regardless of the payment amount — that the facilitator broadcasts. When neither path qualifies the payload carries no sponsoring extension at all. Among the shipped default assets the flag is set on MegaETH MegaUSD (mainnet) and on Mezo mUSD and Radius SBC (mainnet and testnet). +> **Token selection for the `exact` scheme**: EIP-3009 tokens (for example official Base USDC) settle gaslessly via `transferWithAuthorization`. Plain ERC-20 tokens (for example BSC USDC/USDT and TRON USDT/USDD) settle via the Permit2 path and need a one-time `approve(Permit2)` — on TRON the client auto-broadcasts it on first payment (on EVM it never does; see the sponsoring paths below), or, on TRON when the server advertises `trc20ApprovalResourceSponsoring` (SDK 1.2.0+), signs it and lets the facilitator sponsor and broadcast it (since 2.1.0 only with the client extension from `@bankofai/x402-tron-extensions` registered). You set the per-token method on the server under `accepts[].price.extra`; the SDK surfaces it on the wire as `accepts[].extra`: EIP-3009 → `{ name, version }`; plain ERC-20 → `{ assetTransferMethod: "permit2" }`. A permit2 asset that also implements EIP-2612 carries `{ name, version }` alongside `assetTransferMethod`; omitting that pair is precisely how a server tells clients to skip EIP-2612. Both sponsoring paths live inside the permit2 branch, so neither applies to an EIP-3009 asset. On a permit2 asset the client signs a gasless EIP-2612 permit when a `readContract` capability is available (from the signer or a configured RPC), the server advertises the `eip2612GasSponsoring` extension, `extra` carries both `name` and `version`, and the current Permit2 allowance does not already cover the payment. Note the asymmetry: a *missing* read capability skips the permit entirely, whereas a read that *throws* is caught and signing proceeds. Otherwise the client *tries* ERC-20 approval gas sponsoring, which needs `readContract`, the separate `erc20ApprovalGasSponsoring` extension from the server, a signer that can sign raw transactions, and a transaction count (from the signer or a configured RPC), and again an allowance that does not already cover the payment; there the client signs an `approve` for `MaxUint256` — always the max, regardless of the payment amount — that the facilitator broadcasts. When neither path qualifies the payload carries no sponsoring extension at all. Among the shipped default assets the `supportsEip2612` flag is set on MegaETH MegaUSD (mainnet) and on Mezo mUSD and Radius SBC (mainnet and testnet). --- @@ -136,8 +135,8 @@ x402 defines five named payment schemes. Four have complete client + server + fa The `exact` scheme pays the exact amount advertised. It covers two token transfer paths: -- **EIP-3009 `transferWithAuthorization`** — for tokens that natively support it (e.g. official Base USDC and BSC testnet DHLU). Gasless: no `approve` needed; the client signs a typed-data authorization and the facilitator calls `transferWithAuthorization` on-chain. -- **Permit2** — for plain ERC-20 / TRC-20 tokens that do not implement ERC-3009 (e.g. BSC USDC/USDT, TRON USDT/USDD). The client signs a Permit2 witness and the facilitator settles via the `x402ExactPermit2Proxy` contract. A one-time `approve(Permit2)` is required; the client auto-broadcasts it on first payment. On TRON, SDK 1.2.0 adds the `trc20ApprovalResourceSponsoring` extension — when the server advertises it, the client signs that approve without broadcasting it and the facilitator delegates the Energy/Bandwidth and broadcasts it, so the payer needs no TRX for the approve. +- **EIP-3009 `transferWithAuthorization`** — for tokens that natively support it (e.g. official Base USDC). Gasless: no `approve` needed; the client signs a typed-data authorization and the facilitator calls `transferWithAuthorization` on-chain. +- **Permit2** — for plain ERC-20 / TRC-20 tokens that do not implement ERC-3009 (e.g. BSC USDC/USDT, TRON USDT/USDD). The client signs a Permit2 witness and the facilitator settles via the `x402ExactPermit2Proxy` contract. A one-time `approve(Permit2)` is required; on TRON the client auto-broadcasts it on first payment, while on EVM it must already be in place or be relayed through a gas-sponsoring extension. On TRON, SDK 1.2.0 adds the `trc20ApprovalResourceSponsoring` extension — when the server advertises it, the client signs that approve without broadcasting it and the facilitator delegates the Energy/Bandwidth and broadcasts it, so the payer needs no TRX for the approve. Since 2.1.0 the client must register `createTrc20ApprovalResourceSponsoringClientExtension(signer)` from `@bankofai/x402-tron-extensions`; otherwise the payment fails with `trc20_approval_client_extension_not_registered`. The `exact` scheme conforms to the **v2 wire format** published by the **x402 Foundation**: a stock v2 client can pay a protected endpoint on this SDK's server directly, and this SDK's client can pay any v2-compliant server — no project-specific translation required. Transfer authorization data is carried in `payload.authorization` on the EIP-3009 path and in `payload.permit2Authorization` on the Permit2 path. @@ -151,7 +150,7 @@ A payment-channel scheme for high-frequency micro-payments (e.g. AI agent per-to ### `auth-capture` Scheme -An EVM client implementation for refundable Base Commerce Payments: authorize funds first, then capture, void, or refund them later. The published SDK currently exposes `@bankofai/x402-evm/auth-capture/client`; its server and facilitator implementations are not shipped yet, so it cannot currently be deployed end to end using only the published package. +An EVM client implementation for refundable Base Commerce Payments: authorize funds first, then capture, void, or refund them later. The official `@x402/evm` package (which the SDK uses for EVM since 2.1.0) currently exposes `@x402/evm/auth-capture/client`; its server and facilitator implementations are not shipped yet, so it cannot currently be deployed end to end using only the published package. ### `exact_gasfree` Scheme @@ -220,7 +219,7 @@ You may deploy your own Facilitator to gain full control over payment verificati | Core Component | TRON/BSC/Base Implementation | | :------------- | :---------------------- | -| **Networks** | The three TRON IDs (`tron:728126428`, `tron:2494104990`, `tron:3448148188`) plus any `eip155:` — client and resource server both default to `eip155:*`, and the SDK ships default assets for twenty EVM networks beyond `eip155:56` / `97` / `8453` / `84532`. What can actually settle is bounded by the networks the facilitator has configured, which it must enumerate explicitly | +| **Networks** | The three TRON IDs (`tron:728126428`, `tron:2494104990`, `tron:3448148188`) plus any `eip155:` — client and resource server both default to `eip155:*`, and the official `@x402/evm` ships default assets for Base, Base Sepolia and many other EVM networks, but not BSC (`eip155:56` / `97` need an explicit asset). What can actually settle is bounded by the networks the facilitator has configured, which it must enumerate explicitly | | **Token Standard** | TRC-20 (built-in USDT & USDD support), BEP-20, ERC-20 (Base official USDC) | | **Signing Mechanism** | TIP-712 / EIP-712 typed data signing | | **Payment Schemes** | `exact`, `upto`, `batch-settlement`, `exact_gasfree` (TRON) | @@ -242,7 +241,7 @@ registerToken(TRON_NILE, { }); ``` -On the **resource server** side, custom EVM tokens are advertised by adding an entry to the server's `EVM_TOKENS` table in `src/chains/evm.ts` — an explicit `{ asset, amount, extra }` object. Adding a chain is one table entry; no SDK changes are needed. +On the **resource server** side, custom EVM tokens are advertised with an explicit `{ asset, amount, extra }` price object in the route's `accepts`; no SDK changes are needed. (The `EVM_TOKENS` table of the earlier example server was removed with the EVM examples in x402 v2.1.0; see the [upstream EVM examples](https://github.com/x402-foundation/x402/tree/main/examples/typescript).) Once registered, you can use the custom token symbol in TRON prices (e.g., `"0.001 MYT"`). @@ -257,4 +256,4 @@ x402 is deeply tailored for blockchain-native architectures, providing seamless - **Development Environment**: Use testnets for development and debugging. - **Default Settlement Asset**: TRON/BSC routes use their configured stablecoins; Base uses official **USDC**. - **Security Model**: TIP-712 / EIP-712 typed data signing ensures secure, trust-minimized payment authorization. -- **Extensibility**: Expand support for any custom TRC-20/BEP-20 token via the TRON token registry (`registerToken`) or the server's `EVM_TOKENS` config table. +- **Extensibility**: Expand support for any custom TRC-20/BEP-20 token via the TRON token registry (`registerToken`) or an explicit `{ asset, amount, extra }` route price. diff --git a/docs/x402/core-concepts/wallet.md b/docs/x402/core-concepts/wallet.md index c3b4c917..eb5717ab 100644 --- a/docs/x402/core-concepts/wallet.md +++ b/docs/x402/core-concepts/wallet.md @@ -76,7 +76,7 @@ x402 uses typed data signing for secure payment authorization. ## Token Approval -For the `exact` payment scheme, plain ERC-20/TRC-20 tokens (e.g. BSC USDC/USDT, TRON USDT/USDD) settle via the Permit2 path. The client must authorize the Permit2 contract to transfer tokens — a one-time `approve(Permit2, max)`. On TRON the client SDK auto-broadcasts this approve on the first payment; on EVM it never broadcasts — it attaches a signed, unbroadcast approve for the facilitator to relay when the server advertises a gas-sponsoring extension, and otherwise the allowance must be granted once out of band or verification fails with `permit2_allowance_required`. On TRON, when the resource server advertises `trc20ApprovalResourceSponsoring` (SDK 1.2.0+), the client signs the `approve(Permit2, MaxUint256)` transaction but does not broadcast it — the facilitator temporarily delegates the Energy — and, when needed, Bandwidth — that the payer lacks and broadcasts it, so the payer needs no TRX for that first approve. This requires an activated, single-signature TRON EOA. ERC-3009 tokens (e.g. BSC testnet DHLU) need no approve — they settle gaslessly via `transferWithAuthorization`. +For the `exact` payment scheme, plain ERC-20/TRC-20 tokens (e.g. BSC USDC/USDT, TRON USDT/USDD) settle via the Permit2 path. The client must authorize the Permit2 contract to transfer tokens — a one-time `approve(Permit2, max)`. On TRON the client SDK auto-broadcasts this approve on the first payment; on EVM it never broadcasts — it attaches a signed EIP-2612 permit or a signed, unbroadcast approve for the facilitator to relay when the server advertises a gas-sponsoring extension, and otherwise the allowance must be granted once out of band or verification fails with `permit2_allowance_required`. On TRON, when the resource server advertises `trc20ApprovalResourceSponsoring` (SDK 1.2.0+), the client signs the `approve(Permit2, MaxUint256)` transaction but does not broadcast it — the facilitator temporarily delegates the Energy — and, when needed, Bandwidth — that the payer lacks and broadcasts it, so the payer needs no TRX for that first approve. This requires an activated, single-signature TRON EOA. Since 2.1.0 the client must register `createTrc20ApprovalResourceSponsoringClientExtension(signer)` from `@bankofai/x402-tron-extensions`; otherwise the payment fails with `trc20_approval_client_extension_not_registered`. ERC-3009 tokens (e.g. official Base USDC) need no approve — they settle gaslessly via `transferWithAuthorization`. --- @@ -97,7 +97,7 @@ For the `exact` payment scheme, plain ERC-20/TRC-20 tokens (e.g. BSC USDC/USDT, | Network | RPC Endpoint | | :------- | :------------ | | **Mainnet** | `https://bsc-dataseed.binance.org` | -| **Testnet** | `https://data-seed-prebsc-1-s1.binance.org:8545` | +| **Testnet** | `https://bsc-testnet-rpc.publicnode.com` | --- diff --git a/docs/x402/faq.md b/docs/x402/faq.md index 1e13abf4..e74c92d9 100644 --- a/docs/x402/faq.md +++ b/docs/x402/faq.md @@ -11,7 +11,7 @@ x402 revives the long-unused HTTP `402 Payment Required` status code and transfo #### Is x402 a commercial product? -**No.** x402 is an open-source blockchain implementation of the x402 protocol, released under the MIT license. You are free to use it without purchasing any commercial product. +**No.** x402 is an open-source blockchain implementation of the x402 protocol. The [repository](https://github.com/BofAI/x402) is MIT-licensed, while the published npm packages `@bankofai/x402-tron` and `@bankofai/x402-tron-extensions` declare `Apache-2.0` in their `package.json` (as do the official `@x402/*` packages). You are free to use it without purchasing any commercial product. #### Why replace traditional payment channels or API keys? @@ -27,13 +27,13 @@ Not at all. Any Web API or content provider—whether Web3-native or traditional #### What languages and frameworks are supported? -x402 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packages: +x402 is a **TypeScript-only** SDK: the TRON packages are published as `@bankofai/x402-tron` and `@bankofai/x402-tron-extensions`, and Core, EVM and the framework integrations are the official `@x402/*` packages: - **Server middleware**: Express, Fastify, Hono, Next.js -- **Client**: wrapped `fetch` (`@bankofai/x402-fetch`), Axios, MCP transport +- **Client**: wrapped `fetch` (`@x402/fetch`), Axios, MCP transport - **Facilitator**: chain-agnostic engine with per-scheme verify + settle -The previous Python SDK lives under `legacy/` for reference. +The retired Python SDK and the old root `legacy/` archive were removed in x402 v2.0.0, and the compatibility npm packages under `typescript/packages/legacy/` in v2.1.0. --- @@ -70,7 +70,7 @@ Common pricing models include: x402 defines five named payment schemes. Four are available end to end; `auth-capture` currently ships client-side support only: -- **`exact`**: Pay the exact advertised amount. EIP-3009 tokens (e.g. official Base USDC and 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. +- **`exact`**: Pay the exact advertised amount. EIP-3009 tokens (e.g. official Base USDC) 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. - **`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. The relayer deducts its own fee from the payment token, on top of the payment amount. @@ -82,10 +82,10 @@ x402 defines five named payment schemes. Four are available end to end; `auth-ca - A stock v2 client can directly access this SDK's `exact` protected endpoints with no project-specific adapter layer. - This SDK's client can pay v2-compatible servers directly. -- In the V2 structure, transfer authorization data is carried in the `payload.authorization` field (a structured object). -- BSC USDT/USDC are plain ERC-20s (no ERC-3009). They settle via the Permit2 path under the `exact` scheme — the client auto-broadcasts a one-time `approve(Permit2)` on first payment. ERC-3009 tokens like BSC testnet **DHLU** settle gaslessly with no approve. +- In the V2 structure, transfer authorization data is a structured object: `payload.authorization` on the EIP-3009 path, `payload.permit2Authorization` on the Permit2 path. +- BSC USDT/USDC are plain ERC-20s (no ERC-3009). They settle via the Permit2 path under the `exact` scheme and need a one-time `approve(Permit2)`. On EVM the client never broadcasts it: it must already be in place, or be relayed by the facilitator through a gas-sponsoring extension the server advertises — otherwise the request fails with `permit2_allowance_required`. - Base Mainnet official USDC uses EIP-3009 under `exact`: the payer signs `transferWithAuthorization`, so no Permit2 approval is required. -- The `legacy/examples/bsc-testnet-smoke/` directory (part of the `legacy/` tree, kept for reference) contains smoke tests for bidirectional interoperability (Coinbase official client → BANK OF AI server, BANK OF AI client → Coinbase official server) that you can use as a debugging and integration reference. +- The former `legacy/examples/bsc-testnet-smoke/` interoperability smoke tests were removed together with the root `legacy/` archive in x402 v2.0.0. Use the runnable [`examples/typescript`](https://github.com/BofAI/x402/tree/main/examples/typescript) workspace as the current client → server → facilitator reference; since v2.1.0 it covers TRON only, so for EVM use the [upstream examples](https://github.com/x402-foundation/x402/tree/main/examples/typescript). --- @@ -95,22 +95,23 @@ x402 defines five named payment schemes. Four are available end to end; `auth-ca | Network | Token | Status | | --------------------------- | ------------- | ----------- | -| TRON Mainnet (`tron:0x2b6653dc`) | USDT (TRC-20) | **Mainnet** | -| TRON Nile (`tron:0xcd8690dc`) | USDT (TRC-20) | **Testnet** | -| TRON Shasta (`tron:0x94a9059e`) | USDT (TRC-20) | **Testnet** (SDK/CLI only — the official facilitator does not settle Shasta; use Nile or self-host) | -| TRON Mainnet (`tron:0x2b6653dc`) | USDD (TRC-20) | **Mainnet** | -| TRON Nile (`tron:0xcd8690dc`) | USDD (TRC-20) | **Testnet** | +| TRON Mainnet (`tron:728126428`) | USDT (TRC-20) | **Mainnet** | +| TRON Nile (`tron:3448148188`) | USDT (TRC-20) | **Testnet** | +| TRON Shasta (`tron:2494104990`) | USDT (TRC-20) | **Testnet** (SDK/CLI only — the official facilitator does not settle Shasta; use Nile or self-host) | +| TRON Mainnet (`tron:728126428`) | USDD (TRC-20) | **Mainnet** | +| TRON Nile (`tron:3448148188`) | USDD (TRC-20) | **Testnet** | | BSC Mainnet (`eip155:56`) | USDT (BEP-20) | **Mainnet** | -| BSC Mainnet (`eip155:56`) | USDC (BEP-20) | **Mainnet** | +| BSC Mainnet (`eip155:56`) | USDC (BEP-20; `0x8AC76a…`, not in any shipped token registry — explicit asset only) | **Mainnet** | | BSC Testnet (`eip155:97`) | USDT (BEP-20) | **Testnet** | | BSC Testnet (`eip155:97`) | USDC (BEP-20) | **Testnet** | -| BSC Testnet (`eip155:97`) | DHLU (BEP-20, for `exact` interop tests) | **Testnet** | | Base Mainnet (`eip155:8453`) | Official USDC (ERC-20, EIP-3009) | **Mainnet** | | Base Sepolia (`eip155:84532`) | USDC (ERC-20, EIP-3009) | **Testnet** | -Only some of these are **default assets** (USDT on TRON and BSC Mainnet, USDC on BSC Testnet and Base). Since SDK 1.1.0 a client's spend controls reject any other asset — including TRON USDD, BSC Mainnet USDC and BSC Testnet USDT — unless it is allowlisted via `spendControls.allowedAssets`. +TRON identifiers use decimal chain IDs since x402 v2.0.0 (`@bankofai/x402-tron` 2.0.0); the older hex forms (`tron:0x2b6653dc`, `tron:0xcd8690dc`, `tron:0x94a9059e`) are still accepted as input aliases. -Custom TRC-20 tokens can be added via the TRON token registry (`registerToken` from `@bankofai/x402-tron`); custom BEP-20 tokens are advertised by adding an entry to the server's `EVM_TOKENS` config table. +Only some of these are **default assets** (USDT on the three TRON networks, USDC on Base and Base Sepolia). Since SDK 1.1.0 a client's spend controls reject any other asset — including TRON USDD and every BSC asset — unless it is allowlisted via `spendControls.allowedAssets`. + +Custom TRC-20 tokens can be added via the TRON token registry (`registerToken` from `@bankofai/x402-tron`); custom BEP-20 tokens are advertised with an explicit `{ asset, amount, extra }` price on the server route. #### What fees are involved? @@ -130,7 +131,7 @@ Custom TRC-20 tokens can be added via the TRON token registry (`registerToken` f 1. **Buyer (client/agent)** signs locally (browser, serverless function, or agent VM). 2. **Seller** verifies signatures without accessing private keys. -3. **Facilitator** submits transactions with its own settlement wallet, resolved through `@bankofai/agent-wallet` — the raw key never enters the facilitator process. +3. **Facilitator** submits transactions with its own settlement wallet, resolved through `@bankofai/agent-wallet` — with the `privy` or `wallet_cli` provider the key stays outside the facilitator process (`raw_secret` keeps a plaintext key in config and is for development only). #### How does refunds work? @@ -167,11 +168,11 @@ The flow mirrors a human user: Install the published packages in your TypeScript app and build against npm, for example: ```bash -pnpm add @bankofai/x402-fetch @bankofai/x402-tron @bankofai/x402-evm @bankofai/agent-wallet -pnpm add @bankofai/x402-core @bankofai/x402-express +pnpm add @x402/core@2.28.0 @x402/fetch@2.28.0 @bankofai/x402-tron@2.1.0 @x402/evm@2.28.0 @bankofai/agent-wallet +pnpm add @x402/express@2.28.0 ``` -Use the framework package that matches your server (`express`, `hono`, `fastify`, or `next`). The [`examples/typescript`](https://github.com/BofAI/x402/tree/main/examples/typescript) workspace is a runnable reference for client → server → facilitator flows, not a prerequisite for application development. +Use the framework package that matches your server (`@x402/express`, `@x402/hono`, `@x402/fastify`, or `@x402/next`), at the same `2.28.0` as `@x402/core` — `@bankofai/x402-tron` 2.1.0 requires exactly `@x402/core@2.28.0`. Add `@bankofai/x402-tron-extensions@2.1.0` only if you use TRON resource sponsoring. The [`examples/typescript`](https://github.com/BofAI/x402/tree/main/examples/typescript) workspace is a runnable reference for client → server → facilitator flows, not a prerequisite for application development. #### Which testnet is recommended? @@ -195,10 +196,11 @@ Common causes: 1. Invalid signature (incorrect domain or payload). 2. Insufficient payment amount. -3. Insufficient token allowance granted to Facilitator. -4. Insufficient wallet balance. +3. Insufficient wallet balance. + +The response body is `{}` by default. The reason is the `error` field of the payment requirements carried, Base64-encoded, in the `PAYMENT-REQUIRED` response header — decode it (for example with `decodePaymentRequiredHeader` from `@x402/core/http`) for diagnostics. -Check the `error` field in the server’s JSON response for detailed diagnostics. +An insufficient Permit2 allowance on the `exact` / `upto` Permit2 path does not return 402: the server answers HTTP `412 Precondition Failed` with `error: "permit2_allowance_required"` in the same header. (The `batch-settlement` deposit path reports it as a 402 with its own scheme-specific code.) #### It works on Nile but fails on Mainnet — why? diff --git a/docs/x402/getting-started/quickstart-for-human.md b/docs/x402/getting-started/quickstart-for-human.md index ed142a18..26712ae1 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. +x402 is a **TypeScript-only** SDK: the TRON mechanism ships as `@bankofai/x402-tron` and runs on the official `@x402/*` Core and HTTP packages. This guide shows how to integrate the published npm packages directly. ::: --- @@ -31,7 +31,7 @@ x402 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packa ### Checklist Before You Start -- [ ] **Node.js 22+** and **pnpm 11.1+** installed +- [ ] **Node.js 24.22.1+** 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) @@ -94,16 +94,16 @@ 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/agent-wallet @bankofai/x402-fetch @bankofai/x402-tron +pnpm add @bankofai/agent-wallet @x402/core@2.28.0 @x402/fetch@2.28.0 @bankofai/x402-tron@2.1.0 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. +Use `npm install` or `yarn add` with the same package names if your project does not use pnpm. Keep `@x402/core` and `@x402/fetch` at exactly `2.28.0` — `@bankofai/x402-tron` 2.1.0 declares `@x402/core@2.28.0` as an exact peer dependency. :::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` +x402 uses [Agent Wallet](../../Agent-Wallet/QuickStart.md) to resolve and manage wallet credentials. Agent Wallet (3.0+) is installed with the package set above. Wallet resolution priority: +1. The Agent Wallet CLI config (`~/.agent-wallet`), when it contains at least one wallet — set up with `agent-wallet start raw_secret`, `wallet_cli` or `privy` +2. Environment variables `AGENT_WALLET_PRIVATE_KEY` (or `AGENT_WALLET_MNEMONIC`) This guide uses the environment variable method. ::: @@ -145,7 +145,8 @@ The client wraps `fetch` so HTTP `402 Payment Required` challenges are paid auto ```typescript import { resolveWallet, type Wallet, type Eip712Capable } from "@bankofai/agent-wallet"; -import { x402Client, wrapFetchWithPayment } from "@bankofai/x402-fetch"; +import { x402Client } from "@x402/core/client"; +import { wrapFetchWithPayment } from "@x402/fetch"; import { createClientTronSigner, TRON_NILE } from "@bankofai/x402-tron"; import { ExactTronScheme } from "@bankofai/x402-tron/exact/client"; @@ -210,15 +211,14 @@ See [SDK Feature Matrix](../sdk-features.md) for the full options, including `al | 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 | +| `resolve_wallet could not find a wallet source in config or env` | 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 | | `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` | +| `Top-level await is currently not supported with the "cjs" output format` (under `tsx`) | Project is not declared as ESM, so the script's top-level `await` is compiled as CommonJS | Add `"type": "module"` to your `package.json` | If you need finer-grained error handling in your code: @@ -232,7 +232,7 @@ try { console.error(await res.text()); } } catch (error) { - if (error instanceof Error && error.message.includes("no payment option")) { + if (error instanceof Error && error.message.includes("No network/scheme registered")) { 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"); diff --git a/docs/x402/getting-started/quickstart-for-sellers.md b/docs/x402/getting-started/quickstart-for-sellers.md index d3e9975b..2f7fd583 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. +x402 is a **TypeScript-only** SDK: the TRON mechanism ships as `@bankofai/x402-tron` and runs on the official `@x402/*` Core, EVM and framework packages. This guide shows how to build with the published npm packages. ::: --- @@ -28,7 +28,7 @@ x402 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` packa In your terminal (Terminal on macOS/Linux, or PowerShell/Command Prompt on Windows), run the following commands to confirm the required tools are installed: ```bash -node --version # Requires Node.js 22 or higher +node --version # Requires Node.js 24.22.1 or higher pnpm --version # Requires pnpm 11.1 or higher git --version # Version control tool ``` @@ -132,14 +132,14 @@ Deposit a small amount of official USDC on Base Mainnet. The resource server onl ## Step 1: Install the SDK Packages -Install the Express adapter and the TRON/EVM payment schemes in your TypeScript API project: +Install official Core, the Express adapter and the TRON/EVM payment schemes in your TypeScript API project: ```bash -pnpm add express @bankofai/x402-core @bankofai/x402-express @bankofai/x402-tron @bankofai/x402-evm +pnpm add express @x402/core@2.28.0 @x402/express@2.28.0 @bankofai/x402-tron@2.1.0 @x402/evm@2.28.0 pnpm add -D tsx # to run the TypeScript entry point below ``` -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. +Use the framework package that matches your server (`@x402/express`, `@x402/hono`, `@x402/fastify`, or `@x402/next`), at the same `2.28.0` as `@x402/core` — `@bankofai/x402-tron` 2.1.0 declares `@x402/core@2.28.0` as an exact peer dependency. Install `@x402/evm` only for BSC/Base routes. Use `npm install` or `yarn add` with the same package names if your project does not use pnpm. 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. @@ -169,16 +169,13 @@ Here are minimal Express resource servers for TRON and Base. `GET /credit` requi ```typescript import express from "express"; -import { createResourceServer } from "@bankofai/x402-core"; -import { HTTPFacilitatorClient } from "@bankofai/x402-core/server"; -import { - x402HTTPResourceServer, - paymentMiddlewareFromHTTPServer, -} from "@bankofai/x402-express"; +import { HTTPFacilitatorClient, x402ResourceServer } from "@x402/core/server"; +import { x402HTTPResourceServer } from "@x402/core/http"; +import { paymentMiddlewareFromHTTPServer } from "@x402/express"; import { TRON_NILE } from "@bankofai/x402-tron"; import { ExactTronScheme } from "@bankofai/x402-tron/exact/server"; -const server = createResourceServer( +const server = new x402ResourceServer( new HTTPFacilitatorClient({ // Replace this before running — the server syncs with the facilitator on // startup, so a placeholder URL makes the first protected request fail @@ -222,15 +219,12 @@ express() ```typescript import express from "express"; -import { createResourceServer } from "@bankofai/x402-core"; -import { HTTPFacilitatorClient } from "@bankofai/x402-core/server"; -import { - x402HTTPResourceServer, - paymentMiddlewareFromHTTPServer, -} from "@bankofai/x402-express"; -import { ExactEvmScheme } from "@bankofai/x402-evm/exact/server"; - -const server = createResourceServer( +import { HTTPFacilitatorClient, x402ResourceServer } from "@x402/core/server"; +import { x402HTTPResourceServer } from "@x402/core/http"; +import { paymentMiddlewareFromHTTPServer } from "@x402/express"; +import { ExactEvmScheme } from "@x402/evm/exact/server"; + +const server = new x402ResourceServer( new HTTPFacilitatorClient({ // Replace this before running — the server syncs with the facilitator on // startup, so a placeholder URL makes the first protected request fail @@ -313,7 +307,7 @@ The officially hosted Facilitator service requires **no infrastructure to mainta Set the `url` in `HTTPFacilitatorClient` to the official endpoint: ```typescript -const server = createResourceServer( +const server = new x402ResourceServer( new HTTPFacilitatorClient({ url: "https://facilitator.bankofai.io", }) @@ -322,7 +316,7 @@ const server = createResourceServer( This is the address your x402 server uses to verify and settle payments — **for API calls only**, no need to open it in a browser. -> ⚠️ **Without an API Key, this endpoint is rate-limited** (one `/settle` call per IP per minute). Suitable for testing only. +> ⚠️ **Without an API Key, this endpoint is rate-limited** (10 requests per IP per minute, counted separately for `/verify` and `/settle`). Suitable for testing only. #### 4.2 Apply for an API Key @@ -330,14 +324,14 @@ This is the address your x402 server uses to verify and settle payments — **fo 2. On the Dashboard, click **"Create API Key"** 3. Confirm, then click **View** in the Dashboard to see and copy your API Key -With an API Key, the official service allows **1,000 `/settle` requests per API Key per minute**, sufficient for production use. +With an API Key, the official service allows **1,000 requests per API Key per minute for each of `/verify` and `/settle`**, sufficient for production use. #### 4.3 Wire the API Key into Your Server 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 -FACILITATOR_API_KEY=paste_your_api_key_here +export FACILITATOR_API_KEY=paste_your_api_key_here ``` `HTTPFacilitatorClient` sends the header only if you give it `createAuthHeaders` — without this the server silently stays on the anonymous tier: @@ -364,7 +358,7 @@ new HTTPFacilitatorClient({ The self-hosted option gives you full control over the settlement wallet, RPC endpoints, and which networks and schemes you register — neither the SDK nor the facilitator charges a fee of its own. It runs the example facilitator (`examples/typescript/facilitator/basic`), which exposes `/verify`, `/settle`, `/supported` over HTTP and dispatches by the payment's `network` field. -> **Base sellers:** the bundled example facilitator registers only `eip155:97` and `eip155:56` (`EVM_NETWORKS` in `facilitator/basic/src/chains/evm.ts`). To settle on Base, either use the official facilitator — which enables `eip155:8453` and `eip155:84532` — or add those ids to `EVM_NETWORKS` yourself. +> **BSC and Base sellers:** since x402 v2.1.0 the bundled example facilitator registers TRON networks only (`TRON_NETWORKS` in `facilitator/basic/src/chains/tron.ts`). To settle on BSC or Base, either use the official facilitator — which enables `eip155:56`, `eip155:97`, `eip155:8453` and `eip155:84532` — or build an EVM facilitator with official `@x402/evm` following the [upstream examples](https://github.com/x402-foundation/x402/tree/main/examples/typescript). > ⚠️ **Security reminder — please read first:** > - A self-hosted Facilitator uses your wallet to submit on-chain settlement transactions — **this wallet should be separate from your receiving wallet** @@ -377,27 +371,25 @@ The facilitator verifies signatures and settles on-chain. It registers the `exac ```typescript // examples/typescript/facilitator/basic/src/index.ts (abridged) -import { x402Facilitator } from "@bankofai/x402-core/facilitator"; +import { x402Facilitator } from "@x402/core/facilitator"; const facilitator = new x402Facilitator() .onBeforeSettle(async ctx => console.log("[settle] before", ctx.requirements.network)) .onAfterSettle(async ctx => console.log("[settle] after", ctx.requirements.network)) .onSettleFailure(async ctx => console.log("[settle] failure", ctx)); -// Register each chain only if its wallet resolves (EVM-only, TRON-only, or both). -const evm = await registerEvm(facilitator); +// Register each chain only if its wallet resolves. Only TRON networks are registered. const tron = await registerTron(facilitator); // Exposes POST /verify, POST /settle, GET /supported on FACILITATOR_PORT. app.listen(PORT, () => console.log(`🚀 Facilitator on http://localhost:${PORT}`)); ``` -Each chain module adapts the agent-wallet to a facilitator signer: +The TRON chain module adapts the agent-wallet to a facilitator signer: -- **EVM** — `createFacilitatorEvmSigner(wallet, { network, rpcUrl })`, then `facilitator.register(network, new ExactEvmScheme(signer))` - **TRON** — `createFacilitatorTronSigner(wallet, { network, apiKey })`, then `facilitator.register(network, new ExactTronScheme(signer))` -The signer factories build the viem client / TronWeb internally; the example **never reads a raw private key** — `AGENT_WALLET_PRIVATE_KEY` is consumed by `@bankofai/agent-wallet`. +The signer factory builds TronWeb internally; the example **never reads a raw private key** — `AGENT_WALLET_PRIVATE_KEY` is consumed by `@bankofai/agent-wallet`. #### 4.2 Start the Facilitator @@ -410,9 +402,10 @@ pnpm dev:facilitator **After a successful start, you should see output like:** ``` -[evm] facilitator registered eip155:97 (0x…) [tron] facilitator registered tron:3448148188 (T…) -🚀 Facilitator on http://localhost:4022 (evm=true, tron=true) +[tron] facilitator registered tron:2494104990 (T…) +[tron] facilitator registered tron:728126428 (T…) +🚀 Facilitator on http://localhost:4022 (tron=true) ``` > ✅ **Success:** Facilitator is running on port 4022 — **keep this terminal window open, do not close it** @@ -472,10 +465,10 @@ To test the complete pay → receive content flow, use the minimal client in [Qu |---------|-------|----------| | `Failed to fetch` / connection refused | Facilitator or server not running | Start the facilitator first, then run your API server entry point | | Client selects nothing / no matching requirement | 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` | +| `Top-level await is currently not supported with the "cjs" output format` under `npx tsx` | Project is not declared as ESM, so an entry file with top-level `await` is compiled as CommonJS | Add `"type": "module"` to your `package.json` | | `No network/scheme registered for x402 version: 2 …` | The selected client network has no registered scheme | Ensure the client registers 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. Note the SDK reads no environment variables — `EVM_RPC_URL` is honoured by the reference example apps; in your own server pass the RPC URL to the signer factory | +| `Insufficient balance` / allowance error | Test wallet lacks test tokens, or Permit2 allowance too low | Claim test tokens from the faucet. On TRON the client auto-approves Permit2 on first payment; on EVM, approve Permit2 once yourself | +| `Connection timeout` | Network or request timeout | Check your connection. Note the SDK reads no environment variables — `TRON_GRID_API_KEY` is read by the reference example apps; in your own code pass `apiKey` / `rpcUrl` to the signer factory | --- @@ -500,15 +493,11 @@ price: "1 USDT", ### 2. Set a Reliable EVM RPC -BSC mainnet needs a stable endpoint. Set this for both the client and facilitator: - -```bash -EVM_RPC_URL=https://bsc-rpc.publicnode.com -``` +BSC mainnet needs a stable endpoint, such as `https://bsc-rpc.publicnode.com`. The SDK reads no environment variables, and since v2.1.0 the repository examples are TRON-only — configure the endpoint on the EVM signers you build with official `@x402/evm`, for both the client and a self-hosted facilitator. ### 3. (Self-Hosted) Switch the Facilitator to Mainnet -The example facilitator's `TRON_NETWORKS` already includes `TRON_MAINNET` (`tron:728126428`), and `EVM_NETWORKS` includes `eip155:97` and `eip155:56` — Base (`eip155:8453` / `eip155:84532`) is not registered there, so add it if you settle on Base. Fund the Facilitator wallet with real TRX/BNB to cover settlement gas, then restart: +The example facilitator's `TRON_NETWORKS` already includes `TRON_MAINNET` (`tron:728126428`); it registers no EVM networks, so settle BSC or Base through the official facilitator or your own `@x402/evm` facilitator. Fund the Facilitator wallet with real TRX to cover settlement energy, then restart: ```bash pnpm dev:facilitator diff --git a/docs/x402/index.md b/docs/x402/index.md index cfbfdf7f..1d93a7a2 100644 --- a/docs/x402/index.md +++ b/docs/x402/index.md @@ -17,7 +17,7 @@ x402 currently supports **TRON**, **BNB Smart Chain (BSC)**, and **Base**, with Feel free to submit a PR to the [GitHub repository](https://github.com/BofAI/docs). Our only principle is to maintain neutrality — aside from essential resource links, please avoid promotional or branded content. **Building with x402?** -Install the published [`@bankofai/x402-*`](https://www.npmjs.com/package/@bankofai/x402-tron) packages in your TypeScript app. The [`x402` repository](https://github.com/BofAI/x402) ships runnable client → server → facilitator examples under `examples/typescript/` for reference — `exact`, `gasfree`, `upto`, and `batch-settlement`. +Install the published [`@bankofai/x402-tron`](https://www.npmjs.com/package/@bankofai/x402-tron) packages together with the official `@x402/*` packages in your TypeScript app. The [`x402` repository](https://github.com/BofAI/x402) ships runnable client → server → facilitator examples under `examples/typescript/` for reference — `exact`, `gasfree`, `upto`, and `batch-settlement`. --- @@ -86,9 +86,9 @@ Our goal is to build a low-barrier, permissionless, developer-friendly programma x402 currently supports the following networks: -- **TRON Mainnet** (`tron:0x2b6653dc`) -- **TRON Shasta Testnet** (`tron:0x94a9059e`) — SDK/CLI only; not settled by the official facilitator -- **TRON Nile Testnet** (`tron:0xcd8690dc`) +- **TRON Mainnet** (`tron:728126428`) +- **TRON Shasta Testnet** (`tron:2494104990`) — SDK/CLI only; not settled by the official facilitator +- **TRON Nile Testnet** (`tron:3448148188`) - **BSC Mainnet** (`eip155:56`) - **BSC Testnet** (`eip155:97`) - **Base Mainnet** (`eip155:8453`) @@ -96,7 +96,9 @@ x402 currently supports the following networks: Base Mainnet payments use official USDC with the `exact` scheme and EIP-3009 authorization. -> **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. It defines five named schemes: `exact` (ERC-3009 / Permit2), `upto`, `batch-settlement`, `exact_gasfree` (TRON), and the currently client-only `auth-capture` (EVM). The previous-generation Python + TypeScript SDK lives under `legacy/` for reference. See the [SDK Feature Matrix](./x402/sdk-features) for the full breakdown. +Since x402 v2.0.0, TRON identifiers use decimal chain IDs; the older hex forms (`tron:0x2b6653dc`, `tron:0x94a9059e`, `tron:0xcd8690dc`) are still accepted as input aliases. + +> **SDK (TypeScript-only)**: x402 is a TypeScript-only SDK: the TRON mechanism and TRON resource-sponsoring extension ship as `@bankofai/x402-tron` and `@bankofai/x402-tron-extensions`, on top of the official `@x402/*` packages (`core`, `evm`, `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. It defines five named schemes: `exact` (ERC-3009 / Permit2), `upto`, `batch-settlement`, `exact_gasfree` (TRON), and the currently client-only `auth-capture` (EVM). The previous-generation Python + TypeScript SDK archive was removed in x402 v2.0.0, and the compatibility npm packages under `typescript/packages/legacy/` in v2.1.0. See the [SDK Feature Matrix](./x402/sdk-features) for the full breakdown. --- diff --git a/docs/x402/sdk-features.md b/docs/x402/sdk-features.md index 16e72013..ab1da43a 100644 --- a/docs/x402/sdk-features.md +++ b/docs/x402/sdk-features.md @@ -1,15 +1,15 @@ --- title: 'SDK Feature Matrix' -description: 'Feature support matrix for the x402 TypeScript SDK, published as granular @bankofai/x402-* packages.' +description: 'Feature support matrix for the x402 TypeScript SDK: the @bankofai/x402-tron and @bankofai/x402-tron-extensions packages on official @x402/* Core.' --- # SDK Feature Matrix This page tracks the feature support of the x402 SDK. -> **SDK (TypeScript-only)**: x402 is a **TypeScript-only** SDK published as granular `@bankofai/x402-*` npm packages. The source is maintained in a pnpm/turbo monorepo, but applications should depend on the published packages. The previous-generation Python + TypeScript SDK lives under `legacy/` for reference. +> **SDK (TypeScript-only)**: x402 is a **TypeScript-only** SDK. It publishes the TRON mechanism and the TRON resource-sponsoring extension as the `@bankofai/x402-tron` and `@bankofai/x402-tron-extensions` npm packages and builds on the official x402 Foundation `@x402/*` packages for Core, EVM, the HTTP/MCP integrations and the generic extensions. The source is maintained in a pnpm/turbo monorepo, but applications should depend on the published packages. The previous-generation Python + TypeScript SDK archive (`legacy/`) was removed from the repository in 2.0.0, and the `typescript/packages/legacy/` compatibility packages in 2.1.0. > -> **Current release: 1.2.0** (2026-08-28). The 11 `@bankofai/x402-*` packages share one version line but no longer all move together: 1.2.0 published `@bankofai/x402-extensions` and `@bankofai/x402-tron` at `1.2.0`, `@bankofai/x402-express`, `-fastify`, `-hono` and `-next` at `1.1.1`, and left `@bankofai/x402-core`, `-evm`, `-fetch`, `-axios` and `-mcp` at `1.1.0` (no API or dependency change in this release). Each package pins its internal dependencies to `~` of the published version of that dependency, so install the set as published above. The SDK requires **Node.js 22+**. +> **Current release: 2.1.0** (2026-10-23). The payment call chain now runs on official `@x402/core` `2.28.0`, which `@bankofai/x402-tron` `2.1.0` declares as an exact peer dependency; use the matching official HTTP/MCP integration (`@x402/fetch`, `@x402/axios`, `@x402/express`, `@x402/fastify`, `@x402/hono`, `@x402/next` or `@x402/mcp`, all `2.28.0`). TRON resource sponsoring moved to the separate `@bankofai/x402-tron-extensions` `2.1.0`, which pins the exact mechanism version — upgrade the two TRON packages together. EVM uses official `@x402/evm` `2.28.0` and the generic extensions official `@x402/extensions` `2.28.0`; the local EVM package and `@bankofai/x402-extensions` were removed. `@bankofai/x402-core` and the `@bankofai/x402-*` HTTP/MCP adapters built on it are not interchangeable with the 2.1 mechanism — new TRON integrations use official Core and adapters. Upgrading from 2.0 is a source migration; see the [TRON 2.1 migration guide](https://github.com/BofAI/x402/blob/main/docs/migrations/tron-2.1.md). The SDK requires **Node.js 24.22.1+**; the runnable examples use `@bankofai/agent-wallet` **3.0+**. --- @@ -17,17 +17,18 @@ 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`, plus the `auth-capture` client (`@bankofai/x402-evm/auth-capture/client` — no server or facilitator export) | -| `@bankofai/x402-tron` | TRON mechanism: `exact`, `upto`, `batch-settlement`, `exact_gasfree` | -| `@bankofai/x402-fetch` | Wrapped-`fetch` client (`wrapFetchWithPayment`) | -| `@bankofai/x402-express` | Express server middleware | -| `@bankofai/x402-hono` | Hono server middleware | -| `@bankofai/x402-fastify` | Fastify server middleware | -| `@bankofai/x402-next` | Next.js server middleware | -| `@bankofai/x402-axios` | Axios client wrapper | -| `@bankofai/x402-mcp` | MCP transport (client + server) for AI agents | -| `@bankofai/x402-extensions` | Extensions: EVM gas-sponsoring (`eip2612GasSponsoring`, `erc20ApprovalGasSponsoring`), TRON resource sponsoring (`trc20ApprovalResourceSponsoring`, new in 1.2.0), payment-identifier, bazaar, sign-in-with-x, offer-receipt, builder-code | +| `@bankofai/x402-tron` | TRON mechanism: `exact`, `upto`, `batch-settlement`, `exact_gasfree`; TRON signer factories, `/rpc` and `/transactions` utilities, TRON logger | +| `@bankofai/x402-tron-extensions` | TRON approval resource sponsoring (`trc20ApprovalResourceSponsoring`): declaration, client pre-signing extension, facilitator runtime and coordinator — moved here in 2.1.0 | +| `@x402/core` (official) | Protocol types, client/facilitator/server engines, `HTTPFacilitatorClient` | +| `@x402/evm` (official) | EVM mechanism: `exact`, `upto`, `batch-settlement`, plus the `auth-capture` client (`@x402/evm/auth-capture/client` — no server or facilitator export) | +| `@x402/fetch` (official) | Wrapped-`fetch` client (`wrapFetchWithPayment`) | +| `@x402/express` (official) | Express server middleware | +| `@x402/hono` (official) | Hono server middleware | +| `@x402/fastify` (official) | Fastify server middleware | +| `@x402/next` (official) | Next.js server middleware | +| `@x402/axios` (official) | Axios client wrapper | +| `@x402/mcp` (official) | MCP transport (client + server) for AI agents | +| `@x402/extensions` (official) | Generic extensions: EVM gas-sponsoring (`eip2612GasSponsoring`, `erc20ApprovalGasSponsoring`), payment-identifier, bazaar, sign-in-with-x, offer-receipt, builder-code | --- @@ -55,14 +56,14 @@ This page tracks the feature support of the x402 SDK. | `tron:728126428` | `TRON_MAINNET` | ✅ | | `tron:3448148188` | `TRON_NILE` | ✅ | | `tron:2494104990` | `TRON_SHASTA` | ✅ | -| `eip155:56` (BSC Mainnet) | - | ✅ | -| `eip155:97` (BSC Testnet) | - | ✅ | +| `eip155:56` (BSC Mainnet) | - | ✅ (explicit asset only) | +| `eip155:97` (BSC Testnet) | - | ✅ (explicit asset only) | | `eip155:8453` (Base Mainnet) | - | ✅ | | `eip155:84532` (Base Sepolia) | - | ✅ (CLI/SDK testing) | -> **TRON ID format**: since `@bankofai/x402-tron` 2.0.0 the SDK constants use decimal CAIP-2 references. The older hexadecimal forms (`tron:0x2b6653dc`, `tron:0xcd8690dc`, `tron:0x94a9059e`) are still accepted as input aliases, and are what the official facilitator and the API catalog currently report. +> **TRON ID format**: since `@bankofai/x402-tron` 2.0.0 the SDK constants use decimal CAIP-2 references. The older hexadecimal forms (`tron:0x2b6653dc`, `tron:0xcd8690dc`, `tron:0x94a9059e`) are still accepted as input aliases and are normalized to the decimal form. The official facilitator reports the decimal identifiers in `/supported`; the API Catalog still lists the hexadecimal forms. -> Twenty further upstream EVM chains (MegaETH, Monad, Polygon, Arbitrum One/Sepolia, Celo, XDC, Flare, Mezo, Radius, Stable, ADI, HPP, Igra, …) are also wired into the EVM default-asset registry. The public API Catalog publishes Base Mainnet routes only; Base Sepolia remains available for CLI/SDK testing. +> EVM support comes from the official `@x402/evm` 2.28.0. Its default-asset registry covers Base, Base Sepolia, Ethereum, Polygon, Arbitrum One/Sepolia, Avalanche, Celo, Sei, MegaETH, Monad, Stable, XDC, Flare, Mezo, Radius, ADI, HPP, Igra and others — but **not BSC**. On BSC, price a route with an explicit `{ asset, amount, extra }` object (a `$` price fails with `No default asset configured for network eip155:56`), and clients must allowlist the asset in `spendControls.allowedAssets`. The public API Catalog publishes Base Mainnet routes only; Base Sepolia remains available for CLI/SDK testing. --- @@ -90,7 +91,7 @@ A scheme/network server now declares which payment flows it supports per asset-t Legacy v1.0 `SchemeNetworkServer` implementations may omit their payment-flow declaration; they continue to use the authorization flow. -`upfront` and `escrow` are orchestration hooks for custom schemes. As of 1.1.0 every built-in server scheme (`exact`, `upto`, `batch-settlement`, `exact_gasfree`) declares `authorization` only, so `extra.paymentFlow` does not appear on the wire with the shipped schemes. +The TRON server schemes (`exact`, `upto`, `batch-settlement`, `exact_gasfree`) and the EVM `upto` and `batch-settlement` schemes declare `authorization` only. The official EVM `exact` scheme (`@x402/evm`) also supports `upfront`, for both `eip3009` and `permit2`: a route opts in by setting `extra: { paymentFlow: "upfront" }` on that payment option, and only then does `extra.paymentFlow` appear on the wire. No shipped scheme declares `escrow`; it remains a hook for custom schemes. > **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. @@ -98,31 +99,42 @@ Legacy v1.0 `SchemeNetworkServer` implementations may omit their payment-flow de ## Extensions {#extensions} -`@bankofai/x402-extensions` ships optional protocol extensions: `bazaar`, `sign-in-with-x`, `offer-receipt`, `payment-identifier`, `eip2612-gas-sponsoring`, `erc20-approval-gas-sponsoring`, `trc20-approval-resource-sponsoring`, and `builder-code`. All of them are exported from the package root — there is no per-extension import subpath for the sponsoring extensions. A resource server declares an extension in `PaymentRequired.extensions`; the sponsoring extensions and `payment-identifier` act only on a declared extension, while `builder-code` attribution is attached by whichever party registered it. +The generic protocol extensions — `bazaar`, `sign-in-with-x`, `offer-receipt`, `payment-identifier`, `eip2612-gas-sponsoring`, `erc20-approval-gas-sponsoring`, and `builder-code` — come from official `@x402/extensions` `2.28.0`: most through subpaths such as `@x402/extensions/bazaar`, the two EVM gas-sponsoring extensions from the package root. TRON `trc20-approval-resource-sponsoring` ships separately in `@bankofai/x402-tron-extensions`, exported from its root and from `/trc20-approval-resource-sponsoring` (with `/client`, `/facilitator` and `/resourceService` beneath it). A resource server declares an extension in `PaymentRequired.extensions`; the sponsoring extensions and `payment-identifier` act only on a declared extension, while `builder-code` attribution is attached by whichever party registered it. -### TRON approval resource sponsoring (new in 1.2.0) +### TRON approval resource sponsoring (new in 1.2.0, separate package since 2.1.0) `trc20ApprovalResourceSponsoring` (wire-schema version `1`) lets a payer make their **first** TRON Permit2 payment or channel deposit without holding TRX. Instead of broadcasting the one-time `approve(Permit2, MaxUint256)` itself, the client signs that transaction and attaches the signed bytes to the payment payload; the facilitator strictly decodes and validates them against the selected payment, temporarily delegates the Stake 2.0 Energy — and, when needed, Bandwidth — that the payer lacks, broadcasts the transaction unchanged, and reclaims the delegation afterwards through a recoverable state machine. | Party | What it does | |-------|--------------| | Resource server | **Opts in** — spread `declareTrc20ApprovalResourceSponsoringExtension()` into the route's `extensions`. The route must use `extra.assetTransferMethod: "permit2"`. | -| Client | **Nothing to configure** — `@bankofai/x402-tron` attaches the signed approval automatically when the server declared version `1`, the selected path uses Permit2, and the current Permit2 allowance is insufficient. | -| Facilitator | **Opts in** — register `createTrc20ApprovalResourceSponsoringExtension(runtime)` with a runtime built by `createTrc20ResourceSponsoringRuntime({ ... })` from `@bankofai/x402-tron`. | +| Client | **Opts in** (since 2.1.0) — register `client.registerExtension(createTrc20ApprovalResourceSponsoringClientExtension(signer))` after the payment schemes. It attaches the signed approval when the server declared version `1`, the selected path uses Permit2, and the current Permit2 allowance is insufficient. Without it, a sponsored payment fails with `trc20_approval_client_extension_not_registered`. | +| Facilitator | **Opts in** — register `createTrc20ApprovalResourceSponsoringExtension(runtime)` with a runtime built by `createTrc20ResourceSponsoringRuntime({ ... })`, both from `@bankofai/x402-tron-extensions`. A facilitator without the runtime returns `sponsor_runtime_unavailable`. | It applies to TRON `exact` (with `assetTransferMethod: "permit2"`), TRON `upto`, and the Permit2 **deposit/top-up** path of `batch-settlement`. It is not used for EIP-3009 transfers, nor for batch vouchers, claims, settles, or refunds. It sponsors only that one `approve` transaction — the scheme payload still remains the sole authority over amount, recipient, nonce, and deadline, and no fee is charged inside the approval. There is no new endpoint: the flow stays `402 Payment Required` → `PAYMENT-SIGNATURE` → `/verify` → `/settle`. ```typescript -import { declareTrc20ApprovalResourceSponsoringExtension } from "@bankofai/x402-extensions"; - -const route = { - price: { - amount: "1000000", - asset: "T...", - extra: { assetTransferMethod: "permit2" }, - }, - extensions: { - ...declareTrc20ApprovalResourceSponsoringExtension(), +import type { RoutesConfig } from "@x402/core/http"; +import { TRON_NILE } from "@bankofai/x402-tron"; +import { declareTrc20ApprovalResourceSponsoringExtension } from "@bankofai/x402-tron-extensions"; + +const routes: RoutesConfig = { + "GET /weather": { + accepts: [ + { + scheme: "exact", + network: TRON_NILE, + payTo: "T...", + price: { + amount: "1000000", + asset: "T...", + extra: { assetTransferMethod: "permit2" }, + }, + }, + ], + extensions: { + ...declareTrc20ApprovalResourceSponsoringExtension(), + }, }, }; ``` @@ -131,23 +143,22 @@ const route = { - The payer must be an **activated, single-signature TRON EOA** using the default owner permission. Multisig and custom-permission accounts are not supported. - Under the default `zero-first` approval strategy a **non-zero but insufficient** allowance is rejected with `approval_reset_required` — the SDK never inserts an implicit `approve(0)`. A token that is not a known Permit2 asset raises `approval_asset_unsupported` unless you configure a strategy for it with `createTrc20ApprovalPolicy`. - A production facilitator must back the runtime with a durable operation coordinator and run reconciliation at startup and on a schedule. The exported `InMemoryTrc20SponsoringCoordinator` is for tests and single-process development only. -- The [official facilitator](./core-concepts/OfficialFacilitator.md) does **not** currently enable this extension. TRON approval sponsoring requires a self-hosted facilitator with a resource-owner wallet that has Stake 2.0 capacity. +- The [official facilitator](./core-concepts/OfficialFacilitator.md) advertises this extension in `/supported`, but its production configuration sponsors **TRON Nile USDT only** and requires an API Key. Sponsoring on TRON Mainnet, or for other tokens, requires a self-hosted facilitator with a resource-owner wallet that has Stake 2.0 capacity. ::: --- ## Signers -Key custody is in [`@bankofai/agent-wallet`](https://github.com/BofAI/agent-wallet); the SDK never sees a raw private key. The signer factories build the chain client (viem / TronWeb) internally. +The TRON signer factories in `@bankofai/x402-tron` adapt a wallet — such as one resolved by [`@bankofai/agent-wallet`](https://github.com/BofAI/agent-wallet) — so the SDK never sees a raw private key, and build TronWeb internally. | Signer factory | Role | |----------|------| | `createClientTronSigner` | Client (TRON) | -| `createClientEvmSigner` | Client (EVM) | | `createFacilitatorTronSigner` | Facilitator (TRON) | -| `createFacilitatorEvmSigner` | Facilitator (EVM) | | `createAuthorizerTronSigner` | Authorizer (TRON, batch-settlement) | -| `createAuthorizerEvmSigner` | Authorizer (EVM, batch-settlement) | + +EVM signing uses the public signer adapters of official `@x402/evm` (for example `toClientEvmSigner` and `toFacilitatorEvmSigner`). The former `@bankofai/x402-evm` agent-wallet factories (`createClientEvmSigner`, `createFacilitatorEvmSigner`, `createAuthorizerEvmSigner`) were retired in 2.1.0; follow the [upstream EVM examples](https://github.com/x402-foundation/x402/tree/main/examples/typescript). --- @@ -181,7 +192,7 @@ Since 1.1.0 a client will only pay assets it recognizes from the default-asset r | Protected-route integration | ✅ (`paymentMiddlewareFromHTTPServer`, `x402HTTPResourceServer`) | | Multi-chain `accepts` advertisement | ✅ | | Gas-sponsoring extension, EVM (`eip2612GasSponsoring` / `erc20ApprovalGasSponsoring`) | ✅ | -| Resource-sponsoring extension, TRON (`trc20ApprovalResourceSponsoring`) | ✅ — new in 1.2.0; declare with `declareTrc20ApprovalResourceSponsoringExtension()` | +| Resource-sponsoring extension, TRON (`trc20ApprovalResourceSponsoring`) | ✅ — new in 1.2.0; declare with `declareTrc20ApprovalResourceSponsoringExtension()` from `@bankofai/x402-tron-extensions` | | Payment verification (via facilitator) | ✅ | | Payment settlement (via facilitator) | ✅ | @@ -198,10 +209,13 @@ Since 1.1.0 a client will only pay assets it recognizes from the default-asset r | Confirm transaction (receipt polling) | ✅ | | Extension hooks (`onBeforeSettle` / `onAfterSettle` / `onSettleFailure`) | ✅ | | EVM smart accounts — deployed accounts, ERC-7702 delegation, ERC-6492 counterfactual wallets | ✅ — signature verification is facilitator-side; ERC-6492 requires an explicit `eip6492AllowedFactories` allowlist | +| Pending settlement (`settlement_pending`) | ✅ — new in 2.0.0. When a transaction was broadcast but its receipt is not yet known, settlement returns the non-terminal `settlement_pending` with the original transaction ID; reconcile that transaction instead of resubmitting. TRON receipt waiting defaults to 90 s (`confirmationTimeoutMs` on `createFacilitatorTronSigner`) | +| Pending-settlement recovery, TRON | ✅ — new in 2.1.0. The TRON facilitator schemes save the original transaction ID (or GasFree relayer trace) before waiting for the receipt, so a retry of the same payment resumes it instead of broadcasting again. The default `InMemoryTronPendingSettlementStore` covers one process only; for restarts or multiple replicas, inject a persistent, shared `TronPendingSettlementStore` through the `pendingSettlementStore` constructor option. A failed save after broadcast returns `settlement_store_unavailable` (keeping the known transaction ID); an unhandled settlement callback error returns `settlement_execution_failed` | +| `upto` preflight reads, TRON | ✅ — new in 2.1.0. A failed or malformed allowance/balance read returns `chain_read_failed` before any settlement is broadcast | > The self-hosted example facilitator (`facilitator/basic`) exposes `/verify`, `/settle`, `/supported`. The official hosted facilitator additionally offers the settlement-record queries `GET /payments/tx/{tx_hash}` and `GET /payments`, plus `/health` — see [Official Facilitator](./core-concepts/OfficialFacilitator.md). Prometheus metrics are served on a separate monitoring port (`9001` in the shipped configs), not on the public API base. There is no `/fee/quote` endpoint: the SDK schemes carry no facilitator fee. > -> `HTTPFacilitatorClient` uses typed timeout errors and a 90-second default timeout since 1.1.0. Its rate-limit retry (3 attempts) applies to `getSupported()` only — `verify()` and `settle()` surface a 429 to the caller rather than retrying. +> Since 2.1.0, `HTTPFacilitatorClient` comes from official `@x402/core` `2.28.0`: it uses typed timeout errors and a 90-second default timeout, and the repository examples set `timeoutMs: 120_000` explicitly. After switching to the official HTTP/MCP packages, recheck your request timeouts. Its rate-limit retry (3 attempts) applies to `getSupported()` only — `verify()` and `settle()` surface a 429 to the caller rather than retrying. --- @@ -211,24 +225,23 @@ Since 1.1.0 a client will only pay assets it recognizes from the default-asset r |--------|---------|--------| | USDT (TRC-20) | `tron:728126428`, `tron:3448148188`, `tron:2494104990` | ✅ | | USDD (TRC-20) | `tron:728126428`, `tron:3448148188` | ✅ | -| USDT (BEP-20) | `eip155:56`, `eip155:97` | ✅ | -| USDC (BEP-20) | `eip155:56`, `eip155:97` | ✅ | -| DHLU (BSC testnet, ERC-3009) | `eip155:97` | ✅ | +| USDT (BEP-20) | `eip155:56`, `eip155:97` | ✅ (explicit asset) | +| USDC (BEP-20) | `eip155:56`, `eip155:97` | ✅ (explicit asset; the `eip155:56` address is in no shipped token registry) | | Official USDC (ERC-20, EIP-3009) | `eip155:8453`, `eip155:84532` | ✅ | -| Custom TRC-20 / BEP-20 | any | ✅ (via token registry / `EVM_TOKENS` config) | +| Custom TRC-20 / BEP-20 | any | ✅ (via the TRON token registry / an explicit `{ asset, amount, extra }` price) | -> Only some of these are **default assets**: USDT on TRON and BSC Mainnet, USDC on BSC Testnet and Base. Since 1.1.0 a client's spend controls reject every other asset — USDD, BSC Mainnet USDC, BSC Testnet USDT, DHLU, custom tokens — unless it is allowlisted via `spendControls.allowedAssets`. See [Network & Token Support](./core-concepts/network-and-token-support.md#supported-tokens). +> Only some of these are **default assets**: USDT on the three TRON networks and USDC on Base and Base Sepolia. Since 1.1.0 a client's spend controls reject every other asset — USDD, every BSC asset, custom tokens — unless it is allowlisted via `spendControls.allowedAssets`. See [Network & Token Support](./core-concepts/network-and-token-support.md#supported-tokens). --- ## Observability -All `@bankofai/x402-*` packages write through one process-global logger from `@bankofai/x402-core`. Call `setLogger(...)` once at startup to redirect logs to a file, `pino`/`winston`, or `noopLogger` to silence. +The TRON mechanism writes through a process-global logger exported by `@bankofai/x402-tron` (since 2.1.0; previously from `@bankofai/x402-core`). Call `setLogger(...)` once at startup to redirect logs to a file, `pino`/`winston`, or `noopLogger` to silence. Official `@x402/core` and `@x402/extensions` do not use this logger — register lifecycle hooks where you need their events logged. --- ## Legend - ✅ = Implemented -- ⏳ = Planned / In Progress -- ❌ = Not Planned +- ⚠️ = Partially implemented (see the notes column) +- ❌ = Not supported diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs-changelog/current/x402.md b/i18n/zh-Hans/docusaurus-plugin-content-docs-changelog/current/x402.md index 70441a61..62c3e8e2 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs-changelog/current/x402.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs-changelog/current/x402.md @@ -7,6 +7,46 @@ description: 'x402 支付协议、SDK 与 CLI 的版本发布记录。' x402 协议、SDK 与 [Wallet CLI 指引](/zh-Hans/wallet-cli/) 的版本发布记录。 +
+
2026-10-27
+
+ +### Facilitator 错误码补全 + +
文档修复
+ +- facilitator 错误列表补充了协议层的赞助原因(`approval_transaction_reused`、`sponsor_approval_lifetime_exceeded`、`sponsor_existing_delegation`)、`/settle` 的 `400 permit2_invalid_authorization`、`500 internal_error`,以及 GasFree 代理的 `502 bad_gateway`。 +- **Wallet CLI 命令参考**——新增常见错误码表(`missing_wallet_address`、`auth_required`、`invalid_option`、`no_matching_requirement`、`permit2_allowance_required` 等)及退出码,并补充 `bai recharge` 的规则:`--to`、代币默认值(Base 上 USDC,其他网络 USDT)和触发 `invalid_amount` 的最低金额。 + +👉 [Facilitator](/zh-Hans/x402/core-concepts/facilitator/) · [Wallet CLI 命令参考](/zh-Hans/wallet-cli/command-reference/) + +
+
+ +
+
2026-10-25
+
+ +### 文档对齐 SDK 2.1.0 与 Facilitator v2.2.2 + +
文档修复
+ +- **SDK 2.1.0**——SDK 相关页面按 2.1.0 版本组合更新:`@bankofai/x402-tron` 2.1.0 与新增的 `@bankofai/x402-tron-extensions` 2.1.0(两者需一起升级)运行在官方 `@x402/core` 2.28.0 之上,搭配官方 `@x402/*` HTTP/MCP 集成、`@x402/evm` 与 `@x402/extensions` 2.28.0。快速入门改为从 `@x402/core`、`@x402/fetch`、`@x402/express` 导入,并用 `new x402ResourceServer(...)` 取代 `@bankofai/x402-core` 的 `createResourceServer`(2.1 机制不使用它)。本地 EVM 包、`@bankofai/x402-extensions` 与 `typescript/packages/legacy/` 兼容包已在 2.1.0 删除(根目录 `legacy/`,含已退役的 Python SDK,早在 2.0.0 删除)。TRON 资源赞助现在需要显式注册 client 扩展;SDK 要求 Node.js 24.22.1+。官方 `@x402/evm` 不内置 BSC 默认资产,BSC 路由须用显式的 `{ asset, amount, extra }` 对象定价,client 也须放行 BSC 资产;在本文档涉及的网络中,默认资产现为 TRON 上的 USDT 与 Base / Base Sepolia 上的 USDC。 +- **待确认结算**——补充了 `settlement_pending`:它不是终态,应对账而不是重新提交。2.1.0 新增可注入的 `pendingSettlementStore`(默认的 `InMemoryTronPendingSettlementStore` 只覆盖单个进程),以及 `settlement_store_unavailable`、`settlement_execution_failed` 错误码,并把 `chain_read_failed`(此前已用于 `exact` 的 Permit2 读取)扩展到 `upto` 的预检读取。`HTTPFacilitatorClient` 现在来自官方 Core,默认超时 90 秒;示例设置为 120 秒。 +- **示例仅覆盖 TRON**——仓库示例现在只覆盖 TRON,卖家快速入门因此引导 BSC 与 Base 卖家使用官方 facilitator 或上游 `@x402/evm` 示例。官方 facilitator v2.2.1 与 v2.2.2 都是安全更新版本(更新 Node.js 与依赖;v2.2.2 还装入了修复 CVE-2026-111497 的系统 Brotli),文档中描述的行为不变。 +- **TRON ID 改为十进制**——示例和表格统一使用 `tron:728126428`(主网)、`tron:3448148188`(Nile)、`tron:2494104990`(Shasta),x402 SDK 仍接受十六进制写法作为输入,wallet-cli 的 `--network` 不接受。API Catalog 例外:它的 schema 目前只接受十六进制。 +- **官方 Facilitator 限流**——匿名调用每个 IP 每分钟 10 次,API Key 每分钟 1,000 次,`/verify` 与 `/settle` 分别计数(两者都限流)。超限返回 `429` 并带 `Retry-After`。此前文档写的是每分钟一次 `/settle`。 +- **Nile 资源赞助**——官方 Facilitator 在 `/supported` 中列出 `trc20ApprovalResourceSponsoring`,但仅在 Nile 为 Nile USDT 启用,且需要 API Key(否则返回 `sponsor_auth_required` / `sponsor_network_disabled`)。补充了 `GET /sponsoring/ready` 以及 `/verify`、`/settle` 的错误码。 +- **结算记录**——成功的结算按 (network, asset, payer, nonce) 由部分唯一索引保证唯一。这更正了 9 月 9 日记录中"表上没有唯一约束"的说法。 +- **API Catalog**——本地自检需要 Python 3.11+;提交清单补齐其余 CI 规则(`pay.md` 必含的字符串、TRON 第一条路由须为 `exact` + `permit2`、不得出现 `--scheme exact_gasfree`、`status` 四个键必填),并说明写死数量的测试需在同一个 PR 里更新。列表命令读取本地缓存,只有缓存不存在或缺少所需内容时才下载,因此缓存可能过期时请运行 `update-catalog` 刷新。 +- **Wallet CLI 命令参考**——改为以 `@tron-walletcli/wallet-cli@4.15.1` 为准,补充已知稳定币默认每笔最多 1 美元的上限(`amount_exceeds_limit`)、`--out`(二进制响应必须使用)、`--max-gasfree-fee-raw`,以及 `--max-raw-amount` 必须同时指定 `--token` 或 `--asset`。快速入门提示 TRON 上某代币的首次 `exact` 付款可能先广播一次 `approve(Permit2, MaxUint256)`;结果说明补充了结算后出现响应格式错误的情况(`retryPayment: false`)。快速入门还注明 wallet-cli Skill 锁定 4.14.0,配合 Skill 使用时应安装该版本。 +- **协议细节**——`402` 的付款要求放在 Base64 编码的 `PAYMENT-REQUIRED` 头中,响应体为 `{}`;验证失败的原因也在该头的 `error` 字段;`exact` / `upto` 的 Permit2 额度不足返回 `412 permit2_allowance_required`。EVM `exact` 还支持 `upfront` 付款流程。Permit2 载荷使用 `payload.permit2Authorization`。代币表删除了 DHLU(现有代码均不再引用),BSC 主网 USDC 标注为仅可作为显式资产;官方 Facilitator 的限流计数按实例;npm 包许可证为 Apache-2.0(仓库 LICENSE 为 MIT)。 + +👉 [SDK 功能](/zh-Hans/x402/sdk-features/) · [官方 Facilitator](/zh-Hans/x402/core-concepts/OfficialFacilitator/) · [上架服务](/zh-Hans/x402/api-catalog/list-your-service/) + +
+
+
2026-09-28
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 58f225b5..40921997 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/AGENTS.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/AGENTS.md @@ -16,7 +16,7 @@ import TabItem from '@theme/TabItem'; - `docs/faq.md` — 常见问题解答。 - `sidebars.js` — Docusaurus 侧边栏配置文件。 - `docusaurus.config.js` — Docusaurus 主配置文件。 -- `docs/sdk-features.md` — 仅 TypeScript 的 x402 SDK(`@bankofai/x402-*` 包)功能矩阵。 +- `docs/sdk-features.md` — 仅 TypeScript 的 x402 SDK(基于官方 `@x402/*` 包的 `@bankofai/x402-tron` 与 `@bankofai/x402-tron-extensions`)功能矩阵。 ## 3. 代码与文档的同步机制 @@ -28,8 +28,8 @@ import TabItem from '@theme/TabItem'; - 底层机制的变更 $\rightarrow$ 需更新 `core-concepts` 文档。 ## 4. 风格与规范 -- 以 **TypeScript** 作为主要代码示例(SDK 仅 TypeScript;此前的 Python SDK 已移至 `legacy/`)。 -- 优先提供可直接基于已发布 `@bankofai/x402-*` npm 包运行的代码示例。`examples/typescript/` 中的可运行代码可作为与包 API 一致时的参考实现。 +- 以 **TypeScript** 作为主要代码示例(SDK 仅 TypeScript;此前的 Python SDK 已在 x402 v2.0.0 中移除)。 +- 优先提供可直接基于已发布 npm 包(`@bankofai/x402-tron`、`@bankofai/x402-tron-extensions` 与官方 `@x402/*`)运行的代码示例。`examples/typescript/` 中的可运行代码可作为与包 API 一致时的参考实现。 - 所有 API 调用示例必须包含完整的错误处理逻辑。 - 内容撰写面向具有 **2–5 年经验** 的开发者。 - 必须使用 Docusaurus MDX 组件(``、``)来展示多语言代码。 @@ -58,7 +58,7 @@ import TabItem from '@theme/TabItem'; -- **网络标识**:必须遵循 `tron:` CAIP-2 格式。优先使用 `@bankofai/x402-tron` 导出的常量(`TRON_MAINNET`、`TRON_NILE`、`TRON_SHASTA`),不要硬编码旧的名称。 +- **网络标识**:必须遵循 `tron:` CAIP-2 格式(如 Nile 为 `tron:3448148188`);`tron:0xcd8690dc` 这类十六进制写法是已弃用的输入别名。优先使用 `@bankofai/x402-tron` 导出的常量(`TRON_MAINNET`、`TRON_NILE`、`TRON_SHASTA`),不要硬编码旧的名称。 - **签名标准**:TRON 签名必须引用 **TIP-712** 标准(请勿混淆为 EIP-712)。 - **地址格式**:Token 地址必须使用 Base58 编码格式(即以 `T` 开头的地址)。 - **节点接入**:节点访问需指向 TronGrid 端点。 @@ -126,7 +126,7 @@ import TabItem from '@theme/TabItem'; - `*/signers/` 目录中新增了签名器。 - 客户端 (Client) 或服务端 (Server) 新增了功能特性。 -**注意**:SDK 仅 TypeScript。更新文档时需对照已发布的 `@bankofai/x402-*` 包 API、`typescript/packages/` 的导出与 `examples/typescript/` 的参考源码交叉检查。 +**注意**:SDK 仅 TypeScript。更新文档时需对照已发布包(`@bankofai/x402-tron`、`@bankofai/x402-tron-extensions`、官方 `@x402/*`)的 API、`typescript/packages/` 的导出与 `examples/typescript/` 的参考源码交叉检查。 ## 12.开发常用命令 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/get-started.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/get-started.md index a411c026..14e31e86 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 @@ -5,18 +5,18 @@ description: "用 wallet-cli 查询目录和预览付费接口。" # Catalog 快速入门 -先按 [Wallet CLI 快速入门](/zh-Hans/wallet-cli/quickstart/)安装 `@tron-walletcli/wallet-cli@4.14.0`。目录查询不需要钱包或密码,支付预览和付款需要已配置账户。 +先按 [Wallet CLI 快速入门](/zh-Hans/wallet-cli/quickstart/)安装 Wallet CLI。目录查询不需要钱包或密码,支付预览和付款需要已配置账户。 ## 浏览目录 ```bash +wallet-cli x402 update-catalog -o json wallet-cli x402 provider-list -o json wallet-cli x402 provider-show dia -o json wallet-cli x402 endpoint-list dia -o json -wallet-cli x402 update-catalog -o json ``` -`provider-list` 可按支持的网络、类别和 capability 过滤。`update-catalog` 会更新本地缓存。 +`update-catalog` 把目录下载到本地缓存。`provider-list`、`provider-show` 和 `endpoint-list` 读取该缓存,只有缓存不存在或缺少所需内容时才从目录下载;它们不会刷新缓存,需要最新的服务和价格时请重新运行 `update-catalog`。`provider-list` 支持 `--network`、`--category` 和 `--capability` 过滤。 ## 选择接口和网络 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/index.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/index.md index cf73d5ad..b2bd5e14 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/index.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/api-catalog/index.md @@ -35,7 +35,7 @@ import ThemedImage from '@theme/ThemedImage'; - **[前端目录站](https://bankofai.io/catalog)**:给人浏览、比较服务。 - **wallet-cli**:在命令行里搜索、查看、直接付费调用。 -- **MCP**:`@bankofai/x402-mcp` 让 Agent 能通过 MCP 为 x402 端点付款。支持目录发现的 MCP(在 MCP 客户端里按名称浏览目录)尚未发布,当前请用 `wallet-cli x402 provider-list` 做发现。 +- **MCP**:`@x402/mcp`(SDK 2.1.0 起使用的官方 MCP 集成)让 Agent 能通过 MCP 为 x402 端点付款。支持目录发现的 MCP(在 MCP 客户端里按名称浏览目录)尚未发布,当前请用 `wallet-cli x402 provider-list` 做发现。 ## 目录里有什么 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 130bde1f..322b1c12 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 @@ -163,7 +163,7 @@ SunPump 服务的真实文件 `providers/sunpump-token-launch/catalog.json`: ### pay.md 怎么写 -`pay.md` 是人和 Agent 都会读的调用说明,建议包含三部分:服务基本信息、各端点的地址与价格、可直接复制的调用示例。目录仓库的 CI 测试要求每个 `pay.md` 都包含带 `--network tron:728126428` 和 `--scheme exact` 的 `wallet-cli x402 pay` 示例、提到 `exact_gasfree`,并覆盖 Base 主网(`eip155:8453`)。SunPump 的真实文件 `providers/sunpump-token-launch/pay.md`: +`pay.md` 是人和 Agent 都会读的调用说明,建议包含三部分:服务基本信息、各端点的地址与价格、可直接复制的调用示例。目录仓库的 CI 测试要求每个 `pay.md` 都包含带 `--network tron:728126428` 和 `--scheme exact` 的 `wallet-cli x402 pay` 示例、提到 `exact_gasfree`,并覆盖 Base 主网:文中必须出现 `Base Mainnet`、`eip155:8453`、以 `-base` 结尾的 gateway provider、`USDC` 和 `EIP-3009`,且不得出现 `Sepolia` 或 `eip155:84532`。SunPump 的真实文件 `providers/sunpump-token-launch/pay.md`: ````markdown # SunPump Agent Token Launch API @@ -286,20 +286,21 @@ CI 会强制以下规则,建议提交前逐条对照: - `version` 必须为 `1`。 - `fqn` 为小写字母/数字/连字符,且与目录名一致。 - `category` 必须是合法类目之一(见[参考](./reference.md#合法类目))。 -- `chains` 至少一条,使用 CAIP-2 风格的链 ID。TRON 链 ID 只能是 `tron:0x2b6653dc`、`tron:0xcd8690dc` 或 `tron:0x94a9059e`。CI 测试要求每个服务都列出 Base 主网 `eip155:8453`,并拒绝 Base Sepolia `eip155:84532`。 +- `chains` 至少一条,使用 CAIP-2 风格的链 ID。TRON 链 ID 只能是 `tron:0x2b6653dc`、`tron:0xcd8690dc` 或 `tron:0x94a9059e`,十进制形式(`tron:728126428`)会被拒绝,见[链 ID](./reference.md#链-id)。CI 测试要求每个服务都列出 Base 主网 `eip155:8453`,并拒绝 Base Sepolia `eip155:84532`。 - `isFirstParty`、`isFeatured`(布尔值)与 `featuredTags`(字符串数组,可为空 `[]`)为**必填**,缺一即校验失败。 - 每个 endpoint 的 `method` 必须大写、`path` 以 `/` 开头、`maxPriceUsd` 不小于 `minPriceUsd`。 - `serviceUrl`、各端点 `url` 和各路由 `url` 都必须以 `https://` 开头。 - 不允许出现未定义的字段——顶层、端点、路由、`i18n.` 和 `status` 都会拒绝未知字段。 - `x402Routes` 在 schema 中是选填,但 CI 测试要求每个端点恰好发布一条 Base 主网路由:`scheme` 为 `exact`、`assetTransferMethod` 为 `eip3009`,`provider` 以 `-base` 结尾。每条路由的 `network` 都必须出现在 `chains` 里,`exact_gasfree` 只能用于 TRON 网络。每条路由都需要 `network`、`provider`、`scheme` 和 `url`;`exact` 路由还必须带 `assetTransferMethod`(`permit2` 或 `eip3009`),`exact_gasfree` 路由则必须**省略**该字段。同一网络可以出现多次——TRON 通常同时发布 `exact` 与 `exact_gasfree` 两条路由——只要每组 `(provider, network, scheme, url)` 唯一即可。旧的 `fee` / `feeConfig` 字段会被拒绝。详见[参考](./reference.md#x402routes--多网络路由)。 +- 凡有 TRON 路由的端点,第一条 TRON 路由必须是 `exact` + `permit2`(默认方式);服务级 `description`(含 `i18n` 翻译)不得包含 `--scheme exact_gasfree`。 - 服务与每个 endpoint 都必须提供 `i18n.zh-CN` 的 `title`、`subtitle`、`description`、`useCase`。 -- 如填写 `status`,取值只能是:`catalog` 为 `listed`/`unlisted`;`gateway` 为 `configured`/`unknown`/`unavailable`;`payment` 为 `paid-route`/`mainnet`/`testnet`/`unknown`;`upstream` 为 `public`/`authenticated`/`unknown`/`unavailable`。 +- `status` 可不填;如填写,四个键都必须给出,取值只能是:`catalog` 为 `listed`/`unlisted`;`gateway` 为 `configured`/`unknown`/`unavailable`;`payment` 为 `paid-route`/`mainnet`/`testnet`/`unknown`;`upstream` 为 `public`/`authenticated`/`unknown`/`unavailable`。 - `pay.md` 必须与 `catalog.json` 一同提交,两份文件都会被敏感信息扫描。 - 不得包含任何密钥、私钥或内网地址。 ## 第 2 步:本地自检 -提交前先安装校验依赖,再在本地跑一遍校验、构建和单元测试(与 CI 的步骤相同): +提交前先安装校验依赖,再在本地跑一遍校验、构建和单元测试(与 CI 的步骤相同)。脚本需要 Python 3.11 或更高版本(CI 用 3.12);在 3.10 上会报 `ImportError: cannot import name 'UTC' from 'datetime'`。 ```bash pip install -r requirements.txt @@ -310,6 +311,10 @@ python3 -m unittest discover -s tests 前两条会输出 `validated N provider(s)` 和 `built N provider(s) into dist`,N 是仓库里全部服务的数量(包括你新加的)。 +:::note 测试里写死的数量 +`tests/test_build.py` 固定了目录当前的若干总数,例如所有服务的 Base 主网路由总数。新服务即使通过 `validate.py`,也可能在这些断言上失败(例如 `AssertionError: 20 != 18`);请在同一个 PR 里更新期望值。 +::: + ## 第 3 步:提交 Pull Request 把这两份文件加入[目录仓库](https://github.com/BofAI/x402-catalog)对应目录,并一起提交重新生成的 `dist/` 文件: 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 a6892fe8..a30db1f2 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 @@ -59,7 +59,7 @@ description: catalog.json / pay.md 的字段定义、合法类目与链 ID,以 | 字段 | 类型 | 说明 | |---|---|---| -| `network` | string | 该路由结算所在的标准 CAIP-2 链 ID(如 `tron:0x2b6653dc`、`eip155:56`、`eip155:8453`)。旧的 TRON 别名如 `tron:nile` 会被 schema 校验拒绝。 | +| `network` | string | 该路由结算所在的 CAIP-2 链 ID(如 `tron:0x2b6653dc`、`eip155:56`、`eip155:8453`)。TRON 只接受[链 ID](#链-id) 中列出的十六进制形式;`tron:nile` 之类的别名和十进制形式 `tron:728126428` 都会被目录的校验拒绝。 | | `provider` | string | 处理该网络的 gateway provider `fqn` | | `scheme` | string | 该路由的 x402 支付方案:`exact`,或在 TRON 上 `exact_gasfree` —— 由每条路由各自声明 | | `assetTransferMethod` | string | 每条 `exact` 路由都**必须填写**:TRON/BSC 路由使用 `permit2`,Base USDC 路由使用 `eip3009`。只有 `exact_gasfree` 路由应省略该字段。 | @@ -68,7 +68,7 @@ description: catalog.json / pay.md 的字段定义、合法类目与链 ID,以 构建时该字段以 `x402_routes` 透传到产物。存在时,调用方/Agent 按目标支付链选择对应路由;顶层 `url` 仍是默认路由。 :::note GasFree 路由 -在 TRON 上,可以为同一端点在 `exact` 路由之外再加一条 `exact_gasfree` 路由:由 relayer 代付网络能量、并从支付代币里扣除手续费,付款方无需 TRX。GasFree 路由仅限 TRON,且不能带 `assetTransferMethod`。自 x402 SDK 1.0.1 起(当前版本 1.2.0),relayer 费用由客户端估算,因此目录路由**不得**再发布旧的 `fee` 或 `feeConfig` 字段。 +在 TRON 上,可以为同一端点在 `exact` 路由之外再加一条 `exact_gasfree` 路由:由 relayer 代付网络能量、并从支付代币里扣除手续费,付款方无需 TRX。GasFree 路由仅限 TRON,且不能带 `assetTransferMethod`。自 x402 SDK 1.0.1 起,relayer 费用由客户端估算,因此目录路由**不得**再发布旧的 `fee` 或 `feeConfig` 字段。 ::: 例如一个端点可以为每条支持的链各提供一条路由 —— TRON 主网、BSC 主网和 Base 主网,各有自己的 `provider` 和 `scheme`。调用时把 `wallet-cli x402 pay` 指向所选路由的 `url`,并传入匹配的 `--network` / `--scheme`: @@ -88,7 +88,7 @@ wallet-cli x402 pay --dry-run -o json 'https://x402-gateway.bankofai.io/provider ### status 块 -`status` 为选填,描述服务各环节的状态,包含 `catalog` / `gateway` / `payment` / `upstream` 四个键。未提供时,构建产物(服务详情)会自动填充默认值: +`status` 为选填,描述服务各环节的状态,包含 `catalog` / `gateway` / `payment` / `upstream` 四个键;填写时四个键都必须给出。未提供时,构建产物(服务详情)会自动填充默认值: ```json { "catalog": "listed", "gateway": "unknown", "payment": "unknown", "upstream": "unknown" } @@ -105,7 +105,7 @@ wallet-cli x402 pay --dry-run -o json 'https://x402-gateway.bankofai.io/provider ## pay.md -与 `catalog.json` 同目录提交、面向人和 Agent 的可读调用说明,为**必交**文件。建议包含:服务基本信息(FQN、入口地址、类目、结算链)、各端点的地址与价格,以及可直接复制的调用示例。目录仓库的 CI 测试要求包含带 `--network tron:728126428` 和 `--scheme exact` 的 `wallet-cli x402 pay` 示例、提到 `exact_gasfree`,并覆盖 Base 主网(`eip155:8453`)。该文件与 `catalog.json` 一样会经过敏感信息扫描(见下)。 +与 `catalog.json` 同目录提交、面向人和 Agent 的可读调用说明,为**必交**文件。建议包含:服务基本信息(FQN、入口地址、类目、结算链)、各端点的地址与价格,以及可直接复制的调用示例。目录仓库的 CI 测试要求包含带 `--network tron:728126428` 和 `--scheme exact` 的 `wallet-cli x402 pay` 示例、提到 `exact_gasfree`,并覆盖 Base 主网(须出现 `Base Mainnet`、`eip155:8453`、`-base`、`USDC` 和 `EIP-3009`,不得出现 `Sepolia` 或 `eip155:84532`)。该文件与 `catalog.json` 一样会经过敏感信息扫描(见下)。 ## 合法类目 @@ -122,6 +122,10 @@ security shopping storage translation `chains` 采用 CAIP-2 风格的链标识,主网与测试网均可识别: +:::note TRON ID 格式 +目录 schema 只接受下表中十六进制形式的 TRON 链 ID。x402 SDK(2.0.0 起)和 Wallet CLI 使用十进制 CAIP-2 ID —— `tron:728126428`(主网)、`tron:3448148188`(Nile)、`tron:2494104990`(Shasta)。SDK 仍把十六进制值作为同一条链的已弃用别名接受;Wallet CLI 的全局 `--network`(`x402 pay` 和账户类命令使用)不接受——请用十进制 ID 或 `tron`、`nile`、`shasta` 等别名;只有目录筛选 `x402 provider-list --network` 也接受十六进制写法。因此 CLI 示例传 `--network tron:728126428`,而 `catalog.json` 写 `tron:0x2b6653dc`。 +::: + | 链 | ID | |---|---| | TRON 主网 | `tron:0x2b6653dc` | @@ -214,6 +218,8 @@ CI 构建后生成静态快照 `dist/`,由 Catalog Server 通过 `/api/` 路 ## 本地构建与运行 +需要 Python 3.11 或更高版本。 + ```bash # 安装校验依赖(jsonschema) pip install -r requirements.txt diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/OfficialFacilitator.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/OfficialFacilitator.md index 8a67d851..c342fad7 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/OfficialFacilitator.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/OfficialFacilitator.md @@ -62,11 +62,13 @@ Facilitator 由官方持续维护和升级,包括: | 模式 |限速 |说明 | |-----|-----|-----| -| **匿名调用(Anonymous Mode)** | 官方服务:每个 IP 每分钟最多 1 次;自建部署未配置 `rate_limit.anonymous` 时,默认每个 IP 每分钟最多 10 次(可自行调整) | 不需要 API Key,适用于本地开发和功能测试 | -| **API Key 调用(API Key Mode)** | 官方服务:每个 API Key 每分钟最多 1000 次;自建部署未配置 `rate_limit.authenticated` 时采用相同默认值(可自行调整) | 需要 API Key,适用于生产环境和高频支付请求 | +| **匿名调用(Anonymous Mode)** | 官方服务:每个 IP 每分钟最多 10 次,`/verify` 与 `/settle` 分别计数;这也是自建部署未配置 `rate_limit.anonymous` 时的默认值(可自行调整) | 不需要 API Key,适用于本地开发和功能测试 | +| **API Key 调用(API Key Mode)** | 官方服务:每个 API Key 每分钟最多 1000 次,`/verify` 与 `/settle` 分别计数;自建部署未配置 `rate_limit.authenticated` 时采用相同默认值(可自行调整) | 需要 API Key,适用于生产环境和高频支付请求 | 两种模式的调用方式完全相同,但在 **身份识别与接口限速策略** 上有所不同。 +> **计数按实例进行。** 官方生产配置使用 `rate_limit.store: memory`,每个 facilitator 实例各自维护计数器;落到不同实例上的请求不会累计到同一个总数里。自建部署默认同样使用内存存储——如需在多个副本间共享计数,请设置 `rate_limit.store: redis`(并配置 `redis_url`)。 + @@ -78,8 +80,8 @@ Facilitator 由官方持续维护和升级,包括: 在匿名模式下: -- `/settle` 接口会启用 **限速** -- **官方服务按每个 IP 每分钟最多调用 1 次**;自建部署未配置 `rate_limit.anonymous` 时,默认按每个 IP 每分钟最多调用 **10 次**,且可自行调整。 +- `/verify` 与 `/settle` 接口会启用 **限速**,各自独立计数 +- **官方服务对每个接口按每个 IP 每分钟最多调用 10 次**,与自建部署未配置 `rate_limit.anonymous` 时的默认值相同,且可自行调整。 该模式主要用于: @@ -96,7 +98,7 @@ curl -X POST https://facilitator.bankofai.io/settle \ -d '{ ... }' ``` -虽然匿名模式可以正常调用所有核心接口,但由于 `/settle` 的调用频率非常低,因此 **不适合生产环境使用**。 +虽然匿名模式可以正常调用所有核心接口,但由于 `/verify` 与 `/settle` 的单 IP 限额较低,因此 **不适合生产环境使用**。 如果你的应用需要处理真实用户支付或较高频率的请求,建议使用 **API Key 调用模式**。 @@ -121,7 +123,7 @@ curl -X POST https://facilitator.bankofai.io/settle \ 当 Facilitator 识别到 API Key 后: -- 在官方服务上,`/settle` 限额提升至**每个 API Key 每分钟 1000 次** +- 在官方服务上,`/verify` 与 `/settle` 的限额各自提升至**每个 API Key 每分钟 1000 次** 这意味着你的服务可以支持 **生产级别的支付吞吐量**。 @@ -256,23 +258,31 @@ curl -X POST https://facilitator.bankofai.io/settle \ |------|------|------| | GET | `/health` | 服务健康检查 | | GET | `/supported` | 查询支持的支付能力和配置 | -| POST | `/verify` | 验证支付载荷有效性 | +| POST | `/verify` | 验证支付载荷有效性(**受限速保护**) | | POST | `/settle` | 执行链上结算(**受限速保护**) | | GET | `/payments/tx/{tx_hash}` | 按结算交易哈希查询支付记录 | | GET | `/payments?network=&nonce=[&asset=&payer=]` | 按链上授权身份查询支付记录 | | GET | `/payments` | 已认证卖家的结算记录流(`?limit=&offset=`;`limit` 默认 `50`、上限 `200`——超过 `200` 会被静默压到 `200`,不会报错;`offset` 默认 `0`) | +| GET | `/sponsoring/ready` | TRON 授权资源赞助的就绪状态(`?network=` 只查单个网络);就绪返回 HTTP `200`,否则(启动中、恢复中、降级或未启用赞助)返回 `503` | -> **不存在** `/fee/quote` 端点,各方案也不收取 facilitator 费用。限速仅作用于 `/settle` 接口,其他接口不受限速影响。 +> **不存在** `/fee/quote` 端点,各方案也不收取 facilitator 费用。限速作用于 `/verify` 与 `/settle`(分别计数),其他接口不限速。超出限额的请求返回 HTTP `429`、响应体 `{"error":"rate_limit_exceeded"}`,并带 `Retry-After` 头。 ### 官方服务结算的网络与方案 | 网络 | 环境 | |---|---| -| `tron:0x2b6653dc`(TRON 主网)· `tron:0xcd8690dc`(Nile) | 主网 · 测试网 | +| `tron:728126428`(TRON 主网)· `tron:3448148188`(Nile) | 主网 · 测试网 | | `eip155:56`(BSC)· `eip155:97`(BSC 测试网) | 主网 · 测试网 | | `eip155:8453`(Base)· `eip155:84532`(Base Sepolia) | 主网 · 测试网 | -以上网络均注册了 `exact`、`upto` 与 `batch-settlement`;TRON 在服务持有 GasFree 中继凭证的网络上(TRON 主网与 Nile)额外注册 `exact_gasfree`。以所连接部署的 `/supported` 返回为准。官方 facilitator 目前未启用 `trc20ApprovalResourceSponsoring` 扩展——TRON 授权资源赞助需要自建 facilitator。但在其 EVM 网络(BSC 与 Base)上,官方确实为每一条 EVM 网络注册了 ERC-20 授权 gas 代付扩展——不过只有当资源服务端在路由上声明该扩展时,代付才会真正生效。 +以上网络均注册了 `exact`、`upto` 与 `batch-settlement`;TRON 在服务持有 GasFree 中继凭证的网络上(TRON 主网与 Nile)额外注册 `exact_gasfree`。以所连接部署的 `/supported` 返回为准。TRON 网络以十进制 CAIP-2 标识返回;旧的十六进制写法(`tron:0x2b6653dc`、`tron:0xcd8690dc`)仍可作为输入别名。 + +`/supported` 列出两个扩展: + +- `erc20ApprovalGasSponsoring`——为官方服务的每一条 EVM 网络(BSC 与 Base)注册。 +- `trc20ApprovalResourceSponsoring`——TRON 授权资源赞助**仅在 Nile 上启用**,仅针对配置的资产(Nile USDT),并且**需要 API Key**。匿名请求若携带该扩展,会被以 `sponsor_auth_required` 拒绝;已认证请求若针对 TRON 主网,会被以 `sponsor_network_disabled` 拒绝。`GET /sponsoring/ready` 可查询赞助运行时是否就绪。 + +无论哪种代付,只有当资源服务端在路由上声明了对应扩展时才会真正生效。 ### 支付记录查询 @@ -292,7 +302,7 @@ curl -X POST https://facilitator.bankofai.io/settle \ > 提供 API Key 时,这两个接口只返回与你的账户关联的支付记录,不会看到其他卖家的数据。 :::danger 不带 API Key 时 -匿名请求下,`tx_hash` 与 `network` + `nonce` 查询**不添加卖家过滤**,返回结果可能包含已绑定卖家的记录——任何持有准确标识符的人都能查到对应记录。`/payments` 列表接口仍要求身份验证,因此不存在免认证的列表接口;但这两个查询接口也没有限流(官方服务按每个 IP 每分钟 1 次的匿名限流只覆盖 `/settle`),而结算 tx hash 又是链上公开数据。请把结算元数据视为事实上公开,而非按卖家隔离。 +匿名请求下,`tx_hash` 与 `network` + `nonce` 查询**不添加卖家过滤**,返回结果可能包含已绑定卖家的记录——任何持有准确标识符的人都能查到对应记录。`/payments` 列表接口仍要求身份验证,因此不存在免认证的列表接口;但这两个查询接口也没有限流(官方服务按每个 IP 每分钟 10 次的匿名限流只覆盖 `/verify` 与 `/settle`),而结算 tx hash 又是链上公开数据。请把结算元数据视为事实上公开,而非按卖家隔离。 **以上描述的是当前实现行为,不代表推荐的访问控制策略。** 想让查询限定在自己账户范围内请带上 API Key,并且绝不要把结算 tx hash 或其 nonce 当作秘密。 ::: @@ -303,7 +313,7 @@ curl -X POST https://facilitator.bankofai.io/settle \ **Q:不配置 API Key 能正常运行吗?** -可以运行,但官方服务将 `/settle` 限制为每个 IP 每分钟 1 次。自建部署未配置 `rate_limit.anonymous` 时,默认每个 IP 每分钟 10 次,且可自行调整。匿名访问只适合测试,任何真实流量都必须配置 API Key。 +可以运行,但官方服务将 `/verify` 与 `/settle` 各自限制为每个 IP 每分钟 10 次,与自建部署未配置 `rate_limit.anonymous` 时的默认值相同,且可自行调整。匿名访问只适合测试,任何真实流量都必须配置 API Key。 **Q:API Key 会过期吗?** @@ -311,7 +321,7 @@ curl -X POST https://facilitator.bankofai.io/settle \ **Q:我可以在多个项目中使用同一个 API Key 吗?** -可以,同一个 API Key 可以在多个服务实例中复用。在官方服务上,这些实例共享该 Key 每分钟 1000 次 `/settle` 调用的限额;不会因为使用这个 Key 的服务器增多而分别重置配额。 +可以,同一个 API Key 可以在多个服务实例中复用。在官方服务上,限额按 API Key 而非调用方服务器计算:你的各个实例共用该 Key 每分钟 1000 次 `/settle` 调用的限额(`/verify` 另有独立的 1000 次),不会每台服务器各得一份配额。这些计数器按 facilitator 实例维护(`rate_limit.store: memory`),因此限额在每个 facilitator 实例内生效,而不是一个全局总数。 **Q:我想更换 API Key,怎么操作?** diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/client-server.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/client-server.md index 55cc651a..3702c53c 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/client-server.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/client-server.md @@ -23,7 +23,7 @@ import ThemedImage from '@theme/ThemedImage'; - **发起请求**:向资源服务器发送初始 HTTP 请求。 - **处理支付要求**:解析 `402 Payment Required` 响应,并提取支付详情。 -- **管理代币授权**:为普通 ERC-20/TRC-20 代币授权 Permit2(一次性 `approve(Permit2)`);ERC-3009 代币无需授权。由谁广播因链而异。**在 TRON 上**,client 会在首次付款时自动广播该授权、能量自付——除非 server 声明了 `trc20ApprovalResourceSponsoring` 扩展(SDK 1.2.0+),此时 client 只签名不广播,由 facilitator 赞助能量/带宽并广播。**在 EVM 上 client 从不广播任何交易**:要么在 server 声明了 `eip2612GasSponsoring` 或 `erc20ApprovalGasSponsoring` 时附上一笔已签名但未广播的授权交由 facilitator 转发;要么在没有任何相关扩展时,验款直接以 `permit2_allowance_required` 失败,授权必须在首次付款前另行完成。详见 [SDK 功能矩阵](../sdk-features.md#extensions)。 +- **管理代币授权**:为普通 ERC-20/TRC-20 代币授权 Permit2(一次性 `approve(Permit2)`);ERC-3009 代币无需授权。由谁广播因链而异。**在 TRON 上**,client 会在首次付款时自动广播该授权、能量自付(默认 `allowanceMode: "auto"` 时如此;设为 `"skip"` 则由应用自行处理授权)——除非 server 声明了 `trc20ApprovalResourceSponsoring` 扩展,此时 client 只签名不广播,由 facilitator 赞助能量/带宽并广播。2.1.0 起,这需要用 `client.registerExtension(createTrc20ApprovalResourceSponsoringClientExtension(signer))` 注册 `@bankofai/x402-tron-extensions` 中的 client 扩展;未注册时,受赞助的付款会以 `trc20_approval_client_extension_not_registered` 失败,不会退回由 client 自行广播。**在 EVM 上 client 从不广播任何交易**:要么附上链下的 EIP-2612 permit 签名(server 声明了 `eip2612GasSponsoring` 时),或附上一笔已签名但未广播的授权交易交由 facilitator 转发(`erc20ApprovalGasSponsoring`);要么在没有任何相关扩展时,验款直接以 `permit2_allowance_required` 失败,授权必须在首次付款前另行完成。详见 [SDK 功能矩阵](../sdk-features.md#extensions)。 - **准备支付载荷**:根据服务端的要求,构建并签署支付载荷。 - **携带支付凭证重发请求**:在请求头中附加 `PAYMENT-SIGNATURE` 并重新发送请求。 @@ -41,7 +41,7 @@ import ThemedImage from '@theme/ThemedImage'; ### 核心职责 -- **定义支付要求**:对未附带有效支付凭证的请求响应 HTTP `402 Payment Required`,并在响应体中详细说明支付要求。 +- **定义支付要求**:对未附带有效支付凭证的请求响应 HTTP `402 Payment Required`,并在 Base64 编码的 `PAYMENT-REQUIRED` 响应头中详细说明支付要求(响应体默认为 `{}`)。 - **验证支付载荷**:调用 Facilitator 服务对传入的签名载荷进行验证。 - **结算交易**:验证通过后,通过 Facilitator 提交交易以完成资金结算。 - **交付资源**:支付确认无误后,向客户端返回所请求的资源。 @@ -66,6 +66,8 @@ import ThemedImage from '@theme/ThemedImage'; }} /> +图中是客户端看到的顺序:资源在结算之后才到达。在默认的 `authorization` 流程下,服务端会先执行处理逻辑再结算,并在结算成功后才放出响应(见上文第 5 步)。 + ## 总结 在 x402 协议体系中: diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/facilitator.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/facilitator.md index 8fa8adb4..2e866511 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/facilitator.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/facilitator.md @@ -19,7 +19,7 @@ Facilitator 是一种中间件服务,主要负责: - **支付验证**:确认客户端提交的签名载荷严格符合服务端声明的支付要求。 - **支付结算**:将验证通过的交易提交至区块链网络,并监控上链状态。 -- **结算记录**:每次 settle 尝试写入一行——记录层不做任何去重、也没有唯一约束,因此失败与重试都会累积。实际上每个授权身份至多只会有一条*成功*记录,但这来自链上的重放保护(同一笔授权只能结算一次),而非记录层的去重。它同时支持记录查询,调用方认证后才按卖家过滤。保存失败只会记日志,绝不影响 `/settle` 的返回。 +- **结算记录**:每次拿到结算机制结果(成功或失败)的 settle 尝试写入一行,因此失败与重试都会累积。在结算之前或结算过程中被拒绝的请求不写记录:请求体格式错误(400)、赞助访问被拒(403/503)、Permit2 重放防护错误,以及内部错误(500)。表上有一个针对 (`network`, `asset`, `payer`, `nonce`) 且条件为 `status = 'success'` 的部分唯一索引,保证每笔授权至多一条*成功*记录,与链上的重放保护(同一笔授权只能结算一次)互为补充。它同时支持记录查询,调用方认证后才按卖家过滤。保存失败只会记日志,绝不影响 `/settle` 的返回。 - **结果反馈**:将验证与结算结果返回给服务端,作为服务端决定是否交付资源的依据。 > **注意**:Facilitator **不持有资金**,也不充当托管方——它仅根据客户端签名的指令执行验证与链上操作。 @@ -31,7 +31,7 @@ Facilitator 是一种中间件服务,主要负责: - **降低运维门槛**:服务端无需直接处理区块链节点交互或 RPC 管理。 - **协议标准化**:确保跨服务的支付验证与结算流程保持一致。 - **快速集成**:服务端仅需极少的区块链开发工作即可开始接收支付。 -- **资源费管理**:Facilitator 负责支付交易执行所需的 TRX(能量 Energy 和带宽 Bandwidth)/BNB,降低了服务端的持有成本。自 SDK 1.2.0 起,TRON 的 Facilitator 还可以选择启用 `trc20ApprovalResourceSponsoring` 扩展,向付款方临时委托自己的 Stake 2.0 能量(必要时还有带宽),使付款方的首笔 `approve(Permit2)` 无需 TRX。该能力需要主动启用:Facilitator 必须注册赞助 runtime,并配套有界的赞助策略与持久化的操作协调器。无论哪种代付,资源服务端都还要在路由上声明对应扩展——正是这个声明让 SDK 客户端附带代付载荷(Facilitator 本身并不校验它,因此非 SDK 客户端可以绕过这一步)。EVM 网络上有对应的能力——为付款方的 ERC-20 `approve` 代付 gas——但 SDK 不会替你接好:自建 Facilitator 必须自行注册该扩展。官方 Facilitator 已为其服务的 EVM 网络注册,详见[官方 Facilitator](./OfficialFacilitator.md)。 +- **资源费管理**:Facilitator 负责支付交易执行所需的 TRX(能量 Energy 和带宽 Bandwidth)/BNB,降低了服务端的持有成本。自 SDK 1.2.0 起,TRON 的 Facilitator 还可以选择启用 `trc20ApprovalResourceSponsoring` 扩展,向付款方临时委托自己的 Stake 2.0 能量(必要时还有带宽),使付款方的首笔 `approve(Permit2)` 无需 TRX。该能力需要主动启用:Facilitator 必须注册赞助 runtime,并配套有界的赞助策略与持久化的操作协调器。无论哪种代付,资源服务端都还要在路由上声明对应扩展——正是这个声明让 SDK 客户端附带代付载荷(Facilitator 本身并不校验它,因此非 SDK 客户端可以绕过这一步)。EVM 网络上有对应的能力——为付款方的 ERC-20 `approve` 代付 gas——但 SDK 不会替你接好:自建 Facilitator 必须自行注册该扩展。官方 Facilitator 已为其服务的 EVM 网络注册,并在 Nile 上为持有 API Key 的调用方启用了 TRON 授权资源赞助,详见[官方 Facilitator](./OfficialFacilitator.md)。 虽然开发者可以选择在本地自行实现验证与结算逻辑,但使用 Facilitator 能显著加速开发周期并确保协议实现的规范性。 @@ -74,7 +74,7 @@ Facilitator 是一种中间件服务,主要负责: 如果您希望完全掌控结算钱包、RPC 节点、能量管理,或注册哪些网络与方案,又或有特定的隐私/合规要求,可以选择自己部署 Facilitator 服务。 > ⚠️ **自托管安全提示:** -> - 自托管 Facilitator 需要一个**有余额的专用钱包**来支付区块链手续费。该钱包通过 `@bankofai/agent-wallet` 解析、在进程外解锁(例如 `AGENT_WALLET_PASSWORD`)——原始私钥不会进入服务进程 +> - 自托管 Facilitator 需要一个**有余额的专用钱包**来支付区块链手续费。该钱包通过 `@bankofai/agent-wallet` v3 解析:使用 `privy` 或 `wallet_cli` provider 时私钥留在服务进程之外;`raw_secret` provider 会把明文私钥存在配置中,仅适用于开发环境 > - **这个 Facilitator 钱包应与您的收款钱包分开**,请专门创建一个新钱包 > - Facilitator 钱包只需存入少量代币(用于手续费),不要存入大量资金 > - 不要把原始私钥写进 `.env`、配置文件或命令行,**更不要提交到 Git 或分享给任何人** @@ -91,30 +91,35 @@ Facilitator 是一种中间件服务,主要负责: |------|------|------| | GET | `/health` | 服务健康检查 | | GET | `/supported` | 查询支持的支付能力和配置 | -| POST | `/verify` | 验证支付载荷有效性 | -| POST | `/settle` | 执行链上结算(官方 Facilitator 下**受限速保护**);并持久化一条结算记录 | +| POST | `/verify` | 验证支付载荷有效性(**受限速保护**,见下文) | +| POST | `/settle` | 执行链上结算(**受限速保护**,见下文);并持久化一条结算记录 | | GET | `/payments/tx/{tx_hash}` | 按结算交易哈希查询支付记录(认证后仅返回当前卖家的记录) | | GET | `/payments?network=&nonce=[&asset=&payer=]` | 按链上授权身份查询支付记录(认证后仅返回当前卖家的记录) | | GET | `/payments` | 已认证卖家的结算记录流(`?limit=&offset=`;`limit` 默认 `50`、上限 `200`——超过 `200` 会被静默压到 `200`,不会报错;`offset` 默认 `0`) | +| GET | `/sponsoring/ready` | TRON 授权资源赞助的就绪状态(`?network=` 只查单个网络);就绪返回 HTTP `200`,否则(启动中、恢复中、降级或未启用赞助)返回 `503` | | GET | `/metrics` | Prometheus 指标(运维用途;仅当监控与主端口共用时才在主端口暴露) | | ALL | `/mainnet/*` · `/nile/*` | GasFree Open API 透明代理(HMAC 签名)——由 TRON `exact_gasfree` 方案内部使用 | 记录查询的失败会返回以下错误码:无匹配记录时 `404 not_found`;身份查询参数不完整(传了 `network`/`nonce`/`asset`/`payer` 中的部分,但缺少必需的 `network`+`nonce` 组合)时 `400 invalid_identity_query`;调用 `/payments` 但既未提供身份参数也未提供 API Key 时 `400 missing_identity_or_auth`。 +`/verify` 与 `/settle` 保持 x402 的响应结构(`invalidReason` / `errorReason`)。除 SDK 自身的原因外,服务还会返回:请求体格式错误时 `400 invalid_json` 或 `missing_parameters`;`413` `{"code":"body_too_large","message":…}`(默认上限 1 MiB);`429` `{"error":"rate_limit_exceeded"}`;请求携带 `trc20ApprovalResourceSponsoring` 但部署不予赞助时 `403 sponsor_auth_required`、`sponsor_network_disabled` 或 `sponsor_pay_to_invalid`;暂时性状况返回 `503` 并带 `Retry-After`(`sponsor_owner_busy`、`sponsor_recovery_in_progress`、`sponsor_storage_unavailable`,以及仅 `/settle` 会返回的 `permit2_authorization_busy`、`permit2_storage_unavailable`、`permit2_nonce_check_unavailable`)。`/settle` 时 nonce 已被消耗的 Permit2 授权会以 `permit2_nonce_consumed`(HTTP 200)失败,不会广播新交易;授权格式错误时 `/settle` 返回 `400 permit2_invalid_authorization`。受赞助的授权还可能在协议层失败(HTTP 200,放在 `invalidReason` / `errorReason` 里):`approval_transaction_reused`(已签名的 approve 已被用于另一笔不同的支付请求)、`sponsor_approval_lifetime_exceeded`(已签名 approve 的有效期超过 630 秒),以及仅 `/settle` 会返回的 `sponsor_existing_delegation`。未预期的异常返回 `500 internal_error`。GasFree 代理只挂在 `/mainnet` 和 `/nile` 下(其他路径直接返回普通的 `404`),上游失败或响应过大时返回 `502 bad_gateway`。 + > **不存在** `/fee/quote` 端点,各方案也完全不收取 facilitator 费用。支付记录以链上授权身份(`network` + `scheme` + `asset` + `payer` + `nonce`)为键,而非客户端提供的 payment ID。 --- ## 限速策略 -`/settle` 端点根据调用方的认证状态动态执行限速: +`/verify` 与 `/settle` 端点根据调用方的认证状态动态执行限速,两个端点各自独立计数: | 模式 | 限速 | 认证方式 | |------|------|----------| -| **已认证** | 官方服务:每个 API Key 每分钟最多 1000 次;自建部署未配置 `rate_limit.authenticated` 时采用相同默认值(可自行调整) | 请求头携带 `X-API-KEY: ` | -| **匿名** | 官方服务:每个 IP 每分钟最多 1 次;自建部署未配置 `rate_limit.anonymous` 时,默认每个 IP 每分钟最多 10 次(可自行调整) | 不携带 API Key | +| **已认证** | 官方服务:每个 API Key 每分钟最多 1000 次,`/verify` 与 `/settle` 分别计数;自建部署未配置 `rate_limit.authenticated` 时采用相同默认值(可自行调整) | 请求头携带 `X-API-KEY: ` | +| **匿名** | 官方服务:每个 IP 每分钟最多 10 次,`/verify` 与 `/settle` 分别计数;这也是自建部署未配置 `rate_limit.anonymous` 时的默认值(可自行调整) | 不携带 API Key | + +其他端点(`/supported`、`/payments/*`、`/sponsoring/ready`、`/health`)不限速。超出限额时返回 HTTP `429` `{"error":"rate_limit_exceeded"}`,并带 `Retry-After` 头。 -其他端点(`/verify`、`/supported`、`/payments/*`)不单独限速。 +> **计数按实例进行。** 官方生产配置使用 `rate_limit.store: memory`,每个 facilitator 实例各自维护计数器;落到不同实例上的请求不会累计到同一个总数里。自建部署默认同样使用内存存储——如需在多个副本间共享计数,请设置 `rate_limit.store: redis`(并配置 `redis_url`)。 > **提示**:任何生产级别的工作负载都建议通过[管理后台](https://admin-facilitator.bankofai.io)申请 API Key,以解锁更高的限速配额。 @@ -132,7 +137,7 @@ Facilitator 是一种中间件服务,主要负责: - **携带有效 `X-API-KEY`**——查询结果按该 Key 对应的卖家过滤。 - **匿名调用 `tx_hash` 或 `network` + `nonce` 查询接口**——当前实现**不添加卖家过滤**,返回结果可能包含已绑定卖家的记录。 - **`/payments` 列表接口**——仍要求身份验证:不带身份参数又不带 API Key 时返回 `400`,只给部分身份参数同样返回 `400`,不会退化成记录流。 -- **这两个查询接口没有限流**——官方服务按每个 IP 每分钟 1 次的匿名限流只作用于 `/settle`,记录查询接口没有单独限流。 +- **这两个查询接口没有限流**——官方服务的匿名限流只作用于 `/verify` 与 `/settle`,记录查询接口没有单独限流。 结算 tx hash 属于链上公开数据,而 `network` + `nonce` 查询还能查到**失败**的结算——包括广播前就失败的那些,它们根本没有 tx hash,也就无从通过其他途径查到。实际后果是:**结算元数据应当被视为事实上公开的**,尽管并不存在免认证的列表接口。响应体从不包含卖家 id,因此查询暴露的是某条已绑定卖家记录的支付元数据,而不是卖家归属本身。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/gateway.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/gateway.md index d342b5c8..c315ebee 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/gateway.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/gateway.md @@ -74,7 +74,7 @@ import ThemedImage from '@theme/ThemedImage'; ### 面向 AI Agent:一个目录,汇聚海量 API,按需付费 -- **当前用 CLI 发现** —— `wallet-cli x402 provider-list` / `provider-show` / `endpoint-list` 可定位所需 API 及其路由。通过 MCP 付款由 `@bankofai/x402-mcp` 支持;支持目录发现的 MCP 尚未发布。 +- **当前用 CLI 发现** —— `wallet-cli x402 provider-list` / `provider-show` / `endpoint-list` 可定位所需 API 及其路由。通过 MCP 付款由 `@x402/mcp` 支持;支持目录发现的 MCP 尚未发布。 - **按次计费** —— 无需订阅,无最低消费。 - **实时价格透明** —— 网关在 `402` 响应中返回实时计算的价格,客户端授权会绑定所选支付要求;报价本身并不是网关的密码学签名。 - **无账号、无密钥** —— 钱包即身份,无需注册或管理任何 API Key。 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 d59b88c9..868d8729 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 @@ -49,13 +49,13 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: "error": "Payment required", "resource": { "url": "http://example.com/protected", - "description": null, - "mimeType": null + "description": "", + "mimeType": "" }, "accepts": [ { "scheme": "exact", - "network": "tron:0xcd8690dc", + "network": "tron:3448148188", "amount": "100", "asset": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", "payTo": "", @@ -79,8 +79,8 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: "error": "Payment required", "resource": { "url": "http://example.com/protected", - "description": null, - "mimeType": null + "description": "", + "mimeType": "" }, "accepts": [ { @@ -123,12 +123,12 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: | `resource` | 关于请求资源的信息 | | `accepts` | 接受的支付选项数组 | | `scheme` | 支付方案(`exact`、`upto`、`batch-settlement`、`exact_gasfree`) | -| `network` | 网络标识符——三个 TRON 标识(`tron:0x2b6653dc`、`tron:0xcd8690dc`、`tron:0x94a9059e`)或任意 `eip155:`:资源服务端默认注册 `eip155:*`,因此该字段并不限于 `eip155:56` / `97` / `8453` / `84532`。能否结算则另由 facilitator 已配置的网络决定 | +| `network` | 网络标识符——三个 TRON 标识(`tron:728126428`、`tron:3448148188`、`tron:2494104990`)或任意 `eip155:`:资源服务端默认注册 `eip155:*`,因此该字段并不限于 `eip155:56` / `97` / `8453` / `84532`。能否结算则另由 facilitator 已配置的网络决定 | | `amount` | 支付金额,以最小单位计(例如:100 = 0.0001 USDT) | | `asset` | TRC-20/BEP-20 代币合约地址 | | `payTo` | 卖家的钱包地址 | | `maxTimeoutSeconds` | 支付有效期的最大时长 | -| `extra` | 方案相关数据——`assetTransferMethod`(`eip3009` / `permit2`)、EIP-3009 资产、以及同时支持 EIP-2612 的 permit2 资产的 `name`/`version`,以及声明了非默认付款流程时的 `paymentFlow`(`upfront` 或 `escrow`)——内置方案全部使用默认的 `authorization` 流程,该字段不会写入 `extra`。其中不含费用对象:各方案不收取 facilitator 费用。 | +| `extra` | 方案相关数据——`assetTransferMethod`(`eip3009` / `permit2`)、EIP-3009 资产、以及同时支持 EIP-2612 的 permit2 资产的 `name`/`version`,以及路由选择了非默认付款流程时的 `paymentFlow`(`upfront` 或 `escrow`)——默认的 `authorization` 流程不会写入 `extra`。TRON 方案与 EVM `upto` / `batch-settlement` 只支持 `authorization`;EVM `exact` 还支持 `upfront`。其中不含费用对象:各方案不收取 facilitator 费用。 | | `extensions` | 支付方案的附加上下文(如 EVM gas 赞助、TRON 的 `trc20ApprovalResourceSponsoring`、payment-identifier) | ## 支付签名结构 @@ -143,7 +143,7 @@ x402 定义了一组标准化 HTTP 标头用于支付通信: "x402Version": 2, "accepted": { "scheme": "exact", - "network": "tron:0xcd8690dc", + "network": "tron:3448148188", "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 5500f375..970c33de 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 @@ -7,8 +7,8 @@ import TabItem from '@theme/TabItem'; ## TRON 网络标识符 -x402 采用 CAIP-2 网络标识符格式:`tron:`。 -应用代码中优先使用 `@bankofai/x402-tron` 导出的常量(`TRON_MAINNET`、`TRON_NILE`、`TRON_SHASTA`),不要手动复制不透明的 hex 字符串。 +x402 采用 CAIP-2 网络标识符格式:`tron:`(十进制链 ID)。 +应用代码中优先使用 `@bankofai/x402-tron` 导出的常量(`TRON_MAINNET`、`TRON_NILE`、`TRON_SHASTA`),不要手动复制标识符字符串。 ### 标识符参考表 @@ -18,7 +18,7 @@ x402 采用 CAIP-2 网络标识符格式:`tron:`。 | **TRON Shasta** | `tron:2494104990` | `TRON_SHASTA` | TRON Shasta 测试网 | | **TRON Nile** | `tron:3448148188` | `TRON_NILE` | TRON Nile 测试网 | -> **TRON 标识格式**:自 `@bankofai/x402-tron` 2.0.0 起,SDK 常量使用十进制 CAIP-2 引用。旧的十六进制形式(`tron:0x2b6653dc`、`tron:0xcd8690dc`、`tron:0x94a9059e`)仍可作为输入别名使用,官方 facilitator 与 API Catalog 目前返回的也是十六进制形式。 +> **TRON 标识格式**:自 `@bankofai/x402-tron` 2.0.0 起,SDK 常量使用十进制 CAIP-2 引用。旧的十六进制形式(`tron:0x2b6653dc`、`tron:0xcd8690dc`、`tron:0x94a9059e`)仍可作为输入别名使用,并会被规范化为十进制形式。官方 facilitator 的 `/supported` 返回十进制标识;API Catalog 目前仍列出十六进制形式。 ## BSC 网络标识符 @@ -30,7 +30,7 @@ x402 采用 CAIP-2 网络标识符格式:`tron:`。 | **BSC Mainnet** | `eip155:56` | BSC 主网 (生产环境) | | **BSC Testnet** | `eip155:97` | BSC 测试网 | -> **注意**:自托管 Facilitator 的 YAML 配置**只接受规范的 CAIP-2 标识符**——`eip155:56`、`eip155:97`、`eip155:8453`、`eip155:84532`、`tron:0x2b6653dc`、`tron:0xcd8690dc`、`tron:0x94a9059e`。`bsc:mainnet`、`tron:nile` 这类易读别名不会被解析,启动时会直接报错。 +> **注意**:自托管 Facilitator 的 YAML 配置**只接受规范的 CAIP-2 标识符**——`eip155:56`、`eip155:97`、`eip155:8453`、`eip155:84532`、`tron:728126428`、`tron:3448148188`、`tron:2494104990`。已弃用的十六进制 TRON 标识(`tron:0x…`)仍被接受,并会规范化为十进制。`bsc:mainnet`、`tron:nile` 这类易读别名不会被解析,启动时会直接报错。 ## Base 网络标识符 @@ -75,18 +75,17 @@ x402 支持 **TRC-20、BEP-20 和 ERC-20** 代币。TRON/BSC 路由使用各自 | **USDD** | `tron:728126428` | `TXDk8mbtRbXeYuMNS83CfKPaYYT8XWv9Hz` | | **USDD** | `tron:3448148188` | `TGjgvdTWWrybVLaVeFqSyVqJQWjxqRYbaK` | | **USDT** | `eip155:56` | `0x55d398326f99059fF775485246999027B3197955` | -| **USDC** | `eip155:56` | `0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d` | +| **USDC** | `eip155:56` | `0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d`(不在任何内置代币注册表中——仅能作为显式资产) | | **USDT** | `eip155:97` | `0x337610d27c682E347C9cD60BD4b3b107C9d34dDd` | | **USDC** | `eip155:97` | `0x64544969ed7EBf5f083679233325356EbE738930` | -| **DHLU** | `eip155:97` | `0x375cADdd2cB68cE82e3D9B075D551067a7b4B816` | | **USDC** | `eip155:8453` | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` | | **USDC** | `eip155:84532` | `0x036CbD53842c5426634e7929541eC2318f3dCF7e` | -> **默认资产与需显式放行的资产(SDK 1.1.0 起)**:默认资产注册表在 TRON(`tron:728126428`、`tron:3448148188`、`tron:2494104990`)与 BSC 主网(`eip155:56`)上解析 **USDT**,在 BSC 测试网(`eip155:97`)与 Base(`eip155:8453`、`eip155:84532`)上解析 **USDC**。注册表还为本页未列表的二十条 EVM 网络(MegaETH、Monad、Polygon、Arbitrum、Mezo、Radius、XDC、Celo、Flare 等)内置了默认资产。上表中的其余代币——TRON USDD、BSC 主网 USDC、BSC 测试网 USDT、DHLU 以及任何自定义代币——都属于「仅由服务端公布」:1.1.0 的客户端消费管控默认开启,除非你通过 `spendControls.allowedAssets` 放行,否则客户端会拒绝支付。CLI 资产选择请参见 [wallet-cli 命令参考](/zh-Hans/wallet-cli/command-reference/)。 +> **默认资产与需显式放行的资产(SDK 1.1.0 起)**:默认资产注册表在 TRON(`tron:728126428`、`tron:3448148188`、`tron:2494104990`,来自 `@bankofai/x402-tron`)上解析 **USDT**,在 Base(`eip155:8453`、`eip155:84532`,来自官方 `@x402/evm` 2.28.0)上解析 **USDC**。`@x402/evm` 还为本页未列表的其他 EVM 网络(Ethereum、Polygon、Arbitrum、Avalanche、Celo、Sei、MegaETH、Monad、XDC、Flare 等)内置了默认资产,但**不包括 BSC**:BSC 路由必须用显式的 `{ asset, amount, extra }` 对象定价。上表中的其余代币——TRON USDD、所有 BSC 资产以及任何自定义代币——都属于「仅由服务端公布」:1.1.0 的客户端消费管控默认开启,除非你通过 `spendControls.allowedAssets` 放行,否则客户端会拒绝支付。CLI 资产选择请参见 [wallet-cli 命令参考](/zh-Hans/wallet-cli/command-reference/)。 -> **扩展支持**:协议具有高度的可扩展性。通过 TRON 代币注册表(`@bankofai/x402-tron` 的 `registerToken`)或 server 的 `EVM_TOKENS` 配置表,您可以轻松配置并支持任意自定义的 TRC-20/BEP-20 代币。 +> **扩展支持**:协议具有高度的可扩展性。通过 TRON 代币注册表(`@bankofai/x402-tron` 的 `registerToken`)或在 server 路由上使用显式的 `{ asset, amount, extra }` 价格,您可以轻松配置并支持任意自定义的 TRC-20/BEP-20 代币。 -> **关于 `exact` 方案的代币选择**:EIP-3009 代币(如 Base 官方 USDC、BSC 测试网 DHLU)通过 `transferWithAuthorization` 无 gas 结算。普通 ERC-20 代币(如 BSC USDC/USDT、TRON USDT/USDD)通过 Permit2 路径结算——客户端首次付款时自动广播一次性 `approve(Permit2)`;在 TRON 上,若 server 声明了 `trc20ApprovalResourceSponsoring`(SDK 1.2.0+),则改为客户端签名、由 facilitator 赞助并广播。每种代币的结算方式由你在 server 端 `accepts[].price.extra` 里配置,SDK 会在协议数据中以 `accepts[].extra` 下发:EIP-3009 → `{ name, version }`;普通 ERC-20 → `{ assetTransferMethod: "permit2" }`。若某个 permit2 资产同时实现了 EIP-2612,`extra` 会在 `assetTransferMethod` 之外一并带上 `{ name, version }`;反过来,省略这对字段正是服务端告诉客户端「跳过 EIP-2612」的方式。两条代付路径都位于 permit2 分支内,因此对 EIP-3009 资产一概不适用。在 permit2 资产上,客户端签名无 gas 的 EIP-2612 permit 需要同时满足:具备 `readContract` 能力(由签名方或已配置的 RPC 提供)、服务端声明了 `eip2612GasSponsoring` 扩展、`extra` 里 `name` 与 `version` 都在、且当前 Permit2 额度尚不足以覆盖本次支付。注意这里的不对称:**缺少**读取能力会直接跳过 permit,而读取**抛错**则会被捕获、签名照常进行。否则客户端会*尝试* ERC-20 授权 gas 代付,这条路径要求 `readContract` 能力、服务端声明另一个独立的 `erc20ApprovalGasSponsoring` 扩展、签名方既能签原始交易又能报告交易计数,同样也要求现有额度不足;此时由客户端签名一笔 `MaxUint256` 的 `approve`——始终是最大值,与支付金额无关——由 facilitator 负责广播。两条路径都不满足时,载荷里不会带任何代付扩展。内置默认资产中带该标记的是 MegaETH MegaUSD(主网)以及 Mezo mUSD 与 Radius SBC(主网与测试网均有)。 +> **关于 `exact` 方案的代币选择**:EIP-3009 代币(如 Base 官方 USDC)通过 `transferWithAuthorization` 无 gas 结算。普通 ERC-20 代币(如 BSC USDC/USDT、TRON USDT/USDD)通过 Permit2 路径结算,需要一次性 `approve(Permit2)`——在 TRON 上客户端首次付款时自动广播(EVM 上从不广播,见下文的代付路径);在 TRON 上,若 server 声明了 `trc20ApprovalResourceSponsoring`(SDK 1.2.0+),则改为客户端签名、由 facilitator 赞助并广播(从 2.1.0 起须注册 `@bankofai/x402-tron-extensions` 中的客户端扩展)。每种代币的结算方式由你在 server 端 `accepts[].price.extra` 里配置,SDK 会在协议数据中以 `accepts[].extra` 下发:EIP-3009 → `{ name, version }`;普通 ERC-20 → `{ assetTransferMethod: "permit2" }`。若某个 permit2 资产同时实现了 EIP-2612,`extra` 会在 `assetTransferMethod` 之外一并带上 `{ name, version }`;反过来,省略这对字段正是服务端告诉客户端「跳过 EIP-2612」的方式。两条代付路径都位于 permit2 分支内,因此对 EIP-3009 资产一概不适用。在 permit2 资产上,客户端签名无 gas 的 EIP-2612 permit 需要同时满足:具备 `readContract` 能力(由签名方或已配置的 RPC 提供)、服务端声明了 `eip2612GasSponsoring` 扩展、`extra` 里 `name` 与 `version` 都在、且当前 Permit2 额度尚不足以覆盖本次支付。注意这里的不对称:**缺少**读取能力会直接跳过 permit,而读取**抛错**则会被捕获、签名照常进行。否则客户端会*尝试* ERC-20 授权 gas 代付,这条路径要求 `readContract` 能力、服务端声明另一个独立的 `erc20ApprovalGasSponsoring` 扩展、签名方能签原始交易,并能获取交易计数(由签名方或已配置的 RPC 提供),同样也要求现有额度不足;此时由客户端签名一笔 `MaxUint256` 的 `approve`——始终是最大值,与支付金额无关——由 facilitator 负责广播。两条路径都不满足时,载荷里不会带任何代付扩展。内置默认资产中带 `supportsEip2612` 标记的是 MegaETH MegaUSD(主网)以及 Mezo mUSD 与 Radius SBC(主网与测试网均有)。 ## 安全签名 @@ -118,8 +117,8 @@ x402 定义了五种命名支付方案。其中四种按链族提供完整的 cl `exact` 方案支付公布的准确金额,覆盖两种代币转账路径: -- **EIP-3009 `transferWithAuthorization`**:适用于原生支持该标准的代币(如 Base 官方 USDC、BSC 测试网 DHLU)。无 gas:无需 `approve`;客户端签署类型化数据授权,facilitator 在链上调用 `transferWithAuthorization`。 -- **Permit2**:适用于不实现 ERC-3009 的普通 ERC-20/TRC-20 代币(如 BSC USDC/USDT、TRON USDT/USDD)。客户端签署 Permit2 witness,facilitator 通过 `x402ExactPermit2Proxy` 合约结算。需要一次性 `approve(Permit2)`;客户端首次付款时自动广播。在 TRON 上,SDK 1.2.0 新增了 `trc20ApprovalResourceSponsoring` 扩展——若 server 声明了它,client 只签名而不广播该授权,由 facilitator 委托能量/带宽并广播,因此付款方授权时无需 TRX。 +- **EIP-3009 `transferWithAuthorization`**:适用于原生支持该标准的代币(如 Base 官方 USDC)。无 gas:无需 `approve`;客户端签署类型化数据授权,facilitator 在链上调用 `transferWithAuthorization`。 +- **Permit2**:适用于不实现 ERC-3009 的普通 ERC-20/TRC-20 代币(如 BSC USDC/USDT、TRON USDT/USDD)。客户端签署 Permit2 witness,facilitator 通过 `x402ExactPermit2Proxy` 合约结算。需要一次性 `approve(Permit2)`;在 TRON 上客户端首次付款时自动广播,在 EVM 上则须事先授权或通过 gas 代付扩展转发。在 TRON 上,SDK 1.2.0 新增了 `trc20ApprovalResourceSponsoring` 扩展——若 server 声明了它,client 只签名而不广播该授权,由 facilitator 委托能量/带宽并广播,因此付款方授权时无需 TRX。从 2.1.0 起,客户端必须注册 `@bankofai/x402-tron-extensions` 中的 `createTrc20ApprovalResourceSponsoringClientExtension(signer)`,否则付款会以 `trc20_approval_client_extension_not_registered` 失败。 `exact` 方案遵循 **x402 Foundation** 发布的 **v2 链路格式**:标准 v2 客户端可直接向本 SDK 的服务端发起付款请求,本 SDK 客户端也可直接访问任何 v2 兼容的服务端——无需项目特定的转换。转账授权数据在 EIP-3009 路径下位于 `payload.authorization`,在 Permit2 路径下位于 `payload.permit2Authorization`。 @@ -133,7 +132,7 @@ x402 定义了五种命名支付方案。其中四种按链族提供完整的 cl ### `auth-capture` 方案 -面向可退款 Base Commerce Payments 的 EVM client 实现:先授权资金,之后再执行 capture、void 或 refund。当前发布的 SDK 仅提供 `@bankofai/x402-evm/auth-capture/client`;server 与 facilitator 实现尚未发布,因此暂时无法只依靠发布包完成端到端部署。 +面向可退款 Base Commerce Payments 的 EVM client 实现:先授权资金,之后再执行 capture、void 或 refund。官方 `@x402/evm` 包(SDK 自 2.1.0 起用它处理 EVM)目前仅提供 `@x402/evm/auth-capture/client`;server 与 facilitator 实现尚未发布,因此暂时无法只依靠发布包完成端到端部署。 ### `exact_gasfree` 方案 @@ -193,7 +192,7 @@ CLI 取的是服务端 `accepts` 列表中第一条匹配你过滤条件的支 | 核心组件 | TRON/BSC/Base 实现详情 | | :----------- | :----------------------------------------- | -| **网络环境** | 三个 TRON 标识(`tron:728126428`、`tron:2494104990`、`tron:3448148188`)以及任意 `eip155:`——客户端与资源服务端默认注册的都是 `eip155:*`,SDK 为 `eip155:56` / `97` / `8453` / `84532` 之外的二十条 EVM 网络也内置了默认资产。但真正能结算的范围由 facilitator 显式配置的网络决定 | +| **网络环境** | 三个 TRON 标识(`tron:728126428`、`tron:2494104990`、`tron:3448148188`)以及任意 `eip155:`——客户端与资源服务端默认注册的都是 `eip155:*`,官方 `@x402/evm` 为 Base、Base Sepolia 及许多其他 EVM 网络内置了默认资产,但不包括 BSC(`eip155:56` / `97` 需显式指定资产)。但真正能结算的范围由 facilitator 显式配置的网络决定 | | **代币标准** | TRC-20 代币(默认内置 USDT 和 USDD 支持)、BEP-20 代币、ERC-20 代币(Base 官方 USDC) | | **签名机制** | TIP-712 / EIP-712 类型化数据签名 | | **支付方案** | `exact`、`upto`、`batch-settlement`、`exact_gasfree`(TRON) | @@ -213,7 +212,7 @@ registerToken(TRON_NILE, { }); ``` -在**资源服务器**侧,自定义 EVM 代币通过在 server 的 `src/chains/evm.ts` 中的 `EVM_TOKENS` 表添加一条目来公布——一个显式的 `{ asset, amount, extra }` 对象。添加一条链仅需一条表项;无需改动 SDK。 +在**资源服务器**侧,自定义 EVM 代币通过在路由的 `accepts` 中使用显式的 `{ asset, amount, extra }` 价格对象来公布;无需改动 SDK。(旧示例 server 的 `EVM_TOKENS` 表已随 EVM 示例在 x402 v2.1.0 中移除,请参考[上游 EVM 示例](https://github.com/x402-foundation/x402/tree/main/examples/typescript)。) 注册完成后,即可在 TRON 价格中使用自定义代币符号(例如 `"0.001 MYT"`)。 @@ -226,4 +225,4 @@ x402 专为区块链架构深度定制,提供了原生的 TRC-20/BEP-20/ERC-20 - **开发环境**:推荐优先使用 **测试网** 进行开发与调试。 - **默认结算资产**:TRON/BSC 路由使用各自配置的稳定币;Base 使用官方 **USDC**。 - **安全机制**:TIP-712 / EIP-712 类型化数据签名机制确保了安全且最小化信任 (Trust-minimized) 的支付授权流程。 -- **扩展能力**:可通过 TRON 代币注册表(`registerToken`)或 server 的 `EVM_TOKENS` 配置表灵活扩展支持任意自定义的 **TRC-20/BEP-20 代币**。 +- **扩展能力**:可通过 TRON 代币注册表(`registerToken`)或显式的 `{ asset, amount, extra }` 路由价格灵活扩展支持任意自定义的 **TRC-20/BEP-20 代币**。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/wallet.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/wallet.md index 1c1cc387..9e9d75ac 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/wallet.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/core-concepts/wallet.md @@ -56,9 +56,7 @@ x402 协议采用类型化数据签名来执行安全的支付授权。 ## 代币授权 -对于 `exact` 支付方案,普通 ERC-20/TRC-20 代币(如 BSC USDC/USDT、TRON USDT/USDD)通过 Permit2 路径结算。客户端需授权 Permit2 合约划转代币——一次性 `approve(Permit2, max)`。在 TRON 上,客户端 SDK 会在首次付款时自动广播此授权;在 EVM 上则从不广播——当 server 声明了 gas 代付扩展时,客户端附上一笔已签名但未广播的授权交由 facilitator 转发,否则授权必须另行完成,不然验款会以 `permit2_allowance_required` 失败。在 TRON 上,当 resource server 声明了 `trc20ApprovalResourceSponsoring`(SDK 1.2.0+)时,client 只签名 `approve(Permit2, MaxUint256)` 而不广播——由 facilitator 临时委托付款方所缺的能量(必要时还有带宽)并广播,因此付款方首笔授权无需 TRX。该路径要求付款方是已激活的单签名 TRON EOA。ERC-3009 代币(如 BSC 测试网 DHLU)无需授权——通过 `transferWithAuthorization` 无 gas 结算。 - -x402 客户端 SDK 会自动处理此操作。 +对于 `exact` 支付方案,普通 ERC-20/TRC-20 代币(如 BSC USDC/USDT、TRON USDT/USDD)通过 Permit2 路径结算。客户端需授权 Permit2 合约划转代币——一次性 `approve(Permit2, max)`。在 TRON 上,客户端 SDK 会在首次付款时自动广播此授权;在 EVM 上则从不广播——当 server 声明了 gas 代付扩展时,客户端附上 EIP-2612 permit 签名或一笔已签名但未广播的授权交由 facilitator 转发,否则授权必须另行完成,不然验款会以 `permit2_allowance_required` 失败。在 TRON 上,当 resource server 声明了 `trc20ApprovalResourceSponsoring`(SDK 1.2.0+)时,client 只签名 `approve(Permit2, MaxUint256)` 而不广播——由 facilitator 临时委托付款方所缺的能量(必要时还有带宽)并广播,因此付款方首笔授权无需 TRX。该路径要求付款方是已激活的单签名 TRON EOA。从 2.1.0 起,客户端必须注册 `@bankofai/x402-tron-extensions` 中的 `createTrc20ApprovalResourceSponsoringClientExtension(signer)`,否则付款会以 `trc20_approval_client_extension_not_registered` 失败。ERC-3009 代币(如 Base 官方 USDC)无需授权——通过 `transferWithAuthorization` 无 gas 结算。 ## 网络节点端点 @@ -80,7 +78,7 @@ x402 客户端 SDK 会自动处理此操作。 | 网络环境 (Network) | RPC 端点 (Endpoint) | | :------------------ | :------------------------------- | | **Mainnet** (主网) | `https://bsc-dataseed.binance.org` | -| **Testnet** (测试网) | `https://data-seed-prebsc-1-s1.binance.org:8545` | +| **Testnet** (测试网) | `https://bsc-testnet-rpc.publicnode.com` | --- 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 2e3f6a32..5b290ae8 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 @@ -11,7 +11,7 @@ x402 唤醒了长期闲置的 HTTP `402 Payment Required` 状态码,将其转 #### x402 是商业产品吗? -**不是。** x402 是 x402 协议针对区块链的开源实现,遵循 MIT 许可协议发布。您无需购买任何商业产品即可自由使用。 +**不是。** x402 是 x402 协议针对区块链的开源实现。[代码仓库](https://github.com/BofAI/x402)采用 MIT 许可协议,而已发布的 npm 包 `@bankofai/x402-tron` 与 `@bankofai/x402-tron-extensions` 在其 `package.json` 中声明的是 `Apache-2.0`(官方 `@x402/*` 包同样如此)。您无需购买任何商业产品即可自由使用。 #### 为什么要摒弃传统支付渠道或 API 密钥? @@ -25,13 +25,13 @@ x402 唤醒了长期闲置的 HTTP `402 Payment Required` 状态码,将其转 #### 支持哪些语言和框架? -x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发布: +x402 是**仅 TypeScript** 的 SDK:TRON 相关包以 `@bankofai/x402-tron` 与 `@bankofai/x402-tron-extensions` 发布,Core、EVM 与框架集成使用官方 `@x402/*` 包: - **服务端中间件**:Express、Fastify、Hono、Next.js -- **客户端**:包装 `fetch`(`@bankofai/x402-fetch`)、Axios、MCP 传输 +- **客户端**:包装 `fetch`(`@x402/fetch`)、Axios、MCP 传输 - **Facilitator**:链无关引擎,按方案 verify + settle -此前的 Python SDK 已移至 `legacy/` 仅供参考。 +已退役的 Python SDK 与旧的根目录 `legacy/` 归档已在 x402 v2.0.0 中移除,`typescript/packages/legacy/` 下的兼容 npm 包也已在 v2.1.0 中移除。 ### Facilitator @@ -62,7 +62,7 @@ x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发 x402 定义了五种命名支付方案。其中四种可端到端使用;`auth-capture` 目前仅提供客户端支持: -- **`exact`**:支付公布的准确金额。EIP-3009 代币(如 Base 官方 USDC、BSC 测试网 DHLU)通过 `transferWithAuthorization` 无 gas 结算;普通 ERC-20/TRC-20 代币(如 BSC USDC/USDT、TRON USDT/USDD)通过 Permit2 路径结算,首次付款需一次性 `approve(Permit2)`。`exact` 的协议 payload 遵循 **x402 Foundation** 的 v2 规范。 +- **`exact`**:支付公布的准确金额。EIP-3009 代币(如 Base 官方 USDC)通过 `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`**:面向高频微支付的支付通道——一次性链上存入,然后用链下凭证支付多次请求,一笔交易批量结算。含退款路径。 - **`exact_gasfree`**(仅限 TRON):允许买家使用 USDT/USDD 付款而无需持有 TRX 来支付 gas。由 relayer 通过 GasFree API 支付链上 energy——客户端无需配置 API 密钥。relayer 会在付款金额之外,从支付代币中扣除自己的中继费。 @@ -74,10 +74,10 @@ x402 定义了五种命名支付方案。其中四种可端到端使用;`auth- - 标准的 v2 客户端可以直接访问本 SDK 的 `exact` 受保护端点,无需任何项目特定的适配层。 - 本 SDK 的客户端可以直接向 v2 兼容的服务端付款。 -- V2 结构中转账授权数据位于 `payload.authorization` 字段(结构化对象)。 -- BSC USDT/USDC 是普通 ERC-20(无 ERC-3009),在 `exact` 方案下通过 Permit2 路径结算——客户端首次付款时自动广播一次性 `approve(Permit2)`。ERC-3009 代币(如 BSC 测试网 DHLU)则无 gas 结算,无需 approve。 +- V2 结构中转账授权数据是结构化对象:EIP-3009 路径位于 `payload.authorization`,Permit2 路径位于 `payload.permit2Authorization`。 +- BSC USDT/USDC 是普通 ERC-20(无 ERC-3009),在 `exact` 方案下通过 Permit2 路径结算,需要一次性 `approve(Permit2)`。在 EVM 上客户端从不广播该授权:要么事先已授权,要么在 server 声明了 gas 代付扩展时交由 facilitator 转发——否则请求会以 `permit2_allowance_required` 失败。 - Base 主网官方 USDC 在 `exact` 下使用 EIP-3009:付款方签署 `transferWithAuthorization`,无需 Permit2 approve。 -- 仓库中的 `legacy/examples/bsc-testnet-smoke/` 目录(属于保留作参考的 `legacy/` 目录)提供了双向互通的烟雾测试示例(Coinbase 官方客户端 → BANK OF AI 服务端、BANK OF AI 客户端 → Coinbase 官方服务端),可作为调试与集成参考。 +- 原 `legacy/examples/bsc-testnet-smoke/` 互通烟雾测试已随根目录 `legacy/` 归档在 x402 v2.0.0 中移除。当前请以可运行的 [`examples/typescript`](https://github.com/BofAI/x402/tree/main/examples/typescript) 工作区作为 client → server → facilitator 的参考;自 v2.1.0 起它只覆盖 TRON,EVM 请参考[上游示例](https://github.com/x402-foundation/x402/tree/main/examples/typescript)。 ### 资产、网络及费用 @@ -85,22 +85,23 @@ x402 定义了五种命名支付方案。其中四种可端到端使用;`auth- | 网络 | 代币 | 状态 | | ----------------------------- | ------------- | ----------- | -| TRON 主网 (`tron:0x2b6653dc`) | USDT (TRC-20) | **Mainnet** | -| TRON Nile (`tron:0xcd8690dc`) | USDT (TRC-20) | **Testnet** | -| TRON Shasta (`tron:0x94a9059e`) | USDT (TRC-20) | **测试网**(仅 SDK/CLI 支持——官方 facilitator 不结算 Shasta,请用 Nile 或自建) | -| TRON Mainnet (`tron:0x2b6653dc`) | USDD (TRC-20) | **Mainnet** | -| TRON Nile (`tron:0xcd8690dc`) | USDD (TRC-20) | **Testnet** | +| TRON 主网 (`tron:728126428`) | USDT (TRC-20) | **Mainnet** | +| TRON Nile (`tron:3448148188`) | USDT (TRC-20) | **Testnet** | +| TRON Shasta (`tron:2494104990`) | USDT (TRC-20) | **测试网**(仅 SDK/CLI 支持——官方 facilitator 不结算 Shasta,请用 Nile 或自建) | +| TRON Mainnet (`tron:728126428`) | USDD (TRC-20) | **Mainnet** | +| TRON Nile (`tron:3448148188`) | USDD (TRC-20) | **Testnet** | | BSC 主网 (`eip155:56`) | USDT (BEP-20) | **Mainnet** | -| BSC 主网 (`eip155:56`) | USDC (BEP-20) | **Mainnet** | +| BSC 主网 (`eip155:56`) | USDC(BEP-20;`0x8AC76a…`,不在任何内置代币注册表中——仅能作为显式资产) | **Mainnet** | | BSC testnet (`eip155:97`) | USDT (BEP-20) | **Testnet** | | BSC testnet (`eip155:97`) | USDC (BEP-20) | **Testnet** | -| BSC testnet (`eip155:97`) | DHLU (BEP-20, 用于 `exact` 互通测试) | **Testnet** | | Base 主网 (`eip155:8453`) | 官方 USDC(ERC-20,EIP-3009) | **Mainnet** | | Base Sepolia (`eip155:84532`) | USDC(ERC-20,EIP-3009) | **Testnet** | -其中只有一部分是**默认资产**(TRON 与 BSC 主网的 USDT、BSC 测试网与 Base 的 USDC)。SDK 1.1.0 起,客户端消费管控会拒绝其他资产——包括 TRON USDD、BSC 主网 USDC、BSC 测试网 USDT——除非通过 `spendControls.allowedAssets` 放行。 +自 x402 v2.0.0(`@bankofai/x402-tron` 2.0.0)起,TRON 标识使用十进制链 ID;旧的十六进制写法(`tron:0x2b6653dc`、`tron:0xcd8690dc`、`tron:0x94a9059e`)仍可作为输入别名。 -此外,可通过 TRON 代币注册表(`@bankofai/x402-tron` 的 `registerToken`)添加自定义 TRC-20 代币;自定义 BEP-20 代币则通过在 server 的 `EVM_TOKENS` 配置表中添加条目来公布。 +其中只有一部分是**默认资产**(TRON 三个网络上的 USDT,Base 与 Base Sepolia 上的 USDC)。SDK 1.1.0 起,客户端消费管控会拒绝其他资产——包括 TRON USDD 和所有 BSC 资产——除非通过 `spendControls.allowedAssets` 放行。 + +此外,可通过 TRON 代币注册表(`@bankofai/x402-tron` 的 `registerToken`)添加自定义 TRC-20 代币;自定义 BEP-20 代币则通过在 server 路由上使用显式的 `{ asset, amount, extra }` 价格来公布。 #### 涉及哪些费用? @@ -118,7 +119,7 @@ x402 定义了五种命名支付方案。其中四种可端到端使用;`auth- 1. **买家(客户端/代理)**:在本地运行时环境(如浏览器、Serverless 函数、代理虚拟机)中完成签名。 2. **卖家**:无需接触买家私钥;仅负责验证签名的有效性。 -3. **Facilitator**:使用自己的结算钱包提交交易,钱包通过 `@bankofai/agent-wallet` 解析——原始私钥不会进入 facilitator 进程。 +3. **Facilitator**:使用自己的结算钱包提交交易,钱包通过 `@bankofai/agent-wallet` 解析——使用 `privy` 或 `wallet_cli` provider 时私钥留在 facilitator 进程之外(`raw_secret` 把明文私钥存在配置中,仅适用于开发环境)。 #### 退款机制如何运作? @@ -149,11 +150,11 @@ x402 定义了五种命名支付方案。其中四种可端到端使用;`auth- 在您的 TypeScript 应用中安装已发布的 npm 包并基于这些包开发,例如: ```bash -pnpm add @bankofai/x402-fetch @bankofai/x402-tron @bankofai/x402-evm @bankofai/agent-wallet -pnpm add @bankofai/x402-core @bankofai/x402-express +pnpm add @x402/core@2.28.0 @x402/fetch@2.28.0 @bankofai/x402-tron@2.1.0 @x402/evm@2.28.0 @bankofai/agent-wallet +pnpm add @x402/express@2.28.0 ``` -请根据服务框架选择对应包(`express`、`hono`、`fastify` 或 `next`)。[`examples/typescript`](https://github.com/BofAI/x402/tree/main/examples/typescript) 工作区是 client → server → facilitator 流程的可运行参考,不是应用开发的前置条件。 +请根据服务框架选择对应包(`@x402/express`、`@x402/hono`、`@x402/fastify` 或 `@x402/next`),版本与 `@x402/core` 一致为 `2.28.0`——`@bankofai/x402-tron` 2.1.0 要求精确的 `@x402/core@2.28.0`。仅在使用 TRON 资源赞助时再安装 `@bankofai/x402-tron-extensions@2.1.0`。[`examples/typescript`](https://github.com/BofAI/x402/tree/main/examples/typescript) 工作区是 client → server → facilitator 流程的可运行参考,不是应用开发的前置条件。 #### 推荐使用哪个测试网? @@ -175,10 +176,11 @@ BSC 上推荐使用 **BSC Testnet** 进行测试。该网络是 BSC 主网的镜 1. **签名无效**:域 (Domain) 参数配置错误或载荷 (Payload) 字段不匹配。 2. **支付金额不足**:签名载荷中的金额低于服务端要求的金额。 -3. **授权额度 (Allowance) 不足**:客户端对 Facilitator 的代币授权额度不足。 -4. **账户余额不足**:客户端钱包地址缺乏足够的 USDT。 +3. **账户余额不足**:客户端钱包地址缺乏足够的 USDT。 + +响应体默认是 `{}`。失败原因在 `PAYMENT-REQUIRED` 响应头里——该头部是 Base64 编码的付款要求,其中的 `error` 字段即诊断信息,可用 `@x402/core/http` 的 `decodePaymentRequiredHeader` 解码查看。 -建议查看服务端返回的 JSON 响应中的 `error` 字段,以获取具体的错误诊断信息。 +`exact` / `upto` 的 Permit2 路径上授权额度 (Allowance) 不足时,返回的不是 402:服务端会响应 HTTP `412 Precondition Failed`,同一头部中的 `error` 为 `"permit2_allowance_required"`。(`batch-settlement` 的存入路径则以 402 返回其方案专属的错误码。) #### 在 Nile 测试网运行正常,切换到主网后失败,常见原因有哪些? 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 388748e6..e5c6c11e 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 包。 +x402 是**仅 TypeScript** 的 SDK:TRON 机制以 `@bankofai/x402-tron` 发布,运行在官方 `@x402/*` Core 与 HTTP 包之上。本指南展示如何直接集成已发布的 npm 包。 ::: --- @@ -31,7 +31,7 @@ x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发 ### 开始前清单 -- [ ] 已安装 **Node.js 22+** 和 **pnpm 11.1+** +- [ ] 已安装 **Node.js 24.22.1+** 和 **pnpm 11.1+** - [ ] 已创建专用**测试钱包**(见下文) - [ ] 已领取测试代币(免费) - [ ] 有一个目标 x402 保护的 API URL(例如按[卖家快速入门](./quickstart-for-sellers.md)启动的 `/credit` 接口) @@ -94,16 +94,16 @@ x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发 在您的 TypeScript 应用中安装已发布的 npm 包: ```bash -pnpm add @bankofai/agent-wallet @bankofai/x402-fetch @bankofai/x402-tron +pnpm add @bankofai/agent-wallet @x402/core@2.28.0 @x402/fetch@2.28.0 @bankofai/x402-tron@2.1.0 pnpm add -D tsx # 运行下面的 TypeScript 入口文件 ``` -如果您的项目不使用 pnpm,也可以用 `npm install` 或 `yarn add` 安装同名包。 +如果您的项目不使用 pnpm,也可以用 `npm install` 或 `yarn add` 安装同名包。`@x402/core` 与 `@x402/fetch` 请保持精确的 `2.28.0`——`@bankofai/x402-tron` 2.1.0 将 `@x402/core@2.28.0` 声明为精确版本的 peer 依赖。 :::info 钱包管理 -x402 使用 [Agent Wallet](../../Agent-Wallet/QuickStart.md) 解析和管理钱包凭据。Agent Wallet 会随上面的包一起安装。私钥解析优先级: -1. 加密钱包文件(通过 Agent Wallet CLI 导入) -2. 环境变量 `AGENT_WALLET_PRIVATE_KEY` +x402 使用 [Agent Wallet](../../Agent-Wallet/QuickStart.md) 解析和管理钱包凭据。Agent Wallet(3.0+)会随上面的包一起安装。钱包解析优先级: +1. Agent Wallet CLI 配置(`~/.agent-wallet`),且其中至少有一个钱包——通过 `agent-wallet start raw_secret`、`wallet_cli` 或 `privy` 配置 +2. 环境变量 `AGENT_WALLET_PRIVATE_KEY`(或 `AGENT_WALLET_MNEMONIC`) 本指南使用环境变量方式。 ::: @@ -145,7 +145,8 @@ const signer = await createClientTronSigner(wallet, { ```typescript import { resolveWallet, type Wallet, type Eip712Capable } from "@bankofai/agent-wallet"; -import { x402Client, wrapFetchWithPayment } from "@bankofai/x402-fetch"; +import { x402Client } from "@x402/core/client"; +import { wrapFetchWithPayment } from "@x402/fetch"; import { createClientTronSigner, TRON_NILE } from "@bankofai/x402-tron"; import { ExactTronScheme } from "@bankofai/x402-tron/exact/client"; @@ -209,15 +210,14 @@ client.setSpendControls({ maxAmountPerPayment: "$5" }); | 问题 | 原因 | 解决方案 | |---------|-------|----------| -| `WalletNotFoundError` / 解析不到钱包 | agent-wallet 里没有钱包,或当前 shell 未设置 `AGENT_WALLET_PRIVATE_KEY` | 执行 `agent-wallet start`,或确保在**运行脚本的同一终端窗口**中执行 `export` | -| `WalletNotFoundError: No active wallet set` | agent-wallet 未配置钱包 | 运行 `agent-wallet start` 并按提示导入私钥 | +| `resolve_wallet could not find a wallet source in config or env` | agent-wallet 里没有钱包,或当前 shell 未设置 `AGENT_WALLET_PRIVATE_KEY` | 执行 `agent-wallet start`,或确保在**运行脚本的同一终端窗口**中执行 `export` | | `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"` | +| (`tsx` 下)`Top-level await is currently not supported with the "cjs" output format` | 项目未声明为 ESM,脚本中的顶层 `await` 被按 CommonJS 编译 | 在 `package.json` 中添加 `"type": "module"` | 如需更细粒度的错误处理: @@ -231,7 +231,7 @@ try { console.error(await res.text()); } } catch (error) { - if (error instanceof Error && error.message.includes("no payment option")) { + if (error instanceof Error && error.message.includes("No network/scheme registered")) { 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"); 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 8f6d27d3..0f038173 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 包开发。 +x402 是**仅 TypeScript** 的 SDK:TRON 机制以 `@bankofai/x402-tron` 发布,运行在官方 `@x402/*` Core、EVM 与框架包之上。本指南展示如何基于已发布的 npm 包开发。 ::: --- @@ -28,7 +28,7 @@ x402 是**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` 包发 在终端(macOS/Linux 的 Terminal,或 Windows 的 PowerShell/命令提示符)中运行以下命令,确认所需工具已安装: ```bash -node --version # 需要 Node.js 22 或更高版本 +node --version # 需要 Node.js 24.22.1 或更高版本 pnpm --version # 需要 pnpm 11.1 或更高版本 git --version # 版本控制工具 ``` @@ -132,14 +132,14 @@ git --version # 版本控制工具 ## 第一步:安装 SDK 包 -在您的 TypeScript API 项目中安装 Express 适配器以及 TRON/EVM 支付 scheme: +在您的 TypeScript API 项目中安装官方 Core、Express 适配器以及 TRON/EVM 支付 scheme: ```bash -pnpm add express @bankofai/x402-core @bankofai/x402-express @bankofai/x402-tron @bankofai/x402-evm +pnpm add express @x402/core@2.28.0 @x402/express@2.28.0 @bankofai/x402-tron@2.1.0 @x402/evm@2.28.0 pnpm add -D tsx # 运行下面的 TypeScript 入口文件 ``` -请根据服务框架选择对应包(`@bankofai/x402-express`、`@bankofai/x402-hono`、`@bankofai/x402-fastify` 或 `@bankofai/x402-next`)。如果项目不使用 pnpm,也可以用 `npm install` 或 `yarn add` 安装同名包。 +请根据服务框架选择对应包(`@x402/express`、`@x402/hono`、`@x402/fastify` 或 `@x402/next`),版本与 `@x402/core` 一致为 `2.28.0`——`@bankofai/x402-tron` 2.1.0 将 `@x402/core@2.28.0` 声明为精确版本的 peer 依赖。`@x402/evm` 仅在使用 BSC/Base 路由时需要。如果项目不使用 pnpm,也可以用 `npm install` 或 `yarn add` 安装同名包。 如果开发者想要一个更完整的 client → server → facilitator 例子,可以参考仓库中的 [examples](https://github.com/BofAI/x402/tree/main/examples/typescript);应用开发仍应依赖已发布的 npm 包,而不是链接 monorepo 源码。 @@ -169,16 +169,13 @@ pnpm add -D tsx # 运行下面的 TypeScript 入口文件 ```typescript import express from "express"; -import { createResourceServer } from "@bankofai/x402-core"; -import { HTTPFacilitatorClient } from "@bankofai/x402-core/server"; -import { - x402HTTPResourceServer, - paymentMiddlewareFromHTTPServer, -} from "@bankofai/x402-express"; +import { HTTPFacilitatorClient, x402ResourceServer } from "@x402/core/server"; +import { x402HTTPResourceServer } from "@x402/core/http"; +import { paymentMiddlewareFromHTTPServer } from "@x402/express"; import { TRON_NILE } from "@bankofai/x402-tron"; import { ExactTronScheme } from "@bankofai/x402-tron/exact/server"; -const server = createResourceServer( +const server = new x402ResourceServer( new HTTPFacilitatorClient({ // 运行前请替换——服务端启动时会与 facilitator 同步, // 占位地址会让第一个受保护请求失败(主机不可达或返回 HTTP 错误状态时是 500; @@ -221,15 +218,12 @@ express() ```typescript import express from "express"; -import { createResourceServer } from "@bankofai/x402-core"; -import { HTTPFacilitatorClient } from "@bankofai/x402-core/server"; -import { - x402HTTPResourceServer, - paymentMiddlewareFromHTTPServer, -} from "@bankofai/x402-express"; -import { ExactEvmScheme } from "@bankofai/x402-evm/exact/server"; - -const server = createResourceServer( +import { HTTPFacilitatorClient, x402ResourceServer } from "@x402/core/server"; +import { x402HTTPResourceServer } from "@x402/core/http"; +import { paymentMiddlewareFromHTTPServer } from "@x402/express"; +import { ExactEvmScheme } from "@x402/evm/exact/server"; + +const server = new x402ResourceServer( new HTTPFacilitatorClient({ // 运行前请替换——服务端启动时会与 facilitator 同步, // 占位地址会让第一个受保护请求失败(主机不可达或返回 HTTP 错误状态时是 500; @@ -311,7 +305,7 @@ Facilitator 是一个**自动结算服务**:当有人为您的 API 付款时 在 `HTTPFacilitatorClient` 中将 `url` 设为官方端点: ```typescript -const server = createResourceServer( +const server = new x402ResourceServer( new HTTPFacilitatorClient({ url: "https://facilitator.bankofai.io", }) @@ -320,7 +314,7 @@ const server = createResourceServer( 这是您的 x402 server 用于验证和结算付款的地址——**仅供 API 调用**,无需在浏览器中打开。 -> ⚠️ **未配置 API Key 时,该端点受速率限制**(每个 IP 每分钟一次 `/settle`)。仅适合测试。 +> ⚠️ **未配置 API Key 时,该端点受速率限制**(每个 IP 每分钟 10 次,`/verify` 与 `/settle` 分别计数)。仅适合测试。 #### 4.2 申请 API Key @@ -328,14 +322,14 @@ const server = createResourceServer( 2. 在 Dashboard 上点击 **"Create API Key"** 3. 确认后,在 Dashboard 点击 **View** 查看并复制您的 API Key -配置 API Key 后,官方服务允许**每个 API Key 每分钟调用 `/settle` 1,000 次**,足以满足生产需求。 +配置 API Key 后,官方服务允许**每个 API Key 每分钟 `/verify` 与 `/settle` 各 1,000 次**,足以满足生产需求。 #### 4.3 将 API Key 接入您的 server 官方 key 以 `X-API-KEY` 头的形式随每次 facilitator 调用发送。生产环境中,请将它保存在环境变量或密钥管理系统中,并随 facilitator 请求发送。 ```bash -FACILITATOR_API_KEY=paste_your_api_key_here +export FACILITATOR_API_KEY=paste_your_api_key_here ``` 只有传入 `createAuthHeaders`,`HTTPFacilitatorClient` 才会发送该请求头——否则服务端会静默停留在匿名档位: @@ -362,7 +356,7 @@ new HTTPFacilitatorClient({ 自托管方式让您完全掌控结算钱包、RPC 节点以及注册哪些网络与方案——SDK 与 facilitator 本身都不收取任何费用。它运行示例 facilitator(`examples/typescript/facilitator/basic`),通过 HTTP 暴露 `/verify`、`/settle`、`/supported`,并按付款的 `network` 字段分发。 -> **Base 卖家注意:** 仓库自带的示例 facilitator 只注册了 `eip155:97` 与 `eip155:56`(见 `facilitator/basic/src/chains/evm.ts` 的 `EVM_NETWORKS`)。要在 Base 上结算,请使用已启用 `eip155:8453` 与 `eip155:84532` 的官方 facilitator,或自行把这两个网络加进 `EVM_NETWORKS`。 +> **BSC 与 Base 卖家注意:** 自 x402 v2.1.0 起,仓库自带的示例 facilitator 只注册 TRON 网络(见 `facilitator/basic/src/chains/tron.ts` 的 `TRON_NETWORKS`)。要在 BSC 或 Base 上结算,请使用已启用 `eip155:56`、`eip155:97`、`eip155:8453` 与 `eip155:84532` 的官方 facilitator,或参考[上游示例](https://github.com/x402-foundation/x402/tree/main/examples/typescript)用官方 `@x402/evm` 自建 EVM facilitator。 > ⚠️ **安全提醒——请先阅读:** > - 自托管 Facilitator 使用您的钱包提交链上结算交易——**此钱包应与您的收款钱包分开** @@ -375,27 +369,25 @@ facilitator 验证签名并在链上结算。它按链注册 `exact` scheme 并 ```typescript // examples/typescript/facilitator/basic/src/index.ts(节选) -import { x402Facilitator } from "@bankofai/x402-core/facilitator"; +import { x402Facilitator } from "@x402/core/facilitator"; const facilitator = new x402Facilitator() .onBeforeSettle(async ctx => console.log("[settle] before", ctx.requirements.network)) .onAfterSettle(async ctx => console.log("[settle] after", ctx.requirements.network)) .onSettleFailure(async ctx => console.log("[settle] failure", ctx)); -// 仅当钱包解析成功时才注册该链(可仅 EVM、仅 TRON,或两者)。 -const evm = await registerEvm(facilitator); +// 仅当钱包解析成功时才注册该链。只注册 TRON 网络。 const tron = await registerTron(facilitator); // 在 FACILITATOR_PORT 上暴露 POST /verify、POST /settle、GET /supported。 app.listen(PORT, () => console.log(`🚀 Facilitator on http://localhost:${PORT}`)); ``` -每个链模块将 agent-wallet 适配为 facilitator signer: +TRON 链模块将 agent-wallet 适配为 facilitator signer: -- **EVM** —— `createFacilitatorEvmSigner(wallet, { network, rpcUrl })`,然后 `facilitator.register(network, new ExactEvmScheme(signer))` - **TRON** —— `createFacilitatorTronSigner(wallet, { network, apiKey })`,然后 `facilitator.register(network, new ExactTronScheme(signer))` -signer 工厂内部构建 viem client / TronWeb;示例**从不读取原始私钥**——`AGENT_WALLET_PRIVATE_KEY` 由 `@bankofai/agent-wallet` 消费。 +signer 工厂内部构建 TronWeb;示例**从不读取原始私钥**——`AGENT_WALLET_PRIVATE_KEY` 由 `@bankofai/agent-wallet` 消费。 #### 4.2 启动 Facilitator @@ -408,9 +400,10 @@ pnpm dev:facilitator **启动成功后,应看到类似输出:** ``` -[evm] facilitator registered eip155:97 (0x…) [tron] facilitator registered tron:3448148188 (T…) -🚀 Facilitator on http://localhost:4022 (evm=true, tron=true) +[tron] facilitator registered tron:2494104990 (T…) +[tron] facilitator registered tron:728126428 (T…) +🚀 Facilitator on http://localhost:4022 (tron=true) ``` > ✅ **成功:** Facilitator 在 4022 端口运行——**保持此终端窗口打开,不要关闭** @@ -470,10 +463,10 @@ curl -si http://localhost:4021/credit | grep -i '^payment-required:' | cut -d' ' |---------|-------|----------| | `Failed to fetch` / connection refused | facilitator 或 server 未运行 | 先启动 facilitator,再运行您的 API server 入口文件 | | 客户端选不出付款选项 | 客户端选择的网络或代币与 server 公布的选项不匹配 | 检查 server 的 `accepts`(网络 + 代币),例如 `TRON_NILE` + `USDT` | -| `npx tsx` 下出现 `ERR_PACKAGE_PATH_NOT_EXPORTED` | 项目未声明为 ESM | 在 `package.json` 中添加 `"type": "module"` | +| `npx tsx` 下出现 `Top-level await is currently not supported with the "cjs" output format` | 项目未声明为 ESM,含顶层 `await` 的入口文件被按 CommonJS 编译 | 在 `package.json` 中添加 `"type": "module"` | | `No network/scheme registered for x402 version: 2 …` | 客户端选择的网络没有注册的 scheme | 确保 client 注册了目标网络,例如 `TRON_NILE` | -| `Insufficient balance` / allowance 错误 | 测试钱包缺少测试代币,或 Permit2 授权额度过低 | 从水龙头领取测试代币;client 在首次付款时会自动批准 Permit2 | -| `Connection timeout` | 网络或请求超时 | 检查连接。注意 SDK 不读取任何环境变量——`EVM_RPC_URL` 由 参考示例程序识别;在自己的服务端里请把 RPC 地址直接传给 signer 工厂函数 | +| `Insufficient balance` / allowance 错误 | 测试钱包缺少测试代币,或 Permit2 授权额度过低 | 从水龙头领取测试代币。在 TRON 上 client 首次付款时会自动批准 Permit2;在 EVM 上需要自己先批准一次 Permit2 | +| `Connection timeout` | 网络或请求超时 | 检查连接。注意 SDK 不读取任何环境变量——`TRON_GRID_API_KEY` 由参考示例程序读取;在自己的代码里请把 `apiKey` / `rpcUrl` 直接传给 signer 工厂函数 | --- @@ -498,15 +491,11 @@ price: "1 USDT", ### 2. 设置可靠的 EVM RPC -BSC 主网需要稳定端点。为 client 和 facilitator 都设置: - -```bash -EVM_RPC_URL=https://bsc-rpc.publicnode.com -``` +BSC 主网需要稳定端点,例如 `https://bsc-rpc.publicnode.com`。SDK 不读取环境变量,且自 v2.1.0 起仓库示例只覆盖 TRON——请在用官方 `@x402/evm` 构建的 EVM signer 上配置该端点,client 与自托管 facilitator 都需要。 ### 3.(自托管)将 Facilitator 切换到主网 -示例 facilitator 的 `TRON_NETWORKS` 已包含 `TRON_MAINNET`(`tron:728126428`),`EVM_NETWORKS` 已包含 `eip155:97` 与 `eip155:56`——但不含 Base(`eip155:8453` / `eip155:84532`),若在 Base 结算需自行添加。向 Facilitator 钱包充入足够的真实 TRX/BNB 以支付结算 gas,然后重启: +示例 facilitator 的 `TRON_NETWORKS` 已包含 `TRON_MAINNET`(`tron:728126428`);它不注册任何 EVM 网络,BSC 或 Base 请通过官方 facilitator 或您自建的 `@x402/evm` facilitator 结算。向 Facilitator 钱包充入足够的真实 TRX 以支付结算能量,然后重启: ```bash pnpm dev: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 8eacb38c..95aa880d 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 @@ -13,7 +13,7 @@ x402 是一种基于 HTTP `402 Payment Required` 状态码的区块链开放支 **有意参与文档共建?** 欢迎在 [GitHub 仓库](https://github.com/BofAI/docs)提交 PR!我们唯一的原则是保持文档的中立性:除必要的资源链接外,请避免包含任何品牌推广内容。 -**使用 x402 开发?** 请在您的 TypeScript 应用中安装已发布的 [`@bankofai/x402-*`](https://www.npmjs.com/package/@bankofai/x402-tron) 包。[`x402` 仓库](https://github.com/BofAI/x402) 在 `examples/typescript/` 下提供完整 client → server → facilitator 可运行示例,用于参考——`exact`、`gasfree`、`upto`、`batch-settlement`。 +**使用 x402 开发?** 请在您的 TypeScript 应用中安装已发布的 [`@bankofai/x402-tron`](https://www.npmjs.com/package/@bankofai/x402-tron) 等包,并搭配官方 `@x402/*` 包。[`x402` 仓库](https://github.com/BofAI/x402) 在 `examples/typescript/` 下提供完整 client → server → facilitator 可运行示例,用于参考——`exact`、`gasfree`、`upto`、`batch-settlement`。 ## 为什么要使用 x402? @@ -72,9 +72,9 @@ x402 支持广泛的应用场景,包括: x402 目前支持以下网络环境: -- **TRON 主网** (`tron:0x2b6653dc`) -- **TRON Shasta 测试网** (`tron:0x94a9059e`)——仅 SDK/CLI 可用,官方 facilitator 不结算 -- **TRON Nile 测试网** (`tron:0xcd8690dc`) +- **TRON 主网** (`tron:728126428`) +- **TRON Shasta 测试网** (`tron:2494104990`)——仅 SDK/CLI 可用,官方 facilitator 不结算 +- **TRON Nile 测试网** (`tron:3448148188`) - **BSC 主网** (`eip155:56`) - **BSC 测试网** (`eip155:97`) - **Base 主网**(`eip155:8453`) @@ -82,7 +82,9 @@ x402 目前支持以下网络环境: Base 主网使用官方 USDC,通过 `exact` 方案和 EIP-3009 授权完成支付。 -> **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),以及目前仅有 client 的 `auth-capture`(EVM)。此前的 Python + TypeScript SDK 已移至 `legacy/` 仅供参考。完整对比详见 [SDK 功能特性](./x402/sdk-features)。 +自 x402 v2.0.0 起,TRON 标识使用十进制链 ID;旧的十六进制写法(`tron:0x2b6653dc`、`tron:0x94a9059e`、`tron:0xcd8690dc`)仍可作为输入别名。 + +> **SDK(仅 TypeScript)**:x402 是仅 TypeScript 的 SDK:TRON 机制与 TRON 资源赞助扩展以 `@bankofai/x402-tron` 和 `@bankofai/x402-tron-extensions` 发布,构建在官方 `@x402/*` 包(`core`、`evm`、`fetch`、`express`、`hono`、`fastify`、`next`、`axios`、`mcp`、`extensions`)之上。源码由 pnpm/turbo monorepo 维护,但应用开发应安装已发布的包。它定义了五种命名方案:`exact`(ERC-3009 / Permit2)、`upto`、`batch-settlement`、`exact_gasfree`(TRON),以及目前仅有 client 的 `auth-capture`(EVM)。上一代 Python + TypeScript SDK 归档已在 x402 v2.0.0 中移除,`typescript/packages/legacy/` 下的兼容 npm 包也已在 v2.1.0 中移除。完整对比详见 [SDK 功能特性](./x402/sdk-features)。 ## 快速开始 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 03865aac..98786c82 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/sdk-features.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/x402/sdk-features.md @@ -1,15 +1,15 @@ --- title: 'SDK 功能矩阵' -description: 'x402 TypeScript SDK 的功能支持矩阵,以颗粒化 @bankofai/x402-* 包发布。' +description: 'x402 TypeScript SDK 的功能支持矩阵:基于官方 @x402/* Core 的 @bankofai/x402-tron 与 @bankofai/x402-tron-extensions 包。' --- # SDK 功能矩阵 本页跟踪 x402 SDK 的功能支持情况。 -> **SDK(仅 TypeScript)**:x402 是一个**仅 TypeScript** 的 SDK,以颗粒化的 `@bankofai/x402-*` npm 包发布。源码由 pnpm/turbo monorepo 维护,但应用应依赖已发布的包。此前的 Python + TypeScript SDK 已移至 `legacy/` 仅供参考。 +> **SDK(仅 TypeScript)**:x402 是一个**仅 TypeScript** 的 SDK。TRON 机制与 TRON 资源赞助扩展以 `@bankofai/x402-tron` 与 `@bankofai/x402-tron-extensions` npm 包发布,Core、EVM、HTTP/MCP 集成和通用扩展则直接使用 x402 Foundation 官方的 `@x402/*` 包。源码由 pnpm/turbo monorepo 维护,但应用应依赖已发布的包。上一代 Python + TypeScript SDK 的 `legacy/` 归档已在 2.0.0 中从仓库移除,`typescript/packages/legacy/` 下的兼容包也已在 2.1.0 中移除。 > -> **当前版本:1.2.0**(2026-08-28)。11 个 `@bankofai/x402-*` 包共用一条版本线,但不再次次齐步发布:1.2.0 发布了 `@bankofai/x402-extensions` 与 `@bankofai/x402-tron` 的 `1.2.0`,`@bankofai/x402-express`、`-fastify`、`-hono`、`-next` 的 `1.1.1`,而 `@bankofai/x402-core`、`-evm`、`-fetch`、`-axios`、`-mcp` 仍为 `1.1.0`(本次发布未变更其 API 与依赖)。每个包将内部依赖锁定为对应包已发布版本的 `~` 范围,因此请按上述版本组合安装。SDK 要求 **Node.js 22+**。 +> **当前版本:2.1.0**(2026-10-23)。付款调用链改为基于官方 `@x402/core` `2.28.0`,`@bankofai/x402-tron` `2.1.0` 将其声明为精确版本的 peer 依赖;请搭配对应的官方 HTTP/MCP 集成(`@x402/fetch`、`@x402/axios`、`@x402/express`、`@x402/fastify`、`@x402/hono`、`@x402/next` 或 `@x402/mcp`,均为 `2.28.0`)。TRON 资源赞助移入独立的 `@bankofai/x402-tron-extensions` `2.1.0`,它锁定机制包的精确版本——两个 TRON 包需一起升级。EVM 直接使用官方 `@x402/evm` `2.28.0`,通用扩展使用官方 `@x402/extensions` `2.28.0`;本地 EVM 包与 `@bankofai/x402-extensions` 已移除。`@bankofai/x402-core` 及基于它的 `@bankofai/x402-*` HTTP/MCP 适配器不能与 2.1 机制混用——新的 TRON 集成请使用官方 Core 与适配器。从 2.0 升级需要迁移源码,见 [TRON 2.1 迁移指南](https://github.com/BofAI/x402/blob/main/docs/migrations/tron-2.1.md)。SDK 要求 **Node.js 24.22.1+**;可运行示例使用 `@bankofai/agent-wallet` **3.0+**。 --- @@ -17,17 +17,18 @@ description: 'x402 TypeScript SDK 的功能支持矩阵,以颗粒化 @bankofai | 包 | 用途 | |---------|---------| -| `@bankofai/x402-core` | 协议类型、client/facilitator/server 引擎、`HTTPFacilitatorClient`、可观测性 | -| `@bankofai/x402-evm` | EVM 机制:`exact`、`upto`、`batch-settlement`,另含 `auth-capture` 的 client(`@bankofai/x402-evm/auth-capture/client`,不导出 server 与 facilitator) | -| `@bankofai/x402-tron` | TRON 机制:`exact`、`upto`、`batch-settlement`、`exact_gasfree` | -| `@bankofai/x402-fetch` | 包装 `fetch` 的 client(`wrapFetchWithPayment`) | -| `@bankofai/x402-express` | Express server 中间件 | -| `@bankofai/x402-hono` | Hono server 中间件 | -| `@bankofai/x402-fastify` | Fastify server 中间件 | -| `@bankofai/x402-next` | Next.js server 中间件 | -| `@bankofai/x402-axios` | Axios client 包装 | -| `@bankofai/x402-mcp` | 面向 AI 代理的 MCP 传输(client + server) | -| `@bankofai/x402-extensions` | 扩展:EVM gas 赞助(`eip2612GasSponsoring`、`erc20ApprovalGasSponsoring`)、TRON 资源赞助(`trc20ApprovalResourceSponsoring`,1.2.0 新增)、payment-identifier、bazaar、sign-in-with-x、offer-receipt、builder-code | +| `@bankofai/x402-tron` | TRON 机制:`exact`、`upto`、`batch-settlement`、`exact_gasfree`;TRON signer 工厂、`/rpc` 与 `/transactions` 工具、TRON logger | +| `@bankofai/x402-tron-extensions` | TRON 授权资源赞助(`trc20ApprovalResourceSponsoring`):声明、client 预签名扩展、facilitator runtime 与协调器——2.1.0 起移入此包 | +| `@x402/core`(官方) | 协议类型、client/facilitator/server 引擎、`HTTPFacilitatorClient` | +| `@x402/evm`(官方) | EVM 机制:`exact`、`upto`、`batch-settlement`,另含 `auth-capture` 的 client(`@x402/evm/auth-capture/client`,不导出 server 与 facilitator) | +| `@x402/fetch`(官方) | 包装 `fetch` 的 client(`wrapFetchWithPayment`) | +| `@x402/express`(官方) | Express server 中间件 | +| `@x402/hono`(官方) | Hono server 中间件 | +| `@x402/fastify`(官方) | Fastify server 中间件 | +| `@x402/next`(官方) | Next.js server 中间件 | +| `@x402/axios`(官方) | Axios client 包装 | +| `@x402/mcp`(官方) | 面向 AI 代理的 MCP 传输(client + server) | +| `@x402/extensions`(官方) | 通用扩展:EVM gas 赞助(`eip2612GasSponsoring`、`erc20ApprovalGasSponsoring`)、payment-identifier、bazaar、sign-in-with-x、offer-receipt、builder-code | --- @@ -55,14 +56,14 @@ description: 'x402 TypeScript SDK 的功能支持矩阵,以颗粒化 @bankofai | `tron:728126428` | `TRON_MAINNET` | ✅ | | `tron:3448148188` | `TRON_NILE` | ✅ | | `tron:2494104990` | `TRON_SHASTA` | ✅ | -| `eip155:56`(BSC 主网) | - | ✅ | -| `eip155:97`(BSC 测试网) | - | ✅ | +| `eip155:56`(BSC 主网) | - | ✅(仅显式资产) | +| `eip155:97`(BSC 测试网) | - | ✅(仅显式资产) | | `eip155:8453`(Base 主网) | - | ✅ | | `eip155:84532`(Base Sepolia) | - | ✅(CLI/SDK 测试) | -> **TRON 标识格式**:自 `@bankofai/x402-tron` 2.0.0 起,SDK 常量使用十进制 CAIP-2 引用。旧的十六进制形式(`tron:0x2b6653dc`、`tron:0xcd8690dc`、`tron:0x94a9059e`)仍可作为输入别名使用,官方 facilitator 与 API Catalog 目前返回的也是十六进制形式。 +> **TRON 标识格式**:自 `@bankofai/x402-tron` 2.0.0 起,SDK 常量使用十进制 CAIP-2 引用。旧的十六进制形式(`tron:0x2b6653dc`、`tron:0xcd8690dc`、`tron:0x94a9059e`)仍可作为输入别名使用,并会被规范化为十进制形式。官方 facilitator 的 `/supported` 返回十进制标识;API Catalog 目前仍列出十六进制形式。 -> 另有二十条上游 EVM 链(MegaETH、Monad、Polygon、Arbitrum One/Sepolia、Celo、XDC、Flare、Mezo、Radius、Stable、ADI、HPP、Igra 等)也已接入 EVM 默认资产注册表。公开 API Catalog 只发布 Base 主网路由;Base Sepolia 保留用于 CLI/SDK 测试。 +> EVM 支持来自官方 `@x402/evm` 2.28.0。其默认资产注册表覆盖 Base、Base Sepolia、Ethereum、Polygon、Arbitrum One/Sepolia、Avalanche、Celo、Sei、MegaETH、Monad、Stable、XDC、Flare、Mezo、Radius、ADI、HPP、Igra 等链,但**不包括 BSC**。在 BSC 上,路由价格须写成显式的 `{ asset, amount, extra }` 对象(写 `$` 价格会报 `No default asset configured for network eip155:56`),client 也须把该资产加入 `spendControls.allowedAssets`。公开 API Catalog 只发布 Base 主网路由;Base Sepolia 保留用于 CLI/SDK 测试。 --- @@ -90,7 +91,7 @@ scheme/network server 现在会按资产转账方式声明自己支持哪些付 v1.0 的 `SchemeNetworkServer` 实现可以不声明付款流程,它们会继续沿用 authorization 流程。 -`upfront` 与 `escrow` 是给自定义方案用的编排钩子。截至 1.1.0,内置的四个 server 方案(`exact`、`upto`、`batch-settlement`、`exact_gasfree`)都只声明 `authorization`,因此使用内置方案时 `extra.paymentFlow` 不会出现在协议数据里。 +TRON 的 server 方案(`exact`、`upto`、`batch-settlement`、`exact_gasfree`)以及 EVM 的 `upto` 与 `batch-settlement` 只声明 `authorization`。官方 EVM `exact` 方案(`@x402/evm`)在 `eip3009` 和 `permit2` 下还支持 `upfront`:路由在该付款选项上设置 `extra: { paymentFlow: "upfront" }` 即可启用,只有这时 `extra.paymentFlow` 才会出现在协议数据里。没有任何内置方案声明 `escrow`,它仍是留给自定义方案的钩子。 > **x402 Foundation v2 兼容性**:`exact` 方案(EVM 和 TRON)符合 **x402 Foundation** 发布的 v2 线格式。标准 v2 client 可与本 SDK 的 server 互通,反之亦然。详见[网络与代币支持 → `exact` 方案](./core-concepts/network-and-token-support.md#exact-scheme)。 @@ -98,31 +99,42 @@ v1.0 的 `SchemeNetworkServer` 实现可以不声明付款流程,它们会继 ## 扩展(Extensions) {#extensions} -`@bankofai/x402-extensions` 提供一组可选的协议扩展:`bazaar`、`sign-in-with-x`、`offer-receipt`、`payment-identifier`、`eip2612-gas-sponsoring`、`erc20-approval-gas-sponsoring`、`trc20-approval-resource-sponsoring` 与 `builder-code`。它们均从包根导出——赞助类扩展没有单独的子路径入口。由 resource server 在 `PaymentRequired.extensions` 中声明某个扩展;赞助类扩展与 `payment-identifier` 只在 server 声明后才生效,而 `builder-code` 的归属码由注册了它的一方自行附加,不依赖 server 声明。 +通用协议扩展——`bazaar`、`sign-in-with-x`、`offer-receipt`、`payment-identifier`、`eip2612-gas-sponsoring`、`erc20-approval-gas-sponsoring` 与 `builder-code`——来自官方 `@x402/extensions` `2.28.0`:大多通过 `@x402/extensions/bazaar` 这类子路径导入,两个 EVM gas 赞助扩展从包根导入。TRON 的 `trc20-approval-resource-sponsoring` 单独发布在 `@bankofai/x402-tron-extensions` 中,从包根及 `/trc20-approval-resource-sponsoring`(其下另有 `/client`、`/facilitator`、`/resourceService`)导出。由 resource server 在 `PaymentRequired.extensions` 中声明某个扩展;赞助类扩展与 `payment-identifier` 只在 server 声明后才生效,而 `builder-code` 的归属码由注册了它的一方自行附加,不依赖 server 声明。 -### TRON 授权资源赞助(1.2.0 新增) +### TRON 授权资源赞助(1.2.0 新增,2.1.0 起为独立包) `trc20ApprovalResourceSponsoring`(协议 schema 版本 `1`)让付款方在**不持有 TRX** 的情况下完成 TRON 上的**首笔** Permit2 付款或通道存入。client 不再自行广播那笔一次性的 `approve(Permit2, MaxUint256)`,而是签名后将已签名的交易字节随付款载荷一并上传;facilitator 严格解码并将其与本次付款绑定校验,临时向付款方委托其所缺的(Stake 2.0)能量——必要时还有带宽,原封不动地广播该交易,随后通过可恢复的状态机回收委托的资源。 | 角色 | 做什么 | |------|--------| | Resource server | **主动启用**——将 `declareTrc20ApprovalResourceSponsoringExtension()` 展开到路由的 `extensions` 里。该路由必须使用 `extra.assetTransferMethod: "permit2"`。 | -| Client | **无需配置**——当 server 声明了版本 `1`、所选路径为 Permit2、且当前 Permit2 授权额度不足时,`@bankofai/x402-tron` 会自动附上已签名的授权交易。 | -| Facilitator | **主动启用**——用 `@bankofai/x402-tron` 的 `createTrc20ResourceSponsoringRuntime({ ... })` 构造 runtime,再注册 `createTrc20ApprovalResourceSponsoringExtension(runtime)`。 | +| Client | **主动启用**(2.1.0 起)——注册完付款 scheme 后,调用 `client.registerExtension(createTrc20ApprovalResourceSponsoringClientExtension(signer))`。当 server 声明了版本 `1`、所选路径为 Permit2、且当前 Permit2 授权额度不足时,它会附上已签名的授权交易。未注册时,受赞助的付款会报 `trc20_approval_client_extension_not_registered`。 | +| Facilitator | **主动启用**——用 `createTrc20ResourceSponsoringRuntime({ ... })` 构造 runtime,再注册 `createTrc20ApprovalResourceSponsoringExtension(runtime)`,两者均来自 `@bankofai/x402-tron-extensions`。facilitator 缺少 runtime 时返回 `sponsor_runtime_unavailable`。 | 适用于 TRON 的 `exact`(`assetTransferMethod: "permit2"`)、TRON 的 `upto`,以及 `batch-settlement` 的 Permit2 **存入/补充**路径;不用于 EIP-3009 转账,也不用于批量结算的凭证、claim、settle 与退款路径。它只赞助那一笔 `approve` 交易——付款金额、收款方、nonce、截止时间仍然只由 scheme 载荷决定,且这笔 `approve` 内部不会向用户收取任何费用。也没有新增接口:流程仍为 `402 Payment Required` → `PAYMENT-SIGNATURE` → `/verify` → `/settle`。 ```typescript -import { declareTrc20ApprovalResourceSponsoringExtension } from "@bankofai/x402-extensions"; - -const route = { - price: { - amount: "1000000", - asset: "T...", - extra: { assetTransferMethod: "permit2" }, - }, - extensions: { - ...declareTrc20ApprovalResourceSponsoringExtension(), +import type { RoutesConfig } from "@x402/core/http"; +import { TRON_NILE } from "@bankofai/x402-tron"; +import { declareTrc20ApprovalResourceSponsoringExtension } from "@bankofai/x402-tron-extensions"; + +const routes: RoutesConfig = { + "GET /weather": { + accepts: [ + { + scheme: "exact", + network: TRON_NILE, + payTo: "T...", + price: { + amount: "1000000", + asset: "T...", + extra: { assetTransferMethod: "permit2" }, + }, + }, + ], + extensions: { + ...declareTrc20ApprovalResourceSponsoringExtension(), + }, }, }; ``` @@ -131,23 +143,22 @@ const route = { - 付款方必须是**已激活的单签名 TRON 外部账户(EOA)**,且使用默认的 owner 权限;不支持多签与自定义权限账户。 - 在默认的 `zero-first` 授权策略下,**非零但不足**的授权额度会直接报 `approval_reset_required`——SDK 不会自动插入一笔 `approve(0)`。不属于已知 Permit2 资产的代币会报 `approval_asset_unsupported`,除非你用 `createTrc20ApprovalPolicy` 为它配置策略。 - 生产环境的 facilitator 必须为 runtime 配备持久化的操作协调器,并在启动时及定时运行对账;导出的 `InMemoryTrc20SponsoringCoordinator` 仅用于测试和单进程开发。 -- [官方 facilitator](./core-concepts/OfficialFacilitator.md) 目前**未**启用该扩展;TRON 授权赞助需要自建 facilitator,并准备一个有 Stake 2.0 资源量的资源持有钱包。 +- [官方 facilitator](./core-concepts/OfficialFacilitator.md) 已在 `/supported` 中声明该扩展,但其生产配置**只赞助 TRON Nile 上的 USDT**,且需要 API Key。要在 TRON 主网或为其他代币赞助,需要自建 facilitator,并准备一个有 Stake 2.0 资源量的资源持有钱包。 ::: --- ## Signer -密钥托管在 [`@bankofai/agent-wallet`](https://github.com/BofAI/agent-wallet) 中;SDK 从不接触原始私钥。signer 工厂内部构建链 client(viem / TronWeb)。 +`@bankofai/x402-tron` 中的 TRON signer 工厂对钱包(例如由 [`@bankofai/agent-wallet`](https://github.com/BofAI/agent-wallet) 解析出的钱包)做适配,SDK 从不接触原始私钥;TronWeb 由工厂在内部构建。 | signer 工厂 | 角色 | |----------|------| | `createClientTronSigner` | Client(TRON) | -| `createClientEvmSigner` | Client(EVM) | | `createFacilitatorTronSigner` | Facilitator(TRON) | -| `createFacilitatorEvmSigner` | Facilitator(EVM) | | `createAuthorizerTronSigner` | Authorizer(TRON,batch-settlement) | -| `createAuthorizerEvmSigner` | Authorizer(EVM,batch-settlement) | + +EVM 签名使用官方 `@x402/evm` 的公开 signer 适配器(例如 `toClientEvmSigner`、`toFacilitatorEvmSigner`)。原 `@bankofai/x402-evm` 的 agent-wallet 工厂(`createClientEvmSigner`、`createFacilitatorEvmSigner`、`createAuthorizerEvmSigner`)已在 2.1.0 中退役,请参考[上游 EVM 示例](https://github.com/x402-foundation/x402/tree/main/examples/typescript)。 --- @@ -181,7 +192,7 @@ const route = { | 受保护路由集成 | ✅(`paymentMiddlewareFromHTTPServer`、`x402HTTPResourceServer`) | | 多链 `accepts` 公布 | ✅ | | EVM gas 赞助扩展(`eip2612GasSponsoring` / `erc20ApprovalGasSponsoring`) | ✅ | -| TRON 资源赞助扩展(`trc20ApprovalResourceSponsoring`) | ✅ —— 1.2.0 新增;用 `declareTrc20ApprovalResourceSponsoringExtension()` 声明 | +| TRON 资源赞助扩展(`trc20ApprovalResourceSponsoring`) | ✅ —— 1.2.0 新增;用 `@bankofai/x402-tron-extensions` 的 `declareTrc20ApprovalResourceSponsoringExtension()` 声明 | | 付款验证(通过 facilitator) | ✅ | | 付款结算(通过 facilitator) | ✅ | @@ -198,10 +209,13 @@ const route = { | 确认交易(回执轮询) | ✅ | | 扩展钩子(`onBeforeSettle` / `onAfterSettle` / `onSettleFailure`) | ✅ | | EVM 智能账户——已部署账户、ERC-7702 委托、ERC-6492 反事实钱包 | ✅ —— 签名验证在 facilitator 侧;ERC-6492 需显式配置 `eip6492AllowedFactories` 白名单 | +| 待确认结算(`settlement_pending`) | ✅ —— 2.0.0 新增。交易已广播但回执尚未确定时,结算返回非终态的 `settlement_pending` 并保留原交易 ID;应对账该交易,而不是重新提交。TRON 回执等待默认 90 秒(`createFacilitatorTronSigner` 的 `confirmationTimeoutMs`) | +| 待确认结算恢复(TRON) | ✅ —— 2.1.0 新增。TRON facilitator 各 scheme 在等待回执前先保存原交易 ID(或 GasFree 中继 trace),同一笔付款重试时会续接该交易,而不会再次广播。默认的 `InMemoryTronPendingSettlementStore` 只覆盖单个进程;需要重启恢复或多副本部署时,通过构造参数 `pendingSettlementStore` 注入持久化、可共享的 `TronPendingSettlementStore`。广播后保存失败返回 `settlement_store_unavailable`(保留已知交易 ID);结算回调未处理的异常返回 `settlement_execution_failed` | +| `upto` 预检读取(TRON) | ✅ —— 2.1.0 新增。授权额度/余额读取失败或返回格式异常时,在广播任何结算交易之前返回 `chain_read_failed` | > 自托管示例 facilitator(`facilitator/basic`)暴露 `/verify`、`/settle`、`/supported`。官方托管 facilitator 额外提供结算记录查询 `GET /payments/tx/{tx_hash}` 与 `GET /payments`,以及 `/health`——详见[官方 Facilitator](./core-concepts/OfficialFacilitator.md)。Prometheus 指标在独立的监控端口上(发布配置中为 `9001`),不在对外 API 端口。没有 `/fee/quote` 端点:SDK 的各方案不收取 facilitator 费用。 > -> 1.1.0 起,`HTTPFacilitatorClient` 使用带类型的超时错误,默认超时 90 秒。其限流重试(3 次)只作用于 `getSupported()`——`verify()` 与 `settle()` 遇到 429 会直接抛给调用方,不会重试。 +> 2.1.0 起,`HTTPFacilitatorClient` 来自官方 `@x402/core` `2.28.0`:使用带类型的超时错误,默认超时为 90 秒;仓库示例显式设置了 `timeoutMs: 120_000`。切换到官方 HTTP/MCP 包后,请重新核对请求超时设置。其限流重试(3 次)只作用于 `getSupported()`——`verify()` 与 `settle()` 遇到 429 会直接抛给调用方,不会重试。 --- @@ -211,24 +225,23 @@ const route = { |--------|---------|--------| | USDT(TRC-20) | `tron:728126428`、`tron:3448148188`、`tron:2494104990` | ✅ | | USDD(TRC-20) | `tron:728126428`、`tron:3448148188` | ✅ | -| USDT(BEP-20) | `eip155:56`、`eip155:97` | ✅ | -| USDC(BEP-20) | `eip155:56`、`eip155:97` | ✅ | -| DHLU(BSC 测试网,ERC-3009) | `eip155:97` | ✅ | +| USDT(BEP-20) | `eip155:56`、`eip155:97` | ✅(显式资产) | +| USDC(BEP-20) | `eip155:56`、`eip155:97` | ✅(显式资产;`eip155:56` 的地址不在任何内置代币注册表中) | | 官方 USDC(ERC-20,EIP-3009) | `eip155:8453`、`eip155:84532` | ✅ | -| 自定义 TRC-20 / BEP-20 | 任意 | ✅(通过代币注册表 / `EVM_TOKENS` 配置) | +| 自定义 TRC-20 / BEP-20 | 任意 | ✅(通过 TRON 代币注册表 / 显式的 `{ asset, amount, extra }` 价格) | -> 其中只有一部分是**默认资产**:TRON 与 BSC 主网上的 USDT、BSC 测试网与 Base 上的 USDC。1.1.0 起,客户端消费管控会拒绝其余资产——USDD、BSC 主网 USDC、BSC 测试网 USDT、DHLU、自定义代币——除非通过 `spendControls.allowedAssets` 放行。详见[网络与代币支持](./core-concepts/network-and-token-support.md#supported-tokens)。 +> 其中只有一部分是**默认资产**:TRON 三个网络上的 USDT,以及 Base 与 Base Sepolia 上的 USDC。1.1.0 起,客户端消费管控会拒绝其余资产——USDD、所有 BSC 资产、自定义代币——除非通过 `spendControls.allowedAssets` 放行。详见[网络与代币支持](./core-concepts/network-and-token-support.md#supported-tokens)。 --- ## 可观测性 -所有 `@bankofai/x402-*` 包通过 `@bankofai/x402-core` 的一个进程级 logger 输出日志。启动时调用一次 `setLogger(...)` 即可将日志重定向到文件、`pino`/`winston`,或用 `noopLogger` 静默。 +TRON 机制通过 `@bankofai/x402-tron` 导出的进程级 logger 输出日志(2.1.0 起;此前来自 `@bankofai/x402-core`)。启动时调用一次 `setLogger(...)` 即可将日志重定向到文件、`pino`/`winston`,或用 `noopLogger` 静默。官方 `@x402/core` 与 `@x402/extensions` 不使用该 logger——需要记录它们的事件时,请注册生命周期钩子。 --- ## 图例 - ✅ = 已实现 -- ⏳ = 计划中 / 进行中 -- ❌ = 不计划 +- ⚠️ = 部分实现(见说明列) +- ❌ = 不支持 diff --git a/static/img/diagrams/x402-api-catalog-pipeline.light.svg b/static/img/diagrams/x402-api-catalog-pipeline.light.svg index 2504efa6..a9070f95 100644 --- a/static/img/diagrams/x402-api-catalog-pipeline.light.svg +++ b/static/img/diagrams/x402-api-catalog-pipeline.light.svg @@ -60,11 +60,11 @@ - x402-cli + wallet-cli search, inspect, paid calls MCP - Agents call services by name + Pays endpoints; no catalog lookup yet diff --git a/static/img/diagrams/x402-api-catalog-pipeline.svg b/static/img/diagrams/x402-api-catalog-pipeline.svg index ec765829..2534bdb0 100644 --- a/static/img/diagrams/x402-api-catalog-pipeline.svg +++ b/static/img/diagrams/x402-api-catalog-pipeline.svg @@ -60,11 +60,11 @@ - x402-cli + wallet-cli search, inspect, paid calls MCP - Agents call services by name + Pays endpoints; no catalog lookup yet diff --git a/static/img/diagrams/x402-api-catalog-pipeline.zh.light.svg b/static/img/diagrams/x402-api-catalog-pipeline.zh.light.svg index 0d0941c9..3cccaa65 100644 --- a/static/img/diagrams/x402-api-catalog-pipeline.zh.light.svg +++ b/static/img/diagrams/x402-api-catalog-pipeline.zh.light.svg @@ -60,11 +60,11 @@ - x402-cli + wallet-cli 搜索、查看、付费调用 MCP - Agent 按名字直接调用 + 仅付费调用 · 暂不支持按目录查找 diff --git a/static/img/diagrams/x402-api-catalog-pipeline.zh.svg b/static/img/diagrams/x402-api-catalog-pipeline.zh.svg index 258ba913..413c525e 100644 --- a/static/img/diagrams/x402-api-catalog-pipeline.zh.svg +++ b/static/img/diagrams/x402-api-catalog-pipeline.zh.svg @@ -60,11 +60,11 @@ - x402-cli + wallet-cli 搜索、查看、付费调用 MCP - Agent 按名字直接调用 + 仅付费调用 · 暂不支持按目录查找 diff --git a/static/img/diagrams/x402-payment-scheme-flow.zh.light.svg b/static/img/diagrams/x402-payment-scheme-flow.zh.light.svg index fe509bcc..9e66bcdc 100644 --- a/static/img/diagrams/x402-payment-scheme-flow.zh.light.svg +++ b/static/img/diagrams/x402-payment-scheme-flow.zh.light.svg @@ -47,7 +47,7 @@ 结算 Settle - transferWithAuthorization · Permit2 · 批量领取 · GasFree 中继 + transferWithAuthorization · Permit2 permitTransferFrom · 批量领取 · GasFree 中继 3 FACILITATOR diff --git a/static/img/diagrams/x402-payment-scheme-flow.zh.svg b/static/img/diagrams/x402-payment-scheme-flow.zh.svg index ef7d242c..63aa056c 100644 --- a/static/img/diagrams/x402-payment-scheme-flow.zh.svg +++ b/static/img/diagrams/x402-payment-scheme-flow.zh.svg @@ -47,7 +47,7 @@ 结算 Settle - transferWithAuthorization · Permit2 · 批量领取 · GasFree 中继 + transferWithAuthorization · Permit2 permitTransferFrom · 批量领取 · GasFree 中继 3 FACILITATOR From a9cc212f6fa476e80f75cf49ac92e812b2a4e45c Mon Sep 17 00:00:00 2001 From: jizhen181-dot Date: Wed, 28 Oct 2026 17:02:01 +0800 Subject: [PATCH 02/13] docs(wallet-cli): document 4.15.1 behaviour - Common error-code table with exit codes. - Spend cap, --dry-run, route filters and paymentStatus details. - B.AI recharge: routes, token default, minimums and check order. - Skills pin 4.14.0; Node.js security baselines. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/BANK-OF-AI/QuickStart.md | 2 +- docs/wallet-cli/command-reference.md | 28 +++++++++++++++---- docs/wallet-cli/index.md | 2 +- docs/wallet-cli/quickstart.md | 10 ++++--- .../current/BANK-OF-AI/QuickStart.md | 2 +- .../current/wallet-cli/command-reference.md | 28 +++++++++++++++---- .../current/wallet-cli/index.md | 2 +- .../current/wallet-cli/quickstart.md | 10 ++++--- 8 files changed, 62 insertions(+), 22 deletions(-) diff --git a/docs/BANK-OF-AI/QuickStart.md b/docs/BANK-OF-AI/QuickStart.md index d6a66b23..1be0f452 100644 --- a/docs/BANK-OF-AI/QuickStart.md +++ b/docs/BANK-OF-AI/QuickStart.md @@ -15,7 +15,7 @@ Choose an entry point for your task: | Recharge B.AI | [wallet-cli recharge guidance](/wallet-cli/command-reference/) | | DeFi workflows and data queries | [Skill catalog](/McpServer-Skills/SKILLS/BANKOFAISkill/) | -Installation requires Node.js 20 or newer and an agent that supports local Skills. Select only the Skills you need. Installing a Skill does not install its external CLI or configure a wallet; match its dependency version to the installed CLI. +Installation requires Node.js 22.23.4+ (22.x), 24.22.1+ (24.x), or 26.12.1+ and an agent that supports local Skills. Select only the Skills you need. Installing a Skill does not install its external CLI or configure a wallet; match its dependency version to the installed CLI. Complete wallet setup locally. Never send a private key, mnemonic, or master password to an AI. Before paying, check the network, address, token, amount, and fees. diff --git a/docs/wallet-cli/command-reference.md b/docs/wallet-cli/command-reference.md index 12833ff9..7f705e87 100644 --- a/docs/wallet-cli/command-reference.md +++ b/docs/wallet-cli/command-reference.md @@ -6,7 +6,7 @@ description: "Commands and payment options for wallet-cli." # Wallet CLI Command Reference -This reference targets the published **4.14.0** package. Use schema discovery to inspect command parameters. +This reference targets the published **4.15.1** package. Use schema discovery to inspect command parameters. ```bash wallet-cli --json-schema -o json @@ -19,21 +19,39 @@ wallet-cli bai recharge --json-schema -o json - `--network`: explicit payment network; use `tron:728126428` for TRON mainnet. - `--account`: wallet-cli account selection. - `--token` or `--asset` and `--decimals`: select an asset according to the schema. -- `--max-amount` / `--max-raw-amount`: mutually exclusive payment caps. +- `--max-amount` / `--max-raw-amount`: mutually exclusive payment caps. `--max-raw-amount` is in smallest units and requires `--token` or `--asset`, because a raw amount has no unit. Without `--max-amount` or `--max-raw-amount`, a built-in ceiling of $1 per payment applies to known stablecoins; routes priced above it are dropped before signing, and the command fails with `amount_exceeds_limit` when every offered route is above it. A `--dry-run` preview does not apply this built-in cap, so a preview can pass while the real payment still fails with `amount_exceeds_limit`. - `--dry-run`: read payment requirements without signing. - `--method`, `--header`, `--body` / `--body-file`: HTTP request options. +- `--out `: write the response body byte-for-byte to a new file instead of `data.response`; an existing file is refused before any request is sent. Binary media types (such as `application/octet-stream`, images, audio, video, PDF, and archives) require `--out`. - `--password-stdin`: secure master-password input for signing. - `-o json`: machine output. ## GasFree payments {#gasfree-payments-tron} -To pay a TRON route through GasFree, pass `--scheme exact_gasfree` and cap `--max-gasfree-fee`. Without `--scheme`, the first matching route the server offers is used, which can be a GasFree route; pass `--scheme exact` to rule that out. Use `--gasfree-relay` to select the relay service. The payment amount cap does not include the GasFree fee. +To pay a TRON route through GasFree, pass `--scheme exact_gasfree` and cap the fee with `--max-gasfree-fee` (or `--max-gasfree-fee-raw` in smallest units). Without `--scheme`, the first matching route the server offers is used, which can be a GasFree route; pass `--scheme exact` to rule that out. Use `--gasfree-relay` to select the relay service. The payment amount cap does not include the GasFree fee. ## Result handling Operations return `wallet-cli.result.v1` with `success`, `command`, and `data` or `error`. Exit `0` means command success, `1` execution failure, and `2` invalid invocation. Schema discovery returns a command catalog or input schema rather than an operation envelope. -The paid response is in `data.response`. On failure inspect `error.details.paymentStatus` and `retryPayment`. `not_sent` means no payment was sent; `unknown` means the outcome cannot be established. Reconcile the existing transaction rather than paying again when `retryPayment: false` is returned. +The paid response is in `data.response`. On failure inspect `error.details.paymentStatus` and `retryPayment`. `not_sent` means no payment was sent; `unknown` means the outcome cannot be established. Reconcile the existing transaction rather than paying again when `retryPayment: false` is returned. A response format error can also occur after the payment has settled; `error.details` then keeps `paymentStatus: "settled"`, the transaction hash, and `retryPayment: false`, so reconcile with the provider instead of paying again. A successful paid result reports what was paid in `data.payment`. + +### Common error codes + +| Code | Exit | When | +| --- | --- | --- | +| `missing_wallet_address` | 1 | No wallet-cli account is configured (also for `--dry-run`) | +| `auth_required` | 1 | A real payment was attempted without `--password-stdin` | +| `invalid_option` | 2 | `--max-raw-amount` without `--token` / `--asset`, a binary response without `--out`, or mutually exclusive flags | +| `output_exists` | 2 | The `--out` file already exists; nothing was sent | +| `no_matching_requirement` | 1 | No route matched `--network` / `--token` / `--asset` / `--scheme`, or, without `--max-amount` / `--max-raw-amount`, no route uses an asset the built-in spend control allows; `paymentStatus: "not_sent"` | +| `amount_exceeds_limit` | 1 | The route's price is above `--max-amount`, `--max-raw-amount` or the built-in $1 cap; `not_sent` | +| `permit2_allowance_required` | 1 | Permit2 allowance missing on an unsponsored route | +| `gasfree_insufficient_balance` / `fee_cap_exceeded` | 1 | GasFree balance or `--max-gasfree-fee` too low | +| `provider_error` / `provider_rate_limited` | 1 | The endpoint or facilitator failed or returned 429 (`error.details.retryAfterSeconds` when sent) | +| `invalid_x402_response` | 1 | The paid response could not be decoded; may carry `paymentStatus: "settled"` | + +`paymentStatus` appears in `error.details` only for real payments; a `--dry-run` failure carries no `error.details`. ## B.AI recharge @@ -42,6 +60,6 @@ wallet-cli bai recharge 1 --network tron:728126428 --token USDT --dry-run -o jso wallet-cli bai recharge-orders --json-schema -o json ``` -Requires a wallet-cli account and a stored B.AI API key. Recharge supports the configured mainnet routes only. A preview creates no order, binds no wallet, and makes no payment. A real recharge may first bind the paying address, which must be within the authorized operation. `creditStatus: "unconfirmed"` is not a failed payment: use `bai report-recharge` for the original transaction instead of paying again. +Requires a wallet-cli account and a stored B.AI API key; without the key every `bai` command, including a preview, exits `2` with `bai_credentials_missing` (after the amount and network checks). Recharge supports the configured mainnet routes only: TRON USDT / USDD, BSC USDT and Base USDC. `--to` takes a B.AI account email or an EVM / TRON / Solana address; omit it to recharge your own account. `--token` defaults to USDC on Base and USDT elsewhere. The minimum is 1 USDT / USDC (USDD has none) — below that the command fails with `invalid_amount`. A preview creates no order, binds no wallet, and makes no payment. A real recharge may first bind the paying address, which must be within the authorized operation. `creditStatus: "unconfirmed"` is not a failed payment: use `bai report-recharge` for the original transaction instead of paying again. [Quick start](/wallet-cli/quickstart/) · [FAQ](/wallet-cli/faq/) diff --git a/docs/wallet-cli/index.md b/docs/wallet-cli/index.md index 8e26c43b..34dce2b5 100644 --- a/docs/wallet-cli/index.md +++ b/docs/wallet-cli/index.md @@ -5,7 +5,7 @@ description: "Use wallet-cli for payments and service discovery." # Wallet CLI and x402 -Use **`@tron-walletcli/wallet-cli@4.14.0`** for new command-line integrations. +Use **`@tron-walletcli/wallet-cli@4.15.1`** for new command-line integrations. | Task | Entry point | | --- | --- | diff --git a/docs/wallet-cli/quickstart.md b/docs/wallet-cli/quickstart.md index d4472ee3..98be7010 100644 --- a/docs/wallet-cli/quickstart.md +++ b/docs/wallet-cli/quickstart.md @@ -6,21 +6,23 @@ description: "Install wallet-cli and preview an x402 payment." # Wallet CLI Quick Start -Requires Node.js 20 or newer. +Requires Node.js 22.23.4+ (22.x), 24.22.1+ (24.x), or 26.12.1+. ## Install and inspect ```bash -npm install -g @tron-walletcli/wallet-cli@4.14.0 +npm install -g @tron-walletcli/wallet-cli@4.15.1 wallet-cli --version wallet-cli x402 pay --json-schema -o json ``` +If you will use the wallet-cli Skill, install the version that Skill pins instead (currently 4.14.0) — see the [Skills quick start](/McpServer-Skills/SKILLS/QuickStart/). + :::tip Permission error on install? If `npm install -g` fails with a permission error (such as `EACCES`) on macOS or Linux, see npm's official guide: [Resolving EACCES permissions errors when installing packages globally](https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally). ::: -In 4.14.0, help, version, and schema discovery do not read wallet data. A first operational command may return `command: "migration"`: only the migration ran, so inspect its result before invoking the original command again. +Since 4.14.0, help, version, and schema discovery do not read wallet data. A first operational command may return `command: "migration"`: only the migration ran, so inspect its result before invoking the original command again. ## Prepare an account @@ -55,7 +57,7 @@ wallet-cli x402 pay https://x402-gateway.bankofai.io/providers/dia-price-tron/v1 --dry-run -o json ``` -Before paying, confirm the network, recipient, amount, and fees. Remove `--dry-run` only for the authorized payment, and supply the master password through `--password-stdin` from an approved secure source, never a password argument. Cap GasFree fees separately with `--max-gasfree-fee`. +Before paying, confirm the network, recipient, amount, and fees. Remove `--dry-run` only for the authorized payment, and supply the master password through `--password-stdin` from an approved secure source, never a password argument. Cap GasFree fees separately with `--max-gasfree-fee`. On TRON, a first `exact` payment in a token may broadcast `approve(Permit2, MaxUint256)` from the account before paying, unless the endpoint sponsors the approval: it burns the account's Energy or TRX and leaves an unlimited Permit2 allowance on that token. The result reports it in `data.approval`. After an uncertain result, reconcile the transaction and inspect `error.details.paymentStatus`. Do not pay again when `retryPayment: false` is returned. diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/BANK-OF-AI/QuickStart.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/BANK-OF-AI/QuickStart.md index c718c34b..65debe64 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/BANK-OF-AI/QuickStart.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/BANK-OF-AI/QuickStart.md @@ -15,7 +15,7 @@ description: "选择 BANK OF AI Skills,使用 wallet-cli 配置钱包与支付 | 充值 B.AI | [wallet-cli 充值说明](/zh-Hans/wallet-cli/command-reference/) | | DeFi 业务与数据查询 | [Skill 列表](/zh-Hans/McpServer-Skills/SKILLS/BANKOFAISkill/) | -安装需要 Node.js 20 或更新版本,以及支持本地 Skills 的 Agent。按需选择 Skill;Skill 安装不会自动安装外部 CLI,也不会自动配置钱包。检查 Skill 依赖版本与实际 CLI 一致。 +安装需要 Node.js 22.23.4+(22.x)、24.22.1+(24.x)或 26.12.1+,以及支持本地 Skills 的 Agent。按需选择 Skill;Skill 安装不会自动安装外部 CLI,也不会自动配置钱包。检查 Skill 依赖版本与实际 CLI 一致。 首次配置钱包在本地完成。不要把私钥、助记词或主密码发给 AI;支付前核对网络、地址、币种、金额与手续费。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/wallet-cli/command-reference.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/wallet-cli/command-reference.md index 23fe905c..32ef0d43 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/wallet-cli/command-reference.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/wallet-cli/command-reference.md @@ -6,7 +6,7 @@ description: "wallet-cli 命令与支付参数。" # Wallet CLI 命令参考 -以 **4.14.0** 发布包为准。通过命令 schema 查询可用参数。 +以 **4.15.1** 发布包为准。通过命令 schema 查询可用参数。 ```bash wallet-cli --json-schema -o json @@ -19,21 +19,39 @@ wallet-cli bai recharge --json-schema -o json - `--network`:指定支付网络;TRON 主网使用 `tron:728126428`。 - `--account`:选择 wallet-cli 账户。 - `--token` 或 `--asset`、`--decimals`:按 schema 指定支付资产。 -- `--max-amount` / `--max-raw-amount`:二选一,限制支付数量。 +- `--max-amount` / `--max-raw-amount`:二选一,限制支付数量。`--max-raw-amount` 以最小单位计,必须同时指定 `--token` 或 `--asset`,因为原始数量本身没有单位。`--max-amount` 和 `--max-raw-amount` 都不指定时,已知稳定币默认每笔上限 1 美元;超过该价格的路线会在签名前被排除;所有路线都超过时,命令以 `amount_exceeds_limit` 失败。`--dry-run` 预览不应用这个内置上限,所以预览能通过,实际付款仍可能以 `amount_exceeds_limit` 失败。 - `--dry-run`:读取支付要求,不签名。 - `--method`、`--header`、`--body` / `--body-file`:HTTP 请求配置。 +- `--out `:把响应体按原始字节写入新文件,而不是放在 `data.response`;文件已存在时在发出任何请求前即拒绝。二进制媒体类型(如 `application/octet-stream`、图片、音视频、PDF、压缩包)必须使用 `--out`。 - `--password-stdin`:实际签名所需主密码的安全输入通道。 - `-o json`:机器输出。 ## GasFree 支付 {#gasfree-payments-tron} -要通过 GasFree 支付 TRON 路线,请指定 `--scheme exact_gasfree`,并用 `--max-gasfree-fee` 限制手续费。不指定 `--scheme` 时,会使用服务端给出的第一条匹配路线,这条路线可能就是 GasFree;如需排除,请指定 `--scheme exact`。使用 `--gasfree-relay` 选择服务。支付金额上限不包含 GasFree 手续费。 +要通过 GasFree 支付 TRON 路线,请指定 `--scheme exact_gasfree`,并用 `--max-gasfree-fee`(或以最小单位计的 `--max-gasfree-fee-raw`)限制手续费。不指定 `--scheme` 时,会使用服务端给出的第一条匹配路线,这条路线可能就是 GasFree;如需排除,请指定 `--scheme exact`。使用 `--gasfree-relay` 选择服务。支付金额上限不包含 GasFree 手续费。 ## 结果处理 操作返回 `wallet-cli.result.v1`,包含 `success`、`command`、`data` 或 `error`。退出码 `0` 表示命令成功,`1` 为执行错误,`2` 为调用错误。schema 查询返回命令目录或输入 schema,不是操作结果对象。 -支付读取 `data.response`;失败时查看 `error.details.paymentStatus` 和 `retryPayment`。`not_sent` 表示未发送支付,`unknown` 表示不能确定;`retryPayment: false` 时应核对已有交易,不能再次支付。 +支付读取 `data.response`;失败时查看 `error.details.paymentStatus` 和 `retryPayment`。`not_sent` 表示未发送支付,`unknown` 表示不能确定;`retryPayment: false` 时应核对已有交易,不能再次支付。响应格式错误也可能发生在付款已结算之后,此时 `error.details` 仍保留 `paymentStatus: "settled"`、交易哈希和 `retryPayment: false`,应凭交易哈希与服务方核对,不要再次付款。付款成功时,`data.payment` 会给出实际支付的资产与数量。 + +### 常见错误码 + +| 错误码 | 退出码 | 出现场景 | +| --- | --- | --- | +| `missing_wallet_address` | 1 | 没有配置 wallet-cli 账户(`--dry-run` 也需要) | +| `auth_required` | 1 | 实际付款时没有传 `--password-stdin` | +| `invalid_option` | 2 | `--max-raw-amount` 没带 `--token` / `--asset`、二进制响应没带 `--out`,或同时传了互斥参数 | +| `output_exists` | 2 | `--out` 指定的文件已存在;未发出任何请求 | +| `no_matching_requirement` | 1 | 没有路线匹配 `--network` / `--token` / `--asset` / `--scheme`,或在未传 `--max-amount` / `--max-raw-amount` 时,没有路线使用内置支出控制允许的资产;`paymentStatus: "not_sent"` | +| `amount_exceeds_limit` | 1 | 路线价格高于 `--max-amount`、`--max-raw-amount` 或内置的 1 美元上限;`not_sent` | +| `permit2_allowance_required` | 1 | 未代付的路线上缺少 Permit2 授权额度 | +| `gasfree_insufficient_balance` / `fee_cap_exceeded` | 1 | GasFree 余额不足或 `--max-gasfree-fee` 过低 | +| `provider_error` / `provider_rate_limited` | 1 | 端点或 facilitator 出错或返回 429(有则带 `error.details.retryAfterSeconds`) | +| `invalid_x402_response` | 1 | 付费响应无法解码;可能带 `paymentStatus: "settled"` | + +只有实际付款时 `error.details` 里才会带 `paymentStatus`;`--dry-run` 失败时没有 `error.details`。 ## B.AI 充值 @@ -42,6 +60,6 @@ wallet-cli bai recharge 1 --network tron:728126428 --token USDT --dry-run -o jso wallet-cli bai recharge-orders --json-schema -o json ``` -需要 wallet-cli 账户及已存储的 B.AI API Key。充值只支持配置中允许的主网;预览不创建订单、不绑定钱包、不付款。实际充值可能先绑定付款地址,需在授权范围内执行。`creditStatus: "unconfirmed"` 不代表付款失败,应使用 `bai report-recharge` 报告原交易,不要重新充值。 +需要 wallet-cli 账户及已存储的 B.AI API Key;没有 Key 时所有 `bai` 命令(包括预览)都会以退出码 `2` 返回 `bai_credentials_missing`(金额和网络检查之后)。充值只支持配置中允许的主网路线:TRON USDT / USDD、BSC USDT、Base USDC。`--to` 可填 B.AI 账户邮箱或 EVM / TRON / Solana 地址,省略则给自己充值;`--token` 在 Base 上默认 USDC,其他网络默认 USDT;最低金额为 1 USDT / USDC(USDD 无下限),低于下限返回 `invalid_amount`。预览不创建订单、不绑定钱包、不付款。实际充值可能先绑定付款地址,需在授权范围内执行。`creditStatus: "unconfirmed"` 不代表付款失败,应使用 `bai report-recharge` 报告原交易,不要重新充值。 [快速入门](/zh-Hans/wallet-cli/quickstart/) · [常见问题](/zh-Hans/wallet-cli/faq/) diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/wallet-cli/index.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/wallet-cli/index.md index de9636cd..18056c2d 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/wallet-cli/index.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/wallet-cli/index.md @@ -5,7 +5,7 @@ description: "使用 wallet-cli 进行支付和服务发现。" # Wallet CLI 与 x402 -新的命令行接入使用 **`@tron-walletcli/wallet-cli@4.14.0`**。 +新的命令行接入使用 **`@tron-walletcli/wallet-cli@4.15.1`**。 | 需求 | 新入口 | | --- | --- | diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/wallet-cli/quickstart.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/wallet-cli/quickstart.md index 201751f3..3fd2b0e0 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/wallet-cli/quickstart.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/wallet-cli/quickstart.md @@ -6,21 +6,23 @@ description: "安装 wallet-cli 并预览 x402 支付。" # Wallet CLI 快速入门 -需要 Node.js 20 或更新版本。 +需要 Node.js 22.23.4+(22.x)、24.22.1+(24.x)或 26.12.1+。 ## 安装和检查 ```bash -npm install -g @tron-walletcli/wallet-cli@4.14.0 +npm install -g @tron-walletcli/wallet-cli@4.15.1 wallet-cli --version wallet-cli x402 pay --json-schema -o json ``` +如果要配合 wallet-cli Skill 使用,请改装该 Skill 锁定的版本(目前是 4.14.0),见 [Skills 快速入门](/zh-Hans/McpServer-Skills/SKILLS/QuickStart/)。 + :::tip 安装时报权限错误? 在 macOS 或 Linux 上,如果 `npm install -g` 报权限错误(如 `EACCES`),请参考 npm 官方文档:[Resolving EACCES permissions errors when installing packages globally](https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally)。 ::: -4.14.0 的帮助、版本和 schema 查询不读取钱包数据。首次执行其他命令可能返回 `command: "migration"`;这表示只完成了迁移,原命令尚未执行,需检查结果后再运行。 +从 4.14.0 起,帮助、版本和 schema 查询不读取钱包数据。首次执行其他命令可能返回 `command: "migration"`;这表示只完成了迁移,原命令尚未执行,需检查结果后再运行。 ## 准备钱包 @@ -55,7 +57,7 @@ wallet-cli x402 pay https://x402-gateway.bankofai.io/providers/dia-price-tron/v1 --dry-run -o json ``` -确认网络、收款地址、金额和费用后才能付款。实际付款去掉 `--dry-run`,使用 `--password-stdin` 从已授权的安全来源输入主密码;不要把密码放到命令行参数中。GasFree 需要单独限制 `--max-gasfree-fee`。 +确认网络、收款地址、金额和费用后才能付款。实际付款去掉 `--dry-run`,使用 `--password-stdin` 从已授权的安全来源输入主密码;不要把密码放到命令行参数中。GasFree 需要单独限制 `--max-gasfree-fee`。在 TRON 上,某个代币的首次 `exact` 付款可能会先从账户广播 `approve(Permit2, MaxUint256)`(端点代付授权时除外):这会消耗账户自己的 Energy 或 TRX,并给 Permit2 留下该代币的无限额度授权。结果会在 `data.approval` 中说明。 支付结果不确定时先检查交易和 `error.details.paymentStatus`;出现 `retryPayment: false` 时不要重新付款。 From c108988ed77a0fdab261b5a1d8cd5caad065935c Mon Sep 17 00:00:00 2001 From: jizhen181-dot Date: Wed, 28 Oct 2026 17:02:01 +0800 Subject: [PATCH 03/13] docs(8004): align with SDK 1.2.1 and registry contracts - Subgraph defaults per language, aliases (bsc/evm resolve to 97 without chainId 56), feeLimit and embeddings. - New Common Contract Errors section, by contract function. - getAgent/loadAgent/registerIPFS behaviour without a subgraph or uploader. - agentWallet is cleared on transfer; Quick Start sample notes. Co-Authored-By: Claude Opus 5.5 (1M context) --- changelog/8004.md | 38 +++++++++ docs/8004/QuickStart.md | 3 + docs/8004/SupportedNetworks.md | 8 +- docs/8004/Usage/ConfigureAgents.md | 84 ++++++++++++------- docs/8004/Usage/Install.md | 8 +- docs/8004/Usage/RegistrationHTTP.md | 7 +- docs/8004/contract.md | 8 ++ docs/8004/general.md | 2 +- docs/8004/sdk-features.md | 60 ++++++++----- .../current/8004.md | 38 +++++++++ .../current/8004/QuickStart.md | 7 +- .../current/8004/SupportedNetworks.md | 8 +- .../current/8004/Usage/ConfigureAgents.md | 81 +++++++++++------- .../current/8004/Usage/Install.md | 8 +- .../current/8004/Usage/RegistrationHTTP.md | 7 +- .../current/8004/contract.md | 10 ++- .../current/8004/general.md | 2 +- .../current/8004/sdk-features.md | 60 ++++++++----- 18 files changed, 313 insertions(+), 126 deletions(-) diff --git a/changelog/8004.md b/changelog/8004.md index 5317a1f6..4bf01d80 100644 --- a/changelog/8004.md +++ b/changelog/8004.md @@ -7,6 +7,44 @@ description: 'Release notes for the 8004 Protocol.' Release notes for the 8004 Protocol. +
+
Oct 27, 2026
+
+ +### Subgraph defaults, aliases and contract errors + +
DocsFix
+ +- **Subgraph** — the Python SDK ships default subgraph URLs for Base Mainnet and Base Sepolia (TypeScript ships none; BSC has none in either), so the pages no longer say a subgraph always has to be deployed by you. +- **Config and aliases** — Python-only `embeddings`; `feeLimit` defaults (120,000,000 SUN in TypeScript, 10,000,000 in Python); TypeScript's `bsc` / `bsc:mainnet` / `evm` aliases, all of which resolve to BSC Testnet unless `chainId: 56` is passed; the TypeScript IPFS prerequisite is an `ipfsUploader` callback, and Python RPC endpoints include Base. +- **New: Common Contract Errors** — the registry revert reasons a reader hits through the documented flows (`Not authorized`, `reserved key`, `expired`, `invalid wallet sig`, `Self-feedback not allowed`, …) with their causes. + +👉 [Configure Agents](/8004/Usage/ConfigureAgents/) · [SDK Feature Matrix](/8004/sdk-features/) + +
+
+ +
+
Oct 23, 2026
+
+ +### Docs aligned with 8004 SDK 1.2.1 + +
DocsFix
+ +- **Release** — the feature matrix names `@bankofai/8004-sdk` 1.2.1 (the Python package is still not on PyPI). The TypeScript SDK needs Node.js 22.23.4+ (22.x), 24.22.1+ (24.x), or 26.12.1+ (26.x). +- **Base networks** — Base Mainnet and Base Sepolia, with their official ERC-8004 registry addresses, are documented (all three registries in TypeScript; Identity and Reputation only in Python, via `eip155:8453` / `eip155:84532`). TRON agent IDs use the network's chain ID as prefix (for example `3448148188:` on Nile). +- **Registration files** — since 1.2.0, `registerIPFS()` publishes the canonical registration-v1 keys (`services`, `x402Support`, `registrations`) and uses the TRC-8004 `type` on TRON. TypeScript `toJSON()` still returns the internal names, so map them before hosting the file yourself. This updates the Sep 9 note. +- **Feature matrix** — adds the TypeScript registry read APIs, the new `register()` overloads, and per-agent approvals; reading an agent's owner is now supported in both languages. The TypeScript `updateRegistration` sample now type-checks under `strict`. +- **On-chain metadata sample** — the TypeScript sample called `agent.register()`, which always mints a new agent; it now uses `updateOnChainMetadata()`. The Python sample now writes staged keys through `registerIPFS()`, since on a registered agent `register(uri)` and `updateRegistration()` only update the URI. +- **BSC network names** — the network table listed BSC as `mainnet` / `testnet`, but a bare `mainnet` resolves to TRON and TypeScript rejects `testnet`. BSC is now given as `eip155:56` / `eip155:97`. +- **Indexing and IPFS** — Python `refreshIndex()` / `refreshAgentIndex()` are marked as not working in 1.2.1 (the SDK builds its indexer without the Identity Registry), so without a subgraph Python `getAgent()` raises `Agent … not found in index` and TypeScript returns `undefined`. TypeScript reads `ipfs://` URIs through the public `ipfs.io` gateway; Python needs an IPFS client for that and for `giveFeedback(feedbackFile=...)`. The TRON chain-ID agent IDs date from 1.1.2, not 1.2.0. + +👉 [SDK Feature Matrix](/8004/sdk-features/) · [Supported Networks](/8004/SupportedNetworks/) · [Contracts](/8004/contract/) + +
+
+
Sep 9, 2026
diff --git a/docs/8004/QuickStart.md b/docs/8004/QuickStart.md index c2ab8495..70aca13e 100644 --- a/docs/8004/QuickStart.md +++ b/docs/8004/QuickStart.md @@ -117,6 +117,8 @@ agent.setActive(True) agent.setX402Support(False) # Register on-chain +# Replace with the URL where you host this agent's registration JSON; +# loadAgent() below fetches it, and a URL that does not serve it raises an HTTP error. reg_tx = agent.register("https://example.com/agent-card.json") reg = reg_tx.wait_confirmed(timeout=180).result @@ -185,6 +187,7 @@ async function main() { agent.setX402Support(false); // Register on-chain + // Replace with the URL where you host this agent's registration JSON. const tx = await agent.register("https://example.com/agent-card.json"); const { result: registrationFile } = await tx.waitConfirmed(); diff --git a/docs/8004/SupportedNetworks.md b/docs/8004/SupportedNetworks.md index 12770400..7cda8527 100644 --- a/docs/8004/SupportedNetworks.md +++ b/docs/8004/SupportedNetworks.md @@ -8,10 +8,14 @@ The SDK currently supports the following networks and default RPC/node endpoints | :--- | :--- | :--- | :--- | | **EVM** | BSC Mainnet | `eip155:56` (`chainId=56`) | `https://bsc-dataseed.binance.org` | | **EVM** | BSC Testnet | `eip155:97` (`chainId=97`) | `https://data-seed-prebsc-1-s1.binance.org:8545` | +| **EVM** | Base Mainnet | `eip155:8453` (`chainId=8453`) | `https://mainnet.base.org` | +| **EVM** | Base Sepolia | `eip155:84532` (`chainId=84532`) | `https://sepolia.base.org` | | **TRON** | TRON Mainnet | `mainnet` | `https://api.trongrid.io` | | **TRON** | Nile Testnet | `nile` | `https://nile.trongrid.io` | | **TRON** | Shasta Testnet | `shasta` | `https://api.shasta.trongrid.io` | Notes: -- Explorer defaults are `bscscan.com` / `testnet.bscscan.com` for BSC and `tronscan.org` variants for TRON. -- Subgraph URL is currently optional and may be unavailable depending on deployment. +- Explorer defaults are `bscscan.com` / `testnet.bscscan.com` for BSC, `basescan.org` / `sepolia.basescan.org` for Base, and `tronscan.org` variants for TRON. +- Base was added to the TypeScript SDK in 1.2.0; it also accepts the aliases `base` and `base:sepolia`. The Python SDK has no Base aliases and no Base Validation Registry entry; it only knows the Identity and Reputation Registry addresses for `chainId` 8453 / 84532, so pass `network="eip155:8453"` / `"eip155:84532"`. A bare `network="base"` is not rejected in Python: it falls back to chainId 97 (BSC Testnet). +- The default endpoints apply to the TypeScript SDK. The Python SDK has no default endpoint: `rpcUrl` is required, and `SDK(...)` raises `rpcUrl is required` without it. +- Subgraph is optional. The Python SDK has built-in subgraph URLs for Base Mainnet and Base Sepolia; the TypeScript SDK has none, so pass `subgraphUrl`. BSC has no built-in subgraph in either SDK. diff --git a/docs/8004/Usage/ConfigureAgents.md b/docs/8004/Usage/ConfigureAgents.md index 55f44891..9fc7aedd 100644 --- a/docs/8004/Usage/ConfigureAgents.md +++ b/docs/8004/Usage/ConfigureAgents.md @@ -172,9 +172,9 @@ agent.setMCP("https://mcp.example.com/"); -When you set the MCP endpoint, the SDK will automatically: -* Fetch tools, prompts, and resources from the endpoint. -* Populate the agent's capabilities. +What `setMCP()` does beyond recording the endpoint differs by language: +* **Python**: by default (`auto_fetch=True`) it fetches tools, prompts, and resources from the endpoint and stores them on the MCP endpoint entry as `mcpTools`, `mcpPrompts`, and `mcpResources`. A failed fetch is skipped: network and parse errors are logged only at debug level, and a non-HTTP(S) endpoint logs a warning. Pass `auto_fetch=False` to turn this off. +* **TypeScript**: it only records the endpoint URL and version (default `2025-06-18`). It does not contact the endpoint. ### A2A (Agent-to-Agent) Endpoint @@ -200,9 +200,9 @@ agent.setA2A("https://a2a.example.com/agent-card.json"); -The SDK will automatically: -* Fetch skills from the A2A agent card. -* Index these capabilities for search. +What `setA2A()` does beyond recording the endpoint differs by language: +* **Python**: by default (`auto_fetch=True`) it fetches the skill tags (`skills[].tags`) from the A2A agent card and stores them on the A2A endpoint entry as `a2aSkills`. A failed fetch is skipped: network and parse errors are logged only at debug level, and a non-HTTP(S) endpoint logs a warning. Pass `auto_fetch=False` to turn this off. +* **TypeScript**: it only records the agent card URL and version (default `0.3.0`). It does not fetch the card. ### ENS @@ -227,9 +227,9 @@ agent.setENS("myagent.eth"); -This stores the ENS name in: -* The registration file. -* As on-chain metadata. +Both SDKs store the ENS name as an `ENS` endpoint in the registration file. Writing it on-chain as the `agentName` metadata key differs: +* **Python**: the first `register()` (minting) writes `agentName` on-chain for you; on an already registered agent, `register(uri)` only updates the URI, so use `registerIPFS()`, which writes changed metadata including `agentName`. +* **TypeScript**: `setENS()` only changes the local registration file, and `register()` / `registerIPFS()` do not send `agentName`. Call `await agent.updateOnChainMetadata()` on a registered agent to write it. ### Remove Endpoints @@ -369,7 +369,7 @@ The SDK builds the typed data for you, but it cannot invent the new wallet's sig | :--- | :--- | | `signature` (Python) / `signature` (TS) | Uses your bytes as-is. This is the path for smart contract wallets and any external/offline signer. | | `new_wallet_signer` (Python) / `newWalletSigner` (TS) | Signs with that key. The SDK checks the key's address against `newWallet` first and raises if they differ. | -| neither | Falls back to the SDK signer — **and this only succeeds if the SDK signer's address is the new wallet**. Otherwise it raises `New wallet must sign. Provide new_wallet_signer (EOA) or signature (ERC-1271/external).` | +| neither | Falls back to the SDK signer — **and this only succeeds if the SDK signer's address is the new wallet**. Otherwise Python raises `New wallet must sign. Provide new_wallet_signer (EOA) or signature (ERC-1271/external).` and TypeScript throws `newWalletSigner address (…) does not match newWallet (…).` If the TypeScript SDK has no signer at all, it throws `New wallet signature is required. Provide options.newWalletSigner or options.signature.` | :::caution The bare one-argument call is not the general case `setWallet(address)` with no signing option works **only** when the SDK signer already is that address. Since the transaction sender must also be the owner or an approved operator, the bare call is effectively for "point the agent at the wallet I am already signing with". To attach a wallet that is *different* from the SDK signer, you must supply `new_wallet_signer` / `newWalletSigner` or a ready-made `signature`. @@ -400,10 +400,9 @@ agent.addSkill("advanced_reasoning_planning/strategic_planning", validate_oasf=T ```typescript -// Add a skill without validation +// The TypeScript SDK does not validate against the OASF taxonomy: +// addSkill() accepts any string agent.addSkill("custom_skill/my_skill"); - -// Add a skill with validation agent.addSkill("advanced_reasoning_planning/strategic_planning"); ``` @@ -430,10 +429,9 @@ agent.addDomain("finance_and_business/investment_services", validate_oasf=True) ```typescript -// Add a domain without validation +// The TypeScript SDK does not validate against the OASF taxonomy: +// addDomain() accepts any string agent.addDomain("custom_domain/my_domain"); - -// Add a domain with validation agent.addDomain("finance_and_business/investment_services"); ``` @@ -568,21 +566,26 @@ Certain properties can be managed directly as on-chain metadata. ```python -# Update on-chain metadata +# Update on-chain metadata (the agent must already be registered) agent.setMetadata({"version": "1.1.0", "tier": "pro"}) -# If already registered and updating URI, you can call: -# tx = agent.updateRegistration(agentURI="https://example.com/agent-card-updated.json") -# tx.wait_confirmed(timeout=180) +# setMetadata() only stages the keys. On a registered agent, the next registerIPFS() +# (requires an IPFS client) uploads the file, replaces the URI with ipfs://..., and then +# writes each changed key on chain (best-effort) inside wait_confirmed(). +# register(uri) and updateRegistration() update only the URI of a registered agent. +tx = agent.registerIPFS() +tx.wait_confirmed(timeout=180) ``` ```typescript -// Update on-chain metadata +// Update on-chain metadata (the agent must already be registered) agent.setMetadata({ version: "1.1.0", tier: "pro" }); -const tx = await agent.register("https://example.com/agent-card-updated.json"); -await tx.waitConfirmed(); +// Sends one setMetadata transaction per key in the local metadata (plus agentName +// when an ENS name is set) and returns their hashes. +// Do not call register() here: it always mints a new agent. +const txHashes = await agent.updateOnChainMetadata(); ``` @@ -608,8 +611,8 @@ agent = sdk.loadAgent("97:123") ```typescript -// Query agent summary by ID -const agentSummary = await sdk.getAgent("97:123"); +// Load agent by ID +const agent = await sdk.loadAgent("97:123"); ``` @@ -634,9 +637,11 @@ print(agent.active) ```typescript -console.log(agentSummary?.name); -console.log(agentSummary?.description); -console.log(agentSummary?.active); +// The TypeScript Agent has no name/description/active getters; read them from toJSON() +const file = agent.toJSON(); +console.log(file.name); +console.log(file.description); +console.log(file.active); ``` @@ -680,7 +685,7 @@ const agent = sdk.createAgent({ }); agent.setMCP("https://mcp.example.com/") - .setMetadata({ ens: "advanced-agent.eth" }) + .setENS("advanced-agent.eth") .addSkill("advanced_reasoning_planning/strategic_planning") .addDomain("technology/data_science/data_science") .setActive(true) @@ -693,4 +698,23 @@ await tx.waitConfirmed(); - \ No newline at end of file + + +## Common Contract Errors + +These revert reasons come from the TRC-8004 / ERC-8004 registry contracts; the "Where" column names the contract function and the SDK calls that send it. On EVM networks a string reason such as `Not authorized` appears in the SDK's transaction error (usually from gas estimation). A custom ERC-721 error raised inside a Reputation or Validation call, such as `giveFeedback()` on an unregistered agent, may show only as its selector (`0x7e273289` is `ERC721NonexistentToken`). On TRON both SDKs report only `TRON transaction reverted: (REVERT)`, so look the transaction up on TronScan to see the reason. + +| Revert reason | Where | Cause and fix | +| --- | --- | --- | +| `Not authorized` | Identity Registry `setMetadata` / `setAgentURI` / `setAgentWallet`, sent by `updateOnChainMetadata()`, `updateRegistration()`, `registerIPFS()` and `setWallet()`; Validation Registry `validationRequest` | The sender is not the agent's owner, approved address or operator. Sign with the owner, or `addOperator()` (TypeScript also `agent.approve()`) first | +| `ERC721InsufficientApproval` | `transferFrom`, sent by TypeScript `transfer()` | The sender is not the owner, approved address or operator. Python `transfer()` checks the owner before sending and raises `ValueError: Only the current owner (…) can transfer the agent` instead | +| `reserved key` | `register()` metadata, `setMetadata` | `agentWallet` is reserved; use `setWallet()` | +| `bad wallet` / `expired` / `deadline too far` | `setWallet` | Zero address; `deadline` already passed; `deadline` more than 5 minutes ahead | +| `invalid wallet sig` | `setWallet` | The signature was not produced by the new wallet (ECDSA, or ERC-1271 for contract wallets) | +| `Self-feedback not allowed` | `giveFeedback` | The agent's owner, an operator or the approved address rated the agent | +| `index must be > 0` / `index out of bounds` | `revokeFeedback`, `appendResponse`, `readFeedback` (SDK `getFeedback()`) | `feedbackIndex` is 0, or higher than the last feedback that client gave the agent (including when it gave none) | +| `Already revoked` | `revokeFeedback` | The feedback was already revoked | +| `Empty URI` | `appendResponse` | `responseURI` is empty. Python `appendResponse()` builds the URI only when an IPFS client is configured and the response has `text` or `attachments`; otherwise, or when the IPFS upload fails, it sends an empty URI and hits this error | +| `clientAddresses required` | `getSummary`, called by Python `getReputationSummary()` without a subgraph | The agent has no feedback yet, so the client list read from the chain is empty. `sdk.getReputationSummary()` takes no client list, so treat this as "no reputation yet" (TypeScript returns zeros instead) | +| `exists` / `not validator` / `resp>100` / `unknown` | Validation request / response | Duplicate request hash; responder is not the named validator; score above 100; unknown request hash | +| `ERC721NonexistentToken` | Identity Registry writes and `ownerOf` / `tokenURI` reads, `giveFeedback`, `validationRequest` | The agent ID is not registered on the configured network. Python `loadAgent()` raises `Failed to load agent …`; TypeScript `loadAgent()` does not throw and returns an agent with an empty URI | diff --git a/docs/8004/Usage/Install.md b/docs/8004/Usage/Install.md index 7335ef8d..6e6d3d21 100644 --- a/docs/8004/Usage/Install.md +++ b/docs/8004/Usage/Install.md @@ -7,7 +7,7 @@ * **Python**: 3.11 or higher * **pip**: Package manager * **Private Key**: For signing transactions (not required for read-only mode) -* **RPC Node**: An RPC endpoint for a [supported network](/8004/SupportedNetworks/) — an EVM endpoint for BSC, or a TRON node endpoint +* **RPC Node**: An RPC endpoint for a [supported network](/8004/SupportedNetworks/) — an EVM endpoint for BSC or Base, or a TRON node endpoint * **IPFS Provider (Optional)**: Pinata, Filecoin account, or local IPFS node * **Subgraph (Optional)**: Use this when your deployment provides a subgraph endpoint @@ -42,11 +42,11 @@ pip install -e . ## Install with TypeScript ### Prerequisites -* **Node.js**: 20 or higher +* **Node.js**: 22.23.4+ (22.x), 24.22.1+ (24.x), or 26.12.1+ (26.x) * **npm or yarn**: Package manager * **Write Operation Configuration**: Write operations require configuring a `signer` (private key string) -* **RPC Node**: An RPC endpoint for a [supported network](/8004/SupportedNetworks/) — an EVM endpoint for BSC, or a TRON node endpoint -* **IPFS Provider (Optional)**: Pinata, Filecoin account, or local IPFS node +* **RPC Node**: An RPC endpoint for a [supported network](/8004/SupportedNetworks/) — an EVM endpoint for BSC or Base, or a TRON node endpoint +* **IPFS (Optional)**: the TypeScript SDK has no built-in provider; pass an `ipfsUploader` callback for `registerIPFS()` * **Subgraph (Optional)**: You may provide `subgraphUrl` or `subgraphOverrides` as needed. diff --git a/docs/8004/Usage/RegistrationHTTP.md b/docs/8004/Usage/RegistrationHTTP.md index 82febd72..fdc2c84b 100644 --- a/docs/8004/Usage/RegistrationHTTP.md +++ b/docs/8004/Usage/RegistrationHTTP.md @@ -347,7 +347,7 @@ const jsonContent = JSON.stringify(registrationData, null, 2); // 5. Update the URI on-chain (only if the URI has changed) const tx = await agent.updateRegistration("https://yourdomain.com/agents/my-agent-updated.json"); -await tx.waitConfirmed(); +if ("waitConfirmed" in tx) await tx.waitConfirmed(); // returns the Agent itself when no URI is passed ``` @@ -396,7 +396,8 @@ The SDK generates a registration file compliant with the 8004 standard: } ``` -**Note:** two things to watch when you publish this file. +**Note:** three things to watch when you publish this file. -* **TypeScript does not emit these keys.** Python's `registrationFile().to_dict()` (and `str(...)`) produces exactly the shape above. In `@bankofai/8004-sdk` **1.1.2**, `agent.toJSON()` returns the SDK's internal shape — `endpoints` and `x402support` — and `uploadRegistrationFile()` serialises that object as-is, so `registerIPFS()` publishes the internal keys too. Map `endpoints` → `services` and `x402support` → `x402Support` yourself before hosting the file from TypeScript. +* **TypeScript's `toJSON()` is not this shape.** Python's `registrationFile().to_dict()` (and `str(...)`) produces the keys above, but for an agent built with `createAgent()` neither carries chain or registry info, so `registrations` comes out as `[]` and `type` is the EIP-8004 URL even on TRON; `agent.toJson()` passes that info and fills in `registrations` (once the agent has an ID) and the TRON `type`. In `@bankofai/8004-sdk` **1.2.1**, `agent.toJSON()` still returns the SDK's internal shape — `endpoints` and `x402support` — so map `endpoints` → `services` and `x402support` → `x402Support` yourself before hosting the file from TypeScript. `registerIPFS()` does not need this: since 1.2.0 it publishes the canonical keys (`type`, `services`, `registrations` with the minted agent ID, `x402Support`), plus TypeScript's own `tags` and `metadata`, and `loadAgent()` reads both the canonical and the internal key names. +* **TRON uses a different `type`.** On TRON, the file that `registerIPFS()` publishes in either SDK — and Python's `agent.toJson()` — sets `type` to `https://github.com/tronprotocol/tips/blob/master/tip-8004.md#registration-v1` instead of the EIP-8004 URL. * `setA2A()` defaults the endpoint version to `0.30` in Python and `0.3.0` in TypeScript. Pass the version explicitly if you need both languages to agree. diff --git a/docs/8004/contract.md b/docs/8004/contract.md index 7743929d..5e8c07e4 100644 --- a/docs/8004/contract.md +++ b/docs/8004/contract.md @@ -17,3 +17,11 @@ | BSC Testnet | IdentityRegistry | 0x8004A818BFB912233c491871b3d84c89A494BD9e | | BSC Testnet | ReputationRegistry | 0x8004B663056A597Dffe9eCcC1965A193B7388713 | | BSC Testnet | ValidationRegistry | 0x8004Cb1BF31DAf7788923b405b754f57acEB4272 | +| Base Mainnet | IdentityRegistry | 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432 | +| Base Mainnet | ReputationRegistry | 0x8004BAa17C55a88189AE136b182e5fdA19dE9b63 | +| Base Mainnet | ValidationRegistry | 0x8004Cc8439f36fd5F9F049D9fF86523Df6dAAB58 | +| Base Sepolia | IdentityRegistry | 0x8004A818BFB912233c491871b3d84c89A494BD9e | +| Base Sepolia | ReputationRegistry | 0x8004B663056A597Dffe9eCcC1965A193B7388713 | +| Base Sepolia | ValidationRegistry | 0x8004Cb1BF31DAf7788923b405b754f57acEB4272 | + +The Base addresses are the official ERC-8004 Registry deployments that the TypeScript SDK (1.2.0 and later) is configured with. The Python SDK ships only the Identity and Reputation Registry addresses for Base. diff --git a/docs/8004/general.md b/docs/8004/general.md index 8a9c9de9..e7abe194 100644 --- a/docs/8004/general.md +++ b/docs/8004/general.md @@ -26,7 +26,7 @@ The 8004 Protocol leverages the blockchain as a shared public registry that anyo This file defines the Agent’s basic information, payment wallet, and multiple communication endpoints (such as Web, MCP, DID, etc.), and supports automatic domain matching or `.well-known` path verification to confirm endpoint ownership. - As an NFT asset, the Agent identity is transferable. Upon ownership transfer, the payment address is automatically reset to ensure secure control of service revenue by the new owner. + As an NFT asset, the Agent identity is transferable. Upon ownership transfer, the payment address (`agentWallet`) is cleared, so the previous owner's wallet stops receiving service revenue; the new owner sets a new one with `setWallet`. - **Reputation System** diff --git a/docs/8004/sdk-features.md b/docs/8004/sdk-features.md index a704a0e1..42a310cb 100644 --- a/docs/8004/sdk-features.md +++ b/docs/8004/sdk-features.md @@ -9,7 +9,7 @@ This page tracks what the 8004 SDK actually implements, and where the TypeScript > **Two implementations, one repository.** `8004-sdk` ships a TypeScript package and a Python package from the same repository (`ts/` and `python/`). They target the same contracts and the same registration file format, but **they are not feature-identical** — the gaps are listed under [Language parity](#language-parity). > -> **Current release:** `@bankofai/8004-sdk` **1.1.2** on npm; the Python package is not on PyPI, so install it from the repository's `main` branch. TypeScript requires **Node.js ≥ 20**; Python requires **Python ≥ 3.11**. +> **Current release:** `@bankofai/8004-sdk` **1.2.1** on npm; the Python package (source version `1.2.1`) is not on PyPI, so install it from the repository's `main` branch. TypeScript requires **Node.js 22.23.4+ (22.x), 24.22.1+ (24.x), or 26.12.1+ (26.x)**; Python requires **Python ≥ 3.11**. --- @@ -40,24 +40,30 @@ The Python package is not yet published to PyPI; install it from the repository. | `SDK` — chain clients, registries, top-level calls | ✅ | ✅ | | | `Agent` — registration file builder + on-chain agent | ✅ | ✅ | | | `TransactionHandle` — await confirmation, map the result | ✅ | ✅ | `waitConfirmed()` / `wait_confirmed()` | -| `SubgraphClient` — indexed queries | ✅ | ✅ | Optional; requires a deployed subgraph | +| `SubgraphClient` — indexed queries | ✅ | ✅ | Optional. Python ships default subgraph URLs for Base Mainnet and Base Sepolia (and Ethereum, Polygon, Sepolia); TypeScript ships none, so pass `subgraphUrl`. Neither has a BSC default | | `AgentIndexer` | ✅ | ✅ | Python also exposes `refreshIndex` / `refreshAgentIndex` | --- ## Networks -Contract addresses ship with the SDK in `resource/chains.json` and are identical in both languages. The full list is on the [Contract Addresses](/8004/contract/) page. +Contract addresses ship with the SDK. The BSC and TRON entries are identical in both languages; for Base, the TypeScript SDK configures all three registries, while the Python SDK knows only the Identity and Reputation Registry addresses. The full list is on the [Contract Addresses](/8004/contract/) page. + +Pass BSC as `eip155:56` / `eip155:97`. A bare `mainnet` resolves to **TRON** mainnet in both SDKs, and a bare `testnet` is rejected by TypeScript (Python falls back to chainId 97). TypeScript additionally accepts `bsc`, `bsc:mainnet` and `evm`, but without `chainId: 56` **all three resolve to BSC Testnet (97)** — including `bsc:mainnet`. Use `eip155:56` for BSC Mainnet. | Ecosystem | Network name | CAIP-2 / chainId | EIP-712 chainId | Default endpoint | |---|---|---|---|---| -| BSC | `mainnet` | `eip155:56` / `56` | `56` | `https://bsc-dataseed.binance.org` | -| BSC | `testnet` | `eip155:97` / `97` | `97` | `https://data-seed-prebsc-1-s1.binance.org:8545` | -| TRON | `mainnet` | — | `728126428` | `https://api.trongrid.io` | -| TRON | `nile` | — | `3448148188` | `https://nile.trongrid.io` | -| TRON | `shasta` | — | `2494104990` | `https://api.shasta.trongrid.io` | +| BSC | `eip155:56` | `eip155:56` / `56` | `56` | `https://bsc-dataseed.binance.org` | +| BSC | `eip155:97` | `eip155:97` / `97` | `97` | `https://data-seed-prebsc-1-s1.binance.org:8545` | +| Base | `base` | `eip155:8453` / `8453` | `8453` | `https://mainnet.base.org` | +| Base | `base:sepolia` | `eip155:84532` / `84532` | `84532` | `https://sepolia.base.org` | +| TRON | `mainnet` | — / `728126428` | `728126428` | `https://api.trongrid.io` | +| TRON | `nile` | — / `3448148188` | `3448148188` | `https://nile.trongrid.io` | +| TRON | `shasta` | — / `2494104990` | `2494104990` | `https://api.shasta.trongrid.io` | + +Use the bare TRON names (`mainnet` / `nile` / `shasta`) — that is what the examples show. Both SDKs also accept a `tron:`-prefixed alias (`tron:nile`, and a bare `tron` resolves to Nile), stripping the prefix internally; these are the SDK's own aliases, not the CAIP-2 identifiers x402 uses. The EIP-712 chainId column is what the SDK puts in the typed-data domain when signing an agent-wallet change on TRON. Since 1.1.2 both SDKs also use that value as the TRON chainId, so agent IDs take the form `3448148188:` on Nile (older releases produced `1:`; persisted IDs are not rewritten). `loadAgent()` and the reputation calls in both SDKs reject an ID whose chain prefix differs from the configured network; indexer and subgraph queries such as `getAgent()` and `searchFeedback()` do not check it. -Use the bare TRON names (`mainnet` / `nile` / `shasta`) — that is what the examples show. Both SDKs also accept a `tron:`-prefixed alias (`tron:nile`, and a bare `tron` resolves to Nile), stripping the prefix internally; these are the SDK's own aliases, not the CAIP-2 identifiers x402 uses. The EIP-712 chainId column is what the SDK puts in the typed-data domain when signing an agent-wallet change on TRON. +Base uses the official ERC-8004 Registry deployments. TypeScript accepts `base` / `base:mainnet` / `eip155:8453` and `base:sepolia` / `eip155:84532`. Python accepts only `eip155:8453` / `eip155:84532` and has no Base Validation Registry; a bare `network="base"` is not rejected but falls back to chainId 97 (BSC Testnet). --- @@ -68,10 +74,12 @@ Use the bare TRON names (`mainnet` / `nile` / `shasta`) — that is what the exa | Create an agent locally | ✅ | ✅ | `sdk.createAgent(...)` | | Edit name / description / image | ✅ | ✅ | `agent.updateInfo({...})` — edits the local registration file; publish it with `updateRegistration()` | | Register with an HTTP(S) URI | ✅ | ✅ | `agent.register(agentURI)` | -| Register via IPFS upload | ✅ | ✅ | `agent.registerIPFS()` | +| Register without a URI, or with on-chain metadata entries | ✅ | ✅ | TS passes them explicitly: `agent.register()` / `agent.register(agentURI, metadata)`. Python's `register(agentURI)` takes only the URI but mints the metadata staged with `setMetadata()` (plus the ENS name as `agentName`); `registerIPFS()` mints without a URI first | +| Register via IPFS upload | ✅ | ✅ | `agent.registerIPFS()` — for a new agent, mints first, then uploads the file with the minted agent ID and sets the URI (two transactions) | | Update the on-chain URI | ✅ | ✅ | `agent.updateRegistration(...)` | | Set the agent URI locally | ✅ | ✅ | `agent.setAgentUri(uri)` — local only, no transaction | | Load an agent from chain by ID | ✅ | ✅ | `sdk.loadAgent(agentId)` — works without a subgraph | +| Read the on-chain agent URI | ✅ | ❌ | `sdk.getAgentURI(agentId)` | | MCP / A2A / ENS endpoints | ✅ | ✅ | `setMCP()`, `setA2A()`, `setENS()` | | Remove endpoints | ✅ | ✅ | `removeEndpoint()`, `removeEndpoints()` | | OASF skills and domains | ✅ | ✅ | `addSkill()`, `addDomain()`, `removeSkill()`, `removeDomain()` — but stored differently: Python builds an `OASF` entry inside `services` (its `version` is `0.8`), TypeScript pushes the slugs into a flat `tags` array | @@ -79,7 +87,8 @@ Use the bare TRON names (`mainnet` / `nile` / `shasta`) — that is what the exa | Trust models | ✅ | ✅ | `setTrust(...)` — an object in TypeScript, keyword arguments in Python; both cover `reputation`, `cryptoEconomic`, `teeAttestation` | | Replace the trust model list wholesale | ✅ | ✅ | TypeScript `agent.setTrustModels([...])` normalises the names; Python `agent.trustModels([...])` assigns them as given | | Arbitrary metadata | ✅ | ✅ | `setMetadata()` | -| Read / delete a single metadata key | ❌ | ✅ | `agent.getMetadata()`, `agent.delMetadata()` | +| Read local metadata / delete one key | ❌ | ✅ | `agent.getMetadata()` returns a copy of all local metadata; `agent.delMetadata(key)` deletes one key — local registration file | +| Read one on-chain metadata value | ✅ | ❌ | `sdk.getMetadata(agentId, key)` — returns the raw bytes as hex | | Push metadata changes on-chain | ✅ | ❌ | `agent.updateOnChainMetadata()` | | Active flag | ✅ | ✅ | `setActive()`; Python also has `activate()` / `deactivate()` | | x402 support flag | ✅ | ✅ | `setX402Support()` | @@ -118,7 +127,9 @@ All reputation calls live on the `SDK` object in both languages. | Aggregate summary | ✅ | ✅ | `sdk.getReputationSummary(...)` | | Revoke your own feedback | ✅ | ✅ | `sdk.revokeFeedback(...)` | | Append a response to feedback | ✅ | ✅ | `sdk.appendResponse(...)` | -| Search feedback | ✅ | ✅ | `sdk.searchFeedback(...)` — subgraph-backed | +| Search feedback | ✅ | ✅ | `sdk.searchFeedback(...)` — subgraph-backed; without a subgraph, TypeScript returns `[]` and Python reads a single agent's feedback from chain | +| Read all feedback from chain | ✅ | ❌ | `sdk.readAllFeedback(...)` | +| Read clients, last index, response count | ✅ | ❌ | `sdk.getClients()`, `sdk.getLastIndex()`, `sdk.getResponseCount()` | | Build a feedback file | ❌ | ✅ | `sdk.prepareFeedbackFile(...)` | :::note Self-feedback is blocked on-chain @@ -134,6 +145,8 @@ The Reputation Registry rejects feedback from the agent's owner and from any app | Request validation | ✅ | ❌ | `sdk.validationRequest(...)` | | Submit a validator response | ✅ | ❌ | `sdk.validationResponse(...)` | | Read validation status | ✅ | ❌ | `sdk.getValidationStatus(...)` | +| Aggregate validation summary | ✅ | ❌ | `sdk.getValidationSummary(...)` | +| List an agent's / a validator's request hashes | ✅ | ❌ | `sdk.getAgentValidations(...)`, `sdk.getValidatorRequests(...)` | :::caution Validation is TypeScript-only today The Python package resolves the Validation Registry contract and ships its ABI, but exposes **no** validation methods. Use the TypeScript SDK, or call the contract directly, if you need the Validation Registry from Python. @@ -150,11 +163,13 @@ The registry itself is deliberately generic: only the validator named in the req | Transfer the agent | ✅ | ✅ | `agent.transfer(...)`; Python also has `sdk.transferAgent(...)` | | Approve the new owner as operator during transfer | ✅ | ❌ | TS `transfer(to, approveOperator)`; the Python `Agent.transfer` takes only the address | | Add / remove an operator | ✅ | ✅ | `agent.addOperator()`, `agent.removeOperator()` | -| Read the owner | ❌ | ✅ | `sdk.getAgentOwner()` | +| Approve an address for this agent only | ✅ | ❌ | `agent.approve(operator)` | +| Read approvals | ✅ | ❌ | `sdk.getApproved(agentId)`, `sdk.isApprovedForAll(owner, operator)` | +| Read the owner | ✅ | ✅ | `sdk.getAgentOwner()` | | Ownership / transfer pre-checks | ❌ | ✅ | `sdk.isAgentOwner()`, `sdk.canTransferAgent()` | :::note Transfer clears the agent wallet -The Identity Registry clears `agentWallet` on every transfer, so `getAgentWallet()` returns the zero address afterwards. The new owner must call `setWallet()` again. +The Identity Registry clears `agentWallet` on every transfer, so it reads back as the zero address afterwards — which the SDKs report as `undefined` (TypeScript `sdk.getAgentWallet()`) / `None` (Python `agent.getWallet()`). The new owner must call `setWallet()` again. ::: --- @@ -164,13 +179,13 @@ The Identity Registry clears `agentWallet` on every transfer, so `getAgentWallet | Feature | TypeScript | Python | Requires subgraph | |---|:--:|:--:|:--:| | `sdk.loadAgent(agentId)` | ✅ | ✅ | No — reads the chain directly | -| `sdk.getAgent(agentId)` | ✅ | ✅ | Yes | +| `sdk.getAgent(agentId)` | ✅ | ✅ | Yes (Python falls back to its local index cache, which `refreshIndex` cannot fill in 1.2.1 — see below) | | `sdk.searchAgents(filters)` | ✅ | ✅ | Yes | -| `sdk.searchFeedback(filters)` | ✅ | ✅ | Yes | +| `sdk.searchFeedback(filters)` | ✅ | ✅ | Yes, except Python's on-chain fallback for a single `agentId` | | `sdk.getSubgraphClient(chainId?)` — Python `sdk.get_subgraph_client()` | ✅ | ✅ | — returns nothing when unconfigured | -| `sdk.refreshIndex()`, `sdk.refreshAgentIndex()` | ❌ | ✅ | Yes — same indexer as `getAgent` | +| `sdk.refreshIndex()`, `sdk.refreshAgentIndex()` | ❌ | ⚠️ | Broken in 1.2.1: the SDK builds its indexer without the Identity Registry, so `refreshAgentIndex()` raises `Failed to get agent data: Identity registry not available` and `refreshIndex()` returns `[]` | -If no subgraph is configured, the index-backed calls are unavailable — `loadAgent()` remains the way to fetch an agent. +Without a subgraph (TypeScript unless you pass `subgraphUrl` or a `subgraphOverrides` entry for the chain; Python on BSC unless you pass `subgraphOverrides`, and always on TRON), `searchAgents()` is unavailable, Python `getAgent()` raises `Agent … not found in index` and TypeScript `getAgent()` returns `undefined`, TypeScript `searchFeedback()` returns `[]`, and Python `searchFeedback()` works only for a single `agentId`. `loadAgent()` remains the way to fetch an agent. On TRON, Python's `getAgent(":")` still queries a subgraph URL given in `subgraphOverrides` or the `SUBGRAPH_URL_` environment variable. --- @@ -186,9 +201,9 @@ The two languages configure storage completely differently. | Filecoin | `ipfs="filecoinPin"` | `filecoinPrivateKey` | | Self-hosted IPFS node | `ipfs="node"` | `ipfsNodeUrl` | -**TypeScript** ships none of these. `SDKConfig` exposes a single `ipfsUploader?: (json: string) => Promise` callback that you implement yourself; `registerIPFS()` throws `No ipfsUploader configured` without it. +**TypeScript** ships none of these. `SDKConfig` exposes a single `ipfsUploader?: (json: string) => Promise` callback that you implement yourself; `registerIPFS()` throws `No ipfsUploader configured` without it. For a new agent that error comes from `waitConfirmed()`, after the registration transaction has already minted the agent with an empty URI, so configure the uploader first. -IPFS is optional in both languages. It is needed only for `registerIPFS()` and for reading an `ipfs://` agent URI; HTTP(S) registration works without it. +IPFS is optional in both languages. It is needed for `registerIPFS()`; in Python also for reading an `ipfs://` agent URI and for `giveFeedback(feedbackFile=...)` (which raises without an IPFS client). TypeScript reads `ipfs://` URIs through the public `https://ipfs.io/ipfs/` gateway with no configuration. HTTP(S) registration works without IPFS. --- @@ -197,9 +212,9 @@ IPFS is optional in both languages. It is needed only for `registerIPFS()` and f The two implementations diverge in four ways worth planning around: 1. **Validation is TypeScript-only.** See above — this is the largest functional gap. -2. **Defaults and config shapes differ.** `setA2A()` defaults to version `0.30` in Python and `0.3.0` in TypeScript; `subgraphUrl` and `ipfsUploader` are TypeScript-only constructor options, while `registryOverrides`, `indexingStore` and the built-in IPFS providers are Python-only. +2. **Defaults and config shapes differ.** `setA2A()` defaults to version `0.30` in Python and `0.3.0` in TypeScript; `subgraphUrl` and `ipfsUploader` are TypeScript-only constructor options, while `registryOverrides`, `indexingStore`, `embeddings` and the built-in IPFS providers are Python-only. `feeLimit` (TRON, in SUN) defaults to 120,000,000 in TypeScript and 10,000,000 in Python. 3. **Reading agent fields.** Python exposes twenty-one read-only properties on `Agent` (`name`, `description`, `endpoints`, `mcpTools`, `owners`, `operators`, `updatedAt`, and so on). TypeScript exposes only `agent.agentId`; everything else is read through `agent.toJSON()`. -4. **Helper coverage.** Python adds ownership pre-checks (`isAgentOwner`, `canTransferAgent`), metadata accessors (`getMetadata`, `delMetadata`), `activate()` / `deactivate()`, and `saveToFile()`. TypeScript adds `updateOnChainMetadata()`, `uploadRegistrationFile()` and `submitRegister()`. +4. **Helper coverage.** TypeScript also exposes `sdk.getTypedDataChainId()`; Python also exposes `sdk.chain_id()`, `sdk.registries()`, `sdk.set_chain()`, `sdk.isReadOnly` and `agent.registrationFile()` / `agent.toJson()`. Python adds ownership pre-checks (`isAgentOwner`, `canTransferAgent`), metadata accessors (`getMetadata`, `delMetadata`), `activate()` / `deactivate()`, and `saveToFile()`. TypeScript adds `updateOnChainMetadata()`, `uploadRegistrationFile()`, `submitRegister()`, `agent.approve()`, and the Registry read calls listed above (`getAgentURI`, `sdk.getMetadata`, `getApproved`, `isApprovedForAll`, `readAllFeedback`, `getClients`, `getLastIndex`, `getResponseCount`, and the validation reads). :::note Two Python names are defined twice In the Python `Agent` class, `transfer` and `trustModels` are each defined twice and the later definition wins. The effective `transfer` is `transfer(newOwnerAddress)` — the earlier four-argument form with `approve_operator` is unreachable — and the read-only `trustModels` property is shadowed by the setter of the same name, so `agent.trustModels` returns the bound method rather than the list. Read the trust models from `agent.registrationFile()` instead. @@ -211,3 +226,4 @@ In the Python `Agent` class, `transfer` and `trustModels` are each defined twice - ✅ = Implemented - ❌ = Not implemented in this language +- ⚠️ = Present but not working in the current release diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs-changelog/current/8004.md b/i18n/zh-Hans/docusaurus-plugin-content-docs-changelog/current/8004.md index d43b3c99..91b74ddc 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs-changelog/current/8004.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs-changelog/current/8004.md @@ -7,6 +7,44 @@ description: '8004 协议的版本发布记录。' 8004 协议的版本发布记录。 +
+
2026-10-27
+
+ +### Subgraph 默认值、别名与合约错误 + +
文档修复
+ +- **Subgraph**——Python SDK 内置了 Base 主网与 Base Sepolia 的默认 subgraph 地址(TypeScript 没有;BSC 两边都没有),相关页面不再说 subgraph 一定要自行部署。 +- **配置与别名**——Python 独有的 `embeddings`;`feeLimit` 默认值(TypeScript 120,000,000 SUN,Python 10,000,000);TypeScript 的 `bsc` / `bsc:mainnet` / `evm` 别名,不传 `chainId: 56` 时都会解析为 BSC 测试网;TypeScript 的 IPFS 前置条件是 `ipfsUploader` 回调;Python 的 RPC 端点包含 Base。 +- **新增「常见合约错误」**——按文档流程会碰到的注册表回退原因(`Not authorized`、`reserved key`、`expired`、`invalid wallet sig`、`Self-feedback not allowed` 等)及其原因。 + +👉 [配置 Agent](/zh-Hans/8004/Usage/ConfigureAgents/) · [SDK 功能矩阵](/zh-Hans/8004/sdk-features/) + +
+
+ +
+
2026-10-23
+
+ +### 文档对齐 8004 SDK 1.2.1 + +
文档修复
+ +- **版本**——功能矩阵改为 `@bankofai/8004-sdk` 1.2.1(Python 包仍未发布到 PyPI)。TypeScript SDK 需要 Node.js 22.23.4+(22.x)、24.22.1+(24.x)或 26.12.1+(26.x)。 +- **Base 网络**——补充 Base 主网与 Base Sepolia 及其官方 ERC-8004 注册表地址(TypeScript 支持全部三个注册表;Python 仅支持身份与信誉注册表,需使用 `eip155:8453` / `eip155:84532`)。TRON 上的 Agent ID 以所在网络的 chainId 为前缀(如 Nile 上为 `3448148188:`)。 +- **注册文件**——自 1.2.0 起,`registerIPFS()` 发布规范的 registration-v1 键名(`services`、`x402Support`、`registrations`),TRON 上使用 TRC-8004 的 `type`。TypeScript 的 `toJSON()` 仍返回内部键名,自行托管文件前需要转换。本条更新了 9 月 9 日的说明。 +- **功能矩阵**——补充 TypeScript 注册表读取 API、`register()` 新重载和单个 Agent 授权;读取 Agent 所有者现在两种语言都支持。TypeScript 的 `updateRegistration` 示例现可在 `strict` 下通过类型检查。 +- **链上元数据示例**——TypeScript 示例原先调用 `agent.register()`,它总会铸造新 Agent;现改用 `updateOnChainMetadata()`。Python 示例改为通过 `registerIPFS()` 写入暂存的键,因为对已注册的 Agent,`register(uri)` 与 `updateRegistration()` 只更新 URI。 +- **BSC 网络名**——网络表原先把 BSC 写成 `mainnet` / `testnet`,但单写 `mainnet` 会解析为 TRON,TypeScript 也会拒绝 `testnet`。BSC 现写为 `eip155:56` / `eip155:97`。 +- **索引与 IPFS**——Python 的 `refreshIndex()` / `refreshAgentIndex()` 标注为 1.2.1 中不可用(SDK 构造索引器时没有传入身份注册表),因此没有 subgraph 时 Python 的 `getAgent()` 会抛出 `Agent … not found in index`,TypeScript 返回 `undefined`。TypeScript 通过公共 `ipfs.io` 网关读取 `ipfs://` URI;Python 读取它以及 `giveFeedback(feedbackFile=...)` 都需要 IPFS 客户端。以 TRON chainId 为前缀的 Agent ID 自 1.1.2 起使用,而非 1.2.0。 + +👉 [SDK 功能矩阵](/zh-Hans/8004/sdk-features/) · [支持的网络](/zh-Hans/8004/SupportedNetworks/) · [合约地址](/zh-Hans/8004/contract/) + +
+
+
2026-09-09
diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/QuickStart.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/QuickStart.md index 564a321b..8a5015e3 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/QuickStart.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/QuickStart.md @@ -118,13 +118,15 @@ agent.setActive(True) agent.setX402Support(False) # Register on-chain +# Replace with the URL where you host this agent's registration JSON; +# loadAgent() below fetches it, and a URL that does not serve it raises an HTTP error. reg_tx = agent.register("https://example.com/agent-card.json") reg = reg_tx.wait_confirmed(timeout=180).result # Optional: point the agent at a dedicated wallet (requires signature verification). # By default the agent wallet is the owner's wallet. The one-argument form below only # works when the SDK signer IS that wallet; otherwise pass new_wallet_signer. -# See Configure Agents -> "How the signature is supplied". +# 参见「配置代理」->「签名从何而来」。 # agent.setWallet("TYourTronWalletAddress") print(f"✅ Agent registered!") @@ -186,13 +188,14 @@ async function main() { agent.setX402Support(false); // Register on-chain + // Replace with the URL where you host this agent's registration JSON. const tx = await agent.register("https://example.com/agent-card.json"); const { result: registrationFile } = await tx.waitConfirmed(); // Optional: point the agent at a dedicated wallet (requires signature verification). // By default the agent wallet is the owner's wallet. The one-argument form below only // works when the SDK signer IS that wallet; otherwise pass newWalletSigner. - // See Configure Agents -> "How the signature is supplied". + // 参见「配置代理」->「签名从何而来」。 // await agent.setWallet('TYourTronWalletAddress'); console.log('✅ Agent registered!'); diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/SupportedNetworks.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/SupportedNetworks.md index e41888fb..91fc377b 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/SupportedNetworks.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/SupportedNetworks.md @@ -9,11 +9,15 @@ SDK 当前支持以下网络及默认 RPC/节点端点: | :--- | :--- | :--- | :--- | | **EVM** | BSC 主网 | `eip155:56` (`chainId=56`) | `https://bsc-dataseed.binance.org` | | **EVM** | BSC 测试网 | `eip155:97` (`chainId=97`) | `https://data-seed-prebsc-1-s1.binance.org:8545` | +| **EVM** | Base 主网 | `eip155:8453` (`chainId=8453`) | `https://mainnet.base.org` | +| **EVM** | Base Sepolia 测试网 | `eip155:84532` (`chainId=84532`) | `https://sepolia.base.org` | | **TRON** | TRON 主网 | `mainnet` | `https://api.trongrid.io` | | **TRON** | Nile 测试网 | `nile` | `https://nile.trongrid.io` | | **TRON** | Shasta 测试网 | `shasta` | `https://api.shasta.trongrid.io` | **说明:** -- BSC 默认区块浏览器为 `bscscan.com` / `testnet.bscscan.com`,TRON 默认浏览器为 `tronscan.org` 及其对应测试网版本。 -- Subgraph URL 当前为可选配置,具体是否可用取决于部署情况。 +- BSC 默认区块浏览器为 `bscscan.com` / `testnet.bscscan.com`,Base 为 `basescan.org` / `sepolia.basescan.org`,TRON 默认浏览器为 `tronscan.org` 及其对应测试网版本。 +- Base 自 1.2.0 起加入 TypeScript SDK,也可使用别名 `base` 与 `base:sepolia`。Python SDK 没有 Base 别名,也没有 Base 的验证注册表条目;它只内置了 `chainId` 8453 / 84532 上身份注册表与信誉注册表的地址,请传 `network="eip155:8453"` / `"eip155:84532"`。在 Python 中单写 `network="base"` 不会报错,而是回落到 chainId 97(BSC 测试网)。 +- 上表的默认端点适用于 TypeScript SDK。Python SDK 没有默认端点:必须传入 `rpcUrl`,否则 `SDK(...)` 会报 `rpcUrl is required`。 +- Subgraph 为可选。Python SDK 内置了 Base 主网与 Base Sepolia 的 subgraph 地址;TypeScript SDK 没有内置,需自行传 `subgraphUrl`。两个 SDK 都没有 BSC 的内置 subgraph。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/Usage/ConfigureAgents.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/Usage/ConfigureAgents.md index 1d35f306..29ec2e18 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/Usage/ConfigureAgents.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/Usage/ConfigureAgents.md @@ -172,9 +172,9 @@ agent.setMCP("https://mcp.example.com/"); -当你设置 MCP 端点时,SDK 会自动: -* 从端点获取工具、提示词(prompts)和资源。 -* 填充代理的能力集(capabilities)。 +除记录端点外,`setMCP()` 的行为因语言而异: +* **Python**:默认(`auto_fetch=True`)会从端点获取工具、提示词(prompts)和资源,并以 `mcpTools`、`mcpPrompts`、`mcpResources` 存入该 MCP 端点条目。获取失败会被跳过:网络和解析错误只在 debug 级别记录,非 HTTP(S) 端点会记录一条 warning。传 `auto_fetch=False` 可关闭。 +* **TypeScript**:只记录端点 URL 和版本(默认 `2025-06-18`),不会访问该端点。 ### A2A (Agent-to-Agent) 端点 @@ -200,9 +200,9 @@ agent.setA2A("https://a2a.example.com/agent-card.json"); -SDK 会自动: -* 从 A2A 代理卡片(agent card)中获取技能。 -* 为搜索索引这些能力。 +除记录端点外,`setA2A()` 的行为因语言而异: +* **Python**:默认(`auto_fetch=True`)会从 A2A 代理卡片(agent card)中获取技能标签(`skills[].tags`),并以 `a2aSkills` 存入该 A2A 端点条目。获取失败会被跳过:网络和解析错误只在 debug 级别记录,非 HTTP(S) 端点会记录一条 warning。传 `auto_fetch=False` 可关闭。 +* **TypeScript**:只记录代理卡片 URL 和版本(默认 `0.3.0`),不会获取该卡片。 ### ENS @@ -227,9 +227,9 @@ agent.setENS("myagent.eth"); -这会将 ENS 名称存储在: -* 注册文件中。 -* 作为链上元数据。 +两个 SDK 都会把 ENS 名称作为 `ENS` 端点存入注册文件。以 `agentName` 元数据键写上链则有区别: +* **Python**:首次 `register()`(铸造)时会自动把 `agentName` 写上链;对已注册的 Agent,`register(uri)` 只更新 URI,需改用 `registerIPFS()`,它会把包括 `agentName` 在内的改动元数据写上链。 +* **TypeScript**:`setENS()` 只修改本地注册文件,`register()` / `registerIPFS()` 也不会发送 `agentName`。需在已注册的 Agent 上调用 `await agent.updateOnChainMetadata()` 才会写上链。 ### 移除端点 @@ -367,7 +367,7 @@ SDK 会替你构造类型化数据,但它无法凭空造出新钱包的签名 | :--- | :--- | | `signature`(Python / TS 同名) | 直接使用你给的字节。这是智能合约钱包以及任何外部/离线签名场景的路径。 | | `new_wallet_signer`(Python)/ `newWalletSigner`(TS) | 用该私钥签名。SDK 会先校验该私钥对应的地址是否等于 `newWallet`,不一致则直接报错。 | -| 两者都不传 | 回退到 SDK signer——**且仅当 SDK signer 的地址就是新钱包时才会成功**。否则抛出 `New wallet must sign. Provide new_wallet_signer (EOA) or signature (ERC-1271/external).` | +| 两者都不传 | 回退到 SDK signer——**且仅当 SDK signer 的地址就是新钱包时才会成功**。否则 Python 抛出 `New wallet must sign. Provide new_wallet_signer (EOA) or signature (ERC-1271/external).`,TypeScript 抛出 `newWalletSigner address (…) does not match newWallet (…).`。若 TypeScript SDK 根本没有 signer,则抛出 `New wallet signature is required. Provide options.newWalletSigner or options.signature.` | :::caution 只传一个地址并不是通用写法 不带任何签名参数的 `setWallet(address)`,**仅**在 SDK signer 本身就是该地址时才可用。又因为交易发送方还必须是所有者或获授权的操作员,所以这种写法实际上只适用于「把 Agent 指向我当前正在用来签名的这个钱包」。若要绑定一个与 SDK signer *不同*的钱包,就必须提供 `new_wallet_signer` / `newWalletSigner`,或一个已经准备好的 `signature`。 @@ -398,10 +398,9 @@ agent.addSkill("advanced_reasoning_planning/strategic_planning", validate_oasf=T ```typescript -// 添加技能而不进行验证 +// TypeScript SDK 不做 OASF 分类法校验: +// addSkill() 接受任意字符串 agent.addSkill("custom_skill/my_skill"); - -// 添加带有验证的技能 agent.addSkill("advanced_reasoning_planning/strategic_planning"); ``` @@ -428,10 +427,9 @@ agent.addDomain("finance_and_business/investment_services", validate_oasf=True) ```typescript -// 添加领域而不进行验证 +// TypeScript SDK 不做 OASF 分类法校验: +// addDomain() 接受任意字符串 agent.addDomain("custom_domain/my_domain"); - -// 添加带有验证的领域 agent.addDomain("finance_and_business/investment_services"); ``` @@ -566,21 +564,25 @@ agent.setTrust({ reputation: true, cryptoEconomic: true, teeAttestation: true }) ```python -# 更新链上元数据 +# 更新链上元数据(Agent 须已注册) agent.setMetadata({"version": "1.1.0", "tier": "pro"}) -# 若已注册并要更新 URI,可调用: -# tx = agent.updateRegistration(agentURI="https://example.com/agent-card-updated.json") -# tx.wait_confirmed(timeout=180) +# setMetadata() 只暂存这些键。对已注册的 Agent,下一次 registerIPFS()(需配置 IPFS 客户端) +# 会上传文件、把 URI 替换为 ipfs://...,然后在 wait_confirmed() 中逐个把改动过的键 +# 写上链(尽力而为)。对已注册的 Agent,register(uri) 与 updateRegistration() 只更新 URI。 +tx = agent.registerIPFS() +tx.wait_confirmed(timeout=180) ``` ```typescript -// 更新链上元数据 +// 更新链上元数据(Agent 须已注册) agent.setMetadata({ version: "1.1.0", tier: "pro" }); -const tx = await agent.register("https://example.com/agent-card-updated.json"); -await tx.waitConfirmed(); +// 本地元数据中的每个键各发送一笔 setMetadata 交易(设置了 ENS 名称时另加一笔 agentName), +// 返回交易哈希列表。 +// 不要在这里调用 register():它总是会铸造一个新 Agent。 +const txHashes = await agent.updateOnChainMetadata(); ``` @@ -606,8 +608,8 @@ agent = sdk.loadAgent("97:123") ```typescript -// 通过 ID 查询代理摘要 -const agentSummary = await sdk.getAgent("97:123"); +// 通过 ID 加载代理 +const agent = await sdk.loadAgent("97:123"); ``` @@ -632,9 +634,11 @@ print(agent.active) ```typescript -console.log(agentSummary?.name); -console.log(agentSummary?.description); -console.log(agentSummary?.active); +// TypeScript 的 Agent 没有 name/description/active 访问器,需从 toJSON() 读取 +const file = agent.toJSON(); +console.log(file.name); +console.log(file.description); +console.log(file.active); ``` @@ -678,7 +682,7 @@ const agent = sdk.createAgent({ }); agent.setMCP("https://mcp.example.com/") - .setMetadata({ ens: "advanced-agent.eth" }) + .setENS("advanced-agent.eth") .addSkill("advanced_reasoning_planning/strategic_planning") .addDomain("technology/data_science/data_science") .setActive(true) @@ -692,3 +696,22 @@ await tx.waitConfirmed(); + +## 常见合约错误 + +以下回退原因来自 TRC-8004 / ERC-8004 注册表合约;"位置"一列写的是合约函数,以及会发送它的 SDK 调用。在 EVM 网络上,`Not authorized` 这类字符串原因会出现在 SDK 的交易错误里(通常来自 gas 估算)。在信誉或验证合约调用里触发的 ERC-721 自定义错误(例如对未注册 Agent 调用 `giveFeedback()`)可能只显示选择器(`0x7e273289` 即 `ERC721NonexistentToken`)。在 TRON 上两种 SDK 都只报 `TRON transaction reverted: (REVERT)`,需要到 TronScan 查看交易才能看到原因。 + +| 回退原因 | 位置 | 原因与处理 | +| --- | --- | --- | +| `Not authorized` | 身份注册表的 `setMetadata` / `setAgentURI` / `setAgentWallet`,由 `updateOnChainMetadata()`、`updateRegistration()`、`registerIPFS()` 和 `setWallet()` 发送;验证注册表的 `validationRequest` | 发送方不是该 Agent 的所有者、被批准地址或操作员。改用所有者签名,或先 `addOperator()`(TypeScript 还可用 `agent.approve()`) | +| `ERC721InsufficientApproval` | `transferFrom`,由 TypeScript 的 `transfer()` 发送 | 发送方不是所有者、被批准地址或操作员。Python 的 `transfer()` 会在发送前检查所有者,直接抛出 `ValueError: Only the current owner (…) can transfer the agent` | +| `reserved key` | `register()` 的元数据、`setMetadata` | `agentWallet` 是保留键,请用 `setWallet()` | +| `bad wallet` / `expired` / `deadline too far` | `setWallet` | 零地址;`deadline` 已过期;`deadline` 超过当前时间 5 分钟 | +| `invalid wallet sig` | `setWallet` | 签名不是由新钱包产生(ECDSA,合约钱包则为 ERC-1271) | +| `Self-feedback not allowed` | `giveFeedback` | Agent 的所有者、操作员或被批准地址给自己的 Agent 评分 | +| `index must be > 0` / `index out of bounds` | `revokeFeedback`、`appendResponse`、`readFeedback`(SDK 的 `getFeedback()`) | `feedbackIndex` 为 0,或大于该客户端给这个 Agent 的最后一条反馈序号(包括从未给过反馈) | +| `Already revoked` | `revokeFeedback` | 该反馈已被撤回 | +| `Empty URI` | `appendResponse` | `responseURI` 为空。Python 的 `appendResponse()` 只有在配置了 IPFS 客户端、且回复带有 `text` 或 `attachments` 时才会生成 URI,否则(或 IPFS 上传失败时)发送空 URI 并触发此错误 | +| `clientAddresses required` | `getSummary`,没有 subgraph 时由 Python 的 `getReputationSummary()` 调用 | 该 Agent 还没有任何反馈,从链上读到的客户端列表为空。`sdk.getReputationSummary()` 不接受客户端列表参数,按「尚无信誉」处理即可(TypeScript 则返回 0) | +| `exists` / `not validator` / `resp>100` / `unknown` | 验证请求 / 响应 | 请求哈希重复;响应者不是指定的验证者;分数超过 100;请求哈希不存在 | +| `ERC721NonexistentToken` | 身份注册表的写操作和 `ownerOf` / `tokenURI` 读取、`giveFeedback`、`validationRequest` | 该 Agent ID 未在所配置网络上注册。Python 的 `loadAgent()` 会抛出 `Failed to load agent …`;TypeScript 的 `loadAgent()` 不报错,返回一个 URI 为空的 Agent | diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/Usage/Install.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/Usage/Install.md index e4175aef..35df961b 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/Usage/Install.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/Usage/Install.md @@ -7,7 +7,7 @@ * **Python**: 3.11 或更高版本 * **pip**: 包管理器 * **私钥**: 用于签署交易(若仅运行只读模式则不需要) -* **RPC 节点**: [受支持网络](/zh-Hans/8004/SupportedNetworks/)的 RPC 端点——BSC 使用 EVM 端点,TRON 使用 TRON 节点端点 +* **RPC 节点**: [受支持网络](/zh-Hans/8004/SupportedNetworks/)的 RPC 端点——BSC 或 Base 使用 EVM 端点,TRON 使用 TRON 节点端点 * **IPFS 提供商(可选)**: Pinata、Filecoin 账号或本地 IPFS 节点 * **Subgraph(可选)**: 当你的部署提供 subgraph 端点时使用 @@ -40,11 +40,11 @@ pip install -e . ## 通过 TypeScript 安装 ### 前置要求 -* **Node.js**: 20 或更高版本 +* **Node.js**: 22.23.4+(22.x)、24.22.1+(24.x)或 26.12.1+(26.x) * **npm 或 yarn**: 包管理器 * **写入操作配置**: 写入操作需配置 `signer`(私钥字符串) -* **RPC 节点**: [受支持网络](/zh-Hans/8004/SupportedNetworks/)的 RPC 端点——BSC 使用 EVM 端点,TRON 使用 TRON 节点端点 -* **IPFS 提供商(可选)**: Pinata、Filecoin 账号或本地 IPFS 节点 +* **RPC 节点**: [受支持网络](/zh-Hans/8004/SupportedNetworks/)的 RPC 端点——BSC 或 Base 使用 EVM 端点,TRON 使用 TRON 节点端点 +* **IPFS(可选)**: TypeScript SDK 没有内置提供商,`registerIPFS()` 需要传入 `ipfsUploader` 回调 * **Subgraph(可选)**: 可按需传入 `subgraphUrl` 或 `subgraphOverrides` diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/Usage/RegistrationHTTP.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/Usage/RegistrationHTTP.md index e5c6f883..564ca7cf 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/Usage/RegistrationHTTP.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/Usage/RegistrationHTTP.md @@ -346,7 +346,7 @@ const jsonContent = JSON.stringify(registrationData, null, 2); // 5. 在链上更新 URI(仅当 URI 发生更改时) const tx = await agent.updateRegistration("https://yourdomain.com/agents/my-agent-updated.json"); -await tx.waitConfirmed(); +if ("waitConfirmed" in tx) await tx.waitConfirmed(); // 未传 URI 时直接返回 Agent 本身 ``` @@ -395,7 +395,8 @@ SDK 会生成符合 8004 标准的注册文件: } ``` -说明:发布这个文件时有两点需要注意。 +说明:发布这个文件时有三点需要注意。 -* **TypeScript 不会输出这两个键。** Python 的 `registrationFile().to_dict()`(以及 `str(...)`)产出的正是上面这种形态。而在 `@bankofai/8004-sdk` **1.1.2** 中,`agent.toJSON()` 返回的是 SDK 内部结构——`endpoints` 与 `x402support`——且 `uploadRegistrationFile()` 会把该对象原样序列化,因此 `registerIPFS()` 发布出去的同样是内部键名。在 TypeScript 中自行托管文件时,请自己把 `endpoints` → `services`、`x402support` → `x402Support` 转换好。 +* **TypeScript 的 `toJSON()` 不是这种形态。** Python 的 `registrationFile().to_dict()`(以及 `str(...)`)产出的键与上面一致,但对 `createAgent()` 创建的 Agent,二者都不带链与注册表信息,因此 `registrations` 为 `[]`,且即使在 TRON 上 `type` 也是 EIP-8004 的 URL;`agent.toJson()` 会传入这些信息,补全 `registrations`(Agent 已有 ID 时)以及 TRON 的 `type`。而在 `@bankofai/8004-sdk` **1.2.1** 中,`agent.toJSON()` 返回的仍是 SDK 内部结构——`endpoints` 与 `x402support`——因此在 TypeScript 中自行托管文件时,请自己把 `endpoints` → `services`、`x402support` → `x402Support` 转换好。`registerIPFS()` 则无需这一步:自 1.2.0 起,它发布的是规范键名(`type`、`services`、带有铸造出的 Agent ID 的 `registrations`、`x402Support`),外加 TypeScript 自有的 `tags` 与 `metadata`;`loadAgent()` 也能同时读取规范键名与内部键名。 +* **TRON 使用不同的 `type`。** 在 TRON 上,两个 SDK 通过 `registerIPFS()` 发布的文件——以及 Python 的 `agent.toJson()`——会把 `type` 设为 `https://github.com/tronprotocol/tips/blob/master/tip-8004.md#registration-v1`,而不是 EIP-8004 的 URL。 * `setA2A()` 的端点版本默认值,Python 为 `0.30`,TypeScript 为 `0.3.0`。若需要两个语言一致,请显式传入版本号。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/contract.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/contract.md index 91a76d03..2ee942ed 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/contract.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/contract.md @@ -17,4 +17,12 @@ | BSC Mainnet | ValidationRegistry | 0x8004Cc8439f36fd5F9F049D9fF86523Df6dAAB58 | | BSC Testnet | IdentityRegistry | 0x8004A818BFB912233c491871b3d84c89A494BD9e | | BSC Testnet | ReputationRegistry | 0x8004B663056A597Dffe9eCcC1965A193B7388713 | -| BSC Testnet | ValidationRegistry | 0x8004Cb1BF31DAf7788923b405b754f57acEB4272 | \ No newline at end of file +| BSC Testnet | ValidationRegistry | 0x8004Cb1BF31DAf7788923b405b754f57acEB4272 | +| Base Mainnet | IdentityRegistry | 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432 | +| Base Mainnet | ReputationRegistry | 0x8004BAa17C55a88189AE136b182e5fdA19dE9b63 | +| Base Mainnet | ValidationRegistry | 0x8004Cc8439f36fd5F9F049D9fF86523Df6dAAB58 | +| Base Sepolia | IdentityRegistry | 0x8004A818BFB912233c491871b3d84c89A494BD9e | +| Base Sepolia | ReputationRegistry | 0x8004B663056A597Dffe9eCcC1965A193B7388713 | +| Base Sepolia | ValidationRegistry | 0x8004Cb1BF31DAf7788923b405b754f57acEB4272 | + +Base 地址为官方 ERC-8004 注册表部署,即 TypeScript SDK(1.2.0 及以上)内置的配置。Python SDK 只内置了 Base 上身份注册表与信誉注册表的地址。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/general.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/general.md index 3baf9406..fdc2cfc0 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/general.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/general.md @@ -15,7 +15,7 @@ ## 核心概念 - **身份认证** - 8004 协议建立了一套无许可的身份认证体系,允许任何 Agent 或服务通过铸造 NFT 兼容身份完成注册,其核心是将链上身份 (agentId) 映射至存储于任意位置(HTTPS、IPFS 或链上)的元数据文件 (agent-registration.json)。该文件定义了 Agent 的基本信息、支付钱包及多样化的通信端点(如 Web、MCP、DID 等),并支持通过域名自动匹配或 `.well-known` 路径验证端点所有权。作为 NFT 资产,Agent 身份具备可转移性,且在所有权转移时会自动重置支付地址,从而确保新所有者对服务收入的安全控制。 + 8004 协议建立了一套无许可的身份认证体系,允许任何 Agent 或服务通过铸造 NFT 兼容身份完成注册,其核心是将链上身份 (agentId) 映射至存储于任意位置(HTTPS、IPFS 或链上)的元数据文件 (agent-registration.json)。该文件定义了 Agent 的基本信息、支付钱包及多样化的通信端点(如 Web、MCP、DID 等),并支持通过域名自动匹配或 `.well-known` 路径验证端点所有权。作为 NFT 资产,Agent 身份具备可转移性,所有权转移时支付地址(`agentWallet`)会被清空,原所有者的钱包不再接收服务收入;新所有者需用 `setWallet` 重新设置。 - **信誉系统** 8004 协议定义了一个中立的公共信誉存储标准。反馈由客户端地址自行提交,归属即由该地址确定,并通过结构化标签支持多维度评价。注册表本身只强制最小限度的规则——尤其是 Agent 的所有者及其授权操作员不能给该 Agent 留下反馈——并提供针对调用方指定客户端集合的链上聚合。除此之外的信誉算法、排名聚合与反垃圾过滤逻辑,均交由生态应用层自主构建。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/sdk-features.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/sdk-features.md index 6a90ec2f..e019e3e3 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/sdk-features.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/8004/sdk-features.md @@ -9,7 +9,7 @@ description: '8004 SDK 在 TypeScript 与 Python 两个实现中的特性支持 > **同一个仓库,两套实现。** `8004-sdk` 从同一仓库(`ts/` 与 `python/`)分别发布 TypeScript 包与 Python 包。它们面向相同的合约、相同的注册文件格式,但**功能并不完全对等**——差异汇总见[语言差异](#语言差异)。 > -> **当前版本:** npm 上的 `@bankofai/8004-sdk` 为 **1.1.2**;Python 包未发布到 PyPI,请从仓库 `main` 分支安装。TypeScript 要求 **Node.js ≥ 20**;Python 要求 **Python ≥ 3.11**。 +> **当前版本:** npm 上的 `@bankofai/8004-sdk` 为 **1.2.1**;Python 包(源码版本 `1.2.1`)未发布到 PyPI,请从仓库 `main` 分支安装。TypeScript 要求 **Node.js 22.23.4+(22.x)、24.22.1+(24.x)或 26.12.1+(26.x)**;Python 要求 **Python ≥ 3.11**。 --- @@ -40,24 +40,30 @@ Python 包尚未发布到 PyPI,请从仓库安装。 | `SDK`——链客户端、注册表、顶层调用 | ✅ | ✅ | | | `Agent`——注册文件构造器 + 链上 Agent | ✅ | ✅ | | | `TransactionHandle`——等待确认并映射结果 | ✅ | ✅ | `waitConfirmed()` / `wait_confirmed()` | -| `SubgraphClient`——索引查询 | ✅ | ✅ | 可选;需已部署 subgraph | +| `SubgraphClient`——索引查询 | ✅ | ✅ | 可选。Python 内置了 Base 主网与 Base Sepolia(以及 Ethereum、Polygon、Sepolia)的默认 subgraph 地址;TypeScript 没有内置,需自行传 `subgraphUrl`。两者都没有 BSC 的默认 subgraph | | `AgentIndexer` | ✅ | ✅ | Python 额外提供 `refreshIndex` / `refreshAgentIndex` | --- ## 支持网络 -合约地址随 SDK 一起分发在 `resource/chains.json` 中,两个语言完全一致。完整列表见[合约地址](/zh-Hans/8004/contract/)页面。 +合约地址随 SDK 一起分发。BSC 与 TRON 的条目在两个语言中完全一致;Base 网络在 TypeScript SDK 中配置了全部三个注册表,Python SDK 只内置了身份注册表与信誉注册表的地址。完整列表见[合约地址](/zh-Hans/8004/contract/)页面。 + +BSC 请写成 `eip155:56` / `eip155:97`。单写 `mainnet` 在两个 SDK 中都会解析为 **TRON** 主网,单写 `testnet` 会被 TypeScript 拒绝(Python 会回落到 chainId 97)。TypeScript 还接受 `bsc`、`bsc:mainnet` 和 `evm`,但不传 `chainId: 56` 时**三者都会解析为 BSC 测试网(97)**——包括 `bsc:mainnet`。BSC 主网请用 `eip155:56`。 | 生态 | 网络名 | CAIP-2 / chainId | EIP-712 chainId | 默认端点 | |---|---|---|---|---| -| BSC | `mainnet` | `eip155:56` / `56` | `56` | `https://bsc-dataseed.binance.org` | -| BSC | `testnet` | `eip155:97` / `97` | `97` | `https://data-seed-prebsc-1-s1.binance.org:8545` | -| TRON | `mainnet` | — | `728126428` | `https://api.trongrid.io` | -| TRON | `nile` | — | `3448148188` | `https://nile.trongrid.io` | -| TRON | `shasta` | — | `2494104990` | `https://api.shasta.trongrid.io` | +| BSC | `eip155:56` | `eip155:56` / `56` | `56` | `https://bsc-dataseed.binance.org` | +| BSC | `eip155:97` | `eip155:97` / `97` | `97` | `https://data-seed-prebsc-1-s1.binance.org:8545` | +| Base | `base` | `eip155:8453` / `8453` | `8453` | `https://mainnet.base.org` | +| Base | `base:sepolia` | `eip155:84532` / `84532` | `84532` | `https://sepolia.base.org` | +| TRON | `mainnet` | — / `728126428` | `728126428` | `https://api.trongrid.io` | +| TRON | `nile` | — / `3448148188` | `3448148188` | `https://nile.trongrid.io` | +| TRON | `shasta` | — / `2494104990` | `2494104990` | `https://api.shasta.trongrid.io` | + +TRON 请使用裸名称(`mainnet` / `nile` / `shasta`),示例中也是这么写的。两个 SDK 同时接受带 `tron:` 前缀的别名(如 `tron:nile`,单独的 `tron` 会解析为 Nile),内部会去掉该前缀;这是 SDK 自身的别名,与 x402 使用的 CAIP-2 标识不是一回事。EIP-712 chainId 一列,是 SDK 在 TRON 上签署 Agent 钱包变更时写入类型化数据域的值。自 1.1.2 起,两个 SDK 也把该值用作 TRON 的 chainId,因此 Nile 上的 Agent ID 形如 `3448148188:`(旧版本生成的是 `1:`,已保存的 ID 不会被自动改写)。两个 SDK 的 `loadAgent()` 与信誉相关调用会拒绝链前缀与当前所配网络不一致的 ID;`getAgent()`、`searchFeedback()` 等索引器 / subgraph 查询不做这项检查。 -TRON 请使用裸名称(`mainnet` / `nile` / `shasta`),示例中也是这么写的。两个 SDK 同时接受带 `tron:` 前缀的别名(如 `tron:nile`,单独的 `tron` 会解析为 Nile),内部会去掉该前缀;这是 SDK 自身的别名,与 x402 使用的 CAIP-2 标识不是一回事。EIP-712 chainId 一列,是 SDK 在 TRON 上签署 Agent 钱包变更时写入类型化数据域的值。 +Base 使用官方 ERC-8004 注册表部署。TypeScript 接受 `base` / `base:mainnet` / `eip155:8453` 以及 `base:sepolia` / `eip155:84532`。Python 只接受 `eip155:8453` / `eip155:84532`,也没有 Base 的验证注册表;单写 `network="base"` 不会报错,而是回落到 chainId 97(BSC 测试网)。 --- @@ -68,10 +74,12 @@ TRON 请使用裸名称(`mainnet` / `nile` / `shasta`),示例中也是这 | 本地创建 Agent | ✅ | ✅ | `sdk.createAgent(...)` | | 修改名称 / 描述 / 图片 | ✅ | ✅ | `agent.updateInfo({...})`——只改本地注册文件,需再调 `updateRegistration()` 发布 | | 以 HTTP(S) URI 注册 | ✅ | ✅ | `agent.register(agentURI)` | -| 通过 IPFS 上传注册 | ✅ | ✅ | `agent.registerIPFS()` | +| 不带 URI 注册,或附带链上元数据条目注册 | ✅ | ✅ | TS 显式传参:`agent.register()` / `agent.register(agentURI, metadata)`。Python 的 `register(agentURI)` 只接受 URI,但会把 `setMetadata()` 暂存的元数据(以及作为 `agentName` 的 ENS 名称)随铸造一起写入;`registerIPFS()` 会先不带 URI 铸造 | +| 通过 IPFS 上传注册 | ✅ | ✅ | `agent.registerIPFS()`——新 Agent 会先铸造,再带着铸造出的 Agent ID 上传文件并设置 URI(两笔交易) | | 更新链上 URI | ✅ | ✅ | `agent.updateRegistration(...)` | | 在本地设置 agent URI | ✅ | ✅ | `agent.setAgentUri(uri)`——仅本地,不发交易 | | 按 ID 从链上加载 Agent | ✅ | ✅ | `sdk.loadAgent(agentId)`——无需 subgraph | +| 读取链上 agent URI | ✅ | ❌ | `sdk.getAgentURI(agentId)` | | MCP / A2A / ENS 端点 | ✅ | ✅ | `setMCP()`、`setA2A()`、`setENS()` | | 移除端点 | ✅ | ✅ | `removeEndpoint()`、`removeEndpoints()` | | OASF 技能与领域 | ✅ | ✅ | `addSkill()`、`addDomain()`、`removeSkill()`、`removeDomain()`——但存储位置不同:Python 在 `services` 中构建 `OASF` 条目(其 `version` 为 `0.8`),TypeScript 则把 slug 推入扁平的 `tags` 数组 | @@ -79,7 +87,8 @@ TRON 请使用裸名称(`mainnet` / `nile` / `shasta`),示例中也是这 | 信任模型 | ✅ | ✅ | `setTrust(...)`——TypeScript 传对象,Python 传关键字参数;两者都支持 `reputation`、`cryptoEconomic`、`teeAttestation` | | 整体替换信任模型列表 | ✅ | ✅ | TypeScript 的 `agent.setTrustModels([...])` 会归一化名称;Python 的 `agent.trustModels([...])` 按原样赋值 | | 任意元数据 | ✅ | ✅ | `setMetadata()` | -| 读取 / 删除单个元数据键 | ❌ | ✅ | `agent.getMetadata()`、`agent.delMetadata()` | +| 读取本地元数据 / 删除单个键 | ❌ | ✅ | `agent.getMetadata()` 返回全部本地元数据的副本;`agent.delMetadata(key)` 删除单个键——针对本地注册文件 | +| 读取单个链上元数据值 | ✅ | ❌ | `sdk.getMetadata(agentId, key)`——以十六进制返回原始字节 | | 将元数据变更推送上链 | ✅ | ❌ | `agent.updateOnChainMetadata()` | | 激活标志 | ✅ | ✅ | `setActive()`;Python 另有 `activate()` / `deactivate()` | | x402 支持标志 | ✅ | ✅ | `setX402Support()` | @@ -118,7 +127,9 @@ TRON 请使用裸名称(`mainnet` / `nile` / `shasta`),示例中也是这 | 聚合摘要 | ✅ | ✅ | `sdk.getReputationSummary(...)` | | 撤销自己的反馈 | ✅ | ✅ | `sdk.revokeFeedback(...)` | | 对反馈追加回应 | ✅ | ✅ | `sdk.appendResponse(...)` | -| 检索反馈 | ✅ | ✅ | `sdk.searchFeedback(...)`——依赖 subgraph | +| 检索反馈 | ✅ | ✅ | `sdk.searchFeedback(...)`——依赖 subgraph;没有 subgraph 时,TypeScript 返回 `[]`,Python 会从链上读取单个 Agent 的反馈 | +| 从链上读取全部反馈 | ✅ | ❌ | `sdk.readAllFeedback(...)` | +| 读取客户端列表、最新索引、回应数 | ✅ | ❌ | `sdk.getClients()`、`sdk.getLastIndex()`、`sdk.getResponseCount()` | | 构建反馈文件 | ❌ | ✅ | `sdk.prepareFeedbackFile(...)` | :::note 链上禁止自评 @@ -134,6 +145,8 @@ TRON 请使用裸名称(`mainnet` / `nile` / `shasta`),示例中也是这 | 发起验证请求 | ✅ | ❌ | `sdk.validationRequest(...)` | | 提交验证者响应 | ✅ | ❌ | `sdk.validationResponse(...)` | | 读取验证状态 | ✅ | ❌ | `sdk.getValidationStatus(...)` | +| 验证聚合摘要 | ✅ | ❌ | `sdk.getValidationSummary(...)` | +| 列出某 Agent / 某验证者的请求哈希 | ✅ | ❌ | `sdk.getAgentValidations(...)`、`sdk.getValidatorRequests(...)` | :::caution 验证功能目前仅 TypeScript 可用 Python 包会解析验证注册表合约、也内置了它的 ABI,但**没有**暴露任何验证方法。如果需要在 Python 中使用验证注册表,请改用 TypeScript SDK,或直接调用合约。 @@ -150,11 +163,13 @@ Python 包会解析验证注册表合约、也内置了它的 ABI,但**没有* | 转让 Agent | ✅ | ✅ | `agent.transfer(...)`;Python 另有 `sdk.transferAgent(...)` | | 转让时将新所有者设为操作员 | ✅ | ❌ | TS 为 `transfer(to, approveOperator)`;Python 的 `Agent.transfer` 只接受地址 | | 添加 / 移除操作员 | ✅ | ✅ | `agent.addOperator()`、`agent.removeOperator()` | -| 读取所有者 | ❌ | ✅ | `sdk.getAgentOwner()` | +| 仅针对该 Agent 授权某地址 | ✅ | ❌ | `agent.approve(operator)` | +| 读取授权情况 | ✅ | ❌ | `sdk.getApproved(agentId)`、`sdk.isApprovedForAll(owner, operator)` | +| 读取所有者 | ✅ | ✅ | `sdk.getAgentOwner()` | | 所有权 / 转让前置检查 | ❌ | ✅ | `sdk.isAgentOwner()`、`sdk.canTransferAgent()` | :::note 转让会清空 Agent 钱包 -身份注册表在每次转让时都会清空 `agentWallet`,因此转让后 `getAgentWallet()` 返回零地址。新所有者必须重新调用 `setWallet()`。 +身份注册表在每次转让时都会清空 `agentWallet`,转让后链上读到的是零地址——SDK 会把它报告为 `undefined`(TypeScript `sdk.getAgentWallet()`)/ `None`(Python `agent.getWallet()`)。新所有者必须重新调用 `setWallet()`。 ::: --- @@ -164,13 +179,13 @@ Python 包会解析验证注册表合约、也内置了它的 ABI,但**没有* | 能力 | TypeScript | Python | 是否需要 subgraph | |---|:--:|:--:|:--:| | `sdk.loadAgent(agentId)` | ✅ | ✅ | 否——直接读链 | -| `sdk.getAgent(agentId)` | ✅ | ✅ | 是 | +| `sdk.getAgent(agentId)` | ✅ | ✅ | 是(Python 没有 subgraph 时回落到本地索引缓存,但 1.2.1 中 `refreshIndex` 无法填充它——见下文) | | `sdk.searchAgents(filters)` | ✅ | ✅ | 是 | -| `sdk.searchFeedback(filters)` | ✅ | ✅ | 是 | +| `sdk.searchFeedback(filters)` | ✅ | ✅ | 是;Python 指定单个 `agentId` 时可回退到链上读取 | | `sdk.getSubgraphClient(chainId?)`——Python 为 `sdk.get_subgraph_client()` | ✅ | ✅ | ——未配置时不返回 | -| `sdk.refreshIndex()`、`sdk.refreshAgentIndex()` | ❌ | ✅ | 是——与 `getAgent` 共用索引器 | +| `sdk.refreshIndex()`、`sdk.refreshAgentIndex()` | ❌ | ⚠️ | 1.2.1 中不可用:SDK 构造索引器时没有传入身份注册表,`refreshAgentIndex()` 会抛 `Failed to get agent data: Identity registry not available`,`refreshIndex()` 返回 `[]` | -若未配置 subgraph,依赖索引的调用不可用——此时 `loadAgent()` 仍是获取 Agent 的途径。 +没有 subgraph 时(TypeScript 除非传了 `subgraphUrl` 或该链的 `subgraphOverrides`;Python 在 BSC 上除非传了 `subgraphOverrides`,在 TRON 上则总是如此),`searchAgents()` 不可用;Python 的 `getAgent()` 会抛出 `Agent … not found in index`,TypeScript 的 `getAgent()` 返回 `undefined`,TypeScript 的 `searchFeedback()` 返回 `[]`,Python 的 `searchFeedback()` 只能针对单个 `agentId` 使用。此时 `loadAgent()` 仍是获取 Agent 的途径。在 TRON 上,Python 的 `getAgent(":")` 仍会查询 `subgraphOverrides` 或环境变量 `SUBGRAPH_URL_` 给出的 subgraph 地址。 --- @@ -186,9 +201,9 @@ Python 包会解析验证注册表合约、也内置了它的 ABI,但**没有* | Filecoin | `ipfs="filecoinPin"` | `filecoinPrivateKey` | | 自建 IPFS 节点 | `ipfs="node"` | `ipfsNodeUrl` | -**TypeScript** 不内置任何提供方。`SDKConfig` 只暴露一个需要你自行实现的 `ipfsUploader?: (json: string) => Promise` 回调;未提供时 `registerIPFS()` 会抛出 `No ipfsUploader configured`。 +**TypeScript** 不内置任何提供方。`SDKConfig` 只暴露一个需要你自行实现的 `ipfsUploader?: (json: string) => Promise` 回调;未提供时 `registerIPFS()` 会抛出 `No ipfsUploader configured`。对新 Agent 来说,这个错误要到 `waitConfirmed()` 才出现,此时注册交易已经用空 URI 铸造了该 Agent,所以请先配置好 uploader。 -两个语言中 IPFS 都是可选的。只有 `registerIPFS()` 以及读取 `ipfs://` 形式的 agent URI 才需要它;HTTP(S) 注册无需配置。 +两个语言中 IPFS 都是可选的。`registerIPFS()` 需要它;Python 读取 `ipfs://` 形式的 agent URI、以及 `giveFeedback(feedbackFile=...)` 也需要它(未配置 IPFS 客户端时会报错)。TypeScript 无需任何配置,通过公共网关 `https://ipfs.io/ipfs/` 读取 `ipfs://` URI。HTTP(S) 注册无需 IPFS。 --- @@ -197,9 +212,9 @@ Python 包会解析验证注册表合约、也内置了它的 ABI,但**没有* 两套实现有四处差异值得在选型时纳入考虑: 1. **验证功能仅 TypeScript 有。** 见上文——这是最大的功能缺口。 -2. **默认值与配置形态不同。** `setA2A()` 的默认版本 Python 为 `0.30`、TypeScript 为 `0.3.0`;`subgraphUrl` 与 `ipfsUploader` 是 TypeScript 独有的构造参数,而 `registryOverrides`、`indexingStore` 及内置 IPFS 提供方则是 Python 独有。 +2. **默认值与配置形态不同。** `setA2A()` 的默认版本 Python 为 `0.30`、TypeScript 为 `0.3.0`;`subgraphUrl` 与 `ipfsUploader` 是 TypeScript 独有的构造参数,而 `registryOverrides`、`indexingStore`、`embeddings` 及内置 IPFS 提供方则是 Python 独有。`feeLimit`(TRON,单位 SUN)的默认值 TypeScript 为 120,000,000,Python 为 10,000,000。 3. **读取 Agent 字段的方式不同。** Python 在 `Agent` 上暴露了二十一个只读属性(`name`、`description`、`endpoints`、`mcpTools`、`owners`、`operators`、`updatedAt` 等)。TypeScript 只暴露 `agent.agentId`,其余一律通过 `agent.toJSON()` 读取。 -4. **辅助方法各有侧重。** Python 多出所有权前置检查(`isAgentOwner`、`canTransferAgent`)、元数据存取(`getMetadata`、`delMetadata`)、`activate()` / `deactivate()` 以及 `saveToFile()`。TypeScript 多出 `updateOnChainMetadata()`、`uploadRegistrationFile()` 与 `submitRegister()`。 +4. **辅助方法各有侧重。** TypeScript 另有 `sdk.getTypedDataChainId()`;Python 另有 `sdk.chain_id()`、`sdk.registries()`、`sdk.set_chain()`、`sdk.isReadOnly` 以及 `agent.registrationFile()` / `agent.toJson()`。Python 多出所有权前置检查(`isAgentOwner`、`canTransferAgent`)、元数据存取(`getMetadata`、`delMetadata`)、`activate()` / `deactivate()` 以及 `saveToFile()`。TypeScript 多出 `updateOnChainMetadata()`、`uploadRegistrationFile()`、`submitRegister()`、`agent.approve()`,以及上文列出的注册表读取调用(`getAgentURI`、`sdk.getMetadata`、`getApproved`、`isApprovedForAll`、`readAllFeedback`、`getClients`、`getLastIndex`、`getResponseCount` 和各项验证读取)。 :::note Python 中有两个同名定义重复 在 Python 的 `Agent` 类里,`transfer` 与 `trustModels` 各自被定义了两次,最终生效的是后一个。生效的 `transfer` 是 `transfer(newOwnerAddress)`——此前那个带 `approve_operator` 的四参数版本不可达;而只读的 `trustModels` 属性被同名 setter 覆盖,因此 `agent.trustModels` 返回的是绑定方法而非列表。要读取信任模型,请改用 `agent.registrationFile()`。 @@ -211,3 +226,4 @@ Python 包会解析验证注册表合约、也内置了它的 ABI,但**没有* - ✅ = 已实现 - ❌ = 该语言未实现 +- ⚠️ = 存在但在当前版本中不可用 From c1715b55691e1429365f46a62183b26cc04d53b4 Mon Sep 17 00:00:00 2001 From: jizhen181-dot Date: Wed, 28 Oct 2026 17:02:02 +0800 Subject: [PATCH 04/13] docs(openclaw, mcp): match installer and TRON MCP Server code - OpenClaw: installer prompts and output (skills 1.4.6 copy mode), first-install-only configuration, Clean mode scope, Node.js error text. - Recharge MCP (recharge.bankofai.io/mcp) is offline; point to wallet-cli bai recharge. - TRON MCP: npm 1.1.7 vs v1.1.8, endpoints and rate limits, Docker --readonly, 405 on GET/DELETE /mcp, agent-wallet 2.x reset. - add-mcp -y installs project-level config; walkthrough includes the scope prompt. Co-Authored-By: Claude Opus 5.5 (1M context) --- changelog/mcp-server.md | 34 ++++ changelog/openclaw-extension.md | 33 ++++ .../MCP/BSCMCPServer/Features.md | 2 + .../MCP/BSCMCPServer/Installation.md | 7 +- .../McpServer-Skills/MCP/TRONMCPServer/FAQ.md | 69 +++++--- .../MCP/TRONMCPServer/Intro.md | 2 +- .../LocalPrivatizedDeployment.md | 52 +++--- .../MCP/TRONMCPServer/OfficialServerAccess.md | 16 +- .../MCP/TRONMCPServer/QuickStart.md | 10 +- .../MCP/TRONMCPServer/ToolList.md | 8 +- docs/Openclaw-extension/FAQ.md | 12 +- docs/Openclaw-extension/Intro.md | 2 +- docs/Openclaw-extension/QuickStart.md | 156 ++++++++++++------ .../current/mcp-server.md | 34 ++++ .../current/openclaw-extension.md | 33 ++++ .../MCP/BSCMCPServer/Features.md | 2 + .../MCP/BSCMCPServer/Installation.md | 7 +- .../McpServer-Skills/MCP/TRONMCPServer/FAQ.md | 69 +++++--- .../MCP/TRONMCPServer/Intro.md | 2 +- .../LocalPrivatizedDeployment.md | 52 +++--- .../MCP/TRONMCPServer/OfficialServerAccess.md | 16 +- .../MCP/TRONMCPServer/QuickStart.md | 10 +- .../MCP/TRONMCPServer/ToolList.md | 8 +- .../current/Openclaw-extension/FAQ.md | 12 +- .../current/Openclaw-extension/Intro.md | 2 +- .../current/Openclaw-extension/QuickStart.md | 156 ++++++++++++------ 26 files changed, 586 insertions(+), 220 deletions(-) diff --git a/changelog/mcp-server.md b/changelog/mcp-server.md index c561d71b..d5661a92 100644 --- a/changelog/mcp-server.md +++ b/changelog/mcp-server.md @@ -7,6 +7,40 @@ description: 'Release notes for MCP Server.' Release notes for MCP Server. +
+
Oct 27, 2026
+
+ +### Package contents, Docker mode and HTTP details + +
DocsFix
+ +- The npm package ships `build/`, `bin/`, `package.json`, `README.md` and `LICENSE`; the Docker image always runs read-only (`--readonly` is hard-coded); `GET` / `DELETE /mcp` return 405 and SSE is not supported; `GET /` returns server information; `tron` / `trx` / `testnet` are accepted network aliases. + +👉 [Local Deployment](/McpServer-Skills/MCP/TRONMCPServer/LocalPrivatizedDeployment/) · [Tool List](/McpServer-Skills/MCP/TRONMCPServer/ToolList/) + +
+
+ +
+
Oct 23, 2026
+
+ +### TRON MCP Server docs matched to the code + +
DocsFix
+ +- **RPC without an API key** — on `main` (tag `v1.1.8`), Mainnet requests without `TRONGRID_API_KEY` go to `https://hptg.bankofai.io`; with a key they go to `api.trongrid.io`. Nile and Shasta always use the TronGrid testnet nodes. npm `1.1.7` still uses `api.trongrid.io` without a key. +- **Tools and prompts** — `write_contract` takes no `feeLimit` (only `deploy_contract` does); `tron://networks` returns `{"supportedNetworks":[...]}`; read-only mode registers 4 prompts, not 6. +- **Wallet errors** — the FAQ now quotes the real agent-wallet 2.x error texts (`resolve_wallet could not find a wallet source in config or env`, `Password required for local_secure wallets`, `No active wallet set.`, `MAC mismatch — wrong password or corrupted file`). agent-wallet 2.3.x and 2.4.0 also accept the aliases `TRON_PRIVATE_KEY` and `TRON_MNEMONIC`, but read these env vars only when no password resolves and the wallet directory holds no wallets; otherwise they are silently ignored. On that path, with both a private key and a mnemonic set, agent-wallet 2.3.x gives `Wallet not configured.` and 2.4.0 gives `Provide only one of AGENT_WALLET_PRIVATE_KEY or AGENT_WALLET_MNEMONIC`. +- **Node.js** — a source checkout of `v1.1.8` requires 22.23.4+ (22.x) or 24.22.1+ (24.x); npm `1.1.7`, which `npx` runs, declares `>=20`. The pages recommend the October 2026 security releases either way. The cloud-service Quick Start replaced its hard requirement "Node.js v20.0.0 or higher" with "Node.js, needed to run `npx`", recommending 22.23.4+ or 24.22.1+. +- **Agent Wallet install pinned to 2.x** — the server depends on `@bankofai/agent-wallet ^2.3.0`, but an unpinned `npm install -g @bankofai/agent-wallet` now installs 3.0.0, which has no `local_secure` wallets, master password, or `--save-runtime-secrets`. The pages now use `npm install -g @bankofai/agent-wallet@2` and note that the Agent-Wallet docs describe 3.x. + +👉 [Quick Start](/McpServer-Skills/MCP/TRONMCPServer/QuickStart/) · [FAQ](/McpServer-Skills/MCP/TRONMCPServer/FAQ/) · [Local Private Deployment](/McpServer-Skills/MCP/TRONMCPServer/LocalPrivatizedDeployment/) + +
+
+
Sep 9, 2026
diff --git a/changelog/openclaw-extension.md b/changelog/openclaw-extension.md index bacfb5e7..4283ddce 100644 --- a/changelog/openclaw-extension.md +++ b/changelog/openclaw-extension.md @@ -7,6 +7,39 @@ description: 'Release notes for the Openclaw Extension.' Release notes for the Openclaw Extension. +
+
Oct 27, 2026
+
+ +### Installer details corrected + +
DocsFix
+ +- The skill configuration phase (API key prompt, `Next steps`) runs only for skills that were not already in the skill list before the run (on the default global install it covers `~/.openclaw/skills/`, `~/.agents/skills/` and other agents' skill folders), so re-installs print `No new skills were installed.` and skip it; the Quick Start now says so and points to the manual API key steps. The `Proceed with installation?` prompt and the `bankofai-recharge` remote URL are documented. +- The Node.js error text matches what the installer prints (on Windows without the `Error: ` prefix); the manual `bankofai-config.json` steps set `chmod 600` like the installer does; Windows is described as almost identical with the differences in the FAQ; deleting `~/.openclaw/skills/` removes skills only — MCP entries, the API key file, global npm packages and `~/.agent-wallet` stay; Clean mode clears the MCP entries, skills and config files and re-initialises agent-wallet, but never uninstalls the npm packages. + +👉 [Quick Start](/Openclaw-extension/QuickStart/) · [FAQ](/Openclaw-extension/FAQ/) + +
+
+ +
+
Oct 23, 2026
+
+ +### Docs matched to the current installer + +
DocsFix
+ +- **Correction to the Sep 9 entry** — those installer changes never shipped. The installer on `main` still pins Skills `v1.5.15` (14 skills, no `wallet-cli`), `@bankofai/agent-wallet` 2.3.1 and `@bankofai/mcp-server-tron` 1.1.7, and writes `base_url: https://chat.ainft.com`. The Quick Start and FAQ now describe that installer, and a note at the top explains that its wallet steps follow agent-wallet 2.x. +- **What else the docs now say** — selecting `x402-payment` also runs `npm install --global @bankofai/x402-cli@1.0.1`; the TronScan API key is optional (without one the skill uses `ts.bankofai.io`); a project-level install goes to `/skills/`; there is no TronGrid prompt; with an existing wallet, agent-wallet 2.3.1 first asks whether to add one or exit; and on Windows the installer exits if `~/.openclaw` is missing. +- **Node.js** — both installers check the full version against `^22.23.4 || ^24.22.1 || >=26.12.1` before installing anything. + +👉 [Quick Start](/Openclaw-extension/QuickStart/) · [FAQ](/Openclaw-extension/FAQ/) + +
+
+
Sep 9, 2026
diff --git a/docs/McpServer-Skills/MCP/BSCMCPServer/Features.md b/docs/McpServer-Skills/MCP/BSCMCPServer/Features.md index de103d95..ed1fcb1e 100644 --- a/docs/McpServer-Skills/MCP/BSCMCPServer/Features.md +++ b/docs/McpServer-Skills/MCP/BSCMCPServer/Features.md @@ -19,3 +19,5 @@ The project is divided into the following core functional modules: **Common Components**: Shared utilities and types **Greenfield**: Support for file management operations on the Greenfield network, including file uploads, downloads, and the management of files and storage buckets + +**Agents (ERC-8004)**: Register and resolve on-chain AI agent identities on the ERC-8004 Identity Registry (`register_erc8004_agent`, `set_erc8004_agent_uri`, `get_erc8004_agent`, `get_erc8004_agent_wallet`) diff --git a/docs/McpServer-Skills/MCP/BSCMCPServer/Installation.md b/docs/McpServer-Skills/MCP/BSCMCPServer/Installation.md index 15e354c8..10342ac4 100644 --- a/docs/McpServer-Skills/MCP/BSCMCPServer/Installation.md +++ b/docs/McpServer-Skills/MCP/BSCMCPServer/Installation.md @@ -3,7 +3,7 @@ ### Prerequisites * **bun** v1.2.10 or higher -* **Node.js** v18 or higher (this page previously stated v17; the rest of the BANK OF AI toolchain requires 18+, and the TRON MCP server requires 20+) +* **Node.js** v17 or higher (the upstream README's requirement; `package.json` declares no `engines`, and the project's release workflow uses Node.js 20) ### Quick Start @@ -22,6 +22,7 @@ * `PRIVATE_KEY`: Your wallet private key (required for executing transactions) * `LOG_LEVEL`: Set the log level (`DEBUG`, `INFO`, `WARN`, `ERROR`) * `PORT`: Server port number (default: `3001` — the TRON MCP server also defaults to 3001, so change one of them if you run both locally) + * `BNBCHAIN_MCP_SKIP_TRANSFER_CONFIRMATION` (optional, default `false`): by default, transfer and payment tools only return a preview and a `confirmToken` (valid for 5 minutes) without sending anything; call `confirm_transfer` with that token to execute. Set it to `true` to execute immediately 4. **Install dependencies and start the development server:** ```bash @@ -49,9 +50,11 @@ Use the following template to configure the local server in your MCP client: } ``` +> The template follows the upstream README. With a `url` entry the client connects to the already running server, so the `env` block is not passed to it: the server reads `PRIVATE_KEY` from its own `.env`. + ### Test with the Web UI -Use @modelcontextprotocol/inspector for testing. Run the following command to launch the test UI: +Use @modelcontextprotocol/inspector for testing. Run the following command to launch the test UI (the script runs the latest inspector through `npx`, which currently requires Node.js 22.19 or later): ```bash bun run test diff --git a/docs/McpServer-Skills/MCP/TRONMCPServer/FAQ.md b/docs/McpServer-Skills/MCP/TRONMCPServer/FAQ.md index 542090af..dee972ba 100644 --- a/docs/McpServer-Skills/MCP/TRONMCPServer/FAQ.md +++ b/docs/McpServer-Skills/MCP/TRONMCPServer/FAQ.md @@ -12,11 +12,15 @@ Connection issues usually occur during the initial configuration phase. If your This is the most common issue. Troubleshoot in the following order: -1. **Check Node.js version**. TRON MCP Server requires v20.0.0 or higher: +1. **Check Node.js version**. What is declared depends on how you run the server: + - **`npx -y @bankofai/mcp-server-tron`** runs the npm package `1.1.7`, which declares Node.js `>=20`. + - **A source checkout** of `main` (tag `v1.1.8`) requires 22.23.4+ (22.x) or 24.22.1+ (24.x). Its `package.json` still says `1.1.7`, so the server reports version `1.1.7` there too. + + Either way, we recommend the October 2026 security releases, 22.23.4+ or 24.22.1+: ```bash - node --version # Should output v20.x.x or higher + node --version # recommended: v22.23.4+ or v24.22.1+ ``` - If your version is too low, upgrade Node.js first. + If your version is below what your route declares, upgrade Node.js first. 2. **Check that npx is available**. Run `npx --version` in your terminal. If the command is not found, your Node.js installation is incomplete — reinstall it. @@ -47,15 +51,22 @@ When using HTTP mode (`npx -y @bankofai/mcp-server-tron --http`, or `npm run sta 3. **Firewall blocking**. If you're accessing the local HTTP service from another machine, check whether the firewall allows inbound connections on that port. -### Write tools appear but return "Wallet not configured" error +### Write tools appear but return a wallet error {#write-tools-wallet-error} + +As of v1.1.7, write tools (transfers, staking, etc.) are always visible in the AI's tool list, but wallet availability is checked at execution time. If you call a write tool without a usable wallet, the tool returns an error such as `Error transferring TRX: `, where `` comes from Agent Wallet — see [Wallet error messages](#wallet-error-messages) below for what each one means. -As of v1.1.7, write tools (transfers, staking, etc.) are always visible in the AI's tool list, but wallet availability is checked at execution time. If you call a write tool without a configured wallet, it will return an error prompting you to set up a wallet. +To enable write operations, set up Agent Wallet **2.x**, the version this server depends on: -To enable write operations, configure [Agent Wallet](../../../Agent-Wallet/Intro.md): +```bash +npm install -g @bankofai/agent-wallet@2 +agent-wallet start local_secure --save-runtime-secrets +``` -- Set `AGENT_WALLET_PASSWORD` environment variable with your master password +- `--save-runtime-secrets` writes your master password to `~/.agent-wallet/runtime_secrets.json`; alternatively, set the `AGENT_WALLET_PASSWORD` environment variable to it - Optionally set `AGENT_WALLET_DIR` if using a custom wallet directory +The [Agent-Wallet documentation](../../../Agent-Wallet/Intro.md) describes Agent Wallet 3.x, which this server does not use yet — use the 2.x commands above. + After configuring, restart your AI client. For detailed instructions, see [Local Private Deployment](./LocalPrivatizedDeployment.md). :::info @@ -66,22 +77,36 @@ If you're connected via the official cloud service or using `--readonly` mode, w ## Authentication & Key Issues -### "Wallet not configured" error +### Wallet error messages {#wallet-error-messages} + +TRON MCP Server uses [Agent Wallet](../../../Agent-Wallet/Intro.md) for all wallet management. When a write tool (or `get_wallet_address` / `sign_message`) cannot get a wallet, the error text tells you which case you hit: -This means no wallet has been set up for signing transactions. TRON MCP Server uses [Agent Wallet](../../../Agent-Wallet/Intro.md) for all wallet management. To resolve: +| Error text | Meaning | +| :--- | :--- | +| `resolve_wallet could not find a wallet source in config or env` | No wallet at all: no password resolves, the wallet directory holds no wallets, and none of `AGENT_WALLET_PRIVATE_KEY`, `TRON_PRIVATE_KEY`, `AGENT_WALLET_MNEMONIC` or `TRON_MNEMONIC` is set. | +| `Password required for local_secure wallets` | Wallets exist in the wallet directory, but no password resolved — neither `runtime_secrets.json` nor `AGENT_WALLET_PASSWORD`. | +| `No active wallet set.` | A password resolved, but the wallet directory holds no wallets. In this case the private-key and mnemonic variables are ignored — create or import a wallet with Agent Wallet, or remove the password so the env-var path is used. | +| `MAC mismatch — wrong password or corrupted file` | A password was found but does not match the keystore (see the next section). | +| `Wallet not configured.` | Agent Wallet could not even load its configuration — for example a malformed `runtime_secrets.json` or `wallets_config.json`. With agent-wallet 2.3.x (what a source checkout's `package-lock.json` installs), setting both a private key and a mnemonic also ends here, when the env-var path is reached (see below the table). | +| `Provide only one of AGENT_WALLET_PRIVATE_KEY or AGENT_WALLET_MNEMONIC` | A private key (`AGENT_WALLET_PRIVATE_KEY` or `TRON_PRIVATE_KEY`) and a mnemonic (`AGENT_WALLET_MNEMONIC` or `TRON_MNEMONIC`) are both set and the env-var path is reached, with agent-wallet 2.4.0 — what `npx -y @bankofai/mcp-server-tron` (npm `1.1.7`, dependency `^2.3.0`) installs today. The server passes the text through, e.g. `Error transferring TRX: Provide only one of …`, or `Error: Provide only one of …` from `get_wallet_address`. Unset one of the two. | -1. **Install and initialize Agent Wallet** following the [Agent-Wallet documentation](../../../Agent-Wallet/Intro.md). -2. **Set the environment variable**: +Both agent-wallet versions read the private key from `AGENT_WALLET_PRIVATE_KEY` or its alias `TRON_PRIVATE_KEY`, and the mnemonic from `AGENT_WALLET_MNEMONIC` or its alias `TRON_MNEMONIC`. They read these env vars only on the env-var path — when no password resolves **and** the wallet directory holds no wallets. Otherwise the variables are silently ignored, and neither of the both-set errors above can occur. + +To resolve the first two: + +1. **No wallet yet: install and initialize Agent Wallet 2.x** with `npm install -g @bankofai/agent-wallet@2`, then `agent-wallet start local_secure --save-runtime-secrets`, which also saves the master password to `runtime_secrets.json`. (The [Agent-Wallet documentation](../../../Agent-Wallet/Intro.md) describes 3.x, which this server does not use yet.) +2. **Wallets already exist: make the password available** — export it: ```bash export AGENT_WALLET_PASSWORD='' ``` -3. **Restart your AI client** for the changes to take effect. + or save it to `runtime_secrets.json` as described in [Local Private Deployment](./LocalPrivatizedDeployment.md) (Path 1). Re-running `agent-wallet start` does not help: with wallets present it only offers `add`, which creates a new wallet and makes it the active one, or `exit`, which saves nothing. +3. **Restart your AI client** for the changes to take effect. The server resolves the wallet source once and caches it, so a restart is required after changing wallet settings. -### "Agent wallet password incorrect" error +### "MAC mismatch — wrong password or corrupted file" error -`AGENT_WALLET_PASSWORD` must exactly match the master password generated when you ran `agent-wallet start`. Verify that the wallet directory exists (`ls ~/.agent-wallet/`) and that `AGENT_WALLET_DIR` points to the correct path if you used a custom directory. +The password the server resolved (from `runtime_secrets.json` or `AGENT_WALLET_PASSWORD`) must exactly match the master password you set when you ran `agent-wallet start`. Verify that the wallet directory exists (`ls ~/.agent-wallet/`) and that `AGENT_WALLET_DIR` points to the correct path if you used a custom directory. -If the password is lost, you'll need to re-initialize. **Warning: this wipes all wallets and keys — ensure funds are moved or mnemonics backed up before proceeding.** Run `agent-wallet reset` to wipe and start over — see [CLI Reference → Reset](../../../Agent-Wallet/Developer/CLI-Reference.md#agent-wallet-reset-reset-all-data) and [Agent-Wallet FAQ](../../../Agent-Wallet/FAQ.md) for details. +If the password is lost, you'll need to re-initialize. **Warning: this wipes all wallets and keys — ensure funds are moved or mnemonics backed up before proceeding.** Run `agent-wallet reset` to wipe and start over. In agent-wallet 2.x (what this server uses), `reset` deletes every file in `~/.agent-wallet` — `master.json`, `wallets_config.json`, `runtime_secrets.json` and the `secret_*.json` keystores. The Agent-Wallet pages describe 3.x, whose `reset` removes only `wallets_config.json`. ### TronGrid API Key not working @@ -115,7 +140,7 @@ Interacting with smart contracts (including TRC20 token transfers) requires Ener **How to resolve:** - Estimate cost first: "Estimate how much Energy is needed to call this contract's transfer function" - Stake TRX for Energy: "Stake 500 TRX for Energy" -- If using `write_contract`, have the AI increase the `feeLimit` parameter +- `write_contract` has no fee-limit parameter, so make sure the wallet holds enough TRX to burn for the Energy shortfall. Only `deploy_contract` accepts a `feeLimit` (in Sun, default 1,000,000,000 = 1000 TRX), which you can ask the AI to raise for a large deployment ### "Account not found" or "Account not activated" @@ -158,7 +183,7 @@ If this keeps happening, remind the AI: "Please only use tools provided by TRON Several common causes and solutions: -- **No TronGrid API Key**: Public RPC has rate limits; adding a free API Key can significantly improve performance +- **No TronGrid API Key**: Without `TRONGRID_API_KEY`, Mainnet requests go to the BANK OF AI fallback endpoint `https://hptg.bankofai.io` on a source checkout from `v1.1.8`, and to `https://api.trongrid.io` without a key on npm `1.1.7` (what `npx` runs). Setting a free API Key sends them to `https://api.trongrid.io` under your own quota in both versions - **Complex multi-tool workflows**: Some operations (like full wallet analysis) require multiple sequential calls — waiting is normal - **Use testnet for development**: Nile and Shasta testnets are usually faster - **Be more specific in prompts**: Reduce the AI's exploratory calls — tell it directly which tool to use and which network to query @@ -183,7 +208,13 @@ Yes. Define multiple MCP Server entries in your MCP client configuration — for ### How do I update to the latest version? -If you're using the `npx` method, you always get the latest published version. To force clearing the cache: +If you're using the `npx` method, `npx -y @bankofai/mcp-server-tron` does not always fetch the latest release: it can run a copy that is already installed — globally, in the current project, or, on older npm versions, in the npx cache. To always get the latest published version, ask for it explicitly, for example in your MCP client configuration: + +```bash +npx -y @bankofai/mcp-server-tron@latest +``` + +To clear the npx cache instead, delete `~/.npm/_npx` (and, if needed, run `npm cache clean --force`). The third-party `clear-npx-cache` package does the same: ```bash npx clear-npx-cache @@ -200,5 +231,5 @@ npm run build ### What MCP protocol version is supported? -TRON MCP Server supports MCP protocol version **2025-11-25**, using `@modelcontextprotocol/sdk` 1.22.0 or higher. +The protocol version is negotiated by `@modelcontextprotocol/sdk`, which the server depends on as `^1.22.0`; a source checkout's `package-lock.json` pins 1.27.1. MCP protocol version **2025-11-25** requires SDK 1.24.1 or later — SDK 1.22.0–1.24.0 top out at 2025-06-18. Older protocol versions requested by the client are also accepted. diff --git a/docs/McpServer-Skills/MCP/TRONMCPServer/Intro.md b/docs/McpServer-Skills/MCP/TRONMCPServer/Intro.md index 2f0a0fc6..738dc833 100644 --- a/docs/McpServer-Skills/MCP/TRONMCPServer/Intro.md +++ b/docs/McpServer-Skills/MCP/TRONMCPServer/Intro.md @@ -17,7 +17,7 @@ This means different things to different people: ## What Can It Do? -TRON MCP Server covers almost all common TRON blockchain operations, from read-only queries to asset management, providing **97 tools**, **6 prompt templates**, and **1 resource definition**. +TRON MCP Server covers almost all common TRON blockchain operations, from read-only queries to asset management, providing **97 tools**, **6 prompt templates**, and **1 resource definition**. In read-only mode (the official cloud service or `--readonly`), write tools and the 2 write prompts are not registered, leaving 68 read tools and 4 prompt templates. Here is an overview of core capabilities — each one can be triggered via natural language: diff --git a/docs/McpServer-Skills/MCP/TRONMCPServer/LocalPrivatizedDeployment.md b/docs/McpServer-Skills/MCP/TRONMCPServer/LocalPrivatizedDeployment.md index a086ee22..134d731c 100644 --- a/docs/McpServer-Skills/MCP/TRONMCPServer/LocalPrivatizedDeployment.md +++ b/docs/McpServer-Skills/MCP/TRONMCPServer/LocalPrivatizedDeployment.md @@ -29,15 +29,17 @@ Of course, all read-only query capabilities are also fully retained. | Requirement | Description | | :--- | :--- | -| **Node.js** | v20.0.0 or higher ([download](https://nodejs.org/)) | +| **Node.js** | Recommended: 22.23.4+ (22.x) or 24.22.1+ (24.x), the October 2026 security releases ([download](https://nodejs.org/)). A source checkout of `main` (tag `v1.1.8`, Option B below) requires this range (its `package.json` still says `1.1.7`, so the server reports version `1.1.7`); the npm package `1.1.7` that `npx` runs (Option A) declares `>=20`. | | **TronGrid API Key** | Optional but recommended ([apply here](https://www.trongrid.io/)) | Verify your Node.js version: ```bash -node --version # Should output v20.x.x or higher +node --version # recommended: v22.23.4+ or v24.22.1+ ``` +The requirement is the `engines` field in `package.json`: on a source checkout, `npm install` under another Node.js version prints an `EBADENGINE` warning but still installs, and the server does not check the Node.js version at runtime. + ### Security Principles Before configuring your wallet, make sure to understand the following security principles: @@ -50,7 +52,7 @@ Before configuring your wallet, make sure to understand the following security p ## Installation Steps ### Step 1: Configure Wallet -The wallet determines which identity the AI assistant uses to perform on-chain operations. TRON MCP Server uses [Agent Wallet](../../../Agent-Wallet/Intro.md) for secure wallet management. If no wallet is configured, write tools will return an error prompting you to set up a wallet. +The wallet determines which identity the AI assistant uses to perform on-chain operations. TRON MCP Server uses [Agent Wallet](../../../Agent-Wallet/Intro.md) for secure wallet management. If no wallet is configured, write tools return a wallet error when called (see [FAQ](./FAQ.md#write-tools-wallet-error)). #### Agent Wallet @@ -63,34 +65,38 @@ TRON MCP Server uses [Agent Wallet](../../../Agent-Wallet/Intro.md) for wallet m | Runtime Wallet Switching | Yes | | Recommended For | All use cases | -> For installation, initialization, and detailed usage of Agent Wallet, see the [Agent-Wallet documentation](../../../Agent-Wallet/Intro.md). +> TRON MCP Server depends on Agent Wallet **2.x** (`@bankofai/agent-wallet ^2.3.0`). The [Agent-Wallet documentation](../../../Agent-Wallet/Intro.md) describes 3.x, which this server does not use yet — follow the 2.x commands on this page. -First, install Agent Wallet: +First, install the Agent Wallet 2.x CLI: ```bash -npm install -g @bankofai/agent-wallet +npm install -g @bankofai/agent-wallet@2 ``` +The `@2` pin installs the latest 2.x release (2.4.0 at the time of writing). Without it, npm installs 3.x, which has no `local_secure` wallets, no master password, and no `--save-runtime-secrets`, so the steps below would not work. + Then, choose one of the following two paths depending on your situation: #### Path 1: Generate a New Wallet (Recommended for New Users) -If you don't have an existing private key, use `agent-wallet start` to generate a new wallet with an encrypted keystore and master password: +If you don't have an existing private key, use `agent-wallet start local_secure` to generate a new wallet with an encrypted keystore and master password: ```bash -agent-wallet start +agent-wallet start local_secure --save-runtime-secrets ``` -Follow the interactive prompts to set your master password and generate a wallet. Agent Wallet manages the encrypted keystore for you, but the server still needs the password at signing time — plain `agent-wallet start` does not persist it. Do one of: +Follow the interactive prompts to set your master password and generate a wallet. Agent Wallet manages the encrypted keystore for you, but the server still needs the password at signing time. `--save-runtime-secrets` writes it to `~/.agent-wallet/runtime_secrets.json`; without the flag it is not persisted, and you must instead export `AGENT_WALLET_PASSWORD` in the environment the MCP server runs in. + +If you already ran `agent-wallet start` without the flag, do not run it again to fix this: with wallets present it only offers `add`, which creates a new wallet and makes it the active one, or `exit`, which saves nothing. Export `AGENT_WALLET_PASSWORD`, or save the password with one of these commands: -- run `agent-wallet start --save-runtime-secrets`, which writes the password to `~/.agent-wallet/runtime_secrets.json`, or -- export `AGENT_WALLET_PASSWORD` in the environment the MCP server runs in. +- `agent-wallet sign msg hello -n tron --save-runtime-secrets` — asks for the password, saves it, then signs a test message with the active wallet. It saves the password before checking it, so if it prints `Wrong password`, delete `~/.agent-wallet/runtime_secrets.json` and run it again. +- `agent-wallet add local_secure --save-runtime-secrets` — checks the password before saving it, but also creates an additional wallet (the active wallet stays the same). -Without either, unlocking a `local_secure` wallet fails when a write tool is called. Use `AGENT_WALLET_DIR` if your keystore lives outside `~/.agent-wallet`. +Without a saved or exported password, unlocking a `local_secure` wallet fails when a write tool is called. Use `AGENT_WALLET_DIR` if your keystore lives outside `~/.agent-wallet`. #### Path 2: Import an Existing Private Key -If you already have a private key you want to use, set it via the `AGENT_WALLET_PRIVATE_KEY` environment variable. Note the precedence: the env-var path is only reached when no password resolves (neither `runtime_secrets.json` nor `AGENT_WALLET_PASSWORD`) **and** the wallet directory holds no wallets. If you already ran Path 1, saved a runtime password, or ran the Openclaw installer, the keystore path wins and this variable is silently ignored. +If you already have a private key you want to use, set it via the `AGENT_WALLET_PRIVATE_KEY` environment variable (Agent Wallet also accepts the alias `TRON_PRIVATE_KEY`, and a mnemonic via `AGENT_WALLET_MNEMONIC` or `TRON_MNEMONIC`). Note the precedence: the env-var path is only reached when no password resolves (neither `runtime_secrets.json` nor `AGENT_WALLET_PASSWORD`) **and** the wallet directory holds no wallets. If you already ran Path 1, saved a runtime password, or ran the Openclaw installer, the keystore path wins and these variables are silently ignored. ```bash export AGENT_WALLET_PRIVATE_KEY=your_private_key_here @@ -120,14 +126,22 @@ echo $AGENT_WALLET_PRIVATE_KEY #### TronGrid API Key -The TRON Mainnet public RPC has strict rate limits. For frequent on-chain queries, it is strongly recommended to configure a free TronGrid API Key: +On a source checkout from `v1.1.8`, the API Key also decides which Mainnet endpoint the server talks to. For frequent on-chain queries, it is recommended to configure a free TronGrid API Key: ```bash # Add to ~/.zshrc or ~/.bashrc export TRONGRID_API_KEY="" ``` -Register for free at [trongrid.io](https://www.trongrid.io/). The server still works without this, but may encounter rate-limiting errors during high-frequency operations. Testnet networks (Nile, Shasta) are less affected by rate limits. +Register for free at [trongrid.io](https://www.trongrid.io/). How the variable affects each network (the only difference between versions is Mainnet without a key): + +| Network | `TRONGRID_API_KEY` set | `TRONGRID_API_KEY` not set | +| :--- | :--- | :--- | +| **Mainnet** | `https://api.trongrid.io`, with your key sent as `TRON-PRO-API-KEY` (your own quota) | Source checkout from `v1.1.8`: falls back to the BANK OF AI endpoint `https://hptg.bankofai.io`. npm `1.1.7` (what `npx` runs): `https://api.trongrid.io` without a key | +| **Nile** | `https://nile.trongrid.io` (key header also sent) | `https://nile.trongrid.io` | +| **Shasta** | `https://api.shasta.trongrid.io` (key header also sent) | `https://api.shasta.trongrid.io` | + +The server works without a key, but keyless requests to TronGrid (Mainnet on npm `1.1.7`, and Nile / Shasta) share TronGrid's public rate limits, so high-frequency use can hit rate-limit errors. Set one if you want Mainnet traffic to go to TronGrid under your own quota. --- @@ -138,7 +152,7 @@ Multiple deployment options are available. For most users, Option A is sufficien #### Option A: Run directly with npx (Recommended) -No need to clone the repository — run the latest version directly via `npx`. This is also the default method used in the MCP client configuration examples below. +No need to clone the repository — run the latest version directly via `npx`. This is also the command used in the [Configuration Notes](#configuration-notes) below. ```bash npx -y @bankofai/mcp-server-tron @@ -173,7 +187,7 @@ From a source checkout (Option B) you can use the script instead: npm run start:http ``` -This will start a local stateless Streamable HTTP server (default: `http://localhost:3001/mcp`) that your MCP client can connect to. Each request is handled independently — no session state is maintained between requests. +This will start a local stateless Streamable HTTP server (default: `http://localhost:3001/mcp`) that your MCP client can connect to. `GET` and `DELETE` on `/mcp` return `405` (SSE is not supported), and `GET /` returns server information. Each request is handled independently — no session state is maintained between requests. You can customize the port and host via environment variables: @@ -182,11 +196,11 @@ export MCP_PORT=3001 # default: 3001 export MCP_HOST=0.0.0.0 # default: 0.0.0.0 ``` -The Docker and source-checkout start scripts also read `MCP_LOG_DIR` (default `/app/logs` in the container, `./logs` from a checkout). The published npm package ships only `build/` and `bin/`, so that variable does not apply to the `npx` route above. +The Docker and source-checkout start scripts also read `MCP_LOG_DIR` (default `/app/logs` in the container, `./logs` from a checkout). The published npm package ships only `build/`, `bin/`, `package.json`, `README.md` and `LICENSE`, so that variable does not apply to the `npx` route above. #### Option D: Docker Deployment -Run TRON MCP Server in a Docker container for isolated, reproducible environments. The Docker image runs in **read-only HTTP mode** by default. +Run TRON MCP Server in a Docker container for isolated, reproducible environments. The Docker image always runs in **read-only HTTP mode**: `docker-start.sh` passes `--readonly`, and there is no switch to turn it off. ```bash # 1. Create a .env file for sensitive variables (never commit this file) diff --git a/docs/McpServer-Skills/MCP/TRONMCPServer/OfficialServerAccess.md b/docs/McpServer-Skills/MCP/TRONMCPServer/OfficialServerAccess.md index de9f4449..a02a3a88 100644 --- a/docs/McpServer-Skills/MCP/TRONMCPServer/OfficialServerAccess.md +++ b/docs/McpServer-Skills/MCP/TRONMCPServer/OfficialServerAccess.md @@ -85,7 +85,7 @@ If you have Node.js installed and prefer the command line, run the following dir npx add-mcp https://tron-mcp-server.bankofai.io/mcp -y ``` -The `-y` flag skips all interactive prompts and automatically installs to every AI tool detected on your computer. Once complete, it will show ✅ Installation complete! along with the list of agents it was installed to. +The `-y` flag skips all interactive prompts. add-mcp then writes project-level config in the current directory: for the AI tools it detects there (from marker folders and files such as `.claude`, `.cursor`, `.vscode` or `.mcp.json`), or, if it detects none, for every tool that supports a project config. When it finishes it prints `Installation complete` and the agents it installed to. Once installation is complete, you can start interacting with the TRON blockchain via TRON MCP Server. @@ -117,7 +117,7 @@ The installer automatically detects the remote MCP service URL and generates a s **2️⃣ Choose which AI tools to install to** -The installer auto-detects AI tools on your computer (e.g., Claude Code, Cursor, Cline, etc.). Use Space to select the ones you want: +The installer detects AI tools from marker folders and files in the current directory (such as `.claude`, `.cursor`, `.vscode` or `.mcp.json`), for example Claude Code or Cursor. Use Space to select the ones you want: ``` ◇ Detected 1 agent @@ -128,7 +128,7 @@ The installer auto-detects AI tools on your computer (e.g., Claude Code, Cursor, **3️⃣ Confirm installation details** -The installer displays an installation summary. Review it and select `Yes` to proceed: +If every tool you selected supports both project and global config, the installer first asks **Installation scope** (`Project` / `Global`); the summary below is for `Project`. It then displays an installation summary. Review it and select `Yes` to proceed: ``` ◇ Installation Summary ────╮ @@ -151,11 +151,11 @@ When you see output like this, TRON MCP Server has been successfully installed t ``` ◇ Installation complete │ -◇ Installed to 1 agent ───────╮ -│ │ -│ ✓ Claude Code: ~/.mcp.json │ -│ │ -├──────────────────────────────╯ +◇ Installed to 1 agent ──────────────────╮ +│ │ +│ ✓ Claude Code: ~/my-project/.mcp.json │ +│ │ +├─────────────────────────────────────────╯ │ └ Done! ``` diff --git a/docs/McpServer-Skills/MCP/TRONMCPServer/QuickStart.md b/docs/McpServer-Skills/MCP/TRONMCPServer/QuickStart.md index 2437a124..4765bf4b 100644 --- a/docs/McpServer-Skills/MCP/TRONMCPServer/QuickStart.md +++ b/docs/McpServer-Skills/MCP/TRONMCPServer/QuickStart.md @@ -2,7 +2,7 @@ The goal of this page is simple: **get you connected in 1 minute and make your first blockchain query.** -We'll use the [official cloud service](./OfficialServerAccess.md) for this quick start. The cloud service is read-only — no dependencies to install, no wallet to configure, no API Key required. Just copy a config snippet into your AI client and start asking questions. +We'll use the [official cloud service](./OfficialServerAccess.md) for this quick start. The cloud service is read-only — no dependencies to install, no wallet to configure, no API Key required. Just paste one install prompt into your AI Agent and start asking questions. --- @@ -11,12 +11,12 @@ We'll use the [official cloud service](./OfficialServerAccess.md) for this quick Before you begin, make sure you have the following installed: - Any AI client that supports MCP -- **Node.js v20.0.0 or higher** (needed for `npx` command execution) ([Node.js Download](https://nodejs.org/)) +- **Node.js** — needed to run `npx` ([Node.js Download](https://nodejs.org/)). We recommend the October 2026 security releases: 22.23.4+ (22.x) or 24.22.1+ (24.x) Verify your Node.js version: ```bash -node --version # should output v20.x.x or higher +node --version # recommended: v22.23.4+ or v24.22.1+ ``` --- @@ -60,7 +60,7 @@ Check the TRX balance of TRON address TXyz... If everything is working, the AI will automatically call the `get_balance` tool and return the TRX balance of that address. Seeing a result means you've successfully connected. :::info About the Cloud Service's Capabilities -The configuration above connects to the **official cloud read-only service**, which supports all query operations (checking balances, looking up transactions, reading contract state, etc.) but does not support write operations (transfers, contract calls, etc.). For full read/write capabilities, please refer to [Local Private Deployment](./LocalPrivatizedDeployment.md). +The install above connects to the **official cloud read-only service**, which supports all query operations (checking balances, looking up transactions, reading contract state, etc.) but does not support write operations (transfers, contract calls, etc.). For full read/write capabilities, please refer to [Local Private Deployment](./LocalPrivatizedDeployment.md). ::: --- @@ -80,7 +80,7 @@ Once connected, try a few more prompts to get a feel for what TRON MCP Server ca | "Get the ABI of contract TXyz..." | Read a smart contract interface definition | | "Query the latest events triggered by contract TXyz..." | Get contract event logs | -These are just the tip of the iceberg. For the full list of 97 tools and 6 prompt templates, see [Full Capability List](./ToolList.md). +These are just the tip of the iceberg. For the full list of 97 tools and 6 prompt templates (the read-only cloud service exposes the 68 read tools and 4 of the prompts), see [Full Capability List](./ToolList.md). --- diff --git a/docs/McpServer-Skills/MCP/TRONMCPServer/ToolList.md b/docs/McpServer-Skills/MCP/TRONMCPServer/ToolList.md index 8f5b581a..af1daa13 100644 --- a/docs/McpServer-Skills/MCP/TRONMCPServer/ToolList.md +++ b/docs/McpServer-Skills/MCP/TRONMCPServer/ToolList.md @@ -12,11 +12,11 @@ Each tool is labeled with a **mode** — "read" or "write": - **Read tools**: Only query on-chain data and do not affect any state. They can be used in both cloud services and local deployments. - **Write tools**: Modify blockchain state (e.g., transfers, staking, contract interactions). These require a configured wallet (via [Agent Wallet](../../../Agent-Wallet/Intro.md)) to execute. -Write tools are always visible in the AI’s tool list, but wallet availability is checked at execution time. If no wallet is configured, calling a write tool will return an error prompting you to set up a wallet. In **read-only mode** (cloud service or `--readonly` flag), write tools are not registered. +Write tools are always visible in the AI’s tool list, but wallet availability is checked at execution time. If no wallet is configured, calling a write tool returns a wallet error (see [FAQ](./FAQ.md#wallet-error-messages)). In **read-only mode** (cloud service or `--readonly` flag), the 29 write tools and the 2 write prompts (`prepare_transfer`, `interact_with_contract`) are not registered, leaving 68 read tools and 4 prompts. ::: :::tip `network` parameter -Most tools include an optional `network` parameter used to specify the target network (`mainnet`, `nile`, or `shasta`). If not specified, the default is `mainnet`. +Most tools include an optional `network` parameter used to specify the target network (`mainnet`, `nile`, or `shasta`; `tron` / `trx` are aliases for `mainnet` and `testnet` for `nile`). If not specified, the default is `mainnet`. During testing, it is recommended to explicitly set `nile` each time to avoid unintended operations on the mainnet. ::: @@ -353,6 +353,8 @@ These tools provide direct access to TRON full-node RPC methods for advanced que Prompts are pre-defined workflow templates that guide the AI through complex multi-step operations. They help ensure safety (e.g., confirming before transfers) and thoroughness (e.g., checking balance before sending). +The two prompts with "Requires Wallet: Yes" are not registered in read-only mode (cloud service or `--readonly`), so read-only connections see only the other 4. + | Prompt Name | Description | Key Parameters | Requires Wallet | | :--- | :--- | :--- | :--- | | `prepare_transfer` | Safely prepare and execute a token transfer with balance checks, cost estimation, and user confirmation. | `tokenType`, `recipient`, `amount`, `network`, `tokenAddress` | Yes | @@ -376,4 +378,4 @@ Resources provide static reference data that the AI can query for context. | Resource Name | URI | Description | | :--- | :--- | :--- | -| `supported_networks` | `tron://networks` | Returns the list of all supported TRON networks and their configuration (RPC URLs, explorer links, etc.). | +| `supported_networks` | `tron://networks` | Returns the identifiers of the supported TRON networks as JSON: `{"supportedNetworks": ["mainnet", "nile", "shasta"]}`. RPC URLs and explorer links are not included. | diff --git a/docs/Openclaw-extension/FAQ.md b/docs/Openclaw-extension/FAQ.md index a82241e5..42fdeb61 100644 --- a/docs/Openclaw-extension/FAQ.md +++ b/docs/Openclaw-extension/FAQ.md @@ -10,7 +10,7 @@ Don't panic when you see an error — it's usually just a small setting that's n **In short**: Your computer doesn't have Node.js installed, or the version is too old. -**How to fix**: Go to the [Node.js official website](https://nodejs.org/) and download the latest stable version (LTS, v20 or higher — `@bankofai/mcp-server-tron`, which the wizard installs, declares `node >= 20`). Install it like any regular software by clicking "Next" all the way through. Then close the terminal window and run the installation command again. +**How to fix**: Go to the [Node.js official website](https://nodejs.org/) and download the latest stable version (LTS — the installer requires 22.23.4+ on 22.x, 24.22.1+ on 24.x, or 26.12.1+; Node.js 24 is the safest choice). Install it like any regular software by clicking "Next" all the way through. Then close the terminal window and run the installation command again. ### Error Says "command not found: git" @@ -62,7 +62,7 @@ Don't panic when you see an error — it's usually just a small setting that's n ### Why Can Others Send Transfers While My AI Can Only Read Data? -**Reason**: Your AI is currently in ultra-safe "read-only mode." This is because you skipped the AgentWallet configuration during installation and didn't provide it with wallet keys. +**Reason**: Transfers and trades must be signed by a wallet in AgentWallet, and your AI can't find a usable one. The installer doesn't let you skip this step — on a first install, if `agent-wallet start` fails or is cancelled, the whole installer stops — so this usually means the wallet setup never finished, or the wallet data in `~/.agent-wallet` was reset or deleted afterwards. **How to fix**: Run the installation script again. At the AgentWallet setup level, follow the prompts carefully to properly configure your wallet. After configuring and restarting, transfer and trading functions will be activated. @@ -83,7 +83,7 @@ Don't panic when you see an error — it's usually just a small setting that's n **How to fix**: 1. **Quick fix**: Wait a few minutes before asking again. -2. **Permanent fix**: Go to [TronGrid](https://www.trongrid.io/) and apply for a free dedicated API Key. Enter this key during installation, and AI will be able to use the VIP express lane. +2. **Permanent fix**: Go to [TronGrid](https://www.trongrid.io/) and apply for a free dedicated API Key. The installer doesn't ask for this key — set it yourself as the `TRONGRID_API_KEY` environment variable (see [How to Add API Keys](./QuickStart.md#️-how-to-add-api-keys-vip-pass-after-installation)), restart OpenClaw, and AI will be able to use the VIP express lane. --- @@ -95,7 +95,7 @@ Absolutely! When the installation wizard reaches Level 4, it will list all skill ### I'm Done With It — How Do I Uninstall? -The simplest brute-force method: Open your file manager, find the `~/.openclaw/skills/` (Mac/Linux) or `%USERPROFILE%\.openclaw\skills\` (Windows) directory, delete the skill folder(s) you no longer want, then restart the AI software — they'll be completely gone. +The simplest brute-force method: Open your file manager, find the `~/.openclaw/skills/` (Mac/Linux) or `%USERPROFILE%\.openclaw\skills\` (Windows) directory, delete the skill folder(s) you no longer want, then restart the AI software — the skills are gone. The MCP server entries, `~/.mcporter/bankofai-config.json`, the global npm packages and `~/.agent-wallet` stay. The installer's Clean mode removes the MCP entries, the installed skills, `~/.x402-config.json` and `bankofai-config.json`, then re-initialises agent-wallet (`agent-wallet reset`, then `start --override`); it does not uninstall the global npm packages. ### I Messed Everything Up — Can I Reinstall? @@ -110,11 +110,11 @@ Reinstall anytime! Don't worry about breaking your computer. ### Does the Installer Need Admin Privileges? -Not for the config files — those all land under your user directory, and the installer touches neither the registry nor Program Files. The one thing that reaches outside it is the pinned global install `npm install -g @bankofai/agent-wallet@`. On Windows that goes to `%APPDATA%\npm` and needs no elevation; on macOS or Linux with a system-wide Node it writes to the global `node_modules` directory (for example `/usr/local/lib/node_modules`) and may ask for your password. +Not for the config files — those all land under your user directory, and the installer touches neither the registry nor Program Files. The things that reach outside it are the pinned global npm installs: `npm install -g @bankofai/agent-wallet@` (unless 2.3.1 is already installed), and `npm install --global @bankofai/x402-cli@` (only when the x402-payment skill is installed). On Windows these go to `%APPDATA%\npm` and need no elevation; on macOS or Linux with a system-wide Node it writes to the global `node_modules` directory (for example `/usr/local/lib/node_modules`) and may ask for your password. ### Is the Windows Experience the Same as Mac/Linux? -Identical. The Windows installer (`install.ps1`) is a full port of the Linux/macOS version (`install.sh`) — same installation flow, same multi-select menus, same config file structure. The only differences are file paths (`~/` becomes `%USERPROFILE%\`) and file permissions (`chmod 600` becomes `icacls` ACL). +Almost. The Windows installer (`install.ps1`) is a port of the Linux/macOS version (`install.sh`) — same installation flow, same multi-select menus, same config file structure. The differences are file paths (`~/` becomes `%USERPROFILE%\`), file permissions (`chmod 600` becomes `icacls` ACL), and the OpenClaw check: if the `.openclaw` folder doesn't exist in your home directory, `install.sh` warns and asks `Continue anyway? (y/N)`, while `install.ps1` stops with an error — install OpenClaw first, then re-run it. ### Can I Use WSL (Windows Subsystem for Linux)? diff --git a/docs/Openclaw-extension/Intro.md b/docs/Openclaw-extension/Intro.md index 9ffcdc93..34d625ab 100644 --- a/docs/Openclaw-extension/Intro.md +++ b/docs/Openclaw-extension/Intro.md @@ -51,7 +51,7 @@ It will digest all the boring code and data for you, and report back in the clea - **I'm a total beginner**: Perfect! Don't want to deal with code, get dizzy looking at charts, and just want to chat with AI to help you check data and make trades? This was tailor-made for you. - **I'm a Web3 veteran**: Tired of opening web pages and connecting wallets every day? Want a personal trading assistant on call 24/7? It can save you tons of time watching charts and checking contracts. -- **I'm a Windows user**: No problem at all! Since v1.4.5, OpenClaw Extension natively supports Windows 10/11. One PowerShell command and you're set — the experience is identical to Mac/Linux. +- **I'm a Windows user**: No problem at all! Since v1.4.5, OpenClaw Extension natively supports Windows 10/11. One PowerShell command and you're set — the experience is almost identical to Mac/Linux (the few differences are listed in the [FAQ](./FAQ.md)). --- diff --git a/docs/Openclaw-extension/QuickStart.md b/docs/Openclaw-extension/QuickStart.md index 24392a77..416076d4 100644 --- a/docs/Openclaw-extension/QuickStart.md +++ b/docs/Openclaw-extension/QuickStart.md @@ -2,6 +2,10 @@ Our goal: **Spend a few minutes following the wizard, clicking a few buttons, and get your AI to successfully fetch its first piece of on-chain data.** +:::note Versions pinned by the installer +The one-click installer currently installs **agent-wallet 2.3.1** and **Skills v1.5.15**. The wallet steps on this page therefore follow agent-wallet 2.x (master password, `local_secure` wallets), not the 3.x behavior described in the [Agent-Wallet docs](../Agent-Wallet/Intro.md). +::: + --- ## 🕹️ Prerequisites @@ -9,7 +13,7 @@ Our goal: **Spend a few minutes following the wizard, clicking a few buttons, an Before you begin, make sure the following basic software is installed on your computer (if not, download and install them from their official websites just like any regular software): 1. **OpenClaw**: Your AI assistant software. -2. **Node.js** (v20 or above): the wizard installs `@bankofai/mcp-server-tron`, which declares `node >= 20`. *(Extremely important — neither installer enforces 20: the macOS/Linux script only checks that `node` exists, and the Windows script enforces only 18. An older runtime passes pre-flight and fails later.)* +2. **Node.js** (22.23.4+ on 22.x, 24.22.1+ on 24.x, or 26.12.1+): both installers check the full version against `^22.23.4 || ^24.22.1 || >=26.12.1` and stop before installing anything if Node.js is missing or too old. *(Node.js 24 is the safest choice: it satisfies every component the wizard installs.)* 3. **Git**: A small tool used to download skill packs. **Windows users, additional requirements:** @@ -68,7 +72,7 @@ install.bat -🚑 **First Aid: Got an error right after pressing Enter?** If the screen says `command not found: node` (Mac/Linux) or `node is not recognized` (Windows), it means your computer is missing the prerequisites mentioned above. 👉 [Click here to see how to fix it](./FAQ.md#error-says-command-not-found-node-or-npm-install-failed) +🚑 **First Aid: Got an error right after pressing Enter?** If the screen says `Error: Node.js ^22.23.4 || ^24.22.1 || >=26.12.1 is required` (possibly followed by `found vX.Y.Z`; on Windows a similar message without `Error: ` appears under `Installation failed with error:`), it means your computer is missing the prerequisites mentioned above. 👉 [Click here to see how to fix it](./FAQ.md#error-says-command-not-found-node-or-npm-install-failed) If there are no errors, an English wizard will appear on screen. Think of it as a text-based mini-game with 4 levels: @@ -102,7 +106,7 @@ If you chose `2` (Clean install), the installer lists everything that will be de The following data will be permanently deleted: • ALL MCP entries in: ~/.mcporter/mcporter.json • ALL installed skills (global and workspace) - • x402 config file: ~/.x402-config.json + • legacy x402 config file: ~/.x402-config.json • BANK OF AI local config: ~/.mcporter/bankofai-config.json • AgentWallet config will be overwritten by: agent-wallet start --override --save-runtime-secrets @@ -115,9 +119,9 @@ After confirming, the installer automatically removes old skills: ``` Running cleanup... -◇ Found 10 unique installed skill(s) +◇ Found 14 unique installed skill(s) ◇ Removal process complete -◆ Successfully removed 10 skill(s) +◆ Successfully removed 14 skill(s) ✓ Clean install cleanup completed. @@ -130,7 +134,8 @@ Then runs `agent-wallet reset` to completely wipe old wallet data: Step 0: AgentWallet Setup Launching: agent-wallet reset -This will delete ALL wallet data in: ~/.agent-wallet +This will delete ALL wallet data in: /home//.agent-wallet + 4 file(s): master.json, wallets_config.json, runtime_secrets.json, secret_.json ✔ Are you sure you want to reset? This cannot be undone. Yes ✔ Really delete everything? Last chance! Yes @@ -209,8 +214,12 @@ If you chose auto-generate in step ②, the master password generated for you wi This master password is the key to your AI's wallet. **Lose it and you lose access to the wallet.** Write it down on paper, save it in a password manager — anything but forgetting it. ::: -:::tip See "Wallet already initialized." during a Normal install upgrade? -If you've previously installed AgentWallet and chose Normal install, the wizard skips the password setup and lets you enter a Wallet ID and generate a wallet directly. Your previous master password and existing wallets are preserved. +:::tip Already have wallets? (Normal install upgrade) +If AgentWallet already has wallets and you chose Normal install, the wizard first shows `Already initialized with N wallet(s), active: ` and asks **What would you like to do?** +- **exit** — keep everything as is; the installer continues to the next level. +- **add** — choose the wallet type, then unlock with your **existing** master password (`Master Password (enter your existing password to unlock)`; this prompt is skipped if the password was saved to `runtime_secrets.json` by an earlier install). After `Wallet already initialized.`, enter a new Wallet ID and generate a wallet as in steps ③–④; the new wallet becomes the active one. No new password is set. + +Your previous master password and existing wallets are preserved either way. ::: (🚑 Got stuck with an error? 👉 [Click here to see how to fix AgentWallet installation failures](./FAQ.md#agentwallet-installation-failed)) @@ -272,12 +281,16 @@ Unlike TRON (which uses the encrypted AgentWallet), BNB Chain currently stores y #### bankofai-recharge (Recharge Assistant) -This one is fully automatic — no input needed! It connects to BANK OF AI's remote recharge service. +This one is fully automatic — no input needed! It registers the remote server `https://recharge.bankofai.io/mcp` (type `remote` in the add-mcp summary). ``` ✓ Configuration saved for bankofai-recharge. ``` +:::caution The recharge MCP service is offline +`https://recharge.bankofai.io/mcp` has been taken offline. The installer still selects and registers `bankofai-recharge` by default, but its tools no longer respond, so you can uncheck it in the MCP selection above. To top up your BANK OF AI account, use wallet-cli's [`bai recharge`](../wallet-cli/command-reference.md#bai-recharge) instead. +::: + ### 🟢 Level 4: Pick Your Skill Packs (Give AI a "Brain") First, choose where to install the skills: @@ -294,15 +307,20 @@ Select skills installation scope: Press Enter (or type `1`) to install globally — this way all your OpenClaw workspaces can use these skills. +:::note If you choose `2` (Workspace-level) +After you pick skills in the picker below, the skills tool asks **Installation scope** (`Project` / `Global`) once more. Choose `Project` to install into a `skills/` folder inside the directory you ran the installer from (`/skills/`); choosing `Global` installs to `~/.openclaw/skills/` anyway, but the installer then compares only the workspace list, so it prints `No new skills were installed.`, skips the API key prompt and `Next steps`, and does not install the x402 CLI. Choose `1` above if you want global skills. +::: + Then the skill picker launches: ``` -◇ Found 10 skills +◇ Found 14 skills │ ◇ Select skills to install (space to toggle) -│ agent-wallet, bankofai-guide, recharge-skill, SunPerp Perpetual Futures Trading, -│ SunPump Meme Token Toolkit, SunSwap DEX Trading, TronScan Data Lookup, -│ USDD / JUST Protocol, wallet-cli, x402-payment +│ agent-wallet, bankofai-guide, Multi-Sig & Account Permissions, recharge-skill, +│ SunPerp Perpetual Futures Trading, SunPump Meme Token Toolkit, SunSwap DEX Trading, +│ TRC20 Token Toolkit, TronScan Data Lookup, TRX Staking & SR Voting, twitter-digest, +│ twitter-mcp, USDD / JUST Protocol, x402-payment ``` Here's what each skill does: @@ -311,50 +329,87 @@ Here's what each skill does: | :--- | :--- | | **agent-wallet** | AgentWallet management operations (view wallets, sign transactions) | | **bankofai-guide** | Onboarding helper that walks the AI through next steps after installation | -| **SunSwap DEX Trading** | Swap tokens on SunSwap (TRON's biggest DEX) | -| **SunPerp Perpetual Futures** | Trade perpetual futures on SunPerp | +| **Multi-Sig & Account Permissions** | Manage TRON multi-sig permissions — keys, thresholds, and co-signed proposals | +| **recharge-skill** | Check and top up your BANK OF AI balance | +| **SunPerp Perpetual Futures Trading** | Trade perpetual futures on SunPerp | | **SunPump Meme Token Toolkit** | Create and trade meme tokens on SunPump; query token info, rankings, holders, and trade history | +| **SunSwap DEX Trading** | Swap tokens on SunSwap (TRON's biggest DEX) | +| **TRC20 Token Toolkit** | TRC20 transfers, approvals, balance queries, and token metadata | | **TronScan Data Lookup** | Query blockchain data via TronScan | +| **TRX Staking & SR Voting** | Stake TRX, vote for Super Representatives, and claim voting rewards | +| **twitter-digest** | Generate an X/Twitter daily digest (mentions, home timeline, reply opportunities) | +| **twitter-mcp** | Install and authorize the `xurl` CLI for X/Twitter, or register the hosted X MCP bridge | | **USDD / JUST Protocol** | Manage USDD stablecoin and JUST Protocol positions | -| **wallet-cli** | Standalone TRON wallet operations (transfers, staking, voting, signing) via the pinned `wallet-cli` npm package | -| **x402-payment** | x402 protocol payments (agent-to-agent) | -| **recharge-skill** | Check and top up your BANK OF AI balance | +| **x402-payment** | Pay x402-protected HTTP APIs on TRON or BSC through the `x402-cli` command | After selecting, the installer shows a security risk assessment: ``` ◇ Security Risk Assessments │ Gen Socket Snyk +│ agent-wallet Safe 1 alert High Risk │ bankofai-guide Safe 0 alerts High Risk +│ Multi-Sig & Account Permissions -- -- -- │ recharge-skill Safe 1 alert Med Risk │ SunPerp Perpetual Futures Trading -- -- -- -│ SunPump Meme Token Toolkit -- -- -- -│ SunSwap DEX Trading -- -- -- -│ TronScan Data Lookup -- -- -- -│ USDD / JUST Protocol -- -- -- -│ wallet-cli -- -- -- +│ ... │ x402-payment Safe 1 alert Med Risk -│ agent-wallet Safe 1 alert High Risk ``` -Review the report, then confirm to proceed. When installation completes: +Review the report, then answer the `Proceed with installation?` prompt with `Yes`. When installation completes: ``` -◇ Installed 10 skills +◇ Proceed with installation? +│ Yes │ -│ ✓ agent-wallet → ~/.openclaw/skills/agent-wallet -│ ✓ bankofai-guide → ~/.openclaw/skills/bankofai-guide -│ ✓ recharge-skill → ~/.openclaw/skills/recharge-skill -│ ✓ SunPerp Perpetual Futures Trading → ~/.openclaw/skills/sunperp-perpetual-futures-trading -│ ✓ SunPump Meme Token Toolkit → ~/.openclaw/skills/sunpump-meme-token-toolkit -│ ✓ SunSwap DEX Trading → ~/.openclaw/skills/sunswap-dex-trading -│ ✓ TronScan Data Lookup → ~/.openclaw/skills/tronscan-data-lookup -│ ✓ USDD / JUST Protocol → ~/.openclaw/skills/usdd-just-protocol -│ ✓ wallet-cli → ~/.openclaw/skills/wallet-cli -│ ✓ x402-payment → ~/.openclaw/skills/x402-payment -``` - -After skills are installed, the installer enters a configuration phase: +◇ Installed 14 skills +│ +│ ✓ agent-wallet (copied) +│ → ~/.openclaw/skills/agent-wallet +│ ✓ bankofai-guide (copied) +│ → ~/.openclaw/skills/bankofai-guide +│ ✓ Multi-Sig & Account Permissions (copied) +│ → ~/.openclaw/skills/multi-sig-account-permissions +│ ✓ recharge-skill (copied) +│ → ~/.openclaw/skills/recharge-skill +│ ✓ SunPerp Perpetual Futures Trading (copied) +│ → ~/.openclaw/skills/sunperp-perpetual-futures-trading +│ ✓ SunPump Meme Token Toolkit (copied) +│ → ~/.openclaw/skills/sunpump-meme-token-toolkit +│ ✓ SunSwap DEX Trading (copied) +│ → ~/.openclaw/skills/sunswap-dex-trading +│ ✓ TRC20 Token Toolkit (copied) +│ → ~/.openclaw/skills/trc20-token-toolkit +│ ✓ TronScan Data Lookup (copied) +│ → ~/.openclaw/skills/tronscan-data-lookup +│ ✓ TRX Staking & SR Voting (copied) +│ → ~/.openclaw/skills/trx-staking-sr-voting +│ ✓ twitter-digest (copied) +│ → ~/.openclaw/skills/twitter-digest +│ ✓ twitter-mcp (copied) +│ → ~/.openclaw/skills/twitter-mcp +│ ✓ USDD / JUST Protocol (copied) +│ → ~/.openclaw/skills/usdd-just-protocol +│ ✓ x402-payment (copied) +│ → ~/.openclaw/skills/x402-payment +``` + +#### x402 CLI (only if x402-payment is installed) + +If `x402-payment` is among your installed skills, the installer then installs the pinned payment CLI globally (it skips this when `x402-cli` 1.0.1 is already present): + +``` +Installing @bankofai/x402-cli@1.0.1... +✓ Installed x402 CLI 1.0.1 +``` + +This runs `npm install --global @bankofai/x402-cli@1.0.1`, so — like the AgentWallet CLI — it lands in your global npm directory rather than in an OpenClaw folder. + +After skills are installed, the installer compares the skill list before and after and runs a configuration phase for each skill it considers new: + +:::caution Only on a first install +"New" means not present in the skill list before this run. That list covers `~/.openclaw/skills/`, the shared `~/.agents/skills/` folder and the skill folders of any other agent on the machine, so where these skills are already in one of them (for example from an earlier install) the installer prints `No new skills were installed.` after the x402 CLI step (an already-installed CLI shows `✓ x402 CLI 1.0.1 is already installed`), skips the prompts below, and the final summary shows only the MCP config file. In that case create the API key file by hand — see [How to Add API Keys](#️-how-to-add-api-keys-vip-pass-after-installation) — and set `TRONSCAN_API_KEY` yourself if you want it. +::: #### recharge-skill API Key Configuration @@ -366,9 +421,13 @@ Recharge requests use the remote BANK OF AI recharge MCP endpoint. ? Enter BANKOFAI_API_KEY (optional, hidden): ``` +:::caution Recharging through recharge-skill no longer works +The remote recharge MCP endpoint that recharge-skill uses for recharges has been taken offline, so recharge requests through this skill fail. To top up, use [`wallet-cli bai recharge`](../wallet-cli/command-reference.md#bai-recharge). +::: + **Don't have one? Just press Enter to skip.** You can always create the config file later — see "[How to Add API Keys](#️-how-to-add-api-keys-vip-pass-after-installation)" below. -When `Installation Complete!` lights up at the bottom of the screen — congratulations, you've passed all levels! +When `Installation Complete!` lights up at the bottom of the screen — congratulations, you've passed all levels! The `Installed skills` list and `Next steps` below appear only when the installer detected new skills; otherwise the summary goes straight from the config-file lines to the closing `Repository:` / `Skills:` links. ``` ═══════════════════════════════════════ @@ -382,13 +441,17 @@ When `Installation Complete!` lights up at the bottom of the screen — congratu ✓ Installed skills: • agent-wallet • bankofai-guide + • Multi-Sig & Account Permissions • recharge-skill • SunPerp Perpetual Futures Trading • SunPump Meme Token Toolkit • SunSwap DEX Trading + • TRC20 Token Toolkit • TronScan Data Lookup + • TRX Staking & SR Voting + • twitter-digest + • twitter-mcp • USDD / JUST Protocol - • wallet-cli • x402-payment Verify with: npx skills list -g @@ -439,7 +502,7 @@ Totally get it! You were just browsing during installation and pressed Enter to | Key Name | What's It For? | Where to Get It for Free? | | :--- | :--- | :--- | | `TRONGRID_API_KEY` | Express lane for the TRON toolbox — without it you'll be throttled | Register for free at [trongrid.io](https://www.trongrid.io/) | -| `TRONSCAN_API_KEY` | Required for the TronScan data lookup skill | Apply for free at [tronscan.org](https://tronscan.org/#/myaccount/apiKeys) | +| `TRONSCAN_API_KEY` | Optional for the TronScan Data Lookup skill — without it the skill goes through the BofAI proxy `ts.bankofai.io`; your own key gives higher rate limits | Apply for free at [tronscan.org](https://tronscan.org/#/myaccount/apiKeys) | | `BANKOFAI_API_KEY` | Used for topping up or checking balance on BANK OF AI | Get it after logging in at [chat.bankofai.io/key](https://chat.bankofai.io/key) | @@ -490,7 +553,8 @@ If you have this key, simply copy and run the following command in the terminal ```bash -mkdir -p ~/.mcporter && echo '{"api_key": "paste_your_BANKOFAI_API_KEY_here", "base_url": "https://chat.bankofai.io/"}' > ~/.mcporter/bankofai-config.json +mkdir -p ~/.mcporter && echo '{"api_key": "paste_your_BANKOFAI_API_KEY_here", "base_url": "https://chat.ainft.com"}' > ~/.mcporter/bankofai-config.json +chmod 600 ~/.mcporter/bankofai-config.json # the installer does this too; the file holds your API key ``` @@ -498,7 +562,7 @@ mkdir -p ~/.mcporter && echo '{"api_key": "paste_your_BANKOFAI_API_KEY_here", "b ```powershell New-Item -ItemType Directory -Force -Path "$env:USERPROFILE\.mcporter" | Out-Null -'{"api_key": "paste_your_BANKOFAI_API_KEY_here", "base_url": "https://chat.bankofai.io/"}' | Out-File -Encoding utf8 "$env:USERPROFILE\.mcporter\bankofai-config.json" +'{"api_key": "paste_your_BANKOFAI_API_KEY_here", "base_url": "https://chat.ainft.com"}' | Out-File -Encoding utf8 "$env:USERPROFILE\.mcporter\bankofai-config.json" ``` @@ -518,7 +582,7 @@ After installation, the following files are created on your machine. All sensiti | `~/.mcporter/mcporter.json` | MCP server configurations (including BNB Chain private key if provided) | | `~/.mcporter/bankofai-config.json` | BANK OF AI API key | | `~/.openclaw/skills/` | Globally installed skill packs | -| `.openclaw/skills/` | Workspace-level skill packs (if you chose option 2) | +| `skills/` (in the directory you ran the installer from) | Workspace-level skill packs (if you chose option 2, then `Project`) | | `~/.agent-wallet/` | AgentWallet encrypted wallet data | @@ -529,7 +593,7 @@ After installation, the following files are created on your machine. All sensiti | `%USERPROFILE%\.mcporter\mcporter.json` | MCP server configurations (including BNB Chain private key if provided) | | `%USERPROFILE%\.mcporter\bankofai-config.json` | BANK OF AI API key | | `%USERPROFILE%\.openclaw\skills\` | Globally installed skill packs | -| `.openclaw\skills\` | Workspace-level skill packs (if you chose option 2) | +| `skills\` (in the directory you ran the installer from) | Workspace-level skill packs (if you chose option 2, then `Project`) | | `%USERPROFILE%\.agent-wallet\` | AgentWallet encrypted wallet data | diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs-changelog/current/mcp-server.md b/i18n/zh-Hans/docusaurus-plugin-content-docs-changelog/current/mcp-server.md index 18d0e46c..da1a39ad 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs-changelog/current/mcp-server.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs-changelog/current/mcp-server.md @@ -7,6 +7,40 @@ description: 'MCP Server 的版本发布记录。' MCP Server 的版本发布记录。 +
+
2026-10-27
+
+ +### 包内容、Docker 模式与 HTTP 细节 + +
文档修复
+ +- npm 包包含 `build/`、`bin/`、`package.json`、`README.md` 与 `LICENSE`;Docker 镜像始终以只读模式运行(`--readonly` 写死);`/mcp` 的 `GET` / `DELETE` 返回 405、不支持 SSE;`GET /` 返回服务信息;`tron` / `trx` / `testnet` 是可用的网络别名。 + +👉 [本地部署](/zh-Hans/McpServer-Skills/MCP/TRONMCPServer/LocalPrivatizedDeployment/) · [工具列表](/zh-Hans/McpServer-Skills/MCP/TRONMCPServer/ToolList/) + +
+
+ +
+
2026-10-23
+
+ +### TRON MCP Server 文档按代码更正 + +
文档修复
+ +- **未配置 API Key 时的 RPC**——`main`(tag `v1.1.8`)中,未设置 `TRONGRID_API_KEY` 时主网请求走 `https://hptg.bankofai.io`,设置后走 `api.trongrid.io`。Nile 与 Shasta 始终使用 TronGrid 测试网节点。npm 上的 `1.1.7` 在未配置 Key 时仍使用 `api.trongrid.io`。 +- **工具与提示词**——`write_contract` 没有 `feeLimit` 参数(只有 `deploy_contract` 有);`tron://networks` 返回 `{"supportedNetworks":[...]}`;只读模式下注册 4 个提示词,而非 6 个。 +- **钱包报错**——常见问题改为引用 agent-wallet 2.x 的真实报错文本(`resolve_wallet could not find a wallet source in config or env`、`Password required for local_secure wallets`、`No active wallet set.`、`MAC mismatch — wrong password or corrupted file`)。agent-wallet 2.3.x 和 2.4.0 都接受别名 `TRON_PRIVATE_KEY` 和 `TRON_MNEMONIC`,但只有在解析不到密码且钱包目录里没有钱包时才会读取这些环境变量,否则会静默忽略。在这条路径上同时设置了私钥和助记词时,agent-wallet 2.3.x 报 `Wallet not configured.`,2.4.0 报 `Provide only one of AGENT_WALLET_PRIVATE_KEY or AGENT_WALLET_MNEMONIC`。 +- **Node.js**——源码检出的 `v1.1.8` 要求 22.23.4+(22.x)或 24.22.1+(24.x);`npx` 运行的 npm `1.1.7` 声明的是 `>=20`。无论哪种方式,页面都推荐 2026 年 10 月的安全更新版本。云服务快速开始页把硬性要求「Node.js v20.0.0 或更高版本」改为「需要 Node.js 以执行 `npx`」,并推荐 22.23.4+ 或 24.22.1+。 +- **Agent Wallet 安装固定到 2.x**——服务端依赖 `@bankofai/agent-wallet ^2.3.0`,但不带版本号的 `npm install -g @bankofai/agent-wallet` 现在会装上 3.0.0,它没有 `local_secure` 钱包、主密码和 `--save-runtime-secrets`。页面现改用 `npm install -g @bankofai/agent-wallet@2`,并注明 Agent-Wallet 文档描述的是 3.x。 + +👉 [快速开始](/zh-Hans/McpServer-Skills/MCP/TRONMCPServer/QuickStart/) · [常见问题与排查](/zh-Hans/McpServer-Skills/MCP/TRONMCPServer/FAQ/) · [本地私有化部署](/zh-Hans/McpServer-Skills/MCP/TRONMCPServer/LocalPrivatizedDeployment/) + +
+
+
2026-09-09
diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs-changelog/current/openclaw-extension.md b/i18n/zh-Hans/docusaurus-plugin-content-docs-changelog/current/openclaw-extension.md index 37e1cb01..9abe6823 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs-changelog/current/openclaw-extension.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs-changelog/current/openclaw-extension.md @@ -7,6 +7,39 @@ description: 'Openclaw 扩展的版本发布记录。' Openclaw 扩展的版本发布记录。 +
+
2026-10-27
+
+ +### 安装器细节更正 + +
文档修复
+ +- 技能配置环节(API Key 提示、`Next steps`)只对运行前技能列表里没有的技能运行(默认的全局安装下,列表涵盖 `~/.openclaw/skills/`、`~/.agents/skills/` 和其他 Agent 的技能目录),因此重装会打印 `No new skills were installed.` 并跳过;快速开始已说明这一点并指向手动补填 API Key 的步骤。补充了 `Proceed with installation?` 提示和 `bankofai-recharge` 的远程地址。 +- Node.js 报错文字改为安装器实际输出(Windows 上没有 `Error: ` 前缀);手动创建 `bankofai-config.json` 的步骤和安装器一样加上 `chmod 600`;Windows 改为「基本一样,差异见 FAQ」;删除 `~/.openclaw/skills/` 只会移除技能——MCP 条目、API Key 文件、全局 npm 包和 `~/.agent-wallet` 仍保留;Clean 模式会清掉 MCP 条目、技能和配置文件并重新初始化 agent-wallet,但从不卸载 npm 包。 + +👉 [快速开始](/zh-Hans/Openclaw-extension/QuickStart/) · [常见问题](/zh-Hans/Openclaw-extension/FAQ/) + +
+
+ +
+
2026-10-23
+
+ +### 文档按当前安装器更正 + +
文档修复
+ +- **更正 9 月 9 日的条目**——那条所述的安装器改动并未发布。`main` 上的安装器仍锁定 Skills `v1.5.15`(14 个 Skill,不含 `wallet-cli`)、`@bankofai/agent-wallet` 2.3.1 与 `@bankofai/mcp-server-tron` 1.1.7,并写入 `base_url: https://chat.ainft.com`。快速入门与常见问题现按这一安装器描述,页首也说明了其钱包步骤遵循 agent-wallet 2.x。 +- **文档的其他更正**——选择 `x402-payment` 时还会执行 `npm install --global @bankofai/x402-cli@1.0.1`;TronScan API Key 为可选(不填时 Skill 走 `ts.bankofai.io`);项目级安装位置为 `/skills/`;安装过程没有 TronGrid 提示;已有钱包时 agent-wallet 2.3.1 会先询问新增还是退出;Windows 上缺少 `~/.openclaw` 时安装器直接退出。 +- **Node.js**——两个安装器都会在安装任何内容之前,按 `^22.23.4 || ^24.22.1 || >=26.12.1` 检查完整版本号。 + +👉 [快速开始](/zh-Hans/Openclaw-extension/QuickStart/) · [常见问题](/zh-Hans/Openclaw-extension/FAQ/) + +
+
+
2026-09-09
diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/BSCMCPServer/Features.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/BSCMCPServer/Features.md index b33b8bd3..d78ba9e8 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/BSCMCPServer/Features.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/BSCMCPServer/Features.md @@ -18,3 +18,5 @@ **公共组件**:共享工具程序和类型 **Greenfield**:支持 Greenfield 网络上的文件管理操作,包括文件的上传、下载,以及文件和存储桶 (buckets) 的管理 + +**Agents(ERC-8004)**:在 ERC-8004 身份注册表上注册和查询链上 AI Agent 身份(`register_erc8004_agent`、`set_erc8004_agent_uri`、`get_erc8004_agent`、`get_erc8004_agent_wallet`) diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/BSCMCPServer/Installation.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/BSCMCPServer/Installation.md index 1f855cc0..1be43f26 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/BSCMCPServer/Installation.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/BSCMCPServer/Installation.md @@ -3,7 +3,7 @@ ### 前置要求 * **bun** v1.2.10 或更高版本 -* **Node.js** v18 或更高版本(该项目自身的下限是 v17,但 BANK OF AI 工具链的其余部分要求 18+,TRON MCP 服务更要求 20+) +* **Node.js** v17 或更高版本(上游 README 的要求;`package.json` 未声明 `engines`,项目的发布流程使用 Node.js 20) ### 快速开始 @@ -22,6 +22,7 @@ * `PRIVATE_KEY`:你的钱包私钥(执行交易操作时必填) * `LOG_LEVEL`:设置日志级别(`DEBUG`, `INFO`, `WARN`, `ERROR`) * `PORT`:服务器端口号(默认:`3001` —— TRON MCP 服务的默认端口同样是 3001,本地同时运行两者时需要改掉其中一个) + * `BNBCHAIN_MCP_SKIP_TRANSFER_CONFIRMATION`(可选,默认 `false`):默认情况下,转账和支付类工具只返回预览和 `confirmToken`(5 分钟内有效),不会发送交易;需再用该 token 调用 `confirm_transfer` 才会执行。设为 `true` 则立即执行 4. **安装依赖并启动开发服务器:** ```bash @@ -50,8 +51,10 @@ } ``` +> 该模板沿用上游 README。使用 `url` 配置时,客户端连接的是已在运行的服务,`env` 块不会传给服务进程:服务从自己的 `.env` 读取 `PRIVATE_KEY`。 + ### 使用 Web UI 测试 -使用 @modelcontextprotocol/inspector 进行测试。运行以下命令启动测试 UI: +使用 @modelcontextprotocol/inspector 进行测试。运行以下命令启动测试 UI(该脚本通过 `npx` 运行最新版 inspector,目前要求 Node.js 22.19 及以上): ```bash bun run test diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/FAQ.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/FAQ.md index b64c562b..ceadf408 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/FAQ.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/FAQ.md @@ -12,11 +12,15 @@ 这是最常见的问题。按以下顺序逐一排查: -1. **检查 Node.js 版本**。TRON MCP Server 需要 v20.0.0 或更高版本: +1. **检查 Node.js 版本**。声明的版本要求取决于你运行服务端的方式: + - **`npx -y @bankofai/mcp-server-tron`** 运行的是 npm 包 `1.1.7`,它声明的是 Node.js `>=20`。 + - **源码检出**的 `main`(tag `v1.1.8`)要求 22.23.4+(22.x)或 24.22.1+(24.x)。其 `package.json` 里的版本号仍是 `1.1.7`,因此服务端上报的版本也是 `1.1.7`。 + + 无论哪种方式,都推荐使用 2026 年 10 月的安全更新版本 22.23.4+ 或 24.22.1+: ```bash - node --version # 应输出 v20.x.x 或更高 + node --version # 推荐:v22.23.4+ 或 v24.22.1+ ``` - 如果版本太低,请先升级 Node.js。 + 如果版本低于你所用方式声明的要求,请先升级 Node.js。 2. **检查 npx 是否可用**。在终端运行 `npx --version`。如果找不到命令,说明 Node.js 安装不完整,需要重新安装。 @@ -47,15 +51,22 @@ 3. **防火墙拦截**。如果你从另一台机器访问本地 HTTP 服务,检查防火墙是否允许该端口的入站连接。 -### 写入工具出现但返回"钱包未配置"错误 +### 写入工具出现但返回钱包错误 {#write-tools-wallet-error} + +从 v1.1.7 起,写入工具(转账、质押等)始终出现在 AI 的工具列表中,但会在执行时检查钱包是否已配置。如果没有可用钱包就调用写入工具,会返回类似 `Error transferring TRX: <原因>` 的错误,其中 `<原因>` 来自 Agent Wallet——各条错误的含义见下方[钱包错误信息](#wallet-error-messages)。 -从 v1.1.7 起,写入工具(转账、质押等)始终出现在 AI 的工具列表中,但会在执行时检查钱包是否已配置。如果没有配置钱包就调用写入工具,会返回错误提示你设置钱包。 +要启用写入操作,请配置本服务端所依赖的 Agent Wallet **2.x**: -要启用写入操作,请配置 [Agent Wallet](../../../Agent-Wallet/Intro.md): +```bash +npm install -g @bankofai/agent-wallet@2 +agent-wallet start local_secure --save-runtime-secrets +``` -- 设置 `AGENT_WALLET_PASSWORD` 环境变量为你的主密码 +- `--save-runtime-secrets` 会把主密码写入 `~/.agent-wallet/runtime_secrets.json`;也可以改为把 `AGENT_WALLET_PASSWORD` 环境变量设为主密码 - 可选设置 `AGENT_WALLET_DIR`(如使用自定义钱包目录) +[Agent-Wallet 文档](../../../Agent-Wallet/Intro.md)描述的是 Agent Wallet 3.x,本服务端尚未使用该版本——请使用上面的 2.x 命令。 + 配置完成后重启 AI 客户端即可。详细说明请参阅[本地私有化部署](./LocalPrivatizedDeployment.md)。 :::info @@ -66,22 +77,36 @@ ## 认证与密钥问题 -### "钱包未配置"错误 +### 钱包错误信息 {#wallet-error-messages} + +TRON MCP Server 使用 [Agent Wallet](../../../Agent-Wallet/Intro.md) 进行所有钱包管理。当写入工具(或 `get_wallet_address` / `sign_message`)拿不到钱包时,错误文本会告诉你属于哪种情况: -这表示尚未设置用于签名交易的钱包。TRON MCP Server 使用 [Agent Wallet](../../../Agent-Wallet/Intro.md) 进行所有钱包管理。解决方法: +| 错误文本 | 含义 | +| :--- | :--- | +| `resolve_wallet could not find a wallet source in config or env` | 完全没有钱包:解析不到密码,钱包目录中没有任何钱包,且 `AGENT_WALLET_PRIVATE_KEY`、`TRON_PRIVATE_KEY`、`AGENT_WALLET_MNEMONIC`、`TRON_MNEMONIC` 都未设置。 | +| `Password required for local_secure wallets` | 钱包目录中有钱包,但没有解析到密码——既没有 `runtime_secrets.json`,也没有 `AGENT_WALLET_PASSWORD`。 | +| `No active wallet set.` | 解析到了密码,但钱包目录中没有任何钱包。此时私钥和助记词环境变量都会被忽略——请用 Agent Wallet 创建或导入钱包,或去掉密码以走环境变量私钥路径。 | +| `MAC mismatch — wrong password or corrupted file` | 找到了密码,但与 keystore 不匹配(见下一节)。 | +| `Wallet not configured.` | Agent Wallet 连配置都无法加载——例如 `runtime_secrets.json` 或 `wallets_config.json` 格式错误。使用 agent-wallet 2.3.x(源码检出按 `package-lock.json` 安装的版本)时,在走到环境变量路径时(见表格下方说明)同时设置了私钥和助记词,也会得到这条错误。 | +| `Provide only one of AGENT_WALLET_PRIVATE_KEY or AGENT_WALLET_MNEMONIC` | 使用 agent-wallet 2.4.0(`npx -y @bankofai/mcp-server-tron`,即 npm `1.1.7`、依赖 `^2.3.0`,当前安装的版本)时,走到了环境变量路径,且同时设置了私钥(`AGENT_WALLET_PRIVATE_KEY` 或 `TRON_PRIVATE_KEY`)和助记词(`AGENT_WALLET_MNEMONIC` 或 `TRON_MNEMONIC`)。服务端会原样透传这段文本,例如 `Error transferring TRX: Provide only one of …`,或 `get_wallet_address` 返回的 `Error: Provide only one of …`。去掉其中一个即可。 | -1. **安装并初始化 Agent Wallet**,参阅 [Agent-Wallet 文档](../../../Agent-Wallet/Intro.md)。 -2. **设置环境变量**: +两个 agent-wallet 版本都从 `AGENT_WALLET_PRIVATE_KEY` 或其别名 `TRON_PRIVATE_KEY` 读取私钥,从 `AGENT_WALLET_MNEMONIC` 或其别名 `TRON_MNEMONIC` 读取助记词。只有走到环境变量路径——解析不到任何密码**且**钱包目录里一个钱包都没有——时才会读取这些变量;否则它们会被静默忽略,上面两种「同时设置」引起的错误也都不会出现。 + +前两种情况的解决方法: + +1. **还没有钱包:安装并初始化 Agent Wallet 2.x**:执行 `npm install -g @bankofai/agent-wallet@2`,再执行 `agent-wallet start local_secure --save-runtime-secrets`,同时把主密码保存到 `runtime_secrets.json`。([Agent-Wallet 文档](../../../Agent-Wallet/Intro.md)描述的是 3.x,本服务端尚未使用该版本。) +2. **已经有钱包:让服务端能拿到密码**——导出环境变量: ```bash export AGENT_WALLET_PASSWORD='<你的主密码>' ``` -3. **重启 AI 客户端**使配置生效。 + 或按[本地私有化部署](./LocalPrivatizedDeployment.md)(路径 1)的方法保存到 `runtime_secrets.json`。重新执行 `agent-wallet start` 没有用:已有钱包时它只提供 `add`(创建一个新钱包并把它设为当前钱包)和 `exit`(不保存任何内容)两个选项。 +3. **重启 AI 客户端**使配置生效。服务端只解析一次钱包来源并缓存,修改钱包设置后必须重启。 -### "Agent Wallet 密码错误" +### "MAC mismatch — wrong password or corrupted file" 错误 -`AGENT_WALLET_PASSWORD` 必须与运行 `agent-wallet start` 时生成的主密码完全一致。请确认钱包目录存在(`ls ~/.agent-wallet/`),如果使用了自定义目录,确保 `AGENT_WALLET_DIR` 指向正确路径。 +服务端解析到的密码(来自 `runtime_secrets.json` 或 `AGENT_WALLET_PASSWORD`)必须与运行 `agent-wallet start` 时设置的主密码完全一致。请确认钱包目录存在(`ls ~/.agent-wallet/`),如果使用了自定义目录,确保 `AGENT_WALLET_DIR` 指向正确路径。 -如果密码丢失,需要重新初始化钱包。**警告:此操作会清除所有钱包和密钥——请务必提前转移资金或备份助记词。** 运行 `agent-wallet reset` 清除并重新开始——详见 [CLI 命令行手册 → 重置](../../../Agent-Wallet/Developer/CLI-Reference.md#agent-wallet-reset重置所有数据)和 [Agent-Wallet 常见问题](../../../Agent-Wallet/FAQ.md)。 +如果密码丢失,需要重新初始化钱包。**警告:此操作会清除所有钱包和密钥——请务必提前转移资金或备份助记词。** 运行 `agent-wallet reset` 清除并重新开始。在 agent-wallet 2.x(本服务使用的版本)中,`reset` 会删除 `~/.agent-wallet` 里的所有文件——`master.json`、`wallets_config.json`、`runtime_secrets.json` 以及 `secret_*.json` 密钥库。Agent-Wallet 文档描述的是 3.x,其 `reset` 只删除 `wallets_config.json`。 ### TronGrid API Key 不生效 @@ -115,7 +140,7 @@ **怎么解决:** - 先预估费用:"预估调用这个合约的 transfer 函数需要多少能量" - 质押 TRX 换取能量:"质押 500 TRX 获取能量" -- 如果使用 `write_contract`,可以让 AI 提高 `feeLimit` 参数 +- `write_contract` 没有手续费上限参数,请确保钱包有足够 TRX 燃烧以补足能量缺口。只有 `deploy_contract` 接受 `feeLimit`(单位 Sun,默认 1,000,000,000 = 1000 TRX),部署大合约时可以让 AI 调高它 ### "账户不存在"或"账户未激活" @@ -158,7 +183,7 @@ AI 可能将 TRON MCP Server 的能力与其他区块链工具混淆。如果它 几种常见原因和对策: -- **没有 TronGrid API Key**:公共 RPC 有频率限制,添加免费的 API Key 可以显著改善 +- **没有 TronGrid API Key**:未设置 `TRONGRID_API_KEY` 时,`v1.1.8` 起的源码检出中主网请求走 BANK OF AI 回退节点 `https://hptg.bankofai.io`,npm `1.1.7`(`npx` 运行的版本)则不带 Key 访问 `https://api.trongrid.io`。配置免费的 API Key 后,两个版本都会以你自己的配额访问 `https://api.trongrid.io` - **复杂的多工具工作流**:某些操作(如钱包全貌分析)需要多个串行调用,等待是正常的 - **使用测试网开发**:Nile 和 Shasta 测试网通常响应更快 - **提示词更明确**:减少 AI 的探索性调用——直接告诉它用哪个工具、查哪个网络 @@ -183,7 +208,13 @@ AI 可能将 TRON MCP Server 的能力与其他区块链工具混淆。如果它 ### 如何更新到最新版本? -如果你使用的是 `npx` 方式运行,每次都会自动获取最新发布版本。若要强制刷新缓存: +如果你使用的是 `npx` 方式运行,`npx -y @bankofai/mcp-server-tron` 并不一定会拉取最新版本:它可能直接运行已安装的副本——全局安装的、当前项目里的,或者在较旧的 npm 版本上 npx 缓存里的。要始终获取最新发布版本,请显式指定,例如在 MCP 客户端配置中使用: + +```bash +npx -y @bankofai/mcp-server-tron@latest +``` + +也可以清除 npx 缓存:删除 `~/.npm/_npx`(必要时再执行 `npm cache clean --force`)。第三方包 `clear-npx-cache` 的作用相同: ```bash npx clear-npx-cache @@ -200,6 +231,6 @@ npm run build ### 支持哪个 MCP 协议版本? -TRON MCP Server 支持 MCP 协议版本 **2025-11-25**,使用 `@modelcontextprotocol/sdk` 1.22.0 或更高版本。 +协议版本由 `@modelcontextprotocol/sdk` 协商决定,服务端对它的依赖是 `^1.22.0`;源码检出的 `package-lock.json` 锁定为 1.27.1。MCP 协议版本 **2025-11-25** 需要 SDK 1.24.1 或更高版本——SDK 1.22.0–1.24.0 最高只支持 2025-06-18。客户端请求的更早协议版本同样可以使用。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/Intro.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/Intro.md index 8ec6b500..f23d69aa 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/Intro.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/Intro.md @@ -17,7 +17,7 @@ TRON MCP Server 是连接 AI 助手与 TRON 区块链的桥梁。它基于 [Mode ## 它能做什么? -TRON MCP Server 覆盖了 TRON 区块链上几乎所有常见操作,从只读查询到资产管理,共提供 **97 个工具**、**6 个提示词模板**和 **1 个资源定义**。 +TRON MCP Server 覆盖了 TRON 区块链上几乎所有常见操作,从只读查询到资产管理,共提供 **97 个工具**、**6 个提示词模板**和 **1 个资源定义**。在只读模式(官方云服务或 `--readonly`)下,写入工具和 2 个写入类提示词模板不会被注册,只剩 68 个读取工具和 4 个提示词模板。 以下是核心能力概览——每一项都可以通过自然语言触发: diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/LocalPrivatizedDeployment.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/LocalPrivatizedDeployment.md index 72e6dace..ee3a696a 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/LocalPrivatizedDeployment.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/LocalPrivatizedDeployment.md @@ -29,15 +29,17 @@ | 要求 | 说明 | | :--- | :--- | -| **Node.js** | v20.0.0 或更高版本([下载](https://nodejs.org/)) | +| **Node.js** | 推荐 22.23.4+(22.x)或 24.22.1+(24.x),即 2026 年 10 月的安全更新版本([下载](https://nodejs.org/))。源码检出的 `main`(tag `v1.1.8`,即下文方式 B)要求这一范围(其 `package.json` 里的版本号仍是 `1.1.7`,因此服务端上报的版本也是 `1.1.7`);`npx` 运行的 npm 包 `1.1.7`(方式 A)声明的是 `>=20`。 | | **TronGrid API Key** | 可选但推荐([申请地址](https://www.trongrid.io/)) | 验证 Node.js 版本: ```bash -node --version # 应输出 v20.x.x 或更高 +node --version # 推荐:v22.23.4+ 或 v24.22.1+ ``` +这一要求写在 `package.json` 的 `engines` 字段里:在源码检出中用其他 Node.js 版本执行 `npm install`,会打印 `EBADENGINE` 警告但仍会完成安装;服务端运行时也不会检查 Node.js 版本。 + ### 安全原则 在配置钱包之前,请务必理解以下安全原则: @@ -50,7 +52,7 @@ node --version # 应输出 v20.x.x 或更高 ## 安装步骤 ### 第一步:配置钱包 -钱包决定了 AI 助手以哪个身份执行链上操作。TRON MCP Server 使用 [Agent Wallet](../../../Agent-Wallet/Intro.md) 进行安全的钱包管理。如果没有配置钱包,写入工具会在执行时返回错误提示你设置钱包。 +钱包决定了 AI 助手以哪个身份执行链上操作。TRON MCP Server 使用 [Agent Wallet](../../../Agent-Wallet/Intro.md) 进行安全的钱包管理。如果没有配置钱包,调用写入工具时会返回钱包错误(见[常见问题](./FAQ.md#write-tools-wallet-error))。 #### Agent Wallet @@ -63,34 +65,38 @@ TRON MCP Server 使用 [Agent Wallet](../../../Agent-Wallet/Intro.md) 管理钱 | 运行时切换钱包 | 是 | | 推荐场景 | 所有使用场景 | -> Agent Wallet 的安装、初始化及详细用法请参阅 [Agent-Wallet 文档](../../../Agent-Wallet/Intro.md)。 +> TRON MCP Server 依赖 Agent Wallet **2.x**(`@bankofai/agent-wallet ^2.3.0`)。[Agent-Wallet 文档](../../../Agent-Wallet/Intro.md)描述的是 3.x,本服务端尚未使用该版本——请按本页的 2.x 命令操作。 -首先,安装 Agent Wallet: +首先,安装 Agent Wallet 2.x CLI: ```bash -npm install -g @bankofai/agent-wallet +npm install -g @bankofai/agent-wallet@2 ``` +`@2` 会安装最新的 2.x 版本(撰写时为 2.4.0)。不加版本号时 npm 会安装 3.x,它没有 `local_secure` 钱包、主密码和 `--save-runtime-secrets`,下面的步骤将无法使用。 + 然后,根据你的情况选择以下两种路径之一: #### 路径 1:生成新钱包(推荐新用户使用) -如果你没有现成的私钥,使用 `agent-wallet start` 生成新钱包,包含加密密钥库和主密码: +如果你没有现成的私钥,使用 `agent-wallet start local_secure` 生成新钱包,包含加密密钥库和主密码: ```bash -agent-wallet start +agent-wallet start local_secure --save-runtime-secrets ``` -按照交互式提示设置主密码并生成钱包。Agent Wallet 会自动管理加密密钥库,但服务端在签名时仍然需要这个密码——而直接跑 `agent-wallet start` 并不会持久化它。请二选一: +按照交互式提示设置主密码并生成钱包。Agent Wallet 会自动管理加密密钥库,但服务端在签名时仍然需要这个密码。`--save-runtime-secrets` 会把它写入 `~/.agent-wallet/runtime_secrets.json`;不加这个参数时密码不会被持久化,你需要改为在 MCP 服务端运行的环境里 export `AGENT_WALLET_PASSWORD`。 + +如果你已经不带这个参数执行过 `agent-wallet start`,不要为此重新执行它:已有钱包时它只提供 `add`(创建一个新钱包并把它设为当前钱包)和 `exit`(不保存任何内容)两个选项。请 export `AGENT_WALLET_PASSWORD`,或用下面任一命令保存密码: -- 执行 `agent-wallet start --save-runtime-secrets`,把密码写入 `~/.agent-wallet/runtime_secrets.json`;或 -- 在 MCP 服务端运行的环境里 export `AGENT_WALLET_PASSWORD`。 +- `agent-wallet sign msg hello -n tron --save-runtime-secrets`——询问密码并保存,然后用当前钱包签一条测试消息。它在校验密码之前就会保存,所以如果输出 `Wrong password`,请删除 `~/.agent-wallet/runtime_secrets.json` 后重试。 +- `agent-wallet add local_secure --save-runtime-secrets`——先校验密码再保存,但同时会多创建一个钱包(当前钱包不变)。 -两者都没有时,调用写操作工具会因为无法解锁 `local_secure` 钱包而失败。密钥库不在 `~/.agent-wallet` 时请用 `AGENT_WALLET_DIR` 指定。 +既没有保存也没有导出密码时,调用写操作工具会因为无法解锁 `local_secure` 钱包而失败。密钥库不在 `~/.agent-wallet` 时请用 `AGENT_WALLET_DIR` 指定。 #### 路径 2:导入已有私钥 -如果你已经有想使用的私钥,通过 `AGENT_WALLET_PRIVATE_KEY` 环境变量设置。注意优先级:只有在**解析不到任何密码**(既没有 `runtime_secrets.json`,也没有 `AGENT_WALLET_PASSWORD`)**且**钱包目录里一个钱包都没有时,才会走到这条环境变量路径。如果你已经执行过「路径 1」、保存过运行时密码,或跑过 Openclaw 安装器,密钥库路径会优先生效,该变量会被静默忽略。 +如果你已经有想使用的私钥,通过 `AGENT_WALLET_PRIVATE_KEY` 环境变量设置(Agent Wallet 也接受别名 `TRON_PRIVATE_KEY`,以及通过 `AGENT_WALLET_MNEMONIC` 或 `TRON_MNEMONIC` 设置助记词)。注意优先级:只有在**解析不到任何密码**(既没有 `runtime_secrets.json`,也没有 `AGENT_WALLET_PASSWORD`)**且**钱包目录里一个钱包都没有时,才会走到这条环境变量路径。如果你已经执行过「路径 1」、保存过运行时密码,或跑过 Openclaw 安装器,密钥库路径会优先生效,这些变量会被静默忽略。 ```bash export AGENT_WALLET_PRIVATE_KEY=你的私钥 @@ -120,14 +126,22 @@ echo $AGENT_WALLET_PRIVATE_KEY #### TronGrid API Key -TRON 主网公共 RPC 有严格的频率限制。对于频繁的链上查询,强烈建议配置一个免费的 TronGrid API Key: +在 `v1.1.8` 起的源码检出中,API Key 还决定了服务端访问哪个主网节点。对于频繁的链上查询,建议配置一个免费的 TronGrid API Key: ```bash # 添加到 ~/.zshrc 或 ~/.bashrc export TRONGRID_API_KEY="<你的-TronGrid-API-Key>" ``` -在 [trongrid.io](https://www.trongrid.io/) 免费注册即可获取。不配置也能使用,但高频操作时可能会遇到限速错误。测试网(Nile、Shasta)受限速影响较小。 +在 [trongrid.io](https://www.trongrid.io/) 免费注册即可获取。该变量对各网络的影响(各版本唯一的差别在于未配置 Key 时的主网): + +| 网络 | 已设置 `TRONGRID_API_KEY` | 未设置 `TRONGRID_API_KEY` | +| :--- | :--- | :--- | +| **Mainnet** | `https://api.trongrid.io`,并以 `TRON-PRO-API-KEY` 请求头携带你的 Key(使用你自己的配额) | `v1.1.8` 起的源码检出:回退到 BANK OF AI 节点 `https://hptg.bankofai.io`。npm `1.1.7`(`npx` 运行的版本):不带 Key 访问 `https://api.trongrid.io` | +| **Nile** | `https://nile.trongrid.io`(同样携带 Key 请求头) | `https://nile.trongrid.io` | +| **Shasta** | `https://api.shasta.trongrid.io`(同样携带 Key 请求头) | `https://api.shasta.trongrid.io` | + +不配置 Key 也能正常使用,但不带 Key 发往 TronGrid 的请求(npm `1.1.7` 的主网,以及 Nile / Shasta)共用 TronGrid 的公共限流,高频使用时可能遇到限流错误。如果希望主网请求走 TronGrid 并使用你自己的配额,再配置即可。 --- @@ -137,7 +151,7 @@ export TRONGRID_API_KEY="<你的-TronGrid-API-Key>" #### 方式 A:npx 直接运行(推荐) -无需克隆仓库,通过 `npx` 直接运行最新版本。这也是下方 MCP 客户端配置示例中默认采用的方式。 +无需克隆仓库,通过 `npx` 直接运行最新版本。这也是下文[配置说明](#配置说明)中使用的命令。 ```bash npx -y @bankofai/mcp-server-tron @@ -172,7 +186,7 @@ npx -y @bankofai/mcp-server-tron --http npm run start:http ``` -这会启动一个本地无状态 Streamable HTTP 服务器(默认:`http://localhost:3001/mcp`),每个请求独立处理,不维护会话状态。 +这会启动一个本地无状态 Streamable HTTP 服务器(默认:`http://localhost:3001/mcp`),对 `/mcp` 的 `GET` 和 `DELETE` 返回 `405`(不支持 SSE),`GET /` 返回服务信息。每个请求独立处理,不维护会话状态。 你可以通过环境变量自定义端口和主机: @@ -181,11 +195,11 @@ export MCP_PORT=3001 # 默认:3001 export MCP_HOST=0.0.0.0 # 默认:0.0.0.0 ``` -Docker 与源码检出的启动脚本还会读取 `MCP_LOG_DIR`(容器内默认 `/app/logs`,源码检出默认 `./logs`)。已发布的 npm 包只包含 `build/` 与 `bin/`,因此该变量不适用于上面的 `npx` 方式。 +Docker 与源码检出的启动脚本还会读取 `MCP_LOG_DIR`(容器内默认 `/app/logs`,源码检出默认 `./logs`)。已发布的 npm 包只包含 `build/`、`bin/`、`package.json`、`README.md` 与 `LICENSE`,因此该变量不适用于上面的 `npx` 方式。 #### 方式 D:Docker 部署 -在 Docker 容器中运行 TRON MCP Server,适合隔离、可重现的环境。Docker 镜像默认以**只读 HTTP 模式**运行。 +在 Docker 容器中运行 TRON MCP Server,适合隔离、可重现的环境。Docker 镜像始终以**只读 HTTP 模式**运行:`docker-start.sh` 固定传入 `--readonly`,没有关闭它的开关。 ```bash # 1. 创建 .env 文件存放敏感变量(切勿将此文件提交到版本控制) diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/OfficialServerAccess.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/OfficialServerAccess.md index 335d85ec..ab971335 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/OfficialServerAccess.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/OfficialServerAccess.md @@ -85,7 +85,7 @@ AI 给出 ✅ 确认后,TRON MCP Server 就已就位,可以直接开始提 npx add-mcp https://tron-mcp-server.bankofai.io/mcp -y ``` -`-y` 参数会跳过所有交互选择,自动安装到你电脑上检测到的所有 AI 工具中。安装完成后会显示 ✅ 安装完成!以及安装到了哪些 Agent。 +`-y` 参数会跳过所有交互选择。add-mcp 随后在当前目录写入项目级配置:写给它在当前目录检测到的 AI 工具(依据 `.claude`、`.cursor`、`.vscode`、`.mcp.json` 等标志性文件夹和文件);一个都没检测到时,则写给所有支持项目配置的工具。完成后会打印 `Installation complete` 以及安装到了哪些 Agent。 安装完成后,即可使用 TRON MCP Server 开始与 TRON 区块链交互。 @@ -117,7 +117,7 @@ npx add-mcp https://tron-mcp-server.bankofai.io/mcp **2️⃣ 选择要安装到哪些 AI 工具** -安装器会自动检测你电脑上装了哪些 AI 工具(如 Claude Code、Cursor、Cline 等),用空格键勾选你要用的: +安装器会根据当前目录里的标志性文件夹和文件(如 `.claude`、`.cursor`、`.vscode`、`.mcp.json`)检测 AI 工具,例如 Claude Code、Cursor。用空格键勾选你要用的: ``` ◇ Detected 1 agent @@ -128,7 +128,7 @@ npx add-mcp https://tron-mcp-server.bankofai.io/mcp **3️⃣ 确认安装信息** -安装器会展示安装摘要,确认无误后选择 `Yes` 开始安装: +如果勾选的工具都同时支持项目级和全局配置,安装器会先问 **Installation scope**(`Project` / `Global`),下面的摘要对应 `Project`。随后安装器会展示安装摘要,确认无误后选择 `Yes` 开始安装: ``` ◇ Installation Summary ────╮ @@ -151,11 +151,11 @@ npx add-mcp https://tron-mcp-server.bankofai.io/mcp ``` ◇ Installation complete │ -◇ Installed to 1 agent ───────╮ -│ │ -│ ✓ Claude Code: ~/.mcp.json │ -│ │ -├──────────────────────────────╯ +◇ Installed to 1 agent ──────────────────╮ +│ │ +│ ✓ Claude Code: ~/my-project/.mcp.json │ +│ │ +├─────────────────────────────────────────╯ │ └ Done! ``` diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/QuickStart.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/QuickStart.md index b4c52239..c6595e71 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/QuickStart.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/QuickStart.md @@ -2,7 +2,7 @@ 这个页面的目标很简单:**让你在 1 分钟内完成接入,发起第一次区块链查询。** -我们会使用[官方云服务](./OfficialServerAccess.md)来完成这次快速体验。云服务是只读的,不需要安装任何依赖、不需要配置钱包、不需要申请 API Key——你只需要把一段配置复制到 AI 客户端,就能开始提问。 +我们会使用[官方云服务](./OfficialServerAccess.md)来完成这次快速体验。云服务是只读的,不需要安装任何依赖、不需要配置钱包、不需要申请 API Key——你只需要把一段安装提示词粘贴给 AI Agent,就能开始提问。 --- @@ -11,12 +11,12 @@ 在开始之前,确保你已经安装了以下工具: - 所有支持 MCP 的 AI 客户端 -- **Node.js v20.0.0 或更高版本**(用于执行 `npx` 命令)([Node.js 下载](https://nodejs.org/)) +- **Node.js**——用于执行 `npx` 命令([Node.js 下载](https://nodejs.org/))。推荐使用 2026 年 10 月的安全更新版本:22.23.4+(22.x)或 24.22.1+(24.x) 验证 Node.js 版本: ```bash -node --version # 应输出 v20.x.x 或更高 +node --version # 推荐:v22.23.4+ 或 v24.22.1+ ``` --- @@ -60,7 +60,7 @@ AI 给出 ✅ 确认后,TRON MCP Server 就已就位,可以直接开始提 如果一切正常,AI 会自动调用 `get_balance` 工具并返回该地址的 TRX 余额。看到结果,说明你已经成功接入了。 :::info 关于云服务的能力范围 -以上配置连接的是**官方云只读服务**,支持所有查询类操作(查余额、查交易、查合约状态等),但不支持写操作(转账、合约调用等)。如需完整的读写功能,请参阅[本地私有化部署](./LocalPrivatizedDeployment.md)。 +以上安装连接的是**官方云只读服务**,支持所有查询类操作(查余额、查交易、查合约状态等),但不支持写操作(转账、合约调用等)。如需完整的读写功能,请参阅[本地私有化部署](./LocalPrivatizedDeployment.md)。 ::: --- @@ -80,7 +80,7 @@ AI 给出 ✅ 确认后,TRON MCP Server 就已就位,可以直接开始提 | "获取合约 TXyz... 的 ABI" | 读取智能合约接口定义 | | "查询合约 TXyz... 最近触发的事件" | 获取合约事件日志 | -这些只是冰山一角。完整的 97 个工具和 6 个提示词模板,请查阅 [完整能力清单](./ToolList.md)。 +这些只是冰山一角。完整的 97 个工具和 6 个提示词模板(只读云服务提供其中 68 个读取工具和 4 个提示词模板),请查阅 [完整能力清单](./ToolList.md)。 --- diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/ToolList.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/ToolList.md index 9a26450f..8f7ea9c0 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/ToolList.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/McpServer-Skills/MCP/TRONMCPServer/ToolList.md @@ -12,11 +12,11 @@ TRON MCP Server 提供 **97 个工具**、**6 个提示词模板**和 **1 个资 - **读取工具**:只查询链上数据,不影响任何状态。在云服务和本地部署中均可使用。 - **写入工具**:会修改区块链状态(转账、质押、合约调用等)。执行时需要已配置的钱包(通过 [Agent Wallet](../../../Agent-Wallet/Intro.md))。 -写入工具始终会出现在 AI 的可用工具列表中,但会在执行时检查钱包是否已配置。如果没有配置钱包,调用写入工具会返回错误提示你设置钱包。在**只读模式**(云服务或 `--readonly` 标志)下,写入工具不会被注册。 +写入工具始终会出现在 AI 的可用工具列表中,但会在执行时检查钱包是否已配置。如果没有配置钱包,调用写入工具会返回钱包错误(见[常见问题](./FAQ.md#wallet-error-messages))。在**只读模式**(云服务或 `--readonly` 标志)下,29 个写入工具和 2 个写入类提示词模板(`prepare_transfer`、`interact_with_contract`)不会被注册,只剩 68 个读取工具和 4 个提示词模板。 ::: :::tip network 参数 -大多数工具都有一个可选的 `network` 参数,用于指定目标网络(`mainnet`、`nile` 或 `shasta`)。不指定时默认走主网。在测试阶段,建议每次都明确指定 `nile`,避免意外操作主网。 +大多数工具都有一个可选的 `network` 参数,用于指定目标网络(`mainnet`、`nile` 或 `shasta`;`tron` / `trx` 等同于 `mainnet`,`testnet` 等同于 `nile`)。不指定时默认走主网。在测试阶段,建议每次都明确指定 `nile`,避免意外操作主网。 ::: --- @@ -341,6 +341,8 @@ TRON 的链上治理机制——超级代表可以创建和投票表决网络参 工具是单个操作,而提示词模板是**预定义的多步工作流**。当你触发一个提示词时,AI 会按照预设的流程串联多个工具来完成任务——比如转账前先检查余额、预估费用、请你确认,然后才执行。 +"是否需要钱包"为"是"的 2 个提示词模板在只读模式(云服务或 `--readonly`)下不会被注册,只读连接只能看到其余 4 个。 + | 提示词名称 | 描述 | 关键参数 | 是否需要钱包 | | :--- | :--- | :--- | :--- | | `prepare_transfer` | 安全准备和执行代币转账,含余额检查、费用预估和用户确认 | `tokenType`, `recipient`, `amount`, `network`, `tokenAddress` | 是 | @@ -364,4 +366,4 @@ TRON 的链上治理机制——超级代表可以创建和投票表决网络参 | 资源名称 | URI | 描述 | | :--- | :--- | :--- | -| `supported_networks` | `tron://networks` | 返回所有支持的 TRON 网络及其配置信息(RPC 地址、浏览器链接等) | +| `supported_networks` | `tron://networks` | 以 JSON 返回支持的 TRON 网络标识:`{"supportedNetworks": ["mainnet", "nile", "shasta"]}`,不包含 RPC 地址或浏览器链接 | diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/Openclaw-extension/FAQ.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/Openclaw-extension/FAQ.md index 1a4cf6f4..ca2d1c95 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/Openclaw-extension/FAQ.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/Openclaw-extension/FAQ.md @@ -10,7 +10,7 @@ **简单来说**:你的电脑上没装 Node.js,或者版本太老了。 -**怎么解决**:去 [Node.js 官网](https://nodejs.org/) 下载最新的稳定版(LTS,v20 或更高——向导安装的 `@bankofai/mcp-server-tron` 声明了 `node >= 20`),像装普通软件一样一路点"下一步"装好。然后关掉终端里的黑框框,重新运行一次安装口令。 +**怎么解决**:去 [Node.js 官网](https://nodejs.org/) 下载最新的稳定版(LTS——安装器要求 22.x 为 22.23.4+、24.x 为 24.22.1+,或 26.12.1+;推荐选 Node.js 24),像装普通软件一样一路点"下一步"装好。然后关掉终端里的黑框框,重新运行一次安装口令。 ### 报错里写着 "command not found: git" @@ -62,7 +62,7 @@ ### 凭什么别人能转账,我的 AI 只能查数据? -**原因**:你现在的 AI 是极度安全的"只读模式"。因为你在安装时跳过了 AgentWallet 配置,没有给它留钱包钥匙。 +**原因**:转账和交易都需要 AgentWallet 里的钱包来签名,而你的 AI 找不到可用的钱包。安装器并不允许跳过这一步——首次安装时如果 `agent-wallet start` 失败或被取消,整个安装器都会直接退出——所以这通常说明钱包配置没有走完,或者之后 `~/.agent-wallet` 里的钱包数据被重置或删除了。 **怎么解决**:重新跑一次安装脚本,在 AgentWallet 设置那一关跟着提示认真把钱包配好。配好并重启后,转账和交易功能就会被激活。 @@ -83,7 +83,7 @@ **怎么解决**: 1. **治标**:歇几分钟再问。 -2. **治本**:去 [TronGrid](https://www.trongrid.io/) 免费申请一个专属的 API Key。安装时把这个 Key 填进去,AI 就能跑 VIP 高速通道了。 +2. **治本**:去 [TronGrid](https://www.trongrid.io/) 免费申请一个专属的 API Key。安装器不会询问这个 Key——请自己把它设为环境变量 `TRONGRID_API_KEY`(见「[事后怎么补填 API Key](./QuickStart.md#️-事后怎么补填-api-keyvip-通行证)」),重启 OpenClaw 后,AI 就能跑 VIP 高速通道了。 --- @@ -95,7 +95,7 @@ ### 玩腻了,怎么卸载它们? -最简单粗暴的方法:打开电脑的文件夹,找到 `~/.openclaw/skills/`(Mac/Linux)或 `%USERPROFILE%\.openclaw\skills\`(Windows)目录,把你不想用的技能文件夹直接删掉,然后重启 AI 软件,它就彻底消失了。 +最简单粗暴的方法:打开电脑的文件夹,找到 `~/.openclaw/skills/`(Mac/Linux)或 `%USERPROFILE%\.openclaw\skills\`(Windows)目录,把你不想用的技能文件夹直接删掉,然后重启 AI 软件,技能就没了。MCP 服务条目、`~/.mcporter/bankofai-config.json`、全局 npm 包和 `~/.agent-wallet` 仍会保留。安装器的 Clean 模式会清掉 MCP 条目、已装技能、`~/.x402-config.json` 和 `bankofai-config.json`,并重新初始化 agent-wallet(先 `agent-wallet reset`,再 `start --override`);它不会卸载全局 npm 包。 ### 我瞎填了一通装坏了,能重新装吗? @@ -110,11 +110,11 @@ ### 安装需要管理员权限吗? -配置文件不需要——它们都写在当前用户目录下,安装器也不会碰注册表或 Program Files。唯一会写到用户目录之外的是带版本号的全局安装 `npm install -g @bankofai/agent-wallet@<版本>`。在 Windows 上它会装到 `%APPDATA%\npm`,无需提权;在 macOS 或 Linux 上若 Node 是系统级安装,则会写入全局 `node_modules` 目录(例如 `/usr/local/lib/node_modules`),可能要求输入密码。 +配置文件不需要——它们都写在当前用户目录下,安装器也不会碰注册表或 Program Files。会写到用户目录之外的是带版本号的全局 npm 安装:`npm install -g @bankofai/agent-wallet@<版本>`(已装有 2.3.1 时跳过),以及 `npm install --global @bankofai/x402-cli@<版本>`(仅在装了 x402-payment 技能时执行)。在 Windows 上它们会装到 `%APPDATA%\npm`,无需提权;在 macOS 或 Linux 上若 Node 是系统级安装,则会写入全局 `node_modules` 目录(例如 `/usr/local/lib/node_modules`),可能要求输入密码。 ### Windows 和 Mac/Linux 的安装体验一样吗? -一模一样。Windows 安装器 (`install.ps1`) 是 Linux/macOS 版本 (`install.sh`) 的完整移植——相同的安装流程、相同的多选菜单、相同的配置文件结构。唯一的区别是文件路径从 `~/` 变成了 `%USERPROFILE%\`,文件权限从 `chmod 600` 变成了 `icacls` ACL。 +基本一样。Windows 安装器 (`install.ps1`) 是 Linux/macOS 版本 (`install.sh`) 的移植——相同的安装流程、相同的多选菜单、相同的配置文件结构。区别在于:文件路径从 `~/` 变成了 `%USERPROFILE%\`,文件权限从 `chmod 600` 变成了 `icacls` ACL;另外是 OpenClaw 检查——如果你的用户目录下没有 `.openclaw` 文件夹,`install.sh` 会给出警告并询问 `Continue anyway? (y/N)`,而 `install.ps1` 会直接报错退出,需要先装好 OpenClaw 再重新运行。 ### 可以用 WSL (Windows Subsystem for Linux) 安装吗? diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/Openclaw-extension/Intro.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/Openclaw-extension/Intro.md index 1328d586..86686b83 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/Openclaw-extension/Intro.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/Openclaw-extension/Intro.md @@ -51,7 +51,7 @@ OpenClaw Extension 的出现,是为了让你的 Web3 体验从"每步都要亲 - **我是纯小白玩家**:太棒了!不想折腾代码,看图表就头晕,只想用平时聊天的方式让 AI 帮忙查数据、做交易,这就是为你量身定制的。 - **我是 Web3 老手**:懒得天天开网页连钱包,想拥有一个随叫随到的私人交易助理,它能帮你省下大把盯盘和查合约的时间。 -- **我是 Windows 用户**:完全没问题!v1.4.5 起原生支持 Windows 10/11,PowerShell 搞定安装,体验和 Mac/Linux 一模一样。 +- **我是 Windows 用户**:完全没问题!v1.4.5 起原生支持 Windows 10/11,PowerShell 搞定安装,体验和 Mac/Linux 基本一样(少数差异见[常见问题](./FAQ.md))。 --- diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/Openclaw-extension/QuickStart.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/Openclaw-extension/QuickStart.md index f5e55529..a80e1775 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/Openclaw-extension/QuickStart.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/Openclaw-extension/QuickStart.md @@ -2,6 +2,10 @@ 我们的目标是:**花几分钟跟着向导点几下,让你的 AI 成功查到第一笔链上数据。** +:::note 安装器锁定的版本 +一键安装器目前安装的是 **agent-wallet 2.3.1** 和 **Skills v1.5.15**。因此本页的钱包步骤遵循 agent-wallet 2.x(主密码、`local_secure` 钱包),而不是 [Agent-Wallet 文档](../Agent-Wallet/Intro.md)中介绍的 3.x 行为。 +::: + --- ## 🕹️ 准备工作 @@ -9,7 +13,7 @@ 在开始之前,请确保你的电脑上已经装好了以下几种基础软件(如果没有,请像装普通软件一样去官网下载安装): 1. **OpenClaw**:你的 AI 助手软件。 -2. **Node.js**(v20 或以上):安装向导会装 `@bankofai/mcp-server-tron`,它声明了 `node >= 20`。*(极其重要——两个安装器都不强制 20:macOS/Linux 脚本只检查 `node` 是否存在,Windows 脚本也只强制 18。版本过低会通过预检但在后面报错。)* +2. **Node.js**(22.x 需 22.23.4+,24.x 需 24.22.1+,或 26.12.1+):两个安装器都会按 `^22.23.4 || ^24.22.1 || >=26.12.1` 检查完整版本号,未安装或版本过低会在安装任何内容之前直接报错退出。*(推荐 Node.js 24:它能满足安装向导所装的全部组件。)* 3. **Git**:用来下载技能包的小工具。 **Windows 用户额外注意:** @@ -68,7 +72,7 @@ install.bat -🚑 **急救包:敲完回车就报错了?** 如果屏幕提示 `command not found: node`(Mac/Linux)或 `node is not recognized`(Windows),说明你的电脑缺少上面说的基础环境。👉 [点这里看怎么解决](./FAQ.md#报错里写着-command-not-found-node-或-npm-install-失败) +🚑 **急救包:敲完回车就报错了?** 如果屏幕提示 `Error: Node.js ^22.23.4 || ^24.22.1 || >=26.12.1 is required`(后面可能跟着 `found vX.Y.Z`;Windows 上会在 `Installation failed with error:` 下方显示类似的提示,前面没有 `Error: `),说明你的电脑缺少上面说的基础环境。👉 [点这里看怎么解决](./FAQ.md#报错里写着-command-not-found-node-或-npm-install-失败) 如果没有报错,屏幕上会跳出安装向导。请把它当成一个文字小游戏,整个流程分 4 关: @@ -102,7 +106,7 @@ Installation Mode The following data will be permanently deleted: • ALL MCP entries in: ~/.mcporter/mcporter.json • ALL installed skills (global and workspace) - • x402 config file: ~/.x402-config.json + • legacy x402 config file: ~/.x402-config.json • BANK OF AI local config: ~/.mcporter/bankofai-config.json • AgentWallet config will be overwritten by: agent-wallet start --override --save-runtime-secrets @@ -115,9 +119,9 @@ The following data will be permanently deleted: ``` Running cleanup... -◇ Found 10 unique installed skill(s) +◇ Found 14 unique installed skill(s) ◇ Removal process complete -◆ Successfully removed 10 skill(s) +◆ Successfully removed 14 skill(s) ✓ Clean install cleanup completed. @@ -130,7 +134,8 @@ Clean complete — proceeding with fresh setup... Step 0: AgentWallet Setup Launching: agent-wallet reset -This will delete ALL wallet data in: ~/.agent-wallet +This will delete ALL wallet data in: /home//.agent-wallet + 4 file(s): master.json, wallets_config.json, runtime_secrets.json, secret_.json ✔ Are you sure you want to reset? This cannot be undone. Yes ✔ Really delete everything? Last chance! Yes @@ -209,8 +214,12 @@ Active wallet: my_wallet_1 主密码是打开你 AI 钱包的唯一钥匙。**丢了密码 = 丢了钱包的访问权限。** 拿笔写下来、存到密码管理器里——随便什么方式,千万别忘了。 ::: -:::tip 升级安装时看到 "Wallet already initialized."? -如果你之前已经装过 AgentWallet,选普通安装后向导会跳过密码设置,直接让你输入 Wallet ID 并生成钱包。之前的主密码和已有钱包都会保留。 +:::tip 已经有钱包了?(普通安装升级) +如果 AgentWallet 里已经有钱包,而你选了普通安装,向导会先显示 `Already initialized with N wallet(s), active: `,并询问 **What would you like to do?** +- **exit**——什么都不改,安装器直接进入下一关。 +- **add**——先选钱包类型,再用你**原来的**主密码解锁(`Master Password (enter your existing password to unlock)`;如果之前的安装已把密码保存到 `runtime_secrets.json`,这一步会自动跳过)。看到 `Wallet already initialized.` 后,按第 ③–④ 步输入新的 Wallet ID 并生成钱包;新钱包会成为当前活跃钱包。不会设置新密码。 + +无论选哪个,之前的主密码和已有钱包都会保留。 ::: (🚑 报错卡住了?👉 [点这里看 AgentWallet 安装失败怎么解决](./FAQ.md#agentwallet-安装失败了)) @@ -272,12 +281,16 @@ This server still uses PRIVATE_KEY configuration. #### bankofai-recharge(充值助手) -这个全自动,不用输入任何东西!它会自动连接 BANK OF AI 的远程充值服务。 +这个全自动,不用输入任何东西!它注册的是远程服务 `https://recharge.bankofai.io/mcp`(add-mcp 汇总里显示为 `remote` 类型)。 ``` ✓ Configuration saved for bankofai-recharge. ``` +:::caution 充值 MCP 服务已下线 +`https://recharge.bankofai.io/mcp` 已经下线。安装器仍会默认勾选并注册 `bankofai-recharge`,但它的工具已不再响应,你可以在上面的 MCP 选择环节取消勾选。给 BANK OF AI 账户充值,请改用 wallet-cli 的 [`bai recharge`](../wallet-cli/command-reference.md#bai-充值)。 +::: + ### 🟢 第 4 关:挑选技能包(给 AI 装"脑子") 先选安装范围: @@ -294,15 +307,20 @@ Select skills installation scope: 直接按回车(或输入 `1`)选全局安装——这样你所有 OpenClaw 工作区都能用这些技能。 +:::note 如果你选了 `2`(工作区级别) +在下面的技能选择之后,技能工具会再问一次 **Installation scope**(`Project` / `Global`)。选 `Project` 会装到你运行安装器时所在目录下的 `skills/` 文件夹(`<当前目录>/skills/<技能>`);选 `Global` 则仍然装到 `~/.openclaw/skills/`,但安装器之后只比较工作区的技能列表,于是会打印 `No new skills were installed.`、跳过 API Key 提示和 `Next steps`,也不会安装 x402 CLI。想装成全局技能,请在上一步选 `1`。 +::: + 然后技能选择器启动: ``` -◇ Found 10 skills +◇ Found 14 skills │ ◇ Select skills to install (space to toggle) -│ agent-wallet, bankofai-guide, recharge-skill, SunPerp Perpetual Futures Trading, -│ SunPump Meme Token Toolkit, SunSwap DEX Trading, TronScan Data Lookup, -│ USDD / JUST Protocol, wallet-cli, x402-payment +│ agent-wallet, bankofai-guide, Multi-Sig & Account Permissions, recharge-skill, +│ SunPerp Perpetual Futures Trading, SunPump Meme Token Toolkit, SunSwap DEX Trading, +│ TRC20 Token Toolkit, TronScan Data Lookup, TRX Staking & SR Voting, twitter-digest, +│ twitter-mcp, USDD / JUST Protocol, x402-payment ``` 每个技能是干啥的: @@ -311,50 +329,87 @@ Select skills installation scope: | :--- | :--- | | **agent-wallet** | AgentWallet 钱包管理操作(查看钱包、签署交易) | | **bankofai-guide** | 安装完成后引导 AI 帮你完成后续操作的入门助手 | -| **SunSwap DEX Trading** | 在 SunSwap(波场最大的去中心化交易所)上换币 | -| **SunPerp Perpetual Futures** | 在 SunPerp 上做永续合约交易 | +| **Multi-Sig & Account Permissions** | 管理 TRON 多签权限——密钥、阈值与联署提案 | +| **recharge-skill** | 查询和充值 BANK OF AI 余额 | +| **SunPerp Perpetual Futures Trading** | 在 SunPerp 上做永续合约交易 | | **SunPump Meme Token Toolkit** | 在 SunPump 上创建与交易 meme 代币,查询代币信息、排行、持有者与交易历史 | +| **SunSwap DEX Trading** | 在 SunSwap(波场最大的去中心化交易所)上换币 | +| **TRC20 Token Toolkit** | TRC20 转账、授权、余额查询与代币元数据 | | **TronScan Data Lookup** | 通过 TronScan 查链上数据 | +| **TRX Staking & SR Voting** | 质押 TRX、给超级代表投票并领取投票奖励 | +| **twitter-digest** | 生成 X/Twitter 日报(提及、首页时间线、可回复机会) | +| **twitter-mcp** | 安装并授权 X/Twitter 的 `xurl` 命令行工具,或注册托管的 X MCP 桥接 | | **USDD / JUST Protocol** | 管理 USDD 稳定币与 JUST 协议仓位 | -| **wallet-cli** | 通过锁定版 `wallet-cli` npm 包直接完成 TRON 钱包操作(转账、质押、投票、签名) | -| **x402-payment** | x402 协议支付(Agent 间付款) | -| **recharge-skill** | 查询和充值 BANK OF AI 余额 | +| **x402-payment** | 通过 `x402-cli` 命令在 TRON 或 BSC 上为 x402 保护的 HTTP API 付款 | 选完后,安装器会显示安全风险评估: ``` ◇ Security Risk Assessments │ Gen Socket Snyk +│ agent-wallet Safe 1 alert High Risk │ bankofai-guide Safe 0 alerts High Risk +│ Multi-Sig & Account Permissions -- -- -- │ recharge-skill Safe 1 alert Med Risk │ SunPerp Perpetual Futures Trading -- -- -- -│ SunPump Meme Token Toolkit -- -- -- -│ SunSwap DEX Trading -- -- -- -│ TronScan Data Lookup -- -- -- -│ USDD / JUST Protocol -- -- -- -│ wallet-cli -- -- -- +│ ... │ x402-payment Safe 1 alert Med Risk -│ agent-wallet Safe 1 alert High Risk ``` -查看报告后确认继续。安装完成时: +查看报告后,在 `Proceed with installation?` 提示处选 `Yes`。安装完成时: ``` -◇ Installed 10 skills +◇ Proceed with installation? +│ Yes │ -│ ✓ agent-wallet → ~/.openclaw/skills/agent-wallet -│ ✓ bankofai-guide → ~/.openclaw/skills/bankofai-guide -│ ✓ recharge-skill → ~/.openclaw/skills/recharge-skill -│ ✓ SunPerp Perpetual Futures Trading → ~/.openclaw/skills/sunperp-perpetual-futures-trading -│ ✓ SunPump Meme Token Toolkit → ~/.openclaw/skills/sunpump-meme-token-toolkit -│ ✓ SunSwap DEX Trading → ~/.openclaw/skills/sunswap-dex-trading -│ ✓ TronScan Data Lookup → ~/.openclaw/skills/tronscan-data-lookup -│ ✓ USDD / JUST Protocol → ~/.openclaw/skills/usdd-just-protocol -│ ✓ wallet-cli → ~/.openclaw/skills/wallet-cli -│ ✓ x402-payment → ~/.openclaw/skills/x402-payment -``` - -技能装完后,安装器会自动进入配置环节: +◇ Installed 14 skills +│ +│ ✓ agent-wallet (copied) +│ → ~/.openclaw/skills/agent-wallet +│ ✓ bankofai-guide (copied) +│ → ~/.openclaw/skills/bankofai-guide +│ ✓ Multi-Sig & Account Permissions (copied) +│ → ~/.openclaw/skills/multi-sig-account-permissions +│ ✓ recharge-skill (copied) +│ → ~/.openclaw/skills/recharge-skill +│ ✓ SunPerp Perpetual Futures Trading (copied) +│ → ~/.openclaw/skills/sunperp-perpetual-futures-trading +│ ✓ SunPump Meme Token Toolkit (copied) +│ → ~/.openclaw/skills/sunpump-meme-token-toolkit +│ ✓ SunSwap DEX Trading (copied) +│ → ~/.openclaw/skills/sunswap-dex-trading +│ ✓ TRC20 Token Toolkit (copied) +│ → ~/.openclaw/skills/trc20-token-toolkit +│ ✓ TronScan Data Lookup (copied) +│ → ~/.openclaw/skills/tronscan-data-lookup +│ ✓ TRX Staking & SR Voting (copied) +│ → ~/.openclaw/skills/trx-staking-sr-voting +│ ✓ twitter-digest (copied) +│ → ~/.openclaw/skills/twitter-digest +│ ✓ twitter-mcp (copied) +│ → ~/.openclaw/skills/twitter-mcp +│ ✓ USDD / JUST Protocol (copied) +│ → ~/.openclaw/skills/usdd-just-protocol +│ ✓ x402-payment (copied) +│ → ~/.openclaw/skills/x402-payment +``` + +#### x402 CLI(仅在装了 x402-payment 时) + +如果已安装的技能里有 `x402-payment`,安装器接着会全局安装锁定版本的支付命令行工具(如果已装好 `x402-cli` 1.0.1 则跳过): + +``` +Installing @bankofai/x402-cli@1.0.1... +✓ Installed x402 CLI 1.0.1 +``` + +这一步执行的是 `npm install --global @bankofai/x402-cli@1.0.1`,所以它和 AgentWallet 命令行工具一样,会装进全局 npm 目录,而不是 OpenClaw 的文件夹。 + +技能装完后,安装器会比较安装前后的技能列表,对它认为新装的技能逐个进入配置环节: + +:::caution 只在首次安装时出现 +「新装」指本次运行前技能列表里没有的技能。这个列表会扫描 `~/.openclaw/skills/`、共享目录 `~/.agents/skills/`,以及本机其他 Agent 的技能目录,所以只要这些技能已经在其中某个目录里(例如以前装过),安装器就会在 x402 CLI 步骤之后打印 `No new skills were installed.`(CLI 已装过时显示的是 `✓ x402 CLI 1.0.1 is already installed`),跳过下面的提示,最后的汇总也只显示 MCP 配置文件。这种情况下,请按[怎么补填 API Key](#️-事后怎么补填-api-keyvip-通行证)手动创建 API Key 文件,需要的话再自行设置 `TRONSCAN_API_KEY`。 +::: #### recharge-skill API Key 配置 @@ -366,9 +421,13 @@ Recharge requests use the remote BANK OF AI recharge MCP endpoint. ? Enter BANKOFAI_API_KEY (optional, hidden): ``` +:::caution 通过 recharge-skill 充值已不可用 +recharge-skill 充值时调用的远程充值 MCP 服务已经下线,因此通过这个技能发起的充值会失败。需要充值时,请使用 [`wallet-cli bai recharge`](../wallet-cli/command-reference.md#bai-充值)。 +::: + **现在没有?直接按回车跳过。** 以后拿到了 Key 可以手动创建配置文件,详见下方「[事后怎么补填 API Key](#️-事后怎么补填-api-keyvip-通行证)」。 -当屏幕底部亮起 `Installation Complete!` 时——恭喜,通关成功! +当屏幕底部亮起 `Installation Complete!` 时——恭喜,通关成功!下面的 `Installed skills` 列表和 `Next steps` 只有在安装器检测到新技能时才会出现,否则汇总在配置文件那几行之后,直接接上结尾的 `Repository:` / `Skills:` 链接。 ``` ═══════════════════════════════════════ @@ -382,13 +441,17 @@ Recharge requests use the remote BANK OF AI recharge MCP endpoint. ✓ Installed skills: • agent-wallet • bankofai-guide + • Multi-Sig & Account Permissions • recharge-skill • SunPerp Perpetual Futures Trading • SunPump Meme Token Toolkit • SunSwap DEX Trading + • TRC20 Token Toolkit • TronScan Data Lookup + • TRX Staking & SR Voting + • twitter-digest + • twitter-mcp • USDD / JUST Protocol - • wallet-cli • x402-payment Verify with: npx skills list -g @@ -439,7 +502,7 @@ Skills: https://github.com/BofAI/skills | Key 名称 | 它是干嘛的? | 去哪免费领? | | :--- | :--- | :--- | | `TRONGRID_API_KEY` | 波场工具箱的高速通道,不填会被限速 | [trongrid.io](https://www.trongrid.io/) 免费注册获取 | -| `TRONSCAN_API_KEY` | TronScan 查数据技能必须用到 | [tronscan.org](https://tronscan.org/#/myaccount/apiKeys) 免费申请 | +| `TRONSCAN_API_KEY` | TronScan Data Lookup 技能可选——不填时技能会走 BofAI 代理 `ts.bankofai.io`;填自己的 Key 可获得更高的频率限制 | [tronscan.org](https://tronscan.org/#/myaccount/apiKeys) 免费申请 | | `BANKOFAI_API_KEY` | 给 BANK OF AI 充值或查余额用 | [chat.bankofai.io/key](https://chat.bankofai.io/key) 登录后获取 | @@ -490,7 +553,8 @@ Skills: https://github.com/BofAI/skills ```bash -mkdir -p ~/.mcporter && echo '{"api_key": "你的BANKOFAI_API_KEY填在这里", "base_url": "https://chat.bankofai.io/"}' > ~/.mcporter/bankofai-config.json +mkdir -p ~/.mcporter && echo '{"api_key": "你的BANKOFAI_API_KEY填在这里", "base_url": "https://chat.ainft.com"}' > ~/.mcporter/bankofai-config.json +chmod 600 ~/.mcporter/bankofai-config.json # 安装器也会这么做;这个文件里有你的 API Key ``` @@ -498,7 +562,7 @@ mkdir -p ~/.mcporter && echo '{"api_key": "你的BANKOFAI_API_KEY填在这里", ```powershell New-Item -ItemType Directory -Force -Path "$env:USERPROFILE\.mcporter" | Out-Null -'{"api_key": "你的BANKOFAI_API_KEY填在这里", "base_url": "https://chat.bankofai.io/"}' | Out-File -Encoding utf8 "$env:USERPROFILE\.mcporter\bankofai-config.json" +'{"api_key": "你的BANKOFAI_API_KEY填在这里", "base_url": "https://chat.ainft.com"}' | Out-File -Encoding utf8 "$env:USERPROFILE\.mcporter\bankofai-config.json" ``` @@ -518,7 +582,7 @@ New-Item -ItemType Directory -Force -Path "$env:USERPROFILE\.mcporter" | Out-Nul | `~/.mcporter/mcporter.json` | MCP 服务器配置(包括 BNB Chain 私钥,如果你填了的话) | | `~/.mcporter/bankofai-config.json` | BANK OF AI 的 API Key | | `~/.openclaw/skills/` | 全局安装的技能包 | -| `.openclaw/skills/` | 工作区级别的技能包(选了选项 2 才有) | +| `skills/`(位于你运行安装器时所在的目录) | 工作区级别的技能包(选了选项 2 并选 `Project` 才有) | | `~/.agent-wallet/` | AgentWallet 加密钱包数据 | @@ -529,7 +593,7 @@ New-Item -ItemType Directory -Force -Path "$env:USERPROFILE\.mcporter" | Out-Nul | `%USERPROFILE%\.mcporter\mcporter.json` | MCP 服务器配置(包括 BNB Chain 私钥,如果你填了的话) | | `%USERPROFILE%\.mcporter\bankofai-config.json` | BANK OF AI 的 API Key | | `%USERPROFILE%\.openclaw\skills\` | 全局安装的技能包 | -| `.openclaw\skills\` | 工作区级别的技能包(选了选项 2 才有) | +| `skills\`(位于你运行安装器时所在的目录) | 工作区级别的技能包(选了选项 2 并选 `Project` 才有) | | `%USERPROFILE%\.agent-wallet\` | AgentWallet 加密钱包数据 | From e5ae9fff53fd19bd8441ad57bafe70354aedc478 Mon Sep 17 00:00:00 2001 From: jizhen181-dot Date: Wed, 28 Oct 2026 17:02:02 +0800 Subject: [PATCH 05/13] docs(agent-wallet, skills): rewrite Agent Wallet for 3.0.0 and fix Skills setup - Agent Wallet 3.0.0: wallet types, exec-script credentials, canonical CAIP-2 networks, error codes, signAndBroadcast timeouts, wallet_cli TRON payload requirements, config schema. - Skills: install from /tree/main, per-skill credentials, npm install after install and update, sun-cli 1.2.2, Permit2 approval per swap. Co-Authored-By: Claude Opus 5.5 (1M context) --- changelog/agent-wallet.md | 55 ++ changelog/skills.md | 48 ++ docs/Agent-Wallet/Developer/CLI-Reference.md | 382 +++++------- docs/Agent-Wallet/Developer/SDK-Cookbook.md | 330 ++-------- docs/Agent-Wallet/Developer/SDK-Guide.md | 539 ++++------------- docs/Agent-Wallet/FAQ.md | 170 +++--- docs/Agent-Wallet/Intro.md | 105 ++-- docs/Agent-Wallet/QuickStart.md | 221 +++---- docs/McpServer-Skills/SKILLS/BANKOFAISkill.md | 20 +- docs/McpServer-Skills/SKILLS/Faq.md | 10 +- docs/McpServer-Skills/SKILLS/Intro.md | 4 +- docs/McpServer-Skills/SKILLS/QuickStart.md | 17 +- .../current/agent-wallet.md | 57 +- .../current/skills.md | 48 ++ .../Agent-Wallet/Developer/CLI-Reference.md | 413 +++++-------- .../Agent-Wallet/Developer/SDK-Cookbook.md | 331 ++-------- .../Agent-Wallet/Developer/SDK-Guide.md | 565 +++++------------- .../current/Agent-Wallet/FAQ.md | 210 ++++--- .../current/Agent-Wallet/Intro.md | 132 ++-- .../current/Agent-Wallet/QuickStart.md | 237 ++++---- .../McpServer-Skills/SKILLS/BANKOFAISkill.md | 20 +- .../current/McpServer-Skills/SKILLS/Faq.md | 10 +- .../current/McpServer-Skills/SKILLS/Intro.md | 4 +- .../McpServer-Skills/SKILLS/QuickStart.md | 17 +- .../agent-wallet-x402-permit-flow.light.svg | 10 +- .../agent-wallet-x402-permit-flow.svg | 10 +- ...agent-wallet-x402-permit-flow.zh.light.svg | 12 +- .../agent-wallet-x402-permit-flow.zh.svg | 12 +- 28 files changed, 1430 insertions(+), 2559 deletions(-) diff --git a/changelog/agent-wallet.md b/changelog/agent-wallet.md index 111096ee..e97df563 100644 --- a/changelog/agent-wallet.md +++ b/changelog/agent-wallet.md @@ -7,6 +7,61 @@ description: 'Release notes for Agent Wallet.' Release notes for Agent Wallet. +
+
Oct 27, 2026
+
+ +### Error codes, Privy automation and config schema + +
DocsFix
+ +- **SDK Guide** — lists the `code` values of `WalletCliExecutionError` / `WalletCliUsageError` (`capability_missing`, `network_mismatch`, `timeout`, …) and that wallet-cli's own failure codes pass through; a `wallet_cli` chainId mismatch throws `SigningError`; `signAndBroadcast()` returns `{ txId, stage: 'timeout' }` when a broadcast times out or the `wait` deadline passes, and throws `WalletCliSubmittedTransactionError` only when a status query fails after broadcast; the `/advanced` export list is complete. +- **CLI Reference** — `privy` automation needs both `--app-id` and `--app-secret-exec`, otherwise a reuse or secret prompt exits 1; `-g/--generate` is parsed but ignored; the `wallets_config.json` layout is described. + +👉 [SDK Guide](/Agent-Wallet/Developer/SDK-Guide/) · [CLI Reference](/Agent-Wallet/Developer/CLI-Reference/) + +
+
+ +
+
Oct 21, 2026
+
+ +### Docs rewritten for Agent Wallet 3.0 + +
DocsBreaking
+ +- **Rewritten for 3.0.0** — every page now follows `@bankofai/agent-wallet` 3.0.0. The wallet types are `wallet_cli` (recommended), `privy` and `raw_secret`. `local_secure`, the master password, `AGENT_WALLET_PASSWORD`, `runtime_secrets.json`, and the `init`, `change-password` and `sign msg` commands no longer exist. See [Upgrading from 2.x](/Agent-Wallet/FAQ/#upgrade-from-2x). +- **Credentials** — wallet-cli and Privy secrets should come from exec scripts (`--cli-password-exec`, `--app-secret-exec`; a direct `--app-secret` value is also accepted but stored in plaintext); 3.x has no password environment variable. The env fallback reads only `AGENT_WALLET_PRIVATE_KEY` / `AGENT_WALLET_MNEMONIC`; the 2.x aliases such as `TRON_PRIVATE_KEY` are no longer read. +- **Exact network IDs** — `-n` / `network` accept only canonical CAIP-2 strings such as `tron:728126428`, `tron:3448148188` or `eip155:56`. Aliases like `tron:nile` and hex TRON IDs are rejected. +- **Signed transactions** — `signTransaction()` returns a `SignedTransactionArtifact` with a `family` field instead of a string, and the cookbook branches on it. `signMessage` was removed. +- **TypeScript only** — the Python tabs were removed. The PyPI package `bankofai-agent-wallet` stopped at 2.4.0 and follows the 2.x model. +- **Reference fixes** — `reset` removes only `wallets_config.json`; the error list now includes the `ExternalSigner*` and `WalletCli*` classes; the `/advanced` and `/integrations/wallet-cli` entry points and `AGENT_WALLET_WALLET_CLI_PATH` are documented. + +👉 [Quick Start](/Agent-Wallet/QuickStart/) · [CLI Reference](/Agent-Wallet/Developer/CLI-Reference/) · [SDK Guide](/Agent-Wallet/Developer/SDK-Guide/) + +
+
+ +
+
Sep 10, 2026
+
+ +### Agent Wallet v3.0.0 + +
New ReleaseBreaking
+ +- **Wallet types** — new `wallet_cli` type delegates TRON and EVM transaction and typed-data signing to a local wallet-cli account (compatible range `>=4.13.0 <5.0.0`). `local_secure`, the master password, `AGENT_WALLET_PASSWORD` and `runtime_secrets.json` are removed; existing `local_secure` wallets are not converted. +- **Signing API** — `signTransaction()` returns a `SignedTransactionArtifact` with a `family` field (`rawTransaction` for EVM, `transaction` for TRON) instead of a string. `signRaw()`, `signMessage()` and the CLI `sign msg` command are removed; only transaction and typed-data signing remain. +- **Package surface** — low-level adapters, clients and config resolvers move to `@bankofai/agent-wallet/advanced`; wallet-cli helpers are under `@bankofai/agent-wallet/integrations/wallet-cli`. `ConfigWalletProvider` is now `new ConfigWalletProvider(dir, options)`. +- **Credentials and environment** — Privy and wallet-cli secrets accept `{ "exec": "/absolute/script" }` references (`--app-secret-exec`, `--cli-password-exec`). The 2.x aliases `TRON_PRIVATE_KEY`, `TRON_MNEMONIC` and `TRON_ACCOUNT_INDEX` are no longer read; use `AGENT_WALLET_PRIVATE_KEY`, `AGENT_WALLET_MNEMONIC` and `AGENT_WALLET_MNEMONIC_ACCOUNT_INDEX`. +- Published to npm on September 10, 2026. The Python package stays at 2.4.0 on PyPI. Upgrade steps: [Upgrading from 2.x](/Agent-Wallet/FAQ/#upgrade-from-2x). + +👉 [Introduction](/Agent-Wallet/Intro/) · [CLI Reference](/Agent-Wallet/Developer/CLI-Reference/) · [SDK Guide](/Agent-Wallet/Developer/SDK-Guide/) + +
+
+
Sep 9, 2026
diff --git a/changelog/skills.md b/changelog/skills.md index b183061a..48548fb0 100644 --- a/changelog/skills.md +++ b/changelog/skills.md @@ -7,6 +7,54 @@ description: 'Release notes for SKILLS.' Release notes for SKILLS. +
+
Oct 27, 2026
+
+ +### Setup steps and credentials per Skill + +
DocsFix
+ +- **Quick Start** — the two steps `npx skills add` does not do: `npm install -g @sun-protocol/sun-cli@1.2.2` for SunSwap / SunPump, and `npm install` inside the SunPerp, TronScan and USDD Skill folders. `x402`, `bai` and `8004` are wallet-cli command families outside the wallet-cli Skill's scope. +- **Skill catalog** — the credentials column names the environment variables each Skill reads (`TRON_PRIVATE_KEY`, `SUNPERP_ACCESS_KEY` / `SUNPERP_SECRET_KEY`, `TRONSCAN_API_KEY`, …); the SunPump Skill asks for a logo image before a launch; the SunPerp example no longer suggests changing an existing position's stop-loss. + +👉 [Quick Start](/McpServer-Skills/SKILLS/QuickStart/) · [Skill Catalog](/McpServer-Skills/SKILLS/BANKOFAISkill/) + +
+
+ +
+
Oct 22, 2026
+
+ +### Skills 3.0.1 — Node.js security baseline + +
New Release
+ +- **Node.js** — the bundled Node.js Skills and the wallet-cli installer require Node.js `^22.23.4 || ^24.22.1 || >=26.12.1`, the October 2026 security releases. The installer validates the full version, including when the pinned CLI is already installed. +- **wallet-cli pin unchanged** — the `wallet-cli` Skill still pins `@tron-walletcli/wallet-cli@4.14.0`. +- **Docs** — the Skills and BANK OF AI quick starts state the new Node.js requirement. + +👉 [Quick Start](/McpServer-Skills/SKILLS/QuickStart/) + +
+
+ +
+
Oct 21, 2026
+
+ +### Install Skills from the stable main branch + +
DocsFix
+ +- **Install command** — now `npx skills add https://github.com/BofAI/skills/tree/main -g`. Without `/tree/main` the installer uses the repository's default branch, `develop`, whose unreleased `wallet-cli` Skill pins a different CLI version from the `@tron-walletcli/wallet-cli@4.14.0` the docs install. The FAQ's update instructions follow the same rule, and no longer pass `-y`, which made the skills CLI install into every agent detected on the machine (all 79 known agents when none is detected) and overwrite their copies. + +👉 [Quick Start](/McpServer-Skills/SKILLS/QuickStart/) · [FAQ](/McpServer-Skills/SKILLS/Faq/) + +
+
+
Sep 28, 2026
diff --git a/docs/Agent-Wallet/Developer/CLI-Reference.md b/docs/Agent-Wallet/Developer/CLI-Reference.md index 7a419d7b..e18112e2 100644 --- a/docs/Agent-Wallet/Developer/CLI-Reference.md +++ b/docs/Agent-Wallet/Developer/CLI-Reference.md @@ -1,115 +1,137 @@ # CLI Reference -A complete reference for every Agent-wallet command. Whether you're reviewing the basics or configuring automation scripts, you'll find the answer here. +A complete reference for every `agent-wallet` 3.x command. Whether you're reviewing the basics or configuring automation scripts, you'll find the answer here. :::tip Just getting started? -If you haven't created a wallet yet, head to [Quick Start](../QuickStart.md) first — three steps, under a minute. +If you haven't created a wallet yet, head to [Quick Start](../QuickStart.md) first. +::: + +``` +Usage: agent-wallet [options] + +Commands: + start Quick setup: init + configure wallet + add Add a wallet configuration + list List all configured wallets + use [id] Set the active wallet + inspect Show wallet details + resolve-address [id] Resolve wallet addresses + remove [id] Remove a wallet + sign Sign transactions or typed data + reset Delete all wallet data +``` + +Every command accepts `--dir, -d ` (wallet directory, default `~/.agent-wallet`, or `AGENT_WALLET_DIR` when set) and `--help, -h`. Add `-h` after any command or subcommand — for example `agent-wallet start wallet_cli -h` — to see its exact options. + +:::caution Removed in 3.0 +`init`, `change-password`, `sign msg`, the `local_secure` wallet type, and the `-p/--password` and `--save-runtime-secrets` flags no longer exist; `-g/--generate` is still parsed but ignored — 3.x does not generate keys. Agent-wallet 3.x has no master password and does not generate keys. ::: --- ## Basic Commands -The core operations you'll use most often — creating wallets and signing. +### `agent-wallet start` (Create a Wallet and Make It Active) -### `agent-wallet start` (Initialize / Create Wallet) - -**Interactive creation (recommended):** ```bash -agent-wallet start +agent-wallet start # interactive: choose a wallet type +agent-wallet start [options] ``` -The system walks you through choosing a wallet type, generating keys, and setting a master password. Just follow the prompts. -:::danger Avoid the `raw_secret` wallet type for real funds -The interactive wizard may offer a `raw_secret` option. This type stores your private key **unencrypted** on disk — any program with file system access can read it directly. Only use `raw_secret` in fully isolated test environments. For any wallet holding real funds, always choose `local_secure`. -::: +Creates the wallet directory if needed, adds one wallet, and makes it the **active** wallet. If wallets already exist, `start` first asks whether to `add` another or `exit`; pass `--override` to skip that question. -:::tip Privy wallet type -The wizard also offers a `privy` option for Privy-managed server wallets. This type delegates key custody to Privy's infrastructure — no local private key is stored on disk. You'll need a Privy App ID, App Secret, and Wallet ID to configure it: +Naming the wallet type as a subcommand skips the type prompt. For CI or a background service, also pass `-w` and every credential flag — without them the CLI prompts, and prompts fail in a non-interactive environment. If wallets may already exist, pass `--override` too; otherwise the add/exit question can't be asked and `start` exits 1. + +| Option | Applies to | Description | +| :--- | :--- | :--- | +| `-w, --wallet-id ` | all | Wallet ID to create. Prompt defaults: `default_raw`, `default_privy`, `default_cli` | +| `--override` | `start` only | Skip the "already initialized" prompt when wallets already exist | +| `-k, --private-key ` | `raw_secret` | Import a hex private key | +| `-m, --mnemonic ` | `raw_secret` | Import a BIP-39 mnemonic | +| `-mi, --mnemonic-index ` | `raw_secret` | Account index for the mnemonic (default `0`; requires `-m`) | +| `--derive-as ` | `raw_secret` | `eip155` or `tron`; answers the mnemonic derivation prompt (3.0.0 checks the value but does not store it, so it does not change the derived addresses) | +| `--app-id ` | `privy` | Privy app ID | +| `--app-secret ` | `privy` | Privy app secret (plaintext; prefer `--app-secret-exec`) | +| `--app-secret-exec ` | `privy` | Executable that prints the Privy app secret | +| `--privy-wallet-id ` | `privy` | Existing Privy wallet ID | +| `--account